All files / src/pages website.tsx

86.02% Statements 80/93
89.71% Branches 96/107
86.66% Functions 13/15
90.69% Lines 78/86

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393                                              61x 61x   61x 61x   61x 61x 61x 61x 61x   61x 61x   61x 61x 61x   61x 61x     61x 61x           61x 25x 22x 3x           61x 25x 3x       61x 2x 2x       61x 61x 26x         23x     3x                               3x     61x 1x 1x 1x 1x 1x       1x       61x 2x 2x 2x 2x 1x   1x   2x       61x 2x 2x 2x 2x 1x   1x   2x       61x 2x 2x 2x 1x   1x       61x   61x 2x                         59x 3x                                 1x                             56x 61x 61x     61x                     61x       61x                                                                                                                                                                                                                 2x 2x 2x                                                                                                                                
// Website Page - Manage pro dedicated website
import { useState, useEffect } from "react";
import { Globe, Copy, Check } from "lucide-react";
import { useQueryClient } from "@tanstack/react-query";
import { useBlocker } from "@tanstack/react-router";
import { usePro } from "@/lib/pro-context";
import {
	websiteApi,
	getErrorMessage,
	type WebsiteBuildJob,
} from "@/lib/api";
import { notify } from "@/lib/notify";
import { queryKeys } from "@/lib/query-keys";
import { useWebsiteSettings, useWebsiteTemplates } from "@/hooks/queries/useWebsiteQueries";
import { Button } from "@/components/ui/button";
import { StickyPageHeader } from "@/components/ui/sticky-page-header";
import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card";
import { Skeleton } from "@/components/ui/skeleton";
import { TemplateGallery } from "@/components/website/TemplateGallery";
import { BuildStatusMonitor } from "@/components/website/BuildStatusMonitor";
import { DomainSettings } from "@/components/website/DomainSettings";
 
export default function WebsitePage() {
	const { proId, pro, isLoading: proLoading, error: proError } = usePro();
	const queryClient = useQueryClient();
 
	const { data: settingsData, isLoading: settingsLoading } = useWebsiteSettings(proId);
	const { data: templates = [], isLoading: templatesLoading } = useWebsiteTemplates(proId);
 
	const website = settingsData?.website ?? null;
	const previewUrl = settingsData?.previewUrl ?? null;
	const publishedUrl = settingsData?.publishedUrl ?? null;
	const customDomainUrl = settingsData?.customDomainUrl ?? null;
	const cnameTarget = settingsData?.cnameTarget ?? null;
 
	const [polledBuild, setPolledBuild] = useState<WebsiteBuildJob | null>(null);
	const latestBuild = polledBuild ?? settingsData?.latestBuild ?? null;
 
	const [saving, setSaving] = useState(false);
	const [publishing, setPublishing] = useState(false);
	const [cancelling, setCancelling] = useState(false);
 
	const [selectedTemplate, setSelectedTemplate] = useState<string>("");
	const [copied, setCopied] = useState(false);
 
	// Block navigation when template selection has unsaved changes
	const hasChanges = !!website && website.templateId !== selectedTemplate && selectedTemplate !== "";
	useBlocker({
		shouldBlockFn: () => hasChanges,
		withResolver: true,
	});
 
	// Sync selected template when settings data loads
	useEffect(() => {
		if (settingsData?.website?.templateId) {
			setSelectedTemplate(settingsData.website.templateId);
		I} else if (templates.length > 0) {
			setSelectedTemplate(templates[0].id);
		}
	}, [settingsData?.website?.templateId, templates]);
 
	// Clear polled build when settings data refreshes
	useEffect(() => {
		if (settingsData?.latestBuild) {
			setPolledBuild(null);
		}
	}, [settingsData?.latestBuild]);
 
	const invalidateWebsite = () => {
		Iif (!proId) return;
		queryClient.invalidateQueries({ queryKey: queryKeys.website.settings(proId) });
	};
 
	// Poll for build status while building
	const buildStatus = latestBuild?.status;
	useEffect(() => {
		if (
			!proId ||
			!buildStatus ||
			!["pending", "queued", "building", "deploying"].includes(buildStatus)
		) {
			return;
		}
 
		const pollInterval = setInterval(async () => {
			try {
				const status = await websiteApi.getBuildStatus(proId);
				setPolledBuild(status.latestBuild);
 
				if (
					status.latestBuild &&
					["deployed", "failed", "cancelled"].includes(status.latestBuild.status)
				) {
					queryClient.invalidateQueries({ queryKey: queryKeys.website.settings(proId) });
				}
			} catch {
				// Silently fail polling
			}
		}, 3000);
 
		return () => clearInterval(pollInterval);
	}, [proId, buildStatus, queryClient]);
 
	const handleSave = async () => {
		Iif (!proId) return;
		try {
			setSaving(true);
			await websiteApi.updateSettings(proId, { templateId: selectedTemplate });
			invalidateWebsite();
		} catch (err) {
			notify.error(getErrorMessage(err));
		} finally {
			setSaving(false);
		}
	};
 
	const handlePublish = async () => {
		Iif (!proId) return;
		try {
			setPublishing(true);
			const result = await websiteApi.publish(proId);
			setPolledBuild(result.buildJob);
		} catch (err) {
			notify.error(getErrorMessage(err));
		} finally {
			setPublishing(false);
		}
	};
 
	const handleCancelBuild = async () => {
		Iif (!proId) return;
		try {
			setCancelling(true);
			await websiteApi.cancelBuild(proId);
			invalidateWebsite();
		} catch (err) {
			notify.error(getErrorMessage(err));
		} finally {
			setCancelling(false);
		}
	};
 
	const handlePreview = async () => {
		Iif (!proId) return;
		try {
			const tokenData = await websiteApi.getPreviewToken(proId);
			window.open(tokenData.previewUrl, "_blank");
		} catch (err) {
			notify.error(getErrorMessage(err));
		}
	};
 
	const loading = settingsLoading || templatesLoading;
 
	if (loading || proLoading) {
		return (
			<div className="space-y-6">
				<Skeleton className="h-8 w-48" />
				<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
					<Skeleton className="h-48" />
					<Skeleton className="h-48" />
					<Skeleton className="h-48" />
				</div>
				<Skeleton className="h-64" />
			</div>
		);
	}
 
	if (!proId) {
		return (
			<div className="p-6 text-center">
				<h1 className="text-xl font-semibold text-foreground-default mb-2">
					No Pro Profile
				</h1>
				<p className="text-foreground-muted mb-4">
					You need to be associated with a pro to manage a website.
				</p>
				{proError && (
					<p className="text-red-600 text-sm">
						Error loading pro: {proError}
					</p>
				)}
				<p className="text-foreground-muted text-sm mt-4">
					Try{" "}
					<button
						type="button"
						onClick={() => window.location.reload()}
						className="text-primary-600 underline"
					>
						refreshing the page
					</button>{" "}
					or{" "}
					<a href="/login" className="text-primary-600 underline">
						logging in again
					</a>
					.
				</p>
			</div>
		);
	}
 
	const isProPublished = pro?.status === "published";
	const canPublish = isProPublished && pro?.slug && !hasChanges;
	const isBuilding = ["pending", "queued", "building", "deploying"].includes(
		latestBuild?.status || "",
	);
	const publishDisabledReason = !isProPublished
		? "Your profile is in Draft. An Interioring admin must mark it Published before you can publish your website."
		: !pro?.slug
			? "Set a pro slug in your profile"
			: hasChanges
				? "Save your changes first"
				: isBuilding
					? "Build in progress"
					: null;
 
	const visitSiteUrl =
		publishedUrl ||
		(latestBuild?.status === "deployed" && latestBuild?.deploymentUrl) ||
		null;
 
	return (
		<div className="space-y-6">
			<StickyPageHeader>
				<div className="w-full">
					<div className="flex items-center justify-between w-full gap-4">
						<h1 className="text-2xl font-bold text-foreground-default flex items-center gap-2 flex-shrink-0">
							<Globe className="h-6 w-6" />
							Website
						</h1>
						<div className="flex items-center gap-3">
							{previewUrl ? (
								<Button variant="outline" size="sm" onClick={handlePreview}>
									Preview
								</Button>
							) : pro?.slug ? null : (
								<span className="text-xs text-foreground-muted">
									Set a URL slug in <a href="/profile" className="text-primary-600 underline">Profile</a> to enable preview
								</span>
							)}
							{hasChanges && (
								<Button size="sm" onClick={handleSave} disabled={saving}>
									{saving ? "Saving..." : "Save Changes"}
								</Button>
							)}
							<Button
								size="sm"
								onClick={handlePublish}
								disabled={!canPublish || publishing || isBuilding}
								variant={hasChanges ? "outline" : "default"}
								title={publishDisabledReason || undefined}
							>
								{publishing
									? "Publishing..."
									: isBuilding
										? "Building..."
										: website?.status === "published"
											? "Republish"
											: "Publish"}
							</Button>
						</div>
					</div>
					{!isProPublished && (
						<div className="text-sm text-amber-700 bg-amber-50 border border-amber-200 rounded-md px-3 py-2 mt-2 space-y-1">
							<p>
								<strong>Your profile is in Draft.</strong> Before your website
								can go live, an Interioring admin needs to change your{" "}
								<strong>Publish status</strong> from Draft to Published.
							</p>
							<p className="text-amber-800/80">
								Email{" "}
								<a
									href="mailto:support@interioring.com?subject=Please%20publish%20my%20profile"
									className="underline"
								>
									support@interioring.com
								</a>{" "}
								to request approval.
							</p>
						</div>
					)}
				</div>
			</StickyPageHeader>
 
			{/* Publish Status + Website Address — side by side on large screens */}
			<div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
				<BuildStatusMonitor
					websiteStatus={website?.status}
					lastPublishedAt={website?.lastPublishedAt ?? null}
					hasUnpublishedChanges={website?.hasUnpublishedChanges}
					latestBuild={latestBuild}
					isBuilding={isBuilding}
					cancelling={cancelling}
					onCancelBuild={handleCancelBuild}
				/>
 
				{/* Website Address */}
				<Card>
					<CardHeader>
						<CardTitle>Website Address</CardTitle>
					</CardHeader>
					<CardContent>
						{pro?.slug ? (
							<div className="flex items-center justify-between p-4 bg-background-subtle rounded-lg">
								<div className="flex items-center gap-3 min-w-0">
									<div className="flex-shrink-0 w-8 h-8 bg-primary-50 rounded-lg flex items-center justify-center">
										<svg className="w-4 h-4 text-primary-600" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
											<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9m-9 9a9 9 0 019-9" />
										</svg>
									</div>
									<div className="min-w-0">
										<p className="font-medium text-foreground-default truncate">
											{pro.slug}.interioring.com
										</p>
										{customDomainUrl && (
											<p className="text-sm text-foreground-muted truncate">
												{website?.customDomain}
											</p>
										)}
									</div>
								</div>
								<div className="flex items-center gap-2 flex-shrink-0">
									<button
										type="button"
										title="Copy URL"
										onClick={() => {
											navigator.clipboard.writeText(`https://${pro.slug}.interioring.com`);
											setCopied(true);
											setTimeout(() => setCopied(false), 2000);
										}}
										className="p-2 rounded-lg hover:bg-background-muted transition-colors text-foreground-muted"
									>
										{copied ? <Check className="w-4 h-4 text-success" /> : <Copy className="w-4 h-4" />}
									</button>
									{website?.status === "published" && visitSiteUrl && (
										<a
											href={visitSiteUrl}
											target="_blank"
											rel="noopener noreferrer"
											className="inline-flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-primary-700 bg-primary-50 hover:bg-primary-100 rounded-md transition-colors"
										>
											Visit Site
											<svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
												<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
											</svg>
										</a>
									)}
									{website?.status !== "published" && (
										<span className="text-xs text-foreground-subtle">Not published yet</span>
									)}
								</div>
							</div>
						) : (
							<div className="flex items-center gap-3 p-4 bg-background-subtle rounded-lg">
								<svg className="w-5 h-5 text-foreground-subtle flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
									<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1" />
								</svg>
								<p className="text-sm text-foreground-muted">
									Set your pro slug in{" "}
									<a href="/profile" className="text-primary-600 font-medium hover:underline">
										Profile
									</a>{" "}
									to get your website address.
								</p>
							</div>
						)}
					</CardContent>
				</Card>
			</div>
 
			{/* Template Selection */}
			<TemplateGallery
				templates={templates}
				selectedTemplate={selectedTemplate}
				onSelect={setSelectedTemplate}
			/>
 
			{/* Custom Domain */}
			{pro?.slug && (
				<DomainSettings
					proId={proId}
					proSlug={pro.slug}
					customDomain={website?.customDomain}
					customDomainVerified={website?.customDomainVerified}
					customDomainUrl={customDomainUrl}
					cnameTarget={cnameTarget}
					onDomainChanged={invalidateWebsite}
				/>
			)}
		</div>
	);
}