Scroll: the Flutter operator console for the DBBASIC Object Server, for people building alongside AI agents.

0 downloads

dbbasic-scroll/lib/schema_form.dart
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-scroll.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-scroll.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-scroll.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

quellhorst Extension fields + schema conflict field names e8a817f 4 months, 1 week ago History
schema_form.dart · 20.1 KB · 611 lines
1import 'package:flutter/material.dart';
2
3import 'api.dart';
4
5/// Parsed view of the schema form contract (docs/schema-forms.md on the
6/// object server). Schemas declare semantics, never widgets — this file maps
7/// those semantics onto Scroll's idiom (dropdowns, pickers, switches).
8
9/// Boolean record fields store canonically as "true"/"false" strings; older
10/// rows and raw-JSON writes may hold real booleans or other spellings.
11bool schemaBoolIsTrue(dynamic value) {
12 if (value is bool) return value;
13 final text = value?.toString().trim().toLowerCase();
14 return text == 'true' || text == '1' || text == 'yes';
15}
16
17class SchemaFieldSpec {
18 SchemaFieldSpec({
19 required this.name,
20 required this.label,
21 required this.type,
22 required this.required,
23 required this.readOnly,
24 required this.enumValues,
25 required this.relationCollection,
26 required this.relationDisplayField,
27 required this.defaultValue,
28 required this.placeholder,
29 required this.help,
30 required this.validation,
31 required this.transitions,
32 });
33
34 final String name;
35 final String label;
36 final String type;
37 final bool required;
38 final bool readOnly;
39 final List<String> enumValues;
40 final String? relationCollection;
41 final String relationDisplayField;
42 final dynamic defaultValue;
43 final String? placeholder;
44 final String? help;
45 final Map<String, dynamic> validation;
46
47 /// Enum lifecycle map ({state: [allowed next states]}), enforced on record
48 /// update server-side. A value missing from the map is terminal.
49 final Map<String, List<String>> transitions;
50
51 bool get isEnum => enumValues.isNotEmpty;
52 bool get hasTransitions => transitions.isNotEmpty;
53
54 /// The enum values legal from [current]: the current state plus its
55 /// allowed moves. Without a transitions map (or before a value exists,
56 /// i.e. on create) every enum value is offered.
57 List<String> allowedEnumValues(String? current) {
58 if (!hasTransitions || current == null || current.isEmpty) {
59 return enumValues;
60 }
61 final moves = transitions[current] ?? const <String>[];
62 return [current, ...moves.where((move) => move != current)];
63 }
64
65 bool get isRelation =>
66 relationCollection != null && relationCollection!.isNotEmpty;
67 bool get isBoolean => type == 'boolean' || type == 'bool';
68 bool get isInteger => type == 'integer' || type == 'int';
69 bool get isNumber => type == 'number' || type == 'float' || type == 'double';
70 bool get isDate => type == 'date';
71 bool get isDateTime => type == 'datetime' || type == 'timestamp';
72 // 'text' is the plain string type in the schema vocabulary; only
73 // 'textarea' asks for a multiline control.
74 bool get isMultiline => type == 'textarea';
75
76 static SchemaFieldSpec from(Map<String, dynamic> raw) {
77 final name = (raw['name'] ?? raw['field'] ?? '').toString();
78 final relation = raw['relation'] ?? raw['references'] ?? raw['ref'];
79 String? relationCollection;
80 var relationDisplayField = 'name';
81 if (relation is String && relation.trim().isNotEmpty) {
82 relationCollection = relation.trim();
83 } else if (relation is Map) {
84 relationCollection = relation['collection']?.toString();
85 final display = relation['display_field']?.toString();
86 if (display != null && display.isNotEmpty) {
87 relationDisplayField = display;
88 }
89 }
90 final enumRaw = raw['enum'] ?? raw['choices'] ?? raw['options'];
91 final type = (raw['type'] ?? raw['field_type'] ?? 'string')
92 .toString()
93 .toLowerCase();
94 return SchemaFieldSpec(
95 name: name,
96 label: (raw['label'] ?? _titleCase(name)).toString(),
97 type: type,
98 required: raw['required'] == true,
99 readOnly:
100 raw['read_only'] == true ||
101 raw['readonly'] == true ||
102 raw['computed'] == true ||
103 type == 'computed',
104 enumValues: enumRaw is List
105 ? enumRaw.map((value) => value.toString()).toList()
106 : const [],
107 relationCollection: relationCollection,
108 relationDisplayField: relationDisplayField,
109 defaultValue: raw['default'],
110 placeholder: raw['placeholder']?.toString(),
111 help: (raw['help'] ?? raw['description'])?.toString(),
112 validation: raw['validation'] is Map
113 ? Map<String, dynamic>.from(raw['validation'] as Map)
114 : const {},
115 transitions: raw['transitions'] is Map
116 ? (raw['transitions'] as Map).map(
117 (state, moves) => MapEntry(
118 state.toString(),
119 moves is List
120 ? moves.map((move) => move.toString()).toList()
121 : const <String>[],
122 ),
123 )
124 : const {},
125 );
126 }
127
128 static String _titleCase(String value) {
129 return value
130 .replaceAll('_', ' ')
131 .split(' ')
132 .where((part) => part.isNotEmpty)
133 .map((part) => '${part[0].toUpperCase()}${part.substring(1)}')
134 .join(' ');
135 }
136}
137
138class SchemaFormSpec {
139 SchemaFormSpec({
140 required this.fields,
141 required this.listMode,
142 required this.listFields,
143 });
144
145 final List<SchemaFieldSpec> fields;
146 final String listMode; // table | cards | feed
147 final List<String> listFields;
148
149 bool get hasFields => fields.isNotEmpty;
150
151 static final SchemaFormSpec empty = SchemaFormSpec(
152 fields: const [],
153 listMode: 'table',
154 listFields: const [],
155 );
156
157 /// Accepts either the schema document itself or a detail payload that
158 /// nests it under `schema`.
159 static SchemaFormSpec fromSchema(Map<String, dynamic>? detail) {
160 if (detail == null) return empty;
161 final schema = detail['schema'] is Map
162 ? Map<String, dynamic>.from(detail['schema'] as Map)
163 : detail;
164
165 final rawFields = schema['fields'];
166 final specs = <SchemaFieldSpec>[];
167 if (rawFields is List) {
168 for (final item in rawFields) {
169 if (item is Map) {
170 final spec = SchemaFieldSpec.from(Map<String, dynamic>.from(item));
171 if (spec.name.isNotEmpty) specs.add(spec);
172 }
173 }
174 } else if (rawFields is Map) {
175 rawFields.forEach((key, value) {
176 final map = value is Map
177 ? Map<String, dynamic>.from(value)
178 : <String, dynamic>{};
179 map['name'] = key.toString();
180 final spec = SchemaFieldSpec.from(map);
181 if (spec.name.isNotEmpty) specs.add(spec);
182 });
183 }
184
185 // forms.default.fields declares operator-chosen field order.
186 final forms = schema['forms'];
187 if (forms is Map && forms['default'] is Map) {
188 final order = (forms['default'] as Map)['fields'];
189 if (order is List && order.isNotEmpty) {
190 final rank = <String, int>{
191 for (var i = 0; i < order.length; i++) order[i].toString(): i,
192 };
193 specs.sort((a, b) {
194 final ra = rank[a.name] ?? (rank.length + specs.indexOf(a));
195 final rb = rank[b.name] ?? (rank.length + specs.indexOf(b));
196 return ra.compareTo(rb);
197 });
198 }
199 }
200
201 var listMode = 'table';
202 var listFields = const <String>[];
203 final views = schema['views'];
204 if (views is Map) {
205 final mode = views['list_mode']?.toString();
206 if (mode != null && mode.isNotEmpty) listMode = mode;
207 final fields = views['list_fields'];
208 if (fields is List) {
209 listFields = fields.map((f) => f.toString()).toList();
210 }
211 }
212
213 return SchemaFormSpec(
214 fields: specs,
215 listMode: listMode,
216 listFields: listFields,
217 );
218 }
219}
220
221/// Sentinel returned when the operator asks to edit the record as raw JSON
222/// instead of through the generated form.
223const schemaFormRawJsonRequested = '__schema_form_raw_json__';
224
225/// Shows a form generated from [spec]. Returns the record payload to write,
226/// [schemaFormRawJsonRequested] if the operator wants the raw JSON editor,
227/// or null on cancel.
228Future<dynamic> showSchemaRecordFormDialog(
229 BuildContext context, {
230 required String collection,
231 required SchemaFormSpec spec,
232 Map<String, dynamic>? initial,
233}) {
234 return showDialog<dynamic>(
235 context: context,
236 builder: (dialogContext) => _SchemaRecordFormDialog(
237 collection: collection,
238 spec: spec,
239 initial: initial,
240 ),
241 );
242}
243
244class _SchemaRecordFormDialog extends StatefulWidget {
245 const _SchemaRecordFormDialog({
246 required this.collection,
247 required this.spec,
248 this.initial,
249 });
250
251 final String collection;
252 final SchemaFormSpec spec;
253 final Map<String, dynamic>? initial;
254
255 @override
256 State<_SchemaRecordFormDialog> createState() =>
257 _SchemaRecordFormDialogState();
258}
259
260class _SchemaRecordFormDialogState extends State<_SchemaRecordFormDialog> {
261 final Map<String, TextEditingController> _text = {};
262 final Map<String, String?> _enums = {};
263 final Map<String, String?> _relations = {};
264 final Map<String, bool> _booleans = {};
265 final Map<String, String> _fieldErrors = {};
266 final Map<String, List<Map<String, dynamic>>> _relationOptions = {};
267 final Set<String> _relationsLoading = {};
268 final ScrollController _scrollController = ScrollController();
269
270 bool get _isEdit => widget.initial != null;
271
272 @override
273 void initState() {
274 super.initState();
275 for (final field in widget.spec.fields) {
276 if (field.readOnly) continue;
277 var initial = widget.initial?[field.name] ?? field.defaultValue;
278 // Owner-scoped app collections require owner_id == session user on
279 // create; prefill it so the server-enforced value is the starting one.
280 if (!_isEdit && initial == null && field.name == 'owner_id') {
281 initial = ScrollAPI().sessionUserId;
282 }
283 if (field.isBoolean) {
284 _booleans[field.name] = schemaBoolIsTrue(initial);
285 } else if (field.isEnum) {
286 final value = initial?.toString();
287 _enums[field.name] = field.enumValues.contains(value) ? value : null;
288 } else if (field.isRelation) {
289 _relations[field.name] = initial?.toString();
290 _loadRelationOptions(field);
291 } else {
292 _text[field.name] = TextEditingController(
293 text: initial?.toString() ?? '',
294 );
295 }
296 }
297 }
298
299 @override
300 void dispose() {
301 for (final controller in _text.values) {
302 controller.dispose();
303 }
304 _scrollController.dispose();
305 super.dispose();
306 }
307
308 Future<void> _loadRelationOptions(SchemaFieldSpec field) async {
309 final collection = field.relationCollection;
310 if (collection == null || _relationsLoading.contains(field.name)) return;
311 _relationsLoading.add(field.name);
312 final records = await ScrollAPI().listAdminCollectionRecords(
313 collection,
314 limit: 100,
315 );
316 if (!mounted) return;
317 setState(() {
318 _relationOptions[field.name] = [
319 for (final record in records)
320 if (record is Map)
321 Map<String, dynamic>.from(
322 record.map((k, v) => MapEntry(k.toString(), v)),
323 ),
324 ];
325 });
326 }
327
328 String _relationLabel(SchemaFieldSpec field, Map<String, dynamic> record) {
329 final display = record[field.relationDisplayField];
330 final id = _recordId(record);
331 if (display != null && display.toString().trim().isNotEmpty) {
332 return '${display.toString()} ($id)';
333 }
334 return id;
335 }
336
337 String _recordId(Map<String, dynamic> record) {
338 final raw =
339 record['id'] ?? record['record_id'] ?? record['key'] ?? record['name'];
340 return raw?.toString() ?? '';
341 }
342
343 Map<String, dynamic>? _buildPayload() {
344 final payload = <String, dynamic>{};
345 final errors = <String, String>{};
346 for (final field in widget.spec.fields) {
347 if (field.readOnly) continue;
348 dynamic value;
349 if (field.isBoolean) {
350 // Booleans store canonically as "true"/"false" strings server-side.
351 value = (_booleans[field.name] ?? false) ? 'true' : 'false';
352 } else if (field.isEnum) {
353 value = _enums[field.name];
354 } else if (field.isRelation) {
355 value = _relations[field.name];
356 } else {
357 final text = _text[field.name]?.text.trim() ?? '';
358 if (text.isEmpty) {
359 value = null;
360 } else if (field.isInteger) {
361 value = int.tryParse(text);
362 if (value == null) errors[field.name] = 'Must be an integer';
363 } else if (field.isNumber) {
364 value = num.tryParse(text);
365 if (value == null) errors[field.name] = 'Must be a number';
366 } else {
367 value = text;
368 }
369 }
370
371 final missing =
372 value == null || (value is String && value.trim().isEmpty);
373 if (field.required && missing && !errors.containsKey(field.name)) {
374 errors[field.name] = 'Required';
375 }
376
377 if (!missing) {
378 payload[field.name] = value;
379 } else if (_isEdit && widget.initial!.containsKey(field.name)) {
380 // Cleared on edit — send an explicit null so the server clears it.
381 payload[field.name] = null;
382 }
383 }
384 if (errors.isNotEmpty) {
385 setState(() {
386 _fieldErrors
387 ..clear()
388 ..addAll(errors);
389 });
390 return null;
391 }
392 return payload;
393 }
394
395 Future<void> _pickDate(SchemaFieldSpec field) async {
396 final controller = _text[field.name];
397 if (controller == null) return;
398 final now = DateTime.now();
399 final current = DateTime.tryParse(controller.text) ?? now;
400 final picked = await showDatePicker(
401 context: context,
402 initialDate: current,
403 firstDate: DateTime(now.year - 20),
404 lastDate: DateTime(now.year + 20),
405 );
406 if (picked == null) return;
407 controller.text = field.isDateTime
408 ? picked.toUtc().toIso8601String()
409 : '${picked.year.toString().padLeft(4, '0')}-'
410 '${picked.month.toString().padLeft(2, '0')}-'
411 '${picked.day.toString().padLeft(2, '0')}';
412 }
413
414 Widget _buildField(SchemaFieldSpec field) {
415 final error = _fieldErrors[field.name];
416 final label = field.required ? '${field.label} *' : field.label;
417
418 if (field.readOnly) {
419 final value = widget.initial?[field.name];
420 if (value == null) return const SizedBox.shrink();
421 return Padding(
422 padding: const EdgeInsets.only(bottom: 12),
423 child: InputDecorator(
424 decoration: InputDecoration(
425 border: const OutlineInputBorder(),
426 labelText: '${field.label} (read only)',
427 isDense: true,
428 ),
429 child: Text(value.toString(), style: const TextStyle(fontSize: 13)),
430 ),
431 );
432 }
433
434 if (field.isBoolean) {
435 return Padding(
436 padding: const EdgeInsets.only(bottom: 12),
437 child: SwitchListTile(
438 contentPadding: EdgeInsets.zero,
439 dense: true,
440 title: Text(label, style: const TextStyle(fontSize: 13)),
441 subtitle: field.help == null
442 ? null
443 : Text(field.help!, style: const TextStyle(fontSize: 11)),
444 value: _booleans[field.name] ?? false,
445 onChanged: (value) => setState(() => _booleans[field.name] = value),
446 ),
447 );
448 }
449
450 if (field.isEnum) {
451 // With a transitions map, edits may only move from the record's
452 // stored state to its allowed next states (server-enforced).
453 final storedState = _isEdit
454 ? widget.initial![field.name]?.toString()
455 : null;
456 final values = field.allowedEnumValues(storedState);
457 final terminal =
458 field.hasTransitions && storedState != null && values.length == 1;
459 var helper = field.help;
460 if (terminal) {
461 helper = '"$storedState" is a terminal state';
462 } else if (field.hasTransitions && storedState != null) {
463 helper = helper ?? 'Allowed moves from "$storedState"';
464 }
465 return Padding(
466 padding: const EdgeInsets.only(bottom: 12),
467 child: DropdownButtonFormField<String>(
468 initialValue: _enums[field.name],
469 decoration: InputDecoration(
470 border: const OutlineInputBorder(),
471 labelText: label,
472 helperText: helper,
473 errorText: error,
474 isDense: true,
475 ),
476 items: [
477 if (!field.required)
478 const DropdownMenuItem<String>(
479 value: null,
480 child: Text('—', style: TextStyle(color: Colors.white38)),
481 ),
482 ...values.map(
483 (value) =>
484 DropdownMenuItem<String>(value: value, child: Text(value)),
485 ),
486 ],
487 onChanged: terminal
488 ? null
489 : (value) => setState(() => _enums[field.name] = value),
490 ),
491 );
492 }
493
494 if (field.isRelation) {
495 final options = _relationOptions[field.name];
496 final selected = _relations[field.name];
497 final knownIds = options?.map(_recordId).toSet() ?? const <String>{};
498 return Padding(
499 padding: const EdgeInsets.only(bottom: 12),
500 child: DropdownButtonFormField<String>(
501 initialValue: knownIds.contains(selected) ? selected : null,
502 decoration: InputDecoration(
503 border: const OutlineInputBorder(),
504 labelText: label,
505 helperText:
506 field.help ??
507 'References ${field.relationCollection} records'
508 '${options == null ? ' (loading…)' : ''}',
509 errorText: error,
510 isDense: true,
511 ),
512 items: [
513 if (!field.required)
514 const DropdownMenuItem<String>(
515 value: null,
516 child: Text('—', style: TextStyle(color: Colors.white38)),
517 ),
518 ...?options?.map(
519 (record) => DropdownMenuItem<String>(
520 value: _recordId(record),
521 child: Text(
522 _relationLabel(field, record),
523 overflow: TextOverflow.ellipsis,
524 ),
525 ),
526 ),
527 ],
528 onChanged: (value) => setState(() => _relations[field.name] = value),
529 ),
530 );
531 }
532
533 final controller = _text[field.name];
534 final maxLength = (field.validation['max_length'] as num?)?.toInt();
535 return Padding(
536 padding: const EdgeInsets.only(bottom: 12),
537 child: TextField(
538 controller: controller,
539 maxLines: field.isMultiline ? 4 : 1,
540 maxLength: maxLength,
541 keyboardType: field.isInteger || field.isNumber
542 ? const TextInputType.numberWithOptions(decimal: true)
543 : null,
544 decoration: InputDecoration(
545 border: const OutlineInputBorder(),
546 labelText: label,
547 hintText: field.placeholder,
548 helperText: field.help,
549 errorText: error,
550 isDense: true,
551 counterText: maxLength == null ? null : '',
552 suffixIcon: field.isDate || field.isDateTime
553 ? IconButton(
554 icon: const Icon(Icons.calendar_today_outlined, size: 16),
555 onPressed: () => _pickDate(field),
556 )
557 : null,
558 ),
559 ),
560 );
561 }
562
563 @override
564 Widget build(BuildContext context) {
565 return AlertDialog(
566 title: Text(
567 _isEdit
568 ? 'Edit ${widget.collection} record'
569 : 'New ${widget.collection} record',
570 ),
571 content: SizedBox(
572 width: 520,
573 child: ConstrainedBox(
574 constraints: const BoxConstraints(maxHeight: 520),
575 child: Scrollbar(
576 controller: _scrollController,
577 thumbVisibility: true,
578 child: SingleChildScrollView(
579 controller: _scrollController,
580 padding: const EdgeInsets.only(right: 12),
581 child: Column(
582 mainAxisSize: MainAxisSize.min,
583 crossAxisAlignment: CrossAxisAlignment.stretch,
584 children: widget.spec.fields.map(_buildField).toList(),
585 ),
586 ),
587 ),
588 ),
589 ),
590 actions: [
591 TextButton(
592 onPressed: () =>
593 Navigator.of(context).pop(schemaFormRawJsonRequested),
594 child: const Text('Edit as JSON'),
595 ),
596 TextButton(
597 onPressed: () => Navigator.of(context).pop(null),
598 child: const Text('Cancel'),
599 ),
600 FilledButton.icon(
601 onPressed: () {
602 final payload = _buildPayload();
603 if (payload != null) Navigator.of(context).pop(payload);
604 },
605 icon: const Icon(Icons.save_outlined, size: 16),
606 label: Text(_isEdit ? 'Save Record' : 'Create Record'),
607 ),
608 ],
609 );
610 }
611}