@zodal/media 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +73 -2
- package/dist/chunk-3JIQJ7J6.js +148 -0
- package/dist/chunk-3JIQJ7J6.js.map +1 -0
- package/dist/chunk-7I3V4HKP.js +132 -0
- package/dist/chunk-7I3V4HKP.js.map +1 -0
- package/dist/chunk-AMK7QKN7.js +50 -0
- package/dist/chunk-AMK7QKN7.js.map +1 -0
- package/dist/chunk-NBKMSPYQ.js +46 -0
- package/dist/chunk-NBKMSPYQ.js.map +1 -0
- package/dist/chunk-P3EWPYFQ.js +42 -0
- package/dist/chunk-P3EWPYFQ.js.map +1 -0
- package/dist/chunk-YBCEHG5I.js +68 -0
- package/dist/chunk-YBCEHG5I.js.map +1 -0
- package/dist/commands.cjs +198 -0
- package/dist/commands.cjs.map +1 -0
- package/dist/commands.d.cts +17 -0
- package/dist/commands.d.ts +17 -0
- package/dist/commands.js +171 -0
- package/dist/commands.js.map +1 -0
- package/dist/cues.cjs +78 -0
- package/dist/cues.cjs.map +1 -0
- package/dist/cues.d.cts +39 -0
- package/dist/cues.d.ts +39 -0
- package/dist/cues.js +15 -0
- package/dist/cues.js.map +1 -0
- package/dist/follow.cjs +162 -0
- package/dist/follow.cjs.map +1 -0
- package/dist/follow.d.cts +83 -0
- package/dist/follow.d.ts +83 -0
- package/dist/follow.js +19 -0
- package/dist/follow.js.map +1 -0
- package/dist/index.cjs +510 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +6 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.js +59 -0
- package/dist/index.js.map +1 -0
- package/dist/playback.cjs +72 -0
- package/dist/playback.cjs.map +1 -0
- package/dist/playback.d.cts +47 -0
- package/dist/playback.d.ts +47 -0
- package/dist/playback.js +11 -0
- package/dist/playback.js.map +1 -0
- package/dist/sleep.cjs +176 -0
- package/dist/sleep.cjs.map +1 -0
- package/dist/sleep.d.cts +99 -0
- package/dist/sleep.d.ts +99 -0
- package/dist/sleep.js +15 -0
- package/dist/sleep.js.map +1 -0
- package/dist/timed-text.cjs +155 -0
- package/dist/timed-text.cjs.map +1 -0
- package/dist/timed-text.d.cts +44 -0
- package/dist/timed-text.d.ts +44 -0
- package/dist/timed-text.js +9 -0
- package/dist/timed-text.js.map +1 -0
- package/dist/transport.cjs +167 -0
- package/dist/transport.cjs.map +1 -0
- package/dist/transport.d.cts +74 -0
- package/dist/transport.d.ts +74 -0
- package/dist/transport.js +110 -0
- package/dist/transport.js.map +1 -0
- package/dist/vtt.cjs +66 -0
- package/dist/vtt.cjs.map +1 -0
- package/dist/vtt.d.cts +22 -0
- package/dist/vtt.d.ts +22 -0
- package/dist/vtt.js +7 -0
- package/dist/vtt.js.map +1 -0
- package/package.json +152 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import {
|
|
2
|
+
parseWebVtt
|
|
3
|
+
} from "./chunk-P3EWPYFQ.js";
|
|
4
|
+
import {
|
|
5
|
+
DEFAULT_FOLLOW_OPTIONS,
|
|
6
|
+
DEFAULT_OWN_SCROLL_MS,
|
|
7
|
+
SCROLL_KEYS,
|
|
8
|
+
attachFollow,
|
|
9
|
+
createFollow,
|
|
10
|
+
scrollLineIntoContainer,
|
|
11
|
+
scrollerOf
|
|
12
|
+
} from "./chunk-7I3V4HKP.js";
|
|
13
|
+
import {
|
|
14
|
+
createTimedText
|
|
15
|
+
} from "./chunk-YBCEHG5I.js";
|
|
16
|
+
import {
|
|
17
|
+
CUE_EPSILON_S,
|
|
18
|
+
cueAt,
|
|
19
|
+
cuesDuration,
|
|
20
|
+
formatTime,
|
|
21
|
+
wordAt
|
|
22
|
+
} from "./chunk-AMK7QKN7.js";
|
|
23
|
+
import {
|
|
24
|
+
DEFAULT_SLEEP_FADE_MS,
|
|
25
|
+
DEFAULT_SLEEP_TICK_MS,
|
|
26
|
+
SLEEP_MINUTES,
|
|
27
|
+
createSleepTimer,
|
|
28
|
+
formatCountdown
|
|
29
|
+
} from "./chunk-3JIQJ7J6.js";
|
|
30
|
+
import {
|
|
31
|
+
SEEK_LAND_TIMEOUT_MS,
|
|
32
|
+
seekLanded,
|
|
33
|
+
seekThenPlay
|
|
34
|
+
} from "./chunk-NBKMSPYQ.js";
|
|
35
|
+
export {
|
|
36
|
+
CUE_EPSILON_S,
|
|
37
|
+
DEFAULT_FOLLOW_OPTIONS,
|
|
38
|
+
DEFAULT_OWN_SCROLL_MS,
|
|
39
|
+
DEFAULT_SLEEP_FADE_MS,
|
|
40
|
+
DEFAULT_SLEEP_TICK_MS,
|
|
41
|
+
SCROLL_KEYS,
|
|
42
|
+
SEEK_LAND_TIMEOUT_MS,
|
|
43
|
+
SLEEP_MINUTES,
|
|
44
|
+
attachFollow,
|
|
45
|
+
createFollow,
|
|
46
|
+
createSleepTimer,
|
|
47
|
+
createTimedText,
|
|
48
|
+
cueAt,
|
|
49
|
+
cuesDuration,
|
|
50
|
+
formatCountdown,
|
|
51
|
+
formatTime,
|
|
52
|
+
parseWebVtt,
|
|
53
|
+
scrollLineIntoContainer,
|
|
54
|
+
scrollerOf,
|
|
55
|
+
seekLanded,
|
|
56
|
+
seekThenPlay,
|
|
57
|
+
wordAt
|
|
58
|
+
};
|
|
59
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/playback.ts
|
|
21
|
+
var playback_exports = {};
|
|
22
|
+
__export(playback_exports, {
|
|
23
|
+
SEEK_LAND_TIMEOUT_MS: () => SEEK_LAND_TIMEOUT_MS,
|
|
24
|
+
seekLanded: () => seekLanded,
|
|
25
|
+
seekThenPlay: () => seekThenPlay
|
|
26
|
+
});
|
|
27
|
+
module.exports = __toCommonJS(playback_exports);
|
|
28
|
+
var SEEK_LAND_TIMEOUT_MS = 1500;
|
|
29
|
+
function abortError() {
|
|
30
|
+
const e = new Error("The play was cancelled while its seek was landing.");
|
|
31
|
+
e.name = "AbortError";
|
|
32
|
+
return e;
|
|
33
|
+
}
|
|
34
|
+
function seekLanded(port, { timeoutMs = SEEK_LAND_TIMEOUT_MS, signal } = {}) {
|
|
35
|
+
if (signal?.aborted) return Promise.reject(abortError());
|
|
36
|
+
if (!port.seeking || !port.addEventListener) return Promise.resolve();
|
|
37
|
+
return new Promise((resolve, reject) => {
|
|
38
|
+
let timer;
|
|
39
|
+
const settle = () => {
|
|
40
|
+
clearTimeout(timer);
|
|
41
|
+
port.removeEventListener?.("seeked", landed);
|
|
42
|
+
signal?.removeEventListener("abort", aborted);
|
|
43
|
+
};
|
|
44
|
+
const landed = () => {
|
|
45
|
+
settle();
|
|
46
|
+
resolve();
|
|
47
|
+
};
|
|
48
|
+
const aborted = () => {
|
|
49
|
+
settle();
|
|
50
|
+
reject(abortError());
|
|
51
|
+
};
|
|
52
|
+
timer = setTimeout(() => {
|
|
53
|
+
if (!port.seeking) landed();
|
|
54
|
+
}, timeoutMs);
|
|
55
|
+
port.addEventListener("seeked", landed);
|
|
56
|
+
signal?.addEventListener("abort", aborted);
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
function seekThenPlay(port, time, options = {}) {
|
|
60
|
+
const play = options.play ?? (() => port.play());
|
|
61
|
+
const wasEnded = !!port.ended;
|
|
62
|
+
port.currentTime = time;
|
|
63
|
+
if (!wasEnded || !port.seeking) return Promise.resolve(play());
|
|
64
|
+
return seekLanded(port, options).then(() => play());
|
|
65
|
+
}
|
|
66
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
67
|
+
0 && (module.exports = {
|
|
68
|
+
SEEK_LAND_TIMEOUT_MS,
|
|
69
|
+
seekLanded,
|
|
70
|
+
seekThenPlay
|
|
71
|
+
});
|
|
72
|
+
//# sourceMappingURL=playback.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/playback.ts"],"sourcesContent":["/**\n * Playing from a chosen point, safely on every engine, with no DOM beyond the port itself.\n *\n * The trap: in WebKit (Safari, and every browser on an iPhone or iPad) `el.currentTime = t;\n * el.play()` on an element that has *ended* starts from the end, which ends again at once, or\n * from 0, because the seek has not landed when `play()` runs. Chromium and Firefox apply the\n * seek first. It shows as \"after the audio finished, tapping a transcript line plays from the\n * start\" (annals, 2026-11-13). Measured in Playwright WebKit: 12 of 12 taps restarted at 0;\n * calling `play()` first and seeking again still failed 10 of 12; waiting for `seeked` and then\n * playing was right 16 of 16.\n *\n * So `seekThenPlay` reads whether the element had ended *before* seeking (after the seek WebKit\n * already reports `ended === false`), and if it had and the seek is still landing, it plays on\n * `seeked`. The element has played before, so playing outside the tap is allowed.\n */\n\n/** The part of a media element `seekThenPlay` uses. The optional members are an HTMLMediaElement's. */\nexport interface SeekablePort {\n currentTime: number;\n play(): Promise<void> | void;\n /** True once playback reached the end. A port without it is never waited on. */\n readonly ended?: boolean;\n /** True while a seek is landing. */\n readonly seeking?: boolean;\n addEventListener?(type: 'seeked', listener: () => void): void;\n removeEventListener?(type: 'seeked', listener: () => void): void;\n}\n\n/** Play anyway after this long, if no seek is under way by then (a seek still landing is still awaited). */\nexport const SEEK_LAND_TIMEOUT_MS = 1500;\n\nexport interface SeekThenPlayOptions {\n /** What starting playback means; defaults to `port.play()`. A player passes its own, to catch a refusal. */\n play?: () => Promise<void> | void;\n timeoutMs?: number;\n /** Cancels a play held for its seek (a pause meanwhile): the promise rejects with an AbortError. */\n signal?: AbortSignal;\n}\n\nfunction abortError(): Error {\n const e = new Error('The play was cancelled while its seek was landing.');\n e.name = 'AbortError';\n return e;\n}\n\n/** Resolves once `port`'s seek has landed (`seeked`), or at once when no seek is landing. */\nexport function seekLanded(\n port: SeekablePort,\n { timeoutMs = SEEK_LAND_TIMEOUT_MS, signal }: { timeoutMs?: number; signal?: AbortSignal } = {},\n): Promise<void> {\n if (signal?.aborted) return Promise.reject(abortError());\n if (!port.seeking || !port.addEventListener) return Promise.resolve();\n return new Promise((resolve, reject) => {\n let timer: ReturnType<typeof setTimeout> | undefined;\n const settle = () => {\n clearTimeout(timer);\n port.removeEventListener?.('seeked', landed);\n signal?.removeEventListener('abort', aborted);\n };\n const landed = () => { settle(); resolve(); };\n const aborted = () => { settle(); reject(abortError()); };\n // Playing while the seek is still under way is the bug itself, so the timer only ends a wait\n // whose seek is over without a `seeked` (a source that went away).\n timer = setTimeout(() => { if (!port.seeking) landed(); }, timeoutMs);\n port.addEventListener!('seeked', landed);\n signal?.addEventListener('abort', aborted);\n });\n}\n\n/**\n * Seeks `port` to `time` and plays from there, also when it has ended (see the module note).\n * Plays synchronously, inside the tap, whenever it can; returns what playing returned.\n */\nexport function seekThenPlay(port: SeekablePort, time: number, options: SeekThenPlayOptions = {}): Promise<void> {\n const play = options.play ?? (() => port.play());\n const wasEnded = !!port.ended;\n port.currentTime = time;\n if (!wasE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[]}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Playing from a chosen point, safely on every engine, with no DOM beyond the port itself.
|
|
3
|
+
*
|
|
4
|
+
* The trap: in WebKit (Safari, and every browser on an iPhone or iPad) `el.currentTime = t;
|
|
5
|
+
* el.play()` on an element that has *ended* starts from the end, which ends again at once, or
|
|
6
|
+
* from 0, because the seek has not landed when `play()` runs. Chromium and Firefox apply the
|
|
7
|
+
* seek first. It shows as "after the audio finished, tapping a transcript line plays from the
|
|
8
|
+
* start" (annals, 2026-11-13). Measured in Playwright WebKit: 12 of 12 taps restarted at 0;
|
|
9
|
+
* calling `play()` first and seeking again still failed 10 of 12; waiting for `seeked` and then
|
|
10
|
+
* playing was right 16 of 16.
|
|
11
|
+
*
|
|
12
|
+
* So `seekThenPlay` reads whether the element had ended *before* seeking (after the seek WebKit
|
|
13
|
+
* already reports `ended === false`), and if it had and the seek is still landing, it plays on
|
|
14
|
+
* `seeked`. The element has played before, so playing outside the tap is allowed.
|
|
15
|
+
*/
|
|
16
|
+
/** The part of a media element `seekThenPlay` uses. The optional members are an HTMLMediaElement's. */
|
|
17
|
+
interface SeekablePort {
|
|
18
|
+
currentTime: number;
|
|
19
|
+
play(): Promise<void> | void;
|
|
20
|
+
/** True once playback reached the end. A port without it is never waited on. */
|
|
21
|
+
readonly ended?: boolean;
|
|
22
|
+
/** True while a seek is landing. */
|
|
23
|
+
readonly seeking?: boolean;
|
|
24
|
+
addEventListener?(type: 'seeked', listener: () => void): void;
|
|
25
|
+
removeEventListener?(type: 'seeked', listener: () => void): void;
|
|
26
|
+
}
|
|
27
|
+
/** Play anyway after this long, if no seek is under way by then (a seek still landing is still awaited). */
|
|
28
|
+
declare const SEEK_LAND_TIMEOUT_MS = 1500;
|
|
29
|
+
interface SeekThenPlayOptions {
|
|
30
|
+
/** What starting playback means; defaults to `port.play()`. A player passes its own, to catch a refusal. */
|
|
31
|
+
play?: () => Promise<void> | void;
|
|
32
|
+
timeoutMs?: number;
|
|
33
|
+
/** Cancels a play held for its seek (a pause meanwhile): the promise rejects with an AbortError. */
|
|
34
|
+
signal?: AbortSignal;
|
|
35
|
+
}
|
|
36
|
+
/** Resolves once `port`'s seek has landed (`seeked`), or at once when no seek is landing. */
|
|
37
|
+
declare function seekLanded(port: SeekablePort, { timeoutMs, signal }?: {
|
|
38
|
+
timeoutMs?: number;
|
|
39
|
+
signal?: AbortSignal;
|
|
40
|
+
}): Promise<void>;
|
|
41
|
+
/**
|
|
42
|
+
* Seeks `port` to `time` and plays from there, also when it has ended (see the module note).
|
|
43
|
+
* Plays synchronously, inside the tap, whenever it can; returns what playing returned.
|
|
44
|
+
*/
|
|
45
|
+
declare function seekThenPlay(port: SeekablePort, time: number, options?: SeekThenPlayOptions): Promise<void>;
|
|
46
|
+
|
|
47
|
+
export { SEEK_LAND_TIMEOUT_MS, type SeekThenPlayOptions, type SeekablePort, seekLanded, seekThenPlay };
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Playing from a chosen point, safely on every engine, with no DOM beyond the port itself.
|
|
3
|
+
*
|
|
4
|
+
* The trap: in WebKit (Safari, and every browser on an iPhone or iPad) `el.currentTime = t;
|
|
5
|
+
* el.play()` on an element that has *ended* starts from the end, which ends again at once, or
|
|
6
|
+
* from 0, because the seek has not landed when `play()` runs. Chromium and Firefox apply the
|
|
7
|
+
* seek first. It shows as "after the audio finished, tapping a transcript line plays from the
|
|
8
|
+
* start" (annals, 2026-11-13). Measured in Playwright WebKit: 12 of 12 taps restarted at 0;
|
|
9
|
+
* calling `play()` first and seeking again still failed 10 of 12; waiting for `seeked` and then
|
|
10
|
+
* playing was right 16 of 16.
|
|
11
|
+
*
|
|
12
|
+
* So `seekThenPlay` reads whether the element had ended *before* seeking (after the seek WebKit
|
|
13
|
+
* already reports `ended === false`), and if it had and the seek is still landing, it plays on
|
|
14
|
+
* `seeked`. The element has played before, so playing outside the tap is allowed.
|
|
15
|
+
*/
|
|
16
|
+
/** The part of a media element `seekThenPlay` uses. The optional members are an HTMLMediaElement's. */
|
|
17
|
+
interface SeekablePort {
|
|
18
|
+
currentTime: number;
|
|
19
|
+
play(): Promise<void> | void;
|
|
20
|
+
/** True once playback reached the end. A port without it is never waited on. */
|
|
21
|
+
readonly ended?: boolean;
|
|
22
|
+
/** True while a seek is landing. */
|
|
23
|
+
readonly seeking?: boolean;
|
|
24
|
+
addEventListener?(type: 'seeked', listener: () => void): void;
|
|
25
|
+
removeEventListener?(type: 'seeked', listener: () => void): void;
|
|
26
|
+
}
|
|
27
|
+
/** Play anyway after this long, if no seek is under way by then (a seek still landing is still awaited). */
|
|
28
|
+
declare const SEEK_LAND_TIMEOUT_MS = 1500;
|
|
29
|
+
interface SeekThenPlayOptions {
|
|
30
|
+
/** What starting playback means; defaults to `port.play()`. A player passes its own, to catch a refusal. */
|
|
31
|
+
play?: () => Promise<void> | void;
|
|
32
|
+
timeoutMs?: number;
|
|
33
|
+
/** Cancels a play held for its seek (a pause meanwhile): the promise rejects with an AbortError. */
|
|
34
|
+
signal?: AbortSignal;
|
|
35
|
+
}
|
|
36
|
+
/** Resolves once `port`'s seek has landed (`seeked`), or at once when no seek is landing. */
|
|
37
|
+
declare function seekLanded(port: SeekablePort, { timeoutMs, signal }?: {
|
|
38
|
+
timeoutMs?: number;
|
|
39
|
+
signal?: AbortSignal;
|
|
40
|
+
}): Promise<void>;
|
|
41
|
+
/**
|
|
42
|
+
* Seeks `port` to `time` and plays from there, also when it has ended (see the module note).
|
|
43
|
+
* Plays synchronously, inside the tap, whenever it can; returns what playing returned.
|
|
44
|
+
*/
|
|
45
|
+
declare function seekThenPlay(port: SeekablePort, time: number, options?: SeekThenPlayOptions): Promise<void>;
|
|
46
|
+
|
|
47
|
+
export { SEEK_LAND_TIMEOUT_MS, type SeekThenPlayOptions, type SeekablePort, seekLanded, seekThenPlay };
|
package/dist/playback.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
package/dist/sleep.cjs
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/sleep.ts
|
|
21
|
+
var sleep_exports = {};
|
|
22
|
+
__export(sleep_exports, {
|
|
23
|
+
DEFAULT_SLEEP_FADE_MS: () => DEFAULT_SLEEP_FADE_MS,
|
|
24
|
+
DEFAULT_SLEEP_TICK_MS: () => DEFAULT_SLEEP_TICK_MS,
|
|
25
|
+
SLEEP_MINUTES: () => SLEEP_MINUTES,
|
|
26
|
+
createSleepTimer: () => createSleepTimer,
|
|
27
|
+
formatCountdown: () => formatCountdown
|
|
28
|
+
});
|
|
29
|
+
module.exports = __toCommonJS(sleep_exports);
|
|
30
|
+
var DEFAULT_SLEEP_FADE_MS = 1e4;
|
|
31
|
+
var DEFAULT_SLEEP_TICK_MS = 1e3;
|
|
32
|
+
var SLEEP_MINUTES = [5, 10, 15, 20, 30, 45, 60, 90];
|
|
33
|
+
var JUMP_S = 3;
|
|
34
|
+
var END_EPSILON_S = 0.25;
|
|
35
|
+
var OFF = { target: null, remainingMs: null, fading: false, ended: null };
|
|
36
|
+
function createSleepTimer(port, options = {}) {
|
|
37
|
+
const {
|
|
38
|
+
fadeMs = DEFAULT_SLEEP_FADE_MS,
|
|
39
|
+
tickMs = DEFAULT_SLEEP_TICK_MS,
|
|
40
|
+
gain,
|
|
41
|
+
pause = () => port.pause(),
|
|
42
|
+
now = () => Date.now(),
|
|
43
|
+
setTimer = (fn, ms) => setTimeout(fn, ms),
|
|
44
|
+
clearTimer = (h) => clearTimeout(h)
|
|
45
|
+
} = options;
|
|
46
|
+
let state = OFF;
|
|
47
|
+
const listeners = /* @__PURE__ */ new Set();
|
|
48
|
+
const emit = (next) => {
|
|
49
|
+
const previous = state;
|
|
50
|
+
state = next;
|
|
51
|
+
listeners.forEach((l) => l(state, previous));
|
|
52
|
+
};
|
|
53
|
+
let leftMs = 0;
|
|
54
|
+
let lastAt = 0;
|
|
55
|
+
let lastTime = 0;
|
|
56
|
+
let volume = null;
|
|
57
|
+
let fadingNow = false;
|
|
58
|
+
let handle = null;
|
|
59
|
+
const setLevel = (level) => {
|
|
60
|
+
if (gain) {
|
|
61
|
+
gain(level);
|
|
62
|
+
fadingNow = level < 1;
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
if (level >= 1) {
|
|
66
|
+
if (volume !== null) port.volume = volume;
|
|
67
|
+
volume = null;
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
if (volume === null) volume = port.volume;
|
|
71
|
+
port.volume = volume * level;
|
|
72
|
+
};
|
|
73
|
+
const restoreVolume = () => {
|
|
74
|
+
if (gain) {
|
|
75
|
+
if (fadingNow) gain(1);
|
|
76
|
+
fadingNow = false;
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
setLevel(1);
|
|
80
|
+
};
|
|
81
|
+
const schedule = () => {
|
|
82
|
+
if (handle !== null) clearTimer(handle);
|
|
83
|
+
handle = state.target ? setTimer(tick, state.fading ? Math.min(100, tickMs) : tickMs) : null;
|
|
84
|
+
};
|
|
85
|
+
const stop = (reason) => {
|
|
86
|
+
restoreVolume();
|
|
87
|
+
if (handle !== null) clearTimer(handle);
|
|
88
|
+
handle = null;
|
|
89
|
+
emit({ ...OFF, ended: reason });
|
|
90
|
+
};
|
|
91
|
+
const mediaLeftMs = (seconds) => Math.max(0, seconds - port.currentTime) / (port.playbackRate || 1) * 1e3;
|
|
92
|
+
function tick() {
|
|
93
|
+
const target = state.target;
|
|
94
|
+
if (!target) return;
|
|
95
|
+
const t = now();
|
|
96
|
+
const time = port.currentTime;
|
|
97
|
+
const playing = !port.paused;
|
|
98
|
+
let remaining;
|
|
99
|
+
if (target.kind === "after") {
|
|
100
|
+
if (playing) leftMs -= Math.max(0, t - lastAt);
|
|
101
|
+
remaining = leftMs;
|
|
102
|
+
} else {
|
|
103
|
+
const at = target.kind === "at" ? target.seconds : port.duration;
|
|
104
|
+
if (!Number.isFinite(at) || at <= 0) {
|
|
105
|
+
remaining = Infinity;
|
|
106
|
+
} else {
|
|
107
|
+
const jumped = Math.abs(time - lastTime) > JUMP_S * Math.max(1, port.playbackRate) + (t - lastAt) / 1e3;
|
|
108
|
+
if (jumped && lastTime < at - END_EPSILON_S && time > at) {
|
|
109
|
+
lastAt = t;
|
|
110
|
+
lastTime = time;
|
|
111
|
+
return stop("passed");
|
|
112
|
+
}
|
|
113
|
+
remaining = port.ended || time >= at - END_EPSILON_S ? 0 : mediaLeftMs(at);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
lastAt = t;
|
|
117
|
+
lastTime = time;
|
|
118
|
+
if (remaining <= 0) {
|
|
119
|
+
if (playing) pause();
|
|
120
|
+
return stop("slept");
|
|
121
|
+
}
|
|
122
|
+
const fading = playing && fadeMs > 0 && remaining <= fadeMs;
|
|
123
|
+
if (fading) setLevel(remaining / fadeMs);
|
|
124
|
+
else restoreVolume();
|
|
125
|
+
emit({ target, remainingMs: Number.isFinite(remaining) ? Math.round(remaining) : null, fading, ended: null });
|
|
126
|
+
schedule();
|
|
127
|
+
}
|
|
128
|
+
const onTimeupdate = () => tick();
|
|
129
|
+
port.addEventListener?.("timeupdate", onTimeupdate);
|
|
130
|
+
const timer = {
|
|
131
|
+
get: () => state,
|
|
132
|
+
subscribe(listener) {
|
|
133
|
+
listeners.add(listener);
|
|
134
|
+
return () => listeners.delete(listener);
|
|
135
|
+
},
|
|
136
|
+
set(target) {
|
|
137
|
+
restoreVolume();
|
|
138
|
+
if (target.kind === "after") leftMs = Math.max(0, target.minutes) * 6e4;
|
|
139
|
+
lastAt = now();
|
|
140
|
+
lastTime = port.currentTime;
|
|
141
|
+
state = { ...OFF, target };
|
|
142
|
+
tick();
|
|
143
|
+
},
|
|
144
|
+
extend(minutes) {
|
|
145
|
+
const target = state.target;
|
|
146
|
+
if (!target) return timer.set({ kind: "after", minutes });
|
|
147
|
+
const base = target.kind === "after" ? leftMs : state.remainingMs ?? 0;
|
|
148
|
+
timer.set({ kind: "after", minutes: (base + minutes * 6e4) / 6e4 });
|
|
149
|
+
},
|
|
150
|
+
cancel() {
|
|
151
|
+
if (state.target) stop("cancelled");
|
|
152
|
+
},
|
|
153
|
+
tick,
|
|
154
|
+
dispose() {
|
|
155
|
+
port.removeEventListener?.("timeupdate", onTimeupdate);
|
|
156
|
+
if (state.target) restoreVolume();
|
|
157
|
+
if (handle !== null) clearTimer(handle);
|
|
158
|
+
handle = null;
|
|
159
|
+
listeners.clear();
|
|
160
|
+
}
|
|
161
|
+
};
|
|
162
|
+
return timer;
|
|
163
|
+
}
|
|
164
|
+
function formatCountdown(ms) {
|
|
165
|
+
const s = Math.max(0, Math.ceil(ms / 1e3));
|
|
166
|
+
return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
|
|
167
|
+
}
|
|
168
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
169
|
+
0 && (module.exports = {
|
|
170
|
+
DEFAULT_SLEEP_FADE_MS,
|
|
171
|
+
DEFAULT_SLEEP_TICK_MS,
|
|
172
|
+
SLEEP_MINUTES,
|
|
173
|
+
createSleepTimer,
|
|
174
|
+
formatCountdown
|
|
175
|
+
});
|
|
176
|
+
//# sourceMappingURL=sleep.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/sleep.ts"],"sourcesContent":["/**\n * A sleep timer: pause the media after some listening time, or at a point in it (the end of a\n * chapter, the end of the item), fading the volume out first so the stop does not wake anyone.\n * Headless: no DOM beyond an optional `timeupdate` listener on the port, no zustand, no React.\n *\n * ```ts\n * const sleep = createSleepTimer(audio);\n * sleep.set({ kind: 'after', minutes: 15 }); // 15 minutes of listening\n * sleep.set({ kind: 'at', seconds: 1260 }); // at 21:00 in the item (a chapter's end)\n * sleep.set({ kind: 'end' }); // at the end of the item\n * sleep.extend(5); sleep.cancel();\n * sleep.subscribe((s) => render(s.remainingMs, s.fading));\n * ```\n *\n * Choices, each a default the host can change:\n * - **Listening time, not clock time.** `after` counts down only while the media plays: a person\n * who paused is not asleep, and a timer that ran out during a pause would surprise them.\n * - **A fade** of `fadeMs` (10 s) before the pause; the volume is restored after the pause, after a\n * cancel and after an extend, so the next play is at the volume the person chose. iOS ignores\n * `volume` on a media element: there the fade has no audible effect and the pause still happens; a\n * host that routes the element through Web Audio passes `gain` to fade a `GainNode` instead.\n * - **A jump past an `at` point cancels the timer** (reason `passed`) instead of pausing at once\n * after a seek; a host that wants \"the end of the chapter I am in now\" sets it again.\n * - **Ticks from two clocks**: its own timer (smooth countdown) and the port's `timeupdate` when the\n * port has one, because a phone throttles timers on a hidden page while the audio keeps playing.\n */\n\n/** What the timer needs from a media element (an `HTMLMediaElement` is one). */\nexport interface SleepPort {\n readonly currentTime: number;\n readonly duration: number;\n readonly paused: boolean;\n readonly ended?: boolean;\n readonly playbackRate: number;\n volume: number;\n pause(): void;\n addEventListener?(type: 'timeupdate', listener: () => void): void;\n removeEventListener?(type: 'timeupdate', listener: () => void): void;\n}\n\nexport type SleepTarget =\n /** After this many minutes of listening. */\n | { kind: 'after'; minutes: number }\n /** When playback reaches this media time (seconds); `label` names it for the UI (\"end of chapter\"). */\n | { kind: 'at'; seconds: number; label?: string }\n /** When playback reaches the end of the item. */\n | { kind: 'end' };\n\nexport type SleepEndReason = 'slept' | 'cancelled' | 'passed';\n\nexport interface SleepState {\n /** The target while the timer runs, `null` when it is off. */\n target: SleepTarget | null;\n /** Listening time left, in ms (an `at`/`end` target: estimated from media time and speed); `null` when off. */\n remainingMs: number | null;\n /** The volume is being lowered: the pause is less than `fadeMs` away. */\n fading: boolean;\n /** Why the last timer ended, until a new one is set. */\n ended: SleepEndReason | null;\n}\n\nexport interface SleepTimerOptions {\n /** How long the fade before the pause lasts, in ms. Default 10 000; 0 for none. */\n fadeMs?: number;\n /** Countdown refresh while playing, in ms. Default 1000 (and every 100 ms while fading). */\n tickMs?: number;\n /** Set the fade level, 1 (full) to 0. Default: scale `port.volume`; pass a Web Audio gain setter on iOS. */\n gain?: (level: number) => void;\n /** Pause the media. Default `port.pause()`; a host passes its transport's pause or a command. */\n pause?: () => void;\n /** Clock and timers, for tests. */\n now?: () => number;\n setTimer?: (fn: () => void, ms: number) => unknown;\n clearTimer?: (handle: unknown) => void;\n}\n\nexport interface SleepTimer {\n get(): SleepState;\n subscribe(listener: (state: SleepState, previous: SleepState) => void): () => void;\n set(target: SleepTarget): void;\n /** Add minutes: to an `after` timer's time left, or turn an `at`/`end` target into `after`. */\n extend(minutes: number): void;\n cancel(): void;\n /** Re-read the port; called by its own timer and on `timeupdate`. */\n tick(): void;\n dispose(): void;\n}\n\nexport const DEFAULT_SLEEP_FADE_MS = 10_000;\nexport const DEFAULT_SLEEP_TICK_MS = 1000;\n/** Minutes offered by a sleep-timer picker; a host may offer others. */\nexport const SLEEP_MINUTES = [5, 10, 15, 20, 30, 45, 60, 90] as const;\n/** A playhead step bigger than this (in media seconds per tick, at speed 1) is a jump, not playback. */\nconst JUMP_S = 3;\nconst END_EPSILON_S = 0.25;\n\nconst OFF: SleepState = { target: null, remainingMs: null, fading: false, ended: null };\n\nexport function createSleepTimer(port: SleepPort, options: SleepTimerOptions = {}): SleepTimer {\n const {\n fadeMs = DEFAULT_SLEEP_FADE_MS,\n tickMs = DEFAULT_SLEEP_TICK_MS,\n gain,\n pause = () => port.pause(),\n now = () => Date.now(),\n setTimer = (fn, ms) => setTimeout(fn, ms),\n clearTimer = (h) => clearTimeout(h as ReturnType<typeof setTimeout>),\n } = options;\n\n let state: SleepState = OFF;\n const listeners = new Set<(s: SleepState, p: SleepState) => void>();\n const emit = (next: SleepState) => {\n const previous = state;\n state = next;\n listeners.forEach((l) => l(state, previous));\n };\n\n let leftMs = 0; // `after`: listening time left\n let lastAt = 0; // wall clock of the last tick\n let lastTime = 0; // media time of the last tick\n let volume: number | null = null; // the person's volume, held while fading\n let fadingNow = false;\n let handle: unknown = null;\n\n // The level of the fade, 1 to 0: a host's gain, or the element's volume scaled from where it was.\n const setLevel = (level: number) => {\n if (gain) { gain(level); fadingNow = level < 1; return; }\n if (level >= 1) {\n if (volume !== null) port.volume = volume;\n volume = null;\n return;\n }\n if (volume === null) volume = port.volume;\n port.volume = volume * level;\n };\n const restoreVolume = () => {\n if (gain) { if (fadingNow) gain(1); fadingNow = false; return; }\n setLevel(1);\n };\n const schedule = () => {\n if (handle !== null) clearTimer(handle);\n handle = state.target ? setTimer(tick, state.fading ? Math.min(100, tickMs) : tickMs) : null;\n };\n const stop = (reason: SleepEndReason) => {\n restoreVolume();\n if (handle !== null) clearTimer(handle);\n handle = null;\n emit({ ...OFF, ended: reason });\n };\n\n const mediaLeftMs = (seconds: number) =>\n (Math.max(0, seconds - port.currentTime) / (port.playbackRate || 1)) * 1000;\n\n function tick() {\n const target = state.target;\n if (!target) return;\n const t = now();\n const time = port.currentTime;\n const playing = !port.paused;\n let remaining: number;\n\n if (target.kind === 'after') {\n if (playing) leftMs -= Math.max(0, t - lastAt);\n remaining = leftMs;\n } else {\n const at = target.kind === 'at' ? target.seconds : port.duration;\n if (!Number.isFinite(at) || at <= 0) {\n remaining = Infinity; // `end` before the duration is known\n } else {\n const jumped = Math.abs(time - lastTime) > JUMP_S * Math.max(1, port.playbackRate) + (t - lastAt) / 1000;\n if (jumped && lastTime < at - END_EPSILON_S && time > at) {\n lastAt = t; lastTime = time;\n return stop('passed');\n }\n remaining = port.ended || time >= at - END_EPSILON_S ? 0 : mediaLeftMs(at);\n }\n }\n lastAt = t;\n lastTime = time;\n\n if (remaining <= 0) {\n if (playing) pause();\n return stop('slept');\n }\n const fading = playing && fadeMs > 0 && remaining <= fadeMs;\n if (fading) setLevel(remaining / fadeMs);\n else restoreVolume();\n emit({ target, remainingMs: Number.isFinite(remaining) ? Math.round(remaining) : null, fading, ended: null });\n schedule();\n }\n\n const onTimeupdate = () => tick();\n port.addEventListener?.('timeupdate', onTimeupdate);\n\n const timer: SleepTimer = {\n get: () => state,\n subscribe(listener) {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n set(target) {\n restoreVolume();\n if (target.kind === 'after') leftMs = Math.max(0, target.minutes) * 60_000;\n lastAt = now();\n lastTime = port.currentTime;\n state = { ...OFF, target };\n tick();\n },\n extend(minutes) {\n const target = state.target;\n if (!target) return timer.set({ kind: 'after', minutes });\n const base = target.kind === 'after' ? leftMs : (state.remainingMs ?? 0);\n timer.set({ kind: 'after', minutes: (base + minutes * 60_000) / 60_000 });\n },\n cancel() {\n if (state.target) stop('cancelled');\n },\n tick,\n dispose() {\n port.removeEventListener?.('timeupdate', onTimeupdate);\n if (state.target) restoreVolume();\n if (handle !== null) clearTimer(handle);\n handle = null;\n listeners.clear();\n },\n };\n return timer;\n}\n\n/** \"14:05\" for a countdown in ms (minutes may exceed 59: \"90:00\"). */\nexport function formatCountdown(ms: number): string {\n const s = Math.max(0, Math.ceil(ms / 1000));\n return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`;\n}\n"],"mappings":";;;;;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BAAgB,IAAoB;AAClD,QAAM,IAAI,KAAK,IAAI,GAAG,KAAK,KAAK,KAAK,GAAI,CAAC;AAC1C,SAAO,GAAG,KAAK,MAAM,IAAI,EAAE,CAAC,IAAI,OAAO,IAAI,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC;AACjE;","names":[]}
|
package/dist/sleep.d.cts
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A sleep timer: pause the media after some listening time, or at a point in it (the end of a
|
|
3
|
+
* chapter, the end of the item), fading the volume out first so the stop does not wake anyone.
|
|
4
|
+
* Headless: no DOM beyond an optional `timeupdate` listener on the port, no zustand, no React.
|
|
5
|
+
*
|
|
6
|
+
* ```ts
|
|
7
|
+
* const sleep = createSleepTimer(audio);
|
|
8
|
+
* sleep.set({ kind: 'after', minutes: 15 }); // 15 minutes of listening
|
|
9
|
+
* sleep.set({ kind: 'at', seconds: 1260 }); // at 21:00 in the item (a chapter's end)
|
|
10
|
+
* sleep.set({ kind: 'end' }); // at the end of the item
|
|
11
|
+
* sleep.extend(5); sleep.cancel();
|
|
12
|
+
* sleep.subscribe((s) => render(s.remainingMs, s.fading));
|
|
13
|
+
* ```
|
|
14
|
+
*
|
|
15
|
+
* Choices, each a default the host can change:
|
|
16
|
+
* - **Listening time, not clock time.** `after` counts down only while the media plays: a person
|
|
17
|
+
* who paused is not asleep, and a timer that ran out during a pause would surprise them.
|
|
18
|
+
* - **A fade** of `fadeMs` (10 s) before the pause; the volume is restored after the pause, after a
|
|
19
|
+
* cancel and after an extend, so the next play is at the volume the person chose. iOS ignores
|
|
20
|
+
* `volume` on a media element: there the fade has no audible effect and the pause still happens; a
|
|
21
|
+
* host that routes the element through Web Audio passes `gain` to fade a `GainNode` instead.
|
|
22
|
+
* - **A jump past an `at` point cancels the timer** (reason `passed`) instead of pausing at once
|
|
23
|
+
* after a seek; a host that wants "the end of the chapter I am in now" sets it again.
|
|
24
|
+
* - **Ticks from two clocks**: its own timer (smooth countdown) and the port's `timeupdate` when the
|
|
25
|
+
* port has one, because a phone throttles timers on a hidden page while the audio keeps playing.
|
|
26
|
+
*/
|
|
27
|
+
/** What the timer needs from a media element (an `HTMLMediaElement` is one). */
|
|
28
|
+
interface SleepPort {
|
|
29
|
+
readonly currentTime: number;
|
|
30
|
+
readonly duration: number;
|
|
31
|
+
readonly paused: boolean;
|
|
32
|
+
readonly ended?: boolean;
|
|
33
|
+
readonly playbackRate: number;
|
|
34
|
+
volume: number;
|
|
35
|
+
pause(): void;
|
|
36
|
+
addEventListener?(type: 'timeupdate', listener: () => void): void;
|
|
37
|
+
removeEventListener?(type: 'timeupdate', listener: () => void): void;
|
|
38
|
+
}
|
|
39
|
+
type SleepTarget =
|
|
40
|
+
/** After this many minutes of listening. */
|
|
41
|
+
{
|
|
42
|
+
kind: 'after';
|
|
43
|
+
minutes: number;
|
|
44
|
+
}
|
|
45
|
+
/** When playback reaches this media time (seconds); `label` names it for the UI ("end of chapter"). */
|
|
46
|
+
| {
|
|
47
|
+
kind: 'at';
|
|
48
|
+
seconds: number;
|
|
49
|
+
label?: string;
|
|
50
|
+
}
|
|
51
|
+
/** When playback reaches the end of the item. */
|
|
52
|
+
| {
|
|
53
|
+
kind: 'end';
|
|
54
|
+
};
|
|
55
|
+
type SleepEndReason = 'slept' | 'cancelled' | 'passed';
|
|
56
|
+
interface SleepState {
|
|
57
|
+
/** The target while the timer runs, `null` when it is off. */
|
|
58
|
+
target: SleepTarget | null;
|
|
59
|
+
/** Listening time left, in ms (an `at`/`end` target: estimated from media time and speed); `null` when off. */
|
|
60
|
+
remainingMs: number | null;
|
|
61
|
+
/** The volume is being lowered: the pause is less than `fadeMs` away. */
|
|
62
|
+
fading: boolean;
|
|
63
|
+
/** Why the last timer ended, until a new one is set. */
|
|
64
|
+
ended: SleepEndReason | null;
|
|
65
|
+
}
|
|
66
|
+
interface SleepTimerOptions {
|
|
67
|
+
/** How long the fade before the pause lasts, in ms. Default 10 000; 0 for none. */
|
|
68
|
+
fadeMs?: number;
|
|
69
|
+
/** Countdown refresh while playing, in ms. Default 1000 (and every 100 ms while fading). */
|
|
70
|
+
tickMs?: number;
|
|
71
|
+
/** Set the fade level, 1 (full) to 0. Default: scale `port.volume`; pass a Web Audio gain setter on iOS. */
|
|
72
|
+
gain?: (level: number) => void;
|
|
73
|
+
/** Pause the media. Default `port.pause()`; a host passes its transport's pause or a command. */
|
|
74
|
+
pause?: () => void;
|
|
75
|
+
/** Clock and timers, for tests. */
|
|
76
|
+
now?: () => number;
|
|
77
|
+
setTimer?: (fn: () => void, ms: number) => unknown;
|
|
78
|
+
clearTimer?: (handle: unknown) => void;
|
|
79
|
+
}
|
|
80
|
+
interface SleepTimer {
|
|
81
|
+
get(): SleepState;
|
|
82
|
+
subscribe(listener: (state: SleepState, previous: SleepState) => void): () => void;
|
|
83
|
+
set(target: SleepTarget): void;
|
|
84
|
+
/** Add minutes: to an `after` timer's time left, or turn an `at`/`end` target into `after`. */
|
|
85
|
+
extend(minutes: number): void;
|
|
86
|
+
cancel(): void;
|
|
87
|
+
/** Re-read the port; called by its own timer and on `timeupdate`. */
|
|
88
|
+
tick(): void;
|
|
89
|
+
dispose(): void;
|
|
90
|
+
}
|
|
91
|
+
declare const DEFAULT_SLEEP_FADE_MS = 10000;
|
|
92
|
+
declare const DEFAULT_SLEEP_TICK_MS = 1000;
|
|
93
|
+
/** Minutes offered by a sleep-timer picker; a host may offer others. */
|
|
94
|
+
declare const SLEEP_MINUTES: readonly [5, 10, 15, 20, 30, 45, 60, 90];
|
|
95
|
+
declare function createSleepTimer(port: SleepPort, options?: SleepTimerOptions): SleepTimer;
|
|
96
|
+
/** "14:05" for a countdown in ms (minutes may exceed 59: "90:00"). */
|
|
97
|
+
declare function formatCountdown(ms: number): string;
|
|
98
|
+
|
|
99
|
+
export { DEFAULT_SLEEP_FADE_MS, DEFAULT_SLEEP_TICK_MS, SLEEP_MINUTES, type SleepEndReason, type SleepPort, type SleepState, type SleepTarget, type SleepTimer, type SleepTimerOptions, createSleepTimer, formatCountdown };
|
package/dist/sleep.d.ts
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A sleep timer: pause the media after some listening time, or at a point in it (the end of a
|
|
3
|
+
* chapter, the end of the item), fading the volume out first so the stop does not wake anyone.
|
|
4
|
+
* Headless: no DOM beyond an optional `timeupdate` listener on the port, no zustand, no React.
|
|
5
|
+
*
|
|
6
|
+
* ```ts
|
|
7
|
+
* const sleep = createSleepTimer(audio);
|
|
8
|
+
* sleep.set({ kind: 'after', minutes: 15 }); // 15 minutes of listening
|
|
9
|
+
* sleep.set({ kind: 'at', seconds: 1260 }); // at 21:00 in the item (a chapter's end)
|
|
10
|
+
* sleep.set({ kind: 'end' }); // at the end of the item
|
|
11
|
+
* sleep.extend(5); sleep.cancel();
|
|
12
|
+
* sleep.subscribe((s) => render(s.remainingMs, s.fading));
|
|
13
|
+
* ```
|
|
14
|
+
*
|
|
15
|
+
* Choices, each a default the host can change:
|
|
16
|
+
* - **Listening time, not clock time.** `after` counts down only while the media plays: a person
|
|
17
|
+
* who paused is not asleep, and a timer that ran out during a pause would surprise them.
|
|
18
|
+
* - **A fade** of `fadeMs` (10 s) before the pause; the volume is restored after the pause, after a
|
|
19
|
+
* cancel and after an extend, so the next play is at the volume the person chose. iOS ignores
|
|
20
|
+
* `volume` on a media element: there the fade has no audible effect and the pause still happens; a
|
|
21
|
+
* host that routes the element through Web Audio passes `gain` to fade a `GainNode` instead.
|
|
22
|
+
* - **A jump past an `at` point cancels the timer** (reason `passed`) instead of pausing at once
|
|
23
|
+
* after a seek; a host that wants "the end of the chapter I am in now" sets it again.
|
|
24
|
+
* - **Ticks from two clocks**: its own timer (smooth countdown) and the port's `timeupdate` when the
|
|
25
|
+
* port has one, because a phone throttles timers on a hidden page while the audio keeps playing.
|
|
26
|
+
*/
|
|
27
|
+
/** What the timer needs from a media element (an `HTMLMediaElement` is one). */
|
|
28
|
+
interface SleepPort {
|
|
29
|
+
readonly currentTime: number;
|
|
30
|
+
readonly duration: number;
|
|
31
|
+
readonly paused: boolean;
|
|
32
|
+
readonly ended?: boolean;
|
|
33
|
+
readonly playbackRate: number;
|
|
34
|
+
volume: number;
|
|
35
|
+
pause(): void;
|
|
36
|
+
addEventListener?(type: 'timeupdate', listener: () => void): void;
|
|
37
|
+
removeEventListener?(type: 'timeupdate', listener: () => void): void;
|
|
38
|
+
}
|
|
39
|
+
type SleepTarget =
|
|
40
|
+
/** After this many minutes of listening. */
|
|
41
|
+
{
|
|
42
|
+
kind: 'after';
|
|
43
|
+
minutes: number;
|
|
44
|
+
}
|
|
45
|
+
/** When playback reaches this media time (seconds); `label` names it for the UI ("end of chapter"). */
|
|
46
|
+
| {
|
|
47
|
+
kind: 'at';
|
|
48
|
+
seconds: number;
|
|
49
|
+
label?: string;
|
|
50
|
+
}
|
|
51
|
+
/** When playback reaches the end of the item. */
|
|
52
|
+
| {
|
|
53
|
+
kind: 'end';
|
|
54
|
+
};
|
|
55
|
+
type SleepEndReason = 'slept' | 'cancelled' | 'passed';
|
|
56
|
+
interface SleepState {
|
|
57
|
+
/** The target while the timer runs, `null` when it is off. */
|
|
58
|
+
target: SleepTarget | null;
|
|
59
|
+
/** Listening time left, in ms (an `at`/`end` target: estimated from media time and speed); `null` when off. */
|
|
60
|
+
remainingMs: number | null;
|
|
61
|
+
/** The volume is being lowered: the pause is less than `fadeMs` away. */
|
|
62
|
+
fading: boolean;
|
|
63
|
+
/** Why the last timer ended, until a new one is set. */
|
|
64
|
+
ended: SleepEndReason | null;
|
|
65
|
+
}
|
|
66
|
+
interface SleepTimerOptions {
|
|
67
|
+
/** How long the fade before the pause lasts, in ms. Default 10 000; 0 for none. */
|
|
68
|
+
fadeMs?: number;
|
|
69
|
+
/** Countdown refresh while playing, in ms. Default 1000 (and every 100 ms while fading). */
|
|
70
|
+
tickMs?: number;
|
|
71
|
+
/** Set the fade level, 1 (full) to 0. Default: scale `port.volume`; pass a Web Audio gain setter on iOS. */
|
|
72
|
+
gain?: (level: number) => void;
|
|
73
|
+
/** Pause the media. Default `port.pause()`; a host passes its transport's pause or a command. */
|
|
74
|
+
pause?: () => void;
|
|
75
|
+
/** Clock and timers, for tests. */
|
|
76
|
+
now?: () => number;
|
|
77
|
+
setTimer?: (fn: () => void, ms: number) => unknown;
|
|
78
|
+
clearTimer?: (handle: unknown) => void;
|
|
79
|
+
}
|
|
80
|
+
interface SleepTimer {
|
|
81
|
+
get(): SleepState;
|
|
82
|
+
subscribe(listener: (state: SleepState, previous: SleepState) => void): () => void;
|
|
83
|
+
set(target: SleepTarget): void;
|
|
84
|
+
/** Add minutes: to an `after` timer's time left, or turn an `at`/`end` target into `after`. */
|
|
85
|
+
extend(minutes: number): void;
|
|
86
|
+
cancel(): void;
|
|
87
|
+
/** Re-read the port; called by its own timer and on `timeupdate`. */
|
|
88
|
+
tick(): void;
|
|
89
|
+
dispose(): void;
|
|
90
|
+
}
|
|
91
|
+
declare const DEFAULT_SLEEP_FADE_MS = 10000;
|
|
92
|
+
declare const DEFAULT_SLEEP_TICK_MS = 1000;
|
|
93
|
+
/** Minutes offered by a sleep-timer picker; a host may offer others. */
|
|
94
|
+
declare const SLEEP_MINUTES: readonly [5, 10, 15, 20, 30, 45, 60, 90];
|
|
95
|
+
declare function createSleepTimer(port: SleepPort, options?: SleepTimerOptions): SleepTimer;
|
|
96
|
+
/** "14:05" for a countdown in ms (minutes may exceed 59: "90:00"). */
|
|
97
|
+
declare function formatCountdown(ms: number): string;
|
|
98
|
+
|
|
99
|
+
export { DEFAULT_SLEEP_FADE_MS, DEFAULT_SLEEP_TICK_MS, SLEEP_MINUTES, type SleepEndReason, type SleepPort, type SleepState, type SleepTarget, type SleepTimer, type SleepTimerOptions, createSleepTimer, formatCountdown };
|