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
5 changes: 5 additions & 0 deletions .changeset/friendly-portals-repeat.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@ankhorage/runtime': patch
---

Preserve effective renderer configuration for manifest children rendered outside their original React provider ancestry.
31 changes: 20 additions & 11 deletions src/RuntimeRenderer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -382,26 +382,35 @@ export function RuntimeRenderer(props: RuntimeRendererProps) {
});

return (
<RuntimeRenderer
<RuntimeRendererConfigProvider
key={`${child.id}:${String(repeatKey)}`}
node={child}
registry={effectiveRegistry}
bindingContext={createRuntimeRepeatBindingContext({
baseContext: effectiveConfig.bindingContext,
item,
itemAlias,
})}
/>
replace
value={effectiveConfig}
>
<RuntimeRenderer
node={child}
registry={effectiveRegistry}
bindingContext={createRuntimeRepeatBindingContext({
baseContext: effectiveConfig.bindingContext,
item,
itemAlias,
})}
/>
</RuntimeRendererConfigProvider>
);
}),
)
: shouldRenderRepeatEmptyState
? node.repeat.empty?.map((child) => (
<RuntimeRenderer key={child.id} node={child} registry={effectiveRegistry} />
<RuntimeRendererConfigProvider key={child.id} replace value={effectiveConfig}>
<RuntimeRenderer node={child} registry={effectiveRegistry} />
</RuntimeRendererConfigProvider>
))
: undefined
: node.children?.map((child) => (
<RuntimeRenderer key={child.id} node={child} registry={effectiveRegistry} />
<RuntimeRendererConfigProvider key={child.id} replace value={effectiveConfig}>
<RuntimeRenderer node={child} registry={effectiveRegistry} />
</RuntimeRendererConfigProvider>
));

const propsWithEvents = wrapRuntimeEventProps({
Expand Down
5 changes: 3 additions & 2 deletions src/RuntimeRendererConfig.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -157,10 +157,11 @@ export function mergeRuntimeRendererConfig(
export function RuntimeRendererConfigProvider(props: {
value: RuntimeRendererConfig;
children: React.ReactNode;
replace?: boolean;
}) {
const { value, children } = props;
const { value, children, replace = false } = props;
const inheritedConfig = use(RuntimeRendererConfigContext);
const mergedConfig = mergeRuntimeRendererConfig(value, inheritedConfig);
const mergedConfig = replace ? value : mergeRuntimeRendererConfig(value, inheritedConfig);

return (
<RuntimeRendererConfigContext value={mergedConfig}>{children}</RuntimeRendererConfigContext>
Expand Down
205 changes: 205 additions & 0 deletions src/runtimeRendererPortalConfig.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
import type { ComponentDataBindingRegistry, StateAdapter, UiNode } from '@ankhorage/contracts';
import { expect, it, mock } from 'bun:test';
import React from 'react';
import { act, create } from 'react-test-renderer';

import type { ComponentRegistry } from './registry.js';
import {
RuntimeRendererConfigProvider,
useRuntimeRendererConfig,
} from './RuntimeRendererConfig.js';
import { createRuntimeMemoryStateAdapter } from './runtimeStateAdapter.js';

(
globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }
).IS_REACT_ACT_ENVIRONMENT = true;

void mock.module('react-native', () => ({
StyleSheet: { create: <TStyles,>(styles: TStyles): TStyles => styles },
Text: 'text',
View: 'view',
}));

const { RuntimeRenderer } = await import('./RuntimeRenderer.js');

let capturedPortalChildren: React.ReactElement | undefined;
let expectedStateAdapter: StateAdapter | undefined;
let expectedExecutor: unknown;

const Portal = ({ children }: { readonly children?: React.ReactNode }): React.ReactElement => {
capturedPortalChildren = <>{children}</>;
return <output data-kind="portal" />;
};

const Rows = ({ children }: { readonly children?: React.ReactNode }): React.ReactElement => (
<section>{children}</section>
);

const RowLabel = ({ value }: { readonly value?: unknown }): React.ReactElement => (
<output data-row={String(value)} />
);

const ConfigProbe = (): React.ReactElement => {
const config = useRuntimeRendererConfig();
const context = config.bindingContext;

return (
<output
data-executor={String(config.executeCapability === expectedExecutor)}
data-inherited={String(context?.inherited)}
data-local={String(context?.local)}
data-row-alias={String((context?.row as { label?: unknown } | undefined)?.label)}
data-state-adapter={String(config.stateAdapter === expectedStateAdapter)}
/>
);
};

const Action = ({ onPress }: { readonly onPress?: () => void }): React.ReactElement => (
<button onClick={onPress}>Select</button>
);

const registry: ComponentRegistry = { Action, ConfigProbe, Portal, RowLabel, Rows };

const node = {
children: [
{
children: [
{ id: 'row-label', type: 'RowLabel' },
{ id: 'config-probe', type: 'ConfigProbe' },
{ id: 'action', type: 'Action' },
],
id: 'rows',
repeat: { itemAlias: 'row', source: { capability: 'context.rows' } },
type: 'Rows',
},
],
id: 'portal',
type: 'Portal',
} satisfies UiNode;

const dataBindings = {
action: {
componentId: 'action',
events: { press: [{ target: { capability: 'api.rows.select' } }] },
},
'row-label': {
componentId: 'row-label',
props: { value: { value: { capability: 'context.row', path: 'label' } } },
},
} satisfies ComponentDataBindingRegistry;

it('preserves effective Runtime configuration for repeated children rendered outside provider ancestry', async () => {
const stateAdapter = createRuntimeMemoryStateAdapter();
const executeCapability = mock(() => Promise.resolve({ data: null, ok: true as const }));
expectedStateAdapter = stateAdapter;
expectedExecutor = executeCapability;
const mountedSourceRenderer = mountSourceRenderer({
executeCapability,
rows: [{ label: 'First repository' }],
stateAdapter,
});
const mountedPortalRenderer = mountCapturedPortalChildren();

expectPortalConfiguration(mountedPortalRenderer, 'First repository');

await act(async () => {
const buttonProps = mountedPortalRenderer.root.findByType('button').props as {
readonly onClick?: unknown;
};
const { onClick } = buttonProps;
if (!isVoidCallback(onClick)) throw new Error('Expected the action button to have onClick.');
onClick();
await Promise.resolve();
});
expect(executeCapability).toHaveBeenCalledTimes(1);

updateSourceRenderer(mountedSourceRenderer, {
executeCapability,
rows: [{ label: 'Updated repository' }],
stateAdapter,
});
const updatedPortalChildren = getCapturedPortalChildren();
act(() => {
mountedPortalRenderer.update(updatedPortalChildren);
});

expectPortalConfiguration(mountedPortalRenderer, 'Updated repository');
});

function mountSourceRenderer(args: {
readonly executeCapability: ReturnType<typeof mock>;
readonly rows: readonly { readonly label: string }[];
readonly stateAdapter: StateAdapter;
}): ReturnType<typeof create> {
let renderer: ReturnType<typeof create> | undefined;
act(() => {
renderer = create(renderSource(args));
});
if (renderer === undefined) throw new Error('Expected the source renderer to mount.');
return renderer;
}

function updateSourceRenderer(
renderer: ReturnType<typeof create>,
args: {
readonly executeCapability: ReturnType<typeof mock>;
readonly rows: readonly { readonly label: string }[];
readonly stateAdapter: StateAdapter;
},
): void {
act(() => {
renderer.update(renderSource(args));
});
}

function renderSource(args: {
readonly executeCapability: ReturnType<typeof mock>;
readonly rows: readonly { readonly label: string }[];
readonly stateAdapter: StateAdapter;
}): React.ReactElement {
return (
<RuntimeRendererConfigProvider
value={{
bindingContext: { inherited: 'outer' },
dataBindings,
executeCapability: args.executeCapability,
stateAdapter: args.stateAdapter,
}}
>
<RuntimeRenderer
bindingContext={{ local: 'root', rows: args.rows }}
isRoot
node={node}
registry={registry}
/>
</RuntimeRendererConfigProvider>
);
}

function mountCapturedPortalChildren(): ReturnType<typeof create> {
let renderer: ReturnType<typeof create> | undefined;
act(() => {
renderer = create(getCapturedPortalChildren());
});
if (renderer === undefined) throw new Error('Expected detached portal children to render.');
return renderer;
}

function getCapturedPortalChildren(): React.ReactElement {
if (capturedPortalChildren === undefined)
throw new Error('Expected the portal to capture children.');
return capturedPortalChildren;
}

function isVoidCallback(value: unknown): value is () => void {
return typeof value === 'function';
}

function expectPortalConfiguration(renderer: ReturnType<typeof create>, row: string): void {
expect(renderer.root.findByProps({ 'data-row': row })).toBeDefined();
expect(renderer.root.findByProps({ 'data-inherited': 'outer' })).toBeDefined();
expect(renderer.root.findByProps({ 'data-local': 'root' })).toBeDefined();
expect(renderer.root.findByProps({ 'data-row-alias': row })).toBeDefined();
expect(renderer.root.findByProps({ 'data-state-adapter': 'true' })).toBeDefined();
expect(renderer.root.findByProps({ 'data-executor': 'true' })).toBeDefined();
}