@sublane/supplier-fluent-read 0.1.2 → 0.3.0

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sublane/supplier-fluent-read",
3
- "version": "0.1.2",
3
+ "version": "0.3.0",
4
4
  "type": "module",
5
5
  "main": "./src/index.ts",
6
6
  "exports": {
@@ -47,7 +47,7 @@
47
47
  "license": "GPL-3.0",
48
48
  "description": "FluentRead 供应商(Unofficial):视频字幕翻译垂直切片——vendor 树经 patches 维护,adapter 实现框架契约",
49
49
  "peerDependencies": {
50
- "@sublane/core": "^0.1.2"
50
+ "@sublane/core": "^0.3.0"
51
51
  },
52
52
  "devDependencies": {
53
53
  "@sublane/core": "workspace:*"
package/src/adapter.ts CHANGED
@@ -13,6 +13,7 @@ import { config, configReady, requestConfigPatch } from '../vendor/src/services/
13
13
  import { mountVideoSubtitleTranslation, isSupportedVideoPage } from '../vendor/src/features/video-subtitle/public'
14
14
  import { fluentReadHostRequirements } from './manifest'
15
15
  import { laneToAppearancePosition } from './lane'
16
+ import { createDetachedInstance as createFluentDetachedInstance } from './detached'
16
17
  import { attachPanelDrag } from './panel-drag'
17
18
  import { fluentReadSettingsSchema } from './settings-schema'
18
19
 
@@ -208,6 +209,8 @@ export const fluentReadPlugin = {
208
209
  bilingualDownload: true,
209
210
  sidebar: false,
210
211
  manualTimingOffset: true,
212
+ // F-27/P1:支持 detached 渲染(宿主 feature-detect 首选旗标)
213
+ detachedRender: true,
211
214
  },
212
215
  settingsSchema: fluentReadSettingsSchema,
213
216
  contentScriptRequirements: [
@@ -223,4 +226,6 @@ export const fluentReadPlugin = {
223
226
  },
224
227
  ],
225
228
  createInstance: createFluentReadInstance,
229
+ // F-27/P1:detached 渲染实例(实现见 ./detached.ts;live 零变化,与 live 并存 R1)
230
+ createDetachedInstance: createFluentDetachedInstance,
226
231
  }
@@ -0,0 +1,211 @@
1
+ /**
2
+ * @file suppliers/fluent-read/src/detached.ts
3
+ * 文件职责:fluent-read 的 F-27/P1 detached 渲染实例——在宿主提供的任意 video 元素上,以 vendor 原生
4
+ * UI 规则渲染宿主注入的字幕轨(数据注入 + 时钟外驱 + injected-only)。
5
+ * 主要内容:R2 达成机制 = **Shadow DOM 同构**:宿主父级挂 shadow host,shadow root 注入 vendor
6
+ * 全局样式表(installVideoSubtitleStyle 的同一份 CSS 全文),shadow 内重建同构 DOM
7
+ * (layer > panel > original/translation overlay,同款 ID/class/属性)——vendor 全部 ID/class
8
+ * 规则原样命中 shadow 内元素(by construction),且 shadow 边界使同款 ID 与 live 零冲突
9
+ * (R1/G3:live 的 document 级 getElementById 永远看不到 shadow 内部;vendor 卸载路径的
10
+ * querySelectorAll 也扫不进 shadow)。appearance vars 经 vendor 导出纯函数
11
+ * getVideoSubtitleAppearanceCssVars(同函数实例,R2);字号/布局公式复刻 ui.ts:570-619
12
+ * (锚定注释)但以宿主元素为根(R2 通用路径:无 X 探测/原生字幕探测/菜单预留——注入模式
13
+ * 无原生字幕,normalizedCaption 语义即面板内双行);显示模式同源(vendor config,
14
+ * layer 类切换同 applyVideoDisplayState);lane 经 laneToAppearancePosition(G4);
15
+ * karaoke:Q4 裁决终态渲染——textContent 直写(不走逐字装配)。
16
+ * 模块边界:只经 vendor 公开面(导出函数/常量/config 单例只读)与框架契约;live 行为零变化(N2);
17
+ * 不写 vendor config、不触碰 live DOM(R1)。
18
+ */
19
+ import type {
20
+ DetachedHandle, DetachedInstanceContext, SupplierRuntimeConfig, TrackSource,
21
+ VideoSubtitlePluginInstance,
22
+ } from '@sublane/core'
23
+ import {
24
+ installVideoSubtitleStyle, markVideoUi,
25
+ VIDEO_NORMALIZED_CAPTION_OVERLAY_ID, VIDEO_SUBTITLE_PANEL_ACTIVE_CLASS,
26
+ VIDEO_SUBTITLE_PANEL_ID, VIDEO_TRANSLATION_LAYER_ID, VIDEO_TRANSLATION_OVERLAY_ID,
27
+ } from '../vendor/src/features/video-subtitle/content/ui'
28
+ import { getVideoSubtitleAppearanceCssVars, normalizeVideoSubtitleAppearance } from '../vendor/src/core/config/videoSubtitleAppearance'
29
+ import { fitVideoSubtitleFontSize } from '../vendor/src/features/video-subtitle/content/subtitleLayout'
30
+ import { config } from '../vendor/src/services/config/store'
31
+ import { laneToAppearancePosition } from './lane'
32
+ import { currentCueAt, toVideoSubtitleCues } from './fluent-track'
33
+
34
+ const PANEL_ACTIVE_CLASS = VIDEO_SUBTITLE_PANEL_ACTIVE_CLASS
35
+
36
+ /** detached 面板在同构 DOM 上的定位/样式应用(宿主元素为根;公式锚定 ui.ts:570-619,
37
+ * 差异:无 X viewport/无菜单预留/无原生字幕探测——注入模式语义即 normalizedCaption 双行)。 */
38
+ function layoutPanel(panel: HTMLElement, video: HTMLVideoElement, bottomOffsetPercent: number): number {
39
+ const hostRect = video.getBoundingClientRect()
40
+ const hostWidth = hostRect.width || 960
41
+ const hostHeight = hostRect.height || 540
42
+ const appearance = normalizeVideoSubtitleAppearance(config.videoSubtitleAppearance)
43
+ Object.entries(getVideoSubtitleAppearanceCssVars(appearance)).forEach(([name, value]) => panel.style.setProperty(name, value))
44
+ panel.style.width = 'max-content'
45
+ panel.style.setProperty('max-width', `${Math.max(0, hostWidth * appearance.maxWidth / 100)}px`, 'important')
46
+ const baseFontSize = Math.min(Math.max(hostWidth * 0.022, 16), 30)
47
+ const fontScale = appearance.fontScale / 100
48
+ panel.style.setProperty('--fluent-read-video-subtitle-font-size', `${baseFontSize * fontScale}px`)
49
+ // 车道覆盖(G4):detached lane → bottomOffset%;appearance.bottomOffset===10 的 clamp 特例同款(ui.ts:589)
50
+ const requestedOffset = bottomOffsetPercent === 10
51
+ ? Math.min(Math.max(hostHeight * 0.1, 52), 96)
52
+ : Math.max(12, hostHeight * bottomOffsetPercent / 100)
53
+ const offset = Math.min(requestedOffset, Math.max(0, hostHeight - 24))
54
+ panel.style.setProperty('--fluent-read-video-subtitle-bottom', `${offset}px`)
55
+ panel.style.setProperty('top', appearance.position === 'top' ? `${offset}px` : appearance.position === 'center' ? `${hostHeight / 2}px` : 'auto', 'important')
56
+ panel.style.setProperty('bottom', appearance.position === 'bottom' ? 'var(--fluent-read-video-subtitle-bottom)' : 'auto', 'important')
57
+ const panelMaxHeight = Math.min(
58
+ Math.max(0, hostHeight - (appearance.position === 'center' ? 24 : offset + 12)),
59
+ Math.round(hostHeight * 0.42),
60
+ )
61
+ panel.style.setProperty('max-height', `${panelMaxHeight}px`, 'important')
62
+ panel.style.transform = appearance.position === 'center' ? 'translateY(-50%)' : 'none'
63
+ return baseFontSize * fontScale
64
+ }
65
+
66
+ /** F-27/P1:fluent-read detached 渲染实例(F-27 契约的可选实现)。 */
67
+ export async function createDetachedInstance(
68
+ ctx: DetachedInstanceContext,
69
+ video: HTMLVideoElement,
70
+ source: TrackSource,
71
+ options?: DetachedMountOptions,
72
+ ): Promise<VideoSubtitlePluginInstance & { detach(): DetachedHandle }> {
73
+ // ①vendor 全局样式表就位(幂等;live 同款依赖)并取全文注入 shadow(R2 by construction)
74
+ installVideoSubtitleStyle()
75
+ const vendorCss = document.getElementById('fluent-read-video-subtitle-style')?.textContent ?? ''
76
+
77
+ // ②数据面:注入轨 → vendor cue(时间轴数据;R5 缺译→无 translation 字段)
78
+ let currentSource: TrackSource = source
79
+ let vendorCues = toVideoSubtitleCues((await currentSource.getTrack().catch(() => null))?.cues ?? [])
80
+ const unsubscribers: Array<() => void> = []
81
+
82
+ // ③shadow host(宿主 video 父级,Q5 默认;host 不带 vendor ID——避免 document 级误命中)
83
+ const parentEl = video.parentElement ?? document.body
84
+ const computedStyle = window.getComputedStyle(parentEl)
85
+ if (computedStyle.position === 'static') parentEl.style.position = 'relative'
86
+ const shadowHost = document.createElement('div')
87
+ shadowHost.style.cssText = 'position:absolute;inset:0;pointer-events:none;overflow:hidden;z-index:2147483645;'
88
+ const shadowRoot = shadowHost.attachShadow({ mode: 'open' })
89
+ const styleEl = document.createElement('style')
90
+ styleEl.textContent = vendorCss
91
+ shadowRoot.appendChild(styleEl)
92
+ isolateEvents(shadowHost)
93
+ parentEl.appendChild(shadowHost)
94
+
95
+ // ④shadow 内同构 DOM(layer > panel > overlays;同款 ID/class/属性 → vendor 全部规则命中)
96
+ const layer = document.createElement('div')
97
+ layer.id = VIDEO_TRANSLATION_LAYER_ID
98
+ layer.className = 'fluent-read-video-subtitle-layer fluent-read-video-ui notranslate'
99
+ layer.setAttribute('data-fluent-read-ui', 'video-subtitle')
100
+ layer.setAttribute('translate', 'no')
101
+ const panel = document.createElement('div')
102
+ panel.id = VIDEO_SUBTITLE_PANEL_ID
103
+ panel.className = 'fluent-read-video-subtitle-panel fluent-read-video-ui notranslate'
104
+ panel.setAttribute('data-fluent-read-ui', 'video-subtitle')
105
+ panel.setAttribute('translate', 'no')
106
+ markVideoUi(panel)
107
+ const originalOverlay = document.createElement('div')
108
+ originalOverlay.id = VIDEO_NORMALIZED_CAPTION_OVERLAY_ID
109
+ originalOverlay.className = 'fluent-read-video-subtitle-original notranslate'
110
+ originalOverlay.setAttribute('translate', 'no')
111
+ originalOverlay.setAttribute('aria-live', 'polite')
112
+ const translationOverlay = document.createElement('div')
113
+ translationOverlay.id = VIDEO_TRANSLATION_OVERLAY_ID
114
+ translationOverlay.className = 'fluent-read-video-subtitle notranslate'
115
+ translationOverlay.setAttribute('translate', 'no')
116
+ translationOverlay.setAttribute('aria-live', 'polite')
117
+ panel.appendChild(originalOverlay)
118
+ panel.appendChild(translationOverlay)
119
+ layer.appendChild(panel)
120
+ shadowRoot.appendChild(layer)
121
+
122
+ // ⑤显示模式同源(vendor config;layer 类切换同 applyVideoDisplayState 语义)
123
+ const applyDisplayMode = () => {
124
+ const mode = config.videoSubtitleDisplayMode
125
+ layer.classList.toggle('fluent-read-video-display-translation-only', mode === 'translation-only')
126
+ layer.classList.toggle('fluent-read-video-display-original-only', mode === 'original-only')
127
+ layer.classList.toggle('fluent-read-video-display-hidden', config.videoSubtitleVisible === false)
128
+ }
129
+ applyDisplayMode()
130
+
131
+ // ⑥定位(lane 覆盖 + 宿主根公式)与自适应字号(同款 fit 函数)
132
+ const applyLayout = () => {
133
+ const lanePosition = laneToAppearancePosition(ctx.config.lane)
134
+ const appearance = normalizeVideoSubtitleAppearance(config.videoSubtitleAppearance)
135
+ const bottomOffsetPercent = lanePosition?.bottomOffset ?? appearance.bottomOffset
136
+ const sizedFontPx = layoutPanel(panel, video, bottomOffsetPercent)
137
+ panel.classList.add(PANEL_ACTIVE_CLASS)
138
+ fitVideoSubtitleFontSize(sizedFontPx, parseFloat(panel.style.maxHeight || '0') || sizedFontPx * 4,
139
+ (size) => panel.style.setProperty('--fluent-read-video-subtitle-font-size', `${size}px`),
140
+ () => panel.scrollHeight)
141
+ }
142
+ applyLayout()
143
+
144
+ // ⑦渲染(Q4 终态:textContent 直写;:empty 规则隐藏空行;R5 缺译=无译文行)
145
+ const renderAt = (timeMs: number) => {
146
+ const cue = currentCueAt(vendorCues, timeMs)
147
+ originalOverlay.textContent = cue?.text ?? ''
148
+ translationOverlay.textContent = cue?.translation ?? ''
149
+ const active = Boolean(translationOverlay.textContent || originalOverlay.textContent)
150
+ panel.classList.toggle(PANEL_ACTIVE_CLASS, active)
151
+ }
152
+
153
+ // ⑧时钟(R3):宿主 video 唯一权威;禁自建节拍
154
+ const onTime = () => renderAt(video.currentTime * 1000)
155
+ video.addEventListener('timeupdate', onTime)
156
+ video.addEventListener('seeked', onTime)
157
+ onTime()
158
+
159
+ // ⑨流式补译/换源(onUpdate + setSource)
160
+ const ingest = async () => {
161
+ vendorCues = toVideoSubtitleCues((await currentSource.getTrack().catch(() => null))?.cues ?? [])
162
+ renderAt(video.currentTime * 1000)
163
+ }
164
+ const watchSource = () => {
165
+ if (!currentSource.onUpdate) return
166
+ unsubscribers.push(currentSource.onUpdate((track) => {
167
+ vendorCues = toVideoSubtitleCues(track.cues)
168
+ onTime()
169
+ }))
170
+ }
171
+ watchSource()
172
+
173
+ // ⑩R6/A9 清理:节点/监听/订阅全归零
174
+ let cleaned = false
175
+ const cleanup = () => {
176
+ if (cleaned) return
177
+ cleaned = true
178
+ video.removeEventListener('timeupdate', onTime)
179
+ video.removeEventListener('seeked', onTime)
180
+ for (const unsubscribe of unsubscribers.splice(0)) unsubscribe()
181
+ shadowHost.remove()
182
+ }
183
+
184
+ const instance = {
185
+ mount() { /* 挂载已在 createDetachedInstance 完成(幂等空实现) */ },
186
+ unmount() { cleanup() },
187
+ setConfig(next: SupplierRuntimeConfig) {
188
+ // lane 变更即时生效(M2);settings 的样式权威在 vendor config(与 live 同源)——P1 语义注记
189
+ void next
190
+ applyLayout()
191
+ applyDisplayMode()
192
+ onTime()
193
+ },
194
+ detach(): DetachedHandle {
195
+ return {
196
+ unmount() { cleanup() },
197
+ setSource(next: TrackSource) {
198
+ currentSource = next
199
+ void ingest()
200
+ watchSource()
201
+ },
202
+ }
203
+ },
204
+ } satisfies VideoSubtitlePluginInstance & { detach(): DetachedHandle }
205
+ return instance
206
+ }
207
+
208
+ /** 事件隔离:detached 面板不劫持宿主交互(轻量版:面板层 pointer-events 已由 CSS 关) */
209
+ function isolateEvents(host: HTMLElement): void {
210
+ host.style.pointerEvents = 'none'
211
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * @file suppliers/fluent-read/src/fluent-track.ts
3
+ * 文件职责:SubtitleCue(框架注入轨,F-27 契约)↔ VideoSubtitleCue(vendor 原生形状)的双向映射,
4
+ * 与注入轨的时间轴选择(currentCueAt,R3 时钟的纯函数核)。
5
+ * 主要内容:toVideoSubtitleCues(正向,含 durationMs 缺省推断与末条语义)、
6
+ * cuesFromVideoSubtitleCues(逆向,契约夹具)、currentCueAt(区间 [start, start+duration) 命中)。
7
+ * 模块边界:纯函数,零浏览器依赖;时间语义按提案 §4.0-3;R5:translations 缺项与 null 等价(降级原文行)。
8
+ */
9
+ import type { SubtitleCue } from '@sublane/core'
10
+ import type { VideoSubtitleCue } from '../vendor/src/features/video-subtitle/content/youtubeSubtitleData'
11
+
12
+ export interface ToVendorOptions {
13
+ /** 末条 cue 的轨终点(ms);缺省 Infinity(播到轨终点语义) */
14
+ trackEndMs?: number
15
+ }
16
+
17
+ /** 注入 cue → vendor 原生 cue(F-27 数据面正向映射);译文列 = translations['fluent-read'](R5 缺项≡null) */
18
+ export function toVideoSubtitleCues(cues: SubtitleCue[], opts: ToVendorOptions = {}): Array<VideoSubtitleCue & { translation?: string }> {
19
+ return cues.map((cue, index) => {
20
+ const startMs = cue.tsMs
21
+ let durationMs: number
22
+ if (cue.durationMs != null) {
23
+ durationMs = cue.durationMs
24
+ } else if (index + 1 < cues.length) {
25
+ durationMs = Math.max(0, cues[index + 1]!.tsMs - startMs)
26
+ } else {
27
+ durationMs = opts.trackEndMs != null ? Math.max(0, opts.trackEndMs - startMs) : Number.POSITIVE_INFINITY
28
+ }
29
+ const fluentTranslation = cue.translations?.['fluent-read']
30
+ const vendorCue: VideoSubtitleCue & { translation?: string } = { startMs, durationMs, text: cue.original }
31
+ if (fluentTranslation != null) vendorCue.translation = fluentTranslation
32
+ return vendorCue
33
+ })
34
+ }
35
+
36
+ /** vendor cue → 注入 cue(逆向:契约测试夹具/往返证明;Infinity duration → 无 durationMs) */
37
+ export function cuesFromVideoSubtitleCues(vendorCues: Array<VideoSubtitleCue & { translation?: string }>): SubtitleCue[] {
38
+ return vendorCues.map((vendorCue) => {
39
+ const cue: SubtitleCue = { tsMs: vendorCue.startMs, original: vendorCue.text }
40
+ if (Number.isFinite(vendorCue.durationMs) && vendorCue.durationMs > 0) cue.durationMs = vendorCue.durationMs
41
+ if (vendorCue.translation != null) cue.translations = { 'fluent-read': vendorCue.translation }
42
+ return cue
43
+ })
44
+ }
45
+
46
+ /** 时间轴选择:区间 [startMs, startMs+durationMs) 命中;Infinity duration 播到轨终点;间隙/越界 → null */
47
+ export function currentCueAt(cues: Array<VideoSubtitleCue & { translation?: string }>, timeMs: number): (VideoSubtitleCue & { translation?: string }) | null {
48
+ if (!Number.isFinite(timeMs) || timeMs < 0) return null
49
+ return cues.find((cue) => timeMs >= cue.startMs && timeMs < cue.startMs + cue.durationMs) ?? null
50
+ }