Grouped Feed Without Flicker
elements man recipes/grouped-feedA chat feed with day separators and consecutive messages from one person
grouped into a run. The template has one e:for over the messages. Each row
has two boolean fields, startsDay and startsRun, that say whether its
message starts a day or a run. When a message arrives, only the rows whose
fields changed are updated.
One flat loop with grouping fields
Keep the loop flat. Compute one line per message. Whether the message starts a day or a run depends on the message before it, so store both answers as fields on that line:
Flat linesimport { Message as ChatMessage } from "#app/shared/services/chat"; interface Line { id: string; message: ChatMessage; dayLabel: string; startsDay: boolean; startsRun: boolean; } function dayOf(m: ChatMessage): string { return m.createdAt.toDateString(); } function lines(messages: LiveView<ChatMessage>): Line[] { let out: Line[] = []; let prev: ChatMessage | undefined; for (let m of messages.sort((a, b) => +a.createdAt - +b.createdAt)) { let startsDay = prev === undefined || dayOf(prev) !== dayOf(m); out.push({ id: m.id, message: m, dayLabel: dayOf(m), startsDay, startsRun: startsDay || prev === undefined || prev.userName !== m.userName || +m.createdAt - +prev.createdAt > 5 * 60 * 1000, }); prev = m; } return out; }
Flat loopimport { Message, MessageContent } from "@elements/ui/message"; import { MessageList } from "@elements/ui/message-list"; import { Separator } from "@elements/ui/separator"; <MessageList label={room.name}> <div e:for={line of lines(messages)} e:key={(line: Line) => line.id} class={line.startsRun ? "line" : "line is-grouped"}> <Separator e:if={line.startsDay} label={line.dayLabel} /> <Message author={line.message.userName} grouped={!line.startsRun}> <MessageContent>{line.message.body}</MessageContent> </Message> </div> </MessageList>
app/pages/room/style.css.page-room .line.is-grouped { margin-top: calc(var(--space-1) - var(--message-list-gap)); }
The row is a Message (opens in a new tab) from @elements/ui, inside the
MessageList (opens in a new tab) the chat-rooms recipe already
uses. The day separator is a Separator (opens in a new tab) with the
day as its label, under e:if on the row that starts the day, and the author
header is the Message's own: grouped hides it on every follow-up in a run
and keeps the column, so the bodies line up. The separator's e:if and
grouped are both on one row, so there is no inner loop to rebuild. The shared Message
interface is imported as ChatMessage, since the Message template has the
same name.
A MessageList tightens the gap above a grouped Message that is its direct
child. Here each Message is inside a wrapper <div>, not directly in the list, so
the page's CSS sets the smaller gap on .line.is-grouped, using the list's
--message-list-gap.
lines() mints a fresh wrapper
for every message on every change and the rows still patch: e:key pins each
line to its message id, and a wrapper whose fields hold the same values is not
a new value. Only a row whose fields changed updates. When a
message arrives, every earlier line has the same dayLabel, startsDay and
startsRun as before, so only the new row renders.
An outer loop over [day, rows] tuples works too if it is keyed by the day
(e:key={([day]) => day}): each tuple is a new array on every evaluation, and
without the key every group is rebuilt. The flat loop needs no key for the
groups, and every update stays on the one row it touches.
lines() reads createdAt, so the composer's insert passes
createdAt: new Date(), so the optimistic row is rendered in the correct
day and run as soon as it is inserted.
Reactions
A reaction belongs to a message, and a windowed feed holds only the messages
it has loaded. Store the reactions on the message row and they arrive with it:
in the first page, in every more(), and in the live update when someone
reacts. A second view of the reactions table would hold every reaction in the
room, and a lookup inside the row would scan it for each message.
Terminalelements create migration 'add reactions'
app/migrations/<timestamp>-add-reactions.migration.sql-- add reactions alter table chatMessages add column reactions jsonb not null default '{}'; create table chatReactions ( id uuid primary key default uuidGenerateV7(), createdAt timestamptz not null default now(), messageId uuid not null references chatMessages(id) on delete cascade, userId uuid not null references chatUsers(id) on delete cascade, emoji text not null, unique (messageId, userId, emoji) ); -- Fold each reaction into its message's reactions column, in one update. create or replace function chatReactionsApply() returns trigger language plpgsql as $$ begin if tg_op = 'INSERT' then update chatMessages set reactions = jsonb_set( reactions, array[new.emoji], coalesce(reactions -> new.emoji, '[]') || to_jsonb(new.userId::text)) where id = new.messageId; else update chatMessages set reactions = case when (reactions -> old.emoji) - old.userId::text = '[]' then reactions - old.emoji else jsonb_set(reactions, array[old.emoji], (reactions -> old.emoji) - old.userId::text) end where id = old.messageId; end if; return null; end; $$; create trigger chatReactionsApplyTrigger after insert or delete on chatReactions for each row execute function chatReactionsApply(); -- The notify trigger from chat-rooms, now carrying reactions. create or replace function chatMessagesNotify() returns trigger language plpgsql as $$ declare r record; payload text; begin r := coalesce(new, old); payload := json_build_object( 'op', lower(tg_op), 'data', json_build_object( 'id', r.id, 'createdAt', json_build_object('$type', 'Date', '$value', (extract(epoch from r.createdAt) * 1000)::bigint), 'roomId', r.roomId, 'userId', r.userId, 'userName', r.userName, 'body', r.body, 'reactions', r.reactions ) )::text; -- NOTIFY takes under 8000 bytes. A larger row goes as its id, and the -- server reads the row back. if octet_length(payload) >= 8000 then payload := json_build_object('op', lower(tg_op), 'id', r.id)::text; end if; perform pg_notify(channel_name('chat_messages'), payload); return r; end; $$;
chatReactions stores the reactions, one row per user, emoji and message;
the unique constraint rejects a second identical row, so a double click adds
one reaction. chatReactionsApply folds
each insert or delete into chatMessages.reactions with jsonb operators inside
one update, shaped { "👍": ["<userId>", ...] }. Two people reacting at
once queue on the row lock, and neither overwrites the other. That update
fires chatMessagesNotify, redefined here to carry reactions, so the changed
row reaches every page with the room open.
In app/shared/services/chat.ts, add the field and stop the browser from
writing it:
app/shared/services/chat.tsimport { ForbiddenError, LiveTable, session } from "@elements/app"; export interface Message { // ... reactions: Record<string, string[]>; } export let chatMessages: LiveTable<Message> = new LiveTable<Message>({ insert: (item) => { session.isLoggedInOrThrow(); return chatMessages.insert({ ...item, reactions: {}, }); }, update: () => { throw new ForbiddenError(); }, });
A message starts with no reactions whatever the browser sent, and no update
through the view can write them. Pass reactions: {} in the composer's
insert as well, so the optimistic row has a reactions object for the template to read.
A reaction is toggled by an @rpc in the room's template.ehtml. It takes
the user from the session, never from an argument, so a user can add or remove
only their own:
template.ehtml/** @rpc */ export function toggleReaction(messageId: string, emoji: string) { session.isLoggedInOrThrow(); let userId = session.getOrThrow("userId"); let removed = sql(` delete from chatReactions where messageId = ${messageId} and userId = ${userId} and emoji = ${emoji} returning id `); if (removed.empty()) { sql(` insert into chatReactions ( messageId, userId, emoji ) values ( ${messageId}, ${userId}, ${emoji} ) on conflict do nothing `); } }
The row computes the count and whether you reacted from
line.message.reactions:
template.ehtmlimport { Button } from "@elements/ui/button"; import { Toggle } from "@elements/ui/toggle"; <Message author={line.message.userName} grouped={!line.startsRun}> <MessageContent>{line.message.body}</MessageContent> <div class="cluster is-xs"> <Toggle e:for={[emoji, users] of Object.entries(line.message.reactions)} e:key={([emoji]) => emoji} size="sm" variant="outline" pressed={users.includes(session.get("userId")!)} onPressedChange={() => toggleReaction(line.message.id, emoji)}> {emoji} {users.length} </Toggle> <Button size="sm" variant="ghost" onclick={() => toggleReaction(line.message.id, "👍")}>+👍</Button> </div> </Message>
Each reaction is a Toggle (opens in a new tab): the count is the array's
length, pressed is whether it holds your id, and a press calls the rpc. The
row's reactions then change on the server and come back live, which is what
sets the toggle's state; the template never flips it on its own. The +👍
is a ghost Button (opens in a new tab). The controls are a loop inside
the row, and that fits here: the row changes exactly when its reactions do, so
rebuilding its buttons is the update.
Rules for a grouped list
- One
e:forover one flat list. A loop inside a loop rebuilds the inner one whenever the outer row updates. e:keytakes a function:e:key={(line: Line) => line.id}.- Put a grouping decision on the row as a boolean, not in a nested loop.
- A new wrapper object per row is fine: with
e:keyand equal field values, the existing row is kept. - Child rows that must load with each page of a window, such as reactions, are stored on the parent row, not in a second view.
- A template's name is a type too. Import the data type under another name
when a template has the same name:
Message as ChatMessage.
Related
livetable/mutations: inserting through a view, which broadcasts the row.recipes/chat-rooms: the full chat app this feed belongs in.ui/templates/message: the row template, andgroupedfor a follow-up.html:e:for,e:ifande:key.