From d25167de5838b8401cc8aa53038c5810b351852e Mon Sep 17 00:00:00 2001 From: Wang Zichong Date: Sun, 22 Nov 2026 14:30:30 +0800 Subject: [PATCH] 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). --- PLAN.md | 14 ++ README.md | 6 +- lib/pets/pet_library.dart | 14 ++ lib/screens/chat_screen.dart | 12 +- lib/screens/new_session_screen.dart | 30 ++-- lib/widgets/pet_sprite.dart | 206 ++++++++++++++++++++++------ pubspec.yaml | 2 +- test/pet_layer_test.dart | 122 ++++++++++++++++ 8 files changed, 348 insertions(+), 58 deletions(-) create mode 100644 test/pet_layer_test.dart diff --git a/PLAN.md b/PLAN.md index 265c6e5..7b481fe 100644 --- a/PLAN.md +++ b/PLAN.md @@ -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`) | 项 | 结果 | diff --git a/README.md b/README.md index b8a9d6a..30f24f0 100644 --- a/README.md +++ b/README.md @@ -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 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 events, chat with streaming Markdown and full history paging, tool steps 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 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 -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 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 diff --git a/lib/pets/pet_library.dart b/lib/pets/pet_library.dart index 51bb32c..5283ef8 100644 --- a/lib/pets/pet_library.dart +++ b/lib/pets/pet_library.dart @@ -26,6 +26,7 @@ class PetLibrary extends ChangeNotifier { static const _activeKey = 'pet.active.v1'; static const _enabledKey = 'pet.enabled.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. static const sizes = [40, 52, 64]; @@ -34,6 +35,9 @@ class PetLibrary extends ChangeNotifier { bool enabled = false; double size = 52; + /// Where the pet stands along its edge, 0 = left end, 1 = right end. + double position = 0.5; + String? _packDir; bool _loaded = false; @@ -53,6 +57,7 @@ class PetLibrary extends ChangeNotifier { final prefs = await SharedPreferences.getInstance(); enabled = prefs.getBool(_enabledKey) ?? false; size = (prefs.getDouble(_sizeKey) ?? 52).clamp(32, 80); + position = (prefs.getDouble(_positionKey) ?? 0.5).clamp(0.0, 1.0); final active = prefs.getString(_activeKey); if (active != null && active.isNotEmpty) { final root = await _petsRoot(); @@ -93,6 +98,15 @@ class PetLibrary extends ChangeNotifier { } catch (_) {} } + Future 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 /// the documents directory. Future importZip(List bytes, {Directory? root}) async { diff --git a/lib/screens/chat_screen.dart b/lib/screens/chat_screen.dart index 4614328..a3c7cd3 100644 --- a/lib/screens/chat_screen.dart +++ b/lib/screens/chat_screen.dart @@ -167,10 +167,18 @@ class _ChatScreenState extends State { ], ), ), - 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(), _forms(), - PetSlot(state: _petState()), if (chat.running) _activityStrip(), _composer(widget.keyboardInset), ], diff --git a/lib/screens/new_session_screen.dart b/lib/screens/new_session_screen.dart index ad35ec6..0e1c61e 100644 --- a/lib/screens/new_session_screen.dart +++ b/lib/screens/new_session_screen.dart @@ -221,19 +221,26 @@ class _NewSessionScreenState extends State { body: Column( children: [ Expanded( - child: Center( - child: Padding( - padding: const EdgeInsets.all(32), - child: Text( - '我们今天要做什么?', - textAlign: TextAlign.center, - style: TextStyle( - fontSize: 26, - fontWeight: FontWeight.w600, - color: scheme.onSurface, + child: Stack( + children: [ + Positioned.fill( + child: Center( + child: Padding( + padding: const EdgeInsets.all(32), + child: Text( + '我们今天要做什么?', + textAlign: TextAlign.center, + style: TextStyle( + fontSize: 26, + fontWeight: FontWeight.w600, + color: scheme.onSurface, + ), + ), + ), ), ), - ), + const Positioned.fill(child: PetLayer(state: 'idle')), + ], ), ), Padding( @@ -260,7 +267,6 @@ class _NewSessionScreenState extends State { items: _attachments, onRemove: _removeAttachment, ), - const PetSlot(state: 'idle'), _composer(theme, widget.keyboardInset), ], ), diff --git a/lib/widgets/pet_sprite.dart b/lib/widgets/pet_sprite.dart index dc71edb..908ac4c 100644 --- a/lib/widgets/pet_sprite.dart +++ b/lib/widgets/pet_sprite.dart @@ -1,6 +1,7 @@ -// The input-box pet. A PetSprite plays the pack's sheet frames; PetSlot is -// the strip it stands on, placed directly above the composer (or the activity -// cap when a turn runs). Nothing renders until a pack is imported and enabled. +// The input-box pet. A PetSprite plays the pack's sheet frames; PetLayer is +// the floating layer it lives in, placed over the chat's message area so the +// 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:ui' as ui; @@ -9,12 +10,27 @@ import 'package:flutter/material.dart'; import '../pets/pet_library.dart'; import '../pets/pet_pack.dart'; -/// The strip a pet stands on. It reserves the space above the baseline so the -/// sprite does not cover the last message; the feet rest on its bottom edge, -/// which is the composer's (or the activity cap's) top. -class PetSlot extends StatelessWidget { +/// The pet over the chat. It reserves no layout space: the message list runs +/// underneath, and only the sprite's body takes touches. The feet rest on the +/// bottom edge of the layer, which is the composer's top (or the activity +/// cap's while a turn runs). Dragging it sideways moves it along that edge. +class PetLayer extends StatefulWidget { final String state; - const PetSlot({super.key, required this.state}); + const PetLayer({super.key, required this.state}); + + @override + State createState() => _PetLayerState(); +} + +class _PetLayerState extends State { + /// 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 Widget build(BuildContext context) { @@ -24,30 +40,66 @@ class PetSlot extends StatelessWidget { final library = PetLibrary.instance; final pack = library.pack; if (!library.enabled || pack == null) return const SizedBox.shrink(); - final scale = library.size / pack.canvas.width; - final height = (pack.anchor.dy * scale).clamp(20.0, 80.0); - return SizedBox( - height: height, - child: Align( - alignment: Alignment.bottomCenter, - child: Transform.translate( - // Put the anchor (the feet) on the bottom edge; the rest of the - // canvas hangs above, inside the reserved strip. - offset: Offset( - (pack.canvas.width / 2 - pack.anchor.dx) * scale, - // The composer's own top padding sits between this strip and - // its visible capsule; step over it so the feet land on the - // edge, not above it. - (pack.canvas.height - pack.anchor.dy) * scale + 6, + return LayoutBuilder(builder: (context, constraints) { + final width = constraints.maxWidth; + final size = library.size; + final scale = size / pack.canvas.width; + final height = size * pack.canvas.height / pack.canvas.width; + + // Body extents left and right of the feet, so dragging keeps the + // whole pet on screen. + final leftExtent = (pack.anchor.dx - pack.contentBox.left) * scale; + final rightExtent = (pack.contentBox.right - pack.anchor.dx) * scale; + final lo = leftExtent + _edge; + final hi = width - rightExtent - _edge; + final minFoot = hi <= lo ? width / 2 : lo; + final maxFoot = hi <= lo ? width / 2 : hi; + + 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. 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? onDragUpdate; + final VoidCallback? onDragEnd; + const PetSprite({ super.key, required this.pack, required this.state, required this.width, + this.dragging = false, + this.onDragStart, + this.onDragUpdate, + this.onDragEnd, }); @override @@ -83,6 +147,9 @@ class _PetSpriteState extends State { String? _oneShot; String? _pendingState; + /// The drag reaction's name while a drag holds it. + String? _dragAnimation; + @override void initState() { super.initState(); @@ -95,9 +162,28 @@ class _PetSpriteState extends State { if (oldWidget.pack != widget.pack) { _oneShot = null; _pendingState = null; + _dragAnimation = null; _begin(widget.state); - } else if (oldWidget.state != widget.state) { - if (_oneShot != null) { + return; + } + 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; } else { _begin(widget.state); @@ -111,10 +197,10 @@ class _PetSpriteState extends State { super.dispose(); } - void _begin(String state) { - final animation = widget.pack.animation( - widget.pack.animationForState(state), - ); + void _begin(String state) => _beginNamed(widget.pack.animationForState(state)); + + void _beginNamed(String? name) { + final animation = widget.pack.animation(name); if (animation == null) { _timer?.cancel(); _animation = null; @@ -164,6 +250,16 @@ class _PetSpriteState extends State { setState(() {}); 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) { setState(() => _frame = 0); _schedule(); @@ -173,7 +269,7 @@ class _PetSpriteState extends State { setState(() {}); } - void _react(TapDownDetails details) { + void _react(TapUpDetails details) { final left = details.localPosition.dx < widget.width / 2; final name = widget.pack.reactions[left ? 'tapLeft' : 'tapRight']; final animation = widget.pack.animation(name); @@ -192,8 +288,15 @@ class _PetSpriteState extends State { final width = widget.width; final height = width * widget.pack.canvas.height / widget.pack.canvas.width; return GestureDetector( - behavior: HitTestBehavior.opaque, - onTapDown: _react, + // Only the body takes touches; the rest of the layer lets the message + // 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( size: Size(width, height), painter: _PetPainter( @@ -201,6 +304,7 @@ class _PetSpriteState extends State { animation: _animation, image: _image, frame: _frame, + spriteSize: Size(width, height), ), ), ); @@ -213,13 +317,32 @@ class _PetPainter extends CustomPainter { final ui.Image? image; final int frame; + /// The on-screen size, for hit testing. + final Size spriteSize; + const _PetPainter({ required this.pack, required this.animation, required this.image, 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 void paint(Canvas canvas, Size size) { final animation = this.animation; @@ -263,5 +386,6 @@ class _PetPainter extends CustomPainter { oldDelegate.image != image || oldDelegate.animation != animation || oldDelegate.frame != frame || - oldDelegate.pack != pack; + oldDelegate.pack != pack || + oldDelegate.spriteSize != spriteSize; } diff --git a/pubspec.yaml b/pubspec.yaml index 1cf093f..51542db 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -2,7 +2,7 @@ name: openchamber description: "A lightweight OpenChamber client for phones." publish_to: 'none' -version: 0.4.0+400 +version: 0.4.1+401 environment: sdk: ^3.14.0 diff --git a/test/pet_layer_test.dart b/test/pet_layer_test.dart new file mode 100644 index 0000000..21591af --- /dev/null +++ b/test/pet_layer_test.dart @@ -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, + ); + 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 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()); + }); +}