crowi.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929
  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/icons/user.svg';
  79. }
  80. return user.image || '/images/icons/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. // focus
  173. $('#create-page-today .page-today-input2').eq(0).focus();
  174. });
  175. $('#create-page-today').submit(function(e) {
  176. var prefix1 = $('input.page-today-input1', this).data('prefix');
  177. var input1 = $('input.page-today-input1', this).val();
  178. var prefix2 = $('input.page-today-input2', this).data('prefix');
  179. var input2 = $('input.page-today-input2', this).val();
  180. if (input1 === '') {
  181. prefix1 = 'メモ';
  182. }
  183. if (input2 === '') {
  184. prefix2 = prefix2.slice(0, -1);
  185. }
  186. top.location.href = prefix1 + input1 + prefix2 + input2 + '#edit-form';
  187. return false;
  188. });
  189. $('#create-page-under-tree').submit(function(e) {
  190. var name = $('input', this).val();
  191. if (!name.match(/^\//)) {
  192. name = '/' + name;
  193. }
  194. if (name.match(/.+\/$/)) {
  195. name = name.substr(0, name.length - 1);
  196. }
  197. var names = name.split('/');
  198. names.forEach(function(item, index) {
  199. names[index] = encodeURIComponent(item);
  200. });
  201. top.location.href = names.join('/') + '#edit-form';
  202. return false;
  203. });
  204. // rename
  205. $('#renamePage').on('shown.bs.modal', function (e) {
  206. $('#renamePage #newPageName').focus();
  207. $('#renamePage .msg-already-exists').hide();
  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. $('#renamePage .msg-already-exists').show();
  224. $('#renamePage #linkToNewPage').html(`
  225. <a href="${nameValueMap.new_path}">${nameValueMap.new_path} <i class="icon-login"></i></a>
  226. `);
  227. }
  228. else {
  229. var page = res.page;
  230. top.location.href = page.path + '?renamed=' + pagePath;
  231. }
  232. });
  233. return false;
  234. });
  235. // duplicate
  236. $('#duplicatePage').on('shown.bs.modal', function (e) {
  237. $('#duplicatePage #duplicatePageName').focus();
  238. $('#duplicatePage .msg-already-exists').hide();
  239. });
  240. $('#duplicatePageForm, #unportalize-form').submit(function (e) {
  241. // create name-value map
  242. let nameValueMap = {};
  243. $(this).serializeArray().forEach((obj) => {
  244. nameValueMap[obj.name] = obj.value;
  245. })
  246. $.ajax({
  247. type: 'POST',
  248. url: '/_api/pages.duplicate',
  249. data: $(this).serialize(),
  250. dataType: 'json'
  251. }).done(function(res) {
  252. if (!res.ok) {
  253. // if already exists
  254. $('#duplicatePage .msg-already-exists').show();
  255. $('#duplicatePage #linkToNewPage').html(`
  256. <a href="${nameValueMap.new_path}">${nameValueMap.new_path} <i class="icon-login"></i></a>
  257. `);
  258. }
  259. else {
  260. var page = res.page;
  261. top.location.href = page.path + '?duplicated=' + pagePath;
  262. }
  263. });
  264. return false;
  265. });
  266. // delete
  267. $('#delete-page-form').submit(function(e) {
  268. $.ajax({
  269. type: 'POST',
  270. url: '/_api/pages.remove',
  271. data: $('#delete-page-form').serialize(),
  272. dataType: 'json'
  273. }).done(function(res) {
  274. if (!res.ok) {
  275. $('#delete-errors').html('<i class="fa fa-times-circle"></i> ' + res.error);
  276. $('#delete-errors').addClass('alert-danger');
  277. } else {
  278. var page = res.page;
  279. top.location.href = page.path;
  280. }
  281. });
  282. return false;
  283. });
  284. $('#revert-delete-page-form').submit(function(e) {
  285. $.ajax({
  286. type: 'POST',
  287. url: '/_api/pages.revertRemove',
  288. data: $('#revert-delete-page-form').serialize(),
  289. dataType: 'json'
  290. }).done(function(res) {
  291. if (!res.ok) {
  292. $('#delete-errors').html('<i class="fa fa-times-circle"></i> ' + res.error);
  293. $('#delete-errors').addClass('alert-danger');
  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. }).done(function(res) {
  308. if (!res.ok) {
  309. $('#delete-errors').html('<i class="fa fa-times-circle"></i> ' + res.error);
  310. $('#delete-errors').addClass('alert-danger');
  311. } else {
  312. var page = res.page;
  313. top.location.href = page.path + '?unlinked=true';
  314. }
  315. });
  316. return false;
  317. });
  318. $('#create-portal-button').on('click', function(e) {
  319. $('body').addClass('on-edit');
  320. var path = $('.content-main').data('path');
  321. if (path != '/' && $('.content-main').data('page-id') == '') {
  322. var upperPage = path.substr(0, path.length - 1);
  323. $.get('/_api/pages.get', {path: upperPage}, function(res) {
  324. if (res.ok && res.page) {
  325. $('#portal-warning-modal').modal('show');
  326. }
  327. });
  328. }
  329. });
  330. $('#portal-form-close').on('click', function(e) {
  331. $('body').removeClass('on-edit');
  332. return false;
  333. });
  334. /*
  335. * wrap short path with <strong></strong>
  336. */
  337. $('.page-list-link').each(function() {
  338. var $link = $(this);
  339. var text = $link.text();
  340. var path = $link.data('path');
  341. var shortPath = String($link.data('short-path')); // convert to string
  342. if (path == null || shortPath == null) {
  343. // continue
  344. return;
  345. }
  346. path = entities.encodeHTML(path);
  347. var pattern = escapeStringRegexp(entities.encodeHTML(shortPath)) + '(/)?$';
  348. $link.html(path.replace(new RegExp(pattern), '<strong>' + shortPath + '$1</strong>'));
  349. });
  350. // for list page
  351. let growiRendererForTimeline = null;
  352. $('a[data-toggle="tab"][href="#view-timeline"]').on('show.bs.tab', function() {
  353. var isShown = $('#view-timeline').data('shown');
  354. if (growiRendererForTimeline == null) {
  355. growiRendererForTimeline = new GrowiRenderer(crowi, crowiRenderer, {mode: 'timeline'});
  356. }
  357. if (isShown == 0) {
  358. $('#view-timeline .timeline-body').each(function()
  359. {
  360. var id = $(this).attr('id');
  361. var contentId = '#' + id + ' > script';
  362. var revisionBody = '#' + id + ' .revision-body';
  363. var revisionBodyElem = document.querySelector(revisionBody);
  364. var revisionPath = '#' + id + ' .revision-path';
  365. var pagePath = document.getElementById(id).getAttribute('data-page-path');
  366. var markdown = entities.decodeHTML($(contentId).html());
  367. ReactDOM.render(<Page crowi={crowi} crowiRenderer={growiRendererForTimeline} markdown={markdown} pagePath={pagePath} />, revisionBodyElem);
  368. });
  369. $('#view-timeline').data('shown', 1);
  370. }
  371. });
  372. if (pageId) {
  373. // for Crowi Template LangProcessor
  374. $('.template-create-button', $('#revision-body')).on('click', function() {
  375. var path = $(this).data('path');
  376. var templateId = $(this).data('template');
  377. var template = $('#' + templateId).html();
  378. crowi.saveDraft(path, template);
  379. top.location.href = `${path}#edit-form`;
  380. });
  381. /*
  382. * transplanted to React components -- 2018.02.04 Yuki Takei
  383. *
  384. // if page exists
  385. var $rawTextOriginal = $('#raw-text-original');
  386. if ($rawTextOriginal.length > 0) {
  387. var markdown = entities.decodeHTML($('#raw-text-original').html());
  388. var dom = $('#revision-body-content').get(0);
  389. // create context object
  390. var context = {
  391. markdown,
  392. dom,
  393. currentPagePath: decodeURIComponent(location.pathname)
  394. };
  395. crowi.interceptorManager.process('preRender', context)
  396. .then(() => crowi.interceptorManager.process('prePreProcess', context))
  397. .then(() => {
  398. context.markdown = crowiRenderer.preProcess(context.markdown);
  399. })
  400. .then(() => crowi.interceptorManager.process('postPreProcess', context))
  401. .then(() => {
  402. var revisionBody = $('#revision-body-content');
  403. var parsedHTML = crowiRenderer.render(context.markdown, context.dom);
  404. context.parsedHTML = parsedHTML;
  405. Promise.resolve(context);
  406. })
  407. .then(() => crowi.interceptorManager.process('postRender', context))
  408. .then(() => crowi.interceptorManager.process('preRenderHtml', context))
  409. // render HTML with jQuery
  410. .then(() => {
  411. $('#revision-body-content').html(context.parsedHTML);
  412. $('.template-create-button').on('click', function() {
  413. var path = $(this).data('path');
  414. var templateId = $(this).data('template');
  415. var template = $('#' + templateId).html();
  416. crowi.saveDraft(path, template);
  417. top.location.href = path;
  418. });
  419. Crowi.appendEditSectionButtons('#revision-body-content', markdown);
  420. Promise.resolve($('#revision-body-content'));
  421. })
  422. // process interceptors for post rendering
  423. .then((bodyElement) => {
  424. context = Object.assign(context, {bodyElement})
  425. return crowi.interceptorManager.process('postRenderHtml', context);
  426. });
  427. }
  428. */
  429. // header affix
  430. var $affixContent = $('#page-header');
  431. if ($affixContent.length > 0) {
  432. var $affixContentContainer = $('.row.bg-title');
  433. var containerHeight = $affixContentContainer.outerHeight(true);
  434. // fix height(固定)
  435. $affixContentContainer.css({height: containerHeight + 'px'});
  436. $affixContent.affix({
  437. offset: {
  438. top: function() {
  439. return $('.navbar').outerHeight(true) + containerHeight;
  440. }
  441. }
  442. });
  443. $('[data-affix-disable]').on('click', function(e) {
  444. var $elm = $($(this).data('affix-disable'));
  445. $(window).off('.affix');
  446. $elm.removeData('affix').removeClass('affix affix-top affix-bottom');
  447. return false;
  448. });
  449. }
  450. /*
  451. * transplanted to React components -- 2017.06.02 Yuki Takei
  452. *
  453. // omg
  454. function createCommentHTML(revision, creator, comment, commentedAt) {
  455. var $comment = $('<div>');
  456. var $commentImage = $('<img class="picture img-circle">')
  457. .attr('src', Crowi.userPicture(creator));
  458. var $commentCreator = $('<div class="page-comment-creator">')
  459. .text(creator.username);
  460. var $commentRevision = $('<a class="page-comment-revision label">')
  461. .attr('href', '?revision=' + revision)
  462. .text(revision.substr(0,8));
  463. if (revision !== revisionId) {
  464. $commentRevision.addClass('label-default');
  465. } else {
  466. $commentRevision.addClass('label-primary');
  467. }
  468. var $commentMeta = $('<div class="page-comment-meta">')
  469. //日付変換
  470. .text(moment(commentedAt).format('YYYY/MM/DD HH:mm:ss') + ' ')
  471. .append($commentRevision);
  472. var $commentBody = $('<div class="page-comment-body">')
  473. .html(comment.replace(/(\r\n|\r|\n)/g, '<br>'));
  474. var $commentMain = $('<div class="page-comment-main">')
  475. .append($commentCreator)
  476. .append($commentBody)
  477. .append($commentMeta)
  478. $comment.addClass('page-comment');
  479. if (creator._id === currentUser) {
  480. $comment.addClass('page-comment-me');
  481. }
  482. if (revision !== revisionId) {
  483. $comment.addClass('page-comment-old');
  484. }
  485. $comment
  486. .append($commentImage)
  487. .append($commentMain);
  488. return $comment;
  489. }
  490. // get comments
  491. var $pageCommentList = $('.page-comments-list');
  492. var $pageCommentListNewer = $('#page-comments-list-newer');
  493. var $pageCommentListCurrent = $('#page-comments-list-current');
  494. var $pageCommentListOlder = $('#page-comments-list-older');
  495. var hasNewer = false;
  496. var hasOlder = false;
  497. $.get('/_api/comments.get', {page_id: pageId}, function(res) {
  498. if (res.ok) {
  499. var comments = res.comments;
  500. $.each(comments, function(i, comment) {
  501. var commentContent = createCommentHTML(comment.revision, comment.creator, comment.comment, comment.createdAt);
  502. if (comment.revision == revisionId) {
  503. $pageCommentListCurrent.append(commentContent);
  504. } else {
  505. if (Date.parse(comment.createdAt)/1000 > revisionCreatedAt) {
  506. $pageCommentListNewer.append(commentContent);
  507. hasNewer = true;
  508. } else {
  509. $pageCommentListOlder.append(commentContent);
  510. hasOlder = true;
  511. }
  512. }
  513. });
  514. }
  515. }).fail(function(data) {
  516. }).always(function() {
  517. if (!hasNewer) {
  518. $('.page-comments-list-toggle-newer').hide();
  519. }
  520. if (!hasOlder) {
  521. $pageCommentListOlder.addClass('collapse');
  522. $('.page-comments-list-toggle-older').hide();
  523. }
  524. });
  525. // post comment event
  526. $('#page-comment-form').on('submit', function() {
  527. var $button = $('#comment-form-button');
  528. $button.attr('disabled', 'disabled');
  529. $.post('/_api/comments.add', $(this).serialize(), function(data) {
  530. $button.prop('disabled', false);
  531. if (data.ok) {
  532. var comment = data.comment;
  533. $pageCommentList.prepend(createCommentHTML(comment.revision, comment.creator, comment.comment, comment.createdAt));
  534. $('#comment-form-comment').val('');
  535. $('#comment-form-message').text('');
  536. } else {
  537. $('#comment-form-message').text(data.error);
  538. }
  539. }).fail(function(data) {
  540. if (data.status !== 200) {
  541. $('#comment-form-message').text(data.statusText);
  542. }
  543. });
  544. return false;
  545. });
  546. */
  547. // Like
  548. var $likeButton = $('.like-button');
  549. var $likeCount = $('#like-count');
  550. $likeButton.click(function() {
  551. var liked = $likeButton.data('liked');
  552. var token = $likeButton.data('csrftoken');
  553. if (!liked) {
  554. $.post('/_api/likes.add', {_csrf: token, page_id: pageId}, function(res) {
  555. if (res.ok) {
  556. MarkLiked();
  557. }
  558. });
  559. } else {
  560. $.post('/_api/likes.remove', {_csrf: token, page_id: pageId}, function(res) {
  561. if (res.ok) {
  562. MarkUnLiked();
  563. }
  564. });
  565. }
  566. return false;
  567. });
  568. var $likerList = $("#liker-list");
  569. var likers = $likerList.data('likers');
  570. if (likers && likers.length > 0) {
  571. var users = crowi.findUserByIds(likers.split(','));
  572. if (users) {
  573. AddToLikers(users);
  574. }
  575. }
  576. function AddToLikers (users) {
  577. $.each(users, function(i, user) {
  578. $likerList.append(CreateUserLinkWithPicture(user));
  579. });
  580. }
  581. function MarkLiked()
  582. {
  583. $likeButton.addClass('active');
  584. $likeButton.data('liked', 1);
  585. $likeCount.text(parseInt($likeCount.text()) + 1);
  586. }
  587. function MarkUnLiked()
  588. {
  589. $likeButton.removeClass('active');
  590. $likeButton.data('liked', 0);
  591. $likeCount.text(parseInt($likeCount.text()) - 1);
  592. }
  593. if (!isSeen) {
  594. $.post('/_api/pages.seen', {page_id: pageId}, function(res) {
  595. // ignore unless response has error
  596. if (res.ok && res.seenUser) {
  597. $('#content-main').data('page-is-seen', 1);
  598. }
  599. });
  600. }
  601. function CreateUserLinkWithPicture (user) {
  602. var $userHtml = $('<a>');
  603. $userHtml.data('user-id', user._id);
  604. $userHtml.attr('href', '/user/' + user.username);
  605. $userHtml.attr('title', user.name);
  606. var $userPicture = $('<img class="picture picture-xs img-circle">');
  607. $userPicture.attr('alt', user.name);
  608. $userPicture.attr('src', Crowi.userPicture(user));
  609. $userHtml.append($userPicture);
  610. return $userHtml;
  611. }
  612. // presentation
  613. var presentaionInitialized = false
  614. , $b = $('body');
  615. $(document).on('click', '.toggle-presentation', function(e) {
  616. var $a = $(this);
  617. e.preventDefault();
  618. $b.toggleClass('overlay-on');
  619. if (!presentaionInitialized) {
  620. presentaionInitialized = true;
  621. $('<iframe />').attr({
  622. src: $a.attr('href')
  623. }).appendTo($('#presentation-container'));
  624. }
  625. }).on('click', '.fullscreen-layer', function() {
  626. $b.toggleClass('overlay-on');
  627. });
  628. //
  629. var me = $('body').data('me');
  630. var socket = io();
  631. socket.on('page edited', function (data) {
  632. if (data.user._id != me
  633. && data.page.path == pagePath) {
  634. $('#notifPageEdited').show();
  635. $('#notifPageEdited .edited-user').html(data.user.name);
  636. }
  637. });
  638. } // end if pageId
  639. // hash handling
  640. if (isSavedStatesOfTabChanges) {
  641. $('a[data-toggle="tab"][href="#revision-history"]').on('show.bs.tab', function() {
  642. window.location.hash = '#revision-history';
  643. window.history.replaceState('', 'History', '#revision-history');
  644. });
  645. $('a[data-toggle="tab"][href="#edit-form"]').on('show.bs.tab', function() {
  646. window.location.hash = '#edit-form';
  647. window.history.replaceState('', 'Edit', '#edit-form');
  648. });
  649. $('a[data-toggle="tab"][href="#revision-body"]').on('show.bs.tab', function() {
  650. // couln't solve https://github.com/weseek/crowi-plus/issues/119 completely -- 2017.07.03 Yuki Takei
  651. window.location.hash = '#';
  652. window.history.replaceState('', '', location.href);
  653. });
  654. }
  655. else {
  656. $('a[data-toggle="tab"][href="#revision-history"]').on('show.bs.tab', function() {
  657. window.history.replaceState('', 'History', '#revision-history');
  658. });
  659. $('a[data-toggle="tab"][href="#edit-form"]').on('show.bs.tab', function() {
  660. window.history.replaceState('', 'Edit', '#edit-form');
  661. });
  662. $('a[data-toggle="tab"][href="#revision-body"]').on('show.bs.tab', function() {
  663. window.history.replaceState('', '', location.href.replace(location.hash, ''));
  664. });
  665. // replace all href="#edit-form" link behaviors
  666. $(document).on('click', 'a[href="#edit-form"]', function() {
  667. window.location.replace('#edit-form');
  668. });
  669. }
  670. // focus to editor when 'shown.bs.tab' event fired
  671. $('a[href="#edit-form"]').on('shown.bs.tab', function(e) {
  672. Crowi.setCaretLineAndFocusToEditor();
  673. });
  674. });
  675. /*
  676. Crowi.getRevisionBodyContent = function() {
  677. return $('#revision-body-content').html();
  678. }
  679. Crowi.replaceRevisionBodyContent = function(html) {
  680. $('#revision-body-content').html(html);
  681. }
  682. */
  683. Crowi.findHashFromUrl = function(url)
  684. {
  685. var match;
  686. if (match = url.match(/#(.+)$/)) {
  687. return `#${match[1]}`;
  688. }
  689. return "";
  690. }
  691. Crowi.findSectionHeader = function(hash) {
  692. if (hash.length == 0) {
  693. return;
  694. }
  695. // omit '#'
  696. const id = hash.replace('#', '');
  697. // don't use jQuery and document.querySelector
  698. // because hash may containe Base64 encoded strings
  699. const elem = document.getElementById(id);
  700. if (elem != null && elem.tagName.match(/h\d+/i)) { // match h1, h2, h3...
  701. return elem;
  702. }
  703. return null;
  704. }
  705. Crowi.unhighlightSelectedSection = function(hash)
  706. {
  707. const elem = Crowi.findSectionHeader(hash);
  708. if (elem != null) {
  709. elem.classList.remove('highlighted');
  710. }
  711. }
  712. Crowi.highlightSelectedSection = function(hash)
  713. {
  714. const elem = Crowi.findSectionHeader(hash);
  715. if (elem != null) {
  716. elem.classList.add('highlighted');
  717. }
  718. }
  719. window.addEventListener('load', function(e) {
  720. // hash on page
  721. if (location.hash) {
  722. if (location.hash == '#edit-form') {
  723. $('a[data-toggle="tab"][href="#edit-form"]').tab('show');
  724. // focus
  725. Crowi.setCaretLineAndFocusToEditor();
  726. }
  727. if (location.hash == '#revision-history') {
  728. $('a[data-toggle="tab"][href="#revision-history"]').tab('show');
  729. }
  730. }
  731. if (crowi && crowi.users || crowi.users.length == 0) {
  732. var totalUsers = crowi.users.length;
  733. var $listLiker = $('.page-list-liker');
  734. $listLiker.each(function(i, liker) {
  735. var count = $(liker).data('count') || 0;
  736. if (count/totalUsers > 0.05) {
  737. $(liker).addClass('popular-page-high');
  738. // 5%
  739. } else if (count/totalUsers > 0.02) {
  740. $(liker).addClass('popular-page-mid');
  741. // 2%
  742. } else if (count/totalUsers > 0.005) {
  743. $(liker).addClass('popular-page-low');
  744. // 0.5%
  745. }
  746. });
  747. var $listSeer = $('.page-list-seer');
  748. $listSeer.each(function(i, seer) {
  749. var count = $(seer).data('count') || 0;
  750. if (count/totalUsers > 0.10) {
  751. // 10%
  752. $(seer).addClass('popular-page-high');
  753. } else if (count/totalUsers > 0.05) {
  754. // 5%
  755. $(seer).addClass('popular-page-mid');
  756. } else if (count/totalUsers > 0.02) {
  757. // 2%
  758. $(seer).addClass('popular-page-low');
  759. }
  760. });
  761. }
  762. Crowi.highlightSelectedSection(location.hash);
  763. Crowi.modifyScrollTop();
  764. Crowi.setCaretLineAndFocusToEditor();
  765. });
  766. window.addEventListener('hashchange', function(e) {
  767. Crowi.unhighlightSelectedSection(Crowi.findHashFromUrl(e.oldURL));
  768. Crowi.highlightSelectedSection(Crowi.findHashFromUrl(e.newURL));
  769. Crowi.modifyScrollTop();
  770. // hash on page
  771. if (location.hash) {
  772. if (location.hash == '#edit-form') {
  773. $('a[data-toggle="tab"][href="#edit-form"]').tab('show');
  774. }
  775. if (location.hash == '#revision-history') {
  776. $('a[data-toggle="tab"][href="#revision-history"]').tab('show');
  777. }
  778. }
  779. else {
  780. $('a[data-toggle="tab"][href="#revision-body"]').tab('show');
  781. }
  782. });
  783. window.addEventListener('keydown', (event) => {
  784. const target = event.target;
  785. // ignore when target dom is input
  786. const inputPattern = /^input|textinput|textarea$/i;
  787. if (target.tagName.match(inputPattern)) {
  788. return;
  789. }
  790. switch (event.key) {
  791. case 'e':
  792. if (!event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
  793. Crowi.handleKeyEHandler(event);
  794. }
  795. break;
  796. case 'c':
  797. if (!event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey) {
  798. Crowi.handleKeyCHandler(event);
  799. }
  800. break;
  801. case '/':
  802. if (event.ctrlKey || event.metaKey) {
  803. Crowi.handleKeyCtrlSlashHandler(event);
  804. }
  805. break;
  806. }
  807. });