Skip to content

Commit

Permalink
fix: postMessage error, fix #250
Browse files Browse the repository at this point in the history
  • Loading branch information
Akryum committed Aug 17, 2022
1 parent cefa4f9 commit 0f5b400
Show file tree
Hide file tree
Showing 4 changed files with 15 additions and 7 deletions.
1 change: 1 addition & 0 deletions examples/vue3/src/components/SharedControls.story.vue
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const state = reactive({
number: 20,
longText: 'Longer text...',
select: 'crash-bandicoot',
fn: () => { /* noop */ },
})
defineExpose({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ function syncState () {
if (iframe.value && props.variant.previewReady) {
iframe.value.contentWindow.postMessage({
type: STATE_SYNC,
state: toRawDeep(props.variant.state),
state: toRawDeep(props.variant.state, true),
})
}
}
Expand Down
2 changes: 1 addition & 1 deletion packages/histoire-app/src/app/sandbox.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ const app = createApp({
}
window.parent?.postMessage({
type: STATE_SYNC,
state: toRawDeep(value),
state: toRawDeep(value, true),
})
}, {
deep: true,
Expand Down
17 changes: 12 additions & 5 deletions packages/histoire-app/src/app/util/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { unref, isRef } from 'vue'

const isObject = (val) => val !== null && typeof val === 'object'

export function toRawDeep (val, seen = new WeakMap()) {
export function toRawDeep (val, clean = false, seen = new WeakMap()) {
const unwrappedValue = isRef(val) ? unref(val) : val

if (typeof unwrappedValue === 'symbol') {
Expand All @@ -20,18 +20,25 @@ export function toRawDeep (val, seen = new WeakMap()) {
if (Array.isArray(unwrappedValue)) {
const result = []
seen.set(unwrappedValue, result)
result.push(...unwrappedValue.map(value => toRawDeep(value, seen)))
let list = unwrappedValue.map(value => toRawDeep(value, clean, seen))
if (clean) {
list = list.filter(value => typeof value !== 'function')
}
result.push(...list)
return result
} else {
const result = {}
seen.set(unwrappedValue, result)
toRawObject(unwrappedValue, result, seen)
toRawObject(unwrappedValue, result, clean, seen)
return result
}
}

const toRawObject = (obj: Record<any, any>, target: Record<any, any>, seen = new WeakMap()) => {
const toRawObject = (obj: Record<any, any>, target: Record<any, any>, clean = false, seen = new WeakMap()) => {
Object.keys(obj).forEach((key) => {
target[key] = toRawDeep(obj[key], seen)
if (clean && typeof obj[key] === 'function') {
return
}
target[key] = toRawDeep(obj[key], clean, seen)
})
}

0 comments on commit 0f5b400

Please sign in to comment.