A realtime ccmjs chat component with optional sign-in. Participants can edit, delete and restore their own messages, react with emoji, see who reacted and report a message for review.
ccm.chat.mjs manages state and updates the affected DOM elements. The component
loads its HTML templates from resources/views.mjs and its language packs and SVG
icons from resources/content.mjs. The component's config documents its
dependencies and customization options. The bundled ccmjs framework and its license
are in libs/framework.
- From the
chatdirectory, runpython3 -m http.server 8000. - Open the demo in two browser windows and sign in to try realtime updates.
The demo uses https://kless.inf.h-brs.de/api/ for both chat data and authentication.
Participants can register through the bundled user component in libs/user.
The entry page loads ccmjs and embeds a declarative <ccm-app> that selects the
demo export. See index.html and the demo configuration.
For your own deployment, choose a server, configure the user component and decide
whether to enable registration. The chat API must accept the credentials issued by
the authentication backend at user.url. Pages served over HTTPS require an HTTPS API.
Visitors can read any messages the server grants them access to. With the optional
user component, signing in enables posting, reacting and reporting. Only the
message owner can edit, delete or restore it. Without a signed-in user, both the
interface and the public JavaScript API provide read-only access.
<script src="./libs/framework/ccm-29.1.0.min.js"></script>
<ccm-app component="./ccm.chat.mjs" config='
{
"data": {
"key": "seminar",
"store": ["ccm.store", {
"name": "chat",
"url": "https://example.org/api",
"observe": { "chat": "seminar", "public": true }
}]
},
"user": ["ccm.instance", "./libs/user/ccm.user-1.2.0.min.mjs", {
"url": "https://example.org/api"
}]
}
'></ccm-app>A store can hold several chats. Set data.key to the chat ID and use the same ID
in observe.chat. Each message has its own key within the chat. If you omit
observe, a positive refreshInterval enables polling.
By default the component uses a local IndexedDB store named chat. Tabs on the
same origin coordinate through BroadcastChannel and Web Locks. Use the local store
for previews and a server for enforcing access permissions or syncing across devices.
The demo loads ccmjs 29.1.0, User 1.2.0 and the UI resources from libs. The demo
configuration specifies the local resource paths. The shorter embedding example
above uses the User release's default CDN URLs for its UI resources.
The current ccm-server uses _.owner for ownership. Earlier versions used
_.creator. The owner is the full account identity, realm:key. Each record also
stores author: { realm, key, name }. Tokens and private profile data stay out of
chat records. The chat displays records only when the author identity matches the
protected owner field. Display names are snapshots, so the reaction details also
show each person's unique identity.
| Record type | Key | Contents | Default permissions |
|---|---|---|---|
| Message | [chat, "message", uuid] |
Text, author, timestamps, revision and deletion status | Anyone can read. Only the author can write or delete. |
| Reactions | [chat, "reactions", realm, userKey] |
All emoji reactions one user has added in this chat | Anyone can read. Only the user who reacted can write or delete. |
| Reports | [chat, "reports", realm, userKey] |
All messages one user has reported in this chat | Anyone can read. Only the user who reported them can write or delete. |
| Private archive | [chat, "archive", uuid] |
Deleted message text and a reference to the message | Only the owner can read, write or delete. |
Each participant controls their own reaction and report records. Message authors have no permission to remove another participant's reactions or reports. A participant can withdraw a report or remove a reaction they added. Each distinct emoji counts once per person per message. Anyone who can read a message can select a reaction chip to see who used that emoji. The details work with a keyboard or touchscreen.
Public records use the following permissions by default.
_: {
owner: "ccm:alice",
access: { get: "all", set: "owner", del: "owner" }
}Set permissions.read to all, realm, owner or a group such as realm:group.
Use permissions.readers to grant additional users or groups read-only access.
These settings apply when a record is created. Subsequent edits preserve its current
permissions. Private archives always use owner-only access. For a private chat,
restrict reads on all three public record types. The chat ID identifies the room
and grants no access rights.
When the owner deletes a message, the component first saves its text in a private
archive. Once that write succeeds, it clears the public text and sets deleted: true.
Readers see the author, timestamp and a deletion notice. The owner also sees the
restore action when enabled. Direct reads of the public record return an empty
message body. Anyone who previously read the message may still have a copy.
Restoring a message reads its referenced archive. If the archive is missing, the message stays deleted and the interface shows an error. Reactions and reports stay in their owners' records and reappear when the message is restored.
Archives belong to the message author and are excluded from chat history. Restoring
a message or a failed deletion can leave an unreferenced archive behind. The owner
can remove it with store.del(archiveKey). Keep any archive still referenced by a
deleted message so the owner can restore it.
When a participant confirms a report, the message shows an amber flag and a report
count. The flag tells readers that someone has requested a review. Participants can
withdraw their own reports. Reports identify the reporting account and are visible
to the same readers as the chat. The component has no hidden moderator role or
automatic content removal. External moderation tools can listen for the report event.
The component batches WebSocket notifications briefly, then reads the current records. It also reads again when a subscription reconnects. An optional periodic refresh catches missed events and permission changes. Switching accounts clears the previous account's data from the view before loading the new session's history.
Each message key identifies an existing <article>. The component tracks changes
to its text, metadata, report flag, reactions and actions separately. An incoming
reaction updates the relevant chips and any open reaction details. Other messages,
extension slots, the composer, the User component and open editors keep their DOM
nodes. Drafts and scroll position survive updates. The chat scrolls to the latest
message when the reader is already near the bottom or sends a message. Readers
further up the history can use the New messages button to jump down.
Server writes use set(..., undefined, { ifMatch }). If two sessions for the same
account change reactions or reports concurrently, the component retries against
the latest record. A conflicting edit, deletion or restoration shows an error so
the owner can review the newer message. The server must support conditional writes
and run a single process per database for this guarantee to hold.
The demo uses the English language pack (#labels.en) for both Chat and User and
formats timestamps with en-US. For a German embed, select #labels.de in each
component's labels dependency and set the chat's locale to de-DE. To override
individual chat labels, pass an object such as labels: { send: "Post" }. Missing
labels use their English defaults. The full defaults are in ccm.chat.mjs.
| Property | Description |
|---|---|
data.store, data.key |
ccm.store dependency and chat ID |
user, showUser |
Optional authentication component and whether to display its interface |
title, subtitle, labels |
Headings, interface text, accessible names and error messages |
locale, dateFormat |
Locale and timestamp formatting options |
maxLength, sendOnEnter |
Maximum message length and whether Enter sends. Shift+Enter inserts a line break. |
features |
Enable or disable edit, delete, restore, reactions and reports individually |
emojis |
Emoji available in the picker. Existing reactions remain visible. |
permissions |
Read access for newly created public records |
refreshInterval, refreshDelay |
Periodic refresh interval and delay for batching live notifications, in milliseconds |
conflictRetries |
Maximum number of write attempts for concurrent changes to reactions or reports |
scrollThreshold |
Distance from the bottom, in pixels, at which the chat scrolls automatically |
icons |
Default icons from resources/content.mjs#icons. Override individual icons with trusted SVG. |
ui |
Bundled ccm-ui library for HTML templates, loaded through ccm.load |
views |
DOM factories loaded from resources/views.mjs through ccm.load. Overrides must provide the same signatures and DOM references. |
css |
Component stylesheet, loaded from resources/styles.css through ccm.load by default |
styles |
Custom CSS text applied after the stylesheet |
extensions |
Ordered asynchronous extensions, which can also be loaded through ccm.load |
Message content is rendered as plain text in DOM text nodes. Custom CSS, SVG icons and JavaScript extensions are trusted configuration supplied by the operator.
Chat views use data-on-* attributes to connect DOM events to handlers in
app.events. For example, data-on-submit="submitMessage" binds the composer to
the send handler. The instance calls app.ui.bind(element, app) on newly created
view elements. Existing elements keep their bindings across realtime updates.
Custom button views receive the action name as the third argument to
button(app, label, action, iconName, className). Set it as data-action alongside
data-on-click="action". On click, app.events.action reads the current action
from the button. For message actions, it reads the message ID from the surrounding
card's data-key. The same report button can switch between report and unreport.
Dialog actions apply to the message selected when the dialog opened. The save
action reads the draft from the dialog's textarea. The react action reads the
emoji from the button's data-emoji.
| Method | Effect |
|---|---|
start(), refresh() |
Start the chat or refresh it from the store, respectively |
send(text) |
Create a message |
edit(key, text, revision?) |
Edit your own message. Pass the revision seen when the editor opened to detect a conflicting edit. |
delete(key, revision?), restore(key) |
Delete or restore your own message |
react(key, emoji, active?) |
Add or remove your reaction. Omit active to toggle it. |
report(key, active = true) |
Report a message or pass false to withdraw your report |
getValue() |
Return a copy of { messages, reactions, reports }. Private archives are excluded. |
getReactions(key) |
Return [{ emoji, users: [{ realm, key, name }] }] |
showReactions(key) |
Open the list of people who reacted, grouped by emoji |
emit(type, detail?) |
Send an event with { app, type, ...detail } to extensions and subscribers |
subscribe(listener) |
Register a listener and return an unsubscribe function |
destroy() |
Remove listeners and timers and close the instance's own store subscription |
Mutation methods return a promise that resolves to the saved record, or to null
if a hook cancels the operation. Errors reject the promise. Lifecycle events are
init, ready, before-start, mount, start, refresh, user, connection
and destroy.
Before writing, the component emits before-send, before-edit, before-delete,
before-restore, before-react or before-report with { input, user, cancel }.
Extensions can change input or set cancel = true. The component then checks
the current session, permissions and input before committing the change. A
successful write emits send, edit, delete, restore, react or report
with { record, input, user }. The write still succeeds if a post-commit listener
throws an error.
The render-message event carries { message, element, slot, changed }. Its
changed array lists the affected regions (meta, body, report, reactions,
actions). The render event carries { changed, removed, dom }, where changed
contains DOM elements and removed contains serialized record keys. Both events
fire only for changes to the message DOM. Opening the reaction details emits
reaction-details. The error event carries { error, operation }.
extensions: [
async event => {
if (event.type === "before-send") event.input.text = event.input.text.trim();
if (event.type === "render-message" && !event.slot.firstChild) {
const extra = document.createElement("small");
extra.textContent = "Additional information";
event.slot.append(extra);
}
},
["ccm.load", "https://example.org/chat-extensions.mjs#moderation"]
]After mount, extensions can add their own elements to app.dom.top and
app.dom.bottom, or use the per-message slot from render-message.
Other stable references on app.dom include history, composer, textarea,
user and dialog. The chat rejects a second mutation while one is in progress,
including a mutation started by a hook that the first operation is awaiting.
The test suite lives in the local test/ directory, which Git ignores.
With that directory present, run npm --prefix test test from the repository root
to check record storage, permissions and conflict handling. The browser integration test is opt-in. It
uses the real User component and a local ccm-server with isolated in-memory storage.
To include the browser test, use an existing Playwright installation and a sibling
ccm-server checkout with its dependencies installed.
CHAT_PLAYWRIGHT=/absolute/path/to/playwright/index.mjs node --test test/browser.test.mjsSet CHAT_BROWSER to use an existing Chrome or Chromium executable, CCM_SERVER_ROOT
to select a different server checkout, or CHAT_SCREENSHOT to save a screenshot.
The test checks WebSocket updates, server-side ownership restrictions, private
archives and the mobile layout. It also verifies that realtime updates preserve DOM
nodes, keyboard focus and drafts.