JavaScript API
El widget de Neuroon expone una API JavaScript minimalista para inicialización y control básico.
API Disponible
NeuroonWidget.init(config)
Inicializa y monta el widget en el contenedor especificado.
const widget = NeuroonWidget.init({
container: '#neuroon-search',
token: 'YOUR_TOKEN',
theme: 'auto',
locale: 'es',
// ... más opciones (ver Configuración)
});
Parámetros:
config(NeuroonWidgetConfig): Objeto de configuración del widget
Retorno: WidgetInstance
interface WidgetInstance {
destroy: () => void
setTheme: (theme: 'light' | 'dark' | 'auto') => void
}
El widget está diseñado para funcionar de forma autónoma. La interacción del usuario con el widget (búsquedas, filtros, etc.) se maneja internamente. Para responder a eventos, usa los callbacks.
NeuroonWidget.getInstance()
Obtiene la instancia actual del widget si existe. Útil para verificar si el widget está activo o destruirlo desde otro contexto.
const widget = NeuroonWidget.getInstance();
if (widget) {
widget.destroy();
}
Retorno: WidgetInstance | null
El método setTheme() del objeto retornado por getInstance() tiene funcionalidad limitada. Para cambiar el tema dinámicamente, guarda la referencia del widget retornada por init():
// ✅ Correcto: usar la referencia de init()
const widget = NeuroonWidget.init({ /* config */ });
widget.setTheme('dark');
// ⚠️ Limitado: getInstance().setTheme() no cambia el tema
NeuroonWidget.getInstance()?.setTheme('dark'); // Solo imprime warning
NeuroonWidget.destroy()
Destruye la instancia actual del widget y limpia el DOM.
NeuroonWidget.destroy();
Métodos de la Instancia
widget.setTheme(theme)
Cambia el tema del widget dinámicamente.
const widget = NeuroonWidget.init({ /* config */ });
// Cambiar a tema oscuro
widget.setTheme('dark');
// Cambiar a tema claro
widget.setTheme('light');
// Seguir preferencia del sistema
widget.setTheme('auto');
Parámetros:
theme('light' | 'dark' | 'auto'): Tema a aplicar
widget.destroy()
Destruye esta instancia del widget.
widget.destroy();
Después de llamar destroy(), la instancia ya no es usable. Debes crear una nueva con NeuroonWidget.init().
Ejemplo Completo
// Inicializar widget
const widget = NeuroonWidget.init({
container: '#neuroon-search',
token: 'YOUR_TOKEN',
theme: 'auto',
locale: 'es',
features: {
suggestions: true,
filters: true,
voiceSearch: true,
imageSearch: true,
aiAssistant: false,
},
callbacks: {
onResultClick: (product) => {
console.log('Click en producto:', product.name);
},
onFilterChange: (filters) => {
console.log('Filtros:', filters);
},
},
});
// Cambiar tema según hora del día
const hour = new Date().getHours();
if (hour >= 20 || hour < 6) {
widget.setTheme('dark');
}
// Limpiar al desmontar la página (SPA)
window.addEventListener('beforeunload', () => {
widget.destroy();
});
Acceso Global
El widget se registra automáticamente en window.NeuroonWidget:
// Disponible globalmente después de cargar el script
window.NeuroonWidget.init({ /* config */ });
Integración con Frameworks
React
import { useEffect, useRef } from 'react';
function SearchWidget({ token }) {
const containerRef = useRef(null);
const widgetRef = useRef(null);
useEffect(() => {
if (containerRef.current && !widgetRef.current) {
widgetRef.current = window.NeuroonWidget.init({
container: containerRef.current,
token,
theme: 'auto',
});
}
return () => {
widgetRef.current?.destroy();
widgetRef.current = null;
};
}, [token]);
return <div ref={containerRef} />;
}
Vue
<template>
<div ref="container"></div>
</template>
<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
const props = defineProps(['token']);
const container = ref(null);
let widget = null;
onMounted(() => {
widget = window.NeuroonWidget.init({
container: container.value,
token: props.token,
theme: 'auto',
});
});
onUnmounted(() => {
widget?.destroy();
});
</script>
Próximos pasos
- Callbacks - Responder a eventos del widget
- Configuración - Todas las opciones de configuración
- Theming - Personalización visual