Skip to content

Commit ed97bed

Browse files
perf(inspector): detect, format and minify large JSON/XML cells on a worker isolate
1 parent 1d6ee75 commit ed97bed

2 files changed

Lines changed: 200 additions & 44 deletions

File tree

‎lib/features/workspace/grid_cell_popover_inspector.dart‎

Lines changed: 116 additions & 44 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import 'dart:async' show unawaited;
22
import 'dart:convert';
3+
import 'package:flutter/foundation.dart' show compute, visibleForTesting;
34
import 'package:flutter/material.dart' as material;
45
import 'package:flutter/services.dart';
56
import 'package:querya_desktop/core/editor/querya_code_editor.dart';
@@ -8,6 +9,42 @@ import 'package:querya_desktop/features/workspace/xml_html_formatter.dart';
89
import 'package:querya_desktop/shared/widgets/widgets.dart';
910
import 'package:querya_desktop/core/ui/querya_control_tokens.dart';
1011

12+
/// Text of at least this many UTF-16 units (about 256 KB) is parsed, formatted
13+
/// and minified on a worker isolate: `jsonDecode` and the XML formatter on a
14+
/// multi-megabyte cell would hold the UI thread for whole frames.
15+
@visibleForTesting
16+
int inspectorIsolateThreshold = 256 * 1024;
17+
18+
String _prettyJson(String text) =>
19+
const JsonEncoder.withIndent(' ').convert(jsonDecode(text));
20+
21+
String _compactJson(String text) => jsonEncode(jsonDecode(text));
22+
23+
String _prettyXml(String text) => XmlHtmlFormatter.format(text);
24+
25+
bool _looksLikeJson(String trimmed) =>
26+
(trimmed.startsWith('{') && trimmed.endsWith('}')) ||
27+
(trimmed.startsWith('[') && trimmed.endsWith(']'));
28+
29+
bool _looksLikeXml(String trimmed) =>
30+
trimmed.startsWith('<') && trimmed.endsWith('>');
31+
32+
/// Whether [trimmed] is valid JSON or valid XML (top-level so [compute] can run it).
33+
({bool json, bool xml}) _detectKind(String trimmed) {
34+
if (_looksLikeJson(trimmed)) {
35+
try {
36+
jsonDecode(trimmed);
37+
return (json: true, xml: false);
38+
} catch (_) {
39+
return (json: false, xml: false);
40+
}
41+
}
42+
if (_looksLikeXml(trimmed)) {
43+
return (json: false, xml: XmlHtmlFormatter.validate(trimmed) == null);
44+
}
45+
return (json: false, xml: false);
46+
}
47+
1148
/// Opens a rich modal inspector for viewing and editing large text, JSON, XML, or BLOB values.
1249
///
1350
/// **Apply** and **Ctrl/Cmd+Enter** return the edited string for local staging
@@ -100,41 +137,48 @@ class _GridCellInspectorDialogState
100137
super.dispose();
101138
}
102139

103-
void _formatJson() {
104-
try {
105-
final parsed = jsonDecode(_controller.text);
106-
final pretty = const JsonEncoder.withIndent(' ').convert(parsed);
107-
setState(() {
108-
_isNull = false;
109-
_controller.text = pretty;
110-
});
111-
} catch (_) {
112-
// Not valid JSON, keep as is
113-
}
114-
}
140+
bool _busy = false;
115141

116-
void _minifyJson() {
117-
try {
118-
final parsed = jsonDecode(_controller.text);
119-
final compact = jsonEncode(parsed);
120-
setState(() {
121-
_isNull = false;
122-
_controller.text = compact;
123-
});
124-
} catch (_) {
125-
// Not valid JSON, keep as is
142+
/// Replaces the text with `transform(text)`; a text that does not parse is
143+
/// left as it is. Past [inspectorIsolateThreshold] the work runs on a worker
144+
/// isolate, with the buttons held back meanwhile; an edit made while it ran
145+
/// wins over the result.
146+
Future<void> _rewrite(String Function(String) transform) async {
147+
if (_busy) return;
148+
final text = _controller.text;
149+
String result;
150+
if (text.length < inspectorIsolateThreshold) {
151+
try {
152+
result = transform(text);
153+
} catch (_) {
154+
return;
155+
}
156+
} else {
157+
setState(() => _busy = true);
158+
try {
159+
result = await compute(transform, text);
160+
} catch (_) {
161+
if (mounted) setState(() => _busy = false);
162+
return;
163+
}
164+
if (!mounted) return;
165+
_busy = false;
166+
if (!identical(text, _controller.text) && text != _controller.text) {
167+
setState(() {});
168+
return;
169+
}
126170
}
171+
setState(() {
172+
_isNull = false;
173+
_controller.text = result;
174+
});
127175
}
128176

129-
void _formatXml() {
130-
try {
131-
final pretty = XmlHtmlFormatter.format(_controller.text);
132-
setState(() {
133-
_isNull = false;
134-
_controller.text = pretty;
135-
});
136-
} catch (_) {}
137-
}
177+
void _formatJson() => unawaited(_rewrite(_prettyJson));
178+
179+
void _minifyJson() => unawaited(_rewrite(_compactJson));
180+
181+
void _formatXml() => unawaited(_rewrite(_prettyXml));
138182

139183
void _formatHex() {
140184
var raw = _controller.text.trim();
@@ -171,27 +215,53 @@ class _GridCellInspectorDialogState
171215

172216
// build() asks for both on every rebuild. Parsing a large cell each time
173217
// janks, so the answer is kept for the text it was computed for (the
174-
// controller hands out the same String until the text changes).
218+
// controller hands out the same String until the text changes). Text past
219+
// [inspectorIsolateThreshold] is checked on a worker isolate: the buttons
220+
// appear when it answers.
175221
String? _kindText;
176222
var _kindIsJson = false;
177223
var _kindIsXml = false;
224+
var _detecting = false;
178225

179226
void _refreshKind() {
180227
final raw = _controller.text;
181228
if (identical(raw, _kindText)) return;
182229
_kindText = raw;
183-
final text = raw.trim();
184230
_kindIsJson = false;
185231
_kindIsXml = false;
186-
if ((text.startsWith('{') && text.endsWith('}')) ||
187-
(text.startsWith('[') && text.endsWith(']'))) {
188-
try {
189-
jsonDecode(text);
190-
_kindIsJson = true;
191-
} catch (_) {}
192-
} else if (text.startsWith('<') && text.endsWith('>')) {
193-
_kindIsXml = XmlHtmlFormatter.validate(text) == null;
232+
final text = raw.trim();
233+
if (!_looksLikeJson(text) && !_looksLikeXml(text)) return;
234+
if (raw.length >= inspectorIsolateThreshold) {
235+
_detectInBackground();
236+
return;
194237
}
238+
final kind = _detectKind(text);
239+
_kindIsJson = kind.json;
240+
_kindIsXml = kind.xml;
241+
}
242+
243+
void _detectInBackground() {
244+
if (_detecting) return; // the running check re-reads the latest text
245+
final raw = _kindText;
246+
if (raw == null) return;
247+
_detecting = true;
248+
unawaited(compute(_detectKind, raw.trim()).then((kind) {
249+
_detecting = false;
250+
if (!mounted) return;
251+
if (identical(raw, _kindText)) {
252+
if (kind.json != _kindIsJson || kind.xml != _kindIsXml) {
253+
setState(() {
254+
_kindIsJson = kind.json;
255+
_kindIsXml = kind.xml;
256+
});
257+
}
258+
} else if (_kindText != null &&
259+
_kindText!.length >= inspectorIsolateThreshold) {
260+
_detectInBackground(); // edited meanwhile: check the new text
261+
}
262+
}, onError: (Object _) {
263+
_detecting = false;
264+
}));
195265
}
196266

197267
bool _isJson() {
@@ -312,14 +382,15 @@ class _GridCellInspectorDialogState
312382
QueryaButton.ghost(
313383
label: 'Format JSON',
314384
icon: material.Icons.format_align_left_rounded,
315-
onPressed: _formatJson,
385+
loading: _busy,
386+
onPressed: _busy ? null : _formatJson,
316387
size: QueryaControlSize.sm,
317388
),
318389
const Gap(6),
319390
QueryaButton.ghost(
320391
label: 'Minify',
321392
icon: material.Icons.compress_rounded,
322-
onPressed: _minifyJson,
393+
onPressed: _busy ? null : _minifyJson,
323394
size: QueryaControlSize.sm,
324395
),
325396
const Gap(6),
@@ -328,7 +399,8 @@ class _GridCellInspectorDialogState
328399
QueryaButton.ghost(
329400
label: 'Format XML',
330401
icon: material.Icons.code_rounded,
331-
onPressed: _formatXml,
402+
loading: _busy,
403+
onPressed: _busy ? null : _formatXml,
332404
size: QueryaControlSize.sm,
333405
),
334406
const Gap(6),

‎test/features/workspace/grid_cell_editor_test.dart‎

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import 'package:querya_desktop/features/workspace/grid_cell_editor.dart';
66
import 'package:querya_desktop/features/workspace/grid_cell_popover_inspector.dart';
77
import 'package:querya_desktop/core/theme/querya_theme.dart';
88
import 'package:querya_desktop/features/workspace/result_grid_view.dart';
9+
import 'package:querya_desktop/shared/widgets/querya_spinner.dart';
910
import 'package:shadcn_flutter/shadcn_flutter.dart' hide TextExtension;
1011

1112
import '../../support/querya_theme_test_shell.dart';
@@ -196,6 +197,89 @@ void main() {
196197
expect(result!.contains('"name": "querya"'), isTrue);
197198
});
198199

200+
group('text past the isolate threshold', () {
201+
final saved = inspectorIsolateThreshold;
202+
setUp(() => inspectorIsolateThreshold = 64);
203+
tearDown(() => inspectorIsolateThreshold = saved);
204+
205+
// `compute` runs on a real isolate, which the fake-async test zone does
206+
// not wait for: give it real time between pumps.
207+
Future<void> waitUntil(
208+
WidgetTester tester,
209+
bool Function() done,
210+
) async {
211+
for (var i = 0; i < 100 && !done(); i++) {
212+
await tester.runAsync(
213+
() => Future<void>.delayed(const Duration(milliseconds: 50)),
214+
);
215+
await tester.pump();
216+
}
217+
}
218+
219+
testWidgets('JSON is detected and formatted off the UI thread',
220+
(tester) async {
221+
final big =
222+
'[${List.generate(12, (i) => '{"id":$i,"v":"xxxxxxxxxx"}').join(',')}]';
223+
expect(big.length, greaterThan(inspectorIsolateThreshold));
224+
String? result;
225+
226+
await tester.pumpWidget(
227+
queryaThemeTestShell(
228+
child: material.Builder(
229+
builder: (context) => material.ElevatedButton(
230+
onPressed: () async {
231+
result = await showGridCellInspectorDialog(
232+
context: context,
233+
columnName: 'metadata',
234+
initialValue: big,
235+
rowIndex: 0,
236+
);
237+
},
238+
child: const Text('Open Dialog'),
239+
),
240+
),
241+
),
242+
);
243+
await tester.tap(find.text('Open Dialog'));
244+
await tester.pumpAndSettle();
245+
246+
// The check runs on the worker; the button shows when it answers.
247+
await waitUntil(tester, () => find.text('Format JSON').evaluate().isNotEmpty);
248+
expect(find.text('Format JSON'), findsOneWidget);
249+
250+
await tester.tap(find.text('Format JSON'));
251+
await tester.pump();
252+
await waitUntil(tester, () => find.byType(QueryaSpinner).evaluate().isEmpty);
253+
254+
await tester.tap(find.text('Apply'));
255+
await tester.pumpAndSettle();
256+
expect(result, isNotNull);
257+
expect(result!.contains('\n'), isTrue);
258+
expect(result!.contains('"id": 11'), isTrue);
259+
});
260+
261+
testWidgets('plain large text does not get JSON buttons', (tester) async {
262+
await tester.pumpWidget(
263+
queryaThemeTestShell(
264+
child: material.Builder(
265+
builder: (context) => material.ElevatedButton(
266+
onPressed: () => showGridCellInspectorDialog(
267+
context: context,
268+
columnName: 'notes',
269+
initialValue: 'x' * 200,
270+
),
271+
child: const Text('Open Dialog'),
272+
),
273+
),
274+
),
275+
);
276+
await tester.tap(find.text('Open Dialog'));
277+
await tester.pumpAndSettle();
278+
expect(find.text('Format JSON'), findsNothing);
279+
expect(find.text('Format XML'), findsNothing);
280+
});
281+
});
282+
199283
testWidgets('allows setting value to NULL in dialog', (tester) async {
200284
String? result;
201285

0 commit comments

Comments
 (0)