Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@earthranger/react-native-jsonforms-formatter",
"version": "2.0.0-beta.25",
"version": "2.0.0-beta.32",
Comment thread
doneill marked this conversation as resolved.
"description": "Converts JTD into JSON Schema ",
"main": "./dist/bundle.js",
"types": "./dist/index.d.ts",
Expand Down
6 changes: 5 additions & 1 deletion src/common/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,11 @@ export interface V2BaseProperty {
minimum?: number;
maximum?: number;
format?: 'date-time' | 'date' | 'time' | 'uri';
anyOf?: Array<{ $ref: string } | { oneOf: Array<{ const: any; title?: string }> }>;
anyOf?: Array<
| { $ref: string }
| { oneOf: Array<{ const: any; title?: string }> }
| { type?: string; title?: string; description?: string; enum: any[]; 'x-enumExtra'?: Record<string, { display: string; description?: string; [key: string]: unknown }> }
>;
items?: V2BaseProperty;
properties?: Record<string, V2BaseProperty>;
required?: string[];
Expand Down
16 changes: 7 additions & 9 deletions src/v2/generateUISchema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,20 +46,18 @@ const validateV2Schema = (schema: V2Schema): void => {
if (uiField.type === 'CHOICE_LIST') {
let hasValidStructure = false;

const isValidChoiceItem = (anyOfItem: any): boolean =>
(anyOfItem.oneOf && Array.isArray(anyOfItem.oneOf)) ||
(anyOfItem.enum && Array.isArray(anyOfItem.enum));
Comment thread
doneill marked this conversation as resolved.

if (property.type === 'array' && property.items?.anyOf) {
// Check for oneOf arrays in anyOf items for array types (no $ref support)
hasValidStructure = property.items.anyOf.some((anyOfItem: any) =>
anyOfItem.oneOf && Array.isArray(anyOfItem.oneOf) // Empty arrays are valid
);
hasValidStructure = property.items.anyOf.some(isValidChoiceItem);
} else if (property.anyOf) {
// Check direct anyOf structure for string types (no $ref support)
hasValidStructure = property.anyOf.some((anyOfItem: any) =>
anyOfItem.oneOf && Array.isArray(anyOfItem.oneOf) // Empty arrays are valid
);
hasValidStructure = property.anyOf.some(isValidChoiceItem);
}

if (!hasValidStructure) {
invalidFields.push(`${fieldName}: CHOICE_LIST field requires embedded oneOf arrays - $ref not supported`);
invalidFields.push(`${fieldName}: CHOICE_LIST field requires embedded oneOf or enum arrays - $ref not supported`);
}
}
});
Expand Down
17 changes: 16 additions & 1 deletion src/v2/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ export const createControl = (
control.options!.display = property.format || "date-time";
break;

case "CHOICE_LIST":
case "CHOICE_LIST": {
// Handle multiple choice (array type) first
if (property.type === "array") {
control.options!.multi = true;
Expand All @@ -93,7 +93,22 @@ export const createControl = (
if (uiField.placeholder) {
control.options!.placeholder = uiField.placeholder;
}

const anyOfSource = property.type === "array"
? property.items?.anyOf
: property.anyOf;
const enumItem = anyOfSource?.find(
(a): a is { enum: any[]; "x-enumExtra"?: Record<string, { display: string; [key: string]: unknown }> } =>
"enum" in a
);
if (enumItem) {
control.options!.oneOf = enumItem.enum.map((value: any) => ({
const: value,
title: enumItem["x-enumExtra"]?.[value]?.display ?? String(value),
}));
}
break;
}

case "LOCATION":
control.options!.format = "location";
Expand Down
226 changes: 226 additions & 0 deletions test/v2.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -977,6 +977,232 @@ describe('BOOLEAN field type', () => {
});
});

// ─── enum + x-enumExtra (issue #41) ──────────────────────────────────────────

const enumChoiceSchema: V2Schema = {
json: {
$schema: 'https://json-schema.org/draft/2020-12/schema',
additionalProperties: false,
required: [],
type: 'object',
properties: {
Fire_Status: {
deprecated: false,
title: 'Fire Status',
description: 'Only get one choice',
type: 'string',
anyOf: [
{
type: 'string',
title: 'Choices',
description: 'All choices schema list',
enum: ['active', 'inactive'],
'x-enumExtra': {
active: { display: 'Active', description: 'firerep_status' },
inactive: { display: 'Inactive', description: 'firerep_status' },
},
} as any,
],
},
Equipment: {
deprecated: false,
title: 'Equipment',
description: 'Make many choices',
type: 'array',
uniqueItems: true,
items: {
type: 'string',
anyOf: [
{
type: 'string',
title: 'Choices',
description: 'All choices schema list',
enum: ['emergencykit', 'stretcher', 'other', 'none'],
'x-enumExtra': {
emergencykit: { display: 'Complete Emergency Kit', description: 'medevacrep_specialequipment' },
stretcher: { display: 'Stretcher and other mobilisation devices', description: 'medevacrep_specialequipment' },
other: { display: 'Other requirements', description: 'medevacrep_specialequipment' },
none: { display: 'None', description: 'medevacrep_specialequipment' },
},
} as any,
],
},
},
},
},
ui: {
fields: {
Fire_Status: {
conditionalDependents: [],
parent: 'section-1',
type: 'CHOICE_LIST',
choices: {
eventTypeCategories: [],
existingChoiceList: ['firerep_status'],
featureCategories: [],
myDataType: 'EVENT_TYPES_FROM_EVENT_CATEGORY',
subjectGroups: [],
subjectSubtypes: [],
type: 'EXISTING_CHOICE_LIST',
},
inputType: 'DROPDOWN',
placeholder: 'Single Choice',
},
Equipment: {
conditionalDependents: [],
parent: 'section-1',
type: 'CHOICE_LIST',
choices: {
eventTypeCategories: [],
existingChoiceList: ['medevacrep_specialequipment'],
featureCategories: [],
myDataType: 'EVENT_TYPES_FROM_EVENT_CATEGORY',
subjectGroups: [],
subjectSubtypes: [],
type: 'EXISTING_CHOICE_LIST',
},
inputType: 'DROPDOWN',
placeholder: 'Multiple Choice',
},
},
headers: {},
order: ['section-1'],
sections: {
'section-1': {
columns: 1,
conditions: [],
isActive: true,
label: '',
leftColumn: [
{ name: 'Fire_Status', type: 'field' },
{ name: 'Equipment', type: 'field' },
],
rightColumn: [],
},
},
},
};

describe('V2 generateUISchema — enum + x-enumExtra format (issue #41)', () => {
it('accepts single-select CHOICE_LIST with enum format without throwing', () => {
expect(() => generateUISchema(enumChoiceSchema)).not.toThrow();
});

it('accepts multi-select CHOICE_LIST with enum format on items without throwing', () => {
expect(() => generateUISchema(enumChoiceSchema)).not.toThrow();
});

it('generates dropdown control for single-select enum field with placeholder', () => {
const result = generateUISchema(enumChoiceSchema);
const section = result.elements![0];
const fireStatusControl = section.elements![0];
expect(fireStatusControl).toMatchObject({
type: 'Control',
scope: '#/properties/Fire_Status',
label: 'Fire Status',
options: { format: 'dropdown', placeholder: 'Single Choice' },
});
});

it('injects options.oneOf with display titles for single-select enum field', () => {
const result = generateUISchema(enumChoiceSchema);
const fireStatusControl = result.elements![0].elements![0];
expect(fireStatusControl.options!.oneOf).toEqual([
{ const: 'active', title: 'Active' },
{ const: 'inactive', title: 'Inactive' },
]);
});

it('generates multi dropdown control for array enum field with placeholder', () => {
const result = generateUISchema(enumChoiceSchema);
const section = result.elements![0];
const equipmentControl = section.elements![1];
expect(equipmentControl).toMatchObject({
type: 'Control',
scope: '#/properties/Equipment',
label: 'Equipment',
options: { format: 'dropdown', multi: true, placeholder: 'Multiple Choice' },
});
});

it('injects options.oneOf with display titles for multi-select array enum field', () => {
const result = generateUISchema(enumChoiceSchema);
const equipmentControl = result.elements![0].elements![1];
expect(equipmentControl.options!.oneOf).toEqual([
{ const: 'emergencykit', title: 'Complete Emergency Kit' },
{ const: 'stretcher', title: 'Stretcher and other mobilisation devices' },
{ const: 'other', title: 'Other requirements' },
{ const: 'none', title: 'None' },
]);
});

it('falls back to raw enum value as title when x-enumExtra is missing an entry', () => {
const schemaWithGap: V2Schema = {
...enumChoiceSchema,
json: {
...enumChoiceSchema.json,
properties: {
Fire_Status: {
...enumChoiceSchema.json.properties['Fire_Status'],
anyOf: [
{
enum: ['active', 'unknown'],
'x-enumExtra': {
active: { display: 'Active', description: '' },
// 'unknown' intentionally absent
},
} as any,
],
},
},
},
};
const result = generateUISchema(schemaWithGap);
const control = result.elements![0].elements![0];
expect(control.options!.oneOf).toEqual([
{ const: 'active', title: 'Active' },
{ const: 'unknown', title: 'unknown' },
]);
});

it('injects options.oneOf using raw values as titles when x-enumExtra is entirely absent', () => {
const schemaNoExtra: V2Schema = {
...enumChoiceSchema,
json: {
...enumChoiceSchema.json,
properties: {
Fire_Status: {
...enumChoiceSchema.json.properties['Fire_Status'],
anyOf: [
{ enum: ['active', 'inactive'] } as any,
],
},
Equipment: enumChoiceSchema.json.properties['Equipment'],
},
},
};
const result = generateUISchema(schemaNoExtra);
const control = result.elements![0].elements![0];
expect(control.options!.oneOf).toEqual([
{ const: 'active', title: 'active' },
{ const: 'inactive', title: 'inactive' },
]);
});

it('does not inject options.oneOf for old-format oneOf schemas (backward compatibility)', () => {
// mockV2Schema uses the old anyOf[{ oneOf: [...] }] format — options.oneOf must be absent
const result = generateUISchema(mockV2Schema);
const activityControl = result.elements![0].elements![2]; // patrol_activity
expect(activityControl.options!.oneOf).toBeUndefined();
});

it('does not mutate the original schema.json', () => {
const original = JSON.stringify(enumChoiceSchema.json);
generateUISchema(enumChoiceSchema);
expect(JSON.stringify(enumChoiceSchema.json)).toBe(original);
});
});

// Helper function to extract all controls from nested structure
function getAllControls(uiSchema: any): any[] {
const controls: any[] = [];
Expand Down
Loading
Loading