Component explorer / Application controls
Named displays: commits and people
Use trusted named renderers for scalar fields and compact related records.
Presentation leaves stored values, sorting, filtering and exports unchanged. The unassigned author displays empty text.
Code for this example
These excerpts come from the code running above, formatted for reading. They focus on the component behaviour; imports, fixtures and page setup are available in Full application source below.
Register displays and declare their dependencies
The commit renderer uses its full raw value for copying. The person renderer receives the permitted related record. The same binding serves Grid and read-only Form.
From apps/showcase/src/examples/formatting/named-renderers.js
import { actionIcons, defineCompositeRenderer } from "@getaster/elements";
import { html } from "lit-html";
/** Reuse this registration on string fields; the stored hash stays complete. */
export const abbreviatedCommit = defineCompositeRenderer(["fieldPresentation"], ({ value }) => {
if (typeof value !== "string" || !value)
return "";
return html `<span class="commit-display"><code title=${value}>${value.slice(0, 8)}</code><aster-button
.label=${"Copy full commit"} .labelled=${false} .icon=${actionIcons.copy} .size=${"sm"} .confirmLabel=${"Copied"}
@click=${async (event) => {
event.stopPropagation();
const button = event.currentTarget;
try {
await navigator.clipboard.writeText(value);
button.confirmLabel = "Copied";
button.confirm();
}
catch {
button.confirmLabel = "Copy failed";
button.confirm();
}
}}></aster-button></span>`;
}, {
dependencies: {}
});
export const compactPerson = defineCompositeRenderer(["fieldPresentation"], ({ entity }) => html `<span class="compact-person"><strong>${entity.name ?? ""}</strong><a href=${`mailto:${encodeURIComponent(String(entity.email ?? "")).replace(/%40/gi, "@")}`}>${entity.email ?? ""}</a></span>`, {
dependencies: {
People: ["name", "email"]
}
});
Full application source Application code & shared presentation
import { DataContext, EditModel, keyText } from "@getaster/data";
import { CompositeRegistry, bindFieldPresentations } from "@getaster/elements";
import { html, render } from "lit-html";
import { createMockService } from "@getaster/mock";
import { abbreviatedCommit, compactPerson } from "./named-renderers.js";
const out = document.querySelector("#out");
try {
const metadata = { $Version: "4.01", $EntityContainer: "Example.Container", Example: {
Commit: { $Kind: "EntityType", $Key: ["id"], id: { $Type: "Edm.Int32" }, hash: {}, author: { $Type: "Edm.Int32", $Nullable: true, "@Core.Description": "Author" }, author_ref: { $Kind: "NavigationProperty", $Type: "Example.Person", $ReferentialConstraint: { author: "id" } }, subject: {} },
Person: { $Kind: "EntityType", $Key: ["id"], id: { $Type: "Edm.Int32" }, name: {}, email: {}, company: {}, phone: {}, identity_ref: { $Kind: "NavigationProperty", $Type: "Example.Person", $ReferentialConstraint: { id: "id" }, "@Core.Description": "Identity" }, reports: { $Kind: "NavigationProperty", $Type: "Example.Person", $Collection: true, "@Core.Description": "Reports" } },
Container: { $Kind: "EntityContainer", Commits: { $Collection: true, $Type: "Example.Commit", $NavigationPropertyBinding: { author_ref: "People" } }, People: { $Collection: true, $Type: "Example.Person", $NavigationPropertyBinding: { identity_ref: "People", reports: "People" } } },
} };
const mock = await createMockService({ metadata, data: {
Commits: [{ id: 1, hash: "e341e8fd05375e9225bd3c1e6f482847c113aef0", author: 1, subject: "Keep record display consistent" }, { id: 2, hash: "be415d7fe2295fc404df55ab82c20b73fbd2bb09", author: null, subject: "Handle an unassigned author" }],
People: [{ id: 1, name: "Ada Example", email: "ada@example.com", company: "Example Company", phone: "020 7946 0100" }],
}, wasm: new URL("../lib/odata_mock.wasm", import.meta.url) });
const ctx = await DataContext.connect(mock.transport);
const registry = new CompositeRegistry();
registry.renderer("commit-short", abbreviatedCommit);
registry.renderer("person-compact", compactPerson);
const model = { types: {
Commits: { fields: { hash: { type: "CommitHash" }, author: { ref: "People" } } },
People: { fields: { name: { type: "text" }, email: { type: "text" } }, displayField: "name", display: { renderer: "person-compact" } },
}, customTypes: { CommitHash: { base: "text", display: { renderer: "commit-short" } } } };
const binding = bindFieldPresentations(ctx, model, "Commits", registry);
const records = ctx.collection({ set: "Commits" });
await records.ensure(0, 2);
const edit = new EditModel(ctx, "Commits", keyText([1]));
out.replaceChildren();
render(html`<aster-grid .ctx=${ctx} .collection=${records} .label=${"Commits"} .fieldPresentation=${binding.presentation}
.presentation=${{ columns: { hash: {title:"Commit"}, author: {title:"Author",align:"start"}, subject: {title:"Subject"} } }}
.view=${{ columns: [{ field: "hash", title: "Commit", width: 230 }, { field: "author", title: "Author", width: 240 }, { field: "subject", title: "Subject", width: 310 }], sort: [], filters: {}, frozen: 0 }}></aster-grid>
<h2>Read-only form</h2><aster-form .model=${edit} .readOnly=${true} .fieldPresentation=${binding.presentation}
.sections=${[{ title: "Commit details", items: [{ field: "hash", title: "Commit" }, { field: "author", title: "Author" }, "subject"] }]}></aster-form>`, out);
window.addEventListener("pagehide", () => { binding.dispose(); edit.dispose(); ctx.release(records); }, { once: true });
} catch (error) {
out.setAttribute("role", "alert");
out.textContent = `Could not load the example: ${error instanceof Error ? error.message : String(error)}`;
}
<!doctype html>
<html lang="en">
<head><script type="importmap">{"imports":{"@getaster/data":"../lib/aster-ui.js","@getaster/elements":"../lib/aster-ui.js","@getaster/elements-preview":"../lib/aster-ui-preview.js","@getaster/elements-preview/rich-text":"../lib/aster-ui-rich-text.js","@getaster/data-navigator/model":"../lib/aster-data-navigator.js","@getaster/data-navigator":"../lib/aster-data-navigator.js","@getaster/mock":"../lib/aster-ui-mock.js","lit-html":"../lib/aster-ui.js","@preact/signals-core":"../lib/aster-ui.js"}}</script>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Aster UI — named displays</title>
<link rel="stylesheet" href="../lib/themes/lamplight.css"><link rel="stylesheet" href="../lib/aster-ui.css">
<style>
body { margin: 0; padding: 24px; background: var(--aster-page); color: var(--aster-text); font: 14px/1.5 var(--aster-font-ui); }
h1 { margin: 0 0 8px; font-size: 22px; } h2 { margin-top: 24px; font-size: 17px; }
p { max-width: 70ch; color: var(--aster-text-2); }
aster-grid { height: 260px; } aster-form { max-width: 600px; }
.commit-display { display: inline-flex; align-items: center; gap: var(--aster-gap); }
.compact-person { display: inline-flex; flex-direction: column; gap: calc(var(--aster-gap) / 5); }
.compact-person a { color: var(--aster-accent); }
</style>
</head>
<body>
<h1>Named field and related-record displays</h1>
<p>The same registered renderers serve the grid and read-only form. Copy keeps the complete commit value; the related author supplies the person's name and email.</p>
<div id="out" aria-live="polite">Loading the local OData service…</div>
<script type="module" src="./formatting.js"></script>
</body>
</html>
import { actionIcons, defineCompositeRenderer } from "@getaster/elements";
import { html } from "lit-html";
/** Reuse this registration on string fields; the stored hash stays complete. */
export const abbreviatedCommit = defineCompositeRenderer(["fieldPresentation"], ({ value }) => {
if (typeof value !== "string" || !value) return "";
return html`<span class="commit-display"><code title=${value}>${value.slice(0, 8)}</code><aster-button
.label=${"Copy full commit"} .labelled=${false} .icon=${actionIcons.copy} .size=${"sm"} .confirmLabel=${"Copied"}
@click=${async event => {
event.stopPropagation();
const button = event.currentTarget;
try { await navigator.clipboard.writeText(value); button.confirmLabel = "Copied"; button.confirm(); }
catch { button.confirmLabel = "Copy failed"; button.confirm(); }
}}></aster-button></span>`;
}, { dependencies: {} });
export const compactPerson = defineCompositeRenderer(["fieldPresentation"], ({ entity }) => html`<span class="compact-person"><strong>${entity.name ?? ""}</strong><a href=${`mailto:${encodeURIComponent(String(entity.email ?? "")).replace(/%40/gi, "@")}`}>${entity.email ?? ""}</a></span>`, { dependencies: { People: ["name", "email"] } });
Download showcase-catalogue.ts
export const examples = [
{ id: "formatting", navigationLabel: "Named displays", title: "Display fields and related records", category: "Fields & layouts", file: "formatting.html", action: "Explore named displays", ref: "staticMethod:bindFieldPresentations", description: "Reuse named renderers for compact people and abbreviated commits in a grid and read-only form.", task: "Copy a complete commit from its abbreviated display." },
{ id: "data-navigator", navigationLabel: "Nested views", title: "Explore projects and their related records", category: "Nested data views", file: "data-navigator.html", action: "Explore nested views", ref: "class:NestedGrid", description: "Browse related collections in a nested grid or a custom form, with independent pages and shared selection.", task: "Expand tasks and their assignees, then switch to the form view." },
{ id: "query-calculations", navigationLabel: "Calculated columns", title: "Explore calculated line totals and elapsed hours", category: "Nested data views", file: "query-calculations.html", action: "Explore calculations", ref: "class:NestedGrid", description: "Filter and sort calculated values, with exact totals across every matching page.", task: "Open order lines, change their calculation, then switch to the form view." },
{ id: "foundations", navigationLabel: "Fields & layouts", title: "Fields and layouts for everyday work", category: "Fields & layouts", file: "foundations.html", action: "Explore fields and layouts", ref: "class:CompositeField",
description: "Group related editors, keep numeric values exact, resize nested panes and navigate retained settings and context.",
task: "Edit a budget, revert its group, then resize the workspace and open its settings." },
{ id: "mail", navigationLabel: "Mail workspace", title: "Mail that keeps your draft", category: "Authentication recovery", file: "mail.html", action: "Open the mail workspace", ref: "class:Authentication",
description: "Read messages, keep several drafts open and recover an expired session through a configurable sign-in flow. The entire example uses local mock data.",
task: "Start a draft, expire the session, then send it and complete simulated sign-in." },
{ id: "tiles", navigationLabel: "Tile grids", title: "Folders & device fleets", category: "Tile grids", file: "tiles.html", action: "Explore tile grids", ref: "class:TileGrid",
description: "Browse folders or a virtual fleet of 100,000 devices. Switch between tiles and a table while keeping your selection.",
task: "Try ordered selection, change the tile size, then switch views." },
{ id: "filters", navigationLabel: "Filtering", title: "Queries you can compose", category: "Advanced filtering", file: "filtering.html", action: "Build an expression", ref: "class:FilterBuilder",
description: "Combine nested All, Any and Not groups with typed fields, platform choices, related records and relative dates.",
task: "Open Advanced filter, choose Platform, then try “is one of”." },
{ id: "reports", navigationLabel: "Reporting", title: "From rows to answers", category: "Reporting & grouping", file: "reporting.html", action: "Explore grouped reports", ref: "class:Grid",
description: "Get exact totals across every matching record, expand multiple grouping levels and export the filtered result or ordered picks.",
task: "Group by Platform → Online → Site, then download a CSV." },
{ id: "charts", navigationLabel: "Charts", title: "Charts that work with your data", category: "Component integration", file: "components.html", action: "Connect charts and grids", ref: "class:ComponentHost",
description: "Optional ECharts components share filters and selection with a grid. HTML data views provide the same keyboard and touch actions.",
task: "Choose a platform in the chart, then select a device in either view." },
{ id: "windows", navigationLabel: "Windows", title: "A workspace that keeps your place", category: "Application windows", file: "windows.html", action: "Explore application windows", ref: "class:Window",
description: "Move between device details and editable notes. Minimize, maximize and restore without recreating content, with guarded close and saved layouts.",
task: "Write a note, minimize it, then restore it from the task list." },
{ id: "dashboard", navigationLabel: "Dashboard", title: "Build your own fleet workspace", category: "Dashboard composition", file: "dashboard.html", action: "Compose a dashboard", ref: "class:Dashboard",
description: "Arrange summaries, charts, device grids and notes. Widgets share live filters and selection, with saved layouts and protected edits.",
task: "Filter by platform, add a device, then move or maximize a widget." },
{ id: "dataview", navigationLabel: "DataView", title: "A directory made of custom cards", category: "DataView", file: "dataview.html", action: "Explore DataView", ref: "group:data-view",
description: "Browse a team directory with images, custom templates, live search and server-side sorting. Selection and updates follow the shared data layer.",
task: "Sort Z to A, try compact cards, then open and rename a colleague." },
{ id: "tabs", navigationLabel: "Tabs", title: "A place for every open device", category: "Tabs", file: "tabs.html", action: "Explore tabs", ref: "class:Tabs",
description: "Open data-driven tabs with lazy panels, retained drafts and optional close actions. A scrolling strip works on touch screens and narrow windows.",
task: "Write a note, switch tabs, then try closing your unsaved device." },
{ id: "finance", navigationLabel: "Finance workspace", title: "A ledger that follows every posting", category: "Finance workspace", file: "finance.html", action: "Open the finance workspace", ref: "class:Grid",
description: "Invoices, a chart of accounts and a journal over one dataset. Posting an invoice books its entry and the service recomputes every balance up the tree.",
task: "Post an invoice, then open the chart of accounts and the journal." },
{ id: "toasts", navigationLabel: "Toasts", title: "Messages that say what is happening", category: "Toasts", file: "toasts.html", action: "Explore toasts", ref: "class:Toaster",
description: "Success, warning and error toasts, a loading toast that updates in place with progress, and a small stack that waits while a dialog is open. Errors stay until dismissed.",
task: "Export the rows, then show five messages, open the dialog and press Escape." },
] as const;
export type ExampleId = typeof examples[number]["id"];
/** The standalone editor is also available from each component example. */
export const standaloneExamples: readonly (readonly [string, string])[] = [
...examples.slice(0, 2).map(example => [example.file, example.navigationLabel] as const),
["composition.html", "Composition"],
...examples.slice(2).map(example => [example.file, example.navigationLabel] as const),
];
// Shared navigation for the independent examples; no vendor code is loaded here.
import "@getaster/elements";
import { standaloneExamples } from "../../app/catalogue.ts";
for (const [id, label, values] of [["theme", "Theme", ["lamplight", "harbour"]], ["scheme", "Scheme", ["light", "dark"]]]) {
const choice = document.querySelector(`#${id}`);
choice.label = label;
choice.options = values.map(value => ({ value, label: value[0].toUpperCase() + value.slice(1) }));
choice.value = values[0];
}
const params = new URLSearchParams(location.search);
const themes = ["lamplight", "harbour"];
const schemes = ["light", "dark"];
const theme = params.get("theme");
const scheme = params.get("scheme");
if (themes.includes(theme)) {
document.querySelector("#theme").value = theme;
document.querySelector("#identity").href = `../lib/themes/${theme}.css`;
document.documentElement.dataset.identity = theme;
}
if (schemes.includes(scheme)) {
document.querySelector("#scheme").value = scheme;
document.documentElement.dataset.scheme = scheme;
document.documentElement.style.colorScheme = scheme;
}
const nav = document.createElement("nav");
nav.className = "showcase-nav";
nav.setAttribute("aria-label", "Component examples");
const back = document.createElement("a");
back.textContent = "← Component showcase";
const defaultApp = new URL(document.querySelector('meta[name="aster-site-layout"]') ? "../showcase/" : "../", document.baseURI);
let requestedApp = defaultApp;
try { requestedApp = new URL(params.get("app") ?? defaultApp.href, location.href); } catch { /* Malformed return URLs use the showcase root. */ }
const app = requestedApp.origin === location.origin ? requestedApp : defaultApp;
app.hash = "showcase";
back.href = app.href;
nav.append(back);
const links = document.createElement("div");
links.className = "showcase-nav-links";
nav.append(links);
for (const [file, label] of standaloneExamples) {
const link = document.createElement("a");
link.textContent = label;
link.href = file;
if (location.pathname.endsWith(`/${file}`)) link.setAttribute("aria-current", "page");
links.append(link);
}
function updateLinks() {
for (const link of nav.querySelectorAll("a")) {
const url = new URL(link.href);
if (link !== back) {
url.searchParams.set("theme", document.querySelector("#theme").value);
url.searchParams.set("scheme", document.querySelector("#scheme").value);
url.searchParams.set("showcase", "1");
url.searchParams.set("app", app.pathname);
} else {
url.searchParams.set("identity", document.querySelector("#theme").value);
url.searchParams.set("scheme", document.querySelector("#scheme").value);
}
link.href = url.href;
}
}
function applyAppearance() {
const theme = document.querySelector("#theme").value;
const scheme = document.querySelector("#scheme").value;
const stylesheet = document.querySelector("#identity");
const href = new URL(`../lib/themes/${theme}.css`, document.baseURI).href;
if (stylesheet.href !== href) stylesheet.href = href;
document.documentElement.dataset.identity = theme;
document.documentElement.dataset.scheme = scheme;
document.documentElement.style.colorScheme = scheme;
updateLinks();
}
for (const id of ["theme", "scheme"]) document.querySelector(`#${id}`).addEventListener("change", applyAppearance);
applyAppearance();
const embedded = params.get("embedded") === "1" && parent !== window;
if (!embedded) {
document.querySelector("main").prepend(nav);
requestAnimationFrame(() => {
const current = links.querySelector("[aria-current]");
if (!current || links.scrollWidth <= links.clientWidth) return;
const item = current.getBoundingClientRect();
const viewport = links.getBoundingClientRect();
links.scrollBy({ left: Math.min(0, item.left - viewport.left) + Math.max(0, item.right - viewport.right), behavior: "instant" });
});
const demo = location.pathname.split("/").pop().replace(".html", "");
for (const link of document.querySelectorAll("main a[href]")) {
if (link.hasAttribute("download")) continue;
const target = new URL(link.href);
if (target.origin !== location.origin) continue;
if (["composition", "mail"].includes(demo) && /\.(?:js|yaml|css)$/.test(target.pathname)) {
const viewer = new URL(`../examples/${demo}.html`, location.href);
viewer.searchParams.set("source", target.pathname.split("/").pop());
viewer.searchParams.set("theme", document.querySelector("#theme").value);
viewer.searchParams.set("scheme", document.querySelector("#scheme").value);
viewer.hash = "application-source";
link.href = viewer.href;
} else if (!/\/(?:guide|reference)\//.test(target.pathname)) continue;
link.target = "_blank";
link.rel = "noopener";
link.setAttribute("aria-label", `${link.textContent.trim()} (opens in a new tab)`);
}
}
else {
const demo = location.pathname.split("/").pop().replace(".html", "");
document.documentElement.dataset.embedded = "";
document.documentElement.dataset.demo = demo;
document.querySelector("main").setAttribute("aria-label", document.title);
const state = () => parent.postMessage({ type: "aster-demo-state", state: { theme: document.querySelector("#theme").value, scheme: document.querySelector("#scheme").value } }, location.origin);
const height = () => parent.postMessage({ type: "aster-demo-height", height: Math.ceil(document.body.getBoundingClientRect().height) }, location.origin);
new ResizeObserver(height).observe(document.body);
for (const id of ["theme", "scheme"]) document.querySelector(`#${id}`).addEventListener("change", state);
addEventListener("message", event => {
if (event.origin !== location.origin || event.source !== parent) return;
if (event.data?.type === "aster-example-appearance" && schemes.includes(event.data.scheme)) {
document.querySelector("#scheme").value = event.data.scheme;
if (themes.includes(event.data.theme)) document.querySelector("#theme").value = event.data.theme;
applyAppearance(); state();
}
if (event.data?.type === "aster-demo-request") { state(); height(); }
});
state(); height();
}
main a { color:var(--aster-accent); text-underline-offset:4px; }
.showcase-nav { display: grid; gap: 4px; padding-bottom: 12px; margin-bottom: 20px; border-bottom: 1px solid var(--aster-rule); min-width:0; }
.showcase-nav-links { display:flex; flex-wrap:wrap; gap:4px 16px; min-width:0; }
.showcase-nav a { display: inline-flex; align-items: center; min-height: 44px; color: var(--aster-accent); text-underline-offset: 4px; }
.showcase-nav > a:first-child { margin-right: auto; }
.showcase-nav [aria-current] { font-weight: var(--aster-weight-strong); text-decoration-thickness: 2px; }
.showcase-appearance { display: inline-flex; align-items: center; gap: 8px; }
.showcase-appearance > span { color: var(--aster-text-2); font-weight: var(--aster-weight-label); }
.showcase-appearance aster-choice { width: 9rem; }
.showcase-appearance #scheme { width: 7rem; }
.showcase-grouping aster-choice { width: min(17rem, 65vw); }
/* Match the canvas to the page, including browser rubber-band overscroll. */
html, body { background:var(--showcase-canvas, var(--aster-surface)); }
body { transition:color 300ms ease; }
html:has(.mail-intro) { --showcase-canvas:var(--aster-sunk); }
@media (max-width: 720px), (pointer: coarse) and (max-width: 1024px) {
.showcase-nav-links { flex-wrap:nowrap; overflow-x:auto; scrollbar-width:none; }
.showcase-nav-links::-webkit-scrollbar { display:none; }
.showcase-nav-links a { flex:none; white-space:nowrap; }
.showcase-nav [aria-current] { scroll-margin-inline:16px; }
}
html[data-embedded] body { height:auto; min-height:0!important; padding:20px; }
html[data-embedded] .showcase-appearance:has(#scheme) { display:none; }
html[data-embedded] main > p:last-child:has(a[href="./"]) { display:none; }
html[data-embedded][data-demo="windows"] body { min-height:820px!important; }
@media(max-width:600px) { html[data-embedded] body { padding:12px; } }
.bar select { min-height:var(--aster-ctl); max-width:100%; padding:6px 10px; border:1px solid var(--aster-rule); border-radius:var(--aster-r-ctl); background:var(--aster-sunk); color:var(--aster-text); }
@media(pointer:coarse) { .bar select { min-height:44px; } }
Try the workflow
- Compare the same commit and author in the grid and read-only form.
- Copy the complete hash from its abbreviated display.
- Inspect the dependency declarations in the source.
What the example owns
The application registers JavaScript renderers and owns the display binding. The binding requests declared related fields through normal data access and passes only permitted scalar records.