Skip to content

armgit / dub

Public Imported from GitHub
0

The modern link attribution platform. Loved by world-class engineering teams at Twilio, Zillow, Jobber, Vercel, Raycast, and more.

Add preview section

Tim Wilson726b446575ec
diff --git a/apps/web/ui/modals/add-edit-link-modal-new/index.tsx b/apps/web/ui/modals/add-edit-link-modal-new/index.tsx
index 26d879c2b7..f804730a57 100644
--- a/apps/web/ui/modals/add-edit-link-modal-new/index.tsx
+++ b/apps/web/ui/modals/add-edit-link-modal-new/index.tsx
@@ -29,25 +29,48 @@ import {
import { useParams, useSearchParams } from "next/navigation";
import posthog from "posthog-js";
import { Dispatch, SetStateAction, useEffect, useMemo, useRef } from "react";
-import { Controller, useForm } from "react-hook-form";
+import {
+ Controller,
+ FormProvider,
+ useForm,
+ useFormContext,
+} from "react-hook-form";
import TextareaAutosize from "react-textarea-autosize";
import { toast } from "sonner";
import { mutate } from "swr";
import { useDebounce } from "use-debounce";
+import { LinkPreview } from "./link-preview";
+import { useMetatags } from "./use-metatags";
-export function AddEditLinkModal({
- showAddEditLinkModal,
- setShowAddEditLinkModal,
- props,
- duplicateProps,
- homepageDemo,
-}: {
+export type LinkFormData = LinkWithTagsProps;
+
+type AddEditLinkModalProps = {
showAddEditLinkModal: boolean;
setShowAddEditLinkModal: Dispatch<SetStateAction<boolean>>;
props?: LinkWithTagsProps;
duplicateProps?: LinkWithTagsProps;
homepageDemo?: boolean;
-}) {
+};
+
+export function AddEditLinkModal(props: AddEditLinkModalProps) {
+ const form = useForm<LinkFormData>({
+ defaultValues: props.props || props.duplicateProps || DEFAULT_LINK_PROPS,
+ });
+
+ return (
+ <FormProvider {...form}>
+ <AddEditLinkModalInner {...props} />
+ </FormProvider>
+ );
+}
+
+function AddEditLinkModalInner({
+ showAddEditLinkModal,
+ setShowAddEditLinkModal,
+ props,
+ duplicateProps,
+ homepageDemo,
+}: AddEditLinkModalProps) {
const params = useParams() as { slug?: string };
const { slug } = params;
const searchParams = useSearchParams();
@@ -62,9 +85,7 @@ export function AddEditLinkModal({
setError,
clearErrors,
formState: { isSubmitting, isSubmitSuccessful, errors },
- } = useForm<LinkWithTagsProps>({
- defaultValues: props || duplicateProps || DEFAULT_LINK_PROPS,
- });
+ } = useFormContext<LinkFormData>();
const data = watch();
const { url, domain, key, proxy } = data;
@@ -84,6 +105,11 @@ export function AddEditLinkModal({
[props, slug, domain, workspaceId],
);
+ const { generatingMetatags } = useMetatags({
+ initial: Boolean(props),
+ enabled: showAddEditLinkModal && !proxy && debouncedUrl.length > 0,
+ });
+
const saveDisabled = useMemo(() => {
/*
Disable save if:
@@ -343,7 +369,9 @@ export function AddEditLinkModal({
<div className="scrollbar-hide px-6 md:max-h-[95dvh] md:overflow-auto md:pl-0 md:pr-4">
<div className="relative">
<div className="absolute inset-0 rounded-xl border border-gray-200 bg-gray-50 [mask-image:linear-gradient(to_bottom,black,transparent)]"></div>
- <div className="relative min-h-[300px] p-4"></div>
+ <div className="relative min-h-[300px] p-4">
+ <LinkPreview generatingMetatags={generatingMetatags} />
+ </div>
</div>
</div>
</div>
diff --git a/apps/web/ui/modals/add-edit-link-modal-new/link-preview.tsx b/apps/web/ui/modals/add-edit-link-modal-new/link-preview.tsx
new file mode 100644
index 0000000000..77f366ba86
--- /dev/null
+++ b/apps/web/ui/modals/add-edit-link-modal-new/link-preview.tsx
@@ -0,0 +1,382 @@
+import {
+ Button,
+ FileUpload,
+ Icon,
+ LoadingCircle,
+ ShimmerDots,
+ useMediaQuery,
+} from "@dub/ui";
+import {
+ Facebook,
+ GlobePointer,
+ LinkedIn,
+ NucleoPhoto,
+ Pen2,
+ Twitter,
+} from "@dub/ui/src/icons";
+import { cn, getDomainWithoutWWW, resizeImage } from "@dub/utils";
+import {
+ ChangeEvent,
+ ComponentType,
+ PropsWithChildren,
+ useCallback,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import { useFormContext } from "react-hook-form";
+import ReactTextareaAutosize from "react-textarea-autosize";
+import { toast } from "sonner";
+import { useDebounce } from "use-debounce";
+import { LinkFormData } from ".";
+
+const tabs = ["default", "facebook", "linkedin", "x"] as const;
+type Tab = (typeof tabs)[number];
+
+const tabTitles: Record<Tab, string> = {
+ default: "Default",
+ facebook: "Facebook",
+ linkedin: "LinkedIn",
+ x: "X/Twitter",
+};
+
+const tabIcons: Record<Tab, Icon> = {
+ default: GlobePointer,
+ facebook: Facebook,
+ linkedin: LinkedIn,
+ x: Twitter,
+};
+
+type OGPreviewProps = PropsWithChildren<{
+ title: string | null;
+ description: string | null;
+ hostname: string | null;
+ password: string | null;
+}>;
+
+const tabComponents: Record<Tab, ComponentType<OGPreviewProps>> = {
+ default: DefaultOGPreview,
+ facebook: FacebookOGPreview,
+ linkedin: LinkedInOGPreview,
+ x: XOGPreview,
+};
+
+export function LinkPreview({
+ generatingMetatags,
+}: {
+ generatingMetatags: boolean;
+}) {
+ const { watch, setValue } = useFormContext<LinkFormData>();
+ const { title, description, image, url, password } = watch();
+
+ const [debouncedUrl] = useDebounce(url, 500);
+ const hostname = useMemo(() => {
+ if (password) return "dub.co";
+ return getDomainWithoutWWW(debouncedUrl) ?? null;
+ }, [password, debouncedUrl]);
+
+ const [selectedTab, setSelectedTab] = useState<Tab>("default");
+
+ const onImageChange = (image: string) => {
+ setValue("image", image);
+ setValue("proxy", true);
+ };
+
+ const OGPreview = tabComponents[selectedTab];
+
+ return (
+ <div>
+ <div className="flex items-center justify-between">
+ <h2 className="text-sm font-medium text-gray-700">Link Preview</h2>
+ <Button
+ type="button"
+ variant="outline"
+ icon={<Pen2 className="mx-px size-4" />}
+ className="h-7 w-fit px-1"
+ onClick={() => toast.info("WIP")}
+ />
+ </div>
+ <div className="mt-2.5 grid grid-cols-4 gap-2">
+ {tabs.map((tab) => {
+ const Icon = tabIcons[tab];
+ return (
+ <Button
+ key={tab}
+ variant="secondary"
+ onClick={() => setSelectedTab(tab)}
+ icon={
+ <Icon className="size-4 text-current" fill="currentColor" />
+ }
+ className={cn(
+ "h-7 text-gray-800",
+ tab === selectedTab
+ ? "border-gray-400 bg-white drop-shadow-sm"
+ : "border-gray-300 bg-transparent hover:bg-white",
+ )}
+ title={tabTitles[tab]}
+ />
+ );
+ })}
+ </div>
+ <div className="mt-2">
+ <OGPreview
+ title={title}
+ description={description}
+ hostname={hostname}
+ password={password}
+ >
+ <ImagePreview
+ image={image}
+ onImageChange={onImageChange}
+ generatingMetatags={generatingMetatags}
+ />
+ </OGPreview>
+ </div>
+ </div>
+ );
+}
+
+const ImagePreview = ({
+ image,
+ onImageChange,
+ generatingMetatags,
+}: {
+ image: string | null;
+ onImageChange: (image: string) => void;
+ generatingMetatags?: boolean;
+}) => {
+ const { isMobile } = useMediaQuery();
+
+ const inputFileRef = useRef<HTMLInputElement>(null);
+
+ const [resizing, setResizing] = useState(false);
+
+ const onInputFileChange = useCallback(
+ async (e: ChangeEvent<HTMLInputElement>) => {
+ const file = e.target.files && e.target.files[0];
+ if (!file) return;
+
+ if (file.size / 1024 / 1024 > 2) {
+ toast.error(`File size too big (max 2 MB)`);
+ return;
+ }
+
+ setResizing(true);
+
+ const src = await resizeImage(file);
+ onImageChange(src);
+
+ // Delay to prevent flickering
+ setTimeout(() => setResizing(false), 500);
+ },
+ [],
+ );
+
+ const previewImage = useMemo(() => {
+ if (generatingMetatags || resizing) {
+ return (
+ <div className="flex aspect-[1200/630] w-full flex-col items-center justify-center bg-gray-100">
+ <LoadingCircle />
+ </div>
+ );
+ }
+ if (image) {
+ return (
+ <FileUpload
+ accept="images"
+ variant="plain"
+ imageSrc={image}
+ onChange={async ({ file }) => {
+ setResizing(true);
+
+ onImageChange(await resizeImage(file));
+
+ // Delay to prevent flickering
+ setTimeout(() => setResizing(false), 500);
+ }}
+ loading={generatingMetatags || resizing}
+ clickToUpload={false}
+ showHoverOverlay={false}
+ accessibilityLabel="OG image upload"
+ />
+ );
+ } else {
+ return (
+ <div className="relative aspect-[1200/630] w-full bg-white">
+ {!isMobile && (
+ <ShimmerDots className="opacity-30 [mask-image:radial-gradient(40%_80%,transparent_50%,black)]" />
+ )}
+ <div className="relative flex size-full flex-col items-center justify-center gap-2">
+ <NucleoPhoto className="size-5 text-gray-700" />
+ <p className="max-w-32 text-center text-xs text-gray-700">
+ Enter a link to generate a preview.
+ </p>
+ </div>
+ </div>
+ );
+ }
+ }, [image, generatingMetatags, resizing]);
+
+ return (
+ <>
+ {previewImage}
+ <input
+ key={image}
+ ref={inputFileRef}
+ onChange={onInputFileChange}
+ type="file"
+ accept="image/png,image/jpeg"
+ className="hidden"
+ />
+ </>
+ );
+};
+
+function DefaultOGPreview({ title, description, children }: OGPreviewProps) {
+ const { setValue } = useFormContext<LinkFormData>();
+
+ return (
+ <div>
+ <div className="group relative overflow-hidden rounded-md border border-gray-300">
+ {children}
+ </div>
+ {title && (
+ <ReactTextareaAutosize
+ className="mt-4 line-clamp-2 w-full resize-none border-none p-0 text-xs font-medium text-gray-700 outline-none focus:ring-0"
+ value={title}
+ maxRows={2}
+ onChange={(e) => {
+ setValue("title", e.currentTarget.value);
+ setValue("proxy", true);
+ }}
+ />
+ )}
+ {description && (
+ <ReactTextareaAutosize
+ className="mt-2.5 line-clamp-2 w-full resize-none border-none p-0 text-xs text-gray-700/80 outline-none focus:ring-0"
+ value={description}
+ maxRows={2}
+ onChange={(e) => {
+ setValue("description", e.currentTarget.value);
+ setValue("proxy", true);
+ }}
+ />
+ )}
+ </div>
+ );
+}
+
+function FacebookOGPreview({
+ title,
+ description,
+ hostname,
+ children,
+}: OGPreviewProps) {
+ const { setValue } = useFormContext<LinkFormData>();
+
+ return (
+ <div>
+ <div className="relative border border-gray-300">
+ {children}
+ <div className="grid gap-1 border-t border-gray-300 bg-[#f2f3f5] p-2">
+ {hostname ? (
+ <p className="text-xs uppercase text-[#606770]">{hostname}</p>
+ ) : (
+ <div className="h-4 w-24 rounded-md bg-gray-200" />
+ )}
+ {title || title === "" ? (
+ <input
+ className="truncate border-none bg-transparent p-0 text-xs font-semibold text-[#1d2129] outline-none focus:ring-0"
+ value={title}
+ onChange={(e) => {
+ setValue("title", e.currentTarget.value);
+ setValue("proxy", true);
+ }}
+ />
+ ) : (
+ <div className="h-4 w-full rounded-md bg-gray-200" />
+ )}
+ {description || description === "" ? (
+ <ReactTextareaAutosize
+ className="mb-1 line-clamp-2 w-full resize-none rounded-md border-none bg-gray-200 bg-transparent p-0 text-xs text-[#606770] outline-none focus:ring-0"
+ value={description}
+ maxRows={2}
+ onChange={(e) => {
+ setValue("description", e.currentTarget.value);
+ setValue("proxy", true);
+ }}
+ />
+ ) : (
+ <div className="grid gap-1">
+ <div className="h-4 w-full rounded-md bg-gray-200" />
+ <div className="h-4 w-48 rounded-md bg-gray-200" />
+ </div>
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function LinkedInOGPreview({ title, hostname, children }: OGPreviewProps) {
+ const { setValue } = useFormContext<LinkFormData>();
+
+ return (
+ <div>
+ <div className="relative overflow-hidden rounded-[2px] shadow-[0_0_0_1px_rgba(0,0,0,0.15),0_2px_3px_rgba(0,0,0,0.2)]">
+ {children}
+ <div className="grid gap-1 border-t border-gray-300 bg-white p-2">
+ {title || title === "" ? (
+ <input
+ className="truncate border-none bg-transparent p-0 text-xs font-semibold text-[#000000E6] outline-none focus:ring-0"
+ value={title}
+ onChange={(e) => {
+ setValue("title", e.currentTarget.value);
+ setValue("proxy", true);
+ }}
+ />
+ ) : (
+ <div className="mb-1 h-5 w-full rounded-md bg-gray-200" />
+ )}
+ {hostname ? (
+ <p className="text-[9px] text-[#00000099]">{hostname}</p>
+ ) : (
+ <div className="mb-1 h-4 w-24 rounded-md bg-gray-200" />
+ )}
+ </div>
+ </div>
+ </div>
+ );
+}
+
+function XOGPreview({ title, hostname, children }: OGPreviewProps) {
+ const hasTitle = title || title === "";
+ return (
+ <div>
+ <div className="group relative overflow-hidden rounded-2xl border border-gray-300">
+ {children}
+ <div className="absolute bottom-2 left-0 w-full px-2">
+ <div
+ className={cn(
+ "w-fit max-w-full rounded px-1.5 py-px",
+ hasTitle ? "bg-black/[0.77]" : "bg-gray-200",
+ )}
+ >
+ {hasTitle ? (
+ <span className="block max-w-sm truncate text-xs text-white">
+ {title}
+ </span>
+ ) : (
+ <div className="h-4 w-32" />
+ )}
+ </div>
+ </div>
+ </div>
+ {hostname ? (
+ <p className="mt-1 text-xs text-[#606770]">From {hostname}</p>
+ ) : (
+ <div className="mt-1 h-4 w-24 rounded-md bg-gray-200" />
+ )}
+ </div>
+ );
+}
diff --git a/apps/web/ui/modals/add-edit-link-modal-new/use-metatags.ts b/apps/web/ui/modals/add-edit-link-modal-new/use-metatags.ts
new file mode 100644
index 0000000000..a24ce3dbfa
--- /dev/null
+++ b/apps/web/ui/modals/add-edit-link-modal-new/use-metatags.ts
@@ -0,0 +1,65 @@
+import { getUrlWithoutUTMParams, truncate } from "@dub/utils";
+import { useEffect, useState } from "react";
+import { useFormContext } from "react-hook-form";
+import { useDebounce } from "use-debounce";
+import { LinkFormData } from ".";
+
+export function useMetatags({
+ initial,
+ enabled,
+}: {
+ initial: boolean;
+ enabled: boolean;
+}) {
+ const { watch, setValue } = useFormContext<LinkFormData>();
+ const { url, password } = watch();
+ const [debouncedUrl] = useDebounce(getUrlWithoutUTMParams(url), 500);
+
+ const [generatingMetatags, setGeneratingMetatags] = useState(initial);
+
+ useEffect(() => {
+ // if there's a password, no need to generate metatags
+ if (password) {
+ setGeneratingMetatags(false);
+ setValue("title", "Password Required");
+ setValue(
+ "description",
+ "This link is password protected. Please enter the password to view it.",
+ );
+ setValue("image", "/_static/password-protected.png");
+ return;
+ }
+
+ /**
+ * Only generate metatags if:
+ * - modal is open
+ * - custom OG proxy is not enabled
+ * - url is not empty
+ **/
+ if (enabled) {
+ setValue("title", null);
+ setValue("description", null);
+ setValue("image", null);
+
+ try {
+ // if url is valid, continue to generate metatags, else return null
+ new URL(debouncedUrl);
+ setGeneratingMetatags(true);
+ fetch(`/api/metatags?url=${debouncedUrl}`).then(async (res) => {
+ if (res.status === 200) {
+ const results = await res.json();
+ setValue("title", truncate(results.title, 120));
+ setValue("description", truncate(results.description, 240));
+ setValue("image", results.image);
+ }
+ // set timeout to prevent flickering
+ setTimeout(() => setGeneratingMetatags(false), 200);
+ });
+ } catch (_) {}
+ } else {
+ setGeneratingMetatags(false);
+ }
+ }, [debouncedUrl, password, enabled]);
+
+ return { generatingMetatags };
+}
diff --git a/packages/ui/src/icons/nucleo/globe-pointer.tsx b/packages/ui/src/icons/nucleo/globe-pointer.tsx
new file mode 100644
index 0000000000..0e18ba8e32
--- /dev/null
+++ b/packages/ui/src/icons/nucleo/globe-pointer.tsx
@@ -0,0 +1,48 @@
+import { SVGProps } from "react";
+
+export function GlobePointer(props: SVGProps<SVGSVGElement>) {
+ return (
+ <svg
+ height="18"
+ width="18"
+ viewBox="0 0 18 18"
+ xmlns="http://www.w3.org/2000/svg"
+ {...props}
+ >
+ <g fill="currentColor">
+ <path
+ d="M9.926,16.11c-.461,.092-.938,.14-1.426,.14-4.004,0-7.25-3.246-7.25-7.25S4.496,1.75,8.5,1.75s7.25,3.246,7.25,7.25c0,.264-.014,.524-.041,.78"
+ fill="none"
+ stroke="currentColor"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth="1.5"
+ />
+ <path
+ d="M11.126,10.768l5.94,2.17c.25,.091,.243,.448-.011,.529l-2.719,.87-.87,2.719c-.081,.254-.438,.261-.529,.011l-2.17-5.94c-.082-.223,.135-.44,.359-.359Z"
+ fill="none"
+ stroke="currentColor"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth="1.5"
+ />
+ <path
+ d="M15.75,9c0-1.657-3.246-3-7.25-3S1.25,7.343,1.25,9c0,1.646,3.205,2.983,7.175,3"
+ fill="none"
+ stroke="currentColor"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth="1.5"
+ />
+ <path
+ d="M11.486,8.293c-.147-3.672-1.428-6.543-2.986-6.543-1.657,0-3,3.246-3,7.25s1.343,7.25,3,7.25"
+ fill="none"
+ stroke="currentColor"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth="1.5"
+ />
+ </g>
+ </svg>
+ );
+}
diff --git a/packages/ui/src/icons/nucleo/index.ts b/packages/ui/src/icons/nucleo/index.ts
index 913dc3eb1d..5c96ae343e 100644
--- a/packages/ui/src/icons/nucleo/index.ts
+++ b/packages/ui/src/icons/nucleo/index.ts
@@ -43,6 +43,7 @@ export * from "./gear2";
export * from "./gift";
export * from "./gift-fill";
export * from "./globe";
+export * from "./globe-pointer";
export * from "./globe2";
export * from "./grid-layout-rows";
export * from "./grid-plus";
@@ -63,6 +64,8 @@ export * from "./office-building";
export * from "./page2";
export * from "./paintbrush";
export * from "./pen-writing";
+export * from "./pen2";
+export * from "./photo";
export * from "./pyramid";
export * from "./qrcode";
export * from "./receipt2";
diff --git a/packages/ui/src/icons/nucleo/pen2.tsx b/packages/ui/src/icons/nucleo/pen2.tsx
new file mode 100644
index 0000000000..5969400201
--- /dev/null
+++ b/packages/ui/src/icons/nucleo/pen2.tsx
@@ -0,0 +1,35 @@
+import { SVGProps } from "react";
+
+export function Pen2(props: SVGProps<SVGSVGElement>) {
+ return (
+ <svg
+ height="18"
+ width="18"
+ viewBox="0 0 18 18"
+ xmlns="http://www.w3.org/2000/svg"
+ {...props}
+ >
+ <g fill="currentColor">
+ <line
+ fill="none"
+ stroke="currentColor"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth="1.5"
+ x1="10.547"
+ x2="13.578"
+ y1="4.422"
+ y2="7.453"
+ />
+ <path
+ d="M2.75,15.25s3.599-.568,4.546-1.515c.947-.947,7.327-7.327,7.327-7.327,.837-.837,.837-2.194,0-3.03-.837-.837-2.194-.837-3.03,0,0,0-6.38,6.38-7.327,7.327s-1.515,4.546-1.515,4.546h0Z"
+ fill="none"
+ stroke="currentColor"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth="1.5"
+ />
+ </g>
+ </svg>
+ );
+}
diff --git a/packages/ui/src/icons/nucleo/photo.tsx b/packages/ui/src/icons/nucleo/photo.tsx
new file mode 100644
index 0000000000..7db883cfca
--- /dev/null
+++ b/packages/ui/src/icons/nucleo/photo.tsx
@@ -0,0 +1,45 @@
+import { SVGProps } from "react";
+
+export function NucleoPhoto(props: SVGProps<SVGSVGElement>) {
+ return (
+ <svg
+ height="18"
+ width="18"
+ viewBox="0 0 18 18"
+ xmlns="http://www.w3.org/2000/svg"
+ {...props}
+ >
+ <g fill="currentColor">
+ <path
+ d="M4,14.75l5.836-5.836c.781-.781,2.047-.781,2.828,0l3.586,3.586"
+ fill="none"
+ stroke="currentColor"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth="1.5"
+ />
+ <rect
+ height="11.5"
+ width="14.5"
+ fill="none"
+ rx="2"
+ ry="2"
+ stroke="currentColor"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ strokeWidth="1.5"
+ transform="translate(18 18) rotate(180)"
+ x="1.75"
+ y="3.25"
+ />
+ <circle
+ cx="5.75"
+ cy="7.25"
+ fill="currentColor"
+ r="1.25"
+ stroke="none"
+ />
+ </g>
+ </svg>
+ );
+}
diff --git a/packages/ui/src/index.tsx b/packages/ui/src/index.tsx
index 13ec6393e2..868aec4925 100644
--- a/packages/ui/src/index.tsx
+++ b/packages/ui/src/index.tsx
@@ -22,6 +22,7 @@ export * from "./modal";
export * from "./popover";
export * from "./radio-group";
export * from "./sheet";
+export * from "./shimmer-dots";
export * from "./status-badge";
export * from "./switch";
export * from "./table";
diff --git a/packages/ui/src/shimmer-dots.tsx b/packages/ui/src/shimmer-dots.tsx
new file mode 100644
index 0000000000..029fca79d7
--- /dev/null
+++ b/packages/ui/src/shimmer-dots.tsx
@@ -0,0 +1,150 @@
+import { cn } from "@dub/utils";
+import { useEffect, useRef } from "react";
+
+const vertexShader = `
+attribute vec2 position;
+
+void main()
+{
+ gl_Position = vec4(position, 0.0, 1.0);
+}
+`;
+
+const fragmentShader = `
+precision mediump float;
+
+uniform vec2 resolution;
+uniform float time;
+uniform float dotSize;
+uniform float cellSize;
+uniform float speed;
+
+// Gold noise: https://stackoverflow.com/a/28095165
+float PHI = 1.61803398874989484820459;
+float random(in vec2 xy){
+ return fract(tan(distance(xy*PHI, xy))*xy.x);
+}
+
+void main(void) {
+ vec2 uv = gl_FragCoord.xy;
+
+ vec2 cellUv = vec2(int(uv.x / cellSize), int(uv.y / cellSize));
+ float id = random(cellUv);
+
+ float fadeEffect = (sin(time * speed + id * 20.0) + 1.0) * 0.5;
+
+ vec2 dotUv = fract(uv / cellSize);
+ float dot = step(max(dotUv.x, dotUv.y), dotSize / cellSize);
+
+ float opacity = dot * fadeEffect;
+
+ vec4 fragColor = vec4(vec3(0.0), opacity);
+ fragColor.rgb *= fragColor.a;
+
+ gl_FragColor = fragColor;
+}
+`;
+
+export function ShimmerDots({
+ dotSize = 1,
+ cellSize = 3,
+ speed = 5,
+ className,
+}: {
+ dotSize?: number;
+ cellSize?: number;
+ speed?: number;
+ className?: string;
+}) {
+ const canvasRef = useRef<HTMLCanvasElement>(null);
+
+ useEffect(() => {
+ const canvas = canvasRef.current;
+ if (!canvas || !canvas.parentElement) return;
+
+ const parent = canvas.parentElement;
+ const devicePixelRatio = window.devicePixelRatio || 1;
+ canvas.width = parent.clientWidth * devicePixelRatio;
+ canvas.height = parent.clientHeight * devicePixelRatio;
+
+ const gl = canvas.getContext("webgl");
+
+ if (gl === null) {
+ alert("Failed to initialize WebGL");
+ return;
+ }
+
+ const shaderProgram = gl.createProgram();
+ if (!shaderProgram) {
+ console.error("Failed to create shader program");
+ return;
+ }
+
+ for (let i = 0; i < 2; ++i) {
+ const source = i === 0 ? vertexShader : fragmentShader;
+ const shaderObj = gl.createShader(
+ i === 0 ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER,
+ );
+ if (!shaderObj) {
+ console.error("Failed to create shader");
+ return;
+ }
+ gl.shaderSource(shaderObj, source);
+ gl.compileShader(shaderObj);
+ if (!gl.getShaderParameter(shaderObj, gl.COMPILE_STATUS))
+ console.error(gl.getShaderInfoLog(shaderObj));
+ gl.attachShader(shaderProgram, shaderObj);
+ gl.linkProgram(shaderProgram);
+ }
+
+ if (!gl.getProgramParameter(shaderProgram, gl.LINK_STATUS))
+ console.error(gl.getProgramInfoLog(shaderProgram));
+
+ const position = gl.getAttribLocation(shaderProgram, "position");
+ const time = gl.getUniformLocation(shaderProgram, "time");
+ const resolution = gl.getUniformLocation(shaderProgram, "resolution");
+ const dotSizeUniform = gl.getUniformLocation(shaderProgram, "dotSize");
+ const cellSizeUniform = gl.getUniformLocation(shaderProgram, "cellSize");
+ const speedUniform = gl.getUniformLocation(shaderProgram, "speed");
+
+ gl.useProgram(shaderProgram);
+
+ const pos = [1.0, 1.0, -1.0, 1.0, 1.0, -1.0, -1.0, -1.0];
+ const positionBuffer = gl.createBuffer();
+ gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(pos), gl.STATIC_DRAW);
+
+ gl.enableVertexAttribArray(position);
+ gl.vertexAttribPointer(position, 2, gl.FLOAT, false, 0, 0);
+
+ gl.enable(gl.DEPTH_TEST);
+
+ gl.uniform1f(dotSizeUniform, dotSize);
+ gl.uniform1f(cellSizeUniform, cellSize);
+ gl.uniform1f(speedUniform, speed);
+
+ function render(timestamp: number) {
+ if (gl && canvas && shaderProgram) {
+ gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
+
+ gl.uniform1f(time, timestamp / 1000.0);
+ gl.uniform2f(resolution, canvas.width, canvas.height);
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
+ }
+ requestAnimationFrame(render);
+ }
+
+ requestAnimationFrame(render);
+ }, []);
+
+ return (
+ <div className={cn("absolute inset-0", className)}>
+ <canvas
+ ref={canvasRef}
+ width="100%"
+ height="100%"
+ className="size-full"
+ />
+ </div>
+ );
+}