DinoxDinox AI笔记

TypeScript 类型参考

atomd 插件 API 1 的完整 TypeScript 类型:笔记、修改、视图元素、侧边栏内容、事件,以及带类型的调用封装 atomd.ts。

NSH 的 host.call / host.on 本身不知道 atomd 有哪些接口。示例插件里的 atomd.ts 把 atomd 的 Host API 包成了带类型的函数。把下面的内容保存为插件目录里的 atomd.ts,然后:

import { readNote, listNotes, getMetadata, insertAtCursor, renderSidebar, onNoteEdited } from "./atomd";

nsh check . 会用这些类型检查你的代码,比如视图元素的字段写错、图标名拼错都会报错。

函数一览

函数对应接口需要的权限
readNote(): Promise<Note | null>atomd.note.readatomd.note.read
applyEdits(path, edits): Promise<null>atomd.note.applyEditsatomd.note.applyEdits
listNotes(folder?): Promise<NoteInfo[]>atomd.vault.listatomd.vault.list
readNoteAt(path): Promise<{path, title, markdown}>atomd.vault.readatomd.vault.read
createNote(path, markdown): Promise<{path}>atomd.vault.createatomd.vault.create
modifyNote(path, edits): Promise<null>atomd.vault.modifyatomd.vault.modify
renameNote(from, to): Promise<{path, updated}>atomd.vault.renameatomd.vault.rename
getMetadata(path): Promise<Metadata>atomd.metadata.getatomd.metadata.get
getBacklinks(path): Promise<{path, title}[]>atomd.metadata.backlinksatomd.metadata.backlinks
insertAtCursor(path, text): Promise<null>atomd.editor.insertatomd.editor.insert
renderSidebar(content): voidatomd.ui.renderatomd.ui.render
notify(message): voidatomd.ui.notifyatomd.ui.notify
onNoteChanged(fn): () => void事件 atomd.note.changedatomd.note.read
onNoteEdited(fn): () => void事件 atomd.note.editedatomd.note.read
onViewEvent(fn): () => void事件 atomd.view.event
onCommand(fn): () => void事件 atomd.command,fn(id, context)
openNote(path, at?): Promise<null>atomd.workspace.openatomd.workspace.open
getSettings<T>(): Promise<T>atomd.settings.get声明了设置项即可
setSetting(key, value): Promise<null>atomd.settings.set声明了设置项即可
onSettingsChanged(fn): () => void事件 atomd.settings.changed
prompt(title, opts?): Promise<string | null>atomd.ui.promptatomd.ui.prompt
confirm(title, opts?): Promise<boolean>atomd.ui.confirmatomd.ui.confirm
pick(items, opts?): Promise<string | null>atomd.ui.pickatomd.ui.pick
setStatus(text, opts?): voidatomd.ui.statusatomd.ui.status
paramshost.params

on… 函数返回一个取消监听的函数。所有路径都相对笔记库根目录,见 Host API · 路径。

主要类型

类型字段
NoteRefpath、title
NoteNoteRef 加上 markdown、selection
NoteInfopath、title、size、mtime
Metadatafrontmatter(带类型的 JSON)、frontmatterError?、headings、links、tags、tasks
SettingSpeckey、type、title、description?、default?、options?、placeholder?
PickItemid、label、detail?、icon?
CommandContextpath、selection?
Editfind、replace
SidebarContentactions、body、footer、follow
Element所有视图元素的联合类型,见 视图
ViewEventview、id、action、value

例子:给笔记库做一份标签索引

import { createNote, getMetadata, listNotes, notify } from "./atomd";

const notes = await listNotes();
const byTag = new Map<string, string[]>();
for (const n of notes) {
  const { tags } = await getMetadata(n.path);
  for (const t of tags) byTag.set(t, [...(byTag.get(t) ?? []), n.title]);
}
const md = [...byTag].sort().map(([t, titles]) =>
  `## #${t}\n\n${titles.map((x) => `- [[${x}]]`).join("\n")}`).join("\n\n");
await createNote(`Tag index ${Date.now()}.md`, `# Tag index\n\n${md}\n`);
notify(`Indexed ${notes.length} notes`);

需要的权限:atomd.vault.list、atomd.metadata.get、atomd.vault.create、atomd.ui.notify。

atomd.ts

atomd.ts
// Typed helpers for atomd's plugin API 1 (https://dinox.info/guides/atomd-plugins/host-api).
// Copy this file into your plugin; it only wraps `host` from "nsh".
import { host } from "nsh";

export type NoteRef = { path: string; title: string };
export type Note = NoteRef & { markdown: string; selection: string | null };
export type Edit = { find: string; replace: string };
export type NoteInfo = { path: string; title: string; size: number; mtime: number };
export type Metadata = {
  /** The YAML as typed JSON (`{}` when there is none); null when it doesn't parse. */
  frontmatter: Record<string, unknown> | null;
  /** Why the front matter didn't parse; only then. */
  frontmatterError?: string;
  headings: { level: number; text: string; line: number }[];
  links: { target: string; text: string | null }[];
  tags: string[];
  tasks: { text: string; done: boolean; line: number }[];
};

/** One of `contributes.settings` in manifest.json. */
export type SettingSpec = {
  key: string;
  type: "string" | "number" | "boolean" | "select" | "secret";
  title: string;
  description?: string;
  default?: unknown;
  options?: { value: unknown; label: string }[];
  placeholder?: string;
};

export type PickItem = { id: string; label: string; detail?: string; icon?: IconName };

/** Where a command ran: the open note (quick open, a hotkey) or the menu's note, and the selected text from the editor's menu. */
export type CommandContext = { path: string | null; selection?: string };

export type Tone = "muted" | "faint" | "danger" | "accent";
export type IconName =
  | "sparkles" | "rotate" | "x" | "arrow-up" | "stop" | "note" | "check" | "plus"
  | "search" | "copy" | "trash" | "link" | "list" | "todo" | "settings" | "folder";

export type Element =
  | { type: "column" | "row"; children: Element[]; gap?: number; justify?: "start" | "center" | "end" | "between" }
  | { type: "card" | "bubble" | "composer"; children: Element[] }
  | {
      type: "text"; text: string; tone?: Tone; size?: "xs" | "sm" | "lg";
      weight?: "medium" | "semibold"; mono?: boolean; strike?: boolean; center?: boolean;
    }
  | { type: "icon"; name: IconName; size?: number; tone?: Tone }
  | { type: "chip"; text: string; icon?: IconName }
  | { type: "status"; text: string }
  | { type: "empty"; icon?: IconName; title: string; text?: string }
  | { type: "diff"; before: string; after: string }
  | { type: "divider" }
  | { type: "button"; id: string; label: string; variant?: "primary"; submits?: string }
  | { type: "icon_button"; id: string; icon: IconName; label: string; variant?: "round" }
  | { type: "input"; id: string; placeholder?: string; multiline?: boolean; autofocus?: boolean };

export type SidebarContent = {
  actions?: { id: string; icon: IconName; label: string }[];
  body?: Element[];
  footer?: Element[];
  follow?: boolean;
};

export type ViewEvent = { view: string; id: string; action: "press" | "submit"; value: string | null };

export const params = host.params as { api: number; pluginId: string; vault: string };

/** The open note as in the editor (unsaved typing included), or null. Needs `atomd.note.read`. */
export const readNote = () => host.call<Note | null>("atomd.note.read");

/** Replaces each `find` (which must occur once) with `replace`, as one undo step. Needs `atomd.note.applyEdits`. */
export const applyEdits = (path: string, edits: Edit[]) =>
  host.call<null>("atomd.note.applyEdits", { path, edits });

/** Replaces what the sidebar shows. Needs `atomd.ui.render`. */
export const renderSidebar = (content: SidebarContent) =>
  host.post("atomd.ui.render", { view: "sidebar", content });

/** Shows a toast. Needs `atomd.ui.notify`. */
export const notify = (message: string) => host.post("atomd.ui.notify", { message });

/** The notes under `folder` (vault-relative; default the whole vault), by path. Needs `atomd.vault.list`. */
export const listNotes = (folder?: string) =>
  host.call<NoteInfo[]>("atomd.vault.list", folder === undefined ? {} : { folder });

/** Any note by its vault-relative path (the open one as in the editor). Needs `atomd.vault.read`. */
export const readNoteAt = (path: string) =>
  host.call<{ path: string; title: string; markdown: string }>("atomd.vault.read", { path });

/** Makes a note (and its folders); rejects if it exists. Needs `atomd.vault.create`. */
export const createNote = (path: string, markdown: string) =>
  host.call<{ path: string }>("atomd.vault.create", { path, markdown });

/** `applyEdits` for any note, open or not. Needs `atomd.vault.modify`. */
export const modifyNote = (path: string, edits: Edit[]) =>
  host.call<null>("atomd.vault.modify", { path, edits });

/** Moves a note and the links to it (`updated`: the notes changed); rejects if `to` exists. Needs `atomd.vault.rename`. */
export const renameNote = (from: string, to: string) =>
  host.call<{ path: string; updated: string[] }>("atomd.vault.rename", { from, to });

/** A note's front matter, headings, links, tags and tasks. Needs `atomd.metadata.get`. */
export const getMetadata = (path: string) => host.call<Metadata>("atomd.metadata.get", { path });

/** The notes linking to a note. Needs `atomd.metadata.backlinks`. */
export const getBacklinks = (path: string) =>
  host.call<{ path: string; title: string }[]>("atomd.metadata.backlinks", { path });

/** Inserts at the open note's cursor (lines as Markdown blocks), one undo step. Needs `atomd.editor.insert`. */
export const insertAtCursor = (path: string, text: string) =>
  host.call<null>("atomd.editor.insert", { path, text });

/** The open note's text changed in the editor, 500 ms after edits stop (needs `atomd.note.read`). */
export const onNoteEdited = (fn: (note: NoteRef) => void) =>
  host.on<{ note: NoteRef }>("atomd.note.edited", (d) => fn(d.note));

/** At start and whenever the open note changes (needs `atomd.note.read`). */
export const onNoteChanged = (fn: (note: NoteRef | null) => void) =>
  host.on<{ note: NoteRef | null }>("atomd.note.changed", (d) => fn(d.note));

/** The user pressed a button or submitted an input of one of your views. */
export const onViewEvent = (fn: (e: ViewEvent) => void) => host.on<ViewEvent>("atomd.view.event", fn);

/** The user ran one of the commands in your manifest (quick open, a hotkey or a menu). */
export const onCommand = (fn: (id: string, context: CommandContext) => void) =>
  host.on<{ id: string; context: CommandContext }>("atomd.command", (d) =>
    fn(d.id, d.context ?? { path: null }),
  );

/** Your settings, defaults filled in. Needs `contributes.settings` (no declaration). */
export const getSettings = <T extends Record<string, unknown> = Record<string, unknown>>() =>
  host.call<T>("atomd.settings.get");

/** Sets one of your settings; rejects an unknown key or a wrong type. Needs `contributes.settings` (no declaration). */
export const setSetting = (key: string, value: unknown) =>
  host.call<null>("atomd.settings.set", { key, value });

/** The user changed one of your settings in Settings. Needs `contributes.settings` (no declaration). */
export const onSettingsChanged = (fn: (key: string, value: unknown) => void) =>
  host.on<{ key: string; value: unknown }>("atomd.settings.changed", (d) => fn(d.key, d.value));

/** Asks for text; null when cancelled. Waits for the user (no timeout). Needs `atomd.ui.prompt`. */
export const prompt = (
  title: string,
  opts: { placeholder?: string; value?: string; multiline?: boolean; confirmLabel?: string } = {},
) => host.call<string | null>("atomd.ui.prompt", { title, ...opts }, { timeout: 0 });

/** Asks to confirm; false when cancelled. Waits for the user (no timeout). Needs `atomd.ui.confirm`. */
export const confirm = (
  title: string,
  opts: { message?: string; confirmLabel?: string; danger?: boolean } = {},
) => host.call<boolean>("atomd.ui.confirm", { title, ...opts }, { timeout: 0 });

/** Lets the user pick one of up to 5000 items (fuzzy filter); its id, null when cancelled. Needs `atomd.ui.pick`. */
export const pick = (items: PickItem[], opts: { title?: string; placeholder?: string } = {}) =>
  host.call<string | null>("atomd.ui.pick", { items, ...opts }, { timeout: 0 });

/** Sets your status bar item, or removes it with null; pressing it sends a "status" view event. Needs `atomd.ui.status`. */
export const setStatus = (text: string | null, opts: { tooltip?: string; icon?: IconName } = {}) =>
  host.post("atomd.ui.status", text === null ? { text: null } : { text, ...opts });

/** Opens a note, the cursor at a 0-based line or a heading. Needs `atomd.workspace.open`. */
export const openNote = (path: string, at: { line?: number; heading?: string } = {}) =>
  host.call<null>("atomd.workspace.open", { path, ...at });

On this page