Files
site-builder/craft/src/editor/RichTextToolbar.test.tsx
T
shadowdaoandClaude Opus 5.5 7e8812a752 feat(site-builder): inline bold/italic/underline/links on Heading and Text
Select text inside a selected Heading or Text block and a floating
toolbar offers B / I / U / Link / Unlink (execCommand; mousedown is
prevented so the selection survives; mod+b/i/u handled on the editable).

Storage: new `html` prop holding sanitised inline HTML, with `text` kept
as the plain mirror for AI summaries, search and legacy content.
Unmarked edits store html '' so legacy nodes keep their shape. The
allowlist (b strong i em u a br span; style=color only, hex/rgb/
var(--wsb-*); href via DOMPurify URI check AND safeUrl, unsafe links
unwrapped; target only _blank with forced rel=noopener) runs on commit,
on canvas render and again at export. If `text` was changed without
`html` (Sitesmith update_props), the stale html is ignored.

Each edit commits once (blur, or deselect if no blur came first) as one
setProp = one undo step; the old blur+deselect double commit is gone.
Heading colour default now tokenRef('text'). Sitesmith canvas summary
skips `html`.

Refs #46

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-07 11:41:56 -07:00

175 lines
6.3 KiB
TypeScript

import { describe, test, expect, afterEach, vi } from 'vitest';
import React from 'react';
import { renderEditorHarness, EditorHarness } from '../test-utils/editorHarness';
import { RichTextToolbar, normalizeLinkInput } from './RichTextToolbar';
const STATE = JSON.stringify({
ROOT: {
type: { resolvedName: 'Container' }, isCanvas: true, props: { style: {}, tag: 'div' },
displayName: 'Container', custom: {}, hidden: false, nodes: ['h-1', 'b-1'], linkedNodes: {},
},
'h-1': {
type: { resolvedName: 'Heading' }, isCanvas: false,
props: { text: 'Hello World', html: '', level: 'h2', style: {} },
displayName: 'Heading', custom: {}, hidden: false, parent: 'ROOT', nodes: [], linkedNodes: {},
},
'b-1': {
type: { resolvedName: 'ButtonLink' }, isCanvas: false,
props: { text: 'Go', href: '#' },
displayName: 'Button', custom: {}, hidden: false, parent: 'ROOT', nodes: [], linkedNodes: {},
},
});
let harness: EditorHarness | null = null;
let exec: ReturnType<typeof vi.fn>;
afterEach(() => {
window.getSelection()?.removeAllRanges();
delete (document as any).execCommand;
harness?.unmount();
harness = null;
});
function setup() {
harness = renderEditorHarness({ initialState: STATE });
harness.mountChild(<RichTextToolbar />);
harness.act(() => { harness!.actions.history.clear(); });
// jsdom has no execCommand; stub one that records calls.
exec = vi.fn(() => true);
(document as any).execCommand = exec;
}
const heading = () => harness!.query.node('h-1').get().dom as HTMLElement;
const toolbar = () => harness!.container.querySelector('.rt-toolbar');
const btn = (label: string) => harness!.container.querySelector(`[aria-label="${label}"]`) as HTMLElement;
function selectText(el: HTMLElement) {
harness!.act(() => {
const range = document.createRange();
range.selectNodeContents(el);
const sel = window.getSelection()!;
sel.removeAllRanges();
sel.addRange(range);
document.dispatchEvent(new Event('selectionchange'));
});
}
function press(el: HTMLElement) {
harness!.act(() => {
const down = new MouseEvent('mousedown', { bubbles: true, cancelable: true });
el.dispatchEvent(down);
expect(down.defaultPrevented).toBe(true); // selection must survive
el.dispatchEvent(new MouseEvent('click', { bubbles: true }));
});
}
describe('RichTextToolbar (#46)', () => {
test('renders over a non-collapsed selection inside a selected Heading', () => {
setup();
harness!.act(() => { harness!.actions.selectNode('h-1'); });
expect(toolbar()).toBeNull();
selectText(heading());
expect(toolbar()).not.toBeNull();
expect(toolbar()!.getAttribute('role')).toBe('toolbar');
});
test('B / I / U / Unlink run the matching execCommand and mark the edit', () => {
setup();
harness!.act(() => { harness!.actions.selectNode('h-1'); });
selectText(heading());
press(btn('Bold'));
press(btn('Italic'));
press(btn('Underline'));
press(btn('Remove link'));
expect(exec.mock.calls.map((c) => c[0])).toEqual(['bold', 'italic', 'underline', 'unlink']);
});
test('B followed by blur commits the formatted html as one undo step', () => {
setup();
harness!.act(() => { harness!.actions.selectNode('h-1'); });
selectText(heading());
exec.mockImplementation(() => { heading().innerHTML = '<b>Hello</b> World'; return true; });
press(btn('Bold'));
harness!.act(() => { heading().dispatchEvent(new FocusEvent('focusout', { bubbles: true })); });
const props = harness!.query.node('h-1').get().data.props;
expect(props.html).toBe('<b>Hello</b> World');
expect(props.text).toBe('Hello World');
expect(harness!.query.history.canUndo()).toBe(true);
harness!.act(() => { harness!.actions.history.undo(); });
expect(harness!.query.history.canUndo()).toBe(false);
});
test('hidden when the selection collapses', () => {
setup();
harness!.act(() => { harness!.actions.selectNode('h-1'); });
selectText(heading());
expect(toolbar()).not.toBeNull();
harness!.act(() => {
window.getSelection()!.collapseToStart();
document.dispatchEvent(new Event('selectionchange'));
});
expect(toolbar()).toBeNull();
});
test('hidden when the node is deselected', () => {
setup();
harness!.act(() => { harness!.actions.selectNode('h-1'); });
selectText(heading());
harness!.act(() => { harness!.actions.selectNode(); });
expect(toolbar()).toBeNull();
});
test('not shown for a selection in an unselected Heading', () => {
setup();
selectText(heading());
expect(toolbar()).toBeNull();
});
test('not shown for a contenteditable that is not a selected Heading/Text node', () => {
setup();
harness!.act(() => { harness!.actions.selectNode('b-1'); });
const stray = document.createElement('div');
stray.setAttribute('contenteditable', 'true');
stray.textContent = 'elsewhere';
document.body.appendChild(stray);
selectText(stray);
expect(toolbar()).toBeNull();
stray.remove();
});
test('Link: unsafe URL is refused, a bare domain becomes https://', () => {
setup();
harness!.act(() => { harness!.actions.selectNode('h-1'); });
selectText(heading());
press(btn('Link'));
const input = harness!.container.querySelector('input[aria-label="Link URL"]') as HTMLInputElement;
expect(input).not.toBeNull();
const submit = (v: string) => harness!.act(() => {
Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value')!.set!.call(input, v);
input.dispatchEvent(new Event('input', { bubbles: true }));
input.form!.dispatchEvent(new Event('submit', { bubbles: true, cancelable: true }));
});
submit('javascript:alert(1)');
expect(exec).not.toHaveBeenCalled();
expect(input.getAttribute('aria-invalid')).toBe('true');
submit('example.com/path');
expect(exec).toHaveBeenCalledWith('createLink', false, 'https://example.com/path');
});
});
describe('normalizeLinkInput', () => {
test.each([
['example.com', 'https://example.com'],
['https://e.com/x', 'https://e.com/x'],
['/about', '/about'],
['#contact', '#contact'],
['mailto:a@b.co', 'mailto:a@b.co'],
['javascript:alert(1)', ''],
[' JaVa\tScRiPt:alert(1)', ''],
['data:text/html,x', ''],
['', ''],
])('%j -> %j', (input, expected) => {
expect(normalizeLinkInput(input)).toBe(expected);
});
});