| 1 |
import { create } from 'zustand'; |
| 2 |
|
| 3 |
const seed = (steps) => |
| 4 |
Object.fromEntries( |
| 5 |
steps |
| 6 |
.flatMap(({ inputSchema }) => Object.keys(inputSchema.properties ?? {})) |
| 7 |
.map((name) => [name, '']), |
| 8 |
); |
| 9 |
|
| 10 |
// Persisting these would rehydrate a canvas the page can no longer show. |
| 11 |
export const useCanvasStore = create((set) => ({ |
| 12 |
steps: [], |
| 13 |
activeStep: 0, |
| 14 |
// A step opens for good, so this is a high-water mark rather than a position. |
| 15 |
reached: 0, |
| 16 |
values: {}, |
| 17 |
startSession: (steps) => |
| 18 |
set({ steps, activeStep: 0, reached: 0, values: seed(steps) }), |
| 19 |
endSession: () => set({ steps: [], activeStep: 0, reached: 0, values: {} }), |
| 20 |
setValue: (name, value) => |
| 21 |
set(({ values }) => ({ values: { ...values, [name]: value } })), |
| 22 |
writeValues: (written) => |
| 23 |
set(({ values }) => ({ values: { ...values, ...written } })), |
| 24 |
goToStep: (index) => |
| 25 |
set(({ steps, reached }) => { |
| 26 |
const activeStep = Math.min(Math.max(index, 0), steps.length - 1); |
| 27 |
return { activeStep, reached: Math.max(reached, activeStep) }; |
| 28 |
}), |
| 29 |
})); |
| 30 |
|
| 31 |
// Sending every step lets the agent write where the user cannot see. |
| 32 |
export const activeCanvasStep = () => { |
| 33 |
const { steps, activeStep, values } = useCanvasStore.getState(); |
| 34 |
const inputSchema = steps[activeStep]?.inputSchema ?? null; |
| 35 |
const names = Object.keys(inputSchema?.properties ?? {}); |
| 36 |
return { |
| 37 |
inputSchema, |
| 38 |
values: Object.fromEntries(names.map((name) => [name, values[name] ?? ''])), |
| 39 |
}; |
| 40 |
}; |
| 41 |
|