Habr.Features

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

当前为 2018-11-27 提交的版本,查看 最新版本

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