Skip to content

Commit

Permalink
refactor: 💡 path sync
Browse files Browse the repository at this point in the history
  • Loading branch information
WeilinerL committed Nov 20, 2024
1 parent 0b45856 commit 2e3350a
Show file tree
Hide file tree
Showing 6 changed files with 86 additions and 22 deletions.
17 changes: 6 additions & 11 deletions demo/app.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import mpx, { createApp } from '@mpxjs/core'
import { onChildPathchange } from '@mpxjs/vuese-website/dist/iframe-sync'
import apiProxy from '@mpxjs/api-proxy'

mpx.use(apiProxy, { usePromise: true })
Expand All @@ -9,15 +10,9 @@ createApp({})
const isIframe = __mpx_mode__ === 'web' && window.parent !== window

if (isIframe) {
let prevPath = ''
const handleMessage = (e) => {
const { to } = (typeof e.data === 'object' ? e.data : {}) as any
if (to !== undefined && to !== prevPath) {
mpx.redirectTo({
url: `/pages/${to && to !== 'intro' ? `${to}/` : ''}index`
})
prevPath = to
}
}
window.addEventListener('message', handleMessage)
onChildPathchange((to) => {
mpx.redirectTo({
url: `/pages/${to && to !== 'intro' ? `${to}/` : ''}index`
})
})
}
5 changes: 2 additions & 3 deletions demo/pages/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import mpx, { createPage, ref, onMounted, onUnmounted } from '@mpxjs/core'
import { syncPathToChild } from '@mpxjs/vuese-website/dist/iframe-sync'
import demoConfig from '../common/config'

const SCROLL_KEY = '___scoll_top___'
Expand All @@ -10,9 +11,7 @@ createPage({
const component = `${item.replace(/\(.*\)/, '')}`
const route = `./${component}/index`
if (__mpx_mode__ === 'web' && window.parent !== window) {
window.parent.postMessage({
component
}, '*')
syncPathToChild(component)
return
}
mpx.navigateTo({
Expand Down
44 changes: 44 additions & 0 deletions packages/website/lib/iframe-sync.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/**
* 同步路由到主窗口
* @param iframe
* @param to
*/
export const syncPathToParent = (iframe: HTMLIFrameElement, to: string) => {
iframe?.contentWindow?.postMessage({
value: to
}, '*')
}

const cache = {
prevPath: ''
}
/**
* 监听子路由的变化
* @param callback
* @returns
*/
export const onChildPathchange = (callback?: (path: string) => void): () => void => {
const handleMessage = (e: { data: { value: string } }) => {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const { value } = (typeof e.data === 'object' ? e.data || {} : {})
if (value !== undefined && value !== cache.prevPath) {
callback?.(value)
cache.prevPath = value
}
}
window.addEventListener('message', handleMessage)
return () => {
window.removeEventListener('message', handleMessage)
}
}

/**
* 同步路由到子窗口
* @param to
*/
export const syncPathToChild = (to: string) => {
window.parent.postMessage({
value: to
}, '*')
}
24 changes: 24 additions & 0 deletions packages/website/rollup.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
const path = require('path')
const ts = require('rollup-plugin-typescript2')

const generateConfig = (input, output, external = [], plugins = []) => {
return {
input,
output,
external,
plugins: [
ts({
tsconfig: path.resolve(__dirname, './tsconfig.json')
}),
...plugins,
],
}
}

module.exports = [
generateConfig(path.resolve(__dirname, './lib/iframe-sync.ts'), {
file: path.resolve(__dirname, './dist/iframe-sync.js'),
format: 'es',
name: 'websiteIframeSync'
})
]
14 changes: 6 additions & 8 deletions packages/website/theme/components/Preview.vue
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
import { throttle } from 'lodash-es'
import { ref, onMounted, computed, watch, onUnmounted } from 'vue'
import { useRouter, useRoute, useData } from 'vitepress'
import { syncPathToParent } from '@mpxjs/vuese-website/dist/iframe-sync'
const COMPONENT_DIR_NAME = 'components'
Expand Down Expand Up @@ -62,10 +63,7 @@ const title = computed(() => {
const iframeRef = ref()
const syncChildPath = to => {
iframeRef.value?.contentWindow.postMessage({
to: getComponentName(),
origin: route.path
}, '*')
syncPathToParent(iframeRef.value, getComponentName())
}
const isShowBack = ref(false)
Expand All @@ -83,18 +81,18 @@ watch(() => route.path, (newPath, oldPath) => {
})
const handleMessage = e => {
if (e.data?.component !== undefined) {
if (e.data?.value !== undefined) {
const data = e.data
if (data.component) {
router.go(`${site.value.base}${COMPONENT_DIR_NAME}/${data.component}.html`)
if (data.value) {
router.go(`${site.value.base}${COMPONENT_DIR_NAME}/${data.value}.html`)
return
}
const findComponent = list => {
if (!Array.isArray(list)) {
return null
}
for (const item of list) {
if (item.path?.endsWith(data.component)) {
if (item.path?.endsWith(data.value)) {
return item
}
const target = findComponent(item.children)
Expand Down
4 changes: 4 additions & 0 deletions scripts/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ function makeBuild() {
if (pkgMeta.private) return
await fs.remove(`${pkgDir}/dist`)
await execa('rollup', ['-c', '--environment', `PKG_DIR:${pkgDirName}`], {})
const config = `${pkgDir}/rollup.config.js`
if (fs.pathExistsSync(config)) {
await execa('rollup', ['--config', config])
}

const dtsOutDir = `${pkgDir}/${pkgMeta.types}`

Expand Down

0 comments on commit 2e3350a

Please sign in to comment.