Skip to content

Commit

Permalink
feat(codegen): add ct return value hints (#16)
Browse files Browse the repository at this point in the history
  • Loading branch information
jonambas authored Apr 7, 2024
1 parent bb4de46 commit dc1734f
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 10 deletions.
9 changes: 8 additions & 1 deletion src/__tests__/codegen.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,14 @@ describe('codegen', () => {
"file": "ct.mjs",
},
{
"code": "export const ct: (alias: "foo.100" | "foo.200" | "bar.100" | "bar.200") => string;",
"code": "const pluginCtMap = {
'foo.100': '#fff',
'foo.200': {"base":"#000","lg":"#111"},
'bar.100': 'red',
'bar.200': 'blue',
} as const;
export const ct: <T extends keyof typeof pluginCtMap>(alias: T) => typeof pluginCtMap[T];",
"file": "ct.d.ts",
},
],
Expand Down
17 changes: 8 additions & 9 deletions src/codegen.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import type {
} from '@pandacss/types';
import { makePaths, mapTemplate } from './map';
import type { PluginContext } from './types';
import { serializeValue } from './utils';
import { serializeMapTypes, serializeValue } from './utils';

export const codegen = (
args: CodegenPrepareHookArgs,
Expand All @@ -20,20 +20,19 @@ export const codegen = (

if (!cssFn || !indexFile || !indexDtsFile) return args.artifacts;

const code = `${mapTemplate(map)}
const ctFile: ArtifactContent = {
file: 'ct.mjs',
code: `${mapTemplate(map)}
export const ct = (path) => {
if (!pluginCtMap.has(path)) return 'panda-plugin-ct_alias-not-found';
return pluginCtMap.get(path);
};`;

const paths = makePaths(tokens)
.map((key) => `"${key}"`)
.join(' | ');
};`,
};

const ctFile: ArtifactContent = { file: 'ct.mjs', code };
const ctDtsFile: ArtifactContent = {
file: 'ct.d.ts',
code: `export const ct: (alias: ${paths}) => string;`,
code: `${serializeMapTypes(map)}
\nexport const ct: <T extends keyof typeof pluginCtMap>(alias: T) => typeof pluginCtMap[T];`,
};

cssFn.files.push(ctFile, ctDtsFile);
Expand Down
9 changes: 9 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,12 @@ export const serializeMap = (map: Map<any, any>) => {
export const serializeValue = (value: any) => {
return isObject(value) ? JSON.stringify(value) : `'${value}'`;
};

export const serializeMapTypes = (map: Map<any, any>) => {
let code = 'const pluginCtMap = {';
for (const [key, value] of map.entries()) {
code += `\n '${key}': ${serializeValue(value)},`;
}
code += '\n} as const;';
return code;
};

0 comments on commit dc1734f

Please sign in to comment.