mirror of
https://github.com/Dasemu/Synapse.git
synced 2026-11-27 07:46:25 +00:00
Initial import of LogDarioSeq baseline
Establishes version control for the personal Logseq DB fork before starting the server-client architecture migration and domain features described in docs/agent-guide and the approved implementation plan. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
commit
40631362b3
2016 files changed
+543898
No files matched your search
@@ -0,0 +1 @@
|
||||
docs/
|
||||
@@ -0,0 +1,5 @@
|
||||
src/
|
||||
webpack.*
|
||||
.DS_Store
|
||||
docs/
|
||||
cljs-sdk/
|
||||
@@ -0,0 +1,4 @@
|
||||
module.exports = {
|
||||
...require('prettier-config-standard'),
|
||||
trailingComma: 'es5'
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.0.16]
|
||||
### Added
|
||||
- Support api of `logseq.UI.queryElementRect: (selector: string) => Promise<DOMRectReadOnly | null>`
|
||||
- Support api of `logseq.UI.queryElementById: (id: string) => Promise<string | boolean>`
|
||||
- Support api of `logseq.UI.checkSlotValid: (slot: UISlotIdentity['slot']) => Promise<boolean>`
|
||||
- Support api of `logseq.UI.resolveThemeCssPropsVals: (props: string | Array<string>) => Promise<any>`
|
||||
- Support api of `logseq.Assets.builtInOpen(path: string): Promise<boolean | undefined>`
|
||||
|
||||
### Fixed
|
||||
- fix Plugin can't register command shortcut with editing mode [#10392](https://github.com/logseq/logseq/issues/10392)
|
||||
- fix [Plugin API] [Keymap] Command without keybinding can't be present in Keymap [#10466](https://github.com/logseq/logseq/issues/10466)
|
||||
- fix [Possible DATA LOSS] [Plugin API] [Keymap] Any plugin could break the global config.edn [#10465](https://github.com/logseq/logseq/issues/10465)
|
||||
|
||||
## [0.0.15]
|
||||
### Added
|
||||
- Support a plug-in flag for the plugin slash commands item
|
||||
- Support api of `logseq.App.setCurrentGraphConfigs: (configs: {}) => Promise<void>`
|
||||
- Support hook of `logseq.App.onTodayJournalCreated: IUserHook<{ title: string }`
|
||||
- Support more template-related APIs
|
||||
- Support auto-check updates for the installed plugins from Marketplace
|
||||
|
||||
### Fixed
|
||||
- Select and Input elements rendered using provideUI via `onMacroRendererSlotted` don't function [#8374](https://github.com/logseq/logseq/issues/8374)
|
||||
- `logseq.Editor.getPageBlocksTree` does not work when page uuid is passed in as param [#4920](https://github.com/logseq/logseq/issues/4920)
|
||||
|
||||
|
||||
## [0.0.14]
|
||||
|
||||
### Fixed
|
||||
- missing arguments of `DB.datascriptQuery`
|
||||
|
||||
## [0.0.13]
|
||||
|
||||
### Added
|
||||
- Support block content slot hook `App.onBlockRendererSlotted` with a specific block UUID
|
||||
- Support plugins calling each other `App.invokeExternalPlugin` with key of models & commands.
|
||||
E.g. (It is recommended that the caller plugin upgrade the SDK to the latest.)
|
||||
```typescript
|
||||
// Defined at https://github.com/xyhp915/logseq-journals-calendar/blob/main/src/main.js#L74
|
||||
await logseq.App.invokeExternalPlugin('logseq-journals-calendar.models.goToToday')
|
||||
|
||||
// Defined at https://github.com/vipzhicheng/logseq-plugin-vim-shortcuts/blob/bec05aeee8/src/keybindings/down.ts#L20
|
||||
await logseq.App.invokeExternalPlugin('logseq-plugin-vim-shortcuts.commands.vim-shortcut-down-0')
|
||||
```
|
||||
- Support api of `Editor.saveFocusedCodeEditorContent` [#FQ](https://github.com/logseq/logseq/issues/7714)
|
||||
- Support predicate for `DB.datascriptQuery` inputs
|
||||
|
||||
### Fixed
|
||||
- Incorrect hook payload from `Editor.registerHighlightContextMenuItem`
|
||||
- Auto generate key if not exist for `provideUI` options
|
||||
|
||||
## [0.0.12]
|
||||
|
||||
### Added
|
||||
|
||||
- All configurations of current graph.
|
||||
`App.getCurrentGraphConfigs: () => Promise<any>`
|
||||
- All favorite pages list of current graph.
|
||||
`App.getCurrentGraphFavorites: () => Promise<Array<string> | null>`
|
||||
- All recent pages list of current graph.
|
||||
`App.getCurrentGraphRecent: () => Promise<Array<string> | null>`
|
||||
- Clear right sidebar blocks.
|
||||
`App.clearRightSidebarBlocks: (opts?: { close: boolean }) => void`
|
||||
- Support register `CodeMirror` enhancer. _#Experiment feature_
|
||||
`Experiments.registerExtensionsEnhancer<T = any>(type: 'katex' | 'codemirror', enhancer: (v: T) => Promise<any>)`
|
||||
- Support hooks for app search service. _#Alpha stage_
|
||||
`App.registerSearchService<T extends IPluginSearchServiceHooks>(s: T): void`
|
||||
- Support `focus` option for `App.insertBlock`. Credit
|
||||
to [[[tennox](https://github.com/tennox)]] [#PR](https://github.com/logseq/logseq/commit/4217057a44de65e5c64be37857af2fb4e9534b24)
|
||||
|
||||
### Fixed
|
||||
|
||||
- Adjust build script to be compatible for `shadow-cljs` bundler.
|
||||
> How to set up a clojurescript project with shadow-cljs?
|
||||
> https://github.com/rlhk/logseq-url-plus/blob/main/doc/dev-notes.md
|
||||
@@ -0,0 +1,46 @@
|
||||
## @logseq/libs
|
||||
|
||||
🚀 Logseq SDK libraries.
|
||||
|
||||
#### Installation
|
||||
|
||||
```shell
|
||||
pnpm add @logseq/libs
|
||||
```
|
||||
|
||||
#### Usage
|
||||
|
||||
Load `logseq` plugin sdk as global namespace
|
||||
|
||||
```js
|
||||
import "@logseq/libs"
|
||||
```
|
||||
|
||||
#### APIs & Samples & References
|
||||
- https://logseq.github.io/plugins/
|
||||
- https://github.com/logseq/logseq-plugin-samples
|
||||
- [The New DB properties developer guide - A](./development-notes/db_properties_guide.md)
|
||||
- [The New DB properties developer guide - B](./development-notes/db_properties_skill.md)
|
||||
- [Logseq Plugin Development Agents Guide](./development-notes/AGENTS.md)
|
||||
|
||||
#### Community templates
|
||||
|
||||
1. https://github.com/logseq/cljs-plugin-example
|
||||
2. https://github.com/YU000jp/logseq-plugin-sample-kit-typescript
|
||||
|
||||
#### Feedback
|
||||
If you have any feedback or encounter any issues, feel free to join Logseq's discord group.
|
||||
https://discord.gg/KpN4eHY
|
||||
|
||||
#### Generate CLJS SDK wrappers
|
||||
|
||||
To regenerate the ClojureScript facade from the JS SDK declarations (keeping the same argument shapes as the JS APIs while auto-converting to/from CLJS data):
|
||||
|
||||
```bash
|
||||
pnpm generate:schema # emits dist/logseq-sdk-schema.json
|
||||
bb libs:generate-cljs-sdk # emits logseq/core.cljs and per-proxy files under target/generated-cljs
|
||||
```
|
||||
|
||||
Non-proxy methods (those defined on `ILSPluginUser`, e.g. `ready`, `provide-ui`) land in `logseq.core`. Each proxy (`IAppProxy`, `IEditorProxy`, ...) is emitted to its own namespace such as `logseq.app` or `logseq.editor`, preserving the original JS argument ordering while automatically bean-converting CLJS data.
|
||||
|
||||
Pass `--out-dir` to change the output location or `--ns-prefix` to pick a different namespace root.
|
||||
+134
@@ -0,0 +1,134 @@
|
||||
---
|
||||
name: logseq-plugin-sdk
|
||||
description: Build, debug, or review Logseq plugins with the `@logseq/libs` SDK (TypeScript/JavaScript, iframe/shadow sandboxed). Use when the task involves writing plugin entry code, registering slash/command/UI items, provideUI/provideStyle/provideModel, settings schema, macro renderers, DB-graph properties & tags, Datascript/DSL queries, experimental APIs, theme plugins, or the `logseq/*` CLJS facade generated under this package.
|
||||
---
|
||||
|
||||
# Logseq Plugin SDK Skill
|
||||
|
||||
This skill governs work inside `libs/` — the source of the npm package [`@logseq/libs`](./package.json) and its CLJS facade under [`cljs-sdk/`](./cljs-sdk). Use it whenever the user is authoring, upgrading, or debugging a Logseq plugin, or extending the SDK itself.
|
||||
|
||||
## When to use
|
||||
|
||||
Trigger this skill when the task mentions any of:
|
||||
|
||||
- `@logseq/libs`, `logseq.App`, `logseq.Editor`, `logseq.DB`, `logseq.UI`, `logseq.Assets`, `logseq.Git`, `logseq.Experiments`
|
||||
- `provideUI` / `provideStyle` / `provideModel` / `useSettingsSchema` / `onMacroRendererSlotted`
|
||||
- `registerSlashCommand`, `registerBlockContextMenuItem`, `registerCommandPalette`, `registerUIItem`
|
||||
- Plugin `package.json` `logseq` block, themes, `effect` plugins, iframe/shadow sandbox
|
||||
- DB-graph properties, tags/classes, property idents (`:logseq.property/*`, `:plugin.property.<id>/*`)
|
||||
- Datascript / DSL queries through `logseq.DB.q` / `logseq.DB.datascriptQuery`
|
||||
- Regenerating the CLJS SDK (`yarn run generate:schema`, `bb libs:generate-cljs-sdk`)
|
||||
|
||||
If the user is editing core Logseq app code (not a plugin), prefer the repo-root `AGENTS.md` instead.
|
||||
|
||||
## Golden rules
|
||||
|
||||
1. **Always `await logseq.ready(main)`** before touching any API. Most SDK calls are async RPC over postMessage.
|
||||
2. **Detect graph mode** before using DB-only APIs: `await logseq.App.checkCurrentIsDbGraph()`. `IBatchBlock.properties` is **not** supported for DB graphs — use `Editor.upsertBlockProperty` / `upsertProperty` instead.
|
||||
3. **Clean up listeners** in `logseq.beforeunload` (collect the `off` functions returned by every `onXxx` hook).
|
||||
4. **Batch mutations** (`Editor.insertBatchBlock`) and **debounce** `DB.onChanged` / `onBlockChanged` handlers — they fire on every keystroke.
|
||||
5. **Prefer CSS variables** (`--ls-primary-text-color`, `--ls-primary-background-color`, `--ls-border-color`, …) over hard-coded colors so plugins follow the active theme.
|
||||
6. **Unique plugin id** in `package.json > logseq.id`; keep it lowercase-kebab. `main`/`entry` must point at a built HTML file.
|
||||
7. **Experimental APIs (`logseq.Experiments.*`) are unstable** — only use when no stable API exists and document the reason.
|
||||
8. **Idents are identity.** For built-in or cross-graph stable references, use idents (`:logseq.property/created-at`, `:plugin.property.<plugin-id>/<key>`) instead of display names.
|
||||
|
||||
## Canonical plugin skeleton
|
||||
|
||||
```ts
|
||||
import '@logseq/libs'
|
||||
|
||||
const offHooks: Array<() => void> = []
|
||||
|
||||
async function main() {
|
||||
logseq.useSettingsSchema([
|
||||
{ key: 'enabled', type: 'boolean', default: true, title: 'Enabled', description: '' },
|
||||
])
|
||||
|
||||
logseq.Editor.registerSlashCommand('My Command', async () => {
|
||||
await logseq.Editor.insertAtEditingCursor('Hello from my plugin!')
|
||||
})
|
||||
|
||||
offHooks.push(
|
||||
logseq.DB.onChanged(({ blocks }) => {
|
||||
// debounce in real code
|
||||
}),
|
||||
)
|
||||
|
||||
logseq.beforeunload(async () => {
|
||||
offHooks.forEach((off) => off())
|
||||
})
|
||||
}
|
||||
|
||||
logseq.ready(main).catch(console.error)
|
||||
```
|
||||
|
||||
## Workflow
|
||||
|
||||
1. **Scope the request.** Is it a new plugin, a change to an existing plugin, SDK-internal work, or the CLJS facade?
|
||||
2. **Load the right reference file(s)** from [`./guides/`](./guides) (see table below) before proposing code.
|
||||
3. **For SDK-internal changes**, open the matching TypeScript under [`./src/`](./src) (`LSPlugin.ts` for types, `LSPlugin.user.ts` for the proxy implementation, `modules/` for Experiments/Storage/Request).
|
||||
4. **For CLJS facade changes**, regenerate with:
|
||||
```bash
|
||||
yarn run generate:schema # dist/logseq-sdk-schema.json
|
||||
bb libs:generate-cljs-sdk # target/generated-cljs/logseq/*.cljs
|
||||
```
|
||||
Non-proxy methods land in `logseq.core`; each `IXxxProxy` gets its own namespace (`logseq.app`, `logseq.editor`, …).
|
||||
5. **Validate.** Build the plugin (`npm run build` / `parcel build`) and load it via Settings → Developer mode → `t p` → *Load unpacked plugin*. Use DevTools (`Cmd+Shift+I`) and `logseq.UI.showMsg` for quick feedback.
|
||||
6. **Respect the package.json rules** (see [`guides/AGENTS.md`](./guides/AGENTS.md) §Configuration Fields).
|
||||
|
||||
## Reference map (`./guides/`)
|
||||
|
||||
Load these on demand — do not dump their full contents unless needed:
|
||||
|
||||
| File | Load when… |
|
||||
|------|------------|
|
||||
| [`guides/AGENTS.md`](./guides/AGENTS.md) | Authoritative overview of SDK namespaces, `package.json > logseq` schema, theme plugins, UI injection, macro renderers, lifecycle. Start here for most plugin tasks. |
|
||||
| [`guides/custom_theme_guide.md`](./guides/custom_theme_guide.md) | Building or reviewing Logseq theme plugins, custom theme CSS, `logseq.themes`, `provideTheme`, theme variables, light/dark mode styling, or UI selector/theme-token guidance. |
|
||||
| [`guides/starter_guide.md`](./guides/starter_guide.md) | Bootstrapping a new plugin project (Node/TS toolchain, desktop dev-mode loading, hello-world). |
|
||||
| [`guides/commands_api_guide.md`](./guides/commands_api_guide.md) | `logseq.Commands` unified command bus, placements, command execution, unregister handlers, and migration from legacy command APIs. |
|
||||
| [`guides/db_properties_guide.md`](./guides/db_properties_guide.md) | Conceptual model: file-graph vs DB-graph properties, schema vs values, tag/class modeling. |
|
||||
| [`guides/db_properties_references.md`](./guides/db_properties_references.md) | API reference for `upsertProperty`, `upsertBlockProperty`, property schemas/types/cardinality. |
|
||||
| [`guides/db_tag_property_idents_guide.md`](./guides/db_tag_property_idents_guide.md) | Ident naming rules (`:logseq.property/*`, `:logseq.class/*`, `:plugin.property.<id>/*`, `:plugin.class.<id>/*`) and when to use them. |
|
||||
| [`guides/db_query_guide.md`](./guides/db_query_guide.md) | DSL (`logseq.DB.q`) vs Datascript (`logseq.DB.datascriptQuery`) queries, parameters, change watchers. |
|
||||
| [`guides/experiments_api_guide.md`](./guides/experiments_api_guide.md) | `logseq.Experiments.*` — React/ReactDOM reuse, internal components, CLJS interop, custom fenced-code / route / sidebar / property / block-body renderers. |
|
||||
|
||||
## Core API quick index
|
||||
|
||||
Full code examples live in [`guides/AGENTS.md`](./guides/AGENTS.md) — use this table to jump to the right namespace:
|
||||
|
||||
- `logseq.App` — info, graph, navigation, `registerUIItem`, `registerCommandPalette`, lifecycle hooks (`onCurrentGraphChanged`, `onThemeModeChanged`, `onRouteChanged`, `onMacroRendererSlotted`), `checkCurrentIsDbGraph`.
|
||||
- `logseq.Editor` — slash & context-menu commands, block CRUD, `insertBatchBlock`, pages, cursor/selection, `upsertBlockProperty` / `getBlockProperties` (DB).
|
||||
- `logseq.DB` — `q`, `datascriptQuery`, `onChanged`, `onBlockChanged`, `getFileContent` / `setFileContent`.
|
||||
- `logseq.UI` — `showMsg`, `closeMsg`, `queryElementRect`, `queryElementById`.
|
||||
- `logseq.Assets` — `listFilesOfCurrentGraph`, `makeSandboxStorage`, `makeUrl`, `builtInOpen`.
|
||||
- `logseq.Git` — `execCommand`, `loadIgnoreFile`, `saveIgnoreFile` (**file graphs / desktop only**).
|
||||
- `logseq.Experiments` — unstable; see the Experiments guide before using.
|
||||
- Top-level — `provideUI`, `provideStyle`, `provideModel`, `useSettingsSchema`, `onSettingsChanged`, `updateSettings`, `showMainUI` / `hideMainUI` / `toggleMainUI` / `setMainUIInlineStyle`, `beforeunload`, `ready`.
|
||||
|
||||
## Common pitfalls
|
||||
|
||||
- Forgetting `await` — nearly every API is async.
|
||||
- Using `IBatchBlock.properties` in a DB graph (silently ignored).
|
||||
- Treating `block.content` as current — it is deprecated; use `block.title`.
|
||||
- Registering the same `key` twice in `provideUI` / `provideStyle` without intending to replace.
|
||||
- Hard-coding colors instead of `--ls-*` CSS variables.
|
||||
- Leaking listeners (no cleanup in `beforeunload`).
|
||||
- Shipping plugins without `logseq.id` or with a non-unique id.
|
||||
- Assuming Git APIs exist on mobile / DB graphs.
|
||||
|
||||
## When editing SDK source
|
||||
|
||||
- Type definitions: [`src/LSPlugin.ts`](./src/LSPlugin.ts). Keep `IAppProxy`, `IEditorProxy`, `IDBProxy`, `IUIProxy`, `IAssetsProxy`, `IGitProxy`, `IExperimentsProxy` and the `ILSPluginUser` surface in sync.
|
||||
- User proxy implementation: [`src/LSPlugin.user.ts`](./src/LSPlugin.user.ts).
|
||||
- Modules: [`src/modules/`](./src/modules) (Experiments, Storage, Request).
|
||||
- After changing the public surface, regenerate the CLJS facade (see Workflow step 4) and update [`CHANGELOG.md`](./CHANGELOG.md).
|
||||
- Follow the repo commit style: short imperative subjects, optional scope (e.g. `enhance(libs): …`, `fix(libs): …`).
|
||||
|
||||
## Resources
|
||||
|
||||
- API docs: <https://plugins-doc.logseq.com>
|
||||
- Samples: <https://github.com/logseq/logseq-plugin-samples>
|
||||
- CLJS template: <https://github.com/logseq/cljs-plugin-example>
|
||||
- TS template: <https://github.com/YU000jp/logseq-plugin-sample-kit-typescript>
|
||||
- Discord: <https://discord.gg/KpN4eHY>
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"presets": [
|
||||
[
|
||||
"@babel/preset-env",
|
||||
{
|
||||
"targets": "chrome 72"
|
||||
}
|
||||
]
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
# Clojure/Leiningen
|
||||
pom.xml
|
||||
pom.xml.asc
|
||||
*.jar
|
||||
*.class
|
||||
/lib/
|
||||
/classes/
|
||||
/target/
|
||||
/checkouts/
|
||||
.lein-deps-sum
|
||||
.lein-repl-history
|
||||
.lein-plugins/
|
||||
.lein-failures
|
||||
.nrepl-port
|
||||
|
||||
# ClojureScript/Build
|
||||
.cpcache/
|
||||
.shadow-cljs/
|
||||
dist/
|
||||
out/
|
||||
|
||||
# Node.js
|
||||
node_modules/
|
||||
package-lock.json
|
||||
coverage/
|
||||
.nyc_output/
|
||||
|
||||
# IDE
|
||||
.idea/
|
||||
.vscode/
|
||||
.calva/
|
||||
.calva/output-window
|
||||
.lsp/
|
||||
.clj-kondo/
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
*.log
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2025 Logseq
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,31 @@
|
||||
{:paths ["src" "test"]
|
||||
:deps {org.babashka/cli {:mvn/version "0.8.67"}
|
||||
slipset/deps-deploy {:mvn/version "0.2.2"}}
|
||||
:tasks
|
||||
{:requires ([babashka.cli :as cli])
|
||||
:init (do
|
||||
(defn run [cmd]
|
||||
(let [result (shell cmd)]
|
||||
(when-not (zero? (:exit result))
|
||||
(throw (ex-info "Command failed" result))))))
|
||||
|
||||
clean {:doc "Clean compiled files"
|
||||
:task (do
|
||||
(run "rm -rf dist")
|
||||
(run "rm -rf .shadow-cljs")
|
||||
(run "rm -rf node_modules")
|
||||
(run "rm -rf out")
|
||||
(run "rm -rf .nyc_output")
|
||||
(run "rm -rf coverage"))}
|
||||
|
||||
install {:doc "Install dependencies"
|
||||
:task (run "pnpm install")}
|
||||
|
||||
build-jar {:doc "Build jar file"
|
||||
:task (shell "clojure -T:build jar")}
|
||||
|
||||
deploy {:doc "Deploy jar to Clojars"
|
||||
:task (shell "clojure -T:build deploy")}
|
||||
|
||||
release {:doc "Build release version and deploy to Clojars"
|
||||
:depends [clean install build-jar deploy]}}}
|
||||
@@ -0,0 +1,46 @@
|
||||
(ns build
|
||||
(:require [clojure.data.json :as json]
|
||||
[clojure.tools.build.api :as b]
|
||||
[deps-deploy.deps-deploy :as dd]))
|
||||
|
||||
(def lib 'com.logseq/libs)
|
||||
(def version
|
||||
(-> (slurp "package.json")
|
||||
(json/read-str :key-fn keyword)
|
||||
:version))
|
||||
(def class-dir "target/classes")
|
||||
(def basis (delay (b/create-basis {:project "deps.edn"})))
|
||||
(def jar-file (format "target/%s-%s.jar" (name lib) version))
|
||||
|
||||
(def pom-template
|
||||
[[:description "ClojureScript wrapper for @logseq/libs"]
|
||||
[:url "https://github.com/logseq/logseq"]
|
||||
[:licenses
|
||||
[:license
|
||||
[:name "MIT License"]
|
||||
[:url "https://opensource.org/licenses/MIT"]]]])
|
||||
|
||||
(def options
|
||||
{:class-dir class-dir
|
||||
:lib lib
|
||||
:version version
|
||||
:basis @basis
|
||||
:jar-file jar-file
|
||||
:src-dirs ["src"]
|
||||
:pom-data pom-template})
|
||||
|
||||
(defn clean [_]
|
||||
(b/delete {:path "target"}))
|
||||
|
||||
(defn jar [_]
|
||||
(clean nil)
|
||||
(b/write-pom options)
|
||||
(b/copy-dir {:src-dirs (:paths @basis)
|
||||
:target-dir class-dir})
|
||||
(b/jar options))
|
||||
|
||||
(defn deploy [_]
|
||||
(jar nil)
|
||||
(dd/deploy {:installer :remote
|
||||
:artifact jar-file
|
||||
:pom-file (b/pom-path {:lib lib :class-dir class-dir})}))
|
||||
@@ -0,0 +1,20 @@
|
||||
{:paths ["src" "test"]
|
||||
:deps {org.clojure/clojurescript {:mvn/version "1.12.134"}
|
||||
cljs-bean/cljs-bean {:mvn/version "1.9.0"}}
|
||||
|
||||
:npm-deps {"@logseq/libs" "0.2.3"}
|
||||
|
||||
:aliases
|
||||
{:dev
|
||||
{:extra-paths ["example"]}
|
||||
|
||||
:test
|
||||
{:extra-paths ["test"]
|
||||
:extra-deps {org.clojure/test.check {:mvn/version "1.1.1"}}
|
||||
:ns-default build}
|
||||
|
||||
:build
|
||||
{:deps {io.github.clojure/tools.build {:mvn/version "0.9.6"}
|
||||
slipset/deps-deploy {:mvn/version "0.2.1"}
|
||||
org.clojure/data.json {:mvn/version "2.4.0"}}
|
||||
:ns-default build}}}
|
||||
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"name": "@logseq/cljs-libs",
|
||||
"version": "0.0.12",
|
||||
"packageManager": "pnpm@10.33.0",
|
||||
"description": "Logseq plugin API wrapper",
|
||||
"dependencies": {
|
||||
"@logseq/libs": "0.3.2"
|
||||
},
|
||||
"files": [
|
||||
"dist"
|
||||
],
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/logseq/logseq.git"
|
||||
},
|
||||
"keywords": [
|
||||
"logseq",
|
||||
"clojurescript",
|
||||
"plugin",
|
||||
"@logseq/libs"
|
||||
],
|
||||
"author": "logseq",
|
||||
"license": "MIT",
|
||||
"bugs": {
|
||||
"url": "https://github.com/logseq/logseq/issues"
|
||||
},
|
||||
"homepage": "https://github.com/logseq/logseq#readme"
|
||||
}
|
||||
Generated
+122
@@ -0,0 +1,122 @@
|
||||
lockfileVersion: '9.0'
|
||||
|
||||
settings:
|
||||
autoInstallPeers: true
|
||||
excludeLinksFromLockfile: false
|
||||
|
||||
importers:
|
||||
|
||||
.:
|
||||
dependencies:
|
||||
'@logseq/libs':
|
||||
specifier: 0.3.2
|
||||
version: 0.3.2
|
||||
|
||||
packages:
|
||||
|
||||
'@logseq/libs@0.3.2':
|
||||
resolution: {integrity: sha512-U0nMvmhR7gAL7Ph2AYw6sHCYyJvJDptebqIxPIzHNTvXDWsNeSo8ZyO9QiCGMAaWxj2rHikvx2lqt/Ialc6tBw==}
|
||||
|
||||
'@types/trusted-types@2.0.7':
|
||||
resolution: {integrity: sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==}
|
||||
|
||||
change-case@5.4.4:
|
||||
resolution: {integrity: sha512-HRQyTk2/YPEkt9TnUPbOpr64Uw3KOicFWPVBb+xiHvd6eBx/qPr9xqfBFDT8P2vWsvvz4jbEkfDe71W3VyNu2w==}
|
||||
|
||||
csstype@3.2.3:
|
||||
resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==}
|
||||
|
||||
debug@4.4.3:
|
||||
resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==}
|
||||
engines: {node: '>=6.0'}
|
||||
peerDependencies:
|
||||
supports-color: '*'
|
||||
peerDependenciesMeta:
|
||||
supports-color:
|
||||
optional: true
|
||||
|
||||
deepmerge@4.3.1:
|
||||
resolution: {integrity: sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
|
||||
dompurify@3.3.3:
|
||||
resolution: {integrity: sha512-Oj6pzI2+RqBfFG+qOaOLbFXLQ90ARpcGG6UePL82bJLtdsa6CYJD7nmiU8MW9nQNOtCHV3lZ/Bzq1X0QYbBZCA==}
|
||||
|
||||
eventemitter3@5.0.4:
|
||||
resolution: {integrity: sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==}
|
||||
|
||||
fast-deep-equal@3.1.3:
|
||||
resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==}
|
||||
|
||||
inherits@2.0.3:
|
||||
resolution: {integrity: sha512-x00IRNXNy63jwGkJmzPigoySHbaqpNuzKbBOmzK+g2OdZpQ9w+sxCN+VSB3ja7IAge2OP2qpfxTjeNcyjmW1uw==}
|
||||
|
||||
lodash-es@4.17.23:
|
||||
resolution: {integrity: sha512-kVI48u3PZr38HdYz98UmfPnXl2DXrpdctLrFLCd3kOx1xUkOmpFPx7gCWWM5MPkL/fD8zb+Ph0QzjGFs4+hHWg==}
|
||||
|
||||
ms@2.1.3:
|
||||
resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}
|
||||
|
||||
path@0.12.7:
|
||||
resolution: {integrity: sha512-aXXC6s+1w7otVF9UletFkFcDsJeO7lSZBPUQhtb5O0xJe8LtYhj/GxldoL09bBj9+ZmE2hNoHqQSFMN5fikh4Q==}
|
||||
|
||||
process@0.11.10:
|
||||
resolution: {integrity: sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A==}
|
||||
engines: {node: '>= 0.6.0'}
|
||||
|
||||
util@0.10.4:
|
||||
resolution: {integrity: sha512-0Pm9hTQ3se5ll1XihRic3FDIku70C+iHUdT/W926rSgHV5QgXsYbKZN8MSC3tJtSkhuROzvsQjAaFENRXr+19A==}
|
||||
|
||||
snapshots:
|
||||
|
||||
'@logseq/libs@0.3.2':
|
||||
dependencies:
|
||||
change-case: 5.4.4
|
||||
csstype: 3.2.3
|
||||
debug: 4.4.3
|
||||
deepmerge: 4.3.1
|
||||
dompurify: 3.3.3
|
||||
eventemitter3: 5.0.4
|
||||
fast-deep-equal: 3.1.3
|
||||
lodash-es: 4.17.23
|
||||
path: 0.12.7
|
||||
transitivePeerDependencies:
|
||||
- supports-color
|
||||
|
||||
'@types/trusted-types@2.0.7':
|
||||
optional: true
|
||||
|
||||
change-case@5.4.4: {}
|
||||
|
||||
csstype@3.2.3: {}
|
||||
|
||||
debug@4.4.3:
|
||||
dependencies:
|
||||
ms: 2.1.3
|
||||
|
||||
deepmerge@4.3.1: {}
|
||||
|
||||
dompurify@3.3.3:
|
||||
optionalDependencies:
|
||||
'@types/trusted-types': 2.0.7
|
||||
|
||||
eventemitter3@5.0.4: {}
|
||||
|
||||
fast-deep-equal@3.1.3: {}
|
||||
|
||||
inherits@2.0.3: {}
|
||||
|
||||
lodash-es@4.17.23: {}
|
||||
|
||||
ms@2.1.3: {}
|
||||
|
||||
path@0.12.7:
|
||||
dependencies:
|
||||
process: 0.11.10
|
||||
util: 0.10.4
|
||||
|
||||
process@0.11.10: {}
|
||||
|
||||
util@0.10.4:
|
||||
dependencies:
|
||||
inherits: 2.0.3
|
||||
@@ -0,0 +1,354 @@
|
||||
;; Auto-generated via `bb libs:generate-cljs-sdk`
|
||||
(ns com.logseq.app
|
||||
(:require [com.logseq.core :as core]))
|
||||
|
||||
(def api-proxy (aget js/logseq "App"))
|
||||
|
||||
(defn- get-info-impl
|
||||
[key]
|
||||
(let [method (aget api-proxy "getInfo")
|
||||
args [key]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn get-info
|
||||
([]
|
||||
(get-info-impl nil))
|
||||
([key]
|
||||
(get-info-impl key)))
|
||||
|
||||
(defn get-user-info
|
||||
[]
|
||||
(let [method (aget api-proxy "getUserInfo")
|
||||
args []]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn get-user-configs
|
||||
[]
|
||||
(let [method (aget api-proxy "getUserConfigs")
|
||||
args []]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn register-search-service
|
||||
[s]
|
||||
(let [method (aget api-proxy "registerSearchService")
|
||||
args [s]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn register-command
|
||||
[type opts action]
|
||||
(let [method (aget api-proxy "registerCommand")
|
||||
args [type opts action]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn register-command-palette
|
||||
[opts action]
|
||||
(let [method (aget api-proxy "registerCommandPalette")
|
||||
args [opts action]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn- register-command-shortcut-impl
|
||||
[keybinding action opts]
|
||||
(let [method (aget api-proxy "registerCommandShortcut")
|
||||
args [keybinding action opts]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn register-command-shortcut
|
||||
"Supported key names"
|
||||
([keybinding action]
|
||||
(register-command-shortcut-impl keybinding action nil))
|
||||
([keybinding action opts]
|
||||
(register-command-shortcut-impl keybinding action opts)))
|
||||
|
||||
(defn invoke-external-command
|
||||
"Supported all registered palette commands"
|
||||
[type & args]
|
||||
(let [method (aget api-proxy "invokeExternalCommand")
|
||||
rest-args (vec args)
|
||||
args (into [type] rest-args)]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn invoke-external-plugin
|
||||
"Call external plugin command provided by models or registered commands"
|
||||
[type & args]
|
||||
(let [method (aget api-proxy "invokeExternalPlugin")
|
||||
rest-args (vec args)
|
||||
args (into [type] rest-args)]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn get-external-plugin
|
||||
[pid]
|
||||
(let [method (aget api-proxy "getExternalPlugin")
|
||||
args [pid]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn get-state-from-store
|
||||
"Get state from app store\nvalid state is here\nhttps://github.com/logseq/logseq/blob/master/src/main/frontend/state.cljs#L27"
|
||||
[path]
|
||||
(let [method (aget api-proxy "getStateFromStore")
|
||||
args [path]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn set-state-from-store
|
||||
[path value]
|
||||
(let [method (aget api-proxy "setStateFromStore")
|
||||
args [path value]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn relaunch
|
||||
[]
|
||||
(let [method (aget api-proxy "relaunch")
|
||||
args []]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn quit
|
||||
[]
|
||||
(let [method (aget api-proxy "quit")
|
||||
args []]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn open-external-link
|
||||
[url]
|
||||
(let [method (aget api-proxy "openExternalLink")
|
||||
args [url]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn exec-git-command
|
||||
[args]
|
||||
(let [method (aget api-proxy "execGitCommand")
|
||||
args [args]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn get-current-graph
|
||||
[]
|
||||
(let [method (aget api-proxy "getCurrentGraph")
|
||||
args []]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn check-current-is-db-graph
|
||||
[]
|
||||
(let [method (aget api-proxy "checkCurrentIsDbGraph")
|
||||
args []]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn get-current-graph-configs
|
||||
[& keys]
|
||||
(let [method (aget api-proxy "getCurrentGraphConfigs")
|
||||
rest-keys (vec keys)
|
||||
args (into [] rest-keys)]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn set-current-graph-configs
|
||||
[configs]
|
||||
(let [method (aget api-proxy "setCurrentGraphConfigs")
|
||||
args [configs]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn get-current-graph-favorites
|
||||
[]
|
||||
(let [method (aget api-proxy "getCurrentGraphFavorites")
|
||||
args []]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn get-current-graph-recent
|
||||
[]
|
||||
(let [method (aget api-proxy "getCurrentGraphRecent")
|
||||
args []]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn get-current-graph-templates
|
||||
[]
|
||||
(let [method (aget api-proxy "getCurrentGraphTemplates")
|
||||
args []]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn- push-state-impl
|
||||
[k params query]
|
||||
(let [method (aget api-proxy "pushState")
|
||||
args [k params query]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn push-state
|
||||
([k]
|
||||
(push-state-impl k nil nil))
|
||||
([k params]
|
||||
(push-state-impl k params nil))
|
||||
([k params query]
|
||||
(push-state-impl k params query)))
|
||||
|
||||
(defn- replace-state-impl
|
||||
[k params query]
|
||||
(let [method (aget api-proxy "replaceState")
|
||||
args [k params query]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn replace-state
|
||||
([k]
|
||||
(replace-state-impl k nil nil))
|
||||
([k params]
|
||||
(replace-state-impl k params nil))
|
||||
([k params query]
|
||||
(replace-state-impl k params query)))
|
||||
|
||||
(defn get-current-route
|
||||
[]
|
||||
(let [method (aget api-proxy "getCurrentRoute")
|
||||
args []]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn get-template
|
||||
[name]
|
||||
(let [method (aget api-proxy "getTemplate")
|
||||
args [name]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn exist-template
|
||||
[name]
|
||||
(let [method (aget api-proxy "existTemplate")
|
||||
args [name]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn- create-template-impl
|
||||
[target name opts]
|
||||
(let [method (aget api-proxy "createTemplate")
|
||||
args [target name opts]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn create-template
|
||||
([target name]
|
||||
(create-template-impl target name nil))
|
||||
([target name opts]
|
||||
(create-template-impl target name opts)))
|
||||
|
||||
(defn remove-template
|
||||
[name]
|
||||
(let [method (aget api-proxy "removeTemplate")
|
||||
args [name]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn insert-template
|
||||
[target name]
|
||||
(let [method (aget api-proxy "insertTemplate")
|
||||
args [target name]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn set-zoom-factor
|
||||
[factor]
|
||||
(let [method (aget api-proxy "setZoomFactor")
|
||||
args [factor]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn set-full-screen
|
||||
[flag]
|
||||
(let [method (aget api-proxy "setFullScreen")
|
||||
args [flag]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn set-left-sidebar-visible
|
||||
[flag]
|
||||
(let [method (aget api-proxy "setLeftSidebarVisible")
|
||||
args [flag]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn set-right-sidebar-visible
|
||||
[flag]
|
||||
(let [method (aget api-proxy "setRightSidebarVisible")
|
||||
args [flag]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn- clear-right-sidebar-blocks-impl
|
||||
[opts]
|
||||
(let [method (aget api-proxy "clearRightSidebarBlocks")
|
||||
args [opts]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn clear-right-sidebar-blocks
|
||||
([]
|
||||
(clear-right-sidebar-blocks-impl nil))
|
||||
([opts]
|
||||
(clear-right-sidebar-blocks-impl opts)))
|
||||
|
||||
(defn register-ui-item
|
||||
[type opts]
|
||||
(let [method (aget api-proxy "registerUIItem")
|
||||
args [type opts]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn register-page-menu-item
|
||||
[tag action]
|
||||
(let [method (aget api-proxy "registerPageMenuItem")
|
||||
args [tag action]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn on-current-graph-changed
|
||||
[callback]
|
||||
(let [method (aget api-proxy "onCurrentGraphChanged")
|
||||
args [callback]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn on-graph-after-indexed
|
||||
[callback]
|
||||
(let [method (aget api-proxy "onGraphAfterIndexed")
|
||||
args [callback]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn on-theme-mode-changed
|
||||
[callback]
|
||||
(let [method (aget api-proxy "onThemeModeChanged")
|
||||
args [callback]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn on-theme-changed
|
||||
[callback]
|
||||
(let [method (aget api-proxy "onThemeChanged")
|
||||
args [callback]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn on-today-journal-created
|
||||
[callback]
|
||||
(let [method (aget api-proxy "onTodayJournalCreated")
|
||||
args [callback]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn on-before-command-invoked
|
||||
[condition callback]
|
||||
(let [method (aget api-proxy "onBeforeCommandInvoked")
|
||||
args [condition callback]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn on-after-command-invoked
|
||||
[condition callback]
|
||||
(let [method (aget api-proxy "onAfterCommandInvoked")
|
||||
args [condition callback]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn on-block-renderer-slotted
|
||||
"provide ui slot to specific block with UUID"
|
||||
[condition callback]
|
||||
(let [method (aget api-proxy "onBlockRendererSlotted")
|
||||
args [condition callback]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn on-macro-renderer-slotted
|
||||
"provide ui slot to block `renderer` macro for `{{renderer arg1, arg2}}`"
|
||||
[callback]
|
||||
(let [method (aget api-proxy "onMacroRendererSlotted")
|
||||
args [callback]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn on-page-head-actions-slotted
|
||||
[callback]
|
||||
(let [method (aget api-proxy "onPageHeadActionsSlotted")
|
||||
args [callback]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn on-route-changed
|
||||
[callback]
|
||||
(let [method (aget api-proxy "onRouteChanged")
|
||||
args [callback]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn on-sidebar-visible-changed
|
||||
[callback]
|
||||
(let [method (aget api-proxy "onSidebarVisibleChanged")
|
||||
args [callback]]
|
||||
(core/call-method api-proxy method args)))
|
||||
@@ -0,0 +1,37 @@
|
||||
;; Auto-generated via `bb libs:generate-cljs-sdk`
|
||||
(ns com.logseq.assets
|
||||
(:require [com.logseq.core :as core]))
|
||||
|
||||
(def api-proxy (aget js/logseq "Assets"))
|
||||
|
||||
(defn- list-files-of-current-graph-impl
|
||||
[exts]
|
||||
(let [method (aget api-proxy "listFilesOfCurrentGraph")
|
||||
args [exts]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn list-files-of-current-graph
|
||||
([]
|
||||
(list-files-of-current-graph-impl nil))
|
||||
([exts]
|
||||
(list-files-of-current-graph-impl exts)))
|
||||
|
||||
(defn make-sandbox-storage
|
||||
[]
|
||||
(let [method (aget api-proxy "makeSandboxStorage")
|
||||
args []]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn make-url
|
||||
"make assets scheme url based on current graph"
|
||||
[path]
|
||||
(let [method (aget api-proxy "makeUrl")
|
||||
args [path]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn built-in-open
|
||||
"try to open asset type file in Logseq app"
|
||||
[path]
|
||||
(let [method (aget api-proxy "builtInOpen")
|
||||
args [path]]
|
||||
(core/call-method api-proxy method args)))
|
||||
@@ -0,0 +1,26 @@
|
||||
;; Auto-generated via `bb libs:generate-cljs-sdk`
|
||||
(ns com.logseq.commands
|
||||
(:require [com.logseq.core :as core]))
|
||||
|
||||
(def api-proxy (aget js/logseq "Commands"))
|
||||
|
||||
(defn- register-impl
|
||||
[id options action]
|
||||
(let [method (aget api-proxy "register")
|
||||
args [id options action]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn register
|
||||
"Register a plugin command with one or more placements.\n\nv1 keeps compatibility with the existing command APIs by mapping placements\nto palette commands, shortcuts, slash commands, and context-menu entries.\n`when` is stored as command metadata for future host-side evaluation."
|
||||
([id options]
|
||||
(register-impl id options nil))
|
||||
([id options action]
|
||||
(register-impl id options action)))
|
||||
|
||||
(defn execute
|
||||
"Execute a built-in or plugin command.\n\nBuilt-in commands use the existing `logseq.*` ids. Plugin commands can be\naddressed as `plugin-id/key`, `plugin-id.commands.key`, or a local command\nkey registered by the current plugin."
|
||||
[id & args]
|
||||
(let [method (aget api-proxy "execute")
|
||||
rest-args (vec args)
|
||||
args (into [id] rest-args)]
|
||||
(core/call-method api-proxy method args)))
|
||||
@@ -0,0 +1,145 @@
|
||||
;; Auto-generated via `bb libs:generate-cljs-sdk`
|
||||
(ns com.logseq.core
|
||||
(:require ["@logseq/libs"]
|
||||
[cljs-bean.core :as bean]
|
||||
[com.logseq.util :as util]))
|
||||
|
||||
(defn- normalize-result [result]
|
||||
(if (instance? js/Promise result)
|
||||
(.then result (fn [value] (normalize-result value)))
|
||||
(util/->clj-tagged result)))
|
||||
|
||||
(defn call-method [owner method args]
|
||||
(when-not method
|
||||
(throw (js/Error. "Missing method on logseq namespace")))
|
||||
(normalize-result (.apply method owner (bean/->js args))))
|
||||
|
||||
(def api-proxy js/logseq)
|
||||
|
||||
(defn- ready-impl
|
||||
[model callback]
|
||||
(let [method (aget api-proxy "ready")
|
||||
args [model callback]]
|
||||
(call-method api-proxy method args)))
|
||||
|
||||
(defn ready
|
||||
([]
|
||||
(ready-impl nil nil))
|
||||
([model]
|
||||
(ready-impl model nil))
|
||||
([model callback]
|
||||
(ready-impl model callback)))
|
||||
|
||||
(defn ensure-connected
|
||||
[]
|
||||
(let [method (aget api-proxy "ensureConnected")
|
||||
args []]
|
||||
(call-method api-proxy method args)))
|
||||
|
||||
(defn beforeunload
|
||||
[callback]
|
||||
(let [method (aget api-proxy "beforeunload")
|
||||
args [callback]]
|
||||
(call-method api-proxy method args)))
|
||||
|
||||
(defn provide-model
|
||||
[model]
|
||||
(let [method (aget api-proxy "provideModel")
|
||||
args [model]]
|
||||
(call-method api-proxy method args)))
|
||||
|
||||
(defn provide-theme
|
||||
[theme]
|
||||
(let [method (aget api-proxy "provideTheme")
|
||||
args [theme]]
|
||||
(call-method api-proxy method args)))
|
||||
|
||||
(defn provide-style
|
||||
[style]
|
||||
(let [method (aget api-proxy "provideStyle")
|
||||
args [style]]
|
||||
(call-method api-proxy method args)))
|
||||
|
||||
(defn provide-ui
|
||||
[ui]
|
||||
(let [method (aget api-proxy "provideUI")
|
||||
args [ui]]
|
||||
(call-method api-proxy method args)))
|
||||
|
||||
(defn use-settings-schema
|
||||
[schema]
|
||||
(let [method (aget api-proxy "useSettingsSchema")
|
||||
args [schema]]
|
||||
(call-method api-proxy method args)))
|
||||
|
||||
(defn update-settings
|
||||
[attrs]
|
||||
(let [method (aget api-proxy "updateSettings")
|
||||
args [attrs]]
|
||||
(call-method api-proxy method args)))
|
||||
|
||||
(defn on-settings-changed
|
||||
[cb]
|
||||
(let [method (aget api-proxy "onSettingsChanged")
|
||||
args [cb]]
|
||||
(call-method api-proxy method args)))
|
||||
|
||||
(defn show-settings-ui
|
||||
[]
|
||||
(let [method (aget api-proxy "showSettingsUI")
|
||||
args []]
|
||||
(call-method api-proxy method args)))
|
||||
|
||||
(defn hide-settings-ui
|
||||
[]
|
||||
(let [method (aget api-proxy "hideSettingsUI")
|
||||
args []]
|
||||
(call-method api-proxy method args)))
|
||||
|
||||
(defn set-main-ui-attrs
|
||||
[attrs]
|
||||
(let [method (aget api-proxy "setMainUIAttrs")
|
||||
args [attrs]]
|
||||
(call-method api-proxy method args)))
|
||||
|
||||
(defn set-main-ui-inline-style
|
||||
[style]
|
||||
(let [method (aget api-proxy "setMainUIInlineStyle")
|
||||
args [style]]
|
||||
(call-method api-proxy method args)))
|
||||
|
||||
(defn- hide-main-ui-impl
|
||||
[opts]
|
||||
(let [method (aget api-proxy "hideMainUI")
|
||||
args [opts]]
|
||||
(call-method api-proxy method args)))
|
||||
|
||||
(defn hide-main-ui
|
||||
([]
|
||||
(hide-main-ui-impl nil))
|
||||
([opts]
|
||||
(hide-main-ui-impl opts)))
|
||||
|
||||
(defn- show-main-ui-impl
|
||||
[opts]
|
||||
(let [method (aget api-proxy "showMainUI")
|
||||
args [opts]]
|
||||
(call-method api-proxy method args)))
|
||||
|
||||
(defn show-main-ui
|
||||
([]
|
||||
(show-main-ui-impl nil))
|
||||
([opts]
|
||||
(show-main-ui-impl opts)))
|
||||
|
||||
(defn toggle-main-ui
|
||||
[]
|
||||
(let [method (aget api-proxy "toggleMainUI")
|
||||
args []]
|
||||
(call-method api-proxy method args)))
|
||||
|
||||
(defn resolve-resource-full-url
|
||||
[file-path]
|
||||
(let [method (aget api-proxy "resolveResourceFullUrl")
|
||||
args [file-path]]
|
||||
(call-method api-proxy method args)))
|
||||
@@ -0,0 +1,54 @@
|
||||
;; Auto-generated via `bb libs:generate-cljs-sdk`
|
||||
(ns com.logseq.db
|
||||
(:require [com.logseq.core :as core]))
|
||||
|
||||
(def api-proxy (aget js/logseq "DB"))
|
||||
|
||||
(defn q
|
||||
"Run a DSL query. https://docs.logseq.com/#/page/queries"
|
||||
[dsl]
|
||||
(let [method (aget api-proxy "q")
|
||||
args [dsl]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn custom-query
|
||||
"Executes a datalog query through query-react,\ngiven either a regular datalog query or a simple query."
|
||||
[query]
|
||||
(let [method (aget api-proxy "customQuery")
|
||||
args [query]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn datascript-query
|
||||
"Run a datascript query with parameters."
|
||||
[query & inputs]
|
||||
(let [method (aget api-proxy "datascriptQuery")
|
||||
rest-inputs (vec inputs)
|
||||
args (into [query] rest-inputs)]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn on-changed
|
||||
"Hook all transaction data of DB."
|
||||
[callback]
|
||||
(let [method (aget api-proxy "onChanged")
|
||||
args [callback]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn on-block-changed
|
||||
"Subscribe a specific block changed event"
|
||||
[uuid callback]
|
||||
(let [method (aget api-proxy "onBlockChanged")
|
||||
args [uuid callback]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn set-file-content
|
||||
"For built-in files path `logseq/custom.js`, `logseq/custom.css`, `logseq/publish.js`, `logseq/publish.css` etc."
|
||||
[path content]
|
||||
(let [method (aget api-proxy "setFileContent")
|
||||
args [path content]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn get-file-content
|
||||
[path]
|
||||
(let [method (aget api-proxy "getFileContent")
|
||||
args [path]]
|
||||
(core/call-method api-proxy method args)))
|
||||
@@ -0,0 +1,534 @@
|
||||
;; Auto-generated via `bb libs:generate-cljs-sdk`
|
||||
(ns com.logseq.editor
|
||||
(:require [com.logseq.core :as core]))
|
||||
|
||||
(def api-proxy (aget js/logseq "Editor"))
|
||||
|
||||
(defn register-slash-command
|
||||
"register a custom command which will be added to the Logseq slash command list"
|
||||
[tag action]
|
||||
(let [method (aget api-proxy "registerSlashCommand")
|
||||
args [tag action]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn register-block-context-menu-item
|
||||
"register a custom command in the block context menu (triggered by right-clicking the block dot)"
|
||||
[label action]
|
||||
(let [method (aget api-proxy "registerBlockContextMenuItem")
|
||||
args [label action]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn- register-highlight-context-menu-item-impl
|
||||
[label action opts]
|
||||
(let [method (aget api-proxy "registerHighlightContextMenuItem")
|
||||
args [label action opts]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn register-highlight-context-menu-item
|
||||
"Current it's only available for pdf viewer"
|
||||
([label action]
|
||||
(register-highlight-context-menu-item-impl label action nil))
|
||||
([label action opts]
|
||||
(register-highlight-context-menu-item-impl label action opts)))
|
||||
|
||||
(defn check-editing
|
||||
[]
|
||||
(let [method (aget api-proxy "checkEditing")
|
||||
args []]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn insert-at-editing-cursor
|
||||
[content]
|
||||
(let [method (aget api-proxy "insertAtEditingCursor")
|
||||
args [content]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn restore-editing-cursor
|
||||
[]
|
||||
(let [method (aget api-proxy "restoreEditingCursor")
|
||||
args []]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn- exit-editing-mode-impl
|
||||
[select-block]
|
||||
(let [method (aget api-proxy "exitEditingMode")
|
||||
args [select-block]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn exit-editing-mode
|
||||
([]
|
||||
(exit-editing-mode-impl nil))
|
||||
([select-block]
|
||||
(exit-editing-mode-impl select-block)))
|
||||
|
||||
(defn get-editing-cursor-position
|
||||
[]
|
||||
(let [method (aget api-proxy "getEditingCursorPosition")
|
||||
args []]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn get-editing-block-content
|
||||
[]
|
||||
(let [method (aget api-proxy "getEditingBlockContent")
|
||||
args []]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn get-current-page
|
||||
[]
|
||||
(let [method (aget api-proxy "getCurrentPage")
|
||||
args []]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn get-today-page
|
||||
[]
|
||||
(let [method (aget api-proxy "getTodayPage")
|
||||
args []]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn get-current-block
|
||||
[]
|
||||
(let [method (aget api-proxy "getCurrentBlock")
|
||||
args []]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn get-selected-blocks
|
||||
[]
|
||||
(let [method (aget api-proxy "getSelectedBlocks")
|
||||
args []]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn clear-selected-blocks
|
||||
[]
|
||||
(let [method (aget api-proxy "clearSelectedBlocks")
|
||||
args []]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn get-current-page-blocks-tree
|
||||
"get all blocks of the current page as a tree structure"
|
||||
[]
|
||||
(let [method (aget api-proxy "getCurrentPageBlocksTree")
|
||||
args []]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn get-page-blocks-tree
|
||||
"get all blocks for the specified page"
|
||||
[src-page]
|
||||
(let [method (aget api-proxy "getPageBlocksTree")
|
||||
args [src-page]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn get-page-linked-references
|
||||
"get all page/block linked references"
|
||||
[src-page]
|
||||
(let [method (aget api-proxy "getPageLinkedReferences")
|
||||
args [src-page]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn get-pages-from-namespace
|
||||
"get flatten pages from top namespace"
|
||||
[namespace]
|
||||
(let [method (aget api-proxy "getPagesFromNamespace")
|
||||
args [namespace]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn get-pages-tree-from-namespace
|
||||
"construct pages tree from namespace pages"
|
||||
[namespace]
|
||||
(let [method (aget api-proxy "getPagesTreeFromNamespace")
|
||||
args [namespace]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn new-block-uuid
|
||||
"Create a unique UUID string which can then be assigned to a block."
|
||||
[]
|
||||
(let [method (aget api-proxy "newBlockUUID")
|
||||
args []]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn is-page-block
|
||||
[block]
|
||||
(let [method (aget api-proxy "isPageBlock")
|
||||
args [block]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn- insert-block-impl
|
||||
[src-block content opts]
|
||||
(let [method (aget api-proxy "insertBlock")
|
||||
args [src-block content opts]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn insert-block
|
||||
([src-block content]
|
||||
(insert-block-impl src-block content nil))
|
||||
([src-block content opts]
|
||||
(insert-block-impl src-block content opts)))
|
||||
|
||||
(defn- insert-batch-block-impl
|
||||
[src-block batch opts]
|
||||
(let [method (aget api-proxy "insertBatchBlock")
|
||||
args [src-block batch opts]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn insert-batch-block
|
||||
([src-block batch]
|
||||
(insert-batch-block-impl src-block batch nil))
|
||||
([src-block batch opts]
|
||||
(insert-batch-block-impl src-block batch opts)))
|
||||
|
||||
(defn- update-block-impl
|
||||
[src-block content opts]
|
||||
(let [method (aget api-proxy "updateBlock")
|
||||
args [src-block content opts]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn update-block
|
||||
([src-block content]
|
||||
(update-block-impl src-block content nil))
|
||||
([src-block content opts]
|
||||
(update-block-impl src-block content opts)))
|
||||
|
||||
(defn remove-block
|
||||
[src-block]
|
||||
(let [method (aget api-proxy "removeBlock")
|
||||
args [src-block]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn- get-block-impl
|
||||
[src-block opts]
|
||||
(let [method (aget api-proxy "getBlock")
|
||||
args [src-block opts]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn get-block
|
||||
([src-block]
|
||||
(get-block-impl src-block nil))
|
||||
([src-block opts]
|
||||
(get-block-impl src-block opts)))
|
||||
|
||||
(defn set-block-collapsed
|
||||
[src-block opts]
|
||||
(let [method (aget api-proxy "setBlockCollapsed")
|
||||
args [src-block opts]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn- get-page-impl
|
||||
[src-page opts]
|
||||
(let [method (aget api-proxy "getPage")
|
||||
args [src-page opts]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn get-page
|
||||
([src-page]
|
||||
(get-page-impl src-page nil))
|
||||
([src-page opts]
|
||||
(get-page-impl src-page opts)))
|
||||
|
||||
(defn- create-page-impl
|
||||
[page-name properties opts]
|
||||
(let [method (aget api-proxy "createPage")
|
||||
args [page-name properties opts]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn create-page
|
||||
([page-name]
|
||||
(create-page-impl page-name nil nil))
|
||||
([page-name properties]
|
||||
(create-page-impl page-name properties nil))
|
||||
([page-name properties opts]
|
||||
(create-page-impl page-name properties opts)))
|
||||
|
||||
(defn create-journal-page
|
||||
[date]
|
||||
(let [method (aget api-proxy "createJournalPage")
|
||||
args [date]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn delete-page
|
||||
[page-name]
|
||||
(let [method (aget api-proxy "deletePage")
|
||||
args [page-name]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn rename-page
|
||||
[old-name new-name]
|
||||
(let [method (aget api-proxy "renamePage")
|
||||
args [old-name new-name]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn- get-all-pages-impl
|
||||
[repo]
|
||||
(let [method (aget api-proxy "getAllPages")
|
||||
args [repo]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn get-all-pages
|
||||
([]
|
||||
(get-all-pages-impl nil))
|
||||
([repo]
|
||||
(get-all-pages-impl repo)))
|
||||
|
||||
(defn get-all-tags
|
||||
[]
|
||||
(let [method (aget api-proxy "getAllTags")
|
||||
args []]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn get-all-properties
|
||||
[]
|
||||
(let [method (aget api-proxy "getAllProperties")
|
||||
args []]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn get-tag-objects
|
||||
[name-or-ident]
|
||||
(let [method (aget api-proxy "getTagObjects")
|
||||
args [name-or-ident]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn- create-tag-impl
|
||||
[tag-name opts]
|
||||
(let [method (aget api-proxy "createTag")
|
||||
args [tag-name opts]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn create-tag
|
||||
([tag-name]
|
||||
(create-tag-impl tag-name nil))
|
||||
([tag-name opts]
|
||||
(create-tag-impl tag-name opts)))
|
||||
|
||||
(defn get-tag
|
||||
[name-or-ident]
|
||||
(let [method (aget api-proxy "getTag")
|
||||
args [name-or-ident]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn get-tags-by-name
|
||||
[tag-name]
|
||||
(let [method (aget api-proxy "getTagsByName")
|
||||
args [tag-name]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn add-tag-property
|
||||
[tag-id property-id-or-name]
|
||||
(let [method (aget api-proxy "addTagProperty")
|
||||
args [tag-id property-id-or-name]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn remove-tag-property
|
||||
[tag-id property-id-or-name]
|
||||
(let [method (aget api-proxy "removeTagProperty")
|
||||
args [tag-id property-id-or-name]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn add-tag-extends
|
||||
[tag-id parent-tag-id-or-name]
|
||||
(let [method (aget api-proxy "addTagExtends")
|
||||
args [tag-id parent-tag-id-or-name]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn remove-tag-extends
|
||||
[tag-id parent-tag-id-or-name]
|
||||
(let [method (aget api-proxy "removeTagExtends")
|
||||
args [tag-id parent-tag-id-or-name]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn add-block-tag
|
||||
[block-id tag-id]
|
||||
(let [method (aget api-proxy "addBlockTag")
|
||||
args [block-id tag-id]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn remove-block-tag
|
||||
[block-id tag-id]
|
||||
(let [method (aget api-proxy "removeBlockTag")
|
||||
args [block-id tag-id]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn set-block-icon
|
||||
[block-id icon-type icon-name]
|
||||
(let [method (aget api-proxy "setBlockIcon")
|
||||
args [block-id icon-type icon-name]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn remove-block-icon
|
||||
[block-id]
|
||||
(let [method (aget api-proxy "removeBlockIcon")
|
||||
args [block-id]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn add-property-value-choices
|
||||
[property-id choices]
|
||||
(let [method (aget api-proxy "addPropertyValueChoices")
|
||||
args [property-id choices]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn set-property-node-tags
|
||||
[property-id tag-ids]
|
||||
(let [method (aget api-proxy "setPropertyNodeTags")
|
||||
args [property-id tag-ids]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn- prepend-block-in-page-impl
|
||||
[page content opts]
|
||||
(let [method (aget api-proxy "prependBlockInPage")
|
||||
args [page content opts]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn prepend-block-in-page
|
||||
([page content]
|
||||
(prepend-block-in-page-impl page content nil))
|
||||
([page content opts]
|
||||
(prepend-block-in-page-impl page content opts)))
|
||||
|
||||
(defn- append-block-in-page-impl
|
||||
[page content opts]
|
||||
(let [method (aget api-proxy "appendBlockInPage")
|
||||
args [page content opts]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn append-block-in-page
|
||||
([page content]
|
||||
(append-block-in-page-impl page content nil))
|
||||
([page content opts]
|
||||
(append-block-in-page-impl page content opts)))
|
||||
|
||||
(defn get-previous-sibling-block
|
||||
[src-block]
|
||||
(let [method (aget api-proxy "getPreviousSiblingBlock")
|
||||
args [src-block]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn get-next-sibling-block
|
||||
[src-block]
|
||||
(let [method (aget api-proxy "getNextSiblingBlock")
|
||||
args [src-block]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn- move-block-impl
|
||||
[src-block target-block opts]
|
||||
(let [method (aget api-proxy "moveBlock")
|
||||
args [src-block target-block opts]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn move-block
|
||||
([src-block target-block]
|
||||
(move-block-impl src-block target-block nil))
|
||||
([src-block target-block opts]
|
||||
(move-block-impl src-block target-block opts)))
|
||||
|
||||
(defn- edit-block-impl
|
||||
[src-block opts]
|
||||
(let [method (aget api-proxy "editBlock")
|
||||
args [src-block opts]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn edit-block
|
||||
([src-block]
|
||||
(edit-block-impl src-block nil))
|
||||
([src-block opts]
|
||||
(edit-block-impl src-block opts)))
|
||||
|
||||
(defn select-block
|
||||
[src-block]
|
||||
(let [method (aget api-proxy "selectBlock")
|
||||
args [src-block]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn save-focused-code-editor-content
|
||||
[]
|
||||
(let [method (aget api-proxy "saveFocusedCodeEditorContent")
|
||||
args []]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn get-property
|
||||
[key]
|
||||
(let [method (aget api-proxy "getProperty")
|
||||
args [key]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn- upsert-property-impl
|
||||
[key schema opts]
|
||||
(let [method (aget api-proxy "upsertProperty")
|
||||
args [key schema opts]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn upsert-property
|
||||
([key]
|
||||
(upsert-property-impl key nil nil))
|
||||
([key schema]
|
||||
(upsert-property-impl key schema nil))
|
||||
([key schema opts]
|
||||
(upsert-property-impl key schema opts)))
|
||||
|
||||
(defn remove-property
|
||||
[key]
|
||||
(let [method (aget api-proxy "removeProperty")
|
||||
args [key]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn- upsert-block-property-impl
|
||||
[block key value options]
|
||||
(let [method (aget api-proxy "upsertBlockProperty")
|
||||
args [block key value options]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn upsert-block-property
|
||||
([block key value]
|
||||
(upsert-block-property-impl block key value nil))
|
||||
([block key value options]
|
||||
(upsert-block-property-impl block key value options)))
|
||||
|
||||
(defn remove-block-property
|
||||
[block key]
|
||||
(let [method (aget api-proxy "removeBlockProperty")
|
||||
args [block key]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn get-block-property
|
||||
[block key]
|
||||
(let [method (aget api-proxy "getBlockProperty")
|
||||
args [block key]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn get-block-properties
|
||||
[block]
|
||||
(let [method (aget api-proxy "getBlockProperties")
|
||||
args [block]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn get-page-properties
|
||||
[page]
|
||||
(let [method (aget api-proxy "getPageProperties")
|
||||
args [page]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn- scroll-to-block-in-page-impl
|
||||
[page-name block-id opts]
|
||||
(let [method (aget api-proxy "scrollToBlockInPage")
|
||||
args [page-name block-id opts]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn scroll-to-block-in-page
|
||||
([page-name block-id]
|
||||
(scroll-to-block-in-page-impl page-name block-id nil))
|
||||
([page-name block-id opts]
|
||||
(scroll-to-block-in-page-impl page-name block-id opts)))
|
||||
|
||||
(defn open-in-right-sidebar
|
||||
[id]
|
||||
(let [method (aget api-proxy "openInRightSidebar")
|
||||
args [id]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn open-pdf-viewer
|
||||
[asset-block-id-or-file-url]
|
||||
(let [method (aget api-proxy "openPDFViewer")
|
||||
args [asset-block-id-or-file-url]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn on-input-selection-end
|
||||
[callback]
|
||||
(let [method (aget api-proxy "onInputSelectionEnd")
|
||||
args [callback]]
|
||||
(core/call-method api-proxy method args)))
|
||||
@@ -0,0 +1,61 @@
|
||||
;; Auto-generated via `bb libs:generate-cljs-sdk`
|
||||
(ns com.logseq.experiments
|
||||
(:require [com.logseq.core :as core]))
|
||||
|
||||
(def api-proxy (aget js/logseq "Experiments"))
|
||||
|
||||
(defn invoke-exper-method
|
||||
[type & args]
|
||||
(let [method (aget api-proxy "invokeExperMethod")
|
||||
rest-args (vec args)
|
||||
args (into [type] rest-args)]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn load-scripts
|
||||
[& scripts]
|
||||
(let [method (aget api-proxy "loadScripts")
|
||||
rest-scripts (vec scripts)
|
||||
args (into [] rest-scripts)]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn register-fenced-code-renderer
|
||||
[lang opts]
|
||||
(let [method (aget api-proxy "registerFencedCodeRenderer")
|
||||
args [lang opts]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn register-daemon-renderer
|
||||
[key opts]
|
||||
(let [method (aget api-proxy "registerDaemonRenderer")
|
||||
args [key opts]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn register-hosted-renderer
|
||||
[key opts]
|
||||
(let [method (aget api-proxy "registerHostedRenderer")
|
||||
args [key opts]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn register-sidebar-renderer
|
||||
[key opts]
|
||||
(let [method (aget api-proxy "registerSidebarRenderer")
|
||||
args [key opts]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn register-route-renderer
|
||||
[key opts]
|
||||
(let [method (aget api-proxy "registerRouteRenderer")
|
||||
args [key opts]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn register-extensions-enhancer
|
||||
[type enhancer]
|
||||
(let [method (aget api-proxy "registerExtensionsEnhancer")
|
||||
args [type enhancer]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn ensure-host-scope
|
||||
[]
|
||||
(let [method (aget api-proxy "ensureHostScope")
|
||||
args []]
|
||||
(core/call-method api-proxy method args)))
|
||||
@@ -0,0 +1,23 @@
|
||||
;; Auto-generated via `bb libs:generate-cljs-sdk`
|
||||
(ns com.logseq.git
|
||||
(:require [com.logseq.core :as core]))
|
||||
|
||||
(def api-proxy (aget js/logseq "Git"))
|
||||
|
||||
(defn exec-command
|
||||
[args]
|
||||
(let [method (aget api-proxy "execCommand")
|
||||
args [args]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn load-ignore-file
|
||||
[]
|
||||
(let [method (aget api-proxy "loadIgnoreFile")
|
||||
args []]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn save-ignore-file
|
||||
[content]
|
||||
(let [method (aget api-proxy "saveIgnoreFile")
|
||||
args [content]]
|
||||
(core/call-method api-proxy method args)))
|
||||
@@ -0,0 +1,90 @@
|
||||
;; Auto-generated via `bb libs:generate-cljs-sdk`
|
||||
(ns com.logseq.net
|
||||
(:refer-clojure :exclude [get])
|
||||
(:require [com.logseq.core :as core]))
|
||||
|
||||
(def api-proxy (aget js/logseq "Net"))
|
||||
|
||||
(defn request
|
||||
[options]
|
||||
(let [method (aget api-proxy "request")
|
||||
args [options]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn- get-impl
|
||||
[url options]
|
||||
(let [method (aget api-proxy "get")
|
||||
args [url options]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn get
|
||||
([url]
|
||||
(get-impl url nil))
|
||||
([url options]
|
||||
(get-impl url options)))
|
||||
|
||||
(defn- head-impl
|
||||
[url options]
|
||||
(let [method (aget api-proxy "head")
|
||||
args [url options]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn head
|
||||
([url]
|
||||
(head-impl url nil))
|
||||
([url options]
|
||||
(head-impl url options)))
|
||||
|
||||
(defn- post-impl
|
||||
[url body options]
|
||||
(let [method (aget api-proxy "post")
|
||||
args [url body options]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn post
|
||||
([url]
|
||||
(post-impl url nil nil))
|
||||
([url body]
|
||||
(post-impl url body nil))
|
||||
([url body options]
|
||||
(post-impl url body options)))
|
||||
|
||||
(defn- put-impl
|
||||
[url body options]
|
||||
(let [method (aget api-proxy "put")
|
||||
args [url body options]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn put
|
||||
([url]
|
||||
(put-impl url nil nil))
|
||||
([url body]
|
||||
(put-impl url body nil))
|
||||
([url body options]
|
||||
(put-impl url body options)))
|
||||
|
||||
(defn- patch-impl
|
||||
[url body options]
|
||||
(let [method (aget api-proxy "patch")
|
||||
args [url body options]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn patch
|
||||
([url]
|
||||
(patch-impl url nil nil))
|
||||
([url body]
|
||||
(patch-impl url body nil))
|
||||
([url body options]
|
||||
(patch-impl url body options)))
|
||||
|
||||
(defn- delete-impl
|
||||
[url options]
|
||||
(let [method (aget api-proxy "delete")
|
||||
args [url options]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn delete
|
||||
([url]
|
||||
(delete-impl url nil))
|
||||
([url options]
|
||||
(delete-impl url options)))
|
||||
@@ -0,0 +1,49 @@
|
||||
;; Auto-generated via `bb libs:generate-cljs-sdk`
|
||||
(ns com.logseq.ui
|
||||
(:require [com.logseq.core :as core]))
|
||||
|
||||
(def api-proxy (aget js/logseq "UI"))
|
||||
|
||||
(defn- show-msg-impl
|
||||
[content status opts]
|
||||
(let [method (aget api-proxy "showMsg")
|
||||
args [content status opts]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn show-msg
|
||||
([content]
|
||||
(show-msg-impl content nil nil))
|
||||
([content status]
|
||||
(show-msg-impl content status nil))
|
||||
([content status opts]
|
||||
(show-msg-impl content status opts)))
|
||||
|
||||
(defn close-msg
|
||||
[key]
|
||||
(let [method (aget api-proxy "closeMsg")
|
||||
args [key]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn query-element-rect
|
||||
[selector]
|
||||
(let [method (aget api-proxy "queryElementRect")
|
||||
args [selector]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn query-element-by-id
|
||||
[id]
|
||||
(let [method (aget api-proxy "queryElementById")
|
||||
args [id]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn check-slot-valid
|
||||
[slot]
|
||||
(let [method (aget api-proxy "checkSlotValid")
|
||||
args [slot]]
|
||||
(core/call-method api-proxy method args)))
|
||||
|
||||
(defn resolve-theme-css-props-vals
|
||||
[props]
|
||||
(let [method (aget api-proxy "resolveThemeCssPropsVals")
|
||||
args [props]]
|
||||
(core/call-method api-proxy method args)))
|
||||
@@ -0,0 +1,31 @@
|
||||
(ns com.logseq.util
|
||||
(:require [cljs-bean.core :as bean]
|
||||
[clojure.string :as string]
|
||||
[clojure.walk :as walk]))
|
||||
|
||||
(def ^:private kw-tag "___kw___")
|
||||
|
||||
(defn- decode-kw [v]
|
||||
(if (and (string? v) (string/starts-with? v kw-tag))
|
||||
(let [s (subs v (count kw-tag))
|
||||
i (.indexOf s "/")]
|
||||
(if (neg? i)
|
||||
(keyword s) ; :name
|
||||
(keyword (subs s 0 i) (subs s (inc i))))) ; :ns/name
|
||||
v))
|
||||
|
||||
(defn ->clj-tagged [js]
|
||||
(some->> js
|
||||
bean/->clj
|
||||
(walk/postwalk (fn [f]
|
||||
(cond
|
||||
(keyword? f)
|
||||
(decode-kw (if-let [ns (namespace f)]
|
||||
(str ns "/" (name f))
|
||||
(name f)))
|
||||
|
||||
(string? f)
|
||||
(decode-kw f)
|
||||
|
||||
:else
|
||||
f)))))
|
||||
@@ -0,0 +1,628 @@
|
||||
# AGENTS.md - Logseq Plugin Development Guide
|
||||
|
||||
## Overview
|
||||
|
||||
This document provides guidance for AI agents (Copilot, coding assistants, etc.) to help develop Logseq plugins using
|
||||
the `@logseq/libs` SDK.
|
||||
|
||||
Logseq is a privacy-first, open-source knowledge management and note-taking application built on top of local plain-text
|
||||
Markdown and Org-mode files. The plugin system extends Logseq's functionality through a JavaScript/TypeScript SDK.
|
||||
|
||||
## Repository Structure
|
||||
|
||||
### Core SDK (`logseq/logseq` - `libs/` folder)
|
||||
|
||||
The official SDK source code is located in the `libs/` directory of the main Logseq repository:
|
||||
|
||||
```
|
||||
libs/
|
||||
├── src/
|
||||
│ ├── LSPlugin.ts # Main type definitions & interfaces
|
||||
│ ├── LSPlugin.user.ts # User-facing plugin API implementation
|
||||
│ ├── LSPlugin.core.ts # Core plugin system
|
||||
│ ├── LSPlugin. caller.ts # IPC message caller
|
||||
│ ├── LSPlugin.shadow.ts # Shadow DOM support
|
||||
│ ├── helpers.ts # Utility functions
|
||||
│ ├── modules/ # Additional modules (Experiments, Storage, Request)
|
||||
│ └── postmate/ # Cross-frame communication
|
||||
├── package.json # NPM package config (@logseq/libs)
|
||||
├── README.md # SDK documentation
|
||||
└── CHANGELOG.md # Version history
|
||||
```
|
||||
|
||||
### Plugin Samples (`logseq/logseq-plugin-samples`)
|
||||
|
||||
Official sample plugins demonstrating various SDK features:
|
||||
|
||||
| Sample | Description | Key APIs |
|
||||
|-------------------------------|----------------------------------|-------------------------------------------------|
|
||||
| `logseq-slash-commands` | Basic slash command registration | `Editor.registerSlashCommand` |
|
||||
| `logseq-pomodoro-timer` | Macro renderer & slot UI | `App.onMacroRendererSlotted`, `provideUI` |
|
||||
| `logseq-a-translator` | Selection hooks & float UI | `Editor.onInputSelectionEnd`, `provideUI` |
|
||||
| `logseq-awesome-fonts` | Custom styles & settings | `provideStyle`, `useSettingsSchema` |
|
||||
| `logseq-bujo-themes` | Custom theme development | `provideTheme` |
|
||||
| `logseq-journals-calendar` | Calendar integration | `App.getCurrentGraph`, `Editor.getPage` |
|
||||
| `logseq-emoji-picker` | UI overlay with 3rd party libs | `showMainUI`, `hideMainUI` |
|
||||
| `logseq-reddit-hot-news` | Batch block insertion | `Editor.insertBatchBlock`, `App.registerUIItem` |
|
||||
| `logseq-imdb-top250-importer` | DB graph data import | DB-specific APIs |
|
||||
|
||||
## Plugin Architecture
|
||||
|
||||
### Entry Point Pattern
|
||||
|
||||
Every Logseq plugin follows this basic pattern:
|
||||
|
||||
```typescript
|
||||
import '@logseq/libs'
|
||||
|
||||
async function main() {
|
||||
// Plugin initialization code
|
||||
console.log('Plugin loaded!')
|
||||
}
|
||||
|
||||
// Bootstrap
|
||||
logseq.ready(main).catch(console.error)
|
||||
```
|
||||
|
||||
### Plugin Modes
|
||||
|
||||
Plugins can run in two modes defined in `package.json`:
|
||||
|
||||
- **`iframe`** (default): Plugin runs in an isolated iframe sandbox
|
||||
- **`shadow`** (still draft): Plugin runs in a Shadow DOM container (faster, less isolation)
|
||||
|
||||
> **⚠️ Sandbox Environment:** All Logseq plugins run in an isolated iframe sandbox.
|
||||
> This provides security isolation between plugins and the
|
||||
> main application. Communication between the plugin iframe and
|
||||
> Logseq happens through a postMessage-based RPC mechanism.
|
||||
|
||||
### package.json Configuration
|
||||
|
||||
## Package. json Configuration
|
||||
|
||||
### Basic Structure
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "logseq-my-plugin",
|
||||
"version": "0.1.0",
|
||||
"description": "A brief description of your plugin",
|
||||
"author": "Your Name",
|
||||
"license": "MIT",
|
||||
"main": "dist/index.html",
|
||||
"scripts": {
|
||||
"dev": "parcel ./index.html --public-url ./",
|
||||
"build": "parcel build --public-url . --no-source-maps index.html"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@logseq/libs": "^0.0.17",
|
||||
"parcel": "^2.0.0"
|
||||
},
|
||||
"logseq": {
|
||||
"id": "my-unique-plugin-id",
|
||||
"main": "dist/index.html",
|
||||
"icon": "./icon.png"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Logseq Configuration Block
|
||||
|
||||
The `logseq` field in `package.json` defines plugin metadata and behavior:
|
||||
|
||||
```json
|
||||
{
|
||||
"logseq": {
|
||||
"id": "my-unique-plugin-id",
|
||||
"main": "dist/index.html",
|
||||
"icon": "./icon. png",
|
||||
"title": "My Plugin Display Name",
|
||||
"effect": true,
|
||||
"themes": [
|
||||
{
|
||||
"name": "My Dark Theme",
|
||||
"url": "./css/dark.css",
|
||||
"mode": "dark",
|
||||
"description": "A beautiful dark theme"
|
||||
},
|
||||
{
|
||||
"name": "My Light Theme",
|
||||
"url": "./css/light.css",
|
||||
"mode": "light",
|
||||
"description": "A clean light theme"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Configuration Fields
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|------------|-----------|----------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
|
||||
| `id` | `string` | Yes | Unique plugin identifier. Must be unique across all plugins. Use lowercase with hyphens. |
|
||||
| `main` | `string` | Yes | Entry point HTML file path (relative to package.json). |
|
||||
| `entry` | `string` | No | Alias for `main`. |
|
||||
| `icon` | `string` | No | Plugin icon path. Displayed in plugin marketplace and settings. |
|
||||
| `title` | `string` | No | Display name shown in UI. Falls back to package `name` if not set. |
|
||||
| `effect` | `boolean` | No | When `true`, the plugin runs as a background effect without user interaction. Useful for plugins that only inject styles/themes or run automated tasks. Default: `false`. |
|
||||
| `themes` | `Theme[]` | No | Array of theme definitions this plugin provides. |
|
||||
| `devEntry` | `string` | No | Alternative entry point for development (e.g., with HMR). |
|
||||
|
||||
### Theme Configuration
|
||||
|
||||
For theme-only plugins, define themes in the `themes` array:
|
||||
|
||||
```json
|
||||
{
|
||||
"logseq": {
|
||||
"id": "my-theme-pack",
|
||||
"main": "dist/index.html",
|
||||
"effect": true,
|
||||
"themes": [
|
||||
{
|
||||
"name": "Nord Dark",
|
||||
"url": "./themes/nord-dark.css",
|
||||
"mode": "dark",
|
||||
"description": "Nord-inspired dark color scheme"
|
||||
},
|
||||
{
|
||||
"name": "Nord Light",
|
||||
"url": "./themes/nord-light.css",
|
||||
"mode": "light",
|
||||
"description": "Nord-inspired light color scheme"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Theme Object Fields:**
|
||||
|
||||
| Field | Type | Required | Description |
|
||||
|---------------|----------|----------|--------------------------------------------------|
|
||||
| `name` | `string` | Yes | Theme display name shown in theme selector. |
|
||||
| `url` | `string` | Yes | Path to the CSS file (relative to package.json). |
|
||||
| `mode` | `light` | `dark` | Yes | Theme mode. Determines when theme appears in selector. |
|
||||
| `description` | `string` | No | Brief description of the theme. |
|
||||
|
||||
## Core API Namespaces
|
||||
|
||||
The SDK exposes the following primary namespaces through the global `logseq` object:
|
||||
|
||||
### `logseq. App` - Application APIs
|
||||
|
||||
Application-level operations and hooks:
|
||||
|
||||
```typescript
|
||||
// Get app/user information
|
||||
await logseq.App.getInfo()
|
||||
await logseq.App.getUserConfigs()
|
||||
await logseq.App.getCurrentGraph()
|
||||
|
||||
// Graph operations
|
||||
await logseq.App.getCurrentGraphFavorites()
|
||||
await logseq.App.getCurrentGraphRecent()
|
||||
|
||||
// Navigation
|
||||
logseq.App.pushState('page', { name: 'my-page' })
|
||||
|
||||
// UI Registration
|
||||
logseq.App.registerUIItem('toolbar', {
|
||||
key: 'my-button',
|
||||
template: `<a data-on-click="myHandler">Click</a>`
|
||||
})
|
||||
|
||||
// Command Registration
|
||||
logseq.App.registerCommandPalette({
|
||||
key: 'my-command',
|
||||
label: 'My Command',
|
||||
keybinding: { binding: 'mod+shift+m' }
|
||||
}, () => { /* action */ })
|
||||
|
||||
// Event Hooks
|
||||
logseq.App.onCurrentGraphChanged(() => {})
|
||||
logseq.App.onThemeModeChanged(({ mode }) => {})
|
||||
logseq.App.onRouteChanged(({ path }) => {})
|
||||
logseq.App.onMacroRendererSlotted(({ slot, payload }) => {})
|
||||
```
|
||||
|
||||
### `logseq.Editor` - Editor APIs
|
||||
|
||||
Block and page manipulation:
|
||||
|
||||
```typescript
|
||||
// Slash Commands
|
||||
logseq.Editor.registerSlashCommand('My Command', async ({ uuid }) => {
|
||||
await logseq.Editor.insertAtEditingCursor('Hello!')
|
||||
})
|
||||
|
||||
// Block Context Menu
|
||||
logseq.Editor.registerBlockContextMenuItem('My Action', async ({ uuid }) => {
|
||||
const block = await logseq.Editor.getBlock(uuid)
|
||||
})
|
||||
|
||||
// Block Operations
|
||||
await logseq.Editor.getBlock(uuid)
|
||||
await logseq.Editor.insertBlock(uuid, 'content', { sibling: true })
|
||||
await logseq.Editor.updateBlock(uuid, 'new content')
|
||||
await logseq.Editor.removeBlock(uuid)
|
||||
await logseq.Editor.insertBatchBlock(uuid, [
|
||||
{ content: 'Block 1', children: [{ content: 'Child' }] }
|
||||
])
|
||||
|
||||
// Page Operations
|
||||
await logseq.Editor.getPage('page-name')
|
||||
await logseq.Editor.createPage('new-page', { prop: 'value' })
|
||||
await logseq.Editor.deletePage('page-name')
|
||||
await logseq.Editor.getCurrentPageBlocksTree()
|
||||
|
||||
// Cursor & Selection
|
||||
await logseq.Editor.checkEditing()
|
||||
await logseq.Editor.getEditingCursorPosition()
|
||||
await logseq.Editor.insertAtEditingCursor('text')
|
||||
await logseq.Editor.exitEditingMode()
|
||||
|
||||
// Properties (DB graphs)
|
||||
await logseq.Editor.upsertBlockProperty(uuid, 'key', 'value')
|
||||
await logseq.Editor.getBlockProperties(uuid)
|
||||
```
|
||||
|
||||
### `logseq.DB` - Database APIs
|
||||
|
||||
Query and data operations:
|
||||
|
||||
```typescript
|
||||
// DSL Query (Logseq query language)
|
||||
const results = await logseq.DB.q('[[my-page]]')
|
||||
|
||||
// Datascript Query
|
||||
const results1 = await logseq.DB.datascriptQuery(`
|
||||
[: find (pull ?b [*])
|
||||
:where [?b :block/marker "TODO"]]
|
||||
`)
|
||||
|
||||
// Watch for changes
|
||||
logseq.DB.onChanged(({ blocks, txData }) => {
|
||||
console.log('Database changed:', blocks)
|
||||
})
|
||||
|
||||
// Watch specific block
|
||||
logseq.DB.onBlockChanged(uuid, (block, txData) => {
|
||||
console.log('Block changed:', block)
|
||||
})
|
||||
|
||||
// File operations
|
||||
await logseq.DB.getFileContent('logseq/custom.css')
|
||||
await logseq.DB.setFileContent('logseq/custom.js', 'console.log("hi")')
|
||||
```
|
||||
|
||||
### `logseq.UI` - UI Utilities
|
||||
|
||||
```typescript
|
||||
// Toast messages
|
||||
await logseq.UI.showMsg('Success! ', 'success')
|
||||
await logseq.UI.showMsg('Warning!', 'warning', { timeout: 5000 })
|
||||
logseq.UI.closeMsg(key)
|
||||
|
||||
// DOM queries
|
||||
const rect = await logseq.UI.queryElementRect('.my-selector')
|
||||
const exists = await logseq.UI.queryElementById('my-id')
|
||||
```
|
||||
|
||||
### `logseq.Git` - Git Operations
|
||||
Only supported in file-based graphs for desktop Logseq.
|
||||
|
||||
```typescript
|
||||
const result = await logseq.Git.execCommand(['status'])
|
||||
const ignoreContent = await logseq.Git.loadIgnoreFile()
|
||||
await logseq.Git.saveIgnoreFile('. DS_Store\nnode_modules')
|
||||
```
|
||||
|
||||
### `logseq.Assets` - Asset Management
|
||||
|
||||
```typescript
|
||||
const files = await logseq.Assets.listFilesOfCurrentGraph(['png', 'jpg'])
|
||||
const storage = logseq.Assets.makeSandboxStorage()
|
||||
const url = await logseq.Assets.makeUrl('path/to/file')
|
||||
await logseq.Assets.builtInOpen('path/to/asset. pdf')
|
||||
```
|
||||
|
||||
## UI Injection Patterns
|
||||
|
||||
### provideUI - Inject Custom UI
|
||||
|
||||
```typescript
|
||||
logseq.provideUI({
|
||||
key: 'my-ui',
|
||||
path: '#my-target', // or use `slot` for macro renderers
|
||||
template: `<div data-on-click="myHandler">Click me</div>`,
|
||||
style: { backgroundColor: 'white', padding: '10px' },
|
||||
attrs: { title: 'My UI' },
|
||||
close: 'outside', // close when clicking outside
|
||||
})
|
||||
```
|
||||
|
||||
### provideStyle - Inject CSS
|
||||
|
||||
```typescript
|
||||
logseq.provideStyle(`
|
||||
.my-class {
|
||||
color: var(--ls-primary-text-color);
|
||||
background: var(--ls-primary-background-color);
|
||||
}
|
||||
`)
|
||||
|
||||
// Or with a key for updates
|
||||
logseq.provideStyle({
|
||||
key: 'my-styles',
|
||||
style: `.my-class { color: red; }`
|
||||
})
|
||||
```
|
||||
|
||||
### provideModel - Event Handlers
|
||||
|
||||
```typescript
|
||||
logseq.provideModel({
|
||||
myHandler(e) {
|
||||
console.log('Clicked!', e.dataset)
|
||||
},
|
||||
async asyncHandler(e) {
|
||||
const block = await logseq.Editor.getBlock(e.dataset.blockUuid)
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
### Main UI (Full-screen Overlay)
|
||||
|
||||
```typescript
|
||||
// Show plugin's main UI
|
||||
logseq.showMainUI({ autoFocus: true })
|
||||
|
||||
// Hide it
|
||||
logseq.hideMainUI({ restoreEditingCursor: true })
|
||||
|
||||
// Toggle
|
||||
logseq.toggleMainUI()
|
||||
|
||||
// Style the main UI container
|
||||
logseq.setMainUIInlineStyle({
|
||||
position: 'fixed',
|
||||
top: '100px',
|
||||
left: '50%',
|
||||
zIndex: 11,
|
||||
})
|
||||
```
|
||||
|
||||
## Settings Schema
|
||||
|
||||
Define user-configurable settings:
|
||||
|
||||
```typescript
|
||||
logseq.useSettingsSchema([
|
||||
{
|
||||
key: 'apiKey',
|
||||
type: 'string',
|
||||
default: '',
|
||||
title: 'API Key',
|
||||
description: 'Enter your API key'
|
||||
},
|
||||
{
|
||||
key: 'enableFeature',
|
||||
type: 'boolean',
|
||||
default: true,
|
||||
title: 'Enable Feature',
|
||||
description: 'Toggle this feature on/off'
|
||||
},
|
||||
{
|
||||
key: 'theme',
|
||||
type: 'enum',
|
||||
enumChoices: ['light', 'dark', 'auto'],
|
||||
enumPicker: 'select',
|
||||
default: 'auto',
|
||||
title: 'Theme',
|
||||
description: 'Select theme mode'
|
||||
},
|
||||
{
|
||||
key: 'fontSize',
|
||||
type: 'number',
|
||||
default: 14,
|
||||
title: 'Font Size',
|
||||
description: 'Customize font size',
|
||||
inputAs: 'range'
|
||||
}
|
||||
])
|
||||
|
||||
// Access settings
|
||||
const apiKey = logseq.settings?.apiKey
|
||||
|
||||
// Update settings
|
||||
logseq.updateSettings({ apiKey: 'new-key' })
|
||||
|
||||
// Listen for changes
|
||||
logseq.onSettingsChanged((newSettings, oldSettings) => {
|
||||
console.log('Settings changed:', newSettings)
|
||||
})
|
||||
```
|
||||
|
||||
## Macro Renderer Pattern
|
||||
|
||||
Create custom block renderers using `{{renderer : type, arg1, arg2}}`:
|
||||
|
||||
```typescript
|
||||
logseq.App.onMacroRendererSlotted(({ slot, payload }) => {
|
||||
const [type, ...args] = payload.arguments
|
||||
|
||||
if (type !== ':my-renderer') return
|
||||
|
||||
logseq.provideUI({
|
||||
key: `my-renderer-${payload.uuid}`,
|
||||
slot,
|
||||
template: `
|
||||
<div class="my-renderer">
|
||||
<span>${args.join(', ')}</span>
|
||||
</div>
|
||||
`,
|
||||
})
|
||||
})
|
||||
|
||||
// Register slash command to insert the macro
|
||||
logseq.Editor.registerSlashCommand('Insert My Renderer', async () => {
|
||||
await logseq.Editor.insertAtEditingCursor(
|
||||
`{{renderer :my-renderer, arg1, arg2}}`
|
||||
)
|
||||
})
|
||||
```
|
||||
|
||||
## Key Types Reference
|
||||
|
||||
### Block Entity
|
||||
|
||||
```typescript
|
||||
interface BlockEntity {
|
||||
id: number // Database entity ID
|
||||
uuid: string // Block UUID
|
||||
title: string // Block content
|
||||
content?: string // @deprecated, use title
|
||||
format: 'markdown' | 'org'
|
||||
parent: { id: number }
|
||||
page: { id: number }
|
||||
properties?: Record<string, any>
|
||||
children?: BlockEntity[]
|
||||
'collapsed? ': boolean
|
||||
createdAt: number
|
||||
updatedAt: number
|
||||
}
|
||||
```
|
||||
|
||||
### Page Entity
|
||||
|
||||
```typescript
|
||||
interface PageEntity {
|
||||
id: number
|
||||
uuid: string
|
||||
name: string
|
||||
type: 'page' | 'journal' | 'whiteboard' | 'class' | 'property' | 'hidden'
|
||||
format: 'markdown' | 'org'
|
||||
'journal? ': boolean
|
||||
journalDay?: number // YYYYMMDD format for journals
|
||||
properties?: Record<string, any>
|
||||
createdAt: number
|
||||
updatedAt: number
|
||||
}
|
||||
```
|
||||
|
||||
## Development Workflow
|
||||
|
||||
### Setup
|
||||
|
||||
```bash
|
||||
# Clone sample repository
|
||||
git clone https://github.com/logseq/logseq-plugin-samples
|
||||
cd logseq-plugin-samples/logseq-slash-commands
|
||||
|
||||
# Install dependencies
|
||||
pnpm install
|
||||
|
||||
# Build
|
||||
pnpm build
|
||||
```
|
||||
|
||||
### Loading in Logseq
|
||||
|
||||
1. Open Logseq Desktop
|
||||
2. Enable **Developer mode** in Settings
|
||||
3. Press `t p` to open Plugins dashboard
|
||||
4. Click **Load unpacked plugin**
|
||||
5. Select your plugin directory
|
||||
|
||||
### Debugging
|
||||
|
||||
- Use browser DevTools (Ctrl/Cmd + Shift + I)
|
||||
- Check console for `@logseq/libs` debug output
|
||||
- Use `logseq.UI.showMsg()` for quick debugging
|
||||
|
||||
## Best Practices
|
||||
|
||||
### Performance
|
||||
|
||||
1. **Debounce frequent operations** - especially DB queries and UI updates
|
||||
2. **Use `onBlockChanged` sparingly** - it fires on every edit
|
||||
3. **Batch block operations** - use `insertBatchBlock` instead of multiple `insertBlock` calls
|
||||
4. **Clean up listeners** - store and call off-hooks in `beforeunload`
|
||||
|
||||
```typescript
|
||||
const offHooks: (() => void)[] = []
|
||||
|
||||
offHooks.push(
|
||||
logseq.DB.onChanged(() => { /* ... */ })
|
||||
)
|
||||
|
||||
logseq.beforeunload(async () => {
|
||||
offHooks.forEach(off => off())
|
||||
})
|
||||
```
|
||||
|
||||
### Error Handling
|
||||
|
||||
```typescript
|
||||
try {
|
||||
const block = await logseq.Editor.getBlock(uuid)
|
||||
if (!block) {
|
||||
await logseq.UI.showMsg('Block not found', 'warning')
|
||||
return
|
||||
}
|
||||
// ... proceed
|
||||
} catch (error) {
|
||||
console.error('Plugin error:', error)
|
||||
await logseq.UI.showMsg('An error occurred', 'error')
|
||||
}
|
||||
```
|
||||
|
||||
### CSS Variables
|
||||
|
||||
Use Logseq's CSS custom properties for consistent theming:
|
||||
|
||||
```css
|
||||
.my-plugin-ui {
|
||||
color: var(--ls-primary-text-color);
|
||||
background: var(--ls-primary-background-color);
|
||||
border: 1px solid var(--ls-border-color);
|
||||
}
|
||||
```
|
||||
|
||||
### DB vs File Graphs
|
||||
|
||||
Check graph type before using DB-specific features:
|
||||
|
||||
```typescript
|
||||
const isDbGraph = await logseq.App.checkCurrentIsDbGraph()
|
||||
if (isDbGraph) {
|
||||
// Use DB-specific APIs
|
||||
await logseq.Editor.upsertProperty('my-prop', { type: 'string' })
|
||||
}
|
||||
```
|
||||
|
||||
## Resources
|
||||
|
||||
- **API Documentation**: https://plugins-doc.logseq.com
|
||||
- **Plugin Samples**: https://github.com/logseq/logseq-plugin-samples
|
||||
- **SDK Source**: https://github.com/logseq/logseq/tree/master/libs
|
||||
- **NPM Package**: https://www.npmjs.com/package/@logseq/libs
|
||||
- **Discord Community**: https://discord.gg/KpN4eHY
|
||||
- **Community Templates**:
|
||||
- ClojureScript: https://github.com/logseq/cljs-plugin-example
|
||||
- TypeScript: https://github.com/YU000jp/logseq-plugin-sample-kit-typescript
|
||||
|
||||
## Version Compatibility
|
||||
|
||||
Always check the minimum Logseq version required for specific APIs. Keep `@logseq/libs` updated to the latest version
|
||||
for best compatibility and performance.
|
||||
|
||||
```bash
|
||||
# Check current version
|
||||
npm info @logseq/libs version
|
||||
|
||||
# Update
|
||||
npm update @logseq/libs
|
||||
```
|
||||
@@ -0,0 +1,400 @@
|
||||
# `logseq.Commands` API Guide
|
||||
|
||||
## Quick start
|
||||
|
||||
```ts
|
||||
import '@logseq/libs'
|
||||
|
||||
async function main() {
|
||||
const unregister = logseq.Commands.register(
|
||||
'insert-hello',
|
||||
{
|
||||
title: 'Insert hello',
|
||||
placement: 'slash',
|
||||
},
|
||||
async () => {
|
||||
await logseq.Editor.insertAtEditingCursor('Hello from command!')
|
||||
}
|
||||
)
|
||||
|
||||
logseq.beforeunload(async () => {
|
||||
unregister && unregister()
|
||||
})
|
||||
}
|
||||
|
||||
logseq.ready(main).catch(console.error)
|
||||
```
|
||||
|
||||
## API surface
|
||||
|
||||
### `Commands.register(id, options, action?)`
|
||||
|
||||
Register a command and return an unregister handler.
|
||||
|
||||
```ts
|
||||
const unregister = logseq.Commands.register(id, options, action)
|
||||
```
|
||||
|
||||
The same command can also put its handler in `options.handler`:
|
||||
|
||||
```ts
|
||||
const unregister = logseq.Commands.register('my-command', {
|
||||
title: 'My command',
|
||||
placement: 'palette',
|
||||
handler: async () => {
|
||||
await logseq.UI.showMsg('Run')
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
Return value:
|
||||
|
||||
- `() => void`: unregister handler.
|
||||
- `false`: registration failed, usually because handler/action is missing or invalid.
|
||||
|
||||
The unregister handler is idempotent. Calling it multiple times is safe.
|
||||
|
||||
```ts
|
||||
const unregister = logseq.Commands.register('temporary-command', {
|
||||
title: 'Temporary command',
|
||||
placement: 'palette',
|
||||
handler: () => console.log('run'),
|
||||
})
|
||||
|
||||
unregister && unregister()
|
||||
unregister && unregister() // safe no-op
|
||||
```
|
||||
|
||||
### `Commands.execute(id, ...args)`
|
||||
|
||||
Execute a built-in or plugin command.
|
||||
|
||||
```ts
|
||||
await logseq.Commands.execute('logseq.go/home')
|
||||
await logseq.Commands.execute('my-plugin/some-command')
|
||||
await logseq.Commands.execute('my-plugin.commands.some-command')
|
||||
await logseq.Commands.execute('local-command')
|
||||
```
|
||||
|
||||
Supported id forms:
|
||||
|
||||
| Form | Meaning |
|
||||
| ------------------------ | ----------------------------------------------------------- |
|
||||
| `logseq.*` | Built-in command, forwarded to `App.invokeExternalCommand`. |
|
||||
| `plugin-id/key` | Command registered by another plugin. |
|
||||
| `plugin-id.commands.key` | Backward-compatible plugin command address. |
|
||||
| `key` | Command registered by the current plugin. |
|
||||
|
||||
Plugin command keys are normalized to match host registration rules:
|
||||
|
||||
- trim whitespace;
|
||||
- whitespace becomes `_`;
|
||||
- lower-case;
|
||||
- `:` becomes `-`;
|
||||
- numeric first character becomes `_1`, `_2`, etc.
|
||||
|
||||
## Register options
|
||||
|
||||
```ts
|
||||
type CommandRegisterOptions = {
|
||||
key?: string
|
||||
title?: string
|
||||
label?: string
|
||||
desc?: string
|
||||
handler?: CommandCallback | BlockCommandCallback | Array<SlashCommandAction>
|
||||
when?: string | string[]
|
||||
placement?: CommandPlacement
|
||||
placements?: CommandPlacement[]
|
||||
keybinding?: SimpleCommandKeybinding | string
|
||||
extras?: Record<string, any>
|
||||
type?: string
|
||||
palette?: boolean
|
||||
}
|
||||
```
|
||||
|
||||
Important fields:
|
||||
|
||||
- `key`: stable command key. Defaults to `id`.
|
||||
- `title`: display title. `label` is also accepted for compatibility.
|
||||
- `desc`: command palette description. Defaults to title/label in host palette rendering.
|
||||
- `handler`: command callback. Can be passed here or as third argument.
|
||||
- `placement`: single UI surface.
|
||||
- `placements`: multiple UI surfaces for one logical command.
|
||||
- `keybinding`: string or `{ mode, binding, mac }` shortcut descriptor.
|
||||
- `when`: v1 stores this as metadata for future host-side condition evaluation.
|
||||
- `extras`: placement-specific metadata, e.g. PDF highlight menu options.
|
||||
|
||||
## Placements
|
||||
|
||||
```ts
|
||||
type CommandPlacement =
|
||||
| 'palette'
|
||||
| 'shortcut'
|
||||
| 'slash'
|
||||
| 'block-context-menu'
|
||||
| 'highlight-context-menu'
|
||||
| 'page-menu'
|
||||
| 'simple'
|
||||
```
|
||||
|
||||
### `palette`
|
||||
|
||||
Register a command palette item.
|
||||
|
||||
```ts
|
||||
const unregister = logseq.Commands.register(
|
||||
'open-dashboard',
|
||||
{
|
||||
title: 'Open dashboard',
|
||||
placement: 'palette',
|
||||
},
|
||||
async () => {
|
||||
logseq.showMainUI()
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
### `shortcut`
|
||||
|
||||
Register a keyboard shortcut without necessarily showing it in the command palette.
|
||||
|
||||
```ts
|
||||
const unregister = logseq.Commands.register(
|
||||
'toggle-panel',
|
||||
{
|
||||
title: 'Toggle panel',
|
||||
placement: 'shortcut',
|
||||
keybinding: {
|
||||
mode: 'global',
|
||||
binding: 'mod+shift+p',
|
||||
mac: 'cmd+shift+p',
|
||||
},
|
||||
},
|
||||
() => {
|
||||
logseq.toggleMainUI()
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
Shortcut modes:
|
||||
|
||||
| Mode | Meaning |
|
||||
| ------------- | -------------------------------- |
|
||||
| `global` | Active globally. |
|
||||
| `non-editing` | Active when not editing a block. |
|
||||
| `editing` | Active when editing a block. |
|
||||
|
||||
### `slash`
|
||||
|
||||
Register a slash command.
|
||||
|
||||
```ts
|
||||
const unregister = logseq.Commands.register(
|
||||
'insert-current-date',
|
||||
{
|
||||
title: 'Insert current date',
|
||||
placement: 'slash',
|
||||
},
|
||||
async () => {
|
||||
await logseq.Editor.insertAtEditingCursor(
|
||||
new Date().toISOString().slice(0, 10)
|
||||
)
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
Slash commands also support the legacy action-step form:
|
||||
|
||||
```ts
|
||||
const unregister = logseq.Commands.register(
|
||||
'big-bang',
|
||||
{ title: 'Big Bang', placement: 'slash' },
|
||||
[['editor/input', 'Hello'], ['editor/clear-current-slash']]
|
||||
)
|
||||
```
|
||||
|
||||
### `block-context-menu`
|
||||
|
||||
Register a block context menu item.
|
||||
|
||||
```ts
|
||||
const unregister = logseq.Commands.register(
|
||||
'copy-block-uuid',
|
||||
{
|
||||
title: 'Copy block UUID',
|
||||
placement: 'block-context-menu',
|
||||
},
|
||||
async ({ uuid }) => {
|
||||
await navigator.clipboard.writeText(uuid)
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
### `page-menu`
|
||||
|
||||
Register a page menu item.
|
||||
|
||||
```ts
|
||||
const unregister = logseq.Commands.register(
|
||||
'analyze-page',
|
||||
{
|
||||
title: 'Analyze page',
|
||||
placement: 'page-menu',
|
||||
},
|
||||
async ({ page }) => {
|
||||
console.log('Analyze page', page)
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
### `highlight-context-menu`
|
||||
|
||||
Register a PDF highlight context menu item.
|
||||
|
||||
```ts
|
||||
const unregister = logseq.Commands.register(
|
||||
'send-highlight-to-inbox',
|
||||
{
|
||||
title: 'Send highlight to inbox',
|
||||
placement: 'highlight-context-menu',
|
||||
extras: { clearSelection: true },
|
||||
},
|
||||
async ({ content }) => {
|
||||
await logseq.Editor.appendBlockInPage('Inbox', content)
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
### `simple`
|
||||
|
||||
Register a command without visible UI placement. This is useful when the command is intended to be executed by another plugin through `Commands.execute`.
|
||||
|
||||
```ts
|
||||
const unregister = logseq.Commands.register(
|
||||
'sync-now',
|
||||
{
|
||||
title: 'Sync now',
|
||||
placement: 'simple',
|
||||
},
|
||||
async () => {
|
||||
await syncNow()
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
## Multiple placements
|
||||
|
||||
Use `placements` when one logical command should appear in multiple places.
|
||||
|
||||
```ts
|
||||
const unregister = logseq.Commands.register(
|
||||
'toggle-focus-mode',
|
||||
{
|
||||
title: 'Toggle focus mode',
|
||||
placements: ['palette', 'shortcut'],
|
||||
keybinding: 'mod+shift+f',
|
||||
},
|
||||
() => {
|
||||
toggleFocusMode()
|
||||
}
|
||||
)
|
||||
|
||||
// Removes both palette and shortcut registrations.
|
||||
unregister && unregister()
|
||||
```
|
||||
|
||||
## Dynamic registration patterns
|
||||
|
||||
### Enable or disable a command from settings
|
||||
|
||||
```ts
|
||||
let unregisterExport: (() => void) | false | undefined
|
||||
|
||||
function registerExportCommand() {
|
||||
unregisterExport = logseq.Commands.register(
|
||||
'export-current-page',
|
||||
{ title: 'Export current page', placement: 'palette' },
|
||||
exportCurrentPage
|
||||
)
|
||||
}
|
||||
|
||||
function unregisterExportCommand() {
|
||||
unregisterExport && unregisterExport()
|
||||
unregisterExport = undefined
|
||||
}
|
||||
|
||||
async function main() {
|
||||
if (logseq.settings?.enableExport) registerExportCommand()
|
||||
|
||||
logseq.onSettingsChanged((next) => {
|
||||
unregisterExportCommand()
|
||||
if (next.enableExport) registerExportCommand()
|
||||
})
|
||||
|
||||
logseq.beforeunload(async () => {
|
||||
unregisterExportCommand()
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
### Register temporary commands
|
||||
|
||||
```ts
|
||||
const unregister = logseq.Commands.register(
|
||||
'temporary-review-action',
|
||||
{ title: 'Approve review item', placement: 'palette' },
|
||||
approveCurrentReviewItem
|
||||
)
|
||||
|
||||
setTimeout(() => {
|
||||
unregister && unregister()
|
||||
}, 60_000)
|
||||
```
|
||||
|
||||
## Compatibility with existing APIs
|
||||
|
||||
Old APIs remain supported. Internally, they share the same command registration path as v1 `logseq.Commands`.
|
||||
|
||||
| Existing API | Commands equivalent |
|
||||
| -------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
|
||||
| `App.registerCommandPalette({ key, label }, action)` | `Commands.register(key, { title: label, placement: 'palette' }, action)` |
|
||||
| `App.registerCommandShortcut(keybinding, action, opts)` | `Commands.register(opts.key, { ...opts, placement: 'shortcut', keybinding }, action)` |
|
||||
| `Editor.registerSlashCommand(tag, action)` | `Commands.register(tag, { title: tag, placement: 'slash' }, action)` |
|
||||
| `Editor.registerBlockContextMenuItem(label, action)` | `Commands.register(key, { title: label, placement: 'block-context-menu' }, action)` |
|
||||
| `Editor.registerHighlightContextMenuItem(label, action, opts)` | `Commands.register(key, { title: label, placement: 'highlight-context-menu', extras: opts }, action)` |
|
||||
| `App.registerPageMenuItem(tag, action)` | `Commands.register(key, { title: tag, placement: 'page-menu' }, action)` |
|
||||
|
||||
These old APIs also return unregister handlers after v1.
|
||||
|
||||
## Cleanup semantics
|
||||
|
||||
Commands are cleaned in two ways:
|
||||
|
||||
1. **Manual unregister**: call the function returned by `register`.
|
||||
2. **Plugin lifecycle cleanup**: when the plugin is disabled, reloaded, unloaded, or uninstalled, the host removes all commands registered by that plugin.
|
||||
|
||||
Manual unregister removes:
|
||||
|
||||
- local SDK hook listener;
|
||||
- simple command registry entry;
|
||||
- command palette entry;
|
||||
- shortcut registry entry;
|
||||
- slash command entry, if any.
|
||||
|
||||
Plugin lifecycle cleanup removes all commands by plugin id, including palette-only commands without shortcuts.
|
||||
|
||||
## v1 limitations
|
||||
|
||||
- `when` is metadata only. The host does not yet evaluate VSCode-like context expressions such as `editor.inCodeBlock` or `graph.isDb`.
|
||||
- `Commands.onDidExecute(listener)` is not implemented in v1.
|
||||
- Command collision handling still follows existing host behavior. Prefer stable, plugin-scoped keys.
|
||||
- `Commands.execute` works with registered plugin commands and built-in `logseq.*` commands; it is not a general RPC replacement for arbitrary plugin model methods.
|
||||
|
||||
## Best practices
|
||||
|
||||
- Use a stable `key` for commands that other plugins may call.
|
||||
- Keep `title` user-facing and concise.
|
||||
- Store unregister handlers for dynamic commands and call them before re-registering.
|
||||
- Always clean up dynamic registrations in `logseq.beforeunload`.
|
||||
- Prefer `placements` over registering the same handler several times manually.
|
||||
- Use `placement: 'simple'` for plugin-to-plugin automation commands that should not appear in UI.
|
||||
@@ -0,0 +1,594 @@
|
||||
# Custom Theme Plugin Guide
|
||||
|
||||
This guide summarizes Logseq's current UI theme architecture and gives a practical workflow for building a Logseq **theme plugin** with `@logseq/libs`.
|
||||
|
||||
It is based on the current repository structure and these theme-related entry points:
|
||||
|
||||
- CSS load order: `tailwind.all.css`
|
||||
- Design tokens and theme variables: `src/main/frontend/shui/radix.css`, `src/main/frontend/shui/radix-hsl.css`, `src/main/frontend/shui/vars-classic.css`, `src/main/frontend/shui/colors.css`
|
||||
- Shared shui/Base UI component CSS: `resources/css/shui.css`
|
||||
- CodeMirror theme bridge: `resources/css/codemirror.lsradix.css`
|
||||
- Frontend component CSS: `src/main/frontend/**/*.css`
|
||||
- Theme runtime attributes: `src/main/frontend/components/theme.cljs`, `src/main/frontend/state.cljs`, `src/main/frontend/ui.cljs`
|
||||
- Plugin theme registration/injection: `libs/src/LSPlugin.ts`, `libs/src/LSPlugin.core.ts`, `libs/src/LSPlugin.user.ts`, `libs/src/common.ts`
|
||||
|
||||
## Mental model
|
||||
|
||||
Logseq themes are mostly CSS-variable based. A theme plugin should first override the semantic variables that the app already consumes, and only then add targeted selector overrides for areas that are not fully tokenized.
|
||||
|
||||
### CSS loading order
|
||||
|
||||
The main stylesheet imports theme foundations before app component CSS:
|
||||
|
||||
1. `src/main/frontend/shui/radix.css` — color scales as `--rx-*` variables, for example `--rx-gray-01` through `--rx-gray-12` and alpha variants.
|
||||
2. `src/main/frontend/shui/radix-hsl.css` — HSL forms such as `--rx-gray-01-hsl` for Tailwind/shui tokens.
|
||||
3. `src/main/frontend/shui/vars-classic.css` — Logseq semantic variables, layout variables, default light/dark values for `data-color=logseq`.
|
||||
4. `src/main/frontend/shui/colors.css` — accent palettes selected by `html[data-color=...]`, mapping `--lx-accent-*`, `--lx-gray-*`, shui tokens, and many `--ls-*` values.
|
||||
5. `src/main/frontend/shui/index.css` — Tailwind base.
|
||||
6. `resources/css/shui.css` — shared UI components built on shui/Base UI/Tailwind tokens.
|
||||
7. Third-party CSS: Inter, PhotoSwipe, KaTeX, CodeMirror, PDF.js, Tabler, `codemirror.lsradix.css`.
|
||||
8. `src/main/frontend/**/[!_]*.css` — component and extension CSS.
|
||||
9. A selected plugin theme is injected later as a `<link rel="stylesheet">`, so it can override earlier rules when specificity is equal or higher.
|
||||
|
||||
### Runtime attributes and classes
|
||||
|
||||
Theme CSS should scope by attributes on `html` and compatibility classes on `body`:
|
||||
|
||||
| Hook | Set by | Meaning |
|
||||
| --- | --- | --- |
|
||||
| `html[data-theme="light"]` / `html[data-theme="dark"]` | `frontend.components.theme/container` | Current light/dark mode. Prefer this for theme CSS. |
|
||||
| `html.dark` | same component | Tailwind dark-mode hook. |
|
||||
| `body.light-theme`, `body.white-theme`, `body.dark-theme` | same component | Backward-compatible hooks for older custom CSS/themes. |
|
||||
| `html[data-color="logseq"]` and other colors | same component | Accent color selection. A theme plugin can override or ignore this. |
|
||||
| `html[data-font="serif"|"mono"]`, `html[data-font-global="true"]` | same component | Editor/global font preferences. Avoid fighting these unless your theme intentionally owns typography. |
|
||||
| Platform classes such as `html.is-mobile`, `html.is-electron`, `html.is-mac`, `html.is-native-iphone` | `frontend.ui/inject-document-devices-envs!` | Useful for responsive/mobile-safe fixes. |
|
||||
|
||||
### Plugin theme lifecycle
|
||||
|
||||
A theme can be registered in either of two ways:
|
||||
|
||||
1. Declaratively in `package.json > logseq.themes`. During package preparation, Logseq resolves relative `url` values to plugin resources, registers each theme, and shows them in the theme selector.
|
||||
2. Programmatically with `logseq.provideTheme(theme)`. This is useful for generated themes or settings-driven variants.
|
||||
|
||||
When a user selects a theme, Logseq:
|
||||
|
||||
- removes the previously injected custom theme link;
|
||||
- injects the selected theme CSS link into `document.head`;
|
||||
- persists the selected theme separately for `light` and `dark` modes;
|
||||
- updates `:plugin/selected-theme` and emits plugin app hooks such as `:theme-changed`.
|
||||
|
||||
## Minimal theme plugin
|
||||
|
||||
### Directory layout
|
||||
|
||||
```text
|
||||
logseq-my-theme/
|
||||
├── package.json
|
||||
├── index.html
|
||||
└── themes/
|
||||
├── my-theme-light.css
|
||||
└── my-theme-dark.css
|
||||
```
|
||||
|
||||
### `package.json`
|
||||
|
||||
Use a stable lowercase-kebab `logseq.id`. For a theme-only plugin, set `effect: true` and declare each CSS file in `themes`.
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "logseq-my-theme",
|
||||
"version": "0.1.0",
|
||||
"description": "A custom Logseq theme pack",
|
||||
"license": "MIT",
|
||||
"main": "index.html",
|
||||
"logseq": {
|
||||
"id": "my-theme",
|
||||
"main": "index.html",
|
||||
"title": "My Theme",
|
||||
"icon": "./icon.png",
|
||||
"effect": true,
|
||||
"themes": [
|
||||
{
|
||||
"name": "My Theme Light",
|
||||
"url": "./themes/my-theme-light.css",
|
||||
"mode": "light",
|
||||
"description": "Light variant of My Theme"
|
||||
},
|
||||
{
|
||||
"name": "My Theme Dark",
|
||||
"url": "./themes/my-theme-dark.css",
|
||||
"mode": "dark",
|
||||
"description": "Dark variant of My Theme"
|
||||
}
|
||||
]
|
||||
},
|
||||
"devDependencies": {
|
||||
"@logseq/libs": "^0.0.17"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### `index.html`
|
||||
|
||||
Declarative themes do not need runtime code, but keeping a tiny entry file makes the plugin package explicit and easy to extend later.
|
||||
|
||||
```html
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<title>My Logseq Theme</title>
|
||||
</head>
|
||||
<body></body>
|
||||
</html>
|
||||
```
|
||||
|
||||
### Programmatic variant with `provideTheme`
|
||||
|
||||
If the theme URL or metadata is generated at runtime, use the SDK. Always wait for Logseq to be ready.
|
||||
|
||||
```ts
|
||||
import '@logseq/libs'
|
||||
|
||||
async function main() {
|
||||
logseq.provideTheme({
|
||||
name: 'My Generated Dark Theme',
|
||||
url: './themes/generated-dark.css',
|
||||
mode: 'dark',
|
||||
description: 'Generated from plugin settings',
|
||||
})
|
||||
}
|
||||
|
||||
logseq.ready(main).catch(console.error)
|
||||
```
|
||||
|
||||
## CSS strategy
|
||||
|
||||
Start with variables. Add selector overrides only for UI that cannot be changed via variables.
|
||||
|
||||
### Dark theme starter
|
||||
|
||||
```css
|
||||
/* themes/my-theme-dark.css */
|
||||
|
||||
html[data-theme="dark"] {
|
||||
color-scheme: dark;
|
||||
|
||||
/* Core backgrounds */
|
||||
--ls-primary-background-color: #111827;
|
||||
--ls-secondary-background-color: #172033;
|
||||
--ls-tertiary-background-color: #202b42;
|
||||
--ls-quaternary-background-color: #2a3650;
|
||||
--ls-table-tr-even-background-color: var(--ls-secondary-background-color);
|
||||
--ls-slide-background-color: var(--ls-primary-background-color);
|
||||
|
||||
/* Text */
|
||||
--ls-primary-text-color: #d6deeb;
|
||||
--ls-secondary-text-color: #eef2ff;
|
||||
--ls-title-text-color: #f8fafc;
|
||||
--ls-left-sidebar-text-color: #cbd5e1;
|
||||
|
||||
/* Links and refs */
|
||||
--ls-link-text-color: #7dd3fc;
|
||||
--ls-link-text-hover-color: #bae6fd;
|
||||
--ls-link-ref-text-color: var(--ls-link-text-color);
|
||||
--ls-link-ref-text-hover-color: var(--ls-link-text-hover-color);
|
||||
--ls-block-ref-link-text-color: #38bdf8;
|
||||
--ls-tag-text-color: #93c5fd;
|
||||
--ls-tag-text-hover-color: #bfdbfe;
|
||||
|
||||
/* Borders, guidelines, focus */
|
||||
--ls-border-color: #334155;
|
||||
--ls-secondary-border-color: #475569;
|
||||
--ls-tertiary-border-color: rgb(148 163 184 / 0.18);
|
||||
--ls-guideline-color: rgb(148 163 184 / 0.18);
|
||||
--ls-focus-ring-color: rgb(56 189 248 / 0.45);
|
||||
|
||||
/* Blocks and properties */
|
||||
--ls-block-properties-background-color: #1e293b;
|
||||
--ls-page-properties-background-color: #1e293b;
|
||||
--ls-block-bullet-color: #64748b;
|
||||
--ls-block-bullet-border-color: #475569;
|
||||
--ls-block-highlight-color: rgb(14 165 233 / 0.22);
|
||||
--ls-a-chosen-bg: rgb(56 189 248 / 0.16);
|
||||
--ls-menu-hover-color: var(--ls-a-chosen-bg);
|
||||
|
||||
/* Selection, checkbox, quote, mark, inline code */
|
||||
--ls-selection-background-color: rgb(56 189 248 / 0.32);
|
||||
--ls-selection-text-color: #f8fafc;
|
||||
--ls-page-checkbox-color: #64748b;
|
||||
--ls-page-checkbox-border-color: #475569;
|
||||
--ls-page-blockquote-color: var(--ls-primary-text-color);
|
||||
--ls-page-blockquote-bg-color: #172033;
|
||||
--ls-page-blockquote-border-color: #38bdf8;
|
||||
--ls-page-mark-color: #111827;
|
||||
--ls-page-mark-bg-color: #fde68a;
|
||||
--ls-page-inline-code-color: #e0f2fe;
|
||||
--ls-page-inline-code-bg-color: #0f172a;
|
||||
|
||||
/* Scrollbars and notifications */
|
||||
--ls-scrollbar-foreground-color: rgb(148 163 184 / 0.35);
|
||||
--ls-scrollbar-background-color: rgb(15 23 42 / 0.35);
|
||||
--ls-scrollbar-thumb-hover-color: rgb(148 163 184 / 0.55);
|
||||
--ls-notification-background: #1e293b;
|
||||
--ls-notification-text-color: #f8fafc;
|
||||
|
||||
/* shui/Tailwind HSL tokens: use space-separated HSL channels, not hsl(). */
|
||||
--background: 222 47% 11%;
|
||||
--foreground: 210 40% 96%;
|
||||
--card: 222 47% 13%;
|
||||
--card-foreground: 210 40% 96%;
|
||||
--popover: 222 47% 10%;
|
||||
--popover-foreground: 210 40% 96%;
|
||||
--primary: 199 89% 48%;
|
||||
--primary-foreground: 210 40% 98%;
|
||||
--secondary: 217 33% 18%;
|
||||
--secondary-foreground: 210 40% 96%;
|
||||
--muted: 217 33% 16%;
|
||||
--border: 217 33% 24%;
|
||||
--input: 217 33% 24%;
|
||||
--ring: 199 89% 48%;
|
||||
--accent: 199 89% 48%;
|
||||
--accent-foreground: 210 40% 98%;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] body {
|
||||
background: var(--ls-primary-background-color);
|
||||
color: var(--ls-primary-text-color);
|
||||
}
|
||||
|
||||
html[data-theme="dark"] ::selection {
|
||||
background: var(--ls-selection-background-color);
|
||||
color: var(--ls-selection-text-color);
|
||||
}
|
||||
```
|
||||
|
||||
### Light theme starter
|
||||
|
||||
```css
|
||||
/* themes/my-theme-light.css */
|
||||
|
||||
html[data-theme="light"] {
|
||||
color-scheme: light;
|
||||
|
||||
--ls-primary-background-color: #ffffff;
|
||||
--ls-secondary-background-color: #f8fafc;
|
||||
--ls-tertiary-background-color: #eef2f7;
|
||||
--ls-quaternary-background-color: #e2e8f0;
|
||||
|
||||
--ls-primary-text-color: #1e293b;
|
||||
--ls-secondary-text-color: #0f172a;
|
||||
--ls-title-text-color: #0f172a;
|
||||
--ls-left-sidebar-text-color: #334155;
|
||||
|
||||
--ls-link-text-color: #0369a1;
|
||||
--ls-link-text-hover-color: #075985;
|
||||
--ls-link-ref-text-color: var(--ls-link-text-color);
|
||||
--ls-link-ref-text-hover-color: var(--ls-link-text-hover-color);
|
||||
--ls-block-ref-link-text-color: #0284c7;
|
||||
--ls-tag-text-color: #0369a1;
|
||||
--ls-tag-text-hover-color: #075985;
|
||||
|
||||
--ls-border-color: #cbd5e1;
|
||||
--ls-secondary-border-color: #e2e8f0;
|
||||
--ls-tertiary-border-color: rgb(15 23 42 / 0.08);
|
||||
--ls-guideline-color: rgb(15 23 42 / 0.08);
|
||||
--ls-focus-ring-color: rgb(14 165 233 / 0.35);
|
||||
|
||||
--ls-block-properties-background-color: #f1f5f9;
|
||||
--ls-page-properties-background-color: #f1f5f9;
|
||||
--ls-block-bullet-color: #94a3b8;
|
||||
--ls-block-bullet-border-color: #cbd5e1;
|
||||
--ls-block-highlight-color: #e0f2fe;
|
||||
--ls-a-chosen-bg: #e0f2fe;
|
||||
--ls-menu-hover-color: var(--ls-a-chosen-bg);
|
||||
|
||||
--ls-selection-background-color: #dbeafe;
|
||||
--ls-selection-text-color: #0f172a;
|
||||
--ls-page-checkbox-color: #94a3b8;
|
||||
--ls-page-checkbox-border-color: #94a3b8;
|
||||
--ls-page-blockquote-color: var(--ls-primary-text-color);
|
||||
--ls-page-blockquote-bg-color: #f8fafc;
|
||||
--ls-page-blockquote-border-color: #38bdf8;
|
||||
--ls-page-mark-color: #0f172a;
|
||||
--ls-page-mark-bg-color: #fef3c7;
|
||||
--ls-page-inline-code-color: #0f172a;
|
||||
--ls-page-inline-code-bg-color: #f1f5f9;
|
||||
|
||||
--ls-scrollbar-foreground-color: rgb(15 23 42 / 0.12);
|
||||
--ls-scrollbar-background-color: rgb(15 23 42 / 0.05);
|
||||
--ls-scrollbar-thumb-hover-color: rgb(15 23 42 / 0.22);
|
||||
|
||||
--background: 0 0% 100%;
|
||||
--foreground: 222 47% 11%;
|
||||
--card: 0 0% 100%;
|
||||
--card-foreground: 222 47% 11%;
|
||||
--popover: 0 0% 100%;
|
||||
--popover-foreground: 222 47% 11%;
|
||||
--primary: 199 89% 40%;
|
||||
--primary-foreground: 0 0% 100%;
|
||||
--secondary: 210 40% 96%;
|
||||
--secondary-foreground: 222 47% 11%;
|
||||
--muted: 210 40% 96%;
|
||||
--border: 214 32% 91%;
|
||||
--input: 214 32% 91%;
|
||||
--ring: 199 89% 40%;
|
||||
--accent: 199 89% 40%;
|
||||
--accent-foreground: 0 0% 100%;
|
||||
}
|
||||
```
|
||||
|
||||
## Important variable groups
|
||||
|
||||
Prefer these variables before reaching for selectors.
|
||||
|
||||
### Global layout and typography
|
||||
|
||||
| Variable | Purpose |
|
||||
| --- | --- |
|
||||
| `--ls-page-text-size` | Base page text size under `#root`. |
|
||||
| `--ls-page-title-size` | Page title size. Mobile may override title layout. |
|
||||
| `--ls-main-content-max-width`, `--ls-main-content-max-width-wide` | Main content width. |
|
||||
| `--ls-font-family` | Global app font when not overridden by user font settings. |
|
||||
| `--ls-scrollbar-width` | Custom scrollbar width. |
|
||||
| `--ls-border-radius-low`, `--ls-border-radius-medium` | Classic radius tokens. |
|
||||
| `--ls-headbar-height`, `--ls-headbar-inner-top-padding` | Header sizing. |
|
||||
| `--ls-left-sidebar-width`, `--ls-left-sidebar-sm-width`, `--ls-left-sidebar-nav-btn-size` | Left sidebar sizing. |
|
||||
|
||||
### Logseq semantic colors
|
||||
|
||||
| Variable | Purpose |
|
||||
| --- | --- |
|
||||
| `--ls-primary-background-color` | Main background. |
|
||||
| `--ls-secondary-background-color` | Secondary surfaces, editors, menus. |
|
||||
| `--ls-tertiary-background-color` | Nested/raised surfaces. |
|
||||
| `--ls-quaternary-background-color` | Active/hover surfaces. |
|
||||
| `--ls-primary-text-color`, `--ls-secondary-text-color`, `--ls-title-text-color` | Body, stronger text, titles. |
|
||||
| `--ls-border-color`, `--ls-secondary-border-color`, `--ls-tertiary-border-color` | Borders. |
|
||||
| `--ls-guideline-color` | Block indentation guide lines. |
|
||||
| `--ls-active-primary-color`, `--ls-active-secondary-color` | Active states. |
|
||||
| `--ls-a-chosen-bg`, `--ls-menu-hover-color` | Chosen menu/list item backgrounds. |
|
||||
| `--ls-focus-ring-color` | Focus rings. |
|
||||
|
||||
### Links, references, tags, and blocks
|
||||
|
||||
| Variable | Purpose |
|
||||
| --- | --- |
|
||||
| `--ls-link-text-color`, `--ls-link-text-hover-color` | General links. |
|
||||
| `--ls-link-ref-text-color`, `--ls-link-ref-text-hover-color` | Page references. |
|
||||
| `--ls-block-ref-link-text-color` | Block references. |
|
||||
| `--ls-tag-text-color`, `--ls-tag-text-hover-color`, `--ls-tag-text-opacity`, `--ls-tag-text-hover-opacity` | Tags. |
|
||||
| `--ls-block-bullet-color`, `--ls-block-bullet-border-color`, `--ls-block-bullet-active-color` | Block bullets. |
|
||||
| `--ls-block-highlight-color` | Block highlight. |
|
||||
| `--ls-block-properties-background-color`, `--ls-page-properties-background-color` | Property panels. |
|
||||
|
||||
### Content tokens
|
||||
|
||||
| Variable | Purpose |
|
||||
| --- | --- |
|
||||
| `--ls-selection-background-color`, `--ls-selection-text-color` | Text selection. |
|
||||
| `--ls-page-checkbox-color`, `--ls-page-checkbox-border-color` | Markdown task checkboxes/radios. |
|
||||
| `--ls-page-blockquote-color`, `--ls-page-blockquote-bg-color`, `--ls-page-blockquote-border-color` | Blockquotes. |
|
||||
| `--ls-page-mark-color`, `--ls-page-mark-bg-color` | Highlight/mark text. |
|
||||
| `--ls-page-inline-code-color`, `--ls-page-inline-code-bg-color` | Inline code. |
|
||||
| `--ls-table-tr-even-background-color` | Alternating table rows. |
|
||||
| `--ls-cloze-text-color` | Cloze text. |
|
||||
| `--ls-slide-background-color` | Slide mode background. |
|
||||
|
||||
### shui/Tailwind HSL tokens
|
||||
|
||||
Newer shared UI components use HSL channel tokens, often through Tailwind classes such as `bg-background`, `bg-popover`, `border`, `text-foreground`, and `bg-primary`.
|
||||
|
||||
Set these as space-separated HSL channels:
|
||||
|
||||
```css
|
||||
html[data-theme="dark"] {
|
||||
--background: 222 47% 11%;
|
||||
--foreground: 210 40% 96%;
|
||||
--card: 222 47% 13%;
|
||||
--card-foreground: 210 40% 96%;
|
||||
--popover: 222 47% 10%;
|
||||
--popover-foreground: 210 40% 96%;
|
||||
--primary: 199 89% 48%;
|
||||
--primary-foreground: 210 40% 98%;
|
||||
--secondary: 217 33% 18%;
|
||||
--secondary-foreground: 210 40% 96%;
|
||||
--muted: 217 33% 16%;
|
||||
--border: 217 33% 24%;
|
||||
--input: 217 33% 24%;
|
||||
--ring: 199 89% 48%;
|
||||
--accent: 199 89% 48%;
|
||||
--accent-foreground: 210 40% 98%;
|
||||
}
|
||||
```
|
||||
|
||||
Do not write `--primary: hsl(199 89% 48%)`; consumers call `hsl(var(--primary))`.
|
||||
|
||||
### `--lx-*` and `--rx-*` color scales
|
||||
|
||||
- `--rx-*` variables are Radix-style raw palettes. They are broad and already available.
|
||||
- `--lx-gray-01` through `--lx-gray-12` and `--lx-gray-*-alpha` represent the active neutral scale.
|
||||
- `--lx-accent-01` through `--lx-accent-12` and `--lx-accent-*-alpha` represent the active accent scale.
|
||||
|
||||
If your theme is a complete palette, map `--lx-gray-*` and `--lx-accent-*` as well as `--ls-*`. This makes Radix/shui-heavy UI more consistent:
|
||||
|
||||
```css
|
||||
html[data-theme="dark"] {
|
||||
--lx-gray-01: #0f172a;
|
||||
--lx-gray-02: #111827;
|
||||
--lx-gray-03: #1e293b;
|
||||
--lx-gray-04: #273449;
|
||||
--lx-gray-05: #334155;
|
||||
--lx-gray-06: #475569;
|
||||
--lx-gray-07: #64748b;
|
||||
--lx-gray-08: #94a3b8;
|
||||
--lx-gray-09: #cbd5e1;
|
||||
--lx-gray-10: #dbeafe;
|
||||
--lx-gray-11: #e2e8f0;
|
||||
--lx-gray-12: #f8fafc;
|
||||
|
||||
--lx-accent-09: #0ea5e9;
|
||||
--lx-accent-10: #0284c7;
|
||||
--lx-accent-11: #38bdf8;
|
||||
--lx-accent-12: #e0f2fe;
|
||||
}
|
||||
```
|
||||
|
||||
## UI selector map
|
||||
|
||||
Use this as a last-mile map after variables. Keep overrides narrow and prefer `:where(...)` to avoid specificity wars.
|
||||
|
||||
### App shell and layout
|
||||
|
||||
| Area | Useful selectors | Notes |
|
||||
| --- | --- | --- |
|
||||
| Root/app | `#root`, `#app-container`, `#root-container.theme-container`, `main.theme-container-inner` | `#root` uses `--ls-page-text-size`; `main.theme-container-inner` defines `--left-sidebar-bg-color`. |
|
||||
| Main content | `#main-container`, `#main-content`, `#main-content-container`, `.page-blocks-inner` | Avoid hard-coded viewport hacks; test desktop and mobile. |
|
||||
| Header | `.cp__header`, `.head`, `.button`, `.ui__button` | Mostly tokenized through shui/Tailwind variables. |
|
||||
| Left sidebar | `.left-sidebar-inner`, `.sidebar-header-container`, `.sidebar-contents-container`, `.sidebar-content-group`, `.sidebar-navigations` | Prefer `--left-sidebar-bg-color`, `--ls-left-sidebar-text-color`, and `--ls-left-sidebar-width`. |
|
||||
| Right sidebar | `#right-sidebar`, `.cp__right-sidebar-inner`, `.sidebar-item`, `.references-blocks-item` | Nested reference cards may need extra contrast. |
|
||||
|
||||
### Pages, blocks, and editor
|
||||
|
||||
| Area | Useful selectors | Notes |
|
||||
| --- | --- | --- |
|
||||
| Page title | `.ls-page-title`, `.page-title`, `.journal-title`, `.page-title-sizer-wrapper` | Prefer `--ls-page-title-size` and title text variables. |
|
||||
| Blocks | `.ls-block`, `.block-main-container`, `.block-content-wrapper`, `.block-content`, `.block-body` | Avoid altering core layout unless necessary. |
|
||||
| Block tree guides | `.block-children-container`, `.block-children`, `.block-children-left-border` | Governed by `--ls-guideline-color` and related border variables. |
|
||||
| Bullets/control | `.block-control-wrap`, `.block-control`, `.bullet-container`, `.bullet-link-wrap` | Governed by bullet variables; keep hit areas accessible. |
|
||||
| Page refs | `.page-ref`, `.page-reference`, `.breadcrumb` | Use link/reference variables first. |
|
||||
| Block refs | `.block-ref`, `.block-ref-no-title`, `.open-block-ref-link` | Use `--ls-block-ref-link-text-color`, property surface variables. |
|
||||
| Properties | `.block-properties`, `.page-properties`, `.property-value-inner`, `.property-key` | Use property background variables. |
|
||||
| Editor textarea | `.editor-inner textarea`, `.edit-input`, `.non-block-editor textarea` | Background usually comes from `--ls-secondary-background-color`. |
|
||||
| Autocomplete/slash popup | `#ui__ac-inner`, `.menu-link`, `.absolute-modal[data-modal-name]`, `.cp__commands-slash` | Use menu hover and popover tokens. |
|
||||
|
||||
### Shared UI, dialogs, command palette
|
||||
|
||||
| Area | Useful selectors | Notes |
|
||||
| --- | --- | --- |
|
||||
| Buttons | `.ui__button`, `.button`, `.ui__toggle`, `.ui__toggle-background-on`, `.ui__toggle-background-off` | Set `--primary`, `--primary-foreground`, `--accent`, `--ring`. |
|
||||
| Dialogs/modals | `.ui__modal`, `.ui__modal-panel`, `.ui__dialog-overlay`, `.ui__dialog-content`, `.ui__alert-dialog-content` | `--ls-modal-overlay-gradient-start/end` can control modal overlays. |
|
||||
| Dropdowns/popovers | `.ui__dropdown-menu-content`, `.ui__popover-content`, `div[data-radix-menu-content]`, `div[data-radix-popper-content-wrapper]` | Usually driven by `--popover`, `--border`, `--accent`, `--lx-popover-bg`. |
|
||||
| Select/calendar | `.ui__select-content`, `.ui__calendar`, `.rc-datepicker` | shui tokens and `--accent` matter. |
|
||||
| Notifications | `.ui__notifications .notification-area` | Use `--ls-notification-background`, `--ls-notification-text-color`. |
|
||||
| Command palette | `.cp__cmdk` | Border and hint colors use `--ls-border-color`, `--lx-gray-*`, `--accent`. |
|
||||
| Context menu | `#custom-context-menu`, `.ls-context-menu-content`, `.menu-links-wrapper` | Popover/menu variables usually cover it. |
|
||||
|
||||
### Extensions and special surfaces
|
||||
|
||||
| Area | Useful selectors/variables | Notes |
|
||||
| --- | --- | --- |
|
||||
| CodeMirror | `.cm-s-lsradix`, `.cm-s-lsradix.cm-s-dark`, `.cm-s-lsradix.cm-s-light`, `.CodeMirror-*`, `.cm-*` | `resources/css/codemirror.lsradix.css` already bridges many `--lx-*`/`--ls-*` variables. Override only syntax colors if needed. |
|
||||
| PDF | `.extensions__pdf-container`, `.extensions__pdf-toolbar`, `.extensions__pdf-outline`, `--ph-highlight-color-*`, `--ph-link-color`, `--ph-view-container-width`, `--lx-pdf-container-dark-bg` | PDF highlight colors are `--ph-*`, not `--ls-highlight-color-*`. |
|
||||
| Graph | `.graph-layout`, `.graph-filters`, graph extension CSS under `src/main/frontend/extensions/graph.css` | Some graph styles are canvas/SVG-driven; inspect DOM before overriding. |
|
||||
| Whiteboard/tldraw | `.tl-container`, `.tl-button`, `--ls-wb-stroke-color-default`, `--ls-wb-background-color-default`, `--ls-wb-text-color-default` | Accent colors in `colors.css` set default whiteboard tokens. |
|
||||
| Tables | `.table-wrapper`, `.table-auto`, table rows | Start with `--ls-table-tr-even-background-color`, borders, text tokens. |
|
||||
| Cards/flashcards | `.ls-card`, `.ui__dialog-content[label=flashcards__cp]` | Check dialog contrast and card minimum sizes. |
|
||||
| Plugins UI | `.cp__plugins-page`, `.cp__themes-installed` | Useful when styling the installed theme picker itself. |
|
||||
|
||||
## Scoped overrides: examples
|
||||
|
||||
### Keep overrides mode-specific
|
||||
|
||||
```text
|
||||
html[data-theme="dark"] :where(.cp__right-sidebar-inner .references-blocks-item) {
|
||||
background: color-mix(in srgb, var(--ls-secondary-background-color) 88%, white 12%);
|
||||
}
|
||||
```
|
||||
|
||||
### Prefer low specificity for optional polish
|
||||
|
||||
```text
|
||||
html[data-theme="light"] :where(.page-reference:hover) {
|
||||
background: rgb(14 165 233 / 0.12);
|
||||
}
|
||||
```
|
||||
|
||||
### Avoid global resets
|
||||
|
||||
Avoid rules like this in a theme plugin:
|
||||
|
||||
```css
|
||||
/* Avoid */
|
||||
* {
|
||||
transition: all 200ms ease;
|
||||
}
|
||||
```
|
||||
|
||||
They can slow editing, affect CodeMirror/PDF.js, and break subtle interaction states.
|
||||
|
||||
## Mobile and desktop considerations
|
||||
|
||||
- Test `html.is-mobile`, `html.is-native-iphone`, `html.is-native-android`, and `html.is-electron` layouts if your theme changes spacing or header/sidebar dimensions.
|
||||
- Respect safe-area insets in mobile-specific layout. Existing CSS uses `env(safe-area-inset-*)` in some places.
|
||||
- Avoid changing `-webkit-app-region` on Electron headers/PDF toolbars unless you are fixing a drag-region issue.
|
||||
- Do not shrink block control or bullet hit areas below the existing touch-friendly sizes.
|
||||
- Avoid fixed pixel widths for the main content unless they are variables such as `--ls-main-content-max-width`.
|
||||
|
||||
## Assets and fonts
|
||||
|
||||
Prefer local assets packaged with the plugin. Relative URLs inside the selected theme CSS are resolved relative to the CSS file by the browser.
|
||||
|
||||
```css
|
||||
@font-face {
|
||||
font-family: "MyThemeText";
|
||||
src: url("../fonts/MyThemeText.woff2") format("woff2");
|
||||
font-display: swap;
|
||||
}
|
||||
|
||||
html[data-theme="dark"] {
|
||||
--ls-font-family: "MyThemeText", Inter, ui-sans-serif, system-ui, sans-serif;
|
||||
}
|
||||
```
|
||||
|
||||
Be careful with remote `@import` URLs: they can slow startup, fail offline, and leak network requests from a local-first app.
|
||||
|
||||
## Debugging workflow
|
||||
|
||||
1. Enable Logseq Developer mode.
|
||||
2. Load the unpacked theme plugin.
|
||||
3. Open DevTools and inspect `document.documentElement`:
|
||||
- `data-theme`
|
||||
- `data-color`
|
||||
- `data-font`
|
||||
- platform classes
|
||||
4. In the theme selector, choose each declared light/dark theme.
|
||||
5. Verify the selected CSS appears as a `<link rel="stylesheet">` in `document.head`.
|
||||
6. Inspect computed variables on `html`, `body`, `.theme-container`, and the specific UI area you are styling.
|
||||
7. If a variable is not taking effect, check whether the component is using `--lx-*`, shui HSL tokens, or a targeted class instead of `--ls-*`.
|
||||
|
||||
## Validation checklist
|
||||
|
||||
Before publishing a theme plugin, test at least these screens and states:
|
||||
|
||||
- [ ] Light and dark mode selection; switching between modes keeps each custom theme selection.
|
||||
- [ ] Default accent color and at least one non-default `data-color` accent.
|
||||
- [ ] Page title, journal title, normal blocks, nested blocks, block refs, page refs, tags, properties.
|
||||
- [ ] Editing state: textarea, slash command menu, autocomplete, date picker, block context menu.
|
||||
- [ ] Left sidebar, right sidebar, search, command palette, settings dialogs.
|
||||
- [ ] Notifications, confirmation dialogs, dropdowns, popovers, tooltips.
|
||||
- [ ] Code blocks / CodeMirror, inline code, marks, blockquotes, tables.
|
||||
- [ ] PDF viewer highlights and toolbar if PDF is in scope.
|
||||
- [ ] Graph and whiteboard/tldraw surfaces if your palette changes accents broadly.
|
||||
- [ ] Desktop Electron and at least one mobile/narrow viewport if the theme changes layout/spacing.
|
||||
- [ ] High contrast of text against every background; visible focus rings; visible selected/hover states.
|
||||
- [ ] Reduced-motion friendliness if you add animations.
|
||||
|
||||
## Common pitfalls
|
||||
|
||||
- Overriding only `--ls-*` while newer shui components still read `--background`, `--popover`, `--border`, `--primary`, or `--lx-*` variables.
|
||||
- Writing HSL tokens as full CSS colors instead of channel values.
|
||||
- Using high-specificity selectors or `!important` everywhere, making user custom CSS and future Logseq changes harder to coexist with.
|
||||
- Styling by generated Tailwind class names instead of stable Logseq/Radix selectors and variables.
|
||||
- Forgetting to scope a dark theme to `html[data-theme="dark"]` or a light theme to `html[data-theme="light"]`.
|
||||
- Hard-coding external font/image URLs without offline fallback.
|
||||
- Changing editor layout, block bullets, or mobile sidebars without testing touch interactions.
|
||||
|
||||
## Quick reference: priority order for theme authors
|
||||
|
||||
1. Set `--ls-*` semantic variables for Logseq-specific UI.
|
||||
2. Set shui/Tailwind HSL tokens (`--background`, `--foreground`, `--popover`, `--border`, `--primary`, etc.).
|
||||
3. Map `--lx-gray-*` and `--lx-accent-*` for newer shared UI consistency.
|
||||
4. Add extension variables such as `--ph-*` and `--ls-wb-*` only if your theme covers PDF/whiteboard.
|
||||
5. Add low-specificity, mode-scoped selector overrides for the remaining gaps.
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
# Logseq DB Properties (Developer Guide)
|
||||
|
||||
This note explains how **properties** work in Logseq when using a **DB graph** (database mode), how that differs from a **file graph** (Markdown/Org), and how to use the **plugin SDK** APIs defined in `libs/src/LSPlugin.ts`.
|
||||
|
||||
> Scope: This is written for plugin developers. It focuses on `logseq.Editor.*` property APIs and tag/class modeling.
|
||||
|
||||
---
|
||||
|
||||
## 1) Two worlds: File graph vs DB graph
|
||||
|
||||
### File graph (Markdown / Org)
|
||||
- “Properties” are primarily **text syntax** stored in the file:
|
||||
- Markdown frontmatter (`---`)
|
||||
- Org property drawers (`:PROPERTIES:`)
|
||||
- Inline props (`key:: value`)
|
||||
- When you update a property, you’re often ultimately **editing text**.
|
||||
- SDK calls like `Editor.insertBlock`/`updateBlock` have `opts.properties`, but note this warning in the typings:
|
||||
- `IBatchBlock.properties` is **not supported for DB graph**.
|
||||
|
||||
### DB graph (Database mode)
|
||||
DB mode treats properties as **first-class DB entities**.
|
||||
|
||||
Think of it as a 2-layer model:
|
||||
|
||||
1) **Property definitions (schema)**
|
||||
- A property key (e.g. `rating`, `authors`, `zotero_key`) exists as an entity.
|
||||
- It may have a schema: type, cardinality, visibility.
|
||||
|
||||
2) **Property values (data)**
|
||||
- Blocks/pages can store values for property keys.
|
||||
- Persisted structurally in the DB (not by emitting `key:: value` text).
|
||||
|
||||
In DB graphs, prefer the dedicated APIs:
|
||||
- Property schema: `Editor.getProperty / upsertProperty / removeProperty`
|
||||
- Values on blocks: `Editor.upsertBlockProperty / removeBlockProperty / getBlockProperties`
|
||||
|
||||
---
|
||||
|
||||
## 2) Important types (from `LSPlugin.ts`)
|
||||
|
||||
### `PropertySchema`
|
||||
```ts
|
||||
export type PropertySchema = {
|
||||
type: 'default' | 'number' | 'node' | 'date' | 'checkbox' | 'url' | string,
|
||||
cardinality: 'many' | 'one',
|
||||
hide: boolean
|
||||
public: boolean
|
||||
}
|
||||
```
|
||||
|
||||
Practical meaning:
|
||||
- `type`
|
||||
- Controls editor/UI behavior and (in DB graphs) how values are interpreted.
|
||||
- Common: `default`, `number`, `date`, `checkbox`, `url`, `node`.
|
||||
- `cardinality`
|
||||
- `'one'`: a single value
|
||||
- `'many'`: multiple values (typically passed as an array)
|
||||
- `hide`
|
||||
- Hide in UI property panels.
|
||||
- `public`
|
||||
- Expose property in UI (and typically configure discoverability).
|
||||
|
||||
### Entities you’ll see
|
||||
- `BlockEntity`: blocks, but also used for some “special blocks” such as property entities.
|
||||
- `PageEntity`: pages, tags (classes), property pages (`type: 'property'`), etc.
|
||||
- `BlockIdentity`: a block uuid string OR `{ uuid }`.
|
||||
|
||||
---
|
||||
|
||||
## 3) DB-only vs graph-agnostic checks
|
||||
|
||||
Before doing DB-only work, check graph type:
|
||||
|
||||
```ts
|
||||
const isDbGraph = await logseq.App.checkCurrentIsDbGraph()
|
||||
if (!isDbGraph) {
|
||||
await logseq.UI.showMsg('This feature requires a DB graph.', 'warning')
|
||||
return
|
||||
}
|
||||
|
||||
// Also check app-level capability:
|
||||
const { supportDb } = await logseq.App.getInfo()
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4) Property schema APIs (DB only)
|
||||
|
||||
### Get a property definition
|
||||
```ts
|
||||
const propEntity = await logseq.Editor.getProperty('zotero_key')
|
||||
// -> BlockEntity | null
|
||||
```
|
||||
|
||||
### Create or update a property definition (idempotent)
|
||||
Use `upsertProperty` to ensure the property exists and has the schema you expect.
|
||||
|
||||
```ts
|
||||
await logseq.Editor.upsertProperty(
|
||||
'zotero_key',
|
||||
{
|
||||
type: 'default',
|
||||
cardinality: 'one',
|
||||
hide: false,
|
||||
public: true,
|
||||
},
|
||||
{ name: 'Zotero Key' }
|
||||
)
|
||||
```
|
||||
|
||||
Notes:
|
||||
- `key` is your stable identifier (recommend `snake_case`).
|
||||
- `opts.name` can be used as a **display name** for users.
|
||||
|
||||
### Remove a property definition
|
||||
```ts
|
||||
await logseq.Editor.removeProperty('zotero_key')
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5) Block/page property value APIs
|
||||
|
||||
### Set (upsert) a property value on a block
|
||||
```ts
|
||||
const block = await logseq.Editor.getCurrentBlock()
|
||||
if (!block) return
|
||||
|
||||
await logseq.Editor.upsertBlockProperty(block.uuid, 'zotero_key', 'ABCD1234')
|
||||
```
|
||||
|
||||
### Set multi-value properties (`cardinality: 'many'`)
|
||||
For `many`, pass an array. Use `{ reset: true }` when you want to overwrite vs merge.
|
||||
|
||||
```ts
|
||||
await logseq.Editor.upsertBlockProperty(
|
||||
block.uuid,
|
||||
'authors',
|
||||
['Ada Lovelace', 'Alan Turing'],
|
||||
{ reset: true }
|
||||
)
|
||||
```
|
||||
|
||||
### Remove a value
|
||||
```ts
|
||||
await logseq.Editor.removeBlockProperty(block.uuid, 'zotero_key')
|
||||
```
|
||||
|
||||
### Read properties
|
||||
```ts
|
||||
const props = await logseq.Editor.getBlockProperties(block.uuid)
|
||||
// -> Record<string, any> | null
|
||||
|
||||
const pageProps = await logseq.Editor.getPageProperties('My Page')
|
||||
```
|
||||
|
||||
### Read a single property (returns a `BlockEntity | null`)
|
||||
`getBlockProperty` is useful when you want the DB entity wrapper for a key.
|
||||
|
||||
```ts
|
||||
const v = await logseq.Editor.getBlockProperty(block.uuid, 'zotero_key')
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6) Tags as “classes” + attaching properties (DB modeling)
|
||||
|
||||
In DB graphs, tags can behave like **classes**.
|
||||
|
||||
Relevant APIs:
|
||||
- `Editor.createTag(tagName, opts)`
|
||||
- `Editor.addTagProperty(tagId, propertyIdOrName)` / `removeTagProperty`
|
||||
- `Editor.addTagExtends(tagId, parentTagIdOrName)` / `removeTagExtends`
|
||||
- `Editor.addBlockTag(blockId, tagId)` / `removeBlockTag`
|
||||
|
||||
### Create a tag with tagProperties
|
||||
This is the most developer-friendly way to ship a “schema bundle”:
|
||||
|
||||
```ts
|
||||
const tag = await logseq.Editor.createTag('ZoteroItem', {
|
||||
tagProperties: [
|
||||
{
|
||||
name: 'zotero_key',
|
||||
schema: { type: 'default', cardinality: 'one', public: true, hide: false },
|
||||
},
|
||||
{
|
||||
name: 'authors',
|
||||
schema: { type: 'node', cardinality: 'many', public: true, hide: false },
|
||||
},
|
||||
{
|
||||
name: 'published_at',
|
||||
schema: { type: 'date', cardinality: 'one', public: true, hide: false },
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
if (tag) {
|
||||
const block = await logseq.Editor.getCurrentBlock()
|
||||
if (block) await logseq.Editor.addBlockTag(block.uuid, tag.uuid)
|
||||
}
|
||||
```
|
||||
|
||||
Why this pattern is popular:
|
||||
- Users see a consistent “record type” (`ZoteroItem`) with fields.
|
||||
- Plugins can be idempotent: create if missing, otherwise just reuse.
|
||||
|
||||
### Add properties to an existing tag later
|
||||
```ts
|
||||
const tag = await logseq.Editor.getTag('ZoteroItem')
|
||||
if (tag) {
|
||||
await logseq.Editor.addTagProperty(tag.uuid, 'zotero_key')
|
||||
await logseq.Editor.addTagProperty(tag.uuid, 'authors')
|
||||
}
|
||||
```
|
||||
|
||||
### Tag inheritance
|
||||
```ts
|
||||
await logseq.Editor.addTagExtends('ZoteroItem', 'Reference')
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7) Recommended conventions for plugin authors
|
||||
|
||||
### Prefer DB APIs over text editing in DB graphs
|
||||
- Don’t generate `key:: value` strings as your “source of truth” in DB mode.
|
||||
- Use `upsertProperty` + `upsertBlockProperty`.
|
||||
|
||||
### Keep keys stable; use display names for UX
|
||||
- Use safe keys (`snake_case`, ASCII) for `key`.
|
||||
- Use `upsertProperty(key, schema, { name })` to show a nice label.
|
||||
|
||||
### Be explicit about cardinality
|
||||
- If you intend a list, set `cardinality: 'many'` and always write arrays.
|
||||
- Use `{ reset: true }` when you want to overwrite.
|
||||
|
||||
### Guard DB-only APIs
|
||||
- Always check `App.checkCurrentIsDbGraph()`.
|
||||
|
||||
---
|
||||
|
||||
## 8) A tiny helper wrapper (optional)
|
||||
|
||||
If you’re building a small internal “DB properties SDK” for your plugin, a minimal shape looks like:
|
||||
|
||||
```ts
|
||||
export async function ensureDbGraph() {
|
||||
if (!(await logseq.App.checkCurrentIsDbGraph())) {
|
||||
throw new Error('DB graph required')
|
||||
}
|
||||
}
|
||||
|
||||
export async function ensureProperty(
|
||||
key: string,
|
||||
schema: Partial<import('../src/LSPlugin').PropertySchema>,
|
||||
name?: string
|
||||
) {
|
||||
return logseq.Editor.upsertProperty(key, schema, name ? { name } : undefined)
|
||||
}
|
||||
|
||||
export async function setProp(
|
||||
block: string,
|
||||
key: string,
|
||||
value: any,
|
||||
reset = false
|
||||
) {
|
||||
return logseq.Editor.upsertBlockProperty(block, key, value, reset ? { reset: true } : undefined)
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Appendix: API quick reference (from `LSPlugin.ts`)
|
||||
|
||||
**Property schema (DB only)**
|
||||
- `Editor.getProperty(key)`
|
||||
- `Editor.upsertProperty(key, schema?, opts?)`
|
||||
- `Editor.removeProperty(key)`
|
||||
|
||||
**Block/page values**
|
||||
- `Editor.upsertBlockProperty(block, key, value, { reset? })`
|
||||
- `Editor.removeBlockProperty(block, key)`
|
||||
- `Editor.getBlockProperty(block, key)`
|
||||
- `Editor.getBlockProperties(block)`
|
||||
- `Editor.getPageProperties(page)`
|
||||
|
||||
**Tags / Classes**
|
||||
- `Editor.createTag(tagName, { tagProperties? })`
|
||||
- `Editor.getTag(nameOrIdent)` / `Editor.getAllTags()`
|
||||
- `Editor.addTagProperty(tagId, propertyIdOrName)` / `removeTagProperty`
|
||||
- `Editor.addTagExtends(tagId, parentTagIdOrName)` / `removeTagExtends`
|
||||
- `Editor.addBlockTag(blockId, tagId)` / `removeBlockTag`
|
||||
|
||||
@@ -0,0 +1,680 @@
|
||||
# Logseq DB Properties SDK Reference
|
||||
|
||||
## Overview
|
||||
|
||||
Logseq has two storage modes:
|
||||
- **File-based**: Properties stored as `key:: value` in markdown files
|
||||
- **DB-based**: Properties stored in SQLite with structured schema, types, and relationships
|
||||
|
||||
This guide covers **DB-based properties API** for plugin development.
|
||||
|
||||
---
|
||||
|
||||
## Core Concepts
|
||||
|
||||
### 1. Property Schema (Global Definition)
|
||||
Properties must be defined globally before use. Think of it as creating columns in a database.
|
||||
|
||||
### 2. Tags as Classes
|
||||
Tags act as classes/types. Pages/blocks can be tagged to inherit property schemas.
|
||||
|
||||
### 3. Property Values
|
||||
After defining properties, assign values to specific blocks/pages.
|
||||
|
||||
---
|
||||
|
||||
## API Reference
|
||||
|
||||
### Property Schema APIs
|
||||
|
||||
#### `upsertProperty(name, schema?, opts?)`
|
||||
Define or update a property schema globally.
|
||||
|
||||
**Parameters:**
|
||||
- `name` (string): Property name
|
||||
- `schema` (optional object):
|
||||
- `type`: `'default'` | `'node'` | `'date'` | `'number'` | `'checkbox'` | `'url'`
|
||||
- `cardinality`: `'one'` | `'many'` (for `node` type)
|
||||
- `hide`: boolean - hide property in UI
|
||||
- `public`: boolean - make property public
|
||||
- `opts` (optional object):
|
||||
- `name`: string - display name override
|
||||
|
||||
**Returns:** `IEntityID` object with `id`
|
||||
|
||||
**Example:**
|
||||
```typescript
|
||||
// Simple text property
|
||||
await logseq.Editor.upsertProperty('author', { type: 'default' })
|
||||
|
||||
// Reference property (links to other pages)
|
||||
await logseq.Editor.upsertProperty('tags', {
|
||||
type: 'node',
|
||||
cardinality: 'many'
|
||||
})
|
||||
|
||||
// Hidden property with custom display name
|
||||
await logseq.Editor. upsertProperty('internalKey',
|
||||
{ type: 'default', hide: true },
|
||||
{ name: 'Internal Key' }
|
||||
)
|
||||
```
|
||||
|
||||
#### `getProperty(key)`
|
||||
Retrieve an existing property by key.
|
||||
|
||||
**Returns:** `BlockEntity` or `null`
|
||||
|
||||
**Example:**
|
||||
```typescript
|
||||
const prop = await logseq.Editor. getProperty('author')
|
||||
if (!prop) {
|
||||
await logseq.Editor.upsertProperty('author', { type: 'default' })
|
||||
}
|
||||
```
|
||||
|
||||
#### `removeProperty(key)`
|
||||
Remove a property definition globally.
|
||||
|
||||
**Example:**
|
||||
```typescript
|
||||
await logseq.Editor.removeProperty('deprecatedField')
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Tag (Class) Management APIs
|
||||
|
||||
#### `createTag(name, opts?)`
|
||||
Create a tag as a class/type definition with properties in one call.
|
||||
|
||||
**Parameters:**
|
||||
- `name` (string): Tag name
|
||||
- `opts` (optional object):
|
||||
- `uuid`: string - custom UUID
|
||||
- `tagProperties`: Array of property definitions
|
||||
- `name`: string - property name
|
||||
- `schema`: Partial<PropertySchema> - property schema
|
||||
- `properties`: object - additional properties
|
||||
|
||||
**Returns:** `PageEntity` or `null`
|
||||
|
||||
**Example:**
|
||||
```typescript
|
||||
// Simple tag
|
||||
const bookTag = await logseq.Editor.createTag('book')
|
||||
|
||||
// Tag with custom UUID
|
||||
const articleTag = await logseq.Editor.createTag('article', {
|
||||
uuid: 'custom-uuid-123'
|
||||
})
|
||||
|
||||
// Tag with properties defined in one call
|
||||
const bookTag = await logseq.Editor. createTag('book', {
|
||||
uuid: generateStableUUID('book'),
|
||||
tagProperties: [
|
||||
{
|
||||
name: 'author',
|
||||
schema: { type: 'default' }
|
||||
},
|
||||
{
|
||||
name: 'isbn',
|
||||
schema: { type: 'default' }
|
||||
},
|
||||
{
|
||||
name: 'tags',
|
||||
schema: { type: 'node', cardinality: 'many' }
|
||||
}
|
||||
]
|
||||
})
|
||||
```
|
||||
|
||||
#### `getTag(nameOrIdent)`
|
||||
Retrieve an existing tag by name or entity ID.
|
||||
|
||||
**Returns:** `PageEntity` or `null`
|
||||
|
||||
**Example:**
|
||||
```typescript
|
||||
const tag = await logseq.Editor.getTag('book')
|
||||
if (!tag) {
|
||||
// Tag doesn't exist, create it
|
||||
}
|
||||
```
|
||||
|
||||
#### `getTagsByName(tagName)`
|
||||
Retrieve all tags matching a name (useful for namespaced tags).
|
||||
|
||||
**Returns:** `Array<PageEntity>` or `null`
|
||||
|
||||
**Example:**
|
||||
```typescript
|
||||
const tags = await logseq.Editor.getTagsByName('book')
|
||||
```
|
||||
|
||||
#### `getAllTags()`
|
||||
Get all tags in the current graph.
|
||||
|
||||
**Returns:** `Array<PageEntity>` or `null`
|
||||
|
||||
**Example:**
|
||||
```typescript
|
||||
const allTags = await logseq. Editor.getAllTags()
|
||||
```
|
||||
|
||||
#### `addTagProperty(tagId, propertyIdOrName)`
|
||||
Add a property to a tag's schema. Property must be defined via `upsertProperty` first.
|
||||
|
||||
**Parameters:**
|
||||
- `tagId` (BlockIdentity): Tag UUID
|
||||
- `propertyIdOrName` (BlockIdentity): Property UUID or name
|
||||
|
||||
**Example:**
|
||||
```typescript
|
||||
// Define property globally
|
||||
await logseq.Editor. upsertProperty('author', { type: 'default' })
|
||||
|
||||
// Add to tag
|
||||
const bookTag = await logseq. Editor.createTag('book')
|
||||
await logseq.Editor. addTagProperty(bookTag.uuid, 'author')
|
||||
```
|
||||
|
||||
#### `removeTagProperty(tagId, propertyIdOrName)`
|
||||
Remove a property from a tag's schema.
|
||||
|
||||
**Example:**
|
||||
```typescript
|
||||
await logseq.Editor.removeTagProperty(bookTag.uuid, 'deprecatedField')
|
||||
```
|
||||
|
||||
#### `addTagExtends(tagId, parentTagIdOrName)`
|
||||
Set tag inheritance (class extends).
|
||||
|
||||
**Parameters:**
|
||||
- `tagId` (BlockIdentity): Child tag UUID
|
||||
- `parentTagIdOrName` (BlockIdentity): Parent tag UUID or name
|
||||
|
||||
**Example:**
|
||||
```typescript
|
||||
const mediaTag = await logseq.Editor.createTag('Media')
|
||||
const bookTag = await logseq. Editor.createTag('book')
|
||||
|
||||
// book extends Media
|
||||
await logseq.Editor. addTagExtends(bookTag. uuid, mediaTag.uuid)
|
||||
```
|
||||
|
||||
#### `removeTagExtends(tagId, parentTagIdOrName)`
|
||||
Remove tag inheritance.
|
||||
|
||||
**Example:**
|
||||
```typescript
|
||||
await logseq.Editor.removeTagExtends(bookTag.uuid, mediaTag.uuid)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Block/Page Tagging APIs
|
||||
|
||||
#### `addBlockTag(blockId, tagId)`
|
||||
Tag a block or page, making it an instance of that tag's class.
|
||||
|
||||
**Parameters:**
|
||||
- `blockId` (BlockIdentity): Block or page UUID
|
||||
- `tagId` (BlockIdentity): Tag UUID
|
||||
|
||||
**Example:**
|
||||
```typescript
|
||||
const page = await logseq.Editor. createPage('Moby Dick')
|
||||
const bookTag = await logseq.Editor.getTag('book')
|
||||
await logseq.Editor.addBlockTag(page.uuid, bookTag.uuid)
|
||||
```
|
||||
|
||||
#### `removeBlockTag(blockId, tagId)`
|
||||
Remove a tag from a block or page.
|
||||
|
||||
**Example:**
|
||||
```typescript
|
||||
await logseq.Editor.removeBlockTag(page.uuid, bookTag.uuid)
|
||||
```
|
||||
|
||||
#### `getTagObjects(nameOrIdent)`
|
||||
Get all blocks/pages tagged with a specific tag.
|
||||
|
||||
**Returns:** `Array<BlockEntity>` or `null`
|
||||
|
||||
**Example:**
|
||||
```typescript
|
||||
const allBooks = await logseq.Editor.getTagObjects('book')
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Block/Page Property Value APIs
|
||||
|
||||
#### `upsertBlockProperty(blockUUID, key, value, options?)`
|
||||
Set property value for a specific block or page.
|
||||
|
||||
**Parameters:**
|
||||
- `blockUUID` (BlockIdentity | EntityID): Block or page UUID or entity ID
|
||||
- `key` (string): Property name
|
||||
- `value` (any): Property value
|
||||
- For `node` type with `cardinality: 'many'`: Use array of page IDs (`.id` not `.uuid`)
|
||||
- For `node` type with `cardinality: 'one'`: Use single page ID
|
||||
- For other types: Use primitive values
|
||||
- `options` (optional object):
|
||||
- `reset`: boolean - replace instead of merge
|
||||
|
||||
**Example:**
|
||||
```typescript
|
||||
const page = await logseq.Editor.getPage('my-page-uuid')
|
||||
|
||||
// Set simple value
|
||||
await logseq.Editor.upsertBlockProperty(page.uuid, 'author', 'John Doe')
|
||||
|
||||
// Set number
|
||||
await logseq.Editor.upsertBlockProperty(page.uuid, 'year', 2024)
|
||||
|
||||
// Set single reference (use . id not .uuid)
|
||||
await logseq.Editor.upsertBlockProperty(page.uuid, 'category', categoryPage.id)
|
||||
|
||||
// Set multiple references (use . id not .uuid)
|
||||
await logseq.Editor.upsertBlockProperty(
|
||||
page.uuid,
|
||||
'tags',
|
||||
[tagPage1.id, tagPage2.id, tagPage3.id]
|
||||
)
|
||||
|
||||
// Reset property value completely
|
||||
await logseq.Editor. upsertBlockProperty(
|
||||
page.uuid,
|
||||
'tags',
|
||||
[newTag1.id],
|
||||
{ reset: true }
|
||||
)
|
||||
```
|
||||
|
||||
#### `getBlockProperty(blockId, key)`
|
||||
Get a single property value from a block or page.
|
||||
|
||||
**Returns:** `BlockEntity` or `null`
|
||||
|
||||
**Example:**
|
||||
```typescript
|
||||
const author = await logseq.Editor. getBlockProperty(page.uuid, 'author')
|
||||
```
|
||||
|
||||
#### `getBlockProperties(blockId)`
|
||||
Get all properties from a block.
|
||||
|
||||
**Returns:** `Record<string, any>` or `null`
|
||||
|
||||
**Example:**
|
||||
```typescript
|
||||
const props = await logseq.Editor. getBlockProperties(page.uuid)
|
||||
console.log(props. author, props.isbn)
|
||||
```
|
||||
|
||||
#### `getPageProperties(pageId)`
|
||||
Get all properties from a page.
|
||||
|
||||
**Returns:** `Record<string, any>` or `null`
|
||||
|
||||
**Example:**
|
||||
```typescript
|
||||
const props = await logseq.Editor.getPageProperties(page.uuid)
|
||||
```
|
||||
|
||||
#### `removeBlockProperty(blockId, key)`
|
||||
Remove a property from a block or page.
|
||||
|
||||
**Example:**
|
||||
```typescript
|
||||
await logseq.Editor.removeBlockProperty(page.uuid, 'deprecatedField')
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Special Properties & Utilities
|
||||
|
||||
#### Hide Empty Values
|
||||
Use special property key `:logseq. property/hide-empty-value`:
|
||||
|
||||
```typescript
|
||||
const prop = await logseq.Editor.upsertProperty('optionalField', { type: 'default' })
|
||||
await logseq.Editor.upsertBlockProperty(
|
||||
prop.id, // Use property's entity ID
|
||||
': logseq.property/hide-empty-value',
|
||||
true
|
||||
)
|
||||
```
|
||||
|
||||
#### Set Block Icon
|
||||
```typescript
|
||||
// Tabler icon
|
||||
await logseq.Editor.setBlockIcon(blockId, 'tabler-icon', 'book')
|
||||
|
||||
// Emoji (from emoji-mart)
|
||||
await logseq.Editor.setBlockIcon(blockId, 'emoji', 'books')
|
||||
```
|
||||
|
||||
#### Remove Block Icon
|
||||
```typescript
|
||||
await logseq.Editor.removeBlockIcon(blockId)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Common Patterns
|
||||
|
||||
### Pattern 1: Define Schema with Tag and Properties (Simple)
|
||||
|
||||
```typescript
|
||||
async function setupBookSchema() {
|
||||
// Create tag with all properties in one call
|
||||
const bookTag = await logseq.Editor.createTag('book', {
|
||||
uuid: generateStableUUID('book'),
|
||||
tagProperties: [
|
||||
{ name: 'title', schema: { type: 'default' } },
|
||||
{ name: 'author', schema: { type: 'default' } },
|
||||
{ name: 'isbn', schema: { type: 'default' } },
|
||||
{ name: 'year', schema: { type: 'number' } },
|
||||
{ name: 'tags', schema: { type: 'node', cardinality: 'many' } }
|
||||
]
|
||||
})
|
||||
|
||||
return bookTag
|
||||
}
|
||||
```
|
||||
|
||||
### Pattern 2: Define Schema with Inheritance
|
||||
|
||||
```typescript
|
||||
async function setupSchemaWithInheritance() {
|
||||
// 1. Create parent tag
|
||||
const mediaTag = await logseq.Editor.createTag('Media', {
|
||||
tagProperties: [
|
||||
{ name: 'title', schema: { type: 'default' } },
|
||||
{ name: 'year', schema: { type: 'number' } },
|
||||
{ name: 'tags', schema: { type: 'node', cardinality: 'many' } }
|
||||
]
|
||||
})
|
||||
|
||||
// 2. Create child tag with specific properties
|
||||
const bookTag = await logseq.Editor.createTag('book', {
|
||||
tagProperties: [
|
||||
{ name: 'author', schema: { type: 'default' } },
|
||||
{ name: 'isbn', schema: { type: 'default' } }
|
||||
]
|
||||
})
|
||||
|
||||
// 3. Set inheritance
|
||||
await logseq. Editor.addTagExtends(bookTag.uuid, mediaTag.uuid)
|
||||
|
||||
return { mediaTag, bookTag }
|
||||
}
|
||||
```
|
||||
|
||||
### Pattern 3: Create Instance with Properties
|
||||
|
||||
```typescript
|
||||
async function createBookInstance(bookData) {
|
||||
// 1. Create page with stable UUID
|
||||
const pageUUID = generateStableUUID(bookData.id)
|
||||
let page = await logseq.Editor.getPage(pageUUID)
|
||||
|
||||
if (!page) {
|
||||
page = await logseq.Editor. createPage(
|
||||
bookData.title,
|
||||
{},
|
||||
{ customUUID: pageUUID, redirect: false }
|
||||
)
|
||||
}
|
||||
|
||||
// 2. Tag the page
|
||||
const bookTag = await logseq. Editor.getTag('book')
|
||||
await logseq.Editor.addBlockTag(page.uuid, bookTag. uuid)
|
||||
|
||||
// 3. Set property values
|
||||
await logseq. Editor.upsertBlockProperty(page.uuid, 'title', bookData.title)
|
||||
await logseq.Editor.upsertBlockProperty(page.uuid, 'author', bookData. author)
|
||||
await logseq.Editor.upsertBlockProperty(page.uuid, 'isbn', bookData.isbn)
|
||||
await logseq.Editor.upsertBlockProperty(page.uuid, 'year', bookData. year)
|
||||
|
||||
return page. uuid
|
||||
}
|
||||
```
|
||||
|
||||
### Pattern 4: Link Related Entities
|
||||
|
||||
```typescript
|
||||
async function linkBookToCategories(bookPageUUID, categoryKeys) {
|
||||
// Get or create category pages
|
||||
const categoryIDs = await Promise.all(
|
||||
categoryKeys. map(async (key) => {
|
||||
const catUUID = generateStableUUID(key)
|
||||
let catPage = await logseq.Editor.getPage(catUUID)
|
||||
|
||||
if (!catPage) {
|
||||
catPage = await logseq.Editor.createPage(key, {}, {
|
||||
customUUID: catUUID
|
||||
})
|
||||
}
|
||||
|
||||
return catPage.id // ⚠️ Use .id not .uuid for references
|
||||
})
|
||||
)
|
||||
|
||||
// Link book to categories
|
||||
await logseq.Editor.upsertBlockProperty(
|
||||
bookPageUUID,
|
||||
'tags', // Must be 'node' type with 'many' cardinality
|
||||
categoryIDs
|
||||
)
|
||||
}
|
||||
```
|
||||
|
||||
### Pattern 5: Batch Schema Setup from Configuration
|
||||
|
||||
```typescript
|
||||
async function setupSchemaFromConfig(config) {
|
||||
// config example:
|
||||
// {
|
||||
// "Media": {
|
||||
// "properties": ["title", "year"],
|
||||
// "parent": null
|
||||
// },
|
||||
// "book": {
|
||||
// "properties": ["author", "isbn"],
|
||||
// "parent": "Media"
|
||||
// }
|
||||
// }
|
||||
|
||||
for (const [tagName, tagConfig] of Object. entries(config)) {
|
||||
let tag = await logseq.Editor. getTag(tagName)
|
||||
|
||||
if (!tag) {
|
||||
// Create tag with properties
|
||||
tag = await logseq.Editor.createTag(tagName, {
|
||||
tagProperties: tagConfig.properties. map(name => ({
|
||||
name,
|
||||
schema: { type: 'default' }
|
||||
}))
|
||||
})
|
||||
|
||||
// Set parent if specified
|
||||
if (tagConfig.parent) {
|
||||
const parentTag = await logseq. Editor.getTag(tagConfig. parent)
|
||||
if (parentTag) {
|
||||
await logseq.Editor.addTagExtends(tag.uuid, parentTag.uuid)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Pattern 6: Migrate Existing Pages to New Schema
|
||||
|
||||
```typescript
|
||||
async function migrateToBookSchema() {
|
||||
// 1. Setup schema
|
||||
const bookTag = await logseq.Editor.createTag('book', {
|
||||
tagProperties: [
|
||||
{ name: 'author', schema: { type: 'default' } },
|
||||
{ name: 'year', schema: { type: 'number' } }
|
||||
]
|
||||
})
|
||||
|
||||
// 2. Find all pages with old structure
|
||||
const allPages = await logseq.Editor.getAllPages()
|
||||
|
||||
// 3. Migrate each page
|
||||
for (const page of allPages) {
|
||||
const props = await logseq.Editor. getPageProperties(page.uuid)
|
||||
|
||||
// Check if page has book-like properties
|
||||
if (props?. author || props?.isbn) {
|
||||
// Add book tag
|
||||
await logseq.Editor.addBlockTag(page.uuid, bookTag.uuid)
|
||||
|
||||
// Migrate properties if needed
|
||||
if (props. author) {
|
||||
await logseq.Editor.upsertBlockProperty(
|
||||
page.uuid,
|
||||
'author',
|
||||
props. author
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Best Practices
|
||||
|
||||
### 1. Use Stable UUIDs
|
||||
Generate deterministic UUIDs from stable identifiers:
|
||||
|
||||
```typescript
|
||||
import { v5 as uuidv5 } from 'uuid'
|
||||
|
||||
const NAMESPACE = 'your-plugin-namespace-uuid'
|
||||
|
||||
function generateStableUUID(id: string): string {
|
||||
return uuidv5(id, NAMESPACE)
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Check Before Creating
|
||||
Always check if tags/pages/properties exist before creating:
|
||||
|
||||
```typescript
|
||||
let tag = await logseq.Editor.getTag('book')
|
||||
if (!tag) {
|
||||
tag = await logseq.Editor.createTag('book', {
|
||||
tagProperties: [/* ... */]
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
### 3. Property Definition Order (Manual Approach)
|
||||
If not using `createTag` with `tagProperties`:
|
||||
|
||||
1. Define property globally with `upsertProperty`
|
||||
2. Create tag with `createTag`
|
||||
3. Add property to tag with `addTagProperty`
|
||||
4. Create page and tag it with `addBlockTag`
|
||||
5. Set values with `upsertBlockProperty`
|
||||
|
||||
### 4. Use . id for References ⚠️
|
||||
When setting `node` type properties, use `.id` not `.uuid`:
|
||||
|
||||
```typescript
|
||||
const categoryPage = await logseq.Editor.getPage('category-uuid')
|
||||
|
||||
// ✅ Correct
|
||||
await logseq.Editor.upsertBlockProperty(
|
||||
page.uuid,
|
||||
'category',
|
||||
categoryPage.id
|
||||
)
|
||||
|
||||
// ❌ Wrong
|
||||
await logseq.Editor.upsertBlockProperty(
|
||||
page.uuid,
|
||||
'category',
|
||||
categoryPage.uuid
|
||||
)
|
||||
```
|
||||
|
||||
### 5. Error Handling
|
||||
Wrap API calls in try-catch for robustness:
|
||||
|
||||
```typescript
|
||||
try {
|
||||
await logseq.Editor.upsertBlockProperty(uuid, 'field', value)
|
||||
} catch (error) {
|
||||
console.error(`Failed to set property: ${error}`)
|
||||
await logseq.UI.showMsg(`Error: ${error. message}`, 'error')
|
||||
}
|
||||
```
|
||||
|
||||
### 6. Use createTag with tagProperties
|
||||
Prefer the streamlined approach for better readability:
|
||||
|
||||
```typescript
|
||||
// ✅ Better: One call
|
||||
const tag = await logseq.Editor. createTag('book', {
|
||||
tagProperties: [
|
||||
{ name: 'author', schema: { type: 'default' } },
|
||||
{ name: 'isbn', schema: { type: 'default' } }
|
||||
]
|
||||
})
|
||||
|
||||
// ❌ Verbose: Multiple calls
|
||||
await logseq. Editor.upsertProperty('author', { type: 'default' })
|
||||
await logseq.Editor.upsertProperty('isbn', { type: 'default' })
|
||||
const tag = await logseq.Editor. createTag('book')
|
||||
await logseq.Editor. addTagProperty(tag.uuid, 'author')
|
||||
await logseq.Editor.addTagProperty(tag.uuid, 'isbn')
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Real-World Example: Zotero Plugin
|
||||
|
||||
See complete implementation: [xyhp915/logseq-zotero-plugin](https://github.com/xyhp915/logseq-zotero-plugin/blob/main/src/handlers. ts#L19-L207)
|
||||
|
||||
Key techniques:
|
||||
- Schema defined from `z_item_types. json` metadata
|
||||
- Tag hierarchy: `Zotero` → `book`, `article`, etc.
|
||||
- Stable UUIDs via `v5(itemKey, namespace)`
|
||||
- Relationship properties for collections
|
||||
- Nested blocks for attachments
|
||||
|
||||
---
|
||||
|
||||
## Type Definitions
|
||||
|
||||
```typescript
|
||||
type PropertySchema = {
|
||||
type: 'default' | 'number' | 'node' | 'date' | 'checkbox' | 'url' | string
|
||||
cardinality: 'many' | 'one'
|
||||
hide: boolean
|
||||
public: boolean
|
||||
}
|
||||
|
||||
type BlockIdentity = BlockUUID | Pick<BlockEntity, 'uuid'>
|
||||
type PageIdentity = BlockPageName | BlockIdentity
|
||||
type EntityID = number
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Reference
|
||||
|
||||
- **Type Definitions**: `@logseq/libs` - [LSPlugin. ts](https://github.com/logseq/logseq/blob/master/libs/src/LSPlugin.ts)
|
||||
- **Real Example**: [logseq-zotero-plugin/handlers.ts](https://github.com/xyhp915/logseq-zotero-plugin/blob/main/src/handlers. ts)
|
||||
- **Search More**: [GitHub Code Search](https://github.com/search?type=code&q=repo:xyhp915/logseq-zotero-plugin+upsertBlockProperty)
|
||||
@@ -0,0 +1,550 @@
|
||||
## Logseq Datascript Query Skills Guide
|
||||
|
||||
### 1. Logseq SDK Query APIs
|
||||
|
||||
```typescript
|
||||
// DSL Query - Logseq's query language
|
||||
const results0 = await logseq.DB.q('[[page-name]]')
|
||||
const todos = await logseq.DB.q('(task TODO DOING)')
|
||||
|
||||
// Datascript Query - Datalog syntax (more powerful)
|
||||
const results1 = await logseq.DB.datascriptQuery(`
|
||||
[:find (pull ?b [*])
|
||||
:where [?b :block/marker "TODO"]]
|
||||
`)
|
||||
|
||||
// Query with parameters
|
||||
const results2 = await logseq.DB.datascriptQuery(`
|
||||
[:find (pull ?b [*])
|
||||
:in $ ?name
|
||||
:where
|
||||
[?p :block/name ?name]
|
||||
[? b :block/page ?p]]
|
||||
`, `"my-page"`)
|
||||
|
||||
// Watch database changes
|
||||
logseq.DB.onChanged(({ blocks, txData }) => {
|
||||
console.log('Changed blocks:', blocks)
|
||||
})
|
||||
|
||||
// Watch specific block changes
|
||||
logseq.DB.onBlockChanged(uuid, (block, txData) => {
|
||||
console.log('Block changed:', block)
|
||||
})
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 2. Datalog Query Syntax Basics
|
||||
|
||||
#### 2.1 Basic Structure
|
||||
|
||||
```clojure
|
||||
[:find <return-value> ;; what to return
|
||||
:in $ <params... > ;; input parameters ($ = database)
|
||||
:where <clauses...>] ;; query conditions
|
||||
```
|
||||
|
||||
#### 2.2 : find Clause
|
||||
|
||||
```clojure
|
||||
;; Return entity IDs
|
||||
[:find ?b :where ...]
|
||||
|
||||
;; Return multiple values
|
||||
[:find ?b ?name :where ...]
|
||||
|
||||
;; Return full entity (commonly used)
|
||||
[:find (pull ?b [*]) :where ...]
|
||||
|
||||
;; Return specific attributes
|
||||
[:find (pull ?b [:block/uuid :block/content]) :where ...]
|
||||
|
||||
;; Aggregate functions
|
||||
[:find (count ?b) :where ...]
|
||||
[:find (min ?d) (max ?d) :where ...]
|
||||
```
|
||||
|
||||
#### 2.3 :where Clause - Data Patterns
|
||||
|
||||
```clojure
|
||||
;; Basic triple: [entity attribute value]
|
||||
[?b :block/marker "TODO"] ;; ? b's marker equals "TODO"
|
||||
[? b :block/page ?p] ;; ?b belongs to page ? p
|
||||
[?p :block/name ?name] ;; ? p's name binds to ?name
|
||||
|
||||
;; Multiple conditions (implicit AND)
|
||||
[?b :block/marker "TODO"]
|
||||
[?b :block/page ?p]
|
||||
[?p :block/journal? true] ;; all three must be satisfied
|
||||
```
|
||||
|
||||
#### 2.4 :in Clause - Parameter Passing
|
||||
|
||||
```clojure
|
||||
;; $ is the database (required)
|
||||
[:find (pull ?b [*])
|
||||
:in $
|
||||
:where ...]
|
||||
|
||||
;; Single parameter
|
||||
[:find (pull ?b [*])
|
||||
:in $ ?marker
|
||||
:where [?b :block/marker ? marker]]
|
||||
|
||||
;; Multiple parameters
|
||||
[:find (pull ?b [*])
|
||||
:in $ ?marker ? page-name
|
||||
:where
|
||||
[?b :block/marker ?marker]
|
||||
[? p :block/name ?page-name]
|
||||
[?b :block/page ?p]]
|
||||
|
||||
;; Collection parameter (match multiple values)
|
||||
[:find (pull ?b [*])
|
||||
:in $ [?marker ...]
|
||||
:where [?b :block/marker ?marker]]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3. Schema Reference: File Graph vs DB Graph
|
||||
|
||||
#### 3.1 Block Attributes
|
||||
|
||||
| Attribute | File Graph | DB Graph | Type | Description |
|
||||
|---------------------|:----------:|:--------:|--------|-------------------------------------|
|
||||
| `:block/uuid` | ✅ | ✅ | UUID | Unique block identifier |
|
||||
| `:block/content` | ✅ | ❌ | String | Raw block content (File Graph only) |
|
||||
| `:block/title` | ❌ | ✅ | String | Block title/content (DB Graph only) |
|
||||
| `:block/page` | ✅ | ✅ | Ref | Parent page reference |
|
||||
| `:block/parent` | ✅ | ✅ | Ref | Parent block reference |
|
||||
| `:block/left` | ✅ | ❌ | Ref | Left sibling block |
|
||||
| `:block/order` | ❌ | ✅ | String | Block order in DB Graph |
|
||||
| `:block/refs` | ✅ | ✅ | Ref[] | Referenced pages/blocks |
|
||||
| `:block/marker` | ✅ | ❌ | String | Task marker (TODO/DOING/DONE) |
|
||||
| `:block/priority` | ✅ | ❌ | String | Priority (A/B/C) |
|
||||
| `:block/scheduled` | ✅ | ❌ | Int | Scheduled date (YYYYMMDD) |
|
||||
| `:block/deadline` | ✅ | ❌ | Int | Deadline date (YYYYMMDD) |
|
||||
| `:block/properties` | ✅ | ❌ | Map | Properties as key-value map |
|
||||
| `:block/tags` | ✅ | ✅ | Ref[] | Tag references |
|
||||
| `:block/link` | ❌ | ✅ | Ref | Link to class/tag in DB Graph |
|
||||
| `:block/created-at` | ✅ | ❌ | Int | Creation timestamp (File Graph) |
|
||||
| `:block/updated-at` | ✅ | ❌ | Int | Update timestamp (File Graph) |
|
||||
|
||||
#### 3.2 Page Attributes
|
||||
|
||||
| Attribute | File Graph | DB Graph | Type | Description |
|
||||
|------------------------|:----------:|:--------:|---------|------------------------------------------|
|
||||
| `:block/name` | ✅ | ✅ | String | Page name (lowercase) |
|
||||
| `:block/original-name` | ✅ | ✅ | String | Original page name |
|
||||
| `:block/journal?` | ✅ | ✅ | Boolean | Is journal page |
|
||||
| `:block/journal-day` | ✅ | ✅ | Int | Journal date (YYYYMMDD) |
|
||||
| `:block/type` | ❌ | ✅ | String | Type ("page", "class", "property", etc.) |
|
||||
| `:block/format` | ✅ | ❌ | Keyword | Format (:markdown or :org) |
|
||||
| `:block/file` | ✅ | ❌ | Ref | Associated file reference |
|
||||
|
||||
#### 3.3 DB Graph Specific - System Properties (Idents)
|
||||
|
||||
| Attribute | Type | Description |
|
||||
|--------------------------------------|----------|------------------------------|
|
||||
| `:logseq.property/created-at` | Int (ms) | Creation timestamp |
|
||||
| `:logseq.property/updated-at` | Int (ms) | Update timestamp |
|
||||
| `:logseq.property/icon` | Object | Icon definition `{type, id}` |
|
||||
| `:logseq.property/hide-empty-value` | Boolean | Hide property if empty |
|
||||
| `:logseq.property/closed-value-mode` | Boolean | Enum mode for property |
|
||||
| `:logseq.property/closed-values` | Array | Allowed enum values |
|
||||
| `:logseq.property/schema` | Object | Property schema definition |
|
||||
| `:logseq.property. class/extends` | Ref[] | Parent class references |
|
||||
| `:logseq.property.class/properties` | Ref[] | Class property references |
|
||||
|
||||
#### 3.4 DB Graph Task System
|
||||
|
||||
In DB Graph, tasks use a different system based on tags/classes:
|
||||
|
||||
| Attribute | Description |
|
||||
|--------------------------|-------------------------------------------------------------|
|
||||
| `:block/tags` | Reference to task status class (e.g., `#logseq.class/Todo`) |
|
||||
| `:logseq.task/status` | Task status property |
|
||||
| `:logseq.task/priority` | Task priority property |
|
||||
| `:logseq.task/deadline` | Task deadline property |
|
||||
| `:logseq.task/scheduled` | Task scheduled property |
|
||||
|
||||
---
|
||||
|
||||
### 4. Common Query Examples
|
||||
|
||||
#### 4.1 Task Queries
|
||||
|
||||
**File Graph:**
|
||||
|
||||
```typescript
|
||||
// All TODOs
|
||||
const todos = await logseq.DB.datascriptQuery(`
|
||||
[:find (pull ?b [*])
|
||||
:where [?b :block/marker "TODO"]]
|
||||
`)
|
||||
|
||||
// TODO or DOING
|
||||
const activeTasks = await logseq.DB.datascriptQuery(`
|
||||
[:find (pull ?b [*])
|
||||
:in $ [?m ...]
|
||||
:where [?b :block/marker ? m]]
|
||||
`, `["TODO" "DOING"]`)
|
||||
|
||||
// Tasks with priority A
|
||||
const priorityTasks = await logseq.DB.datascriptQuery(`
|
||||
[:find (pull ?b [*])
|
||||
:where
|
||||
[?b :block/marker ? m]
|
||||
[?b : block/priority "A"]]
|
||||
`)
|
||||
|
||||
// Scheduled for today
|
||||
const today = new Date().toISOString().slice(0, 10).replace(/-/g, '')
|
||||
const scheduled = await logseq.DB.datascriptQuery(`
|
||||
[:find (pull ?b [*])
|
||||
:in $ ? today
|
||||
:where [?b : block/scheduled ?today]]
|
||||
`, parseInt(today))
|
||||
```
|
||||
|
||||
**DB Graph:**
|
||||
|
||||
```typescript
|
||||
// All tasks with TODO status
|
||||
const todos = await logseq.DB.datascriptQuery(`
|
||||
[:find (pull ?b [*])
|
||||
:where
|
||||
[?b :block/tags ?tag]
|
||||
[?tag :db/ident : logseq.class/Todo]]
|
||||
`)
|
||||
|
||||
// Tasks by status property
|
||||
const tasks = await logseq.DB.datascriptQuery(`
|
||||
[:find (pull ?b [*])
|
||||
:where
|
||||
[?b :logseq.task/status ?s]
|
||||
[?s :db/ident :logseq. task/status. todo]]
|
||||
`)
|
||||
```
|
||||
|
||||
#### 4.2 Page Queries
|
||||
|
||||
**Both File Graph and DB Graph:**
|
||||
|
||||
```typescript
|
||||
// All journal pages
|
||||
const journals = await logseq.DB.datascriptQuery(`
|
||||
[:find (pull ?p [*])
|
||||
:where [?p :block/journal? true]]
|
||||
`)
|
||||
|
||||
// Journals in specific month
|
||||
const monthJournals = await logseq.DB.datascriptQuery(`
|
||||
[:find (pull ?p [*])
|
||||
:where
|
||||
[?p :block/journal? true]
|
||||
[?p : block/journal-day ?d]
|
||||
[(>= ?d 20250101)]
|
||||
[(<= ?d 20250131)]]
|
||||
`)
|
||||
|
||||
// Blocks in a specific page
|
||||
const blocks = await logseq.DB.datascriptQuery(`
|
||||
[:find (pull ?b [*])
|
||||
:in $ ? name
|
||||
:where
|
||||
[? p :block/name ?name]
|
||||
[?b :block/page ?p]]
|
||||
`, `"my-page"`)
|
||||
```
|
||||
|
||||
**DB Graph only:**
|
||||
|
||||
```typescript
|
||||
// Pages by type
|
||||
const pages = await logseq.DB.datascriptQuery(`
|
||||
[:find (pull ?p [*])
|
||||
:where [?p :block/type "page"]]
|
||||
`)
|
||||
|
||||
// Class/Tag pages
|
||||
const classes = await logseq.DB.datascriptQuery(`
|
||||
[:find (pull ?p [*])
|
||||
:where [?p : block/type "class"]]
|
||||
`)
|
||||
|
||||
// Recently created pages (last 7 days)
|
||||
const sevenDaysAgo = Date.now() - 7 * 24 * 60 * 60 * 1000
|
||||
const recentPages = await logseq.DB.datascriptQuery(`
|
||||
[:find (pull ?p [*])
|
||||
:where
|
||||
[?p :block/type "page"]
|
||||
[?p :logseq.property/created-at ?created]
|
||||
[(> ? created ${sevenDaysAgo})]]
|
||||
`)
|
||||
```
|
||||
|
||||
#### 4.3 Reference Queries
|
||||
|
||||
**Both File Graph and DB Graph:**
|
||||
|
||||
```typescript
|
||||
// Blocks referencing a specific page
|
||||
const refs = await logseq.DB.datascriptQuery(`
|
||||
[:find (pull ?b [*])
|
||||
:in $ ?page
|
||||
:where
|
||||
[? p :block/name ?page]
|
||||
[?b :block/refs ?p]]
|
||||
`, `"target-page"`)
|
||||
|
||||
// Block references (backlinks)
|
||||
const blockRefs = await logseq.DB.datascriptQuery(`
|
||||
[:find (pull ?b [*])
|
||||
:in $ ?uuid
|
||||
:where
|
||||
[? target :block/uuid ?uuid]
|
||||
[?b :block/refs ?target]]
|
||||
`, `#uuid "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"`)
|
||||
```
|
||||
|
||||
#### 4.4 Property Queries
|
||||
|
||||
**File Graph:**
|
||||
|
||||
```typescript
|
||||
// Blocks with specific property
|
||||
const withProp = await logseq.DB.datascriptQuery(`
|
||||
[:find (pull ?b [*])
|
||||
:where
|
||||
[?b :block/properties ?props]
|
||||
[(get ?props :status)]]
|
||||
`)
|
||||
|
||||
// Property equals specific value
|
||||
const statusDone = await logseq.DB.datascriptQuery(`
|
||||
[:find (pull ?b [*])
|
||||
:where
|
||||
[?b :block/properties ?props]
|
||||
[(get ?props :status) ?v]
|
||||
[(= ?v "done")]]
|
||||
`)
|
||||
```
|
||||
|
||||
**DB Graph:**
|
||||
|
||||
```typescript
|
||||
// Blocks with property value (properties are direct attributes)
|
||||
const withProp = await logseq.DB.datascriptQuery(`
|
||||
[:find (pull ?b [*])
|
||||
:where
|
||||
[?b : user. property/status ?v]]
|
||||
`)
|
||||
|
||||
// Query by property ident
|
||||
const results = await logseq.DB.datascriptQuery(`
|
||||
[:find (pull ?b [*])
|
||||
:where
|
||||
[? prop :db/ident : user.property/status]
|
||||
[?b ? prop ? v]
|
||||
[?v :block/title "done"]]
|
||||
`)
|
||||
```
|
||||
|
||||
#### 4.5 Content Search
|
||||
|
||||
**File Graph:**
|
||||
|
||||
```typescript
|
||||
// Content contains keyword
|
||||
const results = await logseq.DB.datascriptQuery(`
|
||||
[:find (pull ?b [*])
|
||||
:where
|
||||
[? b :block/content ?c]
|
||||
[(clojure.string/includes? ?c "keyword")]]
|
||||
`)
|
||||
```
|
||||
|
||||
**DB Graph:**
|
||||
|
||||
```typescript
|
||||
// Title contains keyword
|
||||
const results = await logseq.DB.datascriptQuery(`
|
||||
[:find (pull ?b [*])
|
||||
:where
|
||||
[?b :block/title ?t]
|
||||
[(clojure.string/includes? ?t "keyword")]]
|
||||
`)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 5. Predicate Functions
|
||||
|
||||
```clojure
|
||||
;; Comparison
|
||||
[(> ? d 20250101)]
|
||||
[(>= ?d 20250101)]
|
||||
[(< ?d 20250131)]
|
||||
[(<= ?d 20250131)]
|
||||
[(= ?v "value")]
|
||||
[(not= ?v "value")]
|
||||
|
||||
;; String operations
|
||||
[(clojure.string/includes? ?s "text")]
|
||||
[(clojure.string/starts-with? ?s "prefix")]
|
||||
[(clojure.string/ends-with? ?s "suffix")]
|
||||
[(clojure.string/blank? ?s)]
|
||||
|
||||
;; Collection operations
|
||||
[(contains? #{"A" "B" "C"} ?v)]
|
||||
|
||||
;; Null checks
|
||||
[(some? ?v)]
|
||||
[(nil? ?v)]
|
||||
|
||||
;; Math operations
|
||||
[(+ ?a ?b) ? sum]
|
||||
[(- ?a ?b) ?diff]
|
||||
[(* ?a ?b) ?product]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 6. NOT and OR Clauses
|
||||
|
||||
```clojure
|
||||
;; NOT - exclude conditions
|
||||
[:find (pull ?b [*])
|
||||
:where
|
||||
[? b :block/marker ? m]
|
||||
(not [?b :block/priority "C"])]
|
||||
|
||||
;; OR - any condition matches
|
||||
[:find (pull ?b [*])
|
||||
:where
|
||||
(or [?b :block/marker "TODO"]
|
||||
[?b :block/marker "DOING"])]
|
||||
|
||||
;; OR with AND (or-join)
|
||||
[:find (pull ?b [*])
|
||||
:where
|
||||
(or-join [? b]
|
||||
(and [?b :block/marker "TODO"]
|
||||
[?b :block/priority "A"])
|
||||
(and [?b :block/marker "DOING"]))]
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 7. Aggregation Queries
|
||||
|
||||
```typescript
|
||||
// Count
|
||||
const count = await logseq.DB.datascriptQuery(`
|
||||
[:find (count ?b)
|
||||
:where [?b : block/marker "TODO"]]
|
||||
`)
|
||||
|
||||
// Group by page
|
||||
const grouped = await logseq.DB.datascriptQuery(`
|
||||
[:find ? name (count ?b)
|
||||
:where
|
||||
[?b :block/marker "TODO"]
|
||||
[?b :block/page ?p]
|
||||
[?p :block/name ?name]]
|
||||
`)
|
||||
|
||||
// Min/Max
|
||||
const range = await logseq.DB.datascriptQuery(`
|
||||
[:find (min ?d) (max ?d)
|
||||
:where
|
||||
[?p :block/journal? true]
|
||||
[?p :block/journal-day ?d]]
|
||||
`)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 8. Cross-Compatible Plugin Example
|
||||
|
||||
```typescript
|
||||
import '@logseq/libs'
|
||||
|
||||
async function detectGraphType(): Promise<'db' | 'file'> {
|
||||
const result = await logseq.DB.datascriptQuery(`
|
||||
[:find ? type .
|
||||
:where [_ :block/type ?type]]
|
||||
`)
|
||||
return result ? 'db' : 'file'
|
||||
}
|
||||
|
||||
async function queryTodos(graphType: 'db' | 'file') {
|
||||
if (graphType === 'file') {
|
||||
return await logseq.DB.datascriptQuery(`
|
||||
[:find (pull ?b [*])
|
||||
:where [?b :block/marker "TODO"]]
|
||||
`)
|
||||
} else {
|
||||
return await logseq.DB.datascriptQuery(`
|
||||
[:find (pull ?b [*])
|
||||
:where
|
||||
[?b :block/tags ?tag]
|
||||
[?tag :db/ident :logseq.class/Todo]]
|
||||
`)
|
||||
}
|
||||
}
|
||||
|
||||
async function queryBlockContent(uuid: string, graphType: 'db' | 'file') {
|
||||
const attr = graphType === 'file' ? ': block/content' : ':block/title'
|
||||
return await logseq.DB.datascriptQuery(`
|
||||
[:find ? content .
|
||||
:in $ ?uuid
|
||||
:where
|
||||
[? b : block/uuid ?uuid]
|
||||
[?b ${attr} ?content]]
|
||||
`, `#uuid "${uuid}"`)
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const graphType = await detectGraphType()
|
||||
console.log('Graph type:', graphType)
|
||||
|
||||
logseq.Editor.registerSlashCommand('Query TODOs', async () => {
|
||||
try {
|
||||
const results = await queryTodos(graphType)
|
||||
const todos = results?.flat() || []
|
||||
|
||||
if (todos.length) {
|
||||
const content = todos.map(t => `- ((${t.uuid}))`).join('\n')
|
||||
await logseq.Editor.insertAtEditingCursor(content)
|
||||
} else {
|
||||
await logseq.UI.showMsg('No TODOs found', 'warning')
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Query failed:', e)
|
||||
await logseq.UI.showMsg('Query failed', 'error')
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
logseq.ready().then(main)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 9. Important Notes
|
||||
|
||||
1. **Page names are lowercase**: `:block/name` stores lowercase names; convert before querying
|
||||
2. **Parameter format**:
|
||||
- Strings: `"value"`
|
||||
- Numbers: `123`
|
||||
- UUIDs: `#uuid "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"`
|
||||
- Keywords: `:keyword`
|
||||
- Collections: `["a" "b" "c"]`
|
||||
3. **Flatten results**: Query results usually need `.flat()` processing
|
||||
4. **Error handling**: Always wrap queries in try-catch
|
||||
5. **Performance**: Use `pull` with specific attributes instead of `[*]` when possible
|
||||
6. **Graph compatibility**: Check graph type before using graph-specific attributes
|
||||
@@ -0,0 +1,352 @@
|
||||
# Property & Tag Idents
|
||||
|
||||
## What is an Ident?
|
||||
|
||||
An **ident** is a unique keyword identifier for a property or tag in the database. It's distinct from:
|
||||
- **name**: Human-readable display name (e.g., "Created At")
|
||||
- **uuid**: Universal unique identifier for the entity
|
||||
- **ident**: Internal database identifier (e.g., `:logseq.property/created-at`)
|
||||
|
||||
**Key characteristics:**
|
||||
- Idents use kebab-case with namespace prefixes
|
||||
- System properties use `:logseq.property/` namespace
|
||||
- System class properties use `:logseq.class/` namespace
|
||||
- Plugin created class use `:plugin.class.xxx-plugin-id/` namespace
|
||||
- Plugin created property use `:plugin.property.xxx-plugin-id/` namespace
|
||||
- Custom properties typically don't have explicit idents (auto-generated)
|
||||
|
||||
## When to Use Idents
|
||||
|
||||
Use idents when:
|
||||
1. Working with **built-in system properties**
|
||||
2. Setting **special behaviors** for properties
|
||||
3. Querying the database directly with datascript
|
||||
4. Creating **stable references** that survive renames
|
||||
|
||||
**Example:**
|
||||
```typescript
|
||||
// Using ident for system property
|
||||
await logseq.Editor. upsertBlockProperty(
|
||||
blockId,
|
||||
':logseq. property/created-at', // ident
|
||||
new Date().getTime()
|
||||
)
|
||||
|
||||
// Using regular property name
|
||||
await logseq.Editor. upsertBlockProperty(
|
||||
blockId,
|
||||
'author', // regular name
|
||||
'John Doe'
|
||||
)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Built-in System Properties
|
||||
|
||||
### Common System Properties
|
||||
|
||||
#### `:logseq.property/created-at`
|
||||
Timestamp when the block/page was created.
|
||||
|
||||
```typescript
|
||||
await logseq.Editor.upsertBlockProperty(
|
||||
page.uuid,
|
||||
':logseq.property/created-at',
|
||||
Date.now()
|
||||
)
|
||||
```
|
||||
|
||||
#### `:logseq.property/updated-at`
|
||||
Timestamp when the block/page was last updated.
|
||||
|
||||
```typescript
|
||||
await logseq.Editor.upsertBlockProperty(
|
||||
block.uuid,
|
||||
':logseq.property/updated-at',
|
||||
Date.now()
|
||||
)
|
||||
```
|
||||
|
||||
#### `:logseq.property/icon`
|
||||
Icon for a page or block (set via `setBlockIcon` API).
|
||||
|
||||
```typescript
|
||||
// Don't set directly, use API:
|
||||
await logseq.Editor. setBlockIcon(page.uuid, 'emoji', 'book')
|
||||
|
||||
// Behind the scenes, this sets:
|
||||
// :logseq.property/icon {: type "emoji", :id "book"}
|
||||
```
|
||||
|
||||
#### `:logseq.property/hide-empty-value`
|
||||
Hide property when value is empty.
|
||||
|
||||
```typescript
|
||||
const prop = await logseq.Editor.upsertProperty('optional-field', {
|
||||
type: 'default'
|
||||
})
|
||||
|
||||
await logseq.Editor.upsertBlockProperty(
|
||||
prop. id, // Apply to property entity itself
|
||||
':logseq.property/hide-empty-value',
|
||||
true
|
||||
)
|
||||
```
|
||||
|
||||
#### `:logseq.property/closed-value-mode`
|
||||
Property only accepts predefined values (enum-like).
|
||||
|
||||
```typescript
|
||||
const prop = await logseq.Editor. upsertProperty('status', { type: 'default' })
|
||||
|
||||
await logseq.Editor.upsertBlockProperty(
|
||||
prop.id,
|
||||
':logseq.property/closed-value-mode',
|
||||
true
|
||||
)
|
||||
|
||||
// Define allowed values
|
||||
await logseq.Editor.upsertBlockProperty(
|
||||
prop. id,
|
||||
':logseq.property/closed-values',
|
||||
['todo', 'in-progress', 'done']
|
||||
)
|
||||
```
|
||||
|
||||
#### `:logseq.property/schema`
|
||||
Property schema definition (type, cardinality, etc.).
|
||||
|
||||
```typescript
|
||||
// Automatically set by upsertProperty, don't set manually
|
||||
await logseq.Editor. upsertProperty('tags', {
|
||||
type: 'node',
|
||||
cardinality: 'many'
|
||||
})
|
||||
|
||||
// Behind the scenes sets:
|
||||
// :logseq. property/schema {:type "node", :cardinality "many"}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Built-in Class (Tag) Properties
|
||||
|
||||
### Tag Inheritance & Schema
|
||||
|
||||
#### `:logseq.property. class/extends`
|
||||
Define parent classes (tag inheritance).
|
||||
|
||||
```typescript
|
||||
const mediaTag = await logseq.Editor.createTag('Media')
|
||||
const bookTag = await logseq. Editor.createTag('book')
|
||||
|
||||
// Use addTagExtends API (recommended)
|
||||
await logseq.Editor. addTagExtends(bookTag. uuid, mediaTag.uuid)
|
||||
|
||||
// Or set directly:
|
||||
await logseq.Editor. upsertBlockProperty(
|
||||
bookTag.uuid,
|
||||
': logseq.property.class/extends',
|
||||
[mediaTag.id] // Array of parent tag IDs
|
||||
)
|
||||
```
|
||||
|
||||
#### `:logseq.property.class/properties`
|
||||
Properties available for this class.
|
||||
|
||||
```typescript
|
||||
// Use addTagProperty API (recommended)
|
||||
await logseq.Editor.addTagProperty(bookTag.uuid, 'author')
|
||||
|
||||
// Or set directly:
|
||||
const authorProp = await logseq.Editor.getProperty('author')
|
||||
await logseq.Editor.upsertBlockProperty(
|
||||
bookTag.uuid,
|
||||
':logseq.property. class/properties',
|
||||
[authorProp.id]
|
||||
)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Working with Idents
|
||||
|
||||
### Pattern 1: Query by Ident
|
||||
|
||||
```typescript
|
||||
// Get property entity by ident
|
||||
const createdAtProp = await logseq. DB.datascriptQuery(`
|
||||
[: find (pull ?p [*])
|
||||
:where
|
||||
[?p :block/type "property"]
|
||||
[?p :block/ident : logseq.property/created-at]]
|
||||
`)
|
||||
|
||||
console.log(createdAtProp)
|
||||
```
|
||||
|
||||
### Pattern 2: Check if Property Has Ident
|
||||
|
||||
```typescript
|
||||
async function getPropertyIdent(propertyName: string) {
|
||||
const prop = await logseq.Editor. getProperty(propertyName)
|
||||
return prop?.ident || null
|
||||
}
|
||||
|
||||
const ident = await getPropertyIdent('created-at')
|
||||
// Returns: ": logseq.property/created-at" or null
|
||||
```
|
||||
|
||||
### Pattern 3: Create Custom Namespaced Property
|
||||
|
||||
```typescript
|
||||
// For plugin-specific properties, use your own namespace
|
||||
const pluginNamespace = 'myplugin'
|
||||
|
||||
async function createPluginProperty(name: string, schema: any) {
|
||||
// Note: Custom idents are not directly settable via API
|
||||
// They're auto-generated, but you can query by name
|
||||
|
||||
const prop = await logseq.Editor.upsertProperty(name, schema)
|
||||
|
||||
// Custom properties won't have idents unless they're system properties
|
||||
return prop
|
||||
}
|
||||
```
|
||||
|
||||
### Pattern 4: Set Multiple System Properties
|
||||
|
||||
```typescript
|
||||
async function setupPageMetadata(pageUUID: string, metadata: any) {
|
||||
const now = Date.now()
|
||||
|
||||
// Set creation timestamp
|
||||
await logseq. Editor.upsertBlockProperty(
|
||||
pageUUID,
|
||||
':logseq.property/created-at',
|
||||
metadata.createdAt || now
|
||||
)
|
||||
|
||||
// Set update timestamp
|
||||
await logseq. Editor.upsertBlockProperty(
|
||||
pageUUID,
|
||||
':logseq.property/updated-at',
|
||||
now
|
||||
)
|
||||
|
||||
// Set custom properties
|
||||
await logseq. Editor.upsertBlockProperty(pageUUID, 'author', metadata.author)
|
||||
await logseq.Editor.upsertBlockProperty(pageUUID, 'source', metadata.source)
|
||||
}
|
||||
```
|
||||
|
||||
### Pattern 5: Configure Property Behavior
|
||||
|
||||
```typescript
|
||||
async function createEnumProperty(name: string, allowedValues: string[]) {
|
||||
// 1. Create property
|
||||
const prop = await logseq.Editor.upsertProperty(name, { type: 'default' })
|
||||
|
||||
// 2. Enable closed-value mode
|
||||
await logseq.Editor.upsertBlockProperty(
|
||||
prop.id,
|
||||
':logseq.property/closed-value-mode',
|
||||
true
|
||||
)
|
||||
|
||||
// 3. Set allowed values
|
||||
await logseq.Editor. upsertBlockProperty(
|
||||
prop.id,
|
||||
':logseq.property/closed-values',
|
||||
allowedValues
|
||||
)
|
||||
|
||||
// 4. Optionally hide when empty
|
||||
await logseq. Editor.upsertBlockProperty(
|
||||
prop.id,
|
||||
':logseq.property/hide-empty-value',
|
||||
true
|
||||
)
|
||||
|
||||
return prop
|
||||
}
|
||||
|
||||
// Usage
|
||||
await createEnumProperty('priority', ['high', 'medium', 'low'])
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## System Property Reference Table
|
||||
|
||||
| Ident | Purpose | Value Type | Applied To |
|
||||
|-------|---------|------------|------------|
|
||||
| `:logseq.property/created-at` | Creation timestamp | number (ms) | Block/Page |
|
||||
| `:logseq.property/updated-at` | Update timestamp | number (ms) | Block/Page |
|
||||
| `:logseq.property/icon` | Icon definition | `{type, id}` object | Block/Page |
|
||||
| `:logseq.property/hide-empty-value` | Hide if empty | boolean | Property entity |
|
||||
| `:logseq.property/closed-value-mode` | Enum mode | boolean | Property entity |
|
||||
| `:logseq.property/closed-values` | Allowed values | array | Property entity |
|
||||
| `:logseq.property/schema` | Schema definition | object | Property entity |
|
||||
| `:logseq.property. class/extends` | Parent classes | array of IDs | Tag entity |
|
||||
| `:logseq.property.class/properties` | Class properties | array of IDs | Tag entity |
|
||||
|
||||
---
|
||||
|
||||
## Best Practices for Idents
|
||||
|
||||
### 1. Prefer High-Level APIs Over Direct Ident Manipulation
|
||||
Use specialized APIs instead of setting idents directly:
|
||||
|
||||
```typescript
|
||||
// ✅ Better: Use API
|
||||
await logseq.Editor.addTagExtends(childTag.uuid, parentTag.uuid)
|
||||
|
||||
// ❌ Avoid: Direct ident manipulation
|
||||
await logseq. Editor.upsertBlockProperty(
|
||||
childTag.uuid,
|
||||
': logseq.property. class/extends',
|
||||
[parentTag.id]
|
||||
)
|
||||
```
|
||||
|
||||
### 2. Only Use Idents for System Properties
|
||||
Custom properties should use regular names:
|
||||
|
||||
```typescript
|
||||
// ✅ Correct: System property with ident
|
||||
await logseq. Editor.upsertBlockProperty(
|
||||
page.uuid,
|
||||
': logseq.property/created-at',
|
||||
Date.now()
|
||||
)
|
||||
|
||||
// ✅ Correct: Custom property with name
|
||||
await logseq.Editor. upsertBlockProperty(
|
||||
page.uuid,
|
||||
'author',
|
||||
'John Doe'
|
||||
)
|
||||
|
||||
// ❌ Wrong: Don't create custom idents
|
||||
await logseq.Editor. upsertBlockProperty(
|
||||
page.uuid,
|
||||
':myplugin/custom-prop', // Not supported
|
||||
'value'
|
||||
)
|
||||
```
|
||||
|
||||
### 3. Query System Properties by Ident in Datascript
|
||||
When using advanced queries, idents provide stable references:
|
||||
|
||||
```typescript
|
||||
// Query all pages created in the last 7 days
|
||||
const recentPages = await logseq. DB.datascriptQuery(`
|
||||
[:find (pull ?p [*])
|
||||
:where
|
||||
[?p :block/type "page"]
|
||||
[?p : logseq.property/created-at ? created]
|
||||
[(> ?created ${Date.now() - 7 * 24 * 60 * 60 * 1000})]]
|
||||
`)
|
||||
```
|
||||
@@ -0,0 +1,804 @@
|
||||
# Logseq Experiments API Guide
|
||||
|
||||
This guide covers the **experimental APIs** exposed as `logseq.Experiments` in the Logseq Plugin SDK.
|
||||
|
||||
These APIs are intentionally lower-level than the stable SDK. They let plugins:
|
||||
|
||||
- reuse host React/ReactDOM
|
||||
- render internal Logseq components
|
||||
- convert between JS and ClojureScript data structures
|
||||
- load scripts dynamically
|
||||
- register custom renderers for fenced code, routes, sidebars, properties, and block bodies
|
||||
- hook internal extensions such as KaTeX
|
||||
- access host/plugin internals when absolutely necessary
|
||||
|
||||
> **⚠️ Warning**
|
||||
>
|
||||
> Everything in `logseq.Experiments` is unstable. Signatures, render props, and behaviors may change without a normal deprecation window. Plugins using these APIs may be temporarily unsupported on the Marketplace.
|
||||
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
The current experimental surface includes:
|
||||
|
||||
1. **React integration**: `React`, `ReactDOM`
|
||||
2. **Internal components**: `Components.Editor`
|
||||
3. **Interop utilities**: `Utils.toClj`, `toJs`, `jsxToClj`, `toKeyword`, `toSymbol`
|
||||
4. **Script loading**: `loadScripts(...)`
|
||||
5. **Renderer registration**:
|
||||
- `registerFencedCodeRenderer(...)`
|
||||
- `registerDaemonRenderer(...)`
|
||||
- `registerRouteRenderer(...)`
|
||||
- `registerHostedRenderer(...)`
|
||||
- `registerSidebarRenderer(...)`
|
||||
- `registerBlockPropertiesRenderer(...)`
|
||||
- `registerBlockRenderer(...)`
|
||||
6. **Extension enhancers**: `registerExtensionsEnhancer(...)`
|
||||
7. **Host/plugin internals**:
|
||||
- `pluginLocal`
|
||||
- `ensureHostScope()`
|
||||
- `invokeExperMethod(...)`
|
||||
|
||||
---
|
||||
|
||||
## 1. React Integration
|
||||
|
||||
Use the host's React runtime instead of bundling your own copy.
|
||||
|
||||
> **React version note**
|
||||
>
|
||||
> Current Logseq hosts ship React 19.x and ReactDOM 19.x. Treat
|
||||
> `logseq.Experiments.React` and `logseq.Experiments.ReactDOM` as the
|
||||
> host's concrete runtime, not as version-neutral compatibility shims.
|
||||
>
|
||||
> Compatibility guidance:
|
||||
>
|
||||
> - Prefer the host React runtime for elements returned from experimental
|
||||
> renderers.
|
||||
> - Do not mix host React elements, hooks, contexts, or portals with a
|
||||
> separately bundled React copy.
|
||||
> - Audit third-party integrations before attaching them to the host
|
||||
> runtime. Older helpers that rely on legacy root APIs such as
|
||||
> `ReactDOM.render`, `ReactDOM.hydrate`, `ReactDOM.unmountComponentAtNode`,
|
||||
> or `findDOMNode` may need updates for React 19.
|
||||
> - In most cases you do **not** need to mount manually with `ReactDOM`.
|
||||
> Return React elements from the experimental `render` callback and let
|
||||
> Logseq own the root.
|
||||
|
||||
### `logseq.Experiments.React`
|
||||
|
||||
Returns the React instance from the host scope.
|
||||
|
||||
```typescript
|
||||
const React = logseq.Experiments.React
|
||||
```
|
||||
|
||||
### `logseq.Experiments.ReactDOM`
|
||||
|
||||
Returns the ReactDOM instance from the host scope.
|
||||
|
||||
```typescript
|
||||
const ReactDOM = logseq.Experiments.ReactDOM
|
||||
```
|
||||
|
||||
### Example
|
||||
|
||||
```typescript
|
||||
const React = logseq.Experiments.React
|
||||
|
||||
const MyComponent = React.createElement(
|
||||
'div',
|
||||
{ className: 'my-plugin-card' },
|
||||
'Hello from a host React tree'
|
||||
)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 2. Components
|
||||
|
||||
### `logseq.Experiments.Components.Editor`
|
||||
|
||||
Renders Logseq page content using an internal page editor component.
|
||||
|
||||
**Type**
|
||||
|
||||
```typescript
|
||||
(props: { page: string } & Record<string, any>) => any
|
||||
```
|
||||
|
||||
**Parameters**
|
||||
|
||||
- `page`: page name to render
|
||||
|
||||
```typescript
|
||||
const Editor = logseq.Experiments.Components.Editor
|
||||
|
||||
const preview = Editor({ page: 'My Page Name' })
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 3. Utilities
|
||||
|
||||
`logseq.Experiments.Utils` exposes host interop helpers.
|
||||
|
||||
### `toClj(input: any)`
|
||||
|
||||
Convert JavaScript data into ClojureScript data structures.
|
||||
|
||||
```typescript
|
||||
const cljData = logseq.Experiments.Utils.toClj({ key: 'value' })
|
||||
```
|
||||
|
||||
### `jsxToClj(input: any)`
|
||||
|
||||
Convert JS/JSX-style input to ClojureScript while preserving JSX-ish structures better than a plain conversion.
|
||||
|
||||
```typescript
|
||||
const view = { type: 'div', props: { children: 'Content' } }
|
||||
const cljView = logseq.Experiments.Utils.jsxToClj(view)
|
||||
```
|
||||
|
||||
### `toJs(input: any)`
|
||||
|
||||
Convert ClojureScript values back into plain JavaScript.
|
||||
|
||||
```typescript
|
||||
const jsData = logseq.Experiments.Utils.toJs(cljData)
|
||||
```
|
||||
|
||||
### `toKeyword(input: any)`
|
||||
|
||||
Convert a string into a ClojureScript keyword.
|
||||
|
||||
```typescript
|
||||
const keyword = logseq.Experiments.Utils.toKeyword('my-key')
|
||||
```
|
||||
|
||||
### `toSymbol(input: any)`
|
||||
|
||||
Convert a string into a ClojureScript symbol.
|
||||
|
||||
```typescript
|
||||
const symbol = logseq.Experiments.Utils.toSymbol('my-symbol')
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 4. Script Loading
|
||||
|
||||
### `logseq.Experiments.loadScripts(...scripts: string[])`
|
||||
|
||||
Dynamically load scripts into the host environment.
|
||||
|
||||
**Parameters**
|
||||
|
||||
- `scripts`: HTTP(S) URLs or relative plugin resource paths
|
||||
|
||||
**Returns**
|
||||
|
||||
```typescript
|
||||
Promise<void>
|
||||
```
|
||||
|
||||
**Behavior**
|
||||
|
||||
- relative paths are resolved against the current plugin resource root
|
||||
- HTTP/HTTPS URLs are used as-is
|
||||
- scripts are loaded in the given order
|
||||
|
||||
```typescript
|
||||
await logseq.Experiments.loadScripts(
|
||||
'https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.umd.min.js'
|
||||
)
|
||||
|
||||
await logseq.Experiments.loadScripts('./vendor/local-helper.js')
|
||||
|
||||
await logseq.Experiments.loadScripts(
|
||||
'https://cdn.example.com/lib1.js',
|
||||
'https://cdn.example.com/lib2.js',
|
||||
'./local-script.js'
|
||||
)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 5. Custom Renderers
|
||||
|
||||
Experimental renderers are where most of the newer APIs live.
|
||||
|
||||
## 5.1 Fenced Code Renderer
|
||||
|
||||
Register a custom renderer for fenced code blocks such as:
|
||||
|
||||
````markdown
|
||||
```my-lang
|
||||
...
|
||||
```
|
||||
````
|
||||
|
||||
### `logseq.Experiments.registerFencedCodeRenderer(lang, opts)`
|
||||
|
||||
```text
|
||||
registerFencedCodeRenderer(
|
||||
lang: string,
|
||||
opts: {
|
||||
edit?: boolean
|
||||
before?: () => Promise<void>
|
||||
subs?: string[]
|
||||
render: (props: { content: string }) => any
|
||||
}
|
||||
): any
|
||||
```
|
||||
|
||||
**Options**
|
||||
|
||||
- `edit`: whether the fenced block remains editable
|
||||
- `before`: async preload hook, usually for loading scripts/assets
|
||||
- `subs`: experimental subscription list
|
||||
- `render`: React renderer receiving `{ content }`
|
||||
|
||||
```typescript
|
||||
logseq.Experiments.registerFencedCodeRenderer('my-chart', {
|
||||
edit: false,
|
||||
before: async () => {
|
||||
await logseq.Experiments.loadScripts(
|
||||
'https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.umd.min.js'
|
||||
)
|
||||
},
|
||||
render: ({ content }) => {
|
||||
const React = logseq.Experiments.React
|
||||
|
||||
return React.createElement('canvas', {
|
||||
ref: (canvas: HTMLCanvasElement | null) => {
|
||||
if (!canvas || !window.Chart) return
|
||||
|
||||
try {
|
||||
const config = JSON.parse(content)
|
||||
new window.Chart(canvas, config)
|
||||
} catch (error) {
|
||||
console.error('Chart renderer error', error)
|
||||
}
|
||||
},
|
||||
})
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## 5.2 Daemon Renderer
|
||||
|
||||
Register a renderer that stays mounted in a global daemon container.
|
||||
|
||||
### `logseq.Experiments.registerDaemonRenderer(key, opts)`
|
||||
|
||||
```text
|
||||
registerDaemonRenderer(
|
||||
key: string,
|
||||
opts: {
|
||||
before?: () => Promise<void>
|
||||
subs?: string[]
|
||||
render: (props: {}) => any
|
||||
}
|
||||
): any
|
||||
```
|
||||
|
||||
**Notes**
|
||||
|
||||
- use `subs`, not `sub`
|
||||
- `before` is supported by the host even if older typings may not show it yet
|
||||
- daemon renderers are useful for lightweight always-on UI, not large app shells
|
||||
|
||||
```typescript
|
||||
logseq.Experiments.registerDaemonRenderer('my-status-bar', {
|
||||
subs: ['ui/theme'],
|
||||
render: () => {
|
||||
const React = logseq.Experiments.React
|
||||
|
||||
return React.createElement(
|
||||
'div',
|
||||
{
|
||||
style: {
|
||||
position: 'fixed',
|
||||
right: 12,
|
||||
bottom: 12,
|
||||
padding: '6px 10px',
|
||||
borderRadius: 8,
|
||||
background: 'var(--ls-secondary-background-color)',
|
||||
},
|
||||
},
|
||||
'Plugin active'
|
||||
)
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## 5.3 Route Renderer
|
||||
|
||||
Register a custom route view.
|
||||
|
||||
### `logseq.Experiments.registerRouteRenderer(key, opts)`
|
||||
|
||||
```text
|
||||
registerRouteRenderer(
|
||||
key: string,
|
||||
opts: {
|
||||
path: string
|
||||
name?: string
|
||||
subs?: string[]
|
||||
render: (props: {}) => any
|
||||
}
|
||||
): any
|
||||
```
|
||||
|
||||
**Options**
|
||||
|
||||
- `path`: route path, e.g. `'/my-plugin-dashboard'`
|
||||
- `name`: optional display name; if omitted, the internal key is reused
|
||||
- `subs`: experimental subscription list
|
||||
- `render`: route component
|
||||
|
||||
```typescript
|
||||
logseq.Experiments.registerRouteRenderer('my-custom-page', {
|
||||
path: '/my-plugin-dashboard',
|
||||
name: 'Dashboard',
|
||||
render: () => {
|
||||
const React = logseq.Experiments.React
|
||||
|
||||
return React.createElement('div', { className: 'my-plugin-dashboard' }, [
|
||||
React.createElement('h1', { key: 'title' }, 'Plugin Dashboard'),
|
||||
React.createElement('p', { key: 'body' }, 'Custom content here'),
|
||||
])
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
> Route navigation is handled by Logseq's router. In docs and examples, prefer describing the registered `path` rather than relying on page navigation APIs, which are not the same thing.
|
||||
|
||||
## 5.4 Hosted Renderer
|
||||
|
||||
Low-level API for host-managed render targets.
|
||||
|
||||
Today, the main built-in consumer is the right sidebar, so most plugins should prefer `registerSidebarRenderer(...)` unless they specifically need the lower-level primitive.
|
||||
|
||||
### `logseq.Experiments.registerHostedRenderer(key, opts)`
|
||||
|
||||
```text
|
||||
registerHostedRenderer(
|
||||
key: string,
|
||||
opts: {
|
||||
title?: string
|
||||
mode?: string
|
||||
type?: string
|
||||
subs?: string[]
|
||||
render: (props: {}) => any
|
||||
}
|
||||
): any
|
||||
```
|
||||
|
||||
**Options**
|
||||
|
||||
- `title`: display title when the host surfaces the renderer
|
||||
- `type`: host-specific placement type
|
||||
- `mode`: host-specific placement mode
|
||||
- `subs`: experimental subscription list
|
||||
- `render`: React renderer
|
||||
|
||||
The host currently passes the registered renderer record back into the render function in some placements. Treat that as implementation detail, not a stable contract.
|
||||
|
||||
## 5.5 Sidebar Renderer
|
||||
|
||||
Convenience wrapper over `registerHostedRenderer(...)` for right-sidebar tools.
|
||||
|
||||
### `logseq.Experiments.registerSidebarRenderer(key, opts)`
|
||||
|
||||
```text
|
||||
registerSidebarRenderer(
|
||||
key: string,
|
||||
opts: {
|
||||
title?: string
|
||||
subs?: string[]
|
||||
render: (props: {}) => any
|
||||
[key: string]: any
|
||||
}
|
||||
): any
|
||||
```
|
||||
|
||||
**Behavior**
|
||||
|
||||
- your key is automatically namespaced internally as `_sidebar.${key}`
|
||||
- `type` is forced to `'sidebar'`
|
||||
- the renderer appears in the right-sidebar plugin menu
|
||||
|
||||
```typescript
|
||||
logseq.Experiments.registerSidebarRenderer('inspector', {
|
||||
title: 'Inspector',
|
||||
render: () => {
|
||||
const React = logseq.Experiments.React
|
||||
|
||||
return React.createElement('div', null, 'Hello from the sidebar renderer')
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## 5.6 Block Properties Renderer
|
||||
|
||||
Render custom UI inside a block's properties area.
|
||||
|
||||
### `logseq.Experiments.registerBlockPropertiesRenderer(key, opts)`
|
||||
|
||||
```text
|
||||
type BlockPropertiesCondition =
|
||||
| { has: string }
|
||||
| { equals: [string, any] }
|
||||
| { in: [string, any[]] }
|
||||
| { not: BlockPropertiesCondition }
|
||||
| { any: BlockPropertiesCondition[] }
|
||||
| { all: BlockPropertiesCondition[] }
|
||||
|
||||
type BlockPropertiesRendererProps = {
|
||||
blockId: string
|
||||
properties: Record<string, any>
|
||||
}
|
||||
|
||||
registerBlockPropertiesRenderer(
|
||||
key: string,
|
||||
opts: {
|
||||
when?: BlockPropertiesCondition | ((props: BlockPropertiesRendererProps) => boolean)
|
||||
mode?: 'prepend' | 'append' | 'replace'
|
||||
priority?: number
|
||||
subs?: string[]
|
||||
render: (props: BlockPropertiesRendererProps) => any
|
||||
}
|
||||
): any
|
||||
```
|
||||
|
||||
**Behavior**
|
||||
|
||||
- `when` may be omitted, a declarative condition, or a synchronous predicate
|
||||
- `mode` controls placement in the properties area:
|
||||
- `prepend`: before native properties
|
||||
- `append`: after native properties
|
||||
- `replace`: replace native properties UI
|
||||
- higher `priority` wins for conflicts
|
||||
- for `replace`, the highest-priority matching replace renderer wins
|
||||
- for `prepend`/`append`, all matching renderers are rendered in priority order
|
||||
|
||||
**Render props**
|
||||
|
||||
- `blockId`: block UUID string
|
||||
- `properties`: plain JS object keyed by property names without the leading `:`
|
||||
|
||||
**Property serialization details**
|
||||
|
||||
Before data is passed into plugins, Logseq normalizes some values:
|
||||
|
||||
- keywords become strings like `'logseq.property/status'`
|
||||
- UUIDs become strings
|
||||
- entity references become small objects such as `{ uuid, title }`
|
||||
- sets / collections of entity references become arrays of those objects
|
||||
|
||||
```typescript
|
||||
logseq.Experiments.registerBlockPropertiesRenderer('priority-pill', {
|
||||
when: { has: 'priority' },
|
||||
mode: 'prepend',
|
||||
priority: 10,
|
||||
render: ({ properties }) => {
|
||||
const React = logseq.Experiments.React
|
||||
const priority = properties.priority
|
||||
|
||||
if (!priority) return null
|
||||
|
||||
return React.createElement(
|
||||
'span',
|
||||
{
|
||||
style: {
|
||||
display: 'inline-flex',
|
||||
marginRight: 8,
|
||||
padding: '2px 8px',
|
||||
borderRadius: 9999,
|
||||
fontSize: 12,
|
||||
background: 'var(--ls-tertiary-background-color)',
|
||||
},
|
||||
},
|
||||
`Priority: ${priority}`
|
||||
)
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
## 5.7 Block Renderer
|
||||
|
||||
Replace a block's main outline body with plugin UI.
|
||||
|
||||
### `logseq.Experiments.registerBlockRenderer(key, opts)`
|
||||
|
||||
```text
|
||||
type BlockRendererChild = Record<string, any> & {
|
||||
children?: BlockRendererChild[]
|
||||
}
|
||||
|
||||
type BlockRendererProps = {
|
||||
blockId: string
|
||||
properties: Record<string, any>
|
||||
uuid?: string
|
||||
page?: string
|
||||
content?: string
|
||||
format?: string
|
||||
children?: BlockRendererChild[]
|
||||
}
|
||||
|
||||
registerBlockRenderer(
|
||||
key: string,
|
||||
opts: {
|
||||
when?: (props: BlockRendererProps) => boolean
|
||||
includeChildren?: boolean
|
||||
priority?: number
|
||||
subs?: string[]
|
||||
render: (props: BlockRendererProps) => any
|
||||
}
|
||||
): any
|
||||
```
|
||||
|
||||
**Behavior**
|
||||
|
||||
- `when` must be a **synchronous predicate function** if provided
|
||||
- declarative conditions are **not** supported here
|
||||
- highest `priority` match wins
|
||||
- when the plugin renderer is active, users can switch back to the native outline view via built-in UI on that block
|
||||
- when `includeChildren` is `true`, Logseq passes a recursive child tree and hides native outline children while the plugin renderer is active
|
||||
|
||||
**Render props**
|
||||
|
||||
- `blockId`: block UUID string
|
||||
- `uuid`: same block UUID
|
||||
- `page`: page title
|
||||
- `content`: block content/title text
|
||||
- `format`: `'markdown'`, `'org'`, etc.
|
||||
- `properties`: normalized property object
|
||||
- `children`: recursive normalized child tree when `includeChildren` is enabled
|
||||
|
||||
```typescript
|
||||
logseq.Experiments.registerBlockRenderer('kanban-card', {
|
||||
when: ({ properties }) => properties.view === 'kanban-card',
|
||||
includeChildren: true,
|
||||
priority: 20,
|
||||
render: ({ content, children = [] }) => {
|
||||
const React = logseq.Experiments.React
|
||||
|
||||
return React.createElement('section', { className: 'my-kanban-card' }, [
|
||||
React.createElement('h3', { key: 'title' }, content || 'Untitled'),
|
||||
React.createElement(
|
||||
'ul',
|
||||
{ key: 'children' },
|
||||
children.map((child, index) =>
|
||||
React.createElement('li', { key: child.uuid || index }, child.title || child.content)
|
||||
)
|
||||
),
|
||||
])
|
||||
},
|
||||
})
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 6. Extension Enhancers
|
||||
|
||||
### `logseq.Experiments.registerExtensionsEnhancer(type, enhancer)`
|
||||
|
||||
Enhance host libraries such as KaTeX.
|
||||
|
||||
```text
|
||||
registerExtensionsEnhancer(
|
||||
type: 'katex' | 'codemirror',
|
||||
enhancer: (value: any) => Promise<any>
|
||||
): any
|
||||
```
|
||||
|
||||
For `katex`, the host immediately invokes the enhancer if KaTeX is already present.
|
||||
|
||||
```typescript
|
||||
logseq.Experiments.registerExtensionsEnhancer('katex', async (katex) => {
|
||||
katex.macros = {
|
||||
...katex.macros,
|
||||
'\\RR': '\\mathbb{R}',
|
||||
'\\NN': '\\mathbb{N}',
|
||||
'\\ZZ': '\\mathbb{Z}',
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 7. Host / Plugin Internals
|
||||
|
||||
## 7.1 `logseq.Experiments.pluginLocal`
|
||||
|
||||
Returns the internal `PluginLocal` instance for the current plugin.
|
||||
|
||||
```typescript
|
||||
const pluginLocal = logseq.Experiments.pluginLocal
|
||||
console.log(pluginLocal.id)
|
||||
```
|
||||
|
||||
Use this sparingly. It is intentionally internal.
|
||||
|
||||
## 7.2 `logseq.Experiments.ensureHostScope()`
|
||||
|
||||
Returns the host scope, currently `window.top`, after attempting an access check.
|
||||
|
||||
```typescript
|
||||
const host = logseq.Experiments.ensureHostScope()
|
||||
```
|
||||
|
||||
This is mostly useful when you need direct access to host globals and understand the risks.
|
||||
|
||||
## 7.3 `logseq.Experiments.invokeExperMethod(type, ...args)`
|
||||
|
||||
Direct escape hatch for calling experimental host methods.
|
||||
|
||||
```typescript
|
||||
const result = logseq.Experiments.invokeExperMethod(
|
||||
'someExperimentalFeature',
|
||||
arg1,
|
||||
arg2
|
||||
)
|
||||
```
|
||||
|
||||
`type` is normalized to snake_case before resolution.
|
||||
|
||||
---
|
||||
|
||||
## 8. Complete Example: Fenced Code Renderer
|
||||
|
||||
```typescript
|
||||
import '@logseq/libs'
|
||||
|
||||
async function main() {
|
||||
logseq.Experiments.registerFencedCodeRenderer('chart', {
|
||||
edit: false,
|
||||
before: async () => {
|
||||
await logseq.Experiments.loadScripts(
|
||||
'https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.umd.min.js'
|
||||
)
|
||||
},
|
||||
render: ({ content }) => {
|
||||
const React = logseq.Experiments.React
|
||||
|
||||
return React.createElement('canvas', {
|
||||
ref: (canvas: HTMLCanvasElement | null) => {
|
||||
if (!canvas || !window.Chart) return
|
||||
|
||||
try {
|
||||
const config = JSON.parse(content)
|
||||
new window.Chart(canvas, config)
|
||||
} catch (error) {
|
||||
console.error('Chart rendering error:', error)
|
||||
}
|
||||
},
|
||||
})
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
logseq.ready(main).catch(console.error)
|
||||
```
|
||||
|
||||
**Usage**
|
||||
|
||||
````markdown
|
||||
```chart
|
||||
{
|
||||
"type": "line",
|
||||
"data": {
|
||||
"labels": ["Jan", "Feb", "Mar", "Apr"],
|
||||
"datasets": [{
|
||||
"label": "Sales",
|
||||
"data": [10, 20, 15, 30],
|
||||
"borderColor": "rgb(75, 192, 192)"
|
||||
}]
|
||||
}
|
||||
}
|
||||
```
|
||||
````
|
||||
|
||||
---
|
||||
|
||||
## 9. Complete Example: Block Properties Badge
|
||||
|
||||
```typescript
|
||||
import '@logseq/libs'
|
||||
|
||||
async function main() {
|
||||
logseq.Experiments.registerBlockPropertiesRenderer('task-status-chip', {
|
||||
when: {
|
||||
any: [
|
||||
{ equals: ['status', 'todo'] },
|
||||
{ equals: ['status', 'doing'] },
|
||||
],
|
||||
},
|
||||
mode: 'append',
|
||||
priority: 5,
|
||||
render: ({ properties }) => {
|
||||
const React = logseq.Experiments.React
|
||||
const value = properties.status
|
||||
|
||||
return React.createElement(
|
||||
'span',
|
||||
{
|
||||
style: {
|
||||
marginLeft: 8,
|
||||
padding: '2px 8px',
|
||||
borderRadius: 9999,
|
||||
fontSize: 12,
|
||||
background: 'var(--ls-secondary-background-color)',
|
||||
},
|
||||
},
|
||||
`Status: ${value}`
|
||||
)
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
logseq.ready(main).catch(console.error)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 10. Best Practices
|
||||
|
||||
1. **Prefer stable APIs first**. Only use `Experiments` when the stable SDK cannot solve the problem.
|
||||
2. **Use host React**. Avoid bundling a second React runtime into the same tree.
|
||||
3. **Keep `when` predicates synchronous**. This is especially important for `registerBlockRenderer(...)`.
|
||||
4. **Use `before` to preload dependencies** instead of doing ad hoc script injection inside render.
|
||||
5. **Treat `subs` as experimental**. Reactive semantics may change.
|
||||
6. **Keep renderers lightweight**. Block and daemon renderers can affect overall app responsiveness.
|
||||
7. **Handle bad input defensively**. Render props often contain user-authored content and properties.
|
||||
8. **Document your experimental usage** in the plugin README so users understand the risk.
|
||||
9. **Prefer `registerSidebarRenderer(...)` over raw hosted renderers** when your goal is a right-sidebar tool.
|
||||
10. **Test against real graphs**. Property values, references, and child trees can vary a lot.
|
||||
|
||||
---
|
||||
|
||||
## 11. Limitations and Notes
|
||||
|
||||
- **Experimental status**: no stability guarantee
|
||||
- **Marketplace support**: may be restricted temporarily
|
||||
- **Security**: be careful with external scripts and direct host access
|
||||
- **Performance**: custom renderers run inside the app UI, so poor implementations are noticeable
|
||||
- **Typings may lag behavior**: some newer runtime options can land before every generated wrapper/type is refreshed
|
||||
|
||||
### ClojureScript SDK note
|
||||
|
||||
The generated ClojureScript wrapper namespace `com.logseq.experiments` currently includes wrappers for:
|
||||
|
||||
- `load-scripts`
|
||||
- `register-fenced-code-renderer`
|
||||
- `register-daemon-renderer`
|
||||
- `register-hosted-renderer`
|
||||
- `register-sidebar-renderer`
|
||||
- `register-route-renderer`
|
||||
- `register-extensions-enhancer`
|
||||
|
||||
At the time of writing, `register-block-properties-renderer` and `register-block-renderer` are not yet present in that generated wrapper, so ClojureScript plugins may need to call them via `invoke-exper-method` until the wrapper is regenerated.
|
||||
|
||||
---
|
||||
|
||||
## See Also
|
||||
|
||||
- [Starter Guide](./starter_guide.md) - getting started with plugin development
|
||||
- [DB Properties Guide](./db_properties_guide.md) - working with database properties
|
||||
- [DB Query Guide](./db_query_guide.md) - querying the Logseq database
|
||||
|
||||
---
|
||||
|
||||
## Support
|
||||
|
||||
For questions and issues:
|
||||
|
||||
- [Logseq Discord](https://discord.gg/logseq) - `#plugin-dev`
|
||||
- [GitHub Discussions](https://github.com/logseq/logseq/discussions)
|
||||
- [Plugin API Documentation](https://plugins-doc.logseq.com/)
|
||||
|
||||
Remember: these are experimental features. Use them carefully and test thoroughly.
|
||||
@@ -0,0 +1,125 @@
|
||||
# Logseq Plugin Starter Guide
|
||||
|
||||
# For Developers
|
||||
|
||||
In this short guide, it will walk you through the steps needed to set up your development environment for writing and
|
||||
running a hello world simple inside of Logseq Desktop Client. You know Logseq Plugin based on Web Technologies composed
|
||||
of JS & HTML & CSS, but neither are mandatory, you can develop plugins use any language which can be translated to
|
||||
javascript (Logseq made by Clojurescript!). We will use Typescript to demonstrate this sample. Because there
|
||||
is [a type definition file](https://www.npmjs.com/package/@logseq/libs) to make development experience even better.
|
||||
|
||||
## Install Node.js and NPM
|
||||
|
||||
You can download Node.js here, which will include NPM: https://nodejs.org/en/download/.
|
||||
|
||||
## Install TypeScript
|
||||
|
||||
To install TypeScript, run `npm install -g typescript` in a terminal.
|
||||
|
||||
## Get Logseq desktop app
|
||||
|
||||
At this time, plugin development and testing needs to be done using the Logseq desktop app. This is because Logseq needs
|
||||
to read your code saved as a local file. The Logseq desktop app can be downloaded
|
||||
here: https://github.com/logseq/logseq/releases.
|
||||
|
||||
If you already have the desktop app, please make sure to update to the latest version, as several features have been
|
||||
added specifically in order to provide a better plugin development experience.
|
||||
|
||||
## Go to Settings > Turn on Developer Mode
|
||||
|
||||
This will bring up the "Plugins" entry in three dots more menu list on top right of head bar. Go to Plugins page, and
|
||||
you will get a button with `Load unpacked plugin` label.
|
||||
|
||||
## Create plugin package from scaffold
|
||||
|
||||
We will use [logseq-hello-world](https://github.com/logseq/logseq-plugin-samples/tree/master/logseq-hello-world) as
|
||||
scaffold. Download this package files using Git or download zip straight to your own plugin package directory.
|
||||
|
||||
## Explain `package.json`
|
||||
|
||||
Generally Logseq plugin package is described by `package.json` file located root. Let's checkout these primary keys.
|
||||
|
||||
```json
|
||||
{
|
||||
"name": "logseq-plugin-hello-world",
|
||||
"version": "0.0.1",
|
||||
"main": "dist/index.html",
|
||||
"logseq": {
|
||||
"id": "yet-another-hello-world-plugin",
|
||||
"title": "Say Hi to Logseq",
|
||||
"icon": "logseq.png"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- __name__ [required] a name of plugin.
|
||||
- it starts with `logseq-plugin` is better for Googling.
|
||||
- __version__ [required] semantic version
|
||||
- related link: https://semver.org/
|
||||
- __main__ [optional] entry of plugin, optional for theme plugin only.
|
||||
- `.html` file entry indicate that the plugin provide main iframe ui.
|
||||
- `.js` file entry indicate that the plugin without main iframe ui.
|
||||
- __logseq__ [required] specs of plugin & indicate it's a Logseq package.
|
||||
- `id` [optional] the identity key of plugin. if you don't provide it that will be auto generated on load
|
||||
development package.
|
||||
- `title` [optional] the title display of plugin list card. if not provided, value of `pkg#name` would be used.
|
||||
- `icon` [optional] plugin logo for your own brand :D.
|
||||
- `minSDKVersion` - [optional] the minimum sdk version what your plugin required. eg: `0.1.0`.
|
||||
- `supportsDB` - [optional] the boolean value indicate whether your plugin support the database feature.
|
||||
- `supportsDBOnly` - [optional] the boolean value indicate whether your plugin only support the database feature.
|
||||
|
||||
Apart from these primary keys, you might find other useful fields, e.g. `author`, `description`, `repository`.
|
||||
Although these are not necessary, but completed fields are kind for your plugin users.
|
||||
|
||||
## Develop your code
|
||||
|
||||
This scaffold using [Parcel](https://v2.parceljs.org/) as `ts` bundler, just it works out of box. Of Course, you could
|
||||
choose another one what you prefer. Then install dependencies `npm install` and watch your code in development mode
|
||||
`npm run dev`. It will build the development version outputs to the dist directory. Go to plugins page and pick your
|
||||
plugin root directory by `Load unpacked plugin` button. You will get a message from this plugin. Let's explain the entry
|
||||
file of `index.ts`.
|
||||
|
||||
### 1. import user plugin SDK [required]
|
||||
|
||||
```js
|
||||
import '@logseq/libs'
|
||||
```
|
||||
|
||||
It provides TS types and global sdk namespace `logseq`.
|
||||
|
||||
### 2. bootstrap your main function [required]
|
||||
|
||||
```js
|
||||
logseq.ready(main).catch(console.error)
|
||||
```
|
||||
|
||||
Limited by the plugin system mechanism, user main function should wait for some preparations to make sure the SDK api
|
||||
works correctly!
|
||||
|
||||
### 3. show your code [required]
|
||||
|
||||
```js
|
||||
function main () {
|
||||
logseq.UI.showMsg('❤️ Message from Hello World Plugin :)')
|
||||
}
|
||||
```
|
||||
|
||||
Change your code and reload the plugin to make it works.
|
||||
|
||||
> If you develop main ui in iframe, [HMR](https://webpack.js.org/concepts/hot-module-replacement/) feature provided by
|
||||
> some ui frameworks is convenient that can avoid reloading plugin again and again.
|
||||
|
||||
🎉 Actually, you're done!
|
||||
|
||||
## Next steps
|
||||
|
||||
- Awesome samples
|
||||
- https://github.com/logseq/logseq-plugin-samples
|
||||
- https://github.com/logseq/awesome-logseq
|
||||
- Community plugins
|
||||
- https://github.com/search?q=logseq-plugin
|
||||
|
||||
# For users
|
||||
|
||||
Currently, Logseq plugin can only run in developer mode. Under this mode, plugin has ability to access notes data. So if
|
||||
you're working with sensitive data, you'd better confirm the plugin is from trusted resource before installing it.
|
||||
Vendored
+5
@@ -0,0 +1,5 @@
|
||||
import { ILSPluginUser } from './dist/LSPlugin'
|
||||
|
||||
declare global {
|
||||
var logseq: ILSPluginUser
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
{
|
||||
"name": "@logseq/libs",
|
||||
"packageManager": "pnpm@10.33.0",
|
||||
"version": "0.3.4",
|
||||
"description": "Logseq SDK libraries",
|
||||
"main": "dist/lsplugin.user.js",
|
||||
"typings": "index.d.ts",
|
||||
"private": false,
|
||||
"scripts": {
|
||||
"build:user": "webpack --mode production",
|
||||
"dev:user": "pnpm build:user -- --mode development --watch",
|
||||
"build:core": "webpack --config webpack.config.core.js --mode production",
|
||||
"dev:core": "pnpm build:core -- --mode development --watch",
|
||||
"generate:schema": "node scripts/extract-sdk-schema.js",
|
||||
"build": "tsc && rm dist/*.js && pnpm build:user",
|
||||
"lint": "prettier --check \"src/**/*.{ts, js}\"",
|
||||
"fix": "prettier --write \"src/**/*.{ts, js}\"",
|
||||
"build:docs": "typedoc src/LSPlugin.user.ts",
|
||||
"build:docs:json": "typedoc --json docs/out.json ./src/LSPlugin.user.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"change-case": "^5.4.4",
|
||||
"csstype": "3.2.3",
|
||||
"debug": "4.4.3",
|
||||
"deepmerge": "4.3.1",
|
||||
"dompurify": "3.3.3",
|
||||
"eventemitter3": "5.0.4",
|
||||
"fast-deep-equal": "3.1.3",
|
||||
"lodash-es": "4.17.23",
|
||||
"path": "0.12.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"ts-morph": "^27.0.2",
|
||||
"@babel/core": "^7.29.0",
|
||||
"@babel/preset-env": "^7.29.2",
|
||||
"@types/debug": "^4.1.13",
|
||||
"@types/lodash-es": "4.17.12",
|
||||
"babel-loader": "^10.1.1",
|
||||
"prettier": "^3.8.1",
|
||||
"prettier-config-standard": "^7.0.0",
|
||||
"terser-webpack-plugin": "^5.4.0",
|
||||
"ts-loader": "9.5.4",
|
||||
"typedoc": "0.28.17",
|
||||
"typescript": "5.9.3",
|
||||
"webpack": "5.105.4",
|
||||
"webpack-bundle-analyzer": "5.2.0",
|
||||
"webpack-cli": "^7.0.2"
|
||||
}
|
||||
}
|
||||
Generated
+2933
File diff suppressed because it is too large.
Load diff
Executable
+193
@@ -0,0 +1,193 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* Extracts metadata about the Logseq JS SDK from the generated *.d.ts files.
|
||||
*
|
||||
* This script uses ts-morph so we can rely on the TypeScript compiler's view of
|
||||
* the declarations. We intentionally read the emitted declaration files in
|
||||
* dist/ so that consumers do not need to depend on the source layout.
|
||||
*
|
||||
* The resulting schema is written to dist/logseq-sdk-schema.json and contains
|
||||
* a simplified representation that downstream tooling (Babashka) can consume.
|
||||
*/
|
||||
|
||||
const fs = require('node:fs');
|
||||
const path = require('node:path');
|
||||
const { Project, Node } = require('ts-morph');
|
||||
|
||||
const ROOT = path.resolve(__dirname, '..');
|
||||
const DIST_DIR = path.join(ROOT, 'dist');
|
||||
const OUTPUT_FILE = path.join(DIST_DIR, 'logseq-sdk-schema.json');
|
||||
const DECL_FILES = [
|
||||
'LSPlugin.d.ts',
|
||||
'LSPlugin.user.d.ts',
|
||||
'modules/LSPlugin.Experiments.d.ts',
|
||||
'modules/LSPlugin.Net.d.ts',
|
||||
];
|
||||
|
||||
/**
|
||||
* Interfaces whose methods will be turned into CLJS wrappers at runtime.
|
||||
* These correspond to `logseq.<Namespace>` targets in the JS SDK.
|
||||
*/
|
||||
const TARGET_INTERFACES = [
|
||||
'IAppProxy',
|
||||
'ICommandsProxy',
|
||||
'IEditorProxy',
|
||||
'IDBProxy',
|
||||
'IUIProxy',
|
||||
'IUtilsProxy',
|
||||
'IGitProxy',
|
||||
'IAssetsProxy',
|
||||
];
|
||||
|
||||
const TARGET_CLASSES = [
|
||||
'LSPluginUser',
|
||||
'LSPluginExperiments',
|
||||
'LSPluginNet',
|
||||
];
|
||||
|
||||
/**
|
||||
* Simple heuristics to determine whether a parameter should be converted via
|
||||
* cljs-bean when crossing the JS <-> CLJS boundary.
|
||||
*/
|
||||
const BEAN_TO_JS_REGEX =
|
||||
/(Record<|Array<|Partial<|UIOptions|UIContainerAttrs|StyleString|StyleOptions|NetRequestOptions|object|any|unknown|IHookEvent|BlockEntity|PageEntity|Promise<\s*Record)/i;
|
||||
|
||||
const project = new Project({
|
||||
compilerOptions: { allowJs: true },
|
||||
});
|
||||
|
||||
DECL_FILES.forEach((file) => {
|
||||
const full = path.join(DIST_DIR, file);
|
||||
if (fs.existsSync(full)) {
|
||||
project.addSourceFileAtPath(full);
|
||||
}
|
||||
});
|
||||
|
||||
const schema = {
|
||||
generatedAt: new Date().toISOString(),
|
||||
interfaces: {},
|
||||
classes: {},
|
||||
};
|
||||
|
||||
const serializeDoc = (symbol) => {
|
||||
if (!symbol) return undefined;
|
||||
const decl = symbol.getDeclarations()[0];
|
||||
if (!decl) return undefined;
|
||||
|
||||
const docs = decl
|
||||
.getJsDocs()
|
||||
.map((doc) => doc.getComment())
|
||||
.filter(Boolean);
|
||||
return docs.length ? docs.join('\n\n') : undefined;
|
||||
};
|
||||
|
||||
const serializeParameter = (signature, symbol, memberNode) => {
|
||||
const name = symbol.getName();
|
||||
const declaration = symbol.getDeclarations()[0];
|
||||
|
||||
let typeText;
|
||||
let optional = symbol.isOptional?.() ?? false;
|
||||
let rest = symbol.isRestParameter?.() ?? false;
|
||||
|
||||
if (declaration && Node.isParameterDeclaration(declaration)) {
|
||||
typeText = declaration.getType().getText();
|
||||
optional = declaration.hasQuestionToken?.() ?? false;
|
||||
rest = declaration.isRestParameter?.() ?? false;
|
||||
} else {
|
||||
const location =
|
||||
signature.getDeclaration?.() ??
|
||||
memberNode ??
|
||||
declaration ??
|
||||
symbol.getDeclarations()[0];
|
||||
typeText = symbol.getTypeAtLocation(location).getText();
|
||||
}
|
||||
|
||||
const convertToJs = BEAN_TO_JS_REGEX.test(typeText);
|
||||
|
||||
return {
|
||||
name,
|
||||
type: typeText,
|
||||
optional,
|
||||
rest,
|
||||
beanToJs: convertToJs,
|
||||
};
|
||||
};
|
||||
|
||||
const serializeSignature = (sig, memberNode) => {
|
||||
const params = sig.getParameters().map((paramSymbol) =>
|
||||
serializeParameter(sig, paramSymbol, memberNode)
|
||||
);
|
||||
const returnType = sig.getReturnType().getText();
|
||||
return {
|
||||
parameters: params,
|
||||
returnType,
|
||||
};
|
||||
};
|
||||
|
||||
const serializeCallable = (symbol, member) => {
|
||||
if (!symbol) return null;
|
||||
const type = symbol.getTypeAtLocation(member);
|
||||
const callSignatures = type.getCallSignatures();
|
||||
if (!callSignatures.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
name: symbol.getName(),
|
||||
documentation: serializeDoc(symbol),
|
||||
signatures: callSignatures.map((sig) => serializeSignature(sig, member)),
|
||||
};
|
||||
};
|
||||
|
||||
const sourceFiles = project.getSourceFiles();
|
||||
sourceFiles.forEach((source) => {
|
||||
source.getInterfaces().forEach((iface) => {
|
||||
const name = iface.getName();
|
||||
if (!TARGET_INTERFACES.includes(name)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const interfaceSymbol = iface.getType().getSymbol();
|
||||
const doc = serializeDoc(interfaceSymbol);
|
||||
const methods = iface
|
||||
.getMembers()
|
||||
.map((member) => serializeCallable(member.getSymbol(), member))
|
||||
.filter(Boolean);
|
||||
|
||||
schema.interfaces[name] = {
|
||||
documentation: doc,
|
||||
methods,
|
||||
};
|
||||
});
|
||||
|
||||
source.getClasses().forEach((cls) => {
|
||||
const name = cls.getName();
|
||||
if (!TARGET_CLASSES.includes(name)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const classSymbol = cls.getType().getSymbol();
|
||||
const doc = serializeDoc(classSymbol);
|
||||
const methods = cls
|
||||
.getInstanceMethods()
|
||||
.filter((method) => method.getName() !== 'constructor')
|
||||
.map((method) => serializeCallable(method.getSymbol(), method))
|
||||
.filter(Boolean);
|
||||
const getters = cls.getGetAccessors().map((accessor) => ({
|
||||
name: accessor.getName(),
|
||||
documentation: serializeDoc(accessor.getSymbol()),
|
||||
returnType: accessor.getReturnType().getText(),
|
||||
}));
|
||||
|
||||
schema.classes[name] = {
|
||||
documentation: doc,
|
||||
methods,
|
||||
getters,
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
fs.mkdirSync(DIST_DIR, { recursive: true });
|
||||
fs.writeFileSync(OUTPUT_FILE, JSON.stringify(schema, null, 2));
|
||||
|
||||
console.log(`Wrote ${OUTPUT_FILE}`);
|
||||
@@ -0,0 +1,456 @@
|
||||
import Debug from 'debug'
|
||||
import { Postmate, Model, ParentAPI, ChildAPI } from './postmate'
|
||||
import EventEmitter from 'eventemitter3'
|
||||
import { PluginLocal } from './LSPlugin.core'
|
||||
import { deferred, IS_DEV } from './common'
|
||||
import { LSPluginShadowFrame } from './LSPlugin.shadow'
|
||||
|
||||
const debug = Debug('LSPlugin:caller')
|
||||
|
||||
type DeferredActor = ReturnType<typeof deferred>
|
||||
|
||||
export const FLAG_AWAIT = '#await#response#'
|
||||
export const LSPMSG = '#lspmsg#'
|
||||
export const LSPMSG_ERROR_TAG = '#lspmsg#error#'
|
||||
export const LSPMSG_SETTINGS = '#lspmsg#settings#'
|
||||
export const LSPMSG_BEFORE_UNLOAD = '#lspmsg#beforeunload#'
|
||||
export const LSPMSG_SYNC = '#lspmsg#reply#'
|
||||
export const LSPMSG_READY = '#lspmsg#ready#'
|
||||
export const LSPMSGFn = (id: string) => `${LSPMSG}${id}`
|
||||
export const AWAIT_LSPMSGFn = (id: string) => `${FLAG_AWAIT}${id}`
|
||||
|
||||
const HEAD_BAR_HEIGHT = 45
|
||||
const MAX_LAYOUT_PERCENT = 99
|
||||
|
||||
/**
|
||||
* Call between core and user
|
||||
*/
|
||||
class LSPluginCaller extends EventEmitter {
|
||||
private _connected: boolean = false
|
||||
|
||||
private _parent?: ParentAPI
|
||||
private _child?: ChildAPI
|
||||
|
||||
private _shadow?: LSPluginShadowFrame
|
||||
|
||||
private _status?: 'pending' | 'timeout'
|
||||
private _userModel: any = {}
|
||||
private _syncGCTimer: any = null
|
||||
|
||||
private _call?: (
|
||||
type: string,
|
||||
payload: any,
|
||||
actor?: DeferredActor,
|
||||
) => Promise<any>
|
||||
private _callUserModel?: (type: string, ...payloads: any[]) => Promise<any>
|
||||
|
||||
private _debugTag = ''
|
||||
|
||||
constructor(private _pluginLocal: PluginLocal | null) {
|
||||
super()
|
||||
|
||||
if (_pluginLocal) {
|
||||
this._debugTag = _pluginLocal.debugTag
|
||||
}
|
||||
}
|
||||
|
||||
// run in host
|
||||
async connectToChild() {
|
||||
if (this._connected) return
|
||||
|
||||
const { shadow } = this._pluginLocal!
|
||||
|
||||
if (shadow) {
|
||||
await this._setupShadowSandbox()
|
||||
} else {
|
||||
await this._setupIframeSandbox()
|
||||
}
|
||||
}
|
||||
|
||||
// run in sandbox
|
||||
async connectToParent(userModel = {}) {
|
||||
if (this._connected) return
|
||||
|
||||
const caller = this
|
||||
const isShadowMode = this._pluginLocal != null
|
||||
|
||||
let syncTag = 0
|
||||
const syncActors = new Map<number, DeferredActor>()
|
||||
const readyDeferred = deferred(1000 * 60)
|
||||
|
||||
const model: any = this._extendUserModel({
|
||||
[LSPMSG_READY]: async (baseInfo: any) => {
|
||||
// dynamically setup common msg handler
|
||||
model[LSPMSGFn(baseInfo?.pid)] = ({
|
||||
type,
|
||||
payload,
|
||||
}: {
|
||||
type: string
|
||||
payload: any
|
||||
}) => {
|
||||
debug(`[host (_call) -> *user] ${this._debugTag}`, type, payload)
|
||||
// host._call without async
|
||||
caller.emit(type, payload)
|
||||
}
|
||||
|
||||
await readyDeferred.resolve()
|
||||
},
|
||||
|
||||
[LSPMSG_BEFORE_UNLOAD]: async (e) => {
|
||||
const actor = deferred(10 * 1000)
|
||||
caller.emit('beforeunload', Object.assign({ actor }, e))
|
||||
await actor.promise
|
||||
},
|
||||
|
||||
[LSPMSG_SETTINGS]: async ({ payload }) => {
|
||||
caller.emit('settings:changed', payload)
|
||||
},
|
||||
|
||||
[LSPMSG]: async ({ ns, type, payload }: any) => {
|
||||
debug(
|
||||
`[host (async) -> *user] ${this._debugTag} ns=${ns} type=${type}`,
|
||||
payload,
|
||||
)
|
||||
|
||||
if (ns && ns.startsWith('hook')) {
|
||||
caller.emit(`${ns}:${type}`, payload)
|
||||
return
|
||||
}
|
||||
|
||||
caller.emit(type, payload)
|
||||
},
|
||||
|
||||
[LSPMSG_SYNC]: ({ _sync, result }: any) => {
|
||||
debug(`[sync host -> *user] #${_sync}`, result)
|
||||
|
||||
if (syncActors.has(_sync)) {
|
||||
const actor = syncActors.get(_sync)
|
||||
|
||||
if (actor) {
|
||||
if (result?.hasOwnProperty(LSPMSG_ERROR_TAG)) {
|
||||
actor.reject(result[LSPMSG_ERROR_TAG])
|
||||
} else {
|
||||
actor.resolve(result)
|
||||
}
|
||||
|
||||
syncActors.delete(_sync)
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
...userModel,
|
||||
})
|
||||
|
||||
if (isShadowMode) {
|
||||
await readyDeferred.promise
|
||||
return JSON.parse(JSON.stringify(this._pluginLocal?.toJSON()))
|
||||
}
|
||||
|
||||
const pm = new Model(model)
|
||||
const handshake = pm.sendHandshakeReply()
|
||||
|
||||
this._status = 'pending'
|
||||
|
||||
await handshake
|
||||
.then((childRefParent: ChildAPI) => {
|
||||
this._child = childRefParent
|
||||
this._connected = true
|
||||
|
||||
this._call = async (type, payload = {}, actor) => {
|
||||
if (actor) {
|
||||
const tag = ++syncTag
|
||||
syncActors.set(tag, actor)
|
||||
payload._sync = tag
|
||||
|
||||
actor.setTag(`async call #${tag}`)
|
||||
debug(`async call #${tag}`)
|
||||
}
|
||||
|
||||
childRefParent.emit(LSPMSGFn(model.baseInfo.id), { type, payload })
|
||||
|
||||
return actor?.promise as Promise<any>
|
||||
}
|
||||
|
||||
this._callUserModel = async (type, payload) => {
|
||||
try {
|
||||
model[type](payload)
|
||||
} catch (e) {
|
||||
debug(`call user model(${type}) not exist. #${this._debugTag}`)
|
||||
}
|
||||
}
|
||||
|
||||
// actors GC
|
||||
this._syncGCTimer = setInterval(() => {
|
||||
if (syncActors.size > 100) {
|
||||
for (const [k, v] of syncActors) {
|
||||
if (v.settled) {
|
||||
syncActors.delete(k)
|
||||
}
|
||||
}
|
||||
}
|
||||
}, 1000 * 60 * 30)
|
||||
})
|
||||
.finally(() => {
|
||||
this._status = undefined
|
||||
})
|
||||
|
||||
await readyDeferred.promise
|
||||
|
||||
return model.baseInfo
|
||||
}
|
||||
|
||||
async call(type: any, payload: any = {}) {
|
||||
return this._call?.call(this, type, payload)
|
||||
}
|
||||
|
||||
// only for callable apis for sdk user
|
||||
async callAsync(type: any, payload: any = {}) {
|
||||
const actor = deferred(1000 * 10)
|
||||
return this._call?.call(this, type, payload, actor)
|
||||
}
|
||||
|
||||
async callUserModel(type: string, ...args: any[]) {
|
||||
return this._callUserModel?.apply(this, [type, ...args])
|
||||
}
|
||||
|
||||
async callUserModelAsync(type: string, ...args: any[]) {
|
||||
type = AWAIT_LSPMSGFn(type)
|
||||
return this._callUserModel?.apply(this, [type, ...args])
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts a raw pixel position to a percentage or pixel CSS value,
|
||||
* clamping the value to [minValue, MAX_LAYOUT_PERCENT%].
|
||||
*/
|
||||
private _calcLayoutPosition(
|
||||
value: number,
|
||||
viewportSize: number | undefined,
|
||||
minValue: number = 0,
|
||||
): string {
|
||||
const clamped = Math.max(value, minValue)
|
||||
if (typeof viewportSize === 'number') {
|
||||
return `${Math.min((clamped * 100) / viewportSize, MAX_LAYOUT_PERCENT)}%`
|
||||
}
|
||||
return `${clamped}px`
|
||||
}
|
||||
|
||||
/**
|
||||
* Restores persisted layout data onto the container element.
|
||||
*/
|
||||
private async _applyContainerLayout(cnt: HTMLDivElement): Promise<void> {
|
||||
const mainLayoutInfo = (await this._pluginLocal?._loadLayoutsData())?.$$0
|
||||
if (!mainLayoutInfo) return
|
||||
|
||||
const { width, height, left, top, vw, vh } = mainLayoutInfo
|
||||
|
||||
cnt.dataset.inited_layout = 'true'
|
||||
Object.assign(cnt.style, {
|
||||
width: `${width}px`,
|
||||
height: `${height}px`,
|
||||
left: this._calcLayoutPosition(left, vw),
|
||||
top: this._calcLayoutPosition(top, vh, HEAD_BAR_HEIGHT),
|
||||
})
|
||||
}
|
||||
|
||||
// run in host
|
||||
async _setupIframeSandbox() {
|
||||
const pl = this._pluginLocal!
|
||||
const id = pl.id
|
||||
const domId = `${id}_lsp_main`
|
||||
const url = new URL(pl.options.entry!)
|
||||
|
||||
url.searchParams.set(
|
||||
`__v__`,
|
||||
IS_DEV ? Date.now().toString() : pl.options.version,
|
||||
)
|
||||
|
||||
// clear zombie sandbox
|
||||
document.querySelector(`#${domId}`)?.remove()
|
||||
|
||||
const cnt = document.createElement('div')
|
||||
cnt.classList.add('lsp-iframe-sandbox-container')
|
||||
cnt.id = domId
|
||||
cnt.dataset.pid = id
|
||||
|
||||
try {
|
||||
await this._applyContainerLayout(cnt)
|
||||
} catch (e) {
|
||||
console.error('[Restore Layout Error]', e)
|
||||
}
|
||||
|
||||
document.body.appendChild(cnt)
|
||||
|
||||
const pt = new Postmate({
|
||||
id: id + '_iframe',
|
||||
container: cnt,
|
||||
url: url.href,
|
||||
classListArray: ['lsp-iframe-sandbox'],
|
||||
model: { baseInfo: JSON.parse(JSON.stringify(pl.toJSON())) },
|
||||
allow: pl.options.allow,
|
||||
// for optimized postmate message
|
||||
enableMessageChannel: true,
|
||||
})
|
||||
|
||||
this._status = 'pending'
|
||||
|
||||
const HANDSHAKE_TIMEOUT = 8_000
|
||||
let timer: ReturnType<typeof setTimeout>
|
||||
|
||||
const timeout = new Promise<never>((_, reject) => {
|
||||
timer = setTimeout(() => {
|
||||
pt.destroy()
|
||||
reject(new Error('handshake Timeout'))
|
||||
}, HANDSHAKE_TIMEOUT)
|
||||
})
|
||||
|
||||
try {
|
||||
const parentRefChild = await Promise.race([
|
||||
pt.sendHandshake(),
|
||||
timeout,
|
||||
]) as ParentAPI
|
||||
|
||||
this._parent = parentRefChild
|
||||
this._connected = true
|
||||
this.emit('connected')
|
||||
|
||||
parentRefChild.on(LSPMSGFn(pl.id), ({ type, payload }: any) => {
|
||||
debug(`[user -> *host] `, type, payload)
|
||||
|
||||
this._pluginLocal?.emit(type, payload || {})
|
||||
this._pluginLocal?.caller.emit(type, payload || {})
|
||||
})
|
||||
|
||||
this._call = async (...args: any) => {
|
||||
// parent all will get message before handshake
|
||||
parentRefChild.call(LSPMSGFn(pl.id), {
|
||||
type: args[0],
|
||||
payload: Object.assign(args[1] || {}, {
|
||||
$$pid: pl.id,
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
this._callUserModel = async (type, ...payloads: any[]) => {
|
||||
if (type.startsWith(FLAG_AWAIT)) {
|
||||
return await parentRefChild.get(
|
||||
type.replace(FLAG_AWAIT, ''),
|
||||
...payloads,
|
||||
)
|
||||
} else {
|
||||
parentRefChild.call(type, payloads?.[0])
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
debug('[iframe sandbox] error', e)
|
||||
throw e
|
||||
} finally {
|
||||
clearTimeout(timer!)
|
||||
this._status = undefined
|
||||
}
|
||||
}
|
||||
|
||||
async _setupShadowSandbox() {
|
||||
const pl = this._pluginLocal!
|
||||
const shadow = (this._shadow = new LSPluginShadowFrame(pl))
|
||||
|
||||
try {
|
||||
this._status = 'pending'
|
||||
|
||||
await shadow.load()
|
||||
|
||||
this._connected = true
|
||||
this.emit('connected')
|
||||
|
||||
this._call = async (type, payload = {}, actor) => {
|
||||
actor && (payload.actor = actor)
|
||||
|
||||
// @ts-ignore Call in same thread
|
||||
this._pluginLocal?.emit(
|
||||
type,
|
||||
Object.assign(payload, {
|
||||
$$pid: pl.id,
|
||||
}),
|
||||
)
|
||||
|
||||
return actor?.promise
|
||||
}
|
||||
|
||||
this._callUserModel = async (...args: any) => {
|
||||
let type = args[0] as string
|
||||
|
||||
if (type?.startsWith(FLAG_AWAIT)) {
|
||||
type = type.replace(FLAG_AWAIT, '')
|
||||
}
|
||||
|
||||
const payload = args[1] || {}
|
||||
const fn = this._userModel[type]
|
||||
|
||||
if (typeof fn === 'function') {
|
||||
await fn.call(null, payload)
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
debug('[shadow sandbox] error', e)
|
||||
throw e
|
||||
} finally {
|
||||
this._status = undefined
|
||||
}
|
||||
}
|
||||
|
||||
_extendUserModel(model: any) {
|
||||
return Object.assign(this._userModel, model)
|
||||
}
|
||||
|
||||
_getSandboxIframeContainer() {
|
||||
return this._parent?.frame.parentNode as HTMLDivElement
|
||||
}
|
||||
|
||||
_getSandboxShadowContainer() {
|
||||
return this._shadow?.frame as HTMLDivElement
|
||||
}
|
||||
|
||||
_getSandboxIframeRoot() {
|
||||
return this._parent?.frame
|
||||
}
|
||||
|
||||
_getSandboxShadowRoot() {
|
||||
return this._shadow?.frame
|
||||
}
|
||||
|
||||
set debugTag(value: string) {
|
||||
this._debugTag = value
|
||||
}
|
||||
|
||||
async destroy() {
|
||||
let root: HTMLElement = null
|
||||
if (this._parent) {
|
||||
root = this._getSandboxIframeContainer()
|
||||
this._parent.destroy()
|
||||
}
|
||||
|
||||
if (this._shadow) {
|
||||
root = this._getSandboxShadowContainer()
|
||||
this._shadow.destroy()
|
||||
}
|
||||
|
||||
root?.parentNode?.removeChild(root)
|
||||
|
||||
// clear GC timer
|
||||
if (this._syncGCTimer) {
|
||||
clearInterval(this._syncGCTimer)
|
||||
this._syncGCTimer = null
|
||||
}
|
||||
|
||||
this._connected = false
|
||||
this._parent = undefined
|
||||
this._child = undefined
|
||||
this._shadow = undefined
|
||||
this._call = undefined
|
||||
this._callUserModel = undefined
|
||||
this._status = undefined
|
||||
}
|
||||
}
|
||||
|
||||
export {
|
||||
LSPluginCaller
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,112 @@
|
||||
import EventEmitter from 'eventemitter3'
|
||||
import { PluginLocal } from './LSPlugin.core'
|
||||
import { LSPluginUser } from './LSPlugin.user'
|
||||
|
||||
// @ts-ignore
|
||||
const { importHTML, createSandboxContainer } = window.QSandbox || {}
|
||||
|
||||
function userFetch(url, opts) {
|
||||
if (!url.startsWith('http')) {
|
||||
url = url.replace('file://', '')
|
||||
return new Promise(async (resolve, reject) => {
|
||||
try {
|
||||
const content = await window.apis.doAction(['readFile', url])
|
||||
resolve({
|
||||
text() {
|
||||
return content
|
||||
},
|
||||
})
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
reject(e)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
return fetch(url, opts)
|
||||
}
|
||||
|
||||
class LSPluginShadowFrame extends EventEmitter<'mounted' | 'unmounted'> {
|
||||
private _frame?: HTMLElement
|
||||
private _root?: ShadowRoot
|
||||
private _loaded = false
|
||||
private _unmountFns: Array<() => Promise<void>> = []
|
||||
|
||||
constructor(private _pluginLocal: PluginLocal) {
|
||||
super()
|
||||
|
||||
_pluginLocal._dispose(() => {
|
||||
this._unmount()
|
||||
})
|
||||
}
|
||||
|
||||
async load() {
|
||||
const { name, entry } = this._pluginLocal.options
|
||||
|
||||
if (this.loaded || !entry) return
|
||||
|
||||
const { template, execScripts } = await importHTML(entry, {
|
||||
fetch: userFetch,
|
||||
})
|
||||
|
||||
this._mount(template, document.body)
|
||||
|
||||
const sandbox = createSandboxContainer(name, {
|
||||
elementGetter: () => this._root?.firstChild,
|
||||
})
|
||||
|
||||
const global = sandbox.instance.proxy as any
|
||||
|
||||
global.__shadow_mode__ = true
|
||||
global.LSPluginLocal = this._pluginLocal
|
||||
global.LSPluginShadow = this
|
||||
global.LSPluginUser = global.logseq = new LSPluginUser(
|
||||
this._pluginLocal.toJSON() as any,
|
||||
this._pluginLocal.caller!
|
||||
)
|
||||
|
||||
// TODO: {mount, unmount}
|
||||
const execResult: any = await execScripts(global, true)
|
||||
|
||||
this._unmountFns.push(execResult.unmount)
|
||||
|
||||
this._loaded = true
|
||||
}
|
||||
|
||||
_mount(content: string, container: HTMLElement) {
|
||||
const frame = (this._frame = document.createElement('div'))
|
||||
frame.classList.add('lsp-shadow-sandbox')
|
||||
frame.id = this._pluginLocal.id
|
||||
|
||||
this._root = frame.attachShadow({ mode: 'open' })
|
||||
this._root.innerHTML = `<div>${content}</div>`
|
||||
|
||||
container.appendChild(frame)
|
||||
|
||||
this.emit('mounted')
|
||||
}
|
||||
|
||||
_unmount() {
|
||||
for (const fn of this._unmountFns) {
|
||||
fn && fn.call(null)
|
||||
}
|
||||
}
|
||||
|
||||
destroy() {
|
||||
this.frame?.parentNode?.removeChild(this.frame)
|
||||
}
|
||||
|
||||
get loaded(): boolean {
|
||||
return this._loaded
|
||||
}
|
||||
|
||||
get document() {
|
||||
return this._root?.firstChild as HTMLElement
|
||||
}
|
||||
|
||||
get frame(): HTMLElement {
|
||||
return this._frame!
|
||||
}
|
||||
}
|
||||
|
||||
export { LSPluginShadowFrame }
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,12 @@
|
||||
import { PluginLocal } from './LSPlugin.core'
|
||||
|
||||
/**
|
||||
* These APIs run in the host and are callable by users,
|
||||
* similar to logseq.apis.cljs but for JS/TS.
|
||||
*/
|
||||
|
||||
export function setSDKMetadata(this: PluginLocal, data: any) {
|
||||
if (this?.sdk && data) {
|
||||
this.sdk = Object.assign({}, this.sdk, data)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,630 @@
|
||||
import { SettingSchemaDesc, StyleString, UIOptions } from './LSPlugin'
|
||||
import { PluginLocal } from './LSPlugin.core'
|
||||
import * as nodePath from 'path'
|
||||
import DOMPurify from 'dompurify'
|
||||
import merge from 'deepmerge'
|
||||
import { snakeCase } from 'change-case'
|
||||
import * as callables from './callable.apis'
|
||||
import EventEmitter from 'eventemitter3'
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
api: any
|
||||
apis: any
|
||||
}
|
||||
}
|
||||
|
||||
export const path =
|
||||
navigator.platform.toLowerCase() === 'win32' ? nodePath.win32 : nodePath.posix
|
||||
export const IS_DEV = process.env.NODE_ENV === 'development'
|
||||
export const PROTOCOL_FILE = 'file://'
|
||||
export const PROTOCOL_LSP = 'lsp://'
|
||||
export const URL_LSP = PROTOCOL_LSP + 'logseq.io/plugins/'
|
||||
export const URL_LSP_EXTERNAL = PROTOCOL_LSP + 'logseq.io/external/'
|
||||
export const URL_LSP_HOST = PROTOCOL_LSP + 'logseq.com/plugins/'
|
||||
export const URL_LSP_HOST_EXTERNAL = PROTOCOL_LSP + 'logseq.com/external/'
|
||||
|
||||
let _appPathRoot: string
|
||||
|
||||
// TODO: snakeCase of lodash is incompatible with `snake-case`
|
||||
export const safeSnakeCase = snakeCase
|
||||
|
||||
export async function getAppPathRoot(): Promise<string> {
|
||||
if (_appPathRoot) {
|
||||
return _appPathRoot
|
||||
}
|
||||
|
||||
return (_appPathRoot = await invokeHostExportedApi(
|
||||
'_callApplication',
|
||||
'getAppPath'
|
||||
))
|
||||
}
|
||||
|
||||
export async function getSDKPathRoot(): Promise<string> {
|
||||
if (IS_DEV) {
|
||||
// TODO: cache in preference file
|
||||
return localStorage.getItem('LSP_DEV_SDK_ROOT') || 'http://localhost:8080'
|
||||
}
|
||||
|
||||
const appPathRoot = await getAppPathRoot()
|
||||
|
||||
return safetyPathJoin(appPathRoot, 'js')
|
||||
}
|
||||
|
||||
export function isObject(item: any) {
|
||||
return item === Object(item) && !Array.isArray(item)
|
||||
}
|
||||
|
||||
export function deepMerge<T>(a: Partial<T>, b: Partial<T>): T {
|
||||
const overwriteArrayMerge = (destinationArray, sourceArray) => sourceArray
|
||||
return merge(a, b, { arrayMerge: overwriteArrayMerge })
|
||||
}
|
||||
|
||||
export type PluginLogLevel = 'DEBUG' | 'INFO' | 'WARN' | 'ERROR'
|
||||
|
||||
export interface PluginLogEntry {
|
||||
ts: number
|
||||
level: PluginLogLevel
|
||||
tag: string
|
||||
message: string
|
||||
}
|
||||
|
||||
export interface PluginLoggerOptions {
|
||||
console?: boolean
|
||||
maxSize?: number
|
||||
level?: PluginLogLevel
|
||||
}
|
||||
|
||||
const LOG_LEVEL_WEIGHT: Record<PluginLogLevel, number> = {
|
||||
DEBUG: 10,
|
||||
INFO: 20,
|
||||
WARN: 30,
|
||||
ERROR: 40,
|
||||
}
|
||||
|
||||
const DEFAULT_LOG_MAX_SIZE = 500
|
||||
|
||||
function safeStringifyArg(it: any): string {
|
||||
if (it == null) return String(it)
|
||||
if (it instanceof Error) return `${it.message}${it.stack ? '\n' + it.stack : ''}`
|
||||
if (typeof it === 'string') return it
|
||||
if (typeof it === 'object') {
|
||||
try {
|
||||
const seen = new WeakSet()
|
||||
return JSON.stringify(it, (_k, v) => {
|
||||
if (typeof v === 'object' && v !== null) {
|
||||
if (seen.has(v)) return '[Circular]'
|
||||
seen.add(v)
|
||||
}
|
||||
return v
|
||||
})
|
||||
} catch (_e) {
|
||||
try { return String(it) } catch (_) { return '[Unserializable]' }
|
||||
}
|
||||
}
|
||||
try { return String(it) } catch (_e) { return '[Unserializable]' }
|
||||
}
|
||||
|
||||
export class PluginLogger extends EventEmitter<'change' | 'append' | 'clear'> {
|
||||
private _logs: PluginLogEntry[] = []
|
||||
private _maxSize: number
|
||||
private _level: PluginLogLevel
|
||||
|
||||
constructor(
|
||||
private _tag?: string,
|
||||
private _opts?: PluginLoggerOptions
|
||||
) {
|
||||
super()
|
||||
this._maxSize = Math.max(50, _opts?.maxSize ?? DEFAULT_LOG_MAX_SIZE)
|
||||
this._level = _opts?.level ?? 'DEBUG'
|
||||
}
|
||||
|
||||
/**
|
||||
* Write a log entry.
|
||||
* Backwards compatible: the legacy boolean tail flag in `payload` to force
|
||||
* console output is still honored.
|
||||
*/
|
||||
write(level: PluginLogLevel | string, payload: any[], inConsole?: boolean) {
|
||||
// back-compat: trailing boolean === true means "force console"
|
||||
if (Array.isArray(payload) && payload.length &&
|
||||
payload[payload.length - 1] === true) {
|
||||
inConsole = true
|
||||
payload = payload.slice(0, -1)
|
||||
}
|
||||
|
||||
const lvl = (typeof level === 'string'
|
||||
? (level.toUpperCase() as PluginLogLevel)
|
||||
: level) as PluginLogLevel
|
||||
const normalizedLevel: PluginLogLevel =
|
||||
lvl in LOG_LEVEL_WEIGHT ? lvl : 'INFO'
|
||||
|
||||
// level filtering
|
||||
if (LOG_LEVEL_WEIGHT[normalizedLevel] < LOG_LEVEL_WEIGHT[this._level]) {
|
||||
return
|
||||
}
|
||||
|
||||
const message = (payload || []).map(safeStringifyArg).join(' ')
|
||||
const entry: PluginLogEntry = {
|
||||
ts: Date.now(),
|
||||
level: normalizedLevel,
|
||||
tag: this._tag || '',
|
||||
message,
|
||||
}
|
||||
|
||||
this._logs.push(entry)
|
||||
// ring buffer
|
||||
if (this._logs.length > this._maxSize) {
|
||||
this._logs.splice(0, this._logs.length - this._maxSize)
|
||||
}
|
||||
|
||||
if (inConsole || this._opts?.console) {
|
||||
const fn = normalizedLevel === 'ERROR'
|
||||
? 'error'
|
||||
: normalizedLevel === 'WARN'
|
||||
? 'warn'
|
||||
: normalizedLevel === 'DEBUG' ? 'debug' : 'info'
|
||||
try {
|
||||
// eslint-disable-next-line no-console
|
||||
console[fn](`[${entry.tag}][${new Date(entry.ts).toLocaleTimeString()}] ${normalizedLevel}: ${message}`)
|
||||
} catch (_e) { /* noop */ }
|
||||
}
|
||||
|
||||
this.emit('append', entry)
|
||||
this.emit('change')
|
||||
}
|
||||
|
||||
clear() {
|
||||
this._logs = []
|
||||
this.emit('clear')
|
||||
this.emit('change')
|
||||
}
|
||||
|
||||
debug(...args: any[]) { this.write('DEBUG', args) }
|
||||
info(...args: any[]) { this.write('INFO', args) }
|
||||
warn(...args: any[]) { this.write('WARN', args) }
|
||||
error(...args: any[]) { this.write('ERROR', args) }
|
||||
|
||||
setTag(s: string) { this._tag = s }
|
||||
getTag() { return this._tag }
|
||||
|
||||
setLevel(l: PluginLogLevel) {
|
||||
if (l in LOG_LEVEL_WEIGHT) this._level = l
|
||||
}
|
||||
getLevel(): PluginLogLevel { return this._level }
|
||||
|
||||
setMaxSize(n: number) {
|
||||
this._maxSize = Math.max(50, n | 0)
|
||||
if (this._logs.length > this._maxSize) {
|
||||
this._logs.splice(0, this._logs.length - this._maxSize)
|
||||
this.emit('change')
|
||||
}
|
||||
}
|
||||
|
||||
/** Structured entries (preferred). */
|
||||
getEntries(): PluginLogEntry[] {
|
||||
return this._logs.slice()
|
||||
}
|
||||
|
||||
/** Legacy tuple format kept for backwards compatibility. */
|
||||
toJSON(): Array<[PluginLogLevel, string]> {
|
||||
return this._logs.map((e) => [e.level,
|
||||
`[${e.tag}][${new Date(e.ts).toLocaleTimeString()}] ${e.message}`])
|
||||
}
|
||||
}
|
||||
|
||||
export function isValidUUID(s: string) {
|
||||
return (
|
||||
typeof s === 'string' &&
|
||||
s.length === 36 &&
|
||||
/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/gi.test(
|
||||
s
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
export function genID() {
|
||||
// Math.random should be unique because of its seeding algorithm.
|
||||
// Convert it to base 36 (numbers + letters), and grab the first 9 characters
|
||||
// after the decimal.
|
||||
return '_' + Math.random().toString(36).substr(2, 9)
|
||||
}
|
||||
|
||||
export function ucFirst(str: string) {
|
||||
return str.charAt(0).toUpperCase() + str.slice(1)
|
||||
}
|
||||
|
||||
export function withFileProtocol(path: string) {
|
||||
if (!path) return ''
|
||||
const reg = /^(http|file|lsp)/
|
||||
|
||||
if (!reg.test(path)) {
|
||||
path = PROTOCOL_FILE + path
|
||||
}
|
||||
|
||||
return path
|
||||
}
|
||||
|
||||
export function safetyPathJoin(basePath: string, ...parts: Array<string>) {
|
||||
try {
|
||||
const url = new URL(basePath)
|
||||
if (!url.origin) throw new Error(null)
|
||||
const fullPath = path.join(basePath.substr(url.origin.length), ...parts)
|
||||
return url.origin + fullPath
|
||||
} catch (e) {
|
||||
return path.join(basePath, ...parts)
|
||||
}
|
||||
}
|
||||
|
||||
export function safetyPathNormalize(basePath: string) {
|
||||
if (!basePath?.match(/^(http?|lsp|assets):/)) {
|
||||
basePath = path.normalize(basePath)
|
||||
}
|
||||
return basePath
|
||||
}
|
||||
|
||||
export function deferred<T = any>(timeout?: number, tag?: string) {
|
||||
let resolve: any, reject: any
|
||||
let settled = false
|
||||
const timeFn = (r: Function) => {
|
||||
return (v: T) => {
|
||||
timeout && clearTimeout(timeout)
|
||||
r(v)
|
||||
settled = true
|
||||
}
|
||||
}
|
||||
|
||||
const promise = new Promise<T>((resolve1, reject1) => {
|
||||
resolve = timeFn(resolve1)
|
||||
reject = timeFn(reject1)
|
||||
|
||||
if (timeout) {
|
||||
// @ts-ignore
|
||||
timeout = setTimeout(
|
||||
() => reject(new Error(`[deferred timeout] ${tag}`)),
|
||||
timeout
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
return {
|
||||
created: Date.now(),
|
||||
setTag: (t: string) => (tag = t),
|
||||
resolve,
|
||||
reject,
|
||||
promise,
|
||||
get settled() {
|
||||
return settled
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export function invokeHostExportedApi(method: string, ...args: Array<any>) {
|
||||
method = method?.startsWith('_call') ? method : method?.replace(/^[_$]+/, '')
|
||||
let method1 = safeSnakeCase(method)
|
||||
|
||||
// @ts-ignore
|
||||
const nsSDK = window.logseq?.sdk
|
||||
const supportedNS = nsSDK && Object.keys(nsSDK)
|
||||
let nsTarget = {}
|
||||
const ns0 = method1?.split('_')?.[0]
|
||||
|
||||
if (ns0 && supportedNS.includes(ns0)) {
|
||||
method1 = method1.replace(new RegExp(`^${ns0}_`), '')
|
||||
nsTarget = nsSDK?.[ns0]
|
||||
}
|
||||
|
||||
const logseqHostExportedApi = Object.assign(
|
||||
// @ts-ignore
|
||||
{}, window.logseq?.api,
|
||||
nsTarget, callables
|
||||
)
|
||||
|
||||
const fn =
|
||||
logseqHostExportedApi[method1] ||
|
||||
window.apis[method1] ||
|
||||
logseqHostExportedApi[method] ||
|
||||
window.apis[method]
|
||||
|
||||
if (!fn) {
|
||||
throw new Error(`Not existed method #${method}`)
|
||||
}
|
||||
return typeof fn !== 'function' ? fn : fn.apply(this, args)
|
||||
}
|
||||
|
||||
export function setupInjectedStyle(
|
||||
style: StyleString,
|
||||
attrs: Record<string, any>
|
||||
) {
|
||||
const key = attrs['data-injected-style']
|
||||
let el = key && document.querySelector(`[data-injected-style=${key}]`)
|
||||
|
||||
if (el) {
|
||||
el.textContent = style
|
||||
return
|
||||
}
|
||||
|
||||
el = document.createElement('style')
|
||||
el.textContent = style
|
||||
|
||||
attrs &&
|
||||
Object.entries(attrs).forEach(([k, v]) => {
|
||||
el.setAttribute(k, v)
|
||||
})
|
||||
|
||||
document.head.append(el)
|
||||
|
||||
return () => {
|
||||
document.head.removeChild(el)
|
||||
}
|
||||
}
|
||||
|
||||
const injectedUIEffects = new Map<string, () => void>()
|
||||
|
||||
// @ts-ignore
|
||||
window.__injectedUIEffects = injectedUIEffects
|
||||
|
||||
export function setupInjectedUI(
|
||||
this: PluginLocal,
|
||||
ui: UIOptions,
|
||||
attrs: Record<string, string>,
|
||||
initialCallback?: (e: { el: HTMLElement; float: boolean }) => void
|
||||
) {
|
||||
let slot: string = ''
|
||||
let selector: string
|
||||
let float: boolean
|
||||
|
||||
const pl = this
|
||||
|
||||
if ('slot' in ui) {
|
||||
slot = ui.slot
|
||||
selector = `#${slot}`
|
||||
} else if ('path' in ui) {
|
||||
selector = ui.path
|
||||
} else {
|
||||
float = true
|
||||
}
|
||||
|
||||
const id = `${pl.id}--${ui.key || genID()}`
|
||||
const key = id
|
||||
|
||||
const target = float
|
||||
? document.body
|
||||
: selector && document.querySelector(selector)
|
||||
if (!target) {
|
||||
console.error(
|
||||
`${this.debugTag} can not resolve selector target ${selector}`
|
||||
)
|
||||
return false
|
||||
}
|
||||
|
||||
if (ui.template) {
|
||||
// safe template
|
||||
ui.template = DOMPurify.sanitize(ui.template, {
|
||||
ADD_TAGS: ['iframe'],
|
||||
ALLOW_UNKNOWN_PROTOCOLS: true,
|
||||
ADD_ATTR: [
|
||||
'allow',
|
||||
'src',
|
||||
'allowfullscreen',
|
||||
'frameborder',
|
||||
'scrolling',
|
||||
'target',
|
||||
],
|
||||
})
|
||||
} else {
|
||||
// remove ui
|
||||
injectedUIEffects.get(id)?.call(null)
|
||||
return
|
||||
}
|
||||
|
||||
let el = document.querySelector(`#${id}`) as HTMLElement
|
||||
let content = float ? el?.querySelector('.ls-ui-float-content') : el
|
||||
|
||||
if (content) {
|
||||
content.innerHTML = ui.template
|
||||
|
||||
// update attributes
|
||||
attrs &&
|
||||
Object.entries(attrs).forEach(([k, v]) => {
|
||||
el.setAttribute(k, v)
|
||||
})
|
||||
|
||||
let positionDirty = el.dataset.dx != null
|
||||
ui.style &&
|
||||
Object.entries(ui.style).forEach(([k, v]) => {
|
||||
if (
|
||||
positionDirty &&
|
||||
['left', 'top', 'bottom', 'right', 'width', 'height'].includes(k)
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
el.style[k] = v
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
el = document.createElement('div')
|
||||
el.id = id
|
||||
el.dataset.injectedUi = key || ''
|
||||
|
||||
if (float) {
|
||||
content = document.createElement('div')
|
||||
content.classList.add('ls-ui-float-content')
|
||||
el.appendChild(content)
|
||||
} else {
|
||||
content = el
|
||||
}
|
||||
|
||||
// TODO: enhance template
|
||||
content.innerHTML = ui.template
|
||||
|
||||
attrs &&
|
||||
Object.entries(attrs).forEach(([k, v]) => {
|
||||
el.setAttribute(k, v)
|
||||
})
|
||||
|
||||
ui.style &&
|
||||
Object.entries(ui.style).forEach(([k, v]) => {
|
||||
el.style[k] = v
|
||||
})
|
||||
|
||||
let teardownUI: () => void
|
||||
let disposeFloat: () => void
|
||||
|
||||
// seu up float container
|
||||
if (float) {
|
||||
el.setAttribute('draggable', 'true')
|
||||
el.setAttribute('resizable', 'true')
|
||||
ui.close && (el.dataset.close = ui.close)
|
||||
el.classList.add('lsp-ui-float-container', 'visible')
|
||||
disposeFloat =
|
||||
(pl._setupResizableContainer(el, key),
|
||||
pl._setupDraggableContainer(el, {
|
||||
key,
|
||||
close: () => teardownUI(),
|
||||
title: attrs?.title,
|
||||
}))
|
||||
}
|
||||
|
||||
if (!!slot && ui.reset) {
|
||||
const exists = Array.from(
|
||||
target.querySelectorAll('[data-injected-ui]')
|
||||
).map((it: HTMLElement) => it.id)
|
||||
|
||||
exists?.forEach((exist: string) => {
|
||||
injectedUIEffects.get(exist)?.call(null)
|
||||
})
|
||||
}
|
||||
|
||||
target.appendChild(el)
|
||||
|
||||
// TODO: How handle events
|
||||
;[
|
||||
'click',
|
||||
'focus',
|
||||
'focusin',
|
||||
'focusout',
|
||||
'blur',
|
||||
'dblclick',
|
||||
'keyup',
|
||||
'keypress',
|
||||
'keydown',
|
||||
'change',
|
||||
'input',
|
||||
'contextmenu',
|
||||
].forEach((type) => {
|
||||
el.addEventListener(
|
||||
type,
|
||||
(e) => {
|
||||
const target = e.target! as HTMLElement
|
||||
const trigger = target.closest(`[data-on-${type}]`) as HTMLElement
|
||||
if (!trigger) return
|
||||
|
||||
const { preventDefault } = trigger.dataset
|
||||
const msgType = trigger.dataset[`on${ucFirst(type)}`]
|
||||
if (msgType)
|
||||
pl.caller?.callUserModel(msgType, transformableEvent(trigger, e))
|
||||
if (preventDefault?.toLowerCase() === 'true') e.preventDefault()
|
||||
},
|
||||
false
|
||||
)
|
||||
})
|
||||
|
||||
// callback
|
||||
initialCallback?.({ el, float })
|
||||
|
||||
teardownUI = () => {
|
||||
disposeFloat?.()
|
||||
injectedUIEffects.delete(id)
|
||||
target!.removeChild(el)
|
||||
}
|
||||
|
||||
injectedUIEffects.set(id, teardownUI)
|
||||
return teardownUI
|
||||
}
|
||||
|
||||
export function cleanInjectedUI(id: string) {
|
||||
if (!injectedUIEffects.has(id)) return
|
||||
const clean = injectedUIEffects.get(id)
|
||||
try {
|
||||
clean()
|
||||
} catch (e) {
|
||||
console.warn('[CLEAN Injected UI] ', id, e)
|
||||
}
|
||||
}
|
||||
|
||||
export function cleanInjectedScripts(this: PluginLocal) {
|
||||
const scripts = document.head.querySelectorAll(`script[data-ref=${this.id}]`)
|
||||
|
||||
scripts?.forEach((it) => it.remove())
|
||||
}
|
||||
|
||||
export function transformableEvent(target: HTMLElement, e: Event) {
|
||||
const obj: any = {}
|
||||
|
||||
if (target) {
|
||||
obj.type = e.type
|
||||
|
||||
const ds = target.dataset
|
||||
const FLAG_RECT = 'rect'
|
||||
|
||||
;['value', 'id', 'className', 'dataset', FLAG_RECT].forEach((k) => {
|
||||
let v: any
|
||||
|
||||
switch (k) {
|
||||
case FLAG_RECT:
|
||||
if (!ds.hasOwnProperty(FLAG_RECT)) return
|
||||
v = target.getBoundingClientRect().toJSON()
|
||||
break
|
||||
default:
|
||||
v = target[k]
|
||||
}
|
||||
|
||||
if (typeof v === 'object') {
|
||||
v = { ...v }
|
||||
}
|
||||
|
||||
obj[k] = v
|
||||
})
|
||||
}
|
||||
|
||||
return obj
|
||||
}
|
||||
|
||||
export function injectTheme(url: string) {
|
||||
const link = document.createElement('link')
|
||||
link.rel = 'stylesheet'
|
||||
link.href = url
|
||||
document.head.appendChild(link)
|
||||
|
||||
const ejectTheme = () => {
|
||||
try {
|
||||
document.head.removeChild(link)
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
}
|
||||
}
|
||||
|
||||
return ejectTheme
|
||||
}
|
||||
|
||||
export function mergeSettingsWithSchema(
|
||||
settings: Record<string, any>,
|
||||
schema: Array<SettingSchemaDesc>
|
||||
) {
|
||||
const defaults = (schema || []).reduce((a, b) => {
|
||||
if ('default' in b) {
|
||||
a[b.key] = b.default
|
||||
}
|
||||
return a
|
||||
}, {})
|
||||
|
||||
// shadow copy
|
||||
return Object.assign(defaults, settings)
|
||||
}
|
||||
|
||||
export function normalizeKeyStr(s: string) {
|
||||
if (typeof s !== 'string') return
|
||||
return s.trim().replace(/\s/g, '_').toLowerCase()
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
import { LSPluginUser } from '../LSPlugin.user'
|
||||
import { PluginLocal } from '../LSPlugin.core'
|
||||
import { safeSnakeCase } from '../common'
|
||||
|
||||
/**
|
||||
* Declarative condition for matching a block's properties map.
|
||||
* Operators: has, equals, in, not, any, all.
|
||||
*/
|
||||
export type BlockPropertiesCondition =
|
||||
| { has: string }
|
||||
| { equals: [string, any] }
|
||||
| { in: [string, Array<any>] }
|
||||
| { not: BlockPropertiesCondition }
|
||||
| { any: Array<BlockPropertiesCondition> }
|
||||
| { all: Array<BlockPropertiesCondition> }
|
||||
|
||||
export type BlockPropertiesRendererProps = {
|
||||
blockId: string
|
||||
properties: Record<string, any>
|
||||
}
|
||||
|
||||
export type BlockRendererChild = Record<string, any> & {
|
||||
children?: Array<BlockRendererChild>
|
||||
}
|
||||
|
||||
export type BlockRendererProps = BlockPropertiesRendererProps & {
|
||||
uuid?: string
|
||||
page?: string
|
||||
content?: string
|
||||
format?: string
|
||||
children?: Array<BlockRendererChild>
|
||||
}
|
||||
|
||||
export type BlockPropertiesPredicate = (
|
||||
props: BlockPropertiesRendererProps
|
||||
) => boolean
|
||||
|
||||
export type BlockRendererPredicate = (
|
||||
props: BlockRendererProps
|
||||
) => boolean
|
||||
|
||||
/**
|
||||
* WARN: These are some experience features and might be adjusted at any time.
|
||||
* These unofficial plugins that use these APIs are temporarily
|
||||
* may not be supported on the Marketplace.
|
||||
*/
|
||||
export class LSPluginExperiments {
|
||||
constructor(private ctx: LSPluginUser) {}
|
||||
|
||||
get React(): unknown {
|
||||
return this.ensureHostScope().React
|
||||
}
|
||||
|
||||
get ReactDOM(): unknown {
|
||||
return this.ensureHostScope().ReactDOM
|
||||
}
|
||||
|
||||
get Components() {
|
||||
const exper = this.ensureHostScope().logseq.sdk.experiments
|
||||
return {
|
||||
Editor: exper.cp_page_editor as (props: { page: string } & any) => any,
|
||||
}
|
||||
}
|
||||
|
||||
get Utils() {
|
||||
const utils = this.ensureHostScope().logseq.sdk.utils
|
||||
const withCall = (name: string): ((input: any) => any) =>
|
||||
utils[safeSnakeCase(name)]
|
||||
return {
|
||||
toClj: withCall('toClj'),
|
||||
jsxToClj: withCall('jsxToClj'),
|
||||
toJs: withCall('toJs'),
|
||||
toKeyword: withCall('toKeyword'),
|
||||
toSymbol: withCall('toSymbol'),
|
||||
}
|
||||
}
|
||||
|
||||
get pluginLocal(): PluginLocal {
|
||||
return this.ensureHostScope().LSPluginCore.ensurePlugin(
|
||||
this.ctx.baseInfo.id
|
||||
)
|
||||
}
|
||||
|
||||
public invokeExperMethod(type: string, ...args: Array<any>) {
|
||||
const host = this.ensureHostScope()
|
||||
type = safeSnakeCase(type)?.toLowerCase()
|
||||
const fn =
|
||||
host.logseq.api['exper_' + type] || host.logseq.sdk.experiments[type]
|
||||
return fn?.apply(host, args)
|
||||
}
|
||||
|
||||
async loadScripts(...scripts: Array<string>) {
|
||||
scripts = scripts.map((it) => {
|
||||
if (!it?.startsWith('http')) {
|
||||
return this.ctx.resolveResourceFullUrl(it)
|
||||
}
|
||||
|
||||
return it
|
||||
})
|
||||
|
||||
scripts.unshift(this.ctx.baseInfo.id)
|
||||
await this.invokeExperMethod('loadScripts', ...scripts)
|
||||
}
|
||||
|
||||
registerFencedCodeRenderer(
|
||||
lang: string,
|
||||
opts: {
|
||||
edit?: boolean
|
||||
before?: () => Promise<void>
|
||||
subs?: Array<string>
|
||||
render: (props: { content: string }) => any
|
||||
}
|
||||
) {
|
||||
return this.invokeExperMethod(
|
||||
'registerFencedCodeRenderer',
|
||||
this.ctx.baseInfo.id,
|
||||
lang,
|
||||
opts
|
||||
)
|
||||
}
|
||||
|
||||
registerDaemonRenderer(
|
||||
key: string,
|
||||
opts: {
|
||||
before?: () => Promise<void>
|
||||
subs?: Array<string>
|
||||
render: (props: {}) => any
|
||||
}
|
||||
) {
|
||||
return this.invokeExperMethod(
|
||||
'registerDaemonRenderer',
|
||||
this.ctx.baseInfo.id,
|
||||
key,
|
||||
opts
|
||||
)
|
||||
}
|
||||
|
||||
registerHostedRenderer(
|
||||
key: string,
|
||||
opts: {
|
||||
title?: string
|
||||
subs?: Array<string>
|
||||
type?: string
|
||||
render: (props: {}) => any
|
||||
}
|
||||
) {
|
||||
return this.invokeExperMethod(
|
||||
'registerHostedRenderer',
|
||||
this.ctx.baseInfo.id,
|
||||
key,
|
||||
opts
|
||||
)
|
||||
}
|
||||
|
||||
registerSidebarRenderer(
|
||||
key: string,
|
||||
opts: {
|
||||
title?: string
|
||||
subs?: Array<string>
|
||||
render: (props: {}) => any
|
||||
[k: string]: any
|
||||
}
|
||||
) {
|
||||
key = `_sidebar.${key}`
|
||||
opts.type = 'sidebar'
|
||||
return this.registerHostedRenderer(key, opts)
|
||||
}
|
||||
|
||||
registerRouteRenderer(
|
||||
key: string,
|
||||
opts: {
|
||||
name?: string
|
||||
subs?: Array<string>
|
||||
path: string
|
||||
render: (props: {}) => any
|
||||
}
|
||||
) {
|
||||
return this.invokeExperMethod(
|
||||
'registerRouteRenderer',
|
||||
this.ctx.baseInfo.id,
|
||||
key,
|
||||
opts
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a custom renderer for the block properties area.
|
||||
* The renderer is shown when the block's properties match the `when` condition.
|
||||
* `when` may be either a declarative condition object or a synchronous predicate.
|
||||
*
|
||||
* @param key Unique key for this renderer (scoped to the plugin).
|
||||
* @param opts Renderer options.
|
||||
* @param opts.when Optional condition or synchronous predicate; if omitted, always matches.
|
||||
* @param opts.mode "prepend" | "append" (default) | "replace".
|
||||
* @param opts.priority Higher number wins when multiple replace renderers match.
|
||||
* @param opts.subs Reserved subscription list for future reactive updates.
|
||||
* @param opts.render React function component receiving `{ blockId, properties }`.
|
||||
*/
|
||||
registerBlockPropertiesRenderer(
|
||||
key: string,
|
||||
opts: {
|
||||
when?: BlockPropertiesCondition | BlockPropertiesPredicate
|
||||
mode?: 'prepend' | 'append' | 'replace'
|
||||
priority?: number
|
||||
subs?: Array<string>
|
||||
render: (props: BlockPropertiesRendererProps) => any
|
||||
}
|
||||
) {
|
||||
return this.invokeExperMethod(
|
||||
'registerBlockPropertiesRenderer',
|
||||
this.ctx.baseInfo.id,
|
||||
key,
|
||||
opts
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a custom renderer for the block body.
|
||||
* When the synchronous predicate matches, the plugin renderer replaces the
|
||||
* default outline view by default. Users can switch back to outline view via
|
||||
* an explicit UI toggle on each matched block.
|
||||
*
|
||||
* @param key Unique key for this renderer (scoped to the plugin).
|
||||
* @param opts Renderer options.
|
||||
* @param opts.when Optional synchronous predicate; if omitted, always matches.
|
||||
* @param opts.includeChildren When true, passes the block's recursive children
|
||||
* tree to the renderer and hides native outline children while the plugin
|
||||
* renderer is active.
|
||||
* @param opts.priority Higher number wins when multiple block renderers match.
|
||||
* @param opts.subs Reserved subscription list for future reactive updates.
|
||||
* @param opts.render React function component receiving block renderer props.
|
||||
*/
|
||||
registerBlockRenderer(
|
||||
key: string,
|
||||
opts: {
|
||||
when?: BlockRendererPredicate
|
||||
includeChildren?: boolean
|
||||
priority?: number
|
||||
subs?: Array<string>
|
||||
render: (props: BlockRendererProps) => any
|
||||
}
|
||||
) {
|
||||
return this.invokeExperMethod(
|
||||
'registerBlockRenderer',
|
||||
this.ctx.baseInfo.id,
|
||||
key,
|
||||
opts
|
||||
)
|
||||
}
|
||||
|
||||
registerExtensionsEnhancer<T = any>(
|
||||
type: 'katex' | 'codemirror',
|
||||
enhancer: (v: T) => Promise<any>
|
||||
) {
|
||||
const host = this.ensureHostScope()
|
||||
|
||||
switch (type) {
|
||||
case 'katex':
|
||||
if (host.katex) {
|
||||
enhancer(host.katex).catch(console.error)
|
||||
}
|
||||
break
|
||||
default:
|
||||
}
|
||||
|
||||
return this.invokeExperMethod(
|
||||
'registerExtensionsEnhancer',
|
||||
this.ctx.baseInfo.id,
|
||||
type,
|
||||
enhancer
|
||||
)
|
||||
}
|
||||
|
||||
ensureHostScope(): any {
|
||||
try {
|
||||
window.top?.document
|
||||
} catch (_e) {
|
||||
console.error('Can not access host scope!')
|
||||
}
|
||||
|
||||
return window.top
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,670 @@
|
||||
import { LSPluginUser } from '../LSPlugin.user'
|
||||
|
||||
export type NetMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'HEAD'
|
||||
|
||||
export type NetResponseType =
|
||||
| 'json'
|
||||
| 'text'
|
||||
| 'base64'
|
||||
| 'arraybuffer'
|
||||
| 'arrayBuffer'
|
||||
|
||||
export type NetHeaders = Record<string, string>
|
||||
|
||||
export type NetRetryOptions = {
|
||||
retries?: number
|
||||
delay?: number
|
||||
factor?: number
|
||||
retryOn?:
|
||||
| Array<number>
|
||||
| ((response: LSPluginNetResponse<any> | Error) => boolean)
|
||||
}
|
||||
|
||||
export type NetCacheOptions = {
|
||||
key?: string
|
||||
ttl?: number
|
||||
maxEntries?: number
|
||||
}
|
||||
|
||||
export type NetRequestOptions<TBody = any> = {
|
||||
url: string
|
||||
method?: NetMethod
|
||||
headers?: NetHeaders
|
||||
body?: TBody | string | ArrayBuffer
|
||||
data?: TBody | string | ArrayBuffer
|
||||
responseType?: NetResponseType
|
||||
timeout?: number
|
||||
retry?: number | NetRetryOptions
|
||||
cache?: boolean | NetCacheOptions
|
||||
signal?: AbortSignal
|
||||
abortable?: boolean
|
||||
}
|
||||
|
||||
export type NetRequestConfig<TBody = any> = Omit<
|
||||
NetRequestOptions<TBody>,
|
||||
'url' | 'method'
|
||||
>
|
||||
|
||||
export type NetRequestBody<TBody = any> = TBody | string | ArrayBuffer
|
||||
|
||||
export type NetResponsePayload<T = any> = {
|
||||
status: number
|
||||
statusText: string
|
||||
ok: boolean
|
||||
url: string
|
||||
headers: NetHeaders
|
||||
body: T
|
||||
}
|
||||
|
||||
type NormalizedRetryOptions = Required<
|
||||
Pick<NetRetryOptions, 'retries' | 'delay' | 'factor'>
|
||||
> &
|
||||
Pick<NetRetryOptions, 'retryOn'>
|
||||
|
||||
type CacheEntry<T = any> = {
|
||||
expires: number
|
||||
response: LSPluginNetResponse<T>
|
||||
}
|
||||
|
||||
type HostResponseType = 'json' | 'text' | 'base64' | 'arraybuffer'
|
||||
|
||||
type HostRequestID = string | number
|
||||
|
||||
const DEFAULT_CACHE_TTL = 5 * 60 * 1000
|
||||
const DEFAULT_CACHE_MAX_ENTRIES = 100
|
||||
const CLIENT_MSG_CALLBACK = '#lsp#request#callback'
|
||||
const genTaskCallbackType = (id: HostRequestID) => `task_callback_${id}`
|
||||
|
||||
function normalizeResponseType(type?: NetResponseType): HostResponseType {
|
||||
return type === 'arrayBuffer' ? 'arraybuffer' : type || 'json'
|
||||
}
|
||||
|
||||
function makeAbortError() {
|
||||
const error = new Error('The request was aborted')
|
||||
error.name = 'AbortError'
|
||||
return error
|
||||
}
|
||||
|
||||
function wait(ms: number) {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms))
|
||||
}
|
||||
|
||||
function responseToCachePayload<T>(
|
||||
response: LSPluginNetResponse<T>
|
||||
): NetResponsePayload<T> {
|
||||
return {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
ok: response.ok,
|
||||
url: response.url,
|
||||
headers: { ...response.headers },
|
||||
body: response.body,
|
||||
}
|
||||
}
|
||||
|
||||
function encodeText(value: string) {
|
||||
return new TextEncoder().encode(value).buffer
|
||||
}
|
||||
|
||||
function decodeText(value: ArrayBuffer) {
|
||||
return new TextDecoder().decode(value)
|
||||
}
|
||||
|
||||
function base64ToArrayBuffer(value: string) {
|
||||
const binary = atob(value)
|
||||
const payload = new Uint8Array(binary.length)
|
||||
|
||||
for (let i = 0; i < binary.length; i++) {
|
||||
payload[i] = binary.charCodeAt(i)
|
||||
}
|
||||
|
||||
return payload.buffer
|
||||
}
|
||||
|
||||
function arrayBufferToBase64(value: ArrayBuffer) {
|
||||
const payload = new Uint8Array(value)
|
||||
const chunkSize = 0x8000
|
||||
let binary = ''
|
||||
|
||||
for (let i = 0; i < payload.length; i += chunkSize) {
|
||||
binary += String.fromCharCode(...payload.subarray(i, i + chunkSize))
|
||||
}
|
||||
|
||||
return btoa(binary)
|
||||
}
|
||||
|
||||
function headersToRecord(headers: Headers) {
|
||||
const result: NetHeaders = {}
|
||||
headers.forEach((value, key) => {
|
||||
result[key] = value
|
||||
})
|
||||
return result
|
||||
}
|
||||
|
||||
function bodyToFetchBody(value: unknown): BodyInit | undefined {
|
||||
if (value == null) return undefined
|
||||
if (typeof value === 'string') return value
|
||||
if (value instanceof ArrayBuffer) return value
|
||||
if (ArrayBuffer.isView(value)) return value as BodyInit
|
||||
return JSON.stringify(value)
|
||||
}
|
||||
|
||||
export class LSPluginNetResponse<T = any> {
|
||||
constructor(
|
||||
private _payload: NetResponsePayload<T>,
|
||||
private _responseType: HostResponseType
|
||||
) {}
|
||||
|
||||
get status() {
|
||||
return this._payload.status
|
||||
}
|
||||
|
||||
get statusText() {
|
||||
return this._payload.statusText
|
||||
}
|
||||
|
||||
get ok() {
|
||||
return this._payload.ok
|
||||
}
|
||||
|
||||
get url() {
|
||||
return this._payload.url
|
||||
}
|
||||
|
||||
get headers() {
|
||||
return this._payload.headers
|
||||
}
|
||||
|
||||
get body() {
|
||||
return this._payload.body
|
||||
}
|
||||
|
||||
async json<R = any>(): Promise<R> {
|
||||
const { body } = this._payload
|
||||
|
||||
if (this._responseType === 'json') {
|
||||
return body as unknown as R
|
||||
}
|
||||
|
||||
if (typeof body === 'string') {
|
||||
return JSON.parse(body) as R
|
||||
}
|
||||
|
||||
if (body instanceof ArrayBuffer) {
|
||||
return JSON.parse(decodeText(body)) as R
|
||||
}
|
||||
|
||||
return body as unknown as R
|
||||
}
|
||||
|
||||
async text(): Promise<string> {
|
||||
const { body } = this._payload
|
||||
|
||||
if (typeof body === 'string') {
|
||||
return body
|
||||
}
|
||||
|
||||
if (body instanceof ArrayBuffer) {
|
||||
return decodeText(body)
|
||||
}
|
||||
|
||||
return JSON.stringify(body)
|
||||
}
|
||||
|
||||
async arrayBuffer(): Promise<ArrayBuffer> {
|
||||
const { body } = this._payload
|
||||
|
||||
if (body instanceof ArrayBuffer) {
|
||||
return body
|
||||
}
|
||||
|
||||
if (this._responseType === 'base64' && typeof body === 'string') {
|
||||
return base64ToArrayBuffer(body)
|
||||
}
|
||||
|
||||
if (typeof body === 'string') {
|
||||
return encodeText(body)
|
||||
}
|
||||
|
||||
return encodeText(JSON.stringify(body))
|
||||
}
|
||||
|
||||
clone(): LSPluginNetResponse<T> {
|
||||
return new LSPluginNetResponse(
|
||||
responseToCachePayload(this),
|
||||
this._responseType
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
export class LSPluginNetError<T = any> extends Error {
|
||||
constructor(public response: LSPluginNetResponse<T>) {
|
||||
super(
|
||||
`HTTP request failed with status ${response.status} ${response.statusText}`.trim()
|
||||
)
|
||||
this.name = 'LSPluginNetError'
|
||||
}
|
||||
|
||||
get status() {
|
||||
return this.response.status
|
||||
}
|
||||
|
||||
get statusText() {
|
||||
return this.response.statusText
|
||||
}
|
||||
|
||||
get url() {
|
||||
return this.response.url
|
||||
}
|
||||
|
||||
get headers() {
|
||||
return this.response.headers
|
||||
}
|
||||
|
||||
get body() {
|
||||
return this.response.body
|
||||
}
|
||||
}
|
||||
|
||||
function responseBodyOrThrow<T>(response: LSPluginNetResponse<T>) {
|
||||
if (response.status >= 200 && response.status < 300) {
|
||||
return response.body
|
||||
}
|
||||
|
||||
throw new LSPluginNetError(response)
|
||||
}
|
||||
|
||||
/**
|
||||
* HTTP client for plugins. Desktop requests are proxied by the host process so
|
||||
* iframe plugins can avoid browser CORS limitations. Web requests fall back to
|
||||
* browser fetch and are subject to normal CORS rules.
|
||||
*/
|
||||
export class LSPluginNet {
|
||||
private _cache = new Map<string, CacheEntry>()
|
||||
private _events = new EventTarget()
|
||||
|
||||
constructor(private _ctx: LSPluginUser) {
|
||||
this._ctx.caller.on(CLIENT_MSG_CALLBACK, (e: any) => {
|
||||
const reqId = e?.requestId
|
||||
if (!reqId) return
|
||||
|
||||
this._events.dispatchEvent(
|
||||
new CustomEvent(genTaskCallbackType(reqId), { detail: e?.payload })
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
async request<T = any>(
|
||||
options: NetRequestOptions
|
||||
): Promise<LSPluginNetResponse<T>> {
|
||||
const method = (options.method || 'GET').toUpperCase() as NetMethod
|
||||
const responseType = normalizeResponseType(options.responseType)
|
||||
const retry = this.normalizeRetry(options.retry)
|
||||
const cacheKey = this.getCacheKey(options, method, responseType)
|
||||
|
||||
if (cacheKey) {
|
||||
const cached = this._cache.get(cacheKey)
|
||||
|
||||
if (cached && cached.expires > Date.now()) {
|
||||
this._cache.delete(cacheKey)
|
||||
this._cache.set(cacheKey, cached)
|
||||
return cached.response.clone()
|
||||
}
|
||||
|
||||
cached && this._cache.delete(cacheKey)
|
||||
}
|
||||
|
||||
let attempt = 0
|
||||
|
||||
while (true) {
|
||||
try {
|
||||
const response = await this.performRequest<T>(
|
||||
options,
|
||||
method,
|
||||
responseType
|
||||
)
|
||||
|
||||
if (attempt < retry.retries && this.shouldRetry(retry, response)) {
|
||||
await wait(retry.delay * Math.pow(retry.factor, attempt++))
|
||||
continue
|
||||
}
|
||||
|
||||
if (cacheKey) {
|
||||
this.pruneCache(this.getCacheMaxEntries(options.cache))
|
||||
this._cache.set(cacheKey, {
|
||||
expires: Date.now() + this.getCacheTTL(options.cache),
|
||||
response: response.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
return response
|
||||
} catch (e: any) {
|
||||
if (
|
||||
options.signal?.aborted ||
|
||||
attempt >= retry.retries ||
|
||||
!this.shouldRetry(retry, e)
|
||||
) {
|
||||
throw e
|
||||
}
|
||||
|
||||
await wait(retry.delay * Math.pow(retry.factor, attempt++))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
get<T = any>(
|
||||
url: string,
|
||||
options?: NetRequestConfig
|
||||
): Promise<T> {
|
||||
return this.requestWithMethod<T>('GET', url, options)
|
||||
}
|
||||
|
||||
head<T = any>(
|
||||
url: string,
|
||||
options?: NetRequestConfig
|
||||
): Promise<T> {
|
||||
return this.requestWithMethod<T>('HEAD', url, options)
|
||||
}
|
||||
|
||||
post<T = any, TBody = any>(
|
||||
url: string,
|
||||
body?: NetRequestBody<TBody>,
|
||||
options?: NetRequestConfig<TBody>
|
||||
): Promise<T> {
|
||||
return this.requestWithBody<T, TBody>('POST', url, body, options)
|
||||
}
|
||||
|
||||
put<T = any, TBody = any>(
|
||||
url: string,
|
||||
body?: NetRequestBody<TBody>,
|
||||
options?: NetRequestConfig<TBody>
|
||||
): Promise<T> {
|
||||
return this.requestWithBody<T, TBody>('PUT', url, body, options)
|
||||
}
|
||||
|
||||
patch<T = any, TBody = any>(
|
||||
url: string,
|
||||
body?: NetRequestBody<TBody>,
|
||||
options?: NetRequestConfig<TBody>
|
||||
): Promise<T> {
|
||||
return this.requestWithBody<T, TBody>('PATCH', url, body, options)
|
||||
}
|
||||
|
||||
delete<T = any, TBody = any>(
|
||||
url: string,
|
||||
options?: NetRequestConfig<TBody>
|
||||
): Promise<T> {
|
||||
return this.requestWithMethod<T, TBody>('DELETE', url, options)
|
||||
}
|
||||
|
||||
private requestWithMethod<T = any, TBody = any>(
|
||||
method: NetMethod,
|
||||
url: string,
|
||||
options: NetRequestConfig<TBody> = {}
|
||||
) {
|
||||
return this.request<T>({
|
||||
...options,
|
||||
url,
|
||||
method,
|
||||
}).then(responseBodyOrThrow)
|
||||
}
|
||||
|
||||
private requestWithBody<T = any, TBody = any>(
|
||||
method: Extract<NetMethod, 'POST' | 'PUT' | 'PATCH'>,
|
||||
url: string,
|
||||
body?: NetRequestBody<TBody>,
|
||||
options: NetRequestConfig<TBody> = {}
|
||||
) {
|
||||
const requestBody = typeof body === 'undefined' ? options.body : body
|
||||
|
||||
return this.request<T>({
|
||||
...options,
|
||||
url,
|
||||
method,
|
||||
body: requestBody,
|
||||
}).then(responseBodyOrThrow)
|
||||
}
|
||||
|
||||
private async performRequest<T>(
|
||||
options: NetRequestOptions,
|
||||
method: NetMethod,
|
||||
responseType: HostResponseType
|
||||
) {
|
||||
if (this.shouldUseFetchFallback()) {
|
||||
return this.performFetchRequest<T>(options, method, responseType)
|
||||
}
|
||||
|
||||
try {
|
||||
return await this.performProxyRequest<T>(options, method, responseType)
|
||||
} catch (e) {
|
||||
if (this.shouldFallbackAfterProxyError(e)) {
|
||||
return this.performFetchRequest<T>(options, method, responseType)
|
||||
}
|
||||
|
||||
throw e
|
||||
}
|
||||
}
|
||||
|
||||
private async performProxyRequest<T>(
|
||||
options: NetRequestOptions,
|
||||
method: NetMethod,
|
||||
responseType: HostResponseType
|
||||
) {
|
||||
if (options.signal?.aborted) {
|
||||
throw makeAbortError()
|
||||
}
|
||||
|
||||
const abortable = Boolean(options.abortable || options.signal)
|
||||
const reqId = await this._ctx._execCallableAPIAsync(
|
||||
'exper_request',
|
||||
this._ctx.baseInfo.id,
|
||||
{
|
||||
url: options.url,
|
||||
method,
|
||||
headers: options.headers,
|
||||
data: options.body ?? options.data,
|
||||
timeout: options.timeout,
|
||||
returnType: responseType,
|
||||
abortable,
|
||||
includeResponse: true,
|
||||
}
|
||||
)
|
||||
|
||||
if (!reqId) {
|
||||
throw new Error('Host HTTP request proxy is not available')
|
||||
}
|
||||
|
||||
const callbackType = genTaskCallbackType(reqId)
|
||||
const payloadPromise = new Promise<NetResponsePayload<T>>(
|
||||
(resolve, reject) => {
|
||||
const listener = (event: Event) => {
|
||||
const payload = (event as CustomEvent).detail
|
||||
|
||||
this._events.removeEventListener(callbackType, listener)
|
||||
|
||||
if (payload && payload instanceof Error) {
|
||||
reject(payload)
|
||||
} else {
|
||||
resolve(payload)
|
||||
}
|
||||
}
|
||||
|
||||
this._events.addEventListener(callbackType, listener, { once: true })
|
||||
}
|
||||
)
|
||||
const abort = () => this.abortProxyRequest(reqId, abortable)
|
||||
|
||||
options.signal?.addEventListener('abort', abort, { once: true })
|
||||
|
||||
try {
|
||||
const payload = await payloadPromise
|
||||
return new LSPluginNetResponse(payload, responseType)
|
||||
} finally {
|
||||
options.signal?.removeEventListener('abort', abort)
|
||||
}
|
||||
}
|
||||
|
||||
private abortProxyRequest(reqId: HostRequestID, abortable: boolean) {
|
||||
if (!abortable) return
|
||||
this._ctx._execCallableAPI('http_request_abort', reqId)
|
||||
}
|
||||
|
||||
private async performFetchRequest<T>(
|
||||
options: NetRequestOptions,
|
||||
method: NetMethod,
|
||||
responseType: HostResponseType
|
||||
) {
|
||||
if (typeof fetch !== 'function') {
|
||||
throw new Error('Browser fetch is not available')
|
||||
}
|
||||
|
||||
if (options.signal?.aborted) {
|
||||
throw makeAbortError()
|
||||
}
|
||||
|
||||
const timeout =
|
||||
typeof options.timeout === 'number' && options.timeout > 0
|
||||
? options.timeout
|
||||
: undefined
|
||||
const controller = timeout || options.signal ? new AbortController() : null
|
||||
const abort = () => controller?.abort()
|
||||
const timeoutId = timeout ? setTimeout(abort, timeout) : null
|
||||
|
||||
options.signal?.addEventListener('abort', abort, { once: true })
|
||||
|
||||
try {
|
||||
const response = await fetch(options.url, {
|
||||
method,
|
||||
headers: options.headers,
|
||||
body: ['GET', 'HEAD'].includes(method)
|
||||
? undefined
|
||||
: bodyToFetchBody(options.body ?? options.data),
|
||||
signal: controller?.signal || options.signal,
|
||||
})
|
||||
const body = await this.readFetchBody<T>(response, method, responseType)
|
||||
|
||||
return new LSPluginNetResponse<T>(
|
||||
{
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
ok: response.ok,
|
||||
url: response.url,
|
||||
headers: headersToRecord(response.headers),
|
||||
body,
|
||||
},
|
||||
responseType
|
||||
)
|
||||
} finally {
|
||||
if (timeoutId) clearTimeout(timeoutId)
|
||||
options.signal?.removeEventListener('abort', abort)
|
||||
}
|
||||
}
|
||||
|
||||
private async readFetchBody<T>(
|
||||
response: Response,
|
||||
method: NetMethod,
|
||||
responseType: HostResponseType
|
||||
) {
|
||||
if (method === 'HEAD' || response.status === 204 || response.status === 205) {
|
||||
return null as T
|
||||
}
|
||||
|
||||
switch (responseType) {
|
||||
case 'json':
|
||||
return (await response.json()) as T
|
||||
case 'text':
|
||||
return (await response.text()) as T
|
||||
case 'arraybuffer':
|
||||
return (await response.arrayBuffer()) as T
|
||||
case 'base64':
|
||||
return arrayBufferToBase64(await response.arrayBuffer()) as T
|
||||
}
|
||||
}
|
||||
|
||||
private shouldUseFetchFallback() {
|
||||
return Boolean((this._ctx.baseInfo as any)?.webMode)
|
||||
}
|
||||
|
||||
private shouldFallbackAfterProxyError(error: unknown) {
|
||||
return error == null && typeof fetch === 'function'
|
||||
}
|
||||
|
||||
private normalizeRetry(
|
||||
retry?: number | NetRetryOptions
|
||||
): NormalizedRetryOptions {
|
||||
if (typeof retry === 'number') {
|
||||
return { retries: Math.max(0, retry), delay: 300, factor: 2 }
|
||||
}
|
||||
|
||||
return {
|
||||
retries: Math.max(0, retry?.retries || 0),
|
||||
delay: retry?.delay || 300,
|
||||
factor: retry?.factor || 2,
|
||||
retryOn: retry?.retryOn,
|
||||
}
|
||||
}
|
||||
|
||||
private shouldRetry(
|
||||
retry: NormalizedRetryOptions,
|
||||
value: LSPluginNetResponse | Error
|
||||
) {
|
||||
const { retryOn } = retry
|
||||
|
||||
if (typeof retryOn === 'function') {
|
||||
return retryOn(value)
|
||||
}
|
||||
|
||||
if (value instanceof LSPluginNetResponse) {
|
||||
return Array.isArray(retryOn)
|
||||
? retryOn.includes(value.status)
|
||||
: value.status === 429 || value.status >= 500
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
private getCacheKey(
|
||||
options: NetRequestOptions,
|
||||
method: NetMethod,
|
||||
responseType: HostResponseType
|
||||
) {
|
||||
if (!options.cache || !['GET', 'HEAD'].includes(method)) return null
|
||||
|
||||
if (typeof options.cache === 'object' && options.cache.key) {
|
||||
return options.cache.key
|
||||
}
|
||||
|
||||
return JSON.stringify({
|
||||
method,
|
||||
url: options.url,
|
||||
headers: options.headers || {},
|
||||
responseType,
|
||||
})
|
||||
}
|
||||
|
||||
private getCacheTTL(cache: NetRequestOptions['cache']) {
|
||||
return typeof cache === 'object' && typeof cache.ttl === 'number'
|
||||
? Math.max(0, cache.ttl)
|
||||
: DEFAULT_CACHE_TTL
|
||||
}
|
||||
|
||||
private getCacheMaxEntries(cache: NetRequestOptions['cache']) {
|
||||
return typeof cache === 'object' && typeof cache.maxEntries === 'number'
|
||||
? Math.max(1, cache.maxEntries)
|
||||
: DEFAULT_CACHE_MAX_ENTRIES
|
||||
}
|
||||
|
||||
private pruneCache(maxEntries: number) {
|
||||
while (this._cache.size >= maxEntries) {
|
||||
const oldest = this._cache.keys().next().value
|
||||
if (!oldest) return
|
||||
this._cache.delete(oldest)
|
||||
}
|
||||
}
|
||||
|
||||
get ctx(): LSPluginUser {
|
||||
return this._ctx
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
import { IPluginSearchServiceHooks } from '../LSPlugin'
|
||||
import { LSPluginUser } from '../LSPlugin.user'
|
||||
import { isArray, isFunction, mapKeys } from 'lodash-es'
|
||||
|
||||
export class LSPluginSearchService {
|
||||
/**
|
||||
* @param ctx
|
||||
* @param serviceHooks
|
||||
*/
|
||||
constructor(
|
||||
private ctx: LSPluginUser,
|
||||
private serviceHooks: IPluginSearchServiceHooks
|
||||
) {
|
||||
ctx._execCallableAPI(
|
||||
'register-search-service',
|
||||
ctx.baseInfo.id,
|
||||
serviceHooks.name,
|
||||
serviceHooks.options
|
||||
)
|
||||
|
||||
// hook events TODO: remove listeners
|
||||
const wrapHookEvent = (k) => `service:search:${k}:${serviceHooks.name}`
|
||||
|
||||
Object.entries({
|
||||
query: {
|
||||
f: 'onQuery',
|
||||
args: ['graph', 'q', true],
|
||||
reply: true,
|
||||
transformOutput: (data: any) => {
|
||||
// TODO: transform keys?
|
||||
if (isArray(data?.blocks)) {
|
||||
data.blocks = data.blocks.map((it) => {
|
||||
return it && mapKeys(it, (_, k) => `block/${k}`)
|
||||
})
|
||||
}
|
||||
|
||||
return data
|
||||
},
|
||||
},
|
||||
rebuildBlocksIndice: { f: 'onIndiceInit', args: ['graph', 'blocks'] },
|
||||
transactBlocks: { f: 'onBlocksChanged', args: ['graph', 'data'] },
|
||||
truncateBlocks: { f: 'onIndiceReset', args: ['graph'] },
|
||||
removeDb: { f: 'onGraph', args: ['graph'] },
|
||||
}).forEach(([k, v]) => {
|
||||
const hookEvent = wrapHookEvent(k)
|
||||
ctx.caller.on(hookEvent, async (payload: any) => {
|
||||
if (isFunction(serviceHooks?.[v.f])) {
|
||||
let ret = null
|
||||
|
||||
try {
|
||||
ret = await serviceHooks[v.f].apply(
|
||||
serviceHooks,
|
||||
(v.args || []).map((prop: any) => {
|
||||
if (!payload) return
|
||||
if (prop === true) return payload
|
||||
if (payload.hasOwnProperty(prop)) {
|
||||
const ret = payload[prop]
|
||||
delete payload[prop]
|
||||
return ret
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
if (v.transformOutput) {
|
||||
ret = v.transformOutput(ret)
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('[SearchService] ', e)
|
||||
ret = e
|
||||
} finally {
|
||||
if (v.reply) {
|
||||
ctx.caller.call(`${hookEvent}:reply`, ret)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import { LSPluginUser } from '../LSPlugin.user'
|
||||
|
||||
export interface IAsyncStorage {
|
||||
getItem(key: string): Promise<string | undefined>
|
||||
|
||||
setItem(key: string, value: string): Promise<void>
|
||||
|
||||
removeItem(key: string): Promise<void>
|
||||
|
||||
hasItem(key: string): Promise<boolean>
|
||||
|
||||
allKeys(): Promise<Array<string>>
|
||||
|
||||
clear(): Promise<void>
|
||||
}
|
||||
|
||||
/**
|
||||
* A storage based on local files under specific context
|
||||
*/
|
||||
class LSPluginFileStorage implements IAsyncStorage {
|
||||
/**
|
||||
* @param ctx
|
||||
* @param opts
|
||||
*/
|
||||
constructor(
|
||||
private ctx: LSPluginUser,
|
||||
private opts?: {
|
||||
assets: boolean
|
||||
}
|
||||
) {}
|
||||
|
||||
/**
|
||||
* plugin id
|
||||
*/
|
||||
get ctxId() {
|
||||
return this.ctx.baseInfo.id
|
||||
}
|
||||
|
||||
/**
|
||||
* @param key A string as file name that support nested directory
|
||||
* @param value Storage value
|
||||
*/
|
||||
setItem(key: string, value: string | any): Promise<void> {
|
||||
return this.ctx.caller.callAsync(`api:call`, {
|
||||
method: 'write-plugin-storage-file',
|
||||
args: [this.ctxId, key, value, this.opts?.assets],
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* @param key
|
||||
*/
|
||||
getItem(key: string): Promise<string | any> {
|
||||
return this.ctx.caller.callAsync(`api:call`, {
|
||||
method: 'read-plugin-storage-file',
|
||||
args: [this.ctxId, key, this.opts?.assets],
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* @param key
|
||||
*/
|
||||
removeItem(key: string): Promise<void> {
|
||||
return this.ctx.caller.callAsync(`api:call`, {
|
||||
method: 'unlink-plugin-storage-file',
|
||||
args: [this.ctxId, key, this.opts?.assets],
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all path file keys
|
||||
*/
|
||||
allKeys(): Promise<Array<string>> {
|
||||
return this.ctx.caller.callAsync(`api:call`, {
|
||||
method: 'list-plugin-storage-files',
|
||||
args: [this.ctxId, this.opts?.assets],
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears the storage
|
||||
*/
|
||||
clear(): Promise<void> {
|
||||
return this.ctx.caller.callAsync(`api:call`, {
|
||||
method: 'clear-plugin-storage-files',
|
||||
args: [this.ctxId, this.opts?.assets],
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* @param key
|
||||
*/
|
||||
hasItem(key: string): Promise<boolean> {
|
||||
return this.ctx.caller.callAsync(`api:call`, {
|
||||
method: 'exist-plugin-storage-file',
|
||||
args: [this.ctxId, key, this.opts?.assets],
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export { LSPluginFileStorage }
|
||||
@@ -0,0 +1,641 @@
|
||||
// Fork from https://github.com/dollarshaveclub/postmate
|
||||
|
||||
export const messageType = 'application/x-postmate-v1+json'
|
||||
export const defaultRequestTimeout = 10_000
|
||||
export const maxHandshakeRequests = 5
|
||||
|
||||
let _messageId = 0
|
||||
|
||||
const generateNewMessageId = () => ++_messageId
|
||||
const log = (...args: any) => (Postmate.debug ? console.log(...args) : null)
|
||||
const resolveOrigin = (url: string) => {
|
||||
const a = document.createElement('a')
|
||||
a.href = url
|
||||
// file:// URLs always have origin === 'null'; use '*' to allow postMessage
|
||||
if (a.protocol === 'file:') return '*'
|
||||
const protocol = a.protocol.length > 4 ? a.protocol : window.location.protocol
|
||||
const host = a.host.length
|
||||
? a.port === '80' || a.port === '443'
|
||||
? a.hostname
|
||||
: a.host
|
||||
: window.location.host
|
||||
return a.origin || `${protocol}//${host}`
|
||||
}
|
||||
|
||||
const messageTypes = {
|
||||
handshake: 1,
|
||||
'handshake-reply': 1,
|
||||
call: 1,
|
||||
emit: 1,
|
||||
reply: 1,
|
||||
request: 1,
|
||||
}
|
||||
|
||||
export const sanitize = (message: any, allowedOrigin: any) => {
|
||||
if (typeof allowedOrigin === 'string' && allowedOrigin !== '*' && message.origin !== allowedOrigin)
|
||||
return false
|
||||
if (!message.data) return false
|
||||
if (typeof message.data === 'object' && !('postmate' in message.data))
|
||||
return false
|
||||
if (message.data.type !== messageType) return false
|
||||
if (!messageTypes[message.data.postmate]) return false
|
||||
return true
|
||||
}
|
||||
|
||||
export const resolveValue = (model: any, property: string, args: Array<any>) => {
|
||||
// args arguments passed from parent to child function
|
||||
const unwrappedContext =
|
||||
typeof model[property] === 'function'
|
||||
? model[property].apply(null, args)
|
||||
: model[property]
|
||||
return Promise.resolve(unwrappedContext)
|
||||
}
|
||||
|
||||
/**
|
||||
* Composes an API to be used by the parent
|
||||
* @param {Object} info Information on the consumer
|
||||
*/
|
||||
export class ParentAPI {
|
||||
public parent: Window
|
||||
public frame: HTMLIFrameElement
|
||||
public child: Window
|
||||
public events = {}
|
||||
public childOrigin: string
|
||||
public listener: (e: any) => void
|
||||
private readonly messagePort?: MessagePort
|
||||
|
||||
private addTransportListener(handler: (e: any) => void) {
|
||||
if (this.messagePort) {
|
||||
console.debug('[DEBUG] Using MessagePort for communication:', this.frame.src)
|
||||
// MessagePort delivers MessageEvent too, but without origin/source.
|
||||
this.messagePort.addEventListener('message', handler as any)
|
||||
// Some browsers require start() when using addEventListener.
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
|
||||
;(this.messagePort as any).start?.()
|
||||
} else {
|
||||
console.debug('[DEBUG] Using postMessage for communication:', this.frame.src)
|
||||
this.parent.addEventListener('message', handler, false)
|
||||
}
|
||||
}
|
||||
|
||||
private removeTransportListener(handler: (e: any) => void) {
|
||||
if (this.messagePort) {
|
||||
this.messagePort.removeEventListener('message', handler as any)
|
||||
} else {
|
||||
this.parent.removeEventListener('message', handler, false)
|
||||
}
|
||||
}
|
||||
|
||||
private postToChild(payload: any) {
|
||||
if (this.messagePort) {
|
||||
this.messagePort.postMessage(payload)
|
||||
return
|
||||
}
|
||||
this.child.postMessage(payload, this.childOrigin)
|
||||
}
|
||||
|
||||
constructor(info: Postmate) {
|
||||
this.parent = info.parent
|
||||
this.frame = info.frame
|
||||
this.child = info.child
|
||||
this.childOrigin = info.childOrigin
|
||||
this.messagePort = info.messagePort
|
||||
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
log('Parent: Registering API')
|
||||
log('Parent: Awaiting messages...')
|
||||
}
|
||||
|
||||
this.listener = (e) => {
|
||||
// Port messages don't have origin/source, so we only enforce postmate/type.
|
||||
if (this.messagePort) {
|
||||
if (!e?.data) return false
|
||||
if (typeof e.data === 'object' && !('postmate' in e.data)) return false
|
||||
if (e.data.type !== messageType) return false
|
||||
if (!messageTypes[e.data.postmate]) return false
|
||||
} else {
|
||||
if (!sanitize(e, this.childOrigin)) return false
|
||||
}
|
||||
|
||||
/**
|
||||
* the assignments below ensures that e, data, and value are all defined
|
||||
*/
|
||||
const { data, name } = ((e || {}).data || {}).value || {}
|
||||
|
||||
if (e.data.postmate === 'emit') {
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
log(`Parent: Received event emission: ${name}`)
|
||||
}
|
||||
if (name in this.events) {
|
||||
this.events[name].forEach((callback: Function) => {
|
||||
callback.call(this, data)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// NOTE: older SDKs rely on window.postMessage only, so we must
|
||||
// initially add listener on window (messagePort is not set yet at construction time)
|
||||
this.addTransportListener(this.listener)
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
log('Parent: Awaiting event emissions from Child')
|
||||
}
|
||||
}
|
||||
|
||||
get(property: string, ...args: any) {
|
||||
return new Promise((resolve, reject) => {
|
||||
// Extract data from response and kill listeners
|
||||
const uid = generateNewMessageId()
|
||||
const timeoutMs =
|
||||
typeof (Postmate as any).requestTimeout === 'number'
|
||||
? (Postmate as any).requestTimeout
|
||||
: defaultRequestTimeout
|
||||
|
||||
let timer: any
|
||||
const transact = (e) => {
|
||||
if (e?.data?.uid === uid && e.data.postmate === 'reply') {
|
||||
this.removeTransportListener(transact)
|
||||
if (timer) clearTimeout(timer)
|
||||
if (e.data.error) {
|
||||
reject(e.data.error)
|
||||
} else {
|
||||
resolve(e.data.value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Prepare for response from Child...
|
||||
this.addTransportListener(transact)
|
||||
|
||||
if (timeoutMs > 0) {
|
||||
timer = setTimeout(() => {
|
||||
this.removeTransportListener(transact)
|
||||
reject(new Error(`Postmate: request timeout (${timeoutMs}ms)`))
|
||||
}, timeoutMs)
|
||||
}
|
||||
|
||||
// Then ask child for information
|
||||
this.postToChild({
|
||||
postmate: 'request',
|
||||
type: messageType,
|
||||
property,
|
||||
args,
|
||||
uid,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
call(property: string, data: any) {
|
||||
// Send information to the child
|
||||
this.postToChild({
|
||||
postmate: 'call',
|
||||
type: messageType,
|
||||
property,
|
||||
data,
|
||||
})
|
||||
}
|
||||
|
||||
on(eventName: string, callback: Function) {
|
||||
if (!this.events[eventName]) {
|
||||
this.events[eventName] = []
|
||||
}
|
||||
this.events[eventName].push(callback)
|
||||
}
|
||||
|
||||
destroy() {
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
log('Parent: Destroying Postmate instance')
|
||||
}
|
||||
this.removeTransportListener(this.listener)
|
||||
try {
|
||||
this.messagePort?.close()
|
||||
} catch (e) {
|
||||
// ignore
|
||||
}
|
||||
this.frame.parentNode.removeChild(this.frame)
|
||||
}
|
||||
}
|
||||
|
||||
// Composes an API to be used by the child
|
||||
export class ChildAPI {
|
||||
private readonly model: any
|
||||
private parent: Window
|
||||
private readonly parentOrigin: string
|
||||
private child: Window
|
||||
private messagePort?: MessagePort
|
||||
private readonly listener: (e: any) => void
|
||||
|
||||
private addTransportListener(handler: (e: any) => void) {
|
||||
if (this.messagePort) {
|
||||
this.messagePort.addEventListener('message', handler as any)
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
|
||||
;(this.messagePort as any).start?.()
|
||||
} else {
|
||||
this.child.addEventListener('message', handler, false)
|
||||
}
|
||||
}
|
||||
|
||||
private postToParent(payload: any, fallbackEvent?: MessageEvent<any>) {
|
||||
if (this.messagePort) {
|
||||
this.messagePort.postMessage(payload)
|
||||
return
|
||||
}
|
||||
// reply uses the event source/origin, others use stored parentOrigin.
|
||||
if (fallbackEvent?.source) {
|
||||
const replyOrigin = fallbackEvent.origin === 'null' ? '*' : fallbackEvent.origin
|
||||
;(fallbackEvent.source as WindowProxy).postMessage(payload, replyOrigin)
|
||||
} else {
|
||||
this.parent.postMessage(payload, this.parentOrigin)
|
||||
}
|
||||
}
|
||||
|
||||
constructor(info: Model) {
|
||||
this.model = info.model
|
||||
this.parent = info.parent
|
||||
this.parentOrigin = info.parentOrigin
|
||||
this.child = info.child
|
||||
this.messagePort = info.messagePort
|
||||
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
log('Child: Registering API')
|
||||
log('Child: Awaiting messages...')
|
||||
}
|
||||
|
||||
this.listener = (e) => {
|
||||
// Port messages don't have origin/source, so we only enforce postmate/type.
|
||||
if (this.messagePort) {
|
||||
if (!e?.data) return
|
||||
if (typeof e.data === 'object' && !('postmate' in e.data)) return
|
||||
if (e.data.type !== messageType) return
|
||||
if (!messageTypes[e.data.postmate]) return
|
||||
} else {
|
||||
if (!sanitize(e, this.parentOrigin)) return
|
||||
}
|
||||
|
||||
const { property, uid, data, args } = e.data
|
||||
|
||||
if (e.data.postmate === 'call') {
|
||||
if (
|
||||
property in this.model &&
|
||||
typeof this.model[property] === 'function'
|
||||
) {
|
||||
this.model[property](data)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Reply to Parent
|
||||
resolveValue(this.model, property, args)
|
||||
.then((value) => {
|
||||
this.postToParent(
|
||||
{
|
||||
property,
|
||||
postmate: 'reply',
|
||||
type: messageType,
|
||||
uid,
|
||||
value,
|
||||
},
|
||||
e
|
||||
)
|
||||
})
|
||||
.catch((error) => {
|
||||
this.postToParent(
|
||||
{
|
||||
property,
|
||||
postmate: 'reply',
|
||||
type: messageType,
|
||||
uid,
|
||||
error,
|
||||
},
|
||||
e
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
// Initially add listener on window (messagePort is not set yet at construction time)
|
||||
this.addTransportListener(this.listener)
|
||||
|
||||
// Listen for channel ready event to switch transport from window to MessagePort
|
||||
if (!this.messagePort) {
|
||||
const channelReadyHandler = (event: CustomEvent) => {
|
||||
const port = event.detail?.port
|
||||
if (port) {
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
log('Child: Switching from window.postMessage to MessagePort')
|
||||
}
|
||||
|
||||
// Step 1: Remove listener from window to avoid duplicate message handling
|
||||
this.child.removeEventListener('message', this.listener, false)
|
||||
|
||||
// Step 2: Update messagePort reference (this affects this.listener validation logic)
|
||||
this.messagePort = port
|
||||
|
||||
// Step 3: Add the same listener to MessagePort (now all communication goes through port)
|
||||
this.messagePort.addEventListener('message', this.listener as any)
|
||||
;(this.messagePort as any).start?.()
|
||||
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
log('Child: Successfully switched to MessagePort. All future messages will use MessageChannel.')
|
||||
}
|
||||
|
||||
// Step 4: Clean up the channel-ready event listener
|
||||
this.child.removeEventListener('postmate:channel-ready', channelReadyHandler as any)
|
||||
}
|
||||
}
|
||||
this.child.addEventListener('postmate:channel-ready', channelReadyHandler as any)
|
||||
}
|
||||
}
|
||||
|
||||
emit(name: string, data: any) {
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
log(`Child: Emitting Event "${name}"`, data)
|
||||
}
|
||||
this.postToParent({
|
||||
postmate: 'emit',
|
||||
type: messageType,
|
||||
value: {
|
||||
name,
|
||||
data,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
export type PostMateOptions = {
|
||||
container: HTMLElement
|
||||
url: string
|
||||
id?: string
|
||||
classListArray?: Array<string>
|
||||
name?: string
|
||||
model?: any,
|
||||
allow?: string
|
||||
/**
|
||||
* Prefer using MessageChannel/MessagePort after handshake.
|
||||
* Defaults to false to keep backward-compatible behavior with older SDKs.
|
||||
*/
|
||||
enableMessageChannel?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* The entry point of the Parent.
|
||||
*/
|
||||
export class Postmate {
|
||||
static debug = false // eslint-disable-line no-undef
|
||||
static requestTimeout: number = defaultRequestTimeout
|
||||
public container?: HTMLElement
|
||||
public parent: Window
|
||||
public frame: HTMLIFrameElement
|
||||
public child?: Window
|
||||
public childOrigin?: string
|
||||
public url: string
|
||||
public model: any
|
||||
static Model: any
|
||||
|
||||
// Preferred transport after handshake.
|
||||
public messagePort?: MessagePort
|
||||
private readonly enableMessageChannel: boolean
|
||||
|
||||
constructor(opts: PostMateOptions) {
|
||||
this.container = opts.container
|
||||
this.url = opts.url
|
||||
this.parent = window
|
||||
this.frame = document.createElement('iframe')
|
||||
if (opts.id) this.frame.id = opts.id
|
||||
if (opts.name) this.frame.name = opts.name
|
||||
if (opts.allow) this.frame.allow = opts.allow
|
||||
this.frame.classList.add.apply(
|
||||
this.frame.classList,
|
||||
opts.classListArray || []
|
||||
)
|
||||
this.container.appendChild(this.frame)
|
||||
this.child = this.frame.contentWindow
|
||||
this.model = opts.model || {}
|
||||
this.enableMessageChannel = !!opts.enableMessageChannel
|
||||
}
|
||||
|
||||
sendHandshake(url?: string) {
|
||||
url = url || this.url
|
||||
const childOrigin = resolveOrigin(url)
|
||||
let attempt = 0
|
||||
let responseInterval: any
|
||||
return new Promise((resolve, reject) => {
|
||||
const runtimeSupportsMessageChannel =
|
||||
typeof MessageChannel !== 'undefined' &&
|
||||
typeof (MessageChannel as any) === 'function'
|
||||
|
||||
const shouldUseMessageChannel =
|
||||
this.enableMessageChannel && runtimeSupportsMessageChannel
|
||||
|
||||
const reply = (e: any) => {
|
||||
if (!sanitize(e, childOrigin)) return false
|
||||
if (e.data.postmate === 'handshake-reply') {
|
||||
clearInterval(responseInterval)
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
log('Parent: Received handshake reply from Child')
|
||||
}
|
||||
this.parent.removeEventListener('message', reply, false)
|
||||
this.childOrigin = e.origin
|
||||
|
||||
// After successful handshake, establish MessageChannel if enabled and child supports it
|
||||
if (shouldUseMessageChannel) {
|
||||
// Check if child returned a port (child initiated the channel)
|
||||
if (e?.ports?.length) {
|
||||
const returnedPort = e.ports[0]
|
||||
if (returnedPort) {
|
||||
this.messagePort = returnedPort
|
||||
;(this.messagePort as any).start?.()
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
log('Parent: Using MessageChannel returned by child')
|
||||
}
|
||||
}
|
||||
} else if (e.data.acceptsMessageChannel) {
|
||||
// Child signals it accepts MessageChannel, so parent creates and transfers port
|
||||
const channel = new MessageChannel()
|
||||
this.messagePort = channel.port1
|
||||
;(this.messagePort as any).start?.()
|
||||
|
||||
// Send port2 to child in a follow-up message
|
||||
this.child.postMessage(
|
||||
{
|
||||
postmate: 'setup-channel',
|
||||
type: messageType,
|
||||
},
|
||||
childOrigin,
|
||||
[channel.port2]
|
||||
)
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
log('Parent: Sent MessageChannel port to child')
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
log('Parent: Saving Child origin', this.childOrigin)
|
||||
}
|
||||
return resolve(new ParentAPI(this))
|
||||
}
|
||||
|
||||
// Might need to remove since parent might be receiving different messages
|
||||
// from different hosts
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
log('Parent: Invalid handshake reply')
|
||||
}
|
||||
return reject('Failed handshake')
|
||||
}
|
||||
|
||||
this.parent.addEventListener('message', reply, false)
|
||||
|
||||
const doSend = () => {
|
||||
attempt++
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
log(`Parent: Sending handshake attempt ${attempt}`, { childOrigin })
|
||||
}
|
||||
|
||||
// Always use window.postMessage for handshake to maintain backward compatibility
|
||||
const payload: any = {
|
||||
postmate: 'handshake',
|
||||
type: messageType,
|
||||
model: this.model,
|
||||
// Signal to child that parent supports MessageChannel
|
||||
enableMessageChannel: shouldUseMessageChannel ? 1 : 0,
|
||||
}
|
||||
|
||||
this.child.postMessage(payload, childOrigin)
|
||||
|
||||
if (attempt === maxHandshakeRequests) {
|
||||
clearInterval(responseInterval)
|
||||
}
|
||||
}
|
||||
|
||||
const loaded = () => {
|
||||
doSend()
|
||||
responseInterval = setInterval(doSend, 500)
|
||||
}
|
||||
|
||||
this.frame.addEventListener('load', loaded)
|
||||
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
log('Parent: Loading frame', { url })
|
||||
}
|
||||
this.frame.src = url
|
||||
})
|
||||
}
|
||||
|
||||
destroy() {
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
log('Postmate: Destroying Postmate instance')
|
||||
}
|
||||
try {
|
||||
this.messagePort?.close()
|
||||
} catch (e) {
|
||||
// ignore
|
||||
}
|
||||
this.frame.parentNode.removeChild(this.frame)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The entry point of the Child
|
||||
*/
|
||||
export class Model {
|
||||
public child: Window
|
||||
public model: any
|
||||
public parent: Window
|
||||
public parentOrigin: string
|
||||
public messagePort?: MessagePort
|
||||
private enableMessageChannel: boolean
|
||||
|
||||
constructor(model: any) {
|
||||
this.child = window
|
||||
this.model = model
|
||||
this.parent = this.child.parent
|
||||
// Child side is controlled by what parent sends in handshake; default false.
|
||||
this.enableMessageChannel = false
|
||||
}
|
||||
|
||||
sendHandshakeReply() {
|
||||
return new Promise((resolve, reject) => {
|
||||
const shake = (e: MessageEvent<any>) => {
|
||||
if (!e.data.postmate) {
|
||||
return
|
||||
}
|
||||
if (e.data.postmate === 'handshake') {
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
log('Child: Received handshake from Parent')
|
||||
}
|
||||
this.child.removeEventListener('message', shake, false)
|
||||
|
||||
// Check if parent supports MessageChannel (but don't use it yet during handshake)
|
||||
this.enableMessageChannel = !!e.data?.enableMessageChannel
|
||||
this.parentOrigin = e.origin
|
||||
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
log('Child: Sending handshake reply to Parent')
|
||||
}
|
||||
|
||||
const runtimeSupportsMessageChannel =
|
||||
typeof MessageChannel !== 'undefined' &&
|
||||
typeof (MessageChannel as any) === 'function'
|
||||
|
||||
// Reply using window.postMessage for backward compatibility
|
||||
// Signal whether child accepts MessageChannel for future communication
|
||||
;(e.source as WindowProxy).postMessage(
|
||||
{
|
||||
postmate: 'handshake-reply',
|
||||
type: messageType,
|
||||
// Tell parent if child can accept MessageChannel
|
||||
acceptsMessageChannel: this.enableMessageChannel && runtimeSupportsMessageChannel ? 1 : 0,
|
||||
},
|
||||
e.origin === 'null' ? '*' : e.origin
|
||||
)
|
||||
|
||||
// Extend model with the one provided by the parent
|
||||
const defaults = e.data.model
|
||||
if (defaults) {
|
||||
Object.keys(defaults).forEach((key) => {
|
||||
this.model[key] = defaults[key]
|
||||
})
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
log('Child: Inherited and extended model from Parent')
|
||||
}
|
||||
}
|
||||
|
||||
// Set up listener for MessageChannel port if both sides support it
|
||||
if (this.enableMessageChannel && runtimeSupportsMessageChannel) {
|
||||
const setupChannel = (setupEvent: MessageEvent<any>) => {
|
||||
if (
|
||||
setupEvent.data?.postmate === 'setup-channel' &&
|
||||
setupEvent.data?.type === messageType &&
|
||||
setupEvent.origin === this.parentOrigin
|
||||
) {
|
||||
const transferredPort = setupEvent?.ports?.[0]
|
||||
if (transferredPort) {
|
||||
this.messagePort = transferredPort
|
||||
;(this.messagePort as any).start?.()
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
log('Child: Received and activated MessageChannel port from parent')
|
||||
}
|
||||
|
||||
// Important: Notify the ChildAPI instance (created below) to switch transport
|
||||
// We'll emit a custom event that ChildAPI can listen to
|
||||
this.child.dispatchEvent(new CustomEvent('postmate:channel-ready', {
|
||||
detail: { port: this.messagePort }
|
||||
}))
|
||||
}
|
||||
this.child.removeEventListener('message', setupChannel, false)
|
||||
}
|
||||
}
|
||||
this.child.addEventListener('message', setupChannel, false)
|
||||
}
|
||||
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
log('Child: Saving Parent origin', this.parentOrigin)
|
||||
}
|
||||
return resolve(new ChildAPI(this))
|
||||
}
|
||||
return reject('Handshake Reply Failed')
|
||||
}
|
||||
this.child.addEventListener('message', shake, false)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
/* Visit https://aka.ms/tsconfig.json to read more about this file */
|
||||
|
||||
/* Basic Options */
|
||||
// "incremental": true, /* Enable incremental compilation */
|
||||
"target": "ESNext",
|
||||
/* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
|
||||
"module": "ESNext",
|
||||
/* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
|
||||
// "lib": [], /* Specify library files to be included in the compilation. */
|
||||
"allowJs": true,
|
||||
/* Allow javascript files to be compiled. */
|
||||
// "checkJs": true, /* Report errors in .js files. */
|
||||
"jsx": "react",
|
||||
/* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
|
||||
"declaration": true,
|
||||
/* Generates corresponding '.d.ts' file. */
|
||||
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
|
||||
"sourceMap": false,
|
||||
/* Generates corresponding '.map' file. */
|
||||
// "outFile": "./", /* Concatenate and emit output to single file. */
|
||||
"outDir": "dist",
|
||||
/* Redirect output structure to the directory. */
|
||||
"rootDir": "src",
|
||||
/* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
|
||||
// "composite": true, /* Enable project compilation */
|
||||
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
|
||||
// "removeComments": true, /* Do not emit comments to output. */
|
||||
// "noEmit": true,
|
||||
/* Do not emit outputs. */
|
||||
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
|
||||
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
|
||||
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
|
||||
|
||||
/* Strict Type-Checking Options */
|
||||
// "strict": true,
|
||||
/* Enable all strict type-checking options. */
|
||||
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
|
||||
// "strictNullChecks": true,
|
||||
/* Enable strict null checks. */
|
||||
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
|
||||
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
|
||||
// "strictPropertyInitialization": true,
|
||||
/* Enable strict checking of property initialization in classes. */
|
||||
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
|
||||
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
|
||||
|
||||
/* Additional Checks */
|
||||
// "noUnusedLocals": true, /* Report errors on unused locals. */
|
||||
// "noUnusedParameters": true, /* Report errors on unused parameters. */
|
||||
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
|
||||
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
|
||||
|
||||
/* Module Resolution Options */
|
||||
"moduleResolution": "bundler",
|
||||
/* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
|
||||
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
|
||||
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
|
||||
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
|
||||
// "typeRoots": [], /* List of folders to include type definitions from. */
|
||||
// "types": [], /* Type declaration files to be included in compilation. */
|
||||
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
|
||||
"esModuleInterop": true,
|
||||
/* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
|
||||
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
|
||||
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
|
||||
|
||||
/* Source Map Options */
|
||||
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
|
||||
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
|
||||
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
|
||||
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
|
||||
|
||||
/* Experimental Options */
|
||||
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
|
||||
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
|
||||
|
||||
/* Advanced Options */
|
||||
"skipLibCheck": true,
|
||||
/* Skip type checking of declaration files. */
|
||||
"forceConsistentCasingInFileNames": true
|
||||
/* Disallow inconsistently-cased references to the same file. */
|
||||
},
|
||||
"include": [
|
||||
"src/**/*.ts"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
const webpack = require('webpack')
|
||||
const path = require('path')
|
||||
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
|
||||
|
||||
module.exports = (env, argv) => {
|
||||
const config = {
|
||||
entry: './src/LSPlugin.core.ts',
|
||||
devtool: 'eval',
|
||||
module: {
|
||||
rules: [
|
||||
{
|
||||
test: /\.tsx?$/,
|
||||
use: 'ts-loader',
|
||||
exclude: /node_modules/,
|
||||
},
|
||||
],
|
||||
},
|
||||
resolve: {
|
||||
extensions: ['.tsx', '.ts', '.js'],
|
||||
},
|
||||
plugins: [
|
||||
new webpack.ProvidePlugin({
|
||||
process: 'process/browser',
|
||||
}),
|
||||
],
|
||||
output: {
|
||||
library: 'LSPlugin',
|
||||
libraryTarget: 'umd',
|
||||
filename: 'lsplugin.core.js',
|
||||
path: path.resolve(__dirname, '../resources/js'),
|
||||
},
|
||||
}
|
||||
|
||||
if (argv.mode === 'production') {
|
||||
delete config.devtool
|
||||
config.plugins.push(new BundleAnalyzerPlugin())
|
||||
}
|
||||
|
||||
return config
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
const pkg = require('./package.json')
|
||||
const path = require('path')
|
||||
const webpack = require('webpack')
|
||||
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
|
||||
const TerserPlugin = require('terser-webpack-plugin')
|
||||
|
||||
module.exports = (env, argv) => {
|
||||
const isProd = argv.mode === 'production'
|
||||
|
||||
return {
|
||||
entry: './src/LSPlugin.user.ts',
|
||||
module: {
|
||||
rules: [
|
||||
{
|
||||
test: /\.tsx?$/,
|
||||
use: [
|
||||
{
|
||||
loader: 'babel-loader'
|
||||
},
|
||||
{
|
||||
loader: 'ts-loader'
|
||||
}
|
||||
],
|
||||
exclude: /node_modules/,
|
||||
}
|
||||
],
|
||||
},
|
||||
resolve: {
|
||||
extensions: ['.tsx', '.ts', '.js'],
|
||||
},
|
||||
optimization: {
|
||||
minimize: isProd,
|
||||
minimizer: [
|
||||
new TerserPlugin()
|
||||
]
|
||||
},
|
||||
plugins: [
|
||||
new webpack.ProvidePlugin({
|
||||
process: 'process/browser',
|
||||
}),
|
||||
new webpack.DefinePlugin({
|
||||
LIB_VERSION: JSON.stringify(pkg.version)
|
||||
})
|
||||
// new BundleAnalyzerPlugin()
|
||||
],
|
||||
output: {
|
||||
library: 'LSPluginEntry',
|
||||
libraryTarget: 'umd',
|
||||
filename: 'lsplugin.user.js',
|
||||
path: path.resolve(__dirname, 'dist')
|
||||
},
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user