chain-studio/lib/widgets/fai_flow_output.dart
flemming-it 34f2b7b313 feat(studio): typed flow outputs + on-disk docs + UX polish
Documentation system (the original "whole docs system is broken"
complaint):
- Studio reads inline docs from disk via the new
  getInstalledModuleDocs RPC. No network, no auth, no provider
  lock-in.
- store.dart probes for MODULE.md eagerly when a module-detail
  sheet opens (a single file stat). The Documentation section
  only renders when the bundle actually shipped docs.
- Shared FaiTheme.markdownStyle helper used by Welcome's
  DocReaderSheet and Store's DocsPanel so every inline doc
  reads in the same typography. The shared style forces
  code.backgroundColor = transparent to suppress the per-span
  bands flutter_markdown's default code style draws on dark
  themes.

Flow run dialog:
- Run-button gating now strips the @version suffix from
  installed capabilities before the contains() check. Without
  this fix the button stayed disabled for every flow with
  dependencies, even after a successful install.
- Studio derives a MIME type from the picked file's extension
  (small per-suffix map; .pdf, .docx, .txt, .json, ...) and
  forwards it to the hub. Fixes "unsupported MIME type:
  application/octet-stream" from text.extract.
- Dialog title tracks the future's state: running -> "extract
  laeuft", success -> "extract -- Ergebnis", failure ->
  "extract -- fehlgeschlagen".
- Output rendering moved from String stringification to a
  sealed FlowOutput type (Text / Json / Bytes / File / Unknown).
  A new FaiFlowOutput widget dispatches per variant: markdown
  for text/markdown (heuristic), pretty JSON for proto Struct,
  inline image preview + Save-As for bytes, Open for file URIs.

Byte sizes:
- New humanBytes() helper renders 23.3 kB / 1.04 MB style values
  with three significant digits, matching Finder / GNOME Files.
  Wired into flow-card pills, picked-file readouts, and the
  bytes-payload preview line.

Signed-off-by: flemming-it <sf@flemming.it>
Signed-off-by: flemming-it <stefan.a.flemming@googlemail.com>
2026-05-25 11:17:58 +02:00

288 lines
9.3 KiB
Dart

// FaiFlowOutput — type-aware renderer for one entry in
// `runSavedFlow`'s output map. Reads `FlowOutput` and dispatches
// to the right widget:
//
// - text: SelectableText for plain text; Markdown widget
// when the (hinted) MIME is text/markdown.
// - json: indented JSON in a code-block container.
// - bytes: inline image thumbnail when image/*, otherwise a
// "{mime}, {size}" summary. Always offers Save-as.
// - file: "Open" button → SystemActions.openInOs(uri).
//
// Stateless on purpose: the dialog wraps it; we never own a
// future or a controller here.
import 'dart:io';
import 'dart:typed_data';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';
import 'package:flutter_markdown/flutter_markdown.dart';
import '../data/flow_output.dart';
import '../data/format.dart';
import '../data/system_actions.dart';
import '../l10n/app_localizations.dart';
import '../theme/theme.dart';
import '../theme/tokens.dart';
class FaiFlowOutput extends StatelessWidget {
final FlowOutput output;
const FaiFlowOutput({super.key, required this.output});
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
switch (output) {
case FlowOutputText(:final text):
return _TextView(text: text);
case FlowOutputJson(:final pretty):
return _CodeBlock(text: pretty, theme: theme);
case FlowOutputBytes(:final bytes, :final mimeType):
return _BytesView(bytes: bytes, mimeType: mimeType);
case FlowOutputFile(:final uri, :final mimeType):
return _FileView(uri: uri, mimeType: mimeType);
case FlowOutputUnknown():
return _CodeBlock(
text: AppLocalizations.of(context)!.flowsOutputUnknown,
theme: theme,
);
}
}
}
/// Plain-text renderer. Auto-detects markdown via a cheap
/// heuristic (leading `#` heading, fenced code block, or
/// numbered/bulleted list) so flows that emit text/markdown
/// without setting an explicit MIME still render formatted.
class _TextView extends StatelessWidget {
final String text;
const _TextView({required this.text});
static final RegExp _markdownHeuristic = RegExp(
r'(^|\n)(#{1,6}\s|```|\*\s|-\s|\d+\.\s)',
);
bool get _looksLikeMarkdown =>
text.length < 64 * 1024 && _markdownHeuristic.hasMatch(text);
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
if (_looksLikeMarkdown) {
return Container(
width: double.infinity,
padding: const EdgeInsets.all(FaiSpace.md),
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHigh,
borderRadius: BorderRadius.circular(FaiRadius.sm),
border: Border.all(color: theme.colorScheme.outlineVariant),
),
child: MarkdownBody(
data: text,
selectable: true,
onTapLink: (_, href, _) async {
if (href != null && href.isNotEmpty) {
await SystemActions.openInOs(href);
}
},
styleSheet: FaiTheme.markdownStyle(theme),
),
);
}
return Container(
width: double.infinity,
padding: const EdgeInsets.all(FaiSpace.md),
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHigh,
borderRadius: BorderRadius.circular(FaiRadius.sm),
border: Border.all(color: theme.colorScheme.outlineVariant),
),
child: SelectableText(
text,
style: theme.textTheme.bodyMedium?.copyWith(height: 1.5),
),
);
}
}
class _CodeBlock extends StatelessWidget {
final String text;
final ThemeData theme;
const _CodeBlock({required this.text, required this.theme});
@override
Widget build(BuildContext context) {
return Container(
width: double.infinity,
padding: const EdgeInsets.all(FaiSpace.md),
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHigh,
borderRadius: BorderRadius.circular(FaiRadius.sm),
border: Border.all(color: theme.colorScheme.outlineVariant),
),
child: SelectableText(
text,
style: FaiTheme.mono(
size: 12,
color: theme.colorScheme.onSurface,
),
),
);
}
}
class _BytesView extends StatelessWidget {
final Uint8List bytes;
final String mimeType;
const _BytesView({required this.bytes, required this.mimeType});
bool get _isImage => mimeType.startsWith('image/');
/// Reasonable default filename for the Save dialog. Strips the
/// MIME up to the slash and uses the suffix when known
/// (image/png → output.png), otherwise a generic `.bin`.
String _defaultFilename() {
final slash = mimeType.indexOf('/');
if (slash < 0 || slash == mimeType.length - 1) return 'output.bin';
final sub = mimeType.substring(slash + 1);
// Strip common parameter suffixes (`png; charset=...`).
final semi = sub.indexOf(';');
final ext = semi < 0 ? sub : sub.substring(0, semi);
// `vnd.openxmlformats-…wordprocessingml.document` → docx.
if (ext.contains('wordprocessingml')) return 'output.docx';
if (ext.contains('spreadsheetml')) return 'output.xlsx';
if (ext.contains('presentationml')) return 'output.pptx';
return 'output.$ext';
}
Future<void> _save(BuildContext context) async {
final l = AppLocalizations.of(context)!;
final path = await FilePicker.platform.saveFile(
dialogTitle: l.flowsOutputSaveAsTitle,
fileName: _defaultFilename(),
);
if (path == null) return;
try {
await File(path).writeAsBytes(bytes, flush: true);
if (!context.mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(l.flowsOutputSavedAt(path))),
);
} catch (e) {
if (!context.mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(l.flowsOutputSaveFailed('$e'))),
);
}
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final l = AppLocalizations.of(context)!;
return Container(
width: double.infinity,
padding: const EdgeInsets.all(FaiSpace.md),
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHigh,
borderRadius: BorderRadius.circular(FaiRadius.sm),
border: Border.all(color: theme.colorScheme.outlineVariant),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (_isImage) ...[
ConstrainedBox(
constraints: const BoxConstraints(maxHeight: 240),
child: ClipRRect(
borderRadius: BorderRadius.circular(FaiRadius.sm),
child: Image.memory(bytes, fit: BoxFit.contain),
),
),
const SizedBox(height: FaiSpace.sm),
],
Text(
'${mimeType.isEmpty ? l.flowsOutputBytesUnknownMime : mimeType}'
' · ${humanBytes(bytes.length)}',
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
const SizedBox(height: FaiSpace.sm),
OutlinedButton.icon(
icon: const Icon(Icons.save_alt, size: 16),
label: Text(l.flowsOutputSaveAs),
onPressed: () => _save(context),
),
],
),
);
}
}
class _FileView extends StatelessWidget {
final String uri;
final String mimeType;
const _FileView({required this.uri, required this.mimeType});
Future<void> _open(BuildContext context) async {
// Most file-URIs come from modules that wrote a temp/output
// path on the host. SystemActions normalises `file://` for
// open-in-OS on all three platforms.
final target = uri.startsWith('file://') ? uri.substring(7) : uri;
final r = await SystemActions.openInOs(target);
if (!context.mounted || r.ok) return;
final l = AppLocalizations.of(context)!;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(l.flowsOutputOpenFailed(r.stderr))),
);
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final l = AppLocalizations.of(context)!;
return Container(
width: double.infinity,
padding: const EdgeInsets.all(FaiSpace.md),
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHigh,
borderRadius: BorderRadius.circular(FaiRadius.sm),
border: Border.all(color: theme.colorScheme.outlineVariant),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SelectableText(
uri,
style: FaiTheme.mono(
size: 11,
color: theme.colorScheme.primary,
),
),
if (mimeType.isNotEmpty) ...[
const SizedBox(height: 4),
Text(
mimeType,
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
],
const SizedBox(height: FaiSpace.sm),
OutlinedButton.icon(
icon: const Icon(Icons.open_in_new, size: 16),
label: Text(l.flowsOutputOpen),
onPressed: () => _open(context),
),
],
),
);
}
}