|
| 1 | +import React, { ComponentType, ReactElement, useEffect, useState } from 'https://esm.sh/react' |
| 2 | +import util, { reModuleExt } from './util.ts' |
| 3 | + |
| 4 | +interface ImportProps { |
| 5 | + from: string |
| 6 | + name?: string // default is 'default' |
| 7 | + props?: Record<string, any> |
| 8 | + fallback?: ReactElement |
| 9 | +} |
| 10 | + |
| 11 | +export default function Import(props: ImportProps) { |
| 12 | + const { __importer, __sourceFile } = (props as any) |
| 13 | + const [error, setError] = useState<string | null>(null) |
| 14 | + const [mod, setMod] = useState<{ Component: ComponentType | null }>({ Component: null }) |
| 15 | + |
| 16 | + useEffect(() => { |
| 17 | + if (reModuleExt.test(__sourceFile)) { |
| 18 | + const p = util.splitPath(__importer) |
| 19 | + p.pop() |
| 20 | + import(util.cleanPath('/_aleph/' + p.join('/') + '/' + props.from)) |
| 21 | + .then(mod => { |
| 22 | + const Component = mod[props.name || 'default'] |
| 23 | + if (util.isLikelyReactComponent(Component)) { |
| 24 | + setMod({ Component }) |
| 25 | + } else { |
| 26 | + setError(`component${props.name ? ` '${props.name}'` : ''} not found`) |
| 27 | + } |
| 28 | + }) |
| 29 | + .catch((err: Error) => { |
| 30 | + setError(err.message) |
| 31 | + }) |
| 32 | + } |
| 33 | + }, [__importer, __sourceFile]) |
| 34 | + |
| 35 | + if (error) { |
| 36 | + return React.createElement('div', { style: { color: 'red' } }, error) |
| 37 | + } |
| 38 | + |
| 39 | + if (mod.Component) { |
| 40 | + return React.createElement(mod.Component, props.props) |
| 41 | + } |
| 42 | + |
| 43 | + if (reModuleExt.test(__sourceFile) && props.fallback) { |
| 44 | + return props.fallback |
| 45 | + } |
| 46 | + |
| 47 | + return null |
| 48 | +} |
0 commit comments