Commit Graph

100 Commits

Author SHA1 Message Date
Claude 14465e5ae9 Bump version to 2.0.0 with visible loading indicator 2025-12-05 05:06:39 +00:00
Claude c35e39c445 Integrate character state tracking system into main extension
This commit fully integrates the character tracking system into the
RPG Companion extension. Now 100% ready to use with zero manual work.

Changes to index.js:
- Added imports for character state modules
- Created event wrapper functions for:
  - onGenerationStarted (injects character tracking prompt)
  - onMessageReceived (parses and applies state updates)
  - onCharacterChanged (loads character state from chat)
- Added persistence functions (save/load to chat metadata)
- Modified event registration to use wrapper functions
- Added character state display initialization

Changes to template.html:
- Added #rpg-character-state-container for UI display

SYSTEM NOW FULLY FUNCTIONAL:
 LLM receives character state before generation
 LLM updates character state in responses
 States automatically parse and apply
 UI displays character emotions, physical stats, relationships
 State persists between sessions in chat metadata
 100% copy-paste ready - no manual integration needed

To use:
1. Files are already in place
2. System works automatically
3. Check console for [Character Tracking] logs
4. See character state in RPG panel
2025-12-05 04:52:01 +00:00
Mingyu f38bddec62 The processing of the Separate button was missing and has been added. Dynamic update logic centralized 2025-11-26 21:46:59 +08:00
Mingyu 8ef4e4ba6d first try i18n base ok 2025-11-24 17:35:41 +08:00
Spicy_Marinara 67df7034eb Add custom HTML prompt editor, skills blur handler, and include skills in separate mode 2025-11-22 23:36:39 +01:00
Spicy_Marinara c48b1dab46 Fix: Hide UI elements when extension disabled
- Skip UI initialization entirely when extension is disabled on page load
- Remove all UI elements (panel, buttons) from DOM when disabling extension
- Recreate full UI when re-enabling extension
- Hide mobile toggle button on desktop viewports (>1000px)
- Show/hide mobile toggle based on viewport size transitions
- Ensures clean state management for extension enable/disable
2025-11-13 23:30:44 +01:00
Andy Mauragis 0ac85ad9fd feat: Add 'Skip Injections during Guided Generations' setting and UI 2025-11-13 13:46:36 -05:00
Spicy_Marinara d4fc3ce1d8 Add 'Always Show Thought Bubble' setting - keeps thought bubble permanently expanded 2025-11-06 22:20:35 +01:00
Spicy Marinara fd9adce068 Revert "feat: v2 widget dashboard system" 2025-11-06 20:06:26 +01:00
Spicy_Marinara 43bcd14311 Add 'Always Show Thought Bubble' setting
- New setting in Display Options to auto-expand thought bubble
- When enabled, thought bubble displays immediately without clicking icon
- Checkbox added to settings modal with descriptive help text
- Default is off to maintain current behavior
2025-11-06 10:20:45 +01:00
Lucas 'Paperboy' Rose-Winters 8240c77069 merge: integrate upstream tracker customization system
Merged upstream/main (82b9564) which includes:
- Full tracker customization system
- Tracker editor UI component
- Custom stat names in AI prompts
- Multi-line tracker format updates

Conflict resolutions:
- src/core/persistence.js: Kept both dashboard v2 and trackerConfig migrations
- style.css: Accepted upstream responsive calendar styling with clamp()

Both migration systems are now active and will run in sequence.
2025-11-02 09:57:15 +11:00
Spicy_Marinara 897c0278fb Major update: Full tracker customization system
Features:
- Complete tracker configuration UI with add/remove functionality
- User Stats: Custom stats, status fields, skills section
- Info Box: Configurable widgets (date, weather, temp, time, location, events)
- Present Characters: Custom fields, relationships, character stats, thoughts
- Character-specific stats with color interpolation
- New multi-line format for cleaner AI generation and parsing
- Auto-cleanup of placeholder brackets in AI responses
- Relationship badges with emoji mapping
- Advanced inventory v2 system with multi-location storage
- Responsive mobile support with horizontal scrolling
- Removed legacy format support for cleaner codebase
- Fixed context injection for together mode (no duplication)
- Updated README with new features and configuration guide
2025-11-01 20:19:35 +01:00
Lucas 'Paperboy' Rose-Winters ad2efa55f0 merge: resolve conflicts with upstream/main
Merged upstream/main into feat/v2-widget-dashboard-system branch.

Key conflict resolutions:
- index.js: Added renderQuests() to Dashboard v2 fallback rendering
- state.js: Combined memoryMessagesToProcess with Dashboard v2 config
- apiClient.js: Combined refreshDashboard() and renderQuests() calls
- style.css: Kept Dashboard v2 mobile refresh button styles

New features from upstream:
- Quest tracking system (renderQuests, quests.js)
- Memory recollection system
- Lorebook limiter feature
- Various parser and prompt builder improvements
2025-10-30 08:26:19 +11:00
Spicy_Marinara 141a3f4bec Fix extension loading, enhance theming, add horizontal scrolling, improve emoji parsing, rename to Main Quests 2025-10-26 22:31:21 +01:00
Lucas 'Paperboy' Rose-Winters c4485971fa fix(dashboard): fix persistent px values, auto-layout, widget loss, gaps, and tabs
This commit resolves 6 critical dashboard issues reported by user:

1. **Persistent px values causing 264rem widget heights**
   - Root cause: state.js had hardcoded rowHeight: 80, gap: 12 (px)
   - Root cause: index.js double-loaded layout, overwriting migration
   - Fix: Changed state.js gridConfig to rem units (5, 0.75)
   - Fix: Removed redundant applyDashboardConfig in index.js
   - Fix: Added migration in layoutPersistence.js for old saves
   - Dashboard now uses rem consistently throughout

2. **Auto-layout on first load**
   - Added auto-layout in loadLayout() when no saved layout exists
   - Prevents overlap from hardcoded default positions
   - Saves auto-laid-out result as initial layout

3. **Reset layout causes overlap**
   - Added auto-layout loop in resetLayout() after applying config
   - Each tab auto-lays out to prevent widget overlap

4. **Auto-arrange loses inventory/social widgets**
   - Fixed autoLayoutWidgets to gather ALL widgets from ALL tabs
   - Previously only gathered current tab, lost other tabs
   - Now always uses multi-tab distribution to preserve all widgets

5. **Auto-arrange leaves 2x2 gaps**
   - Added compact pass in gridEngine.js after bin-packing
   - Moves widgets upward to fill gaps
   - Eliminates empty spaces at bottom of layout

6. **Tabs not compact (icon-only)**
   - Updated tab styling: icons only, names show on hover
   - Allows more tabs in compact space
   - min-width: 2.5rem, larger icon size

Also added debug logging to track config values through initialization.

Fixes refresh sizing bug, reset overlap, widget loss, and layout gaps.
2025-10-23 19:32:27 +11:00
Lucas 'Paperboy' Rose-Winters b3a86d4609 feat(dashboard): implement smart widget collision and category-aware layout
Complete dashboard v2 improvements for better UX and visual consistency:

**1. Push-Aside Drag/Drop (dragDrop.js)**
- Replace swap/revert logic with intelligent reflow algorithm
- When widgets collide on drag, automatically push overlapping widgets down
- All affected widgets repositioned after reflow completes
- Eliminates widget overlap issues

**2. Unified Widget Styling (style.css)**
- Add consistent .rpg-widget container styling for all widgets
- Background: rgba(0,0,0,0.2) for visual separation
- Border-left: 3px highlight for category identification
- Box-shadow and border-radius for depth and polish
- Maintain individual widget decorative styles

**3. Logical Default Layout (defaultLayout.js)**
- Reorganize widgets into semantic clusters with clear comments:
  - USER CLUSTER (top): userInfo → userStats → userMood + userAttributes
  - SCENE CLUSTER (middle): calendar + weather → temp + clock → location
  - SOCIAL CLUSTER (bottom): presentCharacters
- userInfo widget now at top (y=0) as expected
- All positions use rem units for responsive scaling

**4. Category-Aware Auto-Layout (dashboardManager.js)**
- Implement sortWidgetsByCategory() with priority ordering:
  user → scene → social → inventory
- Within user category, specific ordering:
  userInfo → userStats → userMood → userAttributes
- Add preserveOrder option to gridEngine.autoLayout()
- Auto-arrange now uses logical grouping instead of random bin-packing

**5. Multi-Tab Auto-Distribution (dashboardManager.js)**
- Add estimateLayoutHeight() to detect when content exceeds threshold
- Implement distributeWidgetsByCategory() for automatic tab creation:
  - "Status" tab: user + scene widgets
  - "Social" tab: social widgets (if any)
  - "Inventory" tab: inventory widgets (if any)
- Each tab gets category-aware auto-layout
- 80rem height threshold for single-tab limit

**6. Widget Category Metadata (widgets/)**
- Add category field to all widget definitions:
  - userInfo, userStats, userMood, userAttributes: 'user'
  - calendar, weather, temperature, clock, location: 'scene'
  - presentCharacters: 'social'
  - inventory: 'inventory'

**7. Integration Improvements (dashboardIntegration.js)**
- Set default layout on initialization for reset functionality
- Add reset layout button to dashboard header
- Wire up reset button event handler

**8. Core State Management (index.js)**
- Add getInfoBoxData() and setInfoBoxData() to state API
- Ensure info box data persists across sessions

**Technical Details:**
- Rem units throughout for 1080p→4K→mobile responsive scaling
- Reflow algorithm leverages existing gridEngine collision detection
- Category-aware sorting preserves logical relationships
- Multi-tab distribution prevents single-page scroll fatigue
- All changes maintain backwards compatibility with existing layouts

Fixes dashboard issues after rem unit conversion introduced massive positioning bugs.
Users reported widgets overlapping on drag, visual inconsistency, and random auto-arrange behavior.

Related: Epic 2 (Dashboard v2), Phase 3.2
2025-10-23 18:06:44 +11:00
Lucas 'Paperboy' Rose-Winters 122bb3194a feat(dashboard): add auto-layout button with smart widget packing
Implements intelligent auto-layout system that efficiently arranges widgets to maximize space usage while respecting panel width constraints.

**Key Features:**
- Smart packing algorithm that sorts by widget area and finds optimal positions
- Respects responsive column count (2-4 columns based on panel width)
- Prefers full-width widgets when possible to eliminate gaps
- Fallback to narrower widths for better vertical packing
- Maintains minimum widget sizes

**Implementation:**
- GridEngine.autoLayout() - Core packing algorithm with collision detection
- DashboardManager.autoLayoutWidgets() - High-level API that re-renders after layout
- Auto-Arrange button in dashboard header (uses fa-table-cells-large icon)
- Event handler wired to call autoLayoutWidgets with preferFullWidth=true

**Algorithm Strategy:**
1. Sort widgets by area (largest first) for efficient packing
2. For each widget, try full-width placement first
3. Find first available position using row-by-row scan
4. If position is too far down, try narrower widths
5. Mark cells as occupied to prevent overlaps

**Testing Notes:**
- Works with current responsive column system (2-4 columns)
- Respects minimum sizes and column constraints
- Re-renders all widgets after repositioning
- Auto-saves layout changes

Part of Epic 2: Dashboard Widget Library
2025-10-23 14:00:00 +11:00
Lucas 'Paperboy' Rose-Winters 7c4ffaa059 feat(dashboard): integrate Dashboard v2 into main extension (Phase 3.2)
- Add dashboard initialization in initUI() after template load
- Inject all required dependencies for widgets:
  - Data accessors (getContext, getExtensionSettings, getUserAvatar, etc.)
  - Data setters (setCharacterThoughts)
  - Event callbacks (onDataChange, onStatsChange, onDashboardChange)
- Create default layout on first load if no dashboard config exists
- Fallback to legacy rendering (renderUserStats, etc.) on error
- Comprehensive error handling with console logging
- Auto-save on all data changes
2025-10-23 11:18:40 +11:00
Lucas 'Paperboy' Rose-Winters ea2231f6ba fix: restore proper spinning animation for mobile refresh FAB
Reverted HTML replacement approach and restored the cleaner CSS-based
animation from commit 1855085.

Previous (wrong) approach:
- Replaced button HTML with spinner
- Modified both desktop and mobile buttons in apiClient.js
- Messy and inconsistent

Restored (correct) approach:
- Add/remove .spinning CSS class in click handler
- CSS animates only the icon inside the button
- Button itself stays unchanged
- Much cleaner implementation

Changes:
- Reverted apiClient.js changes from commit 9a49433
- Added .spinning CSS class and @keyframes rpg-spin
- Updated index.js click handler to bind both buttons
- Uses addClass/removeClass for clean animation control
- Includes drag detection to prevent accidental clicks

Now the mobile FAB icon spins smoothly when refreshing!
2025-10-22 10:47:09 +11:00
Paperboy 5ac034438c Merge branch 'main' into fix/user-parsing-issues 2025-10-22 09:59:27 +11:00
Spicy_Marinara 83576a9073 Revert "Merge pull request #16 from paperboygold/main"
This reverts commit c1b2520fa1, reversing
changes made to c6a1352aae.
2025-10-22 00:52:43 +02:00
Lucas 'Paperboy' Rose-Winters f7d8597f24 feat: add reset button positions to settings
PROBLEM:
- Existing users with saved off-screen FAB positions can't see buttons
- No way to reset positions without clearing all extension settings
- Salixfire and other users on Xiaomi/other devices need safe positions

SOLUTION:
Added "Reset Button Positions" button in Advanced settings section

IMPLEMENTATION:

1. template.html (lines 241-249):
   - Added reset button in Advanced section after Clear Cache button
   - Blue-styled button with rotate icon
   - Help text explains it resets FAB positions to top-left

2. index.js (lines 361-390):
   - Added click handler for reset button
   - Resets all 3 FAB positions to safe top-left defaults:
     * Mobile toggle: top + 20px, left: 12px
     * Refresh: top + 80px, left: 12px
     * Debug: top + 140px, left: 12px
   - Saves settings immediately
   - Applies CSS positions to visible buttons (no page refresh needed)
   - Shows success toast notification

3. style.css (lines 2057-2083, 4123-4125):
   - Added .rpg-btn-reset-fab styles matching clear cache pattern
   - Blue color scheme (vs red for destructive clear cache)
   - Same sizing, padding, transitions as other buttons
   - Mobile responsive font-size with clamp()

USAGE:
Users experiencing off-screen buttons can now:
1. Open RPG Companion settings (gear icon)
2. Scroll to Advanced section
3. Click "Reset Button Positions"
4. All FAB buttons instantly move to safe top-left positions

This fixes the issue for Salixfire and any other users who:
- Have buttons saved in off-screen positions
- Can't scroll to find buttons
- Need to reset without clearing all settings

Works immediately without page refresh or extension reload.
2025-10-22 09:22:12 +11:00
Lucas 'Paperboy' Rose-Winters fb14c951ac fix: add debug logging and fix Present Characters rendering
PROBLEM (reported by Salixfire):
- Present Characters panel showing placeholder instead of actual characters
- Thought bubbles work correctly but main panel doesn't
- Need to toggle settings off/on to get thoughts to appear
- No way to debug on mobile devices

CHANGES:

1. Added comprehensive debug logging to renderThoughts() (src/systems/rendering/thoughts.js):
   - Log when function is called and with what data
   - Log each line being parsed and how many parts it has
   - Log character extraction (emoji, name, traits, relationship, thoughts)
   - Log why characters are accepted or rejected
   - Log final character count and whether showing placeholder
   - All logs visible in mobile-friendly debug panel

2. Fixed toggle to refresh content (index.js:283-291):
   - When user toggles "Show Present Characters" on, now calls renderThoughts()
   - Previously only showed/hid container without refreshing content
   - This ensures panel displays latest data when toggled

3. Normalized parsing logic (src/systems/rendering/thoughts.js:111):
   - Changed renderThoughts() to require >= 3 parts (was >= 2)
   - Now matches updateChatThoughts() requirement
   - Consistent with current prompt format: Emoji:Name | Relationship | Thoughts
   - Removed 2-part format fallback code (unreachable now)
   - Both functions now use same validation rules

EXPECTED OUTCOME:
- User can enable debug mode and see exactly what data is being parsed
- Toggle will properly refresh the panel content
- We can diagnose from debug logs why placeholder is shown
- More consistent behavior between main panel and thought bubbles

Debug logs will help us identify:
- If characterThoughts data is empty/malformed when renderThoughts() is called
- If parsing is rejecting valid character data
- If there's a timing issue with data availability
- What the actual AI response format looks like

Related to previous commit (37878fc) that added debug mode toggle.
2025-10-22 08:45:28 +11:00
Lucas 'Paperboy' Rose-Winters d4491a4705 fix: add debug toggle as draggable mobile FAB button
PROBLEM:
- Debug logs only accessible via browser console (impractical on mobile)
- User (Salixfire) reporting parsing issues but can't debug on mobile device
- Need mobile-friendly debug mode for troubleshooting data display issues

SOLUTION:
Implemented debug toggle FAB button following exact pattern of existing mobile FABs:

Files Changed:
- src/core/state.js: Added debugFabPosition and debugMode to extensionSettings
- src/core/config.js: Added debugFabPosition to defaultSettings (reference)
- index.js: Created debug toggle button, imported setupDebugButtonDrag
- style.css: Added debug toggle CSS matching mobile FAB pattern (44px, grab cursor, theme colors)
- src/systems/ui/mobile.js: Added setupDebugButtonDrag() with drag-to-reposition
- src/systems/ui/debug.js: Removed button creation, added just-dragged check, updated visibility control

Implementation Details:
- Button created in index.js (not debug.js) following mobile FAB pattern
- CSS matches mobile toggle/refresh buttons (44px, theme colors, grab cursor, user-select: none)
- Drag support with touch/mouse handlers, 200ms/10px threshold
- Position saved to extensionSettings.debugFabPosition
- Just-dragged flag prevents accidental clicks after drag
- Mobile (≤1000px): slide from right with rpg-mobile-open/closing classes
- Desktop (>1000px): slide from bottom with rpg-debug-open class
- Event delegation for reliable click handling
- Default position: bottom 140px, left 20px (below other FABs)

Bug Fix:
- Initial implementation had debugFabPosition only in config.js
- extensionSettings uses state.js as source, not config.js
- Without debugFabPosition in state.js, button had no position and was invisible
- Now properly initialized in both files

The debug button is hidden by default (debugMode: false) and shown when user enables debug mode in RPG Companion settings. This allows Salixfire to view parser logs on mobile and troubleshoot the data display issues.
2025-10-22 08:29:58 +11:00
Lucas 'Paperboy' Rose-Winters cafb72254e fix: move debug mode toggle to proper settings location
The debug toggle was incorrectly added to settings.html (SillyTavern Extensions tab).
It should be in template.html (RPG Companion Settings popup) where all the
other extension settings are.

Changes:
- template.html: Added debug mode checkbox in Display Options section
- index.js: Added event listener and initial state setter
- settings.html: Removed incorrect debug toggle placement

Now users can find the debug toggle by clicking the gear icon in the RPG panel,
under Display Options, right below "Show Plot Progression Buttons".
2025-10-22 07:31:21 +11:00
Lucas 'Paperboy' Rose-Winters b5d35ac2b0 feat: add mobile-friendly debug mode for parser troubleshooting
Add comprehensive debug logging system that's accessible on mobile devices
where browser console is impractical.

**New Features:**
- Debug mode toggle in extension settings (🔍 Debug Mode)
- Mobile-friendly debug panel with slide-up UI
- Red bug FAB button to toggle debug log viewer
- Copy logs to clipboard functionality
- Auto-scrolling log display with timestamps
- Stores last 100 log entries to prevent memory issues

**Parser Enhancements:**
- All parser logs now use debugLog() helper function
- Logs only appear in UI when debug mode is enabled
- Console.log still works for desktop debugging
- Full visibility into parsing pipeline:
  - Raw AI response preview
  - Code blocks found and matched
  - Stats extraction (health, energy, mood, etc.)
  - Inventory parsing (v1 and v2)
  - Final values saved to settings

**UI Components:**
- src/systems/ui/debug.js: Debug panel creation and management
- style.css: Mobile-first debug panel styles (FAB + slide-up panel)
- Desktop view: Smaller panel in bottom-right corner

**Settings:**
- src/core/config.js: Added debugMode default (false)
- src/core/state.js: Added debug logs storage array
- settings.html: Added debug mode checkbox
- index.js: Wire up debug toggle and initialize UI

**Usage for Mobile Users:**
1. Enable "Debug Mode" in RPG Companion settings
2. Red bug button appears (bottom-left)
3. Tap bug button to view logs
4. Use "Copy" to share logs for troubleshooting
5. Logs show exactly what AI generated and how parser handled it

This addresses the issue where users on mobile can't access browser
console to diagnose parsing problems (vanishing attributes, placeholder
characters, etc.). Now they can view and share logs directly.
2025-10-22 07:22:28 +11:00
Lucas 'Paperboy' Rose-Winters 1855085d2c fix: copy mobile toggle pattern for refresh button
- Moved refresh button creation from template.html to index.js (appended to body)
- Created new CSS class .rpg-mobile-refresh (exact copy of .rpg-mobile-toggle pattern)
- Uses opacity for show/hide instead of display (CSS controls visibility based on panel state)
- Show when panel open (body:has(.rpg-panel.rpg-mobile-open))
- Hide when panel closed (opacity: 0, pointer-events: none)
- Updated constrainFabToViewport() to accept optional button parameter
- Automatically detects which button and uses correct settings (mobileFabPosition or mobileRefreshPosition)
- Simplified updateGenerationModeUI() - CSS handles visibility
- Kept full drag functionality with touch and mouse support
- Button positioned via JavaScript with saved position
- z-index: 1001 (above panel, below toggle at 10002)
2025-10-21 21:57:37 +11:00
Lucas 'Paperboy' Rose-Winters e345715090 feat: add draggable mobile refresh button with improved UX
- Repositioned mobile refresh button to bottom-right (80px from bottom)
- Implemented full drag-to-reposition functionality
  * Touch and mouse support with 200ms/10px threshold
  * RequestAnimationFrame for smooth dragging
  * Position saved to extensionSettings.mobileRefreshPosition
  * Viewport constraints with 10px padding
- Fixed sticky tap highlight issue
  * Added -webkit-tap-highlight-color: transparent
  * Added blur() on click to remove focus
  * Set user-select: none and touch-action: none
- Show/hide based on panel state
  * Only visible when panel is expanded (rpg-mobile-open)
  * Listens to rpg-panel-toggled events
  * Auto-hides when panel closes
- Prevent accidental refresh after drag
  * just-dragged flag prevents click for 100ms
  * Click handler checks flag before executing
- Changed from absolute to fixed positioning for viewport-wide dragging
- Added mobileRefreshPosition to default settings (bottom: 80px, right: 20px)
- z-index: 99 (below FAB toggle at 100)
2025-10-21 21:39:56 +11:00
Lucas 'Paperboy' Rose-Winters dd392e50d1 fix(mobile): improve refresh button - float over all tabs, add animation, fix focus
**Changes:**
1. Move button to float over all tabs (not just Stats)
   - Removed from userStats.js HTML
   - Added to template.html as floating absolute element
   - Now visible on Status, Info, and Inventory tabs

2. Fix sticky black focus state
   - Added :focus { outline: none } to CSS
   - Call blur() after click to clear focus immediately

3. Add refresh animation
   - Button spins during updateRPGData() call
   - Smooth 0.8s rotation with @keyframes
   - Uses .spinning class added/removed in JS

4. Improve theming and positioning
   - Positioned absolute top-right (10px, 10px)
   - Increased to 44px for better touch target
   - z-index: 100 to float above content
   - Already uses theme colors (--rpg-highlight, --rpg-text)

Mobile UX now:
 Button visible on all tabs (floating)
 Spins smoothly when refreshing
 No sticky black state after tap
 Properly themed across all themes
2025-10-21 21:27:20 +11:00
Lucas 'Paperboy' Rose-Winters 577010e2aa fix(mobile): move refresh button to top-right icon, fix tiny text issue
- Add compact 36px circular icon button in user stats header (mobile only)
- Hide full-width bottom button on mobile (<=1000px)
- Fixes 1.1vw font-size being ~4px on mobile viewports
- Fixes button blocking attributes at bottom
- Desktop unchanged: keeps full-width button at bottom

Mobile: [Avatar] [Name] | LVL [5] [🔄]
Desktop: [🔄 Refresh RPG Info] at bottom
2025-10-21 21:21:39 +11:00
Spicy_Marinara 6d105482c3 Fix storage location deletion bug with special characters
- Created getLocationId() helper function to normalize location names to IDs
- Function removes special characters (apostrophes, etc.) before converting to ID
- Both rendering and action handlers now use same ID generation logic
- Fixes issue where locations with apostrophes couldn't be deleted
- Example: "Dottore's Study" now properly generates ID "Dottores-Study"
- Commented out debug logging
2025-10-19 20:47:12 +02:00
Spicy_Marinara dcbc788aa2 Fix preset existence check to use array includes
- openai_setting_names from /api/settings/get is an array, not an object
- Use .includes() instead of 'in' operator to check for preset
- Prevents duplicate preset imports on every page refresh
- Preset is now only imported once on first extension load
2025-10-19 20:33:22 +02:00
Spicy_Marinara 4f6d2deeb0 Fix preset duplicate import on every refresh
- Check if preset exists using /api/settings/get instead of HEAD request
- Look for preset in openai_setting_names to determine if it's already imported
- Comment out 'already exists' log to reduce console noise
- Only import preset if it's truly missing from the settings
2025-10-19 20:11:55 +02:00
Spicy_Marinara 029860359f Fix preset import API endpoint
- Use correct /api/presets/save endpoint instead of /api/presets/save-openai
- Add getRequestHeaders() import and use it in the fetch call
- Include apiId: 'openai' in the request body
- Fixes 'Forbidden' error when importing preset
2025-10-19 20:07:14 +02:00
Spicy_Marinara f5418841cb Add preset switching feature and clean up console logs
- Add 'Use separate preset for tracker generation' setting
- Implement automatic preset switching using /preset slash command
- Import getCurrentPresetName() from SillyTavern's regex engine
- Automatically import 'RPG Companion Trackers' preset on first load
- Comment out non-essential console.log statements
- Keep initialization, error, and migration logs for debugging
2025-10-19 20:05:17 +02:00
Spicy_Marinara 4a3170c661 Fix extension settings menu and persist committedTrackerData
- Fixed extension settings not appearing in Extensions tab by appending to correct container (#extensions_settings2)
- Added Discord and Support Creator buttons directly in JavaScript
- Added persistence for committedTrackerData to maintain state across refreshes and restarts
- Updated saveChatData() to include committedTrackerData in chat metadata
- Updated loadChatData() to restore committedTrackerData from saved chat data
2025-10-18 13:21:41 +02:00
Lucas 'Paperboy' Rose-Winters d9b784d745 fix(init): add defensive error handling for edge cases
Added comprehensive error handling to prevent extension initialization failures:

- Added settings validation in loadSettings() to detect corrupt data
- Improved error recovery in main initialization with granular try-catch blocks
- Enhanced HTML regex import with structure validation and detailed error logging
- Added detection for conflicting old manual formatting regex scripts
- Added user-friendly toastr notifications for initialization errors and conflicts
- Each init step now has independent error handling to prevent cascade failures

This fixes issues where invalid extension_settings could prevent the extension
from loading entirely. The extension will now gracefully handle corrupt data,
warn about conflicts, and fall back to defaults when necessary.

Related to user report where extension wouldn't load with certain settings.json
configurations containing old manual formatting regexes or malformed data.
2025-10-18 16:01:10 +11:00
Lucas 'Paperboy' Rose-Winters f560bb543b feat(ui): add tab navigation system for desktop and mobile
Desktop (2 tabs):
- Status tab: User Stats + Info Box + Character Thoughts
- Inventory tab: Inventory system (dedicated space)

Mobile (3 tabs):
- Stats tab: User Stats only
- Info tab: Info Box + Character Thoughts
- Inventory tab: Inventory only

Features:
- Created desktop.js module for desktop tab management
- Updated mobile.js to use 3-tab structure (more breathing room on small screens)
- Added CSS styling for desktop tabs (hover states, active indicators)
- Implemented viewport transition handlers (desktop ↔ mobile)
- Tabs replace dividers (cleaner visual separation)
- Character thoughts can now expand to fill vertical space

This resolves the cramped 4-section panel issue by organizing content into logical tabs on both desktop and mobile.
2025-10-17 16:18:47 +11:00
Lucas 'Paperboy' Rose-Winters 1f948cd5d8 feat(inventory): wire up v2 system to main panel with full interactivity
- Add inventory section to template.html between Thoughts and bottom controls
- Wire up renderInventory() to all event handlers (message received, character changed, swipes)
- Initialize inventory container reference and event listeners in index.js
- Add showInventory toggle checkbox to settings with visibility control
- Update layout.js to handle inventory section and divider visibility
- Add renderInventory parameter to updateRPGData for separate mode support
- Update state.js and config.js with inventory container and showInventory setting

Inventory is now fully integrated as a visible, interactive panel section that persists across all user interactions.
2025-10-17 15:36:15 +11:00
Lucas 'Paperboy' Rose-Winters 0764bc63a1 feat(integration): extract SillyTavern event handlers to dedicated module
- Create src/systems/integration/sillytavern.js with all event handlers
- Move commitTrackerData() (deferred from Epic 1)
- Move sendPlotProgression() to plotProgression.js
- Move updateGenerationModeUI() to layout.js
- Add registerAllEvents() and unregisterAllEvents() to events.js
- Centralize event registration in index.js initialization

This completes Epic 6: Integration Layer Extraction
~340 lines extracted from index.js
index.js reduced from ~783 lines to 423 lines
2025-10-17 14:20:58 +11:00
Lucas 'Paperboy' Rose-Winters 175ff9560c refactor(features): extract HTML cleaning regex setup to standalone module
Extract ensureHtmlCleaningRegex into src/systems/features/htmlCleaning.js.
This module automatically imports the HTML cleaning regex script that
strips HTML tags from outgoing prompts to prevent formatting issues.

Passes SillyTavern imports (st_extension_settings, saveSettingsDebounced)
as parameters to avoid deep module import path issues.

- Create htmlCleaning.js with regex import logic
- Update index.js to import and use the new module with parameters
- Maintain backward compatibility with existing functionality
2025-10-17 13:48:49 +11:00
Lucas 'Paperboy' Rose-Winters 3473f2ac44 refactor(features): extract classic stats controls to standalone module
Extract setupClassicStatsButtons into src/systems/features/classicStats.js.
This module handles the delegated event listeners for classic RPG stat
+/- buttons (STR, DEX, CON, INT, WIS, CHA).

- Create classicStats.js with event delegation for stat buttons
- Update index.js to import and use the new module
- Maintain backward compatibility with existing functionality
2025-10-17 13:45:36 +11:00
Lucas 'Paperboy' Rose-Winters ba50fc5bdc refactor(features): extract plot progression UI to standalone module
Extract plot progression button setup from index.js into dedicated
feature module at src/systems/features/plotProgression.js.

Due to ES6 module import path limitations in deeply nested modules,
the generation logic (sendPlotProgression) remains in index.js where
it can properly import from SillyTavern's script.js. The UI setup
function accepts the generation function as a callback parameter.

Creates plotProgression.js with 62 lines of UI setup code.
Index.js increases from 800 to 869 lines (+69 for generation logic).
2025-10-17 13:39:24 +11:00
Lucas 'Paperboy' Rose-Winters 23fc9fdc9a refactor(ui): extract UI systems into modular architecture
Extracted ~920 lines of UI management code from index.js into 4 specialized modules to improve maintainability and organization.

Modules Created:
- src/systems/ui/theme.js (100 lines) - Theme management and custom colors
- src/systems/ui/modals.js (568 lines) - DiceModal and SettingsModal ES6 classes
- src/systems/ui/layout.js (254 lines) - Panel visibility, positioning, and collapse toggle
- src/systems/ui/mobile.js (694 lines) - Mobile FAB, tabs, keyboard handling, and viewport management

Changes:
- Extracted theme application and custom color management
- Extracted modal classes with proper state management
- Extracted layout management (visibility, sections, positioning)
- Extracted mobile-specific UI (FAB dragging with touch/mouse, tab navigation, keyboard handling)
- Removed unused import (closeMobilePanelWithAnimation only used internally by mobile.js)
- Updated imports in index.js to use new module structure
- Added comprehensive documentation comments

Result:
- index.js reduced from 1606 to 921 lines (-685 lines)
- All UI systems properly modularized with clean dependencies
- Maintains 100% backward compatibility
- All modules pass syntax validation

Dependencies:
- All modules import from src/core/state.js for shared state
- Mobile module imports layout functions for panel animation
- Layout module properly manages DOM element state
2025-10-17 13:02:11 +11:00
Lucas 'Paperboy' Rose-Winters ed4506dc68 fix(dice): replace const assignments with setter function calls
After modular refactor, `pendingDiceRoll` is imported as const from
state module and cannot be reassigned. Replace three direct assignments
with `setPendingDiceRoll()` setter function calls:
- DiceModal.close() method (line 572)
- Save roll button handler (line 691)
- rollDice() function (line 773)

Fixes "Assignment to constant variable" errors preventing dice rolls.
2025-10-17 12:26:40 +11:00
Lucas 'Paperboy' Rose-Winters d2d5593e00 refactor: extract rendering systems
Extract rendering logic from index.js into modular system:
- src/utils/avatars.js: Safe thumbnail URL generation with error handling
- src/systems/rendering/userStats.js: User stats panel with progress bars and classic RPG stats
- src/systems/rendering/infoBox.js: Info box dashboard with weather, date, time, and location widgets
- src/systems/rendering/thoughts.js: Character thoughts panel and floating chat bubbles

Reduces index.js from 3,829 to 2,430 lines (-1,399 lines, -36.5%)
All rendering functions now properly modularized with full JSDoc documentation
Event listeners preserved in render functions for interactive fields
2025-10-17 11:16:29 +11:00
Lucas 'Paperboy' Rose-Winters 17736d9140 feat: extract generation and parsing systems into modules
Extract AI generation and parsing logic from monolithic index.js into
modular architecture under src/systems/generation/.

**Modules Created:**
- promptBuilder.js (319 lines) - AI prompt generation functions
- parser.js (152 lines) - Response parsing and stats extraction
- apiClient.js (154 lines) - Separate mode API call handler
- injector.js (216 lines) - Prompt injection for both modes

**Changes:**
- All functions preserve exact behavior from original
- Import paths calculated for browser module resolution
- Zero functionality changes, pure code organization

Reduces index.js by ~700 lines when combined with function removal
(to be committed separately).
2025-10-17 10:38:35 +11:00
Lucas 'Paperboy' Rose-Winters 5c34407d2c refactor(core): extract core modules (state, persistence, config, events)
Extract core system modules from monolithic index.js into modular architecture:

- src/core/state.js: All extension state variables with controlled setters
- src/core/persistence.js: Settings and chat data persistence functions
- src/core/config.js: Extension metadata and default configuration
- src/core/events.js: SillyTavern event system wrapper

Updated index.js to import and use new core modules.
Removed ~220 lines of state/persistence code from index.js.

Part of Epic 1: Foundation & Core Systems (Phase 1.1-1.2)
2025-10-17 09:13:19 +11:00
Lucas 'Paperboy' Rose-Winters 1db709693d fix: use base64-encoded SVG for avatar fallback to prevent HTML parsing errors
The previous URL-encoded SVG had unencoded quotes that broke HTML attribute parsing.
The browser would misinterpret xmlns="http://www.w3.org/2000/svg" as separate HTML
attributes, causing broken image rendering.

Changes:
- Add FALLBACK_AVATAR_DATA_URI constant with base64-encoded SVG
- Replace all instances of broken inline transparentPixel variable (3 locations)
- Update comparison check to use the new constant

The base64 encoding ensures the data URI is safely embedded in HTML src attributes
without any quote-escaping issues.
2025-10-17 03:15:23 +11:00
Lucas 'Paperboy' Rose-Winters 66712382d5 fix: eliminate 400 Bad Request errors for persona avatar thumbnails
- Add getSafeThumbnailUrl() helper function with comprehensive error handling
- Replace all getThumbnailUrl() calls with safe wrapper that validates results
- Use SVG data URI placeholder instead of 'img/user-default.png' to avoid 400 errors
- Update img onerror handlers to fade opacity instead of trying invalid fallback paths
- Add detailed console logging for debugging avatar loading issues
- Improve updatePersonaAvatar() to only update src when valid URL is available

This fixes persistent 400 errors on some Ubuntu systems where directory names
with spaces (e.g., "User Avatars") caused thumbnail URL construction to fail.

Affected functions:
- getSafeThumbnailUrl() (new)
- updatePersonaAvatar()
- renderUserStats()
- renderCharacterThoughts()
2025-10-17 03:05:37 +11:00