Skip to content
2 changes: 1 addition & 1 deletion registry/base-differences.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"base": {
"components/data-grid/data-grid-actions-column.tsx": "65e56396154c",
"components/data-grid/data-grid-cell-preview.tsx": "identical",
"components/data-grid/data-grid-cell-variants.tsx": "bc08edc9ad39",
"components/data-grid/data-grid-cell-variants.tsx": "2536401b4208",
"components/data-grid/data-grid-cell.tsx": "c220f6db3521",
"components/data-grid/data-grid-column-header.tsx": "37846d66badd",
"components/data-grid/data-grid-context-menu.tsx": "60acddda5b2d",
Expand Down
192 changes: 192 additions & 0 deletions src/app/data-grid/components/contact-cell.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,192 @@
"use client";

import * as React from "react";

import type { DataGridCellProps } from "@/lib/data-grid-types";

import {
DataGridCell,
useCellValue,
} from "@/registry/bases/radix/components/data-grid/data-grid-cell";
import { CellEditorPopover } from "@/registry/bases/radix/components/data-grid/data-grid-cell-variants";
import { Button } from "@/registry/bases/radix/ui/button";
import { Input } from "@/registry/bases/radix/ui/input";
import { Label } from "@/registry/bases/radix/ui/label";

import type { Contact, Person } from "../lib/seeds";

export function ContactCell(props: DataGridCellProps<Person>) {
const { cell, isEditing, readOnly } = props;
const contact = getContact(useCellValue(cell));
const containerRef = React.useRef<HTMLDivElement>(null);
const draftRef = React.useRef<Contact | null | undefined>(undefined);
const isCancelingRef = React.useRef(false);

const onSave = React.useCallback(
(newContact: Contact | null) => {
draftRef.current = undefined;
if (!getIsSameContact(newContact, contact)) cell.setValue(newContact);
cell.table.stopEditing();
},
[cell, contact],
);

const onDraftChange = React.useCallback((draft: Contact | null) => {
draftRef.current = draft;
}, []);

const onOpenChange = React.useCallback(
(open: boolean) => {
if (open) return;
const draft = draftRef.current;
const isCanceling = isCancelingRef.current;
draftRef.current = undefined;
isCancelingRef.current = false;
if (
draft !== undefined &&
!isCanceling &&
!getIsSameContact(draft, contact)
) {
cell.setValue(draft);
}
cell.table.stopEditing();
},
[cell, contact],
);

const onEscapeKeyDown = React.useCallback(() => {
isCancelingRef.current = true;
}, []);

return (
<DataGridCell
{...props}
ref={containerRef}
onMouseDown={isEditing ? onEditingCellMouseDown : undefined}
>
<CellEditorPopover
cell={cell}
open={isEditing}
readOnly={readOnly}
containerRef={containerRef}
className="w-72"
onOpenChange={onOpenChange}
onEscapeKeyDown={onEscapeKeyDown}
onKeyDown={onEditorKeyDown}
>
<ContactForm
contact={contact}
onSave={onSave}
onDraftChange={onDraftChange}
/>
</CellEditorPopover>
{contact ? (
<span data-slot="data-grid-cell-content" dir="auto">
{contact.name}{" "}
<span className="text-muted-foreground">{contact.phone}</span>
</span>
) : null}
</DataGridCell>
);
}

export function parseContact(text: string): Contact | null | undefined {
if (!text) return null;
try {
return getContact(JSON.parse(text)) ?? undefined;
} catch {
return undefined;
}
}

export function sortContacts(
rowA: { original: Person },
rowB: { original: Person },
) {
return (rowA.original.contact?.name ?? "").localeCompare(
rowB.original.contact?.name ?? "",
);
}

interface ContactFormProps {
contact: Contact | null;
onSave: (contact: Contact | null) => void;
onDraftChange: (contact: Contact | null) => void;
}

function ContactForm({ contact, onSave, onDraftChange }: ContactFormProps) {
const id = React.useId();
const [name, setName] = React.useState(contact?.name ?? "");
const [phone, setPhone] = React.useState(contact?.phone ?? "");

const onSubmit = React.useCallback(
(event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
onSave(getDraftContact(name, phone));
},
[name, phone, onSave],
);

const onNameChange = React.useCallback(
(event: React.ChangeEvent<HTMLInputElement>) => {
setName(event.target.value);
onDraftChange(getDraftContact(event.target.value, phone));
},
[phone, onDraftChange],
);

const onPhoneChange = React.useCallback(
(event: React.ChangeEvent<HTMLInputElement>) => {
setPhone(event.target.value);
onDraftChange(getDraftContact(name, event.target.value));
},
[name, onDraftChange],
);

return (
<form className="flex flex-col gap-3 p-3" onSubmit={onSubmit}>
<div className="flex flex-col gap-1.5">
<Label htmlFor={`${id}-name`}>Name</Label>
<Input id={`${id}-name`} value={name} onChange={onNameChange} />
</div>
<div className="flex flex-col gap-1.5">
<Label htmlFor={`${id}-phone`}>Phone</Label>
<Input
id={`${id}-phone`}
type="tel"
value={phone}
onChange={onPhoneChange}
/>
</div>
<Button type="submit" size="sm" className="self-end">
Save
</Button>
</form>
);
}

function getDraftContact(name: string, phone: string): Contact | null {
const contact = { name: name.trim(), phone: phone.trim() };
return contact.name || contact.phone ? contact : null;
}

function getIsSameContact(a: Contact | null, b: Contact | null) {
return a?.name === b?.name && a?.phone === b?.phone;
}

function getContact(value: unknown): Contact | null {
if (!value || typeof value !== "object") return null;
const { name, phone } = value as Record<string, unknown>;
return typeof name === "string" && typeof phone === "string"
? { name, phone }
: null;
}

// Keys bubble from the portaled form to the cell, which ends editing on Tab and Enter.
function onEditorKeyDown(event: React.KeyboardEvent<HTMLDivElement>) {
if (event.key === "Tab" || event.key === "Enter") event.stopPropagation();
}

function onEditingCellMouseDown(event: React.MouseEvent) {
event.preventDefault();
}
13 changes: 13 additions & 0 deletions src/app/data-grid/components/data-grid-demo.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ import {
statuses,
} from "../lib/seeds";
import { worstCasePeople } from "../lib/worst-case";
import { ContactCell, parseContact, sortContacts } from "./contact-cell";
import { DataGridBenchmark } from "./data-grid-benchmark";
import { DataGridDemoSkeleton } from "./data-grid-demo-skeleton";
import { PeopleDataGridActionBar } from "./people-data-grid-action-bar";
Expand Down Expand Up @@ -224,6 +225,18 @@ function DataGridDemoContent({
variant: "text",
},
}),
columnHelper.accessor("contact", {
id: "contact",
header: "Emergency Contact",
minSize: 240,
enableColumnFilter: false,
sortFn: sortContacts,
meta: {
label: "Emergency Contact",
cellComponent: ContactCell,
parseValue: parseContact,
},
}),
columnHelper.accessor("feedback", {
id: "feedback",
header: "Feedback",
Expand Down
17 changes: 17 additions & 0 deletions src/app/data-grid/lib/seeds.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@ import { faker } from "@faker-js/faker";

import type { FileCellData } from "@/lib/data-grid-types";

export interface Contact {
name: string;
phone: string;
}

export interface Person {
id: string;
name?: string;
Expand All @@ -15,6 +20,7 @@ export interface Person {
skills?: string[];
isActive?: boolean;
startDate?: string;
contact?: Contact | null;
attachments?: FileCellData[];
}

Expand Down Expand Up @@ -61,6 +67,8 @@ const FIELD_SALTS = {
status: 5,
isActive: 6,
feedback: 7,
contact: 8,
phone: 9,
} as const;

let pool: SeedPerson[] | null = null;
Expand All @@ -74,6 +82,11 @@ export function generatePeople(count: number): Person[] {
const other = pickItem(seeds, index, "seed");
const { firstName } = base;
const { lastName } = other;
const contact = pickItem(seeds, index, "contact");
const phone = String(randomInt(index, "phone", 0, 9_999_999)).padStart(
7,
"0",
);

return {
id: `person-${index}`,
Expand All @@ -87,6 +100,10 @@ export function generatePeople(count: number): Person[] {
status: pickItem(statuses, index, "status"),
isActive: randomInt(index, "isActive", 0, 1) === 1,
startDate: other.startDate,
contact: {
name: `${contact.firstName} ${contact.lastName}`,
phone: `(555) ${phone.slice(0, 3)}-${phone.slice(3)}`,
},
skills: base.skills,
attachments: other.attachments,
};
Expand Down
4 changes: 4 additions & 0 deletions src/app/data-grid/lib/worst-case.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@ export const worstCasePeople: Person[] = [
],
isActive: true,
startDate: "2025-12-31T23:30:00-08:00",
contact: {
name: "Maximilian Alexander von Hohenberg-Schwarzenfels",
phone: "+48 (12) 345-67-89 ext. 12345 (after 6pm CET only)",
},
attachments: [
{
id: "worst-1-file-0",
Expand Down
Loading
Loading