-
Notifications
You must be signed in to change notification settings - Fork 151
/
Copy pathField.tsx
45 lines (37 loc) · 1.36 KB
/
Field.tsx
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
import { FieldAppSDK } from '@contentful/app-sdk';
import { Note, Stack } from '@contentful/f36-components';
import { useSDK } from '@contentful/react-apps-toolkit';
import { useEffect, useState } from 'react';
import { getEntry, onEntryChanged } from '../utils';
export function Field() {
const sdk = useSDK<FieldAppSDK>();
const [errors, setErrors] = useState<string[]>([]);
useEffect(() => {
sdk.window.startAutoResizer();
return () => sdk.window.stopAutoResizer();
}, []);
useEffect(() => {
return onEntryChanged(sdk, () => {
const entry = getEntry(sdk);
const newErrors: string[] = [];
if ((entry.fields.slug ?? '').startsWith(`${entry.fields.date}-`)) {
sdk.entry.fields['slug'].getForLocale(sdk.locales.default).setInvalid(false);
} else {
sdk.entry.fields['slug'].getForLocale(sdk.locales.default).setInvalid(true);
newErrors.push(`Slug must start with "${entry.fields.date}-"`);
}
setErrors(newErrors);
sdk.field.setValue(newErrors.length === 0 ? 'true' : 'false');
});
}, [sdk]);
return (
<Stack flexDirection="column" alignItems="flex-start">
{errors.length === 0 && <Note variant="positive">Entry is valid</Note>}
{errors.map((error, index) => (
<Note key={index} variant="negative">
{error}
</Note>
))}
</Stack>
);
}