// 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 = 4; /// 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 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(); final _navigations = 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; /// 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 get ready => _readyCompleter.future; /// Every edit the user makes. Stream> get changes => _changes.stream; /// App routes of page links the user followed, e.g. `/p/`. Stream get navigations => _navigations.stream; /// Call once the page has loaded. Future 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; Completer<({String text, String before})>? _selection; /// Whether media files get a Transcribe button, with its words. Future setAi({ required bool transcribe, required Map 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 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 answerTranscript( int id, { Map? result, String? error, }) => _post({ 'type': 'transcribed', 'id': id, 'result': ?result, 'error': ?error, }); 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}); /// The page's own layout: the wider column and the body font ("", serif /// or mono, as the API's PageFont). Future setLayout({required bool fullWidth, required String font}) => _post({'type': 'setLayout', 'fullWidth': fullWidth, 'font': font}); Future 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 setMode(String mode, {String? title}) => _post({'type': 'setMode', 'mode': mode, 'title': ?title}); /// Closes the topmost panel or menu over the text. Future dismiss() => _post({'type': 'dismiss'}); /// Scrolls to a block (`#b-…`) or opens a database record (`#r-…`) of the /// page, once it shows it. Future follow(String hash) => _post({'type': 'follow', 'hash': hash}); /// 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 '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 'error': _error = msg['message'] as String; notifyListeners(); } } Future _post(Map msg) => evaluate('window.docwell.receive(${jsonEncode(jsonEncode(msg))})'); @override void dispose() { _changes.close(); _navigations.close(); super.dispose(); } }