-
-
Notifications
You must be signed in to change notification settings - Fork 5.1k
/
Note.tsx
1635 lines (1371 loc) · 51.5 KB
/
Note.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 AsyncActionQueue from '@joplin/lib/AsyncActionQueue';
import uuid from '@joplin/lib/uuid';
import Setting from '@joplin/lib/models/Setting';
import shim from '@joplin/lib/shim';
import UndoRedoService from '@joplin/lib/services/UndoRedoService';
import NoteBodyViewer from '../../NoteBodyViewer/NoteBodyViewer';
import checkPermissions from '../../../utils/checkPermissions';
import NoteEditor from '../../NoteEditor/NoteEditor';
import * as React from 'react';
import { Keyboard, View, TextInput, StyleSheet, Linking, Share, NativeSyntheticEvent } from 'react-native';
import { Platform, PermissionsAndroid } from 'react-native';
import { connect } from 'react-redux';
import Note from '@joplin/lib/models/Note';
import BaseItem from '@joplin/lib/models/BaseItem';
import Resource from '@joplin/lib/models/Resource';
import Folder from '@joplin/lib/models/Folder';
const Clipboard = require('@react-native-clipboard/clipboard').default;
const md5 = require('md5');
import BackButtonService from '../../../services/BackButtonService';
import NavService, { OnNavigateCallback as OnNavigateCallback } from '@joplin/lib/services/NavService';
import { ModelType } from '@joplin/lib/BaseModel';
import FloatingActionButton from '../../buttons/FloatingActionButton';
const { fileExtension, safeFileExtension } = require('@joplin/lib/path-utils');
import * as mimeUtils from '@joplin/lib/mime-utils';
import ScreenHeader, { MenuOptionType } from '../../ScreenHeader';
import NoteTagsDialog from '../NoteTagsDialog';
import time from '@joplin/lib/time';
import Checkbox from '../../Checkbox';
import { _, currentLocale } from '@joplin/lib/locale';
import { reg } from '@joplin/lib/registry';
import ResourceFetcher from '@joplin/lib/services/ResourceFetcher';
import { BaseScreenComponent } from '../../base-screen';
import { themeStyle, editorFont } from '../../global-style';
import shared, { BaseNoteScreenComponent, Props as BaseProps } from '@joplin/lib/components/shared/note-screen-shared';
import SelectDateTimeDialog from '../../SelectDateTimeDialog';
import ShareExtension from '../../../utils/ShareExtension.js';
import CameraView from '../../CameraView/CameraView';
import { FolderEntity, NoteEntity, ResourceEntity } from '@joplin/lib/services/database/types';
import Logger from '@joplin/utils/Logger';
import ImageEditor from '../../NoteEditor/ImageEditor/ImageEditor';
import promptRestoreAutosave from '../../NoteEditor/ImageEditor/promptRestoreAutosave';
import isEditableResource from '../../NoteEditor/ImageEditor/isEditableResource';
import VoiceTypingDialog from '../../voiceTyping/VoiceTypingDialog';
import { isSupportedLanguage } from '../../../services/voiceTyping/vosk';
import { ChangeEvent as EditorChangeEvent, SelectionRangeChangeEvent, UndoRedoDepthChangeEvent } from '@joplin/editor/events';
import { join } from 'path';
import { Dispatch } from 'redux';
import { RefObject, useContext, useRef } from 'react';
import { SelectionRange } from '../../NoteEditor/types';
import { getNoteCallbackUrl } from '@joplin/lib/callbackUrlUtils';
import { AppState } from '../../../utils/types';
import restoreItems from '@joplin/lib/services/trash/restoreItems';
import { getDisplayParentTitle } from '@joplin/lib/services/trash';
import { PluginStates, utils as pluginUtils } from '@joplin/lib/services/plugins/reducer';
import debounce from '../../../utils/debounce';
import { focus } from '@joplin/lib/utils/focusHandler';
import CommandService, { RegisteredRuntime } from '@joplin/lib/services/CommandService';
import { ResourceInfo } from '../../NoteBodyViewer/hooks/useRerenderHandler';
import getImageDimensions from '../../../utils/image/getImageDimensions';
import resizeImage from '../../../utils/image/resizeImage';
import { CameraResult } from '../../CameraView/types';
import { DialogContext, DialogControl } from '../../DialogManager';
import { CommandRuntimeProps, EditorMode, PickerResponse } from './types';
import commands from './commands';
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
const emptyArray: any[] = [];
const logger = Logger.create('screens/Note');
interface Props extends BaseProps {
provisionalNoteIds: string[];
dispatch: Dispatch;
noteId: string;
useEditorBeta: boolean;
plugins: PluginStates;
themeId: number;
editorFontSize: number;
editorFont: number; // e.g. Setting.FONT_MENLO
showSideMenu: boolean;
searchQuery: string;
ftsEnabled: number;
highlightedWords: string[];
noteHash: string;
toolbarEnabled: boolean;
}
interface ComponentProps extends Props {
dialogs: DialogControl;
}
interface State {
note: NoteEntity;
mode: EditorMode;
readOnly: boolean;
folder: FolderEntity|null;
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
lastSavedNote: any;
isLoading: boolean;
titleTextInputHeight: number;
alarmDialogShown: boolean;
heightBumpView: number;
noteTagDialogShown: boolean;
fromShare: boolean;
showCamera: boolean;
showImageEditor: boolean;
imageEditorResource: ResourceEntity;
imageEditorResourceFilepath: string;
noteResources: Record<string, ResourceInfo>;
newAndNoTitleChangeNoteId: boolean|null;
undoRedoButtonState: {
canUndo: boolean;
canRedo: boolean;
};
voiceTypingDialogShown: boolean;
}
class NoteScreenComponent extends BaseScreenComponent<ComponentProps, State> implements BaseNoteScreenComponent {
// This isn't in this.state because we don't want changing scroll to trigger
// a re-render.
private lastBodyScroll: number|undefined = undefined;
private saveActionQueues_: Record<string, AsyncActionQueue>;
private doFocusUpdate_: boolean;
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
private styles_: any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
private editorRef: any;
private titleTextFieldRef: RefObject<TextInput>;
private navHandler: OnNavigateCallback;
private backHandler: ()=> Promise<boolean>;
private undoRedoService_: UndoRedoService;
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
private noteTagDialog_closeRequested: any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
private onJoplinLinkClick_: any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
private refreshResource: (resource: any, noteBody?: string)=> Promise<void>;
private selection: SelectionRange;
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
private menuOptionsCache_: Record<string, any>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
private focusUpdateIID_: any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
private folderPickerOptions_: any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
public dialogbox: any;
private commandRegistration_: RegisteredRuntime|null = null;
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
public static navigationOptions(): any {
return { header: null };
}
public constructor(props: ComponentProps) {
super(props);
this.state = {
note: Note.new(),
mode: 'view',
readOnly: false,
folder: null,
lastSavedNote: null,
isLoading: true,
titleTextInputHeight: 20,
alarmDialogShown: false,
heightBumpView: 0,
noteTagDialogShown: false,
fromShare: false,
showCamera: false,
showImageEditor: false,
imageEditorResource: null,
noteResources: {},
imageEditorResourceFilepath: null,
newAndNoTitleChangeNoteId: null,
undoRedoButtonState: {
canUndo: false,
canRedo: false,
},
voiceTypingDialogShown: false,
};
this.titleTextFieldRef = React.createRef();
this.saveActionQueues_ = {};
// this.markdownEditorRef = React.createRef(); // For focusing the Markdown editor
this.doFocusUpdate_ = false;
this.styles_ = {};
this.editorRef = React.createRef();
const saveDialog = async () => {
if (this.isModified()) {
const buttonId = await this.props.dialogs.showMenu(
_('This note has been modified:'),
[{ text: _('Save changes'), id: 'save' }, { text: _('Discard changes'), id: 'discard' }, { text: _('Cancel'), id: 'cancel' }],
);
if (buttonId === 'cancel') return true;
if (buttonId === 'save') await this.saveNoteButton_press();
}
return false;
};
this.navHandler = async () => {
return await saveDialog();
};
this.backHandler = async () => {
if (this.isModified()) {
await this.saveNoteButton_press();
}
const isProvisionalNote = this.props.provisionalNoteIds.includes(this.props.noteId);
if (isProvisionalNote) {
return false;
}
if (this.state.mode === 'edit') {
Keyboard.dismiss();
this.setState({
mode: 'view',
});
await this.undoRedoService_.reset();
return true;
}
if (this.state.fromShare) {
// Note: In the past, NAV_BACK caused undesired behaviour in this case:
// - share to Joplin from some other app
// - open Joplin and open any note
// - go back -- with NAV_BACK this causes the app to exit rather than just showing notes
// This no longer seems to happen, but this case should be checked when adjusting navigation
// history behavior.
this.props.dispatch({
type: 'NAV_BACK',
});
ShareExtension.close();
return true;
}
return false;
};
this.noteTagDialog_closeRequested = () => {
this.setState({ noteTagDialogShown: false });
};
this.onJoplinLinkClick_ = async (msg: string) => {
try {
await CommandService.instance().execute('openItem', msg);
} catch (error) {
await this.props.dialogs.error(error.message);
}
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
this.refreshResource = async (resource: any, noteBody: string = null) => {
if (noteBody === null && this.state.note && this.state.note.body) noteBody = this.state.note.body;
if (noteBody === null) return;
const resourceIds = await Note.linkedResourceIds(noteBody);
if (resourceIds.indexOf(resource.id) >= 0) {
shared.clearResourceCache();
const attachedResources = await shared.attachedResources(noteBody);
this.setState({ noteResources: attachedResources });
}
};
this.cameraView_onPhoto = this.cameraView_onPhoto.bind(this);
this.cameraView_onCancel = this.cameraView_onCancel.bind(this);
this.properties_onPress = this.properties_onPress.bind(this);
this.showOnMap_onPress = this.showOnMap_onPress.bind(this);
this.onMarkForDownload = this.onMarkForDownload.bind(this);
this.sideMenuOptions = this.sideMenuOptions.bind(this);
this.folderPickerOptions_valueChanged = this.folderPickerOptions_valueChanged.bind(this);
this.saveNoteButton_press = this.saveNoteButton_press.bind(this);
this.onAlarmDialogAccept = this.onAlarmDialogAccept.bind(this);
this.onAlarmDialogReject = this.onAlarmDialogReject.bind(this);
this.todoCheckbox_change = this.todoCheckbox_change.bind(this);
this.title_changeText = this.title_changeText.bind(this);
this.undoRedoService_stackChange = this.undoRedoService_stackChange.bind(this);
this.screenHeader_undoButtonPress = this.screenHeader_undoButtonPress.bind(this);
this.screenHeader_redoButtonPress = this.screenHeader_redoButtonPress.bind(this);
this.onBodyViewerCheckboxChange = this.onBodyViewerCheckboxChange.bind(this);
this.onUndoRedoDepthChange = this.onUndoRedoDepthChange.bind(this);
this.voiceTypingDialog_onText = this.voiceTypingDialog_onText.bind(this);
this.voiceTypingDialog_onDismiss = this.voiceTypingDialog_onDismiss.bind(this);
}
private registerCommands() {
if (this.commandRegistration_) return;
const dialogs = () => this.props.dialogs;
this.commandRegistration_ = CommandService.instance().componentRegisterCommands<CommandRuntimeProps>(
{
attachFile: this.attachFile.bind(this),
hideKeyboard: () => {
if (this.useEditorBeta()) {
this.editorRef?.current?.hideKeyboard();
} else {
Keyboard.dismiss();
}
},
insertText: this.insertText.bind(this),
get dialogs() {
return dialogs();
},
setCameraVisible: (visible) => {
this.setState({ showCamera: visible });
},
setTagDialogVisible: (visible) => {
if (!this.state.note || !this.state.note.id) return;
this.setState({ noteTagDialogShown: visible });
},
getMode: () => this.state.mode,
setMode: (mode: 'view'|'edit') => {
this.setState({ mode });
},
},
commands,
true,
);
}
private useEditorBeta(): boolean {
return this.props.useEditorBeta;
}
private onUndoRedoDepthChange(event: UndoRedoDepthChangeEvent) {
if (this.useEditorBeta()) {
this.setState({ undoRedoButtonState: {
canUndo: !!event.undoDepth,
canRedo: !!event.redoDepth,
} });
}
}
private undoRedoService_stackChange() {
if (!this.useEditorBeta()) {
this.setState({ undoRedoButtonState: {
canUndo: this.undoRedoService_.canUndo,
canRedo: this.undoRedoService_.canRedo,
} });
}
}
private async undoRedo(type: 'undo'|'redo') {
const undoState = await this.undoRedoService_[type](this.undoState());
if (!undoState) return;
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
this.setState((state: any) => {
const newNote = { ...state.note };
newNote.body = undoState.body;
return {
note: newNote,
};
});
}
private screenHeader_undoButtonPress() {
if (this.useEditorBeta()) {
this.editorRef.current.undo();
} else {
void this.undoRedo('undo');
}
}
private screenHeader_redoButtonPress() {
if (this.useEditorBeta()) {
this.editorRef.current.redo();
} else {
void this.undoRedo('redo');
}
}
public undoState(noteBody: string = null) {
return {
body: noteBody === null ? this.state.note.body : noteBody,
};
}
public styles() {
const themeId = this.props.themeId;
const theme = themeStyle(themeId);
const cacheKey = [themeId, this.state.titleTextInputHeight].join('_');
if (this.styles_[cacheKey]) return this.styles_[cacheKey];
this.styles_ = {};
// TODO: Clean up these style names and nesting
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
const styles: any = {
screen: {
flex: 1,
backgroundColor: theme.backgroundColor,
},
bodyTextInput: {
flex: 1,
paddingLeft: theme.marginLeft,
paddingRight: theme.marginRight,
// Add extra space to allow scrolling past end of document, and also to fix this:
// https://github.com/laurent22/joplin/issues/1437
// 2020-04-20: removed bottom padding because it doesn't work properly in Android
// Instead of being inside the scrollable area, the padding is outside thus
// restricting the view.
// See https://github.com/laurent22/joplin/issues/3041#issuecomment-616267739
// paddingBottom: Math.round(dimensions.height / 4),
textAlignVertical: 'top',
color: theme.color,
backgroundColor: theme.backgroundColor,
fontSize: this.props.editorFontSize,
fontFamily: editorFont(this.props.editorFont),
},
noteBodyViewer: {
flex: 1,
},
checkbox: {
color: theme.color,
paddingRight: 10,
paddingLeft: theme.marginLeft,
paddingTop: 10, // Added for iOS (Not needed for Android??)
paddingBottom: 10, // Added for iOS (Not needed for Android??)
},
markdownButtons: {
borderColor: theme.dividerColor,
color: theme.urlColor,
},
};
styles.noteBodyViewerPreview = {
...styles.noteBodyViewer,
borderTopColor: theme.dividerColor,
borderTopWidth: 1,
borderBottomColor: theme.dividerColor,
borderBottomWidth: 1,
};
styles.titleContainer = {
flex: 0,
flexDirection: 'row',
flexBasis: 'auto',
paddingLeft: theme.marginLeft,
paddingRight: theme.marginRight,
borderBottomColor: theme.dividerColor,
borderBottomWidth: 1,
};
styles.titleContainerTodo = { ...styles.titleContainer };
styles.titleContainerTodo.paddingLeft = 0;
styles.titleTextInput = {
flex: 1,
marginTop: 0,
paddingLeft: 0,
color: theme.color,
backgroundColor: theme.backgroundColor,
fontWeight: 'bold',
fontSize: theme.fontSize,
paddingTop: 10, // Added for iOS (Not needed for Android??)
paddingBottom: 10, // Added for iOS (Not needed for Android??)
};
this.styles_[cacheKey] = StyleSheet.create(styles);
return this.styles_[cacheKey];
}
public isModified() {
return shared.isModified(this);
}
public async requestGeoLocationPermissions() {
if (!Setting.value('trackLocation')) return;
if (Platform.OS === 'web') return;
const response = await checkPermissions(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION, {
message: _('In order to associate a geo-location with the note, the app needs your permission to access your location.\n\nYou may turn off this option at any time in the Configuration screen.'),
title: _('Permission needed'),
});
// If the user simply pressed "Deny", we don't automatically switch it off because they might accept
// once we show the rationale again on second try. If they press "Never again" however we switch it off.
// https://github.com/zoontek/react-native-permissions/issues/385#issuecomment-563132396
if (response === PermissionsAndroid.RESULTS.NEVER_ASK_AGAIN) {
reg.logger().info('Geo-location tracking has been automatically disabled');
Setting.setValue('trackLocation', false);
}
}
public async componentDidMount() {
BackButtonService.addHandler(this.backHandler);
NavService.addHandler(this.navHandler);
shared.clearResourceCache();
shared.installResourceHandling(this.refreshResource);
await shared.initState(this);
this.undoRedoService_ = new UndoRedoService();
this.undoRedoService_.on('stackChange', this.undoRedoService_stackChange);
// Although it is async, we don't wait for the answer so that if permission
// has already been granted, it doesn't slow down opening the note. If it hasn't
// been granted, the popup will open anyway.
void this.requestGeoLocationPermissions();
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
public onMarkForDownload(event: any) {
void ResourceFetcher.instance().markForDownload(event.resourceId);
}
public async markAllAttachedResourcesForDownload() {
const resourceIds = await Note.linkedResourceIds(this.state.note.body);
await ResourceFetcher.instance().markForDownload(resourceIds);
}
public componentDidUpdate(prevProps: Props, prevState: State) {
if (this.doFocusUpdate_) {
this.doFocusUpdate_ = false;
this.scheduleFocusUpdate();
}
if (prevProps.showSideMenu !== this.props.showSideMenu && this.props.showSideMenu) {
this.props.dispatch({
type: 'NOTE_SIDE_MENU_OPTIONS_SET',
options: this.sideMenuOptions(),
});
}
if (prevState.isLoading !== this.state.isLoading && !this.state.isLoading) {
// If there's autosave data, prompt the user to restore it.
void promptRestoreAutosave((drawingData: string) => {
void this.attachNewDrawing(drawingData);
});
// Handle automatic resource downloading
if (this.state.note?.body && Setting.value('sync.resourceDownloadMode') === 'auto') {
void this.markAllAttachedResourcesForDownload();
}
}
// Disable opening/closing the side menu with touch gestures
// when the image editor is open.
if (prevState.showImageEditor !== this.state.showImageEditor) {
this.props.dispatch({
type: 'SET_SIDE_MENU_TOUCH_GESTURES_DISABLED',
disableSideMenuGestures: this.state.showImageEditor,
});
}
if (prevProps.noteId && this.props.noteId && prevProps.noteId !== this.props.noteId) {
// Easier to just go back, then go to the note since
// the Note screen doesn't handle reloading a different note
const noteId = this.props.noteId;
const noteHash = this.props.noteHash;
this.props.dispatch({
type: 'NAV_GO',
routeName: 'Note',
noteId: noteId,
noteHash: noteHash,
});
}
}
public componentWillUnmount() {
BackButtonService.removeHandler(this.backHandler);
NavService.removeHandler(this.navHandler);
shared.uninstallResourceHandling(this.refreshResource);
void this.saveActionQueue(this.state.note.id).processAllNow();
// It cannot theoretically be undefined, since componentDidMount should always be called before
// componentWillUnmount, but with React Native the impossible often becomes possible.
if (this.undoRedoService_) this.undoRedoService_.off('stackChange', this.undoRedoService_stackChange);
this.commandRegistration_?.deregister();
this.commandRegistration_ = null;
}
private title_changeText(text: string) {
shared.noteComponent_change(this, 'title', text);
this.setState({ newAndNoTitleChangeNoteId: null });
}
private onPlainEditorTextChange = (text: string) => {
if (!this.undoRedoService_.canUndo) {
this.undoRedoService_.push(this.undoState());
} else {
this.undoRedoService_.schedulePush(this.undoState());
}
shared.noteComponent_change(this, 'body', text);
};
// Avoid saving immediately -- the NoteEditor's content isn't controlled by its props
// and updating this.state.note immediately causes slow rerenders.
//
// See https://github.com/laurent22/joplin/issues/10130
private onMarkdownEditorTextChange = debounce((event: EditorChangeEvent) => {
shared.noteComponent_change(this, 'body', event.value);
}, 100);
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
private onPlainEditorSelectionChange = (event: NativeSyntheticEvent<any>) => {
this.selection = event.nativeEvent.selection;
};
private onMarkdownEditorSelectionChange = (event: SelectionRangeChangeEvent) => {
this.selection = { start: event.from, end: event.to };
};
public makeSaveAction() {
return async () => {
return shared.saveNoteButton_press(this, null, null);
};
}
public saveActionQueue(noteId: string) {
if (!this.saveActionQueues_[noteId]) {
this.saveActionQueues_[noteId] = new AsyncActionQueue(500);
}
return this.saveActionQueues_[noteId];
}
public scheduleSave() {
this.saveActionQueue(this.state.note.id).push(this.makeSaveAction());
}
private async saveNoteButton_press(folderId: string = null) {
await shared.saveNoteButton_press(this, folderId, null);
Keyboard.dismiss();
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any -- Old code before rule was applied
public async saveOneProperty(name: string, value: any) {
await shared.saveOneProperty(this, name, value);
}
public async resizeImage(localFilePath: string, targetPath: string, mimeType: string) {
const maxSize = Resource.IMAGE_MAX_DIMENSION;
const dimensions = await getImageDimensions(localFilePath);
reg.logger().info('Original dimensions ', dimensions);
const saveOriginalImage = async () => {
await shim.fsDriver().copy(localFilePath, targetPath);
return true;
};
const saveResizedImage = async () => {
dimensions.width = maxSize;
dimensions.height = maxSize;
reg.logger().info('New dimensions ', dimensions);
await resizeImage({
inputPath: localFilePath,
outputPath: targetPath,
maxWidth: dimensions.width,
maxHeight: dimensions.height,
quality: 85,
format: mimeType === 'image/png' ? 'PNG' : 'JPEG',
});
return true;
};
const canResize = dimensions.width > maxSize || dimensions.height > maxSize;
if (canResize) {
const resizeLargeImages = Setting.value('imageResizing');
if (resizeLargeImages === 'alwaysAsk') {
const userAnswer = await this.props.dialogs.showMenu(
`${_('You are about to attach a large image (%dx%d pixels). Would you like to resize it down to %d pixels before attaching it?', dimensions.width, dimensions.height, maxSize)}\n\n${_('(You may disable this prompt in the options)')}`, [
{ text: _('Yes'), id: 'yes' },
{ text: _('No'), id: 'no' },
{ text: _('Cancel'), id: 'cancel' },
]);
if (userAnswer === 'yes') return await saveResizedImage();
if (userAnswer === 'no') return await saveOriginalImage();
if (userAnswer === 'cancel' || !userAnswer) return false;
} else if (resizeLargeImages === 'alwaysResize') {
return await saveResizedImage();
}
}
return await saveOriginalImage();
}
private async insertText(text: string) {
const newNote = { ...this.state.note };
if (this.state.mode === 'edit') {
let newText = '';
if (this.selection) {
newText = `\n${text}\n`;
const prefix = newNote.body.substring(0, this.selection.start);
const suffix = newNote.body.substring(this.selection.end);
newNote.body = `${prefix}${newText}${suffix}`;
} else {
newText = `\n${text}`;
newNote.body = `${newNote.body}\n${newText}`;
}
if (this.useEditorBeta()) {
// The beta editor needs to be explicitly informed of changes
// to the note's body
if (this.editorRef.current) {
this.editorRef.current.insertText(newText);
} else {
logger.info(`Tried to insert text ${text} to the note when the editor is not visible -- updating the note body instead.`);
}
}
} else {
newNote.body += `\n${text}`;
}
this.setState({ note: newNote });
return newNote;
}
public async attachFile(
pickerResponse: PickerResponse,
fileType: string,
): Promise<ResourceEntity|null> {
if (!pickerResponse) {
// User has cancelled
return null;
}
const localFilePath = Platform.select({
ios: decodeURI(pickerResponse.uri),
default: pickerResponse.uri,
});
let mimeType = pickerResponse.type;
if (!mimeType) {
const ext = fileExtension(localFilePath);
mimeType = mimeUtils.fromFileExtension(ext);
}
if (!mimeType && fileType === 'image') {
// Assume JPEG if we couldn't determine the file type. It seems to happen with the image picker
// when the file path is something like content://media/external/images/media/123456
// If the image is not a JPEG, something will throw an error below, but there's a good chance
// it will work.
reg.logger().info('Missing file type and could not detect it - assuming image/jpg');
mimeType = 'image/jpg';
}
reg.logger().info(`Got file: ${localFilePath}`);
reg.logger().info(`Got type: ${mimeType}`);
let resource: ResourceEntity = Resource.new();
resource.id = uuid.create();
resource.mime = mimeType;
resource.title = pickerResponse.fileName ? pickerResponse.fileName : '';
resource.file_extension = safeFileExtension(fileExtension(pickerResponse.fileName ? pickerResponse.fileName : localFilePath));
if (!resource.mime) resource.mime = 'application/octet-stream';
const targetPath = Resource.fullPath(resource);
try {
if (mimeType === 'image/jpeg' || mimeType === 'image/jpg' || mimeType === 'image/png') {
const done = await this.resizeImage(localFilePath, targetPath, mimeType);
if (!done) return null;
} else {
if (fileType === 'image' && mimeType !== 'image/svg+xml') {
await this.props.dialogs.error(_('Unsupported image type: %s', mimeType));
return null;
} else {
await shim.fsDriver().copy(localFilePath, targetPath);
const stat = await shim.fsDriver().stat(targetPath);
if (stat.size >= 200 * 1024 * 1024) {
await shim.fsDriver().remove(targetPath);
throw new Error('Resources larger than 200 MB are not currently supported as they may crash the mobile applications. The issue is being investigated and will be fixed at a later time.');
}
}
}
} catch (error) {
reg.logger().warn('Could not attach file:', error);
await this.props.dialogs.error(error.message);
return null;
}
const itDoes = await shim.fsDriver().waitTillExists(targetPath);
if (!itDoes) throw new Error(`Resource file was not created: ${targetPath}`);
const fileStat = await shim.fsDriver().stat(targetPath);
resource.size = fileStat.size;
resource = await Resource.save(resource, { isNew: true });
const resourceTag = Resource.markupTag(resource);
const newNote = await this.insertText(resourceTag);
void this.refreshResource(resource, newNote.body);
this.scheduleSave();
return resource;
}
private cameraView_onPhoto(data: CameraResult) {
void this.attachFile(
data,
'image',
);
this.setState({ showCamera: false });
}
private cameraView_onInsertBarcode = (data: string) => {
this.setState({ showCamera: false });
void this.insertText(data);
};
private cameraView_onCancel() {
this.setState({ showCamera: false });
}
private async attachNewDrawing(svgData: string) {
const filePath = `${Setting.value('resourceDir')}/saved-drawing.joplin.svg`;
await shim.fsDriver().writeFile(filePath, svgData, 'utf8');
logger.info('Saved new drawing to', filePath);
return await this.attachFile({
uri: filePath,
fileName: _('Drawing'),
}, 'image');
}
private async updateDrawing(svgData: string) {
let resource: ResourceEntity|null = this.state.imageEditorResource;
if (!resource) {
resource = await this.attachNewDrawing(svgData);
// Set resource and file path to allow
// 1. subsequent saves to update the resource
// 2. the editor to load from the resource's filepath (can happen
// if the webview is reloaded).
this.setState({
imageEditorResourceFilepath: Resource.fullPath(resource),
imageEditorResource: resource,
});
} else {
logger.info('Saving drawing to resource', resource.id);
const tempFilePath = join(Setting.value('tempDir'), uuid.createNano());
await shim.fsDriver().writeFile(tempFilePath, svgData, 'utf8');
resource = await Resource.updateResourceBlobContent(
resource.id,
tempFilePath,
);
await shim.fsDriver().remove(tempFilePath);
await this.refreshResource(resource);
}
}
private onSaveDrawing = async (svgData: string) => {
await this.updateDrawing(svgData);
};
private onCloseDrawing = () => {
this.setState({ showImageEditor: false });
};
private drawPicture_onPress = async () => {
logger.info('Showing image editor...');
this.setState({
showImageEditor: true,
imageEditorResourceFilepath: null,
imageEditorResource: null,
});
};
private async editDrawing(item: BaseItem) {
const filePath = Resource.fullPath(item);
this.setState({
showImageEditor: true,
imageEditorResourceFilepath: filePath,
imageEditorResource: item,
});
}
private onEditResource = async (message: string) => {
const messageData = /^edit:(.*)$/.exec(message);
if (!messageData) {
throw new Error('onEditResource: Error: Invalid message');
}
const resourceId = messageData[1];
const resource = await BaseItem.loadItemById(resourceId);
await Resource.requireIsReady(resource);
if (isEditableResource(resource.mime)) {
await this.editDrawing(resource);
} else {
throw new Error(_('Unable to edit resource of type %s', resource.mime));
}
};
private toggleIsTodo_onPress() {
shared.toggleIsTodo_onPress(this);
this.scheduleSave();
}
private async share_onPress() {
await Share.share({
message: `${this.state.note.title}\n\n${this.state.note.body}`,
title: this.state.note.title,
});
}
private properties_onPress() {
this.props.dispatch({ type: 'SIDE_MENU_OPEN' });
}
public async onAlarmDialogAccept(date: Date) {
if (Platform.OS === 'android') {
const response = await checkPermissions(PermissionsAndroid.PERMISSIONS.POST_NOTIFICATIONS);
// The POST_NOTIFICATIONS permission isn't supported on Android API < 33.
// (If unsupported, returns NEVER_ASK_AGAIN).
// On earlier releases, notifications should work without this permission.
if (response === PermissionsAndroid.RESULTS.DENIED) {
logger.warn('POST_NOTIFICATIONS permission was not granted');
return;
}
}
if (Platform.OS === 'web') {
alert('Warning: The due-date has been saved, but showing notifications is not supported by Joplin Web.');
}
const newNote = { ...this.state.note };
newNote.todo_due = date ? date.getTime() : 0;
await this.saveOneProperty('todo_due', date ? date.getTime() : 0);
this.setState({ alarmDialogShown: false });
}
public onAlarmDialogReject() {
this.setState({ alarmDialogShown: false });
}
private async showOnMap_onPress() {
if (!this.state.note.id) return;
const note = await Note.load(this.state.note.id);
try {
const url = Note.geolocationUrl(note);
await Linking.openURL(url);
} catch (error) {
this.props.dispatch({ type: 'SIDE_MENU_CLOSE' });
await this.props.dialogs.error(error.message);
}
}
private async showSource_onPress() {
if (!this.state.note.id) return;
const note = await Note.load(this.state.note.id);
try {
await Linking.openURL(note.source_url);
} catch (error) {
await this.props.dialogs.error(error.message);
}
}
private copyMarkdownLink_onPress() {