From ef823489fef6f5eaef902878e84761d8b4c6f2ca Mon Sep 17 00:00:00 2001 From: FireIsGood Date: Thu, 16 May 2024 01:48:39 -0700 Subject: [PATCH] fix: format complex changes Formats all the general js files. Separate in case these should be treated differently for any reason. This commit includes all javascript and HTML files. --- gulpfile.js | 67 +- postcss.config.js | 14 +- source/assets/page/oops.htm | 288 +++---- source/widget/chmod.html | 195 ++--- tailwind.config.js | 44 +- themes/coo/scripts/add_field.js | 83 +- themes/coo/scripts/github.js | 19 +- themes/coo/scripts/global.js | 130 +-- themes/coo/scripts/markdown_plugin.js | 314 ++++---- themes/coo/scripts/merge_configs.js | 4 +- themes/coo/scripts/pagination_generator.js | 22 +- themes/coo/scripts/seo.js | 109 ++- themes/coo/scripts/share.js | 60 +- themes/coo/scripts/top_generator.js | 20 +- themes/coo/source/js/main.js | 869 ++++++++++----------- 15 files changed, 1123 insertions(+), 1115 deletions(-) diff --git a/gulpfile.js b/gulpfile.js index 1539b72..c1492cb 100644 --- a/gulpfile.js +++ b/gulpfile.js @@ -1,37 +1,44 @@ -const gulp = require('gulp'); -const htmlmin = require('gulp-htmlmin'); -const htmlclean = require('gulp-htmlclean'); -const version = require('gulp-version-number'); -const terser = require('gulp-terser'); +const gulp = require("gulp"); +const htmlmin = require("gulp-htmlmin"); +const htmlclean = require("gulp-htmlclean"); +const version = require("gulp-version-number"); +const terser = require("gulp-terser"); // Compress js files -gulp.task('js', function () { - return gulp.src(['./public/js/main.js']) - .pipe(terser({ - compress: true - })) - .pipe(gulp.dest('./public/js')); +gulp.task("js", function () { + return gulp + .src(["./public/js/main.js"]) + .pipe( + terser({ + compress: true, + }), + ) + .pipe(gulp.dest("./public/js")); }); - // Build html files -gulp.task('html', function () { - return gulp.src('./public/**/*.html') - .pipe(htmlclean()) - .pipe(htmlmin({ - removeComments: true, - minifyJS: true, - minifyCSS: true, - minifyURLs: true, - })) - .pipe(version({ - 'append': { - 'key': '_v', - 'cover': 1, - 'to': ['css', 'js', 'png', 'jpg', 'woff2'] - } - })) - .pipe(gulp.dest('./public')); +gulp.task("html", function () { + return gulp + .src("./public/**/*.html") + .pipe(htmlclean()) + .pipe( + htmlmin({ + removeComments: true, + minifyJS: true, + minifyCSS: true, + minifyURLs: true, + }), + ) + .pipe( + version({ + append: { + key: "_v", + cover: 1, + to: ["css", "js", "png", "jpg", "woff2"], + }, + }), + ) + .pipe(gulp.dest("./public")); }); -gulp.task('default', gulp.parallel('js', 'html')); \ No newline at end of file +gulp.task("default", gulp.parallel("js", "html")); diff --git a/postcss.config.js b/postcss.config.js index dff409f..00ee441 100644 --- a/postcss.config.js +++ b/postcss.config.js @@ -1,8 +1,8 @@ module.exports = { - plugins: { - 'postcss-import': {path: 'themes/coo/source/css'}, - 'tailwindcss': {config: './tailwind.config.js'}, - 'autoprefixer': {}, - 'postcss-minify':{}, - } -}; \ No newline at end of file + plugins: { + "postcss-import": { path: "themes/coo/source/css" }, + tailwindcss: { config: "./tailwind.config.js" }, + autoprefixer: {}, + "postcss-minify": {}, + }, +}; diff --git a/source/assets/page/oops.htm b/source/assets/page/oops.htm index e4027e0..1baaf2e 100644 --- a/source/assets/page/oops.htm +++ b/source/assets/page/oops.htm @@ -1,171 +1,171 @@ - + - - - - + + + + 404 Page NotFound - + - - -
-
+ + +
+
-
-
-
+
+
+

oops!

Error 404 : Page Not Found

go back +
-
- + diff --git a/source/widget/chmod.html b/source/widget/chmod.html index 67053c5..e396435 100644 --- a/source/widget/chmod.html +++ b/source/widget/chmod.html @@ -1,95 +1,102 @@ -
-
-

Permissions:

-
-
- -
-
- -
+
+
+

Permissions:

+
+
+ +
+
+ +
- + - - - - + + + + - - + + - - - - + + + + - - - - + + + + - - - - + + + + - +
UserGroupOtherUserGroupOther
ReadRead
WriteWrite
ExecuteExecute
- - \ No newline at end of file + diff --git a/tailwind.config.js b/tailwind.config.js index d67c7aa..31b8800 100644 --- a/tailwind.config.js +++ b/tailwind.config.js @@ -1,26 +1,26 @@ module.exports = { - darkMode: 'class', // or 'media' or 'class' - plugins: [ - // https://github.com/jamiebuilds/tailwindcss-animate - require("tailwindcss-animate"), - ], - theme: { - boxShadow: { - /* Customized */ - DEFAULT: '0 6px 8px rgba(102, 119, 136, 0.03), 0 1px 2px rgba(102, 119, 136, 0.3)', - md: '0 4px 6px -1px rgba(102, 119, 136, 0.05), 0 2px 4px -1px rgba(102, 119, 136, 0.35)', + darkMode: "class", // or 'media' or 'class' + plugins: [ + // https://github.com/jamiebuilds/tailwindcss-animate + require("tailwindcss-animate"), + ], + theme: { + boxShadow: { + /* Customized */ + DEFAULT: "0 6px 8px rgba(102, 119, 136, 0.03), 0 1px 2px rgba(102, 119, 136, 0.3)", + md: "0 4px 6px -1px rgba(102, 119, 136, 0.05), 0 2px 4px -1px rgba(102, 119, 136, 0.35)", - /* Default */ - sm: '0 1px 2px 0 rgba(0, 0, 0, 0.05)', - lg: '0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)', - xl: '0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)', - '2xl': '0 25px 50px -12px rgba(0, 0, 0, 0.25)', - '3xl': '0 35px 60px -15px rgba(0, 0, 0, 0.3)', - inner: 'inset 0 2px 4px 0 rgba(0, 0, 0, 0.06)', - none: 'none', - } + /* Default */ + sm: "0 1px 2px 0 rgba(0, 0, 0, 0.05)", + lg: "0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05)", + xl: "0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)", + "2xl": "0 25px 50px -12px rgba(0, 0, 0, 0.25)", + "3xl": "0 35px 60px -15px rgba(0, 0, 0, 0.3)", + inner: "inset 0 2px 4px 0 rgba(0, 0, 0, 0.06)", + none: "none", }, - content: { - files: ['**/*.{ejs,md}', '**/widget/*.html', '**/js/main.js'], - } + }, + content: { + files: ["**/*.{ejs,md}", "**/widget/*.html", "**/js/main.js"], + }, }; diff --git a/themes/coo/scripts/add_field.js b/themes/coo/scripts/add_field.js index 22c012c..5fa8bec 100644 --- a/themes/coo/scripts/add_field.js +++ b/themes/coo/scripts/add_field.js @@ -1,51 +1,50 @@ const h2_re = /

#<\/a>(.*)<\/h2>/gm; const h3_re = /

#<\/a>(.*)<\/h3>/gm; - hexo.extend.filter.register("after_post_render", function (data) { - let h2_m; - let h2_list = []; - while ((h2_m = h2_re.exec(data.content)) !== null) { - h2_list.push({ - anchor: h2_m[1].trim(), - title: h2_m[2].trim(), - start: h2_m.index - }) - } + let h2_m; + let h2_list = []; + while ((h2_m = h2_re.exec(data.content)) !== null) { + h2_list.push({ + anchor: h2_m[1].trim(), + title: h2_m[2].trim(), + start: h2_m.index, + }); + } - let h3_list = []; - for (let i = 0; i < h2_list.length; i++) { - let start = h2_list[i].start; - let end = data.content.length; - let next = h2_list[i + 1]; - if (next !== undefined) { - end = next.start; - } - const h2_section = data.content.substring(start, end); - let h3_m; - let h3_items = []; - while ((h3_m = h3_re.exec(h2_section)) !== null) { - h3_items.push({ - anchor: h3_m[1].trim(), - title: h3_m[2].trim() - }); - } - h2_list[i] = h2_list[i]; - h3_list.push(h3_items); + let h3_list = []; + for (let i = 0; i < h2_list.length; i++) { + let start = h2_list[i].start; + let end = data.content.length; + let next = h2_list[i + 1]; + if (next !== undefined) { + end = next.start; } - - let cards = [] - for (let i = 0; i < h2_list.length; i++) { - if (h3_list[i].length === 0) { - continue; - } - delete h2_list[i]['start']; - cards.push({ - h2: h2_list[i], - h3: h3_list[i] - }); + const h2_section = data.content.substring(start, end); + let h3_m; + let h3_items = []; + while ((h3_m = h3_re.exec(h2_section)) !== null) { + h3_items.push({ + anchor: h3_m[1].trim(), + title: h3_m[2].trim(), + }); } + h2_list[i] = h2_list[i]; + h3_list.push(h3_items); + } - data.sections = cards; - return data; + let cards = []; + for (let i = 0; i < h2_list.length; i++) { + if (h3_list[i].length === 0) { + continue; + } + delete h2_list[i]["start"]; + cards.push({ + h2: h2_list[i], + h3: h3_list[i], + }); + } + + data.sections = cards; + return data; }); diff --git a/themes/coo/scripts/github.js b/themes/coo/scripts/github.js index e6d2bd6..e5d2905 100644 --- a/themes/coo/scripts/github.js +++ b/themes/coo/scripts/github.js @@ -1,17 +1,16 @@ hexo.extend.helper.register("request_cheatsheet", function () { - return `https://github.com/Fechin/reference/issues/new?title=Cheatsheet+request%3A+&labels=request&template=cheatsheet-request.md&assignee=Fechin`; + return `https://github.com/Fechin/reference/issues/new?title=Cheatsheet+request%3A+&labels=request&template=cheatsheet-request.md&assignee=Fechin`; }); hexo.extend.helper.register("contributing", function () { - return `https://github.com/Fechin/reference`; + return `https://github.com/Fechin/reference`; }); - hexo.extend.helper.register("edit_page", function () { - let postPage = this.page['layout'] === 'post'; - let url = "https://github.com/Fechin/reference"; - if (postPage) { - url += `/blob/main/source/_posts/${this.page.slug}.md`; - } - return url; -}); \ No newline at end of file + let postPage = this.page["layout"] === "post"; + let url = "https://github.com/Fechin/reference"; + if (postPage) { + url += `/blob/main/source/_posts/${this.page.slug}.md`; + } + return url; +}); diff --git a/themes/coo/scripts/global.js b/themes/coo/scripts/global.js index f7f0e1f..930a379 100644 --- a/themes/coo/scripts/global.js +++ b/themes/coo/scripts/global.js @@ -1,82 +1,84 @@ -const fs = require('fs'); -const path = require('path'); +const fs = require("fs"); +const path = require("path"); hexo.extend.helper.register("icon", (name) => svgIcon(name)); -hexo.extend.generator.register('json', function (locals) { +hexo.extend.generator.register("json", function (locals) { + let searchName = "search.json"; + let datas = locals.posts.sort("date") || []; - let searchName = "search.json"; - let datas = locals.posts.sort('date') || []; + let res = []; + let index = 0; - let res = [] - let index = 0 + datas.each(function (data) { + if (data.indexing !== undefined && !data.indexing) return; + if (data.layout === "note") return; + let temp_data = {}; - datas.each(function (data) { - if (data.indexing !== undefined && !data.indexing) return; - if (data.layout === "note") return; - let temp_data = {} + temp_data.index = index; + temp_data.title = data.title; + temp_data.path = data.permalink.replace(hexo.config.url, ""); + temp_data.icon = svgIcon(data.slug); + temp_data.background = data.background; + temp_data.intro = data.intro; - temp_data.index = index; - temp_data.title = data.title; - temp_data.path = data.permalink.replace(hexo.config.url, ""); - temp_data.icon = svgIcon(data.slug); - temp_data.background = data.background; - temp_data.intro = data.intro; + // categories + temp_data.categories = []; + if (data.categories && data.categories.length > 0) { + data.categories.forEach(function (category) { + temp_data.categories.push(category.name); + }); + } - // categories - temp_data.categories = []; - if (data.categories && data.categories.length > 0) { - data.categories.forEach(function (category) { - temp_data.categories.push(category.name); - }); - } + // tags + temp_data.tags = []; + if (data.tags && data.tags.length > 0) { + data.tags.forEach(function (tag) { + temp_data.tags.push(tag.name); + }); + } + // sections + temp_data.sections = data.sections; - // tags - temp_data.tags = []; - if (data.tags && data.tags.length > 0) { - data.tags.forEach(function (tag) { - temp_data.tags.push(tag.name); - }); - } - // sections - temp_data.sections = data.sections; + res[index] = temp_data; + index += 1; + }); - res[index] = temp_data; - index += 1; - }); - - let json = JSON.stringify(res); - return {path: searchName, data: json}; + let json = JSON.stringify(res); + return { path: searchName, data: json }; }); +hexo.extend.generator.register("list", function (locals) { + const themeConfig = hexo.theme.config; + let content = ""; -hexo.extend.generator.register('list', function (locals) { - const themeConfig = hexo.theme.config; - let content = ""; + themeConfig.index_categories.forEach(function (category) { + content += `
\n${category}\n\n`; + locals.categories + .findOne({ name: category }) + .posts.sort("-date") + .map(function (post) { + content += `- [${post.title}](https://cheatsheets.zip/${post.path}): ${post.intro.trim()}\n`; + }); + content += `\n
\n\n`; + }); - themeConfig.index_categories.forEach(function (category) { - content += `
\n${category}\n\n`; - locals.categories.findOne({name: category}).posts.sort('-date').map(function (post) { - content += `- [${post.title}](https://cheatsheets.zip/${post.path}): ${post.intro.trim()}\n`; - }) - content += `\n
\n\n`; - }); - - return { - path: 'list.md', - data: content - }; + return { + path: "list.md", + data: content, + }; }); - function svgIcon(name) { - // Check file exists - let svgPath = path.resolve("./", "source/assets/icon/", `${name}.svg`); - if (fs.existsSync(svgPath)) { - return fs.readFileSync(svgPath, 'utf8') - } else { - return "\n" + - " \n" + - ""; - } + // Check file exists + let svgPath = path.resolve("./", "source/assets/icon/", `${name}.svg`); + if (fs.existsSync(svgPath)) { + return fs.readFileSync(svgPath, "utf8"); + } else { + return ( + '\n' + + ' \n' + + "" + ); + } } diff --git a/themes/coo/scripts/markdown_plugin.js b/themes/coo/scripts/markdown_plugin.js index 37282c7..001757a 100644 --- a/themes/coo/scripts/markdown_plugin.js +++ b/themes/coo/scripts/markdown_plugin.js @@ -1,172 +1,172 @@ -const fs = require('fs'); -const path = require('path'); +const fs = require("fs"); +const path = require("path"); -hexo.extend.filter.register('markdown-it:renderer', function (md) { - md.use(require('markdown-it-abbr'), {}); - md.use(require('markdown-it-footnote'), {}); - md.use(require('markdown-it-ins'), {}); - md.use(require('markdown-it-sub'), {}); - md.use(require('markdown-it-sup'), {}); - md.use(require('markdown-it-task-lists'), {}); - md.use(require('markdown-it-emoji'), {}); - md.use(require('markdown-it-attrs'), {}); - md.use(require('markdown-it-highlightjs'), {}); - md.use(require('markdown-it-checkbox'), {}); - md.use(require('markdown-it-multimd-table'), { - multiline: false, - rowspan: true, - headerless: false, - }); - md.use(require('markdown-it-shortcode-tag'), { - widget: { - render: function (attrs, env) { - let widgetPath = path.resolve(`./source/widget/${attrs.name}.html`); - if (fs.existsSync(widgetPath)) { - return fs.readFileSync(widgetPath, 'utf8').trim(); - } else { - let error = `Error: ${attrs.name} widget not Found!`; - console.log(error); - return error; - } - } +hexo.extend.filter.register("markdown-it:renderer", function (md) { + md.use(require("markdown-it-abbr"), {}); + md.use(require("markdown-it-footnote"), {}); + md.use(require("markdown-it-ins"), {}); + md.use(require("markdown-it-sub"), {}); + md.use(require("markdown-it-sup"), {}); + md.use(require("markdown-it-task-lists"), {}); + md.use(require("markdown-it-emoji"), {}); + md.use(require("markdown-it-attrs"), {}); + md.use(require("markdown-it-highlightjs"), {}); + md.use(require("markdown-it-checkbox"), {}); + md.use(require("markdown-it-multimd-table"), { + multiline: false, + rowspan: true, + headerless: false, + }); + md.use(require("markdown-it-shortcode-tag"), { + widget: { + render: function (attrs, env) { + let widgetPath = path.resolve(`./source/widget/${attrs.name}.html`); + if (fs.existsSync(widgetPath)) { + return fs.readFileSync(widgetPath, "utf8").trim(); + } else { + let error = `Error: ${attrs.name} widget not Found!`; + console.log(error); + return error; } - }); - headerSections(md, { - h2: { - wrapperClass: 'h2-wrap', - innerClass: 'h3-wrap-list', - }, - h3: { - wrapperClass: 'h3-wrap', - innerClass: 'section', - }, - tagName: "div" - }); + }, + }, + }); + headerSections(md, { + h2: { + wrapperClass: "h2-wrap", + innerClass: "h3-wrap-list", + }, + h3: { + wrapperClass: "h3-wrap", + innerClass: "section", + }, + tagName: "div", + }); }); function headerSections(md, options) { - const opts = Object.assign({}, options); + const opts = Object.assign({}, options); - function addSections(state) { - let tokens = []; // output - let Token = state.Token; - let sections = []; - let nestedLevel = 0; + function addSections(state) { + let tokens = []; // output + let Token = state.Token; + let sections = []; + let nestedLevel = 0; - function openTag(token, parser, classOptName) { - let t = new Token(parser, opts.tagName, 1); - t.block = true; - const cls = token && opts[token.tag] && opts[token.tag][classOptName]; - t.attrs = appendClass(token.attrs, cls); - return t; - } - - function closeTag(parser) { - let t = new Token(parser, opts.tagName, -1); - t.block = true; - return t; - } - - function closeSections(section) { - while (last(sections) && section.header <= last(sections).header) { - sections.pop(); - tokens.push(closeTag('section_inner_close')); - tokens.push(closeTag('section_wrapper_close')); - } - } - - function closeSectionsToCurrentNesting(nesting) { - while (last(sections) && nesting < last(sections).nesting) { - sections.pop(); - tokens.push(closeTag('section_inner_close')); - tokens.push(closeTag('section_wrapper_close')); - } - } - - function closeAllSections() { - while (sections.pop()) { - tokens.push(closeTag('section_inner_close')); - tokens.push(closeTag('section_wrapper_close')); - } - } - - for (let i = 0, l = state.tokens.length; i < l; i++) { - let token = state.tokens[i]; - - // record level of nesting - if (token.type.search('heading') !== 0) { - nestedLevel += token.nesting; - } - if (last(sections) && nestedLevel < last(sections).nesting) { - closeSectionsToCurrentNesting(nestedLevel); - } - - // add sections before headers - let expect = opts.hasOwnProperty(token.tag); - if (token.type === 'heading_open') { - let section = { - header: headingLevel(token.tag), - nesting: nestedLevel - }; - if (last(sections) && section.header <= last(sections).header && expect) { - closeSections(section); - } - if (expect) { - tokens.push(openTag(token, 'section_wrapper_open', 'wrapperClass')); - if (token.attrIndex('id') !== -1) { - // remove ID from token - token.attrs.splice(token.attrIndex('id'), 1); - } - sections.push(section); - - // The attribute has been placed in section_open, - // clear the attribute of the header tag - token.attrs = []; - } - - tokens.push(token); - } else if (token.type === 'heading_close') { // add inner section after headers - tokens.push(token); - if (expect) { - tokens.push(openTag(token, 'section_inner_open', 'innerClass')); - } - } else { - tokens.push(token); - } - - } // end for every token - closeAllSections(); - - state.tokens = tokens; + function openTag(token, parser, classOptName) { + let t = new Token(parser, opts.tagName, 1); + t.block = true; + const cls = token && opts[token.tag] && opts[token.tag][classOptName]; + t.attrs = appendClass(token.attrs, cls); + return t; } - function appendClass(attrs, cls) { - if (cls == null) { - return attrs; - } - if (attrs == null) { - attrs = []; - } - let appended = false; - attrs.forEach(function (x, i) { - if (x[0] === "class") { - x[1] = cls + " " + x[1]; - appended = true; - } - }); - if (!appended) { - attrs.push(["class", cls.trim()]) - } - return attrs; + function closeTag(parser) { + let t = new Token(parser, opts.tagName, -1); + t.block = true; + return t; } - function headingLevel(header) { - return parseInt(header.charAt(1)); + function closeSections(section) { + while (last(sections) && section.header <= last(sections).header) { + sections.pop(); + tokens.push(closeTag("section_inner_close")); + tokens.push(closeTag("section_wrapper_close")); + } } - function last(arr) { - return arr.slice(-1)[0]; + function closeSectionsToCurrentNesting(nesting) { + while (last(sections) && nesting < last(sections).nesting) { + sections.pop(); + tokens.push(closeTag("section_inner_close")); + tokens.push(closeTag("section_wrapper_close")); + } } - md.core.ruler.push('header_sections', addSections); -} \ No newline at end of file + function closeAllSections() { + while (sections.pop()) { + tokens.push(closeTag("section_inner_close")); + tokens.push(closeTag("section_wrapper_close")); + } + } + + for (let i = 0, l = state.tokens.length; i < l; i++) { + let token = state.tokens[i]; + + // record level of nesting + if (token.type.search("heading") !== 0) { + nestedLevel += token.nesting; + } + if (last(sections) && nestedLevel < last(sections).nesting) { + closeSectionsToCurrentNesting(nestedLevel); + } + + // add sections before headers + let expect = opts.hasOwnProperty(token.tag); + if (token.type === "heading_open") { + let section = { + header: headingLevel(token.tag), + nesting: nestedLevel, + }; + if (last(sections) && section.header <= last(sections).header && expect) { + closeSections(section); + } + if (expect) { + tokens.push(openTag(token, "section_wrapper_open", "wrapperClass")); + if (token.attrIndex("id") !== -1) { + // remove ID from token + token.attrs.splice(token.attrIndex("id"), 1); + } + sections.push(section); + + // The attribute has been placed in section_open, + // clear the attribute of the header tag + token.attrs = []; + } + + tokens.push(token); + } else if (token.type === "heading_close") { + // add inner section after headers + tokens.push(token); + if (expect) { + tokens.push(openTag(token, "section_inner_open", "innerClass")); + } + } else { + tokens.push(token); + } + } // end for every token + closeAllSections(); + + state.tokens = tokens; + } + + function appendClass(attrs, cls) { + if (cls == null) { + return attrs; + } + if (attrs == null) { + attrs = []; + } + let appended = false; + attrs.forEach(function (x, i) { + if (x[0] === "class") { + x[1] = cls + " " + x[1]; + appended = true; + } + }); + if (!appended) { + attrs.push(["class", cls.trim()]); + } + return attrs; + } + + function headingLevel(header) { + return parseInt(header.charAt(1)); + } + + function last(arr) { + return arr.slice(-1)[0]; + } + + md.core.ruler.push("header_sections", addSections); +} diff --git a/themes/coo/scripts/merge_configs.js b/themes/coo/scripts/merge_configs.js index ab8c0ea..d5f601b 100644 --- a/themes/coo/scripts/merge_configs.js +++ b/themes/coo/scripts/merge_configs.js @@ -3,6 +3,6 @@ * This fixes an issue with hexo-renderer-stylus, which otherwise ignores these * configuration overrides. */ -hexo.on('generateBefore', function () { - hexo.theme.config = Object.assign({}, hexo.theme.config, hexo.config.theme_config); +hexo.on("generateBefore", function () { + hexo.theme.config = Object.assign({}, hexo.theme.config, hexo.config.theme_config); }); diff --git a/themes/coo/scripts/pagination_generator.js b/themes/coo/scripts/pagination_generator.js index 7529e47..9ad84ef 100644 --- a/themes/coo/scripts/pagination_generator.js +++ b/themes/coo/scripts/pagination_generator.js @@ -1,14 +1,14 @@ let pagination = require("hexo-pagination"); hexo.extend.generator.register("notes-pagination", function (locals) { - let config = this.config; - let posts = locals.posts.filter(post => post.layout === "note").sort("-date"); - return pagination("notes", posts, { - perPage: config.per_page, - layout: ['notes'], - format: "%d/", - data: { - _isNotePagination: true - } - }); -}); \ No newline at end of file + let config = this.config; + let posts = locals.posts.filter((post) => post.layout === "note").sort("-date"); + return pagination("notes", posts, { + perPage: config.per_page, + layout: ["notes"], + format: "%d/", + data: { + _isNotePagination: true, + }, + }); +}); diff --git a/themes/coo/scripts/seo.js b/themes/coo/scripts/seo.js index d587967..1131593 100644 --- a/themes/coo/scripts/seo.js +++ b/themes/coo/scripts/seo.js @@ -1,69 +1,68 @@ -const fs = require('fs'); -const path = require('path'); +const fs = require("fs"); +const path = require("path"); hexo.extend.helper.register("page_title", function () { - let title = ""; - if (this.is_home()) { - title = `${this.config.title} - ${this.config.subtitle}`; - } else if (this.page.layout === "note") { - title = `${this.page.title} - ${this.config.title}`; - } else if (this.is_page()) { - title = `${this.page.title} - ${this.config.title}`; - } else if (this.is_post()) { - title = this.page.title; - let hasCommand = this.page.categories.findOne({name: "Linux Command"}); - if (hasCommand) { - title += " Command"; - } - title = `${title} Cheat Sheet & Quick Reference`; - } else if (this.page._isNotePagination) { - title = `Page ${this.page.current} of Notes - ${this.config.title}` + let title = ""; + if (this.is_home()) { + title = `${this.config.title} - ${this.config.subtitle}`; + } else if (this.page.layout === "note") { + title = `${this.page.title} - ${this.config.title}`; + } else if (this.is_page()) { + title = `${this.page.title} - ${this.config.title}`; + } else if (this.is_post()) { + title = this.page.title; + let hasCommand = this.page.categories.findOne({ name: "Linux Command" }); + if (hasCommand) { + title += " Command"; } - return title; + title = `${title} Cheat Sheet & Quick Reference`; + } else if (this.page._isNotePagination) { + title = `Page ${this.page.current} of Notes - ${this.config.title}`; + } + return title; }); hexo.extend.helper.register("page_description", function () { - let description; - if (this.is_home()) { - description = this.config.description; - } else if (this.page != null && this.page.intro != null) { - description = this.strip_html(this.markdown(this.page.intro)).substring(0, 110); - } else { - description = this.strip_html(this.page.content).substring(0, 130); - } - description = description.replace(/[\r\n\s\s+]+/g, " "); - return description; + let description; + if (this.is_home()) { + description = this.config.description; + } else if (this.page != null && this.page.intro != null) { + description = this.strip_html(this.markdown(this.page.intro)).substring(0, 110); + } else { + description = this.strip_html(this.page.content).substring(0, 130); + } + description = description.replace(/[\r\n\s\s+]+/g, " "); + return description; }); - hexo.extend.helper.register("page_keywords", function () { - let keywords = this.config.keywords; - if (this.page.tags && this.page.tags.each) { - this.page.tags.each(function (tag) { - keywords += ("," + tag.name); - }); - } - return keywords; + let keywords = this.config.keywords; + if (this.page.tags && this.page.tags.each) { + this.page.tags.each(function (tag) { + keywords += "," + tag.name; + }); + } + return keywords; }); hexo.extend.helper.register("page_image", function () { - let homePng = "preview.png"; - let postPng = ""; - if (this.is_post()) { - postPng = `${this.page.slug}-preview.png`; - } + let homePng = "preview.png"; + let postPng = ""; + if (this.is_post()) { + postPng = `${this.page.slug}-preview.png`; + } - let version = (Math.random() + 1).toString(36).substring(7); - let imageURL; + let version = (Math.random() + 1).toString(36).substring(7); + let imageURL; - // Check file exists - let postPath = path.resolve("./", "source/assets/image/", postPng); - if (fs.existsSync(postPath)) { - // Generate image url - imageURL = `${this.config.url}/assets/image/${postPng}?v=${version}`; - } else { - // console.warn(`Warning: ${postPath} not Found!`); - imageURL = `${this.config.url}/assets/image/${homePng}?v=${version}`; - } - return imageURL; -}); \ No newline at end of file + // Check file exists + let postPath = path.resolve("./", "source/assets/image/", postPng); + if (fs.existsSync(postPath)) { + // Generate image url + imageURL = `${this.config.url}/assets/image/${postPng}?v=${version}`; + } else { + // console.warn(`Warning: ${postPath} not Found!`); + imageURL = `${this.config.url}/assets/image/${homePng}?v=${version}`; + } + return imageURL; +}); diff --git a/themes/coo/scripts/share.js b/themes/coo/scripts/share.js index d04a3a2..dc5b0e2 100644 --- a/themes/coo/scripts/share.js +++ b/themes/coo/scripts/share.js @@ -1,32 +1,32 @@ -const {encodeURL} = require('hexo-util'); +const { encodeURL } = require("hexo-util"); hexo.extend.helper.register("share_link", function (type) { - let title = this.page_title(); - let description = this.page_description(); - let url = this.url_for(this.url); - let link = ""; - switch (type) { - case "facebook": - link = `https://facebook.com/sharer/sharer.php?u=${url}`; - break; - case "twitter": - link = `https://twitter.com/intent/tweet/?text=${description}&url=${url}`; - break; - case "linkedin": - link = `https://www.linkedin.com/shareArticle?url=${url}&title=${title}&summary=${description}`; - break; - case "reddit": - link = `https://reddit.com/submit/?url=${url}&resubmit=true&title=${description}`; - break; - case "pinterest": - link = `https://pinterest.com/pin/create/button/?url=${url}&description=${description}`; - break; - case "mail": - link = `mailto:?subject=${title}&body=\n${description}\n\n${url}`; - break; - case "line": - link = `https://social-plugins.line.me/lineit/share?url=${url}`; - break; - } - return encodeURL(link); -}); \ No newline at end of file + let title = this.page_title(); + let description = this.page_description(); + let url = this.url_for(this.url); + let link = ""; + switch (type) { + case "facebook": + link = `https://facebook.com/sharer/sharer.php?u=${url}`; + break; + case "twitter": + link = `https://twitter.com/intent/tweet/?text=${description}&url=${url}`; + break; + case "linkedin": + link = `https://www.linkedin.com/shareArticle?url=${url}&title=${title}&summary=${description}`; + break; + case "reddit": + link = `https://reddit.com/submit/?url=${url}&resubmit=true&title=${description}`; + break; + case "pinterest": + link = `https://pinterest.com/pin/create/button/?url=${url}&description=${description}`; + break; + case "mail": + link = `mailto:?subject=${title}&body=\n${description}\n\n${url}`; + break; + case "line": + link = `https://social-plugins.line.me/lineit/share?url=${url}`; + break; + } + return encodeURL(link); +}); diff --git a/themes/coo/scripts/top_generator.js b/themes/coo/scripts/top_generator.js index eebdc7f..3024169 100644 --- a/themes/coo/scripts/top_generator.js +++ b/themes/coo/scripts/top_generator.js @@ -1,15 +1,15 @@ -const path = require('path'); -const fs = require('hexo-fs'); +const path = require("path"); +const fs = require("hexo-fs"); -const outputFile = path.resolve("./", "source/ga_analytics_tops.json") +const outputFile = path.resolve("./", "source/ga_analytics_tops.json"); const cache = new Map(); hexo.extend.helper.register("topPosts", function (maximum = 4) { - let posts = cache.get(outputFile); - if (!posts) { - let content = fs.readFileSync(outputFile); - posts = JSON.parse(content); - cache.set(outputFile, posts); - } - return posts.slice(0, maximum); + let posts = cache.get(outputFile); + if (!posts) { + let content = fs.readFileSync(outputFile); + posts = JSON.parse(content); + cache.set(outputFile, posts); + } + return posts.slice(0, maximum); }); diff --git a/themes/coo/source/js/main.js b/themes/coo/source/js/main.js index 4052bd9..c81e06e 100644 --- a/themes/coo/source/js/main.js +++ b/themes/coo/source/js/main.js @@ -1,421 +1,421 @@ let Utils = (function () { - return { - LIBRARY: { - fuse: { - lib: ['/js/fuse_6.4.6.js'], - instance: 'Fuse', - attr: {async: true} - } - }, - loadScripts: function (urls, callback, attr = {}, container = document.head) { - let scripts = []; - for (let i in urls) { - scripts[i] = document.createElement('script'); - scripts[i].setAttribute("type", "text/javascript"); - scripts[i].setAttribute("src", urls[i]); - Object.keys(attr).forEach(function (key) { - scripts[i].setAttribute(key, attr[key]); - }) - } - let loadNextScript = function () { - let script = scripts.shift(); - let loaded = false; - container.appendChild(script); - script.onload = script.onreadystatechange = function () { - let rs = this.readyState; - if (rs && rs !== 'complete' && rs !== 'loaded') return; - if (loaded) return; - loaded = true; - if (scripts.length) { - loadNextScript(); - } else { - callback() - } - }; - }; - loadNextScript(); - }, - externalLibrary(library) { - return new Promise(resolve => { - if (window[library.instance] == null) { - this.loadScripts(library.lib, function () { - resolve(window[library.instance]); - }, library.attr, library.container); - } else { - resolve(window[library.instance]); - } - }); - } - }; -}()); - - -window.addEventListener('load', () => { - const isDarkMode = document.documentElement.classList.contains("dark") - if (!isDarkMode) { - let icon = document.querySelector("#darkMode > i").classList; - icon.toggle('icon-light') - icon.toggle('icon-dark') - } - document.querySelector("#darkMode").addEventListener("click", function () { - let html = document.documentElement.classList; - html.toggle('dark') - let icon = document.querySelector("#darkMode > i").classList; - icon.toggle('icon-light') - icon.toggle('icon-dark') - let isDarkMode = html.contains("dark"); - localStorage.theme = isDarkMode ? "dark" : ""; - }); - - /******** List Collapsible ***********/ - document.querySelectorAll("ul.collapsible > li > strong").forEach(function (strong) { - let li = strong.parentElement; - li.classList.add("active"); - strong.classList.toggle("arrow-down"); - strong.addEventListener("click", function () { - li.classList.toggle("active"); - this.classList.toggle("arrow-down"); + return { + LIBRARY: { + fuse: { + lib: ["/js/fuse_6.4.6.js"], + instance: "Fuse", + attr: { async: true }, + }, + }, + loadScripts: function (urls, callback, attr = {}, container = document.head) { + let scripts = []; + for (let i in urls) { + scripts[i] = document.createElement("script"); + scripts[i].setAttribute("type", "text/javascript"); + scripts[i].setAttribute("src", urls[i]); + Object.keys(attr).forEach(function (key) { + scripts[i].setAttribute(key, attr[key]); }); - }); - - - /******** Remove bottom border noise ********/ - document.querySelectorAll(".h3-wrap ul").forEach(function (ul, i) { - let length = ul.querySelectorAll("li").length; - let matches = ul.className.match("cols-([0-9]+)"); - let cols = matches === null ? 1 : parseInt(matches[1]); - let no_border_length = length === 1 || length % cols === 0 ? cols : length % cols; - for (let j = 1; j <= no_border_length; j++) { - let element = ul.querySelector(`li:nth-last-child(${j})`); - if (element != null) { - element.style.borderBottom = "none"; - } - } - }); - - - /******** h3-wrap blink ***********/ - function blinkSection() { - let hash = window.location.hash; - let anchor = document.querySelector(`a[class="h-anchor"][href="${hash}"]`); - if (anchor != null) { - let anchorSection = anchor.parentElement.parentElement; - document.querySelectorAll(".boxed").forEach((e) => { - e.classList.remove("boxed") - }); - let timer = setTimeout(function () { - anchorSection.classList.add("boxed"); - clearTimeout(timer); - }, 100); - } - } - - blinkSection(); - window.addEventListener('popstate', blinkSection); - - - /******** Search ***********/ - const searchEngine = function (options) { - let settings = options ? options : {}; - let defaultOptions = { - trigger: "#mysearch-trigger", - container: "#mysearch", - dbPath: `${location.protocol}//${location.host}/search.json?v=1.0` + } + let loadNextScript = function () { + let script = scripts.shift(); + let loaded = false; + container.appendChild(script); + script.onload = script.onreadystatechange = function () { + let rs = this.readyState; + if (rs && rs !== "complete" && rs !== "loaded") return; + if (loaded) return; + loaded = true; + if (scripts.length) { + loadNextScript(); + } else { + callback(); + } }; - this.container = (typeof settings.container != 'undefined') ? settings.container : defaultOptions.container; - this.trigger = (typeof settings.trigger != 'undefined') ? settings.trigger : defaultOptions.trigger; - this.dbPath = (typeof settings.dbPath != 'undefined') ? settings.dbPath : defaultOptions.dbPath; + }; + loadNextScript(); + }, + externalLibrary(library) { + return new Promise((resolve) => { + if (window[library.instance] == null) { + this.loadScripts( + library.lib, + function () { + resolve(window[library.instance]); + }, + library.attr, + library.container, + ); + } else { + resolve(window[library.instance]); + } + }); + }, + }; +})(); - this.lastSearch = {}; +window.addEventListener("load", () => { + const isDarkMode = document.documentElement.classList.contains("dark"); + if (!isDarkMode) { + let icon = document.querySelector("#darkMode > i").classList; + icon.toggle("icon-light"); + icon.toggle("icon-dark"); + } + document.querySelector("#darkMode").addEventListener("click", function () { + let html = document.documentElement.classList; + html.toggle("dark"); + let icon = document.querySelector("#darkMode > i").classList; + icon.toggle("icon-light"); + icon.toggle("icon-dark"); + let isDarkMode = html.contains("dark"); + localStorage.theme = isDarkMode ? "dark" : ""; + }); - window.search = this; + /******** List Collapsible ***********/ + document.querySelectorAll("ul.collapsible > li > strong").forEach(function (strong) { + let li = strong.parentElement; + li.classList.add("active"); + strong.classList.toggle("arrow-down"); + strong.addEventListener("click", function () { + li.classList.toggle("active"); + this.classList.toggle("arrow-down"); + }); + }); + + /******** Remove bottom border noise ********/ + document.querySelectorAll(".h3-wrap ul").forEach(function (ul, i) { + let length = ul.querySelectorAll("li").length; + let matches = ul.className.match("cols-([0-9]+)"); + let cols = matches === null ? 1 : parseInt(matches[1]); + let no_border_length = length === 1 || length % cols === 0 ? cols : length % cols; + for (let j = 1; j <= no_border_length; j++) { + let element = ul.querySelector(`li:nth-last-child(${j})`); + if (element != null) { + element.style.borderBottom = "none"; + } + } + }); + + /******** h3-wrap blink ***********/ + function blinkSection() { + let hash = window.location.hash; + let anchor = document.querySelector(`a[class="h-anchor"][href="${hash}"]`); + if (anchor != null) { + let anchorSection = anchor.parentElement.parentElement; + document.querySelectorAll(".boxed").forEach((e) => { + e.classList.remove("boxed"); + }); + let timer = setTimeout(function () { + anchorSection.classList.add("boxed"); + clearTimeout(timer); + }, 100); + } + } + + blinkSection(); + window.addEventListener("popstate", blinkSection); + + /******** Search ***********/ + const searchEngine = function (options) { + let settings = options ? options : {}; + let defaultOptions = { + trigger: "#mysearch-trigger", + container: "#mysearch", + dbPath: `${location.protocol}//${location.host}/search.json?v=1.0`, }; - searchEngine.prototype = { - start: function () { - const _this = this; + this.container = typeof settings.container != "undefined" ? settings.container : defaultOptions.container; + this.trigger = typeof settings.trigger != "undefined" ? settings.trigger : defaultOptions.trigger; + this.dbPath = typeof settings.dbPath != "undefined" ? settings.dbPath : defaultOptions.dbPath; - _this.fetchData(); // Prepare search data - this.search = document.querySelector(this.container); - this.box = document.querySelector("#mysearch-box"); - this.input = document.querySelector("#mysearch-input"); - this.result = document.querySelector("#mysearch-list"); - this.lastSearch.query = this.input.value; + this.lastSearch = {}; - this.detectModal(); + window.search = this; + }; + searchEngine.prototype = { + start: function () { + const _this = this; - // Cancel button - const cancel = document.querySelector(".cancel"); - cancel.addEventListener("click", function (e) { - _this.closeModal(true); + _this.fetchData(); // Prepare search data + this.search = document.querySelector(this.container); + this.box = document.querySelector("#mysearch-box"); + this.input = document.querySelector("#mysearch-input"); + this.result = document.querySelector("#mysearch-list"); + this.lastSearch.query = this.input.value; + + this.detectModal(); + + // Cancel button + const cancel = document.querySelector(".cancel"); + cancel.addEventListener("click", function (e) { + _this.closeModal(true); + }); + + // Clear button + const clear = document.querySelector("#mysearch-clear"); + clear.addEventListener("click", function (e) { + _this.doSearch("", true).then(); + }); + + // Search trigger + const trigger = document.querySelector(_this.trigger); + trigger.addEventListener("click", function (e) { + _this.openModal(true); + }); + + document.body.addEventListener("click", function (e) { + if (_this.isOpened()) { + if (!_this.box.contains(e.target) && !trigger.contains(e.target)) { + _this.closeModal(); + } + } + }); + + // Search input event + this.input.addEventListener("keyup", function (e) { + let value = _this.input.value; + if (value === _this.lastSearch.query) { + return; + } + _this.doSearch(value, true).then(); + }); + + document.body.addEventListener("keydown", function (e) { + if (e.key === "ArrowDown") { + if (_this.isOpened()) { + _this.moveItem(false); + e.preventDefault(); + e.stopPropagation(); + } + } else if (e.key === "ArrowUp") { + if (_this.isOpened()) { + _this.moveItem(true); + e.preventDefault(); + e.stopPropagation(); + } + } else if (e.key === "Enter") { + if (_this.isOpened()) { + let active = _this.result.querySelector("li.active > a"); + if (active != null) { + window.location.href = active.getAttribute("href"); + } + } + e.preventDefault(); + e.stopPropagation(); + } else if (e.key === "Escape") { + _this.closeModal(); + e.preventDefault(); + e.stopPropagation(); + } else if ((e.ctrlKey || e.metaKey) && e.key === "k") { + _this.toggleModal(); + e.preventDefault(); + e.stopPropagation(); + } + }); + }, + + moveItem: function (up) { + let current = this.result.querySelector("li.active"); + let next = up ? current.previousElementSibling : current.nextElementSibling; + if (next !== null) { + current.classList.remove("active"); + current.classList.add("inactive"); + next.classList.remove("inactive"); + next.classList.add("active"); + this.renderPreview(); + } + }, + detectModal: function () { + const url_string = window.location.href; + const url = new URL(url_string); + const query = url.searchParams.get("q"); + if (query != null) { + this.input.value = query; + this.openModal(false); + } + }, + isOpened: function () { + return this.search.classList.contains("block"); + }, + toggleModal: function () { + if (this.isOpened()) { + this.closeModal(); + } else { + this.openModal(); + } + }, + openModal: function (reset) { + this.search.classList.remove("hidden"); + this.search.classList.add("block"); + if (reset) { + this.input.value = ""; + } + document.body.classList.add("overflow-hidden"); + this.doSearch(this.input.value, false); + this.input.focus(); + }, + closeModal: function (reset) { + this.search.classList.remove("block"); + this.search.classList.add("hidden"); + if (reset) { + this.input.value = ""; + } + document.body.classList.remove("overflow-hidden"); + this.input.blur(); + }, + changeUrl: function (params) { + let baseURL = `${location.protocol}//${location.host}${location.pathname}`; + let newURL = baseURL; + if (params !== "" && params != null) { + newURL = `${baseURL}?${params}`; + } + history.pushState({}, null, newURL); + }, + fetchData: async function () { + const _this = this; + if (_this.index !== undefined) { + return; + } + return await fetch(_this.dbPath) + .then((resp) => resp.text()) + .then((resp) => { + _this.db = JSON.parse(resp); + _this.index = new Fuse(_this.db, { + // isCaseSensitive: false, + includeScore: false, + shouldSort: true, + includeMatches: true, + matchEmptyQuery: true, + // minMatchCharLength: 1, + // location: 0, + threshold: 0.1, + // distance: 100, + // useExtendedSearch: false, + // ignoreLocation: true, + // ignoreFieldNorm: false, + keys: [ + { name: "title", weight: 12 }, + { name: "tags", weight: 6 }, + { name: "categories", weight: 6 }, + { name: "sections.h3.title", weight: 5 }, + { name: "sections.h2.title", weight: 1 }, + { name: "intro", weight: 1 }, + ], + }); + // default return all + _this.lastSearch.whole = _this.db.map((doc, idx) => ({ + item: doc, + score: 1, + refIndex: idx, + })); + return resp; + }); + }, + doSearch: async function (value, history) { + const _this = this; + await _this.fetchData().then(() => { + if (this.lastSearch.query === value && this.lastSearch.resp !== undefined) { + this.renderResult(this.lastSearch.resp); + this.renderPreview(); + } else { + let results = value !== "" ? _this.index.search(`${value}`) : _this.lastSearch.whole; + if (history) { + this.changeUrl(value === "" ? null : `q=${value}`); + } + this.lastSearch.query = value; + this.lastSearch.resp = results; + this.renderResult(results); + this.renderPreview(); + } + }); + }, + addEventToResult: function () { + const _this = this; + this.result.querySelectorAll("li").forEach(function (li) { + li.addEventListener("mouseover", function (e) { + if (_this.isOpened()) { + _this.result.querySelectorAll("li").forEach(function (e) { + e.classList.remove("active"); + e.classList.add("inactive"); }); - - // Clear button - const clear = document.querySelector("#mysearch-clear"); - clear.addEventListener("click", function (e) { - _this.doSearch("", true).then(); - }); - - // Search trigger - const trigger = document.querySelector(_this.trigger); - trigger.addEventListener("click", function (e) { - _this.openModal(true); - }); - - document.body.addEventListener('click', function (e) { - if (_this.isOpened()) { - if (!_this.box.contains(e.target) && !trigger.contains(e.target)) { - _this.closeModal(); - } - } - }); - - // Search input event - this.input.addEventListener("keyup", function (e) { - let value = _this.input.value - if (value === _this.lastSearch.query) { - return; - } - _this.doSearch(value, true).then(); - }); - - document.body.addEventListener('keydown', function (e) { - if (e.key === "ArrowDown") { - if (_this.isOpened()) { - _this.moveItem(false) - e.preventDefault(); - e.stopPropagation(); - } - } else if (e.key === 'ArrowUp') { - if (_this.isOpened()) { - _this.moveItem(true) - e.preventDefault(); - e.stopPropagation(); - } - } else if (e.key === 'Enter') { - if (_this.isOpened()) { - let active = _this.result.querySelector("li.active > a") - if (active != null) { - window.location.href = active.getAttribute("href"); - } - } - e.preventDefault(); - e.stopPropagation(); - } else if (e.key === 'Escape') { - _this.closeModal(); - e.preventDefault(); - e.stopPropagation(); - } else if ((e.ctrlKey || e.metaKey) && e.key === 'k') { - _this.toggleModal(); - e.preventDefault(); - e.stopPropagation(); - } - }); - - }, - - moveItem: function (up) { - let current = this.result.querySelector("li.active") - let next = up ? current.previousElementSibling : current.nextElementSibling; - if (next !== null) { - current.classList.remove("active"); - current.classList.add("inactive"); - next.classList.remove("inactive"); - next.classList.add("active"); - this.renderPreview(); + this.classList.remove("inactive"); + this.classList.add("active"); + _this.renderPreview(); + } + }); + }); + }, + mark: function (text, matches) { + let result = []; + let pair = matches.shift(); + // Build the formatted string + for (let i = 0; i < text.length; i++) { + let char = text.charAt(i); + if (pair && i === pair[0]) { + result.push(""); + } + result.push(char); + if (pair && i === pair[1]) { + result.push(""); + pair = matches.shift(); + } + } + return result.join(""); + }, + highlightMatches: function (result) { + if (result.matches === undefined || result.item.length === 0) { + return; + } + const _this = this; + result.item = JSON.parse(JSON.stringify(_this.db[result.refIndex])); + result.matches.forEach((m) => { + switch (m.key) { + case "tags": + case "categories": + result.item[m.key][m.refIndex] = _this.mark(m.value, m.indices); + break; + case "sections.h2.title": + result.item["sections"][m.refIndex]["h2"]["title"] = _this.mark(m.value, m.indices); + break; + case "sections.h3.title": + let currLength = 0; + let lastLength = 0; + for (let i = 0; i < result.item["sections"].length; i++) { + let subArr = result.item["sections"][i]["h3"]; + currLength += subArr.length; + if (m.refIndex >= lastLength && m.refIndex < currLength) { + result.item["sections"][i]["h3"][m.refIndex - lastLength]["title"] = _this.mark(m.value, m.indices); + break; + } + lastLength += subArr.length; } - }, - detectModal: function () { - const url_string = window.location.href; - const url = new URL(url_string); - const query = url.searchParams.get("q"); - if (query != null) { - this.input.value = query; - this.openModal(false); - } - }, - isOpened: function () { - return this.search.classList.contains("block"); - }, - toggleModal: function () { - if (this.isOpened()) { - this.closeModal(); - } else { - this.openModal(); - } - }, - openModal: function (reset) { - this.search.classList.remove("hidden") - this.search.classList.add("block") - if (reset) { - this.input.value = ""; - } - document.body.classList.add("overflow-hidden"); - this.doSearch(this.input.value, false); - this.input.focus(); - }, - closeModal: function (reset) { - this.search.classList.remove("block") - this.search.classList.add("hidden") - if (reset) { - this.input.value = ""; - } - document.body.classList.remove("overflow-hidden"); - this.input.blur(); - }, - changeUrl: function (params) { - let baseURL = `${location.protocol}//${location.host}${location.pathname}`; - let newURL = baseURL; - if (params !== "" && params != null) { - newURL = `${baseURL}?${params}` - } - history.pushState({}, null, newURL); - }, - fetchData: async function () { - const _this = this; - if (_this.index !== undefined) { - return; - } - return await fetch(_this.dbPath) - .then(resp => resp.text()) - .then(resp => { - _this.db = JSON.parse(resp); - _this.index = new Fuse(_this.db, { - // isCaseSensitive: false, - includeScore: false, - shouldSort: true, - includeMatches: true, - matchEmptyQuery: true, - // minMatchCharLength: 1, - // location: 0, - threshold: 0.1, - // distance: 100, - // useExtendedSearch: false, - // ignoreLocation: true, - // ignoreFieldNorm: false, - keys: [ - {name: 'title', weight: 12}, - {name: 'tags', weight: 6}, - {name: 'categories', weight: 6}, - {name: 'sections.h3.title', weight: 5}, - {name: 'sections.h2.title', weight: 1}, - {name: 'intro', weight: 1}, - ] - }); - // default return all - _this.lastSearch.whole = _this.db.map((doc, idx) => ({ - item: doc, - score: 1, - refIndex: idx - })); - return resp; - }); - }, - doSearch: async function (value, history) { - const _this = this; - await _this.fetchData().then(() => { - if (this.lastSearch.query === value && this.lastSearch.resp !== undefined) { - this.renderResult(this.lastSearch.resp); - this.renderPreview(); - } else { - let results = value !== "" ? _this.index.search(`${value}`) : _this.lastSearch.whole; - if (history) { - this.changeUrl(value === "" ? null : `q=${value}`); - } - this.lastSearch.query = value; - this.lastSearch.resp = results; - this.renderResult(results); - this.renderPreview(); - } - }); - }, - addEventToResult: function () { - const _this = this; - this.result.querySelectorAll("li").forEach(function (li) { - li.addEventListener("mouseover", function (e) { - if (_this.isOpened()) { - _this.result.querySelectorAll("li").forEach(function (e) { - e.classList.remove("active") - e.classList.add("inactive") - }); - this.classList.remove("inactive"); - this.classList.add("active"); - _this.renderPreview(); - } - }); - }); - }, - mark: function (text, matches) { - let result = [] - let pair = matches.shift() - // Build the formatted string - for (let i = 0; i < text.length; i++) { - let char = text.charAt(i) - if (pair && i === pair[0]) { - result.push('') - } - result.push(char) - if (pair && i === pair[1]) { - result.push('') - pair = matches.shift() - } - } - return result.join(''); - }, - highlightMatches: function (result) { - if (result.matches === undefined || result.item.length === 0) { - return; - } - const _this = this; - result.item = JSON.parse(JSON.stringify(_this.db[result.refIndex])) - result.matches.forEach(m => { - switch (m.key) { - case "tags": - case "categories": - result.item[m.key][m.refIndex] = _this.mark(m.value, m.indices); - break; - case "sections.h2.title": - result.item["sections"][m.refIndex]["h2"]["title"] = _this.mark(m.value, m.indices); - break; - case "sections.h3.title": - let currLength = 0; - let lastLength = 0; - for (let i = 0; i < result.item["sections"].length; i++) { - let subArr = result.item["sections"][i]["h3"]; - currLength += subArr.length; - if (m.refIndex >= lastLength && m.refIndex < currLength) { - result.item["sections"][i]["h3"][m.refIndex - lastLength]["title"] = _this.mark(m.value, m.indices) - break; - } - lastLength += subArr.length; - } - break; - default: - result.item[m.key] = _this.mark(m.value, m.indices); - break; - } - }) - }, - renderResult: function (results) { - const _this = this; - let liHtml = ""; - let index = 0; - results.forEach(function (result, itemIndex) { - let activeStr = "inactive"; - if (index === 0) { - activeStr = "active"; - } + break; + default: + result.item[m.key] = _this.mark(m.value, m.indices); + break; + } + }); + }, + renderResult: function (results) { + const _this = this; + let liHtml = ""; + let index = 0; + results.forEach(function (result, itemIndex) { + let activeStr = "inactive"; + if (index === 0) { + activeStr = "active"; + } - _this.highlightMatches(result); + _this.highlightMatches(result); - let hit = result.item; - let tags = hit.tags || []; - let categories = hit.categories || []; - let tagStr = tags.join("•"); - let tagsHTML = ""; - if (tagStr !== "") { - tagsHTML = `
${tagStr}` - } - liHtml += `
  • + let hit = result.item; + let tags = hit.tags || []; + let categories = hit.categories || []; + let tagStr = tags.join("•"); + let tagsHTML = ""; + if (tagStr !== "") { + tagsHTML = `
    ${tagStr}`; + } + liHtml += `
  • `; - index++; - }); + index++; + }); - this.result.innerHTML = liHtml; - this.addEventToResult(); - }, - renderPreview() { - const active = this.search.querySelector("li.active"); - if (active == null) { - return; - } - const _this = this; - let itemIndex = active.getAttribute("data-index"); - let hit = _this.lastSearch.resp[parseInt(itemIndex)].item; + this.result.innerHTML = liHtml; + this.addEventToResult(); + }, + renderPreview() { + const active = this.search.querySelector("li.active"); + if (active == null) { + return; + } + const _this = this; + let itemIndex = active.getAttribute("data-index"); + let hit = _this.lastSearch.resp[parseInt(itemIndex)].item; - let olInnerHtml = ""; + let olInnerHtml = ""; - hit.sections.forEach(function (section, index, array) { - let h3HTML = ""; - section.h3.forEach(function (h3) { - let anchor = hit.path + h3.anchor; - h3HTML += `${h3.title.toLowerCase()}` - }); - let anchor = hit.path + section.h2.anchor; - olInnerHtml += `
  • + hit.sections.forEach(function (section, index, array) { + let h3HTML = ""; + section.h3.forEach(function (h3) { + let anchor = hit.path + h3.anchor; + h3HTML += `${h3.title.toLowerCase()}`; + }); + let anchor = hit.path + section.h2.anchor; + olInnerHtml += `
  • ${section.h2.title}
  • ${h3HTML}`; - }) + }); - - document.querySelector(".preview-panel").innerHTML = `
    + document.querySelector(".preview-panel").innerHTML = `
    -
    +
    ${hit.icon}
    ${hit.title}
      ${olInnerHtml}
    `; - } - }; + }, + }; - // Start search - Utils.externalLibrary(Utils.LIBRARY.fuse).then(() => new searchEngine().start()); + // Start search + Utils.externalLibrary(Utils.LIBRARY.fuse).then(() => new searchEngine().start()); });