Skip to content
Open
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
70 changes: 70 additions & 0 deletions packages/react-native/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,76 @@ Any prop value can be a dynamic expression resolved at render time:

See [@json-render/core](../core/README.md) for full expression syntax.

### Computed functions

Register named functions through `JSONUIProvider` or a component returned by `createRenderer` to resolve `$computed` expressions:

```tsx
<JSONUIProvider
functions={{ fullName: (args) => `${args.first} ${args.last}` }}
>
<Renderer spec={spec} />
</JSONUIProvider>
```

### Custom directives

Register custom directives through `JSONUIProvider` or a component returned by `createRenderer` to resolve user-defined `$`-prefixed values in component props:

```tsx
import { defineDirective, resolvePropValue } from "@json-render/core";
import { z } from "zod";

const math = defineDirective({
name: "$math",
schema: z.object({
$math: z.literal("multiply"),
a: z.unknown(),
b: z.unknown(),
}),
resolve(value, ctx) {
return Number(resolvePropValue(value.a, ctx)) *
Number(resolvePropValue(value.b, ctx));
},
});

const format = defineDirective({
name: "$format",
schema: z.object({
$format: z.literal("currency"),
value: z.unknown(),
currency: z.string(),
}),
resolve(value, ctx) {
const amount = Number(resolvePropValue(value.value, ctx));
return new Intl.NumberFormat("en-US", {
style: "currency",
currency: value.currency,
}).format(amount);
},
});

<JSONUIProvider directives={[math, format]}>
<Renderer spec={spec} />
</JSONUIProvider>;
```

The directives compose in props, so `$format` can format a `$math` result that reads its operands from state:

```json
{
"$format": "currency",
"value": {
"$math": "multiply",
"a": { "$state": "/price" },
"b": { "$state": "/qty" }
},
"currency": "USD"
}
```

See the [directives documentation](https://json-render.dev/docs/directives) for more details.

## Tab Navigation Pattern

Combine `Pressable`, `setState`, visibility conditions, and dynamic props for functional tabs:
Expand Down
85 changes: 70 additions & 15 deletions packages/react-native/src/renderer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,13 +12,17 @@ import type {
Catalog,
SchemaDefinition,
StateStore,
ComputedFunction,
DirectiveDefinition,
DirectiveRegistry,
} from "@json-render/core";
import {
resolveElementProps,
resolveBindings,
resolveActionParam,
evaluateVisibility,
getByPath,
createDirectiveRegistry,
type PropResolutionContext,
type VisibilityContext as CoreVisibilityContext,
} from "@json-render/core";
Expand All @@ -40,6 +44,23 @@ import { ConfirmDialog } from "./contexts/actions";
import { standardComponents } from "./components/standard";
import { RepeatScopeProvider, useRepeatScope } from "./contexts/repeat-scope";

const EMPTY_FUNCTIONS: Record<string, ComputedFunction> = {};

const FunctionsContext =
React.createContext<Record<string, ComputedFunction>>(EMPTY_FUNCTIONS);

function useFunctions(): Record<string, ComputedFunction> {
return React.useContext(FunctionsContext);
}

const DirectivesContext = React.createContext<DirectiveRegistry | undefined>(
undefined,
);

function useDirectives(): DirectiveRegistry | undefined {
return React.useContext(DirectivesContext);
}

/**
* Props passed to component renderers
*/
Expand Down Expand Up @@ -159,6 +180,8 @@ const ElementRenderer = React.memo(function ElementRenderer({
const { ctx } = useVisibility();
const { execute } = useActions();
const { getSnapshot } = useStateStore();
const functions = useFunctions();
const directives = useDirectives();

// Build context with repeat scope (used for both visibility and props)
const fullCtx: PropResolutionContext = useMemo(
Expand All @@ -169,9 +192,11 @@ const ElementRenderer = React.memo(function ElementRenderer({
repeatItem: repeatScope.item,
repeatIndex: repeatScope.index,
repeatBasePath: repeatScope.basePath,
functions,
directives,
}
: ctx,
[ctx, repeatScope],
: { ...ctx, functions, directives },
[ctx, repeatScope, functions, directives],
);

// Evaluate visibility (now supports $item/$index inside repeat scopes)
Expand Down Expand Up @@ -439,6 +464,10 @@ export interface JSONUIProviderProps {
string,
(value: unknown, args?: Record<string, unknown>) => boolean
>;
/** Named functions for `$computed` expressions in props */
functions?: Record<string, ComputedFunction>;
/** Custom directives for user-defined `$`-prefixed dynamic values */
directives?: DirectiveDefinition[];
/** Callback when state changes (uncontrolled mode) */
onStateChange?: (changes: Array<{ path: string; value: unknown }>) => void;
children: ReactNode;
Expand All @@ -454,9 +483,16 @@ export function JSONUIProvider({
handlers,
navigate,
validationFunctions,
functions,
directives,
onStateChange,
children,
}: JSONUIProviderProps) {
const directiveRegistry = useMemo(
() => (directives ? createDirectiveRegistry(directives) : undefined),
[directives],
);

return (
<StateProvider
store={store}
Expand All @@ -465,10 +501,14 @@ export function JSONUIProvider({
>
<VisibilityProvider>
<ActionProvider handlers={handlers} navigate={navigate}>
<ValidationProvider customFunctions={validationFunctions}>
{children}
<ConfirmationDialogManager />
</ValidationProvider>
<FunctionsContext.Provider value={functions ?? EMPTY_FUNCTIONS}>
<DirectivesContext.Provider value={directiveRegistry}>
<ValidationProvider customFunctions={validationFunctions}>
{children}
<ConfirmationDialogManager />
</ValidationProvider>
</DirectivesContext.Provider>
</FunctionsContext.Provider>
</ActionProvider>
</VisibilityProvider>
</StateProvider>
Expand Down Expand Up @@ -663,6 +703,10 @@ export interface CreateRendererProps {
onAction?: (actionName: string, params?: Record<string, unknown>) => void;
/** Callback when state changes (uncontrolled mode) */
onStateChange?: (changes: Array<{ path: string; value: unknown }>) => void;
/** Named functions for `$computed` expressions in props */
functions?: Record<string, ComputedFunction>;
/** Custom directives for user-defined `$`-prefixed dynamic values */
directives?: DirectiveDefinition[];
/** Whether the spec is currently loading/streaming */
loading?: boolean;
/** Fallback component for unknown types */
Expand Down Expand Up @@ -716,9 +760,16 @@ export function createRenderer<
state,
onAction,
onStateChange,
functions,
directives,
loading,
fallback,
}: CreateRendererProps) {
const directiveRegistry = useMemo(
() => (directives ? createDirectiveRegistry(directives) : undefined),
[directives],
);

// Wrap onAction with a Proxy so any action name routes to the callback
const actionHandlers = onAction
? new Proxy(
Expand All @@ -744,15 +795,19 @@ export function createRenderer<
>
<VisibilityProvider>
<ActionProvider handlers={actionHandlers}>
<ValidationProvider>
<Renderer
spec={spec}
registry={registry}
loading={loading}
fallback={fallback}
/>
<ConfirmationDialogManager />
</ValidationProvider>
<FunctionsContext.Provider value={functions ?? EMPTY_FUNCTIONS}>
<DirectivesContext.Provider value={directiveRegistry}>
<ValidationProvider>
<Renderer
spec={spec}
registry={registry}
loading={loading}
fallback={fallback}
/>
<ConfirmationDialogManager />
</ValidationProvider>
</DirectivesContext.Provider>
</FunctionsContext.Provider>
</ActionProvider>
</VisibilityProvider>
</StateProvider>
Expand Down
14 changes: 14 additions & 0 deletions skills/react-native/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,20 @@ Any prop value can be a data-driven expression resolved at render time:

Components do not use a `statePath` prop for two-way binding. Use `{ "$bindState": "/path" }` on the natural value prop instead.

### Computed functions

Pass named functions to `JSONUIProvider` or a component returned by `createRenderer` with the `functions` prop. These functions resolve `$computed` expressions in element props.

### Custom directives

Pass custom directive definitions to `JSONUIProvider` or a component returned by `createRenderer` with the `directives` prop. Their resolvers can compose with built-in dynamic values such as `$state`:

```tsx
<JSONUIProvider directives={[uppercaseDirective]}>
<Renderer spec={spec} />
</JSONUIProvider>
```

## Built-in Actions

The `setState` action is handled automatically by `ActionProvider` and updates the state model directly, which re-evaluates visibility conditions and dynamic prop expressions:
Expand Down