Collections
Favorites (a member's starred records, ranked for a sidebar), saved items (a member's records to come back to, with a note and a reminder) and lists (named, static collections of one record type owned by a user, a team or the organization) on any registered record.
collections keeps two kinds of hand-picked record sets. Favorites are a member's own stars: any record registered in config.recordTypes can be starred, and the stars keep a rank so a sidebar shows them in the order the member drags them into. Lists are named, static collections of one record type, such as "Key accounts" or "Conference leads": a member adds records by hand or in bulk, and the list keeps them until someone removes them.
A list is the static counterpart of a saved view. A saved view stores a filter, so its rows change as the data changes; a list stores the records themselves. Like a saved view, a list belongs to one user, a team (with the teams module) or the whole organization.
Reading needs collections.read, and starring, creating personal lists and changing entries need collections.write. Creating, renaming or archiving a team or organization list needs collections.share. Admins get every permission, and members get collections.read and collections.write.
better-supabase add collectionsThe module needs tenant, permissions and subjects, and uses teams for team lists and outbox for its events.
Server code calls the collections instance on db, in the caller's organization. With gen.hooks set, better-supabase gen writes the hooks:
export const { useList: useCollections } = defineDataHooks(
"collections",
(db: AppDb) => db.collections,
);import { createCollections } from "better-supabase/blocks/collections";
await db.collections
.star(organizationId, { type: "deal", id: dealId })
.orThrow();
const stars = await db.collections.starred(organizationId).orThrow();
const keyAccounts = await db.collections
.create(organizationId, {
name: "Key accounts",
subjectType: "company",
scope: "team",
teamId,
})
.orThrow();
await db.collections.add(keyAccounts.id, [acmeId, globexId]).orThrow();"use client";
import { useCollections } from "@/lib/supabase/hooks";
const rows = useCollections({ limit: 50 });Favorites
| Method | Does |
|---|---|
star(organizationId, subject) | Stars a record at the end of the caller's favorites; a starred one stays put |
saveStarFolder({ organizationId, name }) | Creates or renames a folder of stars |
moveStar({ subject, folderId }) | Moves a star into a folder, or out of one when folderId is null |
unstar(subject) | Removes the star; false when there was none |
starred(organizationId, { type }) | The caller's stars in rank order, with each record's title and url |
reorderStar(subject, { previous, next }) | Moves a star between its neighbours' rank keys |
Stars are private: each member reads and changes only their own. The record must belong to the organization and the caller must be able to read it (FAVORITE_SUBJECT_FORBIDDEN). title and url come from the record's title and url in config.recordTypes.
These stars are separate from the search module's starred results, which only the command palette reads.
Lists
create(organizationId, { name, subjectType, scope, teamId, description }) makes a list of one subject type, which must be a registered type with a tenant column (COLLECTION_SUBJECT_TYPE_UNKNOWN). The scope defaults to user; a team list needs a team the caller belongs to.
| Method | Does |
|---|---|
add(id, subjectIds) | Adds up to 1000 records to the end, in the order given; ids already in the list are skipped |
remove(id, subjectIds) | Removes records; resolves to how many were removed |
reorder(id, subjectId, neighbors) | Moves an entry between its neighbours' rank keys |
entries(id, { limit, cursor }) | A page of entries in rank order (default 50, at most 200) with rank, addedBy, addedAt, title, url |
listsOf(subject) | The active lists the caller sees that hold a record, for a record's "In lists" panel |
list(organizationId, { subjectType, includeArchived }) | The lists the caller sees, by name (deprecated: use collectionPage) |
collectionPage({ organizationId, ...options }) | One keyset page of the lists the caller sees, with q, sorts, list filters, facets and a count |
get(id) | One list the caller sees, or a not_found error |
rename(id, { name, description }) | Changes the name or the description (null clears it) |
archive(id, archived?) | Archives a list; an archived list keeps its entries but takes no changes |
restore(id) | Brings an archived list back and records collection.restored |
add checks every record before it writes one: a record that is unknown, in another organization or unreadable fails the whole call (COLLECTION_SUBJECT_FORBIDDEN). entries returns next while there may be more; pass it as cursor.
Who sees a list follows its scope: the owner, the team's members, or every member with collections.read. Anyone who sees a list and holds collections.write changes its entries. An entry is visible only when the caller can also read its record through the record table's own policies, so a shared list never shows a record to someone who can't open it.
When a record type sets cascade: true in config.recordTypes, deleting a record deletes its entries and its stars.
Paging lists
collectionPage returns { items, hasMore, nextCursor } for the lists the caller sees (ADR 1077). Sorts are name (the default) and createdAt. Filters are subjectType and scope (lists of values, a list matches any of them) and includeArchived: ["true"]. Facets are subjectType and scope, and q searches the name and the description. collectionFacets and collectionCount read under the same options. Row security decides which lists the caller sees, and the SQL functions are page_collections and get_collection.
const page = await collections
.collectionPage({
organizationId,
filters: { subjectType: ["company"], scope: ["team", "tenant"] },
q: "accounts",
limit: 50,
})
.orThrow();
const total = await collections.collectionCount({ organizationId }).orThrow();
const one = await collections.get(page.items[0].id).orThrow();A cursor belongs to the sort it came from. A sort, filter, facet or text the entity does not declare returns an invalid_input error.
Save for later
Saved items are a member's own "come back to this" list: a record, an
optional note and an optional reminder. Like stars they are private, and the
record must be readable in the organization (SAVED_ITEM_SUBJECT_FORBIDDEN).
A message or a conversation from the messaging block
is a record too, so a chat message can be saved.
const item = await collections
.saveForLater(
organizationId,
{ type: "message", id: messageId },
{
note: "Reply after the board meeting",
remindAt: Temporal.Now.instant().add({ hours: 4 }),
},
)
.orThrow();
const open = await collections.saved(organizationId).orThrow();
await collections.completeSaved(item.id).orThrow();| Method | Does |
|---|---|
saveForLater(organizationId, subject, input) | Saves a record with note (at most 1000 characters) and remindAt; saving it again replaces both and reopens it |
saved(organizationId, { completed, limit, cursor }) | The caller's open items, newest first (default 50, at most 200), with title and url; completed: true lists done ones |
completeSaved(id, completed?) | Marks an item done, or open again with false; false when it isn't the caller's |
removeSaved(id) | Deletes an item; false when it isn't the caller's |
remindDue({ limit }) | Service role: claims the open items whose reminder is due and notifies each member once |
remindAt must be in the future. Run remindDue() from a cron or a
jobs schedule with the service role. It claims up to
limit due items (default 100, at most 500), records saved_item.reminded
for each, and with the notifications block sends
the notification type through the notifier port to the member who saved
it. createBlocks hands the port over:
const { collections } = createBlocks(
{ transport, service },
{
notifications: notificationsBlock,
collections: collectionsBlock.with({ notification: "saved_item.reminder" }),
},
);
await collections.remindDue().orThrow();A claimed item is not reminded again until it is saved with a new reminder.
The reminders block's recurrence rules stay for repeating schedules on a
record; a saved item's reminder is one-off and belongs to one member. When a
record type sets cascade: true, deleting the record deletes its saved items.
Saved views and bulk actions
A saved view can show only the records of a list: store the list's id as state.collectionId, and pass collections.where(id) as the list query's where. With the collections module installed, save checks that the list exists in the organization and is shared or the caller's own (SAVED_VIEW_COLLECTION_NOT_FOUND).
const view = defaultView(
await views.list(organizationId, "companies").orThrow(),
);
const where = view?.state.collectionId
? await collections.where(view.state.collectionId).orThrow()
: undefined;
const page = await companiesList.run(db, query, { where }).orThrow();where reads up to 500 ids (max raises it to 1000) and returns { id: { in: ids } }; pass column when the list's rows point at the record through another column. subjectIds(id) returns the same ids.
With the bulk module installed, collections.add is a built-in action, so a multi-select adds many records at once with a result per row:
await bulk
.run({
organizationId,
subjectType: "person",
rows: selectedIds,
action: "collections.add",
args: { collectionId: list.id },
})
.orThrow();Events
| Event | Data |
|---|---|
collection.created | organizationId, collectionId, subjectType, name, scope |
collection.archived | organizationId, collectionId, subjectType, name |
collection.entry_added, collection.entry_removed | organizationId, collectionId, subjectType, subjectId |
saved_item.reminded | organizationId, savedItemId, userId, subjectType, subjectId, note, remindAt |
Stars and saved items record no other events: they are a member's own bookmarks.
Hooks
The module calls before_collection_create(tenant, subject_type text, scope text), after_collection_create(collection uuid), before_collection_add(collection uuid, subject_ids text[]) and after_collection_add(collection uuid, added text[]). A before_ hook raises to refuse the write. The TypeScript client takes hooks for its methods (see extending blocks).
Wire it to ReUI
The ReUI Contacts Directory (solution-crm-3) has a multi-select toolbar with an "Add to list" action. Fill its list picker from list(organizationId, { subjectType: "person" }), offer "New list" through create, and run the action through bulk_actions.run with collections.add so each row reports its own result; a picker without the bulk module calls add(listId, selectedIds). A "Lists" filter on the directory stores the chosen list as a saved view's state.collectionId.
The Pipeline Dashboard's deal cards carry a favorite star. Read starred(organizationId, { type: "deal" }) once into a set of ids, toggle a card's star with star or unstar, and render the sidebar's "Favorites" group from the same rows, using title and url. Dragging a favorite calls reorderStar with the keys of its new neighbours.
A message's action menu gets "Save for later" with a reminder picker (in an
hour, tomorrow, next week), which calls saveForLater with the message as
the subject. A "Saved" page lists saved(organizationId) with each item's
title, url, note and reminder time, a checkbox that calls completeSaved
and a "Done" tab over saved(organizationId, { completed: true }).
Errors
| Hint | Cause |
|---|---|
COLLECTION_FORBIDDEN | the caller lacks the permission or can't change this list |
COLLECTION_NOT_FOUND | no list the caller sees |
COLLECTION_INVALID | an unknown scope, a team list without a team, or no signed-in user |
COLLECTION_NAME_REQUIRED | the name is empty |
COLLECTION_SUBJECT_TYPE_UNKNOWN | not a registered subject type with a tenant |
COLLECTION_SUBJECT_TYPE_MISMATCH | a bulk run's subject type isn't the list's |
COLLECTION_SUBJECT_FORBIDDEN | a record is unknown, in another organization or unreadable |
COLLECTION_ARCHIVED | the list is archived |
COLLECTION_TOO_MANY | more than 1000 ids in one call |
COLLECTION_RANK_INVALID | not a rank key |
FAVORITE_FORBIDDEN | the caller lacks collections.read in the organization |
FAVORITE_SUBJECT_FORBIDDEN | the record is unknown, in another organization or unreadable |
FAVORITE_INVALID | no signed-in user |
FAVORITE_RANK_INVALID | not a rank key |
SAVED_ITEM_FORBIDDEN | the caller lacks collections.read, or remindDue without the service role |
SAVED_ITEM_SUBJECT_FORBIDDEN | the record is unknown, in another organization or unreadable |
SAVED_ITEM_INVALID | no signed-in user, a note over 1000 characters or a past reminder |
RANK_KEY_INVALID | the neighbours passed to reorder or reorderStar aren't rank keys |
Your own fields
Columns you add to subject_collections with alter table in your own schema files are fields of the block (details):,
keyed by column name with their SQL type. Pass createCollections a Standard Schema
for them as fields: create, rename take them next to the block's own keys and
validate them (a bad value is a validation error), and create, rename, list return them
parsed. A column the module already uses is refused. See
your own fields.
const client = createCollections({
transport,
fields: z.object({ priority: z.number().int().positive().nullable() }),
});Without the client
db.collections is this client. Code that does not go through bsb.db() builds it with a transport and an organization id:
import { createCollections } from "better-supabase/blocks/collections";
const collections = createCollections({ transport });
await collections.star(organizationId, { type: "deal", id: dealId }).orThrow();
const stars = await collections.starred(organizationId).orThrow();
const keyAccounts = await collections
.create(organizationId, {
name: "Key accounts",
subjectType: "company",
scope: "team",
teamId,
})
.orThrow();
await collections.add(keyAccounts.id, [acmeId, globexId]).orThrow();Last updated on
Option sets
Tenant-editable items for a field such as priority or severity, with a label, color, icon and level per item, replacement when an item is removed, and starter items per brand.
Tasks
Issues and tasks on pipelines, with identifiers, parents without cycles, several assignees, priority 0 to 4, estimates, start, end and due dates, locking, projects, iterations, batched edits and a progress tree.