PHP Classes

File: examples/example.php

Recommend this page to a friend!
  Packages of AKONO Metsam Nathan   Theme Sync - Server-Side UI Preference Detector   examples/example.php   Download  
File: examples/example.php
Role: Example script
Content type: text/plain
Description: Full working example demonstrating theme detection and FOUC-free rendering. Run with: php -S localhost:8000 -t examples
Class: Theme Sync - Server-Side UI Preference Detector
Detect dark mode, contrast and motion preferences
Author: By
Last change:
Date: 15 days ago
Size: 1,748 bytes
 

Contents

Class file image Download
<?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>