用途
@json-render/svelte 是 json-render 的 Svelte 5 渲染器,将 json-render 的 JSON 规格(spec)转换为 Svelte 组件树。
主要能力
- 渲染器与 Provider:提供 Renderer 和 JsonUIProvider。JsonUIProvider 组合全部上下文,单项上下文包括 StateContext(跨组件共享状态,使用 JSON Pointer 路径)、ActionContext(处理事件系统派发的动作)、VisibilityContext(基于状态的条件渲染)、ValidationContext(表单字段校验)。
- 目录(Catalog):通过 defineCatalog 结合 @json-render/core 与 @json-render/svelte 的 schema 及 zod 定义组件及其 props。
- 组件注册表:通过 defineRegistry 定义 registry、handlers 和 executeAction,绑定组件与动作(如 submit)。
- 规格结构:使用元素树(element tree)格式,包含 root 与 elements,元素含 type、props、children。
- 可见性条件:元素可用 visible 基于状态显示/隐藏,支持真值检查 { "$state": "/path" }、相等检查(eq)、假值检查(not)、AND($and)、OR($or)。
- 事件系统:组件通过 emit 触发命名事件,元素的 on 字段将事件映射到动作绑定。
- 内置动作:setState 自动处理并更新状态模型;其他内置动作有 pushState、removeState、push、pop。
- 动态 props 与双向绑定:表达式形式包括从状态读取 { "$state": "/state/key" }、读写回状态 { "$bindState": "/form/email" }、repeat 项读写 { "$bindItem": "field" }、条件值 { "$cond": ..., "$then": ..., "$else": ... }。嵌套列表可在 enclosing repeat 内将 repeat.statePath 设为 { "$item": "field" }。组件内可写绑定使用 getBoundProp。
- 上下文辅助方法:getStateValue(path)、getBoundProp(() => value, () => bindingPath)、isVisible(condition)、getAction(name),以及高级访问 getStateContext()、getActionContext()、getVisibilityContext()、getValidationContext()、getOptionalValidationContext()、getFieldValidation(ctx, path, config?)。
- 流式 UI:使用 createUIStream 进行 spec 流式生成,可设置 api、onComplete,并通过 stream.send 发送请求、stream.isStreaming 判断流状态;使用 createChatUI 处理聊天与 UI 响应。
使用方式
- 快速开始:从 @json-render/svelte 导入 Renderer、JsonUIProvider 与 Spec 类型,定义 registry 映射组件(如 Card、Button)。
- 创建目录:使用 defineCatalog(schema, { components: { ... } }),props 由 zod 描述。
- 定义组件:组件应接受 BaseComponentProps<TProps>,包含 props(已解析的组件 props)、children(Snippet,使用 {@render children()})、emit(触发命名事件)、bindings(prop 名到状态路径的映射,用于 $bindState)、loading(spec 流式传输期间为 true)。
- 创建注册表:使用 defineRegistry(catalog, { components, actions })。
- 编写规格:采用元素树格式,例如 root 为 card1,elements 中包含 card1 与 btn1。
- 流式生成:createUIStream({ api: "/api/generate-ui", onComplete }) 配合 Renderer 的 spec 与 loading。
适用场景
- 使用 @json-render/svelte 开发 Svelte 应用。
- 从 JSON 构建 Svelte UI。
- 需要流式生成界面或聊天式 UI 响应的场景。
限制
资料未提供收费、价格、平台支持范围或效果相关说明。