xtx2tsx
Converts XTS component source into TS. The TS can be type checked using the included xtx-shims.d.ts
.
This project only converts xts to ts, type checking is left to consumers of this plugin such as language services
export interface Xts2TsOption {
fileName?: string;
ts: typeof import(typescript);
target?: ScriptTarget;
}
export function xts2ts(
sourceCode: string,
options: Xts2TsOption
): {
code: string;
map: SourceMap;
xtsDiagnostic: void[];
};
For example
input.xts
class Item1 {
id:number;
label:string;
constructor(id:number, label:string){
this.id = id;
this.label = label;
}
}
function commonFunc() {
console.log("顶层的通用函数")
}
@Main
component TestNestedCommonScript {
@State anArray:Item1[] = [
new Item1(1, "Text 1"),
new Item1(2, "Text 2"),
new Item1(3, "Text 3"),
new Item1(4, "Text 4"),
new Item1(5, "Text 5")
];
test() {
console.log(this.anArray)
}
render() {
Column(){
ForEach(this.anArray,
(item:Item1) => {Text(item.label)},
(item:Item1) => item.id.toString()
) //ForEach
Button("Reverse array"){
Text('sadadasd'){
Text('asdads'){
Icon().width(10)
}.width(20).height(40)
}
}
.width(500.0)
.height(150.0)
.onClick(() => {
this.anArray.reverse();
console.log("onClick handler on ShufflingArrayContainer1, this.anArray: " + JSON.stringify(this.anArray));
}) //Button
} // Column
} // build
}
useage:
import fs from 'fs/promises';
import path from 'path';
import { xts2ts } from './parser';
async function run() {
const testRootDir = path.resolve(__dirname, 'input.xts');
const xtsCode = await fs.readFile(testRootDir, {
encoding: 'utf-8',
});
const res = xts2ts(xtsCode, {
ts: (await import('typescript')).default,
});
console.log(res.code);
}
run();
will produce this ugly but type checkable TSX
class Item1 {
id: number;
label: string;
constructor(id: number, label: string) {
this.id = id;
this.label = label;
}
}
function commonFunc() {
console.log('顶层的通用函数');
}
@Main
export default class TestNestedCommonScript extends XTSComponent {
@State anArray: Item1[] = [
new Item1(1, 'Text 1'),
new Item1(2, 'Text 2'),
new Item1(3, 'Text 3'),
new Item1(4, 'Text 4'),
new Item1(5, 'Text 5'),
];
test() {
console.log(this.anArray);
}
render() {
Column().__$$child(() => {
ForEach(
this.anArray,
(item: Item1) => {
Text(item.label);
},
(item: Item1) => item.id.toString()
); //ForEach
Button('Reverse array')
.__$$child(() => {
Text('sadadasd').__$$child(() => {
Text('asdads')
.__$$child(() => {
Icon().width(10);
})
.width(20)
.height(40);
});
})
.width(500.0)
.height(150.0)
.onClick(() => {
this.anArray.reverse();
console.log(
'onClick handler on ShufflingArrayContainer1, this.anArray: ' +
JSON.stringify(this.anArray)
);
}); //Button
}); // Column
} // build
}
with a v3 SourceMap back to the original source.
For more examples of the transformations, see the test/case
folders