/** * Browser-safe rendering helpers for data-driven apps. * * ZERO imports that execute at runtime (types only): the shell can bundle or * inline this without kody:/node: imports. These helpers only build HTML * strings from a definition + state snapshot; all mutation still goes through * server-side `act()`. The UI submits a plain GET form (edge-safe on the * package-app subdomain); the POST route remains for API clients. * Server-rendered; JS may enhance it. * * ES2019 ceiling: no ?. and no ?? in this file. */ import type { AppDefinition, AppState, AppSummary } from './types.ts' /** Escape runtime values before placing them in HTML. */ export function escapeHtml(value: string): string { return value.replace( /[&<>"']/g, function (character: string): string { if (character === '&') return '&' if (character === '<') return '<' if (character === '>') return '>' if (character === '"') return '"' return ''' }, ) } function str(value: unknown): string { if (value === undefined || value === null) return '' return String(value) } function isRecord(value: unknown): value is Record { return value !== null && typeof value === 'object' && !Array.isArray(value) } /** Read one bundle file as a string, or undefined when absent. */ function bundleFile(def: AppDefinition, path: string): string | undefined { var raw = def as unknown as Record if (!isRecord(raw['bundle'])) return undefined var files = (raw['bundle'] as Record)['files'] if (!isRecord(files)) return undefined var content = (files as Record)[path] return typeof content === 'string' ? content : undefined } /** * Inline bundle-relative asset references so the page carries no external * bundle assets: `` becomes an inline script, * `` becomes an inline style. * References with no matching bundle file are dropped, never fetched. * Absolute URLs are left untouched (validation keeps bundles self-contained). */ function inlineBundleAssets(entry: string, def: AppDefinition, used: string[]): string { var withScripts = entry.replace( /]*?)\bsrc\s*=\s*["']([^"']+)["']([^>]*)>\s*<\/script\s*>/gi, function (whole: string, pre: string, src: string): string { var content = bundleFile(def, src) if (content === undefined) return '' used.push(src) return '' }, ) return withScripts.replace( /]*?)\bhref\s*=\s*["']([^"']+)["']([^>]*?)\/?>/gi, function (whole: string, pre: string, href: string): string { if (whole.toLowerCase().indexOf('stylesheet') === -1) return whole var content = bundleFile(def, href) if (content === undefined) return '' used.push(href) return '' }, ) } /** * Render a bundle definition's entry HTML inlined for the app panel. * Only assets the entry explicitly references (`' } export function renderAppSection(def: AppDefinition, state: AppState, appBasePath: string, packageRef?: string): string { var bundleHtml: string try { bundleHtml = renderBundleContent(def, appBasePath + '/apps/' + def.id, packageRef) } catch (err) { bundleHtml = '

This bundle could not be displayed. The stored definition is damaged; reinstall it with add_app.

' } var seedHtml = renderStateSeed(def, state) var hideState = def.ui.hideState === true var fieldNames: string[] = Object.keys(def.stateSchema.fields) var hiddenAttr = hideState ? ' hidden' : '' var fields = fieldNames .map(function (field: string): string { var value = str(state[field]) return '

' + escapeHtml(field) + ': ' + '' + escapeHtml(value) + '

' }) .join('\n') var actions = def.ui.actions || [] var forms = actions .map(function (entry): string { return ( '
' + '' + '
' ) }) .join('\n') return seedHtml + '\n' + bundleHtml + '\n' + fields + '\n' + forms } /** * Render the single app panel box: title bar, body with bare section content, * and an optional back link (omitted when backHref/backLabel are empty). * Pass withHeader=false on full app pages, where the shell chrome already * names the app; overlays keep the header. Defaults to current behavior. * Used by the app page and the modal overlay alike. */ export function renderAppPanel( def: AppDefinition, state: AppState, appBasePath: string, backHref: string, backLabel: string, error?: string, withHeader?: boolean, closeHref?: string, expandHref?: string, packageRef?: string, ): string { var title = escapeHtml(def.ui.title || def.name) var content = renderAppSection(def, state, appBasePath, packageRef) var errHtml = error ? '

Error: ' + escapeHtml(error) + '

\n' : '' var back = backHref !== '' && backLabel !== '' ? '

' + escapeHtml(backLabel) + '

\n' : '' var closeBtn = typeof closeHref === 'string' && closeHref !== '' ? '' : '' var expandBtn = typeof expandHref === 'string' && expandHref !== '' ? '' : '' // On an app page the shell titlebar is the only header (withHeader=false), // so the shell chrome owns the help box and dialog; the panel renders the // help box only when it draws a header itself (modal overlays). var helpBtn = withHeader !== false && helpTextFor(def) !== undefined ? renderHelpButton(def.id) : '' var header = withHeader === false ? '' : '

' + closeBtn + '' + title + '' + helpBtn + expandBtn + '

\n' return ( '
\n' + header + '
\n' + errHtml + content + '\n
\n' + back + '
' ) } /** * Render a modal overlay for one modal-capable app: a `:target`-revealed panel * holding the same single app panel as the app page, plus a close box that * hides it again and an expand box that opens the full app page (mirroring * the widget expand box on the home screen). The outer element is a `div` * so the overlay markup contains exactly one `section.app`. Fully present * in server-rendered HTML. * * When the app defines help, the `[?]` box joins the panel titlebar and the * help dialog is rendered as this section's second element, right after the * overlay. The dialog opens via the shell client with no URL change, so * opening help leaves the overlay (and any expanded layout) exactly as it * was; closing help returns focus to the opener, never navigating. */ export function renderOverlaySection(def: AppDefinition, state: AppState, appBasePath: string, packageRef?: string): string { var panel = renderAppPanel(def, state, appBasePath, '', '', undefined, undefined, '#apps', appBasePath + '/apps/' + def.id, packageRef) var overlay = '
\n' + '
\n' + panel + '\n
\n
' var help = helpTextFor(def) if (help === undefined) return overlay return overlay + '\n' + renderHelpDialog(def.id, def.ui.title || def.name, help) } /** True when the app's default open mode is the modal overlay (fragment link + inline section). */ export function isModalApp(app: AppSummary): boolean { return app.openAs === 'modal' } /** Inline SVG icons were sanitized at validation; detect the stored variant. */ function looksLikeSvg(value: string): boolean { return value.replace(/^\s+/, '').toLowerCase().indexOf('' var textHtml = wide === true ? '' + label + '' + escapeHtml(description) + '' : '' + label + '' return ( '' + iconHtml + textHtml + '' ) } function tilesList(apps: AppSummary[], appBasePath: string, wide?: boolean): string { var items: string[] = [] for (var i = 0; i < apps.length; i++) { items.push(tileItem(apps[i], appBasePath, wide)) } return '
    \n' + items.join('\n') + '\n
' } /** Render the Pinned section (omitted when empty by the caller). */ export function renderPinnedSection(apps: AppSummary[], appBasePath: string): string { return ( '
\n' + '

Pinned

\n' + tilesList(apps, appBasePath, true) + '\n
' ) } /** Render the Recent section with a Clear control (omitted when empty by the caller). */ export function renderRecentSection(apps: AppSummary[], appBasePath: string, formBase?: string): string { return ( '
\n' +'

Recent

' + '
' + '' + '
\n' + tilesList(apps, appBasePath) + '\n
' ) } /** Edit-mode entry point, shown only when at least one app is installed. * The caller decides availability: an all-hidden registry still offers * Edit, even though its visible All list is empty. A GET form matches the * Clear control, so both header actions render as the same button. */ export function editAppsLink(appBasePath: string, formBase?: string): string { var base = typeof formBase === 'string' && formBase !== '' ? formBase : appBasePath + '/apps' return ( '
' + '' + '
' ) } /** Render the All-apps section in browse mode. The Apps page is a launcher: * the All apps header carries the Edit link (to Edit mode) when at least one * app is installed. */ export function renderAllSection( apps: AppSummary[], appBasePath: string, formBase?: string, hint?: string, editAvailable?: boolean, ): string { var list = tilesList(apps, appBasePath) var editLink = editAvailable === true ? ' ' + editAppsLink(appBasePath, formBase) : '' return ( '
\n' +'

All apps

' + editLink + '
\n' + (typeof hint === 'string' && hint !== '' ? '

' + escapeHtml(hint) + '

\n' : '') + list + '\n
' ) } /** Monochrome line icon for one Edit toggle. Strokes follow the button's * text color, so the icon inverts with the pressed state. */ function editToggleIcon(param: string): string { if (param === 'pin') { return ( '' ) } if (param === 'hide') { return ( '' ) } return ( '' ) } /** One state toggle for an Edit row: an icon-only submit button. Its * aria-checked and pressed appearance carry the current state; the hidden * `want` field submits the opposite value, so no JavaScript is required. */ function editToggleForm(formBase: string, param: string, id: string, label: string, isOn: boolean): string { return ( '
' + '' + '' + '' + '
' ) } /** Render the Apps Edit section: one row per installed app, every * installed app including hidden ones, alphabetical by label with id * as tie-break, each row with Pin/Unpin, Hide/Unhide, and Add to * home/Remove from home as plain GET forms through the /apps * mutation route, 303-ing back to ?edit=1. Pinned/Recent stay tiles; * only this section lists rows. No JavaScript is required. */ export function renderEditSection( apps: AppSummary[], pinnedIds: string[], hiddenIds: string[], homepageIds: string[], appBasePath: string, formBase?: string, ): string { var base = typeof formBase === 'string' && formBase !== '' ? formBase : appBasePath + '/apps' var sorted = apps.slice() sorted.sort(function (a, b): number { var al = a.label.toLowerCase() var bl = b.label.toLowerCase() if (al < bl) return -1 if (al > bl) return 1 if (a.id < b.id) return -1 if (a.id > b.id) return 1 return 0 }) var items: string[] = [] for (var i = 0; i < sorted.length; i++) { var app = sorted[i] var rawIcon = app.icon || '#' var icon = looksLikeSvg(rawIcon) ? rawIcon : escapeHtml(rawIcon) var isPinned = pinnedIds.indexOf(app.id) !== -1 var isHidden = hiddenIds.indexOf(app.id) !== -1 var isHome = homepageIds.indexOf(app.id) !== -1 var controls = editToggleForm(base, 'pin', app.id, 'Pinned', isPinned) + editToggleForm(base, 'hide', app.id, 'Hidden', isHidden) + editToggleForm(base, 'home', app.id, 'On home', isHome) items.push( '
  • ' + '' + '' + escapeHtml(app.label) + '' + (app.description ? '' + escapeHtml(app.description) + '' : '') + '' + controls + '' + '
  • ', ) } return ( '
    \n' + '

    Edit apps

    \n' + '
      \n' + items.join('\n') + '\n
    \n
    ' ) } /** * Render a plain list of installed apps (fallback content). * The shell's preferred home rendering is its own themed tile grid. */ export function renderHomeTiles(apps: AppSummary[], appBasePath: string): string { if (apps.length === 0) return '

    No apps yet.

    ' return ( '' ) } /** * Render one dashboard widget: the app's own compact view (same bare content * as the app page) with live state, action forms that PRG back to `/`, * up/down reorder controls, and a link to the full app page. * * `index`/`total` position the widget in homepage order; boundary buttons * render disabled. Fully present in server-rendered HTML. */ export function renderWidgetSection( def: AppDefinition, state: AppState, appBasePath: string, index: number, total: number, error?: string, packageRef?: string, ): string { var title = escapeHtml(def.ui.title || def.name) var content = renderAppSection(def, state, appBasePath, packageRef) var errHtml = error ? '

    Error: ' + escapeHtml(error) + '

    \n' : '' var upDisabled = index <= 0 ? ' disabled' : '' var downDisabled = index >= total - 1 ? ' disabled' : '' return ( '
    \n' + '

    ' + title + '

    \n' + '
    \n' + errHtml + content + '\n
    \n' + '
    \n' + '
    ' + '' + '
    \n' + '
    ' + '' + '
    \n' + '
    \n
    ' ) } /** * Shared empty-state help block (empty-install + mini-apps-user-facing). * Rendered by the Apps page when no apps are installed and by * Home when the homepage is empty and no apps are installed at all. * One block, not two copies, so the two pages cannot silently diverge. * Prompts are plain selectable text in gate-hint code blocks — no copy * button, no Clipboard API (on-device Scribe test: navigator.clipboard * writeText/readText are denied with NotAllowedError). * appBasePath is accepted so call sites pass the same context as the * other renderers; the help text currently contains no links. * * The built-in Help page passes `omitClosing: true`: the closing line * ("Once an app is installed...") is true of the first-run empty * state, not of the Help page itself. Empty Home / empty Apps keep it. */ /** * The full package reference for agent prompts: @owner/leaf. The owner * is the subdomain of the Kody host (hypercubed in hypercubed.kody.run); * the leaf is the mount (the first path segment of the base path). On a * non-Kody host (local mock, localhost) there is no owner, so the bare * leaf is the reference. Mirrors the Store bundle's storePackageSlug. */ export function packageRefForHost(host: string, appBasePath: string): string { var leaf = 'kody-os' if (appBasePath) { var base = appBasePath.charAt(0) === '/' ? appBasePath.slice(1) : appBasePath var slash = base.indexOf('/') var first = slash === -1 ? base : base.slice(0, slash) if (first) { leaf = first } } var suffix = '.kody.run' if (host && host.length > suffix.length && host.slice(host.length - suffix.length) === suffix) { var owner = host.slice(0, host.length - suffix.length) if (owner) { return '@' + owner + '/' + leaf } } return leaf } export function renderEmptyHelp(appBasePath: string, opts?: { omitClosing?: boolean; packageRef?: string }): string { // The full @owner/leaf reference when the caller supplies it (the // shell derives it from the request host + mount); otherwise the // bare leaf from the mount, as before. var slug = 'kody-os' if (opts && typeof opts.packageRef === 'string' && opts.packageRef !== '') { slug = opts.packageRef } else if (appBasePath) { var base = appBasePath.charAt(0) === '/' ? appBasePath.slice(1) : appBasePath var slash = base.indexOf('/') var first = slash === -1 ? base : base.slice(0, slash) if (first) { slug = first } } var ops = 'Read package:' + slug + '#OPERATIONS.md' var block = '

    No apps installed yet. This shell starts empty \u2014 nothing is installed until you add it. Pick a path below. Copy a prompt into a Kody-connected agent.

    \n' + '

    Add your own apps

    \n' + '

    ' + ops + ', then add a new app: Name: [display name]; What it does: [describe what it should do]

    \n' + '

    Remove an app

    \n' + '

    ' + ops + ', then remove this app: [app id]

    \n' + '

    Install the App Catalog

    \n' + '

    ' + ops + ', then install this app: https://github.com/Hypercubed/kody-os/tree/main/catalog/app-store

    \n' if (opts && opts.omitClosing === true) return block return block + '

    Once an app is installed your apps show up on the Apps page.

    ' } /** * Render the widget dashboard grid. An empty homepage list renders one of * two honest empty states: the shared empty help block when no apps * are installed at all, or a short Add-to-home message when apps are * installed but none are on Home. */ export function renderDashboard(widgets: string[], appBasePath: string, hasApps: boolean, packageRef?: string): string { if (widgets.length === 0) { if (hasApps === true) { return ( '
    \n' + '

    Add some to Home from the Apps page. Open Apps, tap Edit, and use Add to home on a row. They appear here live.

    \n' + '
    ' ) } return ( '
    \n' + renderEmptyHelp(appBasePath, packageRef ? { packageRef: packageRef } : undefined) + '\n
    ' ) } return '
    \n' + widgets.join('\n') + '\n
    ' }