-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprompter.js
More file actions
219 lines (200 loc) · 7.53 KB
/
Copy pathprompter.js
File metadata and controls
219 lines (200 loc) · 7.53 KB
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
const track = document.getElementById('track');
const viewport = document.getElementById('viewport');
const pageTag = document.getElementById('pageTag');
const statusEl = document.getElementById('status');
const emptyEl = document.getElementById('empty');
let cfg = null;
let lines = []; // Flattened caption lines: {text, pageStart}
let lineEls = [];
let cur = 0; // Current highlighted line
let offset = 0; // translateY
let playing = false;
let lastT = 0;
let rafId = null;
function normalizeLocale(language) {
const lang = (language || '').trim();
return lang && lang.toLowerCase() !== 'auto' ? lang : undefined;
}
function fallbackSplitSentences(text) {
const parts = [];
const normalized = text.replace(/\r\n/g, '\n');
const chunks = normalized.split(/\n+/).map(s => s.trim()).filter(Boolean);
const sentencePattern = /[^.!?。!?؛؟।॥…]+(?:[.!?。!?؛؟।॥…]+["')\]\u00bb\u201d\u2019]*)?/g;
chunks.forEach((chunk) => {
const matches = chunk.match(sentencePattern);
if (matches && matches.length) {
matches.map(s => s.trim()).filter(Boolean).forEach(s => parts.push(s));
} else {
parts.push(chunk);
}
});
return parts;
}
function splitSentences(text, locale) {
const chunks = text.replace(/\r\n/g, '\n').split(/\n+/).map(s => s.trim()).filter(Boolean);
if (typeof Intl !== 'undefined' && Intl.Segmenter) {
try {
const segmenter = new Intl.Segmenter(locale, { granularity: 'sentence' });
return chunks.flatMap((chunk) =>
Array.from(segmenter.segment(chunk), s => s.segment.trim()).filter(Boolean)
);
} catch {
// Fall through to the punctuation-based splitter.
}
}
return fallbackSplitSentences(text);
}
function splitScript(text, delimRaw, language) {
if (!text || !text.trim()) return [];
let delim;
try { delim = new RegExp(delimRaw); } catch { delim = /\n\n+/; }
const pages = text.split(delim).map(s => s.trim()).filter(Boolean);
const out = [];
const locale = normalizeLocale(language);
pages.forEach((p) => {
const segs = splitSentences(p, locale);
segs.forEach((s, i) => out.push({ text: s, pageStart: i === 0 }));
});
return out;
}
function hexToRgba(hex, a) {
const m = /^#?([0-9a-f]{6})$/i.exec(hex || '#000000');
if (!m) return `rgba(0,0,0,${a})`;
const n = parseInt(m[1], 16);
return `rgba(${(n>>16)&255},${(n>>8)&255},${n&255},${a})`;
}
function applyStyle() {
if (!cfg) return;
const lang = normalizeLocale(cfg.language) || 'en';
const dir = cfg.direction === 'rtl' || cfg.direction === 'ltr' ? cfg.direction : 'auto';
document.documentElement.lang = lang;
document.documentElement.dir = dir === 'auto' ? 'ltr' : dir;
track.dir = dir;
document.getElementById('shell').style.background = hexToRgba(cfg.bgColor, cfg.opacity);
track.style.fontSize = cfg.fontSize + 'px';
track.style.lineHeight = cfg.lineHeight;
track.style.color = cfg.textColor;
track.style.fontFamily = cfg.fontFamily;
document.body.classList.toggle('mirror', !!cfg.mirror);
}
function render() {
track.innerHTML = '';
lineEls = [];
emptyEl.style.display = lines.length ? 'none' : 'flex';
lines.forEach((ln, i) => {
const div = document.createElement('div');
div.className = 'line dim' + (ln.pageStart && i > 0 ? ' pagestart' : '');
div.lang = normalizeLocale(cfg && cfg.language) || '';
div.dir = cfg && (cfg.direction === 'rtl' || cfg.direction === 'ltr') ? cfg.direction : 'auto';
div.textContent = ln.text;
track.appendChild(div);
lineEls.push(div);
});
if (cur >= lines.length) cur = Math.max(0, lines.length - 1);
centerCur(false);
}
function applyOffset(smooth) {
track.style.transition = smooth ? 'transform .22s ease-out' : 'none';
const mir = cfg && cfg.mirror ? ' scaleX(-1)' : '';
track.style.transform = `translateY(${offset}px)${mir}`;
}
// Keep the current line in the upper-middle reading zone.
function centerCur(smooth) {
const el = lineEls[cur];
if (!el) { offset = viewport.clientHeight * 0.42; applyOffset(smooth); return; }
offset = viewport.clientHeight * 0.42 - el.offsetTop - el.offsetHeight / 2;
applyOffset(smooth);
highlight();
updatePageTag();
}
function highlight() {
lineEls.forEach((el, i) => {
el.classList.toggle('cur', i === cur);
el.classList.toggle('dim', i !== cur);
});
}
function updatePageTag() {
if (!lines.length) { pageTag.textContent = ''; return; }
let page = 0;
for (let i = 0; i <= cur && i < lines.length; i++) if (lines[i].pageStart) page++;
const total = lines.filter(l => l.pageStart).length;
pageTag.textContent = `${cur + 1}/${lines.length} lines · Section ${page}/${total}`;
}
function step(d) {
const n = Math.min(Math.max(cur + d, 0), lines.length - 1);
if (n === cur) return;
cur = n;
centerCur(true);
}
function loop(t) {
if (!playing) { rafId = null; return; }
if (!lastT) lastT = t;
const dt = (t - lastT) / 1000;
lastT = t;
offset -= (cfg.scrollSpeed || 40) * dt;
const last = lineEls[lineEls.length - 1];
const minOffset = last ? (viewport.clientHeight * 0.42 - last.offsetTop - last.offsetHeight / 2) : 0;
if (offset <= minOffset) { offset = minOffset; playing = false; updatePlayBtn(); }
applyOffset(false);
const center = viewport.clientHeight * 0.42;
let best = 0, bestD = Infinity;
for (let i = 0; i < lineEls.length; i++) {
const mid = lineEls[i].offsetTop + offset + lineEls[i].offsetHeight / 2;
const dd = Math.abs(mid - center);
if (dd < bestD) { bestD = dd; best = i; }
}
cur = best; highlight(); updatePageTag();
rafId = requestAnimationFrame(loop);
}
function setPlaying(v) {
playing = v;
updatePlayBtn();
if (v) { lastT = 0; if (!rafId) rafId = requestAnimationFrame(loop); }
setStatus();
}
function updatePlayBtn() {
document.getElementById('btnPlay').textContent = playing ? '⏸ Pause' : '▶ Auto';
}
function setStatus() {
statusEl.textContent = `${playing ? '▶ ' + (cfg ? cfg.scrollSpeed : 0) + 'px/s' : 'Manual'}`;
}
function handleCmd(cmd) {
switch (cmd) {
case 'nextLine': if (playing) setPlaying(false); step(1); break;
case 'prevLine': if (playing) setPlaying(false); step(-1); break;
case 'togglePlay': setPlaying(!playing); break;
case 'faster': cfg.scrollSpeed = Math.min(200, (cfg.scrollSpeed || 40) + 8); window.api.setConfig({ scrollSpeed: cfg.scrollSpeed }); setStatus(); break;
case 'slower': cfg.scrollSpeed = Math.max(8, (cfg.scrollSpeed || 40) - 8); window.api.setConfig({ scrollSpeed: cfg.scrollSpeed }); setStatus(); break;
}
}
let wheelAcc = 0, wheelLock = false;
viewport.addEventListener('wheel', (e) => {
if (playing) setPlaying(false);
wheelAcc += e.deltaY;
if (wheelLock) return;
if (Math.abs(wheelAcc) >= 24) {
step(wheelAcc > 0 ? 1 : -1);
wheelAcc = 0;
wheelLock = true;
setTimeout(() => { wheelLock = false; }, 90);
}
}, { passive: true });
document.getElementById('btnControl').onclick = () => window.api.openControl();
document.getElementById('btnLock').onclick = () => window.api.toggleLock();
document.getElementById('btnPlay').onclick = () => setPlaying(!playing);
document.getElementById('btnQuit').onclick = () => window.api.quitApp();
function loadCfg(c) {
const firstLoad = cfg === null;
cfg = c;
lines = splitScript(c.script, c.pageDelimiter, c.language);
applyStyle();
render();
if (firstLoad) { cur = 0; centerCur(false); }
setStatus();
}
window.api.onConfig(loadCfg);
window.api.onCmd(handleCmd);
window.api.onLockChanged((locked) => {
document.getElementById('btnLock').textContent = locked ? '🔒 Locked' : '🔓 Lock';
});
window.api.getConfig().then(loadCfg);