@smart-cloud/ai-kit-ui 1.5.14 → 1.5.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (54) hide show
  1. package/dist/LocaleDirectionProvider.d.ts +5 -0
  2. package/dist/index.cjs +9 -9
  3. package/dist/index.js +9 -9
  4. package/dist/locale.d.ts +13 -0
  5. package/package.json +35 -19
  6. package/eslint.config.js +0 -18
  7. package/src/ShadowBoundary.tsx +0 -229
  8. package/src/ai-chatbot/AiChatbot.tsx +0 -2325
  9. package/src/ai-chatbot/attachmentStorage.ts +0 -238
  10. package/src/ai-chatbot/index.tsx +0 -1
  11. package/src/ai-feature/AiFeature.tsx +0 -2334
  12. package/src/ai-feature/AiFeatureBorder.tsx +0 -22
  13. package/src/ai-feature/ProofreadDiff.tsx +0 -118
  14. package/src/ai-feature/index.tsx +0 -2
  15. package/src/ai-feature/utils.tsx +0 -20
  16. package/src/doc-search/DocSearch.tsx +0 -1313
  17. package/src/doc-search/index.tsx +0 -1
  18. package/src/doc-search/initialFilters.ts +0 -10
  19. package/src/errorHandling.ts +0 -305
  20. package/src/i18n/ar.ts +0 -254
  21. package/src/i18n/de.ts +0 -257
  22. package/src/i18n/en.ts +0 -269
  23. package/src/i18n/es.ts +0 -257
  24. package/src/i18n/fr.ts +0 -258
  25. package/src/i18n/he.ts +0 -250
  26. package/src/i18n/hi.ts +0 -256
  27. package/src/i18n/hu.ts +0 -269
  28. package/src/i18n/id.ts +0 -256
  29. package/src/i18n/index.ts +0 -47
  30. package/src/i18n/it.ts +0 -259
  31. package/src/i18n/ja.ts +0 -256
  32. package/src/i18n/ko.ts +0 -254
  33. package/src/i18n/nb.ts +0 -254
  34. package/src/i18n/nl.ts +0 -255
  35. package/src/i18n/pl.ts +0 -258
  36. package/src/i18n/pt.ts +0 -254
  37. package/src/i18n/ru.ts +0 -254
  38. package/src/i18n/sv.ts +0 -253
  39. package/src/i18n/th.ts +0 -252
  40. package/src/i18n/tr.ts +0 -256
  41. package/src/i18n/ua.ts +0 -257
  42. package/src/i18n/zh.ts +0 -247
  43. package/src/index.tsx +0 -7
  44. package/src/poweredBy.tsx +0 -39
  45. package/src/styles/ai-kit-ui.css +0 -1006
  46. package/src/useAiRun.ts +0 -182
  47. package/src/withAiKitShell.tsx +0 -363
  48. package/tests/ai-disclosures.test.ts +0 -126
  49. package/tests/doc-search-initial-filters.test.ts +0 -20
  50. package/tests/error-handling.test.ts +0 -140
  51. package/tsconfig.json +0 -32
  52. package/tsconfig.node.json +0 -13
  53. package/tsconfig.types.json +0 -13
  54. package/tsup.config.ts +0 -22
@@ -1,2334 +0,0 @@
1
- import {
2
- Alert,
3
- Button,
4
- Collapse,
5
- Divider,
6
- Group,
7
- Input,
8
- Loader,
9
- Modal,
10
- Paper,
11
- Select,
12
- Stack,
13
- Text,
14
- Textarea,
15
- TextInput,
16
- Tooltip,
17
- } from "@mantine/core";
18
- import {
19
- AiFeatureProps,
20
- AiKitFeatureIcon,
21
- type AiKitLanguageCode,
22
- type AiKitStatusEvent,
23
- type AiModePreference,
24
- detectLanguage,
25
- type DetectLanguageOutput,
26
- FeatureOptions,
27
- getAiKitPlugin,
28
- LANGUAGE_OPTIONS,
29
- prompt,
30
- type PromptArgs,
31
- proofread,
32
- type ProofreadArgs,
33
- rewrite,
34
- type RewriteArgs,
35
- summarize,
36
- type SummarizeArgs,
37
- translate,
38
- type TranslateArgs,
39
- waitForAiKitReady,
40
- write,
41
- type WriteArgs,
42
- } from "@smart-cloud/ai-kit-core";
43
- import { I18n } from "aws-amplify/utils";
44
- import * as CountryFlagIcons from "country-flag-icons/react/3x2";
45
- import {
46
- type ComponentProps,
47
- FC,
48
- useCallback,
49
- useEffect,
50
- useMemo,
51
- useRef,
52
- useState,
53
- } from "react";
54
- import ReactMarkdown from "react-markdown";
55
- import remarkGfm from "remark-gfm";
56
-
57
- import {
58
- IconCircleDashedCheck,
59
- IconLanguage,
60
- IconPencilCode,
61
- IconSeo,
62
- IconSum,
63
- } from "@tabler/icons-react";
64
-
65
- import { translations } from "../i18n";
66
- import { PoweredBy } from "../poweredBy";
67
- import {
68
- getAiRunErrorMessage,
69
- type AiRunErrorDetails,
70
- normalizeAiRunError,
71
- } from "../errorHandling";
72
- import {
73
- isBackendConfigured,
74
- readDefaultOutputLanguage,
75
- stripCodeFence,
76
- useAiRun,
77
- } from "../useAiRun";
78
- import { AiKitShellInjectedProps, withAiKitShell } from "../withAiKitShell";
79
- import { AiFeatureBorder } from "./AiFeatureBorder";
80
- import { ProofreadDiff } from "./ProofreadDiff";
81
- import { markdownToHtml } from "./utils";
82
-
83
- I18n.putVocabularies(translations);
84
-
85
- type GeneratedImageMetadata = {
86
- alt_text?: string;
87
- title?: string;
88
- caption?: string;
89
- description?: string;
90
- };
91
-
92
- type GeneratedPostMetadata = {
93
- title?: string;
94
- excerpt?: string;
95
- };
96
-
97
- type LanguageSelectorOption = {
98
- value: AiKitLanguageCode;
99
- label: string;
100
- countryCode: string;
101
- };
102
-
103
- type WriterTone = "neutral" | "formal" | "casual";
104
- type RewriterTone = "as-is" | "more-formal" | "more-casual";
105
- type WriterLength = "short" | "medium" | "long";
106
- type RewriterLength = "as-is" | "shorter" | "longer";
107
- type SummarizerLength = "short" | "medium" | "long";
108
- type SummarizerType = "headline" | "key-points" | "teaser" | "tldr";
109
- type ProofreadResult = {
110
- corrections: ComponentProps<typeof ProofreadDiff>["corrections"];
111
- correctedInput?: string;
112
- };
113
-
114
- const aiKit = getAiKitPlugin();
115
-
116
- const LANGUAGE_TO_COUNTRY_CODE: Record<AiKitLanguageCode, string> = {
117
- ar: "SA",
118
- en: "US",
119
- zh: "CN",
120
- nl: "NL",
121
- fr: "FR",
122
- de: "DE",
123
- he: "IL",
124
- hi: "IN",
125
- hu: "HU",
126
- id: "ID",
127
- it: "IT",
128
- ja: "JP",
129
- ko: "KR",
130
- no: "NO",
131
- pl: "PL",
132
- pt: "PT",
133
- ru: "RU",
134
- es: "ES",
135
- sv: "SE",
136
- th: "TH",
137
- tr: "TR",
138
- uk: "UA",
139
- };
140
-
141
- const RTL_LANGUAGES = new Set<AiKitLanguageCode>(["ar", "he"]);
142
-
143
- function LanguageFlag(props: { countryCode?: string; size?: number }) {
144
- const { countryCode, size = 18 } = props;
145
-
146
- if (!countryCode) {
147
- return null;
148
- }
149
-
150
- const Flag = CountryFlagIcons[
151
- countryCode as keyof typeof CountryFlagIcons
152
- ] as FC<ComponentProps<"svg">> | undefined;
153
-
154
- if (!Flag) {
155
- return null;
156
- }
157
-
158
- return (
159
- <Flag
160
- aria-hidden="true"
161
- focusable="false"
162
- style={{
163
- display: "block",
164
- flex: "none",
165
- height: size,
166
- width: Math.round(size * (4 / 3)),
167
- }}
168
- />
169
- );
170
- }
171
-
172
- function isRtlLanguage(code?: AiKitLanguageCode | "" | null): boolean {
173
- return Boolean(code && RTL_LANGUAGES.has(code as AiKitLanguageCode));
174
- }
175
-
176
- function getSupportedLanguageOptions(): LanguageSelectorOption[] {
177
- return LANGUAGE_OPTIONS.map((languageOption) => {
178
- const countryCode = LANGUAGE_TO_COUNTRY_CODE[languageOption.value];
179
-
180
- return {
181
- value: languageOption.value,
182
- label: languageOption.label,
183
- countryCode,
184
- };
185
- });
186
- }
187
-
188
- const postResponseConstraint = {
189
- type: "object",
190
- properties: {
191
- title: {
192
- type: "string",
193
- minLength: 1,
194
- maxLength: 60,
195
- },
196
- excerpt: {
197
- type: "string",
198
- minLength: 1,
199
- maxLength: 155,
200
- },
201
- },
202
- required: ["title", "excerpt"],
203
- additionalProperties: false,
204
- } as PromptArgs["responseConstraint"];
205
-
206
- const imageResponseConstraint = {
207
- type: "object",
208
- properties: {
209
- alt: {
210
- type: "string",
211
- minLength: 1,
212
- maxLength: 125,
213
- },
214
- title: {
215
- type: "string",
216
- minLength: 1,
217
- maxLength: 80,
218
- },
219
- caption: {
220
- type: "string",
221
- minLength: 1,
222
- maxLength: 150,
223
- },
224
- description: {
225
- type: "string",
226
- minLength: 1,
227
- maxLength: 300,
228
- },
229
- },
230
- required: ["alt", "title", "caption", "description"],
231
- additionalProperties: false,
232
- } as PromptArgs["responseConstraint"];
233
-
234
- function normalizeLang(
235
- code: string | null | undefined,
236
- ): AiKitLanguageCode | null {
237
- const c = (code ?? "").trim();
238
- if (!c) return null;
239
- return (c.toLowerCase().split("-")[0] as AiKitLanguageCode) || null;
240
- }
241
-
242
- async function detectTopLanguage(
243
- text: string,
244
- featureOptions: FeatureOptions,
245
- ): Promise<AiKitLanguageCode> {
246
- const res: DetectLanguageOutput = await detectLanguage(
247
- { text },
248
- featureOptions,
249
- );
250
- const top =
251
- normalizeLang(res.result?.candidates?.[0]?.detectedLanguage) ?? "en";
252
- return top;
253
- }
254
-
255
- async function parseImageMetadataFromPromptResult(
256
- text: string,
257
- outputLang: AiKitLanguageCode | "",
258
- featureOptions: FeatureOptions,
259
- ): Promise<GeneratedImageMetadata> {
260
- const cleaned = stripCodeFence(text || "").trim();
261
- if (!cleaned) return {};
262
-
263
- try {
264
- const parsed = JSON.parse(cleaned) as {
265
- alt?: string;
266
- title?: string;
267
- caption?: string;
268
- description?: string;
269
- };
270
- return {
271
- alt_text:
272
- typeof parsed.alt === "string"
273
- ? outputLang && outputLang !== "en"
274
- ? (
275
- await translate(
276
- {
277
- text: parsed.alt,
278
- sourceLanguage: "en",
279
- targetLanguage: outputLang,
280
- },
281
- featureOptions,
282
- )
283
- ).result
284
- : parsed.alt
285
- : "",
286
- title:
287
- typeof parsed.title === "string"
288
- ? outputLang && outputLang !== "en"
289
- ? (
290
- await translate(
291
- {
292
- text: parsed.title,
293
- sourceLanguage: "en",
294
- targetLanguage: outputLang,
295
- },
296
- featureOptions,
297
- )
298
- ).result
299
- : parsed.title
300
- : "",
301
- caption:
302
- typeof parsed.caption === "string"
303
- ? outputLang && outputLang !== "en"
304
- ? (
305
- await translate(
306
- {
307
- text: parsed.caption,
308
- sourceLanguage: "en",
309
- targetLanguage: outputLang,
310
- },
311
- featureOptions,
312
- )
313
- ).result
314
- : parsed.caption
315
- : "",
316
- description:
317
- typeof parsed.description === "string"
318
- ? outputLang && outputLang !== "en"
319
- ? (
320
- await translate(
321
- {
322
- text: parsed.description,
323
- sourceLanguage: "en",
324
- targetLanguage: outputLang,
325
- },
326
- featureOptions,
327
- )
328
- ).result
329
- : parsed.description
330
- : "",
331
- };
332
- } catch {
333
- return {};
334
- }
335
- }
336
-
337
- async function parsePostMetadataFromPromptResult(
338
- text: string,
339
- outputLang: AiKitLanguageCode | "",
340
- featureOptions: FeatureOptions,
341
- ): Promise<GeneratedPostMetadata> {
342
- const cleaned = stripCodeFence(text || "").trim();
343
- if (!cleaned) return {};
344
-
345
- try {
346
- const parsed = JSON.parse(cleaned) as {
347
- title?: string;
348
- excerpt?: string;
349
- };
350
- return {
351
- title:
352
- typeof parsed.title === "string"
353
- ? outputLang && outputLang !== "en"
354
- ? (
355
- await translate(
356
- {
357
- text: parsed.title,
358
- sourceLanguage: "en",
359
- targetLanguage: outputLang,
360
- },
361
- featureOptions,
362
- )
363
- ).result
364
- : parsed.title
365
- : "",
366
- excerpt:
367
- typeof parsed.excerpt === "string"
368
- ? outputLang && outputLang !== "en"
369
- ? (
370
- await translate(
371
- {
372
- text: parsed.excerpt,
373
- sourceLanguage: "en",
374
- targetLanguage: outputLang,
375
- },
376
- featureOptions,
377
- )
378
- ).result
379
- : parsed.excerpt
380
- : "",
381
- };
382
- } catch {
383
- return {};
384
- }
385
- }
386
-
387
- /**
388
- * Wrapper around WP with:
389
- * - higher z-index (Media Library grid view can be aggressive)
390
- * - standard status + error area
391
- * - optional Cancel action
392
- */
393
- const AiFeatureBase: FC<AiFeatureProps & AiKitShellInjectedProps> = (props) => {
394
- const {
395
- allowOverride: allowOverrideDefaults,
396
- autoRun = true,
397
- editable = true,
398
- onDeviceTimeout,
399
- variation = "default",
400
- title,
401
- showOpenButton = false,
402
- showOpenButtonTitle = true,
403
- showOpenButtonIcon = true,
404
- openButtonTitle,
405
- openButtonIcon,
406
- showRegenerateOnBackendButton = true,
407
- acceptButtonTitle = "Accept",
408
- optionsDisplay = "collapse",
409
- mode,
410
- context,
411
- modeOverride,
412
- colorMode,
413
- default: defaults,
414
- onClose,
415
- onAccept,
416
- onOptionsChanged,
417
- language,
418
- direction,
419
- rootElement,
420
- modalRootElement,
421
- } = props;
422
-
423
- const [languageOverride, setLanguageOverride] = useState<
424
- AiKitLanguageCode | undefined
425
- >();
426
- const [directionOverride, setDirectionOverride] = useState<
427
- "ltr" | "rtl" | "auto" | undefined
428
- >();
429
-
430
- const effectiveUiLanguage = languageOverride ?? normalizeLang(language);
431
- I18n.setLanguage(effectiveUiLanguage || "en");
432
- const currentUiLanguage = effectiveUiLanguage || "en";
433
- const effectiveDirection = useMemo(() => {
434
- const activeDirection = languageOverride ? directionOverride : direction;
435
-
436
- if (!activeDirection || activeDirection === "auto") {
437
- return isRtlLanguage(effectiveUiLanguage) ? "rtl" : "ltr";
438
- }
439
-
440
- return activeDirection;
441
- }, [direction, directionOverride, effectiveUiLanguage, languageOverride]);
442
-
443
- const allowOverride = {
444
- text: allowOverrideDefaults?.text ?? true,
445
- instructions: allowOverrideDefaults?.instructions ?? true,
446
- tone: allowOverrideDefaults?.tone ?? true,
447
- length: allowOverrideDefaults?.length ?? true,
448
- type: allowOverrideDefaults?.type ?? true,
449
- outputLanguage: allowOverrideDefaults?.outputLanguage ?? true,
450
- outputFormat: allowOverrideDefaults?.outputFormat ?? true,
451
- };
452
-
453
- const allowOverrideParameters = useMemo(() => {
454
- return Boolean(
455
- (mode === "write" && allowOverride?.text) ||
456
- ((mode === "write" ||
457
- mode === "rewrite" ||
458
- mode === "generateImageMetadata" ||
459
- mode === "generatePostMetadata") &&
460
- allowOverride?.instructions) ||
461
- ((mode === "write" || mode === "rewrite") && allowOverride?.tone) ||
462
- ((mode === "write" || mode === "rewrite" || mode === "summarize") &&
463
- allowOverride?.length) ||
464
- (mode === "summarize" && allowOverride?.type) ||
465
- allowOverride?.outputLanguage,
466
- );
467
- }, [allowOverride, mode]);
468
-
469
- const [state, setState] = useState<string>();
470
- const [featureOpen, setFeatureOpen] = useState<boolean>(!showOpenButton);
471
- const [optionsOpen, setOptionsOpen] = useState<boolean>(false);
472
- const [backendConfigured, setBackendConfigured] = useState(false);
473
- const [error, setError] = useState<string | null>(null);
474
- const [errorDetails, setErrorDetails] =
475
- useState<AiRunErrorDetails | null>(null);
476
- const [generated, setGenerated] = useState<never | null>(null);
477
- const [text, setText] = useState<string | undefined>(defaults?.text);
478
- const [image] = useState<Blob | undefined>(defaults?.image);
479
- const [instructions, setInstructions] = useState<string | undefined>(
480
- defaults?.instructions,
481
- );
482
- const [detectedLanguage, setDetectedLanguage] = useState<AiKitLanguageCode>();
483
- const [inputLanguage, setInputLanguage] = useState<
484
- AiKitLanguageCode | "auto" | undefined
485
- >(defaults?.inputLanguage);
486
- const [outputFormat, setOutputFormat] = useState<
487
- "plain-text" | "markdown" | "html" | undefined
488
- >(defaults?.outputFormat);
489
- const [outputLanguage, setOutputLanguage] = useState<
490
- AiKitLanguageCode | "auto" | undefined
491
- >(
492
- defaults?.outputLanguage ||
493
- aiKit.settings.defaultOutputLanguage ||
494
- (mode === "rewrite" ? "auto" : undefined),
495
- );
496
- const [length, setLength] = useState<
497
- WriterLength | RewriterLength | SummarizerLength | undefined
498
- >(defaults?.length);
499
- const [tone, setTone] = useState<WriterTone | RewriterTone | undefined>(
500
- defaults?.tone,
501
- );
502
- const [type, setType] = useState<SummarizerType | undefined>(defaults?.type);
503
- const [generatedContentLanguage, setGeneratedContentLanguage] = useState<
504
- AiKitLanguageCode | ""
505
- >("");
506
-
507
- const autoRunOnceRef = useRef(false);
508
- const supportedLanguageOptions = useMemo(
509
- () => getSupportedLanguageOptions(),
510
- [],
511
- );
512
-
513
- const defaultTitle = useMemo(() => {
514
- if (title) {
515
- return title;
516
- }
517
- let t;
518
- switch (mode) {
519
- default:
520
- case "summarize":
521
- t = "Summarize";
522
- break;
523
- case "proofread":
524
- t = "Proofread";
525
- break;
526
- case "write":
527
- t = "Write";
528
- break;
529
- case "rewrite":
530
- t = "Rewrite";
531
- break;
532
- case "translate":
533
- t = "Translate";
534
- break;
535
- case "generatePostMetadata":
536
- t = "Generate Post Metadata";
537
- break;
538
- case "generateImageMetadata":
539
- t = "Generate Image Metadata";
540
- break;
541
- }
542
- return t;
543
- }, [title, mode, effectiveUiLanguage]);
544
-
545
- const formatAiKitStatus = useCallback(
546
- (e: AiKitStatusEvent | null): string | null => {
547
- if (!e || e.silent) return null;
548
-
549
- const step = e.step;
550
- const msg = I18n.get((e.message ?? "").trim());
551
- const p = typeof e.progress === "number" ? e.progress : null;
552
- const pct = p == null ? null : Math.round(p * 100);
553
-
554
- switch (step) {
555
- case "decide":
556
- return msg || I18n.get("Checking capabilities...");
557
- case "on-device:init":
558
- return msg || I18n.get("Initializing on-device AI...");
559
- case "on-device:download":
560
- return (
561
- msg ||
562
- (pct == null
563
- ? I18n.get("Downloading model...")
564
- : I18n.get("Downloading model...") + " " + pct + "%")
565
- );
566
- case "on-device:ready":
567
- return msg || I18n.get("On-device model ready.");
568
- case "on-device:run":
569
- return msg || I18n.get("Generating...");
570
- case "backend:request":
571
- case "backend:waiting":
572
- case "backend:response":
573
- switch (mode) {
574
- case "translate":
575
- return I18n.get("Translating text");
576
- case "rewrite":
577
- return I18n.get("Rewriting text");
578
- case "summarize":
579
- return I18n.get("Summarizing");
580
- case "proofread":
581
- return I18n.get("Proofreading");
582
- case "write":
583
- case "generatePostMetadata":
584
- case "generateImageMetadata":
585
- default:
586
- return I18n.get("Generating text");
587
- }
588
- case "done":
589
- return msg || I18n.get("Done.");
590
- case "error":
591
- return msg || I18n.get("Something went wrong.");
592
- default:
593
- return msg || I18n.get("Working...");
594
- }
595
- },
596
- [effectiveUiLanguage, mode],
597
- );
598
-
599
- const inputText = useMemo(() => {
600
- return text ?? defaults?.getText;
601
- }, [text, defaults]);
602
-
603
- const canGenerate = useMemo(() => {
604
- // If inputText is a function (async or sync getText), we can't determine
605
- // if it has content without calling it. Assume it's valid if provided.
606
- const input = inputText;
607
- if (typeof input === "function") {
608
- switch (mode) {
609
- case "generateImageMetadata":
610
- return Boolean(image);
611
- case "translate":
612
- // For translate, we need outputLanguage check, but can't check text without calling getText
613
- return Boolean(
614
- !outputLanguage || detectedLanguage !== outputLanguage,
615
- );
616
- case "summarize":
617
- case "proofread":
618
- case "rewrite":
619
- case "write":
620
- case "generatePostMetadata":
621
- return true; // Assume getText will provide valid content
622
- default:
623
- return false;
624
- }
625
- }
626
-
627
- // If inputText is a string, check it directly
628
- const text = input as string | undefined;
629
- switch (mode) {
630
- case "generateImageMetadata":
631
- return Boolean(image);
632
- case "translate":
633
- return (
634
- Boolean(text && text.trim().length > 0) &&
635
- (!outputLanguage || detectedLanguage !== outputLanguage)
636
- );
637
- case "summarize":
638
- case "proofread":
639
- case "rewrite":
640
- case "write":
641
- case "generatePostMetadata":
642
- return Boolean(text && text.trim().length > 0);
643
- default:
644
- return false;
645
- }
646
- }, [inputText, mode, image, detectedLanguage, outputLanguage, featureOpen]);
647
-
648
- const ai = useAiRun();
649
- const statusText =
650
- formatAiKitStatus(ai.statusEvent) ?? (state ? I18n.get(state) : null);
651
-
652
- const setGeneratedResultLanguage = useCallback(
653
- (nextLanguage?: AiKitLanguageCode | "auto" | "" | null) => {
654
- if (nextLanguage && nextLanguage !== "auto") {
655
- setGeneratedContentLanguage(nextLanguage);
656
- return;
657
- }
658
-
659
- setGeneratedContentLanguage(readDefaultOutputLanguage() || "");
660
- },
661
- [],
662
- );
663
-
664
- const runGenerate = useCallback(
665
- async (modeOverride?: AiModePreference) => {
666
- if (!canGenerate) {
667
- return;
668
- }
669
- if (allowOverrideParameters && mode !== "proofread" && canGenerate) {
670
- setOptionsOpen(false);
671
- }
672
- setError(null);
673
- setErrorDetails(null);
674
- setGenerated(null);
675
-
676
- const input = await inputText;
677
- try {
678
- // Support both sync and async getText functions
679
- const text =
680
- typeof input === "function" ? await Promise.resolve(input()) : input;
681
- switch (mode) {
682
- case "summarize": {
683
- const outLang =
684
- (outputLanguage && outputLanguage !== "auto"
685
- ? outputLanguage
686
- : null) || readDefaultOutputLanguage();
687
- const res = await ai.run(async ({ signal, onStatus }) => {
688
- const args: SummarizeArgs = {
689
- text: text!.trim(),
690
- format:
691
- outputFormat === "plain-text" ? "plain-text" : "markdown",
692
- length: length as SummarizerLength,
693
- type: type as SummarizerType,
694
- outputLanguage: outLang as SummarizeArgs["outputLanguage"],
695
- };
696
-
697
- const featureOptions: FeatureOptions = {
698
- signal,
699
- onStatus,
700
- context,
701
- modeOverride,
702
- onDeviceTimeoutOverride: onDeviceTimeout,
703
- };
704
-
705
- // Normal single-pass summarization
706
- const out = await summarize(args, featureOptions);
707
- return out.result;
708
- });
709
- setGeneratedResultLanguage(outLang || "");
710
- setGenerated((res as never) ?? "");
711
- break;
712
- }
713
- case "proofread": {
714
- const res = await ai.run(async ({ signal, onStatus }) => {
715
- const expectedInputLanguages: AiKitLanguageCode[] = [];
716
- try {
717
- setState("Detecting input language...");
718
- const res = await detectLanguage(
719
- { text: text!.trim() },
720
- {
721
- signal,
722
- context,
723
- modeOverride,
724
- onDeviceTimeoutOverride: onDeviceTimeout,
725
- silent: true,
726
- },
727
- );
728
- const langCodes = res.result?.candidates
729
- ?.filter((c) => c.confidence && c.confidence > 0.1)
730
- .map((c) => c.detectedLanguage as AiKitLanguageCode);
731
- expectedInputLanguages.push(...langCodes);
732
- } catch {
733
- expectedInputLanguages.push("en");
734
- }
735
- const args: ProofreadArgs = {
736
- text: text!.trim(),
737
- expectedInputLanguages,
738
- };
739
- const out = await proofread(args, {
740
- signal,
741
- onStatus,
742
- context,
743
- modeOverride,
744
- onDeviceTimeoutOverride: onDeviceTimeout,
745
- });
746
- return out.result;
747
- });
748
- setGenerated((res as never) ?? "");
749
- break;
750
- }
751
- case "translate": {
752
- const outLang =
753
- (outputLanguage && outputLanguage !== "auto"
754
- ? outputLanguage
755
- : null) || readDefaultOutputLanguage();
756
- const res = await ai.run(async ({ signal, onStatus }) => {
757
- let inputLang = inputLanguage ?? "auto";
758
- if (inputLang === "auto") {
759
- setState("Detecting input language...");
760
- inputLang = await detectTopLanguage(text!.trim(), {
761
- signal,
762
- context,
763
- modeOverride,
764
- onDeviceTimeoutOverride: onDeviceTimeout,
765
- silent: true,
766
- });
767
- setDetectedLanguage(inputLang);
768
- } else {
769
- setDetectedLanguage(inputLang);
770
- }
771
- if (outLang === inputLang) {
772
- setError(
773
- I18n.get("Input and output languages cannot be the same."),
774
- );
775
- throw new Error(
776
- I18n.get("Input and output languages cannot be the same."),
777
- );
778
- }
779
- const args: TranslateArgs = {
780
- text: text!.trim(),
781
- sourceLanguage: inputLang!,
782
- targetLanguage: outLang,
783
- };
784
-
785
- const featureOptions: FeatureOptions = {
786
- signal,
787
- onStatus,
788
- context,
789
- modeOverride,
790
- onDeviceTimeoutOverride: onDeviceTimeout,
791
- };
792
-
793
- // Normal single-pass translation
794
- const out = await translate(args, featureOptions);
795
- return out.result;
796
- });
797
- setGeneratedResultLanguage(outLang || "");
798
- setGenerated((res as never) ?? "");
799
- break;
800
- }
801
- case "rewrite": {
802
- let generatedLanguage: AiKitLanguageCode | "" = "";
803
- const res = await ai.run(async ({ signal, onStatus }) => {
804
- let outLang =
805
- (outputLanguage && outputLanguage !== "auto"
806
- ? outputLanguage
807
- : null) || readDefaultOutputLanguage();
808
- if (outputLanguage === "auto") {
809
- setState("Detecting input language...");
810
- outLang = await detectTopLanguage(text!.trim(), {
811
- signal,
812
- context,
813
- modeOverride,
814
- onDeviceTimeoutOverride: onDeviceTimeout,
815
- silent: true,
816
- });
817
- setOutputLanguage(outLang);
818
- }
819
- generatedLanguage = outLang || "";
820
- const args: RewriteArgs = {
821
- text: text!.trim(),
822
- context: instructions?.trim() || undefined,
823
- format:
824
- outputFormat === "plain-text" ? "plain-text" : "markdown",
825
- tone: tone as RewriterTone,
826
- length: length as RewriterLength,
827
- outputLanguage: outLang as RewriteArgs["outputLanguage"],
828
- };
829
-
830
- const featureOptions: FeatureOptions = {
831
- signal,
832
- onStatus,
833
- context,
834
- modeOverride,
835
- onDeviceTimeoutOverride: onDeviceTimeout,
836
- };
837
-
838
- // Normal single-pass rewrite
839
- const out = await rewrite(args, featureOptions);
840
- return out.result;
841
- });
842
- setGeneratedResultLanguage(generatedLanguage);
843
- setGenerated((res as never) ?? "");
844
- break;
845
- }
846
- case "write": {
847
- const outLang =
848
- (outputLanguage && outputLanguage !== "auto"
849
- ? outputLanguage
850
- : null) || readDefaultOutputLanguage();
851
- const args: WriteArgs = {
852
- prompt: text!.trim(),
853
- context: instructions?.trim() || undefined,
854
- format: outputFormat === "plain-text" ? "plain-text" : "markdown",
855
- tone: tone as WriterTone,
856
- length: length as WriterLength,
857
- outputLanguage: outLang as WriteArgs["outputLanguage"],
858
- };
859
- const res = await ai.run(async ({ signal, onStatus }) => {
860
- const langFeatureOptions: FeatureOptions = {
861
- signal,
862
- context,
863
- modeOverride,
864
- onDeviceTimeoutOverride: onDeviceTimeout,
865
- silent: true,
866
- };
867
- setState("Detecting input language...");
868
- const inLang = await detectTopLanguage(
869
- text!.trim() + "\n" + (instructions?.trim() || ""),
870
- langFeatureOptions,
871
- );
872
- if (inLang !== outLang && inLang !== "en") {
873
- setState("Translating instructions...");
874
- args.prompt = (
875
- await translate(
876
- {
877
- text: args.prompt,
878
- sourceLanguage: inLang,
879
- targetLanguage: "en",
880
- },
881
- langFeatureOptions,
882
- )
883
- ).result;
884
- if (instructions) {
885
- args.context = (
886
- await translate(
887
- {
888
- text: instructions,
889
- sourceLanguage: inLang,
890
- targetLanguage: "en",
891
- },
892
- langFeatureOptions,
893
- )
894
- ).result;
895
- }
896
- }
897
- const out = await write(args, {
898
- signal,
899
- onStatus,
900
- context,
901
- modeOverride,
902
- onDeviceTimeoutOverride: onDeviceTimeout,
903
- });
904
- return out.result;
905
- });
906
- setGeneratedResultLanguage(outLang || "");
907
- setGenerated((res as never) ?? "");
908
- break;
909
- }
910
- case "generatePostMetadata": {
911
- const messages = [
912
- {
913
- role: "system" as const,
914
- content:
915
- `You generate SEO metadata for a WordPress post.
916
- Return ONLY a minified JSON object with keys: title, excerpt.
917
- Constraints: title <= 60 chars, excerpt <= 155 chars.
918
- Be accurate: do not invent facts; if unsure, use neutral wording.
919
- Do not add extra keys, no markdown, no explanations.
920
- Follow the response constraint strictly.
921
- ` +
922
- (instructions
923
- ? `
924
- Follow these additional instructions: ${instructions}`
925
- : ""),
926
- },
927
- {
928
- role: "user" as const,
929
- content: `Post content:\n${text!.trim()}`,
930
- },
931
- ];
932
- const res = (await ai.run(async ({ signal, onStatus }) => {
933
- const out = await prompt(
934
- {
935
- messages,
936
- outputLanguage: "en",
937
- responseConstraint: postResponseConstraint,
938
- },
939
- {
940
- signal,
941
- onStatus,
942
- context,
943
- modeOverride,
944
- onDeviceTimeoutOverride: onDeviceTimeout,
945
- },
946
- );
947
- return out.result;
948
- })) as string | null;
949
- if (!res) {
950
- setGenerated("" as never);
951
- return;
952
- }
953
- const cleaned = stripCodeFence(res).trim();
954
- const outLang =
955
- (outputLanguage && outputLanguage !== "auto"
956
- ? outputLanguage
957
- : null) || readDefaultOutputLanguage();
958
- try {
959
- setState("Translating result...");
960
- const parsed = (await ai.run(async ({ signal }) => {
961
- return await parsePostMetadataFromPromptResult(
962
- cleaned,
963
- outLang,
964
- {
965
- signal,
966
- context,
967
- modeOverride,
968
- onDeviceTimeoutOverride: onDeviceTimeout,
969
- silent: true,
970
- },
971
- );
972
- })) as string | null;
973
- setGenerated(parsed as never);
974
- } catch {
975
- // If parsing fails, keep raw in the modal. User can still copy/paste.
976
- setGenerated(cleaned as never);
977
- }
978
-
979
- break;
980
- }
981
- case "generateImageMetadata": {
982
- {
983
- const messages = [
984
- {
985
- role: "system",
986
- content:
987
- `You write WordPress media metadata for accessibility and SEO.
988
- Return ONLY a minified JSON object with keys: alt, title, caption, description.
989
- No extra keys. No markdown. No explanations.
990
- Follow the response constraint strictly.
991
-
992
- Guidelines:
993
- - Accurate, concise, non-promotional. No keyword stuffing.
994
- - Prefer plain language; avoid clichés.
995
- - Do not invent facts (names, locations, brands, numbers). If unsure, stay generic.
996
- - alt: describe what’s essential for understanding the image in context; avoid starting with "Image of" / "Photo of".
997
- - title: short, descriptive label.
998
- - caption: optional context users might see below the image; keep short.
999
- - description: 1–2 short sentences; can include context/usage if known.
1000
- ` +
1001
- (instructions
1002
- ? `
1003
- Follow these additional instructions: ${instructions}`
1004
- : ""),
1005
- },
1006
- {
1007
- role: "user",
1008
- content:
1009
- "What can you see on this image according to the optional knowledge base and shared context?",
1010
- },
1011
- ].filter(Boolean) as Array<{
1012
- role: "system" | "user" | "assistant";
1013
- content: string;
1014
- }>;
1015
- const res = (await ai.run(async ({ signal, onStatus }) => {
1016
- const out = await prompt(
1017
- {
1018
- messages,
1019
- images: [image!],
1020
- outputLanguage: "en",
1021
- responseConstraint: imageResponseConstraint,
1022
- },
1023
- {
1024
- signal,
1025
- onStatus,
1026
- context,
1027
- modeOverride,
1028
- onDeviceTimeoutOverride: onDeviceTimeout,
1029
- },
1030
- );
1031
- return out.result;
1032
- })) as string | null;
1033
- if (!res) {
1034
- setGenerated("" as never);
1035
- return;
1036
- }
1037
- const outLang =
1038
- (outputLanguage && outputLanguage !== "auto"
1039
- ? outputLanguage
1040
- : null) || readDefaultOutputLanguage();
1041
-
1042
- const cleaned = stripCodeFence(res).trim();
1043
- try {
1044
- setState("Translating result...");
1045
- const parsed = (await ai.run(async ({ signal }) => {
1046
- return await parseImageMetadataFromPromptResult(
1047
- cleaned,
1048
- outLang,
1049
- {
1050
- signal,
1051
- context,
1052
- modeOverride,
1053
- onDeviceTimeoutOverride: onDeviceTimeout,
1054
- silent: true,
1055
- },
1056
- );
1057
- })) as string | null;
1058
- setGenerated(parsed as never);
1059
- } catch {
1060
- // If parsing fails, keep raw in the modal. User can still copy/paste.
1061
- setGenerated(cleaned as never);
1062
- }
1063
- break;
1064
- }
1065
- }
1066
- }
1067
- } catch (e) {
1068
- const details = normalizeAiRunError(e);
1069
- if (details.kind !== "cancelled") {
1070
- setErrorDetails(details);
1071
- setError(
1072
- getAiRunErrorMessage(details, (message) => I18n.get(message)),
1073
- );
1074
- }
1075
- }
1076
- setState(undefined);
1077
- },
1078
- [
1079
- language,
1080
- ai,
1081
- instructions,
1082
- length,
1083
- outputLanguage,
1084
- text,
1085
- tone,
1086
- context,
1087
- mode,
1088
- type,
1089
- inputLanguage,
1090
- canGenerate,
1091
- allowOverrideParameters,
1092
- ],
1093
- );
1094
-
1095
- const runGenerateOnBackend = useCallback(async () => {
1096
- await runGenerate("backend-only");
1097
- }, [runGenerate]);
1098
-
1099
- const getOpenButtonDefaultIcon = useCallback(
1100
- (className?: string) => {
1101
- switch (mode) {
1102
- case "proofread":
1103
- return <IconCircleDashedCheck className={className} />;
1104
- case "translate":
1105
- return <IconLanguage className={className} />;
1106
- case "summarize":
1107
- return <IconSum className={className} />;
1108
- case "rewrite":
1109
- case "write":
1110
- return <IconPencilCode className={className} />;
1111
- case "generateImageMetadata":
1112
- case "generatePostMetadata":
1113
- return <IconSeo className={className} />;
1114
- default:
1115
- return <AiKitFeatureIcon mode={mode} className={className} />;
1116
- }
1117
- },
1118
- [mode],
1119
- );
1120
-
1121
- const getGenerateTitle = useCallback(() => {
1122
- switch (mode) {
1123
- case "proofread":
1124
- return ai.lastSource
1125
- ? I18n.get("Proofread again")
1126
- : I18n.get("Proofread");
1127
- case "translate":
1128
- return ai.lastSource
1129
- ? I18n.get("Translate again")
1130
- : I18n.get("Translate");
1131
- case "rewrite":
1132
- return ai.lastSource ? I18n.get("Rewrite again") : I18n.get("Rewrite");
1133
- case "summarize":
1134
- return ai.lastSource
1135
- ? I18n.get("Summarize again")
1136
- : I18n.get("Summarize");
1137
- default:
1138
- return ai.lastSource ? I18n.get("Regenerate") : I18n.get("Generate");
1139
- }
1140
- }, [effectiveUiLanguage, ai.lastSource, mode]);
1141
-
1142
- const getRegenerateOnBackendTitle = useCallback(() => {
1143
- switch (mode) {
1144
- case "proofread":
1145
- return I18n.get("Proofread on Backend");
1146
- case "translate":
1147
- return I18n.get("Translate on Backend");
1148
- case "rewrite":
1149
- return I18n.get("Rewrite on Backend");
1150
- case "summarize":
1151
- return I18n.get("Summarize on Backend");
1152
- default:
1153
- return I18n.get("Regenerate on Backend");
1154
- }
1155
- }, [effectiveUiLanguage, mode]);
1156
-
1157
- const close = useCallback(async () => {
1158
- setFeatureOpen(false);
1159
- setGenerated(null);
1160
- setError(null);
1161
- setErrorDetails(null);
1162
- autoRunOnceRef.current = false;
1163
- ai.reset();
1164
- if (!showOpenButton) {
1165
- onClose();
1166
- }
1167
- }, [onClose, autoRunOnceRef, ai, showOpenButton]);
1168
-
1169
- const cancel = useCallback(async () => {
1170
- if (ai.busy) {
1171
- ai.cancel();
1172
- }
1173
- }, [ai.busy]);
1174
-
1175
- useEffect(() => {
1176
- if (
1177
- !featureOpen ||
1178
- !autoRun ||
1179
- !canGenerate ||
1180
- ai.busy ||
1181
- generated ||
1182
- autoRunOnceRef.current
1183
- ) {
1184
- return;
1185
- }
1186
- autoRunOnceRef.current = true;
1187
- queueMicrotask(() => {
1188
- void runGenerate(modeOverride);
1189
- });
1190
- }, [
1191
- ai.busy,
1192
- autoRunOnceRef,
1193
- featureOpen,
1194
- canGenerate,
1195
- autoRun,
1196
- generated,
1197
- runGenerate,
1198
- modeOverride,
1199
- ]);
1200
-
1201
- useEffect(() => {
1202
- if (!allowOverrideParameters) return;
1203
- if (mode === "proofread") return;
1204
- if (!canGenerate) {
1205
- setOptionsOpen(true);
1206
- autoRunOnceRef.current = true;
1207
- }
1208
- }, [allowOverrideParameters, canGenerate, mode]);
1209
-
1210
- useEffect(() => {
1211
- let alive = true;
1212
- (async () => {
1213
- try {
1214
- await waitForAiKitReady();
1215
- const v = await isBackendConfigured();
1216
- if (alive) setBackendConfigured(v);
1217
- } catch {
1218
- if (alive) setBackendConfigured(false);
1219
- }
1220
- })();
1221
- return () => {
1222
- alive = false;
1223
- };
1224
- }, []);
1225
-
1226
- useEffect(() => {
1227
- if (!languageOverride) {
1228
- return;
1229
- }
1230
-
1231
- setDirectionOverride("auto");
1232
- setOutputLanguage(languageOverride);
1233
- setDetectedLanguage(undefined);
1234
- }, [languageOverride]);
1235
-
1236
- const optionsSummary = useMemo(() => {
1237
- const parts: string[] = [];
1238
-
1239
- if (mode === "translate") {
1240
- const lang = LANGUAGE_OPTIONS.find(
1241
- (lo) => lo.value === inputLanguage,
1242
- )?.label;
1243
- parts.push(
1244
- I18n.get("Input language") + ": " + (lang ? I18n.get(lang) : "auto"),
1245
- );
1246
- }
1247
- if (outputLanguage && allowOverride?.outputLanguage) {
1248
- const lang = LANGUAGE_OPTIONS.find(
1249
- (lo) => lo.value === outputLanguage,
1250
- )?.label;
1251
- parts.push(
1252
- I18n.get("Output language") +
1253
- ": " +
1254
- (lang ? I18n.get(lang) : outputLanguage),
1255
- );
1256
- }
1257
- if (mode === "summarize" && type && allowOverride?.type) {
1258
- parts.push(I18n.get("Type") + ": " + I18n.get(type));
1259
- }
1260
- if (
1261
- (mode === "write" || mode === "rewrite") &&
1262
- tone &&
1263
- allowOverride?.tone
1264
- ) {
1265
- parts.push(I18n.get("Tone") + ": " + I18n.get(tone));
1266
- }
1267
- if (
1268
- (mode === "write" || mode === "rewrite" || mode === "summarize") &&
1269
- length &&
1270
- allowOverride?.length
1271
- ) {
1272
- parts.push(I18n.get("Length") + ": " + I18n.get(length));
1273
- }
1274
- if (instructions?.trim() && allowOverride?.instructions) {
1275
- parts.push(I18n.get("Instructions") + ": ✓");
1276
- }
1277
-
1278
- return parts.length ? parts.join(" • ") : I18n.get("No overrides");
1279
- }, [
1280
- effectiveUiLanguage,
1281
- mode,
1282
- inputLanguage,
1283
- outputLanguage,
1284
- type,
1285
- tone,
1286
- length,
1287
- instructions,
1288
- ]);
1289
-
1290
- const compactFieldStyles = {
1291
- label: { fontSize: 11, opacity: 0.85 },
1292
- description: { fontSize: 11, opacity: 0.65, marginTop: 2 },
1293
- input: { fontSize: 12 },
1294
- };
1295
-
1296
- const RootComponent: typeof Modal.Root | typeof Group =
1297
- variation === "modal" ? Modal.Root : Group;
1298
- const ContentComponent: typeof Modal.Content | typeof Group =
1299
- variation === "modal" ? Modal.Content : Group;
1300
- const BodyComponent: typeof Modal.Body | typeof Group =
1301
- variation === "modal" ? Modal.Body : Group;
1302
- const CollapseComponent = optionsDisplay === "collapse" ? Collapse : Stack;
1303
- const OptionsComponent = optionsDisplay === "horizontal" ? Group : Stack;
1304
-
1305
- const selectedLanguageOption = useMemo(
1306
- () =>
1307
- supportedLanguageOptions.find(
1308
- (option) => option.value === currentUiLanguage,
1309
- ) ?? supportedLanguageOptions[0],
1310
- [currentUiLanguage, supportedLanguageOptions],
1311
- );
1312
-
1313
- const renderLanguageOverrideSelect = useCallback(
1314
- (size: "xs" | "sm" = "sm") => (
1315
- <Select
1316
- allowDeselect={false}
1317
- aria-label={I18n.get("Interface language")}
1318
- checkIconPosition="right"
1319
- className="ai-feature-language-selector"
1320
- data={supportedLanguageOptions.map((option) => ({
1321
- value: option.value,
1322
- label: "",
1323
- }))}
1324
- leftSection={
1325
- selectedLanguageOption?.countryCode ? (
1326
- <LanguageFlag
1327
- countryCode={selectedLanguageOption.countryCode}
1328
- size={18}
1329
- />
1330
- ) : null
1331
- }
1332
- onChange={(value) => {
1333
- const nextLanguage = normalizeLang(value);
1334
-
1335
- if (!nextLanguage) {
1336
- return;
1337
- }
1338
-
1339
- setLanguageOverride(nextLanguage);
1340
- }}
1341
- renderOption={({ option }) => {
1342
- const languageOption = supportedLanguageOptions.find(
1343
- (item) => item.value === option.value,
1344
- );
1345
-
1346
- if (!languageOption) {
1347
- return option.label;
1348
- }
1349
-
1350
- return (
1351
- <Group gap="xs" wrap="nowrap">
1352
- {languageOption.countryCode ? (
1353
- <LanguageFlag
1354
- countryCode={languageOption.countryCode}
1355
- size={18}
1356
- />
1357
- ) : null}
1358
- <span>{I18n.get(languageOption.label)}</span>
1359
- </Group>
1360
- );
1361
- }}
1362
- rightSection={null}
1363
- searchable={false}
1364
- size={size}
1365
- styles={{
1366
- dropdown: {
1367
- minWidth: 220,
1368
- },
1369
- input: {
1370
- backgroundColor: "transparent",
1371
- border: 0,
1372
- boxShadow: "none",
1373
- color: "inherit",
1374
- fontSize: 18,
1375
- lineHeight: 1,
1376
- minHeight: size === "sm" ? 36 : 28,
1377
- paddingInlineStart: 0,
1378
- paddingInlineEnd: 0,
1379
- backgroundImage: "none",
1380
- width: size === "sm" ? 44 : 36,
1381
- },
1382
- option: {
1383
- color: "inherit",
1384
- },
1385
- section: {
1386
- color: "inherit",
1387
- alignItems: "center",
1388
- display: "flex",
1389
- height: "100%",
1390
- insetInlineStart: 0,
1391
- justifyContent: "center",
1392
- pointerEvents: "none",
1393
- width: "100%",
1394
- },
1395
- }}
1396
- value={selectedLanguageOption?.value || null}
1397
- w={size === "sm" ? 44 : 36}
1398
- />
1399
- ),
1400
- [
1401
- ai.busy,
1402
- selectedLanguageOption?.countryCode,
1403
- selectedLanguageOption?.value,
1404
- setLanguageOverride,
1405
- supportedLanguageOptions,
1406
- ],
1407
- );
1408
-
1409
- useEffect(() => {
1410
- if (variation !== "modal" || !featureOpen) {
1411
- return;
1412
- }
1413
- document.body.style.overflow = "hidden";
1414
- document.body.onkeydown = (e: KeyboardEvent) => {
1415
- if (e.key === "Escape") {
1416
- e.preventDefault();
1417
- close();
1418
- }
1419
- };
1420
- return () => {
1421
- // remove overflow: hidden; from body element
1422
- document.body.style.overflow = "";
1423
- document.body.onkeydown = null;
1424
- };
1425
- }, [close, variation]);
1426
-
1427
- const openButtonAccessibleLabel = I18n.get(openButtonTitle || defaultTitle);
1428
-
1429
- return (
1430
- <>
1431
- {showOpenButton && (
1432
- <Button
1433
- leftSection={
1434
- showOpenButtonIcon &&
1435
- (openButtonIcon ? (
1436
- <span dangerouslySetInnerHTML={{ __html: openButtonIcon }} />
1437
- ) : (
1438
- getOpenButtonDefaultIcon()
1439
- ))
1440
- }
1441
- className={
1442
- showOpenButtonTitle
1443
- ? "ai-feature-open-button"
1444
- : "ai-feature-open-button-no-title"
1445
- }
1446
- variant={"filled"}
1447
- disabled={featureOpen}
1448
- onClick={() => setFeatureOpen(true)}
1449
- aria-label={openButtonAccessibleLabel}
1450
- data-ai-kit-open-button
1451
- >
1452
- {showOpenButtonTitle && I18n.get(openButtonTitle || defaultTitle)}
1453
- </Button>
1454
- )}
1455
-
1456
- {featureOpen && (
1457
- <RootComponent
1458
- opened={true}
1459
- className="ai-feature-root"
1460
- onClose={close}
1461
- padding="md"
1462
- gap="md"
1463
- size="md"
1464
- portalProps={
1465
- variation === "modal"
1466
- ? {
1467
- target: modalRootElement ?? rootElement,
1468
- reuseTargetNode: true,
1469
- }
1470
- : undefined
1471
- }
1472
- data-ai-kit-theme={colorMode}
1473
- data-ai-kit-variation={variation}
1474
- >
1475
- {variation === "modal" && <Modal.Overlay />}
1476
- <ContentComponent
1477
- w="100%"
1478
- dir={effectiveDirection}
1479
- style={{
1480
- left: 0,
1481
- }}
1482
- >
1483
- {variation === "modal" && (
1484
- <Modal.Header dir={effectiveDirection} style={{ zIndex: 1000 }}>
1485
- {getOpenButtonDefaultIcon("ai-feature-title-icon")}
1486
- <Modal.Title>{I18n.get(defaultTitle)}</Modal.Title>
1487
- <div
1488
- style={{
1489
- display: "flex",
1490
- flex: 1,
1491
- justifyContent: "flex-start",
1492
- marginRight: 8,
1493
- }}
1494
- >
1495
- {renderLanguageOverrideSelect("xs")}
1496
- </div>
1497
- <Modal.CloseButton />
1498
- </Modal.Header>
1499
- )}
1500
- <BodyComponent w="100%" style={{ zIndex: 1001 }}>
1501
- <AiFeatureBorder
1502
- enabled={variation !== "modal"}
1503
- working={ai.busy}
1504
- variation={variation}
1505
- >
1506
- <Stack gap="sm" mb="sm" p="sm" dir={effectiveDirection}>
1507
- {variation !== "modal" && (
1508
- <Group justify="flex-end">
1509
- {renderLanguageOverrideSelect()}
1510
- </Group>
1511
- )}
1512
-
1513
- {/* ERROR */}
1514
- {error && (
1515
- <Alert
1516
- color="red"
1517
- role="alert"
1518
- aria-live="assertive"
1519
- data-ai-kit-error
1520
- >
1521
- <Stack gap={2}>
1522
- <Text size="sm">{I18n.get(error)}</Text>
1523
- {errorDetails?.requestId ? (
1524
- <Text size="xs" c="dimmed">
1525
- {I18n.get("Request ID")}: {errorDetails.requestId}
1526
- </Text>
1527
- ) : null}
1528
- </Stack>
1529
- </Alert>
1530
- )}
1531
-
1532
- {/* OVERRIDABLE PARAMETERS */}
1533
- {allowOverrideParameters && mode !== "proofread" && (
1534
- <Paper
1535
- withBorder
1536
- p="sm"
1537
- mt="md"
1538
- className="ai-feature-options"
1539
- data-options-display={optionsDisplay}
1540
- >
1541
- <Group
1542
- justify="space-between"
1543
- align="center"
1544
- className="ai-feature-options-summary"
1545
- onClick={
1546
- optionsDisplay === "collapse"
1547
- ? () => setOptionsOpen((v) => !v)
1548
- : undefined
1549
- }
1550
- >
1551
- {optionsDisplay === "collapse" && (
1552
- <Stack gap={0}>
1553
- <Text
1554
- size="sm"
1555
- fw={600}
1556
- style={{ lineHeight: 1.1 }}
1557
- >
1558
- {I18n.get("Options")}
1559
- </Text>
1560
- <Text size="xs" c="dimmed" style={{ marginTop: 2 }}>
1561
- {optionsSummary}
1562
- </Text>
1563
- </Stack>
1564
- )}
1565
-
1566
- {optionsDisplay === "collapse" && (
1567
- <Button
1568
- variant="subtle"
1569
- size="xs"
1570
- style={{ minWidth: "fit-content" }}
1571
- onClick={(e) => {
1572
- e.stopPropagation();
1573
- setOptionsOpen((v) => !v);
1574
- }}
1575
- >
1576
- {optionsOpen ? I18n.get("Hide") : I18n.get("Show")}
1577
- </Button>
1578
- )}
1579
- </Group>
1580
-
1581
- <CollapseComponent in={optionsOpen}>
1582
- {optionsDisplay === "collapse" && <Divider my="sm" />}
1583
- <OptionsComponent gap="xs" justify="space-between">
1584
- {/* TOPIC */}
1585
- {mode === "write" && allowOverride?.text && (
1586
- <Tooltip
1587
- label={I18n.get(
1588
- "The topic or subject for the AI to write about.",
1589
- )}
1590
- disabled={optionsDisplay !== "horizontal"}
1591
- position="top"
1592
- >
1593
- <TextInput
1594
- size="xs"
1595
- className="ai-feature-option"
1596
- styles={compactFieldStyles}
1597
- disabled={ai.busy}
1598
- label={I18n.get("Topic")}
1599
- description={
1600
- optionsDisplay !== "horizontal"
1601
- ? I18n.get(
1602
- "The topic or subject for the AI to write about.",
1603
- )
1604
- : undefined
1605
- }
1606
- value={text || ""}
1607
- onChange={(
1608
- e: React.ChangeEvent<HTMLInputElement>,
1609
- ) => {
1610
- const value = e.target.value;
1611
- setText(value);
1612
- onOptionsChanged?.({ text: value });
1613
- }}
1614
- />
1615
- </Tooltip>
1616
- )}
1617
- {/* INSTRUCTIONS */}
1618
- {(mode === "write" ||
1619
- mode === "rewrite" ||
1620
- mode === "generateImageMetadata" ||
1621
- mode === "generatePostMetadata") &&
1622
- allowOverride?.instructions && (
1623
- <Tooltip
1624
- label={I18n.get(
1625
- "Additional instructions to guide the AI.",
1626
- )}
1627
- disabled={optionsDisplay !== "horizontal"}
1628
- position="top"
1629
- >
1630
- <TextInput
1631
- disabled={ai.busy}
1632
- size="xs"
1633
- className="ai-feature-option"
1634
- styles={compactFieldStyles}
1635
- label={I18n.get("Instructions")}
1636
- description={
1637
- optionsDisplay !== "horizontal"
1638
- ? I18n.get(
1639
- "Additional instructions to guide the AI.",
1640
- )
1641
- : undefined
1642
- }
1643
- value={instructions || ""}
1644
- onChange={(
1645
- e: React.ChangeEvent<HTMLInputElement>,
1646
- ) => {
1647
- const value = e.target.value;
1648
- setInstructions(value);
1649
- onOptionsChanged?.({ instructions: value });
1650
- }}
1651
- />
1652
- </Tooltip>
1653
- )}
1654
- {/* INPUT LANGUAGE */}
1655
- {mode === "translate" && (
1656
- <Tooltip
1657
- label={I18n.get(
1658
- "The language of the input text.",
1659
- )}
1660
- disabled={optionsDisplay !== "horizontal"}
1661
- position="top"
1662
- >
1663
- <Select
1664
- disabled={ai.busy}
1665
- size="xs"
1666
- styles={compactFieldStyles}
1667
- className="ai-feature-option"
1668
- label={I18n.get("Input language")}
1669
- description={
1670
- optionsDisplay !== "horizontal"
1671
- ? I18n.get(
1672
- "The language of the input text.",
1673
- )
1674
- : undefined
1675
- }
1676
- data={[
1677
- {
1678
- value: "auto",
1679
- label: I18n.get("Auto-detect"),
1680
- },
1681
- ...LANGUAGE_OPTIONS.map((lo) => ({
1682
- value: lo.value,
1683
- label: I18n.get(lo.label),
1684
- })).sort((a, b) =>
1685
- a.label.localeCompare(b.label),
1686
- ),
1687
- ]}
1688
- value={inputLanguage || "auto"}
1689
- onChange={(value) => {
1690
- const val = value as AiKitLanguageCode;
1691
- setInputLanguage(val);
1692
- setDetectedLanguage(undefined);
1693
- onOptionsChanged?.({ inputLanguage: val });
1694
- }}
1695
- />
1696
- </Tooltip>
1697
- )}
1698
- {/* OUTPUT LANGUAGE */}
1699
- {allowOverride?.outputLanguage && (
1700
- <Tooltip
1701
- label={I18n.get(
1702
- "The language AI-Kit should use for generated text by default (when applicable).",
1703
- )}
1704
- disabled={optionsDisplay !== "horizontal"}
1705
- position="top"
1706
- >
1707
- <Select
1708
- disabled={ai.busy}
1709
- size="xs"
1710
- styles={compactFieldStyles}
1711
- className="ai-feature-option"
1712
- label={I18n.get("Output language")}
1713
- description={
1714
- optionsDisplay !== "horizontal"
1715
- ? I18n.get(
1716
- "The language AI-Kit should use for generated text by default (when applicable).",
1717
- )
1718
- : undefined
1719
- }
1720
- data={[
1721
- ...([
1722
- mode === "rewrite"
1723
- ? {
1724
- value: "auto",
1725
- label: I18n.get("Auto-detect"),
1726
- }
1727
- : undefined,
1728
- ].filter(Boolean) as {
1729
- value: string;
1730
- label: string;
1731
- }[]),
1732
- ...LANGUAGE_OPTIONS.map((lo) => ({
1733
- value: lo.value,
1734
- label: I18n.get(lo.label),
1735
- })).sort((a, b) =>
1736
- a.label.localeCompare(b.label),
1737
- ),
1738
- ]}
1739
- value={
1740
- outputLanguage ||
1741
- aiKit.settings.defaultOutputLanguage ||
1742
- (mode === "rewrite" ? "auto" : "")
1743
- }
1744
- onChange={(value) => {
1745
- const val = value as AiKitLanguageCode;
1746
- setOutputLanguage(val);
1747
- setDetectedLanguage(undefined);
1748
- onOptionsChanged?.({ outputLanguage: val });
1749
- }}
1750
- />
1751
- </Tooltip>
1752
- )}
1753
- {/* TYPE */}
1754
- {mode === "summarize" && allowOverride?.type && (
1755
- <Tooltip
1756
- label={I18n.get("The summary style to generate.")}
1757
- disabled={optionsDisplay !== "horizontal"}
1758
- position="top"
1759
- >
1760
- <Select
1761
- disabled={ai.busy}
1762
- size="xs"
1763
- className="ai-feature-option"
1764
- styles={compactFieldStyles}
1765
- label={I18n.get("Type")}
1766
- description={
1767
- optionsDisplay !== "horizontal"
1768
- ? I18n.get("The summary style to generate.")
1769
- : undefined
1770
- }
1771
- data={[
1772
- {
1773
- value: "headline",
1774
- label: I18n.get("Headline"),
1775
- },
1776
- {
1777
- value: "key-points",
1778
- label: I18n.get("Key Points"),
1779
- },
1780
- {
1781
- value: "teaser",
1782
- label: I18n.get("Teaser"),
1783
- },
1784
- {
1785
- value: "tldr",
1786
- label: I18n.get("TL;DR"),
1787
- },
1788
- ]}
1789
- value={type || "key-points"}
1790
- onChange={(value) => {
1791
- const val = value as SummarizerType;
1792
- setType(val);
1793
- onOptionsChanged?.({ type: val });
1794
- }}
1795
- />
1796
- </Tooltip>
1797
- )}
1798
- {/* TONE */}
1799
- {(mode === "write" || mode === "rewrite") &&
1800
- allowOverride?.tone && (
1801
- <Tooltip
1802
- label={I18n.get(
1803
- "The tone or style for the AI to use.",
1804
- )}
1805
- disabled={optionsDisplay !== "horizontal"}
1806
- position="top"
1807
- >
1808
- <Select
1809
- disabled={ai.busy}
1810
- size="xs"
1811
- className="ai-feature-option"
1812
- styles={compactFieldStyles}
1813
- label={I18n.get("Tone")}
1814
- description={
1815
- optionsDisplay !== "horizontal"
1816
- ? I18n.get(
1817
- "The tone or style for the AI to use.",
1818
- )
1819
- : undefined
1820
- }
1821
- data={
1822
- mode === "write"
1823
- ? [
1824
- {
1825
- value: "neutral",
1826
- label: I18n.get("Neutral"),
1827
- },
1828
- {
1829
- value: "formal",
1830
- label: I18n.get("Formal"),
1831
- },
1832
- {
1833
- value: "casual",
1834
- label: I18n.get("Casual"),
1835
- },
1836
- ]
1837
- : [
1838
- {
1839
- value: "as-is",
1840
- label: I18n.get("As-Is"),
1841
- },
1842
- {
1843
- value: "more-formal",
1844
- label: I18n.get("More formal"),
1845
- },
1846
- {
1847
- value: "more-casual",
1848
- label: I18n.get("More casual"),
1849
- },
1850
- ]
1851
- }
1852
- value={
1853
- tone ||
1854
- (mode === "write" ? "neutral" : "as-is")
1855
- }
1856
- onChange={(value) => {
1857
- const val = value as
1858
- | WriterTone
1859
- | RewriterTone;
1860
- setTone(val);
1861
- onOptionsChanged?.({ tone: val });
1862
- }}
1863
- />
1864
- </Tooltip>
1865
- )}
1866
- {/* LENGTH */}
1867
- {(mode === "write" ||
1868
- mode === "rewrite" ||
1869
- mode === "summarize") &&
1870
- allowOverride?.length && (
1871
- <Tooltip
1872
- label={I18n.get("The target output length.")}
1873
- disabled={optionsDisplay !== "horizontal"}
1874
- position="top"
1875
- >
1876
- <Select
1877
- disabled={ai.busy}
1878
- size="xs"
1879
- className="ai-feature-option"
1880
- styles={compactFieldStyles}
1881
- label={I18n.get("Length")}
1882
- description={
1883
- optionsDisplay !== "horizontal"
1884
- ? I18n.get("The target output length.")
1885
- : undefined
1886
- }
1887
- data={
1888
- mode === "write" || mode === "summarize"
1889
- ? [
1890
- {
1891
- value: "short",
1892
- label: I18n.get("Short"),
1893
- },
1894
- {
1895
- value: "medium",
1896
- label: I18n.get("Medium"),
1897
- },
1898
- {
1899
- value: "long",
1900
- label: I18n.get("Long"),
1901
- },
1902
- ]
1903
- : [
1904
- {
1905
- value: "as-is",
1906
- label: I18n.get("As-Is"),
1907
- },
1908
- {
1909
- value: "shorter",
1910
- label: I18n.get("Shorter"),
1911
- },
1912
- {
1913
- value: "longer",
1914
- label: I18n.get("Longer"),
1915
- },
1916
- ]
1917
- }
1918
- value={
1919
- length ||
1920
- (mode === "rewrite" ? "as-is" : "short")
1921
- }
1922
- onChange={(value) => {
1923
- const val = value as
1924
- | WriterLength
1925
- | RewriterLength
1926
- | SummarizerLength;
1927
- setLength(val);
1928
- onOptionsChanged?.({ length: val });
1929
- }}
1930
- />
1931
- </Tooltip>
1932
- )}
1933
- {/* OUTPUT FORMAT */}
1934
- {mode === "summarize" ||
1935
- mode === "write" ||
1936
- (mode === "rewrite" &&
1937
- allowOverride?.outputFormat && (
1938
- <Tooltip
1939
- label={I18n.get(
1940
- "The format for the generated output.",
1941
- )}
1942
- disabled={optionsDisplay !== "horizontal"}
1943
- position="top"
1944
- >
1945
- <Select
1946
- disabled={ai.busy}
1947
- size="xs"
1948
- className="ai-feature-option"
1949
- styles={compactFieldStyles}
1950
- label={I18n.get("Output format")}
1951
- description={
1952
- optionsDisplay !== "horizontal"
1953
- ? I18n.get(
1954
- "The format for the generated output.",
1955
- )
1956
- : undefined
1957
- }
1958
- data={[
1959
- {
1960
- value: "plain-text",
1961
- label: I18n.get("Plain Text"),
1962
- },
1963
- {
1964
- value: "markdown",
1965
- label: I18n.get("Markdown"),
1966
- },
1967
- {
1968
- value: "html",
1969
- label: I18n.get("HTML"),
1970
- },
1971
- ]}
1972
- value={outputFormat || "markdown"}
1973
- onChange={(value) => {
1974
- const val = value as
1975
- | "plain-text"
1976
- | "markdown"
1977
- | "html";
1978
- setOutputFormat(val);
1979
- onOptionsChanged?.({ outputFormat: val });
1980
- }}
1981
- />
1982
- </Tooltip>
1983
- ))}
1984
- </OptionsComponent>
1985
- </CollapseComponent>
1986
- </Paper>
1987
- )}
1988
-
1989
- {/* AI STATUS */}
1990
- {ai.busy && statusText && (
1991
- <AiFeatureBorder
1992
- enabled={variation === "modal"}
1993
- working={true}
1994
- variation={variation}
1995
- >
1996
- <Group
1997
- justify="center"
1998
- align="center"
1999
- gap="sm"
2000
- m="sm"
2001
- pr="lg"
2002
- >
2003
- <Loader size="sm" />
2004
- <Input.Label className="ai-feature-status-text">
2005
- {statusText}
2006
- </Input.Label>
2007
- </Group>
2008
- </AiFeatureBorder>
2009
- )}
2010
-
2011
- {/* GENERATED OUTPUT */}
2012
- {generated && (
2013
- <Stack mt="md">
2014
- {mode === "proofread" &&
2015
- ((generated as ProofreadResult).corrections.length ===
2016
- 0 ? (
2017
- <Alert color="green">
2018
- {I18n.get(
2019
- "No issues found. Your text looks great!",
2020
- )}
2021
- </Alert>
2022
- ) : (
2023
- <>
2024
- <p style={{ marginTop: 0, opacity: 0.85 }}>
2025
- {I18n.get(
2026
- "Hover highlights to see explanations.",
2027
- )}
2028
- </p>
2029
- <ProofreadDiff
2030
- original={text!}
2031
- corrections={
2032
- (generated as ProofreadResult).corrections
2033
- }
2034
- />
2035
- {(generated as ProofreadResult).correctedInput ? (
2036
- <>
2037
- <h4
2038
- style={{
2039
- marginTop: 16,
2040
- marginBottom: 8,
2041
- }}
2042
- >
2043
- {I18n.get("Corrected")}
2044
- </h4>
2045
- <Group
2046
- c="pre"
2047
- className="ai-feature-generated-content"
2048
- >
2049
- {
2050
- (generated as ProofreadResult)
2051
- .correctedInput
2052
- }
2053
- </Group>
2054
- </>
2055
- ) : null}
2056
- </>
2057
- ))}
2058
- {mode === "generateImageMetadata" && (
2059
- <>
2060
- <TextInput
2061
- readOnly={!editable}
2062
- label={I18n.get("Alt Text")}
2063
- description={I18n.get(
2064
- "The alt text for the image.",
2065
- )}
2066
- value={
2067
- (generated as GeneratedImageMetadata).alt_text ||
2068
- ""
2069
- }
2070
- onChange={(
2071
- e: React.ChangeEvent<HTMLInputElement>,
2072
- ) =>
2073
- setGenerated({
2074
- ...(generated as GeneratedImageMetadata),
2075
- alt_text: e.target.value,
2076
- } as never)
2077
- }
2078
- />
2079
- <TextInput
2080
- readOnly={!editable}
2081
- label={I18n.get("Title")}
2082
- description={I18n.get("The title for the image.")}
2083
- value={
2084
- (generated as GeneratedImageMetadata).title || ""
2085
- }
2086
- onChange={(
2087
- e: React.ChangeEvent<HTMLInputElement>,
2088
- ) =>
2089
- setGenerated({
2090
- ...(generated as GeneratedImageMetadata),
2091
- title: e.target.value,
2092
- } as never)
2093
- }
2094
- />
2095
- <TextInput
2096
- readOnly={!editable}
2097
- label={I18n.get("Caption")}
2098
- description={I18n.get("The caption for the image.")}
2099
- value={
2100
- (generated as GeneratedImageMetadata).caption ||
2101
- ""
2102
- }
2103
- onChange={(
2104
- e: React.ChangeEvent<HTMLInputElement>,
2105
- ) =>
2106
- setGenerated({
2107
- ...(generated as GeneratedImageMetadata),
2108
- caption: e.target.value,
2109
- } as never)
2110
- }
2111
- />
2112
- <TextInput
2113
- readOnly={!editable}
2114
- label={I18n.get("Description")}
2115
- description={I18n.get(
2116
- "The description for the image.",
2117
- )}
2118
- value={
2119
- (generated as GeneratedImageMetadata)
2120
- .description || ""
2121
- }
2122
- onChange={(
2123
- e: React.ChangeEvent<HTMLInputElement>,
2124
- ) =>
2125
- setGenerated({
2126
- ...(generated as GeneratedImageMetadata),
2127
- description: e.target.value,
2128
- } as never)
2129
- }
2130
- />
2131
- </>
2132
- )}
2133
- {mode === "generatePostMetadata" && (
2134
- <>
2135
- <TextInput
2136
- readOnly={!editable}
2137
- label={I18n.get("Title")}
2138
- description={I18n.get("The title for the post.")}
2139
- value={
2140
- (generated as GeneratedPostMetadata).title || ""
2141
- }
2142
- onChange={(
2143
- e: React.ChangeEvent<HTMLInputElement>,
2144
- ) =>
2145
- setGenerated({
2146
- ...(generated as GeneratedPostMetadata),
2147
- title: e.target.value,
2148
- } as never)
2149
- }
2150
- />
2151
- <TextInput
2152
- readOnly={!editable}
2153
- label={I18n.get("Excerpt")}
2154
- description={I18n.get("The excerpt for the post.")}
2155
- value={
2156
- (generated as GeneratedPostMetadata).excerpt || ""
2157
- }
2158
- onChange={(
2159
- e: React.ChangeEvent<HTMLInputElement>,
2160
- ) =>
2161
- setGenerated({
2162
- ...(generated as GeneratedPostMetadata),
2163
- excerpt: e.target.value,
2164
- } as never)
2165
- }
2166
- />
2167
- </>
2168
- )}
2169
- {mode !== "proofread" &&
2170
- mode !== "generateImageMetadata" &&
2171
- mode !== "generatePostMetadata" &&
2172
- typeof generated === "string" && (
2173
- <MarkdownResult
2174
- contentLanguage={generatedContentLanguage}
2175
- value={generated}
2176
- editable={!!editable}
2177
- onChange={(v) => {
2178
- setGenerated(v as never);
2179
- }}
2180
- />
2181
- )}
2182
- </Stack>
2183
- )}
2184
- {generated === "" && (
2185
- <MarkdownResult
2186
- contentLanguage={generatedContentLanguage}
2187
- value={generated}
2188
- editable={false}
2189
- />
2190
- )}
2191
- </Stack>
2192
- {/* ACTIONS */}
2193
- <Group className="ai-kit-actions" gap="sm" mb="sm" p="sm">
2194
- {ai.busy && (
2195
- <Button
2196
- variant="outline"
2197
- size="sm"
2198
- onClick={cancel}
2199
- data-ai-kit-cancel-button
2200
- >
2201
- {I18n.get("Cancel")}
2202
- </Button>
2203
- )}
2204
-
2205
- {!ai.busy && (
2206
- <Button
2207
- variant="filled"
2208
- size="sm"
2209
- disabled={!canGenerate}
2210
- onClick={() => runGenerate()}
2211
- data-ai-kit-generate-button
2212
- >
2213
- {getGenerateTitle()}
2214
- </Button>
2215
- )}
2216
-
2217
- {!ai.busy &&
2218
- ai.lastSource === "on-device" &&
2219
- backendConfigured &&
2220
- showRegenerateOnBackendButton && (
2221
- <Button
2222
- variant="filled"
2223
- size="sm"
2224
- disabled={!canGenerate}
2225
- onClick={runGenerateOnBackend}
2226
- data-ai-kit-regenerate-on-backend-button
2227
- >
2228
- {getRegenerateOnBackendTitle()}
2229
- </Button>
2230
- )}
2231
-
2232
- {!ai.busy && onAccept && (
2233
- <Button
2234
- variant="outline"
2235
- size="sm"
2236
- disabled={
2237
- !generated ||
2238
- (mode === "proofread" &&
2239
- (generated as ProofreadResult).corrections.length ===
2240
- 0)
2241
- }
2242
- onClick={async () => {
2243
- onAccept(
2244
- outputFormat === "html"
2245
- ? await markdownToHtml(generated!)
2246
- : generated!,
2247
- );
2248
- close();
2249
- }}
2250
- data-ai-kit-accept-button
2251
- >
2252
- {I18n.get(acceptButtonTitle!)}
2253
- </Button>
2254
- )}
2255
-
2256
- <Button
2257
- variant="default"
2258
- size="sm"
2259
- onClick={close}
2260
- data-ai-kit-close-button
2261
- >
2262
- {I18n.get("Close")}
2263
- </Button>
2264
- </Group>
2265
- <PoweredBy variation={variation} />
2266
- </AiFeatureBorder>
2267
- </BodyComponent>
2268
- </ContentComponent>
2269
- </RootComponent>
2270
- )}
2271
- </>
2272
- );
2273
- };
2274
-
2275
- function MarkdownResult(props: {
2276
- contentLanguage?: AiKitLanguageCode | "";
2277
- value: string;
2278
- editable: boolean;
2279
- onChange?: (v: string) => void;
2280
- }) {
2281
- const { contentLanguage, value, editable, onChange } = props;
2282
- const contentDirection = isRtlLanguage(contentLanguage) ? "rtl" : "ltr";
2283
- const contentAlign = contentDirection === "rtl" ? "right" : "left";
2284
-
2285
- if (editable) {
2286
- return (
2287
- <Stack
2288
- p={0}
2289
- gap="sm"
2290
- dir={contentDirection}
2291
- style={{ textAlign: contentAlign }}
2292
- >
2293
- <Input.Label>{I18n.get("Generated content")}</Input.Label>
2294
- <Textarea
2295
- value={value}
2296
- onChange={(e) => onChange?.(e.currentTarget.value)}
2297
- autosize
2298
- minRows={2}
2299
- maxRows={12}
2300
- p={0}
2301
- className="ai-feature-generated-content ai-feature-editor"
2302
- styles={{
2303
- input: { direction: contentDirection, textAlign: contentAlign },
2304
- }}
2305
- />
2306
-
2307
- <Input.Label>{I18n.get("Preview")}</Input.Label>
2308
- <Stack
2309
- className="ai-feature-generated-content ai-feature-preview"
2310
- dir={contentDirection}
2311
- style={{ textAlign: contentAlign }}
2312
- >
2313
- <ReactMarkdown remarkPlugins={[remarkGfm]}>{value}</ReactMarkdown>
2314
- </Stack>
2315
- </Stack>
2316
- );
2317
- }
2318
-
2319
- return (
2320
- <Stack
2321
- className="ai-feature-generated-content"
2322
- dir={contentDirection}
2323
- style={{ textAlign: contentAlign }}
2324
- >
2325
- {value ? (
2326
- <ReactMarkdown remarkPlugins={[remarkGfm]}>{value}</ReactMarkdown>
2327
- ) : (
2328
- <Alert color="yellow">{I18n.get("No content generated.")}</Alert>
2329
- )}
2330
- </Stack>
2331
- );
2332
- }
2333
-
2334
- export const AiFeature = withAiKitShell(AiFeatureBase);