Source code
src/showcase/pages/records.js
This file is included in this documentation build. It is displayed as code and is not executed.
/**
* Complete resource and user list workflows built on the same reusable table controller.
*
* @author Laurent Declercq l.declercq@agon-innovation.ch
* @version 20260923
*/
import { dataTable, openDialog, extendComponent } from '@agon/atrium';
import { liveResource, usageStyle, watchLiveUpdates } from '../adapters/live.js';
/**
* Validate safe example fields without treating demo logic as backend authorization.
*
* @param {object} form - Editable record.
* @param {string} collection - resources or users.
* @param {Function} translate - Localized message lookup.
* @returns {Record<string, string>} Field errors.
*/
export function validateRecord(form, collection, translate) {
const errors = {};
if (!String(form.name || '').trim()) {
errors.name = translate('required');
}
if (collection === 'users' && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email || '')) {
errors.email = translate('invalidEmail');
}
return errors;
}
/**
* Build an editable list for two distinct record types without duplicating table behavior.
*
* @param {object} services - Demo adapters, replaceable by a real API.
* @param {string} collection - resources or users.
* @returns {object} Alpine record-list provider.
*/
export function recordsPage(services, collection) {
const isUser = collection === 'users';
let stopLive;
const columns = isUser
? [
{ id: 'name', label: 'name', type: 'title', sortable: true },
{ id: 'email', label: 'email', sortable: true },
{ id: 'role', label: 'role', translate: true, sortable: true },
{ id: 'status', label: 'status', type: 'status', sortable: true }
]
: [
{ id: 'name', label: 'name', type: 'title', sortable: true },
{ id: 'type', label: 'type', translate: true, sortable: true },
{ id: 'status', label: 'status', type: 'status', sortable: true },
{ id: 'usage', label: 'usage', type: 'progress', sortable: true },
{ id: 'region', label: 'region', sortable: true }
];
const baseTable = dataTable({
/**
* Load the requested demo collection through the shared table contract.
*
* @param {object} query - Normalized table query and cancellation signal.
* @returns {Promise<{items: Array<object>, total: number}>} Resolves with the operation result.
*/
load: (query) => services.list(collection, { ...query, live: !isUser }),
columns,
path: `/${collection}`,
/**
* Open a user editor or navigate to the selected resource detail.
*
* @param {object} row - Current record.
* @param {object} table - Active table controller.
* @returns {void}
*/
open: (row, table) => {
if (isUser) {
table.editRecord(row);
} else {
table.$router.push(`/resources/${encodeURIComponent(row.id)}`);
}
}
});
const initializeTable = baseTable.init;
const destroyTable = baseTable.destroy;
return extendComponent(
baseTable,
{
/**
* Start resource telemetry while retaining the shared table initialization.
*
* @returns {void} Loads rows and owns one timer for resource lists only.
*/
init() {
initializeTable.call(this);
if (!isUser) {
stopLive = watchLiveUpdates(
/**
* Update visible telemetry in place without resetting selection, paging, or drafts.
*
* @returns {void} Updates existing rows when no list request is pending.
*/
() => {
if (!this.loading) {
const time = Date.now();
for (const row of this.rows) {
Object.assign(row, liveResource(row, time));
}
}
}
);
}
},
/**
* Release live updates and the shared table's pending request.
*
* @returns {void} Stops all route-owned work.
*/
destroy() {
stopLive?.();
destroyTable.call(this);
},
/**
* Use the same utilization colors as dashboard resource cards.
*
* @param {object} row - Visible resource record.
* @param {object} column - Numeric progress column definition.
* @returns {string} Bounded progress width and threshold color.
*/
progressStyle(row, column) {
return usageStyle(row[column.id]);
},
/** @type {string} Domain collection owned by the consuming application. */
collection,
/** @type {object} Detached editable form state. */
form: {},
/** @type {Record<string, string>} Field validation errors. */
errors: {},
/** @type {boolean} Duplicate-submit guard. */
saving: false,
/** @type {string} Demo-only service state selector. */
scenario: 'normal',
/** @type {boolean} Card/table view preference. */
cardView: false,
/**
* Initialize a new record and show its editor.
*
* @returns {void}
*/
createRecord() {
this.form = {
name: '',
email: '',
description: '',
type: 'application',
status: 'active',
region: 'Zurich',
role: 'viewer',
notes: ''
};
this.errors = {};
openDialog('record-editor');
},
/**
* Edit a detached copy to prevent cancelled edits changing table data.
*
* @param {object} row - Existing record.
* @returns {void}
*/
editRecord(row) {
this.form = { ...row };
this.errors = {};
openDialog('record-editor');
},
/**
* Validate, save, and refresh the current page of results.
*
* @returns {Promise<void>}
*/
async saveRecord() {
if (this.saving || !this.$store.session.can(`${collection}.write`)) {
return;
}
this.errors = validateRecord(this.form, collection, this.$t);
if (Object.keys(this.errors).length) {
this.$nextTick(
/**
* Focus the first invalid field after the edit dialog updates.
*
* @returns {void}
*/
() => document.querySelector('.ui-dialog [aria-invalid="true"]')?.focus()
);
return;
}
this.saving = true;
try {
await services.save(collection, { ...this.form, name: this.form.name.trim() });
this.$dispatch('dialog-close');
this.$store.toasts.push(this.$t(isUser ? 'userSaved' : 'resourceSaved'));
await this.refresh();
} catch (error) {
this.$store.toasts.push(this.$t(error.message), 'danger');
} finally {
this.saving = false;
}
},
/**
* Open a concrete bulk-removal confirmation.
*
* @returns {void}
*/
confirmRemove() {
if (this.selected.length) {
openDialog('remove-records');
}
},
/**
* Remove only explicitly selected demo records.
*
* @returns {Promise<void>}
*/
async removeSelected() {
if (this.saving || !this.$store.session.can(`${collection}.write`)) {
return;
}
this.saving = true;
try {
await services.remove(collection, [ ...this.selected ]);
this.$dispatch('dialog-close');
await this.refresh();
this.$store.toasts.push(this.$t('resourceDeleted'));
} finally {
this.saving = false;
}
},
/**
* Apply a demo request state then refresh.
*
* @returns {void}
*/
changeScenario() {
services.scenario(collection, this.scenario);
this.refresh();
}
}
);
}
/**
* Register the records page provider after its route module is requested.
*
* @param {object} context - Application runtime and consumer-owned services.
* @param {object} context.Alpine - Active Alpine runtime.
* @param {object} context.services - Consumer-owned services.
* @returns {void} Makes the page controller available before template mounting.
*/
export function register({ Alpine, services }) {
Alpine.data(
'recordsPage',
/**
* Construct a fresh records controller for the mounted page.
*
* @param {string} collection - Consumer-selected page variant.
* @returns {object} New page provider with its own lifecycle state.
*/
(collection) => recordsPage(services, collection)
);
}