Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: respect devtools definition #2311

Merged
merged 2 commits into from
Jan 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 27 additions & 6 deletions src/emit.ts
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
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
: {})
)
}