// 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 json) => EditorState( active: { for (final name in (json['active'] as List).cast()) ...EditorCommand.values.where((c) => c.name == name), }, canUndo: json['canUndo'] as bool, canRedo: json['canRedo'] as bool, focused: json['focused'] as bool, ); final Set 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 Function(String script) evaluate; Map? _content; EditorState _state = const EditorState(); bool _ready = false; String? _error; final _readyCompleter = Completer(); final _changes = StreamController>.broadcast(); /// The latest document (Tiptap JSON), null until there is one. Map? 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 get ready => _readyCompleter.future; /// Every edit the user makes. Stream> get changes => _changes.stream; /// Call once the page has loaded. Future hello() => _post({'type': 'hello'}); Future run(EditorCommand c) => _post({'type': 'command', 'command': c.name}); Future setContent(Map? content) { _content = content; return _post({'type': 'setContent', 'content': content}); } Future setEditable(bool editable) => _post({'type': 'setEditable', 'editable': editable}); Future setTheme({required bool dark}) => _post({'type': 'setTheme', 'dark': dark}); Future focus() => _post({'type': 'focus'}); /// Edits the live page through docwell-server instead of local content. Future 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; 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; _changes.add(_content!); case 'state': _state = EditorState.fromJson(msg['state'] as Map); notifyListeners(); case 'collab': _collabStatus = msg['status'] as String; notifyListeners(); case 'error': _error = msg['message'] as String; notifyListeners(); } } Future _post(Map msg) => evaluate('window.docwell.receive(${jsonEncode(jsonEncode(msg))})'); @override void dispose() { _changes.close(); super.dispose(); } }