From b7d7f5d510fc25dec8c0b4932348b3fc508eb5fe Mon Sep 17 00:00:00 2001 From: woksin Date: Sun, 22 Nov 2026 03:01:28 +0100 Subject: [PATCH 1/5] Add ObjectContentEditor behavior specifications --- .../given/an_editor.tsx | 53 ++++++++ .../when_displaying_values.tsx | 88 +++++++++++++ .../when_editing_dates.tsx | 67 ++++++++++ .../when_editing_field_types.tsx | 66 ++++++++++ .../when_navigating_values.tsx | 94 ++++++++++++++ .../when_validating_values.tsx | 120 ++++++++++++++++++ 6 files changed, 488 insertions(+) create mode 100644 Source/ObjectContentEditor/for_ObjectContentEditor/given/an_editor.tsx create mode 100644 Source/ObjectContentEditor/for_ObjectContentEditor/when_displaying_values.tsx create mode 100644 Source/ObjectContentEditor/for_ObjectContentEditor/when_editing_dates.tsx create mode 100644 Source/ObjectContentEditor/for_ObjectContentEditor/when_editing_field_types.tsx create mode 100644 Source/ObjectContentEditor/for_ObjectContentEditor/when_navigating_values.tsx create mode 100644 Source/ObjectContentEditor/for_ObjectContentEditor/when_validating_values.tsx diff --git a/Source/ObjectContentEditor/for_ObjectContentEditor/given/an_editor.tsx b/Source/ObjectContentEditor/for_ObjectContentEditor/given/an_editor.tsx new file mode 100644 index 00000000..250a141f --- /dev/null +++ b/Source/ObjectContentEditor/for_ObjectContentEditor/given/an_editor.tsx @@ -0,0 +1,53 @@ +// 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 { createRoot, type Root } from 'react-dom/client'; +import { ObjectContentEditor, type ObjectContentEditorProps } from '../../ObjectContentEditor'; + +export class an_editor { + readonly container = document.createElement('div'); + private readonly root: Root; + + constructor() { + (globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; + document.body.append(this.container); + this.root = createRoot(this.container); + } + + async render(props: ObjectContentEditorProps) { + await act(async () => this.root.render()); + } + + async dispose() { + await act(async () => this.root.unmount()); + this.container.remove(); + } + + find(selector: string): T { + const element = this.container.querySelector(selector); + if (!element) throw new Error(`Nothing matched '${selector}'.`); + return element; + } + + async click(selector: string) { + await act(async () => this.find(selector).click()); + } + + async setValue(propertyName: string, value: string) { + const element = this.find(`[aria-label="${propertyName}"]`); + const prototype = element instanceof HTMLTextAreaElement + ? HTMLTextAreaElement.prototype + : HTMLInputElement.prototype; + const setter = Object.getOwnPropertyDescriptor(prototype, 'value')!.set!; + await act(async () => { + setter.call(element, value); + element.dispatchEvent(new Event('input', { bubbles: true })); + }); + } + + labels() { + return Array.from(this.container.querySelectorAll('tbody tr td:first-child')) + .map((cell) => cell.textContent); + } +} diff --git a/Source/ObjectContentEditor/for_ObjectContentEditor/when_displaying_values.tsx b/Source/ObjectContentEditor/for_ObjectContentEditor/when_displaying_values.tsx new file mode 100644 index 00000000..42c28b38 --- /dev/null +++ b/Source/ObjectContentEditor/for_ObjectContentEditor/when_displaying_values.tsx @@ -0,0 +1,88 @@ +// 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 { afterEach, beforeEach, describe, it, vi } from 'vitest'; +import { an_editor } from './given/an_editor'; + +const schema = { + properties: { + name: { type: 'string', description: 'An example description' }, + count: { type: 'number' }, + enabled: { type: 'boolean' }, + missing: { type: 'string' }, + empty: { type: 'null' }, + untyped: {}, + }, +}; + +describe('when displaying ObjectContentEditor values in read-only mode', () => { + let editor: an_editor; + const onChange = vi.fn(); + const onValidationChange = vi.fn(); + const timestamp = new Date('2026-01-02T03:04:05Z'); + + beforeEach(async () => { + editor = new an_editor(); + onChange.mockClear(); + onValidationChange.mockClear(); + await editor.render({ + object: { name: 'Sample User', count: 0, enabled: false, empty: null, untyped: 'Text', extra: 'Hidden' }, + schema, + timestamp, + className: 'example-editor', + onChange, + onValidationChange, + }); + }); + + afterEach(async () => editor.dispose()); + + it('should display only schema properties in schema order', () => { + editor.labels().should.deep.equal(['name', 'count', 'enabled', 'missing', 'empty', 'untyped']); + }); + + it('should stringify primitives and leave missing and null values blank', () => { + const values = Array.from(editor.container.querySelectorAll('tbody tr td:last-child')) + .map((cell) => cell.textContent); + values.should.deep.equal(['Sample User', '0', 'false', '', '', 'Text']); + }); + + it('should retain the root styling and component marker', () => { + editor.find('[data-cratis-component="ObjectContentEditor"]').className + .should.equal('order-content example-editor'); + }); + + it('should display the property description affordance', () => { + editor.find('button[aria-label="Property description"] .property-info-icon') + .getAttribute('aria-hidden')!.should.equal('true'); + }); + + it('should display the localized snapshot timestamp', () => { + editor.container.textContent!.should.contain(`Snapshot captured: ${timestamp.toLocaleString()}`); + }); + + it('should not render editable controls or notify changes or validation', () => { + editor.container.querySelectorAll('input, textarea').length.should.equal(0); + onChange.mock.calls.should.have.lengthOf(0); + onValidationChange.mock.calls.should.have.lengthOf(0); + }); +}); + +describe('when displaying an empty ObjectContentEditor root', () => { + let editor: an_editor; + + beforeEach(() => { editor = new an_editor(); }); + afterEach(async () => editor.dispose()); + + it('should omit the table for a null root', async () => { + await editor.render({ object: null, schema: {} }); + editor.container.querySelectorAll('table').length.should.equal(0); + }); + + it('should render an empty table without schema properties', async () => { + await editor.render({ object: { name: 'Sample User' }, schema: {} }); + editor.find('table').querySelectorAll('tr').length.should.equal(0); + }); +}); diff --git a/Source/ObjectContentEditor/for_ObjectContentEditor/when_editing_dates.tsx b/Source/ObjectContentEditor/for_ObjectContentEditor/when_editing_dates.tsx new file mode 100644 index 00000000..02beac1b --- /dev/null +++ b/Source/ObjectContentEditor/for_ObjectContentEditor/when_editing_dates.tsx @@ -0,0 +1,67 @@ +// 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 { afterEach, beforeEach, describe, it, vi } from 'vitest'; +import { DatePickerInput } from '../../Common/DatePickerInput'; +import { an_editor } from './given/an_editor'; + +vi.mock('../../Common/DatePickerInput', () => ({ DatePickerInput: vi.fn(() => null) })); + +const schema = { + properties: { + date: { type: 'string', format: 'date' }, + instant: { type: 'string', format: 'date-time' }, + }, +}; +const object = { date: '2026-01-02', instant: '2026-01-02T03:04:05.000Z' }; +const selectedDate = new Date('2026-02-03T04:05:06.000Z'); + +const picker = (name: string) => { + const call = vi.mocked(DatePickerInput).mock.calls.find(([props]) => props['aria-label'] === name); + if (!call) throw new Error(`Date picker '${name}' was not rendered.`); + return call[0]; +}; + +describe('when editing ObjectContentEditor dates', () => { + let editor: an_editor; + const onChange = vi.fn(); + + beforeEach(async () => { + editor = new an_editor(); + onChange.mockClear(); + vi.mocked(DatePickerInput).mockClear(); + await editor.render({ object, schema, editMode: true, onChange }); + }); + afterEach(async () => editor.dispose()); + + it('should pass date values and time settings to the existing picker', () => { + picker('date').value!.getTime().should.equal(new Date(object.date).getTime()); + picker('instant').value!.getTime().should.equal(new Date(object.instant).getTime()); + (picker('date').showTime === undefined).should.equal(true); + picker('instant').showTime!.should.equal(true); + picker('date').showIcon!.should.equal(true); + }); + + it('should serialize a date without a time and default missing metadata to user', async () => { + await act(async () => picker('date').onChange(selectedDate)); + onChange.mock.calls.should.deep.equal([[{ ...object, date: '2026-02-03' }, { source: 'user' }]]); + }); + + it('should serialize a date-time as an ISO instant and preserve metadata', async () => { + const metadata = { source: 'programmatic' as const }; + await act(async () => picker('instant').onChange(selectedDate, metadata)); + onChange.mock.calls.should.deep.equal([[{ ...object, instant: selectedDate.toISOString() }, metadata]]); + onChange.mock.calls[0][1].should.equal(metadata); + }); + + it('should emit null when either picker is cleared', async () => { + await act(async () => picker('date').onChange(null)); + await act(async () => picker('instant').onChange(null)); + (onChange.mock.calls[0][0].date === null).should.equal(true); + (onChange.mock.calls[1][0].instant === null).should.equal(true); + editor.container.querySelectorAll('small').length.should.equal(2); + }); +}); diff --git a/Source/ObjectContentEditor/for_ObjectContentEditor/when_editing_field_types.tsx b/Source/ObjectContentEditor/for_ObjectContentEditor/when_editing_field_types.tsx new file mode 100644 index 00000000..c45025c6 --- /dev/null +++ b/Source/ObjectContentEditor/for_ObjectContentEditor/when_editing_field_types.tsx @@ -0,0 +1,66 @@ +// 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 { afterEach, beforeEach, describe, it, vi } from 'vitest'; +import { an_editor } from './given/an_editor'; + +const object = { + text: 'Short', long: 'a'.repeat(51), boundary: 'b'.repeat(50), quantity: 3, + enabled: true, nested: { text: 'Nested' }, list: ['Item'], untyped: 'Read only', +}; +const schema = { + properties: { + text: { type: 'string' }, long: { type: 'string' }, boundary: { type: 'string' }, + quantity: { type: 'number' }, enabled: { type: 'boolean' }, nested: { type: 'object' }, + list: { type: 'array' }, untyped: {}, + }, +}; + +describe('when editing ObjectContentEditor field types', () => { + let editor: an_editor; + const onChange = vi.fn(); + + beforeEach(async () => { + editor = new an_editor(); + onChange.mockClear(); + await editor.render({ object, schema, editMode: true, onChange }); + }); + afterEach(async () => editor.dispose()); + + it('should choose the existing input types and long-text boundary', () => { + editor.find('input[aria-label="text"]').getAttribute('value')!.should.equal('Short'); + editor.find('textarea[aria-label="long"]').rows.should.equal(3); + editor.find('input[aria-label="boundary"]').getAttribute('value')!.should.equal(object.boundary); + editor.find('input[aria-label="quantity"]').getAttribute('type')!.should.equal('number'); + editor.find('input[aria-label="enabled"]').checked.should.equal(true); + }); + + it('should keep complex fields unsupported and untyped schema fields read-only', () => { + editor.container.textContent!.should.contain('Array editing not yet supported'); + editor.container.textContent!.should.contain('Object editing not yet supported'); + editor.container.textContent!.should.contain('Read only'); + editor.container.querySelectorAll('[aria-label="untyped"]').length.should.equal(0); + }); + + it('should emit long-text changes with native user metadata', async () => { + await editor.setValue('long', 'Updated'); + onChange.mock.calls[0][0].should.deep.equal({ ...object, long: 'Updated' }); + onChange.mock.calls[0][1].source.should.equal('user'); + (onChange.mock.calls[0][1].nativeEvent instanceof Event).should.equal(true); + }); + + it('should keep controlled fields unchanged until the parent supplies the new object', async () => { + await editor.setValue('text', 'Updated'); + editor.find('[aria-label="text"]').value.should.equal('Short'); + await editor.render({ object: { ...object, text: 'Updated' }, schema, editMode: true, onChange }); + editor.find('[aria-label="text"]').value.should.equal('Updated'); + }); + + it('should only toggle the requested property in a replacement object', async () => { + await editor.click('[aria-label="enabled"]'); + onChange.mock.calls[0][0].should.deep.equal({ ...object, enabled: false }); + object.enabled.should.equal(true); + }); +}); diff --git a/Source/ObjectContentEditor/for_ObjectContentEditor/when_navigating_values.tsx b/Source/ObjectContentEditor/for_ObjectContentEditor/when_navigating_values.tsx new file mode 100644 index 00000000..36fc708c --- /dev/null +++ b/Source/ObjectContentEditor/for_ObjectContentEditor/when_navigating_values.tsx @@ -0,0 +1,94 @@ +// 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 { afterEach, beforeEach, describe, it } from 'vitest'; +import { an_editor } from './given/an_editor'; + +const object = { + details: { name: 'Example Project', nested: { count: 2 } }, + values: ['Sample', 0, false, null, ['Nested']], + records: [{ name: 'First', details: {} }, { name: 'Second', details: {}, extra: 'Hidden' }], + empty: [], +}; +const schema = { + properties: { + details: { type: 'object' }, + values: { type: 'array' }, + records: { type: 'array' }, + empty: { type: 'array' }, + }, +}; + +describe('when navigating ObjectContentEditor values', () => { + let editor: an_editor; + + beforeEach(async () => { + editor = new an_editor(); + await editor.render({ object, schema }); + }); + afterEach(async () => editor.dispose()); + + it('should show data properties rather than root schema properties in a nested object', async () => { + await editor.click('[aria-label="Open details"]'); + editor.labels().should.deep.equal(['name', 'nested']); + await editor.click('[aria-label="Open nested"]'); + editor.labels().should.deep.equal(['count']); + await editor.click('[aria-label="Navigate back"]'); + editor.labels().should.deep.equal(['name', 'nested']); + }); + + it('should return to the root using its breadcrumb', async () => { + await editor.click('[aria-label="Open details"]'); + const rootBreadcrumb = Array.from(editor.container.querySelectorAll('button')) + .find((button) => button.textContent === 'Root'); + if (!rootBreadcrumb) throw new Error('Root breadcrumb was not rendered.'); + await act(async () => rootBreadcrumb.click()); + editor.labels().should.deep.equal(['details', 'values', 'records', 'empty']); + }); + + it('should display primitive array items by index and allow nested array navigation', async () => { + await editor.click('[aria-label="Open values, 5 items"]'); + editor.labels().should.deep.equal(['[0]', '[1]', '[2]', '[3]', '[4]']); + const values = Array.from(editor.container.querySelectorAll('tbody tr td:last-child')) + .map((cell) => cell.textContent); + values.should.deep.equal(['Sample', '0', 'false', '', 'Array[1]']); + await editor.click('[aria-label="Open [4], 1 items"]'); + editor.find('tbody').textContent!.should.equal('[0]Nested'); + }); + + it('should display object arrays using the first item keys with separators', async () => { + await editor.click('[aria-label="Open records, 2 items"]'); + editor.labels().should.deep.equal(['name', 'details', '', 'name', 'details']); + editor.find('td[colspan="2"]').parentElement!.style.height.should.equal('8px'); + editor.container.textContent!.should.not.contain('Hidden'); + }); + + it('should display the empty array message without a table', async () => { + await editor.click('[aria-label="Open empty, 0 items"]'); + editor.container.textContent!.should.contain('Empty array'); + editor.container.querySelectorAll('table').length.should.equal(0); + }); + + it('should reset navigation if the current value is replaced by a primitive', async () => { + await editor.click('[aria-label="Open details"]'); + await editor.render({ object: { ...object, details: 'Replaced' }, schema }); + editor.labels().should.deep.equal(['details', 'values', 'records', 'empty']); + editor.find('[aria-label="Navigate back"]').disabled.should.equal(true); + }); + + it('should retain navigation when the current object is replaced by another object', async () => { + await editor.click('[aria-label="Open details"]'); + await editor.render({ object: { ...object, details: { replacement: true } }, schema }); + editor.labels().should.deep.equal(['replacement']); + }); + + it('should keep a nested object read-only after switching into edit mode', async () => { + await editor.click('[aria-label="Open details"]'); + await editor.render({ object, schema, editMode: true }); + editor.container.querySelectorAll('input, textarea').length.should.equal(0); + editor.labels().should.deep.equal(['name', 'nested']); + }); +}); diff --git a/Source/ObjectContentEditor/for_ObjectContentEditor/when_validating_values.tsx b/Source/ObjectContentEditor/for_ObjectContentEditor/when_validating_values.tsx new file mode 100644 index 00000000..cb5755a6 --- /dev/null +++ b/Source/ObjectContentEditor/for_ObjectContentEditor/when_validating_values.tsx @@ -0,0 +1,120 @@ +// 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 { afterEach, beforeEach, describe, it, vi } from 'vitest'; +import { an_editor } from './given/an_editor'; + +const schema = { + properties: { + name: { type: 'string' }, + email: { type: 'string', format: 'email' }, + website: { type: 'string', format: 'uri' }, + quantity: { type: 'integer' }, + enabled: { type: 'boolean' }, + absent: { type: 'string' }, + }, +}; +const object = { name: '', email: 'invalid', website: 'ftp://example.invalid', quantity: 0, enabled: false }; + +describe('when validating ObjectContentEditor values', () => { + let editor: an_editor; + const onValidationChange = vi.fn(); + const onChange = vi.fn(); + + beforeEach(async () => { + editor = new an_editor(); + onChange.mockClear(); + onValidationChange.mockClear(); + await editor.render({ object, schema, editMode: true, onChange, onValidationChange }); + }); + afterEach(async () => editor.dispose()); + + it('should require every editable field even without a required schema annotation', () => { + editor.find('[aria-label="name"]').getAttribute('aria-invalid')!.should.equal('true'); + editor.find('[aria-label="absent"]').parentElement!.textContent!.should.equal('This field is required'); + }); + + it('should report initial validation after the initial no-error notification', () => { + onValidationChange.mock.calls.should.deep.equal([[false], [true]]); + }); + + it('should retain email and URI validation messages', () => { + editor.find('[aria-label="email"]').parentElement!.textContent!.should.equal('Invalid email format'); + editor.find('[aria-label="website"]').parentElement!.textContent!.should.equal('Invalid URI format'); + }); + + it('should accept zero and false without marking them invalid', () => { + editor.find('[aria-label="quantity"]').hasAttribute('aria-invalid').should.equal(false); + editor.find('[aria-label="enabled"]').hasAttribute('aria-invalid').should.equal(false); + }); + + it('should clear field errors as their values become valid', async () => { + await editor.setValue('name', 'Sample User'); + await editor.setValue('absent', 'Added'); + await editor.setValue('email', 'sample@example.invalid'); + await editor.setValue('website', 'https://example.invalid'); + onValidationChange.mock.lastCall!.should.deep.equal([false]); + editor.container.querySelectorAll('small').length.should.equal(0); + }); + + it('should emit the updated object before updating validation errors', async () => { + const invalidAtChange: boolean[] = []; + await editor.render({ object, schema, editMode: true, onChange: () => { + invalidAtChange.push(editor.find('[aria-label="email"]').hasAttribute('aria-invalid')); + } }); + await editor.setValue('email', 'sample@example.invalid'); + invalidAtChange.should.deep.equal([true]); + editor.find('[aria-label="email"]').hasAttribute('aria-invalid').should.equal(false); + }); + + it('should add a missing property without mutating or removing existing properties', async () => { + await editor.setValue('absent', 'Added'); + onChange.mock.calls[0][0].should.deep.equal({ ...object, absent: 'Added' }); + Object.keys(object).should.not.contain('absent'); + }); + + it('should emit null and a required error when clearing a number', async () => { + await editor.setValue('quantity', ''); + (onChange.mock.calls[0][0].quantity === null).should.equal(true); + editor.find('[aria-label="quantity"]').parentElement!.textContent!.should.equal('This field is required'); + }); + + it('should still update local validation without an onChange handler', async () => { + await editor.render({ object, schema, editMode: true }); + await editor.setValue('email', 'sample@example.invalid'); + editor.find('[aria-label="email"]').hasAttribute('aria-invalid').should.equal(false); + onChange.mock.calls.should.have.lengthOf(0); + }); + + it('should revalidate when the controlled object changes', async () => { + await editor.render({ + object: { name: 'Sample User', email: 'sample@example.invalid', website: 'http://example.invalid', quantity: 1, enabled: true, absent: 'Present' }, + schema, + editMode: true, + onValidationChange, + }); + onValidationChange.mock.lastCall!.should.deep.equal([false]); + }); +}); + +describe('when validating a nonnumeric ObjectContentEditor value', () => { + let editor: an_editor; + let consoleError: ReturnType; + + beforeEach(async () => { + editor = new an_editor(); + consoleError = vi.spyOn(console, 'error').mockImplementation(() => undefined); + await editor.render({ object: { quantity: 'invalid' }, schema: { properties: { quantity: { type: 'number' } } }, editMode: true }); + }); + afterEach(async () => { + await editor.dispose(); + consoleError.mockRestore(); + }); + + it('should retain the numeric validation message', () => { + editor.find('[aria-label="quantity"]').parentElement!.textContent!.should.equal('Must be a valid number'); + }); + +}); From a35e977c9e40029b3a0cfcfe5cbf47ce9b5bab48 Mon Sep 17 00:00:00 2001 From: woksin Date: Sun, 22 Nov 2026 03:14:14 +0100 Subject: [PATCH 2/5] Extract ObjectContentEditor validation and rendering helpers --- .../ObjectContentEditor.tsx | 616 +----------------- Source/ObjectContentEditor/arrayTable.tsx | 70 ++ Source/ObjectContentEditor/editField.tsx | 145 +++++ Source/ObjectContentEditor/styles.ts | 41 ++ Source/ObjectContentEditor/table.tsx | 93 +++ Source/ObjectContentEditor/useNavigation.ts | 57 ++ Source/ObjectContentEditor/useValidation.ts | 50 ++ Source/ObjectContentEditor/validation.ts | 53 ++ Source/ObjectContentEditor/value.tsx | 40 ++ 9 files changed, 585 insertions(+), 580 deletions(-) create mode 100644 Source/ObjectContentEditor/arrayTable.tsx create mode 100644 Source/ObjectContentEditor/editField.tsx create mode 100644 Source/ObjectContentEditor/styles.ts create mode 100644 Source/ObjectContentEditor/table.tsx create mode 100644 Source/ObjectContentEditor/useNavigation.ts create mode 100644 Source/ObjectContentEditor/useValidation.ts create mode 100644 Source/ObjectContentEditor/validation.ts create mode 100644 Source/ObjectContentEditor/value.tsx diff --git a/Source/ObjectContentEditor/ObjectContentEditor.tsx b/Source/ObjectContentEditor/ObjectContentEditor.tsx index 78cb25de..0f6016ec 100644 --- a/Source/ObjectContentEditor/ObjectContentEditor.tsx +++ b/Source/ObjectContentEditor/ObjectContentEditor.tsx @@ -1,16 +1,15 @@ // Copyright (c) Cratis. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -import { Tooltip } from '../Common/Tooltip'; -import React, { useState, useCallback, useMemo, useEffect } from 'react'; -import * as faIcons from 'react-icons/fa6'; +import { useState, useCallback } from 'react'; import { ObjectNavigationalBar } from '../ObjectNavigationalBar'; import type { ChangeHandler } from '../types/ChangeHandler'; import type { ChangeMeta } from '../types/ChangeMeta'; import type { Json, JsonSchema, JsonSchemaProperty } from '../types/JsonSchema'; -import { getValueAtPath } from './objectHelpers'; - -import { DatePickerInput } from '../Common/DatePickerInput'; +import { renderEditField } from './editField'; +import { renderTable } from './table'; +import { useNavigation } from './useNavigation'; +import { useValidation } from './useValidation'; /** * Props for {@link ObjectContentEditor}. @@ -79,168 +78,12 @@ export const ObjectContentEditor = ({ className, }: ObjectContentEditorProps) => { const [navigationPath, setNavigationPath] = useState([]); - const [validationErrors, setValidationErrors] = useState>({}); - - const validateValue = useCallback( - ( - propertyName: string, - value: Json, - property: JsonSchemaProperty, - ): string | undefined => { - if (editMode) { - if (value === null || value === undefined || value === '') { - return 'This field is required'; - } - } else { - const isRequired = schema.required?.includes(propertyName); - if ( - isRequired && - (value === null || value === undefined || value === '') - ) { - return 'This field is required'; - } - } - - if (property.type === 'string' && typeof value === 'string') { - if ( - property.format === 'email' && - value && - !value.match(/^[^\s@]+@[^\s@]+\.[^\s@]+$/) - ) { - return 'Invalid email format'; - } - if ( - property.format === 'uri' && - value && - !value.match(/^https?:\/\/.+/) - ) { - return 'Invalid URI format'; - } - } - - if (property.type === 'number' || property.type === 'integer') { - if ( - value !== null && - value !== undefined && - value !== '' && - isNaN(Number(value)) - ) { - return 'Must be a valid number'; - } - } - - return undefined; - }, - [schema, editMode], - ); - - useEffect(() => { - if (!editMode || navigationPath.length > 0) return; - - const errors: Record = {}; - const properties = schema.properties || {}; - - Object.entries(properties).forEach(([propertyName, property]) => { - const value = (object as Record)[propertyName]; - const error = validateValue( - propertyName, - value, - property as JsonSchemaProperty, - ); - if (error) { - errors[propertyName] = error; - } - }); - - setValidationErrors(errors); - }, [object, schema, editMode, navigationPath, validateValue]); - - useEffect(() => { - if (editMode && onValidationChange) { - const hasErrors = Object.keys(validationErrors).length > 0; - onValidationChange(hasErrors); - } - }, [validationErrors, editMode, onValidationChange]); - - const navigateTo = useCallback( - (segments: string[]) => { - setNavigationPath([...navigationPath, ...segments]); - }, - [navigationPath], - ); - - const navigateToBreadcrumb = useCallback( - (index: number) => { - if (index === 0) { - setNavigationPath([]); - } else { - setNavigationPath(navigationPath.slice(0, index)); - } - }, - [navigationPath], - ); - - const currentData = useMemo(() => { - if (navigationPath.length === 0) { - return object; - } - - const value = getValueAtPath(object, navigationPath); - return value !== null && typeof value === 'object' ? value : null; - }, [object, navigationPath]); - - useEffect(() => { - if (navigationPath.length > 0 && currentData === null) { - setNavigationPath([]); - } - }, [currentData, navigationPath]); - - const currentProperties = useMemo(() => { - const properties = schema.properties || {}; - - if (navigationPath.length === 0) { - return properties; - } - - return {}; - }, [schema, navigationPath]); - - const tableStyle: React.CSSProperties = { - width: '100%', - borderCollapse: 'collapse', - fontFamily: '-apple-system, BlinkMacSystemFont, "SF Mono", monospace', - fontSize: '13px', - }; - - const rowStyle: React.CSSProperties = { - borderBottom: '1px solid var(--cratis-surface-border)', - }; - - const labelStyle: React.CSSProperties = { - padding: '8px 12px', - color: 'var(--cratis-text-color-secondary)', - textAlign: 'left', - fontWeight: 500, - width: '140px', - whiteSpace: 'nowrap', - }; - - const valueStyle: React.CSSProperties = { - padding: '8px 12px', - color: 'var(--cratis-text-color)', - textAlign: 'left', - }; - - const infoIconStyle: React.CSSProperties = { - fontSize: '0.875rem', - color: 'var(--cratis-text-color-secondary)', - flexShrink: 0, - }; - - const fieldErrorStyle: React.CSSProperties = { - color: 'var(--cratis-red-500)', - fontSize: '0.75rem', - }; + const { validationErrors, validateChange } = useValidation({ + object, schema, editMode, navigationPath, onValidationChange, + }); + const { navigateTo, navigateToBreadcrumb, currentData, currentProperties } = useNavigation({ + object, schema, navigationPath, setNavigationPath, + }); const updateValue = useCallback( (propertyName: string, newValue: Json, meta: ChangeMeta) => { @@ -253,431 +96,44 @@ export const ObjectContentEditor = ({ [object, onChange], ); - const renderEditField = ( + const renderEditableValue = ( propertyName: string, property: JsonSchemaProperty, value: Json, - ) => { - const error = validationErrors[propertyName]; - - const handleChange = (newValue: Json, meta: ChangeMeta) => { + ) => renderEditField({ + propertyName, + property, + value, + error: validationErrors[propertyName], + handleChange: (newValue, meta) => { updateValue(propertyName, newValue, meta); - const validationError = validateValue(propertyName, newValue, property); - setValidationErrors((prev) => { - const newErrors = { ...prev }; - if (validationError) { - newErrors[propertyName] = validationError; - } else { - delete newErrors[propertyName]; - } - return newErrors; - }); - }; - - if (property.type === 'boolean') { - return ( -
- - handleChange(event.target.checked, { - source: 'user', - nativeEvent: event.nativeEvent, - }) - } - aria-invalid={Boolean(error) || undefined} - className='cratis:size-5 cratis:accent-[var(--cratis-primary-color)]' - /> - {error && {error}} -
- ); - } - - if (property.type === 'number' || property.type === 'integer') { - return ( -
- - handleChange( - event.target.value === '' - ? null - : event.target.valueAsNumber, - { - source: 'user', - nativeEvent: event.nativeEvent, - }, - ) - } - aria-invalid={Boolean(error) || undefined} - className='cratis-field-input cratis:w-full' - /> - {error && {error}} -
- ); - } - - if (property.type === 'string' && property.format === 'date-time') { - const dateValue = value ? new Date(value as string) : null; - return ( -
- - handleChange( - date ? date.toISOString() : null, - meta ?? { source: 'user' }, - ) - } - showTime - showIcon - invalid={!!error} - /> - {error && {error}} -
- ); - } - - if (property.type === 'string' && property.format === 'date') { - const dateValue = value ? new Date(value as string) : null; - return ( -
- - handleChange( - date ? date.toISOString().split('T')[0] : null, - meta ?? { source: 'user' }, - ) - } - showIcon - invalid={!!error} - /> - {error && {error}} -
- ); - } - - if (property.type === 'array') { - return ( -
- Array editing not yet supported -
- ); - } - - if (property.type === 'object') { - return ( -
- Object editing not yet supported -
- ); - } - - const isLongText = (value as string)?.length > 50; - - if (isLongText) { - return ( -
-