/
UserRulesEditor.jsx
386 lines (342 loc) · 14.3 KB
/
UserRulesEditor.jsx
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
import React, {
useState,
useContext,
useEffect,
useRef,
useCallback,
} from 'react';
import { observer } from 'mobx-react';
import { Range } from 'ace-builds';
import debounce from 'lodash/debounce';
import { SimpleRegex } from '@adguard/tsurlfilter/dist/es/simple-regex';
import { userRulesEditorStore } from './UserRulesEditorStore';
import { Editor } from '../Editor';
import { UserRulesSavingButton } from './UserRulesSavingButton';
import { reactTranslator } from '../../../../common/translators/reactTranslator';
import { Popover } from '../ui/Popover';
import { Checkbox } from '../ui/Checkbox';
import { Icon } from '../ui/Icon';
import { messenger } from '../../../services/messenger';
import { MESSAGE_TYPES, NOTIFIER_TYPES } from '../../../../common/constants';
import { HANDLER_DELAY_MS } from '../../constants';
import { handleFileUpload } from '../../../helpers';
import { log } from '../../../../common/log';
import { ToggleWrapButton } from './ToggleWrapButton';
import { exportData, ExportTypes } from '../../utils/export';
/**
* This module is placed in the common directory because it is used in the options page
* and fullscreen-user-rules page
*/
export const UserRulesEditor = observer(({ fullscreen, uiStore }) => {
const store = useContext(userRulesEditorStore);
const [userFilterEnabled, setUserFilterEnabledSettingId] = useState(false);
const editorRef = useRef(null);
const inputRef = useRef(null);
let shouldResetSize = false;
if (store.userRulesEditorPrefsDropped) {
store.setUserRulesEditorPrefsDropped(false);
shouldResetSize = true;
}
useEffect(() => {
(async () => {
await store.requestSettingsData();
setUserFilterEnabledSettingId(store.userFilterEnabled);
})();
}, [store]);
// Get initial storage content and set to the editor
useEffect(() => {
(async () => {
let editorContent = await messenger.getEditorStorageContent();
// clear editor content from storage after reading it
await messenger.setEditorStorageContent(null);
let resetInfoThatContentChanged = false;
if (!editorContent) {
const { content } = await messenger.getUserRules();
editorContent = content;
resetInfoThatContentChanged = true;
}
editorRef.current.editor.setValue(editorContent, 1);
editorRef.current.editor.session.getUndoManager().reset();
if (resetInfoThatContentChanged) {
store.setUserRulesEditorContentChangedState(false);
}
// initial export button state
const { userRules } = await messenger.sendMessage(
MESSAGE_TYPES.GET_USER_RULES_EDITOR_DATA,
);
if (userRules.length > 0) {
store.setUserRulesExportAvailableState(true);
} else {
store.setUserRulesExportAvailableState(false);
}
})();
}, [store]);
/**
* One of the reasons for request filter to update
* may be adding user rules from other places like assistant and others
* @return {Promise<void>}
*/
const handleUserFilterUpdated = useCallback(async () => {
const { userRules } = await messenger.sendMessage(
MESSAGE_TYPES.GET_USER_RULES_EDITOR_DATA,
);
if (!store.userRulesEditorContentChanged) {
if (editorRef.current) {
editorRef.current.editor.setValue(userRules, 1);
}
store.setUserRulesEditorContentChangedState(false);
await messenger.setEditorStorageContent(null);
}
// disable or enable export button
if (userRules.length > 0) {
store.setUserRulesExportAvailableState(true);
} else {
store.setUserRulesExportAvailableState(false);
}
}, [store]);
// Append listeners
useEffect(() => {
let removeListenerCallback = () => {};
(async () => {
// Subscribe to events of request filter update
// to have actual user rules in the editor
const events = [
NOTIFIER_TYPES.USER_FILTER_UPDATED,
];
removeListenerCallback = await messenger.createEventListener(
events,
async (message) => {
const { type } = message;
switch (type) {
case NOTIFIER_TYPES.USER_FILTER_UPDATED: {
await handleUserFilterUpdated();
break;
}
default: {
log.debug('Undefined message type:', type);
break;
}
}
},
);
})();
return () => {
removeListenerCallback();
};
}, [handleUserFilterUpdated]);
// save editor content to the storage after close of fullscreen
useEffect(() => {
if (fullscreen) {
const beforeUnloadListener = async () => {
if (store.userRulesEditorContentChanged) {
// send content to the storage only before switching editors
const content = editorRef.current.editor.session.getValue();
await messenger.setEditorStorageContent(content);
}
};
window.addEventListener('beforeunload', beforeUnloadListener);
}
}, [store.userRulesEditorContentChanged, fullscreen]);
// subscribe to editor changes, to update editor storage content
useEffect(() => {
const changeHandler = () => {
store.setUserRulesEditorContentChangedState(true);
};
editorRef.current.editor.session.on('change', changeHandler);
}, [store]);
// set initial wrap mode
useEffect(() => {
editorRef.current.editor.session.setUseWrapMode(store.userRulesEditorWrapState);
}, [store.userRulesEditorWrapState]);
const inputChangeHandler = async (event) => {
event.persist();
const file = event.target.files[0];
try {
const rawNewRules = await handleFileUpload(file, 'txt');
const trimmedNewRules = rawNewRules.trim();
if (trimmedNewRules.length < 0) {
return;
}
const oldRulesString = editorRef.current.editor.getValue();
const oldRules = oldRulesString.split('\n');
const newRules = trimmedNewRules.split('\n');
const uniqNewRules = newRules.filter((newRule) => {
const trimmedNewRule = newRule.trim();
if (trimmedNewRule.length === 0) {
return true;
}
const isInOldRules = oldRules.some((oldRule) => oldRule === trimmedNewRule);
return !isInOldRules;
});
const rulesUnion = [...oldRules, ...uniqNewRules];
const rulesUnionString = rulesUnion.join('\n').trim();
if (oldRulesString !== rulesUnionString) {
editorRef.current.editor.setValue(rulesUnionString, 1);
await store.saveUserRules(rulesUnionString);
}
} catch (e) {
log.debug(e.message);
if (uiStore?.addNotification) {
uiStore.addNotification({ description: e.message });
}
}
// eslint-disable-next-line no-param-reassign
event.target.value = '';
};
const importClickHandler = (e) => {
e.preventDefault();
inputRef.current.click();
};
const saveClickHandler = async () => {
if (store.userRulesEditorContentChanged) {
const value = editorRef.current.editor.getValue();
await store.saveUserRules(value);
}
};
const shortcuts = [
{
name: 'save',
bindKey: { win: 'Ctrl-S', mac: 'Command-S' },
exec: saveClickHandler,
},
{
name: 'togglecomment',
bindKey: { win: 'Ctrl-/', mac: 'Command-/' },
exec: (editor) => {
const selection = editor.getSelection();
const ranges = selection.getAllRanges();
const rowsSelected = ranges
.map((range) => {
const [start, end] = [range.start.row, range.end.row];
return Array.from({ length: end - start + 1 }, (_, idx) => idx + start);
})
.flat();
const allRowsCommented = rowsSelected.every((row) => {
const rowLine = editor.session.getLine(row);
return rowLine.trim().startsWith(SimpleRegex.MASK_COMMENT);
});
rowsSelected.forEach((row) => {
const rawLine = editor.session.getLine(row);
// if all lines start with comment mark we remove it
if (allRowsCommented) {
const lineWithRemovedComment = rawLine.replace(SimpleRegex.MASK_COMMENT, '');
editor.session.replace(new Range(row, 0, row), lineWithRemovedComment);
// otherwise we add it
} else {
editor.session.insert({ row, column: 0 }, SimpleRegex.MASK_COMMENT);
}
});
},
},
];
const exportClickHandler = () => {
exportData(ExportTypes.USER_FILTER);
};
// We set wrap mode directly in order to avoid editor re-rendering
// Otherwise editor would remove all unsaved content
const toggleWrap = () => {
const toggledWrapMode = !store.userRulesEditorWrapState;
editorRef.current.editor.session.setUseWrapMode(toggledWrapMode);
store.toggleUserRulesEditorWrapMode(toggledWrapMode);
};
const openEditorFullscreen = async () => {
// send dirty content to the storage only before switching editors
if (store.userRulesEditorContentChanged) {
const content = editorRef.current.editor.session.getValue();
await messenger.setEditorStorageContent(content);
}
await messenger.sendMessage(MESSAGE_TYPES.OPEN_FULLSCREEN_USER_RULES);
};
const closeEditorFullscreen = async () => {
// send dirty content to the storage only before switching editors
if (store.userRulesEditorContentChanged) {
const content = editorRef.current.editor.session.getValue();
await messenger.setEditorStorageContent(content);
}
window.close();
};
const handleUserRulesToggle = debounce((e) => {
store.updateSetting(e.id, e.data);
}, HANDLER_DELAY_MS);
const fullscreenTooltipText = fullscreen
? reactTranslator.getMessage('options_editor_close_fullscreen_button_tooltip')
: reactTranslator.getMessage('options_editor_open_fullscreen_button_tooltip');
return (
<>
<Editor
name="user-rules"
editorRef={editorRef}
shortcuts={shortcuts}
fullscreen={fullscreen}
shouldResetSize={shouldResetSize}
highlightRules
/>
<div className="actions actions--divided">
<div className="actions__group">
{
fullscreen && (
<>
<div className="title__inner">
<h2 className="title">{reactTranslator.getMessage('fullscreen_user_rules_title')}</h2>
</div>
<Checkbox
id="user-filter-enabled"
handler={handleUserRulesToggle}
value={userFilterEnabled}
/>
</>
)
}
<UserRulesSavingButton onClick={saveClickHandler} />
<input
type="file"
id="inputEl"
accept="text/plain"
ref={inputRef}
onChange={inputChangeHandler}
style={{ display: 'none' }}
/>
<button
type="button"
className="button button--m button--transparent actions__btn"
onClick={importClickHandler}
>
{reactTranslator.getMessage('options_userfilter_import')}
</button>
<button
type="button"
className="button button--m button--transparent actions__btn"
onClick={exportClickHandler}
disabled={!store.userRulesExportAvailable}
>
{reactTranslator.getMessage('options_userfilter_export')}
</button>
</div>
<div className="actions__group">
<ToggleWrapButton onClick={toggleWrap} />
<Popover text={fullscreenTooltipText}>
{
fullscreen ? (
<button
type="button"
className="actions__btn actions__btn--icon"
onClick={closeEditorFullscreen}
>
<Icon classname="icon--extend" id="#reduce" />
</button>
) : (
<button
type="button"
className="actions__btn actions__btn--icon"
onClick={openEditorFullscreen}
>
<Icon classname="icon--extend" id="#extend" />
</button>
)
}
</Popover>
</div>
</div>
</>
);
});