All files / src/renderer renderForm.ts

95.65% Statements 66/69
89.18% Branches 33/37
100% Functions 14/14
95.65% Lines 66/69

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                                                        301x               61x 220x   220x 35x     185x 1x     184x         37x 9x     37x 30x     7x               7x       7x   7x 9x   9x       9x 9x 9x         9x 1x 1x     9x 9x     7x 7x       115x   115x 1x     114x                           139x 23x     116x 115x     1x 1x   1x   1x           1x 8x   8x 8x       1x       37x       37x   37x 2x 2x   37x 1x 1x     37x 27x     37x           37x 7x     37x 131x   131x 107x       37x 37x                       37x   37x    
import { evaluateCondition } from "../conditions/evaluateCondition";
import { createElement } from "../dom/createElement";
import { createErrorSummaryId, createFieldDomId } from "../dom/ids";
import type { EventRegistry } from "../dom/events";
import type {
  FieldValue,
  FormStateSnapshot,
  NormalizedField,
  NormalizedFormSchema,
  NormalizedSchemaNode,
  NormalizedSection
} from "../schema/types";
import { builtInRenderers, createDefaultFieldContext } from "./renderField";
import type { RendererRegistry } from "./rendererRegistry";
 
export interface RenderFormOptions {
  schema: NormalizedFormSchema;
  state: FormStateSnapshot;
  classPrefix: string;
  events: EventRegistry;
  registry: RendererRegistry;
  onSubmit(): void;
  onReset(): void;
  onValueChange(fieldName: string, value: FieldValue): void;
  onTouched(fieldName: string): void;
}
 
function isSection(node: NormalizedSchemaNode): node is NormalizedSection {
  return node.type === "section";
}
 
export function collectVisibleFields(
  nodes: NormalizedSchemaNode[],
  values: FormStateSnapshot["values"],
  parentVisible = true
): string[] {
  return nodes.flatMap((node) => {
    const visible = parentVisible && evaluateCondition(node.visibleWhen, values);
 
    if (!visible) {
      return [];
    }
 
    if (isSection(node)) {
      return collectVisibleFields(node.fields, values, visible);
    }
 
    return [node.name];
  });
}
 
function renderErrorSummary(options: RenderFormOptions): HTMLElement | null {
  const entries = Object.entries(options.state.errors).filter(([fieldName]) =>
    options.state.visibleFields.includes(fieldName)
  );
 
  if (entries.length === 0) {
    return null;
  }
 
  const summary = createElement("div", {
    className: `${options.classPrefix}-error-summary`,
    attributes: {
      id: createErrorSummaryId(options.schema.id, options.classPrefix),
      role: "alert",
      tabindex: "-1"
    }
  });
  const title = createElement("h2", {
    className: `${options.classPrefix}-error-summary-title`,
    text: "There is a problem with this form"
  });
  const list = createElement("ul", { className: `${options.classPrefix}-error-summary-list` });
 
  entries.forEach(([fieldName, messages]) => {
    const field = options.schema.fieldMap.get(fieldName);
 
    Iif (!field || messages.length === 0) {
      return;
    }
 
    const item = createElement("li");
    const inputId = createFieldDomId(options.schema.id, field.name, options.classPrefix);
    const link = createElement("a", {
      text: `${field.label}: ${messages[0]}`,
      attributes: { href: `#${inputId}` }
    });
 
    options.events.listen(link, "click", (event) => {
      event.preventDefault();
      document.getElementById(inputId)?.focus();
    });
 
    item.append(link);
    list.append(item);
  });
 
  summary.append(title, list);
  return summary;
}
 
function renderField(field: NormalizedField, options: RenderFormOptions): HTMLElement {
  const renderer = options.registry.get(field.type) ?? builtInRenderers[field.type];
 
  if (!renderer) {
    throw new Error(`No renderer registered for field type "${field.type}".`);
  }
 
  return renderer(
    createDefaultFieldContext(
      field,
      options.schema,
      options.state,
      options.classPrefix,
      options.events,
      options.onValueChange,
      options.onTouched
    )
  );
}
 
function renderNode(node: NormalizedSchemaNode, options: RenderFormOptions): HTMLElement | null {
  if (!evaluateCondition(node.visibleWhen, options.state.values)) {
    return null;
  }
 
  if (!isSection(node)) {
    return renderField(node, options);
  }
 
  const section = createElement("fieldset", { className: `${options.classPrefix}-section` });
  const legend = createElement("legend", { className: `${options.classPrefix}-section-title`, text: node.title });
 
  section.append(legend);
 
  Iif (node.description) {
    section.append(
      createElement("p", { className: `${options.classPrefix}-section-description`, text: node.description })
    );
  }
 
  node.fields.forEach((child) => {
    const renderedChild = renderNode(child, options);
 
    Eif (renderedChild) {
      section.append(renderedChild);
    }
  });
 
  return section;
}
 
export function renderForm(options: RenderFormOptions): HTMLFormElement {
  const form = createElement("form", {
    className: `${options.classPrefix}-form`,
    attributes: { novalidate: true }
  });
  const summary = renderErrorSummary(options);
 
  options.events.listen(form, "submit", (event) => {
    event.preventDefault();
    options.onSubmit();
  });
  options.events.listen(form, "reset", (event) => {
    event.preventDefault();
    options.onReset();
  });
 
  if (options.schema.title) {
    form.append(createElement("h1", { className: `${options.classPrefix}-title`, text: options.schema.title }));
  }
 
  Iif (options.schema.description) {
    form.append(
      createElement("p", { className: `${options.classPrefix}-description`, text: options.schema.description })
    );
  }
 
  if (summary) {
    form.append(summary);
  }
 
  options.schema.fields.forEach((node) => {
    const renderedNode = renderNode(node, options);
 
    if (renderedNode) {
      form.append(renderedNode);
    }
  });
 
  const actions = createElement("div", { className: `${options.classPrefix}-actions` });
  actions.append(
    createElement("button", {
      className: `${options.classPrefix}-button ${options.classPrefix}-button--primary`,
      text: options.schema.submitLabel ?? "Submit",
      attributes: { type: "submit" }
    }),
    createElement("button", {
      className: `${options.classPrefix}-button`,
      text: options.schema.resetLabel ?? "Reset",
      attributes: { type: "reset" }
    })
  );
  form.append(actions);
 
  return form;
}