svelte-hook-form
Version:
A better version of form validation.
1,503 lines (1,454 loc) • 45.9 kB
JavaScript
;
Object.defineProperty(exports, '__esModule', { value: true });
function noop() { }
function assign(tar, src) {
// @ts-ignore
for (const k in src)
tar[k] = src[k];
return tar;
}
function run(fn) {
return fn();
}
function blank_object() {
return Object.create(null);
}
function run_all(fns) {
fns.forEach(run);
}
function is_function(thing) {
return typeof thing === 'function';
}
function safe_not_equal(a, b) {
return a != a ? b == b : a !== b || ((a && typeof a === 'object') || typeof a === 'function');
}
function is_empty(obj) {
return Object.keys(obj).length === 0;
}
function subscribe(store, ...callbacks) {
if (store == null) {
return noop;
}
const unsub = store.subscribe(...callbacks);
return unsub.unsubscribe ? () => unsub.unsubscribe() : unsub;
}
function get_store_value(store) {
let value;
subscribe(store, _ => value = _)();
return value;
}
function component_subscribe(component, store, callback) {
component.$$.on_destroy.push(subscribe(store, callback));
}
function create_slot(definition, ctx, $$scope, fn) {
if (definition) {
const slot_ctx = get_slot_context(definition, ctx, $$scope, fn);
return definition[0](slot_ctx);
}
}
function get_slot_context(definition, ctx, $$scope, fn) {
return definition[1] && fn
? assign($$scope.ctx.slice(), definition[1](fn(ctx)))
: $$scope.ctx;
}
function get_slot_changes(definition, $$scope, dirty, fn) {
if (definition[2] && fn) {
const lets = definition[2](fn(dirty));
if ($$scope.dirty === undefined) {
return lets;
}
if (typeof lets === 'object') {
const merged = [];
const len = Math.max($$scope.dirty.length, lets.length);
for (let i = 0; i < len; i += 1) {
merged[i] = $$scope.dirty[i] | lets[i];
}
return merged;
}
return $$scope.dirty | lets;
}
return $$scope.dirty;
}
function update_slot_base(slot, slot_definition, ctx, $$scope, slot_changes, get_slot_context_fn) {
if (slot_changes) {
const slot_context = get_slot_context(slot_definition, ctx, $$scope, get_slot_context_fn);
slot.p(slot_context, slot_changes);
}
}
function get_all_dirty_from_scope($$scope) {
if ($$scope.ctx.length > 32) {
const dirty = [];
const length = $$scope.ctx.length / 32;
for (let i = 0; i < length; i++) {
dirty[i] = -1;
}
return dirty;
}
return -1;
}
function exclude_internal_props(props) {
const result = {};
for (const k in props)
if (k[0] !== '$')
result[k] = props[k];
return result;
}
function compute_rest_props(props, keys) {
const rest = {};
keys = new Set(keys);
for (const k in props)
if (!keys.has(k) && k[0] !== '$')
rest[k] = props[k];
return rest;
}
function insert(target, node, anchor) {
target.insertBefore(node, anchor || null);
}
function detach(node) {
node.parentNode.removeChild(node);
}
function element(name) {
return document.createElement(name);
}
function listen(node, event, handler, options) {
node.addEventListener(event, handler, options);
return () => node.removeEventListener(event, handler, options);
}
function attr(node, attribute, value) {
if (value == null)
node.removeAttribute(attribute);
else if (node.getAttribute(attribute) !== value)
node.setAttribute(attribute, value);
}
function set_attributes(node, attributes) {
// @ts-ignore
const descriptors = Object.getOwnPropertyDescriptors(node.__proto__);
for (const key in attributes) {
if (attributes[key] == null) {
node.removeAttribute(key);
}
else if (key === 'style') {
node.style.cssText = attributes[key];
}
else if (key === '__value') {
node.value = node[key] = attributes[key];
}
else if (descriptors[key] && descriptors[key].set) {
node[key] = attributes[key];
}
else {
attr(node, key, attributes[key]);
}
}
}
function children(element) {
return Array.from(element.childNodes);
}
function custom_event(type, detail, { bubbles = false, cancelable = false } = {}) {
const e = document.createEvent('CustomEvent');
e.initCustomEvent(type, bubbles, cancelable, detail);
return e;
}
let current_component;
function set_current_component(component) {
current_component = component;
}
function get_current_component() {
if (!current_component)
throw new Error('Function called outside component initialization');
return current_component;
}
function onDestroy(fn) {
get_current_component().$$.on_destroy.push(fn);
}
function createEventDispatcher() {
const component = get_current_component();
return (type, detail, { cancelable = false } = {}) => {
const callbacks = component.$$.callbacks[type];
if (callbacks) {
// TODO are there situations where events could be dispatched
// in a server (non-DOM) environment?
const event = custom_event(type, detail, { cancelable });
callbacks.slice().forEach(fn => {
fn.call(component, event);
});
return !event.defaultPrevented;
}
return true;
};
}
function setContext(key, context) {
get_current_component().$$.context.set(key, context);
return context;
}
function getContext(key) {
return get_current_component().$$.context.get(key);
}
const dirty_components = [];
const binding_callbacks = [];
const render_callbacks = [];
const flush_callbacks = [];
const resolved_promise = Promise.resolve();
let update_scheduled = false;
function schedule_update() {
if (!update_scheduled) {
update_scheduled = true;
resolved_promise.then(flush);
}
}
function add_render_callback(fn) {
render_callbacks.push(fn);
}
// flush() calls callbacks in this order:
// 1. All beforeUpdate callbacks, in order: parents before children
// 2. All bind:this callbacks, in reverse order: children before parents.
// 3. All afterUpdate callbacks, in order: parents before children. EXCEPT
// for afterUpdates called during the initial onMount, which are called in
// reverse order: children before parents.
// Since callbacks might update component values, which could trigger another
// call to flush(), the following steps guard against this:
// 1. During beforeUpdate, any updated components will be added to the
// dirty_components array and will cause a reentrant call to flush(). Because
// the flush index is kept outside the function, the reentrant call will pick
// up where the earlier call left off and go through all dirty components. The
// current_component value is saved and restored so that the reentrant call will
// not interfere with the "parent" flush() call.
// 2. bind:this callbacks cannot trigger new flush() calls.
// 3. During afterUpdate, any updated components will NOT have their afterUpdate
// callback called a second time; the seen_callbacks set, outside the flush()
// function, guarantees this behavior.
const seen_callbacks = new Set();
let flushidx = 0; // Do *not* move this inside the flush() function
function flush() {
const saved_component = current_component;
do {
// first, call beforeUpdate functions
// and update components
while (flushidx < dirty_components.length) {
const component = dirty_components[flushidx];
flushidx++;
set_current_component(component);
update(component.$$);
}
set_current_component(null);
dirty_components.length = 0;
flushidx = 0;
while (binding_callbacks.length)
binding_callbacks.pop()();
// then, once components are updated, call
// afterUpdate functions. This may cause
// subsequent updates...
for (let i = 0; i < render_callbacks.length; i += 1) {
const callback = render_callbacks[i];
if (!seen_callbacks.has(callback)) {
// ...so guard against infinite loops
seen_callbacks.add(callback);
callback();
}
}
render_callbacks.length = 0;
} while (dirty_components.length);
while (flush_callbacks.length) {
flush_callbacks.pop()();
}
update_scheduled = false;
seen_callbacks.clear();
set_current_component(saved_component);
}
function update($$) {
if ($$.fragment !== null) {
$$.update();
run_all($$.before_update);
const dirty = $$.dirty;
$$.dirty = [-1];
$$.fragment && $$.fragment.p($$.ctx, dirty);
$$.after_update.forEach(add_render_callback);
}
}
const outroing = new Set();
let outros;
function transition_in(block, local) {
if (block && block.i) {
outroing.delete(block);
block.i(local);
}
}
function transition_out(block, local, detach, callback) {
if (block && block.o) {
if (outroing.has(block))
return;
outroing.add(block);
outros.c.push(() => {
outroing.delete(block);
if (callback) {
if (detach)
block.d(1);
callback();
}
});
block.o(local);
}
}
function get_spread_update(levels, updates) {
const update = {};
const to_null_out = {};
const accounted_for = { $$scope: 1 };
let i = levels.length;
while (i--) {
const o = levels[i];
const n = updates[i];
if (n) {
for (const key in o) {
if (!(key in n))
to_null_out[key] = 1;
}
for (const key in n) {
if (!accounted_for[key]) {
update[key] = n[key];
accounted_for[key] = 1;
}
}
levels[i] = n;
}
else {
for (const key in o) {
accounted_for[key] = 1;
}
}
}
for (const key in to_null_out) {
if (!(key in update))
update[key] = undefined;
}
return update;
}
function mount_component(component, target, anchor, customElement) {
const { fragment, on_mount, on_destroy, after_update } = component.$$;
fragment && fragment.m(target, anchor);
if (!customElement) {
// onMount happens before the initial afterUpdate
add_render_callback(() => {
const new_on_destroy = on_mount.map(run).filter(is_function);
if (on_destroy) {
on_destroy.push(...new_on_destroy);
}
else {
// Edge case - component was destroyed immediately,
// most likely as a result of a binding initialising
run_all(new_on_destroy);
}
component.$$.on_mount = [];
});
}
after_update.forEach(add_render_callback);
}
function destroy_component(component, detaching) {
const $$ = component.$$;
if ($$.fragment !== null) {
run_all($$.on_destroy);
$$.fragment && $$.fragment.d(detaching);
// TODO null out other refs, including component.$$ (but need to
// preserve final state?)
$$.on_destroy = $$.fragment = null;
$$.ctx = [];
}
}
function make_dirty(component, i) {
if (component.$$.dirty[0] === -1) {
dirty_components.push(component);
schedule_update();
component.$$.dirty.fill(0);
}
component.$$.dirty[(i / 31) | 0] |= (1 << (i % 31));
}
function init(component, options, instance, create_fragment, not_equal, props, append_styles, dirty = [-1]) {
const parent_component = current_component;
set_current_component(component);
const $$ = component.$$ = {
fragment: null,
ctx: null,
// state
props,
update: noop,
not_equal,
bound: blank_object(),
// lifecycle
on_mount: [],
on_destroy: [],
on_disconnect: [],
before_update: [],
after_update: [],
context: new Map(options.context || (parent_component ? parent_component.$$.context : [])),
// everything else
callbacks: blank_object(),
dirty,
skip_bound: false,
root: options.target || parent_component.$$.root
};
append_styles && append_styles($$.root);
let ready = false;
$$.ctx = instance
? instance(component, options.props || {}, (i, ret, ...rest) => {
const value = rest.length ? rest[0] : ret;
if ($$.ctx && not_equal($$.ctx[i], $$.ctx[i] = value)) {
if (!$$.skip_bound && $$.bound[i])
$$.bound[i](value);
if (ready)
make_dirty(component, i);
}
return ret;
})
: [];
$$.update();
ready = true;
run_all($$.before_update);
// `false` as a special case of no DOM component
$$.fragment = create_fragment ? create_fragment($$.ctx) : false;
if (options.target) {
if (options.hydrate) {
const nodes = children(options.target);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
$$.fragment && $$.fragment.l(nodes);
nodes.forEach(detach);
}
else {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
$$.fragment && $$.fragment.c();
}
if (options.intro)
transition_in(component.$$.fragment);
mount_component(component, options.target, options.anchor, options.customElement);
flush();
}
set_current_component(parent_component);
}
/**
* Base class for Svelte components. Used when dev=false.
*/
class SvelteComponent {
$destroy() {
destroy_component(this, 1);
this.$destroy = noop;
}
$on(type, callback) {
const callbacks = (this.$$.callbacks[type] || (this.$$.callbacks[type] = []));
callbacks.push(callback);
return () => {
const index = callbacks.indexOf(callback);
if (index !== -1)
callbacks.splice(index, 1);
};
}
$set($$props) {
if (this.$$set && !is_empty($$props)) {
this.$$.skip_bound = true;
this.$$set($$props);
this.$$.skip_bound = false;
}
}
}
const subscriber_queue = [];
/**
* Creates a `Readable` store that allows reading by subscription.
* @param value initial value
* @param {StartStopNotifier}start start and stop notifications for subscriptions
*/
function readable(value, start) {
return {
subscribe: writable(value, start).subscribe
};
}
/**
* Create a `Writable` store that allows both updating and reading by subscription.
* @param {*=}value initial value
* @param {StartStopNotifier=}start start and stop notifications for subscriptions
*/
function writable(value, start = noop) {
let stop;
const subscribers = new Set();
function set(new_value) {
if (safe_not_equal(value, new_value)) {
value = new_value;
if (stop) { // store is ready
const run_queue = !subscriber_queue.length;
for (const subscriber of subscribers) {
subscriber[1]();
subscriber_queue.push(subscriber, value);
}
if (run_queue) {
for (let i = 0; i < subscriber_queue.length; i += 2) {
subscriber_queue[i][0](subscriber_queue[i + 1]);
}
subscriber_queue.length = 0;
}
}
}
}
function update(fn) {
set(fn(value));
}
function subscribe(run, invalidate = noop) {
const subscriber = [run, invalidate];
subscribers.add(subscriber);
if (subscribers.size === 1) {
stop = start(set) || noop;
}
run(value);
return () => {
subscribers.delete(subscriber);
if (subscribers.size === 0) {
stop();
stop = null;
}
};
}
return { set, update, subscribe };
}
const RULES = new Map();
function defineRule(ruleName, cb) {
if (typeof ruleName != "string") {
cb = ruleName;
ruleName = cb.name;
}
RULES.set(ruleName, cb);
}
function resolveRule(ruleName) {
const cb = RULES.get(ruleName);
return cb;
}
const isPromise = (p) => {
if (!p)
return false;
if (typeof p === "object" &&
typeof p.then === "function" &&
typeof p.catch === "function") {
return true;
}
return false;
};
/**
* Transform a callback to a promise
*
* @param fn function can be async or not async
* @returns Async function
*/
const toPromise = (fn) => {
return function (...args) {
const value = fn.apply(null, args);
if (isPromise(value)) {
return value;
}
if (typeof value === "function") {
return Promise.resolve(value.apply(null, args));
}
return Promise.resolve(value);
};
};
/**
* Patch an object with the nested key value
*
* @param data the source object
* @param key the object key we want to append
* @param value the value of the object's key
* @returns new source object
*
* ### Example
* ```js
* normalizeObject({ z: 440.056 }, "a[0].b.c[2]", "hello world!")
* ```
*/
const normalizeObject = (src, key, value) => {
const data = Object.assign({}, src);
if (!key)
return data;
const escape = key.match(/^\[(.*)\]$/);
// split the key by dot
const queue = [
[data, escape ? [escape[1]] : key.split(".")]
];
while (queue.length > 0) {
const first = queue.shift();
const paths = first[1];
const name = paths.shift();
const result = name.match(/^([a-z\_\.]+)((\[\d+\])+)/i);
if (result && result.length > 2) {
const name = result[1];
// if it's not array, assign it and make it as array
if (!Array.isArray(first[0][name])) {
first[0][name] = [];
}
let cur = first[0][name];
// get array indexes from the key
const indexs = result[2].replace(/^\[+|\]+$/g, "").split("][");
while (indexs.length > 0) {
// convert the the index string to number
const index = parseInt(indexs.shift(), 10);
// if nested index is last position && parent is last position
if (indexs.length === 0) {
if (paths.length === 0) {
cur[index] = value;
}
else {
if (!cur[index]) {
cur[index] = {};
}
}
}
else if (!cur[index]) {
// set to empty array if it's undefined
cur[index] = [];
}
cur = cur[index];
}
if (paths.length > 0) {
queue.push([cur, paths]);
}
continue;
}
if (paths.length === 0) {
first[0][name] = value;
}
else {
if (!first[0][name]) {
first[0][name] = {};
}
queue.push([first[0][name], paths]);
}
}
return data;
};
class FormField {
store;
rules;
bail;
constructor(store, rules, bail) {
this.store = store;
this.rules = rules;
this.bail = bail;
}
/**
* Returns a readonly field state.
*
* @returns {Readable<FieldState>} state of the field.
*/
get state() {
return get_store_value(this.store);
}
/**
* Observe the field state.
*
* @returns {Readable<FieldState>} state of the field.
*
* @example
* ```svelte
* <script lang="ts">
* const state$ = watch("text");
* state$.subscribe((v) => {
* console.log("State =>", v);
* });
* </script>
* ```
*/
get watch() {
const { subscribe } = this.store;
return { subscribe };
}
/**
* Update the current field state.
*
* @param {Partial<FieldState>} state
*
* @example
* ```ts
* field.setState({ valid: true });
* ```
*/
setState(state) {
this.store.update((v) => ({ ...v, ...state }));
}
validate = (value = undefined) => {
const promises = [];
const len = this.rules.length;
let newState = Object.assign(this.state, { errors: [] });
value = value || newState.value;
// If it's empty rules, it will always return `true`
if (len == 0) {
newState = Object.assign(newState, { value, valid: true });
this.setState(newState);
return Promise.resolve(newState);
}
newState = Object.assign(newState, {
// dirty: v.dirty ? true : soft ? false : true,
pending: true,
value
});
this.setState(newState);
// Setup validation rules and pass in field value
let i = 0;
for (i = 0; i < len; i++) {
const { validate, params } = this.rules[i];
promises.push(validate(value, params));
}
if (this.bail) {
return new Promise(async (resolve) => {
for (i = 0; i < len; i++) {
const result = await promises[i];
if (result !== true) {
newState = Object.assign(newState, {
pending: false,
errors: [result],
valid: false
});
this.setState(newState);
resolve(newState);
return;
}
}
newState = Object.assign(newState, {
pending: false,
valid: false
});
this.setState(newState);
resolve(newState);
});
}
return Promise.all(promises).then((result) => {
const errors = result.filter((v) => v !== true);
newState = Object.assign(newState, {
pending: false,
errors,
valid: errors.length === 0
});
this.setState(newState);
return Promise.resolve(newState);
});
};
}
const INPUT_FIELDS = ["INPUT", "SELECT", "TEXTAREA"];
const INPUT_SELECTORS = INPUT_FIELDS.join(",");
const DEFAULT_FORM_STATE = {
dirty: false,
submitCount: 0,
submitting: false,
touched: false,
pending: false,
valid: true
};
const DEFAULT_FIELD_STATE = {
defaultValue: "",
value: "",
pending: false,
dirty: false,
touched: false,
valid: true,
errors: []
};
/**
* Convert string to {@link ValidationRule} object.
*
* @param {string} rule validation rule, eg. "required|min=3"
* @returns {ValidationRule} validation rule object
*/
const _strToValidator = (rule) => {
const params = rule.split(/:/g);
const name = params.shift();
if (!resolveRule(name))
;
return {
name,
validate: toPromise(resolveRule(name)),
params: params[0] ? params[0].split(",").map((v) => decodeURIComponent(v)) : []
};
};
/**
* Custom hook to manage the entire form.
*
* @param {FormConfig} config - configuration. {@link FormConfig}
* @returns {Form<F>} - individual functions to manage the form state. {@link Form<F>}
*
* @example
* ```svelte
* <script lang="ts">
* const form = useForm<{ name: string }>();
* const { control, onSubmit } = form;
*
* const handleSubmit = onSubmit((data) => {
* // PUT your business here when the form submit is success
* }, () => {
* // handle the error
* });
* </script>
*
* <form on:submit={handleSubmit}>
* <input value="test"/>
* <input />
* {errors.exampleRequired && <span>This field is required</span>}
* <input type="submit" value="Submit" />
* </form>
* ```
*/
const useForm = (config = { validateOnChange: true }) => {
// cache for form fields
const cache = new Map();
// global state for form
const form$ = writable(Object.assign({}, DEFAULT_FORM_STATE));
const anyNonDirty = new Map();
const anyPending = new Map();
const anyNonTouched = new Map();
const anyInvalid = new Map();
// errors should be private variable
const errors$ = writable({});
const _updateForm = () => {
form$.update((v) => Object.assign(v, {
valid: anyInvalid.size === 0,
dirty: anyNonDirty.size === 0,
touched: anyNonTouched.size === 0,
pending: anyPending.size > 0
}));
};
const _useLocalStore = (path, state) => {
const { subscribe, set, update } = writable(Object.assign({}, DEFAULT_FIELD_STATE, state));
let unsubscribe;
const _unsubscribeStore = () => {
unsubscribe && unsubscribe();
unsubscribe = null;
};
return {
set,
update,
destroy() {
cache.delete(path); // clean our cache
anyInvalid.delete(path);
anyNonDirty.delete(path);
anyNonTouched.delete(path);
anyPending.delete(path);
_updateForm();
_unsubscribeStore();
},
subscribe(run, invalidate) {
unsubscribe = subscribe(run, invalidate);
return _unsubscribeStore;
}
};
};
const _setStore = (path, state = {}) => {
const store$ = _useLocalStore(path, state);
cache.set(path, new FormField(store$, [], false));
};
const register = (path, option = {}) => {
const value = option.defaultValue;
const isNotEmpty = value !== undefined && value !== null;
const store$ = _useLocalStore(path, {
defaultValue: value,
value: value,
dirty: isNotEmpty
});
let ruleExprs = [];
const { bail = false, rules = [] } = option;
const typeOfRule = typeof rules;
if (typeOfRule === "string") {
ruleExprs = (rules.match(/[^\|]+/g) || []).map((v) => _strToValidator(v));
}
else if (Array.isArray(rules)) {
ruleExprs = rules.reduce((acc, rule) => {
const typeOfVal = typeof rule;
// Skip null, undefined etc
if (!rule)
return acc;
if (typeOfVal === "string") {
rule = rule.trim();
rule && acc.push(_strToValidator(rule));
}
else if (typeOfVal === "function") {
rule = rule;
if (rule.name === "")
;
acc.push({
name: rule.name,
validate: toPromise(rule),
params: []
});
}
return acc;
}, []);
}
else if (typeOfRule !== null && typeOfRule === "object") {
ruleExprs = Object.entries(rules).reduce((acc, cur) => {
const [name, params] = cur;
acc.push({
name,
validate: toPromise(resolveRule(name)),
params: Array.isArray(params) ? params : [params]
});
return acc;
}, []);
}
else ;
const field = new FormField(store$, ruleExprs, bail);
cache.set(path, field);
// if (isNotEmpty && option.validateOnMount) {
// _validate(field, path, {});
// }
if (config.validateOnChange) {
// on every state change, it will update the form
store$.subscribe((state) => {
if (state.valid)
anyInvalid.delete(path);
else if (!state.valid)
anyInvalid.set(path, true);
if (state.dirty)
anyNonDirty.delete(path);
else if (!state.dirty)
anyNonDirty.set(path, true);
if (!state.pending)
anyPending.delete(path);
else if (state.pending)
anyPending.set(path, true);
if (state.touched)
anyNonTouched.delete(path);
else if (!state.touched)
anyNonTouched.set(path, true);
_updateForm();
});
}
return {
subscribe: store$.subscribe
};
};
const unregister = (path) => {
if (cache.has(path)) ;
};
const setValue = (path, value) => {
if (!cache.has(path)) {
_setStore(path);
return;
}
if (value.target) {
const target = value.target;
value = target.value;
}
else if (value.currentTarget) {
const target = value.currentTarget;
value = target.value;
}
else if (value instanceof CustomEvent) {
value = value.detail;
}
const field = cache.get(path);
if (config.validateOnChange) {
field.validate(value);
}
else {
field.setState({ dirty: true, value });
}
};
const setError = (path, errors) => {
if (cache.has(path)) {
cache.get(path).setState({ errors });
}
else {
_setStore(path, { errors });
}
};
const setFocus = (path, touched) => {
if (cache.has(path)) {
const field = cache.get(path);
field.setState({ touched });
if (!touched)
field.validate();
}
};
const getValue = (path) => {
if (!cache.has(path))
return null;
return cache.get(path).state.value;
};
const _useField = (node, option = {}) => {
option = Object.assign({ rules: [], defaultValue: "" }, option);
while (!INPUT_FIELDS.includes(node.nodeName)) {
const el = node.querySelector(INPUT_SELECTORS);
node = el;
if (el)
break;
}
const name = node.name || node.id;
const { rules } = option;
const defaultValue = node.defaultValue ||
node.value ||
option.defaultValue;
const state$ = register(name, { defaultValue, rules });
const onChange = (e) => {
setValue(name, e.currentTarget.value);
};
const onFocus = (focused) => () => {
setFocus(name, focused);
};
if (defaultValue) {
node.setAttribute("value", defaultValue);
}
const listeners = [];
const _attachEvent = (event, cb, opts) => {
node.addEventListener(event, cb, opts);
listeners.push([event, cb]);
};
const _detachEvents = () => {
for (let i = 0, len = listeners.length; i < len; i++) {
const [event, cb] = listeners[i];
node.removeEventListener(event, cb);
}
};
_attachEvent("focus", onFocus(true));
_attachEvent("blur", onFocus(false));
if (config.validateOnChange) {
_attachEvent("input", onChange);
_attachEvent("change", onChange);
}
// if (option.validateOnMount) {
// const field = cache.get(name)!;
// // _validate(field, name, { value: defaultValue });
// }
let unsubscribe;
if (option.handleChange) {
unsubscribe = state$.subscribe((v) => {
option.handleChange(v, node);
});
}
return {
// Release memory when unmount
destroy() {
_detachEvents();
unregister(name);
unsubscribe && unsubscribe();
}
};
};
const reset = (values, option) => {
const defaultOption = {
dirtyFields: false,
errors: false
};
option = Object.assign(defaultOption, option || {});
if (option.errors) {
errors$.set({}); // reset errors
}
const fields = Array.from(cache.values());
for (let i = 0, len = fields.length; i < len; i++) {
// const [store$] = fields[i];
// store$.update((v) => {
// const { defaultValue } = v;
// return Object.assign({}, DEFAULT_FIELD_STATE, {
// defaultValue,
// value: defaultValue
// });
// });
}
};
const useField = (node, option = {}) => {
let field = _useField(node, option);
return {
update(newOption = {}) {
field.destroy(); // reset
field = _useField(node, newOption);
},
destroy() {
field.destroy();
}
};
};
const onSubmit = (successCallback, errorCallback) => async (e) => {
e.preventDefault();
e.stopPropagation();
form$.update((v) => Object.assign(v, {
valid: false,
submitCount: v.submitCount + 1,
submitting: true
}));
let data = {};
let errors = {};
let valid = true;
// Reset the errors
errors$.set(errors);
// Handle the fields cached in the map
const keys = Array.from(cache.keys());
for (const [key, field] of cache.entries()) {
const result = await field.validate();
// Update valid on each loop, if one of the field is invalid,
// the form valid is invalid
valid = valid && result.valid;
if (!result.valid)
errors[key] = result.errors;
data = normalizeObject(data, key, field.state.value);
}
// Handle the fields whose never register in the cache
const { elements = [] } = (e.currentTarget || e.target);
for (let i = 0, len = elements.length; i < len; i++) {
const el = elements[i];
const name = el.name || el.id;
let value = el.value || "";
if (!name)
continue;
// Skip if the key exists in cache
if (keys.includes(name))
continue;
if (config.resolver) {
data = normalizeObject(data, name, value);
continue;
}
// TODO: check checkbox and radio
const { type } = el;
switch (type) {
case "checkbox":
value = el.checked ? value : "";
break;
}
data = normalizeObject(data, name, value);
}
// if (config.resolver) {
// try {
// await config.resolver.validate(data);
// } catch (e) {
// valid = false;
// }
// }
errors$.set(errors);
if (valid) {
await toPromise(successCallback)(data, e);
}
else {
errorCallback && errorCallback(errors, e);
}
// Submitting should end only after execute user callback
form$.update((v) => Object.assign(v, { valid, submitting: false }));
};
const validate = (paths = Array.from(cache.keys())) => {
if (!Array.isArray(paths))
paths = [paths];
const promises = [];
let data = {};
for (let i = 0, len = paths.length; i < len; i++) {
if (!cache.has(paths[i]))
continue;
// const field = cache.get(paths[i])!;
// const state = get(field[0]);
// promises.push(_validate(field, paths[i], state.value));
// data = normalizeObject(data, paths[i], state.value);
}
return Promise.all(promises).then((result) => {
return {
valid: result.every((state) => state.valid),
data: data
};
});
};
const getValues = () => {
let data = {};
const entries = cache.entries();
for (const [key, field] of entries) {
data = normalizeObject(data, key, field.state);
}
return data;
};
const context = {
register,
unregister,
setValue,
getValue,
setError,
setFocus,
getValues,
reset,
watch: (key) => {
if (!cache.has(key)) {
_setStore(key);
}
return cache.get(key).watch;
},
field: useField
};
return {
...context,
control: readable(context),
errors: {
subscribe: errors$.subscribe
},
validate,
onSubmit,
subscribe(run, invalidate) {
const unsubscribe = form$.subscribe(run, invalidate);
return () => {
// prevent memory leak
unsubscribe();
cache.clear(); // clean our cache
};
}
};
};
/* packages/svelte-hook-form/src/components/Form.svelte generated by Svelte v3.48.0 */
const get_default_slot_spread_changes = dirty => dirty & /*state*/ 1;
const get_default_slot_changes$1 = dirty => ({ errors: dirty & /*$errors*/ 2 });
const get_default_slot_context$1 = ctx => ({
.../*state*/ ctx[0],
errors: /*$errors*/ ctx[1],
field: /*field*/ ctx[3]
});
function create_fragment$1(ctx) {
let form;
let current;
let mounted;
let dispose;
const default_slot_template = /*#slots*/ ctx[7].default;
const default_slot = create_slot(default_slot_template, ctx, /*$$scope*/ ctx[6], get_default_slot_context$1);
let form_levels = [/*$$restProps*/ ctx[5]];
let form_data = {};
for (let i = 0; i < form_levels.length; i += 1) {
form_data = assign(form_data, form_levels[i]);
}
return {
c() {
form = element("form");
if (default_slot) default_slot.c();
set_attributes(form, form_data);
},
m(target, anchor) {
insert(target, form, anchor);
if (default_slot) {
default_slot.m(form, null);
}
current = true;
if (!mounted) {
dispose = listen(form, "submit", /*handleSubmit*/ ctx[4]);
mounted = true;
}
},
p(ctx, [dirty]) {
if (default_slot) {
if (default_slot.p && (!current || dirty & /*$$scope, state, $errors*/ 67)) {
update_slot_base(
default_slot,
default_slot_template,
ctx,
/*$$scope*/ ctx[6],
get_default_slot_spread_changes(dirty) || !current
? get_all_dirty_from_scope(/*$$scope*/ ctx[6])
: get_slot_changes(default_slot_template, /*$$scope*/ ctx[6], dirty, get_default_slot_changes$1),
get_default_slot_context$1
);
}
}
set_attributes(form, form_data = get_spread_update(form_levels, [dirty & /*$$restProps*/ 32 && /*$$restProps*/ ctx[5]]));
},
i(local) {
if (current) return;
transition_in(default_slot, local);
current = true;
},
o(local) {
transition_out(default_slot, local);
current = false;
},
d(detaching) {
if (detaching) detach(form);
if (default_slot) default_slot.d(detaching);
mounted = false;
dispose();
}
};
}
const formKey = {};
function instance$1($$self, $$props, $$invalidate) {
const omit_props_names = [];
let $$restProps = compute_rest_props($$props, omit_props_names);
let $errors;
let { $$slots: slots = {}, $$scope } = $$props;
const dispatch = createEventDispatcher();
const dispatchEvent = (event, detail = {}) => {
dispatch(event, detail);
};
const form$ = useForm();
setContext(formKey, form$);
const { errors, onSubmit, field } = form$;
component_subscribe($$self, errors, value => $$invalidate(1, $errors = value));
let state;
const unsubscribe = form$.subscribe(v => {
$$invalidate(0, state = v);
});
onDestroy(unsubscribe);
const handleSubmit = onSubmit(
data => {
dispatchEvent("success", data);
},
e => {
dispatchEvent("failed", e);
}
);
$$self.$$set = $$new_props => {
$$props = assign(assign({}, $$props), exclude_internal_props($$new_props));
$$invalidate(5, $$restProps = compute_rest_props($$props, omit_props_names));
if ('$$scope' in $$new_props) $$invalidate(6, $$scope = $$new_props.$$scope);
};
return [state, $errors, errors, field, handleSubmit, $$restProps, $$scope, slots];
}
class Form extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance$1, create_fragment$1, safe_not_equal, {});
}
}
/* packages/svelte-hook-form/src/components/Field.svelte generated by Svelte v3.48.0 */
const get_default_slot_changes = dirty => ({
pending: dirty & /*$state$*/ 1,
valid: dirty & /*$state$*/ 1,
errors: dirty & /*$state$*/ 1,
dirty: dirty & /*$state$*/ 1,
touched: dirty & /*$state$*/ 1,
value: dirty & /*$state$*/ 1
});
const get_default_slot_context = ctx => ({
pending: /*$state$*/ ctx[0].pending,
valid: /*$state$*/ ctx[0].valid,
errors: /*$state$*/ ctx[0].errors,
dirty: /*$state$*/ ctx[0].dirty,
touched: /*$state$*/ ctx[0].touched,
value: /*$state$*/ ctx[0].value,
field: /*useField*/ ctx[5],
onChange: /*onChange*/ ctx[2],
onFocus: /*onFocus*/ ctx[3],
onBlur: /*onBlur*/ ctx[4]
});
function create_fragment(ctx) {
let current;
const default_slot_template = /*#slots*/ ctx[14].default;
const default_slot = create_slot(default_slot_template, ctx, /*$$scope*/ ctx[13], get_default_slot_context);
return {
c() {
if (default_slot) default_slot.c();
},
m(target, anchor) {
if (default_slot) {
default_slot.m(target, anchor);
}
current = true;
},
p(ctx, [dirty]) {
if (default_slot) {
if (default_slot.p && (!current || dirty & /*$$scope, $state$*/ 8193)) {
update_slot_base(
default_slot,
default_slot_template,
ctx,
/*$$scope*/ ctx[13],
!current
? get_all_dirty_from_scope(/*$$scope*/ ctx[13])
: get_slot_changes(default_slot_template, /*$$scope*/ ctx[13], dirty, get_default_slot_changes),
get_default_slot_context
);
}
}
},
i(local) {
if (current) return;
transition_in(default_slot, local);
current = true;
},
o(local) {
transition_out(default_slot, local);
current = false;
},
d(detaching) {
if (default_slot) default_slot.d(detaching);
}
};
}
function instance($$self, $$props, $$invalidate) {
let $state$;
let { $$slots: slots = {}, $$scope } = $$props;
let { name } = $$props;
let { defaultValue = "" } = $$props;
let { bail = false } = $$props;
let { validateOnBlur = false } = $$props;
let { validateOnMount = false } = $$props;
let { control = null } = $$props;
let { rules = "" } = $$props;
let form;
if (!control) form = getContext(formKey); else form = get_store_value(control);
const { register, unregister, setValue, setFocus, field } = form;
// reactive state
let state$ = register(name, {
defaultValue,
rules,
validateOnBlur,
validateOnMount,
bail
});
component_subscribe($$self, state$, value => $$invalidate(0, $state$ = value));
// let cache = Object.assign({}, $$props);
// beforeUpdate(() => {
// if (JSON.stringify(rules) !== JSON.stringify(cache.rules)) {
// const value = $state$.value;
// cache = Object.assign({}, cache, { defaultValue: value, value, rules });
// state$ = register(name, cache);
// }
// });
const onChange = e => {
setValue(name, e);
};
const onFocus = () => {
setFocus(name, true);
};
const onBlur = () => {
setFocus(name, false);
};
const useField = node => {
node.setAttribute("name", name);
if (defaultValue) node.setAttribute("value", `${defaultValue}`);
field(node, { rules, validateOnMount, defaultValue });
};
onDestroy(() => {
unregister(name);
});
$$self.$$set = $$props => {
if ('name' in $$props) $$invalidate(6, name = $$props.name);
if ('defaultValue' in $$props) $$invalidate(7, defaultValue = $$props.defaultValue);
if ('bail' in $$props) $$invalidate(8, bail = $$props.bail);
if ('validateOnBlur' in $$props) $$invalidate(9, validateOnBlur = $$props.validateOnBlur);
if ('validateOnMount' in $$props) $$invalidate(10, validateOnMount = $$props.validateOnMount);
if ('control' in $$props) $$invalidate(11, control = $$props.control);
if ('rules' in $$props) $$invalidate(12, rules = $$props.rules);
if ('$$scope' in $$props) $$invalidate(13, $$scope = $$props.$$scope);
};
return [
$state$,
state$,
onChange,
onFocus,
onBlur,
useField,
name,
defaultValue,
bail,
validateOnBlur,
validateOnMount,
control,
rules,
$$scope,
slots
];
}
class Field extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance, create_fragment, safe_not_equal, {
name: 6,
defaultValue: 7,
bail: 8,
validateOnBlur: 9,
validateOnMount: 10,
control: 11,
rules: 12
});
}
}
exports.Field = Field;
exports.Form = Form;
exports.defineRule = defineRule;
exports.useForm = useForm;