Habr.Features

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

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

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