crowi.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. /* eslint-disable react/jsx-filename-extension */
  2. import { pathUtils } from 'growi-commons';
  3. require('jquery.cookie');
  4. require('./thirdparty-js/waves');
  5. const Crowi = {};
  6. if (!window) {
  7. window = {};
  8. }
  9. window.Crowi = Crowi;
  10. /**
  11. * set 'data-caret-line' attribute that will be processed when 'shown.bs.tab' event fired
  12. * @param {number} line
  13. */
  14. Crowi.setCaretLineData = function(line) {
  15. const pageEditorDom = document.querySelector('#page-editor');
  16. pageEditorDom.setAttribute('data-caret-line', line);
  17. };
  18. /**
  19. * invoked when;
  20. *
  21. * 1. 'shown.bs.tab' event fired
  22. */
  23. Crowi.setCaretLineAndFocusToEditor = function() {
  24. // get 'data-caret-line' attributes
  25. const pageEditorDom = document.querySelector('#page-editor');
  26. if (pageEditorDom == null) {
  27. return;
  28. }
  29. const { appContainer } = window;
  30. const editorContainer = appContainer.getContainer('EditorContainer');
  31. const line = pageEditorDom.getAttribute('data-caret-line') || 0;
  32. editorContainer.setCaretLine(+line);
  33. // reset data-caret-line attribute
  34. pageEditorDom.removeAttribute('data-caret-line');
  35. // focus
  36. editorContainer.focusToEditor();
  37. };
  38. // original: middleware.swigFilter
  39. Crowi.userPicture = function(user) {
  40. if (!user) {
  41. return '/images/icons/user.svg';
  42. }
  43. return user.image || '/images/icons/user.svg';
  44. };
  45. Crowi.modifyScrollTop = function() {
  46. const offset = 10;
  47. const hash = window.location.hash;
  48. if (hash === '') {
  49. return;
  50. }
  51. const pageHeader = document.querySelector('#page-header');
  52. if (!pageHeader) {
  53. return;
  54. }
  55. const pageHeaderRect = pageHeader.getBoundingClientRect();
  56. const sectionHeader = Crowi.findSectionHeader(hash);
  57. if (sectionHeader === null) {
  58. return;
  59. }
  60. let timeout = 0;
  61. if (window.scrollY === 0) {
  62. timeout = 200;
  63. }
  64. setTimeout(() => {
  65. const sectionHeaderRect = sectionHeader.getBoundingClientRect();
  66. if (sectionHeaderRect.top >= pageHeaderRect.bottom) {
  67. return;
  68. }
  69. window.scrollTo(0, (window.scrollY - pageHeaderRect.height - offset));
  70. }, timeout);
  71. };
  72. Crowi.handleKeyEHandler = (event) => {
  73. // ignore when dom that has 'modal in' classes exists
  74. if (document.getElementsByClassName('modal in').length > 0) {
  75. return;
  76. }
  77. // show editor
  78. $('a[data-toggle="tab"][href="#edit"]').tab('show');
  79. event.preventDefault();
  80. };
  81. Crowi.handleKeyCHandler = (event) => {
  82. // ignore when dom that has 'modal in' classes exists
  83. if (document.getElementsByClassName('modal in').length > 0) {
  84. return;
  85. }
  86. // show modal to create a page
  87. $('#create-page').modal();
  88. event.preventDefault();
  89. };
  90. Crowi.handleKeyCtrlSlashHandler = (event) => {
  91. // show modal to create a page
  92. $('#shortcuts-modal').modal('toggle');
  93. event.preventDefault();
  94. };
  95. Crowi.initClassesByOS = function() {
  96. // add classes to cmd-key by OS
  97. const platform = navigator.platform.toLowerCase();
  98. const isMac = (platform.indexOf('mac') > -1);
  99. document.querySelectorAll('.system-version .cmd-key').forEach((element) => {
  100. if (isMac) {
  101. element.classList.add('mac');
  102. }
  103. else {
  104. element.classList.add('win');
  105. }
  106. });
  107. document.querySelectorAll('#shortcuts-modal .cmd-key').forEach((element) => {
  108. if (isMac) {
  109. element.classList.add('mac');
  110. }
  111. else {
  112. element.classList.add('win', 'key-longer');
  113. }
  114. });
  115. };
  116. Crowi.findHashFromUrl = function(url) {
  117. let match;
  118. /* eslint-disable no-cond-assign */
  119. if (match = url.match(/#(.+)$/)) {
  120. return `#${match[1]}`;
  121. }
  122. /* eslint-enable no-cond-assign */
  123. return '';
  124. };
  125. Crowi.findSectionHeader = function(hash) {
  126. if (hash.length === 0) {
  127. return;
  128. }
  129. // omit '#'
  130. const id = hash.replace('#', '');
  131. // don't use jQuery and document.querySelector
  132. // because hash may containe Base64 encoded strings
  133. const elem = document.getElementById(id);
  134. if (elem != null && elem.tagName.match(/h\d+/i)) { // match h1, h2, h3...
  135. return elem;
  136. }
  137. return null;
  138. };
  139. Crowi.unhighlightSelectedSection = function(hash) {
  140. const elem = Crowi.findSectionHeader(hash);
  141. if (elem != null) {
  142. elem.classList.remove('highlighted');
  143. }
  144. };
  145. Crowi.highlightSelectedSection = function(hash) {
  146. const elem = Crowi.findSectionHeader(hash);
  147. if (elem != null) {
  148. elem.classList.add('highlighted');
  149. }
  150. };
  151. $(() => {
  152. const appContainer = window.appContainer;
  153. const websocketContainer = appContainer.getContainer('WebsocketContainer');
  154. const config = appContainer.getConfig();
  155. const pageId = $('#content-main').data('page-id');
  156. // const revisionId = $('#content-main').data('page-revision-id');
  157. // const revisionCreatedAt = $('#content-main').data('page-revision-created');
  158. // const currentUser = $('#content-main').data('current-user');
  159. const isSeen = $('#content-main').data('page-is-seen');
  160. const pagePath = $('#content-main').data('path');
  161. const isSavedStatesOfTabChanges = config.isSavedStatesOfTabChanges;
  162. $('[data-toggle="popover"]').popover();
  163. $('[data-toggle="tooltip"]').tooltip();
  164. $('[data-tooltip-stay]').tooltip('show');
  165. $('#toggle-crowi-sidebar').click((e) => {
  166. const $body = $('body');
  167. if ($body.hasClass('aside-hidden')) {
  168. $body.removeClass('aside-hidden');
  169. $.cookie('aside-hidden', 0, { expires: 30, path: '/' });
  170. }
  171. else {
  172. $body.addClass('aside-hidden');
  173. $.cookie('aside-hidden', 1, { expires: 30, path: '/' });
  174. }
  175. return false;
  176. });
  177. if ($.cookie('aside-hidden') === 1) {
  178. $('body').addClass('aside-hidden');
  179. }
  180. $('.copy-link').on('click', function() {
  181. $(this).select();
  182. });
  183. // rename
  184. $('#renamePage').on('shown.bs.modal', (e) => {
  185. $('#renamePage #newPageName').focus();
  186. $('#renamePage .msg').hide();
  187. });
  188. $('#renamePageForm').submit(function(e) {
  189. // create name-value map
  190. const nameValueMap = {};
  191. $(this).serializeArray().forEach((obj) => {
  192. nameValueMap[obj.name] = obj.value; // nameValueMap.new_path is renamed page path
  193. });
  194. nameValueMap.socketClientId = websocketContainer.getSocketClientId();
  195. $.ajax({
  196. type: 'POST',
  197. url: '/_api/pages.rename',
  198. data: nameValueMap,
  199. dataType: 'json',
  200. })
  201. .done((res) => {
  202. // error
  203. if (!res.ok) {
  204. const linkPath = pathUtils.normalizePath(nameValueMap.new_path);
  205. $('#renamePage .msg').hide();
  206. $(`#renamePage .msg-${res.code}`).show();
  207. $('#renamePage #linkToNewPage').html(`
  208. <a href="${linkPath}">${linkPath} <i class="icon-login"></i></a>
  209. `);
  210. }
  211. else {
  212. const page = res.page;
  213. window.location.href = `${page.path}?renamed=${pagePath}`;
  214. }
  215. });
  216. return false;
  217. });
  218. // empty trash
  219. $('#emptyTrash').on('shown.bs.modal', (e) => {
  220. $('#emptyTrash .msg').hide();
  221. });
  222. $('#empty-trash-form').submit((e) => {
  223. // create name-value map
  224. const nameValueMap = {};
  225. $('#empty-trash-form').serializeArray().forEach((obj) => {
  226. nameValueMap[obj.name] = obj.value;
  227. });
  228. $.ajax({
  229. type: 'DELETE',
  230. url: '/_api/v3/pages/empty-trash',
  231. data: nameValueMap,
  232. dataType: 'json',
  233. }).done((res) => {
  234. window.location.href = '/trash';
  235. }).fail((jqXHR, textStatus, errorThrown) => {
  236. $('#emptyTrash .msg').hide();
  237. $('#emptyTrash .msg-unknown').show();
  238. });
  239. return false;
  240. });
  241. // Put Back
  242. $('#putBackPage').on('shown.bs.modal', (e) => {
  243. $('#putBackPage .msg').hide();
  244. });
  245. $('#revert-delete-page-form').submit((e) => {
  246. $.ajax({
  247. type: 'POST',
  248. url: '/_api/pages.revertRemove',
  249. data: $('#revert-delete-page-form').serialize(),
  250. dataType: 'json',
  251. }).done((res) => {
  252. // error
  253. if (!res.ok) {
  254. $('#putBackPage .msg').hide();
  255. $(`#putBackPage .msg-${res.code}`).show();
  256. }
  257. else {
  258. const page = res.page;
  259. window.location.href = page.path;
  260. }
  261. });
  262. return false;
  263. });
  264. $('#create-portal-button').on('click', (e) => {
  265. $('a[data-toggle="tab"][href="#edit"]').tab('show');
  266. $('body').addClass('on-edit');
  267. $('body').addClass('builtin-editor');
  268. const path = $('.content-main').data('path');
  269. if (path !== '/' && $('.content-main').data('page-id') === '') {
  270. const upperPage = path.substr(0, path.length - 1);
  271. $.get('/_api/pages.get', { path: upperPage }, (res) => {
  272. if (res.ok && res.page) {
  273. $('#portal-warning-modal').modal('show');
  274. }
  275. });
  276. }
  277. });
  278. $('#portal-form-close').on('click', (e) => {
  279. $('#edit').removeClass('active');
  280. $('body').removeClass('on-edit');
  281. $('body').removeClass('builtin-editor');
  282. window.location.hash = '#';
  283. });
  284. if (pageId) {
  285. // for Crowi Template LangProcessor
  286. $('.template-create-button', $('#revision-body')).on('click', function() {
  287. const path = $(this).data('path');
  288. const templateId = $(this).data('template');
  289. const template = $(`#${templateId}`).html();
  290. const editorContainer = appContainer.getContainer('EditorContainer');
  291. editorContainer.saveDraft(path, template);
  292. window.location.href = `${path}#edit`;
  293. });
  294. if (!isSeen) {
  295. $.post('/_api/pages.seen', { page_id: pageId }, (res) => {
  296. // ignore unless response has error
  297. if (res.ok && res.seenUser) {
  298. $('#content-main').data('page-is-seen', 1);
  299. }
  300. });
  301. }
  302. // presentation
  303. let presentaionInitialized = false;
  304. const $b = $('body');
  305. $(document).on('click', '.toggle-presentation', function(e) {
  306. const $a = $(this);
  307. e.preventDefault();
  308. $b.toggleClass('overlay-on');
  309. if (!presentaionInitialized) {
  310. presentaionInitialized = true;
  311. $('<iframe />').attr({
  312. src: $a.attr('href'),
  313. }).appendTo($('#presentation-container'));
  314. }
  315. }).on('click', '.fullscreen-layer', () => {
  316. $b.toggleClass('overlay-on');
  317. });
  318. } // end if pageId
  319. // tab changing handling
  320. $('a[href="#revision-body"]').on('show.bs.tab', () => {
  321. appContainer.setState({ editorMode: null });
  322. });
  323. $('a[href="#edit"]').on('show.bs.tab', () => {
  324. appContainer.setState({ editorMode: 'builtin' });
  325. $('body').addClass('on-edit');
  326. $('body').addClass('builtin-editor');
  327. });
  328. $('a[href="#edit"]').on('hide.bs.tab', () => {
  329. $('body').removeClass('on-edit');
  330. $('body').removeClass('builtin-editor');
  331. });
  332. $('a[href="#hackmd"]').on('show.bs.tab', () => {
  333. appContainer.setState({ editorMode: 'hackmd' });
  334. $('body').addClass('on-edit');
  335. $('body').addClass('hackmd');
  336. });
  337. $('a[href="#hackmd"]').on('hide.bs.tab', () => {
  338. $('body').removeClass('on-edit');
  339. $('body').removeClass('hackmd');
  340. });
  341. // hash handling
  342. if (isSavedStatesOfTabChanges) {
  343. $('a[data-toggle="tab"][href="#revision-history"]').on('show.bs.tab', () => {
  344. window.location.hash = '#revision-history';
  345. window.history.replaceState('', 'History', '#revision-history');
  346. });
  347. $('a[data-toggle="tab"][href="#edit"]').on('show.bs.tab', () => {
  348. window.location.hash = '#edit';
  349. window.history.replaceState('', 'Edit', '#edit');
  350. });
  351. $('a[data-toggle="tab"][href="#hackmd"]').on('show.bs.tab', () => {
  352. window.location.hash = '#hackmd';
  353. window.history.replaceState('', 'HackMD', '#hackmd');
  354. });
  355. $('a[data-toggle="tab"][href="#revision-body"]').on('show.bs.tab', () => {
  356. // couln't solve https://github.com/weseek/crowi-plus/issues/119 completely -- 2017.07.03 Yuki Takei
  357. window.location.hash = '#';
  358. window.history.replaceState('', '', window.location.href);
  359. });
  360. }
  361. else {
  362. $('a[data-toggle="tab"][href="#revision-history"]').on('show.bs.tab', () => {
  363. window.history.replaceState('', 'History', '#revision-history');
  364. });
  365. $('a[data-toggle="tab"][href="#edit"]').on('show.bs.tab', () => {
  366. window.history.replaceState('', 'Edit', '#edit');
  367. });
  368. $('a[data-toggle="tab"][href="#hackmd"]').on('show.bs.tab', () => {
  369. window.history.replaceState('', 'HackMD', '#hackmd');
  370. });
  371. $('a[data-toggle="tab"][href="#revision-body"]').on('show.bs.tab', () => {
  372. window.history.replaceState('', '', window.location.href.replace(window.location.hash, ''));
  373. });
  374. // replace all href="#edit" link behaviors
  375. $(document).on('click', 'a[href="#edit"]', () => {
  376. window.location.replace('#edit');
  377. });
  378. }
  379. // focus to editor when 'shown.bs.tab' event fired
  380. $('a[href="#edit"]').on('shown.bs.tab', (e) => {
  381. Crowi.setCaretLineAndFocusToEditor();
  382. });
  383. });
  384. window.addEventListener('load', (e) => {
  385. const { appContainer } = window;
  386. // do nothing if user is guest
  387. if (appContainer.currentUser == null) {
  388. return;
  389. }
  390. // hash on page
  391. if (window.location.hash) {
  392. if ((window.location.hash === '#edit' || window.location.hash === '#edit-form') && $('.tab-pane#edit').length > 0) {
  393. appContainer.setState({ editorMode: 'builtin' });
  394. $('a[data-toggle="tab"][href="#edit"]').tab('show');
  395. $('body').addClass('on-edit');
  396. $('body').addClass('builtin-editor');
  397. // focus
  398. Crowi.setCaretLineAndFocusToEditor();
  399. }
  400. else if (window.location.hash === '#hackmd' && $('.tab-pane#hackmd').length > 0) {
  401. appContainer.setState({ editorMode: 'hackmd' });
  402. $('a[data-toggle="tab"][href="#hackmd"]').tab('show');
  403. $('body').addClass('on-edit');
  404. $('body').addClass('hackmd');
  405. }
  406. else if (window.location.hash === '#revision-history' && $('.tab-pane#revision-history').length > 0) {
  407. $('a[data-toggle="tab"][href="#revision-history"]').tab('show');
  408. }
  409. }
  410. });
  411. window.addEventListener('load', (e) => {
  412. const crowi = window.crowi;
  413. if (crowi && crowi.users && crowi.users.length !== 0) {
  414. const totalUsers = crowi.users.length;
  415. const $listLiker = $('.page-list-liker');
  416. $listLiker.each((i, liker) => {
  417. const count = $(liker).data('count') || 0;
  418. if (count / totalUsers > 0.05) {
  419. $(liker).addClass('popular-page-high');
  420. // 5%
  421. }
  422. else if (count / totalUsers > 0.02) {
  423. $(liker).addClass('popular-page-mid');
  424. // 2%
  425. }
  426. else if (count / totalUsers > 0.005) {
  427. $(liker).addClass('popular-page-low');
  428. // 0.5%
  429. }
  430. });
  431. const $listSeer = $('.page-list-seer');
  432. $listSeer.each((i, seer) => {
  433. const count = $(seer).data('count') || 0;
  434. if (count / totalUsers > 0.10) {
  435. // 10%
  436. $(seer).addClass('popular-page-high');
  437. }
  438. else if (count / totalUsers > 0.05) {
  439. // 5%
  440. $(seer).addClass('popular-page-mid');
  441. }
  442. else if (count / totalUsers > 0.02) {
  443. // 2%
  444. $(seer).addClass('popular-page-low');
  445. }
  446. });
  447. }
  448. Crowi.highlightSelectedSection(window.location.hash);
  449. Crowi.modifyScrollTop();
  450. Crowi.initClassesByOS();
  451. });
  452. window.addEventListener('hashchange', (e) => {
  453. Crowi.unhighlightSelectedSection(Crowi.findHashFromUrl(e.oldURL));
  454. Crowi.highlightSelectedSection(Crowi.findHashFromUrl(e.newURL));
  455. Crowi.modifyScrollTop();
  456. // hash on page
  457. if (window.location.hash) {
  458. if (window.location.hash === '#edit') {
  459. $('a[data-toggle="tab"][href="#edit"]').tab('show');
  460. }
  461. else if (window.location.hash === '#hackmd') {
  462. $('a[data-toggle="tab"][href="#hackmd"]').tab('show');
  463. }
  464. else if (window.location.hash === '#revision-history') {
  465. $('a[data-toggle="tab"][href="#revision-history"]').tab('show');
  466. }
  467. }
  468. else {
  469. $('a[data-toggle="tab"][href="#revision-body"]').tab('show');
  470. }
  471. });
  472. window.addEventListener('keydown', (event) => {
  473. const target = event.target;
  474. // ignore when target dom is input
  475. const inputPattern = /^input|textinput|textarea$/i;
  476. if (inputPattern.test(target.tagName) || target.isContentEditable) {
  477. return;
  478. }
  479. switch (event.key) {
  480. case 'e':
  481. if (!event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
  482. Crowi.handleKeyEHandler(event);
  483. }
  484. break;
  485. case 'c':
  486. if (!event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
  487. Crowi.handleKeyCHandler(event);
  488. }
  489. break;
  490. case '/':
  491. if (event.ctrlKey || event.metaKey) {
  492. Crowi.handleKeyCtrlSlashHandler(event);
  493. }
  494. break;
  495. default:
  496. }
  497. });
  498. // adjust min-height of page for print temporarily
  499. window.onbeforeprint = function() {
  500. $('#page-wrapper').css('min-height', '0px');
  501. };