Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(compat): remote-ui compatibility layer #439

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
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
23 changes: 22 additions & 1 deletion examples/kitchen-sink/app/host.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {
} from '@remote-dom/preact/host';
import {ThreadIframe, ThreadWebWorker} from '@quilted/threads';

import type {SandboxAPI} from './types.ts';
import type {LegacySandboxAPI, SandboxAPI} from './types.ts';
import {Button, Modal, Stack, Text, ControlPanel} from './host/components.tsx';
import {createState} from './host/state.ts';

Expand All @@ -30,6 +30,21 @@ const worker = new Worker(
);
const workerSandbox = new ThreadWebWorker<SandboxAPI>(worker);

import {createEndpoint, fromWebWorker} from '@remote-ui/rpc';
import {wrapRemoteUiSandbox} from './host/remote-ui-adapter.ts';

// a wild remote-ui powered sandbox appears!
const legacyWorkerSandbox = createEndpoint<LegacySandboxAPI>(
fromWebWorker(
new Worker(
new URL('./remote/remote-ui-worker/sandbox.ts', import.meta.url),
{
type: 'module',
},
),
),
);

// We will use Preact to render remote elements in this example. The Preact
// helper library lets you do this by mapping the name of a remote element to
// a local Preact component. We’ve implemented the actual UI of our components in
Expand Down Expand Up @@ -57,6 +72,12 @@ const components = new Map([
// rendered by the remote environment. We use this object later to render these trees
// to Preact components using the `RemoteRootRenderer` component.

const sandboxes = {
iframe: iframeSandbox,
worker: workerSandbox,
'remote-ui-worker': wrapRemoteUiSandbox(legacyWorkerSandbox),
};

const {receiver, example, sandbox} = createState(
async ({receiver, example, sandbox}) => {
if (sandbox === 'iframe') {
Expand Down
149 changes: 149 additions & 0 deletions examples/kitchen-sink/app/host/remote-ui-adapter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
import {type Endpoint} from '@remote-ui/rpc';
import {
KIND_COMPONENT,
KIND_FRAGMENT,
KIND_TEXT,
RemoteComponentSerialization,
RemoteFragmentSerialization,
RemoteTextSerialization,
createRemoteChannel,
retain,
release, // todo
} from '@remote-ui/core';
import {
MUTATION_TYPE_INSERT_CHILD,
MUTATION_TYPE_REMOVE_CHILD,
MUTATION_TYPE_UPDATE_PROPERTY,
MUTATION_TYPE_UPDATE_TEXT,
NODE_TYPE_ELEMENT,
RemoteElementSerialization,
RemoteMutationRecordInsertChild,
RemoteMutationRecordRemoveChild,
RemoteMutationRecordUpdateProperty,
RemoteMutationRecordUpdateText,
RemoteNodeSerialization,
} from '@remote-dom/core';
import {LegacySandboxAPI, SandboxAPI} from '../types';
import {Thread} from '@quilted/threads';

export function wrapRemoteUiSandbox(
sandbox: Endpoint<LegacySandboxAPI>,
): Pick<Thread<SandboxAPI>, 'imports'> {
return {
imports: {
async render(connection, api) {
function convertSerialization<
T extends
| RemoteTextSerialization
| RemoteComponentSerialization
| RemoteFragmentSerialization,
>(node: T): RemoteElementSerialization | RemoteNodeSerialization {
switch (node.kind) {
case KIND_COMPONENT:
const properties: Record<string, any> = {};
const children = node.children.map(convertSerialization);
for (const prop in node.props) {
const value = node.props[prop];
if (
typeof value === 'object' &&
value &&
'kind' in value &&
'id' in value
) {
const child = convertSerialization(
value,
) as RemoteElementSerialization;
child.properties!.slot = prop;
children.push(child);
} else {
properties[prop] = value;
retain(value);
}
}
return {
type: NODE_TYPE_ELEMENT,
id: node.id,
element:
'ui' + node.type.replace(/([A-Z])/g, '-$1').toLowerCase(),
properties: properties,
children,
} satisfies RemoteElementSerialization;
case KIND_FRAGMENT:
return {
type: NODE_TYPE_ELEMENT,
id: node.id,
element: 'remote-fragment',
properties: {},
children: node.children.map(convertSerialization),
} satisfies RemoteElementSerialization;
case KIND_TEXT:
return {
type: 3,
id: node.id,
data: node.text,
};
}
}

const channel = createRemoteChannel({
mount(nodes) {
connection.mutate(
nodes.map(
(node, index) =>
[
MUTATION_TYPE_INSERT_CHILD,
'~',
convertSerialization(node),
index,
] satisfies RemoteMutationRecordInsertChild,
),
);
},
insertChild(node, index, child) {
connection.mutate([
[
MUTATION_TYPE_INSERT_CHILD,
node!,
convertSerialization(child),
index,
] satisfies RemoteMutationRecordInsertChild,
]);
},
removeChild(node, index) {
connection.mutate([
[
MUTATION_TYPE_REMOVE_CHILD,
node!,
index,
] satisfies RemoteMutationRecordRemoveChild,
]);
},
updateProps(node, props) {
retain(props, {deep: true});
connection.mutate(
Object.entries(props).map(
([property, value]) =>
[
MUTATION_TYPE_UPDATE_PROPERTY,
node!,
property,
value,
] satisfies RemoteMutationRecordUpdateProperty,
),
);
},
updateText(node, text) {
connection.mutate([
[
MUTATION_TYPE_UPDATE_TEXT,
node!,
text,
] satisfies RemoteMutationRecordUpdateText,
]);
},
});
return sandbox.call.render(channel, api);
},
},
};
}
6 changes: 5 additions & 1 deletion examples/kitchen-sink/app/host/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@ import {SignalRemoteReceiver} from '@remote-dom/preact/host';
import type {RenderExample, RenderSandbox} from '../types.ts';

const DEFAULT_SANDBOX = 'worker';
const ALLOWED_SANDBOX_VALUES = new Set<RenderSandbox>(['iframe', 'worker']);
const ALLOWED_SANDBOX_VALUES = new Set<RenderSandbox>([
'iframe',
'worker',
'remote-ui-worker',
]);

const DEFAULT_EXAMPLE = 'vanilla';
const ALLOWED_EXAMPLE_VALUES = new Set<RenderExample>([
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/** @jsxRuntime automatic */
/** @jsxImportSource react */

import {
createRoot,
createRemoteReactComponent,
type RemoteRoot,
} from '@remote-ui/react';
import {ButtonProperties, StackProperties, RenderAPI} from '../../types';

const Stack = createRemoteReactComponent<'Stack', StackProperties>('Stack');
const Button = createRemoteReactComponent<'Button', ButtonProperties>('Button');

export function renderReact(remoteRoot: RemoteRoot, api: RenderAPI) {
const root = createRoot(remoteRoot);
root.render(<App api={api} />);
}

function App({api}: {api: RenderAPI}) {
return (
<Stack>
<Button onPress={() => api.alert('Hello world')}>Click me</Button>
</Stack>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
import {createRemoteComponent, type RemoteRoot} from '@remote-ui/core';
import type {
RenderAPI,
ButtonProperties,
TextProperties,
ModalProperties,
StackProperties,
} from '../../types.ts';

// these are just type-branded strings
const Button = createRemoteComponent<'Button', ButtonProperties>('Button');
const Text = createRemoteComponent<'Text', TextProperties>('Text');
const Modal = createRemoteComponent<'Modal', ModalProperties>('Modal');
const Stack = createRemoteComponent<'Stack', StackProperties>('Stack');

export function renderVanilla(root: RemoteRoot, api: RenderAPI) {
let count = 0;
let countText = root.createText('0');

function updateCount(newCount: number) {
count = newCount;
countText.update(String(count));
}

const primaryAction = root.createFragment();
primaryAction.append(
root.createComponent(
Button,
{
onPress() {
// remote-ui did not support calling functions on components:
// modal.close();
modal.updateProps({open: false});
},
},
'Close modal',
),
);

const modal = root.createComponent(
Modal,
{
onClose() {
if (count > 0) {
api.alert(`You clicked ${count} times!`);
}

updateCount(0);
},
primaryAction,
},
root.createComponent(
Text,
null,
'Click count: ',
root.createComponent(Text, {emphasis: true}, countText),
),
root.createComponent(
Button,
{
onPress() {
updateCount(count + 1);
},
},
'click me!',
),
);

root.append(
root.createComponent(
Stack,
{spacing: true},
root.createComponent(
Text,
{},
'Rendering example: ',
root.createComponent(Text, {emphasis: true}, api.example),
),

root.createComponent(
Text,
{},
'Rendering in sandbox: ',
root.createComponent(Text, {emphasis: true}, api.sandbox),
),

root.createComponent(
Button,
{
onPress() {
modal.updateProps({open: true});
},
},
'Open modal',
),
),
modal,
);
}
30 changes: 30 additions & 0 deletions examples/kitchen-sink/app/remote/remote-ui-worker/sandbox.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import {retain, createEndpoint, fromWebWorker} from '@remote-ui/rpc';
import {createRemoteRoot} from '@remote-ui/core';

import {renderVanilla} from './example-vanilla.ts';
import {renderReact} from './example-react.tsx';
import type {LegacySandboxAPI} from '../../types.ts';

createEndpoint<LegacySandboxAPI>(fromWebWorker(self as any as Worker)).expose({
async render(connection, api) {
retain(connection);
retain(api, {deep: true});

const root = createRemoteRoot(connection);
switch (api.example) {
case 'react':
renderReact(root, api);
break;
case 'vanilla':
renderVanilla(root, api);
break;
default:
root.append(
root.createText(
`🚫 There is no remote-ui legacy version of the "${api.example}" example.`,
),
);
}
root.mount();
},
});
13 changes: 12 additions & 1 deletion examples/kitchen-sink/app/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,11 @@ export type RenderSandbox =
* The remote code is executed in a web worker.
* @see https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API
*/
| 'worker';
| 'worker'
/**
* A web worker that is using remote-ui
*/
| 'remote-ui-worker';

/**
* Describes the example used to render the UI in the sandboxed environment.
Expand Down Expand Up @@ -58,6 +62,13 @@ export interface SandboxAPI {
render(connection: RemoteConnection, api: RenderAPI): Promise<unknown>;
}

export interface LegacySandboxAPI {
render(
channel: import('@remote-ui/core').RemoteChannel,
api: RenderAPI,
): Promise<unknown>;
}

// These property and method types will be used by both the host and remote environments.
// They will be used to describe the properties that are available on the elements that can
// be synchronized between the two environments.
Expand Down
Loading
Loading