return function () {
$self = url('/@object/@action/' . urlencode('dashboards/builder'));
$board = is_string($_GET['board'] ?? null) && preg_match('~^[a-z0-9_-]{1,32}$~D', $_GET['board']) ? $_GET['board'] : 'main';
$base = $self . '?board=' . $board;
$builder = _class('dashboard_builder');
$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();
$card = fn ($title, $icon, $group, $kind, $w, $h, array $more = []) => $more + ['title' => $title, 'icon' => $icon, 'group' => strtolower($group), 'group_title' => $group,
'kind' => $kind, 'data' => false, 'lazy' => false, 'refresh' => 0, 'cache' => 0, 'config' => [], 'scope' => 'admin', 'desc' => '', 'w' => $w, 'h' => $h,
'min_w' => 2, 'min_h' => 2, 'max_w' => 12, 'max_h' => 16];
$catalogue = [
'demo.revenue' => $card('Revenue', 'fa-money', 'Sales', 'stat', 3, 2, ['desc' => 'Money taken, by period.',
'config' => ['period' => ['type' => 'select', 'options' => ['month' => 'This month', 'year' => 'This year'], 'title' => 'Period']]]),
'demo.sold' => $card('Items sold', 'fa-shopping-cart', 'Sales', 'stat', 3, 2),
'demo.top_products' => $card('Top products', 'fa-trophy', 'Products', 'table', 6, 5, ['desc' => 'Best sellers by revenue.',
'config' => ['limit' => ['type' => 'int', 'min' => 1, 'max' => 10, 'default' => 6, 'title' => 'Rows'], 'hide_header' => ['type' => 'bool', 'title' => 'Hide header']]]),
'demo.colours' => $card('Sold by colour', 'fa-tint', 'Products', 'chart', 4, 4),
'demo.least_viewed' => $card('Least viewed', 'fa-eye-slash', 'Products', 'list', 4, 4, ['lazy' => true, 'desc' => 'Loads after the page.']),
'demo.note' => $card('Note', 'fa-sticky-note-o', 'Other', 'text', 4, 3, ['desc' => 'A text of your own.',
'config' => ['heading' => ['type' => 'text', 'max' => 120, 'title' => 'Heading'], 'text' => ['type' => 'text', 'max' => 2000, 'title' => 'Text']]]),
'demo.clock' => $card('Server time', 'fa-clock-o', 'System', 'stat', 3, 2, ['refresh' => 30]),
'demo.chart' => $card('Sold per colour', 'fa-bar-chart', 'Products', 'chart', 6, 4, ['desc' => 'Chart.js 4, drawn from JSON data.']),
];
// Smart help of the builder: suggested cards with a reason, templates whose cards fit the catalogue (yf_dashboard_smart in the admin)
$suggest = [['type' => 'demo.least_viewed', 'score' => 70, 'reason' => 'You open Products often (12 times in 30 days)'],
['type' => 'demo.chart', 'score' => 55, 'reason' => 'Your site has data for it'], ['type' => 'demo.revenue', 'score' => 40, 'reason' => 'On a board of your group']];
$templates = ['demo.shop' => ['id' => 'demo.shop', 'title' => 'Shop overview', 'icon' => 'fa-shopping-cart', 'desc' => 'Revenue, items sold, top products, chart.',
'layout' => $grid->normalize_v2(['items' => [['type' => 'demo.revenue', 'x' => 0, 'y' => 0, 'w' => 3, 'h' => 2], ['type' => 'demo.sold', 'x' => 3, 'y' => 0, 'w' => 3, 'h' => 2],
['type' => 'demo.top_products', 'x' => 0, 'y' => 2, 'w' => 6, 'h' => 5], ['type' => 'demo.chart', 'x' => 6, 'y' => 0, 'w' => 6, 'h' => 4]]], $catalogue)]];
$by_revenue = $rows;
uasort($by_revenue, fn ($a, $b) => (float) $b['price'] * (int) $b['sold'] <=> (float) $a['price'] * (int) $a['sold']);
$body = function ($type, array $conf) use ($h, $rows, $by_revenue) {
switch ($type) {
case 'demo.revenue':
$sum = 0.0;
foreach ($rows as $r) {
$sum += (float) $r['price'] * (int) $r['sold'];
}
$year = ($conf['period'] ?? 'month') === 'year';
return '<div class="docs-dash-big" data-period="' . ($year ? 'year' : 'month') . '">$' . number_format($year ? $sum * 12 : $sum, 0, '.', ',') . '</div><div class="small text-muted">'
. ($year ? 'this year (sample)' : 'this month (sample)') . '</div>';
case 'demo.sold':
return '<div class="docs-dash-big">' . number_format(array_sum(array_map(fn ($r) => (int) $r['sold'], $rows)), 0, '.', ',') . '</div>';
case 'demo.top_products':
$out = '<table class="table table-condensed table-sm" style="margin:0"><tbody>';
foreach (array_slice($by_revenue, 0, (int) ($conf['limit'] ?? 6), true) as $r) {
$out .= '<tr><td>' . $h($r['name']) . '</td><td class="text-right text-end">' . (int) $r['sold'] . '</td></tr>';
}
return $out . '</tbody></table>';
case 'demo.colours':
$by = [];
foreach ($rows as $r) {
$by[$r['colour']] = ($by[$r['colour']] ?? 0) + (int) $r['sold'];
}
arsort($by);
$out = '';
foreach ($by as $c => $n) {
$out .= '<div class="small">' . $h(ucfirst((string) $c)) . ' <span class="pull-right float-end">' . (int) $n . '</span></div>';
}
return $out;
case 'demo.least_viewed':
$by = $rows;
uasort($by, fn ($a, $b) => (int) $a['viewed'] <=> (int) $b['viewed']);
$out = '<ul class="list-unstyled" style="margin:0">';
foreach (array_slice($by, 0, 6, true) as $r) {
$out .= '<li>' . $h($r['name']) . ' <span class="text-muted">' . (int) $r['viewed'] . '</span></li>';
}
return $out . '</ul>';
case 'demo.note':
$heading = (string) ($conf['heading'] ?? '');
$text = (string) ($conf['text'] ?? 'Edit layout, then the cog of this card to write your note.');
return ($heading !== '' ? '<h4>' . $h($heading) . '</h4>' : '') . '<div data-note="1">' . nl2br($h($text), false) . '</div>';
case 'demo.clock':
return '<div class="docs-dash-big">' . date('H:i:s') . '</div>';
case 'demo.chart':
$by = [];
foreach ($rows as $r) {
$by[ucfirst((string) $r['colour'])] = ($by[ucfirst((string) $r['colour'])] ?? 0) + (int) $r['sold'];
}
$cfg = _class('charts_plugin_chartjs', 'classes/charts/')->config('bar', $by, ['options' => ['animation' => false]]);
return '<div class="yf-board-chart-wrap"><div class="yf-board-chart"><canvas data-yf-chart="' . $h((string) json_encode($cfg)) . '" role="img" aria-label="Sold per colour"></canvas></div></div>';
}
return '';
};
$render = function ($type, $conf) use ($catalogue, $builder, $grid, $body) {
$meta = $catalogue[$type] ?? null;
if ( ! $meta) {
return '';
}
$conf = $grid->normalize_conf($conf, $meta['config'] ?: null);
return $builder->frame($meta + ['type' => $type], $body($type, $conf), $conf);
};
// The board lives in the visitor's session, one per ?board= (the browser tests use their own), with its last 10 versions
$_SESSION['docs_demo_board'] = is_array($_SESSION['docs_demo_board'] ?? null) ? array_slice($_SESSION['docs_demo_board'], -20, null, true) : [];
$store = &$_SESSION['docs_demo_board'][$board];
if ( ! is_array($store)) {
$items = [];
// ?empty=1 starts the board without cards (the empty-board help)
$start = empty($_GET['empty']) ? [['demo.revenue', 0, 0, 3, 2], ['demo.sold', 3, 0, 3, 2], ['demo.clock', 6, 0, 3, 2], ['demo.top_products', 0, 2, 6, 5], ['demo.colours', 6, 2, 4, 4], ['demo.note', 0, 7, 4, 3]] : [];
foreach ($start as $n => $it) {
$items[] = ['i' => 'w' . ($n + 1), 'type' => $it[0], 'x' => $it[1], 'y' => $it[2], 'w' => $it[3], 'h' => $it[4], 'conf' => []];
}
$layout = $grid->normalize_v2(['items' => $items], $catalogue);
$store = ['title' => 'Shop overview', 'version' => 1, 'layout' => $layout, 'versions' => [['version' => 1, 'title' => 'Shop overview', 'layout' => $layout, 'created_at' => time(), 'note' => 'created']]];
}
$keep = function ($layout, $note) use (&$store) {
$store['version']++;
$store['layout'] = $layout;
$store['versions'][] = ['version' => $store['version'], 'title' => $store['title'], 'layout' => $layout, 'created_at' => time(), 'note' => $note];
$store['versions'] = array_slice($store['versions'], -10);
};
$token_ok = function () use ($guard) {
$sent = [$_POST[$guard->TOKEN_NAME] ?? '', $_SERVER[$guard->HEADER_NAME] ?? ''];
return (bool) array_filter($sent, fn ($t) => is_string($t) && $t !== '' && hash_equals($guard->session_token(), $t));
};
$htmx = _class('htmx');
header('Vary: HX-Request, HX-History-Restore-Request');
if (isset($_GET['card']) && $htmx->_wants_fragment()) {
$conf = is_string($_GET['conf'] ?? null) && strlen($_GET['conf']) <= 4000 ? json_decode($_GET['conf'], true, 4) : [];
return $htmx->_result($render(is_string($_GET['type'] ?? null) ? $_GET['type'] : '', is_array($conf) ? $conf : []));
}
if (isset($_GET['versions']) && $htmx->_wants_fragment()) {
$list = [];
foreach (array_reverse($store['versions']) as $v) {
$list[] = ['version' => $v['version'], 'title' => $v['title'], 'author' => 'you', 'created_at' => $v['created_at'], 'note' => $v['note'], 'items' => count($v['layout']['items'])];
}
return $htmx->_result($builder->versions_html($list, $store['version'], $base . '&diff=__V__', $base . '&restore=1', [$guard->TOKEN_NAME, $guard->session_token()]));
}
if (isset($_GET['diff']) && $htmx->_wants_fragment()) {
$old = null;
foreach ($store['versions'] as $v) {
(int) $v['version'] === (int) $_GET['diff'] && $old = $v;
}
return $htmx->_result($old ? $builder->diff_html($builder->diff_layouts($old['layout'], $store['layout'], $catalogue, $old['title'], $store['title'])) : '');
}
if (isset($_GET['export'])) {
no_graphics(true);
header('Content-Disposition: attachment; filename="dashboard-' . $board . '.json"');
$doc = ['schema' => 'yf.dashboard', 'schema_version' => 1, 'scope' => 'admin', 'title' => $store['title'], 'slug' => $board, 'layout' => $store['layout']];
return _class('api')->_response_raw((string) json_encode($doc, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT), 200, 'json');
}
if (isset($_GET['save'])) {
$layout = null;
if ( ! is_post()) {
$r = ['ok' => false, 'error' => 'method', 'code' => 405];
} elseif ( ! $token_ok()) {
$r = ['ok' => false, 'error' => 'csrf', 'code' => 403];
} elseif (($layout = $grid->parse_layout_v2($_POST['layout'] ?? null, $catalogue, ['scope' => 'admin'])) === null) {
$r = ['ok' => false, 'error' => 'layout', 'code' => 400];
} elseif (isset($_POST['version']) && (int) $_POST['version'] > 0 && (int) $_POST['version'] !== $store['version']) {
$r = ['ok' => false, 'error' => 'conflict', 'code' => 409];
} else {
$keep($layout, 'saved');
$r = ['ok' => true, 'error' => '', 'version' => $store['version'], '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');
}
$done = '';
if (isset($_GET['restore']) && is_post() && $token_ok()) {
foreach ($store['versions'] as $v) {
if ((int) $v['version'] === (int) ($_POST['version'] ?? 0)) {
$keep($v['layout'], 'restored version ' . (int) $v['version']);
$done = '<div class="alert alert-success yf-board-msg" role="status">Version ' . (int) $v['version'] . ' restored as version ' . (int) $store['version'] . '.</div>';
}
}
}
css('.docs-dash-big { font-size:26px; font-weight:600; line-height:1.2; }');
$intro = '<p class="docs-demo-intro">The dashboard builder of the admin (<code>yf_dashboard_builder</code>, GridStack 14, no jQuery) on sample cards:
<b>Edit layout</b>, then <b>Add a card</b> from the catalogue (search, kinds, groups; a card may be placed twice), open a card\'s
settings with its cog (or Enter), duplicate or remove it, <b>Undo</b> / <b>Redo</b>, <b>Save</b>. <b>Versions</b> lists the saved
versions with their changes and restores one; <b>Export JSON</b> downloads the board. Layouts are checked on the server
(<code>yf_dashboard_grid::normalize_v2()</code>: known cards, sizes, settings against each card\'s schema) and kept in this session.
The admin keeps boards in the database: <code>?object=manage_dashboards&action=boards</code>.</p>';
return $intro . $done . $builder->render_board(['id' => 1, 'version' => $store['version'], 'layout' => $store['layout']], $catalogue, $render, [
'id' => 'docs-board',
'title' => $store['title'],
'editable' => true,
'save' => $base . '&save=1',
'card' => $base . '&card=1',
'versions' => $base . '&versions=1',
'export' => $base . '&export=1',
'token' => $guard->session_token(),
'token_name' => $guard->TOKEN_NAME,
'suggest' => $suggest,
'templates' => $templates,
]);
};