feat(collection): replace paginated collection browser with full owned map
Adds collection.get_owned endpoint that returns { definitionId → count }
for the player's entire collection in a single DB round-trip. The client
caches this map and filters/sorts entirely client-side using definitions
already in ContentCache, eliminating all pagination and "load more" UI.
- Search, type, and affinity filters now work across the full collection
instantly with no network round-trips
- deck_editor_panel: arch spirit picker also uses the owned map —
removes a separate collection.get_cards request
- cards_view: same pattern, grid rebuilds client-side on filter change
- CollectionCache: persists owned map to disk (owned.json per player)
Generated with [Claude Code](https://claude.ai/code)
via [Happy](https://happy.engineering)
Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Happy <yesreply@happy.engineering>
This commit is contained in:
@@ -12,6 +12,7 @@ var _loaded_player_id : String = ""
|
||||
var _cards_pages : Dictionary = {}
|
||||
var _decks_payload : Dictionary = {}
|
||||
var _deck_payloads : Dictionary = {}
|
||||
var _owned_map : Dictionary = {} ## definitionId(String) → ownedCount(int)
|
||||
|
||||
|
||||
func _ready() -> void:
|
||||
@@ -138,6 +139,27 @@ func remove_deck(deck_id: String) -> void:
|
||||
_write_json_file(_decks_file_path(), _decks_payload)
|
||||
|
||||
|
||||
func get_owned_map() -> Dictionary:
|
||||
_ensure_loaded()
|
||||
if _loaded_player_id.is_empty():
|
||||
return {}
|
||||
if not _owned_map.is_empty():
|
||||
return _owned_map.duplicate(true)
|
||||
var payload := _read_json_file(_owned_file_path())
|
||||
if not payload.is_empty():
|
||||
_owned_map = payload
|
||||
return payload.duplicate(true)
|
||||
return {}
|
||||
|
||||
|
||||
func store_owned_map(map: Dictionary) -> void:
|
||||
_ensure_loaded()
|
||||
if _loaded_player_id.is_empty():
|
||||
return
|
||||
_owned_map = map.duplicate(true)
|
||||
_write_json_file(_owned_file_path(), _owned_map)
|
||||
|
||||
|
||||
func _ensure_loaded() -> void:
|
||||
var current_player_id := Auth.user_id
|
||||
if current_player_id == _loaded_player_id:
|
||||
@@ -146,6 +168,7 @@ func _ensure_loaded() -> void:
|
||||
_cards_pages.clear()
|
||||
_decks_payload.clear()
|
||||
_deck_payloads.clear()
|
||||
_owned_map.clear()
|
||||
|
||||
|
||||
func _player_dir() -> String:
|
||||
@@ -164,6 +187,10 @@ func _deck_file_path(deck_id: String) -> String:
|
||||
return "%s/deck_%s.json" % [_player_dir(), _sanitize_path_component(deck_id)]
|
||||
|
||||
|
||||
func _owned_file_path() -> String:
|
||||
return "%s/owned.json" % _player_dir()
|
||||
|
||||
|
||||
func _sanitize_path_component(value: String) -> String:
|
||||
var safe := value.strip_edges()
|
||||
if safe.is_empty():
|
||||
|
||||
@@ -4,22 +4,23 @@ extends VBoxContainer
|
||||
## Usage:
|
||||
## call open_deck(deck_id, deck_name) to load a deck for editing.
|
||||
## connect back_pressed to return to the deck list.
|
||||
##
|
||||
## The collection browser fetches the full owned map once (collection.get_owned)
|
||||
## and filters/sorts entirely client-side using ContentCache definitions.
|
||||
## No pagination or "load more" needed.
|
||||
|
||||
signal back_pressed()
|
||||
|
||||
const PAGE_SIZE := 100
|
||||
|
||||
# ── Node refs ─────────────────────────────────────────────────────────────────
|
||||
|
||||
@onready var _title_lbl : Label = %TitleLabel
|
||||
@onready var _count_lbl : Label = %CountLabel
|
||||
@onready var _deck_loading_lbl : Label = %DeckLoadingLabel
|
||||
@onready var _title_lbl : Label = %TitleLabel
|
||||
@onready var _count_lbl : Label = %CountLabel
|
||||
@onready var _deck_loading_lbl : Label = %DeckLoadingLabel
|
||||
@onready var _deck_card_list : VBoxContainer = %DeckCardList
|
||||
@onready var _search_input : LineEdit = %SearchInput
|
||||
@onready var _type_option : OptionButton = %TypeOption
|
||||
@onready var _coll_loading_lbl : Label = %CollLoadingLabel
|
||||
@onready var _search_input : LineEdit = %SearchInput
|
||||
@onready var _type_option : OptionButton = %TypeOption
|
||||
@onready var _coll_loading_lbl : Label = %CollLoadingLabel
|
||||
@onready var _coll_list : VBoxContainer = %CollList
|
||||
@onready var _load_more_btn : Button = %LoadMoreBtn
|
||||
|
||||
# ── State ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -31,21 +32,18 @@ var _arch_spirit_id : String = ""
|
||||
var _arch_spirit_row : Control = null
|
||||
var _arch_picker_panel : Control = null
|
||||
|
||||
var _coll_page : int = 1
|
||||
var _coll_total : int = 0
|
||||
var _has_more : bool = false
|
||||
var _is_loading : bool = false
|
||||
var _search_timer : float = 0.0
|
||||
var _coll_req_gen : int = 0
|
||||
const _DEBOUNCE := 0.4
|
||||
## Full owned map fetched once: { definitionId(String) → ownedCount(int) }
|
||||
var _owned : Dictionary = {}
|
||||
var _search_timer : float = 0.0
|
||||
const _DEBOUNCE := 0.15
|
||||
|
||||
# ── Lifecycle ─────────────────────────────────────────────────────────────────
|
||||
|
||||
func _ready() -> void:
|
||||
%BackBtn.pressed.connect(func(): back_pressed.emit())
|
||||
_search_input.text_changed.connect(_on_search_changed)
|
||||
_type_option.item_selected.connect(func(_i): _reload_collection())
|
||||
_load_more_btn.pressed.connect(_on_load_more)
|
||||
_type_option.item_selected.connect(func(_i): _rebuild_coll_list())
|
||||
%LoadMoreBtn.hide()
|
||||
_populate_type_options()
|
||||
|
||||
|
||||
@@ -54,8 +52,7 @@ func _process(delta: float) -> void:
|
||||
_search_timer -= delta
|
||||
if _search_timer <= 0.0:
|
||||
_search_timer = 0.0
|
||||
_reload_collection()
|
||||
|
||||
_rebuild_coll_list()
|
||||
|
||||
|
||||
func _populate_type_options() -> void:
|
||||
@@ -74,7 +71,7 @@ func open_deck(deck_id: String, deck_name: String) -> void:
|
||||
_type_option.selected = 0
|
||||
_deck_qty.clear()
|
||||
_load_deck_contents()
|
||||
_reload_collection()
|
||||
_fetch_owned()
|
||||
|
||||
# ── Deck contents ─────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -158,86 +155,69 @@ func _make_deck_row(card: Dictionary) -> Control:
|
||||
|
||||
return outer
|
||||
|
||||
# ── Collection browser ────────────────────────────────────────────────────────
|
||||
# ── Collection browser (client-side filtered) ─────────────────────────────────
|
||||
|
||||
func _reload_collection() -> void:
|
||||
_coll_page = 1
|
||||
_coll_total = 0
|
||||
_has_more = false
|
||||
# A new query should supersede any in-flight collection request.
|
||||
# Stale responses are already filtered by request generation.
|
||||
_is_loading = false
|
||||
func _fetch_owned() -> void:
|
||||
_coll_loading_lbl.visible = true
|
||||
var cached := CollectionCache.get_owned_map()
|
||||
if not cached.is_empty():
|
||||
_owned = cached
|
||||
_rebuild_coll_list()
|
||||
Network.request(
|
||||
"collection.get_owned",
|
||||
{},
|
||||
func(_t: String, p: Variant): _on_owned_response(p),
|
||||
func(_code: String, msg: String): _on_owned_error(msg)
|
||||
)
|
||||
|
||||
|
||||
func _on_owned_response(payload: Variant) -> void:
|
||||
var p := payload as Dictionary
|
||||
var raw : Variant = p.get("owned", {})
|
||||
_owned = raw if typeof(raw) == TYPE_DICTIONARY else {}
|
||||
CollectionCache.store_owned_map(_owned)
|
||||
_coll_loading_lbl.visible = false
|
||||
_rebuild_coll_list()
|
||||
|
||||
|
||||
func _on_owned_error(msg: String) -> void:
|
||||
_coll_loading_lbl.visible = false
|
||||
push_warning("DeckEditor owned: %s" % msg)
|
||||
|
||||
|
||||
func _rebuild_coll_list() -> void:
|
||||
for child in _coll_list.get_children():
|
||||
child.queue_free()
|
||||
_load_more_btn.visible = false
|
||||
var cached := CollectionCache.get_cards_response(_collection_query_key(1))
|
||||
if not cached.is_empty():
|
||||
_render_coll_response(cached, 1)
|
||||
_fetch_coll_page(1)
|
||||
|
||||
var search := _search_input.text.strip_edges().to_lower()
|
||||
var type_idx := _type_option.selected
|
||||
var type_filter := _type_option.get_item_text(type_idx) if type_idx > 0 else ""
|
||||
|
||||
func _fetch_coll_page(page: int) -> void:
|
||||
if _is_loading:
|
||||
return
|
||||
var rows : Array = []
|
||||
for def_id_var in _owned:
|
||||
var def_id := str(def_id_var)
|
||||
var def := ContentCache.get_definition(def_id)
|
||||
if def.is_empty():
|
||||
continue
|
||||
var card_name := str(def.get("name", ""))
|
||||
var card_type := str(def.get("cardType", ""))
|
||||
if not search.is_empty() and not card_name.to_lower().contains(search):
|
||||
continue
|
||||
if not type_filter.is_empty() and card_type != type_filter:
|
||||
continue
|
||||
rows.append({
|
||||
"cardDefinitionId": def_id,
|
||||
"name": card_name,
|
||||
"cardType": card_type,
|
||||
"affinity": str(def.get("affinity", "")),
|
||||
"rarity": str(def.get("rarity", "")),
|
||||
"tier": def.get("tier"),
|
||||
"ownedCount": int(_owned[def_id_var]),
|
||||
})
|
||||
|
||||
_is_loading = true
|
||||
_coll_loading_lbl.visible = true
|
||||
|
||||
# Bump generation so stale async responses can be ignored.
|
||||
_coll_req_gen += 1
|
||||
var req_gen := _coll_req_gen
|
||||
|
||||
var payload := { "page": page, "pageSize": PAGE_SIZE }
|
||||
payload["groupByDefinition"] = true
|
||||
var search := _search_input.text.strip_edges()
|
||||
if not search.is_empty():
|
||||
payload["nameFilter"] = search
|
||||
|
||||
var type_idx := _type_option.selected
|
||||
if type_idx > 0:
|
||||
payload["cardTypeFilter"] = _type_option.get_item_text(type_idx)
|
||||
|
||||
Network.request(
|
||||
"collection.get_cards",
|
||||
payload,
|
||||
func(_t: String, p: Variant):
|
||||
_on_coll_response(p, page, req_gen),
|
||||
func(_code: String, msg: String):
|
||||
# Only surface error if this is still current request generation.
|
||||
if req_gen == _coll_req_gen:
|
||||
_on_coll_error(msg)
|
||||
)
|
||||
|
||||
func _on_coll_response(payload: Variant, page: int, req_gen: int) -> void:
|
||||
if req_gen != _coll_req_gen:
|
||||
return
|
||||
var p_cache := payload as Dictionary
|
||||
CollectionCache.store_cards_response(_collection_query_key(page), p_cache)
|
||||
_render_coll_response(p_cache, page)
|
||||
#var cards : Array = []
|
||||
#
|
||||
## Track def_ids already in the list to avoid duplicates across pages
|
||||
#var seen : Dictionary = {}
|
||||
#for child in _coll_list.get_children():
|
||||
#if child.has_meta("def_id"):
|
||||
#seen[str(child.get_meta("def_id"))] = true
|
||||
#
|
||||
#for dto in cards:
|
||||
#var def_id := str(dto.get("cardDefinitionId", ""))
|
||||
#if def_id.is_empty() or def_id in seen:
|
||||
#continue
|
||||
### Tier 1 ArchSpirits are commanders — cannot be added as deck cards
|
||||
##if str(dto.get("cardType", "")) == "ArchSpirit" \
|
||||
##and int(dto.get("tier", 1)) <= 1:
|
||||
##continue
|
||||
#seen[def_id] = true
|
||||
#_coll_list.add_child(_make_coll_row(dto))
|
||||
|
||||
|
||||
func _on_coll_error(msg: String) -> void:
|
||||
_is_loading = false
|
||||
_coll_loading_lbl.visible = false
|
||||
push_warning("DeckEditor collection: %s" % msg)
|
||||
rows.sort_custom(func(a, b): return str(a["name"]) < str(b["name"]))
|
||||
for dto in rows:
|
||||
_coll_list.add_child(_make_coll_row(dto))
|
||||
|
||||
|
||||
func _make_coll_row(dto: Dictionary) -> Control:
|
||||
@@ -299,10 +279,6 @@ func _refresh_coll_in_deck_labels() -> void:
|
||||
(child.get_meta("deck_lbl") as Label).text = "In deck: %d" % in_deck
|
||||
|
||||
|
||||
func _on_load_more() -> void:
|
||||
_fetch_coll_page(_coll_page + 1)
|
||||
|
||||
|
||||
func _on_search_changed(_t: String) -> void:
|
||||
_search_timer = _DEBOUNCE
|
||||
|
||||
@@ -367,37 +343,6 @@ func _render_deck_response(payload: Dictionary) -> void:
|
||||
_refresh_coll_in_deck_labels()
|
||||
|
||||
|
||||
func _render_coll_response(payload: Dictionary, page: int) -> void:
|
||||
_is_loading = false
|
||||
_coll_loading_lbl.visible = false
|
||||
var cards : Array = payload.get("cards", [])
|
||||
_coll_total = int(payload.get("totalCount", 0))
|
||||
var page_size := int(payload.get("pageSize", PAGE_SIZE))
|
||||
_coll_page = page
|
||||
_has_more = (page * page_size) < _coll_total
|
||||
_load_more_btn.visible = _has_more
|
||||
|
||||
if page == 1:
|
||||
for child in _coll_list.get_children():
|
||||
child.queue_free()
|
||||
|
||||
var seen : Dictionary = {}
|
||||
if page > 1:
|
||||
for child in _coll_list.get_children():
|
||||
if child.has_meta("def_id"):
|
||||
seen[str(child.get_meta("def_id"))] = true
|
||||
|
||||
|
||||
for raw_dto in cards:
|
||||
var dto := raw_dto as Dictionary
|
||||
var def_id := str(dto.get("cardDefinitionId", ""))
|
||||
if def_id.is_empty() or def_id in seen:
|
||||
continue
|
||||
var def := ContentCache.get_definition(def_id)
|
||||
seen[def_id] = true
|
||||
_coll_list.add_child(_make_coll_row(_hydrate_card_dto(dto, def)))
|
||||
|
||||
|
||||
func _hydrate_card_dto(dto: Dictionary, def: Dictionary) -> Dictionary:
|
||||
var hydrated := dto.duplicate(true)
|
||||
if def.is_empty():
|
||||
@@ -410,16 +355,6 @@ func _hydrate_card_dto(dto: Dictionary, def: Dictionary) -> Dictionary:
|
||||
hydrated["tier"] = tier_value if tier_value != null else null
|
||||
return hydrated
|
||||
|
||||
|
||||
func _collection_query_key(page: int) -> String:
|
||||
var search := _search_input.text.strip_edges()
|
||||
var type_filter := ""
|
||||
var type_idx := _type_option.selected
|
||||
if type_idx > 0:
|
||||
type_filter = _type_option.get_item_text(type_idx)
|
||||
return CollectionCache.cards_query_key(page, PAGE_SIZE, search, type_filter)
|
||||
|
||||
|
||||
# ── Commander / ArchSpirit swap ───────────────────────────────────────────────
|
||||
|
||||
func _update_arch_spirit_row() -> void:
|
||||
@@ -516,36 +451,36 @@ func _build_arch_picker_panel() -> Control:
|
||||
list.add_theme_constant_override("separation", 4)
|
||||
scroll.add_child(list)
|
||||
|
||||
var loading_lbl := Label.new()
|
||||
loading_lbl.text = "Loading..."
|
||||
list.add_child(loading_lbl)
|
||||
# Build from owned map — no extra network request needed.
|
||||
# null Tier in definitions is treated as Tier 1 (matches server rule).
|
||||
var arch_spirits : Array = []
|
||||
for def_id_var in _owned:
|
||||
var def_id := str(def_id_var)
|
||||
var def := ContentCache.get_definition(def_id)
|
||||
if def.is_empty() or str(def.get("cardType", "")) != "ArchSpirit":
|
||||
continue
|
||||
var tier_val : Variant = def.get("tier", null)
|
||||
var tier_int := int(tier_val) if tier_val != null else 1
|
||||
if tier_int != 1:
|
||||
continue
|
||||
arch_spirits.append({ "def_id": def_id, "name": str(def.get("name", def_id)) })
|
||||
|
||||
arch_spirits.sort_custom(func(a, b): return str(a["name"]) < str(b["name"]))
|
||||
|
||||
for entry in arch_spirits:
|
||||
var row_btn := Button.new()
|
||||
row_btn.text = str(entry["name"])
|
||||
row_btn.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS
|
||||
row_btn.size_flags_horizontal = Control.SIZE_EXPAND_FILL
|
||||
row_btn.disabled = str(entry["def_id"]) == _arch_spirit_id
|
||||
row_btn.pressed.connect(_set_arch_spirit.bind(str(entry["def_id"])))
|
||||
list.add_child(row_btn)
|
||||
|
||||
if list.get_child_count() == 0:
|
||||
var empty_lbl := Label.new()
|
||||
empty_lbl.text = "No Tier-1 ArchSpirits in collection."
|
||||
list.add_child(empty_lbl)
|
||||
|
||||
Network.request(
|
||||
"collection.get_cards",
|
||||
{ "page": 1, "pageSize": 50, "cardTypeFilter": "ArchSpirit", "tierFilter": 1 },
|
||||
func(_t: String, p: Variant):
|
||||
if not is_instance_valid(list):
|
||||
return
|
||||
loading_lbl.queue_free()
|
||||
var cards : Array = (p as Dictionary).get("cards", [])
|
||||
for raw in cards:
|
||||
var dto := raw as Dictionary
|
||||
var def_id := str(dto.get("cardDefinitionId", ""))
|
||||
if def_id.is_empty():
|
||||
continue
|
||||
var def := ContentCache.get_definition(def_id)
|
||||
var card_name : String = str(def.get("name", dto.get("name", "?")))
|
||||
var row_btn := Button.new()
|
||||
row_btn.text = card_name
|
||||
row_btn.text_overrun_behavior = TextServer.OVERRUN_TRIM_ELLIPSIS
|
||||
row_btn.size_flags_horizontal = Control.SIZE_EXPAND_FILL
|
||||
row_btn.disabled = def_id == _arch_spirit_id
|
||||
row_btn.pressed.connect(_set_arch_spirit.bind(def_id))
|
||||
list.add_child(row_btn),
|
||||
func(_code: String, msg: String):
|
||||
if is_instance_valid(loading_lbl):
|
||||
loading_lbl.text = "Failed: %s" % msg
|
||||
)
|
||||
return panel
|
||||
|
||||
|
||||
|
||||
@@ -1,36 +1,28 @@
|
||||
extends VBoxContainer
|
||||
## Cards tab — paginated, filterable grid of the player's owned cards.
|
||||
## Cards tab — filterable, sortable grid of the player's owned cards.
|
||||
##
|
||||
## Fetches from collection.get_cards (page, pageSize, nameFilter?,
|
||||
## cardTypeFilter?, affinityFilter?). Displays results as CardWidget
|
||||
## instances in a responsive GridContainer.
|
||||
##
|
||||
## Typing in the search box starts a 0.4 s debounce before reloading.
|
||||
## "Load More" appends the next page without clearing the existing cards.
|
||||
## Fetches the full owned map once (collection.get_owned), then all filtering,
|
||||
## search, and sorting happen client-side using ContentCache definitions.
|
||||
## No "load more" or pagination.
|
||||
|
||||
const CARD_WIDGET := preload("res://scenes/collection/components/CardWidget.tscn")
|
||||
const PAGE_SIZE := 20
|
||||
const CARD_WIDGET := preload("res://scenes/collection/components/CardWidget.tscn")
|
||||
const CARD_WIDTH_ESTIMATE := 168
|
||||
|
||||
# ── Node references ───────────────────────────────────────────────────────────
|
||||
|
||||
@onready var search_input : LineEdit = %SearchInput
|
||||
@onready var type_option : OptionButton = %TypeOption
|
||||
@onready var affinity_option : OptionButton = %AffinityOption
|
||||
@onready var card_grid : GridContainer = %CardGrid
|
||||
@onready var loading_label : Label = %LoadingLabel
|
||||
@onready var empty_label : Label = %EmptyLabel
|
||||
@onready var load_more_btn : Button = %LoadMoreBtn
|
||||
@onready var search_input : LineEdit = %SearchInput
|
||||
@onready var type_option : OptionButton = %TypeOption
|
||||
@onready var affinity_option : OptionButton = %AffinityOption
|
||||
@onready var card_grid : GridContainer = %CardGrid
|
||||
@onready var loading_label : Label = %LoadingLabel
|
||||
@onready var empty_label : Label = %EmptyLabel
|
||||
|
||||
# ── State ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
var _current_page : int = 1
|
||||
var _total_count : int = 0
|
||||
var _has_more : bool = false
|
||||
var _loading : bool = false
|
||||
var _search_timer : float = 0.0
|
||||
var _card_entries : Dictionary = {} ## definitionId(String) -> { count, label }
|
||||
const _SEARCH_DEBOUNCE := 0.4
|
||||
## Full owned map: { definitionId(String) → ownedCount(int) }
|
||||
var _owned : Dictionary = {}
|
||||
var _search_timer : float = 0.0
|
||||
const _SEARCH_DEBOUNCE := 0.15
|
||||
|
||||
# Emitted when the user taps a card — parent uses this to show the detail popup.
|
||||
signal card_selected(dto: Dictionary, def: Dictionary)
|
||||
@@ -42,11 +34,11 @@ func _ready() -> void:
|
||||
_populate_affinity_options()
|
||||
_update_columns()
|
||||
search_input.text_changed.connect(_on_search_changed)
|
||||
type_option.item_selected.connect(func(_i): _reload())
|
||||
affinity_option.item_selected.connect(func(_i): _reload())
|
||||
load_more_btn.pressed.connect(_on_load_more)
|
||||
type_option.item_selected.connect(func(_i): _rebuild_grid())
|
||||
affinity_option.item_selected.connect(func(_i): _rebuild_grid())
|
||||
%LoadMoreBtn.hide()
|
||||
get_viewport().size_changed.connect(_update_columns)
|
||||
_reload()
|
||||
_fetch_owned()
|
||||
|
||||
|
||||
func _exit_tree() -> void:
|
||||
@@ -59,7 +51,7 @@ func _process(delta: float) -> void:
|
||||
_search_timer -= delta
|
||||
if _search_timer <= 0.0:
|
||||
_search_timer = 0.0
|
||||
_reload()
|
||||
_rebuild_grid()
|
||||
|
||||
# ── Option population ─────────────────────────────────────────────────────────
|
||||
|
||||
@@ -92,177 +84,119 @@ func _update_columns() -> void:
|
||||
available_width = get_viewport_rect().size.x - 16.0
|
||||
card_grid.columns = max(1, int(available_width / CARD_WIDTH_ESTIMATE))
|
||||
|
||||
# ── Data fetching ─────────────────────────────────────────────────────────────
|
||||
# ── Data fetching (one-time) ──────────────────────────────────────────────────
|
||||
|
||||
func _reload() -> void:
|
||||
_current_page = 1
|
||||
_total_count = 0
|
||||
_has_more = false
|
||||
_card_entries.clear()
|
||||
for child in card_grid.get_children():
|
||||
child.queue_free()
|
||||
var cached := CollectionCache.get_cards_response(_query_key_for_page(1))
|
||||
if not cached.is_empty():
|
||||
_render_cards_response(cached, 1)
|
||||
_fetch_page(1)
|
||||
|
||||
|
||||
func _fetch_page(page: int) -> void:
|
||||
if _loading:
|
||||
return
|
||||
_loading = true
|
||||
func _fetch_owned() -> void:
|
||||
_set_status("loading")
|
||||
|
||||
var payload := {
|
||||
"page": page,
|
||||
"pageSize": PAGE_SIZE,
|
||||
}
|
||||
var search := search_input.text.strip_edges()
|
||||
if not search.is_empty():
|
||||
payload["nameFilter"] = search
|
||||
|
||||
# Type filter — index 0 = "All Types" (skip)
|
||||
var type_idx := type_option.selected
|
||||
if type_idx > 0:
|
||||
payload["cardTypeFilter"] = type_option.get_item_text(type_idx)
|
||||
|
||||
# Affinity filter — index 0 = "All Affinities" (skip)
|
||||
var aff_idx := affinity_option.selected
|
||||
if aff_idx > 0:
|
||||
payload["affinityFilter"] = affinity_option.get_item_text(aff_idx)
|
||||
|
||||
var cached := CollectionCache.get_owned_map()
|
||||
if not cached.is_empty():
|
||||
_owned = cached
|
||||
_rebuild_grid()
|
||||
Network.request(
|
||||
"collection.get_cards",
|
||||
payload,
|
||||
func(_t: String, p: Variant): _on_cards_response(p, page),
|
||||
func(_code: String, msg: String): _on_error(msg)
|
||||
"collection.get_owned",
|
||||
{},
|
||||
func(_t: String, p: Variant): _on_owned_response(p),
|
||||
func(_code: String, msg: String): _on_owned_error(msg)
|
||||
)
|
||||
|
||||
|
||||
func _on_cards_response(payload: Variant, page: int) -> void:
|
||||
_loading = false
|
||||
var p := payload as Dictionary
|
||||
CollectionCache.store_cards_response(_query_key_for_page(page), p)
|
||||
_render_cards_response(p, page)
|
||||
func _on_owned_response(payload: Variant) -> void:
|
||||
var p := payload as Dictionary
|
||||
var raw : Variant = p.get("owned", {})
|
||||
_owned = raw if typeof(raw) == TYPE_DICTIONARY else {}
|
||||
CollectionCache.store_owned_map(_owned)
|
||||
_rebuild_grid()
|
||||
|
||||
|
||||
func _on_error(msg: String) -> void:
|
||||
_loading = false
|
||||
func _on_owned_error(msg: String) -> void:
|
||||
_set_status("empty")
|
||||
push_warning("CardsView: %s" % msg)
|
||||
|
||||
# ── Button handlers ───────────────────────────────────────────────────────────
|
||||
# ── Grid rendering (client-side filtered) ────────────────────────────────────
|
||||
|
||||
func _on_search_changed(_text: String) -> void:
|
||||
_search_timer = _SEARCH_DEBOUNCE
|
||||
func _rebuild_grid() -> void:
|
||||
for child in card_grid.get_children():
|
||||
child.queue_free()
|
||||
|
||||
|
||||
func _on_load_more() -> void:
|
||||
_fetch_page(_current_page + 1)
|
||||
|
||||
# ── Status helper ─────────────────────────────────────────────────────────────
|
||||
|
||||
func _set_status(state: String) -> void:
|
||||
loading_label.visible = (state == "loading")
|
||||
empty_label.visible = (state == "empty")
|
||||
if state != "loading":
|
||||
load_more_btn.visible = _has_more
|
||||
|
||||
|
||||
func _render_cards_response(payload: Dictionary, page: int) -> void:
|
||||
var cards : Array = payload.get("cards", [])
|
||||
_total_count = int(payload.get("totalCount", 0))
|
||||
var page_size : int = int(payload.get("pageSize", PAGE_SIZE))
|
||||
_current_page = page
|
||||
_has_more = (page * page_size) < _total_count
|
||||
|
||||
if page == 1:
|
||||
_card_entries.clear()
|
||||
for child in card_grid.get_children():
|
||||
child.queue_free()
|
||||
|
||||
for raw_dto in cards:
|
||||
var dto := raw_dto as Dictionary
|
||||
var def := ContentCache.get_definition(str(dto.get("cardDefinitionId", "")))
|
||||
var hydrated := _hydrate_card_dto(dto, def)
|
||||
_add_or_increment_card(hydrated, def)
|
||||
|
||||
if cards.is_empty() and page == 1:
|
||||
if _owned.is_empty():
|
||||
_set_status("empty")
|
||||
else:
|
||||
_set_status("done")
|
||||
|
||||
load_more_btn.visible = _has_more
|
||||
|
||||
|
||||
func _add_or_increment_card(dto: Dictionary, def: Dictionary) -> void:
|
||||
var def_id := str(dto.get("cardDefinitionId", ""))
|
||||
if def_id.is_empty():
|
||||
return
|
||||
|
||||
if _card_entries.has(def_id):
|
||||
var entry := _card_entries.get(def_id, {}) as Dictionary
|
||||
var next_count := int(entry.get("count", 1)) + 1
|
||||
entry["count"] = next_count
|
||||
var count_label := entry.get("label", null) as Label
|
||||
if count_label != null:
|
||||
count_label.text = "x%d" % next_count
|
||||
_card_entries[def_id] = entry
|
||||
var search := search_input.text.strip_edges().to_lower()
|
||||
var type_idx := type_option.selected
|
||||
var aff_idx := affinity_option.selected
|
||||
var type_filter := type_option.get_item_text(type_idx) if type_idx > 0 else ""
|
||||
var aff_filter := affinity_option.get_item_text(aff_idx) if aff_idx > 0 else ""
|
||||
|
||||
var entries : Array = []
|
||||
for def_id_var in _owned:
|
||||
var def_id := str(def_id_var)
|
||||
var count := int(_owned[def_id_var])
|
||||
var def := ContentCache.get_definition(def_id)
|
||||
if def.is_empty():
|
||||
continue
|
||||
var name := str(def.get("name", ""))
|
||||
var c_type := str(def.get("cardType", ""))
|
||||
var affinity := str(def.get("affinity", ""))
|
||||
if not search.is_empty() and not name.to_lower().contains(search):
|
||||
continue
|
||||
if not type_filter.is_empty() and c_type != type_filter:
|
||||
continue
|
||||
if not aff_filter.is_empty() and affinity != aff_filter:
|
||||
continue
|
||||
entries.append({
|
||||
"cardDefinitionId": def_id,
|
||||
"name": name,
|
||||
"cardType": c_type,
|
||||
"affinity": affinity,
|
||||
"rarity": str(def.get("rarity", "")),
|
||||
"tier": def.get("tier"),
|
||||
"copyCount": count,
|
||||
})
|
||||
|
||||
entries.sort_custom(func(a, b): return str(a["name"]) < str(b["name"]))
|
||||
|
||||
if entries.is_empty():
|
||||
_set_status("empty")
|
||||
return
|
||||
|
||||
for dto in entries:
|
||||
var def := ContentCache.get_definition(str(dto["cardDefinitionId"]))
|
||||
_add_card_to_grid(dto, def)
|
||||
|
||||
_set_status("done")
|
||||
|
||||
|
||||
func _add_card_to_grid(dto: Dictionary, def: Dictionary) -> void:
|
||||
var count := int(dto.get("copyCount", 1))
|
||||
|
||||
var wrapper := VBoxContainer.new()
|
||||
wrapper.add_theme_constant_override("separation", 4)
|
||||
wrapper.size_flags_horizontal = Control.SIZE_SHRINK_CENTER
|
||||
|
||||
var widget := CARD_WIDGET.instantiate() as PanelContainer
|
||||
widget.card_pressed.connect(func(_pressed_id: String):
|
||||
var selected_dto := dto.duplicate(true)
|
||||
var entry := _card_entries.get(def_id, {}) as Dictionary
|
||||
selected_dto["copyCount"] = int(entry.get("count", 1))
|
||||
card_selected.emit(selected_dto, def))
|
||||
card_selected.emit(dto.duplicate(true), def))
|
||||
wrapper.add_child(widget)
|
||||
widget.setup(dto, def)
|
||||
|
||||
var count_label := Label.new()
|
||||
count_label.text = "x1"
|
||||
count_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
|
||||
count_label.add_theme_font_size_override("font_size", 11)
|
||||
count_label.modulate = Color(0.72, 0.72, 0.80)
|
||||
wrapper.add_child(count_label)
|
||||
if count > 1:
|
||||
var count_label := Label.new()
|
||||
count_label.text = "x%d" % count
|
||||
count_label.horizontal_alignment = HORIZONTAL_ALIGNMENT_CENTER
|
||||
count_label.add_theme_font_size_override("font_size", 11)
|
||||
count_label.modulate = Color(0.72, 0.72, 0.80)
|
||||
wrapper.add_child(count_label)
|
||||
|
||||
card_grid.add_child(wrapper)
|
||||
_card_entries[def_id] = {
|
||||
"count": 1,
|
||||
"label": count_label,
|
||||
}
|
||||
|
||||
# ── Event handlers ────────────────────────────────────────────────────────────
|
||||
|
||||
func _hydrate_card_dto(dto: Dictionary, def: Dictionary) -> Dictionary:
|
||||
var hydrated := dto.duplicate(true)
|
||||
if def.is_empty():
|
||||
return hydrated
|
||||
hydrated["name"] = str(def.get("name", hydrated.get("name", "")))
|
||||
hydrated["cardType"] = str(def.get("cardType", hydrated.get("cardType", "")))
|
||||
hydrated["affinity"] = str(def.get("affinity", hydrated.get("affinity", "")))
|
||||
hydrated["rarity"] = str(def.get("rarity", hydrated.get("rarity", "")))
|
||||
var tier_value: Variant = def.get("tier", hydrated.get("tier", null))
|
||||
hydrated["tier"] = tier_value if tier_value != null else null
|
||||
return hydrated
|
||||
func _on_search_changed(_text: String) -> void:
|
||||
_search_timer = _SEARCH_DEBOUNCE
|
||||
|
||||
# ── Status helper ─────────────────────────────────────────────────────────────
|
||||
|
||||
func _query_key_for_page(page: int) -> String:
|
||||
var search := search_input.text.strip_edges()
|
||||
var type_filter := ""
|
||||
var affinity_filter := ""
|
||||
var type_idx := type_option.selected
|
||||
if type_idx > 0:
|
||||
type_filter = type_option.get_item_text(type_idx)
|
||||
var aff_idx := affinity_option.selected
|
||||
if aff_idx > 0:
|
||||
affinity_filter = affinity_option.get_item_text(aff_idx)
|
||||
return CollectionCache.cards_query_key(
|
||||
page,
|
||||
PAGE_SIZE,
|
||||
search,
|
||||
type_filter,
|
||||
affinity_filter)
|
||||
func _set_status(state: String) -> void:
|
||||
loading_label.visible = (state == "loading")
|
||||
empty_label.visible = (state == "empty")
|
||||
|
||||
@@ -2,6 +2,12 @@ namespace SOR.Collection;
|
||||
|
||||
// ── Request types (client → server) ──────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Returns the full owned collection as { definitionId → ownedCount }.
|
||||
/// No pagination — the map is small and enables client-side filter/sort.
|
||||
/// </summary>
|
||||
public sealed record GetOwnedRequest; // identity from connection
|
||||
|
||||
/// <summary>
|
||||
/// Paginated list of all cards the authenticated player owns.
|
||||
/// NameFilter: case-insensitive substring match on card name (optional).
|
||||
@@ -75,6 +81,8 @@ public sealed record SelectStarterDeckRequest(Guid StarterDeckId);
|
||||
|
||||
// ── Response / DTO types (server → client) ────────────────────────────────────
|
||||
|
||||
public sealed record GetOwnedResponse(Dictionary<Guid, int> Owned);
|
||||
|
||||
public sealed record GetCardsResponse(
|
||||
IEnumerable<PlayerCardDto> Cards,
|
||||
int TotalCount,
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
namespace SOR.Collection.Handlers;
|
||||
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using SOR.Database.Contexts;
|
||||
using SOR.Networking.Abstractions.Messaging;
|
||||
using SOR.Networking.Abstractions.Transport;
|
||||
using SOR.Shared.Networking;
|
||||
|
||||
/// <summary>
|
||||
/// collection.get_owned — returns the full owned collection as { definitionId → ownedCount }.
|
||||
///
|
||||
/// No pagination: the map is small (one entry per unique card definition owned)
|
||||
/// and returning it all at once lets the client filter and sort without round-trips.
|
||||
/// </summary>
|
||||
internal sealed class CollectionGetOwnedHandler : CollectionHandlerBase, IMessageHandler
|
||||
{
|
||||
private readonly CollectionDbContext _collectionDb;
|
||||
|
||||
public CollectionGetOwnedHandler(CollectionDbContext collectionDb)
|
||||
=> _collectionDb = collectionDb;
|
||||
|
||||
public string MessageType => "collection.get_owned";
|
||||
|
||||
public async Task<IServerMessage?> HandleAsync(
|
||||
IClientMessage message,
|
||||
AuthenticatedConnection connection,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
var accountId = Guid.Parse(connection.UserId);
|
||||
|
||||
var owned = await _collectionDb.PlayerCards
|
||||
.Where(pc => pc.AccountId == accountId)
|
||||
.GroupBy(pc => pc.CardDefinitionId)
|
||||
.Select(g => new { DefId = g.Key, Count = g.Count() })
|
||||
.ToDictionaryAsync(x => x.DefId, x => x.Count, cancellationToken);
|
||||
|
||||
return ServerMessage.Reply(
|
||||
"collection.get_owned.ack",
|
||||
message.Seq,
|
||||
new GetOwnedResponse(owned));
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,7 @@ public static class ServiceRegistration
|
||||
// Message handlers — one per message type, Transient lifetime.
|
||||
// MessageDispatcher collects all IMessageHandler registrations at startup.
|
||||
services.AddTransient<IMessageHandler, CollectionGetCardsHandler>();
|
||||
services.AddTransient<IMessageHandler, CollectionGetOwnedHandler>();
|
||||
services.AddTransient<IMessageHandler, CollectionGetDecksHandler>();
|
||||
services.AddTransient<IMessageHandler, CollectionGetDeckHandler>();
|
||||
services.AddTransient<IMessageHandler, CollectionCreateDeckHandler>();
|
||||
|
||||
Reference in New Issue
Block a user