Habr.Features

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

当前为 2019-12-01 提交的版本,查看 最新版本

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