Habr.Features

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

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

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