-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: cookie color schemes for rewriting html
Now a middleware rewrites the HTML to apply the user preferred color scheme before the page loads, preventing a flash of the wrong color scheme. The _routes.json file tells Cloudflare Functions which routes to work on, preventing the middleware from running on non-html routes and wasting function invocations.
- Loading branch information
Showing
4 changed files
with
67 additions
and
22 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
import { parse } from 'cookie'; | ||
|
||
export const COLOR_SCHEME_COOKIE = 'colorScheme'; | ||
export const COLOR_SCHEME_BODY_ATTRIBUTE = 'data-color-scheme'; | ||
export type ColorSchemeValue = 'light' | 'dark'; | ||
|
||
export const onRequest: PagesFunction = async (context) => { | ||
const cookie = parse(context.request.headers.get('Cookie') ?? ''); | ||
const colorScheme = cookie[COLOR_SCHEME_COOKIE]; | ||
|
||
class ElementHandler { | ||
element(element: Element) { | ||
if(element.tagName === 'body') { | ||
element.setAttribute(COLOR_SCHEME_BODY_ATTRIBUTE, colorScheme); | ||
} | ||
} | ||
} | ||
|
||
if(colorScheme === 'light' || colorScheme === 'dark') { | ||
return new HTMLRewriter().on('body', new ElementHandler()).transform(await context.next()); | ||
} | ||
|
||
return context.next(); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
{ | ||
"version": 1, | ||
"include": ["/api/*", "/", "/article/*"], | ||
"exclude": [] | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters