crowi.js 28 KB

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