@es-js/eshtml
Version:
EsHTML: HTML en Español
433 lines (427 loc) • 11.2 kB
JavaScript
import { compile as compile$1 } from '@es-js/core';
import { invertMap } from '@es-js/core/utils';
import { parser } from './parser.mjs';
import { g as getDictionary$1, r as render } from './shared/eshtml.903f33e1.mjs';
const attributeUsages = {
accept: ["form", "input"],
"accept-charset": ["form"],
accesskey: ["__GLOBAL__"],
action: ["form"],
allow: ["iframe"],
alt: ["area", "img", "input"],
as: ["link"],
async: ["script"],
autocapitalize: ["__GLOBAL__"],
autocomplete: ["form", "input", "select", "textarea"],
autoplay: ["audio", "video"],
background: ["body", "table", "td", "th"],
bgcolor: [
"body",
"col",
"colgroup",
"marquee",
"table",
"tbody",
"tfoot",
"td",
"th",
"tr"
],
border: ["img", "object", "table"],
capture: ["input"],
charset: ["meta"],
checked: ["input"],
cite: ["blockquote", "del", "ins", "q"],
class: ["__GLOBAL__"],
color: ["font", "hr"],
cols: ["textarea"],
colspan: ["td", "th"],
content: ["meta"],
contenteditable: ["__GLOBAL__"],
controls: ["audio", "video"],
coords: ["area"],
crossorigin: ["audio", "img", "link", "script", "video"],
csp: ["iframe"],
data: ["object"],
"data-*": ["__GLOBAL__"],
datetime: ["del", "ins", "time"],
decoding: ["img"],
default: ["track"],
defer: ["script"],
dir: ["__GLOBAL__"],
dirname: ["input", "textarea"],
disabled: [
"button",
"fieldset",
"input",
"optgroup",
"option",
"select",
"textarea"
],
download: ["a", "area"],
draggable: ["__GLOBAL__"],
enctype: ["form"],
enterkeyhint: ["textarea", "contenteditable"],
for: ["label", "output"],
form: [
"button",
"fieldset",
"input",
"label",
"meter",
"object",
"output",
"progress",
"select",
"textarea"
],
formaction: ["input", "button"],
formenctype: ["button", "input"],
formmethod: ["button", "input"],
formnovalidate: ["button", "input"],
formtarget: ["button", "input"],
headers: ["td", "th"],
height: ["canvas", "embed", "iframe", "img", "input", "object", "video"],
hidden: ["__GLOBAL__"],
high: ["meter"],
href: ["a", "area", "base", "link"],
hreflang: ["a", "link"],
"http-equiv": ["meta"],
id: ["__GLOBAL__"],
integrity: ["link", "script"],
inputmode: ["textarea", "contenteditable"],
ismap: ["img"],
itemprop: ["__GLOBAL__"],
kind: ["track"],
label: ["optgroup", "option", "track"],
lang: ["__GLOBAL__"],
loading: ["img", "iframe"],
list: ["input"],
loop: ["audio", "marquee", "video"],
low: ["meter"],
max: ["input", "meter", "progress"],
maxlength: ["input", "textarea"],
minlength: ["input", "textarea"],
media: ["a", "area", "link", "source", "style"],
method: ["form"],
min: ["input", "meter"],
multiple: ["input", "select"],
muted: ["audio", "video"],
name: [
"button",
"form",
"fieldset",
"iframe",
"input",
"object",
"output",
"select",
"textarea",
"map",
"meta",
"param"
],
novalidate: ["form"],
open: ["details", "dialog"],
optimum: ["meter"],
pattern: ["input"],
ping: ["a", "area"],
placeholder: ["input", "textarea"],
playsinline: ["video"],
poster: ["video"],
preload: ["audio", "video"],
readonly: ["input", "textarea"],
referrerpolicy: ["a", "area", "iframe", "img", "link", "script"],
rel: ["a", "area", "link"],
required: ["input", "select", "textarea"],
reversed: ["ol"],
role: ["__GLOBAL__"],
rows: ["textarea"],
rowspan: ["td", "th"],
sandbox: ["iframe"],
scope: ["th"],
scoped: ["style"],
selected: ["option"],
shape: ["a", "area"],
size: ["input", "select"],
sizes: ["link", "img", "source"],
slot: ["__GLOBAL__"],
span: ["col", "colgroup"],
spellcheck: ["__GLOBAL__"],
src: [
"audio",
"embed",
"iframe",
"img",
"input",
"script",
"source",
"track",
"video"
],
srcdoc: ["iframe"],
srclang: ["track"],
srcset: ["img", "source"],
start: ["ol"],
step: ["input"],
style: ["__GLOBAL__"],
tabindex: ["__GLOBAL__"],
target: ["a", "area", "base", "form"],
title: ["__GLOBAL__"],
translate: ["__GLOBAL__"],
type: [
"button",
"input",
"embed",
"object",
"ol",
"script",
"source",
"style",
"menu",
"link"
],
usemap: ["img", "input", "object"],
value: [
"button",
"data",
"input",
"li",
"meter",
"option",
"progress",
"param"
],
width: ["canvas", "embed", "iframe", "img", "input", "object", "video"],
wrap: ["textarea"]
};
const dictionary = /* @__PURE__ */ new Map([
["accept", "aceptar"],
["accept-charset", "aceptar-conjunto-caracteres"],
["accesskey", "tecla-acceso"],
["action", "accion"],
["allow", "permitir"],
["alt", "alternativo"],
["as", "como"],
["async", "asincrono"],
["autocapitalize", "autocapitalizar"],
["autocomplete", "autocompletar"],
["autoplay", "autoreproducir"],
["background", "fondo"],
["bgcolor", "color-fondo"],
["border", "borde"],
["capture", "capturar"],
["charset", "conjunto-caracteres"],
["checked", "chequeado"],
["cite", "citar"],
["class", "clase"],
["color", "color"],
["cols", "columnas"],
["colspan", "extender-columnas"],
["content", "contenido"],
["contenteditable", "contenidoeditable"],
["controls", "controles"],
["coords", "coordenadas"],
["crossorigin", "cruzar-origen"],
["csp", "csp"],
["data", "datos"],
["datetime", "fechahora"],
["decoding", "decodificacion"],
["default", "por-defecto"],
["defer", "diferir"],
["dir", "direccion"],
["dirname", "nombre-direccion"],
["disabled", "deshabilitado"],
["download", "descargar"],
["draggable", "arrastrable"],
["enctype", "tipo-encriptacion"],
["enterkeyhint", "sugerencia-tecla-enter"],
["for", "para"],
["form", "formulario"],
["formaction", "formulario-accion"],
["formenctype", "tipo-formulario-encriptacion"],
["formmethod", "formulario-metodo"],
["formnovalidate", "sin-formulario-validacion"],
["formtarget", "formulario-objetivo"],
["headers", "cabeceras"],
["height", "altura"],
["hidden", "oculto"],
["high", "alto"],
["href", "referencia"],
["hreflang", "lenguaje-referencia"],
["http-equiv", "http-equiv"],
["id", "id"],
["integrity", "integridad"],
["inputmode", "modo-entrada"],
["ismap", "es-mapa"],
["itemprop", "propiedad-elemento"],
["kind", "categoria"],
["label", "etiqueta"],
["lang", "idioma"],
["loading", "cargando"],
["list", "lista"],
["loop", "bucle"],
["low", "bajo"],
["max", "maximo"],
["maxlength", "longitud-maxima"],
["minlength", "longitud-minima"],
["media", "media"],
["method", "metodo"],
["min", "minimo"],
["multiple", "multiple"],
["muted", "silenciado"],
["name", "nombre"],
["novalidate", "sin-validar"],
["open", "abierto"],
["optimum", "optimo"],
["pattern", "patron"],
["ping", "ping"],
["placeholder", "marcador"],
["playsinline", "reproducir-en-linea"],
["poster", "poster"],
["preload", "precargar"],
["readonly", "solo-lectura"],
["referrerpolicy", "politica-referencias"],
["rel", "rel"],
["required", "requerido"],
["reversed", "invertido"],
["role", "rol"],
["rows", "filas"],
["rowspan", "extender-filas"],
["sandbox", "sandbox"],
["scope", "alcance"],
["scoped", "aislado"],
["selected", "seleccionado"],
["shape", "forma"],
["size", "tama\xF1o"],
["sizes", "tama\xF1os"],
["slot", "slot"],
["span", "rango"],
["spellcheck", "verificacion-ortografia"],
["src", "fuente"],
["srcdoc", "fuente-doc"],
["srclang", "fuente-idioma"],
["srcset", "fuente-conjunto"],
["start", "inicio"],
["step", "paso"],
["style", "estilo"],
["tabindex", "indice-tab"],
["target", "objetivo"],
["title", "titulo"],
["translate", "traducir"],
["type", "tipo"],
["usemap", "usar-mapa"],
["value", "valor"],
["width", "ancho"],
["wrap", "envolver"]
]);
function getDictionary(inverted = false) {
if (!inverted) {
return invertMap(dictionary);
}
return dictionary;
}
function transformAttr(htmlTag, attr, options) {
const innerDictionary = getDictionary(options?.to === "eshtml");
const newAttr = innerDictionary.get(attr) || attr;
const htmlAttr = options?.to === "html" ? newAttr : attr;
const usage = attributeUsages[htmlAttr];
if (!usage) {
return attr;
}
if (usage.includes(htmlTag) || usage.includes("__GLOBAL__")) {
return newAttr;
}
return attr;
}
function replaceDocType(code, options) {
const fromDocType = options?.from === "html" ? "<!DOCTYPE html>" : "<!TIPODOC eshtml>";
const toDocType = options?.to === "html" ? "<!DOCTYPE html>" : "<!TIPODOC eshtml>";
const fromDocTypeRegex = new RegExp(escapeRegExp(fromDocType), "gi");
return code.replace(fromDocTypeRegex, toDocType);
}
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}
function compile(content, options = {
from: "eshtml",
to: "html"
}) {
if (!options.from) {
options.from = "eshtml";
}
if (!options.to) {
options.to = "html";
}
if (!options.compileEsJS) {
options.compileEsJS = true;
}
try {
if (options?.to === "html") {
content = replaceDocType(content, {
from: "eshtml",
to: "html"
});
}
const tree = parser(content);
const dictionary = getDictionary$1(options?.to === "eshtml");
const newTree = compileTreeRecursive(tree, dictionary, options);
let output = render(newTree);
if (options?.to === "eshtml") {
output = replaceDocType(output, {
from: "html",
to: "eshtml"
});
}
return output;
} catch (error) {
console.error({ error });
return content;
}
}
function compileTreeRecursive(tree, dictionary, options) {
return tree.map((node) => {
if (typeof node === "string") {
return node;
}
const { tag, attrs, content } = node;
if (!tag) {
return node;
}
const newTag = transformTag(tag, dictionary);
const htmlTag = options?.to === "html" ? newTag : tag;
const newAttrs = transformAttrs(htmlTag, attrs, options);
let newContent = content;
if (htmlTag === "script" && options?.compileEsJS && content) {
newContent = content.map((c) => compileScriptContent(c, options));
} else if (content) {
newContent = compileTreeRecursive(content, dictionary, options);
}
return { tag: newTag, attrs: newAttrs, content: newContent };
});
}
function compileScriptContent(content, options) {
if (typeof content === "string") {
return compile$1(content, {
from: options?.from === "eshtml" ? "esjs" : "js",
to: options?.to === "eshtml" ? "esjs" : "js"
});
}
return content;
}
function transformTag(tagName, dictionary) {
return dictionary.get(tagName.toLowerCase()) || tagName;
}
function transformAttrs(tagName, attrs, options) {
if (!attrs) {
return attrs;
}
const newAttrs = {};
for (const key in attrs) {
const newKey = transformAttr(tagName, key, options);
newAttrs[newKey] = attrs[key];
}
return newAttrs;
}
export { compile };