Habr.Features

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

当前为 2019-03-30 提交的版本,查看 最新版本

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