-
-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathCollectionsTabPane.tsx
More file actions
898 lines (846 loc) · 37.2 KB
/
Copy pathCollectionsTabPane.tsx
File metadata and controls
898 lines (846 loc) · 37.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
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
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
import { css } from "@emotion/react";
import * as React from "react";
import { get, post, postString } from "../utils/bloomApi";
import { BooksOfCollection, IBookInfo } from "./BooksOfCollection";
import { makeMenuItems, MenuItemSpec } from "./menuHelpers";
import { Transition } from "react-transition-group";
import { SplitPane } from "react-collapse-pane";
import { kPanelBackground, kDarkestBackground } from "../bloomMaterialUITheme";
import { WireUpForWinforms } from "../utils/WireUpWinform";
import { CollectionsTabBookPane } from "./collectionsTabBookPane/CollectionsTabBookPane";
import { useEffect, useMemo, useState } from "react";
import useEventListener from "@use-it/event-listener";
import { BookSelectionManager } from "./bookSelectionManager";
import ShowAfterDelay from "../react_components/showAfterDelay";
import { forceCheck as convertAnyVisibleLazyLoads } from "react-lazyload";
import { IconButton, Menu } from "@mui/material";
import GreyTriangleMenuIcon from "../react_components/icons/GreyTriangleMenuIcon";
import { TeamCollectionDialogLauncher } from "../teamCollection/TeamCollectionDialog";
import { SpreadsheetExportDialogLauncher } from "./spreadsheet/SpreadsheetExportDialog";
import { RegistrationDialogEventLauncher } from "../react_components/registration/registrationDialogLauncher";
import { H1 } from "../react_components/l10nComponents";
import { useL10n } from "../react_components/l10nHooks";
import { useSubscribeToWebSocketForEvent } from "../utils/WebSocketManager";
import { EmbeddedProgressDialog } from "../react_components/Progress/ProgressDialog";
import { useSubscribeToWebSocketForObject } from "../utils/WebSocketManager";
import CloseIcon from "@mui/icons-material/Close";
import FolderOpenOutlinedIcon from "@mui/icons-material/FolderOpenOutlined";
import { ImportIcon } from "../react_components/icons/ImportIcon";
import { kBloomBlue } from "../bloomMaterialUITheme";
import { BloomTooltip } from "../react_components/BloomToolTip";
import { Link } from "../react_components/link";
import { ForumInvitationDialogLauncher } from "../react_components/forumInvitationDialog";
import { CollectionSettingsDialog } from "../collection/CollectionSettingsDialog";
import { BooksOnBlorgProgressBar } from "../booksOnBlorg/BooksOnBlorgProgressBar";
import { SubscriptionStatus } from "./SubscriptionStatus";
import {
MakeReaderTemplateBloomPackDialog,
showMakeReaderTemplateBloomPackDialog,
} from "../react_components/makeReaderTemplateBloomPackDialog";
import { AboutDialogLauncher } from "../react_components/aboutDialog";
import { RadioChoiceDialog } from "./RadioChoiceDialog";
const kResizerSize = 10;
type CollectionInfo = {
id: string;
key?: string; // React key, defaults to id
name: string;
shouldLocalizeName: boolean;
isLink: boolean;
isRemovableFolder: boolean;
filter?: (book: IBookInfo) => boolean;
};
export const CollectionsTabPane: React.FunctionComponent = () => {
// Temporary: notify c# about clicks so WinForms menus can close.
// Remove this once menus move into the same browser UI.
React.useEffect(() => {
const notifyBrowserClicked = () => {
(window as any).chrome?.webview?.postMessage("browser-clicked");
};
window.addEventListener("click", notifyBrowserClicked);
return () => {
window.removeEventListener("click", notifyBrowserClicked);
};
}, []);
// This sort of duplicates useApiJson, but allows us to use the underlying state variable.
// Which we really need.
const [collections, setCollections] = useState<
[CollectionInfo] | undefined
>();
useEffect(() => {
get("collections/list", (c) => {
setCollections(c.data);
});
}, []);
// Setting the collectionCount to a new value causes a refresh. Even though it's
// not explicitly referenced anywhere except for being set, not having it results
// in no refreshes when collections are removed.
const [collectionCount, setCollectionCount] = useState<number>(
collections?.length ?? 0,
);
const removeSourceCollection = (id: string) => {
postString("collections/removeSourceCollection", id).then(() => {
finishDeletingCollection(id);
});
};
const [newCollection, setNewCollection] = useState<
CollectionInfo | undefined
>();
const finishAddingNewSourceCollection = (collection: CollectionInfo) => {
if (!collections) return;
const currentIndex = collections.findIndex((value) => {
return value.id && value.id === collection.id;
});
if (currentIndex >= 0) {
// Scroll the already existing collection into view.
const element = document.getElementById(sanitize(collection.id));
if (element) element.scrollIntoView();
} else {
// I have no idea how to control the scrolling of this newly added collection.
collections.push(collection);
setCollectionCount(collections.length);
}
};
const addSourceCollection = () => {
post("collections/addSourceCollection");
};
function finishDeletingCollection(id: string) {
if (!collections) return;
let newIndex = -1;
collections.filter((value, index, array) => {
if (value.id === id) {
array.splice(index, 1);
newIndex = index;
return true;
}
return false;
});
if (newIndex === collections.length) --newIndex;
if (newIndex >= 0) {
const element = document.getElementById(
sanitize(collections[newIndex].id),
);
if (element) element.scrollIntoView();
}
setCollectionCount(collections.length);
}
// Since a user will take as much time as they want to deal with the dialog,
// we can't just wait for the api call to return. Instead we get called back
// via web socket iff they select a folder and close the dialog.
useSubscribeToWebSocketForObject<{
success: boolean;
collection: CollectionInfo;
}>("collections", "addSourceCollection-results", (results) => {
if (results.success) {
setNewCollection(results.collection);
}
});
const [deletedCollection, setDeletedCollection] = useState<
CollectionInfo | undefined
>();
const removeSourceFolder = (id: string) => {
// This opens a file explorer on the given folder, giving the user
// the option of deleting it. We can't depend on waiting long enough
// so we just ignore the return from the post and listen on a socket
// for any update information.
postString("collections/removeSourceFolder", id);
};
useSubscribeToWebSocketForObject<{
success: boolean;
list: [any];
}>("collections", "updateCollectionList", (results) => {
setCollections(results.list);
});
const [draggingSplitter, setDraggingSplitter] = useState(false);
// Initially (when Bloom first starts, until we persist splitter settings) the vertical
// splitter between the editable collection and the others is set to give them equal space.
// When the user drags the splitter, we use a callback to update this, so it will be right
// if we need to use it again.
// It is passed to the vertical splitter as the "initialSizes", which is ignored except
// for the very first render of a particular SplitPane. So to get it to take effect later,
// we have to modify the key of the SplitPane, forcing React to create a whole new one.
// The only time we currently need to do this is when Bloom is restored from being
// minimized, which somehow puts the vertical splitter into a weird state where apparently
// both panes are collapsed and there is nothing to see. As far as I can tell, all other
// changes to window size are handled nicely by the SplitPane.
const [splitHeights, setSplitHeights] = useState([1, 1]);
const [generation, setGeneration] = useState(0);
useSubscribeToWebSocketForEvent("window", "restored", () => {
setGeneration((old) => old + 1);
});
const manager: BookSelectionManager = useMemo(() => {
const manager = new BookSelectionManager();
manager.initialize();
return manager;
}, []);
const [contextMousePoint, setContextMousePoint] = React.useState<
| {
mouseX: number;
mouseY: number;
}
| undefined
>();
// The .bloomSource import decision. The file(s) are chosen first (via C#); then we check (via
// C#) whether any chosen book is already in the collection and, based on that, show the user
// exactly one dialog for the whole batch. If none are present, Dialog 1 asks whether to edit
// the book(s) or make derivatives. If any are present, Dialog 2 asks whether to replace the
// existing book(s) or add the imported ones as new copies. The user never sees both.
const [showImportSourceChoiceDialog, setShowImportSourceChoiceDialog] =
useState(false);
const [showImportDuplicateDialog, setShowImportDuplicateDialog] =
useState(false);
// Whether the "Replace" duplicate choice is allowed for this batch. In a Team Collection a book
// can only be replaced if it is checked out here; when any duplicate isn't, Replace is disabled.
const [importCanReplace, setImportCanReplace] = useState(true);
const importChoiceTitle = useL10n(
"Import books",
"CollectionTab.ImportBloomSource.ChoiceTitle",
);
const importEditChoiceLabel = useL10n(
"Import for editing",
"CollectionTab.ImportBloomSource.EditChoice",
);
const importEditChoiceDescription = useL10n(
"Preserve everything.",
"CollectionTab.ImportBloomSource.EditChoiceDescription",
);
const importDerivativeChoiceLabel = useL10n(
"Import as derivatives — new books based on the originals",
"CollectionTab.ImportBloomSource.DerivativeChoice",
);
const importDerivativeChoiceDescription = useL10n(
"Use a new book ID & make room for new copyright and credits while preserving those of the original.",
"CollectionTab.ImportBloomSource.DerivativeChoiceDescription",
);
const importDuplicateMessage = useL10n(
"Some of these books are already in this collection.",
"CollectionTab.ImportBloomSource.DuplicatePrompt",
);
const importReplaceLabel = useL10n(
"Replace the existing books",
"CollectionTab.ImportBloomSource.Replace",
);
const importReplaceDescription = useL10n(
"The current copies will be overwritten.",
"CollectionTab.ImportBloomSource.ReplaceDescription",
);
const importReplaceNeedsCheckoutDescription = useL10n(
"All books must be checked out",
"CollectionTab.ImportBloomSource.ReplaceNeedsCheckout",
);
const importAddCopyLabel = useL10n(
"Add them as new copies",
"CollectionTab.ImportBloomSource.AddCopy",
);
const importAddCopyDescription = useL10n(
"The existing books stay as they are.",
"CollectionTab.ImportBloomSource.AddCopyDescription",
);
// Decide which single dialog to show after the file(s) have been chosen: Dialog 2 (replace vs.
// add-copy) if any chosen book is already in the collection, otherwise Dialog 1 (edit vs.
// derivative).
//
// Note that when a chosen book is already in the collection we deliberately do NOT offer the
// edit-vs-derivative choice: the duplicate dialog always imports in edit mode, so you can't
// make a derivative of a book that's already in your collection. We couldn't think of a
// plausible scenario where you have a book and a true derivative of it in the same collection,
// so this path isn't worth the extra complexity. Easy to reverse if that turns out to be wrong.
const chooseImportDialog = () => {
post("collections/bloomSourceImportDuplicateInfo", (r) => {
if (r.data.anyDuplicates) {
setImportCanReplace(r.data.canReplace);
setShowImportDuplicateDialog(true);
} else setShowImportSourceChoiceDialog(true);
});
};
// Dialog 1 (shown only when no chosen book is already in the collection): the user chose to
// edit the book(s) as-is or make derivatives (or cancelled). Neither path has a duplicate to
// resolve, so import immediately.
const handleImportSourceChoice = (choice?: string) => {
setShowImportSourceChoiceDialog(false);
if (!choice) return;
const mode = choice === "derivative" ? "derivative" : "edit";
post(`collections/importBloomSource?mode=${mode}`);
};
// Dialog 2 (shown only when at least one chosen book is already in the collection): the user
// chose to replace the existing book(s) or add the imported ones as new copies. That single
// choice applies to every duplicate in the batch.
const handleImportDuplicateChoice = (choice?: string) => {
setShowImportDuplicateDialog(false);
if (!choice) return;
post(`collections/importBloomSource?mode=edit&onDuplicate=${choice}`);
};
const setAdjustedContextMenuPoint = (x: number, y: number) => {
setContextMousePoint({
mouseX: x - 2,
mouseY: y - 4,
});
};
// There's no event built into the splitter that will tell us when drag is done.
// So to tell that it's over, we have a global listener for mouseup.
// useEventListener handles cleaning up the listener when this component is disposed.
// The small delay somehow prevents a problem where the drag would continue after
// mouse up. My hypothesis is that causing a re-render during mouse-up handling
// interferes with the implementation of the splitter and causes it to miss
// mouse up events, perhaps especially if outside the splitter control itself.
useEventListener("mouseup", () => {
if (draggingSplitter) {
// LazyLoad isn't smart enough to notice that the size of the parent scrolling box changed.
// We help out by telling it to check for anything that might have become visible
// because of the drag.
convertAnyVisibleLazyLoads();
}
setTimeout(() => setDraggingSplitter(false), 0);
});
useEffect(() => {
window.addEventListener("keyup", (ev) => {
if (ev.code == "F2") {
// We want to make the selected button show the renaming state.
manager.setRenaming();
}
});
}, []);
const haveNoSources = collections && collections.length === 1;
useEffect(() => {
// If we've got the list of collections and there are no source collections,
// we want to set the splitter to hide the bottom pane.
if (haveNoSources) {
setSplitHeights([1, 0]);
setGeneration((old) => old + 1);
}
}, [haveNoSources]);
if (!collections) {
return <div />;
}
const handleCollectionMenuClick = (
event: React.MouseEvent<HTMLButtonElement>,
) => {
// If there's already a Material-UI menu open somewhere (probably one of the book buttons),
// we don't want to open our own menu, and it's tricky to make it open the menu appropriate
// to the place clicked, which might not even be what the user wanted. Instead, just
// simulate a regular click on the backdrop, which will close the menu. If necessary the
// user can then right-click again.
// This is a known bug in Material-UI, fixed in version 5, so we may be able to do better
// when we switch to that. See https://github.com/mui/material-ui/issues/19145.
const menuBackdrop = (event.target as HTMLElement).closest(
".MuiPopover-root",
);
if (menuBackdrop) {
(event.target as HTMLElement).click();
return;
}
setAdjustedContextMenuPoint(event.clientX, event.clientY);
event.preventDefault();
event.stopPropagation();
};
const handleClose = () => {
setContextMousePoint(undefined);
};
const collectionMenuItemsSpecs: MenuItemSpec[] = [
{
label: "Open or Create Another Collection",
l10nId: "CollectionTab.OpenCreateCollectionMenuItem",
command: "workspace/openOrCreateCollection",
addEllipsis: true,
},
{
label: "Import .bloomSource File(s)",
l10nId: "CollectionTab.ImportBloomSource",
icon: <ImportIcon />,
onClick: () => {
handleClose();
// Choose the file(s) first; then show the one dialog that fits, based on whether
// any chosen book is already in the collection.
post("collections/chooseBloomSourceFilesToImport", (r) => {
if (r.data === true) chooseImportDialog();
});
},
addEllipsis: true,
},
{
label: "Make Bloom Pack of Shell Books",
l10nId: "CollectionTab.MakeBloomPackOfShellBooks",
command: "collections/makeShellBooksBloompack",
addEllipsis: true,
},
{
label: "Make Reader Template Bloom Pack...",
l10nId: "CollectionTab.AddMakeReaderTemplateBloomPackToolStripMenuItem",
onClick: (event: React.MouseEvent<HTMLButtonElement>) => {
showMakeReaderTemplateBloomPackDialog();
},
},
{
label: "Troubleshooting",
l10nId: "CollectionTab.ContextMenu.Troubleshooting",
submenu: [
{
label: "Do Checks of All Books",
l10nId: "CollectionTab.CollectionMenu.doChecksOfAllBooks",
command: "collections/doChecksOfAllBooks",
addEllipsis: true,
},
{
label: "Do Updates of All Books",
l10nId: "CollectionTab.CollectionMenu.doChecksAndUpdatesOfAllBooks",
command: "collections/doUpdatesOfAllBooks",
addEllipsis: true,
},
{
label: "Rescue Missing Images...",
l10nId: "CollectionTab.CollectionMenu.rescueMissingImages",
command: "collections/rescueMissingImages",
},
],
},
];
const bookInfo = manager.getSelectedBookInfo();
const collectionMenuItems = makeMenuItems(
collectionMenuItemsSpecs,
true,
bookInfo?.saveable ?? false,
bookInfo?.deletable ?? false,
handleClose,
// the collection menu commands don't actually use the ID of
// a particular book
"",
collections[0].id,
);
if (newCollection) {
finishAddingNewSourceCollection(newCollection);
setNewCollection(undefined);
}
if (deletedCollection) {
finishDeletingCollection(deletedCollection.id);
setDeletedCollection(undefined);
}
let sourcesCollections = collections.slice(1); // remove the one editable collection
if (sourcesCollections.length > 0) {
// when we're in the "download for editing" mode, there are no other collections
sourcesCollections = [
...processTemplatesCollection(sourcesCollections[0]),
...sourcesCollections.slice(1),
];
}
// Enhance: may want to sort these by local name, though probably keeping Templates
// and possibly Sample Shells at the top.
const collectionComponents = sourcesCollections.map((c) => {
return (
<BooksOfCollectionWithHeading
key={c.key ?? c.id}
name={c.name}
id={c.id}
shouldLocalizeName={c.shouldLocalizeName}
isLink={c.isLink}
isRemovableFolder={c.isRemovableFolder}
manager={manager}
onRemoveSourceCollection={removeSourceCollection}
onRemoveSourceFolder={removeSourceFolder}
filter={c.filter}
/>
);
});
const collectionsHeaderKey = "CollectionTab.BookSourceHeading";
const collectionsHeaderText = "Sources For New Books";
const lockedToOneDownloadedBook = sourcesCollections.length === 0;
return (
<div
css={css`
height: 100%;
background-color: ${kPanelBackground};
color: white;
h1 {
font-size: 20px;
margin: 0;
}
h2 {
font-size: 16px;
margin: 0;
}
.handle-bar,
.handle-bar:hover {
background-color: ${kDarkestBackground};
}
.SplitPane {
position: relative !important; // we may find this messes things up... but the "absolute" positioning default is ridiculous.
height: 100%;
.Pane.horizontal {
overflow-y: auto;
// TODO: this should only be applied to the bottom pane. As is, it pushes the top one away from the top of the screen.
margin-top: ${kResizerSize}px; // have to push down to make room for the resizer! Ughh.
}
.Pane.vertical {
}
}
`}
>
<SplitPane
split="vertical"
// This gives the two panes about the same ratio as in the Legacy view.
// Enhance: we'd like to save the user's chosen width.
initialSizes={[31, 50]}
resizerOptions={{
css: {
width: `${kResizerSize}px`,
background: `${kDarkestBackground}`,
},
hoverCss: {
width: `${kResizerSize}px`,
background: `${kDarkestBackground}`,
},
grabberSize: `${kResizerSize / 2}px`,
}}
hooks={{
onDragStarted: () => {
setDraggingSplitter(true);
},
}}
// onDragFinished={() => {
// alert("stopped dragging");
// setDraggingVSplitter(false);
// }}
>
<SplitPane
key={"gen" + generation}
split="horizontal"
// TODO: the splitter library lets us specify a height, but it doesn't apply it correctly an so the pane that follows
// does not get pushed down to make room for the thicker resizer
initialSizes={splitHeights}
resizerOptions={{
css: {
height: `${kResizerSize}px`,
background: `${kDarkestBackground}`,
},
hoverCss: {
height: `${kResizerSize}px`,
background: `${kDarkestBackground}`,
},
}}
hooks={{
onDragStarted: () => {
setDraggingSplitter(true);
},
onSaveSizes: (sizes) => {
setSplitHeights(sizes);
},
}}
>
<div
css={css`
margin: 10px;
`}
>
<SubscriptionStatus />
<BooksOnBlorgProgressBar />
<h1>
{collections[0].name}
<IconButton
css={css`
// Use && to get enough specificity to beat out .MuiButtonRoot. Alternatively, you can slap !important on inline-style them
&& {
// Triangle positioning.
// Match historical 15-16 px of padding between the text and left edge of triangle
padding-left: 15px;
// Match historical behavior that the triangle bottom is 3-4 px below the baseline of the font.
// (note that in terms of html elements, the bottom of the <h1> element is below the baseline of the text)
padding-top: 0px;
padding-bottom: 0px;
bottom: -1px; // This was experimentally determined, there's no sound theoretical justification for this particular number.
}
`}
onClick={handleCollectionMenuClick}
size="large"
disableRipple
>
<GreyTriangleMenuIcon
css={css`
// Use && to get enough specificity to beat out MaterialUI-generated rules
&& {
width: 10px;
height: unset; // Lets it auto-proportion the height
}
`}
/>
</IconButton>
</h1>
<BooksOfCollection
collectionId={collections[0].id}
isEditableCollection={true}
manager={manager}
lazyLoadCollection={false}
lockedToOneDownloadedBook={
lockedToOneDownloadedBook
}
/>
</div>
<>
{!lockedToOneDownloadedBook && (
<Transition in={true} appear={true} timeout={2000}>
{(state) => (
<div
css={css`
margin: 10px;
`}
className={`group fade-${state}`}
>
<H1
l10nKey={collectionsHeaderKey}
css={css`
padding-bottom: 20px;
`}
>
{collectionsHeaderText}
</H1>
<ShowAfterDelay
waitBeforeShow={100} // REview: we really want to wait for an event that indicates the main collection is mostly painted
>
{collectionComponents}
</ShowAfterDelay>
<Link
l10nKey="CollectionTab.AddSourceCollection"
css={css`
text-transform: uppercase;
padding-bottom: 10px;
`}
onClick={() =>
addSourceCollection()
}
>
Show another collection...
</Link>
</div>
)}
</Transition>
)}
</>
{/* Enhance:possibly if we're NOT showing the Sources for new Books stuff,
we could have a message saying why and to pick an Enterprise subscription to fix it. */}
</SplitPane>
{/* This wrapper is used to... fix up some margin/color stuff I was having trouble with from SplitPane */}
<div
css={css`
height: 100%;
`}
>
<ShowAfterDelay
waitBeforeShow={500} // Review: we really want an event that indicates the collection panes are mostly painted.
>
<CollectionsTabBookPane
// While we're dragging the splitter, we need to overlay the iframe book preview
// so it doesn't steal the mouse events we need for dragging the splitter.
disableEventsInIframe={draggingSplitter}
/>
</ShowAfterDelay>
</div>
</SplitPane>
{contextMousePoint && (
<Menu
keepMounted={true}
open={!!contextMousePoint}
onClose={handleClose}
anchorReference="anchorPosition"
anchorPosition={{
top: contextMousePoint!.mouseY,
left: contextMousePoint!.mouseX,
}}
>
{collectionMenuItems}
</Menu>
)}
<TeamCollectionDialogLauncher />
<SpreadsheetExportDialogLauncher />
<ForumInvitationDialogLauncher />
<RegistrationDialogEventLauncher />
<AboutDialogLauncher />
<CollectionSettingsDialog />
<EmbeddedProgressDialog id="collectionTab" />
<MakeReaderTemplateBloomPackDialog />
<RadioChoiceDialog
open={showImportSourceChoiceDialog}
title={importChoiceTitle}
options={[
{
value: "edit",
label: importEditChoiceLabel,
description: importEditChoiceDescription,
},
{
value: "derivative",
label: importDerivativeChoiceLabel,
description: importDerivativeChoiceDescription,
},
]}
onClose={handleImportSourceChoice}
/>
<RadioChoiceDialog
open={showImportDuplicateDialog}
title={importChoiceTitle}
message={importDuplicateMessage}
options={[
{
value: "replace",
label: importReplaceLabel,
description: importCanReplace
? importReplaceDescription
: importReplaceNeedsCheckoutDescription,
disabled: !importCanReplace,
},
{
value: "addCopy",
label: importAddCopyLabel,
description: importAddCopyDescription,
},
]}
onClose={handleImportDuplicateChoice}
/>
</div>
);
};
const BooksOfCollectionWithHeading: React.FunctionComponent<{
name: string;
id: string;
shouldLocalizeName: boolean;
isLink: boolean;
isRemovableFolder: boolean;
manager: BookSelectionManager;
onRemoveSourceCollection: (id: string) => void;
onRemoveSourceFolder: (id: string) => void;
filter?: (book: IBookInfo) => boolean;
}> = (props) => {
// Using a null l10nId lets us not make a server call when we don't want to.
// (We can't call useL10n conditionally.)
const collectionName = useL10n(
props.name,
props.shouldLocalizeName ? `CollectionTab.${props.name}` : null,
);
return (
<div key={"frag:" + props.id} id={sanitize(props.id)}>
{props.isLink ? (
getRemovableCollectionHeaderDiv(
collectionName,
props.onRemoveSourceCollection,
props.id,
"DoNotShowCollection",
"CollectionTab.DoNotShowCollection",
"Do not show this collection here.",
<CloseIcon />,
)
) : props.isRemovableFolder ? (
getRemovableCollectionHeaderDiv(
collectionName,
props.onRemoveSourceFolder,
props.id,
"RemoveThisGroup",
"CollectionTab.RemoveThisGroup",
"To remove this group, you will need to delete the folder. Click here to view the folder on your drive.",
<FolderOpenOutlinedIcon />,
)
) : (
<h2>{collectionName}</h2>
)}
<BooksOfCollection
collectionId={props.id}
isEditableCollection={false}
manager={props.manager}
lazyLoadCollection={true}
lockedToOneDownloadedBook={false}
filter={props.filter}
/>
</div>
);
};
function getRemovableCollectionHeaderDiv(
collectionName: string,
clickFunction: (id: string) => void,
collectionId: string,
tooltipId: string,
tooltipL10nKey: string,
tooltipText: string,
icon: JSX.Element,
): JSX.Element {
// Make the book list semi-transparent when hovering over the
// "remove collection" button. This function is called with true
// for onMouseEnter and false for onMouseLeave.
function setBooklistTransparency(
ev: React.MouseEvent<HTMLDivElement, MouseEvent>,
makeTransparent: boolean,
): void {
let div: HTMLElement | null = ev.target as HTMLElement;
if (div) {
while (
(div = div.parentElement) &&
!div.classList.contains("removable-collection-header")
);
const dest = div?.nextElementSibling;
if (dest) {
if (makeTransparent) dest.classList.add("largely-transparent");
else dest.classList.remove("largely-transparent");
}
}
}
return (
<div
className="removable-collection-header"
css={css`
display: flex;
flex-flow: row;
&:hover div {
display: block;
cursor: pointer;
}
`}
>
<h2>{collectionName}</h2>
<div
css={css`
margin-left: 30px;
margin-bottom: -10px; // prevent wiggle when appearing/disappearing
display: none;
color: ${kBloomBlue};
background-color: transparent;
`}
onClick={() => clickFunction(collectionId)}
onMouseEnter={(ev) => setBooklistTransparency(ev, true)}
onMouseLeave={(ev) => setBooklistTransparency(ev, false)}
>
<BloomTooltip
id={tooltipId}
placement="right"
tip={{ english: tooltipText, l10nKey: tooltipL10nKey }}
>
{icon}
</BloomTooltip>
</div>
</div>
);
}
function sanitize(id: string): string {
return encodeURIComponent(id).replace(/./g, "_");
}
// Divide the one "templates/" collection into separate collections and sort them
// TODO: sort them according to some criteria TBD
function processTemplatesCollection(
templatesCollection: CollectionInfo,
): CollectionInfo[] {
const simpleTemplates = {
...templatesCollection,
key: templatesCollection.id + "/Simple",
};
// this "f" garbage is because TS refused to see that simpleTemplates.filter is never undefined
const f = (book: IBookInfo) => {
return (
book.folderName.startsWith("Basic Book") ||
book.folderName.startsWith("eBook")
);
};
simpleTemplates.filter = f;
const specializedTemplates = {
...templatesCollection,
key: templatesCollection.id + "/Specialized",
name: "Specialized Templates",
};
specializedTemplates.filter = (book: IBookInfo) => {
return !f(book);
};
return [simpleTemplates, specializedTemplates];
}
WireUpForWinforms(CollectionsTabPane, kPanelBackground);