UNPKG

toast-ease

Version:

An opinionated toast component.

1 lines 15.2 kB
{"version":3,"sources":["../src/toast.tsx","../src/state.ts","#style-inject:#style-inject","../src/tailwind.css"],"sourcesContent":["\"use client\";\nimport React, { useEffect, useRef, useState } from \"react\";\nimport { state, toast } from \"./state\";\nimport \"./tailwind.css\";\nimport { Toast, Toasts } from \"./types\";\n\nconst TOASTS_VISIBLE = 4; // The variable is used to control the numbers of toasts that would be visible.\nconst TOAST_LIFESPAN = 2; // 2 seconds\n\ntype ToastItemProps = Toast;\n\nconst ToastItem = function (toast: ToastItemProps) {\n const toastRef = useRef<HTMLLIElement>(null);\n\n useEffect(\n function () {\n if (!toastRef.current) return;\n\n const { height } = toastRef.current.getBoundingClientRect();\n toastRef.current.style.setProperty(\n \"--toast-height\",\n `${Number(height) * 2}px`\n );\n },\n [toastRef]\n );\n\n return (\n <li ref={toastRef} className=\"toast\">\n {toast.title}\n </li>\n );\n};\n\ntype ToastBoxProps = {\n duration: number;\n toastsVisible: number;\n};\n\nconst ToastBox = function (props: Partial<ToastBoxProps>) {\n const { duration = TOAST_LIFESPAN, toastsVisible = TOASTS_VISIBLE } = props;\n\n const [toasts, setToasts] = useState<Toasts>(state.globalToasts);\n const [componentMounted, setComponentMounted] = useState<boolean>(false);\n\n // Once the component is loaded, marking the component has loaded.\n useEffect(function () {\n setComponentMounted(true);\n }, []);\n\n // Once the component has been loaded, subscribe to the changes in the state.\n useEffect(\n function () {\n if (!componentMounted) return;\n\n state.subscribe((toast) => {\n // Appending the recently added toast to the list.\n setToasts((toasts) => [toast, ...toasts]);\n });\n },\n [componentMounted]\n );\n\n // Setting up listeners to remove the toast, after a defined time interval.\n useEffect(\n function () {\n toasts.forEach((toast) => {\n if (toast.duration === Infinity && !toast.dismisable) {\n markToastDismisable(toast);\n\n setTimeout(() => {\n deleteToast(toast);\n }, duration * 1000);\n }\n });\n },\n [toasts]\n );\n\n const markToastDismisable = (target: Toast) => {\n setToasts((toasts) =>\n toasts.map((toast) => {\n if (toast.id === target.id) {\n return {\n ...toast,\n dismisable: true,\n duration: TOAST_LIFESPAN,\n };\n }\n\n return toast;\n })\n );\n };\n const deleteToast = (target: Toast) => {\n setToasts((toasts) =>\n toasts.filter((toast) => {\n if (toast.id !== target.id) {\n return true;\n }\n\n return false;\n })\n );\n };\n\n return (\n <section className=\"absolute w-screen h-screen bg-transparent overflow-hidden top-0 left-0 bottom-0 right-0 z-[999] pointer-events-none\">\n <div className=\"relative w-screen h-screen\">\n <ol className=\"absolute bottom-0 right-0 p-4\">\n {toasts.slice(0, toastsVisible).map((toast) => (\n <ToastItem {...toast} key={toast.id} />\n ))}\n </ol>\n </div>\n </section>\n );\n};\n\nexport { ToastBox, ToastItem, toast };\n","import { nanoid } from \"nanoid\";\nimport {\n SubscriberFn,\n Toast,\n ToastIndicator,\n ToastInternalProperties,\n Toasts,\n} from \"./types\";\n\nclass Observable {\n private toasts: Toasts;\n private subscribers: Array<SubscriberFn>;\n\n get globalToasts() {\n return this.toasts;\n }\n\n public constructor() {\n this.toasts = [];\n this.subscribers = [];\n }\n\n /**\n * The function allows entities to register a subscriber that\n * allows entities to listen to changes in state.\n */\n public subscribe(subscriberFn: SubscriberFn) {\n this.subscribers.push(subscriberFn);\n }\n\n /**\n * The function is responsible for notifying the subscriber\n * that a new toast has been added.\n *\n * NOTE: the state is managed by the subscribers and independent of the\n * global state.\n *\n */\n public createToast(\n toast: Omit<Toast, ToastInternalProperties>,\n indicator: ToastIndicator\n ) {\n const { description, title } = toast;\n\n const toastObject: Toast = {\n id: nanoid(),\n dismisable: false,\n\n title,\n indicator,\n description,\n duration: Infinity,\n };\n\n // Adding the toast to the global state.\n this.toasts = [toastObject, ...this.toasts];\n\n // Notifying the subscribers about the creation of the toast.\n this.subscribers.forEach((subscriber) => {\n subscriber(toastObject);\n });\n }\n}\nexport const state = new Observable();\n\nconst basicCreateFn =\n (indicator: ToastIndicator = ToastIndicator.info) =>\n (toast: Omit<Toast, ToastInternalProperties>) =>\n state.createToast(toast, indicator);\n\nexport const toast = Object.assign(basicCreateFn(), {\n info: basicCreateFn(ToastIndicator.info),\n warn: basicCreateFn(ToastIndicator.warn),\n error: basicCreateFn(ToastIndicator.error),\n success: basicCreateFn(ToastIndicator.success),\n});\n","\n export default function styleInject(css, { insertAt } = {}) {\n if (!css || typeof document === 'undefined') return\n \n const head = document.head || document.getElementsByTagName('head')[0]\n const style = document.createElement('style')\n style.type = 'text/css'\n \n if (insertAt === 'top') {\n if (head.firstChild) {\n head.insertBefore(style, head.firstChild)\n } else {\n head.appendChild(style)\n }\n } else {\n head.appendChild(style)\n }\n \n if (style.styleSheet) {\n style.styleSheet.cssText = css\n } else {\n style.appendChild(document.createTextNode(css))\n }\n }\n ","import styleInject from '#style-inject';styleInject(\"*,:before,:after{box-sizing:border-box;border-width:0;border-style:solid;border-color:#e5e7eb}:before,:after{--tw-content: \\\"\\\"}html,:host{line-height:1.5;-webkit-text-size-adjust:100%;-moz-tab-size:4;-o-tab-size:4;tab-size:4;font-family:ui-sans-serif,system-ui,sans-serif,\\\"Apple Color Emoji\\\",\\\"Segoe UI Emoji\\\",Segoe UI Symbol,\\\"Noto Color Emoji\\\";font-feature-settings:normal;font-variation-settings:normal;-webkit-tap-highlight-color:transparent}body{margin:0;line-height:inherit}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,Liberation Mono,Courier New,monospace;font-feature-settings:normal;font-variation-settings:normal;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}button,input,optgroup,select,textarea{font-family:inherit;font-feature-settings:inherit;font-variation-settings:inherit;font-size:100%;font-weight:inherit;line-height:inherit;letter-spacing:inherit;color:inherit;margin:0;padding:0}button,select{text-transform:none}button,input:where([type=button]),input:where([type=reset]),input:where([type=submit]){-webkit-appearance:button;background-color:transparent;background-image:none}:-moz-focusring{outline:auto}:-moz-ui-invalid{box-shadow:none}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}[type=search]{-webkit-appearance:textfield;outline-offset:-2px}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}fieldset{margin:0;padding:0}legend{padding:0}ol,ul,menu{list-style:none;margin:0;padding:0}dialog{padding:0}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button,[role=button]{cursor:pointer}:disabled{cursor:default}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}[hidden]{display:none}*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-gradient-from-position: ;--tw-gradient-via-position: ;--tw-gradient-to-position: ;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: ;--tw-contain-size: ;--tw-contain-layout: ;--tw-contain-paint: ;--tw-contain-style: }.\\\\!toast{--toast-height: auto !important;--animation-duration: 3s !important}.toast{--toast-height: auto;--animation-duration: 3s}.\\\\!toast,.toast{margin-left:auto;margin-top:.5rem;width:100%;max-width:20rem;border-radius:.25rem;border-width:1px;--tw-bg-opacity: 1;background-color:rgb(255 255 255 / var(--tw-bg-opacity));padding:.75rem}.\\\\!toast{animation-name:toastAnimation!important;animation-fill-mode:forwards!important;animation-timing-function:ease-in-out!important;animation-duration:var(--animation-duration)!important}.toast{animation-name:toastAnimation;animation-fill-mode:forwards;animation-timing-function:ease-in-out;animation-duration:var(--animation-duration)}@keyframes toastAnimation{0%{opacity:0;height:0px;transform:translateY(-50%)}10%{opacity:1;transform:translateY(0);height:var(--toast-height)}}.pointer-events-none{pointer-events:none}.visible{visibility:visible}.absolute{position:absolute}.relative{position:relative}.bottom-0{bottom:0}.left-0{left:0}.right-0{right:0}.top-0{top:0}.z-\\\\[999\\\\]{z-index:999}.h-screen{height:100vh}.w-screen{width:100vw}.overflow-hidden{overflow:hidden}.bg-transparent{background-color:transparent}.p-4{padding:1rem}.filter{filter:var(--tw-blur) var(--tw-brightness) var(--tw-contrast) var(--tw-grayscale) var(--tw-hue-rotate) var(--tw-invert) var(--tw-saturate) var(--tw-sepia) var(--tw-drop-shadow)}\\n\")"],"mappings":"AACA,OAAOA,GAAS,aAAAC,EAAW,UAAAC,EAAQ,YAAAC,MAAgB,QCDnD,OAAS,UAAAC,MAAc,SASvB,IAAMC,EAAN,KAAiB,CAIf,IAAI,cAAe,CACjB,OAAO,KAAK,MACd,CAEO,aAAc,CACnB,KAAK,OAAS,CAAC,EACf,KAAK,YAAc,CAAC,CACtB,CAMO,UAAUC,EAA4B,CAC3C,KAAK,YAAY,KAAKA,CAAY,CACpC,CAUO,YACLC,EACAC,EACA,CACA,GAAM,CAAE,YAAAC,EAAa,MAAAC,CAAM,EAAIH,EAEzBI,EAAqB,CACzB,GAAIC,EAAO,EACX,WAAY,GAEZ,MAAAF,EACA,UAAAF,EACA,YAAAC,EACA,SAAU,GACZ,EAGA,KAAK,OAAS,CAACE,EAAa,GAAG,KAAK,MAAM,EAG1C,KAAK,YAAY,QAASE,GAAe,C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M,YAAY,EACzD,CAACC,EAAkBC,CAAmB,EAAIH,EAAkB,EAAK,EAGvET,EAAU,UAAY,CACpBY,EAAoB,EAAI,CAC1B,EAAG,CAAC,CAAC,EAGLZ,EACE,UAAY,CACLW,GAELD,EAAM,UAAWb,GAAU,CAEzBW,EAAWD,GAAW,CAACV,EAAO,GAAGU,CAAM,CAAC,CAC1C,CAAC,CACH,EACA,CAACI,CAAgB,CACnB,EAGAX,EACE,UAAY,CACVO,EAAO,QAASV,GAAU,CACpBA,EAAM,WAAa,KAAY,CAACA,EAAM,aACxCgB,EAAoBhB,CAAK,EAEzB,WAAW,IAAM,CACfiB,EAAYjB,CAAK,CACnB,EAAGQ,EAAW,GAAI,EAEtB,CAAC,CACH,EACA,CAACE,CAAM,CACT,EAEA,IAAMM,EAAuBE,GAAkB,CAC7CP,EAAWD,GACTA,EAAO,IAAKV,GACNA,EAAM,KAAOkB,EAAO,GACf,CACL,GAAGlB,EACH,WAAY,GACZ,SAAUF,CACZ,EAGKE,CACR,CACH,CACF,EACMiB,EAAeC,GAAkB,CACrCP,EAAWD,GACTA,EAAO,OAAQV,GACTA,EAAM,KAAOkB,EAAO,EAKzB,CACH,CACF,EAEA,OACEb,EAAA,cAAC,WAAQ,UAAU,uHACjBA,EAAA,cAAC,OAAI,UAAU,8BACbA,EAAA,cAAC,MAAG,UAAU,iCACXK,EAAO,MAAM,EAAGD,CAAa,EAAE,IAAKT,GACnCK,EAAA,cAACN,EAAA,CAAW,GAAGC,EAAO,IAAKA,EAAM,GAAI,CACtC,CACH,CACF,CACF,CAEJ","names":["React","useEffect","useRef","useState","nanoid","Observable","subscriberFn","toast","indicator","description","title","toastObject","nanoid","subscriber","state","basicCreateFn","styleInject","css","insertAt","head","style","styleInject","TOASTS_VISIBLE","TOAST_LIFESPAN","ToastItem","toast","toastRef","useRef","useEffect","height","React","ToastBox","props","duration","toastsVisible","toasts","setToasts","useState","state","componentMounted","setComponentMounted","markToastDismisable","deleteToast","target"]}