crowi.js 24 KB

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