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.

WIP links display persistence

Tim Wilsonb56d9ace9731
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/route.ts
index 75e76ba3fc..8f6076a742 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/route.ts
@@ -9,6 +9,7 @@ import { storage } from "@/lib/storage";
import {
updateWorkspaceSchema,
WorkspaceSchema,
+ WorkspaceSchemaExtended,
} from "@/lib/zod/schemas/workspaces";
import { prisma } from "@dub/prisma";
import { nanoid, R2_URL } from "@dub/utils";
@@ -35,7 +36,7 @@ export const GET = withWorkspace(
return NextResponse.json(
{
- ...WorkspaceSchema.parse({
+ ...WorkspaceSchemaExtended.parse({
...workspace,
id: prefixWorkspaceId(workspace.id),
domains,
diff --git a/apps/web/lib/actions/safe-action.ts b/apps/web/lib/actions/safe-action.ts
index d31b1b6c0d..a97366f9c0 100644
--- a/apps/web/lib/actions/safe-action.ts
+++ b/apps/web/lib/actions/safe-action.ts
@@ -57,6 +57,7 @@ export const authActionClient = actionClient.use(
},
select: {
role: true,
+ workspacePreferences: true,
},
},
},
diff --git a/apps/web/lib/actions/update-workspace-preferences.ts b/apps/web/lib/actions/update-workspace-preferences.ts
new file mode 100644
index 0000000000..8626413d85
--- /dev/null
+++ b/apps/web/lib/actions/update-workspace-preferences.ts
@@ -0,0 +1,50 @@
+"use server";
+
+import { prisma } from "@dub/prisma";
+import z from "../zod";
+import { workspacePreferencesValueSchemas } from "../zod/schemas/workspace-preferences";
+import { authActionClient } from "./safe-action";
+
+const schema = z.object({
+ workspaceId: z.string(),
+ key: z.string(),
+ value: z.any(),
+});
+
+// Update a user's preferences for a workspace
+export const updateWorkspacePreferences = authActionClient
+ .schema(schema)
+ .action(async ({ ctx, parsedInput }) => {
+ const { workspace } = ctx;
+ const { key, value } = parsedInput;
+
+ const valueSchema = workspacePreferencesValueSchemas[key];
+
+ if (!valueSchema)
+ throw new Error(`Invalid workspace preference key: ${key}`);
+
+ const parsedValue = valueSchema.parse(value);
+
+ const workspacePreferences =
+ (workspace.users[0].workspacePreferences as
+ | Record<string, any>
+ | undefined
+ | null) ?? {};
+
+ await prisma.projectUsers.update({
+ where: {
+ userId_projectId: {
+ userId: ctx.user.id,
+ projectId: workspace.id,
+ },
+ },
+ data: {
+ workspacePreferences: {
+ ...workspacePreferences,
+ [key]: parsedValue,
+ },
+ },
+ });
+
+ return { ok: true };
+ });
diff --git a/apps/web/lib/links/links-display.ts b/apps/web/lib/links/links-display.ts
new file mode 100644
index 0000000000..d57e8f1d0e
--- /dev/null
+++ b/apps/web/lib/links/links-display.ts
@@ -0,0 +1,64 @@
+export const linksViewModes = ["cards", "rows"] as const;
+
+export type LinksViewMode = (typeof linksViewModes)[number];
+
+export const linksSortOptions = [
+ {
+ display: "Date created",
+ slug: "createdAt",
+ },
+ {
+ display: "Total clicks",
+ slug: "clicks",
+ },
+ {
+ display: "Last clicked",
+ slug: "lastClicked",
+ },
+ {
+ display: "Total sales",
+ slug: "saleAmount",
+ },
+] as const;
+
+export type LinksSortSlug = (typeof linksSortOptions)[number]["slug"];
+
+export const linksDisplayPropertyIds = [
+ "icon",
+ "link",
+ "url",
+ "title",
+ "description",
+ "createdAt",
+ "user",
+ "tags",
+ "analytics",
+] as const;
+
+export const linksDisplayProperties: {
+ id: LinksDisplayProperty;
+ label: string;
+ switch?: LinksDisplayProperty;
+ mobile?: boolean;
+}[] = [
+ { id: "link", label: "Short link", switch: "title" },
+ { id: "url", label: "Destination URL", switch: "description" },
+ { id: "title", label: "Title", switch: "link" },
+ { id: "description", label: "Description", switch: "url" },
+ { id: "createdAt", label: "Created Date", mobile: false },
+ { id: "user", label: "Creator", mobile: false },
+ { id: "tags", label: "Tags" },
+ { id: "analytics", label: "Analytics" },
+];
+
+export type LinksDisplayProperty = (typeof linksDisplayPropertyIds)[number];
+
+export const defaultLinksDisplayProperties: LinksDisplayProperty[] = [
+ "icon",
+ "link",
+ "url",
+ "createdAt",
+ "user",
+ "tags",
+ "analytics",
+];
diff --git a/apps/web/lib/swr/use-workspace-preferences.ts b/apps/web/lib/swr/use-workspace-preferences.ts
new file mode 100644
index 0000000000..4e412e61c2
--- /dev/null
+++ b/apps/web/lib/swr/use-workspace-preferences.ts
@@ -0,0 +1,42 @@
+"use client";
+
+import { useAction } from "next-safe-action/hooks";
+import { useEffect, useState } from "react";
+import { mutate } from "swr";
+import { updateWorkspacePreferences } from "../actions/update-workspace-preferences";
+import useWorkspace from "./use-workspace";
+
+export const WORKSPACE_PREFERENCES_KEYS = {
+ linksDisplay: "linksDisplay",
+};
+
+export function useWorkspacePreferences<T>(
+ key: string,
+): [
+ T | undefined,
+ (value: T) => Promise<void>,
+ { loading: boolean; mutateWorkspace: () => void },
+] {
+ const { id: workspaceId, slug, users, loading } = useWorkspace();
+ const workspacePreferences = users?.[0]?.workspacePreferences;
+
+ const { executeAsync } = useAction(updateWorkspacePreferences);
+ const [item, setItemState] = useState<T | undefined>(
+ workspacePreferences?.[key],
+ );
+
+ useEffect(() => {
+ setItemState(workspacePreferences?.[key]);
+ }, [workspacePreferences]);
+
+ const setItem = async (value: T) => {
+ setItemState(value);
+ await executeAsync({ key, value, workspaceId: workspaceId! });
+ };
+
+ const mutateWorkspace = () => {
+ mutate(`/api/workspaces/${slug}`);
+ };
+
+ return [item, setItem, { loading, mutateWorkspace }];
+}
diff --git a/apps/web/lib/types.ts b/apps/web/lib/types.ts
index 8d30ce923f..6a7653237c 100644
--- a/apps/web/lib/types.ts
+++ b/apps/web/lib/types.ts
@@ -74,6 +74,7 @@ import {
webhookEventSchemaTB,
WebhookSchema,
} from "./zod/schemas/webhooks";
+import { workspacePreferencesSchema } from "./zod/schemas/workspace-preferences";
export type LinkProps = Link;
@@ -154,6 +155,9 @@ export interface WorkspaceProps extends Project {
export type ExpandedWorkspaceProps = WorkspaceProps & {
allowedHostnames: string[];
+ users: (WorkspaceProps["users"][number] & {
+ workspacePreferences?: z.infer<typeof workspacePreferencesSchema>;
+ })[];
};
export type WorkspaceWithUsers = Omit<WorkspaceProps, "domains">;
diff --git a/apps/web/lib/zod/schemas/workspace-preferences.ts b/apps/web/lib/zod/schemas/workspace-preferences.ts
new file mode 100644
index 0000000000..6a2b4dcd6a
--- /dev/null
+++ b/apps/web/lib/zod/schemas/workspace-preferences.ts
@@ -0,0 +1,26 @@
+import {
+ linksDisplayPropertyIds,
+ linksSortOptions,
+ linksViewModes,
+} from "@/lib/links/links-display";
+import { z } from "zod";
+
+const linksDisplaySchema = z.object({
+ viewMode: z.enum(linksViewModes),
+ sortBy: z.enum(
+ linksSortOptions.map(({ slug }) => slug) as [string, ...string[]],
+ ),
+ showArchived: z.boolean(),
+ displayProperties: z.array(z.enum(linksDisplayPropertyIds)),
+});
+
+export const workspacePreferencesValueSchemas = {
+ linksDisplay: linksDisplaySchema,
+} as const;
+
+export const workspacePreferencesSchema = z.object(
+ workspacePreferencesValueSchemas,
+);
+
+export type WorkspacePreferencesKey =
+ keyof typeof workspacePreferencesValueSchemas;
diff --git a/apps/web/lib/zod/schemas/workspaces.ts b/apps/web/lib/zod/schemas/workspaces.ts
index 5c9cf1f687..97d5b49028 100644
--- a/apps/web/lib/zod/schemas/workspaces.ts
+++ b/apps/web/lib/zod/schemas/workspaces.ts
@@ -4,6 +4,7 @@ import { DEFAULT_REDIRECTS, validSlugRegex } from "@dub/utils";
import slugify from "@sindresorhus/slugify";
import { DomainSchema } from "./domains";
import { planSchema, roleSchema } from "./misc";
+import { workspacePreferencesSchema } from "./workspace-preferences";
export const workspaceIdSchema = z.object({
workspaceId: z
@@ -153,5 +154,5 @@ export const notificationTypes = z.enum([
]);
export const WorkspaceSchemaExtended = WorkspaceSchema.extend({
- workspacePreferences: z.record(z.boolean()).optional(),
+ workspacePreferences: workspacePreferencesSchema.nullish(),
});
diff --git a/apps/web/ui/links/link-display.tsx b/apps/web/ui/links/link-display.tsx
index 08f13b0551..1e2186e274 100644
--- a/apps/web/ui/links/link-display.tsx
+++ b/apps/web/ui/links/link-display.tsx
@@ -1,3 +1,7 @@
+import {
+ linksDisplayProperties,
+ LinksViewMode,
+} from "@/lib/links/links-display";
import { useIsMegaFolder } from "@/lib/swr/use-is-mega-folder";
import {
Button,
@@ -18,11 +22,7 @@ import { AnimatePresence, motion } from "framer-motion";
import { ChevronDown } from "lucide-react";
import { useContext, useState } from "react";
import LinkSort from "./link-sort";
-import {
- LinksDisplayContext,
- LinksViewMode,
- linkDisplayProperties,
-} from "./links-display-provider";
+import { LinksDisplayContext } from "./links-display-provider";
export default function LinkDisplay() {
const {
@@ -122,7 +122,7 @@ export default function LinkDisplay() {
Display Properties
</span>
<div className="mt-4 flex flex-wrap gap-2">
- {linkDisplayProperties.map((property) => {
+ {linksDisplayProperties.map((property) => {
const active = displayProperties.includes(property.id);
return (
<button
diff --git a/apps/web/ui/links/links-display-provider.tsx b/apps/web/ui/links/links-display-provider.tsx
index 0c465458ff..1ee2c9e379 100644
--- a/apps/web/ui/links/links-display-provider.tsx
+++ b/apps/web/ui/links/links-display-provider.tsx
@@ -1,79 +1,23 @@
+import {
+ defaultLinksDisplayProperties,
+ LinksDisplayProperty,
+ linksDisplayPropertyIds,
+ linksSortOptions,
+ LinksSortSlug,
+ LinksViewMode,
+ linksViewModes,
+} from "@/lib/links/links-display";
import { useLocalStorage } from "@dub/ui";
import { useSearchParams } from "next/navigation";
import {
+ createContext,
Dispatch,
PropsWithChildren,
SetStateAction,
- createContext,
useMemo,
useState,
} from "react";
-export const linkViewModes = ["cards", "rows"] as const;
-
-export type LinksViewMode = (typeof linkViewModes)[number];
-
-export const sortOptions = [
- {
- display: "Date created",
- slug: "createdAt",
- },
- {
- display: "Total clicks",
- slug: "clicks",
- },
- {
- display: "Last clicked",
- slug: "lastClicked",
- },
- {
- display: "Total sales",
- slug: "saleAmount",
- },
-] as const;
-
-export type LinksSortSlug = (typeof sortOptions)[number]["slug"];
-
-export const linkDisplayPropertyIds = [
- "icon",
- "link",
- "url",
- "title",
- "description",
- "createdAt",
- "user",
- "tags",
- "analytics",
-] as const;
-
-export const linkDisplayProperties: {
- id: LinkDisplayProperty;
- label: string;
- switch?: LinkDisplayProperty;
- mobile?: boolean;
-}[] = [
- { id: "link", label: "Short link", switch: "title" },
- { id: "url", label: "Destination URL", switch: "description" },
- { id: "title", label: "Title", switch: "link" },
- { id: "description", label: "Description", switch: "url" },
- { id: "createdAt", label: "Created Date", mobile: false },
- { id: "user", label: "Creator", mobile: false },
- { id: "tags", label: "Tags" },
- { id: "analytics", label: "Analytics" },
-];
-
-export type LinkDisplayProperty = (typeof linkDisplayPropertyIds)[number];
-
-export const defaultDisplayProperties: LinkDisplayProperty[] = [
- "icon",
- "link",
- "url",
- "createdAt",
- "user",
- "tags",
- "analytics",
-];
-
function useLinksDisplayOption<T>(
key: string,
parsePersisted: (value: T) => T,
@@ -99,8 +43,8 @@ function useLinksDisplayOption<T>(
export const LinksDisplayContext = createContext<{
viewMode: LinksViewMode;
setViewMode: Dispatch<SetStateAction<LinksViewMode>>;
- displayProperties: LinkDisplayProperty[];
- setDisplayProperties: Dispatch<SetStateAction<LinkDisplayProperty[]>>;
+ displayProperties: LinksDisplayProperty[];
+ setDisplayProperties: Dispatch<SetStateAction<LinksDisplayProperty[]>>;
sortBy: LinksSortSlug;
setSort: Dispatch<SetStateAction<LinksSortSlug>>;
showArchived: boolean;
@@ -111,9 +55,9 @@ export const LinksDisplayContext = createContext<{
}>({
viewMode: "cards",
setViewMode: () => {},
- displayProperties: defaultDisplayProperties,
+ displayProperties: defaultLinksDisplayProperties,
setDisplayProperties: () => {},
- sortBy: sortOptions[0].slug,
+ sortBy: linksSortOptions[0].slug,
setSort: () => {},
showArchived: false,
setShowArchived: () => {},
@@ -126,15 +70,16 @@ export const LinksDisplayContext = createContext<{
});
const parseViewMode = (viewModeRaw: string) =>
- linkViewModes.find((vm) => vm === viewModeRaw) ?? linkViewModes[0];
+ linksViewModes.find((vm) => vm === viewModeRaw) ?? linksViewModes[0];
const parseDisplayProperties = (displayPropertiesRaw: string[]) =>
- linkDisplayPropertyIds.filter(
+ linksDisplayPropertyIds.filter(
(p) => displayPropertiesRaw.findIndex((pr) => pr === p) !== -1,
);
const parseSort = (sort: string) =>
- sortOptions.find(({ slug }) => slug === sort)?.slug ?? sortOptions[0].slug;
+ linksSortOptions.find(({ slug }) => slug === sort)?.slug ??
+ linksSortOptions[0].slug;
const parseShowArchived = (showArchived: boolean) => showArchived === true;
@@ -153,7 +98,7 @@ export function LinksDisplayProvider({ children }: PropsWithChildren) {
} = useLinksDisplayOption<string>(
"view-mode",
parseViewMode,
- linkViewModes[0],
+ linksViewModes[0],
);
// Sort
@@ -166,7 +111,7 @@ export function LinksDisplayProvider({ children }: PropsWithChildren) {
} = useLinksDisplayOption<string>(
"sortBy",
parseSort,
- sortOptions[0].slug,
+ linksSortOptions[0].slug,
sortRaw ? parseSort(sortRaw) : undefined,
);
@@ -191,10 +136,10 @@ export function LinksDisplayProvider({ children }: PropsWithChildren) {
valuePersisted: displayPropertiesPersisted,
persist: persistDisplayProperties,
reset: resetDisplayProperties,
- } = useLinksDisplayOption<LinkDisplayProperty[]>(
+ } = useLinksDisplayOption<LinksDisplayProperty[]>(
"display-properties",
parseDisplayProperties,
- defaultDisplayProperties,
+ defaultLinksDisplayProperties,
);
const isDirty = useMemo(() => {