|
| 1 | +import { transformVNodeArgs, h } from 'vue' |
| 2 | + |
| 3 | +import { pascalCase, kebabCase } from './utils' |
| 4 | + |
| 5 | +interface IStubOptions { |
| 6 | + name?: string |
| 7 | +} |
| 8 | + |
| 9 | +// TODO: figure out how to type this |
| 10 | +type VNodeArgs = any[] |
| 11 | + |
| 12 | +export const createStub = (options: IStubOptions) => { |
| 13 | + const tag = options.name ? `${options.name}-stub` : 'anonymous-stub' |
| 14 | + const render = () => h(tag) |
| 15 | + |
| 16 | + return { name: tag, render } |
| 17 | +} |
| 18 | + |
| 19 | +const resolveComponentStubByName = ( |
| 20 | + componentName: string, |
| 21 | + stubs: Record<any, any> |
| 22 | +) => { |
| 23 | + const componentPascalName = pascalCase(componentName) |
| 24 | + const componentKebabName = kebabCase(componentName) |
| 25 | + |
| 26 | + for (const [stubKey, value] of Object.entries(stubs)) { |
| 27 | + if ( |
| 28 | + stubKey === componentPascalName || |
| 29 | + stubKey === componentKebabName || |
| 30 | + stubKey === componentName |
| 31 | + ) { |
| 32 | + return value |
| 33 | + } |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +const isHTMLElement = (args: VNodeArgs) => |
| 38 | + Array.isArray(args) && typeof args[0] === 'string' |
| 39 | + |
| 40 | +const isCommentOrFragment = (args: VNodeArgs) => typeof args[0] === 'symbol' |
| 41 | + |
| 42 | +const isParent = (args: VNodeArgs) => |
| 43 | + typeof args[0] === 'object' && args[0]['name'] === 'VTU_COMPONENT' |
| 44 | + |
| 45 | +const isComponent = (args: VNodeArgs) => typeof args[0] === 'object' |
| 46 | + |
| 47 | +export function stubComponents(stubs: Record<any, any>) { |
| 48 | + transformVNodeArgs((args) => { |
| 49 | + // args[0] can either be: |
| 50 | + // 1. a HTML tag (div, span...) |
| 51 | + // 2. An object of component options, such as { name: 'foo', render: [Function], props: {...} } |
| 52 | + // Depending what it is, we do different things. |
| 53 | + if (isHTMLElement(args) || isCommentOrFragment(args) || isParent(args)) { |
| 54 | + return args |
| 55 | + } |
| 56 | + |
| 57 | + if (isComponent(args)) { |
| 58 | + const name = args[0]['name'] |
| 59 | + if (!name) { |
| 60 | + return args |
| 61 | + } |
| 62 | + |
| 63 | + const stub = resolveComponentStubByName(name, stubs) |
| 64 | + |
| 65 | + // we return a stub by matching Vue's `h` function |
| 66 | + // where the signature is h(Component, props) |
| 67 | + // case 1: default stub |
| 68 | + if (stub === true) { |
| 69 | + return [createStub({ name }), {}] |
| 70 | + } |
| 71 | + |
| 72 | + // case 2: custom implementation |
| 73 | + if (typeof stub === 'object') { |
| 74 | + return [stubs[name], {}] |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + return args |
| 79 | + }) |
| 80 | +} |
0 commit comments