|
| 1 | +import type { JsfSchema } from '../../src/types' |
| 2 | +import { describe, expect, it } from '@jest/globals' |
| 3 | +import { createHeadlessForm } from '../../src' |
| 4 | + |
| 5 | +describe('custom order', () => { |
| 6 | + it('should sort fields by x-jsf-order', () => { |
| 7 | + const schema: JsfSchema = { |
| 8 | + 'type': 'object', |
| 9 | + 'properties': { |
| 10 | + name: { type: 'string' }, |
| 11 | + age: { type: 'number' }, |
| 12 | + }, |
| 13 | + 'x-jsf-order': ['age', 'name'], |
| 14 | + } |
| 15 | + const form = createHeadlessForm(schema) |
| 16 | + |
| 17 | + const keys = form.fields.map(field => field.name) |
| 18 | + expect(keys).toEqual(['age', 'name']) |
| 19 | + }) |
| 20 | + |
| 21 | + it('should sort nested objects', () => { |
| 22 | + const addressSchema: JsfSchema = { |
| 23 | + 'type': 'object', |
| 24 | + 'properties': { |
| 25 | + state: { type: 'string' }, |
| 26 | + city: { type: 'string' }, |
| 27 | + street: { type: 'string' }, |
| 28 | + }, |
| 29 | + 'x-jsf-order': ['street', 'city', 'state'], |
| 30 | + } |
| 31 | + |
| 32 | + const mainSchema: JsfSchema = { |
| 33 | + 'type': 'object', |
| 34 | + 'properties': { |
| 35 | + address: addressSchema, |
| 36 | + name: { type: 'string' }, |
| 37 | + }, |
| 38 | + 'x-jsf-order': ['name', 'address'], |
| 39 | + } |
| 40 | + |
| 41 | + const form = createHeadlessForm(mainSchema) |
| 42 | + |
| 43 | + const mainKeys = form.fields.map(field => field.name) |
| 44 | + expect(mainKeys).toEqual(['name', 'address']) |
| 45 | + |
| 46 | + const addressField = form.fields.find(field => field.name === 'address') |
| 47 | + if (addressField === undefined) |
| 48 | + throw new Error('Address field not found') |
| 49 | + |
| 50 | + // This already throws if "fields" is undefined |
| 51 | + const addressKeys = addressField.fields?.map(field => field.name) |
| 52 | + expect(addressKeys).toEqual(['street', 'city', 'state']) |
| 53 | + }) |
| 54 | + |
| 55 | + it('should respect initial, unspecified order', () => { |
| 56 | + const schema: JsfSchema = { |
| 57 | + 'type': 'object', |
| 58 | + 'properties': { |
| 59 | + one: { type: 'string' }, |
| 60 | + two: { type: 'string' }, |
| 61 | + three: { type: 'string' }, |
| 62 | + }, |
| 63 | + 'x-jsf-order': ['three'], |
| 64 | + } |
| 65 | + |
| 66 | + const form = createHeadlessForm(schema) |
| 67 | + const keys = form.fields.map(field => field.name) |
| 68 | + |
| 69 | + // "one" and "two" are not specified, |
| 70 | + // so they are added to the end, |
| 71 | + // respecting their relative initial order |
| 72 | + expect(keys).toEqual(['three', 'one', 'two']) |
| 73 | + }) |
| 74 | +}) |
0 commit comments