Greasy Fork 还支持 简体中文。

Habr.Features

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

目前為 2018-10-17 提交的版本,檢視 最新版本

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