Back

0% Statements 0/531
0% Branches 0/1
0% Functions 0/1
0% Lines 0/531

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 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       
import { speak } from '@wordpress/a11y';
import apiFetch from '@wordpress/api-fetch';
import { useEffect, useMemo, useRef, useState } from '@wordpress/element';
import { decodeEntities } from '@wordpress/html-entities';
import { __, _n, _x, sprintf } from '@wordpress/i18n';
import { ButtonLink, Notice, Stack } from '@wordpress/ui';
import { DifmOfferBanner, type DifmOffer } from '../difm-offer/difm-offer-banner.tsx';
import { createAboutPage } from '../lib/about-page.ts';
import { fireConfetti } from '../lib/confetti.ts';
import { createContactPage } from '../lib/contact-page.ts';
import { createEventsPage } from '../lib/events-page.ts';
import { createFirstPostDraft } from '../lib/first-post.ts';
import { createGalleryPage } from '../lib/gallery-page.ts';
import { createPortfolioPiece } from '../lib/portfolio-piece.ts';
import {
	contextFromInferred,
	contextFromTaskIds,
	setTracksContext,
	trackTaskClicked,
	trackTaskCtaClicked,
	trackTaskSkipped,
	trackViewed,
	trackWizardCompleted,
	type TaskStatus,
} from '../lib/tracks.ts';
import { createVideoPage } from '../lib/video-page.ts';
import { Layout } from './layout.tsx';
import {
	nextIncompleteId,
	isCompleteOnClickTask,
	isTaskActionable,
	recordsWizardCompleted,
	resolveCtaUrl,
	tasksFromFixture,
	type EnrichedTask,
	type LaunchpadData,
	type SiteData,
} from './model.ts';
import { TailoredListSkeleton } from './skeleton.tsx';
import { TaskCard, type BusyAction } from './task-card.tsx';
import type { GoalSlug, SiteCopy, TailoredOutput, TailorResult } from '../lib/types.ts';

import './style.scss';

/**
 * Navigate the browser to a task's deeplink (a Calypso path or wp-admin URL).
 *
 * @param url - The destination URL.
 */
function navigate( url: string ): void {
	window.location.href = url;
}

const DASHBOARD_URL = 'index.php';

interface Props {
	// In-flight tailor promise on the wizard→list path. The list waits for it to
	// settle before reading GET /ai-launchpad, otherwise the GET races the PUT and
	// returns an empty list. Its resolved result is a local fallback when the read
	// yields nothing. Omitted for returning users.
	pendingTailor?: Promise< TailorResult >;

	// The composite read the host already fetched, to avoid refetching the same
	// endpoint. Omitted on the wizard→list path.
	initialData?: LaunchpadData;

	// Site context for the preview card, passed on the wizard→list path too so the
	// skeleton can show the preview. The fetched site takes precedence.
	site?: SiteData;

	// The wizard goal, used for the heading until the AI output supplies its own.
	goal?: GoalSlug;

	// The site-language copy the page tasks write into the pages they create.
	copy: SiteCopy;

	// Set only when pendingTailor came from a finished wizard, so bypassed loads record no completion.
	fromWizard?: boolean;
}

/**
 * The tailored launchpad list: task cards rendered from the AI output inside a
 * layout with a heading, "X of N completed" progress, and a site preview. The
 * first incomplete task auto-expands; each task offers an action-specific CTA and
 * "Skip". While loading, a skeleton is shown in the same layout.
 *
 * @param props               - Component props.
 * @param props.pendingTailor - In-flight tailor call to await before fetching.
 * @param props.initialData   - Composite read supplied by the host (returning users).
 * @param props.site          - Site context for the preview (always supplied by the host).
 * @param props.goal          - The wizard goal (wizard→list path), for the heading.
 * @param props.copy          - Site-language copy for the pages the tasks create.
 * @param props.fromWizard    - Whether pendingTailor came from the wizard.
 * @return The tailored-list element.
 */
export function TailoredList( {
	pendingTailor,
	initialData,
	site,
	goal,
	copy,
	fromWizard = false,
}: Props ) {
	// Returning users seed straight from initialData so the first frame isn't the
	// loading copy. The wizard→list path has no initialData and starts as loading.
	const [ tasks, setTasks ] = useState< EnrichedTask[] | null >( () => initialData?.tasks ?? null );
	const [ output, setOutput ] = useState< TailoredOutput | null >(
		() => initialData?.ai_output?.payload ?? null
	);
	const [ skippedIds, setSkippedIds ] = useState< Set< string > >( () => new Set() );
	// Carries both which task and which of its actions is in flight, so each button
	// shows its own spinner instead of the task's primary CTA spinning for every action.
	const [ busy, setBusy ] = useState< { id: string; action: BusyAction } | null >( null );
	// The single expanded card (accordion: only one open at a time). `null` means
	// every card is collapsed — a state the user can reach by toggling the open card
	// shut, which must not auto-reopen.
	const [ openId, setOpenId ] = useState< string | null >( () =>
		initialData?.tasks ? nextIncompleteId( initialData.tasks ) : null
	);
	// Guards the one-time auto-open so the load effect doesn't fight a user who has
	// collapsed every card.
	const didAutoOpen = useRef( !! initialData?.tasks );
	// Seeded from the read (returning users) or the host's `site` prop (wizard path),
	// then overridden once the read lands.
	const [ siteUrl, setSiteUrl ] = useState< string | null >(
		() => initialData?.site?.url ?? site?.url ?? null
	);
	const [ siteTitle, setSiteTitle ] = useState< string | null >(
		() => initialData?.site?.title ?? site?.title ?? null
	);
	// The Site Editor URL: the preview thumbnail's quick link; null on classic themes.
	const [ siteEditUrl, setSiteEditUrl ] = useState< string | null >(
		() => initialData?.site?.edit_url ?? site?.edit_url ?? null
	);
	// Set when the tailored list could not be saved: an error with "Try again" renders in place of
	// a list nobody saved, whose progress would vanish on the next visit.
	const [ saveError, setSaveError ] = useState< TailorResult[ 'saveError' ] | null >( null );
	// Set once "Try again" has saved the list, so the load below reads it back like any other.
	const [ savedOnRetry, setSavedOnRetry ] = useState( false );
	const [ retrying, setRetrying ] = useState( false );
	const [ retryFailed, setRetryFailed ] = useState( false );
	// The free DIFM offer under the task list; null when the server withholds it or the user dismisses it.
	const [ difmOffer, setDifmOffer ] = useState< DifmOffer | null >(
		() => initialData?.difm_offer ?? null
	);
	// Set once the server latches the list as done (here or elsewhere): celebrate, then hand off to the Dashboard.
	const [ allDone, setAllDone ] = useState( false );

	// One viewed event per screen shown; the launchpad screen includes its
	// loading skeleton. The host seeds the context before mounting this view.
	useEffect( () => {
		trackViewed( { step: 'launchpad' } );
	}, [] );

	useEffect( () => {
		// Returning users: render from the data the host already fetched.
		if ( initialData ) {
			setTasks( initialData.tasks );
			setAllDone( !! initialData.list_completed );
			setOutput( initialData.ai_output?.payload ?? null );
			setDifmOffer( initialData.difm_offer ?? null );
			if ( initialData.site ) {
				setSiteUrl( initialData.site.url ?? null );
				setSiteTitle( initialData.site.title ?? null );
				setSiteEditUrl( initialData.site.edit_url ?? null );
			}
			return;
		}

		let cancelled = false;
		( async () => {
			// Wait for the tailor call to settle so the PUT has persisted before we
			// read it back. A rejected tailor still gives its in-memory output as a fallback.
			const result = await Promise.resolve( pendingTailor ).catch( () => undefined );
			if ( result?.saveError && ! savedOnRetry ) {
				if ( ! cancelled ) {
					setSaveError( result.saveError );
				}
				return;
			}

			let data: LaunchpadData | null = null;
			try {
				data = await apiFetch< LaunchpadData >( { path: '/wpcom/v2/ai-launchpad' } );
			} catch {
				// Read failed; fall back to the in-memory result below.
			}
			if ( cancelled ) {
				return;
			}

			if ( data?.site ) {
				setSiteUrl( data.site.url ?? null );
				// blogname is stored HTML-escaped; decode it or the preview renders literal entities. A
				// present-but-blank title stays blank (matches the initial read in app.tsx), only a
				// missing one coalesces to null.
				setSiteTitle( data.site.title != null ? decodeEntities( data.site.title ) : null );
				setSiteEditUrl( data.site.edit_url ?? null );
			}
			setDifmOffer( data?.difm_offer ?? null );

			let nextOutput: TailoredOutput | null = null;
			let nextTasks: EnrichedTask[] = [];
			if ( data && data.tasks.length > 0 ) {
				nextOutput = data.ai_output?.payload ?? null;
				nextTasks = data.tasks;
			} else if ( result?.output ) {
				// Read returned nothing: render the in-memory result instead.
				nextOutput = result.output;
				nextTasks = tasksFromFixture( result.output );
			}
			setOutput( nextOutput );
			setTasks( nextTasks );
			setAllDone( !! data?.list_completed );

			// The wizard→list handoff: the user has completed the wizard and landed on
			// their tasklist. Seed the context synchronously (from exactly what will
			// render) so the event carries the freshly inferred props instead of
			// waiting a render cycle. An empty landing (tailor and read both failed)
			// is an error state, not a tasklist — no completion is recorded for it.
			if ( recordsWizardCompleted( fromWizard, !! pendingTailor, nextTasks.length ) ) {
				setTracksContext( contextFromInferred( nextOutput?.inferred ) );
				setTracksContext( contextFromTaskIds( nextTasks.map( task => task.id ) ) );
				trackWizardCompleted();
			}
		} )();
		return () => {
			cancelled = true;
		};
	}, [ pendingTailor, initialData, savedOnRetry, fromWizard ] );

	useEffect( () => {
		if ( ! allDone ) {
			return;
		}
		fireConfetti();
		const timer = setTimeout( () => navigate( DASHBOARD_URL ), 3000 );
		return () => clearTimeout( timer );
	}, [ allDone ] );

	// Keep the shared Tracks context in step with what is actually rendered, on
	// both the wizard→list path (fresh tailor) and the returning-user path.
	useEffect( () => {
		if ( output?.inferred ) {
			setTracksContext( contextFromInferred( output.inferred ) );
		}
		if ( tasks && tasks.length > 0 ) {
			setTracksContext( contextFromTaskIds( tasks.map( task => task.id ) ) );
		}
	}, [ tasks, output ] );

	// Open the first incomplete card once the tasks first arrive on the wizard→list
	// path. Guarded so it runs only once and never reopens a collapsed list.
	useEffect( () => {
		if ( ! didAutoOpen.current && tasks && tasks.length > 0 ) {
			setOpenId( nextIncompleteId( tasks ) );
			didAutoOpen.current = true;
		}
	}, [ tasks ] );

	const visibleTasks = useMemo(
		() =>
			( tasks ?? [] ).map( task =>
				skippedIds.has( task.id ) ? { ...task, completed: true } : task
			),
		[ tasks, skippedIds ]
	);

	// The task's state for the task_clicked event. Skipped wins over the coerced
	// completed flag so reopen-attempts on skipped tasks are distinguishable.
	const taskStatus = ( task: EnrichedTask ): TaskStatus => {
		if ( task.skipped || skippedIds.has( task.id ) ) {
			return 'skipped';
		}
		return task.completed ? 'completed' : 'to_do';
	};

	// Prefer the goal from the loaded AI output; fall back to the wizard's.
	const effectiveGoal = output?.inferred?.goal ?? goal ?? null;

	const saveErrorTitle = __( "We couldn't save your checklist.", 'jetpack-mu-wpcom' );
	const saveErrorDescription = retryFailed
		? __( "It still didn't save. Check your connection, then try again.", 'jetpack-mu-wpcom' )
		: __(
				'Your checklist is ready, but saving it failed. Check your connection, then try again.',
				'jetpack-mu-wpcom'
			);
	const saveErrorMessage =
		saveError && ! savedOnRetry ? `${ saveErrorTitle } ${ saveErrorDescription }` : null;
	// Polite: the user is waiting on this result, not interrupted by it. The description
	// changes after a failed retry, which announces it again.
	useEffect( () => {
		if ( saveErrorMessage ) {
			speak( saveErrorMessage, 'polite' );
		}
	}, [ saveErrorMessage ] );

	if ( saveError && ! savedOnRetry ) {
		const handleRetry = async () => {
			setRetrying( true );
			const ok = await saveError.retry();
			setRetrying( false );
			if ( ok ) {
				setSavedOnRetry( true );
			} else {
				setRetryFailed( true );
			}
		};

		return (
			<Layout
				progressLabel={ _x(
					'Your checklist is not saved yet',
					'Status line when the generated checklist could not be saved',
					'jetpack-mu-wpcom'
				) }
				goal={ effectiveGoal }
				siteUrl={ siteUrl }
				siteTitle={ siteTitle }
				siteEditUrl={ siteEditUrl }
			>
				<Notice.Root intent="error">
					<Notice.Title>{ saveErrorTitle }</Notice.Title>
					<Notice.Description>{ saveErrorDescription }</Notice.Description>
					<Notice.Actions>
						<Notice.ActionButton
							variant="solid"
							loading={ retrying }
							loadingAnnouncement={
								/* translators: announced to screen reader users while the checklist is being saved again. */
								__( 'Saving your checklist…', 'jetpack-mu-wpcom' )
							}
							onClick={ handleRetry }
						>
							{ __( 'Try again', 'jetpack-mu-wpcom' ) }
						</Notice.ActionButton>
					</Notice.Actions>
				</Notice.Root>
			</Layout>
		);
	}

	if ( ! tasks ) {
		return (
			<Layout
				progressLabel={ _x(
					'Tailoring your checklist…',
					'Status shown while the checklist is being generated, not an instruction',
					'jetpack-mu-wpcom'
				) }
				goal={ effectiveGoal }
				siteUrl={ siteUrl }
				siteTitle={ siteTitle }
				siteEditUrl={ siteEditUrl }
			>
				<TailoredListSkeleton />
			</Layout>
		);
	}

	const completedCount = visibleTasks.filter( task => task.completed ).length;
	const progressLabel = sprintf(
		/* translators: 1: number of completed tasks, 2: total number of tasks. */
		_n( '%1$d of %2$d completed', '%1$d of %2$d completed', completedCount, 'jetpack-mu-wpcom' ),
		completedCount,
		visibleTasks.length
	);

	const handleGetStarted = async ( task: EnrichedTask ) => {
		setBusy( { id: task.id, action: 'primary' } );
		try {
			const url = await resolveCtaUrl(
				task,
				output,
				{
					trackTaskCtaClicked,
					createFirstPostDraft,
					createAboutPage: draft => createAboutPage( draft, copy ),
					createGalleryPage: intro => createGalleryPage( intro, copy ),
					createContactPage: intro => createContactPage( intro, copy ),
					createEventsPage: intro => createEventsPage( intro, copy ),
					createVideoPage: intro => createVideoPage( intro, copy ),
					createPortfolioPiece: () => createPortfolioPiece( copy ),
				},
				siteUrl
			);
			// These tasks have no completion signal in wp-admin, so clicking the CTA
			// is the completion. Persist it before navigating (same-tab nav cancels an
			// un-awaited request); best-effort so a failed write never blocks navigation.
			if ( isCompleteOnClickTask( task.id ) ) {
				await apiFetch( {
					path: '/wpcom/v2/ai-launchpad/complete-task',
					method: 'POST',
					data: { task_id: task.id },
				} ).catch( () => {} );
			} else if ( ! task.in_progress ) {
				// Every other task is recorded as started, so the Agent chat shows it in progress too.
				await apiFetch( {
					path: '/wpcom/v2/ai-launchpad/start-task',
					method: 'POST',
					data: { task_id: task.id },
				} ).catch( () => {} );
			}
			if ( url ) {
				// Keep the button busy through the page unload; clearing it here would flash
				// the label back before the browser navigates, making the flow look stalled.
				navigate( url );
				return;
			}
		} catch {
			// Fall through to clear busy so a thrown CTA can't leave the card disabled.
		}
		setBusy( null );
	};

	// Complete-on-click tasks with no CTA destination offer "Mark as complete":
	// persist the completion and flip the card to done in place. Only flips on a
	// successful write so a failed POST doesn't show a completion that reverts on reload.
	const handleMarkComplete = async ( task: EnrichedTask ) => {
		setBusy( { id: task.id, action: 'primary' } );
		try {
			trackTaskCtaClicked( { task_id: task.id } );
			const response = await apiFetch< { list_completed: boolean } >( {
				path: '/wpcom/v2/ai-launchpad/complete-task',
				method: 'POST',
				data: { task_id: task.id },
			} );
			setTasks( prev =>
				prev ? prev.map( t => ( t.id === task.id ? { ...t, completed: true } : t ) ) : prev
			);
			// Advance the accordion to the next task, mirroring Skip — otherwise the
			// just-completed (now non-collapsible) card keeps openId and the list collapses.
			const afterComplete = ( tasks ?? [] ).map( t =>
				t.id === task.id || skippedIds.has( t.id ) ? { ...t, completed: true } : t
			);
			setOpenId( nextIncompleteId( afterComplete, task.id ) );
			setAllDone( response.list_completed );
		} catch {
			// Leave the task incomplete on failure.
		} finally {
			setBusy( null );
		}
	};

	// Skipping persists server-side (so it survives reloads and counts toward
	// completion), then marks the task complete and expands the next incomplete
	// task. Compute the next id from the post-skip list so it's never re-opened.
	const handleSkip = async ( task: EnrichedTask ) => {
		setBusy( { id: task.id, action: 'skip' } );
		trackTaskSkipped( { task_id: task.id } );
		const response = await apiFetch< { list_completed: boolean } >( {
			path: '/wpcom/v2/ai-launchpad/skip-task',
			method: 'POST',
			data: { task_id: task.id },
		} ).catch( () => null );
		setBusy( null );
		const nextSkipped = new Set( skippedIds ).add( task.id );
		setSkippedIds( nextSkipped );
		const afterSkip = ( tasks ?? [] ).map( t =>
			nextSkipped.has( t.id ) ? { ...t, completed: true } : t
		);
		setOpenId( nextIncompleteId( afterSkip, task.id ) );
		setAllDone( !! response?.list_completed );
	};

	return (
		<Layout
			heading={
				allDone
					? _x(
							"You're all set!",
							'Site Setup heading once every task is done',
							'jetpack-mu-wpcom'
						)
					: undefined
			}
			progressLabel={
				allDone
					? __( 'Your setup is complete. Taking you to your Dashboard…', 'jetpack-mu-wpcom' )
					: progressLabel
			}
			goal={ effectiveGoal }
			siteUrl={ siteUrl }
			siteTitle={ siteTitle }
			siteEditUrl={ siteEditUrl }
		>
			<Stack direction="column" gap="lg">
				<Stack direction="column" gap="sm" className="ai-launchpad-tailored-list">
					{ visibleTasks.map( task => (
						<TaskCard
							key={ task.id }
							task={ task }
							busyAction={ busy?.id === task.id ? busy.action : null }
							isLocked={ busy !== null }
							canStart={ isTaskActionable( task, output, siteUrl ) }
							canMarkComplete={
								isCompleteOnClickTask( task.id ) && ! isTaskActionable( task, output, siteUrl )
							}
							isOpen={ openId === task.id }
							onOpenChange={ open => {
								// Only a collapsed task records a click (auto-expansion goes
								// through setOpenId directly and records nothing).
								if ( open ) {
									trackTaskClicked( { task_id: task.id, task_status: taskStatus( task ) } );
								}
								setOpenId( open ? task.id : null );
							} }
							onCollapsedClick={ () =>
								trackTaskClicked( { task_id: task.id, task_status: taskStatus( task ) } )
							}
							onGetStarted={ () => handleGetStarted( task ) }
							onMarkComplete={ () => handleMarkComplete( task ) }
							onSkip={ () => handleSkip( task ) }
						/>
					) ) }
				</Stack>
				{ /* The div keeps the button as wide as its label instead of stretching with the column. */ }
				{ allDone && (
					<div>
						<ButtonLink variant="solid" href={ DASHBOARD_URL }>
							{ __( 'Go to Dashboard now', 'jetpack-mu-wpcom' ) }
						</ButtonLink>
					</div>
				) }
				{ difmOffer && ! allDone && (
					<DifmOfferBanner offer={ difmOffer } onDismiss={ () => setDifmOffer( null ) } />
				) }
			</Stack>
		</Layout>
	);
}