vlibras-player-webjs
Version:
Biblioteca JavaScript moderna para integração do VLibras Player com React, Vue, Angular e vanilla JS
427 lines • 13.3 kB
JavaScript
;
/**
* Sistema de configuração global para VLibras Player
* Permite configurar uma vez e usar em toda a aplicação
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.VLibrasConfigUtils = exports.VLibrasGlobalConfig = void 0;
/**
* Configuração padrão
*/
const DEFAULT_CONFIG = {
assetsPath: '/target',
defaultRegion: 'BR',
theme: 'auto',
language: 'pt-BR',
enableStats: false,
debug: false,
autoRetry: true,
retryAttempts: 3,
performance: {
preloadAssets: false,
cacheEnabled: true,
maxCacheSize: 50, // 50MB
enableGPUAcceleration: true,
lowLatencyMode: false
},
analytics: {
enabled: false,
anonymizeData: true,
respectDoNotTrack: true
},
accessibility: {
announceStateChanges: true,
keyboardNavigation: true,
reduceMotion: false,
highContrastMode: false,
screenReaderSupport: true
},
experimental: {
enableWorkers: false,
enableOfflineMode: false,
enablePredictiveCache: false,
enableAutoScale: true
}
};
/**
* Classe principal de configuração global
*/
class VLibrasGlobalConfig {
/**
* Configura o VLibras globalmente
*/
static configure(newConfig) {
const previousConfig = { ...this.config };
// Merge profundo da configuração
this.config = this.deepMerge(this.config, newConfig);
// Salva no localStorage se disponível
this.saveToStorage();
// Aplica configurações automaticamente
this.applyConfiguration();
// Notifica listeners
this.notifyListeners();
this.isInitialized = true;
console.log('🔧 VLibras configurado:', {
previous: previousConfig,
current: this.config,
changes: this.getChanges(previousConfig, this.config)
});
}
/**
* Obtém a configuração atual
*/
static getConfig() {
return { ...this.config };
}
/**
* Obtém uma configuração específica
*/
static get(key) {
return this.config[key];
}
/**
* Define uma configuração específica
*/
static set(key, value) {
this.configure({ [key]: value });
}
/**
* Reseta para configuração padrão
*/
static reset() {
this.config = { ...DEFAULT_CONFIG };
this.saveToStorage();
this.applyConfiguration();
this.notifyListeners();
console.log('🔄 VLibras resetado para configuração padrão');
}
/**
* Carrega configuração do localStorage
*/
static loadFromStorage() {
try {
const stored = localStorage.getItem('vlibras-global-config');
if (stored) {
const parsedConfig = JSON.parse(stored);
this.configure(parsedConfig);
return true;
}
}
catch (error) {
console.warn('⚠️ Erro ao carregar configuração do storage:', error);
}
return false;
}
/**
* Salva configuração no localStorage
*/
static saveToStorage() {
try {
localStorage.setItem('vlibras-global-config', JSON.stringify(this.config));
}
catch (error) {
console.warn('⚠️ Erro ao salvar configuração no storage:', error);
}
}
/**
* Adiciona listener para mudanças de configuração
*/
static onChange(listener) {
this.listeners.push(listener);
// Retorna função para remover o listener
return () => {
const index = this.listeners.indexOf(listener);
if (index !== -1) {
this.listeners.splice(index, 1);
}
};
}
/**
* Verifica se foi inicializado
*/
static isConfigured() {
return this.isInitialized;
}
/**
* Cria configuração de player com base na global
*/
static createPlayerConfig(overrides) {
const baseConfig = {
targetPath: this.config.assetsPath,
...overrides
};
return baseConfig;
}
/**
* Obtém configurações por ambiente
*/
static getEnvironmentConfig() {
const isDevelopment = typeof process !== 'undefined' && process.env?.NODE_ENV === 'development';
const isProduction = typeof process !== 'undefined' && process.env?.NODE_ENV === 'production';
if (isDevelopment) {
return {
debug: true,
enableStats: true,
performance: {
...DEFAULT_CONFIG.performance,
preloadAssets: false // Mais rápido em dev
}
};
}
if (isProduction) {
return {
debug: false,
enableStats: false,
performance: {
...DEFAULT_CONFIG.performance,
preloadAssets: true // Melhor UX em prod
}
};
}
return {};
}
/**
* Auto-configura baseado no ambiente
*/
static autoConfigureForEnvironment() {
const envConfig = this.getEnvironmentConfig();
this.configure(envConfig);
}
/**
* Valida configuração
*/
static validateConfig(config) {
const errors = [];
if (config.performance?.maxCacheSize && config.performance.maxCacheSize < 0) {
errors.push('maxCacheSize deve ser maior ou igual a 0');
}
if (config.retryAttempts && config.retryAttempts < 0) {
errors.push('retryAttempts deve ser maior ou igual a 0');
}
if (config.assetsPath && !config.assetsPath.trim()) {
errors.push('assetsPath não pode estar vazio');
}
return {
valid: errors.length === 0,
errors
};
}
/**
* Aplica configurações automaticamente
*/
static applyConfiguration() {
// Aplica tema
this.applyTheme();
// Aplica configurações de acessibilidade
this.applyAccessibilitySettings();
// Aplica configurações de performance
this.applyPerformanceSettings();
}
/**
* Aplica tema
*/
static applyTheme() {
const { theme } = this.config;
const root = document.documentElement;
if (theme === 'auto') {
// Verificar se estamos em ambiente browser e se matchMedia está disponível
if (typeof window !== 'undefined' && window.matchMedia) {
const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
root.setAttribute('data-vlibras-theme', prefersDark ? 'dark' : 'light');
}
else {
// Fallback para light theme em ambientes sem matchMedia (como testes)
root.setAttribute('data-vlibras-theme', 'light');
}
}
else {
root.setAttribute('data-vlibras-theme', theme);
}
}
/**
* Aplica configurações de acessibilidade
*/
static applyAccessibilitySettings() {
const { accessibility } = this.config;
const root = document.documentElement;
if (accessibility.reduceMotion) {
root.style.setProperty('--vlibras-animation-duration', '0.01ms');
}
if (accessibility.highContrastMode) {
root.setAttribute('data-vlibras-contrast', 'high');
}
}
/**
* Aplica configurações de performance
*/
static applyPerformanceSettings() {
const { performance } = this.config;
if (performance.enableGPUAcceleration) {
// Configurações de GPU acceleration serão aplicadas no Unity
}
if (performance.lowLatencyMode) {
// Configurações de baixa latência
}
}
/**
* Notifica todos os listeners
*/
static notifyListeners() {
this.listeners.forEach(listener => {
try {
listener(this.config);
}
catch (error) {
console.error('Erro no listener de configuração:', error);
}
});
}
/**
* Merge profundo de objetos
*/
static deepMerge(target, source) {
const output = { ...target };
for (const key in source) {
if (source[key] !== undefined) {
if (this.isObject(source[key]) && this.isObject(target[key])) {
output[key] = this.deepMerge(target[key], source[key]);
}
else {
output[key] = source[key];
}
}
}
return output;
}
/**
* Verifica se é objeto
*/
static isObject(item) {
return item && typeof item === 'object' && !Array.isArray(item);
}
/**
* Obtém diferenças entre configurações
*/
static getChanges(previous, current) {
const changes = {};
for (const key in current) {
if (JSON.stringify(previous[key]) !== JSON.stringify(current[key])) {
changes[key] = {
from: previous[key],
to: current[key]
};
}
}
return changes;
}
}
exports.VLibrasGlobalConfig = VLibrasGlobalConfig;
VLibrasGlobalConfig.config = { ...DEFAULT_CONFIG };
VLibrasGlobalConfig.listeners = [];
VLibrasGlobalConfig.isInitialized = false;
/**
* Classe de utilitários para configuração
*/
class VLibrasConfigUtils {
/**
* Cria configuração otimizada para mobile
*/
static getMobileConfig() {
return {
performance: {
preloadAssets: false,
cacheEnabled: true,
maxCacheSize: 25, // Menor cache para mobile
enableGPUAcceleration: true,
lowLatencyMode: true
},
accessibility: {
announceStateChanges: true,
keyboardNavigation: false, // Menos relevante em mobile
reduceMotion: false,
highContrastMode: false,
screenReaderSupport: true
}
};
}
/**
* Cria configuração otimizada para desktop
*/
static getDesktopConfig() {
return {
performance: {
preloadAssets: true,
cacheEnabled: true,
maxCacheSize: 100, // Maior cache para desktop
enableGPUAcceleration: true,
lowLatencyMode: false
},
accessibility: {
announceStateChanges: true,
keyboardNavigation: true,
reduceMotion: false,
highContrastMode: false,
screenReaderSupport: true
}
};
}
/**
* Detecta configuração ideal baseada no dispositivo
*/
static detectOptimalConfig() {
const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
const hasGoodConnection = navigator.connection?.effectiveType === '4g';
const hasHighMemory = performance.memory?.jsHeapSizeLimit > 1073741824; // 1GB
let config = {};
if (isMobile) {
config = this.getMobileConfig();
}
else {
config = this.getDesktopConfig();
}
// Ajustes baseados na conexão
if (!hasGoodConnection) {
config.performance = {
preloadAssets: false,
cacheEnabled: true,
maxCacheSize: 10,
enableGPUAcceleration: true,
lowLatencyMode: false
};
}
// Ajustes baseados na memória disponível
if (!hasHighMemory) {
config.performance = {
...(config.performance || DEFAULT_CONFIG.performance),
maxCacheSize: Math.min(config.performance?.maxCacheSize || 25, 25)
};
}
return config;
}
/**
* Aplica configuração ideal automaticamente
*/
static applyOptimalConfig() {
const optimalConfig = this.detectOptimalConfig();
VLibrasGlobalConfig.configure(optimalConfig);
}
}
exports.VLibrasConfigUtils = VLibrasConfigUtils;
// Auto-inicialização
if (typeof window !== 'undefined') {
// Carrega configuração salva
VLibrasGlobalConfig.loadFromStorage();
// Auto-configura para ambiente se não foi configurado manualmente
if (!VLibrasGlobalConfig.isConfigured()) {
VLibrasGlobalConfig.autoConfigureForEnvironment();
}
// Listener para mudanças de tema do sistema (apenas em ambiente browser)
if (typeof window !== 'undefined' && window.matchMedia) {
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
if (VLibrasGlobalConfig.get('theme') === 'auto') {
VLibrasGlobalConfig.configure({}); // Re-aplica tema
}
});
}
}
//# sourceMappingURL=VLibrasGlobalConfig.js.map