|
| 1 | +/** @jsxRuntime automatic */ |
| 2 | +/** @jsxImportSource react */ |
| 3 | +import {retain} from '@quilted/threads'; |
| 4 | + |
| 5 | +import {createRemoteReactComponent} from '@remote-ui/react'; |
| 6 | +import { |
| 7 | + ButtonProperties, |
| 8 | + ModalProperties, |
| 9 | + RenderAPI, |
| 10 | + StackProperties, |
| 11 | + TextProperties, |
| 12 | +} from '../../types'; |
| 13 | +import {useState} from 'react'; |
| 14 | +import {createRoot, createRemoteRoot} from '@remote-ui/react'; |
| 15 | +import {RemoteChannel} from '@remote-ui/core'; |
| 16 | + |
| 17 | +const Button = createRemoteReactComponent< |
| 18 | + 'Button', |
| 19 | + ButtonProperties & {modal?: React.ReactNode} |
| 20 | +>('Button', {fragmentProps: ['modal']}); |
| 21 | + |
| 22 | +const Text = createRemoteReactComponent<'Text', TextProperties>('Text'); |
| 23 | +const Stack = createRemoteReactComponent<'Stack', StackProperties>('Stack'); |
| 24 | +const Modal = createRemoteReactComponent< |
| 25 | + 'Modal', |
| 26 | + ModalProperties & {primaryAction?: React.ReactNode} |
| 27 | +>('Modal', {fragmentProps: ['primaryAction']}); |
| 28 | + |
| 29 | +export function renderUsingReactRemoteUI( |
| 30 | + channel: RemoteChannel, |
| 31 | + api: RenderAPI, |
| 32 | +) { |
| 33 | + retain(api); |
| 34 | + retain(channel); |
| 35 | + |
| 36 | + const remoteRoot = createRemoteRoot(channel, { |
| 37 | + components: ['Button', 'Text', 'Stack', 'Modal'], |
| 38 | + }); |
| 39 | + |
| 40 | + createRoot(remoteRoot).render(<App api={api} />); |
| 41 | + remoteRoot.mount(); |
| 42 | +} |
| 43 | + |
| 44 | +function App({api}: {api: RenderAPI}) { |
| 45 | + return ( |
| 46 | + <Stack spacing> |
| 47 | + <Text> |
| 48 | + Rendering example: <Text emphasis>{api.example}</Text> |
| 49 | + </Text> |
| 50 | + <Text> |
| 51 | + Rendering in sandbox: <Text emphasis>{api.sandbox}</Text> |
| 52 | + </Text> |
| 53 | + <Button modal={<CountModal {...api} />}>Open modal</Button> |
| 54 | + </Stack> |
| 55 | + ); |
| 56 | +} |
| 57 | + |
| 58 | +function CountModal({alert, closeModal}: RenderAPI) { |
| 59 | + const [count, setCount] = useState(0); |
| 60 | + |
| 61 | + const primaryAction = ( |
| 62 | + <Button |
| 63 | + onPress={() => { |
| 64 | + closeModal(); |
| 65 | + }} |
| 66 | + > |
| 67 | + Close |
| 68 | + </Button> |
| 69 | + ); |
| 70 | + |
| 71 | + return ( |
| 72 | + <Modal |
| 73 | + primaryAction={primaryAction} |
| 74 | + onClose={() => { |
| 75 | + if (count > 0) { |
| 76 | + alert(`You clicked ${count} times!`); |
| 77 | + } |
| 78 | + |
| 79 | + setCount(0); |
| 80 | + }} |
| 81 | + > |
| 82 | + <Stack spacing> |
| 83 | + <Text> |
| 84 | + Click count: <Text emphasis>{count}</Text> |
| 85 | + </Text> |
| 86 | + <Button |
| 87 | + onPress={() => { |
| 88 | + setCount((count) => count + 1); |
| 89 | + }} |
| 90 | + > |
| 91 | + Click me! |
| 92 | + </Button> |
| 93 | + </Stack> |
| 94 | + </Modal> |
| 95 | + ); |
| 96 | +} |
0 commit comments