// SPDX-License-Identifier: AGPL-3.0-or-later import 'dart:async'; import 'package:flutter/material.dart'; import '../api/docwell_api.dart'; import '../l10n.dart'; import '../screens/markdown_view.dart'; import '../screens/widgets.dart'; import 'bridge.dart'; /// Answers the editor's Transcribe request [id] for the file at [src] /// (`/api/v1/files/`): the transcript and summary, or why not. Future transcribeForEditor( DocwellApi api, EditorBridge bridge, int id, String src, ) async { final match = RegExp(r'^/api/v1/files/([^/?#]+)').firstMatch(src); if (match == null) { await bridge.answerTranscript(id, error: tr('aiTranscribeFailed')); return; } try { final t = await api.transcribe(Uri.decodeComponent(match.group(1)!)); await bridge.answerTranscript( id, result: { 'name': t.name, 'text': t.text, 'summary': t.summary, 'summaryError': ?t.summaryError, }, ); } catch (e) { await bridge.answerTranscript(id, error: describeError(e)); } } /// Writing actions on the editor's selection (ADR-15), as on the web: the /// result streams in, then replaces the selection or goes below it. class AiWriteSheet extends StatefulWidget { const AiWriteSheet({ super.key, required this.api, required this.bridge, required this.workspace, required this.text, required this.before, }); final DocwellApi api; final EditorBridge bridge; final String workspace; /// The selection, and the text before it (for "continue"). final String text; final String before; /// Opens the sheet for the editor's current selection. static Future open( BuildContext context, { required DocwellApi api, required EditorBridge bridge, required String workspace, }) async { final sel = await bridge.selection(); if (!context.mounted) return; await showModalBottomSheet( context: context, isScrollControlled: true, showDragHandle: true, builder: (_) => AiWriteSheet( api: api, bridge: bridge, workspace: workspace, text: sel.text, before: sel.before, ), ); } @override State createState() => _AiWriteSheetState(); } const _languages = [ 'English', 'Polski', 'Deutsch', 'Français', 'Español', 'Italiano', 'Português', 'Nederlands', 'Українська', ]; class _AiWriteSheetState extends State { final _instruction = TextEditingController(); String _result = ''; String? _error; bool _busy = false; String _action = ''; String _language = ''; StreamSubscription? _stream; bool get _hasText => widget.text.trim().isNotEmpty; @override void initState() { super.initState(); // Translating into English is the usual case, unless the app is in it. _language = appLanguage == 'en' ? 'Deutsch' : 'English'; } @override void dispose() { _stream?.cancel(); _instruction.dispose(); super.dispose(); } Future _run(String action) async { if (_busy) return; if (action == 'custom' && _instruction.text.trim().isEmpty) return; setState(() { _action = action; _busy = true; _result = ''; _error = null; }); final done = Completer(); _stream = widget.api .write( widget.workspace, action: action, text: widget.text, before: widget.before, language: _language, instruction: _instruction.text.trim(), ) .listen( (e) { if (!mounted) return; setState(() { if (e.name == 'delta') _result += e.data['text'] as String? ?? ''; if (e.name == 'error') { _error = e.data['message'] as String? ?? tr('aiFailed'); } }); }, onError: (Object err) { if (mounted) setState(() => _error = describeError(err)); if (!done.isCompleted) done.complete(); }, onDone: () { if (!done.isCompleted) done.complete(); }, ); await done.future; _stream = null; if (mounted) setState(() => _busy = false); } void _stop() => _stream?.cancel().then((_) { if (mounted) setState(() => _busy = false); }); Future _apply({required bool replace}) async { await widget.bridge.insertMarkdown(_result, replace: replace); if (mounted) Navigator.of(context).pop(); } @override Widget build(BuildContext context) { final started = _busy || _result.isNotEmpty || _error != null; final theme = Theme.of(context); return Padding( padding: EdgeInsets.only( left: 16, right: 16, bottom: MediaQuery.of(context).viewInsets.bottom + 16, ), child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Text(tr('aiWriteTitle'), style: theme.textTheme.titleMedium), const SizedBox(height: 8), if (!started) ...[ if (!_hasText) Padding( padding: const EdgeInsets.only(bottom: 8), child: Text( tr('aiWriteNoSelection'), style: TextStyle(color: theme.colorScheme.onSurfaceVariant), ), ), Wrap( spacing: 8, runSpacing: 4, children: [ for (final a in [ 'rewrite', 'fix', 'shorter', 'longer', 'summarize', ]) ActionChip( key: Key('ai-$a'), label: Text(tr('aiAction_$a')), onPressed: _hasText ? () => _run(a) : null, ), ActionChip( key: const Key('ai-continue'), label: Text(tr('aiAction_continue')), onPressed: () => _run('continue'), ), ], ), const SizedBox(height: 8), Row( children: [ Expanded(child: Text(tr('aiAction_translate'))), DropdownButton( value: _language, items: [ for (final l in _languages) DropdownMenuItem(value: l, child: Text(l)), ], onChanged: (l) => setState(() => _language = l ?? _language), ), IconButton( tooltip: tr('aiAction_translate'), icon: const Icon(Icons.translate), onPressed: _hasText ? () => _run('translate') : null, ), ], ), TextField( key: const Key('ai-instruction'), controller: _instruction, maxLength: 2000, decoration: InputDecoration( hintText: tr('aiCustomHint'), counterText: '', suffixIcon: IconButton( tooltip: tr('aiSend'), icon: const Icon(Icons.send), onPressed: () => _run('custom'), ), ), onSubmitted: (_) => _run('custom'), ), ] else ...[ ConstrainedBox( constraints: BoxConstraints( maxHeight: MediaQuery.of(context).size.height * 0.45, ), child: SingleChildScrollView( child: _result.isEmpty ? Text( _busy ? tr('aiWriting') : '', style: TextStyle( color: theme.colorScheme.onSurfaceVariant, ), ) : MarkdownView(_result), ), ), if (_error != null) Padding( padding: const EdgeInsets.only(top: 8), child: Text( _error!, style: TextStyle(color: theme.colorScheme.error), ), ), const SizedBox(height: 12), Wrap( spacing: 8, runSpacing: 4, alignment: WrapAlignment.end, children: [ if (_busy) OutlinedButton(onPressed: _stop, child: Text(tr('aiStop'))) else ...[ TextButton( onPressed: () => setState(() { _result = ''; _error = null; }), child: Text(tr('aiDiscard')), ), TextButton( onPressed: () => _run(_action), child: Text(tr('aiRetry')), ), if (_result.trim().isNotEmpty) OutlinedButton( key: const Key('ai-insert'), onPressed: () => _apply(replace: false), child: Text(tr('aiInsertBelow')), ), if (_result.trim().isNotEmpty && _hasText && _action != 'continue') FilledButton( key: const Key('ai-replace'), onPressed: () => _apply(replace: true), child: Text(tr('aiReplace')), ), ], ], ), ], ], ), ); } }