From 144403a207ec78662835dcec8480077d8cec5fb7 Mon Sep 17 00:00:00 2001 From: july Date: Sun, 1 Mar 2026 15:02:52 -0300 Subject: [PATCH] refactor(layout): recursive head collection and contextual CSS injection --- src/global.ts | 25 +++++++ src/layout.tsx | 171 +++++++++++++++++++++++++++++++++++++++++++----- src/mech/css.ts | 37 ++++------- src/mod.ts | 3 +- 4 files changed, 195 insertions(+), 41 deletions(-) create mode 100644 src/global.ts diff --git a/src/global.ts b/src/global.ts new file mode 100644 index 0000000..818dd4d --- /dev/null +++ b/src/global.ts @@ -0,0 +1,25 @@ +/** + * Copyright (c) 2025 adoravel + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + +import { Middleware } from "@july/snarl"; +import { Context } from "@july/snarl"; +import { AsyncLocalStorage } from "node:async_hooks"; +import { ScopedStyles } from "./mech/css.ts"; + +const contextStorage = new AsyncLocalStorage(); + +export function runWithContext(ctx: Context, fn: () => T): T { + return contextStorage.run(ctx, fn); +} + +export function retrieveContext(): Context | undefined { + return contextStorage.getStore(); +} + +export function contextMiddleware(): Middleware { + return async (ctx, next) => { + return await runWithContext(ctx, () => next()); + }; +} diff --git a/src/layout.tsx b/src/layout.tsx index dac9297..be5a14b 100644 --- a/src/layout.tsx +++ b/src/layout.tsx @@ -1,38 +1,175 @@ +/** + * Copyright (c) 2025 adoravel + * SPDX-License-Identifier: AGPL-3.0-or-later + */ + import { Context } from "@july/snarl"; -import { JsxElement } from "@july/snarl/jsx-runtime"; +import { jsx, JsxElement, JsxNode } from "@july/snarl/jsx-runtime"; +import { css } from "./mech/css.ts"; +import meowmix1 from "./hash/meowmix1.ts"; + +const styles = css(` + :root { + --theme-background: #181825; + --theme-background-alt: #11111b; + --theme-surface: #1e1e2e; + --theme-surface-border: #313244; + --theme-foreground: #cdd6f4; + --theme-primary: #f5e0dc; + --theme-foreground-alt: #a6adc8; + --theme-foreground-bruh: #7f849c; + --theme-separator: #313244; + + --space-0: 0.16rem; + --space-1: 0.25rem; + --space-2: 0.5rem; + --space-pad-surface: 0.625rem; + --space-3: 0.75rem; + --space-4: 1rem; + --space-5: 1.25rem; + --space-6: 1.5rem; + --space-7: 2rem; + --space-8: 2.5rem; + --space-9: 3rem; + --space-10: 4rem; + + --spacing-xs: var(--space-1); + --spacing-sm: var(--space-2); + --spacing-md: var(--space-4); + --spacing-lg: var(--space-6); + --spacing-xl: var(--space-7); + --spacing-2xl: var(--space-9); + --spacing-3xl: var(--space-10); + + --section-margin: var(--space-7); + --card-padding: var(--space-4); + --button-padding-x: var(--space-2); + --button-padding-y: var(--space-1); + --input-padding: var(--space-3); + + --radius-sm: 2px; + --radius-md: 3px; + --radius-lg: 10px; + --radius-circle: 1000px; + --radius-music: 15%; + + --transition-fast: 0.2s ease-in-out; + --transition-smooth: 0.3s cubic-bezier(0.34, 1.56, 0.64, 1); + + --font-size-xs: 11px; + --font-size-sm: 12px; + --font-size-md: 0.875rem; + --font-size-base: 17px; + --font-size-lg: 1.1rem; + --font-size-xl: 1.5rem; + --font-size-2xl: 2.4rem; + + --avatar-size: 160px; + + --max-width: 55em; + --section-spacing: 2em; + + --z-background: -1; + --z-base: 0; + --z-elevated: 10; + } + + *, *::before, *::after { + box-sizing: border-box; + margin: 0; + } + + body { + background-color: var(--theme-background); + color: var(--theme-foreground); + max-width: var(--max-width); + margin: 0 auto; + padding: var(--spacing-xl) 16px; + } + + html, + body, + pre, + code, + button { + font-family: + "Iosevka Custom Web", "Iosevka Custom", Iosevka, monospace, sans-serif; + text-rendering: optimizeLegibility; + line-height: 1.75rem; + } + + a { + color: var(--theme-primary); + text-decoration: none; + } + + @view-transition { + navigation: auto; + } + + #content { + view-transition-name: content; + } +`); export interface LayoutProps { children?: JsxElement | JsxElement[]; } -function flatten(arr: any[]): any[] { - return arr.flatMap((x) => Array.isArray(x) ? flatten(x) : x); +interface CollectResult { + head: JsxNode[]; + body: JsxNode[]; } -export function Layout(props: LayoutProps = {}) { - const children = flatten(props.children ? (Array.isArray(props.children) ? props.children : [props.children]) : []); - const head: JsxElement[] = [], body: JsxElement[] = [], main: JsxElement[] = []; +function collect(node: JsxNode, result: CollectResult): void { + if (node == null || node === false || node === true) return; + + if (Array.isArray(node)) { + return node.forEach((child) => collect(child, result)); + } + + if (typeof node !== "object") { + return void result.body.push(node); + } + + const { tag, props } = node as JsxElement; - for (const child of children) { - if (child?.tag === "head") { - head.push(...child.props?.children ?? []); - } else if (child?.tag === "body") { - body.push(...child.props?.children ?? []); - } else { - main.push(child); - } + if (tag === "head") { + return void result.head.push(props.children); } + if (typeof tag === "function") { + const evaluated = tag(props); + return collect(evaluated, result); + } + + if (props.children == null) { + return void result.body.push(node); + } + + const child: CollectResult = { head: [], body: [] }; + collect(props.children, child); + + if (child.head.length) { + result.head.push(...child.head); + } + result.body.push(jsx(tag, { ...props, children: child.body as any })); +} + +export function Layout({ children }: LayoutProps = {}) { + const result: CollectResult = { head: [], body: [] }; + collect(children, result); + return ( - {head.map((node) => <>{node})} + + {result.head} - {main.map((node, i) => <>{node})} - {body.map((node, i) => <>{node})} + {result.body} ); diff --git a/src/mech/css.ts b/src/mech/css.ts index 9bd5a9f..45ff337 100644 --- a/src/mech/css.ts +++ b/src/mech/css.ts @@ -5,7 +5,8 @@ import meowmix1 from "~/hash/meowmix1.ts"; import { Context, Middleware } from "@july/snarl"; -import { Component, jsx, JsxElement, JsxNode } from "@july/snarl/jsx-runtime"; +import { Component, Fragment, jsx, JsxElement, JsxNode } from "@july/snarl/jsx-runtime"; +import { retrieveContext } from "../global.ts"; const CLASS_RE = /\.([a-zA-Z_][\w-]*)/g; @@ -44,7 +45,7 @@ type ExtractFlatClassKeys = ExtractFromSelectors< Until >; -type ScopedStyles = +export type ScopedStyles = & { [K in ExtractFlatClassKeys]: string; } @@ -77,11 +78,6 @@ export function css(src: S): ScopedStyles { src = src.trim() as S; if (!src) throw new Error("css: empty stylesheet"); - const keys = extractClassKeys(src); - if (!keys.size) { - throw new Error("css: no class selectors found"); - } - const hash = meowmix1(src); if (styleRegistry.has(hash)) { throw new Error(`css: hash collision ${hash}`); @@ -103,6 +99,7 @@ export function css(src: S): ScopedStyles { }, }; + const keys = extractClassKeys(src); for (const key of keys) { result[key] = `${hash}_${key}`; } @@ -138,8 +135,6 @@ declare module "@july/snarl" { interface Context { useStyles(...styles: ScopedStyles[]): void; - get import(): Component<{ styles: ScopedStyles[] }>; - get styles(): Component; } } @@ -159,11 +154,11 @@ Object.defineProperty(Context.prototype, "styles", { // deno-lint-ignore no-this-alias const ctx = this; - return (_props?: JsxElement["props"]) => { + return (_props: any = {}) => { const mem = contextualisedStyles.get(ctx); if (!mem || mem.size === 0) return null; - const nodes: JsxNode[] = []; + const nodes: JsxElement[] = []; for (const hash of mem) { nodes.push( @@ -174,19 +169,15 @@ Object.defineProperty(Context.prototype, "styles", { ); } - return nodes.length === 1 ? nodes[0] : nodes; + return jsx(Fragment, { children: nodes }); }; }, }); -Object.defineProperty(Context.prototype, "import", { - get(this: Context): Component { - // deno-lint-ignore no-this-alias - const ctx = this; - - return function ({ styles }: Parameters[0]) { - ctx.useStyles(...styles); - return ctx.styles({}); - } as any; - }, -}); +export function Import({ styles = [] }: { styles: ScopedStyles[] }) { + const ctx = retrieveContext()!; + if (styles.length) { + ctx.useStyles(...styles); + } + return jsx("head", { children: ctx.styles({}) as JsxElement[] }); +} diff --git a/src/mod.ts b/src/mod.ts index 2ed7154..b8c25fc 100644 --- a/src/mod.ts +++ b/src/mod.ts @@ -7,9 +7,10 @@ import { createRouter } from "@july/snarl"; import { cssMiddleware as scopedStyles } from "~/mech/css.ts"; import { scanRoutes as scan } from "./mech/routing.ts"; import minify from "./mech/mini.ts"; +import { contextMiddleware } from "./global.ts"; const router = createRouter(); -router.use(minify(), scopedStyles()); +router.use(minify(), contextMiddleware(), scopedStyles()); scan(router); -- knotmirror 0.0.1