File size: 9,192 Bytes
52361de
29cabc6
 
8268665
29cabc6
dac2ca2
 
 
 
 
29cabc6
dac2ca2
29cabc6
 
dac2ca2
29cabc6
 
 
52361de
 
 
 
 
 
29cabc6
8f9b02f
 
 
 
dac2ca2
29cabc6
 
52361de
 
 
 
 
 
29cabc6
52361de
 
 
8f9b02f
52361de
 
 
 
 
29cabc6
 
8f9b02f
29cabc6
8f9b02f
 
dac2ca2
29cabc6
 
 
52361de
 
 
 
 
 
 
 
29cabc6
 
 
1dc63a4
29cabc6
52361de
29cabc6
dac2ca2
29cabc6
dac2ca2
29cabc6
dac2ca2
22f4bc7
dac2ca2
22f4bc7
29cabc6
 
 
 
 
 
 
 
 
52361de
dac2ca2
52361de
 
dac2ca2
52361de
dac2ca2
52361de
 
29cabc6
 
dac2ca2
29cabc6
 
dac2ca2
8f9b02f
 
 
29cabc6
8f9b02f
29cabc6
 
 
dac2ca2
c1b563f
 
 
 
 
 
 
dac2ca2
29cabc6
 
 
 
 
 
dac2ca2
29cabc6
 
 
 
 
 
dac2ca2
29cabc6
 
 
 
 
dac2ca2
29cabc6
 
 
 
 
 
dac2ca2
52361de
 
 
dac2ca2
52361de
 
 
dac2ca2
52361de
 
 
 
dac2ca2
52361de
 
 
dac2ca2
52361de
 
 
 
 
 
 
 
dac2ca2
52361de
 
 
 
 
dac2ca2
52361de
 
 
 
 
 
 
 
dac2ca2
52361de
 
 
 
 
822b94b
 
 
 
 
 
 
 
 
 
dac2ca2
29cabc6
 
52361de
 
 
 
 
 
29cabc6
 
 
 
 
 
 
 
 
 
52361de
 
 
 
29cabc6
22f4bc7
 
52361de
 
29cabc6
 
 
 
 
52361de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29cabc6
 
dac2ca2
 
52361de
 
 
 
dac2ca2
29cabc6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
(function (root) {
  "use strict";

  const FEATURE_MATRIX = root.VoiceOfMLReader.features;

  /** @typedef {(detail: unknown, type: string) => void} EventListener */
  /** @typedef {{mode?: string, features?: object, [key: string]: unknown}} Capability */
  /** @typedef {ReaderRuntimeState} RuntimeState */
  /** @typedef {(() => void) | {dispose?: () => void}} Disposable */

  function createEventBus() {
    /** @type {Map<string, Set<EventListener>>} */
    const listeners = new Map();
    let disposed = false;
    /** @param {string} type @param {EventListener} listener */
    function on(type, listener) {
      if (disposed) return () => {};
      const set = listeners.get(type) || new Set();
      set.add(listener);
      listeners.set(type, set);
      return () => {
        set.delete(listener);
        if (!set.size) listeners.delete(type);
      };
    }
    /** @param {string} type */
    function hasListeners(type) {
      return !disposed && (listeners.has(type) || listeners.has("*"));
    }
    /** @param {string} type @param {unknown} detail */
    function emit(type, detail) {
      if (disposed) return;
      for (const listener of [...(listeners.get(type) || []), ...(listeners.get("*") || [])])
        listener(detail, type);
    }
    function dispose() {
      disposed = true;
      listeners.clear();
    }
    return Object.freeze({
      on,
      emit,
      hasListeners,
      dispose,
      get disposed() {
        return disposed;
      }
    });
  }

  /** @param {{events?: Readonly<ReaderEventBus>, initialState?: Partial<RuntimeState>}} [options] */
  function createReaderRuntime(options = {}) {
    const localBus = options.events ? null : createEventBus();
    const events = localBus || /** @type {Readonly<ReaderEventBus>} */ (options.events);
    /** @type {RuntimeState} */
    const state = {
      lifecycle: { phase: "startup", stage: "startup", disposed: false, errorCode: "" },
      source: { id: "", url: "", contentUrl: "", downloadUrl: "", extension: "", metadata: null },
      document: {
        title: "",
        zoom: 1,
        page: 1,
        pageCount: 0,
        restoredEntry: null,
        restorationReady: false
      },
      navigation: { tocEntries: [], currentChapterIndex: -1 },
      search: { query: "", results: [], index: -1 },
      panel: { open: false, selected: "toc", showingAllBookmarks: false, editingBookmark: null },
      formats: { active: null, pdf: {}, html: {}, media: {} },
      capability: null,
      ...(options.initialState || {})
    };
    /** @type {Map<string, number>} */
    const generations = new Map();
    /** @type {Set<Disposable>} */
    const disposables = new Set();
    /** @type {Set<ReturnType<typeof setTimeout>>} */
    const timers = new Set();
    /** @type {Set<number>} */
    const frames = new Set();

    function snapshot() {
      return Object.freeze({
        lifecycle: Object.freeze({ ...state.lifecycle }),
        source: Object.freeze({ ...state.source }),
        document: Object.freeze({ ...state.document }),
        navigation: Object.freeze({ ...state.navigation }),
        search: Object.freeze({ ...state.search }),
        panel: Object.freeze({ ...state.panel }),
        formats: Object.freeze(
          /** @type {ReaderRuntimeFormatsSnapshot} */ (Object.fromEntries(
            Object.entries(state.formats).map(([name, value]) => [
              name,
              Object.freeze({ .../** @type {object} */ (value) })
            ])
          ))
        ),
        capability: state.capability
      });
    }
    /** @template {ReaderRuntimeUpdateDomain} K @param {K} domain @param {Partial<RuntimeState[K]>} patch */
    function update(domain, patch) {
      if (state.lifecycle.disposed && domain !== "lifecycle") return false;
      Object.assign(/** @type {object} */ (state[domain]), patch);
      const type = `state:${domain}`;
      // Custom buses retain their original contract, even without subscriptions.
      if (localBus && !localBus.hasListeners(type) && !localBus.hasListeners("state")) return true;
      const current = snapshot();
      events.emit(type, current);
      events.emit("state", current);
      return true;
    }
    /** @param {string} format @param {Record<string, unknown>} patch */
    function updateFormat(format, patch) {
      if (state.lifecycle.disposed || !state.formats[format]) return false;
      Object.assign(state.formats[format], patch);
      events.emit(`format:${format}`, snapshot());
      events.emit("state", snapshot());
      return true;
    }
    /** @param {string} phase */
    function setPhase(phase) {
      if (state.lifecycle.disposed && phase !== "disposed") return false;
      state.lifecycle.phase = phase;
      events.emit("phase", { phase, state: snapshot() });
      return true;
    }
    /** @param {string} stage */
    function setStage(stage) {
      if (!setPhase(stage)) return false;
      state.lifecycle.stage = stage;
      events.emit("stage", { stage, state: snapshot() });
      return true;
    }
    /** @param {string} code */
    function fail(code) {
      state.lifecycle.errorCode = code;
      setPhase("failed");
      events.emit("error", { code, state: snapshot() });
    }
    /** @param {string} name */
    function nextGeneration(name) {
      const value = (generations.get(name) || 0) + 1;
      generations.set(name, value);
      events.emit("generation", { name, value });
      return value;
    }
    /** @param {string} name */
    function currentGeneration(name) {
      return generations.get(name) || 0;
    }
    /** @param {string} name @param {number} value */
    function isCurrent(name, value) {
      return !state.lifecycle.disposed && generations.get(name) === value;
    }
    /** @template {Disposable | null | undefined} T @param {T} disposable @returns {T} */
    function track(disposable) {
      if (disposable) disposables.add(disposable);
      return disposable;
    }
    /** @param {Disposable} disposable */
    function untrack(disposable) {
      disposables.delete(disposable);
    }
    /** @param {() => void} callback @param {number} [delay] */
    function schedule(callback, delay = 0) {
      const handle = setTimeout(() => {
        timers.delete(handle);
        callback();
      }, delay);
      timers.add(handle);
      return handle;
    }
    /** @param {ReturnType<typeof setTimeout>} handle */
    function cancel(handle) {
      if (!timers.has(handle)) return;
      clearTimeout(handle);
      timers.delete(handle);
    }
    /** @param {() => void} callback */
    function frame(callback) {
      const handle = requestAnimationFrame(() => {
        frames.delete(handle);
        callback();
      });
      frames.add(handle);
      return handle;
    }
    /** @param {number} handle */
    function cancelFrame(handle) {
      if (!frames.has(handle)) return;
      cancelAnimationFrame(handle);
      frames.delete(handle);
    }
    /**
     * @overload
     * @param {ReturnType<import('../../../typings/reader-contract-strict').ReaderContract['capability']>} capability
     * @returns {Readonly<ReturnType<import('../../../typings/reader-contract-strict').ReaderContract['capability']>>}
     */
    /**
     * @overload
     * @param {Capability | null | undefined} capability
     * @returns {Readonly<Capability & {features: object}>}
     */
    /** @param {Capability | null | undefined} capability */
    function negotiate(capability) {
      const mode = capability?.mode || "unsupported";
      const value = Object.freeze({
        ...capability,
        features: Object.freeze({
          ...(capability?.features || FEATURE_MATRIX[mode] || FEATURE_MATRIX.unsupported)
        })
      });
      state.capability = value;
      events.emit("capability", value);
      return value;
    }
    function dispose() {
      if (state.lifecycle.disposed) return;
      state.lifecycle.disposed = true;
      state.lifecycle.phase = "disposed";
      for (const name of generations.keys()) nextGeneration(name);
      for (const disposable of [...disposables].reverse()) {
        try {
          if (typeof disposable === "function") disposable();
          else disposable.dispose?.();
        } catch (_) {}
      }
      for (const handle of timers) clearTimeout(handle);
      for (const handle of frames) cancelAnimationFrame(handle);
      timers.clear();
      frames.clear();
      disposables.clear();
      events.emit("phase", { phase: "disposed", state: snapshot() });
      events.emit("dispose", snapshot());
      events.dispose();
    }
    return Object.freeze({
      state,
      events,
      snapshot,
      update,
      updateFormat,
      setPhase,
      setStage,
      fail,
      nextGeneration,
      currentGeneration,
      isCurrent,
      track,
      untrack,
      schedule,
      cancel,
      frame,
      cancelFrame,
      negotiate,
      dispose
    });
  }

  /** @satisfies {ReaderRuntimeApi} */
  const runtimeApi = Object.freeze({
    FEATURE_MATRIX,
    createEventBus,
    createReaderRuntime
  });
  root.VoiceOfMLReaderRuntime = runtimeApi;
})(typeof self !== "undefined" ? self : globalThis);