Files
ai.interactive.fiction/public/js/ai-fiction.js
T

528 lines
17 KiB
JavaScript

/**
* AI Interactive Fiction
* Main client-side logic for web interface
*/
class AIFiction {
constructor() {
// DOM elements
this.storyContainer = document.getElementById('story');
this.commandHistoryContainer = document.getElementById('command_history');
this.playerInput = document.getElementById('player_input');
this.submitButton = document.getElementById('submit_command');
this.speechButton = document.getElementById('speech');
this.rewindButton = document.getElementById('rewind');
this.saveButton = document.getElementById('save');
this.loadButton = document.getElementById('reload');
this.speedSlider = document.getElementById('speed');
this.speedReset = document.getElementById('speed_reset');
// Game state
this.gameState = {
started: false,
currentRoomId: '',
textSpeed: 50
};
// Socket connection - ensure we're connecting to the right URL
this.socket = io(window.location.origin, {
reconnectionAttempts: 5,
timeout: 10000
});
// Typing effect configuration
this.typingSpeed = 30; // Default value, will be adjusted by slider
this.typingTimeout = null;
// Check for kokoro-js being loaded (Now handled by factory)
// this.checkForKokoroJs(); // No longer needed here
// Bind event handlers
this.bindEvents();
// Initialize socket communication
this.initializeSocket();
// Initialize UI (TTS part will be updated by event)
this.initializeUI();
// Listen for TTS readiness
this.listenForTTSReady();
}
/**
* Check if kokoro-js is loaded
*/
checkForKokoroJs() {
try {
// With our TTS factory in place, we don't need to manually check for kokoro
// as the factory will handle loading and fallback automatically
console.log("TTS Factory will handle initialization of speech systems");
} catch (e) {
console.warn("Error checking for TTS systems:", e);
}
}
/**
* Initialize the UI (Initial state, TTS updated later)
*/
initializeUI() {
this.updateTypingSpeed();
// Start with speech button disabled, will be enabled by tts-ready event
this.speechButton.setAttribute('disabled', 'disabled');
this.speechButton.setAttribute('title', 'Initializing Text-to-Speech...');
this.updateSpeechButton(false);
// Disable other buttons initially
this.rewindButton.setAttribute('disabled', 'disabled');
this.loadButton.setAttribute('disabled', 'disabled');
// Start the game (if socket is ready)
if (this.socket && this.socket.connected) {
this.startGame();
} else {
console.log("Waiting for socket connection to start game...");
}
}
/**
* Listen for the tts-ready event from the factory
*/
listenForTTSReady() {
window.addEventListener('tts-ready', (event) => {
console.log('Received tts-ready event:', event.detail);
const { available, type, handler } = event.detail;
if (available) {
console.log(`TTS System active: ${type}`);
this.speechButton.removeAttribute('disabled');
const ttsName = type === 'kokoro' ? 'Kokoro TTS' : 'Browser TTS';
this.speechButton.setAttribute('title', `Text-to-Speech (${ttsName})`);
// Ensure the button style reflects the initial state (off)
this.updateSpeechButton(window.ttsHandler ? window.ttsHandler.isEnabled() : false);
} else {
console.warn("No TTS system available after initialization.");
this.speechButton.setAttribute('disabled', 'disabled');
this.speechButton.setAttribute('title', 'Text-to-Speech not available');
this.updateSpeechButton(false);
}
});
}
/**
* Bind event handlers to DOM elements
*/
bindEvents() {
// Submit command on button click
this.submitButton.addEventListener('click', () => this.submitCommand());
// Submit command on Enter key
this.playerInput.addEventListener('keydown', (e) => {
if (e.key === 'Enter') {
this.submitCommand();
}
});
// Toggle speech
this.speechButton.addEventListener('click', () => {
// Check if the handler is available (it should be if button is enabled)
if (window.ttsHandler) {
// Ensure AudioContext is resumed on user interaction if using Kokoro
if (window.ttsFactory && window.ttsFactory.usingKokoro && window.ttsHandler.audioContext && window.ttsHandler.audioContext.state === 'suspended') {
window.ttsHandler.audioContext.resume().catch(err => console.error('Error resuming AudioContext on click:', err));
}
// Set user activation flag for the handler
window.ttsHandler.hasUserActivation = true;
const enabled = window.ttsHandler.toggle();
this.updateSpeechButton(enabled);
if (enabled) {
// Speak the last narrative if speech was just enabled
const lastNarrative = this.storyContainer.lastElementChild;
if (lastNarrative && lastNarrative.classList.contains('narrative')) {
console.log("Speaking last narrative on toggle");
// Use a slight delay to ensure audio context is resumed
setTimeout(() => window.ttsHandler.speak(lastNarrative.textContent), 50);
}
// Update the tooltip with active TTS system info
if (window.ttsFactory) {
const ttsInfo = window.ttsFactory.getActiveTTSInfo();
this.speechButton.setAttribute('title', `Text-to-Speech (${ttsInfo.name})`);
}
} else {
// If disabling, ensure speech stops
window.ttsHandler.stop();
}
} else {
console.log('TTS handler not available when speech button clicked.');
// Optionally show an alert or keep button disabled
}
});
// Restart game
this.rewindButton.addEventListener('click', () => {
if (confirm('Are you sure you want to restart the game? All progress will be lost.')) {
this.startGame();
}
});
// Save game
this.saveButton.addEventListener('click', () => {
this.socket.emit('saveGame');
});
// Load game
this.loadButton.addEventListener('click', () => {
this.socket.emit('loadGame');
});
// Adjust typing speed
this.speedSlider.addEventListener('input', () => {
this.updateTypingSpeed();
});
// Reset speed to default
this.speedReset.addEventListener('click', () => {
this.speedSlider.value = 50;
this.updateTypingSpeed();
});
}
/**
* Initialize socket event handlers
*/
initializeSocket() {
// Connection established
this.socket.on('connect', () => {
console.log('Connected to server');
// Automatically start the game once connected
if (!this.gameState.started) {
this.startGame();
}
});
// Connection error
this.socket.on('connect_error', (error) => {
console.error('Connection error:', error);
this.addSystemMessage('Connection error. Please check your network connection and try again.');
});
// Game introduction received
this.socket.on('gameIntroduction', (data) => {
this.clearStory();
this.addNarrative(data.introduction);
this.addNarrative(data.initialRoomDescription);
this.gameState.started = true;
this.gameState.currentRoomId = data.currentRoomId;
// Enable buttons
this.rewindButton.removeAttribute('disabled');
// Focus on input field
this.playerInput.focus();
});
// Narrative response received
this.socket.on('narrativeResponse', (data) => {
// Clear any pending "thinking" indicators
if (this.currentCommandTimeout) {
clearTimeout(this.currentCommandTimeout);
this.currentCommandTimeout = null;
// Remove any existing thinking indicators
document.querySelectorAll('.thinking').forEach(el => el.remove());
}
this.addNarrative(data.text);
if (data.suggestions && data.suggestions.length > 0) {
this.addSuggestions(data.suggestions);
}
// Update game state
if (data.gameState) {
this.gameState.currentRoomId = data.gameState.currentRoomId;
}
// Scroll to bottom and focus input
this.scrollToBottom();
this.playerInput.focus();
// Re-enable input (failsafe)
this.playerInput.disabled = false;
this.submitButton.disabled = false;
});
// Game saved confirmation
this.socket.on('gameSaved', () => {
this.addSystemMessage('Game saved successfully.');
// Enable load button
this.loadButton.removeAttribute('disabled');
});
// Game loaded confirmation
this.socket.on('gameLoaded', (data) => {
this.clearStory();
this.addSystemMessage('Game loaded successfully.');
this.addNarrative(data.currentRoomDescription);
// Update game state
this.gameState.currentRoomId = data.currentRoomId;
});
// Error messages
this.socket.on('error', (data) => {
this.addSystemMessage(`Error: ${data.message}`);
});
}
/**
* Start a new game
*/
startGame() {
this.clearStory();
this.addSystemMessage('Starting a new game...');
this.socket.emit('startGame');
}
/**
* Submit a player command
*/
submitCommand() {
const command = this.playerInput.value.trim();
if (command === '') return;
// Disable input temporarily
this.playerInput.disabled = true;
this.submitButton.disabled = true;
// Add command to history
this.addUserCommand(command);
// Add a temporary "thinking" message
const thinkingId = this.addThinking();
// Send command to server
this.socket.emit('playerCommand', { command });
// Clear input
this.playerInput.value = '';
// Re-enable input field after a short delay (or after 8 seconds as failsafe)
const timeout = setTimeout(() => {
this.playerInput.disabled = false;
this.submitButton.disabled = false;
// Remove thinking indicator
const thinkingElement = document.getElementById(thinkingId);
if (thinkingElement) {
thinkingElement.remove();
}
// Add system message if no response was received (likely timeout)
if (document.getElementById(thinkingId)) {
this.addSystemMessage('The server is taking too long to respond. Please try again.');
}
}, 8000);
// Store the timeout so it can be cleared if we get a response
this.currentCommandTimeout = timeout;
}
/**
* Add a user command to the story
*/
addUserCommand(command) {
const element = document.createElement('p');
element.className = 'user-input';
element.textContent = `> ${command}`;
this.storyContainer.appendChild(element);
this.scrollToBottom();
}
/**
* Add a narrative response with typing effect
*/
addNarrative(text) {
const element = document.createElement('p');
element.className = 'narrative hide';
this.storyContainer.appendChild(element);
// Apply SmartyPants transformations for better typography if available
const processedText = window.SmartyPants && typeof window.SmartyPants.smartypantsu === 'function'
? window.SmartyPants.smartypantsu(text, 1)
: text;
// Clear any existing typing timeouts
if (this.typingTimeout) {
clearTimeout(this.typingTimeout);
}
// Add the text with a typing effect
this.typeText(element, processedText, 0);
// Read text aloud if speech is enabled
if (window.ttsHandler && window.ttsHandler.isEnabled()) {
console.log("Speaking narrative text with TTS");
window.ttsHandler.speak(text);
}
}
/**
* Add suggestions to the story
*/
addSuggestions(suggestions) {
const element = document.createElement('div');
element.className = 'suggestions';
const heading = document.createElement('p');
heading.textContent = 'Suggestions:';
heading.style.fontStyle = 'italic';
heading.style.marginTop = '1rem';
element.appendChild(heading);
const list = document.createElement('ul');
suggestions.forEach(suggestion => {
const item = document.createElement('li');
item.textContent = suggestion;
// Make suggestions clickable
item.style.cursor = 'pointer';
item.addEventListener('click', () => {
this.playerInput.value = suggestion;
this.submitCommand();
});
list.appendChild(item);
});
element.appendChild(list);
this.storyContainer.appendChild(element);
this.scrollToBottom();
}
/**
* Add a system message
*/
addSystemMessage(message) {
const element = document.createElement('p');
element.className = 'system-message';
element.textContent = message;
element.style.fontStyle = 'italic';
element.style.color = '#555';
this.storyContainer.appendChild(element);
this.scrollToBottom();
}
/**
* Add a thinking indicator
*/
addThinking() {
const id = 'thinking-' + Date.now();
const element = document.createElement('div');
element.id = id;
element.className = 'thinking';
element.innerHTML = '<p>Thinking<span class="loading-indicator"><span>.</span><span>.</span><span>.</span></span></p>';
element.style.fontStyle = 'italic';
element.style.color = '#777';
this.storyContainer.appendChild(element);
this.scrollToBottom();
return id;
}
/**
* Clear the story container
*/
clearStory() {
while (this.storyContainer.firstChild) {
this.storyContainer.removeChild(this.storyContainer.firstChild);
}
}
/**
* Type text into an element character by character
*/
typeText(element, text, index) {
// Show the element if it was hidden
if (index === 0) {
element.classList.remove('hide');
}
// Set the current text
element.textContent = text.substring(0, index);
// If we haven't reached the end of the text
if (index < text.length) {
// Calculate delay (randomize slightly for more natural effect)
const delay = Math.max(10, 100 - this.gameState.textSpeed) / 5;
const randomDelay = delay * (0.8 + Math.random() * 0.4);
// Schedule the next character
this.typingTimeout = setTimeout(() => {
this.typeText(element, text, index + 1);
}, randomDelay);
} else {
// Finished typing
this.scrollToBottom();
}
}
/**
* Update the typing speed based on the slider value
*/
updateTypingSpeed() {
this.gameState.textSpeed = parseInt(this.speedSlider.value, 10);
}
/**
* Update the speech button styling
*/
updateSpeechButton(enabled = false) {
if (enabled) {
this.speechButton.style.fontWeight = 'bold';
this.speechButton.style.color = '#000';
this.speechButton.style.backgroundColor = '#eee';
} else {
this.speechButton.style.fontWeight = 'normal';
this.speechButton.style.color = '#333';
this.speechButton.style.backgroundColor = '';
}
}
/**
* Scroll the story container to the bottom
*/
scrollToBottom() {
const container = document.getElementById('page_right');
if (container) {
container.scrollTop = container.scrollHeight;
}
}
}
// Create the application when the DOM is fully loaded
document.addEventListener('DOMContentLoaded', () => {
// Set custom CSS variables based on viewport
const updateViewportVariables = () => {
const vw = window.innerWidth;
const vh = window.innerHeight;
document.documentElement.style.setProperty('--viewport-aspect-ratio', `${vw / vh}`);
// Adjust book size based on viewport
const bookWidth = Math.min(vw * 0.9, vh * 1.4);
const bookHeight = bookWidth / 1.613;
document.documentElement.style.setProperty('--book-width', `${bookWidth}px`);
document.documentElement.style.setProperty('--book-height', `${bookHeight}px`);
};
// Update variables initially and on resize
updateViewportVariables();
window.addEventListener('resize', updateViewportVariables);
// Initialize the application
window.app = new AIFiction();
});