diff --git a/README.md b/README.md index d196d80d..eb110baa 100644 --- a/README.md +++ b/README.md @@ -89,7 +89,7 @@ devplacepy/ | `/admin/trash` | Admin **Trash**: review, restore, and permanently purge soft-deleted content (posts, comments, gists, projects, news, project files, attachments) across the platform | | `/admin/devii-tasks` | Admin **Devii tasks**: every scheduled task across all owners with its schedule, run count, expiry and failure streak, plus per-task disable and delete | | `/notifications` | Notification list, mark read, live unread counts (`/notifications/counts`) | -| `/messages` | Real-time direct messaging over WebSocket (`/messages/ws`): live bidirectional delivery, optimistic send, typing indicators, read receipts, reconnect catch-up, and online/last-seen presence. Messages render through the shared content pipeline (emoji shortcodes, image, video and audio embeds, autolink, sanitization). AI content correction and the AI modifier apply to direct messages: the original is delivered immediately, then a second `message` frame with `ai_processed` replaces the bubble for both participants when the rewrite lands (including across workers). An opened conversation loads its 500 most recent messages and can page older rows with `?before=`; switching threads does not drop the socket. `GET /messages/conversations` returns the conversation list as JSON for a live client refresh; the `POST /messages/send` form remains as a no-JavaScript fallback and now accepts an attachment-only, empty-content message. An administrator can delete the messages they themselves sent (`POST /messages/{uid}/delete`, soft delete, confirmation in the chat UI and in Devii); the bubble disappears live for both participants. `POST /messages/ws-ticket` exchanges a session/API-key auth to a short-lived (30s), single-use ticket a browser WebSocket can carry as `?ticket=...` on the handshake, since a native `WebSocket` cannot set an `Authorization`/`X-API-KEY` header - this is what makes off-session embedding of the chat possible. CLI: `devplace messaging prune-tickets` removes expired tickets | +| `/messages` | Real-time direct messaging over WebSocket (`/messages/ws`): live bidirectional delivery, optimistic send, typing indicators, read receipts, reconnect catch-up, and online/last-seen presence. Messages render through the shared content pipeline (emoji shortcodes, image, video and audio embeds, autolink, sanitization). AI content correction and the AI modifier apply to direct messages: the original is delivered immediately, then a second `message` frame with `ai_processed` replaces the bubble for both participants when the rewrite lands (including across workers). An opened conversation loads its 500 most recent messages and can page older rows with `?before=`; switching threads does not drop the socket. `GET /messages/conversations` returns the conversation list as JSON for a live client refresh; the `POST /messages/send` form remains as a no-JavaScript fallback and now accepts an attachment-only, empty-content message. An administrator can delete the messages they themselves sent (`POST /messages/{uid}/delete`, soft delete, confirmation in the chat UI and in Devii); the bubble disappears live for both participants. `POST /messages/ws-ticket` exchanges a session/API-key auth to a short-lived (30s), single-use ticket a browser WebSocket can carry as `?ticket=...` on the handshake, since a native `WebSocket` cannot set an `Authorization`/`X-API-KEY` header - this is what makes off-session embedding of the chat possible. CLI: `devplace messaging prune-tickets` removes expired tickets. On every other page the topnav Messages icon opens a **Chats** panel (people search, recent conversations, a New message button and a link to the full page), and picking a person opens a small chat window docked at the bottom of the screen, as on Facebook. Up to three windows sit side by side (fewer on narrow screens); a window minimizes to an avatar head that counts unread messages, and open chats survive page navigation within the tab. A profile's Send Message button and a message notification (the live toast and the entry on `/notifications`) open the same docked window instead of leaving the page. Phones keep the full `/messages` page. The message input follows the same layout everywhere: a + button reveals the attachment and GIF buttons, which tuck away again while you type, and the emoji button sits inside the text field | | `/votes` | Upvote/downvote on posts, comments, projects | | `/reactions` | Emoji reactions on posts, comments, gists, projects | | `/bookmarks` | Save/unsave content; `/bookmarks/saved` personal list | @@ -262,7 +262,7 @@ DevPlace is open in the sense that it does not editorialise technical opinion. I ## GIF picker (GIPHY) -A "GIF" button beside the attachment button in the post composer, every comment form and the message input opens a searchable GIPHY panel (trending first, "Powered by GIPHY" attribution). A picked GIF is downloaded by the server and stored as an ordinary attachment, so it renders in the attachment gallery, can be reported and deleted like any file, and counts against the normal attachment limits. +A "GIF" button beside the attachment button in the post composer, every comment form and the message input (behind its + button) opens a searchable GIPHY panel (trending first, "Powered by GIPHY" attribution). A picked GIF is downloaded by the server and stored as an ordinary attachment, so it renders in the attachment gallery, can be reported and deleted like any file, and counts against the normal attachment limits. An administrator enters the GIPHY API key under **Admin > Services > Giphy** (also the content rating, default `pg`, and the API base URL); the key is stored in `site_settings`, never reaches a browser, and the button stays hidden until it is set. Searches run on the server, are cached for five minutes, and each member may make 30 per minute. Routes: `GET /giphy/status`, `/giphy/search?q=`, `/giphy/trending`, `POST /giphy/attach` (documented under Uploads at `/docs/uploads.html`); Devii has `search_gifs`, `trending_gifs` and `attach_gif`. Details: `devplacepy/services/giphy/CLAUDE.md`. diff --git a/devplacepy/services/messaging/CLAUDE.md b/devplacepy/services/messaging/CLAUDE.md index a8b9260f..bd6d2645 100644 --- a/devplacepy/services/messaging/CLAUDE.md +++ b/devplacepy/services/messaging/CLAUDE.md @@ -87,6 +87,10 @@ Live/echoed message bubbles are NEVER injected as raw HTML. `AppChat._buildBubbl The messaging frontend is the single self-booting custom element `` (`static/js/components/AppChat.js`), which replaced the old page-controller trio `MessagesLayout.js`/`MessagesSocket.js`/`MessageSearch.js` (all deleted) and `messages.css` (superseded by `static/css/chat.css`) - see `devplacepy/static/js/CLAUDE.md` for the component roster entry. `MobileNav.js` does **not** own the mobile pane (that duplicate was removed; `dp-chat` is the only pane controller). `templates/messages.html` renders `` wrapping the SAME server-rendered `.messages-list`/`.messages-main`/`.messages-thread`/`.message-bubble` markup as before (no-JS/crawler fallback), which the component *adopts* on `connectedCallback` rather than discarding. It owns a `ChatSocket` (`static/js/chat/ChatSocket.js`, exponential backoff, `4013` fast-path, 25s ping), sends over WS with an optimistic pending bubble keyed by `client_id`, reconciles on the echoed `message` frame, applies later `ai_processed` frames in place (compare `dp-content[data-source]`, never rendered `textContent`), injects the Report control on every live incoming bubble, catches up with `{type:"sync"}` on reconnect, and switches conversations without dropping the socket (`GET /messages?with_uid=` JSON + `history.pushState`). Older history loads via `GET /messages?with_uid=&before=` when the thread is scrolled to the top. Mobile: CSS hides the inactive pane from `with-uid` / `.show-list` before JS runs (no stacked FOUC); the composer does not auto-focus on coarse pointers; keyboard inset uses `visualViewport.offsetTop + height`; Enter-to-send is desktop-only. **The send button is disabled while `dp-upload` is busy AND while a genuine new send is in flight** (the send-lock, see "Send dedupe" above) - a `.failed`-bubble retry never engages it, so retrying an old message never blocks typing/sending a new one. Presence in `mode="page"` stays on the page-global `PresenceManager`. An opt-in `ai-indicator="true"` attribute shows "Adjusting..." while `ai_pending` and "Adjusted by AI" when the revision lands. Styling is in `static/css/chat.css` using `variables.css` tokens only, responsive down to 360px. +**Composer layout (every mode).** The message form is `[+] [composer-tools] [composer-field] [send]`: the `.composer-more-btn` toggles `tools-open` on the form, revealing `.composer-tools` (`dp-upload` and `dp-gif-picker`); typing collapses the tools again unless an upload is in flight or attachments are pending, a starting upload (paste, drop, pick) opens them so the count stays visible, and a send collapses them. The textarea lives inside `.composer-field`, the pill that also holds the emoji button (`ContentEnhancer.initEmojiPickers` appends the button into the field and re-homes the picker popup onto the form, and the GIF panel is positioned against the form too, so neither popup is clipped by the narrow pill). `messages.html` and `AppChat._buildComposer` emit the identical structure. + +**Docked windows (`mode="window"`).** On every page except `/messages`, `dp-chat-dock` (see `devplacepy/static/js/CLAUDE.md`) hosts small `dp-chat mode="window"` elements. Window mode builds its own skeleton (header via `_buildHeader` with avatar and name, no back button, no element ids so several windows can coexist), loads history through the same `GET /messages?with_uid=` JSON the page uses (`_loadConversation`, which also marks the conversation and its notifications read) **before** subscribing to the shared socket, so the reconnect `sync` starts from the newest loaded stamp, and never touches `history`. Its thread always counts as active (`_activePane = "thread"`), so read receipts and the active-conversation marker behave exactly as on the page. No server change was needed: the dock uses only `/messages/conversations`, `/messages/search`, `GET /messages?with_uid=` and `WS /messages/ws`. + **Auto-scroll never fights a manual scroll-up.** `_startScrollWatcher`/`_stabilizeScroll` force `scrollTop = scrollHeight` on every thread mutation (new bubble, attachment/image finishing loading) ONLY while `_userAtBottom` is true, re-checked every `requestAnimationFrame` up to `STABILIZE_MAX_FRAMES`. The one thing that used to break this: while a multi-frame stabilize loop was in flight (`_stabilizePending`), the real `scroll` event listener (`_bindAutoScroll`) ignored EVERY scroll event outright, including a genuine user wheel/touch scroll-up that happened to land inside that window - so a rapid burst of incoming messages (each restarting the stabilize loop while attachments were still loading) could silently overwrite a user's attempt to scroll up to read history. The fix: every programmatic scroll (`_scrollThreadToEnd`, `_stabilizeScroll`) records the exact `scrollTop` it just set in `_lastForcedScrollTop`; the `scroll` listener only skips its own echo (`_stabilizePending && scrollTop === _lastForcedScrollTop`) and always processes a scroll that lands anywhere else, so a real user scroll-up is detected and `_userAtBottom` flips to `false` immediately, even mid-stabilization. Never gate scroll-intent detection on `_stabilizePending` alone again. ## Attachments stream live diff --git a/devplacepy/static/css/CLAUDE.md b/devplacepy/static/css/CLAUDE.md index dac4d9fa..cf27581d 100644 --- a/devplacepy/static/css/CLAUDE.md +++ b/devplacepy/static/css/CLAUDE.md @@ -20,7 +20,7 @@ Every `z-index` is a token from `variables.css`; literal values are forbidden ex | Band | Order (bottom to top) | |------|-----------------------| -| Content | `--z-fab` 900, `--z-nav-overlay` 998, `--z-nav-panel` 999, `--z-nav` 1000, `--z-nav-drop` 1001, `--z-modal` 2000, `--z-popover` 2100, `--z-lightbox` 10000 | +| Content | `--z-fab` 900, `--z-chat-dock` 950, `--z-nav-overlay` 998, `--z-nav-panel` 999, `--z-nav` 1000, `--z-nav-drop` 1001, `--z-modal` 2000, `--z-popover` 2100, `--z-lightbox` 10000 | | Chrome | `--z-chrome-fw` 2147480000, `--z-chrome-devii` 2147483000, `--z-chrome-toast` 2147483400, `--z-chrome-menu` 2147483500, `--z-chrome-dialog` 2147483647 | The chrome band is **user-CSS-proof by design**: per-user injected CSS (the customization feature) must never stack above floating windows, the Devii terminal, toasts, the context menu, or confirm dialogs, so they live at the top of the integer range AND carry `will-change: transform` (the layer-promotion group in `base.css` - any new always-on fixed chrome element must join both). Toasts sit in the chrome band deliberately: they fire over open modals and stay clickable. The Devii tutorial-overlay ladder (2147483600-602 in `devii.css`) is an intentional local sequence between `--z-chrome-menu` and the devii avatar. A new stacked element picks the matching token or adds one between two stops in `variables.css` - never a number at the use site. diff --git a/devplacepy/static/css/base.css b/devplacepy/static/css/base.css index 14b0da06..48989dbd 100644 --- a/devplacepy/static/css/base.css +++ b/devplacepy/static/css/base.css @@ -1050,6 +1050,8 @@ body:has(.page-messages) { .context-menu, .dp-toast-host, .feed-fab, +.chat-panel, +.chat-dock-tray, .lightbox-overlay { will-change: transform; } diff --git a/devplacepy/static/css/chat-dock.css b/devplacepy/static/css/chat-dock.css new file mode 100644 index 00000000..6f1f18e4 --- /dev/null +++ b/devplacepy/static/css/chat-dock.css @@ -0,0 +1,352 @@ +/* retoor */ + +dp-chat-dock { + --chat-window-width: 328px; + --chat-window-height: 455px; + --chat-panel-width: 360px; + --chat-head-size: 48px; + --chat-icon-size: 28px; + --chat-fab-lane: 64px; + display: contents; +} + +.chat-icon-btn { + flex-shrink: 0; + width: var(--chat-icon-size); + height: var(--chat-icon-size); + padding: 0; + display: inline-flex; + align-items: center; + justify-content: center; + background: none; + border: none; + border-radius: 50%; + color: var(--text-secondary); + font-size: 0.9375rem; + line-height: 1; + cursor: pointer; + text-decoration: none; +} + +.chat-icon-btn:hover, +.chat-icon-btn:focus-visible { + background: var(--bg-card-hover); + color: var(--text-primary); +} + +/* ── Chats panel (opened from the topnav Messages icon) ─── */ + +.chat-panel { + position: fixed; + top: calc(var(--nav-height) + var(--space-xs)); + right: var(--space-lg); + z-index: var(--z-nav-drop); + width: var(--chat-panel-width); + max-width: calc(100vw - var(--space-2xl)); + max-height: calc(100vh - var(--nav-height) - var(--space-2xl)); + display: flex; + flex-direction: column; + background: var(--bg-secondary); + border: 1px solid var(--border-light); + border-radius: var(--radius-lg); + box-shadow: var(--shadow-lg); +} + +.chat-panel[hidden] { + display: none; +} + +.chat-panel-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: var(--space-sm); + padding: var(--space-md) var(--space-lg) var(--space-sm); +} + +.chat-panel-title { + font-size: 1.25rem; + font-weight: 700; +} + +.chat-panel-search { + padding: 0 var(--space-lg) var(--space-sm); +} + +.chat-panel-search-input { + width: 100%; + margin: 0; + font-size: 0.875rem; +} + +.chat-panel-list { + flex: 1; + min-height: 0; + overflow-y: auto; + overscroll-behavior: contain; + padding: 0 var(--space-sm) var(--space-sm); +} + +.chat-panel-list .conversation-item, +.chat-compose-results .conversation-item { + border-radius: var(--radius); + color: var(--text-primary); + text-decoration: none; +} + +.chat-panel-list .empty-state, +.chat-compose-results .empty-state { + padding: var(--space-xl) var(--space-lg); + font-size: 0.875rem; +} + +.chat-panel-footer { + display: block; + flex-shrink: 0; + padding: var(--space-md); + border-top: 1px solid var(--border); + text-align: center; + font-size: 0.875rem; + font-weight: 600; +} + +/* ── Bottom tray: docked chat windows + minimized heads ─── */ + +.chat-dock-tray { + position: fixed; + right: var(--space-lg); + bottom: 0; + z-index: var(--z-chat-dock); + display: flex; + align-items: flex-end; + gap: var(--space-sm); + max-width: calc(100vw - var(--space-2xl)); + pointer-events: none; +} + +body:has(.feed-fab) .chat-dock-tray { + right: calc(var(--space-2xl) + var(--chat-fab-lane) + var(--space-sm)); +} + +.chat-dock-windows { + display: flex; + align-items: flex-end; + gap: var(--space-sm); + min-width: 0; +} + +.chat-dock-heads { + display: flex; + flex-direction: column-reverse; + align-items: center; + gap: var(--space-sm); + padding-bottom: var(--space-lg); +} + +.chat-dock-heads:empty { + display: none; +} + +.chat-window, +.chat-head { + pointer-events: auto; +} + +.chat-window { + position: relative; + width: var(--chat-window-width); + height: var(--chat-window-height); + max-height: calc(100vh - var(--nav-height) - var(--space-lg)); + display: flex; + flex-direction: column; + min-width: 0; + background: var(--bg-card); + border: 1px solid var(--border-light); + border-bottom: none; + border-radius: var(--radius-lg) var(--radius-lg) 0 0; + box-shadow: var(--shadow-lg); +} + +dp-chat[mode="window"] { + display: flex; + flex-direction: column; + flex: 1; + min-height: 0; +} + +dp-chat[mode="window"] .messages-main { + flex: 1; +} + +.chat-window .messages-main-header { + gap: var(--space-sm); + padding: var(--space-sm) var(--space-sm) var(--space-sm) var(--space-md); + border-radius: var(--radius-lg) var(--radius-lg) 0 0; + cursor: pointer; +} + +.chat-window .messages-main-header:hover { + background: var(--bg-card-hover); +} + +.chat-window .messages-header-info { + flex: 1; +} + +.chat-window .messages-main-header h3 { + font-size: 0.9375rem; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.chat-window-actions { + display: flex; + align-items: center; + gap: var(--space-xs); + margin-left: auto; +} + +.chat-window .messages-thread { + padding: var(--space-md); + padding-bottom: var(--space-sm); + gap: var(--space-sm); +} + +.chat-window .message-bubble { + max-width: 80%; + padding: var(--space-sm) var(--space-md); + font-size: 0.8125rem; +} + +.chat-window .message-bubble.grouped { + margin-top: calc(var(--space-xs) - var(--space-sm)); +} + +.chat-window .messages-input-area { + gap: var(--space-xs); + min-height: 0; + padding: var(--space-sm); +} + +.chat-window .messages-input-area textarea { + padding: var(--space-xs) var(--space-sm); + font-size: 0.8125rem; +} + +.chat-window .messages-send-btn, +.chat-window .composer-more-btn { + width: var(--chat-icon-size); + height: var(--chat-icon-size); + margin-bottom: var(--space-xs); + font-size: 0.875rem; +} + +.chat-window .composer-more-btn { + font-size: 1.25rem; +} + +.chat-window .composer-tools { + min-height: var(--chat-icon-size); + margin-bottom: var(--space-xs); +} + +.chat-window .messages-jump-new { + bottom: calc(var(--chat-head-size) + var(--space-lg)); +} + +/* ── New message window ─────────────────────────────────── */ + +.chat-window-compose .messages-main-header { + cursor: default; + border-bottom: 1px solid var(--border); +} + +.chat-window-compose .messages-main-header:hover { + background: none; +} + +.chat-compose-to { + padding: var(--space-sm) var(--space-md); + border-bottom: 1px solid var(--border); +} + +.chat-compose-to label { + display: flex; + align-items: center; + gap: var(--space-sm); + font-size: 0.875rem; + color: var(--text-muted); +} + +.chat-compose-input { + flex: 1; + min-width: 0; + margin: 0; + font-size: 0.875rem; +} + +.chat-compose-results { + flex: 1; + min-height: 0; + overflow-y: auto; + overscroll-behavior: contain; + padding: var(--space-xs); +} + +/* ── Minimized chat heads ───────────────────────────────── */ + +.chat-head { + position: relative; +} + +.chat-head-open { + position: relative; + display: block; + padding: 0; + background: none; + border: none; + border-radius: 50%; + box-shadow: var(--shadow-lg); + cursor: pointer; +} + +.chat-head-open .avatar-img { + width: var(--chat-head-size); + height: var(--chat-head-size); +} + +.chat-head-badge { + top: 0; + right: 0; +} + +.chat-head .chat-head-close { + position: absolute; + top: calc(var(--space-xs) * -1); + left: calc(var(--space-xs) * -1); + width: var(--space-xl); + height: var(--space-xl); + font-size: 0.6875rem; + background: var(--bg-secondary); + border: 1px solid var(--border-light); + opacity: 0; + transition: opacity 0.1s ease; +} + +.chat-head:hover .chat-head-close, +.chat-head:focus-within .chat-head-close { + opacity: 1; +} + +@media (max-width: 1024px) { + body:has(.feed-fab) .chat-dock-tray { + right: calc(var(--space-lg) + var(--chat-fab-lane) + var(--space-sm)); + } +} + +@media (max-width: 768px) { + dp-chat-dock { + display: none; + } +} diff --git a/devplacepy/static/css/chat.css b/devplacepy/static/css/chat.css index 3dda1046..6189ed40 100644 --- a/devplacepy/static/css/chat.css +++ b/devplacepy/static/css/chat.css @@ -448,6 +448,7 @@ dp-chat[mode="embed"] { } .messages-input-area { + position: relative; padding: var(--space-md) var(--space-lg); padding-bottom: calc(var(--space-md) + env(safe-area-inset-bottom)); border-top: 1px solid var(--border); @@ -459,6 +460,65 @@ dp-chat[mode="embed"] { background: var(--bg-card); } +.composer-more-btn { + flex-shrink: 0; + width: 36px; + height: 36px; + padding: 0; + display: flex; + align-items: center; + justify-content: center; + background: none; + border: none; + border-radius: 50%; + color: var(--accent); + font-size: 1.5rem; + font-weight: 700; + line-height: 1; + cursor: pointer; + transition: transform 0.15s ease, background 0.15s ease; +} + +.composer-more-btn:hover { + background: var(--bg-card-hover); +} + +.messages-input-area.tools-open .composer-more-btn { + transform: rotate(45deg); +} + +.composer-tools { + display: none; + flex-shrink: 0; + align-items: center; + gap: var(--space-xs); + min-height: 36px; +} + +.messages-input-area.tools-open .composer-tools { + display: flex; +} + +.composer-field { + flex: 1; + min-width: 0; + display: flex; + align-items: flex-end; + background: var(--bg-secondary); + border: 1px solid var(--border); + border-radius: var(--radius-xl); +} + +.composer-field:focus-within { + border-color: var(--accent); +} + +.composer-field .emoji-toggle-btn { + flex-shrink: 0; + padding: var(--space-xs) var(--space-sm); + line-height: 1.5; +} + .messages-input-area .mention-wrapper { flex: 1; min-width: 0; @@ -480,9 +540,9 @@ dp-chat[mode="embed"] { padding: var(--space-sm) var(--space-md); font-family: inherit; font-size: 0.875rem; - border-radius: var(--radius); - background: var(--bg-secondary); - border: 1px solid var(--border); + border-radius: var(--radius-xl); + background: none; + border: none; color: var(--text-primary); outline: none; } @@ -494,10 +554,6 @@ dp-chat[mode="embed"] { } } -.messages-input-area textarea:focus { - border-color: var(--accent); -} - .messages-input-area textarea::placeholder { color: var(--text-muted); } @@ -517,20 +573,13 @@ dp-chat[mode="embed"] { } .messages-input-area dp-gif-picker { + position: static; flex-shrink: 0; - align-items: flex-end; } .messages-input-area .gif-picker-wrapper { - left: auto; - right: 0; -} - -@media (max-width: 480px) { - .messages-input-area .gif-picker-wrapper { - left: var(--space-sm); - right: var(--space-sm); - } + left: var(--space-sm); + width: min(22rem, calc(100% - var(--space-lg))); } .messages-send-btn { @@ -726,6 +775,7 @@ dp-chat[mode="embed"] { min-height: 44px; } + .composer-more-btn, .messages-send-btn { width: 44px; height: 44px; diff --git a/devplacepy/static/css/components.css b/devplacepy/static/css/components.css index 509c48ca..43f05f04 100644 --- a/devplacepy/static/css/components.css +++ b/devplacepy/static/css/components.css @@ -484,6 +484,7 @@ dp-gif-picker[hidden] { .dp-toast-link { cursor: pointer; + pointer-events: auto; } .dp-toast-success { diff --git a/devplacepy/static/css/variables.css b/devplacepy/static/css/variables.css index 291f455d..9930ba50 100644 --- a/devplacepy/static/css/variables.css +++ b/devplacepy/static/css/variables.css @@ -64,6 +64,7 @@ --max-content: 1200px; --z-fab: 900; + --z-chat-dock: 950; --z-nav-overlay: 998; --z-nav-panel: 999; --z-nav: 1000; diff --git a/devplacepy/static/js/Application.js b/devplacepy/static/js/Application.js index 8e5b5651..f41ff28b 100644 --- a/devplacepy/static/js/Application.js +++ b/devplacepy/static/js/Application.js @@ -119,7 +119,8 @@ class Application { this.planningGenerator = new PlanningGenerator(); this.mediaGallery = new MediaGallery(); this.reportDialog = new ReportDialog(); - this.liveNotifications = new LiveNotifications(this.pubsub, this.toast); + this.chatDock = document.querySelector("dp-chat-dock"); + this.liveNotifications = new LiveNotifications(this.pubsub, this.toast, this.chatDock); this.presence = new PresenceManager(this.pubsub); this.onlineUsers = new OnlineUsers(this.pubsub); this.localTime = new LocalTime(); diff --git a/devplacepy/static/js/CLAUDE.md b/devplacepy/static/js/CLAUDE.md index 8a3d6c39..4081c4e9 100644 --- a/devplacepy/static/js/CLAUDE.md +++ b/devplacepy/static/js/CLAUDE.md @@ -14,7 +14,7 @@ This file documents JS module organization, custom web components, and shared fr ## Custom web components (`static/js/components/`) Self-contained, presentational UI is built as custom elements with the `dp-` prefix: -`dp-avatar`, `dp-code`, `dp-content`, `dp-title`, `dp-toast`, `dp-dialog`, `dp-context-menu`, `dp-upload`, `dp-gif-picker`, `dp-lightbox`, `dp-chat`, `dp-quiz-player`, `dp-quiz-builder`. +`dp-avatar`, `dp-code`, `dp-content`, `dp-title`, `dp-toast`, `dp-dialog`, `dp-context-menu`, `dp-upload`, `dp-gif-picker`, `dp-lightbox`, `dp-chat`, `dp-chat-dock`, `dp-quiz-player`, `dp-quiz-builder`. `dp-quiz-player` (`AppQuizPlayer.js`) and `dp-quiz-builder` (`AppQuizBuilder.js`) both **adopt** server-rendered markup rather than building it (the `dp-chat` `mode="page"` pattern): the player intercepts each question's real `
` through `Http.sendForm`, renders the graded result in place, shows a `Checking…` state while a `free_text` grade is in flight, ticks the remaining time from `Format.duration`, and advances to the next slide; the builder toggles the kind-specific field groups from the question-kind picker and submits the add-question form through `Http.sendForm`. Neither re-renders a prompt (the server already rendered it through `render_content`), neither opens a WebSocket, and neither implements a fetch wrapper, a poller or a dialog. Removing the JS leaves a fully working no-JS quiz. @@ -22,6 +22,8 @@ Self-contained, presentational UI is built as custom elements with the `dp-` pre `dp-chat` (`AppChat.js`) is the Slack-like DM chat widget that fully replaced the old page-controller trio `MessagesLayout.js`/`MessagesSocket.js`/`MessageSearch.js` (deleted) and `static/css/messages.css` (superseded by `static/css/chat.css`) on `/messages`. Unlike every other component here, it does NOT build its DOM from scratch on `connectedCallback` when server-rendered light-DOM children already exist (`mode="page"`) - it **adopts** the existing `.messages-list`/`.messages-main`/`.messages-thread`/`.message-bubble` markup `templates/messages.html` still renders (so no-JS and crawler fallback both keep working) and only builds a from-scratch skeleton when none is present (`mode="embed"`, a standalone `` usable outside `/messages`). It owns its own `ChatSocket` instance, the conversation search dropdown (absorbed from the old `MessageSearch.js`, still built on the shared `ListNav` utility), consecutive-message grouping (`chat/MessageGrouping.js`), a working optimistic send with `.pending`/`.failed` (tap-to-retry) bubble states, and an opt-in (`ai-indicator` attribute) "Adjusted by AI" caption shown when a reconciled echo's `ai_processed` frame flag is true and the content changed from what was locally typed - never a diff/revert UI, the backend keeps no pre-correction copy to diff against. Presence needs no component code at all: the adopted markup keeps its `data-presence-uid` attributes, so the page-global `PresenceManager` (below) already drives it, and the conversation list it builds live uses the shared `Avatar.badgeElement(user)` rather than hand-rolled dot markup. In `mode="embed"`, where no page-global instance may exist, it constructs a root-scoped `PresenceManager` instead of re-implementing presence - `dp-chat` owns no presence logic of its own. The message body itself keeps rendering through `` (see "CLIENT-only now" below) - the redesign only removed the historical `no-copy` attribute on message bubbles so `dp-content`'s own existing `.content-copy-btn` doubles as the hover/focus-reveal action toolbar's Copy button (§6.3 of the design doc it was built from), instead of a second copy mechanism being hand-rolled. +`dp-chat-dock` (`AppChatDock.js`, `app.chatDock`) is the Facebook-style docked chat, server-rendered once in `base.html` (block `chat_dock`, members only; `messages.html` empties the block so `/messages` has no dock). It builds the **Chats panel** (opened by any `[data-chat-panel-toggle]`, the topnav Messages icon; people search via `ListNav`, recent conversations from `/messages/conversations`, a New message compose window) and a bottom-right **tray** of chat windows plus minimized avatar heads. Each window is a plain `dp-chat` with `mode="window"`, so every chat behaviour (optimistic send, reconcile, AI frames, typing, receipts, delete, report, attachments, older history) is the one `AppChat` implementation. Rules that keep it correct: window `dp-chat` elements are **never moved in the DOM** (moving a custom element runs `disconnectedCallback`, which closes its socket channel, and the `_built` guard skips the rebuild), so windows are appended in creation order and removed, never reordered; a minimized window is destroyed and re-created on expand, which reloads its history and marks it read, so a head never marks anything read; open/minimized state lives in `sessionStorage` (per tab, the `ScrollMemory` precedent) under `devplace.chat-dock.`; at the 768px mobile breakpoint the dock renders nothing and every trigger falls through to its `href` (the full `/messages` page). Any element with `data-chat-open=""` (plus `data-chat-username`/`data-chat-avatar-seed`, emitted by the `_chat_open_attrs.html` partial) opens a window on click: the profile Send Message button and the `/notifications` card link of a `message` notification use it, and `LiveNotifications` routes a `message` toast's click through `app.chatDock.open()` and falls back to the URL when it returns `false`. All windows share ONE WebSocket through `chat/ChatSocketHub.js`: `subscribe(handlers)` returns a channel with the `ChatSocket` surface (`send`/`isOpen`/`close`, where `close` unsubscribes), the socket opens on the first subscriber and closes with the last, and a late subscriber gets `onReady` on a microtask. A `dp-chat` given `.hub` subscribes instead of opening its own socket, and drops `error` frames whose `client_id` is not one of its own pending sends. `chat/ConversationItem.js` is the one `.conversation-item` builder shared by `/messages` and the dock. `dp-chat` dispatches a bubbling `dp-chat:conversation` event (detail `{user}`) after it renders a conversation, which the dock uses to learn a window's partner name and to refresh the unread counters. + `static/js/chat/ChatSocket.js` and `static/js/chat/MessageGrouping.js` are chat-scoped helpers used only by `AppChat.js` - `ChatSocket` is modeled on `PubSubClient.js`'s real exponential backoff (200ms doubling to a 5000ms cap, reset on a successful connect) rather than the flat-delay retry the deleted `MessagesSocket.js` used, and preserves the same `4013` "wrong worker" fast-retry special case. `MessageGrouping.shouldGroup(previous, current)` is the one pure predicate (<=300s gap, same sender) shared by both the initial-history grouping pass and the live-append path, so the two can never disagree. Neither file is a general-purpose "do not reimplement" utility for the rest of the app (see the out-of-scope note in the design document this shipped from) - they are not added to the do-not-reimplement list below; a future non-chat WebSocket feature should keep hand-rolling its own client (as `DeviiSocket.js`/`DeepsearchProgressSocket.js`/`SeoProgressSocket.js`/`AppDeepsearchChat.js`'s inline socket already do) rather than reaching into `chat/`. Conventions: diff --git a/devplacepy/static/js/ContentEnhancer.js b/devplacepy/static/js/ContentEnhancer.js index dac99a3c..7bc8dd0c 100644 --- a/devplacepy/static/js/ContentEnhancer.js +++ b/devplacepy/static/js/ContentEnhancer.js @@ -57,6 +57,12 @@ export class ContentEnhancer { return; } if (form && form.classList.contains("messages-input-area")) { + form.appendChild(picker.wrapper); + const field = textarea.closest(".composer-field"); + if (field) { + field.appendChild(btn); + return; + } const sendBtn = form.querySelector(".messages-send-btn"); if (sendBtn) form.insertBefore(btn, sendBtn); else form.appendChild(btn); diff --git a/devplacepy/static/js/DeviiTerminal.js b/devplacepy/static/js/DeviiTerminal.js index 588cfb7d..2aad64f4 100644 --- a/devplacepy/static/js/DeviiTerminal.js +++ b/devplacepy/static/js/DeviiTerminal.js @@ -94,6 +94,7 @@ export class DeviiTerminal { if (document.querySelector(".modal-overlay.visible")) return false; if (document.querySelector(".dialog-overlay.visible")) return false; if (document.querySelector(".context-menu.visible")) return false; + if (document.querySelector(".chat-panel:not([hidden])")) return false; const mobilePanel = document.getElementById("mobile-panel"); if (mobilePanel && mobilePanel.classList.contains("open")) return false; const active = document.activeElement; diff --git a/devplacepy/static/js/LiveNotifications.js b/devplacepy/static/js/LiveNotifications.js index 9be6c646..38b26f09 100644 --- a/devplacepy/static/js/LiveNotifications.js +++ b/devplacepy/static/js/LiveNotifications.js @@ -3,9 +3,10 @@ const TOAST_MS = 6000; export class LiveNotifications { - constructor(pubsub, toast) { + constructor(pubsub, toast, chatDock = null) { this.pubsub = pubsub; this.toast = toast; + this.chatDock = chatDock; this.uid = document.body.dataset.userUid || ""; if (!this.uid) return; this.topic = `user.${this.uid}.notifications`; @@ -14,15 +15,30 @@ export class LiveNotifications { onNotification(data) { if (!data || !data.message) return; - this.toast.show(data.message, { - type: "info", - ms: TOAST_MS, - url: this._openUrl(data), - }); + const url = this._openUrl(data); + const options = { type: "info", ms: TOAST_MS, url }; + const chatUid = this._chatUid(data); + if (chatUid && this.chatDock) { + options.onClick = (event) => { + if (!this.chatDock.open({ uid: chatUid })) { + window.location.href = url; + return; + } + event.currentTarget.remove(); + }; + } + this.toast.show(data.message, options); } _openUrl(data) { if (data.uid) return `/notifications/open/${data.uid}`; return data.target_url || "/notifications"; } + + _chatUid(data) { + if (data.type !== "message" || !data.target_url) return null; + const target = new URL(data.target_url, window.location.origin); + if (target.pathname !== "/messages") return null; + return target.searchParams.get("with_uid"); + } } diff --git a/devplacepy/static/js/chat/ChatSocket.js b/devplacepy/static/js/chat/ChatSocket.js index b40bc276..28cff44b 100644 --- a/devplacepy/static/js/chat/ChatSocket.js +++ b/devplacepy/static/js/chat/ChatSocket.js @@ -7,6 +7,13 @@ const MAX_BACKOFF_MS = 5000; const PING_MS = 25000; export class ChatSocket { + static resolveUrl(path) { + if (/^wss?:\/\//i.test(path)) return path; + const scheme = location.protocol === "https:" ? "wss:" : "ws:"; + const normalized = path.startsWith("/") ? path : `/${path}`; + return `${scheme}//${location.host}${normalized}`; + } + constructor(url, handlers) { this.url = url; this.handlers = handlers || {}; diff --git a/devplacepy/static/js/chat/ChatSocketHub.js b/devplacepy/static/js/chat/ChatSocketHub.js new file mode 100644 index 00000000..68001a54 --- /dev/null +++ b/devplacepy/static/js/chat/ChatSocketHub.js @@ -0,0 +1,72 @@ +// retoor + +import { ChatSocket } from "./ChatSocket.js"; + +export class ChatSocketHub { + constructor(url) { + this.url = url; + this.socket = null; + this.ready = null; + this.subscribers = new Set(); + } + + subscribe(handlers) { + this.subscribers.add(handlers); + if (!this.socket) { + this._connect(); + } else if (this.ready) { + queueMicrotask(() => { + if (this.ready && this.subscribers.has(handlers)) this._call(handlers, "onReady", this.ready); + }); + } + return { + send: (frame) => this.send(frame), + isOpen: () => this.isOpen(), + close: () => this._unsubscribe(handlers), + }; + } + + send(frame) { + return !!this.socket && this.socket.send(frame); + } + + isOpen() { + return !!this.socket && this.socket.isOpen(); + } + + _connect() { + const socket = new ChatSocket(this.url, { + onReady: (payload) => { + if (this.socket !== socket) return; + this.ready = payload; + this._emit("onReady", payload); + }, + onMessage: (frame) => { + if (this.socket === socket) this._emit("onMessage", frame); + }, + onClose: (event) => { + if (this.socket !== socket) return; + this.ready = null; + this._emit("onClose", event); + }, + }); + this.socket = socket; + socket.connect(); + } + + _unsubscribe(handlers) { + this.subscribers.delete(handlers); + if (this.subscribers.size || !this.socket) return; + this.socket.close(); + this.socket = null; + this.ready = null; + } + + _emit(name, payload) { + for (const handlers of [...this.subscribers]) this._call(handlers, name, payload); + } + + _call(handlers, name, payload) { + if (typeof handlers[name] === "function") handlers[name](payload); + } +} diff --git a/devplacepy/static/js/chat/ConversationItem.js b/devplacepy/static/js/chat/ConversationItem.js new file mode 100644 index 00000000..dd9900e1 --- /dev/null +++ b/devplacepy/static/js/chat/ConversationItem.js @@ -0,0 +1,62 @@ +// retoor + +import { Avatar } from "../Avatar.js"; +import { contentRenderer } from "../ContentRenderer.js"; + +const PREVIEW_CHARS = 60; + +export class ConversationItem { + static build(conv, activeUid = null) { + const user = conv.other_user || {}; + const active = !!user.uid && user.uid === activeUid; + const item = document.createElement("a"); + item.href = `/messages?with_uid=${user.uid || ""}`; + item.className = `conversation-item${active ? " active" : ""}`; + item.dataset.convUid = user.uid || ""; + item.dataset.convUsername = user.username || ""; + item.dataset.convAvatarSeed = user.avatar_seed || ""; + item.setAttribute("role", "listitem"); + if (active) item.setAttribute("aria-current", "true"); + + item.appendChild(Avatar.badgeElement(user)); + + const info = document.createElement("div"); + info.className = "conversation-info"; + const name = document.createElement("div"); + name.className = "conversation-name"; + name.textContent = user.username || ""; + const preview = document.createElement("div"); + preview.className = "conversation-preview"; + preview.textContent = contentRenderer.preview(conv.last_message, PREVIEW_CHARS); + info.append(name, preview); + item.appendChild(info); + + const unread = document.createElement("span"); + unread.className = "conversation-unread-dot"; + unread.hidden = !conv.unread; + const sr = document.createElement("span"); + sr.className = "sr-only"; + sr.textContent = "Unread messages"; + unread.appendChild(sr); + item.appendChild(unread); + + const time = document.createElement("span"); + time.className = "conversation-time"; + if (conv.last_message_at) { + time.setAttribute("datetime", conv.last_message_at); + time.dataset.dt = ""; + time.dataset.dtMode = "ago"; + if (window.app && window.app.localTime) window.app.localTime.apply(time); + } + item.appendChild(time); + return item; + } + + static user(item) { + return { + uid: item.dataset.convUid || "", + username: item.dataset.convUsername || "", + avatar_seed: item.dataset.convAvatarSeed || "", + }; + } +} diff --git a/devplacepy/static/js/components/AppChat.js b/devplacepy/static/js/components/AppChat.js index b9342bb4..3aeb661d 100644 --- a/devplacepy/static/js/components/AppChat.js +++ b/devplacepy/static/js/components/AppChat.js @@ -5,6 +5,7 @@ import { assetUrl } from "../assetVersion.js"; import { ChatSocket } from "../chat/ChatSocket.js"; import { shouldGroup } from "../chat/MessageGrouping.js"; import { dateKey, dateLabel } from "../chat/DateSeparators.js"; +import { ConversationItem } from "../chat/ConversationItem.js"; import { Http } from "../Http.js"; import { Avatar } from "../Avatar.js"; import { DomUtils } from "../DomUtils.js"; @@ -100,10 +101,18 @@ export class AppChat extends Component { this._ensureJumpButton(); this._bindActiveConversation(); this._bindDelete(); - this._connect(); this._initPresence(); + if (this.mode === "window") { + this._loadConversation(this.withUid).catch(() => {}).finally(() => this._connect()); + } else { + this._connect(); + } this._scrollThreadToEnd(); this._hasOlder = !!(this.thread && this.thread.querySelectorAll(".message-bubble").length >= CONVERSATION_PAGE_SIZE); + if (this.mode !== "window" && this.input && !this._isCoarse()) this.input.focus({ preventScroll: true }); + } + + focusComposer() { if (this.input && !this._isCoarse()) this.input.focus({ preventScroll: true }); } @@ -164,86 +173,66 @@ export class AppChat extends Component { this.input = this.form ? this.form.querySelector('textarea[name="content"], input[name="content"]') : null; this.upload = this.form ? this.form.querySelector("dp-upload") : null; this.sendBtn = this.form ? this.form.querySelector(".messages-send-btn") : null; - this.typingEl = this.querySelector("#typing-indicator"); - this.backBtn = this.querySelector("#messages-back-btn"); + this.typingEl = this.querySelector(".typing-indicator"); + this.backBtn = this.querySelector(".messages-back-btn"); this.searchInput = this.querySelector("#message-search"); } + _assignId(el, id) { + if (this.mode !== "window") el.id = id; + } + _ensureSkeleton() { if (this.main) return; - this.main = document.createElement("div"); this.main.className = "messages-main"; + const header = this.mode === "window" + ? this._buildHeader(this.partner || { uid: this.withUid }) + : this._buildPresenceHeader(); + this.thread = this._buildThread(); + this.form = this._buildComposer(this.withUid); + this.main.append(header, this.thread, this.form); + this.appendChild(this.main); + this._wireContentEnhancer(); + } + _buildPresenceHeader() { const header = document.createElement("div"); header.className = "messages-main-header"; const headerInfo = document.createElement("div"); headerInfo.className = "messages-header-info"; + headerInfo.appendChild(this._buildPresence({ uid: this.withUid })); + header.appendChild(headerInfo); + return header; + } + + _buildPresence(user) { const presence = document.createElement("span"); presence.className = "messages-presence"; - presence.id = "messages-presence"; + this._assignId(presence, "messages-presence"); presence.setAttribute("role", "status"); presence.setAttribute("aria-live", "polite"); presence.setAttribute("data-presence-label", ""); - presence.setAttribute("data-presence-uid", this.withUid || ""); + presence.setAttribute("data-presence-uid", user.uid || ""); + presence.setAttribute("data-presence-last-seen", user.last_seen || ""); presence.textContent = "offline"; - headerInfo.appendChild(presence); - header.appendChild(headerInfo); - - this.thread = document.createElement("div"); - this.thread.className = "messages-thread"; - this.thread.setAttribute("role", "log"); - this.thread.setAttribute("aria-label", "Message transcript"); - this.thread.setAttribute("aria-live", "polite"); - this.thread.setAttribute("aria-relevant", "additions"); + return presence; + } + _buildThread() { + const thread = document.createElement("div"); + thread.className = "messages-thread"; + thread.setAttribute("role", "log"); + thread.setAttribute("aria-label", "Message transcript"); + thread.setAttribute("aria-live", "polite"); + thread.setAttribute("aria-relevant", "additions"); this.typingEl = document.createElement("div"); this.typingEl.className = "typing-indicator"; - this.typingEl.id = "typing-indicator"; + this._assignId(this.typingEl, "typing-indicator"); this.typingEl.hidden = true; this.typingEl.append(document.createElement("span"), document.createElement("span"), document.createElement("span")); - this.thread.appendChild(this.typingEl); - - this.form = document.createElement("form"); - this.form.className = "messages-input-area"; - this.form.setAttribute("method", "POST"); - this.form.setAttribute("action", this.sendUrl); - this.form.setAttribute("data-live-form", ""); - - const receiverInput = document.createElement("input"); - receiverInput.type = "hidden"; - receiverInput.name = "receiver_uid"; - receiverInput.value = this.withUid || ""; - this.form.appendChild(receiverInput); - - this.input = document.createElement("textarea"); - this.input.name = "content"; - this.input.rows = 1; - this.input.maxLength = 2000; - this.input.autocomplete = "off"; - this.input.placeholder = "Type a message..."; - this.input.setAttribute("aria-label", "Type a message"); - - this.upload = document.createElement("dp-upload"); - this.upload.setAttribute("multiple", ""); - this.upload.setAttribute("paste", ""); - this.upload.setAttribute("max-files", String(this.maxAttachments)); - - this.sendBtn = document.createElement("button"); - this.sendBtn.type = "submit"; - this.sendBtn.className = "messages-send-btn"; - this.sendBtn.setAttribute("aria-label", "Send"); - const sendIcon = document.createElement("span"); - sendIcon.className = "send-icon"; - sendIcon.textContent = "➤"; - const sendSpinner = document.createElement("span"); - sendSpinner.className = "send-spinner"; - sendSpinner.setAttribute("aria-hidden", "true"); - this.sendBtn.append(sendIcon, sendSpinner); - - this.form.append(this.input, this.upload, document.createElement("dp-gif-picker"), this.sendBtn); - this.main.append(header, this.thread, this.form); - this.appendChild(this.main); + thread.appendChild(this.typingEl); + return thread; } _capAttachments() { @@ -287,9 +276,16 @@ export class AppChat extends Component { if (this.upload) { this.upload.addEventListener("dp-upload:busy", (event) => { this._uploading = !!(event.detail && event.detail.busy); + if (this._uploading) this._setToolsOpen(true); this._refreshSendButton(); }); } + this.moreBtn = this.form.querySelector(".composer-more-btn"); + if (this.moreBtn) { + this.moreBtn.addEventListener("click", () => { + this._setToolsOpen(!this.form.classList.contains("tools-open")); + }); + } this.input.addEventListener("keydown", (event) => { if (event.key === "Enter" && !event.shiftKey && !this._isCoarse()) { event.preventDefault(); @@ -298,10 +294,25 @@ export class AppChat extends Component { }); this.input.addEventListener("input", () => { if (!this._supportsFieldSizing) this._scheduleAutoGrow(); + if (this.input.value.trim()) this._collapseTools(); this._sendTyping(); }); } + _setToolsOpen(open) { + if (!this.form || !this.moreBtn) return; + this.form.classList.toggle("tools-open", open); + this.moreBtn.setAttribute("aria-expanded", open ? "true" : "false"); + const label = open ? "Hide actions" : "More actions"; + this.moreBtn.setAttribute("aria-label", label); + this.moreBtn.title = label; + } + + _collapseTools() { + if (this._uploading || this._collectAttachments().length) return; + this._setToolsOpen(false); + } + _scheduleAutoGrow() { if (this._autoGrowFrame) return; this._autoGrowFrame = requestAnimationFrame(() => { @@ -403,6 +414,7 @@ export class AppChat extends Component { this.input.value = ""; this._resetAutoGrow(); if (this.upload && typeof this.upload.clear === "function") this.upload.clear(); + this._setToolsOpen(false); this.input.focus({ preventScroll: true }); } @@ -683,28 +695,29 @@ export class AppChat extends Component { } async _connect() { + if (this.hub) { + this.socket = this.hub.subscribe(this._socketHandlers()); + return; + } const url = await this._resolveWsUrl(); if (!url) return; - this.socket = new ChatSocket(url, { + this.socket = new ChatSocket(url, this._socketHandlers()); + this.socket.connect(); + } + + _socketHandlers() { + return { onReady: (payload) => this.onReady(payload), onMessage: (frame) => this.onFrame(frame), onClose: () => { this._socketReady = false; this._noteDisconnected(); }, - }); - this.socket.connect(); - } - - _wsBaseUrl() { - if (/^wss?:\/\//i.test(this.wsPath)) return this.wsPath; - const scheme = location.protocol === "https:" ? "wss:" : "ws:"; - const path = this.wsPath.startsWith("/") ? this.wsPath : `/${this.wsPath}`; - return `${scheme}//${location.host}${path}`; + }; } async _resolveWsUrl() { - const base = this._wsBaseUrl(); + const base = ChatSocket.resolveUrl(this.wsPath); if (this.mode !== "embed" || !this.apiKey || !this.wsTicketUrl) { return base; } @@ -814,6 +827,7 @@ export class AppChat extends Component { } _handleError(frame) { + if (this.hub && !this._pendingSends.has(frame.client_id)) return; if (frame.client_id) this._failPendingSend(frame.client_id); if (window.app && window.app.toast) { window.app.toast.show(frame.text || "Message not sent.", { type: "error" }); @@ -1020,7 +1034,7 @@ export class AppChat extends Component { } async _refreshConversations() { - if (this.mode === "embed" || !this.list) return; + if (this.mode !== "page" || !this.list) return; const container = this.list.querySelector(".messages-conversations"); if (!container) return; try { @@ -1043,46 +1057,7 @@ export class AppChat extends Component { } _buildConversationItem(conv) { - const user = conv.other_user || {}; - const item = document.createElement("a"); - item.href = `/messages?with_uid=${user.uid || ""}`; - item.className = `conversation-item${user.uid && user.uid === this.withUid ? " active" : ""}`; - item.dataset.convUid = user.uid || ""; - item.setAttribute("role", "listitem"); - if (user.uid && user.uid === this.withUid) item.setAttribute("aria-current", "true"); - - item.appendChild(Avatar.badgeElement(user)); - - const info = document.createElement("div"); - info.className = "conversation-info"; - const name = document.createElement("div"); - name.className = "conversation-name"; - name.textContent = user.username || ""; - const preview = document.createElement("div"); - preview.className = "conversation-preview"; - preview.textContent = contentRenderer.preview(conv.last_message, 60); - info.append(name, preview); - item.appendChild(info); - - const unread = document.createElement("span"); - unread.className = "conversation-unread-dot"; - unread.hidden = !conv.unread; - const sr = document.createElement("span"); - sr.className = "sr-only"; - sr.textContent = "Unread messages"; - unread.appendChild(sr); - item.appendChild(unread); - - const time = document.createElement("span"); - time.className = "conversation-time"; - if (conv.last_message_at) { - time.setAttribute("datetime", conv.last_message_at); - time.dataset.dt = ""; - time.dataset.dtMode = "ago"; - if (window.app && window.app.localTime) window.app.localTime.apply(time); - } - item.appendChild(time); - + const item = ConversationItem.build(conv, this.withUid); this._bindConversationClick(item); return item; } @@ -1248,7 +1223,8 @@ export class AppChat extends Component { } _initMobilePane() { - if (this.mode === "embed" || !this.list || !this.main) return; + if (this.mode === "window") this._activePane = "thread"; + if (this.mode !== "page" || !this.list || !this.main) return; this._activePane = this.withUid ? "thread" : "list"; this._applyPane(); @@ -1292,7 +1268,7 @@ export class AppChat extends Component { } _bindHistory() { - if (this.mode === "embed" || this._onPopState) return; + if (this.mode !== "page" || this._onPopState) return; this._onPopState = () => { const params = new URLSearchParams(window.location.search); const uid = params.get("with_uid"); @@ -1322,8 +1298,7 @@ export class AppChat extends Component { } this._opening = true; try { - const data = await Http.getJson(`/messages?with_uid=${encodeURIComponent(uid)}`); - this._renderConversation(uid, data); + await this._loadConversation(uid); const url = `/messages?with_uid=${encodeURIComponent(uid)}`; if (push) window.history.pushState({ withUid: uid }, "", url); else window.history.replaceState({ withUid: uid }, "", url); @@ -1338,6 +1313,11 @@ export class AppChat extends Component { } } + async _loadConversation(uid) { + const data = await Http.getJson(`/messages?with_uid=${encodeURIComponent(uid)}`); + this._renderConversation(uid, data); + } + _renderConversation(uid, data) { this.withUid = uid; this.setAttribute("with-uid", uid); @@ -1356,6 +1336,7 @@ export class AppChat extends Component { }); this._newCount = 0; this._updateJumpButton(); + this.dispatchEvent(new CustomEvent("dp-chat:conversation", { bubbles: true, detail: { user: data.other_user || null } })); } _ensureMainShell(otherUser) { @@ -1371,18 +1352,7 @@ export class AppChat extends Component { } this.main.innerHTML = ""; this.main.appendChild(this._buildHeader(otherUser)); - this.thread = document.createElement("div"); - this.thread.className = "messages-thread"; - this.thread.setAttribute("role", "log"); - this.thread.setAttribute("aria-label", "Message transcript"); - this.thread.setAttribute("aria-live", "polite"); - this.thread.setAttribute("aria-relevant", "additions"); - this.typingEl = document.createElement("div"); - this.typingEl.className = "typing-indicator"; - this.typingEl.id = "typing-indicator"; - this.typingEl.hidden = true; - this.typingEl.append(document.createElement("span"), document.createElement("span"), document.createElement("span")); - this.thread.appendChild(this.typingEl); + this.thread = this._buildThread(); this.form = this._buildComposer(otherUser.uid || this.withUid); this.main.append(this.thread, this.form); this._adopt(); @@ -1398,18 +1368,21 @@ export class AppChat extends Component { _buildHeader(user) { const header = document.createElement("div"); header.className = "messages-main-header"; - const back = document.createElement("button"); - back.type = "button"; - back.className = "messages-back-btn"; - back.id = "messages-back-btn"; - back.setAttribute("aria-label", "Back to conversations"); - back.innerHTML = "←"; - back.addEventListener("click", () => { - if (!this._isMobile()) return; - this._showList(); - }); - this.backBtn = back; - header.appendChild(back); + if (this.mode === "page") { + const back = document.createElement("button"); + back.type = "button"; + back.className = "messages-back-btn"; + back.id = "messages-back-btn"; + back.setAttribute("aria-label", "Back to conversations"); + back.innerHTML = "←"; + back.addEventListener("click", () => { + if (!this._isMobile()) return; + this._showList(); + }); + this.backBtn = back; + header.appendChild(back); + } + header.appendChild(this._avatarLink(user)); const info = document.createElement("div"); info.className = "messages-header-info"; const title = document.createElement("h3"); @@ -1417,32 +1390,29 @@ export class AppChat extends Component { link.href = `/profile/${encodeURIComponent(user.username || "")}`; link.textContent = user.username || ""; title.appendChild(link); - const presence = document.createElement("span"); - presence.className = "messages-presence"; - presence.id = "messages-presence"; - presence.setAttribute("role", "status"); - presence.setAttribute("aria-live", "polite"); - presence.setAttribute("data-presence-label", ""); - presence.setAttribute("data-presence-uid", user.uid || ""); - presence.setAttribute("data-presence-last-seen", user.last_seen || ""); - presence.textContent = "offline"; - info.append(title, presence); + info.append(title, this._buildPresence(user)); header.appendChild(info); return header; } + _avatarLink(user) { + if (!user.username && !user.avatar_seed) { + const placeholder = document.createElement("span"); + placeholder.className = "avatar-badge"; + return placeholder; + } + const link = document.createElement("a"); + link.href = `/profile/${encodeURIComponent(user.username || "")}`; + link.className = "user-avatar-link"; + link.appendChild(Avatar.badgeElement(user)); + return link; + } + _fillHeader(user) { const header = this.querySelector(".messages-main-header"); if (!header) return; const avatarHost = header.querySelector(".user-avatar-link, .avatar-badge"); - if (avatarHost && user.uid) { - const badge = Avatar.badgeElement(user); - const link = document.createElement("a"); - link.href = `/profile/${encodeURIComponent(user.username || "")}`; - link.className = "user-avatar-link"; - link.appendChild(badge); - avatarHost.replaceWith(link); - } + if (avatarHost && user.uid) avatarHost.replaceWith(this._avatarLink(user)); const nameLink = header.querySelector(".messages-header-info h3 a, .messages-header-info a"); if (nameLink) { nameLink.href = `/profile/${encodeURIComponent(user.username || "")}`; @@ -1480,10 +1450,23 @@ export class AppChat extends Component { this.input.setAttribute("aria-label", "Type a message"); this.input.className = "emoji-picker-target"; this.input.setAttribute("data-mention", ""); + const moreBtn = document.createElement("button"); + moreBtn.type = "button"; + moreBtn.className = "composer-more-btn"; + moreBtn.setAttribute("aria-label", "More actions"); + moreBtn.setAttribute("aria-expanded", "false"); + moreBtn.title = "More actions"; + moreBtn.textContent = "+"; this.upload = document.createElement("dp-upload"); this.upload.setAttribute("multiple", ""); this.upload.setAttribute("paste", ""); this.upload.setAttribute("max-files", String(this.maxAttachments)); + const tools = document.createElement("div"); + tools.className = "composer-tools"; + tools.append(this.upload, document.createElement("dp-gif-picker")); + const field = document.createElement("div"); + field.className = "composer-field"; + field.appendChild(this.input); this.sendBtn = document.createElement("button"); this.sendBtn.type = "submit"; this.sendBtn.className = "messages-send-btn"; @@ -1495,7 +1478,7 @@ export class AppChat extends Component { sendSpinner.className = "send-spinner"; sendSpinner.setAttribute("aria-hidden", "true"); this.sendBtn.append(sendIcon, sendSpinner); - form.append(receiverInput, this.input, this.upload, this.sendBtn); + form.append(receiverInput, moreBtn, tools, field, this.sendBtn); return form; } diff --git a/devplacepy/static/js/components/AppChatDock.js b/devplacepy/static/js/components/AppChatDock.js new file mode 100644 index 00000000..648cd280 --- /dev/null +++ b/devplacepy/static/js/components/AppChatDock.js @@ -0,0 +1,576 @@ +// retoor + +import { Component } from "./Component.js"; +import { Avatar } from "../Avatar.js"; +import { Http } from "../Http.js"; +import { ListNav } from "../ListNav.js"; +import { ChatSocket } from "../chat/ChatSocket.js"; +import { ChatSocketHub } from "../chat/ChatSocketHub.js"; +import { ConversationItem } from "../chat/ConversationItem.js"; + +const MOBILE_BREAKPOINT_PX = 768; +const WINDOW_SLOT_PX = 336; +const DOCK_RESERVED_PX = 96; +const MAX_OPEN_WINDOWS = 3; +const MAX_ENTRIES = 8; +const MAX_SEEN_FRAMES = 500; +const SEARCH_DEBOUNCE_MS = 200; +const STORAGE_PREFIX = "devplace.chat-dock."; + +export class AppChatDock extends Component { + constructor() { + super(); + this._built = false; + this.entries = []; + this.windows = new Map(); + this.heads = new Map(); + this.seenFrames = new Set(); + this.channel = null; + this.compose = null; + this.conversations = null; + this.panelOpen = false; + this._resizeFrame = null; + } + + connectedCallback() { + if (this._built) return; + this._built = true; + this.selfUid = this.attr("self-uid"); + this.selfIsAdmin = this.attr("self-admin", "false") === "true"; + this.conversationsUrl = this.attr("conversations-url", "/messages/conversations"); + this.searchUrl = this.attr("search-url", "/messages/search"); + this.hub = new ChatSocketHub(ChatSocket.resolveUrl(this.attr("ws-url", "/messages/ws"))); + this._buildPanel(); + this._buildTray(); + this._bindDocument(); + this._bindToggles(); + this.entries = this._restore(); + if (!this._isMobile()) this._enforceLimits(); + this._render(); + } + + disconnectedCallback() { + for (const entry of this.windows.values()) entry.section.remove(); + this.windows.clear(); + if (this.channel) this.channel.close(); + this.channel = null; + } + + open(user, { focus = true } = {}) { + if (!user || !user.uid || user.uid === this.selfUid || this._isMobile()) return false; + this._closePanel(); + let entry = this.entries.find((item) => item.uid === user.uid); + if (entry) { + this.entries.splice(this.entries.indexOf(entry), 1); + entry.username = user.username || entry.username; + entry.avatar_seed = user.avatar_seed || entry.avatar_seed; + } else { + entry = { uid: user.uid, username: user.username || "", avatar_seed: user.avatar_seed || "" }; + } + entry.minimized = false; + entry.unread = 0; + this.entries.unshift(entry); + this._enforceLimits(); + this._commit(); + const win = this.windows.get(entry.uid); + if (focus && win) win.chat.focusComposer(); + return true; + } + + minimize(uid) { + const entry = this.entries.find((item) => item.uid === uid); + if (!entry) return; + entry.minimized = true; + this._commit(); + } + + close(uid) { + this.entries = this.entries.filter((item) => item.uid !== uid); + this._commit(); + } + + togglePanel() { + if (this.panelOpen) this._closePanel(); + else this._openPanel(); + } + + openCompose() { + this._closePanel(); + if (!this.compose) { + this.compose = this._buildCompose(); + this._enforceLimits(); + this._commit(); + } + this.compose.querySelector(".chat-compose-input").focus({ preventScroll: true }); + } + + closeCompose() { + if (!this.compose) return; + this.compose.remove(); + this.compose = null; + } + + _isMobile() { + return window.innerWidth <= MOBILE_BREAKPOINT_PX; + } + + _maxOpen() { + const fit = Math.floor((window.innerWidth - DOCK_RESERVED_PX) / WINDOW_SLOT_PX); + return Math.max(1, Math.min(MAX_OPEN_WINDOWS, fit)); + } + + _enforceLimits() { + const slots = Math.max(1, this._maxOpen() - (this.compose ? 1 : 0)); + let expanded = 0; + for (const entry of this.entries) { + if (entry.minimized) continue; + expanded += 1; + if (expanded > slots) entry.minimized = true; + } + this.entries = this.entries.slice(0, MAX_ENTRIES); + } + + _commit() { + this._persist(); + this._render(); + } + + _storageKey() { + return `${STORAGE_PREFIX}${this.selfUid}`; + } + + _restore() { + try { + const parsed = JSON.parse(window.sessionStorage.getItem(this._storageKey()) || "[]"); + if (!Array.isArray(parsed)) return []; + return parsed + .filter((item) => item && item.uid && item.uid !== this.selfUid) + .slice(0, MAX_ENTRIES) + .map((item) => ({ + uid: String(item.uid), + username: String(item.username || ""), + avatar_seed: String(item.avatar_seed || ""), + minimized: !!item.minimized, + unread: Number(item.unread) || 0, + })); + } catch { + return []; + } + } + + _persist() { + try { + window.sessionStorage.setItem(this._storageKey(), JSON.stringify(this.entries)); + } catch { + /* storage unavailable: the dock still works for this page */ + } + } + + _render() { + const visible = this._isMobile() ? [] : this.entries; + if (this._isMobile()) this.closeCompose(); + const expanded = visible.filter((entry) => !entry.minimized); + const minimized = visible.filter((entry) => entry.minimized); + + for (const [uid, win] of this.windows) { + if (expanded.some((entry) => entry.uid === uid)) continue; + win.section.remove(); + this.windows.delete(uid); + } + for (const entry of [...expanded].reverse()) { + if (!this.windows.has(entry.uid)) this.windows.set(entry.uid, this._buildWindow(entry)); + } + + for (const [uid, head] of this.heads) { + if (minimized.some((entry) => entry.uid === uid)) continue; + head.remove(); + this.heads.delete(uid); + } + for (const entry of minimized) { + let head = this.heads.get(entry.uid); + if (!head) { + head = this._buildHead(entry); + this.heads.set(entry.uid, head); + } + this._updateHead(head, entry); + this.headColumn.appendChild(head); + } + + this._syncChannel(visible.length > 0); + } + + _syncChannel(wanted) { + if (wanted && !this.channel) { + this.channel = this.hub.subscribe({ onMessage: (frame) => this._onFrame(frame) }); + } else if (!wanted && this.channel) { + this.channel.close(); + this.channel = null; + } + } + + _onFrame(frame) { + if (!frame || frame.type !== "message" || !frame.uid || frame.sender_uid === this.selfUid) return; + if (this.seenFrames.has(frame.uid)) return; + if (this.seenFrames.size >= MAX_SEEN_FRAMES) this.seenFrames.clear(); + this.seenFrames.add(frame.uid); + const entry = this.entries.find((item) => item.uid === frame.sender_uid); + if (!entry || !entry.minimized) return; + entry.unread = (entry.unread || 0) + 1; + this._persist(); + const head = this.heads.get(entry.uid); + if (head) this._updateHead(head, entry); + } + + _buildTray() { + this.tray = document.createElement("div"); + this.tray.className = "chat-dock-tray"; + this.windowRow = document.createElement("div"); + this.windowRow.className = "chat-dock-windows"; + this.headColumn = document.createElement("div"); + this.headColumn.className = "chat-dock-heads"; + this.tray.append(this.windowRow, this.headColumn); + this.appendChild(this.tray); + } + + _buildWindow(entry) { + const section = document.createElement("section"); + section.className = "chat-window"; + section.dataset.chatUid = entry.uid; + section.setAttribute("aria-label", `Chat with ${entry.username || "member"}`); + this.windowRow.insertBefore(section, this.compose); + + const chat = document.createElement("dp-chat"); + chat.setAttribute("mode", "window"); + chat.setAttribute("self-uid", this.selfUid); + chat.setAttribute("self-admin", this.selfIsAdmin ? "true" : "false"); + chat.setAttribute("with-uid", entry.uid); + chat.setAttribute("ai-indicator", "true"); + chat.hub = this.hub; + chat.partner = { uid: entry.uid, username: entry.username, avatar_seed: entry.avatar_seed }; + section.addEventListener("dp-chat:conversation", (event) => this._onConversation(entry.uid, event.detail.user)); + section.appendChild(chat); + + const header = chat.querySelector(".messages-main-header"); + if (header) { + header.appendChild(this._windowActions([ + this._iconButton("chat-window-minimize", "Minimize chat", "–", () => this.minimize(entry.uid)), + this._iconButton("chat-window-close", "Close chat", "✕", () => this.close(entry.uid)), + ])); + header.addEventListener("click", (event) => { + if (event.target.closest("a, button")) return; + this.minimize(entry.uid); + }); + } + return { section, chat }; + } + + _onConversation(uid, user) { + const entry = this.entries.find((item) => item.uid === uid); + if (entry && user) { + entry.username = user.username || entry.username; + entry.avatar_seed = user.avatar_seed || entry.avatar_seed; + this._persist(); + const win = this.windows.get(uid); + if (win) win.section.setAttribute("aria-label", `Chat with ${entry.username || "member"}`); + } + if (window.app && window.app.counters) window.app.counters.poll(); + } + + _buildCompose() { + const section = document.createElement("section"); + section.className = "chat-window chat-window-compose"; + section.setAttribute("aria-label", "New message"); + + const header = document.createElement("div"); + header.className = "messages-main-header"; + const title = document.createElement("h3"); + title.textContent = "New message"; + header.append(title, this._windowActions([ + this._iconButton("chat-window-close", "Close new message", "✕", () => this.closeCompose()), + ])); + + const to = document.createElement("div"); + to.className = "chat-compose-to"; + const label = document.createElement("label"); + label.textContent = "To:"; + const input = document.createElement("input"); + input.type = "search"; + input.className = "chat-compose-input"; + input.placeholder = "Search people..."; + input.autocomplete = "off"; + input.setAttribute("aria-label", "Search people to message"); + label.appendChild(input); + to.appendChild(label); + + const results = document.createElement("div"); + results.className = "chat-compose-results"; + results.setAttribute("role", "listbox"); + results.setAttribute("aria-label", "People"); + + section.append(header, to, results); + this.windowRow.appendChild(section); + this._bindPeopleSearch(input, results, { + onEmpty: () => results.replaceChildren(), + onChoose: (user) => { + this.closeCompose(); + this.open(user); + }, + }); + return section; + } + + _windowActions(buttons) { + const actions = document.createElement("div"); + actions.className = "chat-window-actions"; + actions.append(...buttons); + return actions; + } + + _iconButton(className, label, glyph, onClick) { + const btn = document.createElement("button"); + btn.type = "button"; + btn.className = `chat-icon-btn ${className}`; + btn.setAttribute("aria-label", label); + btn.title = label; + btn.textContent = glyph; + btn.addEventListener("click", (event) => { + event.stopPropagation(); + onClick(); + }); + return btn; + } + + _buildHead(entry) { + const head = document.createElement("div"); + head.className = "chat-head"; + head.dataset.chatUid = entry.uid; + + const openBtn = document.createElement("button"); + openBtn.type = "button"; + openBtn.className = "chat-head-open"; + openBtn.setAttribute("aria-label", `Open chat with ${entry.username || "member"}`); + openBtn.title = entry.username || ""; + openBtn.appendChild(Avatar.badgeElement(entry, 40, "md")); + const badge = document.createElement("span"); + badge.className = "nav-badge chat-head-badge"; + badge.hidden = true; + openBtn.appendChild(badge); + openBtn.addEventListener("click", () => this.open(entry)); + + const closeBtn = this._iconButton("chat-head-close", `Close chat with ${entry.username || "member"}`, "✕", () => this.close(entry.uid)); + head.append(openBtn, closeBtn); + return head; + } + + _updateHead(head, entry) { + const badge = head.querySelector(".chat-head-badge"); + const unread = entry.unread || 0; + badge.textContent = String(unread); + badge.hidden = unread === 0; + const label = `Open chat with ${entry.username || "member"}`; + head.querySelector(".chat-head-open").setAttribute("aria-label", unread ? `${label}, ${unread} unread` : label); + } + + _buildPanel() { + this.panel = document.createElement("div"); + this.panel.className = "chat-panel"; + this.panel.id = "chat-panel"; + this.panel.hidden = true; + this.panel.setAttribute("role", "dialog"); + this.panel.setAttribute("aria-label", "Chats"); + + const header = document.createElement("div"); + header.className = "chat-panel-header"; + const title = document.createElement("h2"); + title.className = "chat-panel-title"; + title.textContent = "Chats"; + const compose = this._iconButton("chat-panel-compose", "New message", "✎", () => this.openCompose()); + const expand = document.createElement("a"); + expand.className = "chat-icon-btn chat-panel-expand"; + expand.href = "/messages"; + expand.title = "Open Messages"; + expand.setAttribute("aria-label", "Open Messages"); + expand.textContent = "↗"; + header.append(title, this._windowActions([compose, expand])); + + const search = document.createElement("div"); + search.className = "chat-panel-search"; + this.searchInput = document.createElement("input"); + this.searchInput.type = "search"; + this.searchInput.className = "chat-panel-search-input"; + this.searchInput.placeholder = "Search people..."; + this.searchInput.autocomplete = "off"; + this.searchInput.setAttribute("aria-label", "Search people"); + search.appendChild(this.searchInput); + + this.panelList = document.createElement("div"); + this.panelList.className = "chat-panel-list"; + this.panelList.setAttribute("role", "listbox"); + this.panelList.setAttribute("aria-label", "Conversations"); + + const footer = document.createElement("a"); + footer.className = "chat-panel-footer"; + footer.href = "/messages"; + footer.textContent = "See all in Messages"; + + this.panel.append(header, search, this.panelList, footer); + this.appendChild(this.panel); + this.panelNav = this._bindPeopleSearch(this.searchInput, this.panelList, { + onEmpty: () => this._showConversations(), + onChoose: (user) => this.open(user), + }); + } + + _bindPeopleSearch(input, list, { onEmpty, onChoose }) { + const nav = new ListNav(input, list, { + itemSelector: ".conversation-item", + activeClass: "active", + firstDefault: false, + chooseOnTab: false, + isOpen: () => true, + onChoose: (item) => onChoose(ConversationItem.user(item)), + }); + let timer = null; + let sequence = 0; + input.addEventListener("input", () => { + clearTimeout(timer); + const query = input.value.trim(); + sequence += 1; + if (!query) { + onEmpty(); + return; + } + const token = sequence; + timer = window.setTimeout(async () => { + let results = []; + try { + const data = await Http.getJson(`${this.searchUrl}?q=${encodeURIComponent(query)}`); + results = data.results || []; + } catch { + results = []; + } + if (token !== sequence) return; + this._fillList(list, results.map((user) => ({ other_user: user })), "No people found"); + nav.opened(); + if (results.length) nav.setActive(0); + }, SEARCH_DEBOUNCE_MS); + }); + list.addEventListener("click", (event) => { + const item = event.target.closest(".conversation-item"); + if (!item || event.button !== 0 || event.metaKey || event.ctrlKey || event.shiftKey || event.altKey) return; + event.preventDefault(); + onChoose(ConversationItem.user(item)); + }); + return nav; + } + + _fillList(list, conversations, emptyText) { + list.replaceChildren(...conversations.map((conv) => ConversationItem.build(conv))); + if (conversations.length) return; + const empty = document.createElement("div"); + empty.className = "empty-state empty-state-borderless"; + empty.textContent = emptyText; + list.appendChild(empty); + } + + _showConversations() { + if (this.conversations === null) { + this._fillList(this.panelList, [], "Loading…"); + return; + } + this._fillList(this.panelList, this.conversations, "No conversations yet"); + this.panelNav.opened(); + } + + async _loadConversations() { + try { + const data = await Http.getJson(this.conversationsUrl); + this.conversations = data.conversations || []; + } catch { + this.conversations = this.conversations || []; + } + if (this.panelOpen && !this.searchInput.value.trim()) this._showConversations(); + } + + _openPanel() { + this.panelOpen = true; + this.panel.hidden = false; + this._setToggleState(true); + this.searchInput.value = ""; + this._showConversations(); + this._loadConversations(); + this.searchInput.focus({ preventScroll: true }); + } + + _closePanel() { + if (!this.panelOpen) return; + this.panelOpen = false; + this.panel.hidden = true; + this._setToggleState(false); + } + + _toggles() { + return document.querySelectorAll("[data-chat-panel-toggle]"); + } + + _bindToggles() { + this._toggles().forEach((toggle) => { + toggle.setAttribute("aria-haspopup", "dialog"); + toggle.setAttribute("aria-controls", this.panel.id); + toggle.setAttribute("aria-expanded", "false"); + }); + } + + _setToggleState(open) { + this._toggles().forEach((toggle) => toggle.setAttribute("aria-expanded", open ? "true" : "false")); + } + + _intercepts(event) { + if (this._isMobile() || event.button !== 0) return false; + return !(event.metaKey || event.ctrlKey || event.shiftKey || event.altKey); + } + + _bindDocument() { + document.addEventListener("click", (event) => { + const toggle = event.target.closest("[data-chat-panel-toggle]"); + if (toggle) { + if (!this._intercepts(event)) return; + event.preventDefault(); + this.togglePanel(); + return; + } + const opener = event.target.closest("[data-chat-open]"); + if (opener) { + if (!this._intercepts(event)) return; + event.preventDefault(); + this.open({ + uid: opener.dataset.chatOpen, + username: opener.dataset.chatUsername || "", + avatar_seed: opener.dataset.chatAvatarSeed || "", + }); + return; + } + if (this.panelOpen && !this.panel.contains(event.target)) this._closePanel(); + }); + document.addEventListener("keydown", (event) => { + if (event.key !== "Escape" || !this.panelOpen) return; + this._closePanel(); + const toggle = this._toggles()[0]; + if (toggle) toggle.focus(); + }); + window.addEventListener("resize", () => { + cancelAnimationFrame(this._resizeFrame); + this._resizeFrame = requestAnimationFrame(() => { + if (this._isMobile()) { + this._closePanel(); + } else { + this._enforceLimits(); + this._persist(); + } + this._render(); + }); + }); + } +} + +customElements.define("dp-chat-dock", AppChatDock); diff --git a/devplacepy/static/js/components/index.js b/devplacepy/static/js/components/index.js index 07624327..b597dc39 100644 --- a/devplacepy/static/js/components/index.js +++ b/devplacepy/static/js/components/index.js @@ -15,6 +15,7 @@ import "./AppDocsChat.js"; import "./AppIsslop.js"; import "./AppIsslopRun.js"; import "./AppChat.js"; +import "./AppChatDock.js"; import "./AppQuizPlayer.js"; import "./AppQuizBuilder.js"; import "./AppOpinionWar.js"; diff --git a/devplacepy/templates/_card_link.html b/devplacepy/templates/_card_link.html index ae78c6dd..758e0d8f 100644 --- a/devplacepy/templates/_card_link.html +++ b/devplacepy/templates/_card_link.html @@ -1 +1 @@ - + diff --git a/devplacepy/templates/_chat_open_attrs.html b/devplacepy/templates/_chat_open_attrs.html new file mode 100644 index 00000000..46da41fb --- /dev/null +++ b/devplacepy/templates/_chat_open_attrs.html @@ -0,0 +1 @@ +{%- if _chat_user and _chat_user.get('uid') %} data-chat-open="{{ _chat_user['uid'] }}" data-chat-username="{{ _chat_user['username'] }}" data-chat-avatar-seed="{{ avatar_seed(_chat_user) }}"{% endif -%} diff --git a/devplacepy/templates/base.html b/devplacepy/templates/base.html index 02227071..1bba4c71 100644 --- a/devplacepy/templates/base.html +++ b/devplacepy/templates/base.html @@ -53,6 +53,10 @@ + {% if user %} + + + {% endif %} {% block extra_head %}{% endblock %} {{ custom_css_tag(request) }} {{ extra_head_tag() }} @@ -88,7 +92,7 @@ {% if user %} {% set msg_unread = get_unread_messages(user["uid"]) %} - +