return function () {
$self = url('/@object/@action/' . urlencode('dashboards/grid'));
$board = is_string($_GET['board'] ?? null) && preg_match('~^[a-z0-9_-]{1,32}$~D', $_GET['board']) ? $_GET['board'] : 'main';
$base = $self . '?board=' . $board;
$grid = _class('dashboard_grid');
$guard = _class('csrf_guard');
$h = fn ($v) => $grid->h($v);
// Sample cards over the shipped product data; nothing here reads a table
$rows = _class('docs')->_sample('products')->load();
$revenue = 0.0;
$sold = 0;
$views = 0;
$by_colour = [];
foreach ($rows as $row) {
$revenue += (float) $row['price'] * (int) $row['sold'];
$sold += (int) $row['sold'];
$views += (int) $row['viewed'];
$by_colour[$row['colour']] = ($by_colour[$row['colour']] ?? 0) + (int) $row['sold'];
}
arsort($by_colour);
$by_revenue = $rows;
uasort($by_revenue, fn ($a, $b) => (float) $b['price'] * (int) $b['sold'] <=> (float) $a['price'] * (int) $a['sold']);
$by_views = $rows;
uasort($by_views, fn ($a, $b) => (int) $a['viewed'] <=> (int) $b['viewed']);
$catalogue = [
'revenue' => ['title' => 'Revenue', 'icon' => 'fa-money', 'group' => 'Sales', 'w' => 3, 'h' => 2],
'sold' => ['title' => 'Items sold', 'icon' => 'fa-shopping-cart', 'group' => 'Sales', 'w' => 3, 'h' => 2],
'conversion' => ['title' => 'Views to sales', 'icon' => 'fa-filter', 'group' => 'Sales', 'w' => 3, 'h' => 2],
'clock' => ['title' => 'Server time', 'icon' => 'fa-clock-o', 'group' => 'System', 'w' => 3, 'h' => 2],
'top_chart' => ['title' => 'Sold by product', 'icon' => 'fa-bar-chart', 'group' => 'Sales', 'w' => 6, 'h' => 5],
'top_products' => ['title' => 'Top products by revenue', 'icon' => 'fa-trophy', 'group' => 'Products', 'w' => 6, 'h' => 5],
'colours' => ['title' => 'Sold by colour', 'icon' => 'fa-tint', 'group' => 'Products', 'w' => 4, 'h' => 4],
'notes' => ['title' => 'Notes', 'icon' => 'fa-sticky-note-o', 'group' => 'Other', 'w' => 4, 'h' => 4],
'least_viewed' => ['title' => 'Least viewed', 'icon' => 'fa-eye-slash', 'group' => 'Products', 'w' => 4, 'h' => 4],
];
$bar = fn ($value, $max) => '<div class="yf-ah-bar" style="height:6px;border-radius:3px;background:rgba(127,127,127,.25);overflow:hidden">'
. '<span style="display:block;height:100%;width:' . ($max > 0 ? round($value / $max * 100) : 0) . '%;background:currentColor;opacity:.6"></span></div>';
$body = function ($id) use ($h, $rows, $revenue, $sold, $views, $by_colour, $by_revenue, $by_views, $base, $bar) {
switch ($id) {
case 'revenue':
return '<div class="docs-dash-big">$' . number_format($revenue, 0, '.', ',') . '</div><div class="small text-success">+12% on last month (sample)</div>';
case 'sold':
return '<div class="docs-dash-big">' . number_format($sold, 0, '.', ',') . '</div><div class="small text-muted">' . count($rows) . ' products</div>';
case 'conversion':
return '<div class="docs-dash-big">' . ($views > 0 ? number_format($sold / $views * 100, 1) : '0') . '%</div><div class="small text-muted">'
. number_format($views, 0, '.', ',') . ' views</div>';
case 'clock':
return '<div class="docs-dash-big" id="docs-dash-clock">' . date('H:i:s') . '</div>'
. '<button type="button" class="btn btn-default btn-outline-secondary btn-xs btn-sm" hx-get="' . $h($base . '&widget=clock') . '" hx-select="#docs-dash-clock" hx-target="#docs-dash-clock" hx-swap="outerHTML">'
. '<i class="fa fa-refresh" aria-hidden="true"></i> Refresh</button>';
case 'top_chart':
// inline SVG, no script: works in a card loaded later and under any theme (currentColor)
$top = array_slice($by_revenue, 0, 8, true);
$max = max(array_map(fn ($r) => (int) $r['sold'], $top) ?: [1]);
$svg = '<svg viewBox="0 0 320 ' . (count($top) * 22) . '" width="100%" role="img" aria-label="Sold by product" style="max-height:100%">';
$i = 0;
foreach ($top as $r) {
$w = round((int) $r['sold'] / $max * 140);
$y = $i++ * 22;
$svg .= '<text x="0" y="' . ($y + 14) . '" font-size="11" fill="currentColor">' . $h(mb_strimwidth($r['name'], 0, 22, '…')) . '</text>'
. '<rect x="130" y="' . ($y + 4) . '" width="' . $w . '" height="13" rx="2" fill="currentColor" opacity=".55"></rect>'
. '<text x="' . (134 + $w) . '" y="' . ($y + 14) . '" font-size="10" fill="currentColor">' . (int) $r['sold'] . '</text>';
}
return $svg . '</svg>';
case 'top_products':
$out = '<table class="table table-condensed table-sm" style="margin:0"><thead><tr><th>Product</th><th class="text-right text-end">Sold</th><th class="text-right text-end">Revenue</th></tr></thead><tbody>';
foreach (array_slice($by_revenue, 0, 6, true) as $r) {
$out .= '<tr><td>' . $h($r['name']) . '</td><td class="text-right text-end">' . (int) $r['sold'] . '</td><td class="text-right text-end">$'
. number_format((float) $r['price'] * (int) $r['sold'], 0, '.', ',') . '</td></tr>';
}
return $out . '</tbody></table>';
case 'colours':
$out = '';
$max = max($by_colour ?: [1]);
foreach ($by_colour as $colour => $count) {
$out .= '<div class="small">' . $h(ucfirst((string) $colour)) . ' <span class="pull-right float-end">' . (int) $count . '</span></div>' . $bar($count, $max);
}
return $out;
case 'notes':
return '<p><b>Edit layout</b> to drag cards by their handle, resize them from the corner, add more from the list or remove them; <b>Save</b> keeps the layout for this browser session.</p>'
. '<p class="small text-muted">Keyboard: focus a card, then arrows move it, Shift + arrows resize it, Delete removes it.</p>';
case 'least_viewed':
$out = '<ul class="list-unstyled" style="margin:0">';
foreach (array_slice($by_views, 0, 6, true) as $r) {
$out .= '<li>' . $h($r['name']) . ' <span class="text-muted">' . (int) $r['viewed'] . '</span></li>';
}
return $out . '</ul>';
}
return '';
};
$card = fn ($id, $meta) => '<div class="panel panel-default card docs-dash-card" data-card="' . $h($id) . '"><div class="panel-heading card-header">'
. '<i class="fa ' . $h($meta['icon']) . ' fa-fw" aria-hidden="true"></i> ' . $h($meta['title']) . '</div>'
. '<div class="panel-body card-body">' . $body($id) . '</div></div>';
// The layout lives in the visitor's session, one per ?board= (the browser tests use their own)
$_SESSION['docs_demo_dash'] = is_array($_SESSION['docs_demo_dash'] ?? null) ? array_slice($_SESSION['docs_demo_dash'], -20, null, true) : [];
$stored = &$_SESSION['docs_demo_dash'][$board];
$default = array_intersect_key($catalogue, array_flip(['revenue', 'sold', 'conversion', 'clock', 'top_chart', 'top_products', 'colours', 'notes']));
$htmx = _class('htmx');
header('Vary: HX-Request, HX-History-Restore-Request');
$widget = $_GET['widget'] ?? null;
if (is_string($widget) && $htmx->_wants_fragment()) {
return $htmx->_result(isset($catalogue[$widget]) ? $card($widget, $catalogue[$widget]) : '');
}
if (isset($_GET['save'])) {
$sent = [$_POST[$guard->TOKEN_NAME] ?? '', $_SERVER[$guard->HEADER_NAME] ?? ''];
$token_ok = (bool) array_filter($sent, fn ($t) => is_string($t) && $t !== '' && hash_equals($guard->session_token(), $t));
$layout = null;
if ( ! is_post()) {
$r = ['ok' => false, 'error' => 'method', 'layout' => [], 'code' => 405];
} elseif ( ! $token_ok) {
$r = ['ok' => false, 'error' => 'csrf', 'layout' => [], 'code' => 403];
} elseif ( ! empty($_POST['reset'])) {
$stored = null;
$r = ['ok' => true, 'error' => '', 'layout' => $grid->default_layout($default), 'code' => 200];
} elseif (($layout = $grid->parse_layout($_POST['layout'] ?? null, $catalogue)) === null) {
$r = ['ok' => false, 'error' => 'layout', 'layout' => [], 'code' => 400];
} else {
$stored = json_encode(['v' => 1, 'items' => $layout]);
$r = ['ok' => true, 'error' => '', 'layout' => $layout, 'code' => 200];
}
no_graphics(true);
$code = $r['code'];
unset($r['code']);
return _class('api')->_response_raw((string) json_encode($r, JSON_UNESCAPED_SLASHES), $code, 'json');
}
asset('htmx');
css('.docs-dash-big { font-size:26px; font-weight:600; line-height:1.2; } .docs-dash-card .panel-heading, .docs-dash-card .card-header { padding:6px 10px; font-weight:600; font-size:13px; }'
. ' .docs-dash-card .panel-body, .docs-dash-card .card-body { padding:8px 10px; font-size:13px; }');
$layout = (is_string($stored) ? $grid->parse_layout($stored, $catalogue) : null) ?? $grid->default_layout($default);
$intro = '<p class="docs-demo-intro">A dashboard grid on GridStack 14 (asset <code>gridstack</code>, MIT, no jQuery) and the
<code>yf_dashboard_grid</code> starter: <b>Edit layout</b>, then drag a card by its handle, resize it from the corner, add one from
the list (it loads from the server with htmx), remove one, <b>Auto-arrange</b>, <b>Save</b>. The layout is posted as JSON with the
session CSRF token, checked against the card list on the server (<code>yf_dashboard_grid::parse_layout()</code>) and kept in this
session. The cards are sample data; the admin builder (<code>?object=manage_dashboards&action=boards</code>, demo
<code>dashboards/builder</code>) puts the admin home cards on the same grid. Under 768 px the cards stack in one column.</p>';
return $intro . $grid->render($layout, $catalogue, $card, [
'id' => 'docs-dash',
'save' => $base . '&save=1',
'fragment' => $base . '&widget=__ID__',
'token' => $guard->session_token(),
'token_name' => $guard->TOKEN_NAME,
]);
};