2
0

crowi.js 27 KB

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