From 97bb8f364dd4f169f28be3c6ea209eb34b8531ac Mon Sep 17 00:00:00 2001 From: bilalgursen Date: Wed, 25 Nov 2026 01:48:58 +0300 Subject: [PATCH] =?UTF-8?q?feat(cam):=20s=C4=B1v=C4=B1=20cam=20Liquid=20Gl?= =?UTF-8?q?ass=20UI=202.0=20motoruna=20ta=C5=9F=C4=B1nd=C4=B1=20(=E2=86=92?= =?UTF-8?q?=202.13.0)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bilal'in kiti (bilalgursen/liquid-glass@9c65d01) src/components/liquid-glass/ altına olduğu gibi alındı: engine.ts, dom-snapshot.ts, glass-layer.tsx, glass-lens.tsx. sivi-cam.tsx artık yalnız sarmalayıcı: SiviCam kitin GlassLayer uyarlaması (ok damlası, baştaki ikonda sola ayrılma, CTA yüzeyinde canlı arka + --glass-tint mavi boya, cam tercihi), KayanCam kitin GlassLens'i, RozetCami kitin GlassBadge camı. Kitle gelen davranışlar: basılan yerde ışıklanma, basılı tutup çekme, yaklaşan cam butonların kaynaşması, şeffaf camın kenarında çevreyi yansıtma. İşaretler kitin adlarına geçti (data-glass-ready, data-glass-moving/traveling, data-glass-highlight); .kt-sayfa-blur data-glass-skip ile camda çizilmez. CAM_YAYI kaldırıldı (yaylar kitin SPRINGS'i). Kit klasörü lint ve tasarım denetiminde kendi biçiminde bırakılır; kitteki /s bayrağı için TypeScript hedefi ES2018. DESIGN.md §4.50 ve sürüm notu güncellendi. Co-Authored-By: Claude Opus 5.5 --- docs/tasarim/DESIGN.md | 44 +- eslint.config.mjs | 6 + package.json | 2 +- scripts/tasarim-denetim.ts | 6 +- src/app/globals.css | 9 + src/app/layout.tsx | 7 +- src/app/surum-notlari/page.tsx | 9 + src/components/liquid-glass/dom-snapshot.ts | 805 ++++++ src/components/liquid-glass/engine.ts | 2507 +++++++++++++++++ src/components/liquid-glass/glass-layer.tsx | 793 ++++++ src/components/liquid-glass/glass-lens.tsx | 475 ++++ src/components/mobil-menu.tsx | 4 +- src/components/sivi-cam.tsx | 2160 +++++--------- src/components/sivi-kap.ts | 2 +- src/components/ui/alt-sayfa.tsx | 2 +- src/components/ui/bildirim.tsx | 2 +- src/components/ui/button.tsx | 4 +- src/components/ui/dialog.tsx | 2 +- src/components/ui/sayfalama.tsx | 2 +- src/components/ui/secim-haplari.tsx | 10 +- src/components/yeni-rozeti.tsx | 8 +- .../katalog/components/katalog-arama.tsx | 2 +- .../kullanici/components/giris-linki.tsx | 4 +- .../kullanici/components/user-nav.tsx | 2 +- .../liste/components/liste-cekmecesi.tsx | 4 +- .../liste/components/program-ekle-butonu.tsx | 4 +- .../liste/components/program-tablosu.tsx | 10 +- .../rapor/components/sohbet-client.tsx | 2 +- src/lib/hareket.ts | 21 - tsconfig.json | 2 +- 30 files changed, 5323 insertions(+), 1587 deletions(-) create mode 100644 src/components/liquid-glass/dom-snapshot.ts create mode 100644 src/components/liquid-glass/engine.ts create mode 100644 src/components/liquid-glass/glass-layer.tsx create mode 100644 src/components/liquid-glass/glass-lens.tsx diff --git a/docs/tasarim/DESIGN.md b/docs/tasarim/DESIGN.md index 406f90a..fefcc69 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-cam:bg-transparent data-cam:hover:bg-transparent`. CTA düz turuncudur; yalnız **CTA yüzeylerinin içinde** `cam="seffaf"` ile mavi boyalı liquid + data-glass-ready:bg-transparent data-glass-ready:hover:bg-transparent`. CTA düz turuncudur; yalnız **CTA yüzeylerinin içinde** `cam="seffaf"` ile mavi boyalı liquid glass olur (12 Kas 2026, §4.50). `cam="cam"` turuncu boyalı varyasyondur, kullanılmıyor. Metin önce, ok sonda. Başta ikon yok. `Sparkles` yok. Kullanım yerinde yalnız yerleşim sınıfı eklenir (`w-full sm:w-auto`, `mt-6`); yükseklik, renk, geçiş yazılmaz. @@ -2076,7 +2076,7 @@ yok" kuralının üçüncü istisnası (başlık üstü eyebrow değil, kart kö "progressive blur" iki kez denendi (güçlü ve hafif), Bilal 12 Kas 2026'da ikisini de kaldırttı — geri önerilmez. - Cam ilk karesini çizene dek ve WebGL2 yoksa rozet düz hâlindedir: `bg-primary` dolu hap, beyaz - CSS şeridi (`kt-yeni-serit`, 5 sn, kenarlar maskeyle erir). `data-cam` gelince zemin ve DOM + CSS şeridi (`kt-yeni-serit`, 5 sn, kenarlar maskeyle erir). `data-glass-ready` gelince zemin ve DOM şeridi bırakılır. - Hareketi azalt: şerit durur, tek ortalı "Yeni" (camda da, düz hâlde de). Ekran okuyucuya `sr-only` "Yeni yazı". Cam yalnız ekrandayken çizilir. @@ -2108,6 +2108,26 @@ Bilal (12 Kas 2026): "CTA butonlarını liquid-glass projesinde yaptığım buto 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`, `ui/glass/runtime.ts`, `ui/glass/physics.ts`. §11.3'e göre çevrildi. +- **Kitin 2.0 sürümüne geçildi** (Bilal, 25 Kas 2026: "burdaki liquid glassları güncel liquid + glass ile güncelle"; site 2.13.0). Motor ve bakış artık kitin kendisidir: + `src/components/liquid-glass/` altında `engine.ts`, `dom-snapshot.ts`, `glass-layer.tsx`, + `glass-lens.tsx` (bilalgursen/liquid-glass@9c65d01) **olduğu gibi** durur, elle değiştirilmez; + kit güncellenince dosyalar yeniden kopyalanır (lint ve `pnpm tasarim:denetim` bu klasörü + kitin biçiminde bırakır). `sivi-cam.tsx` yalnız sarmalayıcıdır: `SiviCam` kitin `GlassLayer`'ının + uyarlaması (ok damlası kendiliğinden bulunur, üstüne gelince ya da `otoDamla`'da ayrılır, + baştaki ikonda sola ayrılır; CTA yüzeyinde yüzeyi canlı çizer ve `--glass-tint` ile maviye + boyanır, globals.css), `KayanCam` kitin `GlassLens`'i, `RozetCami` kitin `GlassBadge` camı. + Kitle gelen davranışlar: basılan yerde ışıklanma (`GLOW`, `LIGHT`), basılı tutup çekince + peşinden gelip jöle gibi dönme (`PULL`), yaklaşan iki cam butonun kaynaşması (`COHESION`), + şeffaf camın kenarında çevresini yansıtması (`MIRROR`; kenardaki sabit mavi çizgi kalktı). + Cam hazır olunca kaba `data-glass-ready` yazılır (`SIVI_KAP` buna bakar); mercek kaba + `data-glass-moving` / `data-glass-traveling`, seçili vurgu `data-glass-highlight` taşır. + Şeffaf camın kırılma, bulanıklık ve ton değerleri kitin varsayılanıdır (kırılma 44 → basınca + 37; CTA yüzeyinde boya %82, dışında ton %60); aşağıdaki maddelerde bunlardan farklı yazan + sayılar (ör. CTA bandında "10 → 32", "%8 büyütür", "%7 beyaz ton") eskidir. Sayfa + bulanıklığı katmanları (`.kt-sayfa-blur`) `data-glass-skip` ile camda çizilmez. 25 Kas + 2026'da 1024 px'te (`/rehber`, ana sayfa kapanışı, sıralama seçenekleri) ve 375 px'te + (ana sayfa, telefon menüsü, açık ve koyu tema) bakıldı; 375 px'te yatay taşma 0. - **Sıvı yalnız cam yüzeylerde** (Bilal, 12 Kas 2026: "gooey animasyonu sadece liquid glass'larda olsun, diğer geliştirmeleri sil"). Renkli ve düz butonlar — turuncu CTA, mavi birincil, ikincil, outline, ikonlu haplar — düzdür: ne cam zemin, ne şişme, ne ok damlası. @@ -2177,7 +2197,7 @@ liquid glass olsun". Kaynak Bilal'in açık kaynak kiti **Liquid Glass UI** (Bilal, 12 Kas 2026: "ikonlar yuvarlakları tam ortalamıyor"). Ölçüldü: satır düğmesinde ve hap damlasında ikon merkezi ile cam dairesinin merkezi arasındaki fark 0 px. Cam kurulunca eski `active:scale` kapanır - (`data-cam:active:scale-100`; büyümeyi cam yapar). WebGL2 yoksa düğme eski düz hâlindedir. + (`data-glass-ready:active:scale-100`; büyümeyi cam yapar). WebGL2 yoksa düğme eski düz hâlindedir. 12 Kas 2026'da 1280 ve 375 px'te, açık ve koyu temada bakıldı; 375 px'te yatay taşma 0. - **Sıvı cam kutusu — `CamSecici`, `src/components/cam-secici.tsx`, `src/lib/cam-tercihi.ts`** (Bilal, 12 Kas 2026: "sitenin en altına camsılığı açıp kapama seçeneği koy, ilham kaynağı deyip @@ -2199,7 +2219,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-cam:active:scale-100`. + tüm yuvarlak butonlar sıvı cam olmalı"): `SIVI_KAP` + ilk çocuk ``, `data-glass-ready:active:scale-100`. Kapsam: `DialogContent` ve `AltSayfaKapat` çarpıları, arama kapatma, telefon menüsü açma/kapama, üst çubuktaki "Yapay Zekâ Listem" bağlantısı (ikon yerine `PikselDugmeYuzu`, §4.43; `` 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ışı. @@ -2216,7 +2236,7 @@ Cam kurulunca eski `active:scale` kapanır - **Hareket (kitle aynı):** üstüne gelince cam her yana yüksekliğin %8'i kadar şişer; en ve boy ayrı yaylarla faz farkıyla oturur (damla gibi yalpalar), yazı 1,04'e büyür. Basınca cam ve yazı 1,08'e büyür, gölge derinleşir, bırakınca hafif sekerek döner. İmleç sayfadayken kenar ışığı - ona %40 döner. Yaylar `CAM_YAYI` (`src/lib/hareket.ts`); "sekmesiz" kuralının (§6) Bilal'in + ona %40 döner. Yaylar kitin `SPRINGS`'i (`src/components/liquid-glass/engine.ts`); "sekmesiz" kuralının (§6) Bilal'in istediği istisnasıdır. Ölçek butonun `scale` özelliğine yazılır (yazı camla birlikte büyür); geniş butonda büyüme yan başına 6 px ile sınırlıdır (telefonda tam genişlik butonda yatay taşma olmasın; 375 px'te ölçüldü, taşma 0). @@ -2231,21 +2251,21 @@ Cam kurulunca eski `active:scale` kapanır `ArrowRight` taşıyan cam yüzeyde (`cam="cam"` CTA, karttaki "Yazıyı oku") üstüne gelince gövdenin ucu geri çekilir, ok yüksekliği çapında bir daire olarak ayrılır, aradaki sıvı köprü incelip kopar (aralık yüksekliğin dörtte biri); imleç çıkınca ve basınca geri karışır. Biçim - gölgelendiricide yumuşak birleşimdir, SVG "goo" filtresi yok. Yaylar `CAM_YAYI.damla` / - `damlaDonus`. Yerleşim: `globals.css` kuralı ikonu `data-sivi` ucundaki daire bölgesinin + gölgelendiricide yumuşak birleşimdir, SVG "goo" filtresi yok. Yaylar `SPRINGS.dropletOut` / + `dropletIn`. Yerleşim: `globals.css` kuralı ikonu `data-sivi` ucundaki daire bölgesinin ortasına yerleştirir (`--ok-cap` = buton yüksekliği, `SiviCam` ölçer), yazı kalan gövdede ortalanır; yalnız fareli cihazda. - **Kayan sekme merceği — `KayanCam`** (Bilal, 12 Kas 2026: "tab geçişinde de geçerken liquid glass olsun", "geçerken şeffaf cam olacak, örnekteki gibi"; kit `SegmentedControl`). `SecimHaplari`'nin her kullanımında (§4.22) ve liste dilim sekmelerinde (Hayal · Dengeli · Güvenli, `program-tablosu.tsx`; Bilal: "burada liquid glass geçişi yok, ekle") açılır. Seçim değişince mercek eski vurgunun yerinden yenisine - yayla kayar (`CAM_YAYI.kayma`, hafif sekme). Başta düz vurgu rengindedir (buzlu); yola çıkınca + yayla kayar (`SPRINGS.slide`, hafif sekme). Başta düz vurgu rengindedir (buzlu); yola çıkınca en %12, boy %35 şişer ve **şeffaf cama döner**: altındaki seçenekleri (çip zemini, kenarlığı, etiket, ikon) kenarında büker, ortasında %12 büyütür, kenarda renkleri hafifçe ayrıştırır; kenar ışığı, kostik ve gölge alır. Hedefe yaklaşınca buzlanıp düz vurguya oturur. **Hareket kitin aynısıdır** (Bilal: "tıklayınca, basılı tutunca davranışı aynı olmalı"): basılı tutunca mercek olduğu yerde şişip açılır (seçim değişmez); 4 px'ten sonra sürükleyince - merkezi parmağı sıkı yayla izler (`CAM_YAYI.surukleme`, 40 rad/sn, sekmesiz), bırakınca en + merkezi parmağı sıkı yayla izler (`SPRINGS.drag`, 40 rad/sn, sekmesiz), bırakınca en yakın seçenek seçilir; dokununca seçim **bırakışta** olur ve merkez yeni seçeneğe yumuşak yayla gider (`kayma`, 14 rad/sn, sekme 0,25); hedefe seçenek eninin %6'sı kalana dek mercek açık kalır. Kenar ışığı imlece dönmez (kitte yalnız butonlarda döner). Radix sekmesi basar basmaz @@ -2258,13 +2278,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-cam-vurgu` + `[[data-cam-geziyor]_&]:opacity-0!` taşır (mercek ilk karesini çizince - gizlenir); seçili seçenek `[[data-cam-yolda]_&]:…!` sınıflarıyla yoldayken seçilmemiş gibi + `data-glass-highlight` + `[[data-glass-moving]_&]:opacity-0!` taşır (mercek ilk karesini çizince + gizlenir); seçili seçenek `[[data-glass-traveling]_&]:…!` sınıflarıyla yoldayken seçilmemiş gibi boyanır (şeffaf camın altında okunsun), hedefe yaklaşınca seçili rengine camın altında döner. Durağanken görünen düz vurgudur; WebGL2 yoksa ve hareketi azalt'ta eski `layoutId` kayması/yerinde belirme aynen çalışır. Tema seçici, satır seçimi (`karsilastirma-yorungesi`) ve içindekiler çizgisi cam değildir. -- **Sade karşılık:** ilk kare çizilince butona `data-cam` yazılır ve buton turuncu zeminini +- **Sade karşılık:** ilk kare çizilince butona `data-glass-ready` yazılır ve buton turuncu zeminini bırakır. O ana kadar, WebGL2 yoksa ve bağlam kaybolursa buton eski düz turuncu CTA'dır (`hover:bg-orange-600`, `active:scale-[0.97]`); iki zemin aynı anda görünmez. - **Ne zaman çizilir:** boy ya da tema değişince, ekrana girince, imleç oynayınca ve yaylar diff --git a/eslint.config.mjs b/eslint.config.mjs index e4751bf..72fd7a4 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -17,6 +17,12 @@ const eslintConfig = defineConfig([ // Türkçe TTS sanal ortamı (scripts/seslendir.py); içindeki torch JS dosyaları lint'e girmesin. ".venv-tts/**", ]), + // Liquid Glass UI kiti (DESIGN.md §4.50) olduğu gibi kopyalanır, elle değiştirilmez; + // kitin kendi biçimindeki iki kalıp burada hata sayılmaz. + { + files: ["src/components/liquid-glass/**"], + rules: { "react-hooks/refs": "off", "prefer-const": "off" }, + }, ]); export default eslintConfig; diff --git a/package.json b/package.json index 141bd76..cf8ab54 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "kolaytercih", - "version": "2.12.15", + "version": "2.13.0", "private": true, "engines": { "node": ">=22" diff --git a/scripts/tasarim-denetim.ts b/scripts/tasarim-denetim.ts index a669739..bcb58d1 100644 --- a/scripts/tasarim-denetim.ts +++ b/scripts/tasarim-denetim.ts @@ -4,7 +4,8 @@ * * Çıkış kodu: hata varsa 1, yoksa 0. Uyarılar çıkış kodunu etkilemez. * Kapsam: src/**\/*.tsx. Hariç: src/components/ui (shadcn tabanı) ve - * src/components/dev (yalnızca geliştirici paneli) — bazı kurallarda. + * src/components/dev (yalnızca geliştirici paneli) — bazı kurallarda; + * src/components/liquid-glass (kitten olduğu gibi kopyalanır, §4.50) — tümünde. */ import { readdirSync, readFileSync, statSync } from "node:fs"; import { join, relative } from "node:path"; @@ -34,6 +35,8 @@ type Kural = { const KOK = process.cwd(); const KAYNAK = join(KOK, "src"); const UI_VEYA_DEV = /src\/components\/(ui|dev)\//; +/** Liquid Glass UI kiti olduğu gibi kopyalanır, elle değiştirilmez (DESIGN.md §4.50). */ +const KIT = /src\/components\/liquid-glass\//; function tsxDosyalari(dizin: string): string[] { const sonuc: string[] = []; @@ -350,6 +353,7 @@ const KURALLAR: Kural[] = [ const bulgular: Bulgu[] = []; for (const yol of tsxDosyalari(KAYNAK)) { const gorece = relative(KOK, yol); + if (KIT.test(gorece)) continue; const icerik = readFileSync(yol, "utf8"); for (const k of KURALLAR) { if (!k.uiDahil && UI_VEYA_DEV.test(gorece)) continue; diff --git a/src/app/globals.css b/src/app/globals.css index 42f7e52..49447dc 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -1474,6 +1474,15 @@ html.lenis body { } } +/* CTA yüzeyindeki şeffaf sıvı cam mavi boyalıdır (DESIGN.md §4.50; `SiviCam` boyayı + buradan okur). Mavi bantta bir ton koyu: kendi rengindeki zeminden ayrılsın. */ +[data-cta-yuzey] { + --glass-tint: var(--primary); +} +[data-cta-yuzey][data-cta-ton="mavi"] { + --glass-tint: color-mix(in oklch, var(--primary), black 28%); +} + /* İkonlu buton (DESIGN.md §4.50; `Button` ya da `SIVI_KAP` taşıyan elle yazılmış hap): ikon, üstüne gelince gövdeden damla olarak ayrılan dairenin ortasında durur; yazı kalan gövdede ortalanır. `data-sivi` ikonun ucunu söyler ("son" / diff --git a/src/app/layout.tsx b/src/app/layout.tsx index 6d39cf9..f9e4a43 100644 --- a/src/app/layout.tsx +++ b/src/app/layout.tsx @@ -120,9 +120,10 @@ export default function RootLayout({ {/* Site geneli progressive blur — üst ve alt. Stil globals.css'te (.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. */} -
-
+ ile düşürülüp degrade fade korunuyor. Şeffaf sıvı cam bu katmanı + çizmez (`data-glass-skip`, DESIGN.md §4.50): içinden geçen yazı net kırılır. */} +
+
diff --git a/src/app/surum-notlari/page.tsx b/src/app/surum-notlari/page.tsx index 3bdf127..d01ca46 100644 --- a/src/app/surum-notlari/page.tsx +++ b/src/app/surum-notlari/page.tsx @@ -33,6 +33,15 @@ type Surum = { }; const SURUMLER: Surum[] = [ + { + surum: "2.13.0", + tarih: "25 Kasım 2026", + maddeler: [], + arayuz: [ + "Sıvı cam görünümü yenilendi (sayfanın en altındaki \"Sıvı cam\" kutusunu işaretleyince açılır). Cam butonlar artık bastığın yerden ışıklanıyor; basılı tutup parmağını kaydırınca buton peşinden biraz gelip bırakınca jöle gibi yerine dönüyor.", + "Yan yana duran iki cam buton birbirine yaklaşınca iki su damlası gibi kaynaşıyor. Şeffaf camın kenarı da çevresindeki renkleri hafifçe yansıtıyor.", + ], + }, { surum: "2.12.15", tarih: "25 Kasım 2026", diff --git a/src/components/liquid-glass/dom-snapshot.ts b/src/components/liquid-glass/dom-snapshot.ts new file mode 100644 index 0000000..b780224 --- /dev/null +++ b/src/components/liquid-glass/dom-snapshot.ts @@ -0,0 +1,805 @@ +// KolayTercih (DESIGN.md §4.50): Liquid Glass UI 2.0.0'dan (bilalgursen/liquid-glass@9c65d01, +// 24 Kas 2026) olduğu gibi alındı. Elle değiştirilmez; kit güncellenince dosya yeniden kopyalanır. + +// 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, +) { + const raw = node.textContent ?? '' + let text = raw.replace(/\s+/g, ' ').trim() + if (!text) return + const range = document.createRange() + range.selectNodeContents(node) + const lines = [...range.getClientRects()].filter((rect) => rect.width > 0.5) + if (!lines.length) 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 + const left = Math.max(0, Math.floor(box.x * scale + matrix.e)) + const top = Math.max(0, Math.floor(box.y * scale + 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) * scale + 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 +} + +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) + 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 = (element: Element, parentOpacity: number, isDeferred = false, style = getComputedStyle(element)) => { + 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 = [...element.childNodes].map((node) => { + const childStyle = node instanceof Element ? getComputedStyle(node) : null + const [layer, z] = childStyle ? layerOf(childStyle, inFlexOrGrid) : [1, 0] + return { node, childStyle, layer, z } + }) + // 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 } of children) { + if (childStyle) walk(node as Element, opacity, false, childStyle) + else if (node.nodeType === Node.TEXT_NODE) { + ctx.globalAlpha = opacity + drawText(ctx, node as Text, style, originX, originY, lang, intersects) + } + } + } + if (style.display === 'contents') { + drawChildren() + return + } + const rect = 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 (rect.width <= 0 || rect.height <= 0 || (rect.width <= 1 && rect.height <= 1) || !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 new file mode 100644 index 0000000..4d05be1 --- /dev/null +++ b/src/components/liquid-glass/engine.ts @@ -0,0 +1,2507 @@ +// KolayTercih (DESIGN.md §4.50): Liquid Glass UI 2.0.0'dan (bilalgursen/liquid-glass@9c65d01, +// 24 Kas 2026) olduğu gibi alındı. Elle değiştirilmez; kit güncellenince dosya yeniden kopyalanır. + +// 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. +// `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; +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, lod); + 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); +} + +void main() { + vec2 px = vec2(gl_FragCoord.x, uSize.y - gl_FragCoord.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) { + outColor = outsideCol * (1.0 - mask); + return; + } + } + if (mask <= 0.0) { + 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 < 1.0) { + vec3 frost = frostedRadial(local, dist, uFrostBlur * mix(1.0, uFrostEdge, pow(ratio, 1.3))); + 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 < 1.0) { + // 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. + vec3 frost = frosted(at + bend, frostBlur * mix(1.0, uFrostEdge, pow(bendEdge, 1.3))); + 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); + } + + // 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) + if (gl.getShaderParameter(s, gl.COMPILE_STATUS)) return s + console.warn('[liquid-glass] shader failed to compile', gl.getShaderInfoLog(s)) + return null + } + 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) + 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 attr = gl.getAttribLocation(program, 'a') + gl.enableVertexAttribArray(attr) + gl.vertexAttribPointer(attr, 2, gl.FLOAT, false, 0, 0) + + // Two 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 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)) + 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) + if (mipmapped) gl.generateMipmap(gl.TEXTURE_2D) + return tex + } + const back = layer() + const front = layer() + if (!back.ctx || !front.ctx) return null + type Painted = { back: WebGLTexture | null; front: WebGLTexture | null; w: number; h: 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 = { tex: WebGLTexture | null; 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 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) + 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. + const sent: number[] = [] + const set = (name: string, a: number, b?: number, c?: number, d?: number) => { + const at = u(name) + if (b === undefined) gl.uniform1f(at, a) + else if (c === undefined) gl.uniform2f(at, a, b) + else if (d === undefined) gl.uniform3f(at, a, b, c) + else gl.uniform4f(at, a, b, c, d) + sent.push(a, b ?? 0, c ?? 0, d ?? 0) + } + /** 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 + } + // 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) + + const unit = m.unit + const r = m.refraction + /** The layers are the ones this view was last drawn with. */ + let fresh = true + if (r) { + let p = painted.get(v) + if (!p) painted.set(v, (p = { back: texture(true), front: texture(false), w: 0, h: 0, at: 0 })) + const now = performance.now() + const sized = p.w === devW && p.h === devH + // A painter that takes only `back` has no front layer: none is cleared or uploaded. + const fronted = r.paint.length > 1 + fresh = !repaint && sized && now - p.at < REPAINT_EVERY + gl.activeTexture(gl.TEXTURE0) + gl.bindTexture(gl.TEXTURE_2D, p.back) + if (!fresh) { + for (const l of fronted ? [back, front] : [back]) { + if (l.canvas.width !== devW || l.canvas.height !== devH) { + l.canvas.width = devW + l.canvas.height = devH + } + l.ctx!.setTransform(1, 0, 0, 1, 0, 0) + l.ctx!.clearRect(0, 0, devW, devH) + l.ctx!.setTransform(dpr, 0, 0, dpr, 0, 0) + } + // A painter that says nothing changed keeps the textures it already has. + fresh = r.paint(back.ctx!, front.ctx!) === false && sized + } + if (!fresh) { + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, back.canvas) + gl.generateMipmap(gl.TEXTURE_2D) + } + gl.activeTexture(gl.TEXTURE1) + gl.bindTexture(gl.TEXTURE_2D, fronted ? p.front : blank.front) + if (!fresh) { + if (fronted) gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, front.canvas) + p.w = devW + p.h = devH + p.at = now + } + } else { + gl.activeTexture(gl.TEXTURE0) + gl.bindTexture(gl.TEXTURE_2D, blank.back) + gl.activeTexture(gl.TEXTURE1) + gl.bindTexture(gl.TEXTURE_2D, blank.front) + } + sent.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 + } + gl.activeTexture(gl.TEXTURE2) + if (f) { + let a = mirrored.get(v) + if (!a) mirrored.set(v, (a = { tex: texture(true), 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() + gl.bindTexture(gl.TEXTURE_2D, a.tex) + 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) + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, around.canvas) + gl.generateMipmap(gl.TEXTURE_2D) + 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 { + gl.bindTexture(gl.TEXTURE_2D, blank.back) + 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('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() + 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.tex) + } + const p = painted.get(v) + if (!p) return + painted.delete(v) + gl.deleteTexture(p.back) + gl.deleteTexture(p.front) + }, + 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-layer.tsx b/src/components/liquid-glass/glass-layer.tsx new file mode 100644 index 0000000..43b7c77 --- /dev/null +++ b/src/components/liquid-glass/glass-layer.tsx @@ -0,0 +1,793 @@ +'use client' + +// KolayTercih (DESIGN.md §4.50): Liquid Glass UI 2.0.0'dan (bilalgursen/liquid-glass@9c65d01, +// 24 Kas 2026) olduğu gibi alındı. Elle değiştirilmez; kit güncellenince dosya yeniden kopyalanır. + +// 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} +@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) + const padBottom = 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 new file mode 100644 index 0000000..6bb6f77 --- /dev/null +++ b/src/components/liquid-glass/glass-lens.tsx @@ -0,0 +1,475 @@ +'use client' + +// KolayTercih (DESIGN.md §4.50): Liquid Glass UI 2.0.0'dan (bilalgursen/liquid-glass@9c65d01, +// 24 Kas 2026) olduğu gibi alındı. Elle değiştirilmez; kit güncellenince dosya yeniden kopyalanır. + +// 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 => ( +// +// ))} +//
+// +// 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 6ca86e2..d1b9946 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-cam:active:scale-100 motion-reduce:transition-none sm:size-12")} + className={cn(SIVI_KAP, "kt-dokunma relative flex size-9 shrink-0 cursor-pointer items-center justify-center rounded-full border border-slate-200 bg-card text-slate-900 outline-none transition-[background-color,transform] duration-150 hover:bg-slate-100 focus-visible:ring-3 focus-visible:ring-ring/50 active:scale-[0.96] data-glass-ready:active:scale-100 motion-reduce:transition-none sm:size-12")} > @@ -210,7 +210,7 @@ export function MobilMenu({