Jakub Zych 764cb42894 refactor: the DM-only conversation-actions rule as a helper
dmActionsTarget (app/lib/slots.ts) answers the open DM's row or null;
ChatHeader renders the slot from it. Same behaviour, testable outside a
component.
2026-11-01 19:17:42 +01:00
2026-10-31 14:09:09 +01:00

vue-chat-layer

A Nuxt layer with the member chat of the SummerCMS chat plugins: channels, direct messages, threads, mentions, reactions, typing, unread counts, attachments, pins, link cards and slash commands, live over the site's one Centrifuge connection.

export default defineNuxtConfig({ extends: ['vue-chat-layer'] })

Overview

The chat plugins answer JSON and publish realtime events:

  • golem15.chat (/_chat/api/v1): conversations, messages, replies, reactions, attachments, read marks and typing;
  • golem15.chatchannels (/_chatchannels/api/v1): joining and leaving channels, pins;
  • golem15.chatbots (/_chatbots/api/v1): the slash command catalog and dispatch.

The host application decides who belongs to its community and which channels exist. It answers a small bootstrap (see "Host bootstrap contract"), and the layer does the rest: <ChatPage> is the full chat (a sidebar with channels and DMs, the open conversation, a thread pane), and <ChatFloatingPanel> is a corner button with an unread badge that opens the user's DMs on any page.

Members join and leave the channels the host has; the layer has no channel creation UI. Every message, name and file name is rendered as text, except a message body, which goes through an escape-first inline renderer (code, bold, italic, links and mentions only).

Installation

Add the layer as a git dependency pinned to a tag, next to the Nuxt and Vue versions it is built for:

{
  "dependencies": {
    "nuxt": "4.4.8",
    "vue": "3.5.35",
    "vue-chat-layer": "git+https://git.golem15.com/golem15/vue-chat-layer.git#v0.1.0"
  }
}
// nuxt.config.ts
export default defineNuxtConfig({
  extends: ['vue-chat-layer'],
  runtimeConfig: {
    public: {
      chat: { hostApiBase: '/_acme/api/v1' },
    },
  },
  i18n: {
    defaultLocale: 'en',
    locales: [{ code: 'en', language: 'en-US' }, { code: 'pl', language: 'pl-PL' }],
  },
})

The layer declares @nuxtjs/i18n (10.4.0) and centrifuge (5.7.3), so the app does not list @nuxtjs/i18n again. It registers its chat.* copy only for the locales the app enables (en, pl). The browser calls every API on the site's own origin: route /_chat, /_chatchannels, /_chatbots, the host bootstrap, /api/realtime/token and the /ws WebSocket to the application (a dev proxy locally, the web server in production).

Runtime config

Key Env Default Purpose
chat.apiBase NUXT_CHAT_API_BASE http://127.0.0.1:8096/_chat/api/v1 Server-only chat API base, for an app page that fetches chat data on the server
public.chat.apiBase NUXT_PUBLIC_CHAT_API_BASE /_chat/api/v1 Browser base of golem15.chat
public.chat.channelsApiBase NUXT_PUBLIC_CHAT_CHANNELS_API_BASE /_chatchannels/api/v1 Browser base of golem15.chatchannels
public.chat.botsApiBase NUXT_PUBLIC_CHAT_BOTS_API_BASE /_chatbots/api/v1 Browser base of golem15.chatbots
public.chat.hostApiBase NUXT_PUBLIC_CHAT_HOST_API_BASE '' Base of the host bootstrap; the chat does not start without it (a console error names the key)

Usage

The chat components use window, the DOM and a WebSocket, so render them on the client only:

<!-- pages/chat.vue -->
<template>
  <ClientOnly v-if="loggedIn"><ChatPage /></ClientOnly>
  <NuxtLink v-else to="/register">Register to chat</NuxtLink>
</template>
<!-- layouts/default.vue: the floating panel on every page but the chat itself -->
<ClientOnly>
  <ChatFloatingPanel v-if="loggedIn && route.path !== '/chat'" chat-path="/chat" />
</ClientOnly>

Both start the chat store themselves. The page owns its route, its copy and what anonymous visitors see; the layer renders nothing for a visitor without a token.

The auth hook

The app provides chatAuth from a Nuxt plugin. The layer calls it whenever it sends a request, also outside a component's setup, so read the token from a source that works there (document.cookie, a store), not from useCookie:

// plugins/chat-auth.ts
export default defineNuxtPlugin(() => ({
  provide: {
    chatAuth: {
      // The user's frontend JWT, or null.
      token: () => readTokenCookie(),
      // Renews the token and answers the new one, or null.
      refresh: async () => {
        const res = await $fetch<{ token?: string }>('/_user/api/v1/refresh', {
          method: 'POST',
          headers: { Authorization: `Bearer ${readTokenCookie()}` },
        }).catch(() => null)
        if (res?.token) writeTokenCookie(res.token)
        return res?.token ?? null
      },
      // The session cannot be renewed.
      unauthorized: () => writeTokenCookie(null),
    },
  },
}))

Every request carries Authorization: Bearer {token()}. A 401 refreshes once and retries; a second 401, or a refresh without a token, calls unauthorized(). The layer never stores the token. The caller's user id comes from chatAuth.userId() when the hook has it, else from the token's numeric sub claim.

Host bootstrap contract

The host answers two routes under public.chat.hostApiBase, both behind its user JWT:

GET {hostApiBase}/chat — who the caller is in the community:

{
  "member": true,
  "moderator": false,
  "context": { "type": "acme", "id": 1 },
  "channels": [
    { "id": 3, "slug": "general", "name": "general", "conversation_id": 12, "joined": true, "unread": 2, "mentions": 0 }
  ],
  "conversations": [
    {
      "id": 40,
      "type": "dm",
      "other_user_id": 7,
      "unread": 1,
      "last_message": { "id": 901, "sender_id": 7, "content": "Hi!", "created_at": "2026-10-31T09:12:00Z" }
    }
  ],
  "limits": { "max_files": 5, "max_bytes": 5242880, "max_embeds": 3 }
}

A user outside the community gets {"member": false} and the chat shows a short note. context is the golem15.chat context DMs are created in (POST /_chat/api/v1/contexts/{type}/{id}/dm) and the golem15.chatchannels context of the channels. moderator lets the user delete other people's messages in channels (never in DMs); the server enforces the same rule. channels are the community's public channels: joined is false for a channel the user left. Opening a channel calls GET /_chat/api/v1/contexts/channel/{id}/conversation, which makes the user a participant. max_embeds caps the link cards of one message.

GET {hostApiBase}/chat/members — the other members, for the DM picker and mentions:

{ "members": [{ "id": 7, "name": "Ada", "surname": "Hart", "handle": "ada", "is_bot": false }] }

Realtime

app/lib/realtime.ts is the page's one Centrifuge client. The chat holds user:{me} for the whole session and the open conversation's chat:conversation:{id}; any other code on the page subscribes through the same client:

import { onUserEvent, openChannel, setRealtimeAuth, subscribe } from 'vue-chat-layer/app/lib/realtime'
  • setRealtimeAuth(getToken, refresh?): the bearer of the token route GET /api/realtime/token. The chat store sets it from $chatAuth when the app has not.
  • subscribe(channel, hooks), presence(channel), openChannel(channel, hooks), connect(), disconnect(), onConnection(listener), onUnavailable(listener).
  • onUserEvent(handler): hears the user:{me} publications the chat does not handle (a call layer's video:* events, for example). Never subscribe to user:{me} a second time.

A 401, 403 or 404 from the token route ends realtime for the session; the chat then polls the open conversation every 15 seconds and the counts every 60 seconds.

Slots

  • ChatPage and ChatPanel: conversation-actions with { conversation }, rendered in the conversation header only for a DM (a call button, for example).
  • ChatPage and ChatChannelList: sidebar-footer, below the channel list.
  • ChatFloatingPanel: conversation-actions, in the header of the open DM.

A message with an http(s) URL shows a card with the URL's host and path (ChatLinkEmbed); nothing is fetched. A host renders its own links with a registered component, which gets the URL as the url prop:

// plugins/chat-embeds.client.ts
import { registerEmbedRenderer } from 'vue-chat-layer/app/lib/linkEmbeds'
import PostCard from '~/components/PostCard.vue'

export default defineNuxtPlugin(() => {
  registerEmbedRenderer((url) => url.origin === location.origin && url.pathname.startsWith('/blog/'), PostCard)
})

linkify(escapedHtml) (same module) turns the URLs of already-escaped text into links, and embedRendererFor(url) answers the registered component of a URL.

Slash commands

Typing / at the start of the composer opens the commands of GET {botsApiBase}/commands. Picking one, or sending any text that starts with /, calls POST {botsApiBase}/dispatch with {input} instead of posting a message. The answer shows under the conversation as a row only the sender sees, dismissable; an unknown command shows the refusal.

Components

Component Purpose
ChatPage The full chat: sidebar, conversation, thread pane, new-message dialog
ChatFloatingPanel Corner button with the unread badge (DMs plus mentions); opens the DMs; props chatPath (default /chat)
ChatChannelList, ChatDmList The sidebar lists
ChatPanel, ChatHeader, ChatMessageList, ChatMessage, ChatComposer The open conversation
ChatThreadPane, ChatPinsPanel A thread with its replies; a channel's pins
ChatReactionBar, ChatStagingChips, ChatDeleteDialog, ChatMemberPicker, ChatMentionPopup, ChatCommandPicker, ChatLinkEmbed Parts of the above
ChatAvatar, ChatIcon, ChatNotices Initials avatar, stroke icons, short notices

Composables: useChat() (the store, one per app, state in useState keys prefixed chat:), useChatApi() (the HTTP client bound to runtime config and the hook), useChatNotice(). The pure modules in app/lib/ are imported explicitly, never auto-imported: client.ts (createChatClient, ChatApiError, userIdFromToken), realtime.ts, linkEmbeds.ts, chatEvents.ts, chatFormat.ts, chatText.ts, chatUnread.ts, format.ts, attachments.ts.

Tokens

app/assets/css/chat-tokens.css holds every colour, size and space of the components as --chat-* custom properties, and chat-base.css the neutral rules (every selector starts with .chat-). Override tokens after the layer's CSS:

:root:root {
  --chat-color-accent: #1d2940;
  --chat-height: 70vh;
}

Copy

Every string is under chat.* in i18n/locales/en.json and pl.json. An app overrides any key in its own messages.

Development

pnpm install
pnpm dev                 # the playground (.playground) on a local application
pnpm build:playground

Testing

pnpm test                # vitest: the HTTP client (tests/smoke.test.ts)

The consuming application covers the components with browser checks.

Description
Nuxt layer: member chat for the SummerCMS chat plugins
Readme 270 KiB
Languages
TypeScript 67.3%
Vue 25%
CSS 7.7%