feat(market): save others' offers as favorites (Wallapop-style)

Adds a Favorites feature: a heart on the offer detail saves another
person's listing to an encrypted, per-identity SavedOffersStore
(keystore JSON snapshot, no plaintext at rest). A new /favorites screen
(wired from the drawer) lists saved offers offline-first and, when a
relay is reachable, flags ones that are gone as "no longer available".
i18n en/es/pt/ast; store + screen + detail-heart tests.
This commit is contained in:
vjrj 2026-07-13 08:21:43 +02:00
parent f6967e8cbb
commit d6225eed38
19 changed files with 806 additions and 3 deletions

View file

@ -17,6 +17,7 @@ import 'services/offer_outbox.dart';
import 'services/onboarding_store.dart';
import 'services/profile_cache.dart';
import 'services/profile_store.dart';
import 'services/saved_offers_store.dart';
import 'services/social_account_store.dart';
import 'services/social_connection.dart';
import 'services/social_service.dart';
@ -28,6 +29,7 @@ import 'ui/auto_backup_gate.dart';
import 'ui/calendar_screen.dart';
import 'ui/chat_list_screen.dart';
import 'ui/chat_screen.dart';
import 'ui/favorites_screen.dart';
import 'ui/home_screen.dart';
import 'ui/intro_screen.dart';
import 'ui/inventory_list_screen.dart';
@ -58,6 +60,7 @@ class TaneApp extends StatelessWidget {
this.messageStore,
this.profileStore,
this.profileCache,
this.savedOffers,
this.socialAccounts,
this.inbox,
this.notifications,
@ -76,6 +79,7 @@ class TaneApp extends StatelessWidget {
messageStore,
profileStore,
profileCache,
savedOffers,
socialAccounts,
inbox,
) {
@ -112,6 +116,9 @@ class TaneApp extends StatelessWidget {
/// Optional cache of peers' published display names.
final ProfileCache? profileCache;
/// Optional store of the user's saved ("favorite") market offers.
final SavedOffersStore? savedOffers;
/// Optional store of the active social identity, for the profile switcher.
final SocialAccountStore? socialAccounts;
@ -140,6 +147,7 @@ class TaneApp extends StatelessWidget {
MessageStore? messageStore,
ProfileStore? profileStore,
ProfileCache? profileCache,
SavedOffersStore? savedOffers,
SocialAccountStore? socialAccounts,
InboxService? inbox,
) {
@ -173,9 +181,18 @@ class TaneApp extends StatelessWidget {
mine: offer.authorPubkeyHex == social.publicKeyHex,
profileCache: profileCache,
selfPubkey: social.publicKeyHex,
savedOffers: savedOffers,
);
},
),
if (social != null && savedOffers != null)
GoRoute(
path: '/favorites',
builder: (context, state) => FavoritesScreen(
savedOffers: savedOffers,
connection: connection,
),
),
if (messageStore != null)
GoRoute(
path: '/messages',

View file

@ -18,6 +18,7 @@ import 'services/offer_outbox.dart';
import 'services/onboarding_store.dart';
import 'services/profile_cache.dart';
import 'services/profile_store.dart';
import 'services/saved_offers_store.dart';
import 'services/social_account_store.dart';
import 'services/social_connection.dart';
import 'services/social_service.dart';
@ -85,6 +86,7 @@ class _BootstrapState extends State<Bootstrap> {
messageStore: getIt<MessageStore>(),
profileStore: getIt<ProfileStore>(),
profileCache: getIt<ProfileCache>(),
savedOffers: getIt<SavedOffersStore>(),
socialAccounts: getIt<SocialAccountStore>(),
inbox: inbox,
notifications: notifications,

View file

@ -39,6 +39,7 @@ import '../services/message_store.dart';
import '../services/offer_outbox.dart';
import '../services/profile_cache.dart';
import '../services/profile_store.dart';
import '../services/saved_offers_store.dart';
import '../services/social_account_store.dart';
import '../services/social_connection.dart';
import '../services/social_service.dart';
@ -184,6 +185,9 @@ Future<void> configureDependencies() async {
..registerSingleton<ProfileCache>(
ProfileCache(secretStore, accountScope: scope),
)
..registerSingleton<SavedOffersStore>(
SavedOffersStore(secretStore, accountScope: scope),
)
..registerSingleton<ExportImportService>(
ExportImportService(
repository: varietyRepository,
@ -301,6 +305,8 @@ Future<void> switchSocialAccount(int account) async {
await getIt.unregister<MessageStore>();
await getIt.unregister<ProfileStore>();
await getIt.unregister<ProfileCache>();
await getIt<SavedOffersStore>().close();
await getIt.unregister<SavedOffersStore>();
// Re-register the per-identity stores under the new scope, then the identity.
getIt
@ -313,6 +319,9 @@ Future<void> switchSocialAccount(int account) async {
..registerSingleton<ProfileCache>(
ProfileCache(secretStore, accountScope: scope),
)
..registerSingleton<SavedOffersStore>(
SavedOffersStore(secretStore, accountScope: scope),
)
..registerSingleton<UnreadService>(
UnreadService(getIt<MessageStore>(), secretStore),
);

View file

@ -5,6 +5,13 @@
"illustration": "O escueyi un dibuxu",
"remove": "Quitar"
},
"favorites": {
"title": "Favoritos",
"empty": "Entá nun tienes favoritos. Guarda ofertes que te presten del mercáu.",
"save": "Guardar en favoritos",
"remove": "Quitar de favoritos",
"unavailable": "Yá nun ta disponible"
},
"seedSaving": {
"title": "Guardar la so semiente",
"subtitle": "Lo que fai falta pa caltener la variedá fiel",

View file

@ -5,6 +5,13 @@
"illustration": "Or pick an illustration",
"remove": "Remove"
},
"favorites": {
"title": "Favorites",
"empty": "No favorites yet. Save offers you like from the market.",
"save": "Save to favorites",
"remove": "Remove from favorites",
"unavailable": "No longer available"
},
"seedSaving": {
"title": "Saving its seed",
"subtitle": "What it takes to keep the variety true",

View file

@ -5,6 +5,13 @@
"illustration": "O elige un dibujo",
"remove": "Quitar"
},
"favorites": {
"title": "Favoritos",
"empty": "Aún no tienes favoritos. Guarda ofertas que te gusten del mercado.",
"save": "Guardar en favoritos",
"remove": "Quitar de favoritos",
"unavailable": "Ya no está disponible"
},
"seedSaving": {
"title": "Conservar su semilla",
"subtitle": "Lo que hace falta para mantener la variedad fiel",

View file

@ -5,6 +5,13 @@
"illustration": "Ou escolhe um desenho",
"remove": "Remover"
},
"favorites": {
"title": "Favoritos",
"empty": "Ainda não tens favoritos. Guarda ofertas que gostes do mercado.",
"save": "Guardar nos favoritos",
"remove": "Remover dos favoritos",
"unavailable": "Já não está disponível"
},
"seedSaving": {
"title": "Guardar a sua semente",
"subtitle": "O que é preciso para manter a variedade fiel",

View file

@ -4,9 +4,9 @@
/// To regenerate, run: `dart run slang`
///
/// Locales: 4
/// Strings: 2032 (508 per locale)
/// Strings: 2052 (513 per locale)
///
/// Built on 2026-07-12 at 10:59 UTC
/// Built on 2026-07-13 at 05:54 UTC
// coverage:ignore-file
// ignore_for_file: type=lint, unused_import

View file

@ -40,6 +40,7 @@ class TranslationsAst extends Translations with BaseTranslations<AppLocale, Tran
// Translations
@override late final _Translations$avatar$ast avatar = _Translations$avatar$ast._(_root);
@override late final _Translations$favorites$ast favorites = _Translations$favorites$ast._(_root);
@override late final _Translations$seedSaving$ast seedSaving = _Translations$seedSaving$ast._(_root);
@override late final _Translations$calendar$ast calendar = _Translations$calendar$ast._(_root);
@override late final _Translations$app$ast app = _Translations$app$ast._(_root);
@ -99,6 +100,20 @@ class _Translations$avatar$ast extends Translations$avatar$en {
@override String get remove => 'Quitar';
}
// Path: favorites
class _Translations$favorites$ast extends Translations$favorites$en {
_Translations$favorites$ast._(TranslationsAst root) : this._root = root, super.internal(root);
final TranslationsAst _root; // ignore: unused_field
// Translations
@override String get title => 'Favoritos';
@override String get empty => 'Entá nun tienes favoritos. Guarda ofertes que te presten del mercáu.';
@override String get save => 'Guardar en favoritos';
@override String get remove => 'Quitar de favoritos';
@override String get unavailable => 'Yá nun ta disponible';
}
// Path: seedSaving
class _Translations$seedSaving$ast extends Translations$seedSaving$en {
_Translations$seedSaving$ast._(TranslationsAst root) : this._root = root, super.internal(root);
@ -1312,6 +1327,11 @@ extension on TranslationsAst {
'avatar.fromPhoto' => 'Facer o escoyer una semeya',
'avatar.illustration' => 'O escueyi un dibuxu',
'avatar.remove' => 'Quitar',
'favorites.title' => 'Favoritos',
'favorites.empty' => 'Entá nun tienes favoritos. Guarda ofertes que te presten del mercáu.',
'favorites.save' => 'Guardar en favoritos',
'favorites.remove' => 'Quitar de favoritos',
'favorites.unavailable' => 'Yá nun ta disponible',
'seedSaving.title' => 'Guardar la so semiente',
'seedSaving.subtitle' => 'Lo que fai falta pa caltener la variedá fiel',
'seedSaving.lifeCycle' => 'Ciclu',

View file

@ -41,6 +41,7 @@ class Translations with BaseTranslations<AppLocale, Translations> {
// Translations
late final Translations$avatar$en avatar = Translations$avatar$en.internal(_root);
late final Translations$favorites$en favorites = Translations$favorites$en.internal(_root);
late final Translations$seedSaving$en seedSaving = Translations$seedSaving$en.internal(_root);
late final Translations$calendar$en calendar = Translations$calendar$en.internal(_root);
late final Translations$app$en app = Translations$app$en.internal(_root);
@ -108,6 +109,30 @@ class Translations$avatar$en {
String get remove => 'Remove';
}
// Path: favorites
class Translations$favorites$en {
Translations$favorites$en.internal(this._root);
final Translations _root; // ignore: unused_field
// Translations
/// en: 'Favorites'
String get title => 'Favorites';
/// en: 'No favorites yet. Save offers you like from the market.'
String get empty => 'No favorites yet. Save offers you like from the market.';
/// en: 'Save to favorites'
String get save => 'Save to favorites';
/// en: 'Remove from favorites'
String get remove => 'Remove from favorites';
/// en: 'No longer available'
String get unavailable => 'No longer available';
}
// Path: seedSaving
class Translations$seedSaving$en {
Translations$seedSaving$en.internal(this._root);
@ -2315,6 +2340,11 @@ extension on Translations {
'avatar.fromPhoto' => 'Take or choose a photo',
'avatar.illustration' => 'Or pick an illustration',
'avatar.remove' => 'Remove',
'favorites.title' => 'Favorites',
'favorites.empty' => 'No favorites yet. Save offers you like from the market.',
'favorites.save' => 'Save to favorites',
'favorites.remove' => 'Remove from favorites',
'favorites.unavailable' => 'No longer available',
'seedSaving.title' => 'Saving its seed',
'seedSaving.subtitle' => 'What it takes to keep the variety true',
'seedSaving.lifeCycle' => 'Cycle',
@ -2818,6 +2848,8 @@ extension on Translations {
'sale.currencyHint' => '€, Ğ1, hours… (optional)',
'sale.hours' => 'hours',
'sale.note' => 'Note (optional)',
_ => null,
} ?? switch (path) {
'sale.save' => 'Save',
'sale.delete' => 'Remove',
'sale.removeConfirm' => 'Remove this sale?',

View file

@ -40,6 +40,7 @@ class TranslationsEs extends Translations with BaseTranslations<AppLocale, Trans
// Translations
@override late final _Translations$avatar$es avatar = _Translations$avatar$es._(_root);
@override late final _Translations$favorites$es favorites = _Translations$favorites$es._(_root);
@override late final _Translations$seedSaving$es seedSaving = _Translations$seedSaving$es._(_root);
@override late final _Translations$calendar$es calendar = _Translations$calendar$es._(_root);
@override late final _Translations$app$es app = _Translations$app$es._(_root);
@ -99,6 +100,20 @@ class _Translations$avatar$es extends Translations$avatar$en {
@override String get remove => 'Quitar';
}
// Path: favorites
class _Translations$favorites$es extends Translations$favorites$en {
_Translations$favorites$es._(TranslationsEs root) : this._root = root, super.internal(root);
final TranslationsEs _root; // ignore: unused_field
// Translations
@override String get title => 'Favoritos';
@override String get empty => 'Aún no tienes favoritos. Guarda ofertas que te gusten del mercado.';
@override String get save => 'Guardar en favoritos';
@override String get remove => 'Quitar de favoritos';
@override String get unavailable => 'Ya no está disponible';
}
// Path: seedSaving
class _Translations$seedSaving$es extends Translations$seedSaving$en {
_Translations$seedSaving$es._(TranslationsEs root) : this._root = root, super.internal(root);
@ -1314,6 +1329,11 @@ extension on TranslationsEs {
'avatar.fromPhoto' => 'Hacer o elegir una foto',
'avatar.illustration' => 'O elige un dibujo',
'avatar.remove' => 'Quitar',
'favorites.title' => 'Favoritos',
'favorites.empty' => 'Aún no tienes favoritos. Guarda ofertas que te gusten del mercado.',
'favorites.save' => 'Guardar en favoritos',
'favorites.remove' => 'Quitar de favoritos',
'favorites.unavailable' => 'Ya no está disponible',
'seedSaving.title' => 'Conservar su semilla',
'seedSaving.subtitle' => 'Lo que hace falta para mantener la variedad fiel',
'seedSaving.lifeCycle' => 'Ciclo',
@ -1817,6 +1837,8 @@ extension on TranslationsEs {
'sale.hours' => 'horas',
'sale.note' => 'Nota (opcional)',
'sale.save' => 'Guardar',
_ => null,
} ?? switch (path) {
'sale.delete' => 'Quitar',
'sale.removeConfirm' => '¿Quitar esta venta?',
_ => null,

View file

@ -40,6 +40,7 @@ class TranslationsPt extends Translations with BaseTranslations<AppLocale, Trans
// Translations
@override late final _Translations$avatar$pt avatar = _Translations$avatar$pt._(_root);
@override late final _Translations$favorites$pt favorites = _Translations$favorites$pt._(_root);
@override late final _Translations$seedSaving$pt seedSaving = _Translations$seedSaving$pt._(_root);
@override late final _Translations$calendar$pt calendar = _Translations$calendar$pt._(_root);
@override late final _Translations$app$pt app = _Translations$app$pt._(_root);
@ -99,6 +100,20 @@ class _Translations$avatar$pt extends Translations$avatar$en {
@override String get remove => 'Remover';
}
// Path: favorites
class _Translations$favorites$pt extends Translations$favorites$en {
_Translations$favorites$pt._(TranslationsPt root) : this._root = root, super.internal(root);
final TranslationsPt _root; // ignore: unused_field
// Translations
@override String get title => 'Favoritos';
@override String get empty => 'Ainda não tens favoritos. Guarda ofertas que gostes do mercado.';
@override String get save => 'Guardar nos favoritos';
@override String get remove => 'Remover dos favoritos';
@override String get unavailable => 'Já não está disponível';
}
// Path: seedSaving
class _Translations$seedSaving$pt extends Translations$seedSaving$en {
_Translations$seedSaving$pt._(TranslationsPt root) : this._root = root, super.internal(root);
@ -1311,6 +1326,11 @@ extension on TranslationsPt {
'avatar.fromPhoto' => 'Tirar ou escolher uma foto',
'avatar.illustration' => 'Ou escolhe um desenho',
'avatar.remove' => 'Remover',
'favorites.title' => 'Favoritos',
'favorites.empty' => 'Ainda não tens favoritos. Guarda ofertas que gostes do mercado.',
'favorites.save' => 'Guardar nos favoritos',
'favorites.remove' => 'Remover dos favoritos',
'favorites.unavailable' => 'Já não está disponível',
'seedSaving.title' => 'Guardar a sua semente',
'seedSaving.subtitle' => 'O que é preciso para manter a variedade fiel',
'seedSaving.lifeCycle' => 'Ciclo',

View file

@ -0,0 +1,123 @@
import 'dart:async';
import 'dart:convert';
import 'package:commons_core/commons_core.dart';
import '../security/secret_store.dart';
/// A person's saved ("favorite") market offers — other people's listings they
/// bookmarked, Wallapop-style. Keystore-backed (no plaintext at rest) and
/// namespaced by the active identity's [accountScope], like [ProfileStore].
///
/// We keep a *snapshot* of each offer (not just its coordinate) so the Favorites
/// list renders offline, and so a since-withdrawn offer can still be shown as
/// "no longer available" instead of vanishing. The stable key is the offer's
/// addressable coordinate `authorPubkeyHex:id` ([keyOf]).
class SavedOffersStore {
SavedOffersStore(this._store, {String accountScope = ''})
: _key = accountScope.isEmpty
? 'tane.social.saved_offers'
: 'tane.social.$accountScope.saved_offers';
final SecretStore _store;
final String _key;
final _changes = StreamController<void>.broadcast();
/// Emits whenever the saved set changes, so open screens can refresh.
Stream<void> get changes => _changes.stream;
/// The stable per-offer key: its NIP-99 addressable coordinate without the
/// kind (`authorPubkeyHex:id`). Same offer same key on every device.
static String keyOf(Offer offer) => '${offer.authorPubkeyHex}:${offer.id}';
/// Every saved offer, newest first (by save time).
Future<List<Offer>> list() async {
final raw = await _store.read(_key);
if (raw == null || raw.isEmpty) return const [];
final entries = (jsonDecode(raw) as List)
.cast<Map<String, dynamic>>()
.toList()
..sort((a, b) => (b['savedAt'] as int).compareTo(a['savedAt'] as int));
return [for (final e in entries) _decode(e)];
}
/// Whether [key] (from [keyOf]) is currently saved.
Future<bool> isSaved(String key) async =>
(await _rawList()).any((e) => e['key'] == key);
/// Saves [offer] (idempotent on its key). Newer snapshot replaces an older one.
Future<void> save(Offer offer, {required int savedAt}) async {
final key = keyOf(offer);
final list = await _rawList()..removeWhere((e) => e['key'] == key);
list.add({..._encode(offer), 'key': key, 'savedAt': savedAt});
await _writeRaw(list);
}
/// Removes the saved offer with [key] (from [keyOf]); no-op if absent.
Future<void> remove(String key) async {
final list = await _rawList()..removeWhere((e) => e['key'] == key);
await _writeRaw(list);
}
/// Toggles [offer]'s saved state; returns the new state (true = now saved).
Future<bool> toggle(Offer offer, {required int savedAt}) async {
if (await isSaved(keyOf(offer))) {
await remove(keyOf(offer));
return false;
}
await save(offer, savedAt: savedAt);
return true;
}
Future<List<Map<String, dynamic>>> _rawList() async {
final raw = await _store.read(_key);
if (raw == null || raw.isEmpty) return [];
return (jsonDecode(raw) as List).cast<Map<String, dynamic>>().toList();
}
Future<void> _writeRaw(List<Map<String, dynamic>> list) async {
await _store.write(_key, jsonEncode(list));
if (!_changes.isClosed) _changes.add(null);
}
Map<String, dynamic> _encode(Offer o) => {
'id': o.id,
'author': o.authorPubkeyHex,
'summary': o.summary,
'type': o.type.name,
'status': o.status.name,
if (o.category != null) 'category': o.category,
'geohash': o.approxGeohash,
if (o.radiusKm != null) 'radiusKm': o.radiusKm,
if (o.priceAmount != null) 'priceAmount': o.priceAmount,
if (o.priceCurrency != null) 'priceCurrency': o.priceCurrency,
if (o.exchangeTerms != null) 'exchangeTerms': o.exchangeTerms,
if (o.imageUrl != null) 'imageUrl': o.imageUrl,
if (o.expiresAt != null) 'expiresAt': o.expiresAt!.millisecondsSinceEpoch,
'isOrganic': o.isOrganic,
};
Offer _decode(Map<String, dynamic> e) => Offer(
id: e['id'] as String,
authorPubkeyHex: e['author'] as String,
summary: e['summary'] as String,
type: OfferType.values.byName(e['type'] as String),
status: OfferLifecycle.values.byName(e['status'] as String? ?? 'active'),
category: e['category'] as String?,
approxGeohash: e['geohash'] as String? ?? '',
radiusKm: e['radiusKm'] as int?,
priceAmount: e['priceAmount'] as num?,
priceCurrency: e['priceCurrency'] as String?,
exchangeTerms: e['exchangeTerms'] as String?,
imageUrl: e['imageUrl'] as String?,
expiresAt: e['expiresAt'] == null
? null
: DateTime.fromMillisecondsSinceEpoch(e['expiresAt'] as int),
isOrganic: e['isOrganic'] as bool? ?? false,
);
Future<void> close() async {
await _changes.close();
}
}

View file

@ -103,6 +103,12 @@ class AppDrawer extends StatelessWidget {
_DrawerItem(
icon: const Icon(Icons.favorite),
label: t.menu.wishlist,
onTap: marketEnabled
? () {
Navigator.of(context).pop();
context.push('/favorites');
}
: null,
),
// The ego-centric web of trust ("your people") live once the
// social layer is on.

View file

@ -0,0 +1,257 @@
import 'dart:async';
import 'package:commons_core/commons_core.dart';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import '../i18n/strings.g.dart';
import '../services/saved_offers_store.dart';
import '../services/social_connection.dart';
import 'market_widgets.dart';
import 'theme.dart';
/// The Wallapop-style "Favorites": offers from other people the user saved.
/// Shows the saved snapshots offline-first; when a relay is reachable it checks
/// which ones are still published and flags the rest as no longer available
/// (they may have been withdrawn or expired). Tapping opens the offer detail.
class FavoritesScreen extends StatefulWidget {
const FavoritesScreen({
required this.savedOffers,
this.connection,
super.key,
});
final SavedOffersStore savedOffers;
/// The shared relay connection, used to check whether saved offers still
/// exist. Null (tests / no social layer) no check, snapshots shown as-is.
final SocialConnection? connection;
@override
State<FavoritesScreen> createState() => _FavoritesScreenState();
}
class _FavoritesScreenState extends State<FavoritesScreen> {
List<Offer>? _offers;
var _liveKeys = <String>{};
var _checked = false;
StreamSubscription<void>? _changesSub;
@override
void initState() {
super.initState();
_changesSub = widget.savedOffers.changes.listen((_) => _load());
_load();
}
@override
void dispose() {
_changesSub?.cancel();
super.dispose();
}
Future<void> _load() async {
final offers = await widget.savedOffers.list();
if (!mounted) return;
setState(() => _offers = offers);
unawaited(_check(offers));
}
/// Asks the relay which saved offers are still out there. Offline (no session)
/// leaves [_checked] false, so nothing is wrongly flagged as gone.
Future<void> _check(List<Offer> offers) async {
final connection = widget.connection;
if (connection == null || offers.isEmpty) return;
final session = await connection.session();
if (session == null || !mounted) return;
final live = <String>{};
final geohashes = {
for (final o in offers)
if (o.approxGeohash.isNotEmpty) o.approxGeohash,
};
final subs = <StreamSubscription<Offer>>[];
for (final geohash in geohashes) {
subs.add(
session.offers
.discover(DiscoveryQuery(geohashPrefix: geohash))
.listen((o) => live.add(SavedOffersStore.keyOf(o)), onError: (_) {}),
);
}
// The discover streams stay open for live offers and never signal "done";
// give them a beat to deliver what's stored, then take stock.
await Future<void>.delayed(const Duration(seconds: 5));
for (final s in subs) {
unawaited(s.cancel());
}
if (!mounted) return;
setState(() {
_liveKeys = live;
_checked = true;
});
}
@override
Widget build(BuildContext context) {
final t = context.t;
final offers = _offers;
return Scaffold(
appBar: AppBar(title: Text(t.favorites.title)),
body: offers == null
? const Center(child: CircularProgressIndicator())
: offers.isEmpty
? _Empty(text: t.favorites.empty)
: ListView.separated(
padding: const EdgeInsets.all(12),
itemCount: offers.length,
separatorBuilder: (_, _) => const SizedBox(height: 10),
itemBuilder: (context, i) {
final offer = offers[i];
final key = SavedOffersStore.keyOf(offer);
// Only call something gone once a check actually ran and didn't
// see it never while offline (checked == false).
final gone = _checked && !_liveKeys.contains(key);
return _FavoriteCard(
offer: offer,
unavailable: gone,
onOpen: () => context.push('/market/offer', extra: offer),
onRemove: () => widget.savedOffers.remove(key),
);
},
),
);
}
}
class _FavoriteCard extends StatelessWidget {
const _FavoriteCard({
required this.offer,
required this.unavailable,
required this.onOpen,
required this.onRemove,
});
final Offer offer;
final bool unavailable;
final VoidCallback onOpen;
final VoidCallback onRemove;
@override
Widget build(BuildContext context) {
final t = context.t;
final radius = BorderRadius.circular(14);
return Material(
color: Colors.white,
borderRadius: radius,
child: InkWell(
key: Key('favorites.offer.${offer.authorPubkeyHex}.${offer.id}'),
onTap: onOpen,
borderRadius: radius,
child: Container(
decoration: BoxDecoration(
borderRadius: radius,
border: Border.all(color: seedOutline),
),
padding: const EdgeInsets.all(16),
child: Opacity(
opacity: unavailable ? 0.55 : 1,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
if (offer.imageUrl != null) ...[
OfferThumbnail(
url: offer.imageUrl!,
semanticLabel: t.market.photo,
),
const SizedBox(width: 12),
],
Expanded(
child: Text(
offer.summary,
style: const TextStyle(
fontSize: 17,
fontWeight: FontWeight.w500,
color: seedOnSurface,
),
),
),
IconButton(
key: Key('favorites.remove.${offer.authorPubkeyHex}'
'.${offer.id}'),
icon: const Icon(Icons.favorite, color: seedGreen),
tooltip: t.favorites.remove,
onPressed: onRemove,
),
],
),
const SizedBox(height: 4),
Row(
children: [
if (unavailable)
Row(
children: [
const Icon(Icons.cloud_off,
size: 15, color: seedMuted),
const SizedBox(width: 4),
Text(
t.favorites.unavailable,
style:
const TextStyle(color: seedMuted, fontSize: 13),
),
],
)
else
OfferTypeChip(label: offerTypeLabel(t, offer.type)),
const Spacer(),
if (offer.type == OfferType.sale && offer.priceAmount != null)
Text(
'${offer.priceAmount} ${offer.priceCurrency ?? ''}'
.trim(),
style: const TextStyle(
color: seedOnSurface,
fontWeight: FontWeight.w600,
),
),
],
),
],
),
),
),
),
);
}
}
class _Empty extends StatelessWidget {
const _Empty({required this.text});
final String text;
@override
Widget build(BuildContext context) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
Icons.favorite_border,
size: 64,
color: seedGreen.withValues(alpha: 0.5),
),
const SizedBox(height: 16),
Text(
text,
textAlign: TextAlign.center,
style: Theme.of(context).textTheme.bodyLarge,
),
],
),
),
);
}
}

View file

@ -7,6 +7,7 @@ import 'package:go_router/go_router.dart';
import '../i18n/strings.g.dart';
import '../services/profile_cache.dart';
import '../services/saved_offers_store.dart';
import '../services/social_connection.dart';
import '../services/social_service.dart';
import '../state/peer_rating_cubit.dart';
@ -27,6 +28,7 @@ class MarketOfferDetailScreen extends StatefulWidget {
this.mine = false,
this.profileCache,
this.selfPubkey,
this.savedOffers,
super.key,
});
@ -38,6 +40,10 @@ class MarketOfferDetailScreen extends StatefulWidget {
/// Whether this is the current user's own listing (hide the message button).
final bool mine;
/// Store of the user's saved ("favorite") offers, for the save toggle. Null in
/// tests / when there's no social layer → the heart action is hidden.
final SavedOffersStore? savedOffers;
/// Optional cache of peers' published display names; null in tests.
final ProfileCache? profileCache;
@ -58,10 +64,32 @@ class _MarketOfferDetailScreenState extends State<MarketOfferDetailScreen> {
bool _profileLoading = true;
PeerRatingState? _sellerRating;
/// Whether this offer is in the user's favorites; null while loading (the
/// heart action stays hidden until we know, to avoid a flicker).
bool? _saved;
@override
void initState() {
super.initState();
_loadSeller();
_loadSaved();
}
Future<void> _loadSaved() async {
final store = widget.savedOffers;
if (store == null) return;
final saved = await store.isSaved(SavedOffersStore.keyOf(widget.offer));
if (mounted) setState(() => _saved = saved);
}
Future<void> _toggleSaved() async {
final store = widget.savedOffers;
if (store == null) return;
final nowSaved = await store.toggle(
widget.offer,
savedAt: DateTime.now().millisecondsSinceEpoch,
);
if (mounted) setState(() => _saved = nowSaved);
}
/// Best-effort fetch of the author's published profile (name/about/Ğ1), the
@ -145,8 +173,23 @@ class _MarketOfferDetailScreenState extends State<MarketOfferDetailScreen> {
Widget build(BuildContext context) {
final t = context.t;
final o = widget.offer;
final saved = _saved;
return Scaffold(
appBar: AppBar(title: Text(o.summary)),
appBar: AppBar(
title: Text(o.summary),
actions: [
// Save other people's offers (Wallapop-style). Hidden on your own
// listing and until the saved state is known.
if (!widget.mine && widget.savedOffers != null && saved != null)
IconButton(
key: const Key('offerDetail.save'),
icon: Icon(saved ? Icons.favorite : Icons.favorite_border),
color: saved ? seedGreen : null,
tooltip: saved ? t.favorites.remove : t.favorites.save,
onPressed: _toggleSaved,
),
],
),
body: ListView(
padding: const EdgeInsets.all(16),
children: [