Habr.Features

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

当前为 2019-02-23 提交的版本,查看 最新版本

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