added backup and email client

This commit is contained in:
2026-02-01 00:02:35 +01:00
parent ef18381dd8
commit 8c9e61cf17
210 changed files with 24211 additions and 742 deletions
+25 -2
View File
@@ -791,8 +791,7 @@
"node_modules/csstype": {
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
"dev": true
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="
},
"node_modules/debug": {
"version": "4.4.3",
@@ -1098,6 +1097,14 @@
"node": ">=10.13.0"
}
},
"node_modules/goober": {
"version": "2.1.18",
"resolved": "https://registry.npmjs.org/goober/-/goober-2.1.18.tgz",
"integrity": "sha512-2vFqsaDVIT9Gz7N6kAL++pLpp41l3PfDuusHcjnGLfR6+huZkl6ziX+zgVC3ZxpqWhzH6pyDdGrCeDhMIvwaxw==",
"peerDependencies": {
"csstype": "^3.0.10"
}
},
"node_modules/gopd": {
"version": "1.2.0",
"resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",
@@ -1664,6 +1671,22 @@
"react": "^16.8.0 || ^17 || ^18 || ^19"
}
},
"node_modules/react-hot-toast": {
"version": "2.6.0",
"resolved": "https://registry.npmjs.org/react-hot-toast/-/react-hot-toast-2.6.0.tgz",
"integrity": "sha512-bH+2EBMZ4sdyou/DPrfgIouFpcRLCJ+HoCA32UoAYHn6T3Ur5yfcDCeSr5mwldl6pFOsiocmrXMuoCJ1vV8bWg==",
"dependencies": {
"csstype": "^3.1.3",
"goober": "^2.1.16"
},
"engines": {
"node": ">=10"
},
"peerDependencies": {
"react": ">=16",
"react-dom": ">=16"
}
},
"node_modules/react-refresh": {
"version": "0.17.0",
"resolved": "https://registry.npmjs.org/react-refresh/-/react-refresh-0.17.0.tgz",
+19 -13
View File
@@ -1,67 +1,73 @@
{
"hash": "eeae1b35",
"hash": "b8db82d9",
"configHash": "c7be2068",
"lockfileHash": "9edb0d4c",
"browserHash": "fe173fb8",
"lockfileHash": "ee9bf28c",
"browserHash": "deb47249",
"optimized": {
"react": {
"src": "../../react/index.js",
"file": "react.js",
"fileHash": "6771d2e5",
"fileHash": "304f33a9",
"needsInterop": true
},
"react-dom": {
"src": "../../react-dom/index.js",
"file": "react-dom.js",
"fileHash": "4b5e071f",
"fileHash": "96d32bc1",
"needsInterop": true
},
"react/jsx-dev-runtime": {
"src": "../../react/jsx-dev-runtime.js",
"file": "react_jsx-dev-runtime.js",
"fileHash": "053f8773",
"fileHash": "6424b7ea",
"needsInterop": true
},
"react/jsx-runtime": {
"src": "../../react/jsx-runtime.js",
"file": "react_jsx-runtime.js",
"fileHash": "5bc5ee39",
"fileHash": "af95a7a1",
"needsInterop": true
},
"@tanstack/react-query": {
"src": "../../@tanstack/react-query/build/modern/index.js",
"file": "@tanstack_react-query.js",
"fileHash": "25a02139",
"fileHash": "c9459c14",
"needsInterop": false
},
"axios": {
"src": "../../axios/index.js",
"file": "axios.js",
"fileHash": "7d1ba6fe",
"fileHash": "032e1913",
"needsInterop": false
},
"lucide-react": {
"src": "../../lucide-react/dist/esm/lucide-react.js",
"file": "lucide-react.js",
"fileHash": "3ebbc663",
"fileHash": "341675db",
"needsInterop": false
},
"react-dom/client": {
"src": "../../react-dom/client.js",
"file": "react-dom_client.js",
"fileHash": "8b0b7734",
"fileHash": "6520a32f",
"needsInterop": true
},
"react-hook-form": {
"src": "../../react-hook-form/dist/index.esm.mjs",
"file": "react-hook-form.js",
"fileHash": "d05e0352",
"fileHash": "29e58164",
"needsInterop": false
},
"react-router-dom": {
"src": "../../react-router-dom/dist/index.js",
"file": "react-router-dom.js",
"fileHash": "0c95dc90",
"fileHash": "4b5d4fdc",
"needsInterop": false
},
"react-hot-toast": {
"src": "../../react-hot-toast/dist/index.mjs",
"file": "react-hot-toast.js",
"fileHash": "7423c32d",
"needsInterop": false
}
},
+486
View File
@@ -0,0 +1,486 @@
"use client";
import {
require_react
} from "./chunk-3TFVT2CW.js";
import {
__toESM
} from "./chunk-4MBMRILA.js";
// node_modules/react-hot-toast/dist/index.mjs
var import_react = __toESM(require_react(), 1);
var import_react2 = __toESM(require_react(), 1);
var y = __toESM(require_react(), 1);
// node_modules/goober/dist/goober.modern.js
var e = { data: "" };
var t = (t2) => {
if ("object" == typeof window) {
let e2 = (t2 ? t2.querySelector("#_goober") : window._goober) || Object.assign(document.createElement("style"), { innerHTML: " ", id: "_goober" });
return e2.nonce = window.__nonce__, e2.parentNode || (t2 || document.head).appendChild(e2), e2.firstChild;
}
return t2 || e;
};
var l = /(?:([\u0080-\uFFFF\w-%@]+) *:? *([^{;]+?);|([^;}{]*?) *{)|(}\s*)/g;
var a = /\/\*[^]*?\*\/| +/g;
var n = /\n+/g;
var o = (e2, t2) => {
let r = "", l2 = "", a2 = "";
for (let n3 in e2) {
let c2 = e2[n3];
"@" == n3[0] ? "i" == n3[1] ? r = n3 + " " + c2 + ";" : l2 += "f" == n3[1] ? o(c2, n3) : n3 + "{" + o(c2, "k" == n3[1] ? "" : t2) + "}" : "object" == typeof c2 ? l2 += o(c2, t2 ? t2.replace(/([^,])+/g, (e3) => n3.replace(/([^,]*:\S+\([^)]*\))|([^,])+/g, (t3) => /&/.test(t3) ? t3.replace(/&/g, e3) : e3 ? e3 + " " + t3 : t3)) : n3) : null != c2 && (n3 = /^--/.test(n3) ? n3 : n3.replace(/[A-Z]/g, "-$&").toLowerCase(), a2 += o.p ? o.p(n3, c2) : n3 + ":" + c2 + ";");
}
return r + (t2 && a2 ? t2 + "{" + a2 + "}" : a2) + l2;
};
var c = {};
var s = (e2) => {
if ("object" == typeof e2) {
let t2 = "";
for (let r in e2) t2 += r + s(e2[r]);
return t2;
}
return e2;
};
var i = (e2, t2, r, i2, p2) => {
let u2 = s(e2), d2 = c[u2] || (c[u2] = ((e3) => {
let t3 = 0, r2 = 11;
for (; t3 < e3.length; ) r2 = 101 * r2 + e3.charCodeAt(t3++) >>> 0;
return "go" + r2;
})(u2));
if (!c[d2]) {
let t3 = u2 !== e2 ? e2 : ((e3) => {
let t4, r2, o2 = [{}];
for (; t4 = l.exec(e3.replace(a, "")); ) t4[4] ? o2.shift() : t4[3] ? (r2 = t4[3].replace(n, " ").trim(), o2.unshift(o2[0][r2] = o2[0][r2] || {})) : o2[0][t4[1]] = t4[2].replace(n, " ").trim();
return o2[0];
})(e2);
c[d2] = o(p2 ? { ["@keyframes " + d2]: t3 } : t3, r ? "" : "." + d2);
}
let f3 = r && c.g ? c.g : null;
return r && (c.g = c[d2]), ((e3, t3, r2, l2) => {
l2 ? t3.data = t3.data.replace(l2, e3) : -1 === t3.data.indexOf(e3) && (t3.data = r2 ? e3 + t3.data : t3.data + e3);
})(c[d2], t2, i2, f3), d2;
};
var p = (e2, t2, r) => e2.reduce((e3, l2, a2) => {
let n3 = t2[a2];
if (n3 && n3.call) {
let e4 = n3(r), t3 = e4 && e4.props && e4.props.className || /^go/.test(e4) && e4;
n3 = t3 ? "." + t3 : e4 && "object" == typeof e4 ? e4.props ? "" : o(e4, "") : false === e4 ? "" : e4;
}
return e3 + l2 + (null == n3 ? "" : n3);
}, "");
function u(e2) {
let r = this || {}, l2 = e2.call ? e2(r.p) : e2;
return i(l2.unshift ? l2.raw ? p(l2, [].slice.call(arguments, 1), r.p) : l2.reduce((e3, t2) => Object.assign(e3, t2 && t2.call ? t2(r.p) : t2), {}) : l2, t(r.target), r.g, r.o, r.k);
}
var d;
var f;
var g;
var b = u.bind({ g: 1 });
var h = u.bind({ k: 1 });
function m(e2, t2, r, l2) {
o.p = t2, d = e2, f = r, g = l2;
}
function w(e2, t2) {
let r = this || {};
return function() {
let l2 = arguments;
function a2(n3, o2) {
let c2 = Object.assign({}, n3), s2 = c2.className || a2.className;
r.p = Object.assign({ theme: f && f() }, c2), r.o = / *go\d+/.test(s2), c2.className = u.apply(r, l2) + (s2 ? " " + s2 : ""), t2 && (c2.ref = o2);
let i2 = e2;
return e2[0] && (i2 = c2.as || e2, delete c2.as), g && i2[0] && g(c2), d(i2, c2);
}
return t2 ? t2(a2) : a2;
};
}
// node_modules/react-hot-toast/dist/index.mjs
var b2 = __toESM(require_react(), 1);
var x = __toESM(require_react(), 1);
var Z = (e2) => typeof e2 == "function";
var h2 = (e2, t2) => Z(e2) ? e2(t2) : e2;
var W = /* @__PURE__ */ (() => {
let e2 = 0;
return () => (++e2).toString();
})();
var E = /* @__PURE__ */ (() => {
let e2;
return () => {
if (e2 === void 0 && typeof window < "u") {
let t2 = matchMedia("(prefers-reduced-motion: reduce)");
e2 = !t2 || t2.matches;
}
return e2;
};
})();
var re = 20;
var k = "default";
var H = (e2, t2) => {
let { toastLimit: o2 } = e2.settings;
switch (t2.type) {
case 0:
return { ...e2, toasts: [t2.toast, ...e2.toasts].slice(0, o2) };
case 1:
return { ...e2, toasts: e2.toasts.map((r) => r.id === t2.toast.id ? { ...r, ...t2.toast } : r) };
case 2:
let { toast: s2 } = t2;
return H(e2, { type: e2.toasts.find((r) => r.id === s2.id) ? 1 : 0, toast: s2 });
case 3:
let { toastId: a2 } = t2;
return { ...e2, toasts: e2.toasts.map((r) => r.id === a2 || a2 === void 0 ? { ...r, dismissed: true, visible: false } : r) };
case 4:
return t2.toastId === void 0 ? { ...e2, toasts: [] } : { ...e2, toasts: e2.toasts.filter((r) => r.id !== t2.toastId) };
case 5:
return { ...e2, pausedAt: t2.time };
case 6:
let i2 = t2.time - (e2.pausedAt || 0);
return { ...e2, pausedAt: void 0, toasts: e2.toasts.map((r) => ({ ...r, pauseDuration: r.pauseDuration + i2 })) };
}
};
var v = [];
var j = { toasts: [], pausedAt: void 0, settings: { toastLimit: re } };
var f2 = {};
var Y = (e2, t2 = k) => {
f2[t2] = H(f2[t2] || j, e2), v.forEach(([o2, s2]) => {
o2 === t2 && s2(f2[t2]);
});
};
var _ = (e2) => Object.keys(f2).forEach((t2) => Y(e2, t2));
var Q = (e2) => Object.keys(f2).find((t2) => f2[t2].toasts.some((o2) => o2.id === e2));
var S = (e2 = k) => (t2) => {
Y(t2, e2);
};
var se = { blank: 4e3, error: 4e3, success: 2e3, loading: 1 / 0, custom: 4e3 };
var V = (e2 = {}, t2 = k) => {
let [o2, s2] = (0, import_react.useState)(f2[t2] || j), a2 = (0, import_react.useRef)(f2[t2]);
(0, import_react.useEffect)(() => (a2.current !== f2[t2] && s2(f2[t2]), v.push([t2, s2]), () => {
let r = v.findIndex(([l2]) => l2 === t2);
r > -1 && v.splice(r, 1);
}), [t2]);
let i2 = o2.toasts.map((r) => {
var l2, g2, T;
return { ...e2, ...e2[r.type], ...r, removeDelay: r.removeDelay || ((l2 = e2[r.type]) == null ? void 0 : l2.removeDelay) || (e2 == null ? void 0 : e2.removeDelay), duration: r.duration || ((g2 = e2[r.type]) == null ? void 0 : g2.duration) || (e2 == null ? void 0 : e2.duration) || se[r.type], style: { ...e2.style, ...(T = e2[r.type]) == null ? void 0 : T.style, ...r.style } };
});
return { ...o2, toasts: i2 };
};
var ie = (e2, t2 = "blank", o2) => ({ createdAt: Date.now(), visible: true, dismissed: false, type: t2, ariaProps: { role: "status", "aria-live": "polite" }, message: e2, pauseDuration: 0, ...o2, id: (o2 == null ? void 0 : o2.id) || W() });
var P = (e2) => (t2, o2) => {
let s2 = ie(t2, e2, o2);
return S(s2.toasterId || Q(s2.id))({ type: 2, toast: s2 }), s2.id;
};
var n2 = (e2, t2) => P("blank")(e2, t2);
n2.error = P("error");
n2.success = P("success");
n2.loading = P("loading");
n2.custom = P("custom");
n2.dismiss = (e2, t2) => {
let o2 = { type: 3, toastId: e2 };
t2 ? S(t2)(o2) : _(o2);
};
n2.dismissAll = (e2) => n2.dismiss(void 0, e2);
n2.remove = (e2, t2) => {
let o2 = { type: 4, toastId: e2 };
t2 ? S(t2)(o2) : _(o2);
};
n2.removeAll = (e2) => n2.remove(void 0, e2);
n2.promise = (e2, t2, o2) => {
let s2 = n2.loading(t2.loading, { ...o2, ...o2 == null ? void 0 : o2.loading });
return typeof e2 == "function" && (e2 = e2()), e2.then((a2) => {
let i2 = t2.success ? h2(t2.success, a2) : void 0;
return i2 ? n2.success(i2, { id: s2, ...o2, ...o2 == null ? void 0 : o2.success }) : n2.dismiss(s2), a2;
}).catch((a2) => {
let i2 = t2.error ? h2(t2.error, a2) : void 0;
i2 ? n2.error(i2, { id: s2, ...o2, ...o2 == null ? void 0 : o2.error }) : n2.dismiss(s2);
}), e2;
};
var ce = 1e3;
var w2 = (e2, t2 = "default") => {
let { toasts: o2, pausedAt: s2 } = V(e2, t2), a2 = (0, import_react2.useRef)(/* @__PURE__ */ new Map()).current, i2 = (0, import_react2.useCallback)((c2, m2 = ce) => {
if (a2.has(c2)) return;
let p2 = setTimeout(() => {
a2.delete(c2), r({ type: 4, toastId: c2 });
}, m2);
a2.set(c2, p2);
}, []);
(0, import_react2.useEffect)(() => {
if (s2) return;
let c2 = Date.now(), m2 = o2.map((p2) => {
if (p2.duration === 1 / 0) return;
let R = (p2.duration || 0) + p2.pauseDuration - (c2 - p2.createdAt);
if (R < 0) {
p2.visible && n2.dismiss(p2.id);
return;
}
return setTimeout(() => n2.dismiss(p2.id, t2), R);
});
return () => {
m2.forEach((p2) => p2 && clearTimeout(p2));
};
}, [o2, s2, t2]);
let r = (0, import_react2.useCallback)(S(t2), [t2]), l2 = (0, import_react2.useCallback)(() => {
r({ type: 5, time: Date.now() });
}, [r]), g2 = (0, import_react2.useCallback)((c2, m2) => {
r({ type: 1, toast: { id: c2, height: m2 } });
}, [r]), T = (0, import_react2.useCallback)(() => {
s2 && r({ type: 6, time: Date.now() });
}, [s2, r]), d2 = (0, import_react2.useCallback)((c2, m2) => {
let { reverseOrder: p2 = false, gutter: R = 8, defaultPosition: z } = m2 || {}, O = o2.filter((u2) => (u2.position || z) === (c2.position || z) && u2.height), K = O.findIndex((u2) => u2.id === c2.id), B = O.filter((u2, I) => I < K && u2.visible).length;
return O.filter((u2) => u2.visible).slice(...p2 ? [B + 1] : [0, B]).reduce((u2, I) => u2 + (I.height || 0) + R, 0);
}, [o2]);
return (0, import_react2.useEffect)(() => {
o2.forEach((c2) => {
if (c2.dismissed) i2(c2.id, c2.removeDelay);
else {
let m2 = a2.get(c2.id);
m2 && (clearTimeout(m2), a2.delete(c2.id));
}
});
}, [o2, i2]), { toasts: o2, handlers: { updateHeight: g2, startPause: l2, endPause: T, calculateOffset: d2 } };
};
var de = h`
from {
transform: scale(0) rotate(45deg);
opacity: 0;
}
to {
transform: scale(1) rotate(45deg);
opacity: 1;
}`;
var me = h`
from {
transform: scale(0);
opacity: 0;
}
to {
transform: scale(1);
opacity: 1;
}`;
var le = h`
from {
transform: scale(0) rotate(90deg);
opacity: 0;
}
to {
transform: scale(1) rotate(90deg);
opacity: 1;
}`;
var C = w("div")`
width: 20px;
opacity: 0;
height: 20px;
border-radius: 10px;
background: ${(e2) => e2.primary || "#ff4b4b"};
position: relative;
transform: rotate(45deg);
animation: ${de} 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275)
forwards;
animation-delay: 100ms;
&:after,
&:before {
content: '';
animation: ${me} 0.15s ease-out forwards;
animation-delay: 150ms;
position: absolute;
border-radius: 3px;
opacity: 0;
background: ${(e2) => e2.secondary || "#fff"};
bottom: 9px;
left: 4px;
height: 2px;
width: 12px;
}
&:before {
animation: ${le} 0.15s ease-out forwards;
animation-delay: 180ms;
transform: rotate(90deg);
}
`;
var Te = h`
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
`;
var F = w("div")`
width: 12px;
height: 12px;
box-sizing: border-box;
border: 2px solid;
border-radius: 100%;
border-color: ${(e2) => e2.secondary || "#e0e0e0"};
border-right-color: ${(e2) => e2.primary || "#616161"};
animation: ${Te} 1s linear infinite;
`;
var ge = h`
from {
transform: scale(0) rotate(45deg);
opacity: 0;
}
to {
transform: scale(1) rotate(45deg);
opacity: 1;
}`;
var he = h`
0% {
height: 0;
width: 0;
opacity: 0;
}
40% {
height: 0;
width: 6px;
opacity: 1;
}
100% {
opacity: 1;
height: 10px;
}`;
var L = w("div")`
width: 20px;
opacity: 0;
height: 20px;
border-radius: 10px;
background: ${(e2) => e2.primary || "#61d345"};
position: relative;
transform: rotate(45deg);
animation: ${ge} 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275)
forwards;
animation-delay: 100ms;
&:after {
content: '';
box-sizing: border-box;
animation: ${he} 0.2s ease-out forwards;
opacity: 0;
animation-delay: 200ms;
position: absolute;
border-right: 2px solid;
border-bottom: 2px solid;
border-color: ${(e2) => e2.secondary || "#fff"};
bottom: 6px;
left: 6px;
height: 10px;
width: 6px;
}
`;
var be = w("div")`
position: absolute;
`;
var Se = w("div")`
position: relative;
display: flex;
justify-content: center;
align-items: center;
min-width: 20px;
min-height: 20px;
`;
var Ae = h`
from {
transform: scale(0.6);
opacity: 0.4;
}
to {
transform: scale(1);
opacity: 1;
}`;
var Pe = w("div")`
position: relative;
transform: scale(0.6);
opacity: 0.4;
min-width: 20px;
animation: ${Ae} 0.3s 0.12s cubic-bezier(0.175, 0.885, 0.32, 1.275)
forwards;
`;
var $ = ({ toast: e2 }) => {
let { icon: t2, type: o2, iconTheme: s2 } = e2;
return t2 !== void 0 ? typeof t2 == "string" ? b2.createElement(Pe, null, t2) : t2 : o2 === "blank" ? null : b2.createElement(Se, null, b2.createElement(F, { ...s2 }), o2 !== "loading" && b2.createElement(be, null, o2 === "error" ? b2.createElement(C, { ...s2 }) : b2.createElement(L, { ...s2 })));
};
var Re = (e2) => `
0% {transform: translate3d(0,${e2 * -200}%,0) scale(.6); opacity:.5;}
100% {transform: translate3d(0,0,0) scale(1); opacity:1;}
`;
var Ee = (e2) => `
0% {transform: translate3d(0,0,-1px) scale(1); opacity:1;}
100% {transform: translate3d(0,${e2 * -150}%,-1px) scale(.6); opacity:0;}
`;
var ve = "0%{opacity:0;} 100%{opacity:1;}";
var De = "0%{opacity:1;} 100%{opacity:0;}";
var Oe = w("div")`
display: flex;
align-items: center;
background: #fff;
color: #363636;
line-height: 1.3;
will-change: transform;
box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1), 0 3px 3px rgba(0, 0, 0, 0.05);
max-width: 350px;
pointer-events: auto;
padding: 8px 10px;
border-radius: 8px;
`;
var Ie = w("div")`
display: flex;
justify-content: center;
margin: 4px 10px;
color: inherit;
flex: 1 1 auto;
white-space: pre-line;
`;
var ke = (e2, t2) => {
let s2 = e2.includes("top") ? 1 : -1, [a2, i2] = E() ? [ve, De] : [Re(s2), Ee(s2)];
return { animation: t2 ? `${h(a2)} 0.35s cubic-bezier(.21,1.02,.73,1) forwards` : `${h(i2)} 0.4s forwards cubic-bezier(.06,.71,.55,1)` };
};
var N = y.memo(({ toast: e2, position: t2, style: o2, children: s2 }) => {
let a2 = e2.height ? ke(e2.position || t2 || "top-center", e2.visible) : { opacity: 0 }, i2 = y.createElement($, { toast: e2 }), r = y.createElement(Ie, { ...e2.ariaProps }, h2(e2.message, e2));
return y.createElement(Oe, { className: e2.className, style: { ...a2, ...o2, ...e2.style } }, typeof s2 == "function" ? s2({ icon: i2, message: r }) : y.createElement(y.Fragment, null, i2, r));
});
m(x.createElement);
var we = ({ id: e2, className: t2, style: o2, onHeightUpdate: s2, children: a2 }) => {
let i2 = x.useCallback((r) => {
if (r) {
let l2 = () => {
let g2 = r.getBoundingClientRect().height;
s2(e2, g2);
};
l2(), new MutationObserver(l2).observe(r, { subtree: true, childList: true, characterData: true });
}
}, [e2, s2]);
return x.createElement("div", { ref: i2, className: t2, style: o2 }, a2);
};
var Me = (e2, t2) => {
let o2 = e2.includes("top"), s2 = o2 ? { top: 0 } : { bottom: 0 }, a2 = e2.includes("center") ? { justifyContent: "center" } : e2.includes("right") ? { justifyContent: "flex-end" } : {};
return { left: 0, right: 0, display: "flex", position: "absolute", transition: E() ? void 0 : "all 230ms cubic-bezier(.21,1.02,.73,1)", transform: `translateY(${t2 * (o2 ? 1 : -1)}px)`, ...s2, ...a2 };
};
var Ce = u`
z-index: 9999;
> * {
pointer-events: auto;
}
`;
var D = 16;
var Fe = ({ reverseOrder: e2, position: t2 = "top-center", toastOptions: o2, gutter: s2, children: a2, toasterId: i2, containerStyle: r, containerClassName: l2 }) => {
let { toasts: g2, handlers: T } = w2(o2, i2);
return x.createElement("div", { "data-rht-toaster": i2 || "", style: { position: "fixed", zIndex: 9999, top: D, left: D, right: D, bottom: D, pointerEvents: "none", ...r }, className: l2, onMouseEnter: T.startPause, onMouseLeave: T.endPause }, g2.map((d2) => {
let c2 = d2.position || t2, m2 = T.calculateOffset(d2, { reverseOrder: e2, gutter: s2, defaultPosition: t2 }), p2 = Me(c2, m2);
return x.createElement(we, { id: d2.id, key: d2.id, onHeightUpdate: T.updateHeight, className: d2.visible ? Ce : "", style: p2 }, d2.type === "custom" ? h2(d2.message, d2) : a2 ? a2(d2) : x.createElement(N, { toast: d2, position: c2 }));
}));
};
var zt = n2;
export {
L as CheckmarkIcon,
C as ErrorIcon,
F as LoaderIcon,
N as ToastBar,
$ as ToastIcon,
Fe as Toaster,
zt as default,
h2 as resolveValue,
n2 as toast,
w2 as useToaster,
V as useToasterStore
};
//# sourceMappingURL=react-hot-toast.js.map
File diff suppressed because one or more lines are too long
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2019 Cristian Bote
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+857
View File
@@ -0,0 +1,857 @@
<p align="center">
<img src="./goober_cover.png" width="500" alt="goober" />
</p>
🥜 goober, a less than 1KB css-in-js solution.
[![Backers on Open Collective](https://opencollective.com/goober/backers/badge.svg)](#backers)
[![Sponsors on Open Collective](https://opencollective.com/goober/sponsors/badge.svg)](#sponsors)
[![version](https://img.shields.io/npm/v/goober)](https://www.npmjs.com/package/goober)
[![status](https://travis-ci.org/cristianbote/goober.svg?branch=master)](https://travis-ci.org/cristianbote/goober)
[![gzip size](https://img.badgesize.io/https://unpkg.com/goober@latest/dist/goober.modern.js?compression=gzip)](https://unpkg.com/goober)
[![downloads](https://img.shields.io/npm/dm/goober)](https://www.npmjs.com/package/goober)
[![coverage](https://img.shields.io/codecov/c/github/cristianbote/goober.svg?maxAge=2592000)](https://codecov.io/github/cristianbote/goober?branch=master)
[![Slack](https://img.shields.io/badge/slack-join-orange)](https://join.slack.com/t/gooberdev/shared_invite/enQtOTM5NjUyOTcwNzI1LWUwNzg0NTQwODY1NDJmMzQ2NzdlODI4YTM3NWUwYjlkY2ZkNGVmMTFlNGMwZGUyOWQyZmI4OTYwYmRiMzE0NGQ)
# 🪒 The Great Shave Off Challenge
Can you shave off bytes from goober? Do it and you're gonna get paid! [More info here](https://goober.rocks/the-great-shave-off)
# Motivation
I've always wondered if you could get a working solution for css-in-js with a smaller footprint. While I was working on a side project I wanted to use styled-components, or more accurately the `styled` pattern. Looking at the JavaScript bundle sizes, I quickly realized that I would have to include ~12kB([styled-components](https://github.com/styled-components/styled-components)) or ~11kB([emotion](https://github.com/emotion-js/emotion)) just so I can use the `styled` paradigm. So, I embarked on a mission to create a smaller alternative for these well established APIs.
# Why the peanuts emoji?
It's a pun on the tagline.
> css-in-js at the cost of peanuts!
> 🥜goober
# Talks and Podcasts
* [React Round Up](https://reactroundup.com/wrangle-your-css-in-js-for-peanuts-using-goober-ft-cristian-bote-rru-177) 👉 https://reactroundup.com/wrangle-your-css-in-js-for-peanuts-using-goober-ft-cristian-bote-rru-177
* ReactDay Berlin 2019 👉 https://www.youtube.com/watch?v=k4-AVy3acqk
* [PodRocket](https://podrocket.logrocket.com/) by [LogRocket](https://logrocket.com/) 👉 https://podrocket.logrocket.com/goober
* [ngParty](https://www.ngparty.cz/) 👉 https://www.youtube.com/watch?v=XKFvOBDPeB0
# Table of contents
- [Usage](#usage)
- [Examples](#examples)
- [Tradeoffs](#comparison-and-tradeoffs)
- [SSR](#ssr)
- [Benchmarks](#benchmarks)
- [Browser](#browser)
- [SSR](#ssr-1)
- [API](#api)
- [styled](#styledtagname-string--function-forwardref-function)
- [setup](#setuppragma-function-prefixer-function-theme-function-forwardprops-function)
- [With prefixer](#with-prefixer)
- [With theme](#with-theme)
- [With forwardProps](#with-forwardProps)
- [css](#csstaggedtemplate)
- [targets](#targets)
- [extractCss](#extractcsstarget)
- [createGlobalStyles](#createglobalstyles)
- [keyframes](#keyframes)
- [shouldForwardProp](#shouldForwardProp)
- [Integrations](#integrations)
- [Babel Plugin](#babel-plugin)
- [Babel Macro Plugin](#babel-macro-plugin)
- [Next.js](#nextjs)
- [Gatsby](#gatsby)
- [Preact CLI Plugin](#preact-cli-plugin)
- [CSS Prop](#css-prop)
- [Features](#features)
- [Sharing Style](#sharing-style)
- [Autoprefixer](#autoprefixer)
- [TypeScript](#typescript)
- [Content Security Policy (CSP)](#content-security-policy-csp)-
- [Browser Support](#browser-support)
- [Contributing](#contributing)
# Usage
The API is inspired by emotion `styled` function. Meaning, you call it with your `tagName`, and it returns a vDOM component for that tag. Note, `setup` needs to be ran before the `styled` function is used.
```jsx
import { h } from 'preact';
import { styled, setup } from 'goober';
// Should be called here, and just once
setup(h);
const Icon = styled('span')`
display: flex;
flex: 1;
color: red;
`;
const Button = styled('button')`
background: dodgerblue;
color: white;
border: ${Math.random()}px solid white;
&:focus,
&:hover {
padding: 1em;
}
.otherClass {
margin: 0;
}
${Icon} {
color: black;
}
`;
```
# Examples
- [Vanilla](https://codesandbox.io/s/qlywyp7z4q)
- [React](https://codesandbox.io/s/k0mnp40n7v)
- [Preact](https://codesandbox.io/s/r15wj2qm7o)
- [SSR with Preact](https://codesandbox.io/s/7m9zzl6746)
- [Fre](https://codesandbox.io/s/fre-goober-ffqjv)
# Comparison and tradeoffs
In this section I would like to compare goober, as objectively as I can, with the latest versions of two most well known css-in-js packages: styled-components and emotion.
I've used the following markers to reflect the state of each feature:
- ✅ Supported
- 🟡 Partially supported
- 🛑 Not supported
Here we go:
| Feature name | Goober | Styled Components | Emotion |
| ---------------------- | ------- | ----------------- | ------- |
| Base bundle size | 1.25 kB | 12.6 kB | 7.4 kB |
| Framework agnostic | ✅ | 🛑 | 🛑 |
| Render with target \*1 | ✅ | 🛑 | 🛑 |
| `css` api | ✅ | ✅ | ✅ |
| `css` prop | ✅ | ✅ | ✅ |
| `styled` | ✅ | ✅ | ✅ |
| `styled.<tag>` | ✅ \*2 | ✅ | ✅ |
| default export | 🛑 | ✅ | ✅ |
| `as` | ✅ | ✅ | ✅ |
| `.withComponent` | 🛑 | ✅ | ✅ |
| `.attrs` | 🛑 | ✅ | 🛑 |
| `shouldForwardProp` | ✅ | ✅ | ✅ |
| `keyframes` | ✅ | ✅ | ✅ |
| Labels | 🛑 | 🛑 | ✅ |
| ClassNames | 🛑 | 🛑 | ✅ |
| Global styles | ✅ | ✅ | ✅ |
| SSR | ✅ | ✅ | ✅ |
| Theming | ✅ | ✅ | ✅ |
| Tagged Templates | ✅ | ✅ | ✅ |
| Object styles | ✅ | ✅ | ✅ |
| Dynamic styles | ✅ | ✅ | ✅ |
Footnotes
- [1] `goober` can render in _any_ dom target. Meaning you can use `goober` to define scoped styles in any context. Really useful for web-components.
- [2] Supported only via `babel-plugin-transform-goober`
# SSR
You can get the critical CSS for SSR via `extractCss`. Take a look at this example: [CodeSandbox: SSR with Preact and goober](https://codesandbox.io/s/7m9zzl6746) and read the full explanation for `extractCSS` and `targets` below.
# Benchmarks
The results are included inside the build output as well.
## Browser
Coming soon!
## SSR
The benchmark is testing the following scenario:
```jsx
import styled from '<packageName>';
// Create the dynamic styled component
const Foo = styled('div')((props) => ({
opacity: props.counter > 0.5 ? 1 : 0,
'@media (min-width: 1px)': {
rule: 'all'
},
'&:hover': {
another: 1,
display: 'space'
}
}));
// Serialize the component
renderToString(<Foo counter={Math.random()} />);
```
The results are:
```
goober x 200,437 ops/sec ±1.93% (87 runs sampled)
styled-components@5.2.1 x 12,650 ops/sec ±9.09% (48 runs sampled)
emotion@11.0.0 x 104,229 ops/sec ±2.06% (88 runs sampled)
Fastest is: goober
```
# API
As you can see, goober supports most of the CSS syntax. If you find any issues, please submit a ticket, or open a PR with a fix.
### `styled(tagName: String | Function, forwardRef?: Function)`
- `@param {String|Function} tagName` The name of the DOM element you'd like the styles to be applied to
- `@param {Function} forwardRef` Forward ref function. Usually `React.forwardRef`
- `@returns {Function}` Returns the tag template function.
```js
import { styled } from 'goober';
const Btn = styled('button')`
border-radius: 4px;
`;
```
#### Different ways of customizing the styles
##### Tagged templates functions
```js
import { styled } from 'goober';
const Btn = styled('button')`
border-radius: ${(props) => props.size}px;
`;
<Btn size={20} />;
```
##### Function that returns a string
```js
import { styled } from 'goober';
const Btn = styled('button')(
(props) => `
border-radius: ${props.size}px;
`
);
<Btn size={20} />;
```
##### JSON/Object
```js
import { styled } from 'goober';
const Btn = styled('button')((props) => ({
borderRadius: props.size + 'px'
}));
<Btn size={20} />;
```
##### Arrays
```js
import { styled } from 'goober';
const Btn = styled('button')([
{ color: 'tomato' },
({ isPrimary }) => ({ background: isPrimary ? 'cyan' : 'gray' })
]);
<Btn />; // This will render the `Button` with `background: gray;`
<Btn isPrimary />; // This will render the `Button` with `background: cyan;`
```
##### Forward ref function
As goober is JSX library agnostic, you need to pass in the forward ref function for the library you are using. Here's how you do it for React.
```js
const Title = styled('h1', React.forwardRef)`
font-weight: bold;
color: dodgerblue;
`;
```
### `setup(pragma: Function, prefixer?: Function, theme?: Function, forwardProps?: Function)`
The call to `setup()` should occur only once. It should be called in the entry file of your project.
Given the fact that `react` uses `createElement` for the transformed elements and `preact` uses `h`, `setup` should be called with the proper _pragma_ function. This was added to reduce the bundled size and being able to bundle an esmodule version. At the moment, it's the best tradeoff I can think of.
```js
import React from 'react';
import { setup } from 'goober';
setup(React.createElement);
```
#### With prefixer
```js
import React from 'react';
import { setup } from 'goober';
const customPrefixer = (key, value) => `${key}: ${value};\n`;
setup(React.createElement, customPrefixer);
```
#### With theme
```js
import React, { createContext, useContext, createElement } from 'react';
import { setup, styled } from 'goober';
const theme = { primary: 'blue' };
const ThemeContext = createContext(theme);
const useTheme = () => useContext(ThemeContext);
setup(createElement, undefined, useTheme);
const ContainerWithTheme = styled('div')`
color: ${(props) => props.theme.primary};
`;
```
#### With forwardProps
The `forwardProps` function offers a way to achieve the same `shouldForwardProps` functionality as emotion and styled-components (with transient props) offer. The difference here is that the function receives the whole props and you are in charge of removing the props that should not end up in the DOM.
This is a super useful functionality when paired with theme object, variants, or any other customisation one might need.
```js
import React from 'react';
import { setup, styled } from 'goober';
setup(React.createElement, undefined, undefined, (props) => {
for (let prop in props) {
// Or any other conditions.
// This could also check if this is a dev build and not remove the props
if (prop === 'size') {
delete props[prop];
}
}
});
```
The functionality of "transient props" (with a "\$" prefix) can be implemented as follows:
```js
import React from 'react';
import { setup, styled } from 'goober';
setup(React.createElement, undefined, undefined, (props) => {
for (let prop in props) {
if (prop[0] === '$') {
delete props[prop];
}
}
});
```
Alternatively you can use `goober/should-forward-prop` addon to pass only the filter function and not have to deal with the full `props` object.
```js
import React from 'react';
import { setup, styled } from 'goober';
import { shouldForwardProp } from 'goober/should-forward-prop';
setup(
React.createElement,
undefined,
undefined,
// This package accepts a `filter` function. If you return false that prop
// won't be included in the forwarded props.
shouldForwardProp((prop) => {
return prop !== 'size';
})
);
```
### `css(taggedTemplate)`
- `@returns {String}` Returns the className.
To create a className, you need to call `css` with your style rules in a tagged template.
```js
import { css } from "goober";
const BtnClassName = css`
border-radius: 4px;
`;
// vanilla JS
const btn = document.querySelector("#btn");
// BtnClassName === 'g016232'
btn.classList.add(BtnClassName);
// JSX
// BtnClassName === 'g016232'
const App => <button className={BtnClassName}>click</button>
```
#### Different ways of customizing `css`
##### Passing props to `css` tagged templates
```js
import { css } from 'goober';
// JSX
const CustomButton = (props) => (
<button
className={css`
border-radius: ${props.size}px;
`}
>
click
</button>
);
```
##### Using `css` with JSON/Object
```js
import { css } from 'goober';
const BtnClassName = (props) =>
css({
background: props.color,
borderRadius: props.radius + 'px'
});
```
**Notice:** using `css` with object can reduce your bundle size.
We can also declare styles at the top of the file by wrapping `css` into a function that we call to get the className.
```js
import { css } from 'goober';
const BtnClassName = (props) => css`
border-radius: ${props.size}px;
`;
// vanilla JS
// BtnClassName({size:20}) -> g016360
const btn = document.querySelector('#btn');
btn.classList.add(BtnClassName({ size: 20 }));
// JSX
// BtnClassName({size:20}) -> g016360
const App = () => <button className={BtnClassName({ size: 20 })}>click</button>;
```
The difference between calling `css` directly and wrapping into a function is the timing of its execution. The former is when the component(file) is imported, the latter is when it is actually rendered.
If you use `extractCSS` for SSR, you may prefer to use the latter, or the `styled` API to avoid inconsistent results.
### `targets`
By default, goober will append a style tag to the `<head>` of a document. You might want to target a different node, for instance, when you want to use goober with web components (so you'd want it to append style tags to individual shadowRoots). For this purpose, you can `.bind` a new target to the `styled` and `css` methods:
```js
import * as goober from 'goober';
const target = document.getElementById('target');
const css = goober.css.bind({ target: target });
const styled = goober.styled.bind({ target: target });
```
If you don't provide a target, goober always defaults to `<head>` and in environments without a DOM (think certain SSR solutions), it will just use a plain string cache to store generated styles which you can extract with `extractCSS`(see below).
### `extractCss(target?)`
- `@returns {String}`
Returns the `<style>` tag that is rendered in a target and clears the style sheet. Defaults to `<head>`.
```js
const { extractCss } = require('goober');
// After your app has rendered, just call it:
const styleTag = `<style id="_goober">${extractCss()}</style>`;
// Note: To be able to `hydrate` the styles you should use the proper `id` so `goober` can pick it up and use it as the target from now on
```
### `createGlobalStyles`
To define your global styles you need to create a `GlobalStyles` component and use it as part of your tree. The `createGlobalStyles` is available at `goober/global` addon.
```js
import { createGlobalStyles } from 'goober/global';
const GlobalStyles = createGlobalStyles`
html,
body {
background: light;
}
* {
box-sizing: border-box;
}
`;
export default function App() {
return (
<div id="root">
<GlobalStyles />
<Navigation>
<RestOfYourApp>
</div>
)
}
```
#### How about using `glob` function directly?
Before the global addon, `goober/global`, there was a method named `glob` that was part of the main package that would do the same thing, more or less. Having only that method to define global styles usually led to missing global styles from the extracted css, since the pattern did not enforce the evaluation of the styles at render time. The `glob` method is still exported from `goober/global`, in case you have a hard dependency on it. It still has the same API:
```js
import { glob } from 'goober';
glob`
html,
body {
background: light;
}
* {
box-sizing: border-box;
}
`;
```
### `keyframes`
`keyframes` is a helpful method to define reusable animations that can be decoupled from the main style declaration and shared across components.
```js
import { keyframes } from 'goober';
const rotate = keyframes`
from, to {
transform: rotate(0deg);
}
50% {
transform: rotate(180deg);
}
`;
const Wicked = styled('div')`
background: tomato;
color: white;
animation: ${rotate} 1s ease-in-out;
`;
```
### `shouldForwardProp`
To implement the `shouldForwardProp` without the need to provide the full loop over `props` you can use the `goober/should-forward-prop` addon.
```js
import { h } from 'preact';
import { setup } from 'goober';
import { shouldForwardProp } from 'goober/should-forward-prop';
setup(
h,
undefined,
undefined,
shouldForwardProp((prop) => {
// Do NOT forward props that start with `$` symbol
return prop['0'] !== '$';
})
);
```
# Integrations
## Babel plugin
You're in love with the `styled.div` syntax? Fear no more! We got you covered with a babel plugin that will take your lovely syntax from `styled.tag` and translate it to goober's `styled("tag")` call.
```sh
npm i --save-dev babel-plugin-transform-goober
# or
yarn add --dev babel-plugin-transform-goober
```
Visit the package in here for more info (https://github.com/cristianbote/goober/tree/master/packages/babel-plugin-transform-goober)
## Babel macro plugin
A babel-plugin-macros macro for [🥜goober][goober], rewriting `styled.div` syntax to `styled('div')` calls.
### Usage
Once you've configured [babel-plugin-macros](https://github.com/kentcdodds/babel-plugin-macros), change your imports from `goober` to `goober/macro`.
Now you can create your components using `styled.*` syntax:.
```js
import { styled } from 'goober/macro';
const Button = styled.button`
margin: 0;
padding: 1rem;
font-size: 1rem;
background-color: tomato;
`;
```
## [Next.js](https://github.com/vercel/next.js)
Want to use `goober` with Next.js? We've got you covered! Follow the example below or from the main [examples](https://github.com/vercel/next.js/tree/canary/examples/with-goober) directory.
```sh
npx create-next-app --example with-goober with-goober-app
# or
yarn create next-app --example with-goober with-goober-app
```
## [Gatsby](https://github.com/gatsbyjs/gatsby)
Want to use `goober` with Gatsby? We've got you covered! We have our own plugin to deal with styling your Gatsby projects.
```sh
npm i --save goober gatsby-plugin-goober
# or
yarn add goober gatsby-plugin-goober
```
## Preact CLI plugin
If you use Goober with Preact CLI, you can use [preact-cli-goober-ssr](https://github.com/gerhardsletten/preact-cli-goober-ssr)
```sh
npm i --save-dev preact-cli-goober-ssr
# or
yarn add --dev preact-cli-goober-ssr
# preact.config.js
const gooberPlugin = require('preact-cli-goober-ssr')
export default (config, env) => {
gooberPlugin(config, env)
}
```
When you build your Preact application, this will run `extractCss` on your pre-rendered pages and add critical styles for each page.
## CSS Prop
You can use a custom `css` prop to pass in styles on HTML elements with this Babel plugin.
Installation:
```sh
npm install --save-dev @agney/babel-plugin-goober-css-prop
```
List the plugin in `.babelrc`:
```
{
"plugins": [
"@agney/babel-plugin-goober-css-prop"
]
}
```
Usage:
```javascript
<main
css={`
display: flex;
min-height: 100vh;
justify-content: center;
align-items: center;
`}
>
<h1 css="color: dodgerblue">Goober</h1>
</main>
```
# Features
- [x] Basic CSS parsing
- [x] Nested rules with pseudo selectors
- [x] Nested styled components
- [x] [Extending Styles](#sharing-style)
- [x] Media queries (@media)
- [x] Keyframes (@keyframes)
- [x] Smart (lazy) client-side hydration
- [x] Styling any component
- via `` const Btn = ({className}) => {...}; const TomatoBtn = styled(Btn)`color: tomato;` ``
- [x] Vanilla (via `css` function)
- [x] `globalStyle` (via `glob`) so one would be able to create global styles
- [x] target/extract from elements other than `<head>`
- [x] [vendor prefixing](#autoprefixer)
# Content Security Policy (CSP)
goober supports Content Security Policy nonces for inline styles. Set `window.__nonce__` before loading the library:
```js
<script nonce="your-nonce-here">
window.__nonce__ = 'your-nonce-here';
</script>
```
The nonce will be added to goober's `<style>` element.
# Sharing style
There are a couple of ways to effectively share/extend styles across components.
## Extending
You can extend the desired component that needs to be enriched or overwritten with another set of css rules.
```js
import { styled } from 'goober';
// Let's declare a primitive for our styled component
const Primitive = styled('span')`
margin: 0;
padding: 0;
`;
// Later on we could get the primitive shared styles and also add our owns
const Container = styled(Primitive)`
padding: 1em;
`;
```
## Using `as` prop
Another helpful way to extend a certain component is with the `as` property. Given our example above we could modify it like:
```jsx
import { styled } from 'goober';
// Our primitive element
const Primitive = styled('span')`
margin: 0;
padding: 0;
`;
const Container = styled('div')`
padding: 1em;
`;
// At composition/render time
<Primitive as={'div'} /> // <div class="go01234" />
// Or using the `Container`
<Primitive as={Container} /> // <div class="go01234 go56789" />
```
# Autoprefixer
Autoprefixing is a helpful way to make sure the generated css will work seamlessly on the whole spectrum of browsers. With that in mind, the core `goober` package can't hold that logic to determine the autoprefixing needs, so we added a new package that you can choose to address them.
```sh
npm install goober
# or
yarn add goober
```
After the main package is installed it's time to bootstrap goober with it:
```js
import { setup } from 'goober';
import { prefix } from 'goober/prefixer';
// Bootstrap goober
setup(React.createElement, prefix);
```
And voilà! It is done!
# TypeScript
`goober` comes with type definitions build in, making it easy to get started in TypeScript straight away.
## Prop Types
If you're using custom props and wish to style based on them, you can do so as follows:
```ts
interface Props {
size: number;
}
styled('div')<Props>`
border-radius: ${(props) => props.size}px;
`;
// This also works!
styled<Props>('div')`
border-radius: ${(props) => props.size}px;
`;
```
## Extending Theme
If you're using a [custom theme](../api/setup.md#with-theme) and want to add types to it, you can create a declaration file at the base of your project.
```ts
// goober.d.t.s
import 'goober';
declare module 'goober' {
export interface DefaultTheme {
colors: {
primary: string;
};
}
}
```
You should now have autocompletion for your theme.
```ts
const ThemeContainer = styled('div')`
background-color: ${(props) => props.theme.colors.primary};
`;
```
# Browser support
`goober` supports all major browsers (Chrome, Edge, Firefox, Safari).
To support IE 11 and older browsers, make sure to use a tool like [Babel](https://babeljs.io/) to transform your code into code that works in the browsers you target.
# Contributing
Feel free to try it out and checkout the examples. If you wanna fix something feel free to open a issue or a PR.
## Backers
Thank you to all our backers! 🙏
<a href="https://opencollective.com/goober#backers" target="_blank"><img src="https://opencollective.com/goober/backers.svg?width=890"></a>
## Sponsors
Support this project by becoming a sponsor. Your logo will show up here with a link to your website.
<a href="https://opencollective.com/goober#sponsors" target="_blank"><img src="https://opencollective.com/goober/sponsors.svg?width=890"></a>
+1
View File
@@ -0,0 +1 @@
let e={data:""},t=t=>{if("object"==typeof window){let e=(t?t.querySelector("#_goober"):window._goober)||Object.assign(document.createElement("style"),{innerHTML:" ",id:"_goober"});return e.nonce=window.__nonce__,e.parentNode||(t||document.head).appendChild(e),e.firstChild}return t||e},r=/(?:([\u0080-\uFFFF\w-%@]+) *:? *([^{;]+?);|([^;}{]*?) *{)|(}\s*)/g,l=/\/\*[^]*?\*\/| +/g,a=/\n+/g,n=(e,t)=>{let r="",l="",a="";for(let o in e){let s=e[o];"@"==o[0]?"i"==o[1]?r=o+" "+s+";":l+="f"==o[1]?n(s,o):o+"{"+n(s,"k"==o[1]?"":t)+"}":"object"==typeof s?l+=n(s,t?t.replace(/([^,])+/g,e=>o.replace(/([^,]*:\S+\([^)]*\))|([^,])+/g,t=>/&/.test(t)?t.replace(/&/g,e):e?e+" "+t:t)):o):null!=s&&(o=/^--/.test(o)?o:o.replace(/[A-Z]/g,"-$&").toLowerCase(),a+=n.p?n.p(o,s):o+":"+s+";")}return r+(t&&a?t+"{"+a+"}":a)+l},o={},s=e=>{if("object"==typeof e){let t="";for(let r in e)t+=r+s(e[r]);return t}return e},c=(e,t,c,p,i)=>{let u=s(e),d=o[u]||(o[u]=(e=>{let t=0,r=11;for(;t<e.length;)r=101*r+e.charCodeAt(t++)>>>0;return"go"+r})(u));if(!o[d]){let t=u!==e?e:(e=>{let t,n,o=[{}];for(;t=r.exec(e.replace(l,""));)t[4]?o.shift():t[3]?(n=t[3].replace(a," ").trim(),o.unshift(o[0][n]=o[0][n]||{})):o[0][t[1]]=t[2].replace(a," ").trim();return o[0]})(e);o[d]=n(i?{["@keyframes "+d]:t}:t,c?"":"."+d)}let f=c&&o.g?o.g:null;return c&&(o.g=o[d]),((e,t,r,l)=>{l?t.data=t.data.replace(l,e):-1===t.data.indexOf(e)&&(t.data=r?e+t.data:t.data+e)})(o[d],t,p,f),d},p=(e,t,r)=>e.reduce((e,l,a)=>{let o=t[a];if(o&&o.call){let e=o(r),t=e&&e.props&&e.props.className||/^go/.test(e)&&e;o=t?"."+t:e&&"object"==typeof e?e.props?"":n(e,""):!1===e?"":e}return e+l+(null==o?"":o)},"");function i(e){let r=this||{},l=e.call?e(r.p):e;return c(l.unshift?l.raw?p(l,[].slice.call(arguments,1),r.p):l.reduce((e,t)=>Object.assign(e,t&&t.call?t(r.p):t),{}):l,t(r.target),r.g,r.o,r.k)}let u,d,f,g=i.bind({g:1}),b=i.bind({k:1});exports.css=i,exports.extractCss=e=>{let r=t(e),l=r.data;return r.data="",l},exports.glob=g,exports.keyframes=b,exports.setup=function(e,t,r,l){n.p=t,u=e,d=r,f=l},exports.styled=function(e,t){let r=this||{};return function(){let l=arguments;function a(n,o){let s=Object.assign({},n),c=s.className||a.className;r.p=Object.assign({theme:d&&d()},s),r.o=/ *go\d+/.test(c),s.className=i.apply(r,l)+(c?" "+c:""),t&&(s.ref=o);let p=e;return e[0]&&(p=s.as||e,delete s.as),f&&p[0]&&f(s),u(p,s)}return t?t(a):a}};
+1
View File
@@ -0,0 +1 @@
let e={data:""},t=t=>{if("object"==typeof window){let e=(t?t.querySelector("#_goober"):window._goober)||Object.assign(document.createElement("style"),{innerHTML:" ",id:"_goober"});return e.nonce=window.__nonce__,e.parentNode||(t||document.head).appendChild(e),e.firstChild}return t||e},r=e=>{let r=t(e),l=r.data;return r.data="",l},l=/(?:([\u0080-\uFFFF\w-%@]+) *:? *([^{;]+?);|([^;}{]*?) *{)|(}\s*)/g,a=/\/\*[^]*?\*\/| +/g,n=/\n+/g,o=(e,t)=>{let r="",l="",a="";for(let n in e){let c=e[n];"@"==n[0]?"i"==n[1]?r=n+" "+c+";":l+="f"==n[1]?o(c,n):n+"{"+o(c,"k"==n[1]?"":t)+"}":"object"==typeof c?l+=o(c,t?t.replace(/([^,])+/g,e=>n.replace(/([^,]*:\S+\([^)]*\))|([^,])+/g,t=>/&/.test(t)?t.replace(/&/g,e):e?e+" "+t:t)):n):null!=c&&(n=/^--/.test(n)?n:n.replace(/[A-Z]/g,"-$&").toLowerCase(),a+=o.p?o.p(n,c):n+":"+c+";")}return r+(t&&a?t+"{"+a+"}":a)+l},c={},s=e=>{if("object"==typeof e){let t="";for(let r in e)t+=r+s(e[r]);return t}return e},i=(e,t,r,i,p)=>{let u=s(e),d=c[u]||(c[u]=(e=>{let t=0,r=11;for(;t<e.length;)r=101*r+e.charCodeAt(t++)>>>0;return"go"+r})(u));if(!c[d]){let t=u!==e?e:(e=>{let t,r,o=[{}];for(;t=l.exec(e.replace(a,""));)t[4]?o.shift():t[3]?(r=t[3].replace(n," ").trim(),o.unshift(o[0][r]=o[0][r]||{})):o[0][t[1]]=t[2].replace(n," ").trim();return o[0]})(e);c[d]=o(p?{["@keyframes "+d]:t}:t,r?"":"."+d)}let f=r&&c.g?c.g:null;return r&&(c.g=c[d]),((e,t,r,l)=>{l?t.data=t.data.replace(l,e):-1===t.data.indexOf(e)&&(t.data=r?e+t.data:t.data+e)})(c[d],t,i,f),d},p=(e,t,r)=>e.reduce((e,l,a)=>{let n=t[a];if(n&&n.call){let e=n(r),t=e&&e.props&&e.props.className||/^go/.test(e)&&e;n=t?"."+t:e&&"object"==typeof e?e.props?"":o(e,""):!1===e?"":e}return e+l+(null==n?"":n)},"");function u(e){let r=this||{},l=e.call?e(r.p):e;return i(l.unshift?l.raw?p(l,[].slice.call(arguments,1),r.p):l.reduce((e,t)=>Object.assign(e,t&&t.call?t(r.p):t),{}):l,t(r.target),r.g,r.o,r.k)}let d,f,g,b=u.bind({g:1}),h=u.bind({k:1});function m(e,t,r,l){o.p=t,d=e,f=r,g=l}function w(e,t){let r=this||{};return function(){let l=arguments;function a(n,o){let c=Object.assign({},n),s=c.className||a.className;r.p=Object.assign({theme:f&&f()},c),r.o=/ *go\d+/.test(s),c.className=u.apply(r,l)+(s?" "+s:""),t&&(c.ref=o);let i=e;return e[0]&&(i=c.as||e,delete c.as),g&&i[0]&&g(c),d(i,c)}return t?t(a):a}}export{u as css,r as extractCss,b as glob,h as keyframes,m as setup,w as styled};
+1
View File
@@ -0,0 +1 @@
let e={data:""},t=t=>{if("object"==typeof window){let e=(t?t.querySelector("#_goober"):window._goober)||Object.assign(document.createElement("style"),{innerHTML:" ",id:"_goober"});return e.nonce=window.__nonce__,e.parentNode||(t||document.head).appendChild(e),e.firstChild}return t||e},r=e=>{let r=t(e),l=r.data;return r.data="",l},l=/(?:([\u0080-\uFFFF\w-%@]+) *:? *([^{;]+?);|([^;}{]*?) *{)|(}\s*)/g,a=/\/\*[^]*?\*\/| +/g,n=/\n+/g,o=(e,t)=>{let r="",l="",a="";for(let n in e){let c=e[n];"@"==n[0]?"i"==n[1]?r=n+" "+c+";":l+="f"==n[1]?o(c,n):n+"{"+o(c,"k"==n[1]?"":t)+"}":"object"==typeof c?l+=o(c,t?t.replace(/([^,])+/g,e=>n.replace(/([^,]*:\S+\([^)]*\))|([^,])+/g,t=>/&/.test(t)?t.replace(/&/g,e):e?e+" "+t:t)):n):null!=c&&(n=/^--/.test(n)?n:n.replace(/[A-Z]/g,"-$&").toLowerCase(),a+=o.p?o.p(n,c):n+":"+c+";")}return r+(t&&a?t+"{"+a+"}":a)+l},c={},s=e=>{if("object"==typeof e){let t="";for(let r in e)t+=r+s(e[r]);return t}return e},i=(e,t,r,i,p)=>{let u=s(e),d=c[u]||(c[u]=(e=>{let t=0,r=11;for(;t<e.length;)r=101*r+e.charCodeAt(t++)>>>0;return"go"+r})(u));if(!c[d]){let t=u!==e?e:(e=>{let t,r,o=[{}];for(;t=l.exec(e.replace(a,""));)t[4]?o.shift():t[3]?(r=t[3].replace(n," ").trim(),o.unshift(o[0][r]=o[0][r]||{})):o[0][t[1]]=t[2].replace(n," ").trim();return o[0]})(e);c[d]=o(p?{["@keyframes "+d]:t}:t,r?"":"."+d)}let f=r&&c.g?c.g:null;return r&&(c.g=c[d]),((e,t,r,l)=>{l?t.data=t.data.replace(l,e):-1===t.data.indexOf(e)&&(t.data=r?e+t.data:t.data+e)})(c[d],t,i,f),d},p=(e,t,r)=>e.reduce((e,l,a)=>{let n=t[a];if(n&&n.call){let e=n(r),t=e&&e.props&&e.props.className||/^go/.test(e)&&e;n=t?"."+t:e&&"object"==typeof e?e.props?"":o(e,""):!1===e?"":e}return e+l+(null==n?"":n)},"");function u(e){let r=this||{},l=e.call?e(r.p):e;return i(l.unshift?l.raw?p(l,[].slice.call(arguments,1),r.p):l.reduce((e,t)=>Object.assign(e,t&&t.call?t(r.p):t),{}):l,t(r.target),r.g,r.o,r.k)}let d,f,g,b=u.bind({g:1}),h=u.bind({k:1});function m(e,t,r,l){o.p=t,d=e,f=r,g=l}function w(e,t){let r=this||{};return function(){let l=arguments;function a(n,o){let c=Object.assign({},n),s=c.className||a.className;r.p=Object.assign({theme:f&&f()},c),r.o=/ *go\d+/.test(s),c.className=u.apply(r,l)+(s?" "+s:""),t&&(c.ref=o);let i=e;return e[0]&&(i=c.as||e,delete c.as),g&&i[0]&&g(c),d(i,c)}return t?t(a):a}}export{u as css,r as extractCss,b as glob,h as keyframes,m as setup,w as styled};
+1
View File
@@ -0,0 +1 @@
!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e||self).goober={})}(this,function(e){let t={data:""},r=e=>{if("object"==typeof window){let t=(e?e.querySelector("#_goober"):window._goober)||Object.assign(document.createElement("style"),{innerHTML:" ",id:"_goober"});return t.nonce=window.__nonce__,t.parentNode||(e||document.head).appendChild(t),t.firstChild}return e||t},n=/(?:([\u0080-\uFFFF\w-%@]+) *:? *([^{;]+?);|([^;}{]*?) *{)|(}\s*)/g,l=/\/\*[^]*?\*\/| +/g,o=/\n+/g,a=(e,t)=>{let r="",n="",l="";for(let o in e){let s=e[o];"@"==o[0]?"i"==o[1]?r=o+" "+s+";":n+="f"==o[1]?a(s,o):o+"{"+a(s,"k"==o[1]?"":t)+"}":"object"==typeof s?n+=a(s,t?t.replace(/([^,])+/g,e=>o.replace(/([^,]*:\S+\([^)]*\))|([^,])+/g,t=>/&/.test(t)?t.replace(/&/g,e):e?e+" "+t:t)):o):null!=s&&(o=/^--/.test(o)?o:o.replace(/[A-Z]/g,"-$&").toLowerCase(),l+=a.p?a.p(o,s):o+":"+s+";")}return r+(t&&l?t+"{"+l+"}":l)+n},s={},c=e=>{if("object"==typeof e){let t="";for(let r in e)t+=r+c(e[r]);return t}return e},i=(e,t,r,i,f)=>{let d=c(e),p=s[d]||(s[d]=(e=>{let t=0,r=11;for(;t<e.length;)r=101*r+e.charCodeAt(t++)>>>0;return"go"+r})(d));if(!s[p]){let t=d!==e?e:(e=>{let t,r,a=[{}];for(;t=n.exec(e.replace(l,""));)t[4]?a.shift():t[3]?(r=t[3].replace(o," ").trim(),a.unshift(a[0][r]=a[0][r]||{})):a[0][t[1]]=t[2].replace(o," ").trim();return a[0]})(e);s[p]=a(f?{["@keyframes "+p]:t}:t,r?"":"."+p)}let u=r&&s.g?s.g:null;return r&&(s.g=s[p]),((e,t,r,n)=>{n?t.data=t.data.replace(n,e):-1===t.data.indexOf(e)&&(t.data=r?e+t.data:t.data+e)})(s[p],t,i,u),p},f=(e,t,r)=>e.reduce((e,n,l)=>{let o=t[l];if(o&&o.call){let e=o(r),t=e&&e.props&&e.props.className||/^go/.test(e)&&e;o=t?"."+t:e&&"object"==typeof e?e.props?"":a(e,""):!1===e?"":e}return e+n+(null==o?"":o)},"");function d(e){let t=this||{},n=e.call?e(t.p):e;return i(n.unshift?n.raw?f(n,[].slice.call(arguments,1),t.p):n.reduce((e,r)=>Object.assign(e,r&&r.call?r(t.p):r),{}):n,r(t.target),t.g,t.o,t.k)}let p,u,g,b=d.bind({g:1}),h=d.bind({k:1});e.css=d,e.extractCss=e=>{let t=r(e),n=t.data;return t.data="",n},e.glob=b,e.keyframes=h,e.setup=function(e,t,r,n){a.p=t,p=e,u=r,g=n},e.styled=function(e,t){let r=this||{};return function(){let n=arguments;function l(o,a){let s=Object.assign({},o),c=s.className||l.className;r.p=Object.assign({theme:u&&u()},s),r.o=/ *go\d+/.test(c),s.className=d.apply(r,n)+(c?" "+c:""),t&&(s.ref=a);let i=e;return e[0]&&(i=s.as||e,delete s.as),g&&i[0]&&g(s),p(i,s)}return t?t(l):l}}});
+1
View File
@@ -0,0 +1 @@
var l=require("goober");let e=l.css.bind({g:1});exports.createGlobalStyles=function(){const e=l.styled.call({g:1},"div").apply(null,arguments);return function(l){return e(l),null}},exports.glob=e;
+1
View File
@@ -0,0 +1 @@
import{css as n,styled as l}from"goober";let o=n.bind({g:1});function r(){const n=l.call({g:1},"div").apply(null,arguments);return function(l){return n(l),null}}export{r as createGlobalStyles,o as glob};
+1
View File
@@ -0,0 +1 @@
import{css as n,styled as l}from"goober";let o=n.bind({g:1});function r(){const n=l.call({g:1},"div").apply(null,arguments);return function(l){return n(l),null}}export{r as createGlobalStyles,o as glob};
+1
View File
@@ -0,0 +1 @@
!function(e,o){"object"==typeof exports&&"undefined"!=typeof module?o(exports,require("goober")):"function"==typeof define&&define.amd?define(["exports","goober"],o):o((e||self).gooberGlobal={},e.goober)}(this,function(e,o){let n=o.css.bind({g:1});e.createGlobalStyles=function(){const e=o.styled.call({g:1},"div").apply(null,arguments);return function(o){return e(o),null}},e.glob=n});
+25
View File
@@ -0,0 +1,25 @@
import { Properties as CSSProperties } from 'csstype';
import { Theme, DefaultTheme } from 'goober';
export = gooberGlobal;
export as namespace gooberGlobal;
declare namespace gooberGlobal {
interface CSSAttribute extends CSSProperties {
[key: string]: CSSAttribute | string | number | undefined;
}
function createGlobalStyles(
tag: CSSAttribute | TemplateStringsArray | string,
...props: Array<
| string
| number
| ((props: Theme<DefaultTheme>) => CSSAttribute | string | number | false | undefined)
>
): Function;
function glob(
tag: CSSAttribute | TemplateStringsArray | string,
...props: Array<string | number>
): void;
}
+42
View File
@@ -0,0 +1,42 @@
{
"name": "goober-global",
"amdName": "gooberGlobal",
"version": "0.0.1",
"description": "The createGlobalStyles addon function for goober",
"sideEffects": false,
"main": "dist/goober-global.cjs",
"module": "dist/goober-global.esm.js",
"umd:main": "dist/goober-global.umd.js",
"source": "src/index.js",
"unpkg": "dist/goober-global.umd.js",
"types": "./global.d.ts",
"type": "module",
"scripts": {
"build": "rm -rf dist && microbundle --entry src/index.js --name gooberGlobal --no-sourcemap --generateTypes false",
"test": "jest"
},
"repository": {
"type": "git",
"url": "https://github.com/cristianbote/goober.git",
"directory": "global"
},
"author": "Cristian <botecristian@yahoo.com>",
"keywords": [
"goober",
"styled",
"global"
],
"license": "MIT",
"peerDependencies": {
"goober": "^2.0.29"
},
"devDependencies": {
"goober": "^2.0.29",
"microbundle": "^0.14.2",
"jest": "^24.1.0",
"preact": "^10.5.6",
"@babel/plugin-transform-react-jsx": "^7.7.0",
"@babel/preset-env": "^7.3.1",
"babel-jest": "^24.1.0"
}
}
@@ -0,0 +1,9 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`createGlobalStyles regular 1`] = `" html, body{background:dodgerblue;}"`;
exports[`createGlobalStyles regular 2`] = `"<div></div>"`;
exports[`createGlobalStyles with theme 1`] = `"html, body{margin:0;background:blue;}"`;
exports[`createGlobalStyles with theme 2`] = `"<div></div>"`;
+22
View File
@@ -0,0 +1,22 @@
import { glob, createGlobalStyles } from '../index';
import { css, setup } from 'goober';
jest.mock('goober', () => ({
css: jest.fn().mockReturnValue('css()')
}));
describe('global', () => {
beforeEach(() => {
css.mockClear();
});
it('type', () => {
expect(typeof glob).toEqual('function');
expect(typeof createGlobalStyles).toEqual('function');
});
it('glob', () => {
glob`a:b`;
expect(css).toBeCalledWith(['a:b']);
});
});
+56
View File
@@ -0,0 +1,56 @@
import { h, createContext, render } from 'preact';
import { useContext } from 'preact/hooks';
import { setup, extractCss } from 'goober';
import { createGlobalStyles } from '../index';
describe('createGlobalStyles', () => {
it('regular', () => {
setup(h);
const target = document.createElement('div');
const GlobalStyle = createGlobalStyles`
html, body {
background: dodgerblue;
}
`;
render(
<div>
<GlobalStyle />
</div>,
target
);
expect(extractCss()).toMatchSnapshot();
expect(target.innerHTML).toMatchSnapshot();
});
it('with theme', () => {
const ThemeContext = createContext();
const useTheme = () => useContext(ThemeContext);
setup(h, null, useTheme);
const target = document.createElement('div');
const GlobalStyle = createGlobalStyles`
html, body {
margin: 0;
background: ${(props) => props.theme.color};
}
`;
render(
<ThemeContext.Provider value={{ color: 'blue' }}>
<div>
<GlobalStyle />
</div>
</ThemeContext.Provider>,
target
);
expect(extractCss()).toMatchSnapshot();
expect(target.innerHTML).toMatchSnapshot();
});
});
+26
View File
@@ -0,0 +1,26 @@
import { css, styled } from 'goober';
/**
* CSS Global function to declare global styles
* @type {Function}
*/
export let glob = css.bind({ g: 1 });
/**
* Creates the global styles component to be used as part of your tree.
* @returns {Function}
*/
export function createGlobalStyles() {
const fn = styled.call({ g: 1 }, 'div').apply(null, arguments);
/**
* This is the actual component that gets rendered.
*/
return function GlobalStyles(props) {
// Call the above styled.
fn(props);
// Returns a hole.
return null;
};
}
+101
View File
@@ -0,0 +1,101 @@
import { Properties as CSSProperties } from 'csstype';
export = goober;
export as namespace goober;
declare namespace goober {
interface DefaultTheme {}
type Theme<T extends object> = keyof T extends never ? T : { theme: T };
interface StyledFunction {
// used when creating a styled component from a native HTML element
<T extends keyof React.JSX.IntrinsicElements, P extends Object = {}>(
tag: T,
forwardRef?: ForwardRefFunction
): Tagged<
React.JSX.LibraryManagedAttributes<T, React.JSX.IntrinsicElements[T]> &
P &
Theme<DefaultTheme>
>;
// used to extend other styled components. Inherits props from the extended component
<PP extends Object = {}, P extends Object = {}>(
tag: StyledVNode<PP>,
forwardRef?: ForwardRefFunction
): Tagged<PP & P & Theme<DefaultTheme>>;
// used when creating a component from a string (html native) but using a non HTML standard
// component, such as when you want to style web components
<P extends Object = {}>(tag: string): Tagged<
P & Partial<React.JSX.ElementChildrenAttribute>
>;
// used to create a styled component from a JSX element (both functional and class-based)
<T extends React.JSX.Element | React.JSX.ElementClass, P extends Object = {}>(
tag: T,
forwardRef?: ForwardRefFunction
): Tagged<P>;
}
// used when creating a styled component from a native HTML element with the babel-plugin-transform-goober parser
type BabelPluginTransformGooberStyledFunction = {
[T in keyof React.JSX.IntrinsicElements]: Tagged<
React.JSX.LibraryManagedAttributes<T, React.JSX.IntrinsicElements[T]> &
Theme<DefaultTheme>
>;
};
type ForwardRefFunction = {
(props: any, ref: any): any;
};
type ForwardPropsFunction = (props: object) => void;
const styled: StyledFunction & BabelPluginTransformGooberStyledFunction;
function setup<T>(
val: T,
prefixer?: (key: string, val: any) => string,
theme?: Function,
forwardProps?: ForwardPropsFunction
): void;
function extractCss(target?: Element): string;
function glob(
tag: CSSAttribute | TemplateStringsArray | string,
...props: Array<string | number>
): void;
function css(
tag: CSSAttribute | TemplateStringsArray | string,
...props: Array<string | number>
): string;
function keyframes(
tag: CSSAttribute | TemplateStringsArray | string,
...props: Array<string | number>
): string;
type StyledVNode<T> = ((props: T, ...args: any[]) => any) & {
defaultProps?: T;
displayName?: string;
};
type StylesGenerator<P extends Object = {}> = (props: P) => CSSAttribute | string;
type Tagged<P extends Object = {}> = <PP extends Object = { as?: any }>(
tag:
| CSSAttribute
| (CSSAttribute | StylesGenerator<P & PP>)[]
| TemplateStringsArray
| string
| StylesGenerator<P & PP>,
...props: Array<
| string
| number
| ((props: P & PP) => CSSAttribute | string | number | false | undefined)
>
) => StyledVNode<Omit<P & PP, keyof Theme<DefaultTheme>>>;
interface CSSAttribute extends CSSProperties {
[key: string]: CSSAttribute | string | number | undefined | null;
}
}
+43
View File
@@ -0,0 +1,43 @@
const { createMacro, MacroError } = require('babel-plugin-macros');
const { addNamed } = require('@babel/helper-module-imports');
module.exports = createMacro(gooberMacro);
function gooberMacro({ references, babel, state }) {
const program = state.file.path;
if (references.default) {
throw new MacroError('goober.macro does not support default import');
}
// Inject import {...} from 'goober'
Object.keys(references).forEach((refName) => {
const id = addNamed(program, refName, 'goober');
references[refName].forEach((referencePath) => {
referencePath.node.name = id.name;
});
});
const t = babel.types;
const styledReferences = references.styled || [];
styledReferences.forEach((referencePath) => {
const type = referencePath.parentPath.type;
if (type === 'MemberExpression') {
const node = referencePath.parentPath.node;
const functionName = node.object.name;
let elementName = node.property.name;
// Support custom elements
if (/[A-Z]/.test(elementName)) {
elementName = elementName.replace(/[A-Z]/g, '-$&').toLowerCase();
}
referencePath.parentPath.replaceWith(
t.callExpression(t.identifier(functionName), [t.stringLiteral(elementName)])
);
}
});
}
+22
View File
@@ -0,0 +1,22 @@
{
"name": "goober.macro",
"version": "1.0.0",
"description": "A babel macro for goober, rewriting styled.div to styled('div') calls",
"main": "index.js",
"repository": {
"type": "git",
"url": "https://github.com/cristianbote/goober.git",
"directory": "macro"
},
"author": "Hadeeb Farhan <hadeebfarhan1@gmail.com>",
"keywords": [
"babel-plugin-macros",
"goober",
"styled"
],
"license": "MIT",
"peerDependencies": {
"@babel/helper-module-imports": "^7.8.3",
"babel-plugin-macros": "^2.8.0"
}
}
+154
View File
@@ -0,0 +1,154 @@
{
"name": "goober",
"version": "2.1.18",
"description": "A less than 1KB css-in-js solution",
"sideEffects": false,
"main": "dist/goober.cjs",
"module": "dist/goober.esm.js",
"umd:main": "dist/goober.umd.js",
"source": "src/index.js",
"unpkg": "dist/goober.umd.js",
"types": "goober.d.ts",
"type": "module",
"files": [
"src",
"macro",
"global/dist",
"global/src",
"global/package.json",
"global/global.d.ts",
"prefixer/dist",
"prefixer/src",
"prefixer/package.json",
"prefixer/autoprefixer.d.ts",
"prefixer/README.md",
"should-forward-prop/dist",
"should-forward-prop/src",
"should-forward-prop/package.json",
"should-forward-prop/should-forward-prop.d.ts",
"should-forward-prop/README.md",
"README.md",
"dist",
"package.json",
"typings.json",
"goober.d.ts"
],
"exports": {
".": {
"require": "./dist/goober.cjs",
"import": "./dist/goober.modern.js",
"umd": "./dist/goober.umd.js",
"types": "./goober.d.ts"
},
"./macro": "./macro/index.js",
"./global": {
"import": "./global/dist/goober-global.modern.js",
"require": "./global/dist/goober-global.cjs",
"umd": "./global/dist/goober-global.umd.js",
"types": "./global/global.d.ts"
},
"./prefixer": {
"import": "./prefixer/dist/goober-autoprefixer.modern.js",
"require": "./prefixer/dist/goober-autoprefixer.cjs",
"umd": "./prefixer/dist/goober-autoprefixer.umd.js",
"types": "./prefixer/autoprefixer.d.ts"
},
"./should-forward-prop": {
"import": "./should-forward-prop/dist/goober-should-forward-prop.modern.js",
"require": "./should-forward-prop/dist/goober-should-forward-prop.cjs",
"umd": "./should-forward-prop/dist/goober-should-forward-prop.umd.js",
"types": "./should-forward-prop/should-forward-prop.d.ts"
}
},
"scripts": {
"test": "npm run test-ts && npm run test-unit -- --ci --coverage && npm run build && npm run test-perf",
"test-perf": "NODE_ENV=production node benchmarks/perf.cjs",
"test-perf-hash": "NODE_ENV=production node benchmarks/perf-hash.cjs",
"test-unit-core": "jest --setupFiles ./tests/setup.js --roots ./src packages",
"test-unit": "npm run test-unit-core && npm run test-addon-global && npm run test-addon-prefixer",
"test-addon-global": "cd global && npm run test",
"test-addon-prefixer": "cd prefixer && npm run test",
"test-ts": "tsc -p ts-tests",
"clean": "rimraf dist",
"size-check": "filesize",
"build": "npm run build:core && npm run build:prefixer && npm run build:global && npm run build:should-forward-prop",
"build:prefixer": "cd ./prefixer && npm run build",
"build:global": "cd ./global && npm run build",
"build:should-forward-prop": "cd ./should-forward-prop && npm run build",
"build:core": "npm run clean && npm run build:dist && npm run size-check",
"build:lib": "microbundle --entry src/index.js --name goober --no-sourcemap --generateTypes false",
"build:dist": "npm run build:lib -- --output dist",
"build:debug": "npm run build:lib -- --output debug --no-compress",
"dev": "npm run clean && microbundle watch --entry src/index.js --output dist --name goober",
"sandbox": "wmr --public sandbox/wmr",
"deploy": "npm run build && npm publish",
"format": "prettier \"**/*.{js,ts,tsx,md}\" --write"
},
"keywords": [
"css-in-js",
"goober",
"styled",
"emotion",
"styled-components",
"javascript",
"react",
"preact"
],
"author": "Cristian <botecristian@yahoo.com>",
"repository": {
"type": "git",
"url": "https://github.com/cristianbote/goober"
},
"license": "MIT",
"devDependencies": {
"@ampproject/filesize": "^4.0.0",
"@babel/core": "^7.2.2",
"@babel/plugin-transform-react-jsx": "^7.7.0",
"@babel/preset-env": "^7.3.1",
"@emotion/core": "^11.0.0",
"@emotion/styled": "^11.0.0",
"@emotion/react": "^11.1.4",
"@types/react": "^16.9.34",
"babel-jest": "^24.1.0",
"benchmark": "^2.1.4",
"csstype": "^3.0.10",
"husky": "4.2.4",
"jest": "^24.1.0",
"lint-staged": "10.2.0",
"microbundle": "^0.15.0",
"preact": "^10.0.0",
"prettier": "2.0.5",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"rimraf": "3.0.2",
"styled-components": "^5.2.1",
"typescript": "^3.6.3",
"wmr": "^3.7.2"
},
"peerDependencies": {
"csstype": "^3.0.10"
},
"typings": "./goober.d.ts",
"filesize": {
"./dist/goober.modern.js": {
"gzip": "1300B"
},
"./dist/goober.cjs": {
"gzip": "1300B"
}
},
"lint-staged": {
"*.{js,ts,tsx,md}": [
"prettier --write"
]
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"collective": {
"type": "opencollective",
"url": "https://opencollective.com/goober"
}
}
+20
View File
@@ -0,0 +1,20 @@
# goober-autoprefixer
A css autoprefixer for [🥜goober](https://github.com/cristianbote/goober) using [style-vendorizer](https://github.com/kripod/style-vendorizer).
## Install
`npm install --save goober`
## How to use it
This packages exports a `prefix` function that needs to be passed to goober's `setup` function like this:
```jsx
import React from 'react';
import { setup } from 'goober';
import { prefix } from 'goober/prefixer';
// Setup goober for react with autoprefixer
setup(React.createElement, prefix);
```
+7
View File
@@ -0,0 +1,7 @@
export = autoprefixer;
export as namespace autoprefixer;
declare namespace autoprefixer {
function prefix(key: string, val: any): string;
}
+1
View File
@@ -0,0 +1 @@
var e=require("style-vendorizer");exports.prefix=function(s,$){let r="";const t=e.cssPropertyAlias(s);t&&(r+=`${t}:${$};`);const o=e.cssPropertyPrefixFlags(s);1&o&&(r+=`-webkit-${s}:${$};`),2&o&&(r+=`-moz-${s}:${$};`),4&o&&(r+=`-ms-${s}:${$};`);const i=e.cssValuePrefixFlags(s,$);return 1&i?r+=`${s}:-webkit-${$};`:2&i?r+=`${s}:-moz-${$};`:4&i&&(r+=`${s}:-ms-${$};`),r+=`${s}:${$};`,r};
@@ -0,0 +1 @@
import{cssPropertyAlias as $,cssPropertyPrefixFlags as t,cssValuePrefixFlags as o}from"style-vendorizer";function e(e,n){let r="";const m=$(e);m&&(r+=`${m}:${n};`);const s=t(e);1&s&&(r+=`-webkit-${e}:${n};`),2&s&&(r+=`-moz-${e}:${n};`),4&s&&(r+=`-ms-${e}:${n};`);const i=o(e,n);return 1&i?r+=`${e}:-webkit-${n};`:2&i?r+=`${e}:-moz-${n};`:4&i&&(r+=`${e}:-ms-${n};`),r+=`${e}:${n};`,r}export{e as prefix};
@@ -0,0 +1 @@
import{cssPropertyAlias as $,cssPropertyPrefixFlags as t,cssValuePrefixFlags as o}from"style-vendorizer";function e(e,n){let r="";const m=$(e);m&&(r+=`${m}:${n};`);const s=t(e);1&s&&(r+=`-webkit-${e}:${n};`),2&s&&(r+=`-moz-${e}:${n};`),4&s&&(r+=`-ms-${e}:${n};`);const i=o(e,n);return 1&i?r+=`${e}:-webkit-${n};`:2&i?r+=`${e}:-moz-${n};`:4&i&&(r+=`${e}:-ms-${n};`),r+=`${e}:${n};`,r}export{e as prefix};
@@ -0,0 +1 @@
!function(e,o){"object"==typeof exports&&"undefined"!=typeof module?o(exports,require("style-vendorizer")):"function"==typeof define&&define.amd?define(["exports","style-vendorizer"],o):o((e||self).gooberPrefixer={},e.styleVendorizer)}(this,function(e,o){e.prefix=function(e,t){let s="";const i=o.cssPropertyAlias(e);i&&(s+=`${i}:${t};`);const r=o.cssPropertyPrefixFlags(e);1&r&&(s+=`-webkit-${e}:${t};`),2&r&&(s+=`-moz-${e}:${t};`),4&r&&(s+=`-ms-${e}:${t};`);const n=o.cssValuePrefixFlags(e,t);return 1&n?s+=`${e}:-webkit-${t};`:2&n?s+=`${e}:-moz-${t};`:4&n&&(s+=`${e}:-ms-${t};`),s+=`${e}:${t};`,s}});
+44
View File
@@ -0,0 +1,44 @@
{
"name": "goober-autoprefixer",
"version": "1.2.3",
"sideEffects": false,
"main": "./dist/goober-autoprefixer.cjs",
"module": "./dist/goober-autoprefixer.esm.js",
"umd:main": "./dist/goober-autoprefixer.umd.js",
"source": "./src/index.js",
"unpkg": "./dist/goober-autoprefixer.umd.js",
"types": "./autoprefixer.d.ts",
"type": "module",
"author": {
"name": "Jovi De Croock",
"url": "https://www.jovidecroock.com/"
},
"license": "MIT",
"scripts": {
"build": "rm -rf ./dist && microbundle --entry src/index.js --name gooberPrefixer --no-sourcemap --generateTypes false",
"test": "jest"
},
"devDependencies": {
"microbundle": "^0.14.2",
"@babel/plugin-transform-react-jsx": "^7.7.0",
"@babel/preset-env": "^7.3.1",
"babel-jest": "^24.1.0",
"jest": "^24.1.0",
"style-vendorizer": "^2.0.0"
},
"keywords": [
"goober",
"prefixer",
"autoprefixer",
"css",
"postcss"
],
"files": [
"src",
"dist",
"README.md",
"package.json",
"LICENSE",
"autoprefixer.d.ts"
]
}
+28
View File
@@ -0,0 +1,28 @@
import { cssPropertyAlias, cssPropertyPrefixFlags, cssValuePrefixFlags } from 'style-vendorizer';
export function prefix(property, value) {
let cssText = '';
/* Resolve aliases, e.g. `gap` -> `grid-gap` */
const propertyAlias = cssPropertyAlias(property);
if (propertyAlias) cssText += `${propertyAlias}:${value};`;
/* Prefix properties, e.g. `backdrop-filter` -> `-webkit-backdrop-filter` */
const propertyFlags = cssPropertyPrefixFlags(property);
if (propertyFlags & 0b001) cssText += `-webkit-${property}:${value};`;
if (propertyFlags & 0b010) cssText += `-moz-${property}:${value};`;
if (propertyFlags & 0b100) cssText += `-ms-${property}:${value};`;
/* Prefix values, e.g. `position: "sticky"` -> `position: "-webkit-sticky"` */
/* Notice that flags don't overlap and property prefixing isn't needed here */
const valueFlags = cssValuePrefixFlags(property, value);
if (valueFlags & 0b001) cssText += `${property}:-webkit-${value};`;
else if (valueFlags & 0b010) cssText += `${property}:-moz-${value};`;
else if (valueFlags & 0b100) cssText += `${property}:-ms-${value};`;
/* Include the standardized declaration last */
/* https://css-tricks.com/ordering-css3-properties/ */
cssText += `${property}:${value};`;
return cssText;
}
@@ -0,0 +1 @@
exports.shouldForwardProp=function(o){return function(r){for(let e in r)o(e)||delete r[e]}};
@@ -0,0 +1 @@
function e(e){return function(n){for(let t in n)e(t)||delete n[t]}}export{e as shouldForwardProp};
@@ -0,0 +1 @@
function e(e){return function(n){for(let t in n)e(t)||delete n[t]}}export{e as shouldForwardProp};
@@ -0,0 +1 @@
!function(e,o){"object"==typeof exports&&"undefined"!=typeof module?o(exports):"function"==typeof define&&define.amd?define(["exports"],o):o((e||self).gooberForwardProp={})}(this,function(e){e.shouldForwardProp=function(e){return function(o){for(let n in o)e(n)||delete o[n]}}});
+41
View File
@@ -0,0 +1,41 @@
{
"name": "goober-should-forward-prop",
"amdName": "gooberForwardProp",
"version": "0.0.1",
"description": "The shouldForwardProp addon function for goober",
"sideEffects": false,
"main": "./dist/goober-should-forward-prop.cjs",
"module": "./dist/goober-should-forward-prop.esm.js",
"umd:main": "./dist/goober-should-forward-prop.umd.js",
"source": "./src/index.js",
"unpkg": "./dist/goober-should-forward-prop.umd.js",
"types": "./should-forward-prop.d.ts",
"type": "module",
"scripts": {
"build": "rm -rf dist && microbundle --entry src/index.js --name gooberForwardProp --no-sourcemap --generateTypes false",
"test": "jest --setupFiles ./jest.setup.js"
},
"repository": {
"type": "git",
"url": "https://github.com/cristianbote/goober.git",
"directory": "should-forward-prop"
},
"author": "Jonas De Vrient <devrient.jonas@gmail.com>",
"keywords": [
"goober",
"styled",
"should-forward-prop"
],
"license": "MIT",
"peerDependencies": {
"goober": "^2.0.18"
},
"devDependencies": {
"microbundle": "^0.14.2",
"jest": "^24.1.0",
"preact": "^10.5.6",
"@babel/plugin-transform-react-jsx": "^7.7.0",
"@babel/preset-env": "^7.3.1",
"babel-jest": "^24.1.0"
}
}
@@ -0,0 +1,9 @@
export = gooberShouldForwardProp;
export as namespace shouldForwardProp;
declare namespace gooberShouldForwardProp {
type ForwardPropFunction = (prop: string) => boolean;
function shouldForwardProp(fwdProp: ForwardPropFunction): (props: object) => undefined;
}
@@ -0,0 +1,25 @@
import { css } from 'goober';
import { shouldForwardProp } from '../index';
describe('shouldForwardProp', () => {
it('type', () => {
expect(typeof shouldForwardProp).toEqual('function');
});
it('shouldForwardProp', () => {
const fn = shouldForwardProp((prop) => {
// Filter out props prefixed with '$'
return prop[0] !== '$';
});
const props = {
color: 'red',
$shouldAnimate: true
};
// 'render'
fn(props);
expect(props).toEqual({ color: 'red' });
});
});
+19
View File
@@ -0,0 +1,19 @@
/**
* Should forward prop utility function
* @param {Function} filterPropFunction The flter function
*/
export function shouldForwardProp(filterPropFunction) {
/**
* The forward props function passed to `setup`
* @param {object} props
*/
function forwardProp(props) {
for (let p in props) {
if (!filterPropFunction(p)) {
delete props[p];
}
}
}
return forwardProp;
}
+114
View File
@@ -0,0 +1,114 @@
import { css, glob, keyframes } from '../css';
import { hash } from '../core/hash';
import { compile } from '../core/compile';
import { getSheet } from '../core/get-sheet';
jest.mock('../core/hash', () => ({
hash: jest.fn().mockReturnValue('hash()')
}));
jest.mock('../core/compile', () => ({
compile: jest.fn().mockReturnValue('compile()')
}));
jest.mock('../core/get-sheet', () => ({
getSheet: jest.fn().mockReturnValue('getSheet()')
}));
describe('css', () => {
beforeEach(() => {
hash.mockClear();
compile.mockClear();
getSheet.mockClear();
});
it('type', () => {
expect(typeof css).toEqual('function');
});
it('args: tagged', () => {
const out = css`base${1}`;
expect(compile).toBeCalledWith(['base', ''], [1], undefined);
expect(getSheet).toBeCalled();
expect(hash).toBeCalledWith('compile()', 'getSheet()', undefined, undefined, undefined);
expect(out).toEqual('hash()');
});
it('args: object', () => {
const out = css({ foo: 1 });
expect(hash).toBeCalledWith({ foo: 1 }, 'getSheet()', undefined, undefined, undefined);
expect(compile).not.toBeCalled();
expect(getSheet).toBeCalled();
expect(out).toEqual('hash()');
});
it('args: array', () => {
const propsBased = jest.fn().mockReturnValue({
backgroundColor: 'gold'
});
const payload = [{ foo: 1 }, { baz: 2 }, { opacity: 0, color: 'red' }, propsBased];
const out = css(payload);
expect(propsBased).toHaveBeenCalled();
expect(hash).toBeCalledWith(
{ foo: 1, baz: 2, opacity: 0, color: 'red', backgroundColor: 'gold' },
'getSheet()',
undefined,
undefined,
undefined
);
expect(compile).not.toBeCalled();
expect(getSheet).toBeCalled();
expect(out).toEqual('hash()');
});
it('args: function', () => {
const incoming = { foo: 'foo' };
const out = css.call({ p: incoming }, (props) => ({ foo: props.foo }));
expect(hash).toBeCalledWith(incoming, 'getSheet()', undefined, undefined, undefined);
expect(compile).not.toBeCalled();
expect(getSheet).toBeCalled();
expect(out).toEqual('hash()');
});
it('bind', () => {
const target = '';
const p = {};
const g = true;
const out = css.bind({
target,
p,
g
})`foo: 1`;
expect(hash).toBeCalledWith('compile()', 'getSheet()', true, undefined, undefined);
expect(compile).toBeCalledWith(['foo: 1'], [], p);
expect(getSheet).toBeCalledWith(target);
expect(out).toEqual('hash()');
});
});
describe('glob', () => {
it('type', () => {
expect(typeof glob).toEqual('function');
});
it('args: g', () => {
glob`a:b`;
expect(hash).toBeCalledWith('compile()', 'getSheet()', 1, undefined, undefined);
});
});
describe('keyframes', () => {
it('type', () => {
expect(typeof keyframes).toEqual('function');
});
it('args: k', () => {
keyframes`a:b`;
expect(hash).toBeCalledWith('compile()', 'getSheet()', undefined, undefined, 1);
});
});
+14
View File
@@ -0,0 +1,14 @@
import * as goober from '../index';
describe('goober', () => {
it('exports', () => {
expect(Object.keys(goober).sort()).toEqual([
'css',
'extractCss',
'glob',
'keyframes',
'setup',
'styled'
]);
});
});
+246
View File
@@ -0,0 +1,246 @@
import { h, createContext, render } from 'preact';
import { useContext, forwardRef } from 'preact/compat';
import { setup, css, styled, keyframes } from '../index';
import { extractCss } from '../core/update';
describe('integrations', () => {
it('preact', () => {
const ThemeContext = createContext();
const useTheme = () => useContext(ThemeContext);
setup(h, null, useTheme);
const target = document.createElement('div');
const Span = styled('span', forwardRef)`
color: red;
`;
const SpanWrapper = styled('div')`
color: cyan;
${Span} {
border: 1px solid red;
}
`;
const BoxWithColor = styled('div')`
color: ${(props) => props.color};
`;
const BoxWithColorFn = styled('div')(
(props) => `
color: ${props.color};
`
);
const BoxWithThemeColor = styled('div')`
color: ${(props) => props.theme.color};
`;
const BoxWithThemeColorFn = styled('div')(
(props) => `
color: ${props.theme.color};
`
);
const fadeAnimation = keyframes`
0% {
opacity: 0;
}
99% {
opacity: 1;
color: dodgerblue;
}
`;
const BoxWithAnimation = styled('span')`
opacity: 0;
animation: ${fadeAnimation} 500ms ease-in-out;
`;
const BoxWithConditionals = styled('div')([
{ foo: 1 },
(props) => ({ color: props.isActive ? 'red' : 'tomato' }),
null,
{ baz: 0 },
false,
{ baz: 0 }
]);
const shared = { opacity: 0 };
const BoxWithShared = styled('div')(shared);
const BoxWithSharedAndConditional = styled('div')([shared, { baz: 0 }]);
const BoxWithHas = styled('div')`
label:has(input, select),
:has(foo, boo) {
color: red;
}
`;
const refSpy = jest.fn();
render(
<ThemeContext.Provider value={{ color: 'blue' }}>
<div>
<Span ref={refSpy} />
<Span as={'div'} />
<SpanWrapper>
<Span />
</SpanWrapper>
<BoxWithColor color={'red'} />
<BoxWithColorFn color={'red'} />
<BoxWithThemeColor />
<BoxWithThemeColorFn />
<BoxWithThemeColor theme={{ color: 'green' }} />
<BoxWithThemeColorFn theme={{ color: 'orange' }} />
<BoxWithAnimation />
<BoxWithConditionals isActive />
<BoxWithShared />
<BoxWithSharedAndConditional />
<div className={css([shared, { background: 'cyan' }])} />
<BoxWithHas />
</div>
</ThemeContext.Provider>,
target
);
expect(extractCss()).toMatchInlineSnapshot(
[
'"',
' ', // Empty white space that holds the textNode that the styles are appended
'@keyframes go384228713{0%{opacity:0;}99%{opacity:1;color:dodgerblue;}}',
'.go1127809067{opacity:0;background:cyan;}',
'.go3865451590{color:red;}',
'.go3991234422{color:cyan;}',
'.go3991234422 .go3865451590{border:1px solid red;}',
'.go1925576363{color:blue;}',
'.go3206651468{color:green;}',
'.go4276997079{color:orange;}',
'.go2069586824{opacity:0;animation:go384228713 500ms ease-in-out;}',
'.go631307347{foo:1;color:red;baz:0;}',
'.go3865943372{opacity:0;}',
'.go1162430001{opacity:0;baz:0;}',
'.go2602823658 label:has(input, select),.go2602823658 :has(foo, boo){color:red;}',
'"'
].join('')
);
expect(refSpy).toHaveBeenCalledWith(
expect.objectContaining({
tagName: 'SPAN'
})
);
});
it('support extending with as', () => {
const list = ['p', 'm', 'as', 'bg'];
setup(h, undefined, undefined, (props) => {
for (let prop in props) {
if (list.indexOf(prop) !== -1) {
delete props[prop];
}
}
});
const target = document.createElement('div');
const Base = styled('div')(({ p = 0, m }) => [
{
color: 'white',
padding: p + 'em'
},
m != null && { margin: m + 'em' }
]);
const Super = styled(Base)`
background: ${(p) => p.bg || 'none'};
`;
render(
<div>
<Base />
<Base p={2} />
<Base m={1} p={3} as={'span'} />
<Super m={1} bg={'dodgerblue'} as={'button'} />
</div>,
target
);
// Makes sure the resulting DOM does not contain any props
expect(target.innerHTML).toEqual(
[
'<div>',
'<div class="go103173764"></div>',
'<div class="go103194166"></div>',
'<span class="go2081835032"></span>',
'<button class="go1969245729 go1824201605"></button>',
'</div>'
].join('')
);
expect(extractCss()).toMatchInlineSnapshot(
[
'"',
'.go1969245729{color:white;padding:0em;margin:1em;}',
'.go103173764{color:white;padding:0em;}',
'.go103194166{color:white;padding:2em;}',
'.go2081835032{color:white;padding:3em;margin:1em;}',
'.go1824201605{background:dodgerblue;}',
'"'
].join('')
);
});
it('shouldForwardProps', () => {
const list = ['p', 'm', 'as'];
setup(h, undefined, undefined, (props) => {
for (let prop in props) {
if (list.indexOf(prop) !== -1) {
delete props[prop];
}
}
});
const target = document.createElement('div');
const Base = styled('div')(({ p = 0, m }) => [
{
color: 'white',
padding: p + 'em'
},
m != null && { margin: m + 'em' }
]);
render(
<div>
<Base />
<Base p={2} />
<Base m={1} p={3} as={'span'} />
</div>,
target
);
// Makes sure the resulting DOM does not contain any props
expect(target.innerHTML).toEqual(
[
'<div>',
'<div class="go103173764"></div>',
'<div class="go103194166"></div>',
'<span class="go2081835032"></span>',
'</div>'
].join(''),
`"<div><div class=\\"go103173764\\"></div><div class=\\"go103194166\\"></div><span class=\\"go2081835032\\"></span></div>"`
);
expect(extractCss()).toMatchInlineSnapshot(
[
'"',
'.go103173764{color:white;padding:0em;}',
'.go103194166{color:white;padding:2em;}',
'.go2081835032{color:white;padding:3em;margin:1em;}',
'"'
].join('')
);
});
});
+159
View File
@@ -0,0 +1,159 @@
import { styled, setup } from '../styled';
import { extractCss } from '../core/update';
const pragma = jest.fn((tag, props) => {
return { tag, props: { ...props, className: props.className.replace(/go\d+/g, 'go') } };
});
expect.extend({
toMatchVNode(received, tag, props) {
expect(received.tag).toEqual(tag);
expect(received.props).toEqual(props);
return {
message: 'Expected vnode to match vnode',
pass: true
};
}
});
describe('styled', () => {
beforeEach(() => {
pragma.mockClear();
setup(pragma);
extractCss();
});
it('calls pragma', () => {
setup(undefined);
expect(() => styled()()()).toThrow();
setup(pragma);
const vnode = styled('div')``();
expect(pragma).toBeCalledTimes(1);
expect(vnode).toMatchVNode('div', {
className: 'go'
});
});
it('extend props', () => {
const vnode = styled('tag')`
color: peachpuff;
`({ bar: 1 });
expect(vnode).toMatchVNode('tag', {
bar: 1,
className: 'go'
});
expect(extractCss()).toEqual('.go3183460609{color:peachpuff;}');
});
it('concat className if present in props', () => {
const vnode = styled('tag')`
color: peachpuff;
`({ bar: 1, className: 'existing' });
expect(vnode).toMatchVNode('tag', {
bar: 1,
className: 'go existing'
});
});
it('pass template function', () => {
const vnode = styled('tag')((props) => ({ color: props.color }))({ color: 'red' });
expect(vnode).toMatchVNode('tag', {
className: 'go',
color: 'red'
});
expect(extractCss()).toEqual('.go3433634237{color:red;}');
});
it('change tag via "as" prop', () => {
const Tag = styled('tag')`
color: red;
`;
// Simulate a render
let vnode = Tag();
expect(vnode).toMatchVNode('tag', { className: 'go' });
// Simulate a render with
vnode = Tag({ as: 'foo' });
// Expect it to be changed to foo
expect(vnode).toMatchVNode('foo', { className: 'go' });
// Simulate a render
vnode = Tag();
expect(vnode).toMatchVNode('tag', { className: 'go' });
});
it('support forwardRef', () => {
const forwardRef = jest.fn((fn) => (props) => fn(props, 'ref'));
const vnode = styled('tag', forwardRef)`
color: red;
`({ bar: 1 });
expect(vnode).toMatchVNode('tag', {
bar: 1,
className: 'go',
ref: 'ref'
});
});
it('setup useTheme', () => {
setup(pragma, null, () => 'theme');
const styleFn = jest.fn(() => ({}));
const vnode = styled('tag')(styleFn)({ bar: 1 });
expect(styleFn).toBeCalledWith({ bar: 1, theme: 'theme' });
expect(vnode).toMatchVNode('tag', {
bar: 1,
className: 'go'
});
});
it('setup useTheme with theme prop override', () => {
setup(pragma, null, () => 'theme');
const styleFn = jest.fn(() => ({}));
const vnode = styled('tag')(styleFn)({ theme: 'override' });
expect(styleFn).toBeCalledWith({ theme: 'override' });
expect(vnode).toMatchVNode('tag', { className: 'go', theme: 'override' });
});
it('uses babel compiled classNames', () => {
const Comp = styled('tag')``;
Comp.className = 'foobar';
const vnode = Comp({});
expect(vnode).toMatchVNode('tag', { className: 'go foobar' });
});
it('omits css prop with falsy should forward prop function', () => {
const shouldForwardProp = (props) => {
for (let prop in props) {
if (prop.includes('$')) delete props[prop];
}
};
// Overwrite setup for this test
setup(pragma, undefined, undefined, shouldForwardProp);
const vnode = styled('tag')`
color: peachpuff;
`({ bar: 1, $templateColumns: '1fr 1fr' });
expect(vnode).toMatchVNode('tag', { className: 'go', bar: 1 });
});
it('pass truthy logical and operator', () => {
const Tag = styled('tag')((props) => props.draw && { color: 'yellow' });
// Simulate a render
let vnode = Tag({ draw: true });
expect(vnode).toMatchVNode('tag', { className: 'go', draw: true });
expect(extractCss()).toEqual('.go2986228274{color:yellow;}');
});
});
+219
View File
@@ -0,0 +1,219 @@
import { astish } from '../astish';
describe('astish', () => {
it('regular', () => {
expect(
astish(`
prop: value;
`)
).toEqual({
prop: 'value'
});
});
it('nested', () => {
expect(
astish(`
prop: value;
@keyframes foo {
0% {
attr: value;
}
50% {
opacity: 1;
}
100% {
foo: baz;
}
}
named {
background-image: url('/path-to-jpg.png');
}
opacity: 0;
.class,
&:hover {
-webkit-touch: none;
}
`)
).toEqual({
prop: 'value',
opacity: '0',
'.class, &:hover': {
'-webkit-touch': 'none'
},
'@keyframes foo': {
'0%': {
attr: 'value'
},
'50%': {
opacity: '1'
},
'100%': {
foo: 'baz'
}
},
named: {
'background-image': "url('/path-to-jpg.png')"
}
});
});
it('merging', () => {
expect(
astish(`
.c {
font-size:24px;
}
.c {
color:red;
}
`)
).toEqual({
'.c': {
'font-size': '24px',
color: 'red'
}
});
});
it('regression', () => {
expect(
astish(`
&.g0ssss {
aa: foo;
box-shadow: 0 1px rgba(0, 2, 33, 4) inset;
}
named {
transform: scale(1.2), rotate(1, 1);
}
@media screen and (some-rule: 100px) {
foo: baz;
opacity: 1;
level {
one: 1;
level {
two: 2;
}
}
}
.a{
color: red;
}
.b {
color: blue;
}
`)
).toEqual({
'&.g0ssss': {
aa: 'foo',
'box-shadow': '0 1px rgba(0, 2, 33, 4) inset'
},
'.a': {
color: 'red'
},
'.b': {
color: 'blue'
},
named: {
transform: 'scale(1.2), rotate(1, 1)'
},
'@media screen and (some-rule: 100px)': {
foo: 'baz',
opacity: '1',
level: {
one: '1',
level: {
two: '2'
}
}
}
});
});
it('should strip comments', () => {
expect(
astish(`
color: red;
/*
some comment
*/
transform: translate3d(0, 0, 0);
/**
* other comment
*/
background: peachpuff;
font-size: xx-large; /* inline comment */
/* foo: bar */
font-weight: bold;
`)
).toEqual({
color: 'red',
transform: 'translate3d(0, 0, 0)',
background: 'peachpuff',
'font-size': 'xx-large',
'font-weight': 'bold'
});
});
// for reference on what is valid:
// https://www.w3.org/TR/CSS22/syndata.html#value-def-identifier
it('should not mangle valid css identifiers', () => {
expect(
astish(`
:root {
--azAZ-_中文09: 0;
}
`)
).toEqual({
':root': {
'--azAZ-_中文09': '0'
}
});
});
it('should parse multiline background declaration', () => {
expect(
astish(`
background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" fill="white"><path d="M7.5 36.7h58.4v10.6H7.5V36.7zm0-15.9h58.4v10.6H7.5V20.8zm0 31.9h58.4v10.6H7.5V52.7zm0 15.9h58.4v10.6H7.5V68.6zm63.8-15.9l10.6 15.9 10.6-15.9H71.3zm21.2-5.4L81.9 31.4 71.3 47.3h21.2z"/></svg>')
center/contain;
`)
).toEqual({
background: `url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" fill="white"><path d="M7.5 36.7h58.4v10.6H7.5V36.7zm0-15.9h58.4v10.6H7.5V20.8zm0 31.9h58.4v10.6H7.5V52.7zm0 15.9h58.4v10.6H7.5V68.6zm63.8-15.9l10.6 15.9 10.6-15.9H71.3zm21.2-5.4L81.9 31.4 71.3 47.3h21.2z"/></svg>') center/contain`
});
});
it('should handle inline @media block', () => {
expect(
astish(
`h1 { font-size: 1rem; } @media only screen and (min-width: 850px) { h1 { font-size: 2rem; } }`
)
).toEqual({
h1: {
'font-size': '1rem'
},
'@media only screen and (min-width: 850px)': {
h1: {
'font-size': '2rem'
}
}
});
});
it('should handle newlines as part of the rule value', () => {
expect(
astish(
`tag {
font-size: first
second;
}`
)
).toEqual({
tag: {
'font-size': 'first second'
}
});
});
});
+70
View File
@@ -0,0 +1,70 @@
import { compile } from '../compile';
const template = (str, ...defs) => {
return (props) => compile(str, defs, props);
};
describe('compile', () => {
it('simple', () => {
expect(template`prop: 1;`({})).toEqual('prop: 1;');
});
it('vnode', () => {
expect(template`prop: 1; ${() => ({ props: { className: 'class' } })}`({})).toEqual(
'prop: 1; .class'
);
// Empty or falsy
expect(template`prop: 1; ${() => ({ props: { foo: 1 } })}`({})).toEqual('prop: 1; ');
});
it('vanilla classname', () => {
expect(template`prop: 1; ${() => 'go0ber'}`({})).toEqual('prop: 1; .go0ber');
});
it('value interpolations', () => {
// This interpolations are testing the ability to interpolate thruty and falsy values
expect(template`prop: 1; ${() => 0},${() => undefined},${() => null},${2}`({})).toEqual(
'prop: 1; 0,,,2'
);
const tmpl = template`
background: dodgerblue;
${(props) =>
props.padding === 'bloo' &&
`
padding: ${props.padding}px;
`}
border: 1px solid blue;
`;
expect(tmpl({})).toEqual(`
background: dodgerblue;
border: 1px solid blue;
`);
});
describe('objects', () => {
it('normal', () => {
expect(template`prop: 1;${(p) => ({ color: p.color })}`({ color: 'red' })).toEqual(
'prop: 1;color:red;'
);
});
it('styled-system', () => {
const color = (p) => ({ color: p.color });
const background = (p) => ({ backgroundColor: p.backgroundColor });
const props = { color: 'red', backgroundColor: 'blue' };
const res = template`
prop: 1;
${color}
${background}
`(props);
expect(res.replace(/([\s|\n]+)/gm, '').trim()).toEqual(
'prop:1;color:red;background-color:blue;'
);
});
});
});
+70
View File
@@ -0,0 +1,70 @@
import { getSheet } from '../get-sheet';
describe('getSheet', () => {
it('regression', () => {
const target = getSheet();
expect(target.nodeType).toEqual(3);
});
it('custom target', () => {
const custom = document.createElement('div');
const sheet = getSheet(custom);
expect(sheet.nodeType).toEqual(3);
expect(sheet.parentElement.nodeType).toEqual(1);
expect(sheet.parentElement.getAttribute('id')).toEqual('_goober');
});
it('reuse sheet', () => {
const custom = document.createElement('div');
const sheet = getSheet(custom);
const second = getSheet(custom);
expect(sheet === second).toBeTruthy();
});
it('applies nonce from window.__nonce__', () => {
const sheet = getSheet();
const style = sheet.parentElement;
const prevAttr = style.getAttribute('nonce');
const hadAttr = style.hasAttribute('nonce');
const prevNonce = window.__nonce__;
style.removeAttribute('nonce');
delete window.__nonce__;
window.__nonce__ = 'secure-nonce';
getSheet();
expect(style.getAttribute('nonce')).toEqual('secure-nonce');
if (prevAttr != null) style.setAttribute('nonce', prevAttr);
else if (!hadAttr) style.removeAttribute('nonce');
if (prevNonce === undefined) delete window.__nonce__;
else window.__nonce__ = prevNonce;
});
it('server side', () => {
const bkp = global.document;
delete global.document;
expect(() => getSheet()).not.toThrow();
global.document = bkp;
});
it('server side with custom collector', () => {
const bkp = global.document;
const win = global.window;
delete global.document;
delete global.window;
const collector = { data: '' };
expect(collector === getSheet(collector)).toBeTruthy();
global.document = bkp;
global.window = win;
});
});
+126
View File
@@ -0,0 +1,126 @@
import { hash } from '../hash';
import { toHash } from '../to-hash';
import { update } from '../update';
import { parse } from '../parse';
import { astish } from '../astish';
jest.mock('../astish', () => ({
astish: jest.fn().mockReturnValue('astish()')
}));
jest.mock('../parse', () => ({
parse: jest.fn().mockReturnValue('parse()')
}));
jest.mock('../to-hash', () => ({
toHash: jest.fn().mockReturnValue('toHash()')
}));
jest.mock('../update', () => ({
update: jest.fn().mockReturnValue('update()')
}));
jest.mock('../astish', () => ({
astish: jest.fn().mockReturnValue('astish()')
}));
jest.mock('../parse', () => ({
parse: jest.fn().mockReturnValue('parse()')
}));
describe('hash', () => {
beforeEach(() => {
toHash.mockClear();
update.mockClear();
parse.mockClear();
astish.mockClear();
});
it('regression', () => {
const res = hash('compiled', 'target');
expect(toHash).toBeCalledWith('compiled');
expect(update).toBeCalledWith('parse()', 'target', undefined, null);
expect(astish).toBeCalledWith('compiled');
expect(parse).toBeCalledWith('astish()', '.toHash()');
expect(res).toEqual('toHash()');
});
it('regression: cache', () => {
const res = hash('compiled', 'target');
expect(toHash).not.toBeCalled();
expect(astish).not.toBeCalled();
expect(parse).not.toBeCalled();
expect(update).toBeCalledWith('parse()', 'target', undefined, null);
expect(res).toEqual('toHash()');
});
it('regression: global', () => {
const res = hash('global', 'target', true);
expect(toHash).toBeCalledWith('global');
expect(astish).not.toBeCalled();
expect(parse).not.toBeCalled();
expect(update).toBeCalledWith('parse()', 'target', undefined, null);
expect(res).toEqual('toHash()');
});
it('regression: global-style-replace', () => {
const res = hash('global', 'target', true);
expect(toHash).not.toBeCalled();
expect(astish).not.toBeCalled();
expect(parse).not.toBeCalled();
expect(update).toBeCalledWith('parse()', 'target', undefined, 'parse()');
expect(res).toEqual('toHash()');
});
it('regression: keyframes', () => {
const res = hash('keyframes', 'target', undefined, undefined, 1);
expect(toHash).toBeCalledWith('keyframes');
expect(astish).not.toBeCalled();
expect(parse).not.toBeCalled();
expect(update).toBeCalledWith('parse()', 'target', undefined, null);
expect(res).toEqual('toHash()');
});
it('regression: object', () => {
const className = Math.random() + 'unique';
toHash.mockReturnValue(className);
const res = hash({ baz: 1 }, 'target');
expect(toHash).toBeCalledWith('baz1');
expect(astish).not.toBeCalled();
expect(parse).toBeCalledWith({ baz: 1 }, '.' + className);
expect(update).toBeCalledWith('parse()', 'target', undefined, null);
expect(res).toEqual(className);
});
it('regression: cache-object', () => {
const className = Math.random() + 'unique';
toHash.mockReturnValue(className);
// Since it's not yet cached
hash({ cacheObject: 1 }, 'target');
expect(toHash).toBeCalledWith('cacheObject1');
toHash.mockClear();
// Different object
hash({ foo: 2 }, 'target');
expect(toHash).toBeCalledWith('foo2');
toHash.mockClear();
// First object should not call .toHash
hash({ cacheObject: 1 }, 'target');
expect(toHash).not.toBeCalled();
});
});
+327
View File
@@ -0,0 +1,327 @@
import { parse } from '../parse';
describe('parse', () => {
it('regular', () => {
const out = parse(
{
display: 'value',
button: {
border: '0'
},
'&.nested': {
foo: '1px',
baz: 'scale(1), translate(1)'
}
},
'hush'
);
expect(out).toEqual(
[
'hush{display:value;}',
'hush button{border:0;}',
'hush.nested{foo:1px;baz:scale(1), translate(1);}'
].join('')
);
});
it('camelCase', () => {
const out = parse(
{
fooBarProperty: 'value',
button: {
webkitPressSomeButton: '0'
},
'&.nested': {
foo: '1px',
backgroundEffect: 'scale(1), translate(1)'
}
},
'hush'
);
expect(out).toEqual(
[
'hush{foo-bar-property:value;}',
'hush button{webkit-press-some-button:0;}',
'hush.nested{foo:1px;background-effect:scale(1), translate(1);}'
].join('')
);
});
it('keyframes', () => {
const out = parse(
{
'@keyframes superAnimation': {
'11.1%': {
opacity: '0.9999'
},
'111%': {
opacity: '1'
}
},
'@keyframes foo': {
to: {
baz: '1px',
foo: '1px'
}
},
'@keyframes complex': {
'from, 20%, 53%, 80%, to': {
transform: 'translate3d(0,0,0)'
},
'40%, 43%': {
transform: 'translate3d(0, -30px, 0)'
},
'70%': {
transform: 'translate3d(0, -15px, 0)'
},
'90%': {
transform: 'translate3d(0,-4px,0)'
}
}
},
'hush'
);
expect(out).toEqual(
[
'@keyframes superAnimation{11.1%{opacity:0.9999;}111%{opacity:1;}}',
'@keyframes foo{to{baz:1px;foo:1px;}}',
'@keyframes complex{from, 20%, 53%, 80%, to{transform:translate3d(0,0,0);}40%, 43%{transform:translate3d(0, -30px, 0);}70%{transform:translate3d(0, -15px, 0);}90%{transform:translate3d(0,-4px,0);}}'
].join('')
);
});
it('font-face', () => {
const out = parse(
{
'@font-face': {
'font-weight': 100
}
},
'FONTFACE'
);
expect(out).toEqual(['@font-face{font-weight:100;}'].join(''));
});
it('@media', () => {
const out = parse(
{
'@media any all (no-really-anything)': {
position: 'super-absolute'
}
},
'hush'
);
expect(out).toEqual(
['@media any all (no-really-anything){hush{position:super-absolute;}}'].join('')
);
});
it('@import', () => {
const out = parse(
{
'@import': "url('https://domain.com/path?1=s')"
},
'hush'
);
expect(out).toEqual(["@import url('https://domain.com/path?1=s');"].join(''));
});
it('cra', () => {
expect(
parse(
{
'@import': "url('path/to')",
'@font-face': {
'font-weight': 100
},
'text-align': 'center',
'.logo': {
animation: 'App-logo-spin infinite 20s linear',
height: '40vmin',
'pointer-events': 'none'
},
'.header': {
'background-color': '#282c34',
'min-height': '100vh',
display: 'flex',
'flex-direction': 'column',
'align-items': 'center',
'justify-content': 'center',
'font-size': 'calc(10px + 2vmin)',
color: 'white'
},
'.link': {
color: '#61dafb'
},
'@keyframes App-logo-spin': {
from: {
transform: 'rotate(0deg)'
},
to: {
transform: 'rotate(360deg)'
}
}
},
'App'
)
).toEqual(
[
"@import url('path/to');",
'App{text-align:center;}',
'@font-face{font-weight:100;}',
'App .logo{animation:App-logo-spin infinite 20s linear;height:40vmin;pointer-events:none;}',
'App .header{background-color:#282c34;min-height:100vh;display:flex;flex-direction:column;align-items:center;justify-content:center;font-size:calc(10px + 2vmin);color:white;}',
'App .link{color:#61dafb;}',
'@keyframes App-logo-spin{from{transform:rotate(0deg);}to{transform:rotate(360deg);}}'
].join('')
);
});
it('@supports', () => {
expect(
parse(
{
'@supports (some: 1px)': {
'@media (s: 1)': {
display: 'flex'
}
},
'@supports': {
opacity: 1
}
},
'hush'
)
).toEqual(
[
'@supports (some: 1px){@media (s: 1){hush{display:flex;}}}',
'@supports{hush{opacity:1;}}'
].join('')
);
});
it('unwrapp', () => {
expect(
parse(
{
'--foo': 1,
opacity: 1,
'@supports': {
'--bar': 'none'
},
html: {
background: 'goober'
}
},
''
)
).toEqual(
['--foo:1;opacity:1;', '@supports{--bar:none;}', 'html{background:goober;}'].join('')
);
});
it('nested with multiple selector', () => {
const out = parse(
{
display: 'value',
'&:hover,&:focus': {
border: '0',
span: {
index: 'unset'
}
},
'p,b,i': {
display: 'block',
'&:focus,input': {
opacity: 1,
'div,span': {
opacity: 0
}
}
}
},
'hush'
);
expect(out).toEqual(
[
'hush{display:value;}',
'hush:hover,hush:focus{border:0;}',
'hush:hover span,hush:focus span{index:unset;}',
'hush p,hush b,hush i{display:block;}',
'hush p:focus,hush p input,hush b:focus,hush b input,hush i:focus,hush i input{opacity:1;}',
'hush p:focus div,hush p:focus span,hush p input div,hush p input span,hush b:focus div,hush b:focus span,hush b input div,hush b input span,hush i:focus div,hush i:focus span,hush i input div,hush i input span{opacity:0;}'
].join('')
);
});
it('should handle the :where(a,b) cases', () => {
expect(
parse(
{
div: {
':where(a, b)': {
color: 'blue'
}
}
},
''
)
).toEqual('div :where(a, b){color:blue;}');
});
it('should handle null and undefined values', () => {
expect(
parse(
{
div: {
opacity: 0,
color: null
}
},
''
)
).toEqual('div{opacity:0;}');
expect(
parse(
{
div: {
opacity: 0,
color: undefined // or `void 0` when minified
}
},
''
)
).toEqual('div{opacity:0;}');
});
it('does not transform the case of custom CSS variables', () => {
expect(
parse({
'--cP': 'red'
})
).toEqual('--cP:red;');
expect(
parse({
'--c-P': 'red'
})
).toEqual('--c-P:red;');
expect(
parse({
'--cp': 'red'
})
).toEqual('--cp:red;');
expect(
parse({
':root': {
'--cP': 'red'
}
})
).toEqual(':root{--cP:red;}');
});
});
+17
View File
@@ -0,0 +1,17 @@
import { toHash } from '../to-hash';
describe('to-hash', () => {
it('regression', () => {
const res = toHash('goober');
expect(res).toEqual('go1990315141');
expect(toHash('goober')).toEqual('go1990315141');
});
it('collision', () => {
const a = toHash('background:red;color:black;');
const b = toHash('background:black;color:red;');
expect(a === b).toBeFalsy();
});
});
+64
View File
@@ -0,0 +1,64 @@
import { update, extractCss } from '../update';
import { getSheet } from '../get-sheet';
describe('update', () => {
it('regression', () => {
const t = { data: '' };
update('css', t);
expect(t.data).toEqual('css');
});
it('regression: duplicate', () => {
const t = { data: '' };
update('css', t);
update('foo', t);
update('css', t);
expect(t.data).toEqual('cssfoo');
});
it('regression: extract and flush', () => {
update('filled', getSheet());
expect(extractCss()).toEqual(' filled');
expect(extractCss()).toEqual('');
});
it('regression: extract and flush without DOM', () => {
const bkp = global.self;
delete global.self;
update('filled', getSheet());
expect(extractCss()).toEqual('filled');
expect(extractCss()).toEqual('');
global.self = bkp;
});
it('regression: extract and flush from custom target', () => {
const target = document.createElement('div');
update('filled', getSheet());
update('filledbody', getSheet(target));
expect(extractCss(target)).toEqual(' filledbody');
expect(extractCss(target)).toEqual('');
});
it('regression: append or prepend', () => {
extractCss();
update('end', getSheet());
update('start', getSheet(), true);
expect(extractCss()).toEqual('startend');
});
it('regression: global style replacement', () => {
const t = { data: 'html, body { background-color: white; }' };
update(
'html, body { background-color: black; }',
t,
undefined,
'html, body { background-color: white; }'
);
expect(t.data).toEqual('html, body { background-color: black; }');
});
});
+28
View File
@@ -0,0 +1,28 @@
let newRule = /(?:([\u0080-\uFFFF\w-%@]+) *:? *([^{;]+?);|([^;}{]*?) *{)|(}\s*)/g;
let ruleClean = /\/\*[^]*?\*\/| +/g;
let ruleNewline = /\n+/g;
let empty = ' ';
/**
* Convert a css style string into a object
* @param {String} val
* @returns {Object}
*/
export let astish = (val) => {
let tree = [{}];
let block, left;
while ((block = newRule.exec(val.replace(ruleClean, '')))) {
// Remove the current entry
if (block[4]) {
tree.shift();
} else if (block[3]) {
left = block[3].replace(ruleNewline, empty).trim();
tree.unshift((tree[0][left] = tree[0][left] || {}));
} else {
tree[0][block[1]] = block[2].replace(ruleNewline, empty).trim();
}
}
return tree[0];
};
+41
View File
@@ -0,0 +1,41 @@
import { parse } from './parse';
/**
* Can parse a compiled string, from a tagged template
* @param {String} value
* @param {Object} [props]
*/
export let compile = (str, defs, data) => {
return str.reduce((out, next, i) => {
let tail = defs[i];
// If this is a function we need to:
if (tail && tail.call) {
// 1. Call it with `data`
let res = tail(data);
// 2. Grab the className
let className = res && res.props && res.props.className;
// 3. If there's none, see if this is basically a
// previously styled className by checking the prefix
let end = className || (/^go/.test(res) && res);
if (end) {
// If the `end` is defined means it's a className
tail = '.' + end;
} else if (res && typeof res == 'object') {
// If `res` it's an object, we're either dealing with a vnode
// or an object returned from a function interpolation
tail = res.props ? '' : parse(res, '');
} else {
// Regular value returned. Can be falsy as well.
// Here we check if this is strictly a boolean with false value
// define it as `''` to be picked up as empty, otherwise use
// res value
tail = res === false ? '' : res;
}
}
return out + next + (tail == null ? '' : tail);
}, '');
};
+27
View File
@@ -0,0 +1,27 @@
let GOOBER_ID = '_goober';
let ssr = {
data: ''
};
/**
* Returns the _commit_ target
* @param {Object} [target]
* @returns {HTMLStyleElement|{data: ''}}
*/
export let getSheet = (target) => {
if (typeof window === 'object') {
// Querying the existing target for a previously defined <style> tag
// We're doing a querySelector because the <head> element doesn't implemented the getElementById api
let el =
(target ? target.querySelector('#' + GOOBER_ID) : window[GOOBER_ID]) ||
Object.assign(document.createElement('style'), {
innerHTML: ' ',
id: GOOBER_ID
});
el.nonce = window.__nonce__;
if (!el.parentNode) (target || document.head).appendChild(el);
return el.firstChild;
}
return target || ssr;
};
+67
View File
@@ -0,0 +1,67 @@
import { toHash } from './to-hash';
import { update } from './update';
import { astish } from './astish';
import { parse } from './parse';
/**
* In-memory cache.
*/
let cache = {};
/**
* Stringifies a object structure
* @param {Object} data
* @returns {String}
*/
let stringify = (data) => {
if (typeof data == 'object') {
let out = '';
for (let p in data) out += p + stringify(data[p]);
return out;
} else {
return data;
}
};
/**
* Generates the needed className
* @param {String|Object} compiled
* @param {Object} sheet StyleSheet target
* @param {Object} global Global flag
* @param {Boolean} append Append or not
* @param {Boolean} keyframes Keyframes mode. The input is the keyframes body that needs to be wrapped.
* @returns {String}
*/
export let hash = (compiled, sheet, global, append, keyframes) => {
// Get a string representation of the object or the value that is called 'compiled'
let stringifiedCompiled = stringify(compiled);
// Retrieve the className from cache or hash it in place
let className =
cache[stringifiedCompiled] || (cache[stringifiedCompiled] = toHash(stringifiedCompiled));
// If there's no entry for the current className
if (!cache[className]) {
// Build the _ast_-ish structure if needed
let ast = stringifiedCompiled !== compiled ? compiled : astish(compiled);
// Parse it
cache[className] = parse(
// For keyframes
keyframes ? { ['@keyframes ' + className]: ast } : ast,
global ? '' : '.' + className
);
}
// If the global flag is set, save the current stringified and compiled CSS to `cache.g`
// to allow replacing styles in <style /> instead of appending them.
// This is required for using `createGlobalStyles` with themes
let cssToReplace = global && cache.g ? cache.g : null;
if (global) cache.g = cache[className];
// add or update
update(cache[className], sheet, append, cssToReplace);
// return hash
return className;
};
+60
View File
@@ -0,0 +1,60 @@
/**
* Parses the object into css, scoped, blocks
* @param {Object} obj
* @param {String} selector
* @param {String} wrapper
*/
export let parse = (obj, selector) => {
let outer = '';
let blocks = '';
let current = '';
for (let key in obj) {
let val = obj[key];
if (key[0] == '@') {
// If these are the `@` rule
if (key[1] == 'i') {
// Handling the `@import`
outer = key + ' ' + val + ';';
} else if (key[1] == 'f') {
// Handling the `@font-face` where the
// block doesn't need the brackets wrapped
blocks += parse(val, key);
} else {
// Regular at rule block
blocks += key + '{' + parse(val, key[1] == 'k' ? '' : selector) + '}';
}
} else if (typeof val == 'object') {
// Call the parse for this block
blocks += parse(
val,
selector
? // Go over the selector and replace the matching multiple selectors if any
selector.replace(/([^,])+/g, (sel) => {
// Return the current selector with the key matching multiple selectors if any
return key.replace(/([^,]*:\S+\([^)]*\))|([^,])+/g, (k) => {
// If the current `k`(key) has a nested selector replace it
if (/&/.test(k)) return k.replace(/&/g, sel);
// If there's a current selector concat it
return sel ? sel + ' ' + k : k;
});
})
: key
);
} else if (val != undefined) {
// Convert all but CSS variables
key = /^--/.test(key) ? key : key.replace(/[A-Z]/g, '-$&').toLowerCase();
// Push the line for this property
current += parse.p
? // We have a prefixer and we need to run this through that
parse.p(key, val)
: // Nope no prefixer just append it
key + ':' + val + ';';
}
}
// If we have properties apply standard rule composition
return outer + (selector && current ? selector + '{' + current + '}' : current) + blocks;
};
+15
View File
@@ -0,0 +1,15 @@
/**
* Transforms the input into a className.
* The multiplication constant 101 is selected to be a prime,
* as is the initial value of 11.
* The intermediate and final results are truncated into 32-bit
* unsigned integers.
* @param {String} str
* @returns {String}
*/
export let toHash = (str) => {
let i = 0,
out = 11;
while (i < str.length) out = (101 * out + str.charCodeAt(i++)) >>> 0;
return 'go' + out;
};
+25
View File
@@ -0,0 +1,25 @@
import { getSheet } from './get-sheet';
/**
* Extracts and wipes the cache
* @returns {String}
*/
export let extractCss = (target) => {
let sheet = getSheet(target);
let out = sheet.data;
sheet.data = '';
return out;
};
/**
* Updates the target and keeps a local cache
* @param {String} css
* @param {Object} sheet
* @param {Boolean} append
* @param {?String} cssToReplace
*/
export let update = (css, sheet, append, cssToReplace) => {
cssToReplace
? (sheet.data = sheet.data.replace(cssToReplace, css))
: sheet.data.indexOf(css) === -1 &&
(sheet.data = append ? css + sheet.data : sheet.data + css);
};
+40
View File
@@ -0,0 +1,40 @@
import { hash } from './core/hash';
import { compile } from './core/compile';
import { getSheet } from './core/get-sheet';
/**
* css entry
* @param {String|Object|Function} val
*/
function css(val) {
let ctx = this || {};
let _val = val.call ? val(ctx.p) : val;
return hash(
_val.unshift
? _val.raw
? // Tagged templates
compile(_val, [].slice.call(arguments, 1), ctx.p)
: // Regular arrays
_val.reduce((o, i) => Object.assign(o, i && i.call ? i(ctx.p) : i), {})
: _val,
getSheet(ctx.target),
ctx.g,
ctx.o,
ctx.k
);
}
/**
* CSS Global function to declare global styles
* @type {Function}
*/
let glob = css.bind({ g: 1 });
/**
* `keyframes` function for defining animations
* @type {Function}
*/
let keyframes = css.bind({ k: 1 });
export { css, glob, keyframes };
+3
View File
@@ -0,0 +1,3 @@
export { styled, setup } from './styled';
export { extractCss } from './core/update';
export { css, glob, keyframes } from './css';
+73
View File
@@ -0,0 +1,73 @@
import { css } from './css';
import { parse } from './core/parse';
let h, useTheme, fwdProp;
function setup(pragma, prefix, theme, forwardProps) {
// This one needs to stay in here, so we won't have cyclic dependencies
parse.p = prefix;
// These are scope to this context
h = pragma;
useTheme = theme;
fwdProp = forwardProps;
}
/**
* styled function
* @param {string} tag
* @param {function} forwardRef
*/
function styled(tag, forwardRef) {
let _ctx = this || {};
return function wrapper() {
let _args = arguments;
function Styled(props, ref) {
// Grab a shallow copy of the props
let _props = Object.assign({}, props);
// Keep a local reference to the previous className
let _previousClassName = _props.className || Styled.className;
// _ctx.p: is the props sent to the context
_ctx.p = Object.assign({ theme: useTheme && useTheme() }, _props);
// Set a flag if the current components had a previous className
// similar to goober. This is the append/prepend flag
// The _empty_ space compresses better than `\s`
_ctx.o = / *go\d+/.test(_previousClassName);
_props.className =
// Define the new className
css.apply(_ctx, _args) + (_previousClassName ? ' ' + _previousClassName : '');
// If the forwardRef fun is defined we have the ref
if (forwardRef) {
_props.ref = ref;
}
// Assign the _as with the provided `tag` value
let _as = tag;
// If this is a string -- checking that is has a first valid char
if (tag[0]) {
// Try to assign the _as with the given _as value if any
_as = _props.as || tag;
// And remove it
delete _props.as;
}
// Handle the forward props filter if defined and _as is a string
if (fwdProp && _as[0]) {
fwdProp(_props);
}
return h(_as, _props);
}
return forwardRef ? forwardRef(Styled) : Styled;
};
}
export { styled, setup };
+5
View File
@@ -0,0 +1,5 @@
{
"name": "goober",
"main": "goober.d.ts",
"version": false
}
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020 Timo Lins
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+72
View File
@@ -0,0 +1,72 @@
<a href="https://react-hot-toast.com/"><img alt="react-hot-toast - Try it out" src="https://github.com/timolins/react-hot-toast/raw/main/assets/header.svg"/></a>
<div align="center">
<img src="https://badgen.net/npm/v/react-hot-toast" alt="NPM Version" />
<img src="https://badgen.net/bundlephobia/minzip/react-hot-toast" alt="minzipped size"/>
<img src="https://github.com/timolins/react-hot-toast/workflows/CI/badge.svg" alt="Build Status" />
</a>
</div>
<br />
<div align="center"><strong>Smoking hot Notifications for React.</strong></div>
<div align="center"> Lightweight, customizable and beautiful by default.</div>
<br />
<div align="center">
<a href="https://react-hot-toast.com/">Website</a>
<span> · </span>
<a href="https://react-hot-toast.com/docs">Documentation</a>
<span> · </span>
<a href="https://twitter.com/timolins">Twitter</a>
</div>
<br />
<div align="center">
<sub>Cooked by <a href="https://twitter.com/timolins">Timo Lins</a> 👨‍🍳</sub>
</div>
<br />
## Features
- 🔥 **Hot by default**
- 🔩 **Easily Customizable**
-**Promise API** - _Automatic loader from a promise_
- 🕊 **Lightweight** - _less than 5kb including styles_
-**Accessible**
- 🤯 **Headless Hooks** - _Create your own with [`useToaster()`](https://react-hot-toast.com/docs/use-toaster)_
## Installation
#### With pnpm
```sh
pnpm add react-hot-toast
```
#### With NPM
```sh
npm install react-hot-toast
```
## Getting Started
Add the Toaster to your app first. It will take care of rendering all notifications emitted. Now you can trigger `toast()` from anywhere!
```jsx
import toast, { Toaster } from 'react-hot-toast';
const notify = () => toast('Here is your toast.');
const App = () => {
return (
<div>
<button onClick={notify}>Make me a toast</button>
<Toaster />
</div>
);
};
```
## Documentation
Find the full API reference on [official documentation](https://react-hot-toast.com/docs).
+130
View File
@@ -0,0 +1,130 @@
import * as react from 'react';
import { CSSProperties } from 'react';
import * as goober from 'goober';
type ToastType = 'success' | 'error' | 'loading' | 'blank' | 'custom';
type ToastPosition = 'top-left' | 'top-center' | 'top-right' | 'bottom-left' | 'bottom-center' | 'bottom-right';
type Renderable = React.ReactElement | string | null;
interface IconTheme {
primary: string;
secondary: string;
}
type ValueFunction<TValue, TArg> = (arg: TArg) => TValue;
type ValueOrFunction<TValue, TArg> = TValue | ValueFunction<TValue, TArg>;
declare const resolveValue: <TValue, TArg>(valOrFunction: ValueOrFunction<TValue, TArg>, arg: TArg) => TValue;
interface Toast {
type: ToastType;
id: string;
toasterId?: string;
message: ValueOrFunction<Renderable, Toast>;
icon?: Renderable;
duration?: number;
pauseDuration: number;
position?: ToastPosition;
removeDelay?: number;
ariaProps: {
role: 'status' | 'alert';
'aria-live': 'assertive' | 'off' | 'polite';
};
style?: CSSProperties;
className?: string;
iconTheme?: IconTheme;
createdAt: number;
visible: boolean;
dismissed: boolean;
height?: number;
}
type ToastOptions = Partial<Pick<Toast, 'id' | 'icon' | 'duration' | 'ariaProps' | 'className' | 'style' | 'position' | 'iconTheme' | 'toasterId' | 'removeDelay'>>;
type DefaultToastOptions = ToastOptions & {
[key in ToastType]?: ToastOptions;
};
interface ToasterProps {
position?: ToastPosition;
toastOptions?: DefaultToastOptions;
reverseOrder?: boolean;
gutter?: number;
containerStyle?: React.CSSProperties;
containerClassName?: string;
toasterId?: string;
children?: (toast: Toast) => React.ReactElement;
}
type Message = ValueOrFunction<Renderable, Toast>;
type ToastHandler = (message: Message, options?: ToastOptions) => string;
declare const toast: {
(message: Message, opts?: ToastOptions): string;
error: ToastHandler;
success: ToastHandler;
loading: ToastHandler;
custom: ToastHandler;
dismiss(toastId?: string, toasterId?: string): void;
dismissAll(toasterId?: string): void;
remove(toastId?: string, toasterId?: string): void;
removeAll(toasterId?: string): void;
promise<T>(promise: Promise<T> | (() => Promise<T>), msgs: {
loading: Renderable;
success?: ValueOrFunction<Renderable, T>;
error?: ValueOrFunction<Renderable, any>;
}, opts?: DefaultToastOptions): Promise<T>;
};
declare const useToaster: (toastOptions?: DefaultToastOptions, toasterId?: string) => {
toasts: Toast[];
handlers: {
updateHeight: (toastId: string, height: number) => void;
startPause: () => void;
endPause: () => void;
calculateOffset: (toast: Toast, opts?: {
reverseOrder?: boolean;
gutter?: number;
defaultPosition?: ToastPosition;
}) => number;
};
};
interface ToasterSettings {
toastLimit: number;
}
interface ToasterState {
toasts: Toast[];
settings: ToasterSettings;
pausedAt: number | undefined;
}
declare const useStore: (toastOptions?: DefaultToastOptions, toasterId?: string) => ToasterState;
interface ToastBarProps {
toast: Toast;
position?: ToastPosition;
style?: react.CSSProperties;
children?: (components: {
icon: Renderable;
message: Renderable;
}) => Renderable;
}
declare const ToastBar: react.FC<ToastBarProps>;
interface ErrorTheme {
primary?: string;
secondary?: string;
}
declare const ErrorIcon: goober.StyledVNode<Omit<react.ClassAttributes<HTMLDivElement> & react.HTMLAttributes<HTMLDivElement> & goober.DefaultTheme & ErrorTheme, never>>;
interface LoaderTheme {
primary?: string;
secondary?: string;
}
declare const LoaderIcon: goober.StyledVNode<Omit<react.ClassAttributes<HTMLDivElement> & react.HTMLAttributes<HTMLDivElement> & goober.DefaultTheme & LoaderTheme, never>>;
interface CheckmarkTheme {
primary?: string;
secondary?: string;
}
declare const CheckmarkIcon: goober.StyledVNode<Omit<react.ClassAttributes<HTMLDivElement> & react.HTMLAttributes<HTMLDivElement> & goober.DefaultTheme & CheckmarkTheme, never>>;
declare const ToastIcon: react.FC<{
toast: Toast;
}>;
declare const Toaster: react.FC<ToasterProps>;
export { CheckmarkIcon, DefaultToastOptions, ErrorIcon, IconTheme, LoaderIcon, Renderable, Toast, ToastBar, ToastIcon, ToastOptions, ToastPosition, ToastType, Toaster, ToasterProps, ValueFunction, ValueOrFunction, toast as default, resolveValue, toast, useToaster, useStore as useToasterStore };
+179
View File
@@ -0,0 +1,179 @@
"use client";
"use strict";var se=Object.create;var k=Object.defineProperty;var ae=Object.getOwnPropertyDescriptor;var ie=Object.getOwnPropertyNames;var ne=Object.getPrototypeOf,ce=Object.prototype.hasOwnProperty;var pe=(e,t)=>{for(var o in t)k(e,o,{get:t[o],enumerable:!0})},G=(e,t,o,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of ie(t))!ce.call(e,a)&&a!==o&&k(e,a,{get:()=>t[a],enumerable:!(s=ae(t,a))||s.enumerable});return e};var j=(e,t,o)=>(o=e!=null?se(ne(e)):{},G(t||!e||!e.__esModule?k(o,"default",{value:e,enumerable:!0}):o,e)),de=e=>G(k({},"__esModule",{value:!0}),e);var Ue={};pe(Ue,{CheckmarkIcon:()=>U,ErrorIcon:()=>C,LoaderIcon:()=>L,ToastBar:()=>N,ToastIcon:()=>$,Toaster:()=>oe,default:()=>Le,resolveValue:()=>g,toast:()=>i,useToaster:()=>M,useToasterStore:()=>w});module.exports=de(Ue);var me=e=>typeof e=="function",g=(e,t)=>me(e)?e(t):e;var J=(()=>{let e=0;return()=>(++e).toString()})(),_=(()=>{let e;return()=>{if(e===void 0&&typeof window<"u"){let t=matchMedia("(prefers-reduced-motion: reduce)");e=!t||t.matches}return e}})();var A=require("react");var le=20,Y="default";var K=(e,t)=>{let{toastLimit:o}=e.settings;switch(t.type){case 0:return{...e,toasts:[t.toast,...e.toasts].slice(0,o)};case 1:return{...e,toasts:e.toasts.map(r=>r.id===t.toast.id?{...r,...t.toast}:r)};case 2:let{toast:s}=t;return K(e,{type:e.toasts.find(r=>r.id===s.id)?1:0,toast:s});case 3:let{toastId:a}=t;return{...e,toasts:e.toasts.map(r=>r.id===a||a===void 0?{...r,dismissed:!0,visible:!1}:r)};case 4:return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(r=>r.id!==t.toastId)};case 5:return{...e,pausedAt:t.time};case 6:let n=t.time-(e.pausedAt||0);return{...e,pausedAt:void 0,toasts:e.toasts.map(r=>({...r,pauseDuration:r.pauseDuration+n}))}}},V=[],Z={toasts:[],pausedAt:void 0,settings:{toastLimit:le}},T={},ee=(e,t=Y)=>{T[t]=K(T[t]||Z,e),V.forEach(([o,s])=>{o===t&&s(T[t])})},Q=e=>Object.keys(T).forEach(t=>ee(e,t)),te=e=>Object.keys(T).find(t=>T[t].toasts.some(o=>o.id===e)),P=(e=Y)=>t=>{ee(t,e)},ue={blank:4e3,error:4e3,success:2e3,loading:1/0,custom:4e3},w=(e={},t=Y)=>{let[o,s]=(0,A.useState)(T[t]||Z),a=(0,A.useRef)(T[t]);(0,A.useEffect)(()=>(a.current!==T[t]&&s(T[t]),V.push([t,s]),()=>{let r=V.findIndex(([u])=>u===t);r>-1&&V.splice(r,1)}),[t]);let n=o.toasts.map(r=>{var u,x,y;return{...e,...e[r.type],...r,removeDelay:r.removeDelay||((u=e[r.type])==null?void 0:u.removeDelay)||(e==null?void 0:e.removeDelay),duration:r.duration||((x=e[r.type])==null?void 0:x.duration)||(e==null?void 0:e.duration)||ue[r.type],style:{...e.style,...(y=e[r.type])==null?void 0:y.style,...r.style}}});return{...o,toasts:n}};var Te=(e,t="blank",o)=>({createdAt:Date.now(),visible:!0,dismissed:!1,type:t,ariaProps:{role:"status","aria-live":"polite"},message:e,pauseDuration:0,...o,id:(o==null?void 0:o.id)||J()}),D=e=>(t,o)=>{let s=Te(t,e,o);return P(s.toasterId||te(s.id))({type:2,toast:s}),s.id},i=(e,t)=>D("blank")(e,t);i.error=D("error");i.success=D("success");i.loading=D("loading");i.custom=D("custom");i.dismiss=(e,t)=>{let o={type:3,toastId:e};t?P(t)(o):Q(o)};i.dismissAll=e=>i.dismiss(void 0,e);i.remove=(e,t)=>{let o={type:4,toastId:e};t?P(t)(o):Q(o)};i.removeAll=e=>i.remove(void 0,e);i.promise=(e,t,o)=>{let s=i.loading(t.loading,{...o,...o==null?void 0:o.loading});return typeof e=="function"&&(e=e()),e.then(a=>{let n=t.success?g(t.success,a):void 0;return n?i.success(n,{id:s,...o,...o==null?void 0:o.success}):i.dismiss(s),a}).catch(a=>{let n=t.error?g(t.error,a):void 0;n?i.error(n,{id:s,...o,...o==null?void 0:o.error}):i.dismiss(s)}),e};var l=require("react");var ye=1e3,M=(e,t="default")=>{let{toasts:o,pausedAt:s}=w(e,t),a=(0,l.useRef)(new Map).current,n=(0,l.useCallback)((c,m=ye)=>{if(a.has(c))return;let p=setTimeout(()=>{a.delete(c),r({type:4,toastId:c})},m);a.set(c,p)},[]);(0,l.useEffect)(()=>{if(s)return;let c=Date.now(),m=o.map(p=>{if(p.duration===1/0)return;let I=(p.duration||0)+p.pauseDuration-(c-p.createdAt);if(I<0){p.visible&&i.dismiss(p.id);return}return setTimeout(()=>i.dismiss(p.id,t),I)});return()=>{m.forEach(p=>p&&clearTimeout(p))}},[o,s,t]);let r=(0,l.useCallback)(P(t),[t]),u=(0,l.useCallback)(()=>{r({type:5,time:Date.now()})},[r]),x=(0,l.useCallback)((c,m)=>{r({type:1,toast:{id:c,height:m}})},[r]),y=(0,l.useCallback)(()=>{s&&r({type:6,time:Date.now()})},[s,r]),d=(0,l.useCallback)((c,m)=>{let{reverseOrder:p=!1,gutter:I=8,defaultPosition:X}=m||{},W=o.filter(f=>(f.position||X)===(c.position||X)&&f.height),re=W.findIndex(f=>f.id===c.id),q=W.filter((f,H)=>H<re&&f.visible).length;return W.filter(f=>f.visible).slice(...p?[q+1]:[0,q]).reduce((f,H)=>f+(H.height||0)+I,0)},[o]);return(0,l.useEffect)(()=>{o.forEach(c=>{if(c.dismissed)n(c.id,c.removeDelay);else{let m=a.get(c.id);m&&(clearTimeout(m),a.delete(c.id))}})},[o,n]),{toasts:o,handlers:{updateHeight:x,startPause:u,endPause:y,calculateOffset:d}}};var h=j(require("react")),v=require("goober");var S=j(require("react")),E=require("goober");var R=require("goober"),ge=R.keyframes`
from {
transform: scale(0) rotate(45deg);
opacity: 0;
}
to {
transform: scale(1) rotate(45deg);
opacity: 1;
}`,he=R.keyframes`
from {
transform: scale(0);
opacity: 0;
}
to {
transform: scale(1);
opacity: 1;
}`,xe=R.keyframes`
from {
transform: scale(0) rotate(90deg);
opacity: 0;
}
to {
transform: scale(1) rotate(90deg);
opacity: 1;
}`,C=(0,R.styled)("div")`
width: 20px;
opacity: 0;
height: 20px;
border-radius: 10px;
background: ${e=>e.primary||"#ff4b4b"};
position: relative;
transform: rotate(45deg);
animation: ${ge} 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275)
forwards;
animation-delay: 100ms;
&:after,
&:before {
content: '';
animation: ${he} 0.15s ease-out forwards;
animation-delay: 150ms;
position: absolute;
border-radius: 3px;
opacity: 0;
background: ${e=>e.secondary||"#fff"};
bottom: 9px;
left: 4px;
height: 2px;
width: 12px;
}
&:before {
animation: ${xe} 0.15s ease-out forwards;
animation-delay: 180ms;
transform: rotate(90deg);
}
`;var F=require("goober"),be=F.keyframes`
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
`,L=(0,F.styled)("div")`
width: 12px;
height: 12px;
box-sizing: border-box;
border: 2px solid;
border-radius: 100%;
border-color: ${e=>e.secondary||"#e0e0e0"};
border-right-color: ${e=>e.primary||"#616161"};
animation: ${be} 1s linear infinite;
`;var O=require("goober"),Se=O.keyframes`
from {
transform: scale(0) rotate(45deg);
opacity: 0;
}
to {
transform: scale(1) rotate(45deg);
opacity: 1;
}`,Ae=O.keyframes`
0% {
height: 0;
width: 0;
opacity: 0;
}
40% {
height: 0;
width: 6px;
opacity: 1;
}
100% {
opacity: 1;
height: 10px;
}`,U=(0,O.styled)("div")`
width: 20px;
opacity: 0;
height: 20px;
border-radius: 10px;
background: ${e=>e.primary||"#61d345"};
position: relative;
transform: rotate(45deg);
animation: ${Se} 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275)
forwards;
animation-delay: 100ms;
&:after {
content: '';
box-sizing: border-box;
animation: ${Ae} 0.2s ease-out forwards;
opacity: 0;
animation-delay: 200ms;
position: absolute;
border-right: 2px solid;
border-bottom: 2px solid;
border-color: ${e=>e.secondary||"#fff"};
bottom: 6px;
left: 6px;
height: 10px;
width: 6px;
}
`;var Pe=(0,E.styled)("div")`
position: absolute;
`,Re=(0,E.styled)("div")`
position: relative;
display: flex;
justify-content: center;
align-items: center;
min-width: 20px;
min-height: 20px;
`,Ee=E.keyframes`
from {
transform: scale(0.6);
opacity: 0.4;
}
to {
transform: scale(1);
opacity: 1;
}`,ve=(0,E.styled)("div")`
position: relative;
transform: scale(0.6);
opacity: 0.4;
min-width: 20px;
animation: ${Ee} 0.3s 0.12s cubic-bezier(0.175, 0.885, 0.32, 1.275)
forwards;
`,$=({toast:e})=>{let{icon:t,type:o,iconTheme:s}=e;return t!==void 0?typeof t=="string"?S.createElement(ve,null,t):t:o==="blank"?null:S.createElement(Re,null,S.createElement(L,{...s}),o!=="loading"&&S.createElement(Pe,null,o==="error"?S.createElement(C,{...s}):S.createElement(U,{...s})))};var De=e=>`
0% {transform: translate3d(0,${e*-200}%,0) scale(.6); opacity:.5;}
100% {transform: translate3d(0,0,0) scale(1); opacity:1;}
`,Oe=e=>`
0% {transform: translate3d(0,0,-1px) scale(1); opacity:1;}
100% {transform: translate3d(0,${e*-150}%,-1px) scale(.6); opacity:0;}
`,Ie="0%{opacity:0;} 100%{opacity:1;}",ke="0%{opacity:1;} 100%{opacity:0;}",_e=(0,v.styled)("div")`
display: flex;
align-items: center;
background: #fff;
color: #363636;
line-height: 1.3;
will-change: transform;
box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1), 0 3px 3px rgba(0, 0, 0, 0.05);
max-width: 350px;
pointer-events: auto;
padding: 8px 10px;
border-radius: 8px;
`,Ve=(0,v.styled)("div")`
display: flex;
justify-content: center;
margin: 4px 10px;
color: inherit;
flex: 1 1 auto;
white-space: pre-line;
`,we=(e,t)=>{let s=e.includes("top")?1:-1,[a,n]=_()?[Ie,ke]:[De(s),Oe(s)];return{animation:t?`${(0,v.keyframes)(a)} 0.35s cubic-bezier(.21,1.02,.73,1) forwards`:`${(0,v.keyframes)(n)} 0.4s forwards cubic-bezier(.06,.71,.55,1)`}},N=h.memo(({toast:e,position:t,style:o,children:s})=>{let a=e.height?we(e.position||t||"top-center",e.visible):{opacity:0},n=h.createElement($,{toast:e}),r=h.createElement(Ve,{...e.ariaProps},g(e.message,e));return h.createElement(_e,{className:e.className,style:{...a,...o,...e.style}},typeof s=="function"?s({icon:n,message:r}):h.createElement(h.Fragment,null,n,r))});var B=require("goober"),b=j(require("react"));(0,B.setup)(b.createElement);var Me=({id:e,className:t,style:o,onHeightUpdate:s,children:a})=>{let n=b.useCallback(r=>{if(r){let u=()=>{let x=r.getBoundingClientRect().height;s(e,x)};u(),new MutationObserver(u).observe(r,{subtree:!0,childList:!0,characterData:!0})}},[e,s]);return b.createElement("div",{ref:n,className:t,style:o},a)},Ce=(e,t)=>{let o=e.includes("top"),s=o?{top:0}:{bottom:0},a=e.includes("center")?{justifyContent:"center"}:e.includes("right")?{justifyContent:"flex-end"}:{};return{left:0,right:0,display:"flex",position:"absolute",transition:_()?void 0:"all 230ms cubic-bezier(.21,1.02,.73,1)",transform:`translateY(${t*(o?1:-1)}px)`,...s,...a}},Fe=B.css`
z-index: 9999;
> * {
pointer-events: auto;
}
`,z=16,oe=({reverseOrder:e,position:t="top-center",toastOptions:o,gutter:s,children:a,toasterId:n,containerStyle:r,containerClassName:u})=>{let{toasts:x,handlers:y}=M(o,n);return b.createElement("div",{"data-rht-toaster":n||"",style:{position:"fixed",zIndex:9999,top:z,left:z,right:z,bottom:z,pointerEvents:"none",...r},className:u,onMouseEnter:y.startPause,onMouseLeave:y.endPause},x.map(d=>{let c=d.position||t,m=y.calculateOffset(d,{reverseOrder:e,gutter:s,defaultPosition:t}),p=Ce(c,m);return b.createElement(Me,{id:d.id,key:d.id,onHeightUpdate:y.updateHeight,className:d.visible?Fe:"",style:p},d.type==="custom"?g(d.message,d):a?a(d):b.createElement(N,{toast:d,position:c}))}))};var Le=i;0&&(module.exports={CheckmarkIcon,ErrorIcon,LoaderIcon,ToastBar,ToastIcon,Toaster,resolveValue,toast,useToaster,useToasterStore});
//# sourceMappingURL=index.js.map
File diff suppressed because one or more lines are too long
+179
View File
@@ -0,0 +1,179 @@
"use client";
var Z=e=>typeof e=="function",h=(e,t)=>Z(e)?e(t):e;var W=(()=>{let e=0;return()=>(++e).toString()})(),E=(()=>{let e;return()=>{if(e===void 0&&typeof window<"u"){let t=matchMedia("(prefers-reduced-motion: reduce)");e=!t||t.matches}return e}})();import{useEffect as ee,useState as te,useRef as oe}from"react";var re=20,k="default";var H=(e,t)=>{let{toastLimit:o}=e.settings;switch(t.type){case 0:return{...e,toasts:[t.toast,...e.toasts].slice(0,o)};case 1:return{...e,toasts:e.toasts.map(r=>r.id===t.toast.id?{...r,...t.toast}:r)};case 2:let{toast:s}=t;return H(e,{type:e.toasts.find(r=>r.id===s.id)?1:0,toast:s});case 3:let{toastId:a}=t;return{...e,toasts:e.toasts.map(r=>r.id===a||a===void 0?{...r,dismissed:!0,visible:!1}:r)};case 4:return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(r=>r.id!==t.toastId)};case 5:return{...e,pausedAt:t.time};case 6:let i=t.time-(e.pausedAt||0);return{...e,pausedAt:void 0,toasts:e.toasts.map(r=>({...r,pauseDuration:r.pauseDuration+i}))}}},v=[],j={toasts:[],pausedAt:void 0,settings:{toastLimit:re}},f={},Y=(e,t=k)=>{f[t]=H(f[t]||j,e),v.forEach(([o,s])=>{o===t&&s(f[t])})},_=e=>Object.keys(f).forEach(t=>Y(e,t)),Q=e=>Object.keys(f).find(t=>f[t].toasts.some(o=>o.id===e)),S=(e=k)=>t=>{Y(t,e)},se={blank:4e3,error:4e3,success:2e3,loading:1/0,custom:4e3},V=(e={},t=k)=>{let[o,s]=te(f[t]||j),a=oe(f[t]);ee(()=>(a.current!==f[t]&&s(f[t]),v.push([t,s]),()=>{let r=v.findIndex(([l])=>l===t);r>-1&&v.splice(r,1)}),[t]);let i=o.toasts.map(r=>{var l,g,T;return{...e,...e[r.type],...r,removeDelay:r.removeDelay||((l=e[r.type])==null?void 0:l.removeDelay)||(e==null?void 0:e.removeDelay),duration:r.duration||((g=e[r.type])==null?void 0:g.duration)||(e==null?void 0:e.duration)||se[r.type],style:{...e.style,...(T=e[r.type])==null?void 0:T.style,...r.style}}});return{...o,toasts:i}};var ie=(e,t="blank",o)=>({createdAt:Date.now(),visible:!0,dismissed:!1,type:t,ariaProps:{role:"status","aria-live":"polite"},message:e,pauseDuration:0,...o,id:(o==null?void 0:o.id)||W()}),P=e=>(t,o)=>{let s=ie(t,e,o);return S(s.toasterId||Q(s.id))({type:2,toast:s}),s.id},n=(e,t)=>P("blank")(e,t);n.error=P("error");n.success=P("success");n.loading=P("loading");n.custom=P("custom");n.dismiss=(e,t)=>{let o={type:3,toastId:e};t?S(t)(o):_(o)};n.dismissAll=e=>n.dismiss(void 0,e);n.remove=(e,t)=>{let o={type:4,toastId:e};t?S(t)(o):_(o)};n.removeAll=e=>n.remove(void 0,e);n.promise=(e,t,o)=>{let s=n.loading(t.loading,{...o,...o==null?void 0:o.loading});return typeof e=="function"&&(e=e()),e.then(a=>{let i=t.success?h(t.success,a):void 0;return i?n.success(i,{id:s,...o,...o==null?void 0:o.success}):n.dismiss(s),a}).catch(a=>{let i=t.error?h(t.error,a):void 0;i?n.error(i,{id:s,...o,...o==null?void 0:o.error}):n.dismiss(s)}),e};import{useEffect as X,useCallback as A,useRef as ne}from"react";var ce=1e3,w=(e,t="default")=>{let{toasts:o,pausedAt:s}=V(e,t),a=ne(new Map).current,i=A((c,m=ce)=>{if(a.has(c))return;let p=setTimeout(()=>{a.delete(c),r({type:4,toastId:c})},m);a.set(c,p)},[]);X(()=>{if(s)return;let c=Date.now(),m=o.map(p=>{if(p.duration===1/0)return;let R=(p.duration||0)+p.pauseDuration-(c-p.createdAt);if(R<0){p.visible&&n.dismiss(p.id);return}return setTimeout(()=>n.dismiss(p.id,t),R)});return()=>{m.forEach(p=>p&&clearTimeout(p))}},[o,s,t]);let r=A(S(t),[t]),l=A(()=>{r({type:5,time:Date.now()})},[r]),g=A((c,m)=>{r({type:1,toast:{id:c,height:m}})},[r]),T=A(()=>{s&&r({type:6,time:Date.now()})},[s,r]),d=A((c,m)=>{let{reverseOrder:p=!1,gutter:R=8,defaultPosition:z}=m||{},O=o.filter(u=>(u.position||z)===(c.position||z)&&u.height),K=O.findIndex(u=>u.id===c.id),B=O.filter((u,I)=>I<K&&u.visible).length;return O.filter(u=>u.visible).slice(...p?[B+1]:[0,B]).reduce((u,I)=>u+(I.height||0)+R,0)},[o]);return X(()=>{o.forEach(c=>{if(c.dismissed)i(c.id,c.removeDelay);else{let m=a.get(c.id);m&&(clearTimeout(m),a.delete(c.id))}})},[o,i]),{toasts:o,handlers:{updateHeight:g,startPause:l,endPause:T,calculateOffset:d}}};import*as y from"react";import{styled as J,keyframes as G}from"goober";import*as b from"react";import{styled as U,keyframes as xe}from"goober";import{styled as pe,keyframes as M}from"goober";var de=M`
from {
transform: scale(0) rotate(45deg);
opacity: 0;
}
to {
transform: scale(1) rotate(45deg);
opacity: 1;
}`,me=M`
from {
transform: scale(0);
opacity: 0;
}
to {
transform: scale(1);
opacity: 1;
}`,le=M`
from {
transform: scale(0) rotate(90deg);
opacity: 0;
}
to {
transform: scale(1) rotate(90deg);
opacity: 1;
}`,C=pe("div")`
width: 20px;
opacity: 0;
height: 20px;
border-radius: 10px;
background: ${e=>e.primary||"#ff4b4b"};
position: relative;
transform: rotate(45deg);
animation: ${de} 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275)
forwards;
animation-delay: 100ms;
&:after,
&:before {
content: '';
animation: ${me} 0.15s ease-out forwards;
animation-delay: 150ms;
position: absolute;
border-radius: 3px;
opacity: 0;
background: ${e=>e.secondary||"#fff"};
bottom: 9px;
left: 4px;
height: 2px;
width: 12px;
}
&:before {
animation: ${le} 0.15s ease-out forwards;
animation-delay: 180ms;
transform: rotate(90deg);
}
`;import{styled as ue,keyframes as fe}from"goober";var Te=fe`
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
`,F=ue("div")`
width: 12px;
height: 12px;
box-sizing: border-box;
border: 2px solid;
border-radius: 100%;
border-color: ${e=>e.secondary||"#e0e0e0"};
border-right-color: ${e=>e.primary||"#616161"};
animation: ${Te} 1s linear infinite;
`;import{styled as ye,keyframes as q}from"goober";var ge=q`
from {
transform: scale(0) rotate(45deg);
opacity: 0;
}
to {
transform: scale(1) rotate(45deg);
opacity: 1;
}`,he=q`
0% {
height: 0;
width: 0;
opacity: 0;
}
40% {
height: 0;
width: 6px;
opacity: 1;
}
100% {
opacity: 1;
height: 10px;
}`,L=ye("div")`
width: 20px;
opacity: 0;
height: 20px;
border-radius: 10px;
background: ${e=>e.primary||"#61d345"};
position: relative;
transform: rotate(45deg);
animation: ${ge} 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275)
forwards;
animation-delay: 100ms;
&:after {
content: '';
box-sizing: border-box;
animation: ${he} 0.2s ease-out forwards;
opacity: 0;
animation-delay: 200ms;
position: absolute;
border-right: 2px solid;
border-bottom: 2px solid;
border-color: ${e=>e.secondary||"#fff"};
bottom: 6px;
left: 6px;
height: 10px;
width: 6px;
}
`;var be=U("div")`
position: absolute;
`,Se=U("div")`
position: relative;
display: flex;
justify-content: center;
align-items: center;
min-width: 20px;
min-height: 20px;
`,Ae=xe`
from {
transform: scale(0.6);
opacity: 0.4;
}
to {
transform: scale(1);
opacity: 1;
}`,Pe=U("div")`
position: relative;
transform: scale(0.6);
opacity: 0.4;
min-width: 20px;
animation: ${Ae} 0.3s 0.12s cubic-bezier(0.175, 0.885, 0.32, 1.275)
forwards;
`,$=({toast:e})=>{let{icon:t,type:o,iconTheme:s}=e;return t!==void 0?typeof t=="string"?b.createElement(Pe,null,t):t:o==="blank"?null:b.createElement(Se,null,b.createElement(F,{...s}),o!=="loading"&&b.createElement(be,null,o==="error"?b.createElement(C,{...s}):b.createElement(L,{...s})))};var Re=e=>`
0% {transform: translate3d(0,${e*-200}%,0) scale(.6); opacity:.5;}
100% {transform: translate3d(0,0,0) scale(1); opacity:1;}
`,Ee=e=>`
0% {transform: translate3d(0,0,-1px) scale(1); opacity:1;}
100% {transform: translate3d(0,${e*-150}%,-1px) scale(.6); opacity:0;}
`,ve="0%{opacity:0;} 100%{opacity:1;}",De="0%{opacity:1;} 100%{opacity:0;}",Oe=J("div")`
display: flex;
align-items: center;
background: #fff;
color: #363636;
line-height: 1.3;
will-change: transform;
box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1), 0 3px 3px rgba(0, 0, 0, 0.05);
max-width: 350px;
pointer-events: auto;
padding: 8px 10px;
border-radius: 8px;
`,Ie=J("div")`
display: flex;
justify-content: center;
margin: 4px 10px;
color: inherit;
flex: 1 1 auto;
white-space: pre-line;
`,ke=(e,t)=>{let s=e.includes("top")?1:-1,[a,i]=E()?[ve,De]:[Re(s),Ee(s)];return{animation:t?`${G(a)} 0.35s cubic-bezier(.21,1.02,.73,1) forwards`:`${G(i)} 0.4s forwards cubic-bezier(.06,.71,.55,1)`}},N=y.memo(({toast:e,position:t,style:o,children:s})=>{let a=e.height?ke(e.position||t||"top-center",e.visible):{opacity:0},i=y.createElement($,{toast:e}),r=y.createElement(Ie,{...e.ariaProps},h(e.message,e));return y.createElement(Oe,{className:e.className,style:{...a,...o,...e.style}},typeof s=="function"?s({icon:i,message:r}):y.createElement(y.Fragment,null,i,r))});import{css as _e,setup as Ve}from"goober";import*as x from"react";Ve(x.createElement);var we=({id:e,className:t,style:o,onHeightUpdate:s,children:a})=>{let i=x.useCallback(r=>{if(r){let l=()=>{let g=r.getBoundingClientRect().height;s(e,g)};l(),new MutationObserver(l).observe(r,{subtree:!0,childList:!0,characterData:!0})}},[e,s]);return x.createElement("div",{ref:i,className:t,style:o},a)},Me=(e,t)=>{let o=e.includes("top"),s=o?{top:0}:{bottom:0},a=e.includes("center")?{justifyContent:"center"}:e.includes("right")?{justifyContent:"flex-end"}:{};return{left:0,right:0,display:"flex",position:"absolute",transition:E()?void 0:"all 230ms cubic-bezier(.21,1.02,.73,1)",transform:`translateY(${t*(o?1:-1)}px)`,...s,...a}},Ce=_e`
z-index: 9999;
> * {
pointer-events: auto;
}
`,D=16,Fe=({reverseOrder:e,position:t="top-center",toastOptions:o,gutter:s,children:a,toasterId:i,containerStyle:r,containerClassName:l})=>{let{toasts:g,handlers:T}=w(o,i);return x.createElement("div",{"data-rht-toaster":i||"",style:{position:"fixed",zIndex:9999,top:D,left:D,right:D,bottom:D,pointerEvents:"none",...r},className:l,onMouseEnter:T.startPause,onMouseLeave:T.endPause},g.map(d=>{let c=d.position||t,m=T.calculateOffset(d,{reverseOrder:e,gutter:s,defaultPosition:t}),p=Me(c,m);return x.createElement(we,{id:d.id,key:d.id,onHeightUpdate:T.updateHeight,className:d.visible?Ce:"",style:p},d.type==="custom"?h(d.message,d):a?a(d):x.createElement(N,{toast:d,position:c}))}))};var zt=n;export{L as CheckmarkIcon,C as ErrorIcon,F as LoaderIcon,N as ToastBar,$ as ToastIcon,Fe as Toaster,zt as default,h as resolveValue,n as toast,w as useToaster,V as useToasterStore};
//# sourceMappingURL=index.mjs.map
File diff suppressed because one or more lines are too long
+93
View File
@@ -0,0 +1,93 @@
import { CSSProperties } from 'react';
type ToastType = 'success' | 'error' | 'loading' | 'blank' | 'custom';
type ToastPosition = 'top-left' | 'top-center' | 'top-right' | 'bottom-left' | 'bottom-center' | 'bottom-right';
type Renderable = React.ReactElement | string | null;
interface IconTheme {
primary: string;
secondary: string;
}
type ValueFunction<TValue, TArg> = (arg: TArg) => TValue;
type ValueOrFunction<TValue, TArg> = TValue | ValueFunction<TValue, TArg>;
declare const resolveValue: <TValue, TArg>(valOrFunction: ValueOrFunction<TValue, TArg>, arg: TArg) => TValue;
interface Toast {
type: ToastType;
id: string;
toasterId?: string;
message: ValueOrFunction<Renderable, Toast>;
icon?: Renderable;
duration?: number;
pauseDuration: number;
position?: ToastPosition;
removeDelay?: number;
ariaProps: {
role: 'status' | 'alert';
'aria-live': 'assertive' | 'off' | 'polite';
};
style?: CSSProperties;
className?: string;
iconTheme?: IconTheme;
createdAt: number;
visible: boolean;
dismissed: boolean;
height?: number;
}
type ToastOptions = Partial<Pick<Toast, 'id' | 'icon' | 'duration' | 'ariaProps' | 'className' | 'style' | 'position' | 'iconTheme' | 'toasterId' | 'removeDelay'>>;
type DefaultToastOptions = ToastOptions & {
[key in ToastType]?: ToastOptions;
};
interface ToasterProps {
position?: ToastPosition;
toastOptions?: DefaultToastOptions;
reverseOrder?: boolean;
gutter?: number;
containerStyle?: React.CSSProperties;
containerClassName?: string;
toasterId?: string;
children?: (toast: Toast) => React.ReactElement;
}
type Message = ValueOrFunction<Renderable, Toast>;
type ToastHandler = (message: Message, options?: ToastOptions) => string;
declare const toast: {
(message: Message, opts?: ToastOptions): string;
error: ToastHandler;
success: ToastHandler;
loading: ToastHandler;
custom: ToastHandler;
dismiss(toastId?: string, toasterId?: string): void;
dismissAll(toasterId?: string): void;
remove(toastId?: string, toasterId?: string): void;
removeAll(toasterId?: string): void;
promise<T>(promise: Promise<T> | (() => Promise<T>), msgs: {
loading: Renderable;
success?: ValueOrFunction<Renderable, T>;
error?: ValueOrFunction<Renderable, any>;
}, opts?: DefaultToastOptions): Promise<T>;
};
declare const useToaster: (toastOptions?: DefaultToastOptions, toasterId?: string) => {
toasts: Toast[];
handlers: {
updateHeight: (toastId: string, height: number) => void;
startPause: () => void;
endPause: () => void;
calculateOffset: (toast: Toast, opts?: {
reverseOrder?: boolean;
gutter?: number;
defaultPosition?: ToastPosition;
}) => number;
};
};
interface ToasterSettings {
toastLimit: number;
}
interface ToasterState {
toasts: Toast[];
settings: ToasterSettings;
pausedAt: number | undefined;
}
declare const useStore: (toastOptions?: DefaultToastOptions, toasterId?: string) => ToasterState;
export { DefaultToastOptions, IconTheme, Renderable, Toast, ToastOptions, ToastPosition, ToastType, ToasterProps, ValueFunction, ValueOrFunction, toast as default, resolveValue, toast, useToaster, useStore as useToasterStore };
+2
View File
@@ -0,0 +1,2 @@
"use strict";var x=Object.defineProperty;var C=Object.getOwnPropertyDescriptor;var H=Object.getOwnPropertyNames;var j=Object.prototype.hasOwnProperty;var Q=(e,t)=>{for(var s in t)x(e,s,{get:t[s],enumerable:!0})},Y=(e,t,s,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of H(t))!j.call(e,n)&&n!==s&&x(e,n,{get:()=>t[n],enumerable:!(r=C(t,n))||r.enumerable});return e};var B=e=>Y(x({},"__esModule",{value:!0}),e);var Z={};Q(Z,{default:()=>K,resolveValue:()=>A,toast:()=>i,useToaster:()=>w,useToasterStore:()=>b});module.exports=B(Z);var W=e=>typeof e=="function",A=(e,t)=>W(e)?e(t):e;var I=(()=>{let e=0;return()=>(++e).toString()})(),se=(()=>{let e;return()=>{if(e===void 0&&typeof window<"u"){let t=matchMedia("(prefers-reduced-motion: reduce)");e=!t||t.matches}return e}})();var m=require("react");var X=20,R="default";var M=(e,t)=>{let{toastLimit:s}=e.settings;switch(t.type){case 0:return{...e,toasts:[t.toast,...e.toasts].slice(0,s)};case 1:return{...e,toasts:e.toasts.map(o=>o.id===t.toast.id?{...o,...t.toast}:o)};case 2:let{toast:r}=t;return M(e,{type:e.toasts.find(o=>o.id===r.id)?1:0,toast:r});case 3:let{toastId:n}=t;return{...e,toasts:e.toasts.map(o=>o.id===n||n===void 0?{...o,dismissed:!0,visible:!1}:o)};case 4:return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(o=>o.id!==t.toastId)};case 5:return{...e,pausedAt:t.time};case 6:let T=t.time-(e.pausedAt||0);return{...e,pausedAt:void 0,toasts:e.toasts.map(o=>({...o,pauseDuration:o.pauseDuration+T}))}}},E=[],U={toasts:[],pausedAt:void 0,settings:{toastLimit:X}},p={},F=(e,t=R)=>{p[t]=M(p[t]||U,e),E.forEach(([s,r])=>{s===t&&r(p[t])})},_=e=>Object.keys(p).forEach(t=>F(e,t)),k=e=>Object.keys(p).find(t=>p[t].toasts.some(s=>s.id===e)),S=(e=R)=>t=>{F(t,e)},q={blank:4e3,error:4e3,success:2e3,loading:1/0,custom:4e3},b=(e={},t=R)=>{let[s,r]=(0,m.useState)(p[t]||U),n=(0,m.useRef)(p[t]);(0,m.useEffect)(()=>(n.current!==p[t]&&r(p[t]),E.push([t,r]),()=>{let o=E.findIndex(([f])=>f===t);o>-1&&E.splice(o,1)}),[t]);let T=s.toasts.map(o=>{var f,g,D;return{...e,...e[o.type],...o,removeDelay:o.removeDelay||((f=e[o.type])==null?void 0:f.removeDelay)||(e==null?void 0:e.removeDelay),duration:o.duration||((g=e[o.type])==null?void 0:g.duration)||(e==null?void 0:e.duration)||q[o.type],style:{...e.style,...(D=e[o.type])==null?void 0:D.style,...o.style}}});return{...s,toasts:T}};var G=(e,t="blank",s)=>({createdAt:Date.now(),visible:!0,dismissed:!1,type:t,ariaProps:{role:"status","aria-live":"polite"},message:e,pauseDuration:0,...s,id:(s==null?void 0:s.id)||I()}),y=e=>(t,s)=>{let r=G(t,e,s);return S(r.toasterId||k(r.id))({type:2,toast:r}),r.id},i=(e,t)=>y("blank")(e,t);i.error=y("error");i.success=y("success");i.loading=y("loading");i.custom=y("custom");i.dismiss=(e,t)=>{let s={type:3,toastId:e};t?S(t)(s):_(s)};i.dismissAll=e=>i.dismiss(void 0,e);i.remove=(e,t)=>{let s={type:4,toastId:e};t?S(t)(s):_(s)};i.removeAll=e=>i.remove(void 0,e);i.promise=(e,t,s)=>{let r=i.loading(t.loading,{...s,...s==null?void 0:s.loading});return typeof e=="function"&&(e=e()),e.then(n=>{let T=t.success?A(t.success,n):void 0;return T?i.success(T,{id:r,...s,...s==null?void 0:s.success}):i.dismiss(r),n}).catch(n=>{let T=t.error?A(t.error,n):void 0;T?i.error(T,{id:r,...s,...s==null?void 0:s.error}):i.dismiss(r)}),e};var c=require("react");var J=1e3,w=(e,t="default")=>{let{toasts:s,pausedAt:r}=b(e,t),n=(0,c.useRef)(new Map).current,T=(0,c.useCallback)((a,d=J)=>{if(n.has(a))return;let u=setTimeout(()=>{n.delete(a),o({type:4,toastId:a})},d);n.set(a,u)},[]);(0,c.useEffect)(()=>{if(r)return;let a=Date.now(),d=s.map(u=>{if(u.duration===1/0)return;let O=(u.duration||0)+u.pauseDuration-(a-u.createdAt);if(O<0){u.visible&&i.dismiss(u.id);return}return setTimeout(()=>i.dismiss(u.id,t),O)});return()=>{d.forEach(u=>u&&clearTimeout(u))}},[s,r,t]);let o=(0,c.useCallback)(S(t),[t]),f=(0,c.useCallback)(()=>{o({type:5,time:Date.now()})},[o]),g=(0,c.useCallback)((a,d)=>{o({type:1,toast:{id:a,height:d}})},[o]),D=(0,c.useCallback)(()=>{r&&o({type:6,time:Date.now()})},[r,o]),N=(0,c.useCallback)((a,d)=>{let{reverseOrder:u=!1,gutter:O=8,defaultPosition:V}=d||{},h=s.filter(l=>(l.position||V)===(a.position||V)&&l.height),L=h.findIndex(l=>l.id===a.id),v=h.filter((l,P)=>P<L&&l.visible).length;return h.filter(l=>l.visible).slice(...u?[v+1]:[0,v]).reduce((l,P)=>l+(P.height||0)+O,0)},[s]);return(0,c.useEffect)(()=>{s.forEach(a=>{if(a.dismissed)T(a.id,a.removeDelay);else{let d=n.get(a.id);d&&(clearTimeout(d),n.delete(a.id))}})},[s,T]),{toasts:s,handlers:{updateHeight:g,startPause:f,endPause:D,calculateOffset:N}}};var K=i;0&&(module.exports={resolveValue,toast,useToaster,useToasterStore});
//# sourceMappingURL=index.js.map
File diff suppressed because one or more lines are too long
+2
View File
@@ -0,0 +1,2 @@
var N=e=>typeof e=="function",D=(e,t)=>N(e)?e(t):e;var V=(()=>{let e=0;return()=>(++e).toString()})(),J=(()=>{let e;return()=>{if(e===void 0&&typeof window<"u"){let t=matchMedia("(prefers-reduced-motion: reduce)");e=!t||t.matches}return e}})();import{useEffect as L,useState as C,useRef as H}from"react";var j=20,h="default";var v=(e,t)=>{let{toastLimit:s}=e.settings;switch(t.type){case 0:return{...e,toasts:[t.toast,...e.toasts].slice(0,s)};case 1:return{...e,toasts:e.toasts.map(o=>o.id===t.toast.id?{...o,...t.toast}:o)};case 2:let{toast:r}=t;return v(e,{type:e.toasts.find(o=>o.id===r.id)?1:0,toast:r});case 3:let{toastId:a}=t;return{...e,toasts:e.toasts.map(o=>o.id===a||a===void 0?{...o,dismissed:!0,visible:!1}:o)};case 4:return t.toastId===void 0?{...e,toasts:[]}:{...e,toasts:e.toasts.filter(o=>o.id!==t.toastId)};case 5:return{...e,pausedAt:t.time};case 6:let T=t.time-(e.pausedAt||0);return{...e,pausedAt:void 0,toasts:e.toasts.map(o=>({...o,pauseDuration:o.pauseDuration+T}))}}},O=[],I={toasts:[],pausedAt:void 0,settings:{toastLimit:j}},l={},M=(e,t=h)=>{l[t]=v(l[t]||I,e),O.forEach(([s,r])=>{s===t&&r(l[t])})},P=e=>Object.keys(l).forEach(t=>M(e,t)),U=e=>Object.keys(l).find(t=>l[t].toasts.some(s=>s.id===e)),f=(e=h)=>t=>{M(t,e)},Q={blank:4e3,error:4e3,success:2e3,loading:1/0,custom:4e3},x=(e={},t=h)=>{let[s,r]=C(l[t]||I),a=H(l[t]);L(()=>(a.current!==l[t]&&r(l[t]),O.push([t,r]),()=>{let o=O.findIndex(([p])=>p===t);o>-1&&O.splice(o,1)}),[t]);let T=s.toasts.map(o=>{var p,A,y;return{...e,...e[o.type],...o,removeDelay:o.removeDelay||((p=e[o.type])==null?void 0:p.removeDelay)||(e==null?void 0:e.removeDelay),duration:o.duration||((A=e[o.type])==null?void 0:A.duration)||(e==null?void 0:e.duration)||Q[o.type],style:{...e.style,...(y=e[o.type])==null?void 0:y.style,...o.style}}});return{...s,toasts:T}};var B=(e,t="blank",s)=>({createdAt:Date.now(),visible:!0,dismissed:!1,type:t,ariaProps:{role:"status","aria-live":"polite"},message:e,pauseDuration:0,...s,id:(s==null?void 0:s.id)||V()}),S=e=>(t,s)=>{let r=B(t,e,s);return f(r.toasterId||U(r.id))({type:2,toast:r}),r.id},n=(e,t)=>S("blank")(e,t);n.error=S("error");n.success=S("success");n.loading=S("loading");n.custom=S("custom");n.dismiss=(e,t)=>{let s={type:3,toastId:e};t?f(t)(s):P(s)};n.dismissAll=e=>n.dismiss(void 0,e);n.remove=(e,t)=>{let s={type:4,toastId:e};t?f(t)(s):P(s)};n.removeAll=e=>n.remove(void 0,e);n.promise=(e,t,s)=>{let r=n.loading(t.loading,{...s,...s==null?void 0:s.loading});return typeof e=="function"&&(e=e()),e.then(a=>{let T=t.success?D(t.success,a):void 0;return T?n.success(T,{id:r,...s,...s==null?void 0:s.success}):n.dismiss(r),a}).catch(a=>{let T=t.error?D(t.error,a):void 0;T?n.error(T,{id:r,...s,...s==null?void 0:s.error}):n.dismiss(r)}),e};import{useEffect as F,useCallback as m,useRef as W}from"react";var X=1e3,q=(e,t="default")=>{let{toasts:s,pausedAt:r}=x(e,t),a=W(new Map).current,T=m((i,c=X)=>{if(a.has(i))return;let u=setTimeout(()=>{a.delete(i),o({type:4,toastId:i})},c);a.set(i,u)},[]);F(()=>{if(r)return;let i=Date.now(),c=s.map(u=>{if(u.duration===1/0)return;let g=(u.duration||0)+u.pauseDuration-(i-u.createdAt);if(g<0){u.visible&&n.dismiss(u.id);return}return setTimeout(()=>n.dismiss(u.id,t),g)});return()=>{c.forEach(u=>u&&clearTimeout(u))}},[s,r,t]);let o=m(f(t),[t]),p=m(()=>{o({type:5,time:Date.now()})},[o]),A=m((i,c)=>{o({type:1,toast:{id:i,height:c}})},[o]),y=m(()=>{r&&o({type:6,time:Date.now()})},[r,o]),k=m((i,c)=>{let{reverseOrder:u=!1,gutter:g=8,defaultPosition:R}=c||{},E=s.filter(d=>(d.position||R)===(i.position||R)&&d.height),w=E.findIndex(d=>d.id===i.id),_=E.filter((d,b)=>b<w&&d.visible).length;return E.filter(d=>d.visible).slice(...u?[_+1]:[0,_]).reduce((d,b)=>d+(b.height||0)+g,0)},[s]);return F(()=>{s.forEach(i=>{if(i.dismissed)T(i.id,i.removeDelay);else{let c=a.get(i.id);c&&(clearTimeout(c),a.delete(i.id))}})},[s,T]),{toasts:s,handlers:{updateHeight:A,startPause:p,endPause:y,calculateOffset:k}}};var Ae=n;export{Ae as default,D as resolveValue,n as toast,q as useToaster,x as useToasterStore};
//# sourceMappingURL=index.mjs.map
File diff suppressed because one or more lines are too long
+103
View File
@@ -0,0 +1,103 @@
{
"name": "react-hot-toast",
"description": "Smoking hot React Notifications. Lightweight, customizable and beautiful by default.",
"version": "2.6.0",
"author": "Timo Lins",
"license": "MIT",
"repository": "timolins/react-hot-toast",
"keywords": [
"react",
"notifications",
"toast",
"snackbar"
],
"main": "dist/index.js",
"types": "dist/index.d.ts",
"exports": {
"./package.json": "./package.json",
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.js"
},
"./headless": {
"types": "./headless/index.d.ts",
"import": "./headless/index.mjs",
"require": "./headless/index.js"
}
},
"files": [
"headless",
"dist",
"src"
],
"engines": {
"node": ">=10"
},
"husky": {
"hooks": {
"pre-commit": "prettier src --ignore-unknown --write"
}
},
"prettier": {
"printWidth": 80,
"semi": true,
"singleQuote": true,
"arrowParens": "always",
"trailingComma": "es5"
},
"size-limit": [
{
"path": "dist/index.js",
"limit": "5.5 KB"
},
{
"path": "dist/index.mjs",
"limit": "5.5 KB"
},
{
"path": "headless/index.js",
"limit": "2.5 KB"
},
{
"path": "headless/index.mjs",
"limit": "2.5 KB"
}
],
"devDependencies": {
"@jest/types": "^29.6.3",
"@size-limit/preset-small-lib": "^7.0.8",
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.1.0",
"@types/jest": "^29.5.14",
"@types/react": "^18.3.18",
"@types/react-dom": "^18.3.5",
"esbuild-minify-templates": "^0.13.1",
"jest": "^29.7.0",
"jest-environment-jsdom": "^29.7.0",
"prettier": "^2.8.8",
"react": "^18.3.1",
"react-dom": "^18.3.1",
"size-limit": "^7.0.8",
"ts-jest": "^29.2.5",
"tslib": "^2.8.1",
"tsup": "^6.7.0",
"typescript": "^5.7.2"
},
"dependencies": {
"csstype": "^3.1.3",
"goober": "^2.1.16"
},
"peerDependencies": {
"react": ">=16",
"react-dom": ">=16"
},
"scripts": {
"start": "tsup --watch",
"build": "tsup",
"test": "jest --runInBand",
"setup": "pnpm i && cd site && pnpm i && cd .. && pnpm run link",
"link": "pnpm link ./site/node_modules/react && pnpm link ./site/node_modules/react-dom",
"size": "size-limit"
}
}
+61
View File
@@ -0,0 +1,61 @@
import { styled, keyframes } from 'goober';
const circleAnimation = keyframes`
from {
transform: scale(0) rotate(45deg);
opacity: 0;
}
to {
transform: scale(1) rotate(45deg);
opacity: 1;
}`;
const checkmarkAnimation = keyframes`
0% {
height: 0;
width: 0;
opacity: 0;
}
40% {
height: 0;
width: 6px;
opacity: 1;
}
100% {
opacity: 1;
height: 10px;
}`;
export interface CheckmarkTheme {
primary?: string;
secondary?: string;
}
export const CheckmarkIcon = styled('div')<CheckmarkTheme>`
width: 20px;
opacity: 0;
height: 20px;
border-radius: 10px;
background: ${(p) => p.primary || '#61d345'};
position: relative;
transform: rotate(45deg);
animation: ${circleAnimation} 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275)
forwards;
animation-delay: 100ms;
&:after {
content: '';
box-sizing: border-box;
animation: ${checkmarkAnimation} 0.2s ease-out forwards;
opacity: 0;
animation-delay: 200ms;
position: absolute;
border-right: 2px solid;
border-bottom: 2px solid;
border-color: ${(p) => p.secondary || '#fff'};
bottom: 6px;
left: 6px;
height: 10px;
width: 6px;
}
`;
+71
View File
@@ -0,0 +1,71 @@
import { styled, keyframes } from 'goober';
const circleAnimation = keyframes`
from {
transform: scale(0) rotate(45deg);
opacity: 0;
}
to {
transform: scale(1) rotate(45deg);
opacity: 1;
}`;
const firstLineAnimation = keyframes`
from {
transform: scale(0);
opacity: 0;
}
to {
transform: scale(1);
opacity: 1;
}`;
const secondLineAnimation = keyframes`
from {
transform: scale(0) rotate(90deg);
opacity: 0;
}
to {
transform: scale(1) rotate(90deg);
opacity: 1;
}`;
export interface ErrorTheme {
primary?: string;
secondary?: string;
}
export const ErrorIcon = styled('div')<ErrorTheme>`
width: 20px;
opacity: 0;
height: 20px;
border-radius: 10px;
background: ${(p) => p.primary || '#ff4b4b'};
position: relative;
transform: rotate(45deg);
animation: ${circleAnimation} 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275)
forwards;
animation-delay: 100ms;
&:after,
&:before {
content: '';
animation: ${firstLineAnimation} 0.15s ease-out forwards;
animation-delay: 150ms;
position: absolute;
border-radius: 3px;
opacity: 0;
background: ${(p) => p.secondary || '#fff'};
bottom: 9px;
left: 4px;
height: 2px;
width: 12px;
}
&:before {
animation: ${secondLineAnimation} 0.15s ease-out forwards;
animation-delay: 180ms;
transform: rotate(90deg);
}
`;
+26
View File
@@ -0,0 +1,26 @@
import { styled, keyframes } from 'goober';
const rotate = keyframes`
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
`;
export interface LoaderTheme {
primary?: string;
secondary?: string;
}
export const LoaderIcon = styled('div')<LoaderTheme>`
width: 12px;
height: 12px;
box-sizing: border-box;
border: 2px solid;
border-radius: 100%;
border-color: ${(p) => p.secondary || '#e0e0e0'};
border-right-color: ${(p) => p.primary || '#616161'};
animation: ${rotate} 1s linear infinite;
`;
+111
View File
@@ -0,0 +1,111 @@
import * as React from 'react';
import { styled, keyframes } from 'goober';
import { Toast, ToastPosition, resolveValue, Renderable } from '../core/types';
import { ToastIcon } from './toast-icon';
import { prefersReducedMotion } from '../core/utils';
const enterAnimation = (factor: number) => `
0% {transform: translate3d(0,${factor * -200}%,0) scale(.6); opacity:.5;}
100% {transform: translate3d(0,0,0) scale(1); opacity:1;}
`;
const exitAnimation = (factor: number) => `
0% {transform: translate3d(0,0,-1px) scale(1); opacity:1;}
100% {transform: translate3d(0,${factor * -150}%,-1px) scale(.6); opacity:0;}
`;
const fadeInAnimation = `0%{opacity:0;} 100%{opacity:1;}`;
const fadeOutAnimation = `0%{opacity:1;} 100%{opacity:0;}`;
const ToastBarBase = styled('div')`
display: flex;
align-items: center;
background: #fff;
color: #363636;
line-height: 1.3;
will-change: transform;
box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1), 0 3px 3px rgba(0, 0, 0, 0.05);
max-width: 350px;
pointer-events: auto;
padding: 8px 10px;
border-radius: 8px;
`;
const Message = styled('div')`
display: flex;
justify-content: center;
margin: 4px 10px;
color: inherit;
flex: 1 1 auto;
white-space: pre-line;
`;
interface ToastBarProps {
toast: Toast;
position?: ToastPosition;
style?: React.CSSProperties;
children?: (components: {
icon: Renderable;
message: Renderable;
}) => Renderable;
}
const getAnimationStyle = (
position: ToastPosition,
visible: boolean
): React.CSSProperties => {
const top = position.includes('top');
const factor = top ? 1 : -1;
const [enter, exit] = prefersReducedMotion()
? [fadeInAnimation, fadeOutAnimation]
: [enterAnimation(factor), exitAnimation(factor)];
return {
animation: visible
? `${keyframes(enter)} 0.35s cubic-bezier(.21,1.02,.73,1) forwards`
: `${keyframes(exit)} 0.4s forwards cubic-bezier(.06,.71,.55,1)`,
};
};
export const ToastBar: React.FC<ToastBarProps> = React.memo(
({ toast, position, style, children }) => {
const animationStyle: React.CSSProperties = toast.height
? getAnimationStyle(
toast.position || position || 'top-center',
toast.visible
)
: { opacity: 0 };
const icon = <ToastIcon toast={toast} />;
const message = (
<Message {...toast.ariaProps}>
{resolveValue(toast.message, toast)}
</Message>
);
return (
<ToastBarBase
className={toast.className}
style={{
...animationStyle,
...style,
...toast.style,
}}
>
{typeof children === 'function' ? (
children({
icon,
message,
})
) : (
<>
{icon}
{message}
</>
)}
</ToastBarBase>
);
}
);
+77
View File
@@ -0,0 +1,77 @@
import * as React from 'react';
import { styled, keyframes } from 'goober';
import { Toast } from '../core/types';
import { ErrorIcon, ErrorTheme } from './error';
import { LoaderIcon, LoaderTheme } from './loader';
import { CheckmarkIcon, CheckmarkTheme } from './checkmark';
const StatusWrapper = styled('div')`
position: absolute;
`;
const IndicatorWrapper = styled('div')`
position: relative;
display: flex;
justify-content: center;
align-items: center;
min-width: 20px;
min-height: 20px;
`;
const enter = keyframes`
from {
transform: scale(0.6);
opacity: 0.4;
}
to {
transform: scale(1);
opacity: 1;
}`;
export const AnimatedIconWrapper = styled('div')`
position: relative;
transform: scale(0.6);
opacity: 0.4;
min-width: 20px;
animation: ${enter} 0.3s 0.12s cubic-bezier(0.175, 0.885, 0.32, 1.275)
forwards;
`;
export type IconThemes = Partial<{
success: CheckmarkTheme;
error: ErrorTheme;
loading: LoaderTheme;
}>;
export const ToastIcon: React.FC<{
toast: Toast;
}> = ({ toast }) => {
const { icon, type, iconTheme } = toast;
if (icon !== undefined) {
if (typeof icon === 'string') {
return <AnimatedIconWrapper>{icon}</AnimatedIconWrapper>;
} else {
return icon;
}
}
if (type === 'blank') {
return null;
}
return (
<IndicatorWrapper>
<LoaderIcon {...iconTheme} />
{type !== 'loading' && (
<StatusWrapper>
{type === 'error' ? (
<ErrorIcon {...iconTheme} />
) : (
<CheckmarkIcon {...iconTheme} />
)}
</StatusWrapper>
)}
</IndicatorWrapper>
);
};
+143
View File
@@ -0,0 +1,143 @@
import { css, setup } from 'goober';
import * as React from 'react';
import {
resolveValue,
ToasterProps,
ToastPosition,
ToastWrapperProps,
} from '../core/types';
import { useToaster } from '../core/use-toaster';
import { prefersReducedMotion } from '../core/utils';
import { ToastBar } from './toast-bar';
setup(React.createElement);
const ToastWrapper = ({
id,
className,
style,
onHeightUpdate,
children,
}: ToastWrapperProps) => {
const ref = React.useCallback(
(el: HTMLElement | null) => {
if (el) {
const updateHeight = () => {
const height = el.getBoundingClientRect().height;
onHeightUpdate(id, height);
};
updateHeight();
new MutationObserver(updateHeight).observe(el, {
subtree: true,
childList: true,
characterData: true,
});
}
},
[id, onHeightUpdate]
);
return (
<div ref={ref} className={className} style={style}>
{children}
</div>
);
};
const getPositionStyle = (
position: ToastPosition,
offset: number
): React.CSSProperties => {
const top = position.includes('top');
const verticalStyle: React.CSSProperties = top ? { top: 0 } : { bottom: 0 };
const horizontalStyle: React.CSSProperties = position.includes('center')
? {
justifyContent: 'center',
}
: position.includes('right')
? {
justifyContent: 'flex-end',
}
: {};
return {
left: 0,
right: 0,
display: 'flex',
position: 'absolute',
transition: prefersReducedMotion()
? undefined
: `all 230ms cubic-bezier(.21,1.02,.73,1)`,
transform: `translateY(${offset * (top ? 1 : -1)}px)`,
...verticalStyle,
...horizontalStyle,
};
};
const activeClass = css`
z-index: 9999;
> * {
pointer-events: auto;
}
`;
const DEFAULT_OFFSET = 16;
export const Toaster: React.FC<ToasterProps> = ({
reverseOrder,
position = 'top-center',
toastOptions,
gutter,
children,
toasterId,
containerStyle,
containerClassName,
}) => {
const { toasts, handlers } = useToaster(toastOptions, toasterId);
return (
<div
data-rht-toaster={toasterId || ''}
style={{
position: 'fixed',
zIndex: 9999,
top: DEFAULT_OFFSET,
left: DEFAULT_OFFSET,
right: DEFAULT_OFFSET,
bottom: DEFAULT_OFFSET,
pointerEvents: 'none',
...containerStyle,
}}
className={containerClassName}
onMouseEnter={handlers.startPause}
onMouseLeave={handlers.endPause}
>
{toasts.map((t) => {
const toastPosition = t.position || position;
const offset = handlers.calculateOffset(t, {
reverseOrder,
gutter,
defaultPosition: position,
});
const positionStyle = getPositionStyle(toastPosition, offset);
return (
<ToastWrapper
id={t.id}
key={t.id}
onHeightUpdate={handlers.updateHeight}
className={t.visible ? activeClass : ''}
style={positionStyle}
>
{t.type === 'custom' ? (
resolveValue(t.message, t)
) : children ? (
children(t)
) : (
<ToastBar toast={t} position={toastPosition} />
)}
</ToastWrapper>
);
})}
</div>
);
};
+232
View File
@@ -0,0 +1,232 @@
import { useEffect, useState, useRef } from 'react';
import { DefaultToastOptions, Toast, ToastType } from './types';
export const TOAST_EXPIRE_DISMISS_DELAY = 1000;
export const TOAST_LIMIT = 20;
export const DEFAULT_TOASTER_ID = 'default';
interface ToasterSettings {
toastLimit: number;
}
export enum ActionType {
ADD_TOAST,
UPDATE_TOAST,
UPSERT_TOAST,
DISMISS_TOAST,
REMOVE_TOAST,
START_PAUSE,
END_PAUSE,
}
export type Action =
| {
type: ActionType.ADD_TOAST;
toast: Toast;
}
| {
type: ActionType.UPSERT_TOAST;
toast: Toast;
}
| {
type: ActionType.UPDATE_TOAST;
toast: Partial<Toast>;
}
| {
type: ActionType.DISMISS_TOAST;
toastId?: string;
}
| {
type: ActionType.REMOVE_TOAST;
toastId?: string;
}
| {
type: ActionType.START_PAUSE;
time: number;
}
| {
type: ActionType.END_PAUSE;
time: number;
};
interface ToasterState {
toasts: Toast[];
settings: ToasterSettings;
pausedAt: number | undefined;
}
interface State {
[toasterId: string]: ToasterState;
}
export const reducer = (state: ToasterState, action: Action): ToasterState => {
const { toastLimit } = state.settings;
switch (action.type) {
case ActionType.ADD_TOAST:
return {
...state,
toasts: [action.toast, ...state.toasts].slice(0, toastLimit),
};
case ActionType.UPDATE_TOAST:
return {
...state,
toasts: state.toasts.map((t) =>
t.id === action.toast.id ? { ...t, ...action.toast } : t
),
};
case ActionType.UPSERT_TOAST:
const { toast } = action;
return reducer(state, {
type: state.toasts.find((t) => t.id === toast.id)
? ActionType.UPDATE_TOAST
: ActionType.ADD_TOAST,
toast,
});
case ActionType.DISMISS_TOAST:
const { toastId } = action;
return {
...state,
toasts: state.toasts.map((t) =>
t.id === toastId || toastId === undefined
? {
...t,
dismissed: true,
visible: false,
}
: t
),
};
case ActionType.REMOVE_TOAST:
if (action.toastId === undefined) {
return {
...state,
toasts: [],
};
}
return {
...state,
toasts: state.toasts.filter((t) => t.id !== action.toastId),
};
case ActionType.START_PAUSE:
return {
...state,
pausedAt: action.time,
};
case ActionType.END_PAUSE:
const diff = action.time - (state.pausedAt || 0);
return {
...state,
pausedAt: undefined,
toasts: state.toasts.map((t) => ({
...t,
pauseDuration: t.pauseDuration + diff,
})),
};
}
};
const listeners: Array<
[toasterId: string, reducer: (state: ToasterState) => void]
> = [];
const defaultToasterState: ToasterState = {
toasts: [],
pausedAt: undefined,
settings: {
toastLimit: TOAST_LIMIT,
},
};
let memoryState: State = {};
export const dispatch = (action: Action, toasterId = DEFAULT_TOASTER_ID) => {
memoryState[toasterId] = reducer(
memoryState[toasterId] || defaultToasterState,
action
);
listeners.forEach(([id, listener]) => {
if (id === toasterId) {
listener(memoryState[toasterId]);
}
});
};
export const dispatchAll = (action: Action) =>
Object.keys(memoryState).forEach((toasterId) => dispatch(action, toasterId));
export const getToasterIdFromToastId = (toastId: string) =>
Object.keys(memoryState).find((toasterId) =>
memoryState[toasterId].toasts.some((t) => t.id === toastId)
);
export const createDispatch =
(toasterId = DEFAULT_TOASTER_ID) =>
(action: Action) => {
dispatch(action, toasterId);
};
export const defaultTimeouts: {
[key in ToastType]: number;
} = {
blank: 4000,
error: 4000,
success: 2000,
loading: Infinity,
custom: 4000,
};
export const useStore = (
toastOptions: DefaultToastOptions = {},
toasterId: string = DEFAULT_TOASTER_ID
): ToasterState => {
const [state, setState] = useState<ToasterState>(
memoryState[toasterId] || defaultToasterState
);
const initial = useRef(memoryState[toasterId]);
// TODO: Switch to useSyncExternalStore when targeting React 18+
useEffect(() => {
if (initial.current !== memoryState[toasterId]) {
setState(memoryState[toasterId]);
}
listeners.push([toasterId, setState]);
return () => {
const index = listeners.findIndex(([id]) => id === toasterId);
if (index > -1) {
listeners.splice(index, 1);
}
};
}, [toasterId]);
const mergedToasts = state.toasts.map((t) => ({
...toastOptions,
...toastOptions[t.type],
...t,
removeDelay:
t.removeDelay ||
toastOptions[t.type]?.removeDelay ||
toastOptions?.removeDelay,
duration:
t.duration ||
toastOptions[t.type]?.duration ||
toastOptions?.duration ||
defaultTimeouts[t.type],
style: {
...toastOptions.style,
...toastOptions[t.type]?.style,
...t.style,
},
}));
return {
...state,
toasts: mergedToasts,
};
};
+159
View File
@@ -0,0 +1,159 @@
import {
Renderable,
Toast,
ToastOptions,
ToastType,
DefaultToastOptions,
ValueOrFunction,
resolveValue,
} from './types';
import { genId } from './utils';
import {
createDispatch,
Action,
ActionType,
dispatchAll,
getToasterIdFromToastId,
} from './store';
type Message = ValueOrFunction<Renderable, Toast>;
type ToastHandler = (message: Message, options?: ToastOptions) => string;
const createToast = (
message: Message,
type: ToastType = 'blank',
opts?: ToastOptions
): Toast => ({
createdAt: Date.now(),
visible: true,
dismissed: false,
type,
ariaProps: {
role: 'status',
'aria-live': 'polite',
},
message,
pauseDuration: 0,
...opts,
id: opts?.id || genId(),
});
const createHandler =
(type?: ToastType): ToastHandler =>
(message, options) => {
const toast = createToast(message, type, options);
const dispatch = createDispatch(
toast.toasterId || getToasterIdFromToastId(toast.id)
);
dispatch({ type: ActionType.UPSERT_TOAST, toast });
return toast.id;
};
const toast = (message: Message, opts?: ToastOptions) =>
createHandler('blank')(message, opts);
toast.error = createHandler('error');
toast.success = createHandler('success');
toast.loading = createHandler('loading');
toast.custom = createHandler('custom');
/**
* Dismisses the toast with the given id. If no id is given, dismisses all toasts.
* The toast will transition out and then be removed from the DOM.
* Applies to all toasters, except when a `toasterId` is given.
*/
toast.dismiss = (toastId?: string, toasterId?: string) => {
const action: Action = {
type: ActionType.DISMISS_TOAST,
toastId,
};
if (toasterId) {
createDispatch(toasterId)(action);
} else {
dispatchAll(action);
}
};
/**
* Dismisses all toasts.
*/
toast.dismissAll = (toasterId?: string) => toast.dismiss(undefined, toasterId);
/**
* Removes the toast with the given id.
* The toast will be removed from the DOM without any transition.
*/
toast.remove = (toastId?: string, toasterId?: string) => {
const action: Action = {
type: ActionType.REMOVE_TOAST,
toastId,
};
if (toasterId) {
createDispatch(toasterId)(action);
} else {
dispatchAll(action);
}
};
/**
* Removes all toasts.
*/
toast.removeAll = (toasterId?: string) => toast.remove(undefined, toasterId);
/**
* Create a loading toast that will automatically updates with the promise.
*/
toast.promise = <T>(
promise: Promise<T> | (() => Promise<T>),
msgs: {
loading: Renderable;
success?: ValueOrFunction<Renderable, T>;
error?: ValueOrFunction<Renderable, any>;
},
opts?: DefaultToastOptions
) => {
const id = toast.loading(msgs.loading, { ...opts, ...opts?.loading });
if (typeof promise === 'function') {
promise = promise();
}
promise
.then((p) => {
const successMessage = msgs.success
? resolveValue(msgs.success, p)
: undefined;
if (successMessage) {
toast.success(successMessage, {
id,
...opts,
...opts?.success,
});
} else {
toast.dismiss(id);
}
return p;
})
.catch((e) => {
const errorMessage = msgs.error ? resolveValue(msgs.error, e) : undefined;
if (errorMessage) {
toast.error(errorMessage, {
id,
...opts,
...opts?.error,
});
} else {
toast.dismiss(id);
}
});
return promise;
};
export { toast };
+97
View File
@@ -0,0 +1,97 @@
import { CSSProperties } from 'react';
export type ToastType = 'success' | 'error' | 'loading' | 'blank' | 'custom';
export type ToastPosition =
| 'top-left'
| 'top-center'
| 'top-right'
| 'bottom-left'
| 'bottom-center'
| 'bottom-right';
export type Renderable = React.ReactElement | string | null;
export interface IconTheme {
primary: string;
secondary: string;
}
export type ValueFunction<TValue, TArg> = (arg: TArg) => TValue;
export type ValueOrFunction<TValue, TArg> =
| TValue
| ValueFunction<TValue, TArg>;
const isFunction = <TValue, TArg>(
valOrFunction: ValueOrFunction<TValue, TArg>
): valOrFunction is ValueFunction<TValue, TArg> =>
typeof valOrFunction === 'function';
export const resolveValue = <TValue, TArg>(
valOrFunction: ValueOrFunction<TValue, TArg>,
arg: TArg
): TValue => (isFunction(valOrFunction) ? valOrFunction(arg) : valOrFunction);
export interface Toast {
type: ToastType;
id: string;
toasterId?: string;
message: ValueOrFunction<Renderable, Toast>;
icon?: Renderable;
duration?: number;
pauseDuration: number;
position?: ToastPosition;
removeDelay?: number;
ariaProps: {
role: 'status' | 'alert';
'aria-live': 'assertive' | 'off' | 'polite';
};
style?: CSSProperties;
className?: string;
iconTheme?: IconTheme;
createdAt: number;
visible: boolean;
dismissed: boolean;
height?: number;
}
export type ToastOptions = Partial<
Pick<
Toast,
| 'id'
| 'icon'
| 'duration'
| 'ariaProps'
| 'className'
| 'style'
| 'position'
| 'iconTheme'
| 'toasterId'
| 'removeDelay'
>
>;
export type DefaultToastOptions = ToastOptions & {
[key in ToastType]?: ToastOptions;
};
export interface ToasterProps {
position?: ToastPosition;
toastOptions?: DefaultToastOptions;
reverseOrder?: boolean;
gutter?: number;
containerStyle?: React.CSSProperties;
containerClassName?: string;
toasterId?: string;
children?: (toast: Toast) => React.ReactElement;
}
export interface ToastWrapperProps {
id: string;
className?: string;
style?: React.CSSProperties;
onHeightUpdate: (id: string, height: number) => void;
children?: React.ReactNode;
}
+145
View File
@@ -0,0 +1,145 @@
import { useEffect, useCallback, useRef } from 'react';
import { createDispatch, ActionType, useStore, dispatch } from './store';
import { toast } from './toast';
import { DefaultToastOptions, Toast, ToastPosition } from './types';
export const REMOVE_DELAY = 1000;
export const useToaster = (
toastOptions?: DefaultToastOptions,
toasterId: string = 'default'
) => {
const { toasts, pausedAt } = useStore(toastOptions, toasterId);
const toastTimeouts = useRef(
new Map<Toast['id'], ReturnType<typeof setTimeout>>()
).current;
const addToRemoveQueue = useCallback(
(toastId: string, removeDelay = REMOVE_DELAY) => {
if (toastTimeouts.has(toastId)) {
return;
}
const timeout = setTimeout(() => {
toastTimeouts.delete(toastId);
dispatch({
type: ActionType.REMOVE_TOAST,
toastId: toastId,
});
}, removeDelay);
toastTimeouts.set(toastId, timeout);
},
[]
);
useEffect(() => {
if (pausedAt) {
return;
}
const now = Date.now();
const timeouts = toasts.map((t) => {
if (t.duration === Infinity) {
return;
}
const durationLeft =
(t.duration || 0) + t.pauseDuration - (now - t.createdAt);
if (durationLeft < 0) {
if (t.visible) {
toast.dismiss(t.id);
}
return;
}
return setTimeout(() => toast.dismiss(t.id, toasterId), durationLeft);
});
return () => {
timeouts.forEach((timeout) => timeout && clearTimeout(timeout));
};
}, [toasts, pausedAt, toasterId]);
const dispatch = useCallback(createDispatch(toasterId), [toasterId]);
const startPause = useCallback(() => {
dispatch({
type: ActionType.START_PAUSE,
time: Date.now(),
});
}, [dispatch]);
const updateHeight = useCallback(
(toastId: string, height: number) => {
dispatch({
type: ActionType.UPDATE_TOAST,
toast: { id: toastId, height },
});
},
[dispatch]
);
const endPause = useCallback(() => {
if (pausedAt) {
dispatch({ type: ActionType.END_PAUSE, time: Date.now() });
}
}, [pausedAt, dispatch]);
const calculateOffset = useCallback(
(
toast: Toast,
opts?: {
reverseOrder?: boolean;
gutter?: number;
defaultPosition?: ToastPosition;
}
) => {
const { reverseOrder = false, gutter = 8, defaultPosition } = opts || {};
const relevantToasts = toasts.filter(
(t) =>
(t.position || defaultPosition) ===
(toast.position || defaultPosition) && t.height
);
const toastIndex = relevantToasts.findIndex((t) => t.id === toast.id);
const toastsBefore = relevantToasts.filter(
(toast, i) => i < toastIndex && toast.visible
).length;
const offset = relevantToasts
.filter((t) => t.visible)
.slice(...(reverseOrder ? [toastsBefore + 1] : [0, toastsBefore]))
.reduce((acc, t) => acc + (t.height || 0) + gutter, 0);
return offset;
},
[toasts]
);
// Keep track of dismissed toasts and remove them after the delay
useEffect(() => {
toasts.forEach((toast) => {
if (toast.dismissed) {
addToRemoveQueue(toast.id, toast.removeDelay);
} else {
// If toast becomes visible again, remove it from the queue
const timeout = toastTimeouts.get(toast.id);
if (timeout) {
clearTimeout(timeout);
toastTimeouts.delete(toast.id);
}
}
});
}, [toasts, addToRemoveQueue]);
return {
toasts,
handlers: {
updateHeight,
startPause,
endPause,
calculateOffset,
},
};
};
+19
View File
@@ -0,0 +1,19 @@
export const genId = (() => {
let count = 0;
return () => {
return (++count).toString();
};
})();
export const prefersReducedMotion = (() => {
// Cache result
let shouldReduceMotion: boolean | undefined = undefined;
return () => {
if (shouldReduceMotion === undefined && typeof window !== 'undefined') {
const mediaQuery = matchMedia('(prefers-reduced-motion: reduce)');
shouldReduceMotion = !mediaQuery || mediaQuery.matches;
}
return shouldReduceMotion;
};
})();
+21
View File
@@ -0,0 +1,21 @@
import { toast } from '../core/toast';
export type {
DefaultToastOptions,
IconTheme,
Renderable,
Toast,
ToasterProps,
ToastOptions,
ToastPosition,
ToastType,
ValueFunction,
ValueOrFunction,
} from '../core/types';
export { resolveValue } from '../core/types';
export { useToaster } from '../core/use-toaster';
export { useStore as useToasterStore } from '../core/store';
export { toast };
export default toast;
+13
View File
@@ -0,0 +1,13 @@
import { toast } from './core/toast';
export * from './headless';
export { ToastBar } from './components/toast-bar';
export { ToastIcon } from './components/toast-icon';
export { Toaster } from './components/toaster';
export { CheckmarkIcon } from './components/checkmark';
export { ErrorIcon } from './components/error';
export { LoaderIcon } from './components/loader';
export { toast };
export default toast;