@ikeofficial/liquid-glass-js 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,16 +1,26 @@
1
1
  # Liquid Glass JS
2
2
 
3
- A dependency-free glass material for ordinary HTML elements. It can bend the element’s own text, CSS and images, sample an image, canvas or video behind it, or refract the live page backdrop. Angular, React and Vue bind the same JavaScript core to their lifecycle.
3
+ A dependency-free glass material for ordinary HTML elements. It can refract the native page backdrop or the contents of a declared scroll pane. Angular, React and Vue bind the same JavaScript core to their lifecycle.
4
4
 
5
5
  ## Playground
6
6
 
7
+ Try the [interactive demo on GitHub Pages](https://bigimattia.github.io/liquidglass-js/).
8
+
9
+ ![Automatic mode using viewport SVG to bend a grid in the live scroll pane](docs/images/playground.png)
10
+
11
+ To run the playground locally:
12
+
7
13
  ```sh
8
14
  mise trust
9
15
  mise install
10
16
  mise run dev
11
17
  ```
12
18
 
13
- Open [the local playground](http://127.0.0.1:4173/demo/). Drag the lens or focus it and use the arrow keys. Compare the photo, grid and typography scenes and change the optical settings. Select Button, Switch, Slider, Segmented, or Media in the native-controls showcase to try the control and copy Tailwind HTML, JavaScript, Angular, Vue, or React source. The usage panel includes examples for all four entry points.
19
+ Open [the local playground](http://127.0.0.1:4173/demo/) to refract the contents of a live scroll pane. The renderer starts at **Automatic**. Switch between photo, grid, and typography artwork inside the pane and scroll it beneath the pinned glass. **Simple** shows one refraction slider. **Advanced** adds radius, bevel, curvature, chroma, blur, and tint opacity.
20
+
21
+ In **Usage**, choose a renderer and a language to copy the corresponding layout and configuration. **Automatic** and **Viewport SVG** examples pass a `viewportSource`. Angular uses a template reference to the scroll pane.
22
+
23
+ The native-controls showcase has its own renderer picker. Select Button, Switch, Slider, Segmented, or Media and copy the Tailwind markup or the matching JavaScript, Angular, Vue, or React configuration. The Media example has no viewport source, so forcing **Viewport SVG** falls back to frost.
14
24
 
15
25
  ## Install
16
26
 
@@ -37,7 +47,7 @@ import { liquidGlass } from "@ikeofficial/liquid-glass-js";
37
47
  import "@ikeofficial/liquid-glass-js/style.css";
38
48
 
39
49
  const item = document.querySelector("#item");
40
- const glass = liquidGlass(item, { mode: "content", radius: 30, refraction: 18 });
50
+ const glass = liquidGlass(item, { mode: "auto", viewportSource: "#feed", radius: 30 });
41
51
 
42
52
  glass.update({ chroma: 0.2 });
43
53
  glass.destroy();
@@ -57,12 +67,28 @@ import { LiquidGlassDirective } from "@ikeofficial/liquid-glass-js/angular";
57
67
 
58
68
  @Component({
59
69
  imports: [LiquidGlassDirective],
60
- template: '<button [liquidGlass]="{ mode: \'content\', radius: 22 }">Continue</button>',
70
+ template: `
71
+ <div class="glass-shell">
72
+ <main #feed class="glass-source">Scrollable content</main>
73
+ <button class="glass-bar"
74
+ [liquidGlass]="{ mode: 'viewport', viewportSource: feed, radius: 24 }">
75
+ Continue
76
+ </button>
77
+ </div>
78
+ `,
79
+ styles: `
80
+ .glass-shell { position: relative; isolation: isolate; }
81
+ .glass-source { height: 24rem; overflow: auto; }
82
+ .glass-bar {
83
+ position: absolute; inset: 1rem 1rem auto; min-height: 3rem;
84
+ border: 0; background: transparent; color: inherit;
85
+ }
86
+ `,
61
87
  })
62
88
  export class Action {}
63
89
  ```
64
90
 
65
- A bare `liquidGlass` attribute uses the defaults.
91
+ Use `mode: 'auto'` with the same source to prefer native backdrop refraction. A selector such as `viewportSource: '#feed'` also works.
66
92
 
67
93
  ## React
68
94
 
@@ -71,7 +97,7 @@ import { useLiquidGlass } from "@ikeofficial/liquid-glass-js/react";
71
97
  import "@ikeofficial/liquid-glass-js/style.css";
72
98
 
73
99
  export function Action() {
74
- const ref = useLiquidGlass({ mode: "content", radius: 22 });
100
+ const ref = useLiquidGlass({ mode: "auto", radius: 22 });
75
101
  return <button ref={ref}>Continue</button>;
76
102
  }
77
103
  ```
@@ -87,7 +113,7 @@ import "@ikeofficial/liquid-glass-js/style.css";
87
113
  </script>
88
114
 
89
115
  <template>
90
- <button v-liquid-glass="{ mode: 'content', radius: 22 }">Continue</button>
116
+ <button v-liquid-glass="{ mode: 'auto', radius: 22 }">Continue</button>
91
117
  </template>
92
118
  ```
93
119
 
@@ -95,30 +121,30 @@ The directive can also be registered globally with `app.directive("liquid-glass"
95
121
 
96
122
  ## Rendering modes
97
123
 
98
- | Options | What bends | Browser behavior |
99
- | --- | --- | --- |
100
- | `{ mode: "content" }` | The host’s rendered pixels, including its CSS background and descendants | SVG element filter in Chromium, Firefox and WebKit |
101
- | Default, or `{ mode: "auto" }` | Live page pixels when supported, otherwise the supplied backdrop | SVG refraction in Chromium, sampled media when supplied, then CSS frost |
102
- | `{ mode: "backdrop" }` | Arbitrary page pixels behind the host | SVG refraction in Chromium. CSS frost in other engines. A supplied backdrop retains its sample-first behavior. |
103
- | `{ mode: "sampled", backdrop: media }` | A supplied `<img>`, `<canvas>`, or `<video>` behind the host | Shared WebGL renderer where available, with Canvas 2D fallback |
104
- | `{ mode: "frost" }` | No displacement | CSS tint, blur and highlights where supported |
124
+ | Mode | Behavior |
125
+ | --- | --- |
126
+ | `auto` (default when `mode` is omitted) | Native backdrop refraction, then viewport SVG if a usable source is configured, then frosted glass |
127
+ | `viewport` | SVG refraction of the declared source. Uses frost when the source or filter is unavailable |
128
+ | `backdrop` | Native backdrop refraction where supported. Uses frost otherwise |
129
+ | `frost` | CSS blur, tint, and highlights |
130
+ | `off` | Disables glass and restores author styling |
105
131
 
106
- Use an ordinary HTML host with available `::before` and `::after` pseudo-elements. For content mode, put the artwork inside the host or use a CSS background. The filter refracts pixels only inside the lens silhouette. Use a decorative presentation layer for labels that must stay sharp, and keep the filtered host compact on mobile. The playground clips the aligned scene copy at the parent after refraction, so the glass outline stays stable as the optical settings change.
132
+ `viewportSource` accepts a same-document HTML element or a selector resolved in the lens’s document or shadow root. Give the source a bounded, axis-aligned viewport and place the lens in an overlapping sibling layer. The source must be outside the lens subtree and the lens must be outside the source subtree. The source’s own scrolling moves the scene under the lens while the filter stays in place. Call `glass.refresh()` after changing their relative position or replacing a selector target without an options update.
107
133
 
108
- A sampled media element must sit visually behind the lens in the same document, axis-aligned, without padding or borders. Images and videos support `object-fit: fill` or centered `cover` or `contain`. Use a same-origin or CORS-enabled source. The library resamples on resize, scroll, and media load. Video uses `requestVideoFrameCallback()` when available. Call `glass.refresh()` after moving the lens programmatically or redrawing a canvas.
134
+ Viewport SVG applies a CSS filter to the source, which creates a stacking context and can change positioning for fixed descendants. Keep fixed overlays outside that source. The source may contain ordinary text, images, and interactive HTML. Native video compositing varies by browser. Use an ordinary lens host with available `::before` and `::after` pseudo-elements.
109
135
 
110
- Automatic mode requires an explicit `backdrop` element for the sampled fallback. Use `mode: "sampled"` when the video or image should drive refraction on every browser. For the native-control snippets, load Tailwind CSS v4 and the shared glass stylesheet. The Media example also needs a same-origin video and poster, or a video served with CORS enabled and loaded with `crossorigin="anonymous"`.
136
+ The SVG renderers use an internally generated PNG data URL and fall back to frost if it cannot load. Reduced motion disables pointer tracking. Reduced transparency and forced colors use a solid treatment. The `liquid-glass` class with the shared stylesheet gives you a CSS-only treatment.
111
137
 
112
- The SVG modes use an internally generated PNG data URL. Where CSP disallows `data:` images, use a sampled backdrop or frost. Reduced motion disables pointer tracking. Reduced transparency and forced colors use a solid treatment. A CSS-only treatment is also available by applying the `liquid-glass` class with the shared stylesheet.
138
+ The `content` and `sampled` modes and the media `backdrop` option have been removed. For local artwork, position it in an HTML source layer behind the lens and use `viewportSource`. The native-control examples use Tailwind CSS v4 and the shared glass stylesheet.
113
139
 
114
140
  ## Options
115
141
 
116
142
  | Option | Default | Effect |
117
143
  | --- | --- | --- |
118
- | `mode` | `"auto"` | Auto, content, backdrop, sampled, or frost |
119
- | `backdrop` | `null` | Optional image, canvas or video source for auto, backdrop, and sampled modes |
144
+ | `mode` | `"auto"` | Auto, viewport, backdrop, frost, or off |
145
+ | `viewportSource` | `null` | HTML element or selector for the scroll pane or scene in auto and viewport modes |
120
146
  | `radius` | 24 | Corner radius in CSS pixels. Set size with your CSS |
121
- | `refraction` | 18 | Requested edge displacement in CSS pixels, bounded by the lens size. Zero disables distortion |
147
+ | `refraction` | 18 | Requested edge displacement in CSS pixels. Zero disables distortion |
122
148
  | `bevel` | 24 | Width of the refracted edge in CSS pixels |
123
149
  | `curvature` | 2 | Shape of the optical bevel, 0.25–8 |
124
150
  | `chroma` | 0 | Color-channel spread, 0–1 |
@@ -1 +1 @@
1
- :where(.liquid-glass){--liquid-glass-lens: ;--liquid-glass-content-filter: none;--liquid-glass-overlay-filter: var(--liquid-glass-lens) blur(var(--liquid-glass-blur, 2px)) saturate(var(--liquid-glass-saturation, 1.35));--liquid-glass-light-x: 25%;--liquid-glass-light-y: 0%;position:relative;z-index:0;border-radius:var(--liquid-glass-radius, 24px);filter:var(--liquid-glass-content-filter)}:where(.liquid-glass):before,:where(.liquid-glass):after{content:"";position:absolute;inset:0;border-radius:inherit;pointer-events:none}:where(.liquid-glass):before{z-index:-1;background:radial-gradient(ellipse at var(--liquid-glass-light-x) var(--liquid-glass-light-y),rgb(255 255 255 / var(--liquid-glass-glow, .23)),transparent 72%),rgb(var(--liquid-glass-tint-rgb, 255 255 255) / var(--liquid-glass-tint, .14));-webkit-backdrop-filter:var(--liquid-glass-overlay-filter);backdrop-filter:var(--liquid-glass-overlay-filter)}:where(.liquid-glass):after{padding:1px;opacity:calc(var(--liquid-glass-edge, .85) * var(--liquid-glass-css-rim, 1));background:radial-gradient(ellipse at var(--liquid-glass-light-x) var(--liquid-glass-light-y),rgb(255 255 255 / .95),transparent 64%),linear-gradient(var(--liquid-glass-angle, 145deg),rgb(255 255 255 / .55),rgb(255 255 255 / .11) 50%,rgb(255 255 255 / .42));mask:linear-gradient(#000 0 0) content-box,linear-gradient(#000 0 0);mask-composite:exclude}:where(.liquid-glass:active):before{box-shadow:inset 0 0 18px #ffffff2b}:where(.liquid-glass>.liquid-glass-backdrop){position:absolute;inset:0;width:100%;height:100%;z-index:-2;border-radius:inherit;pointer-events:none}@media(prefers-reduced-transparency:reduce),(forced-colors:active){:where(.liquid-glass){filter:none}:where(.liquid-glass):before{background:var(--liquid-glass-solid, Canvas);-webkit-backdrop-filter:none;backdrop-filter:none}:where(.liquid-glass):after{background:currentColor}:where(.liquid-glass>.liquid-glass-backdrop){visibility:hidden}}
1
+ :where(.liquid-glass){--liquid-glass-lens: ;--liquid-glass-overlay-filter: var(--liquid-glass-lens) blur(var(--liquid-glass-blur, 2px)) saturate(var(--liquid-glass-saturation, 1.35));--liquid-glass-light-x: 25%;--liquid-glass-light-y: 0%;position:relative;z-index:0;border-radius:var(--liquid-glass-radius, 24px)}:where(.liquid-glass):before,:where(.liquid-glass):after{content:"";position:absolute;inset:0;border-radius:inherit;pointer-events:none}:where(.liquid-glass):before{z-index:-1;background:radial-gradient(ellipse at var(--liquid-glass-light-x) var(--liquid-glass-light-y),rgb(255 255 255 / var(--liquid-glass-glow, .23)),transparent 72%),rgb(var(--liquid-glass-tint-rgb, 255 255 255) / var(--liquid-glass-tint, .14));-webkit-backdrop-filter:var(--liquid-glass-overlay-filter);backdrop-filter:var(--liquid-glass-overlay-filter)}:where(.liquid-glass):after{padding:1px;opacity:var(--liquid-glass-edge, .85);background:radial-gradient(ellipse at var(--liquid-glass-light-x) var(--liquid-glass-light-y),rgb(255 255 255 / .95),transparent 64%),linear-gradient(var(--liquid-glass-angle, 145deg),rgb(255 255 255 / .55),rgb(255 255 255 / .11) 50%,rgb(255 255 255 / .42));mask:linear-gradient(#000 0 0) content-box,linear-gradient(#000 0 0);mask-composite:exclude}:where(.liquid-glass:active):before{box-shadow:inset 0 0 18px #ffffff2b}@media(prefers-reduced-transparency:reduce),(forced-colors:active){:where(.liquid-glass):before{background:var(--liquid-glass-solid, Canvas);-webkit-backdrop-filter:none;backdrop-filter:none}:where(.liquid-glass):after{background:currentColor}}
@@ -1,11 +1,11 @@
1
- export type LiquidGlassMode = "auto" | "content" | "backdrop" | "sampled" | "frost";
2
- export type LiquidGlassRenderer = "content" | "backdrop" | "sampled" | "frost";
1
+ export type LiquidGlassMode = "auto" | "viewport" | "backdrop" | "frost" | "off";
2
+ export type LiquidGlassRenderer = "viewport" | "backdrop" | "frost" | "off";
3
3
 
4
4
  export interface LiquidGlassOptions {
5
- /** Auto (default) prefers live backdrop refraction, then a supplied backdrop, then frost. */
5
+ /** Auto (default) tries native backdrop, viewport SVG, then frost. */
6
6
  mode?: LiquidGlassMode;
7
- /** Optional image, canvas, or video displayed behind a lens in auto, sampled, or backdrop mode. */
8
- backdrop?: HTMLImageElement | HTMLCanvasElement | HTMLVideoElement | null;
7
+ /** Viewport SVG source in auto or viewport mode. A selector resolves in the lens’s document or shadow root. */
8
+ viewportSource?: string | HTMLElement | null;
9
9
  /** Uniform corner radius in CSS pixels. Defaults to 24. */
10
10
  radius?: number;
11
11
  /** Blur in CSS pixels. Defaults to 2. */
@@ -37,7 +37,7 @@ export interface LiquidGlassController {
37
37
  readonly renderer: LiquidGlassRenderer;
38
38
  /** Merge changes, or reset omitted options to their defaults with replace. */
39
39
  update(options: LiquidGlassOptions, behavior?: { replace?: boolean }): void;
40
- /** Resample an explicit backdrop after changing position or drawing new canvas content. */
40
+ /** Recheck the renderer and source geometry after changing their relative position. */
41
41
  refresh(): void;
42
42
  destroy(): void;
43
43
  }
@@ -1 +1 @@
1
- import{lensGeometry as te}from"./optics.js";import{resolveOptions as K}from"./options.js";import{makeBackdropLens as ne}from"./renderers/sampled.js";import{browserEngine as re,makeSvgLens as ie}from"./renderers/svg.js";const H=new WeakMap,R="liquid-glass";function le(t,z={}){const O=t?.ownerDocument,n=O?.defaultView;if(!n||!(t instanceof n.HTMLElement))throw new TypeError("liquidGlass requires an HTML element");const C=H.get(t);if(C)return C.update(z),C;let r=K(n,z);const T=re(n),Q=T==="blink"&&n.CSS?.supports("backdrop-filter",'url("#glass")'),S=n.matchMedia("(prefers-reduced-motion: reduce)"),w=n.matchMedia("(prefers-reduced-transparency: reduce), (forced-colors: active)"),V=new Map,U=t.classList.contains(R),q=new n.ResizeObserver(a);let M,P,l,x,c,A,v=null,p=null,g,m="frost",h=!1;function s(e,i){const o="--liquid-glass-"+e;t.style.getPropertyValue(o)!==String(i)&&(V.has(o)||V.set(o,[t.style.getPropertyValue(o),t.style.getPropertyPriority(o)]),t.style.setProperty(o,i))}function a(){!h&&v===null&&(v=n.requestAnimationFrame(Z))}function f(e,i=""){s("overlay-filter",e==="content"?"none":""),s("css-rim",e==="content"||e==="sampled"?0:""),s("content-filter",e==="content"?i:""),s("lens",e==="backdrop"?i:""),m!==e&&(m=e,n.queueMicrotask(()=>{!h&&m===e&&t.dispatchEvent(new n.CustomEvent("liquidglass:rendererchange",{detail:{renderer:e}}))}))}function y(){M?.dispose(),M=void 0,P=void 0}function Z(){v=null;const{mode:e,refraction:i,radius:o,bevel:d,curvature:u,lightAngle:$}=r,E=e==="content",j=Q&&(e==="auto"||e==="backdrop"),D=j&&e==="auto",b=E?t.offsetWidth:t.clientWidth,k=E?t.offsetHeight:t.clientHeight;if(w.matches||e==="frost"||!i||!t.isConnected||!b||!k){f("frost"),y(),l?.canvas.remove();return}const X=E?Math.min(n.devicePixelRatio||1,2):1,Y=[b,k,Math.min(o,b/2,k/2),d,u,$,X].join("/");Y!==x?.key&&(x={...te(b,k,r,X),width:b,height:k,key:Y});function I(){return c?(l??=ne(O),l.canvas.parentNode||t.prepend(l.canvas),l.render(c,x,r)?(f("sampled"),!0):(l.canvas.remove(),!1)):(l?.canvas.remove(),!1)}if(!D&&I()){y();return}if(!E&&!j){f("frost"),y();return}const F=E?"content":"backdrop";P!==F&&(y(),M=ie(t,T,F),P=F,l?.canvas.remove(),f("frost"));const ee=r;M.render(x,r,J=>{r===ee&&(J?(l?.canvas.remove(),f(F,J)):(!D||!I())&&f("frost"))})}function L(){g=void 0,s("light-x",""),s("light-y","")}function B(e){!r.interactive||S.matches||e.pointerType==="touch"||(g={x:e.clientX,y:e.clientY},p===null&&(p=n.requestAnimationFrame(()=>{if(p=null,!g)return;const{width:i,height:o,left:d,top:u}=t.getBoundingClientRect();!i||!o||(s("light-x",(g.x-d)/i*100+"%"),s("light-y",(g.y-u)/o*100+"%"))})))}function G(e){c!==e&&(c&&(q.unobserve(c),c.removeEventListener("load",a),A?.(),A=void 0),c=e,c?(q.observe(c),c.addEventListener("load",a),c.localName==="video"&&(A=_(c)),n.addEventListener("scroll",a,!0),n.addEventListener("resize",a)):(n.removeEventListener("scroll",a,!0),n.removeEventListener("resize",a)))}function _(e){const i=["loadeddata","seeked","resize"];for(const u of i)e.addEventListener(u,a);function o(){w.matches||a(),d=e.requestVideoFrameCallback(o)}let d=e.requestVideoFrameCallback?.(o);return()=>{d!==void 0&&e.cancelVideoFrameCallback(d);for(const u of i)e.removeEventListener(u,a)}}function W(){t.classList.add(R),s("radius",r.radius+"px"),s("blur",r.blur+"px"),s("saturation",r.saturation),s("tint",r.tint),s("glow",r.glow),s("edge",r.edgeHighlight),s("angle",r.lightAngle+"deg"),r.interactive||L(),G(r.refraction&&["auto","backdrop","sampled"].includes(r.mode)?r.backdrop:null),a()}const N={get renderer(){return m},update(e,{replace:i=!1}={}){h||(r=K(n,e,i?void 0:r),W())},refresh:a,destroy(){if(!h){h=!0,v!==null&&n.cancelAnimationFrame(v),p!==null&&n.cancelAnimationFrame(p),y(),l?.canvas.remove(),G(null),q.disconnect(),t.removeEventListener("pointermove",B),t.removeEventListener("pointerleave",L),S.removeEventListener("change",L),w.removeEventListener("change",a);for(const[e,[i,o]]of V)t.style.setProperty(e,i,o);U||t.classList.remove(R),H.delete(t),m="frost"}}};return H.set(t,N),t.addEventListener("pointermove",B,{passive:!0}),t.addEventListener("pointerleave",L),S.addEventListener("change",L),w.addEventListener("change",a),q.observe(t),W(),N}export{le as liquidGlass};
1
+ import{lensGeometry as Y}from"./optics.js";import{resolveOptions as N}from"./options.js";import{browserEngine as j,makeSvgLens as I}from"./renderers/svg.js";import{makeViewportLens as J}from"./renderers/viewport.js";const C=new WeakMap,y="liquid-glass";function $(t,F={}){const i=t?.ownerDocument?.defaultView;if(!i||!(t instanceof i.HTMLElement))throw new TypeError("liquidGlass requires an HTML element");const k=C.get(t);if(k)return k.update(F),k;let r=N(i,F);const P=j(i),B=P==="blink"&&i.CSS?.supports("backdrop-filter",'url("#glass")'),q=i.matchMedia("(prefers-reduced-motion: reduce)"),M=i.matchMedia("(prefers-reduced-transparency: reduce), (forced-colors: active)"),m=new Map,W=t.classList.contains(y),L=new i.ResizeObserver(u);let w,E,x,c=null,l=null,g=null,p,f="off",v=!1;function s(e,n){const o="--liquid-glass-"+e;t.style.getPropertyValue(o)!==String(n)&&(m.has(o)||m.set(o,[t.style.getPropertyValue(o),t.style.getPropertyPriority(o)]),t.style.setProperty(o,n))}function R(){for(const[e,[n,o]]of m)t.style.setProperty(e,n,o);m.clear()}function u(){!v&&r.mode!=="off"&&l===null&&(l=i.requestAnimationFrame(X))}function a(e,n=""){e!=="off"&&s("lens",e==="backdrop"?n:""),f!==e&&(f=e,i.queueMicrotask(()=>{!v&&f===e&&t.dispatchEvent(new i.CustomEvent("liquidglass:rendererchange",{detail:{renderer:e}}))}))}function b(){w?.dispose(),w=void 0}function H(e){(!(e.target instanceof i.Node)||!c?.contains(e.target))&&u()}function d(e){e!==c&&(E?.dispose(),E=void 0,c&&L.unobserve(c),!c&&e&&(i.addEventListener("scroll",H,!0),i.addEventListener("resize",u)),c=e,c&&L.observe(c),c||(i.removeEventListener("scroll",H,!0),i.removeEventListener("resize",u)))}function D(){const e=t.getRootNode();let n=r.viewportSource;if(typeof n=="string")try{n=e.querySelector(n)}catch{return null}return!(n instanceof i.HTMLElement)||n.getRootNode()!==e||n.contains(t)||t.contains(n)?null:n}function O(){const e=D();if(d(e),!e?.isConnected){a("frost");return}E??=J(t,e,P),f!=="viewport"&&a("frost");const n=r;E.render(r,o=>{r===n&&a(o?"viewport":"frost")})}function X(){l=null;const{mode:e,refraction:n}=r,{clientWidth:o,clientHeight:S}=t;if(M.matches||e==="frost"||!n||!t.isConnected||!o||!S){b(),d(null),a("frost");return}if(B&&(e==="auto"||e==="backdrop")){x=Y(o,S,r,x),w??=I(t);const A=r;w.render(x,r,G=>{r===A&&(G?(d(null),a("backdrop",G)):e==="auto"?O():(d(null),a("frost")))});return}b(),e==="viewport"||e==="auto"?O():(d(null),a("frost"))}function h(){p=void 0,r.mode!=="off"&&(s("light-x",""),s("light-y",""))}function T(e){r.mode==="off"||!r.interactive||q.matches||e.pointerType==="touch"||(p={x:e.clientX,y:e.clientY},g===null&&(g=i.requestAnimationFrame(()=>{if(g=null,!p)return;const{width:n,height:o,left:S,top:A}=t.getBoundingClientRect();!n||!o||(s("light-x",(p.x-S)/n*100+"%"),s("light-y",(p.y-A)/o*100+"%"))})))}function V(){if(r.mode==="off"){l!==null&&i.cancelAnimationFrame(l),l=null,p=void 0,b(),d(null),R(),t.classList.remove(y),a("off");return}t.classList.add(y),s("radius",r.radius+"px"),s("blur",r.blur+"px"),s("saturation",r.saturation),s("tint",r.tint),s("glow",r.glow),s("edge",r.edgeHighlight),s("angle",r.lightAngle+"deg"),r.interactive||h(),f==="off"&&a("frost"),u()}const z={get renderer(){return f},update(e,{replace:n=!1}={}){v||(r=N(i,e,n?void 0:r),V())},refresh:u,destroy(){v||(v=!0,l!==null&&i.cancelAnimationFrame(l),g!==null&&i.cancelAnimationFrame(g),b(),d(null),L.disconnect(),t.removeEventListener("pointermove",T),t.removeEventListener("pointerleave",h),q.removeEventListener("change",h),M.removeEventListener("change",u),R(),W?t.classList.add(y):t.classList.remove(y),C.delete(t),f="off")}};return C.set(t,z),t.addEventListener("pointermove",T,{passive:!0}),t.addEventListener("pointerleave",h),q.addEventListener("change",h),M.addEventListener("change",u),L.observe(t),V(),z}export{$ as liquidGlass};
@@ -1 +1 @@
1
- const nt=192,ot=1.5,h=new Map;function tt(t){if(h.has(t))return h.get(t);const n=new Float32Array(193),a=1.3+t*.55,l=Math.tan(Math.acos(1/1.5));n[0]=1;for(let r=1;r<192;r++){const c=1-r/192,I=c**(a-1)*(1-c**a)**(1/a-1),M=Math.atan(I),o=Math.tan(M-Math.asin(Math.sin(M)/1.5));n[r]=.72*o/l+.28*c*c*(3-2*c)}return h.size===32&&h.delete(h.keys().next().value),h.set(t,n),n}function st(t,n,{radius:a,bevel:l,curvature:r,lightAngle:c=145},I=1){const M=Math.min(I,512/Math.max(t,n)),o=Math.max(1,Math.round(t*M)),i=Math.max(1,Math.round(n*M)),N=new Uint8Array(o*i),P=new Uint8Array(o*i),H=new Float32Array(o*i*2),U=t/2,k=n/2,W=Math.min(a,U,k),J=Math.min(l,U,k),v=t/o,z=n/i,G=Math.max(v,z),X=tt(r),j=c*Math.PI/180,K=-Math.sin(j),L=Math.cos(j),O=Math.ceil(o/2),Q=Math.ceil(i/2);for(let s=0;s<Q;s++){const x=W-(s+.5)*z,f=i-s-1;for(let e=0;e<O;e++){let w=function(_,$,C,D){const A=_*o+$;N[A]=R,F&&(H[2*A]=C*F,H[2*A+1]=D*F);const E=-C*K-D*L;P[A]=Z*(.19+.81*Math.max(E,-E*.64))};const d=W-(e+.5)*v,g=Math.max(0,d),u=Math.max(0,x),m=g&&u?Math.hypot(g,u):g+u,Y=W-m-Math.min(Math.max(d,x),0);if(Y<=-G/2)continue;const R=Math.min(1,.5+Y/G)*255,p=o-e-1,S=p===e?0:m?g/m:+(d>x),b=f===s?0:m?u/m:+(x>d),q=Math.max(0,Y),B=Math.min(192,q*192/J),y=Math.floor(B),F=X[y]+(X[Math.min(192,y+1)]-X[y])*(B-y),T=Math.max(0,1-q/2.1),V=Math.max(0,1-q/10),Z=255*(.78*T**2+.22*V**2);w(s,e,S,b),p!==e&&w(s,p,-S,b),f!==s&&w(f,e,S,-b),f!==s&&p!==e&&w(f,p,-S,-b)}}return{columns:o,rows:i,offsets:H,coverage:N,highlights:P}}function et(t,n,a,l){return Math.min(t,Math.min(a,l)*.48/(1+n))}export{st as lensGeometry,et as lensStrength};
1
+ function A(a){const o=Math.max(0,Math.min(1,a));return o*o*(3-2*o)}function R(a,o,{radius:z,refraction:F,bevel:C,curvature:N},P){const i=Math.min(z,a/2,o/2),X=Math.min(C,a/2,o/2),r=X*(.45+.55*Math.min(1,.625*(F/X))),Y=Math.min(i,r),p=r-Y,j=.14+.035*N,G=.8*(1-j)/1.5,M=Math.min(F,r*G),H=[a,o,i,r,N,M].join("/");if(P?.key===H)return P;const W=Math.min(1,512/Math.max(a,o)),e=Math.max(1,Math.round(a*W)),l=Math.max(1,Math.round(o*W)),d=new Float32Array(e*l*2),D=a/e,E=o/l;for(let n=0;n<Math.ceil(l/2);n++){const s=i-(n+.5)*E,c=l-n-1;for(let t=0;t<Math.ceil(e/2);t++){let k=function(K,L,O,Q){const q=2*(K*e+L);d[q]=O*B,d[q+1]=Q*B};const m=i-(t+.5)*D,u=Math.max(0,m),h=Math.max(0,s),x=u&&h?Math.hypot(u,h):u+h,J=i-x-Math.min(Math.max(m,s),0),B=I(J,Math.max(-m,-s));if(!B)continue;const f=e-t-1,b=f===t?0:x?u/x:+(m>s),y=c===n?0:x?h/x:+(s>m);k(n,t,b,y),f!==t&&k(n,f,-b,y),c!==n&&k(c,t,b,-y),c!==n&&f!==t&&k(c,f,-b,-y)}}function I(n,s){if(n<=0||n>=r||!M)return 0;const c=p?Y+p*A(s/(2*p)):r;if(n>=c)return 0;const t=c*j;return Math.min(M,c*G)/M*A(n/t)*(1-A((n-t)/(c-t)))}return{width:a,height:o,columns:e,rows:l,offsets:d,strength:M,key:H}}export{R as lensGeometry};
@@ -1 +1 @@
1
- const a=Object.freeze({mode:"auto",backdrop:null,radius:24,blur:2,refraction:18,bevel:24,curvature:2,chroma:0,saturation:1.35,tint:.14,glow:.23,edgeHighlight:.85,lightAngle:145,interactive:!0}),u={radius:[0,1/0],blur:[0,1/0],refraction:[0,1/0],bevel:[.5,1/0],curvature:[.25,8],chroma:[0,1],saturation:[0,1/0],tint:[0,1],glow:[0,1],edgeHighlight:[0,1],lightAngle:[-1/0,1/0]};function f(o,i,c=a){const e={...c};for(const t of Object.keys(a))i[t]!==void 0&&(e[t]=i[t]);for(const[t,[s,l]]of Object.entries(u)){const r=e[t];if(!Number.isFinite(r)||r<s||r>l)throw new RangeError("Invalid liquidGlass option: "+t)}if(!["auto","content","backdrop","sampled","frost"].includes(e.mode))throw new TypeError('mode must be "auto", "content", "backdrop", "sampled", or "frost"');if(typeof e.interactive!="boolean")throw new TypeError("interactive must be a boolean");const n=e.backdrop;if(n!==null&&(!(n instanceof o.HTMLImageElement||n instanceof o.HTMLCanvasElement||n instanceof o.HTMLVideoElement)||n.ownerDocument!==o.document))throw new TypeError("backdrop must be an image, canvas, or video from the same document, or null");return e}export{f as resolveOptions};
1
+ const u=Object.freeze({mode:"auto",viewportSource:null,radius:24,blur:2,refraction:18,bevel:24,curvature:2,chroma:0,saturation:1.35,tint:.14,glow:.23,edgeHighlight:.85,lightAngle:145,interactive:!0}),s={radius:[0,1/0],blur:[0,1/0],refraction:[0,1/0],bevel:[.5,1/0],curvature:[.25,8],chroma:[0,1],saturation:[0,1/0],tint:[0,1],glow:[0,1],edgeHighlight:[0,1],lightAngle:[-1/0,1/0]};function l(r,i,a=u){const e={...a};for(const t of Object.keys(u))i[t]!==void 0&&(e[t]=i[t]);for(const[t,[c,f]]of Object.entries(s)){const n=e[t];if(!Number.isFinite(n)||n<c||n>f)throw new RangeError("Invalid liquidGlass option: "+t)}if(!["auto","viewport","backdrop","frost","off"].includes(e.mode))throw new TypeError('mode must be "auto", "viewport", "backdrop", "frost", or "off"');if(typeof e.interactive!="boolean")throw new TypeError("interactive must be a boolean");const o=e.viewportSource;if(o!==null&&typeof o!="string"&&(!(o instanceof r.HTMLElement)||o.ownerDocument!==r.document))throw new TypeError("viewportSource must be a selector, a same-document HTML element, or null");return e}export{l as resolveOptions};
@@ -1 +1 @@
1
- import{lensStrength as X}from"../optics.js";const Y="http://www.w3.org/2000/svg",K=new WeakMap,S={x:0,y:0,width:1,height:1};let W=0;function $(n){const{userAgentData:r,userAgent:t}=n.navigator;return r?.brands.some(({brand:s})=>s==="Chromium")||/\b(?:Chrome|Chromium)\//.test(t)?"blink":/Firefox\//.test(t)?"gecko":/AppleWebKit\//.test(t)?"webkit":"unknown"}function C(n,r){for(const[t,s]of Object.entries(r)){const e=String(s);n.getAttribute(t)!==e&&n.setAttribute(t,e)}return n}function I(n,r,t){return C(n.createElementNS(Y,r),t)}function z(n,r,t,s){if(!s)return{unit:1,xScale:1,yScale:1};if(n==="webkit"){const e=Math.min(r,t);return{unit:e,xScale:e/r,yScale:e/t}}return{unit:n==="gecko"?Math.hypot(r,t)/Math.SQRT2:r,xScale:1,yScale:1}}function J(n,r,t,s){K.has(n)||K.set(n,{entries:new Map,canvas:n.createElement("canvas")});const{entries:e,canvas:i}=K.get(n),c=[r,t,s.key].join("/");let a=e.get(c);if(a)return e.delete(c),e.set(c,a),a;const{columns:g,rows:h,offsets:p,coverage:l,highlights:b,width:f,height:o}=s,{xScale:d,yScale:y}=z(r,f,o,t);i.width=g,i.height=h;const v=i.getContext("2d");if(a={url:null,ready:Promise.resolve(null)},v){const R=v.createImageData(g,h),x=R.data;for(let m=0;m<l.length;m++){const u=4*m;x[u]=127.5+127.5*p[2*m]*d,x[u+1]=127.5+127.5*p[2*m+1]*y,x[u+2]=b[m],x[u+3]=t?l[m]:255}v.putImageData(R,0,0);const M=i.toDataURL(),O=new n.defaultView.Image;O.src=M,a.ready=O.decode().then(()=>(a.url=M,M),()=>null)}return e.size>=32&&e.delete(e.keys().next().value),e.set(c,a),a}function Z(n,r,t){const s=I(n,"filter",{...S,id:"liquid-glass-"+ ++W,primitiveUnits:r?"objectBoundingBox":"userSpaceOnUse","color-interpolation-filters":"sRGB"});function e(f,o){const d=I(n,f,o);return s.append(d),d}r&&e("feFlood",{...S,"flood-color":"rgb(128,128,0)",result:"neutral"});const i=e("feImage",{...S,preserveAspectRatio:"none",result:r?"shape":"offsets"});r&&e("feComposite",{...S,in:"shape",in2:"neutral",operator:"over",result:"offsets"});const c=t.blur?"frosted":"SourceGraphic",a=t.blur?e("feGaussianBlur",{in:"SourceGraphic",result:c}):null;function g(f){return e("feDisplacementMap",{in:c,in2:"offsets",xChannelSelector:"R",yChannelSelector:"G",result:f})}const h=[];if(t.chroma){const f=["red","green","blue"];for(const[o,d]of f.entries()){h.push(g(d));const y=Array(20).fill(0);y[o*6]=1,y[19]=1,e("feColorMatrix",{in:d,values:y.join(" "),result:d+"Only"})}e("feBlend",{in:"redOnly",in2:"greenOnly",mode:"screen",result:"redGreen"}),e("feBlend",{in:"redGreen",in2:"blueOnly",mode:"screen",result:"rgb"}),e("feComposite",{in:"rgb",in2:"green",operator:"in",result:"warped"})}else h.push(g("warped"));let p="warped";const l=t.saturation?e("feColorMatrix",{in:p,type:"saturate",result:"saturated"}):null;l&&(p="saturated");const b=t.rim?e("feColorMatrix",{...S,in:"offsets",result:"rim"}):null;return b&&(e("feComposite",{...S,in:"rim",in2:p,operator:"atop",result:"lit"}),p="lit"),r&&(e("feComposite",{...S,in:p,in2:"shape",operator:"in",result:"interior"}),e("feComposite",{in:"SourceGraphic",in2:"shape",operator:"out",result:"exterior"}),e("feComposite",{in:"interior",in2:"exterior",operator:"arithmetic",k2:1,k3:1})),{graph:s,map:i,displacements:h,blur:a,saturation:l,rim:b}}function ee(n,r,t){const s=n.ownerDocument,e=s.defaultView,i=t==="content",c=I(s,"svg",{width:0,height:0,"aria-hidden":"true"});c.style.cssText="position:absolute;overflow:hidden;pointer-events:none";const a=n.getRootNode();(a===s?s.body:a).append(c);const g=I(s,"defs",{});c.append(g);let h,p=0,l,b=!1,f,o,d,y,v,R=!1;function x(u=!1){u&&(o.graph.id="liquid-glass-"+ ++W),f.apply('url("#'+o.graph.id+'")')}function M(){if(!l)return;const{geometry:u,options:q}=f,{width:w,height:k,key:B}=u,{refraction:D,chroma:T,blur:j,saturation:U,edgeHighlight:E}=q,L=[l,B,D,T,i?j:0,i?U:1,i?E:0];if(y?.every((G,A)=>G===L[A])){x();return}y=L;const F={chroma:!!T,blur:i&&!!j,saturation:i&&U!==1,rim:i&&!!E},N=Object.values(F).join("/");d!==N&&(d=N,o=Z(s,i,F),g.replaceChildren(o.graph));const{unit:H}=z(r,w,k,i),P=2*X(D,T,w,k)/H;if(i){const G=18/w,A=18/k;C(o.graph,{x:-G,y:-A,width:1+2*G,height:1+2*A})}const Q=o.map.getAttribute("href")!==l;C(o.map,{href:l,width:i?1:w,height:i?1:k});for(const[G,A]of o.displacements.entries())C(A,{scale:P*(F.chroma?1+(G-1)*T:1)});o.blur&&C(o.blur,{stdDeviation:j/w+" "+j/k}),o.saturation&&C(o.saturation,{values:U}),o.rim&&C(o.rim,{values:"0 0 0 0 1 0 0 0 0 1 0 0 0 0 1 0 0 "+E+" 0 0"});const V=i&&r==="webkit";x(V),V&&Q&&(e.clearTimeout(v),v=e.setTimeout(()=>x(!0),94))}function O(u,q,w){if(f={geometry:u,options:q,apply:w},h!==u.key){h=u.key,b=!1;const k=++p,B=J(s,r,i,u);B.url?l=B.url:B.ready.then(D=>{R||k!==p||(D?(l=D,M()):l||(b=!0,f.apply("")))})}b?w(""):M()}function m(){R=!0,e.clearTimeout(v),c.remove()}return{render:O,dispose:m}}export{$ as browserEngine,ee as makeSvgLens};
1
+ const y="http://www.w3.org/2000/svg",x=new WeakMap;let k=0;function q(t){const{userAgentData:s,userAgent:e}=t.navigator;return s?.brands.some(({brand:r})=>r==="Chromium")||/\b(?:Chrome|Chromium)\//.test(e)?"blink":/Firefox\//.test(e)?"gecko":/AppleWebKit\//.test(e)?"webkit":"unknown"}function w(t,s){for(const[e,r]of Object.entries(s)){const n=String(r);t.getAttribute(e)!==n&&t.setAttribute(e,n)}return t}function g(t,s,e){return w(t.createElementNS(y,s),e)}function v(t){const s=t.ownerDocument,e=g(s,"svg",{width:0,height:0,"aria-hidden":"true"});e.style.cssText="position:absolute;overflow:hidden;pointer-events:none";const r=g(s,"defs",{});e.append(r);const n=t.getRootNode();return(n===s?s.body:n).append(e),{root:e,defs:r}}function b(){return"liquid-glass-"+ ++k}function D(t,s){x.has(t)||x.set(t,{entries:new Map,canvas:t.createElement("canvas")});const{entries:e,canvas:r}=x.get(t),{key:n}=s;let o=e.get(n);if(o)return e.delete(n),e.set(n,o),o;const{columns:a,rows:i,offsets:u}=s;r.width=a,r.height=i;const l=r.getContext("2d");if(o={url:null,ready:Promise.resolve(null)},l){const c=l.createImageData(a,i),p=c.data;for(let d=0;d<a*i;d++){const h=4*d;p[h]=128+127*u[2*d],p[h+1]=128+127*u[2*d+1],p[h+3]=255}l.putImageData(c,0,0);const f=r.toDataURL(),m=new t.defaultView.Image;m.src=f,o.ready=m.decode().then(()=>(o.url=f,f),()=>null)}return e.size>=32&&e.delete(e.keys().next().value),e.set(n,o),o.ready.then(c=>{!c&&e.get(n)===o&&e.delete(n)}),o}function C(t,s){function e(o,a){const i=g(t.ownerDocument,o,a);return t.append(i),i}function r(o){return e("feDisplacementMap",{in:"SourceGraphic",in2:"offsets",xChannelSelector:"R",yChannelSelector:"G",result:o})}if(!s)return[r("warped")];const n=[];for(const[o,a]of["red","green","blue"].entries()){n.push(r(a));const i=Array(20).fill(0);i[o*6]=i[19]=1,e("feColorMatrix",{in:a,values:i.join(" "),result:a+"Only"})}return e("feBlend",{in:"redOnly",in2:"greenOnly",mode:"screen",result:"redGreen"}),e("feBlend",{in:"redGreen",in2:"blueOnly",mode:"screen",result:"rgb"}),e("feComposite",{in:"rgb",in2:"green",operator:"in",result:"warped"}),n}function M(t,s,e){const r=2*s/(1+e);for(const[n,o]of t.entries())w(o,{scale:r*(t.length===1?1:1+(n-1)*e)})}function R(t,s){let e,r=0;const n={url:null,key:null,failed:!1,requestMap:o,cancel:a};function o(i){if(e===i.key)return;e=i.key,n.failed=!1;const u=++r,l=D(t,i);if(l.url){n.url=l.url,n.key=i.key;return}l.ready.then(c=>{u===r&&(n.url=c,n.key=i.key,n.failed=!c,s())})}function a(){r++}return n}function A(t){const{root:s,defs:e}=v(t),r=R(t.ownerDocument,l);let n,o,a,i,u;function l(){const{geometry:c,options:p,apply:f}=n;if(r.failed){f("");return}if(!r.url||r.key!==c.key)return;const{width:m,height:d}=c,{chroma:h}=p;u!==!!h&&(u=!!h,o=g(t.ownerDocument,"filter",{id:b(),x:0,y:0,width:1,height:1,primitiveUnits:"userSpaceOnUse","color-interpolation-filters":"sRGB"}),a=g(t.ownerDocument,"feImage",{x:0,y:0,preserveAspectRatio:"none",result:"offsets"}),o.append(a),i=C(o,u),e.replaceChildren(o)),w(a,{href:r.url,width:m,height:d}),M(i,c.strength,h),f('url("#'+o.id+'")')}return{render(c,p,f){n={geometry:c,options:p,apply:f},r.requestMap(c),l()},dispose(){r.cancel(),s.remove()}}}export{C as appendRefraction,w as attrs,q as browserEngine,b as filterId,v as filterRoot,R as makeMapRequest,A as makeSvgLens,M as setDisplacement,g as svg};
@@ -0,0 +1 @@
1
+ import{lensGeometry as D}from"../optics.js";import{appendRefraction as I,attrs as P,filterId as S,filterRoot as A,makeMapRequest as G,setDisplacement as W,svg as w}from"./svg.js";const v=new WeakMap;function M(i,n,t){let e=v.get(i);if(!e){const{style:l}=i,r=i.ownerDocument.defaultView.getComputedStyle(i).filter;e={value:l.getPropertyValue("filter"),priority:l.getPropertyPriority("filter"),base:r&&r!=="none"?r:"",lenses:new Map},v.set(i,e)}e.lenses.set(n,'url("#'+t+'")'),O(i,e)}function O(i,{base:n,lenses:t,priority:e}){const l=[n,...t.values()].filter(Boolean).join(" ");i.style.getPropertyValue("filter")!==l&&i.style.setProperty("filter",l,e)}function T(i,n){const t=v.get(i);t?.lenses.delete(n)&&(t.lenses.size?O(i,t):(i.style.setProperty("filter",t.value,t.priority),v.delete(i)))}function U(i,n){const t=i.getBoundingClientRect(),e=n.getBoundingClientRect();if(t.right<=e.left||t.bottom<=e.top||t.left>=e.right||t.top>=e.bottom)return null;const{offsetWidth:l,offsetHeight:r}=n;if(!l||!r||!e.width||!e.height||!t.width||!t.height)return null;const u=l/e.width,d=r/e.height;return{viewport:{x:0,y:0,width:l,height:r},lens:{x:(t.left-e.left)*u,y:(t.top-e.top)*d,width:t.width*u,height:t.height*d}}}function L(i,n,t){const e={},l=n.ownerDocument,r=l.defaultView,{root:u,defs:d}=A(n),s=G(l,B);let a,V,k,o,h,b,j,R,m;const x=t==="webkit";function B(p=U(i,n)){const{options:C,applied:f}=V;if(!p||s.failed||!n.isConnected||!i.isConnected){r.clearTimeout(m),T(n,e),k=void 0,f(!1);return}if(!s.url||s.key!==a.key)return;const{viewport:c,lens:g}=p,{chroma:y}=C,F=[...Object.values(c),...Object.values(g),a.key,y].join("/");if(F===k){f(!0);return}k=F,R!==!!y&&(R=!!y,o=w(l,"filter",{id:S(),filterUnits:"userSpaceOnUse",primitiveUnits:"userSpaceOnUse","color-interpolation-filters":"sRGB"}),b=w(l,"feFlood",{"flood-color":"#808000",result:"neutral"}),h=w(l,"feImage",{preserveAspectRatio:"none",result:"lens"}),o.append(b,h,w(l,"feComposite",{in:"lens",in2:"neutral",operator:"over",result:"offsets"})),j=I(o,R),d.replaceChildren(o));const q=h.getAttribute("href")!==s.url;P(o,c),P(b,c),P(h,{...g,href:s.url}),W(j,a.strength,y),x&&(o.id=S()),M(n,e,o.id),x&&q&&(r.clearTimeout(m),m=r.setTimeout(()=>{o.id=S(),M(n,e,o.id)},94)),f(!0)}return{render(p,C){V={options:p,applied:C};const f=U(i,n);if(f){const{width:c,height:g}=f.lens;a=D(c,g,p,a),s.requestMap(a)}B(f)},dispose(){s.cancel(),r.clearTimeout(m),T(n,e),u.remove()}}}export{L as makeViewportLens};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ikeofficial/liquid-glass-js",
3
- "version": "0.2.1",
3
+ "version": "0.3.0",
4
4
  "description": "Refractive, interactive glass surfaces for the web",
5
5
  "type": "module",
6
6
  "exports": {
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: liquid-glass-js
3
- description: Install and integrate the Liquid Glass JS library with plain JavaScript, Angular, React, or Vue. Use when a user requests this library or wants to tune its element, image, or live-page refraction.
3
+ description: Install and integrate the Liquid Glass JS library with plain JavaScript, Angular, React, or Vue. Use when a user requests this library or wants to tune its viewport or live-page refraction.
4
4
  ---
5
5
 
6
6
  ## Install
@@ -17,9 +17,9 @@ description: Install and integrate the Liquid Glass JS library with plain JavaSc
17
17
 
18
18
  Use an ordinary HTML host with geometry supplied by the app’s CSS and available `::before` and `::after` pseudo-elements. The adapters clean themselves up and treat a new options object as the complete configuration.
19
19
 
20
- ## Choose the surface to refract
20
+ ## Choose the renderer
21
21
 
22
- - `{ mode: "content" }` bends the host’s own rendered pixels across browsers. Put the artwork inside the element or paint it via its CSS background. Use a decorative layer when text must stay optically sharp.
23
- - `{ mode: "sampled", backdrop: media }` samples a same-origin or CORS-enabled image, canvas, or video behind the lens. Use an axis-aligned, borderless source and `object-fit: fill` or centered `cover` or `contain`. Call `glass.refresh()` after changing position or redrawing a canvas.
24
- - Automatic mode (the default) refracts live page pixels in Chromium and falls back to the supplied backdrop or CSS frost. Use `{ mode: "backdrop" }` without a source to select live page refraction explicitly. `{ mode: "frost" }` uses CSS directly. Use sampled or frost mode if CSP prevents the generated SVG-map image.
25
- - Use the target project’s own markup and geometry. Check focus, contrast, and the effect over detailed artwork. Run `mise run dev` in the library checkout for the playground and framework examples.
22
+ - Omitting `mode` selects `auto`. Use `{ viewportSource: source }` to try native backdrop refraction, then viewport SVG when the source is usable, then frost.
23
+ - `{ mode: "viewport", viewportSource: source }` selects viewport SVG explicitly. Supply a same-tree HTML element or selector. Use a bounded scroll pane and position the lens above it in a separate layer. In Angular, a template reference such as `#feed` can be passed as `viewportSource: feed`.
24
+ - `{ mode: "backdrop" }` selects native backdrop refraction when available. `{ mode: "frost" }` selects CSS frost directly. `{ mode: "off" }` disables the material and restores author styling.
25
+ - Call `glass.refresh()` after moving the lens relative to the source or replacing its selector target. Run `mise run dev` and use the **Usage** renderer picker to get a matching JavaScript, Angular, React, or Vue example. Verify the effect over live text and detailed artwork.
@@ -1 +0,0 @@
1
- import{lensStrength as L}from"../optics.js";import{drawWebGl as V}from"./webgl.js";function z(s){const i=s.createElement("canvas");i.className="liquid-glass-backdrop",i.setAttribute("aria-hidden","true");const m=i.getContext("2d"),r=s.createElement("canvas"),a=r.getContext("2d");let p;function v(t,o,w){const{columns:e,rows:h,offsets:u,coverage:N,highlights:R}=o,{refraction:q,chroma:B,edgeHighlight:A}=w;if(!m||!a||!t.isConnected)return!1;const n=t.getBoundingClientRect(),l=i.getBoundingClientRect();if(!l.width||!l.height||!n.width||!n.height||n.right<=l.left||n.left>=l.right||n.bottom<=l.top||n.top>=l.bottom||t.localName==="img"&&(!t.complete||!t.naturalWidth)||t.localName==="canvas"&&(!t.width||!t.height)||t.localName==="video"&&(t.readyState<2||!t.videoWidth))return!1;(!p||i.width!==e||i.height!==h)&&(i.width=r.width=e,i.height=r.height=h,p=m.createImageData(e,h));const x=e/l.width,b=h/l.height,I=L(q,B,o.width,o.height),F=I*e/o.width,G=I*h/o.height;let k=n.left,D=n.top,M=n.width,C=n.height;if(t.localName!=="canvas"){const d=t.naturalWidth??t.videoWidth,f=t.naturalHeight??t.videoHeight,g=s.defaultView.getComputedStyle(t).objectFit;if(g==="cover"||g==="contain"){const W=(g==="cover"?Math.max:Math.min)(M/d,C/f),H=W*d,c=W*f;k+=(M-H)/2,D+=(C-c)/2,M=H,C=c}else if(g!=="fill")return!1}if(a.clearRect(0,0,e,h),a.save(),a.beginPath(),a.rect((n.left-l.left)*x,(n.top-l.top)*b,n.width*x,n.height*b),a.clip(),a.drawImage(t,(k-l.left)*x,(D-l.top)*b,M*x,C*b),a.restore(),V(s,r,o,I,w,m))return!0;let E;try{E=a.getImageData(0,0,e,h).data}catch(d){if(d.name!=="SecurityError")throw d;return r.width=e,!1}for(let d=0,f=0;d<h;d++)for(let g=0;g<e;g++,f++){const P=u[f*2]*F,W=u[f*2+1]*G,H=R[f]*A/255;for(let c=0;c<4;c++){const j=c===0?1-B:c===2?1+B:1,S=X(E,e,h,g+P*j,d+W*j,c);p.data[f*4+c]=c===3?S*N[f]/255:S+(255-S)*H}}return m.putImageData(p,0,0),!0}return{canvas:i,render:v}}function X(s,i,m,r,a,p){r=Math.max(0,Math.min(i-1,r)),a=Math.max(0,Math.min(m-1,a));const v=Math.floor(r),t=Math.floor(a),o=r-v,w=a-t,e=(t*i+v)*4+p,h=o?4:0,u=w?i*4:0,N=s[e]*(1-o)+s[e+h]*o,R=s[e+u]*(1-o)+s[e+u+h]*o;return N*(1-w)+R*w}export{z as makeBackdropLens};
@@ -1,28 +0,0 @@
1
- const u=new WeakMap,D=`
2
- attribute vec2 position;
3
- varying vec2 uv;
4
- void main() {
5
- gl_Position = vec4(position, 0.0, 1.0);
6
- uv = vec2(position.x + 1.0, 1.0 - position.y) * 0.5;
7
- }
8
- `,b=`
9
- precision mediump float;
10
- varying vec2 uv;
11
- uniform sampler2D plate;
12
- uniform sampler2D lens;
13
- uniform vec2 strength;
14
- uniform float chroma;
15
- uniform float rim;
16
-
17
- void main() {
18
- vec4 map = texture2D(lens, uv);
19
- vec2 offset = (map.rg * 255.0 - 128.0) / 127.0 * strength;
20
- vec4 color = texture2D(plate, uv + offset);
21
- if (chroma > 0.0) {
22
- color.r = texture2D(plate, uv + offset * (1.0 - chroma)).r;
23
- color.b = texture2D(plate, uv + offset * (1.0 + chroma)).b;
24
- }
25
- color.rgb = mix(color.rgb, vec3(1.0), map.b * rim);
26
- gl_FragColor = vec4(color.rgb, color.a * map.a);
27
- }
28
- `;function v(e){const t=e.createProgram();for(const[a,n]of[[e.VERTEX_SHADER,D],[e.FRAGMENT_SHADER,b]]){const s=e.createShader(a);e.shaderSource(s,n),e.compileShader(s),e.attachShader(t,s),e.deleteShader(s)}if(e.linkProgram(t),!e.getProgramParameter(t,e.LINK_STATUS))return e.deleteProgram(t),null;e.useProgram(t);const r=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,r),e.bufferData(e.ARRAY_BUFFER,new Float32Array([-1,-1,3,-1,-1,3]),e.STATIC_DRAW);const o=e.getAttribLocation(t,"position");e.enableVertexAttribArray(o),e.vertexAttribPointer(o,2,e.FLOAT,!1,0,0);for(const[a,n]of["plate","lens"].entries())e.activeTexture(e.TEXTURE0+a),e.bindTexture(e.TEXTURE_2D,e.createTexture()),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.uniform1i(e.getUniformLocation(t,n),a);return e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,e.NONE),{strength:e.getUniformLocation(t,"strength"),chroma:e.getUniformLocation(t,"chroma"),rim:e.getUniformLocation(t,"rim")}}function L(e){const t=e.createElement("canvas"),r=t.getContext("webgl",{antialias:!1,depth:!1,stencil:!1,premultipliedAlpha:!1});if(!r)return null;let o=v(r),a;return t.addEventListener("webglcontextlost",n=>{n.preventDefault(),o=null}),t.addEventListener("webglcontextrestored",()=>{o=v(r),a=void 0}),function(s,m,T,{chroma:A,edgeHighlight:d},R){if(!o||r.isContextLost())return!1;const{width:_,height:x,columns:f,rows:E,offsets:h,coverage:p,highlights:U}=m;(t.width!==f||t.height!==E)&&(t.width=f,t.height=E),r.viewport(0,0,f,E),r.activeTexture(r.TEXTURE0);try{r.texImage2D(r.TEXTURE_2D,0,r.RGBA,r.RGBA,r.UNSIGNED_BYTE,s)}catch(c){if(c.name!=="SecurityError")throw c;return!1}if(a!==m){const c=new Uint8ClampedArray(f*E*4);for(let i=0;i<p.length;i++)c[4*i]=128+127*h[2*i],c[4*i+1]=128+127*h[2*i+1],c[4*i+2]=U[i],c[4*i+3]=p[i];r.activeTexture(r.TEXTURE1),r.texImage2D(r.TEXTURE_2D,0,r.RGBA,f,E,0,r.RGBA,r.UNSIGNED_BYTE,c),a=m}return r.uniform2f(o.strength,T/_,T/x),r.uniform1f(o.chroma,A),r.uniform1f(o.rim,d),r.drawArrays(r.TRIANGLES,0,3),R.clearRect(0,0,f,E),R.drawImage(t,0,0),!0}}function P(e,t,r,o,a,n){return u.has(e)||u.set(e,L(e)),u.get(e)?.(t,r,o,a,n)??!1}export{P as drawWebGl};