MCPcopy Create free account
hub / github.com/formkit/formkit / reset

Function reset

packages/core/src/reset.ts:66–141  ·  view source on GitHub ↗
(
  id: string | FormKitNode,
  resetTo?: unknown
)

Source from the content-addressed store, hash-verified

64 * @public
65 */
66export function reset(
67 id: string | FormKitNode,
68 resetTo?: unknown
69): FormKitNode | undefined {
70 const node = typeof id === 'string' ? getNode(id) : id
71 if (node) {
72 const initial = (n: FormKitNode) => {
73 const initial = cloneAny(n.props.initial)
74
75 if (initial !== undefined) return initial
76
77 return n.type === 'group' ? {} : n.type === 'list' ? [] : undefined
78 }
79
80 // pause all events in this tree.
81 node._e.pause(node)
82 // Set it back to basics
83 const resetValue = cloneAny(resetTo)
84 const hasExplicitReset = Boolean(resetTo && !empty(resetTo))
85 const isDeepReset =
86 hasExplicitReset && node.type !== 'input' && isObject(resetTo)
87 if (hasExplicitReset) {
88 node.props.initial = isObject(resetValue) ? init(resetValue) : resetValue
89 node.props._init = node.props.initial
90 }
91 if (isDeepReset) {
92 node.walk((child) => {
93 const resetAddress = child.address.slice(node.address.length)
94 const childResetValue = valueAtResetAddress(resetValue, resetAddress)
95 const nextInitial =
96 childResetValue === missingResetValue
97 ? initial(child)
98 : cloneAny(childResetValue)
99 child.props.initial = isObject(nextInitial)
100 ? init(nextInitial)
101 : nextInitial
102 child.props._init = child.props.initial
103 })
104 }
105
106 // Set children back to basics in case they were additive (had their own value for example)
107 node.walk((child) => {
108 // Skip resetting synced lists to default.
109 if (child.type === 'list' && child.sync) return
110 child.input(initial(child), false)
111 })
112 // Finally we need to lay any values back on top (if it is a group/list) since group values
113 // take precedence over child values.
114 node.input(
115 empty(resetValue) && resetValue ? resetValue : initial(node),
116 false
117 )
118
119 // If this is a deep reset, we need to make sure the "initial" state of all
120 // children are also reset. Fixes https://github.com/formkit/formkit/issues/791#issuecomment-1651213253
121 if (isDeepReset) {
122 node.walk((child) => {
123 // Clone the value so deep comparisons (e.g., dirty checks) work correctly.

Callers 5

group.spec.tsFile · 0.90
resetValueFunction · 0.90
form.spec.tsFile · 0.90
group.spec.tsFile · 0.90
list.spec.tsFile · 0.90

Calls 9

getNodeFunction · 0.90
cloneAnyFunction · 0.90
emptyFunction · 0.90
isObjectFunction · 0.90
initFunction · 0.90
warnFunction · 0.90
valueAtResetAddressFunction · 0.85
initialFunction · 0.85
clearStateFunction · 0.85

Tested by

no test coverage detected