crowi.js 27 KB

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