From 23ff42cc4092da3aa29346b5be3f1f3c3e873c88 Mon Sep 17 00:00:00 2001 From: woksin Date: Sun, 22 Nov 2026 04:46:08 +0100 Subject: [PATCH 1/5] Characterize number normalization and canvas note interactions --- .../shapes/Note/for_Note/given/a_note.tsx | 40 ++++++++++++ .../Note/for_Note/when_committing_text.tsx | 50 ++++++++++++++ .../Note/for_Note/when_fitting_text.tsx | 54 +++++++++++++++ .../for_Note/when_moving_and_resizing.tsx | 65 +++++++++++++++++++ .../when_normalizing_controlled_values.tsx | 44 +++++++++++++ 5 files changed, 253 insertions(+) create mode 100644 Source/Canvas/shapes/Note/for_Note/given/a_note.tsx create mode 100644 Source/Canvas/shapes/Note/for_Note/when_committing_text.tsx create mode 100644 Source/Canvas/shapes/Note/for_Note/when_fitting_text.tsx create mode 100644 Source/Canvas/shapes/Note/for_Note/when_moving_and_resizing.tsx create mode 100644 Source/Common/for_NumberInput/when_normalizing_controlled_values.tsx diff --git a/Source/Canvas/shapes/Note/for_Note/given/a_note.tsx b/Source/Canvas/shapes/Note/for_Note/given/a_note.tsx new file mode 100644 index 00000000..43214895 --- /dev/null +++ b/Source/Canvas/shapes/Note/for_Note/given/a_note.tsx @@ -0,0 +1,40 @@ +// Copyright (c) Cratis. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +import { act } from 'react'; +import { vi } from 'vitest'; +import { Note, type NoteProps } from '../../Note'; +import { mountPrimitive } from '../../../../../Common/for_Primitives/given/a_primitive_dom'; + +export const mountNote = async (overrides: Partial = {}) => { + const props: NoteProps = { + note: { id: 'sample-note', x: 10, y: 20, width: 200, height: 160, text: 'Sample note' }, + selected: true, + onSelect: vi.fn(), + onMove: vi.fn(), + onMoveEnd: vi.fn(), + onResize: vi.fn(), + onResizeEnd: vi.fn(), + onTextChange: vi.fn(), + onExpandedChange: vi.fn(), + ...overrides, + }; + const mounted = await mountPrimitive(); + const element = mounted.container.querySelector('.canvas-note')!; + element.setPointerCapture = vi.fn(); + const handles = Array.from(element.querySelectorAll('.canvas-note__handle')); + handles.forEach(handle => { handle.setPointerCapture = vi.fn(); }); + return { ...mounted, props, element, handles }; +}; + +export const pointAt = async ( + element: HTMLElement, + type: string, + options: MouseEventInit = {}, +) => { + await act(async () => { + const event = new MouseEvent(type, { bubbles: true, buttons: 1, ...options }); + Object.defineProperty(event, 'pointerId', { value: 1 }); + element.dispatchEvent(event); + }); +}; diff --git a/Source/Canvas/shapes/Note/for_Note/when_committing_text.tsx b/Source/Canvas/shapes/Note/for_Note/when_committing_text.tsx new file mode 100644 index 00000000..e2686844 --- /dev/null +++ b/Source/Canvas/shapes/Note/for_Note/when_committing_text.tsx @@ -0,0 +1,50 @@ +// Copyright (c) Cratis. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +// @vitest-environment jsdom + +import { act } from 'react'; +import { expect } from 'chai'; +import { afterEach, describe, it, vi } from 'vitest'; +import { setNativeValue, unmountPrimitive } from '../../../../Common/for_Primitives/given/a_primitive_dom'; +import { NoteTextChanged } from '../NoteTextChanged'; +import { mountNote, pointAt } from './given/a_note'; + +const { publish } = vi.hoisted(() => ({ publish: vi.fn() })); +vi.mock('../../../../Common/messaging/useOptionalMessenger', () => ({ useOptionalMessenger: () => publish })); + +describe('when committing note text', () => { + let mounted: Awaited>; + + afterEach(async () => { + if (mounted) await unmountPrimitive(mounted); + vi.clearAllMocks(); + }); + + it('should commit and publish once on blur rather than per keystroke', async () => { + mounted = await mountNote(); + await act(async () => mounted.element.dispatchEvent(new MouseEvent('dblclick', { bubbles: true }))); + const textarea = mounted.element.querySelector('textarea')!; + await setNativeValue(textarea, 'Updated sample note'); + expect(mounted.props.onTextChange).not.toHaveBeenCalled(); + expect(publish).not.toHaveBeenCalled(); + await act(async () => textarea.blur()); + expect(mounted.props.onTextChange).toHaveBeenCalledExactlyOnceWith('sample-note', 'Updated sample note'); + expect(publish).toHaveBeenCalledExactlyOnceWith(new NoteTextChanged('sample-note', 'Updated sample note')); + expect(vi.mocked(mounted.props.onTextChange).mock.invocationCallOrder[0]).to.be.lessThan(publish.mock.invocationCallOrder[0]); + expect(mounted.element.querySelector('textarea')).to.equal(null); + }); + + it('should cancel editing on Escape and ignore note dragging while editing', async () => { + mounted = await mountNote(); + await act(async () => mounted.element.dispatchEvent(new MouseEvent('dblclick', { bubbles: true }))); + const textarea = mounted.element.querySelector('textarea')!; + await setNativeValue(textarea, 'Uncommitted sample'); + await pointAt(mounted.element, 'pointerdown'); + await act(async () => textarea.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape', bubbles: true }))); + expect(mounted.props.onSelect).not.toHaveBeenCalled(); + expect(mounted.props.onTextChange).not.toHaveBeenCalled(); + expect(publish).not.toHaveBeenCalled(); + expect(mounted.element.querySelector('.canvas-note__text')?.textContent).to.equal('Sample note'); + }); +}); diff --git a/Source/Canvas/shapes/Note/for_Note/when_fitting_text.tsx b/Source/Canvas/shapes/Note/for_Note/when_fitting_text.tsx new file mode 100644 index 00000000..a8a3fd39 --- /dev/null +++ b/Source/Canvas/shapes/Note/for_Note/when_fitting_text.tsx @@ -0,0 +1,54 @@ +// Copyright (c) Cratis. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +// @vitest-environment jsdom + +import { act } from 'react'; +import { expect } from 'chai'; +import { afterEach, describe, it, vi } from 'vitest'; +import { unmountPrimitive } from '../../../../Common/for_Primitives/given/a_primitive_dom'; +import { mountNote, pointAt } from './given/a_note'; + +describe('when fitting note text', () => { + let mounted: Awaited>; + + afterEach(async () => { + if (mounted) await unmountPrimitive(mounted); + vi.restoreAllMocks(); + }); + + it('should fit the largest font within the padded height', async () => { + vi.spyOn(HTMLElement.prototype, 'scrollHeight', 'get').mockImplementation(function (this: HTMLElement) { + return Number.parseFloat(this.style.fontSize) * 2; + }); + mounted = await mountNote(); + const text = mounted.element.querySelector('.canvas-note__text')!; + expect(Number.parseFloat(text.style.fontSize)).to.be.within(67, 68); + expect(mounted.element.querySelector('button')).to.equal(null); + expect(mounted.props.onExpandedChange).toHaveBeenCalledWith('sample-note', false); + }); + + it('should expand overflowing text temporarily and hide resize handles while expanded', async () => { + vi.spyOn(HTMLElement.prototype, 'scrollHeight', 'get').mockReturnValue(300); + mounted = await mountNote(); + const button = mounted.element.querySelector('.canvas-note__expand')!; + expect(button.getAttribute('aria-label')).to.equal('See full text'); + expect(mounted.element.querySelector('.canvas-note__text')?.style.fontSize).to.equal('4px'); + await act(async () => button.click()); + expect(mounted.element.style.height).to.equal('324px'); + expect(mounted.element.classList.contains('canvas-note--expanded')).to.equal(true); + expect(mounted.element.querySelectorAll('.canvas-note__handle').length).to.equal(0); + expect(mounted.props.onExpandedChange).toHaveBeenLastCalledWith('sample-note', true); + await pointAt(mounted.element, 'pointerout', { relatedTarget: document.body }); + expect(mounted.element.style.height).to.equal('160px'); + expect(mounted.element.querySelectorAll('.canvas-note__handle').length).to.equal(8); + expect(mounted.props.onExpandedChange).toHaveBeenLastCalledWith('sample-note', false); + }); + + it('should size blank text from the note dimensions without showing overflow', async () => { + vi.spyOn(HTMLElement.prototype, 'scrollHeight', 'get').mockReturnValue(300); + mounted = await mountNote({ note: { id: 'blank-note', x: 0, y: 0, width: 200, height: 160, text: ' ' } }); + expect(mounted.element.querySelector('.canvas-note__text')?.style.fontSize).to.equal('64px'); + expect(mounted.element.querySelector('button')).to.equal(null); + }); +}); diff --git a/Source/Canvas/shapes/Note/for_Note/when_moving_and_resizing.tsx b/Source/Canvas/shapes/Note/for_Note/when_moving_and_resizing.tsx new file mode 100644 index 00000000..f29741aa --- /dev/null +++ b/Source/Canvas/shapes/Note/for_Note/when_moving_and_resizing.tsx @@ -0,0 +1,65 @@ +// Copyright (c) Cratis. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +// @vitest-environment jsdom + +import { expect } from 'chai'; +import { afterEach, describe, it, vi } from 'vitest'; +import { unmountPrimitive } from '../../../../Common/for_Primitives/given/a_primitive_dom'; +import { mountNote, pointAt } from './given/a_note'; + +describe('when moving and resizing a note', () => { + let mounted: Awaited>; + + afterEach(async () => { + if (mounted) await unmountPrimitive(mounted); + vi.restoreAllMocks(); + }); + + it('should select additively and move in world coordinates at the effective zoom', async () => { + mounted = await mountNote(); + vi.spyOn(mounted.element, 'getBoundingClientRect').mockReturnValue({ width: 400 } as DOMRect); + await pointAt(mounted.element, 'pointerdown', { clientX: 100, clientY: 100, shiftKey: true }); + await pointAt(mounted.element, 'pointermove', { clientX: 140, clientY: 160 }); + await pointAt(mounted.element, 'pointerup'); + await pointAt(mounted.element, 'pointercancel'); + expect(mounted.props.onSelect).toHaveBeenCalledExactlyOnceWith('sample-note', true); + expect(mounted.props.onMove).toHaveBeenCalledExactlyOnceWith('sample-note', 30, 50); + expect(mounted.props.onMoveEnd).toHaveBeenCalledExactlyOnceWith('sample-note'); + }); + + it('should ignore movement without pressed buttons or an active drag', async () => { + mounted = await mountNote(); + await pointAt(mounted.element, 'pointermove', { clientX: 50 }); + await pointAt(mounted.element, 'pointerdown'); + await pointAt(mounted.element, 'pointermove', { clientX: 50, buttons: 0 }); + expect(mounted.props.onMove).not.toHaveBeenCalled(); + }); + + it('should keep the opposite edges anchored when northwest resizing hits the minimum', async () => { + mounted = await mountNote(); + await pointAt(mounted.handles[0], 'pointerdown', { clientX: 10, clientY: 20 }); + await pointAt(mounted.handles[0], 'pointermove', { clientX: 500, clientY: 500 }); + await pointAt(mounted.handles[0], 'pointercancel'); + await pointAt(mounted.handles[0], 'pointerup'); + expect(mounted.props.onResize).toHaveBeenCalledExactlyOnceWith('sample-note', 130, 100, 80, 80); + expect(mounted.props.onResizeEnd).toHaveBeenCalledExactlyOnceWith('sample-note'); + expect(mounted.props.onSelect).not.toHaveBeenCalled(); + expect(mounted.props.onMove).not.toHaveBeenCalled(); + }); + + it('should resize every edge and corner without moving unaffected edges', async () => { + mounted = await mountNote(); + const bounds = [ + [30, 50, 180, 130], [10, 50, 200, 130], [10, 50, 220, 130], [10, 20, 220, 160], + [10, 20, 220, 190], [10, 20, 200, 190], [30, 20, 180, 190], [30, 20, 180, 160], + ]; + for (const [index, handle] of mounted.handles.entries()) { + await pointAt(handle, 'pointerdown'); + await pointAt(handle, 'pointermove', { clientX: 20, clientY: 30 }); + await pointAt(handle, 'pointerup'); + expect(mounted.props.onResize).toHaveBeenLastCalledWith('sample-note', ...bounds[index]); + } + expect(mounted.props.onResizeEnd).toHaveBeenCalledTimes(8); + }); +}); diff --git a/Source/Common/for_NumberInput/when_normalizing_controlled_values.tsx b/Source/Common/for_NumberInput/when_normalizing_controlled_values.tsx new file mode 100644 index 00000000..a3136d5c --- /dev/null +++ b/Source/Common/for_NumberInput/when_normalizing_controlled_values.tsx @@ -0,0 +1,44 @@ +// Copyright (c) Cratis. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +// @vitest-environment jsdom + +import { act } from 'react'; +import { expect } from 'chai'; +import { afterEach, describe, it } from 'vitest'; +import { NumberInput } from '../NumberInput'; +import { mountPrimitive, unmountPrimitive, type MountedPrimitive } from '../for_Primitives/given/a_primitive_dom'; +import { mountNumberInput } from './given/a_number_input'; + +describe('when normalizing controlled number values', () => { + let mounted: MountedPrimitive | undefined; + + afterEach(async () => { + if (mounted) await unmountPrimitive(mounted); + mounted = undefined; + }); + + it('should snap relative to the minimum without stepping beyond a nonaligned maximum', async () => { + const numberInput = await mountNumberInput({ + initialValue: 12, + min: 1, + max: 10, + step: 4, + 'aria-label': 'Sample quantity', + }); + mounted = numberInput; + expect(numberInput.events).to.deep.equal([{ kind: 'change', value: 9 }]); + expect(numberInput.input.value).to.equal('9'); + }); + + it('should request a rejected normalization only once until the controlled value changes', async () => { + const changes: (number | null)[] = []; + const render = (value: number) => changes.push(next)} />; + mounted = await mountPrimitive(render(12)); + await act(async () => mounted!.root.render(render(12))); + expect(changes).to.deep.equal([10]); + await act(async () => mounted!.root.render(render(8))); + await act(async () => mounted!.root.render(render(12))); + expect(changes).to.deep.equal([10, 10]); + }); +}); From 4a4c9b649ef58f35ffc6b89aba4bb2b46af60ec9 Mon Sep 17 00:00:00 2001 From: woksin Date: Sun, 22 Nov 2026 04:54:43 +0100 Subject: [PATCH 2/5] Describe atomic and tab presentation props for the picker Expose accessible labels for ProgressBar, Surface, NumericInput, and Tabs, plus progress value visibility and numeric placeholders. Keep values, constraints, tab items, and callbacks outside presentation editing. --- Documentation/ComponentPicker/index.md | 6 + Source/Common/NumericInputImplementation.tsx | 14 +- Source/Common/SurfaceImplementation.tsx | 16 ++- Source/Common/Tabs.tsx | 108 ++++++++------- .../given/atomic_and_tab_components.tsx | 80 +++++++++++ ...when_picking_atomic_and_tab_components.tsx | 90 ++++++++++++ ...previewing_atomic_and_tab_presentation.tsx | 131 ++++++++++++++++++ Source/Display/ProgressBarImplementation.tsx | 27 ++-- .../when_checking_presentation_descriptors.ts | 4 +- .../when_preserving_presentation_dom.tsx | 4 +- 10 files changed, 410 insertions(+), 70 deletions(-) create mode 100644 Source/ComponentPicker/for_ComponentPicker/given/atomic_and_tab_components.tsx create mode 100644 Source/ComponentPicker/for_ComponentPicker/when_picking_atomic_and_tab_components.tsx create mode 100644 Source/ComponentPicker/for_ComponentPicker/when_previewing_atomic_and_tab_presentation.tsx diff --git a/Documentation/ComponentPicker/index.md b/Documentation/ComponentPicker/index.md index 56e4bdff..34c797f4 100644 --- a/Documentation/ComponentPicker/index.md +++ b/Documentation/ComponentPicker/index.md @@ -139,6 +139,10 @@ Components with descriptors today: | `Tag` | `Tag` | `severity`, `rounded` | | `Skeleton` | `Skeleton` | `width`, `height`, `borderRadius`, `circle` | | `ProgressSpinner` | `ProgressSpinner` | `aria-label` | +| `ProgressBar` | `ProgressBar` | `showValue`, `aria-label` | +| `Surface` | `Surface` | `aria-label` | +| `NumericInput` | `NumericInput` | `placeholder`, `aria-label` | +| `Tabs` | `Tabs` | `aria-label` | | `Breadcrumbs` | `Breadcrumbs` | `aria-label` | | `Message` | `Message` | `severity` | | `Toolbar` | `Toolbar` | `orientation`, `aria-label` | @@ -152,6 +156,8 @@ Components with descriptors today: `DataPage` renders a `Page` and is marked `DataPage`; its title is the `Page` title property. +The `Tabs` accessible label belongs to its tab list. Progress values, numeric input values and constraints, tab items, selected values, and callbacks are not exposed as editable presentation properties. + ### Describe your own component To make your own component pickable and editable, declare its presentation properties with `describeComponent`, then pass that descriptor and the incoming props to `useComponentPresentation`. The descriptor's property names are checked against the component's props. In this `Banner`, the editor can propose a headline or emphasis change; `onDismiss` is not exposed: diff --git a/Source/Common/NumericInputImplementation.tsx b/Source/Common/NumericInputImplementation.tsx index 666902be..bc99d7f4 100644 --- a/Source/Common/NumericInputImplementation.tsx +++ b/Source/Common/NumericInputImplementation.tsx @@ -3,6 +3,13 @@ import { forwardRef, type ChangeEvent } from 'react'; import type { NumericInputProps } from './NumericInput'; +import { describeComponent } from '../configuration/identity/describeComponent'; +import { useComponentPresentation } from '../configuration/identity/useComponentPresentation'; + +const numericInputDescriptor = describeComponent('NumericInput', [ + { name: 'placeholder', label: 'Placeholder', type: 'string' }, + { name: 'aria-label', label: 'Accessible label', type: 'string' }, +]); type Root = NonNullable['root']; type AriaInvalid = NumericInputProps['aria-invalid']; @@ -43,6 +50,7 @@ export const NumericInputImplementation = forwardRef< HTMLInputElement, NumericInputProps >(function NumericInputImplementation(props, ref) { + const [presentation, marker] = useComponentPresentation(numericInputDescriptor, props); const { value, invalid: _invalid, @@ -54,14 +62,15 @@ export const NumericInputImplementation = forwardRef< readOnly: _readOnly, 'aria-invalid': _ariaInvalid, ...nativeProps - } = props; + } = presentation; const root = pt?.root; - const state = resolveState(props, root); + const state = resolveState(presentation, root); return ( ('Surface', [ + { name: 'aria-label', label: 'Accessible label', type: 'string' }, +]); const assignSurfaceRef = (ref: ForwardedRef, element: HTMLElement | null) => { if (typeof ref === 'function') ref(element); @@ -11,14 +17,15 @@ const assignSurfaceRef = (ref: ForwardedRef, element: HTMLElement | /** Core implementation for the semantic-surface presentation slot. */ export const SurfaceImplementation = forwardRef( - function SurfaceImplementation( - { as: Element = 'div', pt, className, style, ...nativeProps }, - ref, - ) { + function SurfaceImplementation(props, ref) { + const [presentation, marker] = useComponentPresentation(surfaceDescriptor, props); + const { as: Element = 'div' } = props; + const { as: _as, pt, className, style, ...nativeProps } = presentation; return ( { assignSurfaceRef(ref, element); }} @@ -27,7 +34,6 @@ export const SurfaceImplementation = forwardRef( .join(' ')} style={{ ...pt?.root?.style, ...style }} data-cratis-part='root' - data-cratis-component='Surface' /> ); }, diff --git a/Source/Common/Tabs.tsx b/Source/Common/Tabs.tsx index 0008fe9b..f3d462f5 100644 --- a/Source/Common/Tabs.tsx +++ b/Source/Common/Tabs.tsx @@ -11,6 +11,8 @@ import { import type { ExactPartKeys } from '../types/ExactPartKeys'; import type { PartsOf } from '../types/parts'; import { classNames } from '../ClassNames/classNames'; +import { describeComponent } from '../configuration/identity/describeComponent'; +import { useComponentPresentation } from '../configuration/identity/useComponentPresentation'; /** Attributes a consumer may hand to one {@link Tabs} part: class, style, title and data attributes. */ export type TabsPartAttributes = Pick< @@ -67,6 +69,10 @@ export interface TabsProps { pt?: TabsParts; } +const tabsDescriptor = describeComponent('Tabs', [ + { name: 'aria-label', label: 'Accessible label', type: 'string' }, +]); + /** * A tab set: a list of tabs, each optionally revealing a panel. * @@ -78,59 +84,63 @@ export interface TabsProps { * element that is not there. When the choice drives a view rendered elsewhere it is a *value* rather * than a panel — reach for `ToggleGroup`, which says so to assistive technology. */ -export const Tabs = ({ - tabs, - value, - onChange, - disabled = false, - 'aria-label': ariaLabel, - 'aria-labelledby': ariaLabelledBy, - className, - pt, -}: TabsProps) => ( - onChange(String(key))} - isDisabled={disabled} - className={classNames('cratis-tabs', pt?.root?.className, className)} - data-cratis-part='root' - data-cratis-component='Tabs' - data-disabled={disabled || undefined} - > - { + const [presentation, marker] = useComponentPresentation(tabsDescriptor, props); + const { + tabs, + value, + onChange, + disabled = false, + 'aria-label': ariaLabel, + 'aria-labelledby': ariaLabelledBy, + className, + pt, + } = presentation; + return ( + onChange(String(key))} + isDisabled={disabled} + className={classNames('cratis-tabs', pt?.root?.className, className)} + data-cratis-part='root' + data-disabled={disabled || undefined} > + + {tabs.map((tab) => ( + + {tab.label} + + ))} + {tabs.map((tab) => ( - - {tab.label} - + {tab.content} + ))} - - {tabs.map((tab) => ( - - {tab.content} - - ))} - -); + + ); +}; diff --git a/Source/ComponentPicker/for_ComponentPicker/given/atomic_and_tab_components.tsx b/Source/ComponentPicker/for_ComponentPicker/given/atomic_and_tab_components.tsx new file mode 100644 index 00000000..9645f9f9 --- /dev/null +++ b/Source/ComponentPicker/for_ComponentPicker/given/atomic_and_tab_components.tsx @@ -0,0 +1,80 @@ +// Copyright (c) Cratis. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +import React, { type ReactElement } from 'react'; +import { NumericInput } from '../../../Common/NumericInput'; +import { Surface } from '../../../Common/Surface'; +import { Tabs } from '../../../Common/Tabs'; +import { ProgressBar } from '../../../Display/ProgressBar'; +import type { PresentationPropertyDescriptor } from '../../../configuration/identity/PresentationPropertyDescriptor'; +import type { PresentationPropertyValue } from '../../../configuration/identity/PresentationPropertyValue'; + +interface PresentationComponentCase { + component: string; + element: ReactElement; + defaults: ReactElement; + properties: readonly PresentationPropertyDescriptor>[]; + current: Record; + preview: Record; + read: (element: HTMLElement) => unknown; + rendered: unknown; + previewed: unknown; + defaultRendered: unknown; +} + +export const atomicAndTabComponents: readonly PresentationComponentCase[] = [ + { + component: 'ProgressBar', + element: , + defaults: , + properties: [ + { name: 'showValue', label: 'Show value', type: 'boolean', defaultValue: true }, + { name: 'aria-label', label: 'Accessible label', type: 'string', defaultValue: 'Progress' }, + ], + current: { showValue: true, 'aria-label': 'Example progress' }, + preview: { showValue: false, 'aria-label': 'Preview progress' }, + read: (element) => [element.getAttribute('aria-label'), element.querySelector('[data-cratis-part="label"]')?.textContent], + rendered: ['Example progress', '40%'], + previewed: ['Preview progress', undefined], + defaultRendered: ['Progress', '0%'], + }, + { + component: 'Surface', + element: Example content, + defaults: , + properties: [{ name: 'aria-label', label: 'Accessible label', type: 'string' }], + current: { 'aria-label': 'Example surface' }, + preview: { 'aria-label': 'Preview surface' }, + read: (element) => element.getAttribute('aria-label'), + rendered: 'Example surface', + previewed: 'Preview surface', + defaultRendered: null, + }, + { + component: 'NumericInput', + element: , + defaults: , + properties: [ + { name: 'placeholder', label: 'Placeholder', type: 'string' }, + { name: 'aria-label', label: 'Accessible label', type: 'string' }, + ], + current: { placeholder: 'Example number', 'aria-label': 'Example quantity' }, + preview: { placeholder: 'Preview number', 'aria-label': 'Preview quantity' }, + read: (element) => [element.getAttribute('placeholder'), element.getAttribute('aria-label')], + rendered: ['Example number', 'Example quantity'], + previewed: ['Preview number', 'Preview quantity'], + defaultRendered: [null, null], + }, + { + component: 'Tabs', + element: undefined} />, + defaults: undefined} />, + properties: [{ name: 'aria-label', label: 'Accessible label', type: 'string' }], + current: { 'aria-label': 'Example tabs' }, + preview: { 'aria-label': 'Preview tabs' }, + read: (element) => element.querySelector('[role="tablist"]')!.getAttribute('aria-label'), + rendered: 'Example tabs', + previewed: 'Preview tabs', + defaultRendered: null, + }, +]; diff --git a/Source/ComponentPicker/for_ComponentPicker/when_picking_atomic_and_tab_components.tsx b/Source/ComponentPicker/for_ComponentPicker/when_picking_atomic_and_tab_components.tsx new file mode 100644 index 00000000..a8168026 --- /dev/null +++ b/Source/ComponentPicker/for_ComponentPicker/when_picking_atomic_and_tab_components.tsx @@ -0,0 +1,90 @@ +// Copyright (c) Cratis. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +// @vitest-environment jsdom + +import React, { act } from 'react'; +import { + knownComponentDescriptors, + previewPresentationChanges, + registeredComponentFor, +} from '../../configuration/identity/componentInstances'; +import type { PresentationChange } from '../../configuration/identity/PresentationChange'; +import { describeComponentElement } from '../describeComponentElement'; +import { atomicAndTabComponents } from './given/atomic_and_tab_components'; +import { click, hover, mountScreen, startPicking, unmountScreen, type ScreenInTheDom } from './given/a_screen_in_the_dom'; + +for (const example of atomicAndTabComponents) { + describe(`when picking a ${example.component}`, () => { + let screen: ScreenInTheDom; + let element: HTMLElement; + + beforeEach(async () => { + screen = await mountScreen(<>{example.element}{example.element}); + element = screen.container.querySelector(`[data-cratis-component="${example.component}"]`)!; + }); + + afterEach(async () => { + screen.picker().cancel(); + await unmountScreen(screen); + }); + + it('should register only its typed presentation properties', () => { + registeredComponentFor(element)!.descriptor.properties.should.deep.equal(example.properties); + }); + + it('should make its static descriptor discoverable', () => { + knownComponentDescriptors().find((descriptor) => descriptor.component === example.component)! + .should.equal(registeredComponentFor(element)!.descriptor); + }); + + it('should report current values through the picker', async () => { + const pending = await startPicking(screen); + await hover(element); + await click(element); + const picked = (await pending.result)!; + picked.component.should.equal(example.component); + picked.presentationProperties.map(({ name, value, editable }) => ({ name, value, editable })) + .should.deep.equal(Object.entries(example.current).map(([name, value]) => ({ name, value, editable: true }))); + }); + + it('should read registered values rather than DOM attributes', () => { + element.setAttribute('aria-label', 'DOM-only'); + element.setAttribute('placeholder', 'DOM-only'); + element.setAttribute('data-show-value', 'DOM-only'); + Object.fromEntries(describeComponentElement(element).presentationProperties.map(({ name, value }) => [name, value])) + .should.deep.equal(example.current); + }); + + it('should preview and revert without changing registered props or another instance', async () => { + const changes: PresentationChange[] = Object.entries(example.preview).map(([property, to]) => ({ + property, from: example.current[property], to, + })); + const original = registeredComponentFor(element)!.props; + const other = screen.container.querySelectorAll(`[data-cratis-component="${example.component}"]`)[1]; + let revert!: () => void; + [example.read(element)].should.deep.equal([example.rendered]); + await act(async () => { revert = previewPresentationChanges(element, changes); }); + [example.read(element)].should.deep.equal([example.previewed]); + [example.read(other)].should.deep.equal([example.rendered]); + registeredComponentFor(element)!.props.should.deep.equal(original); + Object.fromEntries(describeComponentElement(element).presentationProperties.map(({ name, value }) => [name, value])) + .should.deep.equal(example.current); + await act(async () => { revert(); revert(); }); + [example.read(element)].should.deep.equal([example.rendered]); + }); + + it('should preserve defaults while reporting unset props as editable', async () => { + await act(async () => screen.root.render(example.defaults)); + const defaultElement = screen.container.querySelector(`[data-cratis-component="${example.component}"]`)!; + [example.read(defaultElement)].should.deep.equal([example.defaultRendered]); + describeComponentElement(defaultElement).presentationProperties.map(({ name, value, editable }) => ({ name, value, editable })) + .should.deep.equal(example.properties.map(({ name }) => ({ name, value: undefined, editable: true }))); + }); + + it('should unregister when unmounted', async () => { + await act(async () => screen.root.render(<>)); + [registeredComponentFor(element)].should.deep.equal([undefined]); + }); + }); +} diff --git a/Source/ComponentPicker/for_ComponentPicker/when_previewing_atomic_and_tab_presentation.tsx b/Source/ComponentPicker/for_ComponentPicker/when_previewing_atomic_and_tab_presentation.tsx new file mode 100644 index 00000000..864b7fa7 --- /dev/null +++ b/Source/ComponentPicker/for_ComponentPicker/when_previewing_atomic_and_tab_presentation.tsx @@ -0,0 +1,131 @@ +// Copyright (c) Cratis. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +// @vitest-environment jsdom + +import React, { act, createRef } from 'react'; +import { NumericInput } from '../../Common/NumericInput'; +import { Surface } from '../../Common/Surface'; +import { Tabs } from '../../Common/Tabs'; +import { ProgressBar } from '../../Display/ProgressBar'; +import { previewPresentationChanges } from '../../configuration/identity/componentInstances'; +import { click, mountScreen, unmountScreen, type ScreenInTheDom } from './given/a_screen_in_the_dom'; + +const markerIn = (screen: ScreenInTheDom, component: string) => + screen.container.querySelector(`[data-cratis-component="${component}"]`)!; + +const previewLabel = (element: HTMLElement) => + previewPresentationChanges(element, [{ property: 'aria-label', from: undefined, to: 'Preview name' }]); + +describe('when previewing atomic and tab presentation details', () => { + let screen: ScreenInTheDom; + + afterEach(async () => { await unmountScreen(screen); }); + + it('should preserve progress bounds and external labeling when hiding the value label', async () => { + screen = await mountScreen(); + const element = markerIn(screen, 'ProgressBar'); + let revert!: () => void; + await act(async () => { + revert = previewPresentationChanges(element, [ + { property: 'showValue', from: undefined, to: false }, + { property: 'aria-label', from: undefined, to: 'Preview progress' }, + ]); + }); + [element.getAttribute('aria-label'), element.getAttribute('aria-labelledby'), element.getAttribute('aria-valuenow')] + .should.deep.equal([null, 'example-heading', '100']); + [element.querySelector('[data-cratis-part="label"]')].should.deep.equal([null]); + element.querySelector('[data-cratis-part="indicator"]')!.style.width.should.equal('100%'); + await act(async () => revert()); + element.querySelector('[data-cratis-part="label"]')!.textContent!.should.equal('100%'); + }); + + it('should leave indeterminate progress semantics unchanged during a label preview', async () => { + screen = await mountScreen(); + const element = markerIn(screen, 'ProgressBar'); + await act(async () => { previewLabel(element); }); + element.getAttribute('aria-label')!.should.equal('Preview name'); + [element.dataset.mode, element.dataset.busy, element.dataset.loading].should.deep.equal(['indeterminate', 'true', 'true']); + [element.getAttribute('aria-valuenow'), element.getAttribute('aria-valuemin'), element.getAttribute('aria-valuemax'), element.querySelector('[data-cratis-part="label"]')] + .should.deep.equal([null, null, null, null]); + }); + + it('should preserve surface markup, parts, children and callback refs during a label preview', async () => { + const refs: (HTMLElement | null)[] = []; + screen = await mountScreen( + { refs.push(element); }} className='example-surface' + style={{ padding: 8 }} pt={{ root: { className: 'example-part', style: { margin: 4 } } }}> + Example content + , + ); + const element = markerIn(screen, 'Surface'); + let revert!: () => void; + await act(async () => { revert = previewLabel(element); }); + element.getAttribute('aria-label')!.should.equal('Preview name'); + element.tagName.should.equal('ARTICLE'); + element.className.should.equal('cratis-surface example-part example-surface'); + [element.style.padding, element.style.margin].should.deep.equal(['8px', '4px']); + element.querySelector('strong')!.textContent!.should.equal('Example content'); + [refs.at(-1)].should.deep.equal([element]); + await act(async () => revert()); + [element.getAttribute('aria-label')].should.deep.equal([null]); + await act(async () => screen.root.render(<>)); + [refs.at(-1)].should.deep.equal([null]); + }); + + it('should preserve numeric input value, native state, parts and object refs without emitting changes', async () => { + const ref = createRef(); + const changes: (number | undefined)[] = []; + screen = await mountScreen( + { changes.push(value); }} + pt={{ root: { className: 'example-part', style: { margin: 4 }, placeholder: 'Example number' } }} />, + ); + const element = ref.current!; + let revert!: () => void; + await act(async () => { + revert = previewPresentationChanges(element, [ + { property: 'placeholder', from: undefined, to: 'Preview number' }, + { property: 'aria-label', from: undefined, to: 'Preview quantity' }, + ]); + }); + [element.placeholder, element.getAttribute('aria-label')].should.deep.equal(['Preview number', 'Preview quantity']); + [element.value, element.min, element.max, element.step, element.name, element.type].should.deep.equal(['12', '2', '20', '2', 'example-quantity', 'number']); + [element.disabled, element.readOnly, element.dataset.invalid, element.dataset.disabled, element.dataset.readonly].should.deep.equal([true, true, 'true', 'true', 'true']); + element.classList.contains('example-part').should.equal(true); + element.style.margin.should.equal('4px'); + [ref.current].should.deep.equal([element]); + await act(async () => revert()); + element.placeholder.should.equal('Example number'); + changes.should.deep.equal([]); + await act(async () => screen.root.render(<>)); + [ref.current].should.deep.equal([null]); + }); + + it('should preserve tab content, selection and callbacks during a tab-list label preview', async () => { + const selections: string[] = []; + screen = await mountScreen(First example, content: Example panel }, + { id: 'second', label: 'Second example', content: 'Another example panel' }, + { id: 'disabled', label: 'Disabled example', content: 'Disabled example panel', disabled: true }, + ]} value='first' onChange={(value) => { selections.push(value); }} pt={{ list: { className: 'example-list' } }} />); + const element = markerIn(screen, 'Tabs'); + let revert!: () => void; + await act(async () => { revert = previewLabel(element); }); + const list = element.querySelector('[role="tablist"]')!; + list.getAttribute('aria-label')!.should.equal('Preview name'); + list.getAttribute('aria-labelledby')!.split(' ').should.contain('example-heading'); + list.classList.contains('example-list').should.equal(true); + const tabs = element.querySelectorAll('[role="tab"]'); + tabs[0].getAttribute('aria-selected')!.should.equal('true'); + tabs[2].getAttribute('aria-disabled')!.should.equal('true'); + element.querySelector('strong')!.textContent!.should.equal('First example'); + element.querySelector('em')!.textContent!.should.equal('Example panel'); + selections.should.deep.equal([]); + await click(tabs[1]); + selections.should.deep.equal(['second']); + await act(async () => revert()); + [list.getAttribute('aria-label')].should.deep.equal([null]); + list.getAttribute('aria-labelledby')!.split(' ').should.contain('example-heading'); + }); +}); diff --git a/Source/Display/ProgressBarImplementation.tsx b/Source/Display/ProgressBarImplementation.tsx index 68591c5f..4cbbb3df 100644 --- a/Source/Display/ProgressBarImplementation.tsx +++ b/Source/Display/ProgressBarImplementation.tsx @@ -2,25 +2,34 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. import type { ProgressBarProps } from './ProgressBar'; +import { describeComponent } from '../configuration/identity/describeComponent'; +import { useComponentPresentation } from '../configuration/identity/useComponentPresentation'; + +const progressBarDescriptor = describeComponent('ProgressBar', [ + { name: 'showValue', label: 'Show value', type: 'boolean', defaultValue: true }, + { name: 'aria-label', label: 'Accessible label', type: 'string', defaultValue: 'Progress' }, +]); /** Core implementation for the progress-bar presentation slot. */ -export const ProgressBarImplementation = ({ - value = 0, - mode = 'determinate', - showValue = true, - 'aria-label': ariaLabel = 'Progress', - 'aria-labelledby': ariaLabelledBy, - className, -}: ProgressBarProps) => { +export const ProgressBarImplementation = (props: ProgressBarProps) => { + const [presentation, marker] = useComponentPresentation(progressBarDescriptor, props); + const { + value = 0, + mode = 'determinate', + showValue = true, + 'aria-label': ariaLabel = 'Progress', + 'aria-labelledby': ariaLabelledBy, + className, + } = presentation; const boundedValue = Math.min(100, Math.max(0, value)); const ariaValue = mode === 'determinate' ? boundedValue : undefined; const isBusy = mode === 'indeterminate' || boundedValue < 100; return (
[...source.matchAll(/describeComponent<\w+>\(\s*'(\w+)'/gu)].map((match) => match[1]); @@ -27,7 +27,7 @@ describe('when checking presentation descriptor coverage', () => { .should.deep.equal(['Example']); }); - it('should retain at least eighteen statically described component types', () => { + it('should retain at least twenty-two statically described component types', () => { const described = new Set(descriptorsIn(sourceRoot)); described.size.should.be.at.least(MINIMUM_DESCRIBED_COMPONENTS); }); diff --git a/Source/renderer/for_self_hosting/when_preserving_presentation_dom.tsx b/Source/renderer/for_self_hosting/when_preserving_presentation_dom.tsx index 81a752af..3cc8eb30 100644 --- a/Source/renderer/for_self_hosting/when_preserving_presentation_dom.tsx +++ b/Source/renderer/for_self_hosting/when_preserving_presentation_dom.tsx @@ -75,14 +75,14 @@ const baselines: Readonly> = Object.freeze({ controlSelector: 'input[role="switch"]', }, progress: { - html: '
42%
', + html: '
42%
', tags: { div: 1, span: 2 }, parts: { indicator: 1, label: 1, root: 1 }, roles: { progressbar: 1 }, controlSelector: '[role="progressbar"]', }, surface: { - html: '
Content
', + html: '
Content
', tags: { article: 1 }, parts: { root: 1 }, roles: {}, From f7508934fa3ca772345170959a95a66fe5a75bcb Mon Sep 17 00:00:00 2001 From: woksin Date: Sun, 22 Nov 2026 05:01:45 +0100 Subject: [PATCH 3/5] Mark NumericInput instances with their id or name --- Source/Common/NumericInputImplementation.tsx | 6 +++++- .../when_picking_atomic_and_tab_components.tsx | 17 +++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/Source/Common/NumericInputImplementation.tsx b/Source/Common/NumericInputImplementation.tsx index bc99d7f4..98e6e55d 100644 --- a/Source/Common/NumericInputImplementation.tsx +++ b/Source/Common/NumericInputImplementation.tsx @@ -50,7 +50,11 @@ export const NumericInputImplementation = forwardRef< HTMLInputElement, NumericInputProps >(function NumericInputImplementation(props, ref) { - const [presentation, marker] = useComponentPresentation(numericInputDescriptor, props); + const [presentation, marker] = useComponentPresentation( + numericInputDescriptor, + props, + props.id ?? props.name, + ); const { value, invalid: _invalid, diff --git a/Source/ComponentPicker/for_ComponentPicker/when_picking_atomic_and_tab_components.tsx b/Source/ComponentPicker/for_ComponentPicker/when_picking_atomic_and_tab_components.tsx index a8168026..709099ca 100644 --- a/Source/ComponentPicker/for_ComponentPicker/when_picking_atomic_and_tab_components.tsx +++ b/Source/ComponentPicker/for_ComponentPicker/when_picking_atomic_and_tab_components.tsx @@ -10,6 +10,7 @@ import { registeredComponentFor, } from '../../configuration/identity/componentInstances'; import type { PresentationChange } from '../../configuration/identity/PresentationChange'; +import { NumericInput } from '../../Common/NumericInput'; import { describeComponentElement } from '../describeComponentElement'; import { atomicAndTabComponents } from './given/atomic_and_tab_components'; import { click, hover, mountScreen, startPicking, unmountScreen, type ScreenInTheDom } from './given/a_screen_in_the_dom'; @@ -88,3 +89,19 @@ for (const example of atomicAndTabComponents) { }); }); } + +describe('when picking a NumericInput given an id or a name', () => { + let screen: ScreenInTheDom; + + beforeEach(async () => { + screen = await mountScreen(<>); + }); + + afterEach(async () => unmountScreen(screen)); + + it('should mark each instance with its id or name', () => { + Array.from(screen.container.querySelectorAll('[data-cratis-component="NumericInput"]')) + .map((element) => element.getAttribute('data-cratis-component-id')) + .should.deep.equal(['example-id', 'example-name']); + }); +}); From 662612c851690c86f94e8a33d12f2c7bca071a64 Mon Sep 17 00:00:00 2001 From: woksin Date: Sun, 22 Nov 2026 05:15:55 +0100 Subject: [PATCH 4/5] Decompose number input and canvas note internals --- Source/Canvas/shapes/Note/Note.tsx | 452 +-------------- Source/Canvas/shapes/Note/NoteData.ts | 18 + Source/Canvas/shapes/Note/NoteHandle.ts | 5 + Source/Canvas/shapes/Note/NoteProps.ts | 36 ++ Source/Canvas/shapes/Note/ResizeStart.ts | 15 + Source/Canvas/shapes/Note/fitText.ts | 35 ++ Source/Canvas/shapes/Note/renderHandles.tsx | 38 ++ Source/Canvas/shapes/Note/resizeBounds.ts | 21 + Source/Canvas/shapes/Note/textMetrics.ts | 11 + Source/Canvas/shapes/Note/useNoteEditing.ts | 43 ++ Source/Canvas/shapes/Note/useNoteExpansion.ts | 29 + Source/Canvas/shapes/Note/useNoteMove.ts | 47 ++ Source/Canvas/shapes/Note/useNoteResize.ts | 36 ++ .../Canvas/shapes/Note/useNoteTextLayout.ts | 54 ++ Source/Common/NumberInput.tsx | 541 ++---------------- Source/Common/NumberInputParts.ts | 24 + Source/Common/NumberInputProps.ts | 67 +++ Source/Common/numberInputAttributes.ts | 10 + Source/Common/numberInputValue.ts | 49 ++ Source/Common/renderNumberInputAdornment.tsx | 49 ++ Source/Common/renderNumberInputControl.tsx | 83 +++ Source/Common/renderNumberInputMessage.tsx | 40 ++ Source/Common/renderNumberInputStep.tsx | 75 +++ Source/Common/useControlledNumberValue.ts | 42 ++ Source/Common/useNumberInputState.ts | 64 +++ 25 files changed, 955 insertions(+), 929 deletions(-) create mode 100644 Source/Canvas/shapes/Note/NoteData.ts create mode 100644 Source/Canvas/shapes/Note/NoteHandle.ts create mode 100644 Source/Canvas/shapes/Note/NoteProps.ts create mode 100644 Source/Canvas/shapes/Note/ResizeStart.ts create mode 100644 Source/Canvas/shapes/Note/fitText.ts create mode 100644 Source/Canvas/shapes/Note/renderHandles.tsx create mode 100644 Source/Canvas/shapes/Note/resizeBounds.ts create mode 100644 Source/Canvas/shapes/Note/textMetrics.ts create mode 100644 Source/Canvas/shapes/Note/useNoteEditing.ts create mode 100644 Source/Canvas/shapes/Note/useNoteExpansion.ts create mode 100644 Source/Canvas/shapes/Note/useNoteMove.ts create mode 100644 Source/Canvas/shapes/Note/useNoteResize.ts create mode 100644 Source/Canvas/shapes/Note/useNoteTextLayout.ts create mode 100644 Source/Common/NumberInputParts.ts create mode 100644 Source/Common/NumberInputProps.ts create mode 100644 Source/Common/numberInputAttributes.ts create mode 100644 Source/Common/numberInputValue.ts create mode 100644 Source/Common/renderNumberInputAdornment.tsx create mode 100644 Source/Common/renderNumberInputControl.tsx create mode 100644 Source/Common/renderNumberInputMessage.tsx create mode 100644 Source/Common/renderNumberInputStep.tsx create mode 100644 Source/Common/useControlledNumberValue.ts create mode 100644 Source/Common/useNumberInputState.ts diff --git a/Source/Canvas/shapes/Note/Note.tsx b/Source/Canvas/shapes/Note/Note.tsx index a94045d8..4977f909 100644 --- a/Source/Canvas/shapes/Note/Note.tsx +++ b/Source/Canvas/shapes/Note/Note.tsx @@ -2,415 +2,38 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. import type React from 'react'; -import { useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react'; -import { useOptionalMessenger } from '../../../Common/messaging/useOptionalMessenger'; -import { NoteTextChanged } from './NoteTextChanged'; -import { whenNoteFontReady } from './noteFont'; +import { useCallback, useRef } from 'react'; import { FaPlus } from 'react-icons/fa6'; - -const MIN_SIZE = 80; -// How small the fitted text is allowed to get. Notes live on a canvas that zooms, so text too small to -// read at 1:1 is still perfectly legible one zoom step in — shrinking is a far better answer than -// hiding the text behind an affordance, and the floor is set low enough to say so. Only text that will -// not fit even at this size falls back to the expand affordance. -const MIN_FONT_SIZE = 4; -const MAX_FONT_SIZE = 120; -const PADDING = 12; -const LINE_HEIGHT_RATIO = 1.4; - -/** Controlled data rendered by {@link Note}. */ -export interface NoteData { - /** Stable note identity. */ - id: string; - /** World-space horizontal position. */ - x: number; - /** World-space vertical position. */ - y: number; - /** Note width. */ - width: number; - /** Note height. */ - height: number; - /** Editable note text. */ - text: string; -} - -interface FontFit { - fontSize: number; - /** True when the text still does not fit at MIN_FONT_SIZE — the note needs the expand affordance. */ - overflows: boolean; -} - -function textFitsAtSize( - measurer: HTMLDivElement, - text: string, - fontSize: number, - availableWidth: number, - availableHeight: number, -): boolean { - measurer.style.width = `${availableWidth}px`; - measurer.style.fontSize = `${fontSize}px`; - measurer.style.lineHeight = `${LINE_HEIGHT_RATIO}`; - measurer.textContent = text; - return measurer.scrollHeight <= availableHeight; -} - -function findOptimalFontSize( - measurer: HTMLDivElement, - text: string, - width: number, - height: number, -): FontFit { - if (!(text ?? '').trim()) - return { - fontSize: Math.min(MAX_FONT_SIZE, Math.min(width, height) * 0.4), - overflows: false, - }; - - const availableWidth = width - PADDING * 2; - const availableHeight = height - PADDING * 2; - - let low = MIN_FONT_SIZE; - let high = MAX_FONT_SIZE; - - // Quick check: if the readability floor doesn't fit, stop shrinking and flag the overflow instead. - if (!textFitsAtSize(measurer, text, low, availableWidth, availableHeight)) { - return { fontSize: MIN_FONT_SIZE, overflows: true }; - } - - // Binary search for the largest fitting font size - while (high - low > 0.5) { - const mid = (low + high) / 2; - if (textFitsAtSize(measurer, text, mid, availableWidth, availableHeight)) { - low = mid; - } else { - high = mid; - } - } - - return { fontSize: Math.floor(low), overflows: false }; -} - -const HANDLE_KEYS = ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w'] as const; -type HandleKey = (typeof HANDLE_KEYS)[number]; - -const HANDLE_POSITIONS: Record = { - nw: { top: -4, left: -4 }, - n: { top: -4, left: '50%', transform: 'translateX(-50%)' }, - ne: { top: -4, right: -4 }, - e: { top: '50%', right: -4, transform: 'translateY(-50%)' }, - se: { bottom: -4, right: -4 }, - s: { bottom: -4, left: '50%', transform: 'translateX(-50%)' }, - sw: { bottom: -4, left: -4 }, - w: { top: '50%', left: -4, transform: 'translateY(-50%)' }, -}; - -const RESIZE_CURSORS: Record = { - nw: 'nw-resize', - n: 'n-resize', - ne: 'ne-resize', - e: 'e-resize', - se: 'se-resize', - s: 's-resize', - sw: 'sw-resize', - w: 'w-resize', -}; - -/** Props for a fully controlled movable, resizable, editable Canvas note. */ -export interface NoteProps { - /** Current note data. */ - note: NoteData; - /** Whether selection handles are visible. */ - selected: boolean; - - /** - * Selects this note. `additive` reports that the gesture carried a shift/meta/ctrl modifier, so a - * board supporting multi-select can extend its selection instead of replacing it. - */ - onSelect: (id: string, additive: boolean) => void; - - /** Reports drag movement. */ - onMove: (id: string, x: number, y: number) => void; - /** Reports drag completion. */ - onMoveEnd?: (id: string) => void; - /** Reports resize movement and the resulting bounds. */ - onResize: (id: string, x: number, y: number, width: number, height: number) => void; - /** Reports resize completion. */ - onResizeEnd?: (id: string) => void; - /** Reports committed text edits. */ - onTextChange: (id: string, text: string) => void; - - /** - * Reports that the note grew to show all of its text, or shrank back. An expanded note reaches over - * whatever sits below it, so the host has to raise it above its siblings for the duration — a note - * renders inside its own stacking context, so it cannot do that for itself. - */ - onExpandedChange?: (id: string, isExpanded: boolean) => void; -} +import type { NoteProps } from './NoteProps'; +import { useNoteEditing } from './useNoteEditing'; +import { useNoteTextLayout } from './useNoteTextLayout'; +import { useNoteExpansion } from './useNoteExpansion'; +import { useNoteMove } from './useNoteMove'; +import { useNoteResize } from './useNoteResize'; +import { renderHandles } from './renderHandles'; +import { LINE_HEIGHT_RATIO } from './textMetrics'; + +export type { NoteData } from './NoteData'; +export type { NoteProps } from './NoteProps'; /** * A fully controlled movable, resizable, editable Canvas note with automatic font fitting. Text * shrinks to fit the note's bounds; when it no longer fits even at the readability floor, a "see full * text" button grows the note temporarily. Double-click to edit, drag to move, drag handles to resize. */ -export const Note: React.FC = ({ - note, - selected, - onSelect, - onMove, - onMoveEnd, - onResize, - onResizeEnd, - onTextChange, - onExpandedChange, -}) => { - // Opt-in messaging: resolves to undefined without an Arc messenger, and the publish below then - // simply does not happen — the `onTextChange` callback remains the note's contract either way. - const publish = useOptionalMessenger(); +export const Note: React.FC = (props) => { + const { note, selected } = props; + const editing = useNoteEditing(props); const noteRef = useRef(null); - const measurerRef = useRef(null); - const textareaRef = useRef(null); - const [isEditing, setIsEditing] = useState(false); - const [liveText, setLiveText] = useState(note.text); - const [fontSize, setFontSize] = useState(MAX_FONT_SIZE); - const [textareaTopPadding, setTextareaTopPadding] = useState(PADDING); - // True once the text no longer fits even at the readability floor — shows the "see full text" button. - const [isOverflowing, setIsOverflowing] = useState(false); - // The height the note needs to show every line of its text at the fitted size. - const [fullTextHeight, setFullTextHeight] = useState(0); - const [isShowingFullText, setIsShowingFullText] = useState(false); - // The note face is a webfont, so the first measurement can land against the fallback's metrics. - // Flipping this re-runs the fit once the real face is in. - const [isFontReady, setIsFontReady] = useState(false); - - useEffect(() => { - let cancelled = false; - void whenNoteFontReady().then(() => { - if (!cancelled) setIsFontReady(true); - }); - return () => { - cancelled = true; - }; - }, []); - - const dragRef = useRef<{ - clientX: number; - clientY: number; - startX: number; - startY: number; - zoom: number; - } | null>(null); - - const resizeRef = useRef<{ - handle: HandleKey; - clientX: number; - clientY: number; - startX: number; - startY: number; - startWidth: number; - startHeight: number; - zoom: number; - } | null>(null); - + const { measurerRef, fontSize, textareaTopPadding, isOverflowing, fullTextHeight } = useNoteTextLayout(note, editing.displayText); + const { isExpanded, handleExpand, handlePointerLeave } = useNoteExpansion(props, isOverflowing, editing.isEditing); const readEffectiveZoom = useCallback((): number => { if (!noteRef.current) return 1; const renderedWidth = noteRef.current.getBoundingClientRect().width; return renderedWidth > 0 ? renderedWidth / note.width : 1; }, [note.width]); - - // ── Move ──────────────────────────────────────────────────────────────── - - const handlePointerDown = useCallback( - (event: React.PointerEvent) => { - if (isEditing) return; - event.stopPropagation(); - onSelect(note.id, event.shiftKey || event.metaKey || event.ctrlKey); - dragRef.current = { - clientX: event.clientX, - clientY: event.clientY, - startX: note.x, - startY: note.y, - zoom: readEffectiveZoom(), - }; - event.currentTarget.setPointerCapture(event.pointerId); - }, - [isEditing, note.id, note.x, note.y, onSelect, readEffectiveZoom], - ); - - const handlePointerMove = useCallback( - (event: React.PointerEvent) => { - if (!dragRef.current || !event.buttons) return; - const { clientX, clientY, startX, startY, zoom } = dragRef.current; - const deltaX = (event.clientX - clientX) / zoom; - const deltaY = (event.clientY - clientY) / zoom; - onMove(note.id, startX + deltaX, startY + deltaY); - }, - [note.id, onMove], - ); - - const handlePointerUp = useCallback(() => { - if (dragRef.current) { - dragRef.current = null; - onMoveEnd?.(note.id); - } - }, [note.id, onMoveEnd]); - - // ── Resize ────────────────────────────────────────────────────────────── - - const handleResizePointerDown = useCallback( - (handle: HandleKey) => (event: React.PointerEvent) => { - event.stopPropagation(); - resizeRef.current = { - handle, - clientX: event.clientX, - clientY: event.clientY, - startX: note.x, - startY: note.y, - startWidth: note.width, - startHeight: note.height, - zoom: readEffectiveZoom(), - }; - event.currentTarget.setPointerCapture(event.pointerId); - }, - [note.x, note.y, note.width, note.height, readEffectiveZoom], - ); - - const handleResizePointerMove = useCallback( - (event: React.PointerEvent) => { - if (!resizeRef.current || !event.buttons) return; - const { - handle, - clientX, - clientY, - startX, - startY, - startWidth, - startHeight, - zoom, - } = resizeRef.current; - const deltaX = (event.clientX - clientX) / zoom; - const deltaY = (event.clientY - clientY) / zoom; - - let newX = startX; - let newY = startY; - let newWidth = startWidth; - let newHeight = startHeight; - - if (handle === 'e' || handle === 'ne' || handle === 'se') { - newWidth = Math.max(MIN_SIZE, startWidth + deltaX); - } - if (handle === 'w' || handle === 'nw' || handle === 'sw') { - newWidth = Math.max(MIN_SIZE, startWidth - deltaX); - newX = startX + startWidth - newWidth; - } - if (handle === 's' || handle === 'se' || handle === 'sw') { - newHeight = Math.max(MIN_SIZE, startHeight + deltaY); - } - if (handle === 'n' || handle === 'ne' || handle === 'nw') { - newHeight = Math.max(MIN_SIZE, startHeight - deltaY); - newY = startY + startHeight - newHeight; - } - - onResize(note.id, newX, newY, newWidth, newHeight); - }, - [note.id, onResize], - ); - - const handleResizePointerUp = useCallback(() => { - if (resizeRef.current) { - resizeRef.current = null; - onResizeEnd?.(note.id); - } - }, [note.id, onResizeEnd]); - - // ── Text editing ──────────────────────────────────────────────────────── - - const handleDoubleClick = useCallback( - (event: React.MouseEvent) => { - event.stopPropagation(); - setLiveText(note.text); - setIsEditing(true); - }, - [note.text], - ); - - const handleTextareaChange = useCallback( - (event: React.ChangeEvent) => { - setLiveText(event.currentTarget.value); - }, - [], - ); - - const handleTextareaBlur = useCallback( - (event: React.FocusEvent) => { - const text = event.currentTarget.value; - onTextChange(note.id, text); - // Published at the same commit point as the callback — once per committed edit, never - // per keystroke — for hosts that listen on the messenger instead of (or besides) props. - publish?.(new NoteTextChanged(note.id, text)); - setIsEditing(false); - }, - [note.id, onTextChange, publish], - ); - - const handleTextareaKeyDown = useCallback( - (event: React.KeyboardEvent) => { - if (event.key === 'Escape') { - setIsEditing(false); - } - }, - [], - ); - - // Use live text for font sizing when editing, otherwise use committed text - const displayText = isEditing ? liveText : note.text; - - // Measure optimal font size using an off-screen div that mirrors the note's - // word-wrap behavior. Runs synchronously before paint so there is no flash. - // Also measures actual text height so the textarea can be vertically centred. - useLayoutEffect(() => { - if (!measurerRef.current) return; - const { fontSize: optimal, overflows } = findOptimalFontSize( - measurerRef.current, - displayText, - note.width, - note.height, - ); - setFontSize(optimal); - setIsOverflowing(overflows); - - // After finding the font, read the actual rendered text height to compute - // vertical padding that centres the text inside the textarea. - const measurer = measurerRef.current; - measurer.style.width = `${note.width - PADDING * 2}px`; - measurer.style.fontSize = `${optimal}px`; - measurer.style.lineHeight = `${LINE_HEIGHT_RATIO}`; - measurer.textContent = displayText || '\u00A0'; - const renderedHeight = measurer.scrollHeight; - const topPad = Math.max(PADDING, (note.height - renderedHeight) / 2); - setTextareaTopPadding(topPad); - // The same measurement answers how tall the note has to grow to show everything. - setFullTextHeight(renderedHeight + PADDING * 2); - }, [displayText, note.width, note.height, isFontReady]); - - const isExpanded = isShowingFullText && isOverflowing && !isEditing; - - // Editing, retyping or resizing the note re-fits the text, and the note may well fit again — the - // grown state belongs to the text that no longer fits, so it never outlives it. - useEffect(() => { - if (!isOverflowing) setIsShowingFullText(false); - }, [isOverflowing]); - - useEffect(() => { - onExpandedChange?.(note.id, isExpanded); - }, [isExpanded, note.id, onExpandedChange]); - - const handleExpand = useCallback((event: React.MouseEvent) => { - event.stopPropagation(); - setIsShowingFullText(true); - }, []); - - // Growing is a look, not a mode: the note falls back to its own size the moment the pointer leaves it. - const handlePointerLeave = useCallback(() => setIsShowingFullText(false), []); + const { handlePointerDown, handlePointerMove, handlePointerUp } = useNoteMove(props, editing.isEditing, readEffectiveZoom); + const resize = useNoteResize(props, readEffectiveZoom); return (
= ({ onPointerUp={handlePointerUp} onPointerCancel={handlePointerUp} onPointerLeave={handlePointerLeave} - onDoubleClick={handleDoubleClick} + onDoubleClick={editing.handleDoubleClick} > {/* Off-screen measurement div — mirrors text styling for accurate fitting */}