Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/linear-option-render.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@formhaus/core": patch
---

- Fixed `renderToStaticMarkup()` and `checkDefinition()` taking quadratic time on fields with thousands of options.
60 changes: 60 additions & 0 deletions packages/core/__tests__/html/static-scaling.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { afterEach, describe, expect, it, vi } from 'vitest';
import { renderToStaticMarkup } from '../../src/html';
import type { StaticMarkupOptions } from '../../src/html';
import { form } from './fixtures';

const SCANNERS = ['indexOf', 'includes', 'find', 'findIndex', 'some', 'every'] as const;

function scanned(run: () => void): number {
let total = 0;
for (const name of SCANNERS) {
const original = Array.prototype[name] as (...args: unknown[]) => unknown;
vi.spyOn(Array.prototype, name).mockImplementation(function (this: unknown[], ...args: unknown[]) {
total += this.length;
return original.apply(this, args);
} as never);
}
try {
run();
} finally {
vi.restoreAllMocks();
}
return total;
}

function scans(type: string, size: number, defaulted: boolean, options: StaticMarkupOptions): number {
const values = Array.from({ length: size }, (_, index) => `v${index}`);
const field = {
key: 'k',
type,
label: 'K',
options: values.map((value, index) => ({ value, label: `Option ${index}` })),
...(defaulted && { defaultValue: values }),
};
const definition = form([field as never]);
return scanned(() => renderToStaticMarkup(definition, { ...options, values: options.values && { k: values } }));
}

const SMALL = 200;
const LARGE = 800;

describe('option rendering scales linearly', () => {
afterEach(() => vi.restoreAllMocks());

const cases: [string, string, boolean, StaticMarkupOptions][] = [
['radio', 'radio', false, {}],
['read-only radio with nothing selected', 'radio', false, { readOnly: true }],
['select', 'select', false, {}],
['autocomplete', 'autocomplete', false, {}],
['multiselect', 'multiselect', false, {}],
['multiselect with every option selected', 'multiselect', false, { values: {} }],
['read-only multiselect with every option selected', 'multiselect', false, { values: {}, readOnly: true }],
['multiselect with every option as its default', 'multiselect', true, {}],
];

it.each(cases)('%s', (_name, type, defaulted, options) => {
const small = scans(type, SMALL, defaulted, options);
const large = scans(type, LARGE, defaulted, options);
expect(large).toBeLessThan(small * (LARGE / SMALL) * 1.5);
});
});
6 changes: 3 additions & 3 deletions packages/core/src/definition-validation/fields.ts
Original file line number Diff line number Diff line change
Expand Up @@ -63,9 +63,9 @@ function ruleIssues(context: CheckContext, { field, path, group }: FieldEntry, f
}

function optionIssues({ field, path }: FieldEntry): DefinitionIssue[] {
const values = (field.options ?? []).map((option) => option.value);
return values.flatMap((value, index) =>
values.indexOf(value) < index ? [error('duplicate-option-value', `${path}/options/${index}/value`, value)] : [],
const seen = new Set<unknown>();
return (field.options ?? []).flatMap(({ value }, index) =>
seen.size === seen.add(value).size ? [error('duplicate-option-value', `${path}/options/${index}/value`, value)] : [],
);
}

Expand Down
8 changes: 4 additions & 4 deletions packages/core/src/definition-validation/warnings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,8 @@ function valueIssue(target: FormField, operator: string, operand: unknown, path:
return mismatch(`${JSON.stringify(wrong)} is a ${typeof wrong}, but "${target.key}" holds a ${expected}`, `Use a ${expected} value`);
const options =
(expected === 'string' || list) && !target.optionsFrom && target.options?.length ? target.options.map((option) => option.value) : null;
const missing = options && operands.find((item) => !options.includes(item as string));
const known = options && new Set<unknown>(options);
const missing = known && operands.find((item) => !known.has(item));
return options && missing !== undefined
? mismatch(
`${JSON.stringify(missing)} is not an option of "${target.key}"`,
Expand Down Expand Up @@ -97,11 +98,10 @@ function optionIssues({ field, path }: FieldEntry): DefinitionIssue[] {
];
}
const values = field.options.map((option) => option.value);
const known = new Set<unknown>(values);
const defaults = field.type === 'multiselect' && Array.isArray(field.defaultValue) ? field.defaultValue : [field.defaultValue];
const missing =
field.defaultValue === undefined || !values.length || field.optionsFrom
? undefined
: defaults.find((value) => !values.includes(value as string));
field.defaultValue === undefined || !values.length || field.optionsFrom ? undefined : defaults.find((value) => !known.has(value));
if (missing === undefined) return [];
return [
warning(
Expand Down
47 changes: 32 additions & 15 deletions packages/core/src/html/choices.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { optionChecked, optionDescriptionId, optionLocked } from '../fields/state';
import { optionChecked, optionDescriptionId } from '../fields/state';
import { optionText } from '../fields/options';
import { scaleView } from '../fields/scale';
import { dividerBefore, optionTexts } from '../internal/options';
Expand All @@ -11,8 +11,19 @@ type OptionVariant = 'radio' | 'multiselect';

const optionsOf = ({ field }: FieldContext): FieldOption[] => (Array.isArray(field.options) ? field.options : []);

const firstOpen = (context: FieldContext): number =>
optionsOf(context).findIndex((option) => !optionLocked(option, context.value, context.readOnly));
interface OptionStates {
checked: (option: FieldOption) => boolean;
locked: (option: FieldOption) => boolean;
firstOpen: number;
}

function optionStates(context: FieldContext): OptionStates {
const { value, readOnly } = context;
const selected = Array.isArray(value) ? new Set<unknown>(value) : undefined;
const checked = (option: FieldOption): boolean => (selected ? selected.has(option.value) : optionChecked(value, option));
const locked = (option: FieldOption): boolean => option.disabled === true || (readOnly && !checked(option));
return { checked, locked, firstOpen: optionsOf(context).findIndex((option) => !locked(option)) };
}

const picture = (option: FieldOption): Html | false => {
const source = imageSource(option.image);
Expand All @@ -37,17 +48,24 @@ function optionLabel(option: FieldOption, id: string, variant: OptionVariant): C
];
}

function optionInput(context: FieldContext, option: FieldOption, id: string, type: 'radio' | 'checkbox', first: boolean): Html {
const { field, value, readOnly } = context;
function optionInput(
context: FieldContext,
states: OptionStates,
option: FieldOption,
id: string,
type: 'radio' | 'checkbox',
first: boolean,
): Html {
const { field } = context;
return html('input', {
id,
name: field.key,
autocomplete: field.autocomplete,
type,
class: `fh-field__${type}`,
value: option.value,
checked: optionChecked(value, option),
disabled: optionLocked(option, value, readOnly),
checked: states.checked(option),
disabled: states.locked(option),
required: type === 'radio' && !!field.validation?.required,
autofocus: first && context.autofocus,
'aria-describedby': option.description ? optionDescriptionId(id) : undefined,
Expand All @@ -57,6 +75,7 @@ function optionInput(context: FieldContext, option: FieldOption, id: string, typ

export function radio(context: FieldContext): Html {
const { id } = context;
const states = optionStates(context);
return shell(
context,
'radio',
Expand All @@ -65,7 +84,7 @@ export function radio(context: FieldContext): Html {
return html(
'div',
{ class: 'fh-field__radio-option' },
optionInput(context, option, optionId, 'radio', index === firstOpen(context)),
optionInput(context, states, option, optionId, 'radio', index === states.firstOpen),
optionLabel(option, optionId, 'radio'),
);
}),
Expand All @@ -75,6 +94,7 @@ export function radio(context: FieldContext): Html {
export function multiselect(context: FieldContext): Html {
const { id, text, field } = context;
const options = optionsOf(context);
const states = optionStates(context);
return shell(
context,
'multiselect',
Expand All @@ -85,7 +105,7 @@ export function multiselect(context: FieldContext): Html {
html(
'div',
{ class: 'fh-field__multiselect-option' },
optionInput(context, option, optionId, 'checkbox', index === firstOpen(context)),
optionInput(context, states, option, optionId, 'checkbox', index === states.firstOpen),
optionLabel(option, optionId, 'multiselect'),
),
];
Expand Down Expand Up @@ -132,7 +152,8 @@ export function scale(context: FieldContext): Html {
}

export function select(context: FieldContext): Html {
const { field, value, readOnly } = context;
const { field, value } = context;
const { locked } = optionStates(context);
const current = textOf(value);
const placeholder = field.placeholder;
return shell(
Expand All @@ -144,11 +165,7 @@ export function select(context: FieldContext): Html {
(!!placeholder || current === '') &&
html('option', { value: '', disabled: true, hidden: !placeholder, selected: current === '' }, placeholder),
optionsOf(context).map((option) =>
html(
'option',
{ value: option.value, disabled: optionLocked(option, value, readOnly), selected: option.value === current },
option.label,
),
html('option', { value: option.value, disabled: locked(option), selected: option.value === current }, option.label),
),
),
);
Expand Down
16 changes: 10 additions & 6 deletions packages/core/src/html/markup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,14 +17,18 @@ const UNSAFE_ALL = /[&<>"'\0]/g;

const escapeHtml = (text: string): string => (UNSAFE.test(text) ? text.replace(UNSAFE_ALL, (char) => ESCAPES[char]) : text);

function content(children: readonly Child[]): string {
let text = '';
function collect(children: readonly Child[], parts: string[]): void {
for (const child of children) {
if (child instanceof Html) text += child.value;
else if (Array.isArray(child)) text += content(child);
else if (typeof child === 'string' || typeof child === 'number') text += escapeHtml(String(child));
if (child instanceof Html) parts.push(child.value);
else if (Array.isArray(child)) collect(child, parts);
else if (typeof child === 'string' || typeof child === 'number') parts.push(escapeHtml(String(child)));
}
return text;
}

function content(children: readonly Child[]): string {
const parts: string[] = [];
collect(children, parts);
return parts.join('');
}

export function html(name: string, attrs: Attrs, ...children: Child[]): Html {
Expand Down
Loading