Habr.Features

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

当前为 2019-04-02 提交的版本,查看 最新版本

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