@picked/svelte 0.0.1-dev.1772412203098 → 0.0.1-dev.1773363643396

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,16 @@
1
- export type { FormField } from './create-form.svelte';
2
- export { getForm } from './get-form';
1
+ import { ValidationError } from '@picked/client';
2
+ interface GetFormOptions {
3
+ id: string;
4
+ title: string;
5
+ onSuccess?: () => void | Promise<void>;
6
+ onError?: (errors: ValidationError[]) => void | Promise<void>;
7
+ }
8
+ type SubmitEventWithCurrentTarget = SubmitEvent & {
9
+ currentTarget: EventTarget & HTMLFormElement;
10
+ };
11
+ export declare function getForm({ id: formId, title, onError, onSuccess }: GetFormOptions): {
12
+ form: {
13
+ onsubmit: import('effector').EventCallable<SubmitEventWithCurrentTarget>;
14
+ };
15
+ };
16
+ export {};
@@ -1 +1 @@
1
- import{getForm as e}from"./get-form.js";export{e as getForm};
1
+ import{createEvent as k,createEffect as m,attach as y,sample as b,split as D}from"effector";import{getPicked as F,getExperience as B}from"../hooks/client.js";import"@picked/client";import{getStep as N}from"../hooks/step.js";import"svelte";import"svelte/store";import"@picked/analytics";function z({id:l,title:d,onError:g,onSuccess:x}){const n=F(),E=N(),i=B(),{currentStepStore:u}=i,h=k(),v=m(e=>n.responses.commit(e)),S=y({source:{step:u},effect:m(({step:e})=>{n.eventBus({type:"form_submit_success",form:{id:l,title:d},experience:i,step:e??void 0}),x?.()})}),A=y({source:{step:u},mapParams:(e,a)=>({step:a.step,errors:e.errors}),effect:m(({step:e,errors:a})=>{n.eventBus({type:"form_submit_error",form:{id:l,title:d},exception:{reason:a},experience:i,step:e??void 0}),a.forEach(c=>{n.eventBus({type:"field_validation_error",exception:{reason:[c]},experience:i,step:e??void 0})}),g?.(a)})});return b({clock:h,source:{step:u},fn:({step:e})=>({formId:l,title:d,step:e}),target:m(({formId:e,title:a,step:c})=>{n.eventBus({type:"form_submit",form:{id:e,title:a},experience:i,step:c??void 0})})}),b({clock:h,source:{fields:n.fields.listStore,stepFields:E.fields,step:u},fn:({stepFields:e},a)=>{a.preventDefault();const c=new FormData(a.currentTarget),_=Array.from(c.entries()),p={data:{},push(t){const s=t.questionId,r=this.data[s];r?Array.isArray(r)&&Array.isArray(t.value)?Array.isArray(r)&&Array.isArray(t.value)&&(typeof r[0]=="string"?this.data[s]=[...r,...t.value].map(String):typeof r[0]=="number"?this.data[s]=[...r,...t.value].map(Number):typeof r[0]=="boolean"?this.data[s]=[...r,...t.value].map(o=>!!o):this.data[s]=t.value):this.data[s]=t.value:this.data[s]=t.value}};return e.forEach(t=>{const s=t.key??t.id??"";let r=_.filter(([o])=>o===s);r.length===0&&(r=[[s,""]]),r.forEach(([,o])=>{const f=s;if(o===""){p.push({questionId:f,value:null});return}switch(t.type){case"text":p.push({questionId:f,value:t.multiple?[String(o)]:String(o)});break;case"number":p.push({questionId:f,value:t.multiple?[Number(o)]:Number(o)});break;case"boolean":p.push({questionId:f,value:t.multiple?[o==="true"]:o==="true"});break}})}),p.data},target:v}),D({source:v.doneData,match:{hasErrors:({errors:e})=>e.length>0},cases:{hasErrors:A,__:S}}),{form:{onsubmit:h}}}export{z as getForm};
@@ -4,9 +4,4 @@ export interface GetFieldResponse {
4
4
  value: Store<FieldValue>;
5
5
  field: Store<Field | null>;
6
6
  }
7
- /**
8
- * @deprecated Field options and status are now available directly on the Field object
9
- * from the step fields store. Use `field.options`, `field.status`, and `field.error`
10
- * instead of accessing them through this hook.
11
- */
12
7
  export declare function getField(id: string): GetFieldResponse;
@@ -1,13 +1,13 @@
1
1
  import { Store } from 'effector';
2
- import { ExperienceStep } from '@picked/client';
3
- import { FormInstance, FormField } from '../form/create-form.svelte';
4
- export interface StepContext extends FormInstance {
2
+ import { ExperienceStep, Field, Response } from '@picked/client';
3
+ type FieldWithValue = Field & {
4
+ value: Response | undefined;
5
+ };
6
+ export interface StepContext {
5
7
  step: Store<ExperienceStep>;
6
- /** Directly accessible fields with current response values — usable without a form */
7
- fields: Store<FormField[]>;
8
- isActive: Store<boolean>;
9
- /** @deprecated Use `isActive` instead */
8
+ fields: Store<FieldWithValue[]>;
10
9
  isActiveStep: Store<boolean>;
11
10
  }
12
- export declare function setStepContext(stepId: string): StepContext;
13
11
  export declare function getStep(): StepContext;
12
+ export declare function setStepContext(stepId: string): StepContext;
13
+ export {};
@@ -1 +1 @@
1
- import{getContext as h,onMount as A,setContext as E}from"svelte";import{createEffect as g,createEvent as O,sample as p}from"effector";import{STEP_CONTEXT_KEY as x}from"../context.js";import{createForm as k}from"../form/create-form.svelte";import{getStepRouter as C}from"../router/context.js";import{getPicked as I,getExperience as _}from"./client.js";function b(c){const o=_().treeStore.map(s=>{const d=s.steps.find(f=>f.id===c);if(!d)throw new Error(`Step with id "${c}" not found in the experience tree.`);return d}),l=o.map(s=>s.label),u=o.map(s=>s.fieldIds),r=k(c,l,u);return{stepStore:o,form:r}}function K(c){const{activeStep:a}=C(),o=a.map(e=>e?.id===c),{stepStore:l,form:u}=b(c),r=I(),s=g(e=>{r.fields.resolveAll(e)});function d(e,n){return e.dependsOn?.length?e.dependsOn.every(i=>{const t=n[i];return t!=null&&t!==""&&!(Array.isArray(t)&&t.length===0)}):!0}const f=O();p({clock:f,source:{step:l,fields:r.fields.listStore},fn:({step:e,fields:n})=>e.fieldIds.filter(i=>!n.find(t=>t.id===i)?.dependsOn?.length),target:s});const m=g(({step:e,fields:n,responses:i})=>{for(const t of e.fieldIds){const S=n.find(v=>v.id===t);S?.dependsOn?.length&&(d(S,i)?r.fields.resolveAll([t],{force:!0,context:{responses:i}}):r.fields.setWaiting(t))}});return p({clock:f,source:{step:l,fields:r.fields.listStore,responses:r.responses.getAllStore},target:m}),A(()=>{f()}),p({clock:o,source:{step:l,fields:r.fields.listStore},filter:(e,n)=>n,fn:({step:e,fields:n})=>e.fieldIds.filter(i=>!n.find(t=>t.id===i)?.dependsOn?.length),target:s}),p({clock:o,source:{step:l,fields:r.fields.listStore,responses:r.responses.getAllStore},filter:(e,n)=>n,target:m}),E(x,{step:l,isActive:o,isActiveStep:o,...u})}function M(){return h(x)}export{M as getStep,K as setStepContext};
1
+ import{getContext as v,setContext as x}from"svelte";import{createStore as E,combine as l,attach as h,createEffect as w,sample as p}from"effector";import{getStepFields as A}from"@picked/client";import{STEP_CONTEXT_KEY as u}from"../context.js";import{getStepRouter as C}from"../router/context.js";import{getExperience as k,getPicked as y}from"./client.js";function D(){return v(u)}function N(s){const S=k(),o=y(),{activeStep:d}=C(),i=d.map(e=>e?.id===s),f=S.treeStore.map(e=>{const r=e.steps.find(t=>t.id===s);if(!r)throw new Error(`Step with id "${s}" not found in the experience tree.`);return r}),a=E([]),m=l({fields:a,responses:o.responses.listStore},({fields:e,responses:r})=>e.map(t=>{const c=r.find(g=>g.fieldId===t.id)?.value;return{...t,value:c}})),n=h({source:l({step:f,fields:o.fields.listStore}),effect:w(async({step:{fieldIds:e},fields:r})=>await A(o,r.filter(t=>{const c=t.key??t.id??"";return e.includes(c)})))});return p({source:{isActiveStep:i},filter:({isActiveStep:e})=>e,target:n}),p({clock:o.responses.listStore,source:{isActiveStep:i},filter:({isActiveStep:e})=>e,target:n}),p({source:n.doneData,target:a}),x(u,{step:f,fields:m,isActiveStep:i})}export{D as getStep,N as setStepContext};
@@ -20,7 +20,7 @@
20
20
  <td>{$currentNode?.id || ''}</td>
21
21
  <td>{$currentNode?.type || ''}</td>
22
22
  <td>{$currentStep?.id || ''}</td>
23
- <td>{$currentStep?.label || ''}</td>
23
+ <td>{$currentStep?.name || ''}</td>
24
24
  <td>{totalNextStepNodes}</td>
25
25
  <td>{$stepsToOrigin[0]} - {$stepsToOrigin[1]}</td>
26
26
  <td>{$stepsToLeaf[0]} - {$stepsToLeaf[1]}</td>
@@ -1 +1 @@
1
- import{__vitePreload as i}from"../../_virtual/preload-helper.js";import{lazyComponent as r}from"@picked/client";import{createExperience as p,createExperiencePlugin as a}from"@picked/client/plugins/create-experience";import{adaptSvelteComponent as l}from"../../component.js";const v=t=>{const e=p({id:"devtools",name:"Picked Devtools",condition:!1,initializeOpen:!1,targets:[{selector:"body",placement:"append"}],component:l(r(()=>i(()=>import("./DevToolsExperience.svelte"),[])))});return e.addStep({label:"Tools"}),[{name:"svelte-devtools",setup:o=>{t?.enabled&&o.eventBus.watch(n=>{n.type==="ready"&&o.experiences.launch({id:e.id,options:{bypassCondition:!0}})})}},a({experiences:[e]})]};export{v as svelteDevtoolsPlugin};
1
+ import{__vitePreload as i}from"../../_virtual/preload-helper.js";import{lazyComponent as r}from"@picked/client";import{createExperience as p,createExperiencePlugin as a}from"@picked/client/plugins/create-experience";import{adaptSvelteComponent as s}from"../../component.js";const v=t=>{const e=p({id:"devtools",name:"Picked Devtools",condition:!1,initializeOpen:!1,targets:[{selector:"body",placement:"append"}],component:s(r(()=>i(()=>import("./DevToolsExperience.svelte"),[])))});return e.addStep({name:"Tools"}),[{name:"svelte-devtools",setup:o=>{t?.enabled&&o.eventBus.watch(n=>{n.type==="ready"&&o.experiences.launch({id:e.id,options:{bypassCondition:!0}})})}},a({experiences:[e]})]};export{v as svelteDevtoolsPlugin};
@@ -10,7 +10,7 @@
10
10
  <EventsTable />
11
11
  <Spacer />
12
12
  <Divider />
13
- <Stack padding="small">
13
+ <Stack padding="small">
14
14
  <Text size="caption" color="subdued">
15
15
  {$events.length} events
16
16
  </Text>
@@ -19,8 +19,8 @@
19
19
  <Card sectioned>
20
20
  <Stack direction="vertical" gap="medium" padding="medium">
21
21
  <div>
22
- <Text weight="semibold">Type</Text>
23
- <Text>{$config.type}</Text>
22
+ <Text weight="semibold">Name</Text>
23
+ <Text>{$config.name}</Text>
24
24
  </div>
25
25
 
26
26
  <div>
@@ -100,7 +100,7 @@
100
100
  const getNodeLabel = (node: ExperienceNode): string => {
101
101
  if (node.type === 'origin') return 'Start'
102
102
  if (node.type === 'step' && node.stepId)
103
- return stepsMap.get(node.stepId)?.label ?? 'Unknown Step'
103
+ return stepsMap.get(node.stepId)?.name ?? 'Unknown Step'
104
104
  if (node.type === 'conditional' && node.conditionalId) {
105
105
  const conditional = conditionalsMap.get(node.conditionalId)
106
106
  if (conditional?.label) return conditional.label
@@ -186,7 +186,7 @@
186
186
  const g = svg.append('g').attr('transform', `translate(${margin.left},${margin.top})`)
187
187
 
188
188
  const linkGenerator = d3
189
- .linkHorizontal<d3.HierarchyPointLink<ProcessedNode>, ProcessedNode>()
189
+ .linkHorizontal<d3.HierarchyPointLink<ProcessedNode>, d3.HierarchyPointNode<ProcessedNode>>()
190
190
  .x((d) => d.y)
191
191
  .y((d) => d.x)
192
192
 
@@ -1,5 +1,5 @@
1
1
  <script lang="ts">
2
- import type { ResponseListItem, PrimitiveFieldValue, Field, FieldValue } from '@picked/client'
2
+ import type { ResponseListItem, PrimitiveFieldValue, FieldValue, Field } from '@picked/client'
3
3
  import { getPicked } from '../../../../hooks'
4
4
  import { Button, Text, CodeBlock, Banner, Stack } from '../../ui'
5
5
 
@@ -8,13 +8,21 @@
8
8
 
9
9
  const client = getPicked()
10
10
 
11
+ function isPrimitiveFieldValue(val: unknown): val is PrimitiveFieldValue {
12
+ return val === null || typeof val === 'string' || typeof val === 'number' || typeof val === 'boolean'
13
+ }
14
+
15
+ function isOptionSelected(optionValue: unknown): boolean {
16
+ if (!isPrimitiveFieldValue(optionValue)) return false
17
+ return selectedOptions.has(optionValue)
18
+ }
19
+
11
20
  let isEditing = false
12
21
  let editValue = ''
13
22
  let editError = ''
14
- let selectedOptions: Set<FieldValue> = new Set()
23
+ let selectedOptions: Set<PrimitiveFieldValue> = new Set()
15
24
 
16
- $: hasOptions = Array.isArray(field?.options) && field.options.length > 0
17
- $: staticOptions = Array.isArray(field?.options) ? field.options : null
25
+ $: hasOptions = field?.options && field.options.length > 0
18
26
  $: currentValue = response?.value ?? null
19
27
 
20
28
  function formatValue(value: unknown): string {
@@ -37,8 +45,8 @@
37
45
  if (hasOptions) {
38
46
  selectedOptions = new Set()
39
47
  if (Array.isArray(currentValue)) {
40
- currentValue.forEach((v) => selectedOptions.add(v))
41
- } else if (currentValue !== null && currentValue !== undefined) {
48
+ currentValue.forEach((v) => { if (isPrimitiveFieldValue(v)) selectedOptions.add(v) })
49
+ } else if (isPrimitiveFieldValue(currentValue)) {
42
50
  selectedOptions.add(currentValue)
43
51
  }
44
52
  } else {
@@ -53,7 +61,8 @@
53
61
  selectedOptions = new Set()
54
62
  }
55
63
 
56
- function toggleOption(optionValue: FieldValue) {
64
+ function toggleOption(optionValue: unknown) {
65
+ if (!isPrimitiveFieldValue(optionValue)) return
57
66
  if (field?.multiple) {
58
67
  if (selectedOptions.has(optionValue)) {
59
68
  selectedOptions.delete(optionValue)
@@ -107,12 +116,13 @@
107
116
  if (field?.multiple) {
108
117
  newValue = values
109
118
  } else {
110
- newValue = values.at(0) ?? null
119
+ newValue = values[0] ?? null
111
120
  }
112
121
  } else {
113
122
  newValue = parseValue(editValue)
114
123
  }
115
124
 
125
+ if (field.id == null) return
116
126
  const result = await client.responses.commit({ [field.id]: newValue })
117
127
 
118
128
  if (result.errors.length > 0) {
@@ -129,6 +139,7 @@
129
139
  }
130
140
 
131
141
  function handleClear() {
142
+ if (field.id == null) return
132
143
  client.responses.clear(field.id)
133
144
  }
134
145
  </script>
@@ -143,21 +154,21 @@
143
154
  <td>
144
155
  {#if isEditing}
145
156
  <Stack direction="vertical" gap="small">
146
- {#if hasOptions && staticOptions}
157
+ {#if hasOptions && field?.options}
147
158
  <Stack direction="vertical" gap="small">
148
- {#each staticOptions as option (option.id)}
159
+ {#each field.options as option (option.id)}
149
160
  <label class="option-label">
150
161
  {#if field.multiple}
151
162
  <input
152
163
  type="checkbox"
153
- checked={selectedOptions.has(option.value)}
164
+ checked={isOptionSelected(option.value)}
154
165
  on:change={() => toggleOption(option.value)}
155
166
  />
156
167
  {:else}
157
168
  <input
158
169
  type="radio"
159
170
  name="field-{field.id}"
160
- checked={selectedOptions.has(option.value)}
171
+ checked={isOptionSelected(option.value)}
161
172
  on:change={() => toggleOption(option.value)}
162
173
  />
163
174
  {/if}
@@ -16,7 +16,7 @@
16
16
  $: responseMap = new Map(responses.map((r) => [r.fieldId, r]))
17
17
 
18
18
  $: allFieldRows = allFields.map((field) => {
19
- const response = responseMap.get(field.id)
19
+ const response = field.id != null ? responseMap.get(field.id) : undefined
20
20
  return {
21
21
  field,
22
22
  response: response || null,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@picked/svelte",
3
- "version": "0.0.1-dev.1772412203098",
3
+ "version": "0.0.1-dev.1773363643396",
4
4
  "dependencies": {
5
5
  "d3": "^7.9.0"
6
6
  },
@@ -9,6 +9,7 @@
9
9
  "@picked/client": "workspace:*",
10
10
  "@repo/eslint-config": "workspace:*",
11
11
  "@repo/typescript-config": "workspace:*",
12
+ "@size-limit/file": "^12.0.0",
12
13
  "@sveltejs/package": "^2.3.11",
13
14
  "@sveltejs/vite-plugin-svelte": "^6.2.4",
14
15
  "@tsconfig/svelte": "^5.0.4",
@@ -18,6 +19,7 @@
18
19
  "effector": "^23.3.0",
19
20
  "fast-glob": "^3.3.3",
20
21
  "happy-dom": "^20.0.2",
22
+ "size-limit": "^12.0.0",
21
23
  "svelte": "^5.34.3",
22
24
  "svelte-check": "^4.2.2",
23
25
  "typedoc": "^0.28.5",
@@ -78,15 +80,43 @@
78
80
  "knip",
79
81
  "jscpd",
80
82
  "eslint",
81
- "tsc"
83
+ "tsc",
84
+ "attw"
82
85
  ],
86
+ "ignoreDependencies": [
87
+ "@picked/analytics",
88
+ "@picked/client",
89
+ "@repo/eslint-config",
90
+ "@repo/typescript-config",
91
+ "@sveltejs/package",
92
+ "@tsconfig/svelte"
93
+ ],
94
+ "ignoreFiles": [
95
+ "eslint.config.js",
96
+ "src/components/index.ts",
97
+ "src/components/LazyImage.svelte",
98
+ "src/index.ts",
99
+ "src/plugins/devtools/index.ts",
100
+ "src/plugins/devtools/PickedLogo.svelte",
101
+ "src/plugins/framework/index.ts",
102
+ "src/router/index.ts",
103
+ "src/router/Step.svelte",
104
+ "src/router/StepRouter.svelte"
105
+ ],
106
+ "ignoreIssues": {
107
+ "src/**": [
108
+ "exports",
109
+ "types",
110
+ "duplicates"
111
+ ]
112
+ },
83
113
  "entry": [
84
114
  "src/plugins/devtools/ui/index.ts"
85
115
  ]
86
116
  },
87
117
  "module": "./dist/index.js",
88
118
  "peerDependencies": {
89
- "@picked/client": "0.0.1-dev.1772412203098",
119
+ "@picked/client": "0.0.1-dev.1773363643396",
90
120
  "effector": "^23.3.0",
91
121
  "svelte": "^5.34.3"
92
122
  },
@@ -98,10 +128,11 @@
98
128
  "dev": "vite build --watch",
99
129
  "jscpd": "jscpd src",
100
130
  "knip": "knip",
101
- "lint": "eslint .",
131
+ "lint": "if [ \"$AGENT\" = \"true\" ]; then echo \"[AGENT HINT] Prefer running lint on specific files from the repo root: node scripts/lint-files.js <files>\"; fi && eslint .",
102
132
  "lint-files": "eslint",
103
133
  "lint:format": "eslint . --fix",
104
134
  "lint:report": "eslint . -o './.reports/eslint.json' -f json || [ -f './.reports/eslint.json' ]",
135
+ "size": "size-limit",
105
136
  "svelte-check": "svelte-check --tsconfig ./tsconfig.json",
106
137
  "svelte-check:report": "mkdir -p ./.reports && pnpm svelte-check --tsconfig ./tsconfig.json --output=machine > ./.reports/svelte-check.txt || [ -f './.reports/svelte-check.txt' ]",
107
138
  "test": "vitest run",
@@ -110,6 +141,36 @@
110
141
  "test:watch": "vitest",
111
142
  "type-check": "tsc -p . --noEmit"
112
143
  },
144
+ "size-limit": [
145
+ {
146
+ "path": "dist/index.js",
147
+ "limit": "10 kB"
148
+ },
149
+ {
150
+ "path": "dist/server/index.js",
151
+ "limit": "10 kB"
152
+ },
153
+ {
154
+ "path": "dist/router/index.js",
155
+ "limit": "5 kB"
156
+ },
157
+ {
158
+ "path": "dist/form/index.js",
159
+ "limit": "5 kB"
160
+ },
161
+ {
162
+ "path": "dist/hooks/index.js",
163
+ "limit": "5 kB"
164
+ },
165
+ {
166
+ "path": "dist/plugins/framework/index.js",
167
+ "limit": "5 kB"
168
+ },
169
+ {
170
+ "path": "dist/plugins/devtools/index.js",
171
+ "limit": "5 kB"
172
+ }
173
+ ],
113
174
  "svelte": "./dist/index.js",
114
175
  "type": "module",
115
176
  "types": "./dist/index.d.ts"
@@ -1,13 +0,0 @@
1
- import { FieldBase, FieldValue } from '@picked/client';
2
- type FieldLike = Pick<FieldBase, 'id' | 'type' | 'multiple'>;
3
- /**
4
- * Parses a FormData snapshot into a typed record of field responses.
5
- *
6
- * - Fields absent from FormData are mapped to `null`.
7
- * - Empty string values are mapped to `null`.
8
- * - Repeated entries for the same field (e.g. multi-select checkboxes) are
9
- * merged into a typed array — matching the field's declared element type.
10
- * - Values are coerced to the field's declared type (text → string, number → number, boolean → boolean).
11
- */
12
- export declare function buildResponsesFromFormData(fields: FieldLike[], formData: FormData): Record<string, FieldValue>;
13
- export {};
@@ -1 +0,0 @@
1
- function i(e,o,n){const r=e[o];if(r===void 0){e[o]=n;return}if(Array.isArray(r)&&Array.isArray(n)&&n.length>0){typeof r[0]=="string"?e[o]=[...r,...n].map(String):typeof r[0]=="number"?e[o]=[...r,...n].map(Number):typeof r[0]=="boolean"?e[o]=[...r,...n].map(t=>!!t):e[o]=n;return}e[o]=n}function b(e,o){const n=Array.from(o.entries()),r={};return e.forEach(t=>{let m=n.filter(([s])=>s===t.id);m.length===0&&(m=[[t.id,""]]),m.forEach(([,s])=>{if(s===""){i(r,t.id,null);return}switch(t.type){case"text":case"object":i(r,t.id,t.multiple?[String(s)]:String(s));break;case"number":i(r,t.id,t.multiple?[Number(s)]:Number(s));break;case"boolean":i(r,t.id,t.multiple?[s==="true"]:s==="true");break}})}),r}export{b as buildResponsesFromFormData};
@@ -1,17 +0,0 @@
1
- import { FieldValue, FieldWithStatus, Picked } from '@picked/client';
2
- import { Store, StoreWritable } from 'effector';
3
- /**
4
- * Creates a reactive store of evaluated fields for a given set of field IDs.
5
- *
6
- * Fields are re-evaluated whenever:
7
- * - The available field IDs change (e.g. a step is entered)
8
- * - Any response is committed (options may depend on prior answers)
9
- * - The global field registry changes (fields registered after init)
10
- * - Staged values change (field visibility conditions may reference responses.*)
11
- *
12
- * Evaluation runs `getStepFields` with effective responses (committed + staged) as context,
13
- * so visibility conditions see live in-session values rather than only committed responses.
14
- */
15
- export declare function createFieldEvaluator(client: Picked, fieldIds: Store<string[]>, stagedValuesStore: StoreWritable<Record<string, FieldValue>>): {
16
- fieldsStore: Store<FieldWithStatus[]>;
17
- };
@@ -1 +0,0 @@
1
- import{getStepFields as m}from"@picked/client";import{createStore as u,attach as F,createEffect as S,sample as i}from"effector";function k(e,r,s){const o=u([]),t=F({source:{allFields:e.fields.listStore,fieldIds:r,staged:s,committed:e.responses.getAllStore},effect:S(async({allFields:l,fieldIds:a,staged:c,committed:d})=>{const f=l.filter(p=>a.includes(p.id)),n={...d,...c};return await m(e,f,{responses:n})})});return i({clock:t.doneData,target:o}),t(),i({clock:[e.responses.listStore,r,e.fields.listStore,s],target:t}),{fieldsStore:o}}export{k as createFieldEvaluator};
@@ -1,41 +0,0 @@
1
- import { FieldValue, FieldWithStatus, Picked, ValidationError } from '@picked/client';
2
- import { EventCallable, Store, StoreWritable } from 'effector';
3
- export interface FieldValidation {
4
- /** Dispatch when a field value changes — runs validation if the field has been touched. */
5
- fieldChangeEvent: EventCallable<{
6
- fieldId: string;
7
- value: FieldValue;
8
- }>;
9
- /** Dispatch when a field loses focus — always runs full validation including required check. */
10
- fieldBlurEvent: EventCallable<{
11
- fieldId: string;
12
- value: FieldValue;
13
- }>;
14
- /** Which fields have been interacted with — used by formFieldsStore to show/hide errors. */
15
- touchedStore: StoreWritable<Partial<Record<string, boolean>>>;
16
- /**
17
- * Per-field validation errors — written by client-side validation and overwritten
18
- * by server errors on commit failure. Exposed as writable so the submit pipeline
19
- * can populate server errors and reset state on new submit attempts.
20
- */
21
- fieldErrorsStore: StoreWritable<Partial<Record<string, ValidationError>>>;
22
- /** Flat list of all current validation errors — derived from fieldErrorsStore. */
23
- formErrorsStore: Store<ValidationError[]>;
24
- /**
25
- * Current in-session field values — updated on every onChange/onBlur before commit.
26
- * Used as the responses context for condition evaluation so conditions react to
27
- * live input without writing to client.responses prematurely.
28
- */
29
- stagedValuesStore: StoreWritable<Record<string, FieldValue>>;
30
- }
31
- /**
32
- * Creates the client-side validation slice for a form.
33
- *
34
- * Responsibilities:
35
- * - Tracks which fields have been touched (first blur = touched)
36
- * - Validates on blur (full: includes required check) and on change (if already touched)
37
- * - Uses the same json-logic evaluator the server uses, so client and server results match
38
- * - Maintains stagedValuesStore: current in-session values used as responses context for
39
- * condition evaluation, avoiding premature writes to client.responses
40
- */
41
- export declare function createFieldValidation(client: Picked, fieldsStore: Store<FieldWithStatus[]>, stagedValuesStore: StoreWritable<Record<string, FieldValue>>): FieldValidation;
@@ -1 +0,0 @@
1
- import{evaluateRuleLogic as M}from"@picked/client";import{createEvent as h,createStore as y,sample as p,attach as q}from"effector";function F(s){return s===null||s===""||Array.isArray(s)&&s.length===0}function R(s,k,c){const f=h(),a=h(),u=y({});p({clock:a,source:u,fn:(r,{fieldId:e})=>({...r,[e]:!0}),target:u});const g=y({}),v=g.map(r=>Object.values(r).filter(e=>e!==void 0)),m=q({source:{fields:k,staged:c,committed:s.responses.getAllStore},effect:async({fields:r,staged:e,committed:n},{fieldId:t,value:i,checkRequired:E})=>{const o=r.find(d=>d.id===t);if(!o)return{fieldId:t,error:null};if(o.validation&&Object.keys(o.validation).length>0){const d={...n,...e},l=await M(s,o.validation,{responses:d,$input:i});if(typeof l=="string")return{fieldId:t,error:{fieldId:t,userMessage:l,systemMessage:l,value:i}};if(l===!1)return{fieldId:t,error:{fieldId:t,userMessage:"This field is invalid",systemMessage:"Field validation rule returned false.",value:i}}}return E&&o.required&&F(i)?{fieldId:t,error:{fieldId:t,userMessage:"This field is required",systemMessage:"Field is required.",value:i}}:{fieldId:t,error:null}}});return p({clock:f,source:u,filter:(r,{fieldId:e})=>r[e]===!0,fn:(r,{fieldId:e,value:n})=>({fieldId:e,value:n,checkRequired:!1}),target:m}),p({clock:a,fn:({fieldId:r,value:e})=>({fieldId:r,value:e,checkRequired:!0}),target:m}),c.on(f,(r,{fieldId:e,value:n})=>({...r,[e]:n})),c.on(a,(r,{fieldId:e,value:n})=>({...r,[e]:n})),g.on(m.doneData,(r,{fieldId:e,error:n})=>{if(n===null){const t={...r};return delete t[e],t}return{...r,[e]:n}}),{fieldChangeEvent:f,fieldBlurEvent:a,touchedStore:u,fieldErrorsStore:g,formErrorsStore:v,stagedValuesStore:c}}export{R as createFieldValidation};
@@ -1 +0,0 @@
1
- import"svelte/internal/client";import{createStore as C,combine as P,attach as j,sample as u}from"effector";import{getPicked as N,getExperience as R}from"../hooks/client.js";import{createFieldEvaluator as W}from"./create-field-evaluator.js";import{createFieldValidation as q}from"./create-field-validation.js";import{createSubmitPipeline as w}from"./create-submit-pipeline.svelte";function x(m){const t=m.currentTarget;if(t instanceof HTMLInputElement)return t.type==="checkbox"?t.checked:t.value;if(t instanceof HTMLSelectElement||t instanceof HTMLTextAreaElement)return t.value}function X(m,t,k){const r=N(),g=R(),{currentStepStore:F,goToNextStep:I}=g,d=C({}),{fieldsStore:a}=W(r,k,d),{fieldChangeEvent:E,fieldBlurEvent:T,touchedStore:b,fieldErrorsStore:p,formErrorsStore:A}=q(r,a,d),y=P({fields:a,responses:r.responses.listStore,staged:d,fieldErrors:p,touched:b},({fields:s,responses:o,staged:i,fieldErrors:S,touched:f})=>s.map(e=>({...e,value:i[e.id]??o.find(n=>n.fieldId===e.id)?.value,error:S[e.id],touched:f[e.id]??!1,onChange:n=>{const c=x(n);c!==void 0&&E({fieldId:e.id,value:c})},onBlur:n=>{const c=x(n);c!==void 0&&T({fieldId:e.id,value:c})}}))),D=j({source:{staged:d,committed:r.responses.getAllStore,allFields:r.fields.listStore},effect:({staged:s,committed:o,allFields:i},S)=>{const f={...o,...s};for(const e of S){const n=i.find(v=>v.id===e);if(!n)continue;(n.dependsOn??[]).every(v=>{const l=f[v];return l!=null&&l!==""&&!(Array.isArray(l)&&l.length===0)})?r.fields.resolveAll([e],{force:!0,context:{responses:f}}):r.fields.setWaiting(e)}}});u({clock:E,source:{fields:a},fn:({fields:s},{fieldId:o})=>s.filter(i=>i.dependsOn?.includes(o)).map(i=>i.id),target:D});const{submitEvent:H,isFormSubmitting:L,onSubmit:M,onSuccess:O,onError:V,submitStarted:h,serverErrorsReceived:B}=w({client:r,experienceInstance:g,formId:m,title:t,stepStore:F,fieldsStore:a,goToNextStep:I});return u({clock:h,fn:()=>({}),target:b}),u({clock:h,fn:()=>({}),target:p}),u({clock:B,fn:s=>Object.fromEntries(s.map(o=>[o.fieldId,o])),target:p}),{form:{onsubmit:H,errors:A,submitting:L,onSubmit:M,onSuccess:O,onError:V},fields:y}}export{X as createForm};
@@ -1,41 +0,0 @@
1
- import { FieldValue, FieldWithStatus, ValidationError } from '@picked/client';
2
- import { EventCallable, Store } from 'effector';
3
- import { ErrorCallback, SubmitCallback, SubmitEventWithCurrentTarget, SuccessCallback } from './create-submit-pipeline.svelte';
4
- export type FormField = Omit<FieldWithStatus, 'error'> & {
5
- value: FieldValue | undefined;
6
- /** Validation error for this field, or undefined if valid. */
7
- error: ValidationError | undefined;
8
- touched: boolean;
9
- onChange: (e: Event) => void;
10
- onBlur: (e: Event) => void;
11
- };
12
- /**
13
- * Return type for createForm()
14
- * Provides form handlers, reactive stores, and callback registration
15
- */
16
- export interface FormInstance<TFieldIds extends string = string> {
17
- /** Form element props (bind to <form>) */
18
- form: {
19
- onsubmit: EventCallable<SubmitEventWithCurrentTarget>;
20
- /** Flat list of all current validation errors — derived from fieldErrors */
21
- errors: Store<ValidationError[]>;
22
- /** Reactive store indicating if form is currently submitting */
23
- submitting: Store<boolean>;
24
- /** Register callbacks to transform/validate data before submission */
25
- onSubmit: (callback: SubmitCallback<TFieldIds>) => void;
26
- /** Register callbacks to run on successful form submission */
27
- onSuccess: (callback: SuccessCallback<TFieldIds>) => void;
28
- /** Register callbacks to run on form validation errors */
29
- onError: (callback: ErrorCallback) => void;
30
- };
31
- /** Reactive store of fields with current values, errors, touched state, and event handlers */
32
- fields: Store<FormField[]>;
33
- }
34
- /**
35
- * Creates a form instance tied to a set of field IDs.
36
- * Handles field evaluation, form submission, data transformation,
37
- * validation, event bus tracking, and step navigation.
38
- *
39
- * Used internally by setStepContext — access via getStep() in components.
40
- */
41
- export declare function createForm(formId: string, title: Store<string>, fieldIds: Store<string[]>): FormInstance;
@@ -1 +0,0 @@
1
- export * from './create-form.js';
@@ -1 +0,0 @@
1
- import*as C from"svelte/internal/client";import{createEvent as i,createStore as B,createEffect as l,attach as O,sample as s,split as R}from"effector";import{buildResponsesFromFormData as T}from"./build-responses.js";function k(c){let o=[];return{executeFx:l(async(...a)=>await c(o,...a)),register:a=>{const f=()=>{o=o.filter(p=>p!==a)};C.user_effect(()=>(o.push(a),f))}}}function q({client:c,experienceInstance:o,formId:u,title:m,stepStore:a,fieldsStore:f,goToNextStep:p}){const n=i(),y=i(),v=i(),_=i(),x=i(),d=B(!1),D=B(!1);D.on(_,()=>!0).on(n,()=>!1);const N=n.map(()=>{}),g=k(async(e,t)=>{await Promise.all(e.map(r=>Promise.resolve(r(t))))}),b=k(async(e,t)=>{await Promise.all(e.map(r=>Promise.resolve(r(t))))}),F=k(async(e,t)=>{let r=t;for(const E of e){const w=await Promise.resolve(E(r));w!==void 0&&(r=w)}return r}),P=l(async e=>{const t=await c.responses.commit(e);return{data:e,errors:t.errors}}),h=O({source:{step:a,title:m},mapParams:(e,t)=>({step:t.step,title:t.title,data:e.data}),effect:l(async({step:e,title:t,data:r})=>(c.eventBus({type:"form_submit_success",form:{id:u,title:t},experience:o,step:e??void 0}),r))}),S=O({source:{step:a,title:m},mapParams:(e,t)=>({step:t.step,title:t.title,errors:e.errors}),effect:l(async({step:e,title:t,errors:r})=>(c.eventBus({type:"form_submit_error",form:{id:u,title:t},exception:{reason:r},experience:o,step:e??void 0}),r.forEach(E=>{c.eventBus({type:"field_validation_error",exception:{reason:[E]},experience:o,step:e??void 0})}),r))});return s({clock:n,fn:()=>!0,target:d}),s({clock:n,source:{step:a,title:m},fn:({step:e,title:t})=>({formId:u,title:t,step:e}),target:l(({formId:e,title:t,step:r})=>{c.eventBus({type:"form_submit",form:{id:e,title:t},experience:o,step:r??void 0})})}),s({clock:n,source:{stepFields:f},fn:({stepFields:e},t)=>(t.preventDefault(),T(e,new FormData(t.currentTarget))),target:F.executeFx}),s({clock:F.executeFx.doneData,target:P}),R({source:P.doneData,match:{hasErrors:({errors:e})=>e.length>0},cases:{hasErrors:S,__:h}}),s({clock:h.doneData,target:y}),s({clock:y,fn:e=>({data:e,stopNavigation:_}),target:g.executeFx}),s({clock:g.executeFx.done,target:x}),s({clock:x,source:D,filter:e=>!e,target:p}),s({clock:S.doneData,target:v}),s({clock:v,target:b.executeFx}),s({clock:[x,b.executeFx.done],fn:()=>!1,target:d}),{submitEvent:n,isFormSubmitting:d,onSubmit:F.register,onSuccess:g.register,onError:b.register,submitStarted:N,serverErrorsReceived:v}}export{q as createSubmitPipeline};
@@ -1,53 +0,0 @@
1
- import { ExperienceInstance, ExperienceStep, FieldValue, FieldWithStatus, Picked, ValidationError } from '@picked/client';
2
- import { Event, EventCallable, Store } from 'effector';
3
- export type SubmitEventWithCurrentTarget = SubmitEvent & {
4
- currentTarget: EventTarget & HTMLFormElement;
5
- };
6
- export type SuccessCallback<TFieldIds extends string = string> = (options: {
7
- data: Record<TFieldIds, FieldValue>;
8
- stopNavigation: EventCallable<void>;
9
- }) => void | Promise<void>;
10
- export type ErrorCallback = (errors: ValidationError[]) => void | Promise<void>;
11
- export type SubmitCallback<TFieldIds extends string = string> = (data: Record<TFieldIds, FieldValue>) => Record<TFieldIds, FieldValue> | void | Promise<Record<TFieldIds, FieldValue> | void>;
12
- export interface SubmitPipelineConfig {
13
- client: Picked;
14
- experienceInstance: ExperienceInstance;
15
- formId: string;
16
- title: Store<string>;
17
- stepStore: Store<ExperienceStep | null>;
18
- fieldsStore: Store<FieldWithStatus[]>;
19
- goToNextStep: EventCallable<void>;
20
- }
21
- export interface SubmitPipeline {
22
- submitEvent: EventCallable<SubmitEventWithCurrentTarget>;
23
- isFormSubmitting: Store<boolean>;
24
- onSubmit: (callback: SubmitCallback) => void;
25
- onSuccess: (callback: SuccessCallback) => void;
26
- onError: (callback: ErrorCallback) => void;
27
- /**
28
- * Fired when a submit attempt starts — callers use this to clear validation state.
29
- * Separating this from `submitEvent` keeps the pipeline decoupled from the
30
- * validation module's internal stores.
31
- */
32
- submitStarted: Event<void>;
33
- /**
34
- * Fired when the server returns validation errors — callers write these to
35
- * `fieldErrorsStore` in the validation module.
36
- */
37
- serverErrorsReceived: Event<ValidationError[]>;
38
- }
39
- /**
40
- * Creates the submit pipeline for a form instance.
41
- *
42
- * Manages the full lifecycle of a form submission:
43
- * - Emitting event bus calls (form_submit, form_submit_success, form_submit_error)
44
- * - Running onSubmit data-transform callbacks in series
45
- * - Committing responses to the server
46
- * - Running onSuccess/onError callbacks in parallel
47
- * - Navigating to the next step (unless stopNavigation is called)
48
- *
49
- * Returns coordination events (`submitStarted`, `serverErrorsReceived`) that the
50
- * caller wires to the validation module to keep validation state in sync without
51
- * the pipeline needing direct access to validation stores.
52
- */
53
- export declare function createSubmitPipeline({ client, experienceInstance, formId, title, stepStore, fieldsStore, goToNextStep, }: SubmitPipelineConfig): SubmitPipeline;
@@ -1 +0,0 @@
1
- export * from './create-submit-pipeline.js';
@@ -1,16 +0,0 @@
1
- import { ValidationError } from '@picked/client';
2
- interface GetFormOptions {
3
- id: string;
4
- title: string;
5
- onSuccess?: () => void | Promise<void>;
6
- onError?: (errors: ValidationError[]) => void | Promise<void>;
7
- }
8
- type SubmitEventWithCurrentTarget = SubmitEvent & {
9
- currentTarget: EventTarget & HTMLFormElement;
10
- };
11
- export declare function getForm({ id: formId, title, onError, onSuccess }: GetFormOptions): {
12
- form: {
13
- onsubmit: import('effector').EventCallable<SubmitEventWithCurrentTarget>;
14
- };
15
- };
16
- export {};
@@ -1 +0,0 @@
1
- import{createEvent as _,createEffect as f,attach as v,sample as y,split as k}from"effector";import{getPicked as D,getExperience as F}from"../hooks/client.js";import"@picked/client";import{getStep as B}from"../hooks/step.js";import"svelte";import"svelte/store";import"@picked/analytics";function z({id:m,title:l,onError:b,onSuccess:g}){const a=D(),x=B(),i=F(),{currentStepStore:u}=i,d=_(),h=f(t=>a.responses.commit(t)),E=v({source:{step:u},effect:f(({step:t})=>{a.eventBus({type:"form_submit_success",form:{id:m,title:l},experience:i,step:t??void 0}),g?.()})}),S=v({source:{step:u},mapParams:(t,s)=>({step:s.step,errors:t.errors}),effect:f(({step:t,errors:s})=>{a.eventBus({type:"form_submit_error",form:{id:m,title:l},exception:{reason:s},experience:i,step:t??void 0}),s.forEach(c=>{a.eventBus({type:"field_validation_error",exception:{reason:[c]},experience:i,step:t??void 0})}),b?.(s)})});return y({clock:d,source:{step:u},fn:({step:t})=>({formId:m,title:l,step:t}),target:f(({formId:t,title:s,step:c})=>{a.eventBus({type:"form_submit",form:{id:t,title:s},experience:i,step:c??void 0})})}),y({clock:d,source:{fields:a.fields.listStore,stepFields:x.fields,step:u},fn:({stepFields:t},s)=>{s.preventDefault();const c=new FormData(s.currentTarget),A=Array.from(c.entries()),p={data:{},push(r){const o=r.questionId,e=this.data[o];e?Array.isArray(e)&&Array.isArray(r.value)?Array.isArray(e)&&Array.isArray(r.value)&&(typeof e[0]=="string"?this.data[o]=[...e,...r.value].map(String):typeof e[0]=="number"?this.data[o]=[...e,...r.value].map(Number):typeof e[0]=="boolean"?this.data[o]=[...e,...r.value].map(n=>!!n):this.data[o]=r.value):this.data[o]=r.value:this.data[o]=r.value}};return t.forEach(r=>{const o=A.filter(([e])=>e===r.id);o.length!==0&&o.forEach(([,e])=>{const n=r.id;if(e===""){p.push({questionId:n,value:null});return}switch(r.type){case"text":p.push({questionId:n,value:r.multiple?[String(e)]:String(e)});break;case"number":p.push({questionId:n,value:r.multiple?[Number(e)]:Number(e)});break;case"boolean":p.push({questionId:n,value:r.multiple?[e==="true"]:e==="true"});break}})}),p.data},target:h}),k({source:h.doneData,match:{hasErrors:({errors:t})=>t.length>0},cases:{hasErrors:S,__:E}}),{form:{onsubmit:d}}}export{z as getForm};