@sfinges/sf-conversation 0.0.0-stage → 0.1.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/README.md +225 -2
- package/fesm2022/sfinges-sf-conversation.mjs +1807 -0
- package/fesm2022/sfinges-sf-conversation.mjs.map +1 -0
- package/index.d.ts +5 -0
- package/lib/components/conversation-button/conversation-button.component.d.ts +36 -0
- package/lib/components/conversation-composer/conversation-composer.component.d.ts +48 -0
- package/lib/components/conversation-panel/conversation-panel.component.d.ts +88 -0
- package/lib/gateways/conversation-access-token.port.d.ts +13 -0
- package/lib/gateways/conversation-directory.port.d.ts +24 -0
- package/lib/gateways/conversation-http.service.d.ts +31 -0
- package/lib/gateways/conversation-realtime.port.d.ts +29 -0
- package/lib/gateways/conversation-signalr.service.d.ts +110 -0
- package/lib/gateways/conversation.port.d.ts +38 -0
- package/lib/models/conversation.model.d.ts +73 -0
- package/lib/state/conversation-user-names.service.d.ts +22 -0
- package/lib/state/conversation.store.d.ts +86 -0
- package/lib/utils/conversation-error.util.d.ts +8 -0
- package/lib/utils/mention.util.d.ts +21 -0
- package/lib/utils/uuid.util.d.ts +5 -0
- package/package.json +27 -3
- package/public-api.d.ts +16 -0
|
@@ -0,0 +1,1807 @@
|
|
|
1
|
+
import * as i0 from '@angular/core';
|
|
2
|
+
import { InjectionToken, inject, Injectable, makeEnvironmentProviders, NgZone, DestroyRef, signal, viewChild, computed, ChangeDetectionStrategy, Component, input, model, output, Injector, effect, untracked, afterNextRender, ViewEncapsulation, ElementRef } from '@angular/core';
|
|
3
|
+
import { HttpClient, HttpParams } from '@angular/common/http';
|
|
4
|
+
import { map, catchError, filter, debounceTime, distinctUntilChanged, switchMap } from 'rxjs/operators';
|
|
5
|
+
import { HubConnectionBuilder, LogLevel, HubConnectionState } from '@microsoft/signalr';
|
|
6
|
+
import { Subject, firstValueFrom, of, Subscription, fromEvent, merge, EMPTY } from 'rxjs';
|
|
7
|
+
import { DOCUMENT, DatePipe } from '@angular/common';
|
|
8
|
+
import { takeUntilDestroyed, toObservable } from '@angular/core/rxjs-interop';
|
|
9
|
+
import * as i1 from 'primeng/button';
|
|
10
|
+
import { ButtonModule } from 'primeng/button';
|
|
11
|
+
import * as i2$1 from 'primeng/drawer';
|
|
12
|
+
import { DrawerModule } from 'primeng/drawer';
|
|
13
|
+
import * as i3 from 'primeng/menu';
|
|
14
|
+
import { MenuModule } from 'primeng/menu';
|
|
15
|
+
import * as i4 from 'primeng/message';
|
|
16
|
+
import { MessageModule } from 'primeng/message';
|
|
17
|
+
import * as i5 from 'primeng/skeleton';
|
|
18
|
+
import { SkeletonModule } from 'primeng/skeleton';
|
|
19
|
+
import * as i2 from 'primeng/textarea';
|
|
20
|
+
import { TextareaModule } from 'primeng/textarea';
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Contrato de datos de la conversación, igual al que devuelve la v2 de la API `notifications`.
|
|
24
|
+
*
|
|
25
|
+
* El tenant no aparece en ninguna parte: sale del token que pone el interceptor del front.
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
const CONVERSATION_SERVICE = new InjectionToken('CONVERSATION_SERVICE');
|
|
29
|
+
/**
|
|
30
|
+
* URL base de la API para `ConversationHttpService`, hasta la versión incluida
|
|
31
|
+
* (por ejemplo `https://<apim>/notifications/v2/`). Las rutas se arman relativas a ella.
|
|
32
|
+
*/
|
|
33
|
+
const CONVERSATION_API_URL = new InjectionToken('CONVERSATION_API_URL');
|
|
34
|
+
|
|
35
|
+
const CONVERSATION_REALTIME = new InjectionToken('CONVERSATION_REALTIME');
|
|
36
|
+
|
|
37
|
+
const CONVERSATION_DIRECTORY = new InjectionToken('CONVERSATION_DIRECTORY');
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Token de usuario para lo que no pasa por los interceptores de `HttpClient`: la negociación y el
|
|
41
|
+
* WebSocket del canal en vivo (`provideConversationRealtime`). El adaptador lo pide en cada
|
|
42
|
+
* conexión y reconexión, así que debe devolver siempre el token vigente, no uno guardado al
|
|
43
|
+
* arrancar.
|
|
44
|
+
*/
|
|
45
|
+
const CONVERSATION_ACCESS_TOKEN = new InjectionToken('CONVERSATION_ACCESS_TOKEN');
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Implementación de `ConversationGateway` contra la v2 de la API `notifications` del APIM.
|
|
49
|
+
*
|
|
50
|
+
* No pone el token ni la llave de suscripción: eso lo hace el interceptor del front, igual que
|
|
51
|
+
* con las demás rutas v2. El tenant sale del token, por eso no hay `idKatios` en la ruta.
|
|
52
|
+
*/
|
|
53
|
+
class ConversationHttpService {
|
|
54
|
+
http = inject(HttpClient);
|
|
55
|
+
baseUrl = inject(CONVERSATION_API_URL);
|
|
56
|
+
listMessages(entityType, entityId, query = {}) {
|
|
57
|
+
let params = new HttpParams();
|
|
58
|
+
if (query.beforeId != null) {
|
|
59
|
+
params = params.set('beforeId', String(query.beforeId));
|
|
60
|
+
}
|
|
61
|
+
if (query.afterId != null) {
|
|
62
|
+
params = params.set('afterId', String(query.afterId));
|
|
63
|
+
}
|
|
64
|
+
if (query.limit != null) {
|
|
65
|
+
params = params.set('limit', String(query.limit));
|
|
66
|
+
}
|
|
67
|
+
return this.http.get(this.url(this.messagesPath(entityType, entityId)), { params });
|
|
68
|
+
}
|
|
69
|
+
postMessage(entityType, entityId, message) {
|
|
70
|
+
return this.http.post(this.url(this.messagesPath(entityType, entityId)), message);
|
|
71
|
+
}
|
|
72
|
+
editMessage(messageId, body) {
|
|
73
|
+
return this.http
|
|
74
|
+
.put(this.url(`conversations/messages/${encodeURIComponent(String(messageId))}`), { body })
|
|
75
|
+
.pipe(map((response) => response ?? null));
|
|
76
|
+
}
|
|
77
|
+
deleteMessage(messageId) {
|
|
78
|
+
return this.http.delete(this.url(`conversations/messages/${encodeURIComponent(String(messageId))}`));
|
|
79
|
+
}
|
|
80
|
+
markRead(entityType, entityId, lastReadMessageId) {
|
|
81
|
+
return this.http.put(this.url(`${this.entityPath(entityType, entityId)}/read`), { lastReadMessageId });
|
|
82
|
+
}
|
|
83
|
+
unreadSummary(entityType, entityIds) {
|
|
84
|
+
return this.http.post(this.url('conversations/unread'), { entityType, entityIds });
|
|
85
|
+
}
|
|
86
|
+
entityPath(entityType, entityId) {
|
|
87
|
+
return `conversations/${encodeURIComponent(entityType)}/${encodeURIComponent(entityId)}`;
|
|
88
|
+
}
|
|
89
|
+
messagesPath(entityType, entityId) {
|
|
90
|
+
return `${this.entityPath(entityType, entityId)}/messages`;
|
|
91
|
+
}
|
|
92
|
+
url(path) {
|
|
93
|
+
return `${this.baseUrl.replace(/\/+$/, '')}/${path}`;
|
|
94
|
+
}
|
|
95
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: ConversationHttpService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
|
|
96
|
+
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: ConversationHttpService, providedIn: 'root' });
|
|
97
|
+
}
|
|
98
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: ConversationHttpService, decorators: [{
|
|
99
|
+
type: Injectable,
|
|
100
|
+
args: [{ providedIn: 'root' }]
|
|
101
|
+
}] });
|
|
102
|
+
/**
|
|
103
|
+
* Atajo para el caso común: `CONVERSATION_SERVICE` con `ConversationHttpService` sobre la URL dada.
|
|
104
|
+
* El front sigue necesitando `provideHttpClient(...)` con su interceptor de token.
|
|
105
|
+
*/
|
|
106
|
+
function provideConversationHttp(apiUrl) {
|
|
107
|
+
return makeEnvironmentProviders([
|
|
108
|
+
{ provide: CONVERSATION_API_URL, useValue: apiUrl },
|
|
109
|
+
{ provide: CONVERSATION_SERVICE, useExisting: ConversationHttpService },
|
|
110
|
+
]);
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/** Evento de cliente que envía el servicio con cada cambio de una conversación. */
|
|
114
|
+
const CONVERSATION_MESSAGE_EVENT = 'CONVERSATION_MESSAGE';
|
|
115
|
+
/** Tras cerrar el último panel, la conexión sigue abierta este tiempo por si se abre otro. */
|
|
116
|
+
const CONVERSATION_IDLE_DISCONNECT_MS = 60_000;
|
|
117
|
+
/**
|
|
118
|
+
* Una unión pedida mientras la conexión se recupera espera como mucho este tiempo. Después se
|
|
119
|
+
* rechaza y el panel sigue sin canal (pide lo nuevo al volver a la pestaña).
|
|
120
|
+
*/
|
|
121
|
+
const CONVERSATION_JOIN_TIMEOUT_MS = 15_000;
|
|
122
|
+
/**
|
|
123
|
+
* Una conexión que duró al menos esto se considera estable: si se cae después, se reintenta de
|
|
124
|
+
* inmediato. Si se cae antes, cada intento espera más (evita conectar y caer en bucle).
|
|
125
|
+
*/
|
|
126
|
+
const CONVERSATION_STABLE_CONNECTION_MS = 60_000;
|
|
127
|
+
/**
|
|
128
|
+
* Pausas entre intentos (reconectar, volver a unirse a un grupo): rápido al principio y después
|
|
129
|
+
* cada minuto, sin rendirse mientras haya un panel abierto. Al cerrarse el último, se detiene.
|
|
130
|
+
*/
|
|
131
|
+
const CONVERSATION_RECONNECT_DELAYS_MS = [0, 2_000, 10_000, 30_000, 60_000];
|
|
132
|
+
const reconnectPolicy = {
|
|
133
|
+
nextRetryDelayInMilliseconds: ({ previousRetryCount }) => retryDelay(previousRetryCount),
|
|
134
|
+
};
|
|
135
|
+
function retryDelay(attempt) {
|
|
136
|
+
const delays = CONVERSATION_RECONNECT_DELAYS_MS;
|
|
137
|
+
return delays[Math.min(attempt, delays.length - 1)] ?? 0;
|
|
138
|
+
}
|
|
139
|
+
/**
|
|
140
|
+
* Canal en vivo listo sobre Azure SignalR Service en modo serverless (TFNBXNotifications):
|
|
141
|
+
*
|
|
142
|
+
* - Conecta al hub `conversations` de la misma API (`<CONVERSATION_API_URL>conversations`): el
|
|
143
|
+
* cliente de SignalR llama solo a `POST conversations/negotiate`, que devuelve la URL y el token
|
|
144
|
+
* de Azure SignalR. El token del front entra por `CONVERSATION_ACCESS_TOKEN`, porque ni la
|
|
145
|
+
* negociación hecha por SignalR ni el WebSocket pasan por los interceptores de `HttpClient`.
|
|
146
|
+
* - Se une y sale de cada conversación con `POST conversations/{tipo}/{id}/join|leave` y el
|
|
147
|
+
* `connectionId`. Estas sí van por `HttpClient`, con el interceptor del front, como el resto de
|
|
148
|
+
* la API. Las de un mismo grupo salen en orden, una después de la otra.
|
|
149
|
+
* - Conecta con el primer panel que se abre y desconecta un minuto después de cerrarse el último.
|
|
150
|
+
* Al reconectar (cambia el `connectionId`) vuelve a unirse a los grupos abiertos y emite
|
|
151
|
+
* `reconnected$`, para que el panel pida lo que se perdió. Si una de esas uniones falla, la
|
|
152
|
+
* reintenta mientras el panel siga abierto.
|
|
153
|
+
* - La conexión, sus pings y los temporizadores corren fuera de la zona de Angular; solo los
|
|
154
|
+
* eventos para los paneles vuelven a ella.
|
|
155
|
+
*/
|
|
156
|
+
class ConversationSignalRService {
|
|
157
|
+
http = inject(HttpClient);
|
|
158
|
+
zone = inject(NgZone);
|
|
159
|
+
// Opcionales: si faltan, `join` falla y el panel sigue sin canal, en vez de no poder crearse.
|
|
160
|
+
baseUrl = inject(CONVERSATION_API_URL, { optional: true });
|
|
161
|
+
accessToken = inject(CONVERSATION_ACCESS_TOKEN, { optional: true });
|
|
162
|
+
eventsSubject = new Subject();
|
|
163
|
+
reconnectedSubject = new Subject();
|
|
164
|
+
groups = new Map();
|
|
165
|
+
/** La última operación pendiente de cada grupo: unirse y salir se encadenan por grupo. */
|
|
166
|
+
queues = new Map();
|
|
167
|
+
/** Uniones que esperan a que termine una reconexión en curso. */
|
|
168
|
+
waiters = [];
|
|
169
|
+
connection = null;
|
|
170
|
+
starting = null;
|
|
171
|
+
stopping = null;
|
|
172
|
+
stopRequested = false;
|
|
173
|
+
idleTimer = null;
|
|
174
|
+
restartTimer = null;
|
|
175
|
+
connectedAt = 0;
|
|
176
|
+
closeStreak = 0;
|
|
177
|
+
destroyed = false;
|
|
178
|
+
events$ = this.eventsSubject.asObservable();
|
|
179
|
+
reconnected$ = this.reconnectedSubject.asObservable();
|
|
180
|
+
join(entityType, entityId) {
|
|
181
|
+
if (this.destroyed) {
|
|
182
|
+
return Promise.reject(new Error('El canal en vivo se cerró.'));
|
|
183
|
+
}
|
|
184
|
+
if (!this.baseUrl || !this.accessToken) {
|
|
185
|
+
return Promise.reject(new Error('El canal en vivo necesita CONVERSATION_API_URL y CONVERSATION_ACCESS_TOKEN.'));
|
|
186
|
+
}
|
|
187
|
+
this.cancelIdleStop();
|
|
188
|
+
const key = groupKey(entityType, entityId);
|
|
189
|
+
const existing = this.groups.get(key);
|
|
190
|
+
if (existing) {
|
|
191
|
+
existing.refs++;
|
|
192
|
+
return existing.joined;
|
|
193
|
+
}
|
|
194
|
+
const group = {
|
|
195
|
+
key,
|
|
196
|
+
entityType,
|
|
197
|
+
entityId,
|
|
198
|
+
refs: 1,
|
|
199
|
+
connectionId: null,
|
|
200
|
+
joined: Promise.resolve(),
|
|
201
|
+
retryTimer: null,
|
|
202
|
+
};
|
|
203
|
+
group.joined = this.connected()
|
|
204
|
+
.then(() => this.enqueue(key, () => this.joinGroup(group)))
|
|
205
|
+
.catch((error) => {
|
|
206
|
+
// Sin grupo, el panel pide lo nuevo al volver a la pestaña. Aquí solo se olvida.
|
|
207
|
+
if (this.groups.get(key) === group) {
|
|
208
|
+
this.forget(group);
|
|
209
|
+
}
|
|
210
|
+
throw error;
|
|
211
|
+
});
|
|
212
|
+
this.groups.set(key, group);
|
|
213
|
+
return group.joined;
|
|
214
|
+
}
|
|
215
|
+
leave(entityType, entityId) {
|
|
216
|
+
const key = groupKey(entityType, entityId);
|
|
217
|
+
const group = this.groups.get(key);
|
|
218
|
+
if (!group) {
|
|
219
|
+
return Promise.resolve();
|
|
220
|
+
}
|
|
221
|
+
group.refs--;
|
|
222
|
+
if (group.refs > 0) {
|
|
223
|
+
return Promise.resolve();
|
|
224
|
+
}
|
|
225
|
+
this.forget(group);
|
|
226
|
+
// En cola detrás de la unión: si todavía no terminaba, sale apenas termine.
|
|
227
|
+
return this.enqueue(key, () => {
|
|
228
|
+
const connectionId = this.currentConnectionId();
|
|
229
|
+
if (!connectionId || group.connectionId !== connectionId) {
|
|
230
|
+
// Sin conexión, o unida con una anterior: Azure SignalR ya soltó el grupo.
|
|
231
|
+
return Promise.resolve();
|
|
232
|
+
}
|
|
233
|
+
group.connectionId = null;
|
|
234
|
+
return this.post('leave', group, connectionId);
|
|
235
|
+
}).catch(() => {
|
|
236
|
+
// Salir es limpieza: si falla, el grupo se suelta al cerrarse la conexión.
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
ngOnDestroy() {
|
|
240
|
+
this.destroyed = true;
|
|
241
|
+
this.cancelIdleStop();
|
|
242
|
+
this.cancelRestart();
|
|
243
|
+
this.groups.forEach((group) => this.clearRetry(group));
|
|
244
|
+
this.groups.clear();
|
|
245
|
+
this.rejectWaiters(new Error('El canal en vivo se cerró.'));
|
|
246
|
+
this.stopRequested = true;
|
|
247
|
+
void this.connection?.stop().catch(() => undefined);
|
|
248
|
+
this.eventsSubject.complete();
|
|
249
|
+
this.reconnectedSubject.complete();
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Crea la conexión. Las pruebas la reemplazan por una falsa; un front no necesita tocarla.
|
|
253
|
+
*/
|
|
254
|
+
createConnection(url, options) {
|
|
255
|
+
return new HubConnectionBuilder()
|
|
256
|
+
.withUrl(url, options)
|
|
257
|
+
.withAutomaticReconnect(reconnectPolicy)
|
|
258
|
+
.configureLogging(LogLevel.Error)
|
|
259
|
+
.build();
|
|
260
|
+
}
|
|
261
|
+
/** Une la conexión vigente al grupo. Si la conexión cambió mientras tanto, repite con la nueva. */
|
|
262
|
+
joinGroup(group) {
|
|
263
|
+
if (this.groups.get(group.key) !== group) {
|
|
264
|
+
// Se dejó antes de alcanzar a unirse: no entra a un grupo que nadie mira.
|
|
265
|
+
return Promise.resolve();
|
|
266
|
+
}
|
|
267
|
+
const connectionId = this.currentConnectionId();
|
|
268
|
+
if (!connectionId) {
|
|
269
|
+
return Promise.reject(new Error('El canal en vivo no está conectado.'));
|
|
270
|
+
}
|
|
271
|
+
if (group.connectionId === connectionId) {
|
|
272
|
+
// La reunión tras reconectar ya la hizo.
|
|
273
|
+
return Promise.resolve();
|
|
274
|
+
}
|
|
275
|
+
return this.post('join', group, connectionId).then(() => {
|
|
276
|
+
group.connectionId = connectionId;
|
|
277
|
+
const current = this.currentConnectionId();
|
|
278
|
+
if (current && current !== connectionId) {
|
|
279
|
+
return this.joinGroup(group);
|
|
280
|
+
}
|
|
281
|
+
// Si está reconectando, la reunión de `rejoinAll` la repite con la conexión nueva.
|
|
282
|
+
return undefined;
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
/** Conecta si hace falta y devuelve el `connectionId` vigente. */
|
|
286
|
+
connected() {
|
|
287
|
+
return (this.stopping ?? Promise.resolve())
|
|
288
|
+
.then(() => {
|
|
289
|
+
if (this.destroyed) {
|
|
290
|
+
throw new Error('El canal en vivo se cerró.');
|
|
291
|
+
}
|
|
292
|
+
const connection = (this.connection ??= this.buildConnection());
|
|
293
|
+
if (connection.state === HubConnectionState.Reconnecting) {
|
|
294
|
+
return this.waitForReconnect();
|
|
295
|
+
}
|
|
296
|
+
if (connection.state !== HubConnectionState.Connected) {
|
|
297
|
+
this.starting ??= this.zone
|
|
298
|
+
.runOutsideAngular(() => connection.start())
|
|
299
|
+
.then(() => {
|
|
300
|
+
this.connectedAt = Date.now();
|
|
301
|
+
})
|
|
302
|
+
.finally(() => {
|
|
303
|
+
this.starting = null;
|
|
304
|
+
});
|
|
305
|
+
return this.starting;
|
|
306
|
+
}
|
|
307
|
+
return undefined;
|
|
308
|
+
})
|
|
309
|
+
.then(() => {
|
|
310
|
+
const connectionId = this.currentConnectionId();
|
|
311
|
+
if (!connectionId) {
|
|
312
|
+
throw new Error('El canal en vivo no está conectado.');
|
|
313
|
+
}
|
|
314
|
+
return connectionId;
|
|
315
|
+
});
|
|
316
|
+
}
|
|
317
|
+
waitForReconnect() {
|
|
318
|
+
return new Promise((resolve, reject) => {
|
|
319
|
+
const timer = this.zone.runOutsideAngular(() => setTimeout(() => {
|
|
320
|
+
this.waiters = this.waiters.filter((w) => w !== waiter);
|
|
321
|
+
reject(new Error('El canal en vivo no se recuperó a tiempo.'));
|
|
322
|
+
}, CONVERSATION_JOIN_TIMEOUT_MS));
|
|
323
|
+
const waiter = {
|
|
324
|
+
resolve: () => {
|
|
325
|
+
clearTimeout(timer);
|
|
326
|
+
resolve();
|
|
327
|
+
},
|
|
328
|
+
reject: (error) => {
|
|
329
|
+
clearTimeout(timer);
|
|
330
|
+
reject(error);
|
|
331
|
+
},
|
|
332
|
+
};
|
|
333
|
+
this.waiters.push(waiter);
|
|
334
|
+
});
|
|
335
|
+
}
|
|
336
|
+
buildConnection() {
|
|
337
|
+
const accessToken = this.accessToken;
|
|
338
|
+
const connection = this.createConnection(this.url('conversations'), {
|
|
339
|
+
// SignalR la llama en cada negociación (también al reconectar): el token es el vigente.
|
|
340
|
+
accessTokenFactory: () => Promise.resolve(accessToken?.()).then((token) => token ?? ''),
|
|
341
|
+
// La autenticación va en el token: sin cookies, el APIM no necesita CORS con credenciales.
|
|
342
|
+
withCredentials: false,
|
|
343
|
+
});
|
|
344
|
+
connection.on(CONVERSATION_MESSAGE_EVENT, (event) => this.zone.run(() => this.eventsSubject.next(event)));
|
|
345
|
+
connection.onreconnected(() => {
|
|
346
|
+
this.connectedAt = Date.now();
|
|
347
|
+
this.resolveWaiters();
|
|
348
|
+
void this.rejoinAll();
|
|
349
|
+
});
|
|
350
|
+
connection.onclose(() => this.handleClose());
|
|
351
|
+
return connection;
|
|
352
|
+
}
|
|
353
|
+
/** Vuelve a unir los grupos abiertos a la conexión nueva y después avisa a los paneles. */
|
|
354
|
+
rejoinAll() {
|
|
355
|
+
const groups = [...this.groups.values()];
|
|
356
|
+
return Promise.all(groups.map((group) => this.rejoin(group, 0))).then(() => this.notifyReconnected());
|
|
357
|
+
}
|
|
358
|
+
rejoin(group, attempt) {
|
|
359
|
+
return this.enqueue(group.key, () => {
|
|
360
|
+
const connectionId = this.currentConnectionId();
|
|
361
|
+
if (this.groups.get(group.key) !== group || !connectionId || group.connectionId === connectionId) {
|
|
362
|
+
return Promise.resolve();
|
|
363
|
+
}
|
|
364
|
+
return this.post('join', group, connectionId).then(() => {
|
|
365
|
+
group.connectionId = connectionId;
|
|
366
|
+
});
|
|
367
|
+
}).catch(() => {
|
|
368
|
+
// Sin grupo no llegan sus eventos: se reintenta mientras el panel siga abierto.
|
|
369
|
+
group.connectionId = null;
|
|
370
|
+
this.scheduleRejoin(group, attempt + 1);
|
|
371
|
+
});
|
|
372
|
+
}
|
|
373
|
+
scheduleRejoin(group, attempt) {
|
|
374
|
+
this.clearRetry(group);
|
|
375
|
+
group.retryTimer = this.zone.runOutsideAngular(() => setTimeout(() => {
|
|
376
|
+
group.retryTimer = null;
|
|
377
|
+
if (this.destroyed || this.groups.get(group.key) !== group || !this.currentConnectionId()) {
|
|
378
|
+
// Cerrado, o sin conexión: la próxima reconexión vuelve a unir el grupo.
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
void this.rejoin(group, attempt).then(() => {
|
|
382
|
+
if (group.connectionId) {
|
|
383
|
+
this.notifyReconnected();
|
|
384
|
+
}
|
|
385
|
+
});
|
|
386
|
+
}, retryDelay(attempt)));
|
|
387
|
+
}
|
|
388
|
+
/**
|
|
389
|
+
* La conexión se cerró: por `stop()` o porque el servidor la cerró sin permitir reconectar.
|
|
390
|
+
* En el segundo caso, si hay paneles abiertos, se vuelve a conectar desde cero.
|
|
391
|
+
*/
|
|
392
|
+
handleClose() {
|
|
393
|
+
this.rejectWaiters(new Error('El canal en vivo se desconectó.'));
|
|
394
|
+
if (this.destroyed || this.stopRequested || this.groups.size === 0) {
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
const stable = Date.now() - this.connectedAt >= CONVERSATION_STABLE_CONNECTION_MS;
|
|
398
|
+
this.closeStreak = stable ? 0 : this.closeStreak + 1;
|
|
399
|
+
this.scheduleRestart(this.closeStreak);
|
|
400
|
+
}
|
|
401
|
+
scheduleRestart(attempt) {
|
|
402
|
+
this.cancelRestart();
|
|
403
|
+
this.restartTimer = this.zone.runOutsideAngular(() => setTimeout(() => {
|
|
404
|
+
this.restartTimer = null;
|
|
405
|
+
if (this.destroyed || this.groups.size === 0) {
|
|
406
|
+
return;
|
|
407
|
+
}
|
|
408
|
+
this.connected()
|
|
409
|
+
.then(() => this.rejoinAll())
|
|
410
|
+
.catch(() => this.scheduleRestart(attempt + 1));
|
|
411
|
+
}, retryDelay(attempt)));
|
|
412
|
+
}
|
|
413
|
+
scheduleIdleStop() {
|
|
414
|
+
if (this.groups.size > 0 || !this.connection || this.destroyed) {
|
|
415
|
+
return;
|
|
416
|
+
}
|
|
417
|
+
this.cancelIdleStop();
|
|
418
|
+
this.idleTimer = this.zone.runOutsideAngular(() => setTimeout(() => {
|
|
419
|
+
this.idleTimer = null;
|
|
420
|
+
if (this.groups.size === 0) {
|
|
421
|
+
this.stop();
|
|
422
|
+
}
|
|
423
|
+
}, CONVERSATION_IDLE_DISCONNECT_MS));
|
|
424
|
+
}
|
|
425
|
+
stop() {
|
|
426
|
+
const connection = this.connection;
|
|
427
|
+
if (!connection || this.stopping) {
|
|
428
|
+
return;
|
|
429
|
+
}
|
|
430
|
+
this.cancelRestart();
|
|
431
|
+
// Antes de `stop()`: SignalR puede llamar a `onclose` en el mismo instante.
|
|
432
|
+
this.stopRequested = true;
|
|
433
|
+
this.stopping = connection
|
|
434
|
+
.stop()
|
|
435
|
+
.catch(() => undefined)
|
|
436
|
+
.finally(() => {
|
|
437
|
+
this.stopping = null;
|
|
438
|
+
this.stopRequested = false;
|
|
439
|
+
});
|
|
440
|
+
}
|
|
441
|
+
/** Encadena la operación detrás de la anterior del mismo grupo, para que lleguen en orden. */
|
|
442
|
+
enqueue(key, operation) {
|
|
443
|
+
const previous = this.queues.get(key) ?? Promise.resolve();
|
|
444
|
+
const next = previous.then(operation);
|
|
445
|
+
const tail = next.catch(() => undefined);
|
|
446
|
+
this.queues.set(key, tail);
|
|
447
|
+
void tail.then(() => {
|
|
448
|
+
if (this.queues.get(key) === tail) {
|
|
449
|
+
this.queues.delete(key);
|
|
450
|
+
}
|
|
451
|
+
});
|
|
452
|
+
return next;
|
|
453
|
+
}
|
|
454
|
+
post(action, group, connectionId) {
|
|
455
|
+
const path = `conversations/${encodeURIComponent(group.entityType)}/${encodeURIComponent(group.entityId)}/${action}`;
|
|
456
|
+
return firstValueFrom(this.http.post(this.url(path), { connectionId }), { defaultValue: null }).then(() => undefined);
|
|
457
|
+
}
|
|
458
|
+
forget(group) {
|
|
459
|
+
this.groups.delete(group.key);
|
|
460
|
+
this.clearRetry(group);
|
|
461
|
+
this.scheduleIdleStop();
|
|
462
|
+
}
|
|
463
|
+
currentConnectionId() {
|
|
464
|
+
const connection = this.connection;
|
|
465
|
+
return connection?.state === HubConnectionState.Connected ? (connection.connectionId ?? null) : null;
|
|
466
|
+
}
|
|
467
|
+
notifyReconnected() {
|
|
468
|
+
if (!this.destroyed) {
|
|
469
|
+
this.zone.run(() => this.reconnectedSubject.next());
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
resolveWaiters() {
|
|
473
|
+
const waiters = this.waiters;
|
|
474
|
+
this.waiters = [];
|
|
475
|
+
waiters.forEach((w) => w.resolve());
|
|
476
|
+
}
|
|
477
|
+
rejectWaiters(error) {
|
|
478
|
+
const waiters = this.waiters;
|
|
479
|
+
this.waiters = [];
|
|
480
|
+
waiters.forEach((w) => w.reject(error));
|
|
481
|
+
}
|
|
482
|
+
clearRetry(group) {
|
|
483
|
+
if (group.retryTimer) {
|
|
484
|
+
clearTimeout(group.retryTimer);
|
|
485
|
+
group.retryTimer = null;
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
cancelIdleStop() {
|
|
489
|
+
if (this.idleTimer) {
|
|
490
|
+
clearTimeout(this.idleTimer);
|
|
491
|
+
this.idleTimer = null;
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
cancelRestart() {
|
|
495
|
+
if (this.restartTimer) {
|
|
496
|
+
clearTimeout(this.restartTimer);
|
|
497
|
+
this.restartTimer = null;
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
url(path) {
|
|
501
|
+
return `${(this.baseUrl ?? '').replace(/\/+$/, '')}/${path}`;
|
|
502
|
+
}
|
|
503
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: ConversationSignalRService, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
|
|
504
|
+
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: ConversationSignalRService, providedIn: 'root' });
|
|
505
|
+
}
|
|
506
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: ConversationSignalRService, decorators: [{
|
|
507
|
+
type: Injectable,
|
|
508
|
+
args: [{ providedIn: 'root' }]
|
|
509
|
+
}] });
|
|
510
|
+
function groupKey(entityType, entityId) {
|
|
511
|
+
return `${entityType}\u0000${entityId}`;
|
|
512
|
+
}
|
|
513
|
+
/**
|
|
514
|
+
* Canal en vivo listo: `CONVERSATION_REALTIME` con `ConversationSignalRService`. Usa la URL de
|
|
515
|
+
* `CONVERSATION_API_URL` (la pone `provideConversationHttp`) y el token de
|
|
516
|
+
* `CONVERSATION_ACCESS_TOKEN`, que el front provee. Si falta alguno, el panel funciona sin canal.
|
|
517
|
+
*/
|
|
518
|
+
function provideConversationRealtime() {
|
|
519
|
+
return makeEnvironmentProviders([{ provide: CONVERSATION_REALTIME, useExisting: ConversationSignalRService }]);
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
function userKey(user) {
|
|
523
|
+
return `${user.tdoc}:${user.ndoc}`;
|
|
524
|
+
}
|
|
525
|
+
function escapeRegExp(value) {
|
|
526
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
527
|
+
}
|
|
528
|
+
/**
|
|
529
|
+
* Parte el texto en trozos para resaltar las menciones sin `[innerHTML]`: la plantilla pinta cada
|
|
530
|
+
* trozo con interpolación. Solo se resaltan los nombres de `mentions` del mensaje; un `@` escrito a
|
|
531
|
+
* mano que no corresponde a una mención queda como texto.
|
|
532
|
+
*/
|
|
533
|
+
function splitMentions(body, mentionNames) {
|
|
534
|
+
const names = [...new Set(mentionNames.filter((name) => name.trim().length > 0))]
|
|
535
|
+
// Los nombres largos primero, para que "@Ana María" no se corte en "@Ana".
|
|
536
|
+
.sort((a, b) => b.length - a.length)
|
|
537
|
+
.map(escapeRegExp);
|
|
538
|
+
if (!body || names.length === 0) {
|
|
539
|
+
return [{ text: body, mention: false }];
|
|
540
|
+
}
|
|
541
|
+
const pattern = new RegExp(`@(?:${names.join('|')})`, 'g');
|
|
542
|
+
const segments = [];
|
|
543
|
+
let last = 0;
|
|
544
|
+
for (const match of body.matchAll(pattern)) {
|
|
545
|
+
const start = match.index ?? 0;
|
|
546
|
+
if (start > last) {
|
|
547
|
+
segments.push({ text: body.slice(last, start), mention: false });
|
|
548
|
+
}
|
|
549
|
+
segments.push({ text: match[0], mention: true });
|
|
550
|
+
last = start + match[0].length;
|
|
551
|
+
}
|
|
552
|
+
if (last < body.length) {
|
|
553
|
+
segments.push({ text: body.slice(last), mention: false });
|
|
554
|
+
}
|
|
555
|
+
return segments;
|
|
556
|
+
}
|
|
557
|
+
/**
|
|
558
|
+
* La mención que se está escribiendo justo antes del cursor: `@` al inicio o después de un
|
|
559
|
+
* espacio, seguido de lo que va del nombre (sin espacios). `null` si no hay ninguna.
|
|
560
|
+
*/
|
|
561
|
+
function mentionQueryAt(text, caret) {
|
|
562
|
+
const before = text.slice(0, caret);
|
|
563
|
+
const match = /(?:^|\s)@([^\s@]{0,40})$/.exec(before);
|
|
564
|
+
if (!match) {
|
|
565
|
+
return null;
|
|
566
|
+
}
|
|
567
|
+
const query = match[1] ?? '';
|
|
568
|
+
return { start: caret - query.length - 1, query };
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
/**
|
|
572
|
+
* Nombres de los usuarios que aparecen en el hilo. Pide cada usuario una sola vez al
|
|
573
|
+
* `CONVERSATION_DIRECTORY` y lo guarda mientras viva el panel.
|
|
574
|
+
*/
|
|
575
|
+
class ConversationUserNames {
|
|
576
|
+
directory = inject(CONVERSATION_DIRECTORY, { optional: true });
|
|
577
|
+
destroyRef = inject(DestroyRef);
|
|
578
|
+
requested = new Set();
|
|
579
|
+
names = signal(new Map());
|
|
580
|
+
/** Mapa `tdoc:ndoc` → nombre. Es una señal: la vista se repinta cuando llega un nombre. */
|
|
581
|
+
resolved = this.names.asReadonly();
|
|
582
|
+
/** Pide los nombres que todavía no se han pedido. */
|
|
583
|
+
ensure(users) {
|
|
584
|
+
const missing = [];
|
|
585
|
+
for (const user of users) {
|
|
586
|
+
const key = userKey(user);
|
|
587
|
+
if (!this.requested.has(key)) {
|
|
588
|
+
this.requested.add(key);
|
|
589
|
+
missing.push({ tdoc: user.tdoc, ndoc: user.ndoc });
|
|
590
|
+
}
|
|
591
|
+
}
|
|
592
|
+
if (!this.directory || missing.length === 0) {
|
|
593
|
+
return;
|
|
594
|
+
}
|
|
595
|
+
this.directory
|
|
596
|
+
.resolveUsers(missing)
|
|
597
|
+
.pipe(
|
|
598
|
+
// Sin nombre se muestra el documento: no vale la pena un estado de error para esto.
|
|
599
|
+
catchError(() => of([])), takeUntilDestroyed(this.destroyRef))
|
|
600
|
+
.subscribe((users) => this.remember(users));
|
|
601
|
+
}
|
|
602
|
+
/** Guarda nombres que ya se conocen, como los de las personas elegidas al mencionar. */
|
|
603
|
+
remember(users) {
|
|
604
|
+
if (users.length === 0) {
|
|
605
|
+
return;
|
|
606
|
+
}
|
|
607
|
+
this.names.update((current) => {
|
|
608
|
+
const next = new Map(current);
|
|
609
|
+
for (const user of users) {
|
|
610
|
+
const key = userKey(user);
|
|
611
|
+
this.requested.add(key);
|
|
612
|
+
next.set(key, user.name);
|
|
613
|
+
}
|
|
614
|
+
return next;
|
|
615
|
+
});
|
|
616
|
+
}
|
|
617
|
+
/** El nombre, o el documento mientras no haya nombre. */
|
|
618
|
+
label(user, names = this.names()) {
|
|
619
|
+
return names.get(userKey(user)) ?? `${user.tdoc} ${user.ndoc}`.trim();
|
|
620
|
+
}
|
|
621
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: ConversationUserNames, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
|
|
622
|
+
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: ConversationUserNames });
|
|
623
|
+
}
|
|
624
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: ConversationUserNames, decorators: [{
|
|
625
|
+
type: Injectable
|
|
626
|
+
}] });
|
|
627
|
+
|
|
628
|
+
const FALLBACK = {
|
|
629
|
+
load: 'No se pudieron cargar los mensajes.',
|
|
630
|
+
send: 'No se pudo enviar el mensaje.',
|
|
631
|
+
edit: 'No se pudo editar el mensaje.',
|
|
632
|
+
delete: 'No se pudo borrar el mensaje.',
|
|
633
|
+
};
|
|
634
|
+
function statusOf(error) {
|
|
635
|
+
const status = error?.status;
|
|
636
|
+
return typeof status === 'number' ? status : null;
|
|
637
|
+
}
|
|
638
|
+
function codeOf(error) {
|
|
639
|
+
const body = error?.error;
|
|
640
|
+
if (body && typeof body === 'object' && 'code' in body) {
|
|
641
|
+
const code = body.code;
|
|
642
|
+
return typeof code === 'string' ? code : null;
|
|
643
|
+
}
|
|
644
|
+
return null;
|
|
645
|
+
}
|
|
646
|
+
/**
|
|
647
|
+
* Traduce un error del puerto a una frase para la persona. Nunca muestra el texto técnico del
|
|
648
|
+
* backend. Distingue el 403 del servicio (`NOT_AUTHOR`) del 403 del APIM (al perfil le falta la
|
|
649
|
+
* opción), como pide el contrato de la v2.
|
|
650
|
+
*/
|
|
651
|
+
function describeConversationError(error, action) {
|
|
652
|
+
const status = statusOf(error);
|
|
653
|
+
if (status === 0) {
|
|
654
|
+
return 'No hay conexión con el servicio de conversación. Revise su conexión e intente de nuevo.';
|
|
655
|
+
}
|
|
656
|
+
if (status === 401) {
|
|
657
|
+
return 'Su sesión venció. Vuelva a iniciar sesión.';
|
|
658
|
+
}
|
|
659
|
+
if (status === 403) {
|
|
660
|
+
if (codeOf(error) === 'NOT_AUTHOR') {
|
|
661
|
+
return 'Solo quien escribió el mensaje puede editarlo o borrarlo.';
|
|
662
|
+
}
|
|
663
|
+
const what = action === 'load' ? 'ver' : 'escribir en';
|
|
664
|
+
return `Su perfil no tiene permiso para ${what} la conversación. Si se lo acaban de asignar, intente de nuevo en unos minutos.`;
|
|
665
|
+
}
|
|
666
|
+
if (status === 404 && (action === 'edit' || action === 'delete')) {
|
|
667
|
+
return 'El mensaje ya no existe.';
|
|
668
|
+
}
|
|
669
|
+
if (status === 400 && (action === 'send' || action === 'edit')) {
|
|
670
|
+
return 'El mensaje no es válido: no puede estar vacío ni pasar de 4.000 caracteres.';
|
|
671
|
+
}
|
|
672
|
+
if (status === 429) {
|
|
673
|
+
return 'Se hicieron demasiadas solicitudes. Espere un momento e intente de nuevo.';
|
|
674
|
+
}
|
|
675
|
+
return FALLBACK[action];
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
/**
|
|
679
|
+
* uuid v4 para `clientMessageId`. `crypto.randomUUID` solo existe en contextos seguros (https o
|
|
680
|
+
* localhost); en otro caso se arma con `crypto.getRandomValues`, que está en todos los navegadores.
|
|
681
|
+
*/
|
|
682
|
+
function createClientMessageId() {
|
|
683
|
+
const cryptoApi = globalThis.crypto;
|
|
684
|
+
if (typeof cryptoApi?.randomUUID === 'function') {
|
|
685
|
+
return cryptoApi.randomUUID();
|
|
686
|
+
}
|
|
687
|
+
const bytes = new Uint8Array(16);
|
|
688
|
+
cryptoApi.getRandomValues(bytes);
|
|
689
|
+
bytes[6] = ((bytes[6] ?? 0) & 0x0f) | 0x40;
|
|
690
|
+
bytes[8] = ((bytes[8] ?? 0) & 0x3f) | 0x80;
|
|
691
|
+
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
|
|
692
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
/** Tamaño de página: de 30 en 30 hacia atrás. */
|
|
696
|
+
const CONVERSATION_PAGE_SIZE = 30;
|
|
697
|
+
function normalize(message) {
|
|
698
|
+
return {
|
|
699
|
+
...message,
|
|
700
|
+
body: message.deleted ? '' : message.body ?? '',
|
|
701
|
+
mentions: message.mentions ?? [],
|
|
702
|
+
editedAt: message.editedAt ?? null,
|
|
703
|
+
clientMessageId: message.clientMessageId ?? null,
|
|
704
|
+
};
|
|
705
|
+
}
|
|
706
|
+
function maxSentId(items) {
|
|
707
|
+
let max = null;
|
|
708
|
+
for (const item of items) {
|
|
709
|
+
if (item.id != null && (max === null || item.id > max)) {
|
|
710
|
+
max = item.id;
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
return max;
|
|
714
|
+
}
|
|
715
|
+
function minSentId(items) {
|
|
716
|
+
let min = null;
|
|
717
|
+
for (const item of items) {
|
|
718
|
+
if (item.id != null && (min === null || item.id < min)) {
|
|
719
|
+
min = item.id;
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
return min;
|
|
723
|
+
}
|
|
724
|
+
/** Los confirmados por id ascendente; los pendientes y fallidos al final, en el orden en que se escribieron. */
|
|
725
|
+
function ordered(items) {
|
|
726
|
+
const sent = items.filter((i) => i.status === 'sent').sort((a, b) => (a.id ?? 0) - (b.id ?? 0));
|
|
727
|
+
const local = items.filter((i) => i.status !== 'sent');
|
|
728
|
+
return [...sent, ...local];
|
|
729
|
+
}
|
|
730
|
+
/**
|
|
731
|
+
* Estado de una conversación abierta: la lista, la paginación hacia atrás, el envío optimista,
|
|
732
|
+
* los mensajes en vivo y hasta dónde leyó la persona. Vive con el panel (provider del componente).
|
|
733
|
+
*/
|
|
734
|
+
class ConversationStore {
|
|
735
|
+
gateway = inject(CONVERSATION_SERVICE);
|
|
736
|
+
realtime = inject(CONVERSATION_REALTIME, { optional: true });
|
|
737
|
+
names = inject(ConversationUserNames);
|
|
738
|
+
destroyRef = inject(DestroyRef);
|
|
739
|
+
items = signal([]);
|
|
740
|
+
status = signal('idle');
|
|
741
|
+
loadError = signal(null);
|
|
742
|
+
hasOlder = signal(false);
|
|
743
|
+
olderStatus = signal('idle');
|
|
744
|
+
/** `lastReadMessageId` al abrir: de ahí sale la marca "Mensajes nuevos". */
|
|
745
|
+
lastReadAtOpen = signal(null);
|
|
746
|
+
/** Error de una acción sobre un mensaje (editar, borrar), para mostrarlo en el panel. */
|
|
747
|
+
notice = signal(null);
|
|
748
|
+
/** Borrador del campo de texto. Sobrevive a cerrar y abrir el panel de la misma entidad. */
|
|
749
|
+
draft = signal('');
|
|
750
|
+
/** Personas elegidas en la lista de menciones mientras se escribe el borrador. */
|
|
751
|
+
draftMentions = signal([]);
|
|
752
|
+
/** Hay canal en vivo y el panel ya está unido al grupo. */
|
|
753
|
+
live = signal(false);
|
|
754
|
+
entity = null;
|
|
755
|
+
session = new Subscription();
|
|
756
|
+
sessionId = 0;
|
|
757
|
+
lastMarkedRead = 0;
|
|
758
|
+
markReadDeferred = false;
|
|
759
|
+
/** Abre (o reabre) la conversación de una entidad. */
|
|
760
|
+
open(entityType, entityId) {
|
|
761
|
+
const sameEntity = this.entity?.type === entityType && this.entity?.id === entityId;
|
|
762
|
+
this.endSession();
|
|
763
|
+
if (!sameEntity) {
|
|
764
|
+
this.reset();
|
|
765
|
+
this.entity = { type: entityType, id: entityId };
|
|
766
|
+
}
|
|
767
|
+
this.sessionId++;
|
|
768
|
+
this.connectRealtime();
|
|
769
|
+
if (sameEntity && this.status() === 'ready') {
|
|
770
|
+
this.lastReadAtOpen.set(this.lastMarkedRead);
|
|
771
|
+
// Ya tenemos el hilo: solo lo nuevo, sin volver a pintar el esqueleto. Con canal en vivo
|
|
772
|
+
// lo pide la unión al grupo (o su fallo), para no pedirlo dos veces.
|
|
773
|
+
if (!this.realtime) {
|
|
774
|
+
this.refreshNewer();
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
else {
|
|
778
|
+
this.load();
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
/** Cierra la conversación: sale del grupo en vivo y corta lo que estuviera pidiendo. */
|
|
782
|
+
close() {
|
|
783
|
+
this.endSession();
|
|
784
|
+
}
|
|
785
|
+
retryLoad() {
|
|
786
|
+
this.load();
|
|
787
|
+
}
|
|
788
|
+
loadOlder() {
|
|
789
|
+
const entity = this.entity;
|
|
790
|
+
const oldest = minSentId(this.items());
|
|
791
|
+
if (!entity || oldest === null || this.olderStatus() === 'loading') {
|
|
792
|
+
return;
|
|
793
|
+
}
|
|
794
|
+
this.olderStatus.set('loading');
|
|
795
|
+
const session = this.sessionId;
|
|
796
|
+
this.session.add(this.gateway.listMessages(entity.type, entity.id, { beforeId: oldest, limit: CONVERSATION_PAGE_SIZE }).subscribe({
|
|
797
|
+
next: (page) => {
|
|
798
|
+
if (session !== this.sessionId) {
|
|
799
|
+
return;
|
|
800
|
+
}
|
|
801
|
+
this.upsertMany(page.messages);
|
|
802
|
+
this.hasOlder.set(page.messages.length >= CONVERSATION_PAGE_SIZE);
|
|
803
|
+
this.olderStatus.set('idle');
|
|
804
|
+
},
|
|
805
|
+
error: () => {
|
|
806
|
+
if (session === this.sessionId) {
|
|
807
|
+
this.olderStatus.set('error');
|
|
808
|
+
}
|
|
809
|
+
},
|
|
810
|
+
}));
|
|
811
|
+
}
|
|
812
|
+
/**
|
|
813
|
+
* Trae lo posterior al último mensaje que hay en pantalla. Si llega una página completa puede
|
|
814
|
+
* haber más, así que se recarga la primera página en lugar de dejar un hueco.
|
|
815
|
+
*/
|
|
816
|
+
refreshNewer() {
|
|
817
|
+
const entity = this.entity;
|
|
818
|
+
if (!entity) {
|
|
819
|
+
return;
|
|
820
|
+
}
|
|
821
|
+
if (this.status() !== 'ready') {
|
|
822
|
+
if (this.status() !== 'loading') {
|
|
823
|
+
this.load();
|
|
824
|
+
}
|
|
825
|
+
return;
|
|
826
|
+
}
|
|
827
|
+
const newest = maxSentId(this.items());
|
|
828
|
+
if (newest === null) {
|
|
829
|
+
this.load(true);
|
|
830
|
+
return;
|
|
831
|
+
}
|
|
832
|
+
const session = this.sessionId;
|
|
833
|
+
this.session.add(this.gateway.listMessages(entity.type, entity.id, { afterId: newest, limit: CONVERSATION_PAGE_SIZE }).subscribe({
|
|
834
|
+
next: (page) => {
|
|
835
|
+
if (session !== this.sessionId) {
|
|
836
|
+
return;
|
|
837
|
+
}
|
|
838
|
+
if (page.messages.length >= CONVERSATION_PAGE_SIZE) {
|
|
839
|
+
this.load(true);
|
|
840
|
+
return;
|
|
841
|
+
}
|
|
842
|
+
this.upsertMany(page.messages);
|
|
843
|
+
this.markReadLatest();
|
|
844
|
+
},
|
|
845
|
+
// Es una actualización de fondo: lo que hay en pantalla sigue valiendo y el
|
|
846
|
+
// siguiente disparo (volver a la pestaña, reabrir) lo vuelve a intentar.
|
|
847
|
+
error: () => undefined,
|
|
848
|
+
}));
|
|
849
|
+
}
|
|
850
|
+
/** La pestaña del navegador volvió a estar visible. */
|
|
851
|
+
onVisible() {
|
|
852
|
+
if (this.markReadDeferred) {
|
|
853
|
+
this.markReadLatest();
|
|
854
|
+
}
|
|
855
|
+
// También con canal en vivo: si se cayó o perdió el grupo sin avisar, aquí se pone al día.
|
|
856
|
+
this.refreshNewer();
|
|
857
|
+
}
|
|
858
|
+
send(body, mentions) {
|
|
859
|
+
const entity = this.entity;
|
|
860
|
+
const text = body.trim();
|
|
861
|
+
if (!entity || text.length === 0) {
|
|
862
|
+
return;
|
|
863
|
+
}
|
|
864
|
+
const clientMessageId = createClientMessageId();
|
|
865
|
+
const pending = {
|
|
866
|
+
key: `c:${clientMessageId}`,
|
|
867
|
+
id: null,
|
|
868
|
+
clientMessageId,
|
|
869
|
+
source: 'app',
|
|
870
|
+
author: { tdoc: '', ndoc: '' },
|
|
871
|
+
body: text,
|
|
872
|
+
mentions,
|
|
873
|
+
createdAt: new Date().toISOString(),
|
|
874
|
+
editedAt: null,
|
|
875
|
+
deleted: false,
|
|
876
|
+
mine: true,
|
|
877
|
+
status: 'sending',
|
|
878
|
+
error: null,
|
|
879
|
+
};
|
|
880
|
+
this.items.update((list) => [...list, pending]);
|
|
881
|
+
this.post(entity, pending);
|
|
882
|
+
}
|
|
883
|
+
/** Reenvía un mensaje que falló, con el mismo `clientMessageId`: el servicio no lo duplica. */
|
|
884
|
+
retrySend(key) {
|
|
885
|
+
const entity = this.entity;
|
|
886
|
+
const item = this.items().find((i) => i.key === key && i.status === 'failed');
|
|
887
|
+
if (!entity || !item) {
|
|
888
|
+
return;
|
|
889
|
+
}
|
|
890
|
+
this.patch(key, { status: 'sending', error: null });
|
|
891
|
+
this.post(entity, item);
|
|
892
|
+
}
|
|
893
|
+
/** Quita de la lista un mensaje que no se pudo enviar. */
|
|
894
|
+
discard(key) {
|
|
895
|
+
this.items.update((list) => list.filter((i) => !(i.key === key && i.status === 'failed')));
|
|
896
|
+
}
|
|
897
|
+
/** Cambia el texto de un mensaje propio. Resuelve `true` si quedó guardado. */
|
|
898
|
+
edit(item, body) {
|
|
899
|
+
const text = body.trim();
|
|
900
|
+
if (item.id === null || text.length === 0) {
|
|
901
|
+
return Promise.resolve(false);
|
|
902
|
+
}
|
|
903
|
+
const id = item.id;
|
|
904
|
+
return this.run(this.gateway.editMessage(id, text), 'edit', (response) => {
|
|
905
|
+
if (response && typeof response === 'object' && 'id' in response) {
|
|
906
|
+
this.upsertMany([response]);
|
|
907
|
+
}
|
|
908
|
+
else {
|
|
909
|
+
this.patch(item.key, { body: text, editedAt: new Date().toISOString() });
|
|
910
|
+
}
|
|
911
|
+
});
|
|
912
|
+
}
|
|
913
|
+
/** Borrado lógico de un mensaje propio. Resuelve `true` si quedó borrado. */
|
|
914
|
+
remove(item) {
|
|
915
|
+
if (item.id === null) {
|
|
916
|
+
return Promise.resolve(false);
|
|
917
|
+
}
|
|
918
|
+
return this.run(this.gateway.deleteMessage(item.id), 'delete', () => this.patch(item.key, { deleted: true, body: '', mentions: [] }));
|
|
919
|
+
}
|
|
920
|
+
dismissNotice() {
|
|
921
|
+
this.notice.set(null);
|
|
922
|
+
}
|
|
923
|
+
load(silent = false) {
|
|
924
|
+
const entity = this.entity;
|
|
925
|
+
if (!entity) {
|
|
926
|
+
return;
|
|
927
|
+
}
|
|
928
|
+
if (!silent) {
|
|
929
|
+
this.status.set('loading');
|
|
930
|
+
this.loadError.set(null);
|
|
931
|
+
}
|
|
932
|
+
const session = this.sessionId;
|
|
933
|
+
this.session.add(this.gateway.listMessages(entity.type, entity.id, { limit: CONVERSATION_PAGE_SIZE }).subscribe({
|
|
934
|
+
next: (page) => {
|
|
935
|
+
if (session === this.sessionId) {
|
|
936
|
+
this.applyFirstPage(page);
|
|
937
|
+
}
|
|
938
|
+
},
|
|
939
|
+
error: (error) => {
|
|
940
|
+
if (session !== this.sessionId || silent) {
|
|
941
|
+
return;
|
|
942
|
+
}
|
|
943
|
+
this.status.set('error');
|
|
944
|
+
this.loadError.set(describeConversationError(error, 'load'));
|
|
945
|
+
},
|
|
946
|
+
}));
|
|
947
|
+
}
|
|
948
|
+
applyFirstPage(page) {
|
|
949
|
+
const messages = (page.messages ?? []).map(normalize);
|
|
950
|
+
const newestInPage = messages.reduce((max, m) => Math.max(max, m.id), 0);
|
|
951
|
+
// Se conservan los pendientes y lo confirmado después de que se pidió la página (un envío
|
|
952
|
+
// propio o un evento en vivo que llegó mientras cargaba).
|
|
953
|
+
const kept = this.items().filter((i) => i.status !== 'sent' || (i.id ?? 0) > newestInPage);
|
|
954
|
+
const sent = messages.map((m) => this.toItem(m));
|
|
955
|
+
this.items.set(ordered([...sent, ...kept]));
|
|
956
|
+
this.hasOlder.set(messages.length >= CONVERSATION_PAGE_SIZE);
|
|
957
|
+
this.olderStatus.set('idle');
|
|
958
|
+
const lastRead = page.lastReadMessageId ?? null;
|
|
959
|
+
this.lastReadAtOpen.set(lastRead);
|
|
960
|
+
this.lastMarkedRead = Math.max(this.lastMarkedRead, lastRead ?? 0);
|
|
961
|
+
this.status.set('ready');
|
|
962
|
+
this.loadError.set(null);
|
|
963
|
+
this.resolveNames(messages);
|
|
964
|
+
this.markReadLatest();
|
|
965
|
+
}
|
|
966
|
+
post(entity, item) {
|
|
967
|
+
const clientMessageId = item.clientMessageId ?? '';
|
|
968
|
+
// El envío no se corta al cerrar ni al destruir el panel: abortar la petición dejaría en
|
|
969
|
+
// duda si llegó. La respuesta termina la suscripción.
|
|
970
|
+
this.gateway
|
|
971
|
+
.postMessage(entity.type, entity.id, { clientMessageId, body: item.body, mentions: item.mentions })
|
|
972
|
+
.subscribe({
|
|
973
|
+
next: (message) => {
|
|
974
|
+
if (this.isCurrent(entity)) {
|
|
975
|
+
this.upsertMany([{ ...message, mine: true }]);
|
|
976
|
+
}
|
|
977
|
+
},
|
|
978
|
+
error: (error) => {
|
|
979
|
+
if (this.isCurrent(entity)) {
|
|
980
|
+
this.patch(item.key, { status: 'failed', error: describeConversationError(error, 'send') });
|
|
981
|
+
}
|
|
982
|
+
},
|
|
983
|
+
});
|
|
984
|
+
}
|
|
985
|
+
run(request, action, onSuccess) {
|
|
986
|
+
const entity = this.entity;
|
|
987
|
+
this.notice.set(null);
|
|
988
|
+
return new Promise((resolve) => {
|
|
989
|
+
request.pipe(takeUntilDestroyed(this.destroyRef)).subscribe({
|
|
990
|
+
next: (response) => {
|
|
991
|
+
if (entity && this.isCurrent(entity)) {
|
|
992
|
+
onSuccess(response);
|
|
993
|
+
}
|
|
994
|
+
resolve(true);
|
|
995
|
+
},
|
|
996
|
+
error: (error) => {
|
|
997
|
+
if (entity && this.isCurrent(entity)) {
|
|
998
|
+
this.notice.set(describeConversationError(error, action));
|
|
999
|
+
}
|
|
1000
|
+
resolve(false);
|
|
1001
|
+
},
|
|
1002
|
+
// Un observable que completa sin emitir (DELETE sin cuerpo en un mock) también es éxito.
|
|
1003
|
+
complete: () => resolve(true),
|
|
1004
|
+
});
|
|
1005
|
+
});
|
|
1006
|
+
}
|
|
1007
|
+
connectRealtime() {
|
|
1008
|
+
const realtime = this.realtime;
|
|
1009
|
+
const entity = this.entity;
|
|
1010
|
+
if (!realtime || !entity) {
|
|
1011
|
+
return;
|
|
1012
|
+
}
|
|
1013
|
+
const session = this.sessionId;
|
|
1014
|
+
this.session.add(realtime.events$
|
|
1015
|
+
.pipe(filter((e) => String(e.entityType) === entity.type && String(e.entityId) === entity.id))
|
|
1016
|
+
.subscribe((event) => this.applyEvent(event)));
|
|
1017
|
+
if (realtime.reconnected$) {
|
|
1018
|
+
this.session.add(realtime.reconnected$.subscribe(() => this.refreshNewer()));
|
|
1019
|
+
}
|
|
1020
|
+
Promise.resolve()
|
|
1021
|
+
.then(() => realtime.join(entity.type, entity.id))
|
|
1022
|
+
.then(() => {
|
|
1023
|
+
if (session !== this.sessionId) {
|
|
1024
|
+
// Se cerró o cambió de entidad mientras se unía: sale del grupo que ya no mira.
|
|
1025
|
+
Promise.resolve()
|
|
1026
|
+
.then(() => realtime.leave(entity.type, entity.id))
|
|
1027
|
+
.catch(() => undefined);
|
|
1028
|
+
return;
|
|
1029
|
+
}
|
|
1030
|
+
this.live.set(true);
|
|
1031
|
+
// Lo que se escribió entre la primera página y la unión al grupo no llega en vivo.
|
|
1032
|
+
if (this.status() === 'ready') {
|
|
1033
|
+
this.refreshNewer();
|
|
1034
|
+
}
|
|
1035
|
+
}, () => {
|
|
1036
|
+
if (session === this.sessionId) {
|
|
1037
|
+
// Sin grupo, lo nuevo llega al volver a la pestaña; ahora se pide una vez.
|
|
1038
|
+
this.live.set(false);
|
|
1039
|
+
if (this.status() === 'ready') {
|
|
1040
|
+
this.refreshNewer();
|
|
1041
|
+
}
|
|
1042
|
+
}
|
|
1043
|
+
});
|
|
1044
|
+
}
|
|
1045
|
+
applyEvent(event) {
|
|
1046
|
+
if (!event.message) {
|
|
1047
|
+
return;
|
|
1048
|
+
}
|
|
1049
|
+
// El canal no sabe quién mira: `mine` sale de lo que ya había (el eco del mensaje propio se
|
|
1050
|
+
// reconoce por clientMessageId), nunca del evento.
|
|
1051
|
+
const message = { ...event.message, mine: false };
|
|
1052
|
+
const items = this.items();
|
|
1053
|
+
const known = items.some((i) => (i.id !== null && i.id === message.id) ||
|
|
1054
|
+
(message.clientMessageId != null && i.clientMessageId === message.clientMessageId));
|
|
1055
|
+
if (event.change !== 'created') {
|
|
1056
|
+
// Editar o borrar algo que no está en pantalla no cambia nada visible, y agregarlo
|
|
1057
|
+
// dejaría un hueco en la paginación hacia atrás.
|
|
1058
|
+
if (!known) {
|
|
1059
|
+
return;
|
|
1060
|
+
}
|
|
1061
|
+
}
|
|
1062
|
+
else if (!known) {
|
|
1063
|
+
const oldest = minSentId(items);
|
|
1064
|
+
// Más viejo que lo cargado: llegará al pedir los anteriores.
|
|
1065
|
+
if (this.status() === 'ready' && this.hasOlder() && oldest !== null && message.id < oldest) {
|
|
1066
|
+
return;
|
|
1067
|
+
}
|
|
1068
|
+
}
|
|
1069
|
+
this.upsertMany([message]);
|
|
1070
|
+
const item = this.items().find((i) => i.id === message.id);
|
|
1071
|
+
if (event.change === 'created' && !item?.mine) {
|
|
1072
|
+
this.markReadLatest();
|
|
1073
|
+
}
|
|
1074
|
+
}
|
|
1075
|
+
/** Lleva `lastReadMessageId` hasta el mensaje más nuevo, si la persona lo puede estar viendo. */
|
|
1076
|
+
markReadLatest() {
|
|
1077
|
+
const entity = this.entity;
|
|
1078
|
+
const newest = maxSentId(this.items());
|
|
1079
|
+
if (!entity || newest === null || newest <= this.lastMarkedRead) {
|
|
1080
|
+
return;
|
|
1081
|
+
}
|
|
1082
|
+
if (typeof document !== 'undefined' && document.visibilityState === 'hidden') {
|
|
1083
|
+
this.markReadDeferred = true;
|
|
1084
|
+
return;
|
|
1085
|
+
}
|
|
1086
|
+
this.markReadDeferred = false;
|
|
1087
|
+
const previous = this.lastMarkedRead;
|
|
1088
|
+
this.lastMarkedRead = newest;
|
|
1089
|
+
this.gateway
|
|
1090
|
+
.markRead(entity.type, entity.id, newest)
|
|
1091
|
+
.pipe(takeUntilDestroyed(this.destroyRef))
|
|
1092
|
+
.subscribe({
|
|
1093
|
+
// Si falla, el contador de no leídos queda alto; el siguiente mensaje o la
|
|
1094
|
+
// siguiente apertura lo vuelve a intentar.
|
|
1095
|
+
error: () => {
|
|
1096
|
+
if (this.lastMarkedRead === newest) {
|
|
1097
|
+
this.lastMarkedRead = previous;
|
|
1098
|
+
}
|
|
1099
|
+
},
|
|
1100
|
+
});
|
|
1101
|
+
}
|
|
1102
|
+
upsertMany(messages) {
|
|
1103
|
+
if (messages.length === 0) {
|
|
1104
|
+
return;
|
|
1105
|
+
}
|
|
1106
|
+
const incoming = messages.map(normalize);
|
|
1107
|
+
this.items.update((current) => {
|
|
1108
|
+
const list = [...current];
|
|
1109
|
+
for (const message of incoming) {
|
|
1110
|
+
const index = list.findIndex((i) => (i.id !== null && i.id === message.id) ||
|
|
1111
|
+
(message.clientMessageId !== null && i.clientMessageId === message.clientMessageId));
|
|
1112
|
+
if (index >= 0) {
|
|
1113
|
+
const existing = list[index];
|
|
1114
|
+
// El evento en vivo no sabe quién lo mira: se conserva `mine` de lo que ya había.
|
|
1115
|
+
list[index] = { ...this.toItem(message), key: existing.key, mine: message.mine || existing.mine };
|
|
1116
|
+
}
|
|
1117
|
+
else {
|
|
1118
|
+
list.push(this.toItem(message));
|
|
1119
|
+
}
|
|
1120
|
+
}
|
|
1121
|
+
return ordered(list);
|
|
1122
|
+
});
|
|
1123
|
+
this.resolveNames(incoming);
|
|
1124
|
+
}
|
|
1125
|
+
patch(key, changes) {
|
|
1126
|
+
this.items.update((list) => list.map((i) => (i.key === key ? { ...i, ...changes } : i)));
|
|
1127
|
+
}
|
|
1128
|
+
toItem(message) {
|
|
1129
|
+
const key = message.clientMessageId ? `c:${message.clientMessageId}` : `m:${message.id}`;
|
|
1130
|
+
return { ...message, key, status: 'sent', error: null };
|
|
1131
|
+
}
|
|
1132
|
+
resolveNames(messages) {
|
|
1133
|
+
const refs = [];
|
|
1134
|
+
for (const message of messages) {
|
|
1135
|
+
if (!message.mine) {
|
|
1136
|
+
refs.push(message.author);
|
|
1137
|
+
}
|
|
1138
|
+
refs.push(...message.mentions);
|
|
1139
|
+
}
|
|
1140
|
+
this.names.ensure(refs);
|
|
1141
|
+
}
|
|
1142
|
+
isCurrent(entity) {
|
|
1143
|
+
return this.entity?.type === entity.type && this.entity?.id === entity.id;
|
|
1144
|
+
}
|
|
1145
|
+
endSession() {
|
|
1146
|
+
const realtime = this.realtime;
|
|
1147
|
+
const entity = this.entity;
|
|
1148
|
+
if (realtime && entity && this.live()) {
|
|
1149
|
+
Promise.resolve()
|
|
1150
|
+
.then(() => realtime.leave(entity.type, entity.id))
|
|
1151
|
+
// Salir del grupo es limpieza: si falla, el hub lo suelta al desconectarse.
|
|
1152
|
+
.catch(() => undefined);
|
|
1153
|
+
}
|
|
1154
|
+
this.live.set(false);
|
|
1155
|
+
this.session.unsubscribe();
|
|
1156
|
+
this.session = new Subscription();
|
|
1157
|
+
this.sessionId++;
|
|
1158
|
+
}
|
|
1159
|
+
reset() {
|
|
1160
|
+
this.items.set([]);
|
|
1161
|
+
this.status.set('idle');
|
|
1162
|
+
this.loadError.set(null);
|
|
1163
|
+
this.hasOlder.set(false);
|
|
1164
|
+
this.olderStatus.set('idle');
|
|
1165
|
+
this.lastReadAtOpen.set(null);
|
|
1166
|
+
this.notice.set(null);
|
|
1167
|
+
this.draft.set('');
|
|
1168
|
+
this.draftMentions.set([]);
|
|
1169
|
+
this.lastMarkedRead = 0;
|
|
1170
|
+
this.markReadDeferred = false;
|
|
1171
|
+
}
|
|
1172
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: ConversationStore, deps: [], target: i0.ɵɵFactoryTarget.Injectable });
|
|
1173
|
+
static ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: ConversationStore });
|
|
1174
|
+
}
|
|
1175
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: ConversationStore, decorators: [{
|
|
1176
|
+
type: Injectable
|
|
1177
|
+
}] });
|
|
1178
|
+
|
|
1179
|
+
/** Largo máximo que acepta el servicio. */
|
|
1180
|
+
const CONVERSATION_MAX_LENGTH = 4000;
|
|
1181
|
+
const MAX_SUGGESTIONS = 8;
|
|
1182
|
+
/** Corta la búsqueda pendiente sin consultar al directorio. */
|
|
1183
|
+
const RESET = '\u0000';
|
|
1184
|
+
let nextId$1 = 0;
|
|
1185
|
+
/**
|
|
1186
|
+
* Campo para escribir un mensaje, con la lista de personas para mencionar al escribir `@`.
|
|
1187
|
+
* El borrador vive en el store, así que no se pierde al cerrar y reabrir el panel.
|
|
1188
|
+
*/
|
|
1189
|
+
class ConversationComposerComponent {
|
|
1190
|
+
store = inject(ConversationStore);
|
|
1191
|
+
names = inject(ConversationUserNames);
|
|
1192
|
+
directory = inject(CONVERSATION_DIRECTORY, { optional: true });
|
|
1193
|
+
input = viewChild.required('input');
|
|
1194
|
+
uid = nextId$1++;
|
|
1195
|
+
inputId = `sfc-composer-${this.uid}`;
|
|
1196
|
+
hintId = `sfc-composer-hint-${this.uid}`;
|
|
1197
|
+
listId = `sfc-mentions-${this.uid}`;
|
|
1198
|
+
maxLength = CONVERSATION_MAX_LENGTH;
|
|
1199
|
+
suggestions = signal([]);
|
|
1200
|
+
active = signal(0);
|
|
1201
|
+
mentionStart = signal(null);
|
|
1202
|
+
query$ = new Subject();
|
|
1203
|
+
suggestionsOpen = computed(() => this.mentionStart() !== null && this.suggestions().length > 0);
|
|
1204
|
+
remaining = computed(() => CONVERSATION_MAX_LENGTH - this.store.draft().length);
|
|
1205
|
+
canSend = computed(() => this.store.draft().trim().length > 0);
|
|
1206
|
+
/** Lo que anuncia el lector de pantalla al abrirse la lista de menciones. */
|
|
1207
|
+
suggestionsAnnouncement = computed(() => {
|
|
1208
|
+
const count = this.suggestionsOpen() ? this.suggestions().length : 0;
|
|
1209
|
+
if (count === 0) {
|
|
1210
|
+
return '';
|
|
1211
|
+
}
|
|
1212
|
+
return count === 1
|
|
1213
|
+
? '1 persona para mencionar. Use las flechas para elegir.'
|
|
1214
|
+
: `${count} personas para mencionar. Use las flechas para elegir.`;
|
|
1215
|
+
});
|
|
1216
|
+
activeOptionId = computed(() => (this.suggestionsOpen() ? this.optionId(this.active()) : null));
|
|
1217
|
+
/**
|
|
1218
|
+
* En una pantalla táctil no hay Shift+Enter: ahí Enter hace salto de línea y se envía con el
|
|
1219
|
+
* botón. Con teclado físico, Enter envía.
|
|
1220
|
+
*/
|
|
1221
|
+
enterSends = !(globalThis.matchMedia?.('(pointer: coarse)').matches ?? false);
|
|
1222
|
+
constructor() {
|
|
1223
|
+
this.query$
|
|
1224
|
+
.pipe(debounceTime(200), distinctUntilChanged(), switchMap((query) => this.directory && query !== RESET
|
|
1225
|
+
? this.directory.searchUsers(query).pipe(catchError(() => of([])))
|
|
1226
|
+
: of([])), takeUntilDestroyed(inject(DestroyRef)))
|
|
1227
|
+
.subscribe((users) => {
|
|
1228
|
+
this.suggestions.set(users.slice(0, MAX_SUGGESTIONS));
|
|
1229
|
+
this.active.set(0);
|
|
1230
|
+
});
|
|
1231
|
+
}
|
|
1232
|
+
/** Pone el foco en el campo, por ejemplo al abrir el panel. */
|
|
1233
|
+
focus() {
|
|
1234
|
+
this.input().nativeElement.focus();
|
|
1235
|
+
}
|
|
1236
|
+
optionId(index) {
|
|
1237
|
+
return `${this.listId}-${index}`;
|
|
1238
|
+
}
|
|
1239
|
+
userKey(user) {
|
|
1240
|
+
return userKey(user);
|
|
1241
|
+
}
|
|
1242
|
+
onInput() {
|
|
1243
|
+
this.store.draft.set(this.input().nativeElement.value);
|
|
1244
|
+
this.updateMention();
|
|
1245
|
+
}
|
|
1246
|
+
updateMention() {
|
|
1247
|
+
if (!this.directory) {
|
|
1248
|
+
return;
|
|
1249
|
+
}
|
|
1250
|
+
const element = this.input().nativeElement;
|
|
1251
|
+
const found = mentionQueryAt(element.value, element.selectionStart ?? element.value.length);
|
|
1252
|
+
if (!found) {
|
|
1253
|
+
this.closeSuggestions();
|
|
1254
|
+
return;
|
|
1255
|
+
}
|
|
1256
|
+
this.mentionStart.set(found.start);
|
|
1257
|
+
this.query$.next(found.query);
|
|
1258
|
+
}
|
|
1259
|
+
closeSuggestions() {
|
|
1260
|
+
this.mentionStart.set(null);
|
|
1261
|
+
this.suggestions.set([]);
|
|
1262
|
+
// Descarta la búsqueda pendiente y deja que la misma vuelva a disparar al escribir otra vez `@`.
|
|
1263
|
+
this.query$.next(RESET);
|
|
1264
|
+
}
|
|
1265
|
+
onKeydown(event) {
|
|
1266
|
+
if (event.isComposing) {
|
|
1267
|
+
return;
|
|
1268
|
+
}
|
|
1269
|
+
if (this.suggestionsOpen()) {
|
|
1270
|
+
const count = this.suggestions().length;
|
|
1271
|
+
switch (event.key) {
|
|
1272
|
+
case 'ArrowDown':
|
|
1273
|
+
event.preventDefault();
|
|
1274
|
+
this.active.update((i) => (i + 1) % count);
|
|
1275
|
+
return;
|
|
1276
|
+
case 'ArrowUp':
|
|
1277
|
+
event.preventDefault();
|
|
1278
|
+
this.active.update((i) => (i - 1 + count) % count);
|
|
1279
|
+
return;
|
|
1280
|
+
case 'Enter':
|
|
1281
|
+
case 'Tab': {
|
|
1282
|
+
event.preventDefault();
|
|
1283
|
+
const user = this.suggestions()[this.active()];
|
|
1284
|
+
if (user) {
|
|
1285
|
+
this.pick(user);
|
|
1286
|
+
}
|
|
1287
|
+
return;
|
|
1288
|
+
}
|
|
1289
|
+
case 'Escape':
|
|
1290
|
+
// Cierra la lista sin cerrar el panel.
|
|
1291
|
+
event.preventDefault();
|
|
1292
|
+
event.stopPropagation();
|
|
1293
|
+
this.closeSuggestions();
|
|
1294
|
+
return;
|
|
1295
|
+
}
|
|
1296
|
+
}
|
|
1297
|
+
if (event.key === 'Enter' && !event.shiftKey && this.enterSends) {
|
|
1298
|
+
event.preventDefault();
|
|
1299
|
+
this.send();
|
|
1300
|
+
}
|
|
1301
|
+
}
|
|
1302
|
+
pick(user) {
|
|
1303
|
+
const start = this.mentionStart();
|
|
1304
|
+
const element = this.input().nativeElement;
|
|
1305
|
+
if (start === null) {
|
|
1306
|
+
return;
|
|
1307
|
+
}
|
|
1308
|
+
const caret = element.selectionStart ?? element.value.length;
|
|
1309
|
+
const inserted = `@${user.name} `;
|
|
1310
|
+
const value = element.value.slice(0, start) + inserted + element.value.slice(caret);
|
|
1311
|
+
element.value = value;
|
|
1312
|
+
this.store.draft.set(value);
|
|
1313
|
+
this.store.draftMentions.update((list) => list.some((u) => userKey(u) === userKey(user)) ? list : [...list, user]);
|
|
1314
|
+
this.names.remember([user]);
|
|
1315
|
+
this.closeSuggestions();
|
|
1316
|
+
const position = start + inserted.length;
|
|
1317
|
+
element.setSelectionRange(position, position);
|
|
1318
|
+
element.focus();
|
|
1319
|
+
}
|
|
1320
|
+
send() {
|
|
1321
|
+
const body = this.store.draft().trim();
|
|
1322
|
+
if (body.length === 0) {
|
|
1323
|
+
return;
|
|
1324
|
+
}
|
|
1325
|
+
// Solo cuentan las menciones cuyo `@nombre` sigue en el texto.
|
|
1326
|
+
const mentions = this.store
|
|
1327
|
+
.draftMentions()
|
|
1328
|
+
.filter((user) => body.includes(`@${user.name}`))
|
|
1329
|
+
.map((user) => ({ tdoc: user.tdoc, ndoc: user.ndoc }));
|
|
1330
|
+
this.store.send(body, mentions);
|
|
1331
|
+
this.store.draft.set('');
|
|
1332
|
+
this.store.draftMentions.set([]);
|
|
1333
|
+
this.input().nativeElement.value = '';
|
|
1334
|
+
this.closeSuggestions();
|
|
1335
|
+
}
|
|
1336
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: ConversationComposerComponent, deps: [], target: i0.ɵɵFactoryTarget.Component });
|
|
1337
|
+
static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "19.2.17", type: ConversationComposerComponent, isStandalone: true, selector: "lib-conversation-composer", viewQueries: [{ propertyName: "input", first: true, predicate: ["input"], descendants: true, isSignal: true }], ngImport: i0, template: "<div class=\"sfc-composer\">\r\n @if (suggestionsOpen()) {\r\n <ul class=\"sfc-suggestions\" role=\"listbox\" [id]=\"listId\" aria-label=\"Personas para mencionar\">\r\n @for (user of suggestions(); track userKey(user); let i = $index) {\r\n <!-- mousedown sin foco: si no, el blur del campo cierra la lista antes del clic -->\r\n <li\r\n role=\"option\"\r\n class=\"sfc-suggestion\"\r\n [id]=\"optionId(i)\"\r\n [attr.aria-selected]=\"i === active()\"\r\n [class.sfc-suggestion--active]=\"i === active()\"\r\n (mousedown)=\"$event.preventDefault()\"\r\n (click)=\"pick(user)\"\r\n >\r\n <span class=\"sfc-suggestion-name\">{{ user.name }}</span>\r\n @if (user.detail) {\r\n <span class=\"sfc-suggestion-detail\">{{ user.detail }}</span>\r\n }\r\n </li>\r\n }\r\n </ul>\r\n }\r\n\r\n <span class=\"sfc-sr-only\" aria-live=\"polite\">{{ suggestionsAnnouncement() }}</span>\r\n <label class=\"sfc-sr-only\" [for]=\"inputId\">Mensaje</label>\r\n <div class=\"sfc-composer-row\">\r\n <textarea\r\n #input\r\n pTextarea\r\n class=\"sfc-composer-input\"\r\n rows=\"2\"\r\n [id]=\"inputId\"\r\n [autoResize]=\"true\"\r\n [attr.maxlength]=\"maxLength\"\r\n [value]=\"store.draft()\"\r\n placeholder=\"Escriba un mensaje. Use @ para mencionar.\"\r\n aria-autocomplete=\"list\"\r\n [attr.aria-controls]=\"suggestionsOpen() ? listId : null\"\r\n [attr.aria-activedescendant]=\"activeOptionId()\"\r\n [attr.aria-describedby]=\"hintId\"\r\n (input)=\"onInput()\"\r\n (keydown)=\"onKeydown($event)\"\r\n (click)=\"updateMention()\"\r\n (blur)=\"closeSuggestions()\"\r\n ></textarea>\r\n <p-button icon=\"pi pi-send\" ariaLabel=\"Enviar mensaje\" [disabled]=\"!canSend()\" (onClick)=\"send()\" />\r\n </div>\r\n <small class=\"sfc-hint\" [id]=\"hintId\">\r\n @if (enterSends) {\r\n Enter env\u00EDa; Shift+Enter agrega una l\u00EDnea.\r\n }\r\n @if (remaining() <= 500) {\r\n Quedan {{ remaining() }} caracteres.\r\n }\r\n </small>\r\n</div>\r\n", styles: [":host{display:block}.sfc-composer{position:relative;display:flex;flex-direction:column;gap:.25rem}.sfc-composer-row{display:flex;align-items:flex-end;gap:.5rem}.sfc-composer-input{flex:1 1 auto;min-width:0;max-height:10rem;resize:none}.sfc-hint{color:var(--p-text-muted-color)}.sfc-suggestions{position:absolute;left:0;right:0;bottom:100%;margin:0 0 .25rem;padding:.25rem;list-style:none;max-height:16rem;overflow-y:auto;background:var(--p-content-background);color:var(--p-text-color);border:1px solid var(--p-content-border-color);border-radius:var(--p-content-border-radius);box-shadow:var(--p-menu-shadow);z-index:1}.sfc-suggestion{display:flex;flex-direction:column;padding:.5rem .75rem;min-height:44px;justify-content:center;border-radius:var(--p-content-border-radius);cursor:pointer}.sfc-suggestion:hover{background:var(--p-content-hover-background)}.sfc-suggestion--active{background:var(--p-highlight-background);color:var(--p-highlight-color)}.sfc-suggestion--active:hover{background:var(--p-highlight-background)}.sfc-suggestion-detail{font-size:.875em;color:var(--p-text-muted-color)}.sfc-suggestion--active .sfc-suggestion-detail{color:inherit}.sfc-sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}\n"], dependencies: [{ kind: "ngmodule", type: ButtonModule }, { kind: "component", type: i1.Button, selector: "p-button", inputs: ["type", "iconPos", "icon", "badge", "label", "disabled", "loading", "loadingIcon", "raised", "rounded", "text", "plain", "severity", "outlined", "link", "tabindex", "size", "variant", "style", "styleClass", "badgeClass", "badgeSeverity", "ariaLabel", "autofocus", "fluid", "buttonProps"], outputs: ["onClick", "onFocus", "onBlur"] }, { kind: "ngmodule", type: TextareaModule }, { kind: "directive", type: i2.Textarea, selector: "[pTextarea], [pInputTextarea]", inputs: ["autoResize", "variant", "fluid", "pSize"], outputs: ["onResize"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
|
|
1338
|
+
}
|
|
1339
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: ConversationComposerComponent, decorators: [{
|
|
1340
|
+
type: Component,
|
|
1341
|
+
args: [{ selector: 'lib-conversation-composer', standalone: true, imports: [ButtonModule, TextareaModule], changeDetection: ChangeDetectionStrategy.OnPush, template: "<div class=\"sfc-composer\">\r\n @if (suggestionsOpen()) {\r\n <ul class=\"sfc-suggestions\" role=\"listbox\" [id]=\"listId\" aria-label=\"Personas para mencionar\">\r\n @for (user of suggestions(); track userKey(user); let i = $index) {\r\n <!-- mousedown sin foco: si no, el blur del campo cierra la lista antes del clic -->\r\n <li\r\n role=\"option\"\r\n class=\"sfc-suggestion\"\r\n [id]=\"optionId(i)\"\r\n [attr.aria-selected]=\"i === active()\"\r\n [class.sfc-suggestion--active]=\"i === active()\"\r\n (mousedown)=\"$event.preventDefault()\"\r\n (click)=\"pick(user)\"\r\n >\r\n <span class=\"sfc-suggestion-name\">{{ user.name }}</span>\r\n @if (user.detail) {\r\n <span class=\"sfc-suggestion-detail\">{{ user.detail }}</span>\r\n }\r\n </li>\r\n }\r\n </ul>\r\n }\r\n\r\n <span class=\"sfc-sr-only\" aria-live=\"polite\">{{ suggestionsAnnouncement() }}</span>\r\n <label class=\"sfc-sr-only\" [for]=\"inputId\">Mensaje</label>\r\n <div class=\"sfc-composer-row\">\r\n <textarea\r\n #input\r\n pTextarea\r\n class=\"sfc-composer-input\"\r\n rows=\"2\"\r\n [id]=\"inputId\"\r\n [autoResize]=\"true\"\r\n [attr.maxlength]=\"maxLength\"\r\n [value]=\"store.draft()\"\r\n placeholder=\"Escriba un mensaje. Use @ para mencionar.\"\r\n aria-autocomplete=\"list\"\r\n [attr.aria-controls]=\"suggestionsOpen() ? listId : null\"\r\n [attr.aria-activedescendant]=\"activeOptionId()\"\r\n [attr.aria-describedby]=\"hintId\"\r\n (input)=\"onInput()\"\r\n (keydown)=\"onKeydown($event)\"\r\n (click)=\"updateMention()\"\r\n (blur)=\"closeSuggestions()\"\r\n ></textarea>\r\n <p-button icon=\"pi pi-send\" ariaLabel=\"Enviar mensaje\" [disabled]=\"!canSend()\" (onClick)=\"send()\" />\r\n </div>\r\n <small class=\"sfc-hint\" [id]=\"hintId\">\r\n @if (enterSends) {\r\n Enter env\u00EDa; Shift+Enter agrega una l\u00EDnea.\r\n }\r\n @if (remaining() <= 500) {\r\n Quedan {{ remaining() }} caracteres.\r\n }\r\n </small>\r\n</div>\r\n", styles: [":host{display:block}.sfc-composer{position:relative;display:flex;flex-direction:column;gap:.25rem}.sfc-composer-row{display:flex;align-items:flex-end;gap:.5rem}.sfc-composer-input{flex:1 1 auto;min-width:0;max-height:10rem;resize:none}.sfc-hint{color:var(--p-text-muted-color)}.sfc-suggestions{position:absolute;left:0;right:0;bottom:100%;margin:0 0 .25rem;padding:.25rem;list-style:none;max-height:16rem;overflow-y:auto;background:var(--p-content-background);color:var(--p-text-color);border:1px solid var(--p-content-border-color);border-radius:var(--p-content-border-radius);box-shadow:var(--p-menu-shadow);z-index:1}.sfc-suggestion{display:flex;flex-direction:column;padding:.5rem .75rem;min-height:44px;justify-content:center;border-radius:var(--p-content-border-radius);cursor:pointer}.sfc-suggestion:hover{background:var(--p-content-hover-background)}.sfc-suggestion--active{background:var(--p-highlight-background);color:var(--p-highlight-color)}.sfc-suggestion--active:hover{background:var(--p-highlight-background)}.sfc-suggestion-detail{font-size:.875em;color:var(--p-text-muted-color)}.sfc-suggestion--active .sfc-suggestion-detail{color:inherit}.sfc-sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}\n"] }]
|
|
1342
|
+
}], ctorParameters: () => [] });
|
|
1343
|
+
|
|
1344
|
+
/** Ancho del panel en escritorio. Por debajo de `MOBILE_QUERY` ocupa toda la pantalla. */
|
|
1345
|
+
const DESKTOP_WIDTH = '420px';
|
|
1346
|
+
const MOBILE_QUERY = '(max-width: 767px)';
|
|
1347
|
+
/** Distancia al final (px) dentro de la cual un mensaje nuevo baja la lista solo. */
|
|
1348
|
+
const STICK_TO_BOTTOM = 80;
|
|
1349
|
+
let nextId = 0;
|
|
1350
|
+
/**
|
|
1351
|
+
* Panel lateral con la conversación de una entidad (un crédito, una solicitud).
|
|
1352
|
+
*
|
|
1353
|
+
* No bloquea la pantalla en escritorio y ocupa toda la pantalla en el celular. Pide los mensajes al
|
|
1354
|
+
* abrirse, de 30 en 30 hacia atrás. Los permisos los decide el front con `canView` y `canPost`; el
|
|
1355
|
+
* que los hace cumplir es el APIM.
|
|
1356
|
+
*/
|
|
1357
|
+
class ConversationPanelComponent {
|
|
1358
|
+
/** Tipo de entidad que entiende el servicio, por ejemplo el de un crédito o una solicitud. */
|
|
1359
|
+
entityType = input.required();
|
|
1360
|
+
entityId = input.required({ transform: (value) => String(value) });
|
|
1361
|
+
/** Puede leer la conversación. Sin esto el panel no se abre. */
|
|
1362
|
+
canView = input.required();
|
|
1363
|
+
/** Puede escribir, editar y borrar lo propio. Sin esto el panel es de solo lectura. */
|
|
1364
|
+
canPost = input.required();
|
|
1365
|
+
/** Abierto o cerrado. Admite `[(visible)]`. */
|
|
1366
|
+
visible = model(false);
|
|
1367
|
+
/** Emite cuando el panel se abre o se cierra, para que el front oculte lo que estorbe. */
|
|
1368
|
+
openChange = output();
|
|
1369
|
+
store = inject(ConversationStore);
|
|
1370
|
+
names = inject(ConversationUserNames);
|
|
1371
|
+
document = inject(DOCUMENT);
|
|
1372
|
+
injector = inject(Injector);
|
|
1373
|
+
scroller = viewChild('scroller');
|
|
1374
|
+
composer = viewChild(ConversationComposerComponent);
|
|
1375
|
+
actionsMenu = viewChild('actionsMenu');
|
|
1376
|
+
isOpen = computed(() => this.visible() && this.canView());
|
|
1377
|
+
isMobile = signal(false);
|
|
1378
|
+
drawerStyle = computed(() => (this.isMobile() ? undefined : { width: DESKTOP_WIDTH, maxWidth: '100vw' }));
|
|
1379
|
+
maxLength = CONVERSATION_MAX_LENGTH;
|
|
1380
|
+
titleId = `sfc-title-${nextId++}`;
|
|
1381
|
+
menuItems = signal([]);
|
|
1382
|
+
editingKey = signal(null);
|
|
1383
|
+
editText = signal('');
|
|
1384
|
+
saving = signal(false);
|
|
1385
|
+
confirmDeleteKey = signal(null);
|
|
1386
|
+
deleting = signal(false);
|
|
1387
|
+
view = computed(() => {
|
|
1388
|
+
const names = this.names.resolved();
|
|
1389
|
+
const lastRead = this.store.lastReadAtOpen() ?? 0;
|
|
1390
|
+
let dividerPlaced = false;
|
|
1391
|
+
return this.store.items().map((item) => {
|
|
1392
|
+
const divider = !dividerPlaced && item.status === 'sent' && !item.mine && (item.id ?? 0) > lastRead;
|
|
1393
|
+
dividerPlaced ||= divider;
|
|
1394
|
+
const mentionNames = item.mentions
|
|
1395
|
+
.map((user) => names.get(userKey(user)))
|
|
1396
|
+
.filter((name) => !!name);
|
|
1397
|
+
return {
|
|
1398
|
+
item,
|
|
1399
|
+
divider,
|
|
1400
|
+
author: item.mine ? 'Usted' : this.names.label(item.author, names),
|
|
1401
|
+
segments: item.deleted ? [] : splitMentions(item.body, mentionNames),
|
|
1402
|
+
};
|
|
1403
|
+
});
|
|
1404
|
+
});
|
|
1405
|
+
wasOpen = false;
|
|
1406
|
+
openerElement = null;
|
|
1407
|
+
nearBottom = true;
|
|
1408
|
+
lastScroller = null;
|
|
1409
|
+
lastSeenKey;
|
|
1410
|
+
pendingPrepend = null;
|
|
1411
|
+
constructor() {
|
|
1412
|
+
const destroyRef = inject(DestroyRef);
|
|
1413
|
+
this.watchViewport(destroyRef);
|
|
1414
|
+
effect(() => {
|
|
1415
|
+
const open = this.isOpen();
|
|
1416
|
+
const type = this.entityType();
|
|
1417
|
+
const id = this.entityId();
|
|
1418
|
+
untracked(() => {
|
|
1419
|
+
if (open) {
|
|
1420
|
+
if (!this.wasOpen) {
|
|
1421
|
+
this.openerElement = this.document.activeElement;
|
|
1422
|
+
}
|
|
1423
|
+
this.cancelMessageActions();
|
|
1424
|
+
this.store.open(type, id);
|
|
1425
|
+
}
|
|
1426
|
+
else if (this.wasOpen) {
|
|
1427
|
+
this.store.close();
|
|
1428
|
+
}
|
|
1429
|
+
if (open !== this.wasOpen) {
|
|
1430
|
+
this.wasOpen = open;
|
|
1431
|
+
this.openChange.emit(open);
|
|
1432
|
+
if (!open) {
|
|
1433
|
+
this.restoreFocus();
|
|
1434
|
+
}
|
|
1435
|
+
}
|
|
1436
|
+
});
|
|
1437
|
+
});
|
|
1438
|
+
// Mantiene la lista abajo cuando llega un mensaje, y quieta cuando se cargan los anteriores.
|
|
1439
|
+
effect(() => {
|
|
1440
|
+
const items = this.view();
|
|
1441
|
+
// El elemento de la lista cambia al reabrir el panel: también hay que ubicarlo.
|
|
1442
|
+
this.scroller();
|
|
1443
|
+
const last = items.at(-1)?.item;
|
|
1444
|
+
untracked(() => afterNextRender(() => this.adjustScroll(last), { injector: this.injector }));
|
|
1445
|
+
});
|
|
1446
|
+
if (this.document.defaultView) {
|
|
1447
|
+
// Escape cierra el panel cuando el foco está dentro. Lo hace el panel y no p-drawer: el
|
|
1448
|
+
// escucha de p-drawer en el documento también se llevaba el Escape del menú de un
|
|
1449
|
+
// mensaje, y su manejador del contenedor no emite visibleChange sin modal. Los Escape
|
|
1450
|
+
// de la lista de menciones y de la edición ya llegan con preventDefault.
|
|
1451
|
+
fromEvent(this.document, 'keydown')
|
|
1452
|
+
.pipe(takeUntilDestroyed(destroyRef))
|
|
1453
|
+
.subscribe((event) => {
|
|
1454
|
+
const target = event.target;
|
|
1455
|
+
if (event.key === 'Escape' && !event.defaultPrevented && this.isOpen() && target?.closest?.('.sfc-drawer')) {
|
|
1456
|
+
event.preventDefault();
|
|
1457
|
+
this.close();
|
|
1458
|
+
}
|
|
1459
|
+
});
|
|
1460
|
+
fromEvent(this.document, 'visibilitychange')
|
|
1461
|
+
.pipe(takeUntilDestroyed(destroyRef))
|
|
1462
|
+
.subscribe(() => {
|
|
1463
|
+
if (this.isOpen() && this.document.visibilityState === 'visible') {
|
|
1464
|
+
this.store.onVisible();
|
|
1465
|
+
}
|
|
1466
|
+
});
|
|
1467
|
+
}
|
|
1468
|
+
}
|
|
1469
|
+
ngOnDestroy() {
|
|
1470
|
+
// Si el front quita el panel abierto (navegó a otra pantalla), que sepa que ya no está.
|
|
1471
|
+
if (this.wasOpen) {
|
|
1472
|
+
this.wasOpen = false;
|
|
1473
|
+
this.store.close();
|
|
1474
|
+
// ngOnDestroy corre antes de que Angular destruya el output, así que todavía se puede emitir.
|
|
1475
|
+
this.openChange.emit(false);
|
|
1476
|
+
}
|
|
1477
|
+
}
|
|
1478
|
+
close() {
|
|
1479
|
+
this.visible.set(false);
|
|
1480
|
+
}
|
|
1481
|
+
onDrawerVisibleChange(visible) {
|
|
1482
|
+
this.visible.set(visible);
|
|
1483
|
+
}
|
|
1484
|
+
onShown() {
|
|
1485
|
+
// p-drawer mueve su contenedor a body al empezar a mostrarse, y mover un elemento reinicia
|
|
1486
|
+
// su scroll: se vuelve a ubicar la lista aquí, que corre después del movimiento.
|
|
1487
|
+
this.lastScroller = null;
|
|
1488
|
+
this.adjustScroll(this.view().at(-1)?.item);
|
|
1489
|
+
afterNextRender(() => {
|
|
1490
|
+
const title = this.document.getElementById(this.titleId);
|
|
1491
|
+
// p-drawer pone role="complementary" sin nombre: se lo da el título.
|
|
1492
|
+
title?.closest('.p-drawer')?.setAttribute('aria-labelledby', this.titleId);
|
|
1493
|
+
// El foco entra al panel (se monta al final de body). Al campo de texto solo en
|
|
1494
|
+
// escritorio: en el celular el teclado taparía los mensajes al abrir.
|
|
1495
|
+
const composer = this.composer();
|
|
1496
|
+
if (this.canPost() && !this.isMobile() && composer) {
|
|
1497
|
+
composer.focus();
|
|
1498
|
+
}
|
|
1499
|
+
else {
|
|
1500
|
+
title?.focus();
|
|
1501
|
+
}
|
|
1502
|
+
}, { injector: this.injector });
|
|
1503
|
+
}
|
|
1504
|
+
onScroll() {
|
|
1505
|
+
const el = this.scroller()?.nativeElement;
|
|
1506
|
+
if (el) {
|
|
1507
|
+
this.nearBottom = el.scrollHeight - el.scrollTop - el.clientHeight < STICK_TO_BOTTOM;
|
|
1508
|
+
}
|
|
1509
|
+
}
|
|
1510
|
+
loadOlder() {
|
|
1511
|
+
const el = this.scroller()?.nativeElement;
|
|
1512
|
+
if (el) {
|
|
1513
|
+
this.pendingPrepend = { height: el.scrollHeight, top: el.scrollTop };
|
|
1514
|
+
}
|
|
1515
|
+
this.store.loadOlder();
|
|
1516
|
+
}
|
|
1517
|
+
openActions(event, item) {
|
|
1518
|
+
this.menuItems.set([
|
|
1519
|
+
{ label: 'Editar', icon: 'pi pi-pencil', command: () => this.startEdit(item) },
|
|
1520
|
+
{ label: 'Borrar', icon: 'pi pi-trash', command: () => this.askDelete(item) },
|
|
1521
|
+
]);
|
|
1522
|
+
this.actionsMenu()?.toggle(event);
|
|
1523
|
+
}
|
|
1524
|
+
canAct(item) {
|
|
1525
|
+
return this.canPost() && item.mine && item.status === 'sent' && !item.deleted && item.id !== null;
|
|
1526
|
+
}
|
|
1527
|
+
startEdit(item) {
|
|
1528
|
+
this.confirmDeleteKey.set(null);
|
|
1529
|
+
this.editingKey.set(item.key);
|
|
1530
|
+
this.editText.set(item.body);
|
|
1531
|
+
afterNextRender(() => this.focusById(`sfc-edit-${item.key}`), { injector: this.injector });
|
|
1532
|
+
}
|
|
1533
|
+
onEditKeydown(event, item) {
|
|
1534
|
+
if (event.key === 'Escape') {
|
|
1535
|
+
event.preventDefault();
|
|
1536
|
+
event.stopPropagation();
|
|
1537
|
+
this.cancelMessageActions(item);
|
|
1538
|
+
}
|
|
1539
|
+
else if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) {
|
|
1540
|
+
event.preventDefault();
|
|
1541
|
+
void this.saveEdit(item);
|
|
1542
|
+
}
|
|
1543
|
+
}
|
|
1544
|
+
async saveEdit(item) {
|
|
1545
|
+
const text = this.editText().trim();
|
|
1546
|
+
if (this.saving() || text.length === 0) {
|
|
1547
|
+
return;
|
|
1548
|
+
}
|
|
1549
|
+
if (text === item.body) {
|
|
1550
|
+
this.cancelMessageActions();
|
|
1551
|
+
return;
|
|
1552
|
+
}
|
|
1553
|
+
this.saving.set(true);
|
|
1554
|
+
const saved = await this.store.edit(item, text);
|
|
1555
|
+
this.saving.set(false);
|
|
1556
|
+
if (saved) {
|
|
1557
|
+
this.cancelMessageActions(item);
|
|
1558
|
+
}
|
|
1559
|
+
}
|
|
1560
|
+
askDelete(item) {
|
|
1561
|
+
this.editingKey.set(null);
|
|
1562
|
+
this.confirmDeleteKey.set(item.key);
|
|
1563
|
+
// El foco va a "Cancelar", la opción que no destruye nada.
|
|
1564
|
+
afterNextRender(() => this.document.getElementById(`sfc-confirm-${item.key}`)?.querySelector('button')?.focus(), {
|
|
1565
|
+
injector: this.injector,
|
|
1566
|
+
});
|
|
1567
|
+
}
|
|
1568
|
+
async confirmDelete(item) {
|
|
1569
|
+
if (this.deleting()) {
|
|
1570
|
+
return;
|
|
1571
|
+
}
|
|
1572
|
+
this.deleting.set(true);
|
|
1573
|
+
const deleted = await this.store.remove(item);
|
|
1574
|
+
this.deleting.set(false);
|
|
1575
|
+
if (deleted) {
|
|
1576
|
+
this.cancelMessageActions(item);
|
|
1577
|
+
}
|
|
1578
|
+
}
|
|
1579
|
+
/**
|
|
1580
|
+
* Cierra la edición o la confirmación de borrado. Con `item`, el foco vuelve a ese mensaje (a su
|
|
1581
|
+
* botón de acciones, o al mensaje si ya no tiene) para no perderse en `body`.
|
|
1582
|
+
*/
|
|
1583
|
+
cancelMessageActions(item) {
|
|
1584
|
+
this.editingKey.set(null);
|
|
1585
|
+
this.confirmDeleteKey.set(null);
|
|
1586
|
+
this.editText.set('');
|
|
1587
|
+
if (item) {
|
|
1588
|
+
afterNextRender(() => {
|
|
1589
|
+
const article = this.document.getElementById(this.messageId(item));
|
|
1590
|
+
const target = article?.querySelector('.sfc-actions button') ?? article;
|
|
1591
|
+
target?.focus();
|
|
1592
|
+
}, { injector: this.injector });
|
|
1593
|
+
}
|
|
1594
|
+
}
|
|
1595
|
+
messageId(item) {
|
|
1596
|
+
return `sfc-message-${item.key}`;
|
|
1597
|
+
}
|
|
1598
|
+
editId(item) {
|
|
1599
|
+
return `sfc-edit-${item.key}`;
|
|
1600
|
+
}
|
|
1601
|
+
adjustScroll(last) {
|
|
1602
|
+
const el = this.scroller()?.nativeElement;
|
|
1603
|
+
if (!el) {
|
|
1604
|
+
this.lastScroller = null;
|
|
1605
|
+
return;
|
|
1606
|
+
}
|
|
1607
|
+
const freshView = el !== this.lastScroller;
|
|
1608
|
+
this.lastScroller = el;
|
|
1609
|
+
if (this.pendingPrepend && this.store.olderStatus() !== 'loading') {
|
|
1610
|
+
el.scrollTop = el.scrollHeight - this.pendingPrepend.height + this.pendingPrepend.top;
|
|
1611
|
+
this.pendingPrepend = null;
|
|
1612
|
+
return;
|
|
1613
|
+
}
|
|
1614
|
+
// La firma incluye el estado: un envío que falla crece y también debe quedar a la vista.
|
|
1615
|
+
const signature = last ? `${last.key}|${last.status}|${last.editedAt ?? ''}|${last.deleted}` : undefined;
|
|
1616
|
+
if (freshView || signature !== this.lastSeenKey) {
|
|
1617
|
+
const stick = freshView || this.nearBottom || !!last?.mine;
|
|
1618
|
+
this.lastSeenKey = signature;
|
|
1619
|
+
if (stick) {
|
|
1620
|
+
el.scrollTop = el.scrollHeight;
|
|
1621
|
+
this.nearBottom = true;
|
|
1622
|
+
}
|
|
1623
|
+
}
|
|
1624
|
+
}
|
|
1625
|
+
restoreFocus() {
|
|
1626
|
+
const opener = this.openerElement;
|
|
1627
|
+
this.openerElement = null;
|
|
1628
|
+
if (opener && opener.isConnected && typeof opener.focus === 'function') {
|
|
1629
|
+
opener.focus();
|
|
1630
|
+
}
|
|
1631
|
+
}
|
|
1632
|
+
focusById(id) {
|
|
1633
|
+
this.document.getElementById(id)?.focus();
|
|
1634
|
+
}
|
|
1635
|
+
watchViewport(destroyRef) {
|
|
1636
|
+
const win = this.document.defaultView;
|
|
1637
|
+
if (!win?.matchMedia) {
|
|
1638
|
+
return;
|
|
1639
|
+
}
|
|
1640
|
+
const query = win.matchMedia(MOBILE_QUERY);
|
|
1641
|
+
this.isMobile.set(query.matches);
|
|
1642
|
+
const listener = (event) => this.isMobile.set(event.matches);
|
|
1643
|
+
query.addEventListener('change', listener);
|
|
1644
|
+
destroyRef.onDestroy(() => query.removeEventListener('change', listener));
|
|
1645
|
+
}
|
|
1646
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: ConversationPanelComponent, deps: [], target: i0.ɵɵFactoryTarget.Component });
|
|
1647
|
+
static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "19.2.17", type: ConversationPanelComponent, isStandalone: true, selector: "lib-conversation-panel", inputs: { entityType: { classPropertyName: "entityType", publicName: "entityType", isSignal: true, isRequired: true, transformFunction: null }, entityId: { classPropertyName: "entityId", publicName: "entityId", isSignal: true, isRequired: true, transformFunction: null }, canView: { classPropertyName: "canView", publicName: "canView", isSignal: true, isRequired: true, transformFunction: null }, canPost: { classPropertyName: "canPost", publicName: "canPost", isSignal: true, isRequired: true, transformFunction: null }, visible: { classPropertyName: "visible", publicName: "visible", isSignal: true, isRequired: false, transformFunction: null } }, outputs: { visible: "visibleChange", openChange: "openChange" }, providers: [ConversationStore, ConversationUserNames], viewQueries: [{ propertyName: "scroller", first: true, predicate: ["scroller"], descendants: true, isSignal: true }, { propertyName: "composer", first: true, predicate: ConversationComposerComponent, descendants: true, isSignal: true }, { propertyName: "actionsMenu", first: true, predicate: ["actionsMenu"], descendants: true, isSignal: true }], ngImport: i0, template: "<!-- closeOnEscape en false: el Escape lo atiende el panel (ver el constructor del componente). -->\r\n<p-drawer\r\n position=\"right\"\r\n styleClass=\"sfc-drawer\"\r\n [visible]=\"isOpen()\"\r\n [modal]=\"false\"\r\n [blockScroll]=\"false\"\r\n [fullScreen]=\"isMobile()\"\r\n [style]=\"drawerStyle()\"\r\n [closable]=\"false\"\r\n [closeOnEscape]=\"false\"\r\n (visibleChange)=\"onDrawerVisibleChange($event)\"\r\n (onShow)=\"onShown()\"\r\n>\r\n <ng-template #header>\r\n <div class=\"sfc-header\">\r\n @if (isMobile()) {\r\n <p-button icon=\"pi pi-arrow-left\" severity=\"secondary\" [text]=\"true\" [rounded]=\"true\" ariaLabel=\"Volver\" (onClick)=\"close()\" />\r\n }\r\n <h2 class=\"sfc-title\" tabindex=\"-1\" [id]=\"titleId\">Conversaci\u00F3n</h2>\r\n @if (!isMobile()) {\r\n <p-button\r\n icon=\"pi pi-times\"\r\n severity=\"secondary\"\r\n [text]=\"true\"\r\n [rounded]=\"true\"\r\n ariaLabel=\"Cerrar conversaci\u00F3n\"\r\n (onClick)=\"close()\"\r\n />\r\n }\r\n </div>\r\n </ng-template>\r\n\r\n @switch (store.status()) {\r\n @case ('error') {\r\n <div class=\"sfc-state\">\r\n <p-message severity=\"error\" icon=\"pi pi-exclamation-circle\" [text]=\"store.loadError() ?? ''\" />\r\n <p-button label=\"Reintentar\" icon=\"pi pi-refresh\" (onClick)=\"store.retryLoad()\" />\r\n </div>\r\n }\r\n @case ('ready') {\r\n @if (view().length === 0) {\r\n <div class=\"sfc-state sfc-empty\">\r\n <i class=\"pi pi-comments sfc-empty-icon\" aria-hidden=\"true\"></i>\r\n <p class=\"sfc-empty-title\">Todav\u00EDa no hay mensajes.</p>\r\n <p class=\"sfc-muted\">\r\n @if (canPost()) {\r\n Escriba el primero para empezar la conversaci\u00F3n de este registro.\r\n } @else {\r\n Cuando alguien escriba, el mensaje aparecer\u00E1 aqu\u00ED.\r\n }\r\n </p>\r\n </div>\r\n } @else {\r\n <div #scroller class=\"sfc-log\" role=\"log\" aria-label=\"Mensajes\" tabindex=\"0\" (scroll)=\"onScroll()\">\r\n @if (store.hasOlder()) {\r\n <div class=\"sfc-older\">\r\n @if (store.olderStatus() === 'error') {\r\n <p-message\r\n severity=\"error\"\r\n size=\"small\"\r\n variant=\"simple\"\r\n icon=\"pi pi-exclamation-circle\"\r\n text=\"No se pudieron cargar los mensajes anteriores.\"\r\n />\r\n }\r\n <p-button\r\n size=\"small\"\r\n severity=\"secondary\"\r\n [text]=\"true\"\r\n [label]=\"store.olderStatus() === 'error' ? 'Reintentar' : 'Ver mensajes anteriores'\"\r\n [loading]=\"store.olderStatus() === 'loading'\"\r\n (onClick)=\"loadOlder()\"\r\n />\r\n </div>\r\n }\r\n\r\n @for (entry of view(); track entry.item.key) {\r\n @if (entry.divider) {\r\n <div class=\"sfc-divider\" role=\"separator\" aria-label=\"Mensajes nuevos\">\r\n <span>Mensajes nuevos</span>\r\n </div>\r\n }\r\n <article\r\n class=\"sfc-message\"\r\n tabindex=\"-1\"\r\n [id]=\"messageId(entry.item)\"\r\n [class.sfc-message--mine]=\"entry.item.mine\"\r\n [attr.aria-label]=\"'Mensaje de ' + entry.author\"\r\n >\r\n <div class=\"sfc-bubble\">\r\n <div class=\"sfc-meta\">\r\n <span class=\"sfc-author\">{{ entry.author }}</span>\r\n <time class=\"sfc-muted\" [attr.datetime]=\"entry.item.createdAt\">\r\n {{ entry.item.createdAt | date: 'yyyy-MM-dd HH:mm' }}\r\n </time>\r\n @if (entry.item.editedAt && !entry.item.deleted) {\r\n <span class=\"sfc-muted\">\u00B7 editado</span>\r\n }\r\n @if (canAct(entry.item) && editingKey() !== entry.item.key) {\r\n <p-button\r\n class=\"sfc-actions\"\r\n icon=\"pi pi-ellipsis-v\"\r\n size=\"small\"\r\n severity=\"secondary\"\r\n [text]=\"true\"\r\n [rounded]=\"true\"\r\n ariaLabel=\"Acciones del mensaje\"\r\n (onClick)=\"openActions($event, entry.item)\"\r\n />\r\n }\r\n </div>\r\n\r\n @if (entry.item.deleted) {\r\n <p class=\"sfc-body sfc-muted sfc-deleted\">\r\n <i class=\"pi pi-ban\" aria-hidden=\"true\"></i>\r\n Mensaje eliminado\r\n </p>\r\n } @else if (editingKey() === entry.item.key) {\r\n <div class=\"sfc-edit\">\r\n <label class=\"sfc-sr-only\" [for]=\"editId(entry.item)\">Editar mensaje</label>\r\n <textarea\r\n #editInput\r\n pTextarea\r\n class=\"sfc-edit-input\"\r\n rows=\"2\"\r\n [id]=\"editId(entry.item)\"\r\n [autoResize]=\"true\"\r\n [attr.maxlength]=\"maxLength\"\r\n [value]=\"editText()\"\r\n (input)=\"editText.set(editInput.value)\"\r\n (keydown)=\"onEditKeydown($event, entry.item)\"\r\n ></textarea>\r\n <div class=\"sfc-edit-actions\">\r\n <p-button label=\"Cancelar\" size=\"small\" severity=\"secondary\" [text]=\"true\" (onClick)=\"cancelMessageActions(entry.item)\" />\r\n <p-button\r\n label=\"Guardar\"\r\n size=\"small\"\r\n [loading]=\"saving()\"\r\n [disabled]=\"editText().trim().length === 0\"\r\n (onClick)=\"saveEdit(entry.item)\"\r\n />\r\n </div>\r\n </div>\r\n } @else {\r\n <p class=\"sfc-body\">@for (segment of entry.segments; track $index) {@if (segment.mention) {<strong class=\"sfc-mention\">{{ segment.text }}</strong>} @else {<ng-container>{{ segment.text }}</ng-container>}}</p>\r\n }\r\n\r\n @if (confirmDeleteKey() === entry.item.key) {\r\n <div\r\n class=\"sfc-confirm\"\r\n role=\"group\"\r\n aria-label=\"Confirmar borrado\"\r\n [id]=\"'sfc-confirm-' + entry.item.key\"\r\n (keydown.escape)=\"$event.preventDefault(); cancelMessageActions(entry.item)\"\r\n >\r\n <span>\u00BFBorrar este mensaje? Los dem\u00E1s ver\u00E1n \u00ABMensaje eliminado\u00BB.</span>\r\n <div class=\"sfc-edit-actions\">\r\n <p-button\r\n label=\"Cancelar\"\r\n size=\"small\"\r\n severity=\"secondary\"\r\n [text]=\"true\"\r\n (onClick)=\"cancelMessageActions(entry.item)\"\r\n />\r\n <p-button\r\n label=\"Borrar mensaje\"\r\n size=\"small\"\r\n severity=\"danger\"\r\n [loading]=\"deleting()\"\r\n (onClick)=\"confirmDelete(entry.item)\"\r\n />\r\n </div>\r\n </div>\r\n }\r\n\r\n @if (entry.item.status === 'sending') {\r\n <span class=\"sfc-muted sfc-status\">Enviando\u2026</span>\r\n } @else if (entry.item.status === 'failed') {\r\n <div class=\"sfc-failed\">\r\n <p-message\r\n severity=\"error\"\r\n size=\"small\"\r\n variant=\"simple\"\r\n icon=\"pi pi-exclamation-circle\"\r\n [text]=\"entry.item.error ?? ''\"\r\n />\r\n <div class=\"sfc-edit-actions\">\r\n <p-button label=\"Descartar\" size=\"small\" severity=\"secondary\" [text]=\"true\" (onClick)=\"store.discard(entry.item.key)\" />\r\n <p-button label=\"Reintentar\" icon=\"pi pi-refresh\" size=\"small\" [outlined]=\"true\" (onClick)=\"store.retrySend(entry.item.key)\" />\r\n </div>\r\n </div>\r\n }\r\n </div>\r\n </article>\r\n }\r\n </div>\r\n }\r\n }\r\n @default {\r\n <div class=\"sfc-log\" aria-busy=\"true\">\r\n <span class=\"sfc-sr-only\">Cargando mensajes</span>\r\n @for (width of ['70%', '55%', '80%', '45%']; track $index; let odd = $odd) {\r\n <div class=\"sfc-skeleton\" [class.sfc-skeleton--mine]=\"odd\">\r\n <p-skeleton width=\"8rem\" height=\"0.75rem\" />\r\n <p-skeleton [width]=\"width\" height=\"2.5rem\" />\r\n </div>\r\n }\r\n </div>\r\n }\r\n }\r\n\r\n <ng-template #footer>\r\n @if (store.notice()) {\r\n <p-message\r\n class=\"sfc-notice\"\r\n severity=\"error\"\r\n icon=\"pi pi-exclamation-circle\"\r\n [closable]=\"true\"\r\n [text]=\"store.notice() ?? ''\"\r\n (onClose)=\"store.dismissNotice()\"\r\n />\r\n }\r\n @if (canPost()) {\r\n <!-- Con el hilo en error un env\u00EDo no se ver\u00EDa: primero hay que reintentar la carga. -->\r\n @if (store.status() !== 'error') {\r\n <lib-conversation-composer />\r\n }\r\n } @else {\r\n <p class=\"sfc-muted sfc-readonly\">Su perfil puede leer esta conversaci\u00F3n, pero no escribir en ella.</p>\r\n }\r\n </ng-template>\r\n\r\n <p-menu\r\n #actionsMenu\r\n [model]=\"menuItems()\"\r\n [popup]=\"true\"\r\n appendTo=\"body\"\r\n />\r\n</p-drawer>\r\n", styles: [".sfc-drawer .p-drawer-header{padding-bottom:.5rem;border-bottom:1px solid var(--p-content-border-color)}.sfc-drawer .p-drawer-content{display:flex;flex-direction:column;overflow:hidden;padding:0}.sfc-drawer .p-drawer-footer{display:flex;flex-direction:column;gap:.5rem;border-top:1px solid var(--p-content-border-color)}.sfc-header{display:flex;align-items:center;gap:.5rem;width:100%}.sfc-title{flex:1 1 auto;outline:none;margin:0;font-size:1.15rem;font-weight:600}.sfc-muted{color:var(--p-text-muted-color)}.sfc-state{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:1rem;flex:1 1 auto;padding:1.5rem;text-align:center}.sfc-empty p{margin:0}.sfc-empty-icon{font-size:2rem;color:var(--p-text-muted-color)}.sfc-empty-title{font-weight:600}.sfc-log{display:flex;flex-direction:column;gap:.75rem;flex:1 1 auto;min-height:0;overflow-y:auto;padding:1rem}.sfc-log:focus-visible{outline:2px solid var(--p-focus-ring-color, var(--p-primary-color));outline-offset:-2px}.sfc-older{display:flex;flex-direction:column;align-items:center;gap:.25rem}.sfc-divider{display:flex;align-items:center;gap:.5rem;font-size:.875rem;color:var(--p-primary-color)}.sfc-divider:before,.sfc-divider:after{content:\"\";flex:1 1 auto;border-top:1px solid currentColor}.sfc-message{display:flex;justify-content:flex-start}.sfc-message--mine{justify-content:flex-end}.sfc-bubble{display:flex;flex-direction:column;gap:.25rem;max-width:85%;min-width:0;padding:.5rem .75rem;border-radius:var(--p-content-border-radius);background:var(--p-content-hover-background);color:var(--p-text-color)}.sfc-message--mine .sfc-bubble{background:var(--p-highlight-background);color:var(--p-highlight-color)}.sfc-message--mine .sfc-bubble .sfc-muted{color:inherit;opacity:.8}.sfc-meta{display:flex;align-items:center;flex-wrap:wrap;gap:.375rem;font-size:.8125rem}.sfc-author{font-weight:600}.sfc-actions{margin-left:auto}.sfc-body{margin:0;white-space:pre-wrap;overflow-wrap:anywhere}.sfc-deleted{display:inline-flex;align-items:center;gap:.375rem;font-style:italic}.sfc-mention{font-weight:600}.sfc-edit,.sfc-confirm,.sfc-failed{display:flex;flex-direction:column;gap:.5rem}.sfc-edit-input{width:100%;max-height:10rem;resize:none}.sfc-edit-actions{display:flex;justify-content:flex-end;flex-wrap:wrap;gap:.5rem}.sfc-status{font-size:.8125rem}.sfc-skeleton{display:flex;flex-direction:column;gap:.375rem;align-items:flex-start}.sfc-skeleton--mine{align-items:flex-end}.sfc-readonly{margin:0}.sfc-sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}.sfc-message:focus-visible{outline:2px solid var(--p-focus-ring-color, var(--p-primary-color));outline-offset:2px;border-radius:var(--p-content-border-radius)}@media (pointer: coarse){.sfc-drawer .p-button{min-height:44px;min-width:44px}}\n"], dependencies: [{ kind: "pipe", type: DatePipe, name: "date" }, { kind: "ngmodule", type: ButtonModule }, { kind: "component", type: i1.Button, selector: "p-button", inputs: ["type", "iconPos", "icon", "badge", "label", "disabled", "loading", "loadingIcon", "raised", "rounded", "text", "plain", "severity", "outlined", "link", "tabindex", "size", "variant", "style", "styleClass", "badgeClass", "badgeSeverity", "ariaLabel", "autofocus", "fluid", "buttonProps"], outputs: ["onClick", "onFocus", "onBlur"] }, { kind: "ngmodule", type: DrawerModule }, { kind: "component", type: i2$1.Drawer, selector: "p-drawer", inputs: ["appendTo", "blockScroll", "style", "styleClass", "ariaCloseLabel", "autoZIndex", "baseZIndex", "modal", "closeButtonProps", "dismissible", "showCloseIcon", "closeOnEscape", "transitionOptions", "visible", "position", "fullScreen", "header", "maskStyle", "closable"], outputs: ["onShow", "onHide", "visibleChange"] }, { kind: "ngmodule", type: MenuModule }, { kind: "component", type: i3.Menu, selector: "p-menu", inputs: ["model", "popup", "style", "styleClass", "appendTo", "autoZIndex", "baseZIndex", "showTransitionOptions", "hideTransitionOptions", "ariaLabel", "ariaLabelledBy", "id", "tabindex"], outputs: ["onShow", "onHide", "onBlur", "onFocus"] }, { kind: "ngmodule", type: MessageModule }, { kind: "component", type: i4.Message, selector: "p-message", inputs: ["severity", "text", "escape", "style", "styleClass", "closable", "icon", "closeIcon", "life", "showTransitionOptions", "hideTransitionOptions", "size", "variant"], outputs: ["onClose"] }, { kind: "ngmodule", type: SkeletonModule }, { kind: "component", type: i5.Skeleton, selector: "p-skeleton", inputs: ["styleClass", "style", "shape", "animation", "borderRadius", "size", "width", "height"] }, { kind: "ngmodule", type: TextareaModule }, { kind: "directive", type: i2.Textarea, selector: "[pTextarea], [pInputTextarea]", inputs: ["autoResize", "variant", "fluid", "pSize"], outputs: ["onResize"] }, { kind: "component", type: ConversationComposerComponent, selector: "lib-conversation-composer" }], changeDetection: i0.ChangeDetectionStrategy.OnPush, encapsulation: i0.ViewEncapsulation.None });
|
|
1648
|
+
}
|
|
1649
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: ConversationPanelComponent, decorators: [{
|
|
1650
|
+
type: Component,
|
|
1651
|
+
args: [{ selector: 'lib-conversation-panel', standalone: true, imports: [
|
|
1652
|
+
DatePipe,
|
|
1653
|
+
ButtonModule,
|
|
1654
|
+
DrawerModule,
|
|
1655
|
+
MenuModule,
|
|
1656
|
+
MessageModule,
|
|
1657
|
+
SkeletonModule,
|
|
1658
|
+
TextareaModule,
|
|
1659
|
+
ConversationComposerComponent,
|
|
1660
|
+
], providers: [ConversationStore, ConversationUserNames], changeDetection: ChangeDetectionStrategy.OnPush, encapsulation: ViewEncapsulation.None, template: "<!-- closeOnEscape en false: el Escape lo atiende el panel (ver el constructor del componente). -->\r\n<p-drawer\r\n position=\"right\"\r\n styleClass=\"sfc-drawer\"\r\n [visible]=\"isOpen()\"\r\n [modal]=\"false\"\r\n [blockScroll]=\"false\"\r\n [fullScreen]=\"isMobile()\"\r\n [style]=\"drawerStyle()\"\r\n [closable]=\"false\"\r\n [closeOnEscape]=\"false\"\r\n (visibleChange)=\"onDrawerVisibleChange($event)\"\r\n (onShow)=\"onShown()\"\r\n>\r\n <ng-template #header>\r\n <div class=\"sfc-header\">\r\n @if (isMobile()) {\r\n <p-button icon=\"pi pi-arrow-left\" severity=\"secondary\" [text]=\"true\" [rounded]=\"true\" ariaLabel=\"Volver\" (onClick)=\"close()\" />\r\n }\r\n <h2 class=\"sfc-title\" tabindex=\"-1\" [id]=\"titleId\">Conversaci\u00F3n</h2>\r\n @if (!isMobile()) {\r\n <p-button\r\n icon=\"pi pi-times\"\r\n severity=\"secondary\"\r\n [text]=\"true\"\r\n [rounded]=\"true\"\r\n ariaLabel=\"Cerrar conversaci\u00F3n\"\r\n (onClick)=\"close()\"\r\n />\r\n }\r\n </div>\r\n </ng-template>\r\n\r\n @switch (store.status()) {\r\n @case ('error') {\r\n <div class=\"sfc-state\">\r\n <p-message severity=\"error\" icon=\"pi pi-exclamation-circle\" [text]=\"store.loadError() ?? ''\" />\r\n <p-button label=\"Reintentar\" icon=\"pi pi-refresh\" (onClick)=\"store.retryLoad()\" />\r\n </div>\r\n }\r\n @case ('ready') {\r\n @if (view().length === 0) {\r\n <div class=\"sfc-state sfc-empty\">\r\n <i class=\"pi pi-comments sfc-empty-icon\" aria-hidden=\"true\"></i>\r\n <p class=\"sfc-empty-title\">Todav\u00EDa no hay mensajes.</p>\r\n <p class=\"sfc-muted\">\r\n @if (canPost()) {\r\n Escriba el primero para empezar la conversaci\u00F3n de este registro.\r\n } @else {\r\n Cuando alguien escriba, el mensaje aparecer\u00E1 aqu\u00ED.\r\n }\r\n </p>\r\n </div>\r\n } @else {\r\n <div #scroller class=\"sfc-log\" role=\"log\" aria-label=\"Mensajes\" tabindex=\"0\" (scroll)=\"onScroll()\">\r\n @if (store.hasOlder()) {\r\n <div class=\"sfc-older\">\r\n @if (store.olderStatus() === 'error') {\r\n <p-message\r\n severity=\"error\"\r\n size=\"small\"\r\n variant=\"simple\"\r\n icon=\"pi pi-exclamation-circle\"\r\n text=\"No se pudieron cargar los mensajes anteriores.\"\r\n />\r\n }\r\n <p-button\r\n size=\"small\"\r\n severity=\"secondary\"\r\n [text]=\"true\"\r\n [label]=\"store.olderStatus() === 'error' ? 'Reintentar' : 'Ver mensajes anteriores'\"\r\n [loading]=\"store.olderStatus() === 'loading'\"\r\n (onClick)=\"loadOlder()\"\r\n />\r\n </div>\r\n }\r\n\r\n @for (entry of view(); track entry.item.key) {\r\n @if (entry.divider) {\r\n <div class=\"sfc-divider\" role=\"separator\" aria-label=\"Mensajes nuevos\">\r\n <span>Mensajes nuevos</span>\r\n </div>\r\n }\r\n <article\r\n class=\"sfc-message\"\r\n tabindex=\"-1\"\r\n [id]=\"messageId(entry.item)\"\r\n [class.sfc-message--mine]=\"entry.item.mine\"\r\n [attr.aria-label]=\"'Mensaje de ' + entry.author\"\r\n >\r\n <div class=\"sfc-bubble\">\r\n <div class=\"sfc-meta\">\r\n <span class=\"sfc-author\">{{ entry.author }}</span>\r\n <time class=\"sfc-muted\" [attr.datetime]=\"entry.item.createdAt\">\r\n {{ entry.item.createdAt | date: 'yyyy-MM-dd HH:mm' }}\r\n </time>\r\n @if (entry.item.editedAt && !entry.item.deleted) {\r\n <span class=\"sfc-muted\">\u00B7 editado</span>\r\n }\r\n @if (canAct(entry.item) && editingKey() !== entry.item.key) {\r\n <p-button\r\n class=\"sfc-actions\"\r\n icon=\"pi pi-ellipsis-v\"\r\n size=\"small\"\r\n severity=\"secondary\"\r\n [text]=\"true\"\r\n [rounded]=\"true\"\r\n ariaLabel=\"Acciones del mensaje\"\r\n (onClick)=\"openActions($event, entry.item)\"\r\n />\r\n }\r\n </div>\r\n\r\n @if (entry.item.deleted) {\r\n <p class=\"sfc-body sfc-muted sfc-deleted\">\r\n <i class=\"pi pi-ban\" aria-hidden=\"true\"></i>\r\n Mensaje eliminado\r\n </p>\r\n } @else if (editingKey() === entry.item.key) {\r\n <div class=\"sfc-edit\">\r\n <label class=\"sfc-sr-only\" [for]=\"editId(entry.item)\">Editar mensaje</label>\r\n <textarea\r\n #editInput\r\n pTextarea\r\n class=\"sfc-edit-input\"\r\n rows=\"2\"\r\n [id]=\"editId(entry.item)\"\r\n [autoResize]=\"true\"\r\n [attr.maxlength]=\"maxLength\"\r\n [value]=\"editText()\"\r\n (input)=\"editText.set(editInput.value)\"\r\n (keydown)=\"onEditKeydown($event, entry.item)\"\r\n ></textarea>\r\n <div class=\"sfc-edit-actions\">\r\n <p-button label=\"Cancelar\" size=\"small\" severity=\"secondary\" [text]=\"true\" (onClick)=\"cancelMessageActions(entry.item)\" />\r\n <p-button\r\n label=\"Guardar\"\r\n size=\"small\"\r\n [loading]=\"saving()\"\r\n [disabled]=\"editText().trim().length === 0\"\r\n (onClick)=\"saveEdit(entry.item)\"\r\n />\r\n </div>\r\n </div>\r\n } @else {\r\n <p class=\"sfc-body\">@for (segment of entry.segments; track $index) {@if (segment.mention) {<strong class=\"sfc-mention\">{{ segment.text }}</strong>} @else {<ng-container>{{ segment.text }}</ng-container>}}</p>\r\n }\r\n\r\n @if (confirmDeleteKey() === entry.item.key) {\r\n <div\r\n class=\"sfc-confirm\"\r\n role=\"group\"\r\n aria-label=\"Confirmar borrado\"\r\n [id]=\"'sfc-confirm-' + entry.item.key\"\r\n (keydown.escape)=\"$event.preventDefault(); cancelMessageActions(entry.item)\"\r\n >\r\n <span>\u00BFBorrar este mensaje? Los dem\u00E1s ver\u00E1n \u00ABMensaje eliminado\u00BB.</span>\r\n <div class=\"sfc-edit-actions\">\r\n <p-button\r\n label=\"Cancelar\"\r\n size=\"small\"\r\n severity=\"secondary\"\r\n [text]=\"true\"\r\n (onClick)=\"cancelMessageActions(entry.item)\"\r\n />\r\n <p-button\r\n label=\"Borrar mensaje\"\r\n size=\"small\"\r\n severity=\"danger\"\r\n [loading]=\"deleting()\"\r\n (onClick)=\"confirmDelete(entry.item)\"\r\n />\r\n </div>\r\n </div>\r\n }\r\n\r\n @if (entry.item.status === 'sending') {\r\n <span class=\"sfc-muted sfc-status\">Enviando\u2026</span>\r\n } @else if (entry.item.status === 'failed') {\r\n <div class=\"sfc-failed\">\r\n <p-message\r\n severity=\"error\"\r\n size=\"small\"\r\n variant=\"simple\"\r\n icon=\"pi pi-exclamation-circle\"\r\n [text]=\"entry.item.error ?? ''\"\r\n />\r\n <div class=\"sfc-edit-actions\">\r\n <p-button label=\"Descartar\" size=\"small\" severity=\"secondary\" [text]=\"true\" (onClick)=\"store.discard(entry.item.key)\" />\r\n <p-button label=\"Reintentar\" icon=\"pi pi-refresh\" size=\"small\" [outlined]=\"true\" (onClick)=\"store.retrySend(entry.item.key)\" />\r\n </div>\r\n </div>\r\n }\r\n </div>\r\n </article>\r\n }\r\n </div>\r\n }\r\n }\r\n @default {\r\n <div class=\"sfc-log\" aria-busy=\"true\">\r\n <span class=\"sfc-sr-only\">Cargando mensajes</span>\r\n @for (width of ['70%', '55%', '80%', '45%']; track $index; let odd = $odd) {\r\n <div class=\"sfc-skeleton\" [class.sfc-skeleton--mine]=\"odd\">\r\n <p-skeleton width=\"8rem\" height=\"0.75rem\" />\r\n <p-skeleton [width]=\"width\" height=\"2.5rem\" />\r\n </div>\r\n }\r\n </div>\r\n }\r\n }\r\n\r\n <ng-template #footer>\r\n @if (store.notice()) {\r\n <p-message\r\n class=\"sfc-notice\"\r\n severity=\"error\"\r\n icon=\"pi pi-exclamation-circle\"\r\n [closable]=\"true\"\r\n [text]=\"store.notice() ?? ''\"\r\n (onClose)=\"store.dismissNotice()\"\r\n />\r\n }\r\n @if (canPost()) {\r\n <!-- Con el hilo en error un env\u00EDo no se ver\u00EDa: primero hay que reintentar la carga. -->\r\n @if (store.status() !== 'error') {\r\n <lib-conversation-composer />\r\n }\r\n } @else {\r\n <p class=\"sfc-muted sfc-readonly\">Su perfil puede leer esta conversaci\u00F3n, pero no escribir en ella.</p>\r\n }\r\n </ng-template>\r\n\r\n <p-menu\r\n #actionsMenu\r\n [model]=\"menuItems()\"\r\n [popup]=\"true\"\r\n appendTo=\"body\"\r\n />\r\n</p-drawer>\r\n", styles: [".sfc-drawer .p-drawer-header{padding-bottom:.5rem;border-bottom:1px solid var(--p-content-border-color)}.sfc-drawer .p-drawer-content{display:flex;flex-direction:column;overflow:hidden;padding:0}.sfc-drawer .p-drawer-footer{display:flex;flex-direction:column;gap:.5rem;border-top:1px solid var(--p-content-border-color)}.sfc-header{display:flex;align-items:center;gap:.5rem;width:100%}.sfc-title{flex:1 1 auto;outline:none;margin:0;font-size:1.15rem;font-weight:600}.sfc-muted{color:var(--p-text-muted-color)}.sfc-state{display:flex;flex-direction:column;align-items:center;justify-content:center;gap:1rem;flex:1 1 auto;padding:1.5rem;text-align:center}.sfc-empty p{margin:0}.sfc-empty-icon{font-size:2rem;color:var(--p-text-muted-color)}.sfc-empty-title{font-weight:600}.sfc-log{display:flex;flex-direction:column;gap:.75rem;flex:1 1 auto;min-height:0;overflow-y:auto;padding:1rem}.sfc-log:focus-visible{outline:2px solid var(--p-focus-ring-color, var(--p-primary-color));outline-offset:-2px}.sfc-older{display:flex;flex-direction:column;align-items:center;gap:.25rem}.sfc-divider{display:flex;align-items:center;gap:.5rem;font-size:.875rem;color:var(--p-primary-color)}.sfc-divider:before,.sfc-divider:after{content:\"\";flex:1 1 auto;border-top:1px solid currentColor}.sfc-message{display:flex;justify-content:flex-start}.sfc-message--mine{justify-content:flex-end}.sfc-bubble{display:flex;flex-direction:column;gap:.25rem;max-width:85%;min-width:0;padding:.5rem .75rem;border-radius:var(--p-content-border-radius);background:var(--p-content-hover-background);color:var(--p-text-color)}.sfc-message--mine .sfc-bubble{background:var(--p-highlight-background);color:var(--p-highlight-color)}.sfc-message--mine .sfc-bubble .sfc-muted{color:inherit;opacity:.8}.sfc-meta{display:flex;align-items:center;flex-wrap:wrap;gap:.375rem;font-size:.8125rem}.sfc-author{font-weight:600}.sfc-actions{margin-left:auto}.sfc-body{margin:0;white-space:pre-wrap;overflow-wrap:anywhere}.sfc-deleted{display:inline-flex;align-items:center;gap:.375rem;font-style:italic}.sfc-mention{font-weight:600}.sfc-edit,.sfc-confirm,.sfc-failed{display:flex;flex-direction:column;gap:.5rem}.sfc-edit-input{width:100%;max-height:10rem;resize:none}.sfc-edit-actions{display:flex;justify-content:flex-end;flex-wrap:wrap;gap:.5rem}.sfc-status{font-size:.8125rem}.sfc-skeleton{display:flex;flex-direction:column;gap:.375rem;align-items:flex-start}.sfc-skeleton--mine{align-items:flex-end}.sfc-readonly{margin:0}.sfc-sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0,0,0,0);white-space:nowrap;border:0}.sfc-message:focus-visible{outline:2px solid var(--p-focus-ring-color, var(--p-primary-color));outline-offset:2px;border-radius:var(--p-content-border-radius)}@media (pointer: coarse){.sfc-drawer .p-button{min-height:44px;min-width:44px}}\n"] }]
|
|
1661
|
+
}], ctorParameters: () => [] });
|
|
1662
|
+
|
|
1663
|
+
/**
|
|
1664
|
+
* Botón "Conversación" con los no leídos de su entidad. Abre el panel lateral.
|
|
1665
|
+
*
|
|
1666
|
+
* Pide solo el resumen de su entidad: al montarse, al cambiar de entidad y, con el panel cerrado,
|
|
1667
|
+
* cuando la pestaña del navegador vuelve a estar visible o el canal en vivo se reconecta. No
|
|
1668
|
+
* consulta cada pocos segundos. En un listado no se usa un botón por fila: el front llama a
|
|
1669
|
+
* `unreadSummary` una vez por página.
|
|
1670
|
+
*/
|
|
1671
|
+
class ConversationButtonComponent {
|
|
1672
|
+
entityType = input.required();
|
|
1673
|
+
entityId = input.required({ transform: (value) => String(value) });
|
|
1674
|
+
/** Puede leer la conversación. Sin esto el botón no se muestra. */
|
|
1675
|
+
canView = input.required();
|
|
1676
|
+
/** Puede escribir. Sin esto el panel abre en solo lectura. */
|
|
1677
|
+
canPost = input.required();
|
|
1678
|
+
/** Emite al abrir y cerrar el panel, por ejemplo para ocultar la burbuja de agentes. */
|
|
1679
|
+
openChange = output();
|
|
1680
|
+
gateway = inject(CONVERSATION_SERVICE);
|
|
1681
|
+
realtime = inject(CONVERSATION_REALTIME, { optional: true });
|
|
1682
|
+
document = inject(DOCUMENT);
|
|
1683
|
+
host = inject(ElementRef);
|
|
1684
|
+
injector = inject(Injector);
|
|
1685
|
+
open = signal(false);
|
|
1686
|
+
unread = signal(0);
|
|
1687
|
+
badge = computed(() => {
|
|
1688
|
+
const count = this.unread();
|
|
1689
|
+
if (count <= 0) {
|
|
1690
|
+
return undefined;
|
|
1691
|
+
}
|
|
1692
|
+
return count > 99 ? '99+' : String(count);
|
|
1693
|
+
});
|
|
1694
|
+
ariaLabel = computed(() => {
|
|
1695
|
+
const count = this.unread();
|
|
1696
|
+
if (count <= 0) {
|
|
1697
|
+
return 'Conversación';
|
|
1698
|
+
}
|
|
1699
|
+
return count === 1 ? 'Conversación, 1 mensaje sin leer' : `Conversación, ${count} mensajes sin leer`;
|
|
1700
|
+
});
|
|
1701
|
+
target = computed(() => ({ type: this.entityType(), id: this.entityId(), canView: this.canView() }));
|
|
1702
|
+
constructor() {
|
|
1703
|
+
merge(toObservable(this.target), this.refreshTriggers().pipe(map(() => this.target())))
|
|
1704
|
+
.pipe(switchMap(({ type, id, canView }) => {
|
|
1705
|
+
if (!canView) {
|
|
1706
|
+
return of(0);
|
|
1707
|
+
}
|
|
1708
|
+
return this.gateway.unreadSummary(type, [id]).pipe(map((rows) => rows.find((row) => String(row.entityId) === id)?.unread ?? 0),
|
|
1709
|
+
// Sin el número el botón sigue sirviendo; el panel muestra el error si lo hay.
|
|
1710
|
+
catchError(() => of(0)));
|
|
1711
|
+
}), takeUntilDestroyed())
|
|
1712
|
+
.subscribe((count) => {
|
|
1713
|
+
// Si el panel ya está abierto, lo nuevo se está leyendo.
|
|
1714
|
+
this.unread.set(this.open() ? 0 : count);
|
|
1715
|
+
});
|
|
1716
|
+
// p-button no deja poner atributos en su <button>: aria-expanded se pone en el DOM.
|
|
1717
|
+
effect(() => {
|
|
1718
|
+
const expanded = String(this.open() && this.canView());
|
|
1719
|
+
afterNextRender(() => this.host.nativeElement.querySelector('p-button button')?.setAttribute('aria-expanded', expanded), {
|
|
1720
|
+
injector: this.injector,
|
|
1721
|
+
});
|
|
1722
|
+
});
|
|
1723
|
+
}
|
|
1724
|
+
toggle() {
|
|
1725
|
+
this.open.update((value) => !value);
|
|
1726
|
+
}
|
|
1727
|
+
onOpenChange(open) {
|
|
1728
|
+
// Al abrir, el panel marca todo como leído; al cerrar, lo que había quedó leído.
|
|
1729
|
+
this.unread.set(0);
|
|
1730
|
+
this.openChange.emit(open);
|
|
1731
|
+
}
|
|
1732
|
+
/** Con el panel cerrado: al volver a la pestaña y al reconectarse el canal en vivo. */
|
|
1733
|
+
refreshTriggers() {
|
|
1734
|
+
const visible = this.document.defaultView
|
|
1735
|
+
? fromEvent(this.document, 'visibilitychange').pipe(filter(() => this.document.visibilityState === 'visible'))
|
|
1736
|
+
: EMPTY;
|
|
1737
|
+
const reconnected = this.realtime?.reconnected$ ?? EMPTY;
|
|
1738
|
+
return merge(visible, reconnected).pipe(filter(() => !this.open()));
|
|
1739
|
+
}
|
|
1740
|
+
static ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: ConversationButtonComponent, deps: [], target: i0.ɵɵFactoryTarget.Component });
|
|
1741
|
+
static ɵcmp = i0.ɵɵngDeclareComponent({ minVersion: "17.0.0", version: "19.2.17", type: ConversationButtonComponent, isStandalone: true, selector: "lib-conversation-button", inputs: { entityType: { classPropertyName: "entityType", publicName: "entityType", isSignal: true, isRequired: true, transformFunction: null }, entityId: { classPropertyName: "entityId", publicName: "entityId", isSignal: true, isRequired: true, transformFunction: null }, canView: { classPropertyName: "canView", publicName: "canView", isSignal: true, isRequired: true, transformFunction: null }, canPost: { classPropertyName: "canPost", publicName: "canPost", isSignal: true, isRequired: true, transformFunction: null } }, outputs: { openChange: "openChange" }, ngImport: i0, template: `
|
|
1742
|
+
@if (canView()) {
|
|
1743
|
+
<p-button
|
|
1744
|
+
label="Conversación"
|
|
1745
|
+
icon="pi pi-comments"
|
|
1746
|
+
severity="secondary"
|
|
1747
|
+
[text]="true"
|
|
1748
|
+
[badge]="badge()"
|
|
1749
|
+
[ariaLabel]="ariaLabel()"
|
|
1750
|
+
(onClick)="toggle()"
|
|
1751
|
+
/>
|
|
1752
|
+
<lib-conversation-panel
|
|
1753
|
+
[entityType]="entityType()"
|
|
1754
|
+
[entityId]="entityId()"
|
|
1755
|
+
[canView]="canView()"
|
|
1756
|
+
[canPost]="canPost()"
|
|
1757
|
+
[(visible)]="open"
|
|
1758
|
+
(openChange)="onOpenChange($event)"
|
|
1759
|
+
/>
|
|
1760
|
+
}
|
|
1761
|
+
`, isInline: true, dependencies: [{ kind: "ngmodule", type: ButtonModule }, { kind: "component", type: i1.Button, selector: "p-button", inputs: ["type", "iconPos", "icon", "badge", "label", "disabled", "loading", "loadingIcon", "raised", "rounded", "text", "plain", "severity", "outlined", "link", "tabindex", "size", "variant", "style", "styleClass", "badgeClass", "badgeSeverity", "ariaLabel", "autofocus", "fluid", "buttonProps"], outputs: ["onClick", "onFocus", "onBlur"] }, { kind: "component", type: ConversationPanelComponent, selector: "lib-conversation-panel", inputs: ["entityType", "entityId", "canView", "canPost", "visible"], outputs: ["visibleChange", "openChange"] }], changeDetection: i0.ChangeDetectionStrategy.OnPush });
|
|
1762
|
+
}
|
|
1763
|
+
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "19.2.17", ngImport: i0, type: ConversationButtonComponent, decorators: [{
|
|
1764
|
+
type: Component,
|
|
1765
|
+
args: [{
|
|
1766
|
+
selector: 'lib-conversation-button',
|
|
1767
|
+
standalone: true,
|
|
1768
|
+
imports: [ButtonModule, ConversationPanelComponent],
|
|
1769
|
+
changeDetection: ChangeDetectionStrategy.OnPush,
|
|
1770
|
+
template: `
|
|
1771
|
+
@if (canView()) {
|
|
1772
|
+
<p-button
|
|
1773
|
+
label="Conversación"
|
|
1774
|
+
icon="pi pi-comments"
|
|
1775
|
+
severity="secondary"
|
|
1776
|
+
[text]="true"
|
|
1777
|
+
[badge]="badge()"
|
|
1778
|
+
[ariaLabel]="ariaLabel()"
|
|
1779
|
+
(onClick)="toggle()"
|
|
1780
|
+
/>
|
|
1781
|
+
<lib-conversation-panel
|
|
1782
|
+
[entityType]="entityType()"
|
|
1783
|
+
[entityId]="entityId()"
|
|
1784
|
+
[canView]="canView()"
|
|
1785
|
+
[canPost]="canPost()"
|
|
1786
|
+
[(visible)]="open"
|
|
1787
|
+
(openChange)="onOpenChange($event)"
|
|
1788
|
+
/>
|
|
1789
|
+
}
|
|
1790
|
+
`,
|
|
1791
|
+
}]
|
|
1792
|
+
}], ctorParameters: () => [] });
|
|
1793
|
+
|
|
1794
|
+
/**
|
|
1795
|
+
* Superficie pública de sf-conversation. Los fronts importan solo de aquí.
|
|
1796
|
+
*
|
|
1797
|
+
* La librería no conoce al front que la usa: el contexto entra por inputs, los datos por
|
|
1798
|
+
* `CONVERSATION_SERVICE`, lo nuevo en vivo por `CONVERSATION_REALTIME` (opcional) y los nombres
|
|
1799
|
+
* por `CONVERSATION_DIRECTORY`.
|
|
1800
|
+
*/
|
|
1801
|
+
|
|
1802
|
+
/**
|
|
1803
|
+
* Generated bundle index. Do not edit.
|
|
1804
|
+
*/
|
|
1805
|
+
|
|
1806
|
+
export { CONVERSATION_ACCESS_TOKEN, CONVERSATION_API_URL, CONVERSATION_DIRECTORY, CONVERSATION_IDLE_DISCONNECT_MS, CONVERSATION_JOIN_TIMEOUT_MS, CONVERSATION_MESSAGE_EVENT, CONVERSATION_REALTIME, CONVERSATION_RECONNECT_DELAYS_MS, CONVERSATION_SERVICE, CONVERSATION_STABLE_CONNECTION_MS, ConversationButtonComponent, ConversationHttpService, ConversationPanelComponent, ConversationSignalRService, provideConversationHttp, provideConversationRealtime };
|
|
1807
|
+
//# sourceMappingURL=sfinges-sf-conversation.mjs.map
|