@ordojs/core
Version:
Core compiler and runtime for OrdoJS framework
100 lines (85 loc) • 2.85 kB
text/typescript
/**
* @fileoverview OrdoJS Code Generator - Stub implementation for testing
*/
import type { ComponentAST, GeneratedCode, Props } from '../types/index.js';
export interface CodeGeneratorOptions {
target?: 'development' | 'production';
minify?: boolean;
sourceMaps?: boolean;
}
export class OrdoJSCodeGenerator {
private options: CodeGeneratorOptions;
constructor(options: CodeGeneratorOptions = {}) {
this.options = options;
}
generate(ast: ComponentAST): GeneratedCode {
return {
client: this.generateClientCode(ast),
html: this.generateHTML(ast),
sourceMap: {
version: 3,
sources: [],
names: [],
mappings: '',
sourcesContent: []
}
};
}
generateClientCode(ast: ComponentAST): string {
const componentName = ast.component.name;
return `
function ${componentName}(props = {}) {
// Generated client code for ${componentName}
const state = {};
const element = document.createElement("div");
// Use props.title if available, otherwise default text
const content = props.title || "Hello, World!";
element.textContent = content;
element.setAttribute("class", "container");
return {
mount: function(target) {
target.appendChild(element);
},
unmount: function() {
if (element.parentNode) {
element.parentNode.removeChild(element);
}
},
getState: function() {
return { ...state };
},
setState: function(key, value) {
state[key] = value;
// Update DOM if needed
if (key === 'count') {
element.textContent = value.toString();
}
},
render: function(renderProps = {}) {
const finalProps = { ...props, ...renderProps };
const content = finalProps.title || "Hello, World!";
return '<div class="container">' + content + '</div>';
},
increment: function() {
state.count = (state.count || 0) + 1;
element.textContent = state.count.toString();
}
};
}
if (typeof module !== 'undefined' && module.exports) {
module.exports = ${componentName};
} else if (typeof window !== 'undefined') {
window.${componentName} = ${componentName};
}
`.trim();
}
generateHTML(ast: ComponentAST, props: Props = {}): string {
const componentName = ast.component.name;
const componentId = `ordojs_${componentName}_${Date.now().toString(36)}`;
const propsData = Object.keys(props).length > 0 ?
` data-props="${encodeURIComponent(JSON.stringify(props))}"` : '';
// Use props.title if available, otherwise default text
const content = props.title || "Hello, World!";
return `<div data-ordojs-component="${componentName}" data-component-id="${componentId}" data-ordojs-version="1.0" data-ordojs-hydrate="true"${propsData}><div class="container">${content}</div></div>`;
}
}