fix: float the pet over the messages and let it be dragged

The pet used to sit in the column above the composer, reserving a strip of
its own: the message list ended there, which read as an opaque band cutting
off the last row. It is now a layer over the message area, so the list keeps
its full height and shows through around the sprite. Only the body of the
sheet takes touches (contentBox, 4dp out); taps and drags on the transparent
canvas still reach the messages underneath.

Dragging the body moves the pet along the composer's top edge (or the
activity cap's) with a small lift while held and the pack's drag reaction.
The spot is stored as a fraction of the width in pet.x.v1, so a restart or a
change in width puts it back in the same place. Taps now react on tap-up so a
drag does not fire a left/right reaction.

0.4.1 (401).
This commit is contained in:
blumia committed 2026-11-22 14:30:30 +08:00
1 parent d72af036a1
commit d25167de58
8 files changed
+348 -58

No files matched your search

+14
View File
@@ -5,6 +5,20 @@
--- ---
## 0.4.1 宠物浮在消息之上、可拖动(分支 `flutter`)
| 项 | 结果 |
| --- | --- |
| 不再占位 | `PetSlot` 换成 `PetLayer`:宠物画在消息列表的 Stack 上层,列表恢复完整高度,字会从宠物四周透出来,不再有一条空白带把最后一行截掉 |
| 透明 | 只有精灵本身作画;画布其余部分不填充。命中测试只认 `contentBox`(外扩 4px),点空白处仍然滚动/点消息 |
| 拖动 | 按住身体左右拖,脚沿输入框上沿移动;松手保存在本机(`pet.x.v1`,0–1 的比例),重启后回到同一位置,窄屏/旋转按比例换算并夹在两端内 |
| 拖动反馈 | 拖动时抬升 6px,并播放包里的 `drag`(`react-drag`)动画;没有该动画就保持当前状态,松手回到聊天状态 |
| 点击 | 从 `onTapDown` 改为 `onTapUp`,拖动不再误触发左右半区的 `tapLeft/tapRight` |
| 测试 | `test/pet_layer_test.dart`:空白处点击穿透、身体吃掉点击、拖动改位置并写入 prefs、无宠物时不画 |
| 版本 | **0.4.1(code 401)** |
---
## 0.4.0 输入框宠物:导入宠物包、精灵动画与状态(分支 `flutter`) ## 0.4.0 输入框宠物:导入宠物包、精灵动画与状态(分支 `flutter`)
| 项 | 结果 | | 项 | 结果 |
+4 -2
View File
@@ -5,7 +5,7 @@ Android first. This branch (`flutter`) is a framework evaluation: the same
feature set as the earlier Asuka/Go and MyGo attempts, reimplemented in feature set as the earlier Asuka/Go and MyGo attempts, reimplemented in
Flutter to compare mobile UI maturity. Flutter to compare mobile UI maturity.
Status: 0.4.0 — servers (passwordless / password login, HTTP/HTTPS and Status: 0.4.1 — servers (passwordless / password login, HTTP/HTTPS and
SOCKS5/socks5h proxy, self-signed certificates and pinning), session list with search and live SOCKS5/socks5h proxy, self-signed certificates and pinning), session list with search and live
events, chat with streaming Markdown and full history paging, tool steps events, chat with streaming Markdown and full history paging, tool steps
grouped per turn (icon, one-line summary, foldable run) with image previews, a grouped per turn (icon, one-line summary, foldable run) with image previews, a
@@ -26,7 +26,9 @@ pending bubble that can be withdrawn; while a turn runs, an activity strip above
the input names the current step and its clock instead of the finished turn's the input names the current step and its clock instead of the finished turn's
footer. Pets are opt-in: nothing is built in, and a dsh-Go sprite pack (a zip footer. Pets are opt-in: nothing is built in, and a dsh-Go sprite pack (a zip
with pack.json) is imported from Settings → 宠物 to stand above the input and with pack.json) is imported from Settings → 宠物 to stand above the input and
react to the turn's mood. The picker groups providers, favourites, react to the turn's mood. The pet floats over the messages (only its body
takes touches) and can be dragged along the input's top edge; the spot is
remembered on the device. The picker groups providers, favourites,
recents and context size. The sidebar footer names the connected server (tap to recents and context size. The sidebar footer names the connected server (tap to
switch) beside a settings key; settings holds appearance (theme mode and seed switch) beside a settings key; settings holds appearance (theme mode and seed
colour, device-local), the server's follow-up behavior (steer or queue on a send colour, device-local), the server's follow-up behavior (steer or queue on a send
+14
View File
@@ -26,6 +26,7 @@ class PetLibrary extends ChangeNotifier {
static const _activeKey = 'pet.active.v1'; static const _activeKey = 'pet.active.v1';
static const _enabledKey = 'pet.enabled.v1'; static const _enabledKey = 'pet.enabled.v1';
static const _sizeKey = 'pet.size.v1'; static const _sizeKey = 'pet.size.v1';
static const _positionKey = 'pet.x.v1';
/// The canvas width a pet is drawn at; the list offers these. /// The canvas width a pet is drawn at; the list offers these.
static const sizes = <double>[40, 52, 64]; static const sizes = <double>[40, 52, 64];
@@ -34,6 +35,9 @@ class PetLibrary extends ChangeNotifier {
bool enabled = false; bool enabled = false;
double size = 52; double size = 52;
/// Where the pet stands along its edge, 0 = left end, 1 = right end.
double position = 0.5;
String? _packDir; String? _packDir;
bool _loaded = false; bool _loaded = false;
@@ -53,6 +57,7 @@ class PetLibrary extends ChangeNotifier {
final prefs = await SharedPreferences.getInstance(); final prefs = await SharedPreferences.getInstance();
enabled = prefs.getBool(_enabledKey) ?? false; enabled = prefs.getBool(_enabledKey) ?? false;
size = (prefs.getDouble(_sizeKey) ?? 52).clamp(32, 80); size = (prefs.getDouble(_sizeKey) ?? 52).clamp(32, 80);
position = (prefs.getDouble(_positionKey) ?? 0.5).clamp(0.0, 1.0);
final active = prefs.getString(_activeKey); final active = prefs.getString(_activeKey);
if (active != null && active.isNotEmpty) { if (active != null && active.isNotEmpty) {
final root = await _petsRoot(); final root = await _petsRoot();
@@ -93,6 +98,15 @@ class PetLibrary extends ChangeNotifier {
} catch (_) {} } catch (_) {}
} }
Future<void> setPosition(double value) async {
position = value.clamp(0.0, 1.0);
notifyListeners();
try {
final prefs = await SharedPreferences.getInstance();
await prefs.setDouble(_positionKey, position);
} catch (_) {}
}
/// Unpacks and activates a pet package. [root] is for tests; the app uses /// Unpacks and activates a pet package. [root] is for tests; the app uses
/// the documents directory. /// the documents directory.
Future<PetPack> importZip(List<int> bytes, {Directory? root}) async { Future<PetPack> importZip(List<int> bytes, {Directory? root}) async {
+10 -2
View File
@@ -167,10 +167,18 @@ class _ChatScreenState extends State<ChatScreen> {
], ],
), ),
), ),
Expanded(child: _messageList()), Expanded(
child: Stack(
children: [
Positioned.fill(child: _messageList()),
// Over the messages, not in the column: the list keeps its
// full height and shows through around the pet.
Positioned.fill(child: PetLayer(state: _petState())),
],
),
),
_permissions(), _permissions(),
_forms(), _forms(),
PetSlot(state: _petState()),
if (chat.running) _activityStrip(), if (chat.running) _activityStrip(),
_composer(widget.keyboardInset), _composer(widget.keyboardInset),
], ],
+18 -12
View File
@@ -221,19 +221,26 @@ class _NewSessionScreenState extends State<NewSessionScreen> {
body: Column( body: Column(
children: [ children: [
Expanded( Expanded(
child: Center( child: Stack(
child: Padding( children: [
padding: const EdgeInsets.all(32), Positioned.fill(
child: Text( child: Center(
'我们今天要做什么?', child: Padding(
textAlign: TextAlign.center, padding: const EdgeInsets.all(32),
style: TextStyle( child: Text(
fontSize: 26, '我们今天要做什么?',
fontWeight: FontWeight.w600, textAlign: TextAlign.center,
color: scheme.onSurface, style: TextStyle(
fontSize: 26,
fontWeight: FontWeight.w600,
color: scheme.onSurface,
),
),
),
), ),
), ),
), const Positioned.fill(child: PetLayer(state: 'idle')),
],
), ),
), ),
Padding( Padding(
@@ -260,7 +267,6 @@ class _NewSessionScreenState extends State<NewSessionScreen> {
items: _attachments, items: _attachments,
onRemove: _removeAttachment, onRemove: _removeAttachment,
), ),
const PetSlot(state: 'idle'),
_composer(theme, widget.keyboardInset), _composer(theme, widget.keyboardInset),
], ],
), ),
+165 -41
View File
@@ -1,6 +1,7 @@
// The input-box pet. A PetSprite plays the pack's sheet frames; PetSlot is // The input-box pet. A PetSprite plays the pack's sheet frames; PetLayer is
// the strip it stands on, placed directly above the composer (or the activity // the floating layer it lives in, placed over the chat's message area so the
// cap when a turn runs). Nothing renders until a pack is imported and enabled. // messages keep their full height and show through around the pet. Nothing
// renders until a pack is imported and enabled.
import 'dart:async'; import 'dart:async';
import 'dart:ui' as ui; import 'dart:ui' as ui;
@@ -9,12 +10,27 @@ import 'package:flutter/material.dart';
import '../pets/pet_library.dart'; import '../pets/pet_library.dart';
import '../pets/pet_pack.dart'; import '../pets/pet_pack.dart';
/// The strip a pet stands on. It reserves the space above the baseline so the /// The pet over the chat. It reserves no layout space: the message list runs
/// sprite does not cover the last message; the feet rest on its bottom edge, /// underneath, and only the sprite's body takes touches. The feet rest on the
/// which is the composer's (or the activity cap's) top. /// bottom edge of the layer, which is the composer's top (or the activity
class PetSlot extends StatelessWidget { /// cap's while a turn runs). Dragging it sideways moves it along that edge.
class PetLayer extends StatefulWidget {
final String state; final String state;
const PetSlot({super.key, required this.state}); const PetLayer({super.key, required this.state});
@override
State<PetLayer> createState() => _PetLayerState();
}
class _PetLayerState extends State<PetLayer> {
/// Where the feet are, as a fraction of the layer's width. Null: use the
/// saved spot.
double? _fraction;
bool _dragging = false;
double _lift = 0;
/// How far from either end the body keeps, logical px.
static const _edge = 8.0;
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -24,30 +40,66 @@ class PetSlot extends StatelessWidget {
final library = PetLibrary.instance; final library = PetLibrary.instance;
final pack = library.pack; final pack = library.pack;
if (!library.enabled || pack == null) return const SizedBox.shrink(); if (!library.enabled || pack == null) return const SizedBox.shrink();
final scale = library.size / pack.canvas.width; return LayoutBuilder(builder: (context, constraints) {
final height = (pack.anchor.dy * scale).clamp(20.0, 80.0); final width = constraints.maxWidth;
return SizedBox( final size = library.size;
height: height, final scale = size / pack.canvas.width;
child: Align( final height = size * pack.canvas.height / pack.canvas.width;
alignment: Alignment.bottomCenter,
child: Transform.translate( // Body extents left and right of the feet, so dragging keeps the
// Put the anchor (the feet) on the bottom edge; the rest of the // whole pet on screen.
// canvas hangs above, inside the reserved strip. final leftExtent = (pack.anchor.dx - pack.contentBox.left) * scale;
offset: Offset( final rightExtent = (pack.contentBox.right - pack.anchor.dx) * scale;
(pack.canvas.width / 2 - pack.anchor.dx) * scale, final lo = leftExtent + _edge;
// The composer's own top padding sits between this strip and final hi = width - rightExtent - _edge;
// its visible capsule; step over it so the feet land on the final minFoot = hi <= lo ? width / 2 : lo;
// edge, not above it. final maxFoot = hi <= lo ? width / 2 : hi;
(pack.canvas.height - pack.anchor.dy) * scale + 6,
final fraction = (_fraction ?? library.position).clamp(0.0, 1.0);
final foot = (fraction * width).clamp(minFoot, maxFoot);
// Stand on the composer's top edge. The sprite's own canvas goes a
// little below the anchor, and the composer keeps a few px of top
// padding above its capsule, so step past both; that overflow is
// fine, the layer does not clip.
final bottom =
-((pack.canvas.height - pack.anchor.dy) * scale + 6) + _lift;
return Stack(
clipBehavior: Clip.none,
children: [
Positioned(
left: foot - pack.anchor.dx * scale,
bottom: bottom,
width: size,
height: height,
child: PetSprite(
pack: pack,
state: widget.state,
width: size,
dragging: _dragging,
onDragStart: () => setState(() {
_dragging = true;
_lift = -6;
}),
onDragUpdate: (dx) {
final next = ((_fraction ?? library.position) * width + dx)
.clamp(minFoot, maxFoot);
setState(() => _fraction = next / width);
},
onDragEnd: () {
final spot = _fraction;
setState(() {
_dragging = false;
_lift = 0;
});
if (spot != null) library.setPosition(spot);
},
),
), ),
child: PetSprite( ],
pack: pack, );
state: state, });
width: library.size,
),
),
),
);
}, },
); );
} }
@@ -60,11 +112,23 @@ class PetSprite extends StatefulWidget {
/// The pack canvas's on-screen width; the height follows the canvas ratio. /// The pack canvas's on-screen width; the height follows the canvas ratio.
final double width; final double width;
/// A drag is in progress: play the pack's drag reaction while held.
final bool dragging;
/// Called when the body is dragged; the layer moves the pet.
final VoidCallback? onDragStart;
final ValueChanged<double>? onDragUpdate;
final VoidCallback? onDragEnd;
const PetSprite({ const PetSprite({
super.key, super.key,
required this.pack, required this.pack,
required this.state, required this.state,
required this.width, required this.width,
this.dragging = false,
this.onDragStart,
this.onDragUpdate,
this.onDragEnd,
}); });
@override @override
@@ -83,6 +147,9 @@ class _PetSpriteState extends State<PetSprite> {
String? _oneShot; String? _oneShot;
String? _pendingState; String? _pendingState;
/// The drag reaction's name while a drag holds it.
String? _dragAnimation;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
@@ -95,9 +162,28 @@ class _PetSpriteState extends State<PetSprite> {
if (oldWidget.pack != widget.pack) { if (oldWidget.pack != widget.pack) {
_oneShot = null; _oneShot = null;
_pendingState = null; _pendingState = null;
_dragAnimation = null;
_begin(widget.state); _begin(widget.state);
} else if (oldWidget.state != widget.state) { return;
if (_oneShot != null) { }
if (oldWidget.dragging != widget.dragging) {
_oneShot = null;
if (widget.dragging) {
final drag = widget.pack.reactions['drag'];
_dragAnimation =
drag != null && widget.pack.animations.containsKey(drag) ? drag : null;
final name = _dragAnimation ?? widget.pack.animationForState(widget.state);
if (name != null) _beginNamed(name);
} else {
final next = _pendingState ?? widget.state;
_pendingState = null;
_dragAnimation = null;
_begin(next);
}
return;
}
if (oldWidget.state != widget.state) {
if (_oneShot != null || widget.dragging) {
_pendingState = widget.state; _pendingState = widget.state;
} else { } else {
_begin(widget.state); _begin(widget.state);
@@ -111,10 +197,10 @@ class _PetSpriteState extends State<PetSprite> {
super.dispose(); super.dispose();
} }
void _begin(String state) { void _begin(String state) => _beginNamed(widget.pack.animationForState(state));
final animation = widget.pack.animation(
widget.pack.animationForState(state), void _beginNamed(String? name) {
); final animation = widget.pack.animation(name);
if (animation == null) { if (animation == null) {
_timer?.cancel(); _timer?.cancel();
_animation = null; _animation = null;
@@ -164,6 +250,16 @@ class _PetSpriteState extends State<PetSprite> {
setState(() {}); setState(() {});
return; return;
} }
// Held by a drag: keep the pose until it is let go, even when the pack's
// drag sheet plays once.
if (widget.dragging &&
_dragAnimation != null &&
animation.name == _dragAnimation &&
!animation.loop) {
setState(() => _frame = 0);
_schedule();
return;
}
if (animation.loop) { if (animation.loop) {
setState(() => _frame = 0); setState(() => _frame = 0);
_schedule(); _schedule();
@@ -173,7 +269,7 @@ class _PetSpriteState extends State<PetSprite> {
setState(() {}); setState(() {});
} }
void _react(TapDownDetails details) { void _react(TapUpDetails details) {
final left = details.localPosition.dx < widget.width / 2; final left = details.localPosition.dx < widget.width / 2;
final name = widget.pack.reactions[left ? 'tapLeft' : 'tapRight']; final name = widget.pack.reactions[left ? 'tapLeft' : 'tapRight'];
final animation = widget.pack.animation(name); final animation = widget.pack.animation(name);
@@ -192,8 +288,15 @@ class _PetSpriteState extends State<PetSprite> {
final width = widget.width; final width = widget.width;
final height = width * widget.pack.canvas.height / widget.pack.canvas.width; final height = width * widget.pack.canvas.height / widget.pack.canvas.width;
return GestureDetector( return GestureDetector(
behavior: HitTestBehavior.opaque, // Only the body takes touches; the rest of the layer lets the message
onTapDown: _react, // list scroll.
behavior: HitTestBehavior.deferToChild,
onTapUp: _react,
onHorizontalDragStart: (_) => widget.onDragStart?.call(),
onHorizontalDragUpdate: (details) =>
widget.onDragUpdate?.call(details.delta.dx),
onHorizontalDragEnd: (_) => widget.onDragEnd?.call(),
onHorizontalDragCancel: () => widget.onDragEnd?.call(),
child: CustomPaint( child: CustomPaint(
size: Size(width, height), size: Size(width, height),
painter: _PetPainter( painter: _PetPainter(
@@ -201,6 +304,7 @@ class _PetSpriteState extends State<PetSprite> {
animation: _animation, animation: _animation,
image: _image, image: _image,
frame: _frame, frame: _frame,
spriteSize: Size(width, height),
), ),
), ),
); );
@@ -213,13 +317,32 @@ class _PetPainter extends CustomPainter {
final ui.Image? image; final ui.Image? image;
final int frame; final int frame;
/// The on-screen size, for hit testing.
final Size spriteSize;
const _PetPainter({ const _PetPainter({
required this.pack, required this.pack,
required this.animation, required this.animation,
required this.image, required this.image,
required this.frame, required this.frame,
required this.spriteSize,
}); });
/// The body only: taps and drags on the transparent canvas around it go to
/// whatever is underneath.
@override
bool? hitTest(Offset position) {
if (spriteSize.width <= 0) return false;
final scale = spriteSize.width / pack.canvas.width;
final body = Rect.fromLTRB(
pack.contentBox.left * scale,
pack.contentBox.top * scale,
pack.contentBox.right * scale,
pack.contentBox.bottom * scale,
).inflate(4);
return body.contains(position);
}
@override @override
void paint(Canvas canvas, Size size) { void paint(Canvas canvas, Size size) {
final animation = this.animation; final animation = this.animation;
@@ -263,5 +386,6 @@ class _PetPainter extends CustomPainter {
oldDelegate.image != image || oldDelegate.image != image ||
oldDelegate.animation != animation || oldDelegate.animation != animation ||
oldDelegate.frame != frame || oldDelegate.frame != frame ||
oldDelegate.pack != pack; oldDelegate.pack != pack ||
oldDelegate.spriteSize != spriteSize;
} }
+1 -1
View File
@@ -2,7 +2,7 @@ name: openchamber
description: "A lightweight OpenChamber client for phones." description: "A lightweight OpenChamber client for phones."
publish_to: 'none' publish_to: 'none'
version: 0.4.0+400 version: 0.4.1+401
environment: environment:
sdk: ^3.14.0 sdk: ^3.14.0
+122
View File
@@ -0,0 +1,122 @@
import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:openchamber/pets/pet_library.dart';
import 'package:openchamber/pets/pet_pack.dart';
import 'package:openchamber/widgets/pet_sprite.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() {
TestWidgetsFlutterBinding.ensureInitialized();
final library = PetLibrary.instance;
setUp(() async {
SharedPreferences.setMockInitialValues({});
library.pack = PetPack.fromJson(
jsonDecode(File('test/fixtures/deepy-pack.json').readAsStringSync())
as Map<String, dynamic>,
);
library.enabled = true;
library.size = 52;
library.position = 0.5;
});
tearDown(() {
library.pack = null;
library.enabled = false;
library.position = 0.5;
});
/// The chat's shape: a message area with the pet floating over it and the
/// composer below.
Future<int Function()> pumpChat(WidgetTester tester) async {
var taps = 0;
await tester.pumpWidget(
MaterialApp(
home: Scaffold(
body: Column(
children: [
Expanded(
child: Stack(
children: [
Positioned.fill(
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: () => taps++,
child: const ColoredBox(color: Color(0xFF101014)),
),
),
const Positioned.fill(child: PetLayer(state: 'idle')),
],
),
),
const SizedBox(height: 80),
],
),
),
),
);
await tester.pump();
return () => taps;
}
testWidgets('the pet floats over the messages and only its body takes taps',
(tester) async {
final taps = await pumpChat(tester);
expect(find.byType(PetSprite), findsOneWidget);
final pet = tester.getCenter(find.byType(PetSprite));
// The transparent part of the layer is not a hit target: the message
// area still receives the tap.
await tester.tapAt(Offset(pet.dx - 160, pet.dy));
await tester.pump();
expect(taps(), 1);
// The body is: tapping it reacts instead of reaching the page.
await tester.tapAt(pet);
await tester.pump();
expect(taps(), 1);
// Nothing reserved in the layout: the message area runs under the pet, so
// the pet's box reaches the composer's top edge.
final layer = tester.getRect(find.byType(PetLayer));
final sprite = tester.getRect(find.byType(PetSprite));
expect(layer.bottom, closeTo(sprite.bottom - 10, 0.5));
expect(sprite.bottom, greaterThanOrEqualTo(layer.bottom));
await tester.pumpWidget(const SizedBox());
});
testWidgets('dragging the pet moves it and keeps the spot', (tester) async {
await pumpChat(tester);
final before = tester.getTopLeft(find.byType(PetSprite)).dx;
await tester.drag(find.byType(PetSprite), const Offset(80, 0));
await tester.pump();
final after = tester.getTopLeft(find.byType(PetSprite)).dx;
expect(after, greaterThan(before + 50));
expect(library.position, greaterThan(0.5));
final prefs = await SharedPreferences.getInstance();
expect(prefs.getDouble('pet.x.v1'), library.position);
await tester.pumpWidget(const SizedBox());
});
testWidgets('nothing is drawn without an imported, enabled pet',
(tester) async {
library.enabled = false;
final taps = await pumpChat(tester);
expect(find.byType(PetSprite), findsNothing);
await tester.tapAt(const Offset(100, 100));
await tester.pump();
expect(taps(), 1);
await tester.pumpWidget(const SizedBox());
});
}