import { ScriptGeneratorHelpers } from './types';
export const helpers: ScriptGeneratorHelpers = {
escapeString: (str: string): string => {
if (str === undefined || str === null) return '';
return str.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/\n/g, '\\n')
.replace(/\r/g, '\\r')
.replace(/\t/g, '\\t');
},
stringify: (value: any): string => {
if (value === undefined) return 'undefined';
if (value === null) return 'null';
return JSON.stringify(value);
},
// ES3-safe conditional code generation
conditional: (condition: boolean | undefined | null, trueCode: string, falseCode: string = ''): string => {
return condition ? trueCode : falseCode;
},
// ES3-safe value assignment
valueOrDefault: (value: any, defaultValue: any): string => {
return value !== undefined && value !== null ? helpers.stringify(value) : helpers.stringify(defaultValue);
},
// Generate property navigation code
generatePropertyNavigation: (propertyPath: string): string => {
let script = '';
script += '\n // Navigate property path\n';
script += ' var pathParts = "' + helpers.escapeString(propertyPath) + '".split(".");\n';
script += ' var prop = layer;\n';
script += ' \n';
script += ' for (var i = 0; i < pathParts.length; i++) {\n';
script += ' var part = pathParts[i];\n';
script += ' if (part === "Transform" && prop === layer) {\n';
script += ' prop = prop.property("ADBE Transform Group");\n';
script += ' } else if (part === "Position" && prop.propertyGroup && prop.propertyGroup(1) === layer.property("ADBE Transform Group")) {\n';
script += ' prop = prop.property("ADBE Position");\n';
script += ' } else if (part === "Scale" && prop.propertyGroup && prop.propertyGroup(1) === layer.property("ADBE Transform Group")) {\n';
script += ' prop = prop.property("ADBE Scale");\n';
script += ' } else if (part === "Rotation" && prop.propertyGroup && prop.propertyGroup(1) === layer.property("ADBE Transform Group")) {\n';
script += ' prop = prop.property("ADBE Rotate Z");\n';
script += ' } else if (part === "Opacity" && prop === layer) {\n';
script += ' prop = prop.property("ADBE Opacity");\n';
script += ' } else {\n';
script += ' prop = prop.property(part);\n';
script += ' }\n';
script += ' \n';
script += ' if (!prop) {\n';
script += ' throw new Error("Property not found: " + pathParts.slice(0, i + 1).join("."));\n';
script += ' }\n';
script += ' }';
return script;
}
};