@sublane/supplier-fluent-read 0.3.0 → 0.3.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sublane/supplier-fluent-read",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "type": "module",
5
5
  "main": "./src/index.ts",
6
6
  "exports": {
@@ -0,0 +1,47 @@
1
+ diff --git a/src/features/video-subtitle/content/translationCache.ts b/src/features/video-subtitle/content/translationCache.ts
2
+ index d07d213..7d4f774 100644
3
+ --- a/src/features/video-subtitle/content/translationCache.ts
4
+ +++ b/src/features/video-subtitle/content/translationCache.ts
5
+ @@ -7,14 +7,22 @@
6
+ import {VideoTranslationScheduler} from './translationScheduler';
7
+ import {selectVideoSubtitlePretranslationCues} from './subtitleLogic';
8
+ import type {VideoSubtitleCue} from './youtubeSubtitleData';
9
+ +/** [wep patch 0015] 活动译文缓存注册表:adapter 侧据此发现 live 管线的活动实例(F-26 cue 流数据源)。 */
10
+ +export const videoTranslationCaches = new Set<VideoTranslationCache>();
11
+ +/** [wep patch 0015] 译文事件监听:缓存写入(译文产出)时通知,source 为规范化原文,translation 为已译文本。 */
12
+ +export type VideoTranslationListener = (source: string, translation: string) => void;
13
+ export class VideoTranslationCache {
14
+ private readonly translatedVideoCache = new Map<string, string>();
15
+ private readonly inFlightVideoTranslations = new Map<string, Promise<string>>();
16
+ private readonly videoTranslationFailures = new Map<string, {attempts: number; retryAt: number}>();
17
+ private readonly translationScheduler: VideoTranslationScheduler;
18
+ private pretranslationCacheVersion = 0;
19
+ + private readonly translationListeners = new Set<VideoTranslationListener>();
20
+ + /** [wep patch 0015] 实例创建时刻(adapter 排序取最新实例)。 */
21
+ + readonly createdAt = Date.now();
22
+ constructor(translate: (text: string, signal: AbortSignal) => Promise<string>) {
23
+ this.translationScheduler = new VideoTranslationScheduler(translate);
24
+ + videoTranslationCaches.add(this);
25
+ }
26
+ clear(): void {
27
+ this.translatedVideoCache.clear();
28
+ @@ -37,6 +45,11 @@ export class VideoTranslationCache {
29
+ peek(source: string): string | undefined {
30
+ return this.translatedVideoCache.get(source.replace(/[\s\u3000]+/g, ' ').trim());
31
+ }
32
+ + /** [wep patch 0015] 订阅译文产出事件(F-27/P1 数据面:adapter 经此读取 vendor 翻译节奏的产出)。 */
33
+ + subscribeTranslations(listener: VideoTranslationListener): () => void {
34
+ + this.translationListeners.add(listener);
35
+ + return () => this.translationListeners.delete(listener);
36
+ + }
37
+ retainPrefetches(sources: readonly string[]): void {
38
+ const keys = new Set(sources.map(source => source.replace(/[\s\u3000]+/g, ' ').trim()));
39
+ for (const source of this.translationScheduler.retainPrefetches(keys)) {
40
+ @@ -79,6 +92,7 @@ export class VideoTranslationCache {
41
+ if (requestVersion === this.pretranslationCacheVersion) {
42
+ this.videoTranslationFailures.delete(key);
43
+ this.translatedVideoCache.set(key, result);
44
+ + for (const listener of this.translationListeners) listener(key, result);
45
+ if (this.translatedVideoCache.size > 160) {
46
+ const oldestKey = this.translatedVideoCache.keys().next().value;
47
+ if (oldestKey) this.translatedVideoCache.delete(oldestKey);
package/src/adapter.ts CHANGED
@@ -6,11 +6,12 @@
6
6
  * 模块边界:只认识框架契约与 vendor 公共面(public.ts / config store);不翻译、不解析字幕、不渲染。
7
7
  */
8
8
  import type {
9
- PluginMountContext, SupplierRuntimeConfig, VideoSubtitlePluginInstance,
9
+ CueStreamEvent, PluginMountContext, SupplierRuntimeConfig, VideoSubtitlePluginInstance,
10
10
  } from '@sublane/core'
11
11
  import browser from 'webextension-polyfill'
12
12
  import { config, configReady, requestConfigPatch } from '../vendor/src/services/config/store'
13
13
  import { mountVideoSubtitleTranslation, isSupportedVideoPage } from '../vendor/src/features/video-subtitle/public'
14
+ import { videoTranslationCaches } from '../vendor/src/features/video-subtitle/content/translationCache'
14
15
  import { fluentReadHostRequirements } from './manifest'
15
16
  import { laneToAppearancePosition } from './lane'
16
17
  import { createDetachedInstance as createFluentDetachedInstance } from './detached'
@@ -193,6 +194,26 @@ export function createFluentReadInstance(ctx: PluginMountContext): VideoSubtitle
193
194
  void requestConfigPatch({ ...(laneChanged ? lanePatch(next.lane) : {}), ...diffSettingsPatch(next.settings) }, browser.runtime.sendMessage.bind(browser.runtime))
194
195
  .catch((error) => console.warn('[fluent-read] 配置同步失败', error))
195
196
  },
197
+ // 缺口2(F-26/0.3.1):fluent 译文数据面——vendor 翻译缓存产出事件流(patch 0015 注册表)。
198
+ // 语义声明:YouTube 默认 roll-up DOM 模式无 cue 区间概念,SubtitleCue.tsMs = 译文首见时刻
199
+ // (宿主 video currentTime);reset 为空快照(句子译文无时间轴可回放),宿主以 upsert 累积。
200
+ subscribeCues(listener: (event: CueStreamEvent) => void): () => void {
201
+ const cache = [...videoTranslationCaches].sort((a, b) => a.createdAt - b.createdAt).at(-1)
202
+ listener({ type: 'reset', cues: [], engine: 'fluent-read' })
203
+ if (!cache) return () => {}
204
+ return cache.subscribeTranslations((source: string, translation: string) => {
205
+ let tsMs = 0
206
+ try {
207
+ const video = document.querySelector<HTMLVideoElement>('video.html5-main-video, video')
208
+ if (video && Number.isFinite(video.currentTime)) tsMs = Math.round(video.currentTime * 1000)
209
+ } catch { /* 主世界不可达时时间轴缺省 0(时间轴语义见上注) */ }
210
+ listener({
211
+ type: 'upsert',
212
+ cues: [{ tsMs, original: source, translations: { 'fluent-read': translation } }],
213
+ engine: 'fluent-read',
214
+ })
215
+ })
216
+ },
196
217
  }
197
218
  return instance
198
219
  }
package/src/detached.ts CHANGED
@@ -17,7 +17,7 @@
17
17
  * 不写 vendor config、不触碰 live DOM(R1)。
18
18
  */
19
19
  import type {
20
- DetachedHandle, DetachedInstanceContext, SupplierRuntimeConfig, TrackSource,
20
+ CueStreamEvent, DetachedHandle, DetachedInstanceContext, SupplierRuntimeConfig, TrackSource,
21
21
  VideoSubtitlePluginInstance,
22
22
  } from '@sublane/core'
23
23
  import {
@@ -29,7 +29,7 @@ import { getVideoSubtitleAppearanceCssVars, normalizeVideoSubtitleAppearance } f
29
29
  import { fitVideoSubtitleFontSize } from '../vendor/src/features/video-subtitle/content/subtitleLayout'
30
30
  import { config } from '../vendor/src/services/config/store'
31
31
  import { laneToAppearancePosition } from './lane'
32
- import { currentCueAt, toVideoSubtitleCues } from './fluent-track'
32
+ import { cuesFromVideoSubtitleCues, currentCueAt, toVideoSubtitleCues } from './fluent-track'
33
33
 
34
34
  const PANEL_ACTIVE_CLASS = VIDEO_SUBTITLE_PANEL_ACTIVE_CLASS
35
35
 
@@ -43,6 +43,11 @@ function layoutPanel(panel: HTMLElement, video: HTMLVideoElement, bottomOffsetPe
43
43
  Object.entries(getVideoSubtitleAppearanceCssVars(appearance)).forEach(([name, value]) => panel.style.setProperty(name, value))
44
44
  panel.style.width = 'max-content'
45
45
  panel.style.setProperty('max-width', `${Math.max(0, hostWidth * appearance.maxWidth / 100)}px`, 'important')
46
+ // 缺口4-居中:宿主根下水平居中(CSS 方式,resize 免 JS;live 用实测宽度居中 ui.ts:609-615——
47
+ // detached 的 layer 内联了 inset 0,此三行即等价居中;声明为 detached 居中实现)
48
+ panel.style.left = '0'
49
+ panel.style.right = '0'
50
+ panel.style.margin = '0 auto'
46
51
  const baseFontSize = Math.min(Math.max(hostWidth * 0.022, 16), 30)
47
52
  const fontScale = appearance.fontScale / 100
48
53
  panel.style.setProperty('--fluent-read-video-subtitle-font-size', `${baseFontSize * fontScale}px`)
@@ -70,14 +75,26 @@ export async function createDetachedInstance(
70
75
  source: TrackSource,
71
76
  options?: DetachedMountOptions,
72
77
  ): Promise<VideoSubtitlePluginInstance & { detach(): DetachedHandle }> {
73
- // ①vendor 全局样式表就位(幂等;live 同款依赖)并取全文注入 shadow(R2 by construction)
74
- installVideoSubtitleStyle()
78
+ // ①vendor 全局样式表就位(幂等;live 同款依赖)并取全文注入 shadow(R2 by construction)。
79
+ // 缺口4-style 所有权:仅当 style 由本 detached 创建时,dispose 才在"无 live DOM 依赖"前提下移除;
80
+ // live 先于 detached 挂载时 style 已存在(非本实例创建),dispose 不动它(live 仍需要)。
81
+ let styleOwnedByDetached = false
82
+ if (!document.getElementById('fluent-read-video-subtitle-style')) {
83
+ installVideoSubtitleStyle()
84
+ styleOwnedByDetached = true
85
+ }
75
86
  const vendorCss = document.getElementById('fluent-read-video-subtitle-style')?.textContent ?? ''
76
87
 
77
88
  // ②数据面:注入轨 → vendor cue(时间轴数据;R5 缺译→无 translation 字段)
78
89
  let currentSource: TrackSource = source
79
90
  let vendorCues = toVideoSubtitleCues((await currentSource.getTrack().catch(() => null))?.cues ?? [])
80
91
  const unsubscribers: Array<() => void> = []
92
+ // 缺口3:有效轨回显流的订阅登记(数据变更点 notify——见 ingest/watchSource)
93
+ const cueListeners = new Set<(event: CueStreamEvent) => void>()
94
+ const notifyCueUpsert = () => {
95
+ const cues = cuesFromVideoSubtitleCues(vendorCues)
96
+ for (const listener of cueListeners) listener({ type: 'upsert', cues })
97
+ }
81
98
 
82
99
  // ③shadow host(宿主 video 父级,Q5 默认;host 不带 vendor ID——避免 document 级误命中)
83
100
  const parentEl = video.parentElement ?? document.body
@@ -156,29 +173,42 @@ export async function createDetachedInstance(
156
173
  video.addEventListener('seeked', onTime)
157
174
  onTime()
158
175
 
176
+ // ⑧b 缺口4:宿主尺寸变化跟踪——字号/可用宽/定位全部依赖宿主 rect,resize 后重排
177
+ // (ResizeObserver,disconnect 归 R6 清理)
178
+ const resizeObserver = new ResizeObserver(() => applyLayout())
179
+ resizeObserver.observe(video)
180
+
159
181
  // ⑨流式补译/换源(onUpdate + setSource)
160
182
  const ingest = async () => {
161
183
  vendorCues = toVideoSubtitleCues((await currentSource.getTrack().catch(() => null))?.cues ?? [])
162
184
  renderAt(video.currentTime * 1000)
185
+ notifyCueUpsert()
163
186
  }
164
187
  const watchSource = () => {
165
188
  if (!currentSource.onUpdate) return
166
189
  unsubscribers.push(currentSource.onUpdate((track) => {
167
190
  vendorCues = toVideoSubtitleCues(track.cues)
168
191
  onTime()
192
+ notifyCueUpsert()
169
193
  }))
170
194
  }
171
195
  watchSource()
172
196
 
173
- // ⑩R6/A9 清理:节点/监听/订阅全归零
197
+ // ⑩R6/A9 清理:节点/监听/订阅全归零;style 仅在"本 detached 创建且无 live DOM 依赖"时移除(缺口4)
174
198
  let cleaned = false
175
199
  const cleanup = () => {
176
200
  if (cleaned) return
177
201
  cleaned = true
202
+ resizeObserver.disconnect()
178
203
  video.removeEventListener('timeupdate', onTime)
179
204
  video.removeEventListener('seeked', onTime)
180
205
  for (const unsubscribe of unsubscribers.splice(0)) unsubscribe()
181
206
  shadowHost.remove()
207
+ if (styleOwnedByDetached
208
+ && !document.getElementById(VIDEO_SUBTITLE_PANEL_ID)
209
+ && !document.getElementById(VIDEO_TRANSLATION_LAYER_ID)) {
210
+ document.getElementById('fluent-read-video-subtitle-style')?.remove()
211
+ }
182
212
  }
183
213
 
184
214
  const instance = {
@@ -199,6 +229,12 @@ export async function createDetachedInstance(
199
229
  void ingest()
200
230
  watchSource()
201
231
  },
232
+ // 缺口3(0.3.1):有效轨回显流——订阅即 reset(vendor cue 规范化视图),ingest/onUpdate → upsert
233
+ subscribeCues(listener: (event: CueStreamEvent) => void): () => void {
234
+ cueListeners.add(listener)
235
+ listener({ type: 'reset', cues: cuesFromVideoSubtitleCues(vendorCues) })
236
+ return () => { cueListeners.delete(listener) }
237
+ },
202
238
  }
203
239
  },
204
240
  } satisfies VideoSubtitlePluginInstance & { detach(): DetachedHandle }
@@ -7,14 +7,22 @@
7
7
  import {VideoTranslationScheduler} from './translationScheduler';
8
8
  import {selectVideoSubtitlePretranslationCues} from './subtitleLogic';
9
9
  import type {VideoSubtitleCue} from './youtubeSubtitleData';
10
+ /** [wep patch 0015] 活动译文缓存注册表:adapter 侧据此发现 live 管线的活动实例(F-26 cue 流数据源)。 */
11
+ export const videoTranslationCaches = new Set<VideoTranslationCache>();
12
+ /** [wep patch 0015] 译文事件监听:缓存写入(译文产出)时通知,source 为规范化原文,translation 为已译文本。 */
13
+ export type VideoTranslationListener = (source: string, translation: string) => void;
10
14
  export class VideoTranslationCache {
11
15
  private readonly translatedVideoCache = new Map<string, string>();
12
16
  private readonly inFlightVideoTranslations = new Map<string, Promise<string>>();
13
17
  private readonly videoTranslationFailures = new Map<string, {attempts: number; retryAt: number}>();
14
18
  private readonly translationScheduler: VideoTranslationScheduler;
15
19
  private pretranslationCacheVersion = 0;
20
+ private readonly translationListeners = new Set<VideoTranslationListener>();
21
+ /** [wep patch 0015] 实例创建时刻(adapter 排序取最新实例)。 */
22
+ readonly createdAt = Date.now();
16
23
  constructor(translate: (text: string, signal: AbortSignal) => Promise<string>) {
17
24
  this.translationScheduler = new VideoTranslationScheduler(translate);
25
+ videoTranslationCaches.add(this);
18
26
  }
19
27
  clear(): void {
20
28
  this.translatedVideoCache.clear();
@@ -37,6 +45,11 @@ export class VideoTranslationCache {
37
45
  peek(source: string): string | undefined {
38
46
  return this.translatedVideoCache.get(source.replace(/[\s\u3000]+/g, ' ').trim());
39
47
  }
48
+ /** [wep patch 0015] 订阅译文产出事件(F-27/P1 数据面:adapter 经此读取 vendor 翻译节奏的产出)。 */
49
+ subscribeTranslations(listener: VideoTranslationListener): () => void {
50
+ this.translationListeners.add(listener);
51
+ return () => this.translationListeners.delete(listener);
52
+ }
40
53
  retainPrefetches(sources: readonly string[]): void {
41
54
  const keys = new Set(sources.map(source => source.replace(/[\s\u3000]+/g, ' ').trim()));
42
55
  for (const source of this.translationScheduler.retainPrefetches(keys)) {
@@ -79,6 +92,7 @@ export class VideoTranslationCache {
79
92
  if (requestVersion === this.pretranslationCacheVersion) {
80
93
  this.videoTranslationFailures.delete(key);
81
94
  this.translatedVideoCache.set(key, result);
95
+ for (const listener of this.translationListeners) listener(key, result);
82
96
  if (this.translatedVideoCache.size > 160) {
83
97
  const oldestKey = this.translatedVideoCache.keys().next().value;
84
98
  if (oldestKey) this.translatedVideoCache.delete(oldestKey);