crowi.js 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810
  1. /* global location */
  2. /* eslint no-restricted-globals: ['error', 'locaion'] */
  3. import React from 'react';
  4. import ReactDOM from 'react-dom';
  5. import { debounce } from 'throttle-debounce';
  6. import { pathUtils } from 'growi-commons';
  7. import GrowiRenderer from '../util/GrowiRenderer';
  8. import RevisionLoader from '../components/Page/RevisionLoader';
  9. const entities = require('entities');
  10. const escapeStringRegexp = require('escape-string-regexp');
  11. require('jquery.cookie');
  12. require('bootstrap-select');
  13. require('./thirdparty-js/agile-admin');
  14. const Crowi = {};
  15. if (!window) {
  16. window = {};
  17. }
  18. window.Crowi = Crowi;
  19. /**
  20. * render Table Of Contents
  21. * @param {string} tocHtml
  22. */
  23. Crowi.renderTocContent = (tocHtml) => {
  24. $('#revision-toc-content').html(tocHtml);
  25. };
  26. /**
  27. * set 'data-caret-line' attribute that will be processed when 'shown.bs.tab' event fired
  28. * @param {number} line
  29. */
  30. Crowi.setCaretLineData = function(line) {
  31. const pageEditorDom = document.querySelector('#page-editor');
  32. pageEditorDom.setAttribute('data-caret-line', line);
  33. };
  34. /**
  35. * invoked when;
  36. *
  37. * 1. 'shown.bs.tab' event fired
  38. */
  39. Crowi.setCaretLineAndFocusToEditor = function() {
  40. // get 'data-caret-line' attributes
  41. const pageEditorDom = document.querySelector('#page-editor');
  42. if (pageEditorDom == null) {
  43. return;
  44. }
  45. const { appContainer } = window;
  46. const editorContainer = appContainer.getContainer('EditorContainer');
  47. const line = pageEditorDom.getAttribute('data-caret-line') || 0;
  48. editorContainer.setCaretLine(+line);
  49. // reset data-caret-line attribute
  50. pageEditorDom.removeAttribute('data-caret-line');
  51. // focus
  52. editorContainer.focusToEditor();
  53. };
  54. // original: middleware.swigFilter
  55. Crowi.userPicture = function(user) {
  56. if (!user) {
  57. return '/images/icons/user.svg';
  58. }
  59. return user.image || '/images/icons/user.svg';
  60. };
  61. Crowi.modifyScrollTop = function() {
  62. const offset = 10;
  63. const hash = window.location.hash;
  64. if (hash === '') {
  65. return;
  66. }
  67. const pageHeader = document.querySelector('#page-header');
  68. if (!pageHeader) {
  69. return;
  70. }
  71. const pageHeaderRect = pageHeader.getBoundingClientRect();
  72. const sectionHeader = Crowi.findSectionHeader(hash);
  73. if (sectionHeader === null) {
  74. return;
  75. }
  76. let timeout = 0;
  77. if (window.scrollY === 0) {
  78. timeout = 200;
  79. }
  80. setTimeout(() => {
  81. const sectionHeaderRect = sectionHeader.getBoundingClientRect();
  82. if (sectionHeaderRect.top >= pageHeaderRect.bottom) {
  83. return;
  84. }
  85. window.scrollTo(0, (window.scrollY - pageHeaderRect.height - offset));
  86. }, timeout);
  87. };
  88. Crowi.handleKeyEHandler = (event) => {
  89. // ignore when dom that has 'modal in' classes exists
  90. if (document.getElementsByClassName('modal in').length > 0) {
  91. return;
  92. }
  93. // show editor
  94. $('a[data-toggle="tab"][href="#edit"]').tab('show');
  95. event.preventDefault();
  96. };
  97. Crowi.handleKeyCHandler = (event) => {
  98. // ignore when dom that has 'modal in' classes exists
  99. if (document.getElementsByClassName('modal in').length > 0) {
  100. return;
  101. }
  102. // show modal to create a page
  103. $('#create-page').modal();
  104. event.preventDefault();
  105. };
  106. Crowi.handleKeyCtrlSlashHandler = (event) => {
  107. // show modal to create a page
  108. $('#shortcuts-modal').modal('toggle');
  109. event.preventDefault();
  110. };
  111. Crowi.initAffix = () => {
  112. const $affixContent = $('#page-header');
  113. if ($affixContent.length > 0) {
  114. const $affixContentContainer = $('.row.bg-title');
  115. const containerHeight = $affixContentContainer.outerHeight(true);
  116. $affixContent.affix({
  117. offset: {
  118. top() {
  119. return $('.navbar').outerHeight(true) + containerHeight;
  120. },
  121. },
  122. });
  123. $('[data-affix-disable]').on('click', function(e) {
  124. const $elm = $($(this).data('affix-disable'));
  125. $(window).off('.affix');
  126. $elm.removeData('affix').removeClass('affix affix-top affix-bottom');
  127. return false;
  128. });
  129. $affixContentContainer.css({ 'min-height': containerHeight });
  130. }
  131. };
  132. Crowi.initSlimScrollForRevisionToc = () => {
  133. const revisionTocElem = document.querySelector('.growi .revision-toc');
  134. const tocContentElem = document.querySelector('.growi .revision-toc .markdownIt-TOC');
  135. // growi layout only
  136. if (revisionTocElem == null || tocContentElem == null) {
  137. return;
  138. }
  139. function getCurrentRevisionTocTop() {
  140. // calculate absolute top of '#revision-toc' element
  141. return revisionTocElem.getBoundingClientRect().top;
  142. }
  143. function resetScrollbar(revisionTocTop) {
  144. // window height - revisionTocTop - .system-version height
  145. let h = window.innerHeight - revisionTocTop - 20;
  146. const tocContentHeight = tocContentElem.getBoundingClientRect().height + 15; // add margin
  147. h = Math.min(h, tocContentHeight);
  148. $('#revision-toc-content').slimScroll({
  149. railVisible: true,
  150. position: 'right',
  151. height: h,
  152. });
  153. }
  154. const resetScrollbarDebounced = debounce(100, resetScrollbar);
  155. // initialize
  156. const revisionTocTop = getCurrentRevisionTocTop();
  157. resetScrollbar(revisionTocTop);
  158. /*
  159. * set event listener
  160. */
  161. // resize
  162. window.addEventListener('resize', (event) => {
  163. resetScrollbarDebounced(getCurrentRevisionTocTop());
  164. });
  165. // affix on
  166. $('#revision-toc').on('affixed.bs.affix', () => {
  167. resetScrollbar(getCurrentRevisionTocTop());
  168. });
  169. // affix off
  170. $('#revision-toc').on('affixed-top.bs.affix', () => {
  171. // calculate sum of height (.navbar-header + .bg-title) + margin-top of .main
  172. const sum = 138;
  173. resetScrollbar(sum);
  174. });
  175. };
  176. Crowi.findHashFromUrl = function(url) {
  177. let match;
  178. /* eslint-disable no-cond-assign */
  179. if (match = url.match(/#(.+)$/)) {
  180. return `#${match[1]}`;
  181. }
  182. /* eslint-enable no-cond-assign */
  183. return '';
  184. };
  185. Crowi.findSectionHeader = function(hash) {
  186. if (hash.length === 0) {
  187. return;
  188. }
  189. // omit '#'
  190. const id = hash.replace('#', '');
  191. // don't use jQuery and document.querySelector
  192. // because hash may containe Base64 encoded strings
  193. const elem = document.getElementById(id);
  194. if (elem != null && elem.tagName.match(/h\d+/i)) { // match h1, h2, h3...
  195. return elem;
  196. }
  197. return null;
  198. };
  199. Crowi.unhighlightSelectedSection = function(hash) {
  200. const elem = Crowi.findSectionHeader(hash);
  201. if (elem != null) {
  202. elem.classList.remove('highlighted');
  203. }
  204. };
  205. Crowi.highlightSelectedSection = function(hash) {
  206. const elem = Crowi.findSectionHeader(hash);
  207. if (elem != null) {
  208. elem.classList.add('highlighted');
  209. }
  210. };
  211. /**
  212. * Return editor mode string
  213. * @return 'builtin' or 'hackmd' or null (not editing)
  214. */
  215. Crowi.getCurrentEditorMode = function() {
  216. const isEditing = $('body').hasClass('on-edit');
  217. if (!isEditing) {
  218. return null;
  219. }
  220. if ($('body').hasClass('builtin-editor')) {
  221. return 'builtin';
  222. }
  223. return 'hackmd';
  224. };
  225. $(() => {
  226. const crowi = window.crowi;
  227. const config = JSON.parse(document.getElementById('crowi-context-hydrate').textContent || '{}');
  228. const pageId = $('#content-main').data('page-id');
  229. // const revisionId = $('#content-main').data('page-revision-id');
  230. // const revisionCreatedAt = $('#content-main').data('page-revision-created');
  231. // const currentUser = $('#content-main').data('current-user');
  232. const isSeen = $('#content-main').data('page-is-seen');
  233. const pagePath = $('#content-main').data('path');
  234. const isSavedStatesOfTabChanges = config.isSavedStatesOfTabChanges;
  235. $('[data-toggle="popover"]').popover();
  236. $('[data-toggle="tooltip"]').tooltip();
  237. $('[data-tooltip-stay]').tooltip('show');
  238. $('#toggle-sidebar').click((e) => {
  239. const $mainContainer = $('.main-container');
  240. if ($mainContainer.hasClass('aside-hidden')) {
  241. $('.main-container').removeClass('aside-hidden');
  242. $.cookie('aside-hidden', 0, { expires: 30, path: '/' });
  243. }
  244. else {
  245. $mainContainer.addClass('aside-hidden');
  246. $.cookie('aside-hidden', 1, { expires: 30, path: '/' });
  247. }
  248. return false;
  249. });
  250. if ($.cookie('aside-hidden') === 1) {
  251. $('.main-container').addClass('aside-hidden');
  252. }
  253. $('.copy-link').on('click', function() {
  254. $(this).select();
  255. });
  256. $('#create-page').on('shown.bs.modal', (e) => {
  257. // quick hack: replace from server side rendering "date" to client side "date"
  258. const today = new Date();
  259. const month = (`0${today.getMonth() + 1}`).slice(-2);
  260. const day = (`0${today.getDate()}`).slice(-2);
  261. const dateString = `${today.getFullYear()}/${month}/${day}`;
  262. $('#create-page-today .page-today-suffix').text(`/${dateString}/`);
  263. $('#create-page-today .page-today-input2').data('prefix', `/${dateString}/`);
  264. // focus
  265. $('#create-page-today .page-today-input2').eq(0).focus();
  266. });
  267. $('#create-page-today').submit(function(e) {
  268. let prefix1 = $('input.page-today-input1', this).data('prefix');
  269. let prefix2 = $('input.page-today-input2', this).data('prefix');
  270. const input1 = $('input.page-today-input1', this).val();
  271. const input2 = $('input.page-today-input2', this).val();
  272. if (input1 === '') {
  273. prefix1 = 'メモ';
  274. }
  275. if (input2 === '') {
  276. prefix2 = prefix2.slice(0, -1);
  277. }
  278. top.location.href = `${prefix1 + input1 + prefix2 + input2}#edit`;
  279. return false;
  280. });
  281. $('#create-page-under-tree').submit(function(e) {
  282. let name = $('input', this).val();
  283. if (!name.match(/^\//)) {
  284. name = `/${name}`;
  285. }
  286. if (name.match(/.+\/$/)) {
  287. name = name.substr(0, name.length - 1);
  288. }
  289. top.location.href = `${pathUtils.encodePagePath(name)}#edit`;
  290. return false;
  291. });
  292. // rename/unportalize
  293. $('#renamePage, #unportalize').on('shown.bs.modal', (e) => {
  294. $('#renamePage #newPageName').focus();
  295. $('#renamePage .msg, #unportalize .msg').hide();
  296. });
  297. $('#renamePageForm, #unportalize-form').submit(function(e) {
  298. // create name-value map
  299. const nameValueMap = {};
  300. $(this).serializeArray().forEach((obj) => {
  301. nameValueMap[obj.name] = obj.value; // nameValueMap.new_path is renamed page path
  302. });
  303. nameValueMap.socketClientId = crowi.getSocketClientId();
  304. $.ajax({
  305. type: 'POST',
  306. url: '/_api/pages.rename',
  307. data: nameValueMap,
  308. dataType: 'json',
  309. })
  310. .done((res) => {
  311. // error
  312. if (!res.ok) {
  313. const linkPath = pathUtils.normalizePath(nameValueMap.new_path);
  314. $('#renamePage .msg, #unportalize .msg').hide();
  315. $(`#renamePage .msg-${res.code}, #unportalize .msg-${res.code}`).show();
  316. $('#renamePage #linkToNewPage, #unportalize #linkToNewPage').html(`
  317. <a href="${linkPath}">${linkPath} <i class="icon-login"></i></a>
  318. `);
  319. }
  320. else {
  321. const page = res.page;
  322. top.location.href = `${page.path}?renamed=${pagePath}`;
  323. }
  324. });
  325. return false;
  326. });
  327. // duplicate
  328. $('#duplicatePage').on('shown.bs.modal', (e) => {
  329. $('#duplicatePage #duplicatePageName').focus();
  330. $('#duplicatePage .msg').hide();
  331. });
  332. $('#duplicatePageForm, #unportalize-form').submit(function(e) {
  333. // create name-value map
  334. const nameValueMap = {};
  335. $(this).serializeArray().forEach((obj) => {
  336. nameValueMap[obj.name] = obj.value; // nameValueMap.new_path is duplicated page path
  337. });
  338. nameValueMap.socketClientId = crowi.getSocketClientId();
  339. $.ajax({
  340. type: 'POST',
  341. url: '/_api/pages.duplicate',
  342. data: nameValueMap,
  343. dataType: 'json',
  344. }).done((res) => {
  345. // error
  346. if (!res.ok) {
  347. const linkPath = pathUtils.normalizePath(nameValueMap.new_path);
  348. $('#duplicatePage .msg').hide();
  349. $(`#duplicatePage .msg-${res.code}`).show();
  350. $('#duplicatePage #linkToNewPage').html(`
  351. <a href="${linkPath}">${linkPath} <i class="icon-login"></i></a>
  352. `);
  353. }
  354. else {
  355. const page = res.page;
  356. top.location.href = `${page.path}?duplicated=${pagePath}`;
  357. }
  358. });
  359. return false;
  360. });
  361. // delete
  362. $('#deletePage').on('shown.bs.modal', (e) => {
  363. $('#deletePage .msg').hide();
  364. });
  365. $('#delete-page-form').submit((e) => {
  366. // create name-value map
  367. const nameValueMap = {};
  368. $('#delete-page-form').serializeArray().forEach((obj) => {
  369. nameValueMap[obj.name] = obj.value;
  370. });
  371. nameValueMap.socketClientId = crowi.getSocketClientId();
  372. $.ajax({
  373. type: 'POST',
  374. url: '/_api/pages.remove',
  375. data: nameValueMap,
  376. dataType: 'json',
  377. }).done((res) => {
  378. // error
  379. if (!res.ok) {
  380. $('#deletePage .msg').hide();
  381. $(`#deletePage .msg-${res.code}`).show();
  382. }
  383. else {
  384. const page = res.page;
  385. top.location.href = page.path;
  386. }
  387. });
  388. return false;
  389. });
  390. // Put Back
  391. $('#putBackPage').on('shown.bs.modal', (e) => {
  392. $('#putBackPage .msg').hide();
  393. });
  394. $('#revert-delete-page-form').submit((e) => {
  395. $.ajax({
  396. type: 'POST',
  397. url: '/_api/pages.revertRemove',
  398. data: $('#revert-delete-page-form').serialize(),
  399. dataType: 'json',
  400. }).done((res) => {
  401. // error
  402. if (!res.ok) {
  403. $('#putBackPage .msg').hide();
  404. $(`#putBackPage .msg-${res.code}`).show();
  405. }
  406. else {
  407. const page = res.page;
  408. top.location.href = page.path;
  409. }
  410. });
  411. return false;
  412. });
  413. $('#unlink-page-form').submit((e) => {
  414. $.ajax({
  415. type: 'POST',
  416. url: '/_api/pages.unlink',
  417. data: $('#unlink-page-form').serialize(),
  418. dataType: 'json',
  419. })
  420. .done((res) => {
  421. if (!res.ok) {
  422. $('#delete-errors').html(`<i class="fa fa-times-circle"></i> ${res.error}`);
  423. $('#delete-errors').addClass('alert-danger');
  424. }
  425. else {
  426. top.location.href = `${res.path}?unlinked=true`;
  427. }
  428. });
  429. return false;
  430. });
  431. $('#create-portal-button').on('click', (e) => {
  432. $('a[data-toggle="tab"][href="#edit"]').tab('show');
  433. $('body').addClass('on-edit');
  434. $('body').addClass('builtin-editor');
  435. const path = $('.content-main').data('path');
  436. if (path !== '/' && $('.content-main').data('page-id') === '') {
  437. const upperPage = path.substr(0, path.length - 1);
  438. $.get('/_api/pages.get', { path: upperPage }, (res) => {
  439. if (res.ok && res.page) {
  440. $('#portal-warning-modal').modal('show');
  441. }
  442. });
  443. }
  444. });
  445. $('#portal-form-close').on('click', (e) => {
  446. $('#edit').removeClass('active');
  447. $('body').removeClass('on-edit');
  448. $('body').removeClass('builtin-editor');
  449. location.hash = '#';
  450. });
  451. /*
  452. * wrap short path with <strong></strong>
  453. */
  454. $('#view-list .page-list-ul-flat .page-list-link').each(function() {
  455. const $link = $(this);
  456. /* eslint-disable-next-line no-unused-vars */
  457. const text = $link.text();
  458. let path = decodeURIComponent($link.data('path'));
  459. const shortPath = decodeURIComponent($link.data('short-path')); // convert to string
  460. if (path == null || shortPath == null) {
  461. // continue
  462. return;
  463. }
  464. path = entities.encodeHTML(path);
  465. const pattern = `${escapeStringRegexp(entities.encodeHTML(shortPath))}(/)?$`;
  466. $link.html(path.replace(new RegExp(pattern), `<strong>${shortPath}$1</strong>`));
  467. });
  468. // for list page
  469. let growiRendererForTimeline = null;
  470. $('a[data-toggle="tab"][href="#view-timeline"]').on('shown.bs.tab', () => {
  471. const isShown = $('#view-timeline').data('shown');
  472. if (growiRendererForTimeline == null) {
  473. const crowi = window.crowi;
  474. const crowiRenderer = window.crowiRenderer;
  475. growiRendererForTimeline = new GrowiRenderer(crowi, crowiRenderer, { mode: 'timeline' });
  476. }
  477. if (isShown === 0) {
  478. $('#view-timeline .timeline-body').each(function() {
  479. const id = $(this).attr('id');
  480. const revisionBody = `#${id} .revision-body`;
  481. const revisionBodyElem = document.querySelector(revisionBody);
  482. const revisionPath = `#${id} .revision-path`; // eslint-disable-line no-unused-vars
  483. const timelineElm = document.getElementById(id);
  484. const pageId = timelineElm.getAttribute('data-page-id');
  485. const pagePath = timelineElm.getAttribute('data-page-path');
  486. const revisionId = timelineElm.getAttribute('data-revision');
  487. ReactDOM.render(
  488. <RevisionLoader
  489. lazy
  490. crowi={crowi}
  491. crowiRenderer={growiRendererForTimeline}
  492. pageId={pageId}
  493. pagePath={pagePath}
  494. revisionId={revisionId}
  495. />,
  496. revisionBodyElem,
  497. );
  498. });
  499. $('#view-timeline').data('shown', 1);
  500. }
  501. });
  502. if (pageId) {
  503. // for Crowi Template LangProcessor
  504. $('.template-create-button', $('#revision-body')).on('click', function() {
  505. const path = $(this).data('path');
  506. const templateId = $(this).data('template');
  507. const template = $(`#${templateId}`).html();
  508. crowi.saveDraft(path, template);
  509. top.location.href = `${path}#edit`;
  510. });
  511. if (!isSeen) {
  512. $.post('/_api/pages.seen', { page_id: pageId }, (res) => {
  513. // ignore unless response has error
  514. if (res.ok && res.seenUser) {
  515. $('#content-main').data('page-is-seen', 1);
  516. }
  517. });
  518. }
  519. // presentation
  520. let presentaionInitialized = false;
  521. const $b = $('body');
  522. $(document).on('click', '.toggle-presentation', function(e) {
  523. const $a = $(this);
  524. e.preventDefault();
  525. $b.toggleClass('overlay-on');
  526. if (!presentaionInitialized) {
  527. presentaionInitialized = true;
  528. $('<iframe />').attr({
  529. src: $a.attr('href'),
  530. }).appendTo($('#presentation-container'));
  531. }
  532. }).on('click', '.fullscreen-layer', () => {
  533. $b.toggleClass('overlay-on');
  534. });
  535. } // end if pageId
  536. // tab changing handling
  537. $('a[href="#edit"]').on('show.bs.tab', () => {
  538. $('body').addClass('on-edit');
  539. $('body').addClass('builtin-editor');
  540. });
  541. $('a[href="#edit"]').on('hide.bs.tab', () => {
  542. $('body').removeClass('on-edit');
  543. $('body').removeClass('builtin-editor');
  544. });
  545. $('a[href="#hackmd"]').on('show.bs.tab', () => {
  546. $('body').addClass('on-edit');
  547. $('body').addClass('hackmd');
  548. });
  549. $('a[href="#hackmd"]').on('hide.bs.tab', () => {
  550. $('body').removeClass('on-edit');
  551. $('body').removeClass('hackmd');
  552. });
  553. // hash handling
  554. if (isSavedStatesOfTabChanges) {
  555. $('a[data-toggle="tab"][href="#revision-history"]').on('show.bs.tab', () => {
  556. window.location.hash = '#revision-history';
  557. window.history.replaceState('', 'History', '#revision-history');
  558. });
  559. $('a[data-toggle="tab"][href="#edit"]').on('show.bs.tab', () => {
  560. window.location.hash = '#edit';
  561. window.history.replaceState('', 'Edit', '#edit');
  562. });
  563. $('a[data-toggle="tab"][href="#hackmd"]').on('show.bs.tab', () => {
  564. window.location.hash = '#hackmd';
  565. window.history.replaceState('', 'HackMD', '#hackmd');
  566. });
  567. $('a[data-toggle="tab"][href="#revision-body"]').on('show.bs.tab', () => {
  568. // couln't solve https://github.com/weseek/crowi-plus/issues/119 completely -- 2017.07.03 Yuki Takei
  569. window.location.hash = '#';
  570. window.history.replaceState('', '', location.href);
  571. });
  572. }
  573. else {
  574. $('a[data-toggle="tab"][href="#revision-history"]').on('show.bs.tab', () => {
  575. window.history.replaceState('', 'History', '#revision-history');
  576. });
  577. $('a[data-toggle="tab"][href="#edit"]').on('show.bs.tab', () => {
  578. window.history.replaceState('', 'Edit', '#edit');
  579. });
  580. $('a[data-toggle="tab"][href="#hackmd"]').on('show.bs.tab', () => {
  581. window.history.replaceState('', 'HackMD', '#hackmd');
  582. });
  583. $('a[data-toggle="tab"][href="#revision-body"]').on('show.bs.tab', () => {
  584. window.history.replaceState('', '', location.href.replace(location.hash, ''));
  585. });
  586. // replace all href="#edit" link behaviors
  587. $(document).on('click', 'a[href="#edit"]', () => {
  588. window.location.replace('#edit');
  589. });
  590. }
  591. // focus to editor when 'shown.bs.tab' event fired
  592. $('a[href="#edit"]').on('shown.bs.tab', (e) => {
  593. Crowi.setCaretLineAndFocusToEditor();
  594. });
  595. });
  596. window.addEventListener('load', (e) => {
  597. // hash on page
  598. if (location.hash) {
  599. if ((location.hash === '#edit' || location.hash === '#edit-form') && $('.tab-pane#edit').length > 0) {
  600. $('a[data-toggle="tab"][href="#edit"]').tab('show');
  601. $('body').addClass('on-edit');
  602. $('body').addClass('builtin-editor');
  603. // focus
  604. Crowi.setCaretLineAndFocusToEditor();
  605. }
  606. else if (location.hash === '#hackmd' && $('.tab-pane#hackmd').length > 0) {
  607. $('a[data-toggle="tab"][href="#hackmd"]').tab('show');
  608. $('body').addClass('on-edit');
  609. $('body').addClass('hackmd');
  610. }
  611. else if (location.hash === '#revision-history' && $('.tab-pane#revision-history').length > 0) {
  612. $('a[data-toggle="tab"][href="#revision-history"]').tab('show');
  613. }
  614. }
  615. const crowi = window.crowi;
  616. if (crowi && crowi.users && crowi.users.length !== 0) {
  617. const totalUsers = crowi.users.length;
  618. const $listLiker = $('.page-list-liker');
  619. $listLiker.each((i, liker) => {
  620. const count = $(liker).data('count') || 0;
  621. if (count / totalUsers > 0.05) {
  622. $(liker).addClass('popular-page-high');
  623. // 5%
  624. }
  625. else if (count / totalUsers > 0.02) {
  626. $(liker).addClass('popular-page-mid');
  627. // 2%
  628. }
  629. else if (count / totalUsers > 0.005) {
  630. $(liker).addClass('popular-page-low');
  631. // 0.5%
  632. }
  633. });
  634. const $listSeer = $('.page-list-seer');
  635. $listSeer.each((i, seer) => {
  636. const count = $(seer).data('count') || 0;
  637. if (count / totalUsers > 0.10) {
  638. // 10%
  639. $(seer).addClass('popular-page-high');
  640. }
  641. else if (count / totalUsers > 0.05) {
  642. // 5%
  643. $(seer).addClass('popular-page-mid');
  644. }
  645. else if (count / totalUsers > 0.02) {
  646. // 2%
  647. $(seer).addClass('popular-page-low');
  648. }
  649. });
  650. }
  651. Crowi.highlightSelectedSection(location.hash);
  652. Crowi.modifyScrollTop();
  653. Crowi.initSlimScrollForRevisionToc();
  654. Crowi.initAffix();
  655. });
  656. window.addEventListener('hashchange', (e) => {
  657. Crowi.unhighlightSelectedSection(Crowi.findHashFromUrl(e.oldURL));
  658. Crowi.highlightSelectedSection(Crowi.findHashFromUrl(e.newURL));
  659. Crowi.modifyScrollTop();
  660. // hash on page
  661. if (location.hash) {
  662. if (location.hash === '#edit') {
  663. $('a[data-toggle="tab"][href="#edit"]').tab('show');
  664. }
  665. else if (location.hash === '#hackmd') {
  666. $('a[data-toggle="tab"][href="#hackmd"]').tab('show');
  667. }
  668. else if (location.hash === '#revision-history') {
  669. $('a[data-toggle="tab"][href="#revision-history"]').tab('show');
  670. }
  671. }
  672. else {
  673. $('a[data-toggle="tab"][href="#revision-body"]').tab('show');
  674. }
  675. });
  676. window.addEventListener('keydown', (event) => {
  677. const target = event.target;
  678. // ignore when target dom is input
  679. const inputPattern = /^input|textinput|textarea$/i;
  680. if (inputPattern.test(target.tagName) || target.isContentEditable) {
  681. return;
  682. }
  683. switch (event.key) {
  684. case 'e':
  685. if (!event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
  686. Crowi.handleKeyEHandler(event);
  687. }
  688. break;
  689. case 'c':
  690. if (!event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
  691. Crowi.handleKeyCHandler(event);
  692. }
  693. break;
  694. case '/':
  695. if (event.ctrlKey || event.metaKey) {
  696. Crowi.handleKeyCtrlSlashHandler(event);
  697. }
  698. break;
  699. default:
  700. }
  701. });
  702. // adjust min-height of page for print temporarily
  703. window.onbeforeprint = function() {
  704. $('#page-wrapper').css('min-height', '0px');
  705. };