Skip to content

Commit

Permalink
feat(vue-playground): add custom cdn supports
Browse files Browse the repository at this point in the history
  • Loading branch information
2214962083 committed May 18, 2022
1 parent 0279054 commit 4fb37e4
Show file tree
Hide file tree
Showing 9 changed files with 72 additions and 22 deletions.
3 changes: 1 addition & 2 deletions packages/doc-site/.vuepress/plugins/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@ import {isProd} from '../utils/common'
import sandboxPlugin from 'vuepress-plugin-sandbox'

const pathResolve = (..._path: string[]) => path.resolve(__dirname, ..._path)
const getPkgUrl = (name: string, version = 'latest', ending = '') =>
`https://cdn.jsdelivr.net/npm/${name}@${version}${ending}`
const getPkgUrl = (name: string, version = 'latest', ending = '') => `https://unpkg.com/${name}@${version}${ending}`

const vuepressPlugins: PluginConfig = [
// for doc search
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@
</script>

<!-- ES Module Shims: Import maps polyfill for modules browsers without import maps support (all except Chrome 89+) -->
<script async src="https://unpkg.com/[email protected]/dist/es-module-shims.min.js"></script>
<script async src="<!--ES_MODULE_SHIMS_CDN-->"></script>
<script type="importmap">
<!--IMPORT_MAP-->
</script>
Expand Down
13 changes: 12 additions & 1 deletion packages/vue-playground/src/core/compiler/preview.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,11 @@ import {Store} from '../store'
import {PreviewProxy} from './preview-proxy'
import PreviewIframe from './preview-iframe.html?raw'
import {compileModulesForPreview} from './module-compiler'
import {DEFAULT_ES_MODULE_SHIMS_CDN} from '../../playground/constants'
import type {PlaygroundPkgCdn} from '../../playground/utils/types-helper'

export interface PreviewOptions {
pkgCdn?: PlaygroundPkgCdn
store: Store
onBeforeDestroy?: () => void
onBeforeLoad?: () => void
Expand All @@ -17,6 +20,7 @@ export class Preview {
sandboxEl?: HTMLIFrameElement
previewProxy?: PreviewProxy
store!: Store
pkgCdn?: PlaygroundPkgCdn
onBeforeDestroy?: () => void
onBeforeLoad?: () => void
onLoad?: () => void
Expand All @@ -25,7 +29,9 @@ export class Preview {

constructor(options: PreviewOptions) {
this.store = options.store
this.pkgCdn = options.pkgCdn
this.onBeforeDestroy = options.onBeforeDestroy
this.onBeforeLoad = options.onBeforeLoad
this.onLoad = options.onLoad
this.onError = options.onError
}
Expand Down Expand Up @@ -58,7 +64,12 @@ export class Preview {
if (!importMap.imports) importMap.imports = {}
if (!importMap.imports.vue) importMap.imports.vue = this.store.state.vueRuntimeURL

this.sandboxEl.srcdoc = PreviewIframe.replace(/<!--IMPORT_MAP-->/, JSON.stringify(importMap))
this.sandboxEl.srcdoc = PreviewIframe.replace(/<!--IMPORT_MAP-->/, JSON.stringify(importMap)) // inject import map
.replace(
/<!--ES_MODULE_SHIMS_CDN-->/,
this.pkgCdn?.['es-module-shims']?.('0.10.1', '/dist/es-module-shims.min.js') || DEFAULT_ES_MODULE_SHIMS_CDN
) // inject es module shims

container.appendChild(this.sandboxEl)

this.previewProxy = new PreviewProxy({
Expand Down
46 changes: 32 additions & 14 deletions packages/vue-playground/src/core/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import {compileFile} from './compiler/transform'
import {utoa, atou} from './utils/common'
import {ImportMap, OutputModes} from './utils/types-helper'
import {SFCScriptCompileOptions, SFCAsyncStyleCompileOptions, SFCTemplateCompileOptions} from 'vue/compiler-sfc'
import {DEFAULT_VUE_RUNTIME_DOM_CDN, DEFAULT_VUE_COMPILER_SFC_CDN} from '../playground/constants'
import type {PlaygroundPkgCdn} from '../playground/utils/types-helper'

const defaultMainFile = 'App.vue'

Expand Down Expand Up @@ -65,32 +67,37 @@ export interface Store {
initialOutputMode: OutputModes
}

interface ReplStoreOptions {
serializedState?: string
initFiles?: File[]
showOutput?: boolean
// loose type to allow getting from the URL without inducing a typing error
outputMode?: OutputModes | string
defaultVueRuntimeURL?: string
pkgCdn?: PlaygroundPkgCdn
initImportMap?: ImportMap
}

export class ReplStore implements Store {
state: StoreState
compiler = defaultCompiler
options?: SFCOptions
initialShowOutput: boolean
initialOutputMode: OutputModes
pkgCdn?: PlaygroundPkgCdn

private defaultVueRuntimeURL: string
private pendingCompiler: Promise<any> | null = null

constructor({
serializedState = '',
defaultVueRuntimeURL = `https://cdn.jsdelivr.net/npm/@vue/runtime-dom@${version}/dist/runtime-dom.esm-browser.js`,
defaultVueRuntimeURL,
showOutput = false,
outputMode = 'preview',
initFiles,
initImportMap
}: {
serializedState?: string
initFiles?: File[]
showOutput?: boolean
// loose type to allow getting from the URL without inducing a typing error
outputMode?: OutputModes | string
defaultVueRuntimeURL?: string
initImportMap?: ImportMap
} = {}) {
initImportMap,
pkgCdn
}: ReplStoreOptions = {}) {
let files: StoreState['files'] = {}

if (serializedState) {
Expand All @@ -108,9 +115,14 @@ export class ReplStore implements Store {
}
}

this.defaultVueRuntimeURL = defaultVueRuntimeURL
this.defaultVueRuntimeURL =
defaultVueRuntimeURL ||
pkgCdn?.['@vue/runtime-dom']?.(version, '/dist/runtime-dom.esm-browser.js') ||
DEFAULT_VUE_RUNTIME_DOM_CDN(version)

this.initialShowOutput = showOutput
this.initialOutputMode = outputMode as OutputModes
this.pkgCdn = pkgCdn

let mainFile = defaultMainFile
if (!files[mainFile]) {
Expand Down Expand Up @@ -228,8 +240,14 @@ export class ReplStore implements Store {
}

async setVueVersion(version: string) {
const compilerUrl = `https://cdn.jsdelivr.net/npm/@vue/compiler-sfc@${version}/dist/compiler-sfc.esm-browser.js`
const runtimeUrl = `https://cdn.jsdelivr.net/npm/@vue/runtime-dom@${version}/dist/runtime-dom.esm-browser.js`
const compilerUrl =
this.pkgCdn?.['@vue/compiler-sfc']?.(version, '/dist/compiler-sfc.esm-browser.js') ||
DEFAULT_VUE_COMPILER_SFC_CDN(version)

const runtimeUrl =
this.pkgCdn?.['@vue/runtime-dom']?.(version, '/dist/runtime-dom.esm-browser.js') ||
DEFAULT_VUE_RUNTIME_DOM_CDN(version)

this.pendingCompiler = import(/* @vite-ignore */ compilerUrl)
this.compiler = await this.pendingCompiler
this.pendingCompiler = null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,14 @@ import {
unref
} from 'vue'
import {Preview} from '../../core/'
import {CLEAR_CONSOLE_INJECT_KEY, STORE_INJECT_KEY, THEME_INJECT_KEY} from '../constants'
import {CLEAR_CONSOLE_INJECT_KEY, PKG_CDN_INJECT_KEY, STORE_INJECT_KEY, THEME_INJECT_KEY} from '../constants'
import {PreviewExpose} from '../utils/types-helper'
const store = inject(STORE_INJECT_KEY)!
const _clearConsole = inject(CLEAR_CONSOLE_INJECT_KEY, false)
const clearConsole = computed(() => unref(_clearConsole))
const theme = inject(THEME_INJECT_KEY)
const pkgCdn = inject(PKG_CDN_INJECT_KEY, {})
const containerRef = ref<HTMLElement>()
const runtimeError = ref()
Expand All @@ -37,6 +38,7 @@ let stopUpdateWatcher: WatchStopHandle | undefined
const preview = new Preview({
store: store!,
pkgCdn: unref(pkgCdn),
onBeforeDestroy() {
stopUpdateWatcher?.()
},
Expand Down
11 changes: 10 additions & 1 deletion packages/vue-playground/src/playground/constants.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type {MaybeRef} from '@vueuse/core'
import type {InjectionKey} from 'vue'
import type {Store} from '../core'
import type {PlaygroundTheme} from './utils/types-helper'
import type {PlaygroundPkgCdn, PlaygroundTheme} from './utils/types-helper'

export const DEFAULT_TITLE = 'Demo' as const
export const PLAYGROUND_COMPONENT_NAME = 'Playground' as const
Expand All @@ -14,6 +14,7 @@ export const CLEAR_CONSOLE_INJECT_KEY = '__clear_console__' as unknown as Inject
export const SHOW_IMPORT_MAP_INJECT_KEY = '__show_import_map__' as unknown as InjectionKey<MaybeRef<boolean>>
export const THEME_INJECT_KEY = '__theme__' as unknown as InjectionKey<MaybeRef<PlaygroundTheme>>
export const SHOW_DARK_MODE_INJECT_KEY = '__show_dark_mode__' as unknown as InjectionKey<MaybeRef<boolean>>
export const PKG_CDN_INJECT_KEY = '__pkg_cdn__' as unknown as InjectionKey<MaybeRef<PlaygroundPkgCdn>>

export const DEFAULT_THEME_COLOR = '#42b883'

Expand Down Expand Up @@ -78,3 +79,11 @@ export const GET_DARK_THEME = (theme?: PlaygroundTheme) => {
...theme
} as PlaygroundTheme
}

export const DEFAULT_VUE_RUNTIME_DOM_CDN = (version: string) =>
`https://unpkg.com/@vue/runtime-dom@${version}/dist/runtime-dom.esm-browser.js`

export const DEFAULT_VUE_COMPILER_SFC_CDN = (version: string) =>
`https://unpkg.com/@vue/compiler-sfc@${version}/dist/compiler-sfc.esm-browser.js`

export const DEFAULT_ES_MODULE_SHIMS_CDN = 'https://unpkg.com/[email protected]/dist/es-module-shims.min.js'
6 changes: 5 additions & 1 deletion packages/vue-playground/src/playground/playground.type.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type {PropType, ExtractPropTypes} from 'vue'
import type {File, ImportMap} from '../core'
import {DEFAULT_TITLE} from './constants'
import type {PlaygroundLifeCycle, PlaygroundThemes} from './utils/types-helper'
import type {PlaygroundLifeCycle, PlaygroundPkgCdn, PlaygroundThemes} from './utils/types-helper'

export const playgroundProps = () =>
({
Expand All @@ -24,6 +24,10 @@ export const playgroundProps = () =>
importMap: {
type: Object as PropType<ImportMap>,
default: () => ({})
},
pkgCdn: {
type: Object as PropType<PlaygroundPkgCdn>,
default: () => ({})
}
} as const)

Expand Down
3 changes: 2 additions & 1 deletion packages/vue-playground/src/playground/playground.vue
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,8 @@ const editorRef = ref<EditorExpose>()
const store = new ReplStore({
initFiles: props.files,
initImportMap: props.importMap
initImportMap: props.importMap,
pkgCdn: props.pkgCdn
})
const showDarkMode = inject(SHOW_DARK_MODE_INJECT_KEY, undefined)
Expand Down
6 changes: 6 additions & 0 deletions packages/vue-playground/src/playground/utils/types-helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,12 @@ export interface TsLib {
filePath?: string
}

export interface PlaygroundPkgCdn {
'@vue/runtime-dom'?: (version: string, ending: string) => string
'@vue/compiler-sfc'?: (version: string, ending: string) => string
'es-module-shims'?: (version: string, ending: string) => string
}

export type PlaygroundOptions = Partial<PlaygroundProps>

export interface PlaygroundLifeCycle {
Expand Down

0 comments on commit 4fb37e4

Please sign in to comment.