Completed options menu and got kokoro to load.
This commit is contained in:
+665
-629
File diff suppressed because it is too large
Load Diff
@@ -1,123 +0,0 @@
|
||||
/**
|
||||
* Kokoro Web Worker
|
||||
* Handles TTS processing in a separate thread to keep UI responsive
|
||||
*/
|
||||
|
||||
// Global variables
|
||||
let kokoroLoaded = false;
|
||||
let isProcessing = false;
|
||||
let voiceOptions = {
|
||||
voice: 'bf_alice',
|
||||
speed: 1.0
|
||||
};
|
||||
|
||||
// Initialize when receiving init message
|
||||
self.onmessage = function(e) {
|
||||
const message = e.data;
|
||||
|
||||
try {
|
||||
switch (message.type) {
|
||||
case 'init':
|
||||
// Just acknowledge initialization - actual model loading happens on first generate call
|
||||
self.postMessage({ type: 'ready' });
|
||||
break;
|
||||
|
||||
case 'generate':
|
||||
if (!message.text) {
|
||||
self.postMessage({
|
||||
type: 'error',
|
||||
error: 'No text provided for generation'
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Store voice options
|
||||
if (message.voice) voiceOptions.voice = message.voice;
|
||||
if (message.speed) voiceOptions.speed = message.speed;
|
||||
|
||||
// Generate speech
|
||||
generateSpeech(message.text)
|
||||
.then(result => {
|
||||
self.postMessage({
|
||||
type: 'generated',
|
||||
result: result
|
||||
}, [result.audio.buffer]);
|
||||
})
|
||||
.catch(error => {
|
||||
self.postMessage({
|
||||
type: 'error',
|
||||
error: `Generation error: ${error.message || error}`
|
||||
});
|
||||
});
|
||||
break;
|
||||
|
||||
default:
|
||||
self.postMessage({
|
||||
type: 'error',
|
||||
error: `Unknown message type: ${message.type}`
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
self.postMessage({
|
||||
type: 'error',
|
||||
error: `Worker error: ${error.message || error}`
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Generate speech from text
|
||||
* @param {string} text - Text to convert to speech
|
||||
*/
|
||||
async function generateSpeech(text) {
|
||||
if (isProcessing) {
|
||||
throw new Error('Already processing another request');
|
||||
}
|
||||
|
||||
isProcessing = true;
|
||||
|
||||
try {
|
||||
// Load Kokoro if not already loaded
|
||||
if (!kokoroLoaded) {
|
||||
try {
|
||||
// Load the Kokoro script
|
||||
self.importScripts('/js/kokoro.js');
|
||||
|
||||
if (!self.Kokoro) {
|
||||
throw new Error('Kokoro failed to load correctly');
|
||||
}
|
||||
|
||||
kokoroLoaded = true;
|
||||
console.log('Kokoro loaded in worker');
|
||||
} catch (loadError) {
|
||||
console.error('Error loading Kokoro in worker:', loadError);
|
||||
throw new Error(`Failed to load Kokoro: ${loadError.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Generate speech using Kokoro
|
||||
const result = await self.Kokoro(text, {
|
||||
voice: voiceOptions.voice,
|
||||
speed: voiceOptions.speed,
|
||||
autoPlay: false
|
||||
});
|
||||
|
||||
// Extract audio data
|
||||
const audioContext = new (self.AudioContext || self.webkitAudioContext)();
|
||||
const audioBuffer = await audioContext.decodeAudioData(result.buffer);
|
||||
|
||||
// Get audio data as Float32Array
|
||||
const audioData = audioBuffer.getChannelData(0);
|
||||
|
||||
// Return the result
|
||||
return {
|
||||
audio: audioData,
|
||||
sampling_rate: audioBuffer.sampleRate
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error generating speech in worker:', error);
|
||||
throw error;
|
||||
} finally {
|
||||
isProcessing = false;
|
||||
}
|
||||
}
|
||||
+37
-26
@@ -22,20 +22,7 @@ class LocalizationModule extends BaseModule {
|
||||
this.languageNames = {
|
||||
'en-us': 'English (US)',
|
||||
'en-gb': 'English (UK)',
|
||||
'de': 'Deutsch',
|
||||
'de-de': 'Deutsch (Deutschland)',
|
||||
'fr': 'Français',
|
||||
'fr-fr': 'Français (France)',
|
||||
'es': 'Español',
|
||||
'es-es': 'Español (España)',
|
||||
'it': 'Italiano',
|
||||
'ja': 'Japanese',
|
||||
'ko': 'Korean',
|
||||
'zh': 'Chinese (Simplified)',
|
||||
'zh-tw': 'Chinese (Traditional)',
|
||||
'ru': 'Russian',
|
||||
'pt': 'Portuguese',
|
||||
'pt-br': 'Portuguese (Brazil)'
|
||||
'de-de': 'Deutsch (Deutschland)'
|
||||
};
|
||||
|
||||
// Bind methods
|
||||
@@ -57,23 +44,47 @@ class LocalizationModule extends BaseModule {
|
||||
try {
|
||||
this.reportProgress(10, "Initializing localization");
|
||||
|
||||
// Load default translations
|
||||
await this.loadTranslations('en-us');
|
||||
|
||||
// Try to load browser locale if available
|
||||
const browserLocale = navigator.language.toLowerCase();
|
||||
if (browserLocale && browserLocale !== 'en-us') {
|
||||
// Get stored locale from persistence manager if available
|
||||
const persistenceManager = this.getModule('persistence-manager');
|
||||
let storedLocale = null;
|
||||
|
||||
if (persistenceManager) {
|
||||
try {
|
||||
this.reportProgress(50, `Loading browser locale: ${browserLocale}`);
|
||||
await this.loadTranslations(browserLocale);
|
||||
this.currentLocale = browserLocale;
|
||||
} catch (localeError) {
|
||||
console.warn(`Failed to load browser locale ${browserLocale}:`, localeError);
|
||||
storedLocale = persistenceManager.getPreference('app', 'locale');
|
||||
if (storedLocale) {
|
||||
console.log(`Localization: Found stored locale: ${storedLocale}`);
|
||||
await this.loadTranslations(storedLocale);
|
||||
this.currentLocale = storedLocale;
|
||||
} else {
|
||||
// If no stored locale, ensure English is the default and persist it
|
||||
console.log('Localization: No stored locale found, defaulting to en-us');
|
||||
await this.loadTranslations('en-us');
|
||||
persistenceManager.updatePreference('app', 'locale', 'en-us');
|
||||
persistenceManager.updatePreference('tts', 'language', 'en-us');
|
||||
this.currentLocale = 'en-us';
|
||||
}
|
||||
} catch (persistError) {
|
||||
console.warn(`Failed to load stored locale:`, persistError);
|
||||
}
|
||||
} else {
|
||||
// If browser locale is available, just load it as a fallback but keep English as default
|
||||
const browserLocale = navigator.language.toLowerCase();
|
||||
if (browserLocale && browserLocale !== 'en-us') {
|
||||
try {
|
||||
this.reportProgress(50, `Loading browser locale as fallback: ${browserLocale}`);
|
||||
await this.loadTranslations(browserLocale);
|
||||
// Do NOT set browser locale as current - keep English as default
|
||||
} catch (localeError) {
|
||||
console.warn(`Failed to load browser locale ${browserLocale}:`, localeError);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// We don't check for persistence manager here to avoid circular dependency
|
||||
// The persistence manager will update our locale after it initializes if needed
|
||||
// Dispatch event to notify about loaded locale
|
||||
document.dispatchEvent(new CustomEvent('localization:languageChanged', {
|
||||
detail: { locale: this.currentLocale }
|
||||
}));
|
||||
|
||||
this.reportProgress(100, "Localization ready");
|
||||
return true;
|
||||
|
||||
+708
-928
File diff suppressed because it is too large
Load Diff
@@ -181,7 +181,15 @@ class TextProcessorModule extends BaseModule {
|
||||
// Define a custom loader for the patterns
|
||||
loader: (file) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const patternPath = `/js/patterns/${file}`;
|
||||
// Determine correct pattern file based on locale
|
||||
let patternFile = file;
|
||||
|
||||
// Special handling for 'en' locale - use en-us.wasm if available
|
||||
if (file === 'en.wasm') {
|
||||
patternFile = 'en-us.wasm';
|
||||
}
|
||||
|
||||
const patternPath = `/js/patterns/${patternFile}`;
|
||||
console.log(`Loading hyphenation pattern: ${patternPath}`);
|
||||
|
||||
fetch(patternPath)
|
||||
|
||||
+163
-84
@@ -15,21 +15,33 @@ class TTSFactoryModule extends BaseModule {
|
||||
constructor() {
|
||||
super('tts-factory', 'TTS Factory');
|
||||
|
||||
// Available TTS handlers
|
||||
this.dependencies = ['persistence-manager', 'localization'];
|
||||
this.handlers = {};
|
||||
|
||||
// Current active handler
|
||||
this.initStatus = {};
|
||||
this.activeHandler = null;
|
||||
|
||||
// Handler initialization status
|
||||
this.initStatus = {
|
||||
browser: false,
|
||||
api: false,
|
||||
kokoro: false
|
||||
};
|
||||
|
||||
// TTS availability flag
|
||||
this.ttsAvailable = false;
|
||||
this.speed = 1; // Default speed
|
||||
|
||||
// Listen for kokoro:ready event
|
||||
document.addEventListener('kokoro:ready', (event) => {
|
||||
if (event.detail && typeof event.detail.success === 'boolean') {
|
||||
console.log('TTS Factory: Received kokoro:ready event with success =', event.detail.success);
|
||||
this.initStatus['kokoro'] = event.detail.success;
|
||||
|
||||
// If this is the current active handler or we don't have an active handler yet,
|
||||
// try to activate Kokoro if it's now ready
|
||||
if ((this.activeHandler === 'kokoro' || !this.activeHandler) && event.detail.success) {
|
||||
// Only attempt to set active handler if TTS is enabled
|
||||
const ttsEnabled = this.getPreference('tts', 'enabled', false);
|
||||
if (ttsEnabled) {
|
||||
this.setActiveHandler('kokoro');
|
||||
}
|
||||
}
|
||||
|
||||
// Update overall TTS availability
|
||||
this.updateTTSAvailability();
|
||||
}
|
||||
});
|
||||
|
||||
// Bind methods
|
||||
this.bindMethods([
|
||||
@@ -45,11 +57,9 @@ class TTSFactoryModule extends BaseModule {
|
||||
'resume',
|
||||
'getVoices',
|
||||
'getPreference',
|
||||
'isSpeaking'
|
||||
'isSpeaking',
|
||||
'configure'
|
||||
]);
|
||||
|
||||
// Add dependencies
|
||||
this.dependencies = ['persistence-manager', 'localization'];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -75,19 +85,37 @@ class TTSFactoryModule extends BaseModule {
|
||||
this.registerHandler('api', new ApiTTSHandler());
|
||||
this.registerHandler('kokoro', new KokoroHandler());
|
||||
|
||||
console.log('TTS Factory: Registered handlers:', Object.keys(this.handlers));
|
||||
this.reportProgress(30, "Registered TTS handlers");
|
||||
|
||||
// Force the initialization of all handlers for diagnostics
|
||||
// This ensures they're all initialized even if not selected
|
||||
const initPromises = [];
|
||||
for (const id of Object.keys(this.handlers)) {
|
||||
console.log(`TTS Factory: Initializing handler ${id}`);
|
||||
initPromises.push(this.initializeHandler(id).then(success => {
|
||||
console.log(`TTS Factory: Handler ${id} initialization ${success ? 'succeeded' : 'failed'}`);
|
||||
return { id, success };
|
||||
}));
|
||||
}
|
||||
|
||||
// Wait for all handlers to initialize
|
||||
const results = await Promise.all(initPromises);
|
||||
console.log('TTS Factory: All handler initialization results:', results);
|
||||
|
||||
// Get user preferences
|
||||
const ttsEnabled = this.getPreference('tts', 'enabled', false);
|
||||
const preferredProvider = this.getPreference('tts', 'provider', 'browser');
|
||||
|
||||
console.log(`TTS Factory: User preferences - enabled: ${ttsEnabled}, provider: ${preferredProvider}`);
|
||||
|
||||
// Initialize handlers based on preferences
|
||||
let initSuccess = false;
|
||||
|
||||
if (ttsEnabled) {
|
||||
// Try to initialize preferred handler first
|
||||
this.reportProgress(50, `Initializing preferred TTS handler: ${preferredProvider}`);
|
||||
initSuccess = await this.initializeHandler(preferredProvider);
|
||||
initSuccess = this.initStatus[preferredProvider] || false;
|
||||
|
||||
if (initSuccess) {
|
||||
this.setActiveHandler(preferredProvider);
|
||||
@@ -96,71 +124,44 @@ class TTSFactoryModule extends BaseModule {
|
||||
console.warn(`Failed to initialize preferred TTS handler: ${preferredProvider}, trying alternatives`);
|
||||
|
||||
// Try Kokoro TTS as fallback if not already tried
|
||||
if (preferredProvider !== 'kokoro') {
|
||||
this.reportProgress(60, "Trying Kokoro TTS as fallback");
|
||||
initSuccess = await this.initializeHandler('kokoro');
|
||||
if (initSuccess) {
|
||||
this.setActiveHandler('kokoro');
|
||||
// Update preference to Kokoro since it worked
|
||||
this.getModule('persistence-manager').updatePreference('tts', 'provider', 'kokoro');
|
||||
}
|
||||
if (preferredProvider !== 'kokoro' && this.initStatus.kokoro) {
|
||||
this.reportProgress(60, "Using Kokoro TTS as fallback");
|
||||
this.setActiveHandler('kokoro');
|
||||
// Update preference to Kokoro since it worked
|
||||
this.getModule('persistence-manager').updatePreference('tts', 'provider', 'kokoro');
|
||||
initSuccess = true;
|
||||
}
|
||||
|
||||
// If Kokoro TTS failed, try Browser TTS
|
||||
if (!initSuccess && preferredProvider !== 'browser') {
|
||||
this.reportProgress(70, "Trying Browser TTS as fallback");
|
||||
initSuccess = await this.initializeHandler('browser');
|
||||
if (initSuccess) {
|
||||
this.setActiveHandler('browser');
|
||||
// Update preference to browser since it worked
|
||||
this.getModule('persistence-manager').updatePreference('tts', 'provider', 'browser');
|
||||
}
|
||||
// Try Browser TTS as fallback if not already tried
|
||||
else if (preferredProvider !== 'browser' && this.initStatus.browser) {
|
||||
this.reportProgress(70, "Using Browser TTS as fallback");
|
||||
this.setActiveHandler('browser');
|
||||
// Update preference to Browser since it worked
|
||||
this.getModule('persistence-manager').updatePreference('tts', 'provider', 'browser');
|
||||
initSuccess = true;
|
||||
}
|
||||
else {
|
||||
// If all failed, disable TTS
|
||||
this.reportProgress(80, "All TTS handlers failed, disabling TTS");
|
||||
this.getModule('persistence-manager').updatePreference('tts', 'enabled', false);
|
||||
this.getModule('persistence-manager').updatePreference('tts', 'provider', 'none');
|
||||
}
|
||||
|
||||
// Note: API TTS is not used as a fallback as it requires manual configuration
|
||||
}
|
||||
} else {
|
||||
// Even if TTS is disabled, initialize handlers in the background
|
||||
// so they're ready if the user enables TTS later
|
||||
this.reportProgress(50, "TTS disabled, initializing handlers in background");
|
||||
|
||||
// Initialize Kokoro and Browser handlers in parallel (not API as it requires configuration)
|
||||
const initPromises = [
|
||||
this.initializeHandler('kokoro'),
|
||||
this.initializeHandler('browser')
|
||||
];
|
||||
|
||||
// Wait for all handlers to initialize
|
||||
await Promise.allSettled(initPromises);
|
||||
|
||||
// Check if any handler initialized successfully
|
||||
initSuccess = this.initStatus.kokoro || this.initStatus.browser;
|
||||
}
|
||||
|
||||
// Set TTS availability flag and dispatch event
|
||||
this.ttsAvailable = initSuccess;
|
||||
// Determine overall TTS availability
|
||||
this.ttsAvailable = this.initStatus.kokoro || this.initStatus.browser;
|
||||
|
||||
// Dispatch event to notify UI about TTS availability
|
||||
document.dispatchEvent(new CustomEvent('tts:availability', {
|
||||
// Dispatch TTS availability event
|
||||
window.dispatchEvent(new CustomEvent('tts:availability', {
|
||||
detail: { available: this.ttsAvailable }
|
||||
}));
|
||||
|
||||
this.reportProgress(100, initSuccess ? "TTS factory ready" : "TTS factory ready (no handlers available)");
|
||||
|
||||
// Always return true since TTS is optional for the application
|
||||
return true;
|
||||
this.reportProgress(100, "TTS factory initialized");
|
||||
return true; // TTS is optional, so always return true
|
||||
} catch (error) {
|
||||
console.error("Error initializing TTS factory:", error);
|
||||
console.error("TTS Factory: Error during initialization:", error);
|
||||
this.reportProgress(100, "TTS factory failed");
|
||||
|
||||
// Set TTS availability to false and dispatch event
|
||||
this.ttsAvailable = false;
|
||||
document.dispatchEvent(new CustomEvent('tts:availability', {
|
||||
detail: { available: false }
|
||||
}));
|
||||
|
||||
// Still return true since TTS is optional
|
||||
return true;
|
||||
return true; // TTS is optional, so always return true
|
||||
}
|
||||
}
|
||||
|
||||
@@ -228,27 +229,43 @@ class TTSFactoryModule extends BaseModule {
|
||||
* @returns {boolean} - Success status
|
||||
*/
|
||||
setActiveHandler(id) {
|
||||
if (!id || !this.handlers[id] || !this.initStatus[id]) {
|
||||
console.warn(`Cannot set active handler to ${id}: handler not found or not initialized`);
|
||||
// Handle 'none' option specially
|
||||
if (id === 'none') {
|
||||
this.activeHandler = null;
|
||||
|
||||
// Update TTS availability state
|
||||
this.ttsAvailable = false;
|
||||
|
||||
// Notify about TTS availability change
|
||||
document.dispatchEvent(new CustomEvent('tts:availability', {
|
||||
detail: { available: false }
|
||||
}));
|
||||
|
||||
console.log("TTS Factory: TTS disabled (none selected)");
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!this.handlers[id]) {
|
||||
console.error(`TTS Factory: Handler not found: ${id}`);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Stop current handler if active
|
||||
if (this.activeHandler) {
|
||||
this.handlers[this.activeHandler].stop();
|
||||
if (!this.initStatus[id]) {
|
||||
console.error(`TTS Factory: Handler not initialized: ${id}`);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Set new active handler
|
||||
this.activeHandler = id;
|
||||
|
||||
// Update preference
|
||||
this.getModule('persistence-manager').updatePreference('tts', 'provider', id);
|
||||
// Update TTS availability state
|
||||
this.ttsAvailable = true;
|
||||
|
||||
// Dispatch event
|
||||
this.dispatchEvent('tts-handler-changed', {
|
||||
handler: id
|
||||
});
|
||||
// Notify about TTS availability change
|
||||
document.dispatchEvent(new CustomEvent('tts:availability', {
|
||||
detail: { available: true }
|
||||
}));
|
||||
|
||||
console.log(`TTS Factory: Active handler set to ${id}`);
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -268,8 +285,16 @@ class TTSFactoryModule extends BaseModule {
|
||||
getAvailableHandlers() {
|
||||
const available = {};
|
||||
|
||||
// Debug logging for diagnostic purposes
|
||||
console.log('TTS Factory: getAvailableHandlers called');
|
||||
console.log('TTS Factory: Current initialization status:', this.initStatus);
|
||||
console.log('TTS Factory: Registered handlers:', Object.keys(this.handlers).join(', '));
|
||||
|
||||
for (const id in this.handlers) {
|
||||
available[id] = this.initStatus[id];
|
||||
// Add the handler to the available list even if it's not initialized yet
|
||||
// This ensures all registered handlers appear in the options
|
||||
available[id] = true;
|
||||
console.log(`TTS Factory: Including handler ${id} in options`);
|
||||
}
|
||||
|
||||
return available;
|
||||
@@ -387,6 +412,60 @@ class TTSFactoryModule extends BaseModule {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update overall TTS availability
|
||||
*/
|
||||
updateTTSAvailability() {
|
||||
this.ttsAvailable = this.initStatus.kokoro || this.initStatus.browser;
|
||||
|
||||
// Dispatch TTS availability event
|
||||
window.dispatchEvent(new CustomEvent('tts:availability', {
|
||||
detail: { available: this.ttsAvailable }
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* Configure TTS settings for all handlers
|
||||
* @param {Object} options - TTS options
|
||||
* @param {number} [options.speed] - Normalized speech rate (0-1 range)
|
||||
*/
|
||||
configure(options = {}) {
|
||||
// If speed is provided, convert the normalized speed (0-1) to the appropriate scale for each handler
|
||||
if (typeof options.speed === 'number') {
|
||||
const normalizedSpeed = Math.max(0, Math.min(1, options.speed));
|
||||
|
||||
// Scale for each handler type
|
||||
for (const id in this.handlers) {
|
||||
// Ensure the handler exists and has the setVoiceOptions method
|
||||
if (this.handlers[id] && typeof this.handlers[id].setVoiceOptions === 'function') {
|
||||
let scaledOptions = {};
|
||||
|
||||
// Scale the speed value appropriately for each handler type
|
||||
if (id === 'browser') {
|
||||
// Browser TTS uses rate from 0.1 to 2.0
|
||||
scaledOptions.rate = 0.1 + (normalizedSpeed * 1.9);
|
||||
} else if (id === 'kokoro') {
|
||||
// Kokoro uses rate from 0.5 to 1.5
|
||||
scaledOptions.rate = 0.5 + (normalizedSpeed);
|
||||
} else if (id === 'api') {
|
||||
// API uses speed from 0.5 to 2.0
|
||||
scaledOptions.speed = 0.5 + (normalizedSpeed * 1.5);
|
||||
}
|
||||
|
||||
// Apply the scaled options to the handler
|
||||
this.handlers[id].setVoiceOptions(scaledOptions);
|
||||
}
|
||||
}
|
||||
|
||||
// Store the normalized value
|
||||
this.speed = normalizedSpeed;
|
||||
|
||||
console.log(`TTS Factory: Speed set to ${normalizedSpeed} (normalized), ${Math.round(normalizedSpeed * 100)}/100`);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean up when module is disposed
|
||||
*/
|
||||
|
||||
+189
-78
@@ -166,41 +166,102 @@ class UIController extends BaseModule {
|
||||
}
|
||||
|
||||
setupEventListeners() {
|
||||
// Listen for command events from input handler - use arrow function to preserve context
|
||||
document.addEventListener('ui:command', (event) => {
|
||||
this.handleCommand(event.detail);
|
||||
});
|
||||
// Set up event listeners for menu buttons
|
||||
const saveButton = document.getElementById('save');
|
||||
const loadButton = document.getElementById('reload');
|
||||
const restartButton = document.getElementById('rewind');
|
||||
const speechToggle = document.getElementById('speech');
|
||||
const optionsButton = document.getElementById('options');
|
||||
|
||||
// Listen for text display events - use arrow function to preserve context
|
||||
document.addEventListener('ui:text:complete', (event) => {
|
||||
console.log('UIController: Text complete event received, ready for next text');
|
||||
});
|
||||
// Get persistence manager module
|
||||
const persistenceManager = this.getModule('persistence-manager');
|
||||
|
||||
// Listen for socket connection events
|
||||
document.addEventListener('socket:connected', () => {
|
||||
console.log('UIController: Socket connected');
|
||||
this.updateButtonStates();
|
||||
});
|
||||
// Set up save button
|
||||
if (saveButton) {
|
||||
saveButton.addEventListener('click', () => {
|
||||
document.dispatchEvent(new CustomEvent('ui:game:save'));
|
||||
});
|
||||
}
|
||||
|
||||
document.addEventListener('socket:disconnected', () => {
|
||||
console.log('UIController: Socket disconnected');
|
||||
this.updateButtonStates();
|
||||
});
|
||||
// Set up load button
|
||||
if (loadButton) {
|
||||
loadButton.addEventListener('click', () => {
|
||||
document.dispatchEvent(new CustomEvent('ui:game:load'));
|
||||
});
|
||||
}
|
||||
|
||||
// Listen for TTS state change events
|
||||
document.addEventListener('tts:stateChange', (event) => {
|
||||
if (event.detail) {
|
||||
if (typeof event.detail.enabled === 'boolean') {
|
||||
this.ttsEnabled = event.detail.enabled;
|
||||
}
|
||||
if (typeof event.detail.available === 'boolean') {
|
||||
this.ttsAvailable = event.detail.available;
|
||||
}
|
||||
// Set up restart button
|
||||
if (restartButton) {
|
||||
restartButton.addEventListener('click', () => {
|
||||
document.dispatchEvent(new CustomEvent('ui:game:restart'));
|
||||
});
|
||||
}
|
||||
|
||||
// Set up speech toggle button
|
||||
if (speechToggle) {
|
||||
// Initialize ttsEnabled from persistence manager
|
||||
if (persistenceManager) {
|
||||
const prefs = persistenceManager.getAllPreferences();
|
||||
this.ttsEnabled = prefs.tts?.enabled ?? false;
|
||||
|
||||
// Update button state
|
||||
this.updateButtonStates();
|
||||
}
|
||||
|
||||
speechToggle.addEventListener('click', () => {
|
||||
// Toggle TTS state
|
||||
this.ttsEnabled = !this.ttsEnabled;
|
||||
|
||||
// Update UI
|
||||
this.updateButtonStates();
|
||||
|
||||
// Save preference
|
||||
if (persistenceManager) {
|
||||
persistenceManager.updatePreference('tts', 'enabled', this.ttsEnabled);
|
||||
}
|
||||
|
||||
// Notify other components
|
||||
document.dispatchEvent(new CustomEvent('ui:tts:toggle', {
|
||||
detail: { enabled: this.ttsEnabled }
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
// Set up options button
|
||||
if (optionsButton) {
|
||||
optionsButton.addEventListener('click', () => {
|
||||
document.dispatchEvent(new CustomEvent('ui:options:toggle'));
|
||||
});
|
||||
}
|
||||
|
||||
// Listen for book events
|
||||
document.addEventListener('book:ready', () => {
|
||||
this.updateButtonStates({
|
||||
canSave: true,
|
||||
canLoad: true,
|
||||
canRestart: true
|
||||
});
|
||||
});
|
||||
|
||||
// Listen for TTS availability events
|
||||
// Listen for restart events
|
||||
document.addEventListener('story:restart', () => {
|
||||
this.updateButtonStates({
|
||||
canSave: true,
|
||||
canLoad: false,
|
||||
canRestart: false
|
||||
});
|
||||
});
|
||||
|
||||
// Listen for save events
|
||||
document.addEventListener('story:save', () => {
|
||||
this.updateButtonStates({
|
||||
canSave: true,
|
||||
canLoad: true,
|
||||
canRestart: true
|
||||
});
|
||||
});
|
||||
|
||||
// Listen for TTS availability changes
|
||||
document.addEventListener('tts:availability', (event) => {
|
||||
if (event.detail && typeof event.detail.available === 'boolean') {
|
||||
this.ttsAvailable = event.detail.available;
|
||||
@@ -208,45 +269,92 @@ class UIController extends BaseModule {
|
||||
}
|
||||
});
|
||||
|
||||
// Add options button to controls section
|
||||
const controlsSection = document.getElementById('controls');
|
||||
if (controlsSection) {
|
||||
// Check if options button already exists
|
||||
if (!document.getElementById('options-button')) {
|
||||
const optionsButton = document.createElement('a');
|
||||
optionsButton.id = 'options-button';
|
||||
optionsButton.href = '#';
|
||||
optionsButton.textContent = 'options';
|
||||
optionsButton.title = 'Show game options';
|
||||
optionsButton.className = 'control-button';
|
||||
optionsButton.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
document.dispatchEvent(new CustomEvent('ui:showOptions'));
|
||||
});
|
||||
controlsSection.appendChild(optionsButton);
|
||||
}
|
||||
|
||||
// Add speech toggle button
|
||||
const speechToggle = document.getElementById('speech-toggle');
|
||||
if (speechToggle) {
|
||||
speechToggle.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
// Dispatch an event for the TTS module to handle instead of calling directly
|
||||
document.dispatchEvent(new CustomEvent('tts:toggle'));
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Listen for window resize events
|
||||
window.addEventListener('resize', () => {
|
||||
this.applyBookSizing();
|
||||
// Listen for TTS engine changes
|
||||
document.addEventListener('tts:engine:change', (event) => {
|
||||
// Update button states since TTS engine changed
|
||||
this.updateButtonStates();
|
||||
});
|
||||
|
||||
// Listen for key events
|
||||
document.addEventListener('keydown', (event) => {
|
||||
// Pass to input handler
|
||||
if (this.inputHandler) {
|
||||
this.inputHandler.handleKeyboardInput(event);
|
||||
// Listen for TTS toggle events from other components
|
||||
document.addEventListener('tts:enabled:change', (event) => {
|
||||
if (event.detail && typeof event.detail.enabled === 'boolean') {
|
||||
this.ttsEnabled = event.detail.enabled;
|
||||
this.updateButtonStates();
|
||||
|
||||
// Ensure persistence is updated
|
||||
if (persistenceManager) {
|
||||
persistenceManager.updatePreference('tts', 'enabled', this.ttsEnabled);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Set up speed slider in main UI
|
||||
const speedSlider = document.getElementById('speed');
|
||||
const speedReset = document.getElementById('speed_reset');
|
||||
|
||||
if (speedSlider) {
|
||||
// Initialize speed from persistence manager
|
||||
if (persistenceManager) {
|
||||
const prefs = persistenceManager.getAllPreferences();
|
||||
// Get the unified speed value (0-1 range)
|
||||
const speed = prefs.tts?.speed ?? 0.5;
|
||||
// Convert to slider range (0-100)
|
||||
speedSlider.value = Math.round(speed * 100);
|
||||
}
|
||||
|
||||
speedSlider.addEventListener('input', (e) => {
|
||||
// Convert slider value (0-100) to normalized speed (0-1)
|
||||
const speed = parseInt(e.target.value) / 100;
|
||||
|
||||
// Scale for different TTS engines
|
||||
// This value is used for real-time preview only
|
||||
const rate = this.ttsEnabled ? speed * 2 : 1;
|
||||
|
||||
// Update animation speed
|
||||
document.dispatchEvent(new CustomEvent('animation:speed:change', {
|
||||
detail: { speed: rate }
|
||||
}));
|
||||
|
||||
// Update TTS speed
|
||||
document.dispatchEvent(new CustomEvent('tts:speed:change', {
|
||||
detail: { speed: speed }
|
||||
}));
|
||||
|
||||
// Save preference
|
||||
if (persistenceManager) {
|
||||
persistenceManager.updatePreference('tts', 'speed', speed);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (speedReset) {
|
||||
speedReset.addEventListener('click', () => {
|
||||
// Reset to default speed (0.5)
|
||||
if (speedSlider) {
|
||||
// Default value is 0.5 in normalized form (0-1),
|
||||
// which is 50 in slider range (0-100)
|
||||
speedSlider.value = 50;
|
||||
|
||||
// Trigger the input event to update all components
|
||||
speedSlider.dispatchEvent(new Event('input'));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Listen for speed change events from other components
|
||||
document.addEventListener('tts:speed:change', (event) => {
|
||||
if (event.detail && typeof event.detail.speed === 'number') {
|
||||
// Update the main UI speed slider
|
||||
const speedSlider = document.getElementById('speed');
|
||||
if (speedSlider) {
|
||||
// Convert normalized speed (0-1) to slider range (0-100)
|
||||
speedSlider.value = Math.round(event.detail.speed * 100);
|
||||
}
|
||||
|
||||
// Save to persistence manager
|
||||
if (persistenceManager) {
|
||||
persistenceManager.updatePreference('tts', 'speed', event.detail.speed);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -342,7 +450,6 @@ class UIController extends BaseModule {
|
||||
|
||||
/**
|
||||
* Update UI button states based on game state
|
||||
* @param {Object} state - Game state information
|
||||
*/
|
||||
updateButtonStates(state = {}) {
|
||||
const { canSave, canLoad, canRestart } = state;
|
||||
@@ -351,7 +458,7 @@ class UIController extends BaseModule {
|
||||
const saveButton = document.getElementById('save');
|
||||
const loadButton = document.getElementById('reload');
|
||||
const restartButton = document.getElementById('rewind');
|
||||
const speechToggle = document.getElementById('speech-toggle');
|
||||
const speechToggle = document.getElementById('speech');
|
||||
|
||||
// Update save button state
|
||||
if (saveButton) {
|
||||
@@ -382,21 +489,25 @@ class UIController extends BaseModule {
|
||||
|
||||
// Update speech toggle button state
|
||||
if (speechToggle) {
|
||||
// Update the button appearance based on TTS state
|
||||
if (this.ttsEnabled) {
|
||||
speechToggle.classList.add('active');
|
||||
speechToggle.title = 'Disable speech';
|
||||
} else {
|
||||
speechToggle.classList.remove('active');
|
||||
speechToggle.title = 'Enable speech';
|
||||
}
|
||||
|
||||
// Disable the button completely if TTS is not available
|
||||
if (this.ttsAvailable === false) {
|
||||
// Update the button appearance based on TTS state using existing styles
|
||||
if (!this.ttsAvailable) {
|
||||
// TTS is not available, disable the button
|
||||
speechToggle.setAttribute('disabled', 'disabled');
|
||||
speechToggle.title = 'Speech not available';
|
||||
speechToggle.title = 'Text-to-speech is not available';
|
||||
} else {
|
||||
// TTS is available, remove disabled attribute
|
||||
speechToggle.removeAttribute('disabled');
|
||||
|
||||
// Update based on whether TTS is enabled
|
||||
if (this.ttsEnabled) {
|
||||
speechToggle.style.fontWeight = 'bold';
|
||||
speechToggle.style.color = '#000';
|
||||
speechToggle.title = 'Disable speech';
|
||||
} else {
|
||||
speechToggle.style.fontWeight = 'normal';
|
||||
speechToggle.style.color = '#999';
|
||||
speechToggle.title = 'Enable speech';
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -243,6 +243,7 @@ class UIDisplayHandler extends BaseModule {
|
||||
<a class="l10n-restart" id="rewind" title="Restart story from beginning" disabled="disabled">restart</a>
|
||||
<a class="l10n-save" id="save" title="Save progress">save</a>
|
||||
<a class="l10n-load" id="reload" title="Reload from save point" disabled="disabled">load</a>
|
||||
<a class="l10n-options" id="options" title="Options">options</a>
|
||||
`;
|
||||
this.pageLeft.appendChild(controls);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user