-
Notifications
You must be signed in to change notification settings - Fork 0
/
Upload.tsx
399 lines (352 loc) · 12.4 KB
/
Upload.tsx
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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
import {useCallback, useContext, useEffect, useState} from 'react';
import {useDropzone} from 'react-dropzone';
import * as pdfjs from 'pdfjs-dist';
import 'react-pdf/dist/esm/Page/AnnotationLayer.css';
import 'react-pdf/dist/esm/Page/TextLayer.css';
import clsx from 'clsx/lite';
import {
type DocumentReference,
addDoc,
collection,
updateDoc,
getDoc,
doc,
} from 'firebase/firestore';
import {
ref as storageReference,
uploadBytes,
getDownloadURL,
getStorage,
connectStorageEmulator,
} from 'firebase/storage';
import {nanoid} from 'nanoid';
import {auth, firestore, app} from '../firebase';
import '../components/pdf/pdf.css';
import PresentationPreferencesEditor, {
type NotesSaveState,
} from '../components/PresentationPreferencesEditor';
import {
type PresentationCreate,
type Note,
type PresentationUpdate,
} from '../../functions/src/presentation';
import DefaultLayout from '../layouts/DefaultLayout';
import {UserContext, type UserDocument} from '../components/UserProvider';
import Loading from '../components/Loading';
import Pdf from '../components/pdf/Pdf';
// TODO: test fails sometimes, done text doesn't show pdf.
const source = new URL('pdfjs-dist/build/pdf.worker.min.js', import.meta.url);
pdfjs.GlobalWorkerOptions.workerSrc = source.toString();
type UploadState =
| 'fetching user'
| 'ready'
| 'creating'
| 'rendering pages'
| 'uploading pages'
| 'setting pages'
| 'done';
const storage = getStorage(app);
if (import.meta.env.MODE === 'emulator') {
connectStorageEmulator(storage, '127.0.0.1', 9199);
}
export default function Upload() {
useEffect(() => {
document.title = `Slidr - Upload`;
}, []);
const [uploadState, setUploadState] = useState<UploadState>('fetching user');
const [userData, setUserData] = useState<UserDocument>();
const [file, setFile] = useState<File>();
const [pageIndex, setPageIndex] = useState(0);
const [pageCount, setPageCount] = useState(0);
const [presentationReference, setPresentationReference] =
useState<DocumentReference>();
const [notes, setNotes] = useState<Note[]>([]);
const [title, setTitle] = useState('');
const [savingState, setSavingState] = useState<NotesSaveState>('saved');
const [pageBlob, setPageBlob] = useState<Blob>();
const [uploadPromises, setUploadPromises] = useState<Array<Promise<string>>>(
[],
);
const [pages, setPages] = useState<string[]>([]);
const {user} = useContext(UserContext);
useEffect(() => {
async function getUserDocument() {
setUploadState('fetching user');
if (!user) {
setUserData(undefined);
return;
}
const userSnapshot = await getDoc(doc(firestore, 'users', user.uid));
setUploadState('ready');
if (!userSnapshot.exists()) {
setUserData({});
return;
}
setUserData(userSnapshot.data() as UserDocument);
}
void getUserDocument();
}, [user]);
const {getRootProps, getInputProps, isDragActive, acceptedFiles} =
useDropzone({
accept: {
// eslint-disable-next-line @typescript-eslint/naming-convention
'application/pdf': ['.pdf'],
},
maxFiles: 1,
});
useEffect(() => {
async function startRenderingFile() {
if (!acceptedFiles[0] || uploadState !== 'ready') {
return;
}
setFile(acceptedFiles[0]);
const presentationReference_ = await addDoc(
collection(firestore, 'presentations'),
{
created: new Date(),
uid: auth.currentUser!.uid,
username: userData?.username ?? '',
twitterHandle: userData?.twitterHandle ?? '',
pages: [],
notes: [],
title: '',
} satisfies PresentationCreate,
);
setPresentationReference(presentationReference_);
const originalName = `${nanoid()}.pdf`;
const originalReference = storageReference(
storage,
`presentations/${presentationReference_.id}/${originalName}`,
);
await uploadBytes(originalReference, acceptedFiles[0], {
cacheControl: 'public;max-age=604800',
});
const originalDownloadUrl = await getDownloadURL(originalReference);
await updateDoc(presentationReference_, {
original: originalDownloadUrl,
} satisfies PresentationUpdate);
setUploadState('rendering pages');
}
void startRenderingFile();
}, [acceptedFiles, uploadState, userData?.twitterHandle, userData?.username]);
const pageRendered = useCallback((canvas: HTMLCanvasElement) => {
// Watermark rendered image
const context = canvas.getContext('2d');
if (context) {
const rootStyles = window.getComputedStyle(
document.querySelector('#root')!,
);
const fontFamily = rootStyles.getPropertyValue('font-family');
// The weight should match an already loaded font so that all watermarks have the same dimensions.
// Otherwise, the first page may not have the correctly scaled font.
const fontStyle = `500 16px ${fontFamily}`;
context.font = fontStyle;
context.fillStyle = 'rgba(255,255,255,0.75)';
context.strokeStyle = 'rgba(0,0,0,0.45)';
const textMetrics = context.measureText('slidr.app');
const x =
canvas.width -
20 -
textMetrics.actualBoundingBoxLeft -
textMetrics.actualBoundingBoxRight;
const y =
canvas.height -
0 -
textMetrics.fontBoundingBoxAscent -
textMetrics.fontBoundingBoxDescent;
context.fillText('slidr.app', x, y);
context.strokeText('slidr.app', x, y);
}
canvas.toBlob(async (blob) => {
if (!blob) {
throw new Error(`Error rendering pdf canvas to image webp blob`);
}
setPageBlob(blob);
}, 'image/webp');
}, []);
useEffect(() => {
async function uploadPage(pageImage: Blob, id: string) {
const pageStorageReference = storageReference(
storage,
`presentations/${id}/${pageIndex
.toString()
.padStart(3, '0')}_${nanoid()}.webp`,
);
await uploadBytes(pageStorageReference, pageImage, {
cacheControl: 'public, max-age=604800, immutable',
});
console.log('upload done', pageIndex);
const pageUrl = await getDownloadURL(pageStorageReference);
console.log('dl url done', pageIndex);
return pageUrl;
}
if (
uploadState !== 'rendering pages' ||
!pageBlob ||
!presentationReference
) {
return;
}
const uploadPromise = uploadPage(pageBlob, presentationReference.id);
setUploadPromises((currentPromises) => [...currentPromises, uploadPromise]);
setPageBlob(undefined);
if (pageIndex < pageCount - 1) {
setPageIndex(pageIndex + 1);
} else {
setUploadState('uploading pages');
// SetRenderingDone(true);
}
}, [uploadState, pageBlob, pageIndex, presentationReference, pageCount]);
useEffect(() => {
async function updatePages() {
if (!presentationReference || uploadState !== 'uploading pages') {
return;
}
console.log('waiting for pages');
const nextPages = await Promise.all(uploadPromises);
console.log('pages done');
const nextNotes = nextPages.map((_, pageIndex) => ({
pageIndices: [pageIndex] as [number, ...number[]],
markdown: '',
}));
setPages(nextPages);
setNotes(nextNotes);
setUploadState('setting pages');
}
void updatePages();
}, [uploadState, presentationReference, uploadPromises]);
useEffect(() => {
async function setPages() {
if (uploadState !== 'setting pages' || !presentationReference) {
return;
}
setSavingState('saving');
console.log('updating doc with pages');
await updateDoc(presentationReference, {
pages,
rendered: new Date(),
title,
notes,
} satisfies PresentationUpdate);
console.log('doc update done');
setUploadState('done');
setSavingState((currentState) =>
currentState === 'saving' ? 'saved' : currentState,
);
}
void setPages();
}, [uploadState, presentationReference, notes, pages, title]);
function getUserFeedback() {
if (uploadState === 'creating') {
return [
'Initializing...',
'i-tabler-loader-3 animate-spin animate-duration-1000',
];
}
if (uploadState === 'rendering pages') {
return ['Rendering...', 'i-tabler-loader-3 animate-spin'];
}
if (uploadState === 'uploading pages' || uploadState === 'setting pages') {
return ['Uploading...', 'i-tabler-arrow-big-up-lines animate-bounce'];
}
if (uploadState === 'done') {
return ['Done', 'i-tabler-check'];
}
return ['', ''];
}
const [message, icon] = getUserFeedback();
async function savePreferences() {
// TODO: there is probably a race condition between uploading === true and uploadDone === true
// Could it be possible to lose some updates?
// The core problem is probably that the this save can happen async and the uploading save happens with an effect
// Consider: always updating here, ignoring uploadingDone
// Or do the upload synchronously 🤔
// if (!uploadDone || !presentationRef) {
// Update, let them both save, we may lose a note if the uploading save happens after this save, but that seems unlikely
if (uploadState !== 'done' || !presentationReference) {
return;
}
setSavingState('saving');
await updateDoc(presentationReference, {
notes,
title,
} satisfies PresentationUpdate);
setSavingState((currentState) =>
currentState === 'saving' ? 'saved' : currentState,
);
}
return (
<DefaultLayout title="New Presentation">
{/* TODO: loading spinner */}
{uploadState === 'fetching user' ? (
<div className="flex flex-col col-span-2 lt-sm:col-span-1 h-40 items-center justify-center">
<Loading />
</div>
) : (
<div className="overflow-hidden flex flex-col items-center p-4 gap-6 pb-10 w-full max-w-screen-md mx-auto">
{!file && (
<div
className="btn rounded-md p-8 flex w-full max-w-screen-sm aspect-video gap-4 cursor-pointer mx-6"
{...getRootProps({role: 'button'})}
>
<label className="flex flex-col items-center justify-center w-full cursor-pointer">
{isDragActive ? (
<>
<div className="i-tabler-arrow-big-down-lines text-6xl animate-bounce animate-duration-500 text-teal-500" />
<div className="text-center">
Drop the pdf presentation here...
</div>
</>
) : (
<>
<div className="i-tabler-arrow-big-down-lines text-6xl animate-bounce" />
<div className="text-center">
Drag 'n' drop a pdf presentation here, or click
to select a pdf presentation
</div>
</>
)}
<input {...getInputProps()} />
</label>
</div>
)}
{uploadState !== 'ready' && (
<div className="flex flex-col w-full max-w-screen-sm">
<div className="relative w-full">
<Pdf
pageIndex={pageIndex}
file={file!}
onSetPageCount={setPageCount}
onPageRendered={pageRendered}
/>
<div className="absolute top-0 left-0 w-full h-full flex flex-col items-center justify-center bg-teal-800 bg-opacity-90">
<div className={clsx('w-10 h-10', icon)} />
<div>{message}</div>
</div>
<div
className="absolute bottom-0 h-[6px] bg-teal"
style={{width: `${((pageIndex + 1) * 100) / pageCount}%`}}
/>
</div>
<div>Rendering slide: {pageIndex + 1}</div>
</div>
)}
<PresentationPreferencesEditor
saveState={savingState}
notes={notes}
title={title}
setNotes={setNotes}
setTitle={setTitle}
pages={pages}
onSave={() => {
void savePreferences();
}}
onDirty={() => {
setSavingState('dirty');
}}
/>
</div>
)}
</DefaultLayout>
);
}