Habr.Features

Всякое-разное для Habr aka habr.com

当前为 2018-06-30 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Habr.Features
  3. // @version 3.1.19
  4. // @description Всякое-разное для Habr aka habr.com
  5. // @author AngReload
  6. // @include https://habr.com/*
  7. // @include http://habr.com/*
  8. // @namespace habr_comments
  9. // @run-at document-start
  10. // @grant none
  11. // @icon https://habr.com/favicon.ico
  12. // ==/UserScript==
  13. /* global localStorage, MutationObserver */
  14.  
  15. // остановка гифок
  16. // клик по гифке заменит картинку на заглушку
  17. // повторный клик вернет гифку на место
  18. const GIF_STOP = true;
  19. // остановить гифки при загрузке страницы
  20. const GIF_STOP_ONLOAD = false;
  21. // цвета заглушки
  22. const GIF_STOP_COLOR_FG = 'White'; // White
  23. const GIF_STOP_COLOR_BG = 'LightGray'; // LightGray or WhiteSmoke
  24. // менять src вместо создания-удаления нод
  25. const GIF_STOP_OVERTYPE = true;
  26.  
  27. // показывать счетчики рейтинга в виде:
  28. // рейтинг = число_голосовавших * (процент_плюсов - процент_минусов)%
  29. const RATING_DETAILS = true;
  30. // клик мышкой по рейтингу меняет вид на простой \ детальный
  31. const RATING_DETAILS_ONCLICK = false;
  32. // рейтинг = число_плюсов - число_минусов (как альтернатива процентам)
  33. const RATING_DETAILS_PN = false;
  34.  
  35. // карма = число_голосовавших * (процент_товарищей - процент_неприятелей)%
  36. const KARMA_DETAILS = true;
  37.  
  38. // показывать метки времени в текущем часовом поясе
  39. // абсолютно, либо относительно текущего времени, либо относительно родительского времени
  40. // меняется по клику, в всплывающей подсказке другие виды времени, автообновляется
  41. const TIME_DETAILS = true;
  42.  
  43. // добавить возможность сортировки комментариев
  44. const COMMENTS_SORT = true;
  45. // сортировать комменты при загрузке страницы или оставить сортировку по времени
  46. const COMMENTS_SORT_ONLOAD = true;
  47. // список доступных сортировок
  48. const sortVariants = [
  49. ['time', 'по времени'],
  50. ['freshness', 'свежести'],
  51. ['trend', 'трендам'], // самая полезная сортировка
  52. ['quality', 'качеству'],
  53. ['rating', 'рейтингу'],
  54. ['popularity', 'популярности'],
  55. ['shuffle', 'перемешать'],
  56. ];
  57.  
  58. // добавить возможность сворачивать комментарии
  59. const COMMENTS_HIDE = true;
  60. // свернуть комментарии если их глубина вложенности равна некому числу
  61. const HIDE_LEVEL = 4;
  62. // сделать «возврат каретки» для комментариев чтобы глубина вложенности не превышала некого числа
  63. const LINE_LEN = 8;
  64. // const LINE_LEN = 16;
  65. // отбивать каждый следущий уровень вложенности дополнительным отступом
  66. const REDUCE_NEW_LINES = true;
  67. // глубина вложенности при «возврате каретки» комментариев обозначается разным цветом
  68. const RAINBOW_NEW_LINE = true;
  69.  
  70. // заменить ссылки ведущие к новым комментариям на дерево комментариев
  71. const COMMENTS_LINKS = true;
  72.  
  73. // запоминание галки «Использовать MarkDown» для комментариев
  74. const COMMENTS_MD = true;
  75.  
  76. // в огнелисе, в отличии о хрома, при загрузке изображений не сохраняется прокрутка
  77. // меня раздражает когда дерево комментариев скачками пытается уехать вниз
  78. // эта опция зафиксирует высоту публикации пока та находится вне обзора
  79. // надо переделать
  80. const FIX_JUMPING_SCROLL = false;
  81.  
  82. // линии вдоль прокрутки для отображения размеров поста и комментариев
  83. const SCROLL_LEGEND = true;
  84.  
  85. // добавляет кнопку активации ночного режима
  86. const NIGHT_MODE = true;
  87.  
  88. // включить разные стили
  89. const USERSTYLE = true;
  90. // показывать гифки только при наведении
  91. const USERSTYLE_GIF_HOVER = false;
  92. // лента постов с увеличенными отступами, нижний бар выровнен вправо
  93. const USERSTYLE_FEED_DISTANCED = true;
  94. // мелкий фикс для отступа в счетчике ленты
  95. const USERSTYLE_COUNTER_NEW_FIX_SPACE = true;
  96. // удаляет правую колонку, там где не жалко
  97. const USERSTYLE_REMOVE_SIDEBAR_RIGHT = true;
  98. // аватарки без скруглений
  99. const USERSTYLE_REMOVE_BORDER_RADIUS_AVATARS = true;
  100. // большие аватарки в профиле и карточках
  101. const USERSTYLE_USERINFO_BIG_AVATARS = true;
  102. // ограничить размер картинок в комментах
  103. const USERSTYLE_COMMENTS_IMG_MAXSIZE = 0;
  104. // нормальные стили для комментариев
  105. const USERSTYLE_COMMENTS_FIX = true;
  106. // нормальные стили для кода
  107. const USERSTYLE_CODE_FIX = true;
  108. // окантовка границ спойлеров
  109. const USERSTYLE_SPOILER_BORDERS = true;
  110. // делает глючные плавающие блоки статичными
  111. const USERSTYLE_STATIC_STICKY = true;
  112. // показывать язык подсветки блоков кода
  113. const USERSTYLE_HLJS_LANG = true;
  114. // показывать язык кода только при наведении
  115. const USERSTYLE_HLJS_LANG_HOVER = false;
  116. // свой шрифт для блоков кода
  117. const USERSTYLE_CODE_FONT = 'PT Mono';
  118. // размер табов в коде
  119. const USERSTYLE_CODE_TABSIZE = 2;
  120. // для ночного режима
  121. const USERSTYLE_CODE_NIGHT = true;
  122.  
  123. // интерфейс для хранения настроек
  124. const userConfig = {
  125. // имя записи в localsorage
  126. key: 'habrafix',
  127. // модель настроек: ключ - возможные значения
  128. model: {
  129. time_publications: ['fromNow', 'absolute'],
  130. time_comments: ['fromParent', 'fromNow', 'absolute'],
  131. comments_order: ['trend', 'time'],
  132. scores_details: [true, false],
  133. comment_markdown: [false, true],
  134. night_mode: [false, true],
  135. },
  136. config: {},
  137. // при старте для конфига берем сохраненные параметры либо по умолчанию
  138. init() {
  139. let jsonString = localStorage.getItem(userConfig.key);
  140. const loadedConfig = jsonString ? JSON.parse(jsonString) : {};
  141. const loadedKeys = Object.keys(loadedConfig);
  142. const config = {};
  143. Object.keys(userConfig.model).forEach((key) => {
  144. const exist = loadedKeys.indexOf(key) >= 0;
  145. config[key] = exist ? loadedConfig[key] : userConfig.model[key][0];
  146. });
  147. jsonString = JSON.stringify(config);
  148. localStorage.setItem(userConfig.key, jsonString);
  149. userConfig.config = config;
  150. },
  151. getItem(key) {
  152. const jsonString = localStorage.getItem(userConfig.key);
  153. const config = JSON.parse(jsonString);
  154. return config[key];
  155. // return userConfig.config[key];
  156. },
  157. setItem(key, value) {
  158. let jsonString = localStorage.getItem(userConfig.key);
  159. const config = JSON.parse(jsonString);
  160. config[key] = value;
  161. jsonString = JSON.stringify(config);
  162. localStorage.setItem(userConfig.key, jsonString);
  163. userConfig.config = config;
  164. },
  165. // каруселит параметр по значения модели
  166. shiftItem(key) {
  167. const currentValue = userConfig.getItem(key);
  168. const availableValues = userConfig.model[key];
  169. const currentIdx = availableValues.indexOf(currentValue);
  170. const nextIdx = (currentIdx + 1) % availableValues.length;
  171. const nextValue = availableValues[nextIdx];
  172. userConfig.setItem(key, nextValue);
  173. return nextValue;
  174. },
  175. };
  176. userConfig.init();
  177.  
  178. // свои стили
  179. const userStyleEl = document.createElement('style');
  180. let userStyle = '';
  181.  
  182. if (USERSTYLE_GIF_HOVER) {
  183. userStyle += `
  184. .post__text img[src$=".gif"]:hover,
  185. .comment__message img[src$=".gif"]:hover {
  186. opacity: 0.75;
  187. }
  188. `;
  189. }
  190.  
  191. if (SCROLL_LEGEND) {
  192. userStyle += `
  193. .legend_el {
  194. position: fixed;
  195. width: 4px;
  196. right: 0;
  197. transition: top 1s ease-out, height 1s ease-out;
  198. z-index: 101;
  199. }
  200.  
  201. #xpanel {
  202. right: 4px;
  203. }
  204. `;
  205. }
  206.  
  207. if (USERSTYLE_FEED_DISTANCED) {
  208. userStyle += `
  209. .post__body_crop {
  210. text-align: right;
  211. }
  212.  
  213. .post__body_crop .post__text {
  214. text-align: left;
  215. }
  216.  
  217. .post__footer {
  218. text-align: right;
  219. }
  220.  
  221. .posts_list .content-list__item_post {
  222. padding: 40px 0;
  223. }
  224. `;
  225. }
  226.  
  227. if (USERSTYLE_COUNTER_NEW_FIX_SPACE) {
  228. userStyle += `
  229. .toggle-menu__item-counter_new {
  230. margin-left: 4px;
  231. }
  232. `;
  233. }
  234.  
  235. if (USERSTYLE_REMOVE_SIDEBAR_RIGHT) {
  236. // remove for
  237. // https://habr.com/post/352896/
  238. // https://habr.com/sandbox/
  239. // https://habr.com/sandbox/115216/
  240. // https://habr.com/users/saggid/posts/
  241. // https://habr.com/users/saggid/comments/
  242. // https://habr.com/users/saggid/favorites/
  243. // https://habr.com/users/saggid/favorites/posts/
  244. // https://habr.com/users/saggid/favorites/comments/
  245. // https://habr.com/company/pvs-studio/blog/353640/
  246. // https://habr.com/company/pvs-studio/blog/
  247. // https://habr.com/company/pvs-studio/blog/top/
  248. // https://habr.com/company/pvs-studio/
  249. // https://habr.com/feed/
  250. // https://habr.com/top/
  251. // https://habr.com/top/yearly/
  252. // https://habr.com/all/
  253. // https://habr.com/all/top10/
  254.  
  255. // display for
  256. // https://habr.com/company/pvs-studio/profile/
  257. // https://habr.com/company/pvs-studio/vacancies/
  258. // https://habr.com/company/pvs-studio/fans/all/rating/
  259. // https://habr.com/company/pvs-studio/workers/new/rating/
  260. // https://habr.com/feed/settings/
  261. // https://habr.com/users/
  262. // https://habr.com/hubs/
  263. // https://habr.com/hubs/admin/
  264. // https://habr.com/companies/
  265. // https://habr.com/companies/category/software/
  266. // https://habr.com/companies/new/
  267. // https://habr.com/flows/design/
  268.  
  269. const path = window.location.pathname;
  270. const isPost = /^\/post\/\d+\/$/.test(path);
  271. const isSandbox = /^\/sandbox\//.test(path);
  272. const isUserPosts = /^\/users\/[^/]+\/posts\//.test(path);
  273. const isUserComments = /^\/users\/[^/]+\/comments\//.test(path);
  274. const isUserFavorites = /^\/users\/[^/]+\/favorites\//.test(path);
  275. const isCompanyBlog = /^\/company\/[^/]+\/blog\//.test(path);
  276. const isCompanyBlog2 = /^\/company\/[^/]+\/(page\d+\/)?$/.test(path);
  277. const isFeed = /^\/feed\//.test(path);
  278. const isHome = /^\/$/.test(path);
  279. const isTop = /^\/top\//.test(path);
  280. const isAll = /^\/all\//.test(path);
  281.  
  282. if (
  283. isPost || isSandbox ||
  284. isUserPosts || isUserComments || isUserFavorites ||
  285. isCompanyBlog || isCompanyBlog2 ||
  286. isFeed || isHome || isTop || isAll
  287. ) {
  288. userStyle += `
  289. .sidebar_right {
  290. display: none;
  291. }
  292.  
  293. .content_left {
  294. padding-right: 0;
  295. }
  296.  
  297. .comment_plain {
  298. max-width: 860px;
  299. }
  300. `;
  301. }
  302. }
  303.  
  304. if (USERSTYLE_REMOVE_BORDER_RADIUS_AVATARS) {
  305. userStyle += `
  306. .user-info__image-pic,
  307. .user-pic_popover,
  308. .media-obj__image-pic {
  309. border-radius: 0;
  310. }
  311. `;
  312. }
  313.  
  314. if (USERSTYLE_USERINFO_BIG_AVATARS) {
  315. userStyle += `
  316. .page-header {
  317. height: auto;
  318. }
  319.  
  320. .media-obj__image-pic_hub,
  321. .media-obj__image-pic_user,
  322. .media-obj__image-pic_company {
  323. width: auto;
  324. height: auto;
  325. }
  326. `;
  327. }
  328.  
  329. if (USERSTYLE_COMMENTS_FIX) {
  330. userStyle += `
  331. .comments_order {
  332. color: #333;
  333. font-size: 14px;
  334. font-family: "-apple-system",BlinkMacSystemFont,Arial,sans-serif;
  335. text-rendering: optimizeLegibility;
  336. border-bottom: 1px solid #e3e3e3;
  337. padding: 8px;
  338. text-align: right;
  339. }
  340.  
  341. .comments_order a {
  342. color: #548eaa;
  343. font-style: normal;
  344. text-decoration: none;
  345. }
  346.  
  347. .comments_order a:hover {
  348. color: #487284;
  349. }
  350.  
  351. .content-list_comments {
  352. overflow: visible;
  353. }
  354.  
  355. .comment__folding-dotholder {
  356. display: none !important;
  357. }
  358.  
  359. .content-list_nested-comments {
  360. border-left: 1px solid #e3e3e3;
  361. margin: 0;
  362. padding-top: 20px;
  363. padding-left: 20px !important;
  364. }
  365.  
  366. .content-list_comments {
  367. /*border-left: 1px solid silver;*/
  368. margin: 0;
  369. padding-left: 0;
  370. padding-top: 20px;
  371. /*background: #FCE4EC;*/
  372. }
  373.  
  374. #comments-list .js-form_placeholder {
  375. border-left: 1px solid #e3e3e3;
  376. padding-left: 20px;
  377. }
  378.  
  379. .comments_new-line {
  380. border-left: 1px solid #777;
  381. border-bottom: 1px solid #777;
  382. border-top: 1px solid #777;
  383. margin-left: -${LINE_LEN * 21}px !important;
  384. background: white;
  385. padding-bottom: 4px;
  386. }
  387.  
  388. /* .comment__head_topic-author.comment__head_new-comment */
  389. .comment__head_topic-author .user-info {
  390. text-decoration: underline;
  391. }
  392. `;
  393. }
  394.  
  395. if (RAINBOW_NEW_LINE) {
  396. userStyle += `
  397. .comments_new-line-1 {
  398. border-color: #0caefb;
  399. }
  400.  
  401. .comments_new-line-2 {
  402. border-color: #06feb7;
  403. }
  404.  
  405. .comments_new-line-3 {
  406. border-color: #fbcb02;
  407. }
  408.  
  409. .comments_new-line-0 {
  410. border-color: #fb0543;
  411. }
  412. `;
  413. }
  414.  
  415. if (REDUCE_NEW_LINES) {
  416. userStyle += `
  417. .comments_new-line .comments_new-line {
  418. margin-left: -${(LINE_LEN - 1) * 21}px !important;
  419. }
  420. `;
  421. }
  422.  
  423. if (USERSTYLE_COMMENTS_IMG_MAXSIZE) {
  424. userStyle += `
  425. .comment__message img {
  426. max-height: ${USERSTYLE_COMMENTS_IMG_MAXSIZE}px;
  427. }
  428.  
  429. .comment__message .spoiler .img {
  430. max-height: auto;
  431. }
  432. `;
  433. }
  434.  
  435. if (USERSTYLE_CODE_FIX) {
  436. let addFont = '';
  437. if (USERSTYLE_CODE_FONT) {
  438. addFont = USERSTYLE_CODE_FONT;
  439. if (addFont.indexOf(' ') >= 0) {
  440. addFont = `"${addFont}"`;
  441. }
  442. addFont += ',';
  443. }
  444.  
  445. const tabSize = USERSTYLE_CODE_TABSIZE || 4;
  446.  
  447. userStyle += `
  448. .editor .text-holder textarea,
  449. .tm-editor__textarea {
  450. font-family: ${addFont} 'Ubuntu Mono', Menlo, Monaco, Consolas, 'Lucida Console', 'Courier New', monospace;
  451. }
  452.  
  453. code {
  454. font-family: ${addFont} 'Ubuntu Mono', Menlo, Monaco, Consolas, 'Lucida Console', 'Courier New', monospace !important;;
  455. -o-tab-size: ${tabSize};
  456. -moz-tab-size: ${tabSize};
  457. tab-size: ${tabSize};
  458. background: #f7f7f7;
  459. border-radius: 3px;
  460. color: #505c66;
  461. display: inline-block;
  462. font-weight: 500;
  463. line-height: 1.29;
  464. padding: 5px 9px;
  465. vertical-align: 1px;
  466. }
  467. `;
  468. }
  469.  
  470. if (USERSTYLE_SPOILER_BORDERS) {
  471. userStyle += `
  472. .spoiler .spoiler_text {
  473. border: 1px dashed rgb(12, 174, 251);
  474. }
  475. `;
  476. }
  477.  
  478. if (USERSTYLE_STATIC_STICKY) {
  479. userStyle += `
  480. .wrapper-sticky,
  481. .js-ad_sticky,
  482. .js-ad_sticky_comments {
  483. position: static !important;
  484. }
  485. `;
  486. }
  487.  
  488. if (USERSTYLE_HLJS_LANG) {
  489. let hover = '';
  490. if (USERSTYLE_HLJS_LANG_HOVER) hover = ':hover';
  491. userStyle += `
  492. pre {
  493. position: relative;
  494. }
  495.  
  496. .hljs${hover}::after {
  497. position: absolute;
  498. font-size: 12px;
  499. content: 'code';
  500. right: 0;
  501. top: 0;
  502. padding: 1px 5px 0 4px;
  503. /*border-bottom: 1px solid #e5e8ec;
  504. border-left: 1px solid #e5e8ec;
  505. border-bottom-left-radius: 3px;
  506. color: #505c66;*/
  507. opacity: .5;
  508. }
  509. `;
  510. userStyle += [
  511. ['1c', '1C:Enterprise (v7, v8)'],
  512. ['abnf', 'Augmented Backus-Naur Form'],
  513. ['accesslog', 'Access log'],
  514. ['actionscript', 'ActionScript'],
  515. ['ada', 'Ada'],
  516. ['apache', 'Apache'],
  517. ['applescript', 'AppleScript'],
  518. ['arduino', 'Arduino'],
  519. ['armasm', 'ARM Assembly'],
  520. ['asciidoc', 'AsciiDoc'],
  521. ['aspectj', 'AspectJ'],
  522. ['autohotkey', 'AutoHotkey'],
  523. ['autoit', 'AutoIt'],
  524. ['avrasm', 'AVR Assembler'],
  525. ['awk', 'Awk'],
  526. ['axapta', 'Axapta'],
  527. ['bash', 'Bash'],
  528. ['basic', 'Basic'],
  529. ['bnf', 'Backus–Naur Form'],
  530. ['brainfuck', 'Brainfuck'],
  531. ['cal', 'C/AL'],
  532. ['capnproto', 'Cap’n Proto'],
  533. ['ceylon', 'Ceylon'],
  534. ['clean', 'Clean'],
  535. ['clojure-repl', 'Clojure REPL'],
  536. ['clojure', 'Clojure'],
  537. ['cmake', 'CMake'],
  538. ['coffeescript', 'CoffeeScript'],
  539. ['coq', 'Coq'],
  540. ['cos', 'Caché Object Script'],
  541. ['cpp', 'C++'],
  542. ['crmsh', 'crmsh'],
  543. ['crystal', 'Crystal'],
  544. ['cs', 'C#'],
  545. ['csp', 'CSP'],
  546. ['css', 'CSS'],
  547. ['d', 'D'],
  548. ['dart', 'Dart'],
  549. ['delphi', 'Delphi'],
  550. ['diff', 'Diff'],
  551. ['django', 'Django'],
  552. ['dns', 'DNS Zone file'],
  553. ['dockerfile', 'Dockerfile'],
  554. ['dos', 'DOS .bat'],
  555. ['dsconfig', 'dsconfig'],
  556. ['dts', 'Device Tree'],
  557. ['dust', 'Dust'],
  558. ['ebnf', 'Extended Backus-Naur Form'],
  559. ['elixir', 'Elixir'],
  560. ['elm', 'Elm'],
  561. ['erb', 'ERB (Embedded Ruby)'],
  562. ['erlang-repl', 'Erlang REPL'],
  563. ['erlang', 'Erlang'],
  564. ['excel', 'Excel'],
  565. ['fix', 'FIX'],
  566. ['flix', 'Flix'],
  567. ['fortran', 'Fortran'],
  568. ['fsharp', 'F#'],
  569. ['gams', 'GAMS'],
  570. ['gauss', 'GAUSS'],
  571. ['gcode', 'G-code (ISO 6983)'],
  572. ['gherkin', 'Gherkin'],
  573. ['glsl', 'GLSL'],
  574. ['go', 'Go'],
  575. ['golo', 'Golo'],
  576. ['gradle', 'Gradle'],
  577. ['groovy', 'Groovy'],
  578. ['haml', 'Haml'],
  579. ['handlebars', 'Handlebars'],
  580. ['haskell', 'Haskell'],
  581. ['haxe', 'Haxe'],
  582. ['hsp', 'HSP'],
  583. ['htmlbars', 'HTMLBars'],
  584. ['http', 'HTTP'],
  585. ['hy', 'Hy'],
  586. ['inform7', 'Inform 7'],
  587. ['ini', 'Ini'],
  588. ['irpf90', 'IRPF90'],
  589. ['java', 'Java'],
  590. ['javascript', 'JavaScript'],
  591. ['jboss-cli', 'jboss-cli'],
  592. ['json', 'JSON'],
  593. ['julia-repl', 'Julia REPL'],
  594. ['julia', 'Julia'],
  595. ['kotlin', 'Kotlin'],
  596. ['lasso', 'Lasso'],
  597. ['ldif', 'LDIF'],
  598. ['leaf', 'Leaf'],
  599. ['less', 'Less'],
  600. ['lisp', 'Lisp'],
  601. ['livecodeserver', 'LiveCode'],
  602. ['livescript', 'LiveScript'],
  603. ['llvm', 'LLVM IR'],
  604. ['lsl', 'Linden Scripting Language'],
  605. ['lua', 'Lua'],
  606. ['makefile', 'Makefile'],
  607. ['markdown', 'Markdown'],
  608. ['mathematica', 'Mathematica'],
  609. ['matlab', 'Matlab'],
  610. ['maxima', 'Maxima'],
  611. ['mel', 'MEL'],
  612. ['mercury', 'Mercury'],
  613. ['mipsasm', 'MIPS Assembly'],
  614. ['mizar', 'Mizar'],
  615. ['mojolicious', 'Mojolicious'],
  616. ['monkey', 'Monkey'],
  617. ['moonscript', 'MoonScript'],
  618. ['n1ql', 'N1QL'],
  619. ['nginx', 'Nginx'],
  620. ['nimrod', 'Nimrod'],
  621. ['nix', 'Nix'],
  622. ['nsis', 'NSIS'],
  623. ['objectivec', 'Objective-C'],
  624. ['ocaml', 'OCaml'],
  625. ['openscad', 'OpenSCAD'],
  626. ['oxygene', 'Oxygene'],
  627. ['parser3', 'Parser3'],
  628. ['perl', 'Perl'],
  629. ['pf', 'pf'],
  630. ['php', 'PHP'],
  631. ['pony', 'Pony'],
  632. ['powershell', 'PowerShell'],
  633. ['processing', 'Processing'],
  634. ['profile', 'Python profile'],
  635. ['prolog', 'Prolog'],
  636. ['protobuf', 'Protocol Buffers'],
  637. ['puppet', 'Puppet'],
  638. ['purebasic', 'PureBASIC'],
  639. ['python', 'Python'],
  640. ['q', 'Q'],
  641. ['qml', 'QML'],
  642. ['r', 'R'],
  643. ['rib', 'RenderMan RIB'],
  644. ['roboconf', 'Roboconf'],
  645. ['routeros', 'Microtik RouterOS script'],
  646. ['rsl', 'RenderMan RSL'],
  647. ['ruby', 'Ruby'],
  648. ['ruleslanguage', 'Oracle Rules Language'],
  649. ['rust', 'Rust'],
  650. ['scala', 'Scala'],
  651. ['scheme', 'Scheme'],
  652. ['scilab', 'Scilab'],
  653. ['scss', 'SCSS'],
  654. ['shell', 'Shell Session'],
  655. ['smali', 'Smali'],
  656. ['smalltalk', 'Smalltalk'],
  657. ['sml', 'SML'],
  658. ['sqf', 'SQF'],
  659. ['sql', 'SQL'],
  660. ['stan', 'Stan'],
  661. ['stata', 'Stata'],
  662. ['step21', 'STEP Part 21'],
  663. ['stylus', 'Stylus'],
  664. ['subunit', 'SubUnit'],
  665. ['swift', 'Swift'],
  666. ['taggerscript', 'Tagger Script'],
  667. ['tap', 'Test Anything Protocol'],
  668. ['tcl', 'Tcl'],
  669. ['tex', 'TeX'],
  670. ['thrift', 'Thrift'],
  671. ['tp', 'TP'],
  672. ['twig', 'Twig'],
  673. ['typescript', 'TypeScript'],
  674. ['vala', 'Vala'],
  675. ['vbnet', 'VB.NET'],
  676. ['vbscript-html', 'VBScript in HTML'],
  677. ['vbscript', 'VBScript'],
  678. ['verilog', 'Verilog'],
  679. ['vhdl', 'VHDL'],
  680. ['vim', 'Vim Script'],
  681. ['x86asm', 'Intel x86 Assembly'],
  682. ['xl', 'XL'],
  683. ['xml', 'HTML, XML'],
  684. ['xquery', 'XQuery'],
  685. ['yaml', 'YAML'],
  686. ['zephir', 'Zephir'],
  687. ].map(([langTag, langName]) => `.hljs.${langTag}${hover}::after{content:'${langName} [${langTag}]'}`).join('');
  688. }
  689.  
  690. if (USERSTYLE_CODE_NIGHT) {
  691. userStyle += `
  692. .night_mode_switcher {
  693. box-sizing: border-box;
  694. position: fixed;
  695. width: 32px;
  696. height: 32px;
  697. right: 32px;
  698. bottom: 32px;
  699. z-index: 101;
  700. background-color: transparent;
  701. border-radius: 50%;
  702. border: 4px solid #aaa;
  703. border-right-width: 16px;
  704. transition: border-color 0.1s ease-out;
  705. }
  706.  
  707. .night_mode_switcher:hover {
  708. border-color: #333;
  709. }
  710.  
  711. .night .night_mode_switcher {
  712. border-color: #515151;
  713. }
  714.  
  715. .night .night_mode_switcher:hover {
  716. border-color: #9e9e9e;
  717. }
  718.  
  719.  
  720. /* bg */
  721. .night .sidebar-block__suggest,
  722. .night .dropdown-container,
  723. .night .poll-result__bar,
  724. .night .comments_new-line,
  725. .night .tm-editor__textarea,
  726. .night .layout,
  727. .night .toggle-menu__most-read,
  728. .night .toggle-menu_most-comments {
  729. background: #171c20;
  730. }
  731.  
  732. /* text */
  733. .night .sidebar-block__suggest,
  734. .night .user-message__body,
  735. .night .promo-block__title_total,
  736. .night .beta-anounce__text,
  737. .night .defination-list__label,
  738. .night .defination-list__value,
  739. .night .search-field__select,
  740. .night .search-field__input[type="text"],
  741. .night .search-form__field,
  742. .night .post-info__title,
  743. .night .dropdown__user-stats,
  744. .night .dropdown-container_white .user-info__special,
  745. .night .n-dropdown-menu__item-link,
  746. .night body,
  747. .night .default-block__polling-title,
  748. .night .poll-result__data-label,
  749. .night code,
  750. .night .user-info__fullname,
  751. .night .user-info__specialization,
  752. .night .page-header__info-title,
  753. .night .page-header__info-desc,
  754. .night .post__title-text,
  755. .night .post__title_link,
  756. .night .checkbox__label,
  757. .night .radio__label,
  758. .night .tm-editor__textarea,
  759. .night .footer-block__title,
  760. .night #TMpanel .container .bmenu > a.current,
  761. .night .post__text-html,
  762. .night .comment__message,
  763. .night .comment-form__preview {
  764. color: #9e9e9e;
  765. }
  766.  
  767. .night .n-dropdown-menu__item-link:hover {
  768. color: white;
  769. }
  770.  
  771. /* top lvl bg */
  772. .night .checkbox__label::before,
  773. .night .radio__label::before,
  774. .night .content-list__item_conversation:hover,
  775. .night .search-field__select,
  776. .night .search-field__input[type="text"],
  777. .night .search-form__field,
  778. .night .dropdown-container,
  779. .night .n-dropdown-menu,
  780. .night .post__translatation,
  781. .night code,
  782. .night .megapost-teasers,
  783. .night .tm-editor_comments,
  784. .night .promo-block__header,
  785. .night .post__text-html blockquote,
  786. .night .default-block,
  787. .night .post-share,
  788. .night .company-info__author,
  789. .night .layout__row_footer-links {
  790. background: #22272B;
  791. }
  792.  
  793. /* not important bg */
  794. .night .btn_blue.disabled,
  795. .night .btn_blue[disabled],
  796. .night .tracker_page table.tracker_folowers tr.new,
  797. .night .dropdown__user-stats,
  798. .night .comment__head_topic-author,
  799. .night .promo-item:hover,
  800. .night .layout__row_navbar,
  801. .night .layout__row_footer,
  802. .night #TMpanel {
  803. background: #1f2327;
  804. }
  805.  
  806. /* borders */
  807. .night #comments-list .js-form_placeholder,
  808. .night .sidebar-block__suggest,
  809. .night .content-list_preview-message,
  810. .night .btn_outline_blue[disabled],
  811. .night .user-message__body_html pre code,
  812. .night .content-list_user-dialog,
  813. .night .wysiwyg-toolbar,
  814. .night .content-list__item_bordered,
  815. .night .promo-block__total,
  816. .night .search-field__select,
  817. .night .search-field__input[type="text"],
  818. .night .search-form__field,
  819. .night .tracker_page table.tracker_folowers tr td,
  820. .night .tracker_page table.tracker_folowers tr th,
  821. .night .stacked-menu__item_devided,
  822. .night .post__text-html table,
  823. .night .post__text-html table td,
  824. .night .post__text-html table th,
  825. .night .n-dropdown-menu__item_border,
  826. .night .dropdown-container,
  827. .night .default-block_bordered,
  828. .night .default_block_polling,
  829. .night .column-wrapper_tabs .sidebar_right,
  830. .night .post__type-label,
  831. .night .promo-block__header,
  832. .night .user-info__contacts,
  833. .night .comment__message pre code,
  834. .night .comment-form__preview pre code,
  835. .night .sandbox-panel,
  836. .night .comment__post-title,
  837. .night .tm-editor__textarea,
  838. .night .promo-block__footer,
  839. .night .author-panel,
  840. .night .promo-block,
  841. .night .post__text-html pre code,
  842. .night .footer-block__title,
  843. .night #TMpanel,
  844. .night .layout__row_navbar,
  845. .night .page-header_bordered,
  846. .night .post-stats,
  847. .night .company-info__about,
  848. .night .company-info_post-additional,
  849. .night .company-info__contacts,
  850. .night .post-share,
  851. .night .content-list__item_devided,
  852. .night .comments_order,
  853. .night .comments-section__head,
  854. .night .content-list_nested-comments,
  855. .night .default-block__header,
  856. .night .column-wrapper_bordered,
  857. .night .tabs-menu,
  858. .night .toggle-menu {
  859. border-color: #393d41;
  860. }
  861.  
  862. .night .poll-result__progress {
  863. background-color: #515151;
  864. }
  865.  
  866. .night .poll-result__progress_winner {
  867. background-color: #5e8eac;
  868. }
  869.  
  870. .night .layout__elevator {
  871. color: #515151;
  872. }
  873.  
  874. .night .layout__elevator:hover {
  875. background-color: #22272B;
  876. }
  877.  
  878. .night .comment__head_topic-author {
  879. background: rgba(145, 120, 21, 0.1);
  880. }
  881.  
  882. .night .comment__head_my-comment {
  883. background: rgba(86, 120, 66, 0.1);
  884. }
  885.  
  886. .night .comment__head_new-comment {
  887. background: rgba(71, 93, 253, 0.1)
  888. }
  889.  
  890. .night .icon-svg_logo-habrahabr {
  891. color: inherit;
  892. }
  893.  
  894. /* img filter */
  895. .night .comment__message img,
  896. .night .comment-form__preview img,
  897. .night .default-block__content #facebook_like_box,
  898. .night .default-block__content #vk_groups,
  899. .night .post img,
  900. .night .page-header__banner img,
  901. .night .company_top_banner img,
  902. .night img .teaser__image,
  903. .night .teaser__image-pic,
  904. .night .article__body img {
  905. filter: brightness(0.5);
  906. transition: all .6s ease-out;
  907. }
  908.  
  909. .night .comment__message img:hover,
  910. .night .comment-form__preview img:hover,
  911. .night .default-block__content #facebook_like_box:hover,
  912. .night .default-block__content #vk_groups:hover,
  913. .night img[alt="en"],
  914. .night img[alt="habr"],
  915. .night img:hover,
  916. .night a.post-author__link img,
  917. .night img.user-info__image-pic,
  918. .night .teaser__image-pic:hover,
  919. .night .teaser__image:hover {
  920. filter: brightness(1.0);
  921. }
  922.  
  923. /* Atelier Cave Dark */
  924. .night .hljs-comment,
  925. .night .hljs-quote {
  926. color:#7e7887 !important
  927. }
  928. .night .hljs-variable,
  929. .night .hljs-template-variable,
  930. .night .hljs-attribute,
  931. .night .hljs-regexp,
  932. .night .hljs-link,
  933. .night .hljs-tag,
  934. .night .hljs-name,
  935. .night .hljs-selector-id,
  936. .night .hljs-selector-class {
  937. color:#be4678 !important
  938. }
  939. .night .hljs-number,
  940. .night .hljs-meta,
  941. .night .hljs-built_in,
  942. .night .hljs-builtin-name,
  943. .night .hljs-literal,
  944. .night .hljs-type,
  945. .night .hljs-params {
  946. color:#aa573c !important
  947. }
  948. .night .hljs-string,
  949. .night .hljs-symbol,
  950. .night .hljs-bullet {
  951. color:#2a9292 !important
  952. }
  953. .night .hljs-title,
  954. .night .hljs-section {
  955. color:#576ddb !important
  956. }
  957. .night .hljs-keyword,
  958. .night .hljs-selector-tag {
  959. color:#955ae7 !important
  960. }
  961. .night .hljs-deletion,
  962. .night .hljs-addition {
  963. color:#19171c !important;
  964. display:inline-block !important;
  965. width:100% !important
  966. }
  967. .night .hljs-deletion {
  968. background-color:#be4678 !important
  969. }
  970. .night .hljs-addition {
  971. background-color:#2a9292 !important
  972. }
  973. .night .hljs {
  974. display:block !important;
  975. overflow-x:auto !important;
  976. background:#19171c !important;
  977. color:#8b8792 !important;
  978. /*padding:0.5em !important*/
  979. }
  980. .night .hljs-emphasis {
  981. font-style:italic !important
  982. }
  983. .night .hljs-strong {
  984. font-weight:bold !important
  985. }
  986. `;
  987. }
  988.  
  989. userStyleEl.innerHTML = userStyle;
  990.  
  991. function readyHead(fn) {
  992. if (document.body) { // если есть body, значит head готов
  993. fn();
  994. } else if (document.documentElement) {
  995. const observer = new MutationObserver(() => {
  996. if (document.body) {
  997. observer.disconnect();
  998. fn();
  999. }
  1000. });
  1001. observer.observe(document.documentElement, { childList: true });
  1002. } else {
  1003. // рекурсивное ожидание появления DOM
  1004. setTimeout(() => readyHead(fn), 10);
  1005. }
  1006. }
  1007.  
  1008. readyHead(() => {
  1009. if (USERSTYLE) document.head.appendChild(userStyleEl);
  1010. if (NIGHT_MODE && userConfig.getItem('night_mode')) {
  1011. document.documentElement.classList.add('night');
  1012. }
  1013. });
  1014.  
  1015. function ready(fn) {
  1016. const { readyState } = document;
  1017. if (readyState === 'loading') {
  1018. document.addEventListener('DOMContentLoaded', () => {
  1019. fn();
  1020. });
  1021. } else {
  1022. fn();
  1023. }
  1024. }
  1025.  
  1026. ready(() => {
  1027. if (COMMENTS_MD) {
  1028. const mdSelectorEl = document.getElementById('comment_markdown');
  1029. if (mdSelectorEl) {
  1030. if (userConfig.getItem('comment_markdown')) mdSelectorEl.checked = true;
  1031. mdSelectorEl.addEventListener('input', () => {
  1032. userConfig.setItem('comment_markdown', mdSelectorEl.checked);
  1033. });
  1034. }
  1035. }
  1036.  
  1037. // надо ли ещё
  1038. [...document.querySelectorAll('iframe[src^="https://codepen.io/"]')]
  1039. .map(el => el.setAttribute('scrolling', 'no'));
  1040.  
  1041. // остановка гифок по клику и воспроизведение при повторном клике
  1042. function toggleGIF(el) {
  1043. // если атрибут со старым линком пуст или отсутствует
  1044. if (!el.dataset.oldSrc) {
  1045. // заменим ссылку на data-url-svg с треугольником в круге
  1046. const w = Math.max(el.clientWidth || 256, 16);
  1047. const h = Math.max(el.clientHeight || 128, 16);
  1048. const cx = w / 2;
  1049. const cy = h / 2;
  1050. const r = Math.min(w, h) / 4;
  1051. const ax = (r * 61) / 128;
  1052. const by = (r * 56) / 128;
  1053. const bx = (r * 35) / 128;
  1054. const svg = `data:image/svg+xml;utf8,
  1055. <svg width='${w}' height='${h}' baseProfile='full' xmlns='http://www.w3.org/2000/svg'>
  1056. <rect x='0' y='0' width='${w}' height='${h}' fill='${GIF_STOP_COLOR_BG}'/>
  1057. <circle cx='${cx}' cy='${cy}' r='${r}' fill='${GIF_STOP_COLOR_FG}'/>
  1058. <polygon points='${cx + ax} ${cy} ${cx - bx} ${cy - by} ${cx - bx} ${cy + by}' fill='${GIF_STOP_COLOR_BG}' />
  1059. </svg>
  1060. `;
  1061. el.dataset.oldSrc = el.getAttribute('src'); // eslint-disable-line no-param-reassign
  1062. el.setAttribute('src', svg);
  1063. } else if (GIF_STOP_OVERTYPE) {
  1064. // иначе поставим svg с троеточием
  1065. const w = el.clientWidth;
  1066. const h = el.clientHeight;
  1067. const cx = w / 2;
  1068. const cy = h / 2;
  1069. const r = Math.min(w, h) / 4;
  1070. const r2 = r / 4;
  1071. const svg = `data:image/svg+xml;utf8,
  1072. <svg width='${w}' height='${h}' baseProfile='full' xmlns='http://www.w3.org/2000/svg'>
  1073. <rect x='0' y='0' width='${w}' height='${h}' fill='${GIF_STOP_COLOR_BG}'/>
  1074. <circle cx='${cx - r}' cy='${cy}' r='${r2}' fill='${GIF_STOP_COLOR_FG}'/>
  1075. <circle cx='${cx}' cy='${cy}' r='${r2}' fill='${GIF_STOP_COLOR_FG}'/>
  1076. <circle cx='${cx + r}' cy='${cy}' r='${r2}' fill='${GIF_STOP_COLOR_FG}'/>
  1077. </svg>
  1078. `;
  1079. el.setAttribute('src', svg);
  1080. // когда отрендерится троеточие, можно менять на исходную гифку
  1081. setTimeout(() => {
  1082. if (el.dataset.oldSrc) {
  1083. el.setAttribute('src', el.dataset.oldSrc);
  1084. el.dataset.oldSrc = ''; // eslint-disable-line no-param-reassign
  1085. }
  1086. }, 100);
  1087. } else {
  1088. const img = document.createElement('img');
  1089. img.setAttribute('src', el.dataset.oldSrc);
  1090. if (el.hasAttribute('align')) {
  1091. img.setAttribute('align', el.getAttribute('align'));
  1092. }
  1093. el.parentNode.insertBefore(img, el);
  1094. img.onclick = () => toggleGIF(img); // eslint-disable-line no-param-reassign
  1095. el.parentNode.removeChild(el);
  1096. }
  1097. }
  1098.  
  1099. if (GIF_STOP) {
  1100. [...document.querySelectorAll('.post__text img[src$=".gif"], .comment__message img[src$=".gif"]')]
  1101. .forEach((el) => {
  1102. if (GIF_STOP_ONLOAD) toggleGIF(el);
  1103. el.onclick = () => toggleGIF(el); // eslint-disable-line no-param-reassign
  1104. });
  1105. }
  1106.  
  1107. // фиксирование высоты публикации чтобы убрать прыжки прокрутки
  1108. if (FIX_JUMPING_SCROLL) {
  1109. const postBodyEl = document.querySelector('.post__body_full');
  1110. const checkPostBodyInViewport = () => postBodyEl.getBoundingClientRect().bottom > 0;
  1111. const autoHeightPost = () => {
  1112. if (checkPostBodyInViewport()) {
  1113. window.removeEventListener('scroll', autoHeightPost);
  1114. postBodyEl.style.height = 'auto';
  1115. }
  1116. };
  1117. if (postBodyEl && !checkPostBodyInViewport()) {
  1118. const h = postBodyEl.clientHeight;
  1119. postBodyEl.style.height = `${h}px`;
  1120. window.addEventListener('scroll', autoHeightPost);
  1121. }
  1122. }
  1123.  
  1124. // счетчики кармы
  1125. if (KARMA_DETAILS) {
  1126. Array.from(document.querySelectorAll('.user-info__stats-item.stacked-counter')).forEach((itemCounter) => {
  1127. itemCounter.style.marginRight = '16px'; // eslint-disable-line no-param-reassign
  1128. });
  1129. Array.from(document.querySelectorAll('.page-header__stats_karma')).forEach((karmaEl) => {
  1130. karmaEl.style.width = 'auto'; // eslint-disable-line no-param-reassign
  1131. karmaEl.style.minWidth = '84px'; // eslint-disable-line no-param-reassign
  1132. });
  1133. Array.from(document.querySelectorAll('.stacked-counter[href="/info/help/karma/"]')).forEach((couterEl) => {
  1134. let total = parseInt(couterEl.title, 10);
  1135. const scoreEl = couterEl.querySelector('.stacked-counter__value');
  1136. if (!scoreEl || !total) return;
  1137. couterEl.style.width = 'auto'; // eslint-disable-line no-param-reassign
  1138. couterEl.style.minWidth = '84px'; // eslint-disable-line no-param-reassign
  1139. const score = parseFloat(scoreEl.innerHTML.replace('–', '-').replace(',', '.'), 10);
  1140. if (score > total) total = score;
  1141. const likes = (total + score) / 2;
  1142. const percent = Math.round((100 * likes) / total);
  1143. const details = `&nbsp;= ${total} × (${percent} ${100 - percent})%`;
  1144. const detailsEl = document.createElement('span');
  1145. detailsEl.innerHTML = details;
  1146. detailsEl.style.color = '#545454';
  1147. detailsEl.style.fontFamily = '"-apple-system",BlinkMacSystemFont,Arial,sans-serif';
  1148. detailsEl.style.fontSize = '13px';
  1149. detailsEl.style.fontWeight = 'normal';
  1150. detailsEl.style.verticalAlign = 'middle';
  1151. scoreEl.appendChild(detailsEl);
  1152. couterEl.title += `, ${(likes).toFixed(2)} плюсов и ${(total - likes).toFixed(2)} минусов`; // eslint-disable-line no-param-reassign
  1153. });
  1154. }
  1155.  
  1156. // счетчики рейтинга с подробностями
  1157. const scoresMap = new Map();
  1158.  
  1159. class Score {
  1160. constructor(el) {
  1161. this.el = el;
  1162. const data = this.constructor.parse(el);
  1163. this.rating = data.rating;
  1164. this.total = data.total;
  1165. this.likes = data.likes;
  1166. this.dislikes = data.dislikes;
  1167. this.isDetailed = false;
  1168. this.observer = new MutationObserver(() => this.update());
  1169. }
  1170.  
  1171. setDetails(isDetailed) {
  1172. if (this.isDetailed === isDetailed) return;
  1173. this.isDetailed = isDetailed;
  1174. this.update();
  1175. }
  1176.  
  1177. update() {
  1178. const data = this.constructor.parse(this.el);
  1179. this.rating = data.rating;
  1180. this.total = data.total;
  1181. this.likes = data.likes;
  1182. this.dislikes = data.dislikes;
  1183. this.observer.disconnect();
  1184. if (this.isDetailed) {
  1185. this.details();
  1186. } else {
  1187. this.simply();
  1188. }
  1189. this.observer.observe(this.el, { childList: true });
  1190. }
  1191.  
  1192. static parse(el) {
  1193. let [total, likes, dislikes] = el
  1194. .attributes.title.textContent
  1195. .match(/[0-9]+/g).map(Number);
  1196. let [, sign, rating] = el.innerHTML.match(/([–]?)(\d+)/); // eslint-disable-line prefer-const
  1197. rating = Number(rating);
  1198. if (sign) rating = -rating;
  1199. // не знаю что там происходит при голосовании, так что на всякий случай
  1200. const diff = rating - (likes - dislikes);
  1201. if (diff < 0) {
  1202. total += Math.abs(diff);
  1203. dislikes += Math.abs(diff);
  1204. } else if (diff > 0) {
  1205. total += diff;
  1206. likes += diff;
  1207. }
  1208. return {
  1209. rating,
  1210. total,
  1211. likes,
  1212. dislikes,
  1213. };
  1214. }
  1215.  
  1216. simply() {
  1217. let innerHTML = '';
  1218. if (this.rating > 0) {
  1219. innerHTML = `+${this.rating}`;
  1220. } else if (this.rating < 0) {
  1221. innerHTML = `–${Math.abs(this.rating)}`;
  1222. } else {
  1223. innerHTML = '0';
  1224. }
  1225. this.el.innerHTML = innerHTML;
  1226. }
  1227.  
  1228. details() {
  1229. let innerHTML = '';
  1230. if (this.rating > 0) {
  1231. innerHTML = `+${this.rating}`;
  1232. } else if (this.rating < 0) {
  1233. innerHTML = `–${Math.abs(this.rating)}`;
  1234. } else {
  1235. innerHTML = '0';
  1236. }
  1237. if (this.total !== 0) {
  1238. let details = '';
  1239. if (RATING_DETAILS_PN) {
  1240. details = `&nbsp;= ${this.likes} ${this.dislikes}`;
  1241. } else {
  1242. const percent = Math.round((100 * this.likes) / this.total);
  1243. details = `&nbsp;= ${this.total} × (${percent} ${100 - percent})%`;
  1244. }
  1245. innerHTML += ` <span style='color: #545454; font-weight: normal'>${details}</span>`;
  1246. }
  1247. this.el.innerHTML = innerHTML;
  1248. }
  1249. }
  1250.  
  1251. // парсим их
  1252. [...document.querySelectorAll('.voting-wjt__counter')].forEach((el) => {
  1253. scoresMap.set(el, new Score(el));
  1254. });
  1255.  
  1256. // добавляем подробностей
  1257. if (RATING_DETAILS) {
  1258. if (RATING_DETAILS_ONCLICK) {
  1259. const isDetailed = userConfig.getItem('scores_details');
  1260. if (isDetailed) scoresMap.forEach(score => score.setDetails(isDetailed));
  1261. scoresMap.forEach((score) => {
  1262. score.el.onclick = () => { // eslint-disable-line no-param-reassign
  1263. const nowDetailed = userConfig.shiftItem('scores_details');
  1264. scoresMap.forEach(s => s.setDetails(nowDetailed));
  1265. };
  1266. });
  1267. } else {
  1268. scoresMap.forEach(score => score.setDetails(true));
  1269. }
  1270. }
  1271.  
  1272. // метки времени и работа с ними
  1273. const pageLoadTime = new Date();
  1274. const monthNames = [
  1275. 'января', 'февраля', 'марта',
  1276. 'апреля', 'мая', 'июня',
  1277. 'июля', 'августа', 'сентября',
  1278. 'октября', 'ноября', 'декабря',
  1279. ];
  1280.  
  1281. class HabraTime {
  1282. constructor(el, parent) {
  1283. this.el = el;
  1284. this.parent = parent;
  1285. this.attrDatetime = this.constructor.getAttributeDatetime(el);
  1286. this.date = new Date(this.attrDatetime);
  1287. }
  1288.  
  1289. // вот было бы хорошо, если б на хабре были datetime атрибуты
  1290. static getAttributeDatetime(el) {
  1291. const imagination = el.getAttribute('datetime');
  1292. if (imagination) return imagination;
  1293.  
  1294. const re = /((сегодня|вчера)|(\d+)[ .]([а-я]+|\d+)[ .]?(\d+)?) в (\d\d:\d\d)/;
  1295. let [,,
  1296. recently, // eslint-disable-line prefer-const
  1297. day, month, year,
  1298. time, // eslint-disable-line prefer-const
  1299. ] = el.innerHTML.match(re);
  1300.  
  1301. // и местное время
  1302. let moscow;
  1303. if (recently || year === undefined) {
  1304. const offsetMoscow = 3 * 60 * 60 * 1000;
  1305. const yesterdayShift = (recently === 'вчера') ? 24 * 60 * 60 * 1000 : 0;
  1306. const offset = pageLoadTime.getTimezoneOffset() * 60 * 1000;
  1307. const value = (pageLoadTime - yesterdayShift) + offsetMoscow + offset;
  1308. moscow = new Date(value);
  1309. }
  1310.  
  1311. if (recently) {
  1312. day = moscow.getDate();
  1313. month = moscow.getMonth() + 1;
  1314. } else if (month.length !== 2) {
  1315. month = monthNames.indexOf(month) + 1;
  1316. } else {
  1317. month = +month;
  1318. }
  1319.  
  1320. if (day < 10) day = `0${+day}`;
  1321. if (month < 10) month = `0${month}`;
  1322. if (year < 100) year = `20${year}`;
  1323. if (year === undefined) year = moscow.getFullYear();
  1324.  
  1325. return `${year}-${month}-${day}T${time}+03:00`;
  1326. }
  1327.  
  1328. absolute() {
  1329. let result = '';
  1330.  
  1331. const time = this.date;
  1332. const day = time.getDate();
  1333. const month = time.getMonth();
  1334. const monthName = monthNames[month];
  1335. const year = time.getFullYear();
  1336. const hours = time.getHours();
  1337. const minutes = time.getMinutes();
  1338.  
  1339. const now = new Date();
  1340. const nowDay = now.getDate();
  1341. const nowMonth = now.getMonth();
  1342. const nowYear = now.getFullYear();
  1343.  
  1344. const yesterday = new Date((now - 24) * 60 * 60 * 1000);
  1345. const yesterdayDay = yesterday.getDate();
  1346. const yesterdayMonth = yesterday.getMonth();
  1347. const yesterdayYear = yesterday.getFullYear();
  1348.  
  1349. const hhmm = `${hours}:${minutes >= 10 ? minutes : `0${minutes}`}`;
  1350.  
  1351. const isToday =
  1352. day === nowDay &&
  1353. month === nowMonth &&
  1354. year === nowYear;
  1355. const isYesterday =
  1356. day === yesterdayDay &&
  1357. month === yesterdayMonth &&
  1358. year === yesterdayYear;
  1359.  
  1360. if (isToday) {
  1361. result = `сегодня в ${hhmm}`;
  1362. } else if (isYesterday) {
  1363. result = `вчера в ${hhmm}`;
  1364. } else if (nowYear === year) {
  1365. result = `${day} ${monthName} в ${hhmm}`;
  1366. } else {
  1367. result = `${day} ${monthName} ${year} в ${hhmm}`;
  1368. }
  1369.  
  1370. return result;
  1371. }
  1372.  
  1373. static relative(milliseconds) {
  1374. let result = '';
  1375.  
  1376. const pluralForm = (n, forms) => {
  1377. if (n % 10 === 1 && n % 100 !== 11) return forms[0];
  1378. if (n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20)) return forms[1];
  1379. return forms[2];
  1380. };
  1381.  
  1382. const formats = [
  1383. ['год', 'года', 'лет'],
  1384. ['месяц', 'месяца', 'месяцев'],
  1385. ['день', 'дня', 'дней'],
  1386. ['час', 'часа', 'часов'],
  1387. ['минуту', 'минуты', 'минут'],
  1388. ];
  1389.  
  1390. const minutes = milliseconds / 60000;
  1391. const hours = minutes / 60;
  1392. const days = hours / 24;
  1393. const months = days / 30;
  1394. const years = months / 12;
  1395. const idx = [years, months, days, hours, minutes].findIndex(x => x >= 1);
  1396.  
  1397. if (idx === -1) {
  1398. result = 'несколько секунд';
  1399. } else {
  1400. const value = Math.floor([years, months, days, hours, minutes][idx]);
  1401. const forms = formats[idx];
  1402. const form = pluralForm(value, forms);
  1403. result = `${value} ${form}`;
  1404. }
  1405. return result;
  1406. }
  1407.  
  1408. fromNow() {
  1409. const diff = Math.abs(Date.now() - this.date);
  1410. return `${this.constructor.relative(diff)} назад`;
  1411. }
  1412.  
  1413. fromParent() {
  1414. const diff = Math.abs(this.date - this.parent.date);
  1415. return `через ${this.constructor.relative(diff)}`;
  1416. }
  1417. }
  1418.  
  1419. // собираем метки времени
  1420. const datesMap = new Map();
  1421. const megapostTimeEl = document.querySelector('.megapost-head__meta > .list_inline > .list__item');
  1422. (megapostTimeEl ? [megapostTimeEl] : [])
  1423. .concat([...document.querySelectorAll(`
  1424. .post__time,
  1425. .preview-data__time-published,
  1426. time.comment__date-time_published,
  1427. .tm-post__date,
  1428. .user-message__date-time
  1429. `)]).forEach((el) => {
  1430. datesMap.set(el, new HabraTime(el));
  1431. });
  1432.  
  1433. function updateTime() {
  1434. datesMap.forEach((habraTime) => {
  1435. let type;
  1436. let otherTypes;
  1437. if (habraTime.parent) {
  1438. type = userConfig.config.time_comments;
  1439. otherTypes = userConfig.model.time_comments
  1440. .filter(str => str !== type);
  1441. } else {
  1442. type = userConfig.config.time_publications;
  1443. otherTypes = userConfig.model.time_publications
  1444. .filter(str => str !== type);
  1445. }
  1446. const title = otherTypes.map(otherType => habraTime[otherType]()).join(', ');
  1447. habraTime.el.innerHTML = habraTime[type](); // eslint-disable-line no-param-reassign
  1448. habraTime.el.setAttribute('title', title);
  1449. });
  1450. }
  1451.  
  1452. if (TIME_DETAILS) {
  1453. datesMap.forEach((habraTime) => {
  1454. habraTime.el.setAttribute(
  1455. 'style',
  1456. 'cursor: pointer; -moz-user-select: none; -webkit-user-select: none; -ms-user-select: none; user-select: none;',
  1457. );
  1458. habraTime.el.onclick = () => { // eslint-disable-line no-param-reassign
  1459. if (habraTime.parent) {
  1460. userConfig.shiftItem('time_comments');
  1461. } else {
  1462. userConfig.shiftItem('time_publications');
  1463. }
  1464. updateTime();
  1465. };
  1466. });
  1467. // подождём, когда дерево комментариев будет построено
  1468. // у некоторых меток времени будут установлены родители
  1469. // тогда и обновим их тексты
  1470. setTimeout(updateTime, 100);
  1471. setInterval(updateTime, 30 * 1000);
  1472. }
  1473.  
  1474. // время публикации, понадобится для корня древа комментариев
  1475. let datePublication = datesMap.get(megapostTimeEl || document.querySelector('.post__time'));
  1476. // если нету публикации поищем самую раннюю метку времени
  1477. if (!datePublication) {
  1478. datePublication = { date: pageLoadTime };
  1479. datesMap.forEach((date) => {
  1480. if (date.date < datePublication.date) datePublication = date;
  1481. });
  1482. }
  1483.  
  1484. // создаем дерево комментариев
  1485. class ItemComment {
  1486. constructor(el, parent) {
  1487. this.parent = parent;
  1488. this.el = el;
  1489. this.lvl = parent.lvl + 1;
  1490. this.id = Number(el.getAttribute('rel'));
  1491. this.commentEl = el.querySelector('.comment');
  1492. if (this.commentEl) {
  1493. this.timeEl = this.commentEl.querySelector('time');
  1494. this.ratingEl = this.commentEl.querySelector('.js-score');
  1495. }
  1496. this.date = datesMap.get(this.timeEl);
  1497. if (this.date) {
  1498. this.date.parent = parent.date;
  1499. } else {
  1500. this.date = parent.date;
  1501. }
  1502. this.votes = scoresMap.get(this.ratingEl) || {
  1503. total: 0, likes: 0, dislikes: 0, rating: 0,
  1504. };
  1505. this.elList = el.querySelector('.content-list_nested-comments');
  1506. }
  1507.  
  1508. existId(id) {
  1509. return !!this.elList.querySelector(id);
  1510. }
  1511.  
  1512. existNew() {
  1513. return !!this.elList.querySelector('.js-comment_new');
  1514. }
  1515.  
  1516. getLength() {
  1517. let { length } = this.list;
  1518. this.list.forEach((node) => {
  1519. length += node.getLength();
  1520. });
  1521. return length;
  1522. }
  1523. }
  1524.  
  1525. class CommentsTree {
  1526. constructor() {
  1527. this.root = {
  1528. isRoot: true,
  1529. date: datePublication,
  1530. lvl: 0,
  1531. elList: document.getElementById('comments-list'),
  1532. list: [],
  1533. };
  1534. }
  1535.  
  1536. static exist() {
  1537. return !!document.getElementById('comments-list');
  1538. }
  1539.  
  1540. update() {
  1541. if (!this.root.elList) return;
  1542. const recAdd = (node) => {
  1543. node.list = Array.from(node.elList.children) // eslint-disable-line no-param-reassign
  1544. .map(el => new ItemComment(el, node));
  1545. node.list.forEach(recAdd);
  1546. };
  1547. recAdd(this.root);
  1548. }
  1549.  
  1550. walkTree(fn) {
  1551. const walk = (tree) => {
  1552. fn(tree);
  1553. tree.list.forEach(walk);
  1554. };
  1555. walk(this.root);
  1556. }
  1557.  
  1558. sort(fn) {
  1559. if (!this.root.elList) return;
  1560. this.walkTree((tree) => {
  1561. tree.list.sort(fn).forEach(subtree => tree.elList.appendChild(subtree.el));
  1562. });
  1563. }
  1564.  
  1565. shuffle() {
  1566. if (!this.root.elList) return;
  1567. const randInt = maximum => Math.floor(Math.random() * (maximum + 1));
  1568. this.walkTree((tree) => {
  1569. const { list } = tree;
  1570. for (let i = 0; i < list.length; i += 1) {
  1571. const j = randInt(i);
  1572. [list[i], list[j]] = [list[j], list[i]];
  1573. }
  1574. list.forEach(subtree => tree.elList.appendChild(subtree.el));
  1575. });
  1576. }
  1577. }
  1578.  
  1579. const commentsTree = new CommentsTree();
  1580. commentsTree.update();
  1581.  
  1582. // здесь начинается сортировка комментариев
  1583. const commentsOrderEl = document.createElement('div');
  1584. commentsOrderEl.classList.add('comments_order');
  1585. commentsOrderEl.innerHTML = sortVariants.map(([type, text]) => {
  1586. const underline = (type === 'time') ? 'style="text-decoration: underline;"' : '';
  1587. return `<a data-order="${type}" ${underline}>${text}</a>`;
  1588. }).join(', ');
  1589.  
  1590. if (COMMENTS_SORT && document.getElementById('comments-list')) {
  1591. const commentsList = document.getElementById('comments-list');
  1592. commentsList.parentElement.insertBefore(commentsOrderEl, commentsList);
  1593. }
  1594.  
  1595. const commentsComparators = {
  1596. time(a, b) {
  1597. return a.id - b.id;
  1598. },
  1599.  
  1600. freshness(a, b) {
  1601. return b.id - a.id;
  1602. },
  1603.  
  1604. rating(a, b) {
  1605. const ascore = a.votes.rating;
  1606. const bscore = b.votes.rating;
  1607. if (bscore !== ascore) return bscore - ascore;
  1608. return b.id - a.id;
  1609. },
  1610.  
  1611. popularity(a, b) {
  1612. const aVotes = a.votes.total;
  1613. const bVotes = b.votes.total;
  1614. if (aVotes !== bVotes) return bVotes - aVotes;
  1615. const aLength = a.getLength();
  1616. const bLength = b.getLength();
  1617. if (aLength !== bLength) return bLength - aLength;
  1618. return b.id - a.id;
  1619. },
  1620.  
  1621. quality(a, b) {
  1622. const aQuality = a.votes.rating / a.votes.total || 0;
  1623. const bQuality = b.votes.rating / b.votes.total || 0;
  1624. if (aQuality !== bQuality) return bQuality - aQuality;
  1625. if (a.votes.rating !== b.votes.rating) return b.votes.rating - a.votes.rating;
  1626. return b.id - a.id;
  1627. },
  1628.  
  1629. trend(a, b) {
  1630. // в первые сутки после публикации статьи число посещений больше чем в остальное время
  1631. const oneDay = 24 * 60 * 60 * 1000;
  1632. const firstDayEnd = +datePublication.date + oneDay;
  1633. // у комментария есть только три дня на голосование с момента его создания
  1634. const threeDays = 3 * oneDay;
  1635. const now = Date.now();
  1636.  
  1637. // прикинем число голосов в первый день
  1638. const aDate = +a.date.date;
  1639. let aViews = 0;
  1640. // в первый день
  1641. if (aDate <= firstDayEnd) {
  1642. aViews += Math.min(firstDayEnd, now) - aDate;
  1643. }
  1644. // и в остальное время
  1645. if (now >= firstDayEnd) {
  1646. const threeDaysEnd = aDate + threeDays;
  1647. // для этого соотношения я собрал статистику
  1648. aViews += (Math.min(threeDaysEnd, now) - Math.max(firstDayEnd, aDate)) / 16;
  1649. }
  1650. const aScore = a.votes.rating / aViews;
  1651.  
  1652. // аналогично
  1653. const bDate = +b.date.date;
  1654. let bViews = 0;
  1655. if (bDate <= firstDayEnd) {
  1656. bViews += Math.min(firstDayEnd, now) - bDate;
  1657. }
  1658. if (now >= firstDayEnd) {
  1659. const threeDaysEnd = bDate + threeDays;
  1660. // найти зависимость активности голосования от времени суток не удалось
  1661. bViews += (Math.min(threeDaysEnd, now) - Math.max(firstDayEnd, bDate)) / 16;
  1662. }
  1663. const bScore = b.votes.rating / bViews;
  1664.  
  1665. if (bScore === aScore) return b.id - a.id;
  1666. return bScore - aScore;
  1667. },
  1668. };
  1669.  
  1670. const sortComments = () => {
  1671. const order = userConfig.getItem('comments_order');
  1672.  
  1673. Array.from(commentsOrderEl.children).forEach((el) => {
  1674. if (el.dataset.order === order) {
  1675. el.style.textDecoration = 'underline'; // eslint-disable-line no-param-reassign
  1676. } else {
  1677. el.style.textDecoration = ''; // eslint-disable-line no-param-reassign
  1678. }
  1679. });
  1680.  
  1681. if (order === 'shuffle') {
  1682. commentsTree.shuffle();
  1683. } else {
  1684. const compare = commentsComparators[order];
  1685. commentsTree.sort(compare);
  1686. }
  1687. };
  1688.  
  1689. // сортируем комменты при загрузке страницы
  1690. // или не сортируем, если они уже по порядку
  1691. if (COMMENTS_SORT && COMMENTS_SORT_ONLOAD && userConfig.getItem('comments_order') !== 'time') {
  1692. sortComments();
  1693. }
  1694.  
  1695. Array.from(commentsOrderEl.children).forEach((el) => {
  1696. el.onclick = () => { // eslint-disable-line no-param-reassign
  1697. userConfig.setItem('comments_order', el.dataset.order);
  1698. sortComments();
  1699. };
  1700. });
  1701.  
  1702. // меняем ссылки ведущие к новым комментариям на ссылки к началу комментариев
  1703. if (COMMENTS_LINKS) {
  1704. const commentsLinks = document.getElementsByClassName('post-stats__comments-link');
  1705.  
  1706. for (let i = 0; i < commentsLinks.length; i += 1) {
  1707. const iLink = commentsLinks[i];
  1708. const hrefValue = iLink.getAttribute('href');
  1709. const hrefToComments = hrefValue.replace('#first_unread', '#comments');
  1710. iLink.setAttribute('href', hrefToComments);
  1711. }
  1712. }
  1713.  
  1714. // сворачивание комментов
  1715. if (COMMENTS_HIDE) {
  1716. const commentHash = window.location.hash;
  1717.  
  1718. const toggle = (subtree) => {
  1719. const listLength = subtree.list.length;
  1720. if (listLength === 0) return;
  1721. /* eslint-disable */
  1722. if (subtree.switcherEl.dataset.isVisibleList === 'true') {
  1723. subtree.switcherEl.dataset.isVisibleList = 'false';
  1724. subtree.switcherEl.innerHTML = `\u229E раскрыть ветвь ${subtree.getLength()}`;
  1725. subtree.elList.style.display = 'none';
  1726. } else {
  1727. subtree.switcherEl.dataset.isVisibleList = 'true';
  1728. subtree.switcherEl.innerHTML = '\u229F';
  1729. subtree.elList.style.display = 'block';
  1730. }
  1731. /* eslint-enable */
  1732. };
  1733.  
  1734. commentsTree.walkTree((subtree) => {
  1735. // не пытаемся сворачивать корень
  1736. if (subtree.isRoot) return;
  1737. // у похищенных нет футера
  1738. const footerEl = subtree.commentEl.querySelector('.comment__footer');
  1739. if (footerEl === null) return;
  1740. // создаём переключатель
  1741. const switcher = document.createElement('a');
  1742. switcher.classList.add('comment__footer-link');
  1743. switcher.classList.add('comment__switcher');
  1744. switcher.dataset.isVisibleList = 'true';
  1745.  
  1746. switcher.innerHTML = '\u229F';
  1747. if (subtree.list.length === 0) switcher.innerHTML = '\u22A1';
  1748. switcher.style.marginLeft = '-5px';
  1749.  
  1750. footerEl.insertBefore(switcher, footerEl.children[0]);
  1751. subtree.switcherEl = switcher; // eslint-disable-line no-param-reassign
  1752.  
  1753. switcher.onclick = () => toggle(subtree);
  1754.  
  1755. const isHideLvl = subtree.lvl === HIDE_LEVEL;
  1756. const isLineLvl = subtree.lvl % LINE_LEN === 0;
  1757. if (isLineLvl) {
  1758. subtree.elList.classList.add('comments_new-line');
  1759. const lineNumber = subtree.lvl / LINE_LEN;
  1760. subtree.elList.classList.add(`comments_new-line-${lineNumber % 4}`);
  1761. }
  1762. // при запуске не сворачиваем ветки с новыми комментами, и содержащие целевой id
  1763. if (
  1764. (isHideLvl || isLineLvl) && !subtree.existNew() &&
  1765. !(commentHash && subtree.existId(commentHash))
  1766. ) {
  1767. toggle(subtree);
  1768. }
  1769. });
  1770. }
  1771.  
  1772. if (SCROLL_LEGEND) {
  1773. const postBodyEl = document.querySelector('.post__body_full') || document.querySelector('.article__body');
  1774. const commentsEl = document.getElementById('comments-list');
  1775. const getPercents = (el) => {
  1776. if (!el) return { topPercent: 0, heightPercent: 0 };
  1777. const pageHeight = document.documentElement.scrollHeight;
  1778. const top = el.getBoundingClientRect().top + window.pageYOffset;
  1779. const topPercent = ((100 * top) / pageHeight).toFixed(2);
  1780. const height = el.clientHeight;
  1781. const heightPercent = ((100 * height) / pageHeight).toFixed(2);
  1782.  
  1783. return { topPercent, heightPercent };
  1784. };
  1785.  
  1786. const updateLegend = (pageEl, legendEl) => {
  1787. const { topPercent, heightPercent } = getPercents(pageEl);
  1788. legendEl.style.top = `${topPercent}%`; // eslint-disable-line no-param-reassign
  1789. legendEl.style.height = `${heightPercent}%`; // eslint-disable-line no-param-reassign
  1790. };
  1791.  
  1792. const legendPost = document.createElement('div');
  1793. legendPost.classList.add('legend_el');
  1794. legendPost.style.background = 'rgba(84, 142, 170, 0.66)';
  1795. updateLegend(postBodyEl, legendPost);
  1796. document.body.appendChild(legendPost);
  1797.  
  1798. const legendComments = document.createElement('div');
  1799. legendComments.classList.add('legend_el');
  1800. legendComments.style.background = 'rgba(49, 176, 7, 0.66)';
  1801. updateLegend(commentsEl, legendComments);
  1802. document.body.appendChild(legendComments);
  1803.  
  1804. setInterval(() => {
  1805. updateLegend(postBodyEl, legendPost);
  1806. updateLegend(commentsEl, legendComments);
  1807. }, 1000);
  1808. }
  1809.  
  1810. if (NIGHT_MODE) {
  1811. const switcherEl = document.createElement('div');
  1812. switcherEl.classList.add('night_mode_switcher');
  1813. switcherEl.onclick = () => {
  1814. const isNightMode = userConfig.shiftItem('night_mode');
  1815. document.documentElement.classList.toggle('night', isNightMode);
  1816. };
  1817. document.body.appendChild(switcherEl);
  1818. setInterval(() => {
  1819. const boolClass = document.documentElement.classList.contains('night');
  1820. const isNightMode = userConfig.getItem('night_mode');
  1821. if (boolClass !== isNightMode) {
  1822. document.documentElement.classList.toggle('night', isNightMode);
  1823. }
  1824. }, 1000);
  1825. }
  1826. });