Habr.Features

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

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

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