@bbki.ng/bb-msg-history 0.14.1 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,12 +1,14 @@
1
1
  import type { AuthorOptions, Message } from './types/index.js';
2
2
  export declare class BBMsgHistory extends HTMLElement {
3
3
  private _mutationObserver?;
4
+ private _debounceTimer?;
5
+ private _eventTracker;
6
+ private _messageProcessor;
7
+ private _scrollManager;
8
+ private _renderer;
4
9
  private _userAuthors;
5
10
  private _lastAuthor;
6
11
  private _lastGroupTimestamp;
7
- private _scrollButtonVisible;
8
- private _scrollListeners;
9
- private _debounceTimer?;
10
12
  static get observedAttributes(): string[];
11
13
  constructor();
12
14
  attributeChangedCallback(name: string, oldValue: string | null, newValue: string | null): void;
@@ -48,26 +50,12 @@ export declare class BBMsgHistory extends HTMLElement {
48
50
  */
49
51
  scrollToBottom(): this;
50
52
  /**
51
- * Check if two messages can be grouped (same author, no timestamp conflict)
53
+ * Internal: Append a single message with incremental DOM update
52
54
  */
53
- private _canGroupMessages;
54
55
  private _appendSingleMessage;
55
56
  connectedCallback(): void;
56
57
  disconnectedCallback(): void;
57
- /**
58
- * Track an event listener for cleanup on disconnect
59
- */
60
- private _addTrackedListener;
61
- /**
62
- * Remove all tracked event listeners
63
- */
64
- private _cleanupListeners;
65
58
  private _setupMutationObserver;
66
59
  private render;
67
- private _renderFullStructure;
68
- private _updateContent;
69
- private _updateLoadingOverlay;
70
60
  private _setupAfterRender;
71
- private _renderEmpty;
72
- private _setupScrollTracking;
73
61
  }
package/dist/component.js CHANGED
@@ -1,21 +1,28 @@
1
- import { EMPTY_STYLES, LOADING_STYLES, MAIN_STYLES } from './const/styles.js';
2
1
  import { parseMessages } from './utils/message-parser.js';
3
- import { resolveAuthorConfig } from './utils/author-resolver.js';
4
- import { setupTooltips } from './utils/tooltip.js';
5
- import { buildMessageRowHtml, setupTooltipForElement } from './utils/message-builder.js';
6
- import { buildScrollButtonHtml } from './utils/scroll-button.js';
2
+ import { EventTracker } from './utils/event-tracker.js';
3
+ import { MessageProcessor } from './core/message-processor.js';
4
+ import { ScrollManager } from './core/scroll-manager.js';
5
+ import { Renderer } from './core/renderer.js';
7
6
  export class BBMsgHistory extends HTMLElement {
8
7
  static get observedAttributes() {
9
8
  return ['theme', 'loading', 'hide-scroll-bar', 'infinite', 'hide-scroll-button'];
10
9
  }
11
10
  constructor() {
12
11
  super();
12
+ // Core modules
13
+ this._eventTracker = new EventTracker();
14
+ this._messageProcessor = new MessageProcessor();
15
+ // State
13
16
  this._userAuthors = new Map();
14
17
  this._lastAuthor = '';
15
- this._scrollButtonVisible = false;
16
- this._scrollListeners = [];
17
18
  this.attachShadow({ mode: 'open' });
18
- // Create MutationObserver once - will be connected in connectedCallback
19
+ // Initialize renderer with shadow root
20
+ this._renderer = new Renderer(this.shadowRoot);
21
+ // Initialize scroll manager with callback
22
+ this._scrollManager = new ScrollManager(this, this.shadowRoot, this._eventTracker, _ => {
23
+ // Callback for visibility changes (state tracking if needed)
24
+ });
25
+ // Create MutationObserver for reactive rendering
19
26
  this._mutationObserver = new MutationObserver(() => {
20
27
  clearTimeout(this._debounceTimer);
21
28
  this._debounceTimer = setTimeout(() => this.render(), 50);
@@ -24,7 +31,7 @@ export class BBMsgHistory extends HTMLElement {
24
31
  attributeChangedCallback(name, oldValue, newValue) {
25
32
  if (oldValue === newValue)
26
33
  return;
27
- if (name === 'theme' || name === 'loading' || name === 'hide-scroll-bar' || name === 'infinite' || name === 'hide-scroll-button') {
34
+ if (['theme', 'loading', 'hide-scroll-bar', 'infinite', 'hide-scroll-button'].includes(name)) {
28
35
  this.render();
29
36
  }
30
37
  }
@@ -93,95 +100,28 @@ export class BBMsgHistory extends HTMLElement {
93
100
  * el.scrollToBottom(); // Scroll with smooth animation
94
101
  */
95
102
  scrollToBottom() {
96
- if (this.hasAttribute('infinite')) {
97
- return this;
98
- }
99
- const container = this.shadowRoot?.querySelector('.history');
100
- if (!container) {
101
- return this;
102
- }
103
- container.scrollTo({
104
- top: container.scrollHeight,
105
- behavior: 'smooth',
106
- });
103
+ this._scrollManager.scrollToBottom();
107
104
  return this;
108
105
  }
109
106
  /**
110
- * Check if two messages can be grouped (same author, no timestamp conflict)
107
+ * Internal: Append a single message with incremental DOM update
111
108
  */
112
- _canGroupMessages(prev, curr) {
113
- if (!prev)
114
- return false;
115
- if (prev.author !== curr.author)
116
- return false;
117
- // Different timestamps = break group
118
- if (prev.timestamp && curr.timestamp && prev.timestamp !== curr.timestamp) {
119
- return false;
120
- }
121
- return true;
122
- }
123
109
  _appendSingleMessage(message) {
124
- const container = this.shadowRoot.querySelector('.history');
125
- // If empty state or no container, do full render first
126
- if (!container) {
110
+ const result = this._renderer.appendSingleMessage(message, this._userAuthors, {
111
+ author: this._lastAuthor,
112
+ groupTimestamp: this._lastGroupTimestamp,
113
+ });
114
+ if (!result.success) {
115
+ // Container not ready, do full render
127
116
  this.render();
128
117
  return;
129
118
  }
130
- const author = message.author;
131
- const text = message.text;
132
- const timestamp = message.timestamp;
133
- const config = resolveAuthorConfig(author, this._userAuthors);
134
- // Build previous message object for grouping check
135
- const prevMessage = this._lastAuthor
136
- ? { author: this._lastAuthor, text: '', timestamp: this._lastGroupTimestamp }
137
- : null;
138
- // Use unified grouping logic
139
- const canGroupWithLast = this._canGroupMessages(prevMessage, message);
140
- const isFirstFromAuthor = !canGroupWithLast;
141
- this._lastAuthor = author;
142
- const isSubsequent = !isFirstFromAuthor;
143
- // Update group timestamp tracking (consistent with render())
144
- if (isFirstFromAuthor) {
145
- // Start new group
146
- this._lastGroupTimestamp = timestamp;
147
- }
148
- else if (!this._lastGroupTimestamp && timestamp) {
149
- // If no timestamp in group yet and current has one, use it
150
- this._lastGroupTimestamp = timestamp;
151
- }
152
- // When appending, we assume this IS the last in group (for now)
153
- // If another message from same author comes, we'll re-render
154
- const isLastInGroup = true;
155
- const groupTimestamp = this._lastGroupTimestamp;
156
- // Use utility function to build message HTML
157
- const msgHtml = buildMessageRowHtml(author, text, config, isSubsequent, groupTimestamp, isLastInGroup);
158
- // Append to container
159
- container.insertAdjacentHTML('beforeend', msgHtml);
160
- // Setup tooltip for new element using utility function
161
- const newWrapper = container.lastElementChild?.querySelector('.avatar-wrapper');
162
- if (newWrapper) {
163
- setupTooltipForElement(newWrapper);
164
- }
165
- // Smooth scroll to bottom (skip in infinite mode)
119
+ // Update state
120
+ this._lastAuthor = result.lastAuthor;
121
+ this._lastGroupTimestamp = result.lastGroupTimestamp;
122
+ // Scroll to bottom (skip in infinite mode)
166
123
  if (!this.hasAttribute('infinite')) {
167
- container.scrollTo({
168
- top: container.scrollHeight,
169
- behavior: 'smooth',
170
- });
171
- // Hide scroll button since we're scrolling to bottom
172
- if (this._scrollButtonVisible) {
173
- this._scrollButtonVisible = false;
174
- const scrollButton = this.shadowRoot.querySelector('.scroll-to-bottom');
175
- if (scrollButton) {
176
- scrollButton.classList.remove('visible');
177
- }
178
- // Dispatch hide event (always, regardless of button visibility)
179
- this.dispatchEvent(new CustomEvent('bb-scrollbuttonhide', {
180
- bubbles: true,
181
- composed: true,
182
- detail: { visible: false }
183
- }));
184
- }
124
+ this._scrollManager.scrollToBottom();
185
125
  }
186
126
  }
187
127
  connectedCallback() {
@@ -191,26 +131,9 @@ export class BBMsgHistory extends HTMLElement {
191
131
  disconnectedCallback() {
192
132
  this._mutationObserver?.disconnect();
193
133
  clearTimeout(this._debounceTimer);
194
- this._cleanupListeners();
195
- }
196
- /**
197
- * Track an event listener for cleanup on disconnect
198
- */
199
- _addTrackedListener(el, type, fn) {
200
- el.addEventListener(type, fn);
201
- this._scrollListeners.push({ el, type, fn });
202
- }
203
- /**
204
- * Remove all tracked event listeners
205
- */
206
- _cleanupListeners() {
207
- this._scrollListeners.forEach(({ el, type, fn }) => {
208
- el.removeEventListener(type, fn);
209
- });
210
- this._scrollListeners = [];
134
+ this._eventTracker.cleanup();
211
135
  }
212
136
  _setupMutationObserver() {
213
- // Observer was already created in constructor, just need to connect it
214
137
  this._mutationObserver?.observe(this, {
215
138
  childList: true,
216
139
  characterData: true,
@@ -222,185 +145,30 @@ export class BBMsgHistory extends HTMLElement {
222
145
  if (messages.length === 0) {
223
146
  this._lastAuthor = '';
224
147
  this._lastGroupTimestamp = undefined;
225
- this._renderEmpty();
148
+ this._renderer.renderEmpty(this.hasAttribute('loading'));
226
149
  return;
227
150
  }
228
- // First pass: determine which messages are last in their group
229
- const lastInGroupFlags = messages.map((msg, i) => {
230
- const next = messages[i + 1];
231
- return !next || !this._canGroupMessages(msg, next);
232
- });
233
- // Second pass: collect the timestamp for each group
234
- // Use the first non-empty timestamp in the group
235
- const groupTimestamps = new Map();
236
- let currentGroupTimestamp;
237
- messages.forEach((msg, i) => {
238
- // Start of a new group
239
- if (i === 0 || !this._canGroupMessages(messages[i - 1], msg)) {
240
- currentGroupTimestamp = msg.timestamp;
241
- }
242
- else if (!currentGroupTimestamp && msg.timestamp) {
243
- // If no timestamp yet and current msg has one, use it
244
- currentGroupTimestamp = msg.timestamp;
245
- }
246
- // If this is the last message in the group, save the timestamp
247
- if (lastInGroupFlags[i]) {
248
- groupTimestamps.set(i, currentGroupTimestamp);
249
- currentGroupTimestamp = undefined;
250
- }
251
- });
252
- // Third pass: build HTML
253
- let lastAuthor = '';
254
- const messagesHtml = messages
255
- .map((msg, i) => {
256
- const { author, text } = msg;
257
- const config = resolveAuthorConfig(author, this._userAuthors);
258
- // Determine if this is a new author group (can't group with previous)
259
- const isFirstFromAuthor = i === 0 || !this._canGroupMessages(messages[i - 1], msg);
260
- lastAuthor = author;
261
- const isSubsequent = !isFirstFromAuthor;
262
- // Get timestamp if this is the last in group
263
- const isLastInGroup = lastInGroupFlags[i];
264
- const groupTimestamp = groupTimestamps.get(i);
265
- // Use utility function to build message HTML
266
- return buildMessageRowHtml(author, text, config, isSubsequent, groupTimestamp, isLastInGroup);
267
- })
268
- .join('');
151
+ // Process messages (single-pass algorithm)
152
+ const { processed, lastAuthor, lastGroupTimestamp } = this._messageProcessor.process(messages);
153
+ // Update state
269
154
  this._lastAuthor = lastAuthor;
270
- // Check if we need to create or update the structure
271
- const historyContainer = this.shadowRoot.querySelector('.history');
272
- const needsFullSetup = !historyContainer;
273
- if (needsFullSetup) {
274
- // First render - create full structure
275
- this._renderFullStructure(messagesHtml);
276
- }
277
- else {
278
- // Update only - preserve DOM structure, just update content
279
- this._updateContent(historyContainer, messagesHtml);
280
- }
281
- }
282
- _renderFullStructure(messagesHtml) {
283
- // Check if we should preserve scroll position before re-rendering
284
- const existingContainer = this.shadowRoot.querySelector('.history');
285
- const wasAtBottom = existingContainer
286
- ? existingContainer.scrollHeight - existingContainer.scrollTop - existingContainer.clientHeight < 50
287
- : true; // Default to true for initial render
288
- const loadingOverlay = this.hasAttribute('loading')
289
- ? `<div class="loading-overlay" role="status" aria-label="Loading messages">
290
- <div class="loading-spinner"></div>
291
- </div>`
292
- : '';
155
+ this._lastGroupTimestamp = lastGroupTimestamp;
156
+ // Render messages
157
+ const isLoading = this.hasAttribute('loading');
293
158
  const hideScrollButton = this.hasAttribute('hide-scroll-button');
294
- this.shadowRoot.innerHTML = `
295
- <style>${MAIN_STYLES}${LOADING_STYLES}</style>
296
- <div class="history" role="log" aria-live="polite" aria-label="Message history">
297
- ${messagesHtml}
298
- </div>
299
- ${hideScrollButton ? '' : buildScrollButtonHtml()}
300
- ${loadingOverlay}
301
- `;
159
+ const { wasAtBottom } = this._renderer.render(processed, this._userAuthors, isLoading, hideScrollButton);
160
+ // Setup scroll tracking and other post-render tasks
302
161
  this._setupAfterRender(wasAtBottom);
303
162
  }
304
- _updateContent(historyContainer, messagesHtml) {
305
- // Preserve scroll position before update
306
- const scrollContainer = historyContainer;
307
- const wasAtBottom = scrollContainer.scrollHeight - scrollContainer.scrollTop - scrollContainer.clientHeight < 50;
308
- // Update messages content only
309
- historyContainer.innerHTML = messagesHtml;
310
- // Update loading overlay
311
- this._updateLoadingOverlay();
312
- // Restore scroll position or scroll to bottom if we were there
313
- if (wasAtBottom) {
314
- scrollContainer.scrollTop = scrollContainer.scrollHeight;
315
- }
316
- // Re-setup tooltips for new content
317
- setupTooltips(this.shadowRoot);
318
- }
319
- _updateLoadingOverlay() {
320
- const existingOverlay = this.shadowRoot.querySelector('.loading-overlay');
321
- const shouldShow = this.hasAttribute('loading');
322
- if (shouldShow && !existingOverlay) {
323
- const overlay = document.createElement('div');
324
- overlay.className = 'loading-overlay';
325
- overlay.setAttribute('role', 'status');
326
- overlay.setAttribute('aria-label', 'Loading messages');
327
- overlay.innerHTML = '<div class="loading-spinner"></div>';
328
- this.shadowRoot.appendChild(overlay);
329
- }
330
- else if (!shouldShow && existingOverlay) {
331
- existingOverlay.remove();
332
- }
333
- }
334
163
  _setupAfterRender(shouldScrollToBottom = true) {
335
164
  requestAnimationFrame(() => {
336
- const container = this.shadowRoot.querySelector('.history');
337
- const scrollButton = this.shadowRoot.querySelector('.scroll-to-bottom');
165
+ const container = this._renderer.getHistoryContainer();
166
+ const scrollButton = this._renderer.getScrollButton();
338
167
  const isInfinite = this.hasAttribute('infinite');
339
168
  if (container && !isInfinite) {
340
- if (shouldScrollToBottom) {
341
- container.scrollTop = container.scrollHeight;
342
- }
343
- this._setupScrollTracking(container, scrollButton, { skipInitialCheck: true });
344
- }
345
- if (scrollButton && !isInfinite) {
346
- scrollButton.addEventListener('click', () => {
347
- container?.scrollTo({
348
- top: container.scrollHeight,
349
- behavior: 'smooth',
350
- });
351
- });
169
+ // Initialize scroll manager
170
+ this._scrollManager.init(container, scrollButton, shouldScrollToBottom);
352
171
  }
353
- setupTooltips(this.shadowRoot);
354
172
  });
355
173
  }
356
- _renderEmpty() {
357
- const isLoading = this.hasAttribute('loading');
358
- if (isLoading) {
359
- // Show loading overlay with minimum height for better appearance
360
- this.shadowRoot.innerHTML = `
361
- <style>${EMPTY_STYLES}${LOADING_STYLES}</style>
362
- <div style="position: relative; min-height: 120px;">
363
- <div class="loading-overlay" role="status" aria-label="Loading messages">
364
- <div class="loading-spinner"></div>
365
- </div>
366
- </div>
367
- `;
368
- }
369
- else {
370
- this.shadowRoot.innerHTML = `
371
- <style>${EMPTY_STYLES}</style>
372
- <div class="empty-state">No messages</div>
373
- `;
374
- }
375
- }
376
- _setupScrollTracking(container, button, options) {
377
- const checkScrollPosition = () => {
378
- const threshold = 50; // pixels from bottom
379
- const isAtBottom = container.scrollHeight - container.scrollTop - container.clientHeight < threshold;
380
- const hasOverflow = container.scrollHeight > container.clientHeight;
381
- // Show button when not at bottom and content has overflow
382
- const shouldShow = !isAtBottom && hasOverflow;
383
- if (shouldShow !== this._scrollButtonVisible) {
384
- this._scrollButtonVisible = shouldShow;
385
- // Only toggle button visibility if button exists
386
- if (button) {
387
- button.classList.toggle('visible', shouldShow);
388
- }
389
- // Dispatch custom event (always, regardless of button visibility)
390
- this.dispatchEvent(new CustomEvent(shouldShow ? 'bb-scrollbuttonshow' : 'bb-scrollbuttonhide', {
391
- bubbles: true,
392
- composed: true,
393
- detail: { visible: shouldShow }
394
- }));
395
- }
396
- };
397
- // Check initial state unless skipped
398
- if (!options?.skipInitialCheck) {
399
- checkScrollPosition();
400
- }
401
- // Listen for scroll events with passive listener for performance
402
- this._addTrackedListener(container, 'scroll', checkScrollPosition);
403
- // Also check on resize
404
- this._addTrackedListener(window, 'resize', checkScrollPosition);
405
- }
406
174
  }
@@ -22,7 +22,7 @@ export const AUTHOR_CONFIG = {
22
22
  textColor: THEME.gray[900],
23
23
  side: 'left',
24
24
  },
25
- 'GitHub': {
25
+ GitHub: {
26
26
  avatar: '<div style="width: 60%; height: 60%; margin: auto"><svg data-testid="geist-icon" height="16" stroke-linejoin="round" viewBox="0 0 16 16" width="16" style="color: currentcolor;"><path fill-rule="evenodd" clip-rule="evenodd" d="M8 1.46252C4.40875 1.46252 1.5 4.37029 1.5 7.96032C1.5 10.8356 3.36062 13.2642 5.94438 14.1251C6.26937 14.182 6.39125 13.987 6.39125 13.8165C6.39125 13.6621 6.38313 13.1504 6.38313 12.6063C4.75 12.9068 4.3275 12.2083 4.1975 11.8428C4.12437 11.6559 3.8075 11.0793 3.53125 10.9249C3.30375 10.8031 2.97875 10.5026 3.52312 10.4945C4.035 10.4863 4.40062 10.9656 4.5225 11.1605C5.1075 12.1433 6.04188 11.8671 6.41563 11.6966C6.4725 11.2742 6.64313 10.9899 6.83 10.8275C5.38375 10.665 3.8725 10.1046 3.8725 7.61919C3.8725 6.91255 4.12438 6.32775 4.53875 5.87291C4.47375 5.71046 4.24625 5.04444 4.60375 4.15099C4.60375 4.15099 5.14812 3.98042 6.39125 4.81701C6.91125 4.67081 7.46375 4.59771 8.01625 4.59771C8.56875 4.59771 9.12125 4.67081 9.64125 4.81701C10.8844 3.9723 11.4288 4.15099 11.4288 4.15099C11.7863 5.04444 11.5588 5.71046 11.4938 5.87291C11.9081 6.32775 12.16 6.90443 12.16 7.61919C12.16 10.1127 10.6406 10.665 9.19438 10.8275C9.43 11.0305 9.63313 11.4204 9.63313 12.0296C9.63313 12.8987 9.625 13.5972 9.625 13.8165C9.625 13.987 9.74687 14.1901 10.0719 14.1251C11.3622 13.6896 12.4835 12.8606 13.2779 11.7547C14.0722 10.6488 14.4997 9.32178 14.5 7.96032C14.5 4.37029 11.5913 1.46252 8 1.46252Z" fill="currentColor"></path></svg></div>',
27
27
  side: 'left',
28
28
  bubbleColor: '#ecf4ec',
@@ -0,0 +1,56 @@
1
+ import type { Message } from '../types/index.js';
2
+ /**
3
+ * Extended message with grouping metadata
4
+ */
5
+ export interface ProcessedMessage extends Message {
6
+ /** Whether this is the first message from this author in the current group */
7
+ isFirstFromAuthor: boolean;
8
+ /** Whether this is the last message in the current group */
9
+ isLastInGroup: boolean;
10
+ /** The timestamp to display for this group (if any) */
11
+ groupTimestamp?: string;
12
+ }
13
+ /**
14
+ * Result of processing messages, including state for incremental updates
15
+ */
16
+ export interface ProcessResult {
17
+ /** Processed messages with grouping metadata */
18
+ processed: ProcessedMessage[];
19
+ /** The author of the last message */
20
+ lastAuthor: string;
21
+ /** The timestamp of the current group */
22
+ lastGroupTimestamp?: string;
23
+ }
24
+ /**
25
+ * MessageProcessor - Handles message grouping and metadata calculation
26
+ *
27
+ * Encapsulates the grouping algorithm to determine:
28
+ * - Which messages are first from an author (show avatar)
29
+ * - Which messages are last in a group (show timestamp)
30
+ * - Group timestamps for display
31
+ *
32
+ * Optimized to process messages in a single pass instead of multiple traversals.
33
+ */
34
+ export declare class MessageProcessor {
35
+ /**
36
+ * Check if two messages can be grouped together
37
+ * Messages can be grouped if they have the same author and compatible timestamps
38
+ *
39
+ * @param prev - Previous message (null if this is the first)
40
+ * @param curr - Current message
41
+ * @returns true if messages can be grouped
42
+ */
43
+ private canGroup;
44
+ /**
45
+ * Process messages to add grouping metadata
46
+ *
47
+ * This method performs a single-pass algorithm that:
48
+ * 1. Determines first/last status for each message in its group
49
+ * 2. Assigns group timestamps consistently
50
+ * 3. Tracks state for incremental updates
51
+ *
52
+ * @param messages - Raw messages from parser
53
+ * @returns Processed messages with grouping metadata and state
54
+ */
55
+ process(messages: Message[]): ProcessResult;
56
+ }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * MessageProcessor - Handles message grouping and metadata calculation
3
+ *
4
+ * Encapsulates the grouping algorithm to determine:
5
+ * - Which messages are first from an author (show avatar)
6
+ * - Which messages are last in a group (show timestamp)
7
+ * - Group timestamps for display
8
+ *
9
+ * Optimized to process messages in a single pass instead of multiple traversals.
10
+ */
11
+ export class MessageProcessor {
12
+ /**
13
+ * Check if two messages can be grouped together
14
+ * Messages can be grouped if they have the same author and compatible timestamps
15
+ *
16
+ * @param prev - Previous message (null if this is the first)
17
+ * @param curr - Current message
18
+ * @returns true if messages can be grouped
19
+ */
20
+ canGroup(prev, curr) {
21
+ if (!prev)
22
+ return false;
23
+ if (prev.author !== curr.author)
24
+ return false;
25
+ // Different timestamps = break group
26
+ if (prev.timestamp && curr.timestamp && prev.timestamp !== curr.timestamp) {
27
+ return false;
28
+ }
29
+ return true;
30
+ }
31
+ /**
32
+ * Process messages to add grouping metadata
33
+ *
34
+ * This method performs a single-pass algorithm that:
35
+ * 1. Determines first/last status for each message in its group
36
+ * 2. Assigns group timestamps consistently
37
+ * 3. Tracks state for incremental updates
38
+ *
39
+ * @param messages - Raw messages from parser
40
+ * @returns Processed messages with grouping metadata and state
41
+ */
42
+ process(messages) {
43
+ if (messages.length === 0) {
44
+ return { processed: [], lastAuthor: '' };
45
+ }
46
+ const processed = [];
47
+ let lastAuthor = '';
48
+ let lastGroupTimestamp;
49
+ // Track group state
50
+ let currentGroupTimestamp;
51
+ for (let i = 0; i < messages.length; i++) {
52
+ const msg = messages[i];
53
+ const prev = i > 0 ? messages[i - 1] : null;
54
+ const next = i < messages.length - 1 ? messages[i + 1] : null;
55
+ // Determine if this is first from author
56
+ const isFirstFromAuthor = !this.canGroup(prev, msg);
57
+ // Start of new group - initialize group timestamp
58
+ if (isFirstFromAuthor) {
59
+ currentGroupTimestamp = msg.timestamp;
60
+ }
61
+ else if (!currentGroupTimestamp && msg.timestamp) {
62
+ // If no timestamp yet and current msg has one, use it
63
+ currentGroupTimestamp = msg.timestamp;
64
+ }
65
+ // Determine if this is last in group
66
+ const isLastInGroup = !next || !this.canGroup(msg, next);
67
+ // Create processed message with metadata
68
+ const processedMsg = {
69
+ ...msg,
70
+ isFirstFromAuthor,
71
+ isLastInGroup,
72
+ groupTimestamp: isLastInGroup ? currentGroupTimestamp : undefined,
73
+ };
74
+ processed.push(processedMsg);
75
+ // Update state tracking
76
+ lastAuthor = msg.author;
77
+ // If this is the last in group, reset group timestamp
78
+ if (isLastInGroup) {
79
+ lastGroupTimestamp = currentGroupTimestamp;
80
+ currentGroupTimestamp = undefined;
81
+ }
82
+ }
83
+ return { processed, lastAuthor, lastGroupTimestamp };
84
+ }
85
+ }
@@ -0,0 +1,87 @@
1
+ import type { AuthorOptions, Message } from '../types/index.js';
2
+ import type { ProcessedMessage } from './message-processor.js';
3
+ /**
4
+ * State for incremental message appending
5
+ */
6
+ export interface LastState {
7
+ author: string;
8
+ groupTimestamp?: string;
9
+ }
10
+ /**
11
+ * Result of a full render operation
12
+ */
13
+ export interface RenderResult {
14
+ wasAtBottom: boolean;
15
+ }
16
+ /**
17
+ * Result of an incremental append operation
18
+ */
19
+ export interface AppendResult {
20
+ success: boolean;
21
+ lastAuthor: string;
22
+ lastGroupTimestamp?: string;
23
+ }
24
+ /**
25
+ * Renderer - Manages all DOM rendering operations
26
+ *
27
+ * Centralizes DOM manipulation logic:
28
+ * - Full render of all messages
29
+ * - Incremental update when appending single messages
30
+ * - Empty state rendering
31
+ * - Loading overlay management
32
+ */
33
+ export declare class Renderer {
34
+ private shadowRoot;
35
+ constructor(shadowRoot: ShadowRoot);
36
+ /**
37
+ * Render the complete message history
38
+ *
39
+ * @param messages - Processed messages with grouping metadata
40
+ * @param authors - User-defined author configurations
41
+ * @param isLoading - Whether to show loading overlay
42
+ * @param hideScrollButton - Whether to hide the scroll-to-bottom button
43
+ * @returns Result indicating if we were at bottom before render
44
+ */
45
+ render(messages: ProcessedMessage[], authors: Map<string, AuthorOptions>, isLoading: boolean, hideScrollButton: boolean): RenderResult;
46
+ /**
47
+ * Build HTML string for all messages
48
+ */
49
+ private buildMessagesHtml;
50
+ /**
51
+ * Render full structure including styles, container, and scroll button
52
+ */
53
+ private renderFullStructure;
54
+ /**
55
+ * Update content while preserving DOM structure
56
+ */
57
+ private updateContent;
58
+ /**
59
+ * Append a single message without full re-render
60
+ *
61
+ * @param message - The message to append
62
+ * @param authors - User-defined author configurations
63
+ * @param lastState - Previous state for grouping logic
64
+ * @returns Result indicating success and updated state
65
+ */
66
+ appendSingleMessage(message: Message, authors: Map<string, AuthorOptions>, lastState: LastState): AppendResult;
67
+ /**
68
+ * Check if two messages can be grouped
69
+ */
70
+ private canGroupMessages;
71
+ /**
72
+ * Render empty state (no messages)
73
+ */
74
+ renderEmpty(isLoading: boolean): void;
75
+ /**
76
+ * Update loading overlay visibility
77
+ */
78
+ updateLoadingOverlay(shouldShow: boolean): void;
79
+ /**
80
+ * Get the history container element
81
+ */
82
+ getHistoryContainer(): HTMLElement | null;
83
+ /**
84
+ * Get the scroll-to-bottom button element
85
+ */
86
+ getScrollButton(): HTMLButtonElement | null;
87
+ }