Files
Docwell/Phone-App/lib/editor/bridge.dart
T
tajniak81andClaude Opus 5.5 ba394b8fac Finish Phase 0: lint, codegen, contributor docs and the two remaining spikes
Repository basics:
- CONTRIBUTING.md and CODE_OF_CONDUCT.md (Contributor Covenant 2.1)
- SPDX AGPL-3.0-or-later headers on all hand-written sources, checked in CI
- golangci-lint (shared .golangci.yml), ESLint and Prettier, all run in CI

API codegen from api/openapi.yaml (npm run generate, drift fails CI):
- Go types via oapi-codegen in Server/internal/api
- a contract test that the router and the spec list the same routes
- Dart models via Phone-App/tool/generate_api.dart; the app uses them

Spike: shared Tiptap editor in a Flutter WebView (ADR-4)
- @docwell/editor-bridge builds the editor into one HTML page with a
  versioned JSON protocol; Phone-App hosts it with webview_flutter and a
  native toolbar. Integration test passes on an Android API 35 emulator.
- flutter_inappwebview dropped: its Android plugin fails on AGP 9.

Spike: Wails v3 desktop (ADR-11)
- system tray, docwell:// deep links (page and space only) with
  single-instance hand-off, and the built-in updater with a required
  ed25519 signing key. Verified on Windows.
- regenerated build assets register the scheme and drop template
  placeholders.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 16:11:07 +01:00

171 lines
4.8 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 = 1;
/// Formatting the native toolbar can apply.
enum EditorCommand {
bold,
italic,
strike,
code,
heading1,
heading2,
heading3,
bulletList,
orderedList,
blockquote,
codeBlock,
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();
/// 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;
/// 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});
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 '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();
super.dispose();
}
}