crowi.js 28 KB

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