fix Flutter shell platform defaults and tab state

This commit is contained in:
2026-10-21 13:28:50 +01:00
parent cee5f72b14
commit 830726fa19
6 changed files with 185 additions and 43 deletions
+2 -9
View File
@@ -31,15 +31,8 @@ class MyApp extends StatelessWidget {
}
return MaterialApp(
title: 'Pipelines',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.blue),
),
darkTheme: ThemeData(
colorScheme: ColorScheme.fromSeed(
seedColor: Colors.blue,
brightness: Brightness.dark,
),
),
theme: ThemeData(),
darkTheme: ThemeData(brightness: Brightness.dark),
themeMode: ThemeMode.system,
home: AdaptiveShell(destinationBodies: destinationBodies),
);
+30 -19
View File
@@ -30,30 +30,38 @@ class _AdaptiveShellState extends State<AdaptiveShell> {
Widget build(BuildContext context) {
final index = AppDestination.values.indexOf(_selected);
final details = destinationDetails(_selected);
final content =
widget.destinationBodies[_selected]?.call(context) ??
Center(child: Text('${details.label} — Not implemented'));
final contents = AppDestination.values.map((destination) {
final item = destinationDetails(destination);
return KeyedSubtree(
key: ValueKey(destination),
child:
widget.destinationBodies[destination]?.call(context) ??
Center(child: Text('${item.label} — Not implemented')),
);
}).toList();
return LayoutBuilder(
builder: (context, constraints) {
final wide = constraints.maxWidth >= 600;
if (widget.cupertino) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(middle: Text(details.label)),
child: Column(
children: [
Expanded(child: content),
CupertinoTabBar(
currentIndex: index,
onTap: (value) => _select(AppDestination.values[value]),
items: _items((destination) {
final item = destinationDetails(destination);
return BottomNavigationBarItem(
icon: Icon(item.icon),
label: item.label,
);
}),
),
],
child: SafeArea(
child: Column(
children: [
Expanded(child: _destinationStack(contents, index)),
CupertinoTabBar(
currentIndex: index,
onTap: (value) => _select(AppDestination.values[value]),
items: _items((destination) {
final item = destinationDetails(destination);
return BottomNavigationBarItem(
icon: Icon(item.cupertinoIcon),
label: item.label,
);
}),
),
],
),
),
);
}
@@ -75,7 +83,7 @@ class _AdaptiveShellState extends State<AdaptiveShell> {
);
}),
),
Expanded(child: content),
Expanded(child: _destinationStack(contents, index)),
],
),
bottomNavigationBar: wide
@@ -96,4 +104,7 @@ class _AdaptiveShellState extends State<AdaptiveShell> {
},
);
}
Widget _destinationStack(List<Widget> contents, int index) =>
IndexedStack(index: index, children: contents);
}
+25 -13
View File
@@ -1,17 +1,29 @@
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
enum AppDestination { pipelines, runs, chat, settings }
({String label, IconData icon}) destinationDetails(AppDestination value) =>
switch (value) {
AppDestination.pipelines => (
label: 'Pipelines',
icon: Icons.account_tree_outlined,
),
AppDestination.runs => (label: 'Runs', icon: Icons.play_circle_outline),
AppDestination.chat => (label: 'Chat', icon: Icons.chat_bubble_outline),
AppDestination.settings => (
label: 'Settings',
icon: Icons.settings_outlined,
),
};
({String label, IconData icon, IconData cupertinoIcon}) destinationDetails(
AppDestination value,
) => switch (value) {
AppDestination.pipelines => (
label: 'Pipelines',
icon: Icons.account_tree_outlined,
cupertinoIcon: CupertinoIcons.arrow_branch,
),
AppDestination.runs => (
label: 'Runs',
icon: Icons.play_circle_outline,
cupertinoIcon: CupertinoIcons.play_circle,
),
AppDestination.chat => (
label: 'Chat',
icon: Icons.chat_bubble_outline,
cupertinoIcon: CupertinoIcons.chat_bubble_2,
),
AppDestination.settings => (
label: 'Settings',
icon: Icons.settings_outlined,
cupertinoIcon: CupertinoIcons.gear,
),
};
+5 -2
View File
@@ -12,7 +12,10 @@ themes active elsewhere, and accepts injectable `WidgetBuilder` bodies through
- `flutter test test/widget_test.dart`: passed (narrow/wide, 2x text scale,
Cupertino controls and injected destination body).
- `flutter analyze`: passed, no issues.
- Web build/browser interaction/capture: not run in this stage; no browser
automation/capture evidence available. Mobile targets are unverified.
- Follow-up verification: widget tests now cover state retention across tab
switches and Cupertino safe-area insets. `flutter build web` succeeds.
- Browser interaction/capture remains unverified: the local Chrome DevTools
probe did not complete, so no rendered evidence is claimed. Mobile targets
are unverified.
No API capabilities are asserted or mocked. No dependencies were added.
+35
View File
@@ -47,6 +47,41 @@ void main() {
expect(find.text('Pipelines — Not implemented'), findsOneWidget);
});
testWidgets('Cupertino content stays inside safe area', (tester) async {
tester.view.padding = const FakeViewPadding(top: 36, bottom: 28);
addTearDown(tester.view.resetPadding);
await tester.pumpWidget(const MyApp(cupertino: true));
final tabBar = tester.getRect(find.byType(CupertinoTabBar));
expect(tabBar.bottom, lessThanOrEqualTo(900 - 28));
expect(tester.takeException(), isNull);
});
testWidgets('destination state survives switching tabs', (tester) async {
var builds = 0;
await tester.pumpWidget(
MaterialApp(
home: AdaptiveShell(
destinationBodies: {
AppDestination.pipelines: (_) => StatefulBuilder(
builder: (context, setState) => TextButton(
onPressed: () => setState(() => builds++),
child: Text('Builds: $builds'),
),
),
AppDestination.runs: (_) => const Text('Runs screen'),
},
),
),
);
await tester.tap(find.text('Builds: 0'));
await tester.pump();
await tester.tap(find.text('Runs').last);
await tester.pumpAndSettle();
await tester.tap(find.text('Pipelines').last);
await tester.pumpAndSettle();
expect(find.text('Builds: 1'), findsOneWidget);
});
testWidgets('destination content can be supplied by integration', (
tester,
) async {
+88
View File
@@ -0,0 +1,88 @@
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
import { spawn } from 'node:child_process';
import { once } from 'node:events';
import { setTimeout as delay } from 'node:timers/promises';
import { join, extname } from 'node:path';
import { tmpdir } from 'node:os';
import { mkdtemp, rm } from 'node:fs/promises';
const root = join(process.cwd(), 'build/web');
const mime = { '.html': 'text/html', '.js': 'text/javascript', '.json': 'application/json', '.wasm': 'application/wasm', '.png': 'image/png', '.ico': 'image/x-icon' };
const server = createServer(async (req, res) => {
try {
const path = join(root, decodeURIComponent(new URL(req.url, 'http://localhost').pathname));
const file = await readFile(path.endsWith('/') ? join(path, 'index.html') : path);
res.writeHead(200, { 'content-type': mime[extname(path)] ?? 'application/octet-stream' }).end(file);
} catch { res.writeHead(404).end('not found'); }
});
server.listen(0, '127.0.0.1');
await once(server, 'listening');
const port = server.address().port;
const profile = await mkdtemp(join(tmpdir(), 'f2-shell-chrome-'));
const chrome = spawn('/Applications/Google Chrome.app/Contents/MacOS/Google Chrome', [
'--headless=new', '--no-first-run', '--no-default-browser-check', '--disable-gpu',
'--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank',
], { stdio: ['ignore', 'ignore', 'pipe'] });
let stderr = '';
chrome.stderr.on('data', data => { stderr += data; });
const waitFor = async fn => {
for (let i = 0; i < 100; i++) { const value = await fn(); if (value) return value; await delay(100); }
throw new Error('Timed out waiting for Chrome DevTools');
};
let ws;
try {
const endpoint = await waitFor(() => stderr.match(/DevTools listening on (ws:\/\/[^\s]+)/)?.[1]);
ws = new WebSocket(endpoint);
await once(ws, 'open');
let id = 0;
const pending = new Map();
ws.addEventListener('message', event => {
const msg = JSON.parse(event.data);
if (msg.id && pending.has(msg.id)) { pending.get(msg.id)(msg); pending.delete(msg.id); }
});
const send = (method, params = {}, sessionId) => new Promise(resolve => {
const callId = ++id; pending.set(callId, resolve);
ws.send(JSON.stringify({ id: callId, method, params, ...(sessionId ? { sessionId } : {}) }));
});
const created = await send('Target.createTarget', { url: `http://127.0.0.1:${port}/` });
if (!created.result) throw new Error(`Target creation failed: ${JSON.stringify(created)}`);
const target = created.result.targetId;
const session = (await send('Target.attachToTarget', { targetId: target, flatten: true })).result.sessionId;
await send('Page.enable', {}, session);
await send('Runtime.enable', {}, session);
const evaluate = async expression => {
const response = await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }, session);
if (response.error) throw new Error(`Runtime.evaluate failed: ${JSON.stringify(response)}`);
return response.result?.result?.value;
};
await delay(3500);
const loaded = await evaluate("({url:location.href, ready:document.readyState, body:document.body.innerText, html:document.body.innerHTML.slice(0,500)})");
if (!loaded?.url.includes(`127.0.0.1:${port}`)) throw new Error(`Fixture did not load: ${JSON.stringify(loaded)}`);
await evaluate("document.querySelector('flt-semantics-placeholder')?.click()");
await delay(900);
const clickLabel = async label => evaluate(`(() => { const e=[...document.querySelectorAll('flt-semantics')].find(x => (x.getAttribute('aria-label') || x.innerText || '').includes(${JSON.stringify(label)})); if (!e) return false; e.click(); return true; })()`);
const labels = await evaluate("[...document.querySelectorAll('flt-semantics')].map(x=>x.getAttribute('aria-label')||x.innerText).filter(Boolean)");
if (!labels?.some(x => x.includes('Pipelines'))) throw new Error(`Flutter semantics unavailable: ${JSON.stringify(labels)}`);
const capture = async (name, width, height) => {
await send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width < 600 }, session);
await delay(350);
const data = (await send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: false }, session)).result.data;
await (await import('node:fs/promises')).writeFile(`${process.env.OPENCODE_ARTIFACT_DIR}/${name}.png`, Buffer.from(data, 'base64'));
};
await capture('f2-shell-phone', 390, 844);
for (const label of ['Runs', 'Chat', 'Settings', 'Pipelines']) {
if (!await clickLabel(label)) throw new Error(`Could not interact with ${label} navigation`);
await delay(250);
const current = await evaluate("[...document.querySelectorAll('flt-semantics')].map(x=>x.getAttribute('aria-label')||x.innerText).filter(Boolean)");
if (!current?.some(x => x.includes(label))) throw new Error(`${label} missing after navigation`);
}
await capture('f2-shell-desktop', 1280, 800);
console.log(JSON.stringify({ labels, captures: ['f2-shell-phone.png', 'f2-shell-desktop.png'], navigated: ['Runs', 'Chat', 'Settings', 'Pipelines'] }, null, 2));
} finally {
ws?.close();
chrome.kill('SIGTERM');
await Promise.race([once(chrome, 'exit'), delay(3000)]);
server.close();
await rm(profile, { recursive: true, force: true });
}