diff --git a/README.md b/README.md new file mode 100644 index 0000000..6fd97b6 --- /dev/null +++ b/README.md @@ -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: `` is the full chat (a sidebar with channels and DMs, the open conversation, a thread pane), and `` 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 + + +``` + +```vue + + + + +``` + +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. diff --git a/app/assets/css/chat-base.css b/app/assets/css/chat-base.css new file mode 100644 index 0000000..00e16fe --- /dev/null +++ b/app/assets/css/chat-base.css @@ -0,0 +1,1255 @@ +/* + * vue-chat-layer neutral styles. Every value comes from chat-tokens.css; + * every selector starts with .chat- so nothing leaks into the app. + */ + +.chat-page, +.chat-floating, +.chat-dialog { + font-family: var(--chat-font); + font-size: var(--chat-font-size); + line-height: var(--chat-line-height); + color: var(--chat-color-text); +} + +.chat-page *, +.chat-floating *, +.chat-dialog * { + box-sizing: border-box; +} + +.chat-sr { + position: absolute !important; + width: 1px; + height: 1px; + padding: 0; + margin: -1px; + overflow: hidden; + clip: rect(0, 0, 0, 0); + white-space: nowrap; + border: 0; +} + +.chat-icon { + width: 1.125rem; + height: 1.125rem; + flex: none; +} + +/* Buttons */ + +.chat-btn, +.chat-icon-btn, +.chat-link-btn, +.chat-row, +.chat-msg-action, +.chat-thread-link, +.chat-msg-file, +.chat-staging-remove, +.chat-reaction-chip, +.chat-reaction-add, +.chat-reaction-pick { + font: inherit; + color: inherit; + cursor: pointer; +} + +.chat-btn { + display: inline-flex; + align-items: center; + gap: var(--chat-space-1); + min-height: var(--chat-target); + padding: 0 var(--chat-space-3); + border: 1px solid var(--chat-color-border); + border-radius: var(--chat-radius); + background: var(--chat-color-bg); + font-weight: 600; +} + +.chat-btn--small { + min-height: 2rem; + font-size: var(--chat-font-size-sm); +} + +.chat-btn--primary { + background: var(--chat-color-accent); + border-color: var(--chat-color-accent); + color: var(--chat-color-on-accent); +} + +.chat-btn--danger { + background: var(--chat-color-danger); + border-color: var(--chat-color-danger); + color: var(--chat-color-on-accent); +} + +.chat-btn--ghost { + background: transparent; +} + +.chat-btn:disabled, +.chat-icon-btn:disabled, +.chat-msg-action:disabled, +.chat-reaction-add:disabled { + opacity: 0.5; + cursor: default; +} + +.chat-btn-row { + display: flex; + flex-wrap: wrap; + gap: var(--chat-space-2); + margin-top: var(--chat-space-2); +} + +.chat-icon-btn { + position: relative; + display: inline-flex; + align-items: center; + justify-content: center; + min-width: var(--chat-target); + min-height: var(--chat-target); + padding: 0; + border: 0; + border-radius: var(--chat-radius); + background: transparent; + color: var(--chat-color-muted); +} + +.chat-icon-btn:hover:not(:disabled), +.chat-icon-btn[aria-pressed='true'] { + background: var(--chat-color-hover); + color: var(--chat-color-text); +} + +.chat-link-btn { + padding: 0; + border: 0; + background: none; + color: var(--chat-color-accent); + text-decoration: underline; +} + +.chat-btn:focus-visible, +.chat-icon-btn:focus-visible, +.chat-link-btn:focus-visible, +.chat-row:focus-visible, +.chat-msg-action:focus-visible, +.chat-list:focus-visible, +.chat-thread-list:focus-visible, +.chat-floating-toggle:focus-visible { + outline: 2px solid var(--chat-color-accent); + outline-offset: 2px; +} + +/* Text helpers */ + +.chat-muted { + color: var(--chat-color-muted); + margin: var(--chat-space-2) 0; +} + +.chat-error { + color: var(--chat-color-danger); + font-size: var(--chat-font-size-sm); + margin: var(--chat-space-2) 0; +} + +.chat-tag { + display: inline-flex; + align-items: center; + gap: 2px; + padding: 0 var(--chat-space-1); + border-radius: var(--chat-radius); + background: var(--chat-color-surface); + color: var(--chat-color-muted); + font-size: var(--chat-font-size-sm); + font-weight: 600; +} + +.chat-tag .chat-icon { + width: 0.875rem; + height: 0.875rem; +} + +.chat-tag--me { + background: var(--chat-color-accent-soft); + color: var(--chat-color-accent); +} + +.chat-eyebrow { + display: block; + color: var(--chat-color-muted); + font-size: var(--chat-font-size-sm); + text-transform: uppercase; + letter-spacing: 0.04em; +} + +.chat-badge { + display: inline-flex; + align-items: center; + justify-content: center; + min-width: 1.25rem; + height: 1.25rem; + padding: 0 0.375rem; + border-radius: var(--chat-radius-pill); + background: var(--chat-color-accent); + color: var(--chat-color-on-accent); + font-size: 0.75rem; + font-weight: 700; + line-height: 1; +} + +.chat-badge--mention { + background: var(--chat-color-danger); +} + +.chat-skeletons { + display: grid; + gap: var(--chat-space-2); + padding: var(--chat-space-3); +} + +.chat-skeleton { + height: 2.5rem; + border-radius: var(--chat-radius); + background: var(--chat-color-surface); + animation: chat-pulse 1.4s ease-in-out infinite; +} + +@keyframes chat-pulse { + 50% { + opacity: 0.5; + } +} + +@media (prefers-reduced-motion: reduce) { + .chat-skeleton { + animation: none; + } +} + +/* The page: sidebar, conversation, thread */ + +.chat-page { + position: relative; + display: grid; + grid-template-columns: var(--chat-sidebar) minmax(0, 1fr); + height: var(--chat-height); + border: 1px solid var(--chat-color-border); + border-radius: var(--chat-radius-card); + background: var(--chat-color-bg); + overflow: hidden; +} + +.chat-page.has-thread { + grid-template-columns: var(--chat-sidebar) minmax(0, 1fr) var(--chat-side); +} + +.chat-sidebar { + display: flex; + flex-direction: column; + gap: var(--chat-space-3); + min-height: 0; + padding: var(--chat-space-3) var(--chat-space-2); + border-right: 1px solid var(--chat-color-border); + background: var(--chat-color-surface); + overflow-y: auto; +} + +.chat-main, +.chat-side { + min-width: 0; + min-height: 0; +} + +.chat-side { + border-left: 1px solid var(--chat-color-border); +} + +@media (max-width: 767px) { + .chat-page, + .chat-page.has-thread { + grid-template-columns: minmax(0, 1fr); + } + + .chat-page.is-open .chat-sidebar, + .chat-page:not(.is-open) .chat-main { + display: none; + } + + .chat-page .chat-side { + position: absolute; + inset: 0; + z-index: 2; + background: var(--chat-color-bg); + } +} + +@media (min-width: 768px) { + .chat-page .chat-back { + display: none; + } +} + +.chat-section-head { + display: flex; + align-items: center; + justify-content: space-between; +} + +.chat-section-title { + display: flex; + align-items: center; + gap: var(--chat-space-1); + margin: 0 var(--chat-space-2); + font-size: var(--chat-font-size-sm); + font-weight: 700; + text-transform: uppercase; + letter-spacing: 0.04em; + color: var(--chat-color-muted); +} + +.chat-section-subtitle { + margin: var(--chat-space-3) var(--chat-space-2) var(--chat-space-1); + font-size: var(--chat-font-size-sm); + font-weight: 600; + color: var(--chat-color-muted); +} + +.chat-rows { + list-style: none; + margin: var(--chat-space-1) 0 0; + padding: 0; + display: grid; + gap: 2px; +} + +.chat-row { + display: flex; + align-items: center; + gap: var(--chat-space-2); + width: 100%; + min-height: var(--chat-target); + padding: var(--chat-space-1) var(--chat-space-2); + border: 0; + border-radius: var(--chat-radius); + background: transparent; + text-align: left; +} + +.chat-row--static { + cursor: default; + justify-content: space-between; + color: var(--chat-color-muted); +} + +.chat-row:hover:not(.chat-row--static):not(:disabled) { + background: var(--chat-color-hover); +} + +.chat-row.is-active { + background: var(--chat-color-accent-soft); +} + +.chat-row.is-unread .chat-row-name { + font-weight: 700; +} + +.chat-row-name { + flex: 1; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.chat-dm-text { + display: grid; + flex: 1; + min-width: 0; +} + +.chat-dm-preview { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + color: var(--chat-color-muted); + font-size: var(--chat-font-size-sm); +} + +.chat-dm-meta { + display: grid; + justify-items: end; + gap: 2px; + color: var(--chat-color-muted); + font-size: 0.75rem; +} + +.chat-dms-empty { + margin: var(--chat-space-2); + font-size: var(--chat-font-size-sm); +} + +/* Avatars */ + +.chat-avatar { + display: inline-flex; + align-items: center; + justify-content: center; + flex: none; + border-radius: 50%; + background: var(--chat-color-muted); + color: var(--chat-av-text); + font-weight: 700; + user-select: none; +} + +.chat-avatar--24 { + width: 24px; + height: 24px; + font-size: 0.625rem; +} + +.chat-avatar--32 { + width: 32px; + height: 32px; + font-size: 0.75rem; +} + +.chat-avatar--44 { + width: 44px; + height: 44px; + font-size: 0.875rem; +} + +.chat-avatar--me { + background: var(--chat-color-text); +} + +/* The conversation */ + +.chat-panel, +.chat-thread { + position: relative; + display: flex; + flex-direction: column; + height: 100%; + min-height: 0; +} + +.chat-panel-empty { + display: grid; + place-content: center; + height: 100%; + padding: var(--chat-space-5); + text-align: center; +} + +.chat-panel-empty-title { + margin: 0; + font-size: var(--chat-font-size-lg); + font-weight: 700; +} + +.chat-head { + padding: var(--chat-space-2) var(--chat-space-3); + border-bottom: 1px solid var(--chat-color-border); +} + +.chat-head-row { + display: flex; + align-items: center; + gap: var(--chat-space-2); +} + +.chat-head-name { + flex: 1; + min-width: 0; +} + +.chat-title { + margin: 0; + font-size: var(--chat-font-size-lg); + font-weight: 700; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.chat-head-actions { + display: flex; + align-items: center; + gap: var(--chat-space-1); +} + +.chat-back .chat-badge { + position: absolute; + top: -2px; + right: -4px; +} + +.chat-presence { + display: flex; + align-items: center; + gap: var(--chat-space-1); + color: var(--chat-color-muted); + font-size: var(--chat-font-size-sm); +} + +.chat-presence-stack { + display: inline-flex; +} + +.chat-presence-stack .chat-avatar + .chat-avatar { + margin-left: -6px; + box-shadow: 0 0 0 2px var(--chat-color-bg); +} + +.chat-presence-dot { + width: 0.5rem; + height: 0.5rem; + border-radius: 50%; + background: var(--chat-color-success); +} + +.chat-strip { + margin: 0; + padding: var(--chat-space-1) var(--chat-space-3); + background: var(--chat-color-surface); + color: var(--chat-color-muted); + font-size: var(--chat-font-size-sm); +} + +.chat-list-wrap { + position: relative; + flex: 1; + min-height: 0; + display: flex; + flex-direction: column; +} + +.chat-list, +.chat-thread-list { + flex: 1; + min-height: 0; + overflow-y: auto; + padding: var(--chat-space-2) 0; +} + +.chat-start { + margin: var(--chat-space-3); + color: var(--chat-color-muted); + font-size: var(--chat-font-size-sm); + text-align: center; +} + +.chat-day, +.chat-new, +.chat-thread-divider { + display: flex; + align-items: center; + gap: var(--chat-space-2); + margin: var(--chat-space-3) var(--chat-space-3) var(--chat-space-2); + color: var(--chat-color-muted); + font-size: 0.75rem; + font-weight: 700; + letter-spacing: 0.04em; +} + +.chat-day::before, +.chat-day::after, +.chat-new::before, +.chat-new::after, +.chat-thread-divider::after { + content: ''; + flex: 1; + border-top: 1px solid var(--chat-color-border); +} + +.chat-new { + color: var(--chat-color-danger); +} + +.chat-new::before, +.chat-new::after { + border-color: var(--chat-color-danger); +} + +.chat-jump { + position: absolute; + left: 50%; + bottom: var(--chat-space-2); + transform: translateX(-50%); + box-shadow: var(--chat-shadow); +} + +.chat-typing { + min-height: 1.25rem; + padding: 0 var(--chat-space-3); + color: var(--chat-color-muted); + font-size: 0.75rem; +} + +/* Messages */ + +.chat-msg { + position: relative; + display: grid; + grid-template-columns: 2.5rem minmax(0, 1fr); + gap: var(--chat-space-2); + padding: var(--chat-space-1) var(--chat-space-3); + margin-top: var(--chat-space-2); +} + +.chat-msg.is-follow { + margin-top: 0; + padding-top: 0; +} + +.chat-msg:hover, +.chat-msg.is-actions-open { + background: var(--chat-color-surface); +} + +.chat-msg.is-mention { + background: var(--chat-color-mention); + box-shadow: inset 3px 0 0 var(--chat-color-danger); +} + +.chat-msg-gutter { + display: flex; + justify-content: center; +} + +.chat-msg.is-follow .chat-msg-gutter .chat-msg-time { + visibility: hidden; + font-size: 0.6875rem; + padding-top: 0.2rem; +} + +.chat-msg.is-follow:hover .chat-msg-gutter .chat-msg-time { + visibility: visible; +} + +.chat-msg-head { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: var(--chat-space-2); +} + +.chat-msg-name { + font-weight: 700; +} + +.chat-msg-time, +.chat-msg-edited { + color: var(--chat-color-muted); + font-size: 0.75rem; +} + +.chat-msg-body { + overflow-wrap: anywhere; +} + +.chat-msg-body a { + color: var(--chat-color-accent); +} + +.chat-msg-body code { + padding: 0 0.25em; + border-radius: 4px; + background: var(--chat-color-surface); + font-size: 0.9em; +} + +.chat-msg-body .mention { + padding: 0 0.15em; + border-radius: 4px; + background: var(--chat-color-accent-soft); + color: var(--chat-color-accent); + font-weight: 600; +} + +.chat-msg-deleted { + margin: 0; + color: var(--chat-color-muted); + font-style: italic; +} + +.chat-msg-edit textarea, +.chat-composer textarea, +.chat-field input { + width: 100%; + padding: var(--chat-space-2); + border: 1px solid var(--chat-color-border); + border-radius: var(--chat-radius); + background: var(--chat-color-bg); + color: inherit; + font: inherit; + line-height: 24px; + resize: none; +} + +.chat-msg-actions { + position: absolute; + top: -0.875rem; + right: var(--chat-space-3); + display: none; + gap: 2px; + padding: 2px; + border: 1px solid var(--chat-color-border); + border-radius: var(--chat-radius); + background: var(--chat-color-bg); + box-shadow: var(--chat-shadow); +} + +.chat-msg:hover .chat-msg-actions, +.chat-msg:focus-within .chat-msg-actions, +.chat-msg.is-actions-open .chat-msg-actions { + display: flex; +} + +.chat-msg-action { + display: inline-flex; + align-items: center; + justify-content: center; + width: 2rem; + height: 2rem; + padding: 0; + border: 0; + border-radius: 4px; + background: transparent; + color: var(--chat-color-muted); +} + +.chat-msg-action:hover:not(:disabled), +.chat-msg-action[aria-pressed='true'] { + background: var(--chat-color-hover); + color: var(--chat-color-text); +} + +.chat-msg-action--danger:hover:not(:disabled) { + color: var(--chat-color-danger); +} + +.chat-msg-files { + list-style: none; + display: flex; + flex-wrap: wrap; + gap: var(--chat-space-2); + margin: var(--chat-space-1) 0 0; + padding: 0; +} + +.chat-msg-file, +.chat-embed { + display: inline-flex; + align-items: center; + gap: var(--chat-space-2); + max-width: 100%; + padding: var(--chat-space-2) var(--chat-space-3); + border: 1px solid var(--chat-color-border); + border-radius: var(--chat-radius); + background: var(--chat-color-bg); + text-align: left; +} + +.chat-msg-file-name { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.chat-msg-file-size { + color: var(--chat-color-muted); + font-size: 0.75rem; +} + +.chat-msg-embeds { + display: grid; + gap: var(--chat-space-1); + margin-top: var(--chat-space-1); +} + +.chat-embed { + color: inherit; + text-decoration: none; + border-left: 3px solid var(--chat-color-accent); +} + +.chat-embed:hover { + background: var(--chat-color-surface); +} + +.chat-embed-main { + display: grid; + min-width: 0; +} + +.chat-embed-host { + font-weight: 600; +} + +.chat-embed-path { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + color: var(--chat-color-muted); + font-size: var(--chat-font-size-sm); +} + +.chat-thread-link { + display: inline-flex; + align-items: center; + gap: var(--chat-space-1); + margin-top: var(--chat-space-1); + padding: 2px var(--chat-space-2); + border: 0; + border-radius: var(--chat-radius); + background: transparent; + color: var(--chat-color-accent); + font-size: var(--chat-font-size-sm); + font-weight: 600; +} + +.chat-thread-link:hover { + background: var(--chat-color-accent-soft); +} + +/* Reactions */ + +.chat-reactions { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: var(--chat-space-1); + margin-top: var(--chat-space-1); +} + +.chat-reaction-chip { + display: inline-flex; + align-items: center; + gap: 4px; + height: 1.75rem; + padding: 0 var(--chat-space-2); + border: 1px solid var(--chat-color-border); + border-radius: var(--chat-radius-pill); + background: var(--chat-color-bg); + font-size: var(--chat-font-size-sm); +} + +.chat-reaction-chip[aria-pressed='true'] { + border-color: var(--chat-color-accent); + background: var(--chat-color-accent-soft); +} + +.chat-reaction-add-wrap { + position: relative; +} + +.chat-reaction-add { + display: inline-flex; + align-items: center; + justify-content: center; + width: 1.75rem; + height: 1.75rem; + padding: 0; + border: 1px solid transparent; + border-radius: var(--chat-radius-pill); + background: transparent; + color: var(--chat-color-muted); +} + +.chat-reaction-add:hover:not(:disabled) { + border-color: var(--chat-color-border); +} + +.chat-reaction-pop { + position: absolute; + bottom: calc(100% + 4px); + left: 0; + z-index: 5; + display: grid; + grid-template-columns: repeat(6, 2.25rem); + gap: 4px; + padding: var(--chat-space-2); + border: 1px solid var(--chat-color-border); + border-radius: var(--chat-radius); + background: var(--chat-color-bg); + box-shadow: var(--chat-shadow); +} + +.chat-reaction-pop.is-below { + top: calc(100% + 4px); + bottom: auto; +} + +.chat-reaction-pick { + width: 2.25rem; + height: 2.25rem; + border: 0; + border-radius: var(--chat-radius); + background: transparent; + font-size: 1.125rem; +} + +.chat-reaction-pick:hover, +.chat-reaction-pick:focus-visible { + background: var(--chat-color-hover); +} + +/* Slash command answers */ + +.chat-ephemeral { + margin: var(--chat-space-2) var(--chat-space-3); + padding: var(--chat-space-2) var(--chat-space-3); + border: 1px dashed var(--chat-color-border); + border-radius: var(--chat-radius); + background: var(--chat-color-surface); +} + +.chat-ephemeral-head { + display: flex; + align-items: center; + gap: var(--chat-space-2); + color: var(--chat-color-muted); + font-size: var(--chat-font-size-sm); +} + +.chat-ephemeral-input { + flex: 1; + font-weight: 600; +} + +.chat-ephemeral-text { + margin-top: var(--chat-space-1); +} + +/* Composer */ + +.chat-composer { + padding: var(--chat-space-2) var(--chat-space-3) var(--chat-space-3); +} + +.chat-composer-field { + position: relative; + border: 1px solid var(--chat-color-border); + border-radius: var(--chat-radius-card); + background: var(--chat-color-bg); +} + +.chat-composer-field:focus-within { + border-color: var(--chat-color-accent); +} + +.chat-composer .chat-composer-field textarea { + display: block; + border: 0; + background: transparent; + outline: none; +} + +.chat-composer-tools { + display: flex; + align-items: center; + gap: var(--chat-space-1); + padding: 0 var(--chat-space-1) var(--chat-space-1); +} + +.chat-composer-gap { + flex: 1; +} + +.chat-pop { + position: absolute; + left: 0; + right: 0; + bottom: calc(100% + 4px); + z-index: 5; + max-height: 16rem; + margin: 0; + padding: var(--chat-space-1); + overflow-y: auto; + list-style: none; + border: 1px solid var(--chat-color-border); + border-radius: var(--chat-radius); + background: var(--chat-color-bg); + box-shadow: var(--chat-shadow); +} + +.chat-pop-option, +.chat-pop-empty { + display: flex; + align-items: center; + gap: var(--chat-space-2); + padding: var(--chat-space-1) var(--chat-space-2); + border-radius: 4px; +} + +.chat-pop-option { + cursor: pointer; +} + +.chat-pop-option.is-active { + background: var(--chat-color-accent-soft); +} + +.chat-pop-empty { + color: var(--chat-color-muted); +} + +.chat-pop-name { + font-weight: 600; +} + +.chat-pop-meta { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + color: var(--chat-color-muted); + font-size: var(--chat-font-size-sm); +} + +.chat-staging { + list-style: none; + display: flex; + flex-wrap: wrap; + gap: var(--chat-space-2); + margin: 0 0 var(--chat-space-2); + padding: 0; +} + +.chat-staging-chip { + position: relative; + display: inline-flex; + align-items: center; + gap: var(--chat-space-2); + max-width: 100%; + padding: var(--chat-space-1) var(--chat-space-1) var(--chat-space-1) var(--chat-space-2); + border: 1px solid var(--chat-color-border); + border-radius: var(--chat-radius); + background: var(--chat-color-surface); + font-size: var(--chat-font-size-sm); + overflow: hidden; +} + +.chat-staging-chip.is-failed { + border-color: var(--chat-color-danger); +} + +.chat-staging-name { + max-width: 12rem; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.chat-staging-size, +.chat-staging-failed { + color: var(--chat-color-muted); +} + +.chat-staging-failed { + color: var(--chat-color-danger); +} + +.chat-staging-remove { + display: inline-flex; + padding: 2px; + border: 0; + background: transparent; + color: var(--chat-color-muted); +} + +.chat-staging-progress { + position: absolute; + left: 0; + bottom: 0; + height: 2px; + background: var(--chat-color-accent); +} + +/* Pins */ + +.chat-pins { + max-height: 45%; + overflow-y: auto; + border-bottom: 1px solid var(--chat-color-border); + background: var(--chat-color-surface); +} + +.chat-pins-head { + display: flex; + align-items: center; + justify-content: space-between; + padding: var(--chat-space-1) var(--chat-space-2) 0; +} + +.chat-pins-list { + list-style: none; + margin: 0; + padding: 0 0 var(--chat-space-2); +} + +.chat-pins .chat-muted, +.chat-pins .chat-error { + margin: var(--chat-space-2) var(--chat-space-3); +} + +/* Dialogs */ + +.chat-dialog { + width: min(28rem, calc(100vw - 2rem)); + padding: var(--chat-space-4); + border: 1px solid var(--chat-color-border); + border-radius: var(--chat-radius-card); + background: var(--chat-color-bg); + box-shadow: var(--chat-shadow); +} + +.chat-dialog::backdrop { + background: var(--chat-color-backdrop); +} + +.chat-dialog-head { + display: flex; + align-items: center; + justify-content: space-between; +} + +.chat-dialog-title { + margin: 0 0 var(--chat-space-2); + font-size: var(--chat-font-size-lg); +} + +.chat-field { + display: grid; + gap: var(--chat-space-1); + margin: var(--chat-space-2) 0; +} + +.chat-field label { + font-weight: 600; + font-size: var(--chat-font-size-sm); +} + +.chat-picker-results { + max-height: 20rem; + overflow-y: auto; +} + +/* Notices */ + +.chat-notices { + position: absolute; + left: 50%; + bottom: var(--chat-space-4); + z-index: 10; + transform: translateX(-50%); + pointer-events: none; +} + +.chat-notice { + display: flex; + align-items: center; + gap: var(--chat-space-2); + margin: 0; + padding: var(--chat-space-1) var(--chat-space-1) var(--chat-space-1) var(--chat-space-3); + border-radius: var(--chat-radius); + background: var(--chat-color-text); + color: var(--chat-color-bg); + font-size: var(--chat-font-size-sm); + box-shadow: var(--chat-shadow); + pointer-events: auto; +} + +.chat-notice .chat-icon-btn { + color: inherit; +} + +/* The floating panel */ + +.chat-floating { + position: fixed; + right: var(--chat-floating-offset); + bottom: var(--chat-floating-offset); + z-index: var(--chat-z-floating); + display: flex; + flex-direction: column; + align-items: flex-end; + gap: var(--chat-space-2); +} + +.chat-floating-toggle { + position: relative; + display: inline-flex; + align-items: center; + justify-content: center; + width: 3.25rem; + height: 3.25rem; + border: 0; + border-radius: 50%; + background: var(--chat-color-accent); + color: var(--chat-color-on-accent); + box-shadow: var(--chat-shadow); + cursor: pointer; +} + +.chat-floating-toggle .chat-icon { + width: 1.5rem; + height: 1.5rem; +} + +.chat-floating-toggle .chat-badge { + position: absolute; + top: -4px; + right: -4px; + background: var(--chat-color-danger); +} + +.chat-floating-box { + position: relative; + display: flex; + flex-direction: column; + width: var(--chat-floating-width); + max-width: calc(100vw - 2 * var(--chat-floating-offset)); + height: var(--chat-floating-height); + border: 1px solid var(--chat-color-border); + border-radius: var(--chat-radius-card); + background: var(--chat-color-bg); + box-shadow: var(--chat-shadow); + overflow: hidden; +} + +.chat-floating-head { + display: flex; + align-items: center; + gap: var(--chat-space-2); + padding: var(--chat-space-2) var(--chat-space-3); + border-bottom: 1px solid var(--chat-color-border); +} + +.chat-floating-title { + flex: 1; + margin: 0; + font-size: var(--chat-font-size); + font-weight: 700; +} + +.chat-floating-body { + flex: 1; + min-height: 0; + display: flex; + flex-direction: column; + overflow-y: auto; +} + +.chat-floating-body > .chat-dms { + padding: var(--chat-space-2); +} + +.chat-floating-body .chat-panel { + flex: 1; +} diff --git a/app/assets/css/chat-tokens.css b/app/assets/css/chat-tokens.css new file mode 100644 index 0000000..2b3ce4b --- /dev/null +++ b/app/assets/css/chat-tokens.css @@ -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); +} diff --git a/app/components/Chat/CommandPicker.vue b/app/components/Chat/CommandPicker.vue new file mode 100644 index 0000000..9614386 --- /dev/null +++ b/app/components/Chat/CommandPicker.vue @@ -0,0 +1,35 @@ + + + diff --git a/app/components/Chat/Composer.vue b/app/components/Chat/Composer.vue index 686426b..12eb12d 100644 --- a/app/components/Chat/Composer.vue +++ b/app/components/Chat/Composer.vue @@ -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(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(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(() => { + 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(() => ) /** 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 })
+
+
+ @@ -233,5 +341,6 @@ defineExpose({ focus })
{{ t('chat.composer.hint') }} + diff --git a/app/components/Chat/DeleteDialog.vue b/app/components/Chat/DeleteDialog.vue new file mode 100644 index 0000000..0e92c06 --- /dev/null +++ b/app/components/Chat/DeleteDialog.vue @@ -0,0 +1,94 @@ + + + diff --git a/app/components/Chat/Header.vue b/app/components/Chat/Header.vue index afa3866..b8958e9 100644 --- a/app/components/Chat/Header.vue +++ b/app/components/Chat/Header.vue @@ -1,19 +1,25 @@ + + diff --git a/app/components/Chat/Message.vue b/app/components/Chat/Message.vue index a069a0e..f3b4562 100644 --- a/app/components/Chat/Message.vue +++ b/app/components/Chat/Message.vue @@ -1,16 +1,43 @@ + + diff --git a/app/components/Chat/MessageList.vue b/app/components/Chat/MessageList.vue index 95b8367..73f2552 100644 --- a/app/components/Chat/MessageList.vue +++ b/app/components/Chat/MessageList.vue @@ -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(null) const sentinel = ref(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" /> +
+
+ + {{ row.input }} + {{ t('chat.commands.onlyYou') }} + +
+

{{ row.error }}

+
+
{{ announcement }}
+ diff --git a/app/components/Chat/Page.vue b/app/components/Chat/Page.vue index 59892e2..2a1ff2c 100644 --- a/app/components/Chat/Page.vue +++ b/app/components/Chat/Page.vue @@ -4,7 +4,8 @@ // inside (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() { diff --git a/app/components/Chat/Panel.vue b/app/components/Chat/Panel.vue index 6bbe1ff..8ae697f 100644 --- a/app/components/Chat/Panel.vue +++ b/app/components/Chat/Panel.vue @@ -1,6 +1,9 @@ + + diff --git a/app/components/Chat/ReactionBar.vue b/app/components/Chat/ReactionBar.vue new file mode 100644 index 0000000..36e9ebb --- /dev/null +++ b/app/components/Chat/ReactionBar.vue @@ -0,0 +1,205 @@ + + + diff --git a/app/components/Chat/StagingChips.vue b/app/components/Chat/StagingChips.vue new file mode 100644 index 0000000..fb17643 --- /dev/null +++ b/app/components/Chat/StagingChips.vue @@ -0,0 +1,36 @@ + + + diff --git a/app/components/Chat/ThreadPane.vue b/app/components/Chat/ThreadPane.vue new file mode 100644 index 0000000..ab65321 --- /dev/null +++ b/app/components/Chat/ThreadPane.vue @@ -0,0 +1,142 @@ + + + diff --git a/app/composables/useChat.ts b/app/composables/useChat.ts index ded73c7..1597c7b 100644 --- a/app/composables/useChat.ts +++ b/app/composables/useChat.ts @@ -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 = Object.freeze({ text: '', error: '', detail: '', sending: false }) +const EMPTY_DRAFT: Readonly = 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>('chat:olderError', () => ({})) /** Who is typing, per conversation (others only). */ const typing = useState>('chat:typing', () => ({})) + /** The allowed reaction keys from the server; null until loaded. */ + const allowedReactions = useState('chat:reactions', () => null) + const thread = useState('chat:thread', () => null) + /** Replies per thread root id, oldest first; absent until loaded. */ + const replies = useState>('chat:replies', () => ({})) + const repliesError = useState>('chat:repliesError', () => ({})) + const threadDrafts = useState>('chat:threadDrafts', () => ({})) + /** Thread mute per root id, as set in this session. */ + const threadMuted = useState>('chat:threadMuted', () => ({})) + /** Pinned message ids per channel id; absent until loaded. */ + const pinIds = useState>('chat:pinIds', () => ({})) + const pinMessages = useState>('chat:pinMessages', () => ({})) + const pinsError = useState>('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('chat:commands', () => null) + const ephemeral = useState>('chat:ephemeral', () => ({})) /** Presence of the open channel: Centrifugo client id to user id. */ const presenceClients = shallowRef>(new Map()) const presenceAvailable = ref(false) @@ -173,6 +237,17 @@ function createChatStore() { let generation = 0 let bootstrapping: Promise | null = null let membersLoading: Promise | null = null + let reactionsLoading: Promise | null = null + let commandsLoading: Promise | null = null + /** The latest reaction toggle per message: only its answer replaces the chips. */ + const reactionSeq = new Map() + // Attachments: the picked File per chip (kept for a retry) and the aborts of uploads in flight. + let fileSeq = 0 + const fileBlobs = new Map() + const fileAborts = new Map() + /** Replies already counted on their root's thread summary in this session. */ + const countedReplies = new Set() + let ephemeralSeq = 0 /** Channels whose conversation route ran this session (it makes the caller a participant). */ const joinedConversations = new Set() @@ -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 { + 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, 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 { + 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 + 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 { + 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, }) } diff --git a/app/lib/attachments.ts b/app/lib/attachments.ts new file mode 100644 index 0000000..8806726 --- /dev/null +++ b/app/lib/attachments.ts @@ -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 { + 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( + files: readonly F[], + limits: Pick, + stagedCount: number, + stagedBytes = 0, + messages: FileCheckMessages = PL_MESSAGES, +): FileCheck { + 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 } +} diff --git a/app/lib/client.ts b/app/lib/client.ts index ea4eb5e..bdfaace 100644 --- a/app/lib/client.ts +++ b/app/lib/client.ts @@ -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 { + 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 { + const finish = (status: number, json: unknown): ChatUploadAnswer => { + const body = unwrap | 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 { + 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(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(channels(context, `/channels/${channelId}/pins`), { method: 'POST', body: { message_id: messageId } }), + unpin: (context: { type: string; id: number }, channelId: number, messageId: number) => + request(channels(context, `/channels/${channelId}/pins/${messageId}`), { method: 'DELETE' }), + /** Edits your own text message; answers the message. */ + edit: (id: number, content: string) => request(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(chat('/reactions')), + /** Adds the user's reaction (idempotent); answers the message's reactions after the change. */ + addReaction: (id: number, key: string) => request(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(chat(`/messages/${id}/reactions/${encodeURIComponent(key)}`), { method: 'DELETE' }), + /** A thread's replies, oldest first. */ + replies: (rootId: number) => request(chat(`/messages/${rootId}/replies`)), + /** Posts a reply in a thread; answers the reply. */ + reply: (rootId: number, body: ChatSendBody) => request(chat(`/messages/${rootId}/replies`), { method: 'POST', body }), + /** Mutes or unmutes a thread for the caller. */ + muteThread: (rootId: number, muted: boolean) => request(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(joinUrl(bases.bots, '/dispatch'), { method: 'POST', body: { input } }), } } diff --git a/app/lib/linkEmbeds.ts b/app/lib/linkEmbeds.ts new file mode 100644 index 0000000..9cdd810 --- /dev/null +++ b/app/lib/linkEmbeds.ts @@ -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 = /(?"'`]+/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 `${escapeHtml(url)}${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() + // [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 +} diff --git a/i18n/locales/en.json b/i18n/locales/en.json index 361e3f9..12e98ae 100644 --- a/i18n/locales/en.json +++ b/i18n/locales/en.json @@ -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)" } } } diff --git a/i18n/locales/pl.json b/i18n/locales/pl.json index 983f14e..bc09999 100644 --- a/i18n/locales/pl.json +++ b/i18n/locales/pl.json @@ -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)" } } } diff --git a/nuxt.config.ts b/nuxt.config.ts index b7c9c34..01ef5ff 100644 --- a/nuxt.config.ts +++ b/nuxt.config.ts @@ -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