From 91f8ef494dae7750cbe60c6225303835803ec4c6 Mon Sep 17 00:00:00 2001 From: Alex <49969959+alexzhang1030@users.noreply.github.com> Date: Tue, 11 Jun 2024 21:47:43 +0800 Subject: [PATCH] feat(core): expose activeComponent to window (#427) --- .../src/core/plugin/components.ts | 3 +++ packages/devtools-kit/src/core/vm/index.ts | 26 +++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 packages/devtools-kit/src/core/vm/index.ts diff --git a/packages/devtools-kit/src/core/plugin/components.ts b/packages/devtools-kit/src/core/plugin/components.ts index a8256ae5..1ac7e9b6 100644 --- a/packages/devtools-kit/src/core/plugin/components.ts +++ b/packages/devtools-kit/src/core/plugin/components.ts @@ -6,6 +6,7 @@ import { DevToolsV6PluginAPIHookKeys, activeAppRecord, devtoolsContext, devtools import { ComponentWalker } from '../../core/component/tree/walker' import { getInstanceState } from '../../core/component/state' import { editState } from '../../core/component/state/editor' +import { exposeInstanceToWindow } from '../vm' const INSPECTOR_ID = 'components' @@ -58,6 +59,8 @@ export function createComponentsDevToolsPlugin(app: App): [PluginDescriptor, Plu }, DevToolsV6PluginAPIHookKeys.INSPECT_COMPONENT) // @ts-expect-error skip type @TODO payload.state = result + + exposeInstanceToWindow(componentInstance) } }) diff --git a/packages/devtools-kit/src/core/vm/index.ts b/packages/devtools-kit/src/core/vm/index.ts new file mode 100644 index 00000000..c79c99bf --- /dev/null +++ b/packages/devtools-kit/src/core/vm/index.ts @@ -0,0 +1,26 @@ +const MAX_$VM = 10 +const $vmQueue: any[] = [] + +// Expose instance data to window +// Copied from https://github.com/vuejs/devtools/blob/f03590025b0b4910cf539531c91384be51a8f8fa/packages/app-backend-core/src/component.ts#L57-L72 +export function exposeInstanceToWindow(componentInstance: any) { + const win = window as any + if (typeof win === 'undefined') + return + + if (!componentInstance) + return + + win.$vm = componentInstance + + // $vm0, $vm1, $vm2, ... + if ($vmQueue[0] !== componentInstance) { + if ($vmQueue.length >= MAX_$VM) { + $vmQueue.pop() + } + for (let i = $vmQueue.length; i > 0; i--) { + win[`$vm${i}`] = $vmQueue[i] = $vmQueue[i - 1] + } + win.$vm0 = $vmQueue[0] = componentInstance + } +}