Files
Docwell/Phone-App/lib/editor/bridge.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

300 lines
9.2 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 = 5;
/// Formatting the native toolbar can apply.
enum EditorCommand {
bold,
italic,
strike,
code,
heading1,
heading2,
heading3,
bulletList,
orderedList,
blockquote,
codeBlock,
underline,
taskList,
callout,
table,
footnote,
status,
tabs,
pageBreak,
emoji,
subpages,
undo,
redo,
}
/// A child page a subpages block lists.
typedef Subpage = ({String id, String title, String icon});
/// 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;
/// Whether a panel or menu is open over the text (a database record, a
/// property picker). The back button closes it with [dismiss].
bool get overlayOpen => _overlayOpen;
bool _overlayOpen = false;
/// 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'});
// ---- AI (ADR-15) ---------------------------------------------------------
/// Called when the user taps Transcribe on an audio or video file: work
/// out the result and pass it to [answerTranscript] with the same id.
void Function(int id, String src, String name)? onTranscribe;
/// Looks up the page's child pages, in order, when a subpages block is
/// shown; without it the block lists none.
Future<List<Subpage>> Function()? onSubpages;
Completer<({String text, String before})>? _selection;
/// Whether media files get a Transcribe button, with its words.
Future<void> setAi({
required bool transcribe,
required Map<String, String> words,
}) => _post({'type': 'setAi', 'transcribe': transcribe, 'words': words});
/// The selected text and the text before it; the page keeps the range
/// for [insertMarkdown].
Future<({String text, String before})> selection() {
_selection?.completeError(StateError('replaced'));
final c = _selection = Completer();
unawaited(_post({'type': 'getSelection'}));
return c.future.timeout(const Duration(seconds: 5));
}
/// Puts Markdown over the range [selection] reported ("replace"), or
/// below its block ("below").
Future<void> insertMarkdown(String markdown, {required bool replace}) =>
_post({
'type': 'insertMarkdown',
'markdown': markdown,
'mode': replace ? 'replace' : 'below',
});
/// The answer to an [onTranscribe] request: the API's AiTranscript as
/// JSON, or an error to show.
Future<void> answerTranscript(
int id, {
Map<String, dynamic>? result,
String? error,
}) => _post({
'type': 'transcribed',
'id': id,
'result': ?result,
'error': ?error,
});
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'});
/// Shows the page's text or its edgeless canvas, as the API's PageMode
/// names them: "page" or "edgeless". The canvas can be edited once
/// [connect]ed and [setEditable]; on saved content it is read-only.
Future<void> setMode(String mode, {String? title}) =>
_post({'type': 'setMode', 'mode': mode, 'title': ?title});
/// Closes the topmost panel or menu over the text.
Future<void> dismiss() => _post({'type': 'dismiss'});
/// Scrolls to a block (`#b-…`) or opens a database record (`#r-…`) of the
/// page, once it shows it.
Future<void> follow(String hash) => _post({'type': 'follow', 'hash': hash});
/// 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 'overlay':
_overlayOpen = msg['open'] as bool;
notifyListeners();
case 'selection':
final c = _selection;
_selection = null;
if (c != null && !c.isCompleted) {
c.complete((
text: msg['text'] as String? ?? '',
before: msg['before'] as String? ?? '',
));
}
case 'transcribe':
final handler = onTranscribe;
final id = msg['id'] as int;
if (handler == null) {
unawaited(answerTranscript(id, error: 'unavailable'));
} else {
handler(id, msg['src'] as String, msg['name'] as String);
}
case 'subpages':
unawaited(_answerSubpages(msg['id'] as int));
case 'error':
_error = msg['message'] as String;
notifyListeners();
}
}
/// Answers a "subpages" request; a failed lookup lists none.
Future<void> _answerSubpages(int id) async {
var pages = const <Subpage>[];
try {
pages = await onSubpages?.call() ?? const [];
} catch (_) {}
await _post({
'type': 'subpageList',
'id': id,
'pages': [
for (final p in pages) {'id': p.id, 'title': p.title, 'icon': p.icon},
],
});
}
Future<void> _post(Map<String, dynamic> msg) =>
evaluate('window.docwell.receive(${jsonEncode(jsonEncode(msg))})');
@override
void dispose() {
_changes.close();
_navigations.close();
super.dispose();
}
}