All files / src/renderer renderField.ts

91.86% Statements 79/86
86.95% Branches 40/46
76.92% Functions 20/26
98.71% Lines 77/78

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 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282                                                                                                            108x   108x                         109x 109x     109x           109x   109x 8x                 109x 8x                 109x       145x       3x       3x 1x     2x       77x 77x                 77x 21x   56x     77x 77x 77x 77x       1x 1x                 1x 1x 1x 1x 1x       30x 30x       30x 30x   30x 57x         57x 57x     30x 30x 30x 30x 30x       1x 1x               1x   1x 1x 1x     1x 1x 1x 1x                       1x           1x 1x 1x 1x 1x     1x 1x     1x 26x 28x 1x 1x 21x                             114x 114x 114x 114x   114x       114x                       7x 1x      
import type {
  FieldSchema,
  FieldValue,
  FormSchema,
  FormStateSnapshot,
  NormalizedField,
  NormalizedFormSchema
} from "../schema/types";
import { createElement } from "../dom/createElement";
import { createErrorDomId, createFieldDomId, createHelpDomId } from "../dom/ids";
import type { EventRegistry } from "../dom/events";
 
/** Public field shape exposed to custom renderers. */
export type RenderedFieldSchema = FieldSchema & {
  /** Normalized field ID derived from `id` or `name`. */
  id: string;
  /** Normalized schema path used internally for stable traversal. */
  path: string[];
};
 
/** Context passed to custom field renderers. */
export interface FieldRenderContext {
  /** Normalized field definition for the field being rendered. */
  field: RenderedFieldSchema;
  /** Schema for the owning form. */
  schema: FormSchema;
  /** Current immutable form state snapshot. */
  state: FormStateSnapshot;
  /** Active CSS class prefix. */
  classPrefix: string;
  /** Stable input ID generated by the runtime. */
  inputId: string;
  /** Stable help text element ID generated by the runtime. */
  helpId: string;
  /** Stable error element ID generated by the runtime. */
  errorId: string;
  /** Space-separated IDs that should be applied to `aria-describedby`. */
  describedBy: string;
  /** Current field value. */
  value: FieldValue;
  /** Current field errors, if any. */
  errors: string[];
  /** Event registry that custom renderers must use for automatic cleanup. */
  events: EventRegistry;
  /** Update the field value in runtime state. */
  setValue(value: FieldValue): void;
  /** Mark the field as touched. */
  markTouched(): void;
}
 
/** Function used to render a custom field type. */
export type FieldRenderer = (context: FieldRenderContext) => HTMLElement;
 
function commonAttributes(context: FieldRenderContext): Record<string, string | boolean | undefined> {
  const { field, inputId, describedBy, errors } = context;
 
  return {
    id: inputId,
    name: field.name,
    disabled: field.disabled ?? false,
    readonly: field.readonly && !["select", "checkbox", "radio"].includes(field.type),
    required: field.required ?? false,
    "aria-invalid": errors.length > 0 ? "true" : "false",
    "aria-describedby": describedBy || undefined
  };
}
 
/** Build shared label, help, and error DOM using safe text nodes only. */
function createFieldShell(context: FieldRenderContext): HTMLDivElement {
  const { classPrefix, errors, errorId, field, helpId, inputId } = context;
  const shell = createElement("div", {
    className: `${classPrefix}-field ${errors.length > 0 ? `${classPrefix}-field--invalid` : ""}`
  });
  const label = createElement("label", {
    className: `${classPrefix}-label`,
    text: field.required ? `${field.label} *` : field.label,
    attributes: { for: inputId }
  });
 
  shell.append(label);
 
  if (field.helpText) {
    shell.append(
      createElement("p", {
        className: `${classPrefix}-help`,
        text: field.helpText,
        attributes: { id: helpId }
      })
    );
  }
 
  if (errors.length > 0) {
    shell.append(
      createElement("p", {
        className: `${classPrefix}-error`,
        text: errors[0],
        attributes: { id: errorId, role: "alert" }
      })
    );
  }
 
  return shell;
}
 
function normalizeInputValue(value: FieldValue): string {
  return value === undefined || value === null ? "" : String(value);
}
 
function readInputValue(input: HTMLInputElement): FieldValue {
  Iif (input.type === "number") {
    return input.value === "" ? null : Number(input.value);
  }
 
  if (input.type === "checkbox") {
    return input.checked;
  }
 
  return input.value;
}
 
function renderInput(context: FieldRenderContext, inputType: string): HTMLElement {
  const shell = createFieldShell(context);
  const input = createElement("input", {
    className: `${context.classPrefix}-control`,
    attributes: {
      ...commonAttributes(context),
      type: inputType,
      placeholder: context.field.placeholder
    }
  });
 
  if (inputType === "checkbox") {
    input.checked = context.value === true;
  } else {
    input.value = normalizeInputValue(context.value);
  }
 
  context.events.listen(input, "input", () => context.setValue(readInputValue(input)));
  context.events.listen(input, "blur", () => context.markTouched());
  shell.insertBefore(input, shell.querySelector(`.${context.classPrefix}-error`));
  return shell;
}
 
function renderTextarea(context: FieldRenderContext): HTMLElement {
  const shell = createFieldShell(context);
  const textarea = createElement("textarea", {
    className: `${context.classPrefix}-control`,
    attributes: {
      ...commonAttributes(context),
      placeholder: context.field.placeholder,
      rows: "4"
    }
  });
 
  textarea.value = normalizeInputValue(context.value);
  context.events.listen(textarea, "input", () => context.setValue(textarea.value));
  context.events.listen(textarea, "blur", () => context.markTouched());
  shell.insertBefore(textarea, shell.querySelector(`.${context.classPrefix}-error`));
  return shell;
}
 
function renderSelect(context: FieldRenderContext): HTMLElement {
  const shell = createFieldShell(context);
  const select = createElement("select", {
    className: `${context.classPrefix}-control`,
    attributes: commonAttributes(context)
  });
  const placeholder = createElement("option", { text: "Select an option", attributes: { value: "" } });
  select.append(placeholder);
 
  context.field.options?.forEach((option) => {
    const optionElement = createElement("option", {
      text: option.label,
      attributes: { value: String(option.value) }
    });
 
    optionElement.selected = String(option.value) === normalizeInputValue(context.value);
    select.append(optionElement);
  });
 
  select.value = normalizeInputValue(context.value);
  context.events.listen(select, "change", () => context.setValue(select.value));
  context.events.listen(select, "blur", () => context.markTouched());
  shell.insertBefore(select, shell.querySelector(`.${context.classPrefix}-error`));
  return shell;
}
 
function renderRadio(context: FieldRenderContext): HTMLElement {
  const shell = createFieldShell(context);
  const group = createElement("div", {
    className: `${context.classPrefix}-radio-group`,
    attributes: {
      role: "radiogroup",
      "aria-labelledby": `${context.inputId}-legend`,
      "aria-describedby": context.describedBy || undefined
    }
  });
  const label = shell.querySelector("label");
 
  Eif (label) {
    label.id = `${context.inputId}-legend`;
    label.removeAttribute("for");
  }
 
  context.field.options?.forEach((option, index) => {
    const optionId = `${context.inputId}-${index}`;
    const optionShell = createElement("div", { className: `${context.classPrefix}-choice` });
    const input = createElement("input", {
      className: `${context.classPrefix}-choice-input`,
      attributes: {
        id: optionId,
        name: context.field.name,
        type: "radio",
        value: String(option.value),
        disabled: context.field.disabled ?? false,
        required: context.field.required ?? false,
        "aria-invalid": context.errors.length > 0 ? "true" : "false"
      }
    });
    const choiceLabel = createElement("label", {
      className: `${context.classPrefix}-choice-label`,
      text: option.label,
      attributes: { for: optionId }
    });
 
    input.checked = String(option.value) === normalizeInputValue(context.value);
    context.events.listen(input, "change", () => context.setValue(String(option.value)));
    context.events.listen(input, "blur", () => context.markTouched());
    optionShell.append(input, choiceLabel);
    group.append(optionShell);
  });
 
  shell.insertBefore(group, shell.querySelector(`.${context.classPrefix}-error`));
  return shell;
}
 
export const builtInRenderers: Record<string, FieldRenderer> = {
  text: (context) => renderInput(context, "text"),
  email: (context) => renderInput(context, "email"),
  number: (context) => renderInput(context, "number"),
  password: (context) => renderInput(context, "password"),
  checkbox: (context) => renderInput(context, "checkbox"),
  textarea: renderTextarea,
  select: renderSelect,
  radio: renderRadio
};
 
export function createDefaultFieldContext(
  field: NormalizedField,
  schema: NormalizedFormSchema,
  state: FormStateSnapshot,
  classPrefix: string,
  events: EventRegistry,
  setValue: (fieldName: string, value: FieldValue) => void,
  markTouched: (fieldName: string) => void
): FieldRenderContext {
  const inputId = createFieldDomId(schema.id, field.name, classPrefix);
  const helpId = createHelpDomId(inputId);
  const errorId = createErrorDomId(inputId);
  const errors = state.errors[field.name] ?? [];
  // `aria-describedby` references only elements that are present in the DOM.
  const describedBy = [field.helpText ? helpId : "", errors.length > 0 ? errorId : ""]
    .filter(Boolean)
    .join(" ");
 
  return {
    field,
    schema,
    state,
    classPrefix,
    inputId,
    helpId,
    errorId,
    describedBy,
    value: state.values[field.name],
    errors,
    events,
    setValue: (value) => setValue(field.name, value),
    markTouched: () => markTouched(field.name)
  };
}