starmusic-mobile
1/**
2 * 遥控器焦点导航引擎(纯 DOM 实现,不依赖 uni API)
3 *
4 * 用途:电视 / 车机端用遥控器方向键 + 确认键操作 UI。
5 * 本引擎 H5 可直接在逻辑层运行;App 端因逻辑层无 DOM,
6 * 需通过 renderjs 在页面视图层运行(见 pages 各页的 renderjs 接入)。
7 *
8 * 设计要点:
9 * - 可聚焦元素统一用 `data-navid` 标记(页面模板逐个打标记);
10 * - 方向键按下时重新采集可见节点坐标,按"主轴距离 + 侧向偏移惩罚"
11 * 选取最近目标,避免跳到斜对角;
12 * - 顶层固定一个"焦点框"(overlay,pointer-events:none)跟随当前项,
13 * 确认键触发元素 click(可正常触发 Vue 的 @click);
14 * - 触摸仍完全可用:焦点框不拦截事件,点击/滑动不受影响(双输入兼容);
15 * - 捕获阶段监听 keydown 并 preventDefault,接管 WebView 默认焦点行为。
16 */
17
18// 键码映射:兼容 DOM 键码 与 部分 Android WebView 的虚拟键码
19const KEYMAP = {
20 up: [38, 119, 19],
21 down: [40, 120, 20],
22 left: [37, 118, 21],
23 right: [39, 122, 22],
24 enter: [13, 32, 66, 23],
25 back: [8, 4, 461], // 返回(默认交给 uni 的 onBackPress,本引擎仅上报)
26 menu: [82, 93],
27}
28
29/**
30 * 可聚焦节点的选择器。
31 * - [data-navid]:跨端显式约定
32 * - .d-press / .d-press-sm:项目既有的「可点击」语义(App.vue 全局样式定义),
33 * 各页面已完整标注,直接复用即可覆盖全部可操作元素,无需逐个补 data-navid
34 * - button / input / textarea:原生可聚焦控件,本身即交互入口
35 */
36const NAV_SELECTOR = '[data-navid], .d-press, .d-press-sm, button, input, textarea'
37
38/** 输入类标签:方向键需交给系统输入法 */
39const INPUT_TAG = /^(INPUT|TEXTAREA)$/i
40
41class TVFocusEngine {
42 constructor(opts = {}) {
43 this.name = opts.name || 'tv'
44 // 回调(onHint 用于非 DOM 端把按键上报出去)
45 this.onMove = opts.onMove || null
46 this.onEnter = opts.onEnter || null
47 this.onBack = opts.onBack || null
48 this.onMenu = opts.onMenu || null
49
50 this.nodes = [] // 已采集的导航节点 { el, x, y, w, h, id }
51 this.currentEl = null // 当前聚焦元素
52 this.ring = null // 焦点框
53 this.enabled = true
54 this.handler = null
55 this.doc = null
56 this._scopeEl = null // 当前导航作用域(弹层)
57 this._prevFocusEl = null // 进入弹层前的焦点,用于弹层关闭后还原
58 this._highlighted = null // 已高亮节点,避免每次遍历全部节点
59 this._lastCenter = null // 焦点框最后一次位置,用于焦点失效后的自愈落点
60 this._retryTimer = null // 节点采集为空时的重试定时器
61 }
62
63 /**
64 * 挂载到指定 document(H5 用 window.document;App renderjs 用当前页面的 document)
65 * - 遍历键盘事件的捕获阶段,接管方向/确认键
66 */
67 mount(documentObj) {
68 this.doc = documentObj
69 if (!this.doc || !this.doc.addEventListener) return this
70 // 清理旧监听,避免重复挂载
71 if (this.handler) this.doc.removeEventListener('keydown', this.handler, true)
72 this.handler = this.onKeyDown.bind(this)
73 this.doc.addEventListener('keydown', this.handler, true)
74 this.ensureRing()
75 return this
76 }
77
78 unmount() {
79 if (this.doc && this.handler) {
80 this.doc.removeEventListener('keydown', this.handler, true)
81 }
82 if (this.ring && this.ring.parentNode) {
83 this.ring.parentNode.removeChild(this.ring)
84 }
85 if (this._retryTimer) {
86 clearTimeout(this._retryTimer)
87 this._retryTimer = null
88 }
89 this.ring = null
90 this.currentEl = null
91 this.nodes = []
92 this._scopeEl = null
93 this._prevFocusEl = null
94 this._highlighted = null
95 this._lastCenter = null
96 }
97
98 onKeyDown(e) {
99 const t = e.target
100 const k = e.keyCode || e.which
101 // 输入框/文本域聚焦时不拦截,交给系统输入法(遥控器字母/方向用于输入)。
102 // 但必须保留一个退出键,否则遥控焦点会永远困在输入框内,无法回到页面。
103 if (t && t.tagName && INPUT_TAG.test(t.tagName)) {
104 if (k === 27 || k === 461) {
105 e.preventDefault()
106 if (t.blur) t.blur()
107 if (this.currentEl) this.setFocus(this.currentEl)
108 }
109 return
110 }
111 for (const name in KEYMAP) {
112 if (KEYMAP[name].includes(k)) {
113 if (name === 'enter') {
114 e.preventDefault()
115 this.activate()
116 } else if (name === 'back') {
117 if (this.onBack) this.onBack()
118 } else if (name === 'menu') {
119 if (this.onMenu) this.onMenu()
120 } else {
121 // 方向键:阻止默认焦点/滚动,完全交给引擎
122 e.preventDefault()
123 this.move(name)
124 }
125 return
126 }
127 }
128 }
129
130 /**
131 * 作用域是否可用:弹层自身可见,且内部至少有一个可见的可聚焦节点。
132 *
133 * 只判断"自身尺寸非 0"不够:只剩遮罩、或内容全是不可聚焦元素的弹层若被当成
134 * 导航作用域,节点采集结果为空 → 所有方向键静默失效(确认键却照旧可用),
135 * 遥控器上的表现就是"焦点卡住,怎么按都不动"。
136 */
137 isScopeUsable(el) {
138 if (!el || !el.querySelectorAll || !el.getBoundingClientRect) return false
139 const r = el.getBoundingClientRect()
140 if (!r.width && !r.height) return false
141 const list = el.querySelectorAll(NAV_SELECTOR)
142 for (let i = 0; i < list.length; i++) {
143 const node = list[i]
144 if (!node || !node.getBoundingClientRect) continue
145 const nr = node.getBoundingClientRect()
146 if (nr.width || nr.height) return true
147 }
148 return false
149 }
150
151 /** 当前导航作用域:取最后一个可用(可见且含可聚焦项)的 [data-nav-scope](弹层面板) */
152 getScopeEl() {
153 const doc = this.doc || (typeof document !== 'undefined' ? document : null)
154 if (!doc || !doc.querySelectorAll) return null
155 const list = doc.querySelectorAll('[data-nav-scope]')
156 for (let i = list.length - 1; i >= 0; i--) {
157 if (this.isScopeUsable(list[i])) return list[i]
158 }
159 return null
160 }
161
162 /** 节点是否仍在文档中(弹层关闭后原节点可能已被销毁) */
163 isAlive(el) {
164 const doc = this.doc || (typeof document !== 'undefined' ? document : null)
165 if (!el) return false
166 // 用 document.contains 判断:被整体移除的子树里节点仍持有 parentNode,
167 // 只看 parentNode 会把已销毁的节点误判为存活
168 if (doc && doc.contains) return doc.contains(el)
169 return !!(el.parentNode && el.parentNode.nodeType === 1)
170 }
171
172 /**
173 * 同步弹层作用域:弹层打开时把焦点带进弹层,关闭后还原到进入前的元素。
174 * @param {boolean} isActivate 是否由确认键触发(关闭弹层时需消费确认键,
175 * 否则会误触「刚才打开弹层的那个按钮」,导致弹层反复开关)
176 * @returns {boolean} 是否消费本次按键
177 */
178 syncScope(isActivate) {
179 const el = this.getScopeEl()
180 if (el === this._scopeEl) return false
181 const prev = this.currentEl
182 this._scopeEl = el
183 this.collect()
184 // 弹层打开:焦点进入弹层首项,并消费本次按键
185 if (el) {
186 if (this.nodes.length) {
187 this._prevFocusEl = prev
188 this.setFocus(this.nodes[0].el)
189 return true
190 }
191 // 作用域内没有可聚焦项(如仅剩遮罩):放弃限制,避免所有按键都失效
192 this._scopeEl = null
193 this.collect()
194 return false
195 }
196 // 弹层关闭:还原进入前的焦点;方向键不消费(可立即继续导航)
197 if (this.isAlive(this._prevFocusEl)) {
198 this.setFocus(this._prevFocusEl)
199 } else {
200 this.currentEl = null
201 if (this.ring) this.ring.style.display = 'none'
202 }
203 return !!isActivate
204 }
205
206 /** 采集当前可见的可聚焦节点(每次导航前重建,坐标始终最新) */
207 collect(root) {
208 const doc = this.doc || (typeof document !== 'undefined' ? document : null)
209 if (!doc) return this.nodes
210 this.doc = doc
211 // 弹层优先:存在可见的 data-nav-scope 时只在其内部导航,
212 // 否则焦点会跑到被遮罩覆盖的页面元素上
213 const scope = this.getScopeEl()
214 this._scopeEl = scope
215 const base = scope || root || doc.body || doc.documentElement
216 if (!base || !base.querySelectorAll) return []
217 const viewportH = doc.documentElement ? doc.documentElement.clientHeight : 0
218 const viewportW = doc.documentElement ? doc.documentElement.clientWidth : 0
219 // 视口判定向外放宽一个边距:被裁在屏幕外的「下一行/下一项」必须能被聚焦,
220 // 聚焦后由 scrollIntoView 滚入可视区。否则遥控只能选中当前屏内的项,长列表无法滚动。
221 const margin = viewportH ? Math.max(120, viewportH * 0.5) : 0
222 const marginX = viewportW ? Math.max(120, viewportW * 0.5) : 0
223 const arr = Array.prototype.slice.call(base.querySelectorAll(NAV_SELECTOR))
224 this.nodes = arr
225 .map((el) => {
226 if (!el || !el.getBoundingClientRect) return null
227 const r = el.getBoundingClientRect()
228 // 只保留非 0 尺寸、且落在(放宽后)视口范围内的项;
229 // 横向同样过滤,避免采集到页面栈中已横向移出/隐藏的节点
230 if (!r.width && !r.height) return null
231 if (viewportH && (r.bottom < -margin || r.top > viewportH + margin)) return null
232 if (viewportW && (r.right < -marginX || r.left > viewportW + marginX)) return null
233 return { el, x: r.left + r.width / 2, y: r.top + r.height / 2, w: r.width, h: r.height }
234 })
235 .filter(Boolean)
236 return this.nodes
237 }
238
239 /** 计算指定方向上的最近目标(经典投影法 + 侧向偏移惩罚) */
240 nearest(from, dir) {
241 if (!this.nodes.length) return null
242 let best = null
243 let bestScore = Infinity
244 for (const n of this.nodes) {
245 if (n.el === from.el) continue
246 const dx = n.x - from.x
247 const dy = n.y - from.y
248 // 必须落在该方向象限;防止 180° 反向跳转
249 if (dir === 'left' && dx >= 0) continue
250 if (dir === 'right' && dx <= 0) continue
251 if (dir === 'up' && dy >= 0) continue
252 if (dir === 'down' && dy <= 0) continue
253 const isHorizontal = dir === 'left' || dir === 'right'
254 const main = isHorizontal ? Math.abs(dx) : Math.abs(dy)
255 const side = isHorizontal ? Math.abs(dy) : Math.abs(dx)
256 // 主轴优先,侧向偏移放大惩罚,避免跳到斜对角
257 const score = main + side * 2.2
258 if (score < bestScore) {
259 bestScore = score
260 best = n
261 }
262 }
263 return best
264 }
265
266 /** 强制一次同步布局:WebView 从子页面返回后可能尚未重排(所有节点 rect 为 0) */
267 forceReflow() {
268 const doc = this.doc || (typeof document !== 'undefined' ? document : null)
269 if (!doc) return
270 if (doc.body) void doc.body.offsetHeight
271 if (doc.documentElement) void doc.documentElement.clientHeight
272 }
273
274 /**
275 * 自愈落点:当前焦点失效时,优先落回焦点框最后所在位置附近的节点
276 * (从子页面返回后焦点框仍停在原来的项上,用户期望从那里继续导航),
277 * 其次取视口内的第一个节点,最后退回列表首项。
278 */
279 recoverFrom(list) {
280 if (!list || !list.length) return null
281 const center = this._lastCenter
282 if (center) {
283 let best = null
284 let bestScore = Infinity
285 for (const n of list) {
286 const score = Math.abs(n.x - center.x) + Math.abs(n.y - center.y)
287 if (score < bestScore) {
288 bestScore = score
289 best = n
290 }
291 }
292 if (best) return best
293 }
294 const doc = this.doc || (typeof document !== 'undefined' ? document : null)
295 const viewportH = doc && doc.documentElement ? doc.documentElement.clientHeight : 0
296 const viewportW = doc && doc.documentElement ? doc.documentElement.clientWidth : 0
297 if (viewportH && viewportW) {
298 const visible = list.find((n) => n.y >= 0 && n.y <= viewportH && n.x >= 0 && n.x <= viewportW)
299 if (visible) return visible
300 }
301 return list[0]
302 }
303
304 /**
305 * 采集为空时错后一帧重试一次。
306 * 页面刚显示/刚从子页面返回时节点可能还没完成布局,直接放弃会让方向键"按了没反应"。
307 */
308 retryMove(dir) {
309 if (this._retryTimer) return
310 this.forceReflow()
311 this._retryTimer = setTimeout(() => {
312 this._retryTimer = null
313 // 只重试一次:页面确实没有任何可聚焦项时不能无限循环重排
314 this.move(dir, true)
315 }, 60)
316 }
317
318 /** 移动焦点 */
319 move(dir, isRetry) {
320 if (!this.enabled) return
321 // 弹层刚打开:本次按键只用于把焦点带进弹层,不继续导航
322 if (this.syncScope(false)) return
323 const list = this.collect()
324 if (!list.length) {
325 if (!isRetry) this.retryMove(dir)
326 return
327 }
328 // 当前焦点可能已失效(子页面返回、列表刷新、弹层关闭):先自愈到有效节点,
329 // 否则焦点框会停在不动的旧位置上,看起来就是"方向键完全失灵"
330 let from = list.find((n) => n.el === this.currentEl)
331 if (!from) {
332 from = this.recoverFrom(list)
333 if (!from) return
334 this.setFocus(from.el)
335 }
336 const target = this.nearest(from, dir) || from
337 this.setFocus(target.el)
338 }
339
340 /** 激活当前项(触发点击) */
341 activate() {
342 if (!this.enabled) return
343 if (this.syncScope(true)) return
344 this.collect()
345 // 当前焦点可能已随弹层/列表刷新被销毁,必须校验,否则确认键会永久失效
346 if (!this.currentEl || !this.isAlive(this.currentEl)) {
347 const from = this.recoverFrom(this.nodes)
348 if (!from) return
349 this.setFocus(from.el)
350 }
351 const el = this.currentEl
352 if (!el) return
353 el.click()
354 // 输入类元素补一次 focus,确保遥控端能唤起输入法
355 if (el.tagName && INPUT_TAG.test(el.tagName) && el.focus) el.focus()
356 }
357
358 /** 设焦 */
359 setFocus(el) {
360 if (!el) return
361 this.currentEl = el
362 this.ensureRing()
363 // 只需改动「上一个」与「当前」两项的高亮,无需遍历全部节点
364 if (this._highlighted && this._highlighted !== el && this._highlighted.classList) {
365 this._highlighted.classList.remove('tv-focused')
366 }
367 if (el.classList) el.classList.add('tv-focused')
368 this._highlighted = el
369 const doc = this.doc || document
370 if (doc) {
371 // 滚动到可见(方向导航时块内滚动)
372 try {
373 el.scrollIntoView && el.scrollIntoView({ block: 'nearest' })
374 } catch (e) {}
375 // 延迟到滚动后读取新坐标(保证焦点框定位准确)
376 const apply = () => {
377 if (!this.ring || this.currentEl !== el) return
378 const r = el.getBoundingClientRect()
379 if (!r.width && !r.height) return
380 // 记录焦点框中心:焦点失效时用它决定自愈落点
381 this._lastCenter = { x: r.left + r.width / 2, y: r.top + r.height / 2 }
382 this.ring.style.display = 'block'
383 this.ring.style.left = r.left + 'px'
384 this.ring.style.top = r.top + 'px'
385 this.ring.style.width = r.width + 'px'
386 this.ring.style.height = r.height + 'px'
387 }
388 apply()
389 setTimeout(apply, 30)
390 }
391 if (this.onMove) this.onMove(el)
392 }
393
394 /** 聚焦第一个可聚焦项 */
395 focusFirst() {
396 this.collect()
397 if (this.nodes.length) this.setFocus(this.nodes[0].el)
398 }
399
400 /** 外部调用:聚焦指定 data-navid(如页面进入时自动定位到首屏按钮) */
401 focusByIndex(i) {
402 this.collect()
403 if (this.nodes[i]) this.setFocus(this.nodes[i].el)
404 }
405
406 ensureRing() {
407 if (this.ring) return
408 const doc = this.doc || (typeof document !== 'undefined' ? document : null)
409 if (!doc || !doc.createElement) return
410 this.ring = doc.createElement('div')
411 this.ring.className = 'tv-focus-ring'
412 this.ring.style.position = 'fixed'
413 this.ring.style.zIndex = '99999'
414 this.ring.style.pointerEvents = 'none'
415 this.ring.style.display = 'none'
416 this.ring.style.transition = 'left .18s ease, top .18s ease, width .18s ease, height .18s ease'
417 this.ring.style.boxSizing = 'border-box'
418 // 挂到页面根容器内以继承主题 CSS 变量(fixed 定位不受父级影响)
419 const host = doc.querySelector('.page') || doc.querySelector('.play-detail') || doc.body
420 if (host) host.appendChild(this.ring)
421 }
422}
423
424/**
425 * 创建并挂载引擎,返回引擎实例。
426 * @param {object} opts { doc, name, onBack, onMenu }
427 */
428export function createFocusEngine(opts = {}) {
429 const engine = new TVFocusEngine(opts)
430 const dd = opts.doc || (typeof document !== 'undefined' ? document : null)
431 if (dd) engine.mount(dd)
432 return engine
433}