|
| 1 | +import { createEffect, createSignal, Show, type Component } from 'solid-js'; |
| 2 | +import { render } from 'solid-js/web'; |
| 3 | +import { Container, Divider, Heading } from '@spuxx/solid'; |
| 4 | +import { InteractiveControls } from './InteractiveControls'; |
| 5 | +import type { Argument } from './types'; |
| 6 | + |
| 7 | +interface Props { |
| 8 | + componentName: string; |
| 9 | + argDefinitions: Record<string, Argument<unknown>>; |
| 10 | + title?: string; |
| 11 | +} |
| 12 | + |
| 13 | +export const InteractiveSolid: Component<Props> = (props) => { |
| 14 | + const { title, componentName, argDefinitions } = props; |
| 15 | + |
| 16 | + let dispose: (() => void) | undefined; |
| 17 | + // eslint-disable-next-line prefer-const |
| 18 | + let containerRef: HTMLDivElement | null = null; |
| 19 | + |
| 20 | + const [state, setState] = createSignal<{ |
| 21 | + component: Component | null; |
| 22 | + args: Record<string, unknown>; |
| 23 | + }>({ component: null, args: {} }); |
| 24 | + |
| 25 | + const importComponent = async () => { |
| 26 | + const module = await import(`@spuxx/solid`); |
| 27 | + const importedComponent = module[componentName as keyof typeof module] as Component; |
| 28 | + setState({ component: importedComponent, args: {} }); |
| 29 | + }; |
| 30 | + importComponent(); |
| 31 | + |
| 32 | + const handleArgsChange = (args: Record<string, unknown>) => { |
| 33 | + setState({ component: state().component!, args }); |
| 34 | + }; |
| 35 | + |
| 36 | + createEffect(() => { |
| 37 | + const { component, args } = state(); |
| 38 | + if (dispose) { |
| 39 | + dispose(); |
| 40 | + } |
| 41 | + |
| 42 | + if (containerRef && component) { |
| 43 | + dispose = render(() => component(args), containerRef); |
| 44 | + } |
| 45 | + }); |
| 46 | + |
| 47 | + return ( |
| 48 | + <div> |
| 49 | + <Container variant="contained" color="gradient"> |
| 50 | + <Heading level={4}>Interactive Example: {title ?? componentName}</Heading> |
| 51 | + <Divider /> |
| 52 | + |
| 53 | + <Show when={state().component}> |
| 54 | + <InteractiveControls argDefinitions={argDefinitions} onArgsChange={handleArgsChange} /> |
| 55 | + <Container |
| 56 | + variant="contained" |
| 57 | + color="background" |
| 58 | + style={{ |
| 59 | + padding: '2rem', |
| 60 | + }} |
| 61 | + > |
| 62 | + <div ref={containerRef!} /> |
| 63 | + </Container> |
| 64 | + </Show> |
| 65 | + <Show when={!state().component}> |
| 66 | + <p>No component specified.</p> |
| 67 | + </Show> |
| 68 | + </Container> |
| 69 | + </div> |
| 70 | + ); |
| 71 | +}; |
0 commit comments