diff --git a/.gitignore b/.gitignore index 48e07a8fc9a..1df000ce846 100644 --- a/.gitignore +++ b/.gitignore @@ -100,6 +100,7 @@ storybook-static # MCP Servers .playwright-mcp/* +/tools/devtools/web/widgetAugmentations.js vite.config.*.timestamp* vitest.config.*.timestamp* diff --git a/browser_tests/tests/vueNodes/widgets/text/textEditorDialog.spec.ts b/browser_tests/tests/vueNodes/widgets/text/textEditorDialog.spec.ts index 7e368b4b719..aad818034a5 100644 --- a/browser_tests/tests/vueNodes/widgets/text/textEditorDialog.spec.ts +++ b/browser_tests/tests/vueNodes/widgets/text/textEditorDialog.spec.ts @@ -73,6 +73,59 @@ test.describe( } ) + test('accepts an imported prompt tag with native undo and redo', async ({ + comfyPage + }) => { + const node = comfyPage.vueNodes + .getNodeByTitle('CLIP Text Encode (Prompt)') + .first() + const widget = node.getByRole('textbox', { name: 'text' }) + const dialog = new TextEditorDialog(comfyPage.page) + + await test.step('import a catalog in the expanded prompt editor', async () => { + await widget.fill('') + await widget.hover() + await node + .getByRole('group', { name: 'Actions' }) + .getByRole('button', { name: 'Expand' }) + .click() + await dialog.root.getByLabel('Import prompt tags').setInputFiles({ + name: 'tags.txt', + mimeType: 'text/plain', + buffer: Buffer.from('blue_eyes,20\nblue_hair,10') + }) + await expect( + dialog.root.getByText('2 tags loaded for this session', { + exact: true + }) + ).toBeVisible() + }) + + await test.step('navigate and accept without leaving the textarea', async () => { + await dialog.editor.pressSequentially('blue') + await expect( + dialog.root.getByRole('option', { selected: true }) + ).toHaveText('blue eyes') + await dialog.editor.press('ArrowDown') + await expect( + dialog.root.getByRole('option', { selected: true }) + ).toHaveText('blue hair') + await dialog.editor.press('Enter') + await expect(dialog.editor).toHaveValue('blue hair') + await expect(dialog.editor).toBeFocused() + await expect(dialog.root.getByRole('listbox')).toBeHidden() + }) + + await test.step('undo and redo the insertion through the native editor', async () => { + await dialog.editor.press('ControlOrMeta+z') + await expect(dialog.editor).toHaveValue('blue') + await dialog.editor.press('ControlOrMeta+Shift+z') + await expect(dialog.editor).toHaveValue('blue hair') + await dialog.close() + await expect(widget).toHaveValue('blue hair') + }) + }) + test('opens long text scrolled to the top', async ({ comfyPage }) => { const node = comfyPage.vueNodes .getNodeByTitle('CLIP Text Encode (Prompt)') diff --git a/browser_tests/tests/vueNodes/widgets/text/textEditorDialog.spec.ts-snapshots/text-editor-dialog-chromium-linux.png b/browser_tests/tests/vueNodes/widgets/text/textEditorDialog.spec.ts-snapshots/text-editor-dialog-chromium-linux.png index 4561ad307d6..5ace0275366 100644 Binary files a/browser_tests/tests/vueNodes/widgets/text/textEditorDialog.spec.ts-snapshots/text-editor-dialog-chromium-linux.png and b/browser_tests/tests/vueNodes/widgets/text/textEditorDialog.spec.ts-snapshots/text-editor-dialog-chromium-linux.png differ diff --git a/docs/adr/WIDGET-AUGMENTATION-0057-core-renders-extension-contributions.md b/docs/adr/WIDGET-AUGMENTATION-0057-core-renders-extension-contributions.md new file mode 100644 index 00000000000..9577d9ca81d --- /dev/null +++ b/docs/adr/WIDGET-AUGMENTATION-0057-core-renders-extension-contributions.md @@ -0,0 +1,71 @@ +# ADR-WIDGET-AUGMENTATION-0057: Core renders extension contributions + +Date: 2026-11-14 + +## Status + +Proposed + +## Context + +A custom-node author wants to help someone write a prompt, not maintain another +editor. Today that help can require replacing widget factories, attaching DOM +listeners, or assigning widget values. Those integrations inherit each +renderer's selection, focus, undo, and teardown problems. Expanding the same +prompt into a dialog can leave the extension's behavior behind. + +## Decision + +Let extensions register declarative contributions against named node widgets. +Core resolves active contributions and renders their controls beside the +existing input. Start with completion suggestions, live text hints, and +synchronous text transformations. The devtools example tells this story with +lighting suggestions, a tag count, and a Normalize tags action on one ordinary +multiline widget, leaving its neighboring notes field alone. + +Registration supplies behavior without handing the extension an input element. + +![Core resolves and renders targeted contributions](./WIDGET-AUGMENTATION-0057-core-renders-extension-contributions/registration.svg) + +An accepted suggestion or transformation goes through core's guarded native +editing operation, then the input's existing value pipeline. There is no second +widget-value writer. The node editor and expanded editor share contributions, +not selection or browser undo history. Refusing an edit leaves the value intact. + +![Guarded insertion rejoins the existing widget update path](./WIDGET-AUGMENTATION-0057-core-renders-extension-contributions/editing.svg) + +## Migration stories + +**Custom Scripts could keep its dictionaries and stop owning the input.** Its +[autocomplete integration](https://github.com/pythongosssss/ComfyUI-Custom-Scripts/blob/609f3afaa74b2f88ef9ce8d939626065e3247469/web/js/autocompleter.js) +replaces the string-widget factory and attaches an autocomplete engine to each +eligible textarea. Already-loaded words could supply completion providers for +explicit widget targets. This migrates cached lookup, not its global widget +discovery, rich dropdown, or custom escaping and insertion rules. + +**Impact Pack could offer prompt help without mutating prompt widgets.** Its +[wildcard integration](https://github.com/ltdrdata/ComfyUI-Impact-Pack/blob/9e2d41da75c185bf7638f860d5d004035f378e9b/js/impact-pack.js) +appends wildcard and LoRA tokens through combo callbacks and writes guidance +directly to textareas. Cached wildcard tokens could supply completions for +`ImpactWildcardProcessor.wildcard_text` and +`ImpactWildcardEncode.wildcard_text`; static guidance could become hints. +Completion would be a different discovery UI, not a drop-in combo replacement. +Population, serialization overrides, and mode-dependent editability stay +outside this API. These are source-based migration candidates, not tested +migrations or promises of full compatibility. + +## Tradeoffs and limits + +Keep native textareas instead of replacing prompt editing with a rich editor. +Reuse existing positioning and design-system controls instead of adding an +autocomplete library. A general mount callback would admit arbitrary UI, but +would also require a public focus, keyboard, accessibility, and edit-lifecycle +contract. Defer that until a concrete contribution cannot fit this model. + +The prototype covers multiline native textareas, not every widget or the +agent's structured ProseMirror editor. Exact targets and synchronous callbacks +deliberately limit discovery and remote suggestions. Native insertion still +depends on deprecated `execCommand`. Core skips unsupported insertion to +preserve undo. Cross-browser undo and automatic loading of the +built devtools extension remain release gates. Existing extension behavior is +not removed or intercepted by this proposal. diff --git a/docs/adr/WIDGET-AUGMENTATION-0057-core-renders-extension-contributions/editing.svg b/docs/adr/WIDGET-AUGMENTATION-0057-core-renders-extension-contributions/editing.svg new file mode 100644 index 00000000000..f72bf63b3ac --- /dev/null +++ b/docs/adr/WIDGET-AUGMENTATION-0057-core-renders-extension-contributions/editing.svg @@ -0,0 +1,39 @@ + + An augmentation edits through the existing input pipeline + A selected completion or text action requests replacement text. Core checks editability, composition, current text and selection, and length. Accepted native insertion emits input into the existing widget update path. Refused edits leave the value unchanged. + + + + + + + The extension proposes text. Core decides whether to edit. + + Choose a completion + or run a text action + + Guard the replacement + useTextareaEdit.replace + + Native text insertion + document.execCommand + + Existing widget update + input / update:model-value + + + + + + text + valid + input + + refused + + Keep the current value + Read-only, disabled, composing, + stale text or selection, or maxlength. + Native undo stays with the focused editor. No second widget-value writer or direct-value fallback. + + diff --git a/docs/adr/WIDGET-AUGMENTATION-0057-core-renders-extension-contributions/registration.svg b/docs/adr/WIDGET-AUGMENTATION-0057-core-renders-extension-contributions/registration.svg new file mode 100644 index 00000000000..0493599733a --- /dev/null +++ b/docs/adr/WIDGET-AUGMENTATION-0057-core-renders-extension-contributions/registration.svg @@ -0,0 +1,39 @@ + + Extensions supply behavior and core renders it + An extension registers targeted contributions. Core resolves enabled contributions for a widget and renders hints, text actions, and completions without giving the extension its input element. + + + + + + Extensions supply behavior. Core owns the widget. + + Register contributions + app.registerExtension + + Match enabled targets + useWidgetAugmentations + + Render core controls + TextareaAugmentations + + Live hint + text(value) + + Text action button + transform(value) + + Autocomplete list + suggest(query) + + + + + + + + target + resolve + Disable or unregister an extension: its contributions disappear, while the existing widget remains. + + diff --git a/knip.config.ts b/knip.config.ts index a94760a5bc5..c8a21288e78 100644 --- a/knip.config.ts +++ b/knip.config.ts @@ -12,6 +12,8 @@ const config: KnipConfig = { 'src/scripts/ui/menu/index.ts', 'src/types/index.ts', 'src/storybook/mocks/**/*.ts', + 'tools/devtools/build.ts', + 'tools/devtools/widgetAugmentations.ts', 'tools/oxlint-plugins/comfyIngestTypes.ts', 'tools/oxlint-plugins/serverFacts.ts', 'tools/oxlint-plugins/vitestCleanup.ts' diff --git a/src/components/graph/widgets/DomWidget.test.ts b/src/components/graph/widgets/DomWidget.test.ts index 7aa815865a2..171164ec5a6 100644 --- a/src/components/graph/widgets/DomWidget.test.ts +++ b/src/components/graph/widgets/DomWidget.test.ts @@ -1,11 +1,14 @@ -import { render } from '@testing-library/vue' +import { render, screen } from '@testing-library/vue' +import userEvent from '@testing-library/user-event' import { fromPartial } from '@total-typescript/shoehorn' import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest' import { nextTick, reactive, ref } from 'vue' +import { i18n } from '@/i18n' import { LGraphNode } from '@/lib/litegraph/src/litegraph' import { useSettingStore } from '@/platform/settings/settingStore' import { useCanvasStore } from '@/renderer/core/canvas/canvasStore' +import { usePromptTagCatalogStore } from '@/renderer/extensions/textEditor/promptTagCatalogStore' import type { BaseDOMWidget } from '@/types/domWidget' import type { DomWidgetState } from '@/stores/domWidgetStore' import { useDomWidgetStore } from '@/stores/domWidgetStore' @@ -273,6 +276,35 @@ describe('native DOM widget interaction lifecycle', () => { useDomWidgetStore().clear() }) + it('offers shared catalog suggestions for a native multiline widget and restores its attributes on removal', async () => { + const user = userEvent.setup() + usePromptTagCatalogStore().importCatalog('blue_eyes') + const widgetState = createWidgetState(false) + const textarea = document.createElement('textarea') + textarea.setAttribute('aria-label', 'Prompt') + textarea.setAttribute('aria-autocomplete', 'none') + Object.assign(widgetState.widget, { element: textarea, type: 'customtext' }) + const view = render(DomWidget, { + props: { widgetState }, + global: { plugins: [i18n] } + }) + await nextTick() + const editor = await screen.findByRole('textbox', { name: 'Prompt' }) + + await user.type(editor, 'blue') + + expect( + await screen.findByRole('option', { name: 'blue eyes' }) + ).toBeVisible() + expect(editor).toHaveFocus() + expect(editor).toHaveAttribute('aria-autocomplete', 'list') + + view.unmount() + + expect(screen.queryByRole('listbox')).toBeNull() + expect(textarea).toHaveAttribute('aria-autocomplete', 'none') + }) + function renderWithUnmountableElement(widgetState: DomWidgetState) { const input = document.createElement('input') Object.assign(widgetState.widget, { element: input }) diff --git a/src/components/graph/widgets/DomWidget.vue b/src/components/graph/widgets/DomWidget.vue index 2d0e92ea14d..e97b05f2c1e 100644 --- a/src/components/graph/widgets/DomWidget.vue +++ b/src/components/graph/widgets/DomWidget.vue @@ -3,6 +3,7 @@ v-show="widgetState.visible" ref="widgetElement" class="dom-widget size-full" + :class="cn(widget.type === 'customtext' && 'flex flex-col')" :title="tooltip" :style="style" > @@ -15,6 +16,16 @@ v-bind="widget.props" @update:model-value="emit('update:widgetValue', $event)" /> + @@ -23,11 +34,13 @@ import { useElementBounding, useEventListener, whenever } from '@vueuse/core' import type { CSSProperties } from 'vue' import { computed, nextTick, onMounted, ref, watch } from 'vue' +import { cn } from '@comfyorg/tailwind-utils' import { useAbsolutePosition } from '@/composables/element/useAbsolutePosition' import { useDomClipping } from '@/composables/element/useDomClipping' import { findFirstNode } from '@/lib/litegraph/src/utils/collections' import { useSettingStore } from '@/platform/settings/settingStore' import { useCanvasStore } from '@/renderer/core/canvas/canvasStore' +import TextareaAugmentations from '@/renderer/extensions/textEditor/components/TextareaAugmentations.vue' import { isComponentWidget, isDOMWidget } from '@/scripts/domWidget' import type { DomWidgetState } from '@/stores/domWidgetStore' @@ -38,6 +51,13 @@ const { widgetState } = defineProps<{ }>() const widget = widgetState.widget +function textareaElement(): HTMLTextAreaElement | undefined { + if (!isDOMWidget(widget)) return undefined + return widget.element instanceof HTMLTextAreaElement + ? widget.element + : undefined +} + const emit = defineEmits<{ 'update:widgetValue': [value: string | object] }>() @@ -169,18 +189,20 @@ onMounted(() => { const inputSpec = widget.node.constructor.nodeData const tooltip = inputSpec?.inputs?.[widget.name]?.tooltip -// Mount DOM element when widget is or becomes visible const mountElementIfVisible = () => { if (!(widgetState.visible && isDOMWidget(widget) && widgetElement.value)) { return } - // Only append if not already a child if (widgetElement.value.contains(widget.element)) { return } try { - widget.element.classList.add('h-full', 'w-full') + widget.element.classList.add( + 'h-full', + 'w-full', + ...(widget.type === 'customtext' ? ['min-h-0', 'flex-1'] : []) + ) widgetElement.value.appendChild(widget.element) } catch (error) { reportDomWidgetMountFailure(error, { diff --git a/src/locales/en/main.json b/src/locales/en/main.json index 19316d247a5..6a17cbc6413 100644 --- a/src/locales/en/main.json +++ b/src/locales/en/main.json @@ -4414,8 +4414,16 @@ } }, "textEditor": { + "actionTooLong": "This action exceeds the text limit. Shorten the text and try again.", + "actionUnavailable": "This action could not edit the text. Your text is unchanged. Edit it manually instead.", "characterCount": "{count} char | {count} chars", "expand": "Expand", + "importTags": "Import prompt tags", + "importTagsError": "Could not load tags. Choose a TXT list or a tag CSV (name, category, count, aliases), up to 10 MB. Your previous catalog is unchanged.", + "importTagsHint": "CSV or TXT · local to this session", + "suggestionCount": "{count} suggestion available | {count} suggestions available", + "suggestions": "Prompt suggestions", + "tagsLoaded": "{count} tag loaded for this session | {count} tags loaded for this session", "title": "{widget} · {node}" }, "widgetFileUpload": { diff --git a/src/platform/extensions/stores/extensionStore.test.ts b/src/platform/extensions/stores/extensionStore.test.ts index 34f81a8ddcf..27b9e9c557a 100644 --- a/src/platform/extensions/stores/extensionStore.test.ts +++ b/src/platform/extensions/stores/extensionStore.test.ts @@ -3,6 +3,13 @@ import { describe, expect, it, vi } from 'vitest' import { useSettingStore } from '@/platform/settings/settingStore' import { api } from '@/scripts/api' import { useExtensionStore } from '@/platform/extensions/stores/extensionStore' +import { useWidgetAugmentations } from '@/platform/extensions/useWidgetAugmentations' +import { reportError } from '@comfyorg/telemetry/reportError' +import type { ComfyExtension } from '@/types/comfy' + +vi.mock(import('@comfyorg/telemetry/reportError'), () => ({ + reportError: vi.fn() +})) describe('extensionStore', () => { describe('registerExtension', () => { @@ -12,6 +19,68 @@ describe('extensionStore', () => { expect(store.isExtensionInstalled('test.ext')).toBe(true) }) + it('registers immutable extensions with valid augmentations', () => { + const store = useExtensionStore() + const extension = Object.freeze({ + name: 'test.immutable', + widgetAugmentations: [ + { + id: 'hint', + kind: 'hint', + target: { nodeType: 'TestNode', widgetName: 'prompt' }, + text: () => 'Prompt hint' + } + ] + } satisfies ComfyExtension) + + store.registerExtension(extension) + + expect(store.extensions[0]).toBe(extension) + }) + + it('does not restore removed augmentations when registering the same object again', () => { + const store = useExtensionStore() + const target = { nodeType: 'TestNode', widgetName: 'prompt' } + const extension: ComfyExtension = { + name: 'test.reregister', + widgetAugmentations: [ + { id: 'hint', kind: 'hint', target, text: () => 'Prompt hint' } + ] + } + const { contributions } = useWidgetAugmentations(() => target) + store.registerExtension(extension) + expect(contributions.value.map((item) => item.key)).toEqual([ + 'test.reregister:hint' + ]) + + store.unregisterExtension(extension.name) + delete extension.widgetAugmentations + store.registerExtension(extension) + + expect(contributions.value).toEqual([]) + }) + + it('retains prototype hooks when excluding malformed augmentations', () => { + class Extension implements ComfyExtension { + [key: string]: unknown + name = 'test.prototype' + widgetAugmentations = [] + initialized = false + + setup() { + this.initialized = true + } + } + const store = useExtensionStore() + const extension = new Extension() + Reflect.set(extension, 'widgetAugmentations', [null]) + + store.registerExtension(extension) + + expect(store.extensions[0]).toBe(extension) + expect(store.extensions[0].setup).toBe(extension.setup) + }) + it('throws for extension without name', () => { const store = useExtensionStore() expect(() => store.registerExtension({ name: '' })).toThrow( @@ -27,6 +96,41 @@ describe('extensionStore', () => { ) }) + it.for([ + null, + { id: 'missing-target', kind: 'hint', text: () => 'broken' }, + { id: 'missing-callback', kind: 'hint', target: {} } + ])('isolates malformed JavaScript augmentations: %j', (invalid) => { + const store = useExtensionStore() + const setup = vi.fn() + const extension: ComfyExtension = { name: 'test.invalid', setup } + const valid = { + id: 'valid', + kind: 'hint', + target: { nodeType: 'TestNode', widgetName: 'prompt' }, + text: (value: string) => `Length: ${value.length}` + } + Reflect.set(extension, 'widgetAugmentations', [invalid, valid]) + Object.freeze(extension) + + store.registerExtension(extension) + store.registerExtension({ name: 'test.neighbor' }) + + expect( + store.getWidgetAugmentations(store.extensions[0]).map((item) => item.id) + ).toEqual(['valid']) + expect(extension.widgetAugmentations).toEqual([invalid, valid]) + expect(store.extensions[0].setup).toBe(setup) + expect(store.isExtensionInstalled('test.neighbor')).toBe(true) + expect(reportError).toHaveBeenCalledWith( + expect.any(Error), + expect.objectContaining({ + errorType: 'error_registering_widget_augmentation', + context: { extension: 'test.invalid' } + }) + ) + }) + it('warns when registering a disabled extension but still installs it', () => { const store = useExtensionStore() try { diff --git a/src/platform/extensions/stores/extensionStore.ts b/src/platform/extensions/stores/extensionStore.ts index 28f63e706c5..5ca04593e45 100644 --- a/src/platform/extensions/stores/extensionStore.ts +++ b/src/platform/extensions/stores/extensionStore.ts @@ -1,6 +1,8 @@ import { defineStore } from 'pinia' import { computed, markRaw, ref, shallowRef } from 'vue' +import { isWidgetAugmentation } from '@/platform/extensions/widgetAugmentation' +import type { WidgetAugmentation } from '@/platform/extensions/widgetAugmentation' import { useSettingStore } from '@/platform/settings/settingStore' import { reportError } from '@comfyorg/telemetry/reportError' import type { ComfyExtension } from '@/types/comfy' @@ -38,6 +40,10 @@ interface ExtensionPathState { export const useExtensionStore = defineStore('extension', () => { // For legacy reasons, the name uniquely identifies an extension const extensionByName = ref>({}) + const widgetAugmentations = new WeakMap< + ComfyExtension, + readonly WidgetAugmentation[] + >() const extensions = computed(() => Object.values(extensionByName.value)) // Not using computed because disable extension requires reloading of the page. // Dynamically update this list won't affect extensions that are already loaded. @@ -91,9 +97,27 @@ export const useExtensionStore = defineStore('extension', () => { console.warn(`Extension ${extension.name} is disabled.`) } + if (extension.widgetAugmentations !== undefined) { + const supplied: unknown = extension.widgetAugmentations + const valid = Array.isArray(supplied) + ? supplied.filter(isWidgetAugmentation) + : [] + if (!Array.isArray(supplied) || valid.length !== supplied.length) { + reportError(new TypeError('Invalid widget augmentation registration'), { + errorType: 'error_registering_widget_augmentation', + surface: 'platform', + context: { extension: extension.name } + }) + } + widgetAugmentations.set(extension, valid) + } extensionByName.value[extension.name] = markRaw(extension) } + function getWidgetAugmentations(extension: ComfyExtension) { + return widgetAugmentations.get(extension) ?? [] + } + const registration = shallowRef({ mode: 'immediate' }) const isHoldingCustomNodes = computed( () => registration.value.mode === 'holding' @@ -166,6 +190,8 @@ export const useExtensionStore = defineStore('extension', () => { } function unregisterExtension(name: string) { + if (isExtensionInstalled(name)) + widgetAugmentations.delete(extensionByName.value[name]) delete extensionByName.value[name] } @@ -281,6 +307,7 @@ export const useExtensionStore = defineStore('extension', () => { isExtensionEnabled, isExtensionReadOnly, registerExtension, + getWidgetAugmentations, unregisterExtension, isHoldingCustomNodes, areLateCustomNodesPending, diff --git a/src/platform/extensions/useWidgetAugmentations.ts b/src/platform/extensions/useWidgetAugmentations.ts new file mode 100644 index 00000000000..66b997a19f5 --- /dev/null +++ b/src/platform/extensions/useWidgetAugmentations.ts @@ -0,0 +1,73 @@ +import { computed, shallowRef } from 'vue' + +import { reportError } from '@comfyorg/telemetry/reportError' +import { useExtensionStore } from '@/platform/extensions/stores/extensionStore' +import type { + WidgetAugmentation, + WidgetAugmentationTarget +} from '@/platform/extensions/widgetAugmentation' + +interface Contribution { + key: string + extension: string + augmentation: WidgetAugmentation +} + +export function useWidgetAugmentations( + target: () => WidgetAugmentationTarget | undefined +) { + const extensions = useExtensionStore() + const failed = shallowRef(new Set()) + const nodeType = computed(() => target()?.nodeType) + const widgetName = computed(() => target()?.widgetName) + const registrations = computed(() => + extensions.extensions + .filter((extension) => extensions.contributes(extension.name)) + .flatMap((extension) => + extensions + .getWidgetAugmentations(extension) + .filter( + (augmentation) => + augmentation.target.nodeType === nodeType.value && + augmentation.target.widgetName === widgetName.value + ) + .map((augmentation) => ({ + key: `${extension.name}:${augmentation.id}`, + extension: extension.name, + augmentation + })) + ) + ) + const contributions = computed(() => + registrations.value.filter((item) => !failed.value.has(item.augmentation)) + ) + + function evaluate( + contribution: Contribution, + read: () => T + ): T | undefined { + if ( + !contributions.value.some( + (item) => + item.extension === contribution.extension && + item.augmentation === contribution.augmentation + ) + ) + return undefined + try { + return read() + } catch (error) { + failed.value = new Set([...failed.value, contribution.augmentation]) + reportError(error, { + errorType: 'error_evaluating_widget_augmentation', + surface: 'platform', + context: { + extension: contribution.extension, + augmentation: contribution.augmentation.id + } + }) + } + } + + return { registrations, contributions, evaluate } +} diff --git a/src/platform/extensions/widgetAugmentation.ts b/src/platform/extensions/widgetAugmentation.ts new file mode 100644 index 00000000000..de914063e97 --- /dev/null +++ b/src/platform/extensions/widgetAugmentation.ts @@ -0,0 +1,66 @@ +export interface WidgetAugmentationTarget { + nodeType: string + widgetName: string +} + +export type WidgetAugmentation = { + id: string + target: WidgetAugmentationTarget +} & ( + | { + kind: 'text-completion' + suggest: (query: string) => readonly string[] + } + | { + kind: 'hint' + text: (value: string) => string + } + | { + kind: 'text-action' + label: string + transform: (value: string) => string + } +) + +function isWidgetAugmentationTarget( + target: unknown +): target is WidgetAugmentationTarget { + return ( + typeof target === 'object' && + target !== null && + 'nodeType' in target && + typeof target.nodeType === 'string' && + 'widgetName' in target && + typeof target.widgetName === 'string' + ) +} + +export function isWidgetAugmentation( + value: unknown +): value is WidgetAugmentation { + if ( + typeof value !== 'object' || + value === null || + !('id' in value) || + typeof value.id !== 'string' || + !('target' in value) || + !isWidgetAugmentationTarget(value.target) || + !('kind' in value) + ) + return false + switch (value.kind) { + case 'text-completion': + return 'suggest' in value && typeof value.suggest === 'function' + case 'hint': + return 'text' in value && typeof value.text === 'function' + case 'text-action': + return ( + 'label' in value && + typeof value.label === 'string' && + 'transform' in value && + typeof value.transform === 'function' + ) + default: + return false + } +} diff --git a/src/renderer/extensions/textEditor/components/TextEditorDialogContent.vue b/src/renderer/extensions/textEditor/components/TextEditorDialogContent.vue index 66214fb6cf5..15049e5b522 100644 --- a/src/renderer/extensions/textEditor/components/TextEditorDialogContent.vue +++ b/src/renderer/extensions/textEditor/components/TextEditorDialogContent.vue @@ -1,4 +1,39 @@