@opentiny/next-sdk 0.4.0 → 0.4.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/agent/AgentModelProvider.ts +78 -81
- package/agent/type.ts +6 -9
- package/agent/utils/getAISDKTools.ts +0 -1
- package/agent/utils/getBuiltinMcpTools.ts +7 -7
- package/core.ts +0 -3
- package/dist/SimulatorMask-BHVXyogh-iNUb4dyF.js +361 -0
- package/dist/agent/type.d.ts +4 -12
- package/dist/agent/utils/getBuiltinMcpTools.d.ts +3 -3
- package/dist/core.d.ts +0 -1
- package/dist/core.js +16 -17
- package/dist/index-CXK8CcKq.js +6076 -0
- package/dist/index.d.ts +0 -3
- package/dist/index.js +57 -4969
- package/dist/{initialize-builtin-WebMCP-HgObT902.js → initialize-builtin-WebMCP-rALfqS-o.js} +1166 -1056
- package/dist/page-tools/a11y/build.d.ts +11 -0
- package/dist/page-tools/a11y/constants.d.ts +9 -0
- package/dist/page-tools/a11y/search.d.ts +17 -0
- package/dist/page-tools/a11y/types.d.ts +104 -0
- package/dist/page-tools/a11y/utils.d.ts +34 -0
- package/dist/page-tools/a11y/vnode.d.ts +37 -0
- package/dist/page-tools/a11y-tree.d.ts +8 -99
- package/dist/page-tools/constants.d.ts +22 -0
- package/dist/page-tools/context.d.ts +28 -0
- package/dist/page-tools/handlers/browserState.d.ts +8 -0
- package/dist/page-tools/handlers/click.d.ts +8 -0
- package/dist/page-tools/handlers/executeJavascript.d.ts +8 -0
- package/dist/page-tools/handlers/fill.d.ts +8 -0
- package/dist/page-tools/handlers/scroll.d.ts +8 -0
- package/dist/page-tools/handlers/searchTree.d.ts +8 -0
- package/dist/page-tools/handlers/select.d.ts +8 -0
- package/dist/page-tools/page-agent-highlight/index.d.ts +9 -0
- package/dist/page-tools/page-agent-mask/SimulatorMask.d.ts +14 -0
- package/dist/page-tools/page-agent-mask/checkDarkMode.d.ts +5 -0
- package/dist/page-tools/page-agent-tool.d.ts +3 -8
- package/dist/page-tools/schema.d.ts +43 -0
- package/dist/page-tools/utils/dom.d.ts +6 -0
- package/dist/page-tools/utils/scroll.d.ts +15 -0
- package/dist/runtime.d.ts +4 -0
- package/dist/runtime.js +744 -0
- package/dist/utils/builtinProxy.d.ts +1 -1
- package/index.ts +0 -5
- package/package.json +6 -17
- package/page-tools/a11y/build.ts +70 -0
- package/page-tools/a11y/constants.ts +110 -0
- package/page-tools/a11y/search.ts +129 -0
- package/page-tools/a11y/types.ts +108 -0
- package/page-tools/a11y/utils.ts +266 -0
- package/page-tools/a11y/vnode.ts +229 -0
- package/page-tools/a11y-tree.ts +8 -527
- package/page-tools/bridge.ts +1 -1
- package/page-tools/constants.ts +72 -0
- package/page-tools/context.ts +13 -0
- package/page-tools/handlers/browserState.ts +12 -0
- package/page-tools/handlers/click.ts +26 -0
- package/page-tools/handlers/executeJavascript.ts +22 -0
- package/page-tools/handlers/fill.ts +60 -0
- package/page-tools/handlers/scroll.ts +66 -0
- package/page-tools/handlers/searchTree.ts +30 -0
- package/page-tools/handlers/select.ts +34 -0
- package/page-tools/page-agent-highlight/index.ts +198 -0
- package/page-tools/page-agent-mask/SimulatorMask.module.css +14 -0
- package/page-tools/page-agent-mask/SimulatorMask.ts +279 -0
- package/page-tools/page-agent-mask/checkDarkMode.ts +181 -0
- package/page-tools/page-agent-mask/cursor-border.svg +3 -0
- package/page-tools/page-agent-mask/cursor-fill.svg +5 -0
- package/page-tools/page-agent-mask/cursor.module.css +70 -0
- package/page-tools/page-agent-prompt.md +34 -18
- package/page-tools/page-agent-tool.ts +104 -152
- package/page-tools/schema.ts +51 -0
- package/page-tools/utils/dom.ts +155 -0
- package/page-tools/utils/scroll.ts +58 -0
- package/runtime.ts +13 -0
- package/utils/builtinProxy.ts +45 -13
- package/vite.config.runtime.ts +22 -0
- package/vite.config.ts +52 -8
- package/McpSdk.ts +0 -14
- package/WebAgent.ts +0 -5
- package/WebMcp.ts +0 -26
- package/Zod.ts +0 -1
- package/dist/McpSdk.d.ts +0 -14
- package/dist/SimulatorMask-BHVXyogh-BFEGpD5S.js +0 -1048
- package/dist/SimulatorMask-BHVXyogh-CCYbrb84.js +0 -801
- package/dist/WebAgent.d.ts +0 -5
- package/dist/WebMcp.d.ts +0 -23
- package/dist/Zod.d.ts +0 -1
- package/dist/index.es.dev.js +0 -59017
- package/dist/index.es.js +0 -46795
- package/dist/index.umd.dev.js +0 -60355
- package/dist/index.umd.js +0 -1248
- package/dist/mcpsdk@1.25.3.dev.js +0 -22780
- package/dist/mcpsdk@1.25.3.es.dev.js +0 -22778
- package/dist/mcpsdk@1.25.3.es.js +0 -16960
- package/dist/mcpsdk@1.25.3.js +0 -48
- package/dist/transport/ExtensionClientTransport.d.ts +0 -24
- package/dist/transport/ExtensionContentServerTransport.d.ts +0 -39
- package/dist/transport/ExtensionPageServerTransport.d.ts +0 -36
- package/dist/transport/messages.d.ts +0 -9
- package/dist/vite.config.mcpSdk.d.ts +0 -2
- package/dist/vite.config.webAgent.d.ts +0 -2
- package/dist/vite.config.webMcp.d.ts +0 -2
- package/dist/vite.config.webMcpFull.d.ts +0 -2
- package/dist/vite.config.zod.d.ts +0 -2
- package/dist/webagent.dev.js +0 -49360
- package/dist/webagent.es.dev.js +0 -49071
- package/dist/webagent.es.js +0 -39219
- package/dist/webagent.js +0 -642
- package/dist/webmcp-full.dev.js +0 -31336
- package/dist/webmcp-full.es.dev.js +0 -30283
- package/dist/webmcp-full.es.js +0 -22889
- package/dist/webmcp-full.js +0 -645
- package/dist/webmcp.dev.js +0 -9572
- package/dist/webmcp.es.dev.js +0 -8518
- package/dist/webmcp.es.js +0 -6727
- package/dist/webmcp.js +0 -602
- package/dist/zod@3.25.76.dev.js +0 -4037
- package/dist/zod@3.25.76.es.dev.js +0 -4033
- package/dist/zod@3.25.76.es.js +0 -2945
- package/dist/zod@3.25.76.js +0 -1
- package/transport/ExtensionClientTransport.ts +0 -100
- package/transport/ExtensionContentServerTransport.ts +0 -162
- package/transport/ExtensionPageServerTransport.ts +0 -149
- package/transport/messages.ts +0 -63
- package/vite-build-tsc.ts +0 -63
- package/vite-env.d.ts +0 -10
- package/vite.config.mcpSdk.ts +0 -28
- package/vite.config.webAgent.ts +0 -19
- package/vite.config.webMcp.ts +0 -40
- package/vite.config.webMcpFull.ts +0 -19
- package/vite.config.zod.ts +0 -23
- /package/dist/{vite-build-tsc.d.ts → vite.config.runtime.d.ts} +0 -0
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
import type { ActionContext } from '../context'
|
|
2
|
+
|
|
3
|
+
export async function handleExecuteJavascript(args: any, ctx: ActionContext) {
|
|
4
|
+
if (!args.script) return ctx.errContent('脚本执行异常: 缺少javascript代码')
|
|
5
|
+
// eslint-disable-next-line no-new-func
|
|
6
|
+
// 方式1:将脚本包裹在 async IIFE 中执行,允许 return 语句
|
|
7
|
+
let result = await new Function(`return (async () => { ${args.script} })()`)()
|
|
8
|
+
// 方式2:若 result 为 undefined(脚本没有 return),降级尝试以表达式方式求值
|
|
9
|
+
// 场景:Agent 写了 "Array.from(...).map(...)" 但没有 return 关键字
|
|
10
|
+
if (result === undefined) {
|
|
11
|
+
try {
|
|
12
|
+
// eslint-disable-next-line no-new-func
|
|
13
|
+
result = await new Function(`return (async () => (${args.script}))()`)()
|
|
14
|
+
} catch {
|
|
15
|
+
// 表达式求值也失败(如含 await/let/const 等语句),保持 undefined
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
await ctx.pageController.hideMask()
|
|
19
|
+
return {
|
|
20
|
+
content: [{ type: 'text' as const, text: `脚本执行结果: ${JSON.stringify(result)}` }]
|
|
21
|
+
}
|
|
22
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { inputTextElement } from '@page-agent/page-controller'
|
|
2
|
+
import { dispatchComposedEvents, isInShadowDom, waitForDomSettled } from '../utils/dom'
|
|
3
|
+
import type { ActionContext } from '../context'
|
|
4
|
+
|
|
5
|
+
export async function handleFill(args: any, ctx: ActionContext) {
|
|
6
|
+
const mode = args.responseMode ?? 'diff'
|
|
7
|
+
if (args.index === undefined || typeof args.text !== 'string') return ctx.errContent('填写结果: 缺少元素索引或文本内容')
|
|
8
|
+
const el = ctx.getRefMap().get(args.index)
|
|
9
|
+
if (!el) return ctx.refreshOnStaleRef('填写', args.index)
|
|
10
|
+
|
|
11
|
+
let targetEl = el
|
|
12
|
+
if (!(targetEl instanceof HTMLInputElement) && !(targetEl instanceof HTMLTextAreaElement)) {
|
|
13
|
+
// querySelector 不穿透 shadow boundary,对 shadow host 补查其 shadowRoot
|
|
14
|
+
const innerInput = el.querySelector('input, textarea')
|
|
15
|
+
?? (el.shadowRoot?.querySelector('input, textarea') as HTMLElement | null)
|
|
16
|
+
if (innerInput) {
|
|
17
|
+
targetEl = innerInput as HTMLElement
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
if (targetEl instanceof HTMLInputElement && targetEl.readOnly) {
|
|
22
|
+
targetEl.value = args.text
|
|
23
|
+
// composed:true 确保事件穿透 shadow boundary,事件委托框架可捕获
|
|
24
|
+
dispatchComposedEvents(targetEl, 'input', 'change', 'blur')
|
|
25
|
+
} else {
|
|
26
|
+
// 优先尝试标准方式(支持 contenteditable、普通 input/textarea)
|
|
27
|
+
let fillSuccess = false
|
|
28
|
+
try {
|
|
29
|
+
await inputTextElement(targetEl, args.text)
|
|
30
|
+
fillSuccess = true
|
|
31
|
+
} catch (fillErr) {
|
|
32
|
+
// inputTextElement 失败时(如 Angular/React 组件包装的密码框),
|
|
33
|
+
// 降级使用原生 input value 描述符触发框架变更检测
|
|
34
|
+
const nativeInputValueSetter = Object.getOwnPropertyDescriptor(
|
|
35
|
+
(targetEl instanceof HTMLTextAreaElement ? HTMLTextAreaElement : HTMLInputElement).prototype,
|
|
36
|
+
'value'
|
|
37
|
+
)?.set
|
|
38
|
+
if (nativeInputValueSetter && (targetEl instanceof HTMLInputElement || targetEl instanceof HTMLTextAreaElement)) {
|
|
39
|
+
nativeInputValueSetter.call(targetEl, args.text)
|
|
40
|
+
// 发送完整事件序列,触发 Angular ngModel / React 合成事件的变更检测
|
|
41
|
+
targetEl.dispatchEvent(new Event('focus', { bubbles: true, composed: true }))
|
|
42
|
+
targetEl.dispatchEvent(new Event('input', { bubbles: true, composed: true }))
|
|
43
|
+
targetEl.dispatchEvent(new Event('change', { bubbles: true, composed: true }))
|
|
44
|
+
targetEl.dispatchEvent(new Event('blur', { bubbles: true, composed: true }))
|
|
45
|
+
fillSuccess = true
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
if (!fillSuccess) {
|
|
49
|
+
return ctx.errContent(`填写结果: 无法填写元素 ${args.index},元素不是 input、textarea 或 contenteditable`)
|
|
50
|
+
}
|
|
51
|
+
// shadow DOM 内元素:inputTextElement 派发的合成事件 composed:false,
|
|
52
|
+
// 补发 composed:true 事件确保事件委托框架(如 React)能收到
|
|
53
|
+
if (isInShadowDom(targetEl)) {
|
|
54
|
+
dispatchComposedEvents(targetEl, 'input', 'change')
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
// 等待框架异步插入的校验错误/条件渲染内容稳定后再采集状态
|
|
58
|
+
await waitForDomSettled()
|
|
59
|
+
return ctx.buildBrowserStateResponse(mode)
|
|
60
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { getScrollInfo, waitForScrollEnd } from '../utils/scroll'
|
|
2
|
+
import type { ActionContext } from '../context'
|
|
3
|
+
|
|
4
|
+
export async function handleScroll(args: any, ctx: ActionContext) {
|
|
5
|
+
const mode = args.responseMode ?? 'diff'
|
|
6
|
+
if (args.down === undefined && args.right === undefined) return ctx.errContent('滚动结果: 缺少滚动方向参数')
|
|
7
|
+
|
|
8
|
+
// 确定滚动目标(有 index 时滚动该元素容器,否则滚动整个文档)
|
|
9
|
+
let scrollTarget: Element | Window = window
|
|
10
|
+
if (args.index !== undefined) {
|
|
11
|
+
const el = ctx.getRefMap().get(args.index)
|
|
12
|
+
if (!el) return ctx.refreshOnStaleRef('滚动', args.index)
|
|
13
|
+
scrollTarget = el
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
// 滚动前快照
|
|
17
|
+
const before = getScrollInfo(scrollTarget)
|
|
18
|
+
|
|
19
|
+
if (args.right !== undefined) {
|
|
20
|
+
const pixels = args.pixels ?? 300
|
|
21
|
+
scrollTarget.scrollBy({ left: args.right ? pixels : -pixels, behavior: 'smooth' })
|
|
22
|
+
} else {
|
|
23
|
+
const pixels = args.pixels ?? Math.round((args.numPages ?? 1) * window.innerHeight)
|
|
24
|
+
scrollTarget.scrollBy({ top: args.down ? pixels : -pixels, behavior: 'smooth' })
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// 等待滚动动画完成后再采集状态(scrollend + 超时兜底)
|
|
28
|
+
await waitForScrollEnd(scrollTarget)
|
|
29
|
+
|
|
30
|
+
// 滚动后快照,计算实际位移
|
|
31
|
+
const after = getScrollInfo(scrollTarget)
|
|
32
|
+
const deltaY = Math.round(after.scrollY - before.scrollY)
|
|
33
|
+
const deltaX = Math.round(after.scrollX - before.scrollX)
|
|
34
|
+
const isHorizontal = args.right !== undefined
|
|
35
|
+
|
|
36
|
+
let scrollMsg: string
|
|
37
|
+
if (Math.abs(deltaY) < 1 && Math.abs(deltaX) < 1) {
|
|
38
|
+
// 实际未发生位移,说明已到达边界
|
|
39
|
+
if (isHorizontal) {
|
|
40
|
+
scrollMsg = args.right ? '⚠️ 已到达右边界,无法继续向右滚动' : '⚠️ 已到达左边界,无法继续向左滚动'
|
|
41
|
+
} else {
|
|
42
|
+
scrollMsg = args.down ? '⚠️ 已到达底部,无法继续向下滚动' : '⚠️ 已到达顶部,无法继续向上滚动'
|
|
43
|
+
}
|
|
44
|
+
} else {
|
|
45
|
+
const axis = isHorizontal ? `水平滚动 ${deltaX}px` : `垂直滚动 ${deltaY}px`
|
|
46
|
+
let boundary = ''
|
|
47
|
+
if (isHorizontal) {
|
|
48
|
+
if (args.right && after.atRight) boundary = ',已到达右边界'
|
|
49
|
+
else if (!args.right && after.atLeft) boundary = ',已到达左边界'
|
|
50
|
+
} else {
|
|
51
|
+
if (args.down && after.atBottom) boundary = ',已到达底部'
|
|
52
|
+
else if (!args.down && after.atTop) boundary = ',已到达顶部'
|
|
53
|
+
}
|
|
54
|
+
scrollMsg = `✅ ${axis}${boundary}`
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// 附加位置信息(参考 page-agent getPageInfo 格式)
|
|
58
|
+
const posInfo = args.right !== undefined
|
|
59
|
+
? `当前水平滚动位置: scrollX=${Math.round(after.scrollX)}px,左侧 ${after.pagesAbove.toFixed(1)} 屏,右侧 ${after.pagesBelow.toFixed(1)} 屏`
|
|
60
|
+
: `当前滚动位置: scrollY=${Math.round(after.scrollY)}px,上方 ${after.pagesAbove.toFixed(1)} 屏,下方 ${after.pagesBelow.toFixed(1)} 屏`
|
|
61
|
+
const scrollResult = `[滚动结果] ${scrollMsg}\n${posInfo}`
|
|
62
|
+
|
|
63
|
+
const stateResult = await ctx.buildBrowserStateResponse(mode)
|
|
64
|
+
stateResult.content[0].text = `${scrollResult}\n\n${stateResult.content[0].text}`
|
|
65
|
+
return stateResult
|
|
66
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { searchA11yTree } from '../a11y-tree'
|
|
2
|
+
import { detectPageDialog, detectValidationErrors } from '../utils/dom'
|
|
3
|
+
import { DEFAULT_ERROR_SELECTORS } from '../constants'
|
|
4
|
+
import type { ActionContext } from '../context'
|
|
5
|
+
|
|
6
|
+
export async function handleSearchTree(args: any, ctx: ActionContext) {
|
|
7
|
+
if (!args.query) return ctx.errContent('搜索失败: 缺少 query 参数')
|
|
8
|
+
const blacklist = (window.__webmcpcli_interactiveBlacklist ?? []) as Element[]
|
|
9
|
+
const whitelist = (window.__webmcpcli_interactiveWhitelist ?? []) as Element[]
|
|
10
|
+
const exposedAttributes = (window.__webmcpcli_exposedAttributes ?? []) as string[]
|
|
11
|
+
const result = searchA11yTree(args.query, document.body, blacklist, whitelist, {
|
|
12
|
+
contextLines: args.contextLines,
|
|
13
|
+
maxMatches: args.maxMatches,
|
|
14
|
+
exposedAttributes,
|
|
15
|
+
errorSelectors: (window.__webmcpcli_errorSelectors ?? DEFAULT_ERROR_SELECTORS).join(', '),
|
|
16
|
+
})
|
|
17
|
+
|
|
18
|
+
ctx.setRefMap(result.refMap)
|
|
19
|
+
ctx.stateCache.update(window.location.href, result.yaml)
|
|
20
|
+
|
|
21
|
+
await ctx.pageController.hideMask()
|
|
22
|
+
// 检测页面弹窗/遮罩层,帮助 AI 发现可能遮挡目标的确认弹窗
|
|
23
|
+
const dialogAlert = detectPageDialog()
|
|
24
|
+
// 检测表单校验错误,提醒 AI 优先修复
|
|
25
|
+
const validationErrors = detectValidationErrors()
|
|
26
|
+
const alerts = `${dialogAlert}${validationErrors}`
|
|
27
|
+
return {
|
|
28
|
+
content: [{ type: 'text' as const, text: alerts ? `${alerts}\n${result.text}` : result.text }]
|
|
29
|
+
}
|
|
30
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import { selectOptionElement } from '@page-agent/page-controller'
|
|
2
|
+
import { dispatchComposedEvents, isInShadowDom, waitForDomSettled } from '../utils/dom'
|
|
3
|
+
import type { ActionContext } from '../context'
|
|
4
|
+
|
|
5
|
+
export async function handleSelect(args: any, ctx: ActionContext) {
|
|
6
|
+
const mode = args.responseMode ?? 'diff'
|
|
7
|
+
if (args.index === undefined || typeof args.text !== 'string') return ctx.errContent('选择结果: 缺少元素索引或文本内容')
|
|
8
|
+
let el = ctx.getRefMap().get(args.index) as HTMLSelectElement | HTMLElement | undefined
|
|
9
|
+
if (!el) return ctx.refreshOnStaleRef('选择', args.index)
|
|
10
|
+
// 若 ref 指向 shadow host,解析其内部真正的 <select>(与 fill 一致)
|
|
11
|
+
let targetSelect: HTMLSelectElement | null = null
|
|
12
|
+
if (el instanceof HTMLSelectElement) {
|
|
13
|
+
targetSelect = el
|
|
14
|
+
} else {
|
|
15
|
+
const innerSelect = el.querySelector('select')
|
|
16
|
+
?? (el.shadowRoot?.querySelector('select') as HTMLSelectElement | null)
|
|
17
|
+
if (innerSelect) {
|
|
18
|
+
targetSelect = innerSelect
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
if (!targetSelect) {
|
|
23
|
+
return ctx.errContent(`选择结果: 无法选择元素 ${args.index},未找到对应的 <select> 元素`)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
await selectOptionElement(targetSelect, args.text)
|
|
27
|
+
// shadow DOM 内元素:补发 composed:true 的 change 事件
|
|
28
|
+
if (isInShadowDom(targetSelect)) {
|
|
29
|
+
dispatchComposedEvents(targetSelect, 'change')
|
|
30
|
+
}
|
|
31
|
+
// 等待框架异步插入的校验错误/条件渲染内容稳定后再采集状态
|
|
32
|
+
await waitForDomSettled()
|
|
33
|
+
return ctx.buildBrowserStateResponse(mode)
|
|
34
|
+
}
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
import { type RefMap } from '../a11y-tree'
|
|
2
|
+
|
|
3
|
+
export const HIGHLIGHT_CONTAINER_ID = 'webmcpcli-highlight-container'
|
|
4
|
+
export const HIGHLIGHT_CONTAINER_STYLE_ID = 'webmcpcli-highlight-container-style'
|
|
5
|
+
const colors = [
|
|
6
|
+
'#FF0000',
|
|
7
|
+
'#00FF00',
|
|
8
|
+
'#0000FF',
|
|
9
|
+
'#FFA500',
|
|
10
|
+
'#800080',
|
|
11
|
+
'#008080',
|
|
12
|
+
'#FF69B4',
|
|
13
|
+
'#4B0082',
|
|
14
|
+
'#FF4500',
|
|
15
|
+
'#2E8B57',
|
|
16
|
+
'#DC143C',
|
|
17
|
+
'#4682B4'
|
|
18
|
+
]
|
|
19
|
+
// border + label opacity
|
|
20
|
+
const opacity = Math.floor(0.3 * 255)
|
|
21
|
+
.toString(16)
|
|
22
|
+
.padStart(2, '0')
|
|
23
|
+
|
|
24
|
+
const injectStyles = `
|
|
25
|
+
#${HIGHLIGHT_CONTAINER_ID} {
|
|
26
|
+
position: fixed;
|
|
27
|
+
pointer-events: none;
|
|
28
|
+
top: 0;
|
|
29
|
+
left: 0;
|
|
30
|
+
width: 100%;
|
|
31
|
+
height: 100%;
|
|
32
|
+
z-index: 2147483640;
|
|
33
|
+
background-color: transparent;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
#${HIGHLIGHT_CONTAINER_ID} div {
|
|
37
|
+
position: fixed;
|
|
38
|
+
pointer-events: none;
|
|
39
|
+
background-color: transparent;
|
|
40
|
+
text-align: right;
|
|
41
|
+
box-sizing: border-box;
|
|
42
|
+
border-radius: 4px;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
#${HIGHLIGHT_CONTAINER_ID} div span {
|
|
46
|
+
display: inline-block;
|
|
47
|
+
color: #fff;
|
|
48
|
+
padding: 0 2px;
|
|
49
|
+
border-radius: 4px;
|
|
50
|
+
}
|
|
51
|
+
`
|
|
52
|
+
|
|
53
|
+
function isElementViewport(element: HTMLElement) {
|
|
54
|
+
const rect = element.getBoundingClientRect()
|
|
55
|
+
return (
|
|
56
|
+
rect.top >= 0 &&
|
|
57
|
+
rect.left >= 0 &&
|
|
58
|
+
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
|
|
59
|
+
rect.right <= (window.innerWidth || document.documentElement.clientWidth)
|
|
60
|
+
)
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const doHighlight = (refMap: RefMap, parentIframe: HTMLIFrameElement | null = null) => {
|
|
64
|
+
// 1、保证注入脚本
|
|
65
|
+
if (!document.head.querySelector(`#${HIGHLIGHT_CONTAINER_STYLE_ID}`)) {
|
|
66
|
+
const style = document.head.appendChild(document.createElement('style'))
|
|
67
|
+
style.id = HIGHLIGHT_CONTAINER_STYLE_ID
|
|
68
|
+
style.textContent = injectStyles
|
|
69
|
+
document.head.appendChild(style)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// 2、保证contrainer( container 在 a11y 时已加入黑名单)
|
|
73
|
+
let container = document.getElementById(HIGHLIGHT_CONTAINER_ID)
|
|
74
|
+
if (!container) {
|
|
75
|
+
container = document.createElement('div')
|
|
76
|
+
container.id = HIGHLIGHT_CONTAINER_ID
|
|
77
|
+
|
|
78
|
+
document.body.appendChild(container)
|
|
79
|
+
} else {
|
|
80
|
+
container.innerHTML = ''
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
let iframeOffset = { x: 0, y: 0 }
|
|
84
|
+
if (parentIframe) {
|
|
85
|
+
const iframeRect = parentIframe.getBoundingClientRect() // Keep getBoundingClientRect for iframe offset
|
|
86
|
+
iframeOffset.x = iframeRect.left
|
|
87
|
+
iframeOffset.y = iframeRect.top
|
|
88
|
+
}
|
|
89
|
+
const fragment = document.createDocumentFragment()
|
|
90
|
+
const overlays = []
|
|
91
|
+
|
|
92
|
+
// 3、 遍历 refMap
|
|
93
|
+
for (const [index, el] of refMap.entries()) {
|
|
94
|
+
if (!isElementViewport(el)) continue
|
|
95
|
+
|
|
96
|
+
const color = colors[index % colors.length]
|
|
97
|
+
const textColor = color + opacity
|
|
98
|
+
|
|
99
|
+
const rect = el.getBoundingClientRect()
|
|
100
|
+
if (rect.width === 0 || rect.height === 0) continue
|
|
101
|
+
|
|
102
|
+
const overlay = document.createElement('div')
|
|
103
|
+
overlay.style.border = `2px solid ${textColor}`
|
|
104
|
+
|
|
105
|
+
const top = rect.top + iframeOffset.y
|
|
106
|
+
const left = rect.left + iframeOffset.x
|
|
107
|
+
|
|
108
|
+
overlay.style.top = `${top}px`
|
|
109
|
+
overlay.style.left = `${left}px`
|
|
110
|
+
overlay.style.width = `${rect.width}px`
|
|
111
|
+
overlay.style.height = `${rect.height}px`
|
|
112
|
+
|
|
113
|
+
// 文字
|
|
114
|
+
const text = document.createElement('span')
|
|
115
|
+
text.style.backgroundColor = textColor
|
|
116
|
+
text.style.height = `${rect.height - 4}px`
|
|
117
|
+
text.style.lineHeight = `${rect.height - 4}px`
|
|
118
|
+
text.textContent = index.toString()
|
|
119
|
+
overlay.appendChild(text)
|
|
120
|
+
|
|
121
|
+
fragment.appendChild(overlay)
|
|
122
|
+
overlays.push({ element: overlay, initialRect: rect })
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
container.appendChild(fragment)
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
export const highlight = (refMap: RefMap, parentIframe: HTMLIFrameElement | null = null) => {
|
|
129
|
+
doHighlight(refMap, parentIframe)
|
|
130
|
+
|
|
131
|
+
// 4、监听滚动和resize事件,更新位置
|
|
132
|
+
const updatePositions = () => doHighlight(refMap, parentIframe)
|
|
133
|
+
const throttleFunction = (func: (...args: any[]) => void, delay: number) => {
|
|
134
|
+
let lastCall = 0
|
|
135
|
+
return (...args: any[]) => {
|
|
136
|
+
const now = performance.now()
|
|
137
|
+
if (now - lastCall < delay) return
|
|
138
|
+
lastCall = now
|
|
139
|
+
return func(...args)
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const throttledUpdatePositions = throttleFunction(updatePositions, 16)
|
|
144
|
+
window.addEventListener('scroll', throttledUpdatePositions, true)
|
|
145
|
+
window.addEventListener('resize', throttledUpdatePositions)
|
|
146
|
+
|
|
147
|
+
const cleanupFn = () => {
|
|
148
|
+
window.removeEventListener('scroll', throttledUpdatePositions, true)
|
|
149
|
+
window.removeEventListener('resize', throttledUpdatePositions)
|
|
150
|
+
}
|
|
151
|
+
const win = window as any
|
|
152
|
+
;(win._highlightCleanupFunctions = win._highlightCleanupFunctions || []).push(cleanupFn)
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** 移除高亮, 可反复调用 */
|
|
156
|
+
export const unhighlight = () => {
|
|
157
|
+
document.getElementById(HIGHLIGHT_CONTAINER_ID)?.remove()
|
|
158
|
+
|
|
159
|
+
const cleanupFunctions = (window as any)._highlightCleanupFunctions || []
|
|
160
|
+
for (const cleanup of cleanupFunctions) {
|
|
161
|
+
if (typeof cleanup === 'function') {
|
|
162
|
+
cleanup()
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
;(window as any)._highlightCleanupFunctions = []
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** 全局监听变化,随时准备移除高亮, 可反复调用 */
|
|
170
|
+
export const globalRemoveListener = () => {
|
|
171
|
+
if ((window as any).__registerGlobalRemoveListener) return
|
|
172
|
+
;(window as any).__registerGlobalRemoveListener = true
|
|
173
|
+
window.addEventListener('popstate', () => {
|
|
174
|
+
unhighlight()
|
|
175
|
+
})
|
|
176
|
+
window.addEventListener('hashchange', () => {
|
|
177
|
+
unhighlight()
|
|
178
|
+
})
|
|
179
|
+
window.addEventListener('beforeunload', () => {
|
|
180
|
+
unhighlight()
|
|
181
|
+
})
|
|
182
|
+
|
|
183
|
+
const navigation = (window as any).navigation
|
|
184
|
+
if (navigation && typeof navigation.addEventListener === 'function') {
|
|
185
|
+
navigation.addEventListener('navigate', () => {
|
|
186
|
+
unhighlight()
|
|
187
|
+
})
|
|
188
|
+
} else {
|
|
189
|
+
// 定时器
|
|
190
|
+
let currentUrl = window.location.href
|
|
191
|
+
setInterval(() => {
|
|
192
|
+
if (window.location.href !== currentUrl) {
|
|
193
|
+
currentUrl = window.location.href
|
|
194
|
+
unhighlight()
|
|
195
|
+
}
|
|
196
|
+
}, 500)
|
|
197
|
+
}
|
|
198
|
+
}
|