| 1 | import type { VirtualModuleTemplate } from './types' |
| 2 | |
| 3 | export const VIRTUAL_SLIDE_PREFIX = '/@slidev/slides/' |
| 4 | |
| 5 | export const templateSlides: VirtualModuleTemplate = { |
| 6 | id: '/@slidev/slides', |
| 7 | async getContent({ data, utils }) { |
| 8 | const layouts = await utils.getLayouts() |
| 9 | const statements = [ |
| 10 | `import { defineAsyncComponent, shallowRef } from 'vue'`, |
| 11 | `import SlideError from '${layouts.error}'`, |
| 12 | `import SlideLoading from '@slidev/client/internals/SlideLoading.vue'`, |
| 13 | `const componentsCache = new Array(${data.slides.length})`, |
| 14 | `const getAsyncComponent = (idx, loader) => defineAsyncComponent({`, |
| 15 | ` loader,`, |
| 16 | ` delay: 300,`, |
| 17 | ` loadingComponent: SlideLoading,`, |
| 18 | ` errorComponent: SlideError,`, |
| 19 | ` onError: e => console.error('Failed to load slide ' + (idx + 1), e) `, |
| 20 | `})`, |
| 21 | ] |
| 22 | const slides = data.slides |
| 23 | .map((_, idx) => { |
| 24 | const no = idx + 1 |
| 25 | statements.push( |
| 26 | `import { meta as f${no} } from '${VIRTUAL_SLIDE_PREFIX}${no}/frontmatter'`, |
| 27 | // For some unknown reason, import error won't be caught by the error component. Catch it here. |
| 28 | `const load${no} = async () => {`, |
| 29 | ` try { return componentsCache[${idx}] ??= await import('${VIRTUAL_SLIDE_PREFIX}${no}/md') }`, |
| 30 | ` catch (e) { console.error('slide failed to load', e); return SlideError }`, |
| 31 | `}`, |
| 32 | ) |
| 33 | return `{ no: ${no}, meta: f${no}, load: load${no}, component: getAsyncComponent(${idx}, load${no}) }` |
| 34 | }) |
| 35 | return [ |
| 36 | ...statements, |
| 37 | `const data = [\n${slides.join(',\n')}\n]`, |
| 38 | `if (import.meta.hot) {`, |
| 39 | ` import.meta.hot.data.slides ??= shallowRef()`, |
| 40 | ` import.meta.hot.data.slides.value = data`, |
| 41 | ` import.meta.hot.dispose(() => componentsCache.length = 0)`, |
| 42 | ` import.meta.hot.accept()`, |
| 43 | `}`, |
| 44 | `export const slides = import.meta.hot ? import.meta.hot.data.slides : shallowRef(data)`, |
| 45 | ].join('\n') |
| 46 | }, |
| 47 | } |
| 48 |