@sublane/supplier-fluent-read 0.3.0 → 0.3.2

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.2",
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.3.0"
50
+ "@sublane/core": "^0.3.1"
51
51
  },
52
52
  "devDependencies": {
53
53
  "@sublane/core": "workspace:*"
@@ -0,0 +1,54 @@
1
+ diff --git a/src/features/video-subtitle/content/translationCache.ts b/src/features/video-subtitle/content/translationCache.ts
2
+ index d07d213..bc9cbc9 100644
3
+ --- a/src/features/video-subtitle/content/translationCache.ts
4
+ +++ b/src/features/video-subtitle/content/translationCache.ts
5
+ @@ -7,14 +7,29 @@
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] 注册表新增事件:实例创建即通知——adapter 侧据此自动(重)绑定最新缓存(F-28:宿主零时序义务)。 */
12
+ +const videoTranslationCacheAddedListeners = new Set<(cache: VideoTranslationCache) => void>();
13
+ +export function onVideoTranslationCacheAdded(cb: (cache: VideoTranslationCache) => void): () => void {
14
+ + videoTranslationCacheAddedListeners.add(cb);
15
+ + return () => videoTranslationCacheAddedListeners.delete(cb);
16
+ +}
17
+ +/** [wep patch 0015] 译文事件监听:缓存写入(译文产出)时通知,source 为规范化原文,translation 为已译文本。 */
18
+ +export type VideoTranslationListener = (source: string, translation: string) => void;
19
+ export class VideoTranslationCache {
20
+ private readonly translatedVideoCache = new Map<string, string>();
21
+ private readonly inFlightVideoTranslations = new Map<string, Promise<string>>();
22
+ private readonly videoTranslationFailures = new Map<string, {attempts: number; retryAt: number}>();
23
+ private readonly translationScheduler: VideoTranslationScheduler;
24
+ private pretranslationCacheVersion = 0;
25
+ + private readonly translationListeners = new Set<VideoTranslationListener>();
26
+ + /** [wep patch 0015] 实例创建时刻(adapter 排序取最新实例)。 */
27
+ + readonly createdAt = Date.now();
28
+ constructor(translate: (text: string, signal: AbortSignal) => Promise<string>) {
29
+ this.translationScheduler = new VideoTranslationScheduler(translate);
30
+ + videoTranslationCaches.add(this);
31
+ + for (const listener of videoTranslationCacheAddedListeners) listener(this);
32
+ }
33
+ clear(): void {
34
+ this.translatedVideoCache.clear();
35
+ @@ -37,6 +52,11 @@ export class VideoTranslationCache {
36
+ peek(source: string): string | undefined {
37
+ return this.translatedVideoCache.get(source.replace(/[\s\u3000]+/g, ' ').trim());
38
+ }
39
+ + /** [wep patch 0015] 订阅译文产出事件(F-27/P1 数据面:adapter 经此读取 vendor 翻译节奏的产出)。 */
40
+ + subscribeTranslations(listener: VideoTranslationListener): () => void {
41
+ + this.translationListeners.add(listener);
42
+ + return () => this.translationListeners.delete(listener);
43
+ + }
44
+ retainPrefetches(sources: readonly string[]): void {
45
+ const keys = new Set(sources.map(source => source.replace(/[\s\u3000]+/g, ' ').trim()));
46
+ for (const source of this.translationScheduler.retainPrefetches(keys)) {
47
+ @@ -79,6 +99,7 @@ export class VideoTranslationCache {
48
+ if (requestVersion === this.pretranslationCacheVersion) {
49
+ this.videoTranslationFailures.delete(key);
50
+ this.translatedVideoCache.set(key, result);
51
+ + for (const listener of this.translationListeners) listener(key, result);
52
+ if (this.translatedVideoCache.size > 160) {
53
+ const oldestKey = this.translatedVideoCache.keys().next().value;
54
+ if (oldestKey) this.translatedVideoCache.delete(oldestKey);
package/src/adapter.ts CHANGED
@@ -6,11 +6,13 @@
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, onVideoTranslationCacheAdded } from '../vendor/src/features/video-subtitle/content/translationCache'
15
+ import { bindLatestCache } from './cache-watch'
14
16
  import { fluentReadHostRequirements } from './manifest'
15
17
  import { laneToAppearancePosition } from './lane'
16
18
  import { createDetachedInstance as createFluentDetachedInstance } from './detached'
@@ -193,6 +195,33 @@ export function createFluentReadInstance(ctx: PluginMountContext): VideoSubtitle
193
195
  void requestConfigPatch({ ...(laneChanged ? lanePatch(next.lane) : {}), ...diffSettingsPatch(next.settings) }, browser.runtime.sendMessage.bind(browser.runtime))
194
196
  .catch((error) => console.warn('[fluent-read] 配置同步失败', error))
195
197
  },
198
+ // 缺口2(F-26/0.3.1)+F-28(0.3.2):fluent 译文数据面——vendor 翻译缓存产出事件流。
199
+ // F-28 订阅时序:bindLatestCache 挂起/自动重绑——早订阅(vendor 未挂载,缓存未建)不 noop,
200
+ // 缓存创建即送达;实例重挂载/SPA 导航产生新缓存时自动切绑最新(宿主零时序义务)。
201
+ // 语义声明:YouTube 默认 roll-up DOM 模式无 cue 区间概念,SubtitleCue.tsMs = 译文首见时刻
202
+ // (宿主 video currentTime);reset 为空快照(句子译文无时间轴可回放),宿主以 upsert 累积。
203
+ subscribeCues(listener: (event: CueStreamEvent) => void): () => void {
204
+ listener({ type: 'reset', cues: [], engine: 'fluent-read' })
205
+ return bindLatestCache(
206
+ {
207
+ getAll: () => [...videoTranslationCaches],
208
+ onAdded: (cb) => onVideoTranslationCacheAdded(cb),
209
+ },
210
+ (cache, emit) => cache.subscribeTranslations((source, translation) => emit({ source, translation })),
211
+ ({ source, translation }) => {
212
+ let tsMs = 0
213
+ try {
214
+ const video = document.querySelector<HTMLVideoElement>('video.html5-main-video, video')
215
+ if (video && Number.isFinite(video.currentTime)) tsMs = Math.round(video.currentTime * 1000)
216
+ } catch { /* 主世界不可达时时间轴缺省 0(时间轴语义见上注) */ }
217
+ listener({
218
+ type: 'upsert',
219
+ cues: [{ tsMs, original: source, translations: { 'fluent-read': translation } }],
220
+ engine: 'fluent-read',
221
+ })
222
+ },
223
+ )
224
+ },
196
225
  }
197
226
  return instance
198
227
  }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * @file suppliers/fluent-read/src/cache-watch.ts
3
+ * 文件职责:F-28(0.3.2)——fluent 译文缓存绑定器:订阅时刻无缓存则挂起,缓存创建/更替时自动
4
+ * (重)绑定最新实例——宿主零时序义务(早订阅不 noop;SPA 导航/实例重挂载后无需重订阅)。
5
+ * 主要内容:bindLatestCache 参数化纯逻辑(getAll/onAdded/subscribeOne 依赖注入,node 直测)。
6
+ * 模块边界:不认识浏览器/DOM;事件映射(缓存事件→CueStreamEvent)归 adapter 接线层。
7
+ */
8
+ export interface CacheRegistry<TCache> {
9
+ getAll(): TCache[]
10
+ onAdded(cb: (cache: TCache) => void): () => void
11
+ }
12
+
13
+ /** 绑定最新缓存实例并跟随更替;返回总退订。
14
+ * 语义:①订阅时已有缓存 → 绑 createdAt 最新者;②无缓存 → 挂起(不发事件不报错),
15
+ * onAdded 触发即绑新缓存(新实例 createdAt 恒更晚,直接切换);③旧绑定先退订再绑新
16
+ * (旧实例迟到事件不送达);④总退订停一切。 */
17
+ export function bindLatestCache<TCache, TEvent>(
18
+ registry: CacheRegistry<TCache> & { getAll(): Array<TCache & { createdAt: number }> },
19
+ subscribeOne: (cache: TCache, emit: (payload: TEvent) => void) => () => void,
20
+ emit: (payload: TEvent) => void,
21
+ ): () => void {
22
+ let offCurrent: (() => void) | null = null
23
+ const bind = (cache: TCache) => {
24
+ offCurrent?.()
25
+ offCurrent = subscribeOne(cache, emit)
26
+ }
27
+ const latest = [...registry.getAll()].sort((a, b) => a.createdAt - b.createdAt).at(-1)
28
+ if (latest) bind(latest)
29
+ const offAdded = registry.onAdded((cache) => bind(cache))
30
+ return () => {
31
+ offCurrent?.()
32
+ offCurrent = null
33
+ offAdded()
34
+ }
35
+ }
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 {
@@ -27,9 +27,9 @@ import {
27
27
  } from '../vendor/src/features/video-subtitle/content/ui'
28
28
  import { getVideoSubtitleAppearanceCssVars, normalizeVideoSubtitleAppearance } from '../vendor/src/core/config/videoSubtitleAppearance'
29
29
  import { fitVideoSubtitleFontSize } from '../vendor/src/features/video-subtitle/content/subtitleLayout'
30
- import { config } from '../vendor/src/services/config/store'
30
+ import { config, subscribeConfig } 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,36 +173,59 @@ 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
+
181
+ // ⑧c F-30(0.3.2):config 跟随——vendor 配置 store 的 subscribeConfig(vendor runtime 自用同款)
182
+ // 接通:live 侧样式/显示模式变更 → detached 重排+重染。0.3.1 曾以"vendor 无订阅 API"为由
183
+ // 文档化此限制,系取证疏漏(store.ts:833 一直导出 subscribeConfig)——本版接通并勘误。
184
+ const offConfig = subscribeConfig(() => {
185
+ applyLayout()
186
+ applyDisplayMode()
187
+ onTime()
188
+ })
189
+
159
190
  // ⑨流式补译/换源(onUpdate + setSource)
160
191
  const ingest = async () => {
161
192
  vendorCues = toVideoSubtitleCues((await currentSource.getTrack().catch(() => null))?.cues ?? [])
162
193
  renderAt(video.currentTime * 1000)
194
+ notifyCueUpsert()
163
195
  }
164
196
  const watchSource = () => {
165
197
  if (!currentSource.onUpdate) return
166
198
  unsubscribers.push(currentSource.onUpdate((track) => {
167
199
  vendorCues = toVideoSubtitleCues(track.cues)
168
200
  onTime()
201
+ notifyCueUpsert()
169
202
  }))
170
203
  }
171
204
  watchSource()
172
205
 
173
- // ⑩R6/A9 清理:节点/监听/订阅全归零
206
+ // ⑩R6/A9 清理:节点/监听/订阅全归零;style 仅在"本 detached 创建且无 live DOM 依赖"时移除(缺口4)
174
207
  let cleaned = false
175
208
  const cleanup = () => {
176
209
  if (cleaned) return
177
210
  cleaned = true
211
+ resizeObserver.disconnect()
212
+ offConfig()
178
213
  video.removeEventListener('timeupdate', onTime)
179
214
  video.removeEventListener('seeked', onTime)
180
215
  for (const unsubscribe of unsubscribers.splice(0)) unsubscribe()
181
216
  shadowHost.remove()
217
+ if (styleOwnedByDetached
218
+ && !document.getElementById(VIDEO_SUBTITLE_PANEL_ID)
219
+ && !document.getElementById(VIDEO_TRANSLATION_LAYER_ID)) {
220
+ document.getElementById('fluent-read-video-subtitle-style')?.remove()
221
+ }
182
222
  }
183
223
 
184
224
  const instance = {
185
225
  mount() { /* 挂载已在 createDetachedInstance 完成(幂等空实现) */ },
186
226
  unmount() { cleanup() },
187
227
  setConfig(next: SupplierRuntimeConfig) {
188
- // lane 变更即时生效(M2);settings 的样式权威在 vendor config(与 live 同源)——P1 语义注记
228
+ // lane 变更即时生效(M2);样式/显示模式经 subscribeConfig 跟随 vendor config(F-30/0.3.2 接通)
189
229
  void next
190
230
  applyLayout()
191
231
  applyDisplayMode()
@@ -199,6 +239,12 @@ export async function createDetachedInstance(
199
239
  void ingest()
200
240
  watchSource()
201
241
  },
242
+ // 缺口3(0.3.1):有效轨回显流——订阅即 reset(vendor cue 规范化视图),ingest/onUpdate → upsert
243
+ subscribeCues(listener: (event: CueStreamEvent) => void): () => void {
244
+ cueListeners.add(listener)
245
+ listener({ type: 'reset', cues: cuesFromVideoSubtitleCues(vendorCues) })
246
+ return () => { cueListeners.delete(listener) }
247
+ },
202
248
  }
203
249
  },
204
250
  } satisfies VideoSubtitlePluginInstance & { detach(): DetachedHandle }
@@ -7,14 +7,29 @@
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] 注册表新增事件:实例创建即通知——adapter 侧据此自动(重)绑定最新缓存(F-28:宿主零时序义务)。 */
13
+ const videoTranslationCacheAddedListeners = new Set<(cache: VideoTranslationCache) => void>();
14
+ export function onVideoTranslationCacheAdded(cb: (cache: VideoTranslationCache) => void): () => void {
15
+ videoTranslationCacheAddedListeners.add(cb);
16
+ return () => videoTranslationCacheAddedListeners.delete(cb);
17
+ }
18
+ /** [wep patch 0015] 译文事件监听:缓存写入(译文产出)时通知,source 为规范化原文,translation 为已译文本。 */
19
+ export type VideoTranslationListener = (source: string, translation: string) => void;
10
20
  export class VideoTranslationCache {
11
21
  private readonly translatedVideoCache = new Map<string, string>();
12
22
  private readonly inFlightVideoTranslations = new Map<string, Promise<string>>();
13
23
  private readonly videoTranslationFailures = new Map<string, {attempts: number; retryAt: number}>();
14
24
  private readonly translationScheduler: VideoTranslationScheduler;
15
25
  private pretranslationCacheVersion = 0;
26
+ private readonly translationListeners = new Set<VideoTranslationListener>();
27
+ /** [wep patch 0015] 实例创建时刻(adapter 排序取最新实例)。 */
28
+ readonly createdAt = Date.now();
16
29
  constructor(translate: (text: string, signal: AbortSignal) => Promise<string>) {
17
30
  this.translationScheduler = new VideoTranslationScheduler(translate);
31
+ videoTranslationCaches.add(this);
32
+ for (const listener of videoTranslationCacheAddedListeners) listener(this);
18
33
  }
19
34
  clear(): void {
20
35
  this.translatedVideoCache.clear();
@@ -37,6 +52,11 @@ export class VideoTranslationCache {
37
52
  peek(source: string): string | undefined {
38
53
  return this.translatedVideoCache.get(source.replace(/[\s\u3000]+/g, ' ').trim());
39
54
  }
55
+ /** [wep patch 0015] 订阅译文产出事件(F-27/P1 数据面:adapter 经此读取 vendor 翻译节奏的产出)。 */
56
+ subscribeTranslations(listener: VideoTranslationListener): () => void {
57
+ this.translationListeners.add(listener);
58
+ return () => this.translationListeners.delete(listener);
59
+ }
40
60
  retainPrefetches(sources: readonly string[]): void {
41
61
  const keys = new Set(sources.map(source => source.replace(/[\s\u3000]+/g, ' ').trim()));
42
62
  for (const source of this.translationScheduler.retainPrefetches(keys)) {
@@ -79,6 +99,7 @@ export class VideoTranslationCache {
79
99
  if (requestVersion === this.pretranslationCacheVersion) {
80
100
  this.videoTranslationFailures.delete(key);
81
101
  this.translatedVideoCache.set(key, result);
102
+ for (const listener of this.translationListeners) listener(key, result);
82
103
  if (this.translatedVideoCache.size > 160) {
83
104
  const oldestKey = this.translatedVideoCache.keys().next().value;
84
105
  if (oldestKey) this.translatedVideoCache.delete(oldestKey);