@react-form-builder/core
Version:
React hook form alternative.
5,122 lines • 152 kB
JavaScript
var $n = Object.defineProperty;
var Mn = (r, t, e) => t in r ? $n(r, t, { enumerable: !0, configurable: !0, writable: !0, value: e }) : r[t] = e;
var a = (r, t, e) => (Mn(r, typeof t != "symbol" ? t + "" : t, e), e), ae = (r, t, e) => {
if (!t.has(r))
throw TypeError("Cannot " + e);
};
var h = (r, t, e) => (ae(r, t, "read from private field"), e ? e.call(r) : t.get(r)), v = (r, t, e) => {
if (t.has(r))
throw TypeError("Cannot add the same private member more than once");
t instanceof WeakSet ? t.add(r) : t.set(r, e);
}, E = (r, t, e, n) => (ae(r, t, "write to private field"), n ? n.call(r, e) : t.set(r, e), e);
var C = (r, t, e) => (ae(r, t, "access private method"), e);
import { jsx as p, Fragment as zt, jsxs as ne } from "@emotion/react/jsx-runtime";
import { css as pt, cx as ft } from "@emotion/css";
import * as Ln from "react";
import { createContext as In, useContext as Vr, useMemo as L, useEffect as K, useState as Ve, useCallback as Ee, createElement as De, Fragment as Bn, useRef as Wn, useImperativeHandle as Kn, forwardRef as qn } from "react";
import { assign as U, merge as Qe, camelCase as Hn, isEmpty as Er, isArray as Jn, clone as le, startCase as Dr, reduce as Un, isUndefined as Pr, isNull as Zn, isObject as ye, upperFirst as _n } from "lodash-es";
import { makeAutoObservable as H, reaction as Pe, makeObservable as Sr, observable as P, autorun as Fr, untracked as Tr, runInAction as Rr, configure as Gn } from "mobx";
import { observer as Or } from "mobx-react";
import { CacheProvider as Qn } from "@emotion/react";
import Xe from "@emotion/cache";
import Xn from "stylis-plugin-rtl";
import { Subject as Yn, debounceTime as to, map as Ye, switchMap as eo } from "rxjs";
import { FluentResource as kr, FluentBundle as xr } from "@fluent/bundle";
import { z as N } from "zod";
const pa = () => (Math.random() * 1e18).toString(36).slice(0, 5).toUpperCase() + "";
function ro(r, t) {
return r.reduce((e, n, o, i) => {
var s;
return (e[s = t(n, o, i)] || (e[s] = [])).push(n), e;
}, {});
}
const Ar = ".", Se = "__DOT__";
function Nr(r) {
return r.replace(new RegExp(`\\${Se}`, "g"), Ar);
}
function zr(r) {
return r.replace(new RegExp(`\\${Ar}`, "g"), Se);
}
const D = (r) => r.replace(new RegExp(" ", "g"), "_"), no = (r) => typeof r == "string" || typeof r == "number" || r instanceof Date ? !0 : typeof (r == null ? void 0 : r.value) < "u", jr = (r, t = "") => {
const e = {};
for (const [n, o] of Object.entries(r)) {
const i = t ? `${t}${Se}${n}` : n;
no(o) ? e[D(i)] = o : typeof o == "boolean" ? e[D(i)] = o ? "true" : "false" : typeof o == "object" && o !== null && Object.assign(e, jr(o, i));
}
return e;
}, tr = Symbol("key");
function $r(r, t, e, n = {}) {
const o = Object.keys(n).map((i) => `${i}=${n[i]}`).join("_");
return `${r}_${t}_${e ? `${e}_` : ""}${o}`;
}
function Mr(r, t, e = {}) {
return $r("autorun", r, t, e);
}
function z(r, t = {}) {
return $r("observable", r, void 0, t);
}
let er = 0;
function Lr(r) {
r[tr] || (++er, r[tr] = `actionData_${er}`);
}
function Ir(r) {
var e;
const t = r.events;
t && Object.values(t).forEach((n) => n.forEach(Lr)), (e = r.children) == null || e.forEach(Ir);
}
function mt(r) {
return (r == null ? void 0 : r.computeType) === "function";
}
function Fe(r) {
return (r == null ? void 0 : r.computeType) === "localization";
}
function Br(r) {
return mt(r) || Fe(r);
}
function ct(r) {
return r.dataKey ?? r.key;
}
class O {
/**
* Creates the component settings.
* @param key the React component key.
* @param type the component type of the form viewer.
*/
constructor(t, e) {
/**
* The React component key.
*/
a(this, "key", "");
/**
* The component data key.
*/
a(this, "dataKey");
/**
* The component type of the form viewer.
*/
a(this, "type", "");
/**
* The component properties.
*/
a(this, "props", {});
/**
* The component CSS styles.
*/
a(this, "css");
/**
* The component wrapper CSS styles.
*/
a(this, "wrapperCss");
/**
* The set of event handlers.
*/
a(this, "events");
/**
* The array of child components.
*/
a(this, "children");
/**
* The component value validation settings.
*/
a(this, "schema");
/**
* The set of arbitrary HTML attributes added to the component.
*/
a(this, "htmlAttributes");
/**
* The tooltip settings.
*/
a(this, "tooltipProps");
/**
* The name of the occupied component property in the parent component.
*/
a(this, "slot");
/**
* The condition for binding a child element to a parent element.
*/
a(this, "slotCondition");
/**
* The expression or function to conditionally render a component.
*/
a(this, "renderWhen");
this.key = t, this.type = e, H(this, void 0, { name: z("ComponentStore", { key: t }) });
}
/**
* Correctly creates the {@link ComponentStore} from deserialized data.
* @param value the deserialized data.
* @returns the component Store.
*/
static createFromObject(t) {
const e = U(new O(t.key, t.type), t);
return Ir(e), e;
}
/**
* Adds the event handler for component.
* @param store the target {@link ComponentStore}.
* @param eventName the target event name.
* @param data the {@link ActionData}.
*/
static addEventHandler(t, e, n) {
var o;
Lr(n), t.events ?? (t.events = {}), (o = t.events)[e] ?? (o[e] = []), t.events[e].push(n);
}
}
const oo = {
/**
* @inheritDoc
*/
get get() {
return {};
},
/**
* @inheritDoc
*/
get wrapperClassName() {
return "";
},
/**
* @inheritDoc
*/
get propsWithoutChildren() {
return {};
},
/**
* @inheritDoc
*/
get ownProps() {
return {};
},
/**
* @inheritDoc
*/
onDidMount() {
},
/**
* @inheritDoc
*/
onWillUnmount() {
},
/**
* @inheritDoc
*/
get isReadOnly() {
return !1;
},
/**
* @inheritDoc
*/
get isDisabled() {
return !1;
}
};
function io(r) {
return () => {
const t = Vr(r);
if (!t)
throw new Error(`The context ${r.displayName} was not found!`);
return t;
};
}
function so(r) {
return r.Provider;
}
function yt(r, t = null) {
const e = In(t);
e.displayName = r;
const n = io(e), o = so(e);
return [n, o, e];
}
class rr {
constructor() {
a(this, "handlers", []);
}
/**
* Adds a handler to the list of subscribers.
* @param handler the handler function to be added.
*/
subscribe(t) {
this.handlers.push(t);
}
/**
* Removes the specified event handler from the list of handlers.
* @param handler the event handler to remove.
*/
unsubscribe(t) {
this.handlers = this.handlers.filter((e) => e !== t);
}
/**
* Returns true if the object has subscribers, false otherwise.
* @returns true if the object has handlers registered for events, otherwise returns false.
*/
get isSubscribed() {
return this.handlers.length > 0;
}
/**
* Invokes the event by calling all registered event handlers.
* @param sender the sender of the event.
* @param eventArgs the event arguments.
*/
invoke(t, e) {
this.handlers.slice().forEach((n) => n(t, e));
}
/**
* Dispose method to release all handlers.
*/
dispose() {
this.handlers = [];
}
}
function Wt(r, t) {
var e;
t(r), (e = r.children) == null || e.forEach((n) => Wt(n, t));
}
function ao(r, t, e = 0) {
if (r === t)
return e;
if (r.children) {
e = e + 1;
for (const n of r.children) {
const o = ao(n, t, e);
if (o)
return o;
}
}
}
let lo = 0;
function co(r) {
return `${r}_${++lo}`;
}
function nr(r, t) {
let e = 1;
const n = Hn(r.type), o = () => `${n}${e}`;
for (; t.has(o()); )
e++;
return r.key = o(), r.key;
}
class uo {
/**
* Constructs a new instance of the ComponentKeyChangedEventArgs class.
* @param oldKey the old key.
* @param newKey the new key.
*/
constructor(t, e) {
this.oldKey = t, this.newKey = e;
}
}
class ho {
constructor() {
/**
* An event that occurs after a component key change.
*/
a(this, "onAfterKeyChanged", new rr());
/**
* An event that occurs before a component is removed from the component tree.
*/
a(this, "onBeforeDelete", new rr());
}
/**
* Unsubscribe from all events.
*/
dispose() {
this.onAfterKeyChanged.dispose(), this.onBeforeDelete.dispose();
}
}
const po = (r) => {
const t = {};
return r.allComponentFields.forEach(({ dataKey: e }) => {
t[e] = r.data[e] ?? "";
}), t;
};
var Ct, j, Y;
class fo {
/**
* Constructor.
* @param componentStore the component settings.
* @param model the component metadata for the form viewer.
* @param childFactory the factory function that creates {@link ComponentData} instance.
* @param getFormValidationResult the function that returns a form validation results.
*/
constructor(t, e, n, o) {
v(this, Ct, void 0);
v(this, j, void 0);
v(this, Y, void 0);
a(this, "_state", {});
/**
* The unique identifier.
*/
a(this, "id");
/**
* The component settings.
*/
a(this, "store");
/**
* The component metadata.
*/
a(this, "model");
/**
* The field with the form data.
*/
a(this, "field");
/**
* The parent node in the component data tree.
*/
a(this, "parent");
/**
* The child nodes in the component data tree.
*/
a(this, "children", []);
/**
* User defined properties of the React component.
*/
a(this, "userDefinedProps");
/**
* If true, then validation is in progress.
*/
a(this, "validating", !1);
/**
* Specifies the root component for the data in the component tree. **Internal use only.**
*/
a(this, "dataRootProvider");
/**
* Specifies the index in the array if the component is in the component array.
* This is not an index in a parent-child structure.
*/
a(this, "index");
/**
* The state of the component. **Internal use only.
*/
a(this, "componentState", oo);
/**
* The function for getting initial data.
*/
a(this, "getInitialData");
var s;
this.store = t, this.model = e, this.id = co(this.model.type), E(this, Y, o), (s = t.children) == null || s.forEach((l) => {
n(l).setParent(this);
}), H(this, void 0, { name: z("ComponentData", { key: t.key }) }), E(this, Ct, [(() => Pe(() => this.key, (l, c) => {
this.invokeOnAfterKeyChanged(this, new uo(c, l));
}))()]);
}
/**
* Sets the new parent for this node.
* @param newParent the new parent.
*/
setParent(t) {
var e;
(e = this.parent) == null || e.removeChild(this), t.addChild(this), this.parent = t;
}
/**
* Inserts the given node after this node.
* @param inserted the node to insert.
*/
insertAfterMe(t) {
this.insert(t, "after");
}
/**
* Inserts the given node before this node.
* @param inserted the node to insert.
*/
insertBeforeMe(t) {
this.insert(t, "before");
}
/**
* @inheritDoc
*/
get state() {
return this._state;
}
/**
* @returns the root component for the data in the component tree.
*/
get dataRoot() {
var t, e;
return ((t = this.dataRootProvider) == null ? void 0 : t.dataRoot) ?? ((e = this.parent) == null ? void 0 : e.dataRoot) ?? this;
}
/**
* @returns the initial data.
*/
get initialData() {
var t, e;
return (e = (t = this.dataRoot).getInitialData) == null ? void 0 : e.call(t);
}
/**
* @returns the key of this node (same as the key of the ComponentStore).
*/
get key() {
return this.store.key;
}
/**
* @returns the ComponentDataEvents object.
*/
get events() {
return h(this, j) || E(this, j, new ho()), h(this, j);
}
/**
* Find the node with the given key.
* @param key the key to find.
* @returns the node or undefined if not found.
*/
findByKey(t) {
if (this.key === t)
return this;
for (let e = 0; e < this.children.length; e++) {
const o = this.children[e].findByKey(t);
if (o)
return o;
}
}
/**
* Assigns unique keys to the items in the tree.
* @param root the root of the tree to unify keys. Defaults to the root of this tree.
* @returns the map of new keys to old keys.
*/
unifyKeys(t) {
const e = /* @__PURE__ */ new Map(), n = [];
return Wt(t, ({ key: o }) => {
n.push(o);
}), Wt(this, (o) => {
const i = nr(o.store, new Set(n));
e.set(i, o.key), n.push(i);
}), e;
}
/**
* Assigns unique keys to the items in the tree.
*/
unifyTree() {
const t = /* @__PURE__ */ new Map();
Wt(this, ({ key: o, store: i }) => {
const s = t.get(o) ?? /* @__PURE__ */ new Set();
s.add(i), t.set(o, s);
});
const n = new Set(t.keys());
t.forEach((o, i) => {
if (o.size <= 1)
return;
Array.from(o).slice(1).forEach((l) => {
const c = nr(l, n);
n.add(c);
});
});
}
/**
* @returns all the fields in the tree as a map. Starts from this node.
*/
get fields() {
const t = this.collectAllFields(/* @__PURE__ */ new Map()), e = /* @__PURE__ */ new Map();
return t.forEach((n, o) => {
e.set(ct(o.store), n);
}), e;
}
/**
* @returns an array of all component fields, including non-unique data keys.
*/
get allComponentFields() {
const t = this.collectAllFields(/* @__PURE__ */ new Map()), e = [];
return t.forEach((n, o) => {
e.push({
dataKey: ct(o.store),
field: n
});
}), e;
}
/**
* @returns an array of all fields, including non-unique data keys.
*/
get allFields() {
return this.allComponentFields.map((t) => t.field);
}
/**
* @returns an array of all children components.
*/
get allChildren() {
return this.collectAllChildren([]);
}
/**
* Deletes this node from the tree.
*/
delete() {
var e;
(e = this.parent) == null || e.removeChild(this);
const t = this.collectAllNodesAsArray([]);
this.invokeOnBeforeDeleted(t), this.disposeNodes(t);
}
/**
* @inheritDoc
*/
get data() {
const t = {};
for (const { dataKey: e, field: n } of this.allComponentFields)
if (n.storeDataInParentForm) {
const o = n.value || {};
Object.keys(o).forEach((i) => t[i] = o[i]);
} else
t[e] = n.value;
return t;
}
/**
* @returns the object to read and modify parent data (available for array elements).
*/
get parentData() {
var e;
if (typeof this.nearestIndex == "number")
return ((e = this.parent) == null ? void 0 : e.data) ?? this.rootData;
}
/**
* @returns the object to read and modify root form data.
*/
get rootData() {
return this.root.data;
}
/**
* @returns all the form data that is of the FluentVariable type.
* Additionally, the keys of the returned object are converted to the snake case.
*/
get fluentData() {
const t = po(this);
return jr(t);
}
/**
* @inheritDoc
*/
get errors() {
const t = {};
for (const { dataKey: e, field: n } of this.allComponentFields) {
n.error && (t[e] = n.error);
const o = n.errors;
o && (Array.isArray(o) ? t[e] = o : (n.storeDataInParentForm && Object.keys(o).forEach((i) => t[i] = o[i]), !n.storeDataInParentForm && Object.keys(o).length > 0 && (t[e] = o)));
}
return t;
}
/**
* @inheritDoc
*/
set errors(t) {
this.allComponentFields.forEach((e) => {
const n = t[e.dataKey];
e.field.setError(n);
});
}
/**
* @inheritDoc
*/
get hasErrors() {
return Object.keys(this.errors).length > 0;
}
/**
* @inheritDoc
*/
setAllErrors(t) {
this.allFields.forEach((e) => e.error = t);
}
/**
* @inheritDoc
*/
async validate() {
return await this.validateForm(), this.errors;
}
/**
* @inheritDoc
*/
async getValidationResult() {
var o;
let t;
const e = async ({ dataKey: i, field: s }) => {
const l = await s.getValidationResult();
if (Er(l))
return;
t ?? (t = {});
let c = t;
if (!s.storeDataInParentForm) {
const d = Jn(l) ? [] : {};
t[i] ?? (t[i] = d), c = t[i];
}
Qe(c, l);
};
await Promise.allSettled(this.allComponentFields.map(e));
const n = await ((o = h(this, Y)) == null ? void 0 : o.call(this));
return n == null || n.forEach((i) => {
t ?? (t = {}), Qe(t, i);
}), t;
}
/**
* @inheritDoc
*/
get isValidating() {
return this.validating;
}
/**
* @inheritDoc
*/
reset() {
this.allFields.forEach((t) => t.reset());
}
/**
* @inheritDoc
*/
clear() {
this.allFields.forEach((t) => t.clear());
}
/**
* Dispose method that releases resources used by the object.
* It disposes the field and all the children objects.
*/
dispose() {
const t = this.collectAllNodesAsArray([]);
this.disposeNodes(t);
}
/**
* @returns true if it has no parent {@link ComponentData}, false otherwise.
*/
get isRoot() {
return !this.parent;
}
/**
* @returns the root of the component tree.
*/
get root() {
return this.parent ? this.parent.root : this;
}
/**
* @returns the index in the array if the component is in the component array
* (looks for the nearest index in the component hierarchy).
*/
get nearestIndex() {
var t;
return typeof this.index < "u" ? this.index : (t = this.parent) == null ? void 0 : t.nearestIndex;
}
async validateForm() {
var t;
this.validating = !0;
try {
await Promise.allSettled([...this.allFields].map((o) => o.validate()));
const e = await ((t = h(this, Y)) == null ? void 0 : t.call(this));
if (!(e != null && e.length))
return;
const n = this.allComponentFields;
e.forEach((o) => {
o && n.forEach(({ field: i, dataKey: s }) => {
if (o[s])
return i.setError(o[s]);
if (i.storeDataInParentForm)
return i.setError(o);
});
});
} finally {
this.validating = !1;
}
}
insert(t, e) {
var c, d;
const n = e === "before" ? 0 : 1;
if (!this.parent)
throw new Error(`Cannot insert without parent. Key = ${this.key}`);
(c = t.parent) == null || c.removeChild(t), t.parent = this.parent;
const o = this.parent.children, i = o.indexOf(this);
if (i < 0)
throw new Error(`Cannot insert not existing element into ComponentData. Key = ${this.key}`);
o.splice(i + n, 0, t), (d = this.parent.store).children ?? (d.children = []);
const s = this.parent.store.children, l = s.indexOf(this.store);
if (l < 0)
throw new Error(`Cannot insert not existing element into ComponentStore. Key = ${this.key}`);
s.splice(l + n, 0, t.store), t.store.slot = this.store.slot, t.store.slotCondition = this.store.slotCondition;
}
/**
* Disposes the nodes by calling the disposers, disposing the field,
* and resetting the parent and children properties to undefined and an empty array, respectively.
* @param nodes the array of ComponentData objects representing the nodes to dispose.
*/
disposeNodes(t) {
t.forEach((e) => {
var n, o;
(n = h(e, j)) == null || n.dispose(), h(e, Ct).forEach((i) => i()), (o = e.field) == null || o.dispose(), e.parent = void 0, e.children = [];
});
}
collectAllNodesAsArray(t) {
t.push(this);
for (let e = 0; e < this.children.length; e++)
this.children[e].collectAllNodesAsArray(t);
return t;
}
collectAllFields(t) {
var e;
if (this.field && t.set(this, this.field), ((e = this.field) == null ? void 0 : e.fieldType) === "repeater")
return t;
for (let n = 0; n < this.children.length; n++)
this.children[n].collectAllFields(t);
return t;
}
collectAllChildren(t) {
t.push(this);
for (let e = 0; e < this.children.length; e++)
this.children[e].collectAllChildren(t);
return t;
}
addChild(t) {
var e;
this.children.indexOf(t) < 0 && this.children.push(t), (e = this.store).children ?? (e.children = []), this.store.children.indexOf(t.store) < 0 && this.store.children.push(t.store);
}
removeChild(t) {
var o;
const e = this.children.indexOf(t);
e > -1 && this.children.splice(e, 1), (o = this.store).children ?? (o.children = []);
const n = this.store.children.indexOf(t.store);
n > -1 && this.store.children.splice(n, 1);
}
invokeOnAfterKeyChanged(t, e) {
var n, o;
(n = h(this, j)) != null && n.onAfterKeyChanged.isSubscribed && h(this, j).onAfterKeyChanged.invoke(t, e), (o = this.parent) == null || o.invokeOnAfterKeyChanged(t, e);
}
invokeOnBeforeDeleted(t) {
var e, n;
(e = h(this, j)) != null && e.onBeforeDelete.isSubscribed && t.forEach((o) => {
var i;
return (i = h(this, j)) == null ? void 0 : i.onBeforeDelete.invoke(o, void 0);
}), (n = this.parent) == null || n.invokeOnBeforeDeleted(t);
}
}
Ct = new WeakMap(), j = new WeakMap(), Y = new WeakMap();
const [
/**
* @returns the instance of the ComponentData of the currently rendered component.
*/
Z,
/**
* Context provider for the useComponentData hook. **Internal use only.**
*/
Wr
] = yt("ComponentDataContext"), Kr = () => {
const { id: r } = Z();
return L(() => ({
"aria-labelledby": `${r}-label`,
"aria-errormessage": `${r}-error`
}), [r]);
}, mo = () => {
const { field: r } = Z(), t = !!(r != null && r.error);
return L(() => ({ "aria-invalid": t }), [t]);
}, fa = () => {
const r = mo(), t = Kr();
return L(() => ({
...t,
...r
}), [t, r]);
};
var Vt;
class M {
/**
* Creates component metadata for the form viewer.
* @param component the React component.
* @param name the component name.
* @param actionsInitializer the function to initialize actions in the component.
* @param valued the name of the component property where the component value is stored.
* @param valueType the type of the component value.
* @param defaultProps the component's default property values.
* @param css the component's CSS values.
* @param wrapperCss the component's wrapper CSS values.
* @param typeName the component type name.
* @param kind the component kind.
* @param readOnly the name of the component property that stores the read-only flag.
* @param propsBindingTypes the component property binding types.
* @param uncontrolledValue the value for the uncontrolled (undefined) state.
* @param disabled the name of the component property that stores the disabled flag.
* @template T the type of React component properties.
*/
constructor(t, e, n, o, i, s, l, c, d, u = "component", g, y = {}, b, W) {
v(this, Vt, void 0);
/**
* The React component.
*/
a(this, "component");
this.actionsInitializer = n, this.valued = o, this.valueType = i, this.defaultProps = s, this.css = l, this.wrapperCss = c, this.typeName = d, this.kind = u, this.readOnly = g, this.propsBindingTypes = y, this.uncontrolledValue = b, this.disabled = W, this.component = Or(t), this.component.displayName = t.displayName || t.name, E(this, Vt, e);
}
/**
* @returns the component name, or type if there is no component name.
*/
get name() {
return h(this, Vt) ?? this.type;
}
/**
* @returns the component type name.
*/
get type() {
return this.typeName || this.component.displayName || this.component.name;
}
}
Vt = new WeakMap();
var _ = /* @__PURE__ */ ((r) => (r.LTR = "ltr", r.RTL = "rtl", r))(_ || {});
const [
/**
* **Internal use only.**
*/
yo,
/**
* **Internal use only.**
*/
go
] = yt("RepeaterPropsContext"), Te = (r) => {
const { className: t } = yo();
return /* @__PURE__ */ p("div", { className: t, children: r.children });
};
Te.displayName = "RepeaterItem";
const vo = new M(Te, "RepeaterItem"), [
/**
* @returns the {@link BuilderMode} builder mode value.
*/
wo,
/**
* The BuilderMode context provider.
*/
ma
] = yt("BuilderModeContext", "viewer"), [
/**
* **Internal use only.**
*/
I,
/**
* **Internal use only.**
*/
Re,
/**
* **Internal use only.**
*/
bo
] = yt("StoreContext");
class jt {
/**
* Creates metadata for a React component property.
* @param key the property name.
* @param name the human-readable property name.
*/
constructor(t, e) {
/**
* The component property key.
*/
a(this, "key");
/**
* The component property name.
*/
a(this, "name");
/**
* The name of the component's property editor.
*/
a(this, "editor");
/**
* The hint for the component property.
*/
a(this, "hint");
/**
* True if the property value can be localized, false otherwise.
*/
a(this, "localizable", !1);
/**
* True if the property value is bound to form data, false otherwise.
*/
a(this, "valued", !1);
/**
* True if the property value controls a read-only flag, false otherwise.
*/
a(this, "readOnly", !1);
/**
* True if the property value controls a disabled flag, false otherwise.
*/
a(this, "disabled", !1);
/**
* Additional properties for the component property editor.
*/
a(this, "editorProps");
/**
* The default property value.
*/
a(this, "default");
/**
* The property value for the uncontrolled state.
*/
a(this, "uncontrolledValue");
/**
* The data type for the value of the property.
*/
a(this, "type");
/**
* True if the component property is required, false otherwise.
*/
a(this, "required", !1);
/**
* The function for validating the property value.
*/
a(this, "validator");
/**
* Message and/or error code for the validation function.
*/
a(this, "errorMap");
/**
* True if the property value can be a calculated property, false otherwise.
*/
a(this, "calculable", !0);
/**
* A function that returns a string containing the source code of the function to bind child components.
* @param props the properties of the component, which are available only inside Form Builder Designer.
*/
a(this, "slotConditionBuilder");
/**
* The component property binding type.
*/
a(this, "bindingType");
this.key = t, this.name = e;
}
/**
* @returns the metadata clone.
*/
clone() {
return Object.create(Object.getPrototypeOf(this), Object.getOwnPropertyDescriptors(this));
}
}
class qr extends jt {
constructor() {
super(...arguments);
/**
* The function that checks whether a child component can be inserted into a parent component.
*/
a(this, "insertPredicate");
}
}
class Co extends jt {
}
class Vo extends jt {
}
class Hr extends jt {
constructor() {
super(...arguments);
/**
* Possible values for the property.
*/
a(this, "data");
}
}
const ya = (r) => r instanceof Hr;
class Eo extends jt {
}
const ga = "HH:mm:ss", Do = {
Property: Hr,
Container: qr,
Event: Co,
Module: Vo,
Style: Eo
};
class Po {
constructor() {
/**
* Type of component property description in the form builder.
*/
a(this, "annotationType", "Module");
/**
* Flag if true, the property name will be automatically converted in the designer from a camel case string to a human-readable string.
*/
a(this, "autoName", !0);
}
}
class Jr {
constructor() {
/**
* Partial metadata for a component property.
*/
a(this, "annotation");
/**
* Options for building an annotation.
*/
a(this, "options", new Po());
}
/**
* @returns the main component property that is used as form data and for validation rules.
*/
get valued() {
return this.setup({ valued: !0 });
}
/**
* Sets the value for the property that prevents uncontrolled state.
* @param uncontrolledValue the value for the uncontrolled state.
* @returns the modified instance of the builder.
*/
uncontrolledValue(t) {
return this.setup({ uncontrolledValue: t });
}
/**
* @returns the component property that can be localized.
*/
get localize() {
return this.setup({ localizable: !0 });
}
/**
* @returns the non-localizable component property.
*/
get notLocalize() {
return this.setup({ localizable: !1 });
}
/**
* Specifies the name of the component property.
* @param name the property name.
* @returns the modified instance of the builder.
*/
named(t) {
return this.setup({ name: t });
}
/**
* Adds the hint to the property name of the component.
* @param hint the hint.
* @returns the modified instance of the builder.
*/
hinted(t) {
return this.setup({ hint: t });
}
/**
* Marks the component property as calculable.
* @param calculable true if the property is calculable.
* @returns the modified instance of the builder.
*/
calculable(t) {
return this.setup({ calculable: t });
}
/**
* Modifies the component property metadata builder with custom options.
* @param options the custom options.
* @returns the modified instance of the builder.
*/
setup(t) {
const { annotationType: e, autoName: n, ...o } = t, i = this.clone();
return i.options.annotationType = e ?? i.options.annotationType, i.options.autoName = n ?? i.options.autoName, U(i.annotation, o), i;
}
/**
* Clones the instance of the builder.
* @returns the cloned instance of the builder.
*/
clone() {
const t = le(this);
return t.options = le(this.options), t.annotation = le(this.annotation), t.annotation ?? (t.annotation = {}), t;
}
/**
* Creates component property metadata for the form builder.
* @param key the unique key of the component property.
* @returns the instance of the component property metadata for the form builder.
*/
build(t) {
const e = this.getName(t), n = new Do[this.options.annotationType](t, e);
return U(n, this.annotation), n;
}
/**
* Sets custom properties for the component's property editor.
* @param props the custom properties
* @returns the modified instance of the builder.
*/
withEditorProps(t) {
const e = this.clone();
return U(e.annotation, { editorProps: t }), e;
}
/**
* Hides the component property editor.
* @returns the modified instance of the builder.
*/
hideEditor() {
const t = this.clone();
return U(t.annotation, { editor: void 0 }), t;
}
/**
* Returns the annotation name.
* @param key the property name
* @returns the annotation name.
*/
getName(t) {
return this.annotation.name ?? (this.options.autoName ? Dr(t) : t);
}
}
class Oe extends Jr {
/**
* Marks the component property as required.
* @returns the modified instance of the builder.
*/
get required() {
return this.setup({ required: !0 });
}
/**
* Sets the default value for the component property.
* @param value the default value.
* @returns the modified instance of the builder.
*/
default(t) {
return this.setup({ default: t });
}
/**
* Modifies the component property metadata builder with validation properties.
* @param validator the validation function.
* @param errorMap the validation error settings.
* @returns the modified instance of the builder.
*/
validated(t, e) {
return this.setup({ validator: t, errorMap: e });
}
}
class Ht extends Oe {
constructor() {
super(...arguments);
a(this, "subType");
}
/**
* Sets the component's value type to an array of strings.
* @returns the modified instance of the builder.
*/
get ofString() {
const e = new Ht().setup({ ...this.options, ...this.annotation, type: "array", editor: "arrayOfString" });
return e.subType = "string", e;
}
/**
* Sets the component's value type to an array of objects.
* @returns the modified instance of the builder.
*/
get ofObject() {
const e = new Ht().setup({ ...this.options, ...this.annotation, type: "array" });
return e.subType = "object", e;
}
}
class Ur extends Oe {
constructor() {
super(...arguments);
/**
* Possible values for the property.
*/
a(this, "values");
/**
* Labels for the possible values of the property.
*/
a(this, "labels");
}
/**
* Marks the component property as required.
* @returns the modified instance of the builder.
*/
get required() {
return super.required;
}
/**
* Sets the labels for predefined values.
* @param labels the labels.
* @returns the modified instance of the builder.
*/
labeled(...e) {
const n = this.clone();
return n.labels = e, n;
}
/**
* Creates component property metadata for the form builder.
* @param key the unique key of the component property.
* @returns the instance of the component property metadata for the form builder.
*/
build(e) {
const n = super.build(e);
return n.data = this.values.map((o, i) => {
var l;
return { label: ((l = this.labels) == null ? void 0 : l[i]) ?? Dr(o.toString()), value: o };
}), n;
}
/**
* Sets the default value for the component property.
* @param value the default value, can be an array of values.
* @returns the modified instance of the builder.
*/
default(e) {
return this.setup({ default: e });
}
}
class So extends Ur {
/**
* Sets the radio buttons as the component's property editor.
* @returns the modified instance of the builder.
*/
radio() {
return this.setup({ editor: "radio" });
}
/**
* Sets the default value for the component property.
* @param value the default value.
* @returns the modified instance of the builder.
*/
default(t) {
return super.default(t);
}
}
class Fo extends Ur {
/**
* Sets the default value for the component property.
* @param value the default value.
* @returns the modified instance of the builder.
*/
default(t) {
return super.default(t);
}
}
const Xt = class Xt extends Jr {
/**
* Creates a component property metadata builder.
* @param editor the property editor type.
* @template T the property type.
*/
constructor(t) {
super(), this.annotation = { editor: t };
}
/**
* Sets the property as a "array" property.
* @returns the instance of the metadata property builder.
*/
get array() {
return new Ht().setup({ ...this.options, ...this.annotation, type: "array" });
}
/**
* Sets the field type for the component property.
* @param type the field type.
* @returns the instance of the metadata property builder.
*/
typed(t) {
return new Oe().setup({ ...this.options, ...this.annotation, type: t });
}
/**
* Sets the property as a "single select" property.
* @param values the possible values for the property.
* @returns the instance of the metadata property builder.
*/
oneOf(...t) {
const e = new So().setup({ ...this.options, ...this.annotation, type: "enum" });
return e.values = t, e;
}
/**
* Sets the property as a "multiple select" property.
* @param values the possible values for the property.
* @returns the instance of the metadata property builder.
*/
someOf(...t) {
const e = new Fo().setup({ ...this.options, ...this.annotation, type: "enum" });
return e.values = t, e;
}
};
/**
* Creates a component property metadata builder.
* @param editor the property editor type.
* @template T the property type.
* @returns the component property metadata builder.
*/
a(Xt, "create", (t) => new Xt(t));
let Jt = Xt;
const va = (r) => r instanceof qr, B = Jt.create;
function T(r) {
return B(r).setup({ annotationType: "Property" });
}
function Zr(r) {
return r.reduce((t, e) => (t[e.key] = e.default, t), {});
}
function dt(r) {
return {
any: {
object: Zr(r)
}
};
}
class To extends Jt {
/**
* Creates a component property metadata builder.
* @param editor the property editor type.
* @template T the property type.
*/
constructor(e) {
super(e);
/**
* The function that checks whether a child component can be inserted into a parent component.
*/
a(this, "insertPredicate");
}
/**
* Specifies a function that will create conditions that check if a child component can be bound to a parent slot.
* @param slotConditionBuilder the function that returns a string containing the source code of the function to bind child components.
* @returns the instance of the metadata property builder.
*/
withSlotConditionBuilder(e) {
return this.setup({ slotConditionBuilder: e });
}
/**
* @inheritDoc
*/
build(e) {
const n = super.build(e);
return n.insertPredicate = this.insertPredicate, n;
}
/**
* Specifies a function that checks whether a child component can be inserted into a parent component.
* @param predicate the function that returns a boolean value.
* @returns the modified instance of the builder.
*/
withInsertRestriction(e) {
const n = this.clone();
return n.insertPredicate = e, n;
}
}
function _r(r) {
return new To(r);
}
const Ro = (r, t) => t.reduceScreen((e, n) => n.key === r ? e + 1 : e, 0) === 1, wa = B("key").typed("string").required.hinted("Unique component key").calculable(!1).validated(Ro, { code: "unique_key", message: "The key must be unique!" }).build("key"), Oo = B("htmlAttributes"), ko = B("validation"), $t = T("string").typed("string").localize, ba = T("object").typed("object"), ke = T("boolean").typed("boolean"), Gr = ke.setup({ readOnly: !0 }), Qr = ke.setup({ disabled: !0 }), Ca = T("number").typed("number"), xo = T("size").typed("string"), Va = T("date").typed("date"), Ea = T("time").typed("time"), Ao = T("array").array, Da = T("color").typed("string"), Pa = B("tooltipType").typed("string"), X = B("size").setup({ calculable: !1 }), or = B("color").setup({ calculable: !1 }), Sa = T("string").calculable(!0).build("className"), ir = B("event").setup({ annotationType: "Event" }), Xr = _r("node").setup({ annotationType: "Container" }), Fa = _r("nodeArray").setup({ annotationType: "Container", bindingType: "array" }), Lt = T("oneOf").oneOf.bind(T("oneOf")), Ta = T("someOf").someOf.bind(T("someOf")), No = B("tooltipProps"), zo = B("renderWhen").typed("boolean"), oe = {
width: X.setup({ default: "100%" }),
height: X,
marginTop: X,
marginRight: X,
marginBottom: X,
marginLeft: X,
color: or,
backgroundColor: or
}, xe = {
flexDirection: Lt("column", "row", "column-reverse", "row-reverse"),
gap: xo,
alignItems: Lt("start", "center", "baseline", "end", "stretch"),
justifyContent: Lt(
"flex-start",
"flex-end",
"center",
"space-between",
"space-around",
"space-evenly",
"start",
"end",
"left",
"right"
),
flexWrap: Lt("wrap", "nowrap", "wrap-reverse")
};
function gt(r, t = {}) {
return Un(r, (e, n, o) => {
var i;
return e.push(((i = n == null ? void 0 : n.setup(t)) == null ? void 0 : i.build(o)) ?? $t.setup(t).build(o)), e;
}, []);
}
function ut(r) {
return gt(r, { annotationType: "Style", calculable: !1 });
}
const jo = (r) => {
const t = wo() === "viewer", n = I().parentStore;
return t && !r.children ? null : /* @__PURE__ */ p("div", { className: r.wrapperClassName, children: t || n ? r.children : /* @__PURE__ */ p(Te, { children: r.children }) });
}, Yr = (r) => /* @__PURE__ */ p(go, { value: r, children: /* @__PURE__ */ p(jo, { wrapperClassName: r.wrapperClassName, children: r.children }) });
Yr.displayName = "Repeater";
const tn = Ao.valued.setup({ editor: "arrayOfObject" }), en = gt({
itemRenderWhen: $t.notLocalize.hinted("The expression or function to conditionally render a repeater item."),
value: tn,
children: Xr
}), { flexDirection: rn, gap: nn } = xe, on = ut({
display: $t.default("flex").hideEditor(),
flexDirection: rn.default("column").named("Item direction").hinted("Item direction"),
gap: nn.default("20px").named("Item gap").hinted("Item gap")
}), $o = dt(on), sn = ut({
display: $t.default("flex").hideEditor(),
flexDirection: rn.default("column").hinted("Repeater direction"),
gap: nn.default("20px").hinted("Repeater gap")
}), Mo = dt(sn), Lo = en.filter((r) => typeof r.default < "u").reduce((r, t) => (r[t.key] = t.default, r), {}), Ut = new M(
Yr,
"Repeater",
void 0,
"value",
"array",
Lo,
$o,
Mo,
"Repeater",
"repeater"
), Ae = (async function() {
}).constructor;
class F {
/**
* Creates a new instance of the ActionDefinition class.
* @param func the function of an action.
* @param body the source code of the Action.
* @param params the parameters of the Action.
*/
constructor(t, e, n = {}) {
this.func = t, this.body = e, this.params = n;
}
/**
* Creates an action from the function.
* @param func the function of an action.
* @param params the parameters of the Action.
* @returns the new instance of the ActionDefinition class.
*/
static functionalAction(t, e = {}) {
return new F(t, void 0, e);
}
/**
* Creates an action from the source code.
* @param body the source code of the Action.
* @param params the parameters of the Action.
* @returns the new instance of the ActionDefinition class.
*/
static sourceAction(t, e = {}) {
const n = Ae("e, args", t);
return new F(n, t, e);
}
/**
* Correctly creates the {@link ActionDefinition} from deserialized data.
* @param value the deserialized data.
* @returns the ActionDefinition instance.
*/
static createFromObject(t) {
return F.sourceAction(t.body, t.params);
}
}
const Io = (r) => {
const t = {};
return r && Object.keys(r).forEach((e) => {
const n = r[e];
t[e] = F.createFromObject(n);
}), t;
}, Ne = "onDidMount", ze = "onWillUnmount";
function ce(r) {
return new Proxy(r, {
get(t, e) {
return e === "toJSON" ? () => t.data : t.data[e];
},
set(t, e, n) {
return t.allComponentFields.filter(({ dataKey: o }) => o === e).forEach(({ field: o }) => {
o.setValue(n);
}), !0;
}
});
}
var Et, Dt, Pt, St, Yt;
class je {
/**
* Creates arguments for the event handler.
* @param type the event type.
* @param sender the component that triggered the event.
* @param store the form viewer settings.
* @param args the event arguments.
* @param renderedProps the component properties that were used to render the sender component.
*/
constructor(t, e, n, o, i) {
v(this, Et, void 0);
v(this, Dt, void 0);
v(this, Pt, void 0);
/**
* The index of the component in the array, if the component is in the array.
*/
a(this, "index");
/**
* Sets user-defined properties for the React component that override other properties of the component.
* @param props the component properties.
*/
a(this, "setUserDefinedProps", (t) => {
this.sender.userDefinedProps = t;
});
v(this, St, (t) => !!(t && t.target && t.type && t.preventDefault));
v(this, Yt, (t) => !h(this, St).call(this, t));
var c;
this.type = t, this.sender = e, this.store = n, this.args = o, this.renderedProps = i, this.index = e.nearestIndex;
const s = typeof this.index == "number", l = e.dataRoot;
if (E(this, Et, ce(l)), s) {
const d = ((c = l.parent) == null ? void 0 : c.dataRoot) ?? this.store.formData;
E(this, Dt, ce(d));
}
E(this, Pt, ce(this.store.formData));
}
/**
* @returns the event handled by the event handler.
*/
get event() {
return this.args.find(h(this, St));
}
/**
* @returns the first element of the event argument array, which is treated as a value.
*/
get value() {
return this.args.filter((t) => typeof t < "u").find(h(this, Yt));
}
/**
* @returns the object for reading and changing form data.
*/
get data() {
return h(this, Et);
}
/**
* @returns the object to read and modify parent data (available for array elements).
*/
get parentData() {
return h(this, Dt);
}
/**
* @returns the object to read and modify root form data.
*/
get rootData() {
return h(this, Pt);
}
}
Et = new WeakMap(), Dt = new WeakMap(), Pt = new WeakMap(), St = new WeakMap(), Yt = new WeakMap();
const Ra = `
/**
* Arguments passed to the event handler.
*/
declare class ActionEventArgs {
/**
* The event type.
*/
readonly type: string
/**
* The component that triggered the event.
*/
readonly sender: ComponentData
/**
* The component properties that were used to render the sender component.
*/
readonly renderedProps: Record<string, any>
/**
* The index of the component in the array, if the component is in the array.
*/
readonly index?: number
/**
* Sets current props of component.
*/
readonly setUserDefinedProps: (props: Record<string, any>) => void
/**
* The form viewer settings.
*/
readonly store: Store
/**
* The event arguments.
*/
readonly args: any[]
/**
* @returns the event handled by the event handler.
*/
get event(): SyntheticEvent | null
/**
* @returns the first element of the event argument array, which is treated as a value.
*/
get value(): any
/**
* @returns the object for reading and changing form data.
*/
get data(): Record<string, unknown>
/**
* @returns the object to read and modify parent data (available for array elements).
*/
get parentData(): Record<string, unknown> | undefined
/**
* @returns the object to read and modify root form data.
*/
get rootData(): Record<string, unknown>
}
`, Mt = [
No.build("tooltipProps"),
zo.build("renderWhen"),
Oo.build("htmlAttributes"),
ko.build("validation"),
ir.build(Ne),
ir.build(ze)
];
class G {
/**
* Creates the component metadata for the form builder.
* @param type the component type name.
* @param properties the component's properties metadata.
* @param css the component's CSS metadata.
* @param wrapperCss the component's wrapper CSS metadata.
* @param modules common metadata for the component.
* @param customPreview the custom ReactNode to be drawn on the toolbar.
* @param valuedAn the metadata for the component value.
* @param kind the component kind.
* @param initialJson the JSON source for the component (instance of {@link ComponentStore} class serialised to JSON).
* @param eventListeners the component metadata event listeners.
* @param icon the component icon.
* @param insertRestriction the function that restricts the insertion of a component into another component.
*/
constructor(t, e, n, o, i, s, l, c = "component", d, u, g, y) {
this.type = t, this.properties = e, this.css = n, this.wrapperCss = o, this.modules = i, this.customPreview = s, this.valuedAn = l, this.kind = c, this.initialJson = d, this.eventListeners = u, this.icon = g, this.insertRestriction = y;
}
}
function an(r) {
return typeof r == "string";
}
function ln(r) {
return typeof r == "number";
}
function ie(r) {
return typeof r == "object" && typeof r.then == "function";
}
function cn(r) {
return typeof r == "object";
}
function k(r, t) {
const e = Or(t);
return e.displayName = r, e;
}
const Oa = new O("", ""), [
/**
* **Internal use only.**
*/
Q,
/**
* **Internal use only.**
*/
dn
] = yt("FormViewerPropsContext"), sr = {
LTR: Xe({
key: _.LTR
}),
RTL: Xe({
key: _.RTL,
stylisPlugins: [Xn],
prepend: !0
})
}, Bo = pt`
display: flex;
width: 100%;
height: 100%;
`, Wo = "optimajet-formviewer", Ko = ft(Wo, Bo), un = ([r, ...t], e, n) => r ? /* @__PURE__ */ p(r, { language: e, children: un(t, e, n) }) : n, qo = (r) => {
const t = I(), e = t.displayedLanguage, n = e.bidi == _.RTL ? sr.RTL : sr.LTR;
return K(() => {
t.formViewerPropsStore.view.getCssLoaders(e.bidi).forEach((i) => {
i().catch((s) => console.error(s));
});
}, [e, t.formViewerPropsStore.view]), /* @__PURE__ */ p("div", { dir: e.bidi, lang: e.fullCode, className: Ko, children: /* @__PURE__ */ p(Qn, { value: n, children: un(t.formViewerPropsStore.view.viewerWrappers, e, r.children) }) });
}, Ho = k("ViewerLocalizationProvider", qo), Jo = ({ children: r }) => {
const [t] = Ve(window.onerror);
return K(() => (window.onerror = (e) => {
if ((e == null ? void 0 : e.toString().search("ResizeObserver")) !== -1) {
const n = document.getElementById(
"webpack-dev-server-client-overlay-div"
), o = document.getElementById(
"webpack-dev-server-client-overlay"
);
return o && o.setAttribute("style", "display: none"), n && n.setAttribute("style", "display: none"), !0;
}
return !1;
}, () => {
window.onerror = t;
}), [t]), /* @__PURE__ */ p(zt, { children: r });
};
class se {
/**
* Creates a localization language for the form builder.
* @param code the language code, for example, 'en'.
* @param dialect the dialect code, for example, 'US'.
* @param name the name of the language, for example 'English'.
* @param description the description of the language, for example 'American English'.
* @param bidi the type of text layout, for example, BiDi.LTR.
*/
constructor(t, e, n, o, i = _.LTR) {
this.code = t, this.dialect = e, this.name = n, this.description = o, this.bidi = i;
}
/**
* @returns Full code of the Language i.e en-US, en-GB etc.
*/
get fullCode() {
return `${this.code}-${this.dialect}`;
}
/**
* Clones an existing instance of the language.
* @param source the cloning object.
* @returns the object clone.
*/
static clone(t) {
return new se(t.code, t.dialect, t.name, t.description, t.bidi);
}
}
const Kt = new se("en", "US", "English", "American English"), Uo = () => I().form.tooltipType;
class A {
/**
* Constructor.
* @param error the error.
* @param result the result.
* @param exceptions the exceptions.
* @param warning the warning.
*/
constructor(t = !1, e, n, o) {
this.error = t, this.result = e, this.exceptions = n, this.warning = o;
}
/**
* Creates a new instance of the CalculableResult class with a successful result.
* @param result the calculable result.
* @returns the new instance of CalculableResult class.
*/
static success(t) {
return new A(!1, t);
}
/**
* Creates a new instance of CalculableResult class with an error.
* @param exceptions the exception array.
* @returns the new instance of CalculableResult class.
*/
static error(t) {
return new A(!0, void 0, t);
}
/**
* Creates a new instance of the CalculableResult class with a warning result.
* @param result the calculable result.
* @returns the new instance of CalculableResult class.
*/
static warning(t) {
return new A(!1, t, void 0, !0);
}
}
const ar = /* @__PURE__ */ new Map(), Zo = (r) => {
const t = ar.get(r);
if (t)
return t;
const e = new Function("form", r);
return ar.set(r, e), e;
}, hn = (r, t) => {
try {
const n = Zo(r)(t);
return A.success(n);
} catch (e) {
return A.error([
e,
{
name: "Function source",
message: r
}
]);
}
}, $e = (r, t) => hn(r.fnSource || "", t), pn = (r, t) => {
if (mt(r))
return $e(r, t).result;
const e = r.value || "";
return hn(`return ${e}`, t).result;
}, _o = (r, t) => {
const e = {};
return Object.keys(r.props).forEach((n) => {
const o = r.props[n];
if (o) {
if (mt(o)) {
const { result: i, error: s, exceptions: l } = $e(o, t);
if (s) {
const c = `Error in the calculable field '${n}' of the '${r.key}' component `;
console.warn(c, l);
return;
}
e[n] = i;
return;
}
Pr(o.value) || (e[n] = o.value);
}
}), e;
}, Go = (r) => r.field ? {
onChange: (t) => {
var e;
(e = r.field) == null || e.setValue(t.value);
},
onBlur: () => {
var t;
(t = r.field) == null || t.setTouched();
}
} : {}, Qo = (r) => {
var t;
return (t = r.htmlAttributes) == null ? void 0 : t.reduce((e, { name: n, value: o }) => {
try {
e[n] = JSON.parse(o);
} catch {
e[n] = o;
}
return e;
}, {});
}, Xo = (r) => {
var t, e;
return !!((e = (t = r.schema) == null ? void 0 : t.validations) != null && e.find((n) => n.key === "required"));
};
function Yo(r, t) {
const e = t.map((n) => ({
func: r.findAction(n).func,
args: n.args ? { ...n.args } : {}
}));
return async (n) => {
try {
for (const { func: o, args: i } of e) {
const s = o(n, i);
ie(s) && await s;
}
} catch (o) {
console.info("Action handler throws an error", o);
}
};
}
const fn = (r, t) => async (...e) => {
var d;
const { data: n, store: o } = r, i = ((d = n.store.events) == null ? void 0 : d[t]) ?? [], s = Yo(o, i), l = r.get, c = new je(t, n, o, e, l);
await s(c);
}, ti = (r) => {
const t = {}, { data: e } = r, n = Go(e), o = [
...Object.keys(e.store.events ?? {}),
...Object.keys(n)
], i = new Set(o);
return i.delete(Ne), i.delete(ze), i.forEach((s) => {
t[s] = async (...l) => {
const c = n[s];
if (c) {
const u = new je(s, e, r.store, l, r.get);
c(u);
}
await fn(r, s)(...l);
};
}), t;
};
class mn {
/**
* Creates an instance that calculates the properties of the form viewer component.
* @param data the data needed to display the component.
* @param store the form viewer settings.
* @param localizer the function to localize the properties of a component, returns a Record with localized properties.
* @param computeChildren the function that calculates all child properties of a component.
*/
constructor(t, e, n, o) {
this.data = t, this.store = e, this.localizer = n, this.computeChildren = o, H(this, void 0, { name: z("ComponentState", { key: t.key }) });
}
/**
* @inheritDoc
*/
get get() {
const t = this.propsWithoutChildren;
return Object.assign({}, t, this.className, this.children(t));
}
/**
* @inheritDoc
*/
get ownProps() {
return { ...this.propsWithoutChildren, ...this.className };
}
/**
* @inheritDoc
*/
get propsWithoutChildren() {
const { htmlAttributes: t, ...e } = this.calculatedProps;
return Object.assign(
{ key: this.data.store.key },
this.data.model.defaultProps,
e,
this.localizedProps,
this.value,
this.readOnly,
this.disabled,
this.events,
t ?? this.htmlAttributes,
this.data.userDefinedProps
);
}
/**
* @returns the component's field value data, if the component can have a field value.
*/
get value() {
if (this.data.model.kind !== "template" && this.data.field) {
const t = this.data.field.value ?? this.data.model.uncontrolledValue;
return { [this.data.field.valued]: t };
}
}
/**
* @returns the read-only property of a component if the component has a read-only flag.
*/
get readOnly() {
if (this.data.model.readOnly)
return { [this.data.model.readOnly]: this.isReadOnly };
}
/**
* @inheritDoc
*/
get isReadOnly() {
var t;
return this.data.model.readOnly ? this.store.formViewerPropsStore.readOnly || ((t = this.data.parent) == null ? void 0 : t.componentState.isReadOnly) || (this.selfProps[this.data.model.readOnly] ?? !1) : !1;
}
/**
* @returns the disabled property of a component if the component has a disabled flag.
*/
get disabled() {
if (this.data.model.disabled)
return { [this.data.model.disabled]: this.isDisabled };
}
/**
* @inheritDoc
*/
get isDisabled() {
var t;
return this.data.model.disabled ? this.store.formViewerPropsStore.disabled || ((t = this.data.parent) == null ? void 0 : t.componentState.isDisabled) || (this.selfProps[this.data.model.disabled] ?? !1) : !1;
}
/**
* @returns the values for all properties of the component, calculates the values of the calculated properties.
*/
get calculatedProps() {
return _o(this.data.store, this.data.dataRoot);
}
/**
* @returns component localized properties.
*/
get localizedProps() {
return this.localizer(this.data.store);
}
/**
* @returns the component event handlers that send events to the event bus.
*/
get events() {
return ti(this);
}
/**
* Calculates and returns className property.
* @returns the Record that contains the className property for the component.
*/
get className() {
return { className: ft(
{ required: Xo(this.data.store) },
this.propsWithoutChildren.className,
this.getClassNameFromCssPart("css")
) };
}
/**
* @inheritDoc
*/
get wrapperClassName() {
return this.getClassNameFromCssPart("wrapperCss");
}
/**
* @returns all arbitrary HTML attributes of the component.
*/
get htmlAttributes() {
return Qo(this.data.store);
}
/**
* Calculates and returns all child components.
* @param props the React component properties.
* @returns the Record that contains the child components of a component.
*/
children(t) {
return this.computeChildren(this.data, t);
}
/**
* @inheritDoc
*/
onDidMount() {
this.executeLifecycleEvent(Ne);
}
/**
* @inheritDoc
*/
onWillUnmount() {
this.executeLifecycleEvent(ze);
}
executeLifecycleEvent(t) {
const e = fn(this, t), n = new je(t, this.data, this.store, [], this.get);
e(n).catch(console.error);
}
getClassNameFromCssPart(t) {
var l, c, d, u, g, y, b, W, Ue, Ze, _e, Ge;
const { model: e, store: n } = this.data, { viewMode: o } = this.store, i = U(
{},
(c = (l = e[t]) == null ? void 0 : l.any) == null ? void 0 : c.object,
(u = (d = n[t]) == null ? void 0 : d.any) == null ? void 0 : u.object
), s = U(
{},
(y = (g = e[t]) == null ? void 0 : g[o]) == null ? void 0 : y.object,
(W = (b = n[t]) == null ? void 0 : b[o]) == null ? void 0 : W.object
);
return pt`
&& {
${i}
${s}
${(Ze = (Ue = n[t]) == null ? void 0 : Ue.any) == null ? void 0 : Ze.string}
${(Ge = (_e = n[t]) == null ? void 0 : _e[o]) == null ? void 0 : Ge.string}
}
`;
}
get selfProps() {
const { htmlAttributes: t, ...e } = this.calculatedProps;
return {
...this.data.model.defaultProps,
...e,
...this.localizedProps,
...this.value,
...this.data.userDefinedProps
};
}
}
const ei = (r, t, e, n, o) => {
const i = new O(t.key, e.type);
i.props = n;
const s = r.createComponentData(i, !1);
return s.dataRootProvider = {
get dataRoot() {
return t.dataRoot;
}
}, s.componentState = new mn(s, r, o, () => ({})), s.componentState;
}, yn = (r, t, e, n) => {
const o = I();
return L(
() => ei(o, r, t, e, n),
[o, r, t, e, n]
);
};
function ri() {
const r = Q(), t = Uo();
if (t)
return r.view.get(t);
}
const ni = ({ tooltipDefinition: r, children: t }) => {
const e = I(), n = Z(), o = n.store, i = Ee((l) => e.localizeComponent("tooltip", n.dataRoot, l), [e, n]), s = yn(n, r, o.tooltipProps, i);
return De(r.component, s.ownProps, t);
}, oi = k("ComponentTooltip", ni), ii = ({ children: r }) => {
const t = ri();
return t ? /* @__PURE__ */ p(oi, { tooltipDefinition: t, children: r }) : /* @__PURE__ */ p(zt, { children: r });
}, si = k("TooltipWrapper", ii), ai = () => {
const r = I(), t = r.form.errorType, e = r.formViewerPropsStore.view, n = Q();
return L(() => {
const o = n.errorWrapper ? new M(n.errorWrapper) : Ce;
return (t ? e.find(t) : o) ?? Ce;
}, [t, e, n.errorWrapper]);
}, li = ({ children: r }) => {
var c;
const t = Z(), e = I(), n = Q(), o = ai(), i = Ee(() => ({}), []), s = yn(t, o, e.form.errorProps, i);
if (n.erroneous)
return /* @__PURE__ */ p(zt, { children: r });
const l = { ...s.ownProps, error: (c = t.field) == null ? void 0 : c.error };
return De(o.component, l, r);
}, lr = k("Erroneous", li);
function Me(r) {
return r.message ?? `Validation failed: ${r.settings.key}`;
}
function ci(r) {
if (r)
return r == null ? void 0 : r.map(Me).join(" ");
}
var Ft, Tt, tt, et;
const te = class te {
constructor(t, e, n, o, i) {
v(this, Ft, new Yn());
v(this, Tt, void 0);
v(this, tt, void 0);
v(this, et, void 0);
/**
* Generates an event to perform validation.
* @param value the validated value.
*/
a(this, "sendValidationEvent", (t) => {
h(this, Ft).next(t);
});
/**
* Performs a validation of the value.
* @param value the validated value.
* @returns the Promise with the result of the validation.
*/
a(this, "validate", (t) => {
const e = new Promise((n) => {
const o = h(this, tt).subscribe((i) => {
n(i), o.unsubscribe();
});
});
return this.sendValidationEvent(t), e;
});
/**
* Returns the validation results without triggering an events and changing the state of the form.
* @param value the validated value.
* @returns the validation results.
*/
a(this, "getValidationResult", (t) => h(this, et).call(this, t));
/**
* Releases allocated resources, must be used when destroying an object instance.
*/
a(this, "dispose", () => {
h(this, Tt).forEach((t) => t.unsubscribe());
});
const s = (l) => {
if (!(!l || l.length === 0))
return t.showAllValidationErrors ? (i ?? ci)(l) : (i == null ? void 0 : i([l[0]])) ?? Me(l[0]);
};
E(this, et, (l) => n(l, t, e)), E(this, tt, h(this, Ft).pipe(
to(200),
Ye(h(this, et)),
eo((l) => l),
Ye(s)
)), E(this, Tt, [
h(this, tt).subscribe(o)
]);
}
};
Ft = new WeakMap(), Tt = new WeakMap(), tt = new WeakMap(), et = new WeakMap(), /**
* Creates a DataValidator instance.
* @param store the form viewer settings.
* @param getFormData the function that returns a form data.
* @param resolver the validation function factory.
* @param args the validation function factory arguments.
* @param setter the callback function called to set a validation error.
* @param localizer the function that localizes validation error messages.
* @template T the validation function factory arguments.
* @returns the DataValidator instance.
*/
a(te, "create", (t, e, n, o, i, s) => new te(t, e, n(o), i, s));
let ge = te;
const di = pt`
display: flex;
`, Le = (r) => {
const { className: t, children: e, ...n } = r, o = L(() => ft(di, t), [t]);
return /* @__PURE__ */ p("div", { className: o, ...n, children: e });
};
Le.displayName = "Screen";
const ui = () => {
const r = Z(), { componentWrapper: t } = Q(), e = r.componentState;
K(() => (e.onDidMount(), () => {
e.onWillUnmount();
}), [e]);
const { key: n, ...o } = e.get, { kind: i, component: s } = r.model, l = ft(o.className, e.wrapperClassName), c = t ?? Le, d = r.store.tooltipProps ? si : Bn, u = t ?? s, g = /* @__PURE__ */ p(s, { ...o }, n);
return i === "container" ? /* @__PURE__ */ p(u, { ...o, className: l }, n) : i === "repeater" ? /* @__PURE__ */ p(c, { children: /* @__PURE__ */ p(d, { children: /* @__PURE__ */ p(lr, { children: /* @__PURE__ */ p(s, { ...o, wrapperClassName: l }, n) }) }) }) : /* @__PURE__ */ p(c, { className: i === "template" ? l : e.wrapperClassName, children: i === "template" ? g : /* @__PURE__ */ p(d, { children: /* @__PURE__ */ p(lr, { children: g }) }) });
}, hi = k("ComponentViewer", ui), gn = ({ data: r, componentDataViewer: t }) => {
const e = r.map((n) => /* @__PURE__ */ p(Wr, { value: n, children: De(t ?? hi) }, n.id));
return /* @__PURE__ */ p(zt, { children: e });
}, { height: pi } = oe, { flexDirection: fi, gap: mi } = xe, vn = ut({
...xe,
...oe,
height: pi.setup({ default: "100%" }),
flexDirection: fi.default("column"),
gap: mi.default("10px")
}), yi = dt(vn), ht = new M(
Le,
void 0,
void 0,
void 0,
void 0,
void 0,
yi,
void 0,
void 0,
"container",
"readOnly",
void 0,
void 0,
"disabled"
), gi = {
color: "red"
}, Ie = ({ error: r }) => /* @__PURE__ */ p("h1", { style: gi, children: (r == null ? void 0 : r.message) ?? JSON.stringify(r) });
Ie.displayName = "InternalError";
const Zt = new M(Ie);
function wn(r) {
const t = new O(Zt.name, Zt.type);
t.props.error = { value: r };
const e = new O(ht.name, ht.type);
return e.children = [t], e;
}
function vi(r) {
const t = { error: r };
return new M(Ie, void 0, void 0, void 0, void 0, t);
}
const wi = () => {
const r = window.innerWidth;
return r <= 600 ? "mobile" : r <= 900 ? "tablet" : "desktop";
};
function bi() {
const r = I(), t = Q();
K(() => {
if (t.viewMode) {
r.viewMode = t.viewMode;
return;
}
const e = () => r.viewMode = wi();
return window.addEventListener("resize", e), () => window.removeEventListener("resize", e);
}, [t.viewMode, r]);
}
const cr = (r, t) => {
r.form.componentTree.errors = t ?? {};
}, Ci = (r, t) => {
console.error(t), r.formLoadError = (t == null ? void 0 : t.message) ?? t;
const e = wn(t);
r.applyPersistedForm({
form: e,
localization: {},
defaultLanguage: Kt.fullCode,
languages: []
});
}, Vi = async (r, t, e) => {
if (t)
try {
const n = t(e);
if (ie(n)) {
const o = await n;
r.applyStringForm(o);
return;
}
r.applyStringForm(n);
} catch (n) {
Ci(r, n);
}
}, Ei = () => {
const r = I(), { formLoadError: t } = r, e = Q(), n = L(() => [r.form.componentTree], [r.form.componentTree]), [o, i] = Ve(e.errors), s = Wn(o);
return s.current = o, bi(), K(() => {
Vi(r, e.getForm, e.formName).then(() => {
cr(r, s.current);
}).catch(console.error);
}, [r, e.getForm, e.formName]), K(() => {
o !== e.errors && (i(e.errors), s.current = e.errors, cr(r, e.errors));
}, [o, e.errors, r]), t ? /* @__PURE__ */ p("div", { className: "form-error", children: t }) : /* @__PURE__ */ p(gn, { data: n });
}, Di = k("Viewer", Ei);
function Pi(r) {
if (!r)
return;
const t = {};
return Object.entries(r).forEach(([e, n]) => {
t[e] = n instanceof F ? n : F.functionalAction(n);
}), t;
}
class Be {
/**
* Constructs a new FormViewerPropsStore from the given FormViewerProps.
* @param formViewerProps the FormViewer props.
* @returns the FormViewerPropsStore.
*/
constructor(t) {
/**
* The metadata of the form viewer components.
*/
a(this, "view", new bt());
/**
* The initial form data.
*/
a(this, "initialData", {});
/**
* The set of metadata of validation rules, grouped by the type of value being validated.
*/
a(this, "validators");
/**
* The set of functions that validate the form data.
*/
a(this, "formValidators");
/**
* The function to localize the properties of a component.
*/
a(this, "localizer");
/**
* Custom actions for the form viewer.
*/
a(this, "actions");
/**
* The full language code passed in the FormViewer properties, e.g. 'en-US'.
*/
a(this, "propsLanguage");
/**
* The default error wrapper used when errorType is not specified in the form.
*/
a(this, "errorWrapper");
/**
* If true, the form is read-only.
*/
a(this, "readOnly");
/**
* If true, the form is disabled.
*/
a(this, "disabled");
/**
* If true, all validation errors will be displayed.
*/
a(this, "showAllValidationErrors");
t && this.applyProps(t), Sr(this, {
view: P.ref,
initialData: P.ref,
validators: P.ref,
formValidators: P.ref,
localizer: P.ref,
actions: P.ref,
propsLanguage: P.ref,
errorWrapper: P.ref,
disabled: P.ref,
readOnly: P.ref,
showAllValidationErrors: P.ref
}, { name: z("FormViewerPropsStore") });
}
/**
* Applies the given FormViewerProps.
* @param formViewerProps the properties to apply.
*/
applyProps(t) {
this.view = t.view, this.initialData = t.initialData ?? {}, this.validators = t.validators, this.formValidators = t.formValidators, this.localizer = t.localize, this.actions = Pi(t.actions), this.propsLanguage = t.language, this.errorWrapper = t.errorWrapper, this.readOnly = t.readOnly, this.disabled = t.disabled, this.showAllValidationErrors = t.showAllValidationErrors;
}
/**
* Returns the clone of the FormViewerPropsStore object.
* @returns the clone of the FormViewerPropsStore object.
*/
clone() {
const t = new Be();
return t.view = this.view, t.initialData = this.initialData, t.validators = this.validators, t.formValidators = this.formValidators, t.localizer = this.localizer, t.actions = this.actions, t.propsLanguage = this.propsLanguage, t.errorWrapper = this.errorWrapper, t.readOnly = this.readOnly, t.disabled = this.disabled, t.showAllValidationErrors = this.showAllValidationErrors, t;
}
}
const Si = (r) => {
if (r)
try {
return JSON.parse(r);
} catch {
return;
}
}, dr = (r, t, e, n, o) => {
const i = r[t] ?? [];
if (typeof e == "number" && i.length >= e)
return;
const s = Si(n) ?? {}, l = [...i];
typeof o == "number" ? l.splice(o, 0, s) : l.push(s), r[t] = l;
}, ur = (r, t, e, n) => {
const o = r[t];
if (!Array.isArray(o) || typeof n == "number" && o.length <= n)
return;
const i = [...o];
i.splice(e, 1), r[t] = i;
}, bn = (r) => {
var e, n;
const t = r.dataRoot;
if (typeof t.index == "number")
return (n = (e = t.store.props) == null ? void 0 : e.repeaterDataKey) == null ? void 0 : n.value;
}, Fi = F.functionalAction((r, t) => {
if (t.dataKey) {
dr(r.data, t.dataKey, t.max, t.rowData, t.index);
return;
}
const e = bn(r.sender);
e && r.parentData && dr(r.parentData, e, t.max, t.rowData, t.index);
}, {
dataKey: "string",
rowData: "string",
index: "number",
max: "number"
}), Ti = F.functionalAction((r, t) => {
const e = t.index ?? r.index ?? -1;
if (t.dataKey) {
ur(r.data, t.dataKey, e, t.min);
return;
}
const n = bn(r.sender);
n && r.parentData && ur(r.parentData, n, e, t.min);
}, {
dataKey: "string",
index: "number",
min: "number"
}), Ri = {
// eslint-disable-next-line no-console
log: F.functionalAction(console.log),
validate: F.functionalAction(async (r, t) => {
const e = r.store.form.componentTree;
if (await e.validate(), t.failOnError === !0 && e.hasErrors)
throw e.errors;
}, {
failOnError: "boolean"
}),
clear: F.functionalAction((r) => r.store.form.componentTree.clear()),
reset: F.functionalAction((r) => r.store.form.componentTree.reset()),
addRow: Fi,
removeRow: Ti
};
function hr(r, t) {
return r.find((e) => e.code === t);
}
function Oi(r, t) {
const [e, n] = t.split("-");
if (n) {
const o = r.find((s) => s.code === e && s.dialect === n);
if (o)
return o;
const i = hr(r, e);
if (i)
return i;
}
return hr(r, t);
}
const Cn = "validator-", ki = (r) => `${Cn}${r}`, ka = (r) => r.startsWith(Cn);
function xi(r, t) {
return new Proxy(r, {
get(e, n) {
return n in e ? e[n] : (t.push(Nr(n)), "");
},
getOwnPropertyDescriptor(e, n) {
return n in e ? Reflect.getOwnPropertyDescriptor(e, n) : {
value: "",
writable: !0,
configurable: !0
};
}
});
}
function We(r, t, e) {
const n = [], o = xi(t, n), i = [];
let s = r.formatPattern(e, o, i);
return s = Nr(s), {
result: s,
missingProperties: n,
fluentErrors: i
};
}
function Vn(r) {
r.length > 0 && console.warn("Localization errors:", r);
}
const En = (r, t) => {
const e = r.defaultLanguage !== t ? r.localization.getFluentBundle(r.defaultLanguage.fullCode) : void 0, n = r.localization.getFluentBundle(t.fullCode);
return { defaultBundle: e, fluentBundle: n };
}, xa = (r) => {
r.localization = zr(r.localization);
const t = `${r.localizationStringId} = ${r.localization}`, e = new kr(t), n = new xr(`${r.language.fullCode}`), o = n.addResource(e);
if (o.length > 0)
return A.error([...o]);
const i = n.getMessage(r.localizationStringId);
if (typeof i > "u")
return A.error([{ message: "Localization message not found", name: "MessageNotFound" }]);
if (i.value === null)
return A.error([{ message: "Localization message is null", name: "MessageIsNull" }]);
const { result: s, missingProperties: l, fluentErrors: c } = We(n, r.data, i.value);
return c.length > 0 ? A.error(c) : l.length > 0 ? A.warning(`The following variable(s) are not defined: ${l.join(", ")}`) : A.success(s);
}, Ai = (r, t, e, n, o = "component") => {
const { defaultBundle: i, fluentBundle: s } = En(r, e), l = {};
return Object.keys(n.props).forEach((c) => {
const d = n.props[c];
if (!Fe(d))
return;
const u = D(`${n.key}_${o}_${c}`), g = s.getMessage(u) ?? (i == null ? void 0 : i.getMessage(u));
if (!g) {
l[c] = "[NOT LOCALIZED]";
return;
}
const { result: y, fluentErrors: b } = We(s, t.fluentData, g.value);
l[c] = y, Vn(b);
}), l;
}, Ni = (r, t, e, n, o) => {
const i = ki(o), s = "message", l = D(`${n.key}_${i}_${s}`), { defaultBundle: c, fluentBundle: d } = En(r, e), u = d.getMessage(l) ?? (c == null ? void 0 : c.getMessage(l));
if (!u)
return;
const { result: g, fluentErrors: y } = We(d, t.fluentData, u.value);
return Vn(y), g;
}, _t = "Template:";
function Dn(r) {
return _t + r;
}
function Pn(r) {
if (r.startsWith(_t))
return r.slice(_t.length);
throw new Error(`Cannot determine template name from '${r}'`);
}
function pr(r) {
return r.startsWith(_t);
}
function zi(r, t, e, n) {
const o = r.props[t];
if (mt(o)) {
const { result: i } = $e(o, e);
return [!0, i];
}
return Fe(o) ? [!0, n("component", r)[t]] : [!1];
}
function f() {
return {
params: [],
withParameter(t, e, n = !1, o, i) {
return this.params.push({ key: t, type: e ?? "string", required: n, default: o, editorType: i }), this;
},
withValidatorFactory(t) {
return { ...this, validatorFactory: t };
}
}.withParameter("message");
}
function Sn(r) {
var e;
const t = (e = r.props.storeDataInParentForm) == null ? void 0 : e.value;
return typeof t > "u" ? !0 : t;
}
const q = (r) => r ?? "Required";
function m(r) {
return async (t) => {
var n;
const e = await (r == null ? void 0 : r.safeParseAsync(t));
return e != null && e.success ? !0 : ((n = e == null ? void 0 : e.error.issues) == null ? void 0 : n[0].message) ?? !1;
};
}
const vt = N.array(N.any()), ji = {
required: f().withValidatorFactory(({ message: r }) => m(vt.nonempty(q(r)))),
nonEmpty: f().withValidatorFactory(({ message: r }) => m(vt.nonempty(r))),
length: f().withParameter("length", "number", !0).withValidatorFactory(({ length: r, message: t }) => m(vt.length(r, t))),
min: f().withParameter("limit", "number", !0).withValidatorFactory(({ limit: r, message: t }) => m(vt.min(r, t))),
max: f().withParameter("limit", "number", !0).withValidatorFactory(({ limit: r, message: t }) => m(vt.max(r, t)))
}, de = N.boolean(), $i = {
required: f().withValidatorFactory(({ message: r }) => m(de.refine((t) => t, q(r)))),
truthy: f().withValidatorFactory(({ message: r }) => m(de.refine((t) => t, r))),
falsy: f().withValidatorFactory(({ message: r }) => m(de.refine((t) => !t, r)))
}, ue = N.date(), Mi = {
required: f().withValidatorFactory(({ message: r }) => m(ue.refine((t) => t, q(r)))),
min: f().withParameter("value", "date", !0).withValidatorFactory(({ value: r, message: t }) => m(ue.min(new Date(r), t))),
max: f().withParameter("value", "date", !0).withValidatorFactory(({ value: r, message: t }) => m(ue.max(new Date(r), t)))
}, J = N.number(), Li = {
required: f().withValidatorFactory(({ message: r }) => m(J.refine((t) => !Pr(t) && !Zn(t), q(r)))),
min: f().withParameter("limit", "number", !0).withValidatorFactory(({ limit: r, message: t }) => m(J.min(r, t))),
max: f().withParameter("limit", "number", !0).withValidatorFactory(({ limit: r, message: t }) => m(J.max(r, t))),
lessThan: f().withParameter("value", "number", !0).withValidatorFactory(({ value: r, message: t }) => m(J.lt(r, t))),
moreThan: f().withParameter("value", "number", !0).withValidatorFactory(({ message: r, value: t }) => m(J.gt(t, r))),
integer: f().withValidatorFactory(({ message: r }) => m(J.int(r))),
multipleOf: f().withParameter("value", "number", !0).withValidatorFactory(({ message: r, value: t }) => m(J.multipleOf(t, r))),
finite: f().withValidatorFactory(({ message: r }) => m(J.finite(r)))
}, Ii = N.union([N.object({}).passthrough(), N.string()]), Bi = {
required: f().withValidatorFactory(({ message: r }) => m(N.unknown().refine((t) => !Er(t), q(r)))),
nonEmpty: f().withValidatorFactory(({ message: r }) => m(Ii.refine((t) => t, r)))
}, R = N.string(), Wi = {
required: f().withValidatorFactory(({ message: r }) => m(N.string({ required_error: q(r) }).nonempty(q(r)))),
nonEmpty: f().withValidatorFactory(({ message: r }) => m(R.nonempty(r))),
length: f().withParameter("length", "number", !0).withValidatorFactory(({ length: r, message: t }) => m(R.length(r, t))),
min: f().withParameter("limit", "number", !0).withValidatorFactory(({ limit: r, message: t }) => m(R.min(r, t))),
max: f().withParameter("limit", "number", !0).withValidatorFactory(({ limit: r, message: t }) => m(R.max(r, t))),
regex: f().withParameter("regex", "string", !0).withValidatorFactory(({ message: r, regex: t }) => m(R.regex(new RegExp(t), r))),
email: f().withValidatorFactory(({ message: r }) => m(R.email(r))),
url: f().withValidatorFactory(({ message: r }) => m(R.url(r))),
uuid: f().withValidatorFactory(({ message: r }) => m(R.uuid(r))),
ip: f().withValidatorFactory(({ message: r }) => m(R.ip(r))),
datetime: f().withParameter("precision", "number").withParameter("offset", "boolean").withValidatorFactory(({ message: r, offset: t, precision: e }) => m(R.datetime({ message: r, offset: t, precision: e }))),
includes: f().withParameter("value", "string", !0).withParameter("position", "number").withValidatorFactory(({ message: r, value: t, position: e }) => m(R.includes(t, { message: r, position: e }))),
startsWith: f().withParameter("value", "string", !0).withValidatorFactory(({ message: r, value: t }) => m(R.startsWith(t, r))),
endsWith: f().withParameter("value", "string", !0).withValidatorFactory(({ message: r, value: t }) => m(R.endsWith(t, r)))
}, Ki = {
required: f().withValidatorFactory(({ message: r }) => m(N.string({ required_error: q(r) }).nonempty(q(r))))
}, qi = {
string: Wi,
number: Li,
boolean: $i,
date: Mi,
time: Ki,
object: Bi,
array: ji,
enum: {}
}, Hi = () => Promise.resolve(!0), Ji = (r) => {
try {
return Ae("value, form", r);
} catch (t) {
return console.error(`Unable to compile the validation function, code:
${r}
`, t), Hi;
}
}, Ui = f().withParameter("code", void 0, !0, void 0, "code").withValidatorFactory(({ code: r, message: t }) => {
const e = Ji(r);
return async (n, o, i, s) => {
try {
return await e(n, s) ? !0 : t ?? !1;
} catch (l) {
throw console.error("Validation error", l), l;
}
};
});
function fr(r, t) {
if (Array.isArray(r) && ln(t) || cn(r) && an(t))
return r[t];
}
function Ke(r, t) {
if (!r.renderWhen)
return !0;
if (!mt(r.renderWhen)) {
const { value: e } = r.renderWhen;
if (typeof e == "string" && e.trim() === "")
return !0;
}
return pn(r.renderWhen, t) === !0;
}
var Rt, Ot, rt;
class Zi {
/**
* Creates the field with repeater data for the component.
* @param repeaterComponentData the component data.
* @param calculateValue the function for calculating the value of the field.
* @param createDataValidator the function to create a data validator.
* @param getInitialData the function to get initial data for the field.
* @param componentDataFactory the factory for creating ComponentData instances.
* @param deferFieldCalculation if true, then the calculated field must be explicitly initialized.
*/
constructor(t, e, n, o, i, s) {
v(this, Rt, void 0);
v(this, Ot, []);
/**
* @inheritDoc
*/
a(this, "error");
/**
* @inheritDoc
*/
a(this, "touched", !1);
/**
* @inheritDoc
*/
a(this, "valued");
/**
* The type of the field value.
*/
a(this, "valueType");
a(this, "dataValidator");
v(this, rt, void 0);
a(this, "initialData");
a(this, "componentStore");
a(this, "model");
/**
* @inheritDoc
*/
a(this, "setError", (t) => {
if (typeof t > "u" || t === null) {
this.clearError();
return;
}
if (!cn(t))
throw new Error(`Expected 'object' type, got '${typeof t}'`);
this.error = t[this.errorFieldName];
const e = t;
this.componentData.forEach((n, o) => {
const i = e == null ? void 0 : e[o];
n.allComponentFields.forEach(({ field: s, dataKey: l }) => s.setError(i == null ? void 0 : i[l]));
});
});
this.repeaterComponentData = t, this.calculateValue = e, this.createDataValidator = n, this.getInitialData = o, this.componentDataFactory = i, this.deferFieldCalculation = s;
const { model: l, store: c } = t;
if (this.model = l, this.componentStore = c, !l.valued)
throw new Error("'model.valued' is falsy");
if (!l.valueType)
throw new Error("'model.typeOfValue' is undefined");
this.valued = l.valued, this.valueType = l.valueType;
const d = "RepeaterField";
H(this, {
model: !1,
dataValidator: P.ref
}, { name: z(d, { key: c.key }), autoBind: !0 }), this.initialData = this.isComputed ? this.computedValue : this.initialDataValue, E(this, rt, [
Fr(
() => {
this.dataValidator = this.createDataValidator(
t,
this.valueType,
(u) => this.error = u
), Tr(() => {
var u;
(u = h(this, Rt)) == null || u.dispose(), E(this, Rt, this.dataValidator);
});
},
{ name: Mr(d, "setValidator", { key: c.key }) }
),
() => {
var u;
return (u = this.dataValidator) == null ? void 0 : u.dispose();
}
]), h(this, rt).push(
Pe(() => ({
isComputed: this.isComputed,
computedValue: this.computedValue,
initialDataValue: this.initialDataValue
}), (u) => {
this.initialData = u.isComputed ? u.computedValue : u.initialDataValue;
}, { name: z(d, { key: this.componentStore.key }) })
);
}
/**
* @inheritDoc
*/
get fieldType() {
return "repeater";
}
/**
* @inheritDoc
*/
init() {
if (this.deferFieldCalculation = !1, this.isComputed) {
setTimeout(() => {
this.initialData = this.computedValue, this.initFields(this.componentData);
}, 0);
return;
}
this.initialData = this.initialDataValue, this.initFields(this.componentData);
}
/**
* @returns the initial value for the field.
*/
get initialValue() {
var t;
return ((t = this.componentStore.props[this.valued]) == null ? void 0 : t.value) ?? this.defaultValue;
}
/**
* @returns the default value for the field.
*/
get defaultValue() {
var t;
return (t = this.model.defaultProps) == null ? void 0 : t[this.valued];
}
/**
* @inheritDoc
*/
dispose() {
h(this, rt).forEach((t) => t()), this.disposeOldComponentDatas();
}
/**
* @inheritDoc
*/
get value() {
const t = [];
return this.componentData.forEach((e) => {
t.push(e.data);
}), t;
}
/**
* @inheritDoc
*/
setValue(t) {
if (t === null || typeof t > "u" || Array.isArray(t)) {
this.initialData = t;
return;
}
}
/**
* @inheritDoc
*/
setTouched() {
this.touched = !0;
}
/**
* @inheritDoc
*/
async validate() {
var e, n;
if (!this.needValidate) {
this.clearError();
return;
}
const t = this.componentData.map((o) => o.validate());
await Promise.allSettled(t), await ((n = (e = this.dataValidator) == null ? void 0 : e.validate) == null ? void 0 : n.call(e, this.value));
}
/**
* @inheritDoc
*/
async getValidationResult() {
if (!this.needValidate)
return;
const t = [];
for (let e = 0; e < this.componentData.length; e++) {
const o = await this.componentData[e].getValidationResult();
t.push(o);
}
return t;
}
/**
* @inheritDoc
*/
reset() {
this.setValue(this.initialValue), this.componentData.forEach((t) => {
t.allFields.forEach((e) => e.reset());
}), this.clearError();
}
/**
* @inheritDoc
*/
clear() {
this.setValue(this.defaultValue), this.touched = !1, this.clearError();
}
/**
* @returns true if the field should be validated, false otherwise.
*/
get needValidate() {
return Ke(this.componentStore, this.repeaterComponentData.dataRoot);
}
/**
* Clears the error message for this field.
*/
clearError() {
this.error = void 0, this.componentData.forEach((t) => {
t.allFields.forEach((e) => e.setError(void 0));
});
}
/**
* @inheritDoc
*/
get errors() {
let t = !1;
const e = [];
if (this.componentData.forEach((n) => {
e.push(n.errors), t = t || n.hasErrors;
}), !!t)
return e;
}
/**
* @returns the component settings for the RepeaterItem component.
*/
get repeaterItemStore() {
var n;
const t = JSON.parse(JSON.stringify(this.componentStore)), e = new O(this.componentStore.key, "RepeaterItem");
return e.type = "RepeaterItem", e.children = t.children, e.renderWhen = (n = t.props) == null ? void 0 : n.itemRenderWhen, e;
}
/**
* @returns the number of elements in the repeater.
*/
get itemsCount() {
return !this.initialData || !Array.isArray(this.initialData) ? 0 : this.initialData.length;
}
/**
* @inheritDoc
*/
get componentData() {
const t = this.itemsCount, e = this.repeaterItemStore, n = this.componentStore.key, o = ct(this.componentStore), i = this.repeaterComponentData.dataRoot;
return Rr(() => {
const s = [];
for (let l = 0; l < t; l++) {
const c = new O(`${n}-context-item-${l}`, "Fragment");
c.props = { repeaterDataKey: { value: o } };
const d = this.componentDataFactory.createComponentData(c, !1);
d.index = l, d.parent = i, d.dataRootProvider = {
get dataRoot() {
return d;
}
}, d.getInitialData = () => {
const W = this.initialData;
if (Array.isArray(W))
return W[l];
};
const u = new O(`${n}-root-item-${l}`, "Fragment"), g = this.componentDataFactory.createComponentData(u, !1);
g.setParent(d);
const y = O.createFromObject(e);
y.key = `${n}-item-${l}`, this.componentDataFactory.createComponentData(y, !0).setParent(g), s.push(d);
}
return this.disposeOldComponentDatas(), E(this, Ot, s), this.deferFieldCalculation || this.initFields(s), s;
});
}
/**
* @returns the initial data value for the field.
*/
get initialDataValue() {
return this.getInitialData() ?? this.initialValue;
}
/**
* @returns the computed value for the field.
*/
get computedValue() {
if (this.deferFieldCalculation)
return this.initialDataValue;
const [, t] = this.calculateValue(this.componentStore, this.valued);
return t;
}
/**
* @returns true if the field value is calculated, otherwise false.
*/
get isComputed() {
return Br(this.componentStore.props[this.valued]);
}
initFields(t) {
t.map((e) => {
e.allFields.forEach((n) => n.init());
});
}
get errorFieldName() {
return `${ct(this.componentStore)}Error`;
}
disposeOldComponentDatas() {
h(this, Ot).forEach((t) => {
t.dispose();
});
}
}
Rt = new WeakMap(), Ot = new WeakMap(), rt = new WeakMap();
const V = (r) => r, w = (r) => {
throw new Error(`Cannot convert from '${r}'`);
}, _i = (r) => JSON.parse(r), mr = (r) => {
try {
const t = JSON.parse(r);
return ye(t) ? t : r;
} catch (t) {
return console.warn(t), r;
}
}, It = (r) => JSON.stringify(r), Bt = (r) => r.toString(), wt = (r) => (t) => t instanceof r ? t : w(t), Gi = (r) => {
if (r === "")
return;
const t = Number(r);
return isNaN(t) && w(r), t;
}, yr = (r) => new Date(r), he = (r) => r > 9 ? `${r}` : `0${r}`, Qi = (r) => {
const t = he(r.getHours()), e = he(r.getMinutes()), n = he(r.getSeconds());
return `${t}:${e}:${n}`;
}, Xi = {
string: {
string: V,
number: Gi,
boolean: (r) => r === "true",
object: mr,
array: _i,
enum: V,
date: yr,
time: V
},
number: {
string: Bt,
number: V,
boolean: (r) => r === 1,
object: mr,
array: w,
enum: V,
date: yr,
time: Bt
},
boolean: {
string: Bt,
number: (r) => r ? 1 : 0,
boolean: V,
object: w,
array: w,
enum: V,
date: w,
time: w
},
object: {
string: It,
number: w,
boolean: w,
object: V,
array: w,
enum: V,
date: w,
time: w
},
array: {
string: It,
number: w,
boolean: w,
object: w,
array: V,
enum: V,
date: w,
time: w
},
enum: {
string: It,
number: wt(Number),
boolean: wt(Boolean),
object: wt(Object),
array: wt(Array),
enum: V,
date: wt(Date),
time: It
},
date: {
string: Bt,
number: (r) => r.getTime(),
boolean: w,
object: w,
array: w,
enum: V,
date: V,
time: Qi
},
time: {
string: V,
number: w,
boolean: w,
object: w,
array: w,
enum: V,
date: w,
time: V
}
}, Yi = (r) => typeof r == "string" ? "string" : typeof r == "number" ? "number" : typeof r == "boolean" ? "boolean" : r instanceof Date ? "date" : Array.isArray(r) ? "array" : typeof r == "object" ? "object" : "enum", ts = (r, t) => {
var o;
if (r === null || typeof r > "u")
return;
const e = Yi(r), n = (o = Xi[e]) == null ? void 0 : o[t];
if (!n)
throw new Error(`Cannot convert ${r} from '${e}' to '${t}'`);
try {
return n(r);
} catch (i) {
throw new Error(`Cannot convert ${r} from '${e}' to '${t}'. ${i}.`);
}
};
var kt, nt;
class es {
/**
* Creates the field with form data for the component.
* @param componentData the component data.
* @param calculateValue the function for calculating the value of the field.
* @param createDataValidator the function to create a data validator.
* @param getInitialData the function to get initial data for the field.
* @param deferFieldCalculation if true, then the calculated field must be explicitly initialized.
*/
constructor(t, e, n, o, i) {
v(this, kt, void 0);
/**
* @inheritDoc
*/
a(this, "error");
/**
* @inheritDoc
*/
a(this, "touched", !1);
/**
* @inheritDoc
*/
a(this, "value");
/**
* @inheritDoc
*/
a(this, "valued");
/**
* The type of the field value.
*/
a(this, "valueType");
a(this, "dataValidator");
v(this, nt, void 0);
a(this, "componentStore");
a(this, "model");
/**
* Sets the error value.
* @param error the error value to be set. If the error is `undefined` or `null`, the error value will be reset to `undefined`.
* @throws {Error} throws an error if the provided value is not a string, undefined, or null.
*/
a(this, "setError", (t) => {
if (typeof t == "string")
this.error = t;
else if (typeof t > "u" || t === null)
this.error = void 0;
else
throw new Error(`Expected 'string | undefined | null' type, got '${typeof t}'`);
});
this.componentData = t, this.calculateValue = e, this.createDataValidator = n, this.getInitialData = o, this.deferFieldCalculation = i;
const { model: s, store: l } = t;
if (this.componentStore = l, this.model = s, !s.valued)
throw new Error("'model.valued' is falsy");
if (!s.valueType)
throw new Error("'model.typeOfValue' is undefined");
this.valued = s.valued, this.valueType = s.valueType;
const c = "SimpleField";
H(this, {
model: !1,
dataValidator: P.ref
}, { name: z(c, { key: l.key }), autoBind: !0 }), this.value = this.isComputed ? this.computedValue : this.initialDataValue, E(this, nt, [
Fr(
() => {
this.dataValidator = this.createDataValidator(
t,
this.valueType,
(d) => this.error = d
), Tr(() => {
var d;
(d = h(this, kt)) == null || d.dispose(), E(this, kt, this.dataValidator);
});
},
{ name: Mr(c, "setValidator", { key: l.key }) }
),
() => {
var d;
return (d = this.dataValidator) == null ? void 0 : d.dispose();
}
]), h(this, nt).push(
Pe(() => ({
isComputed: this.isComputed,
computedValue: this.computedValue,
initialDataValue: this.initialDataValue
}), (d) => {
this.value = d.isComputed ? d.computedValue : d.initialDataValue;
}, { name: z(c, { key: this.componentStore.key }) })
);
}
/**
* @inheritDoc
*/
get fieldType() {
return "simple";
}
/**
* @inheritDoc
*/
init() {
if (this.deferFieldCalculation = !1, this.isComputed) {
setTimeout(() => {
this.value = this.computedValue;
}, 0);
return;
}
this.value = this.initialDataValue;
}
/**
* @returns the initial value for the field.
*/
get initialValue() {
var t;
return ((t = this.componentStore.props[this.valued]) == null ? void 0 : t.value) ?? this.defaultValue;
}
/**
* @returns the default value for the field.
*/
get defaultValue() {
var t;
return (t = this.model.defaultProps) == null ? void 0 : t[this.valued];
}
/**
* @inheritDoc
*/
dispose() {
h(this, nt).forEach((t) => t());
}
/**
* @inheritDoc
*/
setValue(t) {
var e, n, o;
if (this.innerSetValue(ts(t, this.valueType)), !this.needValidate) {
this.clearError();
return;
}
((e = this.componentStore.schema) == null ? void 0 : e.autoValidate) !== !1 && ((o = (n = this.dataValidator) == null ? void 0 : n.sendValidationEvent) == null || o.call(n, this.value));
}
/**
* @inheritDoc
*/
setTouched() {
this.touched = !0;
}
/**
* @inheritDoc
*/
async validate() {
var t, e;
if (!this.needValidate) {
this.clearError();
return;
}
await ((e = (t = this.dataValidator) == null ? void 0 : t.validate) == null ? void 0 : e.call(t, this.value));
}
/**
* @inheritDoc
*/
async getValidationResult() {
var e, n;
if (!this.needValidate)
return;
const t = await ((n = (e = this.dataValidator) == null ? void 0 : e.getValidationResult) == null ? void 0 : n.call(e, this.value));
return t == null ? void 0 : t.map(({ message: o }) => o);
}
/**
* @inheritDoc
*/
reset() {
this.innerSetValue(this.initialValue ?? this.defaultValue), this.clearError();
}
/**
* @inheritDoc
*/
clear() {
this.innerSetValue(this.defaultValue), this.touched = !1, this.clearError();
}
/**
* @returns true if the field should be validated, false otherwise.
*/
get needValidate() {
return Ke(this.componentStore, this.componentData.dataRoot);
}
/**
* Clears the error message for this field.
*/
clearError() {
this.error = void 0;
}
/**
* @returns the initial data value for the field.
*/
get initialDataValue() {
return this.getInitialData() ?? this.initialValue;
}
/**
* @returns the computed value for the field.
*/
get computedValue() {
if (this.deferFieldCalculation)
return this.initialDataValue;
const [, t] = this.calculateValue(this.componentStore, this.valued);
return t;
}
/**
* @returns true if the field value is calculated, otherwise false.
*/
get isComputed() {
return Br(this.componentStore.props[this.valued]);
}
/**
* Sets the value of the field without converting it.
* @param value the value to be set.
*/
innerSetValue(t) {
this.value = t;
}
}
kt = new WeakMap(), nt = new WeakMap();
class Fn {
/**
* Creates the nested form field with form data for the component.
* @param componentStore the component settings.
* @param viewerStore viewerStore the form viewer settings.
*/
constructor(t, e) {
/**
* @inheritDoc
*/
a(this, "valued", "");
/**
* @inheritDoc
*/
a(this, "touched", !1);
/**
* @inheritDoc
*/
a(this, "setError", (t) => {
if (!t)
return;
if (typeof t != "object")
throw new Error(`Expected 'object' type, got '${typeof t}'`);
const e = t;
this.form.allComponentFields.forEach(({ field: n, dataKey: o }) => {
if (e[o])
return n.setError(e[o]);
if (n.storeDataInParentForm)
return n.setError(e);
});
});
this.componentStore = t, this.viewerStore = e, H(
this,
void 0,
{ name: z("FormField", { key: t.key }), autoBind: !0 }
);
}
/**
* @inheritDoc
*/
get fieldType() {
return "simple";
}
/**
* @inheritDoc
*/
get storeDataInParentForm() {
return Sn(this.componentStore);
}
/**
* @inheritDoc
*/
get value() {
return this.form.data;
}
/**
* @inheritDoc
*/
dispose() {
this.viewerStore.dispose();
}
/**
* @inheritDoc
*/
clear() {
this.form.clear(), this.touched = !1;
}
/**
* @inheritDoc
*/
reset() {
this.form.reset();
}
/**
* @inheritDoc
*/
setTouched() {
this.touched = !0;
}
/**
* @inheritDoc
*/
setValue(t) {
if (!t) {
this.form.reset();
return;
}
if (typeof t != "object")
throw new Error(`Expected 'object' type, got '${typeof t}'`);
const e = t;
this.form.allComponentFields.forEach(({ field: n, dataKey: o }) => {
const i = e[o];
typeof i > "u" ? n.reset() : n.setValue(i);
});
}
/**
* @inheritDoc
*/
async validate() {
await this.form.validate();
}
/**
* @inheritDoc
*/
async getValidationResult() {
return await this.form.getValidationResult();
}
/**
* @inheritDoc
*/
init() {
this.form.allFields.forEach((t) => t.init());
}
/**
* @returns the form for the field.
*/
get form() {
return this.viewerStore.form.componentTree;
}
/**
* @inheritDoc
*/
get errors() {
return this.form.errors;
}
}
function rs(r, t) {
return !r || !t || !mt(r) && typeof r.value == "string" && r.value.trim() === "" ? !0 : pn(r, t) === !0;
}
function ns(r, t) {
return t.key === "code" ? -1 : t.key === "required" ? 1 : 0;
}
const os = () => !0;
function is(r, t) {
if (!t || !t.validations || !t.validations.length)
return;
const e = [...t.validations].sort(ns), n = (o) => {
var i;
if (!o.type) {
const s = r.internal[o.key], l = s.validatorFactory(o.args ?? {});
return { settings: o, validator: l, params: s.params };
}
if (o.type === "custom") {
const s = (i = r.custom) == null ? void 0 : i[o.key];
if (s)
return { settings: o, validator: s.validate, params: s.params };
}
return console.warn(`Cannot find rule, key: '${o.key}', type: '${o.type}'`), { settings: o, validator: os };
};
return e.map(n);
}
function ss(r, t) {
const e = is(r, t);
return async (n, o, i) => {
if (!e)
return;
const s = [];
for (const { settings: l, validator: c, params: d } of e) {
const u = {};
if (!rs(l.validateWhen, i == null ? void 0 : i()))
continue;
d == null || d.filter((b) => typeof b.default < "u").map((b) => u[b.key] = b.default), Object.assign(u, l.args);
const g = c(n, o, u, i == null ? void 0 : i()), y = ie(g) ? await g : g;
y !== !0 && s.push({
settings: l,
message: typeof y == "string" ? y : u.message
});
}
return s;
};
}
function as(r) {
return function(t) {
return ss(r, t);
};
}
function ls(r, t) {
let e = 1;
for (; e < 1e4; ) {
const o = `${r}${e}`;
if (!t.has(o))
return o;
e++;
}
const n = (/* @__PURE__ */ new Date()).getTime();
return `${r}_${n}`;
}
class pe {
/**
* Creates a new instance of Form.
* @param componentTree the root component of the form.
* @param localization the localization of the form.
* @param actions the form custom actions.
* @param languages the localization languages of the form.
* @param defaultLanguage the default localization language of the form.
*/
constructor(t, e, n, o, i) {
/**
* Root component of the form.
*/
a(this, "componentTree");
/**
* Localization of the form.
*/
a(this, "localization");
/**
* Localization languages of the form.
*/
a(this, "languages", []);
/**
* The set of action definitions.
*/
a(this, "actions");
/**
* Properties of the component displaying the error.
*/
a(this, "errorProps", {});
/**
* The type name of the component displaying the tooltip.
*/
a(this, "tooltipType");
/**
* The type name of the component displaying the error.
*/
a(this, "errorType");
/**
* Default localization language of the form.
*/
a(this, "defaultLanguage");
/**
* The form validator.
*/
a(this, "formValidator");
this.componentTree = t, this.localization = e, this.actions = n, this.languages = o, this.defaultLanguage = i, this.componentTree.events.onBeforeDelete.subscribe(this.onComponentDataBeforeDelete.bind(this)), this.componentTree.events.onAfterKeyChanged.subscribe(this.onComponentDataAfterKeyChanged.bind(this)), H(this);
}
/**
* @returns the actions names array.
*/
get actionNames() {
return Object.keys(this.actions);
}
/**
* @returns the form validator function.
*/
get formValidatorFunction() {
if (this.formValidator)
return Ae("formData", this.formValidator);
}
/**
* Initializes form fields.
*/
initFields() {
this.componentTree.allFields.forEach((t) => t.init());
}
/**
* Disposes the form. Disposes all the components and localization.
*/
dispose() {
this.componentTree.dispose();
}
/**
* Removes the action from the form.
* @param name the action name to remove.
*/
removeAction(t) {
delete this.actions[t], this.removeCodeActionBinding(t, this.componentTree.store);
}
/**
* Changes the existing action to the new one, adds the action if the existing action is not found.
* @param oldActionName the existing action name.
* @param newAction the new named action.
*/
updateOrAddAction(t, e) {
this.actions[e.name] = e.actionDefinition, this.rebindActionHandlers(this.componentTree.store, t, e), t !== e.name && delete this.actions[t];
}
/**
* Clones the action.
* @param namedAction the named action to clone.
*/
cloneAction(t) {
if (!this.actions)
return;
const e = new Set(this.actionNames), n = JSON.parse(JSON.stringify(t.actionDefinition)), o = ls(`${t.name}_`, e);
this.actions[o] = F.createFromObject(n);
}
rebindActionData(t, e) {
t.name = e.name;
const n = t.args;
if (!n)
return;
const o = new Set(Object.keys(e.actionDefinition.params));
Object.keys(n).forEach((i) => {
o.has(i) || delete n[i];
});
}
rebindActionHandlers(t, e, n) {
var i;
const o = t.events;
o && Object.keys(o).forEach((s) => {
const l = o[s];
l == null || l.filter((c) => c.type === "code" && c.name === e).forEach((c) => this.rebindActionData(c, n));
}), (i = t.children) == null || i.forEach((s) => {
this.rebindActionHandlers(s, e, n);
});
}
removeCodeActionBinding(t, e) {
var o;
const n = e.events;
n && Object.keys(n).forEach((i) => {
const s = n[i];
s.length && (n[i] = s.filter((l) => !(l.type === "code" && l.name === t)));
}), (o = e.children) == null || o.forEach((i) => this.removeCodeActionBinding(t, i));
}
onComponentDataBeforeDelete(t) {
this.localization.removeLocalization(t.key);
}
onComponentDataAfterKeyChanged(t, { oldKey: e, newKey: n }) {
this.localization.changeComponentKey(e, n);
}
}
const cs = "LocalizationStore";
var ee, Tn;
class ds {
constructor(t, e) {
v(this, ee);
this.languageFullCode = t, this.localizationStore = e, H(this, void 0, { name: z("FluentBundleHolder") });
}
get fluentBundle() {
const t = this.localizationStore.value[this.languageFullCode], e = new xr(this.languageFullCode);
return t && C(this, ee, Tn).call(this, t).forEach((o) => {
const i = e.addResource(new kr(o));
i.length > 0 && (console.error(`Unable to add localization resource: ${o}`), i.forEach(console.error));
}), e;
}
}
ee = new WeakSet(), Tn = function(t) {
const e = [];
return Object.entries(t).forEach(([n, o]) => {
Object.entries(o ?? {}).forEach(([i, s]) => {
Object.entries(s ?? {}).forEach(([l, c]) => {
c && e.push(`${n}_${i}_${l} = ${zr(c)}`);
});
});
}), e;
};
class fe {
/**
* The constructor.
* @param value the initial localization value.
*/
constructor(t = {}) {
a(this, "localizationCache", /* @__PURE__ */ new Map());
/**
* The localization data.
*/
a(this, "value", {});
H(this, void 0, { name: z(cs) }), this.value = t;
}
/**
* Returns value of localization constant.
* @param languageFullCode the full code (en-US, en-GB etc.) of the language we are looking to localize.
* @param componentKey the component we are looking to localize.
* @param propertyName the property name we are looking to localize.
* @param type the type of localization.
* @returns the value of localization constant.
*/
getLocalization(t, e, n, o) {
var l, c, d;
const i = D(e), s = D(n);
return (d = (c = (l = this.value[t]) == null ? void 0 : l[i]) == null ? void 0 : c[o]) == null ? void 0 : d[s];
}
/**
* Sets localization for component property.
* @param languageFullCode the full code (en-US, en-GB etc.) of the language in which localization will be set.
* @param componentKey the component key that requires localization.
* @param propertyName the component's property name to be localized.
* @param type the type of localization.
* @param value the localization value.
*/
setLocalization(t, e, n, o, i) {
var c, d, u;
const s = D(e), l = D(n);
(c = this.value)[t] ?? (c[t] = {}), (d = this.value[t])[s] ?? (d[s] = {}), (u = this.value[t][s])[o] ?? (u[o] = {}), this.value[t][s][o][l] = i;
}
/**
* Removes localization for component.
* @param componentKey the component key that requires localization removal.
*/
removeLocalization(t) {
const e = D(t);
for (const n of this.langCodes)
delete this.value[n][e], Object.keys(this.value[n]).length === 0 && delete this.value[n];
}
/**
* Removes localization for component with specified type.
* @param componentKey the component key that requires localization removal.
* @param type the localization type.
*/
removeLocalizationForType(t, e) {
const n = D(t);
for (const o of this.langCodes)
this.value[o][n] && (delete this.value[o][n][e], Object.keys(this.value[o][n]).length === 0 && delete this.value[o][n], Object.keys(this.value[o]).length === 0 && delete this.value[o]);
}
/**
* Checks that the specified language exists in the localization.
* @param languageFullCode The full code (en-US, en-GB etc.) of the language to be checked.
* @returns true if the specified language exists in the localization.
*/
hasLanguage(t) {
return !!this.value[t];
}
/**
* Checks that the specified property has localization.
* @param componentKey the component we are looking to localize.
* @param propertyName the component's property name to be localized.
* @param type the type of localization.
* @returns true if the specified property has localization in at least one language.
*/
hasLocalization(t, e, n) {
const o = D(t), i = D(e);
return Object.values(this.value).some((s) => {
var l, c;
return (c = (l = s == null ? void 0 : s[o]) == null ? void 0 : l[n]) == null ? void 0 : c[i];
});
}
/**
* If the FluentBundle for the specified language is found, this function returns it.
* Otherwise, an empty FluentBundle is returned.
* @param languageFullCode the full code (en-US, en-GB etc.) of the language to get fluent bundle.
* @returns the FluentBundle for the specified language.
*/
getFluentBundle(t) {
const e = this.localizationCache.get(t) ?? new ds(t, this);
return this.localizationCache.has(t) || this.localizationCache.set(t, e), e.fluentBundle;
}
/**
* Changes the component key for all languages in the value object.
* @param oldComponentKey the old component key to be replaced.
* @param newComponentKey the new component key to replace the old component key.
*/
changeComponentKey(t, e) {
const n = D(t), o = D(e);
for (const i of this.langCodes) {
const s = this.value[i][n];
s && (this.value[i][o] = s, delete this.value[i][n]);
}
}
/**
* Retrieves the localization values for a given component key.
* @param componentKey the key of the component to retrieve localization for.
* @returns the object containing the localization values for the component in each supported language.
*/
getLocalizationForComponent(t) {
const e = D(t), n = {};
for (const o of this.langCodes) {
const i = this.value[o][e];
i && (n[o] = {}, n[o][t] = i);
}
return n;
}
/**
* Inserts the localization values for a given component key. Replaces the old component key with the new component key.
* @param localization the localization object for insertion.
* @param oldComponentKey the old component key that needs to be replaced.
* @param newComponentKey the new component key to be added.
*/
addLocalizationWithNewKey(t, e, n) {
const o = D(n), i = Object.keys(t);
for (const s of i) {
const l = t[s][e];
l && (this.value[s][o] = l);
}
}
/**
* @returns the available language codes.
*/
get langCodes() {
return Object.keys(this.value);
}
}
var ve = /* @__PURE__ */ ((r) => (r.version1 = "1", r))(ve || {});
const us = {
RsDatePicker: ["calendarDefaultDate", "defaultValue", "value"],
RsCalendar: ["defaultValue", "value"]
};
function Rn(r, t, e, n) {
var i;
let o = t(e, r);
return (i = r[n]) == null || i.forEach((s) => {
o = Rn(s, t, o, n);
}), o;
}
var xt, At, be;
const qe = class qe {
/**
* Creates form viewer settings.
* @param formViewerPropsStore the form viewer store settings.
* @param componentStateFactory the factory for creating component states.
* @param parentStore the form viewer settings, used in templates.
* @param getInitialData the function to get initial data for the Store.
*/
constructor(t, e, n, o) {
/**
* Changes the form to the component with an error description.
* @param e the error.
*/
v(this, At);
/**
* The currently selected language.
*/
a(this, "selectedLanguage");
/**
* Current display resolution type.
*/
a(this, "viewMode", "desktop");
/**
* The form.
*/
a(this, "form");
/**
* Models for templates that have not been explicitly defined.
*/
v(this, xt, /* @__PURE__ */ new Map());
/**
* The loading form error.
*/
a(this, "formLoadError");
this.formViewerPropsStore = t, this.componentStateFactory = e, this.parentStore = n, this.getInitialData = o;
const i = this.createDataRoot(), s = new fe();
this.form = new pe(i, s, {}, [], Kt), Sr(this, {
form: P,
viewMode: !0,
selectedLanguage: !0,
clear: !0,
parentStore: P.ref,
initialDataSlice: !0,
formLoadError: !0
}, { name: z("ViewerStore") });
}
/**
* @returns the Record with the common actions.
*/
get commonActions() {
return Ri;
}
/**
* Returns an action by the specified action name and action type.
* @param name the action name.
* @param type the action type.
* @returns the action.
*/
getAction(t, e) {
var o;
let n;
switch (e) {
case "common":
n = this.commonActions[t];
break;
case "code":
n = this.form.actions[t];
break;
case "custom":
n = (o = this.formViewerPropsStore.actions) == null ? void 0 : o[t];
break;
}
if (!n)
throw Error(`Action '${t}' with type '${e}' not found!`);
return n;
}
/**
* @inheritDoc
*/
get formData() {
return this.form.componentTree;
}
/**
* Clears the form in Form Viewer.
*/
clear() {
const t = this.form, e = this.createDataRoot(), n = new fe();
this.form = new pe(e, n, {}, t.languages, t.defaultLanguage), t.dispose();
}
/**
* @inheritDoc
*/
dispose() {
this.form.dispose();
}
/**
* @inheritDoc
*/
get initialDataSlice() {
var t;
return this.parentStore ? (t = this.getInitialData) == null ? void 0 : t.call(this) : this.formViewerPropsStore.initialData;
}
/**
* @inheritDoc
*/
get showAllValidationErrors() {
var t;
return (t = this.formViewerPropsStore) == null ? void 0 : t.showAllValidationErrors;
}
/**
* @inheritDoc
*/
reduceScreen(t, e) {
return Rn(this.form.componentTree, t, e, "children");
}
/**
* Searches for an action, returns definition for the found action.
* @param actionData the action's data.
* @returns the action definition.
* @throws Error, if action was not found.
*/
findAction(t) {
return this.getAction(t.name, t.type);
}
/**
* Returns model for the specified type.
* @param type the component type.
* @returns the model for the specified type.
*/
getModel(t) {
const e = this.formViewerPropsStore.view.find(t);
return e || (pr(t) ? h(this, xt).get(t) ?? this.addTemplateModel(t) : vi(`Type '${t}' is not found!`));
}
addTemplateModel(t) {
const e = Pn(t), n = xn(e);
return h(this, xt).set(n.type, n), n;
}
/**
* @deprecated
* Loads a form by form name and sets that form in the form viewer.
* @param getForm the function that loads the form.
* @param formName the form name.
*/
loadForm(t, e) {
if (t)
try {
const n = t(e);
if (ie(n)) {
n.then(this.applyStringForm.bind(this)).catch(C(this, At, be).bind(this));
return;
}
this.applyStringForm(n);
} catch (n) {
C(this, At, be).call(this, n);
}
}
/**
* @inheritDoc
*/
createComponentData(t, e = !1) {
const n = this.getModel(t.type), o = (s) => this.createComponentData(s, e), i = new fo(t, n, o, this.getFormValidatorsResult.bind(this));
return i.field = this.createField(i, e), i.componentState = this.componentStateFactory(i, this), i;
}
/**
* Returns the object with validators for the specified value type.
* @param type the value type.
* @returns the object with validators for the specified value type.
*/
getValidationRules(t) {
var e;
return {
custom: (e = this.formViewerPropsStore.validators) == null ? void 0 : e[t],
internal: {
...qi[t],
code: Ui
}
};
}
createField(t, e) {
const { model: n, store: o } = t;
if (!n.valued)
return;
const i = (u, g) => this.calculateProperty(t, u, g), s = (u, g, y) => this.createDataValidator(u, g, y), l = () => fr(t.initialData, ct(o));
if (n.kind === "repeater")
return new Zi(t, i, s, l, this, e);
if (!pr(n.type))
return new es(t, i, s, l, e);
const c = () => Sn(o) ? t.initialData : fr(t.initialData, ct(o)), d = new qe(this.formViewerPropsStore.clone(), this.componentStateFactory, this, c);
return new Fn(o, d);
}
/**
* Populates the value of this store with the values of the saved form.
* @param text saved form value.
*/
applyStringForm(t) {
try {
const e = JSON.parse(t);
this.fixPropertyTypes(e.form), this.applyPersistedForm(e), this.formLoadError = void 0;
} catch (e) {
this.formLoadError = (e == null ? void 0 : e.message) ?? e, console.error(e);
}
}
fixPropertyTypes(t) {
var n;
t.props || (t.props = {});
const e = us[t.type];
e == null || e.forEach((o) => this.fixDateProperty(t, o)), (n = t.children) == null || n.forEach((o) => this.fixPropertyTypes(o));
}
fixDateProperty(t, e) {
var o;
const n = (o = t.props[e]) == null ? void 0 : o.value;
(an(n) || ln(n)) && (t.props[e].value = new Date(n));
}
/**
* Populates the value of this store with the values of the saved form.
* @param persistedForm saved form value.
*/
applyPersistedForm(t) {
const e = this.form, n = t.version;
typeof n < "u" && n !== ve.version1 && console.warn(`An unsupported version of form '${n}' has been detected. An attempt will be made to upload the form as version '${ve.version1}'.`), Rr(() => {
var u;
const o = O.createFromObject(t.form), i = this.createComponentData(o, !0);
i.getInitialData = () => this.initialDataSlice;
const s = new fe(U({}, t.localization)), l = ((u = t.languages) == null ? void 0 : u.map(se.clone)) ?? [], c = l.find((g) => g.fullCode === t.defaultLanguage) ?? Kt, d = Io(t.actions);
this.form = new pe(i, s, d, l, c), this.form.errorProps = t.errorProps ?? {}, this.form.tooltipType = t.tooltipType, this.form.errorType = t.errorType, this.form.formValidator = t.formValidator;
}), this.form.componentTree.unifyTree(), this.form.initFields(), e.dispose();
}
/**
* @returns the current display language.
*/
get displayedLanguage() {
if (this.parentStore)
return this.parentStore.displayedLanguage;
if (this.formViewerPropsStore.propsLanguage) {
const t = Oi(this.form.languages, this.formViewerPropsStore.propsLanguage);
if (t)
return t;
}
return this.selectedLanguage ?? this.form.defaultLanguage;
}
/**
* @inheritDoc
*/
localizeComponent(t, e, n) {
return this.formViewerPropsStore.localizer ? this.formViewerPropsStore.localizer(n, this.displayedLanguage) : Ai(this.form, e, this.displayedLanguage, n, t);
}
/**
* @inheritDoc
*/
localizeErrorMessages(t, e, n) {
if (n)
return n.map((o) => Ni(this.form, t, this.displayedLanguage, e, o.settings.key) ?? Me(o)).join(" ");
}
calculateProperty(t, e, n) {
const o = t.dataRoot;
return zi(
e,
n,
o,
(i, s) => this.localizeComponent(i, o, s)
);
}
/**
* Creates a data validator for the field.
* @param componentData the component data.
* @param valueType the field's data type.
* @param onError the callback function called when the validation error text is set.
* @returns the data validator.
*/
createDataValidator(t, e, n) {
const o = this.getValidationRules(e), i = (s) => this.localizeErrorMessages(t.dataRoot, t.store, s);
return ge.create(
this,
() => t.dataRoot,
as(o),
t.store.schema,
n,
i
);
}
createDataRoot() {
const t = new O(ht.name, ht.type), e = this.createComponentData(t);
return e.getInitialData = () => this.initialDataSlice, e;
}
async getFormValidatorsResult() {
var s;
const t = this.formViewerPropsStore.formValidators, e = this.form.formValidatorFunction, n = [];
t && n.push(...t.map((l) => l(this.form.componentTree.data))), e && n.push(e(((s = this.form.componentTree) == null ? void 0 : s.data) ?? {}));
const o = await Promise.allSettled(n);
return (o == null ? void 0 : o.map((l) => {
if (l.status === "rejected") {
console.error(l.reason);
return;
}
return l.value;
})).filter((l) => typeof l < "u");
}
};
xt = new WeakMap(), At = new WeakSet(), be = function(t) {
console.error(t), this.formLoadError = (t == null ? void 0 : t.message) ?? t;
const e = wn(t);
this.applyPersistedForm({
form: e,
localization: {},
defaultLanguage: Kt.fullCode,
languages: []
});
};
let we = qe;
const gr = /* @__PURE__ */ new Map();
function hs(r) {
const t = gr.get(r);
if (t)
return t;
const e = new Function("parentProps", r);
return gr.set(r, e), e;
}
function ps(r, t) {
var o;
const e = (o = r.slotCondition) == null ? void 0 : o.trim();
if (!e)
return !0;
const n = hs(e);
try {
return n(t);
} catch (i) {
return console.warn(i), !1;
}
}
const fs = "children";
function ms(r, t, e) {
var d;
const n = ((d = r.field) == null ? void 0 : d.fieldType) === "repeater" ? r.field.componentData : r.children, o = t, i = {}, s = ro(n, (u) => u.store.slot || fs), l = (u) => ps(u.store, e), c = (u) => Ke(u.store, r.dataRoot);
for (const [u, g] of Object.entries(s)) {
const y = g.filter(l).filter(c);
y.length && (i[u] = r.model.propsBindingTypes[u] === "array" ? y.map((b, W) => /* @__PURE__ */ p(o, { data: [b] }, W)) : /* @__PURE__ */ p(o, { data: y }));
}
return i;
}
function ys(r) {
const [t, e] = Ve();
return K(() => {
const n = r();
return e(n), () => n.dispose();
}, []), t;
}
const gs = (r) => {
const { store: t } = r, e = r.props;
return K(() => {
var n;
(n = e.onFormDataChange) == null || n.call(e, t.formData);
}, [t.formData.data, t.formData.errors]), K(() => {
t.formViewerPropsStore.applyProps(e);
}, [
e.initialData,
e.view,
e.validators,
e.formValidators,
e.localize,
e.language,
e.actions,
e.errorWrapper,
e.readOnly,
e.disabled,
e.componentWrapper
]), null;
}, vs = k("Notifier", gs), ws = ({
children: r,
props: { viewerRef: t, ...e },
store: n
}) => (Kn(t, () => n, [n]), /* @__PURE__ */ ne(dn, { value: e, children: [
/* @__PURE__ */ p(vs, { store: n, props: e }),
/* @__PURE__ */ p(Re, { value: n, children: r })
] })), On = k("ExistingStoreProvider", ws), bs = (r, t) => {
function e(o) {
return t.localizeComponent("component", r.dataRoot, o);
}
function n(o, i) {
return ms(o, gn, i);
}
return new mn(r, t, e, n);
}, Cs = ({ children: r, props: t }) => {
const e = Ee(() => new we(new Be(t), bs), [t]), n = ys(e);
return n ? /* @__PURE__ */ p(On, { children: r, props: t, store: n }) : null;
}, Vs = k("FactoryStoreProvider", Cs), Es = (r) => {
const t = Vr(bo);
return t ? /* @__PURE__ */ p(On, { children: r.children, props: r.props, store: t }) : /* @__PURE__ */ p(Vs, { children: r.children, props: r.props });
}, Ds = k("ViewerStoreProvider", Es);
Gn({ enforceActions: "never" });
const Ps = pt`
display: flex;
flex-direction: column;
flex: 1;
gap: 5px;
`, Ss = (r) => {
const { className: t, children: e, ...n } = r, o = L(() => ft(Ps, t), [t]);
return /* @__PURE__ */ p("div", { className: o, ...n, children: e });
}, Fs = (r) => /* @__PURE__ */ p(Jo, { children: /* @__PURE__ */ p(Ds, { props: r, children: /* @__PURE__ */ p(Ho, { children: /* @__PURE__ */ p(Ss, { children: /* @__PURE__ */ p(Di, {}) }) }) }) }), Ts = k("FormViewer", Fs), Rs = {
fontSize: "xx-large",
color: "red"
}, Os = ({ children: r }) => /* @__PURE__ */ p("span", { style: Rs, children: r }), [
/**
* **Internal use only.**
*/
ks,
/**
* **Internal use only.**
*/
xs
] = yt("TemplateContext"), As = (r) => {
const t = Q(), e = Z(), n = L(() => {
const s = {
formName: Pn(e.store.type),
onFormDataChange: void 0,
formValidators: void 0,
disabled: r.disabled,
readOnly: r.readOnly
};
return Object.assign({}, t, s);
}, [e.store.type, t, r]), o = L(() => ({ templateProps: r, viewerProps: t, data: e }), [r, t, e]);
if (!n.getForm)
return /* @__PURE__ */ ne(Os, { children: [
"Please define the ",
/* @__PURE__ */ p("code", { children: "getForm" }),
" property!"
] });
if (!(e.field instanceof Fn))
return null;
const i = e.field.viewerStore;
return /* @__PURE__ */ p(xs, { value: o, children: /* @__PURE__ */ p(Re, { value: i, children: /* @__PURE__ */ p(Ts, { ...n }) }) });
}, kn = ut(oe), Ns = dt(kn);
function xn(r) {
const t = Dn(r), e = { name: r, storeDataInParentForm: !0 };
return new M(
As,
r,
void 0,
t,
"object",
e,
Ns,
void 0,
t,
"template",
"readOnly",
void 0,
void 0,
"disabled"
);
}
const zs = ({ parentStore: r }) => {
const { key: t } = Z(), { viewerProps: e, data: n, templateProps: o } = ks();
return /* @__PURE__ */ p(Re, { value: r, children: /* @__PURE__ */ p(dn, { value: e, children: /* @__PURE__ */ p(Wr, { value: n, children: o[t] }) }) });
}, js = k("SlotContent", zs), $s = {
backgroundColor: "rgb(150, 150, 150, 25%)",
padding: 5
}, Ms = () => {
const { key: r } = Z();
return /* @__PURE__ */ ne("div", { style: $s, children: [
"Slot: '",
r,
"'"
] });
}, Ls = k("SlotPlaceholder", Ms), An = () => {
const { parentStore: r } = I();
return r ? /* @__PURE__ */ p(js, { parentStore: r }) : /* @__PURE__ */ p(Ls, {});
};
An.displayName = "Slot";
const Gt = new M(
An,
"Slot",
void 0,
void 0,
void 0,
void 0,
void 0,
void 0,
void 0,
"slot"
), Is = new G(
Gt.type,
[],
[],
[],
Mt,
void 0,
void 0,
Gt.kind
), Bs = ke.default(!0).calculable(!1).hinted("Store data in parent form").named("Store data in parent form");
function Ws(r) {
const t = Dn(r);
return new G(
t,
gt({
storeDataInParentForm: Bs,
disabled: Qr,
readOnly: Gr
}),
[],
kn,
Mt,
void 0,
void 0,
"template"
);
}
const Nn = ({ children: r }) => /* @__PURE__ */ p(zt, { children: r });
Nn.displayName = "Fragment";
const Ks = new M(
Nn,
"Fragment",
void 0,
void 0,
void 0,
void 0,
void 0,
void 0,
void 0,
"container"
);
var ot, it, Nt, st, qt;
const He = class He {
/**
* Creates an instance of the {@link View}.
* @param models the components metadata.
*/
constructor(t = []) {
/**
* Sets a CSS loader for the specified BiDi direction.
* @param biDi the BiDi direction.
* @param loader the loader function that returns a Promise.
*/
v(this, st);
v(this, ot, /* @__PURE__ */ new Map());
v(this, it, /* @__PURE__ */ new Map());
v(this, Nt, new Array());
/**
* Adds a wrapper to the list of viewers for this viewer wrapper.
* @param wrapper the viewer wrapper to be added. The wrapper is a component that wraps the form viewer.
* @returns the {@link View} instance.
*/
a(this, "withViewerWrapper", (t) => (h(this, Nt).push(t), this));
this.define(ht), this.define(Zt), this.define(Gt), this.define(Ks), this.define(Ut), this.define(vo), t.forEach(this.define.bind(this));
}
/**
* Static wrapper for the {@link View} constructor.
* @param models the components metadata.
* @returns the {@link View} instance.
*/
static create(t) {
return new He(t);
}
/**
* Defines the component's metadata for the form viewer.
* @param model the component's metadata.
*/
define(t) {
h(this, ot).set(t.type, t);
}
/**
* Returns the component's metadata for the form viewer for the specified type.
* @param type the component type.
* @returns the component metadata for the form viewer for the specified type.
*/
get(t) {
const e = this.find(t);
if (e)
return e;
throw new Error(`Type '${t}' is not found!`);
}
/**
* Returns the component's metadata for the form viewer for the specified type.
* @param type the component type.
* @returns the component metadata for the form viewer for the specified type or undefined.
*/
find(t) {
return h(this, ot).get(t);
}
/**
* @returns all component metadata for the form viewer.
*/
all() {
return [...h(this, ot).values()];
}
/**
* Retrieves the viewer wrappers array.
* @returns the viewer wrappers array.
*/
get viewerWrappers() {
return [...h(this, Nt)];
}
/**
* Applies the given CSS loader to the component based on the BiDi layout.
* @param cssLoaderType the BiDi layout type, either 'common', 'ltr', or 'rtl'.
* @param loader the function that returns a Promise to load CSS or other required localization resources.
* @returns the {@link View} instance.
*/
withCssLoader(t, e) {
return t === "common" ? (C(this, st, qt).call(this, _.LTR, e), C(this, st, qt).call(this, _.RTL, e)) : C(this, st, qt).call(this, t, e), this;
}
/**
* Retrieves the CSS loaders for a given BiDi.
* @param biDi the BiDi object for which to retrieve the CSS loaders.
* @returns the array containing the CSS loaders for the specified BiDi.
*/
getCssLoaders(t) {
return h(this, it).get(t) ?? [];
}
};
ot = new WeakMap(), it = new WeakMap(), Nt = new WeakMap(), st = new WeakSet(), qt = function(t, e) {
h(this, it).set(t, [...h(this, it).get(t) ?? [], e]);
};
let bt = He;
const Aa = bt.create;
var S, x;
const re = class re {
constructor(t) {
/**
* Modifies the component's metadata builder with custom options.
* @param opts the custom options.
* @returns the modified instance of the builder.
*/
v(this, S);
/**
* Definer class data.
* @template T React component property type.
*/
a(this, "data");
/**
* Sets the name of the component.
* @param name the component name.
* @returns the modified Definer class instance.
*/
a(this, "name", (t) => C(this, S, x).call(this, { name: t }));
/**
* Sets the kind of the component.
* @param kind the component kind.
* @returns the modified Definer class instance.
*/
a(this, "kind", (t) => C(this, S, x).call(this, { kind: t }));
/**
* Sets the icon of the component.
* @param icon the component icon.
* @returns the modified Definer class instance.
*/
a(this, "icon", (t) => C(this, S, x).call(this, { icon: t }));
/**
* Sets the category of the component.
* @param category the component category.
* @returns the modified Definer class instance.
*/
a(this, "category", (t) => C(this, S, x).call(this, { category: t }));
/**
* Sets the type of the component.
* @param type the component type.
* @returns the modified Definer class instance.
*/
a(this, "type", (t) => (this.data.component.displayName = t, this));
/**
* Sets the metadata of the component's properties.
* @param properties the metadata of the component's properties.
* @returns the modified Definer class instance.
*/
a(this, "props", (t) => C(this, S, x).call(this, { properties: t }));
/**
* Sets the component CSS metadata.
* @param css the component CSS metadata.
* @returns the modified Definer class instance.
*/
a(this, "css", (t) => C(this, S, x).call(this, { cssObject: t }));
/**
* Adds the metadata of the component's actions. **Internal use only.**
* @param fn the function that initializes an actions on a component.
* @returns the modified Definer class instance.
*/
a(this, "actions", (t) => C(this, S, x).call(this, { actionsInitializer: t }));
/**
* Adds the custom component to be displayed in the component list. **Internal use only.**
* @param customPreview the custom component.
* @returns the modified Definer class instance.
*/
a(this, "preview", (t) => C(this, S, x).call(this, { customPreview: t }));
/**
* Sets initial component JSON.
* @param initialJson the JSON source for the component (instance of {@link ComponentStore} class serialised to JSON).
* @returns the modified Definer class instance.
*/
a(this, "initialJson", (t) => C(this, S, x).call(this, { initialJson: t }));
/**
* Sets the component metadata event listeners.
* @param eventListeners the component metadata event listeners.
* @returns the modified Definer class instance.
*/
a(this, "eventListeners", (t) => C(this, S, x).call(this, { eventListeners: t }));
/**
* Sets the function that restricts the insertion of a component into another component.
* @param insertRestriction the function that restricts the insertion of a component into another component.
* @returns the modified Definer class instance.
*/
a(this, "insertRestriction", (t) => C(this, S, x).call(this, { insertRestriction: t }));
this.data = { component: t };
}
/**
* Static method to create an instance of the component's metadata builder class.
* @param component the React component.
* @param displayName the display name for the anonymous component.
* @returns the instance of the {@link Definer} class.
*/
static define(t, e) {
if (!(e ?? t.displayName ?? t.name))
throw Error("Anonymous components are not allowed!");
const o = new re(t);
return e && o.type(e), o;
}
/**
* Static method to create an instance of the preset component's metadata builder class.
* @param name the preset name.
* @param components the components of the preset.
* @returns the instance of the {@link Definer} class.
*/
static definePreset(t, e) {
if (!t)
throw Error("Anonymous components are not allowed!");
const n = () => null, o = new re(n).kind("preset").type(t).name(t), i = new O("", t);
return i.children = e, o.initialJson(JSON.stringify(i));
}
/**
* @returns the component type name.
*/
getType() {
return this.data.component.displayName || this.data.component.name;
}
/**
* Creates component metadata for the form builder and form viewer.
* @returns component metadata for the form builder and form viewer.
*/
build() {
const t = gt(this.data.properties), e = ut(this.data.cssObject), n = ut(oe), o = t.filter((y) => y.valued === !0), i = o[0];
o.length > 1 && console.warn(`Several annotations with the "valued" property were found. There should be only one "valued" property in the component description! The annotation with the key "${o[0].key}" will be used.`);
const s = i ?? t.find((y) => y.name === "value"), l = t.find((y) => y.readOnly), c = t.find((y) => y.disabled), d = t.reduce((y, b) => (b.bindingType && (y[b.key] = b.bindingType), y), {}), u = new M(
this.data.component,
this.data.name || this.getType(),
this.data.actionsInitializer,
s == null ? void 0 : s.key,
s == null ? void 0 : s.type,
Zr(t),
dt(e),
dt(n),
this.getType(),
this.data.kind,
l == null ? void 0 : l.key,
d,
s == null ? void 0 : s.uncontrolledValue,
c == null ? void 0 : c.key
), g = new G(
this.getType(),
t,
e,
n,
Mt,
this.data.customPreview,
s,
this.data.kind,
this.data.initialJson,
this.data.eventListeners,
this.data.icon,
this.data.insertRestriction
);
return { model: u, meta: g, category: this.data.category };
}
};
S = new WeakSet(), x = function(t) {
return Object.assign(this.data, t), this;
};
let Qt = re;
const Na = Qt.define, za = Qt.definePreset, qs = pt`
font-size: 12px;
color: var(--red-600);
margin-top: 0.25rem;
&:before {
content: "❌ ";
font-size: 10px;
padding: 6px;
}
@media (prefers-color-scheme: dark) {
color: var(--red-300);
}
`, Hs = pt`
display: flex;
flex-direction: column;
width: 100%;
height: 100%;
`, zn = ({ children: r, error: t, className: e }) => {
const n = Kr();
return /* @__PURE__ */ ne("div", { className: Hs, children: [
r,
t && /* @__PURE__ */ p("p", { id: n["aria-errormessage"], className: ft(e, qs), children: t })
] });
};
zn.displayName = "DefaultErrorMessage";
const Ce = new M(zn), me = new G(Zt.type, [], [], [], []), vr = new G(
ht.type,
gt({
children: Xr,
disabled: Qr,
readOnly: Gr
}),
vn,
[],
Mt,
void 0,
void 0,
"container"
), Js = [
...Mt
], Us = new G(
Ut.type,
en,
on,
sn,
Js,
void 0,
tn.build("value"),
Ut.kind
), wr = new G(
Ce.type,
gt({
className: $t
}),
[],
[],
[]
), br = "templates", Zs = "structure";
var $, at, lt;
const Je = class Je extends bt {
/**
* Creates metadata for form builder components.
* @param builderComponents the array of metadata of form builder components.
*/
constructor(e) {
super(e.map(({ model: o }) => o));
v(this, $, /* @__PURE__ */ new Map());
v(this, at, /* @__PURE__ */ new Map());
v(this, lt, /* @__PURE__ */ new Map([
[wr.type, wr]
]));
this.builderComponents = e, h(this, $).set(vr.type, vr), h(this, $).set(me.type, me), this.builderComponents.push({ meta: Is, model: Gt, category: br }), this.builderComponents.push({ meta: Us, model: Ut, category: Zs }), e.map(({ meta: o }) => o).forEach((o) => {
h(this, $).set(o.type, o);
});
}
/**
* Returns the component metadata for the specified component type name.
* @param type the component type name.
* @returns the component metadata for the specified component type name.
*/
getMeta(e) {
const n = h(this, $).get(e);
return n || me;
}
/**
* Adds the component metadata to the form builder.
* @param component the component metadata.
*/
addComponent(e) {
this.define(e.model), h(this, $).set(e.meta.type, e.meta);
}
/**
* Removes the component metadata from the form builder.
* @param name the component type name.
*/
removeComponent(e) {
h(this, $).delete(e);
}
/**
* Returns the component metadata for the specified component type name or undefined.
* @param type the component type name.
* @returns the component metadata for the specified component type name or undefined.
*/
findMeta(e) {
return h(this, $).get(e);
}
/**
* Returns the array of metadata properties of the tooltip component.
* @param name the name of the tooltip component type.
* @returns the array of metadata properties of the tooltip component.
*/
getTooltipAnnotations(e) {
var n;
return (n = h(this, at).get(e)) == null ? void 0 : n.properties;
}
/**
* Returns the array of metadata properties of the error component.
* @param name the name of the error component type.
* @returns the array of metadata properties of the error component.
*/
getErrorAnnotations(e) {
var n;
return (n = h(this, lt).get(e)) == null ? void 0 : n.properties;
}
/**
* @returns the array of strings with the names of the component types of the tooltip.
*/
get tooltips() {
return Array.from(h(this, at).keys());
}
/**
* @returns the array of strings with the names of the component types of the error.
*/
get errors() {
return Array.from(h(this, lt).keys());
}
/**
* Sets the metadata of the component that displays the form's tooltips.
* @param builderComponent the metadata of the component that displays the form's tooltips.
* @returns the instance of the {@link BuilderView} class.
*/
withTooltipMeta(e) {
const { model: n, meta: o } = e;
return this.define(n), h(this, at).set(n.type, o), this;
}
/**
* Sets the metadata of the component that displays form's errors.
* @param builderComponent the metadata of the component that displays the form's errors.
* @returns the instance of the {@link BuilderView} class.
*/
withErrorMeta(e) {
const { model: n, meta: o } = e;
return this.define(n), h(this, lt).set(n.type, o), this;
}
/**
* Creates metadata for the form builder for templates from the specified template names.
* @param templates the array of template names.
* @returns the instance of the {@link BuilderView} class.
*/
withTemplates(e) {
return e.forEach((n) => {
const o = Je.createTemplateComponent(n);
this.define(o.model), h(this, $).set(o.meta.type, o.meta), this.builderComponents.push(o);
}), this;
}
/**
* Creates an instance of BuilderComponent for the specified template name.
* @param name the template name
* @returns the BuilderComponent instance.
*/
static createTemplateComponent(e) {
const n = xn(e);
return { meta: Ws(e), model: n, category: br };
}
};
$ = new WeakMap(), at = new WeakMap(), lt = new WeakMap();
let Cr = Je;
const ja = `declare interface IFormData {
/**
* @returns the {@link Record} with all the form data.
*/
get data(): Record<string, unknown>
/**
* @returns the object to read and modify parent data (available for array elements).
*/
get parentData(): Record<string, unknown> | undefined
/**
* @returns the object to read and modify root form data.
*/
get rootData(): Record<string, unknown>
/**
* @returns the {@link Record} with all validation error messages.
*/
get errors(): Record<string, unknown>
/**
* true if the form contains errors, otherwise false.
*/
get hasErrors(): boolean
/**
* @returns A user-defined key-value observable storage. Utilize it to store and share any custom data.
*/
get state(): Record<string, unknown>
/**
* Sets the validation error message for all form data fields.
* @param message the validation error message.
*/
setAllErrors(message?: string): void
/**
* Validates the data in the form.
*/
validate(): Promise<void>
/**
* Returns the validation results without triggering an events and changing the state of the form.
* @returns the validation results.
*/
getValidationResult: () => Promise<ValidationMessages>
/**
* If true, then validation is in progress.
*/
get isValidating(): boolean
/**
* Sets the form to its default value.
*/
reset(): void
/**
* Clears the form data.
*/
clear(): void
/**
* @returns the index in the array if the component is in the component array.
*/
index?: number
}`, $a = (r, t = !0) => r.map((e) => ({
value: ye(e) ? e.value : e,
label: ye(e) ? e.label : t ? _n(e) : e
})), Ma = (r, t, e) => new Promise((n, o) => {
if (document.getElementById(r))
return n();
const i = document.createElement("link");
i.id = r, i.rel = e, i.href = t, i.onload = () => {
n();
}, i.onerror = o, document.head.appendChild(i);
}), La = (r) => {
var e;
const t = document.getElementById(r);
(e = t == null ? void 0 : t.parentNode) == null || e.removeChild(t);
}, _s = parseInt(Ln.version, 10), Ia = (r) => _s >= 19 ? (e) => r(e, e.ref ?? null) : qn(r);
function Gs(r) {
return typeof (r == null ? void 0 : r.finalize) == "function";
}
class Qs {
constructor(t, e) {
a(this, "buffer", []);
a(this, "current", null);
/**
* @inheritDoc
*/
a(this, "prop", (t, e) => this.finalize().prop(t, e));
/**
* @inheritDoc
*/
a(this, "validation", (t) => this.finalize().validation(t));
/**
* @inheritDoc
*/
a(this, "event", (t) => this.finalize().event(t));
/**
* @inheritDoc
*/
a(this, "component", (t, e) => this.finalize().component(t, e));
/**
* @inheritDoc
*/
a(this, "json", () => this.finalize().json());
/**
* @inheritDoc
*/
a(this, "style", (t, e) => this.finalize().style(t, e));
/**
* @inheritDoc
*/
a(this, "children", (t) => this.finalize().children(t));
this.parent = t, this.eventName = e;
}
/**
* @inheritDoc
*/
commonAction(t) {
return this.commit(), this.current = { type: "common", name: t }, this;
}
/**
* @inheritDoc
*/
customAction(t) {
return this.commit(), this.current = { type: "custom", name: t }, this;
}
/**
* @inheritDoc
*/
args(t) {
if (!this.current)
throw new Error("Call default or custom before args");
return this.current.args = t, this;
}
finalize() {
this.commit(), this.parent.events = {};
for (const t of this.buffer)
this.parent.addEvent(this.eventName, t);
return this.parent;
}
commit() {
this.current && (this.buffer.push(this.current), this.current = null);
}
}
class Xs {
constructor(t, e) {
/**
* @inheritDoc
*/
a(this, "prop", (t, e) => this.finalize().prop(t, e));
/**
* @inheritDoc
*/
a(this, "validation", (t) => this.finalize().validation(t));
/**
* @inheritDoc
*/
a(this, "event", (t) => this.finalize().event(t));
/**
* @inheritDoc
*/
a(this, "component", (t, e) => this.finalize().component(t, e));
/**
* @inheritDoc
*/
a(this, "json", () => this.finalize().json());
/**
* @inheritDoc
*/
a(this, "style", (t, e) => this.finalize().style(t, e));
/**
* @inheritDoc
*/
a(this, "children", (t) => this.finalize().children(t));
this.parent = t, this.key = e;
}
/**
* @inheritDoc
*/
args(t) {
return this.finalize(t), this.parent;
}
finalize(t) {
return this.parent.addValidation(this.key, t), this.parent;
}
}
class Ys {
constructor(t, e, n) {
a(this, "props", {});
a(this, "validations", []);
a(this, "events", {});
a(this, "css", {});
a(this, "childComponents", []);
/**
* @inheritDoc
*/
a(this, "json", () => this.parent.json());
/**
* @inheritDoc
*/
a(this, "component", (t, e) => this.parent.component(t, e));
this.parent = t, this.key = e, this.type = n;
}
/**
* @inheritDoc
*/
prop(t, e) {
return this.props[t] = { value: e }, this;
}
/**
* @inheritDoc
*/
validation(t) {
return new Xs(this, t);
}
/**
* @inheritDoc
*/
event(t) {
return new Qs(this, t);
}
buildComponent() {
const t = {
key: this.key,
type: this.type,
props: this.props
};
return this.validations.length && (t.schema = { validations: this.validations }), Object.keys(this.events).length && (t.events = this.events), Object.keys(this.css).length && (t.css = this.css), this.childComponents.length && (t.children = this.childComponents), t;
}
addEvent(t, e) {
this.events[t] || (this.events[t] = []), this.events[t].push(e);
}
addValidation(t, e) {
this.validations.push({ key: t, args: e });
}
/**
* @inheritDoc
*/
style(t, e) {
var o, i;
const n = (o = this.css)[i = e ?? "any"] ?? (o[i] = {});
return typeof t == "object" ? (n.object = { ...n.object, ...t }, this) : (n.string = t, this);
}
/**
* @inheritDoc
*/
children(t) {
const e = new jn(), n = t(e);
return Gs(n) && n.finalize(), this.childComponents = [
...this.childComponents,
...e.build().form.children ?? []
], this;
}
}
class jn {
constructor(t) {
a(this, "components", []);
a(this, "current", null);
this.options = t;
}
/**
* @inheritDoc
*/
component(t, e) {
return this.current && this.components.push(this.current.buildComponent()), this.current = new Ys(this, t, e), this.current;
}
/**
* @inheritDoc
*/
json() {
return JSON.stringify(this.build());
}
build() {
this.current && (this.components.push(this.current.buildComponent()), this.current = null);
const t = {
...this.options,
form: {
key: "Screen",
type: "Screen"
}
};
return this.components.length && (t.form.children = this.components), t;
}
}
function Ba(r) {
return new jn(r);
}
export {
F as ActionDefinition,
je as ActionEventArgs,
Ra as ActionEventArgsDeclaration,
jt as Annotation,
Jt as AnnotationBuilder,
Ht as ArrayBuilder,
Ae as AsyncFunction,
Jr as BaseBuilder,
_ as BiDi,
ma as BuilderModeProvider,
Po as BuilderOptions,
Cr as BuilderView,
A as CalculableResult,
fo as ComponentData,
ho as ComponentDataEvents,
Wr as ComponentDataProvider,
uo as ComponentKeyChangedEventArgs,
mn as ComponentState,
O as ComponentStore,
gn as ComponentTree,
qr as ContainerAnnotation,
ge as DataValidator,
Le as DefaultWrapper,
Ne as DidMountEvent,
Co as EventAnnotation,
pe as Form,
Ts as FormViewer,
Be as FormViewerPropsStore,
ja as IFormDataDeclaration,
tr as KeySymbol,
se as Language,
fe as LocalizationStore,
G as Meta,
M as Model,
Vo as ModuleAnnotation,
To as NodeAnnotationBuilder,
So as OneOfBuilder,
ve as PersistedFormVersion,
Hr as PropertyAnnotation,
Ur as QuantifierBuilder,
Ss as SDiv,
Fo as SomeOfBuilder,
we as Store,
bo as StoreContext,
Re as StoreProvider,
Eo as StyleAnnotation,
Jo as SuppressResizeObserverErrors,
rr as SyncEvent,
Fn as TemplateField,
Oe as TypedBuilder,
bt as View,
dn as ViewerPropsProvider,
ze as WillUnmountEvent,
Ao as array,
ke as boolean,
Ba as buildForm,
$e as calculatePropertyValue,
ps as checkSlotCondition,
Sa as className,
Da as color,
oe as commonStyles,
xe as containerStyles,
Io as createActionValuesFromObject,
B as createAnnotation,
yt as createNonNullableContext,
T as createProperty,
Aa as createView,
X as cssSize,
Va as date,
Na as define,
za as definePreset,
Qr as disabled,
sr as emotionCache,
Oa as emptyComponentStore,
Ce as errorMessageModel,
ir as event,
Oi as findLanguage,
ao as findTreeElementDepth,
Ia as forwardRef,
Dn as generateTemplateTypeName,
ls as generateUniqueName,
ms as getChildren,
Zr as getDefault,
dt as getDefaultCss,
D as getFluentCompatibleId,
jr as getFluentData,
pa as getKey,
ki as getValidatorPropertyBlockType,
Kt as globalDefaultLanguage,
ro as groupBy,
Oo as htmlAttributes,
po as initFormFields,
Zt as internalErrorModel,
va as isContainer,
mt as isFunctionalProperty,
Fe as isLocalizedProperty,
ie as isPromise,
ya as isProperty,
an as isString,
Ro as isUniqueKey,
ka as isValidatorPropertyBlockType,
wa as key,
Ma as loadResource,
Mr as nameAutorun,
z as nameObservable,
k as namedObserver,
Xr as node,
Fa as nodeArray,
Ca as number,
ba as object,
Lt as oneOf,
Gr as readOnly,
zo as renderWhen,
ht as screenModel,
xo as size,
Gt as slotModel,
Ta as someOf,
$t as string,
xa as testFluentLocalization,
Ea as time,
ga as timeFormat,
gt as toArray,
$a as toLabeledValues,
No as tooltipProps,
Pa as tooltipType,
Wt as treeForEach,
La as unloadResource,
fa as useAriaAttributes,
Kr as useAriaAttributesIds,
mo as useAriaInvalid,
wo as useBuilderMode,
Z as useComponentData,
ys as useDisposable,
ai as useErrorModel,
I as useStore,
Uo as useTooltipType,
Q as useViewerProps,
ko as validation
};
//# sourceMappingURL=index.js.map