feat: chat window: world, tribe and direct conversations, live, with unread counts in the menu

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-30 10:59:07 +01:00
parent 5ad01b9d98
commit 241c2a8f7f
12 changed files with 280 additions and 4 deletions

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,90 @@
<script setup lang="ts">
import type { ChatPush } from '~/types/game'
const props = defineProps<{ worldId: number; tribe: boolean }>()
const chat = useChat()
const { state } = chat
const { t } = useI18n()
const clock = useNow()
watch(() => props.worldId, (id) => chat.enter(id), { immediate: true })
// A tribe joined or left changes the channels.
watch(() => props.tribe, () => chat.enter(props.worldId))
ws.listenWhileMounted<ChatPush>('chat:message', null, (data) => {
if (data?.world_id === props.worldId) chat.receive(data.channel, data.message)
})
const name = (c: { channel: string; with: { name: string } | null }) => (c.with ? c.with.name : t(`chat.channels.${c.channel}`))
const messages = computed(() => state.value.messages[state.value.channel] ?? [])
const draft = ref('')
const someone = ref('')
const talking = ref(false)
const list = ref<HTMLElement | null>(null)
async function send() {
if (draft.value.trim() && (await chat.send(draft.value))) draft.value = ''
}
async function talk() {
if (someone.value.trim() && (await chat.talkTo(someone.value))) {
someone.value = ''
talking.value = false
}
}
// Keep the newest message in view.
watch(
() => messages.value.length,
async () => {
await nextTick()
if (list.value) list.value.scrollTop = list.value.scrollHeight
},
)
watch(() => state.value.open, async (open) => {
await nextTick()
if (open && list.value) list.value.scrollTop = list.value.scrollHeight
})
const time = (iso: string) => formatArrival(Date.parse(iso), clock.value, t)
</script>
<!-- The world's chat in a window over the stage: a tab per channel, the talk, a line to write. -->
<template>
<div v-if="state.open" class="pointer-events-none fixed bottom-16 left-1 z-20 flex h-[26rem] max-h-[70dvh] w-[24rem] max-w-[calc(100vw-0.5rem)] md:bottom-2 md:left-2">
<UiWindow class="w-full" :title="$t('chat.title')" closable drag-key="chat" @close="chat.toggle()">
<div class="flex h-[calc(26rem-2rem)] max-h-[calc(70dvh-2rem)] flex-col text-sm">
<nav class="flex flex-wrap gap-0.5 border-b border-wood-700 bg-parchment-200 p-1" role="tablist">
<button
v-for="c in state.channels"
:key="c.channel"
type="button"
role="tab"
:aria-selected="state.channel === c.channel"
class="inline-flex items-center gap-1 border border-wood-800 px-1.5 py-0.5 font-semibold"
:class="state.channel === c.channel ? 'bg-wood-800 text-gold-400' : 'bg-parchment-300 text-wood-950 hover:bg-parchment-100'"
@click="chat.show(c.channel)"
>
{{ name(c) }}
<span v-if="c.unread" class="font-bold text-blood-700 tabular-nums">({{ c.unread }})</span>
</button>
<button type="button" class="btn btn-ghost px-1.5 py-0.5" :title="$t('chat.talk_to')" @click="talking = !talking">+</button>
</nav>
<form v-if="talking" class="flex gap-1 border-b border-wood-700 p-1" @submit.prevent="talk">
<input v-model="someone" class="input min-w-0 flex-1 py-0.5" :placeholder="$t('chat.player')" />
<button type="submit" class="btn btn-primary py-0.5">{{ $t('chat.open') }}</button>
</form>
<div ref="list" class="scroll-y min-h-0 flex-1 space-y-1 bg-parchment-50 p-1.5">
<button v-if="state.more[state.channel]" type="button" class="btn btn-ghost w-full py-0.5 text-xs" @click="chat.older()">{{ $t('chat.older') }}</button>
<p v-if="!messages.length" class="py-6 text-center text-ink-500">{{ $t('chat.empty') }}</p>
<p v-for="m in messages" :key="m.id" class="break-words">
<span class="font-semibold text-wood-900">{{ m.player.name }}</span>
<span class="ml-1 text-xs text-ink-500 tabular-nums">{{ time(m.at) }}</span>
<span class="block whitespace-pre-line">{{ m.body }}</span>
</p>
</div>
<p v-if="chat.error.value" class="alert m-1" role="alert">{{ chat.error.value }}</p>
<form class="flex gap-1 border-t border-wood-700 p-1" @submit.prevent="send">
<input v-model="draft" class="input min-w-0 flex-1 py-1" maxlength="500" :placeholder="$t('chat.write')" />
<button type="submit" class="btn btn-primary py-1">{{ $t('chat.send') }}</button>
</form>
</div>
</UiWindow>
</div>
</template>

View File

@ -12,6 +12,7 @@ const { user, logout } = useAuth()
const { current } = useCurrentWorld() const { current } = useCurrentWorld()
const { worlds, refresh } = useWorld() const { worlds, refresh } = useWorld()
const unread = useUnreadReports() const unread = useUnreadReports()
const chat = useChat()
const villageContext = useVillageContextOrNull() const villageContext = useVillageContextOrNull()
const villageState = computed(() => villageContext?.village.value ?? null) const villageState = computed(() => villageContext?.village.value ?? null)
const { now } = useServerClock() const { now } = useServerClock()
@ -130,6 +131,18 @@ watch(() => route.fullPath, () => menuKey.value++)
<div class="ml-auto flex items-stretch"> <div class="ml-auto flex items-stretch">
<span v-if="world" class="hidden items-center border-l border-wood-700 px-2.5 text-parchment-300 md:flex">{{ world.name }}</span> <span v-if="world" class="hidden items-center border-l border-wood-700 px-2.5 text-parchment-300 md:flex">{{ world.name }}</span>
<button
v-if="entries.length"
type="button"
class="menu-item border-l"
:class="{ 'menu-item-active': chat.state.value.open }"
:title="t('app.chat')"
@click="chat.toggle()"
>
<IconUi name="chat" class="size-4" />
<span class="hidden sm:inline">{{ t('app.chat') }}</span>
<span v-if="chat.unread.value" class="font-bold text-gold-400 tabular-nums">({{ chat.unread.value }})</span>
</button>
<span v-if="user" class="flex items-center gap-1.5 border-l border-wood-700 px-2.5 tabular-nums text-parchment-200" :title="`${t('app.server_time')} · ${connection.text}`"> <span v-if="user" class="flex items-center gap-1.5 border-l border-wood-700 px-2.5 tabular-nums text-parchment-200" :title="`${t('app.server_time')} · ${connection.text}`">
<span class="size-1.5 rounded-full" :class="connection.tone" /> <span class="size-1.5 rounded-full" :class="connection.tone" />
{{ clock }} {{ clock }}

View File

@ -201,5 +201,6 @@ useShortcuts(() => {
</div> </div>
<GameTabBar :village-id="villageId" /> <GameTabBar :village-id="villageId" />
<QuestBook v-if="v.village.value" /> <QuestBook v-if="v.village.value" />
<GameChat v-if="v.village.value" :world-id="v.village.value.world_id" :tribe="!!v.village.value.tribe.tribe" />
</div> </div>
</template> </template>

View File

@ -19,6 +19,7 @@ export type UiIconName =
| 'home' | 'home'
| 'book' | 'book'
| 'rank' | 'rank'
| 'chat'
defineProps<{ name: UiIconName }>() defineProps<{ name: UiIconName }>()
</script> </script>
@ -81,6 +82,7 @@ defineProps<{ name: UiIconName }>()
<path d="M5 10v10h14V10M10 20v-6h4v6" /> <path d="M5 10v10h14V10M10 20v-6h4v6" />
</g> </g>
<path v-else-if="name === 'edit'" d="M4 20l1-4L16 5l3 3L8 19zM14 7l3 3" /> <path v-else-if="name === 'edit'" d="M4 20l1-4L16 5l3 3L8 19zM14 7l3 3" />
<path v-else-if="name === 'chat'" d="M4 5h16v11H9l-5 4z" />
<g v-else-if="name === 'book'"> <g v-else-if="name === 'book'">
<path d="M4 5a2 2 0 0 1 2-2h13v16H6a2 2 0 0 0-2 2z" /> <path d="M4 5a2 2 0 0 1 2-2h13v16H6a2 2 0 0 0-2 2z" />
<path d="M4 21V5M8 7h7M8 11h5" /> <path d="M4 21V5M8 7h7M8 11h5" />

View File

@ -1,12 +1,14 @@
<script setup lang="ts"> <script setup lang="ts">
import type { RouteLocationRaw } from 'vue-router' import type { RouteLocationRaw } from 'vue-router'
defineProps<{ const props = defineProps<{
title: string title: string
/** Where the close cross leads. */ /** Where the close cross leads. */
closeTo?: RouteLocationRaw closeTo?: RouteLocationRaw
/** A close cross that only emits `close`. */ /** A close cross that only emits `close`. */
closable?: boolean closable?: boolean
/** Windows that stand apart (the chat) keep their own place. */
dragKey?: string
}>() }>()
const emit = defineEmits<{ close: [] }>() const emit = defineEmits<{ close: [] }>()
/** Folded to its title bar, so the village behind shows. */ /** Folded to its title bar, so the village behind shows. */
@ -14,7 +16,7 @@ const folded = defineModel<boolean>('folded', { default: false })
// Its parent docks it; the player can drag it away by the title bar on wide screens, and // Its parent docks it; the player can drag it away by the title bar on wide screens, and
// a double-click there puts it back. One offset for every window, kept per browser. // a double-click there puts it back. One offset for every window, kept per browser.
const offset = useWindowOffset() const offset = useWindowOffset(props.dragKey)
const root = ref<HTMLElement | null>(null) const root = ref<HTMLElement | null>(null)
const wide = ref(false) const wide = ref(false)
let mq: MediaQueryList | undefined let mq: MediaQueryList | undefined

View File

@ -0,0 +1,99 @@
import type { ChatChannel, ChatHistory, ChatMessage } from '~/types/game'
interface ChatState {
worldId: number | null
open: boolean
channel: string
channels: ChatChannel[]
messages: Record<string, ChatMessage[]>
more: Record<string, boolean>
}
/**
* The chat of the current world, shared by the window and the menu's unread count. The
* window (GameChat) listens for `chat:message` while it is mounted.
*/
export function useChat() {
const state = useState<ChatState>('chat', () => ({ worldId: null, open: false, channel: 'world', channels: [], messages: {}, more: {} }))
const error = ref<string | null>(null)
const errorText = useErrorText()
const unread = computed(() => state.value.channels.reduce((n, c) => n + c.unread, 0))
const channelOf = (name: string) => state.value.channels.find((c) => c.channel === name)
async function call<T>(event: string, data: object = {}): Promise<T | null> {
if (!state.value.worldId) return null
error.value = null
try {
return await ws.send<T>(event, { world_id: state.value.worldId, ...data })
} catch (e) {
error.value = errorText(e)
return null
}
}
async function enter(worldId: number) {
if (state.value.worldId !== worldId) state.value = { worldId, open: state.value.open, channel: 'world', channels: [], messages: {}, more: {} }
const channels = await call<ChatChannel[]>('chat.channels')
if (channels) state.value.channels = channels
if (state.value.open) await show(state.value.channel)
}
/** Open a channel: its last messages, read from now on. */
async function show(channel: string) {
state.value.channel = channel
const history = await call<ChatHistory>('chat.history', { channel })
if (!history) return
state.value.messages[channel] = history.messages
state.value.more[channel] = history.more
const c = channelOf(channel)
if (c) c.unread = 0
}
async function older() {
const channel = state.value.channel
const first = state.value.messages[channel]?.[0]
if (!first) return
const history = await call<ChatHistory>('chat.history', { channel, before: first.id })
if (!history) return
state.value.messages[channel] = [...history.messages, ...(state.value.messages[channel] ?? [])]
state.value.more[channel] = history.more
}
async function send(body: string) {
const message = await call<ChatMessage>('chat.send', { channel: state.value.channel, body })
if (message) receive(state.value.channel, message, true)
return !!message
}
/** Start a conversation with a player by name. */
async function talkTo(name: string) {
const channel = await call<ChatChannel>('chat.open', { player: name })
if (!channel) return false
if (!channelOf(channel.channel)) state.value.channels.push(channel)
await show(channel.channel)
return true
}
/** A message arrived (pushed, or our own sent one); shown once, counted unread when not in view. */
function receive(channel: string, message: ChatMessage, own = false) {
const list = (state.value.messages[channel] ??= [])
if (list.some((m) => m.id === message.id)) return
list.push(message)
let c = channelOf(channel)
if (!c) {
c = { channel, with: channel.startsWith('dm:') ? message.player : null, unread: 0 }
state.value.channels.push(c)
}
const seen = state.value.open && state.value.channel === channel
if (seen && !own) call('chat.read', { channel })
else if (!seen && !own) c.unread++
}
async function toggle() {
state.value.open = !state.value.open
if (state.value.open) await show(state.value.channel)
}
return { state, error, unread, enter, show, older, send, talkTo, receive, toggle }
}

View File

@ -159,6 +159,8 @@ interface MockState {
reports?: MockReport[] reports?: MockReport[]
/** Claimed quests per `user:world`. */ /** Claimed quests per `user:world`. */
quests?: Record<string, string[]> quests?: Record<string, string[]>
/** Chat messages; the mock has no other players, so only the player's own talk. */
chat?: { id: number; world_id: number; channel: string; user_id: number; body: string; at: number }[]
/** Tribes, each led by the one user who founded it: the mock has no other players. */ /** Tribes, each led by the one user who founded it: the mock has no other players. */
tribes?: { id: number; world_id: number; user_id: number; name: string; tag: string; description: string | null; events: { type: string; payload: Record<string, any>; at: string }[] }[] tribes?: { id: number; world_id: number; user_id: number; name: string; tag: string; description: string | null; events: { type: string; payload: Record<string, any>; at: string }[] }[]
} }
@ -1431,6 +1433,26 @@ const handlers: Record<string, Handler> = {
return { book: questBook(state, v), village: view(state, v, now) } return { book: questBook(state, v), village: view(state, v, now) }
}, },
'chat.channels': (state, user, data) => [
{ channel: 'world', with: null, unread: 0 },
...(mockTribe(state, user.id, Number(data.world_id)) ? [{ channel: 'tribe', with: null, unread: 0 }] : []),
],
'chat.history': (state, user, data) => ({
channel: String(data.channel),
messages: (state.chat ?? [])
.filter((m) => m.world_id === Number(data.world_id) && m.channel === String(data.channel))
.map((m) => ({ id: m.id, player: { id: m.user_id, name: user.name }, body: m.body, at: iso(m.at) })),
more: false,
}),
'chat.read': (_state, _user, data) => ({ channel: String(data.channel), unread: 0 }),
'chat.open': () => fail('no_player'),
'chat.send': (state, user, data) => {
const body = String(data.body ?? '').trim()
if (!body || body.length > 500) fail('chat_length')
const m = { id: nextId(state), world_id: Number(data.world_id), channel: String(data.channel), user_id: user.id, body, at: Date.now() }
;(state.chat ??= []).push(m)
return { id: m.id, player: { id: user.id, name: user.name }, body, at: iso(m.at) }
},
'tribe.show': (state, user, data) => tribePage(state, user.id, Number(data.world_id)), 'tribe.show': (state, user, data) => tribePage(state, user.id, Number(data.world_id)),
'tribe.list': (state, user, data) => 'tribe.list': (state, user, data) =>
(state.tribes ?? []) (state.tribes ?? [])

View File

@ -330,6 +330,32 @@ export interface TribePage {
notice_seconds: number notice_seconds: number
} }
/** A chat channel as the player names it: world, tribe, or dm:<player id>. */
export interface ChatChannel {
channel: string
/** The other player of a direct conversation. */
with: { id: number; name: string } | null
unread: number
}
export interface ChatMessage {
id: number
player: { id: number; name: string }
body: string
at: string
}
/** `chat.history`: oldest first; more when older ones exist. */
export interface ChatHistory {
channel: string
messages: ChatMessage[]
more: boolean
}
/** Push `chat:message` to everyone who reads the channel. */
export interface ChatPush {
world_id: number
channel: string
message: ChatMessage
}
/** `tribe.list`: every tribe of the world, strongest first. */ /** `tribe.list`: every tribe of the world, strongest first. */
export interface TribeListRow extends TribeRef { export interface TribeListRow extends TribeRef {
members: number members: number

View File

@ -9,6 +9,7 @@ export default {
reports: 'Reports', reports: 'Reports',
ranking: 'Ranking', ranking: 'Ranking',
tribe: 'Tribe', tribe: 'Tribe',
chat: 'Chat',
unread_reports: '{count} unread reports', unread_reports: '{count} unread reports',
village: 'Village', village: 'Village',
change_world: 'Change world', change_world: 'Change world',
@ -84,6 +85,8 @@ export default {
pact_active: 'A pact holds: end it first.', pact_active: 'A pact holds: end it first.',
already_member: 'Already in your tribe.', already_member: 'Already in your tribe.',
no_tribe: 'You are not in a tribe.', no_tribe: 'You are not in a tribe.',
chat_length: 'Messages are 1 to 500 characters.',
chat_slow: 'Slow down a little.',
no_space: 'Not enough building space.', no_space: 'Not enough building space.',
max_per_village: 'Only one of these per village.', max_per_village: 'Only one of these per village.',
max_level: 'Already at max level.', max_level: 'Already at max level.',

View File

@ -2,6 +2,7 @@ import { mergeMessages } from '@blax-software/i18n'
import networking from '@blax-software/networking/i18n' import networking from '@blax-software/networking/i18n'
import en from './locales/en' import en from './locales/en'
import auth from './pages/auth' import auth from './pages/auth'
import chat from './pages/chat'
import map from './pages/map' import map from './pages/map'
import quests from './pages/quests' import quests from './pages/quests'
import ranking from './pages/ranking' import ranking from './pages/ranking'
@ -12,6 +13,6 @@ import worlds from './pages/worlds'
// Explicit imports instead of import.meta.glob: @nuxtjs/i18n also loads this file in the // Explicit imports instead of import.meta.glob: @nuxtjs/i18n also loads this file in the
// Nitro build, where glob imports don't exist. Add new page files here, in path order. // Nitro build, where glob imports don't exist. Add new page files here, in path order.
export default mergeMessages({ en }, [auth, map, quests, ranking, reports, tribe, village, worlds], { packages: [networking] }) as { export default mergeMessages({ en }, [auth, chat, map, quests, ranking, reports, tribe, village, worlds], { packages: [networking] }) as {
en: Record<string, any> en: Record<string, any>
} }

17
i18n/pages/chat.ts Normal file
View File

@ -0,0 +1,17 @@
import type { TranslationFile } from '@blax-software/i18n'
export default {
en: {
chat: {
title: 'Chat',
channels: { world: 'World', tribe: 'Tribe' },
talk_to: 'Talk to a player',
player: 'Player name',
open: 'Open',
older: 'Older messages',
empty: 'Nothing said here yet.',
write: 'Write a message',
send: 'Send',
},
},
} satisfies TranslationFile