@asteby/metacore-runtime-react 49.13.0 → 50.0.0
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.
- package/CHANGELOG.md +23 -0
- package/dist/dialogs/dynamic-record.d.ts +41 -0
- package/dist/dialogs/dynamic-record.d.ts.map +1 -1
- package/dist/dialogs/dynamic-record.js +134 -11
- package/dist/dialogs/types.d.ts +5 -0
- package/dist/dialogs/types.d.ts.map +1 -1
- package/dist/icon-picker-field.d.ts +8 -1
- package/dist/icon-picker-field.d.ts.map +1 -1
- package/dist/icon-picker-field.js +8 -4
- package/dist/types.d.ts +6 -0
- package/dist/types.d.ts.map +1 -1
- package/dist/upload-field.d.ts +21 -0
- package/dist/upload-field.d.ts.map +1 -1
- package/dist/upload-field.js +51 -3
- package/package.json +3 -3
- package/src/__tests__/dynamic-record-edit-payload-upload.test.tsx +231 -0
- package/src/__tests__/dynamic-record-texts.test.tsx +75 -0
- package/src/__tests__/icon-picker-icon-only.test.tsx +49 -0
- package/src/dialogs/dynamic-record.tsx +224 -35
- package/src/dialogs/types.ts +5 -0
- package/src/icon-picker-field.tsx +27 -4
- package/src/types.ts +6 -0
- package/src/upload-field.tsx +57 -3
package/dist/upload-field.js
CHANGED
|
@@ -45,6 +45,39 @@ export function uploadedDisplayName(value) {
|
|
|
45
45
|
const parts = cleaned.split('/');
|
|
46
46
|
return parts[parts.length - 1] || cleaned;
|
|
47
47
|
}
|
|
48
|
+
/**
|
|
49
|
+
* True when `file` satisfies an HTML-style accept list (`"image/*,.pdf,image/png"`).
|
|
50
|
+
* Tokens: `type/*` (prefix), `type/sub` (exact MIME) and `.ext` (filename suffix),
|
|
51
|
+
* case-insensitive. An empty/absent list accepts everything. Pure — exported for tests.
|
|
52
|
+
*/
|
|
53
|
+
export function fileMatchesAccept(file, accept) {
|
|
54
|
+
const tokens = (accept ?? '')
|
|
55
|
+
.split(',')
|
|
56
|
+
.map((x) => x.trim().toLowerCase())
|
|
57
|
+
.filter(Boolean);
|
|
58
|
+
if (tokens.length === 0)
|
|
59
|
+
return true;
|
|
60
|
+
const name = (file.name || '').toLowerCase();
|
|
61
|
+
const type = (file.type || '').toLowerCase();
|
|
62
|
+
return tokens.some((tok) => {
|
|
63
|
+
if (tok.startsWith('.'))
|
|
64
|
+
return name.endsWith(tok);
|
|
65
|
+
if (tok.endsWith('/*'))
|
|
66
|
+
return type.startsWith(tok.slice(0, -1));
|
|
67
|
+
return type === tok;
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Client-side gate shared by the upload widgets: `'type'` when the file does not
|
|
72
|
+
* match `accept`, `'size'` when it exceeds `maxSize` (bytes), else null. Pure.
|
|
73
|
+
*/
|
|
74
|
+
export function validateUploadFile(file, opts) {
|
|
75
|
+
if (!fileMatchesAccept(file, opts.accept))
|
|
76
|
+
return 'type';
|
|
77
|
+
if (opts.maxSize && file.size > opts.maxSize)
|
|
78
|
+
return 'size';
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
48
81
|
export function UploadField({ field, value, onChange }) {
|
|
49
82
|
const { t } = useTranslation();
|
|
50
83
|
const api = useApi();
|
|
@@ -60,7 +93,14 @@ export function UploadField({ field, value, onChange }) {
|
|
|
60
93
|
return;
|
|
61
94
|
}
|
|
62
95
|
setError(null);
|
|
63
|
-
|
|
96
|
+
const rejected = validateUploadFile(file, { accept, maxSize });
|
|
97
|
+
if (rejected === 'type') {
|
|
98
|
+
setError(t('common.upload.invalid_type', {
|
|
99
|
+
defaultValue: 'File type not allowed.',
|
|
100
|
+
}));
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
if (rejected === 'size' && maxSize) {
|
|
64
104
|
const mb = (maxSize / (1024 * 1024)).toFixed(1);
|
|
65
105
|
setError(t('common.upload.too_large', {
|
|
66
106
|
mb,
|
|
@@ -105,6 +145,14 @@ export function UploadField({ field, value, onChange }) {
|
|
|
105
145
|
finally {
|
|
106
146
|
setUploading(false);
|
|
107
147
|
}
|
|
108
|
-
}, [api, endpoint, maxSize, storagePath, onChange, t]);
|
|
109
|
-
return (_jsxs("div", { className: "grid gap-1.5", "data-widget": "upload",
|
|
148
|
+
}, [api, endpoint, accept, maxSize, storagePath, onChange, t]);
|
|
149
|
+
return (_jsxs("div", { className: "grid gap-1.5", "data-widget": "upload", onDragOver: (e) => {
|
|
150
|
+
e.preventDefault();
|
|
151
|
+
}, onDrop: (e) => {
|
|
152
|
+
e.preventDefault();
|
|
153
|
+
const dropped = e.dataTransfer?.files?.[0];
|
|
154
|
+
if (!dropped || uploading)
|
|
155
|
+
return;
|
|
156
|
+
void handleFile(dropped);
|
|
157
|
+
}, children: [_jsx(FilePickButton, { id: field.key, accept: accept, loading: uploading, hasFile: hasValue, fileName: hasValue ? uploadedDisplayName(value) : undefined, onFile: (f) => void handleFile(f), pickLabel: field.placeholder || undefined }), error && (_jsx("span", { className: "text-sm text-destructive", role: "alert", children: error }))] }));
|
|
110
158
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@asteby/metacore-runtime-react",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "50.0.0",
|
|
4
4
|
"description": "React runtime for metacore hosts — renders addon contributions dynamically",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -27,7 +27,7 @@
|
|
|
27
27
|
},
|
|
28
28
|
"peerDependencies": {
|
|
29
29
|
"@asteby/metacore-sdk": "^3.14.0",
|
|
30
|
-
"@asteby/metacore-ui": "^2.
|
|
30
|
+
"@asteby/metacore-ui": "^2.25.0",
|
|
31
31
|
"@tanstack/react-query": ">=5",
|
|
32
32
|
"@tanstack/react-router": ">=1.100",
|
|
33
33
|
"@tanstack/react-table": ">=8",
|
|
@@ -51,7 +51,7 @@
|
|
|
51
51
|
},
|
|
52
52
|
"devDependencies": {
|
|
53
53
|
"@asteby/metacore-sdk": "3.14.0",
|
|
54
|
-
"@asteby/metacore-ui": "2.
|
|
54
|
+
"@asteby/metacore-ui": "2.25.0",
|
|
55
55
|
"@tanstack/react-query": "^5.95.0",
|
|
56
56
|
"@tanstack/react-router": "^1.168.0",
|
|
57
57
|
"@tanstack/react-table": "^8.20.0",
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
// @vitest-environment happy-dom
|
|
2
|
+
//
|
|
3
|
+
// DynamicRecordDialog: `editPayload: 'declared'`, client-side upload validation
|
|
4
|
+
// (`maxSize` / `accept`) for `file` and `image` fields, and `deriveFrom` slugs.
|
|
5
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
|
6
|
+
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
|
7
|
+
import { I18nextProvider } from 'react-i18next'
|
|
8
|
+
import i18next from 'i18next'
|
|
9
|
+
|
|
10
|
+
import { DynamicRecordDialog, pickDeclaredFieldValues, slugify } from '../dialogs/dynamic-record'
|
|
11
|
+
import { fileMatchesAccept, validateUploadFile } from '../upload-field'
|
|
12
|
+
import { ApiProvider } from '../api-context'
|
|
13
|
+
import { toast } from 'sonner'
|
|
14
|
+
|
|
15
|
+
vi.mock('sonner', () => ({ toast: { error: vi.fn(), success: vi.fn() } }))
|
|
16
|
+
|
|
17
|
+
const i18n = (() => {
|
|
18
|
+
const inst = i18next.createInstance()
|
|
19
|
+
void inst.init({
|
|
20
|
+
lng: 'es',
|
|
21
|
+
fallbackLng: 'es',
|
|
22
|
+
react: { useSuspense: false },
|
|
23
|
+
resources: { es: { translation: {} } },
|
|
24
|
+
})
|
|
25
|
+
return inst
|
|
26
|
+
})()
|
|
27
|
+
|
|
28
|
+
const post = vi.fn(async (..._a: unknown[]) => ({ data: { data: { url: '/files/x.png' } } }))
|
|
29
|
+
const api = {
|
|
30
|
+
get: vi.fn(async () => ({ data: { data: {} } })),
|
|
31
|
+
post,
|
|
32
|
+
put: async () => ({ data: { success: true } }),
|
|
33
|
+
delete: async () => ({ data: { success: true } }),
|
|
34
|
+
} as never
|
|
35
|
+
|
|
36
|
+
beforeEach(() => {
|
|
37
|
+
post.mockClear()
|
|
38
|
+
vi.mocked(toast.error).mockClear()
|
|
39
|
+
})
|
|
40
|
+
afterEach(() => cleanup())
|
|
41
|
+
|
|
42
|
+
function renderDialog(schema: Record<string, unknown>, props: Record<string, unknown>) {
|
|
43
|
+
return render(
|
|
44
|
+
<I18nextProvider i18n={i18n}>
|
|
45
|
+
<ApiProvider client={api}>
|
|
46
|
+
<DynamicRecordDialog
|
|
47
|
+
open
|
|
48
|
+
onOpenChange={() => {}}
|
|
49
|
+
model="reviews"
|
|
50
|
+
schema={{ title: 'Reseña', ...schema } as never}
|
|
51
|
+
{...(props as object)}
|
|
52
|
+
/>
|
|
53
|
+
</ApiProvider>
|
|
54
|
+
</I18nextProvider>,
|
|
55
|
+
)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const inputOf = (label: string) => {
|
|
59
|
+
const el = screen.getByText(label).closest('div')?.parentElement?.querySelector('input')
|
|
60
|
+
if (!el) throw new Error(`no input for ${label}`)
|
|
61
|
+
return el as HTMLInputElement
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const reviewFields = [
|
|
65
|
+
{ key: 'rating', label: 'Calificación', type: 'text' },
|
|
66
|
+
{ key: 'comment', label: 'Comentario', type: 'text' },
|
|
67
|
+
]
|
|
68
|
+
const record = { id: 7, rating: '5', comment: 'Bien', user_id: 3, approved: true }
|
|
69
|
+
|
|
70
|
+
describe('editPayload', () => {
|
|
71
|
+
it("'declared' sends only declared keys and '' for an emptied field", async () => {
|
|
72
|
+
const onUpdate = vi.fn(async () => undefined)
|
|
73
|
+
renderDialog({ fields: reviewFields, editPayload: 'declared' }, {
|
|
74
|
+
mode: 'edit', recordId: '7', onUpdate, initialRecord: record,
|
|
75
|
+
})
|
|
76
|
+
await waitFor(() => expect(screen.getByText('Comentario')).toBeTruthy())
|
|
77
|
+
fireEvent.change(inputOf('Comentario'), { target: { value: '' } })
|
|
78
|
+
fireEvent.click(screen.getByRole('button', { name: /Guardar|Actualizar/ }))
|
|
79
|
+
await waitFor(() => expect(onUpdate).toHaveBeenCalled())
|
|
80
|
+
const [id, payload] = onUpdate.mock.calls[0] as unknown as [string, Record<string, unknown>]
|
|
81
|
+
expect(id).toBe('7')
|
|
82
|
+
expect(payload).toEqual({ rating: '5', comment: '' })
|
|
83
|
+
})
|
|
84
|
+
|
|
85
|
+
it("default ('all') behaves as before: every form value", async () => {
|
|
86
|
+
const onUpdate = vi.fn(async () => undefined)
|
|
87
|
+
renderDialog({ fields: reviewFields }, {
|
|
88
|
+
mode: 'edit', recordId: '7', onUpdate, initialRecord: record,
|
|
89
|
+
})
|
|
90
|
+
await waitFor(() => expect(screen.getByText('Comentario')).toBeTruthy())
|
|
91
|
+
fireEvent.click(screen.getByRole('button', { name: /Guardar|Actualizar/ }))
|
|
92
|
+
await waitFor(() => expect(onUpdate).toHaveBeenCalled())
|
|
93
|
+
const payload = (onUpdate.mock.calls[0] as unknown[])[1] as Record<string, unknown>
|
|
94
|
+
expect(payload).toEqual({ rating: '5', comment: 'Bien' })
|
|
95
|
+
})
|
|
96
|
+
|
|
97
|
+
it('pickDeclaredFieldValues drops undeclared keys', () => {
|
|
98
|
+
expect(
|
|
99
|
+
pickDeclaredFieldValues({ a: 1, b: null, extra: 'x' }, [
|
|
100
|
+
{ key: 'a', label: 'A', type: 'text' },
|
|
101
|
+
{ key: 'b', label: 'B', type: 'text' },
|
|
102
|
+
{ key: 'c', label: 'C', type: 'text' },
|
|
103
|
+
]),
|
|
104
|
+
).toEqual({ a: 1, b: '', c: '' })
|
|
105
|
+
})
|
|
106
|
+
})
|
|
107
|
+
|
|
108
|
+
describe('upload validation', () => {
|
|
109
|
+
const png = (size: number, type = 'image/png', name = 'a.png') => {
|
|
110
|
+
const f = new File(['x'], name, { type })
|
|
111
|
+
Object.defineProperty(f, 'size', { value: size })
|
|
112
|
+
return f
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
it('helpers match accept lists and sizes', () => {
|
|
116
|
+
expect(fileMatchesAccept({ name: 'a.png', type: 'image/png' }, 'image/*')).toBe(true)
|
|
117
|
+
expect(fileMatchesAccept({ name: 'a.pdf', type: 'application/pdf' }, 'image/*,.pdf')).toBe(true)
|
|
118
|
+
expect(fileMatchesAccept({ name: 'a.gif', type: 'image/gif' }, 'image/png')).toBe(false)
|
|
119
|
+
expect(fileMatchesAccept({ name: 'a.gif', type: 'image/gif' }, undefined)).toBe(true)
|
|
120
|
+
expect(validateUploadFile({ name: 'a', type: 'image/png', size: 10 }, { maxSize: 5 })).toBe('size')
|
|
121
|
+
})
|
|
122
|
+
|
|
123
|
+
it('image: oversized file is rejected without calling /upload', async () => {
|
|
124
|
+
renderDialog({ fields: [{ key: 'logo', label: 'Logo', type: 'image', maxSize: 1024 }] }, { mode: 'create' })
|
|
125
|
+
await waitFor(() => expect(screen.getByText('Logo')).toBeTruthy())
|
|
126
|
+
const input = document.querySelector('input[type="file"]') as HTMLInputElement
|
|
127
|
+
fireEvent.change(input, { target: { files: [png(5000)] } })
|
|
128
|
+
await waitFor(() => expect(screen.getByRole('alert')).toBeTruthy())
|
|
129
|
+
expect(post).not.toHaveBeenCalled()
|
|
130
|
+
expect(toast.error).toHaveBeenCalled()
|
|
131
|
+
})
|
|
132
|
+
|
|
133
|
+
it('image: invalid MIME is rejected, also via drop', async () => {
|
|
134
|
+
renderDialog({ fields: [{ key: 'logo', label: 'Logo', type: 'image', accept: 'image/png' }] }, { mode: 'create' })
|
|
135
|
+
await waitFor(() => expect(screen.getByText('Logo')).toBeTruthy())
|
|
136
|
+
const zone = document.querySelector('input[type="file"]')!.parentElement as HTMLElement
|
|
137
|
+
fireEvent.drop(zone, { dataTransfer: { files: [png(10, 'image/gif', 'a.gif')] } })
|
|
138
|
+
await waitFor(() => expect(screen.getByRole('alert')).toBeTruthy())
|
|
139
|
+
expect(post).not.toHaveBeenCalled()
|
|
140
|
+
})
|
|
141
|
+
|
|
142
|
+
it('image: drop/dragover call preventDefault even with a value or while uploading', async () => {
|
|
143
|
+
renderDialog({ fields: [{ key: 'logo', label: 'Logo', type: 'image' }] }, {
|
|
144
|
+
mode: 'edit', recordId: '1', initialRecord: { id: 1, logo: '/files/a.png' },
|
|
145
|
+
})
|
|
146
|
+
await waitFor(() => expect(screen.getByText('Logo')).toBeTruthy())
|
|
147
|
+
const zone = document.querySelector('input[type="file"]')!.parentElement as HTMLElement
|
|
148
|
+
expect(zone.querySelector('img')).toBeTruthy()
|
|
149
|
+
const over = new Event('dragover', { bubbles: true, cancelable: true })
|
|
150
|
+
zone.dispatchEvent(over)
|
|
151
|
+
expect(over.defaultPrevented).toBe(true)
|
|
152
|
+
const drop = new Event('drop', { bubbles: true, cancelable: true })
|
|
153
|
+
Object.defineProperty(drop, 'dataTransfer', { value: { files: [png(10)] } })
|
|
154
|
+
zone.dispatchEvent(drop)
|
|
155
|
+
expect(drop.defaultPrevented).toBe(true)
|
|
156
|
+
expect(post.mock.calls.some((c) => c[0] === '/upload')).toBe(false)
|
|
157
|
+
})
|
|
158
|
+
|
|
159
|
+
it('image: input value is reset after a rejection so the same file can be re-picked', async () => {
|
|
160
|
+
renderDialog({ fields: [{ key: 'logo', label: 'Logo', type: 'image', maxSize: 1024 }] }, { mode: 'create' })
|
|
161
|
+
await waitFor(() => expect(screen.getByText('Logo')).toBeTruthy())
|
|
162
|
+
const input = document.querySelector('input[type="file"]') as HTMLInputElement
|
|
163
|
+
const spy = vi.spyOn(input, 'value', 'set')
|
|
164
|
+
fireEvent.change(input, { target: { files: [png(5000)] } })
|
|
165
|
+
await waitFor(() => expect(screen.getByRole('alert')).toBeTruthy())
|
|
166
|
+
expect(spy).toHaveBeenCalledWith('')
|
|
167
|
+
})
|
|
168
|
+
|
|
169
|
+
it('image: valid file uploads as before; no options = unchanged (accept image/*)', async () => {
|
|
170
|
+
renderDialog({ fields: [{ key: 'logo', label: 'Logo', type: 'image' }] }, { mode: 'create' })
|
|
171
|
+
await waitFor(() => expect(screen.getByText('Logo')).toBeTruthy())
|
|
172
|
+
const input = document.querySelector('input[type="file"]') as HTMLInputElement
|
|
173
|
+
expect(input.accept).toBe('image/*')
|
|
174
|
+
fireEvent.change(input, { target: { files: [png(10_000_000)] } })
|
|
175
|
+
await waitFor(() => expect(post).toHaveBeenCalledTimes(1))
|
|
176
|
+
const call = post.mock.calls[0] as unknown[]
|
|
177
|
+
expect(call[0]).toBe('/upload')
|
|
178
|
+
expect((call[1] as FormData).get('folder')).toBe('reviews')
|
|
179
|
+
})
|
|
180
|
+
|
|
181
|
+
it('file: invalid type is rejected without calling /upload; valid uploads', async () => {
|
|
182
|
+
renderDialog({ fields: [{ key: 'doc', label: 'Doc', type: 'file', accept: 'image/png', maxSize: 1024 }] }, { mode: 'create' })
|
|
183
|
+
await waitFor(() => expect(screen.getByText('Doc')).toBeTruthy())
|
|
184
|
+
const input = document.querySelector('input[type="file"]') as HTMLInputElement
|
|
185
|
+
fireEvent.change(input, { target: { files: [png(10, 'image/gif', 'a.gif')] } })
|
|
186
|
+
await waitFor(() => expect(screen.getByRole('alert')).toBeTruthy())
|
|
187
|
+
expect(post).not.toHaveBeenCalled()
|
|
188
|
+
fireEvent.change(input, { target: { files: [png(10)] } })
|
|
189
|
+
await waitFor(() => expect(post).toHaveBeenCalledTimes(1))
|
|
190
|
+
})
|
|
191
|
+
})
|
|
192
|
+
|
|
193
|
+
describe('deriveFrom slug', () => {
|
|
194
|
+
const fields = [
|
|
195
|
+
{ key: 'name', label: 'Nombre', type: 'text' },
|
|
196
|
+
{ key: 'slug', label: 'Slug', type: 'text', deriveFrom: { field: 'name', transform: 'slug' } },
|
|
197
|
+
]
|
|
198
|
+
|
|
199
|
+
it('slugify', () => {
|
|
200
|
+
expect(slugify('Asociaciones Médicas')).toBe('asociaciones-medicas')
|
|
201
|
+
expect(slugify(' ¡Niños & Niñas! ')).toBe('ninos-ninas')
|
|
202
|
+
})
|
|
203
|
+
|
|
204
|
+
it('derives while untouched, stops after a manual edit', async () => {
|
|
205
|
+
renderDialog({ fields }, { mode: 'create' })
|
|
206
|
+
await waitFor(() => expect(screen.getByText('Nombre')).toBeTruthy())
|
|
207
|
+
fireEvent.change(inputOf('Nombre'), { target: { value: 'Asociaciones Médicas' } })
|
|
208
|
+
expect(inputOf('Slug').value).toBe('asociaciones-medicas')
|
|
209
|
+
fireEvent.change(inputOf('Slug'), { target: { value: 'mi-slug' } })
|
|
210
|
+
fireEvent.change(inputOf('Nombre'), { target: { value: 'Otro Nombre' } })
|
|
211
|
+
expect(inputOf('Slug').value).toBe('mi-slug')
|
|
212
|
+
})
|
|
213
|
+
|
|
214
|
+
it('edit: an existing slug equal to slugify(name) is NOT overwritten', async () => {
|
|
215
|
+
renderDialog({ fields }, {
|
|
216
|
+
mode: 'edit', recordId: '1', initialRecord: { id: 1, name: 'Mi Nombre', slug: 'mi-nombre' },
|
|
217
|
+
})
|
|
218
|
+
await waitFor(() => expect(inputOf('Nombre').value).toBe('Mi Nombre'))
|
|
219
|
+
fireEvent.change(inputOf('Nombre'), { target: { value: 'Otro Nombre' } })
|
|
220
|
+
expect(inputOf('Slug').value).toBe('mi-nombre')
|
|
221
|
+
})
|
|
222
|
+
|
|
223
|
+
it('edit: an empty slug is still derived', async () => {
|
|
224
|
+
renderDialog({ fields }, {
|
|
225
|
+
mode: 'edit', recordId: '1', initialRecord: { id: 1, name: 'Mi Nombre', slug: '' },
|
|
226
|
+
})
|
|
227
|
+
await waitFor(() => expect(inputOf('Nombre').value).toBe('Mi Nombre'))
|
|
228
|
+
fireEvent.change(inputOf('Nombre'), { target: { value: 'Otro Nombre' } })
|
|
229
|
+
expect(inputOf('Slug').value).toBe('otro-nombre')
|
|
230
|
+
})
|
|
231
|
+
})
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// @vitest-environment happy-dom
|
|
2
|
+
//
|
|
3
|
+
// DynamicRecordDialog: per-model description / submit label from modal
|
|
4
|
+
// metadata (camelCase + snake_case); without them the generic texts remain.
|
|
5
|
+
import { afterEach, describe, expect, it, vi } from 'vitest'
|
|
6
|
+
import { cleanup, render, screen, waitFor } from '@testing-library/react'
|
|
7
|
+
import { I18nextProvider } from 'react-i18next'
|
|
8
|
+
import i18next from 'i18next'
|
|
9
|
+
|
|
10
|
+
import { DynamicRecordDialog } from '../dialogs/dynamic-record'
|
|
11
|
+
import { ApiProvider } from '../api-context'
|
|
12
|
+
|
|
13
|
+
vi.mock('sonner', () => ({ toast: { error: vi.fn(), success: vi.fn() } }))
|
|
14
|
+
afterEach(cleanup)
|
|
15
|
+
|
|
16
|
+
const i18n = (() => {
|
|
17
|
+
const inst = i18next.createInstance()
|
|
18
|
+
void inst.init({ lng: 'es', fallbackLng: 'es', react: { useSuspense: false }, resources: { es: { translation: {} } } })
|
|
19
|
+
return inst
|
|
20
|
+
})()
|
|
21
|
+
|
|
22
|
+
const api = {
|
|
23
|
+
get: vi.fn(async () => ({ data: { data: {} } })),
|
|
24
|
+
post: vi.fn(),
|
|
25
|
+
put: vi.fn(),
|
|
26
|
+
delete: vi.fn(),
|
|
27
|
+
} as never
|
|
28
|
+
|
|
29
|
+
const base = { title: 'Clínica', fields: [{ key: 'name', label: 'Nombre', type: 'text' }] }
|
|
30
|
+
|
|
31
|
+
function renderDialog(mode: 'create' | 'edit' | 'view', extra: Record<string, unknown>) {
|
|
32
|
+
return render(
|
|
33
|
+
<I18nextProvider i18n={i18n}>
|
|
34
|
+
<ApiProvider client={api}>
|
|
35
|
+
<DynamicRecordDialog
|
|
36
|
+
open
|
|
37
|
+
onOpenChange={() => {}}
|
|
38
|
+
mode={mode}
|
|
39
|
+
model="clinics"
|
|
40
|
+
recordId={mode === 'create' ? undefined : '1'}
|
|
41
|
+
initialRecord={mode === 'create' ? undefined : { id: 1, name: 'A' }}
|
|
42
|
+
schema={{ ...base, ...extra } as never}
|
|
43
|
+
/>
|
|
44
|
+
</ApiProvider>
|
|
45
|
+
</I18nextProvider>,
|
|
46
|
+
)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
describe('DynamicRecordDialog textos por modelo', () => {
|
|
50
|
+
it('create: usa createDescription y createSubmitLabel', async () => {
|
|
51
|
+
renderDialog('create', { createDescription: 'Registra la clínica.', createSubmitLabel: 'Registrar' })
|
|
52
|
+
await waitFor(() => expect(screen.getByText('Registra la clínica.')).toBeTruthy())
|
|
53
|
+
expect(screen.getByRole('button', { name: 'Registrar' })).toBeTruthy()
|
|
54
|
+
expect(screen.queryByText('Completa los campos para crear un nuevo registro.')).toBeNull()
|
|
55
|
+
})
|
|
56
|
+
|
|
57
|
+
it('edit y view: formas snake_case', async () => {
|
|
58
|
+
renderDialog('edit', { edit_description: 'Edita la clínica.', edit_submit_label: 'Actualizar clínica' })
|
|
59
|
+
await waitFor(() => expect(screen.getByText('Edita la clínica.')).toBeTruthy())
|
|
60
|
+
expect(screen.getByRole('button', { name: 'Actualizar clínica' })).toBeTruthy()
|
|
61
|
+
cleanup()
|
|
62
|
+
renderDialog('view', { viewDescription: 'Ficha de la clínica.' })
|
|
63
|
+
await waitFor(() => expect(screen.getByText('Ficha de la clínica.')).toBeTruthy())
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
it('sin opciones: textos genéricos de siempre', async () => {
|
|
67
|
+
renderDialog('create', {})
|
|
68
|
+
await waitFor(() => expect(screen.getByText('Completa los campos para crear un nuevo registro.')).toBeTruthy())
|
|
69
|
+
expect(screen.getByRole('button', { name: 'Crear' })).toBeTruthy()
|
|
70
|
+
cleanup()
|
|
71
|
+
renderDialog('edit', { editDescription: ' ' })
|
|
72
|
+
await waitFor(() => expect(screen.getByText('Modifica los campos y guarda los cambios.')).toBeTruthy())
|
|
73
|
+
expect(screen.getByRole('button', { name: 'Guardar cambios' })).toBeTruthy()
|
|
74
|
+
})
|
|
75
|
+
})
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// @vitest-environment happy-dom
|
|
2
|
+
//
|
|
3
|
+
// IconPickerField `iconOnly`: hides the "Imagen" tab; stored value is always a
|
|
4
|
+
// lucide name; a pre-existing url/path is preserved until cleared/replaced.
|
|
5
|
+
import { afterEach, describe, expect, it, vi } from 'vitest'
|
|
6
|
+
import { cleanup, render, screen, fireEvent } from '@testing-library/react'
|
|
7
|
+
|
|
8
|
+
vi.mock('../upload-field', () => ({
|
|
9
|
+
UploadField: () => <div data-testid="upload-field" />,
|
|
10
|
+
}))
|
|
11
|
+
|
|
12
|
+
import { IconPickerField } from '../icon-picker-field'
|
|
13
|
+
import type { ActionFieldDef } from '../types'
|
|
14
|
+
|
|
15
|
+
afterEach(cleanup)
|
|
16
|
+
|
|
17
|
+
const field: ActionFieldDef = { key: 'icon', label: 'Ícono', type: 'text', widget: 'icon' }
|
|
18
|
+
|
|
19
|
+
describe('IconPickerField iconOnly', () => {
|
|
20
|
+
it('por defecto sigue mostrando la pestaña Imagen', () => {
|
|
21
|
+
render(<IconPickerField field={field} value="" onChange={() => {}} />)
|
|
22
|
+
expect(screen.getByRole('tab', { name: 'Imagen' })).toBeTruthy()
|
|
23
|
+
})
|
|
24
|
+
|
|
25
|
+
it.each([
|
|
26
|
+
['prop', { iconOnly: true }, field],
|
|
27
|
+
['field.iconOnly', {}, { ...field, iconOnly: true }],
|
|
28
|
+
['field.icon_only', {}, { ...field, icon_only: true }],
|
|
29
|
+
])('oculta la pestaña Imagen (%s) y guarda el nombre Lucide', (_n, props, f) => {
|
|
30
|
+
const onChange = vi.fn()
|
|
31
|
+
render(<IconPickerField field={f as ActionFieldDef} value="" onChange={onChange} {...props} />)
|
|
32
|
+
expect(screen.queryByRole('tab')).toBeNull()
|
|
33
|
+
fireEvent.click(screen.getByRole('combobox'))
|
|
34
|
+
fireEvent.change(screen.getByLabelText('Buscar ícono'), { target: { value: 'credit' } })
|
|
35
|
+
fireEvent.click(screen.getByRole('option', { name: 'CreditCard' }))
|
|
36
|
+
expect(onChange).toHaveBeenCalledWith('CreditCard')
|
|
37
|
+
expect(screen.queryByTestId('upload-field')).toBeNull()
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
it('un valor URL existente no se corrompe: se muestra y solo cambia al quitar', () => {
|
|
41
|
+
const onChange = vi.fn()
|
|
42
|
+
render(<IconPickerField field={field} iconOnly value="/uploads/logo.png" onChange={onChange} />)
|
|
43
|
+
expect(onChange).not.toHaveBeenCalled()
|
|
44
|
+
expect(screen.getByTestId('icon-legacy-value').textContent).toContain('/uploads/logo.png')
|
|
45
|
+
expect(screen.queryByTestId('upload-field')).toBeNull()
|
|
46
|
+
fireEvent.click(screen.getByRole('button', { name: 'Quitar' }))
|
|
47
|
+
expect(onChange).toHaveBeenCalledWith('')
|
|
48
|
+
})
|
|
49
|
+
})
|