feed-patterns

vitorpamplona/amethyst

Паттерны лент и слоя доступа к данным в Amethyst (FeedFilter, FeedContentState).

Звёзды1 624
Авторvitorpamplona

Установка

SKILL.md

Feed Patterns

Amethyst's "feed" abstraction is: a FeedFilter that decides which notes belong in a list, plus a FeedViewModel that exposes the current state reactively to the UI. Every scrollable list — home, profile, hashtag, bookmarks, notifications, DMs — is a variant of this.

When to Use This Skill

  • Adding a new screen that shows a list of notes.
  • Modifying an existing feed's filtering / ordering / inclusion rules.
  • Investigating why a feed doesn't update after a mute/follow/bookmark change.
  • Deciding whether to extend a ViewModel or write a new filter.
  • Understanding the Android ⇄ Desktop sharing boundary for feeds.

Architecture

┌─────────────────────────────────────────────────────────────┐
│ commons/.../viewmodels/  (shared, KMP)                      │
│   FeedViewModel  ◄── ListChangeFeedViewModel                │
│                 ◄── ChatroomFeedViewModel                   │
│                 ◄── MarmotGroupFeedViewModel                │
│                                                             │
│                                                             │
│ commons/.../ui/feeds/  (shared, KMP)                        │
│   IFeedFilter / FeedFilter<T>  (abstract base)              │
│   IAdditiveFeedFilter / AdditiveFeedFilter<T>               │
│   ChangesFlowFilter                                         │
│   FeedContentState, FeedState — the flow the UI collects    │
└─────────────────────────────────────────────────────────────┘
              ▲
              │ uses
              │
┌─────────────────────────────────────────────────────────────┐
│ amethyst/.../ui/dal/  (Android-only additions)              │
│   AdditiveComplexFeedFilter<T, U>                           │
│   FilterByListParams                                        │
│   DefaultFeedOrder (Note/Event/Card comparators)            │
│   (FeedFilters.kt & ChangesFlowFilter.kt here are just      │
│    back-compat typealiases re-exporting commons)            │
│                                                             │
│   Concrete feeds: HomeNewThreadFeedFilter,                  │
│   HashtagFeedFilter, NotificationFeedFilter, … live in      │
│   feature folders under ui/screen/loggedIn/*/dal/           │
└─────────────────────────────────────────────────────────────┘
              ▲
              │ reads
              │
┌─────────────────────────────────────────────────────────────┐
│ model/LocalCache.kt + account.<feature>.flow                │
└─────────────────────────────────────────────────────────────┘

Key Files

Shared (commons)

commons/src/commonMain/kotlin/com/vitorpamplona/amethyst/commons/viewmodels/:

  • FeedViewModel.kt — abstract class FeedViewModel(localFilter, cacheProvider). Holds a FeedContentState, subscribes to invalidation signals (from Account flows and LocalCacheFlow), re-runs the filter, and emits a new FeedState for the UI.
  • ListChangeFeedViewModel.kt — specialization for feeds whose membership changes frequently (e.g. bookmarks).
  • ChatroomFeedViewModel.kt — DM thread feed.
  • MarmotGroupFeedViewModel.kt — NIP-29 / marmot group feed.
  • LiveStreamTopZappersViewModel.kt, SearchBarState.kt, ChatNewMessageState.kt — narrower, non-feed states that share the plumbing.

Shared filter bases (commons)

commons/src/commonMain/kotlin/com/vitorpamplona/amethyst/commons/ui/feeds/:

  • FeedFilter.kt — abstract class FeedFilter<T> : IFeedFilter<T>. Has feed(): List<T> (the sync query against the cache), feedKey(): String (identity used to cache), limit(), and loadTop().
  • AdditiveFeedFilter.kt — abstract class AdditiveFeedFilter<T> : FeedFilter<T>(), IAdditiveFeedFilter<T>. Adds incremental updates (the "additive" part): updateListWith(oldList, newItems) runs applyFilter(newItems) and grafts accepted items onto the existing list (re-sort + take(limit())) without recomputing everything.
  • ChangesFlowFilter.kt — wraps a filter with a coarse "state changed" signal so the ViewModel knows to re-query.
  • FeedContentState.kt / FeedState.kt — the reactive state the UI collects.

Android DAL (additions on top)

amethyst/src/main/java/com/vitorpamplona/amethyst/ui/dal/:

  • AdditiveComplexFeedFilter.kt — abstract class AdditiveComplexFeedFilter<T, U> : FeedFilter<T>(): like AdditiveFeedFilter but the incoming items (Set<U>) are a different type than the list rows (T).
  • FilterByListParams.kt — common parameters (top-nav filter, exclude muted, since/until) shared across many filters.
  • DefaultFeedOrder.kt — standard comparators (createdAt desc + id tiebreaker for stable paging) for Note, Event, and Card.
  • FeedFilters.kt / ChangesFlowFilter.kt — back-compat typealiases re-exporting the commons classes; don't add logic here.

Concrete filters (Home, Hashtag, Profile, Bookmark, Notifications, Communities, etc.) live in feature dal/ subfolders under amethyst/.../ui/screen/loggedIn/*/ — each extends FeedFilter, AdditiveFeedFilter, or AdditiveComplexFeedFilter. Desktop has its own in desktopApp/.../feeds/DesktopFeedFilters.kt.

Adding a New Feed

  1. Define the filter. Extend AdditiveFeedFilter<Note> (or plain FeedFilter<Note> if additivity doesn't matter; AdditiveComplexFeedFilter<T, U> if incoming items differ in type from list rows). Implement:<!-- -->
    • feedKey() — stable identity (e.g. hashtag name, account pubkey).
    • feed() — synchronous scan over LocalCache / Account state producing an ordered list.
    • limit() — pagination hint.
    • If additive: applyFilter(collection: Set<Note>): Set<Note> and sort(collection: Set<Note>): List<Note>.
  2. Pick or write a ViewModel. If the feed's membership shifts often (bookmarks, notifications), extend ListChangeFeedViewModel. Otherwise FeedViewModel.
  3. Wire invalidation. The ViewModel must observe the right Account flows + LocalCacheFlow so it re-queries when state changes.
  4. Render. In the composable, collect viewModel.feedState.feedContent and render with a LazyColumn { items(..., key = { it.id }) { NoteCompose(it) } }.
  5. Subscribe to relays. Most feeds also need a Subscribable to fetch historical events. See the relay-client skill.

Filter Sharing (Android vs Desktop)

  • The filter base classes (FeedFilter, AdditiveFeedFilter, ChangesFlowFilter) and feed state (FeedContentState) are in commons/.../ui/feeds/ — shared. ViewModels are in commons/.../viewmodels/ — shared.
  • The concrete filters are platform-local: Android's in amethyst/.../ui/screen/loggedIn/*/dal/, Desktop's in desktopApp/.../feeds/. amethyst/.../ui/dal/ keeps Android-only helpers (AdditiveComplexFeedFilter, FilterByListParams, DefaultFeedOrder) plus back-compat typealiases.
  • When porting a feed, share the concrete filter only if both platforms need identical inclusion rules.

Gotchas

  • Never scan LocalCache from a composable. Always go through a FeedFilter + FeedViewModel, which does it on a background dispatcher and debounces invalidation.
  • feedKey() is used as a cache key. Two different semantic feeds must produce different keys, otherwise their state cross-contaminates.
  • Additive updates must stay consistent with the full recompute. If applyFilter accepts a note that feed() wouldn't include, UX drifts.
  • Paging isn't free — use limit() and since/until in FilterByListParams rather than trimming a giant scan.
  • Notifications feed is special — it inspects the follow/mute state (account.kind3FollowList.flow, account.hiddenUsers) and LocalCache deletions to hide muted/deleted content; always run through the FilterByListParams exclusion paths rather than filtering post-hoc.

References

  • references/feed-filter-composition.md — step-by-step for adding a feed.
  • references/viewmodel-base-classes.md — inheritance graph for the FeedViewModel family.
  • Complements: account-state (where the data lives), relay-client (how to subscribe), compose-expert (how to render).

Вставить в README

Ссылка на карточку для вашего README — без картинок и счётчиков.

[DarkPlay: feed-patterns](https://darkplay.ru/ai/skills/vitorpamplona-amethyst-feed-patterns)

Похожие скиллы и другие разделы каталога

Популярное в разделе «Скиллы»

Самые востребованные скиллов раздела по установкам и звёздам.

find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
4 400 000 устан.
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
1 600 000 устан.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
1 600 000 устан.
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
1 600 000 устан.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
1 600 000 устан.
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
1 500 000 устан.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
1 400 000 устан.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
1 300 000 устан.
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
1 300 000 устан.
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.
1 300 000 устан.
Похожее в других разделах каталога

Соседние разделы каталога: возможно, нужный инструмент живёт там.

superpowersobra · Базовая библиотека навыков для Claude Code: TDD, отладка, паттерны совместной работы и…
16 комп.
Code Architectaffaan-m · Проектирует архитектуру функций, анализируя существующие паттерны и соглашения кодовой…
225 587 ★
Csharp Revieweraffaan-m · Ревьюер C#: конвенции .NET, async, безопасность, nullable-типы, производительность.
225 587 ★
Django Revieweraffaan-m · Ревьюер Django: ORM, DRF, миграции, безопасность и production-практики.
225 587 ★
Flutter Revieweraffaan-m · Ревьюер кода Flutter и Dart: виджеты, управление состоянием, идиомы и архитектура.
225 587 ★
Gan Evaluatoraffaan-m · GAN Harness — агент-оценщик: тестирует приложение через Playwright и даёт обратную связь.
225 587 ★
Gan Generatoraffaan-m · GAN Harness — агент-генератор: реализует функции по спецификации и итерирует по отзывам.
225 587 ★
Go Revieweraffaan-m · Ревьюер кода Go: идиоматичность, конкурентность, обработка ошибок и производительность.
225 587 ★
Harmonyos App Resolveraffaan-m · Эксперт по HarmonyOS на ArkTS и ArkUI: состояние V2, навигация, API и производительность.
225 587 ★
Kotlin Revieweraffaan-m · Ревьюер Kotlin и Android/KMP: корутины, Compose, архитектура и типичные ошибки.
225 587 ★

Лучшие ИИ-инструменты для генерации видео

Генерация видео

Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,

VEED.IOVeed
По запросу
5.0
MootionMootion
По запросу
5.0
FlyviFlyvi
Есть бесплатный тариф
4.9
Google Veo 3.1Google
Платно
4.9
Sora (OpenAI)OpenAI
Платно
4.9
PikaPika
Платно
4.9
captions space
Есть бесплатный тариф
4.8
Клайп
Есть бесплатный тариф
4.8
viralpulse.appViralpulse
По запросу
4.8
Viral Maker AIViral-maker
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации текста и копирайтинга

Генерация текста и копирайтинг

Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра

NeuroscribeNeuroscribe
Есть бесплатный тариф
5.0
GoGPTGogpt
По запросу
5.0
ChatsonicChatsonic
По запросу
4.9
НейроТекстерNeuro-texter
По запросу
4.9
ChatGPTOpenAI
По подписке
4.9
Редактум
Есть бесплатный тариф
4.8
ChadGPTChadgpt
По запросу
4.8
Cosmo ScribeCosmoscribe
Есть бесплатный тариф
4.8
Memo HelperCopilot33
По запросу
4.8
LibraChatLibrachat
Есть бесплатный тариф
4.8

Лучшие ИИ-инструменты для генерации изображений

Генерация изображений

Подборка нейросетей для генерации изображений от фотореализма до концепт-арта. Сервисы, которые экономят часы ручной работы, создавая визуал для блогов, рекламы и дизайна за минуты

MagviMagvi
По запросу
5.0
DALL-E 3OpenAI
По подписке
5.0
SupaLabSupalab
По запросу
5.0
Freestyling.aiFreestyling
Есть бесплатный тариф
4.9
ArtGeneration.meArtgeneration
Есть бесплатный тариф
4.9
BigjpgBigjpg
По запросу
4.9
Художник от VKVK
Бесплатно
4.9
Wonderink — ИИ-книги
Есть бесплатный тариф
4.8
Avato AI12ai
По запросу
4.8
Virton AIVirton
По запросу
4.8