<?php
/**
* Framework-free example: Grid, Chart, Scheduler, Forms, Tabs, Modal and Notifications with plain PHP.
*
* composer install && npm install && npm run build
* php -S localhost:8000 examples/plain/index.php
*/
declare(strict_types=1);
use Caelrik\Ui\Assets;
use Caelrik\Ui\Components\Chart;
use Caelrik\Ui\Components\Form;
use Caelrik\Ui\Components\Form\Field;
use Caelrik\Ui\Components\Grid;
use Caelrik\Ui\Data\ArrayDataSource;
require dirname(__DIR__, 2) . '/vendor/autoload.php';
$path = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/';
// Serve the prebuilt bundle (caelrik.js, caelrik.css, chunks/*) from the package's public/ directory.
if (str_starts_with($path, '/assets/')) {
$public = realpath(dirname(__DIR__, 2) . '/public');
$file = realpath($public . '/' . substr($path, strlen('/assets/')));
$inside = $public !== false && $file !== false && str_starts_with($file, $public . DIRECTORY_SEPARATOR);
if (!$inside || !is_file($file)) {
http_response_code(404);
exit('Asset not found. Run "npm run build" first.');
}
$types = ['css' => 'text/css', 'js' => 'text/javascript', 'map' => 'application/json'];
header('Content-Type: ' . ($types[pathinfo($file, PATHINFO_EXTENSION)] ?? 'application/octet-stream'));
readfile($file);
exit;
}
$people = require __DIR__ . '/people.php';
$grid = Grid::make('people')
->caption('People')
->url('/people.json')
->column('id', 'ID', static fn ($column) => $column->searchable(false))
->column('name')
->column('email', 'E-mail')
->column('city')
->export('copy', 'csv', 'print');
if ($path === '/people.json') {
header('Content-Type: application/json');
echo json_encode($grid->respond(new ArrayDataSource($people), $_GET));
exit;
}
$perCity = array_count_values(array_column($people, 'city'));
ksort($perCity);
$chart = Chart::make('cities')
->type('bar')
->title('People per city')
->labels(array_keys($perCity))
->dataset('People', array_values($perCity))
->height(280);
session_start();
$_SESSION['csrf'] ??= bin2hex(random_bytes(16));
require __DIR__ . '/calendar.php';
require __DIR__ . '/article.php';
$errors = [];
$message = null;
if ($path === '/contact' && ($_SERVER['REQUEST_METHOD'] ?? 'GET') === 'POST') {
if (!hash_equals($_SESSION['csrf'], (string) ($_POST['_token'] ?? ''))) {
http_response_code(419);
exit('Invalid CSRF token.');
}
if (filter_var($_POST['email'] ?? '', FILTER_VALIDATE_EMAIL) === false) {
$errors['email'] = 'Please enter a valid e-mail address.';
}
if (mb_strlen(trim((string) ($_POST['message'] ?? ''))) < 10) {
$errors['message'] = 'The message must be at least 10 characters.';
}
$message = $errors === [] ? 'Thanks, your message was sent.' : null;
}
// ?mode=dark: Bootstrap's dark mode. ?custom=1: the theme saved with the theme builder
// (theme-builder.php).
$mode = ($_GET['mode'] ?? '') === 'dark' ? 'dark' : 'light';
$customTheme = isset($_GET['custom'], $_SESSION['theme']) ? '/custom-theme.css' : null;
$form = Form::make('contact')
->action('/contact')
->csrf($_SESSION['csrf'])
->add(
Field::text('name')->required()->maxLength(80),
Field::email('email')->required(),
Field::tel('phone')->mask('(999) 999-9999')->help('Optional.'),
Field::textarea('message')->required()->minLength(10),
)
->errors($errors)
// Only re-fill this form when it is the one that was posted.
->values($path === '/contact' && $message === null ? $_POST : [])
->submit('Send');
require __DIR__ . '/ui.php';
require __DIR__ . '/files.php';
require __DIR__ . '/theme-builder.php';
?>
<!doctype html>
<html lang="en" data-bs-theme="<?= $mode ?>">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Caelrik UI ? plain PHP example</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css">
<script src="https://cdn.jsdelivr.net/npm/jquery@4.0.0/dist/jquery.min.js" defer></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js" defer></script>
<?= Assets::tags('/assets', customTheme: $customTheme) ?>
</head>
<body>
<main class="container py-4">
<h1 class="h3 mb-3">Caelrik UI ? plain PHP</h1>
<nav class="mb-4 small" aria-label="Theme">
Mode:
<?php foreach (['light', 'dark'] as $m) : ?>
<?php $current = $m === $mode && $customTheme === null ? ' aria-current="page"' : '' ?>
<a href="?mode=<?= $m ?>"<?= $current ?>><?= ucfirst($m) ?></a>
<?php endforeach ?>
<?php if (isset($_SESSION['theme'])) : ?>
<?php $current = $customTheme === null ? '' : ' aria-current="page"' ?>
· <a href="?custom=1&mode=<?= $mode ?>"<?= $current ?>>Saved theme</a>
<?php endif ?>
· <a href="/theme-builder">Theme builder</a>
</nav>
<section class="mb-5" aria-labelledby="grid-title">
<h2 id="grid-title" class="h5">Grid (server-side)</h2>
<?= $grid ?>
</section>
<section class="mb-5" aria-labelledby="chart-title">
<h2 id="chart-title" class="h5">Chart</h2>
<?= $chart ?>
</section>
<section class="mb-5" aria-labelledby="scheduler-title">
<h2 id="scheduler-title" class="h5">Scheduler</h2>
<p class="text-body-secondary small">
Drag or resize an event to move it, select a time range to create one, click an event to delete it.
</p>
<?= $scheduler ?>
</section>
<section class="mb-5" aria-labelledby="form-title">
<h2 id="form-title" class="h5">Form</h2>
<?= $form ?>
</section>
<section class="mb-5" aria-labelledby="files-title">
<h2 id="files-title" class="h5">File manager</h2>
<?= $fileManager ?>
</section>
<section class="mb-5" aria-labelledby="ui-title">
<h2 id="ui-title" class="h5">Tabs, modal and notifications</h2>
<?= $tabs ?>
<p class="mt-3"><?= $newsletterModal->trigger('Subscribe to the newsletter') ?></p>
<?= $newsletterModal ?>
</section>
<section class="mb-5" aria-labelledby="article-title">
<h2 id="article-title" class="h5">Rich text and uploads</h2>
<?php if ($article !== null) : ?>
<div class="alert alert-success" role="status">
<p class="mb-2">Published ?<?= htmlspecialchars($article['title']) ?>?.</p>
<p class="mb-2 small">
Cover: <?= htmlspecialchars($article['cover']->originalName) ?>
(<?= htmlspecialchars($article['cover']->mimeType) ?>,
stored as <?= htmlspecialchars($article['cover']->name) ?>)
<?php foreach ($article['attachments'] as $file) : ?>
<br>Attachment: <?= htmlspecialchars($file->originalName) ?>
<?php endforeach ?>
</p>
<?php /* Sanitized by EditorHtml::sanitize(), so it is safe to output as HTML. */ ?>
<div class="border rounded p-2 bg-body"><?= $article['body'] ?></div>
</div>
<?php endif ?>
<?= $articleForm ?>
</section>
</main>
<?= $notification ?>
</body>
</html>
|