Fix TTS module initialization and dependency issues. Update module IDs for consistency, improve circular dependency detection, and fix UI Controller event handling.

This commit is contained in:
2025-04-04 19:15:28 +00:00
parent 02c7b9ef28
commit 49a5af252c
33 changed files with 7227 additions and 4060 deletions
+408 -232
View File
@@ -11,35 +11,71 @@ class PersistenceManagerModule extends BaseModule {
*/
constructor() {
super('persistence-manager', 'Persistence Manager');
this.storage = window.localStorage;
this.stateKey = 'ai_fiction_state';
this.prefsKey = 'ai_fiction_prefs';
// Storage keys
this.keys = {
gameState: 'ai-interactive-fiction-state',
preferences: 'ai-interactive-fiction-preferences',
saveSlots: 'ai-interactive-fiction-saves'
};
// Current game state
this.gameState = null;
// User preferences
this.preferences = null;
// Save slots
this.saveSlots = {};
// Default preferences
this.defaultPreferences = {
animation: {
enabled: true,
speed: 50 // 0-100 scale, 50 is default
},
tts: {
enabled: false,
provider: 'browser', // 'browser', 'kokoro', 'elevenlabs'
provider: 'browser', // 'browser', 'api', 'kokoro'
voice: '',
volume: 1.0
volume: 1.0,
rate: 1.0,
language: 'en-us' // Default language, will be updated during initialization
},
audio: {
masterVolume: 1.0,
musicVolume: 0.7,
sfxVolume: 1.0
},
animation: {
speed: 50, // 0-100 scale
fastForwardKey: ' ' // Space key
sfxVolume: 1.0,
musicEnabled: true,
sfxEnabled: true
},
accessibility: {
highContrast: false,
largerText: false
},
app: {
locale: 'en-us',
theme: 'default'
}
};
// Current preferences (will be loaded from storage)
this.preferences = { ...this.defaultPreferences };
// Bind methods
this.bindMethods([
'saveGameState',
'loadGameState',
'savePreferences',
'loadPreferences',
'getPreference',
'updatePreference',
'resetPreferences',
'createSaveSlot',
'loadSaveSlot',
'deleteSaveSlot',
'getAllSaveSlots'
]);
// Add localization as a dependency
this.dependencies = ['localization'];
}
/**
@@ -48,224 +84,186 @@ class PersistenceManagerModule extends BaseModule {
*/
async initialize() {
try {
// Test storage availability
this.storage = this.getStorageObject();
this.reportProgress(10, "Initializing persistence manager");
// Load preferences automatically
// Load preferences first (with default language settings)
this.loadPreferences();
// Load save slots
this.loadSaveSlots();
// Get localization module
const localization = this.getModule('localization');
if (localization) {
// Update language preferences with current language
const language = localization.getLanguage();
// Update default preferences
this.defaultPreferences.tts.language = language;
this.defaultPreferences.app.locale = language;
// Update current preferences if they exist
if (this.preferences) {
// Only update if not already set by user
if (!this.preferences.tts.language || this.preferences.tts.language === 'en-us') {
this.preferences.tts.language = language;
}
if (!this.preferences.app.locale || this.preferences.app.locale === 'en-us') {
this.preferences.app.locale = language;
}
// Save updated preferences
this.savePreferences();
}
this.reportProgress(80, "Updated language preferences");
} else {
console.warn("Localization module not found or not ready, using default language settings");
// We'll continue without localization - it might initialize later
this.reportProgress(80, "Using default language settings");
}
this.reportProgress(100, "Persistence manager ready");
return true;
} catch (error) {
console.error("Error initializing persistence manager:", error);
// Continue without persistence rather than failing
return true;
this.reportProgress(100, "Persistence manager failed");
return false;
}
}
/**
* Get the appropriate storage object, testing availability
* @returns {Storage} - The storage object to use
*/
getStorageObject() {
try {
// Test if localStorage is available
if (window.localStorage) {
const testKey = '__storage_test__';
window.localStorage.setItem(testKey, testKey);
window.localStorage.removeItem(testKey);
return window.localStorage;
}
} catch (e) {
console.warn('localStorage not available, using memory storage');
// Create a memory-based storage fallback
return this.createMemoryStorage();
}
console.warn('localStorage not available, using memory storage');
return this.createMemoryStorage();
}
/**
* Create a memory-based storage fallback
* @returns {Object} - A storage-like object
*/
createMemoryStorage() {
const memoryStore = {};
return {
getItem: (key) => memoryStore[key] || null,
setItem: (key, value) => {
memoryStore[key] = String(value);
},
removeItem: (key) => {
delete memoryStore[key];
},
clear: () => {
Object.keys(memoryStore).forEach(key => {
delete memoryStore[key];
});
}
};
}
/**
* Save the current game state
* @param {Object} state - The game state to save
* @param {Object} state - Game state to save
* @returns {boolean} - Success status
*/
saveState(state) {
if (!this.storage) {
console.warn('No storage available, game state not saved.');
return false;
}
saveGameState(state) {
if (!state) return false;
try {
const stateString = JSON.stringify(state);
this.storage.setItem(this.stateKey, stateString);
console.log('Game state saved successfully.');
return true;
} catch (error) {
console.error('Error saving game state:', error);
return false;
}
}
/**
* Load the saved game state
* @returns {Object|null} The loaded state or null if no state exists
*/
loadState() {
if (!this.storage) {
console.warn('No storage available, cannot load game state.');
return null;
}
try {
const stateString = this.storage.getItem(this.stateKey);
if (!stateString) {
console.info('No saved game state found.');
return null;
}
this.gameState = state;
localStorage.setItem(this.keys.gameState, JSON.stringify(state));
const state = JSON.parse(stateString);
console.log('Game state loaded successfully.');
return state;
// Dispatch event
this.dispatchEvent('game-state-saved', {
timestamp: new Date().toISOString()
});
return true;
} catch (error) {
console.error('Error loading game state:', error);
return null;
console.error("Error saving game state:", error);
return false;
}
}
/**
* Check if a saved game state exists
* @returns {boolean} Whether a saved state exists
* Load the current game state
* @returns {Object|null} - Loaded game state or null if not found
*/
hasSavedState() {
if (!this.storage) return false;
return !!this.storage.getItem(this.stateKey);
}
/**
* Delete the saved game state
* @returns {boolean} Whether the state was successfully deleted
*/
clearState() {
if (!this.storage) return false;
loadGameState() {
try {
this.storage.removeItem(this.stateKey);
console.log('Game state cleared.');
return true;
const stateJson = localStorage.getItem(this.keys.gameState);
if (!stateJson) return null;
this.gameState = JSON.parse(stateJson);
return this.gameState;
} catch (error) {
console.error('Error clearing game state:', error);
return false;
console.error("Error loading game state:", error);
return null;
}
}
/**
* Save user preferences
* @param {Object} [preferences] - Preferences to save (defaults to current preferences)
* @returns {boolean} Whether preferences were successfully saved
* @returns {boolean} - Success status
*/
savePreferences(preferences = null) {
if (!this.storage) {
console.warn('No storage available, preferences not saved.');
return false;
}
// Use provided preferences or current preferences
const prefsToSave = preferences || this.preferences;
savePreferences() {
try {
const prefsString = JSON.stringify(prefsToSave);
this.storage.setItem(this.prefsKey, prefsString);
console.log('Preferences saved successfully.');
localStorage.setItem(this.keys.preferences, JSON.stringify(this.preferences));
// Update current preferences
if (preferences) {
this.preferences = { ...this.preferences, ...preferences };
}
// Dispatch event
this.dispatchEvent('preferences-saved', {
timestamp: new Date().toISOString()
});
return true;
} catch (error) {
console.error('Error saving preferences:', error);
console.error("Error saving preferences:", error);
return false;
}
}
/**
* Load user preferences
* @returns {Object} The loaded preferences or default preferences if none exist
* @returns {Object} - Loaded preferences or default preferences if not found
*/
loadPreferences() {
if (!this.storage) {
console.warn('No storage available, using default preferences.');
return { ...this.defaultPreferences };
}
try {
const prefsString = this.storage.getItem(this.prefsKey);
if (!prefsString) {
console.info('No saved preferences found, using defaults.');
this.preferences = { ...this.defaultPreferences };
return this.preferences;
const prefsJson = localStorage.getItem(this.keys.preferences);
if (prefsJson) {
// Parse stored preferences
const storedPrefs = JSON.parse(prefsJson);
// Merge with default preferences to ensure all keys exist
this.preferences = this.mergeWithDefaults(storedPrefs, this.defaultPreferences);
} else {
// Use default preferences if none found
this.preferences = JSON.parse(JSON.stringify(this.defaultPreferences));
// Try to set locale based on browser language
const browserLocale = navigator.language.toLowerCase();
if (browserLocale) {
this.preferences.app.locale = browserLocale;
}
}
const loadedPrefs = JSON.parse(prefsString);
// Merge with default preferences to ensure all fields exist
this.preferences = this.mergeWithDefaults(loadedPrefs, this.defaultPreferences);
console.log('Preferences loaded successfully.');
return this.preferences;
} catch (error) {
console.error('Error loading preferences:', error);
this.preferences = { ...this.defaultPreferences };
console.error("Error loading preferences:", error);
// Fall back to default preferences
this.preferences = JSON.parse(JSON.stringify(this.defaultPreferences));
return this.preferences;
}
}
/**
* Merge loaded preferences with default values to ensure all fields exist
* @param {Object} loaded - The loaded preferences
* @param {Object} defaults - The default preferences
* @returns {Object} Merged preferences
* @private
* Merge stored preferences with defaults to ensure all keys exist
* @param {Object} stored - Stored preferences
* @param {Object} defaults - Default preferences
* @returns {Object} - Merged preferences
*/
mergeWithDefaults(loaded, defaults) {
mergeWithDefaults(stored, defaults) {
const result = {};
// Start with defaults
for (const key in defaults) {
if (typeof defaults[key] === 'object' && defaults[key] !== null && !Array.isArray(defaults[key])) {
// Recurse for nested objects
if (loaded && loaded[key]) {
result[key] = this.mergeWithDefaults(loaded[key], defaults[key]);
} else {
result[key] = { ...defaults[key] };
// For each category in defaults
for (const category in defaults) {
result[category] = {};
// Copy all settings from defaults for this category
for (const setting in defaults[category]) {
// Use stored value if it exists, otherwise use default
result[category][setting] = (stored[category] && stored[category][setting] !== undefined)
? stored[category][setting]
: defaults[category][setting];
}
// Copy any additional settings from stored that aren't in defaults
if (stored[category]) {
for (const setting in stored[category]) {
if (result[category][setting] === undefined) {
result[category][setting] = stored[category][setting];
}
}
} else {
// Use loaded value if available, otherwise default
result[key] = (loaded && loaded[key] !== undefined) ? loaded[key] : defaults[key];
}
}
// Copy any additional categories from stored that aren't in defaults
for (const category in stored) {
if (result[category] === undefined) {
result[category] = stored[category];
}
}
@@ -273,81 +271,262 @@ class PersistenceManagerModule extends BaseModule {
}
/**
* Update specific preferences
* @param {string} category - The preference category (e.g., 'tts', 'audio')
* @param {string} setting - The specific setting name
* @param {any} value - The new value
* @param {boolean} [saveImmediately=true] - Whether to save immediately
*/
updatePreference(category, setting, value, saveImmediately = true) {
// Ensure the category exists
if (!this.preferences[category]) {
console.warn(`Preference category '${category}' doesn't exist.`);
return false;
}
// Update the preference
this.preferences[category][setting] = value;
// Save if requested
if (saveImmediately) {
return this.savePreferences();
}
return true;
}
/**
* Get a specific preference value
* @param {string} category - The preference category
* @param {string} setting - The specific setting name
* @param {any} [defaultValue] - Default value if the preference doesn't exist
* @returns {any} The preference value
* Get a specific preference
* @param {string} category - Preference category
* @param {string} setting - Preference setting
* @param {*} defaultValue - Default value if preference not found
* @returns {*} - Preference value
*/
getPreference(category, setting, defaultValue = null) {
// Check if category exists
if (!this.preferences[category]) {
return defaultValue;
if (!this.preferences) {
this.loadPreferences();
}
// Check if setting exists in category
if (this.preferences[category].hasOwnProperty(setting)) {
if (this.preferences[category] && this.preferences[category][setting] !== undefined) {
return this.preferences[category][setting];
}
return defaultValue;
// If default value provided, use it
if (defaultValue !== null) {
return defaultValue;
}
// Otherwise check default preferences
if (this.defaultPreferences[category] && this.defaultPreferences[category][setting] !== undefined) {
return this.defaultPreferences[category][setting];
}
// If all else fails, return null
return null;
}
/**
* Update a specific preference
* @param {string} category - Preference category
* @param {string} setting - Preference setting
* @param {*} value - New value
* @returns {boolean} - Success status
*/
updatePreference(category, setting, value) {
if (!this.preferences) {
this.loadPreferences();
}
// Create category if it doesn't exist
if (!this.preferences[category]) {
this.preferences[category] = {};
}
// Update preference
const oldValue = this.preferences[category][setting];
this.preferences[category][setting] = value;
// Save preferences
this.savePreferences();
// Dispatch event if value changed
if (oldValue !== value) {
this.dispatchEvent('preference-changed', {
category,
setting,
value,
oldValue
});
}
return true;
}
/**
* Reset preferences to defaults
* @param {string} [category] - Optional category to reset (resets all if not specified)
* @param {boolean} [saveImmediately=true] - Whether to save immediately
* @returns {boolean} - Success status
*/
resetPreferences(category = null, saveImmediately = true) {
if (category) {
// Reset only specified category
if (this.defaultPreferences[category]) {
this.preferences[category] = { ...this.defaultPreferences[category] };
}
} else {
// Reset all preferences
this.preferences = { ...this.defaultPreferences };
resetPreferences() {
try {
// Clone default preferences
this.preferences = JSON.parse(JSON.stringify(this.defaultPreferences));
// Save preferences
this.savePreferences();
// Dispatch event
this.dispatchEvent('preferences-reset', {
timestamp: new Date().toISOString()
});
return true;
} catch (error) {
console.error("Error resetting preferences:", error);
return false;
}
// Save if requested
if (saveImmediately) {
return this.savePreferences();
}
return true;
}
/**
* Get all preferences
* @returns {Object} The current preferences
* @returns {Object} - All preferences
*/
getAllPreferences() {
return { ...this.preferences };
if (!this.preferences) {
this.loadPreferences();
}
return this.preferences;
}
/**
* Load save slots
* @returns {Object} - Save slots
*/
loadSaveSlots() {
try {
const slotsJson = localStorage.getItem(this.keys.saveSlots);
if (slotsJson) {
this.saveSlots = JSON.parse(slotsJson);
} else {
this.saveSlots = {};
}
return this.saveSlots;
} catch (error) {
console.error("Error loading save slots:", error);
this.saveSlots = {};
return this.saveSlots;
}
}
/**
* Save save slots
* @returns {boolean} - Success status
*/
saveSaveSlots() {
try {
localStorage.setItem(this.keys.saveSlots, JSON.stringify(this.saveSlots));
return true;
} catch (error) {
console.error("Error saving save slots:", error);
return false;
}
}
/**
* Create a new save slot
* @param {string} name - Save slot name
* @param {Object} state - Game state to save
* @returns {string|null} - Save slot ID or null if failed
*/
createSaveSlot(name, state) {
if (!name || !state) return null;
try {
// Generate unique ID
const id = `save_${Date.now()}`;
// Create save slot
this.saveSlots[id] = {
id,
name,
timestamp: new Date().toISOString(),
state
};
// Save save slots
this.saveSaveSlots();
// Dispatch event
this.dispatchEvent('save-slot-created', {
id,
name,
timestamp: new Date().toISOString()
});
return id;
} catch (error) {
console.error("Error creating save slot:", error);
return null;
}
}
/**
* Load a save slot
* @param {string} id - Save slot ID
* @returns {Object|null} - Game state or null if not found
*/
loadSaveSlot(id) {
if (!id || !this.saveSlots[id]) return null;
try {
const saveSlot = this.saveSlots[id];
// Set as current game state
this.gameState = saveSlot.state;
// Save current game state
this.saveGameState(this.gameState);
// Dispatch event
this.dispatchEvent('save-slot-loaded', {
id,
name: saveSlot.name,
timestamp: new Date().toISOString()
});
return this.gameState;
} catch (error) {
console.error("Error loading save slot:", error);
return null;
}
}
/**
* Delete a save slot
* @param {string} id - Save slot ID
* @returns {boolean} - Success status
*/
deleteSaveSlot(id) {
if (!id || !this.saveSlots[id]) return false;
try {
// Get save slot name before deleting
const name = this.saveSlots[id].name;
// Delete save slot
delete this.saveSlots[id];
// Save save slots
this.saveSaveSlots();
// Dispatch event
this.dispatchEvent('save-slot-deleted', {
id,
name,
timestamp: new Date().toISOString()
});
return true;
} catch (error) {
console.error("Error deleting save slot:", error);
return false;
}
}
/**
* Get all save slots
* @returns {Object} - All save slots
*/
getAllSaveSlots() {
if (!this.saveSlots) {
this.loadSaveSlots();
}
return this.saveSlots;
}
/**
* Clean up when module is disposed
*/
dispose() {
// Nothing to clean up
}
}
@@ -359,6 +538,3 @@ moduleRegistry.register(PersistenceManager);
// Export the module
export { PersistenceManager };
// Keep a reference in window for loader system
window.PersistenceManager = PersistenceManager;