diff --git a/api/electron.mjs b/api/electron.mjs index 9fa95df..7251c93 100644 --- a/api/electron.mjs +++ b/api/electron.mjs @@ -48,7 +48,8 @@ export const webFrame = globalThis.__enhancerElectronApi?.webFrame; * @runtime client * @runtime menu */ -export const sendMessage = globalThis.__enhancerElectronApi?.ipcRenderer?.sendMessage; +export const sendMessage = (channel, data) => + globalThis.__enhancerElectronApi.ipcRenderer.sendMessage(channel, data); /** * send a message to the webview's parent renderer process @@ -61,14 +62,14 @@ export const sendMessage = globalThis.__enhancerElectronApi?.ipcRenderer?.sendMe * @runtime client * @runtime menu */ -export const sendMessageToHost = - globalThis.__enhancerElectronApi?.ipcRenderer?.sendMessageToHost; +export const sendMessageToHost = (channel, data) => + globalThis.__enhancerElectronApi.ipcRenderer.sendMessageToHost(channel, data); /** * receive a message from either the main process or * the webview's parent renderer process * @param {string} channel - the message identifier to listen for - * @param {function} listener - the message handler, passed the args (event, data) + * @param {function} callback - the message handler, passed the args (event, data) * * @env win32 * @env linux @@ -76,4 +77,5 @@ export const sendMessageToHost = * @runtime client * @runtime menu */ -export const onMessage = globalThis.__enhancerElectronApi?.ipcRenderer?.onMessage; +export const onMessage = (channel, callback) => + globalThis.__enhancerElectronApi.ipcRenderer.onMessage(channel, callback); diff --git a/api/fs.mjs b/api/fs.mjs index 659517f..a6e40ab 100644 --- a/api/fs.mjs +++ b/api/fs.mjs @@ -46,3 +46,14 @@ export const getText = fs.getText; * @returns {boolean} whether or not the file exists */ export const isFile = fs.isFile; + +/** + * get an absolute path to files within notion + * @param {string} path - relative to the root notion/resources/app/ e.g. renderer/search.js + * + * @env win32 + * @env linux + * @env darwin + * @runtime electron + */ +export const notionPath = fs.notionPath; diff --git a/api/index.cjs b/api/index.cjs index f3a32ce..f6d8f8c 100644 --- a/api/index.cjs +++ b/api/index.cjs @@ -1,1042 +1,21 @@ -var __defProp = Object.defineProperty; -var __markAsModule = (target) => __defProp(target, "__esModule", { value: true }); -var __export = (target, all) => { - __markAsModule(target); - for (var name3 in all) - __defProp(target, name3, { get: all[name3], enumerable: true }); -}; - -// insert/api/index.mjs -__export(exports, { - components: () => components_exports, - electron: () => electron_exports, - env: () => env_exports, - fmt: () => fmt_exports, - fs: () => fs_exports, - registry: () => registry_exports, - storage: () => storage_exports, - web: () => web_exports -}); - -// insert/api/env.mjs -var env_exports = {}; -__export(env_exports, { - focusMenu: () => focusMenu2, - focusNotion: () => focusNotion2, - name: () => name2, - notionRequire: () => notionRequire2, - reload: () => reload2, - version: () => version2 -}); - -// insert/env/env.mjs -"use strict"; -var name = globalThis.__enhancerElectronApi.platform; -var version = globalThis.__enhancerElectronApi.version; -var focusMenu = globalThis.__enhancerElectronApi.focusMenu; -var focusNotion = globalThis.__enhancerElectronApi.focusNotion; -var reload = globalThis.__enhancerElectronApi.reload; -var notionRequire = globalThis.__enhancerElectronApi.notionRequire; - -// insert/api/env.mjs -"use strict"; -var name2 = name; -var version2 = version; -var focusMenu2 = focusMenu; -var focusNotion2 = focusNotion; -var reload2 = reload; -var notionRequire2 = notionRequire; - -// insert/api/fs.mjs -var fs_exports = {}; -__export(fs_exports, { - getJSON: () => getJSON2, - getText: () => getText2, - isFile: () => isFile2, - localPath: () => localPath2 -}); - -// insert/env/fs.mjs -"use strict"; -var localPath = (path) => `notion://www.notion.so/__notion-enhancer/${path}`; -var getJSON = (path, opts = {}) => { - if (path.startsWith("http")) - return fetch(path, opts).then((res) => res.json()); - try { - return globalThis.__enhancerElectronApi.nodeRequire(`notion-enhancer/${path}`); - } catch (err) { - return fetch(localPath(path), opts).then((res) => res.json()); - } -}; -var getText = (path, opts = {}) => { - if (path.startsWith("http")) - return fetch(path, opts).then((res) => res.text()); - try { - const fs2 = globalThis.__enhancerElectronApi.nodeRequire("fs"), { resolve: resolvePath } = globalThis.__enhancerElectronApi.nodeRequire("path"); - return fs2.readFileSync(resolvePath(`${__dirname}/../../${path}`)); - } catch (err) { - return fetch(localPath(path), opts).then((res) => res.text()); - } -}; -var isFile = async (path) => { - try { - const fs2 = globalThis.__enhancerElectronApi.nodeRequire("fs"), { resolve: resolvePath } = globalThis.__enhancerElectronApi.nodeRequire("path"); - if (path.startsWith("http")) { - await fetch(path); - } else { - try { - fs2.existsSync(resolvePath(`${__dirname}/../../${path}`)); - } catch (err) { - await fetch(localPath(path)); - } - } - return true; - } catch { - return false; - } -}; - -// insert/api/fs.mjs -"use strict"; -var localPath2 = localPath; -var getJSON2 = getJSON; -var getText2 = getText; -var isFile2 = isFile; - -// insert/api/storage.mjs -var storage_exports = {}; -__export(storage_exports, { - addChangeListener: () => addChangeListener2, - db: () => db2, - get: () => get2, - removeChangeListener: () => removeChangeListener2, - set: () => set2 -}); - -// insert/env/storage.mjs -"use strict"; -var get = (path, fallback = void 0) => { - return globalThis.__enhancerElectronApi.db.get(path, fallback); -}; -var set = (path, value) => { - return globalThis.__enhancerElectronApi.db.set(path, value); -}; -var db = (namespace, getFunc = get, setFunc = set) => { - if (typeof namespace === "string") - namespace = [namespace]; - return { - get: (path = [], fallback = void 0) => getFunc([...namespace, ...path], fallback), - set: (path, value) => setFunc([...namespace, ...path], value) - }; -}; -var addChangeListener = (callback) => { - return globalThis.__enhancerElectronApi.db.addChangeListener(callback); -}; -var removeChangeListener = (callback) => { - return globalThis.__enhancerElectronApi.db.removeChangeListener(callback); -}; - -// insert/api/storage.mjs -"use strict"; -var get2 = get; -var set2 = set; -var db2 = db; -var addChangeListener2 = addChangeListener; -var removeChangeListener2 = removeChangeListener; - -// insert/api/electron.mjs -var electron_exports = {}; -__export(electron_exports, { - browser: () => browser, - onMessage: () => onMessage, - sendMessage: () => sendMessage, - sendMessageToHost: () => sendMessageToHost, - webFrame: () => webFrame -}); -"use strict"; -var browser = globalThis.__enhancerElectronApi?.browser; -var webFrame = globalThis.__enhancerElectronApi?.webFrame; -var sendMessage = globalThis.__enhancerElectronApi?.ipcRenderer?.sendMessage; -var sendMessageToHost = globalThis.__enhancerElectronApi?.ipcRenderer?.sendMessageToHost; -var onMessage = globalThis.__enhancerElectronApi?.ipcRenderer?.onMessage; - -// insert/api/fmt.mjs -var fmt_exports = {}; -__export(fmt_exports, { - is: () => is, - rgbContrast: () => rgbContrast, - rgbLogShade: () => rgbLogShade, - slugger: () => slugger, - uuidv4: () => uuidv4 -}); -"use strict"; -var slugger = (heading, slugs = new Set()) => { - heading = heading.replace(/\s/g, "-").replace(/[^A-Za-z0-9-_]/g, "").toLowerCase(); - let i = 0, slug = heading; - while (slugs.has(slug)) { - i++; - slug = `${heading}-${i}`; - } - return slug; -}; -var uuidv4 = () => { - if (crypto?.randomUUID) - return crypto.randomUUID(); - return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, (c) => (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)); -}; -var rgbLogShade = (p, c) => { - var i = parseInt, r = Math.round, [a, b, c, d] = c.split(","), P = p < 0, t = P ? 0 : p * 255 ** 2, P = P ? 1 + p : 1 - p; - return "rgb" + (d ? "a(" : "(") + r((P * i(a[3] == "a" ? a.slice(5) : a.slice(4)) ** 2 + t) ** 0.5) + "," + r((P * i(b) ** 2 + t) ** 0.5) + "," + r((P * i(c) ** 2 + t) ** 0.5) + (d ? "," + d : ")"); -}; -var rgbContrast = (r, g, b) => { - return Math.sqrt(0.299 * (r * r) + 0.587 * (g * g) + 0.114 * (b * b)) > 165.75 ? "rgb(0,0,0)" : "rgb(255,255,255)"; -}; -var patterns = { - alphanumeric: /^[\w\.-]+$/, - uuid: /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i, - semver: /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/i, - email: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/i, - url: /^[(http(s)?):\/\/(www\.)?a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,64}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)$/i, - color: /^(?:#|0x)(?:[a-f0-9]{3}|[a-f0-9]{6})\b|(?:rgb|hsl)a?\([^\)]*\)$/i -}; -function test(str, pattern) { - const match = str.match(pattern); - return !!(match && match.length); -} -var is = async (value, type, { extension = "" } = {}) => { - extension = !value || !value.endsWith || value.endsWith(extension); - if (Array.isArray(type)) { - return type.includes(value); - } - switch (type) { - case "array": - return Array.isArray(value); - case "object": - return value && typeof value === "object" && !Array.isArray(value); - case "undefined": - case "boolean": - case "number": - return typeof value === type && extension; - case "string": - return typeof value === type && extension; - case "alphanumeric": - case "uuid": - case "semver": - case "email": - case "url": - case "color": - return typeof value === "string" && test(value, patterns[type]) && extension; - case "file": - return typeof value === "string" && value && await fs_exports.isFile(value) && extension; - } - return false; -}; - -// insert/api/registry.mjs -var registry_exports = {}; -__export(registry_exports, { - core: () => core, - db: () => db3, - enabled: () => enabled, - errors: () => errors, - get: () => get3, - list: () => list, - optionDefault: () => optionDefault, - optionTypes: () => optionTypes, - profileDB: () => profileDB, - profileName: () => profileName, - supportedEnvs: () => supportedEnvs -}); - -// insert/api/registry-validation.mjs -"use strict"; -var check = async (mod, key, value, types, { - extension = "", - error = `invalid ${key} (${extension ? `${extension} ` : ""}${types}): ${JSON.stringify(value)}`, - optional = false -} = {}) => { - let test2; - for (const type of Array.isArray(types) ? [types] : types.split("|")) { - if (type === "file") { - test2 = value && !value.startsWith("http") ? await fmt_exports.is(`repo/${mod._dir}/${value}`, type, { extension }) : false; - } else - test2 = await fmt_exports.is(value, type, { extension }); - if (test2) - break; - } - if (!test2) { - if (optional && await fmt_exports.is(value, "undefined")) - return true; - if (error) - mod._err(error); - return false; - } - return true; -}; -var validateEnvironments = async (mod) => { - mod.environments = mod.environments ?? registry_exports.supportedEnvs; - const isArray = await check(mod, "environments", mod.environments, "array"); - if (!isArray) - return false; - return mod.environments.map((tag) => check(mod, "environments.env", tag, registry_exports.supportedEnvs)); -}; -var validateTags = async (mod) => { - const isArray = await check(mod, "tags", mod.tags, "array"); - if (!isArray) - return false; - const categoryTags = ["core", "extension", "theme", "integration"], containsCategory = mod.tags.filter((tag) => categoryTags.includes(tag)).length; - if (!containsCategory) { - mod._err(`invalid tags (must contain at least one of 'core', 'extension', 'theme' or 'integration'): - ${JSON.stringify(mod.tags)}`); - return false; - } - const isTheme = mod.tags.includes("theme"), hasThemeMode = mod.tags.includes("light") || mod.tags.includes("dark"), isBothThemeModes = mod.tags.includes("light") && mod.tags.includes("dark"); - if (isTheme && (!hasThemeMode || isBothThemeModes)) { - mod._err(`invalid tags (themes must be either 'light' or 'dark', not neither or both): - ${JSON.stringify(mod.tags)}`); - return false; - } - return mod.tags.map((tag) => check(mod, "tags.tag", tag, "string")); -}; -var validateAuthors = async (mod) => { - const isArray = await check(mod, "authors", mod.authors, "array"); - if (!isArray) - return false; - return mod.authors.map((author) => [ - check(mod, "authors.author.name", author.name, "string"), - check(mod, "authors.author.email", author.email, "email", { optional: true }), - check(mod, "authors.author.homepage", author.homepage, "url"), - check(mod, "authors.author.avatar", author.avatar, "url") - ]); -}; -var validateCSS = async (mod) => { - const isArray = await check(mod, "css", mod.css, "object"); - if (!isArray) - return false; - const tests = []; - for (let dest of ["frame", "client", "menu"]) { - if (!mod.css[dest]) - continue; - let test2 = await check(mod, `css.${dest}`, mod.css[dest], "array"); - if (test2) { - test2 = mod.css[dest].map((file) => check(mod, `css.${dest}.file`, file, "file", { extension: ".css" })); - } - tests.push(test2); - } - return tests; -}; -var validateJS = async (mod) => { - const isArray = await check(mod, "js", mod.js, "object"); - if (!isArray) - return false; - const tests = []; - for (let dest of ["frame", "client", "menu"]) { - if (!mod.js[dest]) - continue; - let test2 = await check(mod, `js.${dest}`, mod.js[dest], "array"); - if (test2) { - test2 = mod.js[dest].map((file) => check(mod, `js.${dest}.file`, file, "file", { extension: ".mjs" })); - } - tests.push(test2); - } - if (mod.js.electron) { - const isArray2 = await check(mod, "js.electron", mod.js.electron, "array"); - if (isArray2) { - for (const file of mod.js.electron) { - const isObject = await check(mod, "js.electron.file", file, "object"); - if (!isObject) { - tests.push(false); - continue; - } - tests.push([ - check(mod, "js.electron.file.source", file.source, "file", { - extension: ".cjs" - }), - check(mod, "js.electron.file.target", file.target, "string", { - extension: ".js" - }) - ]); - } - } else - tests.push(false); - } - return tests; -}; -var validateOptions = async (mod) => { - const isArray = await check(mod, "options", mod.options, "array"); - if (!isArray) - return false; - const tests = []; - for (const option of mod.options) { - const key = "options.option", optTypeValid = await check(mod, `${key}.type`, option.type, registry_exports.optionTypes); - if (!optTypeValid) { - tests.push(false); - continue; - } - option.environments = option.environments ?? registry_exports.supportedEnvs; - tests.push([ - check(mod, `${key}.key`, option.key, "alphanumeric"), - check(mod, `${key}.label`, option.label, "string"), - check(mod, `${key}.tooltip`, option.tooltip, "string", { - optional: true - }), - check(mod, `${key}.environments`, option.environments, "array").then((isArray2) => { - if (!isArray2) - return false; - return option.environments.map((environment) => check(mod, `${key}.environments.env`, environment, registry_exports.supportedEnvs)); - }) - ]); - switch (option.type) { - case "toggle": - tests.push(check(mod, `${key}.value`, option.value, "boolean")); - break; - case "select": { - let test2 = await check(mod, `${key}.values`, option.values, "array"); - if (test2) { - test2 = option.values.map((value) => check(mod, `${key}.values.value`, value, "string")); - } - tests.push(test2); - break; - } - case "text": - case "hotkey": - tests.push(check(mod, `${key}.value`, option.value, "string")); - break; - case "number": - case "color": - tests.push(check(mod, `${key}.value`, option.value, option.type)); - break; - case "file": { - let test2 = await check(mod, `${key}.extensions`, option.extensions, "array"); - if (test2) { - test2 = option.extensions.map((ext) => check(mod, `${key}.extensions.extension`, ext, "string")); - } - tests.push(test2); - break; - } - } - } - return tests; -}; -async function validate(mod) { - let conditions = [ - check(mod, "name", mod.name, "string"), - check(mod, "id", mod.id, "uuid"), - check(mod, "version", mod.version, "semver"), - validateEnvironments(mod), - check(mod, "description", mod.description, "string"), - check(mod, "preview", mod.preview, "file|url", { optional: true }), - validateTags(mod), - validateAuthors(mod), - validateCSS(mod), - validateJS(mod), - validateOptions(mod) - ]; - do { - conditions = await Promise.all(conditions.flat(Infinity)); - } while (conditions.some((condition) => Array.isArray(condition))); - return conditions.every((passed) => passed); -} - -// insert/api/registry.mjs -"use strict"; -var core = [ - "a6621988-551d-495a-97d8-3c568bca2e9e", - "0f0bf8b6-eae6-4273-b307-8fc43f2ee082", - "36a2ffc9-27ff-480e-84a7-c7700a7d232d" -]; -var supportedEnvs = ["linux", "win32", "darwin", "extension"]; -var optionTypes = ["toggle", "select", "text", "number", "color", "file", "hotkey"]; -var profileName = async () => storage_exports.get(["currentprofile"], "default"); -var profileDB = async () => storage_exports.db(["profiles", await profileName()]); -var _list; -var _errors = []; -var list = async (filter = (mod) => true) => { - if (!_list) { - _list = new Promise(async (res, rej) => { - const passed = []; - for (const dir of await fs_exports.getJSON("repo/registry.json")) { - try { - const mod = { - ...await fs_exports.getJSON(`repo/${dir}/mod.json`), - _dir: dir, - _err: (message) => _errors.push({ source: dir, message }) - }; - if (await validate(mod)) - passed.push(mod); - } catch { - _errors.push({ source: dir, message: "invalid mod.json" }); - } - } - res(passed); - }); - } - const filtered = []; - for (const mod of await _list) - if (await filter(mod)) - filtered.push(mod); - return filtered; -}; -var errors = async () => { - await list(); - return _errors; -}; -var get3 = async (id) => { - return (await list((mod) => mod.id === id))[0]; -}; -var enabled = async (id) => { - const mod = await get3(id); - if (!mod.environments.includes(env_exports.name)) - return false; - if (core.includes(id)) - return true; - return (await profileDB()).get(["_mods", id], false); -}; -var optionDefault = async (id, key) => { - const mod = await get3(id), opt = mod.options.find((opt2) => opt2.key === key); - if (!opt) - return void 0; - switch (opt.type) { - case "toggle": - case "text": - case "number": - case "color": - case "hotkey": - return opt.value; - case "select": - return opt.values[0]; - case "file": - return void 0; - } -}; -var db3 = async (id) => { - const db5 = await profileDB(); - return storage_exports.db([id], async (path, fallback = void 0) => { - if (typeof path === "string") - path = [path]; - if (path.length === 2) { - fallback = await optionDefault(id, path[1]) ?? fallback; - } - return db5.get(path, fallback); - }, db5.set); -}; - -// insert/api/web.mjs -var web_exports = {}; -__export(web_exports, { - addDocumentObserver: () => addDocumentObserver, - addHotkeyListener: () => addHotkeyListener, - copyToClipboard: () => copyToClipboard, - empty: () => empty, - escape: () => escape, - html: () => html, - loadStylesheet: () => loadStylesheet, - queryParams: () => queryParams, - raw: () => raw, - readFromClipboard: () => readFromClipboard, - removeDocumentObserver: () => removeDocumentObserver, - removeHotkeyListener: () => removeHotkeyListener, - render: () => render, - whenReady: () => whenReady -}); -"use strict"; -var _hotkeyListenersActivated = false; -var _hotkeyEventListeners = []; -var _documentObserver; -var _documentObserverListeners = []; -var _documentObserverEvents = []; -var whenReady = (selectors = []) => { - return new Promise((res, rej) => { - function onLoad() { - let isReadyInt; - isReadyInt = setInterval(isReadyTest, 100); - function isReadyTest() { - if (selectors.every((selector) => document.querySelector(selector))) { - clearInterval(isReadyInt); - res(true); - } - } - isReadyTest(); - } - if (document.readyState !== "complete") { - document.addEventListener("readystatechange", (event) => { - if (document.readyState === "complete") - onLoad(); - }); - } else - onLoad(); - }); -}; -var queryParams = () => new URLSearchParams(window.location.search); -var escape = (str) => str.replace(/&/g, "&").replace(//g, ">").replace(/'/g, "'").replace(/"/g, """).replace(/\\/g, "\"); -var raw = (str, ...templates) => { - const html2 = str.map((chunk) => chunk + (["string", "number"].includes(typeof templates[0]) ? templates.shift() : escape(JSON.stringify(templates.shift(), null, 2) ?? ""))).join(""); - return html2.includes("
line.trim()).filter((line) => line.length).join(" "); -}; -var html = (str, ...templates) => { - const $fragment = document.createRange().createContextualFragment(raw(str, ...templates)); - return $fragment.children.length === 1 ? $fragment.children[0] : $fragment.children; -}; -var render = ($container, ...$elems) => { - $elems = $elems.map(($elem) => $elem instanceof HTMLCollection ? [...$elem] : $elem).flat(Infinity).filter(($elem) => $elem); - $container.append(...$elems); - return $container; -}; -var empty = ($container) => { - while ($container.firstChild && $container.removeChild($container.firstChild)) - ; - return $container; -}; -var loadStylesheet = (path) => { - const $stylesheet4 = html`ce(e,"__esModule",{value:!0});var g=(e,t)=>{Ge(e);for(var n in t)ce(e,n,{get:t[n],enumerable:!0})};g(exports,{components:()=>N,electron:()=>I,env:()=>A,fmt:()=>h,fs:()=>p,notion:()=>K,registry:()=>y,storage:()=>$,web:()=>o});var A={};g(A,{focusMenu:()=>De,focusNotion:()=>et,name:()=>Qe,notionRequire:()=>nt,reload:()=>tt,version:()=>Ye});"use strict";var le=globalThis.__enhancerElectronApi.platform,de=globalThis.__enhancerElectronApi.version,pe=globalThis.__enhancerElectronApi.focusMenu,ue=globalThis.__enhancerElectronApi.focusNotion,he=globalThis.__enhancerElectronApi.reload,fe=globalThis.__enhancerElectronApi.notionRequire;"use strict";var Qe=le,Ye=de,De=pe,et=ue,tt=he,nt=fe;var p={};g(p,{getJSON:()=>st,getText:()=>ot,isFile:()=>it,localPath:()=>rt,notionPath:()=>at});"use strict";var E=e=>`notion://www.notion.so/__notion-enhancer/${e}`,me=(e,t={})=>{if(e.startsWith("http"))return fetch(e,t).then(n=>n.json());try{return globalThis.__enhancerElectronApi.nodeRequire(`notion-enhancer/${e}`)}catch{return fetch(E(e),t).then(r=>r.json())}},ye=(e,t={})=>{if(e.startsWith("http"))return fetch(e,t).then(n=>n.text());try{let n=globalThis.__enhancerElectronApi.nodeRequire("fs"),{resolve:r}=globalThis.__enhancerElectronApi.nodeRequire("path");return n.readFileSync(r(`${__dirname}/../../${e}`))}catch{return fetch(E(e),t).then(r=>r.text())}},ge=async e=>{try{let t=globalThis.__enhancerElectronApi.nodeRequire("fs"),{resolve:n}=globalThis.__enhancerElectronApi.nodeRequire("path");if(e.startsWith("http"))await fetch(e);else try{t.existsSync(n(`${__dirname}/../../${e}`))}catch{await fetch(E(e))}return!0}catch{return!1}},ve=globalThis.__enhancerElectronApi.notionPath;"use strict";var rt=E,st=me,ot=ye,it=ge,at=ve;var $={};g($,{addChangeListener:()=>pt,db:()=>dt,get:()=>ct,removeChangeListener:()=>ut,set:()=>lt});"use strict";var F=(e,t=void 0)=>globalThis.__enhancerElectronApi.db.get(e,t),H=(e,t)=>globalThis.__enhancerElectronApi.db.set(e,t),we=(e,t=F,n=H)=>(typeof e=="string"&&(e=[e]),{get:(r=[],s=void 0)=>t([...e,...r],s),set:(r,s)=>n([...e,...r],s)}),be=e=>globalThis.__enhancerElectronApi.db.addChangeListener(e),xe=e=>globalThis.__enhancerElectronApi.db.removeChangeListener(e);"use strict";var ct=F,lt=H,dt=we,pt=be,ut=xe;var I={};g(I,{browser:()=>ht,onMessage:()=>gt,sendMessage:()=>mt,sendMessageToHost:()=>yt,webFrame:()=>ft});"use strict";var ht=globalThis.__enhancerElectronApi?.browser,ft=globalThis.__enhancerElectronApi?.webFrame,mt=(e,t)=>globalThis.__enhancerElectronApi.ipcRenderer.sendMessage(e,t),yt=(e,t)=>globalThis.__enhancerElectronApi.ipcRenderer.sendMessageToHost(e,t),gt=(e,t)=>globalThis.__enhancerElectronApi.ipcRenderer.onMessage(e,t);var K={};g(K,{create:()=>bt,get:()=>_e,getPageID:()=>M,getSpaceID:()=>S,getUserID:()=>$e,search:()=>vt,set:()=>wt,sign:()=>$t,upload:()=>xt});"use strict";var m=e=>(e?.length===32&&!e.includes("-")&&(e=e.replace(/([\d\w]{8})([\d\w]{4})([\d\w]{4})([\d\w]{4})([\d\w]{12})/,"$1-$2-$3-$4-$5")),e),$e=()=>JSON.parse(localStorage["LRU:KeyValueStore2:current-user-id"]||{}).value,M=()=>m(o.queryParams().get("p")||location.pathname.split(/(-|\/)/g).reverse()[0]),V,S=async()=>(V||(V=(await _e(M())).space_id),V),_e=async(e,t="block")=>(e=m(e),(await p.getJSON("https://www.notion.so/api/v3/getRecordValues",{headers:{"Content-Type":"application/json"},body:JSON.stringify({requests:[{table:t,id:e}]}),method:"POST"})).results[0].value),vt=async(e="",t=20,n=S())=>(n=m(await n),await p.getJSON("https://www.notion.so/api/v3/search",{headers:{"Content-Type":"application/json"},body:JSON.stringify({type:"BlocksInSpace",query:e,spaceId:n,limit:t,filters:{isDeletedOnly:!1,excludeTemplates:!1,isNavigableOnly:!1,requireEditPermissions:!1,ancestors:[],createdBy:[],editedBy:[],lastEditedTime:{},createdTime:{}},sort:"Relevance",source:"quick_find"}),method:"POST"})),wt=async({recordID:e,recordTable:t="block",spaceID:n=S(),path:r=[]},s={})=>{n=m(await n),e=m(e);let c=await p.getJSON("https://www.notion.so/api/v3/saveTransactions",{headers:{"Content-Type":"application/json"},body:JSON.stringify({requestId:h.uuidv4(),transactions:[{id:h.uuidv4(),spaceId:n,operations:[{pointer:{table:t,id:e,spaceId:n},path:r,command:r.length?"set":"update",args:s}]}]}),method:"POST"});return c.errorId?c:!0},bt=async({recordValue:e={},recordTable:t="block"}={},{prepend:n=!1,siblingID:r=void 0,parentID:s=M(),parentTable:c="block",spaceID:a=S(),userID:i=$e()}={})=>{a=m(await a),s=m(s),r=m(r);let d=m(e?.id??h.uuidv4()),x=[],j={type:"text",id:d,version:0,created_time:new Date().getTime(),last_edited_time:new Date().getTime(),parent_id:s,parent_table:c,alive:!0,created_by_table:"notion_user",created_by_id:i,last_edited_by_table:"notion_user",last_edited_by_id:i,space_id:a,permissions:[{type:"user_permission",role:"editor",user_id:i}]};c==="space"?(s=a,j.parent_id=a,x.push("pages"),j.type="page"):c==="collection_view"?(x.push("page_sort"),j.type="page"):x.push("content");let ae=await p.getJSON("https://www.notion.so/api/v3/saveTransactions",{headers:{"Content-Type":"application/json"},body:JSON.stringify({requestId:h.uuidv4(),transactions:[{id:h.uuidv4(),spaceId:a,operations:[{pointer:{table:c,id:s,spaceId:a},path:x,command:n?"listBefore":"listAfter",args:{...r?{after:r}:{},id:d}},{pointer:{table:t,id:d,spaceId:a},path:[],command:"set",args:{...j,...e}}]}]}),method:"POST"});return ae.errorId?ae:d},xt=async(e,{pageID:t=M(),spaceID:n=S()}={})=>{n=m(await n),t=m(t);let r=await p.getJSON("https://www.notion.so/api/v3/getUploadFileUrl",{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({bucket:"secure",name:e.name,contentType:e.type,record:{table:"block",id:t,spaceId:n}})});return r.errorId?r:(fetch(r.signedPutUrl,{method:"PUT",headers:{"content-type":e.type},body:e}),r.url)},$t=(e,t,n="block")=>(e.startsWith("/")&&(e=`https://notion.so${e}`),e.includes("secure.notion-static.com")&&(e=new URL(e),e=`https://www.notion.so/signed/${encodeURIComponent(e.origin+e.pathname)}?table=${n}&id=${t}`),e);var h={};g(h,{is:()=>Tt,rgbContrast:()=>At,rgbLogShade:()=>Lt,slugger:()=>_t,uuidv4:()=>jt});"use strict";var _t=(e,t=new Set)=>{e=e.replace(/\s/g,"-").replace(/[^A-Za-z0-9-_]/g,"").toLowerCase();let n=0,r=e;for(;t.has(r);)n++,r=`${e}-${n}`;return r},jt=()=>crypto?.randomUUID?crypto.randomUUID():([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g,e=>(e^crypto.getRandomValues(new Uint8Array(1))[0]&15>>e/4).toString(16)),Lt=(e,t)=>{var n=parseInt,r=Math.round,[s,c,t,a]=t.split(","),i=e<0,d=i?0:e*255**2,i=i?1+e:1-e;return"rgb"+(a?"a(":"(")+r((i*n(s[3]=="a"?s.slice(5):s.slice(4))**2+d)**.5)+","+r((i*n(c)**2+d)**.5)+","+r((i*n(t)**2+d)**.5)+(a?","+a:")")},At=(e,t,n)=>Math.sqrt(.299*(e*e)+.587*(t*t)+.114*(n*n))>165.75?"rgb(0,0,0)":"rgb(255,255,255)",Et={alphanumeric:/^[\w\.-]+$/,uuid:/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,semver:/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/i,email:/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/i,url:/^[(http(s)?):\/\/(www\.)?a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,64}\b([-a-zA-Z0-9@:%_\+.~#?&//=]*)$/i,color:/^(?:#|0x)(?:[a-f0-9]{3}|[a-f0-9]{6})\b|(?:rgb|hsl)a?\([^\)]*\)$/i};function St(e,t){let n=e.match(t);return!!(n&&n.length)}var Tt=async(e,t,{extension:n=""}={})=>{if(n=!e||!e.endsWith||e.endsWith(n),Array.isArray(t))return t.includes(e);switch(t){case"array":return Array.isArray(e);case"object":return e&&typeof e=="object"&&!Array.isArray(e);case"undefined":case"boolean":case"number":return typeof e===t&&n;case"string":return typeof e===t&&n;case"alphanumeric":case"uuid":case"semver":case"email":case"url":case"color":return typeof e=="string"&&St(e,Et[t])&&n;case"file":return typeof e=="string"&&e&&await p.isFile(e)&&n}return!1};var y={};g(y,{core:()=>Le,db:()=>Ut,enabled:()=>zt,errors:()=>Jt,get:()=>D,list:()=>Y,optionDefault:()=>Ee,optionTypes:()=>Mt,profileDB:()=>X,profileName:()=>Ae,supportedEnvs:()=>qt});"use strict";var l=async(e,t,n,r,{extension:s="",error:c=`invalid ${t} (${s?`${s} `:""}${r}): ${JSON.stringify(n)}`,optional:a=!1}={})=>{let i;for(let d of Array.isArray(r)?[r]:r.split("|"))if(d==="file"?i=n&&!n.startsWith("http")?await h.is(`repo/${e._dir}/${n}`,d,{extension:s}):!1:i=await h.is(n,d,{extension:s}),i)break;return i||a&&await h.is(n,"undefined")?!0:(c&&e._err(c),!1)},kt=async e=>(e.environments=e.environments??y.supportedEnvs,await l(e,"environments",e.environments,"array")?e.environments.map(n=>l(e,"environments.env",n,y.supportedEnvs)):!1),Ct=async e=>{if(!await l(e,"tags",e.tags,"array"))return!1;let n=["core","extension","theme","integration"];if(!e.tags.filter(i=>n.includes(i)).length)return e._err(`invalid tags (must contain at least one of 'core', 'extension', 'theme' or 'integration'): + ${JSON.stringify(e.tags)}`),!1;let s=e.tags.includes("theme"),c=e.tags.includes("light")||e.tags.includes("dark"),a=e.tags.includes("light")&&e.tags.includes("dark");return s&&(!c||a)?(e._err(`invalid tags (themes must be either 'light' or 'dark', not neither or both): + ${JSON.stringify(e.tags)}`),!1):e.tags.map(i=>l(e,"tags.tag",i,"string"))},Pt=async e=>await l(e,"authors",e.authors,"array")?e.authors.map(n=>[l(e,"authors.author.name",n.name,"string"),l(e,"authors.author.email",n.email,"email",{optional:!0}),l(e,"authors.author.homepage",n.homepage,"url"),l(e,"authors.author.avatar",n.avatar,"url")]):!1,Ot=async e=>{if(!await l(e,"css",e.css,"object"))return!1;let n=[];for(let r of["frame","client","menu"]){if(!e.css[r])continue;let s=await l(e,`css.${r}`,e.css[r],"array");s&&(s=e.css[r].map(c=>l(e,`css.${r}.file`,c,"file",{extension:".css"}))),n.push(s)}return n},Rt=async e=>{if(!await l(e,"js",e.js,"object"))return!1;let n=[];for(let r of["frame","client","menu"]){if(!e.js[r])continue;let s=await l(e,`js.${r}`,e.js[r],"array");s&&(s=e.js[r].map(c=>l(e,`js.${r}.file`,c,"file",{extension:".mjs"}))),n.push(s)}if(e.js.electron)if(await l(e,"js.electron",e.js.electron,"array"))for(let s of e.js.electron){if(!await l(e,"js.electron.file",s,"object")){n.push(!1);continue}n.push([l(e,"js.electron.file.source",s.source,"file",{extension:".cjs"}),l(e,"js.electron.file.target",s.target,"string",{extension:".js"})])}else n.push(!1);return n},Nt=async e=>{if(!await l(e,"options",e.options,"array"))return!1;let n=[];for(let r of e.options){let s="options.option";if(!await l(e,`${s}.type`,r.type,y.optionTypes)){n.push(!1);continue}switch(r.environments=r.environments??y.supportedEnvs,n.push([l(e,`${s}.key`,r.key,"alphanumeric"),l(e,`${s}.label`,r.label,"string"),l(e,`${s}.tooltip`,r.tooltip,"string",{optional:!0}),l(e,`${s}.environments`,r.environments,"array").then(a=>a?r.environments.map(i=>l(e,`${s}.environments.env`,i,y.supportedEnvs)):!1)]),r.type){case"toggle":n.push(l(e,`${s}.value`,r.value,"boolean"));break;case"select":{let a=await l(e,`${s}.values`,r.values,"array");a&&(a=r.values.map(i=>l(e,`${s}.values.value`,i,"string"))),n.push(a);break}case"text":case"hotkey":n.push(l(e,`${s}.value`,r.value,"string"));break;case"number":case"color":n.push(l(e,`${s}.value`,r.value,r.type));break;case"file":{let a=await l(e,`${s}.extensions`,r.extensions,"array");a&&(a=r.extensions.map(i=>l(e,`${s}.extensions.extension`,i,"string"))),n.push(a);break}}}return n};async function je(e){let t=[l(e,"name",e.name,"string"),l(e,"id",e.id,"uuid"),l(e,"version",e.version,"semver"),kt(e),l(e,"description",e.description,"string"),l(e,"preview",e.preview,"file|url",{optional:!0}),Ct(e),Pt(e),Ot(e),Rt(e),Nt(e)];do t=await Promise.all(t.flat(1/0));while(t.some(n=>Array.isArray(n)));return t.every(n=>n)}"use strict";var Le=["a6621988-551d-495a-97d8-3c568bca2e9e","0f0bf8b6-eae6-4273-b307-8fc43f2ee082","36a2ffc9-27ff-480e-84a7-c7700a7d232d"],qt=["linux","win32","darwin","extension"],Mt=["toggle","select","text","number","color","file","hotkey"],Ae=async()=>$.get(["currentprofile"],"default"),X=async()=>$.db(["profiles",await Ae()]),G,Q=[],Y=async(e=t=>!0)=>{G||(G=new Promise(async(n,r)=>{let s=[];for(let c of await p.getJSON("repo/registry.json"))try{let a={...await p.getJSON(`repo/${c}/mod.json`),_dir:c,_err:i=>Q.push({source:c,message:i})};await je(a)&&s.push(a)}catch{Q.push({source:c,message:"invalid mod.json"})}n(s)}));let t=[];for(let n of await G)await e(n)&&t.push(n);return t},Jt=async()=>(await Y(),Q),D=async e=>(await Y(t=>t.id===e))[0],zt=async e=>(await D(e)).environments.includes(A.name)?Le.includes(e)?!0:(await X()).get(["_mods",e],!1):!1,Ee=async(e,t)=>{let n=await D(e),r=n.options.find(s=>s.key===t);if(!!r)switch(r.type){case"toggle":case"text":case"number":case"color":case"hotkey":return r.value;case"select":return r.values[0];case"file":return}},Ut=async e=>{let t=await X();return $.db([e],async(n,r=void 0)=>(typeof n=="string"&&(n=[n]),n.length===2&&(r=await Ee(e,n[1])??r),t.get(n,r)),t.set)};var o={};g(o,{addDocumentObserver:()=>Xt,addHotkeyListener:()=>Vt,copyToClipboard:()=>Ht,empty:()=>Wt,escape:()=>Te,html:()=>Ce,loadStylesheet:()=>Ft,queryParams:()=>Bt,raw:()=>ke,readFromClipboard:()=>It,removeDocumentObserver:()=>Gt,removeHotkeyListener:()=>Kt,render:()=>Pe,whenReady:()=>Zt});"use strict";var Se=!1,T=[],ee,J=[],te=[],Zt=(e=[])=>new Promise((t,n)=>{function r(){let s;s=setInterval(c,100);function c(){e.every(a=>document.querySelector(a))&&(clearInterval(s),t(!0))}c()}document.readyState!=="complete"?document.addEventListener("readystatechange",s=>{document.readyState==="complete"&&r()}):r()}),Bt=()=>new URLSearchParams(window.location.search),Te=e=>e.replace(/&/g,"&").replace(//g,">").replace(/'/g,"'").replace(/"/g,""").replace(/\\/g,"\"),ke=(e,...t)=>{let n=e.map(r=>r+(["string","number"].includes(typeof t[0])?t.shift():Te(JSON.stringify(t.shift(),null,2)??""))).join("");return n.includes("r.trim()).filter(r=>r.length).join(" ")},Ce=(e,...t)=>{let n=document.createRange().createContextualFragment(ke(e,...t));return n.children.length===1?n.children[0]:n.children},Pe=(e,...t)=>(t=t.map(n=>n instanceof HTMLCollection?[...n]:n).flat(1/0).filter(n=>n),e.append(...t),e),Wt=e=>{for(;e.firstChild&&e.removeChild(e.firstChild););return e},Ft=e=>{let t=Ce``; - render(document.head, $stylesheet4); - return $stylesheet4; -}; -var copyToClipboard = async (str) => { - try { - await navigator.clipboard.writeText(str); - } catch { - const $el = document.createElement("textarea"); - $el.value = str; - $el.setAttribute("readonly", ""); - $el.style.position = "absolute"; - $el.style.left = "-9999px"; - document.body.appendChild($el); - $el.select(); - document.execCommand("copy"); - document.body.removeChild($el); - } -}; -var readFromClipboard = () => { - return navigator.clipboard.readText(); -}; -var triggerHotkeyListener = (event, hotkey) => { - const inInput = document.activeElement.nodeName === "INPUT" && !hotkey.listenInInput; - if (inInput) - return; - const pressed = hotkey.keys.every((key) => { - key = key.toLowerCase(); - const modifiers = { - metaKey: ["meta", "os", "win", "cmd", "command"], - ctrlKey: ["ctrl", "control"], - shiftKey: ["shift"], - altKey: ["alt"] - }; - for (const modifier in modifiers) { - const pressed2 = modifiers[modifier].includes(key) && event[modifier]; - if (pressed2) - return true; - } - if (key === "space") - key = " "; - if (key === "plus") - key = "+"; - if (key === event.key.toLowerCase()) - return true; - }); - if (pressed) - hotkey.callback(event); -}; -var addHotkeyListener = (keys, callback, { listenInInput = false, keydown = false } = {}) => { - if (typeof keys === "string") - keys = keys.split("+"); - _hotkeyEventListeners.push({ keys, callback, listenInInput, keydown }); - if (!_hotkeyListenersActivated) { - _hotkeyListenersActivated = true; - document.addEventListener("keyup", (event) => { - for (const hotkey of _hotkeyEventListeners.filter(({ keydown: keydown2 }) => !keydown2)) { - triggerHotkeyListener(event, hotkey); - } - }); - document.addEventListener("keydown", (event) => { - for (const hotkey of _hotkeyEventListeners.filter(({ keydown: keydown2 }) => keydown2)) { - triggerHotkeyListener(event, hotkey); - } - }); - } -}; -var removeHotkeyListener = (callback) => { - _hotkeyEventListeners = _hotkeyEventListeners.filter((listener) => listener.callback !== callback); -}; -var addDocumentObserver = (callback, selectors = []) => { - if (!_documentObserver) { - const handle = (queue) => { - while (queue.length) { - const event = queue.shift(), matchesAddedNode = ($node, selector) => $node instanceof Element && ($node.matches(selector) || $node.matches(`${selector} *`) || $node.querySelector(selector)), matchesTarget = (selector) => event.target.matches(selector) || event.target.matches(`${selector} *`) || [...event.addedNodes].some(($node) => matchesAddedNode($node, selector)); - for (const listener of _documentObserverListeners) { - if (!listener.selectors.length || listener.selectors.some(matchesTarget)) { - listener.callback(event); - } - } - } - }; - _documentObserver = new MutationObserver((list2, observer) => { - if (!_documentObserverEvents.length) - requestIdleCallback(() => handle(_documentObserverEvents)); - _documentObserverEvents.push(...list2); - }); - _documentObserver.observe(document.body, { - childList: true, - subtree: true, - attributes: true - }); - } - _documentObserverListeners.push({ callback, selectors }); -}; -var removeDocumentObserver = (callback) => { - _documentObserverListeners = _documentObserverListeners.filter((listener) => listener.callback !== callback); -}; - -// insert/api/components/index.mjs -var components_exports = {}; -__export(components_exports, { - addCornerAction: () => addCornerAction, - addPanelView: () => addPanelView, - addTooltip: () => addTooltip, - feather: () => feather -}); - -// insert/api/components/tooltip.mjs -"use strict"; -var $stylesheet; -var _$tooltip; -var countLines = ($el) => [...$el.getClientRects()].reduce((prev, val) => prev.some((p) => p.y === val.y) ? prev : [...prev, val], []).length; -var position = async ($ref, offsetDirection, maxLines) => { - _$tooltip.style.top = `0px`; - _$tooltip.style.left = `0px`; - const rect = $ref.getBoundingClientRect(), { offsetWidth, offsetHeight } = _$tooltip, pad = 6; - let x = rect.x, y = Math.floor(rect.y); - if (["top", "bottom"].includes(offsetDirection)) { - if (offsetDirection === "top") - y -= offsetHeight + pad; - if (offsetDirection === "bottom") - y += rect.height + pad; - x -= offsetWidth / 2 - rect.width / 2; - _$tooltip.style.left = `${x}px`; - _$tooltip.style.top = `${y}px`; - const testLines = () => countLines(_$tooltip.firstElementChild) > maxLines, padEdgesX = testLines(); - while (testLines()) { - _$tooltip.style.left = `${window.innerWidth - x > x ? x++ : x--}px`; - } - if (padEdgesX) { - x += window.innerWidth - x > x ? pad : -pad; - _$tooltip.style.left = `${x}px`; - } - } - if (["left", "right"].includes(offsetDirection)) { - y -= offsetHeight / 2 - rect.height / 2; - if (offsetDirection === "left") - x -= offsetWidth + pad; - if (offsetDirection === "right") - x += rect.width + pad; - _$tooltip.style.left = `${x}px`; - _$tooltip.style.top = `${y}px`; - } - return true; -}; -var addTooltip = async ($ref, $content, { delay = 100, offsetDirection = "bottom", maxLines = 1 } = {}) => { - if (!$stylesheet) { - $stylesheet = web_exports.loadStylesheet("api/components/tooltip.css"); - _$tooltip = web_exports.html``; - web_exports.render(document.body, _$tooltip); - } - if (!globalThis.markdownit) - await import(fs_exports.localPath("dep/markdown-it.min.js")); - const md = markdownit({ linkify: true }); - if (!($content instanceof Element)) - $content = web_exports.html`- ${$content.split("\n").map((text) => md.renderInline(text)).join("`; - let displayDelay; - $ref.addEventListener("mouseover", async (event) => { - if (!displayDelay) { - displayDelay = setTimeout(async () => { - if ($ref.matches(":hover")) { - if (_$tooltip.style.display !== "block") { - _$tooltip.style.display = "block"; - web_exports.render(web_exports.empty(_$tooltip), $content); - position($ref, offsetDirection, maxLines); - await _$tooltip.animate([{ opacity: 0 }, { opacity: 1 }], { duration: 65 }).finished; - } - } - displayDelay = void 0; - }, delay); - } - }); - $ref.addEventListener("mouseout", async (event) => { - displayDelay = void 0; - if (_$tooltip.style.display === "block" && !$ref.matches(":hover")) { - await _$tooltip.animate([{ opacity: 1 }, { opacity: 0 }], { duration: 65 }).finished; - _$tooltip.style.display = ""; - } - }); -}; - -// insert/api/components/feather.mjs -"use strict"; -var _$iconSheet; -var feather = async (name3, attrs = {}) => { - if (!_$iconSheet) { - _$iconSheet = web_exports.html`${await fs_exports.getText("dep/feather-sprite.svg")}`; - } - attrs.style = ((attrs.style ? attrs.style + ";" : "") + "stroke:currentColor;stroke-width:2;stroke-linecap:round;stroke-linejoin:round;fill:none;").trim(); - attrs.viewBox = "0 0 24 24"; - return ``; -}; - -// insert/api/components/panel.mjs -"use strict"; -var _views = []; -var svgExpand = web_exports.raw``,Me,w,z,v,_,C,L,Je,ze,re,f,Ue,U,P,Z,se,b,oe,O,B="data-enhancer-panel-pinned",W=()=>_.hasAttribute(B),R=()=>{let e=[z,v,C,_].filter(t=>t);if(W()){ie();for(let t of e)t.removeAttribute(B)}else for(let t of e)t.setAttribute(B,"true");w.set(["panel.pinned"],W())},Ze=async()=>{document.documentElement.style.setProperty("--component--panel-width",f+"px"),w.set(["panel.width"],f)},Be=e=>{e.preventDefault(),re=!0,f=ze+(Je-e.clientX),f<190&&(f=190),f>480&&(f=480),_.style.width=f+"px",C.style.width=f+"px",z.style.paddingRight=f+"px",v&&(v.style.right=f+"px")},We=e=>{_.style.width="",C.style.width="",z.style.paddingRight="",v&&(v.style.right=""),Ze(),L.style.cursor="",document.body.removeEventListener("mousemove",Be),document.body.removeEventListener("mouseup",We)},en=e=>{Je=e.clientX,ze=f,L.style.cursor="auto",document.body.addEventListener("mousemove",Be),document.body.addEventListener("mouseup",We)},tn=()=>document.body.contains(b),Fe=()=>{if(!W())return R();o.render(Ue,O),o.empty(b);for(let t of k){let n=P.contains(t.$title),r=o.render(o.html``,o.render(o.html``,t.$icon.cloneNode(!0),t.$title.cloneNode(!0)));r.addEventListener("click",()=>{Ie(t),w.set(["panel.open"],t.id)}),o.render(b,r)}let e=Z.getBoundingClientRect();o.render(o.empty(O),o.render(o.html``,o.render(o.html``,b))),b.querySelector("[data-open]").focus(),b.animate([{opacity:0},{opacity:1}],{duration:200}),document.addEventListener("keydown",He)},ie=()=>{document.removeEventListener("keydown",He),b.animate([{opacity:1},{opacity:0}],{duration:200}).onfinish=()=>O.remove()},He=e=>{if(tn())switch(e.key){case"Escape":ie(),e.stopPropagation();break;case"Enter":document.activeElement.click(),e.stopPropagation();break;case"ArrowUp":(e.target.previousElementSibling||e.target.parentElement.lastElementChild).focus(),e.stopPropagation();break;case"ArrowDown":(e.target.nextElementSibling||e.target.parentElement.firstElementChild).focus(),e.stopPropagation();break}},Ie=e=>{let t=k.find(({$content:n})=>document.contains(n));o.render(o.empty(P),o.render(o.html``,e.$icon,e.$title)),e.onFocus(),o.render(o.empty(se),e.$content),t&&t.onBlur()};async function nn(){await o.whenReady([".notion-frame"]),z=document.querySelector(".notion-frame"),_=o.html``,C=o.html``,L=o.html`
")} -`,P=o.html``,Z=o.render(o.html``,P),se=o.html``,b=o.html``,oe=o.html`+ ${Dt} +`,O=o.html``;let e='.notion-cursor-listener > div[style*="flex-end"]',t=()=>{document.contains(v)||(v=document.querySelector(e),W()&&v&&v.setAttribute(B,"true"))};v=document.querySelector(e),o.addDocumentObserver(t,[e]),await w.get(["panel.pinned"])&&R(),o.addHotkeyListener(await w.get(["panel.hotkey"]),R),U.addEventListener("click",r=>{r.stopPropagation(),R()}),o.render(_,o.render(Z,P,oe,U),se,L),await rn(),await sn();let n='.notion-cursor-listener > .notion-sidebar-container ~ [style^="position: absolute"]';await o.whenReady([n]),document.querySelector(n).before(C,_)}async function rn(){f=await w.get(["panel.width"],240),Ze(),L.addEventListener("mousedown",en),L.addEventListener("click",()=>{re?re=!1:R()})}async function sn(){Ue=document.querySelector(".notion-app-inner"),Z.addEventListener("click",Fe),oe.addEventListener("click",Fe),O.addEventListener("click",ie)}var Ve=async({id:e,icon:t,title:n,$content:r,onFocus:s=()=>{},onBlur:c=()=>{}})=>{Me||(Me=o.loadStylesheet("api/components/panel.css")),w||(w=await y.db("36a2ffc9-27ff-480e-84a7-c7700a7d232d")),U||(U=o.html``);let a={id:e,$icon:o.render(o.html``,t instanceof Element?t:o.html`${t}`),$title:o.render(o.html``,n),$content:r,onFocus:s,onBlur:c};k.push(a),k.length===1&&await nn(),(k.length===1||await w.get(["panel.open"])===e)&&Ie(a)};"use strict";var Ke,q,Xe=async(e,t)=>{Ke||(Ke=o.loadStylesheet("api/components/corner-action.css"),q=o.html``),await o.whenReady([".notion-help-button"]);let n=document.querySelector(".notion-help-button"),r=document.querySelector(".onboarding-checklist-button");r&&q.prepend(r),q.prepend(n),o.render(document.querySelector(".notion-app-inner > .notion-cursor-listener"),q);let s=o.html` `;return s.addEventListener("click",t),o.render(q,s),s};"use strict";"use strict"; diff --git a/api/index.mjs b/api/index.mjs index e90bf3e..8fdfab8 100644 --- a/api/index.mjs +++ b/api/index.mjs @@ -9,7 +9,7 @@ /** @module notion-enhancer/api */ // compiles to .cjs for use in electron: -// npx -y esbuild insert/api/index.mjs --bundle --format=cjs --outfile=insert/api/index.cjs +// npx -y esbuild insert/api/index.mjs --minify --bundle --format=cjs --outfile=insert/api/index.cjs /** environment-specific methods and constants */ export * as env from './env.mjs'; @@ -22,7 +22,7 @@ export * as storage from './storage.mjs'; export * as electron from './electron.mjs'; /** a basic wrapper around notion's unofficial api */ -// export * as notion from './notion.mjs'; +export * as notion from './notion.mjs'; /** helpers for formatting, validating and parsing values */ export * as fmt from './fmt.mjs'; /** interactions with the enhancer's repository of mods */+ ${await N.feather("chevrons-right")} +