@asteby/metacore-notifications 2.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/LICENSE +201 -0
- package/README.md +87 -0
- package/dist/dropdown.d.ts +14 -0
- package/dist/dropdown.d.ts.map +1 -0
- package/dist/dropdown.js +251 -0
- package/dist/dropdown.js.map +1 -0
- package/dist/hooks.d.ts +26 -0
- package/dist/hooks.d.ts.map +1 -0
- package/dist/hooks.js +81 -0
- package/dist/hooks.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +3 -0
- package/dist/index.js.map +1 -0
- package/dist/types.d.ts +104 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +2 -0
- package/dist/types.js.map +1 -0
- package/package.json +64 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for describing the origin of the Work and
|
|
141
|
+
reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 Asteby, Inc.
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
# @asteby/metacore-notifications
|
|
2
|
+
|
|
3
|
+
Metacore notifications kit — a drop-in bell-icon dropdown, app-badge hook
|
|
4
|
+
(Badging API) and WebSocket integration for real-time push updates.
|
|
5
|
+
|
|
6
|
+
## Install
|
|
7
|
+
|
|
8
|
+
```bash
|
|
9
|
+
pnpm add @asteby/metacore-notifications \
|
|
10
|
+
@asteby/metacore-ui @asteby/metacore-websocket \
|
|
11
|
+
date-fns lucide-react sonner @tanstack/react-query react react-dom
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
This package declares its UI, WebSocket, date, icon and toast libraries as
|
|
15
|
+
`peerDependencies` — the consumer installs them once at the app level.
|
|
16
|
+
|
|
17
|
+
## Usage
|
|
18
|
+
|
|
19
|
+
```tsx
|
|
20
|
+
import { NotificationsDropdown } from '@asteby/metacore-notifications/dropdown'
|
|
21
|
+
import { WebSocketProvider } from '@asteby/metacore-websocket/provider'
|
|
22
|
+
import { api } from '@/lib/api' // your injected axios-compatible client
|
|
23
|
+
import { useNavigate } from '@tanstack/react-router'
|
|
24
|
+
|
|
25
|
+
export function Header() {
|
|
26
|
+
const navigate = useNavigate()
|
|
27
|
+
return (
|
|
28
|
+
<WebSocketProvider url="wss://api.example.com/ws" getToken={getToken}>
|
|
29
|
+
<NotificationsDropdown
|
|
30
|
+
apiClient={api}
|
|
31
|
+
apiBasePath="/data/notifications/me"
|
|
32
|
+
enableBadge
|
|
33
|
+
onNotificationClick={(n) => {
|
|
34
|
+
if (n.link) navigate({ to: n.link })
|
|
35
|
+
else if (n.conversation_id)
|
|
36
|
+
navigate({ to: '/chats', search: { id: n.conversation_id } })
|
|
37
|
+
}}
|
|
38
|
+
/>
|
|
39
|
+
</WebSocketProvider>
|
|
40
|
+
)
|
|
41
|
+
}
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
`apiBasePath` is the only difference between the `ops` and `link` frontends:
|
|
45
|
+
|
|
46
|
+
- `ops`: `"/data/notifications/me"`
|
|
47
|
+
- `link`: `"/dynamic/notifications/me"`
|
|
48
|
+
|
|
49
|
+
## Props
|
|
50
|
+
|
|
51
|
+
| Prop | Type | Default | Notes |
|
|
52
|
+
|----------------------------|-------------------------------------------|----------|-------|
|
|
53
|
+
| `apiClient` | `NotificationsApiClient` (axios-compatible) | — | Never imported as a singleton — inject it. |
|
|
54
|
+
| `apiBasePath` | `string` | — | e.g. `/data/notifications/me`. |
|
|
55
|
+
| `enableBadge` | `boolean` | `true` | Drives `navigator.setAppBadge()`. |
|
|
56
|
+
| `onNotificationClick` | `(n: NotificationItem) => void` | — | Navigate however you like. |
|
|
57
|
+
| `perPage` | `number` | `20` | Initial fetch size. |
|
|
58
|
+
| `locale` | `date-fns` `Locale` | `es` | Used by `formatDistanceToNow`. |
|
|
59
|
+
| `labels` | `Partial<NotificationsDropdownLabels>` | — | i18n overrides. |
|
|
60
|
+
| `subscribeToNotifications` | `(onMessage) => void \| () => void` | — | Bring-your-own subscription (skips `useWebSocketMessage`). |
|
|
61
|
+
|
|
62
|
+
## Hooks
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
import { useAppBadge, useNotifications } from '@asteby/metacore-notifications/hooks'
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
- `useAppBadge()` → `{ badgeCount, setBadge, clearBadge }` — wraps the
|
|
69
|
+
PWA Badging API with a no-op fallback.
|
|
70
|
+
- `useNotifications()` → `{ permission, isSupported, requestPermission,
|
|
71
|
+
isGranted, isDenied, isDefault }` — tracks the browser's
|
|
72
|
+
`Notification.permission` state.
|
|
73
|
+
|
|
74
|
+
## API contract
|
|
75
|
+
|
|
76
|
+
The component expects the injected HTTP client to behave like axios:
|
|
77
|
+
|
|
78
|
+
- `GET {apiBasePath}` with query `{ orderBy, orderDir, per_page }`
|
|
79
|
+
returning `{ data: { data: NotificationItem[] } }`.
|
|
80
|
+
- `PATCH {apiBasePath}/{id}` with body `{ is_read: true }`.
|
|
81
|
+
|
|
82
|
+
WebSocket messages are expected under the discriminator `type: 'NOTIFICATION'`
|
|
83
|
+
with a payload shaped like `NotificationWsPayload`.
|
|
84
|
+
|
|
85
|
+
## License
|
|
86
|
+
|
|
87
|
+
Apache-2.0
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { NotificationsDropdownProps } from './types';
|
|
2
|
+
/**
|
|
3
|
+
* Bell-icon dropdown that lists the authenticated user's notifications,
|
|
4
|
+
* marks them read, shows an unread counter (and optional PWA app badge),
|
|
5
|
+
* and streams new items pushed over WebSocket under the `NOTIFICATION`
|
|
6
|
+
* message type.
|
|
7
|
+
*
|
|
8
|
+
* This component is transport-agnostic: the HTTP client is injected via
|
|
9
|
+
* `apiClient`. The collection base path is injected via `apiBasePath` —
|
|
10
|
+
* the component fetches `GET {apiBasePath}?orderBy=created_at&...` and
|
|
11
|
+
* mutates items via `PATCH {apiBasePath}/{id}`.
|
|
12
|
+
*/
|
|
13
|
+
export declare function NotificationsDropdown({ apiClient, apiBasePath, enableBadge, onNotificationClick, perPage, locale, labels: labelsOverride, subscribeToNotifications, }: NotificationsDropdownProps): import("react/jsx-runtime").JSX.Element;
|
|
14
|
+
//# sourceMappingURL=dropdown.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dropdown.d.ts","sourceRoot":"","sources":["../src/dropdown.tsx"],"names":[],"mappings":"AAkBA,OAAO,KAAK,EAIV,0BAA0B,EAC3B,MAAM,SAAS,CAAA;AA6DhB;;;;;;;;;;GAUG;AACH,wBAAgB,qBAAqB,CAAC,EACpC,SAAS,EACT,WAAW,EACX,WAAkB,EAClB,mBAAmB,EACnB,OAAY,EACZ,MAAW,EACX,MAAM,EAAE,cAAc,EACtB,wBAAwB,GACzB,EAAE,0BAA0B,2CA+K5B"}
|
package/dist/dropdown.js
ADDED
|
@@ -0,0 +1,251 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-runtime";
|
|
2
|
+
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
|
3
|
+
import * as LucideIcons from 'lucide-react';
|
|
4
|
+
import { Button, DropdownMenu, DropdownMenuContent, DropdownMenuGroup, DropdownMenuItem, DropdownMenuLabel, DropdownMenuTrigger, } from '@asteby/metacore-ui/primitives';
|
|
5
|
+
import { useWebSocketMessage } from '@asteby/metacore-websocket/hooks';
|
|
6
|
+
import { formatDistanceToNow } from 'date-fns';
|
|
7
|
+
import { es } from 'date-fns/locale';
|
|
8
|
+
import { toast } from 'sonner';
|
|
9
|
+
import { useAppBadge } from './hooks';
|
|
10
|
+
/** Convert kebab-case to PascalCase ("message-circle" -> "MessageCircle"). */
|
|
11
|
+
const toPascalCase = (str) => str
|
|
12
|
+
.split('-')
|
|
13
|
+
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
|
|
14
|
+
.join('');
|
|
15
|
+
const DEFAULT_LABELS = {
|
|
16
|
+
title: 'Notificaciones',
|
|
17
|
+
newBadge: (count) => `${count} nuevas`,
|
|
18
|
+
empty: 'No tienes notificaciones',
|
|
19
|
+
markAllAsRead: 'Marcar todo como leído',
|
|
20
|
+
enableNotifications: 'Activar notificaciones',
|
|
21
|
+
notificationsEnabled: '¡Notificaciones activadas!',
|
|
22
|
+
permissionsBlocked: 'Permisos bloqueados por el navegador',
|
|
23
|
+
permissionsBlockedDescription: 'Debes habilitarlas desde el icono en la barra de direcciones.',
|
|
24
|
+
permissionRequestFailed: 'No se pudo abrir la solicitud de permisos',
|
|
25
|
+
permissionRequired: 'Permisos requeridos',
|
|
26
|
+
srLabel: 'Notificaciones',
|
|
27
|
+
};
|
|
28
|
+
const getIconFor = (notification) => {
|
|
29
|
+
if (notification.icon) {
|
|
30
|
+
const pascalName = toPascalCase(notification.icon);
|
|
31
|
+
const DynamicIcon = LucideIcons[pascalName];
|
|
32
|
+
if (DynamicIcon)
|
|
33
|
+
return DynamicIcon;
|
|
34
|
+
}
|
|
35
|
+
switch (notification.type) {
|
|
36
|
+
case 'warning':
|
|
37
|
+
return LucideIcons.AlertTriangle;
|
|
38
|
+
case 'success':
|
|
39
|
+
return LucideIcons.CheckCircle2;
|
|
40
|
+
case 'error':
|
|
41
|
+
return LucideIcons.XCircle;
|
|
42
|
+
case 'info':
|
|
43
|
+
default:
|
|
44
|
+
return LucideIcons.Info;
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
const getStyle = (type) => {
|
|
48
|
+
switch (type) {
|
|
49
|
+
case 'warning':
|
|
50
|
+
return 'bg-amber-500 text-white';
|
|
51
|
+
case 'success':
|
|
52
|
+
return 'bg-emerald-500 text-white';
|
|
53
|
+
case 'error':
|
|
54
|
+
return 'bg-red-500 text-white';
|
|
55
|
+
case 'info':
|
|
56
|
+
default:
|
|
57
|
+
return 'bg-blue-500 text-white';
|
|
58
|
+
}
|
|
59
|
+
};
|
|
60
|
+
/**
|
|
61
|
+
* Bell-icon dropdown that lists the authenticated user's notifications,
|
|
62
|
+
* marks them read, shows an unread counter (and optional PWA app badge),
|
|
63
|
+
* and streams new items pushed over WebSocket under the `NOTIFICATION`
|
|
64
|
+
* message type.
|
|
65
|
+
*
|
|
66
|
+
* This component is transport-agnostic: the HTTP client is injected via
|
|
67
|
+
* `apiClient`. The collection base path is injected via `apiBasePath` —
|
|
68
|
+
* the component fetches `GET {apiBasePath}?orderBy=created_at&...` and
|
|
69
|
+
* mutates items via `PATCH {apiBasePath}/{id}`.
|
|
70
|
+
*/
|
|
71
|
+
export function NotificationsDropdown({ apiClient, apiBasePath, enableBadge = true, onNotificationClick, perPage = 20, locale = es, labels: labelsOverride, subscribeToNotifications, }) {
|
|
72
|
+
const labels = useMemo(() => ({ ...DEFAULT_LABELS, ...labelsOverride }), [labelsOverride]);
|
|
73
|
+
const [notifications, setNotifications] = useState([]);
|
|
74
|
+
const [unreadCount, setUnreadCount] = useState(0);
|
|
75
|
+
const [, setLoading] = useState(false);
|
|
76
|
+
const { setBadge } = useAppBadge();
|
|
77
|
+
// Keep fetch callbacks stable across apiClient / basePath changes.
|
|
78
|
+
const apiClientRef = useRef(apiClient);
|
|
79
|
+
apiClientRef.current = apiClient;
|
|
80
|
+
const basePathRef = useRef(apiBasePath);
|
|
81
|
+
basePathRef.current = apiBasePath;
|
|
82
|
+
useEffect(() => {
|
|
83
|
+
if (!enableBadge)
|
|
84
|
+
return;
|
|
85
|
+
setBadge(unreadCount);
|
|
86
|
+
}, [unreadCount, setBadge, enableBadge]);
|
|
87
|
+
const fetchNotifications = useCallback(async () => {
|
|
88
|
+
try {
|
|
89
|
+
setLoading(true);
|
|
90
|
+
const response = await apiClientRef.current.get(basePathRef.current, {
|
|
91
|
+
params: {
|
|
92
|
+
orderBy: 'created_at',
|
|
93
|
+
orderDir: 'desc',
|
|
94
|
+
per_page: perPage,
|
|
95
|
+
},
|
|
96
|
+
});
|
|
97
|
+
const items = response.data?.data ?? [];
|
|
98
|
+
setNotifications(items);
|
|
99
|
+
setUnreadCount(items.filter((n) => !n.is_read).length);
|
|
100
|
+
}
|
|
101
|
+
catch (error) {
|
|
102
|
+
// eslint-disable-next-line no-console
|
|
103
|
+
console.error('Failed to fetch notifications:', error);
|
|
104
|
+
}
|
|
105
|
+
finally {
|
|
106
|
+
setLoading(false);
|
|
107
|
+
}
|
|
108
|
+
}, [perPage]);
|
|
109
|
+
useEffect(() => {
|
|
110
|
+
fetchNotifications();
|
|
111
|
+
}, [fetchNotifications, apiBasePath]);
|
|
112
|
+
// Normalise an incoming WS payload + prepend it to the list.
|
|
113
|
+
const ingestWsPayload = useCallback((payload) => {
|
|
114
|
+
const newNotification = {
|
|
115
|
+
id: payload.id || (typeof crypto !== 'undefined' && 'randomUUID' in crypto
|
|
116
|
+
? crypto.randomUUID()
|
|
117
|
+
: `${Date.now()}-${Math.random()}`),
|
|
118
|
+
title: payload.title,
|
|
119
|
+
message: payload.body || payload.message || payload.description || '',
|
|
120
|
+
type: payload.type || 'info',
|
|
121
|
+
is_read: false,
|
|
122
|
+
created_at: new Date().toISOString(),
|
|
123
|
+
link: payload.link,
|
|
124
|
+
icon: payload.icon,
|
|
125
|
+
image: payload.image,
|
|
126
|
+
metadata: payload.metadata,
|
|
127
|
+
conversation_id: payload.conversation_id,
|
|
128
|
+
};
|
|
129
|
+
setNotifications((prev) => [newNotification, ...prev]);
|
|
130
|
+
setUnreadCount((prev) => prev + 1);
|
|
131
|
+
if (typeof window !== 'undefined' &&
|
|
132
|
+
'Notification' in window &&
|
|
133
|
+
Notification.permission !== 'granted') {
|
|
134
|
+
window.dispatchEvent(new CustomEvent('show-notification-prompt'));
|
|
135
|
+
}
|
|
136
|
+
}, []);
|
|
137
|
+
// WebSocket wiring: use provided hook unless caller supplies a custom
|
|
138
|
+
// subscription. We always run one of the two branches exactly once.
|
|
139
|
+
const useCustomSubscription = Boolean(subscribeToNotifications);
|
|
140
|
+
useEffect(() => {
|
|
141
|
+
if (!useCustomSubscription || !subscribeToNotifications)
|
|
142
|
+
return;
|
|
143
|
+
const unsub = subscribeToNotifications(ingestWsPayload);
|
|
144
|
+
return () => {
|
|
145
|
+
if (typeof unsub === 'function')
|
|
146
|
+
unsub();
|
|
147
|
+
};
|
|
148
|
+
}, [useCustomSubscription, subscribeToNotifications, ingestWsPayload]);
|
|
149
|
+
// Hooks must be called unconditionally. When the caller overrides the
|
|
150
|
+
// subscription we still call `useWebSocketMessage` but with a no-op —
|
|
151
|
+
// this requires a provider in context even when unused, so we skip it
|
|
152
|
+
// entirely via a separate component when override is present.
|
|
153
|
+
return useCustomSubscription ? (_jsx(DropdownShell, { labels: labels, locale: locale, notifications: notifications, unreadCount: unreadCount, onMarkAsRead: async (id) => {
|
|
154
|
+
setNotifications((prev) => prev.map((n) => (n.id === id ? { ...n, is_read: true } : n)));
|
|
155
|
+
setUnreadCount((prev) => Math.max(0, prev - 1));
|
|
156
|
+
try {
|
|
157
|
+
await apiClientRef.current.patch(`${basePathRef.current}/${id}`, {
|
|
158
|
+
is_read: true,
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
catch (error) {
|
|
162
|
+
// eslint-disable-next-line no-console
|
|
163
|
+
console.error('Failed to mark notification as read:', error);
|
|
164
|
+
}
|
|
165
|
+
}, onMarkAllAsRead: async () => {
|
|
166
|
+
const unreadIds = notifications.filter((n) => !n.is_read).map((n) => n.id);
|
|
167
|
+
setNotifications((prev) => prev.map((n) => ({ ...n, is_read: true })));
|
|
168
|
+
setUnreadCount(0);
|
|
169
|
+
try {
|
|
170
|
+
await Promise.all(unreadIds.map((id) => apiClientRef.current.patch(`${basePathRef.current}/${id}`, {
|
|
171
|
+
is_read: true,
|
|
172
|
+
})));
|
|
173
|
+
}
|
|
174
|
+
catch (error) {
|
|
175
|
+
// eslint-disable-next-line no-console
|
|
176
|
+
console.error('Failed to mark all as read:', error);
|
|
177
|
+
}
|
|
178
|
+
}, onNotificationClick: onNotificationClick })) : (_jsx(DropdownWithWebSocket, { labels: labels, locale: locale, notifications: notifications, unreadCount: unreadCount, ingestWsPayload: ingestWsPayload, onMarkAsRead: async (id) => {
|
|
179
|
+
setNotifications((prev) => prev.map((n) => (n.id === id ? { ...n, is_read: true } : n)));
|
|
180
|
+
setUnreadCount((prev) => Math.max(0, prev - 1));
|
|
181
|
+
try {
|
|
182
|
+
await apiClientRef.current.patch(`${basePathRef.current}/${id}`, {
|
|
183
|
+
is_read: true,
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
catch (error) {
|
|
187
|
+
// eslint-disable-next-line no-console
|
|
188
|
+
console.error('Failed to mark notification as read:', error);
|
|
189
|
+
}
|
|
190
|
+
}, onMarkAllAsRead: async () => {
|
|
191
|
+
const unreadIds = notifications.filter((n) => !n.is_read).map((n) => n.id);
|
|
192
|
+
setNotifications((prev) => prev.map((n) => ({ ...n, is_read: true })));
|
|
193
|
+
setUnreadCount(0);
|
|
194
|
+
try {
|
|
195
|
+
await Promise.all(unreadIds.map((id) => apiClientRef.current.patch(`${basePathRef.current}/${id}`, {
|
|
196
|
+
is_read: true,
|
|
197
|
+
})));
|
|
198
|
+
}
|
|
199
|
+
catch (error) {
|
|
200
|
+
// eslint-disable-next-line no-console
|
|
201
|
+
console.error('Failed to mark all as read:', error);
|
|
202
|
+
}
|
|
203
|
+
}, onNotificationClick: onNotificationClick }));
|
|
204
|
+
}
|
|
205
|
+
function DropdownWithWebSocket({ ingestWsPayload, ...rest }) {
|
|
206
|
+
useWebSocketMessage('NOTIFICATION', (message) => {
|
|
207
|
+
if (message.payload)
|
|
208
|
+
ingestWsPayload(message.payload);
|
|
209
|
+
});
|
|
210
|
+
return _jsx(DropdownShell, { ...rest });
|
|
211
|
+
}
|
|
212
|
+
function DropdownShell({ labels, locale, notifications, unreadCount, onMarkAsRead, onMarkAllAsRead, onNotificationClick, }) {
|
|
213
|
+
const notificationApiAvailable = typeof window !== 'undefined' && 'Notification' in window;
|
|
214
|
+
const permission = notificationApiAvailable
|
|
215
|
+
? Notification.permission
|
|
216
|
+
: null;
|
|
217
|
+
return (_jsxs(DropdownMenu, { children: [_jsx(DropdownMenuTrigger, { asChild: true, children: _jsxs(Button, { variant: 'ghost', size: 'icon', className: 'relative', children: [notificationApiAvailable && permission !== 'granted' ? (_jsxs("div", { className: 'relative', children: [_jsx(LucideIcons.BellOff, { className: 'h-[1.2rem] w-[1.2rem] text-muted-foreground' }), permission === 'default' && (_jsx("span", { className: 'absolute -top-1 -right-1 h-2.5 w-2.5 rounded-full bg-yellow-500 ring-2 ring-background', title: labels.permissionRequired }))] })) : (_jsx(LucideIcons.Bell, { className: 'h-[1.2rem] w-[1.2rem] text-foreground' })), unreadCount > 0 && (_jsxs("span", { className: 'absolute -top-1 -right-1 flex h-5 w-5 items-center justify-center rounded-full bg-primary text-[10px] font-bold text-primary-foreground shadow-sm ring-2 ring-background', children: [unreadCount, _jsx("span", { className: 'animate-ping absolute inline-flex h-full w-full rounded-full bg-primary opacity-75' })] })), _jsx("span", { className: 'sr-only', children: labels.srLabel })] }) }), _jsxs(DropdownMenuContent, { className: 'w-85 sm:w-96 p-0', align: 'end', forceMount: true, children: [_jsx(DropdownMenuLabel, { className: 'p-4 font-normal border-b', children: _jsxs("div", { className: 'flex items-center justify-between', children: [_jsx("p", { className: 'text-sm font-semibold', children: labels.title }), unreadCount > 0 && (_jsx("span", { className: 'rounded-full bg-primary/10 px-2 py-0.5 text-xs font-medium text-primary', children: labels.newBadge(unreadCount) }))] }) }), _jsx(DropdownMenuGroup, { className: 'max-h-[350px] overflow-y-auto', children: notifications.length === 0 ? (_jsx("div", { className: 'p-8 text-center text-muted-foreground text-sm', children: labels.empty })) : (notifications.map((notification) => {
|
|
218
|
+
const Icon = getIconFor(notification);
|
|
219
|
+
return (_jsx(DropdownMenuItem, { className: 'cursor-pointer p-3 sm:p-4 focus:bg-muted/50 data-[state=open]:bg-muted/50', onClick: () => {
|
|
220
|
+
if (!notification.is_read)
|
|
221
|
+
onMarkAsRead(notification.id);
|
|
222
|
+
if (onNotificationClick) {
|
|
223
|
+
onNotificationClick(notification);
|
|
224
|
+
}
|
|
225
|
+
else if (notification.link &&
|
|
226
|
+
notification.link.startsWith('http')) {
|
|
227
|
+
window.open(notification.link, '_blank');
|
|
228
|
+
}
|
|
229
|
+
}, children: _jsxs("div", { className: 'flex items-start gap-4 w-full', children: [_jsx("div", { className: 'relative shrink-0', children: notification.image ? (_jsxs(_Fragment, { children: [_jsx("img", { src: notification.image, alt: 'Avatar', className: 'h-10 w-10 rounded-full object-cover border border-muted/40 shadow-sm' }), _jsx("div", { className: 'absolute -bottom-1 -right-1 flex h-5 w-5 items-center justify-center rounded-full bg-background ring-1 ring-border text-primary shadow-sm', children: _jsx(Icon, { className: 'h-[10px] w-[10px] text-current', strokeWidth: 3 }) })] })) : (_jsx("div", { className: `flex h-10 w-10 items-center justify-center rounded-full shadow-sm ring-1 ring-inset ring-black/5 ${getStyle(notification.type)}`, children: _jsx(Icon, { className: 'h-5 w-5 text-white', strokeWidth: 2.5 }) })) }), _jsxs("div", { className: 'flex flex-col gap-1 w-full min-w-0', children: [_jsxs("div", { className: 'flex items-center justify-between gap-2', children: [_jsx("p", { className: `text-sm leading-none truncate ${!notification.is_read ? 'font-semibold text-foreground' : 'text-muted-foreground'}`, children: notification.title }), _jsx("span", { className: 'text-[10px] text-muted-foreground whitespace-nowrap shrink-0', children: formatDistanceToNow(new Date(notification.created_at), {
|
|
230
|
+
addSuffix: true,
|
|
231
|
+
locale,
|
|
232
|
+
}) })] }), _jsx("p", { className: 'text-xs text-muted-foreground line-clamp-2 leading-relaxed', children: notification.message })] }), !notification.is_read && (_jsx("div", { className: 'self-center shrink-0', children: _jsx("div", { className: 'h-2.5 w-2.5 rounded-full bg-primary shadow-sm' }) }))] }) }, notification.id));
|
|
233
|
+
})) }), notifications.length > 0 && (_jsx("div", { className: 'p-2 border-t bg-muted/20', children: _jsx(Button, { variant: 'ghost', size: 'sm', className: 'w-full text-xs h-8', onClick: () => void onMarkAllAsRead(), children: labels.markAllAsRead }) })), notificationApiAvailable && permission !== 'granted' && (_jsx("div", { className: 'p-2 border-t bg-muted/20', children: _jsxs(Button, { variant: 'outline', size: 'sm', className: 'w-full text-xs h-8 gap-2 bg-primary/10 hover:bg-primary/20 text-primary border-primary/20', onClick: async () => {
|
|
234
|
+
try {
|
|
235
|
+
const next = await Notification.requestPermission();
|
|
236
|
+
if (next === 'granted') {
|
|
237
|
+
toast.success(labels.notificationsEnabled);
|
|
238
|
+
setTimeout(() => window.location.reload(), 1500);
|
|
239
|
+
}
|
|
240
|
+
else {
|
|
241
|
+
toast.error(labels.permissionsBlocked, {
|
|
242
|
+
description: labels.permissionsBlockedDescription,
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
catch {
|
|
247
|
+
toast.error(labels.permissionRequestFailed);
|
|
248
|
+
}
|
|
249
|
+
}, children: [_jsx(LucideIcons.BellRing, { className: 'h-3 w-3' }), labels.enableNotifications] }) }))] })] }));
|
|
250
|
+
}
|
|
251
|
+
//# sourceMappingURL=dropdown.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"dropdown.js","sourceRoot":"","sources":["../src/dropdown.tsx"],"names":[],"mappings":";AAAA,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAA;AACzE,OAAO,KAAK,WAAW,MAAM,cAAc,CAAA;AAC3C,OAAO,EACL,MAAM,EACN,YAAY,EACZ,mBAAmB,EACnB,iBAAiB,EACjB,gBAAgB,EAChB,iBAAiB,EACjB,mBAAmB,GACpB,MAAM,gCAAgC,CAAA;AACvC,OAAO,EAAE,mBAAmB,EAAE,MAAM,kCAAk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B,CAAA;AACH,CAAC"}
|
package/dist/hooks.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Drives `navigator.setAppBadge()` (Badging API) when available, gracefully
|
|
3
|
+
* degrading to a no-op on browsers that don't implement it.
|
|
4
|
+
*
|
|
5
|
+
* Returned `setBadge(count)` keeps a local counter in sync with the OS/PWA
|
|
6
|
+
* badge; passing `0` clears it. `clearBadge()` forces removal.
|
|
7
|
+
*/
|
|
8
|
+
export declare function useAppBadge(): {
|
|
9
|
+
badgeCount: number;
|
|
10
|
+
setBadge: (count: number) => void;
|
|
11
|
+
clearBadge: () => void;
|
|
12
|
+
};
|
|
13
|
+
/**
|
|
14
|
+
* Tracks the current `Notification.permission` state and exposes a helper
|
|
15
|
+
* to request it. Polls every second to detect out-of-band changes (e.g.
|
|
16
|
+
* the user toggling the permission from the browser's site settings).
|
|
17
|
+
*/
|
|
18
|
+
export declare function useNotifications(): {
|
|
19
|
+
permission: NotificationPermission;
|
|
20
|
+
isSupported: boolean;
|
|
21
|
+
requestPermission: () => Promise<boolean>;
|
|
22
|
+
isGranted: boolean;
|
|
23
|
+
isDenied: boolean;
|
|
24
|
+
isDefault: boolean;
|
|
25
|
+
};
|
|
26
|
+
//# sourceMappingURL=hooks.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hooks.d.ts","sourceRoot":"","sources":["../src/hooks.ts"],"names":[],"mappings":"AAYA;;;;;;GAMG;AACH,wBAAgB,WAAW;;sBAGY,MAAM;;EAoC5C;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB;;;;;;;EA+B/B"}
|
package/dist/hooks.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { useCallback, useEffect, useState } from 'react';
|
|
2
|
+
/**
|
|
3
|
+
* Drives `navigator.setAppBadge()` (Badging API) when available, gracefully
|
|
4
|
+
* degrading to a no-op on browsers that don't implement it.
|
|
5
|
+
*
|
|
6
|
+
* Returned `setBadge(count)` keeps a local counter in sync with the OS/PWA
|
|
7
|
+
* badge; passing `0` clears it. `clearBadge()` forces removal.
|
|
8
|
+
*/
|
|
9
|
+
export function useAppBadge() {
|
|
10
|
+
const [counter, setCounter] = useState(0);
|
|
11
|
+
const setBadge = useCallback((count) => {
|
|
12
|
+
setCounter(count);
|
|
13
|
+
if (typeof navigator === 'undefined')
|
|
14
|
+
return;
|
|
15
|
+
const nav = navigator;
|
|
16
|
+
if (typeof nav.setAppBadge === 'function') {
|
|
17
|
+
if (count > 0) {
|
|
18
|
+
nav.setAppBadge(count).catch((e) => {
|
|
19
|
+
// eslint-disable-next-line no-console
|
|
20
|
+
console.error('Error setting app badge:', e);
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
else if (typeof nav.clearAppBadge === 'function') {
|
|
24
|
+
nav.clearAppBadge().catch((e) => {
|
|
25
|
+
// eslint-disable-next-line no-console
|
|
26
|
+
console.error('Error clearing app badge:', e);
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
}, []);
|
|
31
|
+
const clearBadge = useCallback(() => {
|
|
32
|
+
setCounter(0);
|
|
33
|
+
if (typeof navigator === 'undefined')
|
|
34
|
+
return;
|
|
35
|
+
const nav = navigator;
|
|
36
|
+
if (typeof nav.clearAppBadge === 'function') {
|
|
37
|
+
nav.clearAppBadge().catch((e) => {
|
|
38
|
+
// eslint-disable-next-line no-console
|
|
39
|
+
console.error('Error clearing app badge:', e);
|
|
40
|
+
});
|
|
41
|
+
}
|
|
42
|
+
}, []);
|
|
43
|
+
return {
|
|
44
|
+
badgeCount: counter,
|
|
45
|
+
setBadge,
|
|
46
|
+
clearBadge,
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Tracks the current `Notification.permission` state and exposes a helper
|
|
51
|
+
* to request it. Polls every second to detect out-of-band changes (e.g.
|
|
52
|
+
* the user toggling the permission from the browser's site settings).
|
|
53
|
+
*/
|
|
54
|
+
export function useNotifications() {
|
|
55
|
+
const isSupported = typeof window !== 'undefined' && 'Notification' in window;
|
|
56
|
+
const [permission, setPermission] = useState(isSupported ? Notification.permission : 'default');
|
|
57
|
+
useEffect(() => {
|
|
58
|
+
if (!isSupported)
|
|
59
|
+
return;
|
|
60
|
+
const interval = setInterval(() => {
|
|
61
|
+
setPermission(Notification.permission);
|
|
62
|
+
}, 1000);
|
|
63
|
+
return () => clearInterval(interval);
|
|
64
|
+
}, [isSupported]);
|
|
65
|
+
const requestPermission = useCallback(async () => {
|
|
66
|
+
if (!isSupported)
|
|
67
|
+
return false;
|
|
68
|
+
const result = await Notification.requestPermission();
|
|
69
|
+
setPermission(result);
|
|
70
|
+
return result === 'granted';
|
|
71
|
+
}, [isSupported]);
|
|
72
|
+
return {
|
|
73
|
+
permission,
|
|
74
|
+
isSupported,
|
|
75
|
+
requestPermission,
|
|
76
|
+
isGranted: permission === 'granted',
|
|
77
|
+
isDenied: permission === 'denied',
|
|
78
|
+
isDefault: permission === 'default',
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
//# sourceMappingURL=hooks.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hooks.js","sourceRoot":"","sources":["../src/hooks.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAA;AAYxD;;;;;;GAMG;AACH,MAAM,UAAU,WAAW;IACzB,MAAM,CAAC,OAAO,EAAE,UAAU,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAA;IAEzC,MAAM,QAAQ,GAAG,WAAW,CAAC,CAAC,KAAa,EAAE,EAAE;QAC7C,UAAU,CAAC,KAAK,CAAC,CAAA;QACjB,IAAI,OAAO,SAAS,KAAK,WAAW;YAAE,OAAM;QAC5C,MAAM,GAAG,GAAG,SAAyC,CAAA;QACrD,IAAI,OAAO,GAAG,CAAC,WAAW,KAAK,UAAU,EAA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,EAAE,aAAa,CAAC,GAAG,QAAQ,CAC1C,WAAW,CAAC,CAAC,CAAC,YAAY,CAAC,UAAU,CAAC,CAAC,CAAC,SAAS,CAClD,CAAA;IAED,SAAS,CAAC,GAAG,EAAE;QACb,IAAI,CAAC,WAAW;YAAE,OAAM;QACxB,MAAM,QAAQ,GAAG,WAAW,CAAC,GAAG,EAAE;YAChC,aAAa,CAAC,YAAY,CAAC,UAAU,CAAC,CAAA;QACxC,CAAC,EAAE,IAAI,CAAC,CAAA;QACR,OAAO,GAAG,EAAE,CAAC,aAAa,CAAC,QAAQ,CAAC,CAAA;IACtC,CAAC,EAAE,CAAC,WAAW,CAAC,CAAC,CAAA;IAEjB,MAAM,iBAAiB,GAAG,WAAW,CAAC,KAAK,IAAI,EAAE;QAC/C,IAAI,CAAC,WAAW;YAAE,OAAO,KAAK,CAAA;QAC9B,MAAM,MAAM,GAAG,MAAM,YAAY,CAAC,iBAAiB,EAAE,CAAA;QACrD,aAAa,CAAC,MAAM,CAAC,CAAA;QACrB,OAAO,MAAM,KAAK,SAAS,CAAA;IAC7B,CAAC,EAAE,CAAC,WAAW,CAAC,CAAC,CAAA;IAEjB,OAAO;QACL,UAAU;QACV,WAAW;QACX,iBAAiB;QACjB,SAAS,EAAE,UAAU,KAAK,SAAS;QACnC,QAAQ,EAAE,UAAU,KAAK,QAAQ;QACjC,SAAS,EAAE,UAAU,KAAK,SAAS;KACpC,CAAA;AACH,CAAC"}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
export { NotificationsDropdown } from './dropdown';
|
|
2
|
+
export { useAppBadge, useNotifications } from './hooks';
|
|
3
|
+
export type { NotificationItem, NotificationType, NotificationsApiClient, NotificationWsPayload, NotificationsDropdownLabels, NotificationsDropdownProps, } from './types';
|
|
4
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAA;AAClD,OAAO,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA;AACvD,YAAY,EACV,gBAAgB,EAChB,gBAAgB,EAChB,sBAAsB,EACtB,qBAAqB,EACrB,2BAA2B,EAC3B,0BAA0B,GAC3B,MAAM,SAAS,CAAA"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAE,MAAM,YAAY,CAAA;AAClD,OAAO,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,SAAS,CAAA"}
|
package/dist/types.d.ts
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import type { Locale } from 'date-fns';
|
|
2
|
+
/**
|
|
3
|
+
* Severity of a notification. Drives default icon + colour palette when no
|
|
4
|
+
* custom `icon` is supplied in the payload.
|
|
5
|
+
*/
|
|
6
|
+
export type NotificationType = 'info' | 'success' | 'warning' | 'error';
|
|
7
|
+
/**
|
|
8
|
+
* Canonical shape of a notification as returned by the Metacore API and
|
|
9
|
+
* rendered inside the dropdown. Extra fields may be present on the wire and
|
|
10
|
+
* are tolerated (but ignored) by the component.
|
|
11
|
+
*/
|
|
12
|
+
export interface NotificationItem {
|
|
13
|
+
id: string;
|
|
14
|
+
title: string;
|
|
15
|
+
message: string;
|
|
16
|
+
type: NotificationType;
|
|
17
|
+
is_read: boolean;
|
|
18
|
+
created_at: string;
|
|
19
|
+
link?: string;
|
|
20
|
+
icon?: string;
|
|
21
|
+
image?: string;
|
|
22
|
+
metadata?: string;
|
|
23
|
+
conversation_id?: string;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Subset of an HTTP client (axios-compatible) used by the notifications
|
|
27
|
+
* package. Declared locally so consumers can inject any compatible client
|
|
28
|
+
* without this package depending on axios.
|
|
29
|
+
*/
|
|
30
|
+
export interface NotificationsApiClient {
|
|
31
|
+
get: <T = unknown>(url: string, config?: {
|
|
32
|
+
params?: Record<string, unknown>;
|
|
33
|
+
}) => Promise<{
|
|
34
|
+
data: T;
|
|
35
|
+
}>;
|
|
36
|
+
patch: <T = unknown>(url: string, data?: unknown) => Promise<{
|
|
37
|
+
data: T;
|
|
38
|
+
}>;
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Shape of a WebSocket `NOTIFICATION` payload. Consumers may provide any
|
|
42
|
+
* of these fields; the component normalises them into a `NotificationItem`.
|
|
43
|
+
*/
|
|
44
|
+
export interface NotificationWsPayload {
|
|
45
|
+
id?: string;
|
|
46
|
+
title: string;
|
|
47
|
+
body?: string;
|
|
48
|
+
message?: string;
|
|
49
|
+
description?: string;
|
|
50
|
+
type?: NotificationType;
|
|
51
|
+
link?: string;
|
|
52
|
+
icon?: string;
|
|
53
|
+
image?: string;
|
|
54
|
+
metadata?: string;
|
|
55
|
+
conversation_id?: string;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Strings used by the dropdown. Overridable for i18n. Defaults to Spanish.
|
|
59
|
+
*/
|
|
60
|
+
export interface NotificationsDropdownLabels {
|
|
61
|
+
title: string;
|
|
62
|
+
newBadge: (count: number) => string;
|
|
63
|
+
empty: string;
|
|
64
|
+
markAllAsRead: string;
|
|
65
|
+
enableNotifications: string;
|
|
66
|
+
notificationsEnabled: string;
|
|
67
|
+
permissionsBlocked: string;
|
|
68
|
+
permissionsBlockedDescription: string;
|
|
69
|
+
permissionRequestFailed: string;
|
|
70
|
+
permissionRequired: string;
|
|
71
|
+
srLabel: string;
|
|
72
|
+
}
|
|
73
|
+
export interface NotificationsDropdownProps {
|
|
74
|
+
/** Injected HTTP client (never imported as singleton). */
|
|
75
|
+
apiClient: NotificationsApiClient;
|
|
76
|
+
/**
|
|
77
|
+
* Base collection path for the current user's notifications. Typical
|
|
78
|
+
* values: `/data/notifications/me` (ops) or `/dynamic/notifications/me`
|
|
79
|
+
* (link). Items are mutated under `${apiBasePath}/${id}`.
|
|
80
|
+
*/
|
|
81
|
+
apiBasePath: string;
|
|
82
|
+
/** When true (default), updates `navigator.setAppBadge` with unread count. */
|
|
83
|
+
enableBadge?: boolean;
|
|
84
|
+
/**
|
|
85
|
+
* Invoked when the user clicks a notification. If omitted, the component
|
|
86
|
+
* falls back to `window.open` for absolute URLs and a no-op otherwise.
|
|
87
|
+
*/
|
|
88
|
+
onNotificationClick?: (notification: NotificationItem) => void;
|
|
89
|
+
/** Number of items fetched on the initial request. Defaults to 20. */
|
|
90
|
+
perPage?: number;
|
|
91
|
+
/** `date-fns` locale used for relative time formatting. */
|
|
92
|
+
locale?: Locale;
|
|
93
|
+
/** Override built-in labels (Spanish by default). */
|
|
94
|
+
labels?: Partial<NotificationsDropdownLabels>;
|
|
95
|
+
/**
|
|
96
|
+
* Optional override for WebSocket subscription. When supplied, the
|
|
97
|
+
* component does NOT call `useWebSocketMessage` and instead exposes the
|
|
98
|
+
* handler via this prop — useful when the app owns its own socket or when
|
|
99
|
+
* `@asteby/metacore-websocket` is unavailable. The caller must invoke
|
|
100
|
+
* `onMessage` with every incoming `NOTIFICATION` payload.
|
|
101
|
+
*/
|
|
102
|
+
subscribeToNotifications?: (onMessage: (payload: NotificationWsPayload) => void) => void | (() => void);
|
|
103
|
+
}
|
|
104
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,UAAU,CAAA;AAEtC;;;GAGG;AACH,MAAM,MAAM,gBAAgB,GAAG,MAAM,GAAG,SAAS,GAAG,SAAS,GAAG,OAAO,CAAA;AAEvE;;;;GAIG;AACH,MAAM,WAAW,gBAAgB;IAC/B,EAAE,EAAE,MAAM,CAAA;IACV,KAAK,EA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AAK,EAAE,MAAM,CAAA;IACb,QAAQ,EAAE,CAAC,KAAK,EAAE,MAAM,KAAK,MAAM,CAAA;IACnC,KAAK,EAAE,MAAM,CAAA;IACb,aAAa,EAAE,MAAM,CAAA;IACrB,mBAAmB,EAAE,MAAM,CAAA;IAC3B,oBAAoB,EAAE,MAAM,CAAA;IAC5B,kBAAkB,EAAE,MAAM,CAAA;IAC1B,6BAA6B,EAAE,MAAM,CAAA;IACrC,uBAAuB,EAAE,MAAM,CAAA;IAC/B,kBAAkB,EAAE,MAAM,CAAA;IAC1B,OAAO,EAAE,MAAM,CAAA;CAChB;AAED,MAAM,WAAW,0BAA0B;IACzC,0DAA0D;IAC1D,SAAS,EAAE,sBAAsB,CAAA;IACjC;;;;OAIG;IACH,WAAW,EAAE,MAAM,CAAA;IACnB,8EAA8E;IAC9E,WAAW,CAAC,EAAE,OAAO,CAAA;IACrB;;;OAGG;IACH,mBAAmB,CAAC,EAAE,CAAC,YAAY,EAAE,gBAAgB,KAAK,IAAI,CAAA;IAC9D,sEAAsE;IACtE,OAAO,CAAC,EAAE,MAAM,CAAA;IAChB,2DAA2D;IAC3D,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,qDAAqD;IACrD,MAAM,CAAC,EAAE,OAAO,CAAC,2BAA2B,CAAC,CAAA;IAC7C;;;;;;OAMG;IACH,wBAAwB,CAAC,EAAE,CACzB,SAAS,EAAE,CAAC,OAAO,EAAE,qBAAqB,KAAK,IAAI,KAChD,IAAI,GAAG,CAAC,MAAM,IAAI,CAAC,CAAA;CACzB"}
|
package/dist/types.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}
|
package/package.json
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@asteby/metacore-notifications",
|
|
3
|
+
"version": "2.0.0",
|
|
4
|
+
"description": "Metacore notifications — dropdown, app badge, WebSocket-driven real-time updates",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "https://github.com/asteby/metacore-sdk",
|
|
9
|
+
"directory": "packages/notifications"
|
|
10
|
+
},
|
|
11
|
+
"type": "module",
|
|
12
|
+
"main": "./dist/index.js",
|
|
13
|
+
"types": "./dist/index.d.ts",
|
|
14
|
+
"files": [
|
|
15
|
+
"dist",
|
|
16
|
+
"README.md"
|
|
17
|
+
],
|
|
18
|
+
"exports": {
|
|
19
|
+
".": {
|
|
20
|
+
"types": "./dist/index.d.ts",
|
|
21
|
+
"import": "./dist/index.js"
|
|
22
|
+
},
|
|
23
|
+
"./dropdown": {
|
|
24
|
+
"types": "./dist/dropdown.d.ts",
|
|
25
|
+
"import": "./dist/dropdown.js"
|
|
26
|
+
},
|
|
27
|
+
"./hooks": {
|
|
28
|
+
"types": "./dist/hooks.d.ts",
|
|
29
|
+
"import": "./dist/hooks.js"
|
|
30
|
+
}
|
|
31
|
+
},
|
|
32
|
+
"peerDependencies": {
|
|
33
|
+
"react": ">=18",
|
|
34
|
+
"react-dom": ">=18",
|
|
35
|
+
"@tanstack/react-query": ">=5",
|
|
36
|
+
"date-fns": ">=3",
|
|
37
|
+
"lucide-react": ">=0.460",
|
|
38
|
+
"sonner": ">=1.7",
|
|
39
|
+
"@asteby/metacore-ui": "^0.3.0",
|
|
40
|
+
"@asteby/metacore-websocket": "^0.3.0"
|
|
41
|
+
},
|
|
42
|
+
"devDependencies": {
|
|
43
|
+
"@tanstack/react-query": "^5.95.0",
|
|
44
|
+
"@types/react": "^19.0.0",
|
|
45
|
+
"@types/react-dom": "^19.0.0",
|
|
46
|
+
"date-fns": "^4.1.0",
|
|
47
|
+
"lucide-react": "^0.460.0",
|
|
48
|
+
"react": "^19.2.4",
|
|
49
|
+
"react-dom": "^19.2.4",
|
|
50
|
+
"sonner": "^1.7.0",
|
|
51
|
+
"typescript": "^5.6.0",
|
|
52
|
+
"@asteby/metacore-ui": "0.3.0",
|
|
53
|
+
"@asteby/metacore-websocket": "0.3.0"
|
|
54
|
+
},
|
|
55
|
+
"publishConfig": {
|
|
56
|
+
"access": "public"
|
|
57
|
+
},
|
|
58
|
+
"scripts": {
|
|
59
|
+
"build": "tsc -p tsconfig.json",
|
|
60
|
+
"dev": "tsc -w -p tsconfig.json",
|
|
61
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
62
|
+
"clean": "rm -rf dist"
|
|
63
|
+
}
|
|
64
|
+
}
|