99dfbbde58
* feat(plugins): add keybindings and modal window capabilities
Add two independent plugin UI capabilities.
Keybindings: plugins declare keybindings in the manifest under
ui.keybindings ({id, default, description}), validated backend-side
(combo grammar + unique ids, requires a UI bundle) and exposed to the
frontend. Plugin JS binds a handler via registry.registerKeybinding(id,
handler); a global dispatcher fires it. Combos are user-overridable in
Settings > Keyboard Shortcuts (namespaced plugin:{pluginId}:{id}) with
conflict detection against core and other plugins.
Modals: host.openModal({title?, content, size?, dismissible?}) returns a
{ close() } handle and renders in a single host-owned Dialog isolated by
PluginErrorBoundary, cleaned up on plugin unload.
Fixture plugin, PLUGIN-API.md / spec, and a Playwright e2e demonstrate a
keybinding handler opening a modal.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(plugins): address review feedback on keybinding dispatch and validation
Core shortcuts now take precedence over plugin keybindings on a colliding
combo (defaultPrevented cooperation between the two capture-phase
dispatchers), a throwing plugin handler no longer aborts dispatch to other
plugins, and the keybinding combo grammar is tightened: the backend validator
and frontend parser both drop the undocumented control/super modifier
aliases and reject shift+digit/symbol combos that can never actually fire
(KeyboardEvent.key reports the shifted character, not the token).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(plugins): stop conflicting core shortcut from double-firing with plugin keybindings
The earlier defaultPrevented guard only covered the central useAppShortcuts
dispatcher. Per-component core shortcuts registered via useKeyboardShortcut
run in the bubble phase, after the capture-phase plugin keybinding dispatcher,
so a plugin-handled-and-prevented combo still triggered the core action too.
Guard useKeyboardShortcut (and use-editor-keybinds, another capture-phase core
listener) on event.defaultPrevented so exactly one action fires per combo.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(plugins): make core shortcuts always win over plugin keybindings
Panel-search, task-switcher, and other core listeners never checked
event.defaultPrevented, so a plugin bound to the same combo (e.g. Cmd/Ctrl+F)
could still fire alongside them. Instead of patching every core listener,
usePluginShortcuts now computes the set of effective core shortcut combos
(registry, resolved through user overrides, plus FIND_IN_PANEL/SAVE) and
skips invoking any plugin handler whose combo is in that set, so the
matching core listener always handles the event exactly once.
Also adds a hook-level regression test for useEditorKeybinds' existing
defaultPrevented guard, and fixes a leaked capture-phase window listener in
use-keyboard-shortcut.test.ts that could bleed into later tests.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* fix(web): keep Cmd+K closing the command panel after shortcut-precedence guard
cmdk's built-in vim bindings intercept Ctrl/Cmd+K and +P as list-navigation
shortcuts and call preventDefault() before the event reaches our window-level
useKeyboardShortcut listeners. Once that hook started bailing on
event.defaultPrevented (added to fix core/plugin shortcut double-firing), the
palette's own Cmd+K close/reopen toggle got silently suppressed whenever focus
was inside the open panel. Disable cmdk's vim bindings on the command palette
so its Ctrl/Cmd+K and +P always reach the app-level toggle.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
* docs(plugins): document keybindings and modal window plugin APIs
Fill in the public author-facing docs that the internal plugin-keybindings
and modal-window contract (PLUGIN-API.md, spec.md) already covers: the
registry.registerKeybinding / host.openModal JS surface, the ui.keybindings
manifest field with its combo grammar, and a capability mention on the
Plugins overview page.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
206 lines
8.0 KiB
TypeScript
206 lines
8.0 KiB
TypeScript
/**
|
|
* Plugin host: the `window.registerKandevPlugin` global + the loader that
|
|
* imports plugin bundles from the boot payload (docs/plans/plugins/PLUGIN-API.md).
|
|
*
|
|
* Loading sequence per bundle: inject `styleUrls` as `<link>` tags, dynamically
|
|
* `import(/* @vite-ignore *\/ bundleUrl)` the bundle (module-level side effect
|
|
* calls `window.registerKandevPlugin`), then call the registered plugin's
|
|
* `initialize(registry, host)`. A bad plugin (throwing bundle, missing
|
|
* registration, or throwing `initialize`) is logged and swallowed — it never
|
|
* breaks boot or blocks other plugins.
|
|
*
|
|
* `registeredPlugins` is never cleared on disable — only on a fresh import
|
|
* (see `resolveRegistration`). The browser's ES module cache means a repeat
|
|
* `import(bundleUrl)` after disable would resolve without re-running the
|
|
* bundle's top-level `registerKandevPlugin` call, so re-enabling in the same
|
|
* tab must reuse the cached registration instead of relying on re-import.
|
|
*/
|
|
import { getBackendConfig } from "@/lib/config";
|
|
import { pluginModalManager } from "./modal-manager";
|
|
import { pluginRegistry } from "./registry";
|
|
import type { ActivePlugin, KandevPlugin, PluginHostApi } from "./types";
|
|
|
|
/** Builds the per-plugin `PluginHostApi` for a given pluginId. */
|
|
export type PluginHostFactory = (pluginId: string) => PluginHostApi;
|
|
|
|
/** Injectable bundle loader — defaults to a real dynamic import. Tests pass a fake. */
|
|
export type BundleImporter = (url: string) => Promise<unknown>;
|
|
|
|
const defaultImporter: BundleImporter = (url) => import(/* @vite-ignore */ url);
|
|
|
|
/**
|
|
* How long `loadPlugin` waits for a single plugin's `initialize(registry, host)`
|
|
* to settle before giving up on it and moving on to the next plugin in the
|
|
* boot list. A plugin whose `initialize()` never resolves must not be able to
|
|
* stall every plugin queued behind it.
|
|
*/
|
|
const DEFAULT_INITIALIZE_TIMEOUT_MS = 10_000;
|
|
|
|
/**
|
|
* Races `promise` against a `timeoutMs` timer. Resolves with `promise`'s
|
|
* value (or rejects with its error) if it settles first; otherwise calls
|
|
* `onTimeout` and resolves with `undefined` once the timer fires — a timeout
|
|
* is deliberately not a rejection, so the caller's loop can continue to the
|
|
* next plugin instead of routing a hang through the same error-handling path
|
|
* as a thrown/rejected `initialize()`. The original promise is not
|
|
* cancelled; if it eventually settles nothing observes it.
|
|
*/
|
|
function raceTimeout<T>(
|
|
promise: Promise<T>,
|
|
timeoutMs: number,
|
|
onTimeout: () => void,
|
|
): Promise<T | void> {
|
|
return new Promise((resolve, reject) => {
|
|
const timer = setTimeout(() => {
|
|
onTimeout();
|
|
resolve();
|
|
}, timeoutMs);
|
|
promise.then(
|
|
(value) => {
|
|
clearTimeout(timer);
|
|
resolve(value);
|
|
},
|
|
(error: unknown) => {
|
|
clearTimeout(timer);
|
|
reject(error as Error);
|
|
},
|
|
);
|
|
});
|
|
}
|
|
|
|
type PluginGlobalWindow = Window & {
|
|
registerKandevPlugin?: (id: string, plugin: KandevPlugin) => void;
|
|
};
|
|
|
|
/** Bundles registered via `window.registerKandevPlugin`, keyed by pluginId. */
|
|
const registeredPlugins = new Map<string, KandevPlugin>();
|
|
|
|
/** Defines `window.registerKandevPlugin` before any bundle loads. Idempotent. */
|
|
export function installPluginGlobal(win: Window = window): void {
|
|
(win as PluginGlobalWindow).registerKandevPlugin = (id, plugin) => {
|
|
registeredPlugins.set(id, plugin);
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Loads every plugin from the boot payload: injects styles, imports the
|
|
* bundle, then runs `initialize(registry, host)`. Each plugin is isolated —
|
|
* a failure anywhere in its load path is logged and does not affect the
|
|
* others or the boot sequence. `initTimeoutMs` (default
|
|
* `DEFAULT_INITIALIZE_TIMEOUT_MS`) bounds how long a single plugin's
|
|
* `initialize()` can block the (sequential) loop before the loader gives up
|
|
* on it and moves on — tests inject a short value instead of waiting out the
|
|
* real default.
|
|
*/
|
|
export async function loadPlugins(
|
|
bootPlugins: ActivePlugin[],
|
|
hostFactory: PluginHostFactory,
|
|
importer: BundleImporter = defaultImporter,
|
|
win: Window = window,
|
|
initTimeoutMs: number = DEFAULT_INITIALIZE_TIMEOUT_MS,
|
|
): Promise<void> {
|
|
installPluginGlobal(win);
|
|
for (const plugin of bootPlugins) {
|
|
await loadPlugin(plugin, hostFactory, importer, initTimeoutMs);
|
|
}
|
|
}
|
|
|
|
async function loadPlugin(
|
|
plugin: ActivePlugin,
|
|
hostFactory: PluginHostFactory,
|
|
importer: BundleImporter,
|
|
initTimeoutMs: number,
|
|
): Promise<void> {
|
|
const { apiBaseUrl } = getBackendConfig();
|
|
try {
|
|
injectStyles(plugin.id, plugin.styleUrls, apiBaseUrl);
|
|
const registered = await resolveRegistration(plugin, importer, apiBaseUrl);
|
|
if (!registered) {
|
|
console.error(`[plugins] "${plugin.id}" bundle did not call registerKandevPlugin`);
|
|
return;
|
|
}
|
|
const host = hostFactory(plugin.id);
|
|
const registry = pluginRegistry.forPlugin(plugin.id, plugin.name);
|
|
await raceTimeout(Promise.resolve(registered.initialize(registry, host)), initTimeoutMs, () => {
|
|
console.warn(
|
|
`[plugins] "${plugin.id}" initialize() timed out after ${initTimeoutMs}ms; continuing without it`,
|
|
);
|
|
});
|
|
} catch (error) {
|
|
console.error(`[plugins] failed to load plugin "${plugin.id}"`, error);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Returns the plugin's registration, importing the bundle only when it
|
|
* isn't already cached from a prior load in this tab (see module doc for
|
|
* why re-enable must not blindly re-import).
|
|
*/
|
|
async function resolveRegistration(
|
|
plugin: ActivePlugin,
|
|
importer: BundleImporter,
|
|
apiBaseUrl: string,
|
|
): Promise<KandevPlugin | undefined> {
|
|
const cached = registeredPlugins.get(plugin.id);
|
|
if (cached) return cached;
|
|
await importer(resolvePluginUrl(plugin.bundleUrl, apiBaseUrl));
|
|
return registeredPlugins.get(plugin.id);
|
|
}
|
|
|
|
/**
|
|
* Prefixes a root-relative plugin asset URL with the backend origin. Plain
|
|
* root-relative URLs only resolve correctly when the SPA and the API share
|
|
* an origin (same-origin production); split-origin dev and the Tauri
|
|
* desktop shell need the explicit `apiBaseUrl`, same as `host.api.fetch`.
|
|
*/
|
|
function resolvePluginUrl(url: string, apiBaseUrl: string): string {
|
|
if (!apiBaseUrl || !url.startsWith("/")) return url;
|
|
return `${apiBaseUrl}${url}`;
|
|
}
|
|
|
|
function injectStyles(pluginId: string, styleUrls: string[] | undefined, apiBaseUrl: string): void {
|
|
if (!styleUrls) return;
|
|
for (const href of styleUrls) {
|
|
const link = document.createElement("link");
|
|
link.rel = "stylesheet";
|
|
link.href = resolvePluginUrl(href, apiBaseUrl);
|
|
link.dataset.pluginId = pluginId;
|
|
document.head.appendChild(link);
|
|
}
|
|
}
|
|
|
|
/** Removes every `<link>` this plugin injected via `injectStyles`. */
|
|
function removeStyles(pluginId: string): void {
|
|
document.querySelectorAll(`link[data-plugin-id="${pluginId}"]`).forEach((link) => link.remove());
|
|
}
|
|
|
|
/**
|
|
* Disables a plugin: calls `destroy?.()`, bulk-revokes its registry
|
|
* registrations, and removes its injected stylesheets. By default this
|
|
* keeps the `registeredPlugins` entry — see module doc — so a later
|
|
* re-enable in the same tab can re-run `initialize` without depending on the
|
|
* browser re-executing the bundle's module-eval side effect.
|
|
*
|
|
* Pass `evictCache: true` for the install/update path specifically: an
|
|
* updated package can ship new bundle code under the same `bundleUrl`, so
|
|
* the cached registration (and, with it, the stale `initialize`/`destroy`
|
|
* closures from the previous version) must be dropped so the next
|
|
* `loadPlugin` re-imports it. This is opt-in — unconditional eviction here
|
|
* would break the plain disable/re-enable cycle's cached-registration reuse.
|
|
*/
|
|
export function unloadPlugin(id: string, options?: { evictCache?: boolean }): void {
|
|
const plugin = registeredPlugins.get(id);
|
|
try {
|
|
plugin?.destroy?.();
|
|
} catch (error) {
|
|
console.error(`[plugins] error destroying plugin "${id}"`, error);
|
|
} finally {
|
|
pluginRegistry.unregisterPlugin(id);
|
|
pluginModalManager.closeAllForPlugin(id);
|
|
removeStyles(id);
|
|
if (options?.evictCache) {
|
|
registeredPlugins.delete(id);
|
|
}
|
|
}
|
|
}
|