UNPKG

histoire

Version:

A fast story book powered by Vite

133 lines (132 loc) • 4.24 kB
import { withStoryExecution } from '@histoire/shared'; import { defineComponent as _defineComponent, h as _h, onBeforeUnmount as _onBeforeUnmount, onMounted as _onMounted, ref as _ref, watch as _watch, } from '@histoire/vendors/vue'; // @ts-expect-error virtual module id import * as generatedSetup from 'virtual:$histoire-generated-global-setup'; // @ts-expect-error virtual module id import * as setup from 'virtual:$histoire-setup'; /** * Setup modules in run order. Accessed through this array: a static * `setup.setupVanilla` makes the bundler warn on every build whose setup * file only has hooks for other frameworks. */ const setupModules = [generatedSetup, setup]; export default _defineComponent({ name: 'RenderStory', props: { variant: { type: Object, required: true, }, story: { type: Object, required: true, }, slotName: { type: String, default: 'default', }, }, emits: { ready: () => true, }, setup(props, { emit }) { const sandbox = _ref(); let mounting = false; let app; let appHooks; async function unmountVariant() { if (app) { await app.onUnmount?.(); if (appHooks) { for (const hook of appHooks.onUnmount) { await hook(); } } app.el.parentNode.removeChild(app.el); app = null; } } async function mountVariant() { if (mounting) return; mounting = true; await unmountVariant(); app = { el: document.createElement('div'), }; for (const setupModule of setupModules) { const setupVanilla = setupModule?.setupVanilla; if (typeof setupVanilla === 'function') { await withStoryExecution(() => setupVanilla({ app, story: props.story, variant: props.variant, }), sandbox.value); } } if (typeof props.variant.setupApp === 'function') { await withStoryExecution(() => props.variant.setupApp({ app, story: props.story, variant: props.variant, }), sandbox.value); } await withStoryExecution(() => app.onMount?.(), sandbox.value); appHooks = { onUpdate: [], onUnmount: [], }; const api = { el: app.el, state: props.variant.state, onUpdate: (cb) => { appHooks.onUpdate.push(cb); }, onUnmount: (cb) => { appHooks.onUnmount.push(cb); }, }; const onMount = props.variant.slots()[props.slotName]; await withStoryExecution(() => onMount(api), sandbox.value); sandbox.value.appendChild(app.el); emit('ready'); } _onMounted(async () => { if (props.variant.configReady) { await mountVariant(); } }); _watch(() => props.variant, async (value) => { if (value.configReady && !mounting) { if (!app) { await mountVariant(); } else { // @TODO check if need to refresh here } } }, { deep: true, }); _watch(() => props.variant.state, async () => { if (appHooks) { for (const hook of appHooks.onUpdate) { await hook(); } } }, { deep: true, }); _onBeforeUnmount(() => { unmountVariant(); }); return { sandbox, }; }, render() { return _h('div', { ref: 'sandbox', }); }, });