Files
Docwell/Phone-App/lib/editor/bridge.dart
T
tajniak81andClaude Opus 5.5 d28f1e02db Add tables, to-dos, callouts and the rest of editor parity
The editor gains the blocks and formatting it lacked next to AFFiNE:

- Tables with a header row, resizable columns, a toolbar to add, delete,
  merge and split, and rows that move by a drag grip, toolbar buttons or
  Ctrl+Alt+Up/Down.
- To-do lists (also from "[] "), callouts with an emoji and colour, and
  headings down to level 6 (Ctrl+Shift+0-6 for text and headings).
- Text colour and highlights from a fixed palette that follows the theme,
  and left, centre and right alignment.
- Optional line numbers on code blocks, with a default hosts can set.
- PDF attachments show their pages inline; pdf.js loads only then, and
  the mobile bundle leaves it out.
- The selection toolbar adds underline, colour, align, inline math, make a
  linked page and copy block link. A grip beside each block drags it and
  opens a menu: turn into, move, duplicate, copy, copy link, delete.
- The slash menu adds Today, Tomorrow, Yesterday, Now and New page.

The web app translates the new words and makes linked pages as children
of the open page. The mobile bridge gets underline, to-do, callout and
table commands, so its protocol moves to version 2 and the bundle is
rebuilt.

docwell-server's converters learn the new nodes: Markdown writes task
lists, GitHub alerts and tables and reads them back; HTML keeps colours
and alignment and reads its own output back; PDF draws tables, to-dos,
callouts and coloured text; Word import keeps tables, alignment, H4-H6
and colours; Notion import turns databases into tables and keeps
callouts and to-dos. Imported tables and H4-H6 headings no longer
collapse into paragraphs and H3.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 12:20:08 +01:00

187 lines
5.4 KiB
Dart

// SPDX-License-Identifier: AGPL-3.0-or-later
// The native side of the editor bridge (ADR-4). The editor page lives in
// Packages/editor-bridge; keep these messages in sync with its protocol.ts.
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
/// Protocol version this app speaks. The page reports its own in "ready".
const editorProtocolVersion = 2;
/// Formatting the native toolbar can apply.
enum EditorCommand {
bold,
italic,
strike,
code,
heading1,
heading2,
heading3,
bulletList,
orderedList,
blockquote,
codeBlock,
underline,
taskList,
callout,
table,
undo,
redo,
}
/// Toolbar state reported by the page.
@immutable
class EditorState {
const EditorState({
this.active = const {},
this.canUndo = false,
this.canRedo = false,
this.focused = false,
});
factory EditorState.fromJson(Map<String, dynamic> json) => EditorState(
active: {
for (final name in (json['active'] as List).cast<String>())
...EditorCommand.values.where((c) => c.name == name),
},
canUndo: json['canUndo'] as bool,
canRedo: json['canRedo'] as bool,
focused: json['focused'] as bool,
);
final Set<EditorCommand> active;
final bool canUndo;
final bool canRedo;
final bool focused;
}
/// Drives the editor page. It does not know about the WebView: [evaluate]
/// runs JavaScript in the page, and the host passes every message the page
/// sends to [handleMessage].
class EditorBridge extends ChangeNotifier {
EditorBridge({required this.evaluate, this._content});
final Future<void> Function(String script) evaluate;
Map<String, dynamic>? _content;
EditorState _state = const EditorState();
bool _ready = false;
String? _error;
final _readyCompleter = Completer<void>();
final _changes = StreamController<Map<String, dynamic>>.broadcast();
final _navigations = StreamController<String>.broadcast();
/// The latest document (Tiptap JSON), null until there is one.
Map<String, dynamic>? get content => _content;
EditorState get state => _state;
bool get isReady => _ready;
/// Live-editing status after [connect]: connecting, connected, offline,
/// denied or changed (see CollabStatus in @docwell/editor).
String? get collabStatus => _collabStatus;
String? _collabStatus;
/// Set when the page is missing, outdated or reported a problem.
String? get error => _error;
/// Completes once the page answered and holds the initial content.
Future<void> get ready => _readyCompleter.future;
/// Every edit the user makes.
Stream<Map<String, dynamic>> get changes => _changes.stream;
/// App routes of page links the user followed, e.g. `/p/<id>`.
Stream<String> get navigations => _navigations.stream;
/// Call once the page has loaded.
Future<void> hello() => _post({'type': 'hello'});
Future<void> run(EditorCommand c) =>
_post({'type': 'command', 'command': c.name});
Future<void> setContent(Map<String, dynamic>? content) {
_content = content;
return _post({'type': 'setContent', 'content': content});
}
Future<void> setEditable(bool editable) =>
_post({'type': 'setEditable', 'editable': editable});
Future<void> setTheme({required bool dark}) =>
_post({'type': 'setTheme', 'dark': dark});
/// The page's own layout: the wider column and the body font ("", serif
/// or mono, as the API's PageFont).
Future<void> setLayout({required bool fullWidth, required String font}) =>
_post({'type': 'setLayout', 'fullWidth': fullWidth, 'font': font});
Future<void> focus() => _post({'type': 'focus'});
/// Edits the live page through docwell-server instead of local content.
Future<void> connect({
required String url,
required String page,
required String token,
required String userName,
required String userColor,
}) => _post({
'type': 'connect',
'url': url,
'page': page,
'token': token,
'user': {'name': userName, 'color': userColor},
});
/// Handles one JSON message from the page.
void handleMessage(String json) {
final msg = jsonDecode(json) as Map<String, dynamic>;
switch (msg['type']) {
case 'ready':
final version = msg['version'] as int;
if (version != editorProtocolVersion) {
_error =
'Editor page speaks protocol $version, app expects '
'$editorProtocolVersion';
notifyListeners();
return;
}
// The page may say ready twice (start-up and hello); load content once.
if (_ready) return;
_ready = true;
unawaited(
setContent(_content).then((_) {
if (!_readyCompleter.isCompleted) _readyCompleter.complete();
}),
);
notifyListeners();
case 'change':
_content = msg['content'] as Map<String, dynamic>;
_changes.add(_content!);
case 'state':
_state = EditorState.fromJson(msg['state'] as Map<String, dynamic>);
notifyListeners();
case 'collab':
_collabStatus = msg['status'] as String;
notifyListeners();
case 'navigate':
_navigations.add(msg['path'] as String);
case 'error':
_error = msg['message'] as String;
notifyListeners();
}
}
Future<void> _post(Map<String, dynamic> msg) =>
evaluate('window.docwell.receive(${jsonEncode(jsonEncode(msg))})');
@override
void dispose() {
_changes.close();
_navigations.close();
super.dispose();
}
}