Habr.Features

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

当前为 2018-10-16 提交的版本,查看 最新版本

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