crowi.js 27 KB

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