vlibras-player-webjs
Version:
Biblioteca JavaScript moderna para integração do VLibras Player com React, Vue, Angular e vanilla JS
138 lines • 4.5 kB
JavaScript
;
/**
* Utilitários específicos para integração React
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.useTextWatcher = useTextWatcher;
exports.useIntersectionObserver = useIntersectionObserver;
exports.extractTextFromReactNode = extractTextFromReactNode;
exports.useLocalStorage = useLocalStorage;
exports.validateTranslationText = validateTranslationText;
exports.prepareTextForLibras = prepareTextForLibras;
const react_1 = require("react");
/**
* Hook para detectar mudanças no texto e automatizar traduções
*/
function useTextWatcher(text, onTextChange, debounceMs = 500) {
const timeoutRef = (0, react_1.useRef)();
(0, react_1.useEffect)(() => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
timeoutRef.current = setTimeout(() => {
if (text && text.trim()) {
onTextChange(text);
}
}, debounceMs);
return () => {
if (timeoutRef.current) {
clearTimeout(timeoutRef.current);
}
};
}, [text, onTextChange, debounceMs]);
}
/**
* Hook para detectar quando um elemento entra na viewport
*/
function useIntersectionObserver(callback, options = {}) {
const targetRef = (0, react_1.useRef)(null);
(0, react_1.useEffect)(() => {
const target = targetRef.current;
if (!target)
return;
const observer = new IntersectionObserver(([entry]) => callback(entry.isIntersecting), options);
observer.observe(target);
return () => {
observer.unobserve(target);
};
}, [callback, options]);
return targetRef;
}
/**
* Utilitário para extrair texto de elementos React
*/
function extractTextFromReactNode(node) {
if (typeof node === 'string' || typeof node === 'number') {
return String(node);
}
if (Array.isArray(node)) {
return node.map(extractTextFromReactNode).join(' ');
}
if (node && typeof node === 'object' && 'props' in node) {
return extractTextFromReactNode(node.props.children);
}
return '';
}
/**
* Hook para persistir configurações no localStorage
*/
function useLocalStorage(key, defaultValue) {
const [value, setValue] = (0, react_1.useState)(() => {
if (typeof window === 'undefined')
return defaultValue;
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : defaultValue;
}
catch {
return defaultValue;
}
});
const setStoredValue = (newValue) => {
try {
const valueToStore = newValue instanceof Function ? newValue(value) : newValue;
setValue(valueToStore);
if (typeof window !== 'undefined') {
window.localStorage.setItem(key, JSON.stringify(valueToStore));
}
}
catch (error) {
console.error(`Error saving to localStorage:`, error);
}
};
return [value, setStoredValue];
}
/**
* Validador de texto para tradução
*/
function validateTranslationText(text) {
const errors = [];
const warnings = [];
// Verificações básicas
if (!text || !text.trim()) {
errors.push('Texto não pode estar vazio');
}
if (text.length > 5000) {
errors.push('Texto muito longo (máximo 5000 caracteres)');
}
if (text.length < 3) {
warnings.push('Texto muito curto pode não ser traduzido corretamente');
}
// Verificar caracteres especiais excessivos
const specialCharsRatio = (text.match(/[^a-zA-ZÀ-ÿ0-9\s]/g) || []).length / text.length;
if (specialCharsRatio > 0.3) {
warnings.push('Muitos caracteres especiais podem afetar a tradução');
}
// Verificar se é apenas números
if (/^\d+$/.test(text.trim())) {
warnings.push('Texto contém apenas números');
}
return {
isValid: errors.length === 0,
errors,
warnings
};
}
/**
* Utilitário para formatação de texto para Libras
*/
function prepareTextForLibras(text) {
return text
.trim()
.replace(/\s+/g, ' ') // Normalizar espaços
.replace(/[""]/g, '"') // Normalizar aspas
.replace(/['']/g, "'") // Normalizar apóstrofes
.replace(/…/g, '...') // Normalizar reticências
.replace(/–|—/g, '-'); // Normalizar travessões
}
//# sourceMappingURL=index.js.map