Habr.Features

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

当前为 2018-11-05 提交的版本,查看 最新版本

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