getsyntux 0.6.0 → 0.7.2
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.
- package/README.md +22 -20
- package/dist/client.d.mts +14 -5
- package/dist/client.mjs +2 -2
- package/dist/client.mjs.map +1 -1
- package/dist/index.d.mts +9 -14
- package/dist/index.mjs +7 -11
- package/dist/index.mjs.map +1 -1
- package/dist/metafile-esm.json +1 -1
- package/dist/templates/GeneratedUI.tsx +45 -27
- package/dist/templates/RerenderHandler.tsx +8 -0
- package/dist/templates/spec.md +7 -26
- package/dist/templates/spec.ts +7 -26
- package/dist/{types-CtXPasY-.d.mts → types-C9N85B_g.d.mts} +4 -5
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -10,7 +10,13 @@ You give it a <code>value</code> and it designs the UI to display it.
|
|
|
10
10
|
|
|
11
11
|
---
|
|
12
12
|
|
|
13
|
-
https://github.com/user-attachments/assets/
|
|
13
|
+
https://github.com/user-attachments/assets/c85de55d-21f3-43ff-8bd3-d6ede2171447
|
|
14
|
+
|
|
15
|
+
*syntux* is designed to **display data**. Do not let this fact intimidate you - that is simply a testament to how token-efficient it is.
|
|
16
|
+
|
|
17
|
+
For instance, if you provide an array `value` with 10,000 items, it will cost you the same as one with 10 items. **That is how efficient syntux is**.
|
|
18
|
+
|
|
19
|
+
### Features
|
|
14
20
|
|
|
15
21
|
- ⚡ **Streamable** - display UI as you generate.
|
|
16
22
|
- 🎨 **Custom Components** - use your own React components.
|
|
@@ -18,7 +24,7 @@ https://github.com/user-attachments/assets/694d4646-c36d-4c19-a111-86e546484101
|
|
|
18
24
|
|
|
19
25
|
**How does it work?** *syntux* generates a JSON-DSL to represent the UI, known as the React Interface Schema. The specifics are in the FAQ [below](#faq).
|
|
20
26
|
|
|
21
|
-
<h3 align="center" margin="0"><a href="https://
|
|
27
|
+
<h3 align="center" margin="0"><a href="https://docs.getsyntux.com/">➡️ view documentation</a></h3>
|
|
22
28
|
|
|
23
29
|
---
|
|
24
30
|
|
|
@@ -45,7 +51,7 @@ const valueToDisplay = {
|
|
|
45
51
|
*syntux* takes the `value` into consideration and designs a UI to best display it. `value` can be anything; an object, array or primitive.
|
|
46
52
|
|
|
47
53
|
> [!TIP]
|
|
48
|
-
> If you are passing in a **large array** as a value, or an object with untrusted input, use the `skeletonize` property. See [the explanation](https://
|
|
54
|
+
> If you are passing in a **large array** as a value, or an object with untrusted input, use the `skeletonize` property. See [the explanation](https://docs.getsyntux.com/advanced#skeletonize-property).
|
|
49
55
|
|
|
50
56
|
### Installation
|
|
51
57
|
|
|
@@ -109,7 +115,7 @@ import { CustomOne, CustomTwo } from '@/my_components'
|
|
|
109
115
|
export default function Home(){
|
|
110
116
|
const valueToDisplay = { ... };
|
|
111
117
|
|
|
112
|
-
<GeneratedUI components={[
|
|
118
|
+
return <GeneratedUI components={[
|
|
113
119
|
{ name: 'Button', props: "{ color: string, text: string }", component: CustomOne },
|
|
114
120
|
{ name: 'Input', props: "{ initial: string, disabled: boolean }", component: CustomTwo, context: "Creates an input field with an (initial) value. Can be disabled." }
|
|
115
121
|
]} />
|
|
@@ -118,33 +124,29 @@ export default function Home(){
|
|
|
118
124
|
|
|
119
125
|
<sup>
|
|
120
126
|
|
|
121
|
-
**Note**: the `components` array above can be generated automatically with `npx getsyntux generate-defs <component.tsx>`. See the [documentation](https://
|
|
127
|
+
**Note**: the `components` array above can be generated automatically with `npx getsyntux generate-defs <component.tsx>`. See the [documentation](https://docs.getsyntux.com/api#generate-defs).
|
|
122
128
|
|
|
123
129
|
</sup>
|
|
124
130
|
|
|
125
131
|
Make sure components are marked with `"use client"`.
|
|
126
132
|
|
|
127
|
-
####
|
|
133
|
+
#### Update value (interactivity)
|
|
128
134
|
|
|
129
|
-
|
|
135
|
+
Use the `useSyntux` hook to retrieve and update the `value` inside a custom component:
|
|
130
136
|
|
|
131
137
|
```jsx
|
|
132
|
-
|
|
138
|
+
"use client";
|
|
133
139
|
|
|
134
|
-
export default function
|
|
135
|
-
|
|
140
|
+
export default function CustomComponent(){
|
|
141
|
+
const { value, setValue } = useSyntux();
|
|
136
142
|
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
143
|
+
return <button onClick={() => {
|
|
144
|
+
const newArr = [...value];
|
|
145
|
+
newArr.push({ ... });
|
|
146
|
+
setValue(newArr);
|
|
147
|
+
}}>Add value</button>
|
|
141
148
|
}
|
|
142
149
|
```
|
|
143
|
-
<sup>
|
|
144
|
-
|
|
145
|
-
**Note**: The name of the action should specify its purpose (it is seen by the LLM). Use `defineTool` to add further context to actions. See the [documentation](https://github.com/puffinsoft/syntux/wiki).
|
|
146
|
-
|
|
147
|
-
</sup>
|
|
148
150
|
|
|
149
151
|
---
|
|
150
152
|
|
|
@@ -153,7 +155,7 @@ export default function Home(){
|
|
|
153
155
|
<details>
|
|
154
156
|
<summary>How expensive is generation?</summary>
|
|
155
157
|
|
|
156
|
-
*syntux* is highly optimized to save tokens. See [here](https://
|
|
158
|
+
*syntux* is highly optimized to save tokens. See [here](https://docs.getsyntux.com/advanced#cost-estimation) for a cost estimation table and an explanation.
|
|
157
159
|
</details>
|
|
158
160
|
|
|
159
161
|
<details>
|
package/dist/client.d.mts
CHANGED
|
@@ -1,17 +1,19 @@
|
|
|
1
1
|
import * as react_jsx_runtime from 'react/jsx-runtime';
|
|
2
2
|
import { StreamableValue } from '@ai-sdk/rsc';
|
|
3
|
+
import * as react from 'react';
|
|
3
4
|
import react__default, { JSX, ComponentType } from 'react';
|
|
4
|
-
import {
|
|
5
|
+
import { A as AnimateOptions, a as ComponentMap, C as ChildrenMap } from './types-C9N85B_g.mjs';
|
|
5
6
|
|
|
6
7
|
/**
|
|
7
8
|
* Client wrapper for Renderer that handles streaming and parsing with server.
|
|
8
9
|
*/
|
|
9
|
-
declare function GeneratedClient({ value, allowedComponents, inputStream, placeholder,
|
|
10
|
+
declare function GeneratedClient({ value, allowedComponents, inputStream, placeholder, errorFallback, animate }: {
|
|
10
11
|
value: any;
|
|
11
12
|
allowedComponents: Record<string, react__default.ComponentType<any> | string>;
|
|
12
13
|
inputStream: StreamableValue<string>;
|
|
13
14
|
placeholder?: JSX.Element;
|
|
14
|
-
|
|
15
|
+
errorFallback?: JSX.Element;
|
|
16
|
+
animate?: AnimateOptions;
|
|
15
17
|
}): react_jsx_runtime.JSX.Element;
|
|
16
18
|
|
|
17
19
|
interface RendererProps {
|
|
@@ -21,11 +23,18 @@ interface RendererProps {
|
|
|
21
23
|
allowedComponents: Record<string, ComponentType<any> | string>;
|
|
22
24
|
global: any;
|
|
23
25
|
local: any;
|
|
24
|
-
|
|
26
|
+
animate?: AnimateOptions;
|
|
25
27
|
}
|
|
26
28
|
/**
|
|
27
29
|
* Renders a UISchema recursively, in accordance to the spec.
|
|
28
30
|
*/
|
|
29
31
|
declare function Renderer(props: RendererProps): react_jsx_runtime.JSX.Element;
|
|
30
32
|
|
|
31
|
-
|
|
33
|
+
type SyntuxContextType = {
|
|
34
|
+
value: any;
|
|
35
|
+
setValue: (arg0: any) => void;
|
|
36
|
+
};
|
|
37
|
+
declare const SyntuxContext: react.Context<SyntuxContextType>;
|
|
38
|
+
declare function useSyntux(): SyntuxContextType;
|
|
39
|
+
|
|
40
|
+
export { GeneratedClient, Renderer, type RendererProps, SyntuxContext, type SyntuxContextType, useSyntux };
|
package/dist/client.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use client";import{readStreamableValue as
|
|
2
|
-
`);return e.length>1?(e.slice(0,e.length-1).forEach(
|
|
1
|
+
"use client";import{readStreamableValue as H}from"@ai-sdk/rsc";import{useEffect as W,useMemo as z,useReducer as B,useRef as K,useState as J}from"react";var x=class{buffer="";schema={childrenMap:{},componentMap:{},root:null};addDelta(r){this.buffer+=r;let e=this.buffer.split(`
|
|
2
|
+
`);return e.length>1?(e.slice(0,e.length-1).forEach(t=>this.handleLine(t)),this.buffer=e[e.length-1],!0):!1}handleLine(r){try{let e=JSON.parse(r),{childrenMap:t,componentMap:s}=this.schema;s[e.id]=e,e.parentId===null?this.schema.root=e:(t[e.parentId]||(t[e.parentId]=[]),t[e.parentId].push(e.id))}catch{}}finish(){this.handleLine(this.buffer),this.buffer=""}};import{Fragment as k,useEffect as D,useState as G}from"react";import{Fragment as F,jsx as f}from"react/jsx-runtime";import{createElement as Y}from"react";var T=(n,r)=>r==="$"?n:r.split(".").reduce((e,t)=>e==null?void 0:e[t],n),v=(n,r,e)=>e.startsWith("$item.")?(e=e.slice(6),T(r,e)):e==="$item"?r:T(n,e),$=new Set(["dangerouslySetInnerHTML"]),N=(n,r,e)=>{if(!e)return e;if("$bind"in e){let t=v(n,r,e.$bind);return Object.keys(t).forEach(s=>{$.has(s)&&delete t[s]}),t}return Object.keys(e).forEach(t=>{if($.has(t)){delete e[t];return}let s=e[t];typeof s=="object"&&(e[t]=N(n,r,s))}),e},O=(n,r,e)=>typeof e=="object"?v(n,r,e.$bind):e;function C(n){var V,A,I;let[r,e]=G(!1);D(()=>{let c=requestAnimationFrame(()=>e(!0));return()=>cancelAnimationFrame(c)},[]);let{id:t,componentMap:s,childrenMap:M,global:l,local:m,allowedComponents:y,animate:o}=n,a=s[t];if(a.type==="TEXT")return f(F,{children:O(l,m,a.content)});let h=(V=a.props)==null?void 0:V.source;if(a.type==="__ForEach__"&&h){let c=v(l,m,h);if(!Array.isArray(c))return null;let p=M[a.id];return f(F,{children:p==null?void 0:p.map((L,U)=>f(k,{children:c.map((X,_)=>Y(C,{...n,id:L,local:X,key:_}))},U))})}let u=y[a.type]||a.type,i={...N(l,m,a.props)};i.style={...i.style||{}};let S=((A=i.style)==null?void 0:A.opacity)??1;i.style.opacity=r?S:0,i.style.transform=r?"translateY(0)":`translateY(${(o==null?void 0:o.offset)??10}px)`,i.style.transition=`opacity ${(o==null?void 0:o.duration)??200}ms ease-out, transform ${(o==null?void 0:o.duration)??200}ms ease-out`,i.style.willChange="opacity, transform";let b=O(l,m,a.content),g=((I=M[a.id])==null?void 0:I.map((c,p)=>f(C,{...n,id:c},p)))||[],w=[b,...g].filter(c=>c!=null);return w.length>0?f(u,{...i,children:w}):f(u,{...i})}import{createContext as j,useContext as q}from"react";var P=j(null);function se(){let n=q(P);if(!n)throw new Error("useSyntux must be used inside a GeneratedUI.");return n}import{Fragment as R,jsx as d}from"react/jsx-runtime";function ye({value:n,allowedComponents:r,inputStream:e,placeholder:t,errorFallback:s,animate:M}){var S;let[l,m]=J(n),[,y]=B(b=>b+1,0),o=K(null),[a,h]=J(!1);W(()=>{o.current=new x,(async()=>{for await(let g of H(e))o.current&&g!==void 0&&o.current.addDelta(g)&&y()})().then(()=>{o.current.finish(),y()}).catch(()=>{h(!0)})},[e]);let u=(S=o==null?void 0:o.current)==null?void 0:S.schema,E=z(()=>({value:l,setValue:m}),[l]),i=()=>a&&s?d(R,{children:s}):u!=null&&u.root?d(C,{id:u.root.id,componentMap:u.componentMap,childrenMap:u.childrenMap,allowedComponents:r,global:l,local:l}):d(R,{children:t});return d(R,{children:d(P.Provider,{value:E,children:i()})})}export{ye as GeneratedClient,C as Renderer,P as SyntuxContext,se as useSyntux};
|
|
3
3
|
//# sourceMappingURL=client.mjs.map
|
package/dist/client.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/client/GeneratedClient.tsx","../src/client/Renderer.tsx","../src/ResponseParser.ts"],"sourcesContent":["\"use client\";\r\n\r\nimport { StreamableValue, readStreamableValue } from '@ai-sdk/rsc';\r\nimport React, { JSX, useEffect, useReducer, useRef, useState } from 'react';\r\nimport { Renderer } from './Renderer';\r\nimport { ResponseParser } from '../ResponseParser';\r\nimport { ContextfulAction } from 'src/types';\r\n\r\n/**\r\n * Client wrapper for Renderer that handles streaming and parsing with server.\r\n */\r\nexport function GeneratedClient({\r\n value,\r\n allowedComponents,\r\n inputStream,\r\n placeholder,\r\n actions\r\n}: {\r\n value: any,\r\n allowedComponents: Record<string, React.ComponentType<any> | string>,\r\n inputStream: StreamableValue<string>,\r\n placeholder?: JSX.Element,\r\n actions?: Record<string, ContextfulAction>\r\n}) {\r\n const [, forceUpdate] = useReducer(x => x + 1, 0);\r\n const parser = useRef<ResponseParser | null>(null);\r\n\r\n useEffect(() => {\r\n // forcibly create a new one for HMR\r\n parser.current = new ResponseParser();\r\n\r\n const parseStream = async () => {\r\n for await (const delta of readStreamableValue(inputStream)) {\r\n if (parser.current && delta !== undefined) {\r\n if (parser.current.addDelta(delta)) {\r\n forceUpdate();\r\n }\r\n }\r\n }\r\n };\r\n\r\n parseStream().then(() => {\r\n parser.current.finish();\r\n forceUpdate();\r\n });\r\n }, [inputStream]);\r\n\r\n const schema = parser?.current?.schema;\r\n\r\n return (\r\n <>\r\n {schema?.root ?\r\n <Renderer id={schema.root.id} componentMap={schema.componentMap} childrenMap={schema.childrenMap} allowedComponents={allowedComponents} global={value} local={value} actions={actions || {}} />\r\n : <>{placeholder}</>}\r\n </>\r\n )\r\n}\r\n","\"use client\";\r\n\r\nimport { ComponentType, Fragment } from 'react'\r\nimport { ChildrenMap, ComponentMap, ContextfulAction, SchemaNode } from '../types';\r\n\r\n/**\r\n * lightweight implementation of lodash.get\r\n */\r\nconst resolvePath = (obj: any, path: string) => {\r\n if (path === '$') return obj;\r\n return path.split('.').reduce((acc, curr) => acc?.[curr], obj)\r\n}\r\n\r\n/**\r\n * parses binding protocol and performs property lookup w/ scope resolution\r\n */\r\nconst get = (global: any, local: any, path: string) => {\r\n if (path.startsWith(\"$item.\")) {\r\n path = path.slice(6)\r\n return resolvePath(local, path);\r\n } else {\r\n if (path === \"$item\") return local;\r\n return resolvePath(global, path);\r\n }\r\n}\r\n\r\n\r\nconst blacklistedProps = new Set([\"dangerouslySetInnerHTML\"])\r\n/**\r\n * recursively parses props for bindings, replacing with true values\r\n */\r\nconst resolveProps = (global: any, local: any, props: any, actions: Record<string, ContextfulAction>) => {\r\n if (!props) return props;\r\n if (\"$action\" in props) {\r\n const action = actions[props.$action];\r\n if (!action) return () => { };\r\n\r\n const resolvedArgs = props.args.map((arg: any) => {\r\n if (arg && typeof arg === \"object\" && \"$bind\" in arg) {\r\n return get(global, local, arg.$bind);\r\n } else {\r\n return arg;\r\n }\r\n })\r\n\r\n return (e: any) => {\r\n action.fn(...resolvedArgs)\r\n }\r\n }\r\n\r\n if (\"$bind\" in props) { // $bind may be falsy value\r\n const resolved = get(global, local, props.$bind);\r\n Object.keys(resolved).forEach((key) => {\r\n if(blacklistedProps.has(key)){\r\n delete resolved[key];\r\n }\r\n })\r\n return resolved;\r\n }\r\n\r\n Object.keys(props).forEach((key) => {\r\n if (blacklistedProps.has(key)) {\r\n delete props[key];\r\n return;\r\n }\r\n\r\n const val = props[key];\r\n if (typeof val === \"object\") {\r\n props[key] = resolveProps(global, local, val, actions);\r\n }\r\n })\r\n return props;\r\n}\r\n\r\n/**\r\n * output node.content, with check for $bind\r\n*/\r\nconst renderContent = (global: any, local: any, content: any) => {\r\n if (typeof content === \"object\") {\r\n return get(global, local, content.$bind);\r\n } else {\r\n return content;\r\n }\r\n}\r\n\r\nexport interface RendererProps {\r\n id: string;\r\n componentMap: ComponentMap;\r\n childrenMap: ChildrenMap;\r\n allowedComponents: Record<string, ComponentType<any> | string>;\r\n global: any;\r\n local: any;\r\n actions: Record<string, ContextfulAction>;\r\n}\r\n\r\n/**\r\n * Renders a UISchema recursively, in accordance to the spec.\r\n */\r\nexport function Renderer(props: RendererProps) {\r\n const {\r\n id, componentMap, childrenMap, global, local, allowedComponents, actions\r\n } = props;\r\n const element = componentMap[id];\r\n\r\n if (element.type === \"TEXT\") return <>{renderContent(global, local, element.content)}</>\r\n\r\n const sourceArrPath = element.props?.source;\r\n if (element.type === '__ForEach__' && sourceArrPath) {\r\n const sourceArr = get(global, local, sourceArrPath)\r\n if (!Array.isArray(sourceArr)) return null;\r\n\r\n const childrenArr = childrenMap[element.id];\r\n return <>{childrenArr?.map((childId: string, index: number) => <Fragment key={index}>\r\n {sourceArr.map((item: any, index1: number) => <Renderer {...props} id={childId} local={item} key={index1} />)}\r\n </Fragment>)}</>\r\n }\r\n\r\n const Component = allowedComponents[element.type] || element.type;\r\n const componentProps = resolveProps(global, local, element.props, actions);\r\n\r\n const contentNode = renderContent(global, local, element.content);\r\n const childNodes = childrenMap[element.id]?.map((childId: string, index: number) => {\r\n return <Renderer\r\n key={index}\r\n {...props}\r\n id={childId}\r\n />\r\n }) || []\r\n\r\n const nodesToRender = [contentNode, ...childNodes].filter(node => node !== null && node !== undefined) // 0 is falsy\r\n\r\n if (nodesToRender.length > 0) {\r\n return <Component {...componentProps}>\r\n {nodesToRender}\r\n </Component>\r\n }\r\n\r\n return <Component {...componentProps} />\r\n}\r\n","import { SchemaNode, UISchema } from \"./types\";\r\n\r\n/**\r\n * Utility class for parsing UISchema from stream.\r\n */\r\nexport class ResponseParser {\r\n buffer = \"\"; // unflushed existing deltas w/o newline\r\n \r\n // schema assembled thus far\r\n schema: UISchema = {\r\n childrenMap: {},\r\n componentMap: {},\r\n root: null\r\n }\r\n\r\n /**\r\n * Update schema with latest data chunk.\r\n * \r\n * Handles multiline input gracefully; can be used to load entire schemas from cache.\r\n * \r\n * @param delta delta from stream.\r\n * @returns true if update is warranted, false otherwise.\r\n */\r\n addDelta(delta: string) {\r\n this.buffer += delta;\r\n const split = this.buffer.split(\"\\n\")\r\n if (split.length > 1) {\r\n split.slice(0, split.length - 1).forEach((line) => this.handleLine(line));\r\n this.buffer = split[split.length - 1];\r\n return true;\r\n }\r\n return false;\r\n }\r\n\r\n /**\r\n * Parses a single line (full JSON object) and updates schema.\r\n * Generally should not be used when streaming data.\r\n */\r\n handleLine(line: string) {\r\n try {\r\n const node: SchemaNode = JSON.parse(line);\r\n\r\n const { childrenMap, componentMap } = this.schema;\r\n\r\n componentMap[node.id] = node;\r\n if (node.parentId === null) {\r\n this.schema.root = node;\r\n } else {\r\n if (!childrenMap[node.parentId]) childrenMap[node.parentId] = []\r\n childrenMap[node.parentId].push(node.id)\r\n }\r\n } catch (err) { /* probably markdown or generation inconsistency */ }\r\n }\r\n\r\n /**\r\n * Clears the buffer and handles any remaining information within.\r\n */\r\n finish(){\r\n this.handleLine(this.buffer);\r\n this.buffer = \"\";\r\n }\r\n}"],"mappings":"aAEA,OAA0B,uBAAAA,MAA2B,cACrD,OAAqB,aAAAC,EAAW,cAAAC,EAAY,UAAAC,MAAwB,QCDpE,OAAwB,YAAAC,MAAgB,QAsGA,mBAAAA,EAAA,OAAAC,MAAA,oBASkB,wBAAAC,MAAA,QAzG1D,IAAMC,EAAc,CAACC,EAAUC,IACvBA,IAAS,IAAYD,EAClBC,EAAK,MAAM,GAAG,EAAE,OAAO,CAACC,EAAKC,IAASD,GAAA,YAAAA,EAAMC,GAAOH,CAAG,EAM3DI,EAAM,CAACC,EAAaC,EAAYL,IAC9BA,EAAK,WAAW,QAAQ,GACxBA,EAAOA,EAAK,MAAM,CAAC,EACZF,EAAYO,EAAOL,CAAI,GAE1BA,IAAS,QAAgBK,EACtBP,EAAYM,EAAQJ,CAAI,EAKjCM,EAAmB,IAAI,IAAI,CAAC,yBAAyB,CAAC,EAItDC,EAAe,CAACH,EAAaC,EAAYG,EAAYC,IAA8C,CACrG,GAAI,CAACD,EAAO,OAAOA,EACnB,GAAI,YAAaA,EAAO,CACpB,IAAME,EAASD,EAAQD,EAAM,OAAO,EACpC,GAAI,CAACE,EAAQ,MAAO,IAAM,CAAE,EAE5B,IAAMC,EAAeH,EAAM,KAAK,IAAKI,GAC7BA,GAAO,OAAOA,GAAQ,UAAY,UAAWA,EACtCT,EAAIC,EAAQC,EAAOO,EAAI,KAAK,EAE5BA,CAEd,EAED,OAAQC,GAAW,CACfH,EAAO,GAAG,GAAGC,CAAY,CAC7B,CACJ,CAEA,GAAI,UAAWH,EAAO,CAClB,IAAMM,EAAWX,EAAIC,EAAQC,EAAOG,EAAM,KAAK,EAC/C,cAAO,KAAKM,CAAQ,EAAE,QAASC,GAAQ,CAChCT,EAAiB,IAAIS,CAAG,GACvB,OAAOD,EAASC,CAAG,CAE3B,CA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W,KAAK,MAAM,EAC3B,KAAK,OAAS,EAClB,CACJ,EFTQ,OACE,YAAAG,EADF,OAAAC,MAAA,oBAzCD,SAASC,GAAgB,CAC9B,MAAAC,EACA,kBAAAC,EACA,YAAAC,EACA,YAAAC,EACA,QAAAC,CACF,EAMG,CAvBH,IAAAC,EAwBE,GAAM,CAAC,CAAEC,CAAW,EAAIC,EAAWC,GAAKA,EAAI,EAAG,CAAC,EAC1CC,EAASC,EAA8B,IAAI,EAEjDC,EAAU,IAAM,CAEdF,EAAO,QAAU,IAAIG,GAED,SAAY,CAC9B,cAAiBC,KAASC,EAAoBZ,CAAW,EACnDO,EAAO,SAAWI,IAAU,QAC1BJ,EAAO,QAAQ,SAASI,CAAK,GAC/BP,EAAY,CAIpB,GAEY,EAAE,KAAK,IAAM,CACvBG,EAAO,QAAQ,OAAO,EACtBH,EAAY,CACd,CAAC,CACH,EAAG,CAACJ,CAAW,CAAC,EAEhB,IAAMa,GAASV,EAAAI,GAAA,YAAAA,EAAQ,UAAR,YAAAJ,EAAiB,OAEhC,OACEP,EAAAD,EAAA,CACG,SAAAkB,GAAA,MAAAA,EAAQ,KACPjB,EAACkB,EAAA,CAAS,GAAID,EAAO,KAAK,GAAI,aAAcA,EAAO,aAAc,YAAaA,EAAO,YAAa,kBAAmBd,EAAmB,OAAQD,EAAO,MAAOA,EAAO,QAASI,GAAW,CAAC,EAAG,EAC3LN,EAAAD,EAAA,CAAG,SAAAM,EAAY,EACrB,CAEJ","names":["readStreamableValue","useEffect","useReducer","useRef","Fragment","jsx","createElement","resolvePath","obj","path","acc","curr","get","global","local","blacklistedProps","resolveProps","props","actions","action","resolvedArgs","arg","e","resolved","key","val","renderContent","content","Renderer","_a","_b","id","componentMap","childrenMap","allowedComponents","element","sourceArrPath","sourceArr","childrenArr","childId","index","item","index1","Component","componentProps","contentNode","childNodes","nodesToRender","node","ResponseParser","delta","split","line","node","childrenMap","componentMap","Fragment","jsx","GeneratedClient","value","allowedComponents","inputStream","placeholder","actions","_a","forceUpdate","useReducer","x","parser","useRef","useEffect","ResponseParser","delta","readStreamableValue","schema","Renderer"]}
|
|
1
|
+
{"version":3,"sources":["../src/client/GeneratedClient.tsx","../src/ResponseParser.ts","../src/client/Renderer.tsx","../src/client/SyntuxContext.tsx"],"sourcesContent":["\"use client\";\r\n\r\nimport { StreamableValue, readStreamableValue } from '@ai-sdk/rsc';\r\nimport React, { JSX, useEffect, useMemo, useReducer, useRef, useState } from 'react';\r\nimport { AnimateOptions } from 'src/types';\r\nimport { ResponseParser } from '../ResponseParser';\r\nimport { Renderer } from './Renderer';\r\nimport { SyntuxContext } from './SyntuxContext';\r\n\r\n/**\r\n * Client wrapper for Renderer that handles streaming and parsing with server.\r\n */\r\nexport function GeneratedClient({\r\n value,\r\n allowedComponents,\r\n inputStream,\r\n placeholder,\r\n errorFallback,\r\n animate\r\n}: {\r\n value: any,\r\n allowedComponents: Record<string, React.ComponentType<any> | string>,\r\n inputStream: StreamableValue<string>,\r\n placeholder?: JSX.Element,\r\n errorFallback?: JSX.Element,\r\n animate?: AnimateOptions\r\n}) {\r\n const [statefulValue, setStatefulValue] = useState(value); // stateful because changeable through context\r\n const [, forceUpdate] = useReducer(x => x + 1, 0);\r\n const parser = useRef<ResponseParser | null>(null);\r\n const [errored, setErrored] = useState(false)\r\n\r\n useEffect(() => {\r\n // forcibly create a new one for HMR\r\n parser.current = new ResponseParser();\r\n\r\n const parseStream = async () => {\r\n for await (const delta of readStreamableValue(inputStream)) {\r\n if (parser.current && delta !== undefined) {\r\n if (parser.current.addDelta(delta)) {\r\n forceUpdate();\r\n }\r\n }\r\n }\r\n };\r\n\r\n parseStream().then(() => {\r\n parser.current.finish();\r\n forceUpdate();\r\n }).catch(() => {\r\n setErrored(true)\r\n });\r\n }, [inputStream]);\r\n\r\n const schema = parser?.current?.schema;\r\n\r\n const providerValue = useMemo(() => ({ value: statefulValue, setValue: setStatefulValue }), [statefulValue]);\r\n\r\n const renderContent = () => {\r\n if(errored && errorFallback) return <>{errorFallback}</>\r\n\r\n if(schema?.root){\r\n return <Renderer id={schema.root.id} componentMap={schema.componentMap} childrenMap={schema.childrenMap} allowedComponents={allowedComponents} global={statefulValue} local={statefulValue} /> \r\n } else {\r\n return <>{placeholder}</>\r\n }\r\n }\r\n\r\n return (\r\n <>\r\n <SyntuxContext.Provider value={providerValue}>\r\n {renderContent()}\r\n </SyntuxContext.Provider >\r\n </>\r\n )\r\n}\r\n","import { SchemaNode, UISchema } from \"./types\";\r\n\r\n/**\r\n * Utility class for parsing UISchema from stream.\r\n */\r\nexport class ResponseParser {\r\n buffer = \"\"; // unflushed existing deltas w/o newline\r\n \r\n // schema assembled thus far\r\n schema: UISchema = {\r\n childrenMap: {},\r\n componentMap: {},\r\n root: null\r\n }\r\n\r\n /**\r\n * Update schema with latest data chunk.\r\n * \r\n * Handles multiline input gracefully; can be used to load entire schemas from cache.\r\n * \r\n * @param delta delta from stream.\r\n * @returns true if update is warranted, false otherwise.\r\n */\r\n addDelta(delta: string) {\r\n this.buffer += delta;\r\n const split = this.buffer.split(\"\\n\")\r\n if (split.length > 1) {\r\n split.slice(0, split.length - 1).forEach((line) => this.handleLine(line));\r\n this.buffer = split[split.length - 1];\r\n return true;\r\n }\r\n return false;\r\n }\r\n\r\n /**\r\n * Parses a single line (full JSON object) and updates schema.\r\n * Generally should not be used when streaming data.\r\n */\r\n handleLine(line: string) {\r\n try {\r\n const node: SchemaNode = JSON.parse(line);\r\n\r\n const { childrenMap, componentMap } = this.schema;\r\n\r\n componentMap[node.id] = node;\r\n if (node.parentId === null) {\r\n this.schema.root = node;\r\n } else {\r\n if (!childrenMap[node.parentId]) childrenMap[node.parentId] = []\r\n childrenMap[node.parentId].push(node.id)\r\n }\r\n } catch (err) { /* probably markdown or generation inconsistency */ }\r\n }\r\n\r\n /**\r\n * Clears the buffer and handles any remaining information within.\r\n */\r\n finish(){\r\n this.handleLine(this.buffer);\r\n this.buffer = \"\";\r\n }\r\n}","\"use client\";\r\n\r\nimport { ComponentType, Fragment, useEffect, useState } from 'react';\r\nimport { AnimateOptions, ChildrenMap, ComponentMap } from '../types';\r\n\r\n/**\r\n * lightweight implementation of lodash.get\r\n */\r\nconst resolvePath = (obj: any, path: string) => {\r\n if (path === '$') return obj;\r\n return path.split('.').reduce((acc, curr) => acc?.[curr], obj)\r\n}\r\n\r\n/**\r\n * parses binding protocol and performs property lookup w/ scope resolution\r\n */\r\nconst get = (global: any, local: any, path: string) => {\r\n if (path.startsWith(\"$item.\")) {\r\n path = path.slice(6)\r\n return resolvePath(local, path);\r\n } else {\r\n if (path === \"$item\") return local;\r\n return resolvePath(global, path);\r\n }\r\n}\r\n\r\n\r\nconst blacklistedProps = new Set([\"dangerouslySetInnerHTML\"])\r\n/**\r\n * recursively parses props for bindings, replacing with true values\r\n */\r\nconst resolveProps = (global: any, local: any, props: any) => {\r\n if (!props) return props;\r\n\r\n if (\"$bind\" in props) { // $bind may be falsy value\r\n const resolved = get(global, local, props.$bind);\r\n Object.keys(resolved).forEach((key) => {\r\n if (blacklistedProps.has(key)) {\r\n delete resolved[key];\r\n }\r\n })\r\n return resolved;\r\n }\r\n\r\n Object.keys(props).forEach((key) => {\r\n if (blacklistedProps.has(key)) {\r\n delete props[key];\r\n return;\r\n }\r\n\r\n const val = props[key];\r\n if (typeof val === \"object\") {\r\n props[key] = resolveProps(global, local, val);\r\n }\r\n })\r\n return props;\r\n}\r\n\r\n/**\r\n * output node.content, with check for $bind\r\n*/\r\nconst renderContent = (global: any, local: any, content: any) => {\r\n if (typeof content === \"object\") {\r\n return get(global, local, content.$bind);\r\n } else {\r\n return content;\r\n }\r\n}\r\n\r\nexport interface RendererProps {\r\n id: string;\r\n componentMap: ComponentMap;\r\n childrenMap: ChildrenMap;\r\n allowedComponents: Record<string, ComponentType<any> | string>;\r\n global: any;\r\n local: any;\r\n animate?: AnimateOptions;\r\n}\r\n\r\n/**\r\n * Renders a UISchema recursively, in accordance to the spec.\r\n */\r\nexport function Renderer(props: RendererProps) {\r\n const [isVisible, setIsVisible] = useState(false);\r\n\r\n useEffect(() => {\r\n const frame = requestAnimationFrame(() => setIsVisible(true));\r\n return () => cancelAnimationFrame(frame)\r\n }, [])\r\n\r\n const {\r\n id, componentMap, childrenMap, global, local, allowedComponents, animate\r\n } = props;\r\n const element = componentMap[id];\r\n\r\n if (element.type === \"TEXT\") return <>{renderContent(global, local, element.content)}</>\r\n\r\n const sourceArrPath = element.props?.source;\r\n if (element.type === '__ForEach__' && sourceArrPath) {\r\n const sourceArr = get(global, local, sourceArrPath)\r\n if (!Array.isArray(sourceArr)) return null;\r\n\r\n const childrenArr = childrenMap[element.id];\r\n return <>{childrenArr?.map((childId: string, index: number) => <Fragment key={index}>\r\n {sourceArr.map((item: any, index1: number) => <Renderer {...props} id={childId} local={item} key={index1} />)}\r\n </Fragment>)}</>\r\n }\r\n\r\n const Component = allowedComponents[element.type] || element.type;\r\n const componentProps = resolveProps(global, local, element.props);\r\n\r\n const animatedProps = {...componentProps}\r\n animatedProps.style = {...(animatedProps.style) || {}}\r\n\r\n const initialOpacity = animatedProps.style?.opacity ?? 1;\r\n animatedProps.style.opacity = isVisible ? initialOpacity : 0;\r\n animatedProps.style.transform = isVisible ? 'translateY(0)' : `translateY(${animate?.offset ?? 10}px)`;\r\n animatedProps.style.transition = `opacity ${animate?.duration ?? 200}ms ease-out, transform ${animate?.duration ?? 200}ms ease-out`;\r\n animatedProps.style.willChange = 'opacity, transform';\r\n\r\n const contentNode = renderContent(global, local, element.content);\r\n const childNodes = childrenMap[element.id]?.map((childId: string, index: number) => {\r\n return <Renderer\r\n key={index}\r\n {...props}\r\n id={childId}\r\n />\r\n }) || []\r\n\r\n const nodesToRender = [contentNode, ...childNodes].filter(node => node !== null && node !== undefined) // 0 is falsy\r\n\r\n if (nodesToRender.length > 0) {\r\n return <Component {...animatedProps}>\r\n {nodesToRender}\r\n </Component>\r\n }\r\n\r\n return <Component {...animatedProps}/>\r\n}\r\n","import { createContext, useContext } from \"react\";\r\n\r\nexport type SyntuxContextType = {\r\n value: any,\r\n setValue: (arg0: any) => void\r\n}\r\n\r\nexport const SyntuxContext = createContext<SyntuxContextType | null>(null)\r\n\r\nexport function useSyntux(){\r\n const context = useContext(SyntuxContext);\r\n if(!context) throw new Error(\"useSyntux must be used inside a GeneratedUI.\");\r\n return context;\r\n}"],"mappings":"aAEA,OAA0B,uBAAAA,MAA2B,cACrD,OAAqB,aAAAC,EAAW,WAAAC,EAAS,cAAAC,EAAY,UAAAC,EAAQ,YAAAC,MAAgB,QCEtE,IAAMC,EAAN,KAAqB,CACxB,OAAS,GAGT,OAAmB,CACf,YAAa,CAAC,EACd,aAAc,CAAC,EACf,KAAM,IACV,EAUA,SAASC,EAAe,CACpB,KAAK,QAAUA,EACf,IAAMC,EAAQ,KAAK,OAAO,MAAM;AAAA,CAAI,EACpC,OAAIA,EAAM,OAAS,GACfA,EAAM,MAAM,EAAGA,EAAM,OAAS,CAAC,EAAE,QAASC,GAAS,KAAK,WAAWA,CAAI,CAAC,EACxE,KAAK,OAASD,EAAMA,EAAM,OAAS,CAAC,EAC7B,IAEJ,EACX,CAMA,WAAWC,EAAc,CACrB,GAAI,CACA,IAAMC,EAAmB,KAAK,MAAMD,CAAI,EAElC,CAAE,YAAAE,EAAa,aAAAC,CAAa,EAAI,KAAK,OAE3CA,EAAaF,EAAK,EAAE,EAAIA,EACpBA,EAAK,WAAa,KAClB,KAAK,OAAO,KAAOA,GAEdC,EAAYD,EAAK,QAAQ,IAAGC,EAAYD,EAAK,QAAQ,EAAI,CAAC,GAC/DC,EAAYD,EAAK,QAAQ,EAAE,KAAKA,EAAK,EAAE,EAE/C,MAAc,CAAsD,CACxE,CAKA,QAAQ,CACJ,KAAK,WAAW,KAAK,MAAM,EAC3B,KAAK,OAAS,EAClB,CACJ,EC3DA,OAAwB,YAAAG,EAAU,aAAAC,EAAW,YAAAC,MAAgB,QA6FrB,mBAAAF,EAAA,OAAAG,MAAA,oBASkB,wBAAAC,MAAA,QAhG1D,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,QAAQ,OAAO,EACtBH,EAAY,CACd,CAAC,EAAE,MAAM,IAAM,CACbM,EAAW,EAAI,CACjB,CAAC,CACH,EAAG,CAACd,CAAW,CAAC,EAEhB,IAAMmB,GAASf,EAAAO,GAAA,YAAAA,EAAQ,UAAR,YAAAP,EAAiB,OAE1BgB,EAAgBC,EAAQ,KAAO,CAAE,MAAOhB,EAAe,SAAUC,CAAiB,GAAI,CAACD,CAAa,CAAC,EAErGiB,EAAgB,IACjBT,GAAWX,EAAsBN,EAAAD,EAAA,CAAG,SAAAO,EAAc,EAElDiB,GAAA,MAAAA,EAAQ,KACFvB,EAAC2B,EAAA,CAAS,GAAIJ,EAAO,KAAK,GAAI,aAAcA,EAAO,aAAc,YAAaA,EAAO,YAAa,kBAAmBpB,EAAmB,OAAQM,EAAe,MAAOA,EAAe,EAErLT,EAAAD,EAAA,CAAG,SAAAM,EAAY,EAI1B,OACEL,EAAAD,EAAA,CACE,SAAAC,EAAC4B,EAAc,SAAd,CAAuB,MAAOJ,EAC5B,SAAAE,EAAc,EACjB,EACF,CAEJ","names":["readStreamableValue","useEffect","useMemo","useReducer","useRef","useState","ResponseParser","delta","split","line","node","childrenMap","componentMap","Fragment","useEffect","useState","jsx","createElement","resolvePath","obj","path","acc","curr","get","global","local","blacklistedProps","resolveProps","props","resolved","key","val","renderContent","content","Renderer","_a","_b","_c","isVisible","setIsVisible","frame","id","componentMap","childrenMap","allowedComponents","animate","element","sourceArrPath","sourceArr","childrenArr","childId","index","item","index1","Component","animatedProps","initialOpacity","contentNode","childNodes","nodesToRender","node","createContext","useContext","SyntuxContext","useSyntux","context","Fragment","jsx","GeneratedClient","value","allowedComponents","inputStream","placeholder","errorFallback","animate","_a","statefulValue","setStatefulValue","useState","forceUpdate","useReducer","x","parser","useRef","errored","setErrored","useEffect","ResponseParser","delta","readStreamableValue","schema","providerValue","useMemo","renderContent","Renderer","SyntuxContext"]}
|
package/dist/index.d.mts
CHANGED
|
@@ -1,20 +1,22 @@
|
|
|
1
|
-
import { S as SyntuxComponent$1,
|
|
2
|
-
export {
|
|
1
|
+
import { S as SyntuxComponent$1, U as UISchema } from './types-C9N85B_g.mjs';
|
|
2
|
+
export { A as AnimateOptions, C as ChildrenMap, a as ComponentMap, b as SchemaNode } from './types-C9N85B_g.mjs';
|
|
3
3
|
import * as react from 'react';
|
|
4
4
|
import { JSX } from 'react';
|
|
5
5
|
import { LanguageModel } from 'ai';
|
|
6
|
-
import { SyntuxComponent,
|
|
6
|
+
import { SyntuxComponent, AnimateOptions } from 'getsyntux';
|
|
7
7
|
|
|
8
8
|
interface GeneratedContentProps {
|
|
9
9
|
value: any;
|
|
10
10
|
model: LanguageModel;
|
|
11
11
|
components?: (SyntuxComponent | string)[];
|
|
12
|
-
actions?: Record<string, ContextfulAction>;
|
|
13
12
|
hint?: string;
|
|
14
13
|
placeholder?: JSX.Element;
|
|
15
14
|
cached?: string;
|
|
16
15
|
onGenerate?: (arg0: string) => void;
|
|
17
16
|
skeletonize?: boolean;
|
|
17
|
+
onError?: (arg0: any) => void;
|
|
18
|
+
errorFallback?: JSX.Element;
|
|
19
|
+
animate?: AnimateOptions;
|
|
18
20
|
}
|
|
19
21
|
|
|
20
22
|
/**
|
|
@@ -25,21 +27,14 @@ declare function generateComponentMap(allowedComponents: (SyntuxComponent$1 | st
|
|
|
25
27
|
/**
|
|
26
28
|
* Creates LLM input in accordance to the spec
|
|
27
29
|
*/
|
|
28
|
-
declare function constructInput({ value, skeletonize, components, hint
|
|
30
|
+
declare function constructInput({ value, skeletonize, components, hint }: GeneratedContentProps): string;
|
|
29
31
|
/**
|
|
30
32
|
* generates a skeleton of the input value, ideal for large arrays or untrusted input.
|
|
31
33
|
* see the FAQ for more information: https://github.com/puffinsoft/syntux/wiki/FAQ#handling-untrusted-input--large-arrays.
|
|
32
34
|
*
|
|
33
35
|
* *important*: assumes arrays are non-polymorphic
|
|
34
36
|
*/
|
|
35
|
-
declare function
|
|
36
|
-
/**
|
|
37
|
-
* attaches metadata to callback to allow LLM understanding
|
|
38
|
-
* @param fn the action to be binded to an event on the UI
|
|
39
|
-
* @param params the parameters the function accepts, in Typescript format (e.g., "id: number, name: string")
|
|
40
|
-
* @param context a description of what the function does, for better LLM context
|
|
41
|
-
*/
|
|
42
|
-
declare function defineTool(fn: Function, params?: string, context?: string): ContextfulAction$1;
|
|
37
|
+
declare function createSkeleton(input: any): any;
|
|
43
38
|
|
|
44
39
|
/**
|
|
45
40
|
* Utility class for parsing UISchema from stream.
|
|
@@ -67,4 +62,4 @@ declare class ResponseParser {
|
|
|
67
62
|
finish(): void;
|
|
68
63
|
}
|
|
69
64
|
|
|
70
|
-
export {
|
|
65
|
+
export { ResponseParser, SyntuxComponent$1 as SyntuxComponent, UISchema, constructInput, createSkeleton, generateComponentMap };
|
package/dist/index.mjs
CHANGED
|
@@ -1,13 +1,9 @@
|
|
|
1
|
-
function
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
<ComponentContext>${c}</ComponentContext>
|
|
6
|
-
<UserContext>${h||""}</UserContext>
|
|
7
|
-
<AvailableActions>${l}</AvailableActions>
|
|
8
|
-
<IsSkeleton>${n.toString()}</IsSkeleton>
|
|
1
|
+
function h(n){return n.reduce((t,e)=>typeof e=="string"?(t[e]=e,t):(t[e.name]=e.component,t),{})}function d({value:n,skeletonize:t=!1,components:e,hint:o}){let s=(e==null?void 0:e.map(r=>typeof r=="string"?r:r.name).join(","))||"",i=e==null?void 0:e.filter(r=>typeof r!="string"),a=(i==null?void 0:i.map(r=>r.context?`${r.name} [props: ${r.props}, details: ${r.context}]`:`${r.name} [props: ${r.props}]`).join(","))||"",l=o,u=JSON.stringify(t?f(n):n);return`<AllowedComponents>${s}</AllowedComponents>
|
|
2
|
+
<ComponentContext>${a}</ComponentContext>
|
|
3
|
+
<UserContext>${l||""}</UserContext>
|
|
4
|
+
<IsSkeleton>${t.toString()}</IsSkeleton>
|
|
9
5
|
<Value>
|
|
10
|
-
${
|
|
11
|
-
</Value>`}function
|
|
12
|
-
`);return
|
|
6
|
+
${u}
|
|
7
|
+
</Value>`}function f(n){return n===null?"null":typeof n!="object"?typeof n:Array.isArray(n)?n.length==0?"null":[f(n[0])]:Object.entries(n).reduce((t,[e,o])=>(t[e]=f(o),t),{})}var p=class{buffer="";schema={childrenMap:{},componentMap:{},root:null};addDelta(t){this.buffer+=t;let e=this.buffer.split(`
|
|
8
|
+
`);return e.length>1?(e.slice(0,e.length-1).forEach(o=>this.handleLine(o)),this.buffer=e[e.length-1],!0):!1}handleLine(t){try{let e=JSON.parse(t),{childrenMap:o,componentMap:s}=this.schema;s[e.id]=e,e.parentId===null?this.schema.root=e:(o[e.parentId]||(o[e.parentId]=[]),o[e.parentId].push(e.id))}catch{}}finish(){this.handleLine(this.buffer),this.buffer=""}};export{p as ResponseParser,d as constructInput,f as createSkeleton,h as generateComponentMap};
|
|
13
9
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/util.ts","../src/ResponseParser.ts"],"sourcesContent":["import { GeneratedContentProps } from \"./templates/GeneratedUI\";\r\nimport {
|
|
1
|
+
{"version":3,"sources":["../src/util.ts","../src/ResponseParser.ts"],"sourcesContent":["import { GeneratedContentProps } from \"./templates/GeneratedUI\";\r\nimport { SyntuxComponent } from \"./types\";\r\n\r\n/**\r\n * Converts a list of components into a dictionary for fast-retrieval\r\n * during rendering.\r\n */\r\nexport function generateComponentMap(allowedComponents: (SyntuxComponent | string)[]) {\r\n return allowedComponents.reduce((acc: Record<string, React.ComponentType<any> | string>, curr: SyntuxComponent | string) => {\r\n if (typeof curr === \"string\") {\r\n acc[curr] = curr;\r\n return acc;\r\n }\r\n\r\n acc[curr.name] = curr.component;\r\n return acc;\r\n }, {})\r\n}\r\n\r\n/**\r\n * Creates LLM input in accordance to the spec\r\n */\r\nexport function constructInput({\r\n value, skeletonize = false, components, hint\r\n}: GeneratedContentProps) {\r\n const allowedComponents = components?.map((item: SyntuxComponent | string) => {\r\n if (typeof item === \"string\") return item;\r\n return item.name;\r\n }).join(',') || \"\"\r\n\r\n const customComponents = components?.filter((item): item is SyntuxComponent => typeof item !== \"string\");\r\n const componentContext = customComponents?.map((item) => {\r\n if (!item.context) {\r\n return `${item.name} [props: ${item.props}]`\r\n } else {\r\n return `${item.name} [props: ${item.props}, details: ${item.context}]`\r\n }\r\n }).join(',') || \"\"\r\n\r\n const userContext = hint;\r\n\r\n const inputValue = JSON.stringify(skeletonize ? createSkeleton(value) : value)\r\n\r\n return `<AllowedComponents>${allowedComponents}</AllowedComponents>\\n<ComponentContext>${componentContext}</ComponentContext>\\n<UserContext>${userContext || \"\"}</UserContext>\\n<IsSkeleton>${skeletonize.toString()}</IsSkeleton>\\n<Value>\\n${inputValue}\\n</Value>`\r\n}\r\n\r\n/**\r\n * generates a skeleton of the input value, ideal for large arrays or untrusted input.\r\n * see the FAQ for more information: https://github.com/puffinsoft/syntux/wiki/FAQ#handling-untrusted-input--large-arrays.\r\n * \r\n * *important*: assumes arrays are non-polymorphic\r\n */\r\nexport function createSkeleton(input: any) {\r\n if (input === null) return \"null\";\r\n\r\n if (typeof input !== \"object\") return typeof input;\r\n\r\n if (Array.isArray(input)) {\r\n if (input.length == 0) {\r\n return \"null\"; // ignore this field completely\r\n } else {\r\n return [createSkeleton(input[0])]\r\n }\r\n }\r\n return Object.entries(input).reduce((acc, [key, value]) => {\r\n acc[key] = createSkeleton(value);\r\n return acc;\r\n }, {})\r\n}","import { SchemaNode, UISchema } from \"./types\";\r\n\r\n/**\r\n * Utility class for parsing UISchema from stream.\r\n */\r\nexport class ResponseParser {\r\n buffer = \"\"; // unflushed existing deltas w/o newline\r\n \r\n // schema assembled thus far\r\n schema: UISchema = {\r\n childrenMap: {},\r\n componentMap: {},\r\n root: null\r\n }\r\n\r\n /**\r\n * Update schema with latest data chunk.\r\n * \r\n * Handles multiline input gracefully; can be used to load entire schemas from cache.\r\n * \r\n * @param delta delta from stream.\r\n * @returns true if update is warranted, false otherwise.\r\n */\r\n addDelta(delta: string) {\r\n this.buffer += delta;\r\n const split = this.buffer.split(\"\\n\")\r\n if (split.length > 1) {\r\n split.slice(0, split.length - 1).forEach((line) => this.handleLine(line));\r\n this.buffer = split[split.length - 1];\r\n return true;\r\n }\r\n return false;\r\n }\r\n\r\n /**\r\n * Parses a single line (full JSON object) and updates schema.\r\n * Generally should not be used when streaming data.\r\n */\r\n handleLine(line: string) {\r\n try {\r\n const node: SchemaNode = JSON.parse(line);\r\n\r\n const { childrenMap, componentMap } = this.schema;\r\n\r\n componentMap[node.id] = node;\r\n if (node.parentId === null) {\r\n this.schema.root = node;\r\n } else {\r\n if (!childrenMap[node.parentId]) childrenMap[node.parentId] = []\r\n childrenMap[node.parentId].push(node.id)\r\n }\r\n } catch (err) { /* probably markdown or generation inconsistency */ }\r\n }\r\n\r\n /**\r\n * Clears the buffer and handles any remaining information within.\r\n */\r\n finish(){\r\n this.handleLine(this.buffer);\r\n this.buffer = \"\";\r\n }\r\n}"],"mappings":"AAOO,SAASA,EAAqBC,EAAiD,CAClF,OAAOA,EAAkB,OAAO,CAACC,EAAwDC,IACjF,OAAOA,GAAS,UAChBD,EAAIC,CAAI,EAAIA,EACLD,IAGXA,EAAIC,EAAK,IAAI,EAAIA,EAAK,UACfD,GACR,CAAC,CAAC,CACT,CAKO,SAASE,EAAe,CAC3B,MAAAC,EAAO,YAAAC,EAAc,GAAO,WAAAC,EAAY,KAAAC,CAC5C,EAA0B,CACtB,IAAMP,GAAoBM,GAAA,YAAAA,EAAY,IAAKE,GACnC,OAAOA,GAAS,SAAiBA,EAC9BA,EAAK,MACb,KAAK,OAAQ,GAEVC,EAAmBH,GAAA,YAAAA,EAAY,OAAQE,GAAkC,OAAOA,GAAS,UACzFE,GAAmBD,GAAA,YAAAA,EAAkB,IAAKD,GACvCA,EAAK,QAGC,GAAGA,EAAK,IAAI,YAAYA,EAAK,KAAK,cAAcA,EAAK,OAAO,IAF5D,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AAC,GAC/DC,EAAYD,EAAK,QAAQ,EAAE,KAAKA,EAAK,EAAE,EAE/C,MAAc,CAAsD,CACxE,CAKA,QAAQ,CACJ,KAAK,WAAW,KAAK,MAAM,EAC3B,KAAK,OAAS,EAClB,CACJ","names":["generateComponentMap","allowedComponents","acc","curr","constructInput","value","skeletonize","components","hint","item","customComponents","componentContext","userContext","inputValue","createSkeleton","input","key","ResponseParser","delta","split","line","node","childrenMap","componentMap"]}
|
package/dist/metafile-esm.json
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"inputs":{"src/types.ts":{"bytes":
|
|
1
|
+
{"inputs":{"src/types.ts":{"bytes":692,"imports":[],"format":"esm"},"src/util.ts":{"bytes":2558,"imports":[{"path":"./templates/GeneratedUI","kind":"import-statement","external":true},{"path":"./types","kind":"import-statement","external":true}],"format":"esm"},"src/ResponseParser.ts":{"bytes":1865,"imports":[{"path":"./types","kind":"import-statement","external":true}],"format":"esm"},"src/index.ts":{"bytes":84,"imports":[{"path":"src/types.ts","kind":"import-statement","original":"./types"},{"path":"src/util.ts","kind":"import-statement","original":"./util"},{"path":"src/ResponseParser.ts","kind":"import-statement","original":"./ResponseParser"}],"format":"esm"},"src/client/Renderer.tsx":{"bytes":4570,"imports":[{"path":"react","kind":"import-statement","external":true},{"path":"../types","kind":"import-statement","external":true},{"path":"react/jsx-runtime","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"src/client/SyntuxContext.tsx":{"bytes":407,"imports":[{"path":"react","kind":"import-statement","external":true}],"format":"esm"},"src/client/GeneratedClient.tsx":{"bytes":2329,"imports":[{"path":"@ai-sdk/rsc","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"src/types","kind":"import-statement","external":true},{"path":"src/ResponseParser.ts","kind":"import-statement","original":"../ResponseParser"},{"path":"src/client/Renderer.tsx","kind":"import-statement","original":"./Renderer"},{"path":"src/client/SyntuxContext.tsx","kind":"import-statement","original":"./SyntuxContext"},{"path":"react/jsx-runtime","kind":"import-statement","external":true}],"format":"esm"},"src/client.ts":{"bytes":133,"imports":[{"path":"src/client/GeneratedClient.tsx","kind":"import-statement","original":"./client/GeneratedClient"},{"path":"src/client/Renderer.tsx","kind":"import-statement","original":"./client/Renderer"},{"path":"src/client/SyntuxContext.tsx","kind":"import-statement","original":"./client/SyntuxContext"}],"format":"esm"},"src/bin/cli_util.mjs":{"bytes":115,"imports":[{"path":"chalk","kind":"import-statement","external":true}],"format":"esm"},"src/bin/commands/init.mjs":{"bytes":3700,"imports":[{"path":"commander","kind":"import-statement","external":true},{"path":"fs-extra","kind":"import-statement","external":true},{"path":"path","kind":"import-statement","external":true},{"path":"child_process","kind":"import-statement","external":true},{"path":"prompts","kind":"import-statement","external":true},{"path":"chalk","kind":"import-statement","external":true},{"path":"src/bin/cli_util.mjs","kind":"import-statement","original":"../cli_util.mjs"},{"path":"url","kind":"import-statement","external":true}],"format":"esm"},"src/bin/commands/generate.mjs":{"bytes":2933,"imports":[{"path":"commander","kind":"import-statement","external":true},{"path":"path","kind":"import-statement","external":true},{"path":"react-docgen-typescript","kind":"import-statement","external":true},{"path":"prompts","kind":"import-statement","external":true},{"path":"chalk","kind":"import-statement","external":true},{"path":"fs-extra","kind":"import-statement","external":true},{"path":"src/bin/cli_util.mjs","kind":"import-statement","original":"../cli_util.mjs"}],"format":"esm"},"src/bin/cli.mjs":{"bytes":482,"imports":[{"path":"commander","kind":"import-statement","external":true},{"path":"src/bin/commands/init.mjs","kind":"import-statement","original":"./commands/init.mjs"},{"path":"src/bin/commands/generate.mjs","kind":"import-statement","original":"./commands/generate.mjs"}],"format":"esm"}},"outputs":{"dist/index.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":6851},"dist/index.mjs":{"imports":[],"exports":["ResponseParser","constructInput","createSkeleton","generateComponentMap"],"entryPoint":"src/index.ts","inputs":{"src/index.ts":{"bytesInOutput":0},"src/util.ts":{"bytesInOutput":809},"src/ResponseParser.ts":{"bytesInOutput":485}},"bytes":1389},"dist/client.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":15781},"dist/client.mjs":{"imports":[{"path":"@ai-sdk/rsc","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react/jsx-runtime","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react","kind":"import-statement","external":true},{"path":"react/jsx-runtime","kind":"import-statement","external":true}],"exports":["GeneratedClient","Renderer","SyntuxContext","useSyntux"],"entryPoint":"src/client.ts","inputs":{"src/client/GeneratedClient.tsx":{"bytesInOutput":848},"src/ResponseParser.ts":{"bytesInOutput":485},"src/client/Renderer.tsx":{"bytesInOutput":1727},"src/client/SyntuxContext.tsx":{"bytesInOutput":172},"src/client.ts":{"bytesInOutput":0}},"bytes":3325},"dist/bin/cli.mjs.map":{"imports":[],"exports":[],"inputs":{},"bytes":12417},"dist/bin/cli.mjs":{"imports":[{"path":"commander","kind":"import-statement","external":true},{"path":"commander","kind":"import-statement","external":true},{"path":"fs-extra","kind":"import-statement","external":true},{"path":"path","kind":"import-statement","external":true},{"path":"child_process","kind":"import-statement","external":true},{"path":"prompts","kind":"import-statement","external":true},{"path":"chalk","kind":"import-statement","external":true},{"path":"chalk","kind":"import-statement","external":true},{"path":"url","kind":"import-statement","external":true},{"path":"commander","kind":"import-statement","external":true},{"path":"path","kind":"import-statement","external":true},{"path":"react-docgen-typescript","kind":"import-statement","external":true},{"path":"prompts","kind":"import-statement","external":true},{"path":"chalk","kind":"import-statement","external":true},{"path":"fs-extra","kind":"import-statement","external":true}],"exports":[],"entryPoint":"src/bin/cli.mjs","inputs":{"src/bin/cli.mjs":{"bytesInOutput":250},"src/bin/commands/init.mjs":{"bytesInOutput":1851},"src/bin/cli_util.mjs":{"bytesInOutput":78},"src/bin/commands/generate.mjs":{"bytesInOutput":1443}},"bytes":3643}}}
|
|
@@ -3,26 +3,29 @@ import { JSX } from 'react';
|
|
|
3
3
|
import { createStreamableValue } from '@ai-sdk/rsc';
|
|
4
4
|
import { LanguageModel, streamText } from 'ai';
|
|
5
5
|
|
|
6
|
+
import { AnimateOptions, ResponseParser, SyntuxComponent, UISchema, constructInput, generateComponentMap } from "getsyntux";
|
|
6
7
|
import { GeneratedClient, Renderer } from 'getsyntux/client';
|
|
7
|
-
import { ContextfulAction, ResponseParser, SyntuxComponent, UISchema, constructInput, generateComponentMap } from "getsyntux";
|
|
8
8
|
|
|
9
9
|
import spec from './spec';
|
|
10
10
|
|
|
11
11
|
export interface GeneratedContentProps {
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
12
|
+
value: any;
|
|
13
|
+
model: LanguageModel;
|
|
14
|
+
components?: (SyntuxComponent | string)[];
|
|
15
|
+
hint?: string;
|
|
16
|
+
placeholder?: JSX.Element;
|
|
17
|
+
cached?: string;
|
|
18
|
+
/*
|
|
19
|
+
* ^ this is a string for two reasons:
|
|
20
|
+
* - it is easier to store
|
|
21
|
+
* - it is parsed then mutated at runtime. This avoids unintended side effects.
|
|
22
|
+
*/
|
|
23
|
+
onGenerate?: (arg0: string) => void;
|
|
24
|
+
skeletonize?: boolean;
|
|
25
|
+
|
|
26
|
+
onError?: (arg0: any) => void;
|
|
27
|
+
errorFallback?: JSX.Element;
|
|
28
|
+
animate?: AnimateOptions
|
|
26
29
|
}
|
|
27
30
|
|
|
28
31
|
/**
|
|
@@ -30,56 +33,71 @@ export interface GeneratedContentProps {
|
|
|
30
33
|
* @param values The values (object, primitive, or array) to be displayed.
|
|
31
34
|
* @param model The LanguageModel (as provided from AI SDK) to use. Must support streaming
|
|
32
35
|
* @param components List of allowed components that LLM can use.
|
|
33
|
-
* @param actions Map of callbacks that can be attached to events (e.g., onClick, onMouseOver) by LLM.
|
|
34
36
|
* @param hint Additional custom instructions for the LLM.
|
|
35
37
|
* @param placeholder A placeholder to show while awaiting streaming (NOT during streaming)
|
|
36
38
|
* @param cached Schema returned from onGenerate, used for caching UI
|
|
37
39
|
* @param onGenerate Callback which accepts a string, to be passed to `cached` to reuse same UI
|
|
38
40
|
* @param skeletonize Compresses value for large inputs (arrays) or untrusted input
|
|
41
|
+
* @param onError Callback which accepts an error, invoked when necessary. If not provided, runtime error occurs.
|
|
42
|
+
* @param errorFallback An element fallback to show if an error occurs during generation.
|
|
39
43
|
*/
|
|
40
44
|
export async function GeneratedUI(props: GeneratedContentProps) {
|
|
41
45
|
const input = constructInput(props);
|
|
42
46
|
|
|
43
|
-
const { value, model, components, placeholder, cached, onGenerate,
|
|
44
|
-
|
|
47
|
+
const { value, model, components, placeholder, cached, onGenerate, onError, errorFallback, animate } = props;
|
|
48
|
+
|
|
45
49
|
const allowedComponents = generateComponentMap(components || []);
|
|
46
50
|
|
|
47
51
|
// prerender if cached
|
|
48
|
-
if(cached){
|
|
52
|
+
if (cached) {
|
|
49
53
|
const parser = new ResponseParser();
|
|
50
54
|
parser.addDelta(cached);
|
|
51
55
|
parser.finish();
|
|
52
56
|
|
|
53
57
|
const schema: UISchema = parser.schema;
|
|
54
58
|
|
|
55
|
-
if(schema.root){
|
|
59
|
+
if (schema.root) {
|
|
56
60
|
return <Renderer id={schema.root.id} componentMap={schema.componentMap} childrenMap={schema.childrenMap}
|
|
57
|
-
allowedComponents={allowedComponents} global={value} local={value}
|
|
61
|
+
allowedComponents={allowedComponents} global={value} local={value} animate={animate} />
|
|
58
62
|
} else {
|
|
59
63
|
return <></>;
|
|
60
64
|
}
|
|
61
65
|
}
|
|
62
66
|
|
|
63
67
|
const stream = createStreamableValue('');
|
|
64
|
-
|
|
65
68
|
(async () => {
|
|
66
69
|
let total = "";
|
|
70
|
+
let errored = false;
|
|
67
71
|
|
|
68
72
|
const { textStream } = await streamText({
|
|
69
73
|
model,
|
|
70
74
|
system: spec,
|
|
71
|
-
prompt: input
|
|
75
|
+
prompt: input,
|
|
76
|
+
onError: (err) => {
|
|
77
|
+
stream.error(err)
|
|
78
|
+
errored = true;
|
|
79
|
+
|
|
80
|
+
if (!onError) {
|
|
81
|
+
if (!errorFallback) {
|
|
82
|
+
throw err;
|
|
83
|
+
}
|
|
84
|
+
} else {
|
|
85
|
+
onError(err)
|
|
86
|
+
}
|
|
87
|
+
}
|
|
72
88
|
})
|
|
73
89
|
|
|
74
|
-
for await(const delta of textStream){
|
|
90
|
+
for await (const delta of textStream) {
|
|
75
91
|
stream.update(delta);
|
|
76
92
|
total += delta;
|
|
77
93
|
}
|
|
78
94
|
|
|
79
|
-
|
|
95
|
+
if (!errored) {
|
|
96
|
+
stream.done();
|
|
97
|
+
}
|
|
80
98
|
|
|
81
|
-
if(onGenerate) onGenerate(total);
|
|
99
|
+
if (onGenerate) onGenerate(total);
|
|
82
100
|
})()
|
|
83
101
|
|
|
84
|
-
return <GeneratedClient value={value} allowedComponents={allowedComponents} inputStream={stream.value} placeholder={placeholder}
|
|
102
|
+
return <GeneratedClient value={value} allowedComponents={allowedComponents} inputStream={stream.value} placeholder={placeholder} errorFallback={errorFallback} animate={animate} />
|
|
85
103
|
}
|
package/dist/templates/spec.md
CHANGED
|
@@ -32,24 +32,6 @@ Use "$bind" in `content` or `props` to link data.
|
|
|
32
32
|
Use "$bind": "$" to reference the global object itself, useful when the value itself is an array and you need to loop through it.
|
|
33
33
|
</binding_rules>
|
|
34
34
|
|
|
35
|
-
<action_rules>
|
|
36
|
-
In the props, to attach event handlers (like onClick), use the "$action" schema.
|
|
37
|
-
Format: { "$action": "actionName", "args": [arg1, arg2, ...] }
|
|
38
|
-
|
|
39
|
-
Argument Rules:
|
|
40
|
-
- Hardcoded value: Pass the literal value directly (e.g., "dark_mode", 15, true).
|
|
41
|
-
- Dynamic value: Use a binding object (e.g., { "$bind": "$item.id" }).
|
|
42
|
-
|
|
43
|
-
Example:
|
|
44
|
-
"props": {
|
|
45
|
-
"onClick": {
|
|
46
|
-
"$action": "addToCart",
|
|
47
|
-
"args": [ { "$bind": "$item.id" }, 1 ]
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
This calls the `addToCart` action with the item's ID and the number 1.
|
|
51
|
-
</action_rules>
|
|
52
|
-
|
|
53
35
|
<iteration>
|
|
54
36
|
To render arrays, use the `__ForEach__` component.
|
|
55
37
|
To define a loop:
|
|
@@ -68,13 +50,13 @@ In the example above, card_1 is the template that repeats for every author. It s
|
|
|
68
50
|
* `AllowedComponents` is a comma-separated list, lowercase for Native HTML tags, Uppercase for Custom React Components. If none are provided, you can use any HTML tag. If they are, only use them to the best of your ability.
|
|
69
51
|
* `ComponentContext` defines the Typescript interface for custom components. Components are separated by a comma, in the format `ComponentName [props: { ... }, details: "..."]`. The `props` indicate what `props` it must accept, in Typescript format. The `details` is an optional field, and describes what the component does. DO NOT hallucinate props. Use the details to better your understanding of how to generate the UI.
|
|
70
52
|
2. Parse Context: Read `UserContext` for specific design requests.
|
|
71
|
-
3. Parse
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
53
|
+
3. Parse Data: Analyze `Value` to determine structure.
|
|
54
|
+
4. Check Skeleton: Read `IsSkeleton`. If it is `true`, that means all the property values have been replaced by the *type* of the value. If it is `false`, then you are seeing the raw values of each property.
|
|
55
|
+
5. Check Existing: If `Existing` exists, then your job is to update the existing UI.
|
|
56
|
+
* Existing is the schema for the existing UI
|
|
57
|
+
* Read UserContext: it contains a request to update the UI
|
|
58
|
+
* Output the same, full UI, updated with the request. For instance, if UserContext says to remove something, generate the same UI, but with the thing removed.
|
|
59
|
+
* Ensure the new UI is semantically valid.
|
|
78
60
|
</input_processing_rules>
|
|
79
61
|
|
|
80
62
|
<output_formatting>
|
|
@@ -84,7 +66,6 @@ Input:
|
|
|
84
66
|
<AllowedComponents>...</AllowedComponents>
|
|
85
67
|
<ComponentContext>...</ComponentContext>
|
|
86
68
|
<UserContext>...</UserContext>
|
|
87
|
-
<AvailableActions>...</AvailableActions>
|
|
88
69
|
<IsSkeleton>...</IsSkeleton>
|
|
89
70
|
<Value>...</Value>
|
|
90
71
|
|
package/dist/templates/spec.ts
CHANGED
|
@@ -38,24 +38,6 @@ Use "$bind" in \`content\` or \`props\` to link data.
|
|
|
38
38
|
Use "$bind": "$" to reference the global object itself, useful when the value itself is an array and you need to loop through it.
|
|
39
39
|
</binding_rules>
|
|
40
40
|
|
|
41
|
-
<action_rules>
|
|
42
|
-
In the props, to attach event handlers (like onClick), use the "$action" schema.
|
|
43
|
-
Format: { "$action": "actionName", "args": [arg1, arg2, ...] }
|
|
44
|
-
|
|
45
|
-
Argument Rules:
|
|
46
|
-
- Hardcoded value: Pass the literal value directly (e.g., "dark_mode", 15, true).
|
|
47
|
-
- Dynamic value: Use a binding object (e.g., { "$bind": "$item.id" }).
|
|
48
|
-
|
|
49
|
-
Example:
|
|
50
|
-
"props": {
|
|
51
|
-
"onClick": {
|
|
52
|
-
"$action": "addToCart",
|
|
53
|
-
"args": [ { "$bind": "$item.id" }, 1 ]
|
|
54
|
-
}
|
|
55
|
-
}
|
|
56
|
-
This calls the \`addToCart\` action with the item's ID and the number 1.
|
|
57
|
-
</action_rules>
|
|
58
|
-
|
|
59
41
|
<iteration>
|
|
60
42
|
To render arrays, use the \`__ForEach__\` component.
|
|
61
43
|
To define a loop:
|
|
@@ -74,13 +56,13 @@ In the example above, card_1 is the template that repeats for every author. It s
|
|
|
74
56
|
* \`AllowedComponents\` is a comma-separated list, lowercase for Native HTML tags, Uppercase for Custom React Components. If none are provided, you can use any HTML tag. If they are, only use them to the best of your ability.
|
|
75
57
|
* \`ComponentContext\` defines the Typescript interface for custom components. Components are separated by a comma, in the format \`ComponentName [props: { ... }, details: "..."]\`. The \`props\` indicate what \`props\` it must accept, in Typescript format. The \`details\` is an optional field, and describes what the component does. DO NOT hallucinate props. Use the details to better your understanding of how to generate the UI.
|
|
76
58
|
2. Parse Context: Read \`UserContext\` for specific design requests.
|
|
77
|
-
3. Parse
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
59
|
+
3. Parse Data: Analyze \`Value\` to determine structure.
|
|
60
|
+
4. Check Skeleton: Read \`IsSkeleton\`. If it is \`true\`, that means all the property values have been replaced by the *type* of the value. If it is \`false\`, then you are seeing the raw values of each property.
|
|
61
|
+
5. Check Existing: If \`Existing\` exists, then your job is to update the existing UI.
|
|
62
|
+
* Existing is the schema for the existing UI
|
|
63
|
+
* Read UserContext: it contains a request to update the UI
|
|
64
|
+
* Output the same, full UI, updated with the request. For instance, if UserContext says to remove something, generate the same UI, but with the thing removed.
|
|
65
|
+
* Ensure the new UI is semantically valid.
|
|
84
66
|
</input_processing_rules>
|
|
85
67
|
|
|
86
68
|
<output_formatting>
|
|
@@ -90,7 +72,6 @@ Input:
|
|
|
90
72
|
<AllowedComponents>...</AllowedComponents>
|
|
91
73
|
<ComponentContext>...</ComponentContext>
|
|
92
74
|
<UserContext>...</UserContext>
|
|
93
|
-
<AvailableActions>...</AvailableActions>
|
|
94
75
|
<IsSkeleton>...</IsSkeleton>
|
|
95
76
|
<Value>...</Value>
|
|
96
77
|
|
|
@@ -20,10 +20,9 @@ type SyntuxComponent = {
|
|
|
20
20
|
component: React.ComponentType<any>;
|
|
21
21
|
context?: string;
|
|
22
22
|
};
|
|
23
|
-
type
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
context: string;
|
|
23
|
+
type AnimateOptions = {
|
|
24
|
+
offset: number;
|
|
25
|
+
duration: number;
|
|
27
26
|
};
|
|
28
27
|
|
|
29
|
-
export type {
|
|
28
|
+
export type { AnimateOptions as A, ChildrenMap as C, SyntuxComponent as S, UISchema as U, ComponentMap as a, SchemaNode as b };
|
package/package.json
CHANGED