-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathdocument.page.tsx
More file actions
638 lines (600 loc) · 19.3 KB
/
document.page.tsx
File metadata and controls
638 lines (600 loc) · 19.3 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
630
631
632
633
634
635
636
637
638
import { DialogContent, DialogOverlay } from "@reach/dialog"
import "@reach/dialog/styles.css"
import React, { useEffect, useState } from "react"
import { isMobile } from "react-device-detect"
import { Helmet } from "react-helmet"
import {
MdOutlineBookmarkAdd,
MdOutlineBookmarkRemove,
MdSettings,
} from "react-icons/md/index"
import { RiArrowUpCircleFill } from "react-icons/ri/index"
import {
Dialog,
DialogBackdrop,
Tab,
TabList,
TabPanel,
useDialogState,
} from "reakit"
import { navigate } from "vite-plugin-ssr/client/router"
import { UserRole, useUser, useUserRole } from "src/auth"
import { useUserId } from "src/auth"
import { CommentStateProvider } from "src/comment-state-context"
import { AudioPlayer, Breadcrumbs, Button, Link } from "src/components"
import { IconTextButton } from "src/components/button"
import { CommentValueProvider } from "src/components/edit-comment-feature"
import { DocumentAudioWithCurate } from "src/components/edit-word-audio/editor"
import { UploadAudioPanel } from "src/components/edit-word-audio/upload"
import { RecordDocumentAudioPanel } from "src/components/record-document-audio-panel"
import { useMediaQuery } from "src/custom-hooks"
import { FormProvider as FormProviderDoc } from "src/edit-doc-data-form-context"
import {
FormProvider as FormProviderParagraph,
useForm as useParagraphForm,
} from "src/edit-paragraph-form-context"
import { EditWordCheckProvider } from "src/edit-word-check-context"
import { FormProvider, useForm } from "src/edit-word-form-context"
import * as Dailp from "src/graphql/dailp"
import Layout from "src/layout"
import { drawerBg } from "src/menu.css"
import { MorphemeDetails } from "src/morpheme"
import { DocumentInfo } from "src/pages/documents/document-info"
import { PanelDetails, PanelLayout, PanelSegment } from "src/panel-layout"
import { usePreferences } from "src/preferences-context"
import { useLocation } from "src/renderer/PageShell"
import { chapterRoute, collectionWordPath } from "src/routes"
import { useScrollableTabState } from "src/scrollable-tabs"
import { AnnotatedForm, DocumentPage } from "src/segment"
import { mediaQueries } from "src/style/constants"
import { BasicMorphemeSegment, LevelOfDetail } from "src/types"
import PageImages from "../../page-image"
import * as css from "./document.css"
import { EditingProvider } from "./editing-context"
enum Tabs {
ANNOTATION = "annotation-tab",
IMAGES = "source-image-tab",
INFO = "info-tab",
}
export type DocumentContents = NonNullable<
Dailp.DocumentContentsQuery["document"]
>
/** A full annotated document, including all metadata and the translation(s) */
const AnnotatedDocumentPage = (props: { id: string }) => {
const [{ data }] = Dailp.useAnnotatedDocumentQuery({
variables: { slug: props.id },
})
const wordIndex = useLocation().hash
const index = wordIndex?.replace("w", "")
const doc = data?.document
if (!doc) {
return null
}
useEffect(() => {
redirectUrl(index)
}, [props.id])
// Redirects this document to the corresponding collection chapter containing document.
function redirectUrl(index: string | undefined) {
if (doc?.chapters?.length === 1) {
const chapter = doc.chapters[0]
const collectionSlug = chapter?.path[0]
const chapterSlug = chapter?.path[chapter.path.length - 1]
wordIndex
? navigate(
collectionWordPath(collectionSlug!, chapterSlug!, parseInt(index!))
)
: navigate(chapterRoute(collectionSlug!, chapterSlug!))
}
}
return (
<Layout>
<Helmet title={doc?.title} />
<main className={css.annotatedDocument}>
<DocumentTitleHeader doc={doc} />
<TabSet doc={doc} />
</main>
</Layout>
)
}
export const Page = AnnotatedDocumentPage
export const TabSet = ({ doc }: { doc: Dailp.DocumentFieldsFragment }) => {
const [isScrollVisible, setIsScrollVisible] = useState(1)
const handleScroll = () => {
if (document.documentElement.scrollHeight > 3000) {
setIsScrollVisible(window.scrollY > 2000 ? 2 : 1)
} else {
setIsScrollVisible(0)
}
}
// Add the scroll event listener when the component is mounted.
// window (and document) cannot seem to be accessed on its own so we need to use this method instead.
useEffect(() => {
window.addEventListener("scroll", handleScroll)
// Remove the scroll event listener on component unmount
return () => {
window.removeEventListener("scroll", handleScroll)
}
}, [])
const tabs = useScrollableTabState({ selectedId: Tabs.ANNOTATION })
// const [{ data }] = Dailp.useDocumentDetailsQuery({
// variables: { slug: doc.slug! },
// })
// const docData = data?.document
// if (!docData) {
// return null
// }
let scrollTopClass = null
switch (isScrollVisible) {
case 0:
scrollTopClass = css.noScrollTop
break
case 1:
scrollTopClass = css.hideScrollTop
break
case 2:
scrollTopClass = css.showScrollTop
break
default:
scrollTopClass = css.noScrollTop
}
return (
<>
<div className={css.wideAndTop}>
<TabList
{...tabs}
id="document-tabs-header"
className={css.docTabs}
aria-label="Document View Types"
>
<Tab {...tabs} id={Tabs.ANNOTATION} className={css.docTab}>
Translation
</Tab>
<Tab {...tabs} id={Tabs.IMAGES} className={css.docTab}>
Original Text
</Tab>
<Tab {...tabs} id={Tabs.INFO} className={css.docTab}>
Document Info
</Tab>
</TabList>
</div>
<Button
id="scroll-top"
className={scrollTopClass}
onClick={() => window.scrollTo({ top: 0, behavior: "smooth" })}
>
<RiArrowUpCircleFill size={45} />
{!isMobile ? <div>Scroll to Top</div> : null}
</Button>
<TabPanel
{...tabs}
className={css.docTabPanel}
id={`${Tabs.ANNOTATION}-panel`}
tabId={Tabs.ANNOTATION}
>
<EditWordCheckProvider>
<TranslationTab doc={doc} />
</EditWordCheckProvider>
</TabPanel>
<TabPanel
{...tabs}
className={css.imageTabPanel}
id={`${Tabs.IMAGES}-panel`}
tabId={Tabs.IMAGES}
>
{doc.translatedPages ? (
<PageImages
pageImages={{
urls:
doc.translatedPages
?.filter((p) => !!p.image)
.map((p) => p.image!.url) ?? [],
}}
document={doc}
/>
) : null}
</TabPanel>
<TabPanel
{...tabs}
className={css.imageTabPanel}
id={`${Tabs.INFO}-panel`}
tabId={Tabs.INFO}
>
{/* Document Info Component */}
{/* Make sure form provider is around the component */}
<FormProviderDoc>
<EditingProvider>
<DocumentInfo doc={doc} />
</EditingProvider>
</FormProviderDoc>
</TabPanel>
</>
)
}
export const TranslationTab = ({
doc,
}: {
doc: Dailp.DocumentFieldsFragment
}) => {
const [selectedMorpheme, setMorpheme] = useState<BasicMorphemeSegment | null>(
null
)
useEffect(() => {
selectAndShowContent(null)
}, [doc.id])
const [dialogOpen, setDialogOpen] = useState(false)
const closeDialog = () => setDialogOpen(false)
const openDetails = (morpheme: BasicMorphemeSegment) => {
setMorpheme(morpheme)
setDialogOpen(true)
}
const dialog = useDialogState({ animated: true })
const [selectedSegment, setSelectedSegment] = useState<PanelSegment | null>(
null
)
const selectAndShowContent = (content: PanelSegment | null) => {
setSelectedSegment(content)
if (content) {
dialog.show()
} else {
dialog.hide()
}
}
// When the mobile version of the word panel is closed, remove any segment selection.
useEffect(() => {
if (!dialog.visible) {
selectAndShowContent(null)
}
}, [dialog.visible])
// This can now be either a word or paragraph.
let panelInfo = {
currContents: selectedSegment,
setCurrContents: selectAndShowContent,
}
const { levelOfDetail, cherokeeRepresentation } = usePreferences()
const isDesktop = useMediaQuery(mediaQueries.medium)
return (
<FormProvider>
<FormProviderParagraph>
<DialogOverlay
className={css.morphemeDialogBackdrop}
isOpen={dialogOpen}
onDismiss={closeDialog}
>
<DialogContent
className={css.unpaddedMorphemeDialog}
aria-label="Segment Details"
>
{selectedMorpheme ? (
<MorphemeDetails
documentId={doc.id}
segment={selectedMorpheme}
hideDialog={closeDialog}
cherokeeRepresentation={cherokeeRepresentation}
/>
) : null}
</DialogContent>
</DialogOverlay>
{!isDesktop && (
<DialogBackdrop {...dialog} className={drawerBg}>
<Dialog
{...dialog}
as="nav"
className={css.mobileWordPanel}
aria-label="Word Panel Drawer"
preventBodyScroll={true}
>
<CommentStateProvider>
<CommentValueProvider>
<PanelLayout
segment={panelInfo.currContents}
setContent={panelInfo.setCurrContents}
/>
</CommentValueProvider>
</CommentStateProvider>
</Dialog>
</DialogBackdrop>
)}
<div className={css.contentContainer}>
<article className={css.annotationContents}>
<p className={css.topMargin}>
Use the{" "}
<span>
<MdSettings size={32} style={{ verticalAlign: "middle" }} />{" "}
Settings
</span>{" "}
button at the top of the page to change how documents are
translated.
</p>
<DocumentContents
{...{
levelOfDetail,
doc,
openDetails,
cherokeeRepresentation,
wordPanelDetails: panelInfo,
}}
/>
</article>
{selectedSegment && (
<div className={css.contentSection2}>
<CommentStateProvider>
<CommentValueProvider>
<PanelLayout
segment={panelInfo.currContents}
setContent={panelInfo.setCurrContents}
/>
</CommentValueProvider>
</CommentStateProvider>
</div>
)}
</div>
</FormProviderParagraph>
</FormProvider>
)
}
const DocumentContents = ({
levelOfDetail,
doc,
openDetails,
cherokeeRepresentation,
wordPanelDetails,
}: {
doc: Dailp.DocumentFieldsFragment
levelOfDetail: LevelOfDetail
cherokeeRepresentation: Dailp.CherokeeOrthography
openDetails: (morpheme: any) => void
wordPanelDetails: PanelDetails
}) => {
const [result, rerunQuery] = Dailp.useDocumentContentsQuery({
variables: {
slug: doc.slug,
isReference: doc.isReference,
morphemeSystem: cherokeeRepresentation,
},
})
const docContents = result.data?.document
const { form, isEditing } = useForm()
const { paragraphForm, isEditingParagraph } = useParagraphForm()
useEffect(() => {
// If the form has been submitted, update the panel's current contents to be the currently selected word
if (form.submitting) {
// Update the form's current word
// wordPanelDetails.setCurrContents(form.values.word)
console.log("[charlie] Not rerunning query :)")
// Query of document contents is rerun to ensure frontend and backend are in sync
// rerunQuery({ requestPolicy: "network-only" })
} else {
// If the form was not submitted, make sure to reset the current word of the form to its unmodified state.
form.update("word", wordPanelDetails.currContents)
}
if (paragraphForm.submitting) {
wordPanelDetails.setCurrContents(paragraphForm.values.paragraph)
console.log("[charlie] Not rerunning query :)")
// Query of document contents is rerun to ensure frontend and backend are in sync
rerunQuery({ requestPolicy: "network-only" })
} else {
paragraphForm.update("paragraph", wordPanelDetails.currContents)
}
}, [isEditing, isEditingParagraph])
if (!docContents) {
return <>Loading...</>
}
return (
<>
{docContents.translatedPages?.map((seg, i) => (
<DocumentPage
key={i}
segment={seg}
onOpenDetails={openDetails}
levelOfDetail={levelOfDetail}
cherokeeRepresentation={cherokeeRepresentation}
pageImages={
doc.translatedPages
?.filter((p) => !!p.image)
.map((p) => p.image!.url) ?? []
}
wordPanelDetails={wordPanelDetails}
/>
))}
{docContents.forms?.map((form, i) => (
<AnnotatedForm
key={i}
segment={form}
onOpenDetails={openDetails}
levelOfDetail={levelOfDetail}
cherokeeRepresentation={cherokeeRepresentation}
pageImages={[]}
wordPanelDetails={wordPanelDetails}
/>
))}
</>
)
}
export const DocumentTitleHeader = (p: {
rootTitle?: string
rootPath?: string
breadcrumbs?: readonly Pick<
Dailp.CollectionChapter["breadcrumbs"][0],
"name" | "slug"
>[]
doc: Dailp.DocumentFieldsFragment
}) => {
const { user } = useUser()
const userId = useUserId()
const role = useUserRole()
return (
<header className={css.docHeader}>
{p.breadcrumbs && (
<Breadcrumbs aria-label="Breadcrumbs">
{p.breadcrumbs.map((crumb) => (
<Link href={`${p.rootPath}/${crumb.slug}`} key={crumb.slug}>
{crumb.name}
</Link>
))}
</Breadcrumbs>
)}
<h1 className={css.docTitle}>
{p.doc.title}
{p.doc.date && ` (${p.doc.date.year})`}{" "}
</h1>
<div className={css.bottomPadded}>
{user ? (
<BookmarkButton
documentId={p.doc.id}
isBookmarked={p.doc.bookmarkedOn !== null}
/>
) : (
<></>
)}
{p.doc.editedAudio.length === 0 && !isMobile && (
<div id="no-audio-message">
<strong>No Audio Available</strong>
</div>
)}
<div className={css.alignRight}>
{!isMobile ? (
<Button onClick={() => window.print()}>Print</Button>
) : null}
</div>
</div>
<div id="audio-and-recording-container">
<div>
{/* only show document audio to non-editors , editors can see which ones are shown from checkmark*/}
{p.doc.editedAudio.length > 0 && role !== UserRole.Editor && (
<>
<h3>Document Audio:</h3>
{p.doc.editedAudio.map((audio, index) => (
<div
id={`document-audio-player-${index}`}
className={css.audioContainer}
key={index}
>
<AudioPlayer
contributor={audio.recordedBy?.displayName}
recordedAt={
audio.recordedAt?.formattedDate
? new Date(audio.recordedAt.formattedDate)
: undefined
}
style={{ flex: 1 }}
audioUrl={audio.resourceUrl}
showProgress
/>
{!isMobile && (
<div>
<a href={audio.resourceUrl}>
<Button>Download Audio</Button>
</a>
</div>
)}
</div>
))}
</>
)}
{role === UserRole.Contributor && (
<>
<h3>User-contributed Audio:</h3>
{p.doc.userContributedAudio.map(
(audio, index) =>
audio.recordedBy?.id === userId && (
<div key={index}>
<AudioPlayer
contributor={"you"}
recordedAt={
audio.recordedAt?.formattedDate
? new Date(audio.recordedAt.formattedDate)
: undefined
}
audioUrl={audio.resourceUrl}
showProgress
/>
</div>
)
)}
</>
)}
{role === UserRole.Editor && (
<>
<h3>User-contributed Audio:</h3>
{p.doc.userContributedAudio.map((audio, index) => (
<div
id={`user-contributed-document-audio-player-${index}`}
className={css.documentAudioContainer}
key={index}
>
{role === UserRole.Editor && (
<>
<DocumentAudioWithCurate
contributor={
audio.recordedBy?.displayName ?? "Unknown Contributor"
}
recordedAt={
audio.recordedAt?.formattedDate
? new Date(audio.recordedAt.formattedDate)
: undefined
}
documentId={p.doc.id}
audio={audio}
/>
{!isMobile && (
<div>
<a href={audio.resourceUrl}>
<Button>Download Audio</Button>
</a>
</div>
)}
</>
)}
</div>
))}
</>
)}
{(role === UserRole.Editor || role === UserRole.Contributor) && (
<>
<RecordDocumentAudioPanel document={p.doc} />
<UploadAudioPanel uploadTo={p.doc}></UploadAudioPanel>
</>
)}
</div>
</div>
</header>
)
}
/** Button that allows users to bookmark a document */
export const BookmarkButton = (props: {
documentId: String
isBookmarked: boolean
}) => {
const [addBookmarkMutationResult, addBookmarkMutation] =
Dailp.useAddBookmarkMutation()
const [removeBookmarkMutationResult, removeBookmarkMutation] =
Dailp.useRemoveBookmarkMutation()
return (
<>
{props.isBookmarked ? (
// Displays a "Cancel" button and "Save" button in editing mode.
<>
<IconTextButton
icon={<MdOutlineBookmarkRemove />}
className={css.BookmarkButton}
onClick={() => {
removeBookmarkMutation({ documentId: props.documentId })
}}
>
Un-Bookmark
</IconTextButton>
</>
) : (
<IconTextButton
icon={<MdOutlineBookmarkAdd />}
className={css.BookmarkButton}
onClick={() => {
addBookmarkMutation({ documentId: props.documentId })
}}
>
Bookmark
</IconTextButton>
)}
</>
)
}