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 value examples and domain/key splitting

Tim Wilson67930c571024
diff --git a/apps/web/app/api/workspaces/[idOrSlug]/import/csv/route.ts b/apps/web/app/api/workspaces/[idOrSlug]/import/csv/route.ts
index dd03dbbc64..455321d298 100644
--- a/apps/web/app/api/workspaces/[idOrSlug]/import/csv/route.ts
+++ b/apps/web/app/api/workspaces/[idOrSlug]/import/csv/route.ts
@@ -82,8 +82,12 @@ export const POST = withWorkspace(async ({ req, workspace, session }) => {
processLink({
payload: createLinkBodySchema.parse({
url: row[mapping.url],
- domain: row[mapping.domain],
- key: row[mapping.key],
+ // Special splitting for domains/keys so they can map from a full URL
+ domain: row[mapping.domain].replace(/^https?:\/\//, "").split("/")[0],
+ key: row[mapping.key]
+ .replace(/^https?:\/\//, "")
+ .split("/")
+ .at(-1),
title: mapping.title ? row[mapping.title] : undefined,
description: mapping.description
? row[mapping.description]
diff --git a/apps/web/ui/modals/import-csv-modal/field-mapping.tsx b/apps/web/ui/modals/import-csv-modal/field-mapping.tsx
index 6901241854..42d2bf7e5e 100644
--- a/apps/web/ui/modals/import-csv-modal/field-mapping.tsx
+++ b/apps/web/ui/modals/import-csv-modal/field-mapping.tsx
@@ -1,7 +1,8 @@
-import { Button, IconMenu, Popover } from "@dub/ui";
-import { Check, TableIcon } from "@dub/ui/src/icons";
+import { Button, IconMenu, Popover, Tooltip } from "@dub/ui";
+import { Check, Magnifier, TableIcon } from "@dub/ui/src/icons";
+import { truncate } from "@dub/utils";
import { ChevronDown } from "lucide-react";
-import { useState } from "react";
+import { useMemo, useState } from "react";
import { Controller } from "react-hook-form";
import { mappableFields, useCsvContext } from ".";
@@ -23,21 +24,45 @@ export function FieldMapping() {
function FieldRow({ field }: { field: keyof typeof mappableFields }) {
const { label, required } = mappableFields[field];
- const { control, fileColumns } = useCsvContext();
+ const { control, watch, fileColumns, firstRows } = useCsvContext();
+
+ const value = watch(field);
const [isOpen, setIsOpen] = useState(false);
+ const examples = useMemo(() => {
+ if (!firstRows) return [];
+
+ let values = firstRows?.map((row) => row[value]).filter(Boolean);
+
+ // Special split handling for domains and keys (should match backend)
+ if (field === "domain")
+ values = values.map((e) => e.replace(/^https?:\/\//, "").split("/")[0]);
+ if (field === "key")
+ values = values.map(
+ (e) =>
+ e
+ .replace(/^https?:\/\//, "")
+ .split("/")
+ .at(-1) as string,
+ );
+
+ values = values.map((e) => truncate(e, 16) as string);
+
+ return values;
+ }, [firstRows, value]);
+
return (
<div key={field} className="flex items-center justify-between gap-6">
<span className="text-sm font-medium text-gray-950">
{label} {required && <span className="text-red-700">*</span>}
</span>
- <Controller
- control={control}
- name={field}
- rules={{ required }}
- render={({ field }) => (
- <div className="min-w-0">
+ <div className="flex min-w-0 items-center">
+ <Controller
+ control={control}
+ name={field}
+ rules={{ required }}
+ render={({ field }) => (
<Popover
align="end"
content={
@@ -65,11 +90,11 @@ function FieldRow({ field }: { field: keyof typeof mappableFields }) {
>
<Button
variant="secondary"
- className="px-3"
+ className="min-w-16 px-3"
onClick={() => setIsOpen((o) => !o)}
text={
<div className="flex items-center gap-1">
- <span className="min-w-12 flex-1 truncate whitespace-nowrap text-left text-gray-800">
+ <span className="flex-1 truncate whitespace-nowrap text-left text-gray-800">
{field.value || (
<span className="text-gray-600">Select column...</span>
)}
@@ -79,9 +104,25 @@ function FieldRow({ field }: { field: keyof typeof mappableFields }) {
}
/>
</Popover>
+ )}
+ />
+ {Boolean(examples?.length) && (
+ <div className="-mr-6 ml-2 shrink-0">
+ <Tooltip
+ content={
+ <div className="block px-3 py-2 text-sm">
+ <span className="font-medium text-gray-950">Examples: </span>
+ <span className="text-gray-500">{examples?.join(", ")}</span>
+ </div>
+ }
+ >
+ <div>
+ <Magnifier className="h-4 w-4 text-gray-400 transition-colors hover:text-gray-500" />
+ </div>
+ </Tooltip>
</div>
)}
- />
+ </div>
</div>
);
}
diff --git a/apps/web/ui/modals/import-csv-modal/index.tsx b/apps/web/ui/modals/import-csv-modal/index.tsx
index 88de83806d..70f2e9cb41 100644
--- a/apps/web/ui/modals/import-csv-modal/index.tsx
+++ b/apps/web/ui/modals/import-csv-modal/index.tsx
@@ -55,6 +55,8 @@ export type ImportCsvFormData = {
const ImportCsvContext = createContext<{
fileColumns: string[] | null;
setFileColumns: (columns: string[] | null) => void;
+ firstRows: Record<string, string>[] | null;
+ setFirstRows: (rows: Record<string, string>[] | null) => void;
control: Control<ImportCsvFormData>;
watch: UseFormWatch<ImportCsvFormData>;
} | null>(null);
@@ -102,6 +104,9 @@ function ImportCsvModal({
const page = pages[pageNumber];
const [fileColumns, setFileColumns] = useState<string[] | null>(null);
+ const [firstRows, setFirstRows] = useState<Record<string, string>[] | null>(
+ null,
+ );
return (
<Modal
@@ -130,7 +135,14 @@ function ImportCsvModal({
<AnimatedSizeContainer height>
<ImportCsvContext.Provider
- value={{ fileColumns, setFileColumns, control, watch }}
+ value={{
+ fileColumns,
+ setFileColumns,
+ firstRows,
+ setFirstRows,
+ control,
+ watch,
+ }}
>
<div className="flex flex-col space-y-6 bg-gray-50 px-4 py-8 text-left sm:px-16">
<form
diff --git a/apps/web/ui/modals/import-csv-modal/select-file.tsx b/apps/web/ui/modals/import-csv-modal/select-file.tsx
index de1e5ab5ff..ecddf3bc8f 100644
--- a/apps/web/ui/modals/import-csv-modal/select-file.tsx
+++ b/apps/web/ui/modals/import-csv-modal/select-file.tsx
@@ -5,7 +5,14 @@ import { Controller } from "react-hook-form";
import { useCsvContext } from ".";
export function SelectFile() {
- const { watch, control, fileColumns, setFileColumns } = useCsvContext();
+ const {
+ watch,
+ control,
+ fileColumns,
+ setFileColumns,
+ firstRows,
+ setFirstRows,
+ } = useCsvContext();
const file = watch("file");
const [error, setError] = useState<string | null>(null);
@@ -16,19 +23,40 @@ export function SelectFile() {
return;
}
- readFirstLine(file)
- .then((firstLine) => {
- const split = firstLine.split(",");
+ readLines(file, 4)
+ .then((lines) => {
+ if (lines.length < 2) {
+ setError("CSV file must have at least 2 rows.");
+ setFileColumns(null);
+ setFirstRows(null);
+ return;
+ }
+
+ const split = lines[0].split(",");
if (split.length <= 1) {
setError("Failed to retrieve CSV column data.");
setFileColumns(null);
+ setFirstRows(null);
return;
}
+
setFileColumns(split);
+ setFirstRows(
+ lines
+ .slice(1)
+ .map((line) =>
+ Object.fromEntries(
+ line
+ .split(",")
+ .map((value, idx) => [split[idx] ?? "unknown", value]),
+ ),
+ ),
+ );
})
.catch(() => {
setError("Failed to read CSV file.");
setFileColumns(null);
+ setFirstRows(null);
});
}, [file]);
@@ -58,7 +86,7 @@ export function SelectFile() {
<div>{error}</div>
) : fileColumns ? (
<p className="text-sm text-gray-600">
- Columns found: {fileColumns.join(", ")}
+ Columns found: {listColumns(fileColumns)}
</p>
) : file ? (
<div className="flex items-center justify-center">
@@ -69,19 +97,33 @@ export function SelectFile() {
);
}
-const readFirstLine = async (file: File): Promise<string> => {
+const maxColumns = 4;
+
+const listColumns = (columns: string[]) => {
+ const eachTruncated = columns.map((column) => truncate(column, 16));
+ const allTruncated =
+ eachTruncated.length <= maxColumns
+ ? eachTruncated
+ : eachTruncated
+ .slice(0, maxColumns)
+ .concat(`and ${eachTruncated.length - maxColumns} more`);
+ return allTruncated.join(", ");
+};
+
+const readLines = async (file: File, count = 4): Promise<string[]> => {
const reader = file.stream().getReader();
const decoder = new TextDecoder("utf-8");
let { value: chunk, done: readerDone } = await reader.read();
- let firstLine = "";
+ let content = "";
+ let result = [];
while (!readerDone) {
- firstLine += decoder.decode(chunk, { stream: true });
- const lines = firstLine.split("\n");
- if (lines.length > 1) {
+ content += decoder.decode(chunk, { stream: true });
+ const lines = content.split("\n");
+ if (lines.length >= count) {
reader.cancel();
- return lines[0];
+ return lines.slice(0, count);
}
({ value: chunk, done: readerDone } = await reader.read());
}
- return firstLine;
+ return result;
};