@formvk/schema 0.1.0 → 1.0.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/CHANGELOG.md ADDED
@@ -0,0 +1,14 @@
1
+ # @formvk/schema
2
+
3
+ ## 1.0.0
4
+
5
+ ### Major Changes
6
+
7
+ - 65c066c: 添加readme.md文档
8
+
9
+ ### Patch Changes
10
+
11
+ - Updated dependencies [65c066c]
12
+ - @formvk/core@1.0.0
13
+ - @formvk/reactive@1.0.0
14
+ - @formvk/shared@1.0.0
package/README.md ADDED
@@ -0,0 +1,66 @@
1
+ # @formvk/schema
2
+
3
+ Schema-first layer for Formvk. `createFragment` turns registered components into typed schema constructors, `createSchema` assembles a typed object schema, and `{{ ... }}` expressions are compiled into reactive field state when the schema is rendered by `@formvk/react` or `@formvk/vue`.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ pnpm add @formvk/schema
9
+ ```
10
+
11
+ ## Usage
12
+
13
+ ```ts
14
+ import { createFragment, createSchema } from '@formvk/schema'
15
+
16
+ const f = createFragment()
17
+
18
+ export const schema = createSchema({
19
+ username: f.Field({ title: 'Username', component: 'Input', required: true }),
20
+ tags: f.Array(f.Field({ component: 'Input' })),
21
+ })
22
+ ```
23
+
24
+ Register component props to get full type inference for `componentProps`:
25
+
26
+ ```ts
27
+ const f = createFragment<{
28
+ Input: { placeholder?: string; value?: string }
29
+ }>()
30
+
31
+ const schema = createSchema({
32
+ username: f.Input({ title: 'Username', componentProps: { placeholder: 'Your name' } }),
33
+ })
34
+ ```
35
+
36
+ Expressions use the `{{ ... }}` syntax and are evaluated against form values and scope:
37
+
38
+ ```ts
39
+ const schema = createSchema({
40
+ limit: f.Input({ title: 'Limit' }),
41
+ name: f.Input({
42
+ title: 'Name',
43
+ maxLength: '{{$values.limit}}',
44
+ }),
45
+ })
46
+ ```
47
+
48
+ ## API
49
+
50
+ - `createFragment(options?)` — returns `Field`, `Object`, `Array`, `Void`, `transform`, plus one constructor per registered component name.
51
+ - `createSchema(properties, patches?)` — builds a typed `object` schema.
52
+ - `Schema` — imperative schema tree; `ISchema` is the plain-object form.
53
+ - Expressions — `SchemaExpression`, `ExpressionProps`, `createExpression`, `createExpressionFn`, `getExpression`.
54
+ - Compiler — `compile`, `shallowCompile`, `registerCompiler`, `silent`.
55
+ - Types — `FieldSchema`, `ObjectSchema`, `ArraySchema`, `VoidSchema`, `Fragment`, `SchemaCreator`.
56
+
57
+ In Vue/React apps, `createSchemaField` from `@formvk/vue` / `@formvk/react` binds component maps to a fragment and renders the schema.
58
+
59
+ ## Documentation
60
+
61
+ - Schema guide: https://formvk.github.io/core/guide/schema
62
+ - Schema API: https://formvk.github.io/core/api/schema
63
+
64
+ ## License
65
+
66
+ MIT
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@formvk/schema",
3
- "version": "0.1.0",
3
+ "version": "1.0.0",
4
4
  "description": "Formvk Schema",
5
5
  "keywords": [
6
6
  "form",
@@ -10,14 +10,18 @@
10
10
  ],
11
11
  "license": "MIT",
12
12
  "author": "yiyunwan",
13
+ "files": [
14
+ "dist",
15
+ "CHANGELOG.md"
16
+ ],
13
17
  "type": "module",
14
18
  "main": "dist/index.js",
15
19
  "module": "dist/index.js",
16
20
  "types": "dist/index.d.ts",
17
21
  "dependencies": {
18
- "@formvk/core": "^0.1.0",
19
- "@formvk/reactive": "^0.1.0",
20
- "@formvk/shared": "^0.1.0"
22
+ "@formvk/core": "~1.0.0",
23
+ "@formvk/reactive": "~1.0.0",
24
+ "@formvk/shared": "~1.0.0"
21
25
  },
22
26
  "devDependencies": {},
23
27
  "scripts": {
@@ -1,334 +0,0 @@
1
- import { expect, test } from 'vitest'
2
-
3
- import { compile, patchCompile, patchSchemaCompile, registerCompiler, shallowCompile, silent } from '../compiler'
4
- import { Schema } from '../schema'
5
-
6
- test('compile', () => {
7
- expect(compile('{{123}}xx')).toEqual('{{123}}xx')
8
- expect(compile('{{123}} ')).toEqual(123)
9
- expect(compile('{{123}}')).toEqual(123)
10
- expect(
11
- compile({
12
- hello: '{{123}}',
13
- })
14
- ).toEqual({
15
- hello: 123,
16
- })
17
- expect(
18
- compile({
19
- array: ['{{123}}'],
20
- })
21
- ).toEqual({
22
- array: [123],
23
- })
24
- const date: any = new Date()
25
- date['expression'] = '{{123}}'
26
- const compiledDate = compile(date)
27
- expect(compiledDate).toEqual(date)
28
- expect(compiledDate['expression']).toEqual('{{123}}')
29
- const moment = { _isAMomentObject: true, expression: '{{123}}' }
30
- const compiledMoment = compile(moment)
31
- expect(compiledMoment).toEqual(moment)
32
- expect(compiledMoment['expression']).toEqual('{{123}}')
33
- const react = { _owner: true, $$typeof: true, expression: '{{123}}' }
34
- const compiledReact = compile(react)
35
- expect(compiledReact).toEqual(react)
36
- expect(compiledReact['expression']).toEqual('{{123}}')
37
- const actions = {
38
- [Symbol.for('__REVA_ACTIONS')]: true,
39
- expression: '{{123}}',
40
- }
41
- const compiledActions = compile(actions)
42
- expect(compiledActions).toEqual(actions)
43
- expect(compiledActions['expression']).toEqual('{{123}}')
44
-
45
- const schema = new Schema({
46
- type: 'object',
47
- properties: {
48
- aa: {
49
- type: 'string',
50
- component: 'Input',
51
- componentProps: '{{123}}',
52
- },
53
- },
54
- })
55
- const compiledSchema = schema.compile()
56
- expect(compiledSchema.toJSON()).toEqual(schema.toJSON())
57
- expect(compiledSchema.properties?.['aa']['componentProps']).toEqual('{{123}}')
58
- const toJSable = {
59
- toJS() {
60
- return {
61
- aa: 123,
62
- }
63
- },
64
- expression: '{{123}}',
65
- }
66
-
67
- const compiledToJSable = compile(toJSable)
68
- expect(compiledToJSable).toEqual(toJSable)
69
- expect(compiledToJSable['expression']).toEqual('{{123}}')
70
-
71
- const toJSONable = {
72
- toJSON() {
73
- return {
74
- aa: 123,
75
- }
76
- },
77
- expression: '{{123}}',
78
- }
79
-
80
- const compiledToJSONable = compile(toJSONable)
81
- expect(compiledToJSONable).toEqual(toJSONable)
82
- expect(compiledToJSONable['expression']).toEqual('{{123}}')
83
-
84
- const circularRef: any = {
85
- expression: '{{123}}',
86
- }
87
- circularRef['self'] = circularRef
88
-
89
- const compiledCircularRef = compile(circularRef)
90
- expect(compiledCircularRef['expression']).toEqual(123)
91
- })
92
-
93
- test('shallowCompile', () => {
94
- expect(shallowCompile('{{123}}xx')).toEqual('{{123}}xx')
95
- expect(shallowCompile('{{123}} ')).toEqual(123)
96
- expect(shallowCompile('{{123}}')).toEqual(123)
97
- expect(
98
- shallowCompile({
99
- hello: '{{123}}',
100
- })
101
- ).toEqual({
102
- hello: '{{123}}',
103
- })
104
- expect(
105
- shallowCompile({
106
- array: ['{{123}}'],
107
- })
108
- ).toEqual({
109
- array: ['{{123}}'],
110
- })
111
- expect(shallowCompile(['{{123}}'])).toEqual(['{{123}}'])
112
- expect(shallowCompile([{ kk: '{{123}}' }])).toEqual([{ kk: '{{123}}' }])
113
- })
114
-
115
- test('unsilent', () => {
116
- silent(false)
117
- expect(() => compile('{{ ( }}')).toThrowError()
118
- })
119
-
120
- test('silent', () => {
121
- silent(true)
122
- expect(() => compile('{{ ( }}')).not.toThrowError()
123
- silent(false)
124
- })
125
-
126
- test('patchCompile', () => {
127
- const targetState = {
128
- title: '',
129
- description: '',
130
- dataSource: [22],
131
- }
132
- patchCompile(
133
- targetState as any,
134
- {
135
- title: '132',
136
- description: '{{"Hello world"}}',
137
- dataSource: [1, 2, 3, '{{333}}'],
138
- extend: '333',
139
- },
140
- {}
141
- )
142
- expect(targetState).toEqual({
143
- title: '132',
144
- description: 'Hello world',
145
- dataSource: [1, 2, 3, 333],
146
- })
147
- })
148
-
149
- test('patchSchemaCompile', () => {
150
- const targetState = {
151
- title: '',
152
- description: '',
153
- dataSource: [22],
154
- }
155
- patchSchemaCompile(
156
- targetState as any,
157
- {
158
- title: '132',
159
- description: '{{"Hello world"}}',
160
- enum: [1, 2, 3, '{{333}}'],
161
- reactions: {
162
- fulfill: {
163
- schema: {
164
- title: 'hello',
165
- },
166
- },
167
- },
168
- version: '1.2.3',
169
- },
170
- {}
171
- )
172
- expect(targetState).toEqual({
173
- title: '132',
174
- description: 'Hello world',
175
- dataSource: [
176
- { label: 1, value: 1 },
177
- { label: 2, value: 2 },
178
- { label: 3, value: 3 },
179
- { label: 333, value: 333 },
180
- ],
181
- })
182
- })
183
-
184
- test('patchSchemaCompile demand un initialized', () => {
185
- function setValidatorRule(name: string, value: any) {
186
- targetState[name] = value
187
- }
188
- const targetState: any = {
189
- title: '',
190
- description: '',
191
- dataSource: [22],
192
- setValidatorRule,
193
- }
194
- patchSchemaCompile(
195
- targetState,
196
- {
197
- title: '132',
198
- display: undefined,
199
- hidden: null,
200
- description: '{{"Hello world"}}',
201
- enum: [1, 2, 3, '{{333}}'],
202
- format: 'phone',
203
- reactions: {
204
- fulfill: {
205
- schema: {
206
- title: 'hello',
207
- },
208
- },
209
- },
210
- version: '1.2.3',
211
- } as any,
212
- {},
213
- true
214
- )
215
- expect(targetState).toEqual({
216
- title: '132',
217
- description: 'Hello world',
218
- hidden: null,
219
- format: 'phone',
220
- setValidatorRule,
221
- dataSource: [
222
- { label: 1, value: 1 },
223
- { label: 2, value: 2 },
224
- { label: 3, value: 3 },
225
- { label: 333, value: 333 },
226
- ],
227
- })
228
- })
229
-
230
- test('patchSchemaCompile demand initialized keeps static keys', () => {
231
- const targetState: any = {
232
- initialized: true,
233
- title: '',
234
- description: '',
235
- dataSource: [22],
236
- }
237
- patchSchemaCompile(
238
- targetState,
239
- {
240
- title: '132',
241
- description: '{{"Hello world"}}',
242
- enum: [1, 2, 3],
243
- version: '1.2.3',
244
- },
245
- {},
246
- true
247
- )
248
- // 静态值不回写,表达式值视为动态依赖,仍然回写
249
- expect(targetState).toEqual({
250
- initialized: true,
251
- title: '',
252
- description: 'Hello world',
253
- dataSource: [22],
254
- })
255
- })
256
-
257
- test('patchSchemaCompile validator expression', () => {
258
- const targetState: any = {
259
- title: '',
260
- validator: [],
261
- }
262
- patchSchemaCompile(
263
- targetState,
264
- {
265
- title: '132',
266
- validator: [
267
- {
268
- remoteCheckUniq: '{{field.value}}',
269
- },
270
- ],
271
- version: '1.2.3',
272
- },
273
- {
274
- field: {
275
- value: 888,
276
- },
277
- }
278
- )
279
- expect(targetState).toEqual({
280
- title: '132',
281
- validator: [{ remoteCheckUniq: 888 }],
282
- })
283
-
284
- const targetOmitState: any = {
285
- title: '',
286
- validator: [],
287
- }
288
- patchSchemaCompile(
289
- targetOmitState,
290
- {
291
- title: '132',
292
- compileOmitted: ['validator'],
293
- validator: [
294
- {
295
- remoteCheckUniq: '{{field.value}}',
296
- },
297
- ],
298
- version: '1.2.3',
299
- },
300
- {
301
- field: {
302
- value: 888,
303
- },
304
- }
305
- )
306
- expect(targetOmitState).toEqual({
307
- title: '132',
308
- validator: [{ remoteCheckUniq: '{{field.value}}' }],
309
- })
310
- })
311
-
312
- test('registerCompiler', () => {
313
- registerCompiler(() => {
314
- return 'compiled'
315
- })
316
- expect(compile('{{123}}xx')).toEqual('{{123}}xx')
317
- expect(compile('{{123}} ')).toEqual('compiled')
318
- expect(compile('{{123}}')).toEqual('compiled')
319
- expect(
320
- compile({
321
- hello: '{{123}}',
322
- })
323
- ).toEqual({
324
- hello: 'compiled',
325
- })
326
- expect(
327
- compile({
328
- array: ['{{123}}'],
329
- })
330
- ).toEqual({
331
- array: ['compiled'],
332
- })
333
- registerCompiler(null as any)
334
- })
@@ -1,83 +0,0 @@
1
- import { describe, expect, test } from 'vitest'
2
-
3
- import { createSchema } from '../create-schema'
4
- import { createFragment } from '../fragment'
5
-
6
- describe('createSchema', () => {
7
- const f = createFragment()
8
-
9
- test('should create schema', () => {
10
- expect(
11
- createSchema({
12
- string: f.Field({ title: '字符串', component: 'Input' }),
13
- })
14
- ).toEqual({
15
- type: 'object',
16
- properties: {
17
- string: {
18
- type: 'string',
19
- title: '字符串',
20
- component: 'Input',
21
- },
22
- },
23
- })
24
- })
25
-
26
- test('accepts plain schema and skips nil', () => {
27
- expect(
28
- createSchema({
29
- plain: { type: 'number', title: '数字' },
30
- empty: null,
31
- missing: undefined,
32
- })
33
- ).toEqual({
34
- type: 'object',
35
- properties: {
36
- plain: { type: 'number', title: '数字' },
37
- },
38
- })
39
- })
40
-
41
- test('forwards patches to creators', () => {
42
- const schema = createSchema(
43
- {
44
- name: f.Field(),
45
- },
46
- [
47
- inner => ({
48
- ...inner,
49
- data: { patched: true },
50
- }),
51
- ]
52
- )
53
- expect(schema.properties).toEqual({
54
- name: {
55
- type: 'string',
56
- data: { patched: true },
57
- },
58
- })
59
- })
60
-
61
- test('composes nested createSchema', () => {
62
- expect(
63
- createSchema({
64
- user: createSchema({
65
- name: f.Field({ required: true }),
66
- }),
67
- })
68
- ).toEqual({
69
- type: 'object',
70
- properties: {
71
- user: {
72
- type: 'object',
73
- properties: {
74
- name: {
75
- type: 'string',
76
- required: true,
77
- },
78
- },
79
- },
80
- },
81
- })
82
- })
83
- })
@@ -1,174 +0,0 @@
1
- import { describe, expect, test } from 'vitest'
2
-
3
- import { createExpression } from '../expression'
4
-
5
- describe('createExpression', () => {
6
- test('expression', () => {
7
- const objExp = createExpression<{
8
- a: {
9
- b: {
10
- c: {
11
- d: string
12
- }
13
- }
14
- }
15
- ['c:d']: string
16
- ['c-d']: string
17
- }>('obj')
18
- expect(`${objExp.a}`).toBe('{{obj.a}}')
19
- expect(`${objExp['c:d']}`).toBe('{{obj["c:d"]}}')
20
- expect(`${objExp['c-d']}`).toBe('{{obj["c-d"]}}')
21
- expect(`${objExp.a.b.c}`).toBe('{{obj.a.b.c}}')
22
-
23
- expect(objExp.a.eq(1)).toBe('{{obj.a === 1}}')
24
- expect(objExp.a.eq('1')).toBe('{{obj.a === "1"}}')
25
- expect(objExp.a.eq(objExp.exp.a.b, true)).toBe('{{obj.a === obj.a.b}}')
26
- expect(objExp.a.b.c.eq(1)).toBe('{{obj.a.b.c === 1}}')
27
-
28
- expect(objExp.a.neq(1)).toBe('{{obj.a !== 1}}')
29
- expect(objExp.a.neq(objExp.exp.a.b, true)).toBe('{{obj.a !== obj.a.b}}')
30
-
31
- expect(objExp.a.gt(1)).toBe('{{obj.a > 1}}')
32
- expect(objExp.a.gt(objExp.exp.a.b, true)).toBe('{{obj.a > obj.a.b}}')
33
-
34
- expect(objExp.a.gte(1)).toBe('{{obj.a >= 1}}')
35
- expect(objExp.a.gte(objExp.exp.a.b, true)).toBe('{{obj.a >= obj.a.b}}')
36
-
37
- expect(objExp.a.lt(1)).toBe('{{obj.a < 1}}')
38
- expect(objExp.a.lt(objExp.exp.a.b, true)).toBe('{{obj.a < obj.a.b}}')
39
-
40
- expect(objExp.a.lte(1)).toBe('{{obj.a <= 1}}')
41
- expect(objExp.a.lte(objExp.exp.a.b, true)).toBe('{{obj.a <= obj.a.b}}')
42
-
43
- expect(objExp.a.and(1)).toBe('{{obj.a && 1}}')
44
- expect(objExp.a.and(objExp.exp.a.b, true)).toBe('{{obj.a && obj.a.b}}')
45
-
46
- expect(objExp.a.or(1)).toBe('{{obj.a || 1}}')
47
- expect(objExp.a.or(objExp.exp.a.b, true)).toBe('{{obj.a || obj.a.b}}')
48
-
49
- expect(objExp.a.ter(1, 2)).toBe('{{obj.a ? 1 : 2}}')
50
- expect(objExp.a.ter(objExp.exp.a.b, objExp.exp.a.b.c, true)).toBe('{{obj.a ? obj.a.b : obj.a.b.c}}')
51
-
52
- // 对象会使用 JSON.stringify 转成字符串
53
- expect(objExp.a.ter({ a: 1 }, { b: 1 })).toBe('{{obj.a ? {"a":1} : {"b":1}}}')
54
- expect(objExp.a.ter([1], [2])).toBe('{{obj.a ? [1] : [2]}}')
55
- })
56
-
57
- test('expression string call', () => {
58
- const objExp = createExpression<{
59
- a: number
60
- b: string
61
- }>('obj')
62
-
63
- expect(objExp.a.toString()).toBe('{{obj.a}}')
64
- expect(objExp.a.valueOf()).toBe('{{obj.a}}')
65
- expect(Object.prototype.toString.call(objExp.a)).toBe('[object String]')
66
- expect(Object.prototype.valueOf.call('{{obj.a}}')).toEqual(new String('{{obj.a}}'))
67
- expect(objExp.b.match(/b/)).toEqual('{{obj.b}}'.match(/b/))
68
- expect(objExp.b.replace(/b/g, 'b')).toEqual('{{obj.b}}'.replace(/b/g, 'b'))
69
- expect(objExp.b.split(/b/)).toEqual('{{obj.b}}'.split(/b/))
70
- expect(objExp.b.substring(1, 2)).toEqual('{{obj.b}}'.substring(1, 2))
71
- expect(objExp.b.toLocaleLowerCase()).toEqual('{{obj.b}}'.toLocaleLowerCase())
72
- expect(objExp.b.toLocaleUpperCase()).toEqual('{{obj.b}}'.toLocaleUpperCase())
73
- expect(objExp.b.toLowerCase()).toEqual('{{obj.b}}'.toLowerCase())
74
- expect(objExp.b.toUpperCase()).toEqual('{{obj.b}}'.toUpperCase())
75
- expect(objExp.b.trim()).toEqual('{{obj.b}}'.trim())
76
- expect(objExp.b.valueOf()).toEqual('{{obj.b}}'.valueOf())
77
-
78
- expect(String.prototype.split.call(objExp.a, /\./)).toEqual(['{{obj', 'a}}'])
79
- })
80
-
81
- test('JSON.stringify(objExp.a)', () => {
82
- const objExp = createExpression<{
83
- a: string
84
- }>('obj')
85
- expect(JSON.stringify(objExp.a)).toBe('"{{obj.a}}"')
86
- expect(
87
- JSON.stringify({
88
- a: objExp.a,
89
- })
90
- ).toBe('{"a":"{{obj.a}}"}')
91
- })
92
-
93
- test('expression.exp', () => {
94
- const objExp = createExpression<{
95
- a: {
96
- b: {
97
- c: {
98
- d: string
99
- }
100
- }
101
- }
102
- }>('obj')
103
- expect(objExp.exp.a.eq(1)).toBe('obj.a === 1')
104
- // 若使用表达式,需要使用 true 标识,否则会被转成字符串
105
- expect(objExp.exp.a.eq(objExp.exp.a)).toBe('obj.a === "obj.a"')
106
- expect(objExp.exp.a.eq(objExp.exp.a, true)).toBe('obj.a === obj.a')
107
- expect(objExp.exp.a.b.c.eq('1')).toBe('obj.a.b.c === "1"')
108
- expect(objExp.exp.a.neq('1')).toBe('obj.a !== "1"')
109
- expect(objExp.exp.a.gt(1)).toBe('obj.a > 1')
110
- expect(objExp.exp.a.gte(1)).toBe('obj.a >= 1')
111
- expect(objExp.exp.a.lt(1)).toBe('obj.a < 1')
112
- expect(objExp.exp.a.lte(1)).toBe('obj.a <= 1')
113
- expect(objExp.exp.a.b.c.lte(1)).toBe('obj.a.b.c <= 1')
114
- expect(`${objExp.exp.a}`).toBe('obj.a')
115
- expect(`${objExp.exp.a.b.c}`).toBe('obj.a.b.c')
116
- expect(`${objExp.exp.a.b.c.d}`).toBe('obj.a.b.c.d')
117
- })
118
-
119
- test('expression.fn', () => {
120
- const objExp = createExpression<{
121
- a(): string
122
- b: {
123
- c(): string
124
- }
125
- }>('obj')
126
- expect(objExp.fn.a()).toBe(`{{function __a() {
127
-
128
- return obj.a()
129
- }}}`)
130
-
131
- expect(objExp.fn.a('$args')).toBe(`{{function __a(...$args) {
132
-
133
- return obj.a(...$args)
134
- }}}`)
135
- expect(
136
- objExp.fn.a('$args', {
137
- expand: false,
138
- })
139
- ).toBe(`{{function __a($args) {
140
-
141
- return obj.a($args)
142
- }}}`)
143
-
144
- expect(objExp.fn.a('$args', 'a', { body: 'var a = $args[0]', expand: false })).toBe(
145
- `{{function __a($args) {
146
- var a = $args[0]
147
- return obj.a($args, a)
148
- }}}`
149
- )
150
-
151
- expect(objExp.fn.b.c()).toBe(`{{function __c() {
152
-
153
- return obj.b.c()
154
- }}}`)
155
- })
156
-
157
- test('expression.fn ignores nil options', () => {
158
- const objExp = createExpression<{
159
- a(): string
160
- }>('obj')
161
- expect(objExp.fn.a(null as any)).toBe(`{{function __a() {
162
-
163
- return obj.a()
164
- }}}`)
165
- })
166
-
167
- test('expression.fn throws on conflicting args', () => {
168
- const objExp = createExpression<{
169
- a(): string
170
- }>('obj')
171
- expect(() => objExp.fn.a('$args', '$event')).toThrowError('$event and $args cannot be passed in at the same time')
172
- expect(() => objExp.fn.a({ body: 'return 1' })).toThrowError('body cannot contain return')
173
- })
174
- })