feat: mini apps customizados com importacao por arquivo/URL, paleta de cores, avatar autenticado e documentacao
Some checks failed
Main Deploy Workflow / deploy_web (push) Has been cancelled
Main Deploy Workflow / deploy_playstore_internal (push) Has been cancelled
Close stale issues and PRs / stale (push) Has been cancelled

This commit is contained in:
2026-09-18 15:11:12 -03:00
parent 94632e0611
commit 1f692b1e4e
18 changed files with 2186 additions and 2 deletions

130
lib/pages/apps/apps.dart Normal file
View File

@@ -0,0 +1,130 @@
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
//
// SPDX-License-Identifier: AGPL-3.0-or-later
import 'dart:convert';
import 'package:file_picker/file_picker.dart';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
import 'package:material_ui/material_ui.dart';
import 'package:matrix/matrix.dart';
import 'package:tatchat/config/setting_keys.dart';
import 'package:tatchat/utils/miniapp_store.dart';
import 'package:tatchat/widgets/matrix.dart';
import 'apps_view.dart';
class Apps extends StatefulWidget {
const Apps({super.key});
@override
AppsController createState() => AppsController();
}
class AppsController extends State<Apps> {
Client get client => Matrix.of(context).client;
Future<void> installMiniApp(String appId) async {
await client.installMiniApp(appId);
if (!mounted) return;
setState(() {});
}
Future<void> uninstallMiniApp(String appId) async {
await client.uninstallMiniApp(appId);
if (!mounted) return;
setState(() {});
}
/// Lets the user pick a `.html` file from their device and imports it as a
/// custom mini app.
Future<void> importMiniAppFromFile() async {
final file = await FilePicker.pickFile(
type: FileType.custom,
allowedExtensions: ['html', 'htm'],
);
if (file == null) return;
final name = file.name.replaceAll(RegExp(r'\.(html?|htm)$'), '');
final bytes = await file.readAsBytes();
await _importHtml(
name: name.isEmpty ? 'Imported app' : name,
html: _decodeBytes(bytes),
);
if (!mounted) return;
setState(() {});
}
/// Fetches an HTML document from [url] and imports it as a custom mini app.
///
/// On web, the browser enforces CORS, so fetching a page that does not send
/// `Access-Control-Allow-Origin` fails with a `ClientException`. In that case
/// we transparently retry through a CORS proxy (if configured) so the import
/// still works.
Future<void> importMiniAppFromUrl(String url) async {
if (url.trim().isEmpty) return;
final response = await _fetchViaCorsProxy(Uri.parse(url));
if (response.statusCode != 200) {
throw Exception('${response.statusCode} ${response.reasonPhrase}');
}
var name = Uri.parse(url).pathSegments.isNotEmpty
? Uri.parse(url).pathSegments.last.replaceAll(
RegExp(r'\.(html?|htm)$'),
'',
)
: url;
if (name.isEmpty) name = 'Imported app';
await _importHtml(name: name, html: response.body);
if (!mounted) return;
setState(() {});
}
/// Fetches [url]. On web, if the initial request fails (usually because the
/// target server lacks CORS headers), retries through the configured CORS
/// proxy. Returns the successful response or rethrows the last error.
Future<http.Response> _fetchViaCorsProxy(Uri uri) async {
try {
final response = await http.get(uri);
if (response.statusCode == 200) return response;
// Non-200 (e.g. 404): fall through to the proxy only for CORS errors.
if (!kIsWeb) return response;
} catch (e) {
if (!kIsWeb) rethrow;
Logs().w('Direct download failed, trying CORS proxy', e);
}
final proxy = AppSettings.miniAppCorsProxy.value;
if (kIsWeb && proxy.isNotEmpty) {
final separator = proxy.contains('?') ? '&' : '?';
final proxied = await http.get(Uri.parse('$proxy$separator$uri'));
if (proxied.statusCode == 200) return proxied;
throw Exception('${proxied.statusCode} ${proxied.reasonPhrase}');
}
throw Exception(
'The server does not allow cross-origin requests (CORS). '
'Import the file manually or set a CORS proxy in the settings.',
);
}
String _decodeBytes(List<int> bytes) {
for (final encoding in const [utf8, latin1]) {
try {
return encoding.decode(bytes);
} catch (_) {}
}
return latin1.decode(bytes, allowInvalid: true);
}
Future<void> _importHtml({
required String name,
required String html,
}) =>
client.importMiniApp(
appId: 'imported-${DateTime.now().millisecondsSinceEpoch}',
name: name,
html: html,
);
@override
Widget build(BuildContext context) => AppsView(this);
}

View File

@@ -0,0 +1,178 @@
// SPDX-FileCopyrightText: 2019-Present Christian Kußowski
// SPDX-FileCopyrightText: 2019-Present Contributors to FluffyChat
//
// SPDX-License-Identifier: AGPL-3.0-or-later
import 'package:go_router/go_router.dart';
import 'package:material_ui/material_ui.dart';
import 'package:matrix/matrix.dart';
import 'package:tatchat/config/miniapp_config.dart';
import 'package:tatchat/l10n/l10n.dart';
import 'package:tatchat/pages/apps/apps.dart';
import 'package:tatchat/utils/miniapp_store.dart';
import 'package:tatchat/widgets/adaptive_dialogs/show_text_input_dialog.dart';
import 'package:tatchat/widgets/layouts/max_width_body.dart';
class AppsView extends StatelessWidget {
final AppsController controller;
const AppsView(this.controller, {super.key});
@override
Widget build(BuildContext context) {
final installed = controller.client.installedMiniApps;
final installedApps = installedMiniAppConfigs(controller.client);
final availableApps = availableMiniApps
.where((app) => !installed.contains(app.id))
.toList();
return Scaffold(
appBar: AppBar(
leading: const Center(child: BackButton()),
title: Text(L10n.of(context).apps),
actions: [
PopupMenuButton<_ImportAction>(
icon: const Icon(Icons.add_box_outlined),
tooltip: L10n.of(context).importApp,
onSelected: (action) async {
switch (action) {
case _ImportAction.file:
await controller.importMiniAppFromFile();
case _ImportAction.url:
final url = await showTextInputDialog(
context: context,
title: L10n.of(context).importFromUrl,
okLabel: L10n.of(context).importApp,
);
if (url == null || url.trim().isEmpty) break;
try {
await controller.importMiniAppFromUrl(url);
if (!context.mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(L10n.of(context).appImported)),
);
} catch (e, s) {
Logs().e('Failed to import mini app', e, s);
if (!context.mounted) return;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(e.toString())),
);
}
}
},
itemBuilder: (context) => [
PopupMenuItem(
value: _ImportAction.file,
child: Row(
children: [
const Icon(Icons.upload_file_outlined),
const SizedBox(width: 12),
Text(L10n.of(context).importFromFile),
],
),
),
PopupMenuItem(
value: _ImportAction.url,
child: Row(
children: [
const Icon(Icons.link),
const SizedBox(width: 12),
Text(L10n.of(context).importFromUrl),
],
),
),
],
),
],
),
body: MaxWidthBody(
withScrolling: false,
child: ListView(
padding: const EdgeInsets.all(16),
children: [
if (installedApps.isNotEmpty) ...[
_SectionHeader(L10n.of(context).installedApps),
for (final app in installedApps)
_AppCard(
app: app,
onTap: () => context.go('/rooms/apps/${app.id}'),
trailing: [
IconButton(
icon: const Icon(Icons.open_in_new),
tooltip: L10n.of(context).open,
onPressed: () => context.go('/rooms/apps/${app.id}'),
),
IconButton(
icon: const Icon(Icons.delete_outline),
tooltip: L10n.of(context).uninstall,
onPressed: () => controller.uninstallMiniApp(app.id),
),
],
),
],
if (availableApps.isNotEmpty) ...[
_SectionHeader(L10n.of(context).availableApps),
for (final app in availableApps)
_AppCard(
app: app,
onTap: null,
trailing: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: TextButton(
onPressed: () => controller.installMiniApp(app.id),
child: Text(L10n.of(context).install),
),
),
],
),
],
],
),
),
);
}
}
enum _ImportAction {
file,
url,
}
class _SectionHeader extends StatelessWidget {
final String text;
const _SectionHeader(this.text);
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(top: 8, bottom: 4),
child: Text(text, style: Theme.of(context).textTheme.titleSmall),
);
}
}
class _AppCard extends StatelessWidget {
final MiniAppConfig app;
final VoidCallback? onTap;
final List<Widget> trailing;
const _AppCard({required this.app, required this.trailing, this.onTap});
@override
Widget build(BuildContext context) {
return Card(
margin: const EdgeInsets.symmetric(vertical: 4),
child: ListTile(
onTap: onTap,
leading: CircleAvatar(
backgroundColor: app.color.withValues(alpha: .15),
foregroundColor: app.color,
child: Icon(app.icon),
),
title: Text(miniAppName(context, app)),
trailing: Row(mainAxisSize: MainAxisSize.min, children: trailing),
),
);
}
}

View File

@@ -0,0 +1,112 @@
// SPDX-FileCopyrightText: 2026 TatuChat
//
// SPDX-License-Identifier: AGPL-3.0-or-later
import 'package:flutter/services.dart';
import 'package:material_ui/material_ui.dart';
import 'package:matrix/matrix.dart';
import 'package:tatchat/config/miniapp_config.dart';
import 'package:tatchat/utils/miniapp_bridge.dart';
import 'package:tatchat/widgets/matrix.dart';
import 'miniapp_shell_stub.dart'
if (dart.library.js_interop) 'miniapp_shell_web.dart'
if (dart.library.ffi) 'miniapp_shell_native.dart';
/// Generic page that renders a mini app. The mini app is a self-contained HTML
/// document that talks to the TatuChat client through the [MiniappBridge]
/// protocol (see `assets/miniapps/`).
class MiniAppPage extends StatefulWidget {
final String appId;
const MiniAppPage({super.key, required this.appId});
@override
State<MiniAppPage> createState() => _MiniAppPageState();
}
class _MiniAppPageState extends State<MiniAppPage> {
Client get client => Matrix.of(context).client;
MiniAppConfig? _config;
String? _html;
bool _notFound = false;
@override
void initState() {
super.initState();
_load();
}
Future<void> _load() async {
final config = resolveMiniAppConfig(client, widget.appId);
if (config == null) {
if (!mounted) return;
setState(() => _notFound = true);
return;
}
if (config.htmlAsset != null) {
final html = await rootBundle.loadString(config.htmlAsset!);
if (!mounted) return;
setState(() {
_config = config;
_html = html;
});
return;
}
// Imported app: the HTML source lives in the account data store.
if (!mounted) return;
setState(() {
_config = config;
_html = config.html;
});
}
/// Entry point of the bridge: called by the web view/iframe with a request
/// coming from the mini app's JavaScript.
Future<Map<String, Object?>> handleRequest(Map<String, dynamic> request) {
final scheme = Theme.of(context).colorScheme;
final brightness = Theme.of(context).brightness;
return MiniappBridge.handleRequest(
client,
widget.appId,
request,
palette: MiniappBridge.buildPalette(scheme, brightness),
);
}
@override
Widget build(BuildContext context) {
if (_notFound) {
return Scaffold(
appBar: AppBar(
leading: const Center(child: BackButton()),
title: Text(widget.appId),
),
body: const Center(child: Text('App not found')),
);
}
final html = _html;
final config = _config;
if (html == null || config == null) {
return Scaffold(
appBar: AppBar(
leading: const Center(child: BackButton()),
title: Text(
_config?.name ?? _config?.id ?? widget.appId,
),
),
body: const Center(
child: CircularProgressIndicator.adaptive(strokeWidth: 2),
),
);
}
return MiniAppShell(
key: ValueKey(widget.appId),
html: html,
appId: widget.appId,
title: config.name ?? config.id,
onRequest: handleRequest,
);
}
}

View File

@@ -0,0 +1,109 @@
// SPDX-FileCopyrightText: 2026 TatuChat
//
// SPDX-License-Identifier: AGPL-3.0-or-later
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:tatchat/l10n/l10n.dart';
/// Native implementation of [MiniAppShell] using an isolated [InAppWebView].
///
/// The mini app HTML is shipped with a small bridge shim injected before
/// `</body>` that forwards `window.parent.postMessage` calls to Dart through
/// `flutter_inappwebview`'s JavaScript handler, and delivers the response
/// back to the mini app via a `postMessage` with the same `requestId`.
class MiniAppShell extends StatefulWidget {
final String html;
final String appId;
final String title;
final Future<Map<String, Object?>> Function(Map<String, dynamic> request)
onRequest;
const MiniAppShell({
super.key,
required this.html,
required this.appId,
required this.title,
required this.onRequest,
});
@override
State<MiniAppShell> createState() => _MiniAppShellState();
}
class _MiniAppShellState extends State<MiniAppShell> {
static const String _handlerName = 'com.tatuchat.miniapp.bridge';
InAppWebViewController? _webViewController;
String get _injectedHtml {
const shim =
'''
<script>
window.addEventListener('message', function (event) {
var msg = event.data;
if (!msg || msg.api !== 'fromMiniApp') return;
window.flutter_inappwebview.callHandler('$_handlerName', msg).then(function (response) {
var reply = Object.assign({}, msg, { response: response });
window.postMessage(reply, '*');
});
});
</script>
''';
final bodyEnd = widget.html.lastIndexOf('</body>');
if (bodyEnd == -1) {
return '${widget.html}\n$shim';
}
return widget.html.replaceRange(bodyEnd, bodyEnd, '\n$shim');
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
backgroundColor: theme.colorScheme.primary,
foregroundColor: theme.colorScheme.onPrimary,
actions: [
IconButton(
tooltip: L10n.of(context).refresh,
icon: const Icon(Icons.refresh_rounded),
onPressed: () => _webViewController?.reload(),
),
],
),
backgroundColor: theme.colorScheme.surface,
body: InAppWebView(
initialSettings: InAppWebViewSettings(
javaScriptEnabled: true,
javaScriptCanOpenWindowsAutomatically: false,
domStorageEnabled: true,
transparentBackground: false,
verticalScrollBarEnabled: true,
horizontalScrollBarEnabled: false,
),
initialData: InAppWebViewInitialData(
data: _injectedHtml,
mimeType: 'text/html',
encoding: 'utf8',
baseUrl: WebUri('https://tatuchat.local'),
),
onWebViewCreated: (controller) {
_webViewController = controller;
controller.addJavaScriptHandler(
handlerName: _handlerName,
callback: (args) async {
if (args.isEmpty) return null;
final raw = args.first;
if (raw is Map<String, dynamic>) {
return widget.onRequest(Map<String, dynamic>.from(raw));
}
return null;
},
);
},
),
);
}
}

View File

@@ -0,0 +1,28 @@
// SPDX-FileCopyrightText: 2026 TatuChat
//
// SPDX-License-Identifier: AGPL-3.0-or-later
import 'package:flutter/widgets.dart';
/// Fallback used when neither `dart.library.js_interop` nor `dart.library.ffi`
/// is available. It should never be selected on a supported platform.
class MiniAppShell extends StatelessWidget {
final String html;
final String appId;
final String title;
final Future<Map<String, Object?>> Function(Map<String, dynamic> request)
onRequest;
const MiniAppShell({
super.key,
required this.html,
required this.appId,
required this.title,
required this.onRequest,
});
@override
Widget build(BuildContext context) => throw UnsupportedError(
'MiniAppShell is not implemented for this platform',
);
}

View File

@@ -0,0 +1,149 @@
// SPDX-FileCopyrightText: 2026 TatuChat
//
// SPDX-License-Identifier: AGPL-3.0-or-later
import 'dart:js_interop';
import 'dart:ui_web' as ui_web;
import 'package:flutter/material.dart';
import 'package:tatchat/l10n/l10n.dart';
import 'package:tatchat/utils/miniapp_bridge.dart';
import 'package:web/web.dart' as web;
/// Web implementation of [MiniAppShell] rendering the mini app into a sandboxed
/// iframe.
///
/// The mini app talks to TatuChat through `postMessage`. This widget listens on
/// `window` for `fromMiniApp` requests, forwards them to the Dart bridge and
/// posts the response back to the iframe's `contentWindow`.
class MiniAppShell extends StatefulWidget {
final String html;
final String appId;
final String title;
final Future<Map<String, Object?>> Function(Map<String, dynamic> request)
onRequest;
const MiniAppShell({
super.key,
required this.html,
required this.appId,
required this.title,
required this.onRequest,
});
@override
State<MiniAppShell> createState() => _MiniAppShellState();
}
class _MiniAppShellState extends State<MiniAppShell> {
static int _viewTypeCounter = 0;
late final String _viewType;
web.HTMLIFrameElement? _iframe;
web.HTMLDivElement? _frameElement;
JSFunction? _messageListener;
@override
void initState() {
super.initState();
_viewType = 'tatchat-miniapp-${_viewTypeCounter++}';
ui_web.platformViewRegistry.registerViewFactory(
_viewType,
(int viewId) => _createElement(),
);
final messageListener = _onMessage.toJS;
_messageListener = messageListener;
web.window.addEventListener('message', messageListener);
}
@override
void dispose() {
final listener = _messageListener;
if (listener != null) {
web.window.removeEventListener('message', listener);
}
super.dispose();
}
web.HTMLIFrameElement _buildIframe() {
final iframe =
web.document.createElement('iframe') as web.HTMLIFrameElement;
iframe.style
..width = '100%'
..height = '100%'
..border = 'none';
iframe.setAttribute(
'sandbox',
'allow-scripts allow-forms allow-same-origin',
);
iframe.setAttribute('srcdoc', widget.html);
return iframe;
}
web.HTMLElement _createElement() {
final div = web.document.createElement('div') as web.HTMLDivElement;
div.style
..width = '100%'
..height = '100%'
..margin = '0'
..padding = '0';
final iframe = _buildIframe();
div.append(iframe);
_iframe = iframe;
_frameElement = div;
return div;
}
void _reload() {
final div = _frameElement;
if (div == null) return;
_iframe?.remove();
final iframe = _buildIframe();
div.append(iframe);
_iframe = iframe;
}
void _onMessage(web.Event event) {
if (!event.isA<web.MessageEvent>()) return;
final messageEvent = event as web.MessageEvent;
final data = messageEvent.data?.dartify();
if (data is! Map) return;
final request = Map<String, dynamic>.from(data);
if (request['api'] != MiniappBridge.api) return;
final iframeWindow = _iframe?.contentWindow;
if (iframeWindow == null) return;
final requestId = request['requestId'];
final widgetId = request['widgetId'];
widget.onRequest(request).then((result) {
iframeWindow.postMessage(
{
'api': MiniappBridge.api,
'widgetId': widgetId,
'requestId': requestId,
'response': result,
}.jsify(),
'*'.toJS,
);
});
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
backgroundColor: theme.colorScheme.primary,
foregroundColor: theme.colorScheme.onPrimary,
actions: [
IconButton(
tooltip: L10n.of(context).refresh,
icon: const Icon(Icons.refresh_rounded),
onPressed: _reload,
),
],
),
backgroundColor: theme.colorScheme.surface,
body: HtmlElementView(viewType: _viewType),
);
}
}