Skip to content

Commit

Permalink
feat: respect devtools definition (#2311)
Browse files Browse the repository at this point in the history
Fixes #2310
  • Loading branch information
webfansplz committed Jan 23, 2024
1 parent ec63f82 commit c3cc713
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 6 deletions.
33 changes: 27 additions & 6 deletions src/emit.ts
Expand Up @@ -4,6 +4,7 @@ import {
ComponentPublicInstance,
ComponentInternalInstance
} from 'vue'
import { getGlobalThis } from './utils'

type Events<T = unknown> = Record<number, Record<string, T[]>>

Expand All @@ -28,18 +29,38 @@ export function emitted<T = unknown>(
}

export const attachEmitListener = () => {
// use devtools to capture this "emit"
setDevtoolsHook(createDevTools(), {})
const target = getGlobalThis()
// override emit to capture events when devtools is defined
if (target.__VUE_DEVTOOLS_GLOBAL_HOOK__) {
const _emit = target.__VUE_DEVTOOLS_GLOBAL_HOOK__.emit
target.__VUE_DEVTOOLS_GLOBAL_HOOK__.emit = (
eventType: any,
...payload: any[]
) => {
_emit.call(target.__VUE_DEVTOOLS_GLOBAL_HOOK__, eventType, ...payload)
captureDevtoolsVueComponentEmitEvent(eventType, payload)
}
} else {
// use devtools to capture this "emit"
setDevtoolsHook(createDevTools(), {})
}
}

function captureDevtoolsVueComponentEmitEvent(
eventType: string,
payload: any[]
) {
if (eventType === DevtoolsHooks.COMPONENT_EMIT) {
const [_, componentVM, event, eventArgs] = payload
recordEvent(componentVM, event, eventArgs)
}
}

// devtools hook only catches Vue component custom events
function createDevTools(): any {
return {
emit(eventType, ...payload) {
if (eventType !== DevtoolsHooks.COMPONENT_EMIT) return

const [_, componentVM, event, eventArgs] = payload
recordEvent(componentVM, event, eventArgs)
captureDevtoolsVueComponentEmitEvent(eventType, payload)
}
} as Partial<typeof devtools>
}
Expand Down
17 changes: 17 additions & 0 deletions src/utils.ts
Expand Up @@ -235,3 +235,20 @@ export function isScriptSetup(
vm && (vm.$ as unknown as { setupState: any }).setupState.__isScriptSetup
)
}

let _globalThis: any
export const getGlobalThis = (): any => {
return (
_globalThis ||
(_globalThis =
typeof globalThis !== 'undefined'
? globalThis
: typeof self !== 'undefined'
? self
: typeof window !== 'undefined'
? window
: typeof global !== 'undefined'
? global
: {})
)
}

0 comments on commit c3cc713

Please sign in to comment.