-
Notifications
You must be signed in to change notification settings - Fork 46
/
code_controller.dart
432 lines (351 loc) · 11.2 KB
/
code_controller.dart
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
import 'dart:math';
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:highlight/highlight_core.dart';
import '../code_modifiers/close_block_code_modifier.dart';
import '../code_modifiers/code_modifier.dart';
import '../code_modifiers/indent_code_modifier.dart';
import '../code_modifiers/tab_code_modifier.dart';
import '../code_theme/code_theme.dart';
import '../code_theme/code_theme_data.dart';
import '../wip/autocomplete/popup_controller.dart';
import '../wip/autocomplete/suggestion.dart';
import '../wip/autocomplete/suggestion_generator.dart';
import 'editor_params.dart';
const _middleDot = '·';
class CodeController extends TextEditingController {
Mode? _language;
/// A highlight language to parse the text with
Mode? get language => _language;
set language(Mode? language) {
if (language == _language) {
return;
}
if (language != null) {
_languageId = _genId();
highlight.registerLanguage(_languageId, language);
}
_language = language;
notifyListeners();
}
Map<String, TextStyle>? _theme;
/// The theme to apply to the [language] parsing result
@Deprecated('Use CodeTheme widget to provide theme to CodeField.')
Map<String, TextStyle>? get theme => _theme;
@Deprecated('Use CodeTheme widget to provide theme to CodeField.')
set theme(Map<String, TextStyle>? theme) {
if (theme == _theme) {
return;
}
_theme = theme;
notifyListeners();
}
/// A map of specific regexes to style
final Map<String, TextStyle>? patternMap;
/// A map of specific keywords to style
final Map<String, TextStyle>? stringMap;
/// Common editor params such as the size of a tab in spaces
///
/// Will be exposed to all [modifiers]
final EditorParams params;
/// A list of code modifiers to dynamically update the code upon certain keystrokes
final List<CodeModifier> modifiers;
/// On web, replace spaces with invisible dots “·” to fix the current issue with spaces
///
/// https://github.com/flutter/flutter/issues/77929
final bool webSpaceFix;
/// onChange callback, called whenever the content is changed
final void Function(String)? onChange;
/* Computed members */
String _languageId = _genId();
String get languageId => _languageId;
final styleList = <TextStyle>[];
final modifierMap = <String, CodeModifier>{};
bool isPopupShown = false;
RegExp? styleRegExp;
late PopupController popupController;
SuggestionGenerator? suggestionGenerator;
CodeController({
String? text,
Mode? language,
@Deprecated('Use CodeTheme widget to provide theme to CodeField.')
Map<String, TextStyle>? theme,
this.patternMap,
this.stringMap,
this.params = const EditorParams(),
this.modifiers = const [
IntendModifier(),
CloseBlockModifier(),
TabModifier(),
],
this.webSpaceFix = true,
this.onChange,
}) : _theme = theme,
super(text: text) {
this.language = language;
// Create modifier map
for (final el in modifiers) {
modifierMap[el.char] = el;
}
suggestionGenerator = SuggestionGenerator(
'language_id'); // TODO: replace string with some generated value for current language id
popupController = PopupController(onCompletionSelected: insertSelectedWord);
}
/// Sets a specific cursor position in the text
void setCursor(int offset) {
selection = TextSelection.collapsed(offset: offset);
}
/// Replaces the current [selection] by [str]
void insertStr(String str) {
final sel = selection;
text = text.replaceRange(selection.start, selection.end, str);
final len = str.length;
selection = sel.copyWith(
baseOffset: sel.start + len,
extentOffset: sel.start + len,
);
}
/// Remove the char just before the cursor or the selection
void removeChar() {
if (selection.start < 1) {
return;
}
final sel = selection;
text = text.replaceRange(selection.start - 1, selection.start, '');
selection = sel.copyWith(
baseOffset: sel.start - 1,
extentOffset: sel.start - 1,
);
}
/// Remove the selected text
void removeSelection() {
final sel = selection;
text = text.replaceRange(selection.start, selection.end, '');
selection = sel.copyWith(
baseOffset: sel.start,
extentOffset: sel.start,
);
}
/// Remove the selection or last char if the selection is empty
void backspace() {
if (selection.start < selection.end) {
removeSelection();
} else {
removeChar();
}
}
KeyEventResult onKey(RawKeyEvent event) {
if (event.isKeyPressed(LogicalKeyboardKey.tab)) {
text = text.replaceRange(selection.start, selection.end, '\t');
return KeyEventResult.handled;
}
if (popupController.isPopupShown) {
if (event.isKeyPressed(LogicalKeyboardKey.arrowUp)) {
popupController.scrollByArrow(ScrollDirection.up);
return KeyEventResult.handled;
}
if (event.isKeyPressed(LogicalKeyboardKey.arrowDown)) {
popupController.scrollByArrow(ScrollDirection.down);
return KeyEventResult.handled;
}
if (event.isKeyPressed(LogicalKeyboardKey.enter)) {
insertSelectedWord();
return KeyEventResult.handled;
}
}
return KeyEventResult.ignored;
}
/// Inserts the word selected from the list of completions
void insertSelectedWord() {
final previousSelection = selection;
String selectedWord = popupController.getSelectedWord();
int startPosition = selection.baseOffset -
suggestionGenerator!.getCurrentWordPrefix().length;
text = text.replaceRange(startPosition, selection.baseOffset, selectedWord);
selection = previousSelection.copyWith(
baseOffset: startPosition + selectedWord.length,
extentOffset: startPosition + selectedWord.length,
);
popupController.hide();
}
/// See webSpaceFix
static String _spacesToMiddleDots(String str) {
return str.replaceAll(' ', _middleDot);
}
/// See webSpaceFix
static String _middleDotsToSpaces(String str) {
return str.replaceAll(_middleDot, ' ');
}
/// Get untransformed text
/// See webSpaceFix
String get rawText {
if (!_webSpaceFix) {
return super.text;
}
return _middleDotsToSpaces(super.text);
}
// Private methods
bool get _webSpaceFix => kIsWeb && webSpaceFix;
static String _genId() {
const chars = 'abcdefghijklmnopqrstuvwxyz1234567890';
final rnd = Random();
return String.fromCharCodes(
Iterable.generate(
10,
(_) => chars.codeUnitAt(rnd.nextInt(chars.length)),
),
);
}
int? _insertedLoc(String a, String b) {
final sel = selection;
if (a.length + 1 != b.length || sel.start != sel.end) {
return null;
}
return sel.start;
}
@override
set value(TextEditingValue newValue) {
final loc = _insertedLoc(text, newValue.text);
if (loc != null) {
final char = newValue.text[loc];
final modifier = modifierMap[char];
final val = modifier?.updateString(rawText, selection, params);
if (val != null) {
// Update newValue
newValue = newValue.copyWith(
text: val.text,
selection: val.selection,
);
}
}
bool hasTextChanged = newValue.text != super.value.text;
bool hasSelectionChanged = newValue.selection != super.value.selection;
//Because of this part of code ctrl + z dont't work. But maybe it's important, so please don't delete.
// Now fix the textfield for web
// if (_webSpaceFix) {
// newValue = newValue.copyWith(text: _spacesToMiddleDots(newValue.text));
// }
onChange?.call(
_webSpaceFix ? _middleDotsToSpaces(newValue.text) : newValue.text,
);
super.value = newValue;
if (hasTextChanged) {
generateSuggestions();
} else if (hasSelectionChanged) {
popupController.hide();
}
}
TextSpan _processPatterns(String text, TextStyle? style) {
final children = <TextSpan>[];
text.splitMapJoin(
styleRegExp!,
onMatch: (Match m) {
if (styleList.isEmpty) {
return '';
}
int idx;
for (idx = 1;
idx < m.groupCount &&
idx <= styleList.length &&
m.group(idx) == null;
idx++) {}
children.add(TextSpan(
text: m[0],
style: styleList[idx - 1],
));
return '';
},
onNonMatch: (String span) {
children.add(TextSpan(text: span, style: style));
return '';
},
);
return TextSpan(style: style, children: children);
}
TextSpan _processLanguage(
String text,
CodeThemeData? widgetTheme,
TextStyle? style,
) {
final rawText = _webSpaceFix ? _middleDotsToSpaces(text) : text;
final result = highlight.parse(rawText, language: _languageId);
final nodes = result.nodes;
final children = <TextSpan>[];
var currentSpans = children;
final stack = <List<TextSpan>>[];
void _traverse(Node node) {
var val = node.value;
final nodeChildren = node.children;
final nodeStyle =
widgetTheme?.styles[node.className] ?? _theme?[node.className];
if (val != null) {
if (_webSpaceFix) {
val = _spacesToMiddleDots(val);
}
var child = TextSpan(text: val, style: nodeStyle);
if (styleRegExp != null) {
child = _processPatterns(val, nodeStyle);
}
currentSpans.add(child);
} else if (nodeChildren != null) {
List<TextSpan> tmp = [];
currentSpans.add(TextSpan(
children: tmp,
style: nodeStyle,
));
stack.add(currentSpans);
currentSpans = tmp;
for (final n in nodeChildren) {
_traverse(n);
if (n == nodeChildren.last) {
currentSpans = stack.isEmpty ? children : stack.removeLast();
}
}
}
}
nodes?.forEach(_traverse);
return TextSpan(style: style, children: children);
}
void generateSuggestions() {
List<Suggestion> suggestions = suggestionGenerator!.getSuggestions(
text,
selection.start,
);
if (suggestions.isNotEmpty) {
popupController.show(suggestions);
} else {
popupController.hide();
}
}
@override
TextSpan buildTextSpan({
required BuildContext context,
TextStyle? style,
bool? withComposing,
}) {
// Retrieve pattern regexp
final patternList = <String>[];
if (_webSpaceFix) {
patternList.add('($_middleDot)');
styleList.add(const TextStyle(color: Colors.transparent));
}
if (stringMap != null) {
patternList.addAll(stringMap!.keys.map((e) => r'(\b' + e + r'\b)'));
styleList.addAll(stringMap!.values);
}
if (patternMap != null) {
patternList.addAll(patternMap!.keys.map((e) => '($e)'));
styleList.addAll(patternMap!.values);
}
styleRegExp = RegExp(patternList.join('|'), multiLine: true);
// Return parsing
if (_language != null) {
return _processLanguage(text, CodeTheme.of(context), style);
}
if (styleRegExp != null) {
return _processPatterns(text, style);
}
return TextSpan(text: text, style: style);
}
}