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

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.
@@ -0,0 +1,13 @@
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 {};
@@ -0,0 +1 @@
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};
@@ -0,0 +1,17 @@
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
+ };
@@ -0,0 +1 @@
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};
@@ -0,0 +1,41 @@
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;
@@ -0,0 +1 @@
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};
@@ -0,0 +1 @@
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};
@@ -0,0 +1,41 @@
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;
@@ -0,0 +1 @@
1
+ export * from './create-form.js';
@@ -0,0 +1 @@
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};
@@ -0,0 +1,53 @@
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;
@@ -0,0 +1 @@
1
+ export * from './create-submit-pipeline.js';
@@ -0,0 +1,16 @@
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 {};
@@ -0,0 +1 @@
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};
@@ -1,16 +1,2 @@
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
+ export type { FormField } from './create-form.svelte';
2
+ export { getForm } from './get-form';
@@ -1 +1 @@
1
- import{createEvent as _,createEffect as m,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:f,title:l,onError:b,onSuccess:g}){const a=D(),x=B(),i=F(),{currentStepStore:u}=i,d=_(),h=m(r=>a.responses.commit(r)),E=v({source:{step:u},effect:m(({step:r})=>{a.eventBus({type:"form_submit_success",form:{id:f,title:l},experience:i,step:r??void 0}),g?.()})}),S=v({source:{step:u},mapParams:(r,o)=>({step:o.step,errors:r.errors}),effect:m(({step:r,errors:o})=>{a.eventBus({type:"form_submit_error",form:{id:f,title:l},exception:{reason:o},experience:i,step:r??void 0}),o.forEach(c=>{a.eventBus({type:"field_validation_error",exception:{reason:[c]},experience:i,step:r??void 0})}),b?.(o)})});return y({clock:d,source:{step:u},fn:({step:r})=>({formId:f,title:l,step:r}),target:m(({formId:r,title:o,step:c})=>{a.eventBus({type:"form_submit",form:{id:r,title:o},experience:i,step:c??void 0})})}),y({clock:d,source:{fields:a.fields.listStore,stepFields:x.fields,step:u},fn:({stepFields:r},o)=>{o.preventDefault();const c=new FormData(o.currentTarget),A=Array.from(c.entries()),p={data:{},push(t){const s=t.questionId,e=this.data[s];e?Array.isArray(e)&&Array.isArray(t.value)?Array.isArray(e)&&Array.isArray(t.value)&&(typeof e[0]=="string"?this.data[s]=[...e,...t.value].map(String):typeof e[0]=="number"?this.data[s]=[...e,...t.value].map(Number):typeof e[0]=="boolean"?this.data[s]=[...e,...t.value].map(n=>!!n):this.data[s]=t.value):this.data[s]=t.value:this.data[s]=t.value}};return r.forEach(t=>{let s=A.filter(([e])=>e===t.id);s.length===0&&(s=[[t.id,""]]),s.forEach(([,e])=>{const n=t.id;if(e===""){p.push({questionId:n,value:null});return}switch(t.type){case"text":p.push({questionId:n,value:t.multiple?[String(e)]:String(e)});break;case"number":p.push({questionId:n,value:t.multiple?[Number(e)]:Number(e)});break;case"boolean":p.push({questionId:n,value:t.multiple?[e==="true"]:e==="true"});break}})}),p.data},target:h}),k({source:h.doneData,match:{hasErrors:({errors:r})=>r.length>0},cases:{hasErrors:S,__:E}}),{form:{onsubmit:d}}}export{z as getForm};
1
+ import{getForm as e}from"./get-form.js";export{e as getForm};
@@ -4,4 +4,9 @@ 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
+ */
7
12
  export declare function getField(id: string): GetFieldResponse;
@@ -1,13 +1,13 @@
1
1
  import { Store } from 'effector';
2
- import { ExperienceStep, Field, Response } from '@picked/client';
3
- type FieldWithValue = Field & {
4
- value: Response | undefined;
5
- };
6
- export interface StepContext {
2
+ import { ExperienceStep } from '@picked/client';
3
+ import { FormInstance, FormField } from '../form/create-form.svelte';
4
+ export interface StepContext extends FormInstance {
7
5
  step: Store<ExperienceStep>;
8
- fields: Store<FieldWithValue[]>;
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 */
9
10
  isActiveStep: Store<boolean>;
10
11
  }
11
- export declare function getStep(): StepContext;
12
12
  export declare function setStepContext(stepId: string): StepContext;
13
- export {};
13
+ export declare function getStep(): StepContext;
@@ -1 +1 @@
1
- import{getContext as v,setContext as x}from"svelte";import{createStore as E,combine as a,attach as h,createEffect as w,sample as c}from"effector";import{getStepFields as A}from"@picked/client";import{STEP_CONTEXT_KEY as l}from"../context.js";import{getStepRouter as C}from"../router/context.js";import{getExperience as F,getPicked as T}from"./client.js";function K(){return v(l)}function N(i){const u=F(),o=T(),{activeStep:S}=C(),s=S.map(e=>e?.id===i),p=u.treeStore.map(e=>{const t=e.steps.find(r=>r.id===i);if(!t)throw new Error(`Step with id "${i}" not found in the experience tree.`);return t}),f=E([]),d=a({fields:f,responses:o.responses.listStore},({fields:e,responses:t})=>e.map(r=>{const m=t.find(g=>g.fieldId===r.id)?.value;return{...r,value:m}})),n=h({source:a({step:p,fields:o.fields.listStore}),effect:w(async({step:{fieldIds:e},fields:t})=>await A(o,t.filter(r=>e.includes(r.id))))});return c({source:{isActiveStep:s},filter:({isActiveStep:e})=>e,target:n}),c({clock:o.responses.listStore,source:{isActiveStep:s},filter:({isActiveStep:e})=>e,target:n}),c({source:n.doneData,target:f}),x(l,{step:p,fields:d,isActiveStep:s})}export{K as getStep,N as setStepContext};
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};
@@ -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?.title || ''}</td>
23
+ <td>{$currentStep?.label || ''}</td>
24
24
  <td>{totalNextStepNodes}</td>
25
25
  <td>{$stepsToOrigin[0]} - {$stepsToOrigin[1]}</td>
26
26
  <td>{$stepsToLeaf[0]} - {$stepsToLeaf[1]}</td>
@@ -9,7 +9,7 @@
9
9
  let zoom = 1
10
10
  let selectedNode = null
11
11
  let highlightedPath: string[][] = []
12
- let error = null
12
+ let error: string | null = null
13
13
  const loading = false
14
14
 
15
15
  let treeRenderingDone = false
@@ -35,10 +35,62 @@
35
35
  _referenceTo?: string
36
36
  }
37
37
 
38
+ function isRecord(val: unknown): val is Record<string, unknown> {
39
+ return val !== null && typeof val === 'object' && !Array.isArray(val)
40
+ }
41
+
42
+ function formatLogicRule(rule: unknown): string {
43
+ if (rule === null || rule === undefined) return '?'
44
+ if (typeof rule === 'string') return rule
45
+ if (typeof rule === 'number' || typeof rule === 'boolean') return String(rule)
46
+ if (Array.isArray(rule)) {
47
+ return rule.map(formatLogicRule).join(', ')
48
+ }
49
+ if (isRecord(rule)) {
50
+ const keys = Object.keys(rule)
51
+ if (keys.length === 0) return 'Condition'
52
+ const op = keys[0]
53
+ const args = rule[op]
54
+
55
+ if (op === 'var') {
56
+ return String(Array.isArray(args) ? args[0] : args)
57
+ }
58
+
59
+ const compOps: Record<string, string> = {
60
+ '==': '=',
61
+ '===': '=',
62
+ '!=': '≠',
63
+ '!==': '≠',
64
+ '>': '>',
65
+ '<': '<',
66
+ '>=': '≥',
67
+ '<=': '≤',
68
+ }
69
+ if (op in compOps && Array.isArray(args) && args.length >= 2) {
70
+ return `${formatLogicRule(args[0])} ${compOps[op]} ${formatLogicRule(args[1])}`
71
+ }
72
+ if (op === 'and' && Array.isArray(args)) {
73
+ return args.map(formatLogicRule).join(' & ')
74
+ }
75
+ if (op === 'or' && Array.isArray(args)) {
76
+ return args.map(formatLogicRule).join(' | ')
77
+ }
78
+ if ((op === '!' || op === 'not') && Array.isArray(args)) {
79
+ return `!${formatLogicRule(args[0])}`
80
+ }
81
+ if (op === 'in' && Array.isArray(args) && args.length >= 2) {
82
+ return `${formatLogicRule(args[0])} in ${formatLogicRule(args[1])}`
83
+ }
84
+ return `${op}(?)`
85
+ }
86
+ return '?'
87
+ }
88
+
38
89
  function renderGraph() {
39
90
  d3.select(svgEl).selectAll('*').remove()
40
91
 
41
92
  const stepsMap = new Map(steps.map((s) => [s.id, s]))
93
+ const conditionalsMap = new Map(conditionals.map((c) => [c.id, c]))
42
94
  const outgoingEdges = new Map<string, ExperienceEdge[]>()
43
95
  edges.forEach((e) => {
44
96
  if (!outgoingEdges.has(e.sourceNodeId)) outgoingEdges.set(e.sourceNodeId, [])
@@ -49,7 +101,12 @@
49
101
  if (node.type === 'origin') return 'Start'
50
102
  if (node.type === 'step' && node.stepId)
51
103
  return stepsMap.get(node.stepId)?.label ?? 'Unknown Step'
52
- if (node.type === 'conditional' && node.conditionalId) return `Condition`
104
+ if (node.type === 'conditional' && node.conditionalId) {
105
+ const conditional = conditionalsMap.get(node.conditionalId)
106
+ if (conditional?.label) return conditional.label
107
+ if (conditional?.condition) return formatLogicRule(conditional.condition)
108
+ return 'Condition'
109
+ }
53
110
  return 'Unknown Node'
54
111
  }
55
112
 
@@ -81,15 +138,16 @@
81
138
  }
82
139
 
83
140
  if (rootNode) {
84
- const convertGraphToTree = (
85
- node: ProcessedNode,
86
- visited = new Set<string>(),
87
- ): ProcessedNode => {
88
- if (visited.has(node.id)) {
141
+ // Use a global visited set so join nodes (multiple incoming branches converging
142
+ // to the same node) only appear once in the tree, with reference nodes on
143
+ // subsequent visits to indicate the convergence point.
144
+ const globalVisited = new Set<string>()
145
+ const convertGraphToTree = (node: ProcessedNode): ProcessedNode => {
146
+ if (globalVisited.has(node.id)) {
89
147
  return {
90
148
  ...node,
91
149
  id: `${node.id}_ref`,
92
- name: `${node.name} (ref)`,
150
+ name: `↩ ${node.name}`,
93
151
  type: `${node.type}_ref`,
94
152
  children: [],
95
153
  _isReference: true,
@@ -97,9 +155,8 @@
97
155
  }
98
156
  }
99
157
 
100
- const newVisited = new Set(visited)
101
- newVisited.add(node.id)
102
- return { ...node, children: node.children.map((c) => convertGraphToTree(c, newVisited)) }
158
+ globalVisited.add(node.id)
159
+ return { ...node, children: node.children.map((c) => convertGraphToTree(c)) }
103
160
  }
104
161
 
105
162
  const treeData = convertGraphToTree(rootNode)
@@ -128,31 +185,75 @@
128
185
 
129
186
  const g = svg.append('g').attr('transform', `translate(${margin.left},${margin.top})`)
130
187
 
188
+ const linkGenerator = d3
189
+ .linkHorizontal<d3.HierarchyPointLink<ProcessedNode>, ProcessedNode>()
190
+ .x((d) => d.y)
191
+ .y((d) => d.x)
192
+
131
193
  g.selectAll('.link')
132
194
  .data(treeRoot.links())
133
195
  .enter()
134
196
  .append('path')
135
197
  .attr('class', 'link')
136
198
  .attr('fill', 'none')
137
- .attr('stroke', '#94a3b8')
199
+ .attr('stroke', (d: any) => {
200
+ if (d.source.data.type !== 'conditional') return '#94a3b8'
201
+ const targetId = d.target.data._isReference
202
+ ? d.target.data._referenceTo
203
+ : d.target.data.id
204
+ const edge = d.source.data._originalEdges.find(
205
+ (e: ExperienceEdge) => e.destinationNodeId === targetId,
206
+ )
207
+ if (edge?.sourceNodeHandle === 'true') return '#10b981'
208
+ if (edge?.sourceNodeHandle === 'false') return '#ef4444'
209
+ return '#94a3b8'
210
+ })
138
211
  .attr('stroke-width', 2)
139
- .attr(
140
- 'd',
141
- d3
142
- .linkHorizontal<d3.HierarchyPointLink<ProcessedNode>, ProcessedNode>()
143
- .x((d) => d.y)
144
- .y((d) => d.x),
145
- )
212
+ .attr('d', linkGenerator)
213
+
214
+ // Label true/false branches from conditional nodes
215
+ g.selectAll('.edge-label')
216
+ .data(treeRoot.links().filter((d: any) => d.source.data.type === 'conditional'))
217
+ .enter()
218
+ .append('text')
219
+ .attr('class', 'edge-label')
220
+ .attr('text-anchor', 'middle')
221
+ .attr('font-size', '10px')
222
+ .attr('font-weight', 'bold')
223
+ .attr('x', (d: any) => (d.source.y + d.target.y) / 2)
224
+ .attr('y', (d: any) => (d.source.x + d.target.x) / 2 - 6)
225
+ .attr('fill', (d: any) => {
226
+ const targetId = d.target.data._isReference
227
+ ? d.target.data._referenceTo
228
+ : d.target.data.id
229
+ const edge = d.source.data._originalEdges.find(
230
+ (e: ExperienceEdge) => e.destinationNodeId === targetId,
231
+ )
232
+ if (edge?.sourceNodeHandle === 'true') return '#10b981'
233
+ if (edge?.sourceNodeHandle === 'false') return '#ef4444'
234
+ return '#64748b'
235
+ })
236
+ .text((d: any) => {
237
+ const targetId = d.target.data._isReference
238
+ ? d.target.data._referenceTo
239
+ : d.target.data.id
240
+ const edge = d.source.data._originalEdges.find(
241
+ (e: ExperienceEdge) => e.destinationNodeId === targetId,
242
+ )
243
+ if (edge?.sourceNodeHandle === 'true') return 'Yes'
244
+ if (edge?.sourceNodeHandle === 'false') return 'No'
245
+ return ''
246
+ })
146
247
 
147
- const nodes = g
248
+ const nodesSelection = g
148
249
  .selectAll('.node')
149
250
  .data(treeRoot.descendants())
150
251
  .enter()
151
252
  .append('g')
152
253
  .attr('class', 'node')
153
- .attr('transform', (d: any) => `translate(${d.y},${d.x})`) // d3.HierarchyPointNode uses x, y
254
+ .attr('transform', (d: any) => `translate(${d.y},${d.x})`)
154
255
 
155
- nodes
256
+ nodesSelection
156
257
  .append('circle')
157
258
  .attr('r', (d: any) => (d.data.type === 'origin' ? 15 : 10))
158
259
  .attr('fill', (d: any) => {
@@ -164,14 +265,14 @@
164
265
  .attr('stroke', '#fff')
165
266
  .attr('stroke-width', 2)
166
267
 
167
- nodes
268
+ nodesSelection
168
269
  .append('text')
169
270
  .attr('dy', (d: any) => (d.children ? -15 : 25))
170
271
  .attr('text-anchor', 'middle')
171
272
  .attr('font-size', '12px')
172
273
  .attr('fill', '#1e293b')
173
274
  .text((d: any) =>
174
- d.data.name.length > 25 ? `${d.data.name.slice(0, 22)}...` : d.data.name,
275
+ d.data.name.length > 30 ? `${d.data.name.slice(0, 27)}...` : d.data.name,
175
276
  )
176
277
 
177
278
  svg.on('dblclick.zoom', null) // Remove default double click zoom
@@ -1,5 +1,5 @@
1
1
  <script lang="ts">
2
- import type { ResponseListItem, PrimitiveFieldValue, Field } from '@picked/client'
2
+ import type { ResponseListItem, PrimitiveFieldValue, Field, FieldValue } from '@picked/client'
3
3
  import { getPicked } from '../../../../hooks'
4
4
  import { Button, Text, CodeBlock, Banner, Stack } from '../../ui'
5
5
 
@@ -11,9 +11,10 @@
11
11
  let isEditing = false
12
12
  let editValue = ''
13
13
  let editError = ''
14
- let selectedOptions: Set<PrimitiveFieldValue> = new Set()
14
+ let selectedOptions: Set<FieldValue> = new Set()
15
15
 
16
- $: hasOptions = field?.options && field.options.length > 0
16
+ $: hasOptions = Array.isArray(field?.options) && field.options.length > 0
17
+ $: staticOptions = Array.isArray(field?.options) ? field.options : null
17
18
  $: currentValue = response?.value ?? null
18
19
 
19
20
  function formatValue(value: unknown): string {
@@ -52,7 +53,7 @@
52
53
  selectedOptions = new Set()
53
54
  }
54
55
 
55
- function toggleOption(optionValue: PrimitiveFieldValue) {
56
+ function toggleOption(optionValue: FieldValue) {
56
57
  if (field?.multiple) {
57
58
  if (selectedOptions.has(optionValue)) {
58
59
  selectedOptions.delete(optionValue)
@@ -65,7 +66,7 @@
65
66
  }
66
67
  }
67
68
 
68
- function parseValue(input: string): unknown {
69
+ function parseValue(input: string): FieldValue {
69
70
  input = input.trim()
70
71
 
71
72
  if (input === '' || input === '-') {
@@ -99,14 +100,14 @@
99
100
 
100
101
  async function saveEdit() {
101
102
  try {
102
- let newValue: unknown
103
+ let newValue: FieldValue
103
104
 
104
105
  if (hasOptions) {
105
106
  const values = Array.from(selectedOptions)
106
107
  if (field?.multiple) {
107
108
  newValue = values
108
109
  } else {
109
- newValue = values[0] ?? null
110
+ newValue = values.at(0) ?? null
110
111
  }
111
112
  } else {
112
113
  newValue = parseValue(editValue)
@@ -142,9 +143,9 @@
142
143
  <td>
143
144
  {#if isEditing}
144
145
  <Stack direction="vertical" gap="small">
145
- {#if hasOptions && field?.options}
146
+ {#if hasOptions && staticOptions}
146
147
  <Stack direction="vertical" gap="small">
147
- {#each field.options as option (option.id)}
148
+ {#each staticOptions as option (option.id)}
148
149
  <label class="option-label">
149
150
  {#if field.multiple}
150
151
  <input
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@picked/svelte",
3
- "version": "0.0.1-dev.1772168509010",
3
+ "version": "0.0.1-dev.1772412203098",
4
4
  "dependencies": {
5
5
  "d3": "^7.9.0"
6
6
  },
@@ -86,7 +86,7 @@
86
86
  },
87
87
  "module": "./dist/index.js",
88
88
  "peerDependencies": {
89
- "@picked/client": "0.0.1-dev.1772168509010",
89
+ "@picked/client": "0.0.1-dev.1772412203098",
90
90
  "effector": "^23.3.0",
91
91
  "svelte": "^5.34.3"
92
92
  },