// PukiWiki - Yet another WikiWikiWeb clone.
// main.js
-// Copyright 2017-2019 PukiWiki Development Team
+// Copyright 2017-2020 PukiWiki Development Team
// License: GPL v2 or (at your option) any later version
//
// PukiWiki JavaScript client script
-window.addEventListener && window.addEventListener('DOMContentLoaded', function() { // eslint-disable-line no-unused-expressions
- 'use strict';
+/* eslint-env browser */
+// eslint-disable-next-line no-unused-expressions
+window.addEventListener && window.addEventListener('DOMContentLoaded', function () {
+ 'use strict'
/**
* @param {NodeList} nodeList
* @param {function(Node, number): void} func
*/
- function forEach(nodeList, func) {
+ function forEach (nodeList, func) {
if (nodeList.forEach) {
- nodeList.forEach(func);
+ nodeList.forEach(func)
} else {
for (var i = 0, n = nodeList.length; i < n; i++) {
- func(nodeList[i], i);
+ func(nodeList[i], i)
}
}
}
// Name for comment
- function setYourName() {
- var NAME_KEY_ID = 'pukiwiki_comment_plugin_name';
- var actionPathname = null;
- function getPathname(formAction) {
- if (actionPathname) return actionPathname;
+ function setYourName () {
+ var NAME_KEY_ID = 'pukiwiki_comment_plugin_name'
+ var actionPathname = null
+ function getPathname (formAction) {
+ if (actionPathname) return actionPathname
try {
- var u = new URL(formAction, document.location);
- var u2 = new URL('./', u);
- actionPathname = u2.pathname;
- return u2.pathname;
+ var u = new URL(formAction, document.location)
+ var u2 = new URL('./', u)
+ actionPathname = u2.pathname
+ return u2.pathname
} catch (e) {
// Note: Internet Explorer doesn't support URL class
- var m = formAction.match(/^https?:\/\/([^/]+)(\/([^?&]+\/)?)/);
+ var m = formAction.match(/^https?:\/\/([^/]+)(\/([^?&]+\/)?)/)
if (m) {
- actionPathname = m[2]; // pathname
+ actionPathname = m[2] // pathname
} else {
- actionPathname = '/';
+ actionPathname = '/'
}
- return actionPathname;
+ return actionPathname
}
}
- function getNameKey(form) {
- var pathname = getPathname(form.action);
- var key = 'path.' + pathname + '.' + NAME_KEY_ID;
- return key;
+ function getNameKey (form) {
+ var pathname = getPathname(form.action)
+ var key = 'path.' + pathname + '.' + NAME_KEY_ID
+ return key
}
- function getForm(element) {
+ function getForm (element) {
if (element.form && element.form.tagName === 'FORM') {
- return element.form;
+ return element.form
}
- var e = element.parentElement;
+ var e = element.parentElement
for (var i = 0; i < 5; i++) {
if (e.tagName === 'FORM') {
- return e;
+ return e
}
- e = e.parentElement;
+ e = e.parentElement
}
- return null;
+ return null
}
- function handleCommentPlugin(form) {
- var namePrevious = '';
- var nameKey = getNameKey(form);
+ function handleCommentPlugin (form) {
+ var namePrevious = ''
+ var nameKey = getNameKey(form)
if (typeof localStorage !== 'undefined') {
- namePrevious = localStorage[nameKey];
+ namePrevious = localStorage[nameKey]
}
var onFocusForm = function () {
if (form.name && !form.name.value && namePrevious) {
- form.name.value = namePrevious;
+ form.name.value = namePrevious
}
- };
- var addOnForcusForm = function(eNullable) {
- if (!eNullable) return;
+ }
+ var addOnForcusForm = function (eNullable) {
+ if (!eNullable) return
if (eNullable.addEventListener) {
- eNullable.addEventListener('focus', onFocusForm);
+ eNullable.addEventListener('focus', onFocusForm)
}
- };
+ }
if (namePrevious) {
- var textList = form.querySelectorAll('input[type=text],textarea');
+ var textList = form.querySelectorAll('input[type=text],textarea')
textList.forEach(function (v) {
- addOnForcusForm(v);
- });
+ addOnForcusForm(v)
+ })
}
- form.addEventListener('submit', function() {
+ form.addEventListener('submit', function () {
if (typeof localStorage !== 'undefined') {
- localStorage[nameKey] = form.name.value;
+ localStorage[nameKey] = form.name.value
}
- }, false);
+ }, false)
}
- function setNameForComment() {
- if (!document.querySelectorAll) return;
+ function setNameForComment () {
+ if (!document.querySelectorAll) return
var elements = document.querySelectorAll(
'input[type=hidden][name=plugin][value=comment],' +
'input[type=hidden][name=plugin][value=pcomment],' +
'input[type=hidden][name=plugin][value=article],' +
- 'input[type=hidden][name=plugin][value=bugtrack]');
+ 'input[type=hidden][name=plugin][value=bugtrack]')
for (var i = 0; i < elements.length; i++) {
- var form = getForm(elements[i]);
+ var form = getForm(elements[i])
if (form) {
- handleCommentPlugin(form);
+ handleCommentPlugin(form)
}
}
}
- setNameForComment();
+ setNameForComment()
}
// AutoTicketLink
- function autoTicketLink() {
- var headReText = '([\\s\\b:\\[\\(,;]|^)';
- var tailReText = '\\b';
+ function autoTicketLink () {
+ var headReText = '([\\s\\b:\\[\\(,;]|^)'
+ var tailReText = '\\b'
var ignoreTags = ['A', 'INPUT', 'TEXTAREA', 'BUTTON',
- 'SCRIPT', 'FRAME', 'IFRAME'];
- var ticketSiteList = [];
- var jiraProjects = null;
- var jiraDefaultInfo = null;
- function regexEscape(key) {
+ 'SCRIPT', 'FRAME', 'IFRAME']
+ var ticketSiteList = []
+ var jiraProjects = null
+ var jiraDefaultInfo = null
+ function regexEscape (key) {
return key.replace(/[-.]/g, function (m) {
- return '\\' + m;
- });
+ return '\\' + m
+ })
}
- function setupSites(siteList) {
+ function setupSites (siteList) {
for (var i = 0, length = siteList.length; i < length; i++) {
- var site = siteList[i];
- var reText = '';
+ var site = siteList[i]
+ var reText = ''
switch (site.type) {
case 'jira':
reText = '(' + regexEscape(site.key) +
- '):([A-Z][A-Z0-9]{1,20}(?:_[A-Z0-9]{1,10}){0,2}-\\d{1,10})';
- break;
+ '):([A-Z][A-Z0-9]{1,20}(?:_[A-Z0-9]{1,10}){0,2}-\\d{1,10})'
+ break
case 'redmine':
- reText = '(' + regexEscape(site.key) + '):(\\d{1,10})';
- break;
+ reText = '(' + regexEscape(site.key) + '):(\\d{1,10})'
+ break
case 'git':
- reText = '(' + regexEscape(site.key) + '):([0-9a-f]{7,40})';
- break;
+ reText = '(' + regexEscape(site.key) + '):([0-9a-f]{7,40})'
+ break
default:
- continue;
+ continue
}
- site.reText = reText;
- site.re = new RegExp(headReText + reText + tailReText);
+ site.reText = reText
+ site.re = new RegExp(headReText + reText + tailReText)
}
}
- function getJiraSite() {
- var reText = '()([A-Z][A-Z0-9]{1,20}(?:_[A-Z0-9]{1,10}){0,2}-\\d{1,10})';
+ function getJiraSite () {
+ var reText = '()([A-Z][A-Z0-9]{1,20}(?:_[A-Z0-9]{1,10}){0,2}-\\d{1,10})'
var site = {
title: 'Builtin JIRA',
type: '_jira_',
key: '_jira_',
reText: reText,
re: new RegExp(headReText + reText + tailReText)
- };
- return site;
+ }
+ return site
}
- function getSiteListFromBody() {
- var defRoot = document.querySelector('#pukiwiki-site-properties .ticketlink-def');
+ function getSiteListFromBody () {
+ var defRoot = document.querySelector('#pukiwiki-site-properties .ticketlink-def')
if (defRoot && defRoot.value) {
- var list = JSON.parse(defRoot.value);
- setupSites(list);
- return list;
+ var list = JSON.parse(defRoot.value)
+ setupSites(list)
+ return list
}
- return [];
+ return []
}
- function getJiraProjectsFromBody() {
- var defRoot = document.querySelector('#pukiwiki-site-properties .ticketlink-jira-def');
+ function getJiraProjectsFromBody () {
+ var defRoot = document.querySelector('#pukiwiki-site-properties .ticketlink-jira-def')
if (defRoot && defRoot.value) {
try {
- return JSON.parse(defRoot.value); // List
+ return JSON.parse(defRoot.value) // List
} catch (e) {
- return null;
+ return null
}
}
- return null;
+ return null
}
- function getJiraDefaultInfoFromBody() {
- var defRoot = document.querySelector('#pukiwiki-site-properties .ticketlink-jira-default-def');
+ function getJiraDefaultInfoFromBody () {
+ var defRoot = document.querySelector('#pukiwiki-site-properties .ticketlink-jira-default-def')
if (defRoot && defRoot.value) {
try {
- return JSON.parse(defRoot.value); // object
+ return JSON.parse(defRoot.value) // object
} catch (e) {
- return null;
+ return null
}
}
- return null;
+ return null
}
- function getSiteList() {
- return ticketSiteList;
+ function getSiteList () {
+ return ticketSiteList
}
- function getJiraProjectList() {
- return jiraProjects;
+ function getJiraProjectList () {
+ return jiraProjects
}
- function getDefaultJira() {
- return jiraDefaultInfo;
+ function getDefaultJira () {
+ return jiraDefaultInfo
}
- function ticketToLink(keyText) {
- var siteList = getSiteList();
+ function ticketToLink (keyText) {
+ var siteList = getSiteList()
for (var i = 0; i < siteList.length; i++) {
- var site = siteList[i];
- var m = keyText.match(site.re);
+ var site = siteList[i]
+ var m = keyText.match(site.re)
if (m) {
- var ticketKey = m[3];
- var title = ticketKey;
- var ticketUrl;
+ var ticketKey = m[3]
+ var title = ticketKey
+ var ticketUrl
if (site.type === '_jira_') {
// JIRA issue
- var projects = getJiraProjectList();
- var hyphen = keyText.indexOf('-');
+ var projects = getJiraProjectList()
+ var hyphen = keyText.indexOf('-')
if (hyphen > 0) {
- var projectKey = keyText.substr(0, hyphen);
+ var projectKey = keyText.substr(0, hyphen)
if (projects) {
for (var j = 0; j < projects.length; j++) {
- var p = projects[j];
+ var p = projects[j]
if (p.key === projectKey) {
if (p.title) {
- title = p.title.replace(/\$1/g, ticketKey);
+ title = p.title.replace(/\$1/g, ticketKey)
}
- ticketUrl = p.base_url + ticketKey;
- break;
+ ticketUrl = p.base_url + ticketKey
+ break
}
}
}
if (!ticketUrl) {
- var defaultJira = getDefaultJira();
+ var defaultJira = getDefaultJira()
if (defaultJira) {
if (defaultJira.title) {
- title = defaultJira.title.replace(/\$1/g, ticketKey);
+ title = defaultJira.title.replace(/\$1/g, ticketKey)
}
- ticketUrl = defaultJira.base_url + ticketKey;
+ ticketUrl = defaultJira.base_url + ticketKey
}
}
}
if (!ticketUrl) {
- return null;
+ return null
}
} else {
// Explicit TicketLink
if (site.title) {
- title = site.title.replace(/\$1/g, ticketKey);
+ title = site.title.replace(/\$1/g, ticketKey)
}
- ticketUrl = site.base_url + ticketKey;
+ ticketUrl = site.base_url + ticketKey
}
return {
url: ticketUrl,
title: title
- };
+ }
}
}
- return null;
+ return null
}
- function getRegex(list) {
- var reText = '';
+ function getRegex (list) {
+ var reText = ''
for (var i = 0, length = list.length; i < length; i++) {
if (reText.length > 0) {
- reText += '|';
+ reText += '|'
}
- reText += list[i].reText;
+ reText += list[i].reText
}
- return new RegExp(headReText + '(' + reText + ')' + tailReText);
+ return new RegExp(headReText + '(' + reText + ')' + tailReText)
}
- function makeTicketLink(element) {
- var siteList = getSiteList();
+ function makeTicketLink (element) {
+ var siteList = getSiteList()
if (!siteList || siteList.length === 0) {
- return;
+ return
}
- var re = getRegex(siteList);
- var f;
- var m;
- var text = element.nodeValue;
+ var re = getRegex(siteList)
+ var f
+ var m
+ var text = element.nodeValue
while (m = text.match(re)) { // eslint-disable-line no-cond-assign
// m[1]: head, m[2]: keyText
if (!f) {
- f = document.createDocumentFragment();
+ f = document.createDocumentFragment()
}
if (m.index > 0 || m[1].length > 0) {
- f.appendChild(document.createTextNode(text.substr(0, m.index) + m[1]));
+ f.appendChild(document.createTextNode(text.substr(0, m.index) + m[1]))
}
- var linkKey = m[2];
- var linkInfo = ticketToLink(linkKey);
+ var linkKey = m[2]
+ var linkInfo = ticketToLink(linkKey)
if (linkInfo) {
- var a = document.createElement('a');
- a.textContent = linkKey;
- a.href = linkInfo.url;
- a.title = linkInfo.title;
- f.appendChild(a);
+ var a = document.createElement('a')
+ a.textContent = linkKey
+ a.href = linkInfo.url
+ a.title = linkInfo.title
+ f.appendChild(a)
} else {
- f.appendChild(document.createTextNode(m[2]));
+ f.appendChild(document.createTextNode(m[2]))
}
- text = text.substr(m.index + m[0].length);
+ text = text.substr(m.index + m[0].length)
}
if (f) {
if (text.length > 0) {
- f.appendChild(document.createTextNode(text));
+ f.appendChild(document.createTextNode(text))
}
- element.parentNode.replaceChild(f, element);
+ element.parentNode.replaceChild(f, element)
}
}
- function walkElement(element) {
- var e = element.firstChild;
+ function walkElement (element) {
+ var e = element.firstChild
while (e) {
if (e.nodeType === 3 && e.nodeValue &&
e.nodeValue.length > 5 && /\S/.test(e.nodeValue)) {
- var next = e.nextSibling;
- makeTicketLink(e);
- e = next;
+ var next = e.nextSibling
+ makeTicketLink(e)
+ e = next
} else {
if (e.nodeType === 1 && ignoreTags.indexOf(e.tagName) === -1) {
- walkElement(e);
+ walkElement(e)
}
- e = e.nextSibling;
+ e = e.nextSibling
}
}
}
if (!Array.prototype.indexOf || !document.createDocumentFragment) {
- return;
+ return
}
- ticketSiteList = getSiteListFromBody();
- jiraProjects = getJiraProjectsFromBody();
- jiraDefaultInfo = getJiraDefaultInfoFromBody();
+ ticketSiteList = getSiteListFromBody()
+ jiraProjects = getJiraProjectsFromBody()
+ jiraDefaultInfo = getJiraDefaultInfoFromBody()
if (jiraDefaultInfo || (jiraProjects && jiraProjects.length > 0)) {
- ticketSiteList.push(getJiraSite());
+ ticketSiteList.push(getJiraSite())
}
- var target = document.getElementById('body');
- walkElement(target);
+ var target = document.getElementById('body')
+ walkElement(target)
}
- function confirmEditFormLeaving() {
- function trim(s) {
+ function confirmEditFormLeaving () {
+ function trim (s) {
if (typeof s !== 'string') {
- return s;
- }
- return s.replace(/^\s+|\s+$/g, '');
- }
- if (!document.querySelector) return;
- var canceled = false;
- var pluginNameE = document.querySelector('#pukiwiki-site-properties .plugin-name');
- if (!pluginNameE) return;
- var originalText = null;
- if (pluginNameE.value !== 'edit') return;
- var editForm = document.querySelector('.edit_form form._plugin_edit_edit_form');
- if (!editForm) return;
- var cancelMsgE = editForm.querySelector('#_msg_edit_cancel_confirm');
- var unloadBeforeMsgE = editForm.querySelector('#_msg_edit_unloadbefore_message');
- var textArea = editForm.querySelector('textarea[name="msg"]');
- if (!textArea) return;
- originalText = textArea.value;
- var isPreview = false;
- var inEditE = document.querySelector('#pukiwiki-site-properties .page-in-edit');
+ return s
+ }
+ return s.replace(/^\s+|\s+$/g, '')
+ }
+ if (!document.querySelector) return
+ var canceled = false
+ var pluginNameE = document.querySelector('#pukiwiki-site-properties .plugin-name')
+ if (!pluginNameE) return
+ var originalText = null
+ if (pluginNameE.value !== 'edit') return
+ var editForm = document.querySelector('.edit_form form._plugin_edit_edit_form')
+ if (!editForm) return
+ var cancelMsgE = editForm.querySelector('#_msg_edit_cancel_confirm')
+ var unloadBeforeMsgE = editForm.querySelector('#_msg_edit_unloadbefore_message')
+ var textArea = editForm.querySelector('textarea[name="msg"]')
+ if (!textArea) return
+ originalText = textArea.value
+ var isPreview = false
+ var inEditE = document.querySelector('#pukiwiki-site-properties .page-in-edit')
if (inEditE && inEditE.value) {
- isPreview = (inEditE.value === 'true');
- }
- var cancelForm = document.querySelector('.edit_form form._plugin_edit_cancel');
- var submited = false;
- editForm.addEventListener('submit', function() {
- canceled = false;
- submited = true;
- });
- cancelForm.addEventListener('submit', function(e) {
- submited = false;
- canceled = false;
+ isPreview = (inEditE.value === 'true')
+ }
+ var cancelForm = document.querySelector('.edit_form form._plugin_edit_cancel')
+ var submited = false
+ editForm.addEventListener('submit', function () {
+ canceled = false
+ submited = true
+ })
+ cancelForm.addEventListener('submit', function (e) {
+ submited = false
+ canceled = false
if (trim(textArea.value) === trim(originalText)) {
- canceled = true;
- return false;
+ canceled = true
+ return false
}
- var message = 'The text you have entered will be discarded. Is it OK?';
+ var message = 'The text you have entered will be discarded. Is it OK?'
if (cancelMsgE && cancelMsgE.value) {
- message = cancelMsgE.value;
+ message = cancelMsgE.value
}
if (window.confirm(message)) { // eslint-disable-line no-alert
// Execute "Cancel"
- canceled = true;
- return true;
- }
- e.preventDefault();
- return false;
- });
- window.addEventListener('beforeunload', function(e) {
- if (canceled) return;
- if (submited) return;
+ canceled = true
+ return true
+ }
+ e.preventDefault()
+ return false
+ })
+ window.addEventListener('beforeunload', function (e) {
+ if (canceled) return
+ if (submited) return
if (!isPreview) {
- if (trim(textArea.value) === trim(originalText)) return;
+ if (trim(textArea.value) === trim(originalText)) return
}
- var message = 'Data you have entered will not be saved.';
+ var message = 'Data you have entered will not be saved.'
if (unloadBeforeMsgE && unloadBeforeMsgE.value) {
- message = unloadBeforeMsgE.value;
+ message = unloadBeforeMsgE.value
}
- e.returnValue = message;
- }, false);
+ e.returnValue = message
+ }, false)
}
- function showPagePassage() {
+ function showPagePassage () {
/**
* @param {Date} now
* @param {string} dateText
*/
- function getSimplePassage(dateText, now) {
+ function getSimplePassage (dateText, now) {
if (!dateText) {
- return '';
+ return ''
}
- var units = [{u: 'm', max: 60}, {u: 'h', max: 24}, {u: 'd', max: 1}];
- var d = new Date();
- d.setTime(Date.parse(dateText));
- var t = (now.getTime() - d.getTime()) / (1000 * 60); // minutes
- var unit = units[0].u; var card = units[0].max;
+ var units = [{ u: 'm', max: 60 }, { u: 'h', max: 24 }, { u: 'd', max: 1 }]
+ var d = new Date()
+ d.setTime(Date.parse(dateText))
+ var t = (now.getTime() - d.getTime()) / (1000 * 60) // minutes
+ var unit = units[0].u; var card = units[0].max
for (var i = 0; i < units.length; i++) {
- unit = units[i].u; card = units[i].max;
- if (t < card) break;
- t = t / card;
+ unit = units[i].u; card = units[i].max
+ if (t < card) break
+ t = t / card
}
- return '' + Math.floor(t) + unit;
+ return '' + Math.floor(t) + unit
}
/**
* @param {Date} now
* @param {string} dateText
*/
- function getPassage(dateText, now) {
- return '(' + getSimplePassage(dateText, now) + ')';
+ function getPassage (dateText, now) {
+ return '(' + getSimplePassage(dateText, now) + ')'
}
- var now = new Date();
- var elements = document.getElementsByClassName('page_passage');
- forEach(elements, function(e) {
- var dt = e.getAttribute('data-mtime');
+ var now = new Date()
+ var elements = document.getElementsByClassName('page_passage')
+ forEach(elements, function (e) {
+ var dt = e.getAttribute('data-mtime')
if (dt) {
- var d = new Date(dt);
- e.textContent = ' ' + getPassage(d, now);
+ var d = new Date(dt)
+ e.textContent = ' ' + getPassage(d, now)
}
- });
- var links = document.getElementsByClassName('link_page_passage');
- forEach(links, function(e) {
- var dt = e.getAttribute('data-mtime');
+ })
+ var links = document.getElementsByClassName('link_page_passage')
+ forEach(links, function (e) {
+ var dt = e.getAttribute('data-mtime')
if (dt) {
- var d = new Date(dt);
+ var d = new Date(dt)
if (e.title) {
- e.title = e.title + ' ' + getPassage(d, now);
+ e.title = e.title + ' ' + getPassage(d, now)
} else {
- e.title = e.textContent + ' ' + getPassage(d, now);
+ e.title = e.textContent + ' ' + getPassage(d, now)
}
}
- });
- var simplePassages = document.getElementsByClassName('simple_passage');
- forEach(simplePassages, function(e) {
- var dt = e.getAttribute('data-mtime');
+ })
+ var simplePassages = document.getElementsByClassName('simple_passage')
+ forEach(simplePassages, function (e) {
+ var dt = e.getAttribute('data-mtime')
if (dt) {
- var d = new Date(dt);
- e.textContent = getSimplePassage(d, now);
+ var d = new Date(dt)
+ e.textContent = getSimplePassage(d, now)
}
- });
+ })
// new plugin
- var newItems = document.getElementsByClassName('__plugin_new');
- forEach(newItems, function(e) {
- var dt = e.getAttribute('data-mtime');
+ var newItems = document.getElementsByClassName('__plugin_new')
+ forEach(newItems, function (e) {
+ var dt = e.getAttribute('data-mtime')
if (dt) {
- var d = new Date(dt);
- var diff = now.getTime() - d.getTime();
- var daySpan = diff / 1000 / 60 / 60 / 24;
+ var d = new Date(dt)
+ var diff = now.getTime() - d.getTime()
+ var daySpan = diff / 1000 / 60 / 60 / 24
if (daySpan < 1) {
- e.textContent = ' New!';
- e.title = getPassage(d, now);
+ e.textContent = ' New!'
+ e.title = getPassage(d, now)
if (e.classList && e.classList.add) {
- e.classList.add('new1');
+ e.classList.add('new1')
}
} else if (daySpan < 5) {
- e.textContent = ' New';
- e.title = getPassage(d, now);
+ e.textContent = ' New'
+ e.title = getPassage(d, now)
if (e.classList && e.classList.add) {
- e.classList.add('new5');
+ e.classList.add('new5')
}
}
}
- });
+ })
}
- function convertExternalLinkToCushionPageLink() {
- function domainQuote(domain) {
- return domain.replace(/\./g, '\\.');
+ function convertExternalLinkToCushionPageLink () {
+ function domainQuote (domain) {
+ return domain.replace(/\./g, '\\.')
}
- function domainsToRegex(domains) {
- var regexList = [];
- domains.forEach(function(domain) {
+ function domainsToRegex (domains) {
+ var regexList = []
+ domains.forEach(function (domain) {
if (domain.substr(0, 2) === '*.') {
// Wildcard domain
- var apex = domain.substr(2);
- var r = new RegExp('((^.*\\.)|^)' + domainQuote(apex) + '$', 'i');
- regexList.push(r);
+ var apex = domain.substr(2)
+ var r = new RegExp('((^.*\\.)|^)' + domainQuote(apex) + '$', 'i')
+ regexList.push(r)
} else {
// Normal domain
- regexList.push(new RegExp('^' + domainQuote(domain) + '$', 'i'));
+ regexList.push(new RegExp('^' + domainQuote(domain) + '$', 'i'))
}
- });
- return regexList;
+ })
+ return regexList
}
- function domainMatch(domain, regexList) {
+ function domainMatch (domain, regexList) {
for (var i = 0, n = regexList.length; i < n; i++) {
if (regexList[i].test(domain)) {
- return true;
+ return true
}
}
- return false;
+ return false
}
- function removeCushionPageLinks() {
- var links = document.querySelectorAll('a.external-link');
- forEach(links, function(link) {
- var originalUrl = link.getAttribute('data-original-url');
+ function removeCushionPageLinks () {
+ var links = document.querySelectorAll('a.external-link')
+ forEach(links, function (link) {
+ var originalUrl = link.getAttribute('data-original-url')
if (originalUrl) {
- link.setAttribute('href', originalUrl);
+ link.setAttribute('href', originalUrl)
}
- });
- }
- if (!document.querySelector || !JSON) return;
- if (!Array || !Array.prototype || !Array.prototype.indexOf) return;
- var extLinkDef = document.querySelector('#pukiwiki-site-properties .external-link-cushion');
- if (!extLinkDef || !extLinkDef.value) return;
- var extLinkInfo = JSON.parse(extLinkDef.value);
- if (!extLinkInfo) return;
- var refInternalDomains = extLinkInfo.internal_domains;
- var silentExternalDomains = extLinkInfo.silent_external_domains;
+ })
+ }
+ if (!document.querySelector || !JSON) return
+ if (!Array || !Array.prototype || !Array.prototype.indexOf) return
+ var extLinkDef = document.querySelector('#pukiwiki-site-properties .external-link-cushion')
+ if (!extLinkDef || !extLinkDef.value) return
+ var extLinkInfo = JSON.parse(extLinkDef.value)
+ if (!extLinkInfo) return
+ var refInternalDomains = extLinkInfo.internal_domains
+ var silentExternalDomains = extLinkInfo.silent_external_domains
if (!Array.isArray(refInternalDomains)) {
- refInternalDomains = [];
+ refInternalDomains = []
}
- var internalDomains = refInternalDomains.slice();
- var location = document.location;
+ var internalDomains = refInternalDomains.slice()
+ var location = document.location
if (location.protocol === 'file:') {
- removeCushionPageLinks();
- return;
+ removeCushionPageLinks()
+ return
}
- if (location.protocol !== 'http:' && location.protocol !== 'https:') return;
+ if (location.protocol !== 'http:' && location.protocol !== 'https:') return
if (internalDomains.indexOf(location.hostname) < 0) {
- internalDomains.push(location.hostname);
+ internalDomains.push(location.hostname)
}
if (!Array.isArray(silentExternalDomains)) {
- silentExternalDomains = [];
- }
- var propsE = document.querySelector('#pukiwiki-site-properties .site-props');
- if (!propsE || !propsE.value) return;
- var siteProps = JSON.parse(propsE.value);
- var sitePathname = siteProps && siteProps.base_uri_pathname;
- if (!sitePathname) return;
- var internalDomainsR = domainsToRegex(internalDomains);
- var silentExternalDomainsR = domainsToRegex(silentExternalDomains);
- var links = document.querySelectorAll('a:not(.external-link):not(.internal-link)');
- var classListEnabled = null;
- forEach(links, function(link) {
+ silentExternalDomains = []
+ }
+ var propsE = document.querySelector('#pukiwiki-site-properties .site-props')
+ if (!propsE || !propsE.value) return
+ var siteProps = JSON.parse(propsE.value)
+ var sitePathname = siteProps && siteProps.base_uri_pathname
+ if (!sitePathname) return
+ var internalDomainsR = domainsToRegex(internalDomains)
+ var silentExternalDomainsR = domainsToRegex(silentExternalDomains)
+ var links = document.querySelectorAll('a:not(.external-link):not(.internal-link)')
+ var classListEnabled = null
+ forEach(links, function (link) {
if (classListEnabled === null) {
- classListEnabled = link.classList && link.classList.add && true;
+ classListEnabled = link.classList && link.classList.add && true
}
- if (!classListEnabled) return;
- var href = link.getAttribute('href');
- if (!href) return; // anchor without href attribute (a name)
- var m = href.match(/^https?:\/\/([0-9a-zA-Z.-]+)(:\d+)?/);
+ if (!classListEnabled) return
+ var href = link.getAttribute('href')
+ if (!href) return // anchor without href attribute (a name)
+ var m = href.match(/^https?:\/\/([0-9a-zA-Z.-]+)(:\d+)?/)
if (m) {
- var host = m[1];
+ var host = m[1]
if (domainMatch(host, internalDomainsR)) {
- link.classList.add('internal-link');
+ link.classList.add('internal-link')
} else {
if (domainMatch(host, silentExternalDomainsR) ||
link.textContent.replace(/\s+/g, '') === '') {
// Don't show extenal link icons on these domains
- link.classList.add('external-link-silent');
+ link.classList.add('external-link-silent')
}
- link.classList.add('external-link');
- link.setAttribute('title', href);
- link.setAttribute('data-original-url', href);
- link.setAttribute('href', sitePathname + '?cmd=external_link&url=' + encodeURIComponent(href));
+ link.classList.add('external-link')
+ link.setAttribute('title', href)
+ link.setAttribute('data-original-url', href)
+ link.setAttribute('href', sitePathname + '?cmd=external_link&url=' + encodeURIComponent(href))
}
} else {
- link.classList.add('internal-link');
+ link.classList.add('internal-link')
}
- });
+ })
}
- function makeTopicpathTitle() {
- if (!document.createDocumentFragment || !window.JSON) return;
- var sitePropE = document.querySelector('#pukiwiki-site-properties');
- if (!sitePropE) return;
- var pageNameE = sitePropE.querySelector('.page-name');
- if (!pageNameE || !pageNameE.value) return;
- var pageName = pageNameE.value;
- var topicpathE = sitePropE.querySelector('.topicpath-links');
- if (!topicpathE || !topicpathE.value) return;
- var topicpathLinks = JSON.parse(topicpathE.value);
- if (!topicpathLinks) return;
- var titleH1 = document.querySelector('h1.title');
- if (!titleH1) return;
- var aList = titleH1.querySelectorAll('a');
- if (!aList || aList.length > 1) return;
- var a = titleH1.querySelector('a');
- if (!a) return;
- if (a.textContent !== pageName) return;
- var fragment = document.createDocumentFragment();
+ function makeTopicpathTitle () {
+ if (!document.createDocumentFragment || !window.JSON) return
+ var sitePropE = document.querySelector('#pukiwiki-site-properties')
+ if (!sitePropE) return
+ var pageNameE = sitePropE.querySelector('.page-name')
+ if (!pageNameE || !pageNameE.value) return
+ var pageName = pageNameE.value
+ var topicpathE = sitePropE.querySelector('.topicpath-links')
+ if (!topicpathE || !topicpathE.value) return
+ var topicpathLinks = JSON.parse(topicpathE.value)
+ if (!topicpathLinks) return
+ var titleH1 = document.querySelector('h1.title')
+ if (!titleH1) return
+ var aList = titleH1.querySelectorAll('a')
+ if (!aList || aList.length > 1) return
+ var a = titleH1.querySelector('a')
+ if (!a) return
+ if (a.textContent !== pageName) return
+ var fragment = document.createDocumentFragment()
for (var i = 0, n = topicpathLinks.length; i < n; i++) {
- var path = topicpathLinks[i];
+ var path = topicpathLinks[i]
if (path.uri) {
- var a1 = document.createElement('a');
- a1.setAttribute('href', path.uri);
- a1.setAttribute('title', path.page);
- a1.textContent = path.leaf;
- fragment.appendChild(a1);
+ var a1 = document.createElement('a')
+ a1.setAttribute('href', path.uri)
+ a1.setAttribute('title', path.page)
+ a1.textContent = path.leaf
+ fragment.appendChild(a1)
} else {
- var s1 = document.createElement('span');
- s1.textContent = path.leaf;
- fragment.appendChild(s1);
- }
- var span = document.createElement('span');
- span.className = 'topicpath-slash';
- span.textContent = '/';
- fragment.appendChild(span);
- }
- var a2 = document.createElement('a');
- a2.setAttribute('href', a.getAttribute('href'));
- a2.setAttribute('title', 'Backlinks');
- a2.textContent = a.textContent.replace(/^.+\//, '');
- fragment.appendChild(a2);
- a.parentNode.replaceChild(fragment, a);
+ var s1 = document.createElement('span')
+ s1.textContent = path.leaf
+ fragment.appendChild(s1)
+ }
+ var span = document.createElement('span')
+ span.className = 'topicpath-slash'
+ span.textContent = '/'
+ fragment.appendChild(span)
+ }
+ var a2 = document.createElement('a')
+ a2.setAttribute('href', a.getAttribute('href'))
+ a2.setAttribute('title', 'Backlinks')
+ a2.textContent = a.textContent.replace(/^.+\//, '')
+ fragment.appendChild(a2)
+ a.parentNode.replaceChild(fragment, a)
}
- setYourName();
- autoTicketLink();
- confirmEditFormLeaving();
- showPagePassage();
- convertExternalLinkToCushionPageLink();
- makeTopicpathTitle();
-});
+ setYourName()
+ autoTicketLink()
+ confirmEditFormLeaving()
+ showPagePassage()
+ convertExternalLinkToCushionPageLink()
+ makeTopicpathTitle()
+})
// PukiWiki - Yet another WikiWikiWeb clone.
// search2.js
// Copyright
-// 2017 PukiWiki Development Team
+// 2017-2020 PukiWiki Development Team
// License: GPL v2 or (at your option) any later version
//
// PukiWiki search2 pluign - JavaScript client script
-window.addEventListener && window.addEventListener('DOMContentLoaded', function() { // eslint-disable-line no-unused-expressions
- 'use strict';
- function enableSearch2() {
- var aroundLines = 2;
- var maxResultLines = 20;
- var defaultSearchWaitMilliseconds = 100;
- var defaultMaxResults = 1000;
- var kanaMap = null;
- var searchProps = {};
+/* eslint-env browser */
+// eslint-disable-next-line no-unused-expressions
+window.addEventListener && window.addEventListener('DOMContentLoaded', function () {
+ 'use strict'
+ function enableSearch2 () {
+ var aroundLines = 2
+ var maxResultLines = 20
+ var defaultSearchWaitMilliseconds = 100
+ var defaultMaxResults = 1000
+ var kanaMap = null
+ var searchProps = {}
/**
* Escape HTML special charactors
*
* @param {string} s
*/
- function escapeHTML(s) {
+ function escapeHTML (s) {
if (typeof s !== 'string') {
- return '' + s;
+ return '' + s
}
- return s.replace(/[&"<>]/g, function(m) {
+ return s.replace(/[&"<>]/g, function (m) {
return {
'&': '&',
'"': '"',
'<': '<',
'>': '>'
- }[m];
- });
+ }[m]
+ })
}
/**
* @param {string} idText
* @param {number} defaultValue
* @type number
*/
- function getIntById(idText, defaultValue) {
- var value = defaultValue;
+ function getIntById (idText, defaultValue) {
+ var value = defaultValue
try {
- var element = document.getElementById(idText);
+ var element = document.getElementById(idText)
if (element) {
- value = parseInt(element.value, 10);
+ value = parseInt(element.value, 10)
if (isNaN(value)) { // eslint-disable-line no-restricted-globals
- value = defaultValue;
+ value = defaultValue
}
}
} catch (e) {
- value = defaultValue;
+ value = defaultValue
}
- return value;
+ return value
}
/**
* @param {string} idText
* @param {string} defaultValue
* @type string
*/
- function getTextById(idText, defaultValue) {
- var value = defaultValue;
+ function getTextById (idText, defaultValue) {
+ var value = defaultValue
try {
- var element = document.getElementById(idText);
+ var element = document.getElementById(idText)
if (element.value) {
- value = element.value;
+ value = element.value
}
} catch (e) {
- value = defaultValue;
+ value = defaultValue
}
- return value;
+ return value
}
- function prepareSearchProps() {
- var p = {};
+ function prepareSearchProps () {
+ var p = {}
p.errorMsg = getTextById('_plugin_search2_msg_error',
- 'An error occurred while processing.');
+ 'An error occurred while processing.')
p.searchingMsg = getTextById('_plugin_search2_msg_searching',
- 'Searching...');
+ 'Searching...')
p.showingResultMsg = getTextById('_plugin_search2_msg_showing_result',
- 'Showing search results');
- p.prevOffset = getTextById('_plugin_search2_prev_offset', '');
- var baseUrlDefault = document.location.pathname + document.location.search;
- baseUrlDefault = baseUrlDefault.replace(/&offset=\d+/, '');
- p.baseUrl = getTextById('_plugin_search2_base_url', baseUrlDefault);
- p.msgPrevResultsTemplate = getTextById('_plugin_search2_msg_prev_results', 'Previous $1 pages');
- p.msgMoreResultsTemplate = getTextById('_plugin_search2_msg_more_results', 'Next $1 pages');
- p.user = getTextById('_plugin_search2_auth_user', '');
- p.showingResultMsg = getTextById('_plugin_search2_msg_showing_result', 'Showing search results');
+ 'Showing search results')
+ p.prevOffset = getTextById('_plugin_search2_prev_offset', '')
+ var baseUrlDefault = document.location.pathname + document.location.search
+ baseUrlDefault = baseUrlDefault.replace(/&offset=\d+/, '')
+ p.baseUrl = getTextById('_plugin_search2_base_url', baseUrlDefault)
+ p.msgPrevResultsTemplate = getTextById('_plugin_search2_msg_prev_results', 'Previous $1 pages')
+ p.msgMoreResultsTemplate = getTextById('_plugin_search2_msg_more_results', 'Next $1 pages')
+ p.user = getTextById('_plugin_search2_auth_user', '')
+ p.showingResultMsg = getTextById('_plugin_search2_msg_showing_result', 'Showing search results')
p.notFoundMessageTemplate = getTextById('_plugin_search2_msg_result_notfound',
- 'No page which contains $1 has been found.');
+ 'No page which contains $1 has been found.')
p.foundMessageTemplate = getTextById('_plugin_search2_msg_result_found',
- 'In the page <strong>$2</strong>, <strong>$3</strong> pages that contain all the terms $1 were found.');
- p.maxResults = getIntById('_plugin_search2_max_results', defaultMaxResults);
- p.searchInterval = getIntById('_plugin_search2_search_wait_milliseconds', defaultSearchWaitMilliseconds);
- p.offset = getIntById('_plugin_search2_offset', 0);
- searchProps = p;
+ 'In the page <strong>$2</strong>, <strong>$3</strong> pages that contain all the terms $1 were found.')
+ p.maxResults = getIntById('_plugin_search2_max_results', defaultMaxResults)
+ p.searchInterval = getIntById('_plugin_search2_search_wait_milliseconds', defaultSearchWaitMilliseconds)
+ p.offset = getIntById('_plugin_search2_offset', 0)
+ searchProps = p
}
- function getSiteProps() {
- var empty = {};
- var propsE = document.querySelector('#pukiwiki-site-properties .site-props');
- if (!propsE) return empty;
- var props = JSON.parse(propsE.value);
- return props || empty;
+ function getSiteProps () {
+ var empty = {}
+ var propsE = document.querySelector('#pukiwiki-site-properties .site-props')
+ if (!propsE) return empty
+ var props = JSON.parse(propsE.value)
+ return props || empty
}
/**
* @param {NodeList} nodeList
* @param {function(Node, number): void} func
*/
- function forEach(nodeList, func) {
+ function forEach (nodeList, func) {
if (nodeList.forEach) {
- nodeList.forEach(func);
+ nodeList.forEach(func)
} else {
for (var i = 0, n = nodeList.length; i < n; i++) {
- func(nodeList[i], i);
+ func(nodeList[i], i)
}
}
}
* @param {string} text
* @param {RegExp} searchRegex
*/
- function findAndDecorateText(text, searchRegex) {
- var isReplaced = false;
- var lastIndex = 0;
- var m;
- var decorated = '';
- if (!searchRegex) return null;
- searchRegex.lastIndex = 0;
+ function findAndDecorateText (text, searchRegex) {
+ var isReplaced = false
+ var lastIndex = 0
+ var m
+ var decorated = ''
+ if (!searchRegex) return null
+ searchRegex.lastIndex = 0
while ((m = searchRegex.exec(text)) !== null) {
if (m[0] === '') {
// Fail-safe
- console.log('Invalid searchRegex ' + searchRegex);
- return null;
+ console.log('Invalid searchRegex ' + searchRegex)
+ return null
}
- isReplaced = true;
- var pre = text.substring(lastIndex, m.index);
- decorated += escapeHTML(pre);
+ isReplaced = true
+ var pre = text.substring(lastIndex, m.index)
+ decorated += escapeHTML(pre)
for (var i = 1; i < m.length; i++) {
if (m[i]) {
- decorated += '<strong class="word' + (i - 1) + '">' + escapeHTML(m[i]) + '</strong>';
+ decorated += '<strong class="word' + (i - 1) + '">' + escapeHTML(m[i]) + '</strong>'
}
}
- lastIndex = searchRegex.lastIndex;
+ lastIndex = searchRegex.lastIndex
}
if (isReplaced) {
- decorated += escapeHTML(text.substr(lastIndex));
- return decorated;
+ decorated += escapeHTML(text.substr(lastIndex))
+ return decorated
}
- return null;
+ return null
}
/**
* @param {Object} session
* @param {RegExp} searchRegex
* @param {boolean} nowSearching
*/
- function getSearchResultMessage(session, searchText, searchRegex, nowSearching) {
- var searchTextDecorated = findAndDecorateText(searchText, searchRegex);
- if (searchTextDecorated === null) searchTextDecorated = escapeHTML(searchText);
- var messageTemplate = searchProps.foundMessageTemplate;
+ function getSearchResultMessage (session, searchText, searchRegex, nowSearching) {
+ var searchTextDecorated = findAndDecorateText(searchText, searchRegex)
+ if (searchTextDecorated === null) searchTextDecorated = escapeHTML(searchText)
+ var messageTemplate = searchProps.foundMessageTemplate
if (!nowSearching && session.hitPageCount === 0) {
- messageTemplate = searchProps.notFoundMessageTemplate;
+ messageTemplate = searchProps.notFoundMessageTemplate
}
- var msg = messageTemplate.replace(/\$1|\$2|\$3/g, function(m) {
+ var msg = messageTemplate.replace(/\$1|\$2|\$3/g, function (m) {
return {
$1: searchTextDecorated,
$2: session.hitPageCount,
$3: session.readPageCount
- }[m];
- });
- return msg;
+ }[m]
+ })
+ return msg
}
/**
* @param {Object} session
*/
- function getSearchProgress(session) {
+ function getSearchProgress (session) {
var progress = '(read:' + session.readPageCount + ', scan:' +
- session.scanPageCount + ', all:' + session.pageCount;
+ session.scanPageCount + ', all:' + session.pageCount
if (session.offset) {
- progress += ', offset: ' + session.offset;
+ progress += ', offset: ' + session.offset
}
- progress += ')';
- return progress;
+ progress += ')'
+ return progress
}
/**
* @param {Object} session
* @param {number} maxResults
*/
- function getOffsetLinks(session, maxResults) {
- var baseUrl = searchProps.baseUrl;
- var links = [];
+ function getOffsetLinks (session, maxResults) {
+ var baseUrl = searchProps.baseUrl
+ var links = []
if ('prevOffset' in session) {
- var prevResultUrl = baseUrl;
+ var prevResultUrl = baseUrl
if (session.prevOffset > 0) {
- prevResultUrl += '&offset=' + session.prevOffset;
+ prevResultUrl += '&offset=' + session.prevOffset
}
- var msgPrev = searchProps.msgPrevResultsTemplate.replace(/\$1/, maxResults);
- var prevResultHtml = '<a href="' + prevResultUrl + '">' + msgPrev + '</a>';
- links.push(prevResultHtml);
+ var msgPrev = searchProps.msgPrevResultsTemplate.replace(/\$1/, maxResults)
+ var prevResultHtml = '<a href="' + prevResultUrl + '">' + msgPrev + '</a>'
+ links.push(prevResultHtml)
}
if ('nextOffset' in session) {
var nextResultUrl = baseUrl + '&offset=' + session.nextOffset +
- '&prev_offset=' + session.offset;
- var msgMore = searchProps.msgMoreResultsTemplate.replace(/\$1/, maxResults);
- var moreResultHtml = '<a href="' + nextResultUrl + '">' + msgMore + '</a>';
- links.push(moreResultHtml);
+ '&prev_offset=' + session.offset
+ var msgMore = searchProps.msgMoreResultsTemplate.replace(/\$1/, maxResults)
+ var moreResultHtml = '<a href="' + nextResultUrl + '">' + msgMore + '</a>'
+ links.push(moreResultHtml)
}
if (links.length > 0) {
- return links.join(' ');
+ return links.join(' ')
}
- return '';
+ return ''
}
- function prepareKanaMap() {
- if (kanaMap !== null) return;
+ function prepareKanaMap () {
+ if (kanaMap !== null) return
if (!String.prototype.normalize) {
- kanaMap = {};
- return;
+ kanaMap = {}
+ return
}
- var dakuten = '\uFF9E';
- var maru = '\uFF9F';
- var map = {};
+ var dakuten = '\uFF9E'
+ var maru = '\uFF9F'
+ var map = {}
for (var c = 0xFF61; c <= 0xFF9F; c++) {
- var han = String.fromCharCode(c);
- var zen = han.normalize('NFKC');
- map[zen] = han;
- var hanDaku = han + dakuten;
- var zenDaku = hanDaku.normalize('NFKC');
+ var han = String.fromCharCode(c)
+ var zen = han.normalize('NFKC')
+ map[zen] = han
+ var hanDaku = han + dakuten
+ var zenDaku = hanDaku.normalize('NFKC')
if (zenDaku.length === 1) { // +Handaku-ten OK
- map[zenDaku] = hanDaku;
+ map[zenDaku] = hanDaku
}
- var hanMaru = han + maru;
- var zenMaru = hanMaru.normalize('NFKC');
+ var hanMaru = han + maru
+ var zenMaru = hanMaru.normalize('NFKC')
if (zenMaru.length === 1) { // +Maru OK
- map[zenMaru] = hanMaru;
+ map[zenMaru] = hanMaru
}
}
- kanaMap = map;
+ kanaMap = map
}
/**
* @param {searchText} searchText
* @type RegExp
*/
- function textToRegex(searchText) {
- if (!searchText) return null;
+ function textToRegex (searchText) {
+ if (!searchText) return null
// 1:Symbol 2:Katakana 3:Hiragana
- var regRep = /([\\^$.*+?()[\]{}|])|([\u30a1-\u30f6])|([\u3041-\u3096])/g;
- var replacementFunc = function(m, m1, m2, m3) {
+ var regRep = /([\\^$.*+?()[\]{}|])|([\u30a1-\u30f6])|([\u3041-\u3096])/g
+ var replacementFunc = function (m, m1, m2, m3) {
if (m1) {
// Symbol - escape with prior backslach
- return '\\' + m1;
+ return '\\' + m1
} else if (m2) {
// Katakana
var r = '(?:' + String.fromCharCode(m2.charCodeAt(0) - 0x60) +
- '|' + m2;
+ '|' + m2
if (kanaMap[m2]) {
- r += '|' + kanaMap[m2];
+ r += '|' + kanaMap[m2]
}
- r += ')';
- return r;
+ r += ')'
+ return r
} else if (m3) {
// Hiragana
- var katakana = String.fromCharCode(m3.charCodeAt(0) + 0x60);
- var r2 = '(?:' + m3 + '|' + katakana;
+ var katakana = String.fromCharCode(m3.charCodeAt(0) + 0x60)
+ var r2 = '(?:' + m3 + '|' + katakana
if (kanaMap[katakana]) {
- r2 += '|' + kanaMap[katakana];
+ r2 += '|' + kanaMap[katakana]
}
- r2 += ')';
- return r2;
+ r2 += ')'
+ return r2
}
- return m;
- };
- var s1 = searchText.replace(/^\s+|\s+$/g, '');
- if (!s1) return null;
- var sp = s1.split(/\s+/);
- var rText = '';
- prepareKanaMap();
+ return m
+ }
+ var s1 = searchText.replace(/^\s+|\s+$/g, '')
+ if (!s1) return null
+ var sp = s1.split(/\s+/)
+ var rText = ''
+ prepareKanaMap()
for (var i = 0; i < sp.length; i++) {
if (rText !== '') {
- rText += '|';
+ rText += '|'
}
- var s = sp[i];
+ var s = sp[i]
if (s.normalize) {
- s = s.normalize('NFKC');
+ s = s.normalize('NFKC')
}
- var s2 = s.replace(regRep, replacementFunc);
- rText += '(' + s2 + ')';
+ var s2 = s.replace(regRep, replacementFunc)
+ rText += '(' + s2 + ')'
}
- return new RegExp(rText, 'ig');
+ return new RegExp(rText, 'ig')
}
/**
* @param {string} statusText
*/
- function setSearchStatus(statusText, statusText2) {
- var statusList = document.querySelectorAll('._plugin_search2_search_status');
- forEach(statusList, function(statusObj) {
- var textObj1 = statusObj.querySelector('._plugin_search2_search_status_text1');
- var textObj2 = statusObj.querySelector('._plugin_search2_search_status_text2');
+ function setSearchStatus (statusText, statusText2) {
+ var statusList = document.querySelectorAll('._plugin_search2_search_status')
+ forEach(statusList, function (statusObj) {
+ var textObj1 = statusObj.querySelector('._plugin_search2_search_status_text1')
+ var textObj2 = statusObj.querySelector('._plugin_search2_search_status_text2')
if (textObj1) {
- var prevText = textObj1.getAttribute('data-text');
+ var prevText = textObj1.getAttribute('data-text')
if (prevText !== statusText) {
- textObj1.setAttribute('data-text', statusText);
+ textObj1.setAttribute('data-text', statusText)
if (statusText.substr(statusText.length - 3) === '...') {
- var firstHalf = statusText.substr(0, statusText.length - 3);
- textObj1.textContent = firstHalf;
- var span = document.createElement('span');
- span.innerHTML = '<span class="plugin-search2-progress plugin-search2-progress1">.</span>'
- + '<span class="plugin-search2-progress plugin-search2-progress2">.</span>'
- + '<span class="plugin-search2-progress plugin-search2-progress3">.</span>';
- textObj1.appendChild(span);
+ var firstHalf = statusText.substr(0, statusText.length - 3)
+ textObj1.textContent = firstHalf
+ var span = document.createElement('span')
+ span.innerHTML = '<span class="plugin-search2-progress plugin-search2-progress1">.</span>' +
+ '<span class="plugin-search2-progress plugin-search2-progress2">.</span>' +
+ '<span class="plugin-search2-progress plugin-search2-progress3">.</span>'
+ textObj1.appendChild(span)
} else {
- textObj1.textContent = statusText;
+ textObj1.textContent = statusText
}
}
}
if (textObj2) {
if (statusText2) {
- textObj2.textContent = ' ' + statusText2;
+ textObj2.textContent = ' ' + statusText2
} else {
- textObj2.textContent = '';
+ textObj2.textContent = ''
}
}
- });
+ })
}
/**
* @param {string} msgHTML
*/
- function setSearchMessage(msgHTML) {
- var objList = document.querySelectorAll('._plugin_search2_message');
- forEach(objList, function(obj) {
- obj.innerHTML = msgHTML;
- });
+ function setSearchMessage (msgHTML) {
+ var objList = document.querySelectorAll('._plugin_search2_message')
+ forEach(objList, function (obj) {
+ obj.innerHTML = msgHTML
+ })
}
- function showSecondSearchForm() {
+ function showSecondSearchForm () {
// Show second search form
- var div = document.querySelector('._plugin_search2_second_form');
+ var div = document.querySelector('._plugin_search2_second_form')
if (div) {
- div.style.display = 'block';
+ div.style.display = 'block'
}
}
/**
* @param {Element} form
* @type string
*/
- function getSearchBase(form) {
- var f = form || document.querySelector('._plugin_search2_form');
- var base = '';
- forEach(f.querySelectorAll('input[name="base"]'), function(radio) {
- if (radio.checked) base = radio.value;
- });
- return base;
+ function getSearchBase (form) {
+ var f = form || document.querySelector('._plugin_search2_form')
+ var base = ''
+ forEach(f.querySelectorAll('input[name="base"]'), function (radio) {
+ if (radio.checked) base = radio.value
+ })
+ return base
}
/**
* Decorate found block (for pre innerHTML)
* @param {Object} block
* @param {RegExp} searchRegex
*/
- function decorateFoundBlock(block, searchRegex) {
- var lines = [];
+ function decorateFoundBlock (block, searchRegex) {
+ var lines = []
for (var j = 0; j < block.lines.length; j++) {
- var line = block.lines[j];
- var decorated = findAndDecorateText(line, searchRegex);
+ var line = block.lines[j]
+ var decorated = findAndDecorateText(line, searchRegex)
if (decorated === null) {
- lines.push('' + (block.startIndex + j + 1) + ':\t' + escapeHTML(line));
+ lines.push('' + (block.startIndex + j + 1) + ':\t' + escapeHTML(line))
} else {
- lines.push('' + (block.startIndex + j + 1) + ':\t' + decorated);
+ lines.push('' + (block.startIndex + j + 1) + ':\t' + decorated)
}
}
if (block.beyondLimit) {
- lines.push('...');
+ lines.push('...')
}
- return lines.join('\n');
+ return lines.join('\n')
}
/**
* @param {string} body
* @param {RegExp} searchRegex
*/
- function getSummaryInfo(body, searchRegex) {
- var lines = body.split('\n');
- var foundLines = [];
- var isInAuthorHeader = true;
- var lastFoundLineIndex = -1 - aroundLines;
- var lastAddedLineIndex = lastFoundLineIndex;
- var blocks = [];
- var lineCount = 0;
- var currentBlock = null;
+ function getSummaryInfo (body, searchRegex) {
+ var lines = body.split('\n')
+ var foundLines = []
+ var isInAuthorHeader = true
+ var lastFoundLineIndex = -1 - aroundLines
+ var lastAddedLineIndex = lastFoundLineIndex
+ var blocks = []
+ var lineCount = 0
+ var currentBlock = null
for (var index = 0, length = lines.length; index < length; index++) {
- var line = lines[index];
+ var line = lines[index]
if (isInAuthorHeader) {
// '#author line is not search target'
if (line.match(/^#author\(/)) {
// Remove this line from search target
- continue;
+ continue
} else if (line.match(/^#freeze(\W|$)/)) {
// Still in header
} else {
// Already in body
- isInAuthorHeader = false;
+ isInAuthorHeader = false
}
}
- var match = line.match(searchRegex);
+ var match = line.match(searchRegex)
if (!match) {
if (index < lastFoundLineIndex + aroundLines + 1) {
- foundLines.push(lines[index]);
- lineCount++;
- lastAddedLineIndex = index;
+ foundLines.push(lines[index])
+ lineCount++
+ lastAddedLineIndex = index
}
} else {
- var startIndex = Math.max(Math.max(lastAddedLineIndex + 1, index - aroundLines), 0);
+ var startIndex = Math.max(Math.max(lastAddedLineIndex + 1, index - aroundLines), 0)
if (lastAddedLineIndex + 1 < startIndex) {
// Newly found!
var block = {
startIndex: startIndex,
foundLineIndex: index,
lines: []
- };
- currentBlock = block;
- foundLines = block.lines;
- blocks.push(block);
+ }
+ currentBlock = block
+ foundLines = block.lines
+ blocks.push(block)
}
if (lineCount >= maxResultLines) {
- currentBlock.beyondLimit = true;
- return blocks;
+ currentBlock.beyondLimit = true
+ return blocks
}
for (var i = startIndex; i < index; i++) {
- foundLines.push(lines[i]);
- lineCount++;
+ foundLines.push(lines[i])
+ lineCount++
}
- foundLines.push(line);
- lineCount++;
- lastFoundLineIndex = lastAddedLineIndex = index;
+ foundLines.push(line)
+ lineCount++
+ lastFoundLineIndex = lastAddedLineIndex = index
}
}
- return blocks;
+ return blocks
}
/**
* @param {Date} now
* @param {string} dateText
*/
- function getPassage(now, dateText) {
+ function getPassage (now, dateText) {
if (!dateText) {
- return '';
+ return ''
}
- var units = [{u: 'm', max: 60}, {u: 'h', max: 24}, {u: 'd', max: 1}];
- var d = new Date();
- d.setTime(Date.parse(dateText));
- var t = (now.getTime() - d.getTime()) / (1000 * 60); // minutes
- var unit = units[0].u; var card = units[0].max;
+ var units = [{ u: 'm', max: 60 }, { u: 'h', max: 24 }, { u: 'd', max: 1 }]
+ var d = new Date()
+ d.setTime(Date.parse(dateText))
+ var t = (now.getTime() - d.getTime()) / (1000 * 60) // minutes
+ var unit = units[0].u; var card = units[0].max
for (var i = 0; i < units.length; i++) {
- unit = units[i].u; card = units[i].max;
- if (t < card) break;
- t = t / card;
+ unit = units[i].u; card = units[i].max
+ if (t < card) break
+ t = t / card
}
- return '(' + Math.floor(t) + unit + ')';
+ return '(' + Math.floor(t) + unit + ')'
}
/**
* @param {string} searchText
*/
- function removeSearchOperators(searchText) {
- var sp = searchText.split(/\s+/);
+ function removeSearchOperators (searchText) {
+ var sp = searchText.split(/\s+/)
if (sp.length <= 1) {
- return searchText;
+ return searchText
}
for (var i = sp.length - 2; i >= 1; i--) {
if (sp[i] === 'OR') {
- sp.splice(i, 1);
+ sp.splice(i, 1)
}
}
- return sp.join(' ');
+ return sp.join(' ')
}
/**
* @param {string} pathname
*/
- function getSearchCacheKeyBase(pathname) {
- return 'path.' + pathname + '.search2.';
+ function getSearchCacheKeyBase (pathname) {
+ return 'path.' + pathname + '.search2.'
}
/**
* @param {string} pathname
*/
- function getSearchCacheKeyDateBase(pathname) {
- var now = new Date();
- var dateKey = now.getFullYear() + '_0' + (now.getMonth() + 1) + '_0' + now.getDate();
- dateKey = dateKey.replace(/_\d?(\d\d)/g, '$1');
- return getSearchCacheKeyBase(pathname) + dateKey + '.';
+ function getSearchCacheKeyDateBase (pathname) {
+ var now = new Date()
+ var dateKey = now.getFullYear() + '_0' + (now.getMonth() + 1) + '_0' + now.getDate()
+ dateKey = dateKey.replace(/_\d?(\d\d)/g, '$1')
+ return getSearchCacheKeyBase(pathname) + dateKey + '.'
}
/**
* @param {string} pathname
* @param {string} searchText
* @param {number} offset
*/
- function getSearchCacheKey(pathname, searchText, offset) {
+ function getSearchCacheKey (pathname, searchText, offset) {
return getSearchCacheKeyDateBase(pathname) + 'offset=' + offset +
- '.' + searchText;
+ '.' + searchText
}
/**
* @param {string} pathname
* @param {string} searchText
*/
- function clearSingleCache(pathname, searchText) {
- if (!window.localStorage) return;
- var removeTargets = [];
- var keyBase = getSearchCacheKeyDateBase(pathname);
+ function clearSingleCache (pathname, searchText) {
+ if (!window.localStorage) return
+ var removeTargets = []
+ var keyBase = getSearchCacheKeyDateBase(pathname)
for (var i = 0, n = localStorage.length; i < n; i++) {
- var key = localStorage.key(i);
+ var key = localStorage.key(i)
if (key.substr(0, keyBase.length) === keyBase) {
// Search result Cache
- var subKey = key.substr(keyBase.length);
- var m = subKey.match(/^offset=\d+\.(.+)$/);
+ var subKey = key.substr(keyBase.length)
+ var m = subKey.match(/^offset=\d+\.(.+)$/)
if (m && m[1] === searchText) {
- removeTargets.push(key);
+ removeTargets.push(key)
}
}
}
- removeTargets.forEach(function(target) {
- localStorage.removeItem(target);
- });
+ removeTargets.forEach(function (target) {
+ localStorage.removeItem(target)
+ })
}
/**
* @param {string} body
*/
- function getBodySummary(body) {
- var lines = body.split('\n');
- var isInAuthorHeader = true;
- var summary = [];
+ function getBodySummary (body) {
+ var lines = body.split('\n')
+ var isInAuthorHeader = true
+ var summary = []
for (var index = 0, length = lines.length; index < length; index++) {
- var line = lines[index];
+ var line = lines[index]
if (isInAuthorHeader) {
// '#author line is not search target'
if (line.match(/^#author\(/)) {
// Remove this line from search target
- continue;
+ continue
} else if (line.match(/^#freeze(\W|$)/)) {
- continue;
+ continue
// Still in header
} else {
// Already in body
- isInAuthorHeader = false;
+ isInAuthorHeader = false
}
}
- line = line.replace(/^\s+|\s+$/g, '');
- if (line.length === 0) continue; // Empty line
- if (line.match(/^#\w+/)) continue; // Block-type plugin
- if (line.match(/^\/\//)) continue; // Comment
+ line = line.replace(/^\s+|\s+$/g, '')
+ if (line.length === 0) continue // Empty line
+ if (line.match(/^#\w+/)) continue // Block-type plugin
+ if (line.match(/^\/\//)) continue // Comment
if (line.substr(0, 1) === '*') {
- line = line.replace(/\s*\[#\w+\]$/, ''); // Remove anchor
+ line = line.replace(/\s*\[#\w+\]$/, '') // Remove anchor
}
- summary.push(line);
+ summary.push(line)
if (summary.length >= 10) {
- continue;
+ continue
}
}
- return summary.join(' ').substring(0, 150);
+ return summary.join(' ').substring(0, 150)
}
/**
* @param {string} q searchText
*/
- function encodeSearchText(q) {
- var sp = q.split(/\s+/);
+ function encodeSearchText (q) {
+ var sp = q.split(/\s+/)
for (var i = 0; i < sp.length; i++) {
- sp[i] = encodeURIComponent(sp[i]);
+ sp[i] = encodeURIComponent(sp[i])
}
- return sp.join('+');
+ return sp.join('+')
}
/**
* @param {string} q searchText
*/
- function encodeSearchTextForHash(q) {
- var sp = q.split(/\s+/);
- return sp.join('+');
+ function encodeSearchTextForHash (q) {
+ var sp = q.split(/\s+/)
+ return sp.join('+')
}
- function getSearchTextInLocationHash() {
- var hash = document.location.hash;
- if (!hash) return '';
- var q = '';
+ function getSearchTextInLocationHash () {
+ var hash = document.location.hash
+ if (!hash) return ''
+ var q = ''
if (hash.substr(0, 3) === '#q=') {
- q = hash.substr(3).replace(/\+/g, ' ');
+ q = hash.substr(3).replace(/\+/g, ' ')
} else {
- return '';
+ return ''
}
- var decodedQ = decodeURIComponent(q);
+ var decodedQ = decodeURIComponent(q)
if (q !== decodedQ) {
- q = decodedQ + ' OR ' + q;
+ q = decodedQ + ' OR ' + q
}
- return q;
+ return q
}
- function colorSearchTextInBody() {
- var searchText = getSearchTextInLocationHash();
- if (!searchText) return;
- var searchRegex = textToRegex(removeSearchOperators(searchText));
- if (!searchRegex) return;
+ function colorSearchTextInBody () {
+ var searchText = getSearchTextInLocationHash()
+ if (!searchText) return
+ var searchRegex = textToRegex(removeSearchOperators(searchText))
+ if (!searchRegex) return
var ignoreTags = ['INPUT', 'TEXTAREA', 'BUTTON',
- 'SCRIPT', 'FRAME', 'IFRAME'];
+ 'SCRIPT', 'FRAME', 'IFRAME']
/**
* @param {Element} element
*/
- function colorSearchText(element) {
- var decorated = findAndDecorateText(element.nodeValue, searchRegex);
+ function colorSearchText (element) {
+ var decorated = findAndDecorateText(element.nodeValue, searchRegex)
if (decorated) {
- var span = document.createElement('span');
- span.innerHTML = decorated;
- element.parentNode.replaceChild(span, element);
+ var span = document.createElement('span')
+ span.innerHTML = decorated
+ element.parentNode.replaceChild(span, element)
}
}
/**
* @param {Element} element
*/
- function walkElement(element) {
- var e = element.firstChild;
+ function walkElement (element) {
+ var e = element.firstChild
while (e) {
if (e.nodeType === 3 && e.nodeValue &&
e.nodeValue.length >= 2 && /\S/.test(e.nodeValue)) {
- var next = e.nextSibling;
- colorSearchText(e, searchRegex);
- e = next;
+ var next = e.nextSibling
+ colorSearchText(e, searchRegex)
+ e = next
} else {
if (e.nodeType === 1 && ignoreTags.indexOf(e.tagName) === -1) {
- walkElement(e);
+ walkElement(e)
}
- e = e.nextSibling;
+ e = e.nextSibling
}
}
}
- var target = document.getElementById('body');
- walkElement(target);
+ var target = document.getElementById('body')
+ walkElement(target)
}
/**
* @param {Array<Object>} newResults
* @param {Element} ul
*/
- function removePastResults(newResults, ul) {
- var removedCount = 0;
- var nodes = ul.childNodes;
+ function removePastResults (newResults, ul) {
+ var removedCount = 0
+ var nodes = ul.childNodes
for (var i = nodes.length - 1; i >= 0; i--) {
- var node = nodes[i];
- if (node.tagName !== 'LI' && node.tagName !== 'DIV') continue;
- var nodePagename = node.getAttribute('data-pagename');
- var isRemoveTarget = false;
+ var node = nodes[i]
+ if (node.tagName !== 'LI' && node.tagName !== 'DIV') continue
+ var nodePagename = node.getAttribute('data-pagename')
+ var isRemoveTarget = false
for (var j = 0, n = newResults.length; j < n; j++) {
- var r = newResults[j];
+ var r = newResults[j]
if (r.name === nodePagename) {
- isRemoveTarget = true;
- break;
+ isRemoveTarget = true
+ break
}
}
if (isRemoveTarget) {
if (node.tagName === 'LI') {
- removedCount++;
+ removedCount++
}
- ul.removeChild(node);
+ ul.removeChild(node)
}
}
- return removedCount;
+ return removedCount
}
/**
* @param {Array<Object>} results
* @param {Element} parentUlElement
* @param {boolean} insertTop
*/
- function addSearchResult(results, searchText, searchRegex, parentUlElement, insertTop) {
- var props = getSiteProps();
- var now = new Date();
- var parentFragment = document.createDocumentFragment();
- results.forEach(function(val) {
- var li = document.createElement('li');
- var hash = '#q=' + encodeSearchTextForHash(searchText);
- var href = val.url + hash;
- var decoratedName = findAndDecorateText(val.name, searchRegex);
+ function addSearchResult (results, searchText, searchRegex, parentUlElement, insertTop) {
+ var props = getSiteProps()
+ var now = new Date()
+ var parentFragment = document.createDocumentFragment()
+ results.forEach(function (val) {
+ var li = document.createElement('li')
+ var hash = '#q=' + encodeSearchTextForHash(searchText)
+ var href = val.url + hash
+ var decoratedName = findAndDecorateText(val.name, searchRegex)
if (!decoratedName) {
- decoratedName = escapeHTML(val.name);
+ decoratedName = escapeHTML(val.name)
}
- var updatedAt = val.updatedAt;
- var passageHtml = '';
+ var updatedAt = val.updatedAt
+ var passageHtml = ''
if (props.show_passage) {
- passageHtml = ' ' + getPassage(now, updatedAt);
+ passageHtml = ' ' + getPassage(now, updatedAt)
}
var liHtml = '<a href="' + escapeHTML(href) + '">' +
- decoratedName + '</a>' + passageHtml;
- li.innerHTML = liHtml;
- li.setAttribute('data-pagename', val.name);
+ decoratedName + '</a>' + passageHtml
+ li.innerHTML = liHtml
+ li.setAttribute('data-pagename', val.name)
// Page detail div
- var div = document.createElement('div');
- div.classList.add('search-result-detail');
- var head = document.createElement('div');
- head.classList.add('search-result-page-summary');
- head.innerHTML = escapeHTML(val.bodySummary);
- div.appendChild(head);
- var summaryInfo = val.hitSummary;
+ var div = document.createElement('div')
+ div.classList.add('search-result-detail')
+ var head = document.createElement('div')
+ head.classList.add('search-result-page-summary')
+ head.innerHTML = escapeHTML(val.bodySummary)
+ div.appendChild(head)
+ var summaryInfo = val.hitSummary
for (var i = 0; i < summaryInfo.length; i++) {
- var pre = document.createElement('pre');
- pre.innerHTML = decorateFoundBlock(summaryInfo[i], searchRegex);
- div.appendChild(pre);
+ var pre = document.createElement('pre')
+ pre.innerHTML = decorateFoundBlock(summaryInfo[i], searchRegex)
+ div.appendChild(pre)
}
- div.setAttribute('data-pagename', val.name);
+ div.setAttribute('data-pagename', val.name)
// Add li to ul (parentUlElement)
- li.appendChild(div);
- parentFragment.appendChild(li);
- });
+ li.appendChild(div)
+ parentFragment.appendChild(li)
+ })
if (insertTop && parentUlElement.firstChild) {
- parentUlElement.insertBefore(parentFragment, parentUlElement.firstChild);
+ parentUlElement.insertBefore(parentFragment, parentUlElement.firstChild)
} else {
- parentUlElement.appendChild(parentFragment);
+ parentUlElement.appendChild(parentFragment)
}
}
- function removeCachedResultsBase(keepTodayCache) {
- var props = getSiteProps();
- if (!props || !props.base_uri_pathname) return;
- var keyPrefix = getSearchCacheKeyDateBase(props.base_uri_pathname);
- var keyBase = getSearchCacheKeyBase(props.base_uri_pathname);
- var removeTargets = [];
+ function removeCachedResultsBase (keepTodayCache) {
+ var props = getSiteProps()
+ if (!props || !props.base_uri_pathname) return
+ var keyPrefix = getSearchCacheKeyDateBase(props.base_uri_pathname)
+ var keyBase = getSearchCacheKeyBase(props.base_uri_pathname)
+ var removeTargets = []
for (var i = 0, n = localStorage.length; i < n; i++) {
- var key = localStorage.key(i);
+ var key = localStorage.key(i)
if (key.substr(0, keyBase.length) === keyBase) {
// Search result Cache
if (keepTodayCache) {
if (key.substr(0, keyPrefix.length) !== keyPrefix) {
- removeTargets.push(key);
+ removeTargets.push(key)
}
} else {
- removeTargets.push(key);
+ removeTargets.push(key)
}
}
}
- removeTargets.forEach(function(target) {
- localStorage.removeItem(target);
- });
+ removeTargets.forEach(function (target) {
+ localStorage.removeItem(target)
+ })
}
- function removeCachedResults() {
- removeCachedResultsBase(true);
+ function removeCachedResults () {
+ removeCachedResultsBase(true)
}
- function removeAllCachedResults() {
- removeCachedResultsBase(false);
+ function removeAllCachedResults () {
+ removeCachedResultsBase(false)
}
/**
* @param {Object} obj
* @param {string} searchText
* @param {number} prevTimestamp
*/
- function showResult(obj, session, searchText, prevTimestamp) {
- var props = getSiteProps();
- var searchRegex = textToRegex(removeSearchOperators(searchText));
- var ul = document.querySelector('#_plugin_search2_result-list');
- if (!ul) return;
+ function showResult (obj, session, searchText, prevTimestamp) {
+ var props = getSiteProps()
+ var searchRegex = textToRegex(removeSearchOperators(searchText))
+ var ul = document.querySelector('#_plugin_search2_result-list')
+ if (!ul) return
if (obj.start_index === 0 && !prevTimestamp) {
- ul.innerHTML = '';
+ ul.innerHTML = ''
}
- var searchDone = obj.search_done;
- if (!session.scanPageCount) session.scanPageCount = 0;
- if (!session.readPageCount) session.readPageCount = 0;
- if (!session.hitPageCount) session.hitPageCount = 0;
- var prevHitPageCount = session.hitPageCount;
- session.hitPageCount += obj.results.length;
+ var searchDone = obj.search_done
+ if (!session.scanPageCount) session.scanPageCount = 0
+ if (!session.readPageCount) session.readPageCount = 0
+ if (!session.hitPageCount) session.hitPageCount = 0
+ var prevHitPageCount = session.hitPageCount
+ session.hitPageCount += obj.results.length
if (!prevTimestamp) {
- session.scanPageCount += obj.scan_page_count;
- session.readPageCount += obj.read_page_count;
- session.pageCount = obj.page_count;
+ session.scanPageCount += obj.scan_page_count
+ session.readPageCount += obj.read_page_count
+ session.pageCount = obj.page_count
}
- session.searchStartTime = obj.search_start_time;
- session.authUser = obj.auth_user;
+ session.searchStartTime = obj.search_start_time
+ session.authUser = obj.auth_user
if (prevHitPageCount === 0 && session.hitPageCount > 0) {
- showSecondSearchForm();
+ showSecondSearchForm()
}
- var results = obj.results;
- var cachedResults = [];
- results.forEach(function(val) {
- var cache = {};
- cache.name = val.name;
- cache.url = val.url;
- cache.updatedAt = val.updated_at;
- cache.updatedTime = val.updated_time;
- cache.bodySummary = getBodySummary(val.body);
- cache.hitSummary = getSummaryInfo(val.body, searchRegex);
- cachedResults.push(cache);
- });
+ var results = obj.results
+ var cachedResults = []
+ results.forEach(function (val) {
+ var cache = {}
+ cache.name = val.name
+ cache.url = val.url
+ cache.updatedAt = val.updated_at
+ cache.updatedTime = val.updated_time
+ cache.bodySummary = getBodySummary(val.body)
+ cache.hitSummary = getSummaryInfo(val.body, searchRegex)
+ cachedResults.push(cache)
+ })
if (prevTimestamp) {
- var removedCount = removePastResults(cachedResults, ul);
- session.hitPageCount -= removedCount;
+ var removedCount = removePastResults(cachedResults, ul)
+ session.hitPageCount -= removedCount
}
- var msg = getSearchResultMessage(session, searchText, searchRegex, !searchDone);
- setSearchMessage(msg);
+ var msg = getSearchResultMessage(session, searchText, searchRegex, !searchDone)
+ setSearchMessage(msg)
if (prevTimestamp) {
- setSearchStatus(searchProps.searchingMsg);
+ setSearchStatus(searchProps.searchingMsg)
} else {
setSearchStatus(searchProps.searchingMsg,
- getSearchProgress(session));
+ getSearchProgress(session))
}
if (searchDone) {
- var singlePageResult = session.offset === 0 && !session.nextOffset;
- var progress = getSearchProgress(session);
- setTimeout(function() {
+ var singlePageResult = session.offset === 0 && !session.nextOffset
+ var progress = getSearchProgress(session)
+ setTimeout(function () {
if (singlePageResult) {
- setSearchStatus('');
+ setSearchStatus('')
} else {
- setSearchStatus(searchProps.showingResultMsg, progress);
+ setSearchStatus(searchProps.showingResultMsg, progress)
}
- }, 2000);
+ }, 2000)
}
if (session.results) {
if (prevTimestamp) {
- var newResult = [].concat(cachedResults);
- Array.prototype.push.apply(newResult, session.results);
- session.results = newResult;
+ var newResult = [].concat(cachedResults)
+ Array.prototype.push.apply(newResult, session.results)
+ session.results = newResult
} else {
- Array.prototype.push.apply(session.results, cachedResults);
+ Array.prototype.push.apply(session.results, cachedResults)
}
} else {
- session.results = cachedResults;
+ session.results = cachedResults
}
- addSearchResult(cachedResults, searchText, searchRegex, ul, prevTimestamp);
- var maxResults = searchProps.maxResults;
+ addSearchResult(cachedResults, searchText, searchRegex, ul, prevTimestamp)
+ var maxResults = searchProps.maxResults
if (searchDone) {
- session.searchText = searchText;
- var prevOffset = searchProps.prevOffset;
+ session.searchText = searchText
+ var prevOffset = searchProps.prevOffset
if (prevOffset) {
- session.prevOffset = parseInt(prevOffset, 10);
+ session.prevOffset = parseInt(prevOffset, 10)
}
- var json = JSON.stringify(session);
- var cacheKey = getSearchCacheKey(props.base_uri_pathname, searchText, session.offset);
+ var json = JSON.stringify(session)
+ var cacheKey = getSearchCacheKey(props.base_uri_pathname, searchText, session.offset)
if (window.localStorage) {
try {
- localStorage[cacheKey] = json;
+ localStorage[cacheKey] = json
} catch (e) {
// QuotaExceededError "exceeded the quota."
- console.log(e);
- removeAllCachedResults();
+ console.log(e)
+ removeAllCachedResults()
}
}
if ('prevOffset' in session || 'nextOffset' in session) {
- setSearchMessage(msg + ' ' + getOffsetLinks(session, maxResults));
+ setSearchMessage(msg + ' ' + getOffsetLinks(session, maxResults))
}
}
if (!searchDone && obj.next_start_index) {
if (session.results.length >= maxResults) {
// Save results
- session.nextOffset = obj.next_start_index;
- var prevOffset2 = searchProps.prevOffset;
+ session.nextOffset = obj.next_start_index
+ var prevOffset2 = searchProps.prevOffset
if (prevOffset2) {
- session.prevOffset = parseInt(prevOffset2, 10);
+ session.prevOffset = parseInt(prevOffset2, 10)
}
- var key = getSearchCacheKey(props.base_uri_pathname, searchText, session.offset);
- localStorage[key] = JSON.stringify(session);
+ var key = getSearchCacheKey(props.base_uri_pathname, searchText, session.offset)
+ localStorage[key] = JSON.stringify(session)
// Stop API calling
- setSearchMessage(msg + ' ' + getOffsetLinks(session, maxResults));
+ setSearchMessage(msg + ' ' + getOffsetLinks(session, maxResults))
setSearchStatus(searchProps.showingResultMsg,
- getSearchProgress(session));
+ getSearchProgress(session))
} else {
- setTimeout(function() {
+ setTimeout(function () {
doSearch(searchText, // eslint-disable-line no-use-before-define
session, obj.next_start_index,
- obj.search_start_time);
- }, searchProps.searchInterval);
+ obj.search_start_time)
+ }, searchProps.searchInterval)
}
}
}
* @param {string} base
* @param {number} offset
*/
- function showCachedResult(searchText, base, offset) {
- var props = getSiteProps();
- var searchRegex = textToRegex(removeSearchOperators(searchText));
- var ul = document.querySelector('#_plugin_search2_result-list');
- if (!ul) return null;
- var searchCacheKey = getSearchCacheKey(props.base_uri_pathname, searchText, offset);
- var cache1 = localStorage[searchCacheKey];
+ function showCachedResult (searchText, base, offset) {
+ var props = getSiteProps()
+ var searchRegex = textToRegex(removeSearchOperators(searchText))
+ var ul = document.querySelector('#_plugin_search2_result-list')
+ if (!ul) return null
+ var searchCacheKey = getSearchCacheKey(props.base_uri_pathname, searchText, offset)
+ var cache1 = localStorage[searchCacheKey]
if (!cache1) {
- return null;
+ return null
}
- var session = JSON.parse(cache1);
- if (!session) return null;
+ var session = JSON.parse(cache1)
+ if (!session) return null
if (base !== session.base) {
- return null;
+ return null
}
- var user = searchProps.user;
+ var user = searchProps.user
if (user !== session.authUser) {
- return null;
+ return null
}
if (session.hitPageCount > 0) {
- showSecondSearchForm();
+ showSecondSearchForm()
}
- var msg = getSearchResultMessage(session, searchText, searchRegex, false);
- setSearchMessage(msg);
- addSearchResult(session.results, searchText, searchRegex, ul);
- var maxResults = searchProps.maxResults;
+ var msg = getSearchResultMessage(session, searchText, searchRegex, false)
+ setSearchMessage(msg)
+ addSearchResult(session.results, searchText, searchRegex, ul)
+ var maxResults = searchProps.maxResults
if ('prevOffset' in session || 'nextOffset' in session) {
- var moreResultHtml = getOffsetLinks(session, maxResults);
- setSearchMessage(msg + ' ' + moreResultHtml);
- var progress = getSearchProgress(session);
- setSearchStatus(searchProps.showingResultMsg, progress);
+ var moreResultHtml = getOffsetLinks(session, maxResults)
+ setSearchMessage(msg + ' ' + moreResultHtml)
+ var progress = getSearchProgress(session)
+ setSearchStatus(searchProps.showingResultMsg, progress)
} else {
- setSearchStatus('');
+ setSearchStatus('')
}
- return session;
+ return session
}
/**
* @param {string} searchText
* @param {number} searchStartTime
* @param {number} prevTimestamp
*/
- function doSearch(searchText, session, startIndex, searchStartTime, prevTimestamp) {
- var props = getSiteProps();
- var baseUrl = './';
+ function doSearch (searchText, session, startIndex, searchStartTime, prevTimestamp) {
+ var props = getSiteProps()
+ var baseUrl = './'
if (props.base_uri_pathname) {
- baseUrl = props.base_uri_pathname;
+ baseUrl = props.base_uri_pathname
}
- var url = baseUrl + '?cmd=search2&action=query';
- url += '&encode_hint=' + encodeURIComponent('\u3077');
+ var url = baseUrl + '?cmd=search2&action=query'
+ url += '&encode_hint=' + encodeURIComponent('\u3077')
if (searchText) {
- url += '&q=' + encodeURIComponent(searchText);
+ url += '&q=' + encodeURIComponent(searchText)
}
if (session.base) {
- url += '&base=' + encodeURIComponent(session.base);
+ url += '&base=' + encodeURIComponent(session.base)
}
if (prevTimestamp) {
- url += '&modified_since=' + prevTimestamp;
+ url += '&modified_since=' + prevTimestamp
} else {
- url += '&start=' + startIndex;
+ url += '&start=' + startIndex
if (searchStartTime) {
- url += '&search_start_time=' + encodeURIComponent(searchStartTime);
+ url += '&search_start_time=' + encodeURIComponent(searchStartTime)
}
if (!('offset' in session)) {
- session.offset = startIndex;
+ session.offset = startIndex
}
}
- fetch(url, {credentials: 'same-origin'}
- ).then(function(response) {
+ fetch(url, { credentials: 'same-origin' }
+ ).then(function (response) {
if (response.ok) {
- return response.json();
+ return response.json()
}
throw new Error(response.status + ': ' +
- response.statusText + ' on ' + url);
- }).then(function(obj) {
- showResult(obj, session, searchText, prevTimestamp);
- })['catch'](function(err) { // eslint-disable-line dot-notation
+ response.statusText + ' on ' + url)
+ }).then(function (obj) {
+ showResult(obj, session, searchText, prevTimestamp)
+ })['catch'](function (err) { // eslint-disable-line dot-notation
if (window.console && console.log) {
- console.log(err);
- console.log('Error! Please check JavaScript console\n' + JSON.stringify(err) + '|' + err);
+ console.log(err)
+ console.log('Error! Please check JavaScript console\n' + JSON.stringify(err) + '|' + err)
}
- setSearchStatus(searchProps.errorMsg);
- });
+ setSearchStatus(searchProps.errorMsg)
+ })
}
- function hookSearch2() {
- var form = document.querySelector('form');
+ function hookSearch2 () {
+ var form = document.querySelector('form')
if (form && form.q) {
- var q = form.q;
+ var q = form.q
if (q.value === '') {
- q.focus();
+ q.focus()
}
}
}
- function removeEncodeHint() {
+ function removeEncodeHint () {
// Remove 'encode_hint' if site charset is UTF-8
- var props = getSiteProps();
- if (!props.is_utf8) return;
- var forms = document.querySelectorAll('form');
- forEach(forms, function(form) {
+ var props = getSiteProps()
+ if (!props.is_utf8) return
+ var forms = document.querySelectorAll('form')
+ forEach(forms, function (form) {
if (form.cmd && form.cmd.value === 'search2') {
if (form.encode_hint && (typeof form.encode_hint.removeAttribute === 'function')) {
- form.encode_hint.removeAttribute('name');
+ form.encode_hint.removeAttribute('name')
}
}
- });
+ })
}
- function kickFirstSearch() {
- var form = document.querySelector('._plugin_search2_form');
- var searchText = form && form.q;
- if (!searchText) return;
+ function kickFirstSearch () {
+ var form = document.querySelector('._plugin_search2_form')
+ var searchText = form && form.q
+ if (!searchText) return
if (searchText && searchText.value) {
- var offset = searchProps.offset;
- var base = getSearchBase(form);
- var prevSession = showCachedResult(searchText.value, base, offset);
+ var offset = searchProps.offset
+ var base = getSearchBase(form)
+ var prevSession = showCachedResult(searchText.value, base, offset)
if (prevSession) {
// Display Cache results, then search only modified pages
if (!('offset' in prevSession) || prevSession.offset === 0) {
doSearch(searchText.value, prevSession, offset, null,
- prevSession.searchStartTime);
+ prevSession.searchStartTime)
} else {
// Show search results
}
} else {
- doSearch(searchText.value, {base: base, offset: offset}, offset, null);
+ doSearch(searchText.value, { base: base, offset: offset }, offset, null)
}
- removeCachedResults();
+ removeCachedResults()
}
}
- function replaceSearchWithSearch2() {
- forEach(document.querySelectorAll('form'), function(f) {
- function onAndRadioClick() {
- var sp = removeSearchOperators(f.word.value).split(/\s+/);
- var newText = sp.join(' ');
+ function replaceSearchWithSearch2 () {
+ forEach(document.querySelectorAll('form'), function (f) {
+ function onAndRadioClick () {
+ var sp = removeSearchOperators(f.word.value).split(/\s+/)
+ var newText = sp.join(' ')
if (f.word.value !== newText) {
- f.word.value = newText;
+ f.word.value = newText
}
}
- function onOrRadioClick() {
- var sp = removeSearchOperators(f.word.value).split(/\s+/);
- var newText = sp.join(' OR ');
+ function onOrRadioClick () {
+ var sp = removeSearchOperators(f.word.value).split(/\s+/)
+ var newText = sp.join(' OR ')
if (f.word.value !== newText) {
- f.word.value = newText;
+ f.word.value = newText
}
}
if (f.action.match(/cmd=search$/)) {
- f.addEventListener('submit', function(e) {
- var q = e.target.word.value;
- var base = '';
- forEach(f.querySelectorAll('input[name="base"]'), function(radio) {
- if (radio.checked) base = radio.value;
- });
- var props = getSiteProps();
- var loc = document.location;
- var baseUri = loc.protocol + '//' + loc.host + loc.pathname;
+ f.addEventListener('submit', function (e) {
+ var q = e.target.word.value
+ var base = ''
+ forEach(f.querySelectorAll('input[name="base"]'), function (radio) {
+ if (radio.checked) base = radio.value
+ })
+ var props = getSiteProps()
+ var loc = document.location
+ var baseUri = loc.protocol + '//' + loc.host + loc.pathname
if (props.base_uri_pathname) {
- baseUri = props.base_uri_pathname;
+ baseUri = props.base_uri_pathname
}
var url = baseUri + '?' +
(props.is_utf8 ? '' : 'encode_hint=' +
encodeURIComponent('\u3077') + '&') +
'cmd=search2' +
'&q=' + encodeSearchText(q) +
- (base ? '&base=' + encodeURIComponent(base) : '');
- e.preventDefault();
- setTimeout(function() {
- window.location.href = url;
- }, 1);
- return false;
- });
- var radios = f.querySelectorAll('input[type="radio"][name="type"]');
- forEach(radios, function(radio) {
+ (base ? '&base=' + encodeURIComponent(base) : '')
+ e.preventDefault()
+ setTimeout(function () {
+ window.location.href = url
+ }, 1)
+ return false
+ })
+ var radios = f.querySelectorAll('input[type="radio"][name="type"]')
+ forEach(radios, function (radio) {
if (radio.value === 'AND') {
- radio.addEventListener('click', onAndRadioClick);
+ radio.addEventListener('click', onAndRadioClick)
} else if (radio.value === 'OR') {
- radio.addEventListener('click', onOrRadioClick);
+ radio.addEventListener('click', onOrRadioClick)
}
- });
+ })
} else if (f.cmd && f.cmd.value === 'search2') {
- f.addEventListener('submit', function() {
- var newSearchText = f.q.value;
- var prevSearchText = f.q.getAttribute('data-original-q');
+ f.addEventListener('submit', function () {
+ var newSearchText = f.q.value
+ var prevSearchText = f.q.getAttribute('data-original-q')
if (newSearchText === prevSearchText) {
// Clear resultCache to search same text again
- var props = getSiteProps();
- clearSingleCache(props.base_uri_pathname, prevSearchText);
+ var props = getSiteProps()
+ clearSingleCache(props.base_uri_pathname, prevSearchText)
}
- });
+ })
}
- });
+ })
}
- function showNoSupportMessage() {
- var pList = document.getElementsByClassName('_plugin_search2_nosupport_message');
+ function showNoSupportMessage () {
+ var pList = document.getElementsByClassName('_plugin_search2_nosupport_message')
for (var i = 0; i < pList.length; i++) {
- var p = pList[i];
- p.style.display = 'block';
+ var p = pList[i]
+ p.style.display = 'block'
}
}
- function isEnabledFetchFunctions() {
+ function isEnabledFetchFunctions () {
if (window.fetch && document.querySelector && window.JSON) {
- return true;
+ return true
}
- return false;
+ return false
}
- function isEnableServerFunctions() {
- var props = getSiteProps();
- if (props.json_enabled) return true;
- return false;
+ function isEnableServerFunctions () {
+ var props = getSiteProps()
+ if (props.json_enabled) return true
+ return false
}
- prepareSearchProps();
- colorSearchTextInBody();
+ prepareSearchProps()
+ colorSearchTextInBody()
if (!isEnabledFetchFunctions()) {
- showNoSupportMessage();
- return;
+ showNoSupportMessage()
+ return
}
- if (!isEnableServerFunctions()) return;
- replaceSearchWithSearch2();
- hookSearch2();
- removeEncodeHint();
- kickFirstSearch();
+ if (!isEnableServerFunctions()) return
+ replaceSearchWithSearch2()
+ hookSearch2()
+ removeEncodeHint()
+ kickFirstSearch()
}
- enableSearch2();
-});
+ enableSearch2()
+})