Skip to content

Commit 50398f8

Browse files
authored
fix: empty field checks (#869)
1 parent 388b7c4 commit 50398f8

2 files changed

Lines changed: 66 additions & 1 deletion

File tree

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import {describe, it, expect} from 'vitest';
2+
import {Field, ObjectField} from '../../core/schema.js';
3+
import {testFieldEmpty} from './test-field-empty.js';
4+
5+
describe('testFieldEmpty', () => {
6+
const objectField: ObjectField = {
7+
type: 'object',
8+
fields: [
9+
{type: 'string', id: 'foo'},
10+
{type: 'string', id: 'bar'},
11+
],
12+
};
13+
14+
const arrayField: Field = {
15+
type: 'array',
16+
of: objectField,
17+
};
18+
19+
describe('array', () => {
20+
it('should return false for a plain non-empty array', () => {
21+
const plainArray = [{foo: 'a'}, {foo: 'b'}];
22+
expect(testFieldEmpty(arrayField, plainArray)).toBe(false);
23+
});
24+
25+
it('should return true for an empty array', () => {
26+
const emptyArray: any[] = [];
27+
expect(testFieldEmpty(arrayField, emptyArray)).toBe(true);
28+
});
29+
30+
it('should return false for a normalized non-empty array', () => {
31+
const normalizedArray = {_array: ['id1'], id1: {foo: 'a'}};
32+
expect(testFieldEmpty(arrayField, normalizedArray)).toBe(false);
33+
});
34+
35+
it('should return true for a normalized array with empty items', () => {
36+
const normalizedArray = {_array: ['id1'], id1: {foo: ''}};
37+
expect(testFieldEmpty(arrayField, normalizedArray)).toBe(true);
38+
});
39+
});
40+
41+
describe('object', () => {
42+
it('should return true for an empty object', () => {
43+
expect(testFieldEmpty(objectField, {})).toBe(true);
44+
});
45+
46+
it('should return true for an object with empty fields', () => {
47+
expect(testFieldEmpty(objectField, {foo: '', bar: ''})).toBe(true);
48+
});
49+
50+
it('should return false for an object with non-empty fields', () => {
51+
expect(testFieldEmpty(objectField, {foo: 'hello'})).toBe(false);
52+
});
53+
});
54+
});

packages/root-cms/ui/utils/test-field-empty.ts

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,17 @@ export function testFieldEmpty(
5252
}
5353
return true;
5454
case 'array':
55+
if (Array.isArray(value)) {
56+
if (value.length === 0) {
57+
return true;
58+
}
59+
for (const item of value) {
60+
if (!testFieldEmpty(field.of, item, types)) {
61+
return false;
62+
}
63+
}
64+
return true;
65+
}
5566
if (
5667
!isObject(value) ||
5768
!Array.isArray(value._array) ||
@@ -64,7 +75,7 @@ export function testFieldEmpty(
6475
return false;
6576
}
6677
}
67-
return false;
78+
return true;
6879
case 'oneof': {
6980
if (!isObject(value) || !value._type) {
7081
return true;

0 commit comments

Comments
 (0)