<?php
declare(strict_types=1);
require __DIR__ . '/../src/ThemePreferenceDetector.php';
use ThemeSync\ThemePreferenceDetector;
// 1) Instantiate as early as possible in your request lifecycle.
$theme = new ThemePreferenceDetector([
// Optional: override the fallback values used before any
// Client Hint or cookie is available (e.g. very first visit).
'color-scheme' => ThemePreferenceDetector::SCHEME_LIGHT,
]);
// 2) Opt in to Client Hints for future requests (Chromium browsers).
// Safe to call even if headers can't be sent in this context.
$theme->sendAcceptCHHeader();
// 3) Use the detected preferences however you like.
$htmlClass = $theme->isDarkMode() ? ' class="dark"' : '';
$motionClass = $theme->prefersReducedMotion() ? ' reduced-motion' : '';
?>
<!doctype html>
<html<?= $htmlClass ?>>
<head>
<meta charset="utf-8">
<?= $theme->getAcceptCHMetaTag() ?>
<style>
<?= $theme->toCssVariables() ?>
body {
background: light-dark(#ffffff, #111318);
color: light-dark(#111318, #f2f2f2);
font-family: system-ui, sans-serif;
}
</style>
<?php // Only needed for browsers without Client Hints support. ?>
<?= $theme->getBootstrapScript() ?>
</head>
<body class="<?= trim($motionClass) ?>">
<h1>Theme Sync demo</h1>
<p>Detected preferences:</p>
<pre><?= htmlspecialchars(print_r($theme->all(), true)) ?></pre>
<p>
Source:
<?php if ($theme->wasDetectedFromClientHints()): ?>
HTTP Client Hints (no JS involved)
<?php elseif ($theme->wasDetectedFromCookie()): ?>
fallback cookie (set by a previous visit)
<?php else: ?>
defaults (first visit, JS about to run to set the cookie for next time)
<?php endif; ?>
</p>
</body>
</html>
|