@open-mercato/ui 0.6.6-develop.6205.1.109e4b6a84 → 0.6.6-develop.6228.1.cf483c68b5
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/dist/backend/CrudForm.js +12 -0
- package/dist/backend/CrudForm.js.map +2 -2
- package/dist/backend/notifications/useNotificationActions.js +48 -20
- package/dist/backend/notifications/useNotificationActions.js.map +2 -2
- package/dist/backend/utils/customFieldForms.js +32 -0
- package/dist/backend/utils/customFieldForms.js.map +2 -2
- package/dist/primitives/tag-input.js +6 -2
- package/dist/primitives/tag-input.js.map +2 -2
- package/package.json +3 -3
- package/src/backend/CrudForm.tsx +12 -0
- package/src/backend/__tests__/CrudForm.custom-fields.test.tsx +67 -0
- package/src/backend/__tests__/custom-field-filters.test.ts +12 -0
- package/src/backend/__tests__/custom-field-forms.test.ts +29 -0
- package/src/backend/notifications/__tests__/useNotificationActions.failedWrites.test.tsx +8 -2
- package/src/backend/notifications/__tests__/useNotificationActions.test.tsx +147 -0
- package/src/backend/notifications/useNotificationActions.ts +58 -20
- package/src/backend/utils/customFieldForms.ts +34 -0
- package/src/primitives/__tests__/tag-input.test.tsx +7 -0
- package/src/primitives/tag-input.tsx +11 -1
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import * as React from "react";
|
|
3
3
|
import { apiCall, apiCallOrThrow } from "../utils/apiCall.js";
|
|
4
|
+
import { useGuardedMutation } from "../injection/useGuardedMutation.js";
|
|
5
|
+
import { useT } from "@open-mercato/shared/lib/i18n/context";
|
|
6
|
+
const NOTIFICATION_ACTIONS_CONTEXT_ID = "notifications-actions";
|
|
4
7
|
function useNotificationActions(notifications, setNotifications, setUnreadCount) {
|
|
5
8
|
const markAsReadRef = React.useRef(async () => {
|
|
6
9
|
});
|
|
@@ -8,27 +11,40 @@ function useNotificationActions(notifications, setNotifications, setUnreadCount)
|
|
|
8
11
|
});
|
|
9
12
|
const [dismissUndo, setDismissUndo] = React.useState(null);
|
|
10
13
|
const dismissUndoTimerRef = React.useRef(null);
|
|
14
|
+
const t = useT();
|
|
15
|
+
const { runMutation, retryLastMutation } = useGuardedMutation({
|
|
16
|
+
contextId: NOTIFICATION_ACTIONS_CONTEXT_ID,
|
|
17
|
+
blockedMessage: t("ui.forms.flash.saveBlocked", "Save blocked by validation")
|
|
18
|
+
});
|
|
11
19
|
const markAsRead = React.useCallback(async (id) => {
|
|
12
|
-
await
|
|
20
|
+
await runMutation({
|
|
21
|
+
operation: () => apiCallOrThrow(`/api/notifications/${id}/read`, { method: "PUT" }),
|
|
22
|
+
context: { formId: NOTIFICATION_ACTIONS_CONTEXT_ID, resourceKind: "notification", retryLastMutation },
|
|
23
|
+
mutationPayload: { id }
|
|
24
|
+
});
|
|
13
25
|
setNotifications(
|
|
14
26
|
(prev) => prev.map(
|
|
15
27
|
(n) => n.id === id ? { ...n, status: "read", readAt: (/* @__PURE__ */ new Date()).toISOString() } : n
|
|
16
28
|
)
|
|
17
29
|
);
|
|
18
30
|
setUnreadCount((prev) => Math.max(0, prev - 1));
|
|
19
|
-
}, [setNotifications, setUnreadCount]);
|
|
31
|
+
}, [runMutation, retryLastMutation, setNotifications, setUnreadCount]);
|
|
20
32
|
React.useEffect(() => {
|
|
21
33
|
markAsReadRef.current = markAsRead;
|
|
22
34
|
}, [markAsRead]);
|
|
23
35
|
const executeAction = React.useCallback(async (id, actionId) => {
|
|
24
|
-
const result = await
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
36
|
+
const result = await runMutation({
|
|
37
|
+
operation: () => apiCall(
|
|
38
|
+
`/api/notifications/${id}/action`,
|
|
39
|
+
{
|
|
40
|
+
method: "POST",
|
|
41
|
+
headers: { "content-type": "application/json" },
|
|
42
|
+
body: JSON.stringify({ actionId })
|
|
43
|
+
}
|
|
44
|
+
),
|
|
45
|
+
context: { formId: NOTIFICATION_ACTIONS_CONTEXT_ID, resourceKind: "notification", retryLastMutation },
|
|
46
|
+
mutationPayload: { id, actionId }
|
|
47
|
+
});
|
|
32
48
|
if (result.ok) {
|
|
33
49
|
setNotifications(
|
|
34
50
|
(prev) => prev.map(
|
|
@@ -38,10 +54,14 @@ function useNotificationActions(notifications, setNotifications, setUnreadCount)
|
|
|
38
54
|
setUnreadCount((prev) => Math.max(0, prev - 1));
|
|
39
55
|
}
|
|
40
56
|
return { href: result.result?.href };
|
|
41
|
-
}, [setNotifications, setUnreadCount]);
|
|
57
|
+
}, [runMutation, retryLastMutation, setNotifications, setUnreadCount]);
|
|
42
58
|
const dismiss = React.useCallback(
|
|
43
59
|
async (id) => {
|
|
44
|
-
await
|
|
60
|
+
await runMutation({
|
|
61
|
+
operation: () => apiCallOrThrow(`/api/notifications/${id}/dismiss`, { method: "PUT" }),
|
|
62
|
+
context: { formId: NOTIFICATION_ACTIONS_CONTEXT_ID, resourceKind: "notification", retryLastMutation },
|
|
63
|
+
mutationPayload: { id }
|
|
64
|
+
});
|
|
45
65
|
const notification = notifications.find((n) => n.id === id);
|
|
46
66
|
setNotifications((prev) => prev.filter((n) => n.id !== id));
|
|
47
67
|
if (notification?.status === "unread") {
|
|
@@ -58,17 +78,21 @@ function useNotificationActions(notifications, setNotifications, setUnreadCount)
|
|
|
58
78
|
}, 6e3);
|
|
59
79
|
}
|
|
60
80
|
},
|
|
61
|
-
[notifications, setNotifications, setUnreadCount]
|
|
81
|
+
[notifications, setNotifications, setUnreadCount, runMutation, retryLastMutation]
|
|
62
82
|
);
|
|
63
83
|
React.useEffect(() => {
|
|
64
84
|
dismissRef.current = dismiss;
|
|
65
85
|
}, [dismiss]);
|
|
66
86
|
const undoDismiss = React.useCallback(async () => {
|
|
67
87
|
if (!dismissUndo) return;
|
|
68
|
-
await
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
88
|
+
await runMutation({
|
|
89
|
+
operation: () => apiCallOrThrow(`/api/notifications/${dismissUndo.notification.id}/restore`, {
|
|
90
|
+
method: "PUT",
|
|
91
|
+
headers: { "content-type": "application/json" },
|
|
92
|
+
body: JSON.stringify({ status: dismissUndo.previousStatus })
|
|
93
|
+
}),
|
|
94
|
+
context: { formId: NOTIFICATION_ACTIONS_CONTEXT_ID, resourceKind: "notification", retryLastMutation },
|
|
95
|
+
mutationPayload: { id: dismissUndo.notification.id, status: dismissUndo.previousStatus }
|
|
72
96
|
});
|
|
73
97
|
setNotifications((prev) => {
|
|
74
98
|
const next = [
|
|
@@ -90,16 +114,20 @@ function useNotificationActions(notifications, setNotifications, setUnreadCount)
|
|
|
90
114
|
window.clearTimeout(dismissUndoTimerRef.current);
|
|
91
115
|
}
|
|
92
116
|
setDismissUndo(null);
|
|
93
|
-
}, [dismissUndo, setNotifications, setUnreadCount]);
|
|
117
|
+
}, [dismissUndo, setNotifications, setUnreadCount, runMutation, retryLastMutation]);
|
|
94
118
|
const markAllRead = React.useCallback(async () => {
|
|
95
|
-
await
|
|
119
|
+
await runMutation({
|
|
120
|
+
operation: () => apiCallOrThrow("/api/notifications/mark-all-read", { method: "PUT" }),
|
|
121
|
+
context: { formId: NOTIFICATION_ACTIONS_CONTEXT_ID, resourceKind: "notification", retryLastMutation },
|
|
122
|
+
mutationPayload: {}
|
|
123
|
+
});
|
|
96
124
|
setNotifications(
|
|
97
125
|
(prev) => prev.map(
|
|
98
126
|
(n) => n.status === "unread" ? { ...n, status: "read", readAt: (/* @__PURE__ */ new Date()).toISOString() } : n
|
|
99
127
|
)
|
|
100
128
|
);
|
|
101
129
|
setUnreadCount(0);
|
|
102
|
-
}, [setNotifications, setUnreadCount]);
|
|
130
|
+
}, [runMutation, retryLastMutation, setNotifications, setUnreadCount]);
|
|
103
131
|
React.useEffect(() => {
|
|
104
132
|
return () => {
|
|
105
133
|
if (dismissUndoTimerRef.current) {
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/backend/notifications/useNotificationActions.ts"],
|
|
4
|
-
"sourcesContent": ["\"use client\"\nimport * as React from 'react'\nimport { apiCall, apiCallOrThrow } from '../utils/apiCall'\nimport type { NotificationDto } from '@open-mercato/shared/modules/notifications/types'\n\nexport type NotificationDismissUndoState = {\n notification: NotificationDto\n previousStatus: 'read' | 'unread'\n} | null\n\ntype SetUnreadCount = React.Dispatch<React.SetStateAction<number>>\n\nexport type NotificationActionsResult = {\n markAsRead: (id: string) => Promise<void>\n executeAction: (id: string, actionId: string) => Promise<{ href?: string }>\n dismiss: (id: string) => Promise<void>\n dismissUndo: NotificationDismissUndoState\n undoDismiss: () => Promise<void>\n markAllRead: () => Promise<void>\n markAsReadRef: React.MutableRefObject<(id: string) => Promise<void>>\n dismissRef: React.MutableRefObject<(id: string) => Promise<void>>\n}\n\nexport function useNotificationActions(\n notifications: NotificationDto[],\n setNotifications: React.Dispatch<React.SetStateAction<NotificationDto[]>>,\n setUnreadCount: SetUnreadCount,\n): NotificationActionsResult {\n const markAsReadRef = React.useRef<(id: string) => Promise<void>>(async () => {})\n const dismissRef = React.useRef<(id: string) => Promise<void>>(async () => {})\n const [dismissUndo, setDismissUndo] = React.useState<NotificationDismissUndoState>(null)\n const dismissUndoTimerRef = React.useRef<number | null>(null)\n\n const markAsRead = React.useCallback(async (id: string) => {\n await apiCallOrThrow(`/api/notifications/${id}/read`, { method: 'PUT' })\n setNotifications((prev) =>\n prev.map((n) =>\n n.id === id ? { ...n, status: 'read', readAt: new Date().toISOString() } : n,\n ),\n )\n setUnreadCount((prev) => Math.max(0, prev - 1))\n }, [setNotifications, setUnreadCount])\n\n React.useEffect(() => {\n markAsReadRef.current = markAsRead\n }, [markAsRead])\n\n const executeAction = React.useCallback(async (id: string, actionId: string) => {\n const result = await apiCall<{ ok: boolean; href?: string }>(\n
|
|
5
|
-
"mappings": ";AACA,YAAY,WAAW;AACvB,SAAS,SAAS,sBAAsB;
|
|
4
|
+
"sourcesContent": ["\"use client\"\nimport * as React from 'react'\nimport { apiCall, apiCallOrThrow } from '../utils/apiCall'\nimport { useGuardedMutation } from '../injection/useGuardedMutation'\nimport { useT } from '@open-mercato/shared/lib/i18n/context'\nimport type { NotificationDto } from '@open-mercato/shared/modules/notifications/types'\n\nconst NOTIFICATION_ACTIONS_CONTEXT_ID = 'notifications-actions'\n\ntype NotificationMutationContext = {\n formId: string\n resourceKind: string\n retryLastMutation: () => Promise<boolean>\n}\n\nexport type NotificationDismissUndoState = {\n notification: NotificationDto\n previousStatus: 'read' | 'unread'\n} | null\n\ntype SetUnreadCount = React.Dispatch<React.SetStateAction<number>>\n\nexport type NotificationActionsResult = {\n markAsRead: (id: string) => Promise<void>\n executeAction: (id: string, actionId: string) => Promise<{ href?: string }>\n dismiss: (id: string) => Promise<void>\n dismissUndo: NotificationDismissUndoState\n undoDismiss: () => Promise<void>\n markAllRead: () => Promise<void>\n markAsReadRef: React.MutableRefObject<(id: string) => Promise<void>>\n dismissRef: React.MutableRefObject<(id: string) => Promise<void>>\n}\n\nexport function useNotificationActions(\n notifications: NotificationDto[],\n setNotifications: React.Dispatch<React.SetStateAction<NotificationDto[]>>,\n setUnreadCount: SetUnreadCount,\n): NotificationActionsResult {\n const markAsReadRef = React.useRef<(id: string) => Promise<void>>(async () => {})\n const dismissRef = React.useRef<(id: string) => Promise<void>>(async () => {})\n const [dismissUndo, setDismissUndo] = React.useState<NotificationDismissUndoState>(null)\n const dismissUndoTimerRef = React.useRef<number | null>(null)\n\n const t = useT()\n const { runMutation, retryLastMutation } = useGuardedMutation<NotificationMutationContext>({\n contextId: NOTIFICATION_ACTIONS_CONTEXT_ID,\n blockedMessage: t('ui.forms.flash.saveBlocked', 'Save blocked by validation'),\n })\n\n const markAsRead = React.useCallback(async (id: string) => {\n await runMutation({\n operation: () => apiCallOrThrow(`/api/notifications/${id}/read`, { method: 'PUT' }),\n context: { formId: NOTIFICATION_ACTIONS_CONTEXT_ID, resourceKind: 'notification', retryLastMutation },\n mutationPayload: { id },\n })\n setNotifications((prev) =>\n prev.map((n) =>\n n.id === id ? { ...n, status: 'read', readAt: new Date().toISOString() } : n,\n ),\n )\n setUnreadCount((prev) => Math.max(0, prev - 1))\n }, [runMutation, retryLastMutation, setNotifications, setUnreadCount])\n\n React.useEffect(() => {\n markAsReadRef.current = markAsRead\n }, [markAsRead])\n\n const executeAction = React.useCallback(async (id: string, actionId: string) => {\n const result = await runMutation({\n operation: () =>\n apiCall<{ ok: boolean; href?: string }>(\n `/api/notifications/${id}/action`,\n {\n method: 'POST',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ actionId }),\n },\n ),\n context: { formId: NOTIFICATION_ACTIONS_CONTEXT_ID, resourceKind: 'notification', retryLastMutation },\n mutationPayload: { id, actionId },\n })\n\n if (result.ok) {\n setNotifications((prev) =>\n prev.map((n) =>\n n.id === id ? { ...n, status: 'actioned', actionTaken: actionId } : n,\n ),\n )\n setUnreadCount((prev) => Math.max(0, prev - 1))\n }\n\n return { href: result.result?.href }\n }, [runMutation, retryLastMutation, setNotifications, setUnreadCount])\n\n const dismiss = React.useCallback(\n async (id: string) => {\n await runMutation({\n operation: () => apiCallOrThrow(`/api/notifications/${id}/dismiss`, { method: 'PUT' }),\n context: { formId: NOTIFICATION_ACTIONS_CONTEXT_ID, resourceKind: 'notification', retryLastMutation },\n mutationPayload: { id },\n })\n const notification = notifications.find((n) => n.id === id)\n setNotifications((prev) => prev.filter((n) => n.id !== id))\n if (notification?.status === 'unread') {\n setUnreadCount((prev) => Math.max(0, prev - 1))\n }\n if (notification) {\n const previousStatus = notification.status === 'unread' ? 'unread' : 'read'\n setDismissUndo({ notification, previousStatus })\n if (dismissUndoTimerRef.current) {\n window.clearTimeout(dismissUndoTimerRef.current)\n }\n dismissUndoTimerRef.current = window.setTimeout(() => {\n setDismissUndo(null)\n }, 6000)\n }\n },\n [notifications, setNotifications, setUnreadCount, runMutation, retryLastMutation],\n )\n\n React.useEffect(() => {\n dismissRef.current = dismiss\n }, [dismiss])\n\n const undoDismiss = React.useCallback(async () => {\n if (!dismissUndo) return\n await runMutation({\n operation: () =>\n apiCallOrThrow(`/api/notifications/${dismissUndo.notification.id}/restore`, {\n method: 'PUT',\n headers: { 'content-type': 'application/json' },\n body: JSON.stringify({ status: dismissUndo.previousStatus }),\n }),\n context: { formId: NOTIFICATION_ACTIONS_CONTEXT_ID, resourceKind: 'notification', retryLastMutation },\n mutationPayload: { id: dismissUndo.notification.id, status: dismissUndo.previousStatus },\n })\n\n setNotifications((prev) => {\n const next = [\n {\n ...dismissUndo.notification,\n status: dismissUndo.previousStatus,\n readAt:\n dismissUndo.previousStatus === 'unread'\n ? null\n : dismissUndo.notification.readAt ?? new Date().toISOString(),\n },\n ...prev.filter((n) => n.id !== dismissUndo.notification.id),\n ]\n return next.sort(\n (a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime(),\n )\n })\n\n if (dismissUndo.previousStatus === 'unread') {\n setUnreadCount((prev) => prev + 1)\n }\n\n if (dismissUndoTimerRef.current) {\n window.clearTimeout(dismissUndoTimerRef.current)\n }\n setDismissUndo(null)\n }, [dismissUndo, setNotifications, setUnreadCount, runMutation, retryLastMutation])\n\n const markAllRead = React.useCallback(async () => {\n await runMutation({\n operation: () => apiCallOrThrow('/api/notifications/mark-all-read', { method: 'PUT' }),\n context: { formId: NOTIFICATION_ACTIONS_CONTEXT_ID, resourceKind: 'notification', retryLastMutation },\n mutationPayload: {},\n })\n setNotifications((prev) =>\n prev.map((n) =>\n n.status === 'unread'\n ? { ...n, status: 'read', readAt: new Date().toISOString() }\n : n,\n ),\n )\n setUnreadCount(0)\n }, [runMutation, retryLastMutation, setNotifications, setUnreadCount])\n\n React.useEffect(() => {\n return () => {\n if (dismissUndoTimerRef.current) {\n window.clearTimeout(dismissUndoTimerRef.current)\n }\n }\n }, [])\n\n return {\n markAsRead,\n executeAction,\n dismiss,\n dismissUndo,\n undoDismiss,\n markAllRead,\n markAsReadRef,\n dismissRef,\n }\n}\n"],
|
|
5
|
+
"mapp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C,qBAAe,CAAC,SAAS,OAAO,CAAC;AAAA,IACnC;AAEA,QAAI,oBAAoB,SAAS;AAC/B,aAAO,aAAa,oBAAoB,OAAO;AAAA,IACjD;AACA,mBAAe,IAAI;AAAA,EACrB,GAAG,CAAC,aAAa,kBAAkB,gBAAgB,aAAa,iBAAiB,CAAC;AAElF,QAAM,cAAc,MAAM,YAAY,YAAY;AAChD,UAAM,YAAY;AAAA,MAChB,WAAW,MAAM,eAAe,oCAAoC,EAAE,QAAQ,MAAM,CAAC;AAAA,MACrF,SAAS,EAAE,QAAQ,iCAAiC,cAAc,gBAAgB,kBAAkB;AAAA,MACpG,iBAAiB,CAAC;AAAA,IACpB,CAAC;AACD;AAAA,MAAiB,CAAC,SAChB,KAAK;AAAA,QAAI,CAAC,MACR,EAAE,WAAW,WACT,EAAE,GAAG,GAAG,QAAQ,QAAQ,SAAQ,oBAAI,KAAK,GAAE,YAAY,EAAE,IACzD;AAAA,MACN;AAAA,IACF;AACA,mBAAe,CAAC;AAAA,EAClB,GAAG,CAAC,aAAa,mBAAmB,kBAAkB,cAAc,CAAC;AAErE,QAAM,UAAU,MAAM;AACpB,WAAO,MAAM;AACX,UAAI,oBAAoB,SAAS;AAC/B,eAAO,aAAa,oBAAoB,OAAO;AAAA,MACjD;AAAA,IACF;AAAA,EACF,GAAG,CAAC,CAAC;AAEL,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -97,6 +97,38 @@ function buildFormFieldFromCustomFieldDef(def, opts) {
|
|
|
97
97
|
} : {},
|
|
98
98
|
...def.multi && def.input === "listbox" ? { listbox: true } : {}
|
|
99
99
|
};
|
|
100
|
+
case "dictionary": {
|
|
101
|
+
if (!def.multi) {
|
|
102
|
+
const input = FieldRegistry.getInput(def.kind);
|
|
103
|
+
if (input) {
|
|
104
|
+
return {
|
|
105
|
+
id,
|
|
106
|
+
label,
|
|
107
|
+
type: "custom",
|
|
108
|
+
...baseProps,
|
|
109
|
+
component: (props) => input({ ...props, def })
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
return { id, label, type: "text", ...baseProps };
|
|
113
|
+
}
|
|
114
|
+
const optionsUrl = def.optionsUrl || (def.dictionaryId ? `/api/dictionaries/${def.dictionaryId}/entries` : void 0);
|
|
115
|
+
return {
|
|
116
|
+
id,
|
|
117
|
+
label,
|
|
118
|
+
type: "select",
|
|
119
|
+
description: def.description,
|
|
120
|
+
required,
|
|
121
|
+
options: [],
|
|
122
|
+
multiple: true,
|
|
123
|
+
listbox: true,
|
|
124
|
+
...optionsUrl ? {
|
|
125
|
+
loadOptions: async (query) => {
|
|
126
|
+
const url = buildOptionsUrl(optionsUrl, query);
|
|
127
|
+
return loadRemoteOptions(url);
|
|
128
|
+
}
|
|
129
|
+
} : {}
|
|
130
|
+
};
|
|
131
|
+
}
|
|
100
132
|
default: {
|
|
101
133
|
if (def.kind === "text" && def.multi) {
|
|
102
134
|
const base = { id, label, type: "tags", ...baseProps };
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../../src/backend/utils/customFieldForms.ts"],
|
|
4
|
-
"sourcesContent": ["import type { CrudField } from '../CrudForm'\nimport type {\n CustomFieldDefDto,\n CustomFieldDefinitionsPayload,\n} from './customFieldDefs'\nimport {\n filterCustomFieldDefs,\n fetchCustomFieldDefs,\n fetchCustomFieldDefinitionsPayload,\n} from './customFieldDefs'\nimport { FieldRegistry, loadGeneratedFieldRegistrations } from '../fields/registry'\nimport { apiCall } from './apiCall'\nimport { normalizeCustomFieldOptions } from '@open-mercato/shared/modules/entities/options'\nimport { CURRENCY_OPTIONS_URL } from '@open-mercato/shared/modules/entities/kinds'\n\nlet registryReady: Promise<void> | null = null\n\nasync function ensureFieldRegistryReady() {\n if (!registryReady) {\n registryReady = loadGeneratedFieldRegistrations().catch((err) => {\n registryReady = null\n throw err\n })\n }\n await registryReady\n}\n\nfunction buildOptionsUrl(base: string, query?: string): string {\n if (!query) return base\n try {\n const isAbsolute = /^([a-z][a-z\\d+\\-.]*:)?\\/\\//i.test(base)\n const origin = typeof window !== 'undefined' ? window.location.origin : 'http://localhost'\n const url = isAbsolute ? new URL(base) : new URL(base, origin)\n if (!url.searchParams.has('query')) url.searchParams.append('query', query)\n if (!url.searchParams.has('q')) url.searchParams.append('q', query)\n if (isAbsolute) return url.toString()\n return `${url.pathname}${url.search}`\n } catch {\n const sep = base.includes('?') ? '&' : '?'\n if (base.includes('query=')) return `${base}${sep}q=${encodeURIComponent(query)}`\n return `${base}${sep}query=${encodeURIComponent(query)}`\n }\n}\n\ntype OptionsResponse = { items?: unknown[] }\n\nasync function loadRemoteOptions(url: string): Promise<Array<{ value: string; label: string }>> {\n try {\n const call = await apiCall<OptionsResponse>(url, undefined, { fallback: { items: [] } })\n if (!call.ok) return []\n const payload = call.result ?? { items: [] }\n const items = Array.isArray(payload?.items) ? payload.items : []\n return items.map((it: any) => ({\n value: String(it?.value ?? it),\n label: String(it?.label ?? it?.value ?? it),\n }))\n } catch {\n return []\n }\n}\n\nexport function buildFormFieldFromCustomFieldDef(\n def: CustomFieldDefDto,\n opts?: { bareIds?: boolean }\n): CrudField | null {\n const id = opts?.bareIds ? def.key : `cf_${def.key}`\n const label = def.label || def.key\n const required = Array.isArray((def as any).validation)\n ? ((def as any).validation as any[]).some((rule) => rule && rule.rule === 'required')\n : false\n const baseProps = {\n description: def.description,\n required,\n ...(def.defaultValue !== undefined && def.defaultValue !== null ? { defaultValue: def.defaultValue } : {}),\n }\n\n switch (def.kind) {\n case 'boolean':\n return { id, label, type: 'checkbox', ...baseProps }\n case 'integer':\n case 'float':\n return { id, label, type: 'number', ...baseProps }\n case 'date':\n return { id, label, type: 'datepicker', ...baseProps }\n case 'datetime':\n return { id, label, type: 'datetime', ...baseProps }\n case 'multiline': {\n let editor: 'simple' | 'uiw' | 'html' = 'html'\n if (def.editor === 'simpleMarkdown') editor = 'simple'\n else if (def.editor === 'htmlRichText') editor = 'html'\n return { id, label, type: 'richtext', ...baseProps, editor }\n }\n case 'select':\n case 'currency':\n case 'relation':\n return {\n id,\n label,\n type: 'select',\n ...baseProps,\n options: normalizeCustomFieldOptions(def.options || []).map((option) => ({\n value: option.value,\n label: option.label,\n })),\n multiple: !!def.multi,\n ...(def.kind === 'currency'\n ? {\n loadOptions: async (query?: string) => {\n const url = buildOptionsUrl(CURRENCY_OPTIONS_URL, query)\n return loadRemoteOptions(url)\n },\n }\n : def.optionsUrl\n ? {\n loadOptions: async (query?: string) => {\n const url = buildOptionsUrl(def.optionsUrl!, query)\n return loadRemoteOptions(url)\n },\n }\n : {}),\n ...(def.multi && def.input === 'listbox' ? ({ listbox: true } as any) : {}),\n }\n default: {\n if (def.kind === 'text' && def.multi) {\n const base: any = { id, label, type: 'tags', ...baseProps }\n const resolvedOptions = normalizeCustomFieldOptions(def.options || [])\n if (resolvedOptions.length > 0) {\n base.options = resolvedOptions.map((option) => ({ value: option.value, label: option.label }))\n }\n if (def.optionsUrl) {\n base.loadOptions = async (query?: string) => {\n const url = buildOptionsUrl(def.optionsUrl!, query)\n return loadRemoteOptions(url)\n }\n }\n return base\n }\n if (def.kind === 'text' && typeof def.editor === 'string' && def.editor) {\n let editor: 'simple' | 'uiw' | 'html' = 'html'\n if (def.editor === 'simpleMarkdown') editor = 'simple'\n else if (def.editor === 'htmlRichText') editor = 'html'\n return { id, label, type: 'richtext', ...baseProps, editor }\n }\n const input = FieldRegistry.getInput(def.kind)\n if (input) {\n return {\n id,\n label,\n type: 'custom',\n ...baseProps,\n component: (props) => input({ ...props, def }),\n }\n }\n return { id, label, type: 'text', ...baseProps }\n }\n }\n}\n\nexport function buildFormFieldsFromCustomFields(\n defs: CustomFieldDefDto[],\n opts?: { bareIds?: boolean }\n): CrudField[] {\n const fields: CrudField[] = []\n const visible = filterCustomFieldDefs(defs, 'form')\n const seenKeys = new Set<string>()\n for (const def of visible) {\n const keyLower = String(def.key).toLowerCase()\n if (seenKeys.has(keyLower)) continue\n seenKeys.add(keyLower)\n const field = buildFormFieldFromCustomFieldDef(def, opts)\n if (field) fields.push(field)\n }\n return fields\n}\n\nexport async function fetchCustomFieldFormStructure(\n entityIds: string | string[],\n fetchImpl?: typeof fetch,\n options?: { bareIds?: boolean },\n): Promise<{ fields: CrudField[]; definitions: CustomFieldDefDto[]; metadata: CustomFieldDefinitionsPayload }> {\n await ensureFieldRegistryReady()\n const metadata = await fetchCustomFieldDefinitionsPayload(entityIds, fetchImpl)\n const definitions = Array.isArray(metadata.items) ? metadata.items : []\n const fields = buildFormFieldsFromCustomFields(definitions, options)\n return { fields, definitions, metadata }\n}\n\nexport async function fetchCustomFieldFormFields(\n entityIds: string | string[],\n fetchImpl?: typeof fetch,\n options?: { bareIds?: boolean },\n): Promise<CrudField[]> {\n const { fields } = await fetchCustomFieldFormStructure(entityIds, fetchImpl, options)\n return fields\n}\n\nexport async function fetchCustomFieldFormFieldsWithDefinitions(\n entityIds: string | string[],\n fetchImpl?: typeof fetch,\n options?: { bareIds?: boolean },\n): Promise<{ fields: CrudField[]; definitions: CustomFieldDefDto[]; metadata: CustomFieldDefinitionsPayload }> {\n return fetchCustomFieldFormStructure(entityIds, fetchImpl, options)\n}\n"],
|
|
5
|
-
"mappings": "AAKA;AAAA,EACE;AAAA,EAEA;AAAA,OACK;AACP,SAAS,eAAe,uCAAuC;AAC/D,SAAS,eAAe;AACxB,SAAS,mCAAmC;AAC5C,SAAS,4BAA4B;AAErC,IAAI,gBAAsC;AAE1C,eAAe,2BAA2B;AACxC,MAAI,CAAC,eAAe;AAClB,oBAAgB,gCAAgC,EAAE,MAAM,CAAC,QAAQ;AAC/D,sBAAgB;AAChB,YAAM;AAAA,IACR,CAAC;AAAA,EACH;AACA,QAAM;AACR;AAEA,SAAS,gBAAgB,MAAc,OAAwB;AAC7D,MAAI,CAA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O,IAAI,CAAC;AAAA,QAC/C;AAAA,MACF;AACA,aAAO,EAAE,IAAI,OAAO,MAAM,QAAQ,GAAG,UAAU;AAAA,IACjD;AAAA,EACF;AACF;AAEO,SAAS,gCACd,MACA,MACa;AACb,QAAM,SAAsB,CAAC;AAC7B,QAAM,UAAU,sBAAsB,MAAM,MAAM;AAClD,QAAM,WAAW,oBAAI,IAAY;AACjC,aAAW,OAAO,SAAS;AACzB,UAAM,WAAW,OAAO,IAAI,GAAG,EAAE,YAAY;AAC7C,QAAI,SAAS,IAAI,QAAQ,EAAG;AAC5B,aAAS,IAAI,QAAQ;AACrB,UAAM,QAAQ,iCAAiC,KAAK,IAAI;AACxD,QAAI,MAAO,QAAO,KAAK,KAAK;AAAA,EAC9B;AACA,SAAO;AACT;AAEA,eAAsB,8BACpB,WACA,WACA,SAC6G;AAC7G,QAAM,yBAAyB;AAC/B,QAAM,WAAW,MAAM,mCAAmC,WAAW,SAAS;AAC9E,QAAM,cAAc,MAAM,QAAQ,SAAS,KAAK,IAAI,SAAS,QAAQ,CAAC;AACtE,QAAM,SAAS,gCAAgC,aAAa,OAAO;AACnE,SAAO,EAAE,QAAQ,aAAa,SAAS;AACzC;AAEA,eAAsB,2BACpB,WACA,WACA,SACsB;AACtB,QAAM,EAAE,OAAO,IAAI,MAAM,8BAA8B,WAAW,WAAW,OAAO;AACpF,SAAO;AACT;AAEA,eAAsB,0CACpB,WACA,WACA,SAC6G;AAC7G,SAAO,8BAA8B,WAAW,WAAW,OAAO;AACpE;",
|
|
4
|
+
"sourcesContent": ["import type { CrudField } from '../CrudForm'\nimport type {\n CustomFieldDefDto,\n CustomFieldDefinitionsPayload,\n} from './customFieldDefs'\nimport {\n filterCustomFieldDefs,\n fetchCustomFieldDefs,\n fetchCustomFieldDefinitionsPayload,\n} from './customFieldDefs'\nimport { FieldRegistry, loadGeneratedFieldRegistrations } from '../fields/registry'\nimport { apiCall } from './apiCall'\nimport { normalizeCustomFieldOptions } from '@open-mercato/shared/modules/entities/options'\nimport { CURRENCY_OPTIONS_URL } from '@open-mercato/shared/modules/entities/kinds'\n\nlet registryReady: Promise<void> | null = null\n\nasync function ensureFieldRegistryReady() {\n if (!registryReady) {\n registryReady = loadGeneratedFieldRegistrations().catch((err) => {\n registryReady = null\n throw err\n })\n }\n await registryReady\n}\n\nfunction buildOptionsUrl(base: string, query?: string): string {\n if (!query) return base\n try {\n const isAbsolute = /^([a-z][a-z\\d+\\-.]*:)?\\/\\//i.test(base)\n const origin = typeof window !== 'undefined' ? window.location.origin : 'http://localhost'\n const url = isAbsolute ? new URL(base) : new URL(base, origin)\n if (!url.searchParams.has('query')) url.searchParams.append('query', query)\n if (!url.searchParams.has('q')) url.searchParams.append('q', query)\n if (isAbsolute) return url.toString()\n return `${url.pathname}${url.search}`\n } catch {\n const sep = base.includes('?') ? '&' : '?'\n if (base.includes('query=')) return `${base}${sep}q=${encodeURIComponent(query)}`\n return `${base}${sep}query=${encodeURIComponent(query)}`\n }\n}\n\ntype OptionsResponse = { items?: unknown[] }\n\nasync function loadRemoteOptions(url: string): Promise<Array<{ value: string; label: string }>> {\n try {\n const call = await apiCall<OptionsResponse>(url, undefined, { fallback: { items: [] } })\n if (!call.ok) return []\n const payload = call.result ?? { items: [] }\n const items = Array.isArray(payload?.items) ? payload.items : []\n return items.map((it: any) => ({\n value: String(it?.value ?? it),\n label: String(it?.label ?? it?.value ?? it),\n }))\n } catch {\n return []\n }\n}\n\nexport function buildFormFieldFromCustomFieldDef(\n def: CustomFieldDefDto,\n opts?: { bareIds?: boolean }\n): CrudField | null {\n const id = opts?.bareIds ? def.key : `cf_${def.key}`\n const label = def.label || def.key\n const required = Array.isArray((def as any).validation)\n ? ((def as any).validation as any[]).some((rule) => rule && rule.rule === 'required')\n : false\n const baseProps = {\n description: def.description,\n required,\n ...(def.defaultValue !== undefined && def.defaultValue !== null ? { defaultValue: def.defaultValue } : {}),\n }\n\n switch (def.kind) {\n case 'boolean':\n return { id, label, type: 'checkbox', ...baseProps }\n case 'integer':\n case 'float':\n return { id, label, type: 'number', ...baseProps }\n case 'date':\n return { id, label, type: 'datepicker', ...baseProps }\n case 'datetime':\n return { id, label, type: 'datetime', ...baseProps }\n case 'multiline': {\n let editor: 'simple' | 'uiw' | 'html' = 'html'\n if (def.editor === 'simpleMarkdown') editor = 'simple'\n else if (def.editor === 'htmlRichText') editor = 'html'\n return { id, label, type: 'richtext', ...baseProps, editor }\n }\n case 'select':\n case 'currency':\n case 'relation':\n return {\n id,\n label,\n type: 'select',\n ...baseProps,\n options: normalizeCustomFieldOptions(def.options || []).map((option) => ({\n value: option.value,\n label: option.label,\n })),\n multiple: !!def.multi,\n ...(def.kind === 'currency'\n ? {\n loadOptions: async (query?: string) => {\n const url = buildOptionsUrl(CURRENCY_OPTIONS_URL, query)\n return loadRemoteOptions(url)\n },\n }\n : def.optionsUrl\n ? {\n loadOptions: async (query?: string) => {\n const url = buildOptionsUrl(def.optionsUrl!, query)\n return loadRemoteOptions(url)\n },\n }\n : {}),\n ...(def.multi && def.input === 'listbox' ? ({ listbox: true } as any) : {}),\n }\n case 'dictionary': {\n if (!def.multi) {\n const input = FieldRegistry.getInput(def.kind)\n if (input) {\n return {\n id,\n label,\n type: 'custom',\n ...baseProps,\n component: (props) => input({ ...props, def }),\n }\n }\n return { id, label, type: 'text', ...baseProps }\n }\n const optionsUrl = def.optionsUrl || (def.dictionaryId ? `/api/dictionaries/${def.dictionaryId}/entries` : undefined)\n return {\n id,\n label,\n type: 'select',\n description: def.description,\n required,\n options: [],\n multiple: true,\n listbox: true,\n ...(optionsUrl\n ? {\n loadOptions: async (query?: string) => {\n const url = buildOptionsUrl(optionsUrl, query)\n return loadRemoteOptions(url)\n },\n }\n : {}),\n }\n }\n default: {\n if (def.kind === 'text' && def.multi) {\n const base: any = { id, label, type: 'tags', ...baseProps }\n const resolvedOptions = normalizeCustomFieldOptions(def.options || [])\n if (resolvedOptions.length > 0) {\n base.options = resolvedOptions.map((option) => ({ value: option.value, label: option.label }))\n }\n if (def.optionsUrl) {\n base.loadOptions = async (query?: string) => {\n const url = buildOptionsUrl(def.optionsUrl!, query)\n return loadRemoteOptions(url)\n }\n }\n return base\n }\n if (def.kind === 'text' && typeof def.editor === 'string' && def.editor) {\n let editor: 'simple' | 'uiw' | 'html' = 'html'\n if (def.editor === 'simpleMarkdown') editor = 'simple'\n else if (def.editor === 'htmlRichText') editor = 'html'\n return { id, label, type: 'richtext', ...baseProps, editor }\n }\n const input = FieldRegistry.getInput(def.kind)\n if (input) {\n return {\n id,\n label,\n type: 'custom',\n ...baseProps,\n component: (props) => input({ ...props, def }),\n }\n }\n return { id, label, type: 'text', ...baseProps }\n }\n }\n}\n\nexport function buildFormFieldsFromCustomFields(\n defs: CustomFieldDefDto[],\n opts?: { bareIds?: boolean }\n): CrudField[] {\n const fields: CrudField[] = []\n const visible = filterCustomFieldDefs(defs, 'form')\n const seenKeys = new Set<string>()\n for (const def of visible) {\n const keyLower = String(def.key).toLowerCase()\n if (seenKeys.has(keyLower)) continue\n seenKeys.add(keyLower)\n const field = buildFormFieldFromCustomFieldDef(def, opts)\n if (field) fields.push(field)\n }\n return fields\n}\n\nexport async function fetchCustomFieldFormStructure(\n entityIds: string | string[],\n fetchImpl?: typeof fetch,\n options?: { bareIds?: boolean },\n): Promise<{ fields: CrudField[]; definitions: CustomFieldDefDto[]; metadata: CustomFieldDefinitionsPayload }> {\n await ensureFieldRegistryReady()\n const metadata = await fetchCustomFieldDefinitionsPayload(entityIds, fetchImpl)\n const definitions = Array.isArray(metadata.items) ? metadata.items : []\n const fields = buildFormFieldsFromCustomFields(definitions, options)\n return { fields, definitions, metadata }\n}\n\nexport async function fetchCustomFieldFormFields(\n entityIds: string | string[],\n fetchImpl?: typeof fetch,\n options?: { bareIds?: boolean },\n): Promise<CrudField[]> {\n const { fields } = await fetchCustomFieldFormStructure(entityIds, fetchImpl, options)\n return fields\n}\n\nexport async function fetchCustomFieldFormFieldsWithDefinitions(\n entityIds: string | string[],\n fetchImpl?: typeof fetch,\n options?: { bareIds?: boolean },\n): Promise<{ fields: CrudField[]; definitions: CustomFieldDefDto[]; metadata: CustomFieldDefinitionsPayload }> {\n return fetchCustomFieldFormStructure(entityIds, fetchImpl, options)\n}\n"],
|
|
5
|
+
"mappings": "AAKA;AAAA,EACE;AAAA,EAEA;AAAA,OACK;AACP,SAAS,eAAe,uCAAuC;AAC/D,SAAS,eAAe;AACxB,SAAS,mCAAmC;AAC5C,SAAS,4BAA4B;AAErC,IAAI,gBAAsC;AAE1C,eAAe,2BAA2B;AACxC,MAAI,CAAC,eAAe;AAClB,oBAAgB,gCAAgC,EAAE,MAAM,CAAC,QAAQ;AAC/D,sBAAgB;AAChB,YAAM;AAAA,IACR,CAAC;AAAA,EACH;AACA,QAAM;AACR;AAEA,SAAS,gBAAgB,MAAc,OAAwB;AAC7D,MAAI,CAAC,MAAO,QAAO;AACnB,MAAI;AACF,UAAM,aAAa,8BAA8B,KAAK,IAAI;AAC1D,UAAM,SAAS,OAAO,WAAW,cAAc,OAAO,SAAS,SAAS;AACxE,UAAM,MAAM,aAAa,IAAI,IAAI,IAAI,IAAI,IAAI,IAAI,MAAM,MAAM;AAC7D,QAAI,CAAC,IAAI,aAAa,IAAI,OAAO,EAAG,KAAI,aAAa,OAAO,SAAS,KAAK;AAC1E,QAAI,CAAC,IAAI,aAAa,IAAI,GAAG,EAAG,KAAI,aAAa,OAAO,KAAK,KAAK;AAClE,QAAI,WAAY,QAAO,IAAI,SAAS;AACpC,WAAO,GAAG,IAAI,QAAQ,GAAG,IAAI,MAAM;AAAA,EACrC,QAAQ;AACN,UAAM,MAAM,KAAK,SAAS,GAAG,IAAI,MAAM;AACvC,QAAI,KAAK,SAAS,QAAQ,EAAG,QAAO,GAAG,IAAI,GAAG,GAAG,KAAK,mBAAmB,KAAK,CAAC;AAC/E,WAAO,GAAG,IAAI,GAAG,GAAG,SAAS,mBAAmB,KAAK,CAAC;AAAA,EACxD;AACF;AAIA,eAAe,kBAAkB,KAA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U,MAAM,EAAE,GAAG,OAAO,IAAI,CAAC;AAAA,QAC/C;AAAA,MACF;AACA,aAAO,EAAE,IAAI,OAAO,MAAM,QAAQ,GAAG,UAAU;AAAA,IACjD;AAAA,EACF;AACF;AAEO,SAAS,gCACd,MACA,MACa;AACb,QAAM,SAAsB,CAAC;AAC7B,QAAM,UAAU,sBAAsB,MAAM,MAAM;AAClD,QAAM,WAAW,oBAAI,IAAY;AACjC,aAAW,OAAO,SAAS;AACzB,UAAM,WAAW,OAAO,IAAI,GAAG,EAAE,YAAY;AAC7C,QAAI,SAAS,IAAI,QAAQ,EAAG;AAC5B,aAAS,IAAI,QAAQ;AACrB,UAAM,QAAQ,iCAAiC,KAAK,IAAI;AACxD,QAAI,MAAO,QAAO,KAAK,KAAK;AAAA,EAC9B;AACA,SAAO;AACT;AAEA,eAAsB,8BACpB,WACA,WACA,SAC6G;AAC7G,QAAM,yBAAyB;AAC/B,QAAM,WAAW,MAAM,mCAAmC,WAAW,SAAS;AAC9E,QAAM,cAAc,MAAM,QAAQ,SAAS,KAAK,IAAI,SAAS,QAAQ,CAAC;AACtE,QAAM,SAAS,gCAAgC,aAAa,OAAO;AACnE,SAAO,EAAE,QAAQ,aAAa,SAAS;AACzC;AAEA,eAAsB,2BACpB,WACA,WACA,SACsB;AACtB,QAAM,EAAE,OAAO,IAAI,MAAM,8BAA8B,WAAW,WAAW,OAAO;AACpF,SAAO;AACT;AAEA,eAAsB,0CACpB,WACA,WACA,SAC6G;AAC7G,SAAO,8BAA8B,WAAW,WAAW,OAAO;AACpE;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
|
@@ -4,6 +4,9 @@ import * as React from "react";
|
|
|
4
4
|
import { cn } from "@open-mercato/shared/lib/utils";
|
|
5
5
|
import { Input } from "./input.js";
|
|
6
6
|
import { Tag } from "./tag.js";
|
|
7
|
+
function defaultRemoveTagLabel(tag) {
|
|
8
|
+
return `Remove ${tag}`;
|
|
9
|
+
}
|
|
7
10
|
function escapeRegExp(input) {
|
|
8
11
|
return input.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
9
12
|
}
|
|
@@ -29,7 +32,8 @@ const TagInput = React.forwardRef(
|
|
|
29
32
|
name,
|
|
30
33
|
"aria-label": ariaLabel,
|
|
31
34
|
"aria-invalid": ariaInvalid,
|
|
32
|
-
rightIcon
|
|
35
|
+
rightIcon,
|
|
36
|
+
removeTagLabel = defaultRemoveTagLabel
|
|
33
37
|
}, ref) => {
|
|
34
38
|
const [internalValue, setInternalValue] = React.useState([]);
|
|
35
39
|
const [inputText, setInputText] = React.useState("");
|
|
@@ -160,7 +164,7 @@ const TagInput = React.forwardRef(
|
|
|
160
164
|
shape: "square",
|
|
161
165
|
disabled,
|
|
162
166
|
onRemove: () => removeTagAt(index),
|
|
163
|
-
removeAriaLabel:
|
|
167
|
+
removeAriaLabel: removeTagLabel(tag),
|
|
164
168
|
children: tag
|
|
165
169
|
},
|
|
166
170
|
`${tag}-${index}`
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../../src/primitives/tag-input.tsx"],
|
|
4
|
-
"sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { cn } from '@open-mercato/shared/lib/utils'\nimport { Input, type InputProps } from './input'\nimport { Tag } from './tag'\n\nexport type TagInputProps = {\n value?: string[]\n onChange?: (value: string[]) => void\n placeholder?: string\n size?: 'sm' | 'default' | 'lg'\n disabled?: boolean\n maxTags?: number\n validate?: (tag: string) => boolean | string\n separator?: string | RegExp\n allowDuplicates?: boolean\n className?: string\n id?: string\n name?: string\n 'aria-label'?: string\n 'aria-invalid'?: boolean\n /**\n * Optional right-side icon for the input row (e.g. info-circle, search). Mirrors\n * the Figma `Tag Input` Filled state with `Right Icon=true`.\n */\n rightIcon?: InputProps['rightIcon']\n}\n\nfunction escapeRegExp(input: string): string {\n return input.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\nfunction buildSplitter(separator: string | RegExp): RegExp {\n if (separator instanceof RegExp) {\n return separator.flags.includes('g')\n ? separator\n : new RegExp(separator.source, `${separator.flags}g`)\n }\n return new RegExp(escapeRegExp(separator), 'g')\n}\n\nexport const TagInput = React.forwardRef<HTMLInputElement, TagInputProps>(\n (\n {\n value: valueProp,\n onChange,\n placeholder,\n size = 'default',\n disabled = false,\n maxTags,\n validate,\n separator = ',',\n allowDuplicates = false,\n className,\n id,\n name,\n 'aria-label': ariaLabel,\n 'aria-invalid': ariaInvalid,\n rightIcon,\n },\n ref,\n ) => {\n const [internalValue, setInternalValue] = React.useState<string[]>([])\n const [inputText, setInputText] = React.useState('')\n const [error, setError] = React.useState<string | null>(null)\n\n const isControlled = valueProp !== undefined\n const value = isControlled ? (valueProp as string[]) : internalValue\n\n const commitValue = React.useCallback(\n (next: string[]) => {\n if (!isControlled) setInternalValue(next)\n onChange?.(next)\n },\n [isControlled, onChange],\n )\n\n const appendToList = React.useCallback(\n (current: string[], rawTag: string): { next: string[]; errorText: string | null } | null => {\n const tag = rawTag.trim()\n if (!tag) return null\n if (!allowDuplicates && current.includes(tag)) return null\n if (typeof maxTags === 'number' && current.length >= maxTags) return null\n if (validate) {\n const result = validate(tag)\n if (result === false) return null\n if (typeof result === 'string') return { next: current, errorText: result }\n }\n return { next: [...current, tag], errorText: null }\n },\n [allowDuplicates, maxTags, validate],\n )\n\n const tryAddTag = React.useCallback(\n (rawTag: string): boolean => {\n const outcome = appendToList(value, rawTag)\n if (!outcome) return false\n if (outcome.errorText !== null) {\n setError(outcome.errorText)\n return false\n }\n setError(null)\n if (outcome.next !== value) commitValue(outcome.next)\n return outcome.next !== value\n },\n [appendToList, commitValue, value],\n )\n\n const tryAddManyTags = React.useCallback(\n (rawTags: string[]) => {\n let acc = value\n let pendingError: string | null = null\n for (const raw of rawTags) {\n const outcome = appendToList(acc, raw)\n if (!outcome) continue\n if (outcome.errorText !== null) {\n pendingError = outcome.errorText\n continue\n }\n acc = outcome.next\n }\n if (acc !== value) commitValue(acc)\n if (pendingError !== null) setError(pendingError)\n else if (acc !== value) setError(null)\n },\n [appendToList, commitValue, value],\n )\n\n const removeTagAt = React.useCallback(\n (index: number) => {\n if (index < 0 || index >= value.length) return\n const next = value.slice(0, index).concat(value.slice(index + 1))\n commitValue(next)\n setError(null)\n },\n [commitValue, value],\n )\n\n const splitter = React.useMemo(() => buildSplitter(separator), [separator])\n\n const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {\n const text = event.target.value\n splitter.lastIndex = 0\n if (splitter.test(text)) {\n splitter.lastIndex = 0\n const parts = text.split(splitter)\n const trailing = parts.pop() ?? ''\n tryAddManyTags(parts)\n setInputText(trailing)\n return\n }\n setInputText(text)\n if (error) setError(null)\n }\n\n const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {\n if (event.key === 'Enter') {\n event.preventDefault()\n tryAddTag(inputText)\n setInputText('')\n return\n }\n if (event.key === 'Backspace' && inputText.length === 0 && value.length > 0) {\n event.preventDefault()\n removeTagAt(value.length - 1)\n }\n }\n\n const limitReached = typeof maxTags === 'number' && value.length >= maxTags\n\n return (\n <div className={cn('flex w-full flex-col gap-1', className)} data-slot=\"tag-input\">\n <Input\n ref={ref}\n type=\"text\"\n size={size}\n id={id}\n name={name}\n value={inputText}\n onChange={handleChange}\n onKeyDown={handleKeyDown}\n placeholder={placeholder}\n disabled={disabled || limitReached}\n aria-label={ariaLabel}\n aria-invalid={ariaInvalid || Boolean(error) || undefined}\n rightIcon={rightIcon}\n data-slot=\"tag-input-field\"\n />\n {value.length > 0 ? (\n <div\n className=\"flex flex-wrap items-center gap-2 pt-1\"\n data-slot=\"tag-input-chips\"\n >\n {value.map((tag, index) => (\n <Tag\n key={`${tag}-${index}`}\n variant=\"default\"\n shape=\"square\"\n disabled={disabled}\n onRemove={() => removeTagAt(index)}\n removeAriaLabel={
|
|
5
|
-
"mappings": ";
|
|
4
|
+
"sourcesContent": ["\"use client\"\n\nimport * as React from 'react'\nimport { cn } from '@open-mercato/shared/lib/utils'\nimport { Input, type InputProps } from './input'\nimport { Tag } from './tag'\n\nexport type TagInputProps = {\n value?: string[]\n onChange?: (value: string[]) => void\n placeholder?: string\n size?: 'sm' | 'default' | 'lg'\n disabled?: boolean\n maxTags?: number\n validate?: (tag: string) => boolean | string\n separator?: string | RegExp\n allowDuplicates?: boolean\n className?: string\n id?: string\n name?: string\n 'aria-label'?: string\n 'aria-invalid'?: boolean\n /**\n * Optional right-side icon for the input row (e.g. info-circle, search). Mirrors\n * the Figma `Tag Input` Filled state with `Right Icon=true`.\n */\n rightIcon?: InputProps['rightIcon']\n /**\n * Builds the accessible label for each tag's remove (\u00D7) button. Lets callers\n * localize the action; defaults to the English `Remove {tag}`.\n */\n removeTagLabel?: (tag: string) => string\n}\n\nfunction defaultRemoveTagLabel(tag: string): string {\n return `Remove ${tag}`\n}\n\nfunction escapeRegExp(input: string): string {\n return input.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n}\n\nfunction buildSplitter(separator: string | RegExp): RegExp {\n if (separator instanceof RegExp) {\n return separator.flags.includes('g')\n ? separator\n : new RegExp(separator.source, `${separator.flags}g`)\n }\n return new RegExp(escapeRegExp(separator), 'g')\n}\n\nexport const TagInput = React.forwardRef<HTMLInputElement, TagInputProps>(\n (\n {\n value: valueProp,\n onChange,\n placeholder,\n size = 'default',\n disabled = false,\n maxTags,\n validate,\n separator = ',',\n allowDuplicates = false,\n className,\n id,\n name,\n 'aria-label': ariaLabel,\n 'aria-invalid': ariaInvalid,\n rightIcon,\n removeTagLabel = defaultRemoveTagLabel,\n },\n ref,\n ) => {\n const [internalValue, setInternalValue] = React.useState<string[]>([])\n const [inputText, setInputText] = React.useState('')\n const [error, setError] = React.useState<string | null>(null)\n\n const isControlled = valueProp !== undefined\n const value = isControlled ? (valueProp as string[]) : internalValue\n\n const commitValue = React.useCallback(\n (next: string[]) => {\n if (!isControlled) setInternalValue(next)\n onChange?.(next)\n },\n [isControlled, onChange],\n )\n\n const appendToList = React.useCallback(\n (current: string[], rawTag: string): { next: string[]; errorText: string | null } | null => {\n const tag = rawTag.trim()\n if (!tag) return null\n if (!allowDuplicates && current.includes(tag)) return null\n if (typeof maxTags === 'number' && current.length >= maxTags) return null\n if (validate) {\n const result = validate(tag)\n if (result === false) return null\n if (typeof result === 'string') return { next: current, errorText: result }\n }\n return { next: [...current, tag], errorText: null }\n },\n [allowDuplicates, maxTags, validate],\n )\n\n const tryAddTag = React.useCallback(\n (rawTag: string): boolean => {\n const outcome = appendToList(value, rawTag)\n if (!outcome) return false\n if (outcome.errorText !== null) {\n setError(outcome.errorText)\n return false\n }\n setError(null)\n if (outcome.next !== value) commitValue(outcome.next)\n return outcome.next !== value\n },\n [appendToList, commitValue, value],\n )\n\n const tryAddManyTags = React.useCallback(\n (rawTags: string[]) => {\n let acc = value\n let pendingError: string | null = null\n for (const raw of rawTags) {\n const outcome = appendToList(acc, raw)\n if (!outcome) continue\n if (outcome.errorText !== null) {\n pendingError = outcome.errorText\n continue\n }\n acc = outcome.next\n }\n if (acc !== value) commitValue(acc)\n if (pendingError !== null) setError(pendingError)\n else if (acc !== value) setError(null)\n },\n [appendToList, commitValue, value],\n )\n\n const removeTagAt = React.useCallback(\n (index: number) => {\n if (index < 0 || index >= value.length) return\n const next = value.slice(0, index).concat(value.slice(index + 1))\n commitValue(next)\n setError(null)\n },\n [commitValue, value],\n )\n\n const splitter = React.useMemo(() => buildSplitter(separator), [separator])\n\n const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {\n const text = event.target.value\n splitter.lastIndex = 0\n if (splitter.test(text)) {\n splitter.lastIndex = 0\n const parts = text.split(splitter)\n const trailing = parts.pop() ?? ''\n tryAddManyTags(parts)\n setInputText(trailing)\n return\n }\n setInputText(text)\n if (error) setError(null)\n }\n\n const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {\n if (event.key === 'Enter') {\n event.preventDefault()\n tryAddTag(inputText)\n setInputText('')\n return\n }\n if (event.key === 'Backspace' && inputText.length === 0 && value.length > 0) {\n event.preventDefault()\n removeTagAt(value.length - 1)\n }\n }\n\n const limitReached = typeof maxTags === 'number' && value.length >= maxTags\n\n return (\n <div className={cn('flex w-full flex-col gap-1', className)} data-slot=\"tag-input\">\n <Input\n ref={ref}\n type=\"text\"\n size={size}\n id={id}\n name={name}\n value={inputText}\n onChange={handleChange}\n onKeyDown={handleKeyDown}\n placeholder={placeholder}\n disabled={disabled || limitReached}\n aria-label={ariaLabel}\n aria-invalid={ariaInvalid || Boolean(error) || undefined}\n rightIcon={rightIcon}\n data-slot=\"tag-input-field\"\n />\n {value.length > 0 ? (\n <div\n className=\"flex flex-wrap items-center gap-2 pt-1\"\n data-slot=\"tag-input-chips\"\n >\n {value.map((tag, index) => (\n <Tag\n key={`${tag}-${index}`}\n variant=\"default\"\n shape=\"square\"\n disabled={disabled}\n onRemove={() => removeTagAt(index)}\n removeAriaLabel={removeTagLabel(tag)}\n >\n {tag}\n </Tag>\n ))}\n </div>\n ) : null}\n {error ? (\n <p\n className=\"text-xs text-status-error-text\"\n role=\"alert\"\n data-slot=\"tag-input-error\"\n >\n {error}\n </p>\n ) : null}\n </div>\n )\n },\n)\n\nTagInput.displayName = 'TagInput'\n"],
|
|
5
|
+
"mappings": ";AAsLM,SACE,KADF;AApLN,YAAY,WAAW;AACvB,SAAS,UAAU;AACnB,SAAS,aAA8B;AACvC,SAAS,WAAW;AA6BpB,SAAS,sBAAsB,KAAqB;AAClD,SAAO,UAAU,GAAG;AACtB;AAEA,SAAS,aAAa,OAAuB;AAC3C,SAAO,MAAM,QAAQ,uBAAuB,MAAM;AACpD;AAEA,SAAS,cAAc,WAAoC;AACzD,MAAI,qBAAqB,QAAQ;AAC/B,WAAO,UAAU,MAAM,SAAS,GAAG,IAC/B,YACA,IAAI,OAAO,UAAU,QAAQ,GAAG,UAAU,KAAK,GAAG;AAAA,EACxD;AACA,SAAO,IAAI,OAAO,aAAa,SAAS,GAAG,GAAG;AAChD;AAE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H,IACE;AAAA,MACH,QACC;AAAA,QAAC;AAAA;AAAA,UACC,WAAU;AAAA,UACV,MAAK;AAAA,UACL,aAAU;AAAA,UAET;AAAA;AAAA,MACH,IACE;AAAA,OACN;AAAA,EAEJ;AACF;AAEA,SAAS,cAAc;",
|
|
6
6
|
"names": []
|
|
7
7
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-mercato/ui",
|
|
3
|
-
"version": "0.6.6-develop.
|
|
3
|
+
"version": "0.6.6-develop.6228.1.cf483c68b5",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -155,13 +155,13 @@
|
|
|
155
155
|
"remark-gfm": "^4.0.1"
|
|
156
156
|
},
|
|
157
157
|
"peerDependencies": {
|
|
158
|
-
"@open-mercato/shared": "0.6.6-develop.
|
|
158
|
+
"@open-mercato/shared": "0.6.6-develop.6228.1.cf483c68b5",
|
|
159
159
|
"react": ">=18.0.0",
|
|
160
160
|
"react-dom": ">=18.0.0",
|
|
161
161
|
"react-is": ">=18.0.0"
|
|
162
162
|
},
|
|
163
163
|
"devDependencies": {
|
|
164
|
-
"@open-mercato/shared": "0.6.6-develop.
|
|
164
|
+
"@open-mercato/shared": "0.6.6-develop.6228.1.cf483c68b5",
|
|
165
165
|
"@testing-library/dom": "^10.4.1",
|
|
166
166
|
"@testing-library/jest-dom": "^6.9.1",
|
|
167
167
|
"@testing-library/react": "^16.3.1",
|
package/src/backend/CrudForm.tsx
CHANGED
|
@@ -2689,6 +2689,12 @@ export function CrudForm<TValues extends Record<string, unknown>>({
|
|
|
2689
2689
|
for (const injectedId of injectedFieldIdSet) {
|
|
2690
2690
|
delete coreValues[injectedId]
|
|
2691
2691
|
}
|
|
2692
|
+
if (customEntity) {
|
|
2693
|
+
const allowedKeys = new Set(cfDefinitions.map((definition) => definition.key).filter(Boolean))
|
|
2694
|
+
for (const key of Object.keys(coreValues)) {
|
|
2695
|
+
if (!allowedKeys.has(key)) delete coreValues[key]
|
|
2696
|
+
}
|
|
2697
|
+
}
|
|
2692
2698
|
|
|
2693
2699
|
let parsedValues: TValues
|
|
2694
2700
|
if (schema) {
|
|
@@ -2722,6 +2728,12 @@ export function CrudForm<TValues extends Record<string, unknown>>({
|
|
|
2722
2728
|
for (const injectedId of injectedFieldIdSet) {
|
|
2723
2729
|
delete projectedCoreValues[injectedId]
|
|
2724
2730
|
}
|
|
2731
|
+
if (customEntity) {
|
|
2732
|
+
const allowedKeys = new Set(cfDefinitions.map((definition) => definition.key).filter(Boolean))
|
|
2733
|
+
for (const key of Object.keys(projectedCoreValues)) {
|
|
2734
|
+
if (!allowedKeys.has(key)) delete projectedCoreValues[key]
|
|
2735
|
+
}
|
|
2736
|
+
}
|
|
2725
2737
|
coreSubmitValues = schema
|
|
2726
2738
|
? schema.parse(collapseDotPathFields(projectedCoreValues, dotPathBaseFieldIds))
|
|
2727
2739
|
: (projectedCoreValues as TValues)
|
|
@@ -275,6 +275,73 @@ describe('CrudForm custom field loading', () => {
|
|
|
275
275
|
expect(container.querySelector('[data-crud-field-id="cf_renewal_quarter"]')?.textContent).toContain('Q3')
|
|
276
276
|
})
|
|
277
277
|
|
|
278
|
+
it('submits custom entity values without loaded record metadata', async () => {
|
|
279
|
+
const handleSubmit = jest.fn().mockResolvedValue(undefined)
|
|
280
|
+
|
|
281
|
+
buildFormFieldFromCustomFieldDefMock.mockImplementation((definition: any) => ({
|
|
282
|
+
id: definition.key,
|
|
283
|
+
label: definition.label ?? definition.key,
|
|
284
|
+
type: 'select',
|
|
285
|
+
multiple: true,
|
|
286
|
+
listbox: true,
|
|
287
|
+
options: [
|
|
288
|
+
{ value: 'north', label: 'North' },
|
|
289
|
+
{ value: 'south', label: 'South' },
|
|
290
|
+
],
|
|
291
|
+
}))
|
|
292
|
+
fetchCustomFieldFormStructureMock.mockResolvedValue({
|
|
293
|
+
fields: [],
|
|
294
|
+
definitions: [
|
|
295
|
+
{
|
|
296
|
+
entityId: 'user:qa_entity',
|
|
297
|
+
key: 'regions',
|
|
298
|
+
label: 'Regions',
|
|
299
|
+
kind: 'dictionary',
|
|
300
|
+
multi: true,
|
|
301
|
+
},
|
|
302
|
+
],
|
|
303
|
+
metadata: {
|
|
304
|
+
items: [],
|
|
305
|
+
fieldsetsByEntity: {},
|
|
306
|
+
entitySettings: {},
|
|
307
|
+
},
|
|
308
|
+
})
|
|
309
|
+
|
|
310
|
+
renderWithProviders(
|
|
311
|
+
<CrudForm
|
|
312
|
+
title="Form"
|
|
313
|
+
entityId="user:qa_entity"
|
|
314
|
+
fields={[]}
|
|
315
|
+
customEntity
|
|
316
|
+
initialValues={{
|
|
317
|
+
id: '123e4567-e89b-12d3-a456-426614174000',
|
|
318
|
+
regions: ['north', 'south'],
|
|
319
|
+
updatedAt: '2026-06-19T10:00:00.000Z',
|
|
320
|
+
createdAt: '2026-06-19T09:00:00.000Z',
|
|
321
|
+
}}
|
|
322
|
+
onSubmit={handleSubmit}
|
|
323
|
+
/>,
|
|
324
|
+
{
|
|
325
|
+
dict: {
|
|
326
|
+
'ui.forms.actions.save': 'Save',
|
|
327
|
+
},
|
|
328
|
+
},
|
|
329
|
+
)
|
|
330
|
+
|
|
331
|
+
await waitFor(() => {
|
|
332
|
+
expect(screen.getByText('North')).toBeInTheDocument()
|
|
333
|
+
})
|
|
334
|
+
|
|
335
|
+
await act(async () => {
|
|
336
|
+
fireEvent.click(screen.getAllByRole('button', { name: 'Save' })[0]!)
|
|
337
|
+
})
|
|
338
|
+
|
|
339
|
+
await waitFor(() => {
|
|
340
|
+
expect(handleSubmit).toHaveBeenCalledTimes(1)
|
|
341
|
+
})
|
|
342
|
+
expect(handleSubmit).toHaveBeenCalledWith({ regions: ['north', 'south'] }, expect.any(Object))
|
|
343
|
+
})
|
|
344
|
+
|
|
278
345
|
it('opens the field manager without submitting the parent form', async () => {
|
|
279
346
|
const handleSubmit = jest.fn().mockResolvedValue(undefined)
|
|
280
347
|
|
|
@@ -24,6 +24,13 @@ describe('buildFilterDefsFromCustomFields', () => {
|
|
|
24
24
|
],
|
|
25
25
|
multi: true,
|
|
26
26
|
},
|
|
27
|
+
{
|
|
28
|
+
key: 'regions',
|
|
29
|
+
kind: 'dictionary',
|
|
30
|
+
filterable: true,
|
|
31
|
+
optionsUrl: '/api/dictionaries/dictionary-1/entries',
|
|
32
|
+
multi: true,
|
|
33
|
+
},
|
|
27
34
|
{ key: 'notes', kind: 'multiline', filterable: true },
|
|
28
35
|
{ key: 'hidden', kind: 'text', filterable: false },
|
|
29
36
|
]
|
|
@@ -44,6 +51,11 @@ describe('buildFilterDefsFromCustomFields', () => {
|
|
|
44
51
|
if (labels.type !== 'select') throw new Error('expected select')
|
|
45
52
|
expect(labels.multiple).toBe(true)
|
|
46
53
|
expect((labels.options || []).map((o) => o.value)).toEqual(['bug','feature'])
|
|
54
|
+
const regions = out.find(f => f.id === 'cf_regionsIn')!
|
|
55
|
+
expect(regions.type).toBe('select')
|
|
56
|
+
if (regions.type !== 'select') throw new Error('expected select')
|
|
57
|
+
expect(regions.multiple).toBe(true)
|
|
58
|
+
expect(typeof regions.loadOptions).toBe('function')
|
|
47
59
|
// text-like (multiline) => text
|
|
48
60
|
expect(out.find(f => f.id === 'cf_notes')!.type).toBe('text')
|
|
49
61
|
// non-filterable omitted
|
|
@@ -1,7 +1,12 @@
|
|
|
1
1
|
import { buildFormFieldsFromCustomFields } from '../utils/customFieldForms'
|
|
2
2
|
import type { CustomFieldDefDto } from '../utils/customFieldFilters'
|
|
3
|
+
import { FieldRegistry } from '../fields/registry'
|
|
3
4
|
|
|
4
5
|
describe('buildFormFieldsFromCustomFields', () => {
|
|
6
|
+
beforeAll(() => {
|
|
7
|
+
FieldRegistry.register('dictionary', { input: () => null })
|
|
8
|
+
})
|
|
9
|
+
|
|
5
10
|
it('maps kinds to CrudField and filters by formEditable', () => {
|
|
6
11
|
const defs: CustomFieldDefDto[] = [
|
|
7
12
|
{ key: 'blocked', kind: 'boolean', filterable: true, formEditable: true },
|
|
@@ -31,6 +36,23 @@ describe('buildFormFieldsFromCustomFields', () => {
|
|
|
31
36
|
{ key: 'notes', kind: 'multiline', filterable: false, formEditable: true },
|
|
32
37
|
// text with editor hint should render richtext
|
|
33
38
|
{ key: 'desc', kind: 'text', filterable: false, formEditable: true, editor: 'htmlRichText' },
|
|
39
|
+
{
|
|
40
|
+
key: 'region',
|
|
41
|
+
kind: 'dictionary',
|
|
42
|
+
dictionaryId: 'dictionary-1',
|
|
43
|
+
optionsUrl: '/api/dictionaries/dictionary-1/entries',
|
|
44
|
+
filterable: true,
|
|
45
|
+
formEditable: true,
|
|
46
|
+
},
|
|
47
|
+
{
|
|
48
|
+
key: 'regions',
|
|
49
|
+
kind: 'dictionary',
|
|
50
|
+
dictionaryId: 'dictionary-1',
|
|
51
|
+
optionsUrl: '/api/dictionaries/dictionary-1/entries',
|
|
52
|
+
multi: true,
|
|
53
|
+
filterable: true,
|
|
54
|
+
formEditable: true,
|
|
55
|
+
},
|
|
34
56
|
{ key: 'hidden', kind: 'text', filterable: true, formEditable: false },
|
|
35
57
|
]
|
|
36
58
|
|
|
@@ -49,6 +71,13 @@ describe('buildFormFieldsFromCustomFields', () => {
|
|
|
49
71
|
if (byId['cf_desc']?.type === 'richtext') {
|
|
50
72
|
expect(byId['cf_desc'].editor).toBe('html')
|
|
51
73
|
}
|
|
74
|
+
expect(byId['cf_region']?.type).toBe('custom')
|
|
75
|
+
expect(byId['cf_regions']?.type).toBe('select')
|
|
76
|
+
if (byId['cf_regions']?.type === 'select') {
|
|
77
|
+
expect(byId['cf_regions'].multiple).toBe(true)
|
|
78
|
+
expect(byId['cf_regions'].listbox).toBe(true)
|
|
79
|
+
expect(typeof byId['cf_regions'].loadOptions).toBe('function')
|
|
80
|
+
}
|
|
52
81
|
expect(byId['cf_hidden']).toBeUndefined()
|
|
53
82
|
})
|
|
54
83
|
})
|
|
@@ -5,9 +5,14 @@ jest.mock('../../utils/api', () => ({
|
|
|
5
5
|
import { act, renderHook } from '@testing-library/react'
|
|
6
6
|
import * as React from 'react'
|
|
7
7
|
import type { NotificationDto } from '@open-mercato/shared/modules/notifications/types'
|
|
8
|
+
import { I18nProvider } from '@open-mercato/shared/lib/i18n/context'
|
|
8
9
|
import { apiFetch } from '../../utils/api'
|
|
9
10
|
import { useNotificationActions } from '../useNotificationActions'
|
|
10
11
|
|
|
12
|
+
function I18nWrapper({ children }: { children: React.ReactNode }) {
|
|
13
|
+
return React.createElement(I18nProvider, { locale: 'en', dict: {} }, children)
|
|
14
|
+
}
|
|
15
|
+
|
|
11
16
|
function makeNotification(id: string): NotificationDto {
|
|
12
17
|
return {
|
|
13
18
|
id,
|
|
@@ -39,8 +44,9 @@ function setFetchResult(status: number) {
|
|
|
39
44
|
function renderActions(notifications: NotificationDto[]) {
|
|
40
45
|
const setNotifications = jest.fn()
|
|
41
46
|
const setUnreadCount = jest.fn()
|
|
42
|
-
const hook = renderHook(
|
|
43
|
-
useNotificationActions(notifications, setNotifications, setUnreadCount),
|
|
47
|
+
const hook = renderHook(
|
|
48
|
+
() => useNotificationActions(notifications, setNotifications, setUnreadCount),
|
|
49
|
+
{ wrapper: I18nWrapper },
|
|
44
50
|
)
|
|
45
51
|
return { hook, setNotifications, setUnreadCount }
|
|
46
52
|
}
|