From b84eed3be52b332ab03a7f54486bc365f1cc0b80 Mon Sep 17 00:00:00 2001 From: martbost Date: Sun, 1 Nov 2026 10:44:40 -0600 Subject: [PATCH] Theme switch: auto | light | dark, stored in localStorage ls.theme and on the account, applied before first paint on every page themehead.js is the one source of the tiny inline head script (and of AUTO_DEFAULT, the one constant Marty decides later: 0 = nothing stored keeps the page's current look, light for Control Room and public pages, dark for the sapphire pages; 1 = follow the device). The script sets data-theme on from ls.theme (auto follows prefers-color-scheme and tracks changes live) and exposes window.LSTheme. tools/stamp-theme-head.cjs writes it into every static page before the first stylesheet with data-theme-base on ; blog, leaderboard, what's-new, the badge page, the unsubscribe page and the wall 404 read the module directly. The site CSP allows inline scripts by hash only, so themehead.CSP_HASH joins script-src (the script was silently blocked until then). Account side: accounts.theme (JSON store and MySQL, alterSafe column), in the public account JSON and /api/me; POST /api/my/profile {theme} rides the existing profile save path and never touches the username. cr-shell.js renders a Light / Dark / Auto segmented control in the topbar of every Control Room screen and paints every .theme-seg on the page (the Profile pane gains an Appearance card with the same control); a click applies at once, saves locally and to the account when signed in; at sign-in the account value wins over the local one, and a local choice is pushed up when the account has none yet. view.html stops reading an undefined --bg so its light variant has a light stage. ?v= tags bumped on every changed stylesheet and script (20261101t / ls20261101t). Co-Authored-By: Claude Fable 5.1 --- accounts.js | 7 ++++++- blog.js | 7 ++++--- db.js | 3 ++- leaderboard.js | 7 ++++--- public/admin.html | 15 ++++++++------- public/ads.html | 9 +++++---- public/contract.html | 7 ++++--- public/conversion-tracking.html | 17 +++++++++-------- public/conversions.html | 9 +++++---- public/credits.html | 15 ++++++++------- public/disclaimer.html | 5 +++-- public/earning.html | 9 +++++---- public/help.html | 7 ++++--- public/index.html | 5 +++-- public/join.html | 11 ++++++----- public/launch.html | 23 ++++++++++++----------- public/ledger.html | 7 ++++--- public/links.html | 25 +++++++++++++------------ public/my.html | 26 ++++++++++++++++---------- public/pages.html | 11 ++++++----- public/partners.html | 15 ++++++++------- public/plays.html | 17 +++++++++-------- public/privacy.html | 5 +++-- public/publishers.html | 11 ++++++----- public/refuel.html | 11 ++++++----- public/reports.html | 11 ++++++----- public/shorts.html | 5 +++-- public/sources.html | 13 +++++++------ public/support.html | 11 ++++++----- public/team.html | 7 ++++--- public/terms.html | 5 +++-- public/traffic-guide.html | 11 ++++++----- public/tx.html | 7 ++++--- public/view.html | 7 ++++--- public/wall.html | 7 ++++--- public/wallet.html | 7 ++++--- public/wallets.html | 17 +++++++++-------- public/zones.html | 11 ++++++----- releases.js | 7 ++++--- server.js | 21 ++++++++++++++------- themehead.js | 33 +++++++++++++++++++++++++++++++++ tools/stamp-theme-head.cjs | 23 +++++++++++++++++++++++ 42 files changed, 299 insertions(+), 188 deletions(-) create mode 100644 themehead.js create mode 100644 tools/stamp-theme-head.cjs diff --git a/accounts.js b/accounts.js index 633675e..feee990 100644 --- a/accounts.js +++ b/accounts.js @@ -38,8 +38,10 @@ const pub = a => a ? { email: a.email, sponsorRef: a.sponsorRef || '', code: a.c avatarUrl: a.avatarUrl || null, bio: a.bio || null, socials: a.socials || null, profileQuarantined: !!a.profileQuarantined, // 2026-10-30: first profile save of a brand-new free account planted a link; stored, never rendered publicly (spamscan.js) chatAvailable: a.chatAvailable === false ? false : true, lastSeen: a.lastSeen || 0, + theme: a.theme || null, // 2026-11-01 appearance: auto | light | dark, follows the member across browsers (cr-shell.js) address: a.address || null, created: a.created } : null; const USER_RE = /^[a-zA-Z0-9_]{3,20}$/; +const THEMES = new Set(['auto', 'light', 'dark']); const normUser = u => String(u || '').trim().toLowerCase(); // ---- JSON fallback ---- @@ -128,6 +130,7 @@ const J = { return { ok: true, account: pub(acct) }; }, async touchSeen(e) { const a = this.db.byEmail[e]; if (a) { a.lastSeen = Date.now(); this.save(); } }, + async setTheme(e, t) { const a = this.db.byEmail[e]; if (!a) return { error: 'No such account.' }; a.theme = THEMES.has(t) ? t : null; this.save(); return { ok: true, account: pub(a) }; }, async setChatAvailable(e, v) { const a = this.db.byEmail[e]; if (!a) return { error: 'No such account.' }; a.chatAvailable = !!v; this.save(); return { ok: true, available: !!v }; }, async getMutes(e) { const a = this.db.byEmail[e]; return (a && Array.isArray(a.chatMutes)) ? a.chatMutes : []; }, async setMute(owner, target, muted) { @@ -232,7 +235,7 @@ const rowPub = r => r ? pub({ email: r.email, sponsorRef: r.sponsor_ref, code: r username: r.username, memberId: r.member_id || 0, joinedVia: r.joined_via || null, joinedRef: r.joined_ref || null, lineBannerUrl: r.line_banner_url, lineTargetUrl: r.line_target_url, wallOffers: r.wall_offers || null, avatarUrl: r.avatar_url, bio: r.bio, socials: r.socials, profileQuarantined: !!r.profile_quarantined, - chatAvailable: r.chat_available === 0 ? false : true, lastSeen: Number(r.last_seen || 0), + chatAvailable: r.chat_available === 0 ? false : true, lastSeen: Number(r.last_seen || 0), theme: r.theme || null, address: r.address, created: Number(r.created) }) : null; const D = { async signup(e, password, ref) { @@ -294,6 +297,7 @@ const D = { return { ok: true, account: await this.byEmail(e) }; }, async touchSeen(e) { await db.q('UPDATE accounts SET last_seen=? WHERE email=?', [Date.now(), e]); }, + async setTheme(e, t) { await db.q('UPDATE accounts SET theme=? WHERE email=?', [THEMES.has(t) ? t : null, e]); return { ok: true, account: await this.byEmail(e) }; }, async setChatAvailable(e, v) { await db.q('UPDATE accounts SET chat_available=? WHERE email=?', [v ? 1 : 0, e]); return { ok: true, available: !!v }; }, async getMutes(e) { const r = await db.q('SELECT chat_mutes FROM accounts WHERE email=?', [e]); @@ -493,6 +497,7 @@ module.exports = { init, signup, login, ensure, onChange, byEmail, byAddress, by setWallOffers: (e, j) => impl().setWallOffers(String(e || '').toLowerCase(), j), setProfile: (e, a, bio, socials, quarantined) => impl().setProfile(String(e || '').toLowerCase(), a, bio, socials, quarantined).then(tap(String(e || '').toLowerCase())), touchSeen: e => impl().touchSeen(String(e || '').toLowerCase()), + setTheme: (e, t) => impl().setTheme(String(e || '').toLowerCase(), t), // appearance only: no onChange tap, InstantAdPay does not mirror it adminSetAddress: (e, a) => impl().adminSetAddress(String(e || '').toLowerCase(), a ? normAddr(a) : null).then(tap(String(e || '').toLowerCase())), positionByAddress: a => impl().positionByAddress(normAddr(a)), removeAccount: e => impl().removeAccount(String(e || '').toLowerCase()), diff --git a/blog.js b/blog.js index c48e0be..87e84b7 100644 --- a/blog.js +++ b/blog.js @@ -4,6 +4,7 @@ // /sitemap.xml, /robots.txt. SEO per post: title, description, canonical, Open Graph, Twitter // card, article dates, BlogPosting JSON-LD, breadcrumb JSON-LD, internal links, related posts. const { SITE_URL } = require('./host'); +const themehead = require('./themehead'); // light/dark theme head script (2026-11-01) const fs = require('fs'); const path = require('path'); const db = require('./db'); @@ -97,19 +98,19 @@ async function bumpViews(slug) { try { await impl().bumpViews(slug); } catch (e) function head(o) { const url = SITE + o.path; const img = o.image ? (o.image.startsWith('http') ? o.image : SITE + o.image) : SITE + '/banners/iap-hero-1200x630.png'; - return '' + return '' + '' + esc(o.title) + '' + '' + '' + (o.article ? '' + (o.article.tags || []).map(t => '').join('') : '') + '' + '' - + '' + + '' + themehead.tag() + '' + '' + '
'; } function tail() { - return '
'; + return ''; } const authorBox = () => '
LinkSpin
' + AUTHOR + 'Founder of LinkSpin and the Crypto Team Build Network. Twenty-plus years of internet marketing, and a habit of writing down what actually worked.
'; const cardHtml = p => '' + (p.cover ? '' : '') + '

' + esc(p.title) + '

' + esc(p.excerpt) + '

' + fmtDate(p.publishedAt || p.created) + ' · ' + readMinutes(p.body) + ' min read' + (p.tags.length ? ' · ' + p.tags.map(esc).join(', ') : '') + '

'; diff --git a/db.js b/db.js index eef7355..7bd37e2 100644 --- a/db.js +++ b/db.js @@ -90,7 +90,8 @@ async function bootstrap() { await alterSafe('ALTER TABLE accounts ADD COLUMN socials VARCHAR(1200) NULL'); // JSON {platform:url} await alterSafe('ALTER TABLE accounts ADD COLUMN line_banner_url VARCHAR(500) NULL'); await alterSafe('ALTER TABLE accounts ADD COLUMN line_target_url VARCHAR(500) NULL'); - await alterSafe('ALTER TABLE accounts ADD COLUMN profile_quarantined TINYINT NOT NULL DEFAULT 0'); // 2026-10-30 link-farm rule: first profile save of a new free account carried a link (spamscan.js) + await alterSafe('ALTER TABLE accounts ADD COLUMN profile_quarantined TINYINT NOT NULL DEFAULT 0'); + await alterSafe('ALTER TABLE accounts ADD COLUMN theme VARCHAR(8) NULL'); // 2026-11-01 appearance: auto | light | dark // 2026-10-30 link-farm rule: first profile save of a new free account carried a link (spamscan.js) await q(`CREATE TABLE IF NOT EXISTS daily_views ( email VARCHAR(190) NOT NULL, day CHAR(10) NOT NULL, diff --git a/leaderboard.js b/leaderboard.js index 734a12a..ecc3378 100644 --- a/leaderboard.js +++ b/leaderboard.js @@ -4,6 +4,7 @@ // on Central time: week = Monday 00:00 to Sunday 23:59, month = calendar month. Winners are recorded at // rollover (checked hourly), announced to Telegram, and credit prizes are granted automatically. const { SITE_HOST, SITE_URL } = require('./host'); +const themehead = require('./themehead'); // light/dark theme head script (2026-11-01) const fs = require('fs'); const path = require('path'); let R = null; // { chain, accounts, ads, dataDir, siteConfig, notify(text), pushFeed(ev) } @@ -131,8 +132,8 @@ async function renderPage() { + (v.top.length ? v.top.map(r => '' + r.rank + '' + esc(r.name) + '' + r.sales + '$' + r.usd.toLocaleString() + '' + r.buyers + '' + r.joins + '').join('') : 'No sales yet in this period.') + ''; const fmtD = ts => new Date(ts).toLocaleDateString('en-US', { timeZone: TZ, month: 'short', day: 'numeric' }); const desc = 'Who is selling the most ad packages on LinkSpin this week and this month. Weekly and monthly referral contest standings, read from the chain.'; - let h = 'Leaderboard | LinkSpin' - + '' + let h = 'Leaderboard | LinkSpin' + + '' + themehead.tag() + '' + '
' + '

Referral contest

Leaderboard: who is selling.

Ranked by ad packages sold to other people (your own positions never count, and the company account is not a contestant). Read from the chain, updated live. Weeks run Monday to Sunday, Central time.

'; h += '

' + week.label + ' ' + fmtD(week.start) + ' to Sunday

' + (week.prize ? '
Weekly prizes: ' + esc(week.prize) + '
' : '') + table(week); @@ -141,7 +142,7 @@ async function renderPage() { const w = winners(); if (w.length) h += '

Past winners

' + w.slice(0, 12).map(x => '
' + (x.kind === 'week' ? 'Week of ' : 'Month of ') + fmtD(x.start) + ': ' + (x.top[0] ? esc(x.top[0].name) + ' (' + x.top[0].sales + ' sold, $' + x.top[0].usd + ')' : 'no sales') + (x.granted && x.granted.length ? ' · awarded: ' + x.granted.map(g => esc(g.name) + ' +' + g.credits.toLocaleString()).join(', ') : (x.prize ? ' · prize ' + esc(x.prize) : '')) + '
').join(''); h += '

Sales are $ of packages bought by members you directly sponsor. Prizes are advertising credits or packages, never cash. No income is guaranteed.

'; - h += '
'; + h += ''; return h; } module.exports = { init, view, compute, renderPage, rolloverTick, winners, periodBounds }; diff --git a/public/admin.html b/public/admin.html index 00aeedc..165ee7a 100644 --- a/public/admin.html +++ b/public/admin.html @@ -1,15 +1,16 @@ - + Admin | LinkSpin + - - - - + + + +
@@ -539,8 +540,8 @@
- + - + diff --git a/public/ads.html b/public/ads.html index 286c5c8..7c3d569 100644 --- a/public/ads.html +++ b/public/ads.html @@ -1,12 +1,13 @@ - + Ads · LinkSpin + - + @@ -68,6 +69,6 @@
Advertising services with a performance referral program. Not an investment product; no income guarantees.
- + diff --git a/public/help.html b/public/help.html index 15d07c2..25a5230 100644 --- a/public/help.html +++ b/public/help.html @@ -1,12 +1,13 @@ - + Help · LinkSpin + - + - + + + @@ -590,7 +591,7 @@ campaigns just like purchased ones.

… …

-
+
Press the button to open the first ad in a new tab.

@@ -609,7 +610,7 @@ can't be skipped — the timer runs on our server. You never see your own videos. Prefer a feed? Open Shorts for a full-screen, swipe-to-next experience.

…

-
+
Press the button to load the first video.
- - + + - + diff --git a/public/pages.html b/public/pages.html index bedad75..18c2e4a 100644 --- a/public/pages.html +++ b/public/pages.html @@ -1,15 +1,16 @@ - + Pages · LinkSpin + - + @@ -130,7 +131,7 @@
Advertising services with a performance referral program. Not an investment product; no income guarantees. Crypto transactions are irreversible. Never spend what you cannot afford to lose.
- + diff --git a/public/plays.html b/public/plays.html index 90217ef..ba8fe49 100644 --- a/public/plays.html +++ b/public/plays.html @@ -1,16 +1,17 @@ - + Team-building plays | LinkSpin + - + @@ -89,7 +90,7 @@
- + diff --git a/public/shorts.html b/public/shorts.html index 4a015f4..04f53c7 100644 --- a/public/shorts.html +++ b/public/shorts.html @@ -1,11 +1,12 @@ - + Shorts | LinkSpin + - + @@ -41,7 +42,7 @@ - + diff --git a/releases.js b/releases.js index 9cff447..80598d1 100644 --- a/releases.js +++ b/releases.js @@ -2,6 +2,7 @@ // shown on the public /whats-new page and in a "What's new" card on every member's Overview. // Storage: DATA_DIR/releases.json { notes: [{id, date, title, body, tags[]}], roadmap: [{id, title, note, status, eta}] } const { SITE_URL } = require('./host'); +const themehead = require('./themehead'); // light/dark theme head script (2026-11-01) const fs = require('fs'); const path = require('path'); let FILE = null; @@ -55,9 +56,9 @@ const tagChip = t => '' + t + ''; function renderPage() { const v = publicView(); const desc = 'What changed on LinkSpin and what is coming next: release notes and the roadmap, updated as things ship.'; - let h = 'What\'s new | LinkSpin' + let h = 'What\'s new | LinkSpin' + '' - + '' + + '' + themehead.tag() + '' + '
' + '

Release notes and roadmap

What\'s new, and what\'s next.

' + esc(desc) + '

'; h += '

On the roadmap

'; @@ -65,7 +66,7 @@ function renderPage() { h += '

Release notes

'; h += v.notes.length ? v.notes.map(n => '

' + esc(n.title) + n.tags.map(tagChip).join('') + '

' + fmt(n.date) + '

' + bodyHtml(n.body) + '
').join('') : '

No notes yet.

'; h += '

Suggestions and bug reports: the chat bubble on any page, or the LinkSpin Telegram group.

'; - h += '
'; + h += ''; return h; } module.exports = { init, notes, roadmap, saveNote, saveRoadmap, remove, publicView, renderPage, bodyHtml, TAGS, STATUSES }; diff --git a/server.js b/server.js index 81b4b9d..05f22a6 100644 --- a/server.js +++ b/server.js @@ -15,6 +15,7 @@ const { URL } = require('url'); const chain = require('./chain'); const auth = require('./auth'); const accounts = require('./accounts'); +const themehead = require('./themehead'); // 2026-11-01 light/dark theme head script for server-rendered pages const ads = require('./ads'); const mailer = require('./mailer'); const { emailIssue } = require('./emailcheck'); // typo / no-mail-domain check for NEW addresses (2026-10-22) @@ -829,7 +830,7 @@ const MIME = { '.html': 'text/html; charset=utf-8', '.css': 'text/css', '.js': ' '.png': 'image/png', '.jpg': 'image/jpeg', '.svg': 'image/svg+xml', '.webp': 'image/webp', '.ico': 'image/x-icon', '.json': 'application/json', '.mp4': 'video/mp4', '.woff2': 'font/woff2', '.gif': 'image/gif', '.webm': 'video/webm', '.txt': 'text/plain; charset=utf-8', '.xml': 'application/xml; charset=utf-8' }; -const CSP = "default-src 'self'; script-src 'self' https://cdn.jsdelivr.net 'sha256-NzvNrqk5jB9YZATwo5BF4JoRlJ02HsnFikbKXgEPdaQ='; worker-src 'self' blob:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; img-src 'self' data: blob: https:; media-src 'self' https: blob:; connect-src 'self' https://*.walletconnect.com wss://*.walletconnect.com https://*.walletconnect.org wss://*.walletconnect.org https://*.reown.com wss://*.reown.com https://*.reown.org wss://*.reown.org https://*.web3modal.org https://*.drpc.org https://*.publicnode.com https://*.coinbase.com; font-src 'self' data: https://fonts.gstatic.com https://fonts.reown.com; form-action 'self'; frame-src https: http:"; +const CSP = "default-src 'self'; script-src 'self' https://cdn.jsdelivr.net 'sha256-NzvNrqk5jB9YZATwo5BF4JoRlJ02HsnFikbKXgEPdaQ=' " + themehead.CSP_HASH + "; worker-src 'self' blob:; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; img-src 'self' data: blob: https:; media-src 'self' https: blob:; connect-src 'self' https://*.walletconnect.com wss://*.walletconnect.com https://*.walletconnect.org wss://*.walletconnect.org https://*.reown.com wss://*.reown.com https://*.reown.org wss://*.reown.org https://*.web3modal.org https://*.drpc.org https://*.publicnode.com https://*.coinbase.com; font-src 'self' data: https://fonts.gstatic.com https://fonts.reown.com; form-action 'self'; frame-src https: http:"; function baseHeaders(extra) { return Object.assign({ 'Content-Security-Policy': CSP, 'X-Content-Type-Options': 'nosniff', 'Referrer-Policy': 'strict-origin-when-cross-origin' }, extra || {}); @@ -1564,7 +1565,7 @@ const server = http.createServer(async (req, res) => { const r = await drip.unsubscribe(u.searchParams.get('e'), u.searchParams.get('t')); const msg = r.error ? r.error : 'Done. You will not get any more follow-up emails from LinkSpin. Your account is unchanged.'; res.writeHead(r.error ? 400 : 200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' })); - return res.end('LinkSpin
LinkSpin

' + (r.error ? 'Hmm.' : 'Unsubscribed.') + '

' + msg + '

Member area

'); + return res.end('LinkSpin' + themehead.tag() + '
LinkSpin

' + (r.error ? 'Hmm.' : 'Unsubscribed.') + '

' + msg + '

Member area

'); } // -- public API @@ -2015,7 +2016,7 @@ const server = http.createServer(async (req, res) => { if (memberId && acct && acct.memberId !== memberId) accounts.setMemberId(acct.email, memberId).catch(() => {}); const out = { signedIn: true, sponsorBlocked, sponsorName: spdMe.name || null, email: s.email || (acct && acct.email) || null, address: s.address || (acct && acct.address) || null, memberId, - username: (acct && acct.username) || null, + username: (acct && acct.username) || null, theme: (acct && acct.theme) || null, refCode: (acct && acct.code) || null, sponsorId, tankHold, // profile + line-banner fields so the Profile pane repopulates on reload (were being saved but not returned) avatarUrl: (acct && acct.avatarUrl) || null, bio: (acct && acct.bio) || null, @@ -3003,6 +3004,12 @@ const server = http.createServer(async (req, res) => { if (!s || !s.email) return json(res, 401, { error: 'Sign in first.' }); const b = await readBody(req); const before = await accounts.byEmail(s.email); + // appearance (2026-11-01): theme auto | light | dark rides the same save path; a theme-only save never touches the username + if (b.theme !== undefined) { + const t = ['auto', 'light', 'dark'].includes(String(b.theme)) ? String(b.theme) : null; + const rt = await accounts.setTheme(s.email, t); + if (b.username === undefined) return json(res, rt.error ? 400 : 200, rt); + } // a username is permanent once set: the invite link, the public wall and every // banner already printed carry it (Marty, 2026-09-10) if (before && before.username && String(b.username || '').trim().toLowerCase() !== String(before.username).toLowerCase()) @@ -4185,15 +4192,15 @@ const server = http.createServer(async (req, res) => { const url = SITE_URL + '/b/' + un + '/' + key, img = SITE_URL + '/badge-img/' + un + '/' + key + '.jpg'; const title = '@' + un + ' unlocked ' + label + ' on LinkSpin'; const desc = label + ': ' + sub + '. LinkSpin pays sponsors in the same transaction, on-chain. Join @' + un + '\u2019s line free.'; - const html = '' + esc(title) + '' + const html = '' + esc(title) + '' + '' + '' + '' - + '' + + '' + themehead.tag() + '' + '' + '
' + esc(label) + ' badge for @' + esc(un) + '

@' + esc(un) + ' unlocked ' + label + '

' + esc(sub.charAt(0).toUpperCase() + sub.slice(1)) + '. On LinkSpin every ad package that sells pays the sponsor in the same transaction, straight to their wallet, on-chain.

' + 'Join @' + esc(un) + '\u2019s line free

Advertising with a performance referral program. Not an investment; no income is guaranteed.

' - + ''; + + ''; res.writeHead(200, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'public, max-age=300' })); return res.end(html); } @@ -4235,7 +4242,7 @@ const server = http.createServer(async (req, res) => { let a = await accounts.byUsername(tok); if (!a) a = await accounts.byCode(tok); // a deleted or never-seen name is a real 404, never a bare "Banner wall" page at 200 (a soft 404 Google kept indexed, 2026-10-30) if (!a) { - const nf = 'No wall under that name | LinkSpin

No wall under that name

This member page does not exist or was removed.

Go to LinkSpin

'; + const nf = 'No wall under that name | LinkSpin' + themehead.tag() + '

No wall under that name

This member page does not exist or was removed.

Go to LinkSpin

'; res.writeHead(404, baseHeaders({ 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-cache', 'X-Robots-Tag': 'noindex' })); return res.end(nf); } diff --git a/themehead.js b/themehead.js new file mode 100644 index 0000000..0fc1046 --- /dev/null +++ b/themehead.js @@ -0,0 +1,33 @@ +// Theme head script (2026-11-01). A member asked for light and dark themes: some readers are vision impaired, some +// struggle with bright screens, some with dark ones. This is the ONE source of the tiny inline script every page +// carries in its , before any stylesheet, so the first paint is already the chosen theme (no flash). +// +// theme value: auto | light | dark, stored in localStorage "ls.theme"; signed-in members also keep it on the +// account (accounts.theme) and the account value wins at sign-in (cr-shell.js). +// data-theme on is always resolved to light or dark (auto follows prefers-color-scheme and tracks changes). +// data-theme-choice carries the raw choice for the switch UI. window.LSTheme = { get, set, apply, base }. +// +// Nothing stored => the page keeps its current look: data-theme-base on says what that is (light for the +// Control Room and public pages, dark for the sapphire site.css pages). AUTO_DEFAULT below is the one constant +// Marty decides later: set it to 1 and pages with nothing stored follow the device instead. After changing it, +// run `node tools/stamp-theme-head.cjs` so every static page carries the new copy (server-rendered pages read +// this module directly). +const AUTO_DEFAULT = 0; + +const BODY = '(function(){var A=' + AUTO_DEFAULT + ',h=document.documentElement,b=h.getAttribute("data-theme-base")||"light",' + + 'm=window.matchMedia?matchMedia("(prefers-color-scheme: dark)"):{matches:false},v;' + + 'function g(){try{v=localStorage.getItem("ls.theme")}catch(e){v=null}return v==="light"||v==="dark"||v==="auto"?v:(A?"auto":b)}' + + 'function ap(){var c=g();h.setAttribute("data-theme",c==="auto"?(m.matches?"dark":"light"):c);h.setAttribute("data-theme-choice",c)}' + + 'ap();if(m.addEventListener)m.addEventListener("change",ap);else if(m.addListener)m.addListener(ap);' + + 'window.LSTheme={base:b,get:g,apply:ap,set:function(c,quiet){try{if(c==="light"||c==="dark"||c==="auto")localStorage.setItem("ls.theme",c);else localStorage.removeItem("ls.theme")}catch(e){}' + + 'ap();if(!quiet)try{dispatchEvent(new CustomEvent("ls-theme",{detail:g()}))}catch(e){}}}})()'; +const SCRIPT = ''; +// The site CSP allows inline scripts by hash only (server.js CSP): one source, one hash. Changing BODY changes the hash, +// and the static pages must be re-stamped so they carry the same bytes. +const CSP_HASH = "'sha256-" + require('crypto').createHash('sha256').update(BODY).digest('base64') + "'"; + +// base: 'light' | 'dark' (the page's look when nothing is stored). Returns the attribute for the tag and the script. +function htmlAttr(base) { return ' data-theme-base="' + (base === 'dark' ? 'dark' : 'light') + '"'; } +function tag() { return SCRIPT; } +// whole-head helper for server-rendered pages: '' + themehead.tag() + ... +module.exports = { AUTO_DEFAULT, SCRIPT, CSP_HASH, htmlAttr, tag }; diff --git a/tools/stamp-theme-head.cjs b/tools/stamp-theme-head.cjs new file mode 100644 index 0000000..0b5c6b7 --- /dev/null +++ b/tools/stamp-theme-head.cjs @@ -0,0 +1,23 @@ +// Stamp the theme head script (themehead.js) into every static page under public/, before the first stylesheet, and +// put data-theme-base on the tag (dark for site.css pages, light for cr.css / pub.css pages). Re-runnable: an +// existing copy between the markers is replaced. Run after changing AUTO_DEFAULT in themehead.js: +// node tools/stamp-theme-head.cjs +const fs = require('fs'), path = require('path'); +const themehead = require(path.join(__dirname, '..', 'themehead.js')); +const dir = path.join(__dirname, '..', 'public'); +const OPEN = '', CLOSE = ''; +let n = 0; +for (const f of fs.readdirSync(dir).filter(f => f.endsWith('.html'))) { + const p = path.join(dir, f); + let html = fs.readFileSync(p, 'utf8'); + if (!//, (m, a) => ''); + const block = OPEN + themehead.tag() + CLOSE; + if (html.includes(OPEN)) html = html.replace(new RegExp(OPEN + '[\\s\\S]*?' + CLOSE), block); + else html = html.replace(/