code
stringlengths 24
2.07M
| docstring
stringlengths 25
85.3k
| func_name
stringlengths 1
92
| language
stringclasses 1
value | repo
stringlengths 5
64
| path
stringlengths 4
172
| url
stringlengths 44
218
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
LoadPlugins = async (settings) => {
const isBase = settings.hasOwnProperty("global")
const plugins = { enable: {}, disable: {}, stop: {}, error: {}, nosetting: {} }
const promises = Object.entries(settings).map(async ([fixedName, setting]) => {
if (!setting) {
plugins.nosetting[fixedName] = fixedName
} else if (!setting.ENABLE && !setting.enable) {
plugins.disable[fixedName] = setting
} else {
try {
const instance = await LoadPlugin(fixedName, setting, isBase)
if (instance) {
plugins.enable[fixedName] = instance
} else {
plugins.stop[fixedName] = setting
}
} catch (error) {
console.error(error)
plugins.error[fixedName] = error
}
}
})
await Promise.all(promises)
// log
const COLORS = { enable: "32", disable: "33", stop: "34", error: "31", nosetting: "35" }
console.group(`${isBase ? "Base" : "Custom"} Plugin`)
Object.entries(plugins).forEach(([t, p]) => console.debug(`[ \x1B[${COLORS[t]}m${t}\x1b[0m ] [ ${Object.keys(p).length} ]:`, p))
console.groupEnd()
return plugins
}
|
Cleanup, generally used for memory reclamation, used infrequently.
|
LoadPlugins
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/plugin.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/plugin.js
|
MIT
|
constructor(utils, i18n) {
this.utils = utils;
this.i18n = i18n;
this.diagramModeFlag = "custom_diagram"; // can be any value, just a flag
this.panel = `<div class="md-diagram-panel md-fences-adv-panel"><div class="md-diagram-panel-header"></div><div class="md-diagram-panel-preview"></div><div class="md-diagram-panel-error"></div></div>`;
this.exitInteractiveStrategies = ["click_exit_button"];
this.parsers = new Map(); // {lang: parser}
this.langMapping = new Map(); // {lang: mappingLang}
// this.pending = new Set(); // cid
// this.timeout = 300;
}
|
Dynamically register and unregister new code block diagram.
|
constructor
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/diagramParser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/diagramParser.js
|
MIT
|
after = mode => {
if (!mode) return mode
const isObj = typeof mode === "object"
const originLang = isObj ? mode.name : mode
const mappingLang = this.langMapping.get(originLang)
if (!mappingLang) {
return mode
}
if (!isObj) {
return mappingLang
}
mode.name = mappingLang
return mode
}
|
If the fenceEnhance plugin is disabled and EXIT_INTERACTIVE_MODE === click_exit_button, then force all charts to disable interactive mode.
|
after
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/diagramParser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/diagramParser.js
|
MIT
|
after = mode => {
if (!mode) return mode
const isObj = typeof mode === "object"
const originLang = isObj ? mode.name : mode
const mappingLang = this.langMapping.get(originLang)
if (!mappingLang) {
return mode
}
if (!isObj) {
return mappingLang
}
mode.name = mappingLang
return mode
}
|
If the fenceEnhance plugin is disabled and EXIT_INTERACTIVE_MODE === click_exit_button, then force all charts to disable interactive mode.
|
after
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/diagramParser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/diagramParser.js
|
MIT
|
afterExport = () => {
setTimeout(() => {
for (const lang of this.parsers.keys()) {
this.refreshAllLangFence(lang)
}
}, 300)
}
|
Called when a syntax error occurs in the code block content, at which point the page will display an error message.
|
afterExport
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/diagramParser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/diagramParser.js
|
MIT
|
afterExport = () => {
setTimeout(() => {
for (const lang of this.parsers.keys()) {
this.refreshAllLangFence(lang)
}
}, 300)
}
|
Called when a syntax error occurs in the code block content, at which point the page will display an error message.
|
afterExport
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/diagramParser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/diagramParser.js
|
MIT
|
callback = () => {
const beforeToHTML = () => {
const extraCssList = []
this.parsers.forEach((parser, lang) => {
this.renderAllLangFence(lang)
const getter = parser.extraStyleGetter
const exist = this.utils.entities.querySelectorInWrite(`.md-fences[lang="${lang}"]`)
if (getter && exist) {
const extraCss = getter()
extraCssList.push(extraCss)
}
})
if (extraCssList.length) {
const base = ` .md-diagram-panel, svg {page-break-inside: avoid;} `
return base + extraCssList.join(" ")
}
}
// Make `frame.js` happy. Avoid null pointer exceptions
// There is a line of code in the export source code: document.querySelector("[cid='" + t.cid + "'] svg").getBoundingClientRect()
const beforeToNative = () => {
this.parsers.forEach((parser, lang) => {
this.renderAllLangFence(lang)
const previews = this.utils.entities.querySelectorAllInWrite(`.md-fences[lang="${lang}"] .md-diagram-panel-preview`)
previews.forEach(preview => {
const svg = preview.querySelector("svg")
if (!svg) {
preview.innerHTML = "<svg></svg>"
}
})
})
}
this.utils.exportHelper.register("diagram-parser", beforeToHTML, afterExport)
this.utils.exportHelper.registerNative("diagram-parser", beforeToNative, afterExport)
}
|
Called when a syntax error occurs in the code block content, at which point the page will display an error message.
|
callback
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/diagramParser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/diagramParser.js
|
MIT
|
callback = () => {
const beforeToHTML = () => {
const extraCssList = []
this.parsers.forEach((parser, lang) => {
this.renderAllLangFence(lang)
const getter = parser.extraStyleGetter
const exist = this.utils.entities.querySelectorInWrite(`.md-fences[lang="${lang}"]`)
if (getter && exist) {
const extraCss = getter()
extraCssList.push(extraCss)
}
})
if (extraCssList.length) {
const base = ` .md-diagram-panel, svg {page-break-inside: avoid;} `
return base + extraCssList.join(" ")
}
}
// Make `frame.js` happy. Avoid null pointer exceptions
// There is a line of code in the export source code: document.querySelector("[cid='" + t.cid + "'] svg").getBoundingClientRect()
const beforeToNative = () => {
this.parsers.forEach((parser, lang) => {
this.renderAllLangFence(lang)
const previews = this.utils.entities.querySelectorAllInWrite(`.md-fences[lang="${lang}"] .md-diagram-panel-preview`)
previews.forEach(preview => {
const svg = preview.querySelector("svg")
if (!svg) {
preview.innerHTML = "<svg></svg>"
}
})
})
}
this.utils.exportHelper.register("diagram-parser", beforeToHTML, afterExport)
this.utils.exportHelper.registerNative("diagram-parser", beforeToNative, afterExport)
}
|
Called when a syntax error occurs in the code block content, at which point the page will display an error message.
|
callback
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/diagramParser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/diagramParser.js
|
MIT
|
beforeToHTML = () => {
const extraCssList = []
this.parsers.forEach((parser, lang) => {
this.renderAllLangFence(lang)
const getter = parser.extraStyleGetter
const exist = this.utils.entities.querySelectorInWrite(`.md-fences[lang="${lang}"]`)
if (getter && exist) {
const extraCss = getter()
extraCssList.push(extraCss)
}
})
if (extraCssList.length) {
const base = ` .md-diagram-panel, svg {page-break-inside: avoid;} `
return base + extraCssList.join(" ")
}
}
|
Called when a syntax error occurs in the code block content, at which point the page will display an error message.
|
beforeToHTML
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/diagramParser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/diagramParser.js
|
MIT
|
beforeToHTML = () => {
const extraCssList = []
this.parsers.forEach((parser, lang) => {
this.renderAllLangFence(lang)
const getter = parser.extraStyleGetter
const exist = this.utils.entities.querySelectorInWrite(`.md-fences[lang="${lang}"]`)
if (getter && exist) {
const extraCss = getter()
extraCssList.push(extraCss)
}
})
if (extraCssList.length) {
const base = ` .md-diagram-panel, svg {page-break-inside: avoid;} `
return base + extraCssList.join(" ")
}
}
|
Called when a syntax error occurs in the code block content, at which point the page will display an error message.
|
beforeToHTML
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/diagramParser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/diagramParser.js
|
MIT
|
beforeToNative = () => {
this.parsers.forEach((parser, lang) => {
this.renderAllLangFence(lang)
const previews = this.utils.entities.querySelectorAllInWrite(`.md-fences[lang="${lang}"] .md-diagram-panel-preview`)
previews.forEach(preview => {
const svg = preview.querySelector("svg")
if (!svg) {
preview.innerHTML = "<svg></svg>"
}
})
})
}
|
Called when a syntax error occurs in the code block content, at which point the page will display an error message.
|
beforeToNative
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/diagramParser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/diagramParser.js
|
MIT
|
beforeToNative = () => {
this.parsers.forEach((parser, lang) => {
this.renderAllLangFence(lang)
const previews = this.utils.entities.querySelectorAllInWrite(`.md-fences[lang="${lang}"] .md-diagram-panel-preview`)
previews.forEach(preview => {
const svg = preview.querySelector("svg")
if (!svg) {
preview.innerHTML = "<svg></svg>"
}
})
})
}
|
Called when a syntax error occurs in the code block content, at which point the page will display an error message.
|
beforeToNative
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/diagramParser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/diagramParser.js
|
MIT
|
enableFocus = () => {
dontFocus = false;
setTimeout(() => dontFocus = true, 200);
}
|
Called when a syntax error occurs in the code block content, at which point the page will display an error message.
|
enableFocus
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/diagramParser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/diagramParser.js
|
MIT
|
enableFocus = () => {
dontFocus = false;
setTimeout(() => dontFocus = true, 200);
}
|
Called when a syntax error occurs in the code block content, at which point the page will display an error message.
|
enableFocus
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/diagramParser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/diagramParser.js
|
MIT
|
stopCall = (...args) => {
if (!dontFocus || !args || !args[0]) return;
const cid = ("string" == typeof args[0]) ? args[0] : args[0]["id"];
if (cid) {
const lang = (File.editor.findElemById(cid).attr("lang") || "").trim().toLowerCase();
if (!cid || !lang) return;
const parser = this.parsers.get(lang);
if (parser && parser.interactiveMode) return this.utils.stopCallError
}
}
|
Called when a syntax error occurs in the code block content, at which point the page will display an error message.
|
stopCall
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/diagramParser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/diagramParser.js
|
MIT
|
stopCall = (...args) => {
if (!dontFocus || !args || !args[0]) return;
const cid = ("string" == typeof args[0]) ? args[0] : args[0]["id"];
if (cid) {
const lang = (File.editor.findElemById(cid).attr("lang") || "").trim().toLowerCase();
if (!cid || !lang) return;
const parser = this.parsers.get(lang);
if (parser && parser.interactiveMode) return this.utils.stopCallError
}
}
|
Called when a syntax error occurs in the code block content, at which point the page will display an error message.
|
stopCall
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/diagramParser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/diagramParser.js
|
MIT
|
showAllTButton = fence => {
const enhance = fence.querySelector(".fence-enhance");
if (!enhance) return;
enhance.querySelectorAll(".enhance-btn").forEach(ele => ele.style.display = "");
return enhance
}
|
Called when a syntax error occurs in the code block content, at which point the page will display an error message.
|
showAllTButton
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/diagramParser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/diagramParser.js
|
MIT
|
showAllTButton = fence => {
const enhance = fence.querySelector(".fence-enhance");
if (!enhance) return;
enhance.querySelectorAll(".enhance-btn").forEach(ele => ele.style.display = "");
return enhance
}
|
Called when a syntax error occurs in the code block content, at which point the page will display an error message.
|
showAllTButton
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/diagramParser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/diagramParser.js
|
MIT
|
showEditButtonOnly = fence => {
const enhance = fence.querySelector(".fence-enhance");
if (!enhance) return;
enhance.style.display = "";
enhance.querySelectorAll(".enhance-btn").forEach(ele => ele.style.display = "none");
enhance.querySelector(".edit-diagram").style.display = "";
}
|
Called when a syntax error occurs in the code block content, at which point the page will display an error message.
|
showEditButtonOnly
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/diagramParser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/diagramParser.js
|
MIT
|
showEditButtonOnly = fence => {
const enhance = fence.querySelector(".fence-enhance");
if (!enhance) return;
enhance.style.display = "";
enhance.querySelectorAll(".enhance-btn").forEach(ele => ele.style.display = "none");
enhance.querySelector(".edit-diagram").style.display = "";
}
|
Called when a syntax error occurs in the code block content, at which point the page will display an error message.
|
showEditButtonOnly
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/diagramParser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/diagramParser.js
|
MIT
|
hideAllButton = fence => {
const enhance = showAllTButton(fence);
if (!enhance) return;
const editButton = enhance.querySelector(".edit-diagram");
if (editButton) {
editButton.style.display = "none";
}
enhance.style.display = "none";
}
|
Called when a syntax error occurs in the code block content, at which point the page will display an error message.
|
hideAllButton
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/diagramParser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/diagramParser.js
|
MIT
|
hideAllButton = fence => {
const enhance = showAllTButton(fence);
if (!enhance) return;
const editButton = enhance.querySelector(".edit-diagram");
if (editButton) {
editButton.style.display = "none";
}
enhance.style.display = "none";
}
|
Called when a syntax error occurs in the code block content, at which point the page will display an error message.
|
hideAllButton
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/diagramParser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/diagramParser.js
|
MIT
|
registerFenceEnhanceButton = (className, action, hint, iconClassName, enable, listener, extraFunc) => {
const btn = { className, action, hint, iconClassName, enable, listener, extraFunc }
return this.utils.callPluginFunction("fence_enhance", "registerButton", btn)
}
|
Called when a syntax error occurs in the code block content, at which point the page will display an error message.
|
registerFenceEnhanceButton
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/diagramParser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/diagramParser.js
|
MIT
|
registerFenceEnhanceButton = (className, action, hint, iconClassName, enable, listener, extraFunc) => {
const btn = { className, action, hint, iconClassName, enable, listener, extraFunc }
return this.utils.callPluginFunction("fence_enhance", "registerButton", btn)
}
|
Called when a syntax error occurs in the code block content, at which point the page will display an error message.
|
registerFenceEnhanceButton
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/diagramParser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/diagramParser.js
|
MIT
|
handleCtrlClick = () => {
const ctrlClick = this.exitInteractiveStrategies.includes("ctrl_click_fence");
if (!ctrlClick) return;
this.utils.entities.eWrite.addEventListener("mouseup", ev => {
if (this.utils.metaKeyPressed(ev) && ev.target.closest(".md-fences-interactive .md-diagram-panel-preview")) {
showAllTButton(ev.target.closest(".md-fences-interactive"));
enableFocus();
}
}, true)
}
|
Called when a syntax error occurs in the code block content, at which point the page will display an error message.
|
handleCtrlClick
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/diagramParser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/diagramParser.js
|
MIT
|
handleCtrlClick = () => {
const ctrlClick = this.exitInteractiveStrategies.includes("ctrl_click_fence");
if (!ctrlClick) return;
this.utils.entities.eWrite.addEventListener("mouseup", ev => {
if (this.utils.metaKeyPressed(ev) && ev.target.closest(".md-fences-interactive .md-diagram-panel-preview")) {
showAllTButton(ev.target.closest(".md-fences-interactive"));
enableFocus();
}
}, true)
}
|
Called when a syntax error occurs in the code block content, at which point the page will display an error message.
|
handleCtrlClick
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/diagramParser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/diagramParser.js
|
MIT
|
handleEditButton = () => {
const editBtn = this.exitInteractiveStrategies.includes("click_exit_button");
const hasInteractive = Array.from(this.parsers.values()).some(parser => parser.interactiveMode);
if (!editBtn || !hasInteractive) return;
const editText = this.i18n.t("global", "edit")
const listener = (ev, button) => {
button.closest(".fence-enhance").querySelectorAll(".enhance-btn").forEach(ele => ele.style.display = "");
enableFocus();
}
const ok = registerFenceEnhanceButton("edit-diagram", "editDiagram", editText, "fa fa-pencil", false, listener);
if (!ok) return;
this.utils.entities.$eWrite.on("mouseenter", ".md-fences-interactive:not(.md-focus)", function () {
showEditButtonOnly(this);
}).on("mouseleave", ".md-fences-interactive.md-focus", function () {
showEditButtonOnly(this);
}).on("mouseleave", ".md-fences-interactive:not(.md-focus)", function () {
hideAllButton(this);
}).on("mouseenter", ".md-fences-interactive.md-focus", function () {
showAllTButton(this);
})
}
|
Called when a syntax error occurs in the code block content, at which point the page will display an error message.
|
handleEditButton
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/diagramParser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/diagramParser.js
|
MIT
|
handleEditButton = () => {
const editBtn = this.exitInteractiveStrategies.includes("click_exit_button");
const hasInteractive = Array.from(this.parsers.values()).some(parser => parser.interactiveMode);
if (!editBtn || !hasInteractive) return;
const editText = this.i18n.t("global", "edit")
const listener = (ev, button) => {
button.closest(".fence-enhance").querySelectorAll(".enhance-btn").forEach(ele => ele.style.display = "");
enableFocus();
}
const ok = registerFenceEnhanceButton("edit-diagram", "editDiagram", editText, "fa fa-pencil", false, listener);
if (!ok) return;
this.utils.entities.$eWrite.on("mouseenter", ".md-fences-interactive:not(.md-focus)", function () {
showEditButtonOnly(this);
}).on("mouseleave", ".md-fences-interactive.md-focus", function () {
showEditButtonOnly(this);
}).on("mouseleave", ".md-fences-interactive:not(.md-focus)", function () {
hideAllButton(this);
}).on("mouseenter", ".md-fences-interactive.md-focus", function () {
showAllTButton(this);
})
}
|
Called when a syntax error occurs in the code block content, at which point the page will display an error message.
|
handleEditButton
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/diagramParser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/diagramParser.js
|
MIT
|
listener = (ev, button) => {
button.closest(".fence-enhance").querySelectorAll(".enhance-btn").forEach(ele => ele.style.display = "");
enableFocus();
}
|
Called when a syntax error occurs in the code block content, at which point the page will display an error message.
|
listener
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/diagramParser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/diagramParser.js
|
MIT
|
listener = (ev, button) => {
button.closest(".fence-enhance").querySelectorAll(".enhance-btn").forEach(ele => ele.style.display = "");
enableFocus();
}
|
Called when a syntax error occurs in the code block content, at which point the page will display an error message.
|
listener
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/diagramParser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/diagramParser.js
|
MIT
|
after = (result, ...args) => {
if (result === true) return true;
let lang = args[0];
if (!lang) return false;
const type = typeof lang;
if (type === "object" && lang.mappingType === this.diagramModeFlag) return true;
if (type === "object" && lang.name) {
lang = lang.name;
}
if (type === "string") {
return this.parsers.get(lang.toLowerCase());
}
return result
}
|
Called when a syntax error occurs in the code block content, at which point the page will display an error message.
|
after
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/diagramParser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/diagramParser.js
|
MIT
|
after = (result, ...args) => {
if (result === true) return true;
let lang = args[0];
if (!lang) return false;
const type = typeof lang;
if (type === "object" && lang.mappingType === this.diagramModeFlag) return true;
if (type === "object" && lang.name) {
lang = lang.name;
}
if (type === "string") {
return this.parsers.get(lang.toLowerCase());
}
return result
}
|
Called when a syntax error occurs in the code block content, at which point the page will display an error message.
|
after
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/diagramParser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/diagramParser.js
|
MIT
|
constructor(utils) {
this.utils = utils
this.htmlHelpers = new Map()
this.nativeHelpers = new Map()
this.isAsync = undefined
}
|
Dynamically register additional actions on export.
|
constructor
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/exportHelper.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/exportHelper.js
|
MIT
|
async function walk(dir) {
const files = await readdir(dir)
const promises = files.map(async file => {
const path = Path.join(dir, file)
const stats = await stat(path)
if (stats.isFile()) {
if (fileFilter(path, stats)) {
const params = await paramsBuilder(path, file, dir, stats)
await callback(params)
}
} else if (stats.isDirectory()) {
if (dirFilter(file)) {
await walk(path)
}
}
})
await Promise.all(promises)
}
|
@param {boolean} shouldSave - Whether to save the content.
@param {string} contentType - The content type (e.g., 'markdown', 'html').
@param {boolean} skipSetContent - Whether to skip setting the content.
@param {any} saveContext - Contextual information for saving (optional).
@returns {string} - The content of the editor.
|
walk
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/index.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/index.js
|
MIT
|
imageReplacement = (_, alt, src) => {
if (!this.isNetworkImage(src) && !this.isSpecialImage(src)) {
src = PATH.resolve(dir || this.getCurrentDirPath(), src);
}
return `<img alt="${alt}" src="${src}">`
}
|
Backup before `File.editor.stylize.toggleFences()` as it uses `File.option` to set block code language. Restore after.
|
imageReplacement
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/index.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/index.js
|
MIT
|
imageReplacement = (_, alt, src) => {
if (!this.isNetworkImage(src) && !this.isSpecialImage(src)) {
src = PATH.resolve(dir || this.getCurrentDirPath(), src);
}
return `<img alt="${alt}" src="${src}">`
}
|
Backup before `File.editor.stylize.toggleFences()` as it uses `File.option` to set block code language. Restore after.
|
imageReplacement
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/index.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/index.js
|
MIT
|
function mousemove(e) {
requestAnimationFrame(() => {
let deltaX = e.clientX - startX;
let deltaY = e.clientY - startY;
if (onMouseMove) {
const { deltaX: newDeltaX, deltaY: newDeltaY } = onMouseMove(deltaX, deltaY) || {};
deltaX = newDeltaX || deltaX;
deltaY = newDeltaY || deltaY;
}
if (resizeWidth) {
resizeElement.style.width = startWidth + deltaX + "px";
}
if (resizeHeight) {
resizeElement.style.height = startHeight + deltaY + "px";
}
})
}
|
Backup before `File.editor.stylize.toggleFences()` as it uses `File.option` to set block code language. Restore after.
|
mousemove
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/index.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/index.js
|
MIT
|
function mouseup() {
document.removeEventListener("mousemove", mousemove);
document.removeEventListener("mouseup", mouseup);
if (onMouseUp) {
onMouseUp()
}
}
|
Backup before `File.editor.stylize.toggleFences()` as it uses `File.option` to set block code language. Restore after.
|
mouseup
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/index.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/index.js
|
MIT
|
onMouseMove = ev => {
if (withMetaKey && !this.metaKeyPressed(ev) || ev.button !== 0) return;
ev.stopPropagation();
ev.preventDefault();
requestAnimationFrame(() => {
if (_onMouseMove) {
_onMouseMove()
}
moveElement.style.left = ev.clientX - shiftX + 'px';
moveElement.style.top = ev.clientY - shiftY + 'px';
});
}
|
Backup before `File.editor.stylize.toggleFences()` as it uses `File.option` to set block code language. Restore after.
|
onMouseMove
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/index.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/index.js
|
MIT
|
onMouseMove = ev => {
if (withMetaKey && !this.metaKeyPressed(ev) || ev.button !== 0) return;
ev.stopPropagation();
ev.preventDefault();
requestAnimationFrame(() => {
if (_onMouseMove) {
_onMouseMove()
}
moveElement.style.left = ev.clientX - shiftX + 'px';
moveElement.style.top = ev.clientY - shiftY + 'px';
});
}
|
Backup before `File.editor.stylize.toggleFences()` as it uses `File.option` to set block code language. Restore after.
|
onMouseMove
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/index.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/index.js
|
MIT
|
onMouseUp = ev => {
if (withMetaKey && !this.metaKeyPressed(ev) || ev.button !== 0) return;
if (_onMouseUp) {
_onMouseUp()
}
ev.stopPropagation();
ev.preventDefault();
document.removeEventListener("mousemove", onMouseMove);
moveElement.onmouseup = null;
document.removeEventListener("mouseup", onMouseUp);
}
|
Backup before `File.editor.stylize.toggleFences()` as it uses `File.option` to set block code language. Restore after.
|
onMouseUp
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/index.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/index.js
|
MIT
|
onMouseUp = ev => {
if (withMetaKey && !this.metaKeyPressed(ev) || ev.button !== 0) return;
if (_onMouseUp) {
_onMouseUp()
}
ev.stopPropagation();
ev.preventDefault();
document.removeEventListener("mousemove", onMouseMove);
moveElement.onmouseup = null;
document.removeEventListener("mouseup", onMouseUp);
}
|
Backup before `File.editor.stylize.toggleFences()` as it uses `File.option` to set block code language. Restore after.
|
onMouseUp
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/index.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/index.js
|
MIT
|
function decorator(original, before, after) {
const fn = function () {
if (before) {
const error = before.call(this, ...arguments)
if (error === utils.stopCallError) return
}
let result = original.apply(this, arguments)
if (after) {
const afterResult = after.call(this, result, ...arguments)
if (changeResult) {
result = afterResult
}
}
return result
}
return Object.defineProperty(fn, "name", { value: original.name })
}
|
Backup before `File.editor.stylize.toggleFences()` as it uses `File.option` to set block code language. Restore after.
|
decorator
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/index.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/index.js
|
MIT
|
fn = function () {
if (before) {
const error = before.call(this, ...arguments)
if (error === utils.stopCallError) return
}
let result = original.apply(this, arguments)
if (after) {
const afterResult = after.call(this, result, ...arguments)
if (changeResult) {
result = afterResult
}
}
return result
}
|
Backup before `File.editor.stylize.toggleFences()` as it uses `File.option` to set block code language. Restore after.
|
fn
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/index.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/index.js
|
MIT
|
fn = function () {
if (before) {
const error = before.call(this, ...arguments)
if (error === utils.stopCallError) return
}
let result = original.apply(this, arguments)
if (after) {
const afterResult = after.call(this, result, ...arguments)
if (changeResult) {
result = afterResult
}
}
return result
}
|
Backup before `File.editor.stylize.toggleFences()` as it uses `File.option` to set block code language. Restore after.
|
fn
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/index.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/index.js
|
MIT
|
newMixin = (utils) => {
const MIXIN = {
...require("./settings"),
...require("./migrate"),
...require("./hotkeyHub"),
...require("./eventHub"),
...require("./stateRecorder"),
...require("./exportHelper"),
...require("./styleTemplater"),
...require("./contextMenu"),
...require("./notification"),
...require("./progressBar"),
...require("./form-dialog"),
...require("./diagramParser"),
...require("./thirdPartyDiagramParser"),
...require("./mermaid"),
...require("./entities"),
}
return Object.fromEntries(Object.entries(MIXIN).map(([name, cls]) => [[name], new cls(utils, i18n)]))
}
|
Backup before `File.editor.stylize.toggleFences()` as it uses `File.option` to set block code language. Restore after.
|
newMixin
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/index.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/index.js
|
MIT
|
newMixin = (utils) => {
const MIXIN = {
...require("./settings"),
...require("./migrate"),
...require("./hotkeyHub"),
...require("./eventHub"),
...require("./stateRecorder"),
...require("./exportHelper"),
...require("./styleTemplater"),
...require("./contextMenu"),
...require("./notification"),
...require("./progressBar"),
...require("./form-dialog"),
...require("./diagramParser"),
...require("./thirdPartyDiagramParser"),
...require("./mermaid"),
...require("./entities"),
}
return Object.fromEntries(Object.entries(MIXIN).map(([name, cls]) => [[name], new cls(utils, i18n)]))
}
|
Backup before `File.editor.stylize.toggleFences()` as it uses `File.option` to set block code language. Restore after.
|
newMixin
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/index.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/index.js
|
MIT
|
getHook = utils => {
const mixin = newMixin(utils)
Object.assign(utils, mixin)
const {
styleTemplater, hotkeyHub, eventHub, stateRecorder, exportHelper, contextMenu,
notification, progressBar, formDialog, diagramParser, thirdPartyDiagramParser,
} = mixin
const registerMixin = (...ele) => Promise.all(ele.map(h => h.process && h.process()))
const optimizeMixin = () => Promise.all(Object.values(mixin).map(h => h.afterProcess && h.afterProcess()))
const registerPreMixin = async () => {
await registerMixin(styleTemplater)
await registerMixin(contextMenu, notification, progressBar, formDialog, stateRecorder, hotkeyHub, exportHelper)
}
const registerPostMixin = async () => {
await registerMixin(eventHub)
await registerMixin(diagramParser, thirdPartyDiagramParser)
eventHub.publishEvent(eventHub.eventType.allPluginsHadInjected)
}
return async pluginLoader => {
await registerPreMixin()
await pluginLoader()
await registerPostMixin()
await optimizeMixin()
// Due to being an asynchronous function, some events (such as afterAddCodeBlock) may have been missed. Reload it
if (File.getMountFolder() != null) {
setTimeout(utils.reload, 50)
}
}
}
|
Backup before `File.editor.stylize.toggleFences()` as it uses `File.option` to set block code language. Restore after.
|
getHook
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/index.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/index.js
|
MIT
|
getHook = utils => {
const mixin = newMixin(utils)
Object.assign(utils, mixin)
const {
styleTemplater, hotkeyHub, eventHub, stateRecorder, exportHelper, contextMenu,
notification, progressBar, formDialog, diagramParser, thirdPartyDiagramParser,
} = mixin
const registerMixin = (...ele) => Promise.all(ele.map(h => h.process && h.process()))
const optimizeMixin = () => Promise.all(Object.values(mixin).map(h => h.afterProcess && h.afterProcess()))
const registerPreMixin = async () => {
await registerMixin(styleTemplater)
await registerMixin(contextMenu, notification, progressBar, formDialog, stateRecorder, hotkeyHub, exportHelper)
}
const registerPostMixin = async () => {
await registerMixin(eventHub)
await registerMixin(diagramParser, thirdPartyDiagramParser)
eventHub.publishEvent(eventHub.eventType.allPluginsHadInjected)
}
return async pluginLoader => {
await registerPreMixin()
await pluginLoader()
await registerPostMixin()
await optimizeMixin()
// Due to being an asynchronous function, some events (such as afterAddCodeBlock) may have been missed. Reload it
if (File.getMountFolder() != null) {
setTimeout(utils.reload, 50)
}
}
}
|
Backup before `File.editor.stylize.toggleFences()` as it uses `File.option` to set block code language. Restore after.
|
getHook
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/index.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/index.js
|
MIT
|
registerPreMixin = async () => {
await registerMixin(styleTemplater)
await registerMixin(contextMenu, notification, progressBar, formDialog, stateRecorder, hotkeyHub, exportHelper)
}
|
Backup before `File.editor.stylize.toggleFences()` as it uses `File.option` to set block code language. Restore after.
|
registerPreMixin
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/index.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/index.js
|
MIT
|
registerPreMixin = async () => {
await registerMixin(styleTemplater)
await registerMixin(contextMenu, notification, progressBar, formDialog, stateRecorder, hotkeyHub, exportHelper)
}
|
Backup before `File.editor.stylize.toggleFences()` as it uses `File.option` to set block code language. Restore after.
|
registerPreMixin
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/index.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/index.js
|
MIT
|
registerPostMixin = async () => {
await registerMixin(eventHub)
await registerMixin(diagramParser, thirdPartyDiagramParser)
eventHub.publishEvent(eventHub.eventType.allPluginsHadInjected)
}
|
Backup before `File.editor.stylize.toggleFences()` as it uses `File.option` to set block code language. Restore after.
|
registerPostMixin
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/index.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/index.js
|
MIT
|
registerPostMixin = async () => {
await registerMixin(eventHub)
await registerMixin(diagramParser, thirdPartyDiagramParser)
eventHub.publishEvent(eventHub.eventType.allPluginsHadInjected)
}
|
Backup before `File.editor.stylize.toggleFences()` as it uses `File.option` to set block code language. Restore after.
|
registerPostMixin
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/index.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/index.js
|
MIT
|
constructor(utils) {
this.utils = utils
}
|
Handles migration operations during the upgrade process.
|
constructor
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/migrate.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/migrate.js
|
MIT
|
constructor(utils) {
this.utils = utils;
this.recorders = new Map(); // map[name]recorder
}
|
Dynamically register and unregister element state recorders (only effective when the window_tab plugin is enabled).
Functionality: Record the state of elements before the user switches tabs, and restore the state of the elements when the user switches back.
For example: plugin `collapse_paragraph`: It is necessary to record which chapters are folded before the user switches tabs,
and then automatically fold the chapters back after the user switches back to maintain consistency.
|
constructor
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/stateRecorder.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/stateRecorder.js
|
MIT
|
constructor(utils) {
this.utils = utils;
this.parsers = new Map();
this.defaultHeight = "230px";
this.defaultBackgroundColor = "#F8F8F8";
this.regexp = /^\/\/{height:"(?<height>.*?)",width:"(?<width>.*?)"}/;
}
|
Dynamically register and unregister third-party code block diagram (derived from DiagramParser).
|
constructor
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/thirdPartyDiagramParser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/thirdPartyDiagramParser.js
|
MIT
|
getLifeCycleFn = (fnName) => () => {
for (const parser of this.parsers.values()) {
if (!parser[fnName]) continue
parser.instanceMap.forEach((instance, cid) => {
const preview = this.utils.entities.querySelectorInWrite(`.md-fences[cid=${cid}] .md-diagram-panel-preview`)
if (preview) {
parser[fnName](preview, instance)
}
})
}
}
|
Since JS doesn't support interfaces, interface functions are passed as parameters.
@param {string} lang: Language.
@param {string} mappingLang: Language to map to.
@param {boolean} destroyWhenUpdate: Whether to clear the HTML in the preview before updating.
@param {boolean} interactiveMode: When in interactive mode, code blocks will not automatically expand.
@param {string} checkSelector: Selector to check if the target Element exists under the current fence.
@param {string|function($pre):string} wrapElement: If the target Element does not exist, create it.
@param {function(): Promise<null>} lazyLoadFunc: Lazy load third-party resources.
@param {function(cid, content, $pre): Promise} setStyleFunc: Set styles.
@param {function(cid, content, $pre): Promise} beforeRenderFunc: Execute before rendering.
@param {function($wrap, string, meta): instance} createFunc: Create a diagram instance, passing in the target Element and the content of the fence.
@param {function($wrap, string, instance, meta): instance} updateFunc: Update the diagram instance when the content is updated.
@param {function(Object): null} destroyFunc: Destroy the diagram instance, passing in the diagram instance.
@param {function(Element, instance): null} beforeExportToNative: Preparation operations before Pandoc export (e.g., adjusting diagram size, color, etc.).
@param {function(Element, instance): null} beforeExportToHTML: Preparation operations before HTML export (e.g., adjusting diagram size, color, etc.).
@param {function(): string} extraStyleGetter: Get extra CSS for export.
@param {function(): string} versionGetter: Get the version.
|
getLifeCycleFn
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/thirdPartyDiagramParser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/thirdPartyDiagramParser.js
|
MIT
|
getLifeCycleFn = (fnName) => () => {
for (const parser of this.parsers.values()) {
if (!parser[fnName]) continue
parser.instanceMap.forEach((instance, cid) => {
const preview = this.utils.entities.querySelectorInWrite(`.md-fences[cid=${cid}] .md-diagram-panel-preview`)
if (preview) {
parser[fnName](preview, instance)
}
})
}
}
|
Since JS doesn't support interfaces, interface functions are passed as parameters.
@param {string} lang: Language.
@param {string} mappingLang: Language to map to.
@param {boolean} destroyWhenUpdate: Whether to clear the HTML in the preview before updating.
@param {boolean} interactiveMode: When in interactive mode, code blocks will not automatically expand.
@param {string} checkSelector: Selector to check if the target Element exists under the current fence.
@param {string|function($pre):string} wrapElement: If the target Element does not exist, create it.
@param {function(): Promise<null>} lazyLoadFunc: Lazy load third-party resources.
@param {function(cid, content, $pre): Promise} setStyleFunc: Set styles.
@param {function(cid, content, $pre): Promise} beforeRenderFunc: Execute before rendering.
@param {function($wrap, string, meta): instance} createFunc: Create a diagram instance, passing in the target Element and the content of the fence.
@param {function($wrap, string, instance, meta): instance} updateFunc: Update the diagram instance when the content is updated.
@param {function(Object): null} destroyFunc: Destroy the diagram instance, passing in the diagram instance.
@param {function(Element, instance): null} beforeExportToNative: Preparation operations before Pandoc export (e.g., adjusting diagram size, color, etc.).
@param {function(Element, instance): null} beforeExportToHTML: Preparation operations before HTML export (e.g., adjusting diagram size, color, etc.).
@param {function(): string} extraStyleGetter: Get extra CSS for export.
@param {function(): string} versionGetter: Get the version.
|
getLifeCycleFn
|
javascript
|
obgnail/typora_plugin
|
plugin/global/core/utils/thirdPartyDiagramParser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/global/core/utils/thirdPartyDiagramParser.js
|
MIT
|
translateFieldBaseProps = (field, pluginI18N) => {
baseProps.forEach(prop => {
const propVal = field[prop]
if (propVal != null) {
const commonVal = commonI18N[prop][propVal]
const pluginVal = pluginI18N[propVal]
field[prop] = commonVal || pluginVal
}
})
}
|
Will NOT modify the schemas structure, just i18n
|
translateFieldBaseProps
|
javascript
|
obgnail/typora_plugin
|
plugin/preferences/index.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/preferences/index.js
|
MIT
|
translateFieldBaseProps = (field, pluginI18N) => {
baseProps.forEach(prop => {
const propVal = field[prop]
if (propVal != null) {
const commonVal = commonI18N[prop][propVal]
const pluginVal = pluginI18N[propVal]
field[prop] = commonVal || pluginVal
}
})
}
|
Will NOT modify the schemas structure, just i18n
|
translateFieldBaseProps
|
javascript
|
obgnail/typora_plugin
|
plugin/preferences/index.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/preferences/index.js
|
MIT
|
translateFieldSpecialProps = (field, pluginI18N) => {
specialProps.forEach(prop => {
const propVal = field[prop]
if (propVal != null) {
Object.keys(propVal).forEach(k => {
const i18nKey = propVal[k]
propVal[k] = pluginI18N[i18nKey]
})
}
})
}
|
Will NOT modify the schemas structure, just i18n
|
translateFieldSpecialProps
|
javascript
|
obgnail/typora_plugin
|
plugin/preferences/index.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/preferences/index.js
|
MIT
|
translateFieldSpecialProps = (field, pluginI18N) => {
specialProps.forEach(prop => {
const propVal = field[prop]
if (propVal != null) {
Object.keys(propVal).forEach(k => {
const i18nKey = propVal[k]
propVal[k] = pluginI18N[i18nKey]
})
}
})
}
|
Will NOT modify the schemas structure, just i18n
|
translateFieldSpecialProps
|
javascript
|
obgnail/typora_plugin
|
plugin/preferences/index.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/preferences/index.js
|
MIT
|
translateFieldNestedBoxesProp = (field, pluginI18N) => {
if (field.nestedBoxes != null) {
field.nestedBoxes.forEach(box => translateBox(box, pluginI18N))
}
}
|
Will NOT modify the schemas structure, just i18n
|
translateFieldNestedBoxesProp
|
javascript
|
obgnail/typora_plugin
|
plugin/preferences/index.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/preferences/index.js
|
MIT
|
translateFieldNestedBoxesProp = (field, pluginI18N) => {
if (field.nestedBoxes != null) {
field.nestedBoxes.forEach(box => translateBox(box, pluginI18N))
}
}
|
Will NOT modify the schemas structure, just i18n
|
translateFieldNestedBoxesProp
|
javascript
|
obgnail/typora_plugin
|
plugin/preferences/index.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/preferences/index.js
|
MIT
|
translateFieldUnitProp = (field) => {
if (field.unit != null) {
field.unit = commonI18N.unit[field.unit]
}
}
|
Will NOT modify the schemas structure, just i18n
|
translateFieldUnitProp
|
javascript
|
obgnail/typora_plugin
|
plugin/preferences/index.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/preferences/index.js
|
MIT
|
translateFieldUnitProp = (field) => {
if (field.unit != null) {
field.unit = commonI18N.unit[field.unit]
}
}
|
Will NOT modify the schemas structure, just i18n
|
translateFieldUnitProp
|
javascript
|
obgnail/typora_plugin
|
plugin/preferences/index.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/preferences/index.js
|
MIT
|
translateBox = (box, pluginI18N) => {
const t = box.title
if (t) {
const commonVal = commonI18N.title[t]
const pluginVal = pluginI18N[t]
box.title = commonVal || pluginVal
}
box.fields.forEach(field => {
translateFieldBaseProps(field, pluginI18N)
translateFieldSpecialProps(field, pluginI18N)
translateFieldNestedBoxesProp(field, pluginI18N)
translateFieldUnitProp(field)
})
}
|
Will NOT modify the schemas structure, just i18n
|
translateBox
|
javascript
|
obgnail/typora_plugin
|
plugin/preferences/index.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/preferences/index.js
|
MIT
|
translateBox = (box, pluginI18N) => {
const t = box.title
if (t) {
const commonVal = commonI18N.title[t]
const pluginVal = pluginI18N[t]
box.title = commonVal || pluginVal
}
box.fields.forEach(field => {
translateFieldBaseProps(field, pluginI18N)
translateFieldSpecialProps(field, pluginI18N)
translateFieldNestedBoxesProp(field, pluginI18N)
translateFieldUnitProp(field)
})
}
|
Will NOT modify the schemas structure, just i18n
|
translateBox
|
javascript
|
obgnail/typora_plugin
|
plugin/preferences/index.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/preferences/index.js
|
MIT
|
uninstall = async () => {
const { FsExtra } = this.utils.Package
const remove = '<script src="./plugin/index.js" defer="defer"></script>'
const windowHTML = this.utils.joinPath("./window.html")
const pluginFolder = this.utils.joinPath("./plugin")
try {
const content = await FsExtra.readFile(windowHTML, "utf-8")
const newContent = content.replace(remove, "")
await FsExtra.writeFile(windowHTML, newContent)
await FsExtra.remove(pluginFolder)
} catch (e) {
alert(e.toString())
return
}
const message = this.i18n._t("global", "success.uninstall")
const confirm = this.i18n._t("global", "confirm")
const op = { type: "info", title: "typora plugin", message, buttons: [confirm] }
await this.utils.showMessageBox(op)
this.utils.restartTypora(false)
}
|
Callback functions for type="action" settings in schema
|
uninstall
|
javascript
|
obgnail/typora_plugin
|
plugin/preferences/index.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/preferences/index.js
|
MIT
|
uninstall = async () => {
const { FsExtra } = this.utils.Package
const remove = '<script src="./plugin/index.js" defer="defer"></script>'
const windowHTML = this.utils.joinPath("./window.html")
const pluginFolder = this.utils.joinPath("./plugin")
try {
const content = await FsExtra.readFile(windowHTML, "utf-8")
const newContent = content.replace(remove, "")
await FsExtra.writeFile(windowHTML, newContent)
await FsExtra.remove(pluginFolder)
} catch (e) {
alert(e.toString())
return
}
const message = this.i18n._t("global", "success.uninstall")
const confirm = this.i18n._t("global", "confirm")
const op = { type: "info", title: "typora plugin", message, buttons: [confirm] }
await this.utils.showMessageBox(op)
this.utils.restartTypora(false)
}
|
Callback functions for type="action" settings in schema
|
uninstall
|
javascript
|
obgnail/typora_plugin
|
plugin/preferences/index.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/preferences/index.js
|
MIT
|
_decompress = (compressed) => {
const [chunk, raw] = compressed.split("-", 2)
const rows = raw.match(new RegExp(`\\w{${chunk}}`, "g"))
return rows.map(r => parseInt(r, 36).toString(2).padStart(rows.length, "0"))
}
|
Callback functions for type="action" settings in schema
|
_decompress
|
javascript
|
obgnail/typora_plugin
|
plugin/preferences/index.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/preferences/index.js
|
MIT
|
_decompress = (compressed) => {
const [chunk, raw] = compressed.split("-", 2)
const rows = raw.match(new RegExp(`\\w{${chunk}}`, "g"))
return rows.map(r => parseInt(r, 36).toString(2).padStart(rows.length, "0"))
}
|
Callback functions for type="action" settings in schema
|
_decompress
|
javascript
|
obgnail/typora_plugin
|
plugin/preferences/index.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/preferences/index.js
|
MIT
|
_toSVG = (compressed, fillColor, size) => {
const table = _decompress(compressed)
const numModules = table.length
const moduleSize = (size / numModules).toFixed(2)
const paths = []
for (let rIdx = 0; rIdx < numModules; rIdx++) {
for (let cIdx = 0; cIdx < numModules; cIdx++) {
if (table[rIdx][cIdx] === "1") {
const x = (cIdx * moduleSize).toFixed(2)
const y = (rIdx * moduleSize).toFixed(2)
paths.push(`M${x},${y}h${moduleSize}v${moduleSize}h${-moduleSize}Z`)
}
}
}
return `<svg width="${size}" height="${size}" viewBox="0 0 ${size} ${size}"><path d="${paths.join("")}" fill="${fillColor}" /></svg>`
}
|
Callback functions for type="action" settings in schema
|
_toSVG
|
javascript
|
obgnail/typora_plugin
|
plugin/preferences/index.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/preferences/index.js
|
MIT
|
_toSVG = (compressed, fillColor, size) => {
const table = _decompress(compressed)
const numModules = table.length
const moduleSize = (size / numModules).toFixed(2)
const paths = []
for (let rIdx = 0; rIdx < numModules; rIdx++) {
for (let cIdx = 0; cIdx < numModules; cIdx++) {
if (table[rIdx][cIdx] === "1") {
const x = (cIdx * moduleSize).toFixed(2)
const y = (rIdx * moduleSize).toFixed(2)
paths.push(`M${x},${y}h${moduleSize}v${moduleSize}h${-moduleSize}Z`)
}
}
}
return `<svg width="${size}" height="${size}" viewBox="0 0 ${size} ${size}"><path d="${paths.join("")}" fill="${fillColor}" /></svg>`
}
|
Callback functions for type="action" settings in schema
|
_toSVG
|
javascript
|
obgnail/typora_plugin
|
plugin/preferences/index.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/preferences/index.js
|
MIT
|
_incompatibleSwitch = (field, settings, tooltip = this.i18n._t("settings", "$tooltip.lowVersion")) => {
field.disabled = true
field.tooltip = tooltip
settings[field.key] = false
}
|
PreProcessors for specific settings in schema
|
_incompatibleSwitch
|
javascript
|
obgnail/typora_plugin
|
plugin/preferences/index.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/preferences/index.js
|
MIT
|
_incompatibleSwitch = (field, settings, tooltip = this.i18n._t("settings", "$tooltip.lowVersion")) => {
field.disabled = true
field.tooltip = tooltip
settings[field.key] = false
}
|
PreProcessors for specific settings in schema
|
_incompatibleSwitch
|
javascript
|
obgnail/typora_plugin
|
plugin/preferences/index.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/preferences/index.js
|
MIT
|
constructor() {
const TYPE = {
OR: "OR",
AND: "AND",
NOT: "NOT",
PAREN_OPEN: "PAREN_OPEN",
PAREN_CLOSE: "PAREN_CLOSE",
KEYWORD: "KEYWORD",
PHRASE: "PHRASE",
REGEXP: "REGEXP",
QUALIFIER: "QUALIFIER",
}
this.TYPE = TYPE
const { OR, AND, NOT, QUALIFIER, PAREN_OPEN, PAREN_CLOSE } = TYPE
this.INVALID_POSITION = {
FIRST: new Set([OR, AND, PAREN_CLOSE]),
LAST: new Set([OR, AND, NOT, PAREN_OPEN, QUALIFIER]),
FOLLOW: {
[OR]: new Set([OR, AND, PAREN_CLOSE]),
[AND]: new Set([OR, AND, PAREN_CLOSE]),
[NOT]: new Set([OR, AND, NOT, PAREN_CLOSE]),
[PAREN_OPEN]: new Set([OR, AND, PAREN_CLOSE]),
[QUALIFIER]: new Set([OR, AND, NOT, PAREN_CLOSE, QUALIFIER]),
},
AND: {
PREV: new Set([OR, AND, NOT, PAREN_OPEN, QUALIFIER]),
NEXT: new Set([OR, AND, NOT, PAREN_CLOSE]),
},
}
this.setQualifier()
}
|
grammar:
<query> ::= <expression>
<expression> ::= <term> ( <or> <term> )*
<term> ::= <factor> ( <conjunction> <factor> )*
<factor> ::= <qualifier>? <match>
<qualifier> ::= <scope> <operator>
<match> ::= <keyword> | '"'<keyword>'"' | '/'<regexp>'/' | '('<expression>')'
<conjunction> ::= <and> | <not>
<and> ::= 'AND' | ' '
<or> ::= 'OR' | '|'
<not> ::= 'NOT' | '-'
<keyword> ::= [^\\s"()|]+
<regexp> ::= [^/]+
<operator> ::= ':' | '=' | '>=' | '<=' | '>' | '<'
<scope> ::= 'default' | 'file' | 'path' | 'ext' | 'content' | 'size' | 'time'
|
constructor
|
javascript
|
obgnail/typora_plugin
|
plugin/search_multi/parser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/search_multi/parser.js
|
MIT
|
setQualifier(scope = ["default", "file", "path", "ext", "content", "time", "size"], operator = [">=", "<=", ":", "=", ">", "<"]) {
const byLength = (a, b) => b.length - a.length
const _scope = [...scope].sort(byLength).join("|")
const _operator = [...operator].sort(byLength).join("|")
this.regex = new RegExp(
[
`(?<AND>(\\s|\\bAND\\b)+)`,
`(?<NOT>-|\\bNOT\\b)`,
`"(?<PHRASE>[^"]*)"`,
`(?<PAREN_OPEN>\\()`,
`(?<PAREN_CLOSE>\\))`,
`(?<OR>\\||\\bOR\\b)`,
`(?<QUALIFIER>(?<SCOPE>${_scope})(?<OPERATOR>${_operator}))`,
`\\/(?<REGEXP>.*?)(?<!\\\\)\\/`,
`(?<KEYWORD>[^\\s"()|]+)`,
].join("|"),
"gi"
)
}
|
grammar:
<query> ::= <expression>
<expression> ::= <term> ( <or> <term> )*
<term> ::= <factor> ( <conjunction> <factor> )*
<factor> ::= <qualifier>? <match>
<qualifier> ::= <scope> <operator>
<match> ::= <keyword> | '"'<keyword>'"' | '/'<regexp>'/' | '('<expression>')'
<conjunction> ::= <and> | <not>
<and> ::= 'AND' | ' '
<or> ::= 'OR' | '|'
<not> ::= 'NOT' | '-'
<keyword> ::= [^\\s"()|]+
<regexp> ::= [^/]+
<operator> ::= ':' | '=' | '>=' | '<=' | '>' | '<'
<scope> ::= 'default' | 'file' | 'path' | 'ext' | 'content' | 'size' | 'time'
|
setQualifier
|
javascript
|
obgnail/typora_plugin
|
plugin/search_multi/parser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/search_multi/parser.js
|
MIT
|
tokenize(query) {
return [...query.trim().matchAll(this.regex)]
.map(_tokens => {
const [qualifier, operand = ""] = Object.entries(_tokens.groups).find(([_, v]) => v != null)
const type = this.TYPE[qualifier] || this.TYPE.KEYWORD
return qualifier === this.TYPE.QUALIFIER
? { type, scope: _tokens.groups.SCOPE, operator: _tokens.groups.OPERATOR }
: { type, operand }
})
.filter((token, i, tokens) => {
if (token.type !== this.TYPE.AND) {
return true
}
const prev = tokens[i - 1]
const next = tokens[i + 1]
let result = true
if (prev) {
result = result && !this.INVALID_POSITION.AND.PREV.has(prev.type)
}
if (next) {
result = result && !this.INVALID_POSITION.AND.NEXT.has(next.type)
}
return result
})
}
|
grammar:
<query> ::= <expression>
<expression> ::= <term> ( <or> <term> )*
<term> ::= <factor> ( <conjunction> <factor> )*
<factor> ::= <qualifier>? <match>
<qualifier> ::= <scope> <operator>
<match> ::= <keyword> | '"'<keyword>'"' | '/'<regexp>'/' | '('<expression>')'
<conjunction> ::= <and> | <not>
<and> ::= 'AND' | ' '
<or> ::= 'OR' | '|'
<not> ::= 'NOT' | '-'
<keyword> ::= [^\\s"()|]+
<regexp> ::= [^/]+
<operator> ::= ':' | '=' | '>=' | '<=' | '>' | '<'
<scope> ::= 'default' | 'file' | 'path' | 'ext' | 'content' | 'size' | 'time'
|
tokenize
|
javascript
|
obgnail/typora_plugin
|
plugin/search_multi/parser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/search_multi/parser.js
|
MIT
|
_parseExpression(tokens) {
let node = this._parseTerm(tokens)
while (tokens.length > 0) {
const type = tokens[0].type
if (type === this.TYPE.OR) {
tokens.shift()
const right = this._parseTerm(tokens)
node = { type, left: node, right }
} else {
break
}
}
return node
}
|
grammar:
<query> ::= <expression>
<expression> ::= <term> ( <or> <term> )*
<term> ::= <factor> ( <conjunction> <factor> )*
<factor> ::= <qualifier>? <match>
<qualifier> ::= <scope> <operator>
<match> ::= <keyword> | '"'<keyword>'"' | '/'<regexp>'/' | '('<expression>')'
<conjunction> ::= <and> | <not>
<and> ::= 'AND' | ' '
<or> ::= 'OR' | '|'
<not> ::= 'NOT' | '-'
<keyword> ::= [^\\s"()|]+
<regexp> ::= [^/]+
<operator> ::= ':' | '=' | '>=' | '<=' | '>' | '<'
<scope> ::= 'default' | 'file' | 'path' | 'ext' | 'content' | 'size' | 'time'
|
_parseExpression
|
javascript
|
obgnail/typora_plugin
|
plugin/search_multi/parser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/search_multi/parser.js
|
MIT
|
_parseTerm(tokens) {
let node = this._parseFactor(tokens)
while (tokens.length > 0) {
const type = tokens[0].type
if (type === this.TYPE.NOT || type === this.TYPE.AND) {
tokens.shift()
const right = this._parseFactor(tokens)
node = { type, left: node, right }
} else {
break
}
}
return node
}
|
grammar:
<query> ::= <expression>
<expression> ::= <term> ( <or> <term> )*
<term> ::= <factor> ( <conjunction> <factor> )*
<factor> ::= <qualifier>? <match>
<qualifier> ::= <scope> <operator>
<match> ::= <keyword> | '"'<keyword>'"' | '/'<regexp>'/' | '('<expression>')'
<conjunction> ::= <and> | <not>
<and> ::= 'AND' | ' '
<or> ::= 'OR' | '|'
<not> ::= 'NOT' | '-'
<keyword> ::= [^\\s"()|]+
<regexp> ::= [^/]+
<operator> ::= ':' | '=' | '>=' | '<=' | '>' | '<'
<scope> ::= 'default' | 'file' | 'path' | 'ext' | 'content' | 'size' | 'time'
|
_parseTerm
|
javascript
|
obgnail/typora_plugin
|
plugin/search_multi/parser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/search_multi/parser.js
|
MIT
|
_parseFactor(tokens) {
const qualifier = (tokens[0].type === this.TYPE.QUALIFIER)
? tokens.shift()
: { type: this.TYPE.QUALIFIER, scope: "default", operator: ":" }
const node = this._parseMatch(tokens)
return this._setQualifier(node, qualifier)
}
|
grammar:
<query> ::= <expression>
<expression> ::= <term> ( <or> <term> )*
<term> ::= <factor> ( <conjunction> <factor> )*
<factor> ::= <qualifier>? <match>
<qualifier> ::= <scope> <operator>
<match> ::= <keyword> | '"'<keyword>'"' | '/'<regexp>'/' | '('<expression>')'
<conjunction> ::= <and> | <not>
<and> ::= 'AND' | ' '
<or> ::= 'OR' | '|'
<not> ::= 'NOT' | '-'
<keyword> ::= [^\\s"()|]+
<regexp> ::= [^/]+
<operator> ::= ':' | '=' | '>=' | '<=' | '>' | '<'
<scope> ::= 'default' | 'file' | 'path' | 'ext' | 'content' | 'size' | 'time'
|
_parseFactor
|
javascript
|
obgnail/typora_plugin
|
plugin/search_multi/parser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/search_multi/parser.js
|
MIT
|
_setQualifier(node, qualifier) {
if (!node) return
const type = node.type
const isLeaf = type === this.TYPE.PHRASE || type === this.TYPE.KEYWORD || type === this.TYPE.REGEXP
const isDefault = !node.scope || node.scope === "default"
if (isLeaf && isDefault) {
node.scope = qualifier.scope
node.operator = qualifier.operator
} else {
this._setQualifier(node.left, qualifier)
this._setQualifier(node.right, qualifier)
}
return node
}
|
grammar:
<query> ::= <expression>
<expression> ::= <term> ( <or> <term> )*
<term> ::= <factor> ( <conjunction> <factor> )*
<factor> ::= <qualifier>? <match>
<qualifier> ::= <scope> <operator>
<match> ::= <keyword> | '"'<keyword>'"' | '/'<regexp>'/' | '('<expression>')'
<conjunction> ::= <and> | <not>
<and> ::= 'AND' | ' '
<or> ::= 'OR' | '|'
<not> ::= 'NOT' | '-'
<keyword> ::= [^\\s"()|]+
<regexp> ::= [^/]+
<operator> ::= ':' | '=' | '>=' | '<=' | '>' | '<'
<scope> ::= 'default' | 'file' | 'path' | 'ext' | 'content' | 'size' | 'time'
|
_setQualifier
|
javascript
|
obgnail/typora_plugin
|
plugin/search_multi/parser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/search_multi/parser.js
|
MIT
|
parse(query) {
query = query.trim()
const tokens = this.tokenize(query)
if (tokens.length === 0) {
// return { type: this.TYPE.KEYWORD, scope: "default", operator: ":", operand: "" }
throw new Error(`Empty Tokens`)
}
this.check(tokens)
const ast = this._parseExpression(tokens)
if (tokens.length !== 0) {
throw new Error(`Failed to Parse Tokens: ${tokens.join(" ")}`)
}
return ast
}
|
grammar:
<query> ::= <expression>
<expression> ::= <term> ( <or> <term> )*
<term> ::= <factor> ( <conjunction> <factor> )*
<factor> ::= <qualifier>? <match>
<qualifier> ::= <scope> <operator>
<match> ::= <keyword> | '"'<keyword>'"' | '/'<regexp>'/' | '('<expression>')'
<conjunction> ::= <and> | <not>
<and> ::= 'AND' | ' '
<or> ::= 'OR' | '|'
<not> ::= 'NOT' | '-'
<keyword> ::= [^\\s"()|]+
<regexp> ::= [^/]+
<operator> ::= ':' | '=' | '>=' | '<=' | '>' | '<'
<scope> ::= 'default' | 'file' | 'path' | 'ext' | 'content' | 'size' | 'time'
|
parse
|
javascript
|
obgnail/typora_plugin
|
plugin/search_multi/parser.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/search_multi/parser.js
|
MIT
|
constructor(plugin) {
this.MIXIN = QualifierMixin
this.config = plugin.config
this.utils = plugin.utils
this.i18n = plugin.i18n
this.parser = new Parser()
this.qualifiers = new Map()
}
|
The matching process consists of the following steps: (Steps 1-4 are executed once; steps 5-6 are executed repeatedly)
1. Parse: Parses the input to generate an Abstract Syntax Tree (AST)
2. Preprocess: Convert certain specific, predefined, and special meaning vocabulary (e.g. converting 'today' in 'mtime=today' to '2024-01-01')
3. Validate: Validates the AST for correctness
4. Cast: Converts operand within the AST nodes into a usable format (e.g. converting '2024-01-01' in 'mtime=2024-01-01' to a timestamp for easier matching). The result is `castResult`
5. Query: Retrieves file data, resulting in `queryResult`
6. Match: Matches `castResult` (from step 4) with `queryResult` (from step 5)
A qualifier has the following attributes:
{string} scope: The query scope
{string} name: A descriptive name for explanation purposes
{string} ancestor: The ancestor Element in DOM. Only available when is_meta=false. Defaults to `QualifierMixin.ANCESTOR.none`
{boolean} is_meta: Indicates if the qualifier scope is a metadata property
{boolean} need_read_file: Determines if the qualifier needs to read file content
{number} cost: The performance cost associated with the `query` function. 1: Read file stats; 2: Read file content; 3: Parse file content; Plus 0.5 when the user input is a regex
{function} preprocess: Convert certain specific, predefined, and special meaning vocabulary from the user input. Defaults to `QualifierMixin.PREPROCESS.noop`
{function} validate: Checks user input and obtain `validateError`. Defaults to `QualifierMixin.VALIDATE.isStringOrRegexp`
{function} cast: Converts user input for easier matching and obtain `castResult`. Defaults to `QualifierMixin.CAST.toStringOrRegexp`
{function} query: Retrieves data from source and obtain `queryResult`
{function} match_keyword: Matches `castResult` with `queryResult` when the user input is a keyword. Defaults to `QualifierMixin.MATCH.compare`
{function} match_phrase: Matches `castResult` with `queryResult` when the user input is a phrase. Behaves the same as `match_keyword` by default
{function} match_regexp: Matches `castResult` with `queryResult` when the user input is a regexp. Defaults to `QualifierMixin.MATCH.regexp`
|
constructor
|
javascript
|
obgnail/typora_plugin
|
plugin/search_multi/searcher.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/search_multi/searcher.js
|
MIT
|
process() {
const qualifiers = this.buildQualifiers()
qualifiers.forEach(q => this.qualifiers.set(q.scope, q))
this.parser.setQualifier(qualifiers.map(q => q.scope), Object.keys(this.MIXIN.OPERATOR))
}
|
The matching process consists of the following steps: (Steps 1-4 are executed once; steps 5-6 are executed repeatedly)
1. Parse: Parses the input to generate an Abstract Syntax Tree (AST)
2. Preprocess: Convert certain specific, predefined, and special meaning vocabulary (e.g. converting 'today' in 'mtime=today' to '2024-01-01')
3. Validate: Validates the AST for correctness
4. Cast: Converts operand within the AST nodes into a usable format (e.g. converting '2024-01-01' in 'mtime=2024-01-01' to a timestamp for easier matching). The result is `castResult`
5. Query: Retrieves file data, resulting in `queryResult`
6. Match: Matches `castResult` (from step 4) with `queryResult` (from step 5)
A qualifier has the following attributes:
{string} scope: The query scope
{string} name: A descriptive name for explanation purposes
{string} ancestor: The ancestor Element in DOM. Only available when is_meta=false. Defaults to `QualifierMixin.ANCESTOR.none`
{boolean} is_meta: Indicates if the qualifier scope is a metadata property
{boolean} need_read_file: Determines if the qualifier needs to read file content
{number} cost: The performance cost associated with the `query` function. 1: Read file stats; 2: Read file content; 3: Parse file content; Plus 0.5 when the user input is a regex
{function} preprocess: Convert certain specific, predefined, and special meaning vocabulary from the user input. Defaults to `QualifierMixin.PREPROCESS.noop`
{function} validate: Checks user input and obtain `validateError`. Defaults to `QualifierMixin.VALIDATE.isStringOrRegexp`
{function} cast: Converts user input for easier matching and obtain `castResult`. Defaults to `QualifierMixin.CAST.toStringOrRegexp`
{function} query: Retrieves data from source and obtain `queryResult`
{function} match_keyword: Matches `castResult` with `queryResult` when the user input is a keyword. Defaults to `QualifierMixin.MATCH.compare`
{function} match_phrase: Matches `castResult` with `queryResult` when the user input is a phrase. Behaves the same as `match_keyword` by default
{function} match_regexp: Matches `castResult` with `queryResult` when the user input is a regexp. Defaults to `QualifierMixin.MATCH.regexp`
|
process
|
javascript
|
obgnail/typora_plugin
|
plugin/search_multi/searcher.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/search_multi/searcher.js
|
MIT
|
buildQualifiers() {
const qualifiers = [...this.buildBaseQualifiers(), ...this.buildMarkdownQualifiers()]
qualifiers.forEach(q => {
q.preprocess = q.preprocess || this.MIXIN.PREPROCESS.noop
q.validate = q.validate || this.MIXIN.VALIDATE.isStringOrRegexp
q.anchor = q.anchor || this.MIXIN.ANCESTOR.none
q.cast = q.cast || this.MIXIN.CAST.toStringOrRegexp
q.KEYWORD = q.match_keyword || this.MIXIN.MATCH.primitiveCompare
q.PHRASE = q.match_phrase || q.KEYWORD
q.REGEXP = q.match_regexp || this.MIXIN.MATCH.stringRegexp
})
return qualifiers
}
|
The matching process consists of the following steps: (Steps 1-4 are executed once; steps 5-6 are executed repeatedly)
1. Parse: Parses the input to generate an Abstract Syntax Tree (AST)
2. Preprocess: Convert certain specific, predefined, and special meaning vocabulary (e.g. converting 'today' in 'mtime=today' to '2024-01-01')
3. Validate: Validates the AST for correctness
4. Cast: Converts operand within the AST nodes into a usable format (e.g. converting '2024-01-01' in 'mtime=2024-01-01' to a timestamp for easier matching). The result is `castResult`
5. Query: Retrieves file data, resulting in `queryResult`
6. Match: Matches `castResult` (from step 4) with `queryResult` (from step 5)
A qualifier has the following attributes:
{string} scope: The query scope
{string} name: A descriptive name for explanation purposes
{string} ancestor: The ancestor Element in DOM. Only available when is_meta=false. Defaults to `QualifierMixin.ANCESTOR.none`
{boolean} is_meta: Indicates if the qualifier scope is a metadata property
{boolean} need_read_file: Determines if the qualifier needs to read file content
{number} cost: The performance cost associated with the `query` function. 1: Read file stats; 2: Read file content; 3: Parse file content; Plus 0.5 when the user input is a regex
{function} preprocess: Convert certain specific, predefined, and special meaning vocabulary from the user input. Defaults to `QualifierMixin.PREPROCESS.noop`
{function} validate: Checks user input and obtain `validateError`. Defaults to `QualifierMixin.VALIDATE.isStringOrRegexp`
{function} cast: Converts user input for easier matching and obtain `castResult`. Defaults to `QualifierMixin.CAST.toStringOrRegexp`
{function} query: Retrieves data from source and obtain `queryResult`
{function} match_keyword: Matches `castResult` with `queryResult` when the user input is a keyword. Defaults to `QualifierMixin.MATCH.compare`
{function} match_phrase: Matches `castResult` with `queryResult` when the user input is a phrase. Behaves the same as `match_keyword` by default
{function} match_regexp: Matches `castResult` with `queryResult` when the user input is a regexp. Defaults to `QualifierMixin.MATCH.regexp`
|
buildQualifiers
|
javascript
|
obgnail/typora_plugin
|
plugin/search_multi/searcher.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/search_multi/searcher.js
|
MIT
|
buildBaseQualifiers() {
const {
PREPROCESS: { resolveDate, resolveNumber, resolveBoolean },
VALIDATE: { isSize, isDate, isNumber, isBoolean },
CAST: { toBytes, toDate, toNumber, toBoolean },
MATCH: { arrayCompare, arrayRegexp },
QUERY: { normalizeDate },
ANCESTOR: { none, write },
} = this.MIXIN
const { splitFrontMatter, Package: { Path } } = this.utils
const QUERY = {
default: ({ path, file, stats, content }) => `${content}\n${path}`,
path: ({ path, file, stats, content }) => path,
dir: ({ path, file, stats, content }) => Path.dirname(path),
file: ({ path, file, stats, content }) => file,
name: ({ path, file, stats, content }) => Path.parse(file).name,
ext: ({ path, file, stats, content }) => Path.extname(file),
size: ({ path, file, stats, content }) => stats.size,
atime: ({ path, file, stats, content }) => normalizeDate(stats.atime),
mtime: ({ path, file, stats, content }) => normalizeDate(stats.mtime),
birthtime: ({ path, file, stats, content }) => normalizeDate(stats.birthtime),
content: ({ path, file, stats, content }) => content,
linenum: ({ path, file, stats, content }) => content.split("\n").length,
charnum: ({ path, file, stats, content }) => content.length,
crlf: ({ path, file, stats, content }) => content.includes("\r\n"),
hasimage: ({ path, file, stats, content }) => /!\[.*?\]\(.*\)|<img.*?src=".*?"/.test(content),
hasimg: ({ path, file, stats, content }) => /<img.*?src=".*?"/.test(content),
haschinese: ({ path, file, stats, content }) => /\p{sc=Han}/u.test(content),
hasemoji: ({ path, file, stats, content }) => /\p{Emoji_Modifier_Base}\p{Emoji_Modifier}?|\p{Emoji_Presentation}|\p{Emoji}\uFE0F/u.test(content),
hasinvisiblechar: ({ path, file, stats, content }) => /[\u0000-\u0008\u000B-\u000C\u000E-\u001F\u007F-\u009F\u200B-\u200D\uFEFF]/.test(content),
line: ({ path, file, stats, content }) => content.split("\n"),
frontmatter: ({ path, file, stats, content }) => {
const { yamlObject } = splitFrontMatter(content)
return yamlObject ? JSON.stringify(yamlObject) : ""
},
chinesenum: ({ path, file, stats, content }) => {
let count = 0
for (const _ of content.matchAll(/\p{sc=Han}/gu)) {
count++
}
return count
},
}
const PROCESS = {
size: { validate: isSize, cast: toBytes },
date: { preprocess: resolveDate, validate: isDate, cast: toDate },
number: { preprocess: resolveNumber, validate: isNumber, cast: toNumber },
boolean: { preprocess: resolveBoolean, validate: isBoolean, cast: toBoolean },
stringArray: { match_keyword: arrayCompare, match_regexp: arrayRegexp },
}
const buildQualifier = (scope, is_meta, need_read_file, cost, anchor, process) => ({
scope, name: this.i18n.t(`scope.${scope}`), is_meta, need_read_file, cost, anchor, query: QUERY[scope], ...process,
})
return [
buildQualifier("default", false, true, 2, write),
buildQualifier("path", true, false, 1, none),
buildQualifier("dir", true, false, 1, none),
buildQualifier("file", true, false, 1, none),
buildQualifier("name", true, false, 1, none),
buildQualifier("ext", true, false, 1, none),
buildQualifier("content", false, true, 2, write),
buildQualifier("frontmatter", false, true, 3, 'pre[mdtype="meta_block"]'),
buildQualifier("size", true, false, 1, none, PROCESS.size),
buildQualifier("birthtime", true, false, 1, none, PROCESS.date),
buildQualifier("mtime", true, false, 1, none, PROCESS.date),
buildQualifier("atime", true, false, 1, none, PROCESS.date),
buildQualifier("linenum", true, true, 2, none, PROCESS.number),
buildQualifier("charnum", true, true, 2, none, PROCESS.number),
buildQualifier("chinesenum", true, true, 2, none, PROCESS.number),
buildQualifier("crlf", true, true, 2, none, PROCESS.boolean),
buildQualifier("hasimage", true, true, 2, none, PROCESS.boolean),
buildQualifier("hasimg", true, true, 2, none, PROCESS.boolean),
buildQualifier("haschinese", true, true, 2, none, PROCESS.boolean),
buildQualifier("hasemoji", true, true, 2, none, PROCESS.boolean),
buildQualifier("hasinvisiblechar", true, true, 2, none, PROCESS.boolean),
buildQualifier("line", false, true, 2, write, PROCESS.stringArray),
]
}
|
The matching process consists of the following steps: (Steps 1-4 are executed once; steps 5-6 are executed repeatedly)
1. Parse: Parses the input to generate an Abstract Syntax Tree (AST)
2. Preprocess: Convert certain specific, predefined, and special meaning vocabulary (e.g. converting 'today' in 'mtime=today' to '2024-01-01')
3. Validate: Validates the AST for correctness
4. Cast: Converts operand within the AST nodes into a usable format (e.g. converting '2024-01-01' in 'mtime=2024-01-01' to a timestamp for easier matching). The result is `castResult`
5. Query: Retrieves file data, resulting in `queryResult`
6. Match: Matches `castResult` (from step 4) with `queryResult` (from step 5)
A qualifier has the following attributes:
{string} scope: The query scope
{string} name: A descriptive name for explanation purposes
{string} ancestor: The ancestor Element in DOM. Only available when is_meta=false. Defaults to `QualifierMixin.ANCESTOR.none`
{boolean} is_meta: Indicates if the qualifier scope is a metadata property
{boolean} need_read_file: Determines if the qualifier needs to read file content
{number} cost: The performance cost associated with the `query` function. 1: Read file stats; 2: Read file content; 3: Parse file content; Plus 0.5 when the user input is a regex
{function} preprocess: Convert certain specific, predefined, and special meaning vocabulary from the user input. Defaults to `QualifierMixin.PREPROCESS.noop`
{function} validate: Checks user input and obtain `validateError`. Defaults to `QualifierMixin.VALIDATE.isStringOrRegexp`
{function} cast: Converts user input for easier matching and obtain `castResult`. Defaults to `QualifierMixin.CAST.toStringOrRegexp`
{function} query: Retrieves data from source and obtain `queryResult`
{function} match_keyword: Matches `castResult` with `queryResult` when the user input is a keyword. Defaults to `QualifierMixin.MATCH.compare`
{function} match_phrase: Matches `castResult` with `queryResult` when the user input is a phrase. Behaves the same as `match_keyword` by default
{function} match_regexp: Matches `castResult` with `queryResult` when the user input is a regexp. Defaults to `QualifierMixin.MATCH.regexp`
|
buildBaseQualifiers
|
javascript
|
obgnail/typora_plugin
|
plugin/search_multi/searcher.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/search_multi/searcher.js
|
MIT
|
buildQualifier = (scope, is_meta, need_read_file, cost, anchor, process) => ({
scope, name: this.i18n.t(`scope.${scope}`), is_meta, need_read_file, cost, anchor, query: QUERY[scope], ...process,
})
|
The matching process consists of the following steps: (Steps 1-4 are executed once; steps 5-6 are executed repeatedly)
1. Parse: Parses the input to generate an Abstract Syntax Tree (AST)
2. Preprocess: Convert certain specific, predefined, and special meaning vocabulary (e.g. converting 'today' in 'mtime=today' to '2024-01-01')
3. Validate: Validates the AST for correctness
4. Cast: Converts operand within the AST nodes into a usable format (e.g. converting '2024-01-01' in 'mtime=2024-01-01' to a timestamp for easier matching). The result is `castResult`
5. Query: Retrieves file data, resulting in `queryResult`
6. Match: Matches `castResult` (from step 4) with `queryResult` (from step 5)
A qualifier has the following attributes:
{string} scope: The query scope
{string} name: A descriptive name for explanation purposes
{string} ancestor: The ancestor Element in DOM. Only available when is_meta=false. Defaults to `QualifierMixin.ANCESTOR.none`
{boolean} is_meta: Indicates if the qualifier scope is a metadata property
{boolean} need_read_file: Determines if the qualifier needs to read file content
{number} cost: The performance cost associated with the `query` function. 1: Read file stats; 2: Read file content; 3: Parse file content; Plus 0.5 when the user input is a regex
{function} preprocess: Convert certain specific, predefined, and special meaning vocabulary from the user input. Defaults to `QualifierMixin.PREPROCESS.noop`
{function} validate: Checks user input and obtain `validateError`. Defaults to `QualifierMixin.VALIDATE.isStringOrRegexp`
{function} cast: Converts user input for easier matching and obtain `castResult`. Defaults to `QualifierMixin.CAST.toStringOrRegexp`
{function} query: Retrieves data from source and obtain `queryResult`
{function} match_keyword: Matches `castResult` with `queryResult` when the user input is a keyword. Defaults to `QualifierMixin.MATCH.compare`
{function} match_phrase: Matches `castResult` with `queryResult` when the user input is a phrase. Behaves the same as `match_keyword` by default
{function} match_regexp: Matches `castResult` with `queryResult` when the user input is a regexp. Defaults to `QualifierMixin.MATCH.regexp`
|
buildQualifier
|
javascript
|
obgnail/typora_plugin
|
plugin/search_multi/searcher.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/search_multi/searcher.js
|
MIT
|
buildQualifier = (scope, is_meta, need_read_file, cost, anchor, process) => ({
scope, name: this.i18n.t(`scope.${scope}`), is_meta, need_read_file, cost, anchor, query: QUERY[scope], ...process,
})
|
The matching process consists of the following steps: (Steps 1-4 are executed once; steps 5-6 are executed repeatedly)
1. Parse: Parses the input to generate an Abstract Syntax Tree (AST)
2. Preprocess: Convert certain specific, predefined, and special meaning vocabulary (e.g. converting 'today' in 'mtime=today' to '2024-01-01')
3. Validate: Validates the AST for correctness
4. Cast: Converts operand within the AST nodes into a usable format (e.g. converting '2024-01-01' in 'mtime=2024-01-01' to a timestamp for easier matching). The result is `castResult`
5. Query: Retrieves file data, resulting in `queryResult`
6. Match: Matches `castResult` (from step 4) with `queryResult` (from step 5)
A qualifier has the following attributes:
{string} scope: The query scope
{string} name: A descriptive name for explanation purposes
{string} ancestor: The ancestor Element in DOM. Only available when is_meta=false. Defaults to `QualifierMixin.ANCESTOR.none`
{boolean} is_meta: Indicates if the qualifier scope is a metadata property
{boolean} need_read_file: Determines if the qualifier needs to read file content
{number} cost: The performance cost associated with the `query` function. 1: Read file stats; 2: Read file content; 3: Parse file content; Plus 0.5 when the user input is a regex
{function} preprocess: Convert certain specific, predefined, and special meaning vocabulary from the user input. Defaults to `QualifierMixin.PREPROCESS.noop`
{function} validate: Checks user input and obtain `validateError`. Defaults to `QualifierMixin.VALIDATE.isStringOrRegexp`
{function} cast: Converts user input for easier matching and obtain `castResult`. Defaults to `QualifierMixin.CAST.toStringOrRegexp`
{function} query: Retrieves data from source and obtain `queryResult`
{function} match_keyword: Matches `castResult` with `queryResult` when the user input is a keyword. Defaults to `QualifierMixin.MATCH.compare`
{function} match_phrase: Matches `castResult` with `queryResult` when the user input is a phrase. Behaves the same as `match_keyword` by default
{function} match_regexp: Matches `castResult` with `queryResult` when the user input is a regexp. Defaults to `QualifierMixin.MATCH.regexp`
|
buildQualifier
|
javascript
|
obgnail/typora_plugin
|
plugin/search_multi/searcher.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/search_multi/searcher.js
|
MIT
|
buildMarkdownQualifiers() {
// Prevent re-parsing of the same file in a SINGLE query
const cache = fn => {
let cached, result
return arg => {
if (arg !== cached) {
result = fn(arg)
cached = arg
}
return result
}
}
const PARSER = {
inline: cache(this.utils.parseMarkdownInline),
block: cache(this.utils.parseMarkdownBlock),
}
const FILTER = {
is: type => node => node.type === type,
wrappedBy: type => {
const openType = `${type}_open`
const closeType = `${type}_close`
let balance = 0
return node => {
if (node.type === openType) {
balance++
} else if (node.type === closeType) {
balance--
}
return balance > 0
}
},
wrappedByTag: (type, tag) => {
const openType = `${type}_open`
const closeType = `${type}_close`
let balance = 0
return node => {
if (node.type === openType && node.tag === tag) {
balance++
} else if (node.type === closeType && node.tag === tag) {
balance--
}
return balance > 0
}
},
wrappedByMulti: (...types) => {
let wrapped = false
const balances = new Uint8Array(types.length).fill(0)
const flags = new Map(
types.flatMap((type, idx) => [
[`${type}_open`, [idx, 1]],
[`${type}_close`, [idx, -1]],
])
)
return node => {
const hit = flags.get(node.type)
if (hit) {
const [idx, addend] = hit
balances[idx] += addend
balances.fill(0, idx + 1)
wrapped = balances.every(val => val > 0)
}
return wrapped
}
}
}
const TRANSFORMER = {
content: node => node.content,
info: node => node.info,
infoAndContent: node => `${node.info}\n${node.content}`,
attrAndContent: node => {
const attrs = node.attrs || []
const attrContent = attrs.map(l => l[l.length - 1]).join(" ")
return `${attrContent}${node.content}`
},
regexpContent: regex => {
return node => {
const content = node.content.trim()
const result = [...content.matchAll(regex)]
return result.map(([_, text]) => text).join(" ")
}
},
contentLine: node => node.content.split("\n"),
taskContent: (selectType = 0) => {
const regexp = /^\[(x|X| )\]\s+(.+)/
return node => {
const content = node.content.trim()
const hit = content.match(regexp)
if (!hit) {
return ""
}
const [_, selectText, taskText] = hit
// 0:both, 1:selected, -1:unselected
switch (selectType) {
case 0:
return taskText
case 1:
return (selectText === "x" || selectText === "X") ? taskText : ""
case -1:
return selectText === " " ? taskText : ""
default:
return ""
}
}
},
}
const preorder = (ast = [], filter) => {
const output = []
const recurse = ast => {
for (const node of ast) {
if (filter(node)) {
output.push(node)
}
const c = node.children
if (c && c.length) {
recurse(c)
}
}
}
recurse(ast)
return output
}
const buildQuery = (parser, filter, transformer) => {
return source => {
const ast = parser(source.content)
const nodes = preorder(ast, filter)
return nodes.flatMap(transformer).filter(Boolean)
}
}
const buildQualifier = (scope, anchor, parser, filter, transformer) => ({
scope,
name: this.i18n.t(`scope.${scope}`),
anchor,
is_meta: false,
need_read_file: true,
cost: 3,
preprocess: this.MIXIN.PREPROCESS.noop,
validate: this.MIXIN.VALIDATE.isStringOrRegexp,
cast: this.MIXIN.CAST.toStringOrRegexp,
match_keyword: this.MIXIN.MATCH.arrayCompare,
match_phrase: this.MIXIN.MATCH.arrayCompare,
match_regexp: this.MIXIN.MATCH.arrayRegexp,
query: buildQuery(parser, filter, transformer),
})
return [
buildQualifier("blockcode", "pre.md-fences", PARSER.block, FILTER.is("fence"), TRANSFORMER.infoAndContent),
buildQualifier("blockcodelang", ".ty-cm-lang-input", PARSER.block, FILTER.is("fence"), TRANSFORMER.info),
buildQualifier("blockcodebody", "pre.md-fences", PARSER.block, FILTER.is("fence"), TRANSFORMER.content),
buildQualifier("blockcodeline", "pre.md-fences", PARSER.block, FILTER.is("fence"), TRANSFORMER.contentLine),
buildQualifier("blockhtml", ".md-html-inline,.md-htmlblock", PARSER.block, FILTER.is("html_block"), TRANSFORMER.content),
buildQualifier("blockquote", '[mdtype="blockquote"]', PARSER.block, FILTER.wrappedBy("blockquote"), TRANSFORMER.content),
buildQualifier("table", '[mdtype="table"]', PARSER.block, FILTER.wrappedBy("table"), TRANSFORMER.content),
buildQualifier("thead", '[mdtype="table"] thead', PARSER.block, FILTER.wrappedBy("thead"), TRANSFORMER.content),
buildQualifier("tbody", '[mdtype="table"] tbody', PARSER.block, FILTER.wrappedBy("tbody"), TRANSFORMER.content),
buildQualifier("ol", 'ol[mdtype="list"]', PARSER.block, FILTER.wrappedBy("ordered_list"), TRANSFORMER.content),
buildQualifier("ul", 'ul[mdtype="list"]', PARSER.block, FILTER.wrappedBy("bullet_list"), TRANSFORMER.content),
buildQualifier("task", ".task-list-item", PARSER.block, FILTER.wrappedByMulti("bullet_list", "list_item", "paragraph"), TRANSFORMER.taskContent(0)),
buildQualifier("taskdone", ".task-list-item.task-list-done", PARSER.block, FILTER.wrappedByMulti("bullet_list", "list_item", "paragraph"), TRANSFORMER.taskContent(1)),
buildQualifier("tasktodo", ".task-list-item.task-list-not-done", PARSER.block, FILTER.wrappedByMulti("bullet_list", "list_item", "paragraph"), TRANSFORMER.taskContent(-1)),
buildQualifier("head", '[mdtype="heading"]', PARSER.block, FILTER.wrappedBy("heading"), TRANSFORMER.content),
buildQualifier("h1", 'h1[mdtype="heading"]', PARSER.block, FILTER.wrappedByTag("heading", "h1"), TRANSFORMER.content),
buildQualifier("h2", 'h2[mdtype="heading"]', PARSER.block, FILTER.wrappedByTag("heading", "h2"), TRANSFORMER.content),
buildQualifier("h3", 'h3[mdtype="heading"]', PARSER.block, FILTER.wrappedByTag("heading", "h3"), TRANSFORMER.content),
buildQualifier("h4", 'h4[mdtype="heading"]', PARSER.block, FILTER.wrappedByTag("heading", "h4"), TRANSFORMER.content),
buildQualifier("h5", 'h5[mdtype="heading"]', PARSER.block, FILTER.wrappedByTag("heading", "h5"), TRANSFORMER.content),
buildQualifier("h6", 'h6[mdtype="heading"]', PARSER.block, FILTER.wrappedByTag("heading", "h6"), TRANSFORMER.content),
buildQualifier("highlight", '[md-inline="highlight"]', PARSER.block, FILTER.is("text"), TRANSFORMER.regexpContent(/==(.+)==/g)),
buildQualifier("image", '[md-inline="image"]', PARSER.inline, FILTER.is("image"), TRANSFORMER.attrAndContent),
buildQualifier("code", '[md-inline="code"]', PARSER.inline, FILTER.is("code_inline"), TRANSFORMER.content),
buildQualifier("link", '[md-inline="link"]', PARSER.inline, FILTER.wrappedBy("link"), TRANSFORMER.attrAndContent),
buildQualifier("strong", '[md-inline="strong"]', PARSER.inline, FILTER.wrappedBy("strong"), TRANSFORMER.content),
buildQualifier("em", '[md-inline="em"]', PARSER.inline, FILTER.wrappedBy("em"), TRANSFORMER.content),
buildQualifier("del", '[md-inline="del"]', PARSER.inline, FILTER.wrappedBy("s"), TRANSFORMER.content),
]
}
|
The matching process consists of the following steps: (Steps 1-4 are executed once; steps 5-6 are executed repeatedly)
1. Parse: Parses the input to generate an Abstract Syntax Tree (AST)
2. Preprocess: Convert certain specific, predefined, and special meaning vocabulary (e.g. converting 'today' in 'mtime=today' to '2024-01-01')
3. Validate: Validates the AST for correctness
4. Cast: Converts operand within the AST nodes into a usable format (e.g. converting '2024-01-01' in 'mtime=2024-01-01' to a timestamp for easier matching). The result is `castResult`
5. Query: Retrieves file data, resulting in `queryResult`
6. Match: Matches `castResult` (from step 4) with `queryResult` (from step 5)
A qualifier has the following attributes:
{string} scope: The query scope
{string} name: A descriptive name for explanation purposes
{string} ancestor: The ancestor Element in DOM. Only available when is_meta=false. Defaults to `QualifierMixin.ANCESTOR.none`
{boolean} is_meta: Indicates if the qualifier scope is a metadata property
{boolean} need_read_file: Determines if the qualifier needs to read file content
{number} cost: The performance cost associated with the `query` function. 1: Read file stats; 2: Read file content; 3: Parse file content; Plus 0.5 when the user input is a regex
{function} preprocess: Convert certain specific, predefined, and special meaning vocabulary from the user input. Defaults to `QualifierMixin.PREPROCESS.noop`
{function} validate: Checks user input and obtain `validateError`. Defaults to `QualifierMixin.VALIDATE.isStringOrRegexp`
{function} cast: Converts user input for easier matching and obtain `castResult`. Defaults to `QualifierMixin.CAST.toStringOrRegexp`
{function} query: Retrieves data from source and obtain `queryResult`
{function} match_keyword: Matches `castResult` with `queryResult` when the user input is a keyword. Defaults to `QualifierMixin.MATCH.compare`
{function} match_phrase: Matches `castResult` with `queryResult` when the user input is a phrase. Behaves the same as `match_keyword` by default
{function} match_regexp: Matches `castResult` with `queryResult` when the user input is a regexp. Defaults to `QualifierMixin.MATCH.regexp`
|
buildMarkdownQualifiers
|
javascript
|
obgnail/typora_plugin
|
plugin/search_multi/searcher.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/search_multi/searcher.js
|
MIT
|
cache = fn => {
let cached, result
return arg => {
if (arg !== cached) {
result = fn(arg)
cached = arg
}
return result
}
}
|
The matching process consists of the following steps: (Steps 1-4 are executed once; steps 5-6 are executed repeatedly)
1. Parse: Parses the input to generate an Abstract Syntax Tree (AST)
2. Preprocess: Convert certain specific, predefined, and special meaning vocabulary (e.g. converting 'today' in 'mtime=today' to '2024-01-01')
3. Validate: Validates the AST for correctness
4. Cast: Converts operand within the AST nodes into a usable format (e.g. converting '2024-01-01' in 'mtime=2024-01-01' to a timestamp for easier matching). The result is `castResult`
5. Query: Retrieves file data, resulting in `queryResult`
6. Match: Matches `castResult` (from step 4) with `queryResult` (from step 5)
A qualifier has the following attributes:
{string} scope: The query scope
{string} name: A descriptive name for explanation purposes
{string} ancestor: The ancestor Element in DOM. Only available when is_meta=false. Defaults to `QualifierMixin.ANCESTOR.none`
{boolean} is_meta: Indicates if the qualifier scope is a metadata property
{boolean} need_read_file: Determines if the qualifier needs to read file content
{number} cost: The performance cost associated with the `query` function. 1: Read file stats; 2: Read file content; 3: Parse file content; Plus 0.5 when the user input is a regex
{function} preprocess: Convert certain specific, predefined, and special meaning vocabulary from the user input. Defaults to `QualifierMixin.PREPROCESS.noop`
{function} validate: Checks user input and obtain `validateError`. Defaults to `QualifierMixin.VALIDATE.isStringOrRegexp`
{function} cast: Converts user input for easier matching and obtain `castResult`. Defaults to `QualifierMixin.CAST.toStringOrRegexp`
{function} query: Retrieves data from source and obtain `queryResult`
{function} match_keyword: Matches `castResult` with `queryResult` when the user input is a keyword. Defaults to `QualifierMixin.MATCH.compare`
{function} match_phrase: Matches `castResult` with `queryResult` when the user input is a phrase. Behaves the same as `match_keyword` by default
{function} match_regexp: Matches `castResult` with `queryResult` when the user input is a regexp. Defaults to `QualifierMixin.MATCH.regexp`
|
cache
|
javascript
|
obgnail/typora_plugin
|
plugin/search_multi/searcher.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/search_multi/searcher.js
|
MIT
|
cache = fn => {
let cached, result
return arg => {
if (arg !== cached) {
result = fn(arg)
cached = arg
}
return result
}
}
|
The matching process consists of the following steps: (Steps 1-4 are executed once; steps 5-6 are executed repeatedly)
1. Parse: Parses the input to generate an Abstract Syntax Tree (AST)
2. Preprocess: Convert certain specific, predefined, and special meaning vocabulary (e.g. converting 'today' in 'mtime=today' to '2024-01-01')
3. Validate: Validates the AST for correctness
4. Cast: Converts operand within the AST nodes into a usable format (e.g. converting '2024-01-01' in 'mtime=2024-01-01' to a timestamp for easier matching). The result is `castResult`
5. Query: Retrieves file data, resulting in `queryResult`
6. Match: Matches `castResult` (from step 4) with `queryResult` (from step 5)
A qualifier has the following attributes:
{string} scope: The query scope
{string} name: A descriptive name for explanation purposes
{string} ancestor: The ancestor Element in DOM. Only available when is_meta=false. Defaults to `QualifierMixin.ANCESTOR.none`
{boolean} is_meta: Indicates if the qualifier scope is a metadata property
{boolean} need_read_file: Determines if the qualifier needs to read file content
{number} cost: The performance cost associated with the `query` function. 1: Read file stats; 2: Read file content; 3: Parse file content; Plus 0.5 when the user input is a regex
{function} preprocess: Convert certain specific, predefined, and special meaning vocabulary from the user input. Defaults to `QualifierMixin.PREPROCESS.noop`
{function} validate: Checks user input and obtain `validateError`. Defaults to `QualifierMixin.VALIDATE.isStringOrRegexp`
{function} cast: Converts user input for easier matching and obtain `castResult`. Defaults to `QualifierMixin.CAST.toStringOrRegexp`
{function} query: Retrieves data from source and obtain `queryResult`
{function} match_keyword: Matches `castResult` with `queryResult` when the user input is a keyword. Defaults to `QualifierMixin.MATCH.compare`
{function} match_phrase: Matches `castResult` with `queryResult` when the user input is a phrase. Behaves the same as `match_keyword` by default
{function} match_regexp: Matches `castResult` with `queryResult` when the user input is a regexp. Defaults to `QualifierMixin.MATCH.regexp`
|
cache
|
javascript
|
obgnail/typora_plugin
|
plugin/search_multi/searcher.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/search_multi/searcher.js
|
MIT
|
preorder = (ast = [], filter) => {
const output = []
const recurse = ast => {
for (const node of ast) {
if (filter(node)) {
output.push(node)
}
const c = node.children
if (c && c.length) {
recurse(c)
}
}
}
recurse(ast)
return output
}
|
The matching process consists of the following steps: (Steps 1-4 are executed once; steps 5-6 are executed repeatedly)
1. Parse: Parses the input to generate an Abstract Syntax Tree (AST)
2. Preprocess: Convert certain specific, predefined, and special meaning vocabulary (e.g. converting 'today' in 'mtime=today' to '2024-01-01')
3. Validate: Validates the AST for correctness
4. Cast: Converts operand within the AST nodes into a usable format (e.g. converting '2024-01-01' in 'mtime=2024-01-01' to a timestamp for easier matching). The result is `castResult`
5. Query: Retrieves file data, resulting in `queryResult`
6. Match: Matches `castResult` (from step 4) with `queryResult` (from step 5)
A qualifier has the following attributes:
{string} scope: The query scope
{string} name: A descriptive name for explanation purposes
{string} ancestor: The ancestor Element in DOM. Only available when is_meta=false. Defaults to `QualifierMixin.ANCESTOR.none`
{boolean} is_meta: Indicates if the qualifier scope is a metadata property
{boolean} need_read_file: Determines if the qualifier needs to read file content
{number} cost: The performance cost associated with the `query` function. 1: Read file stats; 2: Read file content; 3: Parse file content; Plus 0.5 when the user input is a regex
{function} preprocess: Convert certain specific, predefined, and special meaning vocabulary from the user input. Defaults to `QualifierMixin.PREPROCESS.noop`
{function} validate: Checks user input and obtain `validateError`. Defaults to `QualifierMixin.VALIDATE.isStringOrRegexp`
{function} cast: Converts user input for easier matching and obtain `castResult`. Defaults to `QualifierMixin.CAST.toStringOrRegexp`
{function} query: Retrieves data from source and obtain `queryResult`
{function} match_keyword: Matches `castResult` with `queryResult` when the user input is a keyword. Defaults to `QualifierMixin.MATCH.compare`
{function} match_phrase: Matches `castResult` with `queryResult` when the user input is a phrase. Behaves the same as `match_keyword` by default
{function} match_regexp: Matches `castResult` with `queryResult` when the user input is a regexp. Defaults to `QualifierMixin.MATCH.regexp`
|
preorder
|
javascript
|
obgnail/typora_plugin
|
plugin/search_multi/searcher.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/search_multi/searcher.js
|
MIT
|
preorder = (ast = [], filter) => {
const output = []
const recurse = ast => {
for (const node of ast) {
if (filter(node)) {
output.push(node)
}
const c = node.children
if (c && c.length) {
recurse(c)
}
}
}
recurse(ast)
return output
}
|
The matching process consists of the following steps: (Steps 1-4 are executed once; steps 5-6 are executed repeatedly)
1. Parse: Parses the input to generate an Abstract Syntax Tree (AST)
2. Preprocess: Convert certain specific, predefined, and special meaning vocabulary (e.g. converting 'today' in 'mtime=today' to '2024-01-01')
3. Validate: Validates the AST for correctness
4. Cast: Converts operand within the AST nodes into a usable format (e.g. converting '2024-01-01' in 'mtime=2024-01-01' to a timestamp for easier matching). The result is `castResult`
5. Query: Retrieves file data, resulting in `queryResult`
6. Match: Matches `castResult` (from step 4) with `queryResult` (from step 5)
A qualifier has the following attributes:
{string} scope: The query scope
{string} name: A descriptive name for explanation purposes
{string} ancestor: The ancestor Element in DOM. Only available when is_meta=false. Defaults to `QualifierMixin.ANCESTOR.none`
{boolean} is_meta: Indicates if the qualifier scope is a metadata property
{boolean} need_read_file: Determines if the qualifier needs to read file content
{number} cost: The performance cost associated with the `query` function. 1: Read file stats; 2: Read file content; 3: Parse file content; Plus 0.5 when the user input is a regex
{function} preprocess: Convert certain specific, predefined, and special meaning vocabulary from the user input. Defaults to `QualifierMixin.PREPROCESS.noop`
{function} validate: Checks user input and obtain `validateError`. Defaults to `QualifierMixin.VALIDATE.isStringOrRegexp`
{function} cast: Converts user input for easier matching and obtain `castResult`. Defaults to `QualifierMixin.CAST.toStringOrRegexp`
{function} query: Retrieves data from source and obtain `queryResult`
{function} match_keyword: Matches `castResult` with `queryResult` when the user input is a keyword. Defaults to `QualifierMixin.MATCH.compare`
{function} match_phrase: Matches `castResult` with `queryResult` when the user input is a phrase. Behaves the same as `match_keyword` by default
{function} match_regexp: Matches `castResult` with `queryResult` when the user input is a regexp. Defaults to `QualifierMixin.MATCH.regexp`
|
preorder
|
javascript
|
obgnail/typora_plugin
|
plugin/search_multi/searcher.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/search_multi/searcher.js
|
MIT
|
recurse = ast => {
for (const node of ast) {
if (filter(node)) {
output.push(node)
}
const c = node.children
if (c && c.length) {
recurse(c)
}
}
}
|
The matching process consists of the following steps: (Steps 1-4 are executed once; steps 5-6 are executed repeatedly)
1. Parse: Parses the input to generate an Abstract Syntax Tree (AST)
2. Preprocess: Convert certain specific, predefined, and special meaning vocabulary (e.g. converting 'today' in 'mtime=today' to '2024-01-01')
3. Validate: Validates the AST for correctness
4. Cast: Converts operand within the AST nodes into a usable format (e.g. converting '2024-01-01' in 'mtime=2024-01-01' to a timestamp for easier matching). The result is `castResult`
5. Query: Retrieves file data, resulting in `queryResult`
6. Match: Matches `castResult` (from step 4) with `queryResult` (from step 5)
A qualifier has the following attributes:
{string} scope: The query scope
{string} name: A descriptive name for explanation purposes
{string} ancestor: The ancestor Element in DOM. Only available when is_meta=false. Defaults to `QualifierMixin.ANCESTOR.none`
{boolean} is_meta: Indicates if the qualifier scope is a metadata property
{boolean} need_read_file: Determines if the qualifier needs to read file content
{number} cost: The performance cost associated with the `query` function. 1: Read file stats; 2: Read file content; 3: Parse file content; Plus 0.5 when the user input is a regex
{function} preprocess: Convert certain specific, predefined, and special meaning vocabulary from the user input. Defaults to `QualifierMixin.PREPROCESS.noop`
{function} validate: Checks user input and obtain `validateError`. Defaults to `QualifierMixin.VALIDATE.isStringOrRegexp`
{function} cast: Converts user input for easier matching and obtain `castResult`. Defaults to `QualifierMixin.CAST.toStringOrRegexp`
{function} query: Retrieves data from source and obtain `queryResult`
{function} match_keyword: Matches `castResult` with `queryResult` when the user input is a keyword. Defaults to `QualifierMixin.MATCH.compare`
{function} match_phrase: Matches `castResult` with `queryResult` when the user input is a phrase. Behaves the same as `match_keyword` by default
{function} match_regexp: Matches `castResult` with `queryResult` when the user input is a regexp. Defaults to `QualifierMixin.MATCH.regexp`
|
recurse
|
javascript
|
obgnail/typora_plugin
|
plugin/search_multi/searcher.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/search_multi/searcher.js
|
MIT
|
recurse = ast => {
for (const node of ast) {
if (filter(node)) {
output.push(node)
}
const c = node.children
if (c && c.length) {
recurse(c)
}
}
}
|
The matching process consists of the following steps: (Steps 1-4 are executed once; steps 5-6 are executed repeatedly)
1. Parse: Parses the input to generate an Abstract Syntax Tree (AST)
2. Preprocess: Convert certain specific, predefined, and special meaning vocabulary (e.g. converting 'today' in 'mtime=today' to '2024-01-01')
3. Validate: Validates the AST for correctness
4. Cast: Converts operand within the AST nodes into a usable format (e.g. converting '2024-01-01' in 'mtime=2024-01-01' to a timestamp for easier matching). The result is `castResult`
5. Query: Retrieves file data, resulting in `queryResult`
6. Match: Matches `castResult` (from step 4) with `queryResult` (from step 5)
A qualifier has the following attributes:
{string} scope: The query scope
{string} name: A descriptive name for explanation purposes
{string} ancestor: The ancestor Element in DOM. Only available when is_meta=false. Defaults to `QualifierMixin.ANCESTOR.none`
{boolean} is_meta: Indicates if the qualifier scope is a metadata property
{boolean} need_read_file: Determines if the qualifier needs to read file content
{number} cost: The performance cost associated with the `query` function. 1: Read file stats; 2: Read file content; 3: Parse file content; Plus 0.5 when the user input is a regex
{function} preprocess: Convert certain specific, predefined, and special meaning vocabulary from the user input. Defaults to `QualifierMixin.PREPROCESS.noop`
{function} validate: Checks user input and obtain `validateError`. Defaults to `QualifierMixin.VALIDATE.isStringOrRegexp`
{function} cast: Converts user input for easier matching and obtain `castResult`. Defaults to `QualifierMixin.CAST.toStringOrRegexp`
{function} query: Retrieves data from source and obtain `queryResult`
{function} match_keyword: Matches `castResult` with `queryResult` when the user input is a keyword. Defaults to `QualifierMixin.MATCH.compare`
{function} match_phrase: Matches `castResult` with `queryResult` when the user input is a phrase. Behaves the same as `match_keyword` by default
{function} match_regexp: Matches `castResult` with `queryResult` when the user input is a regexp. Defaults to `QualifierMixin.MATCH.regexp`
|
recurse
|
javascript
|
obgnail/typora_plugin
|
plugin/search_multi/searcher.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/search_multi/searcher.js
|
MIT
|
buildQuery = (parser, filter, transformer) => {
return source => {
const ast = parser(source.content)
const nodes = preorder(ast, filter)
return nodes.flatMap(transformer).filter(Boolean)
}
}
|
The matching process consists of the following steps: (Steps 1-4 are executed once; steps 5-6 are executed repeatedly)
1. Parse: Parses the input to generate an Abstract Syntax Tree (AST)
2. Preprocess: Convert certain specific, predefined, and special meaning vocabulary (e.g. converting 'today' in 'mtime=today' to '2024-01-01')
3. Validate: Validates the AST for correctness
4. Cast: Converts operand within the AST nodes into a usable format (e.g. converting '2024-01-01' in 'mtime=2024-01-01' to a timestamp for easier matching). The result is `castResult`
5. Query: Retrieves file data, resulting in `queryResult`
6. Match: Matches `castResult` (from step 4) with `queryResult` (from step 5)
A qualifier has the following attributes:
{string} scope: The query scope
{string} name: A descriptive name for explanation purposes
{string} ancestor: The ancestor Element in DOM. Only available when is_meta=false. Defaults to `QualifierMixin.ANCESTOR.none`
{boolean} is_meta: Indicates if the qualifier scope is a metadata property
{boolean} need_read_file: Determines if the qualifier needs to read file content
{number} cost: The performance cost associated with the `query` function. 1: Read file stats; 2: Read file content; 3: Parse file content; Plus 0.5 when the user input is a regex
{function} preprocess: Convert certain specific, predefined, and special meaning vocabulary from the user input. Defaults to `QualifierMixin.PREPROCESS.noop`
{function} validate: Checks user input and obtain `validateError`. Defaults to `QualifierMixin.VALIDATE.isStringOrRegexp`
{function} cast: Converts user input for easier matching and obtain `castResult`. Defaults to `QualifierMixin.CAST.toStringOrRegexp`
{function} query: Retrieves data from source and obtain `queryResult`
{function} match_keyword: Matches `castResult` with `queryResult` when the user input is a keyword. Defaults to `QualifierMixin.MATCH.compare`
{function} match_phrase: Matches `castResult` with `queryResult` when the user input is a phrase. Behaves the same as `match_keyword` by default
{function} match_regexp: Matches `castResult` with `queryResult` when the user input is a regexp. Defaults to `QualifierMixin.MATCH.regexp`
|
buildQuery
|
javascript
|
obgnail/typora_plugin
|
plugin/search_multi/searcher.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/search_multi/searcher.js
|
MIT
|
buildQuery = (parser, filter, transformer) => {
return source => {
const ast = parser(source.content)
const nodes = preorder(ast, filter)
return nodes.flatMap(transformer).filter(Boolean)
}
}
|
The matching process consists of the following steps: (Steps 1-4 are executed once; steps 5-6 are executed repeatedly)
1. Parse: Parses the input to generate an Abstract Syntax Tree (AST)
2. Preprocess: Convert certain specific, predefined, and special meaning vocabulary (e.g. converting 'today' in 'mtime=today' to '2024-01-01')
3. Validate: Validates the AST for correctness
4. Cast: Converts operand within the AST nodes into a usable format (e.g. converting '2024-01-01' in 'mtime=2024-01-01' to a timestamp for easier matching). The result is `castResult`
5. Query: Retrieves file data, resulting in `queryResult`
6. Match: Matches `castResult` (from step 4) with `queryResult` (from step 5)
A qualifier has the following attributes:
{string} scope: The query scope
{string} name: A descriptive name for explanation purposes
{string} ancestor: The ancestor Element in DOM. Only available when is_meta=false. Defaults to `QualifierMixin.ANCESTOR.none`
{boolean} is_meta: Indicates if the qualifier scope is a metadata property
{boolean} need_read_file: Determines if the qualifier needs to read file content
{number} cost: The performance cost associated with the `query` function. 1: Read file stats; 2: Read file content; 3: Parse file content; Plus 0.5 when the user input is a regex
{function} preprocess: Convert certain specific, predefined, and special meaning vocabulary from the user input. Defaults to `QualifierMixin.PREPROCESS.noop`
{function} validate: Checks user input and obtain `validateError`. Defaults to `QualifierMixin.VALIDATE.isStringOrRegexp`
{function} cast: Converts user input for easier matching and obtain `castResult`. Defaults to `QualifierMixin.CAST.toStringOrRegexp`
{function} query: Retrieves data from source and obtain `queryResult`
{function} match_keyword: Matches `castResult` with `queryResult` when the user input is a keyword. Defaults to `QualifierMixin.MATCH.compare`
{function} match_phrase: Matches `castResult` with `queryResult` when the user input is a phrase. Behaves the same as `match_keyword` by default
{function} match_regexp: Matches `castResult` with `queryResult` when the user input is a regexp. Defaults to `QualifierMixin.MATCH.regexp`
|
buildQuery
|
javascript
|
obgnail/typora_plugin
|
plugin/search_multi/searcher.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/search_multi/searcher.js
|
MIT
|
buildQualifier = (scope, anchor, parser, filter, transformer) => ({
scope,
name: this.i18n.t(`scope.${scope}`),
anchor,
is_meta: false,
need_read_file: true,
cost: 3,
preprocess: this.MIXIN.PREPROCESS.noop,
validate: this.MIXIN.VALIDATE.isStringOrRegexp,
cast: this.MIXIN.CAST.toStringOrRegexp,
match_keyword: this.MIXIN.MATCH.arrayCompare,
match_phrase: this.MIXIN.MATCH.arrayCompare,
match_regexp: this.MIXIN.MATCH.arrayRegexp,
query: buildQuery(parser, filter, transformer),
})
|
The matching process consists of the following steps: (Steps 1-4 are executed once; steps 5-6 are executed repeatedly)
1. Parse: Parses the input to generate an Abstract Syntax Tree (AST)
2. Preprocess: Convert certain specific, predefined, and special meaning vocabulary (e.g. converting 'today' in 'mtime=today' to '2024-01-01')
3. Validate: Validates the AST for correctness
4. Cast: Converts operand within the AST nodes into a usable format (e.g. converting '2024-01-01' in 'mtime=2024-01-01' to a timestamp for easier matching). The result is `castResult`
5. Query: Retrieves file data, resulting in `queryResult`
6. Match: Matches `castResult` (from step 4) with `queryResult` (from step 5)
A qualifier has the following attributes:
{string} scope: The query scope
{string} name: A descriptive name for explanation purposes
{string} ancestor: The ancestor Element in DOM. Only available when is_meta=false. Defaults to `QualifierMixin.ANCESTOR.none`
{boolean} is_meta: Indicates if the qualifier scope is a metadata property
{boolean} need_read_file: Determines if the qualifier needs to read file content
{number} cost: The performance cost associated with the `query` function. 1: Read file stats; 2: Read file content; 3: Parse file content; Plus 0.5 when the user input is a regex
{function} preprocess: Convert certain specific, predefined, and special meaning vocabulary from the user input. Defaults to `QualifierMixin.PREPROCESS.noop`
{function} validate: Checks user input and obtain `validateError`. Defaults to `QualifierMixin.VALIDATE.isStringOrRegexp`
{function} cast: Converts user input for easier matching and obtain `castResult`. Defaults to `QualifierMixin.CAST.toStringOrRegexp`
{function} query: Retrieves data from source and obtain `queryResult`
{function} match_keyword: Matches `castResult` with `queryResult` when the user input is a keyword. Defaults to `QualifierMixin.MATCH.compare`
{function} match_phrase: Matches `castResult` with `queryResult` when the user input is a phrase. Behaves the same as `match_keyword` by default
{function} match_regexp: Matches `castResult` with `queryResult` when the user input is a regexp. Defaults to `QualifierMixin.MATCH.regexp`
|
buildQualifier
|
javascript
|
obgnail/typora_plugin
|
plugin/search_multi/searcher.js
|
https://github.com/obgnail/typora_plugin/blob/master/plugin/search_multi/searcher.js
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.