Files
Docwell/Phone-App/lib/editor/editor_screen.dart
T
tajniak81andClaude Opus 5.5 e441880f2f
CI / desktop (ubuntu-latest) (push) Successful in 1h15m48s
CI / mobile (push) Failing after 3m6s
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s
CI / go (Media) (push) Successful in 10m21s
CI / go (Server) (push) Failing after 19m16s
CI / go (Web-App) (push) Successful in 10m27s
CI / frontend (push) Failing after 7m25s
CI / docker (push) Successful in 46m48s
Add the block types Docmost has and Docwell lacked
The slash menu gains Video, Audio, Page break, Footnote, Tabs, Status,
Emoji, Subpages, Synced block and a fifth column size:
- Video and audio upload a file that plays on the page.
- Page breaks show as a labelled line and start a new page in print,
  Word and PDF.
- Footnotes are numbered in reading order and listed at the end of the
  page. Their notes hold bold, italic, code and links, with a plain copy
  kept for search.
- Tabs hold blocks on several named tabs; which one shows is each
  reader's own choice.
- Status badges are coloured words in the text.
- Typing ":" and a word picks an emoji, from the list the page icon
  picker uses, now kept in the editor package.
- Subpages lists the page's child pages, read afresh from the page tree.
- A synced block is a synced page that shows one block of another page,
  made from a copied block link.

Exports (HTML, Markdown, Word, PDF) and search handle every new block.
Page and space exports list a page's subpages. Labels are translated in
all five languages.

The phone toolbar gets Tabs, Footnote, Status, Emoji, Subpages and Page
break, and the app answers the editor's request for the page's
subpages. The bridge protocol goes to version 5.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 17:37:32 +01:00

260 lines
8.7 KiB
Dart

// SPDX-License-Identifier: AGPL-3.0-or-later
import 'dart:async';
import 'package:flutter/foundation.dart' show Factory;
import 'package:flutter/gestures.dart'
show EagerGestureRecognizer, OneSequenceGestureRecognizer;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'package:webview_flutter/webview_flutter.dart';
import 'package:webview_flutter_android/webview_flutter_android.dart'
show AndroidWebViewController, MixedContentMode;
import 'bridge.dart';
import '../l10n.dart';
/// Where Packages/editor-bridge copies its build (`npm run build -w @docwell/editor-bridge`).
const editorAsset = 'assets/editor/index.html';
/// The address the editor page runs at. A file: page sends no Referer, and
/// YouTube's player refuses to play without one; YouTube asks apps to name
/// themselves as `https://<application id>` instead.
const editorBaseUrl = 'https://app.docwell.docwell_mobile/';
/// Loads the bundled editor page (one self-contained file) at [editorBaseUrl].
///
/// The page's address is https, so Android blocks a plain http [server]
/// (its ws:// collab socket and its images) as mixed content; a server the
/// person signed in to over http is allowed explicitly.
Future<void> loadEditorPage(WebViewController web, {String? server}) async {
final android = web.platform;
if (android is AndroidWebViewController &&
server != null &&
server.startsWith('http://')) {
await android.setMixedContentMode(MixedContentMode.alwaysAllow);
}
final html = await rootBundle.loadString(editorAsset);
await web.loadHtmlString(html, baseUrl: editorBaseUrl);
}
/// The editor's WebView. It takes every touch at once: otherwise Flutter's
/// gesture arena cancels a press held past the long-press delay, and the
/// page could not drag records with a finger (touchdrag.ts).
Widget editorView(WebViewController web) => WebViewWidget(
controller: web,
gestureRecognizers: {
Factory<OneSequenceGestureRecognizer>(EagerGestureRecognizer.new),
},
);
/// The page itself never navigates; embedded players may load in their frames.
NavigationDecision editorNavigation(NavigationRequest req) =>
!req.isMainFrame || req.url.startsWith(editorBaseUrl)
? NavigationDecision.navigate
: NavigationDecision.prevent;
/// The JavaScript channel the page posts to (see transport.ts).
const _channel = 'DocwellNative';
/// The shared Tiptap editor in a WebView, with a native toolbar (ADR-4).
class EditorScreen extends StatefulWidget {
const EditorScreen({
super.key,
required this.title,
this.content,
this.onChanged,
this.onBridge,
});
final String title;
final Map<String, dynamic>? content;
final ValueChanged<Map<String, dynamic>>? onChanged;
/// Hands out the bridge once the WebView exists (tests drive it).
final ValueChanged<EditorBridge>? onBridge;
@override
State<EditorScreen> createState() => _EditorScreenState();
}
class _EditorScreenState extends State<EditorScreen> {
final _web = WebViewController();
late final EditorBridge _bridge = EditorBridge(
content: widget.content,
evaluate: _web.runJavaScript,
);
@override
void initState() {
super.initState();
_bridge.addListener(() => setState(() {}));
_bridge.changes.listen((c) => widget.onChanged?.call(c));
_web
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setBackgroundColor(Colors.transparent)
..addJavaScriptChannel(
_channel,
onMessageReceived: (m) => _bridge.handleMessage(m.message),
)
..setNavigationDelegate(
NavigationDelegate(
onPageFinished: (_) async {
if (!mounted) return;
final dark = Theme.of(context).brightness == Brightness.dark;
await _bridge.setTheme(dark: dark);
await _bridge.hello();
},
// The page is bundled and never navigates; links open nowhere.
onNavigationRequest: editorNavigation,
),
);
unawaited(loadEditorPage(_web));
widget.onBridge?.call(_bridge);
}
@override
void dispose() {
_bridge.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return EditorBackHandler(
bridge: _bridge,
child: Scaffold(
appBar: AppBar(title: Text(widget.title)),
body: Column(
children: [
if (_bridge.error != null)
MaterialBanner(
content: Text(_bridge.error!),
actions: const [SizedBox.shrink()],
),
Expanded(
child: Stack(
children: [
editorView(_web),
if (!_bridge.isReady)
const Center(child: CircularProgressIndicator()),
],
),
),
EditorToolbar(bridge: _bridge),
],
),
),
);
}
}
/// Lets the back button close a panel or menu the editor shows (a database
/// record, a property picker) before it leaves the screen.
class EditorBackHandler extends StatelessWidget {
const EditorBackHandler({
super.key,
required this.bridge,
required this.child,
});
final EditorBridge bridge;
final Widget child;
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: bridge,
builder: (context, child) => PopScope(
canPop: !bridge.overlayOpen,
onPopInvokedWithResult: (didPop, _) {
if (!didPop) unawaited(bridge.dismiss());
},
child: child!,
),
child: child,
);
}
/// Formatting buttons above the keyboard, lit up from the page's state.
class EditorToolbar extends StatelessWidget {
const EditorToolbar({super.key, required this.bridge, this.onAi});
final EditorBridge bridge;
/// Opens the AI writing actions; without it there is no AI button.
final VoidCallback? onAi;
// A getter, so the labels follow the language.
static List<(EditorCommand, IconData, String)> get _buttons => [
(EditorCommand.bold, Icons.format_bold, tr('bold')),
(EditorCommand.italic, Icons.format_italic, tr('italic')),
(EditorCommand.underline, Icons.format_underline, tr('underline')),
(EditorCommand.strike, Icons.format_strikethrough, tr('strike')),
(EditorCommand.heading1, Icons.title, tr('heading')),
(EditorCommand.bulletList, Icons.format_list_bulleted, tr('bulletList')),
(EditorCommand.orderedList, Icons.format_list_numbered, tr('orderedList')),
(EditorCommand.taskList, Icons.checklist, tr('taskList')),
(EditorCommand.callout, Icons.lightbulb_outline, tr('callout')),
(EditorCommand.table, Icons.table_chart_outlined, tr('table')),
(EditorCommand.blockquote, Icons.format_quote, tr('quote')),
(EditorCommand.codeBlock, Icons.code, tr('codeBlock')),
(EditorCommand.tabs, Icons.tab_outlined, tr('toolTabs')),
(EditorCommand.footnote, Icons.superscript, tr('toolFootnote')),
(EditorCommand.status, Icons.label_outline, tr('toolStatus')),
(EditorCommand.emoji, Icons.emoji_emotions_outlined, tr('toolEmoji')),
(EditorCommand.subpages, Icons.account_tree_outlined, tr('toolSubpages')),
(
EditorCommand.pageBreak,
Icons.insert_page_break_outlined,
tr('toolPageBreak'),
),
];
@override
Widget build(BuildContext context) {
final state = bridge.state;
return Material(
elevation: 2,
child: SafeArea(
top: false,
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
children: [
if (onAi != null)
IconButton(
key: const Key('tool-ai'),
tooltip: tr('aiWriteTitle'),
icon: const Icon(Icons.auto_awesome_outlined),
onPressed: bridge.isReady ? onAi : null,
),
IconButton(
tooltip: tr('undo'),
icon: const Icon(Icons.undo),
onPressed: state.canUndo
? () => bridge.run(EditorCommand.undo)
: null,
),
IconButton(
tooltip: tr('redo'),
icon: const Icon(Icons.redo),
onPressed: state.canRedo
? () => bridge.run(EditorCommand.redo)
: null,
),
for (final (command, icon, label) in _buttons)
IconButton(
key: Key('tool-${command.name}'),
tooltip: label,
icon: Icon(icon),
isSelected: state.active.contains(command),
onPressed: bridge.isReady ? () => bridge.run(command) : null,
),
],
),
),
),
);
}
}