omnimux-forms 0.0.0-stage → 0.1.0
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 +10 -2
- package/assets/examples/README.md +7 -0
- package/assets/examples/replication-demo.mp4 +0 -0
- package/cordis.patch.yml +3 -0
- package/dsh.manifest.json +6 -0
- package/lib/client.js +39576 -0
- package/package.json +56 -4
- package/src/client/Fields.jsx +44 -0
- package/src/client/FormsPage.jsx +69 -0
- package/src/client/components.test.mjs +62 -0
- package/src/client/index.js +17 -0
- package/src/client/model.js +142 -0
- package/src/client/model.test.mjs +21 -0
- package/src/client/sidebar-entry.js +94 -0
- package/src/client/theme.js +20 -0
- package/src/client/workbench-seat.test.mjs +23 -0
- package/src/http.test.mjs +53 -0
- package/src/index.js +58 -0
- package/src/store.js +70 -0
- package/src/store.test.mjs +27 -0
package/package.json
CHANGED
|
@@ -1,6 +1,58 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "omnimux-forms",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"main": "src/index.js",
|
|
6
|
+
"exports": {
|
|
7
|
+
".": "./src/index.js",
|
|
8
|
+
"./client": "./lib/client.js",
|
|
9
|
+
"./package.json": "./package.json"
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"src",
|
|
13
|
+
"lib/client.js",
|
|
14
|
+
"assets/examples",
|
|
15
|
+
"cordis.patch.yml",
|
|
16
|
+
"dsh.manifest.json",
|
|
17
|
+
"README.md"
|
|
18
|
+
],
|
|
19
|
+
"scripts": {
|
|
20
|
+
"build": "node scripts/build-client.mjs",
|
|
21
|
+
"test": "node --test src/*.test.mjs src/client/*.test.mjs"
|
|
22
|
+
},
|
|
23
|
+
"devDependencies": {
|
|
24
|
+
"esbuild": "^0.25.0",
|
|
25
|
+
"jsdom": "^30.0.1",
|
|
26
|
+
"react": "^18.2.0",
|
|
27
|
+
"react-dom": "^18.2.0",
|
|
28
|
+
"@chakra-ui/react": "3.37.0",
|
|
29
|
+
"@emotion/react": "11.14.0",
|
|
30
|
+
"dsh-ui-kit": "file:../../packages/dsh-ui-kit",
|
|
31
|
+
"@omnimux/form-contract": "file:../../packages/form-contract"
|
|
32
|
+
},
|
|
33
|
+
"dsh": {
|
|
34
|
+
"bundle": {
|
|
35
|
+
"patch": "./cordis.patch.yml"
|
|
36
|
+
},
|
|
37
|
+
"client": {
|
|
38
|
+
"inject": [
|
|
39
|
+
"@deepseek-ai/dsh-client-ui-renderer",
|
|
40
|
+
"@deepseek-ai/dsh-client-ui-primitives"
|
|
41
|
+
],
|
|
42
|
+
"platform": "web"
|
|
43
|
+
}
|
|
44
|
+
},
|
|
45
|
+
"license": "MIT",
|
|
46
|
+
"peerDependencies": {
|
|
47
|
+
"react": "^18.2.0",
|
|
48
|
+
"react-dom": "^18.2.0"
|
|
49
|
+
},
|
|
50
|
+
"peerDependenciesMeta": {
|
|
51
|
+
"react": {
|
|
52
|
+
"optional": true
|
|
53
|
+
},
|
|
54
|
+
"react-dom": {
|
|
55
|
+
"optional": true
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import React from 'react'
|
|
2
|
+
import { Box, Button, Field, FileUpload, Flex, Input, NumberInput, RadioCard, Slider, Text, Textarea } from '@chakra-ui/react'
|
|
3
|
+
import { control, secondary } from './theme.js'
|
|
4
|
+
|
|
5
|
+
export function FormField({ field, value, errors, disabled, editor, state, hub, workspaceId }) {
|
|
6
|
+
const id = `omnimux-form-${field.id}`, error = errors.map(e => e.message).join(';')
|
|
7
|
+
const change = next => editor.set(field.id, next)
|
|
8
|
+
let input
|
|
9
|
+
if (field.type === 'text') input = <Input id={id} {...control} px="10px" value={value ?? ''} maxLength={field.maxLength} onChange={e => change(e.target.value)} />
|
|
10
|
+
if (field.type === 'textarea') input = <Textarea id={id} {...control} height="auto" minHeight="104px" padding="10px" resize="vertical" value={value ?? ''} maxLength={field.maxLength} onChange={e => change(e.target.value)} />
|
|
11
|
+
if (field.type === 'number') input = <NumberInput.Root id={id} value={value === undefined ? '' : String(value)} min={field.min} max={field.max} step={field.step} disabled={disabled} onValueChange={e => change(e.value === '' ? '' : Number.isFinite(e.valueAsNumber) ? e.valueAsNumber : e.value)}>
|
|
12
|
+
<NumberInput.Input {...control} px="10px" aria-label={field.label} />
|
|
13
|
+
<NumberInput.Control><NumberInput.IncrementTrigger aria-label={`增加${field.label}`} /><NumberInput.DecrementTrigger aria-label={`减少${field.label}`} /></NumberInput.Control>
|
|
14
|
+
</NumberInput.Root>
|
|
15
|
+
if (field.type === 'slider') input = <Slider.Root width="100%" id={id} min={field.min} max={field.max} step={field.step} value={[typeof value === 'number' ? value : field.min]} disabled={disabled} onValueChange={e => change(e.value[0])}>
|
|
16
|
+
<Flex justify="flex-end"><Slider.Label srOnly>{field.label}</Slider.Label><Slider.ValueText /></Flex>
|
|
17
|
+
<Slider.Control paddingBlock="12px"><Slider.Track height="4px" bg="var(--dsw-alias-bg-layer-3)"><Slider.Range bg="var(--dsw-alias-label-primary)" /></Slider.Track><Slider.Thumb index={0} aria-label={field.label} width="16px" height="16px" bg="var(--dsw-alias-label-primary)" borderColor="var(--dsw-alias-border-l3)"><Slider.HiddenInput aria-label={field.label} /></Slider.Thumb></Slider.Control>
|
|
18
|
+
</Slider.Root>
|
|
19
|
+
if (field.type === 'select' || field.type === 'aspect-ratio') input = <RadioCard.Root id={id} value={value ?? null} disabled={disabled} onValueChange={e => change(e.value ?? undefined)} aria-label={field.label}>
|
|
20
|
+
<Flex gap="8px" wrap="wrap">{field.options.map(option => <RadioCard.Item key={option.value} value={option.value} cursor="pointer" border="1px solid var(--dsw-alias-border-l2)" borderRadius="8px" boxShadow="none" bg="var(--dsw-alias-bg-layer-1)" _checked={{ borderColor: 'var(--dsw-alias-label-primary)', bg: 'var(--dsw-alias-interactive-bg-active)' }} _focusWithin={{ outline: '2px solid var(--dsw-alias-brand-primary)', outlineOffset: '2px' }}>
|
|
21
|
+
<RadioCard.ItemHiddenInput /><RadioCard.ItemControl minHeight="32px" padding="8px 12px" gap="8px">{field.type === 'aspect-ratio' && <Box aria-hidden="true" width="20px" height="20px" display="flex" alignItems="center" justifyContent="center"><Box border="1px solid currentColor" width="16px" maxHeight="20px" aspectRatio={option.value.replace(':', '/')} /></Box>}<RadioCard.ItemText fontSize="14px">{option.label}</RadioCard.ItemText></RadioCard.ItemControl>
|
|
22
|
+
</RadioCard.Item>)}</Flex>
|
|
23
|
+
</RadioCard.Root>
|
|
24
|
+
if (field.type === 'file') input = <Box width="100%">
|
|
25
|
+
<FileUpload.Root acceptedFiles={[]} maxFiles={field.maxFiles} maxFileSize={field.maxBytes} accept={field.accept} disabled={disabled} onFileAccept={e => editor.importFiles(field, e.files)} onFileReject={() => editor.rejectFiles()}>
|
|
26
|
+
<FileUpload.HiddenInput id={id} aria-label={field.label} />
|
|
27
|
+
<FileUpload.Dropzone padding="20px" minHeight="104px" border="1px dashed var(--dsw-alias-border-l3)" borderRadius="10px" bg="var(--dsw-alias-bg-layer-1)" _dragging={{ borderColor: 'var(--dsw-alias-brand-primary)' }}>
|
|
28
|
+
<FileUpload.Trigger asChild><Button {...secondary}>选择文件</Button></FileUpload.Trigger>
|
|
29
|
+
<Text fontSize="13px" color="var(--dsw-alias-label-secondary)">或拖放到这里,最多 {field.maxFiles} 个,每个不超过 {Math.round(field.maxBytes / 1024 / 1024)} MB</Text>
|
|
30
|
+
</FileUpload.Dropzone>
|
|
31
|
+
</FileUpload.Root>
|
|
32
|
+
{(Array.isArray(value) ? value : []).map(item => <Flex key={item.ref} align="center" gap="10px" py="8px" borderBottom="1px solid var(--dsw-alias-border-l1)">
|
|
33
|
+
{hub.getFileUrl && !state.staleRefs.includes(item.ref) && <Box flexShrink={0} width="64px" height="48px" overflow="hidden" borderRadius="8px">{item.mimeType.startsWith('image/') ? <Box as="img" alt={item.name} src={hub.getFileUrl({ workspaceId, assetId: item.ref })} width="100%" height="100%" objectFit="contain" /> : item.mimeType.startsWith('video/') ? <Box as="video" aria-label={item.name} src={hub.getFileUrl({ workspaceId, assetId: item.ref })} controls preload="metadata" width="100%" height="100%" objectFit="contain" /> : null}</Box>}
|
|
34
|
+
<Box flex="1" minWidth="0"><Text fontSize="13px" overflowWrap="anywhere">{item.name}</Text><Text fontSize="12px" color={state.staleRefs.includes(item.ref) ? 'var(--dsw-alias-state-error-primary)' : 'var(--dsw-alias-label-secondary)'}>{state.staleRefs.includes(item.ref) ? '素材已失效,请重新选择' : `${(item.sizeBytes / 1024 / 1024).toFixed(1)} MB`}</Text></Box>
|
|
35
|
+
<Button {...secondary} disabled={disabled} onClick={() => editor.removeAttachment(field.id, item.ref)} aria-label={`移除${item.name}`}>移除</Button>
|
|
36
|
+
</Flex>)}
|
|
37
|
+
{state.uploads.filter(u => u.fieldId === field.id).map(upload => <Flex key={upload.id} align="center" gap="8px" py="8px"><Box flex="1" minWidth="0"><Text fontSize="13px" overflowWrap="anywhere">{upload.file.name}</Text><Text role={upload.error ? 'alert' : 'status'} fontSize="12px">{upload.error || `导入中 ${Math.round(upload.progress * 100)}%`}</Text></Box>{upload.error && <Button {...secondary} onClick={() => editor.upload(upload)}>重试</Button>}<Button {...secondary} onClick={() => editor.removeUpload(upload.id)}>移除</Button></Flex>)}
|
|
38
|
+
</Box>
|
|
39
|
+
return <Field.Root id={id} invalid={Boolean(error)} required={field.required} disabled={disabled} gap="8px" data-form-field={field.id}>
|
|
40
|
+
<Field.Label htmlFor={id} fontSize="14px" fontWeight="500">{field.label}<Field.RequiredIndicator /></Field.Label>
|
|
41
|
+
{field.description && <Field.HelperText fontSize="13px" color="var(--dsw-alias-label-secondary)">{field.description}</Field.HelperText>}
|
|
42
|
+
{input}<Field.ErrorText fontSize="13px" color="var(--dsw-alias-state-error-primary)">{error}</Field.ErrorText>
|
|
43
|
+
</Field.Root>
|
|
44
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import React, { useEffect, useMemo, useState, useSyncExternalStore } from 'react'
|
|
2
|
+
import { Box, Button, ChakraProvider, Flex, Heading, Text } from '@chakra-ui/react'
|
|
3
|
+
import deconstruct from '../../../../packages/form-contract/templates/video-deconstruct/definition.json'
|
|
4
|
+
import replication from '../../../../packages/form-contract/templates/structure-replication/definition.json'
|
|
5
|
+
import replacement from '../../../../packages/form-contract/templates/element-replacement/definition.json'
|
|
6
|
+
import marketingInsight from '../../../../packages/form-contract/templates/marketing-insight/definition.json'
|
|
7
|
+
import urlToVideo from '../../../../packages/form-contract/templates/url-to-video/definition.json'
|
|
8
|
+
import { validateDefinition } from '@omnimux/form-contract'
|
|
9
|
+
import { createEditor } from './model.js'
|
|
10
|
+
import { FormField } from './Fields.jsx'
|
|
11
|
+
import { formSystem, primary, secondary } from './theme.js'
|
|
12
|
+
|
|
13
|
+
export const templates = [marketingInsight, urlToVideo, deconstruct, replication, replacement]
|
|
14
|
+
export function checkedTemplates(raw = templates) {
|
|
15
|
+
const results = raw.map(validateDefinition)
|
|
16
|
+
return results.some(result => !result.ok) ? null : results.map(result => result.value)
|
|
17
|
+
}
|
|
18
|
+
function Example({ example }) {
|
|
19
|
+
return <Box as="figure" margin="0"><Box aspectRatio="16/9" width="100%" overflow="hidden" borderRadius="10px" bg="var(--dsw-alias-bg-layer-2)">{example.kind === 'video' ? <Box as="video" src={example.ref} controls preload="metadata" aria-label={example.title} width="100%" height="100%" objectFit="contain" /> : <Box as="img" src={example.ref} alt={example.title} width="100%" height="100%" objectFit="contain" />}</Box><Text as="figcaption" marginTop="10px" fontSize="13px" color="var(--dsw-alias-label-secondary)">{example.title}</Text></Box>
|
|
20
|
+
}
|
|
21
|
+
export function Editor(props) {
|
|
22
|
+
const checked = useMemo(() => validateDefinition(props.definition), [props.definition])
|
|
23
|
+
return checked.ok ? <ValidEditor {...props} definition={checked.value} /> : <Box className="omnimux-forms-error" padding="24px" role="alert">模板配置不可用,无法生成草稿。</Box>
|
|
24
|
+
}
|
|
25
|
+
function ValidEditor({ definition, workspace, hub, onBack }) {
|
|
26
|
+
const editor = useMemo(() => createEditor({ definition, workspaceId: workspace.id, hub }), [definition, workspace.id, hub])
|
|
27
|
+
const state = useSyncExternalStore(editor.subscribe, editor.getSnapshot, editor.getSnapshot)
|
|
28
|
+
const [confirmReset, setConfirmReset] = useState(false)
|
|
29
|
+
useEffect(() => { void editor.load(); return () => editor.dispose() }, [editor])
|
|
30
|
+
useEffect(() => {
|
|
31
|
+
if (!state.focusRevision || !state.errors.length) return
|
|
32
|
+
const field = state.errors.find(e => e.path[0] === 'values')?.path[1]
|
|
33
|
+
const root = document.querySelector(`[data-form-field="${field}"]`)
|
|
34
|
+
root?.querySelector('input:not([type="file"]):not([type="hidden"]):not([hidden]),textarea,button,[tabindex="0"]')?.focus()
|
|
35
|
+
}, [state.focusRevision])
|
|
36
|
+
return <Flex direction="column" height="100%" minHeight="0">
|
|
37
|
+
<Flex align="center" justify="space-between" gap="12px" padding="20px 24px" borderBottom="1px solid var(--dsw-alias-border-l1)"><Button {...secondary} disabled={state.busy} onClick={onBack}>全部模板</Button><Text fontSize="13px" color="var(--dsw-alias-label-secondary)">{workspace.title || '当前工作区'}</Text></Flex>
|
|
38
|
+
<Box overflowY="auto" flex="1" minHeight="0" padding={{ base: '20px 16px', md: '28px' }}>
|
|
39
|
+
<Box maxWidth="1120px" marginInline="auto"><Heading fontFamily="inherit" fontSize="20px" fontWeight="600" margin="0 0 8px">{definition.title}</Heading><Text fontSize="14px" color="var(--dsw-alias-label-secondary)" margin="0 0 28px">{definition.description}</Text>
|
|
40
|
+
<Box display="grid" gridTemplateColumns={{ base: 'minmax(0,1fr)', lg: 'minmax(280px, 0.85fr) minmax(0,1fr)' }} gap={{ base: '24px', lg: '40px' }}>
|
|
41
|
+
<Box><Box position={{ base: 'static', lg: 'sticky' }} top="0"><Text fontSize="13px" fontWeight="500" marginBottom="12px">案例参考</Text><Flex direction="column" gap="20px">{definition.examples.map(example => <Example key={example.ref} example={example} />)}</Flex><Text fontSize="12px" color="var(--dsw-alias-label-secondary)" marginTop="12px">案例仅供参考。请在右侧选择自己的素材。</Text></Box></Box>
|
|
42
|
+
<Flex direction="column" gap="24px" minWidth="0">{state.loading ? <Text className="omnimux-forms-loading" role="status">正在恢复填写内容…</Text> : state.invalid || state.restoreInvalid ? <Text className="omnimux-forms-error" role="alert">{state.notice}</Text> : definition.fields.map(field => <FormField key={field.id} field={field} value={state.values[field.id]} errors={state.errors.filter(e => e.path[1] === field.id)} disabled={state.busy} editor={editor} state={state} hub={hub} workspaceId={workspace.id} />)}</Flex>
|
|
43
|
+
</Box>
|
|
44
|
+
</Box>
|
|
45
|
+
</Box>
|
|
46
|
+
<Box flexShrink="0" borderTop="1px solid var(--dsw-alias-border-l2)" bg="var(--dsw-alias-bg-base)" padding="12px 24px">
|
|
47
|
+
{state.notice && <Text role={state.success ? 'status' : 'alert'} fontSize="13px" marginBottom="8px">{state.notice}</Text>}
|
|
48
|
+
<Flex align="center" justify="space-between" gap="12px" wrap="wrap"><Flex align="center" gap="8px"><Button {...secondary} disabled={state.loading || state.busy || state.invalid} onClick={() => setConfirmReset(true)}>重置表单</Button><Text role="status" fontSize="12px" color="var(--dsw-alias-label-secondary)">{state.saveStatus}</Text></Flex><Button {...primary} disabled={state.loading || state.busy || state.invalid || state.restoreInvalid} onClick={() => editor.submit()}>{state.busy ? '正在生成草稿…' : '生成会话草稿'}</Button></Flex>
|
|
49
|
+
{confirmReset && <Flex role="alertdialog" aria-label="重置表单" align="center" gap="12px" paddingTop="12px" wrap="wrap"><Text fontSize="13px">重置此模板的填写内容?已导入的源文件不会删除。</Text><Button {...secondary} onClick={() => setConfirmReset(false)}>取消</Button><Button {...secondary} onClick={() => { setConfirmReset(false); void editor.reset() }}>确认重置</Button></Flex>}
|
|
50
|
+
</Box>
|
|
51
|
+
</Flex>
|
|
52
|
+
}
|
|
53
|
+
export function FormsPage({ definitions = templates, store, visible = true } = {}) {
|
|
54
|
+
useEffect(() => {
|
|
55
|
+
const api = window.__omnimuxWorkbench
|
|
56
|
+
if (!store || typeof api?.attachStore !== 'function') return undefined
|
|
57
|
+
api.attachStore(store)
|
|
58
|
+
return () => api.detachStore?.(store)
|
|
59
|
+
}, [store])
|
|
60
|
+
const available = useMemo(() => checkedTemplates(definitions), [definitions])
|
|
61
|
+
const [hub, setHub] = useState(() => window.__omnimuxForms)
|
|
62
|
+
useEffect(() => { const ready = () => setHub(window.__omnimuxForms); window.addEventListener('omnimux-forms-ready', ready); return () => window.removeEventListener('omnimux-forms-ready', ready) }, [])
|
|
63
|
+
const [workspace, setWorkspace] = useState(() => hub?.getWorkspace?.() ?? null)
|
|
64
|
+
const [selected, setSelected] = useState(null)
|
|
65
|
+
useEffect(() => { setWorkspace(hub?.getWorkspace?.() ?? null); return hub?.subscribeWorkspace?.(() => setWorkspace(hub.getWorkspace())) }, [hub])
|
|
66
|
+
return <ChakraProvider value={formSystem}><Box className="omnimux-forms-body" aria-hidden={visible ? undefined : true} display={visible ? 'block' : 'none'} height="100%" minHeight="0" width="100%" color="var(--dsw-alias-label-primary)" bg="var(--dsw-alias-bg-base)" fontFamily="inherit" fontSize="14px">
|
|
67
|
+
{!available ? <Box className="omnimux-forms-error" padding="24px" role="alert">模板配置不可用,无法打开任务表单。</Box> : !hub ? <Box padding="24px" role="alert">会话服务尚未就绪,请重新打开任务表单。</Box> : !workspace ? <Box padding="24px" role="status">请先打开目标工作区中的会话,再进入任务表单。</Box> : selected ? <Editor key={`${workspace.id}:${selected.id}`} definition={selected} workspace={workspace} hub={hub} onBack={() => setSelected(null)} /> : <Box overflowY="auto" height="100%" padding={{ base: '24px 16px', md: '32px' }}><Box maxWidth="1080px" marginInline="auto"><Heading fontFamily="inherit" fontSize="20px" fontWeight="600" margin="0 0 8px">任务表单</Heading><Text color="var(--dsw-alias-label-secondary)" margin="0 0 28px">从参考视频出发,整理拆解与复刻要求。</Text><Flex direction="column" gap="24px">{available.map((template, index) => <Box key={template.id} display="grid" gridTemplateColumns={{ base: 'minmax(0,1fr)', md: '240px minmax(0,1fr)' }} gap="24px" paddingBottom="24px" borderBottom="1px solid var(--dsw-alias-border-l2)"><Example example={template.examples[0]} /><Flex direction="column" align="start" justify="center" gap="12px"><Text fontSize="12px" color="var(--dsw-alias-label-secondary)">{String(index + 1).padStart(2, '0')}</Text><Heading fontFamily="inherit" fontSize="16px" fontWeight="600" margin="0">{template.title}</Heading><Text fontSize="14px" color="var(--dsw-alias-label-secondary)" margin="0">{template.description}</Text><Button {...secondary} onClick={() => setSelected(template)}>填写表单</Button></Flex></Box>)}</Flex></Box></Box>}
|
|
68
|
+
</Box></ChakraProvider>
|
|
69
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { test } from 'node:test'
|
|
2
|
+
import { JSDOM } from 'jsdom'
|
|
3
|
+
import assert from 'node:assert/strict'
|
|
4
|
+
import { build } from 'esbuild'
|
|
5
|
+
import { createRequire } from 'node:module'
|
|
6
|
+
import { mkdir, readFile, mkdtemp, rm } from 'node:fs/promises'
|
|
7
|
+
import { fileURLToPath } from 'node:url'
|
|
8
|
+
import { tmpdir } from 'node:os'
|
|
9
|
+
import { join } from 'node:path'
|
|
10
|
+
import { copyExamples } from '../../scripts/copy-examples.mjs'
|
|
11
|
+
const root=fileURLToPath(new URL('../../',import.meta.url)), require=createRequire(import.meta.url)
|
|
12
|
+
const directory=`${root}node_modules/.cache/forms-test`
|
|
13
|
+
await mkdir(directory,{recursive:true})
|
|
14
|
+
const outfile=`${directory}/render.cjs`
|
|
15
|
+
await build({stdin:{contents:`import React from 'react';import {renderToStaticMarkup} from 'react-dom/server';import {createRoot} from 'react-dom/client';import {flushSync} from 'react-dom';import {ChakraProvider} from '@chakra-ui/react';import {FormField} from './src/client/Fields.jsx';import {formSystem} from './src/client/theme.js';import {FormsPage} from './src/client/FormsPage.jsx';export function renderPage(definitions){globalThis.window={};try{return renderToStaticMarkup(<FormsPage definitions={definitions}/>)}finally{delete globalThis.window}};export function render(field){return renderToStaticMarkup(<ChakraProvider value={formSystem}><FormField field={field} value={field.default} errors={[]} state={{staleRefs:[],uploads:[]}} editor={{set(){}}} hub={{}} workspaceId="w"/></ChakraProvider>)};export function mountPage(el,props){const root=createRoot(el);flushSync(()=>root.render(<FormsPage {...props}/>));return {update(next){flushSync(()=>root.render(<FormsPage {...next}/>))},unmount(){flushSync(()=>root.unmount())}}};export {formSystem};`,resolveDir:root,loader:'jsx'},bundle:true,alias:{'@omnimux/form-contract':`${root}../../packages/form-contract/src/index.ts`},format:'cjs',platform:'node',outfile,define:{'process.env.NODE_ENV':'"production"'}})
|
|
16
|
+
const {render,renderPage,formSystem,mountPage}=require(outfile)
|
|
17
|
+
test('all seven native Chakra fields render labels, controls and escaped text',()=>{
|
|
18
|
+
const basic={id:'field',label:'<script>bad()</script>',required:true}
|
|
19
|
+
const fields=[{type:'text'},{type:'textarea'},{type:'file',accept:['video/*'],maxFiles:1,maxBytes:100},{type:'number',min:1,max:10,step:1,default:2},{type:'slider',min:1,max:10,step:1,default:2},{type:'select',options:[{value:'a',label:'Alpha'}]},{type:'aspect-ratio',options:[{value:'16:9',label:'Wide'}]}]
|
|
20
|
+
for(const field of fields){const html=render({...basic,...field});assert.ok(html.includes('<script>bad()</script>'));assert.ok(!html.includes('<script>bad()'));assert.ok(html.includes('data-form-field="field"'))}
|
|
21
|
+
})
|
|
22
|
+
test('theme emits no document reset or html/body base styling',()=>{
|
|
23
|
+
assert.equal(formSystem._config.preflight,false);assert.equal(formSystem._config.cssVarsRoot,'.omnimux-forms-body');assert.deepEqual(formSystem._config.globalCss,{})
|
|
24
|
+
const globals=JSON.stringify(formSystem._global)
|
|
25
|
+
assert.ok(globals.includes('.omnimux-forms-body'));assert.ok(!globals.includes(':root'));assert.ok(!globals.includes('html'))
|
|
26
|
+
})
|
|
27
|
+
test('browser page embeds the real templates and contract without a runtime source dependency',async()=>{
|
|
28
|
+
const result=await build({entryPoints:[`${root}src/client/FormsPage.jsx`],bundle:true,write:false,format:'cjs',platform:'browser',jsx:'automatic',alias:{'@omnimux/form-contract':`${root}../../packages/form-contract/src/index.ts`},external:['react','react/jsx-runtime','react-dom'],define:{'process.env.NODE_ENV':'"production"'}})
|
|
29
|
+
const client=result.outputFiles[0].text
|
|
30
|
+
for(const id of ['marketing-insight','url-to-video','video-deconstruct','structure-replication','element-replacement']) assert.ok(client.includes(id))
|
|
31
|
+
assert.ok(!client.includes('require("@omnimux/form-contract")'))
|
|
32
|
+
})
|
|
33
|
+
test('packaging copies real example bytes and fails if required sources are missing',async t=>{
|
|
34
|
+
const directory=await mkdtemp(join(tmpdir(),'forms-examples-'))
|
|
35
|
+
t.after(()=>rm(directory,{recursive:true,force:true}))
|
|
36
|
+
const source=`${root}../../packages/form-contract/examples`
|
|
37
|
+
await copyExamples(source,`${directory}/assets/examples`)
|
|
38
|
+
assert.deepEqual(await readFile(`${directory}/assets/examples/replication-demo.mp4`),await readFile(`${source}/replication-demo.mp4`))
|
|
39
|
+
await assert.rejects(copyExamples(`${directory}/missing`,`${directory}/other`),{code:'ENOENT'})
|
|
40
|
+
})
|
|
41
|
+
|
|
42
|
+
test('malformed bundled definition fails closed before reading examples or fields',()=>{const html=renderPage([{id:'broken'}]);assert.ok(html.includes('模板配置不可用'));assert.ok(!html.includes('填写表单'));assert.ok(!html.includes('data-form-field'))})
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
test('page attaches its real workbench store, balances replacement and unmount, and hides inactive content',()=>{
|
|
46
|
+
const dom=new JSDOM('<div id="root"></div>',{url:'http://localhost/'})
|
|
47
|
+
const saved={window:globalThis.window,document:globalThis.document}
|
|
48
|
+
globalThis.window=dom.window;globalThis.document=dom.window.document
|
|
49
|
+
const calls=[],first={},second={}
|
|
50
|
+
window.__omnimuxWorkbench={attachStore:s=>calls.push(['attach',s]),detachStore:s=>calls.push(['detach',s])}
|
|
51
|
+
let mounted
|
|
52
|
+
try {
|
|
53
|
+
mounted=mountPage(document.getElementById('root'),{definitions:[{id:'broken'}],store:first})
|
|
54
|
+
assert.deepEqual(calls,[['attach',first]])
|
|
55
|
+
mounted.update({definitions:[{id:'broken'}],store:second,visible:false})
|
|
56
|
+
assert.deepEqual(calls,[['attach',first],['detach',first],['attach',second]])
|
|
57
|
+
const body=document.querySelector('.omnimux-forms-body')
|
|
58
|
+
assert.equal(body.getAttribute('aria-hidden'),'true')
|
|
59
|
+
mounted.unmount();mounted=null
|
|
60
|
+
assert.deepEqual(calls.at(-1),['detach',second])
|
|
61
|
+
} finally { mounted?.unmount();globalThis.window=saved.window;globalThis.document=saved.document;dom.window.close() }
|
|
62
|
+
})
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { createElement } from 'react'
|
|
2
|
+
import { FormsPage } from './FormsPage.jsx'
|
|
3
|
+
export const name = 'omnimux-forms'
|
|
4
|
+
export const inject = ['slots']
|
|
5
|
+
export const FORMS_TAB_ID = 'omnimux-forms:tasks'
|
|
6
|
+
export function apply(ctx) {
|
|
7
|
+
// Left sidebar row under 新会话 is intentionally not mounted (temporarily hidden from rail).
|
|
8
|
+
// `sidebar-entry.js` remains intact for a future re-enable.
|
|
9
|
+
ctx.inject(['betterSidebar'], inner => {
|
|
10
|
+
const sidebar = inner.betterSidebar ?? inner.get?.('betterSidebar')
|
|
11
|
+
ctx.effect(() => sidebar.registerTab({
|
|
12
|
+
id: FORMS_TAB_ID, title: () => '任务表单', order: 19, hidden: false, single: true,
|
|
13
|
+
icon: size => createElement('svg', { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 1.5, 'aria-hidden': true }, createElement('rect', { x: 5, y: 3, width: 14, height: 18, rx: 2 }), createElement('path', { d: 'M8 8h8M8 12h8M8 16h5' })),
|
|
14
|
+
component: FormsPage,
|
|
15
|
+
}), 'omnimux-forms: tasks tab')
|
|
16
|
+
})
|
|
17
|
+
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
import { validateDefinition, validateValues, buildDraft } from '@omnimux/form-contract'
|
|
2
|
+
|
|
3
|
+
export function attachmentValue(file) {
|
|
4
|
+
return { ref: file.assetId, name: file.name, mimeType: file.mimeType, sizeBytes: file.sizeBytes }
|
|
5
|
+
}
|
|
6
|
+
export function defaultValues(definition) {
|
|
7
|
+
return Object.fromEntries(definition.fields.filter(f => 'default' in f).map(f => [f.id, f.default]))
|
|
8
|
+
}
|
|
9
|
+
export async function draftRequest(key, body) {
|
|
10
|
+
const response = await fetch(`/api/omnimux/forms/draft?${new URLSearchParams(key)}`, {
|
|
11
|
+
method: body ? 'PUT' : 'GET', headers: body ? { 'Content-Type': 'application/json' } : undefined,
|
|
12
|
+
body: body ? JSON.stringify({ ...key, ...body }) : undefined,
|
|
13
|
+
})
|
|
14
|
+
const data = await response.json()
|
|
15
|
+
if (!response.ok) { const error = new Error(data.error || '草稿保存失败'); error.status = response.status; throw error }
|
|
16
|
+
return data
|
|
17
|
+
}
|
|
18
|
+
/** One mounted workspace/template editor owns its async results; completed old requests cannot affect a new editor. */
|
|
19
|
+
export function createEditor({ definition, workspaceId, hub, request = draftRequest, uuid = () => crypto.randomUUID() }) {
|
|
20
|
+
const checked = validateDefinition(definition)
|
|
21
|
+
const listeners = new Set()
|
|
22
|
+
const key = { workspaceId, templateId: definition.id, templateVersion: definition.templateVersion }
|
|
23
|
+
let state = { loading: true, values: checked.ok ? defaultValues(checked.value) : {}, errors: [], notice: '', saveStatus: '', uploads: [], busy: false, staleRefs: [], focusRevision: 0 }
|
|
24
|
+
let disposed = false, revision = 0, saveTimer, saves = Promise.resolve(), saveFailure = null, dirty = false, requestKey = '', requestId = '', epoch = 0
|
|
25
|
+
const emit = patch => { if (disposed) return; state = { ...state, ...patch }; listeners.forEach(fn => fn()) }
|
|
26
|
+
const validate = values => { const result = validateValues(definition, values); return result.ok ? [] : result.errors }
|
|
27
|
+
async function save() {
|
|
28
|
+
if (!dirty || disposed || state.loading || saveFailure?.status === 409) return saves
|
|
29
|
+
dirty = false
|
|
30
|
+
const values = structuredClone(state.values)
|
|
31
|
+
emit({ saveStatus: '保存中' })
|
|
32
|
+
saves = saves.catch(() => {}).then(async () => {
|
|
33
|
+
if (saveFailure?.status === 409) throw saveFailure
|
|
34
|
+
const result = await request(key, { values, expectedRevision: revision })
|
|
35
|
+
revision = result.draft.revision; saveFailure = null
|
|
36
|
+
emit({ saveStatus: dirty ? '待保存' : '已保存' })
|
|
37
|
+
}).catch(error => { saveFailure = error; dirty = true; emit({ saveStatus: '保存失败', notice: error.message }) })
|
|
38
|
+
return saves
|
|
39
|
+
}
|
|
40
|
+
async function resolveValues(values) {
|
|
41
|
+
const refs = definition.fields.filter(f => f.type === 'file').flatMap(f => Array.isArray(values[f.id]) ? values[f.id].map(a => a.ref) : [])
|
|
42
|
+
if (!refs.length) return { values, staleRefs: [] }
|
|
43
|
+
// Resolve separately so one missing attachment does not hide other valid previews.
|
|
44
|
+
const results = await Promise.all(refs.map(async ref => {
|
|
45
|
+
try { const [file] = await hub.resolveFiles({ workspaceId, assetIds: [ref] }); if (!file) throw new Error('Missing attachment'); return [ref, attachmentValue(file)] }
|
|
46
|
+
catch { return [ref, null] }
|
|
47
|
+
}))
|
|
48
|
+
const resolved = new Map(results), next = { ...values }
|
|
49
|
+
for (const field of definition.fields.filter(f => f.type === 'file')) {
|
|
50
|
+
if (Array.isArray(values[field.id])) next[field.id] = values[field.id].map(item => resolved.get(item.ref) ?? item)
|
|
51
|
+
}
|
|
52
|
+
return { values: next, staleRefs: results.filter(([, value]) => !value).map(([ref]) => ref) }
|
|
53
|
+
}
|
|
54
|
+
const api = {
|
|
55
|
+
getSnapshot: () => state,
|
|
56
|
+
subscribe(fn) { listeners.add(fn); return () => listeners.delete(fn) },
|
|
57
|
+
async load() {
|
|
58
|
+
if (!checked.ok) return emit({ loading: false, errors: checked.errors, notice: '模板配置不可用,无法生成草稿。', invalid: true })
|
|
59
|
+
try {
|
|
60
|
+
const saved = await request(key)
|
|
61
|
+
if (disposed) return
|
|
62
|
+
revision = saved.draft?.revision ?? 0
|
|
63
|
+
const values = saved.draft?.values ?? defaultValues(checked.value)
|
|
64
|
+
const restored = validateValues(definition, values)
|
|
65
|
+
if (!restored.ok && restored.errors.some(error => ['INVALID_VALUES', 'UNKNOWN_FIELD', 'INVALID_ATTACHMENT'].includes(error.code) || (error.code === 'INVALID_VALUE' && values[error.path[1]] !== ''))) {
|
|
66
|
+
return emit({ loading: false, restoreInvalid: true, notice: '保存的草稿格式不符合当前模板,已保留原稿。请重置此表单后重新填写。' })
|
|
67
|
+
}
|
|
68
|
+
const resolved = await resolveValues(values)
|
|
69
|
+
emit({ loading: false, ...resolved, errors: saved.draft ? validate(resolved.values) : [], saveStatus: saved.draft ? '已恢复草稿' : '', notice: [saved.otherVersions.length ? '保留了旧版本草稿。当前模板使用独立填写内容。' : '', saved.draft && validate(resolved.values).length ? '恢复的草稿需要检查,请修正标出的内容或重置表单。' : ''].filter(Boolean).join(' ') })
|
|
70
|
+
} catch (error) { emit({ loading: false, invalid: true, notice: `无法恢复草稿:${error.message}。请重新打开模板。` }) }
|
|
71
|
+
},
|
|
72
|
+
set(fieldId, value) {
|
|
73
|
+
if (state.loading || state.busy || state.invalid || state.restoreInvalid) return
|
|
74
|
+
const values = { ...state.values }
|
|
75
|
+
if (value === undefined) delete values[fieldId]; else values[fieldId] = value
|
|
76
|
+
emit({ values, errors: state.errors.length ? validate(values) : [], saveStatus: '待保存', success: null })
|
|
77
|
+
dirty = true; clearTimeout(saveTimer); saveTimer = setTimeout(save, 350)
|
|
78
|
+
},
|
|
79
|
+
async importFiles(field, files) {
|
|
80
|
+
if (state.loading || state.busy || state.invalid || state.restoreInvalid) return
|
|
81
|
+
const existing = Array.isArray(state.values[field.id]) ? state.values[field.id] : []
|
|
82
|
+
const outstanding = state.uploads.filter(u => u.fieldId === field.id).length
|
|
83
|
+
if (existing.length + outstanding + files.length > field.maxFiles) return emit({ notice: `${field.label}最多选择 ${field.maxFiles} 个文件。` })
|
|
84
|
+
for (const file of files) {
|
|
85
|
+
const upload = { id: uuid(), fieldId: field.id, file, progress: 0, error: null }
|
|
86
|
+
emit({ uploads: [...state.uploads, upload] })
|
|
87
|
+
void api.upload(upload)
|
|
88
|
+
}
|
|
89
|
+
},
|
|
90
|
+
async upload(upload) {
|
|
91
|
+
const currentEpoch = epoch
|
|
92
|
+
const field = definition.fields.find(f => f.id === upload.fieldId)
|
|
93
|
+
emit({ uploads: state.uploads.map(u => u.id === upload.id ? { ...u, error: null, progress: 0 } : u) })
|
|
94
|
+
try {
|
|
95
|
+
if (upload.file.size > field.maxBytes) throw new Error('文件超过大小限制')
|
|
96
|
+
const imported = await hub.importFile(upload.file, { workspaceId, onProgress(progress) {
|
|
97
|
+
if (currentEpoch === epoch) emit({ uploads: state.uploads.map(u => u.id === upload.id ? { ...u, progress } : u) })
|
|
98
|
+
} })
|
|
99
|
+
if (disposed || currentEpoch !== epoch || !state.uploads.some(u => u.id === upload.id)) return
|
|
100
|
+
const value = attachmentValue(imported)
|
|
101
|
+
const prior = Array.isArray(state.values[field.id]) ? state.values[field.id] : []
|
|
102
|
+
api.set(field.id, [...prior, value])
|
|
103
|
+
emit({ uploads: state.uploads.filter(u => u.id !== upload.id) })
|
|
104
|
+
} catch (error) { if (currentEpoch === epoch) emit({ uploads: state.uploads.map(u => u.id === upload.id ? { ...u, error: error.message } : u) }) }
|
|
105
|
+
},
|
|
106
|
+
rejectFiles() { emit({ notice: '文件类型、数量或大小不符合要求,请检查后重新选择。' }) },
|
|
107
|
+
removeUpload(id) { emit({ uploads: state.uploads.filter(u => u.id !== id) }) },
|
|
108
|
+
removeAttachment(fieldId, ref) { api.set(fieldId, state.values[fieldId].filter(a => a.ref !== ref)); emit({ staleRefs: state.staleRefs.filter(r => r !== ref) }) },
|
|
109
|
+
async reset() {
|
|
110
|
+
if (state.busy) return
|
|
111
|
+
epoch++; clearTimeout(saveTimer)
|
|
112
|
+
emit({ values: defaultValues(definition), errors: [], uploads: [], staleRefs: [], notice: '', success: null, restoreInvalid: false })
|
|
113
|
+
dirty = true; await save()
|
|
114
|
+
},
|
|
115
|
+
async submit() {
|
|
116
|
+
if (state.busy || state.loading || state.invalid || state.restoreInvalid) return
|
|
117
|
+
if (state.uploads.length) return emit({ notice: '请完成上传,或移除失败的文件后再生成草稿。' })
|
|
118
|
+
const errors = validate(state.values)
|
|
119
|
+
if (errors.length) return emit({ errors, focusRevision: state.focusRevision + 1, notice: '请检查标出的字段。' })
|
|
120
|
+
emit({ busy: true, errors: [], notice: '', success: null })
|
|
121
|
+
try {
|
|
122
|
+
await save()
|
|
123
|
+
if (saveFailure) throw saveFailure
|
|
124
|
+
const resolved = await resolveValues(state.values)
|
|
125
|
+
if (disposed) return
|
|
126
|
+
emit(resolved)
|
|
127
|
+
if (resolved.staleRefs.length) throw new Error('部分素材已失效,请移除后重新选择。')
|
|
128
|
+
const draft = buildDraft(definition, resolved.values)
|
|
129
|
+
if (!draft.ok) { emit({ errors: draft.errors }); throw new Error('素材信息已变化,请检查字段。') }
|
|
130
|
+
const fingerprint = JSON.stringify([workspaceId, draft.value.prompt, draft.value.attachments])
|
|
131
|
+
if (requestKey !== fingerprint) { requestKey = fingerprint; requestId = uuid() }
|
|
132
|
+
const result = await hub.prepareDraft({ requestId, workspaceId, prompt: draft.value.prompt, assetIds: draft.value.attachments.map(a => a.ref) })
|
|
133
|
+
if (!result.ok) throw new Error(result.message || result.error || '会话草稿交接失败')
|
|
134
|
+
emit({ success: result.sessionId, notice: '已生成会话草稿。可在输入框编辑并确认发送。' })
|
|
135
|
+
} catch (error) { emit({ notice: error.message }) }
|
|
136
|
+
finally { emit({ busy: false }) }
|
|
137
|
+
},
|
|
138
|
+
flush: save,
|
|
139
|
+
dispose() { clearTimeout(saveTimer); void save(); disposed = true; epoch++; listeners.clear() },
|
|
140
|
+
}
|
|
141
|
+
return api
|
|
142
|
+
}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { test } from 'node:test'
|
|
2
|
+
import assert from 'node:assert/strict'
|
|
3
|
+
import { build } from 'esbuild'
|
|
4
|
+
import { fileURLToPath } from 'node:url'
|
|
5
|
+
const root=fileURLToPath(new URL('../../',import.meta.url))
|
|
6
|
+
const compiled=await build({entryPoints:[`${root}src/client/model.js`],bundle:true,write:false,platform:'node',format:'esm',alias:{'@omnimux/form-contract':`${root}../../packages/form-contract/src/index.ts`}})
|
|
7
|
+
const {createEditor}=await import(`data:text/javascript;base64,${Buffer.from(compiled.outputFiles[0].text).toString('base64')}`)
|
|
8
|
+
const definition={protocolVersion:1,id:'test',templateVersion:'1.0.0',title:'test',description:'test',examples:[{ref:'x',title:'x',kind:'video'}],fields:[{id:'name',type:'text',label:'name',required:true},{id:'file',type:'file',label:'file',required:true,accept:['video/*'],maxFiles:1,maxBytes:100}],prompt:'Do {{name}}',attachments:['file']}
|
|
9
|
+
const file={assetId:'id',name:'a.mp4',mimeType:'video/mp4',sizeBytes:1}
|
|
10
|
+
const values={name:'test',file:[{ref:'id',name:'a.mp4',mimeType:'video/mp4',sizeBytes:1}]}
|
|
11
|
+
function setup(opts={}) { let revision=0,calls=[]; const hub={resolveFiles:async()=>[file],importFile:async()=>file,prepareDraft:async a=>{calls.push(a);return {ok:true,sessionId:'s'}},...opts.hub}; const request=opts.request??(async(k,b)=>b?{draft:{revision:++revision}}:{draft:{values,revision:0},otherVersions:[]});const editor=createEditor({definition,workspaceId:'w',hub,request,uuid:()=>`r${Math.random()}`});return {editor,calls,hub} }
|
|
12
|
+
test('restores and revalidates refs; blocks stale files before creating a session',async()=>{const {editor,calls}=setup({hub:{resolveFiles:async()=>{throw Error('gone')}}});await editor.load();assert.deepEqual(editor.getSnapshot().staleRefs,['id']);await editor.submit();assert.equal(calls.length,0);editor.dispose()})
|
|
13
|
+
test('double click shares in-flight submission; retry preserves request id after timeout',async()=>{let release,attempt=0;const {editor,calls,hub}=setup();hub.prepareDraft=async a=>{calls.push(a);attempt++;if(attempt===1){await new Promise(r=>release=r);return {ok:false,error:'timeout'}}return {ok:true,sessionId:'s'}};await editor.load();const first=editor.submit();await new Promise(r=>setTimeout(r,0));await editor.submit();assert.equal(calls.length,1);release();await first;await editor.submit();assert.equal(calls[0].requestId,calls[1].requestId);assert.equal(editor.getSnapshot().success,'s');editor.dispose()})
|
|
14
|
+
test('late import after removal or disposal never repopulates values',async()=>{let release;const {editor}=setup({hub:{importFile:()=>new Promise(r=>release=r)}});await editor.load();editor.removeAttachment('file','id');await editor.importFiles(definition.fields[1],[{name:'x',size:1}]);const upload=editor.getSnapshot().uploads[0];editor.removeUpload(upload.id);release(file);await new Promise(r=>setTimeout(r,0));assert.deepEqual(editor.getSnapshot().values.file,[]);editor.dispose()})
|
|
15
|
+
test('save failures retain edits and prevent session creation',async()=>{const {editor,calls}=setup({request:async(k,b)=>{if(b)throw Error('disk unavailable');return {draft:{values,revision:0},otherVersions:[]}}});await editor.load();editor.set('name','changed');await editor.submit();assert.equal(editor.getSnapshot().values.name,'changed');assert.equal(calls.length,0);assert.match(editor.getSnapshot().notice,/disk/);editor.dispose()})
|
|
16
|
+
test('corrupt restoration fails closed and cannot overwrite original',async()=>{const {editor,calls}=setup({request:async()=>{throw Error('corrupt')}});await editor.load();editor.set('name','lost');await editor.submit();assert.equal(editor.getSnapshot().invalid,true);assert.equal(calls.length,0);editor.dispose()})
|
|
17
|
+
test('changed prompt creates fresh id and reset retains template defaults',async()=>{const {editor,calls}=setup();await editor.load();await editor.submit();editor.set('name','next');await editor.submit();assert.notEqual(calls[0].requestId,calls[1].requestId);await editor.reset();assert.deepEqual(editor.getSnapshot().values,{});editor.dispose()})
|
|
18
|
+
|
|
19
|
+
test('malformed restored field data stays preserved until explicit reset',async()=>{let writes=0;const {editor}=setup({request:async(k,b)=>{if(b){writes++;return {draft:{revision:1}}}return {draft:{revision:0,values:{name:{unexpected:true},file:[]}},otherVersions:[]}}});await editor.load();assert.equal(editor.getSnapshot().restoreInvalid,true);editor.set('name','replacement');await editor.submit();assert.equal(writes,0);await editor.reset();assert.equal(writes,1);assert.equal(editor.getSnapshot().restoreInvalid,false);editor.dispose()})
|
|
20
|
+
|
|
21
|
+
test('intentionally cleared numeric field remains editable after restoration',async()=>{const numeric={...definition,fields:[{id:'count',label:'Count',type:'number',required:true,min:1,max:5,step:1,default:1}],prompt:'Count {{count}}',attachments:[]};const editor=createEditor({definition:numeric,workspaceId:'w',hub:{resolveFiles:async()=>[]},request:async()=>({draft:{values:{count:''},revision:1},otherVersions:[]})});await editor.load();assert.equal(editor.getSnapshot().restoreInvalid,undefined);assert.equal(editor.getSnapshot().values.count,'');assert.ok(editor.getSnapshot().errors.length);editor.set('count',2);assert.equal(editor.getSnapshot().values.count,2);editor.dispose()})
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 任务表单 row under 新会话, placed by the single sidebar coordinator.
|
|
3
|
+
* Consumes standardized createSidebarEntry from dsh-ui-kit with idempotent activation.
|
|
4
|
+
*
|
|
5
|
+
* Currently unused: `client/index.js` does not call `mountSidebarEntry`
|
|
6
|
+
* (temporarily hidden from left sidebar rail). Kept intact so re-enabling
|
|
7
|
+
* the sidebar entry is a single line change in `index.js`.
|
|
8
|
+
*/
|
|
9
|
+
import { createSidebarEntry } from 'dsh-ui-kit'
|
|
10
|
+
|
|
11
|
+
export const ENTRY_SELECTOR = '[data-omnimux-forms-entry]'
|
|
12
|
+
export const FORMS_TAB_ID = 'omnimux-forms:tasks'
|
|
13
|
+
|
|
14
|
+
const ICON = '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="14" height="14" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true"><rect x="5" y="3" width="14" height="18" rx="2"/><path d="M8 8h8M8 12h8M8 16h5"/></svg>'
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
function resolveWorkbenchTitle(t) {
|
|
19
|
+
try {
|
|
20
|
+
const val = typeof t === 'function' ? t('nav') : undefined
|
|
21
|
+
if (val && val !== 'nav') return val
|
|
22
|
+
} catch {}
|
|
23
|
+
return '任务表单'
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function createWorkbenchStageStore(t, tabId) {
|
|
27
|
+
let store = null
|
|
28
|
+
const ensure = () => {
|
|
29
|
+
if (store) return store
|
|
30
|
+
const api = typeof window !== 'undefined' ? window.__omnimuxWorkbench : undefined
|
|
31
|
+
if (!api || typeof api.createSidebarStore !== 'function') return null
|
|
32
|
+
store = api.createSidebarStore({
|
|
33
|
+
tabId,
|
|
34
|
+
title: () => resolveWorkbenchTitle(t),
|
|
35
|
+
})
|
|
36
|
+
return store
|
|
37
|
+
}
|
|
38
|
+
return {
|
|
39
|
+
getSnapshot() {
|
|
40
|
+
return Boolean(ensure()?.getSnapshot?.())
|
|
41
|
+
},
|
|
42
|
+
subscribe(listener) {
|
|
43
|
+
if (typeof listener !== 'function') return () => {}
|
|
44
|
+
const ready = ensure()
|
|
45
|
+
if (ready && typeof ready.subscribe === 'function') return ready.subscribe(listener)
|
|
46
|
+
let unsub = () => {}
|
|
47
|
+
const started = Date.now()
|
|
48
|
+
const timer = setInterval(() => {
|
|
49
|
+
const next = ensure()
|
|
50
|
+
if (next && typeof next.subscribe === 'function') {
|
|
51
|
+
clearInterval(timer)
|
|
52
|
+
unsub = next.subscribe(listener)
|
|
53
|
+
listener()
|
|
54
|
+
return
|
|
55
|
+
}
|
|
56
|
+
if (Date.now() - started > 8000) clearInterval(timer)
|
|
57
|
+
}, 50)
|
|
58
|
+
return () => {
|
|
59
|
+
clearInterval(timer)
|
|
60
|
+
unsub()
|
|
61
|
+
}
|
|
62
|
+
},
|
|
63
|
+
open() {
|
|
64
|
+
const s = ensure()
|
|
65
|
+
if (!s) return
|
|
66
|
+
s.open()
|
|
67
|
+
},
|
|
68
|
+
close() {
|
|
69
|
+
ensure()?.close?.()
|
|
70
|
+
},
|
|
71
|
+
set(next) {
|
|
72
|
+
if (next) this.open()
|
|
73
|
+
else this.close()
|
|
74
|
+
},
|
|
75
|
+
readBox() {
|
|
76
|
+
return ensure()?.readBox?.() || { top: 0, left: 0, width: 0, height: 0 }
|
|
77
|
+
},
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
export function mountSidebarEntry(_stage, t, locale) {
|
|
83
|
+
return createSidebarEntry({
|
|
84
|
+
id: 'omnimux-forms',
|
|
85
|
+
rank: 11,
|
|
86
|
+
label: () => t('nav'),
|
|
87
|
+
iconSvg: ICON,
|
|
88
|
+
stageStore: createWorkbenchStageStore(t, FORMS_TAB_ID),
|
|
89
|
+
locale,
|
|
90
|
+
access: 'offline',
|
|
91
|
+
customClassName: 'omnimux-forms-entry',
|
|
92
|
+
datasetKey: 'data-omnimux-forms-entry',
|
|
93
|
+
})
|
|
94
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { createSystem, defaultConfig } from '@chakra-ui/react'
|
|
2
|
+
// Keep only component infrastructure; no global reset, root font or document palette.
|
|
3
|
+
const { globalCss: _global, preflight: _reset, ...base } = defaultConfig
|
|
4
|
+
export const formSystem = createSystem({ ...base, theme: { ...base.theme, keyframes: {}, semanticTokens: {} } }, {
|
|
5
|
+
cssVarsRoot: '.omnimux-forms-body', preflight: false, globalCss: {}, disableLayers: true,
|
|
6
|
+
theme: { semanticTokens: { colors: {
|
|
7
|
+
fg: { DEFAULT: { value: 'var(--dsw-alias-label-primary)' }, muted: { value: 'var(--dsw-alias-label-secondary)' }, subtle: { value: 'var(--dsw-alias-label-secondary)' } },
|
|
8
|
+
bg: { DEFAULT: { value: 'var(--dsw-alias-bg-base)' }, subtle: { value: 'var(--dsw-alias-bg-layer-1)' }, muted: { value: 'var(--dsw-alias-bg-layer-2)' }, panel: { value: 'var(--dsw-alias-bg-elevated)' } },
|
|
9
|
+
border: { DEFAULT: { value: 'var(--dsw-alias-border-l2)' }, emphasized: { value: 'var(--dsw-alias-border-l3)' } },
|
|
10
|
+
} } },
|
|
11
|
+
})
|
|
12
|
+
export const control = {
|
|
13
|
+
boxSizing: 'border-box', height: '32px', minHeight: '32px', borderRadius: '8px', fontSize: '14px',
|
|
14
|
+
color: 'var(--dsw-alias-label-primary)', bg: 'var(--dsw-alias-bg-layer-1)',
|
|
15
|
+
border: '1px solid var(--dsw-alias-border-l2)',
|
|
16
|
+
_focusVisible: { outline: '2px solid var(--dsw-alias-brand-primary)', outlineOffset: '2px' },
|
|
17
|
+
_disabled: { opacity: 0.5, cursor: 'not-allowed' },
|
|
18
|
+
}
|
|
19
|
+
export const secondary = { ...control, paddingInline: '12px', _hover: { bg: 'var(--dsw-alias-interactive-bg-hover)' } }
|
|
20
|
+
export const primary = { ...secondary, bg: 'var(--dsw-alias-label-primary)', color: 'var(--dsw-alias-label-primary-inverted)', _hover: { opacity: 0.88 } }
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import assert from 'node:assert/strict'
|
|
2
|
+
import { readFileSync } from 'node:fs'
|
|
3
|
+
import { dirname, join } from 'node:path'
|
|
4
|
+
import { describe, it } from 'node:test'
|
|
5
|
+
import { fileURLToPath } from 'node:url'
|
|
6
|
+
|
|
7
|
+
const here = dirname(fileURLToPath(import.meta.url))
|
|
8
|
+
|
|
9
|
+
describe('forms workbench seat (hidden from left sidebar)', () => {
|
|
10
|
+
it('sidebar entry uses the workbench store and exports standard selectors', () => {
|
|
11
|
+
const source = readFileSync(join(here, 'sidebar-entry.js'), 'utf8')
|
|
12
|
+
assert.match(source, /createWorkbenchStageStore/)
|
|
13
|
+
assert.match(source, /FORMS_TAB_ID = 'omnimux-forms:tasks'/)
|
|
14
|
+
assert.match(source, /ENTRY_SELECTOR = '\[data-omnimux-forms-entry\]'/)
|
|
15
|
+
})
|
|
16
|
+
|
|
17
|
+
it('client apply keeps the tasks tab but does not mount the left sidebar row', () => {
|
|
18
|
+
const source = readFileSync(join(here, 'index.js'), 'utf8')
|
|
19
|
+
assert.doesNotMatch(source, /mountSidebarEntry\(/)
|
|
20
|
+
assert.match(source, /id: FORMS_TAB_ID/)
|
|
21
|
+
assert.match(source, /betterSidebar/)
|
|
22
|
+
})
|
|
23
|
+
})
|