All files / src index.ts

100% Statements 54/54
100% Branches 14/14
100% Functions 16/16
100% Lines 53/53

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216                                                                                                                                                                        7x                     17x 17x 17x 17x 17x 17x   60x 50x     20x 4x             37x 37x 37x                   1x               10x 10x 10x   10x 7x 7x     10x       7x 7x   7x 1x   6x     7x 7x     7x       2x   2x 1x         1x 1x 1x     17x   17x   7x 7x       4x 4x 4x 4x       8x 8x       1x 1x       17x 1x         16x 16x 16x        
import "./styles/form-schema-runtime.css";
 
import { createEventRegistry } from "./dom/events";
import { createFieldDomId } from "./dom/ids";
import { collectVisibleFields, renderForm } from "./renderer/renderForm";
import { createRendererRegistry } from "./renderer/rendererRegistry";
import type { RendererMap } from "./renderer/rendererRegistry";
import { createFormState } from "./state/formState";
import { normalizeSchema } from "./schema/normalizeSchema";
import type {
  CustomValidatorMap,
  FieldErrors,
  FieldValue,
  FormSchema,
  FormStateSnapshot,
  FormValues
} from "./publicTypes";
import { validateForm } from "./validation/validateForm";
 
export type {
  BuiltInFieldType,
  CustomValidator,
  CustomValidatorContext,
  FieldError,
  FieldErrors,
  FieldOption,
  FieldRenderer,
  FieldRenderContext,
  FieldSchema,
  FieldType,
  FieldValue,
  FormSchema,
  FormStateSnapshot,
  FormValues,
  CustomValidatorMap,
  EventRegistry,
  RenderedFieldSchema,
  RendererMap,
  SchemaNode,
  SectionSchema,
  ValidationMessageKey,
  VisibilityCondition,
  VisibilityRule
} from "./publicTypes";
 
/** Options used to create and mount a form instance. */
export interface CreateFormOptions {
  /** Container element whose children are owned by this form instance. */
  container: HTMLElement;
  /** Declarative form schema to render. */
  schema: FormSchema;
  /** Optional values merged over field defaults during initialization and reset. */
  initialValues?: FormValues;
  /** CSS class prefix. Defaults to `fsr`. */
  classPrefix?: string;
  /** Custom synchronous validators keyed by the names used in field schemas. */
  validators?: CustomValidatorMap;
  /** Custom renderers keyed by field type. */
  renderers?: RendererMap;
  /** Called after values change through UI input or `setValues`. */
  onChange?: (values: FormValues, state: FormStateSnapshot) => void;
  /** Called after a valid submit. */
  onSubmit?: (values: FormValues, state: FormStateSnapshot) => void;
  /** Called when validation fails through submit or `validate`. */
  onValidationError?: (errors: FieldErrors, state: FormStateSnapshot) => void;
  /** Called after reset restores the initial state. */
  onReset?: (state: FormStateSnapshot) => void;
}
 
/** Public controller returned by `createForm`. */
export interface FormInstance {
  /** Return a defensive copy of current values. */
  getValues(): FormValues;
  /** Merge values into known schema fields and re-render. */
  setValues(values: FormValues): void;
  /** Validate visible fields and return whether the form is valid. */
  validate(): boolean;
  /** Restore initial values and clear touched, dirty, and error state. */
  reset(): void;
  /** Remove event listeners and DOM owned by the form. */
  destroy(): void;
}
 
function focusErrorSummary(container: HTMLElement, classPrefix: string): void {
  container.querySelector<HTMLElement>(`.${classPrefix}-error-summary`)?.focus();
}
 
/**
 * Render an accessible form into a container from a declarative schema.
 *
 * The runtime owns the container children until `destroy()` is called. Schema
 * text is rendered with DOM APIs and `textContent`; schema strings are never
 * executed as code.
 */
export function createForm(options: CreateFormOptions): FormInstance {
  const schema = normalizeSchema(options.schema);
  const classPrefix = options.classPrefix ?? "fsr";
  const state = createFormState(schema, options.initialValues);
  const registry = createRendererRegistry(options.renderers);
  let events = createEventRegistry();
  let destroyed = false;
 
  const getVisibleFields = () => collectVisibleFields(schema.fields, state.getSnapshot().values);
  const getSnapshot = () => state.getSnapshot(getVisibleFields());
 
  function ensureActive(): void {
    if (destroyed) {
      throw new Error("Cannot use a form instance after destroy() has been called.");
    }
  }
 
  function render(): void {
    // Re-rendering replaces the owned subtree; listener cleanup runs first so
    // custom renderers cannot leak handlers across conditional/state changes.
    events.cleanup();
    events = createEventRegistry();
    options.container.replaceChildren(
      renderForm({
        schema,
        state: getSnapshot(),
        classPrefix,
        events,
        registry,
        onSubmit: submit,
        onReset: reset,
        onValueChange,
        onTouched: (fieldName) => state.markTouched(fieldName)
      })
    );
  }
 
  function validateInternal(shouldNotify: boolean): boolean {
    // Validation is computed against the current visibility snapshot before the
    // form is re-rendered with field-level errors and the summary.
    const result = validateForm(schema, state.getValues(), options.validators, getVisibleFields());
    state.setErrors(result.errors);
    render();
 
    if (!result.valid && shouldNotify) {
      options.onValidationError?.(result.errors, getSnapshot());
      focusErrorSummary(options.container, classPrefix);
    }
 
    return result.valid;
  }
 
  function onValueChange(fieldName: string, value: FieldValue): void {
    state.setValue(fieldName, value);
    const currentErrors = getSnapshot().errors;
 
    if (Object.keys(currentErrors).length > 0) {
      validateInternal(false);
    } else {
      render();
    }
 
    options.onChange?.(state.getValues(), getSnapshot());
    const fieldElement = options.container.querySelector<HTMLElement>(
      `#${createFieldDomId(schema.id, fieldName, classPrefix)}`
    );
    fieldElement?.focus();
  }
 
  function submit(): void {
    const valid = validateInternal(true);
 
    if (valid) {
      options.onSubmit?.(state.getValues(), getSnapshot());
    }
  }
 
  function reset(): void {
    state.reset();
    render();
    options.onReset?.(getSnapshot());
  }
 
  render();
 
  return {
    getValues() {
      ensureActive();
      return state.getValues();
    },
 
    setValues(values) {
      ensureActive();
      state.setValues(values);
      render();
      options.onChange?.(state.getValues(), getSnapshot());
    },
 
    validate() {
      ensureActive();
      return validateInternal(true);
    },
 
    reset() {
      ensureActive();
      reset();
    },
 
    destroy() {
      if (destroyed) {
        return;
      }
 
      // Destroy is idempotent so callers can safely clean up during route or
      // widget teardown without coordinating ownership state.
      events.cleanup();
      options.container.replaceChildren();
      destroyed = true;
    }
  };
}