From 2f41623889feb217021eeaa629a4e0b5630d552f Mon Sep 17 00:00:00 2001 From: woksin Date: Sat, 21 Nov 2026 15:01:01 +0100 Subject: [PATCH 1/4] Raise Code Health of runConformance.tsx --- .../when_collecting_native_form_evidence.ts | 49 ++ Conformance/src/runConformance.tsx | 757 ++++++++++-------- 2 files changed, 471 insertions(+), 335 deletions(-) create mode 100644 Conformance/for_conformance/when_collecting_native_form_evidence.ts diff --git a/Conformance/for_conformance/when_collecting_native_form_evidence.ts b/Conformance/for_conformance/when_collecting_native_form_evidence.ts new file mode 100644 index 00000000..94e1c450 --- /dev/null +++ b/Conformance/for_conformance/when_collecting_native_form_evidence.ts @@ -0,0 +1,49 @@ +// Copyright (c) Cratis. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +import 'chai/register-should.js'; +import { unstable_cratisBuiltIn } from '@cratis/components/renderer/builtin'; +import { beforeAll, describe, it } from 'vitest'; +import { runConformance, type ConformanceReport } from '../src/index.js'; + +const textCases = [ + { slotId: 'common.textInput', name: 'sample' }, + { slotId: 'common.textArea', name: 'notes' }, +] as const; + +const choiceCases = [ + { slotId: 'common.checkbox', name: 'selected', value: 'on' }, + { slotId: 'common.radio', name: 'frequency', value: 'daily' }, + { slotId: 'common.switch', name: 'enabled', value: 'on' }, +] as const; + +describe('when collecting native form evidence', () => { + let report: ConformanceReport; + beforeAll(async () => { + report = await runConformance(unstable_cratisBuiltIn, { document, axe: false }); + }); + + for (const { slotId, name } of textCases) { + it(`should capture the submitted and reset text values for ${slotId}`, () => { + const evidence = report.checks.find((check) => check.id === `behavior.${slotId}`)!.evidence!; + (evidence as object).should.include({ + name, + nativeValue: 'after', + resetValue: 'before', + resetMatches: true, + callbacks: 1, + }); + (evidence.formData as object).should.deep.equal({ + [name]: 'after', + }); + }); + } + + for (const { slotId, name, value } of choiceCases) { + it(`should capture the checked form value and unchecked reset for ${slotId}`, () => { + const evidence = report.checks.find((check) => check.id === `behavior.${slotId}`)!.evidence!; + (evidence as object).should.include({ name, nativeValue: value, resetChecked: false, resetMatches: true, callbacks: 1 }); + (evidence.formData as object).should.deep.equal({ [name]: value }); + }); + } +}); diff --git a/Conformance/src/runConformance.tsx b/Conformance/src/runConformance.tsx index 511561d8..ca694b56 100644 --- a/Conformance/src/runConformance.tsx +++ b/Conformance/src/runConformance.tsx @@ -161,16 +161,18 @@ const checkInteractions = async ( checks, ConformanceFamily.Behavior, `behavior.${profile.slotId}.${concern}`, - passed, - passed - ? interactionMessages[concern] - : `${interactionMessages[concern]} It did not respond as required.`, - profile.slotId, - { concern, passed, ...observed.detail }, + { + passed, + message: passed + ? interactionMessages[concern] + : `${interactionMessages[concern]} It did not respond as required.`, + slotId: profile.slotId, + evidence: { concern, passed, ...observed.detail }, + }, ); } } catch (error) { - addError(checks, ConformanceFamily.Behavior, `behavior.${profile.slotId}.interaction`, error, profile.slotId); + addError(checks, ConformanceFamily.Behavior, `behavior.${profile.slotId}.interaction`, { error, slotId: profile.slotId }); } finally { if (fixture) await unmount(fixture); } @@ -179,13 +181,17 @@ const checkInteractions = async ( const markerForPart = (part: string) => part.replace(/[A-Z]/gu, (letter) => `-${letter.toLowerCase()}`); +const collectElementStates = (element: HTMLElement, observed: Set) => { + const part = element.getAttribute('data-cratis-part'); + if (!part) return; + for (const state of cratisCanonicalPartStates) { + if (element.hasAttribute(`data-${state}`)) observed.add(`${part}.${state}`); + } +}; + const collectRenderedStates = (root: ParentNode, observed: Set) => { for (const element of root.querySelectorAll('[data-cratis-part]')) { - const part = element.getAttribute('data-cratis-part'); - if (!part) continue; - for (const state of cratisCanonicalPartStates) { - if (element.hasAttribute(`data-${state}`)) observed.add(`${part}.${state}`); - } + collectElementStates(element, observed); } }; @@ -222,14 +228,18 @@ const variantPassThrough = (profile: SlotProfile, variantPt: unknown) => { return merged; }; +interface CheckResult { + readonly passed: boolean; + readonly message: string; + readonly slotId?: unstable_SlotId; + readonly evidence?: Readonly>; +} + const addCheck = ( checks: ConformanceCheck[], family: ConformanceFamily, id: string, - passed: boolean, - message: string, - slotId?: unstable_SlotId, - evidence?: Readonly>, + { passed, message, slotId, evidence }: CheckResult, ) => checks.push({ id, @@ -244,23 +254,21 @@ const addError = ( checks: ConformanceCheck[], family: ConformanceFamily, id: string, - error: unknown, - slotId?: unstable_SlotId, + { error, slotId }: { error: unknown; slotId?: unstable_SlotId }, ) => - addCheck( - checks, - family, - id, - false, - error instanceof Error ? error.message : String(error), + addCheck(checks, family, id, { + passed: false, + message: error instanceof Error ? error.message : String(error), slotId, - ); + }); const skipRequested = ( checks: ConformanceCheck[], - options: ConformanceOptions, - library: unstable_UiLibrary, - declaration: unstable_SlotDeclaration, + { options, library, declaration }: { + options: ConformanceOptions; + library: unstable_UiLibrary; + declaration: unstable_SlotDeclaration; + }, checkId: string, slotId: unstable_SlotId, ) => { @@ -281,9 +289,11 @@ const skipRequested = ( checks, ConformanceFamily.Manifest, `skip.${checkId}.undeclared`, - false, - `Skip '${checkId}' has no unsupported/emulated fidelity or absent declared capability.`, - slotId, + { + passed: false, + message: `Skip '${checkId}' has no unsupported/emulated fidelity or absent declared capability.`, + slotId, + }, ); return false; } @@ -298,6 +308,15 @@ const skipRequested = ( return true; }; +const isImmutableLibrary = (library: unstable_UiLibrary) => + Object.isFrozen(library) && + Object.isFrozen(library.capabilities) && + Object.isFrozen(library.profileSlots) && + Object.isFrozen(library.slots) && + Object.values(library.slots).every( + (declaration) => declaration === undefined || Object.isFrozen(declaration), + ); + const checkManifest = ( checks: ConformanceCheck[], library: unstable_UiLibrary, @@ -309,12 +328,13 @@ const checkManifest = ( checks, ConformanceFamily.Manifest, 'manifest.schema', - schemaProblems.length === 0, - schemaProblems.length === 0 - ? 'Static package metadata satisfies the public adapter-schema constraints exercised by this runner.' - : schemaProblems.join('; '), - undefined, - { problems: schemaProblems }, + { + passed: schemaProblems.length === 0, + message: schemaProblems.length === 0 + ? 'Static package metadata satisfies the public adapter-schema constraints exercised by this runner.' + : schemaProblems.join('; '), + evidence: { problems: schemaProblems }, + }, ); const consistencyProblems = compareMetadata( options.metadata, @@ -324,20 +344,23 @@ const checkManifest = ( checks, ConformanceFamily.Manifest, 'manifest.runtimeConsistency', - consistencyProblems.length === 0, - consistencyProblems.length === 0 - ? 'Static package metadata and runtime manifest agree.' - : consistencyProblems.join('; '), - undefined, - { problems: consistencyProblems }, + { + passed: consistencyProblems.length === 0, + message: consistencyProblems.length === 0 + ? 'Static package metadata and runtime manifest agree.' + : consistencyProblems.join('; '), + evidence: { problems: consistencyProblems }, + }, ); } else { addCheck( checks, ConformanceFamily.Manifest, 'manifest.schema', - false, - 'No package.json#cratis metadata was supplied; static/runtime consistency cannot be established.', + { + passed: false, + message: 'No package.json#cratis metadata was supplied; static/runtime consistency cannot be established.', + }, ); } @@ -346,33 +369,40 @@ const checkManifest = ( checks, ConformanceFamily.Manifest, 'manifest.noOverDeclaration', - overDeclarations.length === 0, - overDeclarations.length === 0 - ? 'Every declared capability has bounded evidence and a supporting slot.' - : overDeclarations.join('; '), - undefined, - { problems: overDeclarations }, + { + passed: overDeclarations.length === 0, + message: overDeclarations.length === 0 + ? 'Every declared capability has bounded evidence and a supporting slot.' + : overDeclarations.join('; '), + evidence: { problems: overDeclarations }, + }, ); - const immutable = - Object.isFrozen(library) && - Object.isFrozen(library.capabilities) && - Object.isFrozen(library.profileSlots) && - Object.isFrozen(library.slots) && - Object.values(library.slots).every( - (declaration) => declaration === undefined || Object.isFrozen(declaration), - ); + const immutable = isImmutableLibrary(library); addCheck( checks, ConformanceFamily.Manifest, 'manifest.immutable', - immutable, - immutable - ? 'The runtime manifest, capability/profile arrays, slot map, and declarations are immutable.' - : 'The runtime manifest contains a mutable public container or slot declaration.', + { + passed: immutable, + message: immutable + ? 'The runtime manifest, capability/profile arrays, slot map, and declarations are immutable.' + : 'The runtime manifest contains a mutable public container or slot declaration.', + }, ); }; +const normalizedPropsMatch = ( + normalized: ReturnType, + style: ReturnType, +) => + normalized.className === 'sample' && + normalized.htmlFor === 'field' && + normalized.strokeWidth === 2 && + normalized.fillRule === 'evenodd' && + style.color === 'red' && + (style as Readonly>)['--sample-color'] === 'blue'; + const checkNormalization = (checks: ConformanceCheck[], document: Document) => { const normalized = normalizeReactProps({ class: 'sample', @@ -406,12 +436,7 @@ const checkNormalization = (checks: ConformanceCheck[], document: Document) => { cleanup(); document.dispatchEvent(new Event('click')); const passed = - normalized.className === 'sample' && - normalized.htmlFor === 'field' && - normalized.strokeWidth === 2 && - normalized.fillRule === 'evenodd' && - style.color === 'red' && - (style as Readonly>)['--sample-color'] === 'blue' && + normalizedPropsMatch(normalized, style) && refObject.current === target && callbackRef === target && order.join(',') === 'pt' && @@ -420,12 +445,13 @@ const checkNormalization = (checks: ConformanceCheck[], document: Document) => { checks, ConformanceFamily.ReactNormalization, 'reactNormalization.publicBoundary', - passed, - passed - ? 'React className/htmlFor/style/CSS-variable/SVG casing, ref merge, handler order, preventDefault, and idempotent listener cleanup are normalized.' - : 'React boundary normalization fixture failed.', - undefined, - { normalized, order, listenerCalls }, + { + passed, + message: passed + ? 'React className/htmlFor/style/CSS-variable/SVG casing, ref merge, handler order, preventDefault, and idempotent listener cleanup are normalized.' + : 'React boundary normalization fixture failed.', + evidence: { normalized, order, listenerCalls }, + }, ); }; @@ -450,12 +476,14 @@ const checkPartCoverage = ( checks, ConformanceFamily.Contract, `${contractId}.parts`, - missingParts.length === 0, - missingParts.length === 0 - ? 'Every documented stable DOM part was observed.' - : `Missing parts: ${missingParts.join(', ')}.`, - profile.slotId, - { expectedParts, foundParts: [...foundParts].sort() }, + { + passed: missingParts.length === 0, + message: missingParts.length === 0 + ? 'Every documented stable DOM part was observed.' + : `Missing parts: ${missingParts.join(', ')}.`, + slotId: profile.slotId, + evidence: { expectedParts, foundParts: [...foundParts].sort() }, + }, ); const missingPassThrough = profile.ptKeys @@ -470,51 +498,246 @@ const checkPartCoverage = ( checks, ConformanceFamily.Contract, `${contractId}.pt`, - missingPassThrough.length === 0, - missingPassThrough.length === 0 - ? 'Every typed pt key reached its intended real part.' - : `pt did not reach: ${missingPassThrough.join(', ')}.`, - profile.slotId, - { ptKeys: profile.ptKeys }, + { + passed: missingPassThrough.length === 0, + message: missingPassThrough.length === 0 + ? 'Every typed pt key reached its intended real part.' + : `pt did not reach: ${missingPassThrough.join(', ')}.`, + slotId: profile.slotId, + evidence: { ptKeys: profile.ptKeys }, + }, ); }; +interface SlotCheckContext { + readonly checks: ConformanceCheck[]; + readonly declaration: unstable_SlotDeclaration; + readonly options: ConformanceOptions; + readonly document: Document; + readonly profile: SlotProfile; +} + +interface SlotEnvironment { + readonly library: unstable_UiLibrary; + readonly options: ConformanceOptions; + readonly document: Document; +} + const checkSlot = async ( checks: ConformanceCheck[], - library: unstable_UiLibrary, - options: ConformanceOptions, - document: Document, + { library, options, document }: SlotEnvironment, profile: SlotProfile, ) => { const declaration = library.slots[profile.slotId]; if (!declaration) { - addCheck( - checks, - ConformanceFamily.Contract, - `contract.${profile.slotId}.declaration`, - false, - 'Promised slot has no runtime declaration.', - profile.slotId, - ); + addCheck(checks, ConformanceFamily.Contract, `contract.${profile.slotId}.declaration`, { + passed: false, + message: 'Promised slot has no runtime declaration.', + slotId: profile.slotId, + }); return; } const typedDeclaration = declaration as unstable_SlotDeclaration; - const contractId = `contract.${profile.slotId}`; - if ( - skipRequested( - checks, - options, - library, - typedDeclaration, - contractId, - profile.slotId, - ) - ) - return; + if (skipRequested( + checks, + { options, library, declaration: typedDeclaration }, + `contract.${profile.slotId}`, + profile.slotId, + )) return; + + const context = { checks, declaration: typedDeclaration, options, document, profile }; + const observedStateAssociations = new Set(); + const platformOwnedParts = await checkMountedSlot(context, observedStateAssociations); + await checkStateFixture(context, observedStateAssociations); + if (profile.interact) { + await checkInteractions(checks, document, { declaration: typedDeclaration, profile }, options); + } + checkStateCoverage(context, observedStateAssociations, platformOwnedParts); +}; + +const checkNativeElement = ( + { checks, profile }: SlotCheckContext, + nativeRoot: ReturnType, + fixture: MountedFixture, +) => { + const native = nativeRoot.element; + const exactElement = nativeRoot.tagMatches && + (!profile.refCapable || fixture.ref.current === native); + addCheck(checks, ConformanceFamily.Contract, `contract.${profile.slotId}.elementRef`, { + passed: exactElement, + message: exactElement + ? 'The contract resolves to the exact real native element and forwarded ref.' + : 'The native element or forwarded ref does not match the slot contract.', + slotId: profile.slotId, + evidence: { + selector: profile.nativeSelector, + tag: native?.tagName, + refMatches: fixture.ref.current === native, + }, + }); +}; +const checkCanonicalStates = ({ checks, profile }: SlotCheckContext) => { + const partStates = cratisPartStates[profile.partsKey] as Readonly>; + const canonical = new Set(cratisCanonicalPartStates); + const unexpectedStates = Object.entries(partStates).flatMap(([part, states]) => + states.filter((state) => !canonical.has(state)).map((state) => `${part}.${state}`), + ); + addCheck(checks, ConformanceFamily.Contract, `contract.${profile.slotId}.states`, { + passed: unexpectedStates.length === 0, + message: unexpectedStates.length === 0 + ? 'The public part-state manifest uses only exact canonical state names for this slot.' + : `Unexpected canonical states: ${unexpectedStates.join(', ')}.`, + slotId: profile.slotId, + }); +}; + +const checkOwnership = ({ checks, declaration, document, profile }: SlotCheckContext) => { + const ownerCounts = profile.ownershipSelectors.map( + (selector) => document.querySelectorAll(selector).length, + ); + const ownershipPassed = ownerCounts.every((count) => count === 1); + addCheck(checks, ConformanceFamily.BehaviorOwnership, `ownership.${profile.slotId}`, { + passed: ownershipPassed, + message: ownershipPassed + ? `${declaration.mode} tree exposes exactly one declared interactive semantic root for each bounded selector.` + : `Expected one interactive semantic root for each selector; observed ${ownerCounts.join(', ')}.`, + slotId: profile.slotId, + evidence: { mode: declaration.mode, selectors: profile.ownershipSelectors, ownerCounts }, + }); +}; + +type NamedControl = ReturnType; + +const controlValue = (control: NamedControl) => + control && 'value' in control ? String(control.value) : undefined; + +const controlChecked = (control: NamedControl) => + control && 'checked' in control ? Boolean(control.checked) : undefined; + +const collectFormEvidence = async ( + fixture: MountedFixture, + baseProps: Readonly>, +) => { + const namedControl = fixture.form.elements.namedItem( + typeof baseProps.name === 'string' ? baseProps.name : '', + ); + const formData = Object.fromEntries(new FormData(fixture.form).entries()); + const nativeValue = controlValue(namedControl); + await act(async () => { + fixture.form.reset(); + await Promise.resolve(); + }); + const resetValue = controlValue(namedControl); + const resetChecked = controlChecked(namedControl); + const resetMatches = + (typeof baseProps.defaultValue !== 'string' || resetValue === baseProps.defaultValue) && + (typeof baseProps.defaultChecked !== 'boolean' || resetChecked === baseProps.defaultChecked); + return { + namedControl, + evidence: { + formData, + name: namedControl && 'name' in namedControl ? namedControl.name : undefined, + nativeValue, + resetValue, + resetChecked, + resetMatches, + }, + }; +}; + +const behaviorMatches = ( + baseProps: Readonly>, + callbackCount: number | undefined, + submitEvents: number, + { namedControl, evidence }: Awaited>, +) => + (callbackCount === undefined || callbackCount === 1) && + (baseProps.type !== 'submit' || submitEvents === 1) && + (typeof baseProps.name !== 'string' || namedControl !== null) && + evidence.resetMatches; + +const checkBehavior = async ( + { checks, document, profile }: SlotCheckContext, + fixture: MountedFixture, + baseProps: Readonly>, +) => { + let submitEvents = 0; + fixture.form.addEventListener('submit', (event) => { + event.preventDefault(); + submitEvents += 1; + }); + const exercisedEvidence: Readonly> = profile.exercise + ? ((await act(async () => profile.exercise?.(document, fixture.container, fixture.ref))) ?? {}) + : {}; + const form = await collectFormEvidence(fixture, baseProps); + const behaviorEvidence: Readonly> = { + ...exercisedEvidence, + submitEvents, + ...form.evidence, + }; + const callbackCount = typeof behaviorEvidence.callbacks === 'number' + ? behaviorEvidence.callbacks + : undefined; + const behaviorPassed = behaviorMatches(baseProps, callbackCount, submitEvents, form); + addCheck(checks, ConformanceFamily.Behavior, `behavior.${profile.slotId}`, { + passed: behaviorPassed, + message: behaviorPassed + ? 'Bounded public-prop behavior produced native semantics and at most one ordered callback.' + : `Expected one callback, observed ${String(callbackCount)}.`, + slotId: profile.slotId, + evidence: behaviorEvidence, + }); +}; + +const checkAccessibility = async ( + { checks, options, profile }: SlotCheckContext, + fixture: MountedFixture, +) => { + if (options.axe === false) return; + const axeResult = await axe.run(fixture.container, { + runOnly: { type: 'tag', values: ['wcag2a', 'wcag2aa'] }, + rules: { 'color-contrast': { enabled: false } }, + }); + addCheck(checks, ConformanceFamily.Accessibility, `a11y.${profile.slotId}.axe`, { + passed: axeResult.violations.length === 0, + message: axeResult.violations.length === 0 + ? 'axe found no WCAG A/AA violations in the bounded fixture.' + : `axe violations: ${axeResult.violations.map((violation) => violation.id).join(', ')}.`, + slotId: profile.slotId, + evidence: { violations: axeResult.violations.map((violation) => violation.id) }, + }); +}; + +const mountPartVariants = async ( + { document, declaration, profile, options }: SlotCheckContext, + variantFixtures: MountedFixture[], + observedStateAssociations: Set, +) => { + for (const variant of profile.createPartVariants?.() ?? []) { + const variantFixture = await mount( + document, + declaration, + { ...variant, pt: variantPassThrough(profile, variant.pt) }, + profile.refCapable, + options.wrapper, + ); + variantFixtures.push(variantFixture); + if (profile.activate) { + await act(async () => profile.activate?.(document, variantFixture.container)); + } + collectRenderedStates(document, observedStateAssociations); + } +}; + +const checkMountedSlot = async ( + context: SlotCheckContext, + observedStateAssociations: Set, +) => { + const { checks, declaration: typedDeclaration, options, document, profile } = context; + const contractId = `contract.${profile.slotId}`; let fixture: MountedFixture | undefined; const variantFixtures: MountedFixture[] = []; - const observedStateAssociations = new Set(); let platformOwnedParts: readonly string[] = []; try { const baseProps: Readonly> = { @@ -535,22 +758,7 @@ const checkSlot = async ( profile.activate?.(document, fixture?.container ?? document.body), ); collectRenderedStates(document, observedStateAssociations); - for (const variant of profile.createPartVariants?.() ?? []) { - const variantFixture = await mount( - document, - typedDeclaration, - { ...variant, pt: variantPassThrough(profile, variant.pt) }, - profile.refCapable, - options.wrapper, - ); - variantFixtures.push(variantFixture); - if (profile.activate) { - await act(async () => - profile.activate?.(document, variantFixture.container), - ); - } - collectRenderedStates(document, observedStateAssociations); - } + await mountPartVariants(context, variantFixtures, observedStateAssociations); const nativeRoot = findNativeRoot(profile, document, fixture.container); platformOwnedParts = nativeRoot.platformOwnedParts; @@ -560,161 +768,26 @@ const checkSlot = async ( for (const variantFixture of variantFixtures) await unmount(variantFixture); variantFixtures.length = 0; - const native = nativeRoot.element; - const exactElement = - nativeRoot.tagMatches && - (!profile.refCapable || fixture.ref.current === native); - addCheck( - checks, - ConformanceFamily.Contract, - `${contractId}.elementRef`, - exactElement, - exactElement - ? 'The contract resolves to the exact real native element and forwarded ref.' - : 'The native element or forwarded ref does not match the slot contract.', - profile.slotId, - { - selector: profile.nativeSelector, - tag: native?.tagName, - refMatches: fixture.ref.current === native, - }, - ); - - const partStates = cratisPartStates[profile.partsKey] as Readonly< - Record - >; - const canonical = new Set(cratisCanonicalPartStates); - const unexpectedStates = Object.entries(partStates).flatMap(([part, states]) => - states - .filter((state) => !canonical.has(state)) - .map((state) => `${part}.${state}`), - ); - addCheck( - checks, - ConformanceFamily.Contract, - `${contractId}.states`, - unexpectedStates.length === 0, - unexpectedStates.length === 0 - ? 'The public part-state manifest uses only exact canonical state names for this slot.' - : `Unexpected canonical states: ${unexpectedStates.join(', ')}.`, - profile.slotId, - ); - - const ownerCounts = profile.ownershipSelectors.map( - (selector) => document.querySelectorAll(selector).length, - ); - const ownershipPassed = ownerCounts.every((count) => count === 1); - addCheck( - checks, - ConformanceFamily.BehaviorOwnership, - `ownership.${profile.slotId}`, - ownershipPassed, - ownershipPassed - ? `${typedDeclaration.mode} tree exposes exactly one declared interactive semantic root for each bounded selector.` - : `Expected one interactive semantic root for each selector; observed ${ownerCounts.join(', ')}.`, - profile.slotId, - { - mode: typedDeclaration.mode, - selectors: profile.ownershipSelectors, - ownerCounts, - }, - ); - - let submitEvents = 0; - fixture.form.addEventListener('submit', (event) => { - event.preventDefault(); - submitEvents += 1; - }); - const exercisedEvidence: Readonly> = profile.exercise - ? ((await act(async () => - profile.exercise?.( - document, - fixture?.container ?? document.body, - fixture?.ref ?? createRef(), - ), - )) ?? {}) - : {}; - const namedControl = fixture.form.elements.namedItem( - typeof baseProps.name === 'string' ? baseProps.name : '', - ); - const formData = Object.fromEntries(new FormData(fixture.form).entries()); - const nativeValue = - namedControl && 'value' in namedControl - ? String(namedControl.value) - : undefined; - await act(async () => { - fixture?.form.reset(); - await Promise.resolve(); - }); - const resetValue = - namedControl && 'value' in namedControl - ? String(namedControl.value) - : undefined; - const resetChecked = - namedControl && 'checked' in namedControl - ? Boolean(namedControl.checked) - : undefined; - const resetMatches = - (typeof baseProps.defaultValue !== 'string' || - resetValue === baseProps.defaultValue) && - (typeof baseProps.defaultChecked !== 'boolean' || - resetChecked === baseProps.defaultChecked); - const behaviorEvidence: Readonly> = { - ...exercisedEvidence, - submitEvents, - formData, - name: namedControl && 'name' in namedControl ? namedControl.name : undefined, - nativeValue, - resetValue, - resetChecked, - resetMatches, - }; - const callbackCount = - typeof behaviorEvidence.callbacks === 'number' - ? behaviorEvidence.callbacks - : undefined; - const submitExpected = baseProps.type === 'submit'; - const behaviorPassed = - (callbackCount === undefined || callbackCount === 1) && - (!submitExpected || submitEvents === 1) && - (typeof baseProps.name !== 'string' || namedControl !== null) && - resetMatches; - addCheck( - checks, - ConformanceFamily.Behavior, - `behavior.${profile.slotId}`, - behaviorPassed, - behaviorPassed - ? 'Bounded public-prop behavior produced native semantics and at most one ordered callback.' - : `Expected one callback, observed ${String(callbackCount)}.`, - profile.slotId, - behaviorEvidence, - ); + checkNativeElement(context, nativeRoot, fixture); + checkCanonicalStates(context); + checkOwnership(context); - if (options.axe !== false) { - const axeResult = await axe.run(fixture.container, { - runOnly: { type: 'tag', values: ['wcag2a', 'wcag2aa'] }, - rules: { 'color-contrast': { enabled: false } }, - }); - addCheck( - checks, - ConformanceFamily.Accessibility, - `a11y.${profile.slotId}.axe`, - axeResult.violations.length === 0, - axeResult.violations.length === 0 - ? 'axe found no WCAG A/AA violations in the bounded fixture.' - : `axe violations: ${axeResult.violations.map((violation) => violation.id).join(', ')}.`, - profile.slotId, - { violations: axeResult.violations.map((violation) => violation.id) }, - ); - } + await checkBehavior(context, fixture, baseProps); + await checkAccessibility(context, fixture); } catch (error) { - addError(checks, ConformanceFamily.Contract, contractId, error, profile.slotId); + addError(checks, ConformanceFamily.Contract, contractId, { error, slotId: profile.slotId }); } finally { if (fixture) await unmount(fixture); for (const variantFixture of variantFixtures) await unmount(variantFixture); } + return platformOwnedParts; +}; + +const checkStateFixture = async ( + { checks, declaration: typedDeclaration, options, document, profile }: SlotCheckContext, + observedStateAssociations: Set, +) => { if (profile.createStateProps) { let stateFixture: MountedFixture | undefined; try { @@ -734,29 +807,32 @@ const checkSlot = async ( checks, ConformanceFamily.Behavior, `behavior.${profile.slotId}.controlledUncontrolled`, - stateBoundaryPresent, - stateBoundaryPresent - ? 'Controlled/stateful and uncontrolled/default fixture forms both render through the same public slot declaration.' - : 'State fixture did not render a public part boundary.', - profile.slotId, + { + passed: stateBoundaryPresent, + message: stateBoundaryPresent + ? 'Controlled/stateful and uncontrolled/default fixture forms both render through the same public slot declaration.' + : 'State fixture did not render a public part boundary.', + slotId: profile.slotId, + }, ); } catch (error) { addError( checks, ConformanceFamily.Behavior, `behavior.${profile.slotId}.controlledUncontrolled`, - error, - profile.slotId, + { error, slotId: profile.slotId }, ); } finally { if (stateFixture) await unmount(stateFixture); } } +}; - if (profile.interact) { - await checkInteractions(checks, document, { declaration: typedDeclaration, profile }, options); - } - +const checkStateCoverage = ( + { checks, profile }: SlotCheckContext, + observedStateAssociations: Set, + platformOwnedParts: readonly string[], +) => { const expectedStateAssociations = stateAssociationsOf( cratisPartStates[profile.partsKey] as Readonly>, platformOwnedParts, @@ -768,14 +844,16 @@ const checkSlot = async ( checks, ConformanceFamily.Contract, `contract.${profile.slotId}.stateCoverage`, - missingStateAssociations.length === 0, - missingStateAssociations.length === 0 - ? 'Every canonical component/part state was observed in a bounded fixture.' - : `Canonical states not observed: ${missingStateAssociations.join(', ')}.`, - profile.slotId, { - expectedStateAssociations, - observedStateAssociations: [...observedStateAssociations].sort(), + passed: missingStateAssociations.length === 0, + message: missingStateAssociations.length === 0 + ? 'Every canonical component/part state was observed in a bounded fixture.' + : `Canonical states not observed: ${missingStateAssociations.join(', ')}.`, + slotId: profile.slotId, + evidence: { + expectedStateAssociations, + observedStateAssociations: [...observedStateAssociations].sort(), + }, }, ); }; @@ -805,20 +883,21 @@ const checkServerRendering = ( checks, ConformanceFamily.ServerRendering, `ssr.${profile.slotId}`, - first === second, - first === second - ? 'Server render is DOM-free and deterministic.' - : 'Repeated server renders differ.', - profile.slotId, - { bytes: first.length }, + { + passed: first === second, + message: first === second + ? 'Server render is DOM-free and deterministic.' + : 'Repeated server renders differ.', + slotId: profile.slotId, + evidence: { bytes: first.length }, + }, ); } catch (error) { addError( checks, ConformanceFamily.ServerRendering, `ssr.${profile.slotId}`, - error, - profile.slotId, + { error, slotId: profile.slotId }, ); } } @@ -832,14 +911,15 @@ const checkServerRendering = ( checks, ConformanceFamily.ServerRendering, 'ssr.overlayAbsentPresent', - overlayPassed, - overlayPassed - ? 'The closed tooltip omits its deferred popup while the explicitly present dialog renders during SSR.' - : 'SSR overlay absent/present semantics differ from the bounded fixtures.', - undefined, { - tooltipObserved: tooltipOutput !== undefined, - dialogObserved: dialogOutput !== undefined, + passed: overlayPassed, + message: overlayPassed + ? 'The closed tooltip omits its deferred popup while the explicitly present dialog renders during SSR.' + : 'SSR overlay absent/present semantics differ from the bounded fixtures.', + evidence: { + tooltipObserved: tooltipOutput !== undefined, + dialogObserved: dialogOutput !== undefined, + }, }, ); const distinctOutputs = new Set(outputs.values()).size === outputs.size; @@ -847,12 +927,13 @@ const checkServerRendering = ( checks, ConformanceFamily.ServerRendering, 'ssr.slotOutputIsolation', - distinctOutputs, - distinctOutputs - ? 'Each exercised slot produced a distinct slot-local server-rendered output.' - : 'Two exercised slots collapsed to indistinguishable server-rendered output.', - undefined, - { slots: [...outputs.keys()] }, + { + passed: distinctOutputs, + message: distinctOutputs + ? 'Each exercised slot produced a distinct slot-local server-rendered output.' + : 'Two exercised slots collapsed to indistinguishable server-rendered output.', + evidence: { slots: [...outputs.keys()] }, + }, ); }; @@ -871,8 +952,7 @@ const checkHydration = async ( checks, ConformanceFamily.ServerRendering, 'ssr.hydration', - false, - 'No renderable slot is available for hydration evidence.', + { passed: false, message: 'No renderable slot is available for hydration evidence.' }, ); return; } @@ -904,12 +984,14 @@ const checkHydration = async ( checks, ConformanceFamily.ServerRendering, 'ssr.hydration', - deterministic, - deterministic - ? 'Server markup hydrates deterministically with no recoverable mismatch.' - : `Hydration mismatches: ${recoverableErrors.join('; ')}.`, - profile.slotId, - { recoverableErrors }, + { + passed: deterministic, + message: deterministic + ? 'Server markup hydrates deterministically with no recoverable mismatch.' + : `Hydration mismatches: ${recoverableErrors.join('; ')}.`, + slotId: profile.slotId, + evidence: { recoverableErrors }, + }, ); }; @@ -929,8 +1011,10 @@ const checkEnvironmentalEvidence = async ( checks, ConformanceFamily.Accessibility, `a11y.environment.${mode}`, - false, - 'No renderable slot is available for bounded environmental-host evidence.', + { + passed: false, + message: 'No renderable slot is available for bounded environmental-host evidence.', + }, ); } return; @@ -962,12 +1046,14 @@ const checkEnvironmentalEvidence = async ( checks, ConformanceFamily.Accessibility, `a11y.environment.${mode}`, - inputs[mode], - inputs[mode] - ? `The ${profile.slotId} fixture rendered inside the bounded ${mode} DOM host input.` - : `The ${profile.slotId} fixture did not preserve the bounded ${mode} DOM host input.`, - profile.slotId, - { selector: profile.nativeSelector }, + { + passed: inputs[mode], + message: inputs[mode] + ? `The ${profile.slotId} fixture rendered inside the bounded ${mode} DOM host input.` + : `The ${profile.slotId} fixture did not preserve the bounded ${mode} DOM host input.`, + slotId: profile.slotId, + evidence: { selector: profile.nativeSelector }, + }, ); } } catch (error) { @@ -976,8 +1062,7 @@ const checkEnvironmentalEvidence = async ( checks, ConformanceFamily.Accessibility, `a11y.environment.${mode}`, - error, - profile.slotId, + { error, slotId: profile.slotId }, ); } } finally { @@ -1013,7 +1098,7 @@ export const runConformance = async ( exercised.slotIds.includes(profile.slotId), ); for (const profile of profiles) - await checkSlot(checks, exercised.library, options, document, profile); + await checkSlot(checks, { library: exercised.library, options, document }, profile); checkServerRendering(checks, exercised.library, profiles, options.wrapper); await checkHydration( checks, @@ -1034,8 +1119,10 @@ export const runConformance = async ( checks, ConformanceFamily.Contract, 'runtime.domAvailable', - false, - 'DOM checks require an explicit Document; SSR import remains safe.', + { + passed: false, + message: 'DOM checks require an explicit Document; SSR import remains safe.', + }, ); } From 2582ca9ec146cc99ed6d2ae096f0d45b1c0a7117 Mon Sep 17 00:00:00 2001 From: woksin Date: Sat, 21 Nov 2026 15:01:09 +0100 Subject: [PATCH 2/4] Raise Code Health of slotProfiles.tsx --- .../when_recording_slot_callback_evidence.ts | 73 ++++++ Conformance/src/internal/slotProfiles.tsx | 222 ++++++------------ 2 files changed, 146 insertions(+), 149 deletions(-) create mode 100644 Conformance/for_conformance/when_recording_slot_callback_evidence.ts diff --git a/Conformance/for_conformance/when_recording_slot_callback_evidence.ts b/Conformance/for_conformance/when_recording_slot_callback_evidence.ts new file mode 100644 index 00000000..94c84013 --- /dev/null +++ b/Conformance/for_conformance/when_recording_slot_callback_evidence.ts @@ -0,0 +1,73 @@ +// Copyright (c) Cratis. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +import 'chai/register-should.js'; +import { describe, it } from 'vitest'; +import { createSlotProfiles } from '../src/internal/slotProfiles.js'; + +const changeCases = [ + { slotId: 'common.textInput', value: 'after', expected: 'after' }, + { slotId: 'common.textArea', value: 'after', expected: 'after' }, + { slotId: 'common.numberInput', value: undefined, expected: undefined }, + { slotId: 'common.checkbox', value: true, expected: true }, + { slotId: 'common.radio', value: true, expected: true }, + { slotId: 'common.switch', value: true, expected: true }, + { slotId: 'dropdown.select', value: 'editor', expected: 'editor' }, + { slotId: 'display.datePicker', value: new Date('2026-01-02T00:00:00.000Z'), expected: '2026-01-02T00:00:00.000Z' }, + { slotId: 'display.datePicker', value: null, expected: undefined }, +] as const; + +const callbackFor = (props: Readonly>, name: string) => { + const callback = props[name]; + if (typeof callback !== 'function') throw new Error(`Missing ${name} callback.`); + return callback; +}; + +describe('when recording slot callback evidence', () => { + for (const { slotId, value, expected } of changeCases) { + it(`should preserve the value and native metadata for ${slotId} with ${String(value)}`, () => { + const evidence = new Map>>(); + const profile = createSlotProfiles(evidence).find((candidate) => candidate.slotId === slotId); + if (!profile) throw new Error(`Missing ${slotId} profile.`); + const onChange = callbackFor(profile.createProps(), 'onChange'); + const meta = { source: 'user', nativeEvent: new Event('change') }; + + onChange(value, meta); + onChange(value, meta); + + (evidence.get(slotId)! as object).should.deep.equal({ + callbacks: 2, + value: expected, + source: 'user', + nativeEvent: true, + }); + callbackFor(profile.createProps(), 'onChange')(value); + (evidence.get(slotId)! as object).should.deep.equal({ + callbacks: 1, + value: expected, + source: undefined, + nativeEvent: false, + }); + }); + } + + for (const [slotId, name, value, detail] of [ + ['common.button', 'onClick', undefined, {}], + ['common.iconButton', 'onClick', undefined, {}], + ['dialogs.dialog', 'onClose', undefined, {}], + ['datatables.paginator', 'onPageChange', 2, { page: 2 }], + ] as const) { + it(`should count each ${slotId} fixture independently`, () => { + const evidence = new Map>>(); + const profile = createSlotProfiles(evidence).find((candidate) => candidate.slotId === slotId); + if (!profile) throw new Error(`Missing ${slotId} profile.`); + const callback = callbackFor(profile.createProps(), name); + + callback(value); + callback(value); + (evidence.get(slotId)! as object).should.deep.equal({ callbacks: 2, ...detail }); + callbackFor(profile.createProps(), name)(value); + (evidence.get(slotId)! as object).should.deep.equal({ callbacks: 1, ...detail }); + }); + } +}); diff --git a/Conformance/src/internal/slotProfiles.tsx b/Conformance/src/internal/slotProfiles.tsx index 50697275..91c1c246 100644 --- a/Conformance/src/internal/slotProfiles.tsx +++ b/Conformance/src/internal/slotProfiles.tsx @@ -36,18 +36,44 @@ const click = (container: ParentNode, selector: string) => { const numberInputSlotId = 'common.numberInput'; -const recordNumberChanges = (evidence: Map>>) => { +type Evidence = Map>>; + +const recordCallbacks = ( + evidence: Evidence, + slotId: SlotProfile['slotId'], + describe: (...values: T) => Readonly> = () => ({}), +) => { let callbacks = 0; - const onChange: NumericInputProps['onChange'] = (value, meta) => { + return (...values: T) => { callbacks += 1; - evidence.set(numberInputSlotId, { - callbacks, - value, - source: meta?.source, - nativeEvent: meta?.nativeEvent instanceof Event, - }); + evidence.set(slotId, { callbacks, ...describe(...values) }); }; - return onChange; +}; + +const recordChanges = ( + evidence: Evidence, + slotId: SlotProfile['slotId'], + serialize: (value: T) => unknown = (value) => value, +) => recordCallbacks(evidence, slotId, ( + value: T, + meta?: { source: string; nativeEvent?: Event }, +) => ({ + value: serialize(value), + source: meta?.source, + nativeEvent: meta?.nativeEvent instanceof Event, +})); + +const changeText = ( + container: ParentNode, + selector: string, + prototype: HTMLInputElement | HTMLTextAreaElement, +) => { + const input = container.querySelector(selector); + if (input) { + Object.getOwnPropertyDescriptor(prototype, 'value')?.set?.call(input, 'after'); + input.dispatchEvent(new Event('input', { bubbles: true })); + } + return input; }; const typeNumber = (input: HTMLInputElement | null, value: string) => { @@ -70,19 +96,12 @@ export const createSlotProfiles = ( nativeTag: 'BUTTON', refCapable: true, ownershipSelectors: ['button'], - createProps: () => { - let callbacks = 0; - const props = { - label: 'Save', - icon: createElement('span', null, '+'), - type: 'submit', - onClick: () => { - callbacks += 1; - evidence.set('common.button', { callbacks }); - }, - } satisfies ButtonProps; - return recordProps(props); - }, + createProps: () => recordProps({ + label: 'Save', + icon: createElement('span', null, '+'), + type: 'submit', + onClick: recordCallbacks(evidence, 'common.button'), + } satisfies ButtonProps), createStateProps: () => recordProps({ label: 'Saving', @@ -105,18 +124,11 @@ export const createSlotProfiles = ( nativeTag: 'BUTTON', refCapable: true, ownershipSelectors: ['button'], - createProps: () => { - let callbacks = 0; - const props = { - icon: createElement('span', null, '+'), - 'aria-label': 'Add item', - onClick: () => { - callbacks += 1; - evidence.set('common.iconButton', { callbacks }); - }, - } satisfies IconButtonProps; - return recordProps(props); - }, + createProps: () => recordProps({ + icon: createElement('span', null, '+'), + 'aria-label': 'Add item', + onClick: recordCallbacks(evidence, 'common.iconButton'), + } satisfies IconButtonProps), createStateProps: () => recordProps({ icon: createElement('span', null, '+'), @@ -144,24 +156,12 @@ export const createSlotProfiles = ( nativeTag: 'INPUT', refCapable: true, ownershipSelectors: ['input[type="text"]'], - createProps: () => { - let callbacks = 0; - const props = { - name: 'sample', - defaultValue: 'before', - 'aria-label': 'Sample text', - onChange: (value, meta) => { - callbacks += 1; - evidence.set('common.textInput', { - callbacks, - value, - source: meta?.source, - nativeEvent: meta?.nativeEvent instanceof Event, - }); - }, - } satisfies TextInputProps; - return recordProps(props); - }, + createProps: () => recordProps({ + name: 'sample', + defaultValue: 'before', + 'aria-label': 'Sample text', + onChange: recordChanges(evidence, 'common.textInput'), + } satisfies TextInputProps), createStateProps: () => recordProps({ defaultValue: 'state', @@ -170,14 +170,7 @@ export const createSlotProfiles = ( readOnly: true, } satisfies TextInputProps), exercise: async (_document, container) => { - const input = container.querySelector('input[type="text"]'); - if (input) { - Object.getOwnPropertyDescriptor( - HTMLInputElement.prototype, - 'value', - )?.set?.call(input, 'after'); - input.dispatchEvent(new Event('input', { bubbles: true })); - } + const input = changeText(container, 'input[type="text"]', HTMLInputElement.prototype); return ( evidence.get('common.textInput') ?? { callbacks: 0, value: input?.value } ); @@ -197,7 +190,7 @@ export const createSlotProfiles = ( name: 'quantity', value: 3, 'aria-label': 'Sample quantity', - onChange: recordNumberChanges(evidence), + onChange: recordChanges(evidence, numberInputSlotId), } satisfies NumericInputProps), createStateProps: () => recordProps({ @@ -220,24 +213,12 @@ export const createSlotProfiles = ( nativeTag: 'TEXTAREA', refCapable: true, ownershipSelectors: ['textarea'], - createProps: () => { - let callbacks = 0; - const props = { - name: 'notes', - defaultValue: 'before', - 'aria-label': 'Sample notes', - onChange: (value, meta) => { - callbacks += 1; - evidence.set('common.textArea', { - callbacks, - value, - source: meta?.source, - nativeEvent: meta?.nativeEvent instanceof Event, - }); - }, - } satisfies TextAreaProps; - return recordProps(props); - }, + createProps: () => recordProps({ + name: 'notes', + defaultValue: 'before', + 'aria-label': 'Sample notes', + onChange: recordChanges(evidence, 'common.textArea'), + } satisfies TextAreaProps), createStateProps: () => recordProps({ defaultValue: 'state', @@ -246,14 +227,7 @@ export const createSlotProfiles = ( readOnly: true, } satisfies TextAreaProps), exercise: async (_document, container) => { - const input = container.querySelector('textarea'); - if (input) { - Object.getOwnPropertyDescriptor( - HTMLTextAreaElement.prototype, - 'value', - )?.set?.call(input, 'after'); - input.dispatchEvent(new Event('input', { bubbles: true })); - } + const input = changeText(container, 'textarea', HTMLTextAreaElement.prototype); return ( evidence.get('common.textArea') ?? { callbacks: 0, value: input?.value } ); @@ -274,19 +248,7 @@ export const createSlotProfiles = ( isSwitch ? 'input[role="switch"]' : 'input[type="checkbox"]', ], createProps: () => { - let callbacks = 0; - const onChange = ( - value: boolean, - meta?: { source: string; nativeEvent?: Event }, - ) => { - callbacks += 1; - evidence.set(slotId, { - callbacks, - value, - source: meta?.source, - nativeEvent: meta?.nativeEvent instanceof Event, - }); - }; + const onChange = recordChanges(evidence, slotId); return isSwitch ? recordProps({ label: 'Enabled', @@ -334,25 +296,13 @@ export const createSlotProfiles = ( nativeTag: 'INPUT', refCapable: true, ownershipSelectors: ['input[type="radio"]'], - createProps: () => { - let callbacks = 0; - const props = { - label: 'Daily', - name: 'frequency', - value: 'daily', - defaultChecked: false, - onChange: (value, meta) => { - callbacks += 1; - evidence.set('common.radio', { - callbacks, - value, - source: meta?.source, - nativeEvent: meta?.nativeEvent instanceof Event, - }); - }, - } satisfies RadioProps; - return recordProps(props); - }, + createProps: () => recordProps({ + label: 'Daily', + name: 'frequency', + value: 'daily', + defaultChecked: false, + onChange: recordChanges(evidence, 'common.radio'), + } satisfies RadioProps), createStateProps: () => recordProps({ label: 'Daily', @@ -459,7 +409,6 @@ export const createSlotProfiles = ( refCapable: false, ownershipSelectors: ['[data-cratis-part="trigger"]'], createProps: () => { - let callbacks = 0; const props = { name: 'role', value: null, @@ -473,15 +422,7 @@ export const createSlotProfiles = ( optionValue: 'value', showClear: true, 'aria-label': 'Role', - onChange: (value, meta) => { - callbacks += 1; - evidence.set('dropdown.select', { - callbacks, - value, - source: meta?.source, - nativeEvent: meta?.nativeEvent instanceof Event, - }); - }, + onChange: recordChanges(evidence, 'dropdown.select'), } satisfies DropdownProps; return recordProps(props); }, @@ -600,7 +541,6 @@ export const createSlotProfiles = ( refCapable: false, ownershipSelectors: ['[role="dialog"], dialog'], createProps: () => { - let callbacks = 0; const props = { title: 'Example dialog', subtitle: 'Example subtitle', @@ -608,10 +548,7 @@ export const createSlotProfiles = ( children: 'Dialog content', buttons: 2, dismissable: true, - onClose: () => { - callbacks += 1; - evidence.set('dialogs.dialog', { callbacks }); - }, + onClose: recordCallbacks(evidence, 'dialogs.dialog'), } satisfies DialogProps; return recordProps(props); }, @@ -659,21 +596,12 @@ export const createSlotProfiles = ( refCapable: false, ownershipSelectors: ['[data-cratis-part="group"]'], createProps: () => { - let callbacks = 0; const props = { value: null, showButtonBar: true, placeholder: 'Choose a date', 'aria-label': 'Delivery date', - onChange: (value, meta) => { - callbacks += 1; - evidence.set('display.datePicker', { - callbacks, - value: value?.toISOString(), - source: meta?.source, - nativeEvent: meta?.nativeEvent instanceof Event, - }); - }, + onChange: recordChanges(evidence, 'display.datePicker', (value) => value?.toISOString()), } satisfies DatePickerInputProps; return recordProps(props); }, @@ -746,16 +674,12 @@ export const createSlotProfiles = ( refCapable: false, ownershipSelectors: ['[role="navigation"]'], createProps: () => { - let callbacks = 0; const props = { page: 1, pageCount: 3, totalItems: 30, pageSize: 10, - onPageChange: (page) => { - callbacks += 1; - evidence.set('datatables.paginator', { callbacks, page }); - }, + onPageChange: recordCallbacks(evidence, 'datatables.paginator', (page: number) => ({ page })), } satisfies TablePaginatorProps; return recordProps(props); }, From 5591ba389738475f75bd0a50d667f5c1bb60bb6f Mon Sep 17 00:00:00 2001 From: woksin Date: Sat, 21 Nov 2026 15:01:13 +0100 Subject: [PATCH 3/4] Raise Code Health of choice.tsx --- .../when_resolving_choice_part_state.tsx | 118 ++++++++++++++ Adapters/Designsystemet/src/choice.tsx | 154 +++++++++++++----- 2 files changed, 228 insertions(+), 44 deletions(-) create mode 100644 Adapters/Designsystemet/for_adapter/when_resolving_choice_part_state.tsx diff --git a/Adapters/Designsystemet/for_adapter/when_resolving_choice_part_state.tsx b/Adapters/Designsystemet/for_adapter/when_resolving_choice_part_state.tsx new file mode 100644 index 00000000..98389566 --- /dev/null +++ b/Adapters/Designsystemet/for_adapter/when_resolving_choice_part_state.tsx @@ -0,0 +1,118 @@ +// Copyright (c) Cratis. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +import 'chai/register-should.js'; +import { act, createElement, type ReactNode } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import { afterEach, describe, it } from 'vitest'; +import { DesignsystemetCheckboxSlot, DesignsystemetRadioSlot, DesignsystemetSwitchSlot } from '../src/choice.js'; + +let root: Root | undefined; +let container: HTMLDivElement; + +const render = async (element: ReactNode) => { + container = document.createElement('div'); + document.body.append(container); + root = createRoot(container); + await act(async () => root?.render(element)); + return container.querySelector('input')!; +}; + +afterEach(async () => { + await act(async () => root?.unmount()); + container?.remove(); + root = undefined; +}); + +const slots = [ + { name: 'checkbox', Slot: DesignsystemetCheckboxSlot }, + { name: 'radio', Slot: DesignsystemetRadioSlot }, + { name: 'switch', Slot: DesignsystemetSwitchSlot }, +] as const; + +for (const { name, Slot } of slots) { + describe(`when resolving ${name} part state`, () => { + it('should let explicit false public props override true input-part state', async () => { + const input = await render(createElement(Slot, { + id: 'public-choice', + name: 'example-choice', + value: 'selected', + label: 'Example choice', + checked: false, + disabled: false, + readOnly: false, + 'aria-invalid': false, + onChange: () => undefined, + pt: { input: { id: 'part-choice', checked: true, disabled: true, readOnly: true, 'aria-invalid': true } }, + })); + + [input.checked, input.disabled, input.readOnly].should.deep.equal([false, false, false]); + input.getAttribute('aria-invalid')!.should.equal('false'); + input.id.should.equal('public-choice'); + container.querySelector('label')!.htmlFor.should.equal('public-choice'); + container.querySelectorAll('[data-selected], [data-disabled], [data-readonly], [data-invalid]').length.should.equal(0); + }); + + it('should inherit native state and label association from the input part', async () => { + const input = await render(createElement(Slot, { + label: 'Example choice', + name: 'example-choice', + value: 'selected', + pt: { input: { id: 'part-choice', checked: true, disabled: true, readOnly: true, 'aria-invalid': 'true' } }, + })); + + [input.checked, input.disabled, input.readOnly].should.deep.equal([true, true, true]); + container.querySelector('label')!.htmlFor.should.equal('part-choice'); + for (const part of container.querySelectorAll('[data-cratis-part]')) { + for (const state of ['selected', 'disabled', 'readonly', 'invalid']) { + part.hasAttribute(`data-${state}`).should.equal(true); + } + } + }); + + it('should preserve click order and run the part change before the value-first callback', async () => { + const calls: string[] = []; + const observed: unknown[] = []; + const input = await render(createElement(Slot, { + label: 'Example choice', + name: 'example-choice', + value: 'selected', + defaultChecked: false, + onClick: () => calls.push('public-click'), + onChange: (checked, meta) => { + calls.push('public-change'); + observed.push(checked, meta?.source, meta?.nativeEvent instanceof Event); + }, + pt: { input: { + onClick: () => calls.push('part-click'), + onChange: () => calls.push('part-change'), + } }, + })); + + await act(async () => input.click()); + + calls.should.deep.equal(['part-click', 'public-click', 'part-change', 'public-change']); + observed.should.deep.equal([true, 'user', true]); + input.checked.should.equal(true); + container.querySelector('[data-cratis-part="root"]')!.hasAttribute('data-selected').should.equal(true); + }); + + it('should prevent read-only user changes', async () => { + let changes = 0; + const input = await render(createElement(Slot, { + label: 'Example choice', + name: 'example-choice', + value: 'selected', + defaultChecked: false, + readOnly: true, + onChange: () => { changes += 1; }, + })); + + await act(async () => input.click()); + + changes.should.equal(0); + input.checked.should.equal(false); + container.querySelectorAll('[data-selected]').length.should.equal(0); + }); + }); +} diff --git a/Adapters/Designsystemet/src/choice.tsx b/Adapters/Designsystemet/src/choice.tsx index 43697be4..e966148d 100644 --- a/Adapters/Designsystemet/src/choice.tsx +++ b/Adapters/Designsystemet/src/choice.tsx @@ -12,6 +12,7 @@ import { type ForwardedRef, type HTMLAttributes, type InputHTMLAttributes, + type MouseEvent, } from 'react'; import { Field as DsField, Input as DsInput, Label as DsLabel } from '@digdir/designsystemet-react'; import type { @@ -129,6 +130,105 @@ const VisualPart = ({ ); }; +const resolveChoiceInvalid = (props: ChoiceProps, inputPart: InputHTMLAttributes | undefined) => { + const ariaInvalid = props['aria-invalid'] ?? inputPart?.['aria-invalid'] ?? (props.invalid || undefined); + return { + ariaInvalid, + invalid: Boolean(props.invalid) || ariaInvalid === true || ariaInvalid === 'true', + }; +}; + +const resolveChoiceInputState = (props: ChoiceProps, inputPart: InputHTMLAttributes | undefined) => ({ + checked: props.checked ?? inputPart?.checked, + defaultChecked: props.defaultChecked ?? inputPart?.defaultChecked, + disabled: props.disabled ?? inputPart?.disabled, + readOnly: props.readOnly ?? inputPart?.readOnly, +}); + +const useChoiceInput = (props: ChoiceProps, forwardedRef: ForwardedRef, kind: ChoiceKind) => { + const generatedId = useId(); + const parts = props.pt as ChoiceParts | undefined; + const inputPart = parts?.input as InputHTMLAttributes | undefined; + const inputState = resolveChoiceInputState(props, inputPart); + const { ariaInvalid, invalid } = resolveChoiceInvalid(props, inputPart); + const state = useNativeCheckedState(inputState.checked, inputState.defaultChecked, forwardedRef, kind === 'radio'); + return { + parts, + inputPart, + inputId: props.id ?? inputPart?.id ?? generatedId, + inputState, + ariaInvalid, + state, + attributes: stateAttributes(inputState.disabled, invalid, inputState.readOnly, state.selected), + }; +}; + +const choiceSemantics = (kind: ChoiceKind, role: ChoiceProps['role']) => ({ + type: kind === 'radio' ? 'radio' : 'checkbox', + role: kind === 'switch' ? 'switch' : role, +} as const); + +const choiceAriaReadOnly = (kind: ChoiceKind, readOnly: boolean | undefined) => + kind === 'radio' ? undefined : readOnly || undefined; + +const createChoiceChangeHandler = ({ + partOnChange, + onChange, + readOnly, + kind, + synchronize, +}: { + readonly partOnChange: InputHTMLAttributes['onChange']; + readonly onChange: ChoiceProps['onChange']; + readonly readOnly: boolean | undefined; + readonly kind: ChoiceKind; + readonly synchronize: (checked: boolean) => void; +}) => (event: ChangeEvent) => { + partOnChange?.(event); + if (readOnly || (kind === 'radio' && !event.currentTarget.checked)) return; + synchronize(event.currentTarget.checked); + onChange?.(event.currentTarget.checked, { + source: 'user', + nativeEvent: event.nativeEvent, + }); +}; + +const createChoiceClickHandler = ( + partOnClick: InputHTMLAttributes['onClick'], + onClick: ChoiceProps['onClick'], + readOnly: boolean | undefined, +) => (event: MouseEvent) => { + partOnClick?.(event); + onClick?.(event); + if (readOnly) event.preventDefault(); +}; + +const ChoiceLabel = ({ + label, + parts, + inputId, + attributes, +}: { + readonly label: ChoiceProps['label']; + readonly parts: ChoiceParts | undefined; + readonly inputId: string; + readonly attributes: DataAttributes; +}) => { + const labelPart = parts?.label as HTMLAttributes | undefined; + return label !== undefined && ( + + {label} + + ); +}; + const DesignsystemetChoice = ({ kind, props, @@ -138,18 +238,8 @@ const DesignsystemetChoice = ({ readonly props: ChoiceProps; readonly forwardedRef: ForwardedRef; }) => { - const generatedId = useId(); - const parts = props.pt as ChoiceParts | undefined; - const inputPart = parts?.input as InputHTMLAttributes | undefined; - const checked = props.checked ?? inputPart?.checked; - const defaultChecked = props.defaultChecked ?? inputPart?.defaultChecked; - const disabled = props.disabled ?? inputPart?.disabled; - const readOnly = props.readOnly ?? inputPart?.readOnly; - const ariaInvalid = - props['aria-invalid'] ?? inputPart?.['aria-invalid'] ?? (props.invalid || undefined); - const invalid = Boolean(props.invalid) || ariaInvalid === true || ariaInvalid === 'true'; - const state = useNativeCheckedState(checked, defaultChecked, forwardedRef, kind === 'radio'); - const attributes = stateAttributes(disabled, invalid, readOnly, state.selected); + const { parts, inputPart, inputId, inputState, ariaInvalid, state, attributes } = useChoiceInput(props, forwardedRef, kind); + const { checked, defaultChecked, disabled, readOnly } = inputState; const { label, readOnly: _readOnly, @@ -163,7 +253,7 @@ const DesignsystemetChoice = ({ disabled: _disabled, onClick, 'aria-invalid': _ariaInvalid, - id, + id: _id, ...nativeProps } = props; const { @@ -177,17 +267,9 @@ const DesignsystemetChoice = ({ disabled: _partDisabled, ...inputPartRest } = inputPart ?? {}; - const inputId = id ?? inputPart?.id ?? generatedId; - const labelPart = parts?.label as HTMLAttributes | undefined; - const handleChange = (event: ChangeEvent) => { - partOnChange?.(event); - if (readOnly || (kind === 'radio' && !event.currentTarget.checked)) return; - state.synchronize(event.currentTarget.checked); - onChange?.(event.currentTarget.checked, { - source: 'user', - nativeEvent: event.nativeEvent, - }); - }; + const handleChange = createChoiceChangeHandler({ + partOnChange, onChange, readOnly, kind, synchronize: state.synchronize, + }); return ( )} @@ -201,38 +283,22 @@ const DesignsystemetChoice = ({ {...nativeProps} id={inputId} ref={state.ref} - type={kind === 'radio' ? 'radio' : 'checkbox'} - role={kind === 'switch' ? 'switch' : nativeProps.role} + {...choiceSemantics(kind, nativeProps.role)} checked={checked} defaultChecked={defaultChecked} disabled={disabled} readOnly={readOnly} aria-invalid={ariaInvalid} - aria-readonly={kind === 'radio' ? undefined : readOnly || undefined} + aria-readonly={choiceAriaReadOnly(kind, readOnly)} className={classNames('cratis-designsystemet-choice__input', inputClassName)} style={inputStyle} data-cratis-part='input' {...attributes} onChange={handleChange} - onClick={(event) => { - partOnClick?.(event); - onClick?.(event); - if (readOnly) event.preventDefault(); - }} + onClick={createChoiceClickHandler(partOnClick, onClick, readOnly)} /> - {label !== undefined && ( - - {label} - - )} + ); }; From ca59c15e650118b0c4ea59264f3695ab4bcc5919 Mon Sep 17 00:00:00 2001 From: woksin Date: Sat, 21 Nov 2026 15:01:18 +0100 Subject: [PATCH 4/4] Raise Code Health of fields.tsx --- .../when_resolving_text_field_part_state.tsx | 108 ++++++++++++++++++ Adapters/Designsystemet/src/fields.tsx | 94 ++++++++------- 2 files changed, 153 insertions(+), 49 deletions(-) create mode 100644 Adapters/Designsystemet/for_adapter/when_resolving_text_field_part_state.tsx diff --git a/Adapters/Designsystemet/for_adapter/when_resolving_text_field_part_state.tsx b/Adapters/Designsystemet/for_adapter/when_resolving_text_field_part_state.tsx new file mode 100644 index 00000000..17fdb9c8 --- /dev/null +++ b/Adapters/Designsystemet/for_adapter/when_resolving_text_field_part_state.tsx @@ -0,0 +1,108 @@ +// Copyright (c) Cratis. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. + +import 'chai/register-should.js'; +import { act, createElement, type ReactNode } from 'react'; +import { createRoot, type Root } from 'react-dom/client'; +import { afterEach, describe, it } from 'vitest'; +import type { TextAreaProps, TextInputProps } from '@cratis/components/Common'; +import { DesignsystemetTextAreaSlot, DesignsystemetTextInputSlot } from '../src/fields.js'; + +let root: Root | undefined; +let container: HTMLDivElement; + +const render = async (element: ReactNode) => { + container = document.createElement('div'); + document.body.append(container); + root = createRoot(container); + await act(async () => root?.render(element)); + return container.querySelector('input, textarea')!; +}; + +afterEach(async () => { + await act(async () => root?.unmount()); + container?.remove(); + root = undefined; +}); + +const fields = [ + { + name: 'text input', + Slot: (props: TextInputProps & TextAreaProps) => createElement(DesignsystemetTextInputSlot, props), + prototype: HTMLInputElement.prototype, + }, + { + name: 'text area', + Slot: (props: TextInputProps & TextAreaProps) => createElement(DesignsystemetTextAreaSlot, props), + prototype: HTMLTextAreaElement.prototype, + }, +] as const; + +for (const { name, Slot, prototype } of fields) { + describe(`when resolving ${name} part state`, () => { + it('should let explicit false public props override true root-part state', async () => { + const field = await render(createElement(Slot, { + disabled: false, + readOnly: false, + 'aria-invalid': false, + pt: { root: { disabled: true, readOnly: true, 'aria-invalid': true } }, + })); + + [field.disabled, field.readOnly].should.deep.equal([false, false]); + field.getAttribute('aria-invalid')!.should.equal('false'); + container.querySelectorAll('[data-disabled], [data-readonly], [data-invalid]').length.should.equal(0); + }); + + it('should inherit native state from the root part', async () => { + const field = await render(createElement(Slot, { + pt: { root: { disabled: true, readOnly: true, 'aria-invalid': 'true' } }, + })); + + [field.disabled, field.readOnly].should.deep.equal([true, true]); + for (const state of ['disabled', 'readonly', 'invalid']) { + field.getAttribute(`data-${state}`)!.should.equal('true'); + } + }); + + it('should keep canonical invalid state even when aria-invalid is explicitly false', async () => { + const field = await render(createElement(Slot, { invalid: true, 'aria-invalid': false })); + + field.getAttribute('aria-invalid')!.should.equal('false'); + field.getAttribute('data-invalid')!.should.equal('true'); + }); + + it('should merge root styling before public styling', async () => { + const field = await render(createElement(Slot, { + className: 'public-field', + style: { color: 'blue' }, + pt: { root: { className: 'part-field', style: { color: 'red', margin: '2px' } } }, + })); + + field.classList.contains('part-field').should.equal(true); + field.classList.contains('public-field').should.equal(true); + field.style.color.should.equal('blue'); + field.style.margin.should.equal('2px'); + }); + + it('should call the root handler before the public value-first handler with the native event', async () => { + const calls: string[] = []; + const observed: unknown[] = []; + const field = await render(createElement(Slot, { + defaultValue: 'before', + onChange: (value, meta) => { + calls.push('public'); + observed.push(value, meta?.source, meta?.nativeEvent instanceof Event); + }, + pt: { root: { onChange: () => calls.push('part') } }, + })); + + await act(async () => { + Object.getOwnPropertyDescriptor(prototype, 'value')!.set!.call(field, 'after'); + field.dispatchEvent(new Event('input', { bubbles: true })); + }); + + calls.should.deep.equal(['part', 'public']); + observed.should.deep.equal(['after', 'user', true]); + }); + }); +} diff --git a/Adapters/Designsystemet/src/fields.tsx b/Adapters/Designsystemet/src/fields.tsx index 890e583f..27627a4e 100644 --- a/Adapters/Designsystemet/src/fields.tsx +++ b/Adapters/Designsystemet/src/fields.tsx @@ -1,7 +1,7 @@ // Copyright (c) Cratis. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -import { forwardRef, type ChangeEvent } from 'react'; +import { forwardRef, type ChangeEvent, type ChangeEventHandler } from 'react'; import { Input as DsInput, Textarea as DsTextarea } from '@digdir/designsystemet-react'; import type { NumericInputProps, TextAreaProps, TextInputProps } from '@cratis/components/Common'; import { classNames } from './classNames.js'; @@ -20,6 +20,29 @@ const resolveInvalid = ( }; }; +const resolveFieldState = ( + props: Pick, + root: Pick | undefined, +) => { + const state = resolveInvalid(props.invalid ?? false, props['aria-invalid'], root?.['aria-invalid']); + return { + ...state, + disabled: props.disabled ?? root?.disabled, + readOnly: props.readOnly ?? root?.readOnly, + }; +}; + +const createTextChangeHandler = ( + root: { onChange?: ChangeEventHandler } | undefined, + onChange: TextInputProps['onChange'], +) => (event: ChangeEvent) => { + root?.onChange?.(event); + onChange?.(event.currentTarget.value, { + source: 'user', + nativeEvent: event.nativeEvent, + }); +}; + /** Designsystemet implementation of `common.textInput`. */ export const DesignsystemetTextInputSlot = forwardRef( function DesignsystemetTextInputSlot( @@ -37,31 +60,24 @@ export const DesignsystemetTextInputSlot = forwardRef { - pt?.root?.onChange?.(event); - onChange?.(event.currentTarget.value, { - source: 'user', - nativeEvent: event.nativeEvent, - }); - }} - className={classNames('cratis-designsystemet-text-input', pt?.root?.className, className)} - style={{ ...pt?.root?.style, ...style }} + onChange={createTextChangeHandler(root, onChange)} + className={classNames('cratis-designsystemet-text-input', root?.className, className)} + style={{ ...root?.style, ...style }} data-cratis-part='root' - data-disabled={effectiveDisabled || undefined} + data-disabled={state.disabled || undefined} data-invalid={state.invalid || undefined} - data-readonly={effectiveReadOnly || undefined} + data-readonly={state.readOnly || undefined} /> ); }, @@ -69,19 +85,6 @@ export const DesignsystemetTextInputSlot = forwardRef['root']; -const resolveNumberState = (props: NumericInputProps, root: NumberRoot) => { - const state = resolveInvalid( - props.invalid ?? false, - props['aria-invalid'], - root?.['aria-invalid'], - ); - return { - ...state, - disabled: props.disabled ?? root?.disabled, - readOnly: props.readOnly ?? root?.readOnly, - }; -}; - const createNumberChangeHandler = (root: NumberRoot, onChange: NumericInputProps['onChange']) => (event: ChangeEvent) => { @@ -109,7 +112,7 @@ export const DesignsystemetNumberInputSlot = forwardRef { - pt?.root?.onChange?.(event); - onChange?.(event.currentTarget.value, { - source: 'user', - nativeEvent: event.nativeEvent, - }); - }} - className={classNames('cratis-designsystemet-text-area', pt?.root?.className, className)} - style={{ ...pt?.root?.style, ...style }} + onChange={createTextChangeHandler(root, onChange)} + className={classNames('cratis-designsystemet-text-area', root?.className, className)} + style={{ ...root?.style, ...style }} data-cratis-part='root' - data-disabled={effectiveDisabled || undefined} + data-disabled={state.disabled || undefined} data-invalid={state.invalid || undefined} - data-readonly={effectiveReadOnly || undefined} + data-readonly={state.readOnly || undefined} /> ); },