Compare commits

..
Author SHA1 Message Date
Vito Sansevero b0c0d53676 feat(ui): unify Display Text and Display Any output views 2026-10-16 13:20:28 -07:00
Vito b9103ad9c4 Merge pull request #93 from ComfyAssets/feat/shared-node-dimensions-dialog
feat(ui): migrate Node Dimensions to shared dialog controls
2026-10-16 13:09:13 -07:00
14 changed files with 477 additions and 332 deletions
Binary file not shown.

After

Width:  |  Height:  |  Size: 103 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 103 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 69 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 71 KiB

+132 -7
View File
@@ -280,14 +280,14 @@ test('real display node output renders as text and replaces previous widgets', a
await expect(response).toBeOK();
const data = await response.json();
await page.evaluate(({ id, message }) => kikoHost.nodes.get(String(id)).onExecuted(message), { id, message: data.ui });
await expect(page.getByLabel('text_positive')).toHaveValue('<img src=x onerror="window.injected=true">');
await expect(page.getByLabel('text_negative')).toHaveValue('blur');
await expect(page.getByLabel('Positive prompt', { exact: true })).toHaveValue('<img src=x onerror="window.injected=true">');
await expect(page.getByLabel('Negative prompt', { exact: true })).toHaveValue('blur');
expect(await page.evaluate(() => window.injected)).toBeUndefined();
const next = await (await request.post('/__test__/execute/DisplayText', { data: { text: 'Replacement' } })).json();
await page.evaluate(({ id, message }) => kikoHost.nodes.get(String(id)).onExecuted(message), { id, message: next.ui });
await expect(page.locator('textarea')).toHaveCount(1);
await expect(page.getByLabel('text_display')).toHaveValue('Replacement');
await expect(page.getByLabel('text_display')).toHaveAttribute('readonly', '');
await expect(page.getByLabel('Text output', { exact: true })).toHaveValue('Replacement');
await expect(page.getByLabel('Text output', { exact: true })).toHaveAttribute('readonly', '');
});
test('seed history persists across reloads and removal clears its watcher', async ({ page }) => {
@@ -810,15 +810,15 @@ test('Display Any renders real multiline output and restores serialized values w
await expect(response).toBeOK();
const result = await response.json();
await page.evaluate(({ id, message }) => kikoHost.nodes.get(String(id)).onExecuted(message), { id, message: result.ui });
await expect(page.locator('textarea')).toHaveCount(3);
await expect(page.locator('textarea')).toHaveCount(1);
expect(await page.locator('textarea').evaluateAll(elements => elements.map(element => element.value).join('\n'))).toBe(result.ui.text[0]);
await page.evaluate(id => {
const node = kikoHost.nodes.get(String(id));
node.configure({ widgets_values: ['Restored value'] });
node.onConfigure();
node.onConfigure?.();
}, id);
await expect(page.locator('textarea')).toHaveCount(1);
await expect(page.getByLabel('display_0')).toHaveValue('Restored value');
await expect(page.getByLabel('Value output', { exact: true })).toHaveValue('Restored value');
});
test('gallery pagination sorting and hidden-folder controls use real directory pages', async ({ page, request }) => {
@@ -987,3 +987,128 @@ test('legacy selects retain Enter confirmation', async ({ page }) => {
expect(await page.evaluate(() => window.selectedLegacy)).toEqual(['chosen']);
expect(await page.evaluate(() => window.leakedDialogKeys)).toBe(0);
});
for (const name of ['DisplayText', 'DisplayAny']) {
test(`${name}: shared output follows themes, resizes, copies and preserves empty output`, async ({ page }) => {
await openHost(page);
const id = await createNode(page, name, name === 'DisplayAny' ? { mode: 'tensor shape' } : {});
await page.evaluate(id => {
const node = kikoHost.nodes.get(String(id));
node.onExecuted({ text: ['first\nsecond <b>literal</b>'] });
window.copiedOutput = [];
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText: async text => window.copiedOutput.push(text) } });
}, id);
const panel = page.locator('.ca-text-output');
await expect(panel).toBeVisible();
for (const [color, theme] of [['#fafafa', 'light'], ['#202020', 'dark']]) {
await page.evaluate(color => document.body.style.setProperty('--bg-color', color), color);
await expect(panel).toHaveAttribute('data-ca-theme', theme);
}
const field = panel.getByRole('textbox');
await expect(field).toHaveAttribute('readonly', '');
await expect(field).toHaveValue('first\nsecond <b>literal</b>');
await field.focus();
await page.keyboard.press('ControlOrMeta+A');
expect(await field.evaluate(element => element.value.substring(element.selectionStart, element.selectionEnd))).toBe('first\nsecond <b>literal</b>');
await panel.getByRole('button', { name: /Copy/ }).focus();
await page.keyboard.press('Enter');
await expect(panel.getByRole('status')).toHaveText('Copied.');
expect(await page.evaluate(() => window.copiedOutput)).toEqual(['first\nsecond <b>literal</b>']);
for (const width of [240, 450, 800]) {
await panel.evaluate((element, width) => { element.style.width = `${width}px`; element.style.height = '400px'; }, width);
expect(await panel.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true);
}
await page.evaluate(id => kikoHost.nodes.get(String(id)).onExecuted({ text: [''] }), id);
await expect(panel.getByRole('textbox')).toHaveValue('');
await expect(panel.getByRole('status')).toBeEmpty();
const snapshot = await page.evaluate(id => {
const node = kikoHost.nodes.get(String(id));
const data = {};
node.onSerialize(data);
node.onExecuted({ text: ['replacement'] });
node.configure(data);
return data;
}, id);
expect(snapshot.kikoDisplay).toEqual({ version: 1, text: '' });
await expect(panel.getByRole('textbox')).toHaveValue('');
await page.evaluate(id => kikoHost.removeNode(id), id);
await expect(panel).toHaveCount(0);
});
}
test('display prompt copy feedback handles failure, replacement and removal safely', async ({ page }) => {
await openHost(page);
const id = await createNode(page, 'DisplayText');
await page.evaluate(id => {
kikoHost.nodes.get(String(id)).onExecuted({ text: ['Positive prompt: sun\nNegative prompt: rain'] });
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText: () => Promise.reject(new Error('denied')) } });
}, id);
const panel = page.locator('.ca-text-output');
await panel.getByRole('button', { name: 'Copy negative', exact: true }).click();
await expect(panel.getByRole('status')).toContainText('Could not copy');
await expect(panel.getByRole('textbox', { name: 'Negative prompt', exact: true })).toHaveValue('rain');
await page.evaluate(() => { navigator.clipboard.writeText = () => new Promise(resolve => window.finishCopy = resolve); });
await panel.getByRole('button', { name: 'Copy positive', exact: true }).click();
await page.evaluate(id => {
kikoHost.nodes.get(String(id)).onExecuted({ text: ['new output'] });
window.finishCopy();
}, id);
await expect(panel.getByRole('status')).toBeEmpty();
await panel.getByRole('button', { name: 'Copy text', exact: true }).click();
await page.evaluate(id => { kikoHost.removeNode(id); window.finishCopy(); }, id);
await expect(panel).toHaveCount(0);
});
test('display adapters preserve lifecycle context, arguments, results and saved snapshots', async ({ page }) => {
await openHost(page);
const result = await page.evaluate(async () => {
const calls = [];
let node;
class HookNode {
constructor() { this.widgets = []; this.size = [600, 500]; this.inputs = []; }
addDOMWidget(name, type, element) { document.body.append(element); const widget = { name, element }; this.widgets.push(widget); return widget; }
setSize(size) { this.size = size; }
setDirtyCanvas() {}
onNodeCreated(...args) { calls.push(['created', this === node, args]); return 'created-result'; }
onExecuted(...args) { calls.push(['executed', this === node, args]); return 'executed-result'; }
configure(...args) { calls.push(['configure', this === node, args]); return 'configure-result'; }
onSerialize(...args) { calls.push(['serialize', this === node, args.length]); args[0].external = 'retained'; return 'serialize-result'; }
onRemoved(...args) { calls.push(['removed', this === node, args]); return 'removed-result'; }
}
await kikoHost.extensions.find(extension => extension.name === 'ComfyAssets.DisplayAny').beforeRegisterNodeDef(HookNode, { name: 'DisplayAny' }, kikoHost.app);
node = new HookNode();
const created = node.onNodeCreated('creation');
const executed = node.onExecuted({ text: ['first'] }, 'execution');
const data = {};
const serialized = node.onSerialize(data, 'serialization');
const configured = node.configure({ kikoDisplay: { version: 1, text: 'restored' } }, 'configuration');
const removed = node.onRemoved('removal');
node.onExecuted({ text: ['too late'] });
return { created, executed, serialized, configured, removed, data, text: node.displayOutput.text, calls, disposed: node.displayOutput.scope.signal.aborted, size: node.size };
});
expect(result).toMatchObject({ created: 'created-result', executed: 'executed-result', serialized: 'serialize-result', configured: 'configure-result', removed: 'removed-result', data: { external: 'retained', kikoDisplay: { version: 1, text: 'first' } }, text: 'restored', disposed: true, size: [600, 500] });
expect(result.calls.slice(0, 5)).toEqual([
['created', true, ['creation']],
['executed', true, [{ text: ['first'] }, 'execution']],
['serialize', true, 2],
['configure', true, [{ kikoDisplay: { version: 1, text: 'restored' } }, 'configuration']],
['removed', true, ['removal']],
]);
});
test('display copy feedback expires and malformed execution messages retain the latest output', async ({ page }) => {
await openHost(page);
const id = await createNode(page, 'DisplayText');
await page.evaluate(id => {
const node = kikoHost.nodes.get(String(id));
node.onExecuted({ text: ['latest'] });
for (const message of [null, {}, { text: [] }, { text: [12] }]) node.onExecuted(message);
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText: async () => {} } });
}, id);
const panel = page.locator('.ca-text-output');
await expect(panel.getByRole('textbox')).toHaveValue('latest');
await panel.getByRole('button', { name: 'Copy text', exact: true }).click();
await expect(panel.getByRole('status')).toHaveText('Copied.');
await expect(panel.getByRole('status')).toBeEmpty({ timeout: 4000 });
});
+97
View File
@@ -465,3 +465,100 @@ test('Node Dimensions applies and persists across Classic and Nodes 2.0', async
});
await expect(dialog).toHaveCount(0);
});
for (const name of ['DisplayText', 'DisplayAny']) {
test(`${name}: shared output persists through renderers, themes and legacy reload`, async ({ page }, testInfo) => {
const output = name === 'DisplayText'
? 'Positive prompt: A blue cabin beside a quiet lake, soft morning light, detailed reflections.\nNegative prompt: blur, noise, watermark'
: Array.from({ length: 45 }, (_, index) => `Line ${index}: tensor / diagnostic output`).join('\n');
await page.evaluate(async ({ name, output }) => {
const { app } = await import('/scripts/app.js');
const node = LiteGraph.createNode(name);
app.graph.add(node);
node.setSize([560, 520]);
const mode = node.widgets.find(widget => widget.name === 'mode');
if (mode) mode.value = 'tensor shape';
node.onExecuted({ text: [output] });
app.canvas.centerOnNode(node);
window.displayCopies = [];
Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText: async text => window.displayCopies.push(text) } });
}, { name, output });
const panel = page.locator('.ca-text-output');
await expect(panel).toHaveCount(1);
for (const renderer of [false, true, false]) {
await page.evaluate(async renderer => {
const { app } = await import('/scripts/app.js');
await app.ui.settings.setSettingValue('Comfy.VueNodes.Enabled', renderer);
app.canvas.ds.scale = .85;
app.canvas.centerOnNode(app.graph._nodes[0]);
}, renderer);
await expect.poll(() => page.evaluate(() => LiteGraph.vueNodesMode)).toBe(renderer);
await expect(panel).toBeVisible();
await expect(panel).toHaveCount(1);
await panel.getByRole('button', { name: name === 'DisplayText' ? 'Copy negative' : 'Copy value', exact: true }).focus();
await page.keyboard.press('Enter');
await expect(panel.getByRole('status')).toHaveText('Copied.');
}
expect(await page.evaluate(() => window.displayCopies)).toEqual(Array(3).fill(name === 'DisplayText' ? 'blur, noise, watermark' : output));
const restored = await page.evaluate(async () => {
const { app } = await import('/scripts/app.js');
const workflow = app.graph.serialize();
const saved = workflow.nodes[0];
await app.loadGraphData(workflow);
app.canvas.centerOnNode(app.graph._nodes[0]);
return { snapshot: saved.kikoDisplay, size: Array.from(app.graph._nodes[0].size), mode: app.graph._nodes[0].widgets.find(widget => widget.name === 'mode')?.value };
});
expect(restored.snapshot).toEqual({ version: 1, text: output });
expect(restored.size).toEqual([560, 520]);
if (name === 'DisplayAny') {
expect(restored.mode).toBe('tensor shape');
await expect(panel.getByLabel('Value output', { exact: true })).toHaveValue(output);
} else {
await expect(panel.getByLabel('Positive prompt', { exact: true })).toHaveValue('A blue cabin beside a quiet lake, soft morning light, detailed reflections.');
await expect(panel.getByLabel('Negative prompt', { exact: true })).toHaveValue('blur, noise, watermark');
}
for (const theme of ['light', 'dark']) {
await page.evaluate(async theme => {
const { app } = await import('/scripts/app.js');
await app.ui.settings.setSettingValue('Comfy.ColorPalette', theme);
}, theme);
await expect(panel).toHaveAttribute('data-ca-theme', theme);
await page.screenshot({ path: testInfo.outputPath(`${name}-${theme}.png`) });
}
await page.evaluate(async () => {
const { app } = await import('/scripts/app.js');
app.graph._nodes[0].setSize([280, 520]);
app.canvas.centerOnNode(app.graph._nodes[0]);
});
expect(await panel.evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true);
await page.evaluate(async name => {
const { app } = await import('/scripts/app.js');
const workflow = app.graph.serialize();
delete workflow.nodes[0].kikoDisplay;
workflow.nodes[0].widgets_values = name === 'DisplayText'
? ['✓ Positive Prompt', 'legacy positive', null, '✗ Negative Prompt', 'legacy negative', null]
: ['tensor shape', 'legacy first', 'legacy second', null];
await app.loadGraphData(workflow);
app.canvas.centerOnNode(app.graph._nodes[0]);
}, name);
await expect(panel).toHaveCount(1);
if (name === 'DisplayText') {
await expect(panel.getByLabel('Positive prompt', { exact: true })).toHaveValue('legacy positive');
await expect(panel.getByLabel('Negative prompt', { exact: true })).toHaveValue('legacy negative');
} else {
await expect(panel.getByLabel('Value output', { exact: true })).toHaveValue('legacy first\nlegacy second');
expect(await page.evaluate(async () => {
const { app } = await import('/scripts/app.js');
return app.graph._nodes[0].widgets.find(widget => widget.name === 'mode').value;
})).toBe('tensor shape');
}
await page.evaluate(async () => {
const { app } = await import('/scripts/app.js');
const node = app.graph._nodes[0];
window.removedDisplay = node;
app.graph.remove(node);
});
await expect(panel).toHaveCount(0);
expect(await page.evaluate(() => window.removedDisplay.displayOutput.scope.signal.aborted)).toBe(true);
});
}
+38
View File
@@ -0,0 +1,38 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { outputSections } from '../../web/views/text-output.js';
import { restoreDisplayOutput } from '../../web/controllers/display-node.js';
test('display text recognizes paired prompts and preserves ordinary text verbatim', () => {
assert.deepEqual(outputSections('text', 'Positive prompt: bright ** metadata\nNegative prompt: blur ** metadata').map(section => section.text), ['bright', 'blur']);
assert.deepEqual(outputSections('text', 'POSITIVE PROMPT: sun\nNEGATIVE PROMPT: rain').map(section => section.text), ['sun', 'rain']);
for (const text of ['', 'Positive prompt: alone', '<script>hello</script>\nnext']) {
assert.deepEqual(outputSections('text', text).map(section => section.text), [text]);
}
const long = Array.from({ length: 45 }, (_, index) => `Line ${index}`).join('\n');
assert.deepEqual(outputSections('any', long).map(section => section.text), [long]);
});
test('versioned display snapshots preserve complete output including empty text', () => {
for (const kind of ['text', 'any']) {
for (const text of ['', 'mode\nfull\noutput']) {
assert.equal(restoreDisplayOutput({ kikoDisplay: { version: 1, text }, widgets_values: ['stale'] }, kind, false), text);
}
assert.equal(restoreDisplayOutput({}, kind, false), null);
assert.equal(restoreDisplayOutput({ widgets_values: [] }, kind, false), null);
}
});
test('legacy display workflows restore prompt pairs, converted inputs and every chunk', () => {
assert.equal(restoreDisplayOutput({ widgets_values: ['✓ Positive Prompt', 'sun', null, '✗ Negative Prompt', 'rain', null] }, 'text', false), 'Positive prompt: sun\nNegative prompt: rain');
assert.equal(restoreDisplayOutput({ widgets_values: ['converted', 'saved text', null] }, 'text', true), 'saved text');
assert.equal(restoreDisplayOutput({ widgets_values: ['raw value', 'first\nchunk', 'second\nchunk', null] }, 'any', false), 'first\nchunk\nsecond\nchunk');
assert.equal(restoreDisplayOutput({ widgets_values: ['converted', 'tensor shape', 'shape', null] }, 'any', true), 'shape');
assert.equal(restoreDisplayOutput({ widgets_values: ['tensor shape'] }, 'any', false), null);
assert.equal(restoreDisplayOutput({ widgets_values: [''] }, 'text', false), '');
assert.equal(restoreDisplayOutput({ kikoDisplay: { version: 99, text: 'unknown' }, widgets_values: ['legacy'] }, 'text', false), 'legacy');
});
test('prompt detection retains leading markdown markers accepted by existing workflows', () => {
assert.equal(outputSections('text', 'Positive prompt: **sun\nNegative prompt: rain')[0].text, '**sun');
});
+20 -8
View File
@@ -1,15 +1,21 @@
{
"controllers/display-node.js": {
"lines": 98,
"branches": 95,
"functions": 86,
"statements": 98
},
"display_any.js": {
"lines": 84,
"branches": 66,
"functions": 83,
"statements": 84
"lines": 98,
"branches": 98,
"functions": 98,
"statements": 98
},
"display_text.js": {
"lines": 71,
"branches": 74,
"functions": 42,
"statements": 71
"lines": 98,
"branches": 98,
"functions": 98,
"statements": 98
},
"empty_latent_batch_swap.js": {
"lines": 98,
@@ -137,6 +143,12 @@
"functions": 98,
"statements": 98
},
"views/text-output.js": {
"lines": 98,
"branches": 94,
"functions": 98,
"statements": 98
},
"width_height_swap.js": {
"lines": 98,
"branches": 98,
+63
View File
@@ -0,0 +1,63 @@
import { createScope } from '../ui/core.js';
import { createTextOutputView } from '../views/text-output.js';
export function restoreDisplayOutput(data, kind, hasInputWidget) {
if (data.kikoDisplay?.version === 1 && typeof data.kikoDisplay.text === 'string') return data.kikoDisplay.text;
if (!Array.isArray(data.widgets_values)) return null;
const values = data.widgets_values.slice(hasInputWidget && data.widgets_values.length > 1 ? 1 : 0);
if (kind === 'any' && ['raw value', 'tensor shape'].includes(values[0])) values.shift();
const strings = values.filter(value => typeof value === 'string');
if (!strings.length) return null;
if (kind === 'text' && strings[0] === '✓ Positive Prompt' && strings[2] === '✗ Negative Prompt') {
return `Positive prompt: ${strings[1]}\nNegative prompt: ${strings[3]}`;
}
return kind === 'any' ? strings.join('\n') : strings[0];
}
function updateOutput(node, text) {
if (node.displayOutput.scope.signal.aborted) return;
node.displayOutput.text = text;
node.displayOutput.view.update(text);
node.setDirtyCanvas(true, true);
}
export function registerDisplayNode(nodeType, app, kind) {
const onNodeCreated = nodeType.prototype.onNodeCreated;
nodeType.prototype.onNodeCreated = function () {
const result = onNodeCreated?.apply(this, arguments);
const scope = createScope();
const view = createTextOutputView(scope, kind, app.ui.settings);
this.displayOutput = { scope, view, text: '' };
this.addDOMWidget('kiko_display_output', 'div', view.element, {
serialize: false, hideOnZoom: false,
getMinHeight: () => kind === 'text' ? 240 : 180,
});
this.setSize([Math.max(this.size[0], kind === 'text' ? 400 : 450), Math.max(this.size[1], kind === 'text' ? 300 : 250)]);
updateOutput(this, kind === 'text' ? 'Text will appear here after execution...' : 'Value will appear here...');
return result;
};
const onExecuted = nodeType.prototype.onExecuted;
nodeType.prototype.onExecuted = function (message) {
const result = onExecuted?.apply(this, arguments);
if (typeof message?.text?.[0] === 'string') updateOutput(this, message.text[0]);
return result;
};
const configure = nodeType.prototype.configure;
nodeType.prototype.configure = function (data) {
const text = restoreDisplayOutput(data, kind, Boolean(this.inputs?.[0]?.widget));
const result = configure?.apply(this, arguments);
if (text !== null) updateOutput(this, text);
return result;
};
const onSerialize = nodeType.prototype.onSerialize;
nodeType.prototype.onSerialize = function (data) {
const result = onSerialize?.apply(this, arguments);
data.kikoDisplay = { version: 1, text: this.displayOutput.text };
return result;
};
const onRemoved = nodeType.prototype.onRemoved;
nodeType.prototype.onRemoved = function () {
this.displayOutput.scope.dispose();
return onRemoved?.apply(this, arguments);
};
}
+5 -122
View File
@@ -1,126 +1,9 @@
import { app } from "../../scripts/app.js";
import { ComfyWidgets } from "../../scripts/widgets.js";
import { app } from '../../scripts/app.js';
import { registerDisplayNode } from './controllers/display-node.js';
app.registerExtension({
name: "ComfyAssets.DisplayAny",
name: 'ComfyAssets.DisplayAny',
async beforeRegisterNodeDef(nodeType, nodeData, app) {
if (nodeData.name === "DisplayAny") {
function populate(text) {
// Remove existing display widgets
if (this.widgets) {
const toRemove = [];
for (let i = 0; i < this.widgets.length; i++) {
if (this.widgets[i].name?.startsWith("display_") || this.widgets[i].name === "copy_value") {
this.widgets[i].onRemove?.();
toRemove.push(i);
}
}
// Remove in reverse order to maintain indices
for (let i = toRemove.length - 1; i >= 0; i--) {
this.widgets.splice(toRemove[i], 1);
}
}
// Split text into multiple widgets if it's too long or has multiple lines
const lines = text ? text.split('\n') : [''];
const maxLinesPerWidget = 20;
const chunks = [];
for (let i = 0; i < lines.length; i += maxLinesPerWidget) {
chunks.push(lines.slice(i, i + maxLinesPerWidget).join('\n'));
}
// Create a widget for each chunk
chunks.forEach((chunk, index) => {
const w = ComfyWidgets["STRING"](this, `display_${index}`, ["STRING", { multiline: true }], app).widget;
w.inputEl.readOnly = true;
w.inputEl.style.opacity = 0.8;
w.inputEl.style.fontFamily = "monospace";
w.value = chunk;
});
// Add copy button widget
const copyWidget = {
type: "button",
name: "copy_value",
text: "📋 Copy Value",
callback: () => {
navigator.clipboard.writeText(text || '').then(() => {
copyWidget.text = "✓ Copied!";
this.setDirtyCanvas(true);
setTimeout(() => {
copyWidget.text = "📋 Copy Value";
this.setDirtyCanvas(true);
}, 1500);
}).catch(err => {
console.error('Failed to copy:', err);
});
}
};
this.addCustomWidget(copyWidget);
requestAnimationFrame(() => {
const sz = this.computeSize();
if (sz[0] < this.size[0]) {
sz[0] = this.size[0];
}
if (sz[1] < this.size[1]) {
sz[1] = this.size[1];
}
this.onResize?.(sz);
app.graph.setDirtyCanvas(true, false);
});
}
// When the node is executed we will be sent the display text
const onExecuted = nodeType.prototype.onExecuted;
nodeType.prototype.onExecuted = function (message) {
onExecuted?.apply(this, arguments);
console.log("DisplayAny onExecuted message:", message);
if (message?.text && message.text.length > 0) {
const displayText = message.text[0];
console.log("DisplayAny displayText:", displayText);
populate.call(this, displayText);
} else {
console.log("DisplayAny no text in message");
}
};
const VALUES = Symbol();
const configure = nodeType.prototype.configure;
nodeType.prototype.configure = function () {
this[VALUES] = arguments[0]?.widgets_values;
return configure?.apply(this, arguments);
};
const onConfigure = nodeType.prototype.onConfigure;
nodeType.prototype.onConfigure = function () {
onConfigure?.apply(this, arguments);
const widgets_values = this[VALUES];
if (widgets_values?.length) {
requestAnimationFrame(() => {
const startIdx = widgets_values.length > 1 && this.inputs?.[0]?.widget ? 1 : 0;
if (widgets_values[startIdx]) {
populate.call(this, widgets_values[startIdx]);
}
});
}
};
// Initialize on node creation
const onNodeCreated = nodeType.prototype.onNodeCreated;
nodeType.prototype.onNodeCreated = function() {
onNodeCreated?.apply(this, arguments);
// Set minimum size - make it wider for better JSON display
this.size[0] = Math.max(this.size[0], 450);
this.size[1] = Math.max(this.size[1], 250);
// Add placeholder text
populate.call(this, "Value will appear here...");
};
}
}
if (nodeData.name === 'DisplayAny') registerDisplayNode(nodeType, app, 'any');
},
});
+5 -195
View File
@@ -1,199 +1,9 @@
import { app } from "../../scripts/app.js";
import { ComfyWidgets } from "../../scripts/widgets.js";
import { app } from '../../scripts/app.js';
import { registerDisplayNode } from './controllers/display-node.js';
app.registerExtension({
name: "ComfyAssets.DisplayText",
name: 'ComfyAssets.DisplayText',
async beforeRegisterNodeDef(nodeType, nodeData, app) {
if (nodeData.name === "DisplayText") {
function populate(text) {
// Remove existing widgets
if (this.widgets) {
const toRemove = [];
for (let i = 0; i < this.widgets.length; i++) {
if (this.widgets[i].name?.startsWith("text_") || this.widgets[i].name?.startsWith("copy_")) {
this.widgets[i].onRemove?.();
toRemove.push(i);
}
}
// Remove in reverse order to maintain indices
for (let i = toRemove.length - 1; i >= 0; i--) {
this.widgets.splice(toRemove[i], 1);
}
}
// Parse the text to detect positive/negative prompt format
const posMatch = text.match(/Positive prompt:\s*([\s\S]*?)(?=Negative prompt:|$)/i);
const negMatch = text.match(/Negative prompt:\s*([\s\S]*?)(?=\*\*|$)/i);
if (posMatch && negMatch) {
// Extract prompt content
let positiveText = posMatch[1].trim();
let negativeText = negMatch[1].trim();
// Remove any trailing ** markers
const posEndIndex = positiveText.indexOf('**');
if (posEndIndex > 0) {
positiveText = positiveText.substring(0, posEndIndex).trim();
}
const negEndIndex = negativeText.indexOf('**');
if (negEndIndex > 0) {
negativeText = negativeText.substring(0, negEndIndex).trim();
}
// Create header widget for positive prompt
const posHeader = ComfyWidgets["STRING"](this, "text_pos_header", ["STRING", { multiline: false }], app).widget;
posHeader.inputEl.readOnly = true;
posHeader.inputEl.style.opacity = 0.7;
posHeader.inputEl.style.backgroundColor = "#2a4a2a";
posHeader.inputEl.style.color = "#8f8";
posHeader.inputEl.style.fontWeight = "bold";
posHeader.value = "✓ Positive Prompt";
// Create positive prompt widget
const posWidget = ComfyWidgets["STRING"](this, "text_positive", ["STRING", { multiline: true }], app).widget;
posWidget.inputEl.readOnly = true;
posWidget.inputEl.style.opacity = 0.9;
posWidget.value = positiveText;
// Create copy button widget for positive prompt
const posCopyWidget = {
type: "button",
name: "copy_positive",
text: "📋 Copy Positive",
callback: () => {
navigator.clipboard.writeText(positiveText).then(() => {
posCopyWidget.text = "✓ Copied!";
this.setDirtyCanvas(true);
setTimeout(() => {
posCopyWidget.text = "📋 Copy Positive";
this.setDirtyCanvas(true);
}, 1500);
}).catch(err => {
console.error('Failed to copy:', err);
});
}
};
this.addCustomWidget(posCopyWidget);
// Create header widget for negative prompt
const negHeader = ComfyWidgets["STRING"](this, "text_neg_header", ["STRING", { multiline: false }], app).widget;
negHeader.inputEl.readOnly = true;
negHeader.inputEl.style.opacity = 0.7;
negHeader.inputEl.style.backgroundColor = "#4a2a2a";
negHeader.inputEl.style.color = "#f88";
negHeader.inputEl.style.fontWeight = "bold";
negHeader.value = "✗ Negative Prompt";
// Create negative prompt widget
const negWidget = ComfyWidgets["STRING"](this, "text_negative", ["STRING", { multiline: true }], app).widget;
negWidget.inputEl.readOnly = true;
negWidget.inputEl.style.opacity = 0.9;
negWidget.value = negativeText;
// Create copy button widget for negative prompt
const negCopyWidget = {
type: "button",
name: "copy_negative",
text: "📋 Copy Negative",
callback: () => {
navigator.clipboard.writeText(negativeText).then(() => {
negCopyWidget.text = "✓ Copied!";
this.setDirtyCanvas(true);
setTimeout(() => {
negCopyWidget.text = "📋 Copy Negative";
this.setDirtyCanvas(true);
}, 1500);
}).catch(err => {
console.error('Failed to copy:', err);
});
}
};
this.addCustomWidget(negCopyWidget);
} else {
// Single text display with ComfyUI's standard STRING widget
const w = ComfyWidgets["STRING"](this, "text_display", ["STRING", { multiline: true }], app).widget;
w.inputEl.readOnly = true;
w.inputEl.style.opacity = 0.9;
w.value = text;
// Create copy button widget
const copyWidget = {
type: "button",
name: "copy_text",
text: "📋 Copy",
callback: () => {
navigator.clipboard.writeText(text).then(() => {
copyWidget.text = "✓ Copied!";
this.setDirtyCanvas(true);
setTimeout(() => {
copyWidget.text = "📋 Copy";
this.setDirtyCanvas(true);
}, 1500);
}).catch(err => {
console.error('Failed to copy:', err);
});
}
};
this.addCustomWidget(copyWidget);
}
requestAnimationFrame(() => {
const sz = this.computeSize();
if (sz[0] < this.size[0]) {
sz[0] = this.size[0];
}
if (sz[1] < this.size[1]) {
sz[1] = this.size[1];
}
this.onResize?.(sz);
app.graph.setDirtyCanvas(true, false);
});
}
// When the node is executed we will be sent the input text
const onExecuted = nodeType.prototype.onExecuted;
nodeType.prototype.onExecuted = function (message) {
onExecuted?.apply(this, arguments);
if (message?.text) {
populate.call(this, message.text[0]);
}
};
const VALUES = Symbol();
const configure = nodeType.prototype.configure;
nodeType.prototype.configure = function () {
this[VALUES] = arguments[0]?.widgets_values;
return configure?.apply(this, arguments);
};
const onConfigure = nodeType.prototype.onConfigure;
nodeType.prototype.onConfigure = function () {
onConfigure?.apply(this, arguments);
const widgets_values = this[VALUES];
if (widgets_values?.length) {
requestAnimationFrame(() => {
const startIdx = widgets_values.length > 1 && this.inputs?.[0]?.widget ? 1 : 0;
if (widgets_values[startIdx]) {
populate.call(this, widgets_values[startIdx]);
}
});
}
};
// Initialize on node creation
const onNodeCreated = nodeType.prototype.onNodeCreated;
nodeType.prototype.onNodeCreated = function() {
onNodeCreated?.apply(this, arguments);
// Set default size
this.size[0] = Math.max(this.size[0], 400);
this.size[1] = Math.max(this.size[1], 300);
// Add placeholder text
populate.call(this, "Text will appear here after execution...");
};
}
}
if (nodeData.name === 'DisplayText') registerDisplayNode(nodeType, app, 'text');
},
});
+18
View File
@@ -123,3 +123,21 @@ an immediate `close()` method. OK/Enter supplies the dialog and input/select
values; Cancel/Escape invokes cancellation once. Manual `close()` dismisses
without invoking cancellation. New views should build DOM through shared
factories rather than pass HTML to this compatibility helper.
## Display Text and Display Any
Both nodes use `../views/text-output.js` for labelled, selectable read-only text
areas and shared Copy buttons. Display Text detects paired positive/negative
prompts and offers a copy action for each. Display Any preserves the complete
formatted output in one scrollable monospace field instead of separate chunks.
The view fills the available node area; updating output preserves node size.
Copy success and failure appear in a polite status area. Replacement and removal
cancel delayed feedback and ignore pending clipboard results from the old view.
`../controllers/display-node.js` preserves native input/mode widgets and existing
lifecycle hook arguments, context and return values. Complete output, including
empty text, is saved in a `kikoDisplay: { version: 1, text }` workflow snapshot.
Legacy widget values remain readable: converted input prefixes, prompt header
pairs, native Display Any modes and all saved output chunks are recognized.
The new output DOM widget does not serialize presentation state into native
widget values. Node removal disposes the view, its listeners and theme observers.
+13
View File
@@ -188,3 +188,16 @@
.ca-dialog-error:empty { display: none; }
.ca-dialog input[aria-invalid="true"] { border-color: var(--ca-error); }
@media (max-width: 360px) { .ca-dimension-fields { grid-template-columns: minmax(0, 1fr); } }
.ca-text-output { display: flex; flex-direction: column; gap: 10px; inline-size: 100%; block-size: 100%; min-block-size: 180px; padding: 12px; border-radius: 6px; contain: size; overflow: auto; box-sizing: border-box; }
.ca-text-output > header { display: flex; align-items: center; justify-content: space-between; gap: 8px; padding-block-end: 8px; border-block-end: 1px solid var(--ca-line); }
.ca-text-output h2 { font-size: 13px; font-weight: 550; margin: 0; }
.ca-text-output > header span { color: var(--ca-muted); font-size: 10px; }
.ca-output-content { display: flex; flex-direction: column; flex: 1; gap: 12px; min-block-size: 0; overflow: auto; }
.ca-output-section { display: flex; flex-direction: column; flex: 1 0 110px; gap: 6px; min-inline-size: 0; }
.ca-output-toolbar { display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap; gap: 6px; }
.ca-output-toolbar label { font-size: 12px; font-weight: 550; }
.ca-text-output textarea { inline-size: 100%; flex: 1; min-block-size: 64px; resize: none; opacity: 1; }
.ca-text-output[data-output-kind="any"] textarea { font-family: ui-monospace, SFMono-Regular, Consolas, monospace; }
.ca-text-output > p { font-size: 11px; color: var(--ca-muted); min-block-size: 17px; margin: 0; }
.ca-text-output > p[data-error="true"] { color: var(--ca-error-text); }
+86
View File
@@ -0,0 +1,86 @@
import { createButton, createScope, mountTheme } from '../ui/core.js';
let nextOutput = 0;
export function outputSections(kind, text) {
if (kind === 'text') {
const positive = text.match(/Positive prompt:\s*([\s\S]*?)(?=Negative prompt:|$)/i);
const negative = text.match(/Negative prompt:\s*([\s\S]*?)(?=\*\*|$)/i);
if (positive && negative) {
let positiveText = positive[1].trim();
const marker = positiveText.indexOf('**');
if (marker > 0) positiveText = positiveText.slice(0, marker).trim();
return [
{ label: 'Positive prompt', copy: 'Copy positive', text: positiveText },
{ label: 'Negative prompt', copy: 'Copy negative', text: negative[1].trim() },
];
}
}
return [{ label: kind === 'text' ? 'Text output' : 'Value output', copy: kind === 'text' ? 'Copy text' : 'Copy value', text }];
}
export function createTextOutputView(scope, kind, settings) {
const element = document.createElement('div');
element.className = 'ca-tools ca-text-output';
element.dataset.outputKind = kind;
const header = document.createElement('header');
const title = document.createElement('h2');
title.textContent = kind === 'text' ? 'Display Text' : 'Display Any';
const brand = document.createElement('span');
brand.textContent = 'ComfyAssets';
header.append(title, brand);
const content = document.createElement('div');
content.className = 'ca-output-content';
const status = document.createElement('p');
status.role = 'status';
element.append(header, content, status);
mountTheme(element, settings, scope);
let renderScope;
scope.cleanup(() => {
renderScope?.dispose();
element.remove();
});
return {
element,
update(text) {
renderScope?.dispose();
const current = createScope();
renderScope = current;
content.replaceChildren();
status.textContent = '';
delete status.dataset.error;
const clearStatus = current.debounce(() => { status.textContent = ''; }, 1500);
for (const section of outputSections(kind, text)) {
const row = document.createElement('div');
row.className = 'ca-output-section';
const toolbar = document.createElement('div');
toolbar.className = 'ca-output-toolbar';
const input = document.createElement('textarea');
input.id = `ca-output-${++nextOutput}`;
input.readOnly = true;
input.spellcheck = false;
input.value = section.text;
const label = document.createElement('label');
label.htmlFor = input.id;
label.textContent = section.label;
const copy = createButton(section.copy, 'ca-primary');
toolbar.append(label, copy);
row.append(toolbar, input);
content.append(row);
current.listen(copy, 'click', async () => {
try {
await navigator.clipboard.writeText(section.text);
if (current.signal.aborted) return;
delete status.dataset.error;
status.textContent = 'Copied.';
clearStatus();
} catch {
if (current.signal.aborted) return;
status.dataset.error = 'true';
status.textContent = 'Could not copy. Select the text and copy it manually.';
}
});
}
},
};
}