Open source alternative to Semrush and Ahrefs
TypeScript backlink-analysisgoogle-search-console-mcpkeyword-researchmcpseoseo-agentseo-auditseo-automationseo-skillsseo-toolssite-audit
Port the projects list and create project dialog to shadcn, with inline form errors (EVE-301) (#745)
Carter Smithe1300ff4baf4
diff --git a/src/client/components/AuthErrorCard.tsx b/src/client/components/AuthErrorCard.tsxindex a38211a0..19bf3e68 100644--- a/src/client/components/AuthErrorCard.tsx+++ b/src/client/components/AuthErrorCard.tsx@@ -4,6 +4,15 @@ import {getErrorCode,getStandardErrorMessage,} from "@/client/lib/error-messages";+import { Alert, AlertDescription } from "@/client/components/ui/alert";+import { Button } from "@/client/components/ui/button";+import {+ Card,+ CardContent,+ CardFooter,+ CardHeader,+ CardTitle,+} from "@/client/components/ui/card";import { isHostedClientAuthMode } from "@/lib/auth-mode";import { getSignInHref, getSignInHrefForLocation } from "@/lib/auth-redirect";@@ -56,19 +65,20 @@ function AuthConfigErrorCard({ message, onRetry }: CardProps) {const clientAuthMode = import.meta.env.AUTH_MODE;return (- <div className="card w-full max-w-2xl bg-base-100 border border-base-300 shadow-xl">- <div className="card-body gap-4">- <h2 className="card-title gap-2">- <ShieldAlert className="size-5 text-error" />+ <Card className="w-full max-w-2xl">+ <CardHeader>+ <CardTitle className="flex items-center gap-2">+ <ShieldAlert className="size-5 text-destructive" />Authentication setup required- </h2>-- <div className="alert alert-error">- <span>{message}</span>- </div>+ </CardTitle>+ </CardHeader>+ <CardContent className="space-y-4">+ <Alert variant="destructive">+ <AlertDescription>{message}</AlertDescription>+ </Alert>{clientAuthMode === "hosted" ? (- <p className="text-sm text-base-content/70">+ <p className="text-muted-foreground">Hosted mode requires{" "}<code className="mx-1">BETTER_AUTH_SECRET</code>(32+ characters), <code className="mx-1">BETTER_AUTH_URL</code>, and@@ -76,29 +86,32 @@ function AuthConfigErrorCard({ message, onRetry }: CardProps) {</p>) : null}{clientAuthMode === "cloudflare_access" ? (- <p className="text-sm text-base-content/70">+ <p className="text-muted-foreground">Cloudflare Access mode requires<code className="mx-1">TEAM_DOMAIN</code> (a full https URL) and<code className="mx-1">POLICY_AUD</code> set on the deployment, withan Access application protecting this hostname.</p>) : null}-- <div className="card-actions justify-end">- <button className="btn btn-ghost btn-sm" onClick={onRetry}>- Try Again- </button>- <a- className="btn btn-primary btn-sm"- href={CLOUDFLARE_SETUP_GUIDE_URL}- target="_blank"- rel="noreferrer"- >- Open Setup Guide- </a>- </div>- </div>- </div>+ </CardContent>+ <CardFooter className="justify-end gap-2">+ <Button variant="ghost" onClick={onRetry}>+ Try Again+ </Button>+ <Button+ nativeButton={false}+ render={+ <a+ href={CLOUDFLARE_SETUP_GUIDE_URL}+ target="_blank"+ rel="noreferrer"+ />+ }+ >+ Open Setup Guide+ </Button>+ </CardFooter>+ </Card>);}@@ -122,20 +135,20 @@ function UnauthenticatedErrorCard({ message, onRetry }: CardProps) {}return (- <div className="card w-full max-w-md bg-base-100 border border-base-300 shadow-xl">- <div className="card-body gap-4">- <h2 className="card-title">Authentication required</h2>- <p className="text-sm text-base-content/70">{message}</p>- <p className="text-sm text-base-content/70">+ <Card className="w-full max-w-md">+ <CardHeader>+ <CardTitle>Authentication required</CardTitle>+ </CardHeader>+ <CardContent className="space-y-4 text-muted-foreground">+ <p>{message}</p>+ <p>This deployment uses external authentication. Refresh your accesssession, then try again.</p>- <div className="card-actions justify-end">- <button className="btn btn-primary btn-sm" onClick={onRetry}>- Try Again- </button>- </div>- </div>- </div>+ </CardContent>+ <CardFooter className="justify-end">+ <Button onClick={onRetry}>Try Again</Button>+ </CardFooter>+ </Card>);}diff --git a/src/client/components/InlineConfirm.tsx b/src/client/components/InlineConfirm.tsxindex ee8d7c4f..9de4d0cf 100644--- a/src/client/components/InlineConfirm.tsx+++ b/src/client/components/InlineConfirm.tsx@@ -5,48 +5,73 @@ import { Button } from "@/client/components/ui/button";/*** Two-step delete for a list row: the trash icon swaps to an explicit* Remove/Cancel pair, so a stray click can't destroy anything and no dialog- * is needed.+ * is needed. With `triggerLabel`, the trash icon becomes a text button.*/export function InlineConfirm({label,+ triggerLabel,+ confirmLabel = "Remove",pending,+ disabled = false,onConfirm,}: {/** Accessible name of the trash button, for example "Remove openseo.so". */label: string;+ /** Show a text button, such as "Archive project", instead of the trash icon. */+ triggerLabel?: string;+ confirmLabel?: string;pending: boolean;+ disabled?: boolean;onConfirm: () => void;}) {const [confirming, setConfirming] = useState(false);+ const size = triggerLabel ? "sm" : "xs";if (confirming) {return (<><Buttonvariant="destructive"- size="xs"- disabled={pending}+ size={size}+ disabled={pending || disabled}onClick={() => {setConfirming(false);onConfirm();}}>- Remove+ {confirmLabel}</Button>- <Button variant="ghost" size="xs" onClick={() => setConfirming(false)}>+ <Button+ variant="ghost"+ size={size}+ onClick={() => setConfirming(false)}+ >Cancel</Button></>);}+ if (triggerLabel) {+ return (+ <Button+ variant="destructive"+ size={size}+ disabled={pending || disabled}+ onClick={() => setConfirming(true)}+ >+ {triggerLabel}+ </Button>+ );+ }+return (<Buttonvariant="ghost"size="icon-xs"className="text-destructive hover:text-destructive"aria-label={label}- disabled={pending}+ disabled={pending || disabled}onClick={() => setConfirming(true)}><Trash2 className="size-3.5" />diff --git a/src/client/features/projects/CreateProjectModal.tsx b/src/client/features/projects/CreateProjectModal.tsxindex 7d65165a..aab9437d 100644--- a/src/client/features/projects/CreateProjectModal.tsx+++ b/src/client/features/projects/CreateProjectModal.tsx@@ -1,10 +1,24 @@-import * as React from "react";import { projectsQueryOptions } from "@/client/features/projects/projectQueries";import { useNavigate } from "@tanstack/react-router";import { useMutation, useQueryClient } from "@tanstack/react-query";+import { revalidateLogic } from "@tanstack/react-form";import { toast } from "sonner";-import { Modal } from "@/client/components/Modal";+import { z } from "zod";+import { useAppForm } from "@/client/components/form/useAppForm";+import { Button } from "@/client/components/ui/button";+import {+ Dialog,+ DialogContent,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from "@/client/components/ui/dialog";+import { FieldDescription } from "@/client/components/ui/field";import { setLastProjectId } from "@/client/lib/active-project";+import {+ getErrorCode,+ getStandardErrorMessage,+} from "@/client/lib/error-messages";import {DEFAULT_LOCATION_CODE,getLanguageCode,@@ -12,25 +26,35 @@ import {import { ProjectMarketFields } from "@/client/features/projects/ProjectMarketFields";import { createProject } from "@/serverFunctions/projects";+const createProjectSchema = z.object({+ name: z.string().trim().min(1, "Project name is required"),+ domain: z.string(),+ market: z.object({ locationCode: z.number(), languageCode: z.string() }),+});++// The server sends only the error code, so the field messages live here.+const SERVER_FIELD_ERRORS: Record<string, Record<string, string>> = {+ VALIDATION_ERROR: { domain: "Enter a valid domain, like acme.com." },+ CONFLICT: {+ name: 'A project named "Default" with no domain already exists. Pick a different name or add a domain.',+ },+};+export function CreateProjectModal({ onClose }: { onClose: () => void }) {const navigate = useNavigate();const queryClient = useQueryClient();- const [name, setName] = React.useState("");- const [domain, setDomain] = React.useState("");- const [market, setMarket] = React.useState({- locationCode: DEFAULT_LOCATION_CODE,- languageCode: getLanguageCode(DEFAULT_LOCATION_CODE),- });const createMutation = useMutation({- mutationFn: () =>+ mutationFn: (values: z.infer<typeof createProjectSchema>) =>createProject({data: {- name: name.trim(),- domain: domain.trim() || undefined,- ...market,+ name: values.name.trim(),+ domain: values.domain.trim() || undefined,+ ...values.market,},}),+ // The form shows field errors inline and toasts the rest itself.+ meta: { errorToast: false },onSuccess: async (created) => {setLastProjectId(created.id);await queryClient.invalidateQueries({@@ -49,87 +73,104 @@ export function CreateProjectModal({ onClose }: { onClose: () => void }) {},});- const isPending = createMutation.isPending;-- const handleSubmit = (event: React.FormEvent) => {- event.preventDefault();- if (isPending) return;- if (!name.trim()) {- toast.error("Project name is required");- return;- }- createMutation.mutate();- };+ const form = useAppForm({+ defaultValues: {+ name: "",+ domain: "",+ market: {+ locationCode: DEFAULT_LOCATION_CODE,+ languageCode: getLanguageCode(DEFAULT_LOCATION_CODE),+ },+ },+ validationLogic: revalidateLogic(),+ validators: { onDynamic: createProjectSchema },+ onSubmit: async ({ value, formApi }) => {+ try {+ await createMutation.mutateAsync(value);+ } catch (error) {+ const fields = SERVER_FIELD_ERRORS[getErrorCode(error) ?? ""];+ if (fields) {+ formApi.setErrorMap({ onSubmit: { fields } });+ } else {+ toast.error(getStandardErrorMessage(error));+ }+ }+ },+ });return (- <Modal- maxWidth="max-w-md"- onClose={isPending ? undefined : onClose}- labelledBy="create-project-title"+ <Dialog+ open+ onOpenChange={(open) => {+ if (!open && !createMutation.isPending) onClose();+ }}>- <form onSubmit={handleSubmit} className="space-y-4">- <h2 id="create-project-title" className="text-lg font-semibold">- New project- </h2>+ <DialogContent showCloseButton={false} className="sm:max-w-md">+ <form.AppForm>+ <form.Form className="flex flex-col gap-4">+ <DialogHeader>+ <DialogTitle>New project</DialogTitle>+ </DialogHeader>- <label className="flex flex-col gap-1.5 text-sm">- <span className="font-medium">Name</span>- <input- type="text"- value={name}- onChange={(event) => setName(event.target.value)}- placeholder="Acme Inc."- maxLength={120}- autoFocus- className="input input-bordered w-full"- />- </label>+ <form.AppField name="name">+ {(field) => (+ <field.TextField+ label="Name"+ placeholder="Acme Inc."+ maxLength={120}+ required+ />+ )}+ </form.AppField>- <label className="flex flex-col gap-1.5 text-sm">- <span className="font-medium">- Domain <span className="text-base-content/50">(optional)</span>- </span>- <input- type="text"- value={domain}- onChange={(event) => setDomain(event.target.value)}- placeholder="example.com"- maxLength={255}- className="input input-bordered w-full"- />- <span className="text-xs text-base-content/50">- You can connect Search Console and set up rank tracking after- creating the project.- </span>- </label>+ <form.AppField name="domain">+ {(field) => (+ <field.TextField+ label={+ <>+ Domain{" "}+ <span className="font-normal text-muted-foreground">+ (optional)+ </span>+ </>+ }+ description="You can connect Search Console and set up rank tracking after creating the project."+ placeholder="example.com"+ maxLength={255}+ />+ )}+ </form.AppField>- <div className="flex flex-col gap-1.5">- <ProjectMarketFields value={market} onChange={setMarket} />- <span className="text-xs text-base-content/50">- Keyword, SERP, and domain data uses this country and language unless- a call asks for a different one. Change it later in project- settings.- </span>- </div>+ <div className="flex flex-col gap-2">+ <form.Field name="market">+ {(field) => (+ <ProjectMarketFields+ value={field.state.value}+ onChange={field.handleChange}+ />+ )}+ </form.Field>+ <FieldDescription>+ Keyword, SERP, and domain data uses this country and language+ unless a call asks for a different one. Change it later in+ project settings.+ </FieldDescription>+ </div>- <div className="flex justify-end gap-2">- <button- type="button"- className="btn btn-ghost btn-sm"- onClick={onClose}- disabled={isPending}- >- Cancel- </button>- <button- type="submit"- className="btn btn-primary btn-sm"- disabled={isPending}- >- Create project- </button>- </div>- </form>- </Modal>+ <DialogFooter>+ <Button+ type="button"+ variant="ghost"+ onClick={onClose}+ disabled={createMutation.isPending}+ >+ Cancel+ </Button>+ <form.SubmitButton>Create project</form.SubmitButton>+ </DialogFooter>+ </form.Form>+ </form.AppForm>+ </DialogContent>+ </Dialog>);}diff --git a/src/client/features/projects/ProjectGeneralSettings.tsx b/src/client/features/projects/ProjectGeneralSettings.tsxindex 142b2e85..7f4c886a 100644--- a/src/client/features/projects/ProjectGeneralSettings.tsx+++ b/src/client/features/projects/ProjectGeneralSettings.tsx@@ -1,4 +1,3 @@-import * as React from "react";import { projectsQueryOptions } from "@/client/features/projects/projectQueries";import { useNavigate } from "@tanstack/react-router";import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";@@ -6,6 +5,7 @@ import { toast } from "sonner";import { z } from "zod";import { revalidateLogic } from "@tanstack/react-form";import { useAppForm } from "@/client/components/form/useAppForm";+import { InlineConfirm } from "@/client/components/InlineConfirm";import { SectionHeader } from "@/client/components/PageHeader";import { QueryError, QueryState } from "@/client/components/QueryState";import { ProjectMarketFields } from "@/client/features/projects/ProjectMarketFields";@@ -155,8 +155,6 @@ function DangerSection({}) {const navigate = useNavigate();const queryClient = useQueryClient();- const [confirming, setConfirming] = React.useState(false);-const archiveMutation = useMutation({mutationFn: () => archiveProject({ data: { projectId: project.id } }),onSuccess: async () => {@@ -171,55 +169,25 @@ function DangerSection({});return (- <section className="space-y-3 border-t border-base-300 pt-8">+ <section className="space-y-3 border-t border-border pt-8"><SectionHeader title="Archive project" />-- {confirming ? (- <div className="space-y-3">- <p className="text-sm text-base-content/70">- Archiving{" "}- <span className="font-medium text-base-content">- {project.name}- </span>{" "}- removes it from your workspace and stops its scheduled rank- tracking. You can restore it later from the Projects page.- </p>- <div className="flex gap-2">- <button- type="button"- className="btn btn-error btn-sm"- onClick={() => archiveMutation.mutate()}- disabled={archiveMutation.isPending}- >- Yes, archive project- </button>- <button- type="button"- className="btn btn-ghost btn-sm"- onClick={() => setConfirming(false)}- disabled={archiveMutation.isPending}- >- Cancel- </button>- </div>- </div>- ) : (- <div className="flex items-center justify-between gap-4">- <p className="text-sm text-base-content/60">- {canArchive- ? "Archive this project to remove it from your organization."- : "You can't archive your only project."}- </p>- <button- type="button"- className="btn btn-outline btn-error btn-sm shrink-0"- onClick={() => setConfirming(true)}+ <div className="flex items-center justify-between gap-4">+ <p className="text-sm text-muted-foreground">+ {canArchive+ ? "Archiving removes the project from your workspace and stops its scheduled rank tracking. You can restore it later from the Projects page."+ : "You can't archive your only project."}+ </p>+ <div className="flex shrink-0 gap-2">+ <InlineConfirm+ label={`Archive ${project.name}`}+ triggerLabel="Archive project"+ confirmLabel="Yes, archive project"+ pending={archiveMutation.isPending}disabled={!canArchive}- >- Archive project- </button>+ onConfirm={() => archiveMutation.mutate()}+ /></div>- )}+ </div></section>);}diff --git a/src/routes/_app/projects.tsx b/src/routes/_app/projects.tsxindex e7b59b62..c77386fd 100644--- a/src/routes/_app/projects.tsx+++ b/src/routes/_app/projects.tsx@@ -8,7 +8,10 @@ import {getArchivedProjects,restoreProject,} from "@/serverFunctions/projects";+import { PageHeader, SectionHeader } from "@/client/components/PageHeader";import { QueryState } from "@/client/components/QueryState";+import { Badge } from "@/client/components/ui/badge";+import { Button } from "@/client/components/ui/button";import { getLastProjectId } from "@/client/lib/active-project";import { CreateProjectModal } from "@/client/features/projects/CreateProjectModal";@@ -30,36 +33,29 @@ function ProjectsPage() {return (<div className="h-full overflow-auto px-4 py-8 pb-24 md:px-6 md:py-12 md:pb-8"><div className="mx-auto w-full max-w-2xl space-y-6">- <div className="flex items-start justify-between gap-4">- <div>- <h1 className="text-2xl font-bold tracking-tight">Projects</h1>- <p className="mt-1 text-sm text-base-content/60">- Each project has its own Search Console, rank tracking, and- audits.- </p>- </div>- <button- type="button"- className="btn btn-primary btn-sm shrink-0"- onClick={() => setCreating(true)}- >- <Plus className="size-4" />- New project- </button>- </div>+ <PageHeader+ title="Projects"+ description="Each project has its own Search Console, rank tracking, and audits."+ actions={+ <Button onClick={() => setCreating(true)}>+ <Plus data-icon="inline-start" />+ New project+ </Button>+ }+ /><QueryStatequery={projectsQuery}errorFallback="Failed to load projects">{(data) => (- <ul className="divide-y divide-base-300 overflow-hidden rounded-lg border border-base-300 bg-base-100">+ <ul className="divide-y divide-border overflow-hidden rounded-lg border border-border bg-card">{data.map((project) => (<li key={project.id}><Linkto="/p/$projectId/settings"params={{ projectId: project.id }}- className="flex items-center justify-between gap-3 p-3 transition-colors hover:bg-base-200/40"+ className="flex items-center justify-between gap-3 p-3 transition-colors hover:bg-muted"><span className="flex min-w-0 flex-col"><span className="flex items-center gap-2">@@ -67,16 +63,16 @@ function ProjectsPage() {{project.name}</span>{project.id === currentProjectId ? (- <span className="shrink-0 rounded-full bg-base-300/70 px-1.5 py-0.5 text-[10px] font-medium uppercase tracking-wide text-base-content/60">+ <Badge variant="secondary" size="sm">Current- </span>+ </Badge>) : null}</span>- <span className="truncate text-xs text-base-content/50">+ <span className="truncate text-xs text-muted-foreground">{project.domain ?? "No domain set"}</span></span>- <ChevronRight className="size-4 shrink-0 text-base-content/40" />+ <ChevronRight className="size-4 shrink-0 text-muted-foreground" /></Link></li>))}@@ -118,29 +114,29 @@ function ArchivedProjects() {return (<section className="space-y-3">- <h2 className="text-sm font-medium text-base-content/50">Archived</h2>- <ul className="divide-y divide-base-300 overflow-hidden rounded-lg border border-base-300 bg-base-100">+ <SectionHeader title="Archived" />+ <ul className="divide-y divide-border overflow-hidden rounded-lg border border-border bg-card">{archived.map((project) => (<likey={project.id}className="flex items-center justify-between gap-3 p-3"><span className="flex min-w-0 flex-col">- <span className="truncate font-medium text-base-content/70">+ <span className="truncate font-medium text-muted-foreground">{project.name}</span>- <span className="truncate text-xs text-base-content/50">+ <span className="truncate text-xs text-muted-foreground">{project.domain ?? "No domain set"}</span></span>- <button- type="button"- className="btn btn-ghost btn-sm shrink-0"+ <Button+ variant="ghost"+ size="sm"onClick={() => restoreMutation.mutate(project.id)}disabled={restoreMutation.isPending}>Restore- </button>+ </Button></li>))}</ul>diff --git a/src/server/features/projects/services/projects.test.ts b/src/server/features/projects/services/projects.test.tsindex 75027090..8731971d 100644--- a/src/server/features/projects/services/projects.test.ts+++ b/src/server/features/projects/services/projects.test.ts@@ -116,11 +116,7 @@ describe("project service", () => {});it("maps the reserved Default conflict to a friendly CONFLICT", async () => {- mocks.createProject.mockRejectedValue(- new Error(- "UNIQUE constraint failed: projects.projects_one_default_per_organization_idx",- ),- );+ mocks.createProject.mockRejectedValue(uniqueViolation());await expect(createProject("org_1", { name: "Default", domain: undefined }),@@ -163,11 +159,7 @@ describe("project service", () => {describe("restoreProject", () => {it("maps the Default singleton conflict to a friendly CONFLICT", async () => {- mocks.restoreProject.mockRejectedValue(- new Error(- "UNIQUE constraint failed: projects.projects_one_default_per_organization_idx",- ),- );+ mocks.restoreProject.mockRejectedValue(uniqueViolation());await expect(restoreProject("org_1", { archivedProjectId: "project_default" }),@@ -175,3 +167,12 @@ describe("project service", () => {});});});++// Drizzle wraps the driver's error, so the UNIQUE text is only on the cause.+function uniqueViolation() {+ return new Error("Failed query: insert into projects", {+ cause: new Error(+ "UNIQUE constraint failed: projects.organization_id: SQLITE_CONSTRAINT",+ ),+ });+}diff --git a/src/server/features/projects/services/projects.ts b/src/server/features/projects/services/projects.tsindex 27ba7961..86bbc2d1 100644--- a/src/server/features/projects/services/projects.ts+++ b/src/server/features/projects/services/projects.ts@@ -47,6 +47,15 @@ function resolveMarketInput(input: {return { locationCode, languageCode };}+// Drizzle wraps the driver error in a "Failed query" error, so check the cause+// chain. SQLite reports the violation in the message, Postgres as code 23505.+function isUniqueViolation(error: unknown): boolean {+ if (!(error instanceof Error)) return false;+ if (error.message.includes("UNIQUE constraint failed")) return true;+ if ("code" in error && error.code === "23505") return true;+ return isUniqueViolation(error.cause);+}+// The projects table's only unique index guards the auto-created ("Default",// null) singleton. A UNIQUE violation while writing exactly that name/domain// therefore means one already exists — gating on the input (not just the error@@ -55,12 +64,7 @@ function isReservedDefaultConflict(error: unknown,input: { name: string; domain?: string },) {- return (- input.name === "Default" &&- !input.domain &&- error instanceof Error &&- error.message.includes("UNIQUE constraint failed")- );+ return input.name === "Default" && !input.domain && isUniqueViolation(error);}const RESERVED_DEFAULT_MESSAGE =@@ -176,10 +180,7 @@ export async function restoreProject(// The Default singleton index is the only unique index on projects, and// restore only writes archived_at — so a UNIQUE failure can only mean an// active Default/no-domain project already exists.- if (- error instanceof Error &&- error.message.includes("UNIQUE constraint failed")- ) {+ if (isUniqueViolation(error)) {throw new AppError("CONFLICT",'An active project named "Default" with no domain already exists. Rename it first, then restore this one.',