@chat-leo/chatleo 0.0.0-stage → 2.0.2

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.
Files changed (144) hide show
  1. package/LICENSE +21 -0
  2. package/dist/chatleo/chatleo.esm.js +1 -0
  3. package/dist/chatleo/index.esm.js +1 -0
  4. package/dist/chatleo/p-43ada232.entry.js +1 -0
  5. package/dist/chatleo/p-4485e141.entry.js +1 -0
  6. package/dist/chatleo/p-BnCPdbII.js +1 -0
  7. package/dist/chatleo/p-C-l90Wre.js +1 -0
  8. package/dist/chatleo/p-DQuL1Twl.js +1 -0
  9. package/dist/chatleo/p-DmL518NK.js +3 -0
  10. package/dist/chatleo/p-aed60255.entry.js +1 -0
  11. package/dist/cjs/app-globals-V2Kpy_OQ.js +5 -0
  12. package/dist/cjs/chatleo-avatar_13.cjs.entry.js +2986 -0
  13. package/dist/cjs/chatleo-call-adapter-B2OfC0VZ.js +35 -0
  14. package/dist/cjs/chatleo-chat-input.cjs.entry.js +67 -0
  15. package/dist/cjs/chatleo.cjs.js +25 -0
  16. package/dist/cjs/index-DkSDLR0y.js +56 -0
  17. package/dist/cjs/index-Dxw4YCA_.js +1741 -0
  18. package/dist/cjs/index.cjs.js +7 -0
  19. package/dist/cjs/loader.cjs.js +13 -0
  20. package/dist/cjs/my-component.cjs.entry.js +33 -0
  21. package/dist/collection/__mocks__/stencil-core.js +26 -0
  22. package/dist/collection/collection-manifest.json +27 -0
  23. package/dist/collection/components/chatleo-avatar/chatleo-avatar.css +40 -0
  24. package/dist/collection/components/chatleo-avatar/chatleo-avatar.js +116 -0
  25. package/dist/collection/components/chatleo-chat/chatleo-chat.css +108 -0
  26. package/dist/collection/components/chatleo-chat/chatleo-chat.js +459 -0
  27. package/dist/collection/components/chatleo-chat-header/chatleo-chat-header.css +22 -0
  28. package/dist/collection/components/chatleo-chat-header/chatleo-chat-header.js +105 -0
  29. package/dist/collection/components/chatleo-chat-input/chatleo-chat-input.css +84 -0
  30. package/dist/collection/components/chatleo-chat-input/chatleo-chat-input.js +141 -0
  31. package/dist/collection/components/chatleo-chat-message/chatleo-chat-message.css +149 -0
  32. package/dist/collection/components/chatleo-chat-message/chatleo-chat-message.js +259 -0
  33. package/dist/collection/components/chatleo-component/chatleo-component.css +271 -0
  34. package/dist/collection/components/chatleo-component/chatleo-component.js +1366 -0
  35. package/dist/collection/components/chatleo-new-message-selector/chatleo-new-message-selector.css +96 -0
  36. package/dist/collection/components/chatleo-new-message-selector/chatleo-new-message-selector.js +231 -0
  37. package/dist/collection/components/chatleo-rich-input/chatleo-rich-input.css +352 -0
  38. package/dist/collection/components/chatleo-rich-input/chatleo-rich-input.js +976 -0
  39. package/dist/collection/components/chatleo-rich-message-renderer/chatleo-rich-message-renderer.css +169 -0
  40. package/dist/collection/components/chatleo-rich-message-renderer/chatleo-rich-message-renderer.js +400 -0
  41. package/dist/collection/components/chatleo-room-list/chatleo-room-list.css +111 -0
  42. package/dist/collection/components/chatleo-room-list/chatleo-room-list.js +180 -0
  43. package/dist/collection/components/chatleo-room-tile-component/chatleo-room-tile-component.css +110 -0
  44. package/dist/collection/components/chatleo-room-tile-component/chatleo-room-tile-component.js +241 -0
  45. package/dist/collection/components/chatleo-room-view/chatleo-room-view.css +93 -0
  46. package/dist/collection/components/chatleo-room-view/chatleo-room-view.js +593 -0
  47. package/dist/collection/components/chatleo-tray-component/chatleo-tray-component.css +284 -0
  48. package/dist/collection/components/chatleo-tray-component/chatleo-tray-component.js +391 -0
  49. package/dist/collection/components/chatleo-user-tile/chatleo-user-tile.css +56 -0
  50. package/dist/collection/components/chatleo-user-tile/chatleo-user-tile.js +149 -0
  51. package/dist/collection/components/my-component/my-component.css +4 -0
  52. package/dist/collection/components/my-component/my-component.js +95 -0
  53. package/dist/collection/index.js +10 -0
  54. package/dist/collection/utils/call-entry.js +34 -0
  55. package/dist/collection/utils/delivery.js +7 -0
  56. package/dist/collection/utils/utils.js +51 -0
  57. package/dist/components/chatleo-avatar.d.ts +11 -0
  58. package/dist/components/chatleo-avatar.js +1 -0
  59. package/dist/components/chatleo-chat-header.d.ts +11 -0
  60. package/dist/components/chatleo-chat-header.js +1 -0
  61. package/dist/components/chatleo-chat-input.d.ts +11 -0
  62. package/dist/components/chatleo-chat-input.js +1 -0
  63. package/dist/components/chatleo-chat-message.d.ts +11 -0
  64. package/dist/components/chatleo-chat-message.js +1 -0
  65. package/dist/components/chatleo-chat.d.ts +11 -0
  66. package/dist/components/chatleo-chat.js +1 -0
  67. package/dist/components/chatleo-component.d.ts +11 -0
  68. package/dist/components/chatleo-component.js +1 -0
  69. package/dist/components/chatleo-new-message-selector.d.ts +11 -0
  70. package/dist/components/chatleo-new-message-selector.js +1 -0
  71. package/dist/components/chatleo-rich-input.d.ts +11 -0
  72. package/dist/components/chatleo-rich-input.js +1 -0
  73. package/dist/components/chatleo-rich-message-renderer.d.ts +11 -0
  74. package/dist/components/chatleo-rich-message-renderer.js +1 -0
  75. package/dist/components/chatleo-room-list.d.ts +11 -0
  76. package/dist/components/chatleo-room-list.js +1 -0
  77. package/dist/components/chatleo-room-tile-component.d.ts +11 -0
  78. package/dist/components/chatleo-room-tile-component.js +1 -0
  79. package/dist/components/chatleo-room-view.d.ts +11 -0
  80. package/dist/components/chatleo-room-view.js +1 -0
  81. package/dist/components/chatleo-tray-component.d.ts +11 -0
  82. package/dist/components/chatleo-tray-component.js +1 -0
  83. package/dist/components/chatleo-user-tile.d.ts +11 -0
  84. package/dist/components/chatleo-user-tile.js +1 -0
  85. package/dist/components/index.d.ts +35 -0
  86. package/dist/components/index.js +1 -0
  87. package/dist/components/my-component.d.ts +11 -0
  88. package/dist/components/my-component.js +1 -0
  89. package/dist/components/p-8kvQ-Uh-.js +1 -0
  90. package/dist/components/p-B7cdqAgv.js +1 -0
  91. package/dist/components/p-BdiOcOYZ.js +1 -0
  92. package/dist/components/p-BlbDSb7D.js +1 -0
  93. package/dist/components/p-BnCPdbII.js +1 -0
  94. package/dist/components/p-C-v19aUJ.js +1 -0
  95. package/dist/components/p-C1mF0s8g.js +1 -0
  96. package/dist/components/p-CRtBdzP3.js +1 -0
  97. package/dist/components/p-CfayCm9O.js +1 -0
  98. package/dist/components/p-DGjAxoQy.js +1 -0
  99. package/dist/components/p-Exj_2-yI.js +1 -0
  100. package/dist/components/p-XlwGxsqT.js +1 -0
  101. package/dist/components/p-fjMaTJam.js +1 -0
  102. package/dist/components/p-xt4kzz3B.js +1 -0
  103. package/dist/esm/app-globals-DQuL1Twl.js +3 -0
  104. package/dist/esm/chatleo-avatar_13.entry.js +2972 -0
  105. package/dist/esm/chatleo-call-adapter-BnCPdbII.js +33 -0
  106. package/dist/esm/chatleo-chat-input.entry.js +65 -0
  107. package/dist/esm/chatleo.js +21 -0
  108. package/dist/esm/index-C-l90Wre.js +53 -0
  109. package/dist/esm/index-DmL518NK.js +1733 -0
  110. package/dist/esm/index.js +1 -0
  111. package/dist/esm/loader.js +11 -0
  112. package/dist/esm/my-component.entry.js +31 -0
  113. package/dist/index.cjs.js +1 -0
  114. package/dist/index.js +1 -0
  115. package/dist/types/__mocks__/stencil-core.d.ts +24 -0
  116. package/dist/types/components/chatleo-avatar/chatleo-avatar.d.ts +27 -0
  117. package/dist/types/components/chatleo-chat/chatleo-chat.d.ts +75 -0
  118. package/dist/types/components/chatleo-chat-header/chatleo-chat-header.d.ts +27 -0
  119. package/dist/types/components/chatleo-chat-input/chatleo-chat-input.d.ts +31 -0
  120. package/dist/types/components/chatleo-chat-message/chatleo-chat-message.d.ts +22 -0
  121. package/dist/types/components/chatleo-component/chatleo-component.d.ts +278 -0
  122. package/dist/types/components/chatleo-new-message-selector/chatleo-new-message-selector.d.ts +68 -0
  123. package/dist/types/components/chatleo-rich-input/chatleo-rich-input.d.ts +216 -0
  124. package/dist/types/components/chatleo-rich-message-renderer/chatleo-rich-message-renderer.d.ts +77 -0
  125. package/dist/types/components/chatleo-room-list/chatleo-room-list.d.ts +52 -0
  126. package/dist/types/components/chatleo-room-tile-component/chatleo-room-tile-component.d.ts +59 -0
  127. package/dist/types/components/chatleo-room-view/chatleo-room-view.d.ts +91 -0
  128. package/dist/types/components/chatleo-tray-component/chatleo-tray-component.d.ts +112 -0
  129. package/dist/types/components/chatleo-user-tile/chatleo-user-tile.d.ts +36 -0
  130. package/dist/types/components/my-component/my-component.d.ts +16 -0
  131. package/dist/types/components.d.ts +1593 -0
  132. package/dist/types/index.d.ts +12 -0
  133. package/dist/types/stencil-public-runtime.d.ts +1879 -0
  134. package/dist/types/utils/call-entry.d.ts +9 -0
  135. package/dist/types/utils/delivery.d.ts +7 -0
  136. package/dist/types/utils/utils.d.ts +24 -0
  137. package/loader/cdn.js +1 -0
  138. package/loader/index.cjs.js +1 -0
  139. package/loader/index.d.ts +24 -0
  140. package/loader/index.es2017.js +1 -0
  141. package/loader/index.js +2 -0
  142. package/package.json +70 -3
  143. package/readme.md +111 -0
  144. package/README.md +0 -3
@@ -0,0 +1,2986 @@
1
+ 'use strict';
2
+
3
+ var index = require('./index-Dxw4YCA_.js');
4
+ var index$1 = require('./index-DkSDLR0y.js');
5
+
6
+ const chatleoAvatarCss = () => `:host{--avatar-bg:#dddddd;--status-size:12px;--status-border:2px;--status-position:2px}.user-avatar{position:relative;flex-shrink:0}.user-avatar img{width:var(--avatar-size, 48px);height:var(--avatar-size, 48px);border-radius:50%;object-fit:cover;background-color:var(--avatar-bg);overflow:hidden}.status-indicator{position:absolute;bottom:var(--status-position);right:var(--status-position);width:var(--status-size);height:var(--status-size);border-radius:50%;border:var(--status-border) solid var(--bg-primary)}.status-indicator.online{background-color:var(--status-online)}.status-indicator.offline{background-color:var(--status-offline)}`;
7
+
8
+ const ChatleoAvatar = class {
9
+ constructor(hostRef) {
10
+ index.registerInstance(this, hostRef);
11
+ }
12
+ /**
13
+ * The full name of the user, which is used to generate the initials for the SVG fallback avatar.
14
+ */
15
+ name;
16
+ /**
17
+ * The URL for the user's avatar image. If this is not provided, the component will render a generated SVG avatar.
18
+ */
19
+ url;
20
+ /**
21
+ * A boolean that determines the color of the status indicator. `true` for online (green), `false` for offline (gray).
22
+ */
23
+ isOnline = false;
24
+ /**
25
+ * @function render
26
+ * @description The render method for the `ChatleoAvatar` component. It conditionally renders either the user's image from the `url` prop or a generated SVG avatar if the URL is not available. It also renders a status indicator.
27
+ * @returns {any} A VNode representing the component's UI.
28
+ */
29
+ render() {
30
+ // 1. Define dynamic properties
31
+ const fillColor = 'royalblue';
32
+ const circleRadius = 45;
33
+ // 2. Create the SVG markup as a string
34
+ const svgString = `
35
+ <svg width="100" height="100" xmlns="http://www.w3.org/2000/svg">
36
+ <circle cx="50" cy="50" r="${circleRadius}" fill="${fillColor}" />
37
+ <text x="50" y="55" font-size="12" text-anchor="middle" fill="white">${this.name.substring(0, 2)}</text>
38
+ </svg>
39
+ `;
40
+ // 3. URL-encode the SVG string and create the Data URI
41
+ const dataUri = 'data:image/svg+xml,' + encodeURIComponent(svgString);
42
+ return (index.h("div", { key: 'e7b5846df55e2088312546869f50c32fc1b3f809', class: "user-avatar" }, index.h("img", { key: 'ef7af555265926a194ce8f972286ca3be5746b40', src: this.url ?? dataUri, alt: this.name, title: this.name }), index.h("div", { key: '46e7627446b02d7f1e42d110cbb5fd5a55ff333b', class: `status-indicator ${this.isOnline ? 'online' : 'offline'}` })));
43
+ }
44
+ };
45
+ ChatleoAvatar.style = chatleoAvatarCss();
46
+
47
+ const chatleoChatCss = () => `:host{display:flex;flex-direction:column;flex:1;min-height:0;overflow:hidden}.chat-container-list-and-chat{display:flex;flex-direction:row;height:100%;max-width:100%;min-height:0;overflow:hidden;padding:2px;border:1px solid var(--border-light);box-sizing:border-box;background:var(--bg-primary);position:relative}chatleo-room-view{flex:1;min-width:0;min-height:0;border-left:1px solid var(--border-light);transition:transform 0.3s ease-out}chatleo-room-list{flex:0 0 auto;min-height:0;transition:transform 0.3s ease-out}.toggle-btn{display:none;position:absolute;top:50%;left:50%;transform:translate(-50%, -50%);z-index:100;width:48px;height:48px;border-radius:50%;border:1px solid var(--border-light);background:var(--bg-primary);cursor:pointer;box-shadow:0 2px 8px rgba(0, 0, 0, 0.15);align-items:center;justify-content:center;padding:0}.toggle-btn svg{width:24px;height:24px;fill:var(--text-primary)}@media (max-width: 768px){.chat-container-list-and-chat{overflow-x:hidden}.toggle-btn{display:flex;right:8px;left:auto;top:8px;transform:none}chatleo-room-list{width:100%;flex:1}chatleo-room-view{width:100%;position:absolute;top:0;left:0;right:0;bottom:0;border-left:none}.show-room-list chatleo-room-list{transform:translateX(0)}.show-room-list chatleo-room-view{transform:translateX(100%)}.show-room-view chatleo-room-list{transform:translateX(-100%)}.show-room-view chatleo-room-view{transform:translateX(0)}}`;
48
+
49
+ const ChatleoChat = class {
50
+ constructor(hostRef) {
51
+ index.registerInstance(this, hostRef);
52
+ this.messageChatSent = index.createEvent(this, "messageChatSent");
53
+ }
54
+ /**
55
+ * An instance of the `ChatStore` class, which manages the application's state, including rooms, messages, and user profiles.
56
+ */
57
+ chatStore;
58
+ /**
59
+ * Indicates the current user's online status.
60
+ */
61
+ isOnline = false;
62
+ // TODO: needed?
63
+ /**
64
+ * If `true`, the component will display a loading state instead of the message list.
65
+ */
66
+ pending = false;
67
+ /** Calls are available and enabled for this host. */
68
+ callsAvailable = false;
69
+ /** This client is currently in the room's call. */
70
+ inCall = false;
71
+ selectedRoomId;
72
+ _version = 0;
73
+ _showRoomDetail = false;
74
+ roomViewRef;
75
+ handleToggleMobileView() {
76
+ this._showRoomDetail = !this._showRoomDetail;
77
+ }
78
+ isMobileViewport() {
79
+ return window.innerWidth < 768;
80
+ }
81
+ // --- Host API (used by the app shell for navigation, drafts and shares) ---
82
+ /** Opens a room regardless of the current pane, and shows the conversation on a phone. */
83
+ async openRoom(roomId) {
84
+ if (!roomId)
85
+ return;
86
+ this.selectedRoomId = roomId;
87
+ this.chatStore?.setActiveRoomId(roomId);
88
+ this.chatStore?.markRoomAsRead(roomId);
89
+ if (this.isMobileViewport())
90
+ this._showRoomDetail = true;
91
+ }
92
+ /** Returns to the room list (device back / app back button). */
93
+ async closeRoom() {
94
+ this._showRoomDetail = false;
95
+ this.chatStore?.setActiveRoomId(null);
96
+ }
97
+ async getDraft() {
98
+ return (await this.roomViewRef?.getDraft?.()) ?? '';
99
+ }
100
+ async setDraft(text) {
101
+ if (text)
102
+ await this.roomViewRef?.setDraft?.(text);
103
+ }
104
+ async addFiles(files) {
105
+ await this.roomViewRef?.addFiles?.(files ?? []);
106
+ }
107
+ async focusComposer() {
108
+ await this.roomViewRef?.focusComposer?.();
109
+ }
110
+ /**
111
+ * @function onChatStoreChange
112
+ * @description This watcher is triggered whenever the `chatStore` prop changes. It is responsible for setting up event listeners on the new store to update the component when data changes, such as when a new room is added or a message is received.
113
+ * @param {ChatStore} newStore - The new `ChatStore` instance.
114
+ * @param {ChatStore} oldStore - The previous `ChatStore` instance.
115
+ */
116
+ onChatStoreChange(newStore, oldStore) {
117
+ console.debug('onChatStoreChange', newStore, oldStore);
118
+ // TODO: unbind oldStore listeners
119
+ newStore.addEventListener('roomAdded', r => {
120
+ console.debug('roomAdded', r);
121
+ this._version++;
122
+ });
123
+ newStore.addEventListener('roomMessageAdded', e => {
124
+ console.debug('roomMessageAdded', e);
125
+ this._version++;
126
+ const detail = e.detail;
127
+ if (detail?.roomId && detail.roomId === this.selectedRoomId) {
128
+ newStore.markRoomAsRead(detail.roomId);
129
+ }
130
+ });
131
+ newStore.addEventListener('roomReadCountChanged', () => {
132
+ this._version++;
133
+ });
134
+ newStore.addEventListener('presenceChanged', e => {
135
+ console.debug('onPresenceChange', e);
136
+ this._version++;
137
+ });
138
+ }
139
+ messageChatSent;
140
+ // old
141
+ /**
142
+ * @function handleSendMessage
143
+ * @description This is a listener for the `messageInputSent` event, which is fired by the `chatleo-chat-input` component. It takes the plain text from the event, constructs a `ChatMessageSent` object, and emits it as a `messageChatSent` event.
144
+ * @param {CustomEvent<string>} event - The custom event containing the message text.
145
+ */
146
+ handleSendMessage(event) {
147
+ this.messageChatSent.emit({
148
+ room_id: this.selectedRoomId,
149
+ content: event.detail,
150
+ sender: this.chatStore?.profile?.id,
151
+ content_type: 'text/plain',
152
+ });
153
+ }
154
+ // new
155
+ /**
156
+ * @function messageSendHandler
157
+ * @description This listener handles the `messageSend` event from the `chatleo-rich-input` component. It processes the rich content payload, sanitizing it by removing base64 image previews from attachments to reduce payload size. It then constructs a `ChatMessageSent` object and emits it.
158
+ * @param {CustomEvent<any>} event - The custom event containing the structured message content.
159
+ */
160
+ messageSendHandler(event) {
161
+ console.log('Received the messageSend event: ', JSON.stringify(event.detail));
162
+ // Sanitize blocks: remove preview from each attachment object
163
+ const inputBlocks = event.detail?.blocks ?? [];
164
+ const sanitizedBlocks = inputBlocks.map((block) => {
165
+ if (block?.type === 'attachment' && Array.isArray(block.attachments)) {
166
+ const sanitizedAttachments = block.attachments.map((att) => {
167
+ const { preview, ...rest } = att ?? {};
168
+ return rest;
169
+ });
170
+ return { ...block, attachments: sanitizedAttachments };
171
+ }
172
+ return block;
173
+ });
174
+ this.messageChatSent.emit({
175
+ room_id: this.selectedRoomId,
176
+ // TODO: change to ChatMessageSent type
177
+ content: { blocks: sanitizedBlocks, version: event.detail.version },
178
+ content_type: 'application/json+blocks',
179
+ sender: this.chatStore?.profile?.id,
180
+ });
181
+ }
182
+ //
183
+ /**
184
+ * @function handleRoomClicked
185
+ * @description This listener is triggered when a user clicks on a room in the `chatleo-room-list` component. It updates the `selectedRoomId` state, which causes the component to re-render and display the messages for the newly selected room.
186
+ * @param {CustomEvent<RoomSummary>} event - The custom event containing the summary of the clicked room.
187
+ */
188
+ async handleRoomClicked(event) {
189
+ console.debug(`ChatleoChat.roomClicked`, event);
190
+ await this.openRoom(event.detail.id);
191
+ }
192
+ /**
193
+ * @function render
194
+ * @description The render method for the `ChatleoChat` component. It assembles the chat interface, including the room list and the room view. It uses the new `chatleo-room-view` component to display the selected room.
195
+ * @returns {any} A VNode representing the component's UI.
196
+ */
197
+ render() {
198
+ const mobileViewClass = this._showRoomDetail ? 'show-room-view' : 'show-room-list';
199
+ return (index.h("div", { key: '759aa942b6cfba0635119d0064afe7bc4e2ef901', class: `chat-container-list-and-chat ${mobileViewClass}` }, index.h("chatleo-room-list", { key: 'feecf22c1ab746ec5af8cb1e61708f131946a260', rooms: this.chatStore?.rooms, chatStore: this.chatStore, selectedRoomId: this.selectedRoomId }), index.h("chatleo-room-view", { key: 'c90a58b6946c949288176b3aa5a411b3d7722e7e', ref: el => (this.roomViewRef = el), chatStore: this.chatStore, roomId: this.selectedRoomId, isOnline: this.isOnline, pending: this.pending, callsAvailable: this.callsAvailable, inCall: this.inCall }), index.h("button", { key: 'd1ccaa37c2135f5a0f2945d82cc5becda60ea6e0', class: "toggle-btn", onClick: () => this.handleToggleMobileView() }, index.h("svg", { key: 'e5af148d5cfd19d7bc44cdd76fea530bc6683ea9', viewBox: "0 0 24 24" }, this._showRoomDetail ? index.h("path", { d: "M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z" }) : index.h("path", { d: "M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z" })))));
200
+ }
201
+ static get watchers() { return {
202
+ "chatStore": [{
203
+ "onChatStoreChange": 0
204
+ }]
205
+ }; }
206
+ };
207
+ ChatleoChat.style = chatleoChatCss();
208
+
209
+ const chatleoChatHeaderCss = () => `:host{--header-padding:16px;--header-gap:16px}.chat-header{display:flex;align-items:center;gap:var(--header-gap);padding:var(--header-padding);background:var(--bg-primary)}.header-name{font-family:var(--font-primary);font-weight:700;font-size:16px;line-height:1.6;color:var(--text-primary)}`;
210
+
211
+ const ChatleoChatHeader = class {
212
+ constructor(hostRef) {
213
+ index.registerInstance(this, hostRef);
214
+ }
215
+ /**
216
+ * The name of the user to be displayed in the header.
217
+ */
218
+ name = "";
219
+ /**
220
+ * The URL of the user's avatar image. This is passed to the `chatleo-avatar` component.
221
+ */
222
+ avatar;
223
+ /**
224
+ * A boolean indicating the user's online status, which is also passed to the `chatleo-avatar` component to show a status indicator.
225
+ */
226
+ isOnline = false;
227
+ /**
228
+ * @function render
229
+ * @description The render method for the `ChatleoChatHeader` component. It renders the user's avatar and name within a container.
230
+ * @returns {any} A VNode representing the component's UI.
231
+ */
232
+ render() {
233
+ return (index.h("div", { key: 'ff841f251f2e9a0065ac166e09e08fa5e0d9dd33', class: "chat-header" }, index.h("chatleo-avatar", { key: '9f3a6ee1fdae519dec06bc28c345440e410f8571', name: this.name, url: this.avatar, isOnline: this.isOnline }), index.h("div", { key: 'ab55b0c38ed957115a34fe5dda24e5f0fa888514', class: "header-name" }, this.name)));
234
+ }
235
+ };
236
+ ChatleoChatHeader.style = chatleoChatHeaderCss();
237
+
238
+ /**
239
+ * The text of a call history entry, or `null` when the message is not one.
240
+ *
241
+ * chatleo-server posts call entries as `application/json+blocks` with one `call` block:
242
+ * `{"version":"1","blocks":[{"type":"call","event":"started|ended|missed|declined|failed",
243
+ * "mode":…,"duration_ms":…}],"fallback_text":"Call ended · 1m 5s"}`. The message-level
244
+ * `fallback_text` is preferred; `state` and a block-level `fallback_text` are accepted too.
245
+ */
246
+ function callEntryText(contentBody) {
247
+ try {
248
+ const parsed = JSON.parse(contentBody);
249
+ const block = parsed?.call ?? (Array.isArray(parsed?.blocks) ? parsed.blocks.find((candidate) => candidate?.type === 'call') : undefined);
250
+ if (!block)
251
+ return null;
252
+ const text = block.fallback_text ?? parsed.fallback_text;
253
+ if (text)
254
+ return String(text);
255
+ const outcome = block.event ?? block.state;
256
+ const seconds = typeof block.duration_ms === 'number' ? Math.round(block.duration_ms / 1000) : undefined;
257
+ const duration = seconds ? ` · ${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, '0')}` : '';
258
+ if (outcome === 'missed' || block.reason === 'missed')
259
+ return 'Missed call';
260
+ if (outcome === 'declined' || block.reason === 'declined')
261
+ return 'Call declined';
262
+ if (outcome === 'ended' || outcome === 'failed')
263
+ return `Call ended${duration}`;
264
+ if (outcome === 'started' || outcome === 'active')
265
+ return block.mode === 'group' ? 'Group call started' : 'Call started';
266
+ return 'Call';
267
+ }
268
+ catch {
269
+ return null;
270
+ }
271
+ }
272
+
273
+ /** What the message footer should show for a locally originated message. */
274
+ function deliveryView(message, isOwnMessage) {
275
+ if (!isOwnMessage || !message?.delivery || message.delivery === 'sent') {
276
+ return { status: 'none', canRetry: false };
277
+ }
278
+ return { status: message.delivery, error: message.error, canRetry: Boolean(message.client_id) };
279
+ }
280
+
281
+ const chatleoChatMessageCss = () => `:host{--status-size:9px;--status-border:1.5px}.message-row{display:flex;gap:16px;padding-left:16px}.message-avatar-container{position:relative;width:var(--avatar-size);height:var(--avatar-size);flex-shrink:0}.message-avatar{width:100%;height:100%;border-radius:50%;object-fit:cover;background:var(--bg-light)}.message-status-indicator{position:absolute;bottom:0;right:0;width:var(--status-size);height:var(--status-size);border-radius:50%;border:var(--status-border) solid var(--bg-primary)}.message-status-indicator.online{background:var(--status-online)}.message-status-indicator.offline{background:var(--border-color)}.message-content{flex:1;display:flex;flex-direction:column;gap:4px}.message-header{display:flex;align-items:center;gap:8px}.message-author{font-family:var(--font-primary);font-weight:700;font-size:14px;line-height:1.6;color:var(--text-primary)}.message-timestamp{font-family:var(--font-primary);font-weight:400;font-size:12px;line-height:1.65;color:var(--text-secondary)}.message-timestamp::before{content:'•';margin-right:8px}.message-text{font-family:var(--font-primary);font-weight:400;font-size:14px;line-height:1.6;color:var(--text-primary);word-wrap:break-word;}.message-status{display:flex;align-items:center;gap:8px;font-family:var(--font-primary);font-size:12px;line-height:1.5}.message-status.pending{color:var(--text-secondary);font-style:italic}.message-status.failed{color:#c62828;flex-wrap:wrap}.message-status-actions{display:inline-flex;gap:6px}.status-action{border:1px solid currentColor;background:transparent;color:inherit;border-radius:4px;padding:1px 8px;font:inherit;cursor:pointer}.status-action:hover{background:rgba(198, 40, 40, 0.08)}.status-action.discard{opacity:0.8}.call-message{display:inline-flex;align-items:center;gap:6px;padding:6px 10px;border:1px solid var(--border-light, #ddd);border-radius:8px;font-family:var(--font-primary);font-size:13px;color:var(--text-secondary, #667);background:var(--bg-secondary, transparent)}.call-message::before{content:'☎';font-size:15px}`;
282
+
283
+ const ChatleoChatMessageComponent = class {
284
+ constructor(hostRef) {
285
+ index.registerInstance(this, hostRef);
286
+ this.messageRetry = index.createEvent(this, "messageRetry");
287
+ this.messageDiscard = index.createEvent(this, "messageDiscard");
288
+ }
289
+ message;
290
+ sender = undefined;
291
+ senderIsOnline = false;
292
+ isOwnMessage = false;
293
+ locale = 'en-US';
294
+ translations = {};
295
+ /** Emitted when the user asks to resend a failed message (detail: `client_id`). */
296
+ messageRetry;
297
+ /** Emitted when the user discards a failed/pending message (detail: `client_id`). */
298
+ messageDiscard;
299
+ isStructuredContent(content) {
300
+ try {
301
+ const parsed = JSON.parse(content);
302
+ if (parsed && parsed.blocks && Array.isArray(parsed.blocks) && parsed.version) {
303
+ return parsed;
304
+ }
305
+ }
306
+ catch (e) {
307
+ // Not JSON or invalid structure
308
+ }
309
+ return null;
310
+ }
311
+ formatTimestamp(isoDate) {
312
+ try {
313
+ return new Intl.DateTimeFormat(this.locale, {
314
+ hour: 'numeric',
315
+ minute: 'numeric',
316
+ }).format(new Date(isoDate));
317
+ }
318
+ catch (e) {
319
+ return isoDate;
320
+ }
321
+ }
322
+ defaultTranslations = {
323
+ you: 'You',
324
+ sending: 'Sending…',
325
+ failed: 'Not sent',
326
+ retry: 'Retry',
327
+ discard: 'Discard',
328
+ };
329
+ t(key) {
330
+ console.log(`Translating key: ${key}`, this.translations, this.defaultTranslations);
331
+ // Use the provided translation, fallback to default, finally fallback to the key itself.
332
+ return this.translations[key] || this.defaultTranslations[key] || key;
333
+ }
334
+ callEntry() {
335
+ return callEntryText(this.message.content_body);
336
+ }
337
+ renderMessageContent() {
338
+ const callEntry = this.callEntry();
339
+ if (callEntry)
340
+ return index.h("div", { class: "call-message" }, callEntry);
341
+ const structuredContent = this.isStructuredContent(this.message.content_body);
342
+ if (structuredContent) {
343
+ return (index.h(index.h.Fragment, null, index.h("chatleo-rich-message-renderer", { content: structuredContent, downloadUrls: this.message.attachment_details, alignment: this.isOwnMessage ? 'right' : 'left' })));
344
+ }
345
+ // Fallback to plain text
346
+ return (index.h("div", { class: "message-text", style: { textAlign: this.isOwnMessage ? 'right' : 'left' } }, this.message.content_body));
347
+ }
348
+ renderDeliveryStatus() {
349
+ const view = deliveryView(this.message, this.isOwnMessage);
350
+ if (view.status === 'none')
351
+ return null;
352
+ const clientId = this.message.client_id;
353
+ if (view.status === 'pending') {
354
+ return (index.h("div", { class: "message-status pending", "aria-live": "polite" }, this.t('sending')));
355
+ }
356
+ return (index.h("div", { class: "message-status failed" }, index.h("span", { class: "message-status-text" }, this.t('failed'), view.error ? `: ${view.error}` : ''), view.canRetry && clientId && (index.h("span", { class: "message-status-actions" }, index.h("button", { type: "button", class: "status-action", onClick: () => this.messageRetry.emit(clientId) }, this.t('retry')), index.h("button", { type: "button", class: "status-action discard", onClick: () => this.messageDiscard.emit(clientId) }, this.t('discard'))))));
357
+ }
358
+ render() {
359
+ const authorName = this.isOwnMessage ? this.t('you') : (this.sender?.display_name ?? '');
360
+ return (index.h("div", { key: 'c91f01cbf694c79d4e68b8445a99ffbc5b0b9790', class: "message-row" }, !this.isOwnMessage && index.h("chatleo-avatar", { key: '6f05c378fd18203d9917f1edbc61b20bf94b81b9', name: authorName, url: this.sender?.profile_picture_url ?? null, isOnline: this.senderIsOnline }), index.h("div", { key: 'b1f4df458b587cace3423637b5bad8350a5c3a14', class: "message-content" }, index.h("div", { key: 'f7c565319462013dac380d21a813e21861544833', class: "message-header", style: { justifyContent: this.isOwnMessage ? 'end' : 'start' } }, index.h("span", { key: '4d30b5eb0c55abb854b6192f0fe9c78bb54aff33', class: "message-author" }, authorName), index.h("span", { key: '13867dc122764cbdbdd7fa60f5ff7e6916ed49e7', class: "message-timestamp" }, this.formatTimestamp(this.message.created_at))), this.renderMessageContent(), this.renderDeliveryStatus()), this.isOwnMessage && index.h("chatleo-avatar", { key: 'c818e945cb494c07356fae74c00719e32a2c6b23', name: authorName, url: this.sender?.profile_picture_url ?? null, isOnline: this.senderIsOnline })));
361
+ }
362
+ };
363
+ ChatleoChatMessageComponent.style = chatleoChatMessageCss();
364
+
365
+ const chatleoComponentCss = () => `:host{overflow:hidden;position:relative;height:100%;max-height:100%;min-height:0;--display:block;--bg-primary:#ffffff;--bg-secondary:#f3f4f6;--bg-light:#e7effc;--text-primary:#171a1f;--text-secondary:#9095a1;--border-color:#bdc1ca;--border-light:#eeeeee;--accent-color:#4a86e8;--accent-hover:#3a7bd8;--status-online:#21d184;--status-offline:#6b7280;--font-primary:'Manrope', sans-serif;--avatar-size:36px;--border-radius:8px;--transition-duration:0.2s;display:var(--display)}.connection-banner{display:flex;align-items:center;gap:6px;padding:5px 12px;font-family:var(--font-primary, 'Manrope', sans-serif);font-size:12px;font-weight:600;color:#fff;background:#6b7280;z-index:100;flex-shrink:0}.connection-banner--connecting,.connection-banner--reconnecting{background:#f59e0b;color:#fff}.connection-banner--disconnected{background:#ef4444;color:#fff}.connection-banner__dot{width:7px;height:7px;border-radius:50%;background:rgba(255, 255, 255, 0.8);flex-shrink:0;animation:pulse-dot 1.4s ease-in-out infinite}.connection-banner--disconnected .connection-banner__dot{animation:none}@keyframes pulse-dot{0%,100%{opacity:1}50%{opacity:0.3}}.session-expired-overlay{position:absolute;inset:0;z-index:9999;background:rgba(255, 255, 255, 0.85);backdrop-filter:blur(4px);display:flex;align-items:center;justify-content:center}.session-expired-box{background:var(--bg-primary, #fff);border:1px solid var(--border-color, #bdc1ca);border-radius:var(--border-radius, 8px);box-shadow:0 4px 24px rgba(0, 0, 0, 0.12);padding:32px 28px;max-width:340px;width:100%;text-align:center;display:flex;flex-direction:column;align-items:center;gap:12px}.session-expired-icon{color:#f59e0b;width:32px;height:32px}.session-expired-title{margin:0;font-family:var(--font-primary, 'Manrope', sans-serif);font-size:16px;font-weight:700;color:var(--text-primary, #171a1f)}.session-expired-message{margin:0;font-family:var(--font-primary, 'Manrope', sans-serif);font-size:13px;color:var(--text-secondary, #9095a1);line-height:1.6}.session-expired-button{margin-top:4px;padding:8px 20px;background:var(--accent-color, #4a86e8);color:#fff;border:none;border-radius:var(--border-radius, 8px);font-family:var(--font-primary, 'Manrope', sans-serif);font-size:14px;font-weight:600;cursor:pointer;transition:background var(--transition-duration, 0.2s)}.session-expired-button:hover{background:var(--accent-hover, #3a7bd8)}.call-layer{position:absolute;inset:0;z-index:40;background:var(--bg-primary, #fff);flex-direction:column}.call-layer__back{align-self:flex-end;margin:8px 16px 0;border:1px solid var(--border-color, #ddd);background:transparent;border-radius:6px;padding:4px 10px;font:inherit;cursor:pointer}.incoming-call{position:absolute;inset:0;z-index:50;display:flex;align-items:center;justify-content:center;background:rgba(15, 23, 42, 0.45)}.incoming-call:focus{outline:none}.incoming-call__box{width:min(320px, calc(100% - 32px));background:var(--bg-primary, #fff);border-radius:12px;padding:24px;text-align:center;box-shadow:0 18px 50px rgba(15, 23, 42, 0.25)}.incoming-call__eyebrow{margin:0 0 12px;font-size:12px;letter-spacing:0.08em;text-transform:uppercase;color:var(--text-secondary, #667)}.incoming-call__name{margin:12px 0 20px;font-size:18px;font-weight:700}.incoming-call__actions{display:flex;gap:10px;justify-content:center}.incoming-call__accept,.incoming-call__decline{border-radius:8px;padding:8px 18px;font:inherit;cursor:pointer}.incoming-call__accept{border:none;background:#1b8a3a;color:#fff}.incoming-call__decline{border:1px solid var(--border-color, #ddd);background:transparent;color:inherit}.push-control{display:flex;align-items:center;gap:8px;padding:6px 12px;border:0;border-bottom:1px solid var(--border-light, #eee);background:var(--bg-secondary, #f7f8fa);color:var(--text-primary, #222);font:inherit;font-size:12px;text-align:left;cursor:pointer}.push-control--hint{cursor:default;color:var(--text-secondary, #667)}.push-control--prompt{flex-wrap:wrap}.push-control--prompt button{border:1px solid var(--accent-color, #4a86e8);border-radius:6px;background:transparent;color:var(--accent-color, #4a86e8);padding:3px 10px;font:inherit;cursor:pointer}.push-control__secondary{border-color:var(--border-color, #ddd) !important;color:var(--text-secondary, #667) !important}`;
366
+
367
+ const ChatLeoComponent = class {
368
+ constructor(hostRef) {
369
+ index.registerInstance(this, hostRef);
370
+ this.activeRoomChange = index.createEvent(this, "activeRoomChange");
371
+ this.unreadTotalChange = index.createEvent(this, "unreadTotalChange");
372
+ }
373
+ /**
374
+ * The username of the user, which can be used for authentication.
375
+ */
376
+ username; // optional, not currently used for login without password
377
+ /**
378
+ * An authentication ticket used to establish a connection with the chat service.
379
+ */
380
+ ticket;
381
+ /**
382
+ * If `true`, the component will render as a tray-based chat widget.
383
+ */
384
+ useTray;
385
+ /**
386
+ * If `true`, the component will render as a full-page chat application.
387
+ */
388
+ useMain = false;
389
+ /**
390
+ * If `true`, the component will render as a single room view without the room list.
391
+ */
392
+ useRoomView = false;
393
+ /**
394
+ * The ID of the room to display when using room view mode.
395
+ */
396
+ roomId;
397
+ /**
398
+ * An instance of the `ChatLeoLib` class, which provides the core chat functionalities.
399
+ */
400
+ chatLeoLib;
401
+ /**
402
+ * An instance of the `ChatStore` class, which manages the application's state.
403
+ */
404
+ chatStore;
405
+ //
406
+ serverUrl;
407
+ /**
408
+ * Real-time protocol: `socketio` (default), `v2` (ChatLeo Protocol v2) or `auto`
409
+ * (use v2 when the server's `/.well-known/chatleo` offers it, otherwise Socket.IO).
410
+ * Overrides `ChatLeoLib.transport`.
411
+ */
412
+ transport;
413
+ /** `auto` shows call controls when the server advertises calls; `off` disables the call UI. */
414
+ calls = 'auto';
415
+ /** `manual` shows a notification control; `prompt` also shows an in-page explanation; `off` hides it. */
416
+ push = 'manual';
417
+ /** Path of the push service worker served by the host. */
418
+ pushSwPath;
419
+ isLoggedIn = false;
420
+ loading = false;
421
+ isSessionExpired = false;
422
+ connectionStatus = 'disconnected';
423
+ callsAvailable = false;
424
+ incomingCall = null;
425
+ callView = null;
426
+ showCall = false;
427
+ pushState = null;
428
+ pushPromptDismissed = false;
429
+ /** Fires when the open conversation changes, so a host can drive navigation/history. */
430
+ activeRoomChange;
431
+ /** Fires when the total unread count changes (app badge, title, ...). */
432
+ unreadTotalChange;
433
+ chatEl;
434
+ boundActiveRoomChanged = (e) => this.activeRoomChange.emit(e.detail ?? { roomId: null });
435
+ boundUnreadTotalChanged = (e) => this.unreadTotalChange.emit(e.detail ?? { count: 0 });
436
+ callRingtoneTimer;
437
+ incomingRef;
438
+ callRingtoneContext;
439
+ callsChannel;
440
+ callAdapterRef;
441
+ trayEl;
442
+ // --- External integration event names (global custom events) ---
443
+ // detail: { roomId: string }
444
+ static OPEN_ROOM_EVENT = 'chatleo:openRoom';
445
+ // detail: { userId: string }
446
+ static START_DM_EVENT = 'chatleo:startDM';
447
+ // detail: none or { open: true }
448
+ static NEW_CHAT_EVENT = 'chatleo:newChat';
449
+ // Keep bound listeners for removal
450
+ boundOpenRoomListener = (e) => this.handleExternalOpenRoom(e);
451
+ boundStartDmListener = (e) => this.handleExternalStartDm(e);
452
+ boundNewChatListener = (e) => this.handleExternalNewChat(e);
453
+ boundStartCallListener = (e) => this.handleExternalStartCall(e);
454
+ boundCallRinging = (e) => this.handleCallRinging(e);
455
+ boundCallChanged = (e) => this.handleCallChanged(e);
456
+ boundCallRole = (e) => this.handleCallRole(e);
457
+ boundServiceWorkerMessage = (event) => this.handleServiceWorkerMessage(event);
458
+ /**
459
+ * @function onChatLeoLibChange
460
+ * @description A Stencil watcher that triggers when the `chatLeoLib` prop is updated. This is mainly used for debugging to observe when the library is injected.
461
+ * @param {ChatLeoLib} newValue - The new instance of `ChatLeoLib`.
462
+ */
463
+ onChatLeoLibChange(newValue) {
464
+ console.debug('onChatLeoLibChange', newValue);
465
+ if (newValue) {
466
+ this.requestLibConnection();
467
+ }
468
+ }
469
+ /**
470
+ * @function onChatStoreChange
471
+ * @description A Stencil watcher that triggers when the `chatStore` prop is updated. It attaches an event listener to the new store to listen for new rooms being added.
472
+ * @param {ChatStore} newStore - The new `ChatStore` instance.
473
+ * @param {ChatStore} oldStore - The previous `ChatStore` instance.
474
+ */
475
+ onChatStoreChange(newStore, oldStore) {
476
+ console.debug('onChatStoreChange', newStore, oldStore);
477
+ oldStore?.removeEventListener('callRinging', this.boundCallRinging);
478
+ oldStore?.removeEventListener('callChanged', this.boundCallChanged);
479
+ oldStore?.removeEventListener('callRole', this.boundCallRole);
480
+ oldStore?.removeEventListener('activeRoomChanged', this.boundActiveRoomChanged);
481
+ oldStore?.removeEventListener('unreadTotalChanged', this.boundUnreadTotalChanged);
482
+ newStore.addEventListener('callRinging', this.boundCallRinging);
483
+ newStore.addEventListener('callChanged', this.boundCallChanged);
484
+ newStore.addEventListener('callRole', this.boundCallRole);
485
+ newStore.addEventListener('activeRoomChanged', this.boundActiveRoomChanged);
486
+ newStore.addEventListener('unreadTotalChanged', this.boundUnreadTotalChanged);
487
+ // TODO: unbind oldStore listeners
488
+ newStore.addEventListener('roomAdded', r => {
489
+ console.warn(r);
490
+ });
491
+ this.activeRoomChange.emit({ roomId: newStore.activeRoomId });
492
+ this.unreadTotalChange.emit({ count: newStore.unreadTotal });
493
+ }
494
+ /**
495
+ * @function onTicketChange
496
+ * @description A Stencil watcher that is called when the `ticket` prop changes. This will trigger a reconnection attempt to the chat library with the new ticket.
497
+ * @param {string} _newValue - The new authentication ticket.
498
+ */
499
+ onTicketChange(_newValue) {
500
+ console.debug('onTicketChange', _newValue);
501
+ this.requestLibConnection();
502
+ }
503
+ /** A host can turn the call UI on/off after sign-in (settings screen). */
504
+ onCallsChange(value) {
505
+ this.chatLeoLib?.setCallsEnabled?.(value !== 'off');
506
+ void this.refreshCallsAvailability();
507
+ }
508
+ componentDidLoad() {
509
+ console.debug('ChatLeoComponent:componentDidLoad', this.serverUrl);
510
+ this.requestLibConnection(); // XXX: this triggers: @Prop() "chatStore" on <chatleo-component> is immutable but was modified from within the component.
511
+ // https://stenciljs.com/docs/properties#prop-mutability
512
+ }
513
+ connectedCallback() {
514
+ console.debug(`ChatLeoComponent:connectedCallback`);
515
+ // Register global custom event listeners for external integration
516
+ window.addEventListener(ChatLeoComponent.OPEN_ROOM_EVENT, this.boundOpenRoomListener);
517
+ window.addEventListener(ChatLeoComponent.START_DM_EVENT, this.boundStartDmListener);
518
+ window.addEventListener(ChatLeoComponent.NEW_CHAT_EVENT, this.boundNewChatListener);
519
+ window.addEventListener('chatleo:startCall', this.boundStartCallListener);
520
+ if (typeof navigator !== 'undefined' && 'serviceWorker' in navigator) {
521
+ navigator.serviceWorker.addEventListener('message', this.boundServiceWorkerMessage);
522
+ }
523
+ }
524
+ disconnectedCallback() {
525
+ console.debug('ChatLeoComponent:disconnectedCallback');
526
+ this.chatLeoLib?.unregisterClient(this);
527
+ window.removeEventListener(ChatLeoComponent.OPEN_ROOM_EVENT, this.boundOpenRoomListener);
528
+ window.removeEventListener(ChatLeoComponent.START_DM_EVENT, this.boundStartDmListener);
529
+ window.removeEventListener(ChatLeoComponent.NEW_CHAT_EVENT, this.boundNewChatListener);
530
+ window.removeEventListener('chatleo:startCall', this.boundStartCallListener);
531
+ if (typeof navigator !== 'undefined' && 'serviceWorker' in navigator) {
532
+ navigator.serviceWorker.removeEventListener('message', this.boundServiceWorkerMessage);
533
+ }
534
+ this.chatStore?.removeEventListener('callRinging', this.boundCallRinging);
535
+ this.chatStore?.removeEventListener('callChanged', this.boundCallChanged);
536
+ this.chatStore?.removeEventListener('activeRoomChanged', this.boundActiveRoomChanged);
537
+ this.chatStore?.removeEventListener('unreadTotalChanged', this.boundUnreadTotalChanged);
538
+ this.chatStore?.removeEventListener('callRole', this.boundCallRole);
539
+ this.stopRingtone();
540
+ this.callsChannel?.close();
541
+ }
542
+ async requestLibConnection() {
543
+ console.debug('requestLibConnection', this.chatLeoLib);
544
+ this.chatLeoLib?.setCallsEnabled?.(this.calls !== 'off');
545
+ if (this.pushSwPath)
546
+ this.chatLeoLib?.setPushServiceWorkerPath?.(this.pushSwPath);
547
+ // Register and request connection; ticket preferred when provided
548
+ await this.chatLeoLib?.requestConnection(this, {
549
+ ...(this.ticket ? { ticket: this.ticket } : {}),
550
+ ...(this.transport ? { transport: this.transport } : {}),
551
+ });
552
+ }
553
+ // ChatLeoClient callbacks
554
+ /**
555
+ * @function setLoading
556
+ * @description This method is part of the `ChatLeoClient` interface. It is called by the `ChatLeoLib` to update the component's loading state.
557
+ * @param {boolean} loading - A boolean indicating whether the application is in a loading state.
558
+ */
559
+ setLoading(loading) {
560
+ this.loading = loading;
561
+ }
562
+ /**
563
+ * @function setLoggedIn
564
+ * @description This method is part of the `ChatLeoClient` interface. It is called by the `ChatLeoLib` to update the component's logged-in state.
565
+ * @param {boolean} isLoggedIn - A boolean indicating whether the user is logged in.
566
+ */
567
+ setLoggedIn(isLoggedIn) {
568
+ // XXX: The state/prop "isLoggedIn" changed during "componentDidLoad()", this triggers extra re-renders, try to setup on "componentWillLoad()"
569
+ this.isLoggedIn = isLoggedIn;
570
+ if (isLoggedIn) {
571
+ void this.refreshCallsAvailability();
572
+ void this.refreshPush();
573
+ }
574
+ }
575
+ /**
576
+ * @function setSessionExpired
577
+ * @description Called by ChatLeoLib when token refresh fails. Shows an overlay prompting the user to reload.
578
+ */
579
+ setSessionExpired(expired) {
580
+ this.isSessionExpired = expired;
581
+ }
582
+ /** Called by ChatLeoLib when the socket connection status changes. */
583
+ setConnectionStatus(status) {
584
+ this.connectionStatus = status;
585
+ }
586
+ // --- Public API Methods (callable from DOM element) ---
587
+ /**
588
+ * @function getConnectionStatus
589
+ * @description Returns the current connection and session status of the chat component.
590
+ *
591
+ * Embedding applications should call this method on `window` focus events (or any
592
+ * other relevant trigger) to determine whether the user's session is still valid
593
+ * and whether the page needs to be reloaded.
594
+ *
595
+ * @returns {Promise<{ isConnected: boolean; isSessionExpired: boolean }>}
596
+ * - `isConnected` – `true` when the underlying WebSocket is currently connected.
597
+ * - `isSessionExpired` – `true` when the token refresh has permanently failed
598
+ * (HTTP 401/403 from the refresh endpoint, or too many transient errors).
599
+ * When this is `true` the user must reload the page to restore the session.
600
+ *
601
+ * @example
602
+ * const chatEl = document.querySelector('chatleo-component');
603
+ *
604
+ * // Check on every tab-focus whether a reload is needed
605
+ * window.addEventListener('focus', async () => {
606
+ * const { isSessionExpired } = await chatEl.getConnectionStatus();
607
+ * if (isSessionExpired) {
608
+ * window.location.reload();
609
+ * }
610
+ * });
611
+ */
612
+ async getConnectionStatus() {
613
+ return {
614
+ isConnected: this.chatStore?.isConnected ?? false,
615
+ isSessionExpired: this.isSessionExpired || (this.chatStore?.isSessionExpired ?? false),
616
+ connectionStatus: this.chatStore?.connectionStatus ?? this.connectionStatus,
617
+ };
618
+ }
619
+ /**
620
+ * @function openRoom
621
+ * @description This method provides a public API to programmatically open a specific chat room in the tray view. It calls the `openChatPanel` method on the `chatleo-tray-component` element.
622
+ * @param {string} roomId - The ID of the room to be opened.
623
+ */
624
+ async openRoom(roomId) {
625
+ if (!roomId) {
626
+ console.warn('[chatleo-component] openRoom called without roomId');
627
+ return;
628
+ }
629
+ if (this.useTray) {
630
+ await this.trayEl?.openChatPanel(roomId, false);
631
+ return;
632
+ }
633
+ await this.chatEl?.openRoom?.(roomId);
634
+ }
635
+ /**
636
+ * @function closeRoom
637
+ * @description Returns to the room list (used for the device back action and deep links
638
+ * that could not be opened).
639
+ */
640
+ async closeRoom() {
641
+ if (this.useTray) {
642
+ await this.trayEl?.closeChatPanel?.();
643
+ return;
644
+ }
645
+ await this.chatEl?.closeRoom?.();
646
+ }
647
+ /** The currently open room, or `null` on the room list. */
648
+ async getActiveRoomId() {
649
+ return this.chatStore?.activeRoomId ?? null;
650
+ }
651
+ /** Unsent composer text (used to preserve a draft across an app update). */
652
+ async getDraft() {
653
+ return (await this.chatEl?.getDraft?.()) ?? '';
654
+ }
655
+ /** Restores unsent composer text. */
656
+ async setDraft(text) {
657
+ if (text)
658
+ await this.chatEl?.setDraft?.(text);
659
+ }
660
+ /** Adds shared files to the composer of the open room. */
661
+ async addFiles(files) {
662
+ await this.chatEl?.addFiles?.(files ?? []);
663
+ }
664
+ /** Focuses the composer (share text, deep link). */
665
+ async focusComposer() {
666
+ await this.chatEl?.focusComposer?.();
667
+ }
668
+ /**
669
+ * @function openDirectMessageWithUser
670
+ * @description This method allows programmatically opening a direct message conversation with a specific user. It will either find an existing DM room or create a new one.
671
+ * @param {string} userId - The ID of the user to start a direct message with.
672
+ * @param use_external_id
673
+ */
674
+ async openDirectMessageWithUser(userId, use_external_id = false) {
675
+ if (!userId) {
676
+ console.warn('[chatleo-component] openDirectMessageWithUser called without userId');
677
+ return;
678
+ }
679
+ await this.internalStartDmFlow(userId, use_external_id);
680
+ }
681
+ /**
682
+ * @function openNewChatDraft
683
+ * @description This method programmatically opens the new chat draft view in the tray, allowing the user to start a new conversation.
684
+ */
685
+ async openNewChatDraft() {
686
+ await this.trayEl?.openChatPanel(undefined, true);
687
+ }
688
+ // --- Internal helpers reused by events & @Method API ---
689
+ async internalStartDmFlow(userId, use_external_id = false) {
690
+ if (!userId)
691
+ return;
692
+ try {
693
+ // await this.trayEl?.openChatPanel(undefined, true); // pending state while ensuring DM
694
+ const existingRoomId = this.chatLeoLib?.findDirectMessageRoomIdByUser(userId);
695
+ console.debug(`internalStartDmFlow`, { existingRoomId });
696
+ if (existingRoomId) {
697
+ await this.openRoom(existingRoomId);
698
+ return;
699
+ }
700
+ const ensureResult = await this.chatLeoLib?.ensureDirectMessageRoom(userId, use_external_id);
701
+ const roomId = ensureResult?.roomId;
702
+ if (roomId) {
703
+ await this.openRoom(roomId);
704
+ }
705
+ else {
706
+ console.warn('[chatleo-component] ensureDirectMessageRoom returned no roomId');
707
+ await this.trayEl?.openChatPanel(undefined, false);
708
+ }
709
+ }
710
+ catch (e) {
711
+ console.error('[chatleo-component] Failed to start DM', e);
712
+ await this.trayEl?.openChatPanel(undefined, false);
713
+ }
714
+ }
715
+ // --- Global external event handlers ---
716
+ async handleExternalOpenRoom(event) {
717
+ // Allow sloppy callers that forgot { detail: { roomId }} and instead passed { roomId }
718
+ const sloppy = event.roomId;
719
+ const roomId = event?.detail?.roomId || sloppy;
720
+ if (!roomId) {
721
+ if (!event?.detail) {
722
+ console.warn('[chatleo-component] chatleo:openRoom event missing detail. Use new CustomEvent("chatleo:openRoom", { detail: { roomId: "..." } })');
723
+ }
724
+ return;
725
+ }
726
+ await this.openRoom(roomId);
727
+ }
728
+ async handleExternalStartDm(event) {
729
+ console.log('handleExternalStartDm', event);
730
+ // Support sloppy dispatch new CustomEvent('chatleo:startDM', { userId })
731
+ const sloppy = event.userId;
732
+ const userId = event?.detail?.userId || sloppy;
733
+ const use_external_id = event?.detail?.use_external_id ?? false;
734
+ if (!userId) {
735
+ if (!event?.detail) {
736
+ console.warn('[chatleo-component] chatleo:startDM event missing detail. Dispatch like: new CustomEvent("chatleo:startDM", { detail: { userId: "123" } })');
737
+ }
738
+ return;
739
+ }
740
+ await this.openDirectMessageWithUser(userId, use_external_id);
741
+ }
742
+ async handleExternalNewChat(_event) {
743
+ await this.openNewChatDraft();
744
+ }
745
+ // --- Calls -----------------------------------------------------------------
746
+ async refreshCallsAvailability() {
747
+ if (this.calls === 'off' || !this.chatLeoLib?.ensureCallsAvailable) {
748
+ this.callsAvailable = false;
749
+ return;
750
+ }
751
+ this.callsAvailable = await this.chatLeoLib.ensureCallsAvailable();
752
+ }
753
+ async loadCallComponents() {
754
+ if (typeof window === 'undefined' || window.customElements.get('chatleo-call-adapter'))
755
+ return true;
756
+ try {
757
+ // The self-contained custom-elements build: importing it defines the adapter and every
758
+ // call component it renders. It is bundled into this build as a lazy chunk, so it loads
759
+ // from wherever the chat components are served (the lazy loader of call-components would
760
+ // look for its own entry files next to this build and not find them).
761
+ await Promise.resolve().then(function () { return require('./chatleo-call-adapter-B2OfC0VZ.js'); });
762
+ return !!window.customElements.get('chatleo-call-adapter');
763
+ }
764
+ catch (error) {
765
+ console.warn('[chatleo-component] call components could not be loaded', error);
766
+ return false;
767
+ }
768
+ }
769
+ async startOrJoinCall(roomId, callId, mode) {
770
+ if (!this.chatLeoLib)
771
+ return;
772
+ // Already in this call (the chat was in front): show it again instead of joining twice.
773
+ const running = this.callView && (callId ? this.callView.callId === callId : this.callView.roomId === roomId);
774
+ if (running) {
775
+ this.showCall = true;
776
+ return;
777
+ }
778
+ try {
779
+ const room = this.chatStore?.rooms.find(candidate => candidate.id === roomId);
780
+ const call = callId ? { id: callId, mode: room?.type === 'DirectMessage' ? 'direct' : 'group' } : await this.chatLeoLib.startCall(roomId, mode);
781
+ const credentials = await this.chatLeoLib.joinCall(call.id);
782
+ const loaded = await this.loadCallComponents();
783
+ if (!loaded)
784
+ return;
785
+ this.callView = {
786
+ callId: call.id,
787
+ roomId,
788
+ // The join response names the mode: a call joined from the banner may be a stage call.
789
+ mode: credentials.mode ?? call.mode,
790
+ credentials: {
791
+ sfuUrl: credentials.sfu_url,
792
+ token: credentials.token,
793
+ roomId: credentials.room_id,
794
+ mode: credentials.mode,
795
+ iceServers: credentials.ice_servers,
796
+ },
797
+ };
798
+ this.showCall = true;
799
+ this.incomingCall = null;
800
+ this.stopRingtone();
801
+ }
802
+ catch (error) {
803
+ console.warn('[chatleo-component] call start/join failed', error);
804
+ }
805
+ }
806
+ onIncomingCallChange(call) {
807
+ if (!call)
808
+ return;
809
+ setTimeout(() => this.incomingRef?.focus(), 0);
810
+ }
811
+ handleCallRinging(event) {
812
+ this.incomingCall = event.detail?.call ?? null;
813
+ if (this.incomingCall)
814
+ this.startRingtone(this.incomingCall.id);
815
+ else
816
+ this.stopRingtone();
817
+ }
818
+ handleCallChanged(event) {
819
+ if (this.callView && !event.detail?.call) {
820
+ this.callView = null;
821
+ this.showCall = false;
822
+ this.stopRingtone();
823
+ }
824
+ }
825
+ async acceptIncomingCall() {
826
+ if (!this.incomingCall)
827
+ return;
828
+ const call = this.incomingCall;
829
+ this.incomingCall = null;
830
+ this.stopRingtone();
831
+ await this.startOrJoinCall(call.room_id, call.id);
832
+ }
833
+ async declineIncomingCall() {
834
+ if (!this.incomingCall || !this.chatLeoLib)
835
+ return;
836
+ const call = this.incomingCall;
837
+ this.incomingCall = null;
838
+ this.stopRingtone();
839
+ try {
840
+ await this.chatLeoLib.declineCall(call.id);
841
+ }
842
+ catch (error) {
843
+ console.warn('[chatleo-component] decline failed', error);
844
+ }
845
+ }
846
+ handleExternalStartCall(event) {
847
+ const roomId = event?.detail?.roomId;
848
+ if (roomId)
849
+ void this.startOrJoinCall(roomId, undefined, event.detail.mode);
850
+ }
851
+ /** ChatLeo changed this user's role in a stage call: present a new token so the SFU applies it. */
852
+ handleCallRole(event) {
853
+ const { callId, userId } = event.detail ?? {};
854
+ if (!this.callView || this.callView.callId !== callId)
855
+ return;
856
+ if (userId && userId !== this.chatStore?.profile?.id)
857
+ return;
858
+ this.callAdapterRef
859
+ ?.refreshToken?.()
860
+ .catch(error => console.warn('[chatleo-component] token refresh after a role change failed', error));
861
+ }
862
+ /** Fresh SFU credentials for the running call: token expiry and role changes. */
863
+ callToken = async () => {
864
+ const view = this.callView;
865
+ if (!view || !this.chatLeoLib)
866
+ throw new Error('no call');
867
+ const fresh = await this.chatLeoLib.refreshCallToken(view.callId);
868
+ return { token: fresh.token, sfuUrl: fresh.sfu_url, iceServers: fresh.ice_servers };
869
+ };
870
+ promoteInCall = async (_participantId, _capabilities, participant) => {
871
+ const view = this.callView;
872
+ if (!view || !this.chatLeoLib || !participant?.userId)
873
+ throw new Error('unknown participant');
874
+ await this.chatLeoLib.promoteCallParticipant(view.callId, participant.userId);
875
+ };
876
+ demoteInCall = async (_participantId, participant) => {
877
+ const view = this.callView;
878
+ if (!view || !this.chatLeoLib || !participant?.userId)
879
+ throw new Error('unknown participant');
880
+ await this.chatLeoLib.demoteCallParticipant(view.callId, participant.userId);
881
+ };
882
+ startRingtone(callId) {
883
+ if (typeof window === 'undefined')
884
+ return;
885
+ this.callsChannel ??= typeof BroadcastChannel !== 'undefined' ? new BroadcastChannel('chatleo-calls') : undefined;
886
+ if (this.callsChannel) {
887
+ const claimed = this.callsChannel;
888
+ const handler = (event) => {
889
+ if (event.data?.type === 'ring' && event.data.callId === callId)
890
+ this.stopRingtone();
891
+ };
892
+ claimed.addEventListener('message', handler, { once: true });
893
+ claimed.postMessage({ type: 'ring', callId });
894
+ }
895
+ try {
896
+ const context = this.callRingtoneContext ?? new AudioContext();
897
+ this.callRingtoneContext = context;
898
+ const beep = () => {
899
+ const oscillator = context.createOscillator();
900
+ const gain = context.createGain();
901
+ oscillator.frequency.value = 660;
902
+ gain.gain.value = 0.04;
903
+ oscillator.connect(gain).connect(context.destination);
904
+ oscillator.start();
905
+ setTimeout(() => oscillator.stop(), 180);
906
+ };
907
+ beep();
908
+ this.callRingtoneTimer = setInterval(beep, 1200);
909
+ }
910
+ catch {
911
+ // Autoplay or WebAudio may be unavailable; the visual ringing is enough.
912
+ }
913
+ }
914
+ stopRingtone() {
915
+ if (this.callRingtoneTimer) {
916
+ clearInterval(this.callRingtoneTimer);
917
+ this.callRingtoneTimer = undefined;
918
+ }
919
+ }
920
+ async refreshPush() {
921
+ if (this.push === 'off' || !this.chatLeoLib?.pushState) {
922
+ this.pushState = null;
923
+ return;
924
+ }
925
+ try {
926
+ this.pushState = await this.chatLeoLib.pushState();
927
+ }
928
+ catch {
929
+ this.pushState = null;
930
+ }
931
+ }
932
+ async enablePush() {
933
+ if (!this.chatLeoLib?.enablePush)
934
+ return;
935
+ try {
936
+ this.pushState = await this.chatLeoLib.enablePush();
937
+ this.pushPromptDismissed = true;
938
+ }
939
+ catch (error) {
940
+ console.warn('[chatleo-component] enabling push failed', error);
941
+ await this.refreshPush();
942
+ }
943
+ }
944
+ async disablePush() {
945
+ if (!this.chatLeoLib?.disablePush)
946
+ return;
947
+ try {
948
+ this.pushState = await this.chatLeoLib.disablePush();
949
+ }
950
+ catch (error) {
951
+ console.warn('[chatleo-component] disabling push failed', error);
952
+ }
953
+ }
954
+ handleServiceWorkerMessage(event) {
955
+ if (event.data?.type === 'chatleo:pushVisibility') {
956
+ const roomId = String(event.data.roomId ?? '');
957
+ const visible = typeof document !== 'undefined' && document.visibilityState === 'visible' && this.chatStore?.activeRoomId === roomId;
958
+ event.ports?.[0]?.postMessage({ visible });
959
+ return;
960
+ }
961
+ if (event.data?.type === 'chatleo:openRoom' && event.data.roomId) {
962
+ void this.openRoom(String(event.data.roomId));
963
+ if (typeof navigator !== 'undefined' && 'clearAppBadge' in navigator) {
964
+ void navigator.clearAppBadge();
965
+ }
966
+ }
967
+ }
968
+ renderPushControl() {
969
+ if (this.push === 'off' || !this.pushState)
970
+ return null;
971
+ const state = this.pushState;
972
+ if (state.availability === 'ios_install_required') {
973
+ return index.h("div", { class: "push-control push-control--hint" }, "Add ChatLeo to your home screen to enable notifications.");
974
+ }
975
+ if (state.availability !== 'available')
976
+ return null;
977
+ if (state.permission === 'denied') {
978
+ return index.h("div", { class: "push-control push-control--hint" }, "Notifications are blocked in your browser settings.");
979
+ }
980
+ if (state.subscribed && state.accountEnabled) {
981
+ return (index.h("button", { type: "button", class: "push-control", onClick: () => void this.disablePush() }, "Notifications on"));
982
+ }
983
+ if (this.push === 'prompt' && !this.pushPromptDismissed) {
984
+ return (index.h("div", { class: "push-control push-control--prompt", role: "region", "aria-label": "Enable notifications" }, index.h("span", null, "Get notified about new messages when ChatLeo is in the background."), index.h("button", { type: "button", onClick: () => void this.enablePush() }, "Enable"), index.h("button", { type: "button", class: "push-control__secondary", onClick: () => {
985
+ this.pushPromptDismissed = true;
986
+ } }, "Not now")));
987
+ }
988
+ return (index.h("button", { type: "button", class: "push-control", onClick: () => void this.enablePush() }, "Enable notifications"));
989
+ }
990
+ identityResolver = {
991
+ resolve: (ids) => Object.fromEntries(ids.map(id => {
992
+ const user = this.chatStore?.usernameResolver(id);
993
+ return [
994
+ id,
995
+ {
996
+ displayName: user?.display_name ?? id,
997
+ avatarUrl: user?.profile_picture_url ?? undefined,
998
+ },
999
+ ];
1000
+ })),
1001
+ };
1002
+ /**
1003
+ * The call cannot go on for this user: they were removed or lost access, joined on another
1004
+ * device, the room ended, or the connection could not be restored. Close the call view.
1005
+ */
1006
+ onCallError(event) {
1007
+ const view = this.callView;
1008
+ const code = event.detail?.code;
1009
+ if (!view || !code || !['auth_rejected', 'removed', 'session_replaced', 'room_ended', 'room_full', 'network_failed'].includes(code))
1010
+ return;
1011
+ this.callView = null;
1012
+ this.showCall = false;
1013
+ // After a failure to reconnect the server still counts this device as in the call.
1014
+ if (code === 'network_failed')
1015
+ this.chatLeoLib?.leaveCall(view.callId).catch(() => undefined);
1016
+ }
1017
+ /** The user hung up in the call room: tell the server and return to the conversation. */
1018
+ onCallLeft() {
1019
+ const view = this.callView;
1020
+ if (!view)
1021
+ return;
1022
+ this.callView = null;
1023
+ this.showCall = false;
1024
+ this.chatLeoLib?.leaveCall(view.callId).catch(error => console.warn('[chatleo-component] leave failed', error));
1025
+ }
1026
+ onCallRequested(event) {
1027
+ const detail = event.detail;
1028
+ if (detail?.roomId)
1029
+ void this.startOrJoinCall(detail.roomId, detail.callId);
1030
+ }
1031
+ //
1032
+ /**
1033
+ * @function onNewChatClicked
1034
+ * @description A listener for the `newChatClicked` event. This event is handled within the tray component to open the user selector.
1035
+ * @param {CustomEvent<string>} _event - The custom event object.
1036
+ */
1037
+ onNewChatClicked(_event) {
1038
+ // handled inside tray to open selector
1039
+ }
1040
+ // from in site
1041
+ /**
1042
+ * @function onChatMessage
1043
+ * @description This listener captures the `messageChatSent` event, which is fired by child components when a user sends a message. It then calls the `sendChatMessage` method on the `chatLeoLib` to send the message to the server.
1044
+ * @param {CustomEvent<ChatMessageSent>} event - The custom event containing the message payload.
1045
+ */
1046
+ onChatMessage(event) {
1047
+ console.debug(`messageChatSent`, event);
1048
+ this.chatLeoLib?.sendChatMessage(event.detail);
1049
+ }
1050
+ /**
1051
+ * @function onUserSelectedForChat
1052
+ * @description This listener handles the `userSelected` event, which is fired when a user is selected from the new message selector. It initiates the process of starting a new direct message conversation with the selected user.
1053
+ * @param {CustomEvent<UserProfile>} event - The custom event containing the profile of the selected user.
1054
+ */
1055
+ async onUserSelectedForChat(event) {
1056
+ const user = event.detail;
1057
+ if (!user || !user.id)
1058
+ return;
1059
+ await this.internalStartDmFlow(user.id);
1060
+ }
1061
+ //
1062
+ /**
1063
+ * @function render
1064
+ * @description The render method for the `ChatLeoComponent`. It conditionally renders the `chatleo-chat` (main view), `chatleo-tray-component`, or `chatleo-room-view` based on the `useMain`, `useTray`, and `useRoomView` props.
1065
+ * @returns {any} A VNode representing the component's UI.
1066
+ */
1067
+ get _connectionBannerLabel() {
1068
+ switch (this.connectionStatus) {
1069
+ case 'connecting':
1070
+ return 'Verbindung wird hergestellt…';
1071
+ case 'reconnecting':
1072
+ return 'Verbindung wird wiederhergestellt…';
1073
+ case 'disconnected':
1074
+ return 'Offline';
1075
+ default:
1076
+ return null;
1077
+ }
1078
+ }
1079
+ render() {
1080
+ const bannerLabel = this._connectionBannerLabel;
1081
+ return (index.h("div", { key: 'd0c7c84ebf5fe164868f6e2250252a0899493ee3', style: { height: '100%', maxHeight: 'inherit', width: '100%', display: 'flex', flexDirection: 'column', position: 'relative', overflow: 'hidden', minHeight: '0' } }, this.renderPushControl(), bannerLabel && !this.isSessionExpired && (index.h("div", { key: 'd5147662da351b027aba0542ae3dc5af161d2aa3', class: `connection-banner connection-banner--${this.connectionStatus}` }, index.h("span", { key: '43cad2fcb7fd75d099fa8b73f482e7eb282c0957', class: "connection-banner__dot" }), bannerLabel)), this.useMain && index.h("chatleo-chat", { key: '609457ee0ab1ceaa2484d91d4c54d734770f4d01', ref: el => (this.chatEl = el), chatStore: this.chatStore, callsAvailable: this.callsAvailable, inCall: !!this.callView }), this.useTray && index.h("chatleo-tray-component", { key: 'ebd656fd966561d4f982859b9c36a1e233b204b6', chatStore: this.chatStore, ref: el => (this.trayEl = el) }), this.useRoomView && (index.h("chatleo-room-view", { key: '6af1a89788728c21f72ee1a31b7e70bd7d096f0f', chatStore: this.chatStore, roomId: this.roomId, isOnline: this.chatStore?.isConnected ?? false, pending: this.loading, callsAvailable: this.callsAvailable, inCall: !!this.callView })), this.callView && (index.h("div", { key: '3a346cdaf24c1fe758f86e1233cc4626db023a32', class: "call-layer", style: { display: this.showCall ? 'flex' : 'none' } }, index.h("button", { key: '7720dc641239eb8da833c63c1f30d4ed29fece7c', type: "button", class: "call-layer__back", onClick: () => {
1082
+ this.showCall = false;
1083
+ } }, "Chat"), index.h('chatleo-call-adapter', {
1084
+ ref: (el) => (this.callAdapterRef = el),
1085
+ callId: this.callView.callId,
1086
+ mode: this.callView.mode,
1087
+ connection: this.callView.credentials,
1088
+ autoJoin: true,
1089
+ identity: this.identityResolver,
1090
+ getToken: this.callToken,
1091
+ promoteHandler: this.promoteInCall,
1092
+ demoteHandler: this.demoteInCall,
1093
+ style: { flex: '1', minHeight: '0' },
1094
+ }))), this.incomingCall && (index.h("div", { key: 'ebdc317f30b07009f41f7f729b9e8631ea039752', class: "incoming-call", role: "dialog", "aria-modal": "true", "aria-label": `Incoming call from ${this.incomingCall.caller.display_name ?? this.incomingCall.caller.id}`, tabIndex: -1, ref: el => (this.incomingRef = el) }, index.h("div", { key: '4eac45f10551a47c7bf1ad8035a9da5ed2955e29', class: "incoming-call__box" }, index.h("p", { key: '6f74dee9aa261dc889b70c18e5b110e18b1a2111', class: "incoming-call__eyebrow" }, "Incoming call"), index.h("chatleo-avatar", { key: 'e097d46809d6202d64ebc1eaf42418b74c990e80', name: this.incomingCall.caller.display_name ?? this.incomingCall.caller.id, url: this.incomingCall.caller.profile_picture_url ?? null, isOnline: false }), index.h("p", { key: 'b160c0021f003d230d5fb544d82fd8d23f7df332', class: "incoming-call__name" }, this.incomingCall.caller.display_name ?? this.incomingCall.caller.id), index.h("div", { key: 'b238c1352384a0f14a2abd130fe0f3495da156f3', class: "incoming-call__actions" }, index.h("button", { key: '1b44cc1c87dfb89b4715fb370c490a05d97b6512', type: "button", class: "incoming-call__accept", onClick: () => void this.acceptIncomingCall() }, "Accept"), index.h("button", { key: '97276ec614d0be526f16573a3d0e9f6cb9e24b7c', type: "button", class: "incoming-call__decline", onClick: () => void this.declineIncomingCall() }, "Decline"))))), this.isSessionExpired && (index.h("div", { key: 'b387b49bc31378c63c6520a95bf732c47a142e88', class: "session-expired-overlay" }, index.h("div", { key: '118687b87cc612d9ad47692a3e8f2a38f3b71f32', class: "session-expired-box" }, index.h("svg", { key: '562cf50bb4f6cdd0e4076267c6dea5f8b76b06d7', class: "session-expired-icon", xmlns: "http://www.w3.org/2000/svg", width: "24", height: "24", viewBox: "0 0 24 24", fill: "none" }, index.h("path", { key: '628579c8dad4064d6fcfdfd75801160fe8f0ef8f', d: "M12 9v4M12 17h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z", stroke: "currentColor", "stroke-width": "2", "stroke-linecap": "round", "stroke-linejoin": "round" })), index.h("p", { key: 'e49e2388dad8df0e961cb7e0dc605a4011775eed', class: "session-expired-title" }, "Session abgelaufen"), index.h("p", { key: '0b69cf4687411c7e9f117712b28da57bc798ce07', class: "session-expired-message" }, "Deine Sitzung ist abgelaufen. Bitte lade die Seite neu, um fortzufahren."), index.h("button", { key: '9532b50dccc9f05dc3ee4a5ea2b28eea462a0ed1', class: "session-expired-button", onClick: () => window.location.reload() }, "Seite neu laden"))))));
1095
+ }
1096
+ static get watchers() { return {
1097
+ "chatLeoLib": [{
1098
+ "onChatLeoLibChange": 0
1099
+ }],
1100
+ "chatStore": [{
1101
+ "onChatStoreChange": 0
1102
+ }],
1103
+ "ticket": [{
1104
+ "onTicketChange": 0
1105
+ }],
1106
+ "calls": [{
1107
+ "onCallsChange": 0
1108
+ }],
1109
+ "incomingCall": [{
1110
+ "onIncomingCallChange": 0
1111
+ }]
1112
+ }; }
1113
+ };
1114
+ ChatLeoComponent.style = chatleoComponentCss();
1115
+
1116
+ const chatleoNewMessageSelectorCss = () => `:host{--input-bg:#F3F4F6;--text-placeholder:#9ca3af;--accent-shadow:rgba(59, 130, 246, 0.1);--container-padding:16px;--input-font-size:16px;--list-padding:8px;--tile-padding:12px 16px;display:block}.new-message-selector{display:flex;flex-direction:column;height:100%;max-height:70vh;background-color:var(--bg-primary);color:var(--text-secondary);box-sizing:border-box;width:100%}.title{padding:16px 16px 8px 16px;border-bottom:1px solid var(--border-color);font-weight:700;font-size:16px;color:#171A1F;display:flex;flex-direction:row;justify-content:space-between}.close-button{background:none;border:none;cursor:pointer;font-size:16px;color:var(--text-secondary)}.search-container{padding:16px;flex-shrink:0}.search-input{width:100%;border:0;font-size:14px;border-radius:var(--border-radius);outline:none;background-color:var(--input-bg);color:var(--text-secondary);padding:8px;box-sizing:border-box}.search-input:focus{border-color:var(--accent-color);}.search-input::placeholder{color:var(--text-placeholder)}.suggestions{padding:0 16px;font-size:14px}.users-list{flex:1;overflow-y:auto;}.users-list chatleo-user-tile{padding:8px 16px;display:block;--user-tile-border:none}.users-list chatleo-user-tile:hover{background-color:var(--hover-color)}chatleo-user-tile chatleo-avatar{--avatar-size:36px}`;
1117
+
1118
+ const ChatLeoNewMessageSelector = class {
1119
+ constructor(hostRef) {
1120
+ index.registerInstance(this, hostRef);
1121
+ this.userSelected = index.createEvent(this, "userSelected");
1122
+ this.doClose = index.createEvent(this, "doClose");
1123
+ }
1124
+ /**
1125
+ * An instance of the `ChatStore` class, used to access the list of users and their presence information.
1126
+ */
1127
+ chatStore;
1128
+ /**
1129
+ * The placeholder text to be displayed in the search input field.
1130
+ */
1131
+ placeholder = "Suche";
1132
+ filterText = "";
1133
+ filteredUsers = [];
1134
+ _version = 0;
1135
+ boundOnUserAdded = () => this.onUserAdded();
1136
+ boundOnPresenceChange = () => this.onPresenceChange();
1137
+ userSelected;
1138
+ doClose;
1139
+ /**
1140
+ * @function onChatStoreChange
1141
+ * @description A Stencil watcher that is called when the `chatStore` prop changes. It sets up event listeners on the new store to update the user list when users are added or their presence changes.
1142
+ * @param {ChatStore} chatStore - The new `ChatStore` instance.
1143
+ * @param {ChatStore} oldValue - The previous `ChatStore` instance.
1144
+ */
1145
+ onChatStoreChange(chatStore, oldValue) {
1146
+ this.unbindChatStore(oldValue);
1147
+ this.bindChatStore(chatStore);
1148
+ }
1149
+ connectedCallback() {
1150
+ this.bindChatStore(this.chatStore);
1151
+ }
1152
+ disconnectedCallback() {
1153
+ this.unbindChatStore(this.chatStore);
1154
+ }
1155
+ bindChatStore(chatStore) {
1156
+ if (!chatStore)
1157
+ return;
1158
+ chatStore.addEventListener('userAdded', this.boundOnUserAdded);
1159
+ chatStore.addEventListener('presenceChanged', this.boundOnPresenceChange);
1160
+ // Users are normally already in the store when the selector is opened, so seed
1161
+ // the list from the current store contents rather than waiting for `userAdded`.
1162
+ this.updateFilteredUsers();
1163
+ }
1164
+ unbindChatStore(chatStore) {
1165
+ if (!chatStore)
1166
+ return;
1167
+ chatStore.removeEventListener('userAdded', this.boundOnUserAdded);
1168
+ chatStore.removeEventListener('presenceChanged', this.boundOnPresenceChange);
1169
+ }
1170
+ /**
1171
+ * @function onUserAdded
1172
+ * @description This event handler is called when a new user is added to the `ChatStore`. It triggers an update of the filtered user list to include the new user.
1173
+ */
1174
+ onUserAdded() {
1175
+ // console.debug('User added', event);
1176
+ this.updateFilteredUsers();
1177
+ }
1178
+ /**
1179
+ * @function onPresenceChange
1180
+ * @description This event handler is called when a user's presence status changes in the `ChatStore`. It increments a version counter to trigger a re-render of the component.
1181
+ */
1182
+ onPresenceChange() {
1183
+ console.debug('onPresenceChange');
1184
+ this._version++;
1185
+ }
1186
+ /**
1187
+ * @function onDoClose
1188
+ * @description This method is called when the user clicks the close button. It prevents the default event behavior and emits the `doClose` event to notify the parent component to close the selector.
1189
+ * @param {Event} e - The click event from the close button.
1190
+ */
1191
+ onDoClose(e) {
1192
+ e.preventDefault();
1193
+ this.doClose.emit();
1194
+ }
1195
+ onFilterChange = (event) => {
1196
+ const input = event.target;
1197
+ this.filterText = input.value.toLowerCase();
1198
+ this.updateFilteredUsers();
1199
+ };
1200
+ /**
1201
+ * @function updateFilteredUsers
1202
+ * @description This method filters the list of users from the `ChatStore` based on the text entered in the search input. If the filter text is empty, it displays all users; otherwise, it shows only the users whose display name matches the filter text.
1203
+ */
1204
+ updateFilteredUsers() {
1205
+ const users = this.chatStore?.users ?? [];
1206
+ const selfId = this.chatStore?.profile?.id;
1207
+ const filterText = this.filterText;
1208
+ this.filteredUsers = users.filter(user => {
1209
+ if (user.id === selfId)
1210
+ return false;
1211
+ return !filterText || (user.display_name || '').toLowerCase().includes(filterText);
1212
+ });
1213
+ }
1214
+ onUserSelected = (event) => {
1215
+ const selectedUser = event.detail;
1216
+ if (selectedUser) {
1217
+ this.userSelected.emit(selectedUser);
1218
+ }
1219
+ };
1220
+ /**
1221
+ * @function render
1222
+ * @description The render method for the `ChatLeoNewMessageSelector` component. It constructs the UI, including the header with a close button, the search input, and the list of filtered users. Each user is rendered using the `chatleo-user-tile` component.
1223
+ * @returns {any} A VNode representing the component's UI.
1224
+ */
1225
+ render() {
1226
+ return (index.h("div", { key: 'ec5c9b8d53cce3ff5bc812dc4fc4ba3ab12bf6f8', class: "new-message-selector" }, index.h("div", { key: '62d0468365a42452ccdd3de9aad50aa79d8eb029', class: "title" }, "Neue Nachricht", index.h("button", { key: '74338599974c932922193040da99815d472d79da', class: "close-button", onClick: this.onDoClose.bind(this) }, index.h("svg", { key: 'c277fd2307e0fc618a4ea07146ac026828900cb7', width: "16", height: "16", viewBox: "0 0 16 16", fill: "none", xmlns: "http://www.w3.org/2000/svg" }, index.h("path", { key: 'a30e06e02089d91366bc5bb9a653cf15ebb2f367', d: "M12 4L4 12", stroke: "#565D6D", "stroke-width": "1.37143", "stroke-miterlimit": "10", "stroke-linecap": "square" }), index.h("path", { key: 'f2583d2faf8f1ffefe43e273f2c07cde71dd5502', d: "M12 12L4 4", stroke: "#565D6D", "stroke-width": "1.37143", "stroke-miterlimit": "10", "stroke-linecap": "square" })))), index.h("div", { key: '04983dc0b38f3f7c2bf133dfdfd8aba9a57358e4', class: "search-container" }, index.h("input", { key: '77f351f89f4c78735d1ce34ef0f925d5bea92746', type: "text", class: "search-input", placeholder: this.placeholder, value: this.filterText, onInput: this.onFilterChange })), index.h("span", { key: '26ac88fea8e9855246a74e9196bd6da4c3ea1c88', class: "suggestions" }, "Vorschl\u00E4ge"), index.h("div", { key: '58f1bfe2385d0f7ecaace341c6575135d1c84e63', class: "users-list" }, this.filteredUsers.map(user => {
1227
+ const isOnline = this.chatStore?.isOnline(user.id) ?? false;
1228
+ return (index.h("chatleo-user-tile", { key: user.id, profile: user, isOnline: isOnline, lastSeen: undefined, onUserClicked: this.onUserSelected }));
1229
+ }))));
1230
+ }
1231
+ static get watchers() { return {
1232
+ "chatStore": [{
1233
+ "onChatStoreChange": 0
1234
+ }]
1235
+ }; }
1236
+ };
1237
+ ChatLeoNewMessageSelector.style = chatleoNewMessageSelectorCss();
1238
+
1239
+ const chatleoRichInputCss = () => `:host{display:block;--rich-input-border-radius:12px;--rich-input-padding:4px;--attachment-item-radius:8px;--attachment-preview-size:60px;--min-input-height:18px;--max-input-height:120px;--transition-duration:0.2s}.rich-input-container{position:relative;background:var(--bg-primary, #ffffff);}.rich-input-container:focus-within{border-color:var(--accent-color, #4a86e8);box-shadow:0 0 0 2px rgba(74, 134, 232, 0.1)}.rich-input-container.drag-over{border-color:var(--accent-color, #4a86e8);background:var(--bg-light, #f8fafc)}.editor-area{padding:var(--rich-input-padding)}.editor-wrapper{display:flex;align-items:flex-end;gap:12px}.rich-editor{flex:1;min-height:var(--min-input-height);max-height:var(--max-input-height, 200px);overflow-y:auto;padding:12px 16px;border:none;outline:none;background:var(--bg-secondary, #f8f9fa);border-radius:20px;font-family:var(--font-primary, system-ui, sans-serif);font-size:14px;line-height:1.4;color:var(--text-primary, #212529);white-space:pre-wrap;word-wrap:break-word;resize:none;transition:background-color var(--transition-duration) ease}.rich-editor:focus{}@media (max-width: 768px){.rich-editor{font-size:16px}}.rich-editor:empty::before{content:attr(data-placeholder);color:var(--text-secondary, #6c757d);pointer-events:none}.rich-editor:focus:empty::before{content:''}.attachment-block{display:block;background:var(--bg-secondary, #f8f9fa);border:1px solid var(--border-light, #e9ecef);border-radius:var(--attachment-item-radius);padding:8px;margin:8px 0;max-width:300px;position:relative;box-sizing:border-box;user-select:none;-webkit-user-select:none}.attachment-block .attachment-content{display:flex;flex-direction:column;gap:8px;flex:1;min-width:0}.attachment-item{display:flex;align-items:center;gap:8px;position:relative;min-width:0}.attachment-block .attachment-thumbnail{width:var(--attachment-preview-size);height:var(--attachment-preview-size);object-fit:cover;border-radius:4px;flex-shrink:0}.attachment-item .attachment-thumbnail{width:var(--attachment-preview-size);height:var(--attachment-preview-size);object-fit:cover;border-radius:4px;flex-shrink:0}.attachment-block .attachment-icon{width:var(--attachment-preview-size);height:var(--attachment-preview-size);display:flex;align-items:center;justify-content:center;background:var(--bg-light, #f1f3f4);border-radius:4px;color:var(--text-secondary, #6c757d);flex-shrink:0}.attachment-item .attachment-icon{width:var(--attachment-preview-size);height:var(--attachment-preview-size);display:flex;align-items:center;justify-content:center;background:var(--bg-light, #f1f3f4);border-radius:4px;color:var(--text-secondary, #6c757d);flex-shrink:0}.attachment-block .attachment-info{flex:1;min-width:0}.attachment-item .attachment-info{flex:1;min-width:0}.attachment-block .attachment-name{font-size:12px;font-weight:500;color:var(--text-primary, #212529);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;line-height:1.3}.attachment-item .attachment-name{font-size:12px;font-weight:500;color:var(--text-primary, #212529);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;line-height:1.3}.attachment-block .attachment-size{font-size:11px;color:var(--text-secondary, #6c757d);line-height:1.2}.attachment-item .attachment-size{font-size:11px;color:var(--text-secondary, #6c757d);line-height:1.2}.attachment-block .attachment-remove{position:absolute;top:-6px;right:-6px;width:20px;height:20px;border:none;background:var(--bg-primary, #ffffff);border-radius:50%;display:flex;align-items:center;justify-content:center;cursor:pointer;box-shadow:0 2px 4px rgba(0, 0, 0, 0.1);color:var(--text-secondary, #6c757d);transition:all var(--transition-duration) ease}.attachment-item .attachment-remove{position:absolute;top:-6px;right:-6px;width:20px;height:20px;border:none;background:var(--bg-primary, #ffffff);border-radius:50%;display:flex;align-items:center;justify-content:center;cursor:pointer;box-shadow:0 2px 4px rgba(0, 0, 0, 0.1);color:var(--text-secondary, #6c757d);transition:all var(--transition-duration) ease}.attachment-block .attachment-remove:hover{background:#dc3545;color:white;transform:scale(1.1)}.attachment-item .attachment-remove:hover{background:#dc3545;color:white;transform:scale(1.1)}.rich-editor::-webkit-scrollbar{width:4px}.rich-editor::-webkit-scrollbar-track{background:transparent}.rich-editor::-webkit-scrollbar-thumb{background:var(--border-color, #dee2e6);border-radius:2px}.rich-editor::-webkit-scrollbar-thumb:hover{background:var(--text-secondary, #6c757d)}.input-actions{display:flex;flex-direction:row;align-items:flex-end;gap:2px}.action-button{width:36px;height:36px;border:none;background:transparent;border-radius:18px;cursor:pointer;display:flex;align-items:center;justify-content:center;color:var(--accent-color, #4a86e8);transition:all var(--transition-duration) ease;flex-shrink:0}.action-button:hover:not(:disabled){background:var(--bg-light, #f1f3f4);transform:scale(1.05)}.action-button:disabled{color:var(--text-secondary, #6c757d);cursor:not-allowed;opacity:0.5}.send-button:not(:disabled){color:white}.send-button:hover:not(:disabled){background:var(--accent-hover, #3d71d9)}.drag-overlay{position:absolute;top:0;left:0;right:0;bottom:0;background:rgba(74, 134, 232, 0.05);border:2px dashed var(--accent-color, #4a86e8);border-radius:var(--rich-input-border-radius);display:flex;align-items:center;justify-content:center;z-index:10}.drag-content{text-align:center;color:var(--accent-color, #4a86e8)}.drag-content svg{margin-bottom:8px}.drag-content p{margin:0;font-size:14px;font-weight:500}@media (max-width: 768px){:host{--rich-input-padding:12px;--attachment-preview-size:48px}.attachment-block{max-width:260px}.action-button{width:32px;height:32px}}`;
1240
+
1241
+ const ChatleoRichInput = class {
1242
+ constructor(hostRef) {
1243
+ index.registerInstance(this, hostRef);
1244
+ this.contentChange = index.createEvent(this, "contentChange");
1245
+ this.messageSend = index.createEvent(this, "messageSend");
1246
+ }
1247
+ get hostElement() { return index.getElement(this); }
1248
+ /**
1249
+ * If `true`, the editor and all associated buttons will be disabled, preventing user interaction.
1250
+ */
1251
+ disabled = false;
1252
+ /**
1253
+ * The placeholder text that appears in the editor when it is empty.
1254
+ */
1255
+ placeholder = 'Write a message...';
1256
+ /**
1257
+ * A CSS string that defines the maximum height of the editor area before it starts scrolling.
1258
+ */
1259
+ maxHeight = '200px';
1260
+ /**
1261
+ * A comma-separated string of MIME types or file extensions that the file input should accept. This is passed to the `accept` attribute of the hidden file input element.
1262
+ */
1263
+ acceptFiles = 'image/*,.pdf,.doc,.docx,.txt';
1264
+ isDragOver = false;
1265
+ /**
1266
+ * A state property that is `true` if the editor contains any text or attachments. It is used to enable or disable the send button.
1267
+ */
1268
+ hasContent = false;
1269
+ /** Fires whenever the legacy content snapshot changes (typing, attachments). */
1270
+ contentChange;
1271
+ /** Primary event emitted on send with structured content blocks and generated HTML. */
1272
+ messageSend;
1273
+ /** Contenteditable editor element reference. */
1274
+ editorRef;
1275
+ /** Hidden file input element reference. */
1276
+ fileInputRef;
1277
+ // --- Host API (used by the app shell for drafts, deep links and shares) ---
1278
+ /** Current plain text of the composer. */
1279
+ async getText() {
1280
+ return this.editorRef?.innerText ?? '';
1281
+ }
1282
+ /** Replaces the composer content with `text` (used to restore a draft after an update). */
1283
+ async setText(text) {
1284
+ if (!this.editorRef)
1285
+ return;
1286
+ this.editorRef.innerText = text ?? '';
1287
+ this.placeCaretAtEnd(this.editorRef);
1288
+ this.emitContentChange();
1289
+ }
1290
+ /** Adds files to the composer as attachment blocks (used by the share target). */
1291
+ async addFiles(files) {
1292
+ if (!files?.length)
1293
+ return;
1294
+ await this.handleFiles(files);
1295
+ }
1296
+ /** Focuses the editor and puts the caret at the end. */
1297
+ async focusEditor() {
1298
+ if (!this.editorRef)
1299
+ return;
1300
+ this.editorRef.focus();
1301
+ this.placeCaretAtEnd(this.editorRef);
1302
+ }
1303
+ /**
1304
+ * Generates a unique attachment id.
1305
+ * Combines timestamp and a local counter to avoid collisions.
1306
+ */
1307
+ generateAttachmentId() {
1308
+ return crypto.randomUUID();
1309
+ }
1310
+ /**
1311
+ * Returns true if the given File is an image (based on MIME type).
1312
+ */
1313
+ isImageFile(file) {
1314
+ return file.type.startsWith('image/');
1315
+ }
1316
+ /**
1317
+ * Classifies a file as 'image' | 'document' | 'other' for UI and message blocks.
1318
+ */
1319
+ // private getFileType(file: File): 'image' | 'document' | 'other' {
1320
+ // if (file.type.startsWith('image/')) return 'image';
1321
+ // if (file.type.includes('pdf') || file.type.includes('document') || file.type.includes('text')) return 'document';
1322
+ // return 'other';
1323
+ // }
1324
+ /**
1325
+ * Generates a small dataURL thumbnail for image files using Canvas.
1326
+ * Steps:
1327
+ * - Read as DataURL
1328
+ * - Load into Image
1329
+ * - Draw to canvas constrained to max size
1330
+ * - Return JPEG dataURL or undefined if not image
1331
+ */
1332
+ async generateThumbnail(file) {
1333
+ if (!this.isImageFile(file))
1334
+ return undefined;
1335
+ return new Promise(resolve => {
1336
+ const reader = new FileReader();
1337
+ reader.onload = e => {
1338
+ const img = new Image();
1339
+ img.onload = () => {
1340
+ const canvas = document.createElement('canvas');
1341
+ const ctx = canvas.getContext('2d');
1342
+ // Set thumbnail size
1343
+ const maxSize = 100;
1344
+ let { width, height } = img;
1345
+ if (width > height) {
1346
+ if (width > maxSize) {
1347
+ height = height * (maxSize / width);
1348
+ width = maxSize;
1349
+ }
1350
+ }
1351
+ else {
1352
+ if (height > maxSize) {
1353
+ width = width * (maxSize / height);
1354
+ height = maxSize;
1355
+ }
1356
+ }
1357
+ canvas.width = width;
1358
+ canvas.height = height;
1359
+ ctx?.drawImage(img, 0, 0, width, height);
1360
+ resolve(canvas.toDataURL('image/jpeg', 0.8));
1361
+ };
1362
+ img.src = e.target?.result;
1363
+ };
1364
+ reader.readAsDataURL(file);
1365
+ });
1366
+ }
1367
+ /**
1368
+ * Central file intake handler.
1369
+ * - Normalizes FileList into an array
1370
+ * - Builds FileAttachment objects and generates image previews
1371
+ * - Inserts attachments as a single "attachment-block" at the caret
1372
+ * - Emits contentChange after DOM updates
1373
+ */
1374
+ async handleFiles(files) {
1375
+ const fileArray = Array.from(files);
1376
+ // Create all attachments first
1377
+ const attachments = [];
1378
+ for (const file of fileArray) {
1379
+ const attachment = {
1380
+ mime_type: file.type,
1381
+ id: this.generateAttachmentId(),
1382
+ file,
1383
+ name: file.name,
1384
+ size: file.size,
1385
+ };
1386
+ if (attachment.mime_type.startsWith('image')) {
1387
+ attachment.preview = await this.generateThumbnail(file);
1388
+ }
1389
+ attachments.push(attachment);
1390
+ }
1391
+ // Insert all attachments as a single block if multiple files were selected
1392
+ if (attachments.length > 0) {
1393
+ this.insertAttachmentsAtCursor(attachments);
1394
+ }
1395
+ this.emitContentChange();
1396
+ }
1397
+ /**
1398
+ * Get the current selection scoped to the editor (supports ShadowRoot selection where available).
1399
+ * Returns null if the selection is not inside the editor.
1400
+ */
1401
+ getEditorSelection() {
1402
+ if (!this.editorRef)
1403
+ return null;
1404
+ const sr = this.hostElement.shadowRoot;
1405
+ const sel = sr && typeof sr.getSelection === 'function' ? sr.getSelection() : window.getSelection();
1406
+ if (!sel || sel.rangeCount === 0)
1407
+ return null;
1408
+ const anchor = sel.anchorNode;
1409
+ return anchor && this.editorRef.contains(anchor) ? sel : null;
1410
+ }
1411
+ /**
1412
+ * Place caret at the end of the editor.
1413
+ */
1414
+ placeCaretAtEnd(el) {
1415
+ const range = document.createRange();
1416
+ range.selectNodeContents(el);
1417
+ range.collapse(false);
1418
+ const sel = this.hostElement.shadowRoot?.getSelection?.() ?? window.getSelection();
1419
+ sel?.removeAllRanges();
1420
+ sel?.addRange(range);
1421
+ }
1422
+ /**
1423
+ * Inserts a non-editable "attachment-block" element at the current caret.
1424
+ * - Creates the block via createAttachmentBlock
1425
+ * - Ensures a line break before/after and moves the caret after the block
1426
+ * - Falls back to appending at the end when selection is unavailable or outside editor
1427
+ */
1428
+ insertAttachmentsAtCursor(attachments) {
1429
+ if (!this.editorRef)
1430
+ return;
1431
+ const attachmentBlock = this.createAttachmentBlock(attachments);
1432
+ // Ensure editor has focus so selection is within ShadowRoot/editor
1433
+ this.editorRef.focus();
1434
+ // Use a selection that is guaranteed to be inside the editor
1435
+ let selection = this.getEditorSelection();
1436
+ if (!selection) {
1437
+ // No valid selection inside editor; move caret to end and try again
1438
+ this.placeCaretAtEnd(this.editorRef);
1439
+ selection = this.getEditorSelection();
1440
+ }
1441
+ if (selection && selection.rangeCount > 0) {
1442
+ const range = selection.getRangeAt(0);
1443
+ // If we're in the middle of a text node, break line before inserting the block
1444
+ if (range.startContainer.nodeType === Node.TEXT_NODE && range.startOffset > 0) {
1445
+ range.setStart(range.startContainer, range.startContainer.textContent?.length || 0);
1446
+ range.collapse(true);
1447
+ const br = document.createElement('br');
1448
+ range.insertNode(br);
1449
+ range.setStartAfter(br);
1450
+ }
1451
+ // Insert the block
1452
+ range.insertNode(attachmentBlock);
1453
+ // Add a line break after and place caret after it
1454
+ const brAfter = document.createElement('br');
1455
+ range.setStartAfter(attachmentBlock);
1456
+ range.insertNode(brAfter);
1457
+ range.setStartAfter(brAfter);
1458
+ range.collapse(true);
1459
+ selection.removeAllRanges();
1460
+ selection.addRange(range);
1461
+ return;
1462
+ }
1463
+ // Fallback: append to end with a trailing line break
1464
+ if (this.editorRef.innerHTML.trim() && !this.editorRef.innerHTML.endsWith('<br>')) {
1465
+ this.editorRef.appendChild(document.createElement('br'));
1466
+ }
1467
+ this.editorRef.appendChild(attachmentBlock);
1468
+ const br = document.createElement('br');
1469
+ this.editorRef.appendChild(br);
1470
+ // Position caret after the line break
1471
+ this.placeCaretAtEnd(this.editorRef);
1472
+ }
1473
+ // private insertAttachmentAtCursor(attachment: FileAttachment) {
1474
+ // // For backward compatibility, wrap single attachment in array
1475
+ // this.insertAttachmentsAtCursor([attachment]);
1476
+ // }
1477
+ /**
1478
+ * Builds the DOM for an attachment block containing one or more attachments.
1479
+ * - Stores attachments on the element for later extraction (legacy and new)
1480
+ * - Renders thumbnails for images and generic icons for others
1481
+ * - Adds per-attachment remove buttons, delegating to removeAttachmentFromBlock
1482
+ */
1483
+ createAttachmentBlock(attachments) {
1484
+ const block = document.createElement('div');
1485
+ block.className = 'attachment-block';
1486
+ block.contentEditable = 'false';
1487
+ // Store attachment data (for backward compatibility, store first ID for single attachments)
1488
+ if (attachments.length === 1) {
1489
+ block.setAttribute('data-attachment-id', attachments[0].id);
1490
+ block._attachmentData = attachments[0]; // Legacy support
1491
+ }
1492
+ block._attachmentsData = attachments;
1493
+ const content = document.createElement('div');
1494
+ content.className = 'attachment-content';
1495
+ // Create attachment items
1496
+ attachments.forEach(attachment => {
1497
+ const attachmentItem = document.createElement('div');
1498
+ attachmentItem.className = 'attachment-item';
1499
+ // Thumbnail or icon
1500
+ if (attachment.mime_type.startsWith('image') && attachment.preview) {
1501
+ const img = document.createElement('img');
1502
+ img.src = attachment.preview;
1503
+ img.alt = attachment.name;
1504
+ img.className = 'attachment-thumbnail';
1505
+ attachmentItem.appendChild(img);
1506
+ }
1507
+ else {
1508
+ const icon = document.createElement('div');
1509
+ icon.className = 'attachment-icon';
1510
+ icon.innerHTML = `
1511
+ <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none">
1512
+ <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
1513
+ <polyline points="14,2 14,8 20,8" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
1514
+ </svg>
1515
+ `;
1516
+ attachmentItem.appendChild(icon);
1517
+ }
1518
+ // File info
1519
+ const info = document.createElement('div');
1520
+ info.className = 'attachment-info';
1521
+ const name = document.createElement('div');
1522
+ name.className = 'attachment-name';
1523
+ name.textContent = attachment.name;
1524
+ info.appendChild(name);
1525
+ const size = document.createElement('div');
1526
+ size.className = 'attachment-size';
1527
+ size.textContent = this.formatFileSize(attachment.size);
1528
+ info.appendChild(size);
1529
+ attachmentItem.appendChild(info);
1530
+ // Individual remove button for each attachment
1531
+ const removeBtn = document.createElement('button');
1532
+ removeBtn.className = 'attachment-remove';
1533
+ removeBtn.type = 'button';
1534
+ removeBtn.innerHTML = `
1535
+ <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" fill="none">
1536
+ <path d="M12 4L4 12M4 4l8 8" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
1537
+ </svg>
1538
+ `;
1539
+ removeBtn.onclick = e => {
1540
+ e.preventDefault();
1541
+ e.stopPropagation();
1542
+ this.removeAttachmentFromBlock(block, attachment.id);
1543
+ };
1544
+ attachmentItem.appendChild(removeBtn);
1545
+ content.appendChild(attachmentItem);
1546
+ });
1547
+ block.appendChild(content);
1548
+ return block;
1549
+ }
1550
+ /**
1551
+ * Removes a single attachment from the given block.
1552
+ * - If block becomes empty, removes the entire block
1553
+ * - Otherwise rebuilds the block's DOM with remaining attachments
1554
+ * - Maintains legacy single-attachment metadata for backward compatibility
1555
+ * - Emits contentChange after updates
1556
+ */
1557
+ removeAttachmentFromBlock(block, attachmentId) {
1558
+ const attachmentsData = block._attachmentsData;
1559
+ if (attachmentsData) {
1560
+ const updatedAttachments = attachmentsData.filter(att => att.id !== attachmentId);
1561
+ if (updatedAttachments.length === 0) {
1562
+ // Remove the entire block if no attachments left
1563
+ this.removeAttachmentBlock(block);
1564
+ }
1565
+ else {
1566
+ // Update the block with remaining attachments
1567
+ block._attachmentsData = updatedAttachments;
1568
+ // Update legacy data for backward compatibility
1569
+ if (updatedAttachments.length === 1) {
1570
+ block._attachmentData = updatedAttachments[0];
1571
+ block.setAttribute('data-attachment-id', updatedAttachments[0].id);
1572
+ }
1573
+ else {
1574
+ delete block._attachmentData;
1575
+ block.removeAttribute('data-attachment-id');
1576
+ }
1577
+ // Recreate the content
1578
+ const newBlock = this.createAttachmentBlock(updatedAttachments);
1579
+ block.replaceWith(newBlock);
1580
+ this.emitContentChange();
1581
+ }
1582
+ }
1583
+ }
1584
+ /**
1585
+ * Removes the entire attachment block and adjacent trailing <br> if present.
1586
+ * Emits contentChange afterward.
1587
+ */
1588
+ removeAttachmentBlock(block) {
1589
+ if (block.parentNode) {
1590
+ // Also remove any adjacent line breaks that might be empty
1591
+ const nextSibling = block.nextSibling;
1592
+ if (nextSibling && nextSibling.nodeName === 'BR') {
1593
+ nextSibling.parentNode?.removeChild(nextSibling);
1594
+ }
1595
+ block.parentNode.removeChild(block);
1596
+ this.emitContentChange();
1597
+ }
1598
+ }
1599
+ /**
1600
+ * Editor input handler that emits a legacy content snapshot.
1601
+ */
1602
+ handleInput = () => {
1603
+ this.emitContentChange();
1604
+ };
1605
+ /**
1606
+ * Extracts legacy content:
1607
+ * - Walks the editor DOM collecting plain text and attachment data
1608
+ * - Inserts textual placeholders around attachments to retain context
1609
+ * - Returns trimmed text and a flat list of FileAttachment
1610
+ */
1611
+ extractContent() {
1612
+ if (!this.editorRef) {
1613
+ return { text: '', attachments: [] };
1614
+ }
1615
+ let text = '';
1616
+ const attachments = [];
1617
+ // Walk through all child nodes and extract text and attachments
1618
+ if (!document.createTreeWalker) {
1619
+ // Fallback for environments where createTreeWalker is not available (e.g., JSDOM)
1620
+ const nodes = [];
1621
+ const walk = (node) => {
1622
+ nodes.push(node);
1623
+ node.childNodes.forEach(walk);
1624
+ };
1625
+ walk(this.editorRef);
1626
+ for (const node of nodes) {
1627
+ if (node.nodeType === Node.TEXT_NODE) {
1628
+ text += node.textContent || '';
1629
+ }
1630
+ else if (node.nodeType === Node.ELEMENT_NODE) {
1631
+ const element = node;
1632
+ if (element.classList.contains('attachment-block')) {
1633
+ const attachmentsData = element._attachmentsData;
1634
+ const attachmentData = element._attachmentData;
1635
+ if (attachmentsData) {
1636
+ attachments.push(...attachmentsData);
1637
+ }
1638
+ else if (attachmentData) {
1639
+ attachments.push(attachmentData);
1640
+ }
1641
+ text += '\n[attachment]\n';
1642
+ }
1643
+ else if (element.tagName === 'BR') {
1644
+ text += '\n';
1645
+ }
1646
+ }
1647
+ }
1648
+ }
1649
+ else {
1650
+ const walker = document.createTreeWalker(this.editorRef, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT, {
1651
+ acceptNode: node => {
1652
+ if (node.nodeType === Node.TEXT_NODE) {
1653
+ return NodeFilter.FILTER_ACCEPT;
1654
+ }
1655
+ if (node.nodeType === Node.ELEMENT_NODE) {
1656
+ const element = node;
1657
+ if (element.classList.contains('attachment-block')) {
1658
+ return NodeFilter.FILTER_ACCEPT;
1659
+ }
1660
+ if (element.tagName === 'BR') {
1661
+ return NodeFilter.FILTER_ACCEPT;
1662
+ }
1663
+ }
1664
+ return NodeFilter.FILTER_SKIP;
1665
+ },
1666
+ });
1667
+ let node;
1668
+ while ((node = walker.nextNode())) {
1669
+ if (node.nodeType === Node.TEXT_NODE) {
1670
+ text += node.textContent || '';
1671
+ }
1672
+ else if (node.nodeType === Node.ELEMENT_NODE) {
1673
+ const element = node;
1674
+ if (element.classList.contains('attachment-block')) {
1675
+ // Support both new multiple attachments and legacy single attachment
1676
+ const attachmentsData = element._attachmentsData;
1677
+ const attachmentData = element._attachmentData;
1678
+ if (attachmentsData) {
1679
+ // New multiple attachments format
1680
+ attachments.push(...attachmentsData);
1681
+ }
1682
+ else if (attachmentData) {
1683
+ // Legacy single attachment format
1684
+ attachments.push(attachmentData);
1685
+ }
1686
+ // Add a placeholder in text to maintain positioning context
1687
+ text += '\n[attachment]\n';
1688
+ }
1689
+ else if (element.tagName === 'BR') {
1690
+ text += '\n';
1691
+ }
1692
+ }
1693
+ }
1694
+ }
1695
+ return {
1696
+ text: text.trim(),
1697
+ attachments,
1698
+ };
1699
+ }
1700
+ /**
1701
+ * Generates an HTML representation from structured blocks.
1702
+ * - Escapes text content and preserves line breaks
1703
+ * - Attachment blocks include data-* metadata for downstream consumers
1704
+ */
1705
+ generateHtmlContent(blocks) {
1706
+ const htmlParts = [];
1707
+ for (const block of blocks) {
1708
+ if (block.type === 'text') {
1709
+ // Convert text content to HTML, preserving line breaks
1710
+ const textHtml = block.content.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/\n/g, '<br>');
1711
+ htmlParts.push(`<div data-block-id="${block.id}" data-block-type="text">${textHtml}</div>`);
1712
+ }
1713
+ else if (block.type === 'attachment') {
1714
+ const attachments = block.attachments;
1715
+ // Create attachment HTML with data attributes for the block
1716
+ const attachmentItems = attachments
1717
+ .map(attachment => `
1718
+ <div class="attachment-item" data-attachment-id="${attachment.id}" data-attachment-type="${attachment.mime_type}" data-attachment-name="${this.escapeHtml(attachment.name)}" data-attachment-size="${attachment.size}">
1719
+ ${attachment.mime_type?.startsWith('image') && attachment.preview
1720
+ ? `<img src="${attachment.preview}" alt="${this.escapeHtml(attachment.name)}" class="attachment-thumbnail">`
1721
+ : `<div class="attachment-icon">
1722
+ <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none">
1723
+ <path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
1724
+ <polyline points="14,2 14,8 20,8" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
1725
+ </svg>
1726
+ </div>`}
1727
+ <div class="attachment-info">
1728
+ <div class="attachment-name">${this.escapeHtml(attachment.name)}</div>
1729
+ <div class="attachment-size">${this.formatFileSize(attachment.size)}</div>
1730
+ </div>
1731
+ </div>
1732
+ `)
1733
+ .join('\n');
1734
+ const attachmentHtml = `
1735
+ <div class="attachment-block" data-block-id="${block.id}" data-block-type="attachment" data-attachment-count="${attachments.length}">
1736
+ <div class="attachment-content">
1737
+ ${attachmentItems}
1738
+ </div>
1739
+ </div>`;
1740
+ htmlParts.push(attachmentHtml.trim());
1741
+ }
1742
+ }
1743
+ return htmlParts.join('\n');
1744
+ }
1745
+ /**
1746
+ * Escapes user text for safe embedding into HTML.
1747
+ */
1748
+ escapeHtml(text) {
1749
+ return text.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;').replace(/'/g, '&#39;');
1750
+ }
1751
+ /**
1752
+ * Extracts the structured content model from the editor:
1753
+ * - Iterates top-level children to preserve block boundaries
1754
+ * - Aggregates contiguous text into TextBlock(s)
1755
+ * - Converts each attachment DOM block to an AttachmentBlock
1756
+ * - Produces parallel HTML via generateHtmlContent
1757
+ * This is the source of the primary messageSend payload.
1758
+ */
1759
+ extractStructuredContent() {
1760
+ if (!this.editorRef) {
1761
+ return { blocks: [], version: '1.0', html: '' };
1762
+ }
1763
+ const blocks = [];
1764
+ let blockIdCounter = 0;
1765
+ const children = Array.from(this.editorRef.childNodes);
1766
+ let currentTextContent = '';
1767
+ // Preserve newlines by not trimming the accumulated text
1768
+ const flushTextBlock = () => {
1769
+ if (currentTextContent.length > 0) {
1770
+ const textBlock = {
1771
+ id: `text_${++blockIdCounter}`,
1772
+ type: 'text',
1773
+ content: currentTextContent,
1774
+ };
1775
+ blocks.push(textBlock);
1776
+ currentTextContent = '';
1777
+ }
1778
+ };
1779
+ for (const child of children) {
1780
+ if (child.nodeType === Node.TEXT_NODE) {
1781
+ const textContent = child.textContent ?? '';
1782
+ if (textContent.length > 0) {
1783
+ currentTextContent += textContent;
1784
+ }
1785
+ }
1786
+ else if (child.nodeType === Node.ELEMENT_NODE) {
1787
+ const element = child;
1788
+ if (element.classList.contains('attachment-block')) {
1789
+ // Before an attachment, flush any accumulated text (including its newlines)
1790
+ flushTextBlock();
1791
+ // Support both multiple-attachment and legacy single-attachment formats
1792
+ const attachmentsData = element._attachmentsData;
1793
+ const attachmentData = element._attachmentData;
1794
+ if (attachmentsData) {
1795
+ const attachmentBlock = {
1796
+ id: `attachment_${++blockIdCounter}`,
1797
+ type: 'attachment',
1798
+ attachments: attachmentsData,
1799
+ };
1800
+ blocks.push(attachmentBlock);
1801
+ }
1802
+ else if (attachmentData) {
1803
+ const attachmentBlock = {
1804
+ id: `attachment_${++blockIdCounter}`,
1805
+ type: 'attachment',
1806
+ attachments: [attachmentData],
1807
+ };
1808
+ blocks.push(attachmentBlock);
1809
+ }
1810
+ }
1811
+ else if (element.tagName === 'BR') {
1812
+ // Explicit line break
1813
+ currentTextContent += '\n';
1814
+ }
1815
+ else {
1816
+ // Add the element's text (textContent preserves inner <br> as \n)
1817
+ const textContent = element.textContent ?? '';
1818
+ if (textContent.length > 0) {
1819
+ currentTextContent += textContent;
1820
+ }
1821
+ // If the element is block-level, ensure a newline boundary after it
1822
+ if (this.isBlockElement(element) && !currentTextContent.endsWith('\n')) {
1823
+ currentTextContent += '\n';
1824
+ }
1825
+ }
1826
+ }
1827
+ }
1828
+ // Flush any remaining text (keep trailing newlines)
1829
+ flushTextBlock();
1830
+ const html = this.generateHtmlContent(blocks);
1831
+ return {
1832
+ blocks,
1833
+ version: '1.0',
1834
+ html,
1835
+ };
1836
+ }
1837
+ /**
1838
+ * Returns true if the element is a block-level element where a visual line break is implied.
1839
+ * Used by extractStructuredContent to preserve newlines across block boundaries.
1840
+ */
1841
+ isBlockElement(el) {
1842
+ const blockTags = new Set(['DIV', 'P', 'PRE', 'LI', 'UL', 'OL', 'H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'BLOCKQUOTE']);
1843
+ return blockTags.has(el.tagName);
1844
+ }
1845
+ /**
1846
+ * Keyboard handler:
1847
+ * - Enter sends the message
1848
+ * - Shift+Enter inserts a newline (default behavior)
1849
+ */
1850
+ handleKeyDown = (e) => {
1851
+ if (e.key === 'Enter' && !e.shiftKey) {
1852
+ e.preventDefault();
1853
+ this.handleSendMessage();
1854
+ }
1855
+ };
1856
+ /**
1857
+ * Opens the hidden file input to pick files.
1858
+ */
1859
+ handleFileButtonClick = () => {
1860
+ this.fileInputRef?.click();
1861
+ };
1862
+ /**
1863
+ * Forwards files selected from the file input to handleFiles and resets the input.
1864
+ */
1865
+ handleFileInputChange = (e) => {
1866
+ const target = e.target;
1867
+ if (target.files && target.files.length > 0) {
1868
+ this.handleFiles(target.files);
1869
+ target.value = ''; // Reset input
1870
+ }
1871
+ };
1872
+ /**
1873
+ * Drag handlers to improve UX:
1874
+ * - handleDragOver/handleDragLeave toggle a visual overlay
1875
+ * - handleDrop moves the caret to the drop location and forwards files
1876
+ */
1877
+ handleDragOver = (e) => {
1878
+ e.preventDefault();
1879
+ e.stopPropagation();
1880
+ this.isDragOver = true;
1881
+ };
1882
+ handleDragLeave = (e) => {
1883
+ e.preventDefault();
1884
+ e.stopPropagation();
1885
+ this.isDragOver = false;
1886
+ };
1887
+ /**
1888
+ * Accepts dropped files:
1889
+ * - Places caret at the drop point within the editor when possible
1890
+ * - Delegates to handleFiles for processing and insertion
1891
+ */
1892
+ handleDrop = async (e) => {
1893
+ e.preventDefault();
1894
+ e.stopPropagation();
1895
+ this.isDragOver = false;
1896
+ const files = e.dataTransfer?.files;
1897
+ if (files && files.length > 0) {
1898
+ // Set cursor position to drop location if possible
1899
+ const range = document.caretRangeFromPoint(e.clientX, e.clientY);
1900
+ if (range && this.editorRef?.contains(range.startContainer)) {
1901
+ const selection = window.getSelection();
1902
+ selection?.removeAllRanges();
1903
+ selection?.addRange(range);
1904
+ }
1905
+ await this.handleFiles(files);
1906
+ }
1907
+ };
1908
+ /**
1909
+ * Sends the current message:
1910
+ * - Builds both legacy and structured payloads
1911
+ * - Emits messageSend (structured)
1912
+ * - Clears the editor if there was content
1913
+ */
1914
+ handleSendMessage = () => {
1915
+ const content = this.extractContent();
1916
+ const structuredContent = this.extractStructuredContent();
1917
+ console.debug(`handleSendMessage`, structuredContent.blocks);
1918
+ if (content.text.trim() || content.attachments.length > 0) {
1919
+ // Emit the new structured format as the primary event
1920
+ this.messageSend.emit(structuredContent);
1921
+ // Clear content after sending
1922
+ if (this.editorRef) {
1923
+ this.editorRef.innerHTML = '';
1924
+ }
1925
+ // Update state to reflect cleared content
1926
+ this.emitContentChange();
1927
+ }
1928
+ };
1929
+ /**
1930
+ * Emits a contentChange event with the current legacy content snapshot.
1931
+ * Also updates hasContent state to trigger re-render.
1932
+ */
1933
+ emitContentChange = () => {
1934
+ const content = this.extractContent();
1935
+ const has = !!(content.text.trim() || content.attachments.length > 0);
1936
+ if (this.hasContent !== has)
1937
+ this.hasContent = has;
1938
+ this.contentChange.emit(content);
1939
+ };
1940
+ /**
1941
+ * Formats a byte size into a human-readable string (Bytes, KB, MB, GB).
1942
+ */
1943
+ formatFileSize = (bytes) => {
1944
+ if (bytes === 0)
1945
+ return '0 Bytes';
1946
+ const k = 1024;
1947
+ const sizes = ['Bytes', 'KB', 'MB', 'GB'];
1948
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
1949
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
1950
+ };
1951
+ /**
1952
+ * Renders the component:
1953
+ * - Contenteditable editor with placeholder
1954
+ * - File and send action buttons
1955
+ * - Hidden file input
1956
+ * - Drag-and-drop overlay
1957
+ * The send button is disabled when there is no content or when disabled.
1958
+ */
1959
+ render() {
1960
+ // Use reactive state so typing/attachments trigger re-render
1961
+ const hasContent = this.hasContent;
1962
+ return (index.h("div", { key: '2a3b14309017d69790c17db7591a28f82f49cee4', class: `rich-input-container ${this.isDragOver ? 'drag-over' : ''}`, onDragOver: this.handleDragOver, onDragLeave: this.handleDragLeave, onDrop: this.handleDrop }, index.h("div", { key: '4a2310a460ed29c6d47dd1683f070ebbd054b73a', class: "editor-area" }, index.h("div", { key: '922433e6227fdd46fa71fdc5b05f1c508fcab423', class: "editor-wrapper" }, index.h("div", { key: '6fd7691dab9e056058a0109dfe708e6bd3236c4b', ref: el => (this.editorRef = el), class: "rich-editor", contentEditable: !this.disabled, onInput: this.handleInput, onKeyDown: this.handleKeyDown, "data-placeholder": this.placeholder, style: { maxHeight: this.maxHeight } }), index.h("div", { key: '7ef1ab99474753beafcbf08e85d55e1037b887ff', class: "input-actions" }, index.h("button", { key: '622970886800a5f602a079598d283eea9a1f0689', class: "action-button file-button", onClick: this.handleFileButtonClick, disabled: this.disabled, type: "button" }, index.h("svg", { key: '722d7fb7a68b08888039e36f58d16d39472ad229', xmlns: "http://www.w3.org/2000/svg", width: "17", height: "16", viewBox: "0 0 17 16", fill: "none" }, index.h("path", { key: 'e06306ea498415db01f587e218637594b90a8983', d: "M11.9286 3.42858L11.9286 10.5714C11.9286 12.6286 10.2714 14.2857 8.21429 14.2857C6.15714 14.2857 4.5 12.6286 4.5 10.5714L4.5 4.28572C4.5 2.85715 5.64286 1.71429 7.07143 1.71429C8.5 1.71429 9.64286 2.85715 9.64286 4.28572L9.64286 10C9.64286 10.8 9.01429 11.4286 8.21429 11.4286C7.41429 11.4286 6.78571 10.8 6.78571 10L6.78571 5.14287", stroke: "#4A86E8", "stroke-width": "1.5", "stroke-miterlimit": "10", "stroke-linecap": "square" }))), index.h("button", { key: '717f2e6f57f4b8316ffa58da639f695f4e55ca6f', class: "action-button file-button", onClick: this.handleFileButtonClick, disabled: this.disabled, type: "button" }, index.h("svg", { key: '08a5a232a719d8e4e18053d469e868aeeba1972b', xmlns: "http://www.w3.org/2000/svg", width: "33", height: "32", viewBox: "0 0 33 32", fill: "none" }, index.h("path", { key: 'c642251b6186dde4ab105f7655c212f510734693', d: "M10.5 18.5312L14.3226 14.7683C14.6047 14.4907 15.062 14.4907 15.344 14.7683L18.4444 17.8203M18.4444 17.8203L17.3611 18.8867M18.4444 17.8203L19.7393 16.5457C20.0214 16.268 20.4786 16.268 20.7607 16.5457L23.5 19.2422M11.9444 21.375H22.0556C22.8533 21.375 23.5 20.7384 23.5 19.9531V11.4219C23.5 10.6366 22.8533 10 22.0556 10H11.9444C11.1467 10 10.5 10.6366 10.5 11.4219V19.9531C10.5 20.7384 11.1467 21.375 11.9444 21.375ZM21.6944 13.1992C21.6944 13.9845 21.0477 14.6211 20.25 14.6211C19.4523 14.6211 18.8056 13.9845 18.8056 13.1992C18.8056 12.4139 19.4523 11.7773 20.25 11.7773C21.0477 11.7773 21.6944 12.4139 21.6944 13.1992Z", stroke: "#4A86E8", "stroke-width": "1.5", "stroke-linecap": "round", "stroke-linejoin": "round" }))), index.h("button", { key: 'caa33c6d18525872a4ee2d672bee04a549779499', class: "action-button send-button", onClick: this.handleSendMessage, disabled: this.disabled || !hasContent, type: "button" }, index.h("svg", { key: 'c111af09449b62afeb754eb691abdeee59c092ce', xmlns: "http://www.w3.org/2000/svg", width: "17", height: "16", viewBox: "0 0 17 16", fill: "none" }, index.h("path", { key: 'c7a9328a8abe02f7aa16dbae45574639bc94eb37', d: "M14.214 2.28564L5.64258 9.14279L5.64258 13.1428L7.69972 10.6856", stroke: "#4A86E8", "stroke-width": "1.5", "stroke-miterlimit": "10" }), index.h("path", { key: '0e141532e3694d564b8eab7240fd80a2ce172a7c', d: "M2.78613 6.85707L14.2147 2.28564L11.929 13.7142L2.78613 6.85707Z", stroke: "#4A86E8", "stroke-width": "1.5", "stroke-miterlimit": "10", "stroke-linecap": "square" })))))), index.h("input", { key: 'ed2eb79d5e731a3c324943439f5fcc8cee484e66', ref: el => (this.fileInputRef = el), type: "file", accept: this.acceptFiles, multiple: true, onChange: this.handleFileInputChange, style: { display: 'none' } }), this.isDragOver && (index.h("div", { key: '7d1deb8bc1c5cceac823ea6aa08de5c81e412e3d', class: "drag-overlay" }, index.h("div", { key: 'c27aff7a27b17eb06c4b79f25901e2db7c11be69', class: "drag-content" }, index.h("svg", { key: '13c7243782c1fb604113ec8e09a53cd44aabb1e4', xmlns: "http://www.w3.org/2000/svg", width: "48", height: "48", viewBox: "0 0 48 48", fill: "none" }, index.h("path", { key: '0ac333bcd102668edcf034e559a75cbd64e7bdd8', d: "M38 20v16a4 4 0 0 1-4 4H14a4 4 0 0 1-4-4V20M32 10L24 2l-8 8M24 2v28", stroke: "currentColor", "stroke-width": "2", "stroke-linecap": "round", "stroke-linejoin": "round" })), index.h("p", { key: '4addb3c7733503a556958fa9b46b2c520cc3bf5d' }, "Dateien hier ziehen"))))));
1963
+ }
1964
+ };
1965
+ ChatleoRichInput.style = chatleoRichInputCss();
1966
+
1967
+ const chatleoRichMessageRendererCss = () => `:host{display:block}.rich-message-content{width:100%}.rich-message-content.left{text-align:left}.rich-message-content.right{text-align:right}.rich-message-content p{margin:0.5em 0;line-height:1.4}.rich-message-content p:first-child{margin-top:0}.rich-message-content p:last-child{margin-bottom:0}.attachment-container{display:flex;gap:8px;overflow-x:auto;padding:4px 0;scrollbar-width:thin}.attachment-container::-webkit-scrollbar{height:4px}.attachment-container::-webkit-scrollbar-track{background:#f1f1f1;border-radius:2px}.attachment-container::-webkit-scrollbar-thumb{background:#c1c1c1;border-radius:2px}.attachment-container::-webkit-scrollbar-thumb:hover{background:#a8a8a8}.attachment-item{position:relative;flex-shrink:0;width:80px;height:80px;border-radius:8px;overflow:hidden;background-color:#f5f5f5;border:1px solid #e5e5e5;cursor:pointer;transition:transform 0.2s ease, box-shadow 0.2s ease}.attachment-item:hover{transform:scale(1.05);box-shadow:0 4px 8px rgba(0, 0, 0, 0.1)}.attachment-thumbnail{width:100%;height:100%;display:flex;align-items:center;justify-content:center}.attachment-thumbnail img{width:100%;height:100%;object-fit:cover;border-radius:7px}.image-container{width:100%;height:100%;display:flex;align-items:center;justify-content:center;position:relative}.loading-spinner{display:flex;align-items:center;justify-content:center;width:100%;height:100%}.spinner-circle{animation:spin 1s linear infinite;transform-origin:center;stroke-dasharray:50;stroke-dashoffset:0}@keyframes spin{0%{transform:rotate(0deg);stroke-dashoffset:0}50%{stroke-dashoffset:25}100%{transform:rotate(360deg);stroke-dashoffset:50}}.attachment-overlay{position:absolute;top:0;left:0;right:0;bottom:0;background:rgba(0, 0, 0, 0.3);display:flex;align-items:center;justify-content:center;opacity:0;transition:opacity 0.2s ease;border-radius:7px}.attachment-item:hover .attachment-overlay{opacity:1}.attachment-overlay a{display:flex;align-items:center;justify-content:center;width:32px;height:32px;background:rgba(0, 0, 0, 0.6);border-radius:50%;text-decoration:none;transition:background 0.2s ease}.attachment-overlay a:hover{background:rgba(0, 0, 0, 0.8)}.rich-message-content.right .attachment-container{justify-content:flex-end}`;
1968
+
1969
+ const ChatleoRichMessageRenderer = class {
1970
+ constructor(hostRef) {
1971
+ index.registerInstance(this, hostRef);
1972
+ }
1973
+ /**
1974
+ * The structured message content object to be rendered. This object contains an array of blocks, each of which can be a text or attachment block.
1975
+ */
1976
+ content;
1977
+ /**
1978
+ * A map where keys are attachment IDs and values are objects containing download information for those attachments, such as the download URL.
1979
+ */
1980
+ downloadUrls = {};
1981
+ /**
1982
+ * This property determines the text alignment of the message content. It can be either `'left'` or `'right'`.
1983
+ */
1984
+ alignment = 'left';
1985
+ /**
1986
+ * Optional translations overriding the default UI strings (e.g. `unsupported_content`).
1987
+ */
1988
+ translations = {};
1989
+ /**
1990
+ * State to track loading status and retry attempts for each attachment
1991
+ */
1992
+ attachmentStates = {};
1993
+ MAX_RETRIES = 3;
1994
+ INITIAL_RETRY_DELAY_MS = 1000; // 1 second
1995
+ FETCH_TIMEOUT_MS = 5000; // 5 seconds timeout for HEAD request
1996
+ /**
1997
+ * Initialize attachment state if it doesn't exist
1998
+ */
1999
+ initAttachmentState(attachmentId) {
2000
+ if (!this.attachmentStates[attachmentId]) {
2001
+ this.attachmentStates = {
2002
+ ...this.attachmentStates,
2003
+ [attachmentId]: {
2004
+ isLoading: false,
2005
+ retryCount: 0,
2006
+ hasError: false,
2007
+ }
2008
+ };
2009
+ }
2010
+ }
2011
+ /**
2012
+ * Handle image load error with retry logic
2013
+ */
2014
+ async handleImageError(attachmentId, mimeType, imgElement) {
2015
+ this.initAttachmentState(attachmentId);
2016
+ const state = this.attachmentStates[attachmentId];
2017
+ console.log("handleImageError", attachmentId, state);
2018
+ // Only retry for 404 errors and image types
2019
+ if (!mimeType.startsWith('image/') || state.retryCount >= this.MAX_RETRIES) {
2020
+ // Set error state and use placeholder
2021
+ this.attachmentStates = {
2022
+ ...this.attachmentStates,
2023
+ [attachmentId]: {
2024
+ ...state,
2025
+ isLoading: false,
2026
+ hasError: true,
2027
+ }
2028
+ };
2029
+ imgElement.src = this.getPlaceholderIcon(mimeType);
2030
+ return;
2031
+ }
2032
+ // Check if it's a 404 error by trying to fetch the image
2033
+ const downloadInfo = this.downloadUrls[attachmentId];
2034
+ if (!downloadInfo) {
2035
+ this.attachmentStates = {
2036
+ ...this.attachmentStates,
2037
+ [attachmentId]: {
2038
+ ...state,
2039
+ isLoading: false,
2040
+ hasError: true,
2041
+ }
2042
+ };
2043
+ imgElement.src = this.getPlaceholderIcon(mimeType);
2044
+ return;
2045
+ }
2046
+ try {
2047
+ // Create AbortController for timeout handling
2048
+ const abortController = new AbortController();
2049
+ const timeoutId = setTimeout(() => abortController.abort(), this.FETCH_TIMEOUT_MS);
2050
+ try {
2051
+ const response = await fetch(downloadInfo.download_url, {
2052
+ method: 'HEAD',
2053
+ signal: abortController.signal
2054
+ });
2055
+ clearTimeout(timeoutId);
2056
+ console.debug(`HEAD response`, response);
2057
+ // Only retry on 404 errors
2058
+ if (response.status === 404) {
2059
+ // Set loading state
2060
+ this.attachmentStates = {
2061
+ ...this.attachmentStates,
2062
+ [attachmentId]: {
2063
+ ...state,
2064
+ isLoading: true,
2065
+ retryCount: state.retryCount + 1,
2066
+ }
2067
+ };
2068
+ // Calculate exponential backoff delay
2069
+ const delay = this.INITIAL_RETRY_DELAY_MS * Math.pow(2, state.retryCount);
2070
+ // Wait for backoff delay and retry
2071
+ await new Promise(resolve => setTimeout(resolve, delay));
2072
+ // Retry loading the image
2073
+ this.attachmentStates = {
2074
+ ...this.attachmentStates,
2075
+ [attachmentId]: {
2076
+ ...this.attachmentStates[attachmentId],
2077
+ isLoading: false,
2078
+ }
2079
+ };
2080
+ // Force reload by appending a timestamp to prevent caching
2081
+ const url = new URL(downloadInfo.download_url);
2082
+ url.searchParams.set('retry', String(Date.now()));
2083
+ imgElement.src = url.toString();
2084
+ }
2085
+ else {
2086
+ // Not a 404, just use placeholder
2087
+ this.attachmentStates = {
2088
+ ...this.attachmentStates,
2089
+ [attachmentId]: {
2090
+ ...state,
2091
+ isLoading: false,
2092
+ hasError: true,
2093
+ }
2094
+ };
2095
+ imgElement.src = this.getPlaceholderIcon(mimeType);
2096
+ }
2097
+ }
2098
+ catch (fetchError) {
2099
+ // Clear timeout on fetch error
2100
+ clearTimeout(timeoutId);
2101
+ // Handle timeout or fetch error, use placeholder
2102
+ this.attachmentStates = {
2103
+ ...this.attachmentStates,
2104
+ [attachmentId]: {
2105
+ ...state,
2106
+ isLoading: false,
2107
+ hasError: true,
2108
+ }
2109
+ };
2110
+ imgElement.src = this.getPlaceholderIcon(mimeType);
2111
+ }
2112
+ }
2113
+ catch (error) {
2114
+ // Network error or other issue, use placeholder
2115
+ this.attachmentStates = {
2116
+ ...this.attachmentStates,
2117
+ [attachmentId]: {
2118
+ ...state,
2119
+ isLoading: false,
2120
+ hasError: true,
2121
+ }
2122
+ };
2123
+ imgElement.src = this.getPlaceholderIcon(mimeType);
2124
+ }
2125
+ }
2126
+ /**
2127
+ * Render a loading spinner
2128
+ */
2129
+ renderLoadingSpinner() {
2130
+ return (index.h("div", { class: "loading-spinner" }, index.h("svg", { width: "24", height: "24", viewBox: "0 0 24 24", xmlns: "http://www.w3.org/2000/svg" }, index.h("circle", { class: "spinner-circle", cx: "12", cy: "12", r: "10", fill: "none", stroke: "#6b7280", "stroke-width": "2" }))));
2131
+ }
2132
+ defaultTranslations = {
2133
+ unsupported_content: 'Unsupported content',
2134
+ };
2135
+ t(key) {
2136
+ return this.translations[key] || this.defaultTranslations[key] || key;
2137
+ }
2138
+ /**
2139
+ * Renders text as text nodes separated by <br/> elements. Never uses innerHTML,
2140
+ * so markup in block text is displayed literally.
2141
+ */
2142
+ renderPlainText(text) {
2143
+ const parts = text.split('\n');
2144
+ const nodes = [];
2145
+ parts.forEach((part, i) => {
2146
+ if (part)
2147
+ nodes.push(part);
2148
+ if (i < parts.length - 1)
2149
+ nodes.push(index.h("br", null));
2150
+ });
2151
+ return nodes;
2152
+ }
2153
+ renderTextBlock(block) {
2154
+ if (!block.content)
2155
+ return null;
2156
+ return index.h("p", null, this.renderPlainText(String(block.content)));
2157
+ }
2158
+ /**
2159
+ * Fallback for unknown block types: show `fallback_text` if provided, otherwise a
2160
+ * neutral notice, so a message is never rendered empty.
2161
+ */
2162
+ renderUnknownBlock(block) {
2163
+ if (typeof block?.fallback_text === 'string' && block.fallback_text.length > 0) {
2164
+ return index.h("p", null, this.renderPlainText(block.fallback_text));
2165
+ }
2166
+ return index.h("p", { class: "unsupported-content" }, this.t('unsupported_content'));
2167
+ }
2168
+ /**
2169
+ * Registry of block renderers keyed by block type.
2170
+ */
2171
+ blockRenderers = {
2172
+ text: (block) => this.renderTextBlock(block),
2173
+ attachment: (block) => this.renderAttachmentBlock(block),
2174
+ };
2175
+ generateThumbnail(attachmentId, mimeType) {
2176
+ const downloadInfo = this.downloadUrls[attachmentId];
2177
+ console.debug("generateThumbnail", { downloadUrls: this.downloadUrls, attachmentId, downloadInfo });
2178
+ if (downloadInfo && downloadInfo.mime_type.startsWith('image/')) {
2179
+ // Return the download URL for images - in a real implementation,
2180
+ // we might want to create a thumbnail endpoint or use the full image
2181
+ return downloadInfo.download_url;
2182
+ }
2183
+ // Return a placeholder for non-images or missing download info
2184
+ return this.getPlaceholderIcon(mimeType);
2185
+ }
2186
+ getPlaceholderIcon(mimeType) {
2187
+ // Return SVG data URL for different file types
2188
+ const iconColor = '#6b7280';
2189
+ if (mimeType.startsWith('image/')) {
2190
+ return `data:image/svg+xml,${encodeURIComponent(`
2191
+ <svg width="48" height="48" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
2192
+ <rect x="3" y="3" width="18" height="18" rx="2" ry="2" stroke="${iconColor}" stroke-width="2" fill="none"/>
2193
+ <circle cx="8.5" cy="8.5" r="1.5" fill="${iconColor}"/>
2194
+ <polyline points="21,15 16,10 5,21" stroke="${iconColor}" stroke-width="2" fill="none"/>
2195
+ </svg>
2196
+ `)}`;
2197
+ }
2198
+ if (mimeType.includes('pdf')) {
2199
+ return `data:image/svg+xml,${encodeURIComponent(`
2200
+ <svg width="48" height="48" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
2201
+ <path d="M14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2M18,20H6V4H13V9H18V20Z" fill="${iconColor}"/>
2202
+ </svg>
2203
+ `)}`;
2204
+ }
2205
+ // Default file icon
2206
+ return `data:image/svg+xml,${encodeURIComponent(`
2207
+ <svg width="48" height="48" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
2208
+ <path d="M14,2H6A2,2 0 0,0 4,4V20A2,2 0 0,0 6,22H18A2,2 0 0,0 20,20V8L14,2M18,20H6V4H13V9H18V20Z" stroke="${iconColor}" stroke-width="2" fill="none"/>
2209
+ <polyline points="14,2 14,8 20,8" stroke="${iconColor}" stroke-width="2" fill="none"/>
2210
+ </svg>
2211
+ `)}`;
2212
+ }
2213
+ renderAttachmentBlock(block) {
2214
+ if (!block.attachments || block.attachments.length === 0) {
2215
+ return null;
2216
+ }
2217
+ const attachmentItems = block.attachments.map((attachment) => {
2218
+ const thumbnailSrc = this.generateThumbnail(attachment.id, attachment.mime_type);
2219
+ const downloadInfo = this.downloadUrls[attachment.id];
2220
+ // Initialize state for this attachment
2221
+ this.initAttachmentState(attachment.id);
2222
+ const state = this.attachmentStates[attachment.id];
2223
+ return (index.h("div", { class: "attachment-item", key: attachment.id }, index.h("div", { class: "attachment-thumbnail" }, attachment.mime_type.startsWith('image/') ? (index.h("div", { class: "image-container" }, index.h("img", { src: thumbnailSrc, alt: "Image attachment", onError: (e) => {
2224
+ this.handleImageError(attachment.id, attachment.mime_type, e.target);
2225
+ }, style: { display: state.isLoading ? 'none' : 'block' } }), state.isLoading && this.renderLoadingSpinner())) : (index.h("img", { src: thumbnailSrc, alt: "File attachment" }))), downloadInfo && (index.h("div", { class: "attachment-overlay" }, index.h("a", { href: downloadInfo.download_url, target: "_blank", rel: "noopener noreferrer" }, index.h("svg", { width: "16", height: "16", viewBox: "0 0 24 24", fill: "none", xmlns: "http://www.w3.org/2000/svg" }, index.h("path", { d: "M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4", stroke: "white", "stroke-width": "2", "stroke-linecap": "round", "stroke-linejoin": "round" }), index.h("polyline", { points: "7,10 12,15 17,10", stroke: "white", "stroke-width": "2", "stroke-linecap": "round", "stroke-linejoin": "round" }), index.h("line", { x1: "12", y1: "15", x2: "12", y2: "3", stroke: "white", "stroke-width": "2", "stroke-linecap": "round" })))))));
2226
+ });
2227
+ return (index.h("p", null, index.h("div", { class: "attachment-container" }, attachmentItems)));
2228
+ }
2229
+ /**
2230
+ * @function render
2231
+ * @description The render method for the `ChatleoRichMessageRenderer` component. It iterates over the blocks in the `content` prop and renders each one using the appropriate rendering method (looked up in the `blockRenderers` registry, with `renderUnknownBlock` as fallback).
2232
+ * @returns {any} A VNode representing the component's UI.
2233
+ */
2234
+ render() {
2235
+ if (!this.content || !this.content.blocks) {
2236
+ return index.h("div", { class: `rich-message-content ${this.alignment}` });
2237
+ }
2238
+ const blockElements = this.content.blocks.map((block) => {
2239
+ const renderer = Object.prototype.hasOwnProperty.call(this.blockRenderers, block?.type)
2240
+ ? this.blockRenderers[block.type]
2241
+ : undefined;
2242
+ return renderer ? renderer(block) : this.renderUnknownBlock(block);
2243
+ });
2244
+ return (index.h("div", { class: `rich-message-content ${this.alignment}` }, blockElements));
2245
+ }
2246
+ };
2247
+ ChatleoRichMessageRenderer.style = chatleoRichMessageRendererCss();
2248
+
2249
+ const chatleoRoomListCss = () => `:host{--room-list-width:250px;display:flex;flex-direction:column;max-height:100%;min-height:0;overflow:hidden}.room-list-container{display:flex;flex-direction:column;flex:1;min-height:0;min-width:var(--room-list-width);overflow:hidden}.room-list-header{display:flex;align-items:center;justify-content:space-between;gap:8px;padding:12px 16px;border-bottom:1px solid var(--border-light);flex-shrink:0;font-family:var(--font-primary), sans-serif}.room-list-title{font-weight:700;font-size:16px;color:var(--text-primary, #171A1F)}.new-chat-btn{display:flex;align-items:center;justify-content:center;width:28px;height:28px;border:1px solid var(--border-light);border-radius:6px;background:transparent;cursor:pointer;padding:0;margin:0;flex:0 0 auto;color:#565D6D}.new-chat-btn:hover{color:var(--text-primary, #171A1F);background-color:var(--hover-color, #f3f4f6)}.room-list{min-width:var(--room-list-width);max-height:100%;max-width:100%;display:flex;flex-direction:column;overflow-y:auto;overflow-x:hidden;font-family:var(--font-primary), sans-serif;min-height:0;flex:1}.room-list-empty{display:flex;flex-direction:column;align-items:flex-start;gap:8px;padding:16px;font-family:var(--font-primary), sans-serif;color:var(--text-secondary, #565D6D)}.room-list-empty p{margin:0;font-size:14px}.empty-new-chat-btn{border:1px solid var(--border-light);background:transparent;color:var(--text-primary, #171A1F);border-radius:var(--border-radius, 6px);padding:6px 12px;cursor:pointer;font-size:14px}.empty-new-chat-btn:hover{background-color:var(--hover-color, #f3f4f6)}.active{background-color:var(--bg-secondary, #f0f0f0)}.room-list>*{flex-shrink:0}chatleo-new-message-selector{flex:1;min-height:0;overflow-y:auto}`;
2250
+
2251
+ const ChatleoRoomList = class {
2252
+ constructor(hostRef) {
2253
+ index.registerInstance(this, hostRef);
2254
+ }
2255
+ /**
2256
+ * An array of `ChatRoom` objects to be displayed in the list.
2257
+ */
2258
+ rooms = [];
2259
+ /**
2260
+ * An instance of the `ChatStore` class, which is used to get user presence information.
2261
+ */
2262
+ chatStore;
2263
+ /**
2264
+ * The ID of the currently selected room.
2265
+ */
2266
+ selectedRoomId;
2267
+ _version = 0;
2268
+ /** Whether the new-message user selector is shown instead of the room list. */
2269
+ isNewChatOpen = false;
2270
+ /**
2271
+ * @function onChatStoreChange
2272
+ * @description A Stencil watcher that is called when the `chatStore` prop changes. It attaches a listener to the `presenceChanged` event on the new store to trigger a re-render when a user's presence status changes.
2273
+ * @param {ChatStore} chatStore - The new `ChatStore` instance.
2274
+ * @param {ChatStore} _oldValue - The previous `ChatStore` instance.
2275
+ */
2276
+ onChatStoreChange(chatStore, _oldValue) {
2277
+ if (chatStore) {
2278
+ chatStore.addEventListener('presenceChanged', this.onPresenceChange.bind(this));
2279
+ chatStore.addEventListener('roomReadCountChanged', () => { this._version++; });
2280
+ chatStore.addEventListener('callChanged', () => { this._version++; });
2281
+ }
2282
+ }
2283
+ /**
2284
+ * @function onPresenceChange
2285
+ * @description This event handler is called when a user's presence status changes. It increments a version counter to force a re-render of the component, ensuring that the online status of users in the room list is updated.
2286
+ */
2287
+ onPresenceChange() {
2288
+ console.debug('onPresenceChange');
2289
+ this._version++;
2290
+ }
2291
+ toggleNewChat = (event) => {
2292
+ event.preventDefault();
2293
+ this.isNewChatOpen = !this.isNewChatOpen;
2294
+ };
2295
+ closeNewChat = () => {
2296
+ this.isNewChatOpen = false;
2297
+ };
2298
+ /**
2299
+ * Starting a direct message is handled by `chatleo-component`. Close the selector
2300
+ * once a user has been picked, whether or not the room opens in this view.
2301
+ */
2302
+ onUserSelected() {
2303
+ this.isNewChatOpen = false;
2304
+ }
2305
+ renderHeader() {
2306
+ return (index.h("div", { class: "room-list-header" }, index.h("span", { class: "room-list-title" }, "Nachrichten"), index.h("button", { class: "new-chat-btn", type: "button", title: "Neue Nachricht", "aria-label": "Neue Nachricht", onClick: this.toggleNewChat }, index.h("svg", { xmlns: "http://www.w3.org/2000/svg", width: "16", height: "16", viewBox: "0 0 16 16", fill: "none" }, index.h("path", { d: "M8 3V13", stroke: "currentColor", "stroke-width": "1.5", "stroke-linecap": "round" }), index.h("path", { d: "M3 8H13", stroke: "currentColor", "stroke-width": "1.5", "stroke-linecap": "round" })))));
2307
+ }
2308
+ /**
2309
+ * @function render
2310
+ * @description The render method for the `ChatleoRoomList` component. It maps over the `rooms` array and renders a `chatleo-room-tile-component` for each room, passing the necessary props. When the new-message action is active it renders the user selector instead.
2311
+ * @returns {any} A VNode representing the component's UI.
2312
+ */
2313
+ render() {
2314
+ return (index.h("div", { key: '089d5a42173af13d39cb150ff87af731239d481a', class: "room-list-container" }, this.renderHeader(), this.isNewChatOpen ? (index.h("chatleo-new-message-selector", { chatStore: this.chatStore, onDoClose: this.closeNewChat })) : (index.h("div", { class: "room-list" }, this.rooms?.map(room => {
2315
+ const online = room.participantIdsWithoutSelf?.filter((id) => this.chatStore?.isOnline(id)) ?? [];
2316
+ const isActive = this.selectedRoomId === room.id;
2317
+ return (index.h("div", { style: { padding: '6px 4px' }, class: isActive ? 'active' : '' }, index.h("chatleo-room-tile-component", { room: room, chatStore: this.chatStore, onlineUserIds: online, lastMessage: undefined, timestamp: undefined, unreadCount: room.unreadCount, isActive: isActive })));
2318
+ }), !this.rooms?.length && (index.h("div", { class: "room-list-empty" }, index.h("p", null, "Noch keine Unterhaltungen"), index.h("button", { class: "empty-new-chat-btn", type: "button", onClick: this.toggleNewChat }, "Neue Nachricht")))))));
2319
+ }
2320
+ static get watchers() { return {
2321
+ "chatStore": [{
2322
+ "onChatStoreChange": 0
2323
+ }]
2324
+ }; }
2325
+ };
2326
+ ChatleoRoomList.style = chatleoRoomListCss();
2327
+
2328
+ const chatleoRoomTileComponentCss = () => `:host{--room-name-size:16px;--timestamp-size:12px;--message-size:14px;--unread-size:12px;--room-name-weight:600;--unread-weight:600;--room-margin:4px;--room-spacing:8px;--unread-padding:2px 8px;--unread-radius:10px;--unread-min-width:20px;display:block}.room-tile{display:flex;align-items:center;cursor:pointer;transition:background-color var(--transition-duration) ease}.room-tile.active{background-color:var(--bg-secondary, #f0f0f0)}.room-content{padding-left:var(--room-spacing);flex:1;min-width:0}.room-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:var(--room-margin)}.room-name{font-size:var(--room-name-size);font-weight:var(--room-name-weight);margin:0;color:var(--text-primary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.timestamp{font-size:var(--timestamp-size);color:var(--text-secondary);flex-shrink:0;margin-left:var(--room-spacing)}.room-footer{display:flex;align-items:center;justify-content:space-between}.last-message{font-size:var(--message-size);color:var(--text-secondary);margin:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;flex:1}.read-only-badge{font-size:var(--timestamp-size);color:var(--text-secondary);flex-shrink:0;margin-left:var(--room-spacing)}.unread-count{background-color:var(--accent-color);color:white;font-size:0.7rem;line-height:1;text-align:center;display:flex;justify-content:center;align-items:center;width:1rem;height:1rem;border-radius:50%;overflow:hidden;flex-shrink:0}.call-marker{margin-left:6px;padding:1px 6px;border-radius:999px;background:#1b8a3a;color:#fff;font-size:10px;font-weight:700;text-transform:uppercase}`;
2329
+
2330
+ const ChatLeoRoomTileComponent = class {
2331
+ constructor(hostRef) {
2332
+ index.registerInstance(this, hostRef);
2333
+ this.roomClicked = index.createEvent(this, "roomClicked");
2334
+ }
2335
+ /**
2336
+ * The `ChatRoom` object containing the data for the room to be displayed.
2337
+ */
2338
+ room;
2339
+ /**
2340
+ * An instance of the `ChatStore` class, used to retrieve user information, such as avatar URLs.
2341
+ */
2342
+ chatStore;
2343
+ /**
2344
+ * An array of user IDs for the participants in the room who are currently online.
2345
+ */
2346
+ onlineUserIds;
2347
+ /**
2348
+ * The content of the last message sent in the room.
2349
+ */
2350
+ lastMessage;
2351
+ /**
2352
+ * The timestamp of the last message.
2353
+ */
2354
+ timestamp;
2355
+ /**
2356
+ * The number of unread messages in the room.
2357
+ */
2358
+ unreadCount;
2359
+ /**
2360
+ * Indicates whether this room is currently selected/active.
2361
+ */
2362
+ isActive = false;
2363
+ roomClicked;
2364
+ /**
2365
+ * @function onClick
2366
+ * @description This method is called when the room tile is clicked. It emits the `roomClicked` event with the room's ID.
2367
+ */
2368
+ onClick() {
2369
+ console.log('Room clicked', this.room.id);
2370
+ this.roomClicked.emit({ id: this.room.id });
2371
+ }
2372
+ /**
2373
+ * @function render
2374
+ * @description The render method for the `ChatLeoRoomTileComponent`. It constructs the UI for the room tile, including the avatar, room name, last message, timestamp, and unread count.
2375
+ * @returns {any} A VNode representing the component's UI.
2376
+ */
2377
+ render() {
2378
+ /* TODO: this only works for DM rooms right no */
2379
+ const isOnline = this.onlineUserIds.includes(this.room.participantIdsWithoutSelf[0]);
2380
+ const otherUserAvatarUrl = this.chatStore?.users.find(u => u.id === this.room.participantIdsWithoutSelf[0])?.profile_picture_url;
2381
+ const tileClass = this.isActive ? 'room-tile active' : 'room-tile';
2382
+ const call = this.chatStore?.activeCall(this.room.id);
2383
+ return (index.h("div", { key: '2f667c91928a5dc65554d2204372b322b0e43272', class: tileClass, onClick: () => this.onClick() }, index.h("chatleo-avatar", { key: '2b072a48103fad1cfe23a0eec2c18645572e8071', name: this.room.name, url: otherUserAvatarUrl, isOnline: isOnline }), index.h("div", { key: 'bfb0d3b61dbd0bc816b8c0c578e04c622214a3ad', class: "room-content" }, index.h("div", { key: '2ce0fda6bcd7af24a8bb823f7ba75329449239cf', class: "room-header" }, index.h("h3", { key: 'fa5ed3dd1401c147f2996bc93bed06d8f096a521', class: "room-name" }, this.room.name), index.h("span", { key: '308d082b266a01fad292839ae69c4edd0a21d1bb', class: "timestamp" }, this.timestamp ?? "")), index.h("div", { key: 'f7b3206df5b8f9870ff358f693d4600fb21302d4', class: "room-footer" }, index.h("p", { key: 'a69f70a6b237b7e0c1f5776627f7ffd3ed16685d', class: "last-message" }, call ? 'Call in progress' : (this.lastMessage ?? " ")), call && index.h("span", { key: '03e324140c78c3bce371fd14725eca835596a600', class: "call-marker", title: "Call in progress" }, "Call"), this.room.isReadOnly ? (index.h("span", { class: "read-only-badge" }, "Read only")) : (this.unreadCount > 0 && (index.h("span", { class: "unread-count" }, this.unreadCount)))))));
2384
+ }
2385
+ };
2386
+ ChatLeoRoomTileComponent.style = chatleoRoomTileComponentCss();
2387
+
2388
+ const chatleoRoomViewCss = () => `:host{display:flex;flex-direction:column;max-height:100%;min-height:0;overflow:hidden}.chat-container-chat{display:flex;flex-direction:column;height:100%;width:100%;font-family:var(--font-primary), sans-serif;min-height:0;overflow:hidden;}chatleo-chat-header{flex:0 0 auto;display:block}.chat-container-header-container{flex:0 0 auto;border-bottom:1px solid var(--border-light)}.rich-input-container-wrapper{flex:0 0 auto;padding-top:2px}.messages-container{display:block;flex:1 1 auto;min-height:0;overflow-y:auto;overflow-x:hidden;padding-right:12px;overscroll-behavior:contain;scrollbar-gutter:stable;max-width:100%;border-bottom:1px solid var(--border-light);}.message-group{display:flex;flex-direction:column;gap:16px}.date-separator{text-align:center;font-family:var(--font-primary), sans-serif;font-weight:400;font-size:12px;line-height:1.65;color:var(--text-secondary)}.call-bar{display:flex;align-items:center;justify-content:flex-end;gap:8px;padding:6px 16px;border-bottom:1px solid var(--border-light)}.call-banner{margin-right:auto;font-size:12px;color:var(--text-secondary)}.call-button{border:1px solid var(--accent-color, #4a86e8);background:transparent;color:var(--accent-color, #4a86e8);border-radius:var(--border-radius, 6px);padding:4px 10px;font:inherit;font-size:12px;cursor:pointer}.call-button:hover{background:color-mix(in srgb, var(--accent-color, #4a86e8) 10%, transparent)}`;
2389
+
2390
+ const ChatleoRoomView = class {
2391
+ constructor(hostRef) {
2392
+ index.registerInstance(this, hostRef);
2393
+ this.callRequested = index.createEvent(this, "callRequested");
2394
+ this.messageChatSent = index.createEvent(this, "messageChatSent");
2395
+ }
2396
+ /**
2397
+ * An instance of the `ChatStore` class, which manages the application's state, including rooms, messages, and user profiles.
2398
+ */
2399
+ chatStore;
2400
+ /**
2401
+ * The ID of the room to display.
2402
+ */
2403
+ roomId;
2404
+ /**
2405
+ * Indicates the current user's online status.
2406
+ */
2407
+ isOnline = false;
2408
+ /**
2409
+ * If `true`, the component will display a loading state instead of the message list.
2410
+ */
2411
+ pending = false;
2412
+ /** True when the server advertises calls and the host did not disable them. */
2413
+ callsAvailable = false;
2414
+ /** True while this client is in the room's call (keeps the banner from showing). */
2415
+ inCall = false;
2416
+ callRequested;
2417
+ _version = 0;
2418
+ // Reference to the scroll container for messages
2419
+ messagesContainerRef;
2420
+ richInputRef;
2421
+ resizeObserver;
2422
+ stickToBottom = true;
2423
+ // Track the last message count of the currently selected room to detect appends
2424
+ lastMessageCount = -1;
2425
+ // Bound event handlers for cleanup
2426
+ boundRoomAddedHandler;
2427
+ boundRoomMessageAddedHandler;
2428
+ boundRoomMessageChangedHandler;
2429
+ boundPresenceChangedHandler;
2430
+ // Scroll-back state
2431
+ loadingOlder = false;
2432
+ olderExhausted = false;
2433
+ previousScrollHeight = 0;
2434
+ previousScrollTop = 0;
2435
+ restoreScrollAfterRender = false;
2436
+ /**
2437
+ * @function onChatStoreChange
2438
+ * @description This watcher is triggered whenever the `chatStore` prop changes. It is responsible for setting up event listeners on the new store to update the component when data changes, such as when a new room is added or a message is received.
2439
+ * @param {ChatStore} newStore - The new `ChatStore` instance.
2440
+ * @param {ChatStore} oldStore - The previous `ChatStore` instance.
2441
+ */
2442
+ onChatStoreChange(newStore, oldStore) {
2443
+ console.debug('ChatleoRoomView.onChatStoreChange', newStore, oldStore);
2444
+ // Unbind old store listeners
2445
+ if (oldStore) {
2446
+ if (this.boundRoomAddedHandler) {
2447
+ oldStore.removeEventListener('roomAdded', this.boundRoomAddedHandler);
2448
+ }
2449
+ if (this.boundRoomMessageAddedHandler) {
2450
+ oldStore.removeEventListener('roomMessageAdded', this.boundRoomMessageAddedHandler);
2451
+ }
2452
+ if (this.boundRoomMessageChangedHandler) {
2453
+ oldStore.removeEventListener('roomMessageUpdated', this.boundRoomMessageChangedHandler);
2454
+ oldStore.removeEventListener('roomMessageRemoved', this.boundRoomMessageChangedHandler);
2455
+ }
2456
+ if (this.boundPresenceChangedHandler) {
2457
+ oldStore.removeEventListener('presenceChanged', this.boundPresenceChangedHandler);
2458
+ }
2459
+ }
2460
+ if (newStore) {
2461
+ // Create bound handlers
2462
+ this.boundRoomAddedHandler = (r) => {
2463
+ console.debug('roomAdded', r);
2464
+ this._version++;
2465
+ };
2466
+ this.boundRoomMessageAddedHandler = (e) => {
2467
+ console.debug('roomMessageAdded', e);
2468
+ this._version++;
2469
+ };
2470
+ this.boundRoomMessageChangedHandler = (e) => {
2471
+ console.debug('roomMessageChanged', e);
2472
+ this._version++;
2473
+ };
2474
+ this.boundPresenceChangedHandler = (e) => {
2475
+ console.debug('onPresenceChange', e);
2476
+ this._version++;
2477
+ };
2478
+ // Bind to new store
2479
+ newStore.addEventListener('roomAdded', this.boundRoomAddedHandler);
2480
+ newStore.addEventListener('roomMessageAdded', this.boundRoomMessageAddedHandler);
2481
+ newStore.addEventListener('roomMessageUpdated', this.boundRoomMessageChangedHandler);
2482
+ newStore.addEventListener('roomMessageRemoved', this.boundRoomMessageChangedHandler);
2483
+ newStore.addEventListener('presenceChanged', this.boundPresenceChangedHandler);
2484
+ if (this.roomId) {
2485
+ newStore.setActiveRoomId(this.roomId);
2486
+ newStore.markRoomAsRead(this.roomId);
2487
+ }
2488
+ }
2489
+ }
2490
+ disconnectedCallback() {
2491
+ this.resizeObserver?.disconnect();
2492
+ this.resizeObserver = undefined;
2493
+ if (this.chatStore) {
2494
+ if (this.boundRoomAddedHandler) {
2495
+ this.chatStore.removeEventListener('roomAdded', this.boundRoomAddedHandler);
2496
+ }
2497
+ if (this.boundRoomMessageAddedHandler) {
2498
+ this.chatStore.removeEventListener('roomMessageAdded', this.boundRoomMessageAddedHandler);
2499
+ }
2500
+ if (this.boundRoomMessageChangedHandler) {
2501
+ this.chatStore.removeEventListener('roomMessageUpdated', this.boundRoomMessageChangedHandler);
2502
+ this.chatStore.removeEventListener('roomMessageRemoved', this.boundRoomMessageChangedHandler);
2503
+ }
2504
+ if (this.boundPresenceChangedHandler) {
2505
+ this.chatStore.removeEventListener('presenceChanged', this.boundPresenceChangedHandler);
2506
+ }
2507
+ }
2508
+ }
2509
+ /** Reset scroll tracking when switching rooms and report the new room as active/read. */
2510
+ onRoomIdChanged() {
2511
+ this.lastMessageCount = -1;
2512
+ this.olderExhausted = false;
2513
+ this.loadingOlder = false;
2514
+ this.restoreScrollAfterRender = false;
2515
+ if (this.roomId) {
2516
+ this.chatStore?.setActiveRoomId(this.roomId);
2517
+ this.chatStore?.markRoomAsRead(this.roomId);
2518
+ }
2519
+ }
2520
+ componentDidLoad() {
2521
+ if (this.roomId) {
2522
+ this.chatStore?.setActiveRoomId(this.roomId);
2523
+ this.chatStore?.markRoomAsRead(this.roomId);
2524
+ }
2525
+ // Keep the newest message in view when the visual viewport shrinks (on-screen keyboard).
2526
+ if (typeof ResizeObserver !== 'undefined' && this.messagesContainerRef && !this.resizeObserver) {
2527
+ this.resizeObserver = new ResizeObserver(() => {
2528
+ if (this.stickToBottom)
2529
+ this.scrollToBottom();
2530
+ });
2531
+ this.resizeObserver.observe(this.messagesContainerRef);
2532
+ }
2533
+ }
2534
+ // --- Host API (used by the app shell for drafts, deep links and shares) ---
2535
+ async getDraft() {
2536
+ return (await this.richInputRef?.getText?.()) ?? '';
2537
+ }
2538
+ async setDraft(text) {
2539
+ await this.richInputRef?.setText?.(text ?? '');
2540
+ }
2541
+ async addFiles(files) {
2542
+ await this.richInputRef?.addFiles?.(files ?? []);
2543
+ }
2544
+ async focusComposer() {
2545
+ await this.richInputRef?.focusEditor?.();
2546
+ }
2547
+ messageRetryHandler(event) {
2548
+ if (this.roomId && event.detail)
2549
+ this.chatStore?.retryMessage(this.roomId, event.detail);
2550
+ }
2551
+ requestCall() {
2552
+ if (!this.roomId)
2553
+ return;
2554
+ const active = this.chatStore?.activeCall(this.roomId);
2555
+ this.callRequested.emit({ roomId: this.roomId, callId: active?.id });
2556
+ }
2557
+ messageDiscardHandler(event) {
2558
+ if (this.roomId && event.detail)
2559
+ this.chatStore?.discardMessage(this.roomId, event.detail);
2560
+ }
2561
+ messageChatSent;
2562
+ // new
2563
+ /**
2564
+ * @function messageSendHandler
2565
+ * @description This listener handles the `messageSend` event from the `chatleo-rich-input` component. It processes the rich content payload, sanitizing it by removing base64 image previews from attachments to reduce payload size. It then constructs a `ChatMessageSent` object and emits it.
2566
+ * @param {CustomEvent<any>} event - The custom event containing the structured message content.
2567
+ */
2568
+ messageSendHandler(event) {
2569
+ // Guard: don't send if roomId is not set
2570
+ if (!this.roomId) {
2571
+ console.warn('ChatleoRoomView: Cannot send message without roomId');
2572
+ return;
2573
+ }
2574
+ // Stop event propagation to prevent duplicate handling by parent components
2575
+ event.stopPropagation();
2576
+ console.log('Received the messageSend event: ', JSON.stringify(event.detail));
2577
+ // Sanitize blocks: remove preview from each attachment object
2578
+ const inputBlocks = event.detail?.blocks ?? [];
2579
+ const sanitizedBlocks = inputBlocks.map((block) => {
2580
+ if (block?.type === 'attachment' && Array.isArray(block.attachments)) {
2581
+ const sanitizedAttachments = block.attachments.map((att) => {
2582
+ const { preview, ...rest } = att ?? {};
2583
+ return rest;
2584
+ });
2585
+ return { ...block, attachments: sanitizedAttachments };
2586
+ }
2587
+ return block;
2588
+ });
2589
+ this.messageChatSent.emit({
2590
+ room_id: this.roomId,
2591
+ // TODO: change to ChatMessageSent type
2592
+ content: { blocks: sanitizedBlocks, version: event.detail.version },
2593
+ content_type: 'application/json+blocks',
2594
+ sender: this.chatStore?.profile?.id,
2595
+ });
2596
+ }
2597
+ /** Scroll helpers */
2598
+ scrollToBottom() {
2599
+ if (!this.messagesContainerRef)
2600
+ return;
2601
+ try {
2602
+ this.messagesContainerRef.scrollTop = this.messagesContainerRef.scrollHeight;
2603
+ this.stickToBottom = true;
2604
+ }
2605
+ catch (err) {
2606
+ // best-effort only
2607
+ }
2608
+ }
2609
+ scrollToBottomNextTick() {
2610
+ requestAnimationFrame(() => this.scrollToBottom());
2611
+ }
2612
+ /** Load an older page when the user scrolls near the top, keeping the viewport stable. */
2613
+ async onMessagesScroll() {
2614
+ if (!this.roomId || !this.chatStore || !this.messagesContainerRef)
2615
+ return;
2616
+ const container = this.messagesContainerRef;
2617
+ this.stickToBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - 24;
2618
+ if (this.loadingOlder || this.olderExhausted)
2619
+ return;
2620
+ if (container.scrollTop > 40)
2621
+ return;
2622
+ this.loadingOlder = true;
2623
+ this.previousScrollHeight = this.messagesContainerRef.scrollHeight;
2624
+ this.previousScrollTop = this.messagesContainerRef.scrollTop;
2625
+ const before = this.chatStore.roomMessages(this.roomId).length;
2626
+ try {
2627
+ const hasMore = await this.chatStore.loadOlderMessages(this.roomId);
2628
+ const after = this.chatStore.roomMessages(this.roomId).length;
2629
+ if (after > before)
2630
+ this.restoreScrollAfterRender = true;
2631
+ if (!hasMore && after === before)
2632
+ this.olderExhausted = true;
2633
+ }
2634
+ finally {
2635
+ this.loadingOlder = false;
2636
+ }
2637
+ }
2638
+ /** After every render, if messages for the selected room changed, scroll to bottom */
2639
+ componentDidRender() {
2640
+ if (this.pending)
2641
+ return;
2642
+ if (!this.roomId)
2643
+ return;
2644
+ const msgs = this.chatStore?.roomMessages(this.roomId) ?? [];
2645
+ const currentCount = msgs.length;
2646
+ if (this.restoreScrollAfterRender && this.messagesContainerRef) {
2647
+ const added = this.messagesContainerRef.scrollHeight - this.previousScrollHeight;
2648
+ this.messagesContainerRef.scrollTop = this.previousScrollTop + Math.max(0, added);
2649
+ this.restoreScrollAfterRender = false;
2650
+ this.lastMessageCount = currentCount;
2651
+ return;
2652
+ }
2653
+ if (currentCount !== this.lastMessageCount) {
2654
+ this.scrollToBottomNextTick();
2655
+ this.lastMessageCount = currentCount;
2656
+ }
2657
+ }
2658
+ /**
2659
+ * @function render
2660
+ * @description The render method for the `ChatleoRoomView` component. It displays the chat header, a list of messages grouped by date, and the chat input for a single room.
2661
+ * @returns {any} A VNode representing the component's UI.
2662
+ */
2663
+ render() {
2664
+ const groupedMessages = index$1.groupMessagesByDate(this.chatStore?.roomMessages(this.roomId) ?? []);
2665
+ const currentRoom = this.chatStore?.rooms.find(r => r.id === this.roomId);
2666
+ const isReadOnly = currentRoom?.isReadOnly ?? false;
2667
+ console.debug('ChatleoRoomView.render', groupedMessages);
2668
+ return (index.h("div", { key: '3eb9ef978132245f3f6d41299123021f4a32d55b', class: "chat-container-chat" }, index.h("div", { key: '6bbc3f4dbdd677fcc227550627eb939af7ec17b8', class: "chat-container-header-container" }, index.h("chatleo-chat-header", { key: '1a17709cc4e699fdb3fcd40e39bad9d8f105fef9', name: this.chatStore?.profile?.display_name, avatar: this.chatStore?.profile?.profile_picture_url ?? undefined, isOnline: this.isOnline })), this.callsAvailable && this.roomId && (index.h("div", { key: 'a9696dd64448fcee1d47ea7559dd80a7993e33d0', class: "call-bar" }, this.chatStore?.activeCall(this.roomId) && !this.inCall ? (index.h("span", { class: "call-banner" }, this.chatStore?.activeCall(this.roomId)?.mode === 'direct' ? 'Call in progress' : 'Group call in progress')) : null, index.h("button", { key: '40cf2f4c7d7d1dfd9e1ebe57a9e315e1ff884d22', type: "button", class: "call-button", onClick: () => this.requestCall() }, this.inCall
2669
+ ? 'Call running'
2670
+ : this.chatStore?.activeCall(this.roomId)
2671
+ ? 'Join call'
2672
+ : this.chatStore?.rooms.find(room => room.id === this.roomId)?.type === 'DirectMessage'
2673
+ ? 'Call'
2674
+ : 'Start call'))), this.pending ? (index.h("div", { class: "messages-container" }, index.h("div", null, "Loading chat..."))) : (index.h("div", { class: "messages-container", ref: el => (this.messagesContainerRef = el), onScroll: () => this.onMessagesScroll() }, Object.entries(groupedMessages)
2675
+ .sort(([dateA], [dateB]) => new Date(dateA).getTime() - new Date(dateB).getTime())
2676
+ .map(([date, messages]) => (index.h("div", { class: "message-group" }, index.h("div", { class: "date-separator" }, date), messages.map(message => (index.h("chatleo-chat-message", { message: message, sender: this.chatStore?.usernameResolver(message.sender_id), senderIsOnline: message.sender_id === this.chatStore?.profile.id ? this.chatStore?.isConnected : this.chatStore?.isOnline(message.sender_id), isOwnMessage: message.sender_id === this.chatStore?.profile.id, translations: { you: this.chatStore?.usernameResolver(message.sender_id)?.display_name } })))))))), !isReadOnly && (index.h("div", { key: '42592e707c67d41114596fdcf654631c2f39ee6e', class: "rich-input-container-wrapper" }, index.h("chatleo-rich-input", { key: '2a4fd69962ca7c2ac3c0ded1f5b46088855d9cea', ref: el => (this.richInputRef = el), disabled: !this.roomId, placeholder: 'Nachricht schreiben' })))));
2677
+ }
2678
+ static get watchers() { return {
2679
+ "chatStore": [{
2680
+ "onChatStoreChange": 0
2681
+ }],
2682
+ "roomId": [{
2683
+ "onRoomIdChanged": 0
2684
+ }]
2685
+ }; }
2686
+ };
2687
+ ChatleoRoomView.style = chatleoRoomViewCss();
2688
+
2689
+ const chatleoTrayComponentCss = () => `:host{--hover-color:#f9f9f9;--shadow-light:rgba(0, 0, 0, 0.1);--z-index-tray:1000;--tray-height:52px;--gap-small:12px;--gap-medium:16px;--transition-duration:0.3s;--gray-black:#171A1F;--chat-panel-width:280px;--selector-panel-width:320px;--messages-panel-width:50vw}.tray-container{position:fixed;bottom:0;right:20px;z-index:var(--z-index-tray);display:flex;flex-direction:row;align-items:flex-end;gap:var(--gap-small);font-family:var(--font-primary), sans-serif}.chat-panel{width:var(--chat-panel-width);flex:0 0 var(--chat-panel-width);box-sizing:border-box;position:relative;background:var(--bg-primary);border:1px solid var(--border-color);border-radius:var(--border-radius) var(--border-radius) 0 0;box-shadow:0 -2px 10px var(--shadow-light);overflow:hidden;max-height:var(--tray-height);transition:max-height var(--transition-duration) ease-in-out}.chat-panel.open{max-height:calc(50vh + var(--tray-height));}.tray{display:flex;flex-direction:row;align-items:center;background:var(--bg-primary);border-bottom:1px solid var(--border-light);height:var(--tray-height);box-sizing:border-box;width:100%;padding:0 8px;margin:0;}chatleo-avatar{--avatar-size:36px}.title{margin:0 8px;flex:1 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--gray-black, #171A1F);font-size:14px}.selector-panel{display:none;background:var(--bg-primary);border:1px solid var(--border-color);border-radius:var(--border-radius) var(--border-radius) 0 0;box-shadow:0 -2px 10px var(--shadow-light);box-sizing:border-box;width:var(--selector-panel-width);flex:0 0 var(--selector-panel-width);overflow:hidden;max-height:var(--tray-height);}.selector-panel.open{display:flex;flex-direction:column;max-height:calc(50vh + var(--tray-height))}.messages-panel{display:none;background:var(--bg-primary);border:1px solid var(--border-color);border-radius:var(--border-radius) var(--border-radius) 0 0;box-shadow:0 -2px 10px var(--shadow-light);box-sizing:border-box;width:var(--messages-panel-width);overflow:hidden;position:relative;max-height:70vh;flex-direction:column}.messages-panel.open{display:flex}.new-chat-btn{border:0;background:transparent;cursor:pointer;padding:0;margin:0 8px;flex:0 0 auto;color:#565D6D}.chat-tray-btn{border:0;background:transparent;cursor:pointer;padding:0;margin:0 8px;flex:0 0 auto;color:#565D6D}.chat-content{overflow:hidden}.chat-content ul{margin:0;padding:0;list-style:none;overflow-y:auto;max-height:calc(50vh - var(--tray-height));}.chat-content li{padding:16px;cursor:pointer}.chat-content li:hover{background:var(--hover-color)}@media (max-width: 768px){.chat-panel.open,.selector-panel.open{max-height:calc(80vh + 60px)}.chat-content ul{max-height:calc(80vh - 60px)}}.messages-container-header-closer{position:absolute;top:4px;right:4px}.messages-container{display:block;flex:1 1 auto;min-height:0;overflow-y:auto;overflow-x:hidden;padding-right:16px;overscroll-behavior:contain;scrollbar-gutter:stable;max-width:100%}.message-group{display:flex;flex-direction:column;gap:16px}.date-separator{text-align:center;font-family:var(--font-primary), sans-serif;font-weight:400;font-size:12px;line-height:1.65;color:var(--text-secondary)}.close-button{background:none;border:none;cursor:pointer;font-size:16px;color:var(--text-secondary)}.connection-status-banner{display:flex;align-items:center;gap:6px;padding:5px 12px;font-family:var(--font-primary), sans-serif;font-size:12px;font-weight:600;color:#fff;background:#f59e0b}.connection-status-banner--disconnected{background:#ef4444}.connection-status-banner__dot{width:6px;height:6px;border-radius:50%;background:rgba(255,255,255,0.8);flex-shrink:0;animation:tray-pulse-dot 1.4s ease-in-out infinite}.connection-status-banner--disconnected .connection-status-banner__dot{animation:none}@keyframes tray-pulse-dot{0%,100%{opacity:1}50%{opacity:0.3}}.session-expired-banner{display:flex;align-items:center;gap:6px;background:#fff8e1;border-bottom:1px solid #ffe082;padding:6px 12px;font-family:var(--font-primary), sans-serif;font-size:12px;color:#795548}.session-expired-banner-icon{flex-shrink:0;color:#f59e0b}.session-expired-banner-btn{margin-left:auto;padding:3px 10px;background:#f59e0b;color:#fff;border:none;border-radius:4px;font-family:var(--font-primary), sans-serif;font-size:12px;font-weight:600;cursor:pointer;white-space:nowrap}.session-expired-banner-btn:hover{background:#d97706}`;
2690
+
2691
+ const ChatLeoTrayComponent = class {
2692
+ constructor(hostRef) {
2693
+ index.registerInstance(this, hostRef);
2694
+ this.newChatClicked = index.createEvent(this, "newChatClicked");
2695
+ this.messageChatSent = index.createEvent(this, "messageChatSent");
2696
+ }
2697
+ /**
2698
+ * An instance of the `ChatStore` class, which provides the state for the chat application.
2699
+ */
2700
+ chatStore;
2701
+ isChatOpen = false;
2702
+ isNewChatSelectorOpen = false;
2703
+ isMessagesOpen = false;
2704
+ selectedRoomId;
2705
+ isPending = false;
2706
+ _version = 0;
2707
+ isSessionExpired = false;
2708
+ connectionStatus = 'disconnected';
2709
+ // Reference to the scroll container for messages
2710
+ messagesContainerRef;
2711
+ // Track the last message count of the currently selected room to detect appends
2712
+ lastMessageCount = -1;
2713
+ // Store bound listener references so the same function can be removed when chatStore changes
2714
+ boundOnPresenceChange = () => this.onPresenceChange();
2715
+ boundOnRoomMessageAdded = (e) => this.onRoomMessageAdded(e);
2716
+ boundOnSessionExpiredChanged = (e) => this.onSessionExpiredChanged(e);
2717
+ boundOnConnectionStatusChanged = (e) => this.onConnectionStatusChanged(e);
2718
+ boundOnRoomReadCountChanged = () => { this._version++; };
2719
+ /**
2720
+ * @function onChatStoreChange
2721
+ * @description A Stencil watcher that is called when the `chatStore` prop changes. It attaches event listeners to the new store to handle presence changes and new messages.
2722
+ * @param {ChatStore} chatStore - The new `ChatStore` instance.
2723
+ * @param {ChatStore} _oldValue - The previous `ChatStore` instance.
2724
+ */
2725
+ onChatStoreChange(chatStore, oldValue) {
2726
+ if (oldValue) {
2727
+ oldValue.removeEventListener('presenceChanged', this.boundOnPresenceChange);
2728
+ oldValue.removeEventListener('roomMessageAdded', this.boundOnRoomMessageAdded);
2729
+ oldValue.removeEventListener('sessionExpiredChanged', this.boundOnSessionExpiredChanged);
2730
+ oldValue.removeEventListener('connectionStatusChanged', this.boundOnConnectionStatusChanged);
2731
+ oldValue.removeEventListener('roomReadCountChanged', this.boundOnRoomReadCountChanged);
2732
+ }
2733
+ if (chatStore) {
2734
+ chatStore.addEventListener('presenceChanged', this.boundOnPresenceChange);
2735
+ chatStore.addEventListener('roomMessageAdded', this.boundOnRoomMessageAdded);
2736
+ chatStore.addEventListener('sessionExpiredChanged', this.boundOnSessionExpiredChanged);
2737
+ chatStore.addEventListener('connectionStatusChanged', this.boundOnConnectionStatusChanged);
2738
+ // Sync initial state
2739
+ this.isSessionExpired = chatStore.isSessionExpired;
2740
+ this.connectionStatus = chatStore.connectionStatus;
2741
+ chatStore.addEventListener('roomReadCountChanged', this.boundOnRoomReadCountChanged);
2742
+ }
2743
+ }
2744
+ /**
2745
+ * Reset message count tracking when switching rooms to force a scroll on first render
2746
+ */
2747
+ onSelectedRoomIdChanged() {
2748
+ this.lastMessageCount = -1;
2749
+ this._version++;
2750
+ this.chatStore?.setActiveRoomId(this.selectedRoomId ?? null);
2751
+ }
2752
+ /**
2753
+ * @function onPresenceChange
2754
+ * @description This event handler is called when a user's presence status changes. It increments a version counter to force a re-render of the component.
2755
+ */
2756
+ onPresenceChange() {
2757
+ console.debug('onPresenceChange');
2758
+ this._version++;
2759
+ }
2760
+ /**
2761
+ * @function onRoomMessageAdded
2762
+ * @description This event handler is called when a new message is added to a room. It increments a version counter to force a re-render and display the new message.
2763
+ * @param {CustomEvent<ChatMessageSent>} event - The custom event containing the new message.
2764
+ */
2765
+ onRoomMessageAdded(event) {
2766
+ console.debug('onRoomMessageAdded', event);
2767
+ this._version++;
2768
+ if (this.isMessagesOpen && event.detail?.roomId === this.selectedRoomId) {
2769
+ this.chatStore?.markRoomAsRead(this.selectedRoomId);
2770
+ }
2771
+ }
2772
+ onSessionExpiredChanged(event) {
2773
+ this.isSessionExpired = event.detail.isSessionExpired;
2774
+ if (this.isSessionExpired) {
2775
+ this.isChatOpen = true;
2776
+ }
2777
+ }
2778
+ onConnectionStatusChanged(event) {
2779
+ this.connectionStatus = event.detail.status;
2780
+ }
2781
+ toggleChat = () => {
2782
+ this.isChatOpen = !this.isChatOpen;
2783
+ this._version++;
2784
+ };
2785
+ newChatClicked;
2786
+ /**
2787
+ * @function onNewChatClicked
2788
+ * @description This method is called when the "new chat" button is clicked. It toggles the visibility of the new chat selector panel and emits the `newChatClicked` event.
2789
+ */
2790
+ onNewChatClicked() {
2791
+ if (this.isNewChatSelectorOpen) {
2792
+ this.isNewChatSelectorOpen = false;
2793
+ return;
2794
+ }
2795
+ this.isNewChatSelectorOpen = true;
2796
+ this.isMessagesOpen = false;
2797
+ this.newChatClicked.emit();
2798
+ }
2799
+ // callback for new message selector
2800
+ onUserSelected = () => {
2801
+ this.isNewChatSelectorOpen = false;
2802
+ };
2803
+ /* close selector from child "X" button */
2804
+ onSelectorClose = () => {
2805
+ this.isNewChatSelectorOpen = false;
2806
+ };
2807
+ /**
2808
+ * @function roomClickedHandler
2809
+ * @description This listener is triggered when a room is clicked in the room list. It opens the message panel for the selected room.
2810
+ * @param {CustomEvent<{ id: string }>} event - The custom event containing the ID of the clicked room.
2811
+ */
2812
+ roomClickedHandler(event) {
2813
+ console.log('Received the roomClicked event: ', event.detail);
2814
+ this.isNewChatSelectorOpen = false;
2815
+ this.isMessagesOpen = true;
2816
+ this.selectedRoomId = event.detail.id;
2817
+ this.chatStore?.markRoomAsRead(event.detail.id);
2818
+ }
2819
+ messageChatSent;
2820
+ /**
2821
+ * @function messageSendHandler
2822
+ * @description This listener handles the `messageSend` event from the rich input component. It sanitizes the message content and emits a `messageChatSent` event.
2823
+ * @param {CustomEvent<any>} event - The custom event containing the message content.
2824
+ */
2825
+ messageSendHandler(event) {
2826
+ console.log('Received the messageSend event: ', JSON.stringify(event.detail));
2827
+ // Sanitize blocks: remove preview from each attachment object
2828
+ const inputBlocks = event.detail?.blocks ?? [];
2829
+ const sanitizedBlocks = inputBlocks.map((block) => {
2830
+ if (block?.type === 'attachment' && Array.isArray(block.attachments)) {
2831
+ const sanitizedAttachments = block.attachments.map((att) => {
2832
+ const { preview, ...rest } = att ?? {};
2833
+ return rest;
2834
+ });
2835
+ return { ...block, attachments: sanitizedAttachments };
2836
+ }
2837
+ return block;
2838
+ });
2839
+ this.messageChatSent.emit({
2840
+ room_id: this.selectedRoomId,
2841
+ // TODO: change to ChatMessageSent type
2842
+ content: { blocks: sanitizedBlocks, version: event.detail.version },
2843
+ content_type: 'application/json+blocks',
2844
+ sender: this.chatStore?.profile?.id,
2845
+ });
2846
+ }
2847
+ /**
2848
+ * @function openChatPanel
2849
+ * @description This method programmatically opens the message panel for a specific room.
2850
+ * @param {string} roomId - The ID of the room to open.
2851
+ * @param {boolean} pending - If `true`, the panel will be opened in a pending state.
2852
+ */
2853
+ async openChatPanel(roomId, pending = false) {
2854
+ console.debug(`openChatPanel ${roomId} ${pending}`);
2855
+ this.selectedRoomId = roomId;
2856
+ this.isPending = pending;
2857
+ this.isChatOpen = false;
2858
+ this.isMessagesOpen = true;
2859
+ if (roomId)
2860
+ this.chatStore?.markRoomAsRead(roomId);
2861
+ this._version++;
2862
+ }
2863
+ /**
2864
+ * @function onDoClose
2865
+ * @description This method is called when the close button in the message panel is clicked. It closes the message panel.
2866
+ * @param {Event} e - The click event from the close button.
2867
+ */
2868
+ onDoClose(e) {
2869
+ e.preventDefault();
2870
+ this.isMessagesOpen = false;
2871
+ }
2872
+ /**
2873
+ * Scroll helpers
2874
+ */
2875
+ scrollToBottom() {
2876
+ if (!this.messagesContainerRef)
2877
+ return;
2878
+ try {
2879
+ this.messagesContainerRef.scrollTop = this.messagesContainerRef.scrollHeight;
2880
+ }
2881
+ catch (err) {
2882
+ // no-op: best-effort scrolling only
2883
+ }
2884
+ }
2885
+ scrollToBottomNextTick() {
2886
+ // Ensure DOM is painted before measuring/scrolling
2887
+ requestAnimationFrame(() => {
2888
+ this.scrollToBottom();
2889
+ });
2890
+ }
2891
+ /**
2892
+ * After every render, if messages for the selected room changed, scroll to the bottom
2893
+ */
2894
+ componentDidRender() {
2895
+ if (!this.isMessagesOpen || !this.selectedRoomId)
2896
+ return;
2897
+ const msgs = this.chatStore?.roomMessages(this.selectedRoomId) ?? [];
2898
+ const currentCount = msgs.length;
2899
+ if (currentCount !== this.lastMessageCount) {
2900
+ this.scrollToBottomNextTick();
2901
+ this.lastMessageCount = currentCount;
2902
+ }
2903
+ }
2904
+ /**
2905
+ * @function render
2906
+ * @description The render method for the `ChatLeoTrayComponent`. It renders the different panels of the tray component based on the component's state.
2907
+ * @returns {any} A VNode representing the component's UI.
2908
+ */
2909
+ render() {
2910
+ const groupedMessages = index$1.groupMessagesByDate(this.chatStore?.roomMessages(this.selectedRoomId) ?? []);
2911
+ return (index.h("div", { key: '16d13ecf2c8d78c822b66ee140fdf3aedb03d1fa', class: "tray-container" }, index.h("div", { key: '2087230f83fa231255a127bcf25935c96bb5a89d', class: this.isNewChatSelectorOpen ? 'selector-panel open' : 'selector-panel' }, index.h("chatleo-new-message-selector", { key: '346f747952e4c2d3872db97adfd9fab7434526cf', chatStore: this.chatStore, onUserSelected: this.onUserSelected, onDoClose: this.onSelectorClose })), index.h("div", { key: '245326a45ffdea0c3c8a8507a449391635576c95', class: this.isMessagesOpen ? 'messages-panel open' : 'messages-panel' }, index.h("div", { key: 'b5b82048cbee06bdb73967c2ff342d4bad66a89a', class: "messages-container-header-closer" }, index.h("button", { key: '0196b861999831d834df3407cc5c350fba9338f9', class: "close-button", onClick: this.onDoClose.bind(this) }, index.h("svg", { key: '1db85ebbbb9291ecd8674d25a063bcbe215bd6d0', width: "16", height: "16", viewBox: "0 0 16 16", fill: "none", xmlns: "http://www.w3.org/2000/svg" }, index.h("path", { key: 'd5f23bc40608fac8577860d6ff03e0e5c47e26cf', d: "M12 4L4 12", stroke: "#565D6D", "stroke-width": "1.37143", "stroke-miterlimit": "10", "stroke-linecap": "square" }), index.h("path", { key: '6f27dd8b4a9969dd19bdae6059cad74d5e466d6f', d: "M12 12L4 4", stroke: "#565D6D", "stroke-width": "1.37143", "stroke-miterlimit": "10", "stroke-linecap": "square" })))), index.h("chatleo-chat-header", { key: 'd4320c822ed8ed5e4472c91a8c03508137bb3985', name: this.chatStore?.profile?.display_name, avatar: this.chatStore?.profile?.profile_picture_url ?? 'https://placehold.co/48x48?text=AV', isOnline: this.chatStore?.isConnected }), index.h("div", { key: 'ffb54f65c17f3ecf51f661aaa2cd1777d57e2468', class: "messages-container", ref: (el) => (this.messagesContainerRef = el) }, Object.entries(groupedMessages)
2912
+ .sort(([dateA], [dateB]) => new Date(dateA).getTime() - new Date(dateB).getTime())
2913
+ .map(([date, messages]) => (index.h("div", { class: "message-group" }, index.h("div", { class: "date-separator" }, date), messages.map(message => (index.h("chatleo-chat-message", { message: message, sender: this.chatStore?.usernameResolver(message.sender_id), isOwnMessage: message.sender_id === this.chatStore?.profile.id, translations: { 'you': this.chatStore?.usernameResolver(message.sender_id)?.display_name } }))))))), index.h("chatleo-rich-input", { key: '5db7ffd32df847bbe103659d4f8ededfcc3105b2', disabled: !!!this.selectedRoomId, placeholder: "Nachricht schreiben" })), index.h("div", { key: 'a4374b9f51b6f4f528ca0099df022272d41e8062', id: "chats", class: this.isChatOpen ? 'chat-panel open' : 'chat-panel' }, this.isSessionExpired && (index.h("div", { key: '77f04c709823b47590588651b78531fa23d84254', class: "session-expired-banner" }, index.h("svg", { key: '7a9e8a3baba8576df14229384f67c4e771e4280e', class: "session-expired-banner-icon", xmlns: "http://www.w3.org/2000/svg", width: "16", height: "16", viewBox: "0 0 24 24", fill: "none" }, index.h("path", { key: 'bededb8359f4374f131f914124f89cae938c63f2', d: "M12 9v4M12 17h.01M10.29 3.86L1.82 18a2 2 0 001.71 3h16.94a2 2 0 001.71-3L13.71 3.86a2 2 0 00-3.42 0z", stroke: "currentColor", "stroke-width": "2", "stroke-linecap": "round", "stroke-linejoin": "round" })), index.h("span", { key: '49ede701a42a2c16954859e5c0443c6c94168376' }, "Session abgelaufen \u2013"), index.h("button", { key: '1533de4c91c3e496e82781e03e34d8df9cd92bf7', class: "session-expired-banner-btn", onClick: () => window.location.reload() }, "Seite neu laden"))), !this.isSessionExpired && (this.connectionStatus === 'connecting' || this.connectionStatus === 'reconnecting' || this.connectionStatus === 'disconnected') && (index.h("div", { key: '5f11759ba32e228f990b2866d09e2d25c647315c', class: `connection-status-banner connection-status-banner--${this.connectionStatus}` }, index.h("span", { key: '55ad4bf597fcf0ee3a1e180ebfac85a8c271da16', class: "connection-status-banner__dot" }), this.connectionStatus === 'connecting' ? 'Verbindung wird hergestellt…'
2914
+ : this.connectionStatus === 'reconnecting' ? 'Verbindung wird wiederhergestellt…'
2915
+ : 'Offline')), index.h("div", { key: 'c8adfe1c61695332bef014492c7abe3d641160b0', class: "tray" }, index.h("chatleo-avatar", { key: 'e5ca63cb0a77c19c75ca8404a0ec92833f9881f2', name: this.chatStore?.profile?.display_name ?? "", url: this.chatStore?.profile?.profile_picture_url, isOnline: this.chatStore?.profile?.id ? (this.chatStore?.isOnline(this.chatStore.profile.id) ?? false) : false }), index.h("div", { key: 'a7bbd2492328f400a7e349f8296f3c1a499e171e', class: "title" }, "Nachrichten"), index.h("button", { key: '7c2450e2977563c59a41efc874fc9ca5c6ecbea7', class: "new-chat-btn", onClick: () => this.onNewChatClicked() }, index.h("svg", { key: 'a7de1919583f9264c85d2f8a0879e8f993ff848c', xmlns: "http://www.w3.org/2000/svg", width: "16", height: "16", viewBox: "0 0 16 16", fill: "none" }, index.h("path", { key: '63e200bbf4038f0ceb626000b53f685318cd19f8', d: "M10.497 2.43838L12.7094 4.62657M12.9439 1.6838L13.4519 2.19178C13.9192 2.6591 13.9192 3.41677 13.4519 3.8841L6.72919 10.6068C6.59783 10.7381 6.43768 10.8371 6.26144 10.8958L3.79663 11.7174C3.56275 11.7954 3.34026 11.5729 3.41821 11.339L4.23982 8.87421C4.29857 8.69797 4.39754 8.53783 4.5289 8.40647L11.2516 1.6838C11.7189 1.21648 12.4766 1.21648 12.9439 1.6838Z", stroke: "#565D6D", "stroke-width": "1.5", "stroke-linecap": "round", "stroke-linejoin": "round" }), index.h("path", { key: '222831ec61fc41f09ba0296731aed27050ff1b55', d: "M8 2.13312H7.2H1.8C1.35817 2.13312 1 2.49129 1 2.93312V13.7331C1 14.1749 1.35817 14.5331 1.8 14.5331H12.6C13.0418 14.5331 13.4 14.1749 13.4 13.7331V8.33312V6.99998", stroke: "#565D6D", "stroke-width": "1.5", "stroke-linecap": "round" }))), index.h("button", { key: '51ce8b2bc912659e7347f9eb9bfe1a1c56b23b75', class: "chat-tray-btn", onClick: this.toggleChat }, this.isChatOpen ? (index.h("svg", { xmlns: "http://www.w3.org/2000/svg", width: "16", height: "16", viewBox: "0 0 16 16", fill: "none" }, index.h("path", { d: "M3.07273 4.66669L2 5.73941L8 11.7394L14 5.73941L12.9273 4.66669L8 9.59393L3.07273 4.66669Z", fill: "#565D6D" }))) : (index.h("svg", { xmlns: "http://www.w3.org/2000/svg", width: "16", height: "16", viewBox: "0 0 16 16", fill: "none" }, index.h("path", { d: "M12.9273 11.7393L14 10.6665L8 4.66655L2 10.6665L3.07273 11.7393L8 6.81202L12.9273 11.7393Z", fill: "#565D6D" }))))), index.h("div", { key: '9f46873326aab72ba87cfa6b387de9c5616bb497', class: "chat-content" }, index.h("ul", { key: 'f1f9da34aab6ae95a9d3910de295e1dc64f31c2c' }, this.chatStore?.rooms.map(room => {
2916
+ const online = room.participantIdsWithoutSelf?.filter((id) => this.chatStore.isOnline(id)) ?? [];
2917
+ return (index.h("li", null, index.h("chatleo-room-tile-component", { chatStore: this.chatStore, room: room, onlineUserIds: online, lastMessage: undefined, timestamp: undefined, unreadCount: room.unreadCount })));
2918
+ }))))));
2919
+ }
2920
+ static get watchers() { return {
2921
+ "chatStore": [{
2922
+ "onChatStoreChange": 0
2923
+ }],
2924
+ "selectedRoomId": [{
2925
+ "onSelectedRoomIdChanged": 0
2926
+ }]
2927
+ }; }
2928
+ };
2929
+ ChatLeoTrayComponent.style = chatleoTrayComponentCss();
2930
+
2931
+ const chatleoUserTileCss = () => `:host{--hover-color:#f5f7fa;--user-tile-border:1px solid var(--border-color);--font-size-name:16px;--font-size-status:14px;--font-weight-name:600;--tile-margin:2px;display:block}.user-tile{display:flex;align-items:center;cursor:pointer;transition:background-color var(--transition-duration) ease;border-bottom:var(--user-tile-border)}.user-tile:hover{background-color:var(--hover-color)}.user-content{flex:1;min-width:0;margin-left:8px}.user-header{margin-bottom:var(--tile-margin)}.user-name{font-size:var(--font-size-name);font-weight:var(--font-weight-name);margin:0;color:var(--text-primary);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.user-footer{display:flex;align-items:center}.user-status{font-size:var(--font-size-status);color:var(--text-secondary);margin:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}`;
2932
+
2933
+ const ChatleoUserTile = class {
2934
+ constructor(hostRef) {
2935
+ index.registerInstance(this, hostRef);
2936
+ this.userClicked = index.createEvent(this, "userClicked");
2937
+ }
2938
+ /**
2939
+ * The `UserProfile` object for the user to be displayed. This includes the user's name and avatar URL.
2940
+ */
2941
+ profile;
2942
+ /**
2943
+ * A boolean indicating whether the user is currently online.
2944
+ */
2945
+ isOnline = false;
2946
+ /**
2947
+ * A string indicating when the user was last seen online. This is displayed if the user is not currently online.
2948
+ */
2949
+ lastSeen;
2950
+ userClicked;
2951
+ /**
2952
+ * @function onClick
2953
+ * @description This method is called when the user tile is clicked. It emits the `userClicked` event with the user's profile.
2954
+ */
2955
+ onClick() {
2956
+ if (this.profile) {
2957
+ this.userClicked.emit(this.profile);
2958
+ }
2959
+ }
2960
+ /**
2961
+ * @function render
2962
+ * @description The render method for the `ChatleoUserTile` component. It constructs the UI for the user tile, including the avatar, name, and status.
2963
+ * @returns {any} A VNode representing the component's UI.
2964
+ */
2965
+ render() {
2966
+ const p = this.profile;
2967
+ const avatarUrl = (p?.profile_picture_url);
2968
+ const userName = p?.display_name ?? 'Unknown user';
2969
+ return (index.h("div", { key: 'a1e0334d626b162edba9e5bcb93472ab1d75ea8d', class: "user-tile", onClick: () => this.onClick() }, index.h("chatleo-avatar", { key: '3eed64212482962fe151dbcdb275d2396d91a39f', name: userName, url: avatarUrl, isOnline: this.isOnline }), index.h("div", { key: '9438ec481cd480b576ef18e95a9fc30003b200ea', class: "user-content" }, index.h("div", { key: '62a9cd55c2e1061c28934f419addbd3ac28b6dca', class: "user-header" }, index.h("h3", { key: 'e8f36bfd9e972193fc066b0a0de8a599180104a9', class: "user-name" }, userName)), index.h("div", { key: 'dbffef93dbe1aff1b85a73669d020df94159b014', class: "user-footer" }, index.h("p", { key: 'ee7c35805b645f520b8ef9913c282e0651770684', class: "user-status" }, this.isOnline ? 'Online' : this.lastSeen ? `Zuletzt online ${this.lastSeen}` : '')))));
2970
+ }
2971
+ };
2972
+ ChatleoUserTile.style = chatleoUserTileCss();
2973
+
2974
+ exports.chatleo_avatar = ChatleoAvatar;
2975
+ exports.chatleo_chat = ChatleoChat;
2976
+ exports.chatleo_chat_header = ChatleoChatHeader;
2977
+ exports.chatleo_chat_message = ChatleoChatMessageComponent;
2978
+ exports.chatleo_component = ChatLeoComponent;
2979
+ exports.chatleo_new_message_selector = ChatLeoNewMessageSelector;
2980
+ exports.chatleo_rich_input = ChatleoRichInput;
2981
+ exports.chatleo_rich_message_renderer = ChatleoRichMessageRenderer;
2982
+ exports.chatleo_room_list = ChatleoRoomList;
2983
+ exports.chatleo_room_tile_component = ChatLeoRoomTileComponent;
2984
+ exports.chatleo_room_view = ChatleoRoomView;
2985
+ exports.chatleo_tray_component = ChatLeoTrayComponent;
2986
+ exports.chatleo_user_tile = ChatleoUserTile;