| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482 |
- import { Form, router } from '@inertiajs/react';
- import {
- CircleAlert,
- CircleCheck,
- Send,
- Sparkles,
- SquareDashedMousePointer,
- X,
- } from 'lucide-react';
- import { useEffect, useRef, useState } from 'react';
- import StoreGenerationController from '@/actions/App/Http/Controllers/StoreGenerationController';
- import InputError from '@/components/input-error';
- import type { PreviewSelection } from '@/components/stores/preview-picker';
- import { Button } from '@/components/ui/button';
- import { Spinner } from '@/components/ui/spinner';
- import type { Store, StoreGeneration, UsageCount } from '@/types';
-
- const fieldClass =
- 'w-full rounded-md border border-input bg-transparent px-3 py-2 text-sm shadow-xs outline-none placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50 disabled:cursor-not-allowed disabled:opacity-50';
-
- const examples = [
- 'Make the main colour dark green',
- 'Add a section with our opening hours',
- 'Create a 10% code RAYA10 until the end of the month',
- ];
-
- /**
- * "Ask the AI": a round button that stays at the bottom right of the Design tab. Clicking it opens
- * a chat panel above it. The panel does not cover the page, so the preview can be watched while
- * the AI works. It keeps the last few requests, with any changes waiting for the merchant's OK.
- */
- export default function DesignChat({
- store,
- edits,
- usage,
- busy,
- selection,
- onClearSelection,
- onStartSelecting,
- }: {
- store: Store;
- edits: StoreGeneration[];
- usage: UsageCount;
- busy: boolean;
- /** The part of the preview the merchant selected. The AI changes only that part. */
- selection: PreviewSelection | null;
- onClearSelection: () => void;
- /** Turn on "Select to edit" in the preview. */
- onStartSelecting: () => void;
- }) {
- const [open, setOpen] = useState(false);
- const field = useRef<HTMLTextAreaElement>(null);
- const history = useRef<HTMLDivElement>(null);
- const launcher = useRef<HTMLButtonElement>(null);
-
- const left = Math.max(0, usage.limit - usage.used);
- const disabled = busy || left === 0;
- const working = edits.some(
- (edit) => edit.status === 'queued' || edit.status === 'running',
- );
- const waiting = edits.some(
- (edit) =>
- edit.status === 'completed' && edit.actions_status === 'pending',
- );
- // Newest last, like a chat.
- const ordered = [...edits].reverse();
-
- // Escape closes the panel and puts the focus back on the button.
- useEffect(() => {
- if (!open) {
- return;
- }
-
- const onKey = (event: KeyboardEvent) => {
- if (event.key === 'Escape') {
- setOpen(false);
- launcher.current?.focus();
- }
- };
-
- window.addEventListener('keydown', onKey);
-
- return () => window.removeEventListener('keydown', onKey);
- }, [open]);
-
- useEffect(() => {
- if (open) {
- field.current?.focus();
- }
- }, [open]);
-
- // A new selection opens the panel, ready to type what should change there.
- useEffect(() => {
- if (selection) {
- setOpen(true);
- field.current?.focus();
- }
- }, [selection]);
-
- // Keep the newest message in view.
- useEffect(() => {
- if (open && history.current) {
- history.current.scrollTop = history.current.scrollHeight;
- }
- }, [open, edits]);
-
- function fillExample(text: string) {
- if (field.current) {
- field.current.value = text;
- field.current.focus();
- }
- }
-
- return (
- <>
- {open && (
- <section
- id="ai-chat-panel"
- role="dialog"
- aria-modal="false"
- aria-labelledby="ai-chat-title"
- className="fixed inset-x-3 bottom-20 z-40 flex max-h-[75vh] flex-col overflow-hidden rounded-2xl border bg-background shadow-2xl sm:inset-x-auto sm:right-6 sm:bottom-24 sm:max-h-[min(640px,calc(100vh-8rem))] sm:w-[400px]"
- data-test="ai-chat-panel"
- >
- <header className="flex items-start gap-3 border-b px-4 py-3">
- <Sparkles
- className="mt-0.5 size-4 shrink-0 text-emerald-600 dark:text-emerald-400"
- aria-hidden="true"
- />
- <div className="min-w-0 flex-1">
- <h3 id="ai-chat-title" className="font-medium">
- Ask the AI
- </h3>
- <p className="text-xs text-muted-foreground">
- {left} of {usage.limit} AI edits left
- </p>
- </div>
- <Button
- variant="ghost"
- size="icon"
- className="-mt-1 -mr-2 size-8"
- onClick={() => {
- setOpen(false);
- launcher.current?.focus();
- }}
- aria-label="Close Ask the AI"
- >
- <X />
- </Button>
- </header>
-
- <div
- ref={history}
- className="min-h-0 flex-1 overflow-y-auto px-4 py-3"
- >
- {ordered.length === 0 ? (
- <div className="space-y-3 text-sm">
- <p className="text-muted-foreground">
- Tell the AI what to change in plain words.
- It can change your design, and prepare
- discount codes or price changes for your OK.
- </p>
- <div className="flex flex-wrap gap-2">
- {examples.map((example) => (
- <button
- key={example}
- type="button"
- onClick={() => fillExample(example)}
- disabled={disabled}
- className="rounded-full border px-3 py-1 text-left text-xs hover:bg-muted disabled:opacity-50"
- >
- {example}
- </button>
- ))}
- </div>
- </div>
- ) : (
- <ul className="space-y-4" data-test="edit-history">
- {ordered.map((edit) => (
- <EditMessage
- key={edit.id}
- store={store}
- edit={edit}
- />
- ))}
- </ul>
- )}
- </div>
-
- <Form
- {...StoreGenerationController.edit.form(store.slug)}
- resetOnSuccess
- options={{ preserveScroll: true }}
- onSuccess={onClearSelection}
- className="space-y-2 border-t px-4 py-3"
- >
- {({ processing, errors }) => (
- <>
- {selection ? (
- <div
- className="flex items-start gap-2 rounded-lg border border-emerald-600/30 bg-emerald-50 px-2.5 py-2 text-xs text-emerald-900 dark:bg-emerald-950/40 dark:text-emerald-200"
- data-test="chat-selection"
- >
- <SquareDashedMousePointer
- className="mt-px size-3.5 shrink-0"
- aria-hidden="true"
- />
- <p className="min-w-0 flex-1 break-words">
- <span className="font-semibold">
- Editing: {selection.label}
- </span>
- {selection.detail && (
- <> · {selection.detail}</>
- )}
- <span className="block opacity-75">
- Only this part will change.
- </span>
- </p>
- <button
- type="button"
- onClick={onClearSelection}
- className="-m-1 rounded p-1 hover:bg-emerald-600/10"
- aria-label="Clear the selected part"
- >
- <X className="size-3.5" />
- </button>
- <input
- type="hidden"
- name="target_section"
- value={selection.section}
- />
- <input
- type="hidden"
- name="target_label"
- value={selection.label}
- />
- <input
- type="hidden"
- name="target_detail"
- value={selection.detail ?? ''}
- />
- </div>
- ) : (
- <button
- type="button"
- onClick={onStartSelecting}
- className="inline-flex items-center gap-1.5 text-xs font-medium text-emerald-700 hover:underline dark:text-emerald-400"
- data-test="chat-start-selecting"
- >
- <SquareDashedMousePointer
- className="size-3.5"
- aria-hidden="true"
- />
- Select a part of your store to change
- </button>
- )}
- <label
- htmlFor="instruction"
- className="sr-only"
- >
- Describe the change you want
- </label>
- <textarea
- ref={field}
- id="instruction"
- name="instruction"
- required
- rows={2}
- minLength={3}
- maxLength={500}
- disabled={disabled}
- className={fieldClass}
- placeholder={
- selection
- ? 'What should change here? e.g. Make it shorter'
- : 'e.g. Make the main colour dark green'
- }
- onKeyDown={(event) => {
- // Enter sends; Shift + Enter starts a new line.
- if (
- event.key === 'Enter' &&
- !event.shiftKey &&
- !event.nativeEvent.isComposing
- ) {
- event.preventDefault();
- event.currentTarget.form?.requestSubmit();
- }
- }}
- />
- <InputError message={errors.instruction} />
- <div className="flex items-center justify-between gap-2">
- <p className="text-xs text-muted-foreground">
- {left === 0
- ? 'You have used all the AI edits in your plan.'
- : busy
- ? 'Wait for the current change to finish.'
- : 'One change at a time works best.'}
- </p>
- <Button
- size="sm"
- disabled={disabled || processing}
- data-test="send-edit-button"
- >
- <Send />
- Send
- </Button>
- </div>
- </>
- )}
- </Form>
- </section>
- )}
-
- <button
- ref={launcher}
- type="button"
- data-ai-launcher
- aria-expanded={open}
- aria-controls="ai-chat-panel"
- onClick={() => setOpen((value) => !value)}
- className="fixed right-4 bottom-4 z-40 inline-flex items-center gap-2 rounded-full bg-emerald-700 px-4 py-3 text-sm font-medium text-white shadow-lg transition hover:bg-emerald-800 focus-visible:ring-[3px] focus-visible:ring-emerald-500/50 focus-visible:outline-none sm:right-6 sm:bottom-6 dark:bg-emerald-600 dark:hover:bg-emerald-500"
- data-test="ai-chat-button"
- >
- {open ? (
- <X className="size-4" aria-hidden="true" />
- ) : working ? (
- <Spinner />
- ) : (
- <Sparkles className="size-4" aria-hidden="true" />
- )}
- {open ? 'Close' : working ? 'AI is working…' : 'Ask the AI'}
- {!open && waiting && (
- <>
- <span
- className="absolute -top-0.5 -right-0.5 size-3 rounded-full bg-amber-400 ring-2 ring-background"
- aria-hidden="true"
- />
- <span className="sr-only">
- (a change is waiting for your OK)
- </span>
- </>
- )}
- </button>
- </>
- );
- }
-
- /** One request and the AI's answer. */
- function EditMessage({ store, edit }: { store: Store; edit: StoreGeneration }) {
- return (
- <li className="space-y-2 text-sm">
- <div className="ml-8 rounded-2xl rounded-br-sm bg-muted px-3 py-2 break-words">
- {edit.target && (
- <p className="mb-1 flex items-center gap-1 text-xs text-muted-foreground">
- <SquareDashedMousePointer
- className="size-3 shrink-0"
- aria-hidden="true"
- />
- <span className="min-w-0 truncate">
- {edit.target.label}
- {edit.target.detail && ` · ${edit.target.detail}`}
- </span>
- </p>
- )}
- <p>{edit.instruction}</p>
- </div>
- <div className="flex gap-2">
- <span className="mt-0.5 shrink-0">
- {edit.status === 'completed' ? (
- <CircleCheck className="size-4 text-green-600 dark:text-green-400" />
- ) : edit.status === 'failed' ? (
- <CircleAlert className="size-4 text-red-600 dark:text-red-400" />
- ) : (
- <Spinner />
- )}
- </span>
- <div className="min-w-0">
- <p className="break-words text-muted-foreground">
- {edit.status === 'completed'
- ? (edit.reply ?? 'Done.')
- : edit.status === 'failed'
- ? (edit.error ?? 'This change failed.')
- : 'Working on it…'}
- </p>
- {edit.status === 'completed' && edit.actions.length > 0 && (
- <ProposedActions store={store} edit={edit} />
- )}
- {edit.status === 'completed' &&
- edit.changed === false &&
- edit.actions.length === 0 && (
- <p
- className="mt-1 text-xs font-medium text-amber-700 dark:text-amber-400"
- data-test="edit-no-change"
- >
- No change was made to your design.
- </p>
- )}
- </div>
- </div>
- </li>
- );
- }
-
- /**
- * Store changes the AI prepared from the chat. Nothing happens until the merchant confirms.
- */
- function ProposedActions({
- store,
- edit,
- }: {
- store: Store;
- edit: StoreGeneration;
- }) {
- const [busy, setBusy] = useState(false);
- const pending = edit.actions_status === 'pending';
-
- function send(action: 'confirm' | 'cancel') {
- const route =
- action === 'confirm'
- ? StoreGenerationController.confirm
- : StoreGenerationController.cancel;
-
- router.post(
- route.url({ slug: store.slug, generation: edit.id }),
- {},
- {
- preserveScroll: true,
- onStart: () => setBusy(true),
- onFinish: () => setBusy(false),
- },
- );
- }
-
- return (
- <div
- className="mt-2 space-y-2 rounded-lg border bg-muted/40 p-3"
- data-test="proposed-actions"
- >
- <p className="text-xs font-medium text-muted-foreground">
- {pending
- ? 'Waiting for your OK'
- : edit.actions_status === 'confirmed'
- ? 'Done'
- : 'Cancelled, nothing was changed'}
- </p>
- <ul className="list-disc space-y-1 pl-4">
- {edit.actions.map((summary) => (
- <li
- key={summary}
- className={
- edit.actions_status === 'cancelled'
- ? 'text-muted-foreground line-through'
- : undefined
- }
- >
- {summary}
- </li>
- ))}
- </ul>
- {pending && (
- <div className="flex gap-2 pt-1">
- <Button
- size="sm"
- disabled={busy}
- onClick={() => send('confirm')}
- data-test="confirm-actions-button"
- >
- Confirm
- </Button>
- <Button
- size="sm"
- variant="outline"
- disabled={busy}
- onClick={() => send('cancel')}
- >
- Cancel
- </Button>
- </div>
- )}
- </div>
- );
- }
|