@idosgames/mcp 0.1.19 → 0.1.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/dist/cli.js +2 -2
  2. package/package.json +1 -1
  3. package/registry/host.json +13 -13
  4. package/registry/index.json +474 -147
  5. package/registry/modules/ai.json +65 -0
  6. package/registry/modules/board-game.json +4 -4
  7. package/registry/modules/boosts.json +66 -0
  8. package/registry/modules/character.json +7 -8
  9. package/registry/modules/chat.json +7 -8
  10. package/registry/modules/collections.json +69 -0
  11. package/registry/modules/coop-events.json +67 -0
  12. package/registry/modules/craft.json +7 -8
  13. package/registry/modules/deals.json +7 -8
  14. package/registry/modules/events.json +10 -15
  15. package/registry/modules/friends.json +8 -8
  16. package/registry/modules/idle-rpg.json +4 -4
  17. package/registry/modules/inventory.json +16 -19
  18. package/registry/modules/invite.json +9 -9
  19. package/registry/modules/leaderboard.json +7 -8
  20. package/registry/modules/lootboxes.json +67 -0
  21. package/registry/modules/mailbox.json +71 -0
  22. package/registry/modules/marketplace.json +7 -8
  23. package/registry/modules/mini-game.json +7 -7
  24. package/registry/modules/multiplayer.json +74 -0
  25. package/registry/modules/premium.json +67 -0
  26. package/registry/modules/profile.json +11 -12
  27. package/registry/modules/pvp.json +5 -6
  28. package/registry/modules/quests.json +69 -0
  29. package/registry/modules/rewards.json +17 -23
  30. package/registry/modules/season.json +10 -15
  31. package/registry/modules/store.json +7 -8
  32. package/registry/modules/tutorials.json +7 -8
  33. package/registry/modules/voxelcraft.json +16 -12
  34. package/registry/modules/workshop.json +7 -8
  35. package/registry/skills/blockchain-system.json +1 -1
  36. package/registry/skills/idosgames-compose-modules.json +2 -2
  37. package/registry/skills/idosgames-getting-started.json +1 -1
  38. package/registry/skills/idosgames-module-contract.json +2 -2
  39. package/registry/skills/idosgames-project-structure.json +1 -1
  40. package/registry/skills/idosgames-ui-kit.json +2 -2
  41. package/registry/skills/mailbox-system.json +6 -0
  42. package/registry/skills/multiplayer-realtime.json +2 -2
  43. package/registry/skills/workshop-system.json +1 -1
@@ -7,7 +7,6 @@
7
7
  },
8
8
  "catalog": {
9
9
  "type": "feature",
10
- "inBase": true,
11
10
  "summary": "Chat for any game: channels as tabs, private chats, a feed with earlier messages, slow mode, and report / ignore / write privately in a popup.",
12
11
  "description": "A ready player chat (Unity V2/Runtime/UI/Chat) for ANY game, built on the @idosgames/react/ui kit and client.chat. The title's channels are tabs (names are localization keys) plus 'Private' — 1-on-1 chats (with friends when the title says so). The feed loads its history, pages back to earlier messages, shows the server's copy of what was sent (moderation may mask a word) and counts down the slow mode; a channel the player may not write to shows the server's reason. ONE poll covers every room and runs only while the screen is open, at the interval the server sets; rooms are marked read when the player leaves them. Popups: a message's actions (write privately, report with a reason, ignore the player) and the channel list to join or leave opt-in channels. Registers the 'chat' feature; features.open('chat', { userID }) opens a private chat (the friends card uses it). Its badge is the unread count, read once per session — a closed chat costs nothing. Ships title-seed.json: a world channel, an opt-in trade channel, private chats between friends.",
13
12
  "provides": [
@@ -33,19 +32,19 @@
33
32
  "name": "iDos Games",
34
33
  "url": "https://idosgames.com"
35
34
  },
36
- "version": "0.1.0"
35
+ "version": "0.1.1"
37
36
  },
38
37
  "dependencies": {
39
- "@idosgames/core": "0.19.0",
40
- "@idosgames/module-sdk": "0.6.0",
41
- "@idosgames/react": "0.3.0",
38
+ "@idosgames/core": "0.19.1",
39
+ "@idosgames/module-sdk": "0.8.0",
40
+ "@idosgames/react": "0.4.0",
42
41
  "react": "19.2.7"
43
42
  },
44
- "contentHash": "c8cb8ebf55d121863fddf885d9da0c07a25ad0b764173862787541c747d1b240",
43
+ "contentHash": "1bd9bec3b0ee8548e800e51bf045b0215da4320231fbf8565350554558f846e4",
45
44
  "files": [
46
45
  {
47
46
  "path": "ChatScreen.tsx",
48
- "content": "import {\n useCallback,\n useEffect,\n useRef,\n useState,\n type ReactNode,\n} from \"react\";\nimport type {\n ChatCursor,\n ChatReportReason,\n IDosGamesClient,\n} from \"@idosgames/core\";\nimport type {\n FeatureRegistry,\n FeatureScreenProps,\n} from \"@idosgames/module-sdk\";\nimport { useIDosGamesClient } from \"@idosgames/react\";\nimport {\n Button,\n Center,\n EmptyState,\n Icon,\n IconButton,\n Popup,\n Spinner,\n Tabs,\n errorText,\n outlined,\n panel,\n useCatalog,\n useNow,\n useToast,\n useUiKit,\n v,\n} from \"@idosgames/react/ui\";\nimport {\n authorName,\n channelChoices,\n chatBadge,\n isSystem,\n lastCursor,\n mergeMessages,\n orderedChannels,\n sendable,\n slowModeLeft,\n unreadLabel,\n type ChannelView,\n type MessageView,\n} from \"./model\";\nimport { t } from \"./i18n\";\n\n// Chat (Unity V2/Runtime/UI/Chat): the title's channels as tabs plus \"Private\" (1-on-1 chats with\n// friends). One poll covers every room and runs ONLY while this screen is open, at the interval the\n// server sets; rooms are marked read when the player leaves them. Message actions (report, ignore,\n// write privately) and joining / leaving channels are popups. Another module opens a private chat\n// with features.open(\"chat\", { userID }).\n\ntype Room =\n | { kind: \"channel\"; channel: ChannelView }\n | { kind: \"direct\"; roomID: string; peerName: string };\ntype Conversation = {\n RoomID?: string | null;\n PeerUserID?: string | null;\n PeerProfile?: { Username?: string | null } | null;\n UnreadCount?: number | null;\n LastMessage?: MessageView | null;\n};\nconst DIRECT = \"__direct\";\ntype ChatDefs = {\n Direct?: { IsEnabled?: boolean | null } | null;\n Channels?: Parameters<typeof channelChoices>[0];\n};\n\n/** Badge once per session (a closed chat costs nothing: no background polling). */\nexport function makeChatWatcher(features: FeatureRegistry) {\n return function ChatWatcher(): ReactNode {\n const client = useIDosGamesClient();\n useEffect(() => {\n // The same read gives the badge and whether the title has a chat at all: switched off, or\n // no channels — the lobby hides the tab.\n void client.chat.getChannels().then((r) => {\n const channels = r.ok ? (r.data.Channels ?? []) : [];\n features.setAvailable(\n \"chat\",\n channels.length > 0,\n r.ok\n ? \"the title's chat has no channels (Chat section)\"\n : `the chat is not available on the title (${r.error})`,\n );\n features.setBadge(\"chat\", chatBadge(channels));\n });\n }, [client]);\n return null;\n };\n}\n\nexport function makeChatScreen(features: FeatureRegistry) {\n return function ChatScreen({ args }: FeatureScreenProps): ReactNode {\n const client = useIDosGamesClient();\n const catalog = useCatalog();\n const toast = useToast();\n const [channels, setChannels] = useState<ChannelView[] | null>(null);\n const [interval, setIntervalSec] = useState(5);\n const [mutedUntil, setMutedUntil] = useState<string | null>(null);\n const [tab, setTab] = useState<string | null>(null);\n const [room, setRoom] = useState<Room | null>(null);\n const [feeds, setFeeds] = useState<Record<string, MessageView[]>>({});\n const [unread, setUnread] = useState<Record<string, number | null>>({});\n const [managing, setManaging] = useState(false);\n // The Chat section is not part of the client config — the definitions come from their own call.\n const [defs, setDefs] = useState<ChatDefs | null>(null);\n const roomRef = useRef<Room | null>(null);\n roomRef.current = room;\n\n const loadChannels = useCallback(async () => {\n const res = await client.chat.getChannels();\n if (!res.ok) return setChannels([]);\n const list = orderedChannels(res.data.Channels ?? []);\n setChannels(list);\n setIntervalSec(Math.max(2, Number(res.data.PollIntervalSeconds ?? 5)));\n setMutedUntil(res.data.MutedUntil ?? null);\n setUnread(\n Object.fromEntries(\n list.map((c) => [c.RoomID ?? \"\", c.UnreadCount ?? null]),\n ),\n );\n features.setBadge(\"chat\", 0);\n return list;\n }, [client]);\n\n useEffect(() => {\n void client.chat\n .getChatDefinitions()\n .then((r) => setDefs(r.ok ? (r.data as ChatDefs) : {}));\n }, [client]);\n\n useEffect(() => {\n void loadChannels().then((list) => {\n const target = (args as { userID?: string } | undefined)?.userID;\n if (target)\n return void openDirect(client, target, toast, (r) => {\n setTab(DIRECT);\n setRoom(r);\n });\n const first = list?.[0];\n if (first) {\n setTab(first.ChannelID ?? null);\n setRoom({ kind: \"channel\", channel: first });\n }\n });\n }, [loadChannels]);\n\n // One poll for every room, only while the screen is open.\n useEffect(() => {\n let stopped = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const tick = async () => {\n const res = await client.chat.poll();\n if (stopped) return;\n if (res.ok) {\n const current = roomID(roomRef.current);\n for (const r of res.data.Rooms ?? []) {\n if (!r.RoomID) continue;\n const msgs = r.Messages ?? [];\n if (msgs.length > 0)\n setFeeds((f) => ({\n ...f,\n [r.RoomID!]: mergeMessages(f[r.RoomID!] ?? [], msgs),\n }));\n if (r.RoomID !== current)\n setUnread((u) => ({\n ...u,\n [r.RoomID!]: r.UnreadCount ?? u[r.RoomID!] ?? null,\n }));\n }\n if (res.data.PollIntervalSeconds)\n setIntervalSec(Math.max(2, res.data.PollIntervalSeconds));\n }\n timer = setTimeout(() => void tick(), interval * 1000);\n };\n timer = setTimeout(() => void tick(), interval * 1000);\n return () => {\n stopped = true;\n if (timer) clearTimeout(timer);\n };\n }, [client, interval]);\n\n if (!channels || !defs)\n return (\n <Center>\n <Spinner />\n </Center>\n );\n const directEnabled = !!defs.Direct?.IsEnabled;\n if (channels.length === 0 && !directEnabled)\n return <EmptyState glyph=\"chat\" text={t(\"disabled\")} />;\n\n const pick = (id: string) => {\n setTab(id);\n if (id === DIRECT) return setRoom(null);\n const ch = channels.find((c) => c.ChannelID === id);\n if (ch) setRoom({ kind: \"channel\", channel: ch });\n };\n\n return (\n <div\n style={{\n display: \"grid\",\n gridTemplateColumns: \"minmax(0, 1fr)\",\n gap: 10,\n }}\n >\n <div style={{ display: \"flex\", gap: 8, alignItems: \"center\" }}>\n <div style={{ flex: 1, minWidth: 0 }}>\n <Tabs\n tabs={[\n ...channels.map((c) => ({\n id: c.ChannelID!,\n label: catalog.localize(c.DisplayNameKey ?? c.ChannelID),\n badge:\n Number(\n unreadLabel(unread[c.RoomID ?? \"\"]).replace(\"+\", \"\"),\n ) || undefined,\n })),\n ...(directEnabled ? [{ id: DIRECT, label: t(\"direct\") }] : []),\n ]}\n value={tab ?? \"\"}\n onChange={pick}\n />\n </div>\n <IconButton\n glyph=\"gear\"\n label={t(\"channels\")}\n onClick={() => setManaging(true)}\n size={36}\n tone=\"blue\"\n />\n </div>\n {mutedUntil && new Date(mutedUntil).getTime() > Date.now() ? (\n <div\n style={{\n ...panel,\n padding: 8,\n ...outlined,\n fontSize: 13,\n color: v.red,\n textAlign: \"center\",\n }}\n >\n {t(\"muted\")} {new Date(mutedUntil).toLocaleString()}\n </div>\n ) : null}\n {tab === DIRECT && !room ? (\n <Conversations onOpen={(r) => setRoom(r)} />\n ) : room ? (\n <RoomView\n key={roomID(room)}\n room={room}\n feed={feeds[roomID(room)] ?? []}\n setFeed={(fn) =>\n setFeeds((f) => ({\n ...f,\n [roomID(room)]: fn(f[roomID(room)] ?? []),\n }))\n }\n onBack={room.kind === \"direct\" ? () => setRoom(null) : undefined}\n onOpenDirect={(r) => {\n setTab(DIRECT);\n setRoom(r);\n }}\n directEnabled={directEnabled}\n />\n ) : null}\n {managing ? (\n <ChannelsPopup\n defs={defs}\n joined={channels.map((c) => c.ChannelID ?? \"\")}\n onClose={() => setManaging(false)}\n onChanged={() => void loadChannels()}\n />\n ) : null}\n </div>\n );\n };\n}\n\nfunction roomID(room: Room | null): string {\n if (!room) return \"\";\n return room.kind === \"channel\" ? (room.channel.RoomID ?? \"\") : room.roomID;\n}\n\nasync function openDirect(\n client: IDosGamesClient,\n userID: string,\n toast: (text: string, kind?: \"error\") => void,\n open: (r: Room) => void,\n): Promise<void> {\n const res = await client.chat.openDirectChannel(userID);\n if (!res.ok || !res.data.RoomID)\n return toast(errorText(res.ok ? \"\" : res.error), \"error\");\n open({\n kind: \"direct\",\n roomID: res.data.RoomID,\n peerName: res.data.PeerProfile?.Username ?? userID,\n });\n}\n\nfunction RoomView({\n room,\n feed,\n setFeed,\n onBack,\n onOpenDirect,\n directEnabled,\n}: {\n room: Room;\n feed: MessageView[];\n setFeed: (fn: (prev: MessageView[]) => MessageView[]) => void;\n onBack?: () => void;\n onOpenDirect: (r: Room) => void;\n directEnabled: boolean;\n}): ReactNode {\n const client = useIDosGamesClient();\n const toast = useToast();\n const kit = useUiKit();\n const now = useNow();\n const id = roomID(room);\n const [older, setOlder] = useState<ChatCursor | null | undefined>(undefined);\n const [loading, setLoading] = useState(true);\n const [text, setText] = useState(\"\");\n const [busy, setBusy] = useState(false);\n const [lastSent, setLastSent] = useState<number | null>(null);\n const [picked, setPicked] = useState<MessageView | null>(null);\n const feedRef = useRef<HTMLDivElement>(null);\n const feedNow = useRef(feed);\n feedNow.current = feed;\n const me = client.auth.context?.userID;\n const channel = room.kind === \"channel\" ? room.channel : null;\n const maxLength = channel?.MaxLength ?? 500;\n\n // History first, then mark read up to what was drawn; on leaving, read up to the last message.\n useEffect(() => {\n let alive = true;\n void client.chat.getHistory(id).then((res) => {\n if (!alive) return;\n setLoading(false);\n if (!res.ok) return;\n const merged = mergeMessages(feedNow.current, res.data.Messages ?? []);\n setFeed(() => merged);\n setOlder(res.data.NextBefore ?? null);\n const cursor = lastCursor(id, merged);\n if (cursor) void client.chat.markRead(id, cursor);\n });\n return () => {\n alive = false;\n const cursor = lastCursor(id, feedNow.current);\n if (cursor) void client.chat.markRead(id, cursor);\n };\n }, [client, id]);\n\n // Keep the newest message in view.\n useEffect(() => {\n const el = feedRef.current;\n if (el) el.scrollTop = el.scrollHeight;\n }, [feed.length]);\n\n const loadOlder = async () => {\n if (!older) return;\n const res = await client.chat.getHistory(id, older);\n if (!res.ok) return;\n setFeed((prev) => mergeMessages(prev, res.data.Messages ?? []));\n setOlder(res.data.NextBefore ?? null);\n };\n\n const wait = slowModeLeft(lastSent, channel?.SlowModeSeconds, now);\n const message = sendable(text, maxLength);\n const canWrite = channel ? channel.CanWrite !== false : true;\n\n const send = async () => {\n if (!message || wait > 0) return;\n setBusy(true);\n const res = channel\n ? await client.chat.sendMessage(channel.ChannelID!, message)\n : await client.chat.sendDirect(id, message);\n setBusy(false);\n if (!res.ok) return toast(errorText(res.error), \"error\");\n kit.play(\"tab\");\n setText(\"\");\n setLastSent(Date.now());\n // Render the SERVER's copy: moderation may have masked a word.\n if (res.data.Message)\n setFeed((prev) => mergeMessages(prev, [res.data.Message!]));\n };\n\n return (\n <div\n style={{\n display: \"grid\",\n gridTemplateRows: \"auto minmax(0, 1fr) auto\",\n gap: 8,\n height: \"min(70vh, 640px)\",\n minHeight: 320,\n }}\n >\n {onBack ? (\n <div style={{ display: \"flex\", alignItems: \"center\", gap: 8 }}>\n <Button size=\"sm\" tone=\"grey\" onClick={onBack}>\n ← {t(\"back\")}\n </Button>\n <span style={{ ...outlined, fontSize: 15 }}>\n {room.kind === \"direct\" ? room.peerName : \"\"}\n </span>\n </div>\n ) : (\n <div />\n )}\n <div\n ref={feedRef}\n className=\"idos-scroll\"\n style={{\n ...panel,\n padding: 10,\n overflowY: \"auto\",\n display: \"grid\",\n alignContent: \"start\",\n gap: 6,\n }}\n >\n {older ? (\n <Button\n size=\"sm\"\n tone=\"grey\"\n onClick={() => void loadOlder()}\n style={{ justifySelf: \"center\" }}\n >\n {t(\"older\")}\n </Button>\n ) : null}\n {loading ? (\n <Center minHeight={120}>\n <Spinner />\n </Center>\n ) : feed.length === 0 ? (\n <div\n style={{\n ...outlined,\n fontSize: 13,\n color: v.textDim,\n textAlign: \"center\",\n padding: 20,\n }}\n >\n {t(\"noMessages\")}\n </div>\n ) : null}\n {feed.map((m) => {\n const mine = m.SenderUserID === me;\n const system = isSystem(m);\n return (\n <div\n key={m.MessageID}\n style={{\n display: \"flex\",\n justifyContent: system\n ? \"center\"\n : mine\n ? \"flex-end\"\n : \"flex-start\",\n }}\n >\n <div\n onClick={!mine && !system ? () => setPicked(m) : undefined}\n style={{\n maxWidth: \"80%\",\n padding: \"6px 10px\",\n borderRadius: 12,\n background: system\n ? \"rgba(255,200,60,.18)\"\n : mine\n ? `linear-gradient(180deg, ${v.blue}, ${v.blueDeep})`\n : \"rgba(255,255,255,.1)\",\n cursor: !mine && !system ? \"pointer\" : undefined,\n overflowWrap: \"anywhere\",\n }}\n >\n {!mine ? (\n <div\n style={{\n ...outlined,\n fontSize: 11,\n color: system ? v.gold : v.textDim,\n }}\n >\n {system ? t(\"system\") : authorName(m)}\n </div>\n ) : null}\n <div style={{ fontSize: 14, fontWeight: 600 }}>{m.Text}</div>\n <div\n style={{\n fontSize: 10,\n color: \"rgba(255,255,255,.6)\",\n textAlign: \"right\",\n }}\n >\n {m.SentAt\n ? new Date(m.SentAt).toLocaleTimeString([], {\n hour: \"2-digit\",\n minute: \"2-digit\",\n })\n : \"\"}\n </div>\n </div>\n </div>\n );\n })}\n </div>\n {canWrite ? (\n <div style={{ display: \"flex\", gap: 8 }}>\n <input\n value={text}\n maxLength={maxLength}\n onChange={(e) => setText(e.target.value)}\n onKeyDown={(e) => e.key === \"Enter\" && void send()}\n placeholder={t(\"placeholder\")}\n style={{\n ...panel,\n flex: 1,\n minWidth: 0,\n padding: \"10px 12px\",\n fontSize: 15,\n color: v.text,\n outline: \"none\",\n }}\n data-tutorial-anchor=\"chat:input\"\n />\n <Button\n tone=\"green\"\n disabled={!message || wait > 0}\n busy={busy}\n onClick={() => void send()}\n >\n {wait > 0 ? `${wait}${t(\"sec\")}` : <Icon glyph=\"chat\" size={20} />}\n </Button>\n </div>\n ) : (\n <div\n style={{\n ...panel,\n padding: 10,\n ...outlined,\n fontSize: 13,\n color: v.textDim,\n textAlign: \"center\",\n }}\n >\n {channel?.WriteBlockedReason ?? \"—\"}\n </div>\n )}\n {picked ? (\n <MessagePopup\n message={picked}\n roomID={id}\n directEnabled={directEnabled}\n onOpenDirect={onOpenDirect}\n onClose={() => setPicked(null)}\n />\n ) : null}\n </div>\n );\n}\n\nfunction Conversations({ onOpen }: { onOpen: (r: Room) => void }): ReactNode {\n const client = useIDosGamesClient();\n const [list, setList] = useState<Conversation[] | null>(null);\n useEffect(() => {\n void client.chat\n .getConversations()\n .then((r) =>\n setList(r.ok ? ((r.data.Conversations ?? []) as Conversation[]) : []),\n );\n }, [client]);\n if (!list)\n return (\n <Center>\n <Spinner />\n </Center>\n );\n if (list.length === 0)\n return <EmptyState glyph=\"chat\" text={t(\"noConversations\")} />;\n return (\n <div style={{ display: \"grid\", gap: 8 }}>\n {list.map((c) => {\n const name = c.PeerProfile?.Username ?? c.PeerUserID ?? \"?\";\n return (\n <div\n key={c.RoomID}\n onClick={() =>\n c.RoomID &&\n onOpen({ kind: \"direct\", roomID: c.RoomID, peerName: name })\n }\n style={{\n ...panel,\n padding: 10,\n display: \"flex\",\n alignItems: \"center\",\n gap: 10,\n cursor: \"pointer\",\n }}\n >\n <Icon glyph=\"user\" size={28} />\n <div style={{ flex: 1, minWidth: 0 }}>\n <div style={{ ...outlined, fontSize: 15 }}>{name}</div>\n <div\n style={{\n fontSize: 12,\n color: v.textDim,\n overflow: \"hidden\",\n textOverflow: \"ellipsis\",\n whiteSpace: \"nowrap\",\n }}\n >\n {c.LastMessage?.Text ?? \"\"}\n </div>\n </div>\n {unreadLabel(c.UnreadCount) ? (\n <span\n style={{\n ...outlined,\n fontSize: 12,\n background: v.red,\n borderRadius: 10,\n padding: \"2px 7px\",\n }}\n >\n {unreadLabel(c.UnreadCount)}\n </span>\n ) : null}\n </div>\n );\n })}\n </div>\n );\n}\n\nconst REASONS: Array<{ id: ChatReportReason; label: Parameters<typeof t>[0] }> =\n [\n { id: \"Spam\", label: \"rSpam\" },\n { id: \"Abuse\", label: \"rAbuse\" },\n { id: \"Scam\", label: \"rScam\" },\n { id: \"Inappropriate\", label: \"rInappropriate\" },\n { id: \"Other\", label: \"rOther\" },\n ];\n\nfunction MessagePopup({\n message,\n roomID,\n directEnabled,\n onOpenDirect,\n onClose,\n}: {\n message: MessageView;\n roomID: string;\n directEnabled: boolean;\n onOpenDirect: (r: Room) => void;\n onClose: () => void;\n}): ReactNode {\n const client = useIDosGamesClient();\n const toast = useToast();\n const [reason, setReason] = useState<ChatReportReason>(\"Spam\");\n const [busy, setBusy] = useState<string | null>(null);\n const sender = message.SenderUserID!;\n const run = async (what: string, fn: () => Promise<void>) => {\n setBusy(what);\n await fn();\n setBusy(null);\n };\n return (\n <Popup title={authorName(message)} onClose={onClose} width={420}>\n <div\n style={{\n ...panel,\n padding: 10,\n fontSize: 14,\n fontWeight: 600,\n overflowWrap: \"anywhere\",\n }}\n >\n {message.Text}\n </div>\n {directEnabled ? (\n <Button\n tone=\"blue\"\n busy={busy === \"dm\"}\n onClick={() =>\n void run(\"dm\", async () => {\n await openDirect(client, sender, toast, (r) => {\n onOpenDirect(r);\n onClose();\n });\n })\n }\n >\n <Icon glyph=\"chat\" size={18} /> {t(\"writePrivately\")}\n </Button>\n ) : null}\n <div style={{ display: \"grid\", gap: 6 }}>\n <div style={{ ...outlined, fontSize: 13, color: v.textDim }}>\n {t(\"reason\")}\n </div>\n <Tabs\n tabs={REASONS.map((r) => ({ id: r.id, label: t(r.label) }))}\n value={reason}\n onChange={setReason}\n />\n <Button\n tone=\"red\"\n busy={busy === \"report\"}\n onClick={() =>\n void run(\"report\", async () => {\n const res = await client.chat.reportMessage(\n roomID,\n message.MessageID!,\n reason,\n );\n if (!res.ok) return toast(errorText(res.error), \"error\");\n toast(\n (res.data as { AlreadyReported?: boolean | null })\n .AlreadyReported\n ? t(\"alreadyReported\")\n : t(\"reported\"),\n );\n onClose();\n })\n }\n >\n {t(\"report\")}\n </Button>\n </div>\n <Button\n tone=\"grey\"\n busy={busy === \"ignore\"}\n onClick={() =>\n void run(\"ignore\", async () => {\n const res = await client.chat.ignoreUser(sender);\n if (!res.ok) return toast(errorText(res.error), \"error\");\n toast(t(\"ignored\"));\n onClose();\n })\n }\n >\n {t(\"ignore\")}\n </Button>\n </Popup>\n );\n}\n\nfunction ChannelsPopup({\n defs,\n joined,\n onClose,\n onChanged,\n}: {\n defs: ChatDefs;\n joined: string[];\n onClose: () => void;\n onChanged: () => void;\n}): ReactNode {\n const client = useIDosGamesClient();\n const catalog = useCatalog();\n const toast = useToast();\n const [busy, setBusy] = useState<string | null>(null);\n const [ids, setIds] = useState(joined);\n const choices = channelChoices(defs.Channels, ids);\n const toggle = async (id: string, join: boolean) => {\n setBusy(id);\n const res = join\n ? await client.chat.joinChannel(id)\n : await client.chat.leaveChannel(id);\n setBusy(null);\n if (!res.ok) return toast(errorText(res.error), \"error\");\n setIds((prev) => (join ? [...prev, id] : prev.filter((x) => x !== id)));\n onChanged();\n };\n return (\n <Popup title={t(\"channels\")} onClose={onClose} width={400}>\n <div style={{ display: \"grid\", gap: 8 }}>\n {choices.map((c) => (\n <div\n key={c.id}\n style={{\n ...panel,\n padding: 10,\n display: \"flex\",\n alignItems: \"center\",\n gap: 10,\n }}\n >\n <Icon glyph=\"chat\" size={24} />\n <div style={{ flex: 1, ...outlined, fontSize: 15 }}>\n {catalog.localize(c.name)}\n </div>\n <Button\n size=\"sm\"\n tone={c.joined ? \"grey\" : \"green\"}\n busy={busy === c.id}\n onClick={() => void toggle(c.id, !c.joined)}\n >\n {c.joined ? t(\"leave\") : t(\"join\")}\n </Button>\n </div>\n ))}\n </div>\n </Popup>\n );\n}\n"
47
+ "content": "import {\n useCallback,\n useEffect,\n useRef,\n useState,\n type ReactNode,\n} from \"react\";\nimport type {\n ChatCursor,\n ChatReportReason,\n IDosGamesClient,\n} from \"@idosgames/core\";\nimport type {\n FeatureRegistry,\n FeatureScreenProps,\n} from \"@idosgames/module-sdk\";\nimport { useIDosGamesClient } from \"@idosgames/react\";\nimport {\n Button,\n Center,\n EmptyState,\n errorText,\n Icon,\n IconButton,\n outlined,\n panel,\n Popup,\n Spinner,\n Tabs,\n toneSurface,\n useCatalog,\n useNow,\n useToast,\n useUiKit,\n v,\n} from \"@idosgames/react/ui\";\nimport {\n authorName,\n channelChoices,\n chatBadge,\n isSystem,\n lastCursor,\n mergeMessages,\n orderedChannels,\n sendable,\n slowModeLeft,\n unreadLabel,\n type ChannelView,\n type MessageView,\n} from \"./model\";\nimport { t } from \"./i18n\";\n\n// Chat (Unity V2/Runtime/UI/Chat): the title's channels as tabs plus \"Private\" (1-on-1 chats with\n// friends). One poll covers every room and runs ONLY while this screen is open, at the interval the\n// server sets; rooms are marked read when the player leaves them. Message actions (report, ignore,\n// write privately) and joining / leaving channels are popups. Another module opens a private chat\n// with features.open(\"chat\", { userID }).\n\ntype Room =\n | { kind: \"channel\"; channel: ChannelView }\n | { kind: \"direct\"; roomID: string; peerName: string };\ntype Conversation = {\n RoomID?: string | null;\n PeerUserID?: string | null;\n PeerProfile?: { Username?: string | null } | null;\n UnreadCount?: number | null;\n LastMessage?: MessageView | null;\n};\nconst DIRECT = \"__direct\";\ntype ChatDefs = {\n Direct?: { IsEnabled?: boolean | null } | null;\n Channels?: Parameters<typeof channelChoices>[0];\n};\n\n/** Badge once per session (a closed chat costs nothing: no background polling). */\nexport function makeChatWatcher(features: FeatureRegistry) {\n return function ChatWatcher(): ReactNode {\n const client = useIDosGamesClient();\n useEffect(() => {\n // The same read gives the badge and whether the title has a chat at all: switched off, or\n // no channels — the lobby hides the tab.\n void client.chat.getChannels().then((r) => {\n const channels = r.ok ? (r.data.Channels ?? []) : [];\n features.setAvailable(\n \"chat\",\n channels.length > 0,\n r.ok\n ? \"the title's chat has no channels (Chat section)\"\n : `the chat is not available on the title (${r.error})`,\n );\n features.setBadge(\"chat\", chatBadge(channels));\n });\n }, [client]);\n return null;\n };\n}\n\nexport function makeChatScreen(features: FeatureRegistry) {\n return function ChatScreen({ args }: FeatureScreenProps): ReactNode {\n const client = useIDosGamesClient();\n const catalog = useCatalog();\n const toast = useToast();\n const [channels, setChannels] = useState<ChannelView[] | null>(null);\n const [interval, setIntervalSec] = useState(5);\n const [mutedUntil, setMutedUntil] = useState<string | null>(null);\n const [tab, setTab] = useState<string | null>(null);\n const [room, setRoom] = useState<Room | null>(null);\n const [feeds, setFeeds] = useState<Record<string, MessageView[]>>({});\n const [unread, setUnread] = useState<Record<string, number | null>>({});\n const [managing, setManaging] = useState(false);\n // The Chat section is not part of the client config — the definitions come from their own call.\n const [defs, setDefs] = useState<ChatDefs | null>(null);\n const roomRef = useRef<Room | null>(null);\n roomRef.current = room;\n\n const loadChannels = useCallback(async () => {\n const res = await client.chat.getChannels();\n if (!res.ok) return setChannels([]);\n const list = orderedChannels(res.data.Channels ?? []);\n setChannels(list);\n setIntervalSec(Math.max(2, Number(res.data.PollIntervalSeconds ?? 5)));\n setMutedUntil(res.data.MutedUntil ?? null);\n setUnread(\n Object.fromEntries(\n list.map((c) => [c.RoomID ?? \"\", c.UnreadCount ?? null]),\n ),\n );\n features.setBadge(\"chat\", 0);\n return list;\n }, [client]);\n\n useEffect(() => {\n void client.chat\n .getChatDefinitions()\n .then((r) => setDefs(r.ok ? (r.data as ChatDefs) : {}));\n }, [client]);\n\n useEffect(() => {\n void loadChannels().then((list) => {\n const target = (args as { userID?: string } | undefined)?.userID;\n if (target)\n return void openDirect(client, target, toast, (r) => {\n setTab(DIRECT);\n setRoom(r);\n });\n const first = list?.[0];\n if (first) {\n setTab(first.ChannelID ?? null);\n setRoom({ kind: \"channel\", channel: first });\n }\n });\n }, [loadChannels]);\n\n // One poll for every room, only while the screen is open.\n useEffect(() => {\n let stopped = false;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const tick = async () => {\n const res = await client.chat.poll();\n if (stopped) return;\n if (res.ok) {\n const current = roomID(roomRef.current);\n for (const r of res.data.Rooms ?? []) {\n if (!r.RoomID) continue;\n const msgs = r.Messages ?? [];\n if (msgs.length > 0)\n setFeeds((f) => ({\n ...f,\n [r.RoomID!]: mergeMessages(f[r.RoomID!] ?? [], msgs),\n }));\n if (r.RoomID !== current)\n setUnread((u) => ({\n ...u,\n [r.RoomID!]: r.UnreadCount ?? u[r.RoomID!] ?? null,\n }));\n }\n if (res.data.PollIntervalSeconds)\n setIntervalSec(Math.max(2, res.data.PollIntervalSeconds));\n }\n timer = setTimeout(() => void tick(), interval * 1000);\n };\n timer = setTimeout(() => void tick(), interval * 1000);\n return () => {\n stopped = true;\n if (timer) clearTimeout(timer);\n };\n }, [client, interval]);\n\n if (!channels || !defs)\n return (\n <Center>\n <Spinner />\n </Center>\n );\n const directEnabled = !!defs.Direct?.IsEnabled;\n if (channels.length === 0 && !directEnabled)\n return <EmptyState glyph=\"chat\" text={t(\"disabled\")} />;\n\n const pick = (id: string) => {\n setTab(id);\n if (id === DIRECT) return setRoom(null);\n const ch = channels.find((c) => c.ChannelID === id);\n if (ch) setRoom({ kind: \"channel\", channel: ch });\n };\n\n return (\n <div\n style={{\n display: \"grid\",\n gridTemplateColumns: \"minmax(0, 1fr)\",\n gap: 10,\n }}\n >\n <div style={{ display: \"flex\", gap: 8, alignItems: \"center\" }}>\n <div style={{ flex: 1, minWidth: 0 }}>\n <Tabs\n tabs={[\n ...channels.map((c) => ({\n id: c.ChannelID!,\n label: catalog.localize(c.DisplayNameKey ?? c.ChannelID),\n badge:\n Number(\n unreadLabel(unread[c.RoomID ?? \"\"]).replace(\"+\", \"\"),\n ) || undefined,\n })),\n ...(directEnabled ? [{ id: DIRECT, label: t(\"direct\") }] : []),\n ]}\n value={tab ?? \"\"}\n onChange={pick}\n />\n </div>\n <IconButton\n glyph=\"gear\"\n label={t(\"channels\")}\n onClick={() => setManaging(true)}\n size={36}\n tone=\"blue\"\n />\n </div>\n {mutedUntil && new Date(mutedUntil).getTime() > Date.now() ? (\n <div\n style={{\n ...panel,\n padding: 8,\n ...outlined,\n fontSize: 13,\n color: v.red,\n textAlign: \"center\",\n }}\n >\n {t(\"muted\")} {new Date(mutedUntil).toLocaleString()}\n </div>\n ) : null}\n {tab === DIRECT && !room ? (\n <Conversations onOpen={(r) => setRoom(r)} />\n ) : room ? (\n <RoomView\n key={roomID(room)}\n room={room}\n feed={feeds[roomID(room)] ?? []}\n setFeed={(fn) =>\n setFeeds((f) => ({\n ...f,\n [roomID(room)]: fn(f[roomID(room)] ?? []),\n }))\n }\n onBack={room.kind === \"direct\" ? () => setRoom(null) : undefined}\n onOpenDirect={(r) => {\n setTab(DIRECT);\n setRoom(r);\n }}\n directEnabled={directEnabled}\n />\n ) : null}\n {managing ? (\n <ChannelsPopup\n defs={defs}\n joined={channels.map((c) => c.ChannelID ?? \"\")}\n onClose={() => setManaging(false)}\n onChanged={() => void loadChannels()}\n />\n ) : null}\n </div>\n );\n };\n}\n\nfunction roomID(room: Room | null): string {\n if (!room) return \"\";\n return room.kind === \"channel\" ? (room.channel.RoomID ?? \"\") : room.roomID;\n}\n\nasync function openDirect(\n client: IDosGamesClient,\n userID: string,\n toast: (text: string, kind?: \"error\") => void,\n open: (r: Room) => void,\n): Promise<void> {\n const res = await client.chat.openDirectChannel(userID);\n if (!res.ok || !res.data.RoomID)\n return toast(errorText(res.ok ? \"\" : res.error), \"error\");\n open({\n kind: \"direct\",\n roomID: res.data.RoomID,\n peerName: res.data.PeerProfile?.Username ?? userID,\n });\n}\n\nfunction RoomView({\n room,\n feed,\n setFeed,\n onBack,\n onOpenDirect,\n directEnabled,\n}: {\n room: Room;\n feed: MessageView[];\n setFeed: (fn: (prev: MessageView[]) => MessageView[]) => void;\n onBack?: () => void;\n onOpenDirect: (r: Room) => void;\n directEnabled: boolean;\n}): ReactNode {\n const client = useIDosGamesClient();\n const toast = useToast();\n const kit = useUiKit();\n const now = useNow();\n const id = roomID(room);\n const [older, setOlder] = useState<ChatCursor | null | undefined>(undefined);\n const [loading, setLoading] = useState(true);\n const [text, setText] = useState(\"\");\n const [busy, setBusy] = useState(false);\n const [lastSent, setLastSent] = useState<number | null>(null);\n const [picked, setPicked] = useState<MessageView | null>(null);\n const feedRef = useRef<HTMLDivElement>(null);\n const feedNow = useRef(feed);\n feedNow.current = feed;\n const me = client.auth.context?.userID;\n const channel = room.kind === \"channel\" ? room.channel : null;\n const maxLength = channel?.MaxLength ?? 500;\n\n // History first, then mark read up to what was drawn; on leaving, read up to the last message.\n useEffect(() => {\n let alive = true;\n void client.chat.getHistory(id).then((res) => {\n if (!alive) return;\n setLoading(false);\n if (!res.ok) return;\n const merged = mergeMessages(feedNow.current, res.data.Messages ?? []);\n setFeed(() => merged);\n setOlder(res.data.NextBefore ?? null);\n const cursor = lastCursor(id, merged);\n if (cursor) void client.chat.markRead(id, cursor);\n });\n return () => {\n alive = false;\n const cursor = lastCursor(id, feedNow.current);\n if (cursor) void client.chat.markRead(id, cursor);\n };\n }, [client, id]);\n\n // Keep the newest message in view.\n useEffect(() => {\n const el = feedRef.current;\n if (el) el.scrollTop = el.scrollHeight;\n }, [feed.length]);\n\n const loadOlder = async () => {\n if (!older) return;\n const res = await client.chat.getHistory(id, older);\n if (!res.ok) return;\n setFeed((prev) => mergeMessages(prev, res.data.Messages ?? []));\n setOlder(res.data.NextBefore ?? null);\n };\n\n const wait = slowModeLeft(lastSent, channel?.SlowModeSeconds, now);\n const message = sendable(text, maxLength);\n const canWrite = channel ? channel.CanWrite !== false : true;\n\n const send = async () => {\n if (!message || wait > 0) return;\n setBusy(true);\n const res = channel\n ? await client.chat.sendMessage(channel.ChannelID!, message)\n : await client.chat.sendDirect(id, message);\n setBusy(false);\n if (!res.ok) return toast(errorText(res.error), \"error\");\n kit.play(\"tab\");\n setText(\"\");\n setLastSent(Date.now());\n // Render the SERVER's copy: moderation may have masked a word.\n if (res.data.Message)\n setFeed((prev) => mergeMessages(prev, [res.data.Message!]));\n };\n\n return (\n <div\n style={{\n display: \"grid\",\n gridTemplateRows: \"auto minmax(0, 1fr) auto\",\n gap: 8,\n height: \"min(70vh, 640px)\",\n minHeight: 320,\n }}\n >\n {onBack ? (\n <div style={{ display: \"flex\", alignItems: \"center\", gap: 8 }}>\n <Button size=\"sm\" tone=\"grey\" onClick={onBack}>\n ← {t(\"back\")}\n </Button>\n <span style={{ ...outlined, fontSize: 15 }}>\n {room.kind === \"direct\" ? room.peerName : \"\"}\n </span>\n </div>\n ) : (\n <div />\n )}\n <div\n ref={feedRef}\n className=\"idos-scroll\"\n style={{\n ...panel,\n padding: 10,\n overflowY: \"auto\",\n display: \"grid\",\n alignContent: \"start\",\n gap: 6,\n }}\n >\n {older ? (\n <Button\n size=\"sm\"\n tone=\"grey\"\n onClick={() => void loadOlder()}\n style={{ justifySelf: \"center\" }}\n >\n {t(\"older\")}\n </Button>\n ) : null}\n {loading ? (\n <Center minHeight={120}>\n <Spinner />\n </Center>\n ) : feed.length === 0 ? (\n <div\n style={{\n ...outlined,\n fontSize: 13,\n color: v.textDim,\n textAlign: \"center\",\n padding: 20,\n }}\n >\n {t(\"noMessages\")}\n </div>\n ) : null}\n {feed.map((m) => {\n const mine = m.SenderUserID === me;\n const system = isSystem(m);\n return (\n <div\n key={m.MessageID}\n style={{\n display: \"flex\",\n justifyContent: system\n ? \"center\"\n : mine\n ? \"flex-end\"\n : \"flex-start\",\n }}\n >\n <div\n onClick={!mine && !system ? () => setPicked(m) : undefined}\n style={{\n maxWidth: \"80%\",\n padding: \"6px 10px\",\n borderRadius: 12,\n ...(system\n ? {\n background: `color-mix(in srgb, ${v.gold} 18%, transparent)`,\n }\n : mine\n ? toneSurface(\"blue\")\n : {\n background: `color-mix(in srgb, ${v.text} 10%, transparent)`,\n }),\n cursor: !mine && !system ? \"pointer\" : undefined,\n overflowWrap: \"anywhere\",\n }}\n >\n {!mine ? (\n <div\n style={{\n ...outlined,\n fontSize: 11,\n color: system ? v.gold : v.textDim,\n }}\n >\n {system ? t(\"system\") : authorName(m)}\n </div>\n ) : null}\n <div style={{ fontSize: 14, fontWeight: 600 }}>{m.Text}</div>\n <div\n style={{\n fontSize: 10,\n color: v.textDim,\n textAlign: \"right\",\n }}\n >\n {m.SentAt\n ? new Date(m.SentAt).toLocaleTimeString([], {\n hour: \"2-digit\",\n minute: \"2-digit\",\n })\n : \"\"}\n </div>\n </div>\n </div>\n );\n })}\n </div>\n {canWrite ? (\n <div style={{ display: \"flex\", gap: 8 }}>\n <input\n value={text}\n maxLength={maxLength}\n onChange={(e) => setText(e.target.value)}\n onKeyDown={(e) => e.key === \"Enter\" && void send()}\n placeholder={t(\"placeholder\")}\n style={{\n ...panel,\n flex: 1,\n minWidth: 0,\n padding: \"10px 12px\",\n fontSize: 15,\n color: v.text,\n outline: \"none\",\n }}\n data-tutorial-anchor=\"chat:input\"\n />\n <Button\n tone=\"green\"\n disabled={!message || wait > 0}\n busy={busy}\n onClick={() => void send()}\n >\n {wait > 0 ? `${wait}${t(\"sec\")}` : <Icon glyph=\"chat\" size={20} />}\n </Button>\n </div>\n ) : (\n <div\n style={{\n ...panel,\n padding: 10,\n ...outlined,\n fontSize: 13,\n color: v.textDim,\n textAlign: \"center\",\n }}\n >\n {channel?.WriteBlockedReason ?? \"—\"}\n </div>\n )}\n {picked ? (\n <MessagePopup\n message={picked}\n roomID={id}\n directEnabled={directEnabled}\n onOpenDirect={onOpenDirect}\n onClose={() => setPicked(null)}\n />\n ) : null}\n </div>\n );\n}\n\nfunction Conversations({ onOpen }: { onOpen: (r: Room) => void }): ReactNode {\n const client = useIDosGamesClient();\n const [list, setList] = useState<Conversation[] | null>(null);\n useEffect(() => {\n void client.chat\n .getConversations()\n .then((r) =>\n setList(r.ok ? ((r.data.Conversations ?? []) as Conversation[]) : []),\n );\n }, [client]);\n if (!list)\n return (\n <Center>\n <Spinner />\n </Center>\n );\n if (list.length === 0)\n return <EmptyState glyph=\"chat\" text={t(\"noConversations\")} />;\n return (\n <div style={{ display: \"grid\", gap: 8 }}>\n {list.map((c) => {\n const name = c.PeerProfile?.Username ?? c.PeerUserID ?? \"?\";\n return (\n <div\n key={c.RoomID}\n onClick={() =>\n c.RoomID &&\n onOpen({ kind: \"direct\", roomID: c.RoomID, peerName: name })\n }\n style={{\n ...panel,\n padding: 10,\n display: \"flex\",\n alignItems: \"center\",\n gap: 10,\n cursor: \"pointer\",\n }}\n >\n <Icon glyph=\"user\" size={28} />\n <div style={{ flex: 1, minWidth: 0 }}>\n <div style={{ ...outlined, fontSize: 15 }}>{name}</div>\n <div\n style={{\n fontSize: 12,\n color: v.textDim,\n overflow: \"hidden\",\n textOverflow: \"ellipsis\",\n whiteSpace: \"nowrap\",\n }}\n >\n {c.LastMessage?.Text ?? \"\"}\n </div>\n </div>\n {unreadLabel(c.UnreadCount) ? (\n <span\n style={{\n ...outlined,\n fontSize: 12,\n background: v.red,\n borderRadius: 10,\n padding: \"2px 7px\",\n }}\n >\n {unreadLabel(c.UnreadCount)}\n </span>\n ) : null}\n </div>\n );\n })}\n </div>\n );\n}\n\nconst REASONS: Array<{ id: ChatReportReason; label: Parameters<typeof t>[0] }> =\n [\n { id: \"Spam\", label: \"rSpam\" },\n { id: \"Abuse\", label: \"rAbuse\" },\n { id: \"Scam\", label: \"rScam\" },\n { id: \"Inappropriate\", label: \"rInappropriate\" },\n { id: \"Other\", label: \"rOther\" },\n ];\n\nfunction MessagePopup({\n message,\n roomID,\n directEnabled,\n onOpenDirect,\n onClose,\n}: {\n message: MessageView;\n roomID: string;\n directEnabled: boolean;\n onOpenDirect: (r: Room) => void;\n onClose: () => void;\n}): ReactNode {\n const client = useIDosGamesClient();\n const toast = useToast();\n const [reason, setReason] = useState<ChatReportReason>(\"Spam\");\n const [busy, setBusy] = useState<string | null>(null);\n const sender = message.SenderUserID!;\n const run = async (what: string, fn: () => Promise<void>) => {\n setBusy(what);\n await fn();\n setBusy(null);\n };\n return (\n <Popup title={authorName(message)} onClose={onClose} width={420}>\n <div\n style={{\n ...panel,\n padding: 10,\n fontSize: 14,\n fontWeight: 600,\n overflowWrap: \"anywhere\",\n }}\n >\n {message.Text}\n </div>\n {directEnabled ? (\n <Button\n tone=\"blue\"\n busy={busy === \"dm\"}\n onClick={() =>\n void run(\"dm\", async () => {\n await openDirect(client, sender, toast, (r) => {\n onOpenDirect(r);\n onClose();\n });\n })\n }\n >\n <Icon glyph=\"chat\" size={18} /> {t(\"writePrivately\")}\n </Button>\n ) : null}\n <div style={{ display: \"grid\", gap: 6 }}>\n <div style={{ ...outlined, fontSize: 13, color: v.textDim }}>\n {t(\"reason\")}\n </div>\n <Tabs\n tabs={REASONS.map((r) => ({ id: r.id, label: t(r.label) }))}\n value={reason}\n onChange={setReason}\n />\n <Button\n tone=\"red\"\n busy={busy === \"report\"}\n onClick={() =>\n void run(\"report\", async () => {\n const res = await client.chat.reportMessage(\n roomID,\n message.MessageID!,\n reason,\n );\n if (!res.ok) return toast(errorText(res.error), \"error\");\n toast(\n (res.data as { AlreadyReported?: boolean | null })\n .AlreadyReported\n ? t(\"alreadyReported\")\n : t(\"reported\"),\n );\n onClose();\n })\n }\n >\n {t(\"report\")}\n </Button>\n </div>\n <Button\n tone=\"grey\"\n busy={busy === \"ignore\"}\n onClick={() =>\n void run(\"ignore\", async () => {\n const res = await client.chat.ignoreUser(sender);\n if (!res.ok) return toast(errorText(res.error), \"error\");\n toast(t(\"ignored\"));\n onClose();\n })\n }\n >\n {t(\"ignore\")}\n </Button>\n </Popup>\n );\n}\n\nfunction ChannelsPopup({\n defs,\n joined,\n onClose,\n onChanged,\n}: {\n defs: ChatDefs;\n joined: string[];\n onClose: () => void;\n onChanged: () => void;\n}): ReactNode {\n const client = useIDosGamesClient();\n const catalog = useCatalog();\n const toast = useToast();\n const [busy, setBusy] = useState<string | null>(null);\n const [ids, setIds] = useState(joined);\n const choices = channelChoices(defs.Channels, ids);\n const toggle = async (id: string, join: boolean) => {\n setBusy(id);\n const res = join\n ? await client.chat.joinChannel(id)\n : await client.chat.leaveChannel(id);\n setBusy(null);\n if (!res.ok) return toast(errorText(res.error), \"error\");\n setIds((prev) => (join ? [...prev, id] : prev.filter((x) => x !== id)));\n onChanged();\n };\n return (\n <Popup title={t(\"channels\")} onClose={onClose} width={400}>\n <div style={{ display: \"grid\", gap: 8 }}>\n {choices.map((c) => (\n <div\n key={c.id}\n style={{\n ...panel,\n padding: 10,\n display: \"flex\",\n alignItems: \"center\",\n gap: 10,\n }}\n >\n <Icon glyph=\"chat\" size={24} />\n <div style={{ flex: 1, ...outlined, fontSize: 15 }}>\n {catalog.localize(c.name)}\n </div>\n <Button\n size=\"sm\"\n tone={c.joined ? \"grey\" : \"green\"}\n busy={busy === c.id}\n onClick={() => void toggle(c.id, !c.joined)}\n >\n {c.joined ? t(\"leave\") : t(\"join\")}\n </Button>\n </div>\n ))}\n </div>\n </Popup>\n );\n}\n"
49
48
  },
50
49
  {
51
50
  "path": "i18n.ts",
@@ -65,7 +64,7 @@
65
64
  },
66
65
  {
67
66
  "path": "module.meta.json",
68
- "content": "{\n \"id\": \"chat\",\n \"type\": \"feature\",\n \"inBase\": true,\n \"summary\": \"Chat for any game: channels as tabs, private chats, a feed with earlier messages, slow mode, and report / ignore / write privately in a popup.\",\n \"description\": \"A ready player chat (Unity V2/Runtime/UI/Chat) for ANY game, built on the @idosgames/react/ui kit and client.chat. The title's channels are tabs (names are localization keys) plus 'Private' — 1-on-1 chats (with friends when the title says so). The feed loads its history, pages back to earlier messages, shows the server's copy of what was sent (moderation may mask a word) and counts down the slow mode; a channel the player may not write to shows the server's reason. ONE poll covers every room and runs only while the screen is open, at the interval the server sets; rooms are marked read when the player leaves them. Popups: a message's actions (write privately, report with a reason, ignore the player) and the channel list to join or leave opt-in channels. Registers the 'chat' feature; features.open('chat', { userID }) opens a private chat (the friends card uses it). Its badge is the unread count, read once per session — a closed chat costs nothing. Ships title-seed.json: a world channel, an opt-in trade channel, private chats between friends.\",\n \"provides\": [\n \"chat channels as tabs\",\n \"private chats\",\n \"message feed with earlier messages\",\n \"slow mode countdown\",\n \"report, ignore and write privately\",\n \"join and leave channels\",\n \"chat badge\",\n \"demo channels\"\n ],\n \"tags\": [\"chat\", \"social\", \"messages\", \"dm\", \"moderation\", \"ui\", \"screen\"],\n \"author\": {\n \"name\": \"iDos Games\",\n \"url\": \"https://idosgames.com\"\n },\n \"version\": \"0.1.0\"\n}\n"
67
+ "content": "{\n \"id\": \"chat\",\n \"type\": \"feature\",\n \"summary\": \"Chat for any game: channels as tabs, private chats, a feed with earlier messages, slow mode, and report / ignore / write privately in a popup.\",\n \"description\": \"A ready player chat (Unity V2/Runtime/UI/Chat) for ANY game, built on the @idosgames/react/ui kit and client.chat. The title's channels are tabs (names are localization keys) plus 'Private' — 1-on-1 chats (with friends when the title says so). The feed loads its history, pages back to earlier messages, shows the server's copy of what was sent (moderation may mask a word) and counts down the slow mode; a channel the player may not write to shows the server's reason. ONE poll covers every room and runs only while the screen is open, at the interval the server sets; rooms are marked read when the player leaves them. Popups: a message's actions (write privately, report with a reason, ignore the player) and the channel list to join or leave opt-in channels. Registers the 'chat' feature; features.open('chat', { userID }) opens a private chat (the friends card uses it). Its badge is the unread count, read once per session — a closed chat costs nothing. Ships title-seed.json: a world channel, an opt-in trade channel, private chats between friends.\",\n \"provides\": [\n \"chat channels as tabs\",\n \"private chats\",\n \"message feed with earlier messages\",\n \"slow mode countdown\",\n \"report, ignore and write privately\",\n \"join and leave channels\",\n \"chat badge\",\n \"demo channels\"\n ],\n \"tags\": [\"chat\", \"social\", \"messages\", \"dm\", \"moderation\", \"ui\", \"screen\"],\n \"author\": {\n \"name\": \"iDos Games\",\n \"url\": \"https://idosgames.com\"\n },\n \"version\": \"0.1.1\"\n}\n"
69
68
  }
70
69
  ]
71
70
  }
@@ -0,0 +1,69 @@
1
+ {
2
+ "id": "collections",
3
+ "meta": {
4
+ "name": "Collections",
5
+ "type": "app",
6
+ "engine": "dom"
7
+ },
8
+ "catalog": {
9
+ "type": "feature",
10
+ "summary": "Collections for any game: an album of card sets with set rewards and a grand prize, packs and chests, trading spare cards with friends.",
11
+ "description": "A ready collections screen (engine Collection) for ANY game, built on the @idosgames/react/ui kit and client.collection. Album: the player's collection with every set in order — the cards held (with how many) and the gaps, a reward to claim per completed set and a grand prize for the whole album. Packs: every pack type with every way to pay, opened once or ten at a time (the server rolls them — new cards and duplicates are shown), and collection chests bought with the points duplicates turn into. Trades: offers from other players (accept / decline), your own offers (cancel), and giving a spare card to a friend. Registers the 'collections' feature; its badge counts set rewards and the grand prize waiting. Ships title-seed.json: a small album with sets, a pack and a chest.",
12
+ "provides": [
13
+ "collection album with sets",
14
+ "set rewards and grand prize",
15
+ "card packs, once or ten at a time",
16
+ "collection chests for points",
17
+ "trading cards with friends",
18
+ "badge for rewards waiting"
19
+ ],
20
+ "tags": [
21
+ "collection",
22
+ "album",
23
+ "cards",
24
+ "stickers",
25
+ "trading",
26
+ "ui",
27
+ "screen",
28
+ "events"
29
+ ],
30
+ "author": {
31
+ "name": "iDos Games",
32
+ "url": "https://idosgames.com"
33
+ },
34
+ "version": "0.1.1"
35
+ },
36
+ "dependencies": {
37
+ "@idosgames/core": "0.19.1",
38
+ "@idosgames/module-sdk": "0.8.0",
39
+ "@idosgames/react": "0.4.0",
40
+ "react": "19.2.7"
41
+ },
42
+ "contentHash": "35feb5ba1e12924999427f0d56b56a5b9db239ee8f91d805bcf0c39b40349273",
43
+ "files": [
44
+ {
45
+ "path": "CollectionsScreen.tsx",
46
+ "content": "import {\n useCallback,\n useEffect,\n useRef,\n useState,\n type ReactNode,\n} from \"react\";\nimport type {\n CollectionTradeOfferDocument,\n FriendPublicProfile,\n} from \"@idosgames/core\";\nimport type {\n FeatureRegistry,\n FeatureScreenProps,\n} from \"@idosgames/module-sdk\";\nimport { useIDosGamesClient, useUserState } from \"@idosgames/react\";\nimport {\n Button,\n Card,\n Center,\n EmptyState,\n Icon,\n Popup,\n ProgressBar,\n ResourceList,\n SectionTitle,\n Spinner,\n Tabs,\n canAfford,\n configSection,\n errorText,\n grantLines,\n grantedBy,\n outlined,\n panel,\n useCatalog,\n useCelebrate,\n usePopupClose,\n useStagger,\n useToast,\n useUiKit,\n v,\n} from \"@idosgames/react/ui\";\nimport {\n albumSets,\n chestRows,\n collectionsBadge,\n currentCollection,\n grandPrizeState,\n packOptions,\n type CardRow,\n type ChestRow,\n type CollectionSection,\n type CollectionStateView,\n type PackOption,\n type SetRow,\n} from \"./model\";\nimport { t } from \"./i18n\";\n\n// Collections (engine Collection): an album of sets — every card the player holds or still misses,\n// a reward per completed set and a grand prize for the whole album; packs of cards (currencies) and\n// collection chests (the currency duplicates turn into); and trading a spare card with a friend.\n\ntype Tab = \"album\" | \"packs\" | \"trades\";\n\nexport function CollectionsScreen(_: FeatureScreenProps): ReactNode {\n const client = useIDosGamesClient();\n const state = useUserState();\n const [tab, setTab] = useState<Tab>(\"album\");\n const section = configSection<CollectionSection>(client, \"Collection\");\n const mine = (state?.Collection ?? null) as CollectionStateView | null;\n const collection = currentCollection(section, mine);\n\n const reload = useCallback(async () => {\n await client.collection.getUserState();\n }, [client]);\n useEffect(() => {\n void reload();\n }, [reload]);\n\n if (!collection) return <EmptyState glyph=\"star\" text={t(\"noCollection\")} />;\n const sets = albumSets(collection, mine);\n return (\n <div style={{ display: \"grid\", gap: 14 }}>\n <Tabs\n tabs={[\n {\n id: \"album\",\n label: t(\"album\"),\n badge: collectionsBadge(collection, sets, mine),\n },\n { id: \"packs\", label: t(\"packs\") },\n { id: \"trades\", label: t(\"trades\") },\n ]}\n value={tab}\n onChange={setTab}\n />\n {tab === \"album\" ? (\n <Album\n collectionID={collection.CollectionID}\n name={collection.DisplayName ?? collection.CollectionID}\n grandPrize={grantLines(collection.GrandPrize)}\n prize={grandPrizeState(collection, sets, mine)}\n sets={sets}\n onChanged={reload}\n />\n ) : tab === \"packs\" ? (\n <Packs\n collectionID={collection.CollectionID}\n section={section}\n balance={Number(mine?.CollectionCurrencyBalance ?? 0)}\n onChanged={reload}\n />\n ) : (\n <Trades collectionID={collection.CollectionID} sets={sets} />\n )}\n </div>\n );\n}\n\n// ── Album ────────────────────────────────────────────────────────────────────────────────────\n\nfunction Album({\n collectionID,\n name,\n grandPrize,\n prize,\n sets,\n onChanged,\n}: {\n collectionID: string;\n name: string;\n grandPrize: ReturnType<typeof grantLines>;\n prize: ReturnType<typeof grandPrizeState>;\n sets: SetRow[];\n onChanged: () => Promise<void>;\n}): ReactNode {\n const client = useIDosGamesClient();\n const catalog = useCatalog();\n const celebrate = useCelebrate();\n const toast = useToast();\n const stagger = useStagger();\n const [busy, setBusy] = useState<string | null>(null);\n const owned = sets.reduce((s, x) => s + x.owned, 0);\n const total = sets.reduce((s, x) => s + x.total, 0);\n\n const claimSet = async (setID: string) => {\n setBusy(setID);\n const res = await client.collection.claimSetReward(collectionID, setID);\n setBusy(null);\n if (!res.ok) return toast(errorText(res.error), \"error\");\n celebrate(grantedBy(res.data));\n await onChanged();\n };\n const claimPrize = async () => {\n setBusy(\"grand\");\n const res = await client.collection.claimGrandPrize(collectionID);\n setBusy(null);\n if (!res.ok) return toast(errorText(res.error), \"error\");\n celebrate(grantedBy(res.data), { sound: \"levelUp\" });\n await onChanged();\n };\n\n return (\n <div style={{ display: \"grid\", gap: 12 }}>\n <div style={{ ...panel, padding: 12, display: \"grid\", gap: 8 }}>\n <div style={{ ...outlined, fontSize: 16 }}>\n {catalog.localize(name)}\n </div>\n <ProgressBar value={owned} max={Math.max(1, total)} tone=\"gold\" />\n {grandPrize.length > 0 ? (\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: 10,\n flexWrap: \"wrap\",\n }}\n >\n <span style={{ ...outlined, fontSize: 13, color: v.textDim }}>\n {t(\"grandPrize\")}\n </span>\n <ResourceList lines={grandPrize} size={20} />\n {prize === \"ready\" ? (\n <Button\n tone=\"gold\"\n size=\"sm\"\n attract\n busy={busy === \"grand\"}\n onClick={() => void claimPrize()}\n >\n {t(\"claim\")}\n </Button>\n ) : prize === \"claimed\" ? (\n <Icon glyph=\"check\" size={22} />\n ) : null}\n </div>\n ) : null}\n </div>\n {sets.map((s, i) => (\n <Card key={s.setID} highlight={s.state === \"ready\"} style={stagger(i)}>\n <div style={{ display: \"grid\", gap: 10 }}>\n <div\n style={{\n display: \"flex\",\n justifyContent: \"space-between\",\n alignItems: \"center\",\n gap: 8,\n }}\n >\n <span style={{ ...outlined, fontSize: 15 }}>\n {catalog.localize(s.name)}\n </span>\n <span style={{ ...outlined, fontSize: 13, color: v.gold }}>\n {s.owned} / {s.total}\n </span>\n </div>\n <div\n style={{\n display: \"grid\",\n gridTemplateColumns: \"repeat(auto-fill, minmax(64px, 1fr))\",\n gap: 8,\n }}\n >\n {s.cards.map((c) => (\n <CardTile key={c.id} card={c} />\n ))}\n </div>\n <div\n style={{\n display: \"flex\",\n alignItems: \"center\",\n gap: 10,\n flexWrap: \"wrap\",\n }}\n >\n <ResourceList lines={s.reward} size={18} />\n {s.state === \"ready\" ? (\n <Button\n tone=\"gold\"\n size=\"sm\"\n attract\n busy={busy === s.setID}\n onClick={() => void claimSet(s.setID)}\n data-tutorial-anchor={`collection:set:${s.setID}`}\n >\n {t(\"claim\")}\n </Button>\n ) : s.state === \"claimed\" ? (\n <Icon glyph=\"check\" size={20} />\n ) : null}\n </div>\n </div>\n </Card>\n ))}\n </div>\n );\n}\n\nfunction CardTile({ card }: { card: CardRow }): ReactNode {\n const catalog = useCatalog();\n const has = card.count > 0;\n return (\n <div\n title={catalog.localize(card.name)}\n style={{\n position: \"relative\",\n aspectRatio: \"3 / 4\",\n borderRadius: 10,\n display: \"grid\",\n placeItems: \"center\",\n background: has ? v.panelDeep : v.well,\n border: `2px solid ${has ? catalog.rarityColor(String(card.rarity)) : v.line}`,\n opacity: has ? 1 : 0.45,\n }}\n >\n <Icon glyph={has ? card.icon : \"lock\"} size={30} />\n {card.count > 1 ? (\n <span\n style={{\n position: \"absolute\",\n right: 4,\n bottom: 2,\n ...outlined,\n fontSize: 12,\n }}\n >\n ×{card.count}\n </span>\n ) : null}\n </div>\n );\n}\n\n// ── Packs and chests ─────────────────────────────────────────────────────────────────────────\n\nfunction Packs({\n collectionID,\n section,\n balance,\n onChanged,\n}: {\n collectionID: string;\n section: CollectionSection | undefined;\n balance: number;\n onChanged: () => Promise<void>;\n}): ReactNode {\n const state = useUserState();\n const stagger = useStagger();\n const [opening, setOpening] = useState<\n | { kind: \"pack\"; pack: PackOption; count: number }\n | { kind: \"chest\"; chest: ChestRow }\n | null\n >(null);\n const packs = packOptions(section);\n const chests = chestRows(section);\n const balances = state?.InventoryV2?.VirtualCurrencies as\n Record<string, { Amount?: number }> | undefined;\n if (packs.length === 0 && chests.length === 0)\n return <EmptyState glyph=\"ticket\" text={t(\"noPacks\")} />;\n const bulkOf = (p: PackOption) =>\n p.maxOpen >= 10 &&\n canAfford(\n p.price.map((l) => ({ ...l, amount: l.amount * 10 })),\n balances,\n );\n return (\n <div style={{ display: \"grid\", gap: 12 }}>\n {packs.length > 0 ? (\n <div\n style={{\n display: \"grid\",\n gridTemplateColumns: \"repeat(auto-fill, minmax(170px, 1fr))\",\n gap: 10,\n }}\n >\n {packs.map((p, i) => {\n const affordable = canAfford(p.price, balances);\n return (\n <Card\n key={`${p.packTypeID}:${p.optionID ?? \"\"}`}\n style={{\n display: \"grid\",\n gap: 8,\n justifyItems: \"center\",\n ...stagger(i),\n }}\n >\n <div style={{ ...outlined, fontSize: 15, textAlign: \"center\" }}>\n {p.name}\n </div>\n <div className=\"idos-bounce\">\n <Icon glyph={p.icon} size={56} />\n </div>\n <div style={{ ...outlined, fontSize: 12, color: v.textDim }}>\n {p.cards} {t(\"cards\")}\n </div>\n <Button\n tone={p.price.length === 0 ? \"green\" : \"gold\"}\n disabled={!affordable}\n onClick={() =>\n setOpening({ kind: \"pack\", pack: p, count: 1 })\n }\n style={{ width: \"100%\" }}\n data-tutorial-anchor={`collection:pack:${p.packTypeID}`}\n >\n {p.price.length === 0 ? (\n t(\"open\")\n ) : (\n <ResourceList lines={p.price} size={18} />\n )}\n </Button>\n {bulkOf(p) ? (\n <Button\n tone=\"blue\"\n size=\"sm\"\n onClick={() =>\n setOpening({ kind: \"pack\", pack: p, count: 10 })\n }\n style={{ width: \"100%\" }}\n >\n {t(\"open\")} ×10\n </Button>\n ) : null}\n </Card>\n );\n })}\n </div>\n ) : null}\n {chests.length > 0 ? (\n <div style={{ display: \"grid\", gap: 8 }}>\n <SectionTitle\n right={\n <span style={{ ...outlined, fontSize: 13, color: v.gold }}>\n {t(\"points\")}: {balance}\n </span>\n }\n >\n {t(\"chests\")}\n </SectionTitle>\n <div\n style={{\n display: \"grid\",\n gridTemplateColumns: \"repeat(auto-fill, minmax(170px, 1fr))\",\n gap: 10,\n }}\n >\n {chests.map((c) => (\n <Card\n key={c.chestID}\n style={{ display: \"grid\", gap: 8, justifyItems: \"center\" }}\n >\n <div style={{ ...outlined, fontSize: 15, textAlign: \"center\" }}>\n {c.name}\n </div>\n <Icon glyph={c.icon} size={56} />\n <div style={{ ...outlined, fontSize: 12, color: v.textDim }}>\n {c.cards} {t(\"cards\")}\n </div>\n <Button\n tone=\"gold\"\n disabled={balance < c.cost}\n onClick={() => setOpening({ kind: \"chest\", chest: c })}\n style={{ width: \"100%\" }}\n >\n {c.cost} {t(\"points\")}\n </Button>\n </Card>\n ))}\n </div>\n </div>\n ) : null}\n {opening ? (\n <OpenPopup\n collectionID={collectionID}\n opening={opening}\n onClose={() => setOpening(null)}\n onOpened={onChanged}\n />\n ) : null}\n </div>\n );\n}\n\nfunction OpenPopup({\n collectionID,\n opening,\n onClose,\n onOpened,\n}: {\n collectionID: string;\n opening:\n | { kind: \"pack\"; pack: PackOption; count: number }\n | { kind: \"chest\"; chest: ChestRow };\n onClose: () => void;\n onOpened: () => Promise<void>;\n}): ReactNode {\n const name = opening.kind === \"pack\" ? opening.pack.name : opening.chest.name;\n const count = opening.kind === \"pack\" ? opening.count : 1;\n return (\n <Popup\n title={count > 1 ? `${name} ×${count}` : name}\n onClose={onClose}\n variant=\"center\"\n >\n <OpenBody\n collectionID={collectionID}\n opening={opening}\n onOpened={onOpened}\n />\n </Popup>\n );\n}\n\nfunction OpenBody({\n collectionID,\n opening,\n onOpened,\n}: {\n collectionID: string;\n opening:\n | { kind: \"pack\"; pack: PackOption; count: number }\n | { kind: \"chest\"; chest: ChestRow };\n onOpened: () => Promise<void>;\n}): ReactNode {\n const client = useIDosGamesClient();\n const catalog = useCatalog();\n const celebrate = useCelebrate();\n const toast = useToast();\n const kit = useUiKit();\n const close = usePopupClose();\n const boxRef = useRef<HTMLDivElement>(null);\n const [busy, setBusy] = useState(false);\n const [got, setGot] = useState<Array<{ id: string; dup: boolean }> | null>(\n null,\n );\n\n const open = async () => {\n setBusy(true);\n const started = Date.now();\n const res =\n opening.kind === \"pack\"\n ? await client.collection.openPack(\n collectionID,\n opening.pack.packTypeID,\n opening.count,\n opening.pack.optionID\n ? { selectedOptionID: opening.pack.optionID }\n : undefined,\n )\n : await client.collection.openCollectionChest(\n collectionID,\n opening.chest.chestID,\n );\n await new Promise((r) =>\n setTimeout(\n r,\n Math.max(0, (kit.motion.on ? 700 : 0) - (Date.now() - started)),\n ),\n );\n setBusy(false);\n if (!res.ok) return toast(errorText(res.error), \"error\");\n kit.play(\"lootbox\");\n kit.fx.burst(boxRef.current);\n setGot([\n ...(res.data.GrantedCollectibles ?? []).map((c) => ({\n id: c.CollectibleID,\n dup: false,\n })),\n ...(res.data.DuplicateCollectibles ?? []).map((c) => ({\n id: c.CollectibleID,\n dup: true,\n })),\n ]);\n const bonus = grantedBy(res.data);\n if (bonus.length > 0) celebrate(bonus);\n await onOpened();\n };\n\n if (got)\n return (\n <div style={{ display: \"grid\", gap: 12 }}>\n <div\n style={{\n display: \"grid\",\n gridTemplateColumns: \"repeat(auto-fill, minmax(72px, 1fr))\",\n gap: 8,\n }}\n >\n {got.map((c, i) => (\n <div\n key={`${c.id}:${i}`}\n style={{\n ...panel,\n padding: 6,\n display: \"grid\",\n justifyItems: \"center\",\n gap: 4,\n opacity: c.dup ? 0.6 : 1,\n }}\n >\n <Icon glyph=\"star\" size={28} />\n <span style={{ ...outlined, fontSize: 11, textAlign: \"center\" }}>\n {catalog.localize(c.id)}\n </span>\n <span\n style={{\n ...outlined,\n fontSize: 10,\n color: c.dup ? v.textDim : v.green,\n }}\n >\n {c.dup ? t(\"duplicate\") : t(\"new\")}\n </span>\n </div>\n ))}\n </div>\n <Button tone=\"blue\" onClick={close}>\n {t(\"great\")}\n </Button>\n </div>\n );\n return (\n <div style={{ display: \"grid\", gap: 12, justifyItems: \"center\" }}>\n <div\n ref={boxRef}\n style={{\n animation: busy\n ? \"idos-shake .35s ease-in-out infinite\"\n : \"idos-bounce 1.2s ease-in-out infinite\",\n }}\n >\n <Icon\n glyph={\n opening.kind === \"pack\" ? opening.pack.icon : opening.chest.icon\n }\n size={110}\n />\n </div>\n <Button\n tone=\"gold\"\n size=\"lg\"\n attract\n busy={busy}\n onClick={() => void open()}\n >\n {busy ? t(\"opening\") : t(\"open\")}\n </Button>\n </div>\n );\n}\n\n// ── Trades ───────────────────────────────────────────────────────────────────────────────────\n\nfunction Trades({\n collectionID,\n sets,\n}: {\n collectionID: string;\n sets: SetRow[];\n}): ReactNode {\n const client = useIDosGamesClient();\n const catalog = useCatalog();\n const toast = useToast();\n const [incoming, setIncoming] = useState<\n CollectionTradeOfferDocument[] | null\n >(null);\n const [mine, setMine] = useState<CollectionTradeOfferDocument[]>([]);\n const [giving, setGiving] = useState<CardRow | null>(null);\n const [busy, setBusy] = useState<string | null>(null);\n const spare = sets.flatMap((s) => s.cards).filter((c) => c.spare > 0);\n\n const load = useCallback(async () => {\n const [inc, my] = await Promise.all([\n client.collection.getIncomingTradeOffers(collectionID),\n client.collection.getMyTradeOffers(collectionID),\n ]);\n setIncoming(inc.ok ? (inc.data.Offers ?? []) : []);\n setMine(my.ok ? (my.data.Offers ?? []) : []);\n }, [client, collectionID]);\n useEffect(() => {\n void load();\n }, [load]);\n\n const act = async (\n offerID: string,\n action: \"accept\" | \"decline\" | \"cancel\",\n ) => {\n setBusy(offerID);\n const res =\n action === \"accept\"\n ? await client.collection.acceptTradeOffer(offerID)\n : action === \"decline\"\n ? await client.collection.declineTradeOffer(offerID)\n : await client.collection.cancelTradeOffer(offerID);\n setBusy(null);\n if (!res.ok) return toast(errorText(res.error), \"error\");\n if (action === \"accept\") {\n toast(t(\"traded\"), \"success\");\n void client.collection.getUserState();\n }\n await load();\n };\n\n if (!incoming)\n return (\n <Center>\n <Spinner />\n </Center>\n );\n const pending = (o: CollectionTradeOfferDocument) =>\n !o.Status || o.Status === \"Pending\";\n return (\n <div style={{ display: \"grid\", gap: 14 }}>\n <div style={{ display: \"grid\", gap: 8 }}>\n <SectionTitle>{t(\"incoming\")}</SectionTitle>\n {incoming.filter(pending).length === 0 ? (\n <div style={{ ...outlined, fontSize: 13, color: v.textDim }}>\n {t(\"noIncoming\")}\n </div>\n ) : (\n incoming.filter(pending).map((o) => (\n <Card key={o.OfferID} style={{ display: \"grid\", gap: 8 }}>\n <div style={{ ...outlined, fontSize: 14 }}>\n {o.SenderPublicData?.Username ?? t(\"player\")} ·{\" \"}\n {catalog.localize(o.OfferedCollectibleID ?? \"\")}\n {o.RequestedCollectibleID\n ? ` ⇄ ${catalog.localize(o.RequestedCollectibleID)}`\n : \"\"}\n </div>\n <div style={{ display: \"flex\", gap: 8 }}>\n <Button\n tone=\"green\"\n size=\"sm\"\n busy={busy === o.OfferID}\n onClick={() => void act(o.OfferID, \"accept\")}\n >\n {t(\"accept\")}\n </Button>\n <Button\n tone=\"grey\"\n size=\"sm\"\n onClick={() => void act(o.OfferID, \"decline\")}\n >\n {t(\"decline\")}\n </Button>\n </div>\n </Card>\n ))\n )}\n </div>\n <div style={{ display: \"grid\", gap: 8 }}>\n <SectionTitle>{t(\"sent\")}</SectionTitle>\n {mine.filter(pending).map((o) => (\n <Card\n key={o.OfferID}\n style={{\n display: \"flex\",\n justifyContent: \"space-between\",\n alignItems: \"center\",\n gap: 8,\n }}\n >\n <span style={{ ...outlined, fontSize: 14 }}>\n {catalog.localize(o.OfferedCollectibleID ?? \"\")}\n </span>\n <Button\n tone=\"grey\"\n size=\"sm\"\n busy={busy === o.OfferID}\n onClick={() => void act(o.OfferID, \"cancel\")}\n >\n {t(\"cancel\")}\n </Button>\n </Card>\n ))}\n </div>\n <div style={{ display: \"grid\", gap: 8 }}>\n <SectionTitle>{t(\"giveSpare\")}</SectionTitle>\n {spare.length === 0 ? (\n <div style={{ ...outlined, fontSize: 13, color: v.textDim }}>\n {t(\"noSpare\")}\n </div>\n ) : (\n <div\n style={{\n display: \"grid\",\n gridTemplateColumns: \"repeat(auto-fill, minmax(64px, 1fr))\",\n gap: 8,\n }}\n >\n {spare.map((c) => (\n <button\n key={c.id}\n type=\"button\"\n className=\"idos-press\"\n onClick={() => setGiving(c)}\n style={{ border: \"none\", background: \"none\", padding: 0 }}\n >\n <CardTile card={c} />\n </button>\n ))}\n </div>\n )}\n </div>\n {giving ? (\n <GivePopup\n collectionID={collectionID}\n card={giving}\n onClose={() => setGiving(null)}\n onSent={load}\n />\n ) : null}\n </div>\n );\n}\n\nfunction GivePopup({\n collectionID,\n card,\n onClose,\n onSent,\n}: {\n collectionID: string;\n card: CardRow;\n onClose: () => void;\n onSent: () => Promise<void>;\n}): ReactNode {\n const catalog = useCatalog();\n return (\n <Popup\n title={`${t(\"offerTo\")}: ${catalog.localize(card.name)}`}\n onClose={onClose}\n width={420}\n >\n <FriendPicker collectionID={collectionID} card={card} onSent={onSent} />\n </Popup>\n );\n}\n\nfunction FriendPicker({\n collectionID,\n card,\n onSent,\n}: {\n collectionID: string;\n card: CardRow;\n onSent: () => Promise<void>;\n}): ReactNode {\n const client = useIDosGamesClient();\n const toast = useToast();\n const close = usePopupClose();\n const [friends, setFriends] = useState<FriendPublicProfile[] | null>(null);\n const [busy, setBusy] = useState<string | null>(null);\n useEffect(() => {\n void client.social\n .getFriendsList()\n .then((r) => setFriends(r.ok ? (r.data.Friends ?? []) : []));\n }, [client]);\n if (!friends)\n return (\n <Center>\n <Spinner />\n </Center>\n );\n if (friends.length === 0)\n return <EmptyState glyph=\"friends\" text={t(\"noFriends\")} />;\n const send = async (userID: string) => {\n setBusy(userID);\n const res = await client.collection.sendTradeOffer(\n collectionID,\n card.id,\n false,\n userID,\n );\n setBusy(null);\n if (!res.ok) return toast(errorText(res.error), \"error\");\n toast(t(\"offerSent\"), \"success\");\n close();\n await onSent();\n };\n return (\n <div style={{ display: \"grid\", gap: 8 }}>\n {friends.map((f) => (\n <Card\n key={f.UserID}\n style={{\n display: \"flex\",\n justifyContent: \"space-between\",\n alignItems: \"center\",\n gap: 8,\n }}\n >\n <span style={{ ...outlined, fontSize: 14 }}>\n {f.PublicData?.Username ?? t(\"player\")}\n </span>\n <Button\n tone=\"green\"\n size=\"sm\"\n busy={busy === f.UserID}\n onClick={() => void send(f.UserID)}\n >\n {t(\"give\")}\n </Button>\n </Card>\n ))}\n </div>\n );\n}\n\n// ── Always-on: the badge ─────────────────────────────────────────────────────────────────────\n\n/** Badge: set rewards and the grand prize waiting — only on a title with a collection. */\nexport function makeCollectionsWatcher(features: FeatureRegistry) {\n return function CollectionsBadge(): ReactNode {\n const client = useIDosGamesClient();\n const state = useUserState();\n useEffect(() => {\n void client.collection.getUserState();\n }, [client]);\n useEffect(() => {\n const mine = (state?.Collection ?? null) as CollectionStateView | null;\n const collection = currentCollection(\n configSection<CollectionSection>(client, \"Collection\"),\n mine,\n );\n features.setBadge(\n \"collections\",\n collectionsBadge(collection, albumSets(collection, mine), mine),\n );\n }, [client, state?.Collection]);\n return null;\n };\n}\n"
47
+ },
48
+ {
49
+ "path": "i18n.ts",
50
+ "content": "import { makeT } from \"@idosgames/react/ui\";\n\nconst EN = {\n title: \"Collections\",\n album: \"Album\",\n packs: \"Packs\",\n trades: \"Trades\",\n grandPrize: \"Grand prize\",\n claim: \"Claim\",\n cards: \"cards\",\n open: \"Open\",\n opening: \"Opening…\",\n chests: \"Chests for points\",\n points: \"Points\",\n new: \"New!\",\n duplicate: \"Duplicate\",\n great: \"Great!\",\n incoming: \"Offers to you\",\n noIncoming: \"No offers yet.\",\n sent: \"Your offers\",\n giveSpare: \"Give a spare card\",\n noSpare: \"No spare cards yet — duplicates show up here.\",\n offerTo: \"Give\",\n give: \"Give\",\n offerSent: \"Offer sent!\",\n accept: \"Accept\",\n decline: \"Decline\",\n cancel: \"Cancel\",\n traded: \"Card received!\",\n player: \"Player\",\n noFriends: \"Add friends to trade with them.\",\n noPacks: \"No packs yet. Add them in LiveOps → Collections.\",\n noCollection:\n \"No collection in this game yet. Add one in LiveOps → Collections.\",\n} as const;\n\nexport const t = makeT<keyof typeof EN>(EN, {\n title: \"Коллекции\",\n album: \"Альбом\",\n packs: \"Паки\",\n trades: \"Обмен\",\n grandPrize: \"Главный приз\",\n claim: \"Забрать\",\n cards: \"карт.\",\n open: \"Открыть\",\n opening: \"Открываем…\",\n chests: \"Сундуки за очки\",\n points: \"Очки\",\n new: \"Новая!\",\n duplicate: \"Повтор\",\n great: \"Отлично!\",\n incoming: \"Предложения вам\",\n noIncoming: \"Предложений пока нет.\",\n sent: \"Ваши предложения\",\n giveSpare: \"Отдать лишнюю карту\",\n noSpare: \"Лишних карт пока нет — здесь появятся повторы.\",\n offerTo: \"Отдать\",\n give: \"Отдать\",\n offerSent: \"Предложение отправлено!\",\n accept: \"Принять\",\n decline: \"Отклонить\",\n cancel: \"Отменить\",\n traded: \"Карта получена!\",\n player: \"Игрок\",\n noFriends: \"Добавьте друзей, чтобы меняться с ними.\",\n noPacks: \"Паков пока нет. Добавьте их в LiveOps → Collections.\",\n noCollection:\n \"Коллекций в этой игре пока нет. Добавьте её в LiveOps → Collections.\",\n});\n"
51
+ },
52
+ {
53
+ "path": "index.ts",
54
+ "content": "// @idosgames/mod-collections — Collections for any game: an album of sets to complete, packs and chests of collectibles, set rewards and a grand prize, trading cards with friends.\n\nexport { collectionsModule } from \"./module\";\n"
55
+ },
56
+ {
57
+ "path": "model.ts",
58
+ "content": "// Pure helpers of the collections screen — covered by model.test.ts. The server rolls packs and\n// decides what is complete; these only decide what the screen draws.\n\nimport type { ResourceGrant } from \"@idosgames/core\";\nimport { costLines, grantLines, type ResourceLine } from \"@idosgames/react/ui\";\n\n// ── Configuration (the fields this screen reads) ─────────────────────────────────────────────\n\nexport interface CollectibleView {\n CollectibleID?: string | null;\n DisplayName?: string | null;\n AssetPaths?: Record<string, string> | null;\n Rarity?: number | null;\n SortOrder?: number | null;\n}\n\nexport interface SetView {\n SetID?: string | null;\n DisplayName?: string | null;\n SortOrder?: number | null;\n Collectibles?: CollectibleView[] | null;\n SetCompletionReward?: ResourceGrant | null;\n}\n\nexport interface CollectionView {\n CollectionID?: string | null;\n DisplayName?: string | null;\n Description?: string | null;\n Sets?: SetView[] | null;\n GrandPrize?: ResourceGrant | null;\n}\n\nexport interface PackTypeView {\n PackTypeID?: string | null;\n DisplayName?: string | null;\n AssetPaths?: Record<string, string> | null;\n CollectibleCount?: number | null;\n MaxOpenCount?: number | null;\n PriceOptions?: Record<\n string,\n { OptionID?: string | null; Cost?: unknown } | null\n > | null;\n}\n\nexport interface CollectionChestView {\n CollectionChestID?: string | null;\n DisplayName?: string | null;\n AssetPaths?: Record<string, string> | null;\n CollectionCurrencyCost?: number | null;\n MinCollectibleCount?: number | null;\n MaxCollectibleCount?: number | null;\n}\n\n/** The title's Collection section, as far as the screen cares. */\nexport interface CollectionSection {\n Collections?: Record<string, CollectionView | null> | null;\n PackTypes?: Record<string, PackTypeView | null> | null;\n CollectionChests?: Array<CollectionChestView | null> | null;\n Settings?: { MaxPackOpenCount?: number | null } | null;\n}\n\n/** The player's collection state (UserState.Collection). */\nexport interface CollectionStateView {\n CollectionID?: string;\n CollectionCurrencyBalance?: number;\n OwnedCollectibles?: Record<string, number>;\n OwnedSpecialCollectibles?: Record<string, number>;\n ClaimedSetRewards?: string[];\n IsCollectionCompleted?: boolean;\n GrandPrizeClaimed?: boolean;\n}\n\n// ── Album ────────────────────────────────────────────────────────────────────────────────────\n\n/** The collection the player collects: the one in their state, else the title's first. */\nexport function currentCollection(\n section: CollectionSection | null | undefined,\n state: CollectionStateView | null | undefined,\n): (CollectionView & { CollectionID: string }) | null {\n const all = Object.entries(section?.Collections ?? {})\n .filter(([, c]) => c)\n .map(([id, c]) => ({ ...c!, CollectionID: c!.CollectionID || id }))\n .sort((a, b) => a.CollectionID.localeCompare(b.CollectionID));\n return (\n all.find((c) => c.CollectionID === state?.CollectionID) ?? all[0] ?? null\n );\n}\n\nexport interface CardRow {\n id: string;\n name: string;\n icon: string;\n rarity: number;\n /** How many the player holds (0 — a gap in the album). */\n count: number;\n /** Duplicates the player can give away in a trade. */\n spare: number;\n}\n\nexport interface SetRow {\n setID: string;\n name: string;\n cards: CardRow[];\n owned: number;\n total: number;\n reward: ResourceLine[];\n state: \"claimed\" | \"ready\" | \"collecting\";\n}\n\n/** The album: sets in order, their cards with what the player holds, and each set's reward state. */\nexport function albumSets(\n collection: CollectionView | null | undefined,\n state: CollectionStateView | null | undefined,\n): SetRow[] {\n const owned = state?.OwnedCollectibles ?? {};\n const claimed = state?.ClaimedSetRewards ?? [];\n return [...(collection?.Sets ?? [])]\n .filter((s): s is SetView => !!s)\n .sort(\n (a, b) =>\n Number(a.SortOrder ?? 0) - Number(b.SortOrder ?? 0) ||\n (a.SetID ?? \"\").localeCompare(b.SetID ?? \"\"),\n )\n .map((s) => {\n const setID = s.SetID ?? \"\";\n const cards = [...(s.Collectibles ?? [])]\n .filter((c): c is CollectibleView => !!c?.CollectibleID)\n .sort(\n (a, b) =>\n Number(a.SortOrder ?? 0) - Number(b.SortOrder ?? 0) ||\n a.CollectibleID!.localeCompare(b.CollectibleID!),\n )\n .map((c) => {\n const count = Number(owned[c.CollectibleID!] ?? 0);\n return {\n id: c.CollectibleID!,\n name: c.DisplayName || c.CollectibleID!,\n icon: c.AssetPaths?.icon ?? \"star\",\n rarity: Number(c.Rarity ?? 1),\n count,\n spare: Math.max(0, count - 1),\n };\n });\n const have = cards.filter((c) => c.count > 0).length;\n return {\n setID,\n name: s.DisplayName || setID,\n cards,\n owned: have,\n total: cards.length,\n reward: grantLines(s.SetCompletionReward),\n state: claimed.includes(setID)\n ? \"claimed\"\n : cards.length > 0 && have === cards.length\n ? \"ready\"\n : \"collecting\",\n };\n });\n}\n\n/** The grand prize: claimable once every set is complete (\"none\" — the collection has no prize). */\nexport function grandPrizeState(\n collection: CollectionView | null | undefined,\n sets: SetRow[],\n state: CollectionStateView | null | undefined,\n): \"none\" | \"claimed\" | \"ready\" | \"locked\" {\n if (grantLines(collection?.GrandPrize).length === 0) return \"none\";\n if (state?.GrandPrizeClaimed) return \"claimed\";\n return sets.length > 0 && sets.every((s) => s.state !== \"collecting\")\n ? \"ready\"\n : \"locked\";\n}\n\n// ── Packs and chests ─────────────────────────────────────────────────────────────────────────\n\nexport interface PackOption {\n packTypeID: string;\n optionID: string | null;\n name: string;\n icon: string;\n cards: number;\n price: ResourceLine[];\n maxOpen: number;\n}\n\n/** Every way to open every pack type (one entry per price option; free packs have one entry). */\nexport function packOptions(\n section: CollectionSection | null | undefined,\n): PackOption[] {\n const out: PackOption[] = [];\n for (const [id, p] of Object.entries(section?.PackTypes ?? {})) {\n if (!p) continue;\n const maxOpen = Number(\n p.MaxOpenCount ?? section?.Settings?.MaxPackOpenCount ?? 100,\n );\n if (maxOpen <= 0) continue;\n const base = {\n packTypeID: p.PackTypeID || id,\n name: p.DisplayName || p.PackTypeID || id,\n icon: p.AssetPaths?.icon ?? \"ticket\",\n cards: Number(p.CollectibleCount ?? 1),\n maxOpen,\n };\n const options = Object.entries(p.PriceOptions ?? {}).filter(([, o]) => o);\n if (options.length === 0) out.push({ ...base, optionID: null, price: [] });\n for (const [oid, o] of options)\n out.push({\n ...base,\n optionID: o?.OptionID || oid,\n price: costLines(o?.Cost as never).filter((l) => l.kind !== \"other\"),\n });\n }\n return out.sort(\n (a, b) =>\n a.packTypeID.localeCompare(b.packTypeID) ||\n (a.optionID ?? \"\").localeCompare(b.optionID ?? \"\"),\n );\n}\n\nexport interface ChestRow {\n chestID: string;\n name: string;\n icon: string;\n cost: number;\n cards: string;\n}\n\n/** Collection chests: bought with the collection's own currency (what duplicates turn into). */\nexport function chestRows(\n section: CollectionSection | null | undefined,\n): ChestRow[] {\n return (section?.CollectionChests ?? [])\n .filter((c): c is CollectionChestView => !!c?.CollectionChestID)\n .map((c) => {\n const min = Number(c.MinCollectibleCount ?? 1);\n const max = Number(c.MaxCollectibleCount ?? min);\n return {\n chestID: c.CollectionChestID!,\n name: c.DisplayName || c.CollectionChestID!,\n icon: c.AssetPaths?.icon ?? \"chest\",\n cost: Number(c.CollectionCurrencyCost ?? 0),\n cards: max > min ? `${min}–${max}` : `${min}`,\n };\n });\n}\n\n/** Badge: set rewards and the grand prize waiting. */\nexport function collectionsBadge(\n collection: CollectionView | null | undefined,\n sets: SetRow[],\n state: CollectionStateView | null | undefined,\n): number {\n return (\n sets.filter((s) => s.state === \"ready\").length +\n (grandPrizeState(collection, sets, state) === \"ready\" ? 1 : 0)\n );\n}\n\n/** Whether the title has a collection — until it does, the lobby hides the tab. */\nexport function hasTitleData(section: CollectionSection | undefined): boolean {\n return Object.values(section?.Collections ?? {}).some(Boolean);\n}\n"
59
+ },
60
+ {
61
+ "path": "module.ts",
62
+ "content": "import { defineModule, type Module } from \"@idosgames/module-sdk\";\nimport { configSection } from \"@idosgames/react/ui\";\nimport { CollectionsScreen, makeCollectionsWatcher } from \"./CollectionsScreen\";\nimport { hasTitleData, type CollectionSection } from \"./model\";\nimport { t } from \"./i18n\";\n\n// Collections as a feature of the game: the album, packs and chests, trades with friends. The\n// watcher keeps the badge (set rewards and the grand prize waiting) — only on a title with a\n// collection.\nexport const collectionsModule: Module = defineModule({\n id: \"collections\",\n meta: { name: \"Collections\", type: \"app\", engine: \"dom\" },\n setup(ctx) {\n ctx.features.register({\n id: \"collections\",\n label: t(\"title\"),\n icon: \"star\",\n group: \"events\",\n order: 45,\n available: false,\n Screen: CollectionsScreen,\n });\n const enabled = hasTitleData(\n configSection<CollectionSection>(ctx.client, \"Collection\"),\n );\n ctx.features.setAvailable(\n \"collections\",\n enabled,\n \"no collection on the title (Collection)\",\n );\n if (enabled)\n ctx.registerPanel({\n id: \"badge\",\n slot: \"modal\",\n activeOnly: false,\n component: makeCollectionsWatcher(ctx.features),\n });\n ctx.exposeToAgent({\n state: () => ({ ui: \"dom\", feature: \"collections\" }),\n describeActions: {},\n });\n },\n});\n"
63
+ },
64
+ {
65
+ "path": "module.meta.json",
66
+ "content": "{\n \"id\": \"collections\",\n \"type\": \"feature\",\n \"summary\": \"Collections for any game: an album of card sets with set rewards and a grand prize, packs and chests, trading spare cards with friends.\",\n \"description\": \"A ready collections screen (engine Collection) for ANY game, built on the @idosgames/react/ui kit and client.collection. Album: the player's collection with every set in order — the cards held (with how many) and the gaps, a reward to claim per completed set and a grand prize for the whole album. Packs: every pack type with every way to pay, opened once or ten at a time (the server rolls them — new cards and duplicates are shown), and collection chests bought with the points duplicates turn into. Trades: offers from other players (accept / decline), your own offers (cancel), and giving a spare card to a friend. Registers the 'collections' feature; its badge counts set rewards and the grand prize waiting. Ships title-seed.json: a small album with sets, a pack and a chest.\",\n \"provides\": [\n \"collection album with sets\",\n \"set rewards and grand prize\",\n \"card packs, once or ten at a time\",\n \"collection chests for points\",\n \"trading cards with friends\",\n \"badge for rewards waiting\"\n ],\n \"tags\": [\n \"collection\",\n \"album\",\n \"cards\",\n \"stickers\",\n \"trading\",\n \"ui\",\n \"screen\",\n \"events\"\n ],\n \"author\": {\n \"name\": \"iDos Games\",\n \"url\": \"https://idosgames.com\"\n },\n \"version\": \"0.1.1\"\n}\n"
67
+ }
68
+ ]
69
+ }
@@ -0,0 +1,67 @@
1
+ {
2
+ "id": "coop-events",
3
+ "meta": {
4
+ "name": "Team event",
5
+ "type": "app",
6
+ "engine": "dom"
7
+ },
8
+ "catalog": {
9
+ "type": "feature",
10
+ "summary": "Team events for any game: join a group, each member spins the wheel to build their own object, the team shares a grand prize.",
11
+ "description": "A ready team event screen (engine CoopEvent) for ANY game, built on the @idosgames/react/ui kit and client.coopEvent. Not in a group: the running team events of the title with their timers and team prize, 'Join a team' (the server matches partners, helpers fill the gaps). In a group: every member with their object and its progress, 'Spin' (once or five at a time, free or for currency) to build your own object, the object's reward when it is done, the team prize when every object is done, and leaving the team. The group lives in one shared document on the server — the screen re-reads it after every action. Registers the 'coop-events' feature; its badge counts the object reward and the team prize waiting. Ships title-seed.json: a weekly team build event.",
12
+ "provides": [
13
+ "team event screen",
14
+ "join a team (matchmaking by the server)",
15
+ "spin to build your object",
16
+ "object reward and team prize",
17
+ "badge for rewards waiting"
18
+ ],
19
+ "tags": [
20
+ "coop",
21
+ "team",
22
+ "group",
23
+ "events",
24
+ "social",
25
+ "ui",
26
+ "screen"
27
+ ],
28
+ "author": {
29
+ "name": "iDos Games",
30
+ "url": "https://idosgames.com"
31
+ },
32
+ "version": "0.1.1"
33
+ },
34
+ "dependencies": {
35
+ "@idosgames/core": "0.19.1",
36
+ "@idosgames/module-sdk": "0.8.0",
37
+ "@idosgames/react": "0.4.0",
38
+ "react": "19.2.7"
39
+ },
40
+ "contentHash": "1637a37f2dc83c83692cd674b2b4c4b5ea959d64ab783bffdb09254e50975836",
41
+ "files": [
42
+ {
43
+ "path": "CoopEventsScreen.tsx",
44
+ "content": "import {\n useCallback,\n useEffect,\n useRef,\n useState,\n useSyncExternalStore,\n type ReactNode,\n} from \"react\";\nimport type { ActiveCoopEventInfo, IDosGamesClient } from \"@idosgames/core\";\nimport type {\n FeatureRegistry,\n FeatureScreenProps,\n} from \"@idosgames/module-sdk\";\nimport { useIDosGamesClient, useUserState } from \"@idosgames/react\";\nimport {\n Button,\n canAfford,\n Card,\n Center,\n configSection,\n EmptyState,\n errorText,\n grantedBy,\n Icon,\n outlined,\n panel,\n Popup,\n ProgressBar,\n ResourceList,\n SectionTitle,\n Spinner,\n Timer,\n toneSurface,\n useCatalog,\n useCelebrate,\n useNow,\n useStagger,\n useToast,\n useUiKit,\n v,\n} from \"@idosgames/react/ui\";\nimport {\n bulkSpins,\n chainIDs,\n coopBadge,\n eventOf,\n groupRows,\n spinPrices,\n type CoopEventView,\n type CoopSection,\n type GroupView,\n} from \"./model\";\nimport { t } from \"./i18n\";\n\n// Team events (engine CoopEvent): the player joins a group (the server matches partners, bots fill\n// the gaps), each member spins the wheel to build their own object, and the group shares a grand\n// prize when every object is done. The group lives in ONE shared document on the server, so the\n// screen always re-reads it after an action instead of patching it locally.\n\n/** The player's group and the active events, shared by the screen and the badge (one read). */\nexport function createCoopStore(features: FeatureRegistry) {\n let group: GroupView | null | undefined = undefined;\n const listeners = new Set<() => void>();\n return {\n get: () => group,\n subscribe: (l: () => void) => {\n listeners.add(l);\n return () => listeners.delete(l);\n },\n async load(client: IDosGamesClient): Promise<void> {\n const res = await client.coopEvent.getUserState();\n group = res.ok\n ? ((res.data.ActiveGroup as GroupView | null) ?? null)\n : null;\n const rows = groupRows(\n group,\n eventOf(configSection<CoopSection>(client, \"CoopEvent\"), group),\n client.auth.context?.userID,\n );\n features.setBadge(\"coop-events\", group ? coopBadge(rows) : 0);\n for (const l of listeners) l();\n },\n };\n}\nexport type CoopStore = ReturnType<typeof createCoopStore>;\n\nexport function makeCoopEventsScreen(store: CoopStore) {\n return function CoopEventsScreen(_: FeatureScreenProps): ReactNode {\n const client = useIDosGamesClient();\n const group = useSyncExternalStore(store.subscribe, store.get, store.get);\n useEffect(() => {\n void store.load(client);\n }, [client]);\n if (group === undefined)\n return (\n <Center>\n <Spinner />\n </Center>\n );\n return group ? (\n <Group group={group} store={store} />\n ) : (\n <Join store={store} />\n );\n };\n}\n\n// ── Not in a group: the running events to join ───────────────────────────────────────────────\n\nfunction Join({ store }: { store: CoopStore }): ReactNode {\n const client = useIDosGamesClient();\n const catalog = useCatalog();\n const now = useNow();\n const toast = useToast();\n const stagger = useStagger();\n const [active, setActive] = useState<ActiveCoopEventInfo[] | null>(null);\n const [busy, setBusy] = useState<string | null>(null);\n useEffect(() => {\n const chains = chainIDs(configSection<CoopSection>(client, \"CoopEvent\"));\n void Promise.all(\n chains.map((c) => client.coopEvent.getActiveEvent(c)),\n ).then((all) => setActive(all.flatMap((r) => (r.ok ? [r.data] : []))));\n }, [client]);\n\n const join = async (chainID: string) => {\n setBusy(chainID);\n const res = await client.coopEvent.joinOrCreateGroup(chainID);\n setBusy(null);\n if (!res.ok) return toast(errorText(res.error), \"error\");\n await store.load(client);\n };\n\n if (!active)\n return (\n <Center>\n <Spinner />\n </Center>\n );\n const running = active.filter((a) => a.EventDef);\n if (running.length === 0)\n return <EmptyState glyph=\"friends\" text={t(\"noEvent\")} />;\n return (\n <div style={{ display: \"grid\", gap: 12 }}>\n {running.map((a, i) => {\n const def = a.EventDef as CoopEventView;\n return (\n <Card\n key={a.CoopChainID}\n style={{\n display: \"grid\",\n gap: 10,\n ...toneSurface(\"green\"),\n ...stagger(i),\n }}\n >\n <div style={{ display: \"flex\", alignItems: \"center\", gap: 12 }}>\n <div className=\"idos-bounce\">\n <Icon glyph=\"friends\" size={48} />\n </div>\n <div style={{ flex: 1, minWidth: 0 }}>\n <div style={{ ...outlined, fontSize: 17 }}>\n {catalog.localize(def.DisplayName ?? a.CoopChainID)}\n </div>\n <Timer\n at={a.ComputedEndUtc as string | undefined}\n now={now}\n label={t(\"endsIn\")}\n />\n </div>\n </div>\n {def.Description ? (\n <div\n style={{\n ...outlined,\n fontWeight: 600,\n fontSize: 13,\n color: v.textDim,\n }}\n >\n {catalog.localize(def.Description)}\n </div>\n ) : null}\n <div\n style={{\n display: \"flex\",\n gap: 8,\n alignItems: \"center\",\n flexWrap: \"wrap\",\n }}\n >\n <span style={{ ...outlined, fontSize: 13, color: v.textDim }}>\n {t(\"grandPrize\")}\n </span>\n <ResourceList\n lines={groupRows(null, def, null).grandPrize}\n size={20}\n />\n </div>\n <Button\n tone=\"green\"\n size=\"lg\"\n attract\n busy={busy === a.CoopChainID}\n onClick={() => void join(a.CoopChainID)}\n data-tutorial-anchor={`coop:join:${a.CoopChainID}`}\n >\n {t(\"join\")} · {Number(def.PartnerCount ?? 0) + 1} {t(\"players\")}\n </Button>\n </Card>\n );\n })}\n </div>\n );\n}\n\n// ── In a group ───────────────────────────────────────────────────────────────────────────────\n\nfunction Group({\n group,\n store,\n}: {\n group: GroupView;\n store: CoopStore;\n}): ReactNode {\n const client = useIDosGamesClient();\n const state = useUserState();\n const catalog = useCatalog();\n const celebrate = useCelebrate();\n const toast = useToast();\n const kit = useUiKit();\n const now = useNow();\n const ref = useRef<HTMLDivElement>(null);\n const [busy, setBusy] = useState<string | null>(null);\n const [last, setLast] = useState<number | null>(null);\n const [leaving, setLeaving] = useState(false);\n const event = eventOf(configSection<CoopSection>(client, \"CoopEvent\"), group);\n const rows = groupRows(group, event, client.auth.context?.userID);\n const balances = state?.InventoryV2?.VirtualCurrencies as\n Record<string, { Amount?: number }> | undefined;\n const reload = useCallback(() => store.load(client), [client]);\n\n const spin = async (optionID: string | null, count: number) => {\n setBusy(`${optionID ?? \"\"}:${count}`);\n const res = await client.coopEvent.spin(\n group.CoopChainID ?? \"\",\n group.GroupID ?? \"\",\n count,\n optionID ?? undefined,\n );\n setBusy(null);\n if (!res.ok) return toast(errorText(res.error), \"error\");\n kit.play(\"claim\");\n kit.fx.burst(ref.current);\n setLast(Number(res.data.ProgressDelta ?? 0));\n await reload();\n };\n const claim = async (kind: \"object\" | \"grand\") => {\n setBusy(kind);\n const res =\n kind === \"object\"\n ? await client.coopEvent.claimObjectReward(group.GroupID ?? \"\")\n : await client.coopEvent.claimGrandPrize(group.GroupID ?? \"\");\n setBusy(null);\n if (!res.ok) return toast(errorText(res.error), \"error\");\n celebrate(\n grantedBy(res.data),\n kind === \"grand\" ? { sound: \"levelUp\" } : undefined,\n );\n await reload();\n };\n const leave = async () => {\n setLeaving(false);\n const res = await client.coopEvent.leaveGroup(group.GroupID ?? undefined);\n if (!res.ok) return toast(errorText(res.error), \"error\");\n await reload();\n };\n\n return (\n <div ref={ref} style={{ display: \"grid\", gap: 12 }}>\n <div style={{ ...panel, padding: 12, display: \"grid\", gap: 6 }}>\n <div style={{ ...outlined, fontSize: 17 }}>\n {catalog.localize(event?.DisplayName ?? group.CoopEventID ?? \"\")}\n </div>\n {group.ExpiresAtUtc && !rows.finished ? (\n <Timer at={group.ExpiresAtUtc} now={now} label={t(\"endsIn\")} />\n ) : null}\n {rows.forming ? (\n <div style={{ ...outlined, fontSize: 13, color: v.gold }}>\n {t(\"forming\")}\n </div>\n ) : null}\n </div>\n\n <SectionTitle>{t(\"team\")}</SectionTitle>\n {rows.members.map((m) => (\n <Card\n key={m.userID}\n highlight={m.me}\n style={{ display: \"grid\", gap: 6, opacity: m.left ? 0.5 : 1 }}\n >\n <div\n style={{ display: \"flex\", justifyContent: \"space-between\", gap: 8 }}\n >\n <span style={{ ...outlined, fontSize: 14 }}>\n {m.me ? t(\"you\") : m.name}\n {m.bot ? ` · ${t(\"bot\")}` : \"\"}\n </span>\n <span style={{ ...outlined, fontSize: 13, color: v.textDim }}>\n {catalog.localize(m.objectName)}\n </span>\n </div>\n <ProgressBar\n value={m.progress}\n max={m.max}\n tone={m.done ? \"gold\" : \"green\"}\n />\n </Card>\n ))}\n\n {rows.mine && !rows.mine.done && !rows.finished ? (\n <div style={{ display: \"grid\", gap: 8 }}>\n {last !== null ? (\n <div\n style={{\n ...outlined,\n fontSize: 14,\n color: v.green,\n textAlign: \"center\",\n }}\n >\n +{last} {t(\"progress\")}\n </div>\n ) : null}\n {spinPrices(event).map((o) => {\n const affordable = canAfford(o.price, balances);\n const bulk = bulkSpins(event);\n return (\n <div key={o.id ?? \"free\"} style={{ display: \"flex\", gap: 8 }}>\n <Button\n tone=\"gold\"\n size=\"lg\"\n attract={affordable}\n disabled={!affordable}\n busy={busy === `${o.id ?? \"\"}:1`}\n onClick={() => void spin(o.id, 1)}\n style={{ flex: 1 }}\n data-tutorial-anchor=\"coop:spin\"\n >\n {t(\"spin\")}{\" \"}\n {o.price.length > 0 ? (\n <ResourceList lines={o.price} size={18} />\n ) : null}\n </Button>\n {bulk > 0 ? (\n <Button\n tone=\"blue\"\n disabled={\n !canAfford(\n o.price.map((l) => ({ ...l, amount: l.amount * bulk })),\n balances,\n )\n }\n busy={busy === `${o.id ?? \"\"}:${bulk}`}\n onClick={() => void spin(o.id, bulk)}\n >\n ×{bulk}\n </Button>\n ) : null}\n </div>\n );\n })}\n </div>\n ) : null}\n\n {rows.objectRewardReady ? (\n <Button\n tone=\"gold\"\n attract\n busy={busy === \"object\"}\n onClick={() => void claim(\"object\")}\n >\n {t(\"claimObject\")}{\" \"}\n <ResourceList lines={rows.objectReward} size={18} />\n </Button>\n ) : null}\n {rows.grandPrizeReady ? (\n <Button\n tone=\"gold\"\n size=\"lg\"\n attract\n busy={busy === \"grand\"}\n onClick={() => void claim(\"grand\")}\n >\n {t(\"claimGrand\")} <ResourceList lines={rows.grandPrize} size={20} />\n </Button>\n ) : null}\n {!rows.grandPrizeReady ? (\n <Button\n tone=\"grey\"\n size=\"sm\"\n onClick={() => (rows.finished ? void leave() : setLeaving(true))}\n >\n {rows.finished ? t(\"close\") : t(\"leave\")}\n </Button>\n ) : null}\n {leaving ? (\n <Popup title={t(\"leave\")} onClose={() => setLeaving(false)} width={360}>\n <div style={{ ...outlined, fontSize: 14, textAlign: \"center\" }}>\n {t(\"leaveConfirm\")}\n </div>\n <Button tone=\"red\" onClick={() => void leave()}>\n {t(\"leave\")}\n </Button>\n </Popup>\n ) : null}\n </div>\n );\n}\n\n/** Keeps the badge (object reward and grand prize waiting) — only on a title with team events. */\nexport function makeCoopWatcher(store: CoopStore) {\n return function CoopWatcher(): ReactNode {\n const client = useIDosGamesClient();\n useEffect(() => {\n void store.load(client);\n }, [client]);\n return null;\n };\n}\n"
45
+ },
46
+ {
47
+ "path": "i18n.ts",
48
+ "content": "import { makeT } from \"@idosgames/react/ui\";\n\nconst EN = {\n title: \"Team event\",\n endsIn: \"Ends in\",\n grandPrize: \"Team prize\",\n join: \"Join a team\",\n players: \"players\",\n forming: \"Looking for teammates…\",\n team: \"Your team\",\n you: \"You\",\n bot: \"helper\",\n spin: \"Spin\",\n progress: \"progress\",\n claimObject: \"Claim\",\n claimGrand: \"Claim the team prize\",\n leave: \"Leave the team\",\n leaveConfirm: \"Your progress in this event will be lost.\",\n close: \"Finish\",\n noEvent: \"No team event right now — check back later.\",\n} as const;\n\nexport const t = makeT<keyof typeof EN>(EN, {\n title: \"Командный ивент\",\n endsIn: \"До конца\",\n grandPrize: \"Приз команды\",\n join: \"Вступить в команду\",\n players: \"игр.\",\n forming: \"Ищем напарников…\",\n team: \"Ваша команда\",\n you: \"Вы\",\n bot: \"помощник\",\n spin: \"Крутить\",\n progress: \"прогресса\",\n claimObject: \"Забрать\",\n claimGrand: \"Забрать приз команды\",\n leave: \"Выйти из команды\",\n leaveConfirm: \"Прогресс в этом ивенте пропадёт.\",\n close: \"Завершить\",\n noEvent: \"Сейчас командного ивента нет — загляните позже.\",\n});\n"
49
+ },
50
+ {
51
+ "path": "index.ts",
52
+ "content": "// @idosgames/mod-coop-events — Team events for any game: a group of players builds together - each spins the wheel for their own object, the group shares a grand prize.\n\nexport { coopEventsModule } from \"./module\";\n"
53
+ },
54
+ {
55
+ "path": "model.ts",
56
+ "content": "// Pure helpers of the team events screen — covered by model.test.ts. The group lives on the server\n// (one shared document per group); these only decide what the screen draws.\n\nimport type { ResourceGrant } from \"@idosgames/core\";\nimport { costLines, grantLines, type ResourceLine } from \"@idosgames/react/ui\";\n\n// ── Configuration (the fields this screen reads) ─────────────────────────────────────────────\n\nexport interface CoopObjectView {\n Index?: number | null;\n DisplayName?: string | null;\n AssetPaths?: Record<string, string> | null;\n MaxProgress?: number | null;\n CompletionReward?: ResourceGrant | null;\n}\n\nexport interface CoopEventView {\n CoopEventID?: string | null;\n DisplayName?: string | null;\n Description?: string | null;\n PartnerCount?: number | null;\n BuildObjects?: {\n Objects?: CoopObjectView[] | null;\n PriceOptions?: Record<\n string,\n { OptionID?: string | null; Cost?: unknown } | null\n > | null;\n MaxSpinsPerCall?: number | null;\n } | null;\n GrandPrize?: ResourceGrant | null;\n}\n\n/** The title's CoopEvent section, as far as the screen cares. */\nexport interface CoopSection {\n Chains?: Record<\n string,\n {\n CoopChainID?: string | null;\n DisplayName?: string | null;\n Events?: CoopEventView[] | null;\n } | null\n > | null;\n}\n\n/** The group's shared document (as the server returns it). */\nexport interface GroupView {\n GroupID?: string | null;\n CoopChainID?: string | null;\n CoopEventID?: string | null;\n Status?: string | null;\n ExpiresAtUtc?: string | null;\n Members?: Array<{\n UserID?: string | null;\n PublicData?: { Username?: string | null } | null;\n IsBot?: boolean | null;\n MemberStatus?: string | null;\n GrandPrizeClaimed?: boolean | null;\n BuildObjectsProgress?: {\n ObjectIndex?: number | null;\n ObjectCompletionRewardClaimed?: boolean | null;\n } | null;\n } | null> | null;\n BuildObjectsState?: {\n Objects?: Array<{\n Index?: number | null;\n OwnerUserID?: string | null;\n CurrentProgress?: number | null;\n MaxProgress?: number | null;\n IsCompleted?: boolean | null;\n } | null> | null;\n } | null;\n}\n\n// ── Chains ───────────────────────────────────────────────────────────────────────────────────\n\n/** Chain ids of the title (each runs its own schedule of team events). */\nexport function chainIDs(section: CoopSection | null | undefined): string[] {\n return Object.entries(section?.Chains ?? {})\n .filter(([, c]) => c)\n .map(([id, c]) => c!.CoopChainID || id)\n .sort();\n}\n\n/** The event definition the group plays (by its CoopEventID across the chains). */\nexport function eventOf(\n section: CoopSection | null | undefined,\n group: GroupView | null | undefined,\n): CoopEventView | null {\n for (const c of Object.values(section?.Chains ?? {}))\n for (const e of c?.Events ?? [])\n if (e?.CoopEventID && e.CoopEventID === group?.CoopEventID) return e;\n return null;\n}\n\n// ── The group ────────────────────────────────────────────────────────────────────────────────\n\nexport interface MemberRow {\n userID: string;\n name: string;\n me: boolean;\n bot: boolean;\n left: boolean;\n objectName: string;\n progress: number;\n max: number;\n done: boolean;\n}\n\nexport interface GroupRows {\n members: MemberRow[];\n /** The player's own object (null — not in this group). */\n mine: MemberRow | null;\n /** The player's object is complete and its reward is not taken yet. */\n objectRewardReady: boolean;\n objectReward: ResourceLine[];\n /** The whole group is done and the player has not taken the grand prize. */\n grandPrizeReady: boolean;\n grandPrize: ResourceLine[];\n /** Waiting for partners — the server matches the group. */\n forming: boolean;\n /** The event is over for the group (done, failed or expired). */\n finished: boolean;\n}\n\n/** The group as the screen draws it: every member with their object's progress. */\nexport function groupRows(\n group: GroupView | null | undefined,\n event: CoopEventView | null | undefined,\n myUserID: string | null | undefined,\n): GroupRows {\n const objects = group?.BuildObjectsState?.Objects ?? [];\n const defs = event?.BuildObjects?.Objects ?? [];\n const members: MemberRow[] = (group?.Members ?? [])\n .filter((m): m is NonNullable<typeof m> => !!m?.UserID)\n .map((m) => {\n const index = Number(m.BuildObjectsProgress?.ObjectIndex ?? -1);\n const obj =\n objects.find((o) => o?.OwnerUserID === m.UserID) ??\n objects.find((o) => Number(o?.Index) === index);\n const def = defs.find((d) => Number(d?.Index) === Number(obj?.Index));\n const max = Math.max(\n 1,\n Number(obj?.MaxProgress ?? def?.MaxProgress ?? 1),\n );\n return {\n userID: m.UserID!,\n name: m.PublicData?.Username || m.UserID!,\n me: m.UserID === myUserID,\n bot: m.IsBot === true,\n left: !!m.MemberStatus && m.MemberStatus !== \"Active\",\n objectName: def?.DisplayName || `#${Number(obj?.Index ?? index) + 1}`,\n progress: Math.min(max, Number(obj?.CurrentProgress ?? 0)),\n max,\n done: obj?.IsCompleted === true,\n };\n });\n const mine = members.find((m) => m.me) ?? null;\n const meRaw = (group?.Members ?? []).find((m) => m?.UserID === myUserID);\n const myObj = objects.find((o) => o?.OwnerUserID === myUserID);\n const myDef = defs.find((d) => Number(d?.Index) === Number(myObj?.Index));\n const status = group?.Status ?? \"\";\n return {\n members,\n mine,\n objectRewardReady:\n !!mine?.done &&\n meRaw?.BuildObjectsProgress?.ObjectCompletionRewardClaimed !== true &&\n grantLines(myDef?.CompletionReward).length > 0,\n objectReward: grantLines(myDef?.CompletionReward),\n grandPrizeReady:\n status === \"Completed\" &&\n !!meRaw &&\n meRaw.GrandPrizeClaimed !== true &&\n grantLines(event?.GrandPrize).length > 0,\n grandPrize: grantLines(event?.GrandPrize),\n forming: status === \"Forming\",\n finished: [\"Completed\", \"Failed\", \"Expired\"].includes(status),\n };\n}\n\n/** Ways to pay for a spin (currencies/items); empty — spins are free. */\nexport function spinPrices(\n event: CoopEventView | null | undefined,\n): Array<{ id: string | null; price: ResourceLine[] }> {\n const options = Object.entries(event?.BuildObjects?.PriceOptions ?? {})\n .filter(([, o]) => o)\n .map(([oid, o]) => ({\n id: o?.OptionID || oid,\n price: costLines(o?.Cost as never).filter((l) => l.kind !== \"other\"),\n }));\n return options.length > 0 ? options : [{ id: null, price: [] }];\n}\n\n/** The bulk spin offered next to a single one: five, when the ceiling allows (platform default 25). */\nexport function bulkSpins(event: CoopEventView | null | undefined): number {\n const max = Number(event?.BuildObjects?.MaxSpinsPerCall ?? 25);\n return max >= 5 ? 5 : 0;\n}\n\n/** Badge: the object reward and the grand prize waiting. */\nexport function coopBadge(rows: GroupRows): number {\n return (rows.objectRewardReady ? 1 : 0) + (rows.grandPrizeReady ? 1 : 0);\n}\n\n/** Whether the title has team events — until it does, the lobby hides the tab. */\nexport function hasTitleData(section: CoopSection | undefined): boolean {\n return chainIDs(section).length > 0;\n}\n"
57
+ },
58
+ {
59
+ "path": "module.ts",
60
+ "content": "import { defineModule, type Module } from \"@idosgames/module-sdk\";\nimport { configSection } from \"@idosgames/react/ui\";\nimport {\n createCoopStore,\n makeCoopEventsScreen,\n makeCoopWatcher,\n} from \"./CoopEventsScreen\";\nimport { hasTitleData, type CoopSection } from \"./model\";\nimport { t } from \"./i18n\";\n\n// Team events as a feature of the game. The watcher reads the player's group once on start and\n// keeps the badge (object reward and team prize waiting) — only on a title with team events.\nexport const coopEventsModule: Module = defineModule({\n id: \"coop-events\",\n meta: { name: \"Team event\", type: \"app\", engine: \"dom\" },\n setup(ctx) {\n const store = createCoopStore(ctx.features);\n ctx.features.register({\n id: \"coop-events\",\n label: t(\"title\"),\n icon: \"friends\",\n group: \"events\",\n order: 28,\n available: false,\n Screen: makeCoopEventsScreen(store),\n });\n const enabled = hasTitleData(\n configSection<CoopSection>(ctx.client, \"CoopEvent\"),\n );\n ctx.features.setAvailable(\n \"coop-events\",\n enabled,\n \"no team events on the title (CoopEvent chains)\",\n );\n if (enabled)\n ctx.registerPanel({\n id: \"badge\",\n slot: \"modal\",\n activeOnly: false,\n component: makeCoopWatcher(store),\n });\n ctx.exposeToAgent({\n state: () => ({\n ui: \"dom\",\n feature: \"coop-events\",\n group: store.get()?.GroupID ?? null,\n }),\n describeActions: {},\n });\n },\n});\n"
61
+ },
62
+ {
63
+ "path": "module.meta.json",
64
+ "content": "{\n \"id\": \"coop-events\",\n \"type\": \"feature\",\n \"summary\": \"Team events for any game: join a group, each member spins the wheel to build their own object, the team shares a grand prize.\",\n \"description\": \"A ready team event screen (engine CoopEvent) for ANY game, built on the @idosgames/react/ui kit and client.coopEvent. Not in a group: the running team events of the title with their timers and team prize, 'Join a team' (the server matches partners, helpers fill the gaps). In a group: every member with their object and its progress, 'Spin' (once or five at a time, free or for currency) to build your own object, the object's reward when it is done, the team prize when every object is done, and leaving the team. The group lives in one shared document on the server — the screen re-reads it after every action. Registers the 'coop-events' feature; its badge counts the object reward and the team prize waiting. Ships title-seed.json: a weekly team build event.\",\n \"provides\": [\n \"team event screen\",\n \"join a team (matchmaking by the server)\",\n \"spin to build your object\",\n \"object reward and team prize\",\n \"badge for rewards waiting\"\n ],\n \"tags\": [\"coop\", \"team\", \"group\", \"events\", \"social\", \"ui\", \"screen\"],\n \"author\": {\n \"name\": \"iDos Games\",\n \"url\": \"https://idosgames.com\"\n },\n \"version\": \"0.1.1\"\n}\n"
65
+ }
66
+ ]
67
+ }
@@ -7,7 +7,6 @@
7
7
  },
8
8
  "catalog": {
9
9
  "type": "feature",
10
- "inBase": true,
11
10
  "summary": "Craft screen for any game: trade-up recipes by rarity or collection, a contract of owned items, auto-fill, price options and the result popup.",
12
11
  "description": "A ready craft screen (Unity Alikhan/Craft) for ANY game, built on the @idosgames/react/ui kit and client.craft. The screen lists the title's recipes as cards, lowest rarity first: what goes in (N items of a rarity or a collection) and what can come out. A recipe opens as a popup — the contract: the fitting items the player owns (worn equipment does not count), tap to add, 'Auto' fills from the most plentiful, the price options, and 'Craft'. The server rolls the result (only items with a roll Weight > 0 are promised) and the reward popup shows it flying into the inventory. 'Not enough coins' offers to open the shop (ctx.features.open('store')). Registers the 'craft' feature; its badge counts recipes the player can run now. Ships title-seed.json: 3 Common → Rare for coins and 3 Rare → Legendary for gems.",
13
12
  "provides": [
@@ -33,19 +32,19 @@
33
32
  "name": "iDos Games",
34
33
  "url": "https://idosgames.com"
35
34
  },
36
- "version": "0.1.0"
35
+ "version": "0.1.1"
37
36
  },
38
37
  "dependencies": {
39
- "@idosgames/core": "0.19.0",
40
- "@idosgames/module-sdk": "0.6.0",
41
- "@idosgames/react": "0.3.0",
38
+ "@idosgames/core": "0.19.1",
39
+ "@idosgames/module-sdk": "0.8.0",
40
+ "@idosgames/react": "0.4.0",
42
41
  "react": "19.2.7"
43
42
  },
44
- "contentHash": "771cc072c7bf80a5f8c6822836ed3c4198d4572aa5bc7bea663add134d5e79ee",
43
+ "contentHash": "e91d01d089fbe0897748e06bb079be807ad32b921f44c2999b592001c3bd5464",
45
44
  "files": [
46
45
  {
47
46
  "path": "CraftScreen.tsx",
48
- "content": "import { useEffect, useRef, useState, type ReactNode } from \"react\";\nimport type {\n FeatureRegistry,\n FeatureScreenProps,\n} from \"@idosgames/module-sdk\";\nimport { useIDosGamesClient, useUserState } from \"@idosgames/react\";\nimport {\n Button,\n Card,\n EmptyState,\n Icon,\n ItemTile,\n Popup,\n ResourceList,\n SectionTitle,\n Tabs,\n canAfford,\n configSection,\n errorText,\n grantedBy,\n outlined,\n useCatalog,\n useCelebrate,\n useGameLayout,\n useStagger,\n useToast,\n useUiKit,\n v,\n type ItemDefinitionView,\n} from \"@idosgames/react/ui\";\nimport {\n addToContract,\n autoFill,\n eligibleInputs,\n ownedCounts,\n possibleOutputs,\n recipes,\n type CraftSection,\n type Recipe,\n} from \"./model\";\nimport { t } from \"./i18n\";\n\n// Craft (Unity Alikhan/Craft: recipe cards → contract panel → info popup). The screen is the recipe\n// ladder — \"3 × Common → 1 × Rare\"; a recipe opens its CONTRACT as a popup: the slots to fill, the\n// player's fitting items to tap in (or fill automatically), the ways to pay, what can come out, and\n// \"Craft\". The server rolls the result; it pops out with the reward animation.\n\nexport function makeCraftScreen(features: FeatureRegistry) {\n return function CraftScreen(_: FeatureScreenProps): ReactNode {\n return <Craft features={features} />;\n };\n}\n\nfunction Craft({ features }: { features: FeatureRegistry }): ReactNode {\n const client = useIDosGamesClient();\n const catalog = useCatalog();\n const stagger = useStagger();\n const layout = useGameLayout();\n const [, loaded] = useState(0);\n const section = configSection<CraftSection>(client, \"Craft\");\n useEffect(() => {\n if (!section)\n void client.craft.getDefinitions().then(() => loaded((n) => n + 1));\n void client.user.getUserInventory();\n }, [client, section]);\n const list = recipes(section);\n const types = [...new Set(list.map((r) => r.type))];\n const [tab, setTab] = useState<Recipe[\"type\"]>(\"rarity\");\n const [open, setOpen] = useState<Recipe | null>(null);\n const state = useUserState();\n const owned = ownedCounts(state?.InventoryV2 as never);\n const items = catalog.items as Map<\n string,\n ItemDefinitionView & { CatalogID?: string }\n >;\n\n if (list.length === 0)\n return <EmptyState glyph=\"hammer\" text={t(\"noRecipes\")} />;\n const current = types.includes(tab) ? tab : types[0]!;\n const shown = list.filter((r) => r.type === current);\n\n return (\n <div style={{ display: \"grid\", gap: 14 }}>\n <Tabs\n tabs={types.map((x) => ({\n id: x,\n label: x === \"rarity\" ? t(\"byRarity\") : t(\"byCollection\"),\n }))}\n value={current}\n onChange={setTab}\n />\n <div\n style={{\n display: \"grid\",\n gridTemplateColumns:\n layout === \"phone\"\n ? \"1fr\"\n : \"repeat(auto-fill, minmax(320px, 1fr))\",\n gap: 12,\n }}\n >\n {shown.map((r, i) => {\n const fit = eligibleInputs(r, items, owned).reduce(\n (s, e) => s + e.available,\n 0,\n );\n const ready = fit >= r.count;\n return (\n <Card\n key={r.id}\n highlight={ready}\n onClick={() => setOpen(r)}\n style={{\n display: \"grid\",\n gridTemplateColumns: \"1fr auto 1fr\",\n alignItems: \"center\",\n gap: 10,\n ...stagger(i),\n }}\n >\n <RarityChip rarity={r.input} label={`${r.count} × ${r.input}`} />\n <div className={ready ? \"idos-bounce\" : undefined}>\n <Icon glyph=\"hammer\" size={34} />\n </div>\n <RarityChip rarity={r.output} label={`1 × ${r.output}`} />\n <div\n style={{\n gridColumn: \"1 / -1\",\n display: \"flex\",\n justifyContent: \"space-between\",\n ...outlined,\n fontSize: 12,\n color: v.textDim,\n }}\n >\n <span>\n {t(\"need\")}: {Math.min(fit, r.count)} / {r.count}\n </span>\n <ResourceList lines={r.options[0]?.price ?? []} size={16} />\n </div>\n </Card>\n );\n })}\n </div>\n {open ? (\n <ContractPopup\n recipe={open}\n owned={owned}\n items={items}\n onShop={\n features.get(\"store\") ? () => features.open(\"store\") : undefined\n }\n onClose={() => setOpen(null)}\n />\n ) : null}\n </div>\n );\n}\n\nfunction RarityChip({\n rarity,\n label,\n}: {\n rarity: string;\n label: string;\n}): ReactNode {\n const catalog = useCatalog();\n const color = catalog.rarityColor(rarity);\n return (\n <div style={{ display: \"grid\", justifyItems: \"center\", gap: 4 }}>\n <div\n style={{\n width: 58,\n height: 58,\n borderRadius: 14,\n border: `3px solid ${color}`,\n background: `radial-gradient(circle, ${color}55, ${v.panelDeep} 70%)`,\n display: \"grid\",\n placeItems: \"center\",\n }}\n >\n <Icon glyph=\"box\" size={34} />\n </div>\n <span style={{ ...outlined, fontSize: 12, color }}>{label}</span>\n </div>\n );\n}\n\nfunction ContractPopup({\n recipe,\n owned,\n items,\n onShop,\n onClose,\n}: {\n recipe: Recipe;\n owned: Record<string, number>;\n items: Map<string, ItemDefinitionView & { CatalogID?: string }>;\n onShop?: () => void;\n onClose: () => void;\n}): ReactNode {\n const client = useIDosGamesClient();\n const state = useUserState();\n const celebrate = useCelebrate();\n const toast = useToast();\n const kit = useUiKit();\n const anvil = useRef<HTMLDivElement>(null);\n const eligible = eligibleInputs(recipe, items, owned);\n const [contract, setContract] = useState<string[]>([]);\n const [optionID, setOptionID] = useState(recipe.options[0]?.id ?? \"\");\n const [busy, setBusy] = useState(false);\n const option = recipe.options.find((o) => o.id === optionID);\n const balances = state?.InventoryV2?.VirtualCurrencies as\n Record<string, { Amount?: number }> | undefined;\n const affordable = canAfford(option?.price ?? [], balances);\n\n const craft = async () => {\n setBusy(true);\n const started = Date.now();\n const res = await client.craft.craft(recipe.id, contract, 1, option?.id);\n await new Promise((r) =>\n setTimeout(\n r,\n Math.max(0, (kit.motion.on ? 600 : 0) - (Date.now() - started)),\n ),\n );\n setBusy(false);\n if (!res.ok) return toast(errorText(res.error), \"error\");\n kit.fx.burst(anvil.current);\n setContract([]);\n celebrate(grantedBy(res.data), { title: t(\"crafted\"), sound: \"levelUp\" });\n };\n\n return (\n <Popup\n title={`${t(\"contract\")}: ${recipe.count} × ${recipe.input} → ${recipe.output}`}\n onClose={onClose}\n width={520}\n >\n <div\n ref={anvil}\n style={{\n display: \"flex\",\n flexWrap: \"wrap\",\n gap: 8,\n justifyContent: \"center\",\n animation: busy ? \"idos-shake .35s ease-in-out infinite\" : undefined,\n }}\n >\n {Array.from({ length: recipe.count }, (_, i) => {\n const itemID = contract[i];\n return itemID ? (\n <ItemTile\n key={i}\n itemID={itemID}\n size={56}\n onClick={() => setContract((c) => c.filter((_, j) => j !== i))}\n />\n ) : (\n <div\n key={i}\n style={{\n width: 56,\n height: 56,\n borderRadius: 14,\n border: `3px dashed ${v.panelEdge}`,\n background: \"rgba(0,0,0,.25)\",\n }}\n />\n );\n })}\n </div>\n <SectionTitle\n right={\n <span style={{ display: \"flex\", gap: 6 }}>\n <Button\n size=\"sm\"\n tone=\"blue\"\n onClick={() => setContract(autoFill(recipe, eligible))}\n disabled={eligible.length === 0}\n >\n {t(\"auto\")}\n </Button>\n {contract.length > 0 ? (\n <Button size=\"sm\" tone=\"grey\" onClick={() => setContract([])}>\n {t(\"clear\")}\n </Button>\n ) : null}\n </span>\n }\n >\n <span style={{ fontSize: 15 }}>{t(\"yourItems\")}</span>\n </SectionTitle>\n {eligible.length === 0 ? (\n <EmptyState\n glyph=\"box\"\n text={t(\"noItems\")}\n action={\n onShop ? <Button onClick={onShop}>{t(\"toShop\")}</Button> : undefined\n }\n />\n ) : (\n <div\n style={{\n display: \"flex\",\n flexWrap: \"wrap\",\n gap: 8,\n justifyContent: \"center\",\n }}\n >\n {eligible.map((e) => {\n const used = contract.filter((x) => x === e.itemID).length;\n return (\n <ItemTile\n key={e.itemID}\n itemID={e.itemID}\n count={e.available - used}\n size={64}\n dim={used >= e.available}\n onClick={() =>\n setContract((c) =>\n addToContract(c, e.itemID, recipe, e.available),\n )\n }\n />\n );\n })}\n </div>\n )}\n <Outputs recipe={recipe} items={items} />\n {recipe.options.length > 1 ? (\n <Tabs\n tabs={recipe.options.map((o) => ({\n id: o.id,\n label: o.name ?? o.id,\n }))}\n value={optionID}\n onChange={setOptionID}\n />\n ) : null}\n <Button\n tone=\"gold\"\n size=\"lg\"\n attract={contract.length === recipe.count && affordable}\n disabled={contract.length < recipe.count || !affordable}\n busy={busy}\n onClick={() => void craft()}\n data-tutorial-anchor=\"craft:go\"\n >\n <Icon glyph=\"hammer\" size={22} /> {t(\"craft\")}{\" \"}\n {option && option.price.length > 0 ? (\n <ResourceList\n lines={option.price}\n size={18}\n dimIf={() => !affordable}\n />\n ) : (\n t(\"free\")\n )}\n </Button>\n </Popup>\n );\n}\n\nfunction Outputs({\n recipe,\n items,\n}: {\n recipe: Recipe;\n items: Map<string, ItemDefinitionView & { CatalogID?: string }>;\n}): ReactNode {\n const outputs = possibleOutputs(recipe, items);\n if (outputs.length === 0) return null;\n return (\n <div style={{ display: \"grid\", gap: 6 }}>\n <div style={{ ...outlined, fontSize: 13, color: v.textDim }}>\n {t(\"canYield\")}\n </div>\n <div\n style={{\n display: \"flex\",\n flexWrap: \"wrap\",\n gap: 6,\n justifyContent: \"center\",\n }}\n >\n {outputs.map((id) => (\n <ItemTile key={id} itemID={id} size={48} />\n ))}\n </div>\n </div>\n );\n}\n"
47
+ "content": "import { useEffect, useRef, useState, type ReactNode } from \"react\";\nimport type {\n FeatureRegistry,\n FeatureScreenProps,\n} from \"@idosgames/module-sdk\";\nimport { useIDosGamesClient, useUserState } from \"@idosgames/react\";\nimport {\n Button,\n Card,\n EmptyState,\n Icon,\n ItemTile,\n Popup,\n ResourceList,\n SectionTitle,\n Tabs,\n canAfford,\n configSection,\n errorText,\n grantedBy,\n outlined,\n useCatalog,\n useCelebrate,\n useGameLayout,\n useStagger,\n useToast,\n useUiKit,\n v,\n type ItemDefinitionView,\n} from \"@idosgames/react/ui\";\nimport {\n addToContract,\n autoFill,\n eligibleInputs,\n ownedCounts,\n possibleOutputs,\n recipes,\n type CraftSection,\n type Recipe,\n} from \"./model\";\nimport { t } from \"./i18n\";\n\n// Craft (Unity Alikhan/Craft: recipe cards → contract panel → info popup). The screen is the recipe\n// ladder — \"3 × Common → 1 × Rare\"; a recipe opens its CONTRACT as a popup: the slots to fill, the\n// player's fitting items to tap in (or fill automatically), the ways to pay, what can come out, and\n// \"Craft\". The server rolls the result; it pops out with the reward animation.\n\nexport function makeCraftScreen(features: FeatureRegistry) {\n return function CraftScreen(_: FeatureScreenProps): ReactNode {\n return <Craft features={features} />;\n };\n}\n\nfunction Craft({ features }: { features: FeatureRegistry }): ReactNode {\n const client = useIDosGamesClient();\n const catalog = useCatalog();\n const stagger = useStagger();\n const layout = useGameLayout();\n const [, loaded] = useState(0);\n const section = configSection<CraftSection>(client, \"Craft\");\n useEffect(() => {\n if (!section)\n void client.craft.getDefinitions().then(() => loaded((n) => n + 1));\n void client.user.getUserInventory();\n }, [client, section]);\n const list = recipes(section);\n const types = [...new Set(list.map((r) => r.type))];\n const [tab, setTab] = useState<Recipe[\"type\"]>(\"rarity\");\n const [open, setOpen] = useState<Recipe | null>(null);\n const state = useUserState();\n const owned = ownedCounts(state?.InventoryV2 as never);\n const items = catalog.items as Map<\n string,\n ItemDefinitionView & { CatalogID?: string }\n >;\n\n if (list.length === 0)\n return <EmptyState glyph=\"hammer\" text={t(\"noRecipes\")} />;\n const current = types.includes(tab) ? tab : types[0]!;\n const shown = list.filter((r) => r.type === current);\n\n return (\n <div style={{ display: \"grid\", gap: 14 }}>\n <Tabs\n tabs={types.map((x) => ({\n id: x,\n label: x === \"rarity\" ? t(\"byRarity\") : t(\"byCollection\"),\n }))}\n value={current}\n onChange={setTab}\n />\n <div\n style={{\n display: \"grid\",\n gridTemplateColumns:\n layout === \"phone\"\n ? \"1fr\"\n : \"repeat(auto-fill, minmax(320px, 1fr))\",\n gap: 12,\n }}\n >\n {shown.map((r, i) => {\n const fit = eligibleInputs(r, items, owned).reduce(\n (s, e) => s + e.available,\n 0,\n );\n const ready = fit >= r.count;\n return (\n <Card\n key={r.id}\n highlight={ready}\n onClick={() => setOpen(r)}\n style={{\n display: \"grid\",\n gridTemplateColumns: \"1fr auto 1fr\",\n alignItems: \"center\",\n gap: 10,\n ...stagger(i),\n }}\n >\n <RarityChip rarity={r.input} label={`${r.count} × ${r.input}`} />\n <div className={ready ? \"idos-bounce\" : undefined}>\n <Icon glyph=\"hammer\" size={34} />\n </div>\n <RarityChip rarity={r.output} label={`1 × ${r.output}`} />\n <div\n style={{\n gridColumn: \"1 / -1\",\n display: \"flex\",\n justifyContent: \"space-between\",\n ...outlined,\n fontSize: 12,\n color: v.textDim,\n }}\n >\n <span>\n {t(\"need\")}: {Math.min(fit, r.count)} / {r.count}\n </span>\n <ResourceList lines={r.options[0]?.price ?? []} size={16} />\n </div>\n </Card>\n );\n })}\n </div>\n {open ? (\n <ContractPopup\n recipe={open}\n owned={owned}\n items={items}\n onShop={\n features.get(\"store\") ? () => features.open(\"store\") : undefined\n }\n onClose={() => setOpen(null)}\n />\n ) : null}\n </div>\n );\n}\n\nfunction RarityChip({\n rarity,\n label,\n}: {\n rarity: string;\n label: string;\n}): ReactNode {\n const catalog = useCatalog();\n const color = catalog.rarityColor(rarity);\n return (\n <div style={{ display: \"grid\", justifyItems: \"center\", gap: 4 }}>\n <div\n style={{\n width: 58,\n height: 58,\n borderRadius: 14,\n border: `3px solid ${color}`,\n background: `radial-gradient(circle, ${color}55, ${v.panelDeep} 70%)`,\n display: \"grid\",\n placeItems: \"center\",\n }}\n >\n <Icon glyph=\"box\" size={34} />\n </div>\n <span style={{ ...outlined, fontSize: 12, color }}>{label}</span>\n </div>\n );\n}\n\nfunction ContractPopup({\n recipe,\n owned,\n items,\n onShop,\n onClose,\n}: {\n recipe: Recipe;\n owned: Record<string, number>;\n items: Map<string, ItemDefinitionView & { CatalogID?: string }>;\n onShop?: () => void;\n onClose: () => void;\n}): ReactNode {\n const client = useIDosGamesClient();\n const state = useUserState();\n const celebrate = useCelebrate();\n const toast = useToast();\n const kit = useUiKit();\n const anvil = useRef<HTMLDivElement>(null);\n const eligible = eligibleInputs(recipe, items, owned);\n const [contract, setContract] = useState<string[]>([]);\n const [optionID, setOptionID] = useState(recipe.options[0]?.id ?? \"\");\n const [busy, setBusy] = useState(false);\n const option = recipe.options.find((o) => o.id === optionID);\n const balances = state?.InventoryV2?.VirtualCurrencies as\n Record<string, { Amount?: number }> | undefined;\n const affordable = canAfford(option?.price ?? [], balances);\n\n const craft = async () => {\n setBusy(true);\n const started = Date.now();\n const res = await client.craft.craft(recipe.id, contract, 1, option?.id);\n await new Promise((r) =>\n setTimeout(\n r,\n Math.max(0, (kit.motion.on ? 600 : 0) - (Date.now() - started)),\n ),\n );\n setBusy(false);\n if (!res.ok) return toast(errorText(res.error), \"error\");\n kit.fx.burst(anvil.current);\n setContract([]);\n celebrate(grantedBy(res.data), { title: t(\"crafted\"), sound: \"levelUp\" });\n };\n\n return (\n <Popup\n title={`${t(\"contract\")}: ${recipe.count} × ${recipe.input} → ${recipe.output}`}\n onClose={onClose}\n width={520}\n >\n <div\n ref={anvil}\n style={{\n display: \"flex\",\n flexWrap: \"wrap\",\n gap: 8,\n justifyContent: \"center\",\n animation: busy ? \"idos-shake .35s ease-in-out infinite\" : undefined,\n }}\n >\n {Array.from({ length: recipe.count }, (_, i) => {\n const itemID = contract[i];\n return itemID ? (\n <ItemTile\n key={i}\n itemID={itemID}\n size={56}\n onClick={() => setContract((c) => c.filter((_, j) => j !== i))}\n />\n ) : (\n <div\n key={i}\n style={{\n width: 56,\n height: 56,\n borderRadius: 14,\n border: `3px dashed ${v.panelEdge}`,\n background: v.wellSoft,\n }}\n />\n );\n })}\n </div>\n <SectionTitle\n right={\n <span style={{ display: \"flex\", gap: 6 }}>\n <Button\n size=\"sm\"\n tone=\"blue\"\n onClick={() => setContract(autoFill(recipe, eligible))}\n disabled={eligible.length === 0}\n >\n {t(\"auto\")}\n </Button>\n {contract.length > 0 ? (\n <Button size=\"sm\" tone=\"grey\" onClick={() => setContract([])}>\n {t(\"clear\")}\n </Button>\n ) : null}\n </span>\n }\n >\n <span style={{ fontSize: 15 }}>{t(\"yourItems\")}</span>\n </SectionTitle>\n {eligible.length === 0 ? (\n <EmptyState\n glyph=\"box\"\n text={t(\"noItems\")}\n action={\n onShop ? <Button onClick={onShop}>{t(\"toShop\")}</Button> : undefined\n }\n />\n ) : (\n <div\n style={{\n display: \"flex\",\n flexWrap: \"wrap\",\n gap: 8,\n justifyContent: \"center\",\n }}\n >\n {eligible.map((e) => {\n const used = contract.filter((x) => x === e.itemID).length;\n return (\n <ItemTile\n key={e.itemID}\n itemID={e.itemID}\n count={e.available - used}\n size={64}\n dim={used >= e.available}\n onClick={() =>\n setContract((c) =>\n addToContract(c, e.itemID, recipe, e.available),\n )\n }\n />\n );\n })}\n </div>\n )}\n <Outputs recipe={recipe} items={items} />\n {recipe.options.length > 1 ? (\n <Tabs\n tabs={recipe.options.map((o) => ({\n id: o.id,\n label: o.name ?? o.id,\n }))}\n value={optionID}\n onChange={setOptionID}\n />\n ) : null}\n <Button\n tone=\"gold\"\n size=\"lg\"\n attract={contract.length === recipe.count && affordable}\n disabled={contract.length < recipe.count || !affordable}\n busy={busy}\n onClick={() => void craft()}\n data-tutorial-anchor=\"craft:go\"\n >\n <Icon glyph=\"hammer\" size={22} /> {t(\"craft\")}{\" \"}\n {option && option.price.length > 0 ? (\n <ResourceList\n lines={option.price}\n size={18}\n dimIf={() => !affordable}\n />\n ) : (\n t(\"free\")\n )}\n </Button>\n </Popup>\n );\n}\n\nfunction Outputs({\n recipe,\n items,\n}: {\n recipe: Recipe;\n items: Map<string, ItemDefinitionView & { CatalogID?: string }>;\n}): ReactNode {\n const outputs = possibleOutputs(recipe, items);\n if (outputs.length === 0) return null;\n return (\n <div style={{ display: \"grid\", gap: 6 }}>\n <div style={{ ...outlined, fontSize: 13, color: v.textDim }}>\n {t(\"canYield\")}\n </div>\n <div\n style={{\n display: \"flex\",\n flexWrap: \"wrap\",\n gap: 6,\n justifyContent: \"center\",\n }}\n >\n {outputs.map((id) => (\n <ItemTile key={id} itemID={id} size={48} />\n ))}\n </div>\n </div>\n );\n}\n"
49
48
  },
50
49
  {
51
50
  "path": "i18n.ts",
@@ -65,7 +64,7 @@
65
64
  },
66
65
  {
67
66
  "path": "module.meta.json",
68
- "content": "{\n \"id\": \"craft\",\n \"type\": \"feature\",\n \"inBase\": true,\n \"summary\": \"Craft screen for any game: trade-up recipes by rarity or collection, a contract of owned items, auto-fill, price options and the result popup.\",\n \"description\": \"A ready craft screen (Unity Alikhan/Craft) for ANY game, built on the @idosgames/react/ui kit and client.craft. The screen lists the title's recipes as cards, lowest rarity first: what goes in (N items of a rarity or a collection) and what can come out. A recipe opens as a popup — the contract: the fitting items the player owns (worn equipment does not count), tap to add, 'Auto' fills from the most plentiful, the price options, and 'Craft'. The server rolls the result (only items with a roll Weight > 0 are promised) and the reward popup shows it flying into the inventory. 'Not enough coins' offers to open the shop (ctx.features.open('store')). Registers the 'craft' feature; its badge counts recipes the player can run now. Ships title-seed.json: 3 Common → Rare for coins and 3 Rare → Legendary for gems.\",\n \"provides\": [\n \"craft screen from the title's recipes\",\n \"trade-up by rarity or collection\",\n \"contract popup with owned items\",\n \"auto-fill of the contract\",\n \"price options\",\n \"craft result with reward animation\",\n \"craft badge for runnable recipes\",\n \"demo recipes\"\n ],\n \"tags\": [\"craft\", \"crafting\", \"trade-up\", \"items\", \"ui\", \"screen\", \"economy\"],\n \"author\": {\n \"name\": \"iDos Games\",\n \"url\": \"https://idosgames.com\"\n },\n \"version\": \"0.1.0\"\n}\n"
67
+ "content": "{\n \"id\": \"craft\",\n \"type\": \"feature\",\n \"summary\": \"Craft screen for any game: trade-up recipes by rarity or collection, a contract of owned items, auto-fill, price options and the result popup.\",\n \"description\": \"A ready craft screen (Unity Alikhan/Craft) for ANY game, built on the @idosgames/react/ui kit and client.craft. The screen lists the title's recipes as cards, lowest rarity first: what goes in (N items of a rarity or a collection) and what can come out. A recipe opens as a popup — the contract: the fitting items the player owns (worn equipment does not count), tap to add, 'Auto' fills from the most plentiful, the price options, and 'Craft'. The server rolls the result (only items with a roll Weight > 0 are promised) and the reward popup shows it flying into the inventory. 'Not enough coins' offers to open the shop (ctx.features.open('store')). Registers the 'craft' feature; its badge counts recipes the player can run now. Ships title-seed.json: 3 Common → Rare for coins and 3 Rare → Legendary for gems.\",\n \"provides\": [\n \"craft screen from the title's recipes\",\n \"trade-up by rarity or collection\",\n \"contract popup with owned items\",\n \"auto-fill of the contract\",\n \"price options\",\n \"craft result with reward animation\",\n \"craft badge for runnable recipes\",\n \"demo recipes\"\n ],\n \"tags\": [\"craft\", \"crafting\", \"trade-up\", \"items\", \"ui\", \"screen\", \"economy\"],\n \"author\": {\n \"name\": \"iDos Games\",\n \"url\": \"https://idosgames.com\"\n },\n \"version\": \"0.1.1\"\n}\n"
69
68
  }
70
69
  ]
71
70
  }