vite-plugin-php-components
Version:
Transpile PHP-Components to PHP calls
80 lines (76 loc) • 2.63 kB
JavaScript
// src/index.ts
import rewriteHTML from "vite-plugin-html-rewrite";
// src/utils/hashTagName.ts
function hashTagName(tagName) {
const hash = tagName.split("").reduce(function(a, b) {
a = (a << 5) - a + b.charCodeAt(0);
return a & a;
}, 0);
return "c_" + Math.abs(new Date().getTime() - hash);
}
var hashTagName_default = hashTagName;
// src/utils/makePHPArray.ts
function makePHPArray(attrs) {
const attrPairs = Object.entries(attrs).map((item) => {
const key = item[0].replace(/'/g, "\\'");
let value = item[1];
if (value.startsWith("<?") && value.endsWith("?>") && !value.substring(2).includes("<?")) {
value = value.replace(/<\?(?:php|=)(.+?)(?:;|)\s*\?>/gis, (match, p1) => p1.trim());
} else {
const phpBlocks = [];
value = value.replace(/<\?(?:php|=)(.+?)(?:;|)\s*\?>/gis, (match, p1) => {
phpBlocks.push(p1.trim());
const index = phpBlocks.length - 1;
return `␀␀${index}␀␀`;
}).replace(/'/g, "\\'").replace(/␀␀(\d+)␀␀/g, (match, p1) => {
return `'.(${phpBlocks[parseInt(p1)]}).'`;
});
value = `'${value}'`;
}
return `'${key}' => ${value}`;
});
return `[${attrPairs.join(", ")}]`;
}
var makePHPArray_default = makePHPArray;
// src/index.ts
import { existsSync, lstatSync } from "node:fs";
function transpilePHPComponents(config) {
let viteConfig;
return [
{
name: "html-components-check",
enforce: "pre",
configResolved(config2) {
viteConfig = config2;
},
buildStart(options) {
const phpLibPath = `${viteConfig?.root}/vendor/nititech/html-components`;
if (!config?.skipLibCheck && (!existsSync(phpLibPath) || !lstatSync(phpLibPath).isDirectory())) {
this.error(`
Looks like 'nititech/html-components' is not installed.
This plugin is intended to be used with https://packagist.org/packages/nititech/html-components
`);
}
}
},
rewriteHTML([
{
match: (element) => {
return element.tagName.includes(".");
},
order: "pre",
render(elementDetails, index) {
const varName = "$" + hashTagName_default(elementDetails.tagName);
const className = "\\" + elementDetails.tagName.replace(/\./g, "\\");
const attrArray = makePHPArray_default(elementDetails.attribs);
return `<?php ${varName} = new ${className}(${attrArray}); ?>${elementDetails.innerHTML}<?php ${varName}->close(); ?>`;
}
}
])
];
}
var src_default = transpilePHPComponents;
export {
transpilePHPComponents,
src_default as default
};