fix(theme): зеркалить canonical cookie при первом boot (#13)

This commit is contained in:
Panfilov Konstantin committed 2026-10-21 20:50:25 +03:00
1 parent c6b2b227c0
commit 5ffb0f37e9
1 file changed
+13 -1
+13 -1
View File
@@ -11,7 +11,7 @@ $themeSurface = isset($themeSurface) && in_array($themeSurface, ['public', 'priv
let shown = initial; let shown = initial;
const canonical = value => typeof value === 'string' && value.length <= 128 && /^v1:(light|dark):(manual|preland):[A-Za-z0-9_-]{16,64}(?![\s\S])/.test(value) ? value : null; const canonical = value => typeof value === 'string' && value.length <= 128 && /^v1:(light|dark):(manual|preland):[A-Za-z0-9_-]{16,64}(?![\s\S])/.test(value) ? value : null;
const themeOf = value => value.split(':')[1]; const themeOf = value => value.split(':')[1];
function read() { function readCookie() {
try { try {
for (const part of document.cookie.split(';')) { for (const part of document.cookie.split(';')) {
const cookie = part.trim(); const cookie = part.trim();
@@ -20,6 +20,11 @@ $themeSurface = isset($themeSurface) && in_array($themeSurface, ['public', 'priv
if (value) return value; if (value) return value;
} }
} catch (_) {} } catch (_) {}
return null;
}
function read() {
const cookie = readCookie();
if (cookie) return cookie;
try { return canonical(window.localStorage.getItem(key)); } catch (_) { return null; } try { return canonical(window.localStorage.getItem(key)); } catch (_) { return null; }
} }
function apply(theme) { function apply(theme) {
@@ -66,5 +71,12 @@ $themeSurface = isset($themeSurface) && in_array($themeSurface, ['public', 'priv
document.addEventListener('DOMContentLoaded', refresh); document.addEventListener('DOMContentLoaded', refresh);
document.addEventListener('pjax:end', refresh); document.addEventListener('pjax:end', refresh);
refresh(); refresh();
// Только первый boot зеркалит валидную cookie и уведомляет другие вкладки
// о server import. Read-only refresh/reinit не создают цикл storage events.
const bootCookie = readCookie();
if (bootCookie) {
apply(themeOf(bootCookie));
try { if (window.localStorage.getItem(key) !== bootCookie) window.localStorage.setItem(key, bootCookie); } catch (_) {}
}
})(<?= json_encode($themeInitial, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>, <?= json_encode($themeSurface, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>); })(<?= json_encode($themeInitial, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>, <?= json_encode($themeSurface, JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT) ?>);
</script> </script>