diff --git a/docs/tasarim/DESIGN.md b/docs/tasarim/DESIGN.md
index 455aca3..4642a83 100644
--- a/docs/tasarim/DESIGN.md
+++ b/docs/tasarim/DESIGN.md
@@ -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-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
+ 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
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-glass-ready` gelince zemin ve DOM
+ CSS şeridi (`kt-yeni-serit`, 5 sn, kenarlar maskeyle erir). `data-cam` 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,45 +2102,6 @@ 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`,
@@ -2214,7 +2175,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-glass-ready:active:scale-100`; büyümeyi cam yapar). WebGL2 yoksa düğme eski düz hâlindedir.
+ (`data-cam: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
@@ -2236,7 +2197,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 ` `, `data-glass-ready:active:scale-100`.
+ tüm yuvarlak butonlar sıvı cam olmalı"): `SIVI_KAP` + ilk çocuk ` `, `data-cam: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; ` ` 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ışı.
@@ -2295,13 +2256,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 ` `; düz vurgu
- `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
+ `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
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-glass-ready` yazılır ve buton turuncu zeminini
+- **Sade karşılık:** ilk kare çizilince butona `data-cam` 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
diff --git a/eslint.config.mjs b/eslint.config.mjs
index 966beca..e4751bf 100644
--- a/eslint.config.mjs
+++ b/eslint.config.mjs
@@ -16,8 +16,6 @@ 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/**",
]),
]);
diff --git a/package.json b/package.json
index 3371fc9..87872ba 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "kolaytercih",
- "version": "2.12.14",
+ "version": "2.12.13",
"private": true,
"engines": {
"node": ">=22"
diff --git a/scripts/tasarim-denetim.ts b/scripts/tasarim-denetim.ts
index 33d12ae..a669739 100644
--- a/scripts/tasarim-denetim.ts
+++ b/scripts/tasarim-denetim.ts
@@ -5,8 +5,6 @@
* Çı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";
@@ -36,14 +34,11 @@ 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);
}
diff --git a/src/app/globals.css b/src/app/globals.css
index fc84ba0..42f7e52 100644
--- a/src/app/globals.css
+++ b/src/app/globals.css
@@ -1496,27 +1496,14 @@ html.lenis body {
right: calc(var(--ok-cap) / 2);
translate: 50% -50%;
}
- [data-sivi="bas"]:has(> [data-cam-iz] + svg) {
+ [data-sivi="bas"]:has(> canvas:first-child + svg) {
padding-left: calc(var(--ok-cap) * 1.625);
}
- [data-sivi="bas"] > [data-cam-iz] + svg {
+ [data-sivi="bas"] > canvas:first-child + 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%);
-}
diff --git a/src/app/layout.tsx b/src/app/layout.tsx
index a6b72e3..6d39cf9 100644
--- a/src/app/layout.tsx
+++ b/src/app/layout.tsx
@@ -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. */}
-
-
+
+
diff --git a/src/app/surum-notlari/page.tsx b/src/app/surum-notlari/page.tsx
index 59897df..4a54a2b 100644
--- a/src/app/surum-notlari/page.tsx
+++ b/src/app/surum-notlari/page.tsx
@@ -33,15 +33,6 @@ 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",
diff --git a/src/components/liquid-glass/LICENSE b/src/components/liquid-glass/LICENSE
deleted file mode 100644
index 5ebf61b..0000000
--- a/src/components/liquid-glass/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-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.
diff --git a/src/components/liquid-glass/dom-snapshot.ts b/src/components/liquid-glass/dom-snapshot.ts
deleted file mode 100644
index a37107c..0000000
--- a/src/components/liquid-glass/dom-snapshot.ts
+++ /dev/null
@@ -1,834 +0,0 @@
-// 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()
-
-/**
- * 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 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()
-
-/** Our own copy of an image by URL: a CSS background, or an 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()
-/** 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)[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()
-
-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)[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,
-) {
- 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 },
- })
-}
diff --git a/src/components/liquid-glass/engine.ts b/src/components/liquid-glass/engine.ts
deleted file mode 100644
index 877709f..0000000
--- a/src/components/liquid-glass/engine.ts
+++ /dev/null
@@ -1,2726 +0,0 @@
-// Liquid Glass engine — one shared WebGL2 context that draws every glass surface on the
-// page and copies each result into the surface's own 2D , so a page full of
-// glass never hits the browser's WebGL context limit.
-//
-// Zero dependencies. A GLSL lens with tinted glass, a 1 px border, a frosted resting
-// state, an opt-in gooey droplet and an opt-in frosted blur (cards). The rim mirrors what
-// surrounds the glass: a colourful neighbour shows on the side that faces it.
-//
-// Cost model: the loop runs only while a spring moves, a surface is dirty or the
-// cursor light changes; at rest it stops completely. Off-screen surfaces are not
-// drawn, and neither is a frame that would come out exactly as the one on the canvas:
-// nothing is asked of the GPU for it, and a frame that is drawn sends only what changed.
-// `prefers-reduced-motion` freezes every spring at its target.
-// If WebGL2 is missing or the context is lost, every surface falls back to plain CSS.
-//
-// COPY THIS FILE VERBATIM. Do not rewrite or "simplify" the shader: the look comes
-// from the exact constants below. MIT — https://github.com/bilalgursen/liquid-glass
-
-export type Rgb = [number, number, number]
-export type Rgba = [number, number, number, number]
-
-/** One frame of one glass shape. Lengths in CSS px; origin = the canvas's top-left. */
-export type GlassLens = {
- /** Canvas position inside its positioned parent, and its size. */
- left: number
- top: number
- width: number
- height: number
- /** CSS px per design unit (the shading is designed for a 120-unit-tall lens). */
- unit: number
- /** Body centre and half size. */
- cx: number
- cy: number
- hx: number
- hy: number
- radius: number
- /** Horizontal shift of the body (it pulls back while a droplet separates). */
- bodyX: number
- /** Separated droplet: centre x relative to the lens centre, radius, gooey bridge softness. */
- droplet?: { x: number; r: number; k: number }
- /**
- * A second rounded box melted into the body, in any direction: centre relative to the body's
- * centre, half size, corner radius and gooey bridge softness (all CSS px). Omit it and the
- * shape is exactly the body (and droplet) alone.
- */
- blob?: {
- x: number
- y: number
- hx: number
- hy: number
- r: number
- k: number
- /** Gathers the bridge around one point: the softness falls off from `x` (relative to the body's centre) over `w` px, so a thinning bridge narrows into a neck there. */
- neck?: { x: number; w: number }
- /** Fades the softness out towards the body's far edge: `amount` 0–1 (0 = none), recovering over `reach` × the body's height from that edge. */
- fade?: { amount: number; reach: number }
- /**
- * The blob's own glass, when it is not the body's: tint cover (0–1), frost in CSS px, the
- * bend's falloff and depth (as `tune.bendCurve` / `tune.bendDepth`) and a white rim line
- * (opacity, width in CSS px). It casts no shadow then, and the two glasses melt at the neck.
- */
- material?: { frost: number; blur: number; bendCurve: number; bendDepth: number; borderAlpha: number; borderWidth: number }
- }
- /** Bevel width (design units). */
- bevel: number
- /**
- * Width of the band that bends the backdrop (design units), when it must not follow
- * the bevel: a lens with square corners keeps its bevel within the corner radius but
- * still bends as deep as a pill. Omit for the default, `bevel × 0.35`.
- */
- band?: number
- shadow: number
- shadowSoftness: number
- shadowOffset: number
- /** 0 = flat liquid (no light or shadow), 1 = full glass lighting. */
- strength: number
- color: Rgb
- surface: Rgb
- /** How much the rim thins towards the surface colour (tinted glass). */
- edgeClear: number
- border?: Rgb
- /** Opacity of the border line (0–1, default 1). */
- borderAlpha?: number
- /** Width of the border line in CSS px (default 1). */
- borderWidth?: number
- /** Textured lens: paints what lies beneath and bends it. */
- refraction?: {
- /**
- * Return `false` when both layers came out exactly as the last time, colours included: they
- * are not uploaded again, not even on a frame that re-read sizes and colours.
- * A painter that declares only `back` has no front layer (none is cleared or uploaded).
- */
- paint: (back: CanvasRenderingContext2D, front: CanvasRenderingContext2D) => void | boolean
- refract: number
- magnify: number
- dispersion: number
- blurCenter: number
- blurEdge: number
- /** 1 = frosted (flat `color`), 0 = perfectly clear. */
- frost: number
- /** Frosted blur of the backdrop: a gaussian deviation in CSS px, like CSS `blur()`. 0 or omitted = sharp. */
- blur?: number
- /** How much of the frost shows over the sharp bend (0–1, default 1). */
- blurMix?: number
- /**
- * Radial bend, as the old SVG card drew it: each point near the rim looks towards the
- * centre, by this fraction of the viewport (0.065 there), falling off as (1 − d/half)^bendCurve,
- * and the frost blurs the bent picture. `refract`, `magnify` and the bend band are then unused.
- */
- radial?: number
- }
- /**
- * What the rim mirrors, while the glass is clear: the page around it (see MIRROR). `paint` draws it into a context
- * whose origin is the canvas's top-left (one unit = one CSS px), `reach` CSS px past the canvas
- * on every side; leave the glass itself out. `height` is the glass's own height at rest, in CSS
- * px: the rim looks about that far. A neighbour brighter or more colourful than the surface
- * shows on the rim that faces it, and the rim light's far side takes its colour. Without it the
- * glass mirrors the surface colour alone, which shows nothing. The picture is small and taken
- * rarely: when sizes and colours are re-read and when the canvas changes size, a few times a
- * second at most. `live` takes it again while the glass moves, too.
- */
- reflection?: { paint: (around: CanvasRenderingContext2D, reach: number) => void; height: number; live?: boolean }
- /** Fine-tuning of the look. Every field defaults to the kit's own value, noted in brackets. */
- tune?: {
- /** × rim light [1] and × its line's thickness [1]. */
- rim?: number
- rimWidth?: number
- /** × fresnel glow on the lit side [1], × inner shading [1], × top reflection [1], × warm caustic [1]. */
- fresnel?: number
- inner?: number
- reflection?: number
- caustic?: number
- /** × what the rim of clear glass mirrors of its surroundings [1] (see `reflection` above; 0 = nothing). */
- mirror?: number
- /** Falloff of the bend from the rim inwards, an exponent [1.6]; × how far in it reaches [1]. */
- bendCurve?: number
- bendDepth?: number
- /** Saturation of what shows through [1]; × the frost at the rim [1]. */
- saturation?: number
- frostEdge?: number
- }
- /** Rim light leans towards the cursor. */
- cursorLight: boolean
- /**
- * Light let into the glass at one point (a press): centre relative to the body's centre and
- * reach, in CSS px, and how strong (0 = none; see GLOW). It brightens all the glass near it alike, a melted blob
- * included, unless `blob` says how much of it the blob takes (0–1; 0 keeps the light to the body). `halo` lets it
- * spill past one edge, the body's or the blob's (0–1, how much): there
- * it brightens the page's colour the same way. Without it nothing shows outside the glass.
- */
- glow?: { x: number; y: number; r: number; amount: number; blob?: number; halo?: { around: 'body' | 'blob'; amount: number } }
- /** `false`: this glass does not take the light under the pointer (see LIGHT). Every other glass does, unless that light is turned off. */
- pointerLight?: boolean
- /**
- * Another view this glass continues (one shape drawn by two canvases, each on its side of a
- * seam): it takes that view's light of a press (LIGHT) as it is, where it is on screen, instead
- * of one of its own, so the light does not stop at the seam.
- */
- lightOf?: GlassView
- /** Lens centre on screen, for aiming the cursor light. */
- screenX: number
- screenY: number
- /**
- * How large one CSS px of the canvas is on screen: the host's own CSS `scale` and its
- * ancestors' (1 when omitted). Glass that melts into its neighbours (COHESION) is measured with it.
- */
- scale?: number
-}
-
-export type GlassView = {
- canvas: HTMLCanvasElement
- ctx: CanvasRenderingContext2D
- dirty: boolean
- /**
- * Set it (and wake the engine) when what lies behind the glass may have changed and the glass
- * itself has not, as on scroll: the layers are painted again, sizes and colours are not re-read.
- */
- repaint?: boolean
- visible: boolean
- /** Advance springs; return true while anything still moves. */
- step: (dt: number, reducedMotion: boolean) => boolean
- /** The shape to draw, or null to clear. `refresh`: re-read sizes and colours. */
- lens: (refresh: boolean) => GlassLens | null
- /** The first frame reached the canvas. */
- drawn?: () => void
- /** The GPU context is gone: return to the plain CSS look. */
- lost: () => void
- /**
- * `true`: a pointer that holds this glass pulls it after itself (see PULL). Buttons ask for it;
- * no other glass is pulled. A view may change it at any time: set back to `false`, held glass is let go.
- */
- pull?: boolean
- /** Set by the engine: a pointer holds this glass and may be pulling it. The press lasts as long, outside the glass too. */
- held?: boolean
- /**
- * The CSS scale this view wants on its host (1 = none), when it swells its host itself. The
- * engine writes the host's `scale`: this, times the stretch of a pull. A view that sets it
- * never writes `host.style.scale` itself.
- */
- grow?: number
- /**
- * `true`: this glass is a button (see "The light of a press", above GLOW). A press on it lets
- * light in where it lands (GLOW), on top of the light every glass takes under a press (LIGHT).
- * Left out, the glass is a surface (a card, a menu, a lens) and takes LIGHT alone. The engine
- * hears the press and the keys itself: a view only says what it is.
- */
- button?: boolean
- /** With `button`: the element a press must land in, when it is not the glass's host. */
- pressArea?: Element
- /**
- * `false`: this surface does not take the engine's light around a choice pressed in it (see the
- * rule above GLOW), because it brings that light itself (GlassPopup's lists do) or wants none.
- */
- choices?: boolean
- /**
- * Set by the engine: where a pull has this glass (px from its rest) and how it stretches its
- * host (1 = not at all), as written on the host this frame. A view reads it to undo the stretch
- * on its canvas and draw it in the glass instead (GlassLayer and GlassPopup do).
- */
- pulled?: { x: number; y: number; sx: number; sy: number }
- /**
- * Set by the engine: the hosts of the glass this one melts into (COHESION), or none. Melted,
- * they are one body with it, so a view leaves them out of its picture of what lies behind
- * (GlassLayer does). The list is replaced only when the glass it names changes.
- */
- near?: Element[]
-}
-
-export type GlassEngine = {
- add: (view: GlassView) => void
- remove: (view: GlassView) => void
- /** Schedule a frame (call after changing state the springs read). */
- wake: () => void
- /** Any CSS colour (oklch, var(), color-mix…) → 0..1 RGBA. */
- resolveColor: (css: string) => Rgba
-}
-
-/** Damped spring. `omega` = speed (rad/s), `zeta` = damping ratio (< 1 bounces). Returns true while moving. */
-export type Spring = { x: number; v: number }
-export function stepSpring(s: Spring, target: number, { omega, zeta }: { omega: number; zeta: number }, dt: number) {
- const d = s.x - target
- if (zeta > 0.9995) {
- const b = s.v + omega * d
- const e = Math.exp(-omega * dt)
- s.x = target + (d + b * dt) * e
- s.v = (s.v - omega * b * dt) * e
- } else {
- const wd = omega * Math.sqrt(1 - zeta * zeta)
- const b = (s.v + zeta * omega * d) / wd
- const e = Math.exp(-zeta * omega * dt)
- const cos = Math.cos(wd * dt)
- const sin = Math.sin(wd * dt)
- const x = (d * cos + b * sin) * e
- s.x = target + x
- s.v = e * wd * (b * cos - d * sin) - zeta * omega * x
- }
- // Thresholds scale with the target so pixel springs do not idle on an invisible tail.
- const scale = Math.max(1, Math.abs(target))
- const settled = Math.abs(s.x - target) < 5e-4 * scale && Math.abs(s.v) < 0.005 * scale
- if (settled) {
- s.x = target
- s.v = 0
- }
- return !settled
-}
-
-/**
- * The light of a press. The rule, kept here and applied by the engine:
- *
- * - A button is lit by GLOW: a press lets light in where it lands, the light holds a moment and
- * fades as it spreads. A view says `button: true` and the engine does the rest (Button, Action
- * Button and Button Group, through GlassLayer). The control of a surface that opens (GlassPopup)
- * is a button too and brings the same light itself (`glow` on its lens), because there it goes
- * on to open the surface.
- * - A surface is lit by LIGHT alone: a soft white light where the press lands, for as long as it
- * is held. Every glass that is not a button is a surface: a card, a menu or a list that has
- * opened, a lens, a thumb, a badge. Nothing asks for it; `pointerLight: false` on a lens opts out.
- * - A surface that holds choices also lights up around a choice pressed in it, with GLOW's
- * `select` values: a wide, soft light that stays inside the glass. A choice is an option, a
- * menu item, or anything marked `data-glass-item` or `data-glass-pick`. The engine does it for
- * every surface (a menu, a submenu, a card with rows); the lists of a Select, a Dropdown Menu
- * and a Popover bring the same light themselves (theirs leaves with the surface) and say
- * `choices: false`.
- * - A button takes LIGHT too, beneath its GLOW. No light follows the pointer, and a pointer that
- * only rests on the glass lights nothing.
- *
- * A new component follows the rule by saying what it is: it never draws a light of its own.
- *
- * GLOW: a press lets light into the glass where it lands. The light paints nothing: it brightens what
- * is already there, keeping its colour (luminance L becomes L^(1 / (1 + amount)) at the centre,
- * so black stays black and white stays white). These are
- * the values for wider controls; GLOW_SMALL, below, holds the same set for small ones.
- */
-export const GLOW = {
- /** One press, at the centre of the light. Presses that land before the last has faded add up, to `stack` presses at most. */
- amount: 3.55,
- stack: 3,
- /**
- * A choice made inside an open surface: this much of a press, and a light of its own size. It
- * is a wide, soft light around the choice (`selectReach` at first, `selectSpread` more as it
- * fades, both × the control's height) and it leaves as the surface starts back in.
- */
- select: 0.45,
- selectReach: 1.6,
- selectSpread: 1.2,
- /** A choice's light is gone once the surface is this far back in (0–1 of the way open; higher = it leaves sooner). */
- selectLeave: 0.5,
- /** The light's reach at first, and how much further it spreads as it fades (both × the control's height). */
- reach: 1.65,
- spread: 3,
- /** It stays for at least this long (seconds), comes up at `riseSpeed`, fades at `fadeSpeed` and spreads at `spreadSpeed` (springs: higher = faster). */
- hold: 0.2,
- riseSpeed: 60,
- fadeSpeed: 5.5,
- spreadSpeed: 5,
- /**
- * The press that opens a surface: its light grows with the surface until it covers it whole
- * (its reach ends at `cover` × the surface's diagonal). It lets go once the surface is this
- * far open (0–1) and fades at `coverFadeSpeed`: a flash, not a wash.
- */
- cover: 0.9,
- coverUntil: 0.1,
- coverFadeSpeed: 10,
- /** How much of the light spills past an open surface's edge (0 = none). */
- halo: 0.35,
-}
-/**
- * What the rim mirrors of the page around the glass. Each point of the rim looks outwards and
- * takes the colour of what it faces, where that differs from the surface the glass sits on: an
- * orange button above a control shows as an orange edge along its top. Only clear glass
- * mirrors: glass in its own colour (tinted, or a lens frosted over at rest) shows nothing.
- * These values are the look.
- */
-export const MIRROR = {
- /**
- * How much of a neighbour shows on the rim's line (1 at most: the line is the rim light's own,
- * as thin as the one that leans towards the cursor), and in the band that begins inside it.
- */
- line: 1,
- band: 0.7,
- /**
- * How deep that band goes: this × the glass's shorter half (or its reach, on taller glass).
- * The rim's edge looks `reach` far; the look shortens with depth and ends here, so a
- * neighbour's picture fills the band where it is near and thins out where the rim turns
- * away from it: a crescent on a round glass.
- */
- depth: 0.58,
- /** How fast the picture fades from the rim inwards, an exponent (1 = evenly, higher = it keeps closer to the rim). */
- fall: 1,
- /** How soft the picture is: the patch each point gathers, × the reach (0 = a sharp mirror). */
- soft: 1,
- /** How much more than its plain difference from the surface a neighbour counts. */
- gain: 1.8,
- /** How much a darker neighbour dims the rim (× the above; 0 = not at all). */
- dim: 0.65,
- /** How far the rim's edge looks: this × the glass's height, between `reachMin` and `reachMax` px. */
- reach: 0.55,
- reachMin: 24,
- reachMax: 96,
- /** What a point gathers along its look: shares from its near part, from further out and from its far end. */
- near: 0.25,
- mid: 0.35,
- far: 0.4,
- /** The rim light's far side: its brightness (× the lit side's), and how much of the surroundings' colour it takes (0 = always white). */
- bounce: 0.6,
- tint: 1,
-}
-
-/**
- * The same light on a small control: a single icon, or a label of about five letters (up to
- * roughly twice as wide as it is tall, as in GOOEY). In between the two sets are blended. The
- * light stays close to the press there, comes up slower and holds until the surface is half open.
- */
-export const GLOW_SMALL: typeof GLOW = { ...GLOW, reach: 0.7, spread: 0.7, riseSpeed: 24, coverUntil: 0.5 }
-
-/** The light on a morphing control (Popover): GLOW's, staying longer and adding up a little further. */
-export const MORPH_GLOW: typeof GLOW = { ...GLOW, stack: 3.5, hold: 0.5 }
-export const MORPH_GLOW_SMALL: typeof GLOW = { ...GLOW_SMALL, stack: MORPH_GLOW.stack, hold: MORPH_GLOW.hold }
-
-/**
- * LIGHT, the light every glass takes under a press and the only one a surface takes (the rule is
- * above GLOW): glass lit from within, beginning where the press landed. A press (any
- * pointer, or Space / Enter on the focused control) brings it up, and it stays at that point of
- * the glass for as long as the press is held, wherever the pointer goes; let go, it sinks back.
- * It follows nothing, and a pointer that only rests on the glass lights nothing. It is white laid over the
- * glass: strongest at that point, falling off evenly to nothing at its radius, and it never
- * leaves the glass. Every glass takes it: the kit's controls, and a surface that opens
- * (GlassPopup), on top of its own light (GLOW). A lens that says `pointerLight: false` does not,
- * and `on: false` turns it off everywhere. The light and its numbers are those of Glass HQ's liquid-glass 0.0.2 (MIT,
- * https://github.com/Glass-HQ/liquid-glass). Read on every frame: do not tune them casually.
- */
-export const LIGHT = {
- on: true,
- /** How white the glass is under the pointer at full light (0–1): on a light page, and on a dark one. */
- strength: 0.3,
- strengthDark: 0.16,
- /** How much of the full light a press brings. */
- press: 1,
- /** The light's radius: `size ×` the glass's longer side, between `sizeMin` and `sizeMax` px. */
- size: 0.9,
- sizeMin: 36,
- sizeMax: 180,
- /** A press comes up in about `rise` seconds, overshooting a little (`riseBounce`: 0 = none), and sinks back in `fade` seconds, without bounce. */
- rise: 0.24,
- riseBounce: 0.2,
- fade: 0.42,
-}
-
-/** Every spring the kit uses. Hover width/height bounce out of phase: the glass wobbles like a drop. */
-export const SPRINGS = {
- press: { omega: 16, zeta: 0.6 },
- hoverX: { omega: 17, zeta: 0.42 },
- hoverY: { omega: 12, zeta: 0.34 },
- /** A droplet separating from the body: slow, one small overshoot. */
- dropletOut: { omega: 5, zeta: 0.72 },
- /** The droplet melting back in (pointer leaves or presses). */
- dropletIn: { omega: 13, zeta: 0.7 },
- /** A lens sliding to the newly selected option. */
- slide: { omega: 14, zeta: 0.75 },
- /** A dragged lens following the finger. */
- drag: { omega: 40, zeta: 0.999 },
-} as const
-
-/**
- * Glass that a held pointer pulls after itself: press it, drag away, and it follows a little way
- * through a rubber band, stretches along the pull and thins across it, then swings back like gel
- * when let go. It is for buttons: the engine does it for glass whose view says `pull: true`
- * (GlassLayer does, so Button, Action Button and Button Group; `pull={false}` there keeps one in
- * its place), the innermost one under the press, by moving and stretching its host (CSS
- * `translate` and `scale`, content included). The control of a surface that opens (GlassPopup:
- * Select, Dropdown Menu, Popover, Menu) is a button too while it is shut, and opens when the press
- * is let go on it. No other glass is pulled, and `on: false` here turns it off everywhere. The motion and its numbers are those of Glass HQ's liquid-glass 0.0.2 (MIT,
- * https://github.com/Glass-HQ/liquid-glass). Read on every frame: do not tune them casually.
- */
-export const PULL = {
- on: true,
- /**
- * Glass whose longer side is at most this (px) is small: it follows the pointer from the point
- * it was pressed at. Larger glass moves only once the pointer is past its edge, by how far past.
- */
- smallUntil: 72,
- /** The furthest the pull moves small glass, px: `smallReach + smallReachPerPx × its longer side`. */
- smallReach: 4,
- smallReachPerPx: 0.15,
- /** The same for larger glass, `reachMax` at most. */
- reach: 3,
- reachPerPx: 0.04,
- reachMax: 10,
- /** How fast the band stiffens: 0.55 is a scroll view's. */
- resistance: 0.55,
- /** Following the pointer takes `follow + followPerPx × the longer side` seconds, without bounce (larger glass is heavier). */
- follow: 0.18,
- followPerPx: 5e-4,
- /** Let go: back to rest in about `release` seconds, overshooting like gel (`releaseBounce`: 0 = none, towards 1 = more). */
- release: 0.5,
- releaseBounce: 0.42,
- /**
- * The stretch along one axis: `stretch × the pull ÷ the glass's size that way`, plus
- * `stretchPerSpeed ×` the pull's own speed and `stretchPerDrift ×` the speed the glass's place
- * on the page moves at (px/s). Small glass stretches by `smallStretchMax` at most, larger by
- * `stretchMax`. Across, the glass thins by the square root of the stretch.
- */
- stretch: 0.5,
- stretchPerSpeed: 7e-5,
- stretchPerDrift: 5e-5,
- smallStretchMax: 0.2,
- stretchMax: 0.12,
- /** The drift speed is smoothed in at this rate while held, and dies out at `driftOut` (per second). */
- driftIn: 12,
- driftOut: 10,
-}
-
-/**
- * Cohesion: the glass of two buttons that come near each other melts into one body, as two drops
- * of liquid do. Within reach the sides that face each other lean out, nearer still a bridge forms
- * between them, and it thins and lets go as they part, whatever brings them together: a pull, a
- * swell, the layout. It is for buttons: the engine does it for glass whose view says
- * `button: true` (GlassLayer's, so Button, Action Button and Button Group). A surface (a card, a
- * menu, a lens) never melts, and a button never melts into glass it sits inside. Each canvas
- * draws its own side of the bridge, up to the line where the two glasses are as near, and across
- * the bridge they share their looks (bevel, bend, tint, shadow), so the line does not show. Joined,
- * the light of a press on one runs on into the other (`light` says how much of it), as far as it
- * reaches (GLOW and LIGHT, measured from where the press landed). The shape is a smooth union of
- * the glasses' distance fields, the fusion of Liquid Glass Studio (MIT,
- * https://github.com/iyinchao/liquid-glass-studio). `on: false` turns it off everywhere. Read on
- * every frame: do not tune them casually.
- */
-export const COHESION = {
- on: true,
- /**
- * How soft the bridge is: `reach ×` the shorter glass's height, between `reachMin` and
- * `reachMax` px. Two glasses begin to melt once the gap between them is under this (it eases in
- * until the gap is half of it), and join into one once the gap is under half of it.
- */
- reach: 1.2,
- reachMin: 2,
- reachMax: 6,
- /**
- * How much of the light of a press on one glass runs on into a glass it has melted into, once
- * the bridge between them has some body (0 = none: each keeps its own light; 1 = all of it, as
- * one body). Short of that, the light crosses only where the two meet.
- */
- light: 0.07,
- /** That light fades as it goes into the other glass, as a reflection would: it is down to a third this far from where the two meet (× that glass's half height). */
- lightFade: 1,
-}
-
-/** The bridge's softness between glass of this height (px) and glass as tall or taller (COHESION); 0 while it is off. */
-export function cohesionSoftness(height: number) {
- if (!COHESION.on) return 0
- return Math.min(Math.max(COHESION.reach * height, COHESION.reachMin), Math.max(COHESION.reachMin, COHESION.reachMax))
-}
-
-/**
- * Presses the kit sends itself: GlassPopup keeps a press that would open its surface and hands it
- * on when it is let go. Such a press is no pointer holding the glass: nothing is pulled or lit by
- * it, and no release follows it. Whoever dispatches one adds it here first.
- */
-export const HANDED_ON = new WeakSet()
-
-/** A rubber band: a short pull follows almost one to one, a long one nears `limit` and never reaches it. */
-export function rubberBand(offset: number, limit: number, resistance = 0.55) {
- if (!(limit > 0)) return 0
- return Math.sign(offset) * limit * (1 - 1 / ((Math.abs(offset) * resistance) / limit + 1))
-}
-
-/**
- * The gooey popup: a surface (a list, a menu, a popover) that swells out of its anchor as one
- * body of glass, holds on by a neck that thins and snaps, and plays the same motion backwards to
- * close. Used by GlassPopup (`glass-popup.tsx`). These values are the look: do not tune them casually.
- */
-export const GOOEY = {
- /** How heavy the two halves are. Heavier glass is thrown less by a jolt and swings back slower. */
- weight: 6,
- /** The panel opening: speed, and damping (below 1 it overshoots as it lands). */
- openSpeed: 11,
- openDamping: 1,
- /** Closing replays the opening backwards, at closeSpeed / openSpeed × its pace (equal = the same pace). */
- closeSpeed: 26,
- /** The panel lets go of the trigger once it is this far open (0–1). */
- detachAt: 0.1,
- /** How fast the neck thins once it lets go (lower = a slower snap). */
- snapSpeed: 5.6,
- /** Bridge softness in px at full strength, and how far the panel leans back towards the trigger. */
- neckSoftness: 50,
- neckPull: 11,
- /** The jolt when the neck snaps: its strength, how fast it swings, how soon it dies out (higher = sooner). */
- kick: 6,
- recoilSpeed: 4,
- recoilDamping: 1,
- /** How far each half is thrown by a jolt, and how far the trigger sags while attached (px). */
- triggerJolt: 0,
- panelJolt: 0,
- triggerSag: 6,
- /** The list: how far open the panel is when the first option appears (0–1), the delay between options and each one's fade (seconds). */
- itemsAt: 0.85,
- itemsGap: 0.06,
- itemsFade: 0.22,
- /**
- * Small controls only: a single icon, or a label of about five letters (up to roughly twice as
- * wide as they are tall). The bridge is as wide as the whole control there, so it gets its own
- * softness in px (in place of neckSoftness), a fade of that softness towards the control's far
- * edge (0–1, and how far in it recovers, × the height) and a neck no thinner than this × the
- * height, at first and once it has gathered. Wider controls keep the values above.
- */
- smallNeckSoftness: 14,
- smallEdgeFade: 1,
- smallEdgeReach: 0.5,
- smallNeck: 0.6,
- smallNeckWide: 1.2,
-}
-
-/**
- * The morphing popup: a control that becomes its surface. The surface (Card's glass, as in the
- * gooey popup) comes out over the control itself: round all the way, a little past its own box,
- * then settled, while the control lets go of its label and its glass gives way to the card. The
- * surface's content comes into focus inside it as it grows. Closing is a calmer motion of its
- * own: the content goes first and the surface slides back into the control, slowing as it lands. Used by GlassPopup with `opening: 'morph'` (`glass-popup.tsx`). These values are the
- * look: do not tune them casually.
- */
-export const MORPH = {
- /** The side that grows the most: its speed, and damping (below 1 it lands past the surface and comes back). */
- openSpeed: 30,
- openDamping: 1,
- /** The other side follows on a slower spring with more bounce. */
- crossSpeed: 16,
- crossDamping: 0.58,
- /**
- * While the first side runs ahead of the other, the glass is this much thinner across (× how
- * far ahead, 0–1); as the other catches up and passes it, as much wider.
- */
- pinch: 0,
- /** Corners, frost and the content's focus follow at this speed, without a bounce. */
- calmSpeed: 12,
- /** Closing replays the opening backwards, at this × its pace. */
- closePace: 1.7,
- /** The control's label is gone once the surface is this far out (0–1). */
- labelOut: 0.02,
- /** The content fades in with the calm follow, and is fully visible once that is this far (0–1). */
- contentFade: 0.75,
- /** How soft the label gets as it goes, and the content as it starts (a blur, CSS px). */
- labelBlur: 0,
- contentBlur: 5.5,
- /** How much of the surface's growth the content takes: 1 = it is as small as the glass is, 0 = full size from the start, only cut to the glass. */
- zoom: 1,
- /**
- * Not gooey: the surface and the control are two shapes laid over each other, with a clean
- * edge where they meet. `gooey: 1` melts them there instead, by `softness` CSS px.
- */
- gooey: 0,
- softness: 40,
- /** How the surface starts, in the control's middle: 0 = a circle as tall as the control, 1 = the control's own box. */
- seed: 1,
- /** It stays round all the way until the calm follow is this far (0–1); its own corners come after. */
- cornersFrom: 0.3,
- /**
- * Its weight. At the press the control is thrown down (`kick`: how hard; `throw`: how far a
- * throw of 1 carries it, CSS px) and swings back at `swingSpeed`, dying out by `swingDamping`
- * (below 1 it swings to and fro). Heavier glass is thrown less and swings slower.
- */
- weight: 8,
- kick: 8,
- swingSpeed: 17.5,
- swingDamping: 0.6,
- throw: 80,
- /** The surface comes out this long after the press (seconds): the control is thrown first. */
- openDelay: 0.1,
- /**
- * The surface's way into place: as it grows it is carried up to `drop` CSS px above its place
- * (negative: below), and comes down `dropDelay` seconds after the press on a soft spring
- * (`dropSpeed`; `dropDamping` 1 = no bounce). 0 px = it grows where it is.
- */
- drop: 60,
- dropDelay: 0.2,
- dropSpeed: 9,
- dropDamping: 1,
- /** Asked to close, the surface stays as it is this long (seconds) before it goes back in. */
- closeDelay: 0,
- /**
- * `closeSoft: 1`: closing is a motion of its own (`0`: the opening played backwards). The
- * surface goes back into the control on one spring with no bounce (`closeSpeed`), slowing as it
- * lands, and the control stays still: it is not thrown, does not swell and does not light up. The content
- * does not wait for the glass: it is gone `closeFade` seconds after the close begins. A choice's
- * light comes into the control with the surface and narrows to `closeGlowReach` (× the control's
- * height) as it does, so it does not flood the control. `closeKick`:
- * with the opening played backwards, how much of the throw the control takes once the surface
- * is back in (× `kick`; 0 = it stays still).
- */
- closeSoft: 1,
- closeSpeed: 14,
- closeFade: 0.12,
- closeGlowReach: 1,
- closeKick: 1,
- /** The control's own glass (clear, lit) gives way to the card's between these two points of the calm follow (0–1). */
- frostFrom: 0,
- frostTo: 0.05,
-}
-
-/**
- * The growing popup: a control whose glass becomes its menu. One shape on one spring: the
- * control's own outline grows into the menu's, wherever the menu lies (below, above or beside
- * it), and shrinks back along the same path to close. The side the menu lies on runs ahead and
- * the other follows, so the glass pours towards its place instead of scaling up. The control's
- * label goes as the glass leaves it; the menu's content stays where it is and the glass opens
- * over it. A close that is interrupted carries on from where it is, at the speed it has. It takes
- * no light from a press (GLOW is not used here). Used by
- * GlassPopup with `opening: 'grow'` (`glass-popup.tsx`). The motion and its numbers are those of
- * Glass HQ's liquid-glass 0.0.2 (MIT, https://github.com/Glass-HQ/liquid-glass). These values
- * are the look: do not tune them casually.
- */
-export const MENU = {
- /** Opening takes about `open` seconds and lands a little past the menu (`openBounce`: 0 = not at all, towards 1 = more). */
- open: 0.42,
- openBounce: 0.18,
- /** Closing: the same, on its own spring. */
- close: 0.32,
- closeBounce: 0.1,
- /**
- * The side the menu lies on leads and the other follows, both as exponents: the leading side
- * goes as 1 − (1 − p)^lead, the other as p^follow (1 and 1: both sides grow evenly).
- */
- lead: 1.6,
- follow: 1.4,
- /**
- * On the way the corners stay round: no tighter than `round` × the shape's shorter side, until
- * the motion is `roundFrom` of the way (0–1), easing to the menu's own corners by `roundUntil`.
- */
- round: 0.34,
- roundFrom: 0.35,
- roundUntil: 0.8,
- /** The control's label goes between these two points of the way (0–1), softening by `labelBlur` CSS px. */
- labelFrom: 0.02,
- labelTo: 0.3,
- labelBlur: 3,
- /** The menu's content shows between these two points, coming out of a blur of `contentBlur` CSS px (0 = none: the cheapest). */
- contentFrom: 0.4,
- contentTo: 0.9,
- /** Closing, the content does not wait for the glass: it is gone this long (seconds) after the close begins. */
- closeFade: 0.12,
- contentBlur: 6,
- /** The control's glass (clear, lit) gives way to the card's between these two points. Done by `labelTo`, so the label is gone before the menu's layer takes the glass over. */
- frostFrom: 0,
- frostTo: 0.3,
-}
-
-export const lerp =(a: number, b: number, t: number) => a + (b - a) * t
-export const clamp = (v: number, a = 0, b = 1) => Math.max(a, Math.min(b, v))
-export const smooth = (a: number, b: number, v: number) => {
- const t = clamp((v - a) / (b - a))
- return t * t * (3 - 2 * t)
-}
-export const mixRgb = (a: Rgb, b: Rgb, t: number): Rgb => [lerp(a[0], b[0], t), lerp(a[1], b[1], t), lerp(a[2], b[2], t)]
-export const rgbCss = (c: Rgb) => `rgb(${Math.round(c[0] * 255)} ${Math.round(c[1] * 255)} ${Math.round(c[2] * 255)})`
-
-const isVisibleColor = (c: string) => !!c && c !== 'transparent' && !/rgba\(.*,\s*0\)$/.test(c) && !/\/\s*0\)$/.test(c)
-
-/** The colour an element sits on: the first ancestor with a painted background. */
-export function surfaceColorOf(el: Element | null): string {
- for (let a = el; a; a = a.parentElement) {
- const c = getComputedStyle(a).backgroundColor
- if (isVisibleColor(c)) return c
- }
- return getComputedStyle(document.documentElement).colorScheme.includes('dark') ? 'black' : 'white'
-}
-
-/** The lens is designed 120 units tall; every optic below is in those units. */
-export const DESIGN_HEIGHT = 120
-
-const VERTEX = `#version 300 es
-in vec2 a;
-void main() { gl_Position = vec4(a, 0.0, 1.0); }
-`
-
-const FRAGMENT = `#version 300 es
-precision highp float;
-uniform vec2 uSize, uCenter, uHalf, uLightDir;
-uniform float uUnit, uDevicePx, uRadius, uBevel, uBodyX, uBand, uFieldRadius;
-uniform vec3 uDrop;
-uniform vec4 uBlob;
-uniform vec2 uBlobShape, uBlobNeck, uBlobFade;
-uniform float uRim, uCaustic, uInner, uTopRefl, uTopBase, uRimWidth, uFresnel;
-uniform float uShadow, uShadowSoft, uShadowOffset;
-uniform float uLightMix, uEdgeClear;
-uniform vec3 uSurface, uColor, uBorder;
-uniform float uBorderWidth, uBorderAlpha;
-uniform sampler2D uBack, uFront;
-uniform float uTextured, uRefract, uMag, uDisp, uBlurCenter, uBlurEdge, uBlurShift, uFrost, uFrostBlur, uFrostMix;
-uniform float uFrostEdge, uSaturation, uBendCurve, uEdgeBand;
-uniform vec2 uRadial;
-uniform vec4 uGlow;
-uniform vec2 uGlowHalo;
-uniform float uGlowBlob;
-uniform vec4 uLight;
-uniform vec4 uBlobMat;
-uniform vec3 uBlobLine;
-// The frost of large glass, worked out beforehand at a fraction of the size (FROST_PASS in the
-// engine). uFrostPass.x: 0 = no such picture, the frost is worked out here as ever; 1 = this draw
-// is that picture; 2 = this draw reads it. Then how many pixels one of its texels covers each
-// way, and 1 / (that x the picture's size), to find a pixel in it.
-uniform sampler2D uFrostPic;
-uniform vec4 uFrostPass;
-// How many halvings smaller the picture of the page was painted (BACK_SKIP in the engine): its
-// mip levels are read that many lower.
-uniform float uBackSkip;
-uniform float uCssPx;
-uniform sampler2D uAround;
-uniform vec4 uAroundBox;
-uniform float uAroundScale, uReach;
-uniform vec4 uMirror, uSeen;
-uniform vec2 uBounce;
-uniform float uFall, uSoft;
-// The glass this one melts into (COHESION), up to four, in this glass's design units. uNear: centre
-// (from the lens centre) and half size. uNearShape: corner radius, the radius its bend follows (as
-// uFieldRadius), the bridge's softness, bevel. What the two share across the bridge: uNearTint
-// (tint colour and how much of it covers clear glass, or the colour of tinted glass), uNearLine
-// (rim line colour and opacity), uNearLook (bend, 1 = clear, rim line width, cursor light angle),
-// uNearShade (shadow, its softness and offset, its design unit in this glass's), uNearMirror (as
-// uMirror.z, uReach and uSoft, and how much it mirrors, × this glass's) and the light of a press,
-// uNearGlow and uNearLight (as uGlow and uLight).
-// uNearPair: 1 = that glass's canvas lies over this one's; how joined the two are (0 = apart, 1 =
-// the bridge between them has some body: the light of a press on either fills both).
-uniform float uNearCount;
-uniform vec4 uNear[4], uNearShape[4], uNearTint[4], uNearLine[4], uNearLook[4], uNearShade[4], uNearMirror[4], uNearGlow[4], uNearLight[4];
-uniform vec2 uNearPair[4];
-// How far the light of a press runs into the glass it reaches before it has faded (× its half height).
-uniform float uNearFade;
-out vec4 outColor;
-
-// design units -> texture uv (textures are uploaded flipped: top row at v = 1)
-vec2 toUv(vec2 d) {
- vec2 q = d * uUnit;
- return clamp(vec2(q.x / uSize.x, 1.0 - q.y / uSize.y), vec2(0.0005), vec2(0.9995));
-}
-vec3 backdrop(vec2 st, float lod) {
- vec4 c = textureLod(uBack, st, max(lod - uBackSkip, 0.0));
- return c.rgb + (1.0 - c.a) * uSurface;
-}
-// What surrounds the glass (GlassLens.reflection), at a point of the canvas in design units and
-// blurred over spread. Where the picture is empty, or there is none, it is the surface colour.
-vec3 around(vec2 d, float spread) {
- vec2 st = clamp((d - uAroundBox.xy) / uAroundBox.zw, vec2(0.002), vec2(0.998));
- vec4 c = textureLod(uAround, vec2(st.x, 1.0 - st.y), log2(max(spread * uAroundScale, 1.0)));
- return c.rgb + (1.0 - c.a) * uSurface;
-}
-// Frosted glass: the backdrop under a gaussian blur of deviation sigma (design units),
-// gathered from 32 taps on a golden-angle spiral out to 2.5 deviations. Each tap reads a
-// mip about as wide as the gap between taps, so the frost stays smooth while the backdrop moves.
-vec3 frosted(vec2 p, float sigma) {
- float lod = max(log2(sigma * 0.8 * uUnit) - 0.5, 0.0);
- vec3 sum = vec3(0.0);
- float total = 0.0;
- for (int i = 0; i < 32; i++) {
- float f = float(i) + 0.5;
- float r = sqrt(f / 32.0) * 2.5 * sigma;
- float a = f * 2.39996323;
- float w = exp(-0.5 * r * r / (sigma * sigma));
- sum += backdrop(toUv(p + r * vec2(cos(a), sin(a))), lod) * w;
- total += w;
- }
- return sum / total;
-}
-// The sharp bend: the backdrop at p pushed by bend, its colours split slightly.
-vec3 bent(vec2 p, vec2 bend, float split, float lod) {
- return vec3(
- backdrop(toUv(p + bend * (1.0 + split)), lod).r,
- backdrop(toUv(p + bend), lod).g,
- backdrop(toUv(p + bend * (1.0 - split)), lod).b);
-}
-float roundRect(vec2 p, vec2 b, float r) {
- vec2 q = abs(p) - b + r;
- return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - r;
-}
-float melt(float a, float b, float k) {
- float h = clamp(0.5 + 0.5 * (a - b) / k, 0.0, 1.0);
- return mix(a, b, h) - k * h * (1.0 - h);
-}
-// The glass shape: a pill body, smoothly unioned with a separating droplet.
-float bodyShape(vec2 p) {
- float body = roundRect(p - vec2(uBodyX, 0.0), uHalf, uRadius);
- if (uDrop.y <= 0.0) return body;
- float d = length(p - vec2(uDrop.x, 0.0)) - uDrop.y;
- float k = max(uDrop.z, 1e-3);
- float h = clamp(0.5 + 0.5 * (d - body) / k, 0.0, 1.0);
- return mix(d, body, h) - k * h * (1.0 - h);
-}
-// ...and with the optional second box (uBlobShape.y = its bridge softness, 0 = none).
-float blobSoft(vec2 p) {
- float k = uBlobShape.y;
- if (uBlobNeck.y > 0.0) {
- float n = (p.x - uBlobNeck.x) / uBlobNeck.y;
- // A peaked falloff: as the softness drops, the bridge thins into a thread before it breaks.
- k *= exp(0.2 - sqrt(n * n + 0.04));
- }
- // On a small body the bridge belongs to the side that faces the second box: towards the far
- // edge the softness fades out (uBlobFade: how much, and how far in), or it raises a ridge there.
- if (uBlobFade.x > 0.0) {
- float back = smoothstep(-uHalf.y, -uHalf.y + 2.0 * uHalf.y * max(uBlobFade.y, 0.01), p.y * sign(uBlob.y));
- k *= mix(1.0, back, uBlobFade.x);
- }
- return max(k, 1e-3);
-}
-// The glass's own shape: the body, its droplet and its blob.
-float selfShape(vec2 p) {
- float s = bodyShape(p);
- if (uBlobShape.y <= 0.0) return s;
- return melt(roundRect(p - uBlob.xy, uBlob.zw, uBlobShape.x), s, blobSoft(p));
-}
-// A glass this one melts into (COHESION): a rounded box.
-float nearBox(int i, vec2 p) {
- return roundRect(p - uNear[i].xy, uNear[i].zw, uNearShape[i].x);
-}
-// The shape: its own, melted into every glass within reach.
-float shape(vec2 p) {
- float s = selfShape(p);
- for (int i = 0; i < 4; i++) {
- if (float(i) >= uNearCount) break;
- s = melt(nearBox(i, p), s, max(uNearShape[i].z, 1e-3));
- }
- return s;
-}
-// What casts the drop shadow: the body alone once a blob has a glass of its own.
-float caster(vec2 p) {
- return uBlobShape.y > 0.0 && uBlobLine.z > 0.5 ? bodyShape(p) : shape(p);
-}
-// The body with corners at least as round as the bend is deep (see uBand in main).
-float field(vec2 p) {
- float f = roundRect(p - vec2(uBodyX, 0.0), uHalf, uFieldRadius);
- if (uBlobShape.y > 0.0) f = melt(roundRect(p - uBlob.xy, uBlob.zw, uBlobShape.x), f, blobSoft(p));
- for (int i = 0; i < 4; i++) {
- if (float(i) >= uNearCount) break;
- f = melt(roundRect(p - uNear[i].xy, uNear[i].zw, uNearShape[i].y), f, max(uNearShape[i].z, 1e-3));
- }
- return f;
-}
-// The reference darkens linear colour; on sRGB values the same factor is k^(1/2.2).
-float dim(float k) { return pow(clamp(k, 0.0, 1.0), 1.0 / 2.2); }
-vec3 dim(vec3 k) { return pow(clamp(k, 0.0, 1.0), vec3(1.0 / 2.2)); }
-float height(vec2 p, float bevel) {
- float t = pow(clamp(-shape(p) / bevel, 0.0, 1.0), 1.0 / 1.4);
- return sqrt(1.0 - (1.0 - t) * (1.0 - t));
-}
-// Radial bend (the SVG card's): towards the centre, strongest at the rim, fading over the
-// half size. uRadial is the full bend per axis (design units); uEdgeBand / 0.35 = bendDepth.
-float radialRatio(float d) {
- return clamp(1.0 - abs(d) / (min(uHalf.x, uHalf.y) * uEdgeBand / 0.35), 0.0, 1.0);
-}
-// d = shape(q): the caller has it already.
-vec2 radialBend(vec2 q, float d) {
- vec2 c = q - vec2(uBodyX, 0.0);
- float k = pow(radialRatio(d), uBendCurve) * smoothstep(1.5 * uCssPx, -0.5 * uCssPx, d);
- return -c / max(length(c), 1e-4) * k * uRadial;
-}
-// Frost after the bend: every tap is bent on its own, and taps outside the glass are left
-// out (the SVG filter saw nothing beyond the card), so the rim keeps its colour.
-vec3 frostedRadial(vec2 q, float dq, float sigma) {
- float lod = max(log2(sigma * 0.8 * uUnit) - 0.5, 0.0);
- vec3 sum = vec3(0.0);
- float total = 0.0;
- for (int i = 0; i < 32; i++) {
- float f = float(i) + 0.5;
- float r = sqrt(f / 32.0) * 2.5 * sigma;
- float a = f * 2.39996323;
- vec2 t = q + r * vec2(cos(a), sin(a));
- // One shape per tap: it masks the tap and bends it.
- float dt = shape(t);
- float w = exp(-0.5 * r * r / (sigma * sigma)) * step(dt, 0.0);
- sum += backdrop(toUv(uCenter + t + radialBend(t, dt)), lod) * w;
- total += w;
- }
- return total > 1e-4 ? sum / total : backdrop(toUv(uCenter + q + radialBend(q, dq)), lod);
-}
-// How much of the frost this deep in the glass is read from the picture (0 = worked out here).
-// Within four of the picture's texels of the rim it is worked out in full: it changes too fast
-// there for a smaller picture. The picture fades in over the inner half of that band.
-float frostDeep(float d) {
- if (uFrostPass.x < 1.5) return 0.0;
- float band = 4.0 * uFrostPass.y * uDevicePx;
- return 1.0 - smoothstep(-band, -0.5 * band, d);
-}
-vec3 frostPicture() {
- return texture(uFrostPic, gl_FragCoord.xy * uFrostPass.zw).rgb;
-}
-
-void main() {
- // The frost's own pass draws one texel for every uFrostPass.y pixels each way, and a little
- // past the rim, so that a pixel on the rim finds its neighbours in the picture.
- bool pre = uFrostPass.x > 0.5 && uFrostPass.x < 1.5;
- vec2 fc = pre ? gl_FragCoord.xy * uFrostPass.y : gl_FragCoord.xy;
- float frostReach = pre ? 1.0 + 2.0 * uFrostPass.y * uDevicePx : 1.0;
- vec2 px = vec2(fc.x, uSize.y - fc.y);
- vec2 local = px / uUnit - uCenter;
- float dist = shape(local);
-
- // Melted into other glass (COHESION), both canvases draw one body: each its own side of the line
- // where the two glasses are as near (side: how much nearer the nearest neighbour is here). What
- // the look depends on is shared across the bridge: a neighbour takes r / (1 + Σ r) of it, none
- // deep in this glass, half on that line, all of it deep in its own glass. Both canvases work out
- // the same values on the line, so it does not show. Without neighbours, each is this glass's own.
- float side = -1.0;
- float share = 1.0;
- float mine = dist;
- float nearTotal = 1.0;
- float nearT[4] = float[4](0.0, 0.0, 0.0, 0.0);
- float nearD[4] = float[4](0.0, 0.0, 0.0, 0.0);
- float scale = 1.0;
- float bevel = uBevel;
- float refract = uRefract;
- float blurShift = uBlurShift;
- float shadowAmount = uShadow;
- float shadowSoft = uShadowSoft;
- float shadowOffset = uShadowOffset;
- float ny = local.y / uHalf.y;
- float nx = (local.x - uBodyX) / uHalf.x;
- float ly = local.y;
- vec2 lightDir = uLightDir;
- vec3 lineColor = uBorder;
- float lineAlpha = step(1e-4, uBorderWidth) * uBorderAlpha;
- float lineWidth = uBorderWidth;
- vec3 mirrorShape = vec3(uMirror.z, uReach, uSoft);
- float glowNear = 0.0;
- float lightNear = 0.0;
- float ownLight = 1.0;
- if (uNearCount > 0.0) {
- mine = selfShape(local);
- float nearest = 1e9;
- float sumScale = 1.0;
- float sumBevel = uBevel;
- float sumRefract = uRefract;
- vec3 sumShadow = vec3(uShadow, uShadowSoft, uShadowOffset);
- vec3 sumPlace = vec3(ny, nx, ly);
- vec2 sumDir = uLightDir;
- vec3 sumLine = uBorder * lineAlpha;
- float sumAlpha = lineAlpha;
- float sumWidth = uBorderWidth * lineAlpha;
- vec3 sumMirror = mirrorShape;
- float apartAll = 0.0;
- float glowJoined = 0.0;
- float lightJoined = 0.0;
- for (int i = 0; i < 4; i++) {
- if (float(i) >= uNearCount) break;
- float d = nearBox(i, local);
- nearD[i] = d;
- nearest = min(nearest, d);
- // How far this point has gone over to the neighbour: 0 to 1 across the bridge's softness.
- float t = clamp(0.5 + (mine - d) / max(uNearShape[i].z, 1e-3), 0.0, 1.0);
- nearT[i] = t;
- float r = t / max(1.0 - t, 1e-4);
- nearTotal += r;
- vec4 n = uNear[i];
- sumScale += r * uNearShade[i].w;
- sumBevel += r * uNearShape[i].w;
- sumRefract += r * uNearLook[i].x;
- sumShadow += r * uNearShade[i].xyz;
- sumPlace += r * vec3((local.y - n.y) / n.w, (local.x - n.x) / n.z, local.y - n.y);
- sumDir += r * vec2(cos(uNearLook[i].w), sin(uNearLook[i].w));
- float a = uNearLine[i].w;
- sumLine += r * a * uNearLine[i].rgb;
- sumAlpha += r * a;
- sumWidth += r * a * uNearLook[i].z;
- sumMirror += r * uNearMirror[i].xyz;
- // The light of a press on either glass: shared like the rest while they are apart, and all of
- // it everywhere once they are joined, so it runs on through the whole body.
- // ...fading as it goes deeper into this glass from the line between them, as a reflection would.
- float join = uNearPair[i].y * exp(-max(d - mine, 0.0) / max(uHalf.y * uNearFade, 0.5));
- float apart = r * (1.0 - join);
- apartAll += apart;
- vec2 gd = (local - uNearGlow[i].xy) / max(uNearGlow[i].z, 1.0);
- float glow = uNearGlow[i].w * exp(-dot(gd, gd));
- float light = uNearLight[i].w * max(1.0 - length(local - uNearLight[i].xy) / max(uNearLight[i].z, 1e-3), 0.0);
- glowNear += apart * glow;
- lightNear += apart * light;
- glowJoined += join * glow;
- lightJoined += join * light;
- }
- side = mine - nearest;
- share = clamp(0.5 - side / (4.0 * uDevicePx), 0.0, 1.0);
- // Lengths built into the look (in design units) follow the shared design unit.
- scale = sumScale / nearTotal;
- bevel = sumBevel / nearTotal;
- refract = sumRefract / nearTotal;
- blurShift = uBlurShift + log2(max(scale, 1e-3));
- shadowAmount = sumShadow.x / nearTotal;
- shadowSoft = sumShadow.y / nearTotal;
- shadowOffset = sumShadow.z / nearTotal;
- ny = sumPlace.x / nearTotal;
- nx = sumPlace.y / nearTotal;
- ly = sumPlace.z / nearTotal;
- if (dot(sumDir, sumDir) > 1e-6) lightDir = normalize(sumDir);
- lineAlpha = sumAlpha / nearTotal;
- if (sumAlpha > 1e-4) {
- lineColor = sumLine / sumAlpha;
- lineWidth = sumWidth / sumAlpha;
- }
- mirrorShape = sumMirror / nearTotal;
- glowNear = glowNear / nearTotal + glowJoined;
- lightNear = lightNear / nearTotal + lightJoined;
- ownLight = 1.0 - apartAll / nearTotal;
- }
-
- // Drop shadow: tight + ambient, kept near the glass, faded before the canvas edge.
- float vFade = smoothstep(-0.1, 0.9, ny) * 0.92 + 0.08;
- float outside = smoothstep(-4.0 * scale, 14.0 * scale, dist);
- float near = 1.0 - smoothstep(-6.0 * scale, shadowSoft, caster(local - vec2(0.0, shadowOffset)));
- float far = 1.0 - smoothstep(-10.0 * scale, shadowSoft * 1.5, caster(local - vec2(0.0, shadowOffset * 1.6)));
- float border = min(min(px.x, px.y), min(uSize.x - px.x, uSize.y - px.y));
- float sh = clamp((near + far) * shadowAmount * vFade * outside, 0.0, 0.85) * smoothstep(0.0, 14.0, border);
- vec4 outsideCol = vec4(0.0, 0.0, 0.0, 1.0 - dim(1.0 - sh));
-
- // Glow (see below): its strength here. It stays inside the glass unless a halo is asked for
- // (uGlowHalo: 1 = around the body, 2 = around the blob; and how much).
- float glowAt = 0.0;
- if (uGlow.w > 0.0) {
- vec2 gd = (local - uGlow.xy) / max(uGlow.z, 1.0);
- glowAt = uGlow.w * exp(-dot(gd, gd));
- if (uGlowHalo.x > 0.5) {
- // Past that edge it brightens the page the same way: the page's own colour at its
- // brightest, laid over just thick enough to lift the surface colour to L^(1 / (1 + halo)).
- float edgeDist = uGlowHalo.x > 1.5 ? roundRect(local - uBlob.xy, uBlob.zw, uBlobShape.x) : roundRect(local - vec2(uBodyX, 0.0), uHalf, uRadius);
- float halo = glowAt * uGlowHalo.y * exp(-max(edgeDist, 0.0) / 28.0) * smoothstep(0.0, 14.0, border);
- float pageL = max(dot(uSurface, vec3(0.2126, 0.7152, 0.0722)), 1e-4);
- float pageMax = max(max(uSurface.r, uSurface.g), uSurface.b);
- float cover = clamp((pow(pageL, 1.0 / (1.0 + halo)) / pageL - 1.0) * pageMax / max(1.0 - pageMax, 1e-3), 0.0, 1.0);
- outsideCol = vec4(uSurface / max(pageMax, 1e-3) * cover, cover + outsideCol.a * (1.0 - cover));
- }
- }
-
- // Outside the glass the shadow (and the halo) is the whole pixel: about half of every canvas
- // stops here, before the bevel, the bend and the light are worked out.
- float aa = max(fwidth(dist), 1e-4);
- float mask = 1.0 - smoothstep(-aa, aa, dist);
- // Past the line, the neighbour's own canvas draws the body: here only this glass's share of the
- // shadow the two cast together. Along the line the two canvases cross-fade over a few px: the
- // one beneath draws its glass a little past the line, and the one above fades in over it, so
- // what little the two pictures differ by (each blurs its own picture of the page) does not show
- // as a line. cover: how much of the glass this canvas draws here.
- float cover = 1.0;
- if (uNearCount > 0.0) {
- outsideCol *= share;
- float fade = 4.0 * uCssPx;
- for (int i = 0; i < 4; i++) {
- if (float(i) >= uNearCount) break;
- float s = mine - nearD[i];
- if (uNearPair[i].x > 0.5) cover *= step(s, fade + 2.0 * uDevicePx);
- else cover *= smoothstep(fade, -fade, s);
- }
- if (cover <= 0.0 && !pre) {
- outColor = outsideCol * (1.0 - mask);
- return;
- }
- }
- if (mask <= 0.0 && !pre) {
- outColor = outsideCol;
- return;
- }
-
- // The lighting belongs to the body. A melted blob takes none of it (no reflection, inner
- // shading, rim light or caustic): its face stays flat, and the light fades out where it begins.
- float lit = 1.0;
- if (uBlobShape.y > 0.0) lit = 1.0 - smoothstep(-2.0, 8.0, roundRect(local - vec2(uBodyX, 0.0), uHalf, uRadius));
- // A blob with a glass of its own: its tint, frost and bend take over where the light leaves.
- float own = (1.0 - lit) * uBlobLine.z;
- float frostCover = mix(uFrost, uBlobMat.x, own);
- float frostBlur = mix(uFrostBlur, uBlobMat.y, own);
- float bendCurve = mix(uBendCurve, uBlobMat.z, own);
- float edgeBand = mix(uEdgeBand, uBlobMat.w, own);
-
- // Surface normal from the bevel height field.
- float e = 1.25 * scale;
- float h = height(local, bevel);
- vec2 grad = vec2(height(local + vec2(e, 0.0), bevel) - h, height(local + vec2(0.0, e), bevel) - h) / e;
- vec3 normal = normalize(vec3(-grad * 42.0 * scale, 1.0));
- float depth = clamp(1.0 - h, 0.0, 1.0);
- float edge = 1.0 - smoothstep(0.0, bevel * edgeBand, -dist);
- vec2 dir = normalize(vec2(shape(local + vec2(e, 0.0)) - dist, shape(local + vec2(0.0, e)) - dist) + 1e-6);
-
- vec3 glass;
- if (uTextured > 0.5 && (uRadial.x > 0.0 || uRadial.y > 0.0)) {
- // Radial bend, then frost: the old SVG card's rim.
- float ratio = radialRatio(dist);
- float sharpLod = max(uBlurShift, 0.0);
- if (uFrostBlur > 0.0 && dist < frostReach) {
- float deep = frostDeep(dist);
- vec3 frost = deep > 0.0 ? frostPicture() : vec3(0.0);
- if (deep < 1.0) frost = mix(frostedRadial(local, dist, uFrostBlur * mix(1.0, uFrostEdge, pow(ratio, 1.3))), frost, deep);
- if (pre) {
- outColor = vec4(frost, 1.0);
- return;
- }
- glass = uFrostMix < 1.0 ? mix(bent(uCenter + local, radialBend(local, dist), uDisp * 0.35, sharpLod), frost, uFrostMix) : frost;
- } else {
- glass = bent(uCenter + local, radialBend(local, dist), uDisp * 0.35, sharpLod);
- }
- if (uSaturation != 1.0) glass = max(mix(vec3(dot(glass, vec3(0.2126, 0.7152, 0.0722))), glass, uSaturation), 0.0);
- } else if (uTextured > 0.5) {
- // Refraction: magnify the middle, bend inwards at the rim, split colours slightly.
- // A lens with square corners (uBand > 0) bends deeper than its corner radius. The
- // bend then follows a shape whose corners are at least that round: on the real
- // shape its direction would break along the diagonals. Mask and light keep the real shape.
- float bendEdge = edge;
- vec2 bendDir = dir;
- if (uBand > 0.0) {
- float fd = field(local);
- bendDir = normalize(vec2(field(local + vec2(e, 0.0)) - fd, field(local + vec2(0.0, e)) - fd) + 1e-6);
- bendEdge = 1.0 - smoothstep(0.0, uBand, -fd);
- }
- vec2 magnified = local / (uMag * h + 1.0);
- vec2 bend = -bendDir * refract * pow(bendEdge, bendCurve);
- float split = uDisp * 0.35 * (1.0 - own);
- float lod = max(mix(uBlurCenter, uBlurEdge, pow(bendEdge, 1.3)) + blurShift, 0.0);
- vec2 at = uCenter + magnified;
- if (frostBlur > 0.0 && dist < frostReach) {
- // Frosted (inside the glass only: outside, nothing of it shows). The frost hides the
- // colour split, so one bent point is enough; uFrostMix lets the sharp bend show through.
- float deep = frostDeep(dist);
- vec3 frost = deep > 0.0 ? frostPicture() : vec3(0.0);
- if (deep < 1.0) frost = mix(frosted(at + bend, frostBlur * mix(1.0, uFrostEdge, pow(bendEdge, 1.3))), frost, deep);
- if (pre) {
- outColor = vec4(frost, 1.0);
- return;
- }
- glass = uFrostMix < 1.0 ? mix(bent(at, bend, split, lod), frost, uFrostMix) : frost;
- } else {
- glass = bent(at, bend, split, lod);
- }
- // Vibrancy: what shows through, more (or less) saturated.
- if (uSaturation != 1.0) glass = max(mix(vec3(dot(glass, vec3(0.2126, 0.7152, 0.0722))), glass, uSaturation), 0.0);
- } else {
- // Tinted glass: its own colour in the middle, thinning towards the rim.
- glass = mix(uSurface, uColor, 1.0 - edge * uEdgeClear);
- }
-
- // (The frost's own pass ends here: where there is no frost, its picture is empty.)
- if (pre) {
- outColor = vec4(0.0);
- return;
- }
-
- // Top reflection.
- float top = ((1.0 - smoothstep(-0.05, 0.75, ny)) * (1.0 - nx * 0.12) * uTopRefl * 0.6 + uTopBase) * lit;
- vec3 topDim = dim(1.0 - vec3(1.0, 1.0, 0.72) * top);
- glass *= topDim;
- vec3 seenThrough = glass;
-
- // Frosted resting state: a still lens is the flat highlight colour.
- glass = mix(glass, uColor, frostCover * step(0.5, uTextured));
- // Melted into a neighbour (COHESION), the glass turns into that one's tint or colour across the
- // bridge. Clear glass beside tinted turns all the way by the line, for the tinted side cannot
- // draw what lies behind: that one keeps its own look, and the clear side meets it there.
- float mirrorShare = 1.0;
- if (uNearCount > 0.0) {
- vec3 sumLook = glass;
- float sumW = 1.0;
- float sumMirrors = 1.0;
- for (int i = 0; i < 4; i++) {
- if (float(i) >= uNearCount) break;
- bool clearNear = uNearLook[i].y > 0.5;
- float t = clearNear == (uTextured > 0.5) ? nearT[i] : (clearNear ? 0.0 : min(1.0, 2.0 * nearT[i]));
- float w = t / max(1.0 - t, 1e-4);
- vec3 look = clearNear ? mix(seenThrough, uNearTint[i].rgb, uNearTint[i].a) : mix(uSurface, uNearTint[i].rgb, 1.0 - edge * uEdgeClear) * topDim;
- sumLook += w * look;
- sumW += w;
- sumMirrors += w * uNearMirror[i].w;
- }
- glass = sumLook / sumW;
- // What it mirrors is shared the same way: towards tinted glass, which mirrors nothing, it fades
- // out. Each canvas mirrors its own picture of the surroundings, so the mirror fades out across
- // the bridge too, to nothing on the line: the middle of one body mirrors nothing anyway.
- mirrorShare = sumMirrors / sumW;
- for (int i = 0; i < 4; i++) {
- if (float(i) >= uNearCount) break;
- mirrorShare *= 1.0 - 4.0 * nearT[i] * (1.0 - nearT[i]);
- }
- }
-
- // Inner shading: just inside the rim, a wide band on the left, a deep ring.
- float up = clamp(-dir.y, 0.0, 1.0);
- float right = clamp(dir.x, 0.0, 1.0);
- float left = clamp(-dir.x, 0.0, 1.0);
- float down = clamp(dir.y, 0.0, 1.0);
- float inner = uInner * lit;
- float innerBand = smoothstep(bevel * -0.19, bevel * -0.024, dist);
- glass *= dim(1.0 - innerBand * (up + left * 0.6 + right * 0.3 + down * 0.15) * inner * 2.2);
- float deepBand = smoothstep(bevel * -0.73, bevel * -0.13, dist);
- glass *= dim(1.0 - deepBand * left * inner * 2.0);
- float hx = (dist + bevel * 0.45) / (bevel * 0.26);
- float ring = exp(-hx * hx);
- glass *= dim(1.0 - ring * (right * 0.9 + up * 0.5 + left * 0.4 + down * 0.3) * inner * 1.5);
-
- // Rim light + fresnel; leans a little towards the cursor when there is one.
- float fresnel = pow(clamp(1.0 - normal.z, 0.0, 1.0), 6.0);
- float rimW = max(uDevicePx * 1.1, scale) * uRimWidth;
- float rimLine = 1.0 - smoothstep(0.0, rimW * 1.6, abs(dist + rimW * 1.8));
- float fall = exp(-(ly / (30.0 * scale)) * (ly / (30.0 * scale)));
- float studio = right * right * fall * 0.9 + down * down * 0.2 + left * left * 0.55;
- float lightCos = dot(dir, lightDir);
- float facing = clamp(lightCos, 0.0, 1.0);
- float away = clamp(-lightCos, 0.0, 1.0);
- float aimed = facing * facing * 0.9 + away * away * 0.55;
- float lean = uLightMix * 0.4;
- float rimDir = mix(studio, aimed, lean);
- float front = mix(right, facing, lean);
- float back = mix(left, away, lean);
- // What this point of the glass mirrors. The bevel is a curved mirror: its very edge looks far
- // out, the way the rim faces there, and the look shortens with depth, down to nothing at the
- // band's inner end (uMirror.z). So a neighbour's picture is squeezed into the rim, deepest
- // where it is nearest and thinner as the rim turns away from it: a crescent on a round glass,
- // on a pill a band that tapers round the ends. Each point gathers a soft patch of the
- // surroundings (uSoft wide) at three places along its look, so the picture has no hard edge.
- float into = clamp(-dist / mirrorShape.x, 0.0, 1.0);
- float look = mirrorShape.y * (1.0 - into);
- vec2 rimAt = uCenter + local - dir * dist;
- vec2 across = vec2(-dir.y, dir.x) * mirrorShape.z * 0.7;
- vec3 seen = vec3(0.0);
- for (int i = 0; i < 3; i++) {
- vec2 at = rimAt + dir * look * (0.4 + 0.3 * float(i));
- seen += (around(at, mirrorShape.z) * 0.4 + around(at + across, mirrorShape.z) * 0.3 + around(at - across, mirrorShape.z) * 0.3) * uSeen[i];
- }
- // The light is white where it lands; the far side and the bottom are lit by what bounces back
- // from the surroundings, and take their colour (white from anything dark or grey).
- float seenMax = max(max(seen.r, seen.g), seen.b);
- vec3 bounce = mix(vec3(1.0), seen / max(seenMax, 1e-3), smoothstep(0.08, 0.5, seenMax) * uBounce.y);
- vec3 rimCol = mix(vec3(1.0), bounce, down * 0.6);
- rimCol = mix(rimCol, bounce * uBounce.x, back * 0.85);
- glass += rimCol * (rimLine * rimDir * uRim + fresnel * front * uFresnel * step(0.001, uRim)) * lit;
-
- // Reflection: the rim mirrors what differs from the surface the glass sits on. A neighbour
- // of another colour shows on the rim that faces it; a darker one dims it a little.
- // (uMirror: on the line, in the band inside it, that band's depth, the dimming. uSeen.w: the gain.)
- // much: how far what is seen differs from the surface; hue: that difference at full strength.
- vec3 differs = (seen - uSurface) * uSeen.w;
- float much = max(max(abs(differs.r), abs(differs.g)), abs(differs.b));
- vec3 hue = differs / max(much, 1e-4);
- much = min(much, 1.0);
- // On the rim it is the rim light's own line, no thicker; the band begins inside that line.
- float band = pow(1.0 - into, uFall) * uMirror.y * smoothstep(0.0, rimW * 1.8, -dist);
- float mirror = min(lit * max(rimLine * uMirror.x, band), 1.0) * much * mirrorShare;
- // What it lacks of the surface's colour is taken out of the glass; then the glass is lifted
- // towards the neighbour's colour: dark glass mirrors it on any page.
- glass *= 1.0 - max(-hue, 0.0) * mirror * uMirror.w;
- glass += max(clamp(uSurface + hue, 0.0, 1.0) - glass, 0.0) * mirror;
-
- // Glow: light let in at one point, fading smoothly with distance. It brightens whatever glass
- // is near, evenly from the middle to the rim, a melted blob included (the halo is above),
- // unless the light is kept to the body (uGlowBlob: how much of it the blob takes).
- // Melted, the light of a press on a neighbour runs on into this side of the bridge.
- float glassL = max(dot(glass, vec3(0.2126, 0.7152, 0.0722)), 1e-4);
- float glowHere = glowAt * mix(uGlowBlob, 1.0, lit);
- if (uNearCount > 0.0) glowHere = glowHere * ownLight + glowNear;
- glass *= pow(glassL, 1.0 / (1.0 + glowHere)) / glassL;
-
- // Pointer light (LIGHT): white laid over the glass, strongest where the press landed and falling
- // off evenly to nothing at its radius. (uLight: its centre, its radius, how white.)
- float white = uLight.w > 0.0 ? uLight.w * max(1.0 - length(local - uLight.xy) / max(uLight.z, 1e-3), 0.0) : 0.0;
- if (uNearCount > 0.0) white = white * ownLight + lightNear;
- if (white > 0.0) glass = mix(glass, vec3(1.0), min(white, 1.0));
-
- // Caustic: warm light gathering inside the bottom edge.
- glass += vec3(1.0, 0.92, 0.86) * smoothstep(0.72, 0.98, depth) * down * uCaustic * lit;
-
- // Bordered body (outline buttons): a flat line just inside the edge.
- glass = mix(glass, lineColor, smoothstep(-lineWidth - aa, -lineWidth + aa, dist) * lineAlpha);
- // ...and the white line of a blob with its own glass.
- glass = mix(glass, vec3(1.0), smoothstep(-uBlobLine.x - aa, -uBlobLine.x + aa, dist) * uBlobLine.y * own);
- vec4 col = mix(outsideCol, vec4(clamp(glass, 0.0, 1.0), 1.0), mask * cover);
- // Front layer (selected labels) sits on the frosted pill and fades as the lens clears.
- vec4 fg = texture(uFront, gl_FragCoord.xy / uSize) * mask * cover * uFrost * step(0.5, uTextured);
- outColor = fg + col * (1.0 - fg.a);
-}
-`
-
-function createEngine(): GlassEngine | null {
- const glCanvas = document.createElement('canvas')
- const gl = glCanvas.getContext('webgl2', { alpha: true, premultipliedAlpha: true, antialias: false })
- if (!gl) return null
- const compile = (type: number, src: string) => {
- const s = gl.createShader(type)
- if (!s) return null
- gl.shaderSource(s, src)
- gl.compileShader(s)
- return s
- }
- const vs = compile(gl.VERTEX_SHADER, VERTEX)
- const fs = compile(gl.FRAGMENT_SHADER, FRAGMENT)
- const program = gl.createProgram()
- if (!vs || !fs || !program) return null
- gl.attachShader(program, vs)
- gl.attachShader(program, fs)
- gl.linkProgram(program)
- // A shader's own status is asked for only when linking fails: every such question waits for
- // the GPU, and a program that linked has answered it.
- if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
- for (const s of [vs, fs]) if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) console.warn('[liquid-glass] shader failed to compile', gl.getShaderInfoLog(s))
- return null
- }
- gl.useProgram(program)
- gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer())
- gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW)
- const attr = gl.getAttribLocation(program, 'a')
- gl.enableVertexAttribArray(attr)
- gl.vertexAttribPointer(attr, 2, gl.FLOAT, false, 0, 0)
-
- // Shared canvases for textured lenses: what lies beneath, and what rides on top.
- // Each view keeps its own pair of textures, so a frame that only moves the light re-uses them.
- const layer = () => {
- const canvas = document.createElement('canvas')
- return { canvas, ctx: canvas.getContext('2d') }
- }
- const filters = (mipmapped: boolean) => {
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE)
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR)
- gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, mipmapped ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR)
- }
- const texture = (mipmapped: boolean) => {
- const tex = gl.createTexture()
- gl.bindTexture(gl.TEXTURE_2D, tex)
- gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(4))
- filters(mipmapped)
- if (mipmapped) gl.generateMipmap(gl.TEXTURE_2D)
- return tex
- }
- /** A picture on the GPU, and the size its storage was made for (0 = none yet). */
- type Picture = { tex: WebGLTexture | null; w: number; h: number }
- /**
- * Puts a canvas into a picture, on the texture unit that is active. Its storage is made once
- * for a size (with every mip level, where the picture is seen blurred) and a canvas of that size
- * is then written into it in place: asking for a new image on every upload makes the GPU give
- * the texture new storage each time.
- */
- const upload = (to: Picture, from: HTMLCanvasElement, mipmapped: boolean) => {
- const w = from.width
- const h = from.height
- if (!to.tex || to.w !== w || to.h !== h) {
- if (to.tex) gl.deleteTexture(to.tex)
- to.tex = gl.createTexture()
- gl.bindTexture(gl.TEXTURE_2D, to.tex)
- filters(mipmapped)
- gl.texStorage2D(gl.TEXTURE_2D, mipmapped ? Math.floor(Math.log2(Math.max(w, h))) + 1 : 1, gl.RGBA8, w, h)
- to.w = w
- to.h = h
- } else gl.bindTexture(gl.TEXTURE_2D, to.tex)
- gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, from)
- if (mipmapped) gl.generateMipmap(gl.TEXTURE_2D)
- }
- const back = layer()
- const front = layer()
- if (!back.ctx || !front.ctx) return null
- // The pair is kept per size, for the sizes last drawn: one pair sized to every view in turn was
- // given a new backing store for each of them, on every frame. The front canvas is made when a
- // painter first asks for one.
- type Layer = ReturnType
- type Layers = { back: Layer; front: Layer | null; used: number }
- const LAYER_SIZES = 12
- const layersOf = new Map()
- let layerUse = 0
- const sized = (w: number, h: number) => {
- const l = layer()
- l.canvas.width = w
- l.canvas.height = h
- return l
- }
- const layersFor = (w: number, h: number, fw: number, fh: number) => {
- const key = `${w}x${h}|${fw}x${fh}`
- let l = layersOf.get(key)
- if (!l) {
- if (layersOf.size >= LAYER_SIZES) {
- // The size drawn longest ago gives its canvases back.
- let oldest = ''
- let least = Infinity
- for (const [k, o] of layersOf) if (o.used < least) [oldest, least] = [k, o.used]
- const gone = layersOf.get(oldest)
- for (const o of gone ? [gone.back, gone.front] : []) if (o) o.canvas.width = o.canvas.height = 0
- layersOf.delete(oldest)
- }
- layersOf.set(key, (l = { back: sized(w, h), front: null, used: 0 }))
- }
- if (fw && !l.front) l.front = sized(fw, fh)
- l.used = ++layerUse
- return l
- }
- /**
- * Glass frosted all over shows nothing of the page sharper than its frost: every reading of the
- * page is at mip level log2(0.8 × the frost's softness in device px) − 0.5 or above (frosted in
- * FRAGMENT). The levels beneath that are never read. So the page is painted that many halvings
- * smaller to begin with, `most` at most, and the shader reads it that many levels lower
- * (uBackSkip): a quarter or a sixteenth of the pixels to paint, upload and build mipmaps from,
- * on every frame of live glass. Glass that shows the page sharp anywhere (no frost, a frost
- * mixed with the sharp bend, a blob with a glass of its own) keeps the full picture.
- */
- const BACK_SKIP = { most: 2 }
- const backSkipOf = (m: GlassLens, dpr: number) => {
- const r = m.refraction
- if (!r || m.blob?.material || clamp(r.blurMix ?? 1) < 1) return 0
- const soft = Math.max(0, r.blur ?? 0) * Math.min(1, Math.max(0.05, m.tune?.frostEdge ?? 1)) * dpr
- return soft > 0 ? clamp(Math.floor(Math.log2(soft * 0.8) - 0.5), 0, BACK_SKIP.most) : 0
- }
- type Painted = { back: Picture; front: Picture; w: number; h: number; skip: number; at: number }
- const painted = new Map()
- // A third, small one for what surrounds a lens (its reflection), and each view's own texture of it:
- // where the picture was taken (the canvas's box then, CSS px) and how far past it it reaches.
- const around = layer()
- if (!around.ctx) return null
- /** `busy`: a picture is due (or was taken) while something on the page moved or was lit: it is taken once all is still. */
- type Mirrored = { pic: Picture; w: number; h: number; at: number; left: number; top: number; reach: number; due: boolean; timer: number; busy: boolean }
- /** The pictures of the surroundings taken on this frame. */
- const pictured: Mirrored[] = []
- const mirrored = new Map()
- /** Texels per CSS px of that picture: it is only ever seen blurred. */
- const AROUND_SCALE = 0.5
- /** It is taken again this often, at most (ms). */
- const AROUND_EVERY = 400
- /**
- * While something on the page moves or is lit, a picture already taken is kept, at most this long
- * (ms), and taken again once all is still: taken half way, it would keep a neighbour lit by a
- * press after its light has gone (until something took it again). `live` glass does not wait.
- */
- const AROUND_WAIT = 2000
- /** Something on the page moved or was lit on the last frame, or so far on this one. */
- let busy = false
- let ranLast = false
- // What a lens without layers samples (and ignores): a texture unit is never left empty.
- const blank = { back: texture(true), front: texture(false) }
- // (The frost's picture has a texture unit of its own, never left empty either.)
- gl.activeTexture(gl.TEXTURE3)
- gl.bindTexture(gl.TEXTURE_2D, blank.front)
- gl.activeTexture(gl.TEXTURE0)
- /** The page behind a still lens is read again this often while only the light moves (ms). */
- const REPAINT_EVERY = 120
- gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true)
- gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true)
- gl.uniform1i(gl.getUniformLocation(program, 'uBack'), 0)
- gl.uniform1i(gl.getUniformLocation(program, 'uFront'), 1)
- gl.uniform1i(gl.getUniformLocation(program, 'uAround'), 2)
- /**
- * The frost's own pass. Frost is 32 readings of the page for every pixel of the glass, most of
- * what the GPU does for a frosted card. From `area` device px of glass up, and where the frost
- * is at least `sigma` device px soft, it is first worked out into a picture a fraction of the
- * size: one texel for every (its softness ÷ `texel`) px each way, `most` at most, since a frost
- * that soft has nothing finer to show. The glass then reads that picture, except along its rim
- * (frostDeep in FRAGMENT). Smaller glass gains nothing from a second pass and keeps the one.
- * Measured on the same cards drawn both ways, the two pictures differ by 5 levels in 255 at
- * most, and by more than 1 on fewer than one pixel in a thousand. A blob with a glass of its own (a surface that opens)
- * frosts by a different amount at every point, and keeps the one pass too.
- */
- const FROST_PASS = { area: 150_000, sigma: 5, texel: 2.5, most: 3 }
- gl.uniform1i(gl.getUniformLocation(program, 'uFrostPic'), 3)
- const frostPassAt = gl.getUniformLocation(program, 'uFrostPass')
- /** What uFrostPass.x holds now. */
- let frostPassHeld = 0
- const frostPic = { tex: null as WebGLTexture | null, fbo: null as WebGLFramebuffer | null, w: 0, h: 0, broken: false }
- /** Makes room in the frost's picture for w × h texels (it only grows). False where this GPU cannot draw into it. */
- const frostRoom = (w: number, h: number) => {
- if (frostPic.broken) return false
- if (frostPic.tex && frostPic.w >= w && frostPic.h >= h) return true
- const tw = Math.max(frostPic.w, w)
- const th = Math.max(frostPic.h, h)
- if (frostPic.tex) gl.deleteTexture(frostPic.tex)
- frostPic.tex = gl.createTexture()
- gl.activeTexture(gl.TEXTURE3)
- gl.bindTexture(gl.TEXTURE_2D, frostPic.tex)
- filters(false)
- gl.texStorage2D(gl.TEXTURE_2D, 1, gl.RGBA8, tw, th)
- frostPic.fbo ??= gl.createFramebuffer()
- gl.bindFramebuffer(gl.FRAMEBUFFER, frostPic.fbo)
- gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, frostPic.tex, 0)
- // Asked once for each size the picture grows to: the answer waits for the GPU.
- frostPic.broken = gl.checkFramebufferStatus(gl.FRAMEBUFFER) !== gl.FRAMEBUFFER_COMPLETE
- gl.bindFramebuffer(gl.FRAMEBUFFER, null)
- frostPic.w = tw
- frostPic.h = th
- return !frostPic.broken
- }
- const locations = new Map()
- const u = (name: string) => {
- if (!locations.has(name)) locations.set(name, gl.getUniformLocation(program, name))
- return locations.get(name) ?? null
- }
- // Every uniform of a frame goes through `set`, which keeps the values: a view whose frame
- // would come out exactly as the one already on its canvas is not drawn again, and nothing is
- // asked of the GPU for it. A frame that is drawn sends them with `send`: only those that differ
- // from what the program (one for every view) already holds.
- const sent: number[] = []
- const names: string[] = []
- const sizes: number[] = []
- const set = (name: string, a: number, b?: number, c?: number, d?: number) => {
- names.push(name)
- sizes.push(b === undefined ? 1 : c === undefined ? 2 : d === undefined ? 3 : 4)
- sent.push(a, b ?? 0, c ?? 0, d ?? 0)
- }
- const held = new Map()
- const send = () => {
- for (let i = 0; i < names.length; i++) {
- const at = i * 4
- const a = sent[at]
- const b = sent[at + 1]
- const c = sent[at + 2]
- const d = sent[at + 3]
- let h = held.get(names[i])
- if (h && h[0] === a && h[1] === b && h[2] === c && h[3] === d) continue
- if (!h) held.set(names[i], (h = [a, b, c, d]))
- else [h[0], h[1], h[2], h[3]] = [a, b, c, d]
- const to = u(names[i])
- if (sizes[i] === 1) gl.uniform1f(to, a)
- else if (sizes[i] === 2) gl.uniform2f(to, a, b)
- else if (sizes[i] === 3) gl.uniform3f(to, a, b, c)
- else gl.uniform4f(to, a, b, c, d)
- }
- }
- /** What a view's canvas shows now: its uniforms (empty = nothing usable) and its CSS box. */
- const shown = new WeakMap()
-
- const views = new Set()
- const reduced = window.matchMedia('(prefers-reduced-motion: reduce)')
- let dead = false
-
- // Colour resolving: paint any CSS colour into a 1×1 canvas and read it back.
- const probeCanvas = document.createElement('canvas')
- probeCanvas.width = probeCanvas.height = 1
- const probe = probeCanvas.getContext('2d', { willReadFrequently: true })
- // A colour that means the same on every page and in every theme is resolved once: a scroll
- // or a hover asks for the same few again and again, and asking touches the DOM.
- const ABSOLUTE = /^(?:#[0-9a-f]{3,8}|(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch|color)\([^()]*\)|black|white|transparent)$/i
- const resolved = new Map()
- const resolveColor = (css: string): Rgba => {
- if (!probe) return [1, 1, 1, 1]
- const fixed = ABSOLUTE.test(css) && !/currentcolor/i.test(css)
- const known = fixed ? resolved.get(css) : undefined
- if (known) return [known[0], known[1], known[2], known[3]]
- const span = document.createElement('span')
- span.style.color = css
- // Measured on , never inside a host whose children are observed.
- document.body.appendChild(span)
- const computed = getComputedStyle(span).color
- span.remove()
- probe.clearRect(0, 0, 1, 1)
- probe.fillStyle = computed
- probe.fillRect(0, 0, 1, 1)
- const [r, g, b, a] = probe.getImageData(0, 0, 1, 1).data
- if (fixed) {
- if (resolved.size > 400) resolved.clear()
- resolved.set(css, [r / 255, g / 255, b / 255, a / 255])
- }
- return [r / 255, g / 255, b / 255, a / 255]
- }
-
- // Cursor light: shared, fades in on the first mouse move, out when the pointer leaves.
- const pointer = { x: 0, y: 0, active: false, moved: false, mix: 0 }
-
- // Pointer light (LIGHT). `beam` is the pointer that lights: where it is, what it is over
- // and which pointer is held (`id`, -1 = none).
- // Each lit view keeps its own light: how bright (a spring), where on the glass, and why.
- const beam = { x: 0, y: 0, over: null as EventTarget | null, id: -1 }
- type Lit = {
- glow: Spring
- /** The light's centre, relative to the lens centre (CSS px). */
- x: number
- y: number
- press: boolean
- key: boolean
- /** The glass's host takes no pointer events (a badge): the pointer only has to be over the glass. */
- free: boolean
- /** The body on screen, as last drawn: centre, half size and its shift from the lens centre. */
- sx: number
- sy: number
- hx: number
- hy: number
- bodyX: number
- /** A second box melted into the body (a surface that has opened), as last drawn: its centre from the lens centre, and its half size. */
- blob: { x: number; y: number; hx: number; hy: number } | null
- /** The press landed on that box: the light takes its size from it. */
- onBlob: boolean
- }
- const lights = new Map()
- let relit = false
- const hostOf = (v: GlassView) => v.canvas.parentElement
- /** The pointer is on this glass: inside its body, and on its host (not on something lying over it). */
- const onBlob = (s: Lit) => !!s.blob && Math.abs(beam.x - (s.sx - s.bodyX + s.blob.x)) <= s.blob.hx && Math.abs(beam.y - (s.sy + s.blob.y)) <= s.blob.hy
- const under = (v: GlassView, s: Lit) => {
- if ((Math.abs(beam.x - s.sx) > s.hx || Math.abs(beam.y - s.sy) > s.hy) && !onBlob(s)) return false
- if (s.free) return true
- const host = hostOf(v)
- return !!host && beam.over instanceof Node && host.contains(beam.over) && !host.matches(':disabled, [data-disabled], [aria-disabled="true"]')
- }
- /** A press belongs to the innermost glass under it: a button on a card lights up, the card does not. */
- const innermost = (v: GlassView) => {
- const host = hostOf(v)
- for (const [other, s] of lights) {
- const inner = hostOf(other)
- if (other !== v && !s.free && other.visible && host && inner && inner !== host && host.contains(inner) && under(other, s)) return false
- }
- return true
- }
- /** Advances a view's light; true while it still changes. */
- const stepLight = (v: GlassView, dt: number, still: boolean) => {
- const s = lights.get(v)
- if (!s) return false
- const held = s.press || s.key
- const target = LIGHT.on && held ? LIGHT.press : 0
- if (still) {
- const changed = s.glow.x !== target
- s.glow.x = target
- s.glow.v = 0
- return changed
- }
- return stepSpring(s.glow, target, held ? { omega: (2 * Math.PI) / Math.max(LIGHT.rise, 0.01), zeta: clamp(1 - LIGHT.riseBounce, 0.05, 1) } : { omega: (2 * Math.PI) / Math.max(LIGHT.fade, 0.01), zeta: 1 }, dt)
- }
-
- // The flash of a press on a button (GLOW): the rule above GLOW, applied. A view that says
- // `button: true` is lit where a press lands on it (or at its centre, by Space / Enter): the
- // light comes up, holds for as long as the press does (`hold` at least) and fades as it
- // spreads. Each button keeps its own: how bright, how far it has spread, where it landed (from
- // the host's centre, px), how long it still holds, how many presses' worth is asked for, how
- // small the glass is (which set of values it takes), its height, and what holds it.
- // A surface keeps one too, for a choice pressed in it (`choice`): the same light with GLOW's
- // `select` values, measured in the choice's own height.
- type Flash = { glow: Spring; spread: Spring; x: number; y: number; hold: number; level: number; small: number; height: number; by: number; key: boolean; choice: boolean }
- /** What counts as a choice inside a surface. */
- const CHOICES = ':is([role=option],[role=menuitem],[data-glass-item],[data-glass-pick])'
- const flashes = new Map()
- const flashTune = (small: number): typeof GLOW => {
- if (small <= 0) return GLOW
- if (small >= 1) return GLOW_SMALL
- const mixed = { ...GLOW }
- for (const name of Object.keys(mixed) as (keyof typeof GLOW)[]) mixed[name] = lerp(GLOW[name], GLOW_SMALL[name], small)
- return mixed
- }
- /**
- * Light on this glass at this point (viewport px), or at its centre. Presses that land before
- * the last has faded add up. `choice`: the element chosen inside a surface, whose light it is.
- */
- const flash = (v: GlassView, x?: number, y?: number, choice?: HTMLElement) => {
- const host = hostOf(v)
- if (!host) return null
- let f = flashes.get(v)
- if (!f) flashes.set(v, (f = { glow: { x: 0, v: 0 }, spread: { x: 0, v: 0 }, x: 0, y: 0, hold: 0, level: 0, small: 0, height: 0, by: -1, key: false, choice: false }))
- const r = host.getBoundingClientRect()
- // A light that is still bright keeps spreading from where it is: only a fresh one starts small.
- if (f.glow.x < 0.08) f.spread.x = f.spread.v = 0
- f.x = x === undefined ? 0 : clamp(x - (r.left + r.width / 2), -r.width / 2, r.width / 2)
- f.y = y === undefined ? 0 : clamp(y - (r.top + r.height / 2), -r.height / 2, r.height / 2)
- f.choice = !!choice
- f.height = (choice ?? host).offsetHeight
- // (A surface takes the wide set of values, whatever its own shape.)
- f.small = choice ? 0 : 1 - smooth(2, 2.4, host.offsetWidth / Math.max(f.height, 1))
- const tune = flashTune(f.small)
- f.level = Math.min(Math.max(f.glow.x, 0) + (choice ? tune.select : 1), tune.stack)
- f.hold = tune.hold
- wake()
- return f
- }
- /** Advances a button's flash; true while it still changes. */
- const stepFlash = (v: GlassView, dt: number, still: boolean) => {
- const f = flashes.get(v)
- if (!f) return false
- if (still) {
- const changed = f.glow.x !== 0
- f.glow.x = f.glow.v = f.spread.x = f.spread.v = f.hold = 0
- return changed
- }
- const lit = f.by !== -1 || f.key || f.hold > 0
- const holding = f.hold > 0
- f.hold = Math.max(0, f.hold - dt)
- const tune = flashTune(f.small)
- const a = stepSpring(f.glow, lit ? f.level : 0, { omega: lit ? tune.riseSpeed : tune.fadeSpeed, zeta: 1 }, dt)
- const b = stepSpring(f.spread, lit || f.glow.x > 0.004 ? 1 : 0, { omega: tune.spreadSpeed, zeta: 1 }, dt)
- // A press held still changes nothing: the loop rests until the hold runs out or the press ends.
- return holding || a || (b && f.glow.x > 0.004)
- }
- /** The flash as a lens's `glow`, for a lens that brings none of its own. (The canvas is scaled with the host: the light is measured on the page, so it is divided by that scale.) */
- const flashOf = (v: GlassView): GlassLens['glow'] => {
- const f = flashes.get(v)
- if (!f || f.glow.x <= 0.004) return undefined
- const tune = flashTune(f.small)
- const k = Math.max(0.5, v.grow ?? 1)
- const far = clamp(f.spread.x)
- const reach = f.choice ? tune.selectReach + tune.selectSpread * far : tune.reach + tune.spread * far
- return { x: f.x / k, y: f.y / k, r: f.height * reach, amount: Math.max(0, f.glow.x) * tune.amount, blob: 1 }
- }
-
- // Pull (PULL): glass a held pointer drags after itself, where the view asks for it (buttons).
- // One pointer holds one glass, the innermost under the press. The engine moves its host (CSS `translate`) and stretches it (CSS
- // `scale`, times the view's own `grow`), and lets go when the pointer does.
- type Pulled = {
- /** How far the glass has come after the pointer, each way (px). */
- x: Spring
- y: Spring
- /** The pointer that holds it: where it pressed, where it is, and where the glass rested then. */
- by: { id: number; x: number; y: number; nowX: number; nowY: number; cx: number; cy: number; lastX: number; lastY: number; size: number } | null
- /** How fast the glass's own place on the page moves while held (px/s, smoothed). */
- driftX: number
- driftY: number
- /** The host's own CSS `translate` (a centring class), which the pull adds to. */
- own: string[] | null
- /** What the engine last wrote on the host. */
- moved: string
- scaled: string
- }
- const pulls = new Map()
- const pulledOf = (v: GlassView) => {
- let p = pulls.get(v)
- if (!p) pulls.set(v, (p = { x: { x: 0, v: 0 }, y: { x: 0, v: 0 }, by: null, driftX: 0, driftY: 0, own: null, moved: '', scaled: '' }))
- return p
- }
- /** The centre of the glass on screen where it rests, without the pull. */
- const restOf = (host: HTMLElement, p: Pulled) => {
- const r = host.getBoundingClientRect()
- return { x: r.left + r.width / 2 - p.x.x, y: r.top + r.height / 2 - p.y.x }
- }
- const letGo = (v: GlassView, p: Pulled) => {
- p.by = null
- v.held = false
- }
- /** Advances a view's pull and writes its host's `translate` and `scale`; true while it still moves. */
- const stepPull = (v: GlassView, dt: number, still: boolean) => {
- const p = pulls.get(v)
- if (!p && v.grow === undefined) return false
- const host = hostOf(v)
- if (!host) return false
- const s = p ?? pulledOf(v)
- if (s.by && (v.pull !== true || !PULL.on)) letGo(v, s)
- let sx = 1
- let sy = 1
- let moving = false
- if (still) {
- s.x.x = s.x.v = s.y.x = s.y.v = s.driftX = s.driftY = 0
- } else if (s.by || s.x.x !== 0 || s.y.x !== 0 || s.x.v !== 0 || s.y.v !== 0 || s.driftX !== 0 || s.driftY !== 0) {
- const w = Math.max(host.offsetWidth, 1)
- const h = Math.max(host.offsetHeight, 1)
- const size = Math.max(w, h)
- const small = size <= PULL.smallUntil
- let tx = 0
- let ty = 0
- const by = s.by
- if (by) {
- const at = restOf(host, s)
- // Small glass: how far the pointer has gone since the press. Larger: how far past the edge it is.
- const dx = small ? by.nowX - by.x - (at.x - by.cx) : by.nowX - clamp(by.nowX, at.x - w / 2, at.x + w / 2)
- const dy = small ? by.nowY - by.y - (at.y - by.cy) : by.nowY - clamp(by.nowY, at.y - h / 2, at.y + h / 2)
- const limit = small ? PULL.smallReach + PULL.smallReachPerPx * size : Math.min(PULL.reachMax, PULL.reach + PULL.reachPerPx * size)
- tx = rubberBand(dx, limit, PULL.resistance)
- ty = rubberBand(dy, limit, PULL.resistance)
- if (dt > 0) {
- s.driftX += ((at.x - by.lastX) / dt - s.driftX) * Math.min(1, dt * PULL.driftIn)
- s.driftY += ((at.y - by.lastY) / dt - s.driftY) * Math.min(1, dt * PULL.driftIn)
- }
- by.lastX = at.x
- by.lastY = at.y
- } else {
- s.driftX = Math.abs(s.driftX) < 1 ? 0 : s.driftX * Math.exp(-dt * PULL.driftOut)
- s.driftY = Math.abs(s.driftY) < 1 ? 0 : s.driftY * Math.exp(-dt * PULL.driftOut)
- }
- const spring = by ? { omega: (2 * Math.PI) / (PULL.follow + PULL.followPerPx * by.size), zeta: 1 } : { omega: (2 * Math.PI) / PULL.release, zeta: 1 - PULL.releaseBounce }
- const mx = stepSpring(s.x, tx, spring, dt)
- const my = stepSpring(s.y, ty, spring, dt)
- const most = small ? PULL.smallStretchMax : PULL.stretchMax
- const along = (pull: Spring, length: number, drift: number) =>
- Math.min(most, (PULL.stretch * Math.abs(pull.x)) / length + PULL.stretchPerSpeed * Math.abs(pull.v) + PULL.stretchPerDrift * Math.abs(drift))
- const kx = along(s.x, w, s.driftX)
- const ky = along(s.y, h, s.driftY)
- sx = (1 + kx) / Math.sqrt(1 + ky)
- sy = (1 + ky) / Math.sqrt(1 + kx)
- moving = !!by || mx || my || s.driftX !== 0 || s.driftY !== 0
- }
- const on = Math.abs(s.x.x) > 0.01 || Math.abs(s.y.x) > 0.01
- const px = `${s.x.x.toFixed(3)}px`
- const py = `${s.y.x.toFixed(3)}px`
- const moved = !on ? '' : s.own ? `calc(${s.own[0]} + ${px}) calc(${s.own[1] ?? '0px'} + ${py})` : `${px} ${py}`
- const grow = v.grow ?? 1
- const even = Math.abs(sx - 1) < 1e-4 && Math.abs(sy - 1) < 1e-4
- const scaled = even ? (grow === 1 ? '' : grow.toFixed(4)) : `${(grow * sx).toFixed(5)} ${(grow * sy).toFixed(5)}`
- // The frame that brings the host to rest is still drawn: a view that draws the pull itself (see `pulled`) must see it end.
- if (moved !== s.moved || scaled !== s.scaled) moving = true
- if (moved !== s.moved) host.style.translate = s.moved = moved
- if (scaled !== s.scaled) host.style.scale = s.scaled = scaled
- const at = v.pulled ?? (v.pulled = { x: 0, y: 0, sx: 1, sy: 1 })
- at.x = on ? s.x.x : 0
- at.y = on ? s.y.x : 0
- at.sx = even ? 1 : sx
- at.sy = even ? 1 : sy
- return moving
- }
-
- /** The way the cursor light comes from for a lens (uLightDir, as an angle), and how much the rim leans to it (uLightMix). */
- const aimOf = (m: GlassLens) => {
- const dx = pointer.x - m.screenX
- const dy = pointer.y - m.screenY
- const d = Math.hypot(dx, dy)
- // The light turns in half-degree steps (one step is less than a level of rim light on an
- // 8-bit screen), and stays put while it is off: a cursor moving far away, or over glass
- // without cursor light, leaves the frame as it is.
- const mix = m.cursorLight ? pointer.mix : 0
- const aim = mix > 0 && d > 0.5 ? (Math.round(Math.atan2(dy, dx) * (360 / Math.PI)) * Math.PI) / 360 : -Math.PI / 2
- return { aim, mix }
- }
- /** A glass's light of a press (LIGHT) as its shader takes it (uLight): centre and radius (canvas px, from the lens centre) and how white; null while it is out. */
- const shineOf = (lit: Lit, m: GlassLens): [number, number, number, number] | null => {
- const shine = LIGHT.on && m.pointerLight !== false ? clamp(lit.glow.x) : 0
- if (shine <= 0) return null
- const pageL = 0.2126 * m.surface[0] + 0.7152 * m.surface[1] + 0.0722 * m.surface[2]
- // (A press on a surface beside the control takes the surface's size, not the control's.)
- const side = lit.onBlob && lit.blob ? Math.max(lit.blob.hx, lit.blob.hy) : Math.max(m.hx, m.hy)
- const span = clamp(LIGHT.size * 2 * side, LIGHT.sizeMin, Math.max(LIGHT.sizeMin, LIGHT.sizeMax))
- return [lit.x, lit.y, span, shine * clamp(lerp(LIGHT.strengthDark, LIGHT.strength, smooth(0.25, 0.6, pageL)))]
- }
-
- // Cohesion (COHESION): buttons near each other melt into one body. On a frame that changes a
- // button, every button on screen is measured as it is (its body on the page, and what its look
- // depends on), and each takes the ones within reach, nearest first, four at most. `nears` holds
- // what its shader is given for them (uNear… in FRAGMENT): NEAR_VALUES numbers (nine vec4) for each.
- type Melt = {
- v: GlassView
- m: GlassLens
- host: Element
- /** Screen px per canvas px, and the lens centre on screen (the canvas's own (cx, cy)). */
- g: number
- sx: number
- sy: number
- /** The body on screen: centre, half size, corner radius and the radius its bend follows (px). */
- x: number
- y: number
- hx: number
- hy: number
- r: number
- fr: number
- /** Its height at rest, and one of its design units, on screen (px). */
- rest: number
- du: number
- }
- const NEAR = 4
- const NEAR_NAMES = Array.from({ length: NEAR }, (_, i) =>
- ['uNear', 'uNearShape', 'uNearTint', 'uNearLine', 'uNearLook', 'uNearShade', 'uNearMirror', 'uNearGlow', 'uNearLight'].map((name) => `${name}[${i}]`),
- )
- const NEAR_PAIR = Array.from({ length: NEAR }, (_, i) => `uNearPair[${i}]`)
- /** Per neighbour: its vec4s, then whether its canvas lies over this one's and how joined the two are. */
- const NEAR_VALUES = NEAR_NAMES[0].length * 4 + 2
- /** How much a lens mirrors of its surroundings (see `mirror` in `draw`): only clear glass does. */
- const mirrorOf = (m: GlassLens) => (m.refraction ? m.strength * Math.max(0, m.tune?.mirror ?? 1) * clamp((1 - m.refraction.frost) / 0.4) : 0)
- /** How far into the glass the mirrored band goes, how far the rim looks, and how soft the picture is (CSS px; see uMirror.z, uReach and uSoft). */
- const mirrorShapeOf = (m: GlassLens) => {
- const reached = m.reflection ? clamp(m.reflection.height * MIRROR.reach, MIRROR.reachMin, Math.max(MIRROR.reachMin, MIRROR.reachMax)) : 0
- const deep = Math.max(0.01, MIRROR.depth) * Math.max(1, Math.min(m.hx, m.hy, reached || Infinity))
- return { deep, reach: mirrorOf(m) > 0 && m.reflection ? reached : 0, soft: Math.max(0, MIRROR.soft) * reached }
- }
- const nears = new Map()
- /** The buttons that were on screen when they were last measured: one that comes or goes changes its neighbours. */
- let shownButtons = new Set()
- let meltsChanged = false
- const measure = (v: GlassView, m: GlassLens | null | undefined): Melt | null => {
- const host = hostOf(v)
- if (!host || !m || m.width < 2 || m.height < 2) return null
- const g = m.scale && m.scale > 0 ? m.scale : 1
- const radius = Math.max(0, Math.min(m.radius, m.hx - 0.5, m.hy - 0.5))
- const band = m.refraction ? (m.band ?? 0) * m.unit : 0
- return {
- v,
- m,
- host,
- g,
- sx: m.screenX,
- sy: m.screenY,
- x: m.screenX + m.bodyX * g,
- y: m.screenY,
- hx: Math.max(m.hx, 0.5 * m.unit) * g,
- hy: Math.max(m.hy, 0.5 * m.unit) * g,
- r: radius * g,
- fr: Math.min(Math.max(radius, band), Math.max(0, Math.min(m.hx, m.hy) - 0.5)) * g,
- rest: DESIGN_HEIGHT * m.unit * g,
- du: m.unit * g,
- }
- }
- /**
- * What glass `a` takes for its neighbour `b` (see uNear… in FRAGMENT), in a's design units, at
- * bridge softness `k` (screen px), the two `join`ed this much (0 = apart, 1 = one body for the light).
- */
- const nearValues = (a: Melt, b: Melt, k: number, join: number, out: number[]) => {
- const to = 1 / a.du
- const m = b.m
- const r = m.refraction
- const width = m.border ? Math.max(0, m.borderWidth ?? 1) : 0
- const line = m.border ?? m.color
- out.push((b.x - a.sx) * to, (b.y - a.sy) * to, b.hx * to, b.hy * to)
- out.push(b.r * to, b.fr * to, Math.max(k * to, 1e-3), Math.max(m.bevel, 2) * b.du * to)
- out.push(m.color[0], m.color[1], m.color[2], r ? clamp(r.frost) : 0)
- out.push(line[0], line[1], line[2], width > 0 ? clamp(m.borderAlpha ?? 1) : 0)
- out.push((r?.refract ?? 0) * b.du * to, r ? 1 : 0, width * b.g * to, aimOf(m).aim)
- out.push(m.shadow * m.strength, m.shadowSoftness * b.du * to, m.shadowOffset * b.du * to, b.du * to)
- const shapeB = mirrorShapeOf(m)
- const mine = mirrorOf(a.m)
- out.push(shapeB.deep * b.g * to, shapeB.reach * b.g * to, shapeB.soft * b.g * to, mine > 0 ? mirrorOf(m) / mine : 0)
- // Its light of a press, where it is on screen.
- const glow = m.glow ?? flashOf(b.v)
- if (glow) out.push((b.sx + glow.x * b.g - a.sx) * to, (b.sy + glow.y * b.g - a.sy) * to, glow.r * b.g * to, Math.max(0, glow.amount))
- else out.push(0, 0, 1, 0)
- const lit = lights.get(b.v)
- const light = lit ? shineOf(lit, m) : null
- if (light) out.push((b.sx + light[0] * b.g - a.sx) * to, (b.sy + light[1] * b.g - a.sy) * to, light[2] * b.g * to, light[3])
- else out.push(0, 0, 1, 0)
- // Glass later on the page is painted over glass before it.
- out.push(a.host.compareDocumentPosition(b.host) & Node.DOCUMENT_POSITION_FOLLOWING ? 1 : 0, join)
- }
- /**
- * Measures every button on screen and works out each one's neighbours. `lensOf` holds the lenses
- * already read this frame; any other is read now. Returns the views whose neighbours (as their
- * shaders take them) changed, and those whose `near` changed, which must paint what lies behind again.
- */
- const cohere = (lensOf: Map) => {
- const pool: Melt[] = []
- const showing = new Set()
- for (const v of views) {
- if (v.button !== true || !v.visible) continue
- showing.add(v)
- let m = lensOf.get(v)
- if (m === undefined) lensOf.set(v, (m = v.lens(false)))
- const at = measure(v, m)
- if (at) pool.push(at)
- }
- shownButtons = showing
- const changed = new Set()
- const regrouped = new Set()
- const melted = new Set()
- for (const a of pool) {
- const found: { b: Melt; gap: number; k: number; join: number }[] = []
- for (const b of pool) {
- if (b === a || a.host.contains(b.host) || b.host.contains(a.host)) continue
- const soft = cohesionSoftness(Math.min(a.rest, b.rest))
- if (soft <= 0) continue
- const gap = Math.max(Math.abs(b.x - a.x) - a.hx - b.hx, Math.abs(b.y - a.y) - a.hy - b.hy)
- // The bridge eases in as they near each other: none at `soft` apart, all of it at half that.
- const k = soft * (1 - smooth(0.5, 1, gap / soft))
- // Joined from the moment the bridge forms (half of `soft` apart), fully once it has some body
- // (a quarter of `soft` apart); for the light, by as much as COHESION.light lets it run on.
- if (k > 0.05) found.push({ b, gap, k, join: (1 - smooth(soft / 4, soft / 2, gap)) * clamp(COHESION.light) })
- }
- found.sort((p, q) => p.gap - q.gap)
- const values: number[] = []
- const hosts: Element[] = []
- for (const { b, k, join } of found.slice(0, NEAR)) {
- nearValues(a, b, k, join, values)
- hosts.push(b.host)
- }
- const was = nears.get(a.v)
- if ((was?.length ?? 0) !== values.length || values.some((x, i) => x !== was![i])) changed.add(a.v)
- if (values.length) {
- nears.set(a.v, values)
- melted.add(a.v)
- } else nears.delete(a.v)
- const before = a.v.near ?? []
- if (before.length !== hosts.length || hosts.some((h) => !before.includes(h))) {
- a.v.near = hosts.length ? hosts : undefined
- regrouped.add(a.v)
- }
- }
- // A button that has left the screen (or the page) melts into nothing any more.
- for (const v of [...nears.keys()]) {
- if (melted.has(v)) continue
- nears.delete(v)
- changed.add(v)
- }
- return { changed, regrouped }
- }
-
- const draw = (v: GlassView, refresh: boolean, repaint: boolean, read?: GlassLens | null) => {
- const m = read !== undefined ? read : v.lens(refresh)
- let on = shown.get(v)
- if (!on) shown.set(v, (on = { sent: [], box: '' }))
- if (!m || m.width < 2 || m.height < 2) {
- v.ctx.clearRect(0, 0, v.canvas.width, v.canvas.height)
- on.sent.length = 0
- return
- }
- // The canvas's box is written only when it changes.
- const box = `${m.left}|${m.top}|${m.width}|${m.height}`
- if (box !== on.box) {
- on.box = box
- const st = v.canvas.style
- st.left = `${m.left}px`
- st.top = `${m.top}px`
- st.width = `${m.width}px`
- st.height = `${m.height}px`
- }
- const dpr = Math.min(window.devicePixelRatio || 1, 2)
- const devW = Math.max(2, Math.round(m.width * dpr))
- const devH = Math.max(2, Math.round(m.height * dpr))
- if (v.canvas.width !== devW || v.canvas.height !== devH) {
- v.canvas.width = devW
- v.canvas.height = devH
- on.sent.length = 0
- }
-
- // Nothing is asked of the GPU until this frame is known to differ from the one on the canvas:
- // the layers are painted here, on plain 2D canvases, and put into their textures at the end.
- const unit = m.unit
- const r = m.refraction
- /** The layers are the ones this view was last drawn with. */
- let fresh = true
- let p: Painted | undefined
- /** The layers painted on this frame, to upload. */
- let layers: Layers | undefined
- // A painter that takes only `back` has no front layer: none is cleared or uploaded.
- const fronted = !!r && r.paint.length > 1
- const skip = backSkipOf(m, dpr)
- if (r) {
- p = painted.get(v)
- if (!p) painted.set(v, (p = { back: { tex: null, w: 0, h: 0 }, front: { tex: null, w: 0, h: 0 }, w: 0, h: 0, skip: 0, at: 0 }))
- const now = performance.now()
- const sized = p.w === devW && p.h === devH && p.skip === skip
- fresh = !repaint && sized && now - p.at < REPAINT_EVERY
- if (!fresh) {
- // The page's picture, smaller where the frost never reads it at full size (BACK_SKIP),
- // and fitted to its canvas, so that it covers the glass's canvas exactly as before.
- const bw = skip ? Math.max(2, Math.ceil(devW / 2 ** skip)) : devW
- const bh = skip ? Math.max(2, Math.ceil(devH / 2 ** skip)) : devH
- const l = layersFor(bw, bh, fronted ? devW : 0, fronted ? devH : 0)
- l.back.ctx!.setTransform(1, 0, 0, 1, 0, 0)
- l.back.ctx!.clearRect(0, 0, bw, bh)
- if (skip) l.back.ctx!.setTransform(bw / m.width, 0, 0, bh / m.height, 0, 0)
- else l.back.ctx!.setTransform(dpr, 0, 0, dpr, 0, 0)
- if (fronted && l.front) {
- l.front.ctx!.setTransform(1, 0, 0, 1, 0, 0)
- l.front.ctx!.clearRect(0, 0, devW, devH)
- l.front.ctx!.setTransform(dpr, 0, 0, dpr, 0, 0)
- }
- // A painter that says nothing changed keeps the textures it already has.
- fresh = r.paint(l.back.ctx!, (l.front ?? front).ctx!) === false && sized
- if (!fresh) {
- layers = l
- p.w = devW
- p.h = devH
- p.skip = skip
- p.at = now
- }
- }
- }
- sent.length = names.length = sizes.length = 0
- // The surroundings, for the reflection. The picture is taken when it is first needed, and
- // again when sizes and colours are re-read or the canvas changes size, AROUND_EVERY apart at
- // most (a change that comes sooner waits its turn). A scroll takes none: what surrounds the
- // glass rides along. Until then the picture stays where it was taken, even if the canvas has
- // moved since.
- // Only clear glass mirrors: in full while its own colour covers it no more than a clear
- // button's tint does (0.6), less as the cover grows, and not at all once the glass is its
- // own colour (tinted glass, a lens frosted over at rest, a control painted in its fill).
- // Unlit glass mirrors nothing either. Glass that mirrors nothing takes no picture.
- const clear = r ? clamp((1 - r.frost) / 0.4) : 0
- const mirror = m.strength * Math.max(0, m.tune?.mirror ?? 1) * clear
- const f = mirror > 0 ? m.reflection : undefined
- if (refresh && m.reflection && !f) {
- const idle = mirrored.get(v)
- if (idle) idle.due = true
- }
- /** A picture of the surroundings taken on this frame, to upload. */
- let picture: Mirrored | undefined
- if (f) {
- let a = mirrored.get(v)
- if (!a) mirrored.set(v, (a = { pic: { tex: null, w: 0, h: 0 }, w: 0, h: 0, at: 0, left: 0, top: 0, reach: 0, due: true, timer: 0, busy: false }))
- const taken = a
- const reach = clamp(f.height * MIRROR.reach, MIRROR.reachMin, Math.max(MIRROR.reachMin, MIRROR.reachMax))
- const aw = Math.max(2, Math.ceil((m.width + 2 * reach) * AROUND_SCALE))
- const ah = Math.max(2, Math.ceil((m.height + 2 * reach) * AROUND_SCALE))
- const now = performance.now()
- if (refresh || (f.live && repaint) || a.w !== aw || a.h !== ah || a.reach !== reach) a.due = true
- if (a.due && a.w && busy && !f.live && now - a.at < AROUND_WAIT) {
- // It waits for all to be still (see AROUND_WAIT): the picture it has is kept meanwhile.
- a.busy = true
- } else if (a.due && a.w && now - a.at < AROUND_EVERY) {
- if (!a.timer)
- a.timer = window.setTimeout(
- () => {
- taken.timer = 0
- if (mirrored.get(v) !== taken) return
- v.repaint = true
- wake()
- },
- AROUND_EVERY - (now - a.at),
- )
- } else if (a.due) {
- a.due = false
- if (around.canvas.width !== aw || around.canvas.height !== ah) {
- around.canvas.width = aw
- around.canvas.height = ah
- }
- const c = around.ctx!
- c.setTransform(1, 0, 0, 1, 0, 0)
- c.clearRect(0, 0, aw, ah)
- c.setTransform(AROUND_SCALE, 0, 0, AROUND_SCALE, reach * AROUND_SCALE, reach * AROUND_SCALE)
- f.paint(c, reach)
- picture = a
- a.w = aw
- a.h = ah
- a.at = now
- a.left = m.left
- a.top = m.top
- a.reach = reach
- pictured.push(a)
- fresh = false
- }
- set('uAroundBox', (a.left - m.left - a.reach) / unit, (a.top - m.top - a.reach) / unit, a.w / AROUND_SCALE / unit, a.h / AROUND_SCALE / unit)
- set('uAroundScale', AROUND_SCALE * unit)
- set('uReach', reach / unit)
- } else {
- set('uAroundBox', 0, 0, 1, 1)
- set('uAroundScale', 1)
- set('uReach', 0)
- }
- set('uTextured', r ? 1 : 0)
- set('uRefract', r?.refract ?? 0)
- set('uMag', r?.magnify ?? 0)
- set('uDisp', r?.dispersion ?? 0)
- set('uBlurCenter', r?.blurCenter ?? 0)
- set('uBlurEdge', r?.blurEdge ?? 0)
- // Blur level follows screen density (reference: 2.27 device px per design unit).
- set('uBlurShift', Math.log2(Math.max((unit * dpr) / 2.27, 1e-3)))
- set('uFrost', r?.frost ?? 0)
- set('uBackSkip', skip)
- set('uFrostBlur', Math.max(0, r?.blur ?? 0) / unit)
- set('uFrostMix', clamp(r?.blurMix ?? 1))
- // Radial bend: a share of the viewport per axis, as the SVG card's map was.
- const radial = Math.max(0, r?.radial ?? 0)
- set('uRadial', (radial * window.innerWidth) / unit, (radial * window.innerHeight) / unit)
- set('uCssPx', 1 / unit)
- set('uSize', devW, devH)
- set('uUnit', unit * dpr)
- set('uDevicePx', 1 / (unit * dpr))
- set('uCenter', m.cx / unit, m.cy / unit)
- set('uHalf', Math.max(m.hx / unit, 0.5), Math.max(m.hy / unit, 0.5))
- const radius = Math.max(0, Math.min(m.radius, m.hx - 0.5, m.hy - 0.5) / unit)
- set('uRadius', radius)
- const band = r ? (m.band ?? 0) : 0
- set('uBand', band)
- set('uFieldRadius', Math.min(Math.max(radius, band), Math.max(0, (Math.min(m.hx, m.hy) - 0.5) / unit)))
- set('uBodyX', m.bodyX / unit)
- set('uDrop', (m.droplet?.x ?? 0) / unit, (m.droplet?.r ?? 0) / unit, (m.droplet?.k ?? 0) / unit)
- const blob = m.blob
- set('uBlob', (blob?.x ?? 0) / unit, (blob?.y ?? 0) / unit, (blob?.hx ?? 0) / unit, (blob?.hy ?? 0) / unit)
- set('uBlobShape', (blob?.r ?? 0) / unit, (blob?.k ?? 0) / unit)
- set('uBlobNeck', (blob?.neck?.x ?? 0) / unit, (blob?.neck?.w ?? 0) / unit)
- set('uBlobFade', blob?.fade?.amount ?? 0, blob?.fade?.reach ?? 0.5)
- const mat = blob?.material
- set('uBlobMat', clamp(mat?.frost ?? 0), Math.max(0, mat?.blur ?? 0) / unit, Math.max(0.05, mat?.bendCurve ?? 1.6), 0.35 * Math.max(0.05, mat?.bendDepth ?? 1))
- set('uBlobLine', Math.max(0, mat?.borderWidth ?? 0) / unit, clamp(mat?.borderAlpha ?? 0), mat ? 1 : 0)
- set('uBevel', Math.max(m.bevel, 2))
- const k = m.tune ?? {}
- set('uRim', 0.55 * m.strength * (k.rim ?? 1))
- set('uCaustic', 0.08 * m.strength * (k.caustic ?? 1))
- set('uInner', 0.1 * m.strength * (k.inner ?? 1))
- set('uTopRefl', 0.3 * m.strength * (k.reflection ?? 1))
- set('uTopBase', 0.02 * m.strength * (k.reflection ?? 1))
- set('uRimWidth', Math.max(0.05, k.rimWidth ?? 1))
- set('uFresnel', 0.02 * (k.fresnel ?? 1))
- // The band is as deep as a share of the glass's shorter half, and of its reach on glass taller than that.
- const reached = m.reflection ? clamp(m.reflection.height * MIRROR.reach, MIRROR.reachMin, Math.max(MIRROR.reachMin, MIRROR.reachMax)) : 0
- const deep = (Math.max(0.01, MIRROR.depth) * Math.max(1, Math.min(m.hx, m.hy, reached || Infinity))) / unit
- set('uMirror', clamp(MIRROR.line) * mirror, MIRROR.band * mirror, deep, clamp(MIRROR.dim))
- set('uSoft', (Math.max(0, MIRROR.soft) * reached) / unit)
- const shares = Math.max(MIRROR.near + MIRROR.mid + MIRROR.far, 1e-3)
- set('uSeen', MIRROR.near / shares, MIRROR.mid / shares, MIRROR.far / shares, Math.max(0, MIRROR.gain))
- // The far side of the rim light takes the surroundings' colour on clear glass only.
- set('uBounce', Math.max(0, MIRROR.bounce), clamp(MIRROR.tint) * clear)
- set('uFall', Math.max(0.05, MIRROR.fall))
- set('uBendCurve', Math.max(0.05, k.bendCurve ?? 1.6))
- set('uEdgeBand', 0.35 * Math.max(0.05, k.bendDepth ?? 1))
- set('uSaturation', Math.max(0, k.saturation ?? 1))
- set('uFrostEdge', Math.max(0.05, k.frostEdge ?? 1))
- set('uShadow', m.shadow * m.strength)
- set('uShadowSoft', m.shadowSoftness)
- set('uShadowOffset', m.shadowOffset)
- set('uSurface', ...m.surface)
- set('uColor', ...m.color)
- set('uEdgeClear', m.edgeClear)
- set('uBorder', ...(m.border ?? m.color))
- set('uBorderWidth', m.border ? Math.max(0, m.borderWidth ?? 1) / unit : 0)
- set('uBorderAlpha', clamp(m.borderAlpha ?? 1))
- const { aim, mix: lightMix } = aimOf(m)
- set('uLightDir', Math.cos(aim), Math.sin(aim))
- set('uLightMix', lightMix)
- const glow = m.glow ?? flashOf(v)
- set('uGlow', (glow?.x ?? 0) / unit, (glow?.y ?? 0) / unit, (glow?.r ?? 0) / unit, Math.max(0, glow?.amount ?? 0))
- set('uGlowHalo', glow?.halo ? (glow.halo.around === 'blob' && blob ? 2 : 1) : 0, clamp(glow?.halo?.amount ?? 0))
- set('uGlowBlob', clamp(glow?.blob ?? 1))
- // Pointer light: what the pointer is doing to this glass is worked out here, where the
- // glass's place on screen is fresh; the light itself is advanced once a frame (stepLight).
- let lit = lights.get(v)
- // A glass that continues another takes that one's light (see `lightOf`), measured from here.
- const shared = m.lightOf && m.lightOf !== v ? lights.get(m.lightOf) : undefined
- if (shared) {
- lit = { ...shared, x: shared.x + shared.sx - shared.bodyX - m.screenX, y: shared.y + shared.sy - m.screenY }
- } else if (LIGHT.on && m.pointerLight !== false) {
- if (!lit) {
- const host = hostOf(v)
- lit = { glow: { x: 0, v: 0 }, x: 0, y: 0, press: false, key: false, free: !!host && getComputedStyle(host).pointerEvents === 'none', sx: 0, sy: 0, hx: 0, hy: 0, bodyX: 0, blob: null, onBlob: false }
- lights.set(v, lit)
- }
- lit.sx = m.screenX + m.bodyX
- lit.sy = m.screenY
- lit.hx = m.hx
- lit.hy = m.hy
- lit.bodyX = m.bodyX
- lit.blob = blob ? { x: blob.x, y: blob.y, hx: blob.hx, hy: blob.hy } : null
- // A held pointer lights the glass it is on, or comes onto (a lens arriving under it), until it lets go.
- // The light stays at the point of the glass it began at: it does not follow the pointer.
- const press = lit.press || (beam.id !== -1 && under(v, lit) && innermost(v))
- if (press !== lit.press) {
- relit = true
- if (press) {
- lit.x = beam.x - m.screenX
- lit.y = beam.y - m.screenY
- lit.onBlob = onBlob(lit) && (Math.abs(beam.x - lit.sx) > lit.hx || Math.abs(beam.y - lit.sy) > lit.hy)
- }
- }
- lit.press = press
- }
- const light = lit ? shineOf(lit, m) : null
- if (light) set('uLight', light[0] / unit, light[1] / unit, light[2] / unit, light[3])
- else set('uLight', 0, 0, 1, 0)
- // The glass it melts into (COHESION), as its shader takes them (see uNear in FRAGMENT).
- const near = v.button === true && COHESION.on ? nears.get(v) : undefined
- const count = near ? Math.min(NEAR, near.length / NEAR_VALUES) : 0
- set('uNearCount', count)
- if (count) set('uNearFade', Math.max(0.01, COHESION.lightFade))
- for (let i = 0; i < count; i++) {
- const names = NEAR_NAMES[i]
- for (let j = 0; j < names.length; j++) {
- const at = i * NEAR_VALUES + j * 4
- set(names[j], near![at], near![at + 1], near![at + 2], near![at + 3])
- }
- set(NEAR_PAIR[i], near![i * NEAR_VALUES + NEAR_VALUES - 2], near![i * NEAR_VALUES + NEAR_VALUES - 1])
- }
- // The same layers and the same uniforms as the frame on the canvas: nothing to draw.
- if (fresh && on.sent.length === sent.length && sent.every((value, i) => value === on.sent[i])) return
- on.sent = sent.slice()
- // The shared GL canvas only grows; each view is drawn into its bottom-left corner.
- if (glCanvas.width < devW || glCanvas.height < devH) {
- glCanvas.width = Math.max(glCanvas.width, devW)
- glCanvas.height = Math.max(glCanvas.height, devH)
- }
- gl.viewport(0, 0, devW, devH)
- // What lies beneath, what rides on top and what surrounds the glass: the pictures taken on
- // this frame are uploaded, the others are the ones this view already has.
- gl.activeTexture(gl.TEXTURE0)
- if (p && layers) upload(p.back, layers.back.canvas, true)
- else gl.bindTexture(gl.TEXTURE_2D, p?.back.tex ?? blank.back)
- gl.activeTexture(gl.TEXTURE1)
- if (p && layers?.front && fronted) upload(p.front, layers.front.canvas, false)
- else gl.bindTexture(gl.TEXTURE_2D, (fronted && p?.front.tex) || blank.front)
- gl.activeTexture(gl.TEXTURE2)
- if (picture) upload(picture.pic, around.canvas, true)
- else gl.bindTexture(gl.TEXTURE_2D, (f && mirrored.get(v)?.pic.tex) || blank.back)
- send()
- // The frost's own pass (FROST_PASS): on large, softly frosted glass the frost is drawn first,
- // into a smaller picture that the glass then reads.
- const sigma = r && !blob?.material ? Math.max(0, r.blur ?? 0) * Math.min(1, Math.max(0.05, k.frostEdge ?? 1)) * dpr : 0
- const texel = sigma >= FROST_PASS.sigma && 4 * m.hx * m.hy * dpr * dpr >= FROST_PASS.area ? Math.min(FROST_PASS.most, Math.floor(sigma / FROST_PASS.texel)) : 0
- const fw = texel >= 2 ? Math.ceil(devW / texel) + 1 : 0
- const fh = texel >= 2 ? Math.ceil(devH / texel) + 1 : 0
- if (texel >= 2 && frostRoom(fw, fh)) {
- const sx = 1 / (texel * frostPic.w)
- const sy = 1 / (texel * frostPic.h)
- // The picture is not bound while it is drawn into.
- gl.activeTexture(gl.TEXTURE3)
- gl.bindTexture(gl.TEXTURE_2D, blank.front)
- gl.bindFramebuffer(gl.FRAMEBUFFER, frostPic.fbo)
- // Nothing of what it held is kept: a GPU that draws in tiles need not load it back.
- gl.invalidateFramebuffer(gl.FRAMEBUFFER, [gl.COLOR_ATTACHMENT0])
- gl.viewport(0, 0, fw, fh)
- gl.uniform4f(frostPassAt, 1, texel, sx, sy)
- gl.drawArrays(gl.TRIANGLES, 0, 3)
- gl.bindFramebuffer(gl.FRAMEBUFFER, null)
- gl.viewport(0, 0, devW, devH)
- gl.bindTexture(gl.TEXTURE_2D, frostPic.tex)
- gl.uniform4f(frostPassAt, 2, texel, sx, sy)
- frostPassHeld = 2
- } else if (frostPassHeld) {
- gl.uniform4f(frostPassAt, 0, 1, 0, 0)
- frostPassHeld = 0
- }
- gl.drawArrays(gl.TRIANGLES, 0, 3)
- v.ctx.clearRect(0, 0, devW, devH)
- v.ctx.drawImage(glCanvas, 0, glCanvas.height - devH, devW, devH, 0, 0, devW, devH)
- v.drawn?.()
- }
-
- let raf = 0
- let last = 0
- const frame = (now: number) => {
- raf = 0
- if (dead) return
- const dt = last ? Math.min((now - last) / 1000, 1 / 30) : 1 / 60
- last = now
- const still = reduced.matches
- const target = pointer.active && !still ? 1 : 0
- const before = pointer.mix
- pointer.mix += (target - pointer.mix) * Math.min(1, dt * 6)
- if (Math.abs(pointer.mix - target) < 0.002) pointer.mix = target
- const relight = pointer.moved || pointer.mix !== before
- pointer.moved = false
- let running = pointer.mix !== target
- busy = ranLast || running
- // Buttons melt into each other (COHESION): they are drawn after the rest, once every one has
- // been measured, so each melts into the others as they are on this frame.
- const melting = COHESION.on
- if (!melting && nears.size) {
- for (const v of nears.keys()) {
- v.near = undefined
- v.dirty = true
- }
- nears.clear()
- }
- const due: { v: GlassView; refresh: boolean; repaint: boolean }[] = []
- let regroup = meltsChanged
- meltsChanged = false
- for (const v of views) {
- const stepped = v.step(dt, still)
- // After the view's own springs: its `grow` is this frame's.
- const pulled = stepPull(v, dt, still)
- const moving = stepped || pulled
- // (Both lights of a press: what a surface takes, and a button's flash.)
- const lit = stepLight(v, dt, still)
- const flashing = stepFlash(v, dt, still)
- const glowing = lit || flashing
- if (moving || glowing) running = busy = true
- const melts = melting && v.button === true
- if (melts && v.visible !== shownButtons.has(v)) regroup = true
- if (!v.visible) continue
- const again = v.repaint === true
- if (moving || glowing || v.dirty || again || relight) {
- const refresh = v.dirty
- v.dirty = false
- v.repaint = false
- // Only the light moved: the layers are as they were, so they are not painted again.
- if (melts) due.push({ v, refresh, repaint: moving || refresh || again })
- else draw(v, refresh, moving || refresh || again)
- }
- }
- if (melting && (due.length || regroup)) {
- const lensOf = new Map()
- for (const d of due) lensOf.set(d.v, d.v.lens(d.refresh))
- const { changed, regrouped } = cohere(lensOf)
- // A button whose neighbours moved is drawn again too; one that melts into other glass now (or
- // no longer) paints what lies behind it again, leaving that glass out (or taking it back in).
- for (const d of due) draw(d.v, d.refresh, d.repaint || regrouped.has(d.v), lensOf.get(d.v))
- for (const v of changed) if (v.visible && !due.some((d) => d.v === v)) draw(v, false, regrouped.has(v), lensOf.get(v))
- }
- // A view may have woken the engine during this frame (a popup that has just gone back in
- // does): the next frame is then already asked for, and asking again would start a second
- // loop beside this one, for as long as anything on the page moves.
- // A draw found the pointer on (or off) some glass: its light starts on the next frame.
- if (relit) running = true
- relit = false
- // Pictures of the surroundings that waited while something moved or was lit (or were taken
- // then, having waited as long as they may) are taken once all is still, at once: the glass
- // that takes one is drawn again on the next frame.
- if (running) for (const a of pictured) a.busy = true
- pictured.length = 0
- ranLast = running
- if (running) wake()
- else {
- if (!raf) last = 0
- let again = false
- for (const [v, a] of mirrored) {
- if (!a.busy) continue
- a.busy = false
- a.due = true
- a.at = 0
- v.repaint = true
- again = true
- }
- if (again) wake()
- }
- }
- const wake = () => {
- if (!raf && !dead) raf = requestAnimationFrame(frame)
- }
- const invalidateAll = () => {
- for (const v of views) v.dirty = true
- wake()
- }
-
- window.addEventListener(
- 'pointermove',
- (e) => {
- if (e.pointerType !== 'mouse') return
- pointer.x = e.clientX
- pointer.y = e.clientY
- pointer.active = true
- pointer.moved = true
- wake()
- },
- { passive: true },
- )
- document.documentElement.addEventListener('pointerleave', () => {
- pointer.active = false
- pointer.moved = true
- wake()
- })
- // Pull (PULL): a press holds the innermost glass under it that asks to be pulled, and it is
- // followed over the whole window until it lets go.
- window.addEventListener(
- 'pointerdown',
- (e) => {
- if (!PULL.on || e.button !== 0 || reduced.matches || !(e.target instanceof Node) || HANDED_ON.has(e)) return
- let held: GlassView | null = null
- let heldHost: HTMLElement | null = null
- for (const v of views) {
- const host = hostOf(v)
- if (v.pull !== true || !host || !host.contains(e.target) || host.matches(':disabled, [data-disabled], [aria-disabled="true"]')) continue
- if (pulls.get(v)?.by) return
- if (!heldHost || heldHost.contains(host)) {
- held = v
- heldHost = host
- }
- }
- if (!held || !heldHost) return
- const p = pulledOf(held)
- // The host's own translate is read while the pull's is off it.
- if (!p.moved) {
- const own = getComputedStyle(heldHost).translate
- p.own = !own || own === 'none' ? null : own.split(' ')
- }
- const at = restOf(heldHost, p)
- p.by = { id: e.pointerId, x: e.clientX, y: e.clientY, nowX: e.clientX, nowY: e.clientY, cx: at.x, cy: at.y, lastX: at.x, lastY: at.y, size: Math.max(heldHost.offsetWidth, heldHost.offsetHeight) }
- p.driftX = p.driftY = 0
- held.held = true
- wake()
- },
- { passive: true, capture: true },
- )
- window.addEventListener(
- 'pointermove',
- (e) => {
- for (const p of pulls.values()) {
- if (p.by?.id !== e.pointerId) continue
- p.by.nowX = e.clientX
- p.by.nowY = e.clientY
- wake()
- }
- },
- { passive: true, capture: true },
- )
- const unhold = (e: PointerEvent) => {
- for (const [v, p] of pulls) {
- if (p.by?.id !== e.pointerId) continue
- letGo(v, p)
- wake()
- }
- }
- window.addEventListener('pointerup', unhold, { passive: true, capture: true })
- window.addEventListener('pointercancel', unhold, { passive: true, capture: true })
- // Pointer light (LIGHT): where the lighting pointer is, what it is over and whether it is held.
- // Which glass that lights is decided when each glass is drawn, so every change asks for a frame.
- const lightMoved = () => {
- pointer.moved = true
- wake()
- }
- window.addEventListener(
- 'pointermove',
- (e) => {
- // Only the held pointer counts (a lens may come under it): one that moves over the page without pressing asks for nothing.
- if (!LIGHT.on || e.pointerId !== beam.id) return
- beam.x = e.clientX
- beam.y = e.clientY
- beam.over = e.target
- lightMoved()
- },
- { passive: true, capture: true },
- )
- window.addEventListener(
- 'pointerdown',
- (e) => {
- if (!LIGHT.on || e.button !== 0 || HANDED_ON.has(e)) return
- beam.x = e.clientX
- beam.y = e.clientY
- beam.over = e.target
- beam.id = e.pointerId
- lightMoved()
- },
- { passive: true, capture: true },
- )
- const lift = (e: PointerEvent) => {
- if (e.pointerId !== beam.id) return
- beam.id = -1
- for (const s of lights.values()) s.press = false
- lightMoved()
- }
- window.addEventListener('pointerup', lift, { passive: true, capture: true })
- window.addEventListener('pointercancel', lift, { passive: true, capture: true })
- // A button's flash (GLOW): a press lights the innermost button under it where it lands, and
- // holds it until that pointer lets go; Space or Enter lights the focused button's centre.
- window.addEventListener(
- 'pointerdown',
- (e) => {
- if (e.button !== 0 || HANDED_ON.has(e) || !(e.target instanceof Node)) return
- // A choice pressed inside a surface lights that surface around it.
- const choice = e.target instanceof Element ? e.target.closest(CHOICES) : null
- const chosen = choice && !choice.matches('[data-disabled], [aria-disabled="true"]') ? choice : null
- let hit: GlassView | null = null
- let hitHost: HTMLElement | null = null
- for (const v of views) {
- const host = hostOf(v)
- if (!host || host.matches(':disabled, [data-disabled], [aria-disabled="true"]')) continue
- if (v.button === true ? !(v.pressArea ?? host).contains(e.target) : !chosen || v.choices === false || !v.visible || !host.contains(chosen)) continue
- if (!hitHost || hitHost.contains(host)) {
- hit = v
- hitHost = host
- }
- }
- const f = hit && flash(hit, e.clientX, e.clientY, hit.button === true ? undefined : (chosen ?? undefined))
- if (f) f.by = e.pointerId
- },
- { passive: true, capture: true },
- )
- const unflash = (e: PointerEvent) => {
- for (const f of flashes.values()) {
- if (f.by !== e.pointerId) continue
- f.by = -1
- wake()
- }
- }
- window.addEventListener('pointerup', unflash, { passive: true, capture: true })
- window.addEventListener('pointercancel', unflash, { passive: true, capture: true })
- const flashKey = (e: KeyboardEvent) => {
- if (e.key !== ' ' && e.key !== 'Enter') return
- const down = e.type === 'keydown'
- if (down && e.repeat) return
- if (!down) {
- for (const f of flashes.values()) f.key = false
- return wake()
- }
- const focused = document.activeElement
- if (!focused) return
- // On a surface, the key chooses the focused choice: the light starts at its middle.
- const choice = focused.closest(CHOICES)
- const chosen = choice && !choice.matches('[data-disabled], [aria-disabled="true"]') ? choice : null
- let surface: GlassView | null = null
- let surfaceHost: HTMLElement | null = null
- for (const v of views) {
- const host = hostOf(v)
- if (!host || host.matches(':disabled, [data-disabled], [aria-disabled="true"]')) continue
- if (v.button === true) {
- if (!focused.contains(v.canvas)) continue
- const f = flash(v)
- if (f) f.key = true
- } else if (chosen && v.choices !== false && v.visible && host.contains(chosen) && (!surfaceHost || surfaceHost.contains(host))) {
- surface = v
- surfaceHost = host
- }
- }
- if (surface && chosen) {
- const r = chosen.getBoundingClientRect()
- const f = flash(surface, r.left + r.width / 2, r.top + r.height / 2, chosen)
- if (f) f.key = true
- }
- wake()
- }
- window.addEventListener('keydown', flashKey, true)
- window.addEventListener('keyup', flashKey, true)
- window.addEventListener(
- 'focusout',
- () => {
- for (const f of flashes.values()) f.key = false
- wake()
- },
- true,
- )
- // Space or Enter on the focused control lights the middle of its glass while the key is down.
- const key = (e: KeyboardEvent) => {
- if (e.key !== ' ' && e.key !== 'Enter') return
- const down = e.type === 'keydown'
- if (down && (!LIGHT.on || e.repeat)) return
- const focused = document.activeElement
- for (const [v, s] of lights) {
- const held = down && !s.free && !!focused && focused.contains(v.canvas)
- if (held && !s.key && !s.press) {
- s.x = s.bodyX
- s.y = 0
- }
- s.key = held
- }
- wake()
- }
- window.addEventListener('keydown', key, true)
- window.addEventListener('keyup', key, true)
- window.addEventListener(
- 'focusout',
- () => {
- for (const s of lights.values()) s.key = false
- wake()
- },
- true,
- )
- // Theme switches (class="dark", data-theme, color-scheme) re-read every colour.
- new MutationObserver(invalidateAll).observe(document.documentElement, {
- attributes: true,
- attributeFilter: ['class', 'data-theme', 'style'],
- })
- new MutationObserver(invalidateAll).observe(document.body, { attributes: true, attributeFilter: ['data-theme'], subtree: true })
- window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', invalidateAll)
- // A radial bend scales with the viewport.
- window.addEventListener('resize', invalidateAll, { passive: true })
- glCanvas.addEventListener('webglcontextlost', () => {
- dead = true
- for (const v of views) {
- v.lost()
- v.ctx.clearRect(0, 0, v.canvas.width, v.canvas.height)
- }
- // No frame comes after this: the hosts get back what the engine wrote on them.
- for (const [v, p] of pulls) {
- const host = hostOf(v)
- v.held = false
- if (host && p.moved) host.style.translate = ''
- if (host && p.scaled) host.style.scale = ''
- }
- pulls.clear()
- engine = undefined
- })
-
- return {
- add: (v) => {
- views.add(v)
- meltsChanged = true
- wake()
- },
- remove: (v) => {
- views.delete(v)
- lights.delete(v)
- flashes.delete(v)
- // The glass that melted into it lets go.
- if (v.button === true) {
- meltsChanged = true
- wake()
- }
- nears.delete(v)
- shownButtons.delete(v)
- v.near = undefined
- const pulled = pulls.get(v)
- if (pulled) {
- pulls.delete(v)
- v.held = false
- const host = hostOf(v)
- if (host && pulled.moved) host.style.translate = ''
- if (host && pulled.scaled) host.style.scale = ''
- }
- const a = mirrored.get(v)
- if (a) {
- mirrored.delete(v)
- clearTimeout(a.timer)
- gl.deleteTexture(a.pic.tex)
- }
- const p = painted.get(v)
- if (!p) return
- painted.delete(v)
- gl.deleteTexture(p.back.tex)
- gl.deleteTexture(p.front.tex)
- },
- wake,
- resolveColor,
- }
-}
-
-let engine: GlassEngine | null | undefined
-
-/** The shared engine (created on first use, client only). `null` = no WebGL2: use the CSS look. */
-export function getGlassEngine(): GlassEngine | null {
- if (typeof window === 'undefined') return null
- if (engine === undefined) engine = createEngine()
- return engine
-}
diff --git a/src/components/liquid-glass/glass-badge.tsx b/src/components/liquid-glass/glass-badge.tsx
deleted file mode 100644
index ec26e2d..0000000
--- a/src/components/liquid-glass/glass-badge.tsx
+++ /dev/null
@@ -1,279 +0,0 @@
-'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.
-//
-//
-//
-// New
-//
-//
-// 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(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 (
-
-
-
- {children}
- {/* CSS fallback until the glass draws (and without WebGL2). */}
-
-
- {Array.from({ length: 4 }, (_, i) => (
-
- {children}
-
-
- ))}
-
-
-
- {children}
-
-
- )
-}
-
-export default GlassBadge
diff --git a/src/components/liquid-glass/glass-layer.tsx b/src/components/liquid-glass/glass-layer.tsx
deleted file mode 100644
index b0eb1df..0000000
--- a/src/components/liquid-glass/glass-layer.tsx
+++ /dev/null
@@ -1,795 +0,0 @@
-'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`:
-//
-//
-//
-// Get started
-//
-//
-// 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 (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 `
- )
-}
-
-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(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(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 (
- <>
-
-
- >
- )
-}
-
-export default GlassLayer
diff --git a/src/components/liquid-glass/glass-lens.tsx b/src/components/liquid-glass/glass-lens.tsx
deleted file mode 100644
index 3e08067..0000000
--- a/src/components/liquid-glass/glass-lens.tsx
+++ /dev/null
@@ -1,472 +0,0 @@
-'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:
-//
-//
-//
-// {options.map(o => (
-//
-// {o === value && }
-// {o}
-//
-// ))}
-//
-//
-// 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>()
-
-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(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('[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[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('[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 (
- <>
-
-
- >
- )
-}
-
-export default GlassLens
diff --git a/src/components/mobil-menu.tsx b/src/components/mobil-menu.tsx
index d1b9946..6ca86e2 100644
--- a/src/components/mobil-menu.tsx
+++ b/src/components/mobil-menu.tsx
@@ -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-glass-ready: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-cam:active:scale-100 motion-reduce:transition-none sm:size-12")}
>
@@ -210,7 +210,7 @@ export function MobilMenu({
diff --git a/src/components/sivi-cam.tsx b/src/components/sivi-cam.tsx
index b0dbb4e..585f8eb 100644
--- a/src/components/sivi-cam.tsx
+++ b/src/components/sivi-cam.tsx
@@ -1,197 +1,1663 @@
"use client";
-// Sıvı cam (DESIGN.md §4.1, §4.22, §4.49, §4.50): ürünün cam yüzeylerini Bilal'in açık
-// kaynak kiti "Liquid Glass UI"ya (github.com/bilalgursen/liquid-glass, MIT) bağlayan
-// ince katman. Motorun kendisi `src/components/liquid-glass/` altındadır ve kitten
-// **birebir kopyadır** (sürüm 2.0.4, 25 Kas 2026): `engine.ts`, `dom-snapshot.ts`,
-// `glass-layer.tsx`, `glass-lens.tsx`, `glass-badge.tsx`. O dosyalar elle
-// düzenlenmez; kit güncellenince üstlerine yenisi kopyalanır. Bağımlılık yok (düz
-// WebGL2). 12 Kas 2026'daki elle çeviri (three.js'li ilk kitten) bu dosyada dururdu;
-// Bilal, 26 Kas 2026: "liquid glass'ın son hâline çevir".
+// Sıvı cam (DESIGN.md §4.1, §4.22, §4.50): turuncu CTA'nın zemini ve tek seçimli
+// sekmelerde seçenekten seçeneğe kayan vurgu. Kaynak: Bilal'in açık kaynak kiti
+// "Liquid Glass UI" (github.com/bilalgursen/liquid-glass, MIT) — `ui/Button.tsx`,
+// `ui/SegmentedControl.tsx`, `ui/LiquidGlass.tsx`, `ui/glass/runtime.ts`,
+// `ui/glass/physics.ts`. Bilal, 12 Kas 2026: "CTA butonlarını bu projede yaptığım
+// buton yapısında yapalım", "tab geçişinde de geçerken liquid glass olsun",
+// "oklu CTA'da ok bir sıvı gibi yavaşça ayrılsın, yuvarlak ayrı bir parça olsun".
//
-// Bu dosya yalnız ürüne özgü olanı taşır:
-// - Sıvı cam tercihi (`cam-tercihi.ts`, footer'daki kutu): kapalıyken hiçbir cam
-// kurulmaz, her yüzey sade hâlindedir.
-// - İkon damlası: kit damlayı `data-glass-drop` taşıyan çocukta ve sonda bekler;
-// burada butonun baştaki ya da sondaki ikonu bulunup işaretlenir, üstüne gelince
-// ayrılır (`otoDamla`: ekrana girince), baştaki ikonda tuval yatay çevrilir.
-// - CTA yüzeyi (`[data-cta-yuzey]`): şeffaf cam o yüzeyi canlı kırar ve mavi boyalıdır
-// (`--glass-tint`, globals.css).
+// §11.3'e göre çevrildi:
+// - Kit three.js (WebGPURenderer + TSL) ister; burada aynı gölgelendirici düz
+// WebGL2 GLSL olarak yeniden yazıldı, yeni bağımlılık yok.
+// - Işık modeli aynı: eğimli kenar, üst yansıma, üç katlı iç gölge, kenar ışığı
+// (imlece hafifçe döner), alt kostik, iki katlı gölge. CTA'da alt katman boştur
+// (kitteki buton gibi): cam boyalıdır, doku yok. Sekmede kitteki gibi iki
+// katman var: camın altındaki seçenekler (zemin, kenarlık, etiket, ikon)
+// DOM'dan 2D tuvale çizilir, mercek onu kenarında büker, ortasında büyütür.
+// - Renk token'dan: CTA `--color-orange-500`, sekme vurgunun kendi rengi.
+// - Yaylar `hareket.ts` (`CAM_YAYI`).
//
-// Kap kendi zeminini cam ilk karesini çizince bırakır: kit kaba `data-glass-ready`
-// yazar, `SIVI_KAP` sınıfları onu dinler. WebGL2 yoksa ya da bağlam kaybolursa
-// hiçbir şey değişmez.
+// Kitteki gibi tek ortak WebGL bağlamı her camı çizer ve sonucu camın kendi 2D
+// tuvaline kopyalar: sayfadaki cam sayısı tarayıcının bağlam sınırına takılmaz.
+// Yalnız gerekince çizilir (boy/tema değişince, imleç oynayınca, yay sönene dek);
+// boşta döngü yok, ekran dışında çizim yok. Hareketi azalt'ta cam durağandır.
+// WebGL2 yoksa ya da bağlam kaybolursa hiçbir şey değişmez: CTA düz turuncudur,
+// sekme vurgusu eski gibi `layoutId` ile kayar.
-import { useEffect, useMemo, useRef, useState, type ReactNode } from "react";
-
-import { GlassBadge } from "@/components/liquid-glass/glass-badge";
-import { GlassLayer, type GlassOptics } from "@/components/liquid-glass/glass-layer";
-import { GlassLens } from "@/components/liquid-glass/glass-lens";
-import { useCamAcik } from "@/lib/cam-tercihi";
+import { useEffect, useRef } from "react";
+import { domuCiz } from "@/components/cam-yuzey";
+import { camAcikMi, useCamAcik } from "@/lib/cam-tercihi";
+import { CAM_YAYI } from "@/lib/hareket";
// Kap sınıfları ayrı dosyada (sunucu bileşenleri de alabilsin); istemci dosyaları buradan almaya devam eder.
export { SIVI_KAP } from "@/components/sivi-kap";
-/** CTA yüzeyindeki cam CTA'nın mavi boyasının yoğunluğu ("Yeni" rozetiyle aynı). */
-const CTA_BOYASI = 0.82;
-/** Yüzey dışındaki şeffaf cam ("Giriş yap"): kitin kendi varsayılanı. */
-const SEFFAF_BOYA = 0.6;
-/** Baştaki ikonda tuval yatay çevrilir; imlece dönen kenar ışığı ters düşmesin diye kapatılır. */
-const BASTA_OPTIK: GlassOptics = { cursorLight: false };
+/** Kitteki ölçü: cam 120 birim yüksekliğinde tasarlanır. */
+const BIRIM_YUKSEKLIK = 120;
+/** Basınca büyüme (kit `swell`) ve üstüne gelince yazı ölçeği (kit `hoverScale`). */
+const BASMA_OLCEGI = 1.08;
+const USTUNDE_OLCEGI = 1.04;
+/** Üstüne gelince camın her yana büyümesi: yüksekliğin %8'i (kit `hoverGrow`). */
+const USTUNDE_BUYUME = 0.08;
+/** Ölçekle büyümenin yan başına üst sınırı (px). */
+const EN_COK_BUYUME = 6;
+/** Ayrılan ok damlası ile gövde arasındaki boşluk: buton yüksekliğinin oranı (48 px'te 12 px). */
+const DAMLA_ARALIGI = 0.25;
+/** Kayan cam yoldayken şişmesi (kit: en 1,12, boy `lensScale` 1,35). */
+const KAYARKEN_EN = 0.12;
+const KAYARKEN_BOY = 0.35;
-type Kap = { yuzeyde: boolean; uc: "" | "bas" | "son" };
+const KOSE_GOLGELENDIRICI = `#version 300 es
+in vec2 a;
+void main() { gl_Position = vec4(a, 0.0, 1.0); }
+`;
+
+// Kitin TSL düğümünün (runtime.ts createMaterial) GLSL karşılığı; doku yok.
+// Ek: gövdeden ayrılan damla (yumuşak birleşim) ve yarı saydam cam.
+const PARCA_GOLGELENDIRICI = `#version 300 es
+precision highp float;
+uniform vec2 uBoyut, uMerkez, uYari, uIsikYonu;
+uniform float uBirim, uPiksel, uKose, uEgim, uGovdeX;
+uniform vec3 uDamla;
+uniform float uKenar, uKostik, uIcGolge, uUstYansima, uUstTaban;
+uniform float uGolge, uGolgeYumusak, uGolgeKayma;
+uniform float uIsikKarisim, uTon, uKenarSeffaf;
+uniform vec3 uZemin, uRenk, uCizgi;
+uniform float uCizgiKalin;
+// Doku yolu (sekme merceği): alt katman bükülür, üst katman buzlu hapın üstünde durur.
+uniform sampler2D uArka, uOn;
+uniform float uDokuVar, uKirilma, uBuyutme, uDagilma, uBulanikOrta, uBulanikKenar, uBulanikKayma, uBuz;
+out vec4 cikis;
+
+// Tasarım birimi → doku koordinatı (doku ters yüklenir: üst satır v = 1).
+vec2 dokuYeri(vec2 d) {
+ vec2 q = d * uBirim;
+ return clamp(vec2(q.x / uBoyut.x, 1.0 - q.y / uBoyut.y), vec2(0.0005), vec2(0.9995));
+}
+vec3 arkaOku(vec2 st, float lod) {
+ vec4 c = textureLod(uArka, st, lod);
+ return c.rgb + (1.0 - c.a) * uZemin;
+}
+
+float kutu(vec2 p, vec2 b, float r) {
+ vec2 q = abs(p) - b + r;
+ return length(max(q, 0.0)) + min(max(q.x, q.y), 0.0) - r;
+}
+// Camın biçimi: hap gövde; damla varsa (yarıçap > 0) ona sıvı gibi bağlanır.
+float sekil(vec2 p) {
+ float g = kutu(p - vec2(uGovdeX, 0.0), uYari, uKose);
+ if (uDamla.y <= 0.0) return g;
+ float d = length(p - vec2(uDamla.x, 0.0)) - uDamla.y;
+ float k = max(uDamla.z, 1e-3);
+ float h = clamp(0.5 + 0.5 * (d - g) / k, 0.0, 1.0);
+ return mix(d, g, h) - k * h * (1.0 - h);
+}
+// Kit doğrusal rengi koyultur; sRGB değerde aynı çarpan k^(1/2,2).
+float kis(float k) { return pow(clamp(k, 0.0, 1.0), 1.0 / 2.2); }
+vec3 kis(vec3 k) { return pow(clamp(k, 0.0, 1.0), vec3(1.0 / 2.2)); }
+float yukseklik(vec2 p) {
+ float t = pow(clamp(-sekil(p) / uEgim, 0.0, 1.0), 1.0 / 1.4);
+ return sqrt(1.0 - (1.0 - t) * (1.0 - t));
+}
+
+void main() {
+ vec2 px = vec2(gl_FragCoord.x, uBoyut.y - gl_FragCoord.y);
+ vec2 yerel = px / uBirim - uMerkez;
+ float uzaklik = sekil(yerel);
+
+ // İki katlı gölge: cama yakın, tuval kenarına varmadan söner.
+ float dikey = smoothstep(-0.1, 0.9, yerel.y / uYari.y) * 0.92 + 0.08;
+ float disarida = smoothstep(-4.0, 14.0, uzaklik);
+ float yakin = 1.0 - smoothstep(-6.0, uGolgeYumusak, sekil(yerel - vec2(0.0, uGolgeKayma)));
+ float uzak = 1.0 - smoothstep(-10.0, uGolgeYumusak * 1.5, sekil(yerel - vec2(0.0, uGolgeKayma * 1.6)));
+ float sinir = min(min(px.x, px.y), min(uBoyut.x - px.x, uBoyut.y - px.y));
+ float golge = clamp((yakin + uzak) * uGolge * dikey * disarida, 0.0, 0.85) * smoothstep(0.0, 14.0, sinir);
+ vec4 dis = vec4(0.0, 0.0, 0.0, 1.0 - kis(1.0 - golge));
+
+ // Eğimden yüzey normali.
+ float e = 1.25;
+ float h = yukseklik(yerel);
+ vec2 egim = vec2(yukseklik(yerel + vec2(e, 0.0)) - h, yukseklik(yerel + vec2(0.0, e)) - h) / e;
+ vec3 normal = normalize(vec3(-egim * 42.0, 1.0));
+ float derinlik = clamp(1.0 - h, 0.0, 1.0);
+ float kenar = 1.0 - smoothstep(0.0, uEgim * 0.35, -uzaklik);
+ vec2 yon = normalize(vec2(sekil(yerel + vec2(e, 0.0)) - uzaklik, sekil(yerel + vec2(0.0, e)) - uzaklik) + 1e-6);
+
+ vec3 cam;
+ if (uDokuVar > 0.5) {
+ // Kırılma: ortada büyütme, kenar bandında içeri bükme, renk ayrışması.
+ vec2 buyuk = yerel / (uBuyutme * h + 1.0);
+ vec2 kir = -yon * uKirilma * pow(kenar, 1.6);
+ float ayris = uDagilma * 0.35;
+ float lod = max(mix(uBulanikOrta, uBulanikKenar, pow(kenar, 1.3)) + uBulanikKayma, 0.0);
+ cam = vec3(
+ arkaOku(dokuYeri(uMerkez + buyuk + kir * (1.0 + ayris)), lod).r,
+ arkaOku(dokuYeri(uMerkez + buyuk + kir), lod).g,
+ arkaOku(dokuYeri(uMerkez + buyuk + kir * (1.0 - ayris)), lod).b);
+ } else {
+ // Boyalı cam: ortada kendi rengi, kenara doğru incelir, zemin görünür.
+ cam = mix(uZemin, uRenk, uTon * (1.0 - kenar * uKenarSeffaf));
+ }
+
+ // Üst yansıma.
+ float ny = yerel.y / uYari.y;
+ float nx = (yerel.x - uGovdeX) / uYari.x;
+ float ust = (1.0 - smoothstep(-0.05, 0.75, ny)) * (1.0 - nx * 0.12) * uUstYansima * 0.6 + uUstTaban;
+ cam *= kis(1.0 - vec3(1.0, 1.0, 0.72) * ust);
+
+ // Buzlu dinlenme hâli: mercek durağanken düz vurgu rengidir.
+ cam = mix(cam, uRenk, uBuz * step(0.5, uDokuVar));
+
+ // İç gölge: kenarın hemen içi, sol geniş bant, derinde halka.
+ float yukari = clamp(-yon.y, 0.0, 1.0);
+ float sag = clamp(yon.x, 0.0, 1.0);
+ float sol = clamp(-yon.x, 0.0, 1.0);
+ float asagi = clamp(yon.y, 0.0, 1.0);
+ float icBant = smoothstep(uEgim * -0.19, uEgim * -0.024, uzaklik);
+ cam *= kis(1.0 - icBant * (yukari + sol * 0.6 + sag * 0.3 + asagi * 0.15) * uIcGolge * 2.2);
+ float derinBant = smoothstep(uEgim * -0.73, uEgim * -0.13, uzaklik);
+ cam *= kis(1.0 - derinBant * sol * uIcGolge * 2.0);
+ float hx = (uzaklik + uEgim * 0.45) / (uEgim * 0.26);
+ float halka = exp(-hx * hx);
+ cam *= kis(1.0 - halka * (sag * 0.9 + yukari * 0.5 + sol * 0.4 + asagi * 0.3) * uIcGolge * 1.5);
+
+ // Kenar ışığı + fresnel. İmleç sayfadaysa sabit stüdyo ışığı ona hafifçe döner.
+ float fresnel = pow(clamp(1.0 - normal.z, 0.0, 1.0), 6.0);
+ float kalinlik = max(uPiksel * 1.1, 1.0);
+ float cizgi = 1.0 - smoothstep(0.0, kalinlik * 1.6, abs(uzaklik + kalinlik * 1.8));
+ float dusus = exp(-(yerel.y / 30.0) * (yerel.y / 30.0));
+ float sabit = sag * sag * dusus * 0.9 + asagi * asagi * 0.2 + sol * sol * 0.55;
+ float isikCos = dot(yon, uIsikYonu);
+ float bakan = clamp(isikCos, 0.0, 1.0);
+ float ters = clamp(-isikCos, 0.0, 1.0);
+ float donuk = bakan * bakan * 0.9 + ters * ters * 0.55;
+ float yatis = uIsikKarisim * 0.4;
+ float isikYonu = mix(sabit, donuk, yatis);
+ float on = mix(sag, bakan, yatis);
+ float arka = mix(sol, ters, yatis);
+ vec3 sicakSoguk = mix(vec3(0.82, 0.9, 1.08), vec3(1.2, 0.95, 0.78), 1.0 - smoothstep(-0.5, 0.1, nx));
+ vec3 isikRengi = mix(vec3(1.0), sicakSoguk, asagi * 0.6);
+ isikRengi = mix(isikRengi, vec3(0.12, 0.6, 1.2), arka * 0.85);
+ float isik = cizgi * isikYonu * uKenar + fresnel * on * 0.02 * step(0.001, uKenar);
+ cam += isikRengi * isik;
+
+ // Kostik: alt kenarın içinde toplanan sıcak ışık.
+ cam += vec3(1.0, 0.92, 0.86) * smoothstep(0.72, 0.98, derinlik) * asagi * uKostik;
+
+ float aa = max(fwidth(uzaklik), 1e-4);
+ float maske = 1.0 - smoothstep(-aa, aa, uzaklik);
+ // Kenarlıklı gövde (ikincil/outline buton): kenarın hemen içinde düz çizgi.
+ cam = mix(cam, uCizgi, smoothstep(-uCizgiKalin - aa, -uCizgiKalin + aa, uzaklik) * step(1e-4, uCizgiKalin));
+ vec4 renk = mix(dis, vec4(clamp(cam, 0.0, 1.0), 1.0), maske);
+ // Üst katman: seçili renkteki etiketler buzlu hapın üstünde; cam açıldıkça söner.
+ vec4 ustKat = texture(uOn, gl_FragCoord.xy / uBoyut) * maske * uBuz * step(0.5, uDokuVar);
+ cikis = ustKat + renk * (1.0 - ustKat.a);
+}
+`;
+
+type Yay = { x: number; v: number };
+type Rgb = [number, number, number];
+
+/** Sönümlü yay (kit `stepSpring`): omega hız, zeta sönüm oranı (< 1). Hareket sürüyorsa true. */
+function yayAdim(s: Yay, hedef: number, { omega, zeta }: { omega: number; zeta: number }, dt: number) {
+ const d = s.x - hedef;
+ const wd = omega * Math.sqrt(1 - zeta * zeta);
+ const b = (s.v + zeta * omega * d) / wd;
+ const e = Math.exp(-zeta * omega * dt);
+ const cos = Math.cos(wd * dt);
+ const sin = Math.sin(wd * dt);
+ const x = (d * cos + b * sin) * e;
+ s.x = hedef + x;
+ s.v = e * wd * (b * cos - d * sin) - zeta * omega * x;
+ // Eşikler hedefin ölçeğine göre: piksel cinsinden yaylar (sekme merceği)
+ // gözle görülmeyen bir kuyrukla saniyelerce "hareketli" kalmasın.
+ const olcek = Math.max(1, Math.abs(hedef));
+ const oturdu = Math.abs(s.x - hedef) < 5e-4 * olcek && Math.abs(s.v) < 0.005 * olcek;
+ if (oturdu) {
+ s.x = hedef;
+ s.v = 0;
+ }
+ return !oturdu;
+}
+
+const ara = (a: number, b: number, t: number) => a + (b - a) * t;
+const sinirla = (v: number, a = 0, b = 1) => Math.max(a, Math.min(b, v));
+const yumusak = (a: number, b: number, v: number) => {
+ const t = sinirla((v - a) / (b - a));
+ return t * t * (3 - 2 * t);
+};
+
+const gorunurRenk = (r: string) =>
+ !!r && r !== "transparent" && !/rgba\(.*,\s*0\)$/.test(r) && !/\/\s*0\)$/.test(r);
+
+/** Öğenin durduğu zemin: zemini boyalı ilk ata. */
+function zeminRengi(el: Element | null): string {
+ for (let a = el; a; a = a.parentElement) {
+ const r = getComputedStyle(a).backgroundColor;
+ if (gorunurRenk(r)) return r;
+ }
+ return "white";
+}
+
+/** Bir karede çizilecek cam. Uzunluklar CSS px; tuvalin sol üstü başlangıçtır. */
+type Mercek = {
+ /** Tuvalin kap içindeki yeri ve boyu. */
+ sol: number;
+ ust: number;
+ en: number;
+ boy: number;
+ /** CSS px / tasarım birimi. */
+ birim: number;
+ /** Gövdenin merkezi ve yarı boyu. */
+ mx: number;
+ my: number;
+ yx: number;
+ yy: number;
+ kose: number;
+ /** Gövdenin merkezden yana kayması (damla ayrılırken geri çekilir). */
+ govdeX: number;
+ /** Ayrılan damla: merkezinin x'i (merceğe göre), yarıçapı, birleşim yumuşaklığı. */
+ damla?: { x: number; r: number; k: number };
+ /** Kenar eğiminin genişliği (tasarım birimi). */
+ egim: number;
+ /** Gölge: güç, yumuşaklık ve aşağı kayma (tasarım birimi). */
+ golge: number;
+ golgeYumusak: number;
+ golgeKayma: number;
+ /** Işık ve gölgenin gücü (0 = düz hap, 1 = cam). */
+ guc: number;
+ renk: Rgb;
+ zemin: Rgb;
+ kenarSeffaf: number;
+ /** Gövdenin 1 px kenarlığı (kenarlıklı buton); yoksa çizilmez. */
+ cizgi?: Rgb;
+ /** Altını büken mercek (sekme): katmanları çizer, kırılma ayarlarını verir. */
+ kirma?: {
+ /** İki katmanı çizer; başlangıç tuvalin sol üstü (CSS px). */
+ boya: (arka: CanvasRenderingContext2D, on: CanvasRenderingContext2D) => void;
+ /** Kenarda içeri bükülme (tasarım birimi) ve ortada büyütme. */
+ kirilma: number;
+ buyutme: number;
+ dagilma: number;
+ bulanikOrta: number;
+ bulanikKenar: number;
+ /** 1 = düz vurgu (buzlu), 0 = şeffaf cam. */
+ buz: number;
+ };
+ /** Kenar ışığı imlece döner mi (kitte yalnız butonlarda). */
+ imlecIsigi: boolean;
+ /** Işığın döneceği merkez (ekran koordinatı). */
+ ekranX: number;
+ ekranY: number;
+};
+
+type Gorunum = {
+ tuval: HTMLCanvasElement;
+ ctx: CanvasRenderingContext2D;
+ kirli: boolean;
+ gorunur: boolean;
+ /** Yayları ilerletir; hareket sürüyorsa true. `dur`: hareketi azalt. */
+ adim: (dt: number, dur: boolean) => boolean;
+ /** Çizilecek cam; `null` ise tuval boşaltılır. `yenile`: boy ve renkleri yeniden oku. */
+ mercek: (yenile: boolean) => Mercek | null;
+ /** İlk kare tuvale ulaştı. */
+ cizildi?: () => void;
+ /** Bağlam kayboldu: sade hâle dön. */
+ birak: () => void;
+};
+
+type Calisma = {
+ ekle: (g: Gorunum) => void;
+ cikar: (g: Gorunum) => void;
+ uyandir: () => void;
+ renkCoz: (kap: HTMLElement, deger: string) => Rgb;
+ /** Saydamlığıyla birlikte: [r, g, b, a]. */
+ renkCozA: (kap: HTMLElement, deger: string) => [number, number, number, number];
+};
+
+function calismaKur(): Calisma | null {
+ const glTuval = document.createElement("canvas");
+ const gl = glTuval.getContext("webgl2", { alpha: true, premultipliedAlpha: true, antialias: false });
+ if (!gl) return null;
+ const derle = (tur: number, kaynak: string) => {
+ const g = gl.createShader(tur);
+ if (!g) return null;
+ gl.shaderSource(g, kaynak);
+ gl.compileShader(g);
+ if (gl.getShaderParameter(g, gl.COMPILE_STATUS)) return g;
+ if (process.env.NODE_ENV !== "production") console.warn("Sıvı cam gölgelendiricisi derlenemedi", gl.getShaderInfoLog(g));
+ return null;
+ };
+ const k = derle(gl.VERTEX_SHADER, KOSE_GOLGELENDIRICI);
+ const p = derle(gl.FRAGMENT_SHADER, PARCA_GOLGELENDIRICI);
+ const program = gl.createProgram();
+ if (!k || !p || !program) return null;
+ gl.attachShader(program, k);
+ gl.attachShader(program, p);
+ gl.linkProgram(program);
+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) return null;
+ gl.useProgram(program);
+ gl.bindBuffer(gl.ARRAY_BUFFER, gl.createBuffer());
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([-1, -1, 3, -1, -1, 3]), gl.STATIC_DRAW);
+ const a = gl.getAttribLocation(program, "a");
+ gl.enableVertexAttribArray(a);
+ gl.vertexAttribPointer(a, 2, gl.FLOAT, false, 0, 0);
+ // Sekme merceğinin iki katmanı: ortak 2D tuvaller ve dokular.
+ const katman = () => {
+ const tuval = document.createElement("canvas");
+ const ctx = tuval.getContext("2d");
+ const doku = gl.createTexture();
+ gl.bindTexture(gl.TEXTURE_2D, doku);
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array(4));
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
+ return { tuval, ctx, doku };
+ };
+ const arkaKatman = katman();
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
+ gl.generateMipmap(gl.TEXTURE_2D);
+ const onKatman = katman();
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
+ if (!arkaKatman.ctx || !onKatman.ctx) return null;
+ gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true);
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
+ gl.uniform1i(gl.getUniformLocation(program, "uArka"), 0);
+ gl.uniform1i(gl.getUniformLocation(program, "uOn"), 1);
+ const yerler = new Map();
+ const u = (ad: string) => {
+ if (!yerler.has(ad)) yerler.set(ad, gl.getUniformLocation(program, ad));
+ return yerler.get(ad) ?? null;
+ };
+
+ const gorunumler = new Set();
+ const azalt = window.matchMedia("(prefers-reduced-motion: reduce)");
+ let olu = false;
+
+ // Renk okuma: CSS rengini (oklch dahil) 1×1 tuvale boyayıp okur.
+ const boyaTuval = document.createElement("canvas");
+ boyaTuval.width = boyaTuval.height = 1;
+ const boya = boyaTuval.getContext("2d", { willReadFrequently: true });
+ const renkCoz = (kap: HTMLElement, deger: string): Rgb => {
+ if (!boya) return [1, 1, 1];
+ const olcu = document.createElement("span");
+ olcu.style.color = deger;
+ // Ölçüm öğesi butona değil gövdeye eklenir: butonun çocuk listesi izleniyor,
+ // oraya eklemek her karede yeniden ölçüm döngüsü kurar. Token'lar köktedir.
+ void kap;
+ document.body.appendChild(olcu);
+ const hesap = getComputedStyle(olcu).color;
+ olcu.remove();
+ boya.clearRect(0, 0, 1, 1);
+ boya.fillStyle = hesap;
+ boya.fillRect(0, 0, 1, 1);
+ const [r, g, b] = boya.getImageData(0, 0, 1, 1).data;
+ return [r / 255, g / 255, b / 255];
+ };
+ const renkCozA = (kap: HTMLElement, deger: string): [number, number, number, number] => {
+ if (!boya) return [1, 1, 1, 1];
+ const olcu = document.createElement("span");
+ olcu.style.color = deger;
+ // Ölçüm öğesi butona değil gövdeye eklenir: butonun çocuk listesi izleniyor,
+ // oraya eklemek her karede yeniden ölçüm döngüsü kurar. Token'lar köktedir.
+ void kap;
+ document.body.appendChild(olcu);
+ const hesap = getComputedStyle(olcu).color;
+ olcu.remove();
+ boya.clearRect(0, 0, 1, 1);
+ boya.fillStyle = hesap;
+ boya.fillRect(0, 0, 1, 1);
+ const [r, g, b, a2] = boya.getImageData(0, 0, 1, 1).data;
+ return [r / 255, g / 255, b / 255, a2 / 255];
+ };
+
+ // İmleç ışığı her camda ortak; ilk hareketle açılır, imleç pencereden çıkınca söner.
+ const imlec = { x: 0, y: 0, var: false, oynadi: false, karisim: 0 };
+
+ const ciz = (g: Gorunum, yenile: boolean) => {
+ const m = g.mercek(yenile);
+ if (!m || m.en < 2 || m.boy < 2) {
+ g.ctx.clearRect(0, 0, g.tuval.width, g.tuval.height);
+ return;
+ }
+ const st = g.tuval.style;
+ st.left = `${m.sol}px`;
+ st.top = `${m.ust}px`;
+ st.width = `${m.en}px`;
+ st.height = `${m.boy}px`;
+ const dpr = Math.min(window.devicePixelRatio || 1, 2);
+ const devW = Math.max(2, Math.round(m.en * dpr));
+ const devH = Math.max(2, Math.round(m.boy * dpr));
+ if (g.tuval.width !== devW || g.tuval.height !== devH) {
+ g.tuval.width = devW;
+ g.tuval.height = devH;
+ }
+ // Ortak tuval yalnız büyür; her cam sol alt köşesine çizilir.
+ if (glTuval.width < devW || glTuval.height < devH) {
+ glTuval.width = Math.max(glTuval.width, devW);
+ glTuval.height = Math.max(glTuval.height, devH);
+ }
+ gl.viewport(0, 0, devW, devH);
+
+ const b = m.birim;
+ const kirma = m.kirma;
+ if (kirma) {
+ // Katmanlar her karede yeniden çizilir (etiket renkleri geçişte olabilir).
+ [arkaKatman, onKatman].forEach((kat, i) => {
+ const c2 = kat.ctx!;
+ if (kat.tuval.width !== devW || kat.tuval.height !== devH) {
+ kat.tuval.width = devW;
+ kat.tuval.height = devH;
+ }
+ c2.setTransform(1, 0, 0, 1, 0, 0);
+ c2.clearRect(0, 0, devW, devH);
+ c2.setTransform(dpr, 0, 0, dpr, 0, 0);
+ if (i === 1) kirma.boya(arkaKatman.ctx!, c2);
+ });
+ gl.activeTexture(gl.TEXTURE0);
+ gl.bindTexture(gl.TEXTURE_2D, arkaKatman.doku);
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, arkaKatman.tuval);
+ gl.generateMipmap(gl.TEXTURE_2D);
+ gl.activeTexture(gl.TEXTURE1);
+ gl.bindTexture(gl.TEXTURE_2D, onKatman.doku);
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, onKatman.tuval);
+ }
+ gl.uniform1f(u("uDokuVar"), kirma ? 1 : 0);
+ gl.uniform1f(u("uKirilma"), kirma?.kirilma ?? 0);
+ gl.uniform1f(u("uBuyutme"), kirma?.buyutme ?? 0);
+ gl.uniform1f(u("uDagilma"), kirma?.dagilma ?? 0);
+ gl.uniform1f(u("uBulanikOrta"), kirma?.bulanikOrta ?? 0);
+ gl.uniform1f(u("uBulanikKenar"), kirma?.bulanikKenar ?? 0);
+ // Kit: bulanıklık düzeyi ekran yoğunluğuna göre kayar (2,27 px/birim referans).
+ gl.uniform1f(u("uBulanikKayma"), Math.log2(Math.max((b * dpr) / 2.27, 1e-3)));
+ gl.uniform1f(u("uBuz"), kirma?.buz ?? 0);
+ gl.uniform2f(u("uBoyut"), devW, devH);
+ gl.uniform1f(u("uBirim"), b * dpr);
+ gl.uniform1f(u("uPiksel"), 1 / (b * dpr));
+ gl.uniform2f(u("uMerkez"), m.mx / b, m.my / b);
+ gl.uniform2f(u("uYari"), Math.max(m.yx / b, 0.5), Math.max(m.yy / b, 0.5));
+ gl.uniform1f(u("uKose"), Math.max(0, Math.min(m.kose, m.yx - 0.5, m.yy - 0.5) / b));
+ gl.uniform1f(u("uGovdeX"), m.govdeX / b);
+ gl.uniform3f(u("uDamla"), (m.damla?.x ?? 0) / b, (m.damla?.r ?? 0) / b, (m.damla?.k ?? 0) / b);
+ gl.uniform1f(u("uEgim"), Math.max(m.egim, 2));
+ gl.uniform1f(u("uKenar"), 0.55 * m.guc);
+ gl.uniform1f(u("uKostik"), 0.08 * m.guc);
+ gl.uniform1f(u("uIcGolge"), 0.1 * m.guc);
+ gl.uniform1f(u("uUstYansima"), 0.3 * m.guc);
+ gl.uniform1f(u("uUstTaban"), 0.02 * m.guc);
+ gl.uniform1f(u("uGolge"), m.golge * m.guc);
+ gl.uniform1f(u("uGolgeYumusak"), m.golgeYumusak);
+ gl.uniform1f(u("uGolgeKayma"), m.golgeKayma);
+ gl.uniform3f(u("uZemin"), ...m.zemin);
+ gl.uniform3f(u("uRenk"), ...m.renk);
+ gl.uniform1f(u("uTon"), 1);
+ gl.uniform1f(u("uKenarSeffaf"), m.kenarSeffaf);
+ gl.uniform3f(u("uCizgi"), ...(m.cizgi ?? m.renk));
+ gl.uniform1f(u("uCizgiKalin"), m.cizgi ? 1 / b : 0);
+ const dx = imlec.x - m.ekranX;
+ const dy = imlec.y - m.ekranY;
+ const uz = Math.hypot(dx, dy);
+ gl.uniform2f(u("uIsikYonu"), uz > 0.5 ? dx / uz : 0, uz > 0.5 ? dy / uz : -1);
+ gl.uniform1f(u("uIsikKarisim"), m.imlecIsigi ? imlec.karisim : 0);
+ gl.drawArrays(gl.TRIANGLES, 0, 3);
+ g.ctx.clearRect(0, 0, devW, devH);
+ g.ctx.drawImage(glTuval, 0, glTuval.height - devH, devW, devH, 0, 0, devW, devH);
+ g.cizildi?.();
+ };
+
+ let raf = 0;
+ let son = 0;
+ const kare = (simdi: number) => {
+ raf = 0;
+ if (olu) return;
+ const dt = son ? Math.min((simdi - son) / 1000, 1 / 30) : 1 / 60;
+ son = simdi;
+ const dur = azalt.matches;
+ const hedef = imlec.var && !dur ? 1 : 0;
+ const onceki = imlec.karisim;
+ imlec.karisim += (hedef - imlec.karisim) * Math.min(1, dt * 6);
+ if (Math.abs(imlec.karisim - hedef) < 0.002) imlec.karisim = hedef;
+ const isik = imlec.oynadi || imlec.karisim !== onceki;
+ imlec.oynadi = false;
+ let suruyor = imlec.karisim !== hedef;
+
+ for (const g of gorunumler) {
+ const oynuyor = g.adim(dt, dur);
+ if (oynuyor) suruyor = true;
+ if (!g.gorunur) continue;
+ if (oynuyor || g.kirli || isik) {
+ const yenile = g.kirli;
+ g.kirli = false;
+ ciz(g, yenile);
+ }
+ }
+ if (suruyor) raf = requestAnimationFrame(kare);
+ else son = 0;
+ };
+ const uyandir = () => {
+ if (!raf && !olu) raf = requestAnimationFrame(kare);
+ };
+
+ window.addEventListener(
+ "pointermove",
+ (e) => {
+ if (e.pointerType !== "mouse") return;
+ imlec.x = e.clientX;
+ imlec.y = e.clientY;
+ imlec.var = true;
+ imlec.oynadi = true;
+ uyandir();
+ },
+ { passive: true },
+ );
+ document.documentElement.addEventListener("pointerleave", () => {
+ imlec.var = false;
+ imlec.oynadi = true;
+ uyandir();
+ });
+ // Tema değişince renkler yeniden okunur.
+ new MutationObserver(() => {
+ for (const g of gorunumler) g.kirli = true;
+ uyandir();
+ }).observe(document.documentElement, { attributes: true, attributeFilter: ["class"] });
+ // Bağlam kaybolursa her cam sade hâline döner.
+ glTuval.addEventListener("webglcontextlost", () => {
+ olu = true;
+ for (const g of gorunumler) {
+ g.birak();
+ g.ctx.clearRect(0, 0, g.tuval.width, g.tuval.height);
+ }
+ calisma = undefined;
+ });
+
+ return {
+ ekle: (g) => {
+ gorunumler.add(g);
+ uyandir();
+ },
+ cikar: (g) => gorunumler.delete(g),
+ uyandir,
+ renkCoz,
+ renkCozA,
+ };
+}
+
+let calisma: Calisma | null | undefined;
+const calismaAl = () => (calisma === undefined ? (calisma = calismaKur()) : calisma);
/**
- * Bir butonun, hapın ya da bağlantının cam zemini; kabın (`SIVI_KAP` ya da
- * `Button cam="…"`) **ilk çocuğudur**. Kit `GlassLayer`'ıdır: üstüne gelince
- * yaylarla şişer, basınca içindekilerle büyür ve ışık alır, tutup çekince jel
- * gibi uzayıp geri döner, yakınındaki cam butonla birleşir.
- *
- * Varsayılan boyalı camdır: kabın o anki CSS zemini ve kenarlığıyla boyanır.
- * `seffaf` arkasını büken camdır (CTA yüzeyinde mavi boyalı ve canlı, dışında
- * boyasız). Kap ikon + yazı taşıyorsa ikon, fareli cihazda üstüne gelince gövdeden
- * damla olarak ayrılır; yerleşimi `data-sivi` ile globals.css verir.
+ * Turuncu CTA'nın sıvı zemini; `Button variant="cta" cam="…"` ilk çocuk olarak
+ * koyar. İki varyasyon: `duz` (varsayılan kullanım, `cam="damla"`) düz renkli
+ * gövde, cam ışığı ve gölge yok, yalnız sıvı biçim (şişme, damla ayrılması);
+ * `duz` değilse (`cam="cam"`) aynı biçim üstüne tam cam ışığı. Bilal, 12 Kas
+ * 2026: "renkli butonlarda sadece gooey uygulansın, camsılık yalnız şeffaf
+ * butonlarda güzel duruyor" — camlı hâl silinmedi, varyasyon olarak durur.
+ * İlk kare çizilince butona `data-cam` yazılır ve buton düz turuncu zeminini
+ * bırakır. Üstüne gelince cam en ve boyda ayrı yaylarla şişer, basınca büyür;
+ * ölçek butonun kendisine yazılır (yazı camla birlikte büyür). Buton sonda
+ * `ArrowRight` taşıyorsa üstüne gelince ok gövdeden yavaşça bir damla olarak
+ * ayrılır (aradaki sıvı köprü incelip kopar) ve yanında yuvarlak ayrı bir parça
+ * olarak durur; imleç çıkınca ve basınca gövdeye geri karışır.
*/
export function SiviCam({
+ duz = false,
+ yalnizDamla = false,
seffaf = false,
otoDamla = false,
tetik,
hep = false,
}: {
- /** Arkasını büken liquid glass (`Button cam="seffaf"`). */
+ duz?: boolean;
+ /** Camsı görünüm tercihi kapalıyken de kurulur (üst çubuktaki "Yapay Zekâ Listem"; Bilal, 12 Kas 2026: "hep camsı gözükmeli"). */
+ hep?: boolean;
+ /**
+ * Liquid glass CTA (`cam="seffaf"`; CTA yüzeylerinin içinde mavi boyalı,
+ * dışında boyasız): cam, arkasındaki yüzeyi (`[data-cta-yuzey]`: zemin rengi + canlı piksel
+ * tuvalleri) her karede alt katman olarak çizip kenarında büker, ortasında
+ * büyütür; ışık, gölge, şişme, ölçek ve ok damlası vardır.
+ */
seffaf?: boolean;
- /**
- * İkon damlası üstüne gelmeyi beklemez: düğme ekrana girince kendiliğinden
- * ayrılır ve ayrı durur (dokunmatikte de); basınca gövdeye karışır. Yerleşimi
- * kullanan yer kendi sınıflarıyla verir.
- */
- otoDamla?: boolean;
/**
* Üstüne gelme ve basma, kabın kendisi yerine bu seçiciyle bulunan atadan
- * dinlenir (`closest`): tamamı bağlantı olan kartın içindeki hap.
+ * dinlenir (`closest`): tamamı bağlantı olan kartın içindeki hap, kartın
+ * üstüne gelince tepki verir.
*/
tetik?: string;
- /** Sıvı cam tercihi kapalıyken de kurulur (üst çubuktaki profil düğmesi). */
- hep?: boolean;
+ /** İkon yoksa (ya da cihazda fare yoksa) cam kurulmaz, buton kendi hâlindedir. */
+ yalnizDamla?: boolean;
+ /**
+ * İkon damlası üstüne gelmeyi beklemez: düğme ekrana girince kendiliğinden
+ * ayrılır ve ayrı durur (dokunmatikte de); basınca gövdeye karışır, bırakınca
+ * yine ayrılır. Hareketi azalt'ta baştan ayrıdır. Yerleşimi (ikon dairenin,
+ * yazı gövdenin ortasında) kullanan yer kendi sınıflarıyla verir.
+ */
+ otoDamla?: boolean;
}) {
- const izRef = useRef(null);
+ const tuvalRef = useRef(null);
const acik = useCamAcik();
- const kurulu = hep || acik;
- const [kap, setKap] = useState(null);
- const [ustunde, setUstunde] = useState(false);
useEffect(() => {
- const iz = izRef.current;
- const buton = iz?.parentElement;
- if (!iz || !buton || !kurulu) return;
- const fareVar = window.matchMedia("(hover: hover) and (pointer: fine)");
- const azalt = window.matchMedia("(prefers-reduced-motion: reduce)");
- let ikon: Element | null = null;
+ const tuval = tuvalRef.current;
+ const buton = tuval?.parentElement;
+ const ctx = tuval?.getContext("2d");
+ // Camsı görünüm kapalıysa (footer, `cam-tercihi.ts`) cam kurulmaz: sade hâl.
+ const c = hep || (acik && camAcikMi()) ? calismaAl() : null;
+ if (!tuval || !buton || !ctx || !c) return;
- const olc = () => {
- // İkon: kabın doğrudan çocuğu olan, en sondaki ya da en baştaki SVG (yanında
- // başka içerik varken; sondaki öncelikli). Görünmeyen çocuklar (`sr-only`,
- // gizli etiket) sayılmaz: yalnız ikonu görünen hapın ayrılacak gövdesi yoktur.
- const dugumler = [...buton.childNodes].filter((n) => {
- if (n === iz || n instanceof HTMLCanvasElement) return false;
- if (n instanceof SVGElement) return true;
- if (n instanceof HTMLElement) return n.offsetWidth > 1 && n.offsetHeight > 1;
- return !!n.textContent?.trim();
- });
- const bastaki = dugumler[0];
- const sondaki = dugumler[dugumler.length - 1];
- const ok = dugumler.length < 2 ? null : sondaki instanceof SVGElement ? sondaki : bastaki instanceof SVGElement ? bastaki : null;
- // Damla yalnız fareyle üstüne gelinebilen cihazda ayrılır (yerleşim kuralı da öyle).
- const oklu = !!ok && (otoDamla || fareVar.matches);
- const yeni = oklu ? ok : null;
- if (ikon !== yeni) {
- ikon?.removeAttribute("data-glass-drop");
- ikon = yeni;
- ikon?.setAttribute("data-glass-drop", "");
- }
- const uc: Kap["uc"] = !oklu ? "" : ok === bastaki && ok !== sondaki ? "bas" : "son";
- // İkonun oturduğu dairenin çapı kabın gerçek yüksekliğidir.
- if (oklu) buton.style.setProperty("--ok-cap", `${buton.offsetHeight}px`);
- if ((buton.dataset.sivi ?? "") !== uc) buton.dataset.sivi = uc;
- const yuzeyde = seffaf && !!buton.closest("[data-cta-yuzey]");
- setKap((o) => (o && o.yuzeyde === yuzeyde && o.uc === uc ? o : { yuzeyde, uc }));
+ let w = 0;
+ let h = 0;
+ let oklu = false;
+ let zemin: Rgb = [1, 1, 1];
+ /** Şeffaf camın arkasındaki sayfanın ara çizimi (CTA yüzeyi dışında; aşağıda `boya`). */
+ const sayfa = {
+ tuval: document.createElement("canvas"),
+ ctx: null as CanvasRenderingContext2D | null,
+ anahtar: "",
+ an: 0,
+ eski: true,
+ };
+ /** İkon hangi uçta: sondaysa damla sağa (1), baştaysa sola (−1) ayrılır. */
+ let yon = 1;
+ // Gövde ve kenarlık renkleri butonun kendi CSS'inden okunur (durağan, üstünde,
+ // seçili… hangi hâldeyse); [önceki, yeni] arasında yumuşakça geçilir.
+ let renk: [Rgb, Rgb] = [[1, 1, 1], [1, 1, 1]];
+ let cizgi: [Rgb, Rgb] | null = null;
+ let gorunmez = false;
+ let ornekVar = false;
+ let basili = false;
+ let ustunde = false;
+ let hazir = false;
+ /** Üstüne gelme rengi geçişi (0–1). */
+ let renkGecis = 0;
+ const karistir = (a: Rgb, b: Rgb, t: number): Rgb => [ara(a[0], b[0], t), ara(a[1], b[1], t), ara(a[2], b[2], t)];
+ const basma: Yay = { x: 0, v: 0 };
+ const ustX: Yay = { x: 0, v: 0 };
+ const ustY: Yay = { x: 0, v: 0 };
+ const olcek: Yay = { x: 1, v: 0 };
+ const damla: Yay = { x: 0, v: 0 };
+ const enCok = () => 1 + (2 * EN_COK_BUYUME) / Math.max(w, 1);
+ const fareVar = window.matchMedia("(hover: hover) and (pointer: fine)");
+
+ const g: Gorunum = {
+ tuval,
+ ctx,
+ kirli: true,
+ gorunur: false,
+ adim: (dt, dur) => {
+ if (dur) {
+ // Hareketi azalt: cam durağan, buton ölçeklenmez, damla ayrılmaz.
+ basma.x = ustX.x = ustY.x = basma.v = ustX.v = ustY.v = 0;
+ damla.x = otoDamla && oklu ? 1 : 0;
+ damla.v = 0;
+ olcek.x = 1;
+ buton.style.scale = "";
+ const fark = renkGecis !== 1;
+ renkGecis = 1;
+ if (fark) g.kirli = true;
+ return false;
+ }
+ // Sıvı zemin kurulu her butonda aynı: üstüne gelince şişer, basınca büyür;
+ // ölçek butonun kendisine yazıldığı için içindeki yazı ve ikon da büyür.
+ // İkonu olmayan (cam kurulmayan) butona dokunulmaz.
+ const canli = !yalnizDamla || oklu;
+ const ust = ustunde && canli ? 1 : 0;
+ const olcekHedef = !canli ? 1 : basili ? Math.min(BASMA_OLCEGI, enCok()) : ustunde ? Math.min(USTUNDE_OLCEGI, enCok()) : 1;
+ const b = yayAdim(basma, basili && canli ? 1 : 0, CAM_YAYI.basma, dt);
+ const x = yayAdim(ustX, ust, CAM_YAYI.ustundeEn, dt);
+ const y = yayAdim(ustY, ust, CAM_YAYI.ustundeBoy, dt);
+ const o = yayAdim(olcek, olcekHedef, CAM_YAYI.basma, dt);
+ // Damla üstüne gelince ayrılır; çıkınca ve basınca gövdeye geri karışır.
+ const ayri = (otoDamla ? g.gorunur : ustunde) && !basili;
+ const d = oklu ? yayAdim(damla, ayri ? 1 : 0, ayri ? CAM_YAYI.damla : CAM_YAYI.damlaDonus, dt) : false;
+ if (canli || buton.style.scale) buton.style.scale = olcek.x === 1 ? "" : olcek.x.toFixed(4);
+ // Renk değişimi ≈ 150 ms'de geçer (butonun kendi CSS geçişi gibi).
+ const r = 1 - renkGecis > 0.004;
+ renkGecis = r ? renkGecis + (1 - renkGecis) * Math.min(1, dt * 14) : 1;
+ // Şeffaf cam arkasındaki canlı tuvali yansıtır: ekrandayken her karede çizilir.
+ return b || x || y || o || d || r || (seffaf && g.gorunur);
+ },
+ mercek: (yenile) => {
+ if (yenile) {
+ w = buton.offsetWidth;
+ h = buton.offsetHeight;
+ // İkon: butonun doğrudan çocuğu olan, en sondaki ya da en baştaki SVG
+ // (yanında başka içerik varken). Sondaki öncelikli.
+ // Görünmeyen çocuklar (gizli etiket, `sr-only`) sayılmaz: yalnız ikonu
+ // görünen hap ikon butonudur, ayrılacak gövdesi yoktur.
+ const dugumler = [...buton.childNodes].filter((n) => {
+ if (n === tuval) return false;
+ if (n instanceof SVGElement) return true;
+ if (n instanceof HTMLElement) return n.offsetWidth > 1 && n.offsetHeight > 1;
+ return !!n.textContent?.trim();
+ });
+ const bastaki = dugumler[0];
+ const sondaki = dugumler[dugumler.length - 1];
+ const ok = dugumler.length < 2 ? null : sondaki instanceof SVGElement ? sondaki : bastaki instanceof SVGElement ? bastaki : null;
+ yon = ok && ok === bastaki && ok !== sondaki ? -1 : 1;
+ // Damla yalnız fareyle üstüne gelinebilen cihazda ayrılır (yerleşim kuralı da öyle).
+ oklu = !!ok && (otoDamla || fareVar.matches);
+ // İkonun oturduğu dairenin çapı butonun gerçek yüksekliğidir; ikonun ucu
+ // `data-sivi` ile yerleşim kuralına (globals.css) bildirilir.
+ const uc = !oklu ? "" : yon < 0 ? "bas" : "son";
+ if (oklu) buton.style.setProperty("--ok-cap", `${h}px`);
+ if ((buton.dataset.sivi ?? "") !== uc) {
+ buton.dataset.sivi = uc;
+ // Dolgu değişti: boy bir sonraki ölçümde güncellenir.
+ g.kirli = true;
+ c.uyandir();
+ }
+ zemin = c.renkCoz(buton, zeminRengi(buton.parentElement));
+ if (seffaf) {
+ // Boyasız cam: gövde rengi yok, hafif beyaz tonu gölgelendirici verir.
+ // CTA yüzeyi dışında ("Giriş yap") `renk` camın tintidir (aşağıda `buz`):
+ // kitin kart örneğindeki gibi açık temada beyaz, koyu temada siyah.
+ // CTA yüzeyinde cam mavi boyalıdır (Bilal, 12 Kas 2026: "şeffaf yerine mavi").
+ // Mavi bantta boya bir ton koyudur: cam, kendi rengindeki zeminden ayrılsın.
+ const yuzey = buton.closest("[data-cta-yuzey]");
+ const yuzeyde = !!yuzey;
+ const koyu = !yuzeyde && document.documentElement.classList.contains("dark");
+ const mavi = c.renkCoz(
+ buton,
+ yuzey?.dataset.ctaTon === "mavi" ? "color-mix(in oklch, var(--primary), black 28%)" : "var(--primary)",
+ );
+ renk = yuzeyde ? [mavi, mavi] : koyu ? [[0, 0, 0], [0, 0, 0]] : [[1, 1, 1], [1, 1, 1]];
+ cizgi = null;
+ gorunmez = false;
+ renkGecis = 1;
+ ornekVar = true;
+ } else {
+ // Butonun kendi zemini ve kenarlığı: `data-cam` bir an kaldırılıp okunur
+ // (geçişler kapalıyken; arada boyama olmaz).
+ const vardi = "cam" in buton.dataset;
+ const gecis0 = buton.style.transition;
+ buton.style.transition = "none";
+ if (vardi) delete buton.dataset.cam;
+ const st = getComputedStyle(buton);
+ const dolgu = c.renkCozA(buton, st.backgroundColor);
+ const kenarKalin = st.borderTopStyle === "solid" ? parseFloat(st.borderTopWidth) || 0 : 0;
+ const kenar = c.renkCozA(buton, st.borderTopColor);
+ const cizilemez = st.backgroundImage !== "none" || (st.borderTopStyle !== "solid" && st.borderTopStyle !== "none");
+ if (vardi) {
+ buton.dataset.cam = "";
+ void getComputedStyle(buton).backgroundColor;
+ }
+ buton.style.transition = gecis0;
+ const yeniRenk = karistir(zemin, [dolgu[0], dolgu[1], dolgu[2]], dolgu[3]);
+ const yeniCizgi: Rgb | null =
+ kenarKalin > 0 && kenar[3] > 0.02 ? karistir(yeniRenk, [kenar[0], kenar[1], kenar[2]], kenar[3]) : null;
+ gorunmez = cizilemez || (dolgu[3] < 0.02 && !yeniCizgi);
+ const simdiRenk = ornekVar ? karistir(renk[0], renk[1], renkGecis) : yeniRenk;
+ const simdiCizgi = ornekVar && cizgi ? karistir(cizgi[0], cizgi[1], renkGecis) : (yeniCizgi ?? yeniRenk);
+ const degisti = ornekVar && (simdiRenk.some((v, n) => Math.abs(v - yeniRenk[n]) > 0.004) || !!cizgi !== !!yeniCizgi);
+ renk = [simdiRenk, yeniRenk];
+ cizgi = yeniCizgi ? [simdiCizgi, yeniCizgi] : null;
+ renkGecis = degisti ? 0 : 1;
+ ornekVar = true;
+ if (degisti) c.uyandir();
+ }
+ }
+ if (w < 2 || h < 2) return null;
+ if ((yalnizDamla && !oklu) || gorunmez) {
+ // İkon yok, buton dar ya da zemini çizilemez: cam kurulmaz, buton kendi zeminindedir.
+ if (hazir) {
+ hazir = false;
+ delete buton.dataset.cam;
+ }
+ return null;
+ }
+ const payX = 8;
+ const payUst = 10;
+ const payAlt = Math.round(h * 0.8 + 4);
+ // Kit `pressedLens` + üstüne gelince büyüme. Ölçek butonun kendisine
+ // uygulanır; camın tuval içindeki boyu ona bölünür ki ekrandaki cam
+ // kitteki ölçüye otursun.
+ const p = sinirla(basma.x, -0.12, 1.15);
+ const s = Math.max(0.5, olcek.x);
+ const carpan = ara(1, Math.min(BASMA_OLCEGI, enCok()), p) / s;
+ const buyume = (h * USTUNDE_BUYUME) / s;
+ const t = oklu ? sinirla(damla.x, 0, 1.06) : 0;
+ const geri = h * (1 + DAMLA_ARALIGI) * t;
+ const yy = (h / 2) * carpan + buyume * ustY.x;
+ const k = buton.getBoundingClientRect();
+ const pc = sinirla(basma.x);
+ return {
+ // Tuval butonun dolgu kutusuna göre konumlanır; cam ise kenarlık
+ // kutusuna göre ölçülür. Kenarlık kalınlığı düşülmezse cam 1 px sağa
+ // ve aşağı kayar, ikon dairenin tam ortasına oturmaz.
+ sol: -payX - buton.clientLeft,
+ ust: -payUst - buton.clientTop,
+ en: w + 2 * payX,
+ boy: h + payUst + payAlt,
+ birim: h / BIRIM_YUKSEKLIK,
+ mx: payX + w / 2,
+ my: payUst + h / 2,
+ yx: (w / 2 - geri / 2) * carpan + buyume * ustX.x,
+ yy,
+ kose: 999,
+ govdeX: ((-yon * geri) / 2) * carpan,
+ damla:
+ t > 0.001
+ ? {
+ x: yon * ((w / 2 - h / 2) * carpan + buyume * ustX.x * 0.5),
+ r: yy,
+ // Sıvı köprü: ayrılma başlarken açılır, kopunca kapanır.
+ k: h * 0.34 * yumusak(0, 0.15, t) * (1 - yumusak(0.8, 1, t)),
+ }
+ : undefined,
+ // Kit `pressedLens`: basınca eğim genişler, gölge derinleşir.
+ egim: ara(BIRIM_YUKSEKLIK * 0.42, 62, pc),
+ golge: 0.12 * ara(0.55, 1, pc),
+ golgeYumusak: 34 * ara(0.6, 1, pc),
+ golgeKayma: 22 * ara(0.5, 1, pc),
+ // `duz`: cam ışığı ve gölge yok; düz renk, yalnız sıvı biçim.
+ guc: duz ? 0 : 1,
+ renk: karistir(renk[0], renk[1], renkGecis),
+ cizgi: cizgi ? karistir(cizgi[0], cizgi[1], renkGecis) : undefined,
+ zemin,
+ kenarSeffaf: duz ? 0 : 0.2,
+ imlecIsigi: !duz,
+ kirma: seffaf
+ ? {
+ boya: (arka) => {
+ arka.translate(payX, payUst);
+ const rgb = (v: Rgb) => `rgb(${Math.round(v[0] * 255)} ${Math.round(v[1] * 255)} ${Math.round(v[2] * 255)})`;
+ arka.fillStyle = rgb(zemin);
+ arka.fillRect(-payX, -payUst, w + 2 * payX, h + payUst + payAlt);
+ const ctaYuzeyi = buton.closest("[data-cta-yuzey]");
+ const yuzey = ctaYuzeyi ?? document.body;
+ // Düzen kutusunun köşesi (ölçek butonun kendisine uygulanıyor).
+ const kb = buton.getBoundingClientRect();
+ const lx = kb.left + (kb.width - w) / 2;
+ const ly = kb.top + (kb.height - h) / 2;
+ // CTA yüzeyi dışındaki cam (üst çubuktaki "Giriş yap"): arkasından
+ // geçen sayfanın kendisi (yazı, kart, ikon, resim) bükülür. Sayfa
+ // `domuCiz` ile bir ara tuvale çizilir; kaydırınca, cam yer
+ // değiştirince ve en geç 120 ms'de bir yenilenir (her karede DOM
+ // taranmaz).
+ if (!ctaYuzeyi) {
+ const hedef = arka.canvas;
+ const anahtar = `${hedef.width}:${hedef.height}:${Math.round(lx * 2)}:${Math.round(ly * 2)}:${Math.round(window.scrollX)}:${Math.round(window.scrollY)}`;
+ const simdi = performance.now();
+ if (!sayfa.ctx) sayfa.ctx = sayfa.tuval.getContext("2d");
+ if (sayfa.ctx && (sayfa.eski || anahtar !== sayfa.anahtar || simdi - sayfa.an > 120)) {
+ sayfa.eski = false;
+ sayfa.anahtar = anahtar;
+ sayfa.an = simdi;
+ if (sayfa.tuval.width !== hedef.width || sayfa.tuval.height !== hedef.height) {
+ sayfa.tuval.width = hedef.width;
+ sayfa.tuval.height = hedef.height;
+ }
+ const sc = sayfa.ctx;
+ sc.setTransform(1, 0, 0, 1, 0, 0);
+ sc.clearRect(0, 0, hedef.width, hedef.height);
+ sc.setTransform(arka.getTransform());
+ domuCiz(
+ sc,
+ document.body,
+ new DOMRect(lx, ly, w, h),
+ () => {
+ sayfa.eski = true;
+ },
+ // Üst çubuğun altındaki sayfa bulanıklığı (`.kt-sayfa-blur`) camda
+ // uygulanmaz: cam arkasındakini net kırar (Bilal, 12 Kas 2026).
+ (el) => el === buton || el.classList.contains("kt-sayfa-blur"),
+ new DOMRect(lx - payX, ly - payUst, w + 2 * payX, h + payUst + payAlt),
+ );
+ }
+ if (sayfa.tuval.width && sayfa.tuval.height) {
+ arka.save();
+ arka.setTransform(1, 0, 0, 1, 0, 0);
+ arka.drawImage(sayfa.tuval, 0, 0);
+ arka.restore();
+ }
+ }
+ // Sayfa çiziminde tuvaller zaten yerinde (üstlerindeki perdeyle birlikte).
+ if (ctaYuzeyi) for (const cv of yuzey.querySelectorAll("canvas")) {
+ if (cv === tuval || cv.closest("[data-slot='button']") || !cv.width || !cv.height) continue;
+ const r = cv.getBoundingClientRect();
+ if (r.right < lx - payX || r.left > lx + w + payX || r.bottom < ly - payUst || r.top > ly + h + payAlt) continue;
+ arka.drawImage(cv, r.left - lx, r.top - ly, r.width, r.height);
+ }
+ },
+ // CTA yüzeyi dışında (üst çubuktaki "Giriş yap") optik, kitin "How the
+ // glass works" merceğidir (`HowItWorks.tsx`: `sliderOptics`, 100 px'lik
+ // mercek, bizim 120'lik birime çevrildi): dururken de güçlü kırılma
+ // (37 px → 44 birim; basınca 37), büyütme yok, ortası net; üstünde kart tinti.
+ ...(buton.closest("[data-cta-yuzey]")
+ ? {
+ kirilma: ara(10, 32, pc),
+ buyutme: 0.08 + 0.1 * pc,
+ dagilma: 0.14,
+ bulanikOrta: 0.5,
+ bulanikKenar: 2,
+ // Mavi boya ("Yeni" rozetindeki gibi): arkası boyanın ardından hafifçe seçilir.
+ buz: CTA_BOYASI,
+ }
+ : {
+ kirilma: ara(44, 37, pc),
+ buyutme: 0,
+ dagilma: 0.12,
+ bulanikOrta: 0.35,
+ bulanikKenar: 2.2,
+ // Tint: kitin kart örneği (`GlassCardExamples`) gibi %60.
+ buz: 0.6,
+ }),
+ }
+ : undefined,
+ ekranX: k.left + k.width / 2,
+ ekranY: k.top + k.height / 2,
+ };
+ },
+ cizildi: () => {
+ if (hazir) return;
+ hazir = true;
+ buton.dataset.cam = "";
+ },
+ birak: () => {
+ delete buton.dataset.cam;
+ buton.style.scale = "";
+ },
};
- olc();
const kapali = () => buton.matches(":disabled, [aria-disabled='true']");
- const gir = (e: PointerEvent) => {
- if (e.pointerType !== "mouse" || kapali() || azalt.matches) return;
- setUstunde(true);
+ const kirlet = () => {
+ g.kirli = true;
+ c.uyandir();
+ };
+ const bas = () => {
+ if (kapali()) return;
+ basili = true;
+ c.uyandir();
+ };
+ const birak = () => {
+ basili = false;
+ c.uyandir();
+ };
+ const gir = (e: PointerEvent) => {
+ if (e.pointerType !== "mouse" || kapali()) return;
+ ustunde = true;
+ kirlet();
+ };
+ const cik = () => {
+ basili = false;
+ ustunde = false;
+ kirlet();
};
- const cik = () => setUstunde(false);
const dinlenen: HTMLElement = (tetik ? buton.closest(tetik) : null) ?? buton;
+ dinlenen.addEventListener("pointerdown", bas);
+ dinlenen.addEventListener("pointerup", birak);
+ dinlenen.addEventListener("pointercancel", birak);
dinlenen.addEventListener("pointerenter", gir);
dinlenen.addEventListener("pointerleave", cik);
- // İçerik değişince (artı ↔ tik, ok ↔ bekleme simgesi) ikon yeniden bulunur.
- const mo = new MutationObserver(olc);
- mo.observe(buton, { childList: true });
- const ro = new ResizeObserver(olc);
+ const io = new IntersectionObserver(([giris]) => {
+ g.gorunur = giris.isIntersecting;
+ kirlet();
+ });
+ io.observe(buton);
+ const ro = new ResizeObserver(kirlet);
ro.observe(buton);
+ // İçerik değişince (ok ↔ bekleme simgesi) damla yeniden değerlendirilir.
+ const mo = new MutationObserver(kirlet);
+ mo.observe(buton, {
+ childList: true,
+ attributes: true,
+ attributeFilter: ["class", "disabled", "aria-pressed", "aria-checked", "aria-selected", "aria-expanded", "data-state"],
+ });
+ c.ekle(g);
return () => {
- mo.disconnect();
+ c.cikar(g);
+ // Cam kapatılınca (cam-tercihi) tuvalde son kare ve gölgesi kalmasın.
+ ctx.clearRect(0, 0, tuval.width, tuval.height);
+ io.disconnect();
ro.disconnect();
+ mo.disconnect();
+ dinlenen.removeEventListener("pointerdown", bas);
+ dinlenen.removeEventListener("pointerup", birak);
+ dinlenen.removeEventListener("pointercancel", birak);
dinlenen.removeEventListener("pointerenter", gir);
dinlenen.removeEventListener("pointerleave", cik);
- ikon?.removeAttribute("data-glass-drop");
+ delete buton.dataset.cam;
+ buton.style.scale = "";
buton.style.removeProperty("--ok-cap");
- setUstunde(false);
};
- }, [kurulu, seffaf, otoDamla, tetik]);
+ }, [duz, yalnizDamla, seffaf, otoDamla, tetik, acik, hep]);
- return (
- <>
-
-
- >
- );
+ return ;
+}
+
+type Kutu = { x: number; y: number; w: number; h: number };
+
+/** Kit `SegmentedControl`: bir seçenek 80 birim yüksekliğindedir; optikler 0,9 ölçekli. */
+const SEKME_BIRIM = 80;
+const SEKME_OPTIK = (SEKME_BIRIM * (1 + KAYARKEN_BOY)) / BIRIM_YUKSEKLIK;
+
+const svgOnbellek = new WeakMap>();
+
+/** SVG ikonu verilen renkte resim olarak çizer (renk başına bir kez kurulur). */
+function svgCiz(ctx: CanvasRenderingContext2D, el: SVGSVGElement, renk: string, x: number, y: number, w: number, h: number, yeniden: () => void) {
+ let renkler = svgOnbellek.get(el);
+ if (!renkler) svgOnbellek.set(el, (renkler = new Map()));
+ let resim = renkler.get(renk);
+ if (!resim) {
+ const kopya = el.cloneNode(true) as SVGSVGElement;
+ kopya.removeAttribute("class");
+ kopya.setAttribute("xmlns", "http://www.w3.org/2000/svg");
+ kopya.setAttribute("width", String(w));
+ kopya.setAttribute("height", String(h));
+ kopya.style.color = renk;
+ resim = new Image();
+ resim.onload = yeniden;
+ resim.src = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(new XMLSerializer().serializeToString(kopya))}`;
+ renkler.set(renk, resim);
+ }
+ if (resim.complete && resim.naturalWidth) ctx.drawImage(resim, x, y, w, h);
}
/**
- * Tek seçimli sekmelerde seçenekten seçeneğe kayan cam mercek (§4.22, §4.50); kit
- * `GlassLens`'idir. Kabın (`relative isolate`) ilk çocuğudur; seçenekler
- * `role="radio"` ya da `role="tab"`, seçili seçeneğin düz vurgusu
- * `data-glass-highlight` taşır. Mercek görünürken kaba `data-glass-moving` (düz
- * vurgu gizlenir) ve `data-glass-traveling` (seçili etiket seçilmemiş gibi boyanır)
- * yazılır. Basılı tutunca yerinde açılır, sürüklenir, seçim bırakışta. Tercih
- * kapalıyken ve WebGL2 yokken görünen, eski düz vurgudur.
+ * Sekme kabını iki katmana çizer: `arka` camın altında kalan her şey (zemin,
+ * kenarlık, etiket ve ikonlar kendi renginde), `on` yalnız etiket ve ikonlar,
+ * seçili renkte (buzlu hapın üstünde duran kopya). Başlangıç kabın sol üstü.
+ */
+function sekmeyiCiz(
+ arka: CanvasRenderingContext2D,
+ on: CanvasRenderingContext2D,
+ kap: HTMLElement,
+ seciliRenk: string,
+ yeniden: () => void,
+) {
+ const k0 = kap.getBoundingClientRect();
+ const yuru = (el: Element) => {
+ if (el instanceof HTMLCanvasElement || el.hasAttribute("data-cam-vurgu")) return;
+ const st = getComputedStyle(el);
+ if (st.display === "none" || st.visibility === "hidden") return;
+ const r = el.getBoundingClientRect();
+ const x = r.left - k0.left;
+ const y = r.top - k0.top;
+ if (el instanceof SVGSVGElement) {
+ if (r.width < 1 || r.height < 1) return;
+ svgCiz(arka, el, st.color, x, y, r.width, r.height, yeniden);
+ svgCiz(on, el, seciliRenk, x, y, r.width, r.height, yeniden);
+ return;
+ }
+ if (st.display !== "contents" && r.width > 1 && r.height > 1) {
+ const yaricap = Math.min(parseFloat(st.borderTopLeftRadius) || 0, r.width / 2, r.height / 2);
+ if (gorunurRenk(st.backgroundColor)) {
+ arka.beginPath();
+ arka.roundRect(x, y, r.width, r.height, yaricap);
+ arka.fillStyle = st.backgroundColor;
+ arka.fill();
+ }
+ const kalinlik = parseFloat(st.borderTopWidth) || 0;
+ if (kalinlik > 0 && st.borderTopStyle !== "none" && gorunurRenk(st.borderTopColor)) {
+ arka.beginPath();
+ arka.roundRect(x + kalinlik / 2, y + kalinlik / 2, r.width - kalinlik, r.height - kalinlik, Math.max(0, yaricap - kalinlik / 2));
+ arka.lineWidth = kalinlik;
+ arka.strokeStyle = st.borderTopColor;
+ arka.stroke();
+ }
+ }
+ for (const n of el.childNodes) {
+ if (n instanceof Element) yuru(n);
+ else if (n.nodeType === Node.TEXT_NODE && n.textContent?.trim()) {
+ const aralik = document.createRange();
+ aralik.selectNodeContents(n);
+ const m = aralik.getBoundingClientRect();
+ if (m.width < 1) continue;
+ const metin = n.textContent.trim();
+ for (const [ctx, renk] of [[arka, st.color], [on, seciliRenk]] 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 o = ctx.measureText(metin);
+ const cikinti = o.fontBoundingBoxAscent;
+ const inme = o.fontBoundingBoxDescent;
+ ctx.fillStyle = renk;
+ ctx.fillText(metin, m.left - k0.left, m.top - k0.top + (m.height - cikinti - inme) / 2 + cikinti);
+ }
+ }
+ }
+ };
+ yuru(kap);
+}
+
+/**
+ * Tek seçimli sekmelerde seçenekten seçeneğe kayan cam mercek (§4.22, §4.50).
+ * Hareket kit `SegmentedControl`'un aynısıdır:
+ * - Basılı tutunca mercek olduğu yerde şişer ve şeffaf cama döner (basma yayı).
+ * - Sürükleyince (4 px'ten sonra) merceğin merkezi parmağı sıkı bir yayla izler
+ * (40 rad/sn, sekmesiz); bırakınca en yakın seçenek seçilir.
+ * - Seçim değişince merkez yeni seçeneğe yumuşak yayla gider (14 rad/sn, sekme
+ * 0,25); hedefe seçenek eninin %6'sı kalana dek mercek açık kalır, sonra
+ * buzlanıp düz vurguya oturur.
+ * Mercek altındaki seçenekleri kenarında büker, ortasında büyütür; etiketlerin
+ * üstündedir. Kabın (`relative isolate`) ilk çocuğudur; seçili seçeneğin düz
+ * vurgusu `data-cam-vurgu` taşır, seçenekler `role="radio"` ya da `role="tab"`dır.
+ *
+ * Mercek görünürken kaba iki işaret yazılır: `data-cam-geziyor` (düz vurgu
+ * gizlenir: `[[data-cam-geziyor]_&]:opacity-0!`; motion satır içi opaklık
+ * yazdığı için önemli) ve `data-cam-yolda` (seçili seçenek seçilmemiş gibi
+ * boyanır, şeffaf camın altında okunsun; mercek buzlanmaya başlayınca kalkar,
+ * etiket seçili rengine camın altında döner). Durağanken ve WebGL2 yokken
+ * görünen, eski düz vurgudur. Seçimi seçeneğin kendi tıklaması yapar;
+ * sürükleyip bırakınca en yakın seçeneğe tıklama gönderilir.
*/
export function KayanCam({ secili }: { secili: string | null }) {
+ const tuvalRef = useRef(null);
const acik = useCamAcik();
- return ;
+ const esitleRef = useRef<((kay: boolean) => void) | null>(null);
+
+ useEffect(() => {
+ const tuval = tuvalRef.current;
+ const kap = tuval?.parentElement;
+ const ctx = tuval?.getContext("2d");
+ // Camsı görünüm kapalıysa (footer, `cam-tercihi.ts`) cam kurulmaz: sade hâl.
+ const c = acik && camAcikMi() ? calismaAl() : null;
+ if (!tuval || !kap || !ctx || !c) return;
+ const azaltSorgu = window.matchMedia("(prefers-reduced-motion: reduce)");
+
+ let hedef: Kutu | null = null;
+ /** Mercek tuvalde (basılı, yolda ya da oturuyor). */
+ let aktif = false;
+ let basili = false;
+ /** Sürüklenirken parmağın kap içindeki x'i. */
+ let surukle: number | null = null;
+ let renk: Rgb = [0, 0, 0];
+ let zemin: Rgb = [1, 1, 1];
+ /** Seçili etiketin rengi (durağanken okunur; mercek görünürken seçenek normal boyalıdır). */
+ let seciliRenk = "white";
+ const mx: Yay = { x: 0, v: 0 };
+ const my: Yay = { x: 0, v: 0 };
+ const en: Yay = { x: 0, v: 0 };
+ const boy: Yay = { x: 0, v: 0 };
+ const basma: Yay = { x: 0, v: 0 };
+ const yerles = (k: Kutu) => {
+ mx.x = k.x;
+ my.x = k.y;
+ en.x = k.w;
+ boy.x = k.h;
+ mx.v = my.v = en.v = boy.v = 0;
+ };
+ const secenekler = () =>
+ [...kap.querySelectorAll('[role="radio"], [role="tab"]')].map((oge) => {
+ const a = kap.getBoundingClientRect();
+ const b = oge.getBoundingClientRect();
+ return { oge, x: b.left - a.left + b.width / 2, y: b.top - a.top + b.height / 2, w: b.width, h: b.height };
+ });
+ /** Verilen noktaya en yakın seçenek (satır kırılmışsa önce satır). */
+ const enYakin = (x: number, y: number) => {
+ let iyi: ReturnType[number] | null = null;
+ let uzaklik = Infinity;
+ for (const sc of secenekler()) {
+ const u2 = Math.abs(sc.x - x) + Math.abs(sc.y - y) * 4;
+ if (u2 < uzaklik) {
+ uzaklik = u2;
+ iyi = sc;
+ }
+ }
+ return iyi;
+ };
+ const dur = () => {
+ aktif = false;
+ basma.x = basma.v = 0;
+ if (hedef) yerles(hedef);
+ delete kap.dataset.camGeziyor;
+ delete kap.dataset.camYolda;
+ g.kirli = true;
+ // Etiket seçili rengine dönünce tazele (tema değişmiş olabilir).
+ window.setTimeout(() => {
+ const oge = kap.querySelector("[data-cam-vurgu]")?.parentElement;
+ if (!aktif && oge) seciliRenk = getComputedStyle(oge).color;
+ }, 400);
+ };
+ const baslat = () => {
+ if (aktif || !hedef) return;
+ yerles(hedef);
+ aktif = true;
+ };
+
+ const g: Gorunum = {
+ tuval,
+ ctx,
+ kirli: false,
+ gorunur: false,
+ adim: (dt, azalt) => {
+ if (!aktif || !hedef) return false;
+ if (azalt) {
+ dur();
+ return false;
+ }
+ // Hedef: sürüklerken parmak (en yakın seçeneğin satırı ve boyu), yoksa seçili seçenek.
+ let h2: Kutu = hedef;
+ if (surukle !== null) {
+ const sc = secenekler();
+ const yakin = enYakin(surukle, my.x);
+ if (yakin && sc.length) {
+ const xs = sc.map((o) => o.x);
+ h2 = { x: sinirla(surukle, Math.min(...xs), Math.max(...xs)), y: yakin.y, w: yakin.w, h: yakin.h };
+ }
+ }
+ const yay = surukle !== null ? CAM_YAYI.surukleme : CAM_YAYI.kayma;
+ const a1 = yayAdim(mx, h2.x, yay, dt);
+ const a2 = yayAdim(my, h2.y, yay, dt);
+ const a3 = yayAdim(en, h2.w, yay, dt);
+ const a4 = yayAdim(boy, h2.h, yay, dt);
+ // Kit: hedefe seçenek eninin %6'sı kalana dek mercek açık.
+ const yolda = surukle === null && Math.hypot(mx.x - h2.x, my.x - h2.y) > hedef.w * 0.06;
+ const acik = basili || yolda;
+ if (!acik) delete kap.dataset.camYolda;
+ else if ("camGeziyor" in kap.dataset) kap.dataset.camYolda = "";
+ const b = yayAdim(basma, acik ? 1 : 0, CAM_YAYI.basma, dt);
+ const oynuyor = a1 || a2 || a3 || a4 || b;
+ if (!oynuyor && !basili) dur();
+ return oynuyor;
+ },
+ mercek: () => {
+ if (!aktif || !hedef) return null;
+ // Kit `pressedLens`, dinlenme buzu 1: p basma yayı, açıklık = pc.
+ const p = sinirla(basma.x, -0.12, 1.15);
+ const pc = sinirla(basma.x);
+ const buz = 1 - pc;
+ const payX = 16;
+ const payUst = Math.round(hedef.h * 0.3 + 6);
+ const payAlt = Math.round(hedef.h * 1.1 + 8);
+ const kutu = kap.getBoundingClientRect();
+ return {
+ sol: -payX,
+ ust: -payUst,
+ en: kap.offsetWidth + 2 * payX,
+ boy: kap.offsetHeight + payUst + payAlt,
+ birim: hedef.h / SEKME_BIRIM,
+ mx: payX + mx.x,
+ my: payUst + my.x,
+ yx: (en.x / 2) * (1 + KAYARKEN_EN * p),
+ yy: (boy.x / 2) * (1 + KAYARKEN_BOY * p),
+ kose: 999,
+ govdeX: 0,
+ egim: ara(SEKME_BIRIM * 0.42, 62 * SEKME_OPTIK, pc),
+ golge: 0.12 * ara(0.55, 1, pc),
+ golgeYumusak: 34 * SEKME_OPTIK * ara(0.6, 1, pc),
+ golgeKayma: 22 * SEKME_OPTIK * ara(0.5, 1, pc),
+ guc: pc,
+ renk,
+ zemin,
+ kenarSeffaf: 0,
+ kirma: {
+ boya: (arka, on) => {
+ arka.translate(payX, payUst);
+ on.translate(payX, payUst);
+ sekmeyiCiz(arka, on, kap, seciliRenk, () => {
+ g.kirli = true;
+ c.uyandir();
+ });
+ },
+ kirilma: ara(6, 37, pc) * SEKME_OPTIK * ara(0.06, 1, pc),
+ buyutme: 0.12 * pc,
+ dagilma: 0.12 * pc,
+ bulanikOrta: ara(0.35, 4, buz),
+ bulanikKenar: ara(2.2, 4, buz),
+ buz,
+ },
+ imlecIsigi: false,
+ ekranX: kutu.left + mx.x,
+ ekranY: kutu.top + my.x,
+ };
+ },
+ // Düz vurgu ancak mercek ilk karesini çizince gizlenir (arada boş kare olmaz).
+ cizildi: () => {
+ if (!aktif || "camGeziyor" in kap.dataset) return;
+ kap.dataset.camGeziyor = "";
+ kap.dataset.camYolda = "";
+ },
+ birak: () => {
+ basili = false;
+ surukle = null;
+ dur();
+ },
+ };
+
+ // Seçili vurgunun kap içindeki yeri (merkez + boy).
+ const olc = (): Kutu | null => {
+ const v = kap.querySelector("[data-cam-vurgu]");
+ const oge = v?.parentElement;
+ if (!v || !oge) return null;
+ const a = kap.getBoundingClientRect();
+ const b = oge.getBoundingClientRect();
+ if (b.width < 2 || b.height < 2) return null;
+ renk = c.renkCoz(kap, getComputedStyle(v).backgroundColor);
+ zemin = c.renkCoz(kap, zeminRengi(kap.parentElement));
+ if (!aktif) seciliRenk = getComputedStyle(oge).color;
+ return { x: b.left - a.left + b.width / 2, y: b.top - a.top + b.height / 2, w: b.width, h: b.height };
+ };
+ const esitle = (kay: boolean) => {
+ // Seçili renk, seçim değişmeden önceki durağan hâlden kalır: yeni seçili
+ // etiket bu anda renk geçişinin başındadır.
+ const oncekiRenk = seciliRenk;
+ const eski = hedef;
+ const yeni = olc();
+ const ayni =
+ !!yeni && !!eski && Math.abs(yeni.x - eski.x) < 0.5 && Math.abs(yeni.y - eski.y) < 0.5 && Math.abs(yeni.w - eski.w) < 0.5;
+ if (ayni) return;
+ if (!kay || !yeni || !eski || !g.gorunur || azaltSorgu.matches) {
+ // İlk ölçüm, yeniden boyutlanma, ekran dışı, hareketi azalt: kayma yok.
+ hedef = yeni;
+ if (aktif && !basili) dur();
+ return;
+ }
+ seciliRenk = oncekiRenk;
+ // Mercek eski vurgunun yerinden (ya da o an neredeyse oradan) yola çıkar.
+ baslat();
+ hedef = yeni;
+ c.uyandir();
+ };
+ esitleRef.current = esitle;
+ esitle(false);
+
+ // Bas, sürükle, bırak (kit `onPointerDown/Move/Up`). İşaretçi yakalanmaz:
+ // dokunuş seçeneğin kendi tıklamasına gider.
+ let basX = 0;
+ let oynadi = false;
+ const yerelX = (e: PointerEvent) => e.clientX - kap.getBoundingClientRect().left;
+ const oyna = (e: PointerEvent) => {
+ const x = yerelX(e);
+ if (!oynadi && Math.abs(x - basX) < 4) return;
+ oynadi = true;
+ surukle = x;
+ c.uyandir();
+ };
+ const kaldir = (e: PointerEvent) => {
+ window.removeEventListener("pointermove", oyna);
+ window.removeEventListener("pointerup", kaldir);
+ window.removeEventListener("pointercancel", kaldir);
+ basili = false;
+ if (oynadi && surukle !== null && e.type === "pointerup") {
+ const yakin = enYakin(surukle, my.x);
+ const seciliMi = yakin?.oge.querySelector("[data-cam-vurgu]");
+ if (yakin && !seciliMi) {
+ // Seçimi seçeneğin kendisi yapar (Radix sekmesi mousedown'da, hap tıklamada).
+ yakin.oge.dispatchEvent(new MouseEvent("mousedown", { bubbles: true, cancelable: true, button: 0 }));
+ yakin.oge.click();
+ }
+ }
+ surukle = null;
+ c.uyandir();
+ };
+ const bas = (e: PointerEvent) => {
+ if (e.button !== 0 || azaltSorgu.matches || !hedef || !g.gorunur) return;
+ if (!(e.target instanceof Element) || !e.target.closest('[role="radio"], [role="tab"]')) return;
+ basili = true;
+ oynadi = false;
+ basX = yerelX(e);
+ baslat();
+ window.addEventListener("pointermove", oyna);
+ window.addEventListener("pointerup", kaldir);
+ window.addEventListener("pointercancel", kaldir);
+ c.uyandir();
+ };
+ kap.addEventListener("pointerdown", bas);
+ // Yatay sürükleme sayfayı kaydırmasın; dikey kaydırma serbest.
+ const oncekiDokunma = kap.style.touchAction;
+ kap.style.touchAction = "pan-y";
+
+ const io = new IntersectionObserver(([giris]) => {
+ g.gorunur = giris.isIntersecting;
+ });
+ io.observe(kap);
+ const ro = new ResizeObserver(() => {
+ if (!aktif) esitle(false);
+ });
+ ro.observe(kap);
+ c.ekle(g);
+
+ return () => {
+ c.cikar(g);
+ // Cam kapatılınca (cam-tercihi) tuvalde son kare ve gölgesi kalmasın.
+ ctx.clearRect(0, 0, tuval.width, tuval.height);
+ io.disconnect();
+ ro.disconnect();
+ kap.removeEventListener("pointerdown", bas);
+ window.removeEventListener("pointermove", oyna);
+ window.removeEventListener("pointerup", kaldir);
+ window.removeEventListener("pointercancel", kaldir);
+ kap.style.touchAction = oncekiDokunma;
+ esitleRef.current = null;
+ delete kap.dataset.camGeziyor;
+ delete kap.dataset.camYolda;
+ };
+ }, [acik]);
+
+ // Seçim değişti: mercek eski yerinden yenisine kayar.
+ useEffect(() => {
+ esitleRef.current?.(true);
+ }, [secili]);
+
+ return ;
}
+/** Rozet camındaki şeridin hızı: saniyede kaç birim ("Yeni" + kare) geçer. */
+const ROZET_HIZI = 0.4;
+/** Kartın üstüne gelince şeridin vardığı hız katı ve oraya yaklaşma hızı (1/sn). */
+const ROZET_HIZLI = 3.5;
+const ROZET_IVME = 1.6;
+/** CTA yüzeyindeki cam CTA'nın mavi boyasının yoğunluğu (rozetle aynı). */
+const CTA_BOYASI = 0.82;
+/** Rozet camının mavi boyasının yoğunluğu (0 = boyasız, 1 = düz mavi). */
+const ROZET_BOYASI = 0.82;
+
/**
- * "Yeni" rozetinin camı (DESIGN.md §4.49); kit `GlassBadge`'idir: rozetin kendi
- * rengiyle boyalı, yarı saydam bir damla, içinden yazı şeridi akar, cam yazıyı ve
- * arkasındaki kart köşesini büker. Sıvı cam tercihi kapalıyken `children` (rozetin
- * düz hâli) gösterilir.
+ * "Yeni" rozetinin camı (DESIGN.md §4.49): rozet mavi boyalı, yarı saydam bir
+ * sıvı cam damladır (yazı beyaz),
+ * içinden akan "Yeni ▪ Yeni ▪ …" şeridini (ayraç turuncu piksel kare) ve arkasındaki kart köşesini büker
+ * (kenarda içeri kırar, ortada hafif büyütür); arkadaki kart buzlu camın
+ * ardındaki gibi bulanık görünür, yazı net kalır. Şerit DOM'da değil camın alt katmanında çizilir:
+ * kırılan şey yazının kendisidir. Rozetin ilk çocuğudur; ilk kare çizilince
+ * rozete `data-cam` yazılır ve rozet düz mavi zeminini ve DOM şeridini bırakır.
+ * Arkadaki kart `[data-rozet-zemini]` ile işaretlenir (rozetin konum atasında).
+ * Yalnız ekrandayken çizilir; hareketi azalt'ta şerit durur, tek ortalı yazı
+ * kalır. WebGL2 yoksa rozet eski düz hâlindedir.
*/
-export function RozetCami({ metin, className, children }: { metin: string; className?: string; children: ReactNode }) {
+export function RozetCami({ metin }: { metin: string }) {
+ const tuvalRef = useRef(null);
const acik = useCamAcik();
- // Ayraç karesinin rengi tuvale çizilir: token'ın çözülmüş değeri gerekir.
- const kare = useMemo(
- () => (acik ? getComputedStyle(document.documentElement).getPropertyValue("--color-orange-500").trim() || undefined : undefined),
- [acik],
- );
- if (!acik) return children;
- return (
-
- {metin}
-
- );
+
+ useEffect(() => {
+ const tuval = tuvalRef.current;
+ const kap = tuval?.parentElement;
+ const ctx = tuval?.getContext("2d");
+ // Camsı görünüm kapalıysa (footer, `cam-tercihi.ts`) cam kurulmaz: sade hâl.
+ const c = acik && camAcikMi() ? calismaAl() : null;
+ if (!tuval || !kap || !ctx || !c) return;
+
+ const css = ([r, g2, b]: Rgb) => `rgb(${Math.round(r * 255)} ${Math.round(g2 * 255)} ${Math.round(b * 255)})`;
+ let en = 0;
+ let boy = 0;
+ let zemin: Rgb = [1, 1, 1];
+ let boya = "blue";
+ let kare = "orange";
+ let yaziTipi = "600 12px sans-serif";
+ /** Arkadaki kart: rozete göre yeri, köşesi ve renkleri. */
+ let kart: { x: number; y: number; w: number; h: number; r: number; zemin: string; kenar: string } | null = null;
+ let kayma = 0;
+ let duruyor = false;
+ /** Şeridin anlık hız katı; kartın üstündeyken kademeli olarak artar. */
+ let hizKati = 1;
+ let ustunde = false;
+
+ const olc = () => {
+ const k = kap.getBoundingClientRect();
+ en = kap.offsetWidth;
+ boy = kap.offsetHeight;
+ zemin = c.renkCoz(kap, zeminRengi(kap.parentElement));
+ boya = css(c.renkCoz(kap, "var(--primary)"));
+ kare = css(c.renkCoz(kap, "var(--color-orange-500)"));
+ const st = getComputedStyle(kap);
+ yaziTipi = `${st.fontWeight} ${st.fontSize} ${st.fontFamily}`;
+ const el = kap.offsetParent?.querySelector("[data-rozet-zemini]");
+ if (el) {
+ const r = el.getBoundingClientRect();
+ const es = getComputedStyle(el);
+ kart = {
+ x: r.left - k.left,
+ y: r.top - k.top,
+ w: r.width,
+ h: r.height,
+ r: parseFloat(es.borderTopRightRadius) || 0,
+ zemin: css(c.renkCoz(kap, es.backgroundColor)),
+ kenar: css(c.renkCoz(kap, es.borderTopColor)),
+ };
+ } else kart = null;
+ };
+
+ const g: Gorunum = {
+ tuval,
+ ctx,
+ kirli: true,
+ gorunur: false,
+ adim: (dt, azalt) => {
+ duruyor = azalt;
+ if (azalt || !g.gorunur) return false;
+ hizKati += ((ustunde ? ROZET_HIZLI : 1) - hizKati) * Math.min(1, dt * ROZET_IVME);
+ kayma += dt * ROZET_HIZI * hizKati;
+ return true;
+ },
+ mercek: (yenile) => {
+ if (yenile || !en) olc();
+ if (en < 2 || boy < 2) return null;
+ // Yan pay dar: rozet kartın sağından 8 px taşar, telefonda sayfanın
+ // 16 px'lik kenar boşluğunu aşmamalı.
+ const payX = 6;
+ const payUst = 8;
+ const payAlt = Math.round(boy * 0.9 + 6);
+ const kutu = kap.getBoundingClientRect();
+ return {
+ sol: -payX,
+ ust: -payUst,
+ en: en + 2 * payX,
+ boy: boy + payUst + payAlt,
+ birim: boy / SEKME_BIRIM,
+ mx: payX + en / 2,
+ my: payUst + boy / 2,
+ yx: en / 2,
+ yy: boy / 2,
+ kose: 999,
+ govdeX: 0,
+ egim: SEKME_BIRIM * 0.42,
+ golge: 0.1,
+ golgeYumusak: 30 * SEKME_OPTIK,
+ golgeKayma: 12 * SEKME_OPTIK,
+ guc: 1,
+ renk: zemin,
+ zemin,
+ kenarSeffaf: 0,
+ kirma: {
+ boya: (arka) => {
+ arka.translate(payX, payUst);
+ if (kart) {
+ // Arka bulanık görünür (buzlu cam): kartın zemini yumuşak kenarla
+ // dolar, kenarlığı keskin çizgi yerine üst üste genişleyen soluk
+ // bantlarla çizilir. Yazı bu katmanın üstünde net kalır.
+ // (`ctx.filter` Safari'de yok; bulanıklık elle kurulur.)
+ arka.beginPath();
+ arka.roundRect(kart.x + 0.5, kart.y + 0.5, kart.w - 1, kart.h - 1, kart.r);
+ arka.shadowColor = kart.zemin;
+ arka.shadowBlur = 5 * Math.min(window.devicePixelRatio || 1, 2);
+ arka.fillStyle = kart.zemin;
+ arka.fill();
+ arka.shadowBlur = 0;
+ arka.shadowColor = "transparent";
+ arka.strokeStyle = kart.kenar;
+ for (const [kalinlik, guc] of [[9, 0.14], [6, 0.2], [3, 0.3]] as const) {
+ arka.lineWidth = kalinlik;
+ arka.globalAlpha = guc;
+ arka.stroke();
+ }
+ arka.globalAlpha = 1;
+ }
+ // Cam mavi boyalıdır (beyaz yazı okunsun diye); arkası boyanın
+ // ardından hafifçe seçilir.
+ arka.globalAlpha = ROZET_BOYASI;
+ arka.fillStyle = boya;
+ arka.fillRect(-payX, -payUst, en + 2 * payX, boy + payUst + payAlt);
+ arka.globalAlpha = 1;
+ arka.font = yaziTipi;
+ arka.textBaseline = "middle";
+ arka.fillStyle = "white";
+ const orta = boy / 2 + 0.5;
+ if (duruyor) {
+ arka.textAlign = "center";
+ arka.fillText(metin, en / 2, orta);
+ return;
+ }
+ // Şerit: metin ve arasında küçük turuncu kare sola akar; ek yeri yok.
+ const yaziEni = arka.measureText(metin).width;
+ const birimEni = yaziEni + 12;
+ arka.textAlign = "left";
+ for (let x = -((kayma % 1) * birimEni) - birimEni; x < en + birimEni; x += birimEni) {
+ arka.fillStyle = "white";
+ arka.fillText(metin, x + 6, orta);
+ arka.fillStyle = kare;
+ arka.fillRect(x - 2, boy / 2 - 1.5, 4, 4);
+ }
+ },
+ kirilma: 22 * SEKME_OPTIK,
+ buyutme: 0.1,
+ dagilma: 0.12,
+ bulanikOrta: 0,
+ bulanikKenar: 2.2,
+ buz: 0,
+ },
+ imlecIsigi: false,
+ ekranX: kutu.left + en / 2,
+ ekranY: kutu.top + boy / 2,
+ };
+ },
+ cizildi: () => {
+ kap.dataset.cam = "";
+ },
+ birak: () => {
+ delete kap.dataset.cam;
+ },
+ };
+
+ const kirlet = () => {
+ g.kirli = true;
+ c.uyandir();
+ };
+ const io = new IntersectionObserver(([giris]) => {
+ g.gorunur = giris.isIntersecting;
+ kirlet();
+ });
+ io.observe(kap);
+ // Rozet ya da arkasındaki kart boy değiştirince yerler yeniden ölçülür.
+ const ro = new ResizeObserver(kirlet);
+ ro.observe(kap);
+ const kartKabi = kap.offsetParent;
+ if (kartKabi) ro.observe(kartKabi);
+ // Kartın üstüne gelince şerit kademeli hızlanır, çıkınca yavaşlar.
+ const gir = (e: Event) => {
+ if ((e as PointerEvent).pointerType === "mouse") ustunde = true;
+ };
+ const cik = () => {
+ ustunde = false;
+ };
+ kartKabi?.addEventListener("pointerenter", gir);
+ kartKabi?.addEventListener("pointerleave", cik);
+ c.ekle(g);
+
+ return () => {
+ c.cikar(g);
+ // Cam kapatılınca (cam-tercihi) tuvalde son kare ve gölgesi kalmasın.
+ ctx.clearRect(0, 0, tuval.width, tuval.height);
+ io.disconnect();
+ ro.disconnect();
+ kartKabi?.removeEventListener("pointerenter", gir);
+ kartKabi?.removeEventListener("pointerleave", cik);
+ delete kap.dataset.cam;
+ };
+ }, [metin, acik]);
+
+ return ;
}
diff --git a/src/components/sivi-kap.ts b/src/components/sivi-kap.ts
index d7e3ecb..88a4984 100644
--- a/src/components/sivi-kap.ts
+++ b/src/components/sivi-kap.ts
@@ -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-glass-ready:border-transparent! data-glass-ready:bg-transparent! data-glass-ready:shadow-none!";
+export const SIVI_KAP = "relative isolate data-cam:border-transparent! data-cam:bg-transparent! data-cam:shadow-none!";
diff --git a/src/components/ui/alt-sayfa.tsx b/src/components/ui/alt-sayfa.tsx
index 4f1f8a6..254a8d9 100644
--- a/src/components/ui/alt-sayfa.tsx
+++ b/src/components/ui/alt-sayfa.tsx
@@ -123,7 +123,7 @@ function AltSayfaKapat({ className, children, ...props }: ComponentProps
diff --git a/src/components/ui/bildirim.tsx b/src/components/ui/bildirim.tsx
index d83056c..053e462 100644
--- a/src/components/ui/bildirim.tsx
+++ b/src/components/ui/bildirim.tsx
@@ -606,7 +606,7 @@ function Bildirim({
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-glass-ready: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-cam:active:scale-100")}
>
diff --git a/src/components/ui/button.tsx b/src/components/ui/button.tsx
index a9a6bd0..9e2a255 100644
--- a/src/components/ui/button.tsx
+++ b/src/components/ui/button.tsx
@@ -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-glass-ready` gelir.
+ // `SiviCam` ilk kareyi çizince `data-cam` 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-glass-ready`) buton kendi zeminini ve kenarlığını bırakır.
+ // Cam kurulunca (`data-cam`) buton kendi zeminini ve kenarlığını bırakır.
className: cn(sivi && SIVI_KAP, buttonVariants({ variant, size, className })),
}
diff --git a/src/components/ui/dialog.tsx b/src/components/ui/dialog.tsx
index 298fe75..b31c6de 100644
--- a/src/components/ui/dialog.tsx
+++ b/src/components/ui/dialog.tsx
@@ -75,7 +75,7 @@ function DialogContent({
{showCloseButton && (
diff --git a/src/components/ui/sayfalama.tsx b/src/components/ui/sayfalama.tsx
index 6c53608..dff84f1 100644
--- a/src/components/ui/sayfalama.tsx
+++ b/src/components/ui/sayfalama.tsx
@@ -61,7 +61,7 @@ const NUMARA = cn(
const OK = cn(
HAP,
SIVI_KAP,
- "data-glass-ready:active:scale-100",
+ "data-cam: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",
);
diff --git a/src/components/ui/secim-haplari.tsx b/src/components/ui/secim-haplari.tsx
index 96cdc4f..4ceac2e 100644
--- a/src/components/ui/secim-haplari.tsx
+++ b/src/components/ui/secim-haplari.tsx
@@ -82,14 +82,14 @@ export function SecimHaplari({
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-glass-traveling`) seçili seçenek seçilmemiş gibi
+ // Mercek yoldayken (`data-cam-yolda`) seçili seçenek seçilmemiş gibi
// boyanır: şeffaf camın altında okunur.
kapsul
? secili
- ? "text-slate-50 [[data-glass-traveling]_&]:text-slate-600!"
+ ? "text-slate-50 [[data-cam-yolda]_&]:text-slate-600!"
: "text-slate-600 hover:text-orange-500"
: secili
- ? "border border-transparent text-white [[data-glass-traveling]_&]:border-slate-200! [[data-glass-traveling]_&]:bg-card! [[data-glass-traveling]_&]:text-slate-600!"
+ ? "border border-transparent text-white [[data-cam-yolda]_&]:border-slate-200! [[data-cam-yolda]_&]:bg-card! [[data-cam-yolda]_&]: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({
initial={false}
transition={azalt ? { duration: 0 } : YAY}
className={cn(
- "absolute inset-0 rounded-full [[data-glass-moving]_&]:opacity-0!",
+ "absolute inset-0 rounded-full [[data-cam-geziyor]_&]:opacity-0!",
kapsul ? "bg-slate-900" : "bg-primary",
)}
- data-glass-highlight=""
+ data-cam-vurgu=""
aria-hidden
/>
) : null}
diff --git a/src/components/yeni-rozeti.tsx b/src/components/yeni-rozeti.tsx
index e4aae6c..cd26ea5 100644
--- a/src/components/yeni-rozeti.tsx
+++ b/src/components/yeni-rozeti.tsx
@@ -7,38 +7,44 @@ 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.
*
- * 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.
+ * 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.
*
* 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.
+ * 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.
*/
export function YeniRozeti({ className }: { className?: string }) {
return (
-
+
+
+ Yeni yazı
- Yeni yazı
-
-
- {Array.from({ length: 4 }, (_, i) => (
-
- Yeni
-
-
- ))}
-
-
-
- Yeni
+
+ {Array.from({ length: 4 }, (_, i) => (
+
+ Yeni
+
+
+ ))}
-
+
+ Yeni
+
+
);
}
diff --git a/src/features/katalog/components/katalog-arama.tsx b/src/features/katalog/components/katalog-arama.tsx
index 3833cf2..7ad1eff 100644
--- a/src/features/katalog/components/katalog-arama.tsx
+++ b/src/features/katalog/components/katalog-arama.tsx
@@ -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-glass-ready: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-cam:active:scale-100")}
>
diff --git a/src/features/kullanici/components/giris-linki.tsx b/src/features/kullanici/components/giris-linki.tsx
index de7d5ce..4c699e0 100644
--- a/src/features/kullanici/components/giris-linki.tsx
+++ b/src/features/kullanici/components/giris-linki.tsx
@@ -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-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"
+ ? "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"
}
>
diff --git a/src/features/kullanici/components/user-nav.tsx b/src/features/kullanici/components/user-nav.tsx
index bc822bc..3b66428 100644
--- a/src/features/kullanici/components/user-nav.tsx
+++ b/src/features/kullanici/components/user-nav.tsx
@@ -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-glass-ready: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-cam: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
diff --git a/src/features/liste/components/liste-cekmecesi.tsx b/src/features/liste/components/liste-cekmecesi.tsx
index 2537903..efa478d 100644
--- a/src/features/liste/components/liste-cekmecesi.tsx
+++ b/src/features/liste/components/liste-cekmecesi.tsx
@@ -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-glass-ready: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-cam:active:scale-100")}
>
@@ -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-glass-ready: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-cam:active:scale-100")}
>
diff --git a/src/features/liste/components/program-ekle-butonu.tsx b/src/features/liste/components/program-ekle-butonu.tsx
index 8ff2aac..375e09d 100644
--- a/src/features/liste/components/program-ekle-butonu.tsx
+++ b/src/features/liste/components/program-ekle-butonu.tsx
@@ -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-glass-ready:active:scale-100",
+ "data-cam: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-glass-ready: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-cam:active:scale-100 disabled:cursor-default focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
SIVI_KAP,
SATIR_DUGME_BOYU,
listede
diff --git a/src/features/liste/components/program-tablosu.tsx b/src/features/liste/components/program-tablosu.tsx
index 8e754ec..9e5525c 100644
--- a/src/features/liste/components/program-tablosu.tsx
+++ b/src/features/liste/components/program-tablosu.tsx
@@ -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-glass-traveling]_&]: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-cam-yolda]_&]:data-active:text-slate-600!"
>
{aktif ? (
{d.etiket}
{sonuclar.toplam[d.key].toLocaleString("tr-TR")}
diff --git a/src/features/rapor/components/sohbet-client.tsx b/src/features/rapor/components/sohbet-client.tsx
index dc157e4..f4e31e2 100644
--- a/src/features/rapor/components/sohbet-client.tsx
+++ b/src/features/rapor/components/sohbet-client.tsx
@@ -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-glass-ready: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-cam: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
diff --git a/src/features/rehber/components/rehber-izgarasi.tsx b/src/features/rehber/components/rehber-izgarasi.tsx
index 7c0a0df..b5b47d8 100644
--- a/src/features/rehber/components/rehber-izgarasi.tsx
+++ b/src/features/rehber/components/rehber-izgarasi.tsx
@@ -77,6 +77,7 @@ export function RehberIzgarasi({ yazilar }: { yazilar: RehberKarti[] }) {
{/* Kapak yazı sayfasındaki kapakla aynı adı taşır: tıklayınca
diff --git a/src/lib/hareket.ts b/src/lib/hareket.ts
index 2921c08..785f49f 100644
--- a/src/lib/hareket.ts
+++ b/src/lib/hareket.ts
@@ -39,8 +39,26 @@ export const YAY = {
mercekBirakma: { type: "spring", visualDuration: 0.3, bounce: 0.3 },
} 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).
+/**
+ * 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;
/**
* Kaydırarak onayın (§4.41) iki yayı; `hiz` 0..100, bırakınca işi ne kadar
diff --git a/tsconfig.json b/tsconfig.json
index a852ff7..cf9c65d 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -1,6 +1,6 @@
{
"compilerOptions": {
- "target": "ES2018",
+ "target": "ES2017",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,