11 Commits

Author SHA1 Message Date
4a4f3b2fa0 refactor: Clean architecture + unified badge styling
PART 1: Extract UnreadBadgeManager (Clean Architecture)

Created managers/unreadBadgeManager.js:
✅ Single Responsibility: Manages ONLY badge UI
✅ Methods: increment(), reset(), setCount(), hasUnread()
✅ Handles all DOM manipulation internally
✅ Reusable and testable

Cleaned ChatControllerV2:
❌ Removed 150+ lines of UI logic
❌ Removed duplicate systems (_unreadCount + _newMessagesCount)
❌ Removed deprecated methods:
   - _incrementUnreadBadge()
   - _resetUnreadBadge()
   - _showNewMessagesIndicator()
   - _hideNewMessagesIndicator()
   - _findOrCreateNewMessagesButton()
✅ Now uses: this.badgeManager.increment/reset()

PART 2: Unified Badge Styling

Aligned unread-badge with sticky-date design:
- Same typography (font-size, weight, line-height)
- Same spacing (padding: 6px 12px)
- Same border-radius (10-12px)
- Same shadows (box-shadow hierarchy)
- Same transitions (0.2s ease)
- Same animation patterns (scale, hover effects)
- Added border: 2px for contrast with background

Result:
✅ Consistent UI across all badges
✅ Matches Telegram-like design system
✅ Better visual hierarchy
✅ ~950 lines in Controller (was 1125)
✅ Clean separation of concerns
2026-01-13 15:36:17 +03:00
c0bb7530c5 feat: Smart button visibility and load-to-present on click
Two types of bottom:
1. Historical bottom (hasMoreAfter=true):
   - Button ALWAYS visible (even at scroll bottom)
   - Click → loads latest 50 messages to present time
   - Renders and scrolls to bottom

2. Present bottom (hasMoreAfter=false):
   - Button hidden when isNearBottom()
   - Click → smart scroll (to unread or bottom)

Changes:
- _setupSmartButtonVisibility() monitors hasMoreAfter
- _handleScrollButtonClick() loads history if hasMoreAfter
- Added public loadLatest() method
- Emits 'chat:messagesLoaded' event for UI updates

Result:
- Historical view: button always shows, loads to present
- Present view: button hides at bottom, smart unread scroll
- No more stuck in history without way to present
2026-01-13 15:21:52 +03:00
2cea8c2330 feat: Smart scroll button with unread badge and auto-scroll
Implements Telegram-like behavior for new messages:

1. Smart Auto-scroll (WS messages):
   ✅ User at bottom + present time → auto-scroll to new message
   ✅ User NOT at bottom + present time → show unread badge
   ❌ Historical view (hasMoreAfter=true) → no action

2. Smart Scroll Button (#scrollBtn):
   - Shows unread badge when new messages arrive
   - Click behavior:
     * Has unread + lastReadId → scroll to first unread
     * No unread → scroll to bottom
   - Auto-hides badge when user scrolls to bottom

3. Badge Styling:
   - Red badge with count on top-right of button
   - Pulse animation on appearance
   - Button subtle pulse when has unread

Key Logic:
- Only auto-scroll when hasMoreAfter=false (present time)
- Historical bottom (hasMoreAfter=true) doesn't trigger auto-scroll
- Badge resets on: manual scroll to bottom, button click
- Respects user's scroll position unless at bottom
2026-01-13 15:07:52 +03:00
ad3f141f1c feat: Add instant positioning to last read message on chat open
Problem: After removing autoscroll, last read message wasn't visible on initial load

Solution:
- ✨ NEW: _positionToMessage() - instant viewport positioning WITHOUT scroll animation
- Sets scrollTop BEFORE user sees chat (no visible scrolling)
- Centers last read message with sticky header offset (96px)
- Falls back to bottom position for new chats

Difference:
- ❌ Old: render → scrollIntoView() → visible scroll animation
- ✅ New: render → scrollTop = X → instant positioning

Result:
- Chat opens IMMEDIATELY showing last read message
- NO visible scrolling or animation
- Telegram-like behavior: position is set, not scrolled to
- Natural user experience
2026-01-13 14:41:24 +03:00
d3a876f1cb refactor: Remove all autoscroll except prepend physics correction
BREAKTHROUGH: Discovered append doesn't need autoscroll!

Changes:
- ✅ KEPT: scrollTop correction after prepend (physics, not autoscroll)
  Prevents infinite history loading by compensating scrollHeight growth
- ❌ REMOVED: scrollToBottom() - now empty stub
- ❌ REMOVED: scrollToMessage() - now empty stub
- ❌ REMOVED: Initial scroll on chat open
- ❌ REMOVED: Scroll after loadAround

Philosophy shift:
- Old: We control user's scroll position
- New: IntersectionObserver + physics = natural behavior

Results:
- Newer messages load perfectly WITHOUT autoscroll
- Older messages need ONLY physics correction
- User controls their own scroll position
- Natural infinite scroll experience
2026-01-13 14:35:49 +03:00
0fe736ede8 refactor: переключились на chatDetailV2.js (чистая архитектура)
- Прямой импорт ChatControllerV2 без промежуточных слоев
- Убраны deprecated обертки (window.messageRenderer, window.chatHistoryLoader)
- Меньше кода: 231 vs 264 строки
- Более явная архитектура
- Для тестирования работы в production
2026-01-13 10:03:54 +03:00
6a82ef7b80 fix: используем lastReadTimestamp как fallback для скролла к последнему прочитанному
- Проблема: lastReadMessageId часто равен 0/null
- Решение: используем lastReadTimestamp (API поддерживает оба формата)
- Добавлен this.lastReadTimestamp в ChatControllerV2
- Передаем оба параметра из chatDetail.js
- anchorValue = lastReadMessageId || lastReadTimestamp
- Исправлена поврежденная структура в chatControllerV2.js
2026-01-13 09:46:27 +03:00
041e905a44 fix: заменил scrollTo() на прямое присвоение scrollTop при инициализации
- scrollTo() НЕ работает при первичной загрузке (scrollTop остается 0)
- используется прямое присвоение scrollTop как в legacy коде
- тройной RAF для надежности
- это должно исправить проблему с автозагрузкой истории
2026-01-13 09:30:18 +03:00
77423bfcbb fix: замена всех использований legacy классов на V2 2026-01-13 09:19:19 +03:00
7b57214fdd fix: исправлены импорты в messageEditing и chat/index 2026-01-13 09:18:25 +03:00
6d76988cdd refactor: восстановлены старые стили пузырей сообщений, аватаров и разделителей (pre-redesign)
- Восстановлен мягкий цвет пузырей: color-mix(92%) вместо жесткого var(--bs-primary)
- Аватары: border-radius 9999px + grid layout для идеальных кругов
- Разделители: правильный spacing, font-weight 700, pointer-events, color-mix прозрачность
- Добавлены оптимизации скролла: rootMargin 300px, limit 50 сообщений (Telegram-стиль)
- Добавлены новые модули: messageLoader, scrollManager, chatUtils
- Рефакторинг логики загрузки сообщений для предотвращения дубликатов
- Создана документация по архитектуре и тестированию
2026-01-12 17:21:41 +03:00