Skip to content

Commit

Permalink
Improve Zod bridge - passing props (#1321)
Browse files Browse the repository at this point in the history
  • Loading branch information
piotrpospiech authored May 24, 2024
1 parent e7d7785 commit 75dbb94
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 1 deletion.
24 changes: 24 additions & 0 deletions packages/uniforms-bridge-zod/__tests__/ZodBridge.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { connectField } from 'uniforms';
import { ZodBridge } from 'uniforms-bridge-zod';
import {
any,
Expand Down Expand Up @@ -447,6 +448,29 @@ describe('ZodBridge', () => {
const bridge = new ZodBridge({ schema });
expect(bridge.getProps('a')).toEqual({ label: 'A', required: true });
});

it('works with uniforms props', () => {
const schema = object({ a: string().uniforms({ type: 'password' }) });
const bridge = new ZodBridge({ schema });
expect(bridge.getProps('a')).toEqual({
label: 'A',
required: true,
type: 'password',
});
});

it('works with uniforms props (component)', () => {
const field = jest.fn(() => null);
const Field = connectField(field);

const schema = object({ a: string().uniforms(Field) });
const bridge = new ZodBridge({ schema });
expect(bridge.getProps('a')).toEqual({
component: Field,
label: 'A',
required: true,
});
});
});

describe('#getSubfields', () => {
Expand Down
8 changes: 8 additions & 0 deletions packages/uniforms-bridge-zod/src/ZodBridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,14 @@ export default class ZodBridge<T extends ZodRawShape> extends Bridge {
};

let field = this.getField(name);

const uniforms = field._uniforms;
if (typeof uniforms === 'function') {
props.component = uniforms;
} else {
Object.assign(props, uniforms);
}

if (field instanceof ZodDefault) {
field = field.removeDefault();
props.required = false;
Expand Down
15 changes: 14 additions & 1 deletion packages/uniforms-bridge-zod/src/register.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { filterDOMProps } from 'uniforms';
import { ConnectedField, filterDOMProps, UnknownObject } from 'uniforms';
import { z, ZodTypeAny } from 'zod';

// There's no possibility to retrieve them at runtime.
declare module 'uniforms' {
Expand All @@ -9,3 +10,15 @@ declare module 'uniforms' {
}

filterDOMProps.register('minCount', 'maxCount');

declare module 'zod' {
interface ZodType {
uniforms(uniforms: UnknownObject | ConnectedField<any>): ZodTypeAny;
_uniforms: UnknownObject | ConnectedField<any>;
}
}

z.ZodType.prototype.uniforms = function extend(uniforms) {
this._uniforms = uniforms;
return this;
};

0 comments on commit 75dbb94

Please sign in to comment.