Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions database/database-generated.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4488,6 +4488,10 @@ export type Database = {
[_ in never]: never
}
Functions: {
delete_project: {
Args: { p_confirm: string; p_project_id: number }
Returns: boolean
}
find_project: {
Args: { p_org_ref: string; p_proj_ref: string }
Returns: {
Expand Down
51 changes: 43 additions & 8 deletions editor/components/dialogs/rename-dialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import {
import {
Field,
FieldError,
FieldDescription,
FieldGroup,
FieldLabel,
} from "@/components/ui/field";
Expand All @@ -29,6 +30,14 @@ interface RenameDialogProps {
title?: string | React.ReactNode;
description?: string | React.ReactNode;
itemType?: string;
/**
* Optional short hint shown under the input (e.g. naming guideline).
*/
nameHint?: string | React.ReactNode;
/**
* Optional validation function. Return a user-facing message when invalid.
*/
validateName?: (name: string) => string | null;
}

// Add loading state to the component
Expand All @@ -39,31 +48,49 @@ export function RenameDialog({
title = "Rename item",
description = "Enter a new name for this item.",
itemType = "item",
nameHint,
validateName,
...props
}: React.ComponentProps<typeof Dialog> & RenameDialogProps) {
const [name, setName] = useState(currentName);
const [error, setError] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(false);
const [showValidation, setShowValidation] = useState(false);

const trimmedName = name.trim();
// Avoid "flicker" while typing: only show validation errors after blur or submit.
const validationError =
showValidation && trimmedName ? validateName?.(trimmedName) : null;
const effectiveError = error ?? validationError ?? null;
const isUnchanged = trimmedName === currentName.trim();
const canSubmit = !isLoading && !!trimmedName && !isUnchanged;

// Update the submit handler to handle async operations
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
setShowValidation(true);

// Validate input
if (!name.trim()) {
if (!trimmedName) {
setError(`${itemType} name cannot be empty`);
return;
}

const validationMessage = validateName?.(trimmedName);
if (validationMessage) {
setError(validationMessage);
return;
}

// If name hasn't changed
if (name.trim() === currentName.trim()) {
if (isUnchanged) {
props.onOpenChange?.(false);
return;
}

try {
setIsLoading(true);
const result = await Promise.resolve(onRename(id, name.trim()));
const result = await Promise.resolve(onRename(id, trimmedName));

// Only close if the operation was successful or returned nothing (void)
if (result !== false) {
Expand All @@ -74,7 +101,11 @@ export function RenameDialog({
}
} catch (err) {
console.error("Error renaming:", err);
setError(`An error occurred while renaming the ${itemType}.`);
if (err instanceof Error && err.message) {
setError(err.message);
} else {
setError(`An error occurred while renaming the ${itemType}.`);
}
} finally {
setIsLoading(false);
}
Expand All @@ -89,7 +120,7 @@ export function RenameDialog({
<DialogDescription>{description}</DialogDescription>
</DialogHeader>
<FieldGroup className="py-4 gap-4">
<Field>
<Field data-invalid={!!effectiveError}>
<FieldLabel htmlFor="name" className="text-left">
Name
</FieldLabel>
Expand All @@ -100,12 +131,16 @@ export function RenameDialog({
setName(e.target.value);
setError(null);
}}
onBlur={() => setShowValidation(true)}
placeholder={`Enter ${itemType} name`}
className={error ? "border-red-500" : ""}
aria-invalid={!!effectiveError}
autoFocus
disabled={isLoading}
/>
<FieldError>{error}</FieldError>
{nameHint && <FieldDescription>{nameHint}</FieldDescription>}
<div className="min-h-5">
<FieldError>{effectiveError}</FieldError>
</div>
</Field>
</FieldGroup>
<DialogFooter>
Expand All @@ -114,7 +149,7 @@ export function RenameDialog({
Cancel
</Button>
</DialogClose>
<Button type="submit" disabled={isLoading}>
<Button type="submit" disabled={!canSubmit}>
{isLoading ? "Renaming..." : "Rename"}
</Button>
</DialogFooter>
Expand Down
20 changes: 13 additions & 7 deletions editor/scaffolds/workspace/sidebar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ import { Badge } from "@/components/ui/badge";
import { Labels } from "@/k/labels";
import { Button } from "@/components/ui-editor/button";
import { ShineBorder } from "@/www/ui/shine-border";
import { validateProjectName } from "@/services/utils/regex";
import type {
GDocument,
OrganizationWithAvatar,
Expand Down Expand Up @@ -327,11 +328,16 @@ export function NavProjects({
title="Rename Project"
description="Enter a new name for this project."
currentName={renameProjectDialog.data?.name}
nameHint="Lowercase letters, numbers, and dashes (e.g. my-project)."
validateName={(name) => validateProjectName(name)}
onRename={async (id: string, newName: string): Promise<boolean> => {
const { count } = await client
const { count, error } = await client
.from("project")
.update({ name: newName }, { count: "exact" })
.eq("id", parseInt(id));
if (error) {
throw new Error("Couldn’t rename the project. Please try again.");
}
return count === 1;
// TODO: needs to revalidate
}}
Expand All @@ -353,13 +359,13 @@ export function NavProjects({
}
placeholder={deleteProjectDialog.data?.match}
match={deleteProjectDialog.data?.match}
onDelete={async ({ id }) => {
const { count, error } = await client
.from("project")
.delete({ count: "exact" })
.eq("id", id);
onDelete={async ({ id }, user_confirmation_txt) => {
const { data, error } = await client.rpc("delete_project", {
p_project_id: id,
p_confirm: user_confirmation_txt,
});
if (error) return false;
if (count === 1) {
if (data === true) {
// TODO: needs to revalidate
router.replace(`/${orgname}`);
return true;
Expand Down
17 changes: 17 additions & 0 deletions editor/services/utils/regex.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,23 @@ export const username_validation_messages = {
taken: "This name is taken",
} as const;

/**
* Project name must match DB `project_name_check`.
*
* DB constraint: `^[a-z\d](?:[a-z\d]|-(?=[a-z\d])){1,38}$`
* - lowercase letters + digits
* - dashes allowed, but not consecutively and not at the end
* - length: 2–39
*/
export const PROJECT_NAME_REGEX = /^[a-z\d](?:[a-z\d]|-(?=[a-z\d])){1,38}$/;

export function validateProjectName(name: string): string | null {
if (!PROJECT_NAME_REGEX.test(name)) {
return "Use 2–39 characters: lowercase letters, numbers, and single dashes (e.g. my-project).";
}
return null;
}

/**
* Regex for validating a database name, table name, schema name, etc.
*/
Expand Down
Loading