仰望星辰工作室

starmusic-mobile

starmusic-mobile/ components/tv-nav/tv-nav.vue 14.8 KB · 374 行 原始文件
1<template>
2 <view class="tv-nav-host"><slot /></view>
3</template>
4
5<script>
6/**
7 * 遥控导航组件
8 *
9 * 在电视 / 车机端启用遥控器焦点导航;手机端完全不渲染任何额外能力。
10 *
11 * 原理(uni-app 双端架构):
12 * - 逻辑层:只能通过 isRemote() 判断设备,无法碰 DOM;
13 * - 视图层(App renderjs):页面 WebView 的 document 里做焦点导航、高亮、点击。
14 * 因此本组件利用「逻辑层调用 renderjs 方法」的官方桥接:
15 * mounted() 判断遥控设备后,调 this.$scope.tv.init() 让视图层接管当前页面 document。
16 *
17 * 使用:在目标页面模板顶层放置 <tv-nav />(easycom 自动注册)。
18 * 可聚焦节点自动识别:data-navid / .d-press / .d-press-sm / button / input / textarea;
19 * 弹层面板加 data-nav-scope,焦点即被限制在弹层内部(关闭后自动还原)。
20 * H5 端由 App.vue 已挂载的全局引擎接管,renderjs 在此跳过,避免双引擎。
21 */
22import { isRemote } from '@/common/tv.js'
23
24export default {
25 name: 'tv-nav',
26 props: {
27 // 可动态关闭(例如全屏歌词等特殊场景)
28 enabled: { type: Boolean, default: true },
29 },
30 mounted() {
31 if (!isRemote() || !this.enabled) return
32 // renderjs 方法需等视图层就绪后才能调用;同时做容错,
33 // 桥接失败时静默降级(触摸仍完全可用),不影响页面其余功能
34 this.$nextTick(() => {
35 try {
36 if (this.$scope && this.$scope.tv) this.$scope.tv.init()
37 } catch (err) {
38 console.warn('[tv-nav] 焦点引擎初始化失败', err)
39 }
40 })
41 },
42}
43</script>
44
45<script module="tv" lang="renderjs">
46/**
47 * 视图层脚本(App 端页面 WebView 运行,拥有 document)。
48 * 此处仅操作 DOM,不 import 业务模块;方向键导航 / 确认激活 / 焦点框高亮全部在此闭环。
49 * 触摸仍可用:焦点框 pointer-events:none,不影响点击与滑动(手/遥控双输入兼容)。
50 */
51const KEYMAP = {
52 up: [38, 119, 19],
53 down: [40, 120, 20],
54 left: [37, 118, 21],
55 right: [39, 122, 22],
56 enter: [13, 32, 66, 23],
57}
58
59// 与 common/tv-focus.js 保持一致:显式标记 + 可点击语义 + 原生可聚焦控件
60const NAV_SELECTOR = '[data-navid], .d-press, .d-press-sm, button, input, textarea'
61
62export default {
63 methods: {
64 init() {
65 if (this.__engine) return
66 // H5 端已在 App.vue 挂载全局焦点引擎,这里去重,避免双引擎重复监听
67 if (typeof window !== 'undefined' && window.__tvFocusEngine) return
68 const doc = document
69 if (!doc || !doc.addEventListener) return
70
71 let current = null
72 let scopeEl = null // 当前导航作用域(弹层)
73 let prevFocus = null // 进入弹层前的焦点,用于关闭后还原
74 let highlighted = null // 已高亮节点,避免每次遍历全部节点
75 let lastCenter = null // 焦点框最后一次位置,用于焦点失效后的自愈落点
76 let retryTimer = null // 节点采集为空时的重试定时器
77
78 /**
79 * 节点是否仍在文档中(弹层关闭后原节点可能已被销毁)。
80 * 被整体移除的子树里节点仍持有 parentNode,因此用 doc.contains 判断。
81 */
82 const alive = (el) => !!(el && (doc.contains ? doc.contains(el) : el.parentNode && el.parentNode.nodeType === 1))
83
84 /**
85 * 作用域是否可用:弹层自身可见,且内部至少有一个可见的可聚焦节点。
86 *
87 * 只判断"自身尺寸非 0"不够:只剩遮罩、或内容全是不可聚焦元素的弹层若被当成
88 * 导航作用域,节点采集结果为空 → 所有方向键静默失效(确认键却照旧可用),
89 * 遥控器上的表现就是"焦点卡住,怎么按都不动"。
90 */
91 const usableScope = (el) => {
92 if (!el || !el.querySelectorAll || !el.getBoundingClientRect) return false
93 const r = el.getBoundingClientRect()
94 if (!r.width && !r.height) return false
95 const list = el.querySelectorAll(NAV_SELECTOR)
96 for (let i = 0; i < list.length; i++) {
97 const node = list[i]
98 if (!node || !node.getBoundingClientRect) continue
99 const nr = node.getBoundingClientRect()
100 if (nr.width || nr.height) return true
101 }
102 return false
103 }
104
105 /** 当前导航作用域:最后一个可用(可见且含可聚焦项)的 [data-nav-scope](弹层面板) */
106 const getScope = () => {
107 const list = doc.querySelectorAll('[data-nav-scope]')
108 for (let i = list.length - 1; i >= 0; i--) {
109 if (usableScope(list[i])) return list[i]
110 }
111 return null
112 }
113
114 // 采集当前可见的可聚焦节点(弹层打开时只采集弹层内部)
115 const nodes = () => {
116 scopeEl = getScope()
117 const base = scopeEl || doc.body || (doc.documentElement ? doc.documentElement : null)
118 if (!base || !base.querySelectorAll) return []
119 const vh = doc.documentElement ? doc.documentElement.clientHeight : 0
120 const vw = doc.documentElement ? doc.documentElement.clientWidth : 0
121 // 视口判定放宽一个边距:屏幕外的下一项要能被聚焦,再由 scrollIntoView 滚入可视区,
122 // 否则遥控只能选中当前屏内的项,长列表无法滚动
123 const margin = vh ? Math.max(120, vh * 0.5) : 0
124 const marginX = vw ? Math.max(120, vw * 0.5) : 0
125 return Array.prototype.slice.call(base.querySelectorAll(NAV_SELECTOR))
126 .map((el) => {
127 if (!el.getBoundingClientRect) return null
128 const r = el.getBoundingClientRect()
129 if (!r.width && !r.height) return null
130 if (vh && (r.bottom < -margin || r.top > vh + margin)) return null
131 if (vw && (r.right < -marginX || r.left > vw + marginX)) return null
132 return { el, x: r.left + r.width / 2, y: r.top + r.height / 2 }
133 })
134 .filter(Boolean)
135 }
136
137 // 焦点框
138 const ring = doc.createElement('div')
139 ring.className = 'tv-focus-ring'
140 ring.style.position = 'fixed'
141 ring.style.zIndex = '99999'
142 ring.style.pointerEvents = 'none'
143 ring.style.display = 'none'
144 ring.style.boxSizing = 'border-box'
145 ring.style.transition =
146 'left .18s ease, top .18s ease, width .18s ease, height .18s ease'
147 ring.style.border = '3px solid var(--theme-color, #31c27c)'
148 ring.style.borderRadius = '12px'
149 ring.style.boxShadow = '0 0 0 4px rgba(var(--theme-color-rgb, 49, 194, 124), .3), 0 0 22px rgba(var(--theme-color-rgb, 49, 194, 124), .7)'
150 // 挂到页面根容器内以继承主题 CSS 变量(fixed 定位不受父级影响)
151 const ringHost = doc.querySelector('.page') || doc.querySelector('.play-detail') || doc.body
152 if (ringHost) ringHost.appendChild(ring)
153
154 // 只改动「上一个」与「当前」两项的高亮,避免遍历全部节点与脏高亮残留
155 const highlight = (el) => {
156 if (highlighted && highlighted !== el && highlighted.classList) highlighted.classList.remove('tv-focused')
157 if (el && el.classList) el.classList.add('tv-focused')
158 highlighted = el
159 }
160
161 const applyRing = (el) => {
162 const r = el.getBoundingClientRect()
163 if (!r.width && !r.height) return
164 // 记录焦点框中心:焦点失效时用它决定自愈落点
165 lastCenter = { x: r.left + r.width / 2, y: r.top + r.height / 2 }
166 ring.style.display = 'block'
167 ring.style.left = r.left + 'px'
168 ring.style.top = r.top + 'px'
169 ring.style.width = r.width + 'px'
170 ring.style.height = r.height + 'px'
171 }
172
173 /** 强制一次同步布局:WebView 从子页面返回后可能尚未重排(所有节点 rect 为 0) */
174 const forceReflow = () => {
175 if (doc.body) void doc.body.offsetHeight
176 if (doc.documentElement) void doc.documentElement.clientHeight
177 }
178
179 /**
180 * 自愈落点:当前焦点失效时,优先落回焦点框最后所在位置附近的节点
181 * (从子页面返回后焦点框仍停在原来的项上,用户期望从那里继续导航),
182 * 其次取视口内的第一个节点,最后退回列表首项。
183 */
184 const recoverFrom = (list) => {
185 if (!list || !list.length) return null
186 if (lastCenter) {
187 let best = null
188 let bs = Infinity
189 for (const n of list) {
190 const s = Math.abs(n.x - lastCenter.x) + Math.abs(n.y - lastCenter.y)
191 if (s < bs) {
192 bs = s
193 best = n
194 }
195 }
196 if (best) return best
197 }
198 const vh = doc.documentElement ? doc.documentElement.clientHeight : 0
199 const vw = doc.documentElement ? doc.documentElement.clientWidth : 0
200 if (vh && vw) {
201 const visible = list.find((n) => n.y >= 0 && n.y <= vh && n.x >= 0 && n.x <= vw)
202 if (visible) return visible
203 }
204 return list[0]
205 }
206
207 /**
208 * 采集为空时错后一帧重试一次。
209 * 页面刚显示/刚从子页面返回时节点可能还没完成布局,直接放弃会让方向键"按了没反应"。
210 */
211 const retryMove = (dir) => {
212 if (retryTimer) return
213 forceReflow()
214 retryTimer = setTimeout(() => {
215 retryTimer = null
216 // 只重试一次:页面确实没有任何可聚焦项时不能无限循环重排
217 move(dir, true)
218 }, 60)
219 }
220
221 /**
222 * 弹层打开/关闭时迁移焦点。
223 * @param {boolean} isActivate 是否由确认键触发(关闭弹层时需消费确认键,
224 * 否则会误触「刚才打开弹层的那个按钮」,导致弹层反复开关)
225 * @returns {boolean} 是否消费本次按键
226 */
227 const syncScope = (isActivate) => {
228 const el = getScope()
229 if (el === scopeEl) return false
230 const prev = current
231 scopeEl = el
232 // 弹层打开:焦点进入弹层首项,并消费本次按键
233 if (el) {
234 const list = nodes()
235 if (list.length) {
236 prevFocus = prev
237 current = list[0].el
238 highlight(current)
239 applyRing(current)
240 return true
241 }
242 // 作用域内没有可聚焦项(如仅剩遮罩):放弃限制,避免所有按键都失效
243 scopeEl = null
244 return false
245 }
246 // 弹层关闭:还原进入前的焦点;方向键不消费(可立即继续导航)
247 if (alive(prevFocus)) {
248 current = prevFocus
249 highlight(current)
250 applyRing(current)
251 } else {
252 current = null
253 ring.style.display = 'none'
254 }
255 return !!isActivate
256 }
257
258 // 方向导航(主轴距离 + 侧向偏移惩罚,避免跳斜对角)
259 const move = (dir, isRetry) => {
260 if (syncScope(false)) return
261 const list = nodes()
262 if (!list.length) {
263 if (!isRetry) retryMove(dir)
264 return
265 }
266 // 当前焦点可能已失效(子页面返回、列表刷新、弹层关闭):先自愈到有效节点,
267 // 否则焦点框会停在不动的旧位置上,看起来就是"方向键完全失灵"
268 let from = list.find((n) => n.el === current)
269 if (!from) {
270 from = recoverFrom(list)
271 if (!from) return
272 current = from.el
273 highlight(current)
274 applyRing(current)
275 }
276 let best = null
277 let bs = Infinity
278 for (const n of list) {
279 if (n.el === from.el) continue
280 const dx = n.x - from.x
281 const dy = n.y - from.y
282 if (dir === 'left' && dx >= 0) continue
283 if (dir === 'right' && dx <= 0) continue
284 if (dir === 'up' && dy >= 0) continue
285 if (dir === 'down' && dy <= 0) continue
286 const h = dir === 'left' || dir === 'right'
287 const main = h ? Math.abs(dx) : Math.abs(dy)
288 const side = h ? Math.abs(dy) : Math.abs(dx)
289 const s = main + side * 2.2
290 if (s < bs) {
291 bs = s
292 best = n
293 }
294 }
295 const target = best || from
296 current = target.el
297 highlight(current)
298 try {
299 current.scrollIntoView && current.scrollIntoView({ block: 'nearest' })
300 } catch (e) {}
301 applyRing(current)
302 setTimeout(() => {
303 if (current === target.el) applyRing(current)
304 }, 30)
305 }
306
307 const activate = () => {
308 if (syncScope(true)) return
309 // 当前焦点可能已随弹层/列表刷新被销毁,必须校验,否则确认键会永久失效
310 if (!current || !alive(current)) {
311 const from = recoverFrom(nodes())
312 if (!from) return
313 current = from.el
314 highlight(current)
315 applyRing(current)
316 }
317 if (current && current.click) {
318 current.click()
319 // 输入类元素补一次 focus,确保遥控端能唤起输入法
320 if (/^(INPUT|TEXTAREA)$/i.test(current.tagName || '') && current.focus) current.focus()
321 }
322 }
323
324 /**
325 * 页面重新可见(从子页面返回、应用切回前台)时复位导航状态。
326 * 页面切换后作用域可能已失效、焦点框位置也可能过期;这里只做轻量复位,
327 * 真正的自愈交给 move()(按键时重新采集节点并落回原焦点附近)。
328 */
329 const resync = () => {
330 scopeEl = null
331 if (current && !alive(current)) {
332 current = null
333 ring.style.display = 'none'
334 }
335 if (current) applyRing(current)
336 }
337 // 子页面返回/应用切回前台时 WebView 通常会重新布局,resize 是最可靠的信号;
338 // visibilitychange 兼顾部分不发 resize 的机型
339 if (typeof window !== 'undefined' && window.addEventListener) {
340 window.addEventListener('resize', resync)
341 }
342 doc.addEventListener('visibilitychange', () => {
343 if (!doc.hidden) resync()
344 })
345
346 const handler = (e) => {
347 const t = e.target
348 const k = e.keyCode || e.which
349 // 输入框聚焦时不拦截,交给系统 TV 输入法。
350 // 但必须保留一个退出键,否则遥控焦点会永远困在输入框内。
351 if (t && t.tagName && /^(INPUT|TEXTAREA)$/i.test(t.tagName)) {
352 if (k === 27 || k === 461) {
353 e.preventDefault()
354 if (t.blur) t.blur()
355 if (current) applyRing(current)
356 }
357 return
358 }
359 for (const name in KEYMAP) {
360 if (KEYMAP[name].indexOf(k) > -1) {
361 e.preventDefault()
362 if (name === 'enter') activate()
363 else move(name)
364 return
365 }
366 }
367 }
368 doc.addEventListener('keydown', handler, true)
369
370 this.__engine = { move, activate, highlight, nodes, handler, ring }
371 },
372 },
373}
374</script>