crowi.js 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  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. // TODO GW-2355 remove this after refactoring
  184. $('#create-page').on('shown.bs.modal', (e) => {
  185. // quick hack: replace from server side rendering "date" to client side "date"
  186. const today = new Date();
  187. const month = (`0${today.getMonth() + 1}`).slice(-2);
  188. const day = (`0${today.getDate()}`).slice(-2);
  189. const dateString = `${today.getFullYear()}/${month}/${day}`;
  190. $('#create-page-today .page-today-suffix').text(`/${dateString}/`);
  191. $('#create-page-today .page-today-input2').data('prefix', `/${dateString}/`);
  192. // focus
  193. $('#create-page-today .page-today-input2').eq(0).focus();
  194. });
  195. $('#create-page-today').submit(function(e) {
  196. let prefix1 = $('input.page-today-input1', this).data('prefix');
  197. let prefix2 = $('input.page-today-input2', this).data('prefix');
  198. const input1 = $('input.page-today-input1', this).val();
  199. const input2 = $('input.page-today-input2', this).val();
  200. if (input1 === '') {
  201. prefix1 = 'メモ';
  202. }
  203. if (input2 === '') {
  204. prefix2 = prefix2.slice(0, -1);
  205. }
  206. window.location.href = `${prefix1 + input1 + prefix2 + input2}#edit`;
  207. return false;
  208. });
  209. $('#create-page-under-tree').submit(function(e) {
  210. let name = $('input', this).val();
  211. if (!name.match(/^\//)) {
  212. name = `/${name}`;
  213. }
  214. if (name.match(/.+\/$/)) {
  215. name = name.substr(0, name.length - 1);
  216. }
  217. // TODO: remove by GW-2278
  218. window.location.href = `${pathUtils.encodePagePath(name)}#edit`;
  219. return false;
  220. });
  221. // rename
  222. $('#renamePage').on('shown.bs.modal', (e) => {
  223. $('#renamePage #newPageName').focus();
  224. $('#renamePage .msg').hide();
  225. });
  226. $('#renamePageForm').submit(function(e) {
  227. // create name-value map
  228. const nameValueMap = {};
  229. $(this).serializeArray().forEach((obj) => {
  230. nameValueMap[obj.name] = obj.value; // nameValueMap.new_path is renamed page path
  231. });
  232. nameValueMap.socketClientId = websocketContainer.getSocketClientId();
  233. $.ajax({
  234. type: 'POST',
  235. url: '/_api/pages.rename',
  236. data: nameValueMap,
  237. dataType: 'json',
  238. })
  239. .done((res) => {
  240. // error
  241. if (!res.ok) {
  242. const linkPath = pathUtils.normalizePath(nameValueMap.new_path);
  243. $('#renamePage .msg').hide();
  244. $(`#renamePage .msg-${res.code}`).show();
  245. $('#renamePage #linkToNewPage').html(`
  246. <a href="${linkPath}">${linkPath} <i class="icon-login"></i></a>
  247. `);
  248. }
  249. else {
  250. const page = res.page;
  251. window.location.href = `${page.path}?renamed=${pagePath}`;
  252. }
  253. });
  254. return false;
  255. });
  256. // empty trash
  257. $('#emptyTrash').on('shown.bs.modal', (e) => {
  258. $('#emptyTrash .msg').hide();
  259. });
  260. $('#empty-trash-form').submit((e) => {
  261. // create name-value map
  262. const nameValueMap = {};
  263. $('#empty-trash-form').serializeArray().forEach((obj) => {
  264. nameValueMap[obj.name] = obj.value;
  265. });
  266. $.ajax({
  267. type: 'DELETE',
  268. url: '/_api/v3/pages/empty-trash',
  269. data: nameValueMap,
  270. dataType: 'json',
  271. }).done((res) => {
  272. window.location.href = '/trash';
  273. }).fail((jqXHR, textStatus, errorThrown) => {
  274. $('#emptyTrash .msg').hide();
  275. $('#emptyTrash .msg-unknown').show();
  276. });
  277. return false;
  278. });
  279. // delete
  280. $('#deletePage').on('shown.bs.modal', (e) => {
  281. $('#deletePage .msg').hide();
  282. });
  283. $('#delete-page-form').submit((e) => {
  284. // create name-value map
  285. const nameValueMap = {};
  286. $('#delete-page-form').serializeArray().forEach((obj) => {
  287. nameValueMap[obj.name] = obj.value;
  288. });
  289. nameValueMap.socketClientId = websocketContainer.getSocketClientId();
  290. $.ajax({
  291. type: 'POST',
  292. url: '/_api/pages.remove',
  293. data: nameValueMap,
  294. dataType: 'json',
  295. }).done((res) => {
  296. // error
  297. if (!res.ok) {
  298. $('#deletePage .msg').hide();
  299. $(`#deletePage .msg-${res.code}`).show();
  300. }
  301. else {
  302. const page = res.page;
  303. window.location.href = page.path;
  304. }
  305. });
  306. return false;
  307. });
  308. // Put Back
  309. $('#putBackPage').on('shown.bs.modal', (e) => {
  310. $('#putBackPage .msg').hide();
  311. });
  312. $('#revert-delete-page-form').submit((e) => {
  313. $.ajax({
  314. type: 'POST',
  315. url: '/_api/pages.revertRemove',
  316. data: $('#revert-delete-page-form').serialize(),
  317. dataType: 'json',
  318. }).done((res) => {
  319. // error
  320. if (!res.ok) {
  321. $('#putBackPage .msg').hide();
  322. $(`#putBackPage .msg-${res.code}`).show();
  323. }
  324. else {
  325. const page = res.page;
  326. window.location.href = page.path;
  327. }
  328. });
  329. return false;
  330. });
  331. $('#unlink-page-form').submit((e) => {
  332. $.ajax({
  333. type: 'POST',
  334. url: '/_api/pages.unlink',
  335. data: $('#unlink-page-form').serialize(),
  336. dataType: 'json',
  337. })
  338. .done((res) => {
  339. if (!res.ok) {
  340. $('#delete-errors').html(`<i class="fa fa-times-circle"></i> ${res.error}`);
  341. $('#delete-errors').addClass('alert-danger');
  342. }
  343. else {
  344. window.location.href = `${res.path}?unlinked=true`;
  345. }
  346. });
  347. return false;
  348. });
  349. $('#create-portal-button').on('click', (e) => {
  350. $('a[data-toggle="tab"][href="#edit"]').tab('show');
  351. $('body').addClass('on-edit');
  352. $('body').addClass('builtin-editor');
  353. const path = $('.content-main').data('path');
  354. if (path !== '/' && $('.content-main').data('page-id') === '') {
  355. const upperPage = path.substr(0, path.length - 1);
  356. $.get('/_api/pages.get', { path: upperPage }, (res) => {
  357. if (res.ok && res.page) {
  358. $('#portal-warning-modal').modal('show');
  359. }
  360. });
  361. }
  362. });
  363. $('#portal-form-close').on('click', (e) => {
  364. $('#edit').removeClass('active');
  365. $('body').removeClass('on-edit');
  366. $('body').removeClass('builtin-editor');
  367. window.location.hash = '#';
  368. });
  369. if (pageId) {
  370. // for Crowi Template LangProcessor
  371. $('.template-create-button', $('#revision-body')).on('click', function() {
  372. const path = $(this).data('path');
  373. const templateId = $(this).data('template');
  374. const template = $(`#${templateId}`).html();
  375. const editorContainer = appContainer.getContainer('EditorContainer');
  376. editorContainer.saveDraft(path, template);
  377. window.location.href = `${path}#edit`;
  378. });
  379. if (!isSeen) {
  380. $.post('/_api/pages.seen', { page_id: pageId }, (res) => {
  381. // ignore unless response has error
  382. if (res.ok && res.seenUser) {
  383. $('#content-main').data('page-is-seen', 1);
  384. }
  385. });
  386. }
  387. // presentation
  388. let presentaionInitialized = false;
  389. const $b = $('body');
  390. $(document).on('click', '.toggle-presentation', function(e) {
  391. const $a = $(this);
  392. e.preventDefault();
  393. $b.toggleClass('overlay-on');
  394. if (!presentaionInitialized) {
  395. presentaionInitialized = true;
  396. $('<iframe />').attr({
  397. src: $a.attr('href'),
  398. }).appendTo($('#presentation-container'));
  399. }
  400. }).on('click', '.fullscreen-layer', () => {
  401. $b.toggleClass('overlay-on');
  402. });
  403. } // end if pageId
  404. // tab changing handling
  405. $('a[href="#revision-body"]').on('show.bs.tab', () => {
  406. appContainer.setState({ editorMode: null });
  407. });
  408. $('a[href="#edit"]').on('show.bs.tab', () => {
  409. appContainer.setState({ editorMode: 'builtin' });
  410. $('body').addClass('on-edit');
  411. $('body').addClass('builtin-editor');
  412. });
  413. $('a[href="#edit"]').on('hide.bs.tab', () => {
  414. $('body').removeClass('on-edit');
  415. $('body').removeClass('builtin-editor');
  416. });
  417. $('a[href="#hackmd"]').on('show.bs.tab', () => {
  418. appContainer.setState({ editorMode: 'hackmd' });
  419. $('body').addClass('on-edit');
  420. $('body').addClass('hackmd');
  421. });
  422. $('a[href="#hackmd"]').on('hide.bs.tab', () => {
  423. $('body').removeClass('on-edit');
  424. $('body').removeClass('hackmd');
  425. });
  426. // hash handling
  427. if (isSavedStatesOfTabChanges) {
  428. $('a[data-toggle="tab"][href="#revision-history"]').on('show.bs.tab', () => {
  429. window.location.hash = '#revision-history';
  430. window.history.replaceState('', 'History', '#revision-history');
  431. });
  432. $('a[data-toggle="tab"][href="#edit"]').on('show.bs.tab', () => {
  433. window.location.hash = '#edit';
  434. window.history.replaceState('', 'Edit', '#edit');
  435. });
  436. $('a[data-toggle="tab"][href="#hackmd"]').on('show.bs.tab', () => {
  437. window.location.hash = '#hackmd';
  438. window.history.replaceState('', 'HackMD', '#hackmd');
  439. });
  440. $('a[data-toggle="tab"][href="#revision-body"]').on('show.bs.tab', () => {
  441. // couln't solve https://github.com/weseek/crowi-plus/issues/119 completely -- 2017.07.03 Yuki Takei
  442. window.location.hash = '#';
  443. window.history.replaceState('', '', window.location.href);
  444. });
  445. }
  446. else {
  447. $('a[data-toggle="tab"][href="#revision-history"]').on('show.bs.tab', () => {
  448. window.history.replaceState('', 'History', '#revision-history');
  449. });
  450. $('a[data-toggle="tab"][href="#edit"]').on('show.bs.tab', () => {
  451. window.history.replaceState('', 'Edit', '#edit');
  452. });
  453. $('a[data-toggle="tab"][href="#hackmd"]').on('show.bs.tab', () => {
  454. window.history.replaceState('', 'HackMD', '#hackmd');
  455. });
  456. $('a[data-toggle="tab"][href="#revision-body"]').on('show.bs.tab', () => {
  457. window.history.replaceState('', '', window.location.href.replace(window.location.hash, ''));
  458. });
  459. // replace all href="#edit" link behaviors
  460. $(document).on('click', 'a[href="#edit"]', () => {
  461. window.location.replace('#edit');
  462. });
  463. }
  464. // focus to editor when 'shown.bs.tab' event fired
  465. $('a[href="#edit"]').on('shown.bs.tab', (e) => {
  466. Crowi.setCaretLineAndFocusToEditor();
  467. });
  468. });
  469. window.addEventListener('load', (e) => {
  470. const { appContainer } = window;
  471. // do nothing if user is guest
  472. if (appContainer.currentUser == null) {
  473. return;
  474. }
  475. // hash on page
  476. if (window.location.hash) {
  477. if ((window.location.hash === '#edit' || window.location.hash === '#edit-form') && $('.tab-pane#edit').length > 0) {
  478. appContainer.setState({ editorMode: 'builtin' });
  479. $('a[data-toggle="tab"][href="#edit"]').tab('show');
  480. $('body').addClass('on-edit');
  481. $('body').addClass('builtin-editor');
  482. // focus
  483. Crowi.setCaretLineAndFocusToEditor();
  484. }
  485. else if (window.location.hash === '#hackmd' && $('.tab-pane#hackmd').length > 0) {
  486. appContainer.setState({ editorMode: 'hackmd' });
  487. $('a[data-toggle="tab"][href="#hackmd"]').tab('show');
  488. $('body').addClass('on-edit');
  489. $('body').addClass('hackmd');
  490. }
  491. else if (window.location.hash === '#revision-history' && $('.tab-pane#revision-history').length > 0) {
  492. $('a[data-toggle="tab"][href="#revision-history"]').tab('show');
  493. }
  494. }
  495. });
  496. window.addEventListener('load', (e) => {
  497. const crowi = window.crowi;
  498. if (crowi && crowi.users && crowi.users.length !== 0) {
  499. const totalUsers = crowi.users.length;
  500. const $listLiker = $('.page-list-liker');
  501. $listLiker.each((i, liker) => {
  502. const count = $(liker).data('count') || 0;
  503. if (count / totalUsers > 0.05) {
  504. $(liker).addClass('popular-page-high');
  505. // 5%
  506. }
  507. else if (count / totalUsers > 0.02) {
  508. $(liker).addClass('popular-page-mid');
  509. // 2%
  510. }
  511. else if (count / totalUsers > 0.005) {
  512. $(liker).addClass('popular-page-low');
  513. // 0.5%
  514. }
  515. });
  516. const $listSeer = $('.page-list-seer');
  517. $listSeer.each((i, seer) => {
  518. const count = $(seer).data('count') || 0;
  519. if (count / totalUsers > 0.10) {
  520. // 10%
  521. $(seer).addClass('popular-page-high');
  522. }
  523. else if (count / totalUsers > 0.05) {
  524. // 5%
  525. $(seer).addClass('popular-page-mid');
  526. }
  527. else if (count / totalUsers > 0.02) {
  528. // 2%
  529. $(seer).addClass('popular-page-low');
  530. }
  531. });
  532. }
  533. Crowi.highlightSelectedSection(window.location.hash);
  534. Crowi.modifyScrollTop();
  535. Crowi.initClassesByOS();
  536. });
  537. window.addEventListener('hashchange', (e) => {
  538. Crowi.unhighlightSelectedSection(Crowi.findHashFromUrl(e.oldURL));
  539. Crowi.highlightSelectedSection(Crowi.findHashFromUrl(e.newURL));
  540. Crowi.modifyScrollTop();
  541. // hash on page
  542. if (window.location.hash) {
  543. if (window.location.hash === '#edit') {
  544. $('a[data-toggle="tab"][href="#edit"]').tab('show');
  545. }
  546. else if (window.location.hash === '#hackmd') {
  547. $('a[data-toggle="tab"][href="#hackmd"]').tab('show');
  548. }
  549. else if (window.location.hash === '#revision-history') {
  550. $('a[data-toggle="tab"][href="#revision-history"]').tab('show');
  551. }
  552. }
  553. else {
  554. $('a[data-toggle="tab"][href="#revision-body"]').tab('show');
  555. }
  556. });
  557. window.addEventListener('keydown', (event) => {
  558. const target = event.target;
  559. // ignore when target dom is input
  560. const inputPattern = /^input|textinput|textarea$/i;
  561. if (inputPattern.test(target.tagName) || target.isContentEditable) {
  562. return;
  563. }
  564. switch (event.key) {
  565. case 'e':
  566. if (!event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
  567. Crowi.handleKeyEHandler(event);
  568. }
  569. break;
  570. case 'c':
  571. if (!event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
  572. Crowi.handleKeyCHandler(event);
  573. }
  574. break;
  575. case '/':
  576. if (event.ctrlKey || event.metaKey) {
  577. Crowi.handleKeyCtrlSlashHandler(event);
  578. }
  579. break;
  580. default:
  581. }
  582. });
  583. // adjust min-height of page for print temporarily
  584. window.onbeforeprint = function() {
  585. $('#page-wrapper').css('min-height', '0px');
  586. };