feat: threads, pins, reactions, attachments, link embeds and the command picker

- threads: reply counts, ChatThreadPane with replies, live replies and thread mute
- channel pins in ChatPinsPanel; a refused pin hides the action for the session
- reactions, attachments with upload progress and bearer downloads, inline edits, the delete dialog (moderators also in channels)
- link cards with the registerEmbedRenderer registry; linkify for escaped text
- slash commands: the command picker over chatbots, dispatch with sender-only answers
- slots conversation-actions (DMs only) and sidebar-footer
- chat-tokens.css and chat-base.css, EN and PL copy, README
This commit is contained in:
Jakub Zych
2026-10-31 14:04:54 +01:00
parent 5d581539b3
commit 269c75b5dd
23 changed files with 3625 additions and 43 deletions

231
README.md Normal file
View File

@@ -0,0 +1,231 @@
# 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.
```ts
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:
```json
{
"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"
}
}
```
```ts
// 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:
```vue
<!-- pages/chat.vue -->
<template>
<ClientOnly v-if="loggedIn"><ChatPage /></ClientOnly>
<NuxtLink v-else to="/register">Register to chat</NuxtLink>
</template>
```
```vue
<!-- 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`:
```ts
// 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:
```json
{
"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:
```json
{ "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:
```ts
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.
### Link cards
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:
```ts
// 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:
```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
```sh
pnpm install
pnpm dev # the playground (.playground) on a local application
pnpm build:playground
```
## Testing
```sh
pnpm test # vitest: the HTTP client (tests/smoke.test.ts)
```
The consuming application covers the components with browser checks.

1255
app/assets/css/chat-base.css Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,65 @@
/*
* vue-chat-layer design tokens. Every visual value of the Chat* components
* reads one of these; an app overrides any of them on :root:root (or a
* narrower selector) after the layer's CSS. The defaults are a neutral
* palette.
*/
:root {
/* colour */
--chat-color-text: #1f2328;
--chat-color-muted: #59636e;
--chat-color-bg: #ffffff;
--chat-color-surface: #f6f8fa;
--chat-color-hover: #eef1f4;
--chat-color-border: #d1d9e0;
--chat-color-accent: #0969da;
--chat-color-on-accent: #ffffff;
--chat-color-accent-soft: #ddf4ff;
--chat-color-mention: #fff8c5;
--chat-color-danger: #cf222e;
--chat-color-success: #1a7f37;
--chat-color-backdrop: rgba(31, 35, 40, 0.4);
/* avatar palette */
--chat-av-1: #b35900;
--chat-av-2: #0969da;
--chat-av-3: #1a7f37;
--chat-av-4: #8250df;
--chat-av-5: #bf3989;
--chat-av-6: #0a7480;
--chat-av-7: #9a6700;
--chat-av-8: #cf222e;
--chat-av-text: #ffffff;
/* type */
--chat-font: inherit;
--chat-font-size-sm: 0.8125rem;
--chat-font-size: 0.9375rem;
--chat-font-size-lg: 1.0625rem;
--chat-line-height: 1.5;
/* spacing */
--chat-space-1: 0.25rem;
--chat-space-2: 0.5rem;
--chat-space-3: 0.75rem;
--chat-space-4: 1rem;
--chat-space-5: 1.5rem;
/* radii */
--chat-radius: 6px;
--chat-radius-card: 10px;
--chat-radius-pill: 999px;
/* layout */
--chat-height: min(78vh, 48rem);
--chat-sidebar: 16rem;
--chat-side: 22rem;
--chat-target: 2.25rem;
--chat-floating-width: 22rem;
--chat-floating-height: min(70vh, 34rem);
--chat-floating-offset: 1.25rem;
--chat-z-floating: 60;
/* shadow (popovers, dialogs, the floating panel) */
--chat-shadow: 0 8px 24px rgba(31, 35, 40, 0.12);
}

View File

@@ -0,0 +1,35 @@
<script setup lang="ts">
// The slash command list of the composer (golem15.chatbots): the commands
// whose trigger starts with what follows the "/" at the start of the
// composer. Like the mention list, the textarea keeps focus and points at
// the active option through aria-activedescendant; picking (mousedown, or
// Enter and Tab in the composer) runs the command through the chatbots
// dispatch route, so the answer is shown to the sender only.
import type { ChatCommand } from '../../lib/types'
defineProps<{ id: string; options: ChatCommand[]; active: number; query: string; loading: boolean }>()
const emit = defineEmits<{ pick: [command: ChatCommand]; hover: [index: number] }>()
const { t } = useI18n()
</script>
<template>
<ul :id="id" class="chat-pop chat-command-pop" role="listbox" :aria-label="t('chat.commands.label')">
<li v-if="loading" class="chat-pop-empty" role="option" aria-disabled="true" aria-selected="false">{{ t('chat.loading') }}</li>
<li v-else-if="!options.length" class="chat-pop-empty" role="option" aria-disabled="true" aria-selected="false">{{ t('chat.commands.none', { q: query }) }}</li>
<li
v-for="(c, i) in options"
:id="`${id}-opt-${i}`"
:key="c.trigger"
class="chat-pop-option"
:class="{ 'is-active': i === active }"
role="option"
:aria-selected="i === active ? 'true' : 'false'"
:data-command="c.trigger"
@mousedown.prevent="emit('pick', c)"
@mousemove="i !== active && emit('hover', i)"
>
<span class="chat-pop-name">/{{ c.trigger }}</span>
<span class="chat-pop-meta">{{ c.description }}</span>
</li>
</ul>
</template>

View File

@@ -6,9 +6,19 @@
// Mentions: an @ at a word start (or the @ button) opens a WAI-ARIA 1.2
// combobox on the textarea. While its list is open, Enter and Tab pick and
// never send.
import type { ChatMember } from '../../lib/types'
//
// Slash commands: a "/" at the start of the text opens the command list
// (golem15.chatbots' catalog, loaded once a session) filtered by what
// follows it. Picking one runs it; sending any text that starts with "/"
// runs it too (the store dispatches it instead of posting it). The answer
// shows under the conversation, to the sender only.
//
// Attachments: the paperclip picks files, which upload at once with
// progress; the send waits for them.
import type { ChatCommand, ChatMember } from '../../lib/types'
import { filterMembers } from '../../lib/chatFormat'
import { insertMention, mentionQuery, type MentionQuery } from '../../lib/chatText'
import type { FileCheckMessages } from '../../lib/attachments'
const props = defineProps<{ conversationId: number; label: string; placeholder: string }>()
const emit = defineEmits<{ sent: [] }>()
@@ -19,6 +29,7 @@ const uid = useId()
const fieldId = `chat-composer-${uid}`
const hintId = `chat-composer-hint-${uid}`
const listId = `chat-mentions-${uid}`
const commandListId = `chat-commands-${uid}`
const input = ref<HTMLTextAreaElement | null>(null)
const draft = computed(() => chat.draft(props.conversationId))
@@ -39,6 +50,86 @@ const text = computed({
})
const canSend = computed(() => chat.canSend(props.conversationId))
const fileInput = ref<HTMLInputElement | null>(null)
const fileMessages: FileCheckMessages = {
tooLarge: (name, mb) => t('chat.files.tooLarge', { name, mb }),
overTotal: (mb) => t('chat.files.overTotal', { mb }),
banned: () => t('chat.files.banned'),
tooMany: (max) => t('chat.files.tooMany', { n: max }),
}
function pickFiles() {
if (draft.value.sending) return
fileInput.value?.click()
}
function onFiles() {
const el = fileInput.value
if (!el?.files?.length) return
chat.uploadFiles(props.conversationId, [...el.files], fileMessages)
// The same file can be picked again after a removal.
el.value = ''
void nextTick(focus)
}
/** The command query: what follows a "/" at the start of the text, until a space. */
const commandQuery = computed(() => {
const m = /^\/(\S*)$/.exec(text.value)
return m ? m[1] : null
})
const commandActive = ref(0)
const commandDismissed = ref(false)
const commandOptions = computed<ChatCommand[]>(() => {
const q = commandQuery.value
if (q === null) return []
const lower = q.toLowerCase()
return (chat.commands ?? []).filter((c) => c.trigger.toLowerCase().startsWith(lower))
})
const commandOpen = computed(() => commandQuery.value !== null && !commandDismissed.value)
watch(commandQuery, (q, old) => {
if (q === null) {
commandDismissed.value = false
return
}
if (old === null) void chat.loadCommands()
if (q !== old) commandActive.value = 0
})
async function pickCommand(c: ChatCommand) {
commandDismissed.value = false
if (await chat.runCommand(props.conversationId, `/${c.trigger}`)) {
chat.setDraftText(props.conversationId, '')
emit('sent')
}
void nextTick(focus)
}
function commandKey(e: KeyboardEvent): boolean {
if (!commandOpen.value) return false
const n = commandOptions.value.length
switch (e.key) {
case 'ArrowDown':
if (n) commandActive.value = (commandActive.value + 1) % n
return true
case 'ArrowUp':
if (n) commandActive.value = (commandActive.value - 1 + n) % n
return true
case 'Enter':
case 'Tab':
if (!n || e.shiftKey) return false
void pickCommand(commandOptions.value[commandActive.value])
return true
case 'Escape':
e.stopPropagation()
commandDismissed.value = true
return true
default:
return false
}
}
const LINE = 24
function grow() {
@@ -67,7 +158,10 @@ const mentionOptions = computed<ChatMember[]>(() =>
)
/** Without a member list there is no popup; a typed @handle still works on the server. */
const mentionOpen = computed(() => mention.value !== null && chat.membersState === 'ready')
const activeDescendant = computed(() => (mentionOpen.value && mentionOptions.value.length ? `${listId}-opt-${mentionActive.value}` : undefined))
const activeDescendant = computed(() => {
if (commandOpen.value && commandOptions.value.length) return `${commandListId}-opt-${commandActive.value}`
return mentionOpen.value && mentionOptions.value.length ? `${listId}-opt-${mentionActive.value}` : undefined
})
function updateMention() {
const el = input.value
@@ -167,7 +261,7 @@ async function submit() {
function onKeydown(e: KeyboardEvent) {
if (e.isComposing) return
if (mentionKey(e)) {
if (commandKey(e) || mentionKey(e)) {
e.preventDefault()
return
}
@@ -191,7 +285,18 @@ defineExpose({ focus })
<form class="chat-composer" @submit.prevent="submit">
<label class="chat-sr" :for="fieldId">{{ label }}</label>
<p v-if="errorLine" class="chat-error" role="alert">{{ errorLine }}</p>
<ChatStagingChips :conversation-id="conversationId" @removed="focus" />
<div class="chat-composer-field">
<ChatCommandPicker
v-if="commandOpen && commandQuery !== null"
:id="commandListId"
:options="commandOptions"
:active="commandActive"
:query="commandQuery"
:loading="chat.commands === null"
@pick="pickCommand"
@hover="commandActive = $event"
/>
<ChatMentionPopup
v-if="mentionOpen && mention"
:id="listId"
@@ -213,8 +318,8 @@ defineExpose({ focus })
role="combobox"
aria-autocomplete="list"
aria-haspopup="listbox"
:aria-controls="listId"
:aria-expanded="mentionOpen ? 'true' : 'false'"
:aria-controls="commandOpen ? commandListId : listId"
:aria-expanded="mentionOpen || commandOpen ? 'true' : 'false'"
:aria-activedescendant="activeDescendant"
@keydown="onKeydown"
@keyup="onKeyup"
@@ -223,6 +328,9 @@ defineExpose({ focus })
@blur="mention = null"
></textarea>
<div class="chat-composer-tools">
<button class="chat-icon-btn" type="button" :aria-label="t('chat.files.attach')" :title="t('chat.files.attach')" :disabled="draft.sending" @click="pickFiles">
<ChatIcon name="paperclip" />
</button>
<button class="chat-icon-btn" type="button" :aria-label="t('chat.composer.mention')" :title="t('chat.composer.mention')" :disabled="draft.sending" @click="startMention">
<ChatIcon name="at" />
</button>
@@ -233,5 +341,6 @@ defineExpose({ focus })
</div>
</div>
<span :id="hintId" class="chat-sr">{{ t('chat.composer.hint') }}</span>
<input ref="fileInput" class="chat-sr" type="file" multiple tabindex="-1" aria-hidden="true" @change="onFiles" />
</form>
</template>

View File

@@ -0,0 +1,94 @@
<script setup lang="ts">
// "Delete message?": the one confirmation of the chat. A native
// modal dialog; the keep button gets the initial focus, Esc and the
// backdrop cancel, and a failed delete keeps it open with the error line.
// One instance per message list; focus goes back to the opener, or to the
// list when the opener left with the deleted message.
import type { ChatMessage } from '../../lib/types'
import { shortName } from '../../lib/chatFormat'
const { t } = useI18n()
const chat = useChat()
const uid = useId()
const dialog = ref<HTMLDialogElement | null>(null)
const keepBtn = ref<HTMLButtonElement | null>(null)
const target = ref<ChatMessage | null>(null)
const busy = ref(false)
const error = ref('')
let opener: HTMLElement | null = null
let list: HTMLElement | null = null
const own = computed(() => !!target.value && target.value.sender_id === chat.userId)
const body = computed(() => {
const m = target.value
if (!m || own.value) return t('chat.delete.own')
return t('chat.delete.other', { name: shortName(chat.members.get(m.sender_id), m.sender_name, t('chat.someone')) })
})
function open(message: ChatMessage, from?: HTMLElement | null) {
target.value = message
error.value = ''
busy.value = false
opener = from ?? (document.activeElement instanceof HTMLElement ? document.activeElement : null)
list = opener?.closest<HTMLElement>('.chat-list, .chat-thread-list') ?? null
dialog.value?.showModal()
void nextTick(() => keepBtn.value?.focus())
}
function close() {
dialog.value?.close()
}
function onCancel(e: Event) {
// Esc while the delete is in flight waits for the answer.
if (busy.value) e.preventDefault()
}
function onClose() {
if (opener?.isConnected) opener.focus()
else list?.focus()
opener = null
list = null
target.value = null
}
function onBackdrop(e: MouseEvent) {
if (e.target === dialog.value && !busy.value) close()
}
async function confirm() {
const m = target.value
if (!m || busy.value) return
busy.value = true
error.value = ''
const failed = await chat.remove(m)
busy.value = false
if (failed) {
error.value = t(`chat.${failed}`)
return
}
close()
}
defineExpose({ open })
</script>
<template>
<dialog
ref="dialog"
class="chat-dialog chat-confirm"
:aria-labelledby="`chat-delete-h-${uid}`"
:aria-describedby="`chat-delete-b-${uid}`"
@cancel="onCancel"
@close="onClose"
@click="onBackdrop"
>
<h2 :id="`chat-delete-h-${uid}`" class="chat-dialog-title">{{ t('chat.delete.title') }}</h2>
<p :id="`chat-delete-b-${uid}`" class="chat-confirm-body">{{ body }}</p>
<p v-if="error" class="chat-error" role="alert">{{ error }}</p>
<div class="chat-btn-row">
<button class="chat-btn chat-btn--danger" type="button" :aria-busy="busy ? 'true' : undefined" :disabled="busy" @click="confirm">{{ t('chat.delete.confirm') }}</button>
<button ref="keepBtn" class="chat-btn chat-btn--ghost" type="button" :disabled="busy" @click="close">{{ t('chat.delete.keep') }}</button>
</div>
</dialog>
</template>

View File

@@ -1,19 +1,25 @@
<script setup lang="ts">
// The open conversation's name, presence (channels) or online dot (DMs),
// the back button of narrow layouts (with the unread count of everything
// else) and the channel's leave action. Under it, the connection strip
// shows whenever realtime is not connected. Presence is not announced to
// screen readers.
// else), the channel's pins and leave actions and, for DMs only, the
// conversation-actions slot (a call button, for example). Under it, the
// connection strip shows whenever realtime is not connected. Presence is
// not announced to screen readers.
//
// Slot conversation-actions: { conversation } (the open DM's row), rendered
// only when the open conversation is a DM.
import { badgeText } from '../../lib/chatUnread'
import { shortName } from '../../lib/chatFormat'
const props = withDefaults(defineProps<{ back?: boolean }>(), { back: true })
const emit = defineEmits<{ back: [] }>()
const props = withDefaults(defineProps<{ back?: boolean; pinsOpen?: boolean }>(), { back: true, pinsOpen: false })
const emit = defineEmits<{ back: []; pins: [] }>()
const { t } = useI18n()
const chat = useChat()
const channel = computed(() => chat.activeChannel)
const dm = computed(() => chat.activeDm)
/** The open conversation's kind and row, for the DM-only slot. */
const conversation = computed(() => dm.value ?? null)
const dmName = computed(() => (dm.value ? shortName(chat.members.get(dm.value.other_user_id), '', t('chat.someone')) : ''))
const title = computed(() => (channel.value ? `# ${channel.value.name}` : dmName.value))
const eyebrow = computed(() => (channel.value ? t('chat.header.channel') : t('chat.header.dm')))
@@ -84,6 +90,18 @@ async function leave() {
</template>
</div>
<div class="chat-head-actions">
<slot v-if="conversation && conversation.type === 'dm'" name="conversation-actions" :conversation="conversation" />
<button
v-if="channel"
class="chat-icon-btn"
type="button"
:aria-pressed="pinsOpen ? 'true' : 'false'"
:aria-label="t('chat.pins.title')"
:title="t('chat.pins.title')"
@click="emit('pins')"
>
<ChatIcon name="pin" />
</button>
<button v-if="channel" class="chat-icon-btn" type="button" :aria-label="t('chat.header.leave')" :title="t('chat.header.leave')" :disabled="leaving" @click="leave">
<ChatIcon name="out" />
</button>

View File

@@ -0,0 +1,21 @@
<script setup lang="ts">
// The generic link card: the URL's host and path, nothing fetched. It opens
// in a new tab without an opener or referrer.
const props = defineProps<{ url: URL }>()
const { t } = useI18n()
const path = computed(() => {
const p = `${props.url.pathname}${props.url.search}`
return p === '/' ? '' : p
})
</script>
<template>
<a class="chat-embed" :href="url.href" target="_blank" rel="noopener noreferrer nofollow">
<ChatIcon name="link" />
<span class="chat-embed-main">
<span class="chat-embed-host">{{ url.host }}</span>
<span v-if="path" class="chat-embed-path">{{ path }}</span>
</span>
<span class="chat-sr">{{ t('chat.embed.opens') }}</span>
</a>
</template>

View File

@@ -1,16 +1,43 @@
<script lang="ts">
import { ref } from 'vue'
/** On touch (hover: none) one message at a time shows its action bar. */
const actionsOpenId = ref<number | null>(null)
</script>
<script setup lang="ts">
// One message, left-aligned with the author's initials. The body goes
// through renderChatText only (escape-first inline markdown, autolinks and
// member mentions); it is the only HTML binding of the layer. Names and
// every other field are text bindings.
import type { ChatMember, ChatMessage } from '../../lib/types'
// member mentions); it is the only HTML binding of the layer. Names, file
// names and every other field are text bindings.
//
// The action bar offers a reaction, a reply in a thread (outside the thread
// pane), pin or unpin (channels, while the host allows it), Edit on your own
// text messages and Delete where the store's canDelete allows it. Edits
// happen inline; deletes are confirmed by the list's ChatDeleteDialog.
// The first URLs of the text (up to limits.max_embeds) show as link cards:
// a host's registered renderer, else ChatLinkEmbed.
import type { ChatAttachment, ChatMember, ChatMessage } from '../../lib/types'
import { shortName } from '../../lib/chatFormat'
import { mentionsHandle, renderChatText } from '../../lib/chatText'
import { fmtDateTime, fmtTime } from '../../lib/format'
import { fmtDateTime, fmtSize, fmtTime } from '../../lib/format'
import { embedRendererFor, messageUrls } from '../../lib/linkEmbeds'
import { useMediaQuery } from '../../lib/media'
import ChatLinkEmbed from './LinkEmbed.vue'
import ChatReactionBar from './ReactionBar.vue'
const props = defineProps<{ message: ChatMessage; followUp?: boolean; author?: ChatMember | null; meId: number | null; inThread?: boolean }>()
const emit = defineEmits<{ delete: [message: ChatMessage, opener: HTMLElement | null]; thread: [message: ChatMessage] }>()
const props = defineProps<{ message: ChatMessage; followUp?: boolean; author?: ChatMember | null; meId: number | null }>()
const { t } = useI18n()
const chat = useChat()
const touch = useMediaQuery('(hover: none)')
const root = ref<HTMLElement | null>(null)
const bar = ref<InstanceType<typeof ChatReactionBar> | null>(null)
const reactBtn = ref<HTMLButtonElement | null>(null)
const editBtn = ref<HTMLButtonElement | null>(null)
const deleteBtn = ref<HTMLButtonElement | null>(null)
const editInput = ref<HTMLTextAreaElement | null>(null)
const mine = computed(() => props.meId !== null && props.message.sender_id === props.meId)
const name = computed(() => shortName(props.author, props.message.sender_name, t('chat.someone')))
@@ -22,10 +49,158 @@ const mentionsMe = computed(() => !mine.value && mentionsHandle(props.message.co
const editedTitle = computed(() => (props.message.edited_at ? t('chat.msg.editedAt', { at: fmtDateTime(props.message.edited_at) }) : ''))
const deleted = computed(() => !!props.message.deleted_at)
const rendered = computed(() => renderChatText(props.message.content, chat.membersByHandle))
const hasReactions = computed(() => (props.message.reactions ?? []).some((r) => r.count > 0))
/** The bar shows for an add started from the action bar even without reactions. */
const picking = ref(false)
const actionsOpen = computed(() => actionsOpenId.value === props.message.id)
const canReact = computed(() => !!chat.allowedReactions?.length)
const canEdit = computed(() => chat.canEdit(props.message))
const canDelete = computed(() => chat.canDelete(props.message))
const canThread = computed(() => !props.inThread && !props.message.root_id)
const canPin = computed(() => !props.message.root_id && chat.pinAllowed && chat.isChannel(props.message.conversation_id))
const pinned = computed(() => chat.isPinned(props.message))
const replyCount = computed(() => props.message.thread_summary?.reply_count ?? 0)
/** Link cards: the first URLs of the text, at most limits.max_embeds. */
const embeds = computed(() => {
const max = chat.limits?.max_embeds ?? 1
if (deleted.value || max <= 0) return []
return messageUrls(props.message.content)
.slice(0, max)
.map((url) => ({ url, component: embedRendererFor(url) ?? ChatLinkEmbed }))
})
// Attachments download through a bearer fetch; never shown inline.
const attachments = computed(() => props.message.attachments ?? [])
const downloading = ref<number | null>(null)
async function download(a: ChatAttachment) {
if (downloading.value !== null) return
downloading.value = a.id
try {
await chat.download(props.message, a)
} finally {
downloading.value = null
}
}
// Inline edit: only the text; attachments stay as they are.
const editing = ref(false)
const editText = ref('')
const saving = ref(false)
const editError = ref('')
const LINE = 24
function grow() {
const el = editInput.value
if (!el) return
el.style.height = 'auto'
const cs = getComputedStyle(el)
const max = LINE * 8 + parseFloat(cs.paddingTop) + parseFloat(cs.paddingBottom)
el.style.height = `${Math.min(el.scrollHeight, max)}px`
el.style.overflowY = el.scrollHeight > max ? 'auto' : 'hidden'
}
async function startEdit() {
if (!canEdit.value) return
editText.value = props.message.content ?? ''
editError.value = ''
editing.value = true
actionsOpenId.value = null
await nextTick()
const el = editInput.value
if (!el) return
grow()
el.focus()
el.setSelectionRange(el.value.length, el.value.length)
}
function endEdit() {
editing.value = false
editError.value = ''
void nextTick(() => editBtn.value?.focus())
}
async function saveEdit() {
if (saving.value) return
saving.value = true
editError.value = ''
const failed = await chat.edit(props.message, editText.value)
saving.value = false
if (failed) {
editError.value = t(`chat.${failed}`)
return
}
endEdit()
}
function onEditKeydown(e: KeyboardEvent) {
if (e.isComposing) return
if (e.key === 'Escape') {
e.preventDefault()
e.stopPropagation()
if (!saving.value) endEdit()
return
}
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault()
void saveEdit()
}
}
watch(editText, () => void nextTick(grow))
watch(deleted, (d) => {
if (d) editing.value = false
})
function askDelete() {
if (canDelete.value) emit('delete', props.message, deleteBtn.value)
}
async function addReaction() {
if (!canReact.value) return
picking.value = true
await nextTick()
bar.value?.openPicker(reactBtn.value)
}
function onPickerClosed() {
picking.value = false
}
/** Touch: a tap on the message toggles its action bar; links and buttons keep their own tap. */
function onTap(e: MouseEvent) {
if (!touch.value) return
const target = e.target as HTMLElement | null
if (target?.closest('a, button, textarea, input, .chat-msg-actions')) return
actionsOpenId.value = actionsOpen.value ? null : props.message.id
}
function onOutside(e: PointerEvent) {
if (root.value && e.target instanceof Node && root.value.contains(e.target)) return
if (actionsOpen.value) actionsOpenId.value = null
}
watch(actionsOpen, (open) => {
if (open) document.addEventListener('pointerdown', onOutside, true)
else document.removeEventListener('pointerdown', onOutside, true)
})
onBeforeUnmount(() => {
document.removeEventListener('pointerdown', onOutside, true)
if (actionsOpen.value) actionsOpenId.value = null
})
</script>
<template>
<article class="chat-msg" :class="{ 'is-follow': followUp, 'is-mention': mentionsMe }" :data-message-id="message.id">
<article
ref="root"
class="chat-msg"
:class="{ 'is-follow': followUp, 'is-actions-open': actionsOpen, 'is-mention': mentionsMe, 'is-pinned': pinned }"
:data-message-id="message.id"
@click="onTap"
>
<div class="chat-msg-gutter">
<ChatAvatar v-if="!followUp" :user-id="message.sender_id" :member="author" :fallback="message.sender_name" :me="mine" />
<time v-else class="chat-msg-time" :datetime="message.created_at" :title="timeTitle">{{ time }}</time>
@@ -37,13 +212,69 @@ const rendered = computed(() => renderChatText(props.message.content, chat.membe
<span v-else-if="mine" class="chat-tag chat-tag--me">{{ t('chat.msg.you') }}</span>
<time class="chat-msg-time" :datetime="message.created_at" :title="timeTitle">{{ time }}</time>
<span v-if="message.edited_at" class="chat-msg-edited" :title="editedTitle">{{ t('chat.msg.edited') }}</span>
<span v-if="pinned" class="chat-tag chat-tag--pin"><ChatIcon name="pin" />{{ t('chat.pins.pinned') }}</span>
</div>
<span v-else class="chat-sr">{{ name }}, {{ time }}:</span>
<p v-if="deleted" class="chat-msg-deleted">{{ t('chat.msg.deleted') }}</p>
<form v-else-if="editing" class="chat-msg-edit" @submit.prevent="saveEdit">
<textarea ref="editInput" v-model="editText" rows="1" :aria-label="t('chat.msg.editLabel')" :readonly="saving" @keydown="onEditKeydown"></textarea>
<p v-if="editError" class="chat-error" role="alert">{{ editError }}</p>
<div class="chat-btn-row">
<button class="chat-btn chat-btn--primary chat-btn--small" type="submit" :aria-busy="saving ? 'true' : undefined">{{ t('chat.msg.save') }}</button>
<button class="chat-btn chat-btn--ghost chat-btn--small" type="button" :disabled="saving" @click="endEdit">{{ t('chat.msg.cancel') }}</button>
</div>
</form>
<template v-else>
<div v-if="message.content" class="chat-msg-body" v-html="rendered"></div>
<span v-if="followUp && message.edited_at" class="chat-msg-edited" :title="editedTitle">{{ t('chat.msg.edited') }}</span>
</template>
<ul v-if="!deleted && attachments.length" class="chat-msg-files">
<li v-for="a in attachments" :key="a.id">
<button
class="chat-msg-file"
type="button"
:aria-label="t('chat.msg.download', { name: a.filename, size: fmtSize(a.size) })"
:aria-busy="downloading === a.id ? 'true' : undefined"
@click="download(a)"
>
<ChatIcon name="file" />
<span class="chat-msg-file-name">{{ a.filename }}</span>
<span class="chat-msg-file-size">{{ fmtSize(a.size) }}</span>
</button>
</li>
</ul>
<div v-if="embeds.length && !editing" class="chat-msg-embeds">
<component :is="e.component" v-for="e in embeds" :key="e.url.href" :url="e.url" />
</div>
<ChatReactionBar v-if="!deleted && (hasReactions || picking)" ref="bar" :message="message" @closed="onPickerClosed" />
<button v-if="canThread && replyCount > 0" class="chat-thread-link" type="button" @click="emit('thread', message)">
<ChatIcon name="thread" />{{ t('chat.thread.replies', { n: replyCount }, replyCount) }}
</button>
</div>
<div v-if="!deleted && !editing" class="chat-msg-actions" role="toolbar" :aria-label="t('chat.msg.actions')">
<button ref="reactBtn" class="chat-msg-action" type="button" :aria-label="t('chat.reactions.add')" :title="t('chat.reactions.add')" :disabled="!canReact" @click="addReaction">
<ChatIcon name="smile" />
</button>
<button v-if="canThread" class="chat-msg-action" type="button" :aria-label="t('chat.thread.reply')" :title="t('chat.thread.reply')" @click="emit('thread', message)">
<ChatIcon name="thread" />
</button>
<button
v-if="canPin"
class="chat-msg-action"
type="button"
:aria-label="pinned ? t('chat.pins.unpin') : t('chat.pins.pin')"
:title="pinned ? t('chat.pins.unpin') : t('chat.pins.pin')"
:aria-pressed="pinned ? 'true' : 'false'"
@click="chat.togglePin(message)"
>
<ChatIcon name="pin" />
</button>
<button v-if="canEdit" ref="editBtn" class="chat-msg-action" type="button" :aria-label="t('chat.msg.edit')" :title="t('chat.msg.edit')" @click="startEdit">
<ChatIcon name="pencil" />
</button>
<button v-if="canDelete" ref="deleteBtn" class="chat-msg-action chat-msg-action--danger" type="button" :aria-label="t('chat.msg.delete')" :title="t('chat.msg.delete')" @click="askDelete">
<ChatIcon name="trash" />
</button>
</div>
</article>
</template>

View File

@@ -8,6 +8,8 @@
// and stays until it changes. Older pages load from a top sentinel,
// keeping the first message where it was.
import type { ChatAnchor } from '../../composables/useChat'
import type { ChatMessage } from '../../lib/types'
import { renderChatText } from '../../lib/chatText'
import { groupMessages, shortName } from '../../lib/chatFormat'
import { dividerMessageId, shouldMarkRead } from '../../lib/chatUnread'
@@ -21,6 +23,21 @@ const { t } = useI18n()
const chat = useChat()
const el = ref<HTMLElement | null>(null)
const sentinel = ref<HTMLElement | null>(null)
/** One delete confirmation for the whole list. */
const deleteDialog = ref<{ open: (m: ChatMessage, from?: HTMLElement | null) => void } | null>(null)
function askDelete(message: ChatMessage, opener: HTMLElement | null) {
deleteDialog.value?.open(message, opener)
}
/** Slash command answers for this conversation, shown to the sender only. */
const ephemeral = computed(() => chat.ephemeral[props.conversationId] ?? [])
watch(
() => ephemeral.value.length,
(n, old) => {
if (n > (old ?? 0)) scrollToBottom()
},
)
const list = computed(() => chat.messages[props.conversationId])
const error = computed(() => chat.errors[props.conversationId] ?? '')
@@ -288,14 +305,29 @@ defineExpose({ scrollToBottom })
:follow-up="item.followUp && item.message.id !== dividerId"
:author="chat.members.get(item.message.sender_id)"
:me-id="chat.userId"
@delete="askDelete"
@thread="chat.openThread"
/>
</template>
</template>
</template>
<div v-for="row in ephemeral" :key="`eph-${row.id}`" class="chat-ephemeral" :class="{ 'is-error': row.error }" role="status">
<div class="chat-ephemeral-head">
<ChatIcon name="slash" />
<span class="chat-ephemeral-input">{{ row.input }}</span>
<span class="chat-tag">{{ t('chat.commands.onlyYou') }}</span>
<button class="chat-icon-btn" type="button" :aria-label="t('chat.commands.dismiss')" :title="t('chat.commands.dismiss')" @click="chat.dismissEphemeral(conversationId, row.id)">
<ChatIcon name="close" />
</button>
</div>
<p v-if="row.error" class="chat-error">{{ row.error }}</p>
<div v-else class="chat-ephemeral-text chat-msg-body" v-html="renderChatText(row.text)"></div>
</div>
</div>
<button v-if="pending > 0" class="chat-btn chat-btn--small chat-jump" type="button" @click="scrollToBottom(true)">
<ChatIcon name="arrow-down" />{{ t('chat.list.jump', { n: pending }) }}
</button>
<div class="chat-sr" aria-live="polite">{{ announcement }}</div>
<ChatDeleteDialog ref="deleteDialog" />
</div>
</template>

View File

@@ -4,7 +4,8 @@
// inside <ClientOnly> (it uses window and the DOM); it starts the chat
// store itself.
//
// Slots: sidebar-footer (below the channel list).
// Slots: sidebar-footer (below the channel list) and conversation-actions
// ({ conversation }, in the header of an open DM only).
const { t, locale, localeProperties } = useI18n()
const chat = useChat()
const picker = ref<{ open: () => void } | null>(null)
@@ -24,7 +25,7 @@ function opened() {
</script>
<template>
<div class="chat-page" :class="{ 'is-open': open }">
<div class="chat-page" :class="{ 'is-open': open, 'has-thread': !!chat.thread }">
<p v-if="chat.bootstrapState === 'error' && chat.member === undefined" class="chat-error" role="alert">
{{ t('chat.error.bootstrap') }}
<button class="chat-link-btn" type="button" @click="chat.start(formatLocale)">{{ t('chat.retry') }}</button>
@@ -37,7 +38,10 @@ function opened() {
</ChatChannelList>
<ChatDmList @compose="picker?.open()" @opened="opened" />
</aside>
<ChatPanel ref="panel" class="chat-main" @back="chat.close()" />
<ChatPanel ref="panel" class="chat-main" @back="chat.close()">
<template #conversation-actions="slotProps"><slot name="conversation-actions" v-bind="slotProps" /></template>
</ChatPanel>
<ChatThreadPane v-if="chat.thread" :key="chat.thread.rootId" class="chat-side" />
<ChatMemberPicker ref="picker" @started="opened" />
</template>
<ChatNotices />

View File

@@ -1,6 +1,9 @@
<script setup lang="ts">
// The open conversation: header, messages, the typing line and the
// composer. With nothing open it shows the empty state.
// The open conversation: header (with the pins panel of a channel),
// messages, the typing line and the composer. With nothing open it shows
// the empty state.
//
// Slot conversation-actions: forwarded to ChatHeader (DMs only).
import { shortName } from '../../lib/chatFormat'
const props = withDefaults(defineProps<{ visible?: boolean; back?: boolean }>(), { visible: true, back: true })
@@ -9,6 +12,11 @@ const { t } = useI18n()
const chat = useChat()
const list = ref<{ scrollToBottom: (smooth?: boolean) => void } | null>(null)
const composer = ref<{ focus: () => void } | null>(null)
const pinsOpen = ref(false)
watch(
() => chat.activeId,
() => (pinsOpen.value = false),
)
const dmName = computed(() => (chat.activeDm ? shortName(chat.members.get(chat.activeDm.other_user_id), '', t('chat.someone')) : ''))
const name = computed(() => (chat.activeChannel ? `# ${chat.activeChannel.name}` : dmName.value))
@@ -41,7 +49,10 @@ defineExpose({ focus })
<template>
<section class="chat-panel" :aria-label="name || t('chat.name')">
<template v-if="chat.activeId !== null && chat.kind">
<ChatHeader :back="back" @back="emit('back')" />
<ChatHeader :back="back" :pins-open="pinsOpen" @back="emit('back')" @pins="pinsOpen = !pinsOpen">
<template #conversation-actions="slotProps"><slot name="conversation-actions" v-bind="slotProps" /></template>
</ChatHeader>
<ChatPinsPanel v-if="pinsOpen && chat.activeChannel" @close="pinsOpen = false" />
<ChatMessageList
ref="list"
:key="chat.activeId"

View File

@@ -0,0 +1,43 @@
<script setup lang="ts">
// The open channel's pinned messages (golem15.chatchannels pins), opened
// from the conversation header. Unpinning shows only while the host allows
// pins for the user.
const emit = defineEmits<{ close: [] }>()
const { t } = useI18n()
const chat = useChat()
const uid = useId()
const channel = computed(() => chat.activeChannel)
const list = computed(() => (channel.value ? chat.pinMessages[channel.value.id] : undefined))
const failed = computed(() => (channel.value ? !!chat.pinsError[channel.value.id] : false))
watch(
channel,
(c) => {
if (c) void chat.loadPins(c)
},
{ immediate: true },
)
</script>
<template>
<section v-if="channel" class="chat-pins" :aria-labelledby="`chat-pins-h-${uid}`" @keydown.esc="emit('close')">
<div class="chat-pins-head">
<h3 :id="`chat-pins-h-${uid}`" class="chat-section-title"><ChatIcon name="pin" />{{ t('chat.pins.title') }}</h3>
<button class="chat-icon-btn" type="button" :aria-label="t('chat.close')" @click="emit('close')"><ChatIcon name="close" /></button>
</div>
<p v-if="failed" class="chat-error" role="alert">
{{ t('chat.pins.failed') }}
<button class="chat-link-btn" type="button" @click="chat.loadPins(channel)">{{ t('chat.retry') }}</button>
</p>
<div v-else-if="!list" class="chat-skeletons" aria-busy="true" :aria-label="t('chat.loading')">
<div class="chat-skeleton"></div>
</div>
<p v-else-if="!list.length" class="chat-muted">{{ t('chat.pins.empty') }}</p>
<ul v-else class="chat-pins-list">
<li v-for="m in list" :key="m.id">
<ChatMessage :message="m" :author="chat.members.get(m.sender_id)" :me-id="chat.userId" in-thread />
</li>
</ul>
</section>
</template>

View File

@@ -0,0 +1,205 @@
<script setup lang="ts">
// Reaction chips under a message and the add-reaction popover.
// The popover lists the keys the server allows (golem15.chat.reactions), so
// changing that config changes the picker without a rebuild. A chip toggles
// your own reaction; the store updates it at once and reconciles it with
// the server answer and the realtime events.
import type { ChatMessage } from '../../lib/types'
import { reactorsTitle } from '../../lib/chatFormat'
const props = defineProps<{ message: ChatMessage }>()
const emit = defineEmits<{ closed: [] }>()
const PER_ROW = 6
const { t } = useI18n()
const chat = useChat()
const uid = useId()
const popId = `chat-reactions-${uid}`
const root = ref<HTMLElement | null>(null)
const addBtn = ref<HTMLButtonElement | null>(null)
const pop = ref<HTMLElement | null>(null)
const open = ref(false)
const below = ref(false)
const active = ref(0)
/** Where focus goes when the popover closes (the action bar's button, or the add button). */
let returnTo: HTMLElement | null = null
const chips = computed(() =>
(props.message.reactions ?? [])
.filter((r) => r.count > 0)
.map((r) => {
const mine = chat.userId !== null && r.user_ids.includes(chat.userId)
return {
key: r.key,
count: r.count,
mine,
label: `${r.key} ${r.count}. ${mine ? t('chat.reactions.undo') : t('chat.reactions.join')}`,
title: reactorsTitle(r.user_ids, chat.members, (names, rest) => t('chat.reactions.more', { names, n: rest }), t('chat.someone')),
}
}),
)
const keys = computed(() => chat.allowedReactions ?? [])
const ready = computed(() => keys.value.length > 0)
function toggle(key: string) {
void chat.toggleReaction(props.message, key)
}
/** Above the add button, unless the list has no room there. */
function place() {
const el = root.value
const list = el?.closest('.chat-list, .chat-thread-list')
if (!el || !list) {
below.value = false
return
}
const rows = Math.ceil(keys.value.length / PER_ROW)
const height = rows * 36 + (rows - 1) * 4 + 16 + 2 + 8
below.value = el.getBoundingClientRect().top - list.getBoundingClientRect().top < height
}
function buttons(): HTMLButtonElement[] {
return pop.value ? [...pop.value.querySelectorAll<HTMLButtonElement>('button')] : []
}
function focusActive() {
void nextTick(() => buttons()[active.value]?.focus())
}
/** Opens the popover; focus returns to `from` (or the add button) when it closes. */
function openPicker(from?: HTMLElement | null) {
if (!ready.value) {
void chat.loadReactions()
return
}
returnTo = from ?? addBtn.value
active.value = 0
place()
open.value = true
document.addEventListener('pointerdown', onOutside, true)
focusActive()
}
function close(refocus = true) {
if (!open.value) return
open.value = false
document.removeEventListener('pointerdown', onOutside, true)
const target = returnTo
returnTo = null
if (refocus) target?.focus()
emit('closed')
}
function onOutside(e: PointerEvent) {
const t = e.target as Node | null
if (t && (pop.value?.contains(t) || addBtn.value?.contains(t))) return
const target = returnTo
close(false)
// Focus goes back only when the click did not move it somewhere else.
setTimeout(() => {
const a = document.activeElement
if (!a || a === document.body || pop.value?.contains(a)) target?.focus()
})
}
function pick(key: string) {
toggle(key)
close()
}
function onAdd() {
if (open.value) close()
else openPicker(addBtn.value)
}
function onKeydown(e: KeyboardEvent) {
const n = keys.value.length
if (!n) return
let next = active.value
switch (e.key) {
case 'Escape':
e.preventDefault()
e.stopPropagation()
close()
return
case 'ArrowRight':
next = (active.value + 1) % n
break
case 'ArrowLeft':
next = (active.value - 1 + n) % n
break
case 'ArrowDown':
next = active.value + PER_ROW < n ? active.value + PER_ROW : active.value % PER_ROW
break
case 'ArrowUp':
next = active.value - PER_ROW >= 0 ? active.value - PER_ROW : Math.min(n - 1, active.value % PER_ROW + Math.floor((n - 1) / PER_ROW) * PER_ROW)
break
case 'Home':
next = 0
break
case 'End':
next = n - 1
break
case 'Tab':
close(false)
return
default:
return
}
e.preventDefault()
active.value = next
focusActive()
}
onBeforeUnmount(() => document.removeEventListener('pointerdown', onOutside, true))
defineExpose({ openPicker })
</script>
<template>
<div ref="root" class="chat-reactions">
<button
v-for="c in chips"
:key="c.key"
class="chat-reaction-chip"
type="button"
:aria-pressed="c.mine ? 'true' : 'false'"
:aria-label="c.label"
:title="c.title"
@click="toggle(c.key)"
>
<span class="chat-reaction-emoji" aria-hidden="true">{{ c.key }}</span>
<span class="chat-reaction-count" aria-hidden="true">{{ c.count }}</span>
</button>
<span class="chat-reaction-add-wrap">
<button
ref="addBtn"
class="chat-reaction-add"
type="button"
:aria-label="t('chat.reactions.add')"
aria-haspopup="true"
:aria-expanded="open ? 'true' : 'false'"
:aria-controls="open ? popId : undefined"
:disabled="!ready"
@click="onAdd"
>
<ChatIcon name="smile" />
</button>
<div v-if="open" :id="popId" ref="pop" class="chat-reaction-pop" :class="{ 'is-below': below }" role="group" :aria-label="t('chat.reactions.add')" @keydown="onKeydown">
<button
v-for="(k, i) in keys"
:key="k"
class="chat-reaction-pick"
type="button"
:aria-label="k"
:tabindex="i === active ? 0 : -1"
@click="pick(k)"
@focus="active = i"
>
{{ k }}
</button>
</div>
</span>
</div>
</template>

View File

@@ -0,0 +1,36 @@
<script setup lang="ts">
// The composer's staging row: the files that go out with the next message,
// with their name and size, upload progress or a failed upload with a
// retry. Removing a chip only changes the draft.
import type { StagedFile } from '../../composables/useChat'
import { fmtSize } from '../../lib/format'
const props = defineProps<{ conversationId: number }>()
const emit = defineEmits<{ removed: [] }>()
const { t } = useI18n()
const chat = useChat()
const draft = computed(() => chat.draft(props.conversationId))
function removeFile(f: StagedFile) {
chat.removeFile(props.conversationId, f.localId)
emit('removed')
}
</script>
<template>
<ul v-if="draft.files.length" class="chat-staging" :aria-label="t('chat.files.staged')">
<li v-for="f in draft.files" :key="`file-${f.localId}`" class="chat-staging-chip" :class="`is-${f.state}`">
<span class="chat-staging-name" :title="f.name">{{ f.name }}</span>
<span v-if="f.state === 'uploading'" class="chat-staging-size">{{ t('chat.files.uploading', { n: f.progress }) }}</span>
<template v-else-if="f.state === 'failed'">
<span class="chat-staging-failed">{{ t('chat.files.failed') }}</span>
<button class="chat-link-btn" type="button" @click="chat.retryUpload(conversationId, f.localId)">{{ t('chat.retry') }}</button>
</template>
<span v-else class="chat-staging-size">{{ fmtSize(f.size) }}</span>
<button class="chat-staging-remove" type="button" :aria-label="t('chat.files.remove', { name: f.name })" :disabled="draft.sending" @click="removeFile(f)">
<ChatIcon name="close" />
</button>
<span v-if="f.state === 'uploading'" class="chat-staging-progress" :style="{ width: `${f.progress}%` }" aria-hidden="true"></span>
</li>
</ul>
</template>

View File

@@ -0,0 +1,142 @@
<script setup lang="ts">
// The open thread: its root message, the replies (oldest first) and a reply
// composer. Replies from others arrive live through the store; the bell
// mutes or unmutes the thread for the user.
import type { ChatMessage } from '../../lib/types'
import { shortName } from '../../lib/chatFormat'
const emit = defineEmits<{ close: [] }>()
const { t } = useI18n()
const chat = useChat()
const uid = useId()
const listEl = ref<HTMLElement | null>(null)
const input = ref<HTMLTextAreaElement | null>(null)
const deleteDialog = ref<{ open: (m: ChatMessage, from?: HTMLElement | null) => void } | null>(null)
const rootId = computed(() => chat.thread?.rootId ?? null)
const root = computed(() => {
const th = chat.thread
return th ? (chat.messages[th.conversationId]?.find((m) => m.id === th.rootId) ?? null) : null
})
const list = computed(() => (rootId.value !== null ? chat.replies[rootId.value] : undefined))
const failed = computed(() => (rootId.value !== null ? !!chat.repliesError[rootId.value] : false))
const muted = computed(() => (rootId.value !== null ? !!chat.threadMuted[rootId.value] : false))
const draft = computed(() => chat.threadDraft(rootId.value))
const text = computed({
get: () => draft.value.text,
set: (v: string) => {
if (rootId.value !== null) chat.setThreadDraftText(rootId.value, v)
},
})
const errorLine = computed(() => {
const d = draft.value
if (!d.error) return ''
return d.detail ? `${t(`chat.${d.error}`)} ${d.detail}` : t(`chat.${d.error}`)
})
const rootName = computed(() => (root.value ? shortName(chat.members.get(root.value.sender_id), root.value.sender_name, t('chat.someone')) : ''))
function scrollToBottom() {
void nextTick(() => {
const e = listEl.value
if (e) e.scrollTop = e.scrollHeight
})
}
watch(() => list.value?.length, scrollToBottom)
async function submit() {
if (rootId.value === null) return
if (await chat.sendReply(rootId.value)) scrollToBottom()
}
function onKeydown(e: KeyboardEvent) {
if (e.isComposing || e.key !== 'Enter' || e.shiftKey) return
e.preventDefault()
void submit()
}
function close() {
chat.closeThread()
emit('close')
}
onMounted(() => {
scrollToBottom()
input.value?.focus()
})
</script>
<template>
<aside v-if="rootId !== null" class="chat-thread" :aria-labelledby="`chat-thread-h-${uid}`" @keydown.esc="close">
<header class="chat-head">
<div class="chat-head-row">
<div class="chat-head-name">
<span class="chat-eyebrow">{{ t('chat.thread.title') }}</span>
<h2 :id="`chat-thread-h-${uid}`" class="chat-title">{{ rootName ? t('chat.thread.with', { name: rootName }) : t('chat.thread.title') }}</h2>
</div>
<div class="chat-head-actions">
<button
class="chat-icon-btn"
type="button"
:aria-pressed="muted ? 'true' : 'false'"
:aria-label="muted ? t('chat.thread.unmute') : t('chat.thread.mute')"
:title="muted ? t('chat.thread.unmute') : t('chat.thread.mute')"
@click="chat.setThreadMute(rootId, !muted)"
>
<ChatIcon :name="muted ? 'bell-off' : 'bell'" />
</button>
<button class="chat-icon-btn" type="button" :aria-label="t('chat.thread.close')" :title="t('chat.thread.close')" @click="close">
<ChatIcon name="close" />
</button>
</div>
</div>
</header>
<div ref="listEl" class="chat-thread-list" role="region" :aria-label="t('chat.thread.title')" tabindex="0">
<ChatMessage v-if="root" :message="root" :author="chat.members.get(root.sender_id)" :me-id="chat.userId" in-thread @delete="(m, from) => deleteDialog?.open(m, from)" />
<div class="chat-thread-divider" role="separator">
<span>{{ t('chat.thread.replies', { n: list?.length ?? root?.thread_summary?.reply_count ?? 0 }, list?.length ?? root?.thread_summary?.reply_count ?? 0) }}</span>
</div>
<p v-if="failed" class="chat-error" role="alert">
{{ t('chat.thread.failed') }}
<button class="chat-link-btn" type="button" @click="chat.loadReplies(rootId)">{{ t('chat.retry') }}</button>
</p>
<div v-else-if="!list" class="chat-skeletons" aria-busy="true" :aria-label="t('chat.loading')">
<div class="chat-skeleton"></div>
<div class="chat-skeleton"></div>
</div>
<template v-else>
<ChatMessage
v-for="m in list"
:key="m.id"
:message="m"
:author="chat.members.get(m.sender_id)"
:me-id="chat.userId"
in-thread
@delete="(msg, from) => deleteDialog?.open(msg, from)"
/>
</template>
</div>
<form class="chat-composer chat-thread-composer" @submit.prevent="submit">
<label class="chat-sr" :for="`chat-thread-input-${uid}`">{{ t('chat.thread.replyLabel') }}</label>
<p v-if="errorLine" class="chat-error" role="alert">{{ errorLine }}</p>
<div class="chat-composer-field">
<textarea
:id="`chat-thread-input-${uid}`"
ref="input"
v-model="text"
rows="2"
:placeholder="t('chat.thread.replyPlaceholder')"
:readonly="draft.sending"
@keydown="onKeydown"
></textarea>
<div class="chat-composer-tools">
<span class="chat-composer-gap"></span>
<button class="chat-btn chat-btn--primary chat-send" type="submit" :disabled="!text.trim() || draft.sending" :aria-busy="draft.sending ? 'true' : undefined">
{{ t('chat.thread.send') }}<ChatIcon name="arrow-right" />
</button>
</div>
</div>
</form>
<ChatDeleteDialog ref="deleteDialog" />
</aside>
</template>

View File

@@ -9,11 +9,19 @@
// Realtime: user:{me} for the whole member session (messages from others in
// any conversation, read marks, mention changes; every other event goes to
// onUserEvent handlers), and the open conversation's channel while it is
// open (created, typing, edits, deletions, presence). Without realtime the
// open conversation is polled every 15 s and the counts every 60 s.
// open (created, typing, reactions, edits, deletions, presence). Without
// realtime the open conversation is polled every 15 s and the counts every
// 60 s.
//
// On top of the ported store: threads (replies, thread mute), channel pins,
// reactions, attachments, edits, deletes (a moderator also deletes other
// people's messages in channels) and slash commands (golem15.chatbots: a
// message starting with / is dispatched, never posted; an ephemeral answer
// is a local row only the sender sees).
import { computed, reactive, ref, shallowRef } from 'vue'
import { ChatApiError, userIdFromToken } from '../lib/client'
import { applyChatMessage, needsFetch, parsePublication, type ChatEvent } from '../lib/chatEvents'
import { checkFiles, type FileCheckMessages } from '../lib/attachments'
import { applyChatMessage, applyReaction, needsFetch, parsePublication, type ChatEvent } from '../lib/chatEvents'
import { setFormatLocale } from '../lib/format'
import {
disconnect as disconnectRealtime,
@@ -28,7 +36,7 @@ import {
type ConnectionState,
type PresenceClient,
} from '../lib/realtime'
import type { ChatChannel, ChatConversationRow, ChatLimits, ChatMember, ChatMessage, ChatSendBody } from '../lib/types'
import type { ChatAttachment, ChatChannel, ChatCommand, ChatConversationRow, ChatLimits, ChatMember, ChatMessage, ChatSendBody } from '../lib/types'
export interface ChatDraft {
text: string
@@ -37,6 +45,36 @@ export interface ChatDraft {
/** A server message shown with the error (a 422 field error), or ''. */
detail: string
sending: boolean
/** Staged attachments, uploaded as soon as they are picked. */
files: StagedFile[]
}
/** An attachment chip: uploading with progress, done with its pending id, or failed. */
export interface StagedFile {
localId: number
name: string
size: number
/** 0 to 100. */
progress: number
state: 'uploading' | 'done' | 'failed'
/** The pending attachment id once uploaded. */
id: number | null
}
/** A slash command's answer shown to the sender only, under the conversation. */
export interface ChatEphemeral {
id: number
input: string
/** The answer text (rendered escaped), or '' for an error row. */
text: string
/** The refusal (an unknown command, for example), or ''. */
error: string
}
/** The open thread. */
export interface ChatThread {
rootId: number
conversationId: number
}
/** Where a list was scrolled: restored when the list mounts again. */
@@ -69,7 +107,16 @@ export const TYPING_THROTTLE_MS = 3_000
/** A typing entry expires 6 s after that person's last typing event. */
export const TYPING_EXPIRY_MS = 6_000
const EMPTY_DRAFT: Readonly<ChatDraft> = Object.freeze({ text: '', error: '', detail: '', sending: false })
const EMPTY_DRAFT: Readonly<ChatDraft> = Object.freeze({
text: '',
error: '',
detail: '',
sending: false,
files: Object.freeze([]) as unknown as StagedFile[],
})
/** The fallback limits before the bootstrap answers (golem15.chat MaxAttachments, 5 MiB). */
const DEFAULT_FILE_LIMITS = { max_files: 5, max_bytes: 5 * 1024 * 1024 }
/** The send-error key (chat.error.*) for a failed POST. */
export function sendErrorKey(e: unknown): string {
@@ -165,6 +212,23 @@ function createChatStore() {
const olderError = useState<Record<number, string>>('chat:olderError', () => ({}))
/** Who is typing, per conversation (others only). */
const typing = useState<Record<number, number[]>>('chat:typing', () => ({}))
/** The allowed reaction keys from the server; null until loaded. */
const allowedReactions = useState<string[] | null>('chat:reactions', () => null)
const thread = useState<ChatThread | null>('chat:thread', () => null)
/** Replies per thread root id, oldest first; absent until loaded. */
const replies = useState<Record<number, ChatMessage[]>>('chat:replies', () => ({}))
const repliesError = useState<Record<number, boolean>>('chat:repliesError', () => ({}))
const threadDrafts = useState<Record<number, ChatDraft>>('chat:threadDrafts', () => ({}))
/** Thread mute per root id, as set in this session. */
const threadMuted = useState<Record<number, boolean>>('chat:threadMuted', () => ({}))
/** Pinned message ids per channel id; absent until loaded. */
const pinIds = useState<Record<number, number[]>>('chat:pinIds', () => ({}))
const pinMessages = useState<Record<number, ChatMessage[]>>('chat:pinMessages', () => ({}))
const pinsError = useState<Record<number, boolean>>('chat:pinsError', () => ({}))
/** False after the host refused a pin: the action is hidden for the session. */
const pinAllowed = useState('chat:pinAllowed', () => true)
const commands = useState<ChatCommand[] | null>('chat:commands', () => null)
const ephemeral = useState<Record<number, ChatEphemeral[]>>('chat:ephemeral', () => ({}))
/** Presence of the open channel: Centrifugo client id to user id. */
const presenceClients = shallowRef<Map<string, number>>(new Map())
const presenceAvailable = ref(false)
@@ -173,6 +237,17 @@ function createChatStore() {
let generation = 0
let bootstrapping: Promise<void> | null = null
let membersLoading: Promise<void> | null = null
let reactionsLoading: Promise<void> | null = null
let commandsLoading: Promise<void> | null = null
/** The latest reaction toggle per message: only its answer replaces the chips. */
const reactionSeq = new Map<number, number>()
// Attachments: the picked File per chip (kept for a retry) and the aborts of uploads in flight.
let fileSeq = 0
const fileBlobs = new Map<number, File>()
const fileAborts = new Map<number, AbortController>()
/** Replies already counted on their root's thread summary in this session. */
const countedReplies = new Set<number>()
let ephemeralSeq = 0
/** Channels whose conversation route ran this session (it makes the caller a participant). */
const joinedConversations = new Set<number>()
@@ -350,6 +425,7 @@ function createChatStore() {
await bootstrap()
if (gen !== generation || !member.value) return
void loadMembers()
void loadReactions()
watchVisibility()
void startRealtime()
}
@@ -375,6 +451,7 @@ function createChatStore() {
/** Makes a conversation active and loads its latest page once. */
async function open(conversationId: number, as: ChatKind) {
if (thread.value && thread.value.conversationId !== conversationId) thread.value = null
activeId.value = conversationId
kind.value = as
void syncOpenChannel()
@@ -569,7 +646,10 @@ function createChatStore() {
}
function appendMessage(m: ChatMessage) {
if (m.root_id) return
if (m.root_id) {
addReply(m)
return
}
const list = messages.value[m.conversation_id]
if (list) insertMessage(list, m)
const row = conversations.value.find((c) => c.id === m.conversation_id)
@@ -622,15 +702,105 @@ function createChatStore() {
}
function ensureDraft(conversationId: number): ChatDraft {
if (!drafts.value[conversationId]) drafts.value[conversationId] = { text: '', error: '', detail: '', sending: false }
if (!drafts.value[conversationId]) drafts.value[conversationId] = { text: '', error: '', detail: '', sending: false, files: [] }
return drafts.value[conversationId]
}
/** Text and no send in flight. */
/** True while any attachment of the draft is uploading (the send waits). */
function uploading(conversationId: number | null): boolean {
return draft(conversationId).files.some((f) => f.state === 'uploading')
}
/** Text or an uploaded file, nothing uploading and no send in flight. */
function canSend(conversationId: number | null): boolean {
const d = draft(conversationId)
if (d.sending) return false
return d.text.trim() !== ''
if (d.sending || uploading(conversationId)) return false
return d.text.trim() !== '' || d.files.some((f) => f.state === 'done')
}
function startUpload(conversationId: number, localId: number) {
const file = fileBlobs.get(localId)
const chip = drafts.value[conversationId]?.files.find((f) => f.localId === localId)
if (!file || !chip) return
chip.state = 'uploading'
chip.progress = 0
chip.id = null
const abort = new AbortController()
fileAborts.set(localId, abort)
const gen = generation
// The reactive copy: progress and results land on what the view renders.
const live = () => drafts.value[conversationId]?.files.find((f) => f.localId === localId)
api
.upload(
file,
(n) => {
const c = live()
if (gen === generation && c && c.state === 'uploading') c.progress = n
},
abort.signal,
)
.then((answer) => {
const c = live()
if (gen !== generation || !c || abort.signal.aborted) return
c.state = 'done'
c.progress = 100
c.id = answer.id
})
.catch((e: unknown) => {
const c = live()
if (gen !== generation || !c || abort.signal.aborted) return
c.state = 'failed'
const d = drafts.value[conversationId]
if (d) {
d.error = 'error.upload'
d.detail = e instanceof ChatApiError ? e.field('file') : ''
}
})
.finally(() => {
if (fileAborts.get(localId) === abort) fileAborts.delete(localId)
})
}
/**
* Stages picked files: refused ones (too many, SVG/HTML/XML, over
* limits.max_bytes alone or together with the staged chips) never upload
* and answer their error lines, which also become the draft's error
* detail; the rest upload at once with progress.
*/
function uploadFiles(conversationId: number, files: readonly File[], messages?: FileCheckMessages): string[] {
const d = ensureDraft(conversationId)
const stagedBytes = d.files.reduce((sum, f) => sum + f.size, 0)
const { accepted, errors } = checkFiles(files, limits.value ?? DEFAULT_FILE_LIMITS, d.files.length, stagedBytes, messages)
d.error = errors.length ? 'error.files' : ''
d.detail = errors.join(' ')
for (const file of accepted) {
const localId = ++fileSeq
fileBlobs.set(localId, file)
d.files.push({ localId, name: file.name, size: file.size, progress: 0, state: 'uploading', id: null })
startUpload(conversationId, localId)
}
return errors
}
/** Uploads a failed chip again. */
function retryUpload(conversationId: number, localId: number) {
const chip = drafts.value[conversationId]?.files.find((f) => f.localId === localId)
if (!chip || chip.state !== 'failed') return
const d = drafts.value[conversationId]
if (d) {
d.error = ''
d.detail = ''
}
startUpload(conversationId, localId)
}
/** Drops a chip, aborting its upload if it is still running. */
function removeFile(conversationId: number, localId: number) {
fileAborts.get(localId)?.abort()
fileAborts.delete(localId)
fileBlobs.delete(localId)
const d = drafts.value[conversationId]
if (d) d.files = d.files.filter((f) => f.localId !== localId)
}
function setDraftText(conversationId: number, text: string) {
@@ -649,8 +819,16 @@ function createChatStore() {
if (conversationId === null) return false
const d = ensureDraft(conversationId)
const content = d.text.trim()
if (!content || d.sending) return false
const sent = d.files.filter((f) => f.state === 'done' && f.id !== null)
if ((!content && !sent.length) || d.sending || uploading(conversationId)) return false
// A slash command is dispatched to golem15.chatbots, never posted.
if (content.startsWith('/') && !sent.length) {
const ok = await runCommand(conversationId, content)
if (ok) d.text = ''
return ok
}
const body: ChatSendBody = { content }
if (sent.length) body.attachment_ids = sent.map((f) => f.id as number)
d.sending = true
d.error = ''
d.detail = ''
@@ -660,6 +838,10 @@ function createChatStore() {
if (gen !== generation) return false
appendMessage(m)
d.text = ''
// Failed chips stay, so a file that did not upload is never dropped silently.
const gone = new Set(sent.map((f) => f.localId))
for (const id of gone) fileBlobs.delete(id)
d.files = d.files.filter((f) => !gone.has(f.localId))
return true
} catch (e) {
if (gen !== generation) return false
@@ -701,14 +883,336 @@ function createChatStore() {
return membersLoading
}
/** The loaded copy of a message, if any. */
/** The loaded copy of a message (a thread reply too), if any. */
function findMessage(conversationId: number, id: number): ChatMessage | undefined {
return messages.value[conversationId]?.find((m) => m.id === id)
const hit = messages.value[conversationId]?.find((m) => m.id === id)
if (hit) return hit
for (const list of Object.values(replies.value)) {
const r = list.find((m) => m.id === id && m.conversation_id === conversationId)
if (r) return r
}
return undefined
}
/** The reaction list, once per session; a failure leaves it null so the add button stays disabled. */
function loadReactions(): Promise<void> {
if (allowedReactions.value !== null) return Promise.resolve()
if (reactionsLoading) return reactionsLoading
const gen = generation
reactionsLoading = (async () => {
try {
const keys = await api.reactions()
if (gen === generation) allowedReactions.value = Array.isArray(keys) ? keys.filter((k) => typeof k === 'string' && k !== '') : []
} catch {
/* the add button stays disabled; the next session tries again */
} finally {
if (gen === generation) reactionsLoading = null
}
})()
return reactionsLoading
}
/**
* Toggles the user's reaction: the chip changes at once, the answer
* replaces the message's reactions, and an error undoes the change with a
* notice. Realtime events patch the same list idempotently.
*/
async function toggleReaction(message: Pick<ChatMessage, 'id' | 'conversation_id'>, key: string) {
const me = userId.value
const m = findMessage(message.conversation_id, message.id)
if (me === null || !m || m.deleted_at) return
const add = !(m.reactions ?? []).some((r) => r.key === key && r.user_ids.includes(me))
m.reactions = applyReaction(m.reactions, key, me, add, allowedReactions.value ?? [])
const seq = (reactionSeq.get(m.id) ?? 0) + 1
reactionSeq.set(m.id, seq)
const gen = generation
try {
const answer = add ? await api.addReaction(m.id, key) : await api.removeReaction(m.id, key)
if (gen !== generation || reactionSeq.get(m.id) !== seq) return
const current = findMessage(message.conversation_id, message.id)
if (current && !current.deleted_at) current.reactions = answer.reactions ?? []
} catch {
if (gen !== generation) return
const current = findMessage(message.conversation_id, message.id)
if (current) current.reactions = applyReaction(current.reactions, key, me, !add, allowedReactions.value ?? [])
notice.show(add ? 'error.reactionAdd' : 'error.reactionRemove')
} finally {
if (gen === generation && reactionSeq.get(m.id) === seq) reactionSeq.delete(m.id)
}
}
/** Only your own, live text messages can be edited (golem15.chat edits text only). */
function canEdit(m: ChatMessage): boolean {
return userId.value !== null && m.sender_id === userId.value && !m.deleted_at && m.type === 'text'
}
/**
* Your own messages; someone else's only for a moderator and only in a
* channel, never in a DM. The server enforces the same rule.
*/
function canDelete(m: ChatMessage): boolean {
if (userId.value === null || m.deleted_at) return false
if (m.sender_id === userId.value) return true
return moderator.value && isChannel(m.conversation_id)
}
/** Saves an edit. null when saved (or unchanged); the error key otherwise. */
async function edit(message: ChatMessage, text: string): Promise<string | null> {
const content = text.trim()
if (content === (message.content ?? '').trim()) return null
if (!content) return 'error.edit'
const gen = generation
try {
const next = await api.edit(message.id, content)
if (gen === generation) replaceMessage(next)
return null
} catch (e) {
return e instanceof ChatApiError && e.status === 422 ? 'error.refused' : 'error.edit'
}
}
/** Deletes a message. null when deleted; the error key otherwise. */
async function remove(message: ChatMessage): Promise<string | null> {
const gen = generation
try {
await api.remove(message.id)
if (gen === generation) deleteLocal(message.conversation_id, message.id)
return null
} catch (e) {
// Already gone on the server: show it as deleted.
if (e instanceof ChatApiError && e.status === 404) {
if (gen === generation) deleteLocal(message.conversation_id, message.id)
return null
}
return 'error.delete'
}
}
/**
* Saves a message attachment: a bearer fetch to a blob, saved through a
* temporary anchor with the download attribute. The blob is typed as
* octet-stream, so the browser never renders it.
*/
async function download(message: ChatMessage, a: ChatAttachment): Promise<boolean> {
try {
const data = await api.download(message.id, a.id)
const url = URL.createObjectURL(new Blob([data], { type: 'application/octet-stream' }))
const link = document.createElement('a')
link.href = url
link.download = a.filename || 'file'
link.rel = 'noopener'
link.style.display = 'none'
document.body.appendChild(link)
link.click()
link.remove()
setTimeout(() => URL.revokeObjectURL(url), 30_000)
return true
} catch {
notice.show('error.download')
return false
}
}
/** Inserts a reply in its loaded thread and counts it on the root once. */
function addReply(m: ChatMessage) {
const root = m.root_id
if (!root) return
const list = replies.value[root]
if (list) insertMessage(list, m)
if (countedReplies.has(m.id)) return
countedReplies.add(m.id)
const r = messages.value[m.conversation_id]?.find((x) => x.id === root)
if (!r) return
const s = r.thread_summary ?? { root_id: root, reply_count: 0, participant_ids: [] }
const ids = s.participant_ids.includes(m.sender_id) ? s.participant_ids : [...s.participant_ids, m.sender_id]
r.thread_summary = { ...s, reply_count: s.reply_count + 1, last_reply_at: m.created_at, participant_ids: ids }
}
/** Loads a thread's replies; the counted set learns them, so their events do not count twice. */
async function loadReplies(rootId: number) {
const gen = generation
repliesError.value[rootId] = false
try {
const list = await api.replies(rootId)
if (gen !== generation) return
for (const m of list) countedReplies.add(m.id)
replies.value[rootId] = list
} catch {
if (gen === generation) repliesError.value[rootId] = true
}
}
/** Opens a thread pane on a root message. */
async function openThread(root: ChatMessage) {
thread.value = { rootId: root.id, conversationId: root.conversation_id }
await loadReplies(root.id)
}
function closeThread() {
thread.value = null
}
function threadDraft(rootId: number | null): Readonly<ChatDraft> {
return (rootId !== null && threadDrafts.value[rootId]) || EMPTY_DRAFT
}
function setThreadDraftText(rootId: number, text: string) {
if (!threadDrafts.value[rootId]) threadDrafts.value[rootId] = { text: '', error: '', detail: '', sending: false, files: [] }
const d = threadDrafts.value[rootId]
d.text = text
d.error = ''
d.detail = ''
}
/** Posts a reply in the open thread. */
async function sendReply(rootId: number): Promise<boolean> {
const d = threadDrafts.value[rootId]
const content = d?.text.trim() ?? ''
if (!d || !content || d.sending) return false
d.sending = true
d.error = ''
d.detail = ''
const gen = generation
try {
const m = await api.reply(rootId, { content })
if (gen !== generation) return false
addReply(m)
d.text = ''
return true
} catch (e) {
if (gen !== generation) return false
d.error = sendErrorKey(e)
if (e instanceof ChatApiError) d.detail = e.field('content')
return false
} finally {
d.sending = false
}
}
/** Mutes or unmutes a thread for the user. */
async function setThreadMute(rootId: number, muted: boolean): Promise<boolean> {
try {
const answer = await api.muteThread(rootId, muted)
threadMuted.value[rootId] = answer?.is_muted ?? muted
return true
} catch {
notice.show('error.threadMute')
return false
}
}
/** Loads a channel's pins: the ids, then each message. */
async function loadPins(channel: ChatChannel) {
const ctx = context.value
if (!ctx) return
const gen = generation
pinsError.value[channel.id] = false
try {
const ids = await api.pins(ctx, channel.id)
if (gen !== generation) return
pinIds.value[channel.id] = ids
const got = await Promise.all(ids.slice(0, 50).map((id) => api.message(id).catch(() => null)))
if (gen !== generation) return
pinMessages.value[channel.id] = got.filter((m): m is ChatMessage => !!m && !m.deleted_at)
} catch {
if (gen === generation) pinsError.value[channel.id] = true
}
}
function isPinned(m: ChatMessage): boolean {
const ch = channelOf(m.conversation_id)
return !!ch && (pinIds.value[ch.id] ?? []).includes(m.id)
}
/** Pins or unpins a channel message. A refusal hides the action for the session. */
async function togglePin(m: ChatMessage): Promise<boolean> {
const ch = channelOf(m.conversation_id)
const ctx = context.value
if (!ch || !ctx) return false
const pinned = isPinned(m)
try {
if (pinned) await api.unpin(ctx, ch.id, m.id)
else await api.pin(ctx, ch.id, m.id)
} catch (e) {
if (e instanceof ChatApiError && e.status !== 0 && e.status !== 429 && e.status < 500) {
pinAllowed.value = false
notice.show('error.pinRefused')
} else {
notice.show('error.pin')
}
return false
}
await loadPins(ch)
return true
}
/** The slash commands, once per session. */
function loadCommands(): Promise<void> {
if (commands.value !== null) return Promise.resolve()
if (commandsLoading) return commandsLoading
const gen = generation
commandsLoading = (async () => {
try {
const list = await api.commands()
if (gen === generation) commands.value = list.filter((c) => typeof c?.trigger === 'string' && c.trigger !== '')
} catch {
if (gen === generation) commands.value = []
} finally {
if (gen === generation) commandsLoading = null
}
})()
return commandsLoading
}
/** The text of a command's payload: its content (or text, or message), or a string payload. */
function payloadText(payload: unknown): string {
if (typeof payload === 'string') return payload
if (payload && typeof payload === 'object') {
const p = payload as Record<string, unknown>
for (const k of ['content', 'text', 'message']) if (typeof p[k] === 'string') return p[k] as string
}
return ''
}
/**
* Dispatches a slash command for a conversation. The answer is shown to
* the sender only, as a local row; a refusal (an unknown command, 422)
* becomes an error row. Nothing is posted to the conversation.
*/
async function runCommand(conversationId: number, input: string): Promise<boolean> {
const d = ensureDraft(conversationId)
if (d.sending) return false
d.sending = true
d.error = ''
d.detail = ''
const gen = generation
const rows = () => (ephemeral.value[conversationId] ??= [])
try {
const answer = await api.dispatch(input)
if (gen !== generation) return false
rows().push({ id: ++ephemeralSeq, input, text: payloadText(answer?.payload), error: '' })
return true
} catch (e) {
if (gen !== generation) return false
if (e instanceof ChatApiError && e.status === 422) {
rows().push({ id: ++ephemeralSeq, input, text: '', error: e.field('input') || e.message })
return true
}
d.error = sendErrorKey(e)
return false
} finally {
d.sending = false
}
}
function dismissEphemeral(conversationId: number, id: number) {
const list = ephemeral.value[conversationId]
if (list) ephemeral.value[conversationId] = list.filter((r) => r.id !== id)
}
/** A newer copy of a message (an edit), also in the DM row preview. */
function replaceMessage(next: ChatMessage) {
const list = messages.value[next.conversation_id]
const list = next.root_id ? replies.value[next.root_id] : messages.value[next.conversation_id]
const i = list ? list.findIndex((m) => m.id === next.id) : -1
if (list && i >= 0) list[i] = next
const row = conversations.value.find((c) => c.id === next.conversation_id)
@@ -762,7 +1266,8 @@ function createChatStore() {
const conv = m.conversation_id
stopTyping(conv, m.sender_id)
const isSeen = seen(conv)
if (!m.root_id) {
if (m.root_id) addReply(m)
else {
const list = messages.value[conv]
if (list) insertMessage(list, m)
}
@@ -778,7 +1283,11 @@ function createChatStore() {
switch (ev.kind) {
case 'created':
stopTyping(ev.conversationId, ev.senderId)
if (!ev.rootId && needsFetch(ev, messages.value)) void fetchMessage(ev.id)
if (ev.rootId) {
// A reply: fetched only when its thread or its root is on screen.
const rootId = ev.rootId
if (!countedReplies.has(ev.id) && (replies.value[rootId] || findMessage(ev.conversationId, rootId))) void fetchMessage(ev.id)
} else if (needsFetch(ev, messages.value)) void fetchMessage(ev.id)
return
case 'typing':
onTyping(ev.conversationId, ev.userId)
@@ -795,6 +1304,11 @@ function createChatStore() {
case 'deleted':
deleteLocal(ev.conversationId, ev.id)
return
case 'reacted': {
const m = findMessage(ev.conversationId, ev.id)
if (m && !m.deleted_at) m.reactions = applyReaction(m.reactions, ev.key, ev.userId, ev.added, allowedReactions.value ?? [])
return
}
default:
return
}
@@ -1012,6 +1526,25 @@ function createChatStore() {
generation++
bootstrapping = null
membersLoading = null
reactionsLoading = null
commandsLoading = null
reactionSeq.clear()
for (const a of fileAborts.values()) a.abort()
fileAborts.clear()
fileBlobs.clear()
countedReplies.clear()
allowedReactions.value = null
thread.value = null
replies.value = {}
repliesError.value = {}
threadDrafts.value = {}
threadMuted.value = {}
pinIds.value = {}
pinMessages.value = {}
pinsError.value = {}
pinAllowed.value = true
commands.value = null
ephemeral.value = {}
userId.value = null
member.value = undefined
moderator.value = false
@@ -1104,6 +1637,41 @@ function createChatStore() {
findMessage,
replaceMessage,
deleteLocal,
uploading,
uploadFiles,
retryUpload,
removeFile,
download,
allowedReactions,
loadReactions,
toggleReaction,
canEdit,
canDelete,
edit,
remove,
thread,
replies,
repliesError,
threadMuted,
openThread,
closeThread,
loadReplies,
threadDraft,
setThreadDraftText,
sendReply,
setThreadMute,
pinIds,
pinMessages,
pinsError,
pinAllowed,
loadPins,
isPinned,
togglePin,
commands,
loadCommands,
runCommand,
ephemeral,
dismissEphemeral,
reset,
})
}

101
app/lib/attachments.ts Normal file
View File

@@ -0,0 +1,101 @@
// Client-side attachment checks, ported from a Golem15 SPA. They mirror
// golem15.chat's ChatAttachmentPolicy so a refused file never uploads; the
// server's checks (RejectBanned, the per-file and body limits) stay
// authoritative. The error copy defaults to the SPA's Polish; the layer
// passes its localized messages.
import type { ChatLimits } from './types'
/** golem15.chat BannedExts: script-capable types (stored XSS). */
export const BANNED_EXTENSIONS: readonly string[] = ['svg', 'svgz', 'html', 'htm', 'xhtml', 'xml']
/** golem15.chat BannedMIMEs. */
export const BANNED_MIME_TYPES: readonly string[] = ['image/svg+xml', 'text/html', 'application/xhtml+xml', 'text/xml', 'application/xml']
/** What checkFiles needs of a File. */
export interface FileLike {
name: string
size: number
type: string
}
export interface FileCheck<F extends FileLike> {
accepted: F[]
/** The error lines, one per kind (too-large names each file). */
errors: string[]
}
/** A byte limit in MB for the copy: 62914560 → "60", 1572864 → "1,5". */
export function mbLabel(bytes: number): string {
const mb = bytes / (1024 * 1024)
if (Number.isInteger(mb)) return String(mb)
return (Math.floor(mb * 10) / 10).toFixed(1).replace('.', ',')
}
/** True for SVG, HTML and XML, by extension or MIME type. */
export function isBanned(file: FileLike): boolean {
const dot = file.name.lastIndexOf('.')
const ext = (dot >= 0 ? file.name.slice(dot + 1) : file.name).toLowerCase()
if (BANNED_EXTENSIONS.includes(ext)) return true
const mime = (file.type || '').split(';')[0].trim().toLowerCase()
return BANNED_MIME_TYPES.includes(mime)
}
/** The error lines of checkFiles. */
export interface FileCheckMessages {
tooLarge(name: string, mb: string): string
overTotal(mb: string): string
banned(): string
tooMany(max: number): string
}
const PL_MESSAGES: FileCheckMessages = {
tooLarge: (name, mb) => `Plik „${name}” jest za duży. Limit to ${mb} MB.`,
overTotal: (mb) => `Załączniki jednej wiadomości mogą mieć razem najwyżej ${mb} MB.`,
banned: () => 'Plików SVG, HTML i XML nie można wysyłać na czacie.',
tooMany: (max) => `Możesz dołączyć najwyżej ${max} plików do jednej wiadomości.`,
}
/**
* Splits picked files into those that may upload and the error lines for
* the rest: banned types, files that would take the message's attachments
* above limits.max_bytes in total (stagedBytes is what is already staged),
* and anything over limits.max_files counting the chips already staged.
*/
export function checkFiles<F extends FileLike>(
files: readonly F[],
limits: Pick<ChatLimits, 'max_files' | 'max_bytes'>,
stagedCount: number,
stagedBytes = 0,
messages: FileCheckMessages = PL_MESSAGES,
): FileCheck<F> {
const accepted: F[] = []
const errors: string[] = []
let banned = false
let tooMany = false
let overTotal = false
let total = stagedBytes
for (const f of files) {
if (isBanned(f)) {
banned = true
continue
}
if (limits.max_bytes > 0 && f.size > limits.max_bytes) {
errors.push(messages.tooLarge(f.name, mbLabel(limits.max_bytes)))
continue
}
if (stagedCount + accepted.length >= limits.max_files) {
tooMany = true
continue
}
if (limits.max_bytes > 0 && total + f.size > limits.max_bytes) {
overTotal = true
continue
}
total += f.size
accepted.push(f)
}
if (overTotal) errors.unshift(messages.overTotal(mbLabel(limits.max_bytes)))
if (banned) errors.unshift(messages.banned())
if (tooMany) errors.unshift(messages.tooMany(limits.max_files))
return { accepted, errors }
}

View File

@@ -1,5 +1,6 @@
// The chat layer's HTTP client: golem15.chat (/_chat/api/v1), the host
// bootstrap ({hostApiBase}/chat) and golem15.chatchannels. Pure
// bootstrap ({hostApiBase}/chat), golem15.chatchannels (joins, pins) and
// golem15.chatbots (slash commands). Pure
// and Nuxt-free, so tests drive it with a stub fetch; useChatApi binds it to
// runtime config and the app's $chatAuth hook.
//
@@ -10,10 +11,15 @@
// stores the token.
import type {
ChatBootstrap,
ChatCommand,
ChatConversation,
ChatDispatchAnswer,
ChatMember,
ChatMessage,
ChatReactionsAnswer,
ChatSendBody,
ChatThreadMute,
ChatUploadAnswer,
} from './types'
/** The app's auth hook ($chatAuth): the user's JWT, its renewal and the signed-out callback. */
@@ -221,6 +227,84 @@ export function createChatClient(opts: ChatClientOptions) {
}
const chat = (path: string) => joinUrl(bases.chat, path)
/** Bytes of an authorized GET, with the same refresh as request. */
async function blob(url: string): Promise<Blob> {
const res = await authorized(() => doFetch(url, { method: 'GET', headers: headers({ Accept: '*/*' }) }))
if (!res.ok) throw toError(res.status, await parse(res))
return res.blob()
}
/**
* One multipart upload of a file as the field `file`. With XMLHttpRequest
* (browsers) it reports progress and honours the abort signal; elsewhere
* it falls back to fetch without progress.
*/
function sendUpload(url: string, file: File, onProgress?: (percent: number) => void, signal?: AbortSignal): Promise<ChatUploadAnswer> {
const finish = (status: number, json: unknown): ChatUploadAnswer => {
const body = unwrap<Partial<ChatUploadAnswer> | null>(json)
if (status >= 200 && status < 300 && body && typeof body.id === 'number') {
return { id: body.id, filename: String(body.filename ?? file.name), size: Number(body.size ?? file.size) }
}
throw toError(status, json)
}
if (typeof XMLHttpRequest === 'undefined') {
const form = new FormData()
form.append('file', file, file.name)
return doFetch(url, { method: 'POST', headers: headers(), body: form }).then(async (res) => finish(res.status, await parse(res)))
}
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open('POST', url)
for (const [k, v] of Object.entries(headers())) xhr.setRequestHeader(k, v)
xhr.upload.onprogress = (e) => {
if (e.lengthComputable && e.total > 0) onProgress?.(Math.min(100, Math.round((e.loaded / e.total) * 100)))
}
xhr.onload = () => {
let json: unknown = null
try {
json = xhr.responseText ? JSON.parse(xhr.responseText) : null
} catch {
json = null
}
try {
resolve(finish(xhr.status, json))
} catch (e) {
reject(e)
}
}
xhr.onerror = () => reject(new ChatApiError(0, 'network error'))
xhr.onabort = () => reject(new ChatApiError(0, 'aborted'))
if (signal) {
if (signal.aborted) {
reject(new ChatApiError(0, 'aborted'))
return
}
signal.addEventListener('abort', () => xhr.abort(), { once: true })
}
const form = new FormData()
form.append('file', file, file.name)
xhr.send(form)
})
}
/** The upload, with one refresh-and-retry on 401. */
async function upload(file: File, onProgress?: (percent: number) => void, signal?: AbortSignal): Promise<ChatUploadAnswer> {
const url = chat('/attachments')
const used = token()
try {
return await sendUpload(url, file, onProgress, signal)
} catch (e) {
if (!(e instanceof ChatApiError) || e.status !== 401 || !used || signal?.aborted) throw e
const renewed = await refresh()
if (!renewed) {
auth.unauthorized?.()
throw e
}
onProgress?.(0)
return sendUpload(url, file, onProgress, signal)
}
}
const channels = (context: { type: string; id: number }, path: string) =>
joinUrl(bases.channels, `/contexts/${encodeURIComponent(context.type)}/${context.id}${path}`)
const host = (path: string) => {
@@ -258,6 +342,40 @@ export function createChatClient(opts: ChatClientOptions) {
/** Leaves a channel; it stays listed with joined false. */
leaveChannel: (context: { type: string; id: number }, channelId: number) =>
request<unknown>(channels(context, `/channels/${channelId}/leave`), { method: 'POST' }),
/** The ids of a channel's pinned messages. */
pins: (context: { type: string; id: number }, channelId: number) =>
request<{ pins?: number[] }>(channels(context, `/channels/${channelId}/pins`)).then((r) => (Array.isArray(r?.pins) ? r.pins : [])),
/** Pins a message of the channel (refused unless the host allows the caller). */
pin: (context: { type: string; id: number }, channelId: number, messageId: number) =>
request<unknown>(channels(context, `/channels/${channelId}/pins`), { method: 'POST', body: { message_id: messageId } }),
unpin: (context: { type: string; id: number }, channelId: number, messageId: number) =>
request<unknown>(channels(context, `/channels/${channelId}/pins/${messageId}`), { method: 'DELETE' }),
/** Edits your own text message; answers the message. */
edit: (id: number, content: string) => request<ChatMessage>(chat(`/messages/${id}`), { method: 'PUT', body: { content } }),
/** Deletes a message: your own, or someone else's for a channel moderator. */
remove: (id: number) => request<{ deleted: boolean }>(chat(`/messages/${id}`), { method: 'DELETE' }),
/** The allowed reaction keys in display order. */
reactions: () => request<string[]>(chat('/reactions')),
/** Adds the user's reaction (idempotent); answers the message's reactions after the change. */
addReaction: (id: number, key: string) => request<ChatReactionsAnswer>(chat(`/messages/${id}/reactions`), { method: 'POST', body: { key } }),
/** Removes the user's reaction; the key is one path segment, so it is encoded. */
removeReaction: (id: number, key: string) =>
request<ChatReactionsAnswer>(chat(`/messages/${id}/reactions/${encodeURIComponent(key)}`), { method: 'DELETE' }),
/** A thread's replies, oldest first. */
replies: (rootId: number) => request<ChatMessage[]>(chat(`/messages/${rootId}/replies`)),
/** Posts a reply in a thread; answers the reply. */
reply: (rootId: number, body: ChatSendBody) => request<ChatMessage>(chat(`/messages/${rootId}/replies`), { method: 'POST', body }),
/** Mutes or unmutes a thread for the caller. */
muteThread: (rootId: number, muted: boolean) => request<ChatThreadMute>(chat(`/threads/${rootId}/mute`), { method: 'PUT', body: { muted } }),
/** Uploads one pending attachment with progress. */
upload,
/** An attachment's bytes (participants only; never a public URL). */
download: (messageId: number, fileId: number) => blob(chat(`/attachments/${messageId}/${fileId}`)),
/** The slash commands available to the caller (golem15.chatbots). */
commands: () =>
request<{ commands?: ChatCommand[] }>(joinUrl(bases.bots, '/commands')).then((r) => (Array.isArray(r?.commands) ? r.commands : [])),
/** Runs a slash command; an ephemeral answer is for the sender only. 422 errors.input for an unknown one. */
dispatch: (input: string) => request<ChatDispatchAnswer>(joinUrl(bases.bots, '/dispatch'), { method: 'POST', body: { input } }),
}
}

117
app/lib/linkEmbeds.ts Normal file
View File

@@ -0,0 +1,117 @@
// Links in chat text and the link-embed renderer registry.
//
// The chat has no unfurl backend: a message with an http(s) URL shows a
// card with the URL's host and path (ChatLinkEmbed), fetched from nowhere.
// A host renders its own links (its entity pages, for example) by
// registering a component for the URLs it recognises:
//
// registerEmbedRenderer((url) => url.hostname === location.hostname && url.pathname.startsWith('/blog/'), BlogCard)
//
// The component gets the URL as the `url` prop (a URL object). The first
// registered renderer that matches wins; ChatLinkEmbed is the fallback.
import type { Component } from 'vue'
import { escapeHtml } from './markdown'
const EXTERNAL = ' target="_blank" rel="noopener noreferrer nofollow"'
/** A bare http(s) URL as the chat text renderer finds it. */
const URL_RE = /(?<![\w/@.])https?:\/\/[^\s<>"'`]+/gi
/** Trailing punctuation after a bare URL stays text; a ")" stays only when the URL opened one. */
function splitUrl(raw: string): { url: string; rest: string } {
let url = raw
for (;;) {
const last = url.at(-1)
if (!last) break
if ('.,;:!?\'"]}'.includes(last)) {
url = url.slice(0, -1)
continue
}
if (last === ')' && (url.match(/\(/g)?.length ?? 0) < (url.match(/\)/g)?.length ?? 0)) {
url = url.slice(0, -1)
continue
}
break
}
return { url, rest: raw.slice(url.length) }
}
/** The URL when it parses as http(s), else null. */
function parseHttp(raw: string): URL | null {
try {
const u = new URL(raw)
return u.protocol === 'http:' || u.protocol === 'https:' ? u : null
} catch {
return null
}
}
function unescapeHtml(s: string): string {
return s.replace(/&(amp|lt|gt|quot|#39);/g, (_, e: string) => ({ amp: '&', lt: '<', gt: '>', quot: '"', '#39': "'" })[e] ?? '')
}
/**
* linkify turns the bare http(s) URLs of already-escaped text into links
* that open in a new tab without an opener or referrer. Nothing else is
* produced, so the result stays as safe as its input.
*/
export function linkify(escaped: string): string {
return escaped.replace(/https?:\/\/[^\s<>"'`]+/gi, (raw: string) => {
const plain = unescapeHtml(raw)
const { url, rest } = splitUrl(plain)
const parsed = parseHttp(url)
if (!parsed) return raw
return `<a href="${escapeHtml(url)}"${EXTERNAL}>${escapeHtml(url)}</a>${escapeHtml(rest)}`
})
}
/** The distinct http(s) URLs of a message text (outside code spans), in order. */
export function messageUrls(text: string | null | undefined): URL[] {
if (!text) return []
const plain = text.replace(/`[^`\n]+`/g, ' ')
const out: URL[] = []
const seen = new Set<string>()
// [label](url) links count too: their URL is matched like a bare one.
for (const m of plain.matchAll(URL_RE)) {
const { url } = splitUrl(m[0])
const parsed = parseHttp(url)
if (!parsed || seen.has(parsed.href)) continue
seen.add(parsed.href)
out.push(parsed)
}
return out
}
export type EmbedMatcher = (url: URL) => boolean
interface Renderer {
match: EmbedMatcher
component: Component
}
const renderers: Renderer[] = []
/**
* registerEmbedRenderer renders the URLs `match` accepts with `component`
* (props: url). Returns the function that removes the registration.
*/
export function registerEmbedRenderer(match: EmbedMatcher, component: Component): () => void {
const entry: Renderer = { match, component }
renderers.push(entry)
return () => {
const i = renderers.indexOf(entry)
if (i >= 0) renderers.splice(i, 1)
}
}
/** The registered renderer of a URL, or null for the generic card. */
export function embedRendererFor(url: URL): Component | null {
for (const r of renderers) {
try {
if (r.match(url)) return r.component
} catch {
/* a failing matcher matches nothing */
}
}
return null
}

View File

@@ -25,7 +25,17 @@
"tooManyDms": "Too many new conversations in a short time. Wait a minute and try again.",
"openChannel": "The channel could not open. Try again.",
"leaveChannel": "You could not leave the channel. Try again.",
"joinChannel": "You could not join the channel. Try again."
"joinChannel": "You could not join the channel. Try again.",
"upload": "A file was not uploaded.",
"files": "Some files were not added:",
"reactionAdd": "The reaction could not be added.",
"reactionRemove": "The reaction could not be removed.",
"edit": "The changes could not be saved. Try again.",
"delete": "The message could not be deleted. Try again.",
"download": "The file could not be downloaded. Try again.",
"threadMute": "The thread setting could not be saved.",
"pin": "The pin could not be changed. Try again.",
"pinRefused": "You cannot pin messages in this channel."
},
"unread": {
"messages": "{n} unread message | {n} unread messages",
@@ -54,7 +64,14 @@
"you": "You",
"edited": "(edited)",
"editedAt": "Edited {at}",
"deleted": "Message deleted."
"deleted": "Message deleted.",
"editLabel": "Edit the message",
"save": "Save changes",
"cancel": "Cancel editing",
"download": "Download {name} ({size})",
"actions": "Message actions",
"edit": "Edit",
"delete": "Delete"
},
"day": {
"today": "Today",
@@ -92,6 +109,60 @@
"one": "{a} is typing…",
"two": "{a} and {b} are typing…",
"many": "Several people are typing…"
},
"reactions": {
"add": "Add a reaction",
"undo": "Remove your reaction",
"join": "Add your reaction",
"more": "{names} and {n} others"
},
"thread": {
"title": "Thread",
"with": "Thread: {name}",
"reply": "Reply in a thread",
"replies": "{n} reply | {n} replies",
"mute": "Mute the thread",
"unmute": "Unmute the thread",
"close": "Close the thread",
"failed": "The replies could not load.",
"replyLabel": "Reply in the thread",
"replyPlaceholder": "Reply…",
"send": "Reply"
},
"pins": {
"title": "Pinned messages",
"pinned": "Pinned",
"pin": "Pin",
"unpin": "Unpin",
"empty": "No pinned messages in this channel.",
"failed": "The pinned messages could not load."
},
"files": {
"attach": "Attach files",
"staged": "Attachments",
"uploading": "Uploading… {n}%",
"failed": "Not uploaded",
"remove": "Remove {name}",
"tooLarge": "“{name}” is too large. The limit is {mb} MB.",
"overTotal": "The attachments of one message may take {mb} MB together.",
"banned": "SVG, HTML and XML files cannot be sent in the chat.",
"tooMany": "You can attach at most {n} files to one message."
},
"delete": {
"title": "Delete the message?",
"own": "The message disappears from the conversation for everyone. This cannot be undone.",
"other": "You delete the message from {name} for everyone. This cannot be undone.",
"confirm": "Delete the message",
"keep": "Keep the message"
},
"commands": {
"label": "Slash commands",
"none": "No command starts with “{q}”.",
"onlyYou": "Only you see this",
"dismiss": "Dismiss"
},
"embed": {
"opens": "(opens in a new tab)"
}
}
}

View File

@@ -25,7 +25,17 @@
"tooManyDms": "Za dużo nowych rozmów w krótkim czasie. Odczekaj minutę i spróbuj ponownie.",
"openChannel": "Nie udało się otworzyć kanału. Spróbuj ponownie.",
"leaveChannel": "Nie udało się opuścić kanału. Spróbuj ponownie.",
"joinChannel": "Nie udało się dołączyć do kanału. Spróbuj ponownie."
"joinChannel": "Nie udało się dołączyć do kanału. Spróbuj ponownie.",
"upload": "Nie udało się wysłać pliku.",
"files": "Nie dodano niektórych plików:",
"reactionAdd": "Nie udało się dodać reakcji.",
"reactionRemove": "Nie udało się cofnąć reakcji.",
"edit": "Nie udało się zapisać zmian. Spróbuj ponownie.",
"delete": "Nie udało się usunąć wiadomości. Spróbuj ponownie.",
"download": "Nie udało się pobrać pliku. Spróbuj ponownie.",
"threadMute": "Nie udało się zapisać ustawienia wątku.",
"pin": "Nie udało się zmienić przypięcia. Spróbuj ponownie.",
"pinRefused": "Nie możesz przypinać wiadomości na tym kanale."
},
"unread": {
"messages": "nieprzeczytane: {n}",
@@ -54,7 +64,14 @@
"you": "Ty",
"edited": "(edytowano)",
"editedAt": "Edytowano {at}",
"deleted": "Wiadomość usunięta."
"deleted": "Wiadomość usunięta.",
"editLabel": "Edytuj wiadomość",
"save": "Zapisz zmiany",
"cancel": "Anuluj edycję",
"download": "Pobierz {name} ({size})",
"actions": "Działania wiadomości",
"edit": "Edytuj",
"delete": "Usuń"
},
"day": {
"today": "Dziś",
@@ -92,6 +109,60 @@
"one": "{a} pisze…",
"two": "{a} i {b} piszą…",
"many": "Kilka osób pisze…"
},
"reactions": {
"add": "Dodaj reakcję",
"undo": "Cofnij swoją reakcję",
"join": "Dodaj swoją reakcję",
"more": "{names} i inni ({n})"
},
"thread": {
"title": "Wątek",
"with": "Wątek: {name}",
"reply": "Odpowiedz w wątku",
"replies": "odpowiedzi: {n}",
"mute": "Wycisz wątek",
"unmute": "Włącz powiadomienia wątku",
"close": "Zamknij wątek",
"failed": "Nie udało się wczytać odpowiedzi.",
"replyLabel": "Odpowiedź w wątku",
"replyPlaceholder": "Odpowiedz…",
"send": "Odpowiedz"
},
"pins": {
"title": "Przypięte wiadomości",
"pinned": "Przypięta",
"pin": "Przypnij",
"unpin": "Odepnij",
"empty": "Na tym kanale nie ma przypiętych wiadomości.",
"failed": "Nie udało się wczytać przypiętych wiadomości."
},
"files": {
"attach": "Dołącz pliki",
"staged": "Załączniki",
"uploading": "Wysyłanie… {n}%",
"failed": "Nie wysłano",
"remove": "Usuń {name}",
"tooLarge": "Plik „{name}” jest za duży. Limit to {mb} MB.",
"overTotal": "Załączniki jednej wiadomości mogą mieć razem najwyżej {mb} MB.",
"banned": "Plików SVG, HTML i XML nie można wysyłać na czacie.",
"tooMany": "Do jednej wiadomości możesz dołączyć najwyżej {n} plików."
},
"delete": {
"title": "Usunąć wiadomość?",
"own": "Wiadomość zniknie z rozmowy u wszystkich. Tego nie można cofnąć.",
"other": "Usuniesz wiadomość od {name} u wszystkich. Tego nie można cofnąć.",
"confirm": "Usuń wiadomość",
"keep": "Zostaw wiadomość"
},
"commands": {
"label": "Polecenia",
"none": "Żadne polecenie nie zaczyna się od „{q}”.",
"onlyYou": "Widzisz tylko Ty",
"dismiss": "Zamknij"
},
"embed": {
"opens": "(otwiera się w nowej karcie)"
}
}
}

View File

@@ -54,6 +54,10 @@ export default defineNuxtConfig({
},
],
// Tokens first, then the neutral styles that use them. The app's own css
// array loads after these, so its token overrides win.
css: [`${currentDir}app/assets/css/chat-tokens.css`, `${currentDir}app/assets/css/chat-base.css`],
runtimeConfig: {
chat: {
// Server-only base of the chat API for server-side fetches