@ui5/linter
Version:
A static code analysis tool for UI5
62 lines • 2.26 kB
JavaScript
export class ControllerByIdDtsGenerator {
// Maps module names to local names
imports = new Map();
generate(controllerByIdInfo) {
const mappings = controllerByIdInfo.getMappings();
if (!mappings.size) {
return null;
}
this.imports = new Map();
this.addImport("sap/ui/core/mvc/View"); // View is needed for interface ControllerView
this.addImport("sap/ui/core/Element"); // Element is needed for byId fallback signature
let out = "";
mappings.forEach((idToModules, controllerName) => {
out += this.generateModuleDeclaration(controllerName, idToModules);
});
return this.generateCollectedImports() + out;
}
generateCollectedImports() {
return Array.from(this.imports.entries())
.map(([moduleName, localName]) => `import ${localName} from "${moduleName}";`)
.join("\n") + "\n";
}
generateByIdMapping(idToModules) {
let out = "interface ByIdMapping {\n";
idToModules.forEach((modules, id) => {
const localNames = Array.from(modules).map((moduleName) => this.addImport(moduleName));
out += `\t\t"${id}": ${localNames.join(" | ")};\n`;
});
out += "\t}";
return out;
}
generateModuleDeclaration(controllerName, idToModules) {
const moduleName = controllerName.replace(/\./g, "/") + ".controller";
return `
declare module "${moduleName}" {
${this.generateByIdMapping(idToModules)}
type ByIdFunction = {
<T extends keyof ByIdMapping>(sId: T): ByIdMapping[T];
(sId: string): ${this.imports.get("sap/ui/core/Element")};
}
interface ControllerView extends ${this.imports.get("sap/ui/core/mvc/View")} {
byId: ByIdFunction;
}
export default interface Controller {
byId: ByIdFunction;
getView(): ControllerView;
}
}
`;
}
addImport(moduleName) {
const localName = this.getLocalModuleName(moduleName);
if (!this.imports.has(moduleName)) {
this.imports.set(moduleName, localName);
}
return localName;
}
getLocalModuleName(moduleName) {
return moduleName.replace(/[/.]/g, "_");
}
}
//# sourceMappingURL=ControllerByIdDtsGenerator.js.map