g-comments
v0.2.2
Published
Comments for any web page, powered by a Discourse forum.
Readme
g-comments
Comments for any web page, powered by a Discourse forum running the
discourse-comments plugin. The package root is the framework-agnostic client;
the React components (g-comments/react), the custom elements
(g-comments/element) and the default stylesheet (g-comments/styles.css)
build on it.
Install
pnpm add g-commentsOn the forum: install the plugin, then add your site's host under
Admin → Customize → Embedding (or to discourse_comments_allowed_origins).
React
React 18 or 19 is a peer dependency of g-comments/react only.
Option A: provider and drop-in components
import { CommentCount, Comments, DiscourseComments } from "g-comments/react";
import "g-comments/styles.css";
// Once, near the root of the app.
<DiscourseComments
forum="https://forum.example.com"
theme="auto" // "light" | "dark" | "auto" (prefers-color-scheme) | "inherit" | "forum"
locale="en" // "pt-BR" is bundled too; `messages` overrides single strings
appearance={{ variables: { accent: "var(--brand)", radius: "0" } }}
onEvent={(event) => analytics.track(event.type, event)}
>
<App />
</DiscourseComments>
// Per page. Without props the page URL (canonical link, else the address) and
// document.title identify the thread.
<Comments />
<Comments identifier="blog-1433307" url={canonicalUrl} title={post.title} sort="newest" />
<CommentCount url={postUrl} /> // "12 comments", fetched once, batched with the others
<CommentCount identifier="blog-1433307" render={(n) => n} /><Comments> props: identifier, url, title, sort, maxDepth (visual
nesting, default 2; deeper replies collapse into "Continue this thread"),
signIn ("inline" panel with the forum's providers, "on-submit" signs in
when an anonymous reader posts and keeps the draft, "manual" leaves it to your
UI), onSignInRequired (manual mode: called when an anonymous reader tries to
like or reply; without it those actions are unavailable, and manual mode never
opens the forum's popup itself), readOnly, highlight (comment id; defaults
to the #gc-<id> fragment), guidelinesUrl, onPosted(result), appearance,
unstyled, theme, locale, className.
Open reply, edit, report and delete panels close as soon as the reader loses the right to use them (read-only, forum degraded, signed out), and a post waiting for an on-submit sign-in is dropped if the reader cancels it or the widget goes away first.
The provider also accepts the client options (fetch, headers such as
Authorization for a forum behind basic auth, storage, clientId) or a
ready-made client, plus messages and debug. On localhost (or with
debug) a failing widget shows a diagnostics panel naming the probable setup
problem; production readers only see "Comments are unavailable right now."
onEvent receives comment.posted, comment.pending (sent to the review
queue), comment.liked, auth.signedIn, auth.signedOut (expired when the
forum ended the session) and error (with the failing action).
Option B: no provider
<Comments forum="https://forum.example.com" identifier="blog-1433307" />
<CommentCount forum="https://forum.example.com" identifier="blog-1433307" />Clients come from a page-wide registry keyed by the normalized forum URL, so
every component (and a provider) naming the same forum shares one client: one
sign-in state, one config fetch, one realtime connection. The first options
used for a forum win. clientRegistry is exported from g-comments for
non-React code.
Option C: hooks and primitives
import { Comments, useCommenter, useCommentCount, useThread } from "g-comments/react";
const { thread, snapshot, error, retry } = useThread({ identifier, sort: "newest" });
// snapshot: comments (tree), status, hasMore, pendingNew, branches, awaitingApproval, …
// thread: post, edit, remove, like, flag, pin, loadMore, loadReplies, showPending, context, …
const me = useCommenter();
// me.user, me.status, me.providers, me.degraded, me.signIn({ provider }), me.cancelSignIn(), me.signOut()
const { count } = useCommentCount({ url: postUrl });The drop-in <Comments> is assembled from primitives you can rearrange or
replace:
<Comments.Root identifier="blog-1433307" signIn="manual">
<Comments.Header>
<Comments.Count as="h3" />
<Comments.Sort />
</Comments.Header>
<Comments.SignIn>{(me) => <MyButton onClick={() => me.signIn()}>Join</MyButton>}</Comments.SignIn>
<Comments.Composer placeholder="Say something…" />
<Comments.List>
{(comment, depth) => (
<Comments.Item comment={comment} depth={depth}>
<Comments.Avatar />
<Comments.Body />
<Comments.Actions />
</Comments.Item>
)}
</Comments.List>
<Comments.LoadMore />
</Comments.Root>Also available: Comments.Meta (author, badges, permalink time),
Comments.NewComments (the live "N new comments" pill),
Comments.AwaitingApproval, Comments.Notice (closed, read-only) and
Comments.DevPanel. The List render function is reused for replies at every
depth, and Item keeps the inline reply, edit, report and delete panels.
Classic topics
A forum without nested replies (or a topic switched to classic mode) reads as
one linear list in posting order, like the forum itself: a comment that answers
another carries a "Replying to @user" link instead of being nested under it,
and thread.nested is false.
Styling
g-comments/styles.css styles everything under the widget root
(.gc-root.gc-root--styled); nothing outside it is touched. Class names follow
BEM (gc-comment, gc-comment__body, gc-composer--replying,
gc-button--primary, …) and stay in place with unstyled, which only drops
gc-root--styled. The rules live in the gc-defaults cascade layer, so your
own (unlayered) CSS wins whatever its order or specificity. Cooked comment HTML
is wrapped in .gc-prose.
appearance.elements adds class names: root, header, count, sort,
signIn, composer, textarea, toolbar, list, comment, avatar,
meta, body, actions, menu, button, primaryButton, loadMore,
pill, notice, dialog.
Tokens can be set through appearance.variables (camelCase keys), on the
widget root, or on any ancestor such as :root; values you set apply in every
colour scheme.
| Token | variables key | Light default | Dark default |
| --- | --- | --- | --- |
| --gc-font | font | system UI stack | |
| --gc-fg | fg | #1f2328 | #e6edf3 |
| --gc-fg-muted | fgMuted | #59636e | #9198a1 |
| --gc-bg | bg | #ffffff | #0d1117 |
| --gc-bg-subtle | bgSubtle | #f6f8fa | #151b23 |
| --gc-border | border | #d1d9e0 | #3d444d |
| --gc-accent | accent | #0969da | #4493f8 |
| --gc-accent-fg | accentFg | #ffffff | #0d1117 |
| --gc-danger | danger | #cf222e | #f85149 |
| --gc-radius | radius | 8px | |
| --gc-shadow | shadow | soft drop shadow | darker drop shadow |
| --gc-space | space | 0.5rem (spacing unit) | |
| --gc-avatar-size | avatarSize | 2.25rem (2rem in narrow containers) | |
theme sets data-gc-theme on the root: light, dark, or auto, which
switches with prefers-color-scheme. inherit sets nothing and derives the
neutral colours from the page's text colour, for sites that theme the widget
themselves. forum applies the forum's own look (below). The layout works
down to 320px wide.
Use the forum's look
<DiscourseComments forum="https://forum.example.com" theme="forum">theme="forum" loads the forum's theme once per forum (GET /comments/theme)
and installs it where the widget lives: the page's <head>, or the custom
element's shadow root. Three things arrive:
- Colours. Every custom property the forum's colour definitions emit is
available on the widget root as
--gc-forum-<name>(--gc-forum-primary,--gc-forum-tertiary,--gc-forum-primary-low, …), and the widget tokens default to them:fg←primary,fgMuted←primary-medium,bg←secondary,bgSubtle←primary-very-low,border←primary-low,accent←tertiary,accentFg←secondary,danger←danger. When the theme has a dark palette it applies underprefers-color-scheme: dark. - Fonts.
--gc-fontdefaults to the forum's body font;--gc-forum-font-body,--gc-forum-font-headingand--gc-forum-font-monospacecarry the stacks, and@font-facerules are added to the page for fonts the forum serves. - Theme CSS. The default theme's "Embedded CSS" (Admin → Customize →
Themes → Edit CSS/HTML → Embedded) is imported into the
gc-forumcascade layer, so forum admins can style thegc-*classes without touching the site.
Precedence, for tokens and for plain CSS alike: what a component sets
(appearance) beats the site's own CSS and --gc-* values, which beat the
forum's, which beat the defaults. Site CSS is unlayered and the forum's sits in
gc-forum above gc-defaults, so no ordering or specificity tricks are
needed. useForumTheme() returns the same data for sites that style their own
UI after the forum.
Custom elements (no framework)
g-comments/element registers <discourse-comments> and
<discourse-comment-count> when imported. The module is self-contained: React,
ReactDOM, the client and the default stylesheet are bundled (about 110 kB
gzipped), so one script tag works on any page and nothing else needs
installing. On a site that already renders with React, use g-comments/react
instead; the element keeps its own React and cannot share the page's.
<script type="module" src="https://cdn.jsdelivr.net/npm/g-comments/dist/element.js"></script>
<!-- or, with a bundler: import "g-comments/element"; -->
<discourse-comments forum="https://forum.example.com" identifier="blog-1433307"></discourse-comments>
<discourse-comment-count forum="https://forum.example.com" identifier="blog-1433307"></discourse-comment-count>Attributes mirror the React props, in kebab-case:
| <discourse-comments> | Prop | Values |
| --- | --- | --- |
| forum | forum | forum URL (required, or set element.client) |
| identifier, url, title | same | thread identity; url and title default to the page |
| sort | sort | best, hot, newest, oldest |
| sign-in | signIn | inline (default), on-submit, manual |
| theme | theme | auto (default), light, dark, inherit, forum |
| locale | locale | en, pt-BR |
| max-depth | maxDepth | number, default 2 |
| read-only, unstyled, debug | same | boolean: present means true ("false" is false) |
| highlight | highlight | comment id |
| guidelines-url | guidelinesUrl | URL |
<discourse-comment-count forum identifier host url topic-id format> takes
the <CommentCount> props the same way; format="number" renders just the
number instead of "12 comments". Counts on one page share one request.
Every attribute is also a property with the prop's name
(element.theme = "dark" sets theme="dark"; element.readOnly = false
removes read-only), so frameworks that bind properties work unchanged. Values
that are not valid for an attribute are ignored and the default applies. A
client property (not an attribute) takes a client from createClient, for
options such as headers; otherwise the element uses the page-wide shared
client for its forum, available as element.client.
The widget's events are dispatched from the element as bubbling, composed
CustomEvents named gc: plus the event type, with the event as detail:
gc:comment.posted, gc:comment.pending, gc:comment.liked,
gc:auth.signedIn, gc:auth.signedOut and gc:error. With
sign-in="manual", gc:sign-in-required fires when an anonymous reader asks
to like or reply; start your own sign-in there (for instance
element.client.auth.signIn()).
document.querySelector("discourse-comments").addEventListener("gc:comment.posted", (event) => {
analytics.track("comment", { id: event.detail.comment.id });
});The widget renders in an open shadow root with g-comments/styles.css
applied, so the page's CSS does not reach it and its CSS does not leak out.
Style it through the --gc-* tokens, which cross the shadow boundary from the
element or any ancestor, and through ::part(): every gc-* class inside the
widget is exposed as a part of the same name, modifiers included.
discourse-comments {
--gc-accent: var(--brand);
}
discourse-comments::part(gc-button--primary) {
border-radius: 999px;
}
discourse-comments::part(gc-comment--pinned) {
outline: 1px solid var(--brand);
}unstyled drops the default stylesheet's effect (the classes and parts stay),
theme="inherit" derives the neutral colours from the page's text colour, and
theme="forum" loads the forum's palettes, fonts and theme CSS into the shadow
root (see "Use the forum's look"). Tokens set on the element or an ancestor
reach the widget by inheritance, which a forum stylesheet that sets --gc-*
on .gc-root would override; with theme="forum", set your tokens on
discourse-comments::part(gc-root) instead, which always wins. The count
element has no styles of its own and inherits the page's font.
defineElements({ comments: "my-comments", count: "my-count" }) registers the
same elements under other names; names that are already defined are left
alone, so loading the module twice is harmless. Importing the module on a
server is a no-op, and the elements render nothing until they are connected
in a browser. The classes (DiscourseCommentsElement,
DiscourseCommentCountElement) and the gc:* event map are exported and
typed, including HTMLElementTagNameMap entries for querySelector.
Example apps
Neither is published. examples/vite-react renders the React components
against a forum, from the SDK source:
VITE_FORUM=http://localhost:3000 pnpm --filter example dev # http://localhost:5174examples/plain-html is a page with no framework that loads the built custom
element (pnpm build first); ?forum= points it at another forum:
pnpm --filter example-plain-html dev # http://localhost:5175Allow localhost:5174 and localhost:5175 as embedding hosts on that forum
first (bin/rake "discourse_comments:seed_dev[localhost:5175]" from a
Discourse checkout with the plugin does it for one host).
Publishing
pnpm build, pnpm test, pnpm typecheck and pnpm --filter g-comments
lint:package (publint) should all pass; pnpm --filter g-comments pack
shows what ships: dist/, styles/, this file, the changelog and the
license.
Create a client
Without React, the same client powers everything below.
import { createClient } from "g-comments";
const comments = createClient({ forum: "https://forum.example.com" });
// or share one per forum across the page:
// const comments = clientRegistry.acquire({ forum: "https://forum.example.com" });Options: fetch, headers (e.g. Authorization for a forum behind basic
auth), storage (defaults to localStorage), clientId, locale, debug.
Open the page's thread
// url defaults to <link rel="canonical"> or location.href, title to document.title
const thread = await comments.threads.open({ identifier: "blog-1433307" });
thread.subscribe(() => render(thread.snapshot()));
// snapshot(): { thread, comments (tree), sort, status, hasMore, pendingNew, error, … }
await thread.setSort("newest");
await thread.loadMore();
await thread.loadReplies(comment.id);Sign in and comment
await comments.auth.signIn(); // popup; falls back to a redirect when blocked
comments.auth.onChange(({ status, user }) => updateHeader(status, user));
thread.composer.start(); // when the composer opens
thread.composer.typing(); // on input; lets first posts skip the review queue
const result = await thread.post({ body: "Nice post!", replyTo: comment.id });
if (result.type === "pending") showAwaitingApproval(result.pending);
await thread.like(comment.id);
await comments.auth.signOut();Redirect sign-ins finish on page load (#gc_code=…), as long as the page
creates its client on load.
Realtime
Threads follow the forum's MessageBus anonymously; new top-level comments from
others wait in snapshot().pendingNew until thread.showPending(), while
replies, edits, likes and deletions apply in place. When live updates are not
available the thread refreshes every 30 s (backing off to 2 min, paused in
background tabs); snapshot().connection says which mode is active.
Counts
const counts = await comments.counts([{ url: "https://example.com/blog/1" }, { identifier: "blog-2" }]);
// { "url:https://example.com/blog/1": 3, "id:example.com/blog-2": 0 }Lookups made in the same task share one request.
Errors
Every failure is a CommentsError with a type (rate_limit carries
waitSeconds) and status. unreachable means no response at all; its hint
lists the usual setup causes (origin not allowed, basic auth blocking CORS
preflights, plugin disabled).
