Habr.Features

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

当前为 2019-09-28 提交的版本,查看 最新版本

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