npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@beweco/email-template-builder

v0.1.1

Published

Email Builder Library based on @usewaypoint/email-builder - A React component for building responsive email templates

Readme

email-template-builder

License: MIT

Una librería de editor de emails basada en React y TypeScript, construida sobre @usewaypoint/email-builder. Permite crear emails responsivos de manera visual con una interfaz intuitiva.

✨ Características

  • 📧 Editor Visual: Interfaz drag-and-drop para construir emails
  • 🎨 Bloques Predefinidos: Avatar, Button, Text, Image, Columns, Divider, Spacer, HTML
  • 🎯 Panel de Configuración: Edición de propiedades en tiempo real (Inspector)
  • 🎨 Panel de Estilos: Control global de colores, fuentes y espaciado
  • 📱 Responsive: Los emails generados son compatibles con todos los clientes
  • 🎭 Interfaz Limpia: Modal con editor central y panel de configuración lateral
  • 🌗 Modo Oscuro: Soporte nativo para tema claro y oscuro con un simple prop
  • 🖥️ Vista Desktop/Mobile: Previsualización en diferentes dispositivos
  • 👁️ Modo Preview: Vista previa en tiempo real del email renderizado
  • 📄 Renderizado Solo Lectura: Componente <EmailRenderer /> para mostrar emails guardados
  • 💾 Exportación/Importación: Soporte para JSON y HTML
  • 🖼️ Gestión de Imágenes: Soporte para subida personalizada de imágenes
  • 🌍 Multiidioma: Soporte integrado para 9 idiomas y capacidad de locales personalizados
  • 🧩 Universal: Usable en React, Vanilla JS, Vue, Angular, etc.

📦 Instalación

npm install email-template-builder

# o con pnpm
pnpm add email-template-builder

# o con yarn
yarn add email-template-builder

Peer Dependencies

Esta librería requiere las siguientes dependencias en tu proyecto:

npm install react react-dom @mui/material @mui/icons-material @emotion/react @emotion/styled

🚀 Uso en React

Ahora es más simple que nunca. Importa directamente el componente <EmailEditor />:

import React, { useState } from 'react';
import { EmailEditor, TEditorConfiguration } from 'email-template-builder';

function App() {
  const [editorOpen, setEditorOpen] = useState(false);
  // Estado opcional para controlar el template externamente
  const [template, setTemplate] = useState<TEditorConfiguration | undefined>(undefined);
  
  // Variables personalizadas para insertar en el texto
  const customVariables = [
    {
      key: 'user_name',
      name: 'Nombre del Usuario',
      description: 'Nombre completo del usuario',
      exampleValue: 'Juan Pérez'
    }
  ];

  // Opcional: Manejar la subida de imágenes
  const handleImageUpload = async (file: File): Promise<string> => {
    // Lógica para subir a tu servidor (S3, Cloudinary, etc.)
    const formData = new FormData();
    formData.append('file', file);
    const response = await fetch('/api/upload', { method: 'POST', body: formData });
    const data = await response.json();
    return data.url; 
  };

  // Opcional: Guardar el template
  const handleSave = (document: TEditorConfiguration) => {
    console.log('Guardando template:', document);
    // api.saveTemplate(document);
  };
  
  return (
    <>
      <button onClick={() => setEditorOpen(true)}>
        Abrir Editor de Emails
      </button>
      
      <EmailEditor 
        open={editorOpen} 
        onClose={() => setEditorOpen(false)}
        
        // Callbacks principales
        onSave={handleSave}
        onChange={(document) => setTemplate(document)}
        onUploadImage={handleImageUpload}
        
        // Configuración inicial
        template={template}
        variables={customVariables}
        
        // Personalización
        locale="es" // 'es', 'en', 'pt', 'it', 'fr', 'de', 'nl', 'ca'
        darkMode={false} // Activar modo oscuro
        customLocale={{ // Sobrescribir textos específicos
           "topbar_save": "Guardar Cambios"
        }}
      />
    </>
  );
}

export default App;

🌐 Uso en Vanilla JS / Otros Frameworks

Puedes usar la librería fuera de React (Vue, Angular, Svelte, Vanilla JS) usando mountEmailEditor.

import { mountEmailEditor } from 'email-template-builder';

// 1. Puedes pasar el elemento DOM o un selector CSS
const editor = mountEmailEditor('#editor-container', {
  open: true,
  locale: 'es',
  darkMode: true, // Soporte para modo oscuro
  variables: [
    { key: 'name', name: 'Nombre', exampleValue: 'Usuario' }
  ],
  template: { /* JSON inicial opcional */ },
  onClose: () => {
    console.log('Cerrado');
    editor.update({ open: false }); // Actualizar prop para cerrar
  },
  onChange: (doc) => {
    console.log('Cambio:', doc);
  },
  onSave: (document) => {
    console.log('Guardado:', document);
  },
  onUploadImage: async (file) => {
    // Tu lógica de subida
    return 'https://example.com/image.jpg';
  }
});

// 2. Métodos disponibles
// Actualizar propiedades en cualquier momento
editor.update({ 
  variables: newVariables,
  open: true,
  darkMode: false
});

// Desmontar (limpieza)
// editor.unmount();

🖥️ Renderizado Server-Side (SSR) / Node.js

Si necesitas generar el HTML del email desde un proceso backend o script sin interfaz gráfica:

import { renderEmail } from 'email-template-builder';

// Tu configuración JSON guardada
const myTemplateJson = { ... }; 

// Generar HTML estático
const htmlOutput = renderEmail(myTemplateJson);

console.log(htmlOutput); // <!DOCTYPE html>...

📖 API

<EmailEditor>

Componente principal que renderiza el modal del editor.

Props:

| Prop | Tipo | Default | Descripción | |------|------|---------|-------------| | open | boolean | - | Requerido. Controla si el modal está visible. | | onClose | () => void | - | Requerido. Callback para cerrar el modal. | | onSave | (doc: TEditorConfiguration) => void | - | Callback al hacer clic en Guardar. | | onChange | (doc: TEditorConfiguration) => void | - | Callback invocado en cada cambio del template. | | template | TEditorConfiguration | - | Objeto JSON con el estado inicial del email. | | variables | EmailVariable[] | [] | Lista de variables para insertar en el texto. | | locale | SupportedLocale | 'es' | Idioma de la UI ('es', 'en', 'fr', 'de', 'it', 'pt', 'pt-br', 'nl', 'ca'). | | customLocale | Record<string, string> | - | Objeto para sobrescribir traducciones específicas o añadir nuevas. | | darkMode | boolean | false | Activa el tema oscuro de la interfaz. | | onUploadImage | (file: File) => Promise<string> | - | Función asíncrona para manejar la subida de imágenes. Debe retornar la URL. |

mountEmailEditor(element, props)

Función para montar el editor en entornos no-React. Retorna un objeto con:

  • update(newProps): Actualiza las props del editor.
  • unmount(): Desmonta el componente y limpia el DOM.

<EmailEditorProvider> (Legacy)

Nota: Ya no es necesario usar este provider para envolver el editor, ya que <EmailEditor> maneja su propio contexto y estilos de forma aislada. Se mantiene exportado para retrocompatibilidad.

<EmailRenderer>

Componente para visualizar templates guardados en modo solo lectura (usa un iframe aislado).

<EmailRenderer 
  template={myTemplateJson} 
  minHeight="600px" 
/>

🏗️ Desarrollo

Prerrequisitos

  • Node.js >= 18.x
  • pnpm (recomendado) o npm

Setup

# Clonar el repositorio
git clone https://github.com/beweos/email-editor.git
cd email-editor

# Instalar dependencias
pnpm install

# Iniciar servidor de desarrollo
pnpm dev

Scripts Disponibles

  • pnpm dev - Inicia el servidor de desarrollo con el ejemplo
  • pnpm build:lib - Construye la librería para producción
  • pnpm preview - Preview de la build
  • pnpm type-check - Verifica los tipos TypeScript

🏗️ Build de la Librería

Para construir la librería para distribución:

pnpm build:lib

Esto generará en dist/:

  • index.js - ES Module
  • index.cjs - CommonJS
  • index.d.ts - Declaraciones de TypeScript

📚 Tecnologías

  • React 18 - Framework UI
  • TypeScript - Type safety
  • Material-UI (MUI) - Componentes UI
  • Emotion - CSS-in-JS
  • Vite - Build tool
  • Zustand - State management
  • Zod - Validación
  • @usewaypoint/email-builder - Motor del editor

🎯 Componentes del Editor

Estructura del Modal

El modal incluye dos paneles principales:

📝 Panel Central - Editor

  • Editor: Vista de edición con drag-and-drop de bloques
  • Preview: Vista previa en tiempo real del email renderizado
  • Controles:
    • Toggle entre vista Desktop y Mobile
    • Botón para cambiar entre Editor y Preview

🎨 Panel Derecho - Inspector/Styles

Panel lateral con dos pestañas:

  • Styles: Configuración global del email (colores de fondo, canvas, fuentes, bordes)
  • Inspect: Propiedades del bloque seleccionado (se activa automáticamente al hacer clic en un bloque del editor)

Bloques Disponibles

  • Avatar: Imágenes de perfil circulares
  • Button: Botones con estilos personalizables
  • Text: Texto con formato rico
  • Heading: Encabezados (H1-H6)
  • Image: Imágenes responsive con subida personalizada
  • Columns: Layouts de columnas flexibles
  • Container: Contenedores con padding
  • Divider: Líneas divisoras horizontales
  • Spacer: Espaciado vertical personalizable
  • HTML: Código HTML personalizado

🤝 Contribuir

Las contribuciones son bienvenidas! Por favor:

  1. Fork el proyecto
  2. Crea tu feature branch (git checkout -b feature/AmazingFeature)
  3. Commit tus cambios (git commit -m 'Add some AmazingFeature')
  4. Push al branch (git push origin feature/AmazingFeature)
  5. Abre un Pull Request

📄 Licencia

MIT © [Beweos]

🙏 Agradecimientos

Esta librería está construida sobre el excelente trabajo de:

📮 Soporte

Para reportar bugs o solicitar features, por favor abre un issue.


Hecho con ❤️ por Beweos