UNPKG

react-signal-forms

Version:

A forms library focusing on performance and modular extensibility.

65 lines 2.38 kB
import { signal } from "@preact/signals-react"; import { isArrayField } from "./fields"; export class FieldContext { constructor(field, initialValue) { var _a; this.__blurEffects = []; this.addBlurEffect = (effect) => { this.__blurEffects.push(effect); }; this.peekValue = () => { return this.__valueSignal.peek(); }; this.setValue = (value) => { // TODO: handle computed array field values, which cannot be set. if (!isArrayField(this.__field)) { this.__valueSignal.value = value; } }; this.handleBlur = (event) => { this.__blurEffects.forEach((effect) => effect(event)); }; this.addExtension = (name, fieldExtension, fieldContextProperties) => { this.__extensions[name] = fieldExtension; if (fieldContextProperties != null) { Object.defineProperties(this, fieldContextProperties); } }; this.getExtension = (name) => { return this.__extensions[name]; }; this.__field = field; this.__extensions = {}; this.__valueSignal = signal((_a = initialValue !== null && initialValue !== void 0 ? initialValue : field.defaultValue) !== null && _a !== void 0 ? _a : null); } get name() { return this.__field.name; } get value() { return this.__valueSignal.value; } toJSON() { const entries = Object.entries(Object.getOwnPropertyDescriptors(this)); let proto = Object.getPrototypeOf(this); while (proto != null) { entries.push(...Object.entries(Object.getOwnPropertyDescriptors(proto))); proto = Object.getPrototypeOf(proto); } const jsonObj = entries .filter(([_key, descriptor]) => typeof descriptor.get === "function") .reduce((obj, [key, descriptor]) => { if (descriptor && key[0] !== "_") { try { const val = this[key]; obj[key] = val; } catch (error) { console.error(`Error calling getter ${key}`, error); } } return obj; }, {}); return jsonObj; } } //# sourceMappingURL=fieldContext.js.map