Habr.Features

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

当前为 2019-05-15 提交的版本,查看 最新版本

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