Habr.Features

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

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

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