-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathExtractFields.tsx
More file actions
1479 lines (1408 loc) · 58.6 KB
/
ExtractFields.tsx
File metadata and controls
1479 lines (1408 loc) · 58.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
'use client';
import { Input } from '@/components/ui/input';
import { useCreateBlueprintStore } from '../store';
import { useEffect, useState, memo, useMemo } from 'react';
import { Select } from '@/components/ui/select';
import { Label } from '@/components/ui/label';
import { Button } from '@/components/ui/button';
import Image from 'next/image';
import { AnimatePresence, motion } from 'framer-motion';
import {
DecomposedRegex,
DecomposedRegexPart,
ExternalInput,
parseEmail,
testDecomposedRegex,
} from '@zk-email/sdk';
import { toast } from 'react-toastify';
import { posthog } from 'posthog-js';
import { Separator } from '@/components/ui/separator';
import Link from 'next/link';
import { REGEX_COLORS } from '@/app/constants';
import { Checkbox } from '@/components/ui/checkbox';
// Memoized Status component to prevent recreation on each render
interface StatusProps {
emlContent: string;
showNoRegexesError: boolean;
isGeneratingFields: boolean;
regexGeneratedOutputs: string[];
regexGeneratedOutputErrors: string[];
skipEmlUpload: boolean;
}
// Pure utility function - doesn't need to be recreated on each render
const parseRegexParts = (parts: any): any => {
if (typeof parts === 'string') {
try {
return JSON.parse(parts);
} catch {
return [];
}
}
return parts || [];
};
// Calculate maxLength: sum of all public part maxLengths
const calculateMaxLength = (parts: any[]): number => {
const totalPublicMaxLength = parts.reduce((acc: number, p: any) => {
if (p && p.isPublic) {
return acc + (p.maxLength ?? 64);
}
return acc;
}, 0);
return totalPublicMaxLength || 64;
};
// Calculate maxMatchLength: sum of all public part maxLengths + 16 padding
const calculateMaxMatchLength = (parts: any[]): number => {
const totalPublicMaxLength = parts.reduce((acc: number, p: any) => {
if (p && p.isPublic) {
return acc + (p.maxLength ?? 64);
}
return acc;
}, 0);
return totalPublicMaxLength + 16;
};
const Status = memo(({
emlContent,
isGeneratingFields,
regexGeneratedOutputs,
regexGeneratedOutputErrors,
showNoRegexesError,
skipEmlUpload
}: StatusProps) => {
console.log('skipEmlUpload', skipEmlUpload);
if (!emlContent && !skipEmlUpload) {
return (
<div className="flex items-center gap-2 text-red-400">
<Image
src="/assets/WarningCircle.svg"
alt="fail"
width={20}
height={20}
style={{
maxWidth: '100%',
height: 'auto',
}}
/>
<span className="text-base font-medium">Please provide an email file</span>
</div>
);
}
if (isGeneratingFields) {
return (
<div className="flex items-center gap-2">
<div className="h-5 w-5 animate-spin rounded-full border-2 border-gray-300 border-t-gray-600" />
<span className="text-base font-medium">Generating fields...</span>
</div>
);
}
if (showNoRegexesError) {
return (
<div className="flex items-center gap-2 text-red-400">
<Image
src="/assets/WarningCircle.svg"
alt="fail"
width={20}
height={20}
style={{
maxWidth: '100%',
height: 'auto',
}}
/>
<span className="text-base font-medium">Please add at least one regex</span>
</div>
);
}
// Check for errors in regexGeneratedOutputErrors array
const hasRegexErrors = regexGeneratedOutputErrors.some(error => error && error.length > 0);
if (
(!regexGeneratedOutputs.length ||
hasRegexErrors ||
regexGeneratedOutputs.some((output) =>
Array.isArray(output)
? output.join('').includes('Error')
: output
? output.includes('Error')
: true
)) && !skipEmlUpload
) {
return (
<div className="flex items-center gap-2 text-red-400">
<Image
src="/assets/WarningCircle.svg"
alt="fail"
width={20}
height={20}
style={{
maxWidth: '100%',
height: 'auto',
}}
/>
<span className="text-base font-medium">Some regexes failed to generate output</span>
</div>
);
} else {
return (
<div className="flex items-center gap-2 text-green-300">
<Image
src="/assets/CheckCircle.svg"
alt="check"
width={20}
height={20}
style={{
maxWidth: '100%',
height: 'auto',
}}
/>
<span className="text-base font-medium">All tests passed. Ready to compile</span>
</div>
);
}
});
Status.displayName = 'Status';
const AIPromptInput = memo(({
aiPrompt,
setAiPrompt,
handleGenerateFields,
emlContent,
isGeneratingFieldsLoading,
}: {
aiPrompt: string;
setAiPrompt: (aiPrompt: string) => void;
handleGenerateFields: () => void;
emlContent: string;
isGeneratingFieldsLoading: boolean;
}) => {
const [placeholderIndex, setPlaceholderIndex] = useState(0);
const placeholders = [
'Regex to extract email subject',
'Regex to extract GitHub username',
'Regex to extract Venmo ID',
'Regex to extract time sent',
];
useEffect(() => {
const interval = setInterval(() => {
setPlaceholderIndex((prevIndex) => (prevIndex + 1) % placeholders.length);
}, 3000);
return () => clearInterval(interval);
}, []);
return (
<div className="flex flex-col gap-2">
<div className="rounded-lg border border-[#EDCEF8] p-3 pl-0 shadow-[0px_0px_10px_0px_#EDCEF8]">
<div className="flex items-center justify-between">
<span className="w-full text-base font-medium">
<Input
className="w-full border-0 hover:border-0 focus:border-0 focus-visible:ring-0 focus-visible:ring-offset-0"
placeholder={placeholders[placeholderIndex]}
value={aiPrompt}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
handleGenerateFields();
}
}}
onChange={(e) => setAiPrompt(e.target.value)}
/>
</span>
<Button
className="rounded-lg border-[#EDCEF8] bg-[#FCF3FF] text-sm text-[#9B23C5]"
variant="secondary"
size="sm"
disabled={!emlContent || isGeneratingFieldsLoading}
loading={isGeneratingFieldsLoading}
startIcon={
<Image
src="/assets/Sparkle.svg"
alt="sparkle"
width={16}
height={16}
style={{
maxWidth: '100%',
height: 'auto',
}}
/>
}
onClick={handleGenerateFields}
>
{isGeneratingFieldsLoading ? 'Generating...' : 'Generate'}
</Button>
</div>
</div>
</div>
);
});
AIPromptInput.displayName = 'AIPromptInput';
const ExtractFields = ({
emlContent,
optOut,
setCanCompile,
skipEmlUpload,
}: {
emlContent: string;
optOut: boolean;
setCanCompile: (canCompile: boolean) => void;
skipEmlUpload: boolean;
}) => {
const store = useCreateBlueprintStore();
const { setField, getParsedDecomposedRegexes } = store;
const [isGeneratingFieldsLoading, setIsGeneratingFieldsLoading] = useState<boolean[]>(
Array(store.decomposedRegexes?.length ?? 0).fill(false)
);
const [revealPrivateFields, setRevealPrivateFields] = useState(false);
const [aiPrompts, setAiPrompts] = useState<string[]>(
Array(store.decomposedRegexes?.length ?? 0).fill('')
);
const [regexGeneratedOutputs, setRegexGeneratedOutputs] = useState<string[]>(
Array(store.decomposedRegexes?.length ?? 0).fill('')
);
const [regexGeneratedOutputErrors, setRegexGeneratedOutputErrors] = useState<string[]>(
Array(store.decomposedRegexes?.length ?? 0).fill('')
);
const [isExtractSubjectChecked, setIsExtractSubjectChecked] = useState(false);
const [isExtractReceiverChecked, setIsExtractReceiverChecked] = useState(false);
const [isExtractSenderNameChecked, setIsExtractSenderNameChecked] = useState(false);
const [isExtractSenderDomainChecked, setIsExtractSenderDomainChecked] = useState(false);
const [isExtractTimestampChecked, setIsExtractTimestampChecked] = useState(false);
const [isGeneratingFields, setIsGeneratingFields] = useState(false);
// Sync checkbox states with decomposedRegexes
useEffect(() => {
setIsExtractSubjectChecked(store.decomposedRegexes?.some(r => r.name === 'subject') ?? false);
setIsExtractReceiverChecked(store.decomposedRegexes?.some(r => r.name === 'email_recipient') ?? false);
setIsExtractSenderNameChecked(store.decomposedRegexes?.some(r => r.name === 'email_sender') ?? false);
setIsExtractSenderDomainChecked(store.decomposedRegexes?.some(r => r.name === 'sender_domain') ?? false);
setIsExtractTimestampChecked(store.decomposedRegexes?.some(r => r.name === 'email_timestamp') ?? false);
}, [store.decomposedRegexes]);
// Handle canCompile state updates based on conditions
useEffect(() => {
const hasNoEmail = !emlContent;
const isGenerating = isGeneratingFields;
const noRegexes = !regexGeneratedOutputs.length;
// Check for errors in regexGeneratedOutputErrors array
const hasRegexErrors = regexGeneratedOutputErrors.some(error => error && error.length > 0);
// Check for errors in the output itself
const hasOutputErrors = regexGeneratedOutputs.some((output) =>
Array.isArray(output)
? output.join('').includes('Error')
: output
? output.includes('Error')
: true
);
setCanCompile(!hasNoEmail && !isGenerating && !noRegexes && !hasRegexErrors && !hasOutputErrors);
}, [emlContent, isGeneratingFields, regexGeneratedOutputs, regexGeneratedOutputErrors, setCanCompile]);
// Memoize the stringified value to avoid expensive recalculation on every render
const decomposedRegexesKey = useMemo(
() => JSON.stringify(store.decomposedRegexes),
[store.decomposedRegexes]
);
// Ensure maxMatchLength is always recalculated when parts change
// Use a memoized key based on parts to detect changes without causing infinite loops
const partsKey = useMemo(() => {
return store.decomposedRegexes?.map((regex: DecomposedRegex) => {
const parts = parseRegexParts(regex.parts);
return parts.map((p: any) => ({
isPublic: p.isPublic,
maxLength: p.maxLength,
}));
});
}, [store.decomposedRegexes]);
useEffect(() => {
if (!store.decomposedRegexes?.length) return;
const updatedRegexes = store.decomposedRegexes.map((regex: DecomposedRegex) => {
const parts = parseRegexParts(regex.parts);
const calculatedMaxLength = calculateMaxLength(parts);
const calculatedMaxMatchLength = calculateMaxMatchLength(parts);
// Update if maxLength or maxMatchLength is missing, undefined, or different to ensure they're always set correctly
const needsUpdate =
regex.maxLength === undefined || regex.maxLength === null || regex.maxLength !== calculatedMaxLength ||
regex.maxMatchLength === undefined || regex.maxMatchLength === null || regex.maxMatchLength !== calculatedMaxMatchLength;
if (needsUpdate) {
return {
...regex,
maxLength: calculatedMaxLength,
maxMatchLength: calculatedMaxMatchLength,
};
}
return regex;
});
// Check if any regex was updated
const hasChanges = updatedRegexes.some((updated, index) => {
const original = store.decomposedRegexes[index];
return !original ||
updated.maxLength !== original.maxLength ||
updated.maxMatchLength !== original.maxMatchLength;
});
if (hasChanges) {
setField('decomposedRegexes', updatedRegexes);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [partsKey]);
useEffect(() => {
let cancelled = false;
const generateRegexOutputs = async () => {
setIsGeneratingFields(true);
if (!emlContent || !store.decomposedRegexes?.length) {
// Clear outputs when there are no regexes
setRegexGeneratedOutputs([]);
setRegexGeneratedOutputErrors([]);
setIsGeneratingFields(false);
return;
}
const parsedEmail = await parseEmail(emlContent);
const body = parsedEmail.cleanedBody;
const header = parsedEmail.canonicalizedHeader;
await Promise.all(
store.decomposedRegexes?.map(async (regex: DecomposedRegex, index: number) => {
try {
const parsedRegex = Array.isArray(regex.parts)
? regex
: { ...regex, parts: JSON.parse(regex.parts ?? '[]') };
if (parsedRegex.parts.length === 0) {
return;
}
const regexOutputs = await testDecomposedRegex(
body,
header,
parsedRegex,
revealPrivateFields
);
// Only update state if component is still mounted
if (cancelled) return;
// Validate output lengths against maxLength for public parts
const parts = parseRegexParts(parsedRegex.parts);
let validationError = '';
const errorParts: string[] = [];
parts.forEach((part: any, partIndex: number) => {
if (part.isPublic && part.maxLength !== undefined && regexOutputs[partIndex]) {
const actualLength = regexOutputs[partIndex].length;
if (actualLength > part.maxLength) {
errorParts.push(`Part ${partIndex + 1}: length ${actualLength} exceeds max ${part.maxLength}`);
}
}
});
if (errorParts.length > 0) {
validationError = `Max length exceeded: ${errorParts.join(', ')}`;
}
// Check again before state updates
if (!cancelled) {
setRegexGeneratedOutputs((prev) => {
const updated = [...prev];
// @ts-ignore
updated[index] = regexOutputs;
return updated;
});
setRegexGeneratedOutputErrors((prev) => {
const updated = [...prev];
// @ts-ignore
updated[index] = validationError;
return updated;
});
// Always update maxLength and maxMatchLength based on the actual regex outputs
// This ensures they're calculated from the real output lengths, not just the part definitions
if (!validationError && regexOutputs && regexOutputs.length > 0) {
const parts = parseRegexParts(parsedRegex.parts);
// Update individual part max lengths based on actual output lengths
// Only auto-update if maxLength is undefined (preserves user-defined values)
const updatedParts = parts.map((part: any, partIndex: number) => {
if (part.isPublic && regexOutputs[partIndex]) {
const partLength = regexOutputs[partIndex].length;
// Only auto-update if maxLength is undefined (not manually set)
if (part.maxLength === undefined) {
return {
...part,
maxLength: partLength
};
}
// Keep the manually set value
return part;
}
return part;
});
// Calculate maxLength and maxMatchLength from the updated parts
const calculatedMaxLength = calculateMaxLength(updatedParts);
const calculatedMaxMatchLength = calculateMaxMatchLength(updatedParts);
const decomposedRegexes = [...store.decomposedRegexes];
decomposedRegexes[index] = {
...decomposedRegexes[index],
parts: updatedParts,
maxLength: calculatedMaxLength,
maxMatchLength: calculatedMaxMatchLength
};
setField('decomposedRegexes', decomposedRegexes);
}
}
} catch (error) {
console.error('Error testing decomposed regex:', error);
// Check if cancelled before error state update
if (!cancelled) {
setRegexGeneratedOutputErrors((prev) => {
const updated = [...prev];
// @ts-ignore
updated[index] = 'Error: ' + error;
return updated;
});
}
}
})
);
// Only update if not cancelled
if (!cancelled) {
setIsGeneratingFields(false);
}
};
generateRegexOutputs();
// Cleanup function to set cancelled flag
return () => {
cancelled = true;
};
}, [emlContent, decomposedRegexesKey]);
console.log(store.decomposedRegexes, 'store.decomposedRegexes');
const handleGenerateFields = async (index: number) => {
const updatedIsGeneratingFieldsLoading = [...isGeneratingFieldsLoading];
updatedIsGeneratingFieldsLoading[index] = true;
setIsGeneratingFieldsLoading(updatedIsGeneratingFieldsLoading);
if (!emlContent || !aiPrompts[index]) {
toast.error('Please provide both an email file and extraction goals');
updatedIsGeneratingFieldsLoading[index] = false;
setIsGeneratingFieldsLoading(updatedIsGeneratingFieldsLoading);
return;
}
if (!optOut) {
posthog.capture('$generate_fields_using_ai', { aiPrompt: aiPrompts[index] });
}
try {
const formData = new FormData();
formData.append('emlFile', emlContent);
formData.append('extractionGoals', aiPrompts[index]);
const response = await fetch('/api/generateBlueprintFields', {
method: 'POST',
body: formData,
});
if (!response.ok) {
throw new Error('Failed to generate fields');
}
const data = await response.json();
const updatedRegexes = [...store.decomposedRegexes];
updatedRegexes[index] = {
name: data[0].name,
location: data[0].location === 'body' ? 'body' : 'header',
parts: data[0].parts,
maxLength: calculateMaxLength(data[0].parts),
maxMatchLength: calculateMaxMatchLength(data[0].parts),
};
setField('decomposedRegexes', updatedRegexes);
if (!optOut) {
posthog.capture('$generate_fields_using_ai_success', {
aiPrompt: aiPrompts[index],
convertedRegexes: data,
});
}
toast.success('Successfully generated fields');
} catch (error) {
console.error('Error generating fields:', error);
if (!optOut) {
posthog.capture('$generate_fields_using_ai_error', { aiPrompt: aiPrompts[index] });
}
toast.error('Failed to generate fields');
} finally {
updatedIsGeneratingFieldsLoading[index] = false;
setIsGeneratingFieldsLoading(updatedIsGeneratingFieldsLoading);
// handleTestEmail();
}
};
return (
<div className="flex flex-col gap-6">
{/* Decomposed Regexes */}
<div className="flex flex-col gap-5">
<div className="flex flex-col items-center justify-between">
<div className="mb-4 w-full overflow-hidden rounded-lg">
<div className="flex items-center justify-between py-3">
<div className="flex flex-col gap-1">
<Label className="font-medium text-grey-900">Quick header extraction</Label>
<p className="text-base font-medium text-grey-700">
We auto-write the regexes for all the toggled fields
</p>
</div>
</div>
<div className="flex flex-col">
<div className="flex justify-between rounded-md px-3 py-2">
<div className="flex items-center gap-2">
<button
onClick={() => {
const checked = !isExtractSubjectChecked;
setIsExtractSubjectChecked(checked);
if (checked) {
const subjectParts = [
{
isPublic: false,
regexDef: '(?:\\r\\n|^)subject:',
},
{
isPublic: true,
regexDef: '[^\\r\\n]+',
maxLength: 64,
},
{
isPublic: false,
regexDef: '\\r\\n',
},
];
const subjectRegex: DecomposedRegex = {
name: 'subject',
location: 'header',
parts: subjectParts,
maxLength: calculateMaxLength(subjectParts),
maxMatchLength: calculateMaxMatchLength(subjectParts),
};
setField('decomposedRegexes', [
...(store.decomposedRegexes ?? []),
subjectRegex,
]);
} else {
// Remove the subject regex when unchecked
const filtered = store.decomposedRegexes?.filter(r => r.name !== 'subject') ?? [];
setField('decomposedRegexes', filtered);
}
}}
className="cursor-pointer"
>
<Image
src={
isExtractSubjectChecked ? '/assets/AddField.svg' : '/assets/removeField.svg'
}
alt="toggle subject"
width={16}
height={16}
style={{
maxWidth: '100%',
height: 'auto',
}}
/>
</button>
<span className="text-base font-medium text-grey-900">Subject</span>
</div>
</div>
<div className="flex justify-between rounded-md px-3 py-2">
<div className="flex items-center gap-2">
<button
onClick={() => {
const checked = !isExtractReceiverChecked;
setIsExtractReceiverChecked(checked);
if (checked) {
const receiverParts = [
{
isPublic: false,
regexDef: '(?:\\r\\n|^)to:',
},
{
isPublic: false,
regexDef: '(?:[^\\r\\n]+<)?',
},
{
isPublic: true,
regexDef:
'[a-zA-Z0-9!#$%&\\*\\+-/=\\\\?\\\\^_`{\\\\|}~\\\\.]+@[a-zA-Z0-9_\\\\\.-]+',
maxLength: 64,
},
{
isPublic: false,
regexDef: '>?\\r\\n',
},
];
const receiverRegex: DecomposedRegex = {
name: 'email_recipient',
parts: receiverParts,
location: 'header',
maxLength: calculateMaxLength(receiverParts),
maxMatchLength: calculateMaxMatchLength(receiverParts),
};
setField('decomposedRegexes', [
...(store.decomposedRegexes ?? []),
receiverRegex,
]);
} else {
// Remove the email_recipient regex when unchecked
const filtered = store.decomposedRegexes?.filter(r => r.name !== 'email_recipient') ?? [];
setField('decomposedRegexes', filtered);
}
}}
className="cursor-pointer"
>
<Image
src={
isExtractReceiverChecked
? '/assets/AddField.svg'
: '/assets/removeField.svg'
}
alt="toggle receiver"
width={16}
height={16}
style={{
maxWidth: '100%',
height: 'auto',
}}
/>
</button>
<span className="text-base font-medium text-grey-900">To field</span>
</div>
</div>
<div className="flex justify-between rounded-md px-3 py-2">
<div className="flex items-center gap-2">
<button
onClick={() => {
const checked = !isExtractSenderNameChecked;
setIsExtractSenderNameChecked(checked);
if (checked) {
const senderNameParts = [
{
isPublic: false,
regexDef: '(?:\\r\\n|^)from:',
},
{
isPublic: false,
regexDef: '(?:[^\\r\\n]+<)?',
},
{
isPublic: true,
regexDef:
"[A-Za-z0-9!#$%&'\\*\\+\\-/=\\?\\^_`{\\|}~\\.]+@[A-Za-z0-9\\.-]+",
maxLength: 64,
},
{
isPublic: false,
regexDef: '>?\\r\\n',
},
];
const senderNameRegex: DecomposedRegex = {
name: 'email_sender',
parts: senderNameParts,
location: 'header',
maxLength: calculateMaxLength(senderNameParts),
maxMatchLength: calculateMaxMatchLength(senderNameParts),
};
setField('decomposedRegexes', [
...(store.decomposedRegexes ?? []),
senderNameRegex,
]);
} else {
// Remove the email_sender regex when unchecked
const filtered = store.decomposedRegexes?.filter(r => r.name !== 'email_sender') ?? [];
setField('decomposedRegexes', filtered);
}
}}
className="cursor-pointer"
>
<Image
src={
isExtractSenderNameChecked
? '/assets/AddField.svg'
: '/assets/removeField.svg'
}
alt="toggle sender"
width={16}
height={16}
style={{
maxWidth: '100%',
height: 'auto',
}}
/>
</button>
<span className="text-base font-medium text-grey-900">Sender email</span>
</div>
</div>
<div className="flex justify-between rounded-md px-3 py-2">
<div className="flex items-center gap-2">
<button
onClick={() => {
const checked = !isExtractSenderDomainChecked;
setIsExtractSenderDomainChecked(checked);
if (checked) {
const senderDomainParts = [
{
isPublic: false,
regexDef: '(?:\\r\\n|^)from:[^\\r\\n]*@',
},
{
isPublic: true,
regexDef: '[A-Za-z0-9][A-Za-z0-9\\.-]+',
maxLength: 64,
},
{
isPublic: false,
regexDef: '[>\\r\\n]',
},
];
const senderDomainRegex: DecomposedRegex = {
name: 'sender_domain',
parts: senderDomainParts,
location: 'header',
maxLength: calculateMaxLength(senderDomainParts),
maxMatchLength: calculateMaxMatchLength(senderDomainParts),
};
setField('decomposedRegexes', [
...(store.decomposedRegexes ?? []),
senderDomainRegex,
]);
} else {
// Remove the sender_domain regex when unchecked
const filtered = store.decomposedRegexes?.filter(r => r.name !== 'sender_domain') ?? [];
setField('decomposedRegexes', filtered);
}
}}
className="cursor-pointer"
>
<Image
src={
isExtractSenderDomainChecked
? '/assets/AddField.svg'
: '/assets/removeField.svg'
}
alt="toggle domain"
width={16}
height={16}
style={{
maxWidth: '100%',
height: 'auto',
}}
/>
</button>
<span className="text-base font-medium text-grey-900">Sender domain</span>
</div>
</div>
<div className="flex justify-between rounded-md px-3 py-2">
<div className="flex items-center gap-2">
<button
onClick={() => {
const checked = !isExtractTimestampChecked;
setIsExtractTimestampChecked(checked);
if (checked) {
const timestampParts = [
{
isPublic: false,
regexDef: '(?:\\r\\n|^)dkim-signature:',
},
{
isPublic: false,
regexDef: '(?:[a-z]+=[^;]+; )+t=',
},
{
isPublic: true,
regexDef: '[0-9]+',
maxLength: 64,
},
{
isPublic: false,
regexDef: ';',
},
];
const timestampRegex: DecomposedRegex = {
name: 'email_timestamp',
parts: timestampParts,
location: 'header',
maxLength: calculateMaxLength(timestampParts),
maxMatchLength: calculateMaxMatchLength(timestampParts),
};
setField('decomposedRegexes', [
...(store.decomposedRegexes ?? []),
timestampRegex,
]);
} else {
// Remove the email_timestamp regex when unchecked
const filtered = store.decomposedRegexes?.filter(r => r.name !== 'email_timestamp') ?? [];
setField('decomposedRegexes', filtered);
}
}}
className="cursor-pointer"
>
<Image
src={
isExtractTimestampChecked
? '/assets/AddField.svg'
: '/assets/removeField.svg'
}
alt="toggle timestamp"
width={16}
height={16}
style={{
maxWidth: '100%',
height: 'auto',
}}
/>
</button>
<span className="text-base font-medium text-grey-900">Timestamp</span>
</div>
</div>
</div>
</div>
{store?.decomposedRegexes?.length === 0 ? (
<Button
variant="default"
size="sm"
className="ml-auto"
startIcon={
<Image
src="/assets/Plus.svg"
alt="plus"
width={16}
height={16}
style={{
maxWidth: '100%',
height: 'auto',
}}
/>
}
onClick={() => {
if (!optOut) {
posthog.capture('$add_values_to_extract_decomposed_regex');
}
setField('decomposedRegexes', [
...(store.decomposedRegexes ?? []),
{ maxLength: 64, location: 'header', maxMatchLength: 16, parts: [] },
]);
}}
>
Add values to extract
</Button>
) : null}
</div>
{store.decomposedRegexes?.map((regex: DecomposedRegex, index: number) => {
return (
<div key={index} className="mb-2 flex flex-col gap-3 px-1">
<div className="flex items-center justify-between py-3 pb-1">
<div className="flex items-center gap-2">
<Label className="font-medium">Extracted data #{index + 1}</Label>
</div>
<Button
size="sm"
variant="destructive"
startIcon={
<Image
src="/assets/Trash.svg"
alt="trash"
width={16}
height={16}
style={{
maxWidth: '100%',
height: 'auto',
}}
/>
}
onClick={() => {
const updatedRegexes = [...store.decomposedRegexes];
updatedRegexes.splice(index, 1);
const updatedAiPrompts = aiPrompts.filter((_, i) => i !== index);
setAiPrompts(updatedAiPrompts);
setField('decomposedRegexes', updatedRegexes);
setRegexGeneratedOutputs(regexGeneratedOutputs.filter((_, i) => i !== index));
setRegexGeneratedOutputErrors(
regexGeneratedOutputErrors.filter((_, i) => i !== index)
);
}}
>
Delete
</Button>
</div>
<div className="flex flex-col gap-3 px-4 py-3">
<Input
title="Data Name"
placeholder="receiverName"
value={regex.name}
onChange={(e) => {
const updatedRegexes = [...store.decomposedRegexes];
updatedRegexes[index] = { ...regex, name: e.target.value };
setField('decomposedRegexes', updatedRegexes);
}}
/>
<Select
label="Data Location"
value={regex.location}
onChange={(value: string) => {
const updatedRegexes = [...store.decomposedRegexes];
updatedRegexes[index] = { ...regex, location: value as 'body' | 'header' };
setField('decomposedRegexes', updatedRegexes);
}}
options={[
{ label: 'Email Body', value: 'body' },
{ label: 'Email Header', value: 'header' },
]}
/>
<Checkbox
title="Hash Public Output"
checked={regex.isHashed}
onCheckedChange={(checked: boolean) => {
const updatedRegexes = [...store.decomposedRegexes];
updatedRegexes[index] = { ...regex, isHashed: checked };
setField('decomposedRegexes', updatedRegexes);
}}
/>
</div>
<div className="flex flex-col gap-3 rounded-xl border border-grey-500 p-4">