feat(app): Modules settings, module views in the sidebar and block macros

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Opus 5.5 committed 2026-10-26 16:19:45 +01:00
1 parent 7d338e6d30
commit 0d8c6f4c55
20 files changed
+1945 -6

No files matched your search

+14 -1
View File
@@ -19,10 +19,23 @@ class _SynapseAppState extends State<SynapseApp> {
late final AppState _state =
AppState(widget.backend, settings: widget.settings)
..loadRecent()
..loadTypeIcons();
..loadTypeIcons()
..modules.load();
/// On phones, modules lock what they hold (the secrets vault) when the app is paused.
late final _lifecycle = AppLifecycleListener(
onPause: () => _state.modules.suspend(),
);
@override
void initState() {
super.initState();
_lifecycle;
}
@override
void dispose() {
_lifecycle.dispose();
_state.dispose();
super.dispose();
}
+49
View File
@@ -1,3 +1,4 @@
import 'dart:convert';
import 'dart:typed_data';
import '../graph/graph_model.dart';
@@ -133,6 +134,27 @@ abstract class GraphBackend {
Float32List weights, {
Float32List? initial,
});
// Modules: sandboxed WebAssembly extensions (docs/modules.md).
Future<List<ModuleDto>> modules();
/// Reads a module file without installing it (manifest, for the consent dialog).
Future<ModuleDto> inspectModule(Uint8List wasm);
/// Installs or updates a module; [granted] must list every permission it asks for.
Future<ModuleDto> installModule(Uint8List wasm, List<String> granted);
Future<void> setModuleEnabled(String id, bool enabled);
/// Removes a module from this device; [deleteData] also deletes its synced data.
Future<void> uninstallModule(String id, {bool deleteData = false});
/// Sends a request to a module and returns its decoded JSON response.
Future<Map<String, dynamic>> moduleCall(
String id,
Map<String, dynamic> request,
);
/// Drops a module's running instance (its in-memory state, e.g. unlocked keys).
Future<void> stopModule(String id);
}
class _FfiLayout implements LayoutEngine {
@@ -362,4 +384,31 @@ class FfiGraphBackend implements GraphBackend {
initial: initial,
),
);
@override
Future<List<ModuleDto>> modules() => _g.modules();
@override
Future<ModuleDto> inspectModule(Uint8List wasm) =>
_g.inspectModule(wasm: wasm);
@override
Future<ModuleDto> installModule(Uint8List wasm, List<String> granted) =>
_g.installModule(wasm: wasm, granted: granted);
@override
Future<void> setModuleEnabled(String id, bool enabled) =>
_g.setModuleEnabled(id: id, enabled: enabled);
@override
Future<void> uninstallModule(String id, {bool deleteData = false}) =>
_g.uninstallModule(id: id, deleteData: deleteData);
@override
Future<Map<String, dynamic>> moduleCall(
String id,
Map<String, dynamic> request,
) async {
final out = await _g.moduleCall(id: id, request: jsonEncode(request));
final v = jsonDecode(out);
return v is Map<String, dynamic> ? v : {'error': 'bad response'};
}
@override
Future<void> stopModule(String id) => _g.stopModule(id: id);
}
+14 -2
View File
@@ -12,6 +12,7 @@ import '../state/outline_ops.dart';
import '../theme/theme.dart';
import 'completion.dart';
import 'markdown.dart';
import '../widgets/module_ui.dart';
const indentWidth = 24.0;
const _gutter = 18.0;
@@ -323,6 +324,12 @@ class _BlockViewState extends State<BlockView> {
onBlockRefNewTab: (r) => app.openIdInNewTab(r.pageId),
onUrl: openUrl,
onToggleTodo: () => widget.controller.cycleTodo(widget.node),
macro: (name, args) {
final id = app.modules.macroOwner(name);
return id == null
? null
: ModuleMacro(moduleId: id, name: name.toLowerCase(), args: args);
},
maxWidth: width,
);
_renderedFor = content;
@@ -347,6 +354,8 @@ class _BlockViewState extends State<BlockView> {
Widget build(BuildContext context) {
final app = AppScope.read(context);
final hasRef = widget.node.content.contains('((');
// Module macros appear (or go) as modules are installed, enabled or disabled.
final hasMacro = widget.node.content.contains('{{');
Widget build(double width) {
final r = _render(context, width);
return Text.rich(r.span, key: _key);
@@ -362,9 +371,12 @@ class _BlockViewState extends State<BlockView> {
constraints: const BoxConstraints(
minHeight: blockFontSize * blockLineHeight,
),
child: hasRef
child: hasRef || hasMacro
? ListenableBuilder(
listenable: app.refs,
listenable: Listenable.merge([
app.refs,
if (hasMacro) app.modules,
]),
builder: (context, _) {
_renderedFor = null;
return build(box.maxWidth);
+22
View File
@@ -67,6 +67,7 @@ class RenderContext {
this.onToggleTodo,
this.onPageNewTab,
this.onBlockRefNewTab,
this.macro,
this.maxWidth = 600,
});
@@ -82,6 +83,9 @@ class RenderContext {
/// Middle-click on a page link or block ref.
final void Function(String title)? onPageNewTab;
final void Function(BlockRefDtoLike ref)? onBlockRefNewTab;
/// Widget for a `{{name args}}` macro a module renders; null leaves it as text.
final Widget? Function(String name, String args)? macro;
final double maxWidth;
}
@@ -100,6 +104,7 @@ final _heading = RegExp(r'^(#{1,6}) ');
final _uuid = RegExp(
r'^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$',
);
final _macro = RegExp(r'^\s*([a-z0-9_-]+)(?:\s+([^{}]*))?$');
final _property = RegExp(r'^([A-Za-z0-9_\-]+):: ?(.*)$');
/// Renders Synapse outline Markdown of one block into a single [InlineSpan] tree.
@@ -312,6 +317,23 @@ class BlockRenderer {
continue;
}
}
// {{name args}}: a macro rendered by a module
if (ctx.macro != null && s.startsWith('{{', i)) {
final j = s.indexOf('}}', i + 2);
final m = j < 0 ? null : _macro.firstMatch(s.substring(i + 2, j));
final w = m == null ? null : ctx.macro!(m[1]!, (m[2] ?? '').trim());
if (w != null) {
flush(i);
_atomic(
WidgetSpan(alignment: PlaceholderAlignment.middle, child: w),
1,
off + i,
j + 2 - i,
);
i = plain = j + 2;
continue;
}
}
// ((block ref))
if (s.startsWith('((', i)) {
final j = s.indexOf('))', i + 2);
+43
View File
@@ -9,6 +9,7 @@ import '../graph/network_canvas.dart';
import '../theme/theme.dart';
import '../widgets/dates.dart';
import 'keymap.dart';
import 'modules.dart';
import 'settings.dart';
import 'write_queue.dart';
@@ -37,6 +38,25 @@ class TagsTypesRoute extends AppRoute {
const TagsTypesRoute();
}
/// A view contributed by a module (rendered from the UI tree the module returns).
class ModuleRoute extends AppRoute {
const ModuleRoute(this.moduleId, this.viewId, {this.title = 'Module'});
final String moduleId;
final String viewId;
/// The view's title when it was opened (shown in the tab).
final String title;
@override
bool operator ==(Object other) =>
other is ModuleRoute &&
other.moduleId == moduleId &&
other.viewId == viewId;
@override
int get hashCode => Object.hash(moduleId, viewId);
}
enum GraphMode {
network('Network', Icons.hub_outlined),
brain('Synapses', Icons.bolt_outlined),
@@ -100,6 +120,7 @@ class AppTab {
AllPagesRoute() => 'All pages',
SettingsRoute() => 'Settings',
TagsTypesRoute() => 'Tags & types',
ModuleRoute(:final title) => title,
TagRoute(:final name) => '#$name',
GraphRoute() => 'Graph',
PageTarget(:final title) => label ?? title ?? 'Page',
@@ -111,6 +132,7 @@ class AppTab {
AllPagesRoute() => Icons.description_outlined,
SettingsRoute() => Icons.settings_outlined,
TagsTypesRoute() => Icons.style_outlined,
ModuleRoute() => Icons.extension_outlined,
TagRoute() => Icons.sell_outlined,
GraphRoute() => Icons.hub_outlined,
PageTarget() => Icons.article_outlined,
@@ -128,6 +150,12 @@ Map<String, dynamic>? routeToJson(AppRoute r, {String? label}) => switch (r) {
AllPagesRoute() => {'t': 'all'},
SettingsRoute() => {'t': 'settings'},
TagsTypesRoute() => {'t': 'tags-types'},
ModuleRoute() => {
't': 'module',
'id': r.moduleId,
'view': r.viewId,
'title': r.title,
},
TagRoute() => {'t': 'tag', 'name': r.name},
GraphRoute() => {
't': 'graph',
@@ -156,6 +184,12 @@ AppRoute? routeFromJson(Object? j) {
return const SettingsRoute();
case 'tags-types':
return const TagsTypesRoute();
case 'module':
final id = j['id'];
final view = j['view'];
final title = j['title'];
if (id is! String || view is! String) return null;
return ModuleRoute(id, view, title: title is String ? title : 'Module');
case 'tag':
final name = j['name'];
return name is String && name.isNotEmpty ? TagRoute(name) : null;
@@ -213,6 +247,9 @@ class AppState extends ChangeNotifier {
final SettingsStore _settings;
/// Installed modules, their views, macros and effects.
late final ModulesController modules = ModulesController(backend);
/// Key bindings (defaults plus the user's overrides).
late final Keymap keymap;
@@ -666,6 +703,12 @@ class AppState extends ChangeNotifier {
void toggleTheme(Brightness current) {
setTheme(current == Brightness.dark ? 'paper' : 'paper-dark');
}
@override
void dispose() {
modules.dispose();
super.dispose();
}
}
/// Resolved `((block refs))`, loaded lazily and shared by every rendered block.
+188
View File
@@ -0,0 +1,188 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';
import '../backend/graph_backend.dart';
/// What each permission lets a module do, for the install consent dialog.
const permissionDescriptions = {
'storage': 'Keep its own data in this graph (synced to your other devices)',
'crypto': 'Derive keys from passwords and encrypt or decrypt data (keys stay in the app)',
'clipboard': 'Copy text to the clipboard (cleared after a delay)',
'pages:read': 'Read your pages',
'pages:write': 'Create pages and add blocks to them',
};
/// Modules bundled with the app (Flutter assets), offered for installation in Settings.
const bundledModules = {
'synapse.secrets': (
asset: 'assets/modules/synapse.secrets.wasm',
name: 'Secrets',
description:
'An encrypted vault for passwords, unlocked with a master password.',
),
};
/// Installed modules and the plumbing around them: sidebar views, block macros, periodic
/// ticks, locking on suspend and the effects modules ask for (clipboard, notices).
class ModulesController extends ChangeNotifier {
ModulesController(this.backend);
final GraphBackend backend;
List<ModuleDto> installed = const [];
/// Bumped when modules ask for their block macros to be redrawn (lock, unlock, edits,
/// a tick that changed something). Macro widgets listen to this controller.
int macroVersion = 0;
/// Bumped when a view should re-render (a tick changed the module's state).
int viewVersion = 0;
final _timers = <String, Timer>{};
Timer? _clipboardTimer;
bool _disposed = false;
Iterable<ModuleDto> get enabled => installed.where((m) => m.enabled);
/// Module id rendering `{{name ...}}` blocks (the first enabled one claiming it).
String? macroOwner(String name) {
final n = name.toLowerCase();
for (final m in enabled) {
if (m.macros.contains(n)) return m.id;
}
return null;
}
ModuleDto? byId(String id) {
for (final m in installed) {
if (m.id == id) return m;
}
return null;
}
Future<void> load() async {
try {
installed = await backend.modules();
} catch (_) {
installed = const [];
}
if (_disposed) return;
_restartTimers();
macroVersion++;
notifyListeners();
}
Future<ModuleDto> inspect(Uint8List wasm) => backend.inspectModule(wasm);
Future<ModuleDto> install(Uint8List wasm, List<String> granted) async {
final m = await backend.installModule(wasm, granted);
await load();
return m;
}
Future<void> setEnabled(String id, bool enabled) async {
await backend.setModuleEnabled(id, enabled);
await load();
}
Future<void> uninstall(String id, {bool deleteData = false}) async {
await backend.uninstallModule(id, deleteData: deleteData);
await load();
}
/// Sends a request; errors (including a crashed module) come back as `{'error': ...}`.
Future<Map<String, dynamic>> call(
String id,
Map<String, dynamic> request,
) async {
try {
return await backend.moduleCall(id, request);
} catch (e) {
return {'error': '$e'};
}
}
void _restartTimers() {
for (final t in _timers.values) {
t.cancel();
}
_timers.clear();
for (final m in enabled) {
final s = m.tickSeconds;
if (s == null || s < 5) continue;
_timers[m.id] = Timer.periodic(Duration(seconds: s), (_) => _tick(m.id));
}
}
Future<void> _tick(String id) async {
final r = await call(id, {'op': 'tick'});
if (_disposed || r['changed'] != true) return;
refresh();
}
/// Redraws module views and macros.
void refresh() {
macroVersion++;
viewVersion++;
notifyListeners();
}
/// The app is going to the background: modules lock what they hold (e.g. the vault).
Future<void> suspend() async {
var changed = false;
for (final m in enabled.toList()) {
final r = await call(m.id, {'op': 'suspend'});
changed |= r['changed'] == true;
}
if (changed && !_disposed) refresh();
}
/// Applies the `effects` of a module response. Returns the notices to show and the view to
/// open, which need a `BuildContext` (the caller shows them).
Future<({List<String> toasts, String? openView})> applyEffects(
Map<String, dynamic> response,
) async {
final toasts = <String>[];
String? openView;
final effects = response['effects'];
if (effects is! List) return (toasts: toasts, openView: openView);
for (final e in effects) {
if (e is! Map) continue;
final copy = e['copy'];
if (copy is Map && copy['text'] is String) {
final text = copy['text'] as String;
await Clipboard.setData(ClipboardData(text: text));
final ms = copy['clear_after_ms'];
_clipboardTimer?.cancel();
if (ms is int && ms > 0) {
_clipboardTimer = Timer(Duration(milliseconds: ms), () async {
// Only clear what we put there.
final now = await Clipboard.getData(Clipboard.kTextPlain);
if (now?.text == text) {
await Clipboard.setData(const ClipboardData(text: ''));
}
});
}
}
if (e['toast'] is String) toasts.add(e['toast'] as String);
if (e['open_view'] is String) openView = e['open_view'] as String;
if (e['refresh_macros'] == true) {
macroVersion++;
notifyListeners();
}
}
return (toasts: toasts, openView: openView);
}
@override
void dispose() {
_disposed = true;
for (final t in _timers.values) {
t.cancel();
}
_clipboardTimer?.cancel();
super.dispose();
}
}
+431
View File
@@ -0,0 +1,431 @@
import 'dart:async';
import 'package:flutter/material.dart';
import '../state/app_state.dart';
import '../theme/theme.dart';
import '../editor/block_row.dart' show openUrl;
import '../widgets/common.dart';
import '../widgets/module_ui.dart';
/// A view contributed by a module. The module returns a UI tree (JSON, see
/// `docs/modules.md`); buttons, submitted fields and `change` fields send an `event` with the
/// current text of every field, and the module answers with the next tree plus effects.
class ModuleView extends StatefulWidget {
const ModuleView({super.key, required this.moduleId, required this.viewId});
final String moduleId;
final String viewId;
@override
State<ModuleView> createState() => _ModuleViewState();
}
class _ModuleViewState extends State<ModuleView> {
Map<String, dynamic>? _tree;
String? _error;
bool _busy = false;
int _viewVersion = -1;
/// One controller per field id, kept across trees so typing and focus survive re-renders.
final _fields = <String, TextEditingController>{};
/// The value each field had in the last tree (a new value from the module replaces the
/// text; an unchanged one keeps what the user typed).
final _sent = <String, String>{};
final _hidden = <String, bool>{};
Timer? _debounce;
@override
void initState() {
super.initState();
_render();
}
@override
void dispose() {
_debounce?.cancel();
for (final c in _fields.values) {
c.dispose();
}
super.dispose();
}
Future<void> _render() async {
final r = await AppScope.read(context).modules
.call(widget.moduleId, {'op': 'render', 'view': widget.viewId});
if (mounted) _apply(r);
}
Future<void> _event(String action, {String? arg}) async {
if (_busy) return;
_debounce?.cancel();
setState(() => _busy = true);
final r = await AppScope.read(context).modules.call(widget.moduleId, {
'op': 'event',
'view': widget.viewId,
'action': action,
'arg': ?arg,
'values': {for (final e in _fields.entries) e.key: e.value.text},
});
if (!mounted) return;
setState(() => _busy = false);
_apply(r);
await applyModuleEffects(context, widget.moduleId, r);
}
void _apply(Map<String, dynamic> r) {
setState(() {
final ui = r['ui'];
if (ui is Map<String, dynamic>) {
_tree = ui;
_error = null;
_syncFields(ui);
} else if (r['error'] != null) {
_error = '${r['error']}';
}
});
}
/// Applies field values from the new tree and drops controllers of fields that are gone.
void _syncFields(Map<String, dynamic> tree) {
final seen = <String>{};
void walk(Object? w) {
if (w is List) {
w.forEach(walk);
return;
}
if (w is! Map) return;
if (w['type'] == 'field' && w['id'] is String) {
final id = w['id'] as String;
final value = w['value'] is String ? w['value'] as String : '';
seen.add(id);
final c = _fields.putIfAbsent(id, TextEditingController.new);
if (_sent[id] != value) {
c.text = value;
_sent[id] = value;
}
}
for (final k in const ['children', 'left', 'right', 'items']) {
walk(w[k]);
}
}
walk(tree);
for (final id in _fields.keys.toList()) {
if (!seen.contains(id)) {
_fields.remove(id)!.dispose();
_sent.remove(id);
_hidden.remove(id);
}
}
}
@override
Widget build(BuildContext context) {
final modules = AppScope.read(context).modules;
return ListenableBuilder(
listenable: modules,
builder: (context, _) {
if (_viewVersion != modules.viewVersion) {
final first = _viewVersion < 0;
_viewVersion = modules.viewVersion;
// A tick changed the module's state (auto-lock, a password hidden again).
if (!first) scheduleMicrotask(() => mounted ? _render() : null);
}
final m = modules.byId(widget.moduleId);
if (m == null || !m.enabled) {
return const Center(
child: Text('This module is not installed or is disabled.'),
);
}
return LayoutBuilder(
builder: (context, box) {
final pad = sidePadding(box.maxWidth);
return Stack(
children: [
SingleChildScrollView(
padding: EdgeInsets.fromLTRB(pad, 28, pad, 60),
child: _error != null
? Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
_error!,
style: TextStyle(
color: Theme.of(context).colorScheme.error,
),
),
const SizedBox(height: 12),
OutlinedButton(
onPressed: _render,
child: const Text('Retry'),
),
],
)
: _tree == null
? const SizedBox.shrink()
: _widget(context, _tree!),
),
if (_busy)
const Positioned(
top: 0,
left: 0,
right: 0,
child: LinearProgressIndicator(minHeight: 2),
),
],
);
},
);
},
);
}
List<Widget> _children(BuildContext context, Object? list) => [
if (list is List)
for (final c in list)
if (c is Map<String, dynamic>) _widget(context, c),
];
Widget _widget(BuildContext context, Map<String, dynamic> w) {
final colors = context.colors;
String str(String k) => w[k] is String ? w[k] as String : '';
switch (w['type']) {
case 'column':
final kids = _children(context, w['children']);
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
for (var i = 0; i < kids.length; i++) ...[
if (i > 0) const SizedBox(height: 12),
kids[i],
],
],
);
case 'row':
final raw = (w['children'] is List ? w['children'] as List : const [])
.whereType<Map<String, dynamic>>()
.toList();
final grows = raw.any(
(c) => c['type'] == 'field' || c['type'] == 'pair',
);
if (!grows) {
return Wrap(
spacing: 8,
runSpacing: 8,
crossAxisAlignment: WrapCrossAlignment.center,
children: [for (final c in raw) _widget(context, c)],
);
}
return Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
for (var i = 0; i < raw.length; i++) ...[
if (i > 0) const SizedBox(width: 8),
raw[i]['type'] == 'field' || raw[i]['type'] == 'pair'
? Expanded(child: _widget(context, raw[i]))
: _widget(context, raw[i]),
],
],
);
case 'split':
final left = w['left'] is Map<String, dynamic>
? _widget(context, w['left'] as Map<String, dynamic>)
: const SizedBox.shrink();
final right = w['right'] is Map<String, dynamic>
? _widget(context, w['right'] as Map<String, dynamic>)
: const SizedBox.shrink();
return LayoutBuilder(
builder: (context, box) => box.maxWidth < 640
? Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [left, const SizedBox(height: 24), right],
)
: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(flex: 2, child: left),
const SizedBox(width: 28),
Expanded(flex: 3, child: right),
],
),
);
case 'heading':
return Text(
str('text'),
style: TextStyle(
fontFamily: titleFont,
fontSize: 22,
fontWeight: FontWeight.w600,
color: colors.ink,
),
);
case 'text':
final style = switch (w['style']) {
'muted' => TextStyle(color: colors.muted),
'error' => TextStyle(color: Theme.of(context).colorScheme.error),
'mono' => TextStyle(fontFamily: monoFont, color: colors.ink),
_ => TextStyle(color: colors.ink),
};
return SelectableText(str('text'), style: style.copyWith(height: 1.4));
case 'divider':
return Divider(color: colors.line, height: 1);
case 'pair':
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
str('label'),
style: TextStyle(fontSize: 12, color: colors.muted),
),
const SizedBox(height: 2),
w['link'] == true && _isWebUrl(str('value'))
? TextLink(str('value'), onTap: () => openUrl(str('value')))
: SelectableText(
str('value'),
style: TextStyle(
color: colors.ink,
fontFamily: w['mono'] == true ? monoFont : null,
),
),
],
);
case 'field':
final id = str('id');
final c = _fields.putIfAbsent(id, TextEditingController.new);
final secret = w['secret'] == true;
final hidden = _hidden[id] ?? true;
final submit = w['submit'] is String ? w['submit'] as String : null;
final change = w['change'] is String ? w['change'] as String : null;
return TextField(
key: ValueKey('module-field-$id'),
controller: c,
autofocus: w['autofocus'] == true,
obscureText: secret && hidden,
enableSuggestions: !secret,
autocorrect: !secret,
minLines: w['multiline'] == true ? 3 : 1,
maxLines: w['multiline'] == true ? 8 : 1,
style: TextStyle(fontFamily: secret && !hidden ? monoFont : null),
decoration: InputDecoration(
labelText: str('label'),
hintText: w['hint'] is String ? w['hint'] as String : null,
prefixIcon: moduleIcon(w['icon']) == null
? null
: Icon(moduleIcon(w['icon']), size: 18),
suffixIcon: secret
? IconButton(
tooltip: hidden ? 'Show' : 'Hide',
icon: Icon(
hidden
? Icons.visibility_outlined
: Icons.visibility_off_outlined,
size: 18,
),
onPressed: () => setState(() => _hidden[id] = !hidden),
)
: null,
isDense: true,
border: const OutlineInputBorder(),
),
onSubmitted: submit == null ? null : (_) => _event(submit),
onChanged: change == null
? null
: (_) {
_debounce?.cancel();
_debounce = Timer(
const Duration(milliseconds: 200),
() => _event(change),
);
},
);
case 'button':
final action = str('action');
final arg = w['arg'] is String ? w['arg'] as String : null;
final icon = moduleIcon(w['icon']);
final label = Text(str('label'));
final onPressed = _busy ? null : () => _event(action, arg: arg);
return switch (w['style']) {
'primary' =>
icon == null
? FilledButton(onPressed: onPressed, child: label)
: FilledButton.icon(
onPressed: onPressed,
icon: Icon(icon, size: 18),
label: label,
),
'danger' => TextButton.icon(
style: TextButton.styleFrom(
foregroundColor: Theme.of(context).colorScheme.error,
),
onPressed: onPressed,
icon: Icon(icon ?? Icons.warning_amber_outlined, size: 18),
label: label,
),
_ =>
icon == null
? TextButton(onPressed: onPressed, child: label)
: TextButton.icon(
onPressed: onPressed,
icon: Icon(icon, size: 18),
label: label,
),
};
case 'list':
final items = _children(context, w['items']);
if (items.isEmpty) {
return Text(str('empty'), style: TextStyle(color: colors.muted));
}
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: items,
);
case 'item':
final action = w['action'] is String ? w['action'] as String : null;
final selected = w['selected'] == true;
return Material(
color: selected ? colors.accentSoft : Colors.transparent,
borderRadius: BorderRadius.circular(8),
child: InkWell(
borderRadius: BorderRadius.circular(8),
onTap: action == null || _busy
? null
: () => _event(
action,
arg: w['arg'] is String ? w['arg'] as String : null,
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
str('title'),
style: TextStyle(
color: colors.ink,
fontWeight: FontWeight.w500,
),
),
if (str('subtitle').isNotEmpty)
Text(
str('subtitle'),
style: TextStyle(fontSize: 12, color: colors.muted),
),
],
),
),
),
);
}
return const SizedBox.shrink();
}
}
/// Modules may only link to web pages.
bool _isWebUrl(String s) {
final u = Uri.tryParse(s.trim());
return u != null &&
(u.scheme == 'http' || u.scheme == 'https') &&
u.host.isNotEmpty;
}
+413
View File
@@ -0,0 +1,413 @@
import 'package:file_selector/file_selector.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../backend/graph_backend.dart';
import '../state/app_state.dart';
import '../state/modules.dart';
import '../theme/theme.dart';
/// Picks a module file; replaced in tests.
Future<Uint8List?> Function() pickModuleFile = () async {
final file = await openFile(
acceptedTypeGroups: const [
XTypeGroup(label: 'Synapse module', extensions: ['wasm']),
],
);
return file?.readAsBytes();
};
/// Loads a bundled module; replaced in tests.
Future<Uint8List> Function(String asset) loadBundledModule = (asset) async =>
(await rootBundle.load(asset)).buffer.asUint8List();
/// Settings section: installed modules (enable, remove), bundled ones and install from file.
class ModulesSettings extends StatelessWidget {
const ModulesSettings({super.key});
@override
Widget build(BuildContext context) {
final modules = AppScope.read(context).modules;
final colors = context.colors;
return ListenableBuilder(
listenable: modules,
builder: (context, _) {
final installed = modules.installed;
final available = bundledModules.entries
.where((e) => installed.every((m) => m.id != e.key))
.toList();
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Expanded(
child: Text(
'Modules',
style: Theme.of(context).textTheme.headlineSmall,
),
),
TextButton.icon(
key: const ValueKey('module-install-file'),
onPressed: () => _installFromFile(context),
icon: const Icon(Icons.upload_file_outlined, size: 18),
label: const Text('Install from file…'),
),
],
),
const SizedBox(height: 4),
Text(
'Modules extend Synapse. Each one runs in a sandbox and can only do what you '
'allow when you install it. Installed modules are per device; their data '
'syncs with the graph.',
style: TextStyle(color: colors.muted),
),
const SizedBox(height: 14),
for (final m in installed) _InstalledModule(module: m),
for (final e in available)
_BundledModule(
id: e.key,
asset: e.value.asset,
name: e.value.name,
description: e.value.description,
),
if (installed.isEmpty && available.isEmpty)
Text(
'No modules installed.',
style: TextStyle(color: colors.muted),
),
],
);
},
);
}
static Future<void> _installFromFile(BuildContext context) async {
final messenger = ScaffoldMessenger.of(context);
final Uint8List? bytes;
try {
bytes = await pickModuleFile();
} catch (e) {
messenger.showSnackBar(
SnackBar(content: Text('Could not read the file: $e')),
);
return;
}
if (bytes == null || !context.mounted) return;
await installModuleBytes(context, bytes);
}
}
/// Reads the module, asks for consent to its permissions and installs it.
Future<void> installModuleBytes(BuildContext context, Uint8List bytes) async {
final modules = AppScope.read(context).modules;
final messenger = ScaffoldMessenger.of(context);
final ModuleDto m;
try {
m = await modules.inspect(bytes);
} catch (e) {
messenger.showSnackBar(
SnackBar(content: Text('Not a valid Synapse module: ${_message(e)}')),
);
return;
}
if (!context.mounted) return;
final previous = modules.byId(m.id);
final ok = await showDialog<bool>(
context: context,
builder: (ctx) => _ConsentDialog(module: m, previous: previous),
);
if (ok != true) return;
try {
await modules.install(bytes, m.permissions);
messenger.showSnackBar(
SnackBar(content: Text('${m.name} ${m.version} installed.')),
);
} catch (e) {
messenger.showSnackBar(
SnackBar(content: Text('Could not install ${m.name}: ${_message(e)}')),
);
}
}
String _message(Object e) {
final s = '$e';
return s.startsWith('Exception: ') ? s.substring(11) : s;
}
class _ConsentDialog extends StatelessWidget {
const _ConsentDialog({required this.module, this.previous});
final ModuleDto module;
final ModuleDto? previous;
@override
Widget build(BuildContext context) {
final colors = context.colors;
final m = module;
final update = previous != null;
return AlertDialog(
title: Text(
update
? 'Update ${m.name} (${previous!.version} → ${m.version})?'
: 'Install ${m.name} ${m.version}?',
),
content: SizedBox(
width: 460,
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (m.author.isNotEmpty)
Text('By ${m.author}', style: TextStyle(color: colors.muted)),
if (m.description.isNotEmpty) ...[
const SizedBox(height: 8),
Text(m.description),
],
const SizedBox(height: 16),
Text(
m.permissions.isEmpty
? 'It asks for no permissions.'
: 'It will be allowed to:',
style: const TextStyle(fontWeight: FontWeight.w600),
),
for (final p in m.permissions)
Padding(
padding: const EdgeInsets.only(top: 6),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(
Icons.check_circle_outline,
size: 16,
color: colors.accent,
),
const SizedBox(width: 8),
Expanded(child: Text(permissionDescriptions[p] ?? p)),
],
),
),
if (m.views.isNotEmpty || m.macros.isNotEmpty) ...[
const SizedBox(height: 16),
Text(
[
if (m.views.isNotEmpty)
'Adds ${m.views.map((v) => v.title).join(', ')} to the sidebar.',
if (m.macros.isNotEmpty)
'Renders ${m.macros.map((n) => '{{$n …}}').join(', ')} in blocks.',
].join(' '),
style: TextStyle(color: colors.muted),
),
],
],
),
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: const Text('Cancel'),
),
FilledButton(
key: const ValueKey('module-consent-install'),
onPressed: () => Navigator.pop(context, true),
child: Text(update ? 'Update' : 'Install'),
),
],
);
}
}
class _InstalledModule extends StatelessWidget {
const _InstalledModule({required this.module});
final ModuleDto module;
@override
Widget build(BuildContext context) {
final colors = context.colors;
final m = module;
final modules = AppScope.read(context).modules;
final icon = m.views.isEmpty ? null : m.views.first.icon;
return Container(
margin: const EdgeInsets.only(bottom: 10),
padding: const EdgeInsets.fromLTRB(14, 10, 8, 10),
decoration: BoxDecoration(
border: Border.all(color: colors.line),
borderRadius: BorderRadius.circular(10),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.only(top: 2, right: 12),
child: icon == null
? Icon(Icons.extension_outlined, color: colors.muted)
: Text(icon, style: const TextStyle(fontSize: 20)),
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'${m.name} ${m.version}',
style: TextStyle(
fontWeight: FontWeight.w600,
color: colors.ink,
),
),
if (m.description.isNotEmpty)
Text(m.description, style: TextStyle(color: colors.muted)),
const SizedBox(height: 6),
Wrap(
spacing: 6,
runSpacing: 4,
children: [
for (final p in m.permissions)
Tooltip(
message: permissionDescriptions[p] ?? p,
child: Container(
padding: const EdgeInsets.symmetric(
horizontal: 7,
vertical: 2,
),
decoration: BoxDecoration(
color: colors.codeBg,
borderRadius: BorderRadius.circular(5),
),
child: Text(
p,
style: TextStyle(fontSize: 12, color: colors.muted),
),
),
),
],
),
],
),
),
Column(
children: [
Switch(
key: ValueKey('module-enabled-${m.id}'),
value: m.enabled,
onChanged: (v) => modules.setEnabled(m.id, v),
),
TextButton(
key: ValueKey('module-remove-${m.id}'),
onPressed: () => _remove(context),
child: const Text('Remove'),
),
],
),
],
),
);
}
Future<void> _remove(BuildContext context) async {
final modules = AppScope.read(context).modules;
var deleteData = false;
final ok = await showDialog<bool>(
context: context,
builder: (ctx) => StatefulBuilder(
builder: (ctx, setState) => AlertDialog(
title: Text('Remove ${module.name}?'),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'It is removed from this device. Its data stays in the graph, so '
'installing it again brings it back.',
),
const SizedBox(height: 8),
CheckboxListTile(
key: const ValueKey('module-remove-data'),
contentPadding: EdgeInsets.zero,
value: deleteData,
onChanged: (v) => setState(() => deleteData = v ?? false),
title: const Text(
'Also delete its data on every synced device (cannot be undone)',
),
),
],
),
actions: [
TextButton(
onPressed: () => Navigator.pop(ctx, false),
child: const Text('Cancel'),
),
FilledButton(
key: const ValueKey('module-remove-confirm'),
onPressed: () => Navigator.pop(ctx, true),
child: const Text('Remove'),
),
],
),
),
);
if (ok == true) {
await modules.uninstall(module.id, deleteData: deleteData);
}
}
}
class _BundledModule extends StatelessWidget {
const _BundledModule({
required this.id,
required this.asset,
required this.name,
required this.description,
});
final String id;
final String asset;
final String name;
final String description;
@override
Widget build(BuildContext context) {
final colors = context.colors;
return Container(
margin: const EdgeInsets.only(bottom: 10),
padding: const EdgeInsets.fromLTRB(14, 10, 8, 10),
decoration: BoxDecoration(
border: Border.all(color: colors.line),
borderRadius: BorderRadius.circular(10),
),
child: Row(
children: [
Padding(
padding: const EdgeInsets.only(right: 12),
child: Icon(Icons.extension_outlined, color: colors.muted),
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
name,
style: TextStyle(
fontWeight: FontWeight.w600,
color: colors.ink,
),
),
Text(
'$description Included with Synapse.',
style: TextStyle(color: colors.muted),
),
],
),
),
FilledButton.tonal(
key: ValueKey('module-install-$id'),
onPressed: () async {
final bytes = await loadBundledModule(asset);
if (context.mounted) await installModuleBytes(context, bytes);
},
child: const Text('Install'),
),
],
),
);
}
}
+4 -1
View File
@@ -5,9 +5,10 @@ import '../state/app_state.dart';
import '../state/keymap.dart';
import '../theme/theme.dart';
import '../widgets/common.dart';
import 'modules_settings.dart';
import 'theme_editor.dart';
/// Theme picker and key bindings.
/// Theme picker, modules and key bindings.
class SettingsView extends StatelessWidget {
const SettingsView({super.key});
@@ -88,6 +89,8 @@ class SettingsView extends StatelessWidget {
],
),
const SizedBox(height: 36),
const ModulesSettings(),
const SizedBox(height: 36),
Row(
children: [
Expanded(child: _Heading('Keyboard shortcuts')),
+36
View File
@@ -9,6 +9,7 @@ import '../theme/theme.dart';
import '../widgets/dates.dart';
import 'all_pages_view.dart';
import 'journals_view.dart';
import 'module_view.dart';
import 'page_screen.dart';
import 'hubs_tree.dart';
import 'quick_switcher.dart';
@@ -135,6 +136,10 @@ class _ShellState extends State<Shell> {
AllPagesRoute() => const AllPagesView(),
SettingsRoute() => const SettingsView(),
TagsTypesRoute() => const TagsTypesView(),
ModuleRoute() => ModuleView(
moduleId: route.moduleId,
viewId: route.viewId,
),
TagRoute() => TagView(name: route.name),
PageTarget() => PageScreen(target: route),
},
@@ -333,6 +338,37 @@ class _Sidebar extends StatelessWidget {
onTap: () => go(const TagsTypesRoute()),
onMiddle: () => newTab(const TagsTypesRoute()),
),
// Views of enabled modules.
ListenableBuilder(
listenable: app.modules,
builder: (context, _) => Column(
children: [
for (final m in app.modules.enabled)
for (final v in m.views)
_NavItem(
icon: v.icon == null ? Icons.extension_outlined : null,
leading: v.icon == null
? null
: Padding(
padding: const EdgeInsets.only(right: 10),
child: Text(
v.icon!,
style: const TextStyle(fontSize: 14),
),
),
label: v.title,
selected:
route is ModuleRoute &&
route.moduleId == m.id &&
route.viewId == v.id,
onTap: () =>
go(ModuleRoute(m.id, v.id, title: v.title)),
onMiddle: () =>
newTab(ModuleRoute(m.id, v.id, title: v.title)),
),
],
),
),
const SizedBox(height: 22),
Expanded(
child: ListView(
+12 -1
View File
@@ -6,6 +6,7 @@ import '../editor/block_row.dart';
import '../editor/markdown.dart';
import '../state/app_state.dart';
import '../theme/theme.dart';
import 'module_ui.dart';
/// Max width of the reading column.
const contentWidth = 780.0;
@@ -120,7 +121,7 @@ class _StaticBlockState extends State<StaticBlock> {
final app = AppScope.read(context);
return LayoutBuilder(
builder: (context, box) => ListenableBuilder(
listenable: app.refs,
listenable: Listenable.merge([app.refs, app.modules]),
builder: (context, _) {
_r?.dispose();
_r = BlockRenderer(
@@ -134,6 +135,16 @@ class _StaticBlockState extends State<StaticBlock> {
onPageNewTab: app.openTitleInNewTab,
onBlockRefNewTab: (r) => app.openIdInNewTab(r.pageId),
onUrl: openUrl,
macro: (name, args) {
final id = app.modules.macroOwner(name);
return id == null
? null
: ModuleMacro(
moduleId: id,
name: name.toLowerCase(),
args: args,
);
},
maxWidth: box.maxWidth,
),
).render(widget.content);
+209
View File
@@ -0,0 +1,209 @@
import 'dart:async';
import 'package:flutter/material.dart';
import '../state/app_state.dart';
import '../theme/theme.dart';
/// Icon names modules may use in buttons and macro actions.
IconData? moduleIcon(Object? name) => switch (name) {
'add' => Icons.add,
'lock' => Icons.lock_outline,
'unlock' => Icons.lock_open_outlined,
'copy' => Icons.copy_outlined,
'eye' => Icons.visibility_outlined,
'eye_off' => Icons.visibility_off_outlined,
'edit' => Icons.edit_outlined,
'delete' => Icons.delete_outline,
'key' => Icons.key_outlined,
'refresh' => Icons.refresh,
'save' => Icons.check,
'close' => Icons.close,
'search' => Icons.search,
'link' => Icons.link,
'person' => Icons.person_outline,
_ => null,
};
/// Applies a module response's effects: clipboard (through the controller), notices as snack
/// bars, and opening one of the module's views.
Future<void> applyModuleEffects(
BuildContext context,
String moduleId,
Map<String, dynamic> response,
) async {
final app = AppScope.read(context);
final messenger = ScaffoldMessenger.maybeOf(context);
final out = await app.modules.applyEffects(response);
for (final t in out.toasts) {
messenger?.showSnackBar(SnackBar(content: Text(t)));
}
final view = out.openView;
if (view != null) {
final m = app.modules.byId(moduleId);
final decl = m?.views.where((v) => v.id == view).firstOrNull;
if (decl != null) {
app.go(ModuleRoute(moduleId, view, title: decl.title));
}
}
}
/// A `{{name args}}` macro rendered by a module inside a block: its label, a value (masked or
/// not) and action buttons. Redrawn when the module asks (`ModulesController.macroVersion`).
class ModuleMacro extends StatefulWidget {
const ModuleMacro({
super.key,
required this.moduleId,
required this.name,
required this.args,
});
final String moduleId;
final String name;
final String args;
@override
State<ModuleMacro> createState() => _ModuleMacroState();
}
class _ModuleMacroState extends State<ModuleMacro> {
Map<String, dynamic>? _inline;
int _version = -1;
bool _busy = false;
Map<String, dynamic> get _request => {
'name': widget.name,
'args': widget.args,
};
@override
void didUpdateWidget(ModuleMacro old) {
super.didUpdateWidget(old);
if (old.args != widget.args || old.moduleId != widget.moduleId) {
_version = -1;
}
}
Future<void> _load(int version) async {
_version = version;
final r = await AppScope.read(context).modules
.call(widget.moduleId, {'op': 'macro', ..._request});
if (!mounted) return;
setState(() => _inline = _inlineOf(r));
}
Map<String, dynamic> _inlineOf(Map<String, dynamic> r) {
final i = r['inline'];
if (i is Map<String, dynamic>) return i;
return {'text': widget.args, 'error': '${r['error'] ?? 'No answer'}'};
}
Future<void> _action(String id) async {
if (_busy) return;
setState(() => _busy = true);
final r = await AppScope.read(context).modules.call(widget.moduleId, {
'op': 'macro_action',
'action': id,
..._request,
});
if (!mounted) return;
setState(() {
_busy = false;
_inline = _inlineOf(r);
});
await applyModuleEffects(context, widget.moduleId, r);
}
@override
Widget build(BuildContext context) {
final modules = AppScope.read(context).modules;
return ListenableBuilder(
listenable: modules,
builder: (context, _) {
if (_version != modules.macroVersion) {
final v = modules.macroVersion;
scheduleMicrotask(() {
if (mounted && _version != v) _load(v);
});
}
return _chip(context);
},
);
}
Widget _chip(BuildContext context) {
final colors = context.colors;
final i = _inline;
final small = TextStyle(fontSize: 13, color: colors.ink);
final children = <Widget>[];
if (i == null) {
children.add(Text('{{${widget.name} ${widget.args}}}', style: small));
} else {
final icon = i['icon'];
if (icon is String) {
children.add(Text(icon, style: const TextStyle(fontSize: 12)));
children.add(const SizedBox(width: 5));
}
children.add(
Text(
'${i['text'] ?? widget.args}',
style: small.copyWith(fontWeight: FontWeight.w600),
),
);
final error = i['error'];
final masked = i['masked'];
if (error is String) {
children.add(const SizedBox(width: 8));
children.add(
Text(
error,
style: small.copyWith(color: Theme.of(context).colorScheme.error),
),
);
} else if (masked is String) {
children.add(const SizedBox(width: 8));
children.add(
SelectableText(
masked,
style: small.copyWith(
fontFamily: i['revealed'] == true ? monoFont : null,
color: i['revealed'] == true ? colors.ink : colors.muted,
),
),
);
}
final actions = i['actions'];
if (actions is List) {
for (final a in actions) {
if (a is! Map || a['id'] is! String) continue;
children.add(
IconButton(
tooltip: a['label'] is String ? a['label'] as String : null,
visualDensity: VisualDensity.compact,
iconSize: 15,
padding: EdgeInsets.zero,
constraints: const BoxConstraints.tightFor(width: 26, height: 22),
onPressed: _busy ? null : () => _action(a['id'] as String),
icon: Icon(moduleIcon(a['icon']) ?? Icons.bolt_outlined),
),
);
}
}
}
// Taps on the chip must not start editing the block.
return GestureDetector(
onTapUp: (_) {},
behavior: HitTestBehavior.opaque,
child: Container(
margin: const EdgeInsets.symmetric(horizontal: 1),
padding: const EdgeInsets.only(left: 7, right: 3, top: 1, bottom: 1),
decoration: BoxDecoration(
color: colors.codeBg,
border: Border.all(color: colors.line),
borderRadius: BorderRadius.circular(6),
),
child: Row(mainAxisSize: MainAxisSize.min, children: children),
),
);
}
}
@@ -6,9 +6,13 @@
#include "generated_plugin_registrant.h"
#include <file_selector_linux/file_selector_plugin.h>
#include <url_launcher_linux/url_launcher_plugin.h>
void fl_register_plugins(FlPluginRegistry* registry) {
g_autoptr(FlPluginRegistrar) file_selector_linux_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "FileSelectorPlugin");
file_selector_plugin_register_with_registrar(file_selector_linux_registrar);
g_autoptr(FlPluginRegistrar) url_launcher_linux_registrar =
fl_plugin_registry_get_registrar_for_plugin(registry, "UrlLauncherPlugin");
url_launcher_plugin_register_with_registrar(url_launcher_linux_registrar);
@@ -3,6 +3,7 @@
#
list(APPEND FLUTTER_PLUGIN_LIST
file_selector_linux
url_launcher_linux
)
+89 -1
View File
@@ -65,6 +65,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "1.19.1"
cross_file:
dependency: transitive
description:
name: cross_file
sha256: f141ea4f277af142a0356955707f6556f37b03947d39d55585981a06ca437bd6
url: "https://pub.dev"
source: hosted
version: "0.3.5+5"
crypto:
dependency: transitive
description:
@@ -97,6 +105,70 @@ packages:
url: "https://pub.dev"
source: hosted
version: "7.0.1"
file_selector:
dependency: "direct main"
description:
name: file_selector
sha256: bd15e43e9268db636b53eeaca9f56324d1622af30e5c34d6e267649758c84d9a
url: "https://pub.dev"
source: hosted
version: "1.1.0"
file_selector_android:
dependency: transitive
description:
name: file_selector_android
sha256: d670cd0ce77a2e785b18d8b4d0a8d6a222d6a813ec9b7ddf2790a1b4fb6fa92c
url: "https://pub.dev"
source: hosted
version: "0.5.2+11"
file_selector_ios:
dependency: transitive
description:
name: file_selector_ios
sha256: "5b42ec0ef7626124b4624ea244341e9df780406793c204e89fa68a2e71af115c"
url: "https://pub.dev"
source: hosted
version: "0.5.3+7"
file_selector_linux:
dependency: transitive
description:
name: file_selector_linux
sha256: da76400e7872ce7637ffdce12749ec24169c25f6195c28372208e65a24bcd2ab
url: "https://pub.dev"
source: hosted
version: "0.9.4+1"
file_selector_macos:
dependency: transitive
description:
name: file_selector_macos
sha256: d785431f1910aac8a50e5c492cae912320158030a88703c67b9ef7f1f96fd7ba
url: "https://pub.dev"
source: hosted
version: "0.9.5+2"
file_selector_platform_interface:
dependency: transitive
description:
name: file_selector_platform_interface
sha256: "35e0bd61ebcdb91a3505813b055b09b79dfdc7d0aee9c09a7ba59ae4bb13dc85"
url: "https://pub.dev"
source: hosted
version: "2.7.0"
file_selector_web:
dependency: transitive
description:
name: file_selector_web
sha256: "73181fbc5257776d8ecaa6a94ab3c8e920ad143b9132a6d984a9271dfc6928d3"
url: "https://pub.dev"
source: hosted
version: "0.9.5"
file_selector_windows:
dependency: transitive
description:
name: file_selector_windows
sha256: fbefc5fb92c6d3cbe8d284a2cd971b593bb07d2cd6da8557b81a862250b4acec
url: "https://pub.dev"
source: hosted
version: "0.9.3+6"
flutter:
dependency: "direct main"
description: flutter
@@ -146,6 +218,22 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.0.2"
http:
dependency: transitive
description:
name: http
sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412"
url: "https://pub.dev"
source: hosted
version: "1.6.0"
http_parser:
dependency: transitive
description:
name: http_parser
sha256: "178d74305e7866013777bab2c3d8726205dc5a4dd935297175b19a23a2e66571"
url: "https://pub.dev"
source: hosted
version: "4.1.2"
integration_test:
dependency: "direct dev"
description: flutter
@@ -541,4 +629,4 @@ packages:
version: "3.1.4"
sdks:
dart: ">=3.13.5 <4.0.0"
flutter: ">=3.44.0"
flutter: ">=3.47.0"
+3
View File
@@ -7,6 +7,7 @@ environment:
sdk: ^3.13.5
dependencies:
file_selector: ^1.1.0
flutter:
sdk: flutter
flutter_rust_bridge: 2.13.0
@@ -26,6 +27,8 @@ dev_dependencies:
flutter:
uses-material-design: true
assets:
- assets/modules/
fonts:
- family: Inter
fonts:
+341
View File
@@ -0,0 +1,341 @@
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:synapse/src/backend/graph_backend.dart';
import 'package:synapse/src/state/app_state.dart';
import 'package:synapse/src/theme/theme.dart';
import 'package:synapse/src/views/module_view.dart';
import 'package:synapse/src/views/modules_settings.dart';
import 'package:synapse/src/views/shell.dart';
import 'package:synapse/src/widgets/module_ui.dart';
import 'support/memory_backend.dart';
ModuleDto vault({int? tick}) => ModuleDto(
id: 'synapse.secrets',
name: 'Secrets',
version: '0.1.0',
description: 'An encrypted vault.',
author: 'Synapse',
permissions: const ['storage', 'crypto', 'clipboard'],
views: const [ModuleViewDto(id: 'vault', title: 'Secrets', icon: '🔑')],
macros: const ['secret'],
tickSeconds: tick,
enabled: true,
size: BigInt.from(1000),
);
Future<AppState> pump(
WidgetTester tester,
MemoryBackend b, {
AppRoute? route,
double height = 1000,
}) async {
tester.view.physicalSize = Size(1600, height);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.reset);
final app = AppState(b);
await app.modules.load();
if (route != null) app.go(route);
await tester.pumpWidget(
AppScope(
state: app,
child: MaterialApp(
theme: buildTheme(Brightness.light),
home: const Shell(),
),
),
);
await settle(tester);
return app;
}
Future<void> settle(WidgetTester tester) async {
for (var i = 0; i < 6; i++) {
await tester.pump(const Duration(milliseconds: 50));
}
}
/// Captures what the app puts on the clipboard.
List<String?> mockClipboard(WidgetTester tester) {
final writes = <String?>[];
String? current;
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform,
(call) async {
if (call.method == 'Clipboard.setData') {
current = (call.arguments as Map)['text'] as String?;
writes.add(current);
}
if (call.method == 'Clipboard.getData') return {'text': current};
return null;
},
);
addTearDown(
() => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
SystemChannels.platform,
null,
),
);
return writes;
}
void main() {
test('module routes survive a restart', () {
const r = ModuleRoute('synapse.secrets', 'vault', title: 'Secrets');
final back = routeFromJson(routeToJson(r));
expect(back, r);
expect((back! as ModuleRoute).title, 'Secrets');
expect(routeFromJson({'t': 'module', 'id': 'x'}), isNull);
});
testWidgets('installing a bundled module asks for its permissions first', (
tester,
) async {
final b = MemoryBackend()..inspectResult = vault();
loadBundledModule = (_) async => Uint8List(4);
await pump(tester, b, route: const SettingsRoute(), height: 3000);
await tester.ensureVisible(
find.byKey(const ValueKey('module-install-synapse.secrets')),
);
await tester.tap(
find.byKey(const ValueKey('module-install-synapse.secrets')),
);
await settle(tester);
expect(find.text('Install Secrets 0.1.0?'), findsOneWidget);
expect(find.textContaining('Derive keys from passwords'), findsOneWidget);
// Cancel installs nothing.
await tester.tap(find.text('Cancel'));
await settle(tester);
expect(b.installedModules, isEmpty);
await tester.tap(
find.byKey(const ValueKey('module-install-synapse.secrets')),
);
await settle(tester);
await tester.tap(find.byKey(const ValueKey('module-consent-install')));
await settle(tester);
expect(b.installedModules.keys, ['synapse.secrets']);
// Its view is in the sidebar.
expect(
find.widgetWithText(InkWell, 'Secrets').evaluate().isNotEmpty ||
find.text('Secrets').evaluate().isNotEmpty,
isTrue,
);
// The "installed" notice would cover the buttons.
tester
.state<ScaffoldMessengerState>(find.byType(ScaffoldMessenger))
.removeCurrentSnackBar();
await settle(tester);
// Disabling hides it; removing keeps data unless asked.
await tester.ensureVisible(
find.byKey(const ValueKey('module-enabled-synapse.secrets')),
);
await tester.tap(
find.byKey(const ValueKey('module-enabled-synapse.secrets')),
);
await settle(tester);
expect(b.installedModules['synapse.secrets']!.enabled, isFalse);
await tester.tap(
find.byKey(const ValueKey('module-remove-synapse.secrets')),
);
await settle(tester);
await tester.tap(find.byKey(const ValueKey('module-remove-confirm')));
await settle(tester);
expect(b.installedModules, isEmpty);
});
testWidgets(
'a module view renders its tree, sends field values and applies effects',
(tester) async {
final writes = mockClipboard(tester);
final b = MemoryBackend();
b.installedModules['synapse.secrets'] = vault();
var unlocked = false;
b.moduleHandlers['synapse.secrets'] = (req) {
if (req['op'] == 'event' && req['action'] == 'unlock') {
unlocked = (req['values'] as Map)['password'] == 'correct horse';
if (!unlocked) {
return {
'ui': {
'type': 'column',
'children': [
{
'type': 'field',
'id': 'password',
'label': 'Master password',
'value': '',
'secret': true,
'submit': 'unlock',
},
{'type': 'text', 'text': 'Wrong password.', 'style': 'error'},
{
'type': 'button',
'label': 'Unlock',
'action': 'unlock',
'style': 'primary',
},
],
},
};
}
}
if (req['op'] == 'event' && req['action'] == 'copy_password') {
return {
'ui': {'type': 'text', 'text': 'GitHub'},
'effects': [
{
'copy': {'text': 'hunter2', 'clear_after_ms': 1000},
},
{'toast': 'Password copied.'},
],
};
}
if (unlocked) {
return {
'ui': {
'type': 'column',
'children': [
{'type': 'heading', 'text': 'GitHub'},
{
'type': 'button',
'label': 'Copy',
'action': 'copy_password',
'arg': 'id1',
},
],
},
};
}
return {
'ui': {
'type': 'column',
'children': [
{
'type': 'field',
'id': 'password',
'label': 'Master password',
'value': '',
'secret': true,
'submit': 'unlock',
},
{
'type': 'button',
'label': 'Unlock',
'action': 'unlock',
'style': 'primary',
},
],
},
};
};
await pump(
tester,
b,
route: const ModuleRoute('synapse.secrets', 'vault', title: 'Secrets'),
);
expect(find.byType(ModuleView), findsOneWidget);
final field = find.widgetWithText(TextField, 'Master password');
expect(tester.widget<TextField>(field).obscureText, isTrue);
await tester.enterText(field, 'wrong');
await tester.tap(find.text('Unlock'));
await settle(tester);
expect(find.text('Wrong password.'), findsOneWidget);
expect((b.moduleRequests.last.$2['values'] as Map)['password'], 'wrong');
await tester.enterText(
find.widgetWithText(TextField, 'Master password'),
'correct horse',
);
await tester.testTextInput.receiveAction(TextInputAction.done);
await settle(tester);
expect(find.text('GitHub'), findsOneWidget);
await tester.tap(find.text('Copy'));
await settle(tester);
expect(writes, ['hunter2']);
expect(find.text('Password copied.'), findsOneWidget);
// The clipboard is cleared after the delay (only if it still holds our text).
await tester.pump(const Duration(seconds: 2));
expect(writes, ['hunter2', '']);
},
);
testWidgets('blocks render module macros as chips with actions', (
tester,
) async {
final writes = mockClipboard(tester);
final b = MemoryBackend();
b.installedModules['synapse.secrets'] = vault();
b.moduleHandlers['synapse.secrets'] = (req) => switch (req['op']) {
'macro' => {
'inline': {
'text': req['args'],
'icon': '🔑',
'masked': '••••••••',
'actions': [
{'id': 'copy', 'label': 'Copy password', 'icon': 'copy'},
],
},
},
'macro_action' => {
'inline': {'text': req['args'], 'masked': '••••••••'},
'effects': [
{
'copy': {'text': 's3cret'},
},
],
},
_ => {},
};
final p = b.createPage('Accounts');
b.seed(p.id, [(0, 'GitHub: {{secret GitHub}} and {{embed nothing}}')]);
await pump(tester, b, route: PageTarget(id: p.id));
expect(find.byType(ModuleMacro), findsOneWidget);
expect(find.text('••••••••'), findsOneWidget);
expect(
find.textContaining('{{embed nothing}}', findRichText: true),
findsOneWidget,
);
final req = b.moduleRequests.firstWhere((r) => r.$2['op'] == 'macro').$2;
expect(req['name'], 'secret');
expect(req['args'], 'GitHub');
await tester.tap(find.byTooltip('Copy password'));
await settle(tester);
expect(writes, ['s3cret']);
expect(b.moduleRequests.last.$2['action'], 'copy');
});
testWidgets('without the module, macros stay text', (tester) async {
final b = MemoryBackend();
final p = b.createPage('Accounts');
b.seed(p.id, [(0, 'GitHub: {{secret GitHub}}')]);
await pump(tester, b, route: PageTarget(id: p.id));
expect(find.byType(ModuleMacro), findsNothing);
expect(
find.textContaining('{{secret GitHub}}', findRichText: true),
findsOneWidget,
);
});
testWidgets('suspending the app locks modules and redraws them', (
tester,
) async {
final b = MemoryBackend();
b.installedModules['synapse.secrets'] = vault();
b.moduleHandlers['synapse.secrets'] = (req) =>
req['op'] == 'suspend' ? {'changed': true} : {};
final app = await pump(tester, b);
final before = app.modules.macroVersion;
await app.modules.suspend();
expect(b.moduleRequests.last.$2['op'], 'suspend');
expect(app.modules.macroVersion, greaterThan(before));
});
}
+68
View File
@@ -18,6 +18,74 @@ class MemoryBackend implements GraphBackend {
final outlines = <String, List<OutlineNode>>{};
final aliases = <String, String>{};
final calls = <String>[];
// ---------------------------------------------------------------- modules
// Fakes: [moduleHandlers] answer requests the way a module would.
final installedModules = <String, ModuleDto>{};
final moduleHandlers =
<String, Map<String, dynamic> Function(Map<String, dynamic>)>{};
final moduleRequests = <(String, Map<String, dynamic>)>[];
final stoppedModules = <String>[];
/// What [inspectModule] reads from any file; null means "not a module".
ModuleDto? inspectResult;
@override
Future<List<ModuleDto>> modules() async =>
installedModules.values.toList()
..sort((a, b) => a.name.compareTo(b.name));
@override
Future<ModuleDto> inspectModule(Uint8List wasm) async =>
inspectResult ?? (throw Exception('not a Synapse module'));
@override
Future<ModuleDto> installModule(Uint8List wasm, List<String> granted) async {
final m = await inspectModule(wasm);
if (m.permissions.any((p) => !granted.contains(p))) {
throw Exception('permission not granted');
}
final enabled = installedModules[m.id]?.enabled ?? true;
return installedModules[m.id] = withEnabled(m, enabled);
}
@override
Future<void> setModuleEnabled(String id, bool enabled) async {
installedModules[id] = withEnabled(installedModules[id]!, enabled);
}
@override
Future<void> uninstallModule(String id, {bool deleteData = false}) async {
installedModules.remove(id);
}
@override
Future<Map<String, dynamic>> moduleCall(
String id,
Map<String, dynamic> request,
) async {
final m = installedModules[id];
if (m == null || !m.enabled) throw Exception('module $id is not enabled');
moduleRequests.add((id, request));
return moduleHandlers[id]?.call(request) ?? {};
}
@override
Future<void> stopModule(String id) async => stoppedModules.add(id);
static ModuleDto withEnabled(ModuleDto m, bool enabled) => ModuleDto(
id: m.id,
name: m.name,
version: m.version,
description: m.description,
author: m.author,
permissions: m.permissions,
views: m.views,
macros: m.macros,
tickSeconds: m.tickSeconds,
enabled: enabled,
size: m.size,
);
int _seq = 0;
String _id() => 'id-${_seq++}';
@@ -6,9 +6,12 @@
#include "generated_plugin_registrant.h"
#include <file_selector_windows/file_selector_windows.h>
#include <url_launcher_windows/url_launcher_windows.h>
void RegisterPlugins(flutter::PluginRegistry* registry) {
FileSelectorWindowsRegisterWithRegistrar(
registry->GetRegistrarForPlugin("FileSelectorWindows"));
UrlLauncherWindowsRegisterWithRegistrar(
registry->GetRegistrarForPlugin("UrlLauncherWindows"));
}
@@ -3,6 +3,7 @@
#
list(APPEND FLUTTER_PLUGIN_LIST
file_selector_windows
url_launcher_windows
)