Habr.Features

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

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

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