@openartifactsai/editor-kit 0.0.0-stage → 0.23.0-rc.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.
Files changed (120) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +5 -0
  3. package/README.md +143 -2
  4. package/package.json +67 -4
  5. package/src/Announcer.d.ts +2 -0
  6. package/src/Announcer.js +8 -0
  7. package/src/FindBar.d.ts +31 -0
  8. package/src/FindBar.js +37 -0
  9. package/src/FoldToolbar.d.ts +58 -0
  10. package/src/FoldToolbar.js +438 -0
  11. package/src/PanelEdge.d.ts +20 -0
  12. package/src/PanelEdge.js +74 -0
  13. package/src/VideoShrinkNotice.d.ts +10 -0
  14. package/src/VideoShrinkNotice.js +81 -0
  15. package/src/WheelZoomItem.d.ts +12 -0
  16. package/src/WheelZoomItem.js +18 -0
  17. package/src/agent.d.ts +68 -0
  18. package/src/agent.js +113 -0
  19. package/src/announce.d.ts +21 -0
  20. package/src/announce.js +31 -0
  21. package/src/chrome.d.ts +208 -0
  22. package/src/chrome.js +148 -0
  23. package/src/clipboard.d.ts +19 -0
  24. package/src/clipboard.js +48 -0
  25. package/src/collab/CommentList.d.ts +32 -0
  26. package/src/collab/CommentList.js +165 -0
  27. package/src/collab/CommentViews.d.ts +131 -0
  28. package/src/collab/CommentViews.js +619 -0
  29. package/src/collab/HistoryViews.d.ts +38 -0
  30. package/src/collab/HistoryViews.js +103 -0
  31. package/src/collab/PresenceViews.d.ts +53 -0
  32. package/src/collab/PresenceViews.js +48 -0
  33. package/src/collab/cds/cds.d.ts +151 -0
  34. package/src/collab/cds/cds.js +231 -0
  35. package/src/collab/cds/comment-card.d.ts +113 -0
  36. package/src/collab/cds/comment-card.js +230 -0
  37. package/src/collab/cds/comment-composer.d.ts +35 -0
  38. package/src/collab/cds/comment-composer.js +125 -0
  39. package/src/collab/cds/comments-css.d.ts +2 -0
  40. package/src/collab/cds/comments-css.js +3 -0
  41. package/src/collab/cds/comments.css +504 -0
  42. package/src/collab/cds/edge-piles.d.ts +69 -0
  43. package/src/collab/cds/edge-piles.js +178 -0
  44. package/src/collab/cds/layer.d.ts +41 -0
  45. package/src/collab/cds/layer.js +144 -0
  46. package/src/collab/cds/markdown.d.ts +20 -0
  47. package/src/collab/cds/markdown.js +534 -0
  48. package/src/collab/cds/shield.d.ts +28 -0
  49. package/src/collab/cds/shield.js +114 -0
  50. package/src/collab/cds/time.d.ts +2 -0
  51. package/src/collab/cds/time.js +41 -0
  52. package/src/collab/collab.d.ts +102 -0
  53. package/src/collab/collab.js +121 -0
  54. package/src/collab/comments.d.ts +272 -0
  55. package/src/collab/comments.js +596 -0
  56. package/src/collab/history-wiring.d.ts +32 -0
  57. package/src/collab/history-wiring.js +53 -0
  58. package/src/collab/history.d.ts +59 -0
  59. package/src/collab/history.js +96 -0
  60. package/src/collab/mentions/mention-list.d.ts +63 -0
  61. package/src/collab/mentions/mention-list.js +257 -0
  62. package/src/collab/mentions.d.ts +112 -0
  63. package/src/collab/mentions.js +164 -0
  64. package/src/collab/peer-colors.d.ts +123 -0
  65. package/src/collab/peer-colors.js +273 -0
  66. package/src/collab/pins.d.ts +70 -0
  67. package/src/collab/pins.js +44 -0
  68. package/src/collab/presence.d.ts +92 -0
  69. package/src/collab/presence.js +158 -0
  70. package/src/design-systems.d.ts +46 -0
  71. package/src/design-systems.js +61 -0
  72. package/src/downloads.d.ts +31 -0
  73. package/src/downloads.js +46 -0
  74. package/src/file-drop.d.ts +33 -0
  75. package/src/file-drop.js +36 -0
  76. package/src/find.d.ts +64 -0
  77. package/src/find.js +147 -0
  78. package/src/follow.d.ts +141 -0
  79. package/src/follow.js +389 -0
  80. package/src/index.d.ts +32 -0
  81. package/src/index.js +32 -0
  82. package/src/keys.d.ts +18 -0
  83. package/src/keys.js +42 -0
  84. package/src/menu-fit.d.ts +12 -0
  85. package/src/menu-fit.js +9 -0
  86. package/src/merge.d.ts +23 -0
  87. package/src/merge.js +116 -0
  88. package/src/page-link.d.ts +33 -0
  89. package/src/page-link.js +75 -0
  90. package/src/project-sync.d.ts +161 -0
  91. package/src/project-sync.js +319 -0
  92. package/src/react.d.ts +20 -0
  93. package/src/react.js +20 -0
  94. package/src/read-retries.d.ts +55 -0
  95. package/src/read-retries.js +125 -0
  96. package/src/right-drag-pan.d.ts +128 -0
  97. package/src/right-drag-pan.js +253 -0
  98. package/src/roles.d.ts +39 -0
  99. package/src/roles.js +27 -0
  100. package/src/session.d.ts +56 -0
  101. package/src/session.js +57 -0
  102. package/src/shell.d.ts +60 -0
  103. package/src/shell.js +111 -0
  104. package/src/stash.d.ts +26 -0
  105. package/src/stash.js +69 -0
  106. package/src/styles.css +17 -0
  107. package/src/toolbar-fold.d.ts +106 -0
  108. package/src/toolbar-fold.js +130 -0
  109. package/src/video-shrink/index.d.ts +8 -0
  110. package/src/video-shrink/index.js +7 -0
  111. package/src/video-shrink/plan.d.ts +92 -0
  112. package/src/video-shrink/plan.js +133 -0
  113. package/src/video-shrink/protocol.d.ts +29 -0
  114. package/src/video-shrink/protocol.js +2 -0
  115. package/src/video-shrink/queue.d.ts +69 -0
  116. package/src/video-shrink/queue.js +287 -0
  117. package/src/video-shrink/worker.d.ts +8 -0
  118. package/src/video-shrink/worker.js +223 -0
  119. package/src/wheel-zoom.d.ts +14 -0
  120. package/src/wheel-zoom.js +48 -0
package/src/stash.js ADDED
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Unsaved-work recovery, the shared part: while edits wait to be saved, an
3
+ * editor copies what differs from the saved files to `localStorage` (a
4
+ * "stash"); if the tab closes before the save lands, the next visit offers
5
+ * it back. What a stash holds and how it is restored is the editor's; this
6
+ * module keeps the storage guarded, the age limit and the debounce.
7
+ */
8
+ import { adoptLegacyBrowserStorage } from '@openartifactsai/runtime';
9
+ /** How long a stash is kept, ms (three days). */
10
+ export const STASH_KEEP_MS = 3 * 24 * 60 * 60 * 1000;
11
+ /** True while a stash written at `at` may still be offered (not too old, not from the future). */
12
+ export function stashFresh(at, now) {
13
+ return now - at <= STASH_KEEP_MS && at <= now + 60_000;
14
+ }
15
+ /**
16
+ * A JSON value stored under `key` (e.g. `open-artifacts-design:recovery:<path>`).
17
+ * `parse` validates what is read back (`null`: unusable). Storage that is
18
+ * missing, full or blocked reads as empty and ignores writes.
19
+ */
20
+ export function storedJson(key, parse, storage = () => globalThis.localStorage) {
21
+ const clear = () => {
22
+ try {
23
+ storage()?.removeItem(key);
24
+ }
25
+ catch {
26
+ // Unavailable: nothing to clear.
27
+ }
28
+ };
29
+ return {
30
+ read() {
31
+ try {
32
+ // A stash an older version left under its key (`open-artifact-design:recovery:…`) moves to this one first.
33
+ adoptLegacyBrowserStorage();
34
+ const raw = storage()?.getItem(key);
35
+ return raw ? parse(JSON.parse(raw)) : null;
36
+ }
37
+ catch {
38
+ return null;
39
+ }
40
+ },
41
+ write(value) {
42
+ if (value === null)
43
+ return clear();
44
+ try {
45
+ storage()?.setItem(key, JSON.stringify(value));
46
+ }
47
+ catch {
48
+ // Full or unavailable: recovery is best effort.
49
+ }
50
+ },
51
+ clear,
52
+ };
53
+ }
54
+ /** JSON compared by value (key order and spacing aside), text otherwise. */
55
+ export function normalizeJson(text) {
56
+ try {
57
+ return JSON.stringify(sortKeys(JSON.parse(text)));
58
+ }
59
+ catch {
60
+ return text;
61
+ }
62
+ }
63
+ function sortKeys(value) {
64
+ if (Array.isArray(value))
65
+ return value.map(sortKeys);
66
+ if (value && typeof value === 'object')
67
+ return Object.fromEntries(Object.keys(value).sort().map((k) => [k, sortKeys(value[k])]));
68
+ return value;
69
+ }
package/src/styles.css ADDED
@@ -0,0 +1,17 @@
1
+ /* The comments layer's font: Inter (SIL Open Font License 1.1). Declared on the page, since a shadow root ignores @font-face. */
2
+ @import "@fontsource-variable/inter/wght.css";
3
+
4
+ /*
5
+ * Editors import this after the UI kit's sheet, so Tailwind scans the
6
+ * kit's components for class names:
7
+ *
8
+ * @import "@openartifactsai/ui/styles.css";
9
+ * @import "@openartifactsai/editor-kit/styles.css";
10
+ *
11
+ * The chrome components use the editor's chrome tokens (`bg-chrome`,
12
+ * `text-chrome-fg`, `shadow-chrome`, `outline-chrome-focus`…), which each
13
+ * editor defines in its own `@theme`.
14
+ */
15
+ @source "./";
16
+ /* The comment components draw in a shadow root with their own stylesheet (collab/cds/comments.css). */
17
+ @source not "./collab/cds";
@@ -0,0 +1,106 @@
1
+ /**
2
+ * The rules of a folding toolbar, free of the page so they can be tested:
3
+ * which controls go into the "More tools" card and in what order, which
4
+ * dividers stay, where the card opens, and how keys and focus move.
5
+ * `FoldToolbar.tsx` measures the page and applies them.
6
+ */
7
+ /** Presses inside an element matching this belong to a folding strip's Escape (its card is open, or the key that closed it is still down). */
8
+ export declare const FOLD_OWNS_ESCAPE = "[data-fold-escape]";
9
+ /** How a control takes part in folding. */
10
+ export type FoldRole =
11
+ /** The properties / more button: the first to go, always the card's last item. */
12
+ 'more'
13
+ /** Stays on the strip: the tail group, and controls marked to keep (a link editor opens from the strip only). */
14
+ | 'pinned'
15
+ /** Folds when the strip is too wide, from the end. */
16
+ | 'loose';
17
+ /**
18
+ * Folds `items` (in strip order) until `tooWide()` turns false: the more
19
+ * button first, to the card's end; then loose items from the strip's end,
20
+ * each to the card's front, so the card reads in the strip's order.
21
+ * `move` does the moving (and whatever the strip's width depends on).
22
+ * Returns the card's items, in order.
23
+ */
24
+ export declare function foldItems<T>(items: readonly T[], roleOf: (item: T) => FoldRole, tooWide: () => boolean, move: (item: T, to: 'front' | 'end') => void): T[];
25
+ /** A run of a toolbar row: a divider, or a group that holds controls or holds none. */
26
+ export type FoldRun = 'divider' | 'group' | 'empty';
27
+ /**
28
+ * Which runs of a row show: groups with controls, and between two of them
29
+ * one divider. Empty groups go, and so does a divider at either end or
30
+ * next to another divider.
31
+ */
32
+ export declare function shownRuns(runs: readonly FoldRun[]): boolean[];
33
+ /** Where the card opens: on the strip's side unless that side lacks room and the other has more; `shift` moves it right (px) so it stays in view. */
34
+ export interface CardPlace {
35
+ side: 'above' | 'below';
36
+ shift: number;
37
+ }
38
+ /** Gap between the strip and its card, and the margin the card keeps from the viewport's edges (px). */
39
+ export declare const CARD_GAP = 8;
40
+ export declare const CARD_MARGIN = 8;
41
+ /**
42
+ * Places the card for a strip at `strip` (viewport px) that opened toward
43
+ * `side`, inside `band` (the room the card may use, top and bottom).
44
+ */
45
+ export declare function placeCard(strip: {
46
+ top: number;
47
+ bottom: number;
48
+ right: number;
49
+ }, card: {
50
+ width: number;
51
+ height: number;
52
+ }, side: 'above' | 'below', band: {
53
+ top: number;
54
+ bottom: number;
55
+ }): CardPlace;
56
+ /** A key press, as far as the strip's arrow keys care. */
57
+ export interface StripKey {
58
+ key: string;
59
+ altKey: boolean;
60
+ ctrlKey: boolean;
61
+ metaKey: boolean;
62
+ }
63
+ /**
64
+ * The control an arrow key, Home or End moves focus to, among `count`
65
+ * controls with focus at `at` (-1: none of them). The arrows wrap at the
66
+ * ends; `null` for any other key or with a modifier.
67
+ */
68
+ export declare function arrowStep(press: StripKey, at: number, count: number): number | null;
69
+ /** How far to scroll a box so an item in it is in view with `margin` to spare (negative: to the start; 0: already in view). */
70
+ export declare function scrollToShow(item: {
71
+ left: number;
72
+ right: number;
73
+ }, box: {
74
+ left: number;
75
+ right: number;
76
+ }, margin: number): number;
77
+ /** What focus leaving the strip (or its card) does to an open card. */
78
+ export type FocusExit = 'close' | 'close-unless-back' | 'stay';
79
+ /**
80
+ * Focus left a control of the strip: Tab closes the card (Tab that leaves
81
+ * the focus nowhere checks again a tick later); F6 or Escape that moved the
82
+ * focus out of the strip closes it too, unless a popup of the strip is open
83
+ * or the focus went to a toast. A pointer press elsewhere leaves it open.
84
+ */
85
+ export declare function focusExit(exit: {
86
+ into: 'strip' | 'outside' | 'nowhere';
87
+ tabbing: boolean;
88
+ byFocusKey: boolean;
89
+ popupOpen: boolean;
90
+ toToast: boolean;
91
+ }): FocusExit;
92
+ /**
93
+ * Whether the strip takes an Escape for its card: the card is open (or the
94
+ * key that closed it is still down), the press is in the strip or the card,
95
+ * no popup of the strip is open, and it is not typed into a text field (a
96
+ * slider is not one).
97
+ */
98
+ export declare function takesEscape(press: {
99
+ key: string;
100
+ defaultPrevented: boolean;
101
+ ownedHere: boolean;
102
+ popupOpen: boolean;
103
+ inTextField: boolean;
104
+ }): boolean;
105
+ /** The control a card opened from the keyboard focuses: its first button, else its first field. */
106
+ export declare function firstInCard<T>(buttons: readonly T[], fields: readonly T[]): T | null;
@@ -0,0 +1,130 @@
1
+ /**
2
+ * The rules of a folding toolbar, free of the page so they can be tested:
3
+ * which controls go into the "More tools" card and in what order, which
4
+ * dividers stay, where the card opens, and how keys and focus move.
5
+ * `FoldToolbar.tsx` measures the page and applies them.
6
+ */
7
+ /** Presses inside an element matching this belong to a folding strip's Escape (its card is open, or the key that closed it is still down). */
8
+ export const FOLD_OWNS_ESCAPE = '[data-fold-escape]';
9
+ /**
10
+ * Folds `items` (in strip order) until `tooWide()` turns false: the more
11
+ * button first, to the card's end; then loose items from the strip's end,
12
+ * each to the card's front, so the card reads in the strip's order.
13
+ * `move` does the moving (and whatever the strip's width depends on).
14
+ * Returns the card's items, in order.
15
+ */
16
+ export function foldItems(items, roleOf, tooWide, move) {
17
+ const card = [];
18
+ const more = items.find((item) => roleOf(item) === 'more');
19
+ if (more !== undefined) {
20
+ move(more, 'end');
21
+ card.push(more);
22
+ }
23
+ const loose = items.filter((item) => roleOf(item) === 'loose');
24
+ while (loose.length > 0 && tooWide()) {
25
+ const item = loose.pop();
26
+ move(item, 'front');
27
+ card.unshift(item);
28
+ }
29
+ return card;
30
+ }
31
+ /**
32
+ * Which runs of a row show: groups with controls, and between two of them
33
+ * one divider. Empty groups go, and so does a divider at either end or
34
+ * next to another divider.
35
+ */
36
+ export function shownRuns(runs) {
37
+ const shown = runs.map(() => false);
38
+ let seenGroup = false;
39
+ let divider = null;
40
+ runs.forEach((run, index) => {
41
+ if (run === 'empty')
42
+ return;
43
+ if (run === 'divider') {
44
+ if (seenGroup && divider === null)
45
+ divider = index;
46
+ return;
47
+ }
48
+ if (divider !== null)
49
+ shown[divider] = true;
50
+ divider = null;
51
+ shown[index] = true;
52
+ seenGroup = true;
53
+ });
54
+ return shown;
55
+ }
56
+ /** Gap between the strip and its card, and the margin the card keeps from the viewport's edges (px). */
57
+ export const CARD_GAP = 8;
58
+ export const CARD_MARGIN = 8;
59
+ /**
60
+ * Places the card for a strip at `strip` (viewport px) that opened toward
61
+ * `side`, inside `band` (the room the card may use, top and bottom).
62
+ */
63
+ export function placeCard(strip, card, side, band) {
64
+ const room = { above: strip.top - band.top, below: band.bottom - strip.bottom };
65
+ const other = side === 'above' ? 'below' : 'above';
66
+ const needed = card.height + CARD_GAP + CARD_MARGIN;
67
+ const fits = room[side] >= needed || room[side] >= room[other];
68
+ // The card lines up with the strip's right edge; past the viewport's left edge it moves right.
69
+ const spill = card.width - (strip.right - CARD_MARGIN);
70
+ return { side: fits ? side : other, shift: spill > 0 ? spill : 0 };
71
+ }
72
+ /**
73
+ * The control an arrow key, Home or End moves focus to, among `count`
74
+ * controls with focus at `at` (-1: none of them). The arrows wrap at the
75
+ * ends; `null` for any other key or with a modifier.
76
+ */
77
+ export function arrowStep(press, at, count) {
78
+ if (count === 0 || press.altKey || press.ctrlKey || press.metaKey)
79
+ return null;
80
+ switch (press.key) {
81
+ case 'Home':
82
+ return 0;
83
+ case 'End':
84
+ return count - 1;
85
+ case 'ArrowLeft':
86
+ case 'ArrowUp':
87
+ return at < 0 ? 0 : (at - 1 + count) % count;
88
+ case 'ArrowRight':
89
+ case 'ArrowDown':
90
+ return at < 0 ? 0 : (at + 1) % count;
91
+ default:
92
+ return null;
93
+ }
94
+ }
95
+ /** How far to scroll a box so an item in it is in view with `margin` to spare (negative: to the start; 0: already in view). */
96
+ export function scrollToShow(item, box, margin) {
97
+ if (item.left < box.left + margin)
98
+ return item.left - (box.left + margin);
99
+ if (item.right > box.right - margin)
100
+ return item.right - (box.right - margin);
101
+ return 0;
102
+ }
103
+ /**
104
+ * Focus left a control of the strip: Tab closes the card (Tab that leaves
105
+ * the focus nowhere checks again a tick later); F6 or Escape that moved the
106
+ * focus out of the strip closes it too, unless a popup of the strip is open
107
+ * or the focus went to a toast. A pointer press elsewhere leaves it open.
108
+ */
109
+ export function focusExit(exit) {
110
+ if (exit.into === 'strip')
111
+ return 'stay';
112
+ if (exit.tabbing)
113
+ return exit.into === 'nowhere' ? 'close-unless-back' : 'close';
114
+ if (exit.byFocusKey && exit.into === 'outside' && !exit.popupOpen && !exit.toToast)
115
+ return 'close';
116
+ return 'stay';
117
+ }
118
+ /**
119
+ * Whether the strip takes an Escape for its card: the card is open (or the
120
+ * key that closed it is still down), the press is in the strip or the card,
121
+ * no popup of the strip is open, and it is not typed into a text field (a
122
+ * slider is not one).
123
+ */
124
+ export function takesEscape(press) {
125
+ return press.key === 'Escape' && !press.defaultPrevented && press.ownedHere && !press.popupOpen && !press.inTextField;
126
+ }
127
+ /** The control a card opened from the keyboard focuses: its first button, else its first field. */
128
+ export function firstInCard(buttons, fields) {
129
+ return buttons[0] ?? fields[0] ?? null;
130
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Making videos over the upload limit small enough to store, in a worker:
3
+ * the plan for each try, the queue and its store. The notice that shows the
4
+ * queue is `VideoShrinkNotice` in the React entry.
5
+ */
6
+ export * from './plan.js';
7
+ export * from './queue.js';
8
+ export type { ShrinkAnswer, ShrinkJob, ShrinkSound } from './protocol.js';
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Making videos over the upload limit small enough to store, in a worker:
3
+ * the plan for each try, the queue and its store. The notice that shows the
4
+ * queue is `VideoShrinkNotice` in the React entry.
5
+ */
6
+ export * from "./plan.js";
7
+ export * from "./queue.js";
@@ -0,0 +1,92 @@
1
+ /**
2
+ * Making a video that is over the upload limit small enough to store: what
3
+ * the browser found out about it, the size and bitrate the first try aims
4
+ * at, and how each later try aims smaller when the result is still too big.
5
+ */
6
+ /** Largest video that can be stored where the host gives no limit of its own (20 MB); larger ones are shrunk first. */
7
+ export declare const MAX_VIDEO_BYTES: number;
8
+ /** Sets the largest video the host stores (its `assets.maxBytes`); left out, {@link MAX_VIDEO_BYTES}. */
9
+ export declare function setVideoLimit(bytes: number | undefined): void;
10
+ /** The largest video the host stores, bytes: larger ones are shrunk first. */
11
+ export declare const videoLimit: () => number;
12
+ export type ShrinkCodec = 'avc' | 'vp9';
13
+ /** What reading a video in the worker found. */
14
+ export interface ShrinkProbe {
15
+ width: number;
16
+ height: number;
17
+ /** Seconds. */
18
+ duration: number;
19
+ /** Frames a second; 0 when unknown. */
20
+ fps: number;
21
+ decodable: boolean;
22
+ /** What this browser can write the picture as; null when nothing. */
23
+ codec: ShrinkCodec | null;
24
+ /** The largest short side the encoder took, when it refused the source's own. */
25
+ largestShort?: number;
26
+ /** The sound can be written along with the picture. */
27
+ sound: boolean;
28
+ }
29
+ /** One size the picture is brought down to, with the bitrates it may have. */
30
+ export interface ShrinkStep {
31
+ short: number;
32
+ minBitrate: number;
33
+ maxBitrate: number;
34
+ }
35
+ export interface ShrinkPlan {
36
+ width: number;
37
+ height: number;
38
+ /** Picture bits a second. */
39
+ bitrate: number;
40
+ codec: ShrinkCodec;
41
+ /** Set when the source is faster than {@link SHRINK_FPS}. */
42
+ fps?: number;
43
+ /** Index into {@link SHRINK_STEPS}. */
44
+ step: number;
45
+ withSound: boolean;
46
+ }
47
+ /** Why there is no plan at all. */
48
+ export type ShrinkRefusal = 'unreadable' | 'no-encoder' | 'too-long';
49
+ /**
50
+ * How a shrink ended badly (or, for `sound-dropped`, ended without its sound).
51
+ * `too-large`: the video could not be read or written here at all, so it is refused as over the limit.
52
+ */
53
+ export type ShrinkFailure = 'too-large' | 'too-long' | 'too-big' | 'failed' | 'sound-dropped';
54
+ /** The size a shrunk video aims at under a limit of `limit` bytes, with room to spare. */
55
+ export declare const shrinkTarget: (limit: number) => number;
56
+ /** The size the result aims at under {@link MAX_VIDEO_BYTES}. */
57
+ export declare const SHRINK_TARGET_BYTES: number;
58
+ export declare const SHRINK_ATTEMPTS = 3;
59
+ export declare const SHRINK_SOUND_BITRATE = 132000;
60
+ export declare const SHRINK_FPS = 30;
61
+ export declare const SHRINK_STEPS: readonly ShrinkStep[];
62
+ /** The plan for `step` at `bitrate`: the picture scaled so its short side is the step's (never up). */
63
+ export declare function planAtStep(probe: ShrinkProbe, step: number, bitrate: number, withSound: boolean): ShrinkPlan;
64
+ /**
65
+ * The first try: the largest step no bigger than the source (and than the
66
+ * encoder takes) whose lowest bitrate the byte budget pays for.
67
+ */
68
+ export declare function firstShrinkPlan(probe: ShrinkProbe, target?: number): ShrinkPlan | ShrinkRefusal;
69
+ /**
70
+ * The next try after `plan` came out at `bytes`: the bitrate scaled down by
71
+ * how far over it was, else a smaller step, else the same without sound;
72
+ * null when nothing smaller is left.
73
+ */
74
+ export declare function smallerShrinkPlan(probe: ShrinkProbe, plan: ShrinkPlan, bytes: number, target?: number): ShrinkPlan | null;
75
+ /** `avc1.64xxLL` / `avc1.4dxxLL` (High, Main) as `avc1.4200LL` (Baseline at the same level); others as they are. */
76
+ export declare function baselineCodec(codec: string): string;
77
+ /** The longest video that fits under `limit` at the smallest step's lowest bitrate, in words. */
78
+ export declare function longestFittingLength(limit: number): string;
79
+ export declare function shrinkFailureMessage(failure: ShrinkFailure): string;
80
+ /** What the shrink progress notice says. */
81
+ export declare const SHRINK_WORDS: {
82
+ readonly shrinking: "Shrinking video…";
83
+ readonly retrying: "Still too big, trying a smaller size…";
84
+ readonly placing: "Adding the video…";
85
+ readonly waiting: "Video ready. It’ll be added when you click out of the text box.";
86
+ readonly progressLabel: "Shrinking video";
87
+ readonly limit: () => string;
88
+ readonly keepOpen: "Keep this tab open until it’s done.";
89
+ readonly queued: (count: number) => string;
90
+ readonly cancel: "Cancel";
91
+ readonly encoderMissing: "The video encoder could not be loaded.";
92
+ };
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Making a video that is over the upload limit small enough to store: what
3
+ * the browser found out about it, the size and bitrate the first try aims
4
+ * at, and how each later try aims smaller when the result is still too big.
5
+ */
6
+ /** Largest video that can be stored where the host gives no limit of its own (20 MB); larger ones are shrunk first. */
7
+ export const MAX_VIDEO_BYTES = 20 * 1024 * 1024;
8
+ let limitBytes = MAX_VIDEO_BYTES;
9
+ /** Sets the largest video the host stores (its `assets.maxBytes`); left out, {@link MAX_VIDEO_BYTES}. */
10
+ export function setVideoLimit(bytes) {
11
+ limitBytes = bytes !== undefined && Number.isSafeInteger(bytes) && bytes > 0 ? bytes : MAX_VIDEO_BYTES;
12
+ }
13
+ /** The largest video the host stores, bytes: larger ones are shrunk first. */
14
+ export const videoLimit = () => limitBytes;
15
+ /** The size a shrunk video aims at under a limit of `limit` bytes, with room to spare. */
16
+ export const shrinkTarget = (limit) => Math.floor(limit * 0.92);
17
+ /** The size the result aims at under {@link MAX_VIDEO_BYTES}. */
18
+ export const SHRINK_TARGET_BYTES = shrinkTarget(MAX_VIDEO_BYTES);
19
+ export const SHRINK_ATTEMPTS = 3;
20
+ export const SHRINK_SOUND_BITRATE = 132_000;
21
+ export const SHRINK_FPS = 30;
22
+ export const SHRINK_STEPS = [
23
+ { short: 1080, minBitrate: 4_000_000, maxBitrate: 6_000_000 },
24
+ { short: 720, minBitrate: 2_000_000, maxBitrate: 4_000_000 },
25
+ { short: 480, minBitrate: 1_000_000, maxBitrate: 2_000_000 },
26
+ ];
27
+ const toEven = (value) => Math.max(2, Math.round(value / 2) * 2);
28
+ /** The plan for `step` at `bitrate`: the picture scaled so its short side is the step's (never up). */
29
+ export function planAtStep(probe, step, bitrate, withSound) {
30
+ const short = Math.min(probe.width, probe.height);
31
+ const scale = Math.min(1, (SHRINK_STEPS[step]?.short ?? short) / short);
32
+ return {
33
+ width: toEven(probe.width * scale),
34
+ height: toEven(probe.height * scale),
35
+ bitrate: Math.floor(bitrate),
36
+ codec: probe.codec ?? 'avc',
37
+ ...(probe.fps > SHRINK_FPS + 0.5 ? { fps: SHRINK_FPS } : {}),
38
+ step,
39
+ withSound,
40
+ };
41
+ }
42
+ /**
43
+ * The first try: the largest step no bigger than the source (and than the
44
+ * encoder takes) whose lowest bitrate the byte budget pays for.
45
+ */
46
+ export function firstShrinkPlan(probe, target = SHRINK_TARGET_BYTES) {
47
+ if (!probe.decodable || !(probe.width > 0 && probe.height > 0 && probe.duration > 0))
48
+ return 'unreadable';
49
+ if (probe.codec === null)
50
+ return 'no-encoder';
51
+ const budget = (target * 8) / probe.duration;
52
+ const short = Math.min(probe.width, probe.height);
53
+ let from = 0;
54
+ SHRINK_STEPS.forEach((step, index) => {
55
+ if (step.short >= short)
56
+ from = index;
57
+ });
58
+ if (probe.largestShort !== undefined) {
59
+ const largest = probe.largestShort;
60
+ from = Math.max(from, SHRINK_STEPS.findIndex((step) => step.short <= largest));
61
+ }
62
+ const step = SHRINK_STEPS.findIndex((candidate, index) => index >= from && budget >= candidate.minBitrate);
63
+ if (step < 0)
64
+ return 'too-long';
65
+ const picture = probe.sound ? budget - SHRINK_SOUND_BITRATE : budget;
66
+ return planAtStep(probe, step, Math.min(picture, SHRINK_STEPS[step].maxBitrate), probe.sound);
67
+ }
68
+ /**
69
+ * The next try after `plan` came out at `bytes`: the bitrate scaled down by
70
+ * how far over it was, else a smaller step, else the same without sound;
71
+ * null when nothing smaller is left.
72
+ */
73
+ export function smallerShrinkPlan(probe, plan, bytes, target = SHRINK_TARGET_BYTES) {
74
+ const scaled = plan.bitrate * (target / bytes) * 0.95;
75
+ const floor = (SHRINK_STEPS[plan.step]?.minBitrate ?? Infinity) - (plan.withSound ? SHRINK_SOUND_BITRATE : 0);
76
+ if (scaled >= floor)
77
+ return { ...plan, bitrate: Math.floor(scaled) };
78
+ for (let step = plan.step + 1; step < SHRINK_STEPS.length; step++) {
79
+ const { minBitrate, maxBitrate } = SHRINK_STEPS[step];
80
+ const next = planAtStep(probe, step, Math.min(Math.max(scaled, minBitrate), maxBitrate), plan.withSound);
81
+ if (next.height < plan.height)
82
+ return next.fps === undefined && plan.fps !== undefined ? { ...next, fps: plan.fps } : next;
83
+ }
84
+ if (!plan.withSound)
85
+ return null;
86
+ return { ...plan, withSound: false, bitrate: Math.min(plan.bitrate, SHRINK_STEPS[plan.step]?.minBitrate ?? plan.bitrate) };
87
+ }
88
+ /** `avc1.64xxLL` / `avc1.4dxxLL` (High, Main) as `avc1.4200LL` (Baseline at the same level); others as they are. */
89
+ export function baselineCodec(codec) {
90
+ const match = /^avc1\.(64|4d)[0-9a-f]{2}([0-9a-f]{2})$/i.exec(codec);
91
+ return match ? `avc1.4200${match[2]}` : codec;
92
+ }
93
+ const limitMb = () => Math.round(limitBytes / (1024 * 1024));
94
+ /** The longest video that fits under `limit` at the smallest step's lowest bitrate, in words. */
95
+ export function longestFittingLength(limit) {
96
+ const seconds = (shrinkTarget(limit) * 8) / SHRINK_STEPS[SHRINK_STEPS.length - 1].minBitrate;
97
+ const halves = Math.floor(seconds / 30);
98
+ if (halves < 2)
99
+ return 'under a minute';
100
+ if (halves < 3)
101
+ return 'a minute';
102
+ if (halves < 20)
103
+ return halves === 5 ? 'two and a half minutes' : `${halves / 2} minutes`;
104
+ return `${Math.floor(seconds / 60)} minutes`;
105
+ }
106
+ export function shrinkFailureMessage(failure) {
107
+ const cap = limitMb();
108
+ switch (failure) {
109
+ case 'too-large':
110
+ return `Videos over ${cap} MB can’t be added. Trim or compress it first.`;
111
+ case 'too-long':
112
+ return `This video is too long to fit in ${cap} MB. Trim it to about ${longestFittingLength(limitBytes)} or less.`;
113
+ case 'too-big':
114
+ return `Couldn’t get this video under ${cap} MB. Trim it first.`;
115
+ case 'sound-dropped':
116
+ return `This video was shrunk to fit, but its sound couldn’t be kept. To keep the sound, trim or compress the file to under ${cap} MB and use that file instead.`;
117
+ case 'failed':
118
+ return 'Couldn’t shrink this video. Trim or compress it first.';
119
+ }
120
+ }
121
+ /** What the shrink progress notice says. */
122
+ export const SHRINK_WORDS = {
123
+ shrinking: 'Shrinking video…',
124
+ retrying: 'Still too big, trying a smaller size…',
125
+ placing: 'Adding the video…',
126
+ waiting: 'Video ready. It’ll be added when you click out of the text box.',
127
+ progressLabel: 'Shrinking video',
128
+ limit: () => `Videos can be up to ${limitMb()} MB.`,
129
+ keepOpen: 'Keep this tab open until it’s done.',
130
+ queued: (count) => `${count} more video${count === 1 ? '' : 's'} waiting.`,
131
+ cancel: 'Cancel',
132
+ encoderMissing: 'The video encoder could not be loaded.',
133
+ };
@@ -0,0 +1,29 @@
1
+ /** Messages between the page and the video shrink worker. Each worker does one job and answers once (after progress). */
2
+ import type { ShrinkPlan, ShrinkProbe } from './plan.js';
3
+ export type ShrinkJob = {
4
+ kind: 'probe';
5
+ file: Blob;
6
+ } | {
7
+ kind: 'encode';
8
+ file: Blob;
9
+ plan: ShrinkPlan;
10
+ baseline: boolean;
11
+ };
12
+ /** Whether the sound came along: the source had none, it was kept, or it had to go. */
13
+ export type ShrinkSound = 'none' | 'kept' | 'dropped';
14
+ export type ShrinkAnswer = {
15
+ kind: 'progress';
16
+ value: number;
17
+ } | {
18
+ kind: 'probed';
19
+ probe: ShrinkProbe;
20
+ } | {
21
+ kind: 'encoded';
22
+ bytes: ArrayBuffer;
23
+ type: string;
24
+ sound: ShrinkSound;
25
+ baseline: boolean;
26
+ } | {
27
+ kind: 'failed';
28
+ message: string;
29
+ };
@@ -0,0 +1,2 @@
1
+ /** Messages between the page and the video shrink worker. Each worker does one job and answers once (after progress). */
2
+ export {};
@@ -0,0 +1,69 @@
1
+ /**
2
+ * Videos over the upload limit are written again smaller before they are
3
+ * stored: one at a time, in a worker, in order. While any are queued, the
4
+ * tab asks before it is closed and holds a web lock so the browser does not
5
+ * put it to sleep. The progress notice reads {@link useVideoShrink}.
6
+ */
7
+ import { type ShrinkFailure } from './plan.js';
8
+ import type { ShrinkAnswer, ShrinkJob, ShrinkSound } from './protocol.js';
9
+ /** What the notice shows of one queued video. */
10
+ export interface ShrinkEntry {
11
+ id: number;
12
+ name: string;
13
+ phase: 'queued' | 'shrinking' | 'placing';
14
+ /** 1 for the first try. */
15
+ attempt: number;
16
+ /** 0–1 through the current try. */
17
+ progress: number;
18
+ /** Done, and held until the text box being edited is left. */
19
+ waiting: boolean;
20
+ }
21
+ export declare const useVideoShrink: import("zustand").UseBoundStore<import("zustand").StoreApi<{
22
+ jobs: ShrinkEntry[];
23
+ }>>;
24
+ /** The video could not be made small enough (or, `sound-dropped`, only without its sound). */
25
+ export declare class ShrinkFailed extends Error {
26
+ readonly failure: ShrinkFailure;
27
+ constructor(failure: ShrinkFailure);
28
+ }
29
+ /** The person cancelled it from the notice. */
30
+ export declare class ShrinkCancelled extends Error {
31
+ constructor();
32
+ }
33
+ /** The worker could not be started. */
34
+ export declare class EncoderMissing extends Error {
35
+ constructor();
36
+ }
37
+ export interface ShrunkVideo {
38
+ file: File;
39
+ sound: ShrinkSound;
40
+ }
41
+ /** A queued shrink: its result, and `placed()` to call once the result is placed (or given up). */
42
+ export interface ShrinkTicket {
43
+ id: number;
44
+ result: Promise<ShrunkVideo>;
45
+ placed(): void;
46
+ }
47
+ /** Whether this browser can shrink videos at all. */
48
+ export declare function canShrinkVideos(): boolean;
49
+ /** What a job needs of a worker (tests give their own). */
50
+ export interface ShrinkWorkerPort {
51
+ onmessage: ((event: MessageEvent<ShrinkAnswer>) => void) | null;
52
+ onerror: ((event: ErrorEvent) => void) | null;
53
+ postMessage(job: ShrinkJob): void;
54
+ terminate(): void;
55
+ }
56
+ /** Replaces how workers are made (tests). */
57
+ export declare function setShrinkWorkerFactory(make: () => ShrinkWorkerPort): void;
58
+ /** When a worker that never answered is started again, and for how long that is tried. */
59
+ export declare const WORKER_RETRY_MS: readonly [1500, 6000];
60
+ /** Queues `file` to be made small enough to store. */
61
+ export declare function queueShrink(file: File): ShrinkTicket;
62
+ /** Marks a shrunk video as held until the text box is left (the notice says so). */
63
+ export declare function setShrinkWaiting(id: number, waiting: boolean): void;
64
+ /** True while the video `id` has been cancelled. */
65
+ export declare function shrinkCancelled(id: number): boolean;
66
+ /** Cancels the video `id`: a queued or shrinking one stops, a finished one is not placed. */
67
+ export declare function cancelShrink(id: number): void;
68
+ /** The job the notice is about: the one being shrunk or placed, else the first queued. */
69
+ export declare function leadingShrink(jobs: readonly ShrinkEntry[]): ShrinkEntry | undefined;