-
Notifications
You must be signed in to change notification settings - Fork 53
/
CurateBox.tsx
1163 lines (1121 loc) · 45.3 KB
/
CurateBox.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
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
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { Tag } from '@database/entity/Tag';
import { TagCategory } from '@database/entity/TagCategory';
import { BackIn, LaunchCurationData, TagByIdData, TagByIdResponse, TagGetOrCreateData, TagGetOrCreateResponse, TagSuggestion, TagSuggestionsData, TagSuggestionsResponse } from '@shared/back/types';
import { htdocsPath } from '@shared/constants';
import { convertEditToCurationMetaFile } from '@shared/curate/metaToMeta';
import { CurationIndex, EditCuration, EditCurationMeta, IndexedContent } from '@shared/curate/types';
import { getContentFolderByKey, getCurationFolder, indexContentFolder } from '@shared/curate/util';
import { GamePropSuggestions } from '@shared/interfaces';
import { LangContainer } from '@shared/lang';
import { deepCopy, fixSlashes, sizeToString } from '@shared/Util';
import { Coerce } from '@shared/utils/Coerce';
import { remote } from 'electron';
import * as fs from 'fs-extra';
import { add } from 'node-7z';
import * as path from 'path';
import * as React from 'react';
import { useCallback, useEffect, useMemo, useState } from 'react';
import * as YAML from 'yaml';
import { ProgressData } from '../containers/withProgress';
import { CurationAction } from '../context/CurationContext';
import { newProgress, ProgressContext, ProgressDispatch } from '../context/ProgressContext';
import { curationLog } from '../curate/util';
import { toForcedURL } from '../Util';
import { LangContext } from '../util/lang';
import { pathTo7z } from '../util/SevenZip';
import { CheckBox } from './CheckBox';
import { ConfirmElement, ConfirmElementArgs } from './ConfirmElement';
import { CurateBoxAddApp } from './CurateBoxAddApp';
import { CurateBoxRow } from './CurateBoxRow';
import { CurateBoxWarnings, CurationWarnings, getWarningCount } from './CurateBoxWarnings';
import { DropdownInputField } from './DropdownInputField';
import { GameImageSplit } from './GameImageSplit';
import { InputField } from './InputField';
import { AutoProgressComponent } from './ProgressComponents';
import { SimpleButton } from './SimpleButton';
import { TagInputField } from './TagInputField';
const { strToBool } = Coerce;
type CurateBoxProps = {
/** Meta data of the curation to display. */
curation?: EditCuration;
/** Dispatcher for the curate page state reducer. */
dispatch: React.Dispatch<CurationAction>;
/** Import a curation. */
importCuration: (curation: EditCuration, log?: boolean, date?: Date, progress?: ProgressData) => Promise<void>;
/** Suggestions for the drop-down input fields. */
suggestions?: Partial<GamePropSuggestions> | undefined;
/** Libraries to pick in the drop-down input field. */
libraryOptions: JSX.Element[];
libraries: string[];
tagCategories: TagCategory[];
mad4fpEnabled: boolean;
}
/** A box that displays and lets the user edit a curation. */
export function CurateBox(props: CurateBoxProps) {
// Localized strings
const strings = React.useContext(LangContext);
const [progressState, progressDispatch] = React.useContext(ProgressContext.context);
const [tagInputText, setTagInputText] = React.useState('');
const [tagSuggestions, setTagSuggestions] = React.useState<TagSuggestion[]>([]);
// Content file collisions
const [contentCollisions, setContentCollisions] = useState<ContentCollision[] | undefined>(undefined);
// Check for content file collisions
useEffect(() => {
if (props.curation) {
let isAborted = false;
// Check if there are any content collisions
checkCollisions(props.curation.content)
.then((collisions) => {
if (!isAborted) { setContentCollisions(collisions); }
})
.catch(console.error);
// Ignore the result of the check if the content has changed
return () => { isAborted = true; };
}
}, [props.curation && props.curation.content]);
// Tag Input Field funcs
const onCurrentTagChange = useCallback((event: React.ChangeEvent<InputElement>) => {
const newTag = event.currentTarget.value;
let newSuggestions: TagSuggestion[] = tagSuggestions;
if (newTag !== '') {
// Delayed set
window.Shared.back.send<TagSuggestionsResponse, TagSuggestionsData>(BackIn.GET_TAG_SUGGESTIONS, newTag, (res) => {
if (res.data) {
setTagSuggestions(res.data);
}
});
} else {
newSuggestions = [];
}
setTagInputText(newTag);
setTagSuggestions(newSuggestions);
}, [tagSuggestions]);
const onAddTagSuggestion = useCallback((suggestion: TagSuggestion) => {
if (suggestion.tag.id) {
window.Shared.back.send<TagByIdResponse, TagByIdData>(BackIn.GET_TAG_BY_ID, suggestion.tag.id, (res) => {
const tag = res.data;
if (tag) {
const curation = props.curation;
const oldTags = curation ? (curation.meta.tags || []) : [];
if (curation && oldTags.findIndex(t => t.id == tag.id) == -1) {
props.dispatch({
type: 'edit-curation-meta',
payload: {
key: curation.key,
property: 'tags',
value: [...oldTags, tag]
}
});
}
}
});
}
// Clear out suggestions box
setTagSuggestions([]);
setTagInputText('');
}, [props.curation]);
const onAddTagByString = useCallback((text: string): void => {
if (text !== '') {
window.Shared.back.send<TagGetOrCreateResponse, TagGetOrCreateData>(BackIn.GET_OR_CREATE_TAG, { tag: text }, (res) => {
const tag = res.data;
if (tag) {
const curation = props.curation;
if (curation && curation.meta.tags && curation.meta.tags.findIndex(t => t.id == tag.id) == -1) {
props.dispatch({
type: 'edit-curation-meta',
payload: {
key: curation.key,
property: 'tags',
value: [...curation.meta.tags, tag]
}
});
}
}
});
}
// Clear out suggestions box
setTagSuggestions([]);
setTagInputText('');
}, [props.curation]);
const onRemoveTag = useCallback((tag: Tag, index: number): void => {
const curation = props.curation;
if (curation) {
const tags = curation.meta.tags || [];
const tagIndex = tags.findIndex(t => t.id == tag.id);
if (tagIndex !== -1) {
const newTags = deepCopy(tags);
newTags.splice(tagIndex, 1);
props.dispatch({
type: 'edit-curation-meta',
payload: {
key: curation.key,
property: 'tags',
value: newTags
}
});
}
}
}, [props.curation]);
// Callbacks for the fields (onChange)
const key = props.curation ? props.curation.key : undefined;
const onTitleChange = useOnInputChange('title', key, props.dispatch);
const onAlternateTitlesChange = useOnInputChange('alternateTitles', key, props.dispatch);
const onSeriesChange = useOnInputChange('series', key, props.dispatch);
const onDeveloperChange = useOnInputChange('developer', key, props.dispatch);
const onPublisherChange = useOnInputChange('publisher', key, props.dispatch);
const onPlayModeChange = useOnInputChange('playMode', key, props.dispatch);
const onStatusChange = useOnInputChange('status', key, props.dispatch);
const onVersionChange = useOnInputChange('version', key, props.dispatch);
const onReleaseDateChange = useOnInputChange('releaseDate', key, props.dispatch);
const onLanguageChange = useOnInputChange('language', key, props.dispatch);
const onSourceChange = useOnInputChange('source', key, props.dispatch);
const onPlatformChange = useOnInputChange('platform', key, props.dispatch);
const onApplicationPathChange = useOnInputChange('applicationPath', key, props.dispatch);
const onLaunchCommandChange = useOnInputChange('launchCommand', key, props.dispatch);
const onLibraryChange = useOnInputChange('library', key, props.dispatch);
const onNotesChange = useOnInputChange('notes', key, props.dispatch);
const onOriginalDescriptionChange = useOnInputChange('originalDescription', key, props.dispatch);
const onCurationNotesChange = useOnInputChange('curationNotes', key, props.dispatch);
const onExtremeChange = useOnCheckboxToggle('extreme', key, props.dispatch);
// Callbacks for the fields (onItemSelect)
const onPlayModeSelect = useCallback(transformOnItemSelect(onPlayModeChange), [onPlayModeChange]);
const onStatusSelect = useCallback(transformOnItemSelect(onStatusChange), [onStatusChange]);
const onPlatformItemSelect = useCallback(transformOnItemSelect(onPlatformChange), [onPlatformChange]);
const onApplicationPathItemSelect = useCallback(transformOnItemSelect(onApplicationPathChange), [onPlatformChange]);
// Callback for the fields (onInputKeyDown)
const onInputKeyDown = useCallback((event: React.KeyboardEvent<InputElement>) => {
// @TODO Add keyboard shortcuts for things like importing and removing the curation.
// ...
}, []);
// Callback for when the import button is clicked
const onImportClick = useCallback(async () => {
const { curation } = props;
if (curation) {
// Lock the curation (so it can't be edited while importing)
props.dispatch({
type: 'change-curation-lock',
payload: {
key: curation.key,
lock: true,
},
});
// Check for warnings before importing
const warnings = getCurationWarnings(curation, props.suggestions, props.libraries, strings.curate);
const warningCount = getWarningCount(warnings);
if (warningCount > 0) {
// Prompt user
const res = remote.dialog.showMessageBoxSync({
title: 'Import Warnings',
message: 'There are Warnings present on this Curation.\n\nDo you still wish to import?',
buttons: ['Yes', 'No']
});
if (res === 1) {
// No
props.dispatch({
type: 'change-curation-lock',
payload: {
key: curation.key,
lock: false,
},
});
return;
}
}
// Set status text
const statusProgress = newProgress(curation.key, progressDispatch);
ProgressDispatch.setText(statusProgress, 'Importing Curation...');
ProgressDispatch.setUsePercentDone(statusProgress, false);
// Import the curation
props.importCuration(curation)
.then(() => {
curationLog(`Curation successfully imported! (title: ${curation.meta.title} id: ${curation.key})`);
// Remove the curation
props.dispatch({
type: 'remove-curation',
payload: { key: curation.key }
});
})
.catch(async (error) => {
// Log error
curationLog(`Curation failed to import! (title: ${curation.meta.title} id: ${curation.key}) - ` + error.message);
console.error(error);
// Unlock the curation
props.dispatch({
type: 'change-curation-lock',
payload: {
key: curation.key,
lock: false,
},
});
// Failed or cancelled, reindex content
const content = await indexContentFolder(getContentFolderByKey2(curation.key), curationLog);
props.dispatch({
type: 'set-curation-content',
payload: {
key: curation.key,
content: content
}
});
})
.finally(() => {
ProgressDispatch.finished(statusProgress);
});
}
}, [props.dispatch, props.curation, props.importCuration]);
// Callback for testing a curation works
const doRun = useCallback(async (mad4fp: boolean) => {
if (props.curation) {
// Lock the curation while copying files
props.dispatch({
type: 'change-curation-lock',
payload: {
key: props.curation.key,
lock: true,
},
});
const statusProgress = newProgress(props.curation.key, progressDispatch);
ProgressDispatch.setText(statusProgress, 'Launching Curation...');
ProgressDispatch.setUsePercentDone(statusProgress, false);
await window.Shared.back.sendP<any, LaunchCurationData>(BackIn.LAUNCH_CURATION, {
key: props.curation.key,
meta: props.curation.meta,
addApps: props.curation.addApps.map(addApp => addApp.meta),
mad4fp: mad4fp
});
ProgressDispatch.finished(statusProgress);
// Unlock the curation
props.dispatch({
type: 'change-curation-lock',
payload: {
key: props.curation.key,
lock: false,
},
});
}
}, [props.dispatch, props.curation, strings.dialog]);
const onRunWithMAD4FP = useCallback(() => {
doRun(true);
}, [doRun]);
const onRun = useCallback(() => {
doRun(false);
}, [doRun]);
// Callback for when the index content button is clicked
const onIndexContent = useCallback(async () => {
if (props.curation) {
const content = await indexContentFolder(getContentFolderByKey2(props.curation.key), curationLog);
props.dispatch({
type: 'set-curation-content',
payload: {
key: props.curation.key,
content: content
}
});
}
}, [props.dispatch, props.curation && props.curation.key]);
// Callback for when the open folder button is clicked
const onOpenFolder = useCallback(() => {
if (props.curation) {
remote.shell.openItem(getCurationFolder2(props.curation));
}
}, [props.curation && props.curation.key]);
// Callback for when the remove button is clicked
const onRemoveClick = useCallback(() => {
if (props.curation) {
props.dispatch({
type: 'remove-curation',
payload: { key: props.curation.key }
});
}
}, [props.dispatch, props.curation && props.curation.key]);
// Callback for when the new additional application button is clicked
const onNewAddApp = useCallback(() => {
if (props.curation) {
props.dispatch({
type: 'new-addapp',
payload: {
key: props.curation.key,
type: 'normal'
}
});
}
}, [props.dispatch, props.curation && props.curation.key]);
// Callback for when adding an Extras add app
const onAddExtras = useCallback(() => {
if (props.curation) {
props.dispatch({
type: 'new-addapp',
payload: {
key: props.curation.key,
type: 'extras'
}
});
}
}, [props.dispatch, props.curation && props.curation.key]);
// Callback for when adding a Message add app
const onAddMessage = useCallback(() => {
if (props.curation) {
props.dispatch({
type: 'new-addapp',
payload: {
key: props.curation.key,
type: 'message'
}
});
}
}, [props.dispatch, props.curation && props.curation.key]);
// Callback for when the export button is clicked
const onExportClick = useCallback(async () => {
if (props.curation) {
const curation = props.curation;
props.dispatch({
type: 'change-curation-lock',
payload: {
key: curation.key,
lock: true,
},
});
const warnings = getCurationWarnings(curation, props.suggestions, props.libraries, strings.curate);
const warningCount = getWarningCount(warnings);
if (warningCount > 0) {
// Prompt user
const res = remote.dialog.showMessageBoxSync({
title: 'Export Warnings',
message: 'There are Warnings present on this Curation.\n\nDo you still wish to export?',
buttons: ['Yes', 'No']
});
if (res === 1) {
// No
props.dispatch({
type: 'change-curation-lock',
payload: {
key: curation.key,
lock: false,
},
});
return;
}
}
// Choose where to save the file
const defaultPath = path.join(window.Shared.config.fullFlashpointPath, 'Curations', '_Exports');
await fs.ensureDir(defaultPath);
const filePath = remote.dialog.showSaveDialogSync({
title: strings.dialog.selectFileToExportMeta,
defaultPath: defaultPath,
filters: [{
name: 'Curation archive',
extensions: ['7z'],
}]
});
if (filePath) {
await fs.ensureDir(path.dirname(filePath));
// Check if zip path already exists
await fs.access(filePath, fs.constants.F_OK)
.then(() => {
// Remove old zip - 'Add' will expand zip if it exists
return fs.unlink(filePath);
})
.catch((error) => { /* No file is okay, ignore error */ });
// Save working meta
const metaPath = path.join(getCurationFolder2(curation), 'meta.yaml');
const meta = YAML.stringify(convertEditToCurationMetaFile(curation.meta, props.tagCategories, curation.addApps));
const statusProgress = newProgress(props.curation.key, progressDispatch);
ProgressDispatch.setText(statusProgress, 'Exporting Curation...');
ProgressDispatch.setUsePercentDone(statusProgress, false);
await fs.writeFile(metaPath, meta)
.then(() => {
// Zip it all up
return new Promise<void>((resolve) => {
return add(filePath, getCurationFolder2(curation), { recursive: true, $bin: pathTo7z })
.on('end', () => { resolve(); })
.on('error', (error) => {
curationLog(error.message);
resolve();
});
});
})
.finally(() => {
ProgressDispatch.finished(statusProgress);
});
}
const msg = `Successfully Exported ${curation.meta.title} to ${filePath}`;
console.log(msg);
curationLog(msg);
props.dispatch({
type: 'change-curation-lock',
payload: {
key: curation.key,
lock: false,
},
});
}
}, [props.curation, props.tagCategories]);
// Image callbacks
const onAddThumbnailClick = useAddImageCallback('logo.png', strings, props.curation);
const onAddScreenshotClick = useAddImageCallback('ss.png', strings, props.curation);
const onRemoveThumbnailClick = useRemoveImageCallback('logo.png', props.curation);
const onRemoveScreenshotClick = useRemoveImageCallback('ss.png', props.curation);
const onDropThumbnail = useDropImageCallback('logo.png', props.curation);
const onDropScreenshot = useDropImageCallback('ss.png', props.curation);
// Input props
const editable = true;
const disabled = props.curation ? props.curation.locked : false;
// Whether the platform used by the curation is native locked
const native = useMemo(() => {
if (props.curation && props.curation.meta.platform) {
isPlatformNativeLocked(props.curation.meta.platform);
}
return false;
}, [props.curation]);
// Render additional application elements
const addApps = useMemo(() => (
<>
{ strings.browse.additionalApplications } :
{ props.curation && props.curation.addApps.length > 0 ? (
<table className="curate-box-table">
<tbody>
{ props.curation.addApps.map(addApp => (
<CurateBoxAddApp
key={addApp.key}
curationKey={props.curation && props.curation.key || ''}
curation={addApp}
dispatch={props.dispatch}
disabled={disabled}
platform={props.curation && props.curation.meta.platform}
onInputKeyDown={onInputKeyDown} />
)) }
</tbody>
</table>
) : undefined }
</>
), [
props.curation && props.curation.addApps,
props.curation && props.curation.key,
props.dispatch,
native,
disabled
]);
// Count the number of collisions
const collisionCount: number | undefined = useMemo(() => {
return contentCollisions && contentCollisions.reduce((v, c) => v + (c.fileExists ? 1 : 0), 0);
}, [contentCollisions]);
// Render content (files and folders inside the "content" folder)
const contentFilenames = useMemo(() => {
return props.curation && props.curation.content.map((content, index) => {
const collision = contentCollisions && contentCollisions[index];
// Folders file names ends with '/' and have a file size of 0
const isFolder = (
content.filePath[content.filePath.length - 1] === '/' &&
content.fileSize === 0
);
// Render content element
const contentElement = (
<span className='curate-box-files__entry'>
{content.filePath + (isFolder ? '' : ` (${sizeToString(content.fileSize)})`)}
</span>
);
// Render collision element
const collisionElement = (collision && collision.fileExists) ? (
<span className='curate-box-files__entry-collision'>
{' - Already Exists' + (collision.isFolder ? '' : ` (${sizeToString(content.fileSize)})`)}
</span>
) : undefined;
// Render
return (
<span key={index}>
{contentElement}
{collisionElement}
{'\n'}
</span>
);
});
}, [props.curation && props.curation.content, contentCollisions]);
// Generate Warnings
const warnings = useMemo(() => {
if (props.curation) {
return getCurationWarnings(props.curation, props.suggestions, props.libraries, strings.curate);
}
return {};
}, [props.curation, strings]);
// Render images (logo + ss)
const imageSplit = useMemo(() => {
if (props.curation) {
const thumbnailPath = props.curation.thumbnail.exists ? fixSlashes(`${props.curation.thumbnail.filePath}?v=${props.curation.thumbnail.version}`) : undefined;
const screenshotPath = props.curation.screenshot.exists ? fixSlashes(`${props.curation.screenshot.filePath}?v=${props.curation.screenshot.version}`) : undefined;
return (
<>
<GameImageSplit
text={strings.browse.thumbnail}
imgSrc={thumbnailPath}
showHeaders={false}
onAddClick={onAddThumbnailClick}
onRemoveClick={onRemoveThumbnailClick}
disabled={disabled}
onDrop={onDropThumbnail} />
<GameImageSplit
text={strings.browse.screenshot}
imgSrc={screenshotPath}
showHeaders={false}
onAddClick={onAddScreenshotClick}
onRemoveClick={onRemoveScreenshotClick}
disabled={disabled}
onDrop={onDropScreenshot} />
</>
);
}
}, [props.curation && props.curation.thumbnail, props.curation && props.curation.screenshot, disabled]);
// Own Lirary Options
const ownLibraryOptions = useMemo(() => {
// Add meta's library if invalid (special option)
if (warnings.nonExistingLibrary && props.curation) {
const nonExistingLibrary = (
<option
className='curate-box-select__invalid-option'
key={props.libraryOptions.length}
value={props.curation.meta.library}>
{props.curation.meta.library}
</option>
);
return [ ...props.libraryOptions, nonExistingLibrary ];
}
return props.libraryOptions;
}, [props.curation && props.curation.meta.library, props.libraryOptions, warnings]);
// Render all owned ProgressData as components
const progressComponent = useMemo(() => {
const key = props.curation ? props.curation.key : 'invalid';
const progressArray = progressState[key];
if (progressArray) {
return progressArray.map((data, index) => {
return (
<AutoProgressComponent
key={index}
progressData={data} />
);
});
}
}, [props.curation && progressState[props.curation.key]]);
// Meta
const curationNotes = props.curation && props.curation.meta.curationNotes || '';
// Misc
const sharedInputProps = {
editable: editable,
disabled: disabled,
onKeyDown: onInputKeyDown,
};
// Render
return React.useMemo(() => (
<div id={props.curation && props.curation.key} className='curate-box'>
{/* Images */}
<div className='curate-box-images'>
{imageSplit}
</div>
<div className='curate-box-images-footer'>
<p>{strings.browse.dropImageHere}</p>
</div>
<hr className='curate-box-divider' />
{/* Fields */}
<table className="curate-box-table">
<tbody>
<CurateBoxRow title={strings.filter.title + ':'}>
<InputField
text={props.curation && props.curation.meta.title || ''}
placeholder={strings.browse.noTitle}
onChange={onTitleChange}
{ ...sharedInputProps } />
</CurateBoxRow>
<CurateBoxRow title={strings.browse.alternateTitles + ':'}>
<InputField
text={props.curation && props.curation.meta.alternateTitles || ''}
placeholder={strings.browse.noAlternateTitles}
onChange={onAlternateTitlesChange}
{ ...sharedInputProps } />
</CurateBoxRow>
<CurateBoxRow title={strings.browse.library + ':'}>
{/* Look like a DropdownInputField */}
<div className={warnings.nonExistingLibrary ? 'curate-box-select--warn' : ''}>
<select
className={'input-field input-field--edit simple-input ' +
'input-dropdown__input-field__input__inner ' +
(disabled ? 'simple-input--disabled' : '')}
value={props.curation && props.curation.meta.library || ''}
onChange={onLibraryChange}
disabled={disabled}>
{ownLibraryOptions}
</select>
</div>
</CurateBoxRow>
<CurateBoxRow title={strings.filter.series + ':'}>
<InputField
text={props.curation && props.curation.meta.series || ''}
placeholder={strings.browse.noSeries}
onChange={onSeriesChange}
{ ...sharedInputProps } />
</CurateBoxRow>
<CurateBoxRow title={strings.filter.developer + ':'}>
<InputField
text={props.curation && props.curation.meta.developer || ''}
placeholder={strings.browse.noDeveloper}
onChange={onDeveloperChange}
{ ...sharedInputProps } />
</CurateBoxRow>
<CurateBoxRow title={strings.browse.publisher + ':'}>
<InputField
text={props.curation && props.curation.meta.publisher || ''}
placeholder={strings.browse.noPublisher}
onChange={onPublisherChange}
{ ...sharedInputProps } />
</CurateBoxRow>
<CurateBoxRow title={strings.browse.tags + ':'}>
<TagInputField
placeholder={strings.browse.enterTag}
text={tagInputText}
editable={editable}
tags={props.curation && props.curation.meta.tags || []}
categories={props.tagCategories}
suggestions={tagSuggestions}
onChange={onCurrentTagChange}
onTagSuggestionSelect={onAddTagSuggestion}
onTagSubmit={onAddTagByString}
onTagEditableSelect={onRemoveTag} />
</CurateBoxRow>
<CurateBoxRow title={strings.browse.playMode + ':'}>
<DropdownInputField
text={props.curation && props.curation.meta.playMode || ''}
placeholder={strings.browse.noPlayMode}
onChange={onPlayModeChange}
items={props.suggestions && props.suggestions.playMode || []}
onItemSelect={onPlayModeSelect}
{ ...sharedInputProps } />
</CurateBoxRow>
<CurateBoxRow title={strings.browse.status + ':'}>
<DropdownInputField
text={props.curation && props.curation.meta.status || ''}
placeholder={strings.browse.noStatus}
onChange={onStatusChange}
items={props.suggestions && props.suggestions.status || []}
onItemSelect={onStatusSelect}
{ ...sharedInputProps } />
</CurateBoxRow>
<CurateBoxRow title={strings.browse.version + ':'}>
<InputField
text={props.curation && props.curation.meta.version || ''}
placeholder={strings.browse.noVersion}
onChange={onVersionChange}
{ ...sharedInputProps } />
</CurateBoxRow>
<CurateBoxRow title={strings.browse.releaseDate + ':'}>
<InputField
text={props.curation && props.curation.meta.releaseDate || ''}
placeholder={strings.browse.noReleaseDate}
onChange={onReleaseDateChange}
className={warnings.releaseDateInvalid ? 'input-field--warn' : ''}
{ ...sharedInputProps } />
</CurateBoxRow>
<CurateBoxRow title={strings.browse.language + ':'}>
<InputField
text={props.curation && props.curation.meta.language || ''}
placeholder={strings.browse.noLanguage}
onChange={onLanguageChange}
{ ...sharedInputProps } />
</CurateBoxRow>
<CurateBoxRow title={strings.browse.source + ':'}>
<InputField
text={props.curation && props.curation.meta.source || ''}
placeholder={strings.browse.noSource}
onChange={onSourceChange}
{ ...sharedInputProps } />
</CurateBoxRow>
<CurateBoxRow title={strings.browse.platform + ':'}>
<DropdownInputField
text={props.curation && props.curation.meta.platform || ''}
placeholder={strings.browse.noPlatform}
onChange={onPlatformChange}
items={props.suggestions && props.suggestions.platform || []}
onItemSelect={onPlatformItemSelect}
className={warnings.unusedPlatform ? 'input-field--warn' : ''}
{ ...sharedInputProps } />
</CurateBoxRow>
<CurateBoxRow title={strings.browse.applicationPath + ':'}>
<DropdownInputField
text={props.curation && props.curation.meta.applicationPath || ''}
placeholder={strings.browse.noApplicationPath}
onChange={onApplicationPathChange}
items={props.suggestions && props.suggestions.applicationPath || []}
onItemSelect={onApplicationPathItemSelect}
className={warnings.unusedApplicationPath ? 'input-field--warn' : ''}
{ ...sharedInputProps } />
</CurateBoxRow>
<CurateBoxRow title={strings.browse.launchCommand + ':'}>
<InputField
text={props.curation && props.curation.meta.launchCommand || ''}
placeholder={strings.browse.noLaunchCommand}
onChange={onLaunchCommandChange}
className={(warnings.noLaunchCommand || (warnings.invalidLaunchCommand && warnings.invalidLaunchCommand.length !== 0)) ? 'input-field--warn' : ''}
{ ...sharedInputProps } />
</CurateBoxRow>
<CurateBoxRow title={strings.browse.notes + ':'}>
<InputField
text={props.curation && props.curation.meta.notes || ''}
placeholder={strings.browse.noNotes}
onChange={onNotesChange}
multiline={true}
{ ...sharedInputProps } />
</CurateBoxRow>
<CurateBoxRow title={strings.browse.originalDescription + ':'}>
<InputField
text={props.curation && props.curation.meta.originalDescription || ''}
placeholder={strings.browse.noOriginalDescription}
onChange={onOriginalDescriptionChange}
multiline={true}
{ ...sharedInputProps } />
</CurateBoxRow>
<CurateBoxRow title={strings.curate.curationNotes + ':'}>
<InputField
text={curationNotes}
placeholder={strings.curate.noCurationNotes}
onChange={onCurationNotesChange}
multiline={true}
className={curationNotes.length > 0 ? 'input-field--info' : ''}
{ ...sharedInputProps } />
</CurateBoxRow>
<CurateBoxRow title={strings.browse.extreme + ':'}>
<CheckBox
checked={props.curation && props.curation.meta.extreme}
onToggle={onExtremeChange}
disabled={disabled} />
</CurateBoxRow>
</tbody>
</table>
<hr className='curate-box-divider' />
{/* Additional Application */}
<div className='curate-box-add-apps'>
{addApps}
<SimpleButton
className='curate-box-buttons__button'
value={strings.curate.newAddApp}
onClick={onNewAddApp}
disabled={disabled} />
<SimpleButton
className='curate-box-buttons__button'
value={strings.curate.addExtras}
onClick={onAddExtras}
disabled={disabled} />
<SimpleButton
className='curate-box-buttons__button'
value={strings.curate.addMessage}
onClick={onAddMessage}
disabled={disabled} />
<hr className='curate-box-divider' />
</div>
{/* Content */}
<div className='curate-box-files'>
<div className='curate-box-files__head'>
{strings.curate.contentFiles + ': '}
{(collisionCount !== undefined && collisionCount > 0) ? (
<label className='curate-box-files__head-collision-count'>
({collisionCount} / {contentCollisions && contentCollisions.length} Files or Folders Already Exists)
</label>
) : undefined}
</div>
<pre className='curate-box-files__body simple-scroll'>
{contentFilenames}
</pre>
</div>
<hr className='curate-box-divider' />
{/* Warnings */}
<CurateBoxWarnings warnings={warnings} />
<table>
<tbody>
<CurateBoxRow title={strings.curate.id + ':'}>
<InputField
text={props.curation && props.curation.key || ''}
placeholder={'No ID? Something\'s broken.'}
{ ...sharedInputProps }
disabled={true} />
</CurateBoxRow>
</tbody>
</table>
{/* Buttons */}
<div className='curate-box-buttons'>
<div className='curate-box-buttons__left'>
<SimpleButton
className='curate-box-buttons__button'
value={strings.curate.indexContent}
onClick={onIndexContent}
disabled={disabled} />
<SimpleButton
className='curate-box-buttons__button'
value={strings.curate.openFolder}
onClick={onOpenFolder}
disabled={disabled} />
<SimpleButton
className='curate-box-buttons__button'
value={strings.curate.run}
onClick={onRun}
disabled={disabled} />
{ props.mad4fpEnabled ? (
<SimpleButton
className='curate-box-buttons__button'
value={strings.curate.runWithMAD4FP}
onClick={onRunWithMAD4FP}
disabled={disabled} />
) : undefined}
</div>
<div className='curate-box-buttons__right'>
<ConfirmElement
onConfirm={onRemoveClick}
render={renderRemoveButton}
extra={[strings.curate, disabled]} />
<SimpleButton
className='curate-box-buttons__button'
value={strings.curate.export}
onClick={onExportClick}
disabled={disabled} />
<SimpleButton
className='curate-box-buttons__button'
value={strings.curate.import}
onClick={onImportClick}
disabled={disabled} />
</div>
</div>
{progressComponent}
</div>
), [props.curation, strings, disabled, warnings, onImportClick, progressComponent,
tagInputText, tagSuggestions]);
}
function renderRemoveButton({ activate, activationCounter, reset, extra }: ConfirmElementArgs<[LangContainer['curate'], boolean]>): JSX.Element {
const [ strings, disabled ] = extra;
return (
<SimpleButton
className={
'curate-box-buttons__button' +
((activationCounter > 0) ? ' curate-box-buttons__button--active simple-vertical-shake' : '')
}
value={strings.delete}
title={strings.deleteCurationDesc}
disabled={disabled}
onClick={activate}
onMouseLeave={reset} />
);
}
type InputElement = HTMLInputElement | HTMLTextAreaElement;
/** Subset of the input elements on change event, with only the properties used by the callbacks. */
type InputElementOnChangeEvent = {
currentTarget: {
value: React.ChangeEvent<InputElement>['currentTarget']['value']
}
}
function transformOnItemSelect(callback: (event: InputElementOnChangeEvent) => void) {
return (text: string) => {
callback({ currentTarget: { value: text } });
};
}
/**
* Create a callback for InputField's onChange.
* When called, the callback will set the value of a metadata property to the value of the input field.
* @param property Property the input field should change.
* @param key Key of the curation to edit.
* @param dispatch Dispatcher to use.
*/
function useOnInputChange(property: keyof EditCurationMeta, key: string | undefined, dispatch: React.Dispatch<CurationAction>) {
return useCallback((event: InputElementOnChangeEvent) => {
if (key !== undefined) {
dispatch({
type: 'edit-curation-meta',
payload: {
key: key,
property: property,
value: event.currentTarget.value
}
});
}
}, [dispatch, key]);
}
function useOnCheckboxToggle(property: keyof EditCurationMeta, key: string | undefined, dispatch: React.Dispatch<CurationAction>) {
return useCallback((checked: boolean) => {
if (key !== undefined) {
dispatch({
type: 'edit-curation-meta',
payload: {
key: key,
property: property,
value: checked
}
});
}
}, [dispatch, key]);
}
function useAddImageCallback(filename: string, strings: LangContainer, curation: EditCuration | undefined): () => void {
return useCallback(() => {
const filePaths = window.Shared.showOpenDialogSync({
title: strings.dialog.selectScreenshot,
properties: ['openFile'],
filters: [{ extensions: ['png', 'PNG'], name: 'Image File' }]
});
if (curation && filePaths && filePaths[0].toLowerCase().endsWith('.png')) {
fs.copyFile(filePaths[0], path.join(getCurationFolder2(curation), filename));
}
}, [curation && curation.key]);
}
/**
* Delete an image file inside the curation's folder.
* @param filename Name of the image file.
* @param curation Curation to delete it from.
*/
function useRemoveImageCallback(filename: string, curation: EditCuration | undefined): () => Promise<void> {
return useCallback(async () => {
if (curation) {
const filePath = path.join(getCurationFolder2(curation), filename);
try {
await fs.access(filePath, fs.constants.F_OK | fs.constants.W_OK);
await fs.unlink(filePath);
} catch (error) {
curationLog('Error replacing image - ' + error.message);