AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

design-chat.tsx 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. import { Form, router } from '@inertiajs/react';
  2. import {
  3. CircleAlert,
  4. CircleCheck,
  5. Send,
  6. Sparkles,
  7. SquareDashedMousePointer,
  8. X,
  9. } from 'lucide-react';
  10. import { useEffect, useRef, useState } from 'react';
  11. import StoreGenerationController from '@/actions/App/Http/Controllers/StoreGenerationController';
  12. import InputError from '@/components/input-error';
  13. import type { PreviewSelection } from '@/components/stores/preview-picker';
  14. import { Button } from '@/components/ui/button';
  15. import { Spinner } from '@/components/ui/spinner';
  16. import type { Store, StoreGeneration, UsageCount } from '@/types';
  17. const fieldClass =
  18. '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';
  19. const examples = [
  20. 'Make the main colour dark green',
  21. 'Add a section with our opening hours',
  22. 'Create a 10% code RAYA10 until the end of the month',
  23. ];
  24. /**
  25. * "Ask the AI": a round button that stays at the bottom right of the Design tab. Clicking it opens
  26. * a chat panel above it. The panel does not cover the page, so the preview can be watched while
  27. * the AI works. It keeps the last few requests, with any changes waiting for the merchant's OK.
  28. */
  29. export default function DesignChat({
  30. store,
  31. edits,
  32. usage,
  33. busy,
  34. selection,
  35. onClearSelection,
  36. onStartSelecting,
  37. }: {
  38. store: Store;
  39. edits: StoreGeneration[];
  40. usage: UsageCount;
  41. busy: boolean;
  42. /** The part of the preview the merchant selected. The AI changes only that part. */
  43. selection: PreviewSelection | null;
  44. onClearSelection: () => void;
  45. /** Turn on "Select to edit" in the preview. */
  46. onStartSelecting: () => void;
  47. }) {
  48. const [open, setOpen] = useState(false);
  49. const field = useRef<HTMLTextAreaElement>(null);
  50. const history = useRef<HTMLDivElement>(null);
  51. const launcher = useRef<HTMLButtonElement>(null);
  52. const left = Math.max(0, usage.limit - usage.used);
  53. const disabled = busy || left === 0;
  54. const working = edits.some(
  55. (edit) => edit.status === 'queued' || edit.status === 'running',
  56. );
  57. const waiting = edits.some(
  58. (edit) =>
  59. edit.status === 'completed' && edit.actions_status === 'pending',
  60. );
  61. // Newest last, like a chat.
  62. const ordered = [...edits].reverse();
  63. // Escape closes the panel and puts the focus back on the button.
  64. useEffect(() => {
  65. if (!open) {
  66. return;
  67. }
  68. const onKey = (event: KeyboardEvent) => {
  69. if (event.key === 'Escape') {
  70. setOpen(false);
  71. launcher.current?.focus();
  72. }
  73. };
  74. window.addEventListener('keydown', onKey);
  75. return () => window.removeEventListener('keydown', onKey);
  76. }, [open]);
  77. useEffect(() => {
  78. if (open) {
  79. field.current?.focus();
  80. }
  81. }, [open]);
  82. // A new selection opens the panel, ready to type what should change there.
  83. useEffect(() => {
  84. if (selection) {
  85. setOpen(true);
  86. field.current?.focus();
  87. }
  88. }, [selection]);
  89. // Keep the newest message in view.
  90. useEffect(() => {
  91. if (open && history.current) {
  92. history.current.scrollTop = history.current.scrollHeight;
  93. }
  94. }, [open, edits]);
  95. function fillExample(text: string) {
  96. if (field.current) {
  97. field.current.value = text;
  98. field.current.focus();
  99. }
  100. }
  101. return (
  102. <>
  103. {open && (
  104. <section
  105. id="ai-chat-panel"
  106. role="dialog"
  107. aria-modal="false"
  108. aria-labelledby="ai-chat-title"
  109. 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]"
  110. data-test="ai-chat-panel"
  111. >
  112. <header className="flex items-start gap-3 border-b px-4 py-3">
  113. <Sparkles
  114. className="mt-0.5 size-4 shrink-0 text-emerald-600 dark:text-emerald-400"
  115. aria-hidden="true"
  116. />
  117. <div className="min-w-0 flex-1">
  118. <h3 id="ai-chat-title" className="font-medium">
  119. Ask the AI
  120. </h3>
  121. <p className="text-xs text-muted-foreground">
  122. {left} of {usage.limit} AI edits left
  123. </p>
  124. </div>
  125. <Button
  126. variant="ghost"
  127. size="icon"
  128. className="-mt-1 -mr-2 size-8"
  129. onClick={() => {
  130. setOpen(false);
  131. launcher.current?.focus();
  132. }}
  133. aria-label="Close Ask the AI"
  134. >
  135. <X />
  136. </Button>
  137. </header>
  138. <div
  139. ref={history}
  140. className="min-h-0 flex-1 overflow-y-auto px-4 py-3"
  141. >
  142. {ordered.length === 0 ? (
  143. <div className="space-y-3 text-sm">
  144. <p className="text-muted-foreground">
  145. Tell the AI what to change in plain words.
  146. It can change your design, and prepare
  147. discount codes or price changes for your OK.
  148. </p>
  149. <div className="flex flex-wrap gap-2">
  150. {examples.map((example) => (
  151. <button
  152. key={example}
  153. type="button"
  154. onClick={() => fillExample(example)}
  155. disabled={disabled}
  156. className="rounded-full border px-3 py-1 text-left text-xs hover:bg-muted disabled:opacity-50"
  157. >
  158. {example}
  159. </button>
  160. ))}
  161. </div>
  162. </div>
  163. ) : (
  164. <ul className="space-y-4" data-test="edit-history">
  165. {ordered.map((edit) => (
  166. <EditMessage
  167. key={edit.id}
  168. store={store}
  169. edit={edit}
  170. />
  171. ))}
  172. </ul>
  173. )}
  174. </div>
  175. <Form
  176. {...StoreGenerationController.edit.form(store.slug)}
  177. resetOnSuccess
  178. options={{ preserveScroll: true }}
  179. onSuccess={onClearSelection}
  180. className="space-y-2 border-t px-4 py-3"
  181. >
  182. {({ processing, errors }) => (
  183. <>
  184. {selection ? (
  185. <div
  186. 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"
  187. data-test="chat-selection"
  188. >
  189. <SquareDashedMousePointer
  190. className="mt-px size-3.5 shrink-0"
  191. aria-hidden="true"
  192. />
  193. <p className="min-w-0 flex-1 break-words">
  194. <span className="font-semibold">
  195. Editing: {selection.label}
  196. </span>
  197. {selection.detail && (
  198. <> · {selection.detail}</>
  199. )}
  200. <span className="block opacity-75">
  201. Only this part will change.
  202. </span>
  203. </p>
  204. <button
  205. type="button"
  206. onClick={onClearSelection}
  207. className="-m-1 rounded p-1 hover:bg-emerald-600/10"
  208. aria-label="Clear the selected part"
  209. >
  210. <X className="size-3.5" />
  211. </button>
  212. <input
  213. type="hidden"
  214. name="target_section"
  215. value={selection.section}
  216. />
  217. <input
  218. type="hidden"
  219. name="target_label"
  220. value={selection.label}
  221. />
  222. <input
  223. type="hidden"
  224. name="target_detail"
  225. value={selection.detail ?? ''}
  226. />
  227. </div>
  228. ) : (
  229. <button
  230. type="button"
  231. onClick={onStartSelecting}
  232. className="inline-flex items-center gap-1.5 text-xs font-medium text-emerald-700 hover:underline dark:text-emerald-400"
  233. data-test="chat-start-selecting"
  234. >
  235. <SquareDashedMousePointer
  236. className="size-3.5"
  237. aria-hidden="true"
  238. />
  239. Select a part of your store to change
  240. </button>
  241. )}
  242. <label
  243. htmlFor="instruction"
  244. className="sr-only"
  245. >
  246. Describe the change you want
  247. </label>
  248. <textarea
  249. ref={field}
  250. id="instruction"
  251. name="instruction"
  252. required
  253. rows={2}
  254. minLength={3}
  255. maxLength={500}
  256. disabled={disabled}
  257. className={fieldClass}
  258. placeholder={
  259. selection
  260. ? 'What should change here? e.g. Make it shorter'
  261. : 'e.g. Make the main colour dark green'
  262. }
  263. onKeyDown={(event) => {
  264. // Enter sends; Shift + Enter starts a new line.
  265. if (
  266. event.key === 'Enter' &&
  267. !event.shiftKey &&
  268. !event.nativeEvent.isComposing
  269. ) {
  270. event.preventDefault();
  271. event.currentTarget.form?.requestSubmit();
  272. }
  273. }}
  274. />
  275. <InputError message={errors.instruction} />
  276. <div className="flex items-center justify-between gap-2">
  277. <p className="text-xs text-muted-foreground">
  278. {left === 0
  279. ? 'You have used all the AI edits in your plan.'
  280. : busy
  281. ? 'Wait for the current change to finish.'
  282. : 'One change at a time works best.'}
  283. </p>
  284. <Button
  285. size="sm"
  286. disabled={disabled || processing}
  287. data-test="send-edit-button"
  288. >
  289. <Send />
  290. Send
  291. </Button>
  292. </div>
  293. </>
  294. )}
  295. </Form>
  296. </section>
  297. )}
  298. <button
  299. ref={launcher}
  300. type="button"
  301. data-ai-launcher
  302. aria-expanded={open}
  303. aria-controls="ai-chat-panel"
  304. onClick={() => setOpen((value) => !value)}
  305. 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"
  306. data-test="ai-chat-button"
  307. >
  308. {open ? (
  309. <X className="size-4" aria-hidden="true" />
  310. ) : working ? (
  311. <Spinner />
  312. ) : (
  313. <Sparkles className="size-4" aria-hidden="true" />
  314. )}
  315. {open ? 'Close' : working ? 'AI is working…' : 'Ask the AI'}
  316. {!open && waiting && (
  317. <>
  318. <span
  319. className="absolute -top-0.5 -right-0.5 size-3 rounded-full bg-amber-400 ring-2 ring-background"
  320. aria-hidden="true"
  321. />
  322. <span className="sr-only">
  323. (a change is waiting for your OK)
  324. </span>
  325. </>
  326. )}
  327. </button>
  328. </>
  329. );
  330. }
  331. /** One request and the AI's answer. */
  332. function EditMessage({ store, edit }: { store: Store; edit: StoreGeneration }) {
  333. return (
  334. <li className="space-y-2 text-sm">
  335. <div className="ml-8 rounded-2xl rounded-br-sm bg-muted px-3 py-2 break-words">
  336. {edit.target && (
  337. <p className="mb-1 flex items-center gap-1 text-xs text-muted-foreground">
  338. <SquareDashedMousePointer
  339. className="size-3 shrink-0"
  340. aria-hidden="true"
  341. />
  342. <span className="min-w-0 truncate">
  343. {edit.target.label}
  344. {edit.target.detail && ` · ${edit.target.detail}`}
  345. </span>
  346. </p>
  347. )}
  348. <p>{edit.instruction}</p>
  349. </div>
  350. <div className="flex gap-2">
  351. <span className="mt-0.5 shrink-0">
  352. {edit.status === 'completed' ? (
  353. <CircleCheck className="size-4 text-green-600 dark:text-green-400" />
  354. ) : edit.status === 'failed' ? (
  355. <CircleAlert className="size-4 text-red-600 dark:text-red-400" />
  356. ) : (
  357. <Spinner />
  358. )}
  359. </span>
  360. <div className="min-w-0">
  361. <p className="break-words text-muted-foreground">
  362. {edit.status === 'completed'
  363. ? (edit.reply ?? 'Done.')
  364. : edit.status === 'failed'
  365. ? (edit.error ?? 'This change failed.')
  366. : 'Working on it…'}
  367. </p>
  368. {edit.status === 'completed' && edit.actions.length > 0 && (
  369. <ProposedActions store={store} edit={edit} />
  370. )}
  371. {edit.status === 'completed' &&
  372. edit.changed === false &&
  373. edit.actions.length === 0 && (
  374. <p
  375. className="mt-1 text-xs font-medium text-amber-700 dark:text-amber-400"
  376. data-test="edit-no-change"
  377. >
  378. No change was made to your design.
  379. </p>
  380. )}
  381. </div>
  382. </div>
  383. </li>
  384. );
  385. }
  386. /**
  387. * Store changes the AI prepared from the chat. Nothing happens until the merchant confirms.
  388. */
  389. function ProposedActions({
  390. store,
  391. edit,
  392. }: {
  393. store: Store;
  394. edit: StoreGeneration;
  395. }) {
  396. const [busy, setBusy] = useState(false);
  397. const pending = edit.actions_status === 'pending';
  398. function send(action: 'confirm' | 'cancel') {
  399. const route =
  400. action === 'confirm'
  401. ? StoreGenerationController.confirm
  402. : StoreGenerationController.cancel;
  403. router.post(
  404. route.url({ slug: store.slug, generation: edit.id }),
  405. {},
  406. {
  407. preserveScroll: true,
  408. onStart: () => setBusy(true),
  409. onFinish: () => setBusy(false),
  410. },
  411. );
  412. }
  413. return (
  414. <div
  415. className="mt-2 space-y-2 rounded-lg border bg-muted/40 p-3"
  416. data-test="proposed-actions"
  417. >
  418. <p className="text-xs font-medium text-muted-foreground">
  419. {pending
  420. ? 'Waiting for your OK'
  421. : edit.actions_status === 'confirmed'
  422. ? 'Done'
  423. : 'Cancelled, nothing was changed'}
  424. </p>
  425. <ul className="list-disc space-y-1 pl-4">
  426. {edit.actions.map((summary) => (
  427. <li
  428. key={summary}
  429. className={
  430. edit.actions_status === 'cancelled'
  431. ? 'text-muted-foreground line-through'
  432. : undefined
  433. }
  434. >
  435. {summary}
  436. </li>
  437. ))}
  438. </ul>
  439. {pending && (
  440. <div className="flex gap-2 pt-1">
  441. <Button
  442. size="sm"
  443. disabled={busy}
  444. onClick={() => send('confirm')}
  445. data-test="confirm-actions-button"
  446. >
  447. Confirm
  448. </Button>
  449. <Button
  450. size="sm"
  451. variant="outline"
  452. disabled={busy}
  453. onClick={() => send('cancel')}
  454. >
  455. Cancel
  456. </Button>
  457. </div>
  458. )}
  459. </div>
  460. );
  461. }