-
Notifications
You must be signed in to change notification settings - Fork 32
Expand file tree
/
Copy pathApp.tsx
More file actions
629 lines (556 loc) · 19.4 KB
/
Copy pathApp.tsx
File metadata and controls
629 lines (556 loc) · 19.4 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
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
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
/**
* SPDX-FileCopyrightText: 2020 Excalidraw, 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: MIT
*/
/* eslint-disable @typescript-eslint/no-explicit-any */
import { memo, useCallback, useEffect, useLayoutEffect, useMemo, useState } from 'react'
import { getCurrentUser } from '@nextcloud/auth'
import { translate as t } from '@nextcloud/l10n'
import { loadState } from '@nextcloud/initial-state'
import { Excalidraw as ExcalidrawComponent, useHandleLibrary, Sidebar, isElementLink } from '@nextcloud/excalidraw'
import '@excalidraw/excalidraw/index.css'
import type { LibraryItems } from '@nextcloud/excalidraw/dist/types/excalidraw/types'
import { useExcalidrawStore } from './stores/useExcalidrawStore'
import { useWhiteboardConfigStore } from './stores/useWhiteboardConfigStore'
import { useThemeHandling } from './hooks/useThemeHandling'
import { useCollaboration } from './hooks/useCollaboration'
import { useSmartPicker } from './hooks/useSmartPicker'
import { useTableInsertion } from './hooks/useTableInsertion'
import { useReadOnlyState } from './hooks/useReadOnlyState'
import { ExcalidrawMenu } from './components/ExcalidrawMenu'
import Embeddable from './components/Embeddable'
import { useLangStore } from './stores/useLangStore'
import { NetworkStatusIndicator } from './components/NetworkStatusIndicator'
import { AuthErrorNotification } from './components/AuthErrorNotification'
import { useSync } from './hooks/useSync'
import { useSyncStore } from './stores/useSyncStore'
import { useLibrary } from './hooks/useLibrary'
import { useShallow } from 'zustand/react/shallow'
import { useBoardDataManager } from './hooks/useBoardDataManager'
import { useAssistant } from './hooks/useAssistant'
import logger from './utils/logger'
import { useRecording } from './hooks/useRecording'
import { RecordingOverlay } from './components/Recording'
import { usePresentation } from './hooks/usePresentation'
import { PresentationOverlay } from './components/Presentation'
import { useTimer } from './hooks/useTimer'
import { TimerOverlay } from './components/Timer'
import { useCollaborationStore } from './stores/useCollaborationStore'
import { useElementCreatorTracking } from './hooks/useElementCreatorTracking'
import { useFollowedUser } from './hooks/useFollowedUser'
import { CreatorDisplay } from './components/CreatorDisplay'
import { useCreatorDisplayStore } from './stores/useCreatorDisplayStore'
import type { ExcalidrawElement } from '@nextcloud/excalidraw/dist/types/excalidraw/element/types'
import type { ElementCreatorInfo } from './types/whiteboard'
import { VersionPreviewBanner } from './components/VersionPreviewBanner'
import { useVersionPreview } from './hooks/useVersionPreview'
import { subscribe, unsubscribe } from '@nextcloud/event-bus'
import { useComment } from './hooks/useComment'
import { CommentSidebar } from './components/CommentSidebar'
import { useEmojiPicker } from './hooks/useEmojiPicker'
import { VotingSidebar } from './components/VotingSidebar'
import { useVoting } from './hooks/useVoting'
import { useContextMenuFilter } from './hooks/useContextMenuFilter'
import { useDisableExternalLibraries } from './hooks/useDisableExternalLibraries'
import { callMobileMessage } from './utils/mobileInterface'
const Excalidraw = memo(ExcalidrawComponent)
const MemoizedNetworkStatusIndicator = memo(NetworkStatusIndicator)
const MemoizedAuthErrorNotification = memo(AuthErrorNotification)
const MemoizedExcalidrawMenu = memo(ExcalidrawMenu)
export interface WhiteboardAppProps {
fileId: number
fileName: string
isEmbedded: boolean
publicSharingToken: string | null
collabBackendUrl: string
versionSource: string | null
fileVersion: string | null
}
export default function App({
fileId,
isEmbedded,
fileName,
publicSharingToken,
collabBackendUrl,
versionSource,
fileVersion,
}: WhiteboardAppProps) {
const normalizedFileId = Number.isFinite(fileId) ? fileId : Number(fileId)
const fileNameWithoutExtension = useMemo(() => fileName.split('.').slice(0, -1).join('.'), [fileName])
const maxImageSizeMb = useMemo(() => {
const rawValue = Number(loadState('whiteboard', 'maxFileSize', 10))
if (!Number.isFinite(rawValue) || rawValue <= 0) {
return null
}
return rawValue
}, [])
const maxImageSizeBytes = useMemo(() => (
maxImageSizeMb ? maxImageSizeMb * 1024 * 1024 : null
), [maxImageSizeMb])
const { excalidrawAPI, setExcalidrawAPI, resetExcalidrawAPI } = useExcalidrawStore(useShallow(state => ({
excalidrawAPI: state.excalidrawAPI,
setExcalidrawAPI: state.setExcalidrawAPI,
resetExcalidrawAPI: state.resetExcalidrawAPI,
})))
const {
setConfig,
gridModeEnabled,
initialDataPromise,
resetInitialDataPromise,
resetStore,
setGridModeEnabled,
} = useWhiteboardConfigStore(useShallow(state => ({
setConfig: state.setConfig,
gridModeEnabled: state.gridModeEnabled,
initialDataPromise: state.initialDataPromise,
resetInitialDataPromise: state.resetInitialDataPromise,
resetStore: state.resetStore,
setGridModeEnabled: state.setGridModeEnabled,
})))
const { lang, updateLang } = useLangStore(useShallow(state => ({
lang: state.lang,
updateLang: state.updateLang,
})))
const { terminateWorker } = useSyncStore(useShallow(state => ({
terminateWorker: state.terminateWorker,
})))
const { theme } = useThemeHandling()
const { renderSmartPicker } = useSmartPicker()
const { renderTable } = useTableInsertion()
const { renderAssistant } = useAssistant()
const { renderEmojiPicker } = useEmojiPicker()
const { onChange: onChangeSync, onPointerUpdate } = useSync()
const { fetchLibraryItems, updateLibraryItems, isLibraryLoaded, setIsLibraryLoaded } = useLibrary()
useCollaboration()
const { isReadOnly, refreshReadOnlyState } = useReadOnlyState()
const {
isVersionPreview,
versionLabel,
versionSourceLabel,
exitVersionPreview,
handleRestoreVersion,
handleExternalRestore,
isRestoringVersion,
} = useVersionPreview({
fileId: normalizedFileId,
versionSource,
fileVersion,
excalidrawAPI,
refreshReadOnlyState,
isReadOnly,
})
if (!normalizedFileId && !isVersionPreview) {
logger.warn('[App] Invalid fileId during initialization:', fileId)
return <div className="App-error">{t('whiteboard', 'Invalid whiteboard ID. Please try again.')}</div>
}
// Creator tracking
const creatorDisplaySettings = useCreatorDisplayStore(state => state.settings)
useElementCreatorTracking({ excalidrawAPI, enabled: true })
useFollowedUser({ excalidrawAPI, fileId: normalizedFileId })
useContextMenuFilter(excalidrawAPI)
useDisableExternalLibraries()
useEffect(() => {
const handleVideoError = (e: Event) => {
const target = e.target as HTMLElement
if (target?.tagName === 'VIDEO') {
logger.error('[App] Caught video embed error:', e)
e.stopPropagation()
e.stopImmediatePropagation()
e.preventDefault()
}
}
window.addEventListener('error', handleVideoError, true)
return () => {
window.removeEventListener('error', handleVideoError, true)
}
}, [])
const recordingState = useRecording({ fileId: normalizedFileId })
const presentationState = usePresentation({ fileId: normalizedFileId })
const timerState = useTimer({ fileId: normalizedFileId })
const [isTimerPinned, setIsTimerPinned] = useState(false)
const [isTimerDismissed, setIsTimerDismissed] = useState(false)
const isTimerActive = timerState.status !== 'idle'
const isTimerVisible = isTimerPinned || (isTimerActive && !isTimerDismissed)
useEffect(() => {
if (!isTimerActive) {
setIsTimerDismissed(false)
}
}, [isTimerActive])
const handleToggleTimer = useCallback(() => {
if (isTimerVisible) {
setIsTimerPinned(false)
if (isTimerActive) {
setIsTimerDismissed(true)
}
return
}
setIsTimerDismissed(false)
if (!isTimerActive) {
setIsTimerPinned(true)
}
}, [isTimerVisible, isTimerActive])
// Voting
const { startVoting, vote, endVoting } = useVoting()
const votings = useCollaborationStore(state => state.votings)
useHandleLibrary({
excalidrawAPI,
})
useEffect(() => {
if (!excalidrawAPI) return
const preventEmbedWheelPropagation = () => {
document.querySelectorAll('.excalidraw__embeddable-container').forEach(container => {
if (!container.dataset.wheelPrevented) {
container.addEventListener('wheel', (e) => e.stopPropagation())
container.dataset.wheelPrevented = 'true'
}
})
}
preventEmbedWheelPropagation()
const observer = new MutationObserver(preventEmbedWheelPropagation)
const wrapper = document.querySelector('.excalidraw')
if (wrapper) {
observer.observe(wrapper, { childList: true })
}
return () => observer.disconnect()
}, [excalidrawAPI])
useEffect(() => {
const onRestoreRequested = (payload: any) => {
const payloadFileId = Number(payload?.fileInfo?.id)
const mimetype = payload?.fileInfo?.mimetype
const fileName = payload?.fileInfo?.name ?? ''
const source = payload?.version?.source ?? payload?.version?.url ?? null
const versionId = payload?.version?.fileVersion ?? null
const isWhiteboard = mimetype === 'application/vnd.excalidraw+json'
|| (typeof fileName === 'string' && fileName.toLowerCase().endsWith('.whiteboard'))
if (!payload || !isWhiteboard) {
return
}
if (!Number.isFinite(payloadFileId) || payloadFileId !== normalizedFileId) {
return
}
if (!source) {
logger.error('[App] Missing version source for whiteboard restore request', { payload })
return
}
if (payload && typeof payload === 'object') {
payload.preventDefault = true
}
handleExternalRestore(source, versionId).catch(error => {
logger.error('[App] Failed to handle whiteboard restore from sidebar', { error, source, versionId })
})
}
subscribe('files_versions:restore:requested', onRestoreRequested)
return () => {
unsubscribe('files_versions:restore:requested', onRestoreRequested)
}
}, [handleExternalRestore, normalizedFileId])
// Use the board data manager hook
const { saveOnUnmount, isLoading } = useBoardDataManager()
useEffect(() => {
if (!isLoading && loadState('whiteboard', 'directEditing', false)) {
callMobileMessage('loaded')
}
}, [isLoading])
// Effect to handle fileId changes - cleanup previous board data
useEffect(() => {
// Clear any existing Excalidraw data when fileId changes
if (excalidrawAPI) {
excalidrawAPI.resetScene()
}
// Reset the initialDataPromise to ensure clean state
resetInitialDataPromise()
return () => {
// Save current board data before switching
if (excalidrawAPI) {
saveOnUnmount()
}
}
}, [normalizedFileId, excalidrawAPI, resetInitialDataPromise, saveOnUnmount])
useEffect(() => {
resetInitialDataPromise()
// Fetch library items from the API
window.name = fileName
const fetchLibInterval = setInterval(async () => {
const api = useExcalidrawStore.getState().excalidrawAPI
if (!api) {
logger.warn('[App] Excalidraw API not available, cannot update library')
return
}
clearInterval(fetchLibInterval)
try {
const libraryItems = await fetchLibraryItems()
await api.updateLibrary({
libraryItems: libraryItems || [],
})
setIsLibraryLoaded(true)
} catch (error) {
logger.error('[App] Error updating library items:', error)
}
}, 1000)
// On unmount: Clean up all stores to prevent stale state
return () => {
// Save any pending changes before resetting stores
saveOnUnmount()
// Reset all stores
resetStore()
resetExcalidrawAPI()
// Terminate the worker
terminateWorker()
}
}, [resetInitialDataPromise, resetStore, resetExcalidrawAPI, terminateWorker, saveOnUnmount])
const [activeCommentThreadId, setActiveCommentThreadId] = useState<string | null>(null)
const [commentSidebarDocked, setCommentSidebarDocked] = useState(false)
const { renderComment, commentThreads, panToThread, deleteThread } = useComment({
activeCommentThreadId,
isReadOnly,
onCommentThreadClick: (commentThreadId) => {
setActiveCommentThreadId(commentThreadId)
if (commentThreadId) {
excalidrawAPI?.toggleSidebar({ name: 'commentSidebar', tab: 'comments', force: true })
}
},
onOpenSidebar: () => {
excalidrawAPI?.toggleSidebar({ name: 'commentSidebar', tab: 'comments', force: true })
},
})
useLayoutEffect(() => {
setConfig({
fileId: normalizedFileId,
fileName,
publicSharingToken,
isEmbedded,
collabBackendUrl,
})
}, [setConfig, normalizedFileId, fileName, publicSharingToken, isEmbedded, collabBackendUrl])
// UI Initialization Effect
useEffect(() => {
updateLang()
const renderCustomElements = () => {
renderSmartPicker()
renderTable()
renderAssistant()
renderComment()
renderEmojiPicker()
}
renderCustomElements()
const excalidrawElement = document.querySelector('.excalidraw')
if (!excalidrawElement) return
const observer = new MutationObserver(renderCustomElements)
observer.observe(excalidrawElement, { attributes: true, attributeFilter: ['class'] })
return () => observer.disconnect()
}, [updateLang, renderSmartPicker, renderAssistant, renderComment, renderEmojiPicker, renderTable])
const onLibraryChange = useCallback(async (items: LibraryItems) => {
if (!isLibraryLoaded) {
// Skip updating library items on first load
return
}
try {
await updateLibraryItems(items)
} catch (error) {
logger.error('[App] Error syncing library items:', error)
}
}, [isLibraryLoaded])
const libraryReturnUrl = encodeURIComponent(window.location.href)
// Data loading is now handled by useBoardDataManager
const onLinkOpen = useCallback((element: any, event: any) => {
const link = element.link
if (!link) {
return
}
const { nativeEvent } = event.detail
const isNewTab = nativeEvent.ctrlKey || nativeEvent.metaKey
const isNewWindow = nativeEvent.shiftKey
const isInternalLink = link.startsWith('/') || link.includes(window.location.origin)
if (isElementLink(link) && !isNewTab && !isNewWindow) {
event.preventDefault()
excalidrawAPI?.scrollToContent(link)
return
}
if (isInternalLink && !isNewTab && !isNewWindow) {
event.preventDefault()
window.open(link, '_blank')
}
}, [excalidrawAPI])
const generateIdForFile = useCallback(async (file: File): Promise<string> => {
if (maxImageSizeBytes && file.size > maxImageSizeBytes) {
const maxSizeMb = maxImageSizeMb ?? 0
throw new Error(t('whiteboard', 'Max image size is {max} MB', { max: maxSizeMb }))
}
// must return an id, excalidraws id generator only runs when the callback prop is not set
return Array.from({ length: 40 }, () => Math.floor(Math.random() * 16).toString(16)).join('')
}, [maxImageSizeBytes, maxImageSizeMb])
const handleOnChange = useCallback(() => {
if (isVersionPreview) {
return
}
if (!excalidrawAPI || !normalizedFileId || isLoading) return
onChangeSync()
}, [excalidrawAPI, normalizedFileId, isLoading, onChangeSync, isVersionPreview])
const canvasActions = useMemo(() => {
if (isVersionPreview) {
return {
changeViewBackgroundColor: false,
clearCanvas: false,
export: false,
loadScene: false,
saveAsImage: false,
saveToActiveFile: false,
toggleTheme: false,
}
}
return {
loadScene: false,
}
}, [isVersionPreview])
const appClassName = useMemo(() => (
isVersionPreview ? 'App App--version-preview' : 'App'
), [isVersionPreview])
if (isLoading) {
return (
<div className="App" style={{ display: 'flex', flexDirection: 'column' }}>
<div className="App-loading" style={{
flex: 1,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
}}>
Loading whiteboard...
</div>
</div>
)
}
const beforeElementCreated = (el: ExcalidrawElement) => {
const user = getCurrentUser()
if (!user) {
return el
}
const creatorInfo: ElementCreatorInfo = {
uid: user.uid,
displayName: user.displayName || user.uid,
createdAt: Date.now(),
}
if (!el.customData) {
el.customData = {
creator: creatorInfo,
lastModifiedAt: Date.now(),
}
} else {
el.customData.creator = creatorInfo
el.customData.lastmodifiedAt = Date.now()
}
return el
}
return (
<div className={appClassName} style={{ display: 'flex', flexDirection: 'column' }}>
<div className="excalidraw-wrapper" style={{ flex: 1, height: '100%', position: 'relative' }}>
{!isVersionPreview && <MemoizedNetworkStatusIndicator />}
<MemoizedAuthErrorNotification />
{isVersionPreview && (
<VersionPreviewBanner
versionLabel={versionLabel}
sourceLabel={versionSourceLabel}
onExit={exitVersionPreview}
onRestore={handleRestoreVersion}
isRestoring={isRestoringVersion}
/>
)}
<Excalidraw
validateEmbeddable={() => true}
renderEmbeddable={Embeddable}
beforeElementCreated={beforeElementCreated}
excalidrawAPI={setExcalidrawAPI}
initialData={initialDataPromise}
generateIdForFile={generateIdForFile}
onPointerUpdate={onPointerUpdate}
onChange={handleOnChange}
viewModeEnabled={isReadOnly}
gridModeEnabled={gridModeEnabled}
theme={theme}
name={fileNameWithoutExtension}
UIOptions={{
canvasActions,
...(isVersionPreview ? { tools: { image: false } } : {}),
}}
onLinkOpen={onLinkOpen}
onLibraryChange={onLibraryChange}
langCode={lang}
libraryReturnUrl={libraryReturnUrl}
>
<Sidebar name="commentSidebar" docked={commentSidebarDocked} onDock={setCommentSidebarDocked}>
<Sidebar.Header>
{t('whiteboard', 'Comments')}
</Sidebar.Header>
<Sidebar.Tabs style={{ padding: '0.5rem' }}>
<Sidebar.Tab tab="comments">
<CommentSidebar
threads={commentThreads}
activeThreadId={activeCommentThreadId}
isReadOnly={isReadOnly}
onThreadClick={panToThread}
onDeleteThread={(threadId) => {
activeCommentThreadId === threadId && setActiveCommentThreadId(null)
deleteThread(threadId)
}}
/>
</Sidebar.Tab>
</Sidebar.Tabs>
</Sidebar>
<Sidebar name="custom">
<Sidebar.Header>
{t('whiteboard', 'Voting')}
</Sidebar.Header>
<Sidebar.Tabs style={{ padding: '0.5rem' }}>
<Sidebar.Tab tab="voting">
<VotingSidebar
votings={votings}
onVote={vote}
onEndVoting={endVoting}
onStartVoting={startVoting}
excalidrawAPI={excalidrawAPI}
isReadOnly={isReadOnly}
/>
</Sidebar.Tab>
</Sidebar.Tabs>
</Sidebar>
{!isVersionPreview && (
<MemoizedExcalidrawMenu
fileNameWithoutExtension={fileNameWithoutExtension}
recordingState={recordingState}
presentationState={presentationState}
isTimerVisible={isTimerVisible}
onToggleTimer={handleToggleTimer}
gridModeEnabled={gridModeEnabled}
onToggleGrid={() => setGridModeEnabled(!gridModeEnabled)}
/>
)}
</Excalidraw>
{!isVersionPreview && (
<RecordingOverlay
{...recordingState}
otherRecordingUsers={recordingState.otherUsers}
hasOtherRecordingUsers={recordingState.hasOtherRecordingUsers}
resetError={recordingState.resetError}
dismissSuccess={recordingState.dismissSuccess}
dismissUnavailableInfo={recordingState.dismissUnavailableInfo}
/>
)}
{!isVersionPreview && (
<PresentationOverlay
presentationState={presentationState}
/>
)}
{!isVersionPreview && isTimerVisible && (
<TimerOverlay
timer={timerState}
/>
)}
{!isVersionPreview && (
<CreatorDisplay
excalidrawAPI={excalidrawAPI}
settings={creatorDisplaySettings}
/>
)}
</div>
</div>
)
}