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 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 | 6x 6x 6x 61x 16x 16x 29x 1x 1x 28x 3x 3x 25x 16x 61x 80x 80x 80x 80x 80x 80x 80x 80x 80x 80x 61x 104x 104x 104x 2x 2x 104x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 2x 2x 2x 4x 2x 9x 6x 6x 6x 6x 6x 16x 16x 6x 1x 1x 2x 1x 1x 2x 1x 1x 1x 23x 23x 23x 23x 23x 23x 6x 6x 6x 17x 3x 3x 14x 14x 5x 5x 4x 4x 4x 9x 9x 10x 1x 1x 1x 1x 9x 9x 9x 16x 16x 20x 17x 17x 10x 16x 16x 5x 5x 1x 1x 5x 5x 1x 4x 4x 4x 4x 3x 3x 1x 1x 1x 1x 1x 4x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 61x 22x 22x 61x 61x 11x 11x 11x 10x 1x 1x 2x 2x 50x 61x 61x 61x 61x 61x 61x 61x 61x 41x 61x 61x 61x 61x 61x 61x 61x 61x 41x 41x 41x 41x 65x 61x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 41x 2x 41x 41x 41x 1x 1x 1x 1x 2x 1x 2x 1x 88x 88x 88x 83x 88x 5x 78x 2x 2x 2x 2x 2x 2x 2x 2x 8x 8x 7x 15x 8x 29x 29x 29x 28x 40x 1x 1x 29x | /**
* Coherent.js Form Builder
*
* Utilities for building forms with Coherent.js
*
* @module forms/form-builder
*/
import { render as renderToHTML } from '@coherent.js/core';
/**
* Class applied to each structural slot. Consumers override any subset via
* the `classNames` option; hydrateForm accepts `invalid` and `error` so the
* client writes the same names the server rendered.
*/
export const DEFAULT_CLASS_NAMES = {
/** Wrapper around label, control and error */
field: 'form-field',
label: '',
/** Base class on the control, before any per-field className */
control: '',
/** Added to the control while it has a visible error */
invalid: 'error',
/** The error message element */
error: 'error-message',
submit: 'submit-button'
};
/**
* Attribute names are interpolated into the markup unescaped by
* formatAttributes, so a passthrough has to reject anything that is not a
* plain name — otherwise `{'x onclick=alert(1)': ''}` injects an attribute.
*/
const VALID_ATTRIBUTE_NAME = /^[A-Za-z_:][-A-Za-z0-9_:.]*$/;
/**
* `onclick` and friends are syntactically valid names, and a string value
* renders as an inline handler — script execution from whatever produced the
* field config, and the thing this builder stopped emitting on the form
* itself. Handlers belong in hydration.
*/
const EVENT_HANDLER_NAME = /^on/i;
function safeAttributes(attributes) {
if (!attributes || typeof attributes !== 'object') return {};
const safe = {};
for (const [name, value] of Object.entries(attributes)) {
if (!VALID_ATTRIBUTE_NAME.test(name)) {
console.warn(`[coherent.js/forms] Ignoring invalid attribute name: ${JSON.stringify(name)}`);
continue;
}
if (EVENT_HANDLER_NAME.test(name)) {
console.warn(
`[coherent.js/forms] Ignoring inline event handler "${name}". ` +
'Attach handlers with hydrateForm instead.'
);
continue;
}
safe[name] = value;
}
return safe;
}
/** Join class names, dropping empties so no element carries `class=""`. */
function joinClasses(...names) {
return names.filter(Boolean).join(' ');
}
/**
* Form Builder
* Helps create form components with validation
*/
export class FormBuilder {
constructor(options = {}) {
this.options = {
validateOnChange: true,
validateOnBlur: true,
name: options.name || 'form',
...options
};
this.fields = new Map();
this.groups = new Map();
this.values = {};
this.errors = {};
this.touched = {};
this.initialValues = {};
this.submitHandler = null;
this.errorHandler = null;
this._isSubmitting = false;
}
/**
* Add a field to the form (alias for field)
*/
addField(name, config = {}) {
return this.field(name, config);
}
/**
* Add a field to the form
*/
field(name, config = {}) {
const fieldConfig = {
name,
type: config.type || 'text',
label: config.label || name,
placeholder: config.placeholder || '',
defaultValue: config.defaultValue || '',
validators: config.validators || [],
required: config.required || false,
visible: config.visible !== false,
showWhen: config.showWhen,
...config
};
this.fields.set(name, fieldConfig);
// Set default value
if (config.defaultValue !== undefined) {
this.values[name] = config.defaultValue;
this.initialValues[name] = config.defaultValue;
}
return this;
}
/**
* Remove a field from the form
*/
removeField(name) {
this.fields.delete(name);
delete this.values[name];
delete this.errors[name];
delete this.touched[name];
return this;
}
/**
* Update field configuration
*/
updateField(name, config) {
const field = this.fields.get(name);
Eif (field) {
this.fields.set(name, { ...field, ...config });
}
return this;
}
/**
* Get all fields as array
*/
getFields() {
return Array.from(this.fields.values());
}
/**
* Add a field group
*/
addGroup(name, config = {}) {
this.groups.set(name, {
name,
label: config.label || name,
fields: config.fields || [],
...config
});
// Add fields in the group
Eif (config.fields) {
config.fields.forEach(fieldConfig => {
this.addField(fieldConfig.name, fieldConfig);
});
}
return this;
}
/**
* Get field configuration
*/
getField(name) {
return this.fields.get(name);
}
/**
* Set field value
*/
setValue(name, value) {
this.values[name] = value;
this.touched[name] = true;
const field = this.fields.get(name);
Eif (field && (field.validateOnChange || this.options.validateOnChange)) {
this.validateField(name);
}
}
/**
* Set multiple values
*/
setValues(values) {
Object.assign(this.values, values);
return this;
}
/**
* Get field value
*/
getValue(name) {
return this.values[name];
}
/**
* Get all values
*/
getValues() {
return { ...this.values };
}
/**
* Get field error
*/
getFieldError(name) {
return this.errors[name];
}
/**
* Check if form has errors
*/
hasErrors() {
return Object.keys(this.errors).length > 0;
}
/**
* Clear all errors
*/
clearErrors() {
this.errors = {};
return this;
}
/**
* Check if form is dirty (values changed from initial)
*/
isDirty() {
return Object.keys(this.values).some(key => {
return this.values[key] !== this.initialValues[key];
});
}
/**
* Check if form is valid
*/
isValid() {
const result = this.validate();
return Object.keys(result).length === 0;
}
/**
* Validate a field
*/
validateField(name) {
const field = this.fields.get(name);
Iif (!field) return null;
// Skip validation for hidden fields (support both showWhen and showIf)
const showCondition = field.showWhen || field.showIf;
Iif (showCondition && !showCondition(this.values)) {
delete this.errors[name];
return null;
}
const value = this.values[name];
// Check required
if (field.required && (value === undefined || value === null || value === '')) {
const error = 'This field is required';
this.errors[name] = error;
return error;
}
// Skip further validation if empty and not required
if (!value && !field.required) {
delete this.errors[name];
return null;
}
// Type-based validation
Eif (value) {
if (field.type === 'email') {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(value)) {
const error = 'Please enter a valid email address';
this.errors[name] = error;
return error;
}
} else Iif (field.type === 'url') {
try {
new URL(value);
} catch {
const error = 'Please enter a valid URL';
this.errors[name] = error;
return error;
}
} else Iif (field.type === 'number') {
if (isNaN(Number(value))) {
const error = 'Please enter a valid number';
this.errors[name] = error;
return error;
}
}
}
// Check custom validate function
if (field.validate) {
const error = field.validate(value, this.values);
Eif (error) {
this.errors[name] = error;
return error;
}
}
// Run validators
for (const validator of field.validators || []) {
const error = validator(value, this.values);
if (error) {
this.errors[name] = error;
return error;
}
}
delete this.errors[name];
return null;
}
/**
* Validate all fields
*/
validate() {
const errors = {};
for (const [name] of this.fields) {
// The same predicate buildForm() renders by, so a field that is not on
// the page can never block submission.
if (!this.isFieldVisible(name)) continue;
const error = this.validateField(name);
if (error) {
errors[name] = error;
}
}
this.errors = errors;
return errors;
}
/**
* Set submit handler
*/
onSubmit(handler) {
this.submitHandler = handler;
return this;
}
/**
* Set error handler
*/
onError(handler) {
this.errorHandler = handler;
return this;
}
/**
* Submit the form
*/
async submit() {
const errors = this.validate();
if (Object.keys(errors).length > 0) {
return { success: false, errors };
}
Iif (!this.submitHandler) {
return { success: true, data: this.values };
}
this._isSubmitting = true;
try {
const result = await this.submitHandler(this.values);
this._isSubmitting = false;
return { success: true, data: result };
} catch (error) {
this._isSubmitting = false;
Eif (this.errorHandler) {
this.errorHandler(error);
}
return { success: false, error };
}
}
/**
* Serialize form data
*/
serialize() {
return { ...this.values };
}
/**
* Convert form to HTML string
*/
toHTML(options = {}) {
// Delegates to buildForm() so there is one source of truth. The previous
// hand-rolled string builder dropped action, method and every field
// attribute beyond type/name/id, and interpolated values unescaped.
return renderToHTML(this.buildForm(options));
}
/**
* Mark field as touched
*/
touch(name) {
this.touched[name] = true;
}
/**
* Build input component with validation metadata for hydration
*/
buildInput(name, classNames = this.resolveClassNames()) {
const field = this.fields.get(name);
Iif (!field) return null;
const value = this.values[name] || '';
const error = this.errors[name];
const isTouched = this.touched[name];
// Build validator names string for data-validators attribute
const validatorNames = field.validators
.map(v => {
if (typeof v === 'function') return v.name || 'custom';
if (typeof v === 'string') return v;
return null;
})
.filter(Boolean)
.join(',');
const controlClass = joinClasses(
classNames.control,
field.className,
error && isTouched ? classNames.invalid : null
);
const inputProps = {
// Spread first: name, id, type and the aria-* pair below are the
// builder's own invariants, and hydration keys off them.
...safeAttributes(field.attributes),
type: field.type,
name: field.name,
id: field.name,
value: value,
'aria-invalid': error ? 'true' : 'false',
'aria-describedby': error ? `${name}-error` : undefined
};
Iif (field.placeholder) inputProps.placeholder = field.placeholder;
if (controlClass) inputProps.className = controlClass;
if (field.disabled) inputProps.disabled = true;
if (field.readonly) inputProps.readonly = true;
// Add validation metadata for client-side hydration
if (field.required) {
inputProps.required = true;
inputProps['data-required'] = 'true';
}
Iif (validatorNames) {
inputProps['data-validators'] = validatorNames;
}
// Note: Event handlers are attached during hydration, not inline
// This enables progressive enhancement and CSP compliance
// textarea and select are elements, not input types. `type="textarea"` is
// not valid HTML — browsers render it as a single-line text box.
if (field.type === 'textarea' || field.type === 'select') {
const { type: _type, value: _value, ...rest } = inputProps;
const props = { ...rest };
if (field.type === 'textarea') {
return { textarea: { ...props, text: String(value) } };
}
const { placeholder: _placeholder, ...selectProps } = props;
return {
select: {
...selectProps,
children: (field.options ?? []).map(option => {
const { value: optionValue, label = optionValue } =
typeof option === 'object' && option !== null ? option : { value: option };
return {
option: {
value: optionValue,
selected: String(optionValue) === String(value) || undefined,
text: String(label)
}
};
})
}
};
}
return {
input: inputProps
};
}
/**
* Build label component
*/
buildLabel(name, classNames = this.resolveClassNames()) {
const field = this.fields.get(name);
Iif (!field) return null;
const props = { for: field.name, text: field.label };
Iif (classNames.label) props.className = classNames.label;
return { label: props };
}
/**
* Build error component
*/
buildError(name, classNames = this.resolveClassNames()) {
const error = this.errors[name];
const isTouched = this.touched[name];
Eif (!error || !isTouched) return null;
const props = { id: `${name}-error`, role: 'alert', text: error };
if (classNames.error) props.className = classNames.error;
return { div: props };
}
/**
* Merge configured class names over the defaults
*/
resolveClassNames(overrides = {}) {
return { ...DEFAULT_CLASS_NAMES, ...this.options.classNames, ...overrides };
}
/**
* Build complete field component
*/
buildField(name, classNames = this.resolveClassNames()) {
const field = this.fields.get(name);
Iif (!field) return null;
const children = [
this.buildLabel(name, classNames),
this.buildInput(name, classNames)
];
const error = this.buildError(name, classNames);
Iif (error) {
children.push(error);
}
// data-field is the structural hook hydrateForm uses to find the wrapper,
// so classes stay entirely the consumer's to choose.
const props = { 'data-field': name, children };
Eif (classNames.field) props.className = classNames.field;
return { div: props };
}
/**
* Build entire form
*/
buildForm(options = {}) {
const settings = { ...this.options, ...options };
const classNames = this.resolveClassNames(options.classNames);
const fields = [];
for (const [name] of this.fields) {
// validate() has always skipped fields hidden by showWhen/showIf; render
// agreed with it only by accident, because nothing was ever hidden.
if (!this.isFieldVisible(name)) continue;
fields.push(this.buildField(name, classNames));
}
Eif (settings.submitButton !== false) {
const button = { type: 'submit', text: settings.submitText || 'Submit' };
Eif (classNames.submit) button.className = classNames.submit;
fields.push({ button });
}
const form = {};
if (settings.action) form.action = settings.action;
if (settings.method) form.method = settings.method;
Eif (settings.name) form.name = settings.name;
Iif (settings.id) form.id = settings.id;
if (settings.className) form.className = settings.className;
Iif (settings.enctype) form.enctype = settings.enctype;
// Plain HTML by default: the form posts to `action` and the browser runs
// its own validation with JavaScript off. hydrateForm binds its own submit
// listener, so it never needed the inline handler this used to emit — and
// an inline handler breaks under a strict CSP besides.
if (settings.enhance) {
form.onsubmit = typeof settings.enhance === 'string'
? settings.enhance
: 'handleSubmit(event)';
}
if (settings.novalidate === true) form.novalidate = true;
form.children = fields;
return { form };
}
/**
* Set the form action URL
*/
setAction(action) {
this.options.action = action;
return this;
}
/**
* Set the form submission method
*/
setMethod(method) {
this.options.method = method;
return this;
}
/**
* Build the form component (alias for buildForm)
*/
build(options = {}) {
return this.buildForm(options);
}
/**
* Render the form to a component (alias for buildForm)
*/
render(options = {}) {
return this.buildForm(options);
}
/**
* Check if form is currently submitting
*/
isSubmitting() {
return this._isSubmitting;
}
/**
* Get a field group
*/
getGroup(name) {
return this.groups.get(name);
}
/**
* Check if a field is visible
*/
isFieldVisible(name) {
const field = this.fields.get(name);
Iif (!field) return false;
// visible:false wins outright — a showWhen that happens to return true
// must not resurrect a field the caller switched off.
if (field.visible === false) return false;
// Support both showWhen and showIf
const showCondition = field.showWhen || field.showIf;
if (showCondition) {
return showCondition(this.values);
}
return true;
}
/**
* Reset form
*/
reset() {
// Reset to initial values or empty strings
this.values = {};
for (const [name, field] of this.fields) {
if (field.defaultValue !== undefined) {
this.values[name] = field.defaultValue;
} else E{
this.values[name] = '';
}
}
this.errors = {};
this.touched = {};
this._isSubmitting = false;
return this;
}
}
/**
* Create a form builder
*/
export function createFormBuilder(options = {}) {
const form = new FormBuilder(options);
// Add fields if provided
if (options.fields) {
options.fields.forEach(fieldConfig => {
form.addField(fieldConfig.name, fieldConfig);
});
}
return form;
}
/**
* Build a form component from a configuration object.
*
* Returns a renderable component, as the type declarations have always said.
* It previously returned the FormBuilder itself, so `render(buildForm(...))`
* threw "Invalid component structure". Use createFormBuilder() when you want
* the builder.
*
* @param {Object} config - Form configuration; `fields` may be an array of
* field objects or an object keyed by field name. Remaining keys (action,
* method, name, className, enctype, submitText) configure the form element.
* @returns {Object} A Coherent.js component
*/
export function buildForm(config = {}) {
const { fields = [], ...options } = Array.isArray(config) ? { fields: config } : config;
const builder = new FormBuilder(options);
if (Array.isArray(fields)) {
for (const field of fields) {
Eif (field && field.name) builder.field(field.name, field);
}
} else {
for (const [name, field] of Object.entries(fields)) {
builder.field(name, field);
}
}
return builder.buildForm(options);
}
export default {
FormBuilder,
createFormBuilder,
buildForm
};
|