feat(cam): sıvı cam motoru Liquid Glass UI 2.0.4'e geçti (→ 2.12.14)

12 Kasım'daki elle çeviri kaldırıldı; motor artık kitin kendi dosyalarının
birebir kopyası (src/components/liquid-glass: engine, dom-snapshot,
glass-layer, glass-lens, glass-badge; bağımlılıksız WebGL2, MIT).
sivi-cam.tsx ürüne özgü ince bağdaştırıcı oldu: sıvı cam tercihi, ikon
damlası, CTA yüzeyi. İşaret adları kitinkilere çevrildi (data-glass-ready,
data-glass-highlight, data-glass-moving, data-glass-traveling).

- CTA yüzeyindeki mavi boya CSS'e taşındı (--glass-tint)
- Baştaki ikon damlası için tuval yatay çevriliyor
- CAM_YAYI silindi (yaylar kitin SPRINGS'i)
- Kit klasörü eslint ve tasarım denetimi dışında; tsconfig hedefi ES2018
- DESIGN.md §4.50 güncellendi

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
bilalgursen
2026-11-26 00:59:00 +03:00
parent 4ef3a883b3
commit 85d6790b8e
33 changed files with 5419 additions and 1715 deletions

View File

@@ -250,7 +250,7 @@ bir dosyaya (`src/components/…`) çıkarılıp iki yer de oradan kullanır.
```
Varyantın ürettiği: `relative isolate cursor-pointer bg-orange-500 text-white hover:bg-orange-600
transition-[background-color,transform] duration-200 active:scale-[0.97]
data-cam:bg-transparent data-cam:hover:bg-transparent`. CTA düz turuncudur; yalnız **CTA yüzeylerinin içinde** `cam="seffaf"` ile mavi boyalı liquid
data-glass-ready:bg-transparent data-glass-ready:hover:bg-transparent`. CTA düz turuncudur; yalnız **CTA yüzeylerinin içinde** `cam="seffaf"` ile mavi boyalı liquid
glass olur (12 Kas 2026, §4.50). `cam="cam"` turuncu boyalı varyasyondur, kullanılmıyor. Metin
önce, ok sonda. Başta ikon yok. `Sparkles` yok. Kullanım yerinde yalnız yerleşim sınıfı eklenir
(`w-full sm:w-auto`, `mt-6`); yükseklik, renk, geçiş yazılmaz.
@@ -2076,7 +2076,7 @@ yok" kuralının üçüncü istisnası (başlık üstü eyebrow değil, kart kö
"progressive blur" iki kez denendi (güçlü ve hafif), Bilal 12 Kas 2026'da ikisini de
kaldırttı — geri önerilmez.
- Cam ilk karesini çizene dek ve WebGL2 yoksa rozet düz hâlindedir: `bg-primary` dolu hap, beyaz
CSS şeridi (`kt-yeni-serit`, 5 sn, kenarlar maskeyle erir). `data-cam` gelince zemin ve DOM
CSS şeridi (`kt-yeni-serit`, 5 sn, kenarlar maskeyle erir). `data-glass-ready` gelince zemin ve DOM
şeridi bırakılır.
- Hareketi azalt: şerit durur, tek ortalı "Yeni" (camda da, düz hâlde de). Ekran okuyucuya
`sr-only` "Yeni yazı". Cam yalnız ekrandayken çizilir.
@@ -2102,6 +2102,45 @@ yok" kuralının üçüncü istisnası (başlık üstü eyebrow değil, kart kö
filtresi denendi, Bilal 12 Kas 2026'da "filtrede sadece artan azalan olacak" dedi — geri önerilmez).
### 4.50 Sıvı cam: CTA zemini ve kayan sekme camı — `SiviCam`, `KayanCam`, `src/components/sivi-cam.tsx`
**26 Kas 2026 — motor kitin son hâli (Bilal: "liquid glass'ın son hâline çevir").** 12 Kas'taki
elle çeviri (three.js'li ilk kitten GLSL'e) kaldırıldı. Motor artık kitin kendi dosyalarıdır:
`src/components/liquid-glass/` altında `engine.ts`, `dom-snapshot.ts`, `glass-layer.tsx`,
`glass-lens.tsx`, `glass-badge.tsx` — Liquid Glass UI **2.0.4**'ten (25 Kas 2026) **birebir kopya**,
bağımlılıksız düz WebGL2, MIT (`LICENSE` yanında). Kurallar:
- **O klasör elle düzenlenmez.** Kit güncellenince dosyalar üstüne kopyalanır; ürüne özgü her şey
`sivi-cam.tsx`'tedir. Klasör `eslint` ve `pnpm tasarim:denetim` dışındadır (kendi kurallarıyla
yazılmıştır). `@ui-sdk` isteyen kit bileşenleri (`GlassButton`, `GlassTabs`, menüler) alınmadı:
yeni bağımlılık yok (§11.3).
- **`sivi-cam.tsx` ince bağdaştırıcıdır:** `SiviCam` → `GlassLayer`, `KayanCam` → `GlassLens`,
`RozetCami` → `GlassBadge`. Taşıdıkları: sıvı cam tercihi (kapalıyken hiçbiri kurulmaz), ikon
damlası (ikon bulunup `data-glass-drop` ile işaretlenir; üstüne gelince `apart`, `otoDamla`'da
hep `apart`), CTA yüzeyi (`backdrop="[data-cta-yuzey]"`, `live`, boya %82).
- **İşaret adları kitinkilerdir:** cam kurulunca kaba `data-glass-ready` yazılır (eski `data-cam`;
`SIVI_KAP` ve `data-glass-ready:active:scale-100` bunu dinler), sekmede `data-glass-highlight`,
`data-glass-moving`, `data-glass-traveling`. Camın görmemesi gereken öğe `data-glass-skip` taşır
(üst ve alt sayfa bulanıklığı, `layout.tsx`). `/dev/sivi`'deki `CamYuzey` (§4.48) ayrı bir
denemedir ve `data-cam` adını korur.
- **CTA yüzeyindeki mavi boya CSS'tedir:** `[data-cta-yuzey] [data-seffaf] { --glass-tint: var(--primary) }`,
mavi bantta bir ton koyu (`globals.css`). Optik kitin varsayılanıdır (kırılma 44 → 37, büyütme
yok); aşağıdaki "kırılma 10 → 32, %8 büyütme" ayrıntısı geçersizdir.
- **Baştaki ikonun damlası** (`data-sivi="bas"`, "Listeme ekle"): kit damlayı yalnız sonda ayırır;
bu kapta cam tuvali yatay çevrilir (`transform: scaleX(-1)`, globals.css) ve imlece dönen kenar
ışığı kapatılır. Kaba ikonu bulmak için gizli bir iz öğesi (`data-cam-iz`) eklenir; baştaki ikon
seçicisi ona göredir.
- **Yaylar kitin `SPRINGS`'idir** (`engine.ts`); `hareket.ts`'teki `CAM_YAYI` silindi. Aşağıda
`CAM_YAYI.*` geçen yerler `SPRINGS`'in karşılığı olarak okunur.
- **Kitle gelen yeni davranışlar** (hepsi motorun içinde, ayar yok): basınca cam ışık alır; cam
buton tutulup çekilince jel gibi uzar, bırakınca geri salınır; birbirine yaklaşan cam butonlar
erir gibi birleşir; şeffaf camın kenarı çevresindeki rengi yansıtır; boşta kare çizilmez.
- **"Yeni" rozeti** tercih açıkken tümüyle `GlassBadge`'dir: arkasındaki kartı kendisi çizer
(`data-rozet-zemini` kalktı), cam gelince halkası (`ring-4`) kalkar. Tercih kapalıyken eski düz
rozet ve CSS şeridi durur.
- Bakıldı (26 Kas 2026, dev sunucusu): 1280 px açık ve koyu temada `/rehber` (rozet, "Yazıyı oku"
ve üstüne gelince damla, mavi bant CTA'sı, "Giriş yap"), ana sayfada puan türü merceği, program
sayfasında "Listeme ekle" damlası; 375 px'te `/rehber` (yatay taşma 0); tercih kapalıyken sade hâl.
Bakılmadı: Safari, gerçek telefon, çekmece ve sihirbaz çağrı kartındaki CTA'lar, tutup çekme.
Bilal (12 Kas 2026): "CTA butonlarını liquid-glass projesinde yaptığım buton yapısında yapalım,
liquid glass olsun". Kaynak Bilal'in açık kaynak kiti **Liquid Glass UI**
(github.com/bilalgursen/liquid-glass, MIT): `ui/Button.tsx`, `ui/LiquidGlass.tsx`,
@@ -2175,7 +2214,7 @@ liquid glass olsun". Kaynak Bilal'in açık kaynak kiti **Liquid Glass UI**
(Bilal, 12 Kas 2026: "ikonlar yuvarlakları tam ortalamıyor"). Ölçüldü: satır düğmesinde ve hap
damlasında ikon merkezi ile cam dairesinin merkezi arasındaki fark 0 px.
Cam kurulunca eski `active:scale` kapanır
(`data-cam:active:scale-100`; büyümeyi cam yapar). WebGL2 yoksa düğme eski düz hâlindedir.
(`data-glass-ready:active:scale-100`; büyümeyi cam yapar). WebGL2 yoksa düğme eski düz hâlindedir.
12 Kas 2026'da 1280 ve 375 px'te, açık ve koyu temada bakıldı; 375 px'te yatay taşma 0.
- **Sıvı cam kutusu — `CamSecici`, `src/components/cam-secici.tsx`, `src/lib/cam-tercihi.ts`**
(Bilal, 12 Kas 2026: "sitenin en altına camsılığı açıp kapama seçeneği koy, ilham kaynağı deyip
@@ -2197,7 +2236,7 @@ Cam kurulunca eski `active:scale` kapanır
ortalı durur: tema → resim + kaynak + kutu → iyzico bandı. 12 Kas 2026'da 1280 ve 375 px'te,
açık temada bakıldı; yatay taşma 0.
- **İçinde yalnız ikon olan her yuvarlak düğme camdır** (Bilal, 12 Kas 2026: "sadece içinde ikon olan
tüm yuvarlak butonlar sıvı cam olmalı"): `SIVI_KAP` + ilk çocuk `<SiviCam />`, `data-cam:active:scale-100`.
tüm yuvarlak butonlar sıvı cam olmalı"): `SIVI_KAP` + ilk çocuk `<SiviCam />`, `data-glass-ready:active:scale-100`.
Kapsam: `DialogContent` ve `AltSayfaKapat` çarpıları, arama kapatma, telefon menüsü açma/kapama,
üst çubuktaki "Yapay Zekâ Listem" bağlantısı (ikon yerine `PikselDugmeYuzu`, §4.43; `<SiviCam hep />` ile camsı görünüm kapalıyken de camdır: Bilal, 12 Kas 2026 "hep camsı gözükmeli"; telefon menüsündeki satırda `ListOrdered` ikonu), bildirim çarpısı, liste çekmecesi (temizle, çıkar), sayfalama okları, sihirbaz ve danışman
paneli ikon düğmeleri. Yazılı düğmeler ve avatar/rozet gibi düğme olmayan daireler kapsam dışı.
@@ -2256,13 +2295,13 @@ Cam kurulunca eski `active:scale` kapanır
cam açıldıkça söner. Kap dışındaki sayfa (ör. hero'daki piksel haritası) katmana girmez; cam
orada zemin rengini gösterir.
Kurulum: kap `relative isolate`, ilk çocuk `<KayanCam secili={…} />`; düz vurgu
`data-cam-vurgu` + `[[data-cam-geziyor]_&]:opacity-0!` taşır (mercek ilk karesini çizince
gizlenir); seçili seçenek `[[data-cam-yolda]_&]:…!` sınıflarıyla yoldayken seçilmemiş gibi
`data-glass-highlight` + `[[data-glass-moving]_&]:opacity-0!` taşır (mercek ilk karesini çizince
gizlenir); seçili seçenek `[[data-glass-traveling]_&]:…!` sınıflarıyla yoldayken seçilmemiş gibi
boyanır (şeffaf camın altında okunsun), hedefe yaklaşınca seçili rengine camın altında döner.
Durağanken görünen düz vurgudur; WebGL2 yoksa ve hareketi azalt'ta eski `layoutId`
kayması/yerinde belirme aynen çalışır. Tema seçici, satır seçimi
(`karsilastirma-yorungesi`) ve içindekiler çizgisi cam değildir.
- **Sade karşılık:** ilk kare çizilince butona `data-cam` yazılır ve buton turuncu zeminini
- **Sade karşılık:** ilk kare çizilince butona `data-glass-ready` yazılır ve buton turuncu zeminini
bırakır. O ana kadar, WebGL2 yoksa ve bağlam kaybolursa buton eski düz turuncu CTA'dır
(`hover:bg-orange-600`, `active:scale-[0.97]`); iki zemin aynı anda görünmez.
- **Ne zaman çizilir:** boy ya da tema değişince, ekrana girince, imleç oynayınca ve yaylar

View File

@@ -16,6 +16,8 @@ const eslintConfig = defineConfig([
".claude/worktrees/**",
// Türkçe TTS sanal ortamı (scripts/seslendir.py); içindeki torch JS dosyaları lint'e girmesin.
".venv-tts/**",
// Liquid Glass UI kitinden birebir kopya (DESIGN.md §4.50): elle düzenlenmez, kendi kurallarıyla yazılmıştır.
"src/components/liquid-glass/**",
]),
]);

View File

@@ -1,6 +1,6 @@
{
"name": "kolaytercih",
"version": "2.12.13",
"version": "2.12.14",
"private": true,
"engines": {
"node": ">=22"

View File

@@ -5,6 +5,8 @@
* Çıkış kodu: hata varsa 1, yoksa 0. Uyarılar çıkış kodunu etkilemez.
* Kapsam: src/**\/*.tsx. Hariç: src/components/ui (shadcn tabanı) ve
* src/components/dev (yalnızca geliştirici paneli) — bazı kurallarda.
* Tümüyle hariç: src/components/liquid-glass (Liquid Glass UI kitinden birebir
* kopya, elle düzenlenmez; DESIGN.md §4.50).
*/
import { readdirSync, readFileSync, statSync } from "node:fs";
import { join, relative } from "node:path";
@@ -34,11 +36,14 @@ type Kural = {
const KOK = process.cwd();
const KAYNAK = join(KOK, "src");
const UI_VEYA_DEV = /src\/components\/(ui|dev)\//;
/** Kitten birebir kopyalanan cam motoru (§4.50): bizim kurallarımızla yazılmadı, taranmaz. */
const KIT_KOPYASI = /src\/components\/liquid-glass$/;
function tsxDosyalari(dizin: string): string[] {
const sonuc: string[] = [];
for (const ad of readdirSync(dizin)) {
const yol = join(dizin, ad);
if (KIT_KOPYASI.test(yol)) continue;
if (statSync(yol).isDirectory()) sonuc.push(...tsxDosyalari(yol));
else if (yol.endsWith(".tsx")) sonuc.push(yol);
}

View File

@@ -1496,14 +1496,27 @@ html.lenis body {
right: calc(var(--ok-cap) / 2);
translate: 50% -50%;
}
[data-sivi="bas"]:has(> canvas:first-child + svg) {
[data-sivi="bas"]:has(> [data-cam-iz] + svg) {
padding-left: calc(var(--ok-cap) * 1.625);
}
[data-sivi="bas"] > canvas:first-child + svg {
[data-sivi="bas"] > [data-cam-iz] + svg {
position: absolute;
top: 50%;
left: calc(var(--ok-cap) / 2);
translate: -50% -50%;
}
}
/* Kit damlayı yalnız sonda ayırır: ikonu başta olan kabın cam tuvali yatay
çevrilir (cam simetriktir; boyalı camda arkası kırılmaz). */
[data-sivi="bas"] > canvas:first-child {
transform: scaleX(-1);
}
/* CTA yüzeyindeki şeffaf cam mavi boyalıdır (kit `--glass-tint`); mavi bantta
bir ton koyu, cam kendi rengindeki zeminden ayrılsın (§4.50). */
[data-cta-yuzey] [data-seffaf] {
--glass-tint: var(--primary);
}
[data-cta-yuzey][data-cta-ton="mavi"] [data-seffaf] {
--glass-tint: color-mix(in oklch, var(--primary), black 28%);
}

View File

@@ -121,8 +121,8 @@ export default function RootLayout({
(.kt-sayfa-blur): iOS/iPadOS'ta fixed + backdrop-filter katmanı
kaydırmada ekranın ortasına kayıyor, orada bulanıklık @supports
ile düşürülüp degrade fade korunuyor. */}
<div className="kt-sayfa-blur kt-sayfa-blur-ust print:hidden" aria-hidden />
<div className="kt-sayfa-blur kt-sayfa-blur-alt print:hidden" aria-hidden />
<div className="kt-sayfa-blur kt-sayfa-blur-ust print:hidden" aria-hidden data-glass-skip="" />
<div className="kt-sayfa-blur kt-sayfa-blur-alt print:hidden" aria-hidden data-glass-skip="" />
<SiteTopBanner />
<SiteHeader />
</HeaderGate>

View File

@@ -33,6 +33,15 @@ type Surum = {
};
const SURUMLER: Surum[] = [
{
surum: "2.12.14",
tarih: "26 Kasım 2026",
maddeler: [],
arayuz: [
"Sıvı cam görünümü yenilendi (sayfanın en altındaki \"Sıvı cam\" kutusunu işaretlediysen görürsün). Cam düğmeye basınca içine ışık dolar; düğmeyi tutup çekersen jel gibi uzar, bırakınca yerine döner; yan yana duran cam düğmeler birbirine yaklaşınca birleşir.",
"Şeffaf cam artık çevresindeki rengi kenarında yansıtıyor ve arkasındaki sayfayı daha doğru büküyor. Hareket etmeyen cam artık boşuna çizilmiyor; sayfa daha az yoruluyor.",
],
},
{
surum: "2.12.13",
tarih: "15 Kasım 2026",

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 Bilal Abdullah Gürşen
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,834 @@
// dom-snapshot — paints a DOM subtree into a Canvas2D context at its on-screen position.
//
// A WebGL lens cannot read the page's pixels, so glass that bends the page needs the
// page as a texture. This paints a good-enough picture of it: backgrounds (colours,
// gradients and images, with their size, position and repeat), rounded borders, text,
// inline SVG icons, canvases, images and video (with object-fit) and backdrop blur.
// Siblings are painted in CSS order: negative z-index, content, positioned, positive z-index.
// It is not a browser renderer: no shadows, conic gradients, masks, rotation or
// ::before/::after. An image from another origin is requested again with CORS; if its
// server does not allow that it is left out, because a canvas such an image has touched
// can never become a WebGL texture. Used by `material="clear"` glass, by GlassBadge and,
// through `drawAround`, for what every rim mirrors of the page around it.
//
// COPY THIS FILE VERBATIM. MIT — https://github.com/bilalgursen/liquid-glass
type Box = { x: number; y: number; w: number; h: number }
type Drawable = HTMLImageElement | HTMLCanvasElement | HTMLVideoElement
const isVisibleColor = (color: string) =>
!!color && color !== 'transparent' && !/rgba\(.*,\s*0\)$/.test(color) && !/\/\s*0\)$/.test(color)
/** Splits on a separator that is not inside parentheses: "a(1, 2), b" → ["a(1, 2)", "b"]. */
function splitTop(text: string, separator: string) {
const parts: string[] = []
let depth = 0
let start = 0
for (let i = 0; i < text.length; i++) {
const ch = text[i]
if (ch === '(') depth++
else if (ch === ')') depth--
else if (ch === separator && depth === 0) {
parts.push(text.slice(start, i))
start = i + 1
}
}
parts.push(text.slice(start))
return parts.map((part) => part.trim()).filter(Boolean)
}
/** "40%" or "12px" of a span. */
const lengthOf = (token: string, span: number) => (token.endsWith('%') ? (span * parseFloat(token)) / 100 : parseFloat(token) || 0)
/** One axis of a CSS position ("25%", "12px", "right", "calc(100% - 8px)") inside `free` px of room. */
function along(token: string | undefined, free: number) {
if (!token) return free / 2
const calc = /^calc\(([-\d.]+)% ([+-]) ([\d.]+)px\)$/.exec(token)
if (calc) return (free * Number(calc[1])) / 100 + (calc[2] === '-' ? -1 : 1) * Number(calc[3])
if (/^-?[\d.]/.test(token)) return lengthOf(token, free)
return token === 'left' || token === 'top' ? 0 : token === 'right' || token === 'bottom' ? free : free / 2
}
/** `background-position`, `object-position` and a gradient's `at …` as an offset into the free room. */
function placeOf(position: string, freeX: number, freeY: number): [number, number] {
let [a, b, c, d] = splitTop(position, ' ')
// "right 10px bottom 20px": offsets measured from the named edges.
if (d) return [a === 'right' ? freeX - along(b, freeX) : along(b, freeX), c === 'bottom' ? freeY - along(d, freeY) : along(d, freeY)]
if (a === 'top' || a === 'bottom' || b === 'left' || b === 'right') [a, b] = [b, a]
return [along(a, freeX), along(b, freeY)]
}
// ── Sources: loading, and keeping the canvas readable ────────────────────────
const verdicts = new WeakMap<Drawable, { key: string; ok: boolean }>()
/**
* Is this source safe to draw? One image without CORS (or an SVG, in some browsers)
* taints the whole canvas and WebGL can then no longer read it, so each source is
* tried once on a 1×1 canvas first. `key` is whatever makes it a different picture.
*/
function isClean(source: Drawable, key = '') {
const known = verdicts.get(source)
if (known && known.key === key) return known.ok
let ok = false
try {
const probe = document.createElement('canvas')
probe.width = probe.height = 1
const ctx = probe.getContext('2d', { willReadFrequently: true })
if (ctx) {
ctx.drawImage(source, 0, 0, 1, 1)
ctx.getImageData(0, 0, 1, 1)
ok = true
}
} catch {
// SecurityError: another origin without CORS. InvalidStateError: a broken image.
}
verdicts.set(source, { key, ok })
return ok
}
const waiting = new WeakMap<HTMLImageElement, Set<() => void>>()
/** True once the image can be drawn. Until then `onStale` is called when it arrives. */
function isLoaded(image: HTMLImageElement, onStale?: () => void) {
if (image.complete) return image.naturalWidth > 0
if (!onStale) return false
let callbacks = waiting.get(image)
if (!callbacks) {
const pending = (callbacks = new Set())
waiting.set(image, pending)
image.addEventListener(
'load',
() => {
waiting.delete(image)
pending.forEach((notify) => notify())
},
{ once: true },
)
}
callbacks.add(onStale)
return false
}
const isSameOrigin = (src: string) => {
try {
const url = new URL(src, location.href)
return url.protocol === 'data:' || url.protocol === 'blob:' || url.origin === location.origin
} catch {
return false
}
}
const copies = new Map<string, HTMLImageElement>()
/** Our own copy of an image by URL: a CSS background, or an <img> the page loaded without CORS. */
function imageCopy(src: string) {
let image = copies.get(src)
if (!image) {
if (copies.size > 200) copies.clear()
image = new Image()
if (!isSameOrigin(src)) image.crossOrigin = 'anonymous'
image.decoding = 'async'
image.src = src
copies.set(src, image)
}
return image
}
/** Draws an image or a video frame into its box the way `object-fit` and `object-position` place it. */
function drawFitted(ctx: CanvasRenderingContext2D, source: Drawable, sw: number, sh: number, box: Box, radius: number, style: CSSStyleDeclaration) {
const fit = style.objectFit
let w = box.w
let h = box.h
if (fit !== 'fill') {
const contain = Math.min(box.w / sw, box.h / sh)
const k = fit === 'cover' ? Math.max(box.w / sw, box.h / sh) : fit === 'none' ? 1 : fit === 'scale-down' ? Math.min(1, contain) : contain
w = sw * k
h = sh * k
}
const [ox, oy] = placeOf(style.objectPosition, box.w - w, box.h - h)
const clips = radius > 0 || w > box.w + 0.5 || h > box.h + 0.5
if (clips) {
ctx.save()
ctx.beginPath()
ctx.roundRect(box.x, box.y, box.w, box.h, radius)
ctx.clip()
}
ctx.drawImage(source, box.x + ox, box.y + oy, w, h)
if (clips) ctx.restore()
}
const svgCache = new WeakMap<Element, { key: string; image: HTMLImageElement }>()
/** Set when this browser treats an SVG image as unreadable: icons are then left out. */
let svgTaints = false
/**
* Draws an inline SVG as an image. Colours that come from classes are inlined first.
* Built once per element and rebuilt when the colour, the cache key or the size
* changes, so an animated SVG keeps its first frame instead of rebuilding every call.
*/
function drawSvg(ctx: CanvasRenderingContext2D, svg: SVGSVGElement, color: string, box: Box, onStale: (() => void) | undefined, cacheKey: string) {
if (svgTaints) return
const key = `${color}|${cacheKey}|${Math.round(box.w)}x${Math.round(box.h)}`
let entry = svgCache.get(svg)
if (!entry || entry.key !== key) {
const clone = svg.cloneNode(true) as SVGSVGElement
const originals = [svg, ...svg.querySelectorAll('*')]
const clones = [clone, ...clone.querySelectorAll('*')]
originals.forEach((original, i) => {
const style = getComputedStyle(original)
const target = clones[i] as SVGElement
target.removeAttribute('class')
target.style.fill = style.fill
target.style.stroke = style.stroke
target.style.animation = 'none'
})
clone.setAttribute('xmlns', 'http://www.w3.org/2000/svg')
clone.setAttribute('width', String(box.w))
clone.setAttribute('height', String(box.h))
clone.style.color = color
const image = new Image()
image.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(new XMLSerializer().serializeToString(clone))}`
entry = { key, image }
svgCache.set(svg, entry)
}
if (!isLoaded(entry.image, onStale)) return
if (isClean(entry.image)) ctx.drawImage(entry.image, box.x, box.y, box.w, box.h)
else svgTaints = true
}
// ── Backgrounds: gradients and images ────────────────────────────────────────
type Stop = { color: string; at: number | null; px: boolean }
type Gradient =
| { kind: 'linear'; repeating: boolean; stops: Stop[]; angle: number; corner: string }
| { kind: 'radial'; repeating: boolean; stops: Stop[]; circle: boolean; extent: string; size: string[]; at: string }
type BackgroundImage = { kind: 'url'; src: string } | Gradient
function parseStops(args: string[], currentColor: string): Stop[] | null {
const stops: Stop[] = []
for (const arg of args) {
const tokens = splitTop(arg, ' ')
const positions: string[] = []
while (tokens.length && /^-?[\d.]+(%|px)$/.test(tokens[tokens.length - 1])) positions.unshift(tokens.pop() as string)
if (!tokens.length) continue // a colour hint (a position alone) is skipped
const color = tokens.join(' ').replace(/currentcolor/gi, currentColor)
if (!positions.length) stops.push({ color, at: null, px: false })
for (const position of positions) stops.push({ color, at: parseFloat(position), px: position.endsWith('px') })
}
return stops.length > 1 ? stops : null
}
/** One layer of a computed `background-image`; null for what is not supported (conic gradients, image-set…). */
function parseImage(text: string, currentColor: string): BackgroundImage | null {
const url = /^url\((['"]?)(.*)\1\)$/.exec(text)
if (url) return { kind: 'url', src: url[2] }
const gradient = /^(repeating-)?(linear|radial)-gradient\(([\s\S]*)\)$/.exec(text)
if (!gradient) return null
const repeating = !!gradient[1]
const args = splitTop(gradient[3], ',')
// The first argument is the direction or the shape, unless it is already a colour.
// "in oklab" (the interpolation space) is dropped: canvas always blends in sRGB.
const first = args[0] ?? ''
const head = first.replace(/\bin\s+[\w-]+(\s+\w+\s+hue)?/i, '').trim()
const spaceOnly = head === '' && first !== ''
if (gradient[2] === 'linear') {
let angle = Math.PI
let corner = ''
let isDirection = spaceOnly
if (/^to\s/.test(head)) {
const v = /top/.test(head) ? 't' : /bottom/.test(head) ? 'b' : ''
const hz = /left/.test(head) ? 'l' : /right/.test(head) ? 'r' : ''
if (v && hz) corner = v + hz
else angle = ({ t: 0, r: Math.PI / 2, b: Math.PI, l: Math.PI * 1.5 } as Record<string, number>)[v || hz] ?? Math.PI
isDirection = true
} else if (/^-?[\d.]+(deg|grad|rad|turn)$/.test(head)) {
const n = parseFloat(head)
angle = head.endsWith('turn') ? n * Math.PI * 2 : head.endsWith('grad') ? (n * Math.PI) / 200 : head.endsWith('rad') ? n : (n * Math.PI) / 180
isDirection = true
}
const stops = parseStops(isDirection ? args.slice(1) : args, currentColor)
return stops && { kind: 'linear', repeating, stops, angle, corner }
}
const isShape = spaceOnly || /^(circle|ellipse|closest-|farthest-|at\s|-?[\d.]+(px|%))/.test(head)
const [shape = '', at = 'center'] = isShape ? head.split(/\s*\bat\s+/) : []
const size = shape.match(/-?[\d.]+(px|%)/g) ?? []
const stops = parseStops(isShape ? args.slice(1) : args, currentColor)
return (
stops && {
kind: 'radial',
repeating,
stops,
circle: /circle/.test(shape) || size.length === 1,
extent: /(closest|farthest)-(side|corner)/.exec(shape)?.[0] ?? 'farthest-corner',
size,
at,
}
)
}
const parsed = new Map<string, (BackgroundImage | null)[]>()
function imagesOf(style: CSSStyleDeclaration) {
const value = style.backgroundImage
const key = /currentcolor/i.test(value) ? `${value}|${style.color}` : value
let images = parsed.get(key)
if (!images) {
if (parsed.size > 300) parsed.clear()
images = splitTop(value, ',').map((image) => parseImage(image, style.color))
parsed.set(key, images)
}
return images
}
/** A stop's colour at zero alpha. CSS fades in premultiplied colour, canvas does not, so "transparent" has to keep the hue next to it. */
function clearOf(color: string) {
const legacy = /^rgba?\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)/.exec(color)
if (legacy) return `rgba(${legacy[1]}, ${legacy[2]}, ${legacy[3]}, 0)`
const modern = /^([a-z-]+\([^/)]+?)\s*(\/[^)]*)?\)$/.exec(color)
return modern ? `${modern[1]} / 0)` : color
}
/**
* Resolves stop positions along a gradient line `length` px long. Returns the part of
* the line the stops span (`from`..`to`, as fractions of it) and each stop inside that
* part (0..1). `reach`: how far along the line the box extends (repeats cover it).
*/
function rampOf(stops: Stop[], length: number, repeating: boolean, reach = 1) {
const at = stops.map((stop) => (stop.at === null ? null : stop.px ? stop.at / Math.max(length, 1e-6) : stop.at / 100))
if (at[0] === null) at[0] = 0
if (at[at.length - 1] === null) at[at.length - 1] = 1
for (let i = 1; i < at.length; i++) {
if (at[i] === null) {
// Stops without a position are spread evenly between their neighbours.
let j = i
while (at[j] === null) j++
const a = at[i - 1] as number
const b = Math.max(at[j] as number, a)
for (let k = i; k < j; k++) at[k] = a + ((b - a) * (k - i + 1)) / (j - i + 1)
}
at[i] = Math.max(at[i] as number, at[i - 1] as number)
}
let list: [number, string][] = []
stops.forEach((stop, i) => {
const p = at[i] as number
const before = stops[i - 1]
const after = stops[i + 1]
// A transparent stop becomes its neighbours' colours at zero alpha (see clearOf).
const fades = !isVisibleColor(stop.color)
const fromBefore = fades && !!before && isVisibleColor(before.color)
const toAfter = fades && !!after && isVisibleColor(after.color)
if (fromBefore) list.push([p, clearOf(before.color)])
if (toAfter) list.push([p, clearOf(after.color)])
if (!fromBefore && !toAfter) list.push([p, stop.color])
})
let from = list[0][0]
let to = list[list.length - 1][0]
const period = to - from
if (repeating && period > 1e-4) {
const first = Math.floor(-from / period)
const count = Math.ceil((reach - from) / period) - first
if (count > 200) return null
const one = list
list = []
for (let k = first; k < first + count; k++) for (const [p, color] of one) list.push([p + k * period, color])
from += first * period
to = from + count * period
}
// Stops that all share one position are a hard edge: keep the line a hair long, or canvas paints nothing.
const span = Math.max(to - from, 0.02 / Math.max(length, 1e-6))
return { from, to: from + span, stops: list.map(([p, color]): [number, string] => [Math.min(1, Math.max(0, (p - from) / span)), color]) }
}
/** Fills (0, 0, w, h) with a CSS gradient. */
function fillGradient(ctx: CanvasRenderingContext2D, gradient: Gradient, w: number, h: number) {
if (gradient.kind === 'linear') {
let angle = gradient.angle
if (gradient.corner) {
// "to top right": the line that puts the two neighbouring corners on the 50 % mark.
const base = Math.atan2(h, w)
angle = ({ tr: base, br: Math.PI - base, bl: Math.PI + base, tl: -base } as Record<string, number>)[gradient.corner] ?? base
}
const sin = Math.sin(angle)
const cos = Math.cos(angle)
const length = Math.abs(w * sin) + Math.abs(h * cos)
const ramp = rampOf(gradient.stops, length, gradient.repeating)
if (!ramp) return
// The gradient line runs through the centre of the box.
const x = (t: number) => w / 2 + sin * length * (t - 0.5)
const y = (t: number) => h / 2 - cos * length * (t - 0.5)
const fill = ctx.createLinearGradient(x(ramp.from), y(ramp.from), x(ramp.to), y(ramp.to))
for (const [p, color] of ramp.stops) fill.addColorStop(p, color)
ctx.fillStyle = fill
ctx.fillRect(0, 0, w, h)
return
}
const [cx, cy] = placeOf(gradient.at, w, h)
const dx = [Math.abs(cx), Math.abs(w - cx)]
const dy = [Math.abs(cy), Math.abs(h - cy)]
const pick = gradient.extent.startsWith('closest') ? Math.min : Math.max
let rx = pick(...dx)
let ry = pick(...dy)
if (gradient.size.length) {
rx = lengthOf(gradient.size[0], w)
ry = gradient.size[1] ? lengthOf(gradient.size[1], h) : rx
} else if (gradient.circle) rx = ry = gradient.extent.endsWith('corner') ? Math.hypot(rx, ry) : pick(rx, ry)
else if (gradient.extent.endsWith('corner')) {
rx *= Math.SQRT2
ry *= Math.SQRT2
}
if (rx < 0.01 || ry < 0.01) return
const ramp = rampOf(gradient.stops, rx, gradient.repeating, Math.hypot(Math.max(...dx) / rx, Math.max(...dy) / ry))
if (!ramp) return
const inner = Math.max(0, rx * ramp.from)
const fill = ctx.createRadialGradient(0, 0, inner, 0, 0, Math.max(rx * ramp.to, inner + 1e-3))
for (const [p, color] of ramp.stops) fill.addColorStop(p, color)
// An ellipse is a circle squeezed along y.
ctx.save()
ctx.translate(cx, cy)
ctx.scale(1, ry / rx)
ctx.fillStyle = fill
ctx.fillRect(-cx, (-cy * rx) / ry, w, (h * rx) / ry)
ctx.restore()
}
/**
* Paints an element's `background-image` layers. `area` is the box they are sized and
* positioned in, `bounds` the part of it worth painting. The caller has clipped to the box.
*/
function paintBackgrounds(ctx: CanvasRenderingContext2D, style: CSSStyleDeclaration, area: Box, bounds: Box, onStale?: () => void) {
const images = imagesOf(style)
const sizes = splitTop(style.backgroundSize, ',')
const positions = splitTop(style.backgroundPosition, ',')
const repeats = splitTop(style.backgroundRepeat, ',')
// The first layer is the top one: paint from the last.
for (let n = images.length - 1; n >= 0; n--) {
const image = images[n]
if (!image) continue
let source: HTMLImageElement | null = null
let tw = area.w
let th = area.h
if (image.kind === 'url') {
source = imageCopy(image.src)
if (!isLoaded(source, onStale) || !isClean(source)) continue
tw = source.naturalWidth
th = source.naturalHeight
}
// Tile size: gradients have no size of their own and fill the area.
const size = sizes[n % sizes.length] ?? 'auto'
if (size === 'cover' || size === 'contain') {
const k = (size === 'cover' ? Math.max : Math.min)(area.w / tw, area.h / th)
tw *= k
th *= k
} else {
const [sw = 'auto', sh = 'auto'] = splitTop(size, ' ')
const ratio = tw / th
if (sw !== 'auto') tw = lengthOf(sw, area.w)
if (sh !== 'auto') th = lengthOf(sh, area.h)
if (source && sw !== 'auto' && sh === 'auto') th = tw / ratio
if (source && sw === 'auto' && sh !== 'auto') tw = th * ratio
}
if (!(tw >= 0.5 && th >= 0.5)) continue
const [ox, oy] = placeOf(positions[n % positions.length] ?? '0% 0%', area.w - tw, area.h - th)
const repeat = repeats[n % repeats.length] ?? 'repeat'
const [repeatX, repeatY = repeatX] = repeat.split(' ')
const tilesX = repeat !== 'repeat-y' && repeatX !== 'no-repeat'
const tilesY = repeat !== 'repeat-x' && repeatY !== 'no-repeat'
// Only the tiles that reach the visible part.
const x0 = area.x + ox
const y0 = area.y + oy
const i0 = tilesX ? Math.floor((bounds.x - x0) / tw) : 0
const i1 = tilesX ? Math.floor((bounds.x + bounds.w - x0 - 0.01) / tw) : 0
const j0 = tilesY ? Math.floor((bounds.y - y0) / th) : 0
const j1 = tilesY ? Math.floor((bounds.y + bounds.h - y0 - 0.01) / th) : 0
// A very fine pattern blurs to nothing under glass: not worth hundreds of tiles.
if ((i1 - i0 + 1) * (j1 - j0 + 1) > 400) continue
try {
for (let j = j0; j <= j1; j++) {
for (let i = i0; i <= i1; i++) {
ctx.save()
ctx.translate(x0 + i * tw, y0 + j * th)
if (source) ctx.drawImage(source, 0, 0, tw, th)
else fillGradient(ctx, image as Gradient, tw, th)
ctx.restore()
}
}
} catch {
// A colour this browser's canvas cannot parse: the layer is left out
// (the gradient is built before anything else is saved, so one restore is owed).
ctx.restore()
}
}
}
// ── Text and backdrop blur ───────────────────────────────────────────────────
/** Draws one text node line by line, where the page laid it out and in its own font. */
function drawText(
ctx: CanvasRenderingContext2D,
node: Text,
style: CSSStyleDeclaration,
originX: number,
originY: number,
lang: string | undefined,
isVisible: (rect: DOMRect) => boolean,
range: Range,
) {
const raw = node.textContent ?? ''
let text = raw.replace(/\s+/g, ' ').trim()
if (!text) return
range.selectNodeContents(node)
const lines = [...range.getClientRects()].filter((rect) => rect.width > 0.5)
// No line of it shows: its font is not set up and nothing is measured.
if (!lines.some(isVisible)) return
// The page shows the transformed text. Upper and lower case follow the page's
// language (Turkish i → İ); browsers capitalise without it.
const transform = style.textTransform
if (transform === 'uppercase') text = text.toLocaleUpperCase(lang)
else if (transform === 'lowercase') text = text.toLocaleLowerCase(lang)
else if (transform === 'capitalize') text = text.replace(/(^|\s)(\S)/g, (_, gap: string, letter: string) => gap + letter.toUpperCase())
const rtl = style.direction === 'rtl'
ctx.font = `${style.fontStyle} ${style.fontWeight} ${style.fontSize} ${style.fontFamily}`
if ('letterSpacing' in ctx) ctx.letterSpacing = style.letterSpacing === 'normal' ? '0px' : style.letterSpacing
ctx.direction = rtl ? 'rtl' : 'ltr'
ctx.textAlign = 'left'
ctx.fillStyle = style.color
ctx.textBaseline = 'alphabetic'
const metrics = ctx.measureText('Hgİş')
const ascent = metrics.fontBoundingBoxAscent
const descent = metrics.fontBoundingBoxDescent
const space = ctx.measureText(' ').width
// Fill each line with as many words as fit (a single line takes them all).
const words = text.split(' ')
let next = 0
lines.forEach((rect, i) => {
let line = ''
if (i === lines.length - 1) line = words.slice(next).join(' ')
else {
while (next < words.length) {
const candidate = line ? `${line} ${words[next]}` : words[next]
if (line && ctx.measureText(candidate).width > rect.width + 1) break
line = candidate
next++
}
}
if (!line || !isVisible(rect)) return
// A leading space takes room only after an inline neighbour (not at the start of a
// block): then the line box is wider than its words, and the text starts further in.
const lead = i === 0 && !rtl && /^\s/.test(raw) && rect.width - ctx.measureText(line).width > space * 0.5 ? space : 0
const baseline = rect.top - originY + (rect.height - (ascent + descent)) / 2 + ascent
ctx.fillText(line, rect.left - originX + lead, baseline)
})
}
let scratch: HTMLCanvasElement | undefined
/**
* Blurs a box of the canvas in place (the counterpart of `backdrop-filter: blur()`).
* Like CSS, only what is inside the box is blurred and its edge pixels repeat outwards,
* so content next to a frosted bar does not bleed into it.
*/
function blurBackdrop(ctx: CanvasRenderingContext2D, box: Box, radius: number, blurPx: number) {
const matrix = ctx.getTransform()
const scale = matrix.a
// (A context may be scaled a hair differently each way: the engine fits a small picture to its canvas.)
const scaleY = matrix.d
const left = Math.max(0, Math.floor(box.x * scale + matrix.e))
const top = Math.max(0, Math.floor(box.y * scaleY + matrix.f))
const w = Math.min(ctx.canvas.width, Math.ceil((box.x + box.w) * scale + matrix.e)) - left
const h = Math.min(ctx.canvas.height, Math.ceil((box.y + box.h) * scaleY + matrix.f)) - top
if (w < 1 || h < 1) return
const pad = Math.ceil(blurPx * scale * 3)
scratch ??= document.createElement('canvas')
scratch.width = w + 2 * pad
scratch.height = h + 2 * pad
const copy = scratch.getContext('2d')
if (!copy) return
copy.imageSmoothingEnabled = false
copy.drawImage(ctx.canvas, left, top, w, h, pad, pad, w, h)
copy.drawImage(scratch, pad, pad, 1, h, 0, pad, pad, h)
copy.drawImage(scratch, pad + w - 1, pad, 1, h, pad + w, pad, pad, h)
copy.drawImage(scratch, 0, pad, w + 2 * pad, 1, 0, 0, w + 2 * pad, pad)
copy.drawImage(scratch, 0, pad + h - 1, w + 2 * pad, 1, 0, pad + h, w + 2 * pad, pad)
ctx.save()
ctx.beginPath()
ctx.roundRect(box.x, box.y, box.w, box.h, radius)
ctx.clip()
ctx.setTransform(1, 0, 0, 1, 0, 0)
ctx.globalAlpha = 1
ctx.clearRect(left, top, w, h)
ctx.filter = `blur(${blurPx * scale}px)`
ctx.drawImage(scratch, left - pad, top - pad)
ctx.restore()
}
// ── The walk ─────────────────────────────────────────────────────────────────
/**
* Where a child paints among its siblings (CSS 2.1 appendix E, per parent):
* 0 negative z-index, 1 content in the flow, 2 positioned and stacking boxes, 3 positive z-index.
*/
function layerOf(style: CSSStyleDeclaration, inFlexOrGrid: boolean): [layer: number, z: number] {
const positioned = style.position !== 'static'
const z = (positioned || inFlexOrGrid) && style.zIndex !== 'auto' ? parseInt(style.zIndex, 10) || 0 : 0
if (z) return [z < 0 ? 0 : 3, z]
const stacks =
positioned ||
style.opacity !== '1' ||
style.transform !== 'none' ||
style.filter !== 'none' ||
style.isolation === 'isolate' ||
(style.backdropFilter || 'none') !== 'none'
return [stacks ? 2 : 1, 0]
}
export type DomSnapshotOptions = {
/**
* The viewport point that lands on the context's origin, in CSS px.
* Pass a `getBoundingClientRect()` result; only `left` and `top` are read.
*/
origin: { left: number; top: number }
/** Visit only elements whose box intersects this viewport rectangle. */
region?: { left: number; top: number; right: number; bottom: number }
/** Return true to leave an element and everything inside it out. */
skip?: (element: Element) => boolean
/** Called when an image or an SVG that was not ready has loaded: draw again. */
onStale?: () => void
/** Any string that changes when icon colours may have changed, such as the theme name. */
cacheKey?: string
/**
* Filled in by the walk, for a caller that wants to know whether its picture survives a scroll:
* `pinned` gets every fixed or sticky element met, `touched` says one of them reaches the region,
* and `loose` that something painted may move by itself (an animation, an inline transform, a fixed background).
*/
found?: { pinned: Element[]; touched: boolean; loose: boolean }
}
/**
* Paints `root` and everything inside it into `ctx`. The context must already be
* scaled so that one unit is one CSS px. Boxes that clip their overflow clip their
* children; fixed and sticky elements are painted last, on top.
*/
/** A computed `clip-path` of the `inset()` or `path()` kind as a canvas path; anything else is not clipped. */
function clipShape(value: string, box: Box): Path2D | null {
if (!value || value === 'none') return null
const path = /^path\((?:[a-z-]+\s*,\s*)?["'](.*)["']\)$/s.exec(value)
if (path) {
const shape = new Path2D()
shape.addPath(new Path2D(path[1]), new DOMMatrix().translate(box.x, box.y))
return shape
}
const inset = /^inset\((.*)\)$/s.exec(value)
if (!inset) return null
const [sides, round = ''] = inset[1].split(/\s+round\s+/)
const length = (token: string, of: number) => (token.endsWith('%') ? (parseFloat(token) / 100) * of : parseFloat(token) || 0)
const t = sides.trim().split(/\s+/)
const top = length(t[0], box.h)
const right = length(t[1] ?? t[0], box.w)
const bottom = length(t[2] ?? t[0], box.h)
const left = length(t[3] ?? t[1] ?? t[0], box.w)
const w = Math.max(0, box.w - left - right)
const h = Math.max(0, box.h - top - bottom)
const shape = new Path2D()
shape.roundRect(box.x + left, box.y + top, w, h, Math.min(round ? length(round.trim().split(/\s+/)[0], Math.min(w, h)) : 0, w / 2, h / 2))
return shape
}
/** Screen-reader-only text (a 1 px square) and empty boxes: never painted. */
const isEmpty = (rect: DOMRect) => rect.width <= 0 || rect.height <= 0 || (rect.width <= 1 && rect.height <= 1)
let locale: { of: string; is: string | undefined } | undefined
/** The page's language as a locale, worked out once for each value of `lang`. */
function localeOf(lang: string) {
if (locale?.of === lang) return locale.is
let is: string | undefined
try {
is = Intl.getCanonicalLocales(lang)[0]
} catch {
// Not a language tag: the default locale's rules apply.
}
locale = { of: lang, is }
return is
}
export function drawDom(ctx: CanvasRenderingContext2D, root: Element, options: DomSnapshotOptions) {
const { origin, region, skip, onStale, cacheKey = document.documentElement.className, found } = options
const originX = origin.left
const originY = origin.top
const deferred: { element: Element; opacity: number }[] = []
const intersects = (rect: DOMRect) =>
!region || (rect.right > region.left && rect.left < region.right && rect.bottom > region.top && rect.top < region.bottom)
const lang = localeOf(document.documentElement.lang)
const range = document.createRange()
const walk = (element: Element, parentOpacity: number, isDeferred = false, style = getComputedStyle(element), measured?: DOMRect) => {
if (skip?.(element)) return
if (style.display === 'none' || style.visibility === 'hidden') return
const opacity = parentOpacity * Number(style.opacity)
if (opacity < 0.01) return
if (!isDeferred && element !== root && (style.position === 'fixed' || style.position === 'sticky')) {
deferred.push({ element, opacity: parentOpacity })
found?.pinned.push(element)
return
}
const drawChildren = () => {
const inFlexOrGrid = /flex|grid/.test(style.display)
const children: { node: ChildNode; childStyle: CSSStyleDeclaration | null; layer: number; z: number; rect?: DOMRect }[] = []
for (const node of element.childNodes) {
if (!(node instanceof Element)) {
children.push({ node, childStyle: null, layer: 1, z: 0 })
continue
}
const childStyle = getComputedStyle(node)
// Most siblings on the way down to the region lie outside it, and nothing of such a box is
// painted (see `walk`): it is left out here, before its place among its siblings is worked
// out, which takes most of what is read of an element. Kept whatever its box: an element
// pinned to the viewport (it is met again at the end, and reported in `found`) and one
// without a box of its own (`display: contents`).
let rect: DOMRect | undefined
if (childStyle.position !== 'fixed' && childStyle.position !== 'sticky' && childStyle.display !== 'contents') {
rect = node.getBoundingClientRect()
if (isEmpty(rect) || !intersects(rect)) continue
}
const [layer, z] = layerOf(childStyle, inFlexOrGrid)
children.push({ node, childStyle, layer, z, rect })
}
// The sort is stable: within a layer, document order.
children.sort((a, b) => a.layer - b.layer || a.z - b.z)
for (const { node, childStyle, rect } of children) {
if (childStyle) walk(node as Element, opacity, false, childStyle, rect)
else if (node.nodeType === Node.TEXT_NODE) {
ctx.globalAlpha = opacity
drawText(ctx, node as Text, style, originX, originY, lang, intersects, range)
}
}
}
if (style.display === 'contents') {
drawChildren()
return
}
// (Nothing on the page moves during a walk: a box measured among its siblings is still right.)
const rect = measured ?? element.getBoundingClientRect()
// Screen-reader-only text (a 1 px square) and empty boxes are not painted, a hairline is;
// nothing outside the region is visited.
if (isEmpty(rect) || !intersects(rect)) return
if (found) {
if (isDeferred) found.touched = true
else if (!found.loose) {
// A transform from a stylesheet stays put (a centred box); one written inline is a script's, and may follow the scroll.
const inline = (element as HTMLElement).style as CSSStyleDeclaration | undefined
found.loose =
style.animationName !== 'none' ||
(style.backgroundImage !== 'none' && style.backgroundAttachment.includes('fixed')) ||
(!!inline && !!(inline.transform || inline.translate || inline.rotate || inline.scale))
}
}
const box: Box = { x: rect.left - originX, y: rect.top - originY, w: rect.width, h: rect.height }
// A `clip-path` (inset or path) cuts the box and everything inside it, as on screen.
const shape = clipShape(style.clipPath, box)
if (shape) {
ctx.save()
ctx.clip(shape)
}
try {
paintBox(element, style, rect, box, opacity, drawChildren)
} finally {
if (shape) ctx.restore()
}
}
const paintBox = (element: Element, style: CSSStyleDeclaration, rect: DOMRect, box: Box, opacity: number, drawChildren: () => void) => {
const radius = Math.min(parseFloat(style.borderTopLeftRadius) || 0, rect.width / 2, rect.height / 2)
// Frosted veil (backdrop-filter: blur): blur what is already painted beneath it first,
// otherwise text behind a translucent veil shows up sharp in the glass.
const backdropBlur = /blur\(([\d.]+)px\)/.exec(style.backdropFilter)
if (backdropBlur) blurBackdrop(ctx, box, radius, Number(backdropBlur[1]))
ctx.globalAlpha = opacity
// `background-clip: text` paints the background inside the letters only: no box.
const hasBox = style.backgroundClip !== 'text'
if (hasBox && isVisibleColor(style.backgroundColor)) {
ctx.beginPath()
ctx.roundRect(box.x, box.y, box.w, box.h, radius)
ctx.fillStyle = style.backgroundColor
ctx.fill()
}
if (hasBox && style.backgroundImage !== 'none') {
// The part of the box inside the region: only the tiles that reach it are painted.
const bounds = { ...box }
if (region) {
bounds.x = Math.max(box.x, region.left - originX)
bounds.y = Math.max(box.y, region.top - originY)
bounds.w = Math.min(box.x + box.w, region.right - originX) - bounds.x
bounds.h = Math.min(box.y + box.h, region.bottom - originY) - bounds.y
}
// A fixed background is laid out in the viewport, whatever the element's box.
const area: Box = style.backgroundAttachment.includes('fixed') ? { x: -originX, y: -originY, w: innerWidth, h: innerHeight } : box
ctx.save()
ctx.beginPath()
ctx.roundRect(box.x, box.y, box.w, box.h, radius)
ctx.clip()
paintBackgrounds(ctx, style, area, bounds, onStale)
ctx.restore()
}
const borderWidth = parseFloat(style.borderTopWidth) || 0
if (borderWidth > 0 && style.borderTopStyle !== 'none' && isVisibleColor(style.borderTopColor)) {
ctx.beginPath()
ctx.roundRect(box.x + borderWidth / 2, box.y + borderWidth / 2, box.w - borderWidth, box.h - borderWidth, Math.max(0, radius - borderWidth / 2))
ctx.lineWidth = borderWidth
ctx.strokeStyle = style.borderTopColor
ctx.setLineDash(style.borderTopStyle === 'dashed' ? [4, 3] : [])
ctx.stroke()
ctx.setLineDash([])
}
if (element instanceof SVGSVGElement) {
drawSvg(ctx, element, style.color, box, onStale, cacheKey)
return
}
if (element instanceof HTMLCanvasElement) {
if (element.width && element.height && isClean(element)) ctx.drawImage(element, box.x, box.y, box.w, box.h)
return
}
if (element instanceof HTMLImageElement) {
const src = element.currentSrc || element.src
if (!src) return
// The element itself when the canvas stays readable, otherwise our own CORS copy.
const image = element.complete && element.naturalWidth && isClean(element, src) ? element : imageCopy(src)
if (isLoaded(image, onStale) && isClean(image, src)) drawFitted(ctx, image, image.naturalWidth, image.naturalHeight, box, radius, style)
return
}
if (element instanceof HTMLVideoElement) {
// The current frame; `live` glass follows the playback.
if (element.readyState >= 2 && element.videoWidth && isClean(element, element.currentSrc)) drawFitted(ctx, element, element.videoWidth, element.videoHeight, box, radius, style)
return
}
const clips = element !== root && style.overflow !== 'visible' && element !== document.body && element !== document.documentElement
if (clips) {
ctx.save()
ctx.beginPath()
ctx.roundRect(box.x, box.y, box.w, box.h, radius)
ctx.clip()
}
drawChildren()
if (clips) ctx.restore()
}
walk(root, 1)
for (let i = 0; i < deferred.length; i++) walk(deferred[i].element, deferred[i].opacity, true)
ctx.globalAlpha = 1
}
/**
* Paints what surrounds a box of the viewport, `reach` px past it on every side, with the box's
* top-left on the context's origin: what a glass rim mirrors (`GlassLens.reflection`).
*/
export function drawAround(
ctx: CanvasRenderingContext2D,
root: Element,
box: { left: number; top: number; width: number; height: number },
reach: number,
options: Pick<DomSnapshotOptions, 'skip' | 'onStale'>,
) {
drawDom(ctx, root, {
...options,
origin: box,
region: { left: box.left - reach, top: box.top - reach, right: box.left + box.width + reach, bottom: box.top + box.height + reach },
})
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,279 @@
'use client'
// GlassBadge — a small tinted glass drop with text flowing through it ("New ▪ New ▪ …").
// The text is drawn beneath the glass, so the rim bends the letters as they pass; what
// sits behind the badge (a card corner) shows through, softly blurred.
//
// <div className="relative">
// <Card />
// <GlassBadge className="absolute -top-2 -right-2">New</GlassBadge>
// </div>
//
// Colour: the badge's own CSS background (default blue) and text colour. Hovering the
// badge's positioned parent speeds the flow up. Reduced motion: still, centred text.
// Without WebGL2 a CSS marquee runs instead. COPY VERBATIM. MIT.
import { useEffect, useRef } from 'react'
import { drawAround, drawDom } from './dom-snapshot'
import { GlassStyles } from './glass-layer'
import { getGlassEngine, rgbCss, surfaceColorOf, type GlassView, type Rgb } from './engine'
export type GlassBadgeProps = {
children: string
/** Separator colour (CSS). Default: the text colour. */
dotColor?: string
/** Loops per second at rest. */
speed?: number
/** Opacity of the tint over the backdrop (0–1). */
tint?: number
className?: string
}
const OPTION_UNITS = 80
const OPTICS = (OPTION_UNITS * 1.35) / 120
const HOVER_SPEED = 3.5
const HOVER_ACCEL = 1.6
export function GlassBadge({ children, dotColor, speed = 0.4, tint = 0.82, className = '' }: GlassBadgeProps) {
const canvasRef = useRef<HTMLCanvasElement>(null)
useEffect(() => {
const canvas = canvasRef.current
const host = canvas?.parentElement
const ctx = canvas?.getContext('2d')
const engine = getGlassEngine()
if (!canvas || !host || !ctx || !engine) return
let w = 0
let h = 0
let surface: Rgb = [1, 1, 1]
let paint = 'blue'
let ink = 'white'
let dot = 'white'
let font = '600 12px sans-serif'
let offset = 0
let still = false
let rate = 1
let hovered = false
const snap = { canvas: document.createElement('canvas'), small: document.createElement('canvas'), stale: true, at: 0 }
const measure = () => {
w = host.offsetWidth
h = host.offsetHeight
const s = engine.resolveColor(surfaceColorOf(host.parentElement))
surface = [s[0], s[1], s[2]]
const had = 'glassReady' in host.dataset
if (had) delete host.dataset.glassReady
const st = getComputedStyle(host)
const p = engine.resolveColor(st.backgroundColor)
if (had) host.dataset.glassReady = ''
paint = rgbCss([p[0], p[1], p[2]])
ink = st.color
dot = dotColor ?? st.color
font = `${st.fontWeight} ${st.fontSize} ${st.fontFamily}`
snap.stale = true
}
const view: GlassView = {
canvas,
ctx,
dirty: true,
visible: false,
step: (dt, reduced) => {
still = reduced
if (reduced || !view.visible) return false
rate += ((hovered ? HOVER_SPEED : 1) - rate) * Math.min(1, dt * HOVER_ACCEL)
offset += dt * speed * rate
return true
},
lens: (refresh) => {
if (refresh || !w) measure()
if (w < 2 || h < 2) return null
const padX = 6
const padTop = 8
const padBottom = Math.round(h * 0.9 + 6)
const box = host.getBoundingClientRect()
return {
left: -padX,
top: -padTop,
width: w + 2 * padX,
height: h + padTop + padBottom,
unit: h / OPTION_UNITS,
cx: padX + w / 2,
cy: padTop + h / 2,
hx: w / 2,
hy: h / 2,
radius: 999,
bodyX: 0,
bevel: OPTION_UNITS * 0.42,
shadow: 0.1,
shadowSoftness: 30 * OPTICS,
shadowOffset: 12 * OPTICS,
strength: 1,
color: surface,
surface,
edgeClear: 0,
refraction: {
paint: (back) => {
const dpr = back.getTransform().a
back.translate(padX, padTop)
// What sits behind the badge, painted at a quarter resolution: a cheap blur.
const now = performance.now()
const W = back.canvas.width
const H = back.canvas.height
if (snap.stale || now - snap.at > 500) {
snap.stale = false
snap.at = now
const sw = Math.max(1, Math.round(W / 4))
const sh = Math.max(1, Math.round(H / 4))
snap.small.width = sw
snap.small.height = sh
const sc = snap.small.getContext('2d')
if (sc) {
sc.setTransform(dpr / 4, 0, 0, dpr / 4, (padX * dpr) / 4, (padTop * dpr) / 4)
sc.fillStyle = rgbCss(surface)
sc.fillRect(-padX, -padTop, W, H)
const root = host.offsetParent ?? document.body
drawDom(sc, root, {
origin: { left: box.left, top: box.top },
region: { left: box.left - padX, top: box.top - padTop, right: box.right + padX, bottom: box.bottom + padBottom },
skip: (el) => el === host,
onStale: () => {
snap.stale = true
view.dirty = true
engine.wake()
},
})
}
}
back.save()
back.setTransform(1, 0, 0, 1, 0, 0)
back.imageSmoothingQuality = 'high'
back.drawImage(snap.small, 0, 0, W, H)
back.restore()
back.globalAlpha = tint
back.fillStyle = paint
back.fillRect(-padX, -padTop, w + 2 * padX, h + padTop + padBottom)
back.globalAlpha = 1
back.font = font
back.textBaseline = 'middle'
back.fillStyle = ink
const mid = h / 2 + 0.5
if (still) {
back.textAlign = 'center'
back.fillText(children, w / 2, mid)
return
}
const tw = back.measureText(children).width + 12
back.textAlign = 'left'
for (let x = -((offset % 1) * tw) - tw; x < w + tw; x += tw) {
back.fillStyle = ink
back.fillText(children, x + 6, mid)
back.fillStyle = dot
back.fillRect(x - 2, h / 2 - 1.5, 4, 4)
}
},
refract: 22 * OPTICS,
magnify: 0.1,
dispersion: 0.12,
blurCenter: 0,
blurEdge: 2.2,
frost: 0,
},
cursorLight: true,
pointerLight: true,
// What the rim of a clear badge mirrors: the page around it. A badge in its own
// colour (`tint` above a clear button's 0.6) mirrors nothing.
reflection:
tint > 0.6
? undefined
: {
height: h,
paint: (around, reach) => {
drawAround(around, document.body, { left: box.left - padX, top: box.top - padTop, width: w + 2 * padX, height: h + padTop + padBottom }, reach, {
skip: (el) => el === host || el.hasAttribute('data-glass-skip'),
onStale: dirty,
})
},
},
screenX: box.left + w / 2,
screenY: box.top + h / 2,
}
},
drawn: () => {
host.dataset.glassReady = ''
},
lost: () => {
delete host.dataset.glassReady
},
}
const dirty = () => {
view.dirty = true
engine.wake()
}
const io = new IntersectionObserver(([entry]) => {
view.visible = entry.isIntersecting
dirty()
})
io.observe(host)
const ro = new ResizeObserver(dirty)
ro.observe(host)
const parent = host.offsetParent
if (parent) ro.observe(parent)
const enter = (e: Event) => {
if ((e as PointerEvent).pointerType === 'mouse') hovered = true
}
const leave = () => {
hovered = false
}
parent?.addEventListener('pointerenter', enter)
parent?.addEventListener('pointerleave', leave)
engine.add(view)
return () => {
engine.remove(view)
ctx.clearRect(0, 0, canvas.width, canvas.height)
io.disconnect()
ro.disconnect()
parent?.removeEventListener('pointerenter', enter)
parent?.removeEventListener('pointerleave', leave)
delete host.dataset.glassReady
}
}, [children, dotColor, speed, tint])
return (
<span
data-glass-host=""
className={`pointer-events-none inline-flex h-[22px] w-16 items-center overflow-visible rounded-full bg-[#3291FF] text-xs leading-none font-semibold tracking-[-0.01em] [:where(&)]:text-white ${className}`}
>
<GlassStyles />
<canvas
ref={canvasRef}
aria-hidden
style={{ position: 'absolute', maxWidth: 'none', pointerEvents: 'none', width: 0, height: 0 }}
/>
<span className="sr-only">{children}</span>
{/* CSS fallback until the glass draws (and without WebGL2). */}
<span
aria-hidden
data-glass-fallback=""
className="flex w-full overflow-hidden rounded-full [mask-image:linear-gradient(to_right,transparent,#000_18%,#000_82%,transparent)] motion-reduce:hidden"
>
<span data-glass-marquee="" className="flex w-max shrink-0 items-center">
{Array.from({ length: 4 }, (_, i) => (
<span key={i} className="flex items-center">
<span className="px-1">{children}</span>
<span className="size-1" style={{ background: dotColor ?? 'currentColor' }} />
</span>
))}
</span>
</span>
<span aria-hidden data-glass-fallback="" className="hidden w-full text-center motion-reduce:block">
{children}
</span>
</span>
)
}
export default GlassBadge

View File

@@ -0,0 +1,795 @@
'use client'
// GlassLayer — turns any positioned element (a button, a link, a pill) into liquid glass.
// Put it as the FIRST child of the host and mark the host with `data-glass-host`:
//
// <a data-glass-host href="/start" className="… rounded-full px-6 h-12">
// <GlassLayer material="clear" />
// Get started <ArrowRight />
// </a>
//
// The host keeps its own CSS look until the first glass frame is drawn, then the layer
// sets `data-glass-ready` and the host drops its background, border and shadow (the
// glass now draws them). Without WebGL2 nothing changes: the CSS look stays. Clear glass
// also sets `data-glass-tone="light" | "dark"` from the colour it ends up, for the text.
//
// Hover swells the glass with wobbly springs and press grows it (the host scales with it);
// `swell={false}` keeps it still, as a card's glass is. `blur` frosts what clear glass shows.
// The gooey droplet (used only by GlassActionButton): the host's direct child marked
// `data-glass-drop` sits at the end, and the glass separates around it (`apart`) or melts
// back into one body (`merged`). Switching between the two animates, and the glass swells
// once as it does under the pointer.
// `pulse`: change it and the glass answers once, as if hovered and pressed for a moment
// (GlassActionButton does it when its action succeeds). While it does, the host carries `--glass-bend` (two numbers): put `scale: var(--glass-bend, 1)` on the
// content that should stretch with the glass. `pulseHold` (seconds) keeps it swollen longer
// before it lets go.
// Hold the glass and drag away, and it comes after the pointer a little way, stretched along the
// pull, then swings back like gel when let go (PULL in engine.ts): that is for buttons, which all
// stand on this layer. `pull={false}` keeps one in its place. The host is stretched with CSS, label
// included; the glass undoes that on its canvas and draws the stretch itself, so it stays a pill
// and bends what really lies behind it. COPY VERBATIM.
// MIT — https://github.com/bilalgursen/liquid-glass
import { useEffect, useRef } from 'react'
import { drawAround, drawDom } from './dom-snapshot'
import {
DESIGN_HEIGHT,
PULL,
SPRINGS,
clamp,
cohesionSoftness,
getGlassEngine,
lerp,
mixRgb,
rgbCss,
smooth,
stepSpring,
surfaceColorOf,
type GlassView,
type Rgb,
type Spring,
} from './engine'
export type GlassMaterial = 'clear' | 'tinted'
export type GlassDroplet = 'none' | 'apart' | 'merged'
/**
* Fine-tuning of the glass. Read on every frame: changing a value redraws the glass without
* rebuilding it, so it can follow a slider. Colours and frost apply to clear glass.
*/
export type GlassOptics = {
/** Tint colour, any CSS colour. Default: white on a light page, black on a dark one. */
tintColor?: string
/** A line just inside the rim: its colour, opacity (0–1, default 0: none) and width in px (default 1). */
borderColor?: string
borderAlpha?: number
borderWidth?: number
/** With `blur`: how much of the frost shows over the sharp bend (0–1, default 1). */
frostMix?: number
/** With `blur`: × the frost at the rim, where the glass bends (default 1). */
frostEdge?: number
/** Saturation of what shows through the glass (default 1; 1.5 = more vivid, 0 = grey). */
saturation?: number
/** Without frost: blur of the clear glass in its middle and at its rim, in mip levels (default 0.35 and 2.2). */
clearBlur?: number
clearBlurEdge?: number
/** The bend at the rim, × the kit's own (default 1). */
refraction?: number
/**
* How the rim bends. `edge` (default): along the rim, as deep as the bevel. `radial`: towards
* the centre, by 6.5% of the viewport × `refraction`, fading over half the glass (`bendCurve`
* sets how fast, `bendDepth` how far), and the frost blurs the bent picture: the SVG card's rim.
*/
bendMode?: 'edge' | 'radial'
/** × how far in from the rim the bend reaches (default 1). */
bendDepth?: number
/** How sharply the bend falls off from the rim inwards, an exponent (default 1.6; higher = tighter to the rim). */
bendCurve?: number
/** Colour split at the rim (default 0.12). */
dispersion?: number
/** Magnification of the middle (default 0). */
magnify?: number
/** Light on the glass, all of it (default 1). */
light?: number
/** × the rim light (default 1) and × its line's thickness (default 1). */
rim?: number
rimWidth?: number
/** × the width of the bevel that shades the rim (default 1). */
bevel?: number
/** × the fresnel glow, inner shading, top reflection and warm caustic (each default 1). */
fresnel?: number
inner?: number
reflection?: number
caustic?: number
/** Clear glass: × what the rim mirrors of the page around it, where a colourful neighbour lights the rim that faces it (default 1, 0 = nothing). Tinted glass mirrors nothing. */
mirror?: number
/** The rim light leans towards the cursor (default true). */
cursorLight?: boolean
/** The drop shadow: × its strength, softness and offset (each default 1). */
shadow?: number
shadowSoftness?: number
shadowOffset?: number
/** Dark glass (a black tint, on a dark page): its own tint cover (in place of `tint`) and rim line. Unset values follow the rest. */
dark?: { tint?: number; borderColor?: string; borderAlpha?: number }
}
export type GlassLayerProps = {
/**
* `clear`: transparent glass that bends the page behind it (default).
* `tinted`: glass painted in the host's own CSS background colour, with light and shadow.
*/
material?: GlassMaterial
/**
* The host's `[data-glass-drop]` child as a gooey droplet: `apart` (separated; it melts in
* while pressed) or `merged` (one body). Changing it animates the split or the merge. Default `none`.
*/
droplet?: GlassDroplet
/** Clear glass: how much of the tint covers the backdrop (0 = invisible, 1 = solid). */
tint?: number
/** Clear glass: frost the backdrop with a blur of this many px, like CSS `blur()` (default 0: sharp). */
blur?: number
/** Clear glass: CSS selector of the ancestor whose content is refracted (default: the page). */
backdrop?: string
/** Clear glass: repaint the backdrop every frame (for animated content behind the glass). */
live?: boolean
/** Listen for hover/press on this ancestor instead of the host (e.g. a whole card link). */
trigger?: string
/** Turn the glass off and keep the host's CSS look. */
disabled?: boolean
/** Swell on hover and grow when pressed (default). `false` keeps the glass still under the pointer. */
swell?: boolean
/**
* Change it (a counter) and the glass answers once: it swells as if hovered and pressed for a
* moment. Meanwhile the host has `--glass-bend`, for content that
* stretches with it (`scale: var(--glass-bend, 1)`). Nothing happens on mount, or under reduced motion.
*/
pulse?: unknown
/** How long a pulse stays swollen before it lets go, in seconds (default 0.16: a nod). */
pulseHold?: number
/**
* Hold the glass and drag: it follows the pointer a little way through a rubber band (small glass
* from where it was pressed, larger glass once the pointer is past its edge), stretches along the
* pull and thins across it, and swings back like gel when let go. The host is moved and scaled
* with CSS `translate` and `scale`, content included. Default `true`; `false` keeps the glass in
* its place. Glass that does not swell (`swell={false}`) is never pulled.
*/
pull?: boolean
/** Fine-tuning: tint colour, a rim line, frost mix, bend, light and shadow (see GlassOptics). */
optics?: GlassOptics
}
/** Size of the hover/press response. Matches the kit's Button. */
const PRESS_SCALE = 1.08
const HOVER_SCALE = 1.04
const HOVER_GROW = 0.08
const MAX_GROW_PX = 6
/** Gap between the separated droplet and the body, as a share of the height. */
const DROPLET_GAP = 0.25
/** A pulse: the glass swells as if hovered and pressed for this long (seconds, unless `pulseHold` says otherwise), then lets go. */
const PULSE = 0.16
/** A droplet melting in: the glass nods once it is this far in (0–1 of the way out). */
const NOD_AT = 0.15
/** Already hovered, its hover swell is at rest: the pulse pushes its width and height instead (per second). */
const PULSE_KICK = { x: 24, y: 20 }
/**
* During a pulse the content stretches with the glass, each way by this much of what the pulse
* adds to the glass's swell that way (`--glass-bend`). It comes in and fades at these rates (per second).
* Held swollen, the content does not stay stretched: it evens out at `even`, and as the glass
* lets go it follows at `back` (per second).
*/
const PULSE_BEND = { amount: 0.5, in: 30, out: 5, even: 4, back: 12 }
/** The CSS the glass relies on. Rendered once per page by <GlassStyles /> (React 19 dedupes it). */
export const GLASS_CSS = `
/* Layered, so a utility class on the host (absolute, fixed) still wins over relative. */
@layer components{:where([data-glass-host]){position:relative;isolation:isolate}}
/* Unlayered on purpose: once the glass draws, it must beat the host's own fill utilities. */
[data-glass-host][data-glass-ready]{background:transparent!important;border-color:transparent!important;box-shadow:none!important;-webkit-backdrop-filter:none!important;backdrop-filter:none!important}
@keyframes glass-marquee{to{transform:translateX(-50%)}}
[data-glass-marquee]{animation:glass-marquee var(--glass-marquee-duration,5s) linear infinite}
/* Swapped labels and icons rise from a soft blur; a check draws itself in. */
@keyframes glass-in{from{opacity:0;filter:blur(3px);transform:translateY(4px)}}
[data-glass-in]{animation:glass-in .38s cubic-bezier(.2,.8,.2,1) both}
@keyframes glass-draw{from{stroke-dashoffset:25}}
[data-glass-draw]{stroke-dasharray:25;animation:glass-draw .42s cubic-bezier(.65,0,.35,1) .12s both}
@keyframes glass-spin{to{transform:rotate(1turn)}}
[data-glass-spin]{animation:glass-spin .8s linear infinite}
[data-glass-ready] [data-glass-fallback]{visibility:hidden}
/* A hidden fallback stops moving too. Its marquee ran on unseen, on the main thread, and made the browser work out the page's layers again on every frame of anything else on the page. */
[data-glass-ready] [data-glass-fallback] [data-glass-marquee]{animation:none}
@media (prefers-reduced-motion:reduce){[data-glass-marquee],[data-glass-in],[data-glass-draw],[data-glass-spin]{animation:none}}
`
/** Injects GLASS_CSS once (React 19 hoists and dedupes `<style href precedence>`). */
export function GlassStyles() {
return (
<style href="liquid-glass" precedence="default">
{GLASS_CSS}
</style>
)
}
export function GlassLayer({
material = 'clear',
droplet = 'none',
tint = 0.6,
blur = 0,
backdrop,
live = false,
trigger,
disabled = false,
swell = true,
pulse,
pulseHold,
pull = true,
optics,
}: GlassLayerProps) {
const canvasRef = useRef<HTMLCanvasElement>(null)
// The droplet mode changes without rebuilding the glass, so the change itself animates.
const dropletRef = useRef(droplet)
dropletRef.current = droplet
// Tint, frost and optics are read on every frame: changing them redraws, never rebuilds.
const tuneRef = useRef({ tint, blur, optics })
tuneRef.current = { tint, blur, optics }
const pokeRef = useRef<(() => void) | null>(null)
useEffect(() => pokeRef.current?.(), [droplet, tint, blur, optics])
// A pulse plays when the value changes, never for the one the glass was mounted with.
const pulseRef = useRef<(() => void) | null>(null)
const pulseHoldRef = useRef(pulseHold)
pulseHoldRef.current = pulseHold
// The droplet splitting off or melting in: the glass swells once, as under a hover.
const nodRef = useRef<(() => void) | null>(null)
const lastDroplet = useRef(droplet)
useEffect(() => {
const from = lastDroplet.current
lastDroplet.current = droplet
if (from !== droplet && from !== 'none' && droplet !== 'none') nodRef.current?.()
}, [droplet])
const lastPulse = useRef(pulse)
useEffect(() => {
if (Object.is(lastPulse.current, pulse)) return
lastPulse.current = pulse
pulseRef.current?.()
}, [pulse])
useEffect(() => {
const canvas = canvasRef.current
const host = canvas?.parentElement
const ctx = canvas?.getContext('2d')
const engine = disabled ? null : getGlassEngine()
if (!canvas || !host || !ctx || !engine) return
const clear = material === 'clear'
let w = 0
let h = 0
let hasDroplet = false
/** The host's own corner radius in px; null = a pill. */
let corner: number | null = null
let surface: Rgb = [1, 1, 1]
// Colours come from the host's own CSS (rest, hover, selected…) and cross-fade.
let color: [Rgb, Rgb] = [
[1, 1, 1],
[1, 1, 1],
]
let border: [Rgb, Rgb] | null = null
/** Clear glass: opacity of the optional rim line (GlassOptics). */
let borderAlpha = 1
/** Clear glass: the tint ended up dark (optics.dark applies). */
let darkGlass = false
let colorT = 1
let unpaintable = false
let sampled = false
let pressed = false
let hovered = false
let ready = false
const page = {
canvas: document.createElement('canvas'),
ctx: null as CanvasRenderingContext2D | null,
key: '',
at: 0,
stale: true,
/** The surface colour the picture was last filled with. */
fill: '',
// Where the glass and the page were when the picture was taken, and what the walk found:
// elements pinned to the viewport, and whether everything else scrolls as one piece.
size: '',
lx: 0,
ly: 0,
sx: 0,
sy: 0,
pinned: [] as Element[],
rigid: false,
/** The glass this one melted into when the picture was taken (COHESION): left out of it. */
near: undefined as Element[] | undefined,
}
const press: Spring = { x: 0, v: 0 }
const growX: Spring = { x: 0, v: 0 }
const growY: Spring = { x: 0, v: 0 }
const scale: Spring = { x: 1, v: 0 }
const drop: Spring = { x: 0, v: 0 }
/** How much the droplet is on its way in (0–1), eased: the bridge is held flat then (see the lens). */
let closing = 0
// A pulse: seconds of its swell left, and how much the content bends with it (0–1).
let settle = 0
/** A nod: seconds left of a hover's swell alone (the droplet splitting off or melting in). */
let nod = 0
/** A nod asked for while the droplet is still on its way in: it plays once the two are one body. */
let nodDue = false
const playNod = () => {
nodDue = false
// Hovered, the hover swell is at rest already: its springs are pushed instead (a pulse's push).
if (hovered) {
growX.v += PULSE_KICK.x
growY.v += PULSE_KICK.y
} else nod = PULSE
}
let bend = 0
/** The swell the glass is settling at (0–1, eased): the content bends by what is beyond it, so it is even once the glass holds still. */
let bendFrom = 0
let bent = ''
/** What this canvas carries to undo a pull's stretch of the host: its `scale`, and the point it is taken about. */
let unstretched = ''
let unstretchedAt = ''
const setBend = (next: string) => {
if (bent === next) return
bent = next
if (next) host.style.setProperty('--glass-bend', next)
else host.style.removeProperty('--glass-bend')
}
const maxScale = () => 1 + (2 * MAX_GROW_PX) / Math.max(w, 1)
const view: GlassView = {
canvas,
ctx,
dirty: true,
visible: false,
// What this glass is, for the light of a press (see GLOW in engine.ts): one that swells is a
// button and takes the flash of a press; one that holds still (a card) is a surface.
button: swell,
// A button is pulled after the pointer that holds it (PULL); glass that holds still (a card) is not.
pull: pull && swell,
grow: 1,
step: (dt, still) => {
if (still) {
press.x = growX.x = growY.x = press.v = growX.v = growY.v = 0
drop.x = hasDroplet && dropletRef.current === 'apart' ? 1 : 0
drop.v = 0
closing = drop.x ? 0 : 1
bendFrom = hovered ? 1 : 0
settle = nod = bend = 0
nodDue = false
setBend('')
scale.x = 1
view.grow = 1
if (colorT !== 1) view.dirty = true
colorT = 1
return false
}
const greeting = settle > 0
settle = Math.max(0, settle - dt)
const nodding = nod > 0
nod = Math.max(0, nod - dt)
const hov = hovered || greeting || nodding ? 1 : 0
// A pulse swells the glass as a press does, on top of the hover.
// (A pointer that holds the glass to pull it keeps it pressed outside it too.)
const down = pressed || (swell && view.held === true) || greeting
const target = down ? Math.min(PRESS_SCALE, maxScale()) : hov ? Math.min(HOVER_SCALE, maxScale()) : 1
const a = stepSpring(press, down ? 1 : 0, SPRINGS.press, dt)
const b = stepSpring(growX, hov, SPRINGS.hoverX, dt)
const c = stepSpring(growY, hov, SPRINGS.hoverY, dt)
const d = stepSpring(scale, target, SPRINGS.press, dt)
const apart = dropletRef.current === 'apart' && view.visible && !pressed
const e = hasDroplet ? stepSpring(drop, apart ? 1 : 0, apart ? SPRINGS.dropletOut : SPRINGS.dropletIn, dt) : false
closing = clamp(closing + (apart ? -1 : 1) * dt * 12)
if (nodDue && (apart || drop.x < NOD_AT)) playNod()
// The content follows the glass while the pulse lasts, and lets go as it settles.
bend = clamp(bend + ((greeting ? 1 : 0) - bend) * Math.min(1, dt * (greeting ? PULSE_BEND.in : PULSE_BEND.out)))
if (!greeting && bend < 0.004) bend = 0
bendFrom = clamp(bendFrom + (hov - bendFrom) * Math.min(1, dt * (hov > bendFrom ? PULSE_BEND.even : PULSE_BEND.back)))
const by = bend * PULSE_BEND.amount * 2 * HOVER_GROW
setBend(bend ? `${(1 + (by * (growX.x - bendFrom) * h) / Math.max(w, 1)).toFixed(4)} ${(1 + by * (growY.x - bendFrom)).toFixed(4)}` : '')
// The engine writes the host's scale: this, times the stretch of a pull.
view.grow = scale.x
const fading = 1 - colorT > 0.004
colorT = fading ? colorT + (1 - colorT) * Math.min(1, dt * 14) : 1
return a || b || c || d || e || greeting || nodding || nodDue || bend > 0 || fading || (clear && live && view.visible)
},
lens: (refresh) => {
if (refresh) {
w = host.offsetWidth
h = host.offsetHeight
// The glass takes the host's corners (`rounded-lg`); round enough is a pill.
const rounding = getComputedStyle(host).borderTopLeftRadius
const px = rounding.endsWith('%') ? (Math.min(w, h) * parseFloat(rounding)) / 100 : parseFloat(rounding) || 0
corner = px >= Math.min(w, h) / 2 - 0.5 ? null : px
// The droplet: a direct child marked `data-glass-drop`, laid out by its owner at the end.
const had = hasDroplet
hasDroplet = dropletRef.current !== 'none' && [...host.children].some((c) => c.hasAttribute('data-glass-drop'))
// Springs step before shapes are read: one more frame lets the droplet start moving.
if (hasDroplet !== had) engine.wake()
const s = engine.resolveColor(surfaceColorOf(host.parentElement))
surface = [s[0], s[1], s[2]]
if (clear) {
const o = tuneRef.current.optics
const custom = o?.tintColor || getComputedStyle(host).getPropertyValue('--glass-tint').trim()
const luminance = 0.2126 * surface[0] + 0.7152 * surface[1] + 0.0722 * surface[2]
const t = custom ? engine.resolveColor(custom) : null
const tc: Rgb = t ? [t[0], t[1], t[2]] : luminance > 0.5 ? [1, 1, 1] : [0, 0, 0]
// Light or dark glass: lets the host pick a readable text colour (data-[glass-tone=…]:).
const tone = 0.2126 * tc[0] + 0.7152 * tc[1] + 0.0722 * tc[2] > 0.5 ? 'light' : 'dark'
if (host.dataset.glassTone !== tone) host.dataset.glassTone = tone
darkGlass = tone === 'dark'
color = [tc, tc]
// An optional line just inside the rim.
const line = darkGlass ? { ...o, ...o?.dark } : o
const bc = line?.borderColor && (line.borderAlpha ?? 0) > 0 ? engine.resolveColor(line.borderColor) : null
border = bc ? [[bc[0], bc[1], bc[2]], [bc[0], bc[1], bc[2]]] : null
borderAlpha = bc ? clamp((line?.borderAlpha ?? 0) * bc[3]) : 1
colorT = 1
sampled = true
} else {
// Read the host's own fill and border with the glass briefly lifted.
const had = 'glassReady' in host.dataset
const transition = host.style.transition
host.style.transition = 'none'
if (had) delete host.dataset.glassReady
const st = getComputedStyle(host)
const fill = engine.resolveColor(st.backgroundColor)
const bw = st.borderTopStyle === 'solid' ? parseFloat(st.borderTopWidth) || 0 : 0
const bc = engine.resolveColor(st.borderTopColor)
const cannot = st.backgroundImage !== 'none' || (st.borderTopStyle !== 'solid' && st.borderTopStyle !== 'none')
if (had) {
host.dataset.glassReady = ''
void getComputedStyle(host).backgroundColor
}
host.style.transition = transition
const next = mixRgb(surface, [fill[0], fill[1], fill[2]], fill[3])
const nextBorder: Rgb | null = bw > 0 && bc[3] > 0.02 ? mixRgb(next, [bc[0], bc[1], bc[2]], bc[3]) : null
unpaintable = cannot || (fill[3] < 0.02 && !nextBorder)
const now = sampled ? mixRgb(color[0], color[1], colorT) : next
const nowBorder = sampled && border ? mixRgb(border[0], border[1], colorT) : (nextBorder ?? next)
const changed = sampled && (now.some((v, i) => Math.abs(v - next[i]) > 0.004) || !!border !== !!nextBorder)
color = [now, next]
border = nextBorder ? [nowBorder, nextBorder] : null
colorT = changed ? 0 : 1
sampled = true
if (changed) engine.wake()
}
}
if (w < 2 || h < 2) return null
if (unpaintable) {
if (ready) {
ready = false
delete host.dataset.glassReady
}
return null
}
// The host itself is scaled; the glass inside the canvas is divided by that scale.
const p = clamp(press.x, -0.12, 1.15)
const s = Math.max(0.5, scale.x)
const k = lerp(1, Math.min(PRESS_SCALE, maxScale()), p) / s
const grow = (h * HOVER_GROW) / s
const t = hasDroplet ? clamp(drop.x, 0, 1.06) : 0
const pull = h * (1 + DROPLET_GAP) * t
const hy = (h / 2) * k + grow * growY.x
// Swollen, the droplet's end sits a little off the body's. It joins it as the two
// become one, or the end would jump when the droplet goes (the spring's last
// ripple brings it back for a moment).
const dropX = (w / 2 - h / 2) * k + grow * lerp(growX.x - growY.x, growX.x * 0.5, smooth(0, 0.15, t))
// The canvas keeps 8px beside the glass and 10px above it, and more whenever the glass
// swells past that (a push while it is already swollen): its end is never cut off.
const reach = Math.max((w / 2) * k + grow * growX.x, t > 0.001 ? dropX + hy : 0)
// A pull stretches the host. That stretch is undone on this canvas and drawn by the glass
// itself: it stays a pill with round ends, as long and as thin as the pull makes it, and
// bends what really lies behind it (not a picture of it, pulled out of shape with the host).
const px = view.pulled?.sx ?? 1
const py = view.pulled?.sy ?? 1
// Room for the longest a pull can make it, taken once: a canvas that changed size on
// every frame of a pull would be painted from scratch each time.
const most = px === 1 && py === 1 ? 0 : Math.max(w, h) <= PULL.smallUntil ? PULL.smallStretchMax : PULL.stretchMax
// A button also keeps room for its side of a bridge to glass it melts into (COHESION).
const melt = swell ? Math.ceil(cohesionSoftness(h) / 4) + 3 : 0
const padX = Math.max(8, Math.ceil(reach * (1 + most) - w / 2 + 2), melt)
const padTop = Math.max(10, Math.ceil(hy * (1 + most) - h / 2 + 2), melt)
// Below the glass the canvas keeps room for its drop shadow. Glass that casts none (a card:
// its shadow is CSS) needs no more there than above it, and a canvas that much smaller is
// that much less to paint, upload, shade and copy on every frame.
const padBottom = (tuneRef.current.optics?.shadow ?? 1) <= 0 ? padTop : Math.round(h * 0.8 + 4)
const origin = `${padX + w / 2}px ${padTop + h / 2}px`
const undo = px === 1 && py === 1 ? '' : `${(1 / px).toFixed(6)} ${(1 / py).toFixed(6)}`
if (undo !== unstretched || (undo && origin !== unstretchedAt)) {
canvas.style.transformOrigin = unstretchedAt = origin
canvas.style.scale = unstretched = undo
}
const rect = host.getBoundingClientRect()
const pc = clamp(press.x)
const unit = h / DESIGN_HEIGHT
const bevel = lerp(DESIGN_HEIGHT * 0.42, 62, pc)
// Square corners swell with the glass.
const radius = corner === null ? 999 : corner * (hy / (h / 2))
const { tint, blur, optics: o } = tuneRef.current
// The engine scales the shadow with the light too; divide it back out, so they tune apart.
const strength = Math.max(clamp(o?.light ?? 1, 0, 3), 1e-4)
// The gooey bridge opens as the droplet leaves and closes once it has snapped.
const bridge = h * 0.34 * py * smooth(0, 0.15, t) * (1 - smooth(0.8, 1, t))
// On its way in, the droplet ends up inside the body's end, and a bridge that soft would
// swell that end past the body (it grew, then shrank as the droplet went). There the
// bridge only fills the dip between the two: the end stays as tall as the rest.
const dip = Math.hypot(hy * py, (pull * k * px) / 2) - hy * py
return {
// The canvas is placed against the padding box; the glass is measured on the border box.
left: -padX - host.clientLeft,
top: -padTop - host.clientTop,
width: w + 2 * padX,
height: h + padTop + padBottom,
unit,
cx: padX + w / 2,
cy: padTop + h / 2,
hx: ((w / 2 - pull / 2) * k + grow * growX.x) * px,
hy: hy * py,
radius,
bodyX: (-pull / 2) * k * px,
droplet:
t > 0.001
? {
x: dropX * px,
r: hy * py,
k: lerp(bridge, Math.min(bridge, 4 * dip), closing),
}
: undefined,
// Shading bands deeper than a square corner would meet in diagonal seams: the bevel
// stays within the corner, and the bend keeps the depth it has on a pill.
bevel: (corner === null ? bevel : Math.min(bevel, (radius / unit) * 1.2)) * Math.max(0.05, o?.bevel ?? 1),
band: corner === null || hasDroplet ? undefined : bevel * 0.35 * Math.max(0.05, o?.bendDepth ?? 1),
shadow: (0.12 * lerp(0.55, 1, pc) * Math.max(0, o?.shadow ?? 1)) / strength,
shadowSoftness: 34 * lerp(0.6, 1, pc) * Math.max(0.05, o?.shadowSoftness ?? 1),
shadowOffset: 22 * lerp(0.5, 1, pc) * Math.max(0, o?.shadowOffset ?? 1),
strength,
tune: o && {
rim: o.rim,
rimWidth: o.rimWidth,
fresnel: o.fresnel,
inner: o.inner,
reflection: o.reflection,
caustic: o.caustic,
mirror: o.mirror,
bendCurve: o.bendCurve,
bendDepth: o.bendDepth,
saturation: o.saturation,
frostEdge: o.frostEdge,
},
color: mixRgb(color[0], color[1], colorT),
border: border ? mixRgb(border[0], border[1], colorT) : undefined,
borderAlpha: clear ? borderAlpha : undefined,
borderWidth: clear ? o?.borderWidth : undefined,
surface,
edgeClear: 0.2,
cursorLight: o?.cursorLight ?? true,
pointerLight: true,
// What the rim of clear glass mirrors: the page around it. Tinted glass mirrors nothing.
reflection: !clear ? undefined : {
height: h,
live,
paint: (around, reach) => {
const r = host.getBoundingClientRect()
const box = { left: r.left + (r.width - w) / 2 - padX, top: r.top + (r.height - h) / 2 - padTop, width: w + 2 * padX, height: h + padTop + padBottom }
drawAround(around, (backdrop ? host.closest(backdrop) : null) ?? document.body, box, reach, {
skip: (el) => el === host || el.hasAttribute('data-glass-skip'),
onStale: dirty,
})
},
},
refraction: clear
? {
paint: (back) => {
back.translate(padX, padTop)
const fill = rgbCss(surface)
const recoloured = fill !== page.fill
page.fill = fill
back.fillStyle = fill
back.fillRect(-padX, -padTop, w + 2 * padX, h + padTop + padBottom)
const root = (backdrop ? host.closest(backdrop) : null) ?? document.body
const r = host.getBoundingClientRect()
const lx = r.left + (r.width - w) / 2
const ly = r.top + (r.height - h) / 2
const target = back.canvas
const key = `${target.width}:${target.height}:${Math.round(lx * 2)}:${Math.round(ly * 2)}:${Math.round(scrollX)}:${Math.round(scrollY)}`
const now = performance.now()
if (!page.ctx) page.ctx = page.canvas.getContext('2d')
const region = { left: lx - padX, top: ly - padTop, right: lx + w + padX, bottom: ly + h + padBottom }
// Scrolling with the page, the glass keeps the same page behind it: the picture it has
// is still right. Not when something in it moves by itself, or is pinned to the
// viewport (a sticky header) and touches the glass, now or when it was painted.
const rides =
!live &&
page.rigid &&
page.size === `${target.width}:${target.height}` &&
Math.abs(lx - page.lx + scrollX - page.sx) < 0.05 &&
Math.abs(ly - page.ly + scrollY - page.sy) < 0.05 &&
!page.pinned.some((el) => {
const b = el.getBoundingClientRect()
return b.width > 0 && b.height > 0 && b.right > region.left && b.left < region.right && b.bottom > region.top && b.top < region.bottom
})
// Glass this one melts into (COHESION) is the same body now: the picture leaves it out.
if (page.near !== view.near) {
page.near = view.near
page.stale = true
}
// The page is re-painted when the glass moves over it, and at most every 120 ms otherwise.
// `live` reads it again every frame at 60 Hz, and every second or third frame on a faster display.
const again = !!page.ctx && (page.stale || (key !== page.key && !rides) || now - page.at > (live ? 12 : 120))
if (page.ctx && again) {
page.stale = false
page.key = key
page.at = now
page.size = `${target.width}:${target.height}`
page.lx = lx
page.ly = ly
page.sx = scrollX
page.sy = scrollY
if (page.canvas.width !== target.width || page.canvas.height !== target.height) {
page.canvas.width = target.width
page.canvas.height = target.height
}
const pc2 = page.ctx
pc2.setTransform(1, 0, 0, 1, 0, 0)
pc2.clearRect(0, 0, target.width, target.height)
pc2.setTransform(back.getTransform())
const found = { pinned: [] as Element[], touched: false, loose: false }
drawDom(pc2, root, {
origin: { left: lx, top: ly },
region,
skip: (el) => el === host || el.hasAttribute('data-glass-skip') || !!view.near?.includes(el),
onStale: () => {
page.stale = true
view.dirty = true
engine.wake()
},
found,
})
page.pinned = found.pinned
page.rigid = !found.loose && !found.touched
}
back.save()
back.setTransform(1, 0, 0, 1, 0, 0)
back.drawImage(page.canvas, 0, 0)
back.restore()
// The same picture of the page as last time: the engine keeps its texture.
return again || recoloured
},
refract: lerp(44, 37, pc) * Math.max(0, o?.refraction ?? 1),
magnify: Math.max(0, o?.magnify ?? 0),
dispersion: Math.max(0, o?.dispersion ?? 0.12),
blurCenter: Math.max(0, o?.clearBlur ?? 0.35),
blurEdge: Math.max(0, o?.clearBlurEdge ?? 2.2),
frost: clamp(darkGlass ? (o?.dark?.tint ?? tint) : tint),
blur,
blurMix: o?.frostMix,
radial: o?.bendMode === 'radial' ? 0.065 * Math.max(0, o?.refraction ?? 1) : undefined,
}
: undefined,
screenX: rect.left + rect.width / 2,
screenY: rect.top + rect.height / 2,
// The host's scale on screen (its own and its ancestors'), without a pull's stretch, which the canvas undoes.
scale: rect.width / Math.max(w * px, 1e-3),
}
},
drawn: () => {
if (ready) return
ready = true
host.dataset.glassReady = ''
},
lost: () => {
delete host.dataset.glassReady
view.grow = 1
},
}
const isDisabled = () => host.matches(":disabled, [aria-disabled='true']")
const dirty = () => {
view.dirty = true
engine.wake()
}
pokeRef.current = dirty
// The nod: a hover's swell alone, for PULSE seconds. A droplet melting in swells once it is
// in: pushed while it is still out, its end would stick out past the body's.
nodRef.current = () => {
if (!swell || host.matches(':disabled')) return
if (hasDroplet && dropletRef.current === 'merged' && drop.x >= NOD_AT) nodDue = true
else playNod()
dirty()
}
// The pulse (see `pulse`): the glass swells as under a hover and a press at once, and lets
// go. Hovered, its hover swell is at rest already: those springs are pushed, so it wobbles.
pulseRef.current = () => {
if (!swell || host.matches(':disabled')) return
if (hovered) {
growX.v += PULSE_KICK.x
growY.v += PULSE_KICK.y
}
settle = Math.max(0, pulseHoldRef.current ?? PULSE)
dirty()
}
const onDown = () => {
if (!swell || isDisabled()) return
pressed = true
engine.wake()
}
const onUp = () => {
pressed = false
engine.wake()
}
const onEnter = (e: PointerEvent) => {
if (!swell || e.pointerType !== 'mouse' || isDisabled()) return
hovered = true
dirty()
}
const onLeave = () => {
pressed = false
hovered = false
dirty()
}
const target: HTMLElement = (trigger ? host.closest<HTMLElement>(trigger) : null) ?? host
if (target !== host) view.pressArea = target
target.addEventListener('pointerdown', onDown)
target.addEventListener('pointerup', onUp)
target.addEventListener('pointercancel', onUp)
target.addEventListener('pointerenter', onEnter)
target.addEventListener('pointerleave', onLeave)
const io = new IntersectionObserver(([entry]) => {
view.visible = entry.isIntersecting
dirty()
})
io.observe(host)
const ro = new ResizeObserver(dirty)
ro.observe(host)
// Content changes (label, selected state) re-check the droplet and colours.
const mo = new MutationObserver(dirty)
mo.observe(host, {
childList: true,
attributes: true,
attributeFilter: ['class', 'disabled', 'aria-pressed', 'aria-checked', 'aria-selected', 'aria-expanded', 'data-state'],
})
// A scroll changes what lies behind, never the glass: sizes and colours are not read again.
const onScroll = () => {
view.repaint = true
engine.wake()
}
if (clear) addEventListener('scroll', onScroll, { passive: true, capture: true })
engine.add(view)
return () => {
engine.remove(view)
ctx.clearRect(0, 0, canvas.width, canvas.height)
io.disconnect()
ro.disconnect()
mo.disconnect()
removeEventListener('scroll', onScroll, { capture: true })
target.removeEventListener('pointerdown', onDown)
target.removeEventListener('pointerup', onUp)
target.removeEventListener('pointercancel', onUp)
target.removeEventListener('pointerenter', onEnter)
target.removeEventListener('pointerleave', onLeave)
delete host.dataset.glassReady
delete host.dataset.glassTone
host.style.removeProperty('--glass-bend')
canvas.style.scale = ''
pokeRef.current = null
pulseRef.current = null
nodRef.current = null
}
}, [material, backdrop, live, trigger, disabled, swell, pull])
return (
<>
<GlassStyles />
<canvas
ref={canvasRef}
aria-hidden
style={{ position: 'absolute', zIndex: -1, maxWidth: 'none', pointerEvents: 'none', width: 0, height: 0 }}
/>
</>
)
}
export default GlassLayer

View File

@@ -0,0 +1,472 @@
'use client'
// GlassLens — the sliding glass lens of a segmented control / tab bar. Bring your own
// options (Radix Tabs, a radiogroup, anything) and put the lens first in the container:
//
// <div role="radiogroup" data-glass-host className="relative isolate …">
// <GlassLens value={value} />
// {options.map(o => (
// <button role="radio" aria-checked={o === value} …>
// {o === value && <span data-glass-highlight className="absolute inset-0 rounded-full bg-white" />}
// <span className="relative z-20">{o}</span>
// </button>
// ))}
// </div>
//
// Contract: options carry role="radio" or role="tab"; the selected option contains the
// flat highlight element marked `data-glass-highlight`. Its background colour is the
// lens colour and its corners are the lens's corners: `rounded-full` travels as a pill,
// `rounded-lg` as a rounded rectangle, and the corners grow with the lens as it swells.
// When the selection changes the lens leaves the old highlight, swells into clear glass
// that bends and magnifies the options it passes, then settles into the flat highlight
// again. Press and hold opens the lens in place; drag it and release to select. While
// the lens is visible the container carries:
// data-glass-moving — hide the flat highlight: [[data-glass-moving]_&]:opacity-0
// data-glass-traveling — paint the selected label as unselected, so it reads under clear glass
// Without WebGL2 or with reduced motion the highlight simply jumps. COPY VERBATIM. MIT.
import { useEffect, useRef } from 'react'
import { drawAround } from './dom-snapshot'
import { GlassStyles } from './glass-layer'
import { SPRINGS, clamp, getGlassEngine, lerp, stepSpring, surfaceColorOf, type GlassView, type Rgb, type Spring } from './engine'
/** One option is designed 80 units tall; the optics are scaled to the slider's 120-unit lens. */
const OPTION_UNITS = 80
const OPTICS = (OPTION_UNITS * 1.35) / 120
/** The lens swells while it travels: width +12 %, height +35 %. */
const TRAVEL_W = 0.12
const TRAVEL_H = 0.35
/** An option's centre and size; `r` = its corner radius in px, null for a pill. */
type Box = { x: number; y: number; w: number; h: number; r: number | null }
/** The corner radius of `el` in px (`rounded-lg`, `50%`) on a w × h box. */
function cornerOf(el: Element, w: number, h: number) {
const v = getComputedStyle(el).borderTopLeftRadius
return v.endsWith('%') ? (Math.min(w, h) * parseFloat(v)) / 100 : parseFloat(v) || 0
}
const svgCache = new WeakMap<Element, Map<string, HTMLImageElement>>()
function drawSvg(ctx: CanvasRenderingContext2D, el: SVGSVGElement, color: string, x: number, y: number, w: number, h: number, redraw: () => void) {
let byColor = svgCache.get(el)
if (!byColor) svgCache.set(el, (byColor = new Map()))
let img = byColor.get(color)
if (!img) {
const clone = el.cloneNode(true) as SVGSVGElement
clone.removeAttribute('class')
clone.setAttribute('xmlns', 'http://www.w3.org/2000/svg')
clone.setAttribute('width', String(w))
clone.setAttribute('height', String(h))
clone.style.color = color
img = new Image()
img.onload = redraw
img.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(new XMLSerializer().serializeToString(clone))}`
byColor.set(color, img)
}
if (img.complete && img.naturalWidth) ctx.drawImage(img, x, y, w, h)
}
const visible = (c: string) => !!c && c !== 'transparent' && !/rgba\(.*,\s*0\)$/.test(c) && !/\/\s*0\)$/.test(c)
/** Paints the container into `back` (everything beneath the lens) and the labels into `front` in the selected colour. */
function paintOptions(back: CanvasRenderingContext2D, front: CanvasRenderingContext2D, root: HTMLElement, selectedColor: string, redraw: () => void) {
const o = root.getBoundingClientRect()
let lang: string | undefined
try {
lang = Intl.getCanonicalLocales(document.documentElement.lang)[0]
} catch {
// Not a language tag: the default locale's rules apply.
}
const walk = (el: Element) => {
if (el instanceof HTMLCanvasElement || el.hasAttribute('data-glass-highlight')) return
const st = getComputedStyle(el)
if (st.display === 'none' || st.visibility === 'hidden') return
const r = el.getBoundingClientRect()
const x = r.left - o.left
const y = r.top - o.top
if (el instanceof SVGSVGElement) {
if (r.width < 1 || r.height < 1) return
drawSvg(back, el, st.color, x, y, r.width, r.height, redraw)
drawSvg(front, el, selectedColor, x, y, r.width, r.height, redraw)
return
}
if (st.display !== 'contents' && r.width > 1 && r.height > 1) {
const radius = Math.min(parseFloat(st.borderTopLeftRadius) || 0, r.width / 2, r.height / 2)
if (visible(st.backgroundColor)) {
back.beginPath()
back.roundRect(x, y, r.width, r.height, radius)
back.fillStyle = st.backgroundColor
back.fill()
}
const bw = parseFloat(st.borderTopWidth) || 0
if (bw > 0 && st.borderTopStyle !== 'none' && visible(st.borderTopColor)) {
back.beginPath()
back.roundRect(x + bw / 2, y + bw / 2, r.width - bw, r.height - bw, Math.max(0, radius - bw / 2))
back.lineWidth = bw
back.strokeStyle = st.borderTopColor
back.stroke()
}
}
for (const n of el.childNodes) {
if (n instanceof Element) walk(n)
else if (n.nodeType === Node.TEXT_NODE && n.textContent?.trim()) {
const range = document.createRange()
range.selectNodeContents(n)
const m = range.getBoundingClientRect()
if (m.width < 1) continue
// Labels are drawn as the page shows them (`uppercase` tabs).
const raw = n.textContent.trim()
const text = st.textTransform === 'uppercase' ? raw.toLocaleUpperCase(lang) : st.textTransform === 'lowercase' ? raw.toLocaleLowerCase(lang) : raw
for (const [ctx, color] of [
[back, st.color],
[front, selectedColor],
] as const) {
ctx.font = `${st.fontStyle} ${st.fontWeight} ${st.fontSize} ${st.fontFamily}`
ctx.letterSpacing = st.letterSpacing === 'normal' ? '0px' : st.letterSpacing
ctx.textAlign = 'left'
ctx.textBaseline = 'alphabetic'
const mt = ctx.measureText(text)
ctx.fillStyle = color
ctx.fillText(text, m.left - o.left, m.top - o.top + (m.height - mt.fontBoundingBoxAscent - mt.fontBoundingBoxDescent) / 2 + mt.fontBoundingBoxAscent)
}
}
}
}
walk(root)
}
export type GlassLensProps = {
/** The selected value (any change slides the lens). `null` = nothing selected. */
value: string | number | null
disabled?: boolean
}
export function GlassLens({ value, disabled = false }: GlassLensProps) {
const canvasRef = useRef<HTMLCanvasElement>(null)
const syncRef = useRef<((slide: boolean) => void) | null>(null)
useEffect(() => {
const canvas = canvasRef.current
const root = canvas?.parentElement
const ctx = canvas?.getContext('2d')
const engine = disabled ? null : getGlassEngine()
if (!canvas || !root || !ctx || !engine) return
const reduced = window.matchMedia('(prefers-reduced-motion: reduce)')
let target: Box | null = null
let active = false
let pressed = false
let dragX: number | null = null
let color: Rgb = [0, 0, 0]
let surface: Rgb = [1, 1, 1]
let selectedColor = 'white'
const mx: Spring = { x: 0, v: 0 }
const my: Spring = { x: 0, v: 0 }
const mw: Spring = { x: 0, v: 0 }
const mh: Spring = { x: 0, v: 0 }
/** Corner radius (px) of a rounded-rectangle lens; it travels with the size. */
const mr: Spring = { x: 0, v: 0 }
const press: Spring = { x: 0, v: 0 }
const place = (b: Box) => {
mx.x = b.x
my.x = b.y
mw.x = b.w
mh.x = b.h
mr.x = b.r ?? Math.min(b.w, b.h) / 2
mx.v = my.v = mw.v = mh.v = mr.v = 0
}
const options = () =>
[...root.querySelectorAll<HTMLElement>('[role="radio"], [role="tab"]')].map((el) => {
const a = root.getBoundingClientRect()
const b = el.getBoundingClientRect()
return { el, x: b.left - a.left + b.width / 2, y: b.top - a.top + b.height / 2, w: b.width, h: b.height }
})
const nearest = (x: number, y: number) => {
let best: ReturnType<typeof options>[number] | null = null
let d = Infinity
for (const o of options()) {
const dd = Math.abs(o.x - x) + Math.abs(o.y - y) * 4
if (dd < d) {
d = dd
best = o
}
}
return best
}
const stop = () => {
active = false
press.x = press.v = 0
if (target) place(target)
delete root.dataset.glassMoving
delete root.dataset.glassTraveling
view.dirty = true
setTimeout(() => {
const el = root.querySelector('[data-glass-highlight]')?.parentElement
if (!active && el) selectedColor = getComputedStyle(el).color
}, 400)
}
const start = () => {
if (active || !target) return
place(target)
active = true
}
const view: GlassView = {
canvas,
ctx,
dirty: false,
visible: false,
step: (dt, still) => {
if (!active || !target) return false
if (still) {
stop()
return false
}
let goal: Box = target
if (dragX !== null) {
const all = options()
const near = nearest(dragX, my.x)
if (near && all.length) {
const xs = all.map((o) => o.x)
goal = { x: clamp(dragX, Math.min(...xs), Math.max(...xs)), y: near.y, w: near.w, h: near.h, r: target.r }
}
}
const spring = dragX !== null ? SPRINGS.drag : SPRINGS.slide
const a = stepSpring(mx, goal.x, spring, dt)
const b = stepSpring(my, goal.y, spring, dt)
const c = stepSpring(mw, goal.w, spring, dt)
const d = stepSpring(mh, goal.h, spring, dt)
const f = goal.r !== null && stepSpring(mr, goal.r, spring, dt)
// The lens stays clear until it is within 6 % of an option's width from its target.
const traveling = dragX === null && Math.hypot(mx.x - goal.x, my.x - goal.y) > target.w * 0.06
const open = pressed || traveling
if (!open) delete root.dataset.glassTraveling
else if ('glassMoving' in root.dataset) root.dataset.glassTraveling = ''
const e = stepSpring(press, open ? 1 : 0, SPRINGS.press, dt)
const moving = a || b || c || d || e || f
if (!moving && !pressed) stop()
return moving
},
lens: () => {
if (!active || !target) return null
const p = clamp(press.x, -0.12, 1.15)
const pc = clamp(press.x)
const frost = 1 - pc
const padX = 16
// Room for the larger of the lens and its target: it may travel between sizes.
const tall = Math.max(target.h, mh.x)
const padTop = Math.round(tall * 0.3 + 6)
const padBottom = Math.round(tall * 1.1 + 8)
const box = root.getBoundingClientRect()
// The optics follow the lens's own height, so they scale as it changes size.
const unit = mh.x / OPTION_UNITS
const swell = 1 + TRAVEL_H * p
const hx = (mw.x / 2) * (1 + TRAVEL_W * p)
const hy = (mh.x / 2) * swell
const bevel = lerp(OPTION_UNITS * 0.42, 62 * OPTICS, pc)
const pill = target.r === null
// The highlight's corners, growing with the glass; a pill stays a pill.
const radius = pill ? 999 : Math.min(mr.x * swell, hx, hy)
return {
left: -padX,
top: -padTop,
width: root.offsetWidth + 2 * padX,
height: root.offsetHeight + padTop + padBottom,
unit,
cx: padX + mx.x,
cy: padTop + my.x,
hx,
hy,
radius,
bodyX: 0,
// Shading deeper than a square corner would meet in diagonal seams: the bevel stays
// within the corner, and the bend keeps the depth it has on a pill.
bevel: pill ? bevel : Math.min(bevel, (radius / unit) * 1.2),
band: pill ? undefined : bevel * 0.35,
shadow: 0.12 * lerp(0.55, 1, pc),
shadowSoftness: 34 * OPTICS * lerp(0.6, 1, pc),
shadowOffset: 22 * OPTICS * lerp(0.5, 1, pc),
strength: pc,
color,
surface,
edgeClear: 0,
refraction: {
paint: (back, front) => {
back.translate(padX, padTop)
front.translate(padX, padTop)
paintOptions(back, front, root, selectedColor, () => {
view.dirty = true
engine.wake()
})
},
refract: lerp(6, 37, pc) * OPTICS * lerp(0.06, 1, pc),
magnify: 0.12 * pc,
dispersion: 0.12 * pc,
blurCenter: lerp(0.35, 4, frost),
blurEdge: lerp(2.2, 4, frost),
frost,
},
cursorLight: true,
pointerLight: true,
// What the lens's rim mirrors while it travels (clear): the page around the options.
reflection: {
height: tall,
paint: (around, reach) => {
drawAround(around, document.body, { left: box.left - padX, top: box.top - padTop, width: root.offsetWidth + 2 * padX, height: root.offsetHeight + padTop + padBottom }, reach, {
skip: (el) => el === canvas || el.hasAttribute('data-glass-skip'),
onStale: () => {
view.dirty = true
engine.wake()
},
})
},
},
screenX: box.left + mx.x,
screenY: box.top + my.x,
}
},
// The flat highlight hides only once the lens has drawn its first frame.
drawn: () => {
if (!active || 'glassMoving' in root.dataset) return
root.dataset.glassMoving = ''
root.dataset.glassTraveling = ''
},
lost: () => {
pressed = false
dragX = null
stop()
},
}
const measure = (): Box | null => {
const hl = root.querySelector<HTMLElement>('[data-glass-highlight]')
const el = hl?.parentElement
if (!hl || !el) return null
const a = root.getBoundingClientRect()
const b = el.getBoundingClientRect()
if (b.width < 2 || b.height < 2) return null
const c = engine.resolveColor(getComputedStyle(hl).backgroundColor)
color = [c[0], c[1], c[2]]
const s = engine.resolveColor(surfaceColorOf(root.parentElement))
surface = [s[0], s[1], s[2]]
const st = getComputedStyle(el)
if (!active) selectedColor = st.color
// The corners the highlight shows: its own, or its option's when the option clips it.
let r = cornerOf(hl, b.width, b.height)
if (st.overflowX !== 'visible' || st.overflowY !== 'visible') r = Math.max(r, cornerOf(el, b.width, b.height))
const w = b.width
const h = b.height
return { x: b.left - a.left + w / 2, y: b.top - a.top + h / 2, w, h, r: r >= Math.min(w, h) / 2 - 0.5 ? null : r }
}
const sync = (slide: boolean) => {
const keepColor = selectedColor
const old = target
const next = measure()
const same =
!!next &&
!!old &&
Math.abs(next.x - old.x) < 0.5 &&
Math.abs(next.y - old.y) < 0.5 &&
Math.abs(next.w - old.w) < 0.5 &&
Math.abs(next.h - old.h) < 0.5 &&
next.r === old.r
if (same) return
if (!slide || !next || !old || !view.visible || reduced.matches) {
target = next
if (active && !pressed) stop()
return
}
selectedColor = keepColor
start()
target = next
engine.wake()
}
syncRef.current = sync
sync(false)
// Press, drag, release. The pointer is not captured: a tap still clicks the option.
let downX = 0
let moved = false
const localX = (e: PointerEvent) => e.clientX - root.getBoundingClientRect().left
const onMove = (e: PointerEvent) => {
const x = localX(e)
if (!moved && Math.abs(x - downX) < 4) return
moved = true
dragX = x
engine.wake()
}
const onUp = (e: PointerEvent) => {
removeEventListener('pointermove', onMove)
removeEventListener('pointerup', onUp)
removeEventListener('pointercancel', onUp)
pressed = false
if (moved && dragX !== null && e.type === 'pointerup') {
const near = nearest(dragX, my.x)
if (near && !near.el.querySelector('[data-glass-highlight]')) {
near.el.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, cancelable: true, button: 0 }))
near.el.click()
}
}
dragX = null
engine.wake()
}
const onDown = (e: PointerEvent) => {
if (e.button !== 0 || reduced.matches || !target || !view.visible) return
if (!(e.target instanceof Element) || !e.target.closest('[role="radio"], [role="tab"]')) return
pressed = true
moved = false
downX = localX(e)
start()
addEventListener('pointermove', onMove)
addEventListener('pointerup', onUp)
addEventListener('pointercancel', onUp)
engine.wake()
}
root.addEventListener('pointerdown', onDown)
const touchAction = root.style.touchAction
root.style.touchAction = 'pan-y'
const io = new IntersectionObserver(([entry]) => {
view.visible = entry.isIntersecting
})
io.observe(root)
const ro = new ResizeObserver(() => {
if (!active) sync(false)
})
ro.observe(root)
engine.add(view)
return () => {
engine.remove(view)
ctx.clearRect(0, 0, canvas.width, canvas.height)
io.disconnect()
ro.disconnect()
root.removeEventListener('pointerdown', onDown)
removeEventListener('pointermove', onMove)
removeEventListener('pointerup', onUp)
removeEventListener('pointercancel', onUp)
root.style.touchAction = touchAction
syncRef.current = null
delete root.dataset.glassMoving
delete root.dataset.glassTraveling
}
}, [disabled])
useEffect(() => {
syncRef.current?.(true)
}, [value])
return (
<>
<GlassStyles />
<canvas
ref={canvasRef}
aria-hidden
style={{ position: 'absolute', zIndex: 30, maxWidth: 'none', pointerEvents: 'none', width: 0, height: 0 }}
/>
</>
)
}
export default GlassLens

View File

@@ -132,7 +132,7 @@ export function MobilMenu({
: "Menü"
}
data-ucus-hedefi="mobil"
className={cn(SIVI_KAP, "kt-dokunma relative flex size-9 shrink-0 cursor-pointer items-center justify-center rounded-full border border-slate-200 bg-card text-slate-900 outline-none transition-[background-color,transform] duration-150 hover:bg-slate-100 focus-visible:ring-3 focus-visible:ring-ring/50 active:scale-[0.96] data-cam:active:scale-100 motion-reduce:transition-none sm:size-12")}
className={cn(SIVI_KAP, "kt-dokunma relative flex size-9 shrink-0 cursor-pointer items-center justify-center rounded-full border border-slate-200 bg-card text-slate-900 outline-none transition-[background-color,transform] duration-150 hover:bg-slate-100 focus-visible:ring-3 focus-visible:ring-ring/50 active:scale-[0.96] data-glass-ready:active:scale-100 motion-reduce:transition-none sm:size-12")}
>
<SiviCam />
<MenuCizgileri acik={false} />
@@ -210,7 +210,7 @@ export function MobilMenu({
<button
type="button"
aria-label="Menüyü kapat"
className={cn(SIVI_KAP, "kt-dokunma pointer-events-auto relative flex size-9 cursor-pointer items-center justify-center rounded-full border border-slate-200 bg-card text-slate-900 outline-none transition-[background-color,transform] duration-150 hover:bg-slate-100 focus-visible:ring-3 focus-visible:ring-ring/50 active:scale-[0.96] data-cam:active:scale-100 motion-reduce:transition-none sm:size-12")}
className={cn(SIVI_KAP, "kt-dokunma pointer-events-auto relative flex size-9 cursor-pointer items-center justify-center rounded-full border border-slate-200 bg-card text-slate-900 outline-none transition-[background-color,transform] duration-150 hover:bg-slate-100 focus-visible:ring-3 focus-visible:ring-ring/50 active:scale-[0.96] data-glass-ready:active:scale-100 motion-reduce:transition-none sm:size-12")}
>
<SiviCam />
<MenuCizgileri acik />

File diff suppressed because it is too large Load Diff

View File

@@ -8,4 +8,4 @@
* ve kap kendi zeminini bırakmaz (cam altta kalır, yalnız üstüne gelince
* seçilir). Sunucu bileşenleri (`user-nav.tsx`, `button.tsx`) buradan alır.
*/
export const SIVI_KAP = "relative isolate data-cam:border-transparent! data-cam:bg-transparent! data-cam:shadow-none!";
export const SIVI_KAP = "relative isolate data-glass-ready:border-transparent! data-glass-ready:bg-transparent! data-glass-ready:shadow-none!";

View File

@@ -123,7 +123,7 @@ function AltSayfaKapat({ className, children, ...props }: ComponentProps<typeof
return (
<DialogPrimitive.Close
data-slot="alt-sayfa-kapat"
className={cn(SIVI_KAP, className, "data-cam:active:scale-100")}
className={cn(SIVI_KAP, className, "data-glass-ready:active:scale-100")}
{...props}
>
<SiviCam />

View File

@@ -606,7 +606,7 @@ function Bildirim({
<button
type="button"
onClick={() => kapat(id)}
className={cn(SIVI_KAP, "flex size-9 shrink-0 cursor-pointer items-center justify-center rounded-full text-slate-500 transition-[background-color,color,transform] duration-150 hover:bg-slate-100 hover:text-slate-800 active:scale-[0.96] data-cam:active:scale-100")}
className={cn(SIVI_KAP, "flex size-9 shrink-0 cursor-pointer items-center justify-center rounded-full text-slate-500 transition-[background-color,color,transform] duration-150 hover:bg-slate-100 hover:text-slate-800 active:scale-[0.96] data-glass-ready:active:scale-100")}
>
<SiviCam />
<X className="size-4" aria-hidden />

View File

@@ -24,7 +24,7 @@ const buttonVariants = cva(
// DESIGN.md §4.1: funnel CTA'sının tek kaynağı. Basma tepkisi ölçekle
// (tabandaki 1 px kayma bu iki varyantta kapalı; ikisi birlikte titrer).
// `cam="cam"` verilirse zemini camdır (§4.50; şu an hiçbir yerde yok):
// `SiviCam` ilk kareyi çizince `data-cam` gelir.
// `SiviCam` ilk kareyi çizince `data-glass-ready` gelir.
cta: "cursor-pointer bg-orange-500 text-white transition-[background-color,transform] duration-200 hover:bg-orange-600 active:not-aria-[haspopup]:translate-y-0 active:scale-[0.97] motion-reduce:active:scale-100",
ikincil:
"cursor-pointer border-border bg-background transition-[background-color,border-color,color,transform] duration-150 hover:border-orange-500 hover:bg-orange-50/60 hover:text-orange-500 active:not-aria-[haspopup]:translate-y-0 active:scale-[0.97] motion-reduce:active:scale-100",
@@ -74,7 +74,7 @@ function Button({
"data-slot": "button",
"data-variant": variant,
"data-size": size,
// Cam kurulunca (`data-cam`) buton kendi zeminini ve kenarlığını bırakır.
// Cam kurulunca (`data-glass-ready`) buton kendi zeminini ve kenarlığını bırakır.
className: cn(sivi && SIVI_KAP, buttonVariants({ variant, size, className })),
}

View File

@@ -75,7 +75,7 @@ function DialogContent({
{showCloseButton && (
<DialogPrimitive.Close
data-slot="dialog-close"
className={cn(SIVI_KAP, "kt-dokunma absolute top-3 right-3 z-10 flex size-9 cursor-pointer items-center justify-center rounded-full border border-slate-200 bg-popover text-slate-500 transition-[background-color,transform] duration-150 hover:bg-slate-100 hover:text-slate-800 active:scale-[0.96] data-cam:active:scale-100")}
className={cn(SIVI_KAP, "kt-dokunma absolute top-3 right-3 z-10 flex size-9 cursor-pointer items-center justify-center rounded-full border border-slate-200 bg-popover text-slate-500 transition-[background-color,transform] duration-150 hover:bg-slate-100 hover:text-slate-800 active:scale-[0.96] data-glass-ready:active:scale-100")}
>
<SiviCam />
<XIcon className="size-4" aria-hidden />

View File

@@ -61,7 +61,7 @@ const NUMARA = cn(
const OK = cn(
HAP,
SIVI_KAP,
"data-cam:active:scale-100",
"data-glass-ready:active:scale-100",
"border border-slate-200 bg-card text-slate-700 transition-[background-color,border-color,color,transform,opacity] duration-150 hover:border-orange-500 hover:bg-orange-50/60 hover:text-orange-500 active:scale-[0.96] aria-disabled:pointer-events-none aria-disabled:opacity-40",
);

View File

@@ -82,14 +82,14 @@ export function SecimHaplari<T extends string>({
className={cn(
"kt-dokunma relative inline-flex cursor-pointer items-center gap-1.5 rounded-full font-semibold outline-none transition-[color,border-color,background-color] duration-200 focus-visible:ring-3 focus-visible:ring-ring/50 select-none",
yukseklik,
// Mercek yoldayken (`data-cam-yolda`) seçili seçenek seçilmemiş gibi
// Mercek yoldayken (`data-glass-traveling`) seçili seçenek seçilmemiş gibi
// boyanır: şeffaf camın altında okunur.
kapsul
? secili
? "text-slate-50 [[data-cam-yolda]_&]:text-slate-600!"
? "text-slate-50 [[data-glass-traveling]_&]:text-slate-600!"
: "text-slate-600 hover:text-orange-500"
: secili
? "border border-transparent text-white [[data-cam-yolda]_&]:border-slate-200! [[data-cam-yolda]_&]:bg-card! [[data-cam-yolda]_&]:text-slate-600!"
? "border border-transparent text-white [[data-glass-traveling]_&]:border-slate-200! [[data-glass-traveling]_&]:bg-card! [[data-glass-traveling]_&]:text-slate-600!"
: "border border-slate-200 bg-card text-slate-600 hover:border-slate-300 hover:bg-slate-50",
)}
>
@@ -99,10 +99,10 @@ export function SecimHaplari<T extends string>({
initial={false}
transition={azalt ? { duration: 0 } : YAY}
className={cn(
"absolute inset-0 rounded-full [[data-cam-geziyor]_&]:opacity-0!",
"absolute inset-0 rounded-full [[data-glass-moving]_&]:opacity-0!",
kapsul ? "bg-slate-900" : "bg-primary",
)}
data-cam-vurgu=""
data-glass-highlight=""
aria-hidden
/>
) : null}

View File

@@ -7,44 +7,38 @@ import { cn } from "@/lib/utils";
* "Yeni ▪ Yeni ▪ …" yazısı (arada küçük turuncu piksel kare) sonsuz şerit gibi akar, cam yazıyı ve arkasındaki
* kart köşesini büker.
*
* Cam ilk karesini çizene dek (ve WebGL2 yoksa) rozet düz hâlindedir: mavi
* dolu hap, içinde CSS ile akan beyaz şerit (`kt-yeni-serit`, globals.css).
* Cam gelince `data-cam` ile zemin ve DOM şeridi bırakılır; yazıyı cam çizer.
* Hareketi azalt açıkken şerit durur, tek ortalı "Yeni" görünür.
* Sıvı cam tercihi kapalıyken rozet düz hâlindedir: mavi dolu hap, içinde CSS
* ile akan beyaz şerit (`kt-yeni-serit`, globals.css). Tercih açıkken rozetin
* tamamı kitin `GlassBadge`'idir (`RozetCami`); yazıyı cam çizer, arkasındaki
* kartı kendisi bulur. Hareketi azalt açıkken şerit durur, tek ortalı "Yeni" görünür.
*
* Tek kaynak budur: başka yerde "yeni" işareti gerekiyorsa bu bileşen
* kullanılır, elle hap yazılmaz. Konumu (kartın köşesi) çağıran verir;
* arkasındaki kart `data-rozet-zemini` taşır ki cam onu görebilsin.
* kullanılır, elle hap yazılmaz. Konumu (kartın köşesi) çağıran verir.
*/
export function YeniRozeti({ className }: { className?: string }) {
return (
<span
className={cn(
"kt-yeni-rozet group/rozet pointer-events-none inline-flex h-[22px] w-16 items-center rounded-full bg-primary text-xs leading-none font-semibold tracking-[-0.01em] text-white ring-4 ring-background data-cam:bg-transparent",
className,
)}
>
<RozetCami metin="Yeni" />
<span className="sr-only">Yeni yazı</span>
<RozetCami metin="Yeni" className={cn("bg-primary! ring-4 ring-background", className)}>
<span
aria-hidden
className="kt-yeni-pencere flex w-full overflow-hidden rounded-full group-data-cam/rozet:invisible"
className={cn(
"kt-yeni-rozet pointer-events-none inline-flex h-[22px] w-16 items-center rounded-full bg-primary text-xs leading-none font-semibold tracking-[-0.01em] text-white ring-4 ring-background",
className,
)}
>
<span className="kt-yeni-serit flex w-max shrink-0 items-center">
{Array.from({ length: 4 }, (_, i) => (
<span key={i} className="flex items-center">
<span className="px-1">Yeni</span>
<span className="size-1 bg-orange-500" />
</span>
))}
<span className="sr-only">Yeni yazı</span>
<span aria-hidden className="kt-yeni-pencere flex w-full overflow-hidden rounded-full">
<span className="kt-yeni-serit flex w-max shrink-0 items-center">
{Array.from({ length: 4 }, (_, i) => (
<span key={i} className="flex items-center">
<span className="px-1">Yeni</span>
<span className="size-1 bg-orange-500" />
</span>
))}
</span>
</span>
<span aria-hidden className="kt-yeni-sabit w-full text-center">
Yeni
</span>
</span>
<span
aria-hidden
className="kt-yeni-sabit w-full text-center group-data-cam/rozet:invisible"
>
Yeni
</span>
</span>
</RozetCami>
);
}

View File

@@ -430,7 +430,7 @@ export function KatalogArama({ rehberler }: { rehberler: RehberAramaKaydi[] }) {
type="button"
onClick={kapat}
aria-label="Aramayı kapat"
className={cn(SIVI_KAP, "kt-dokunma relative flex size-9 cursor-pointer items-center justify-center rounded-full border border-slate-200 text-slate-500 transition-[background-color,transform] duration-150 hover:bg-slate-100 hover:text-slate-800 active:scale-[0.96] data-cam:active:scale-100")}
className={cn(SIVI_KAP, "kt-dokunma relative flex size-9 cursor-pointer items-center justify-center rounded-full border border-slate-200 text-slate-500 transition-[background-color,transform] duration-150 hover:bg-slate-100 hover:text-slate-800 active:scale-[0.96] data-glass-ready:active:scale-100")}
>
<SiviCam />
<X className="size-4" aria-hidden />

View File

@@ -51,8 +51,8 @@ export function GirisLinki({ menu = false }: { /** Telefon menüsündeki iri hap
cam="seffaf"
className={
menu
? "h-14 w-full max-w-xs cursor-pointer rounded-full bg-slate-900 px-8 font-heading text-xl font-bold text-slate-50 data-cam:text-slate-900 transition-[background-color,transform] duration-200 hover:bg-slate-700 active:scale-[0.97]"
: "h-9 cursor-pointer rounded-full bg-slate-900 px-3.5 text-sm font-medium text-slate-50 data-cam:text-slate-900 transition-colors duration-200 hover:bg-slate-700 sm:h-12 sm:px-7 sm:text-base"
? "h-14 w-full max-w-xs cursor-pointer rounded-full bg-slate-900 px-8 font-heading text-xl font-bold text-slate-50 data-glass-ready:text-slate-900 transition-[background-color,transform] duration-200 hover:bg-slate-700 active:scale-[0.97]"
: "h-9 cursor-pointer rounded-full bg-slate-900 px-3.5 text-sm font-medium text-slate-50 data-glass-ready:text-slate-900 transition-colors duration-200 hover:bg-slate-700 sm:h-12 sm:px-7 sm:text-base"
}
>
<Link href={href} rel="nofollow">

View File

@@ -40,7 +40,7 @@ function YapayZekaListemDugmesi() {
href="/listem"
aria-label="Yapay Zekâ Listem"
title="Yapay zekânın kurduğu 24 tercihlik listen"
className={cn(SIVI_KAP, "kt-dokunma relative inline-flex size-9 shrink-0 items-center justify-center rounded-full border border-slate-300 bg-slate-100 transition-[background-color,border-color,transform] duration-150 hover:border-slate-400 hover:bg-slate-200 active:scale-[0.96] data-cam:active:scale-100 sm:size-12")}
className={cn(SIVI_KAP, "kt-dokunma relative inline-flex size-9 shrink-0 items-center justify-center rounded-full border border-slate-300 bg-slate-100 transition-[background-color,border-color,transform] duration-150 hover:border-slate-400 hover:bg-slate-200 active:scale-[0.96] data-glass-ready:active:scale-100 sm:size-12")}
>
{/* Yuvarlak cam damla; camsı görünüm kapalıyken de camdır (`hep`,
DESIGN.md §4.50). İkon yerine Piksel: ifadeleri ve el hareketlerini

View File

@@ -167,7 +167,7 @@ export function ListeCekmecesi() {
)
}
title="Listeyi temizle"
className={cn(SIVI_KAP, "absolute top-3 left-3 z-10 flex size-9 cursor-pointer items-center justify-center rounded-full border border-slate-200 bg-popover text-slate-500 transition-[background-color,transform] duration-150 hover:bg-slate-100 hover:text-slate-800 active:scale-[0.96] data-cam:active:scale-100")}
className={cn(SIVI_KAP, "absolute top-3 left-3 z-10 flex size-9 cursor-pointer items-center justify-center rounded-full border border-slate-200 bg-popover text-slate-500 transition-[background-color,transform] duration-150 hover:bg-slate-100 hover:text-slate-800 active:scale-[0.96] data-glass-ready:active:scale-100")}
>
<SiviCam />
<Trash2 className="size-4" aria-hidden />
@@ -487,7 +487,7 @@ function CekmeceSatiri({
// da vardır ("+" düğmesiyle aynı, `program-ekle-butonu.tsx`): sıvı cam
// (§4.50) zemini olmayan düğmeye kurulmaz, yalnız üstüne gelince
// beliriyordu (Bilal, 12 Kas 2026: "hep olmalı").
className={cn(SIVI_KAP, "mr-1 inline-flex size-11 shrink-0 cursor-pointer items-center justify-center rounded-full border border-slate-200 bg-card text-slate-500 transition-[background-color,border-color,color,transform] duration-150 hover:border-orange-500 hover:bg-orange-50/60 hover:text-orange-500 active:scale-[0.92] data-cam:active:scale-100")}
className={cn(SIVI_KAP, "mr-1 inline-flex size-11 shrink-0 cursor-pointer items-center justify-center rounded-full border border-slate-200 bg-card text-slate-500 transition-[background-color,border-color,color,transform] duration-150 hover:border-orange-500 hover:bg-orange-50/60 hover:text-orange-500 active:scale-[0.92] data-glass-ready:active:scale-100")}
>
<SiviCam />
<CircleMinus className="size-5" aria-hidden />

View File

@@ -186,7 +186,7 @@ export function ProgramEkleButonu({
buttonVariants({ variant: "ikincil", size: "lg" }),
SIVI_KAP,
// Basınca büyümeyi cam yapar; cam yokken eski küçülme kalır.
"data-cam:active:scale-100",
"data-glass-ready:active:scale-100",
"pl-[calc(var(--ok-cap)*1.25+1.75rem)]! [&>svg]:absolute [&>svg]:top-1/2 [&>svg]:left-[calc(var(--ok-cap)/2-1px)]! [&>svg]:-translate-x-1/2 [&>svg]:-translate-y-1/2",
listede
? "border-emerald-200 bg-emerald-50 text-emerald-600 disabled:opacity-100"
@@ -227,7 +227,7 @@ export function ProgramEkleButonu({
// turuncu, eklenince yeşil) boyanır; üstüne gelince şişer, basınca büyür.
// Cam kurulamazsa (WebGL2 yok) düğme eski düz hâlindedir.
className={cn(
"inline-flex cursor-pointer items-center justify-center rounded-full border transition-[background-color,border-color,color,transform] duration-150 active:scale-[0.92] data-cam:active:scale-100 disabled:cursor-default focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
"inline-flex cursor-pointer items-center justify-center rounded-full border transition-[background-color,border-color,color,transform] duration-150 active:scale-[0.92] data-glass-ready:active:scale-100 disabled:cursor-default focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
SIVI_KAP,
SATIR_DUGME_BOYU,
listede

View File

@@ -217,13 +217,13 @@ export function ProgramTablosu({
// (basılı tutunca mercek yerinde açılır). Klavye yolu aynı kalır.
onMouseDown={(e) => e.preventDefault()}
onClick={() => setAktifDilim(d.key)}
className="relative min-h-11 cursor-pointer select-none px-2 py-1.5 text-sm font-semibold transition-colors duration-200 hover:text-orange-500 data-active:hover:text-slate-50 group-data-[variant=pill]/tabs-list:h-auto sm:px-4 [[data-cam-yolda]_&]:data-active:text-slate-600!"
className="relative min-h-11 cursor-pointer select-none px-2 py-1.5 text-sm font-semibold transition-colors duration-200 hover:text-orange-500 data-active:hover:text-slate-50 group-data-[variant=pill]/tabs-list:h-auto sm:px-4 [[data-glass-traveling]_&]:data-active:text-slate-600!"
>
{aktif ? (
<motion.span
layoutId="dilim-aktif-hap"
data-cam-vurgu=""
className="absolute inset-0 rounded-full bg-slate-900 [[data-cam-geziyor]_&]:opacity-0!"
data-glass-highlight=""
className="absolute inset-0 rounded-full bg-slate-900 [[data-glass-moving]_&]:opacity-0!"
transition={
hareketAzalt
? { duration: 0 }
@@ -235,13 +235,13 @@ export function ProgramTablosu({
<span className="relative z-10 inline-flex flex-col items-center gap-0.5 sm:flex-row sm:gap-1.5">
<span className="inline-flex items-center gap-1.5">
<d.icon
className={`size-4 ${aktif ? "text-slate-50 [[data-cam-yolda]_&]:text-slate-500!" : d.renk}`}
className={`size-4 ${aktif ? "text-slate-50 [[data-glass-traveling]_&]:text-slate-500!" : d.renk}`}
aria-hidden
/>
{d.etiket}
</span>
<span
className={`text-sm font-medium tabular-nums ${aktif ? "text-slate-50/70 [[data-cam-yolda]_&]:text-slate-500!" : "text-slate-500"}`}
className={`text-sm font-medium tabular-nums ${aktif ? "text-slate-50/70 [[data-glass-traveling]_&]:text-slate-500!" : "text-slate-500"}`}
>
{sonuclar.toplam[d.key].toLocaleString("tr-TR")}
</span>

View File

@@ -230,7 +230,7 @@ const GENIS_YUKSEKLIK = "";
* başlık yan yana sığıyor.
*/
const BASLIK_DUGMESI =
SIVI_KAP + " inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-full border border-slate-200 bg-card text-slate-600 transition-[background-color,color,transform] duration-150 before:absolute before:-inset-1.5 before:content-[''] hover:bg-slate-100 hover:text-slate-800 active:scale-[0.96] data-cam:active:scale-100 motion-reduce:active:scale-100";
SIVI_KAP + " inline-flex size-8 shrink-0 cursor-pointer items-center justify-center rounded-full border border-slate-200 bg-card text-slate-600 transition-[background-color,color,transform] duration-150 before:absolute before:-inset-1.5 before:content-[''] hover:bg-slate-100 hover:text-slate-800 active:scale-[0.96] data-glass-ready:active:scale-100 motion-reduce:active:scale-100";
/**
* Kredi hapı: üst çubuktaki kredi hapının sınıf dizisi (user-nav.tsx; §11.1 V4

View File

@@ -77,7 +77,6 @@ export function RehberIzgarasi({ yazilar }: { yazilar: RehberKarti[] }) {
<li key={y.slug} className="relative flex pt-2.5">
<Link
href={`/rehber/${y.slug}`}
data-rozet-zemini
className="flex w-full flex-col overflow-hidden rounded-3xl border border-slate-200 bg-card p-2 shadow-sm focus-visible:outline-2 focus-visible:outline-offset-4 focus-visible:outline-primary"
>
{/* Kapak yazı sayfasındaki kapakla aynı adı taşır: tıklayınca

View File

@@ -39,26 +39,8 @@ export const YAY = {
mercekBirakma: { type: "spring", visualDuration: 0.3, bounce: 0.3 },
} as const;
/**
* Sıvı cam CTA'nın yayları (§4.49; kaynak: Liquid Glass UI, glass/physics.ts).
* Tuvalde adım adım çözülen sönümlü yaylar: `omega` hız (rad/sn), `zeta` sönüm
* oranı. Basma hafif seker; üstüne gelince en ve boy ayrı hız ve düşük sönümle
* faz farkıyla şişer, cam bir damla gibi yalpalar. "Sekmesiz" kuralının (§6)
* Bilal'in istediği istisnası (12 Kas 2026).
*/
export const CAM_YAYI = {
basma: { omega: 16, zeta: 0.6 },
ustundeEn: { omega: 17, zeta: 0.42 },
ustundeBoy: { omega: 12, zeta: 0.34 },
/** Oklu CTA'da üstüne gelince okun damla olarak ayrılması: yavaş, tek küçük salınım. */
damla: { omega: 5, zeta: 0.72 },
/** İmleç çıkınca ve basınca damlanın gövdeye geri karışması. */
damlaDonus: { omega: 13, zeta: 0.7 },
/** Sekme vurgusunun seçenekten seçeneğe kayması (kit: 14 rad/sn, sekme 0,25). */
kayma: { omega: 14, zeta: 0.75 },
/** Sürüklenen sekme merceğinin parmağı izlemesi (kit: 40 rad/sn, sekmesiz). */
surukleme: { omega: 40, zeta: 0.999 },
} as const;
// Sıvı camın yayları burada değildir: kitin kendi dosyasında durur
// (`src/components/liquid-glass/engine.ts`, `SPRINGS`; DESIGN.md §4.50).
/**
* Kaydırarak onayın (§4.41) iki yayı; `hiz` 0..100, bırakınca işi ne kadar

View File

@@ -1,6 +1,6 @@
{
"compilerOptions": {
"target": "ES2017",
"target": "ES2018",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,