useblysh 1.0.1

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 RISHABH MISHRA
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,100 @@
1
+ # ⚡ useblysh
2
+
3
+ **High-performance visual hashing for seamless image loading.** The unified toolkit for Python and JavaScript to turn heavy images into elegant, byte-sized blurs.
4
+
5
+ [![npm version](https://img.shields.io/npm/v/useblysh?color=blue&style=flat-square)](https://www.npmjs.com/package/useblysh)
6
+ [![pypi version](https://img.shields.io/pypi/v/useblysh?color=green&style=flat-square)](https://pypi.org/project/useblysh)
7
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg?style=flat-square)](https://opensource.org/licenses/MIT)
8
+
9
+ ---
10
+
11
+ ## 🌟 Why useblysh?
12
+
13
+ Standard `loading="lazy"` leaves users staring at empty white boxes. **useblysh** eliminates this "broken" feel by encoding your images into tiny strings that can be sent inside your JSON API response.
14
+
15
+ * **Full-Stack:** Identical hashing logic for Python (Backend) and React (Frontend).
16
+ * **Zero Layout Shift:** Reserve image space instantly to prevent page jumping.
17
+ * **Performance:** Replace 1MB images with 20-byte strings during the initial load.
18
+ * **Modern:** Fully typed with TypeScript and optimized for React 18/19.
19
+
20
+ <img width="1441" height="387" alt="image" src="https://github.com/user-attachments/assets/3e9df482-5872-49d8-8fcf-f63fdaacde56" />
21
+
22
+ <img width="1441" height="387" alt="image" src="https://github.com/user-attachments/assets/50292c6d-f475-49ca-88bb-1fbeb74307be" />
23
+
24
+ ---
25
+
26
+ ## 🛠️ Installation
27
+
28
+ ### Frontend (React/NPM)
29
+ ```bash
30
+ npm install useblysh
31
+ ```
32
+
33
+
34
+ ---
35
+
36
+ ## 🚀 Simple Examples
37
+
38
+
39
+ ### **Generate Hash**
40
+ Generate hashes directly in the browser during an image upload.
41
+
42
+ ```tsx
43
+ import { encodeImage } from 'useblysh';
44
+
45
+ const handleUpload = (event) => {
46
+ const file = event.target.files[0];
47
+ const img = new Image();
48
+ img.src = URL.createObjectURL(file);
49
+
50
+ img.onload = () => {
51
+ // Generate the hash from the image element
52
+ const hash = encodeImage(img);
53
+ console.log("Generated Hash:", hash);
54
+
55
+ // Send { file, hash } to your server
56
+ };
57
+ };
58
+ ```
59
+
60
+ ### **Frontend: Display Placeholder (React)**
61
+ The `ImageHash` component handles everything: it shows the blur immediately and fades in the real image once it's ready.
62
+
63
+ ```tsx
64
+ import { ImageHash } from 'useblysh';
65
+
66
+ const MyGallery = ({ storedHash, imageUrl }) => (
67
+ <ImageHash
68
+ hash={storedHash} // The short string from your DB
69
+ src={imageUrl} // The real high-quality image URL
70
+ className="w-full h-64 rounded-xl"
71
+ />
72
+ );
73
+ ```
74
+
75
+
76
+
77
+ ---
78
+
79
+ ## 💡 Use Cases
80
+
81
+ ### 1. Progressive Image Loading
82
+ Instead of showing a spinner or a blank box, show a beautiful blurred version of the actual image. This keeps users engaged and makes the site feel faster.
83
+
84
+ ### 2. Social Media Feeds
85
+ For infinite scroll feeds (like Instagram or Pinterest), send the `useblysh` string in your initial JSON request. The app can render the entire feed layout with placeholders before a single byte of actual image data is even downloaded.
86
+
87
+ ### 3. SEO & Layout Stability (CLS)
88
+ Prevent "layout shift" where content jumps around as images load. `useblysh` reserves the correct aspect ratio and space immediately.
89
+
90
+ ---
91
+
92
+ ## 📖 How it Works
93
+
94
+ **Blysh** uses a Discrete Cosine Transform (DCT) to extract the most important color frequencies from an image.
95
+ 1. **Encoding:** The image is downsampled and converted into a set of mathematical factors, then compressed into a **Base83** string.
96
+ 2. **Decoding:** The frontend takes that string and reconstructs a low-resolution version of the original image, applying a smooth blur filter for an elegant look.
97
+
98
+ ---
99
+
100
+ **Built with ❤️ for the modern web.**
@@ -0,0 +1 @@
1
+ export declare const decode: (hash: string, width: number, height: number, punch?: number) => Uint8ClampedArray;
@@ -0,0 +1,5 @@
1
+ export declare const encode: (pixels: Uint8ClampedArray, width: number, height: number, componentsX?: number, componentsY?: number) => string;
2
+ /**
3
+ * Encodes an HTMLImageElement into a hash string.
4
+ */
5
+ export declare const encodeImage: (image: HTMLImageElement, componentsX?: number, componentsY?: number) => string;
@@ -0,0 +1,4 @@
1
+ export * from './utils';
2
+ export * from './encoder';
3
+ export * from './decoder';
4
+ export * from './react';
@@ -0,0 +1,17 @@
1
+ import { default as React } from 'react';
2
+ export interface ImageHashCanvasProps extends React.CanvasHTMLAttributes<HTMLCanvasElement> {
3
+ hash: string;
4
+ width?: number;
5
+ height?: number;
6
+ punch?: number;
7
+ }
8
+ export declare const ImageHashCanvas: React.ForwardRefExoticComponent<ImageHashCanvasProps & React.RefAttributes<HTMLCanvasElement>>;
9
+ export interface ImageHashProps extends React.ImgHTMLAttributes<HTMLImageElement> {
10
+ hash: string;
11
+ src: string;
12
+ }
13
+ /**
14
+ * A smart image component that shows a blurred placeholder (hash)
15
+ * until the actual image (src) loads.
16
+ */
17
+ export declare const ImageHash: React.FC<ImageHashProps>;
@@ -0,0 +1,22 @@
1
+ (function(m,T){typeof exports=="object"&&typeof module<"u"?T(exports,require("react")):typeof define=="function"&&define.amd?define(["exports","react"],T):(m=typeof globalThis<"u"?globalThis:m||self,T(m.UseBlysh={},m.React))})(this,(function(m,T){"use strict";const H="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz#$%*+,-.:;=?@[]^_{|}~",O=(r,t)=>{let s="";for(let c=1;c<=t;c++){const o=Math.floor(r/Math.pow(83,t-c))%83;s+=H[o]}return s},I=r=>{let t=0;for(let s=0;s<r.length;s++){const c=r[s],o=H.indexOf(c);t=t*83+o}return t},S=r=>{const t=r/255;return t<=.04045?t/12.92:Math.pow((t+.055)/1.055,2.4)},P=r=>{const t=Math.max(0,Math.min(1,r));return t<=.0031308?Math.round(t*12.92*255):Math.round((1.055*Math.pow(t,.4166666666666667)-.055)*255)},C=(r,t)=>Math.sign(r)*Math.pow(Math.abs(r),t),G=(r,t,s,c=4,o=3)=>{if(c<1||c>9||o<1||o>9)throw new Error("Components must be between 1 and 9");const i=[];for(let a=0;a<o;a++)for(let l=0;l<c;l++){const R=(l===0?1:2)*(a===0?1:2);let h=0,y=0,w=0;for(let M=0;M<s;M++)for(let x=0;x<t;x++){const k=Math.cos(Math.PI*l*x/t)*Math.cos(Math.PI*a*M/s),Y=(M*t+x)*4;h+=k*S(r[Y]),y+=k*S(r[Y+1]),w+=k*S(r[Y+2])}const A=R/(t*s);i.push([h*A,y*A,w*A])}const b=i[0],v=i.slice(1);let E="";E+=O(c-1+(o-1)*9,1);let _=1;if(v.length>0){const a=Math.max(...v.map(R=>Math.max(Math.abs(R[0]),Math.abs(R[1]),Math.abs(R[2])))),l=Math.max(0,Math.min(82,Math.floor(a*166-.5)));E+=O(l,1),_=(l+1)/166}else E+=O(0,1);E+=O((a=>{const l=P(a[0]),R=P(a[1]),h=P(a[2]);return(l<<16)+(R<<8)+h})(b),4);const p=(a,l)=>{const R=Math.max(0,Math.min(18,Math.floor(C(a[0]/l,.5)*9+9.5))),h=Math.max(0,Math.min(18,Math.floor(C(a[1]/l,.5)*9+9.5))),y=Math.max(0,Math.min(18,Math.floor(C(a[2]/l,.5)*9+9.5)));return R*19*19+h*19+y};for(const a of v)E+=O(p(a,_),2);return E},oe=(r,t=4,s=3)=>{const c=document.createElement("canvas");c.width=32,c.height=32;const o=c.getContext("2d");if(!o)throw new Error("Could not create canvas context");o.drawImage(r,0,0,32,32);const i=o.getImageData(0,0,32,32);return G(i.data,32,32,t,s)},X=(r,t,s,c=1)=>{if(!r||r.length<6)throw new Error("The hash is invalid.");const o=I(r[0]),i=o%9+1,b=Math.floor(o/9)+1,E=(I(r[1])+1)/166,_=[],g=I(r.substring(2,6));_.push([S(g>>16&255),S(g>>8&255),S(g&255)]);for(let a=1;a<i*b;a++){const l=I(r.substring(6+(a-1)*2,6+a*2));_.push([C((Math.floor(l/361)-9)/9,2)*E*c,C((Math.floor(l/19%19)-9)/9,2)*E*c,C((l%19-9)/9,2)*E*c])}const p=new Uint8ClampedArray(t*s*4);for(let a=0;a<s;a++)for(let l=0;l<t;l++){let R=0,h=0,y=0;for(let A=0;A<b;A++)for(let M=0;M<i;M++){const x=Math.cos(Math.PI*M*l/t)*Math.cos(Math.PI*A*a/s),k=_[A*i+M];R+=k[0]*x,h+=k[1]*x,y+=k[2]*x}const w=(a*t+l)*4;p[w]=P(R),p[w+1]=P(h),p[w+2]=P(y),p[w+3]=255}return p};var F={exports:{}},N={};/**
2
+ * @license React
3
+ * react-jsx-runtime.production.js
4
+ *
5
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
6
+ *
7
+ * This source code is licensed under the MIT license found in the
8
+ * LICENSE file in the root directory of this source tree.
9
+ */var Z;function se(){if(Z)return N;Z=1;var r=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function s(c,o,i){var b=null;if(i!==void 0&&(b=""+i),o.key!==void 0&&(b=""+o.key),"key"in o){i={};for(var v in o)v!=="key"&&(i[v]=o[v])}else i=o;return o=i.ref,{$$typeof:r,type:c,key:b,ref:o!==void 0?o:null,props:i}}return N.Fragment=t,N.jsx=s,N.jsxs=s,N}var D={};/**
10
+ * @license React
11
+ * react-jsx-runtime.development.js
12
+ *
13
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
14
+ *
15
+ * This source code is licensed under the MIT license found in the
16
+ * LICENSE file in the root directory of this source tree.
17
+ */var Q;function ce(){return Q||(Q=1,process.env.NODE_ENV!=="production"&&(function(){function r(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===me?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case y:return"Fragment";case A:return"Profiler";case w:return"StrictMode";case Y:return"Suspense";case ue:return"SuspenseList";case de:return"Activity"}if(typeof e=="object")switch(typeof e.tag=="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),e.$$typeof){case h:return"Portal";case x:return e.displayName||"Context";case M:return(e._context.displayName||"Context")+".Consumer";case k:var n=e.render;return e=e.displayName,e||(e=n.displayName||n.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case fe:return n=e.displayName||null,n!==null?n:r(e.type)||"Memo";case V:n=e._payload,e=e._init;try{return r(e(n))}catch{}}return null}function t(e){return""+e}function s(e){try{t(e);var n=!1}catch{n=!0}if(n){n=console;var u=n.error,f=typeof Symbol=="function"&&Symbol.toStringTag&&e[Symbol.toStringTag]||e.constructor.name||"Object";return u.call(n,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",f),t(e)}}function c(e){if(e===y)return"<>";if(typeof e=="object"&&e!==null&&e.$$typeof===V)return"<...>";try{var n=r(e);return n?"<"+n+">":"<...>"}catch{return"<...>"}}function o(){var e=z.A;return e===null?null:e.getOwner()}function i(){return Error("react-stack-top-frame")}function b(e){if(K.call(e,"key")){var n=Object.getOwnPropertyDescriptor(e,"key").get;if(n&&n.isReactWarning)return!1}return e.key!==void 0}function v(e,n){function u(){ee||(ee=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",n))}u.isReactWarning=!0,Object.defineProperty(e,"key",{get:u,configurable:!0})}function E(){var e=r(this.type);return te[e]||(te[e]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),e=this.props.ref,e!==void 0?e:null}function _(e,n,u,f,U,J){var d=u.ref;return e={$$typeof:R,type:e,key:n,props:u,_owner:f},(d!==void 0?d:null)!==null?Object.defineProperty(e,"ref",{enumerable:!1,get:E}):Object.defineProperty(e,"ref",{enumerable:!1,value:null}),e._store={},Object.defineProperty(e._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty(e,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty(e,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:U}),Object.defineProperty(e,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:J}),Object.freeze&&(Object.freeze(e.props),Object.freeze(e)),e}function g(e,n,u,f,U,J){var d=n.children;if(d!==void 0)if(f)if(be(d)){for(f=0;f<d.length;f++)p(d[f]);Object.freeze&&Object.freeze(d)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else p(d);if(K.call(n,"key")){d=r(e);var j=Object.keys(n).filter(function(Ee){return Ee!=="key"});f=0<j.length?"{key: someKey, "+j.join(": ..., ")+": ...}":"{key: someKey}",ae[d+f]||(j=0<j.length?"{"+j.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX:
18
+ let props = %s;
19
+ <%s {...props} />
20
+ React keys must be passed directly to JSX without using spread:
21
+ let props = %s;
22
+ <%s key={someKey} {...props} />`,f,d,j,d),ae[d+f]=!0)}if(d=null,u!==void 0&&(s(u),d=""+u),b(n)&&(s(n.key),d=""+n.key),"key"in n){u={};for(var q in n)q!=="key"&&(u[q]=n[q])}else u=n;return d&&v(u,typeof e=="function"?e.displayName||e.name||"Unknown":e),_(e,d,u,o(),U,J)}function p(e){a(e)?e._store&&(e._store.validated=1):typeof e=="object"&&e!==null&&e.$$typeof===V&&(e._payload.status==="fulfilled"?a(e._payload.value)&&e._payload.value._store&&(e._payload.value._store.validated=1):e._store&&(e._store.validated=1))}function a(e){return typeof e=="object"&&e!==null&&e.$$typeof===R}var l=T,R=Symbol.for("react.transitional.element"),h=Symbol.for("react.portal"),y=Symbol.for("react.fragment"),w=Symbol.for("react.strict_mode"),A=Symbol.for("react.profiler"),M=Symbol.for("react.consumer"),x=Symbol.for("react.context"),k=Symbol.for("react.forward_ref"),Y=Symbol.for("react.suspense"),ue=Symbol.for("react.suspense_list"),fe=Symbol.for("react.memo"),V=Symbol.for("react.lazy"),de=Symbol.for("react.activity"),me=Symbol.for("react.client.reference"),z=l.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,K=Object.prototype.hasOwnProperty,be=Array.isArray,B=console.createTask?console.createTask:function(){return null};l={react_stack_bottom_frame:function(e){return e()}};var ee,te={},re=l.react_stack_bottom_frame.bind(l,i)(),ne=B(c(i)),ae={};D.Fragment=y,D.jsx=function(e,n,u){var f=1e4>z.recentlyCreatedOwnerStacks++;return g(e,n,u,!1,f?Error("react-stack-top-frame"):re,f?B(c(e)):ne)},D.jsxs=function(e,n,u){var f=1e4>z.recentlyCreatedOwnerStacks++;return g(e,n,u,!0,f?Error("react-stack-top-frame"):re,f?B(c(e)):ne)}})()),D}var $;function le(){return $||($=1,process.env.NODE_ENV==="production"?F.exports=se():F.exports=ce()),F.exports}var L=le();const W=T.forwardRef(({hash:r,width:t=32,height:s=32,punch:c=1,...o},i)=>{const b=T.useRef(null),[v,E]=T.useState(!1);return T.useImperativeHandle(i,()=>b.current),T.useEffect(()=>{const _=b.current;if(!_)return;const g=new IntersectionObserver(p=>{p[0].isIntersecting&&(E(!0),g.disconnect())},{rootMargin:"100px"});return g.observe(_),()=>g.disconnect()},[]),T.useEffect(()=>{const _=b.current;if(!_||!r||!v)return;const g=_.getContext("2d");if(!g)return;const p=setTimeout(()=>{try{const a=X(r,t,s,c),l=new ImageData(a,t,s);g.putImageData(l,0,0)}catch(a){console.error("Failed to render ImageHash:",a)}},0);return()=>clearTimeout(p)},[r,t,s,c,v]),L.jsx("canvas",{ref:b,width:t,height:s,style:{imageRendering:"pixelated",...o.style},...o})});W.displayName="ImageHashCanvas";const ie=({hash:r,src:t,className:s,style:c,...o})=>{const[i,b]=T.useState(!1),{style:v,...E}=o;return L.jsxs("div",{className:s,style:{position:"relative",overflow:"hidden",display:"inline-block",...c},children:[L.jsx(W,{hash:r,style:{position:"absolute",inset:0,width:"100%",height:"100%",opacity:i?0:1,transition:"opacity 0.5s ease-in-out",pointerEvents:"none"}}),L.jsx("img",{...E,src:t,loading:"lazy",onLoad:()=>b(!0),style:{display:"block",width:"100%",height:"100%",opacity:i?1:0,transition:"opacity 0.5s ease-in-out",...v}})]})};m.CHARACTERS=H,m.ImageHash=ie,m.ImageHashCanvas=W,m.decode=X,m.decodeBase83=I,m.encode=G,m.encodeBase83=O,m.encodeImage=oe,m.linearToSrgb=P,m.signPow=C,m.srgbToLinear=S,Object.defineProperty(m,Symbol.toStringTag,{value:"Module"})}));
@@ -0,0 +1,478 @@
1
+ import ee, { forwardRef as ie, useRef as ue, useState as fe, useImperativeHandle as de, useEffect as X } from "react";
2
+ const te = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz#$%*+,-.:;=?@[]^_{|}~", C = (r, t) => {
3
+ let s = "";
4
+ for (let c = 1; c <= t; c++) {
5
+ const o = Math.floor(r / Math.pow(83, t - c)) % 83;
6
+ s += te[o];
7
+ }
8
+ return s;
9
+ }, D = (r) => {
10
+ let t = 0;
11
+ for (let s = 0; s < r.length; s++) {
12
+ const c = r[s], o = te.indexOf(c);
13
+ t = t * 83 + o;
14
+ }
15
+ return t;
16
+ }, w = (r) => {
17
+ const t = r / 255;
18
+ return t <= 0.04045 ? t / 12.92 : Math.pow((t + 0.055) / 1.055, 2.4);
19
+ }, O = (r) => {
20
+ const t = Math.max(0, Math.min(1, r));
21
+ return t <= 31308e-7 ? Math.round(t * 12.92 * 255) : Math.round((1.055 * Math.pow(t, 1 / 2.4) - 0.055) * 255);
22
+ }, P = (r, t) => Math.sign(r) * Math.pow(Math.abs(r), t), me = (r, t, s, c = 4, o = 3) => {
23
+ if (c < 1 || c > 9 || o < 1 || o > 9)
24
+ throw new Error("Components must be between 1 and 9");
25
+ const i = [];
26
+ for (let a = 0; a < o; a++)
27
+ for (let l = 0; l < c; l++) {
28
+ const v = (l === 0 ? 1 : 2) * (a === 0 ? 1 : 2);
29
+ let g = 0, T = 0, M = 0;
30
+ for (let x = 0; x < s; x++)
31
+ for (let y = 0; y < t; y++) {
32
+ const A = Math.cos(Math.PI * l * y / t) * Math.cos(Math.PI * a * x / s), S = (x * t + y) * 4;
33
+ g += A * w(r[S]), T += A * w(r[S + 1]), M += A * w(r[S + 2]);
34
+ }
35
+ const h = v / (t * s);
36
+ i.push([g * h, T * h, M * h]);
37
+ }
38
+ const m = i[0], E = i.slice(1);
39
+ let b = "";
40
+ b += C(c - 1 + (o - 1) * 9, 1);
41
+ let p = 1;
42
+ if (E.length > 0) {
43
+ const a = Math.max(...E.map((v) => Math.max(Math.abs(v[0]), Math.abs(v[1]), Math.abs(v[2])))), l = Math.max(0, Math.min(82, Math.floor(a * 166 - 0.5)));
44
+ b += C(l, 1), p = (l + 1) / 166;
45
+ } else
46
+ b += C(0, 1);
47
+ b += C(((a) => {
48
+ const l = O(a[0]), v = O(a[1]), g = O(a[2]);
49
+ return (l << 16) + (v << 8) + g;
50
+ })(m), 4);
51
+ const R = (a, l) => {
52
+ const v = Math.max(0, Math.min(18, Math.floor(P(a[0] / l, 0.5) * 9 + 9.5))), g = Math.max(0, Math.min(18, Math.floor(P(a[1] / l, 0.5) * 9 + 9.5))), T = Math.max(0, Math.min(18, Math.floor(P(a[2] / l, 0.5) * 9 + 9.5)));
53
+ return v * 19 * 19 + g * 19 + T;
54
+ };
55
+ for (const a of E)
56
+ b += C(R(a, p), 2);
57
+ return b;
58
+ }, Re = (r, t = 4, s = 3) => {
59
+ const c = document.createElement("canvas");
60
+ c.width = 32, c.height = 32;
61
+ const o = c.getContext("2d");
62
+ if (!o) throw new Error("Could not create canvas context");
63
+ o.drawImage(r, 0, 0, 32, 32);
64
+ const i = o.getImageData(0, 0, 32, 32);
65
+ return me(i.data, 32, 32, t, s);
66
+ }, be = (r, t, s, c = 1) => {
67
+ if (!r || r.length < 6)
68
+ throw new Error("The hash is invalid.");
69
+ const o = D(r[0]), i = o % 9 + 1, m = Math.floor(o / 9) + 1, b = (D(r[1]) + 1) / 166, p = [], _ = D(r.substring(2, 6));
70
+ p.push([
71
+ w(_ >> 16 & 255),
72
+ w(_ >> 8 & 255),
73
+ w(_ & 255)
74
+ ]);
75
+ for (let a = 1; a < i * m; a++) {
76
+ const l = D(r.substring(6 + (a - 1) * 2, 6 + a * 2));
77
+ p.push([
78
+ P((Math.floor(l / 361) - 9) / 9, 2) * b * c,
79
+ P((Math.floor(l / 19 % 19) - 9) / 9, 2) * b * c,
80
+ P((l % 19 - 9) / 9, 2) * b * c
81
+ ]);
82
+ }
83
+ const R = new Uint8ClampedArray(t * s * 4);
84
+ for (let a = 0; a < s; a++)
85
+ for (let l = 0; l < t; l++) {
86
+ let v = 0, g = 0, T = 0;
87
+ for (let h = 0; h < m; h++)
88
+ for (let x = 0; x < i; x++) {
89
+ const y = Math.cos(Math.PI * x * l / t) * Math.cos(Math.PI * h * a / s), A = p[h * i + x];
90
+ v += A[0] * y, g += A[1] * y, T += A[2] * y;
91
+ }
92
+ const M = (a * t + l) * 4;
93
+ R[M] = O(v), R[M + 1] = O(g), R[M + 2] = O(T), R[M + 3] = 255;
94
+ }
95
+ return R;
96
+ };
97
+ var Y = { exports: {} }, j = {};
98
+ /**
99
+ * @license React
100
+ * react-jsx-runtime.production.js
101
+ *
102
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
103
+ *
104
+ * This source code is licensed under the MIT license found in the
105
+ * LICENSE file in the root directory of this source tree.
106
+ */
107
+ var Z;
108
+ function Ee() {
109
+ if (Z) return j;
110
+ Z = 1;
111
+ var r = Symbol.for("react.transitional.element"), t = Symbol.for("react.fragment");
112
+ function s(c, o, i) {
113
+ var m = null;
114
+ if (i !== void 0 && (m = "" + i), o.key !== void 0 && (m = "" + o.key), "key" in o) {
115
+ i = {};
116
+ for (var E in o)
117
+ E !== "key" && (i[E] = o[E]);
118
+ } else i = o;
119
+ return o = i.ref, {
120
+ $$typeof: r,
121
+ type: c,
122
+ key: m,
123
+ ref: o !== void 0 ? o : null,
124
+ props: i
125
+ };
126
+ }
127
+ return j.Fragment = t, j.jsx = s, j.jsxs = s, j;
128
+ }
129
+ var I = {};
130
+ /**
131
+ * @license React
132
+ * react-jsx-runtime.development.js
133
+ *
134
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
135
+ *
136
+ * This source code is licensed under the MIT license found in the
137
+ * LICENSE file in the root directory of this source tree.
138
+ */
139
+ var Q;
140
+ function ve() {
141
+ return Q || (Q = 1, process.env.NODE_ENV !== "production" && (function() {
142
+ function r(e) {
143
+ if (e == null) return null;
144
+ if (typeof e == "function")
145
+ return e.$$typeof === se ? null : e.displayName || e.name || null;
146
+ if (typeof e == "string") return e;
147
+ switch (e) {
148
+ case T:
149
+ return "Fragment";
150
+ case h:
151
+ return "Profiler";
152
+ case M:
153
+ return "StrictMode";
154
+ case S:
155
+ return "Suspense";
156
+ case ne:
157
+ return "SuspenseList";
158
+ case oe:
159
+ return "Activity";
160
+ }
161
+ if (typeof e == "object")
162
+ switch (typeof e.tag == "number" && console.error(
163
+ "Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."
164
+ ), e.$$typeof) {
165
+ case g:
166
+ return "Portal";
167
+ case y:
168
+ return e.displayName || "Context";
169
+ case x:
170
+ return (e._context.displayName || "Context") + ".Consumer";
171
+ case A:
172
+ var n = e.render;
173
+ return e = e.displayName, e || (e = n.displayName || n.name || "", e = e !== "" ? "ForwardRef(" + e + ")" : "ForwardRef"), e;
174
+ case ae:
175
+ return n = e.displayName || null, n !== null ? n : r(e.type) || "Memo";
176
+ case F:
177
+ n = e._payload, e = e._init;
178
+ try {
179
+ return r(e(n));
180
+ } catch {
181
+ }
182
+ }
183
+ return null;
184
+ }
185
+ function t(e) {
186
+ return "" + e;
187
+ }
188
+ function s(e) {
189
+ try {
190
+ t(e);
191
+ var n = !1;
192
+ } catch {
193
+ n = !0;
194
+ }
195
+ if (n) {
196
+ n = console;
197
+ var u = n.error, f = typeof Symbol == "function" && Symbol.toStringTag && e[Symbol.toStringTag] || e.constructor.name || "Object";
198
+ return u.call(
199
+ n,
200
+ "The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",
201
+ f
202
+ ), t(e);
203
+ }
204
+ }
205
+ function c(e) {
206
+ if (e === T) return "<>";
207
+ if (typeof e == "object" && e !== null && e.$$typeof === F)
208
+ return "<...>";
209
+ try {
210
+ var n = r(e);
211
+ return n ? "<" + n + ">" : "<...>";
212
+ } catch {
213
+ return "<...>";
214
+ }
215
+ }
216
+ function o() {
217
+ var e = q.A;
218
+ return e === null ? null : e.getOwner();
219
+ }
220
+ function i() {
221
+ return Error("react-stack-top-frame");
222
+ }
223
+ function m(e) {
224
+ if (V.call(e, "key")) {
225
+ var n = Object.getOwnPropertyDescriptor(e, "key").get;
226
+ if (n && n.isReactWarning) return !1;
227
+ }
228
+ return e.key !== void 0;
229
+ }
230
+ function E(e, n) {
231
+ function u() {
232
+ z || (z = !0, console.error(
233
+ "%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",
234
+ n
235
+ ));
236
+ }
237
+ u.isReactWarning = !0, Object.defineProperty(e, "key", {
238
+ get: u,
239
+ configurable: !0
240
+ });
241
+ }
242
+ function b() {
243
+ var e = r(this.type);
244
+ return H[e] || (H[e] = !0, console.error(
245
+ "Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release."
246
+ )), e = this.props.ref, e !== void 0 ? e : null;
247
+ }
248
+ function p(e, n, u, f, N, U) {
249
+ var d = u.ref;
250
+ return e = {
251
+ $$typeof: v,
252
+ type: e,
253
+ key: n,
254
+ props: u,
255
+ _owner: f
256
+ }, (d !== void 0 ? d : null) !== null ? Object.defineProperty(e, "ref", {
257
+ enumerable: !1,
258
+ get: b
259
+ }) : Object.defineProperty(e, "ref", { enumerable: !1, value: null }), e._store = {}, Object.defineProperty(e._store, "validated", {
260
+ configurable: !1,
261
+ enumerable: !1,
262
+ writable: !0,
263
+ value: 0
264
+ }), Object.defineProperty(e, "_debugInfo", {
265
+ configurable: !1,
266
+ enumerable: !1,
267
+ writable: !0,
268
+ value: null
269
+ }), Object.defineProperty(e, "_debugStack", {
270
+ configurable: !1,
271
+ enumerable: !1,
272
+ writable: !0,
273
+ value: N
274
+ }), Object.defineProperty(e, "_debugTask", {
275
+ configurable: !1,
276
+ enumerable: !1,
277
+ writable: !0,
278
+ value: U
279
+ }), Object.freeze && (Object.freeze(e.props), Object.freeze(e)), e;
280
+ }
281
+ function _(e, n, u, f, N, U) {
282
+ var d = n.children;
283
+ if (d !== void 0)
284
+ if (f)
285
+ if (ce(d)) {
286
+ for (f = 0; f < d.length; f++)
287
+ R(d[f]);
288
+ Object.freeze && Object.freeze(d);
289
+ } else
290
+ console.error(
291
+ "React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead."
292
+ );
293
+ else R(d);
294
+ if (V.call(n, "key")) {
295
+ d = r(e);
296
+ var k = Object.keys(n).filter(function(le) {
297
+ return le !== "key";
298
+ });
299
+ f = 0 < k.length ? "{key: someKey, " + k.join(": ..., ") + ": ...}" : "{key: someKey}", B[d + f] || (k = 0 < k.length ? "{" + k.join(": ..., ") + ": ...}" : "{}", console.error(
300
+ `A props object containing a "key" prop is being spread into JSX:
301
+ let props = %s;
302
+ <%s {...props} />
303
+ React keys must be passed directly to JSX without using spread:
304
+ let props = %s;
305
+ <%s key={someKey} {...props} />`,
306
+ f,
307
+ d,
308
+ k,
309
+ d
310
+ ), B[d + f] = !0);
311
+ }
312
+ if (d = null, u !== void 0 && (s(u), d = "" + u), m(n) && (s(n.key), d = "" + n.key), "key" in n) {
313
+ u = {};
314
+ for (var W in n)
315
+ W !== "key" && (u[W] = n[W]);
316
+ } else u = n;
317
+ return d && E(
318
+ u,
319
+ typeof e == "function" ? e.displayName || e.name || "Unknown" : e
320
+ ), p(
321
+ e,
322
+ d,
323
+ u,
324
+ o(),
325
+ N,
326
+ U
327
+ );
328
+ }
329
+ function R(e) {
330
+ a(e) ? e._store && (e._store.validated = 1) : typeof e == "object" && e !== null && e.$$typeof === F && (e._payload.status === "fulfilled" ? a(e._payload.value) && e._payload.value._store && (e._payload.value._store.validated = 1) : e._store && (e._store.validated = 1));
331
+ }
332
+ function a(e) {
333
+ return typeof e == "object" && e !== null && e.$$typeof === v;
334
+ }
335
+ var l = ee, v = Symbol.for("react.transitional.element"), g = Symbol.for("react.portal"), T = Symbol.for("react.fragment"), M = Symbol.for("react.strict_mode"), h = Symbol.for("react.profiler"), x = Symbol.for("react.consumer"), y = Symbol.for("react.context"), A = Symbol.for("react.forward_ref"), S = Symbol.for("react.suspense"), ne = Symbol.for("react.suspense_list"), ae = Symbol.for("react.memo"), F = Symbol.for("react.lazy"), oe = Symbol.for("react.activity"), se = Symbol.for("react.client.reference"), q = l.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE, V = Object.prototype.hasOwnProperty, ce = Array.isArray, L = console.createTask ? console.createTask : function() {
336
+ return null;
337
+ };
338
+ l = {
339
+ react_stack_bottom_frame: function(e) {
340
+ return e();
341
+ }
342
+ };
343
+ var z, H = {}, J = l.react_stack_bottom_frame.bind(
344
+ l,
345
+ i
346
+ )(), G = L(c(i)), B = {};
347
+ I.Fragment = T, I.jsx = function(e, n, u) {
348
+ var f = 1e4 > q.recentlyCreatedOwnerStacks++;
349
+ return _(
350
+ e,
351
+ n,
352
+ u,
353
+ !1,
354
+ f ? Error("react-stack-top-frame") : J,
355
+ f ? L(c(e)) : G
356
+ );
357
+ }, I.jsxs = function(e, n, u) {
358
+ var f = 1e4 > q.recentlyCreatedOwnerStacks++;
359
+ return _(
360
+ e,
361
+ n,
362
+ u,
363
+ !0,
364
+ f ? Error("react-stack-top-frame") : J,
365
+ f ? L(c(e)) : G
366
+ );
367
+ };
368
+ })()), I;
369
+ }
370
+ var K;
371
+ function pe() {
372
+ return K || (K = 1, process.env.NODE_ENV === "production" ? Y.exports = Ee() : Y.exports = ve()), Y.exports;
373
+ }
374
+ var $ = pe();
375
+ const re = ie(
376
+ ({ hash: r, width: t = 32, height: s = 32, punch: c = 1, ...o }, i) => {
377
+ const m = ue(null), [E, b] = fe(!1);
378
+ return de(i, () => m.current), X(() => {
379
+ const p = m.current;
380
+ if (!p) return;
381
+ const _ = new IntersectionObserver(
382
+ (R) => {
383
+ R[0].isIntersecting && (b(!0), _.disconnect());
384
+ },
385
+ { rootMargin: "100px" }
386
+ // Start decoding 100px before it enters the screen
387
+ );
388
+ return _.observe(p), () => _.disconnect();
389
+ }, []), X(() => {
390
+ const p = m.current;
391
+ if (!p || !r || !E) return;
392
+ const _ = p.getContext("2d");
393
+ if (!_) return;
394
+ const R = setTimeout(() => {
395
+ try {
396
+ const a = be(r, t, s, c), l = new ImageData(a, t, s);
397
+ _.putImageData(l, 0, 0);
398
+ } catch (a) {
399
+ console.error("Failed to render ImageHash:", a);
400
+ }
401
+ }, 0);
402
+ return () => clearTimeout(R);
403
+ }, [r, t, s, c, E]), /* @__PURE__ */ $.jsx(
404
+ "canvas",
405
+ {
406
+ ref: m,
407
+ width: t,
408
+ height: s,
409
+ style: { imageRendering: "pixelated", ...o.style },
410
+ ...o
411
+ }
412
+ );
413
+ }
414
+ );
415
+ re.displayName = "ImageHashCanvas";
416
+ const ge = ({ hash: r, src: t, className: s, style: c, ...o }) => {
417
+ const [i, m] = ee.useState(!1), { style: E, ...b } = o;
418
+ return /* @__PURE__ */ $.jsxs(
419
+ "div",
420
+ {
421
+ className: s,
422
+ style: {
423
+ position: "relative",
424
+ overflow: "hidden",
425
+ display: "inline-block",
426
+ ...c
427
+ },
428
+ children: [
429
+ /* @__PURE__ */ $.jsx(
430
+ re,
431
+ {
432
+ hash: r,
433
+ style: {
434
+ position: "absolute",
435
+ inset: 0,
436
+ width: "100%",
437
+ height: "100%",
438
+ opacity: i ? 0 : 1,
439
+ transition: "opacity 0.5s ease-in-out",
440
+ pointerEvents: "none"
441
+ // Prevent canvas from blocking right-clicks on the image
442
+ }
443
+ }
444
+ ),
445
+ /* @__PURE__ */ $.jsx(
446
+ "img",
447
+ {
448
+ ...b,
449
+ src: t,
450
+ loading: "lazy",
451
+ onLoad: () => m(!0),
452
+ style: {
453
+ display: "block",
454
+ width: "100%",
455
+ height: "100%",
456
+ opacity: i ? 1 : 0,
457
+ transition: "opacity 0.5s ease-in-out",
458
+ ...E
459
+ }
460
+ }
461
+ )
462
+ ]
463
+ }
464
+ );
465
+ };
466
+ export {
467
+ te as CHARACTERS,
468
+ ge as ImageHash,
469
+ re as ImageHashCanvas,
470
+ be as decode,
471
+ D as decodeBase83,
472
+ me as encode,
473
+ C as encodeBase83,
474
+ Re as encodeImage,
475
+ O as linearToSrgb,
476
+ P as signPow,
477
+ w as srgbToLinear
478
+ };
@@ -0,0 +1,6 @@
1
+ export declare const CHARACTERS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz#$%*+,-.:;=?@[]^_{|}~";
2
+ export declare const encodeBase83: (value: number, length: number) => string;
3
+ export declare const decodeBase83: (str: string) => number;
4
+ export declare const srgbToLinear: (value: number) => number;
5
+ export declare const linearToSrgb: (value: number) => number;
6
+ export declare const signPow: (value: number, exp: number) => number;
package/package.json ADDED
@@ -0,0 +1,60 @@
1
+ {
2
+ "name": "useblysh",
3
+ "version": "1.0.1",
4
+ "description": "High-performance visual hashing for seamless image loading. Encode images into tiny strings and decode into beautiful, fast-loading blurs.",
5
+ "main": "./dist/useblysh.js",
6
+ "module": "./dist/useblysh.mjs",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/useblysh.mjs",
12
+ "require": "./dist/useblysh.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "README.md",
18
+ "LICENSE"
19
+ ],
20
+ "scripts": {
21
+ "build": "vite build",
22
+ "dev": "vite",
23
+ "preview": "vite preview",
24
+ "test": "vitest"
25
+ },
26
+ "repository": {
27
+ "type": "git",
28
+ "url": "https://github.com/R1SH4BH81/Blysh.git"
29
+ },
30
+ "homepage": "https://useblysh.vercel.app",
31
+ "bugs": {
32
+ "url": "https://useblysh.vercel.app/report-issue"
33
+ },
34
+ "peerDependencies": {
35
+ "react": ">=16.8.0",
36
+ "react-dom": ">=16.8.0"
37
+ },
38
+ "devDependencies": {
39
+ "@types/react": "^19.0.0",
40
+ "@types/react-dom": "^19.0.0",
41
+ "@vitejs/plugin-react": "^4.3.4",
42
+ "react": "^19.0.0",
43
+ "react-dom": "^19.0.0",
44
+ "typescript": "^5.0.0",
45
+ "vite": "^6.0.0",
46
+ "vite-plugin-dts": "^4.0.0",
47
+ "vitest": "^2.1.8"
48
+ },
49
+ "keywords": [
50
+ "useblysh",
51
+ "placeholder",
52
+ "progressive-loading",
53
+ "image-performance",
54
+ "react",
55
+ "typescript",
56
+ "nextjs"
57
+ ],
58
+ "author": "Rishabh Mishra <rishabhmishra.81@gmail.com>",
59
+ "license": "MIT"
60
+ }