-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
362 lines (301 loc) · 10.2 KB
/
app.js
File metadata and controls
362 lines (301 loc) · 10.2 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
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
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
/**
* RSVP Reader - Main Application
*/
import { parseFile, isSupported } from './lib/parsers/index.js';
import { tokenize } from './lib/tokenizer.js';
import { splitAtORP, getDelayMultiplier } from './lib/orp.js';
import { createTimingController } from './lib/timing.js';
// DOM Elements
const uploadScreen = document.getElementById('upload-screen');
const readerScreen = document.getElementById('reader-screen');
const dropZone = document.getElementById('drop-zone');
const fileInput = document.getElementById('file-input');
const browseBtn = document.getElementById('browse-btn');
const loading = document.getElementById('loading');
const wordBefore = document.getElementById('word-before');
const wordOrp = document.getElementById('word-orp');
const wordAfter = document.getElementById('word-after');
const wordDisplay = document.getElementById('word-display');
const progressBar = document.getElementById('progress-bar');
const progressText = document.getElementById('progress-text');
const playBtn = document.getElementById('play-btn');
const backBtn = document.getElementById('back-btn');
const forwardBtn = document.getElementById('forward-btn');
const closeBtn = document.getElementById('close-btn');
const wpmSlider = document.getElementById('wpm-slider');
const wpmDisplay = document.getElementById('wpm-display');
const statsContainer = document.getElementById('stats-container');
const statsToggleBtn = document.getElementById('stats-toggle-btn');
const timeRemaining = document.getElementById('time-remaining');
const wordsRemaining = document.getElementById('words-remaining');
// State
let currentFile = null;
let showStats = false;
// Timing Controller
const timer = createTimingController({
wpm: 150,
getDelayMultiplier,
onWord: displayWord,
onProgress: updateProgress,
onComplete: onReadingComplete
});
// ============================================
// Bookmark System
// ============================================
function getFileId(file) {
// Create unique ID from filename and size
return `${file.name}_${file.size}`;
}
function saveBookmark(file, position) {
const fileId = getFileId(file);
localStorage.setItem(`bookmark_${fileId}`, position.toString());
}
function loadBookmark(file) {
const fileId = getFileId(file);
const saved = localStorage.getItem(`bookmark_${fileId}`);
return saved ? parseInt(saved) : 0;
}
function clearBookmark(file) {
const fileId = getFileId(file);
localStorage.removeItem(`bookmark_${fileId}`);
}
// ============================================
// File Handling
// ============================================
browseBtn.addEventListener('click', () => fileInput.click());
fileInput.addEventListener('change', handleFileSelect);
dropZone.addEventListener('dragover', (e) => {
e.preventDefault();
dropZone.classList.add('drag-over');
});
dropZone.addEventListener('dragleave', () => {
dropZone.classList.remove('drag-over');
});
dropZone.addEventListener('drop', (e) => {
e.preventDefault();
dropZone.classList.remove('drag-over');
const files = e.dataTransfer.files;
if (files.length > 0) {
processFile(files[0]);
}
});
function handleFileSelect(e) {
const file = e.target.files[0];
if (file) {
processFile(file);
}
}
async function processFile(file) {
// File size validation (50MB max)
const MAX_FILE_SIZE = 50 * 1024 * 1024;
if (file.size > MAX_FILE_SIZE) {
alert('File too large. Maximum size is 50MB.');
return;
}
// MIME type validation
const validMimeTypes = {
'application/pdf': true,
'application/vnd.openxmlformats-officedocument.wordprocessingml.document': true,
'application/epub+zip': true,
'text/plain': true,
'text/markdown': true,
'': true // Empty MIME type allowed (some systems don't set it)
};
if (!validMimeTypes[file.type]) {
alert('Invalid file type detected. Please use PDF, DOCX, EPUB, TXT, or MD files.');
return;
}
if (!isSupported(file)) {
alert('Unsupported file type. Please use PDF, DOCX, EPUB, TXT, or MD files.');
return;
}
showLoading(true);
try {
const text = await parseFile(file);
const words = tokenize(text);
if (words.length === 0) {
throw new Error('No text content found in file');
}
currentFile = file;
timer.load(words);
// Load bookmark and resume from saved position
const savedPosition = loadBookmark(file);
if (savedPosition > 0) {
timer.seek(savedPosition);
}
showReader();
const currentIndex = timer.getCurrentIndex();
displayWord(words[currentIndex], currentIndex);
updateProgress(currentIndex, words.length);
updateStats();
} catch (error) {
console.error('Error processing file:', error);
alert('Error processing file: ' + error.message);
} finally {
showLoading(false);
}
}
// ============================================
// Display
// ============================================
function displayWord(word, index) {
const parts = splitAtORP(word);
wordBefore.textContent = parts.before;
wordOrp.textContent = parts.orp;
wordAfter.textContent = parts.after;
}
function updateProgress(current, total) {
const percent = total > 0 ? Math.round((current / total) * 100) : 0;
progressBar.style.setProperty('--progress', `${percent}%`);
progressText.textContent = `${percent}%`;
// Save bookmark
if (currentFile) {
saveBookmark(currentFile, current);
}
// Update stats
updateStats();
}
function updateStats() {
if (!showStats) return;
const current = timer.getCurrentIndex();
const total = timer.getWordCount();
const wpm = timer.getWPM();
// Calculate time remaining
const wordsLeft = total - current;
const minutesLeft = wordsLeft / wpm;
const hours = Math.floor(minutesLeft / 60);
const minutes = Math.floor(minutesLeft % 60);
const seconds = Math.floor((minutesLeft * 60) % 60);
// Format time
let timeStr;
if (hours > 0) {
timeStr = `${hours}h ${minutes}m`;
} else if (minutes > 0) {
timeStr = `${minutes}m ${seconds}s`;
} else {
timeStr = `${seconds}s`;
}
timeRemaining.textContent = timeStr;
wordsRemaining.textContent = `${wordsLeft}/${total} words`;
}
function onReadingComplete() {
playBtn.classList.remove('playing');
playBtn.textContent = '▶';
}
// ============================================
// Controls
// ============================================
playBtn.addEventListener('click', () => {
const isPlaying = timer.toggle();
playBtn.classList.toggle('playing', isPlaying);
playBtn.textContent = isPlaying ? '⏸' : '▶';
});
backBtn.addEventListener('click', () => {
timer.back(10);
});
forwardBtn.addEventListener('click', () => {
timer.forward(10);
});
closeBtn.addEventListener('click', () => {
timer.pause();
// Save final position before closing
if (currentFile) {
saveBookmark(currentFile, timer.getCurrentIndex());
}
showUpload();
});
wpmSlider.addEventListener('input', () => {
const wpm = parseInt(wpmSlider.value);
timer.setWPM(wpm);
wpmDisplay.textContent = `${wpm} WPM`;
updateStats(); // Update reading time when WPM changes
});
// Tap on word display to toggle play/pause
wordDisplay.addEventListener('click', () => {
playBtn.click();
});
// Stats toggle button
statsToggleBtn.addEventListener('click', () => {
showStats = !showStats;
statsContainer.classList.toggle('hidden', !showStats);
if (showStats) {
updateStats();
}
});
// Progress bar click to seek
progressBar.addEventListener('click', (e) => {
const rect = progressBar.getBoundingClientRect();
const percent = ((e.clientX - rect.left) / rect.width) * 100;
timer.seekPercent(percent);
});
// Keyboard shortcuts
document.addEventListener('keydown', (e) => {
if (!readerScreen.classList.contains('active')) return;
switch (e.code) {
case 'Space':
e.preventDefault();
playBtn.click();
break;
case 'ArrowLeft':
timer.back(5);
break;
case 'ArrowRight':
timer.forward(5);
break;
case 'ArrowUp':
wpmSlider.value = Math.min(1000, parseInt(wpmSlider.value) + 25);
wpmSlider.dispatchEvent(new Event('input'));
break;
case 'ArrowDown':
wpmSlider.value = Math.max(100, parseInt(wpmSlider.value) - 25);
wpmSlider.dispatchEvent(new Event('input'));
break;
case 'Escape':
closeBtn.click();
break;
}
});
// ============================================
// Screen Navigation
// ============================================
function showUpload() {
uploadScreen.classList.add('active');
readerScreen.classList.remove('active');
fileInput.value = '';
}
function showReader() {
uploadScreen.classList.remove('active');
readerScreen.classList.add('active');
}
function showLoading(show) {
if (show) {
dropZone.classList.add('hidden');
loading.classList.remove('hidden');
} else {
dropZone.classList.remove('hidden');
loading.classList.add('hidden');
}
}
// ============================================
// Visit Counter
// ============================================
async function updateVisitCounter() {
try {
const response = await fetch('https://api.countapi.xyz/hit/rsvp-reader-glitches/visits');
const data = await response.json();
document.getElementById('visit-count').textContent = data.value.toLocaleString();
} catch (error) {
console.error('Failed to update visit counter:', error);
document.getElementById('visit-count').textContent = '???';
}
}
// Update counter on page load
updateVisitCounter();
// ============================================
// PWA Service Worker
// ============================================
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('sw.js')
.then(reg => console.log('SW registered'))
.catch(err => console.log('SW registration failed:', err));
}