Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for value variables '@value' and fix default exports #6

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion lib/index.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
export declare const outputDtsFiles: ({ watchPattern, objectIndex, sassInclude }: {
export declare const outputDtsFiles: ({ watchPattern, objectIndex, sassInclude, sassData }: {
watchPattern?: string | undefined;
objectIndex?: boolean | undefined;
sassInclude?: string[] | undefined;
sassData?: string | undefined;
}) => void;
export default outputDtsFiles;
33 changes: 17 additions & 16 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,29 +69,30 @@ var unlinkPromise = util_1.promisify(fs.unlink);
var processor = postcss_1.default(postcss_nested_1.default, postcss_icss_selectors_1.default({ mode: 'local' }));
var toCamelCase = function (str) { return str.replace(/-+(\w)/g, function (_match, firstLetter) { return firstLetter.toUpperCase(); }); };
// const getPath = ( outputDir: string, file: string ) => `${outputDir}/${file}.d.ts`
var getDtsContent = function (sassInclude, includeIndexKey, path) { return __awaiter(_this, void 0, void 0, function () {
var result, lazyResult, classes, namedExports, defaultExport, e_1;
var getDtsContent = function (sassInclude, sassData, includeIndexKey, path) { return __awaiter(_this, void 0, void 0, function () {
var fileData, result, lazyResult, classes, values, matches, namedExports, defaultExport, e_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, 2, , 3]);
fileData = fs.readFileSync(path, 'utf-8');
return [4 /*yield*/, renderPromise({
file: path,
includePaths: sassInclude
// file: path,
data: sassData + "\n" + fileData,
includePaths: sassInclude,
})
// hmm... can't be piped...
];
case 1:
result = _a.sent();
lazyResult = processor.process(result.css.toString());
classes = pipeline_1.default(lazyResult, object_1.prop('root'), icss_utils_1.extractICSS, object_1.prop('icssExports'), object_1.keys, mapArray_1.default(toCamelCase));
namedExports = classes
values = result.css.toString().match(/(?<=@value\s)(.*)(?=:)/gi);
matches = classes.concat((values ? values.map(toCamelCase) : []));
namedExports = matches
.map(function (cssClass) { return "export const " + cssClass + ": string;"; })
.join('\n');
defaultExport = 'export default {} as {\n'
+ classes.map(function (cssClass) { return " " + cssClass + ": string,"; }).join('\n')
+ (includeIndexKey ? '\n [ key: string ]: string' : '')
+ '\n}';
defaultExport = "\n interface Styles {\n " + matches.map(function (cssClass) { return cssClass + ": string"; }).join('\n') + "\n " + (includeIndexKey ? '\n [ key: string ]: string' : '') + "\n }\n\n declare const _styles: Styles\n export default _styles\n ";
return [2 /*return*/, namedExports + "\n" + defaultExport];
case 2:
e_1 = _a.sent();
Expand All @@ -102,12 +103,12 @@ var getDtsContent = function (sassInclude, includeIndexKey, path) { return __awa
});
}); };
// const shaveLeft = ( remove: string, source: string ) => {
// return source[0] === remove
// return source[0] === remove
// ? source.slice(1)
// : source
// }
// const shaveRight = ( remove: string, source: string ) => {
// return source[ source.length ] === remove
// return source[ source.length ] === remove
// ? source.slice(0,1)
// : source
// }
Expand Down Expand Up @@ -151,13 +152,13 @@ var writeDtsContent = function (file, content) { return __awaiter(_this, void 0,
}
});
}); };
var addOrUpdateAction = function (sassInclude, objectIndex, file) { return __awaiter(_this, void 0, void 0, function () {
var addOrUpdateAction = function (sassInclude, sassData, objectIndex, file) { return __awaiter(_this, void 0, void 0, function () {
var _a, _b;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
_a = pipeline_1.default;
return [4 /*yield*/, getDtsContent(sassInclude, objectIndex, file)];
return [4 /*yield*/, getDtsContent(sassInclude, sassData, objectIndex, file)];
case 1:
_b = [_c.sent()];
return [4 /*yield*/, bindStrict_1.default(writeDtsContent, file)];
Expand Down Expand Up @@ -191,11 +192,11 @@ var deleteAction = function (file) { return __awaiter(_this, void 0, void 0, fun
}); };
exports.outputDtsFiles = function (_a) {
// log({watchPattern})
var _b = _a.watchPattern, watchPattern = _b === void 0 ? '*.module.scss' : _b, _c = _a.objectIndex, objectIndex = _c === void 0 ? false : _c, _d = _a.sassInclude, sassInclude = _d === void 0 ? ['src/'] : _d;
var _b = _a.watchPattern, watchPattern = _b === void 0 ? '*.module.scss' : _b, _c = _a.objectIndex, objectIndex = _c === void 0 ? false : _c, _d = _a.sassInclude, sassInclude = _d === void 0 ? ['src/'] : _d, _e = _a.sassData, sassData = _e === void 0 ? '' : _e;
var watcher = chokidar.watch(watchPattern, { depth: 10 });
watcher
.on('add', bindStrict_1.default(addOrUpdateAction, sassInclude, objectIndex))
.on('change', bindStrict_1.default(addOrUpdateAction, sassInclude, objectIndex))
.on('add', bindStrict_1.default(addOrUpdateAction, sassInclude, sassData, objectIndex))
.on('change', bindStrict_1.default(addOrUpdateAction, sassInclude, sassData, objectIndex))
.on('unlink', deleteAction);
};
exports.default = exports.outputDtsFiles;
6 changes: 4 additions & 2 deletions lib/sass-module-types.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ commander_1.default
.version(version)
.usage('[options]')
.option('-b, --base <path>', "default base is " + defaults.base)
.option('-i, --sass-include <paths>', "list of paths to includedefault is " + defaults.sassInclude)
.option('-i, --sass-include <paths>', "list of paths to include. default is " + defaults.sassInclude)
.option('-d, --sass-data <string>', "string to pass to LibSass to compile.")
.option('-p, --pattern <pattern>', "default pattern is " + defaults.pattern)
.option('-k, --includeIndexKeys', 'enable index look ups on default export (disabled by default)')
.parse(process.argv);
Expand All @@ -45,8 +46,9 @@ var sassIncludeArray = commander_1.default.sassInclude
var sassInclude = (sassIncludeArray.length > 0
? sassIncludeArray
: [defaults.sassInclude]);
var sassData = commander_1.default.sassData;
var base = (commander_1.default.base || defaults.base).trim();
var pattern = (commander_1.default.pattern || defaults.pattern).trim();
var objectIndex = (commander_1.default.includeIndexKeys || false);
var watchPattern = (base + "/" + pattern).replace(/\/+/, '/');
index_1.outputDtsFiles({ watchPattern: watchPattern, objectIndex: objectIndex, sassInclude: sassInclude });
index_1.outputDtsFiles({ watchPattern: watchPattern, objectIndex: objectIndex, sassInclude: sassInclude, sassData: sassData });
43 changes: 27 additions & 16 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,13 @@ const processor = postcss(
const toCamelCase = ( str: string ) => str.replace(/-+(\w)/g, ( _match, firstLetter: string ) => firstLetter.toUpperCase() )
// const getPath = ( outputDir: string, file: string ) => `${outputDir}/${file}.d.ts`

const getDtsContent = async ( sassInclude: string[], includeIndexKey: boolean, path: string ) => {
const getDtsContent = async ( sassInclude: string[], sassData: string, includeIndexKey: boolean, path: string ) => {
try {
const fileData = fs.readFileSync(path, 'utf-8')
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would prefer a non-blocking solution

const result = await renderPromise({
file: path,
includePaths: sassInclude
// file: path,
data: `${sassData}\n${fileData}`,
includePaths: sassInclude,
})
// hmm... can't be piped...
const lazyResult = processor.process(result.css.toString())
Expand All @@ -47,15 +49,24 @@ const getDtsContent = async ( sassInclude: string[], includeIndexKey: boolean, p
mapArray(toCamelCase)
)

const namedExports = classes
const values = result.css.toString().match(/(?<=@value\s)(.*)(?=:)/gi);

const matches = [...classes, ...(values ? values.map(toCamelCase) : [])];

const namedExports = matches
.map( cssClass => `export const ${cssClass}: string;` )
.join('\n')

const defaultExport = 'export default {} as {\n'
+ classes.map( cssClass => ` ${cssClass}: string,`).join('\n')
+ ( includeIndexKey ? '\n [ key: string ]: string' : '' )
+ '\n}'

const defaultExport = `
interface Styles {
${matches.map( cssClass => `${cssClass}: string`).join('\n')}
${( includeIndexKey ? '\n [ key: string ]: string' : '' )}
}

declare const _styles: Styles
export default _styles
`

return `${namedExports}\n${defaultExport}`
} catch (e) {
log(e)
Expand All @@ -64,13 +75,13 @@ const getDtsContent = async ( sassInclude: string[], includeIndexKey: boolean, p
}

// const shaveLeft = ( remove: string, source: string ) => {
// return source[0] === remove
// return source[0] === remove
// ? source.slice(1)
// : source
// }

// const shaveRight = ( remove: string, source: string ) => {
// return source[ source.length ] === remove
// return source[ source.length ] === remove
// ? source.slice(0,1)
// : source
// }
Expand Down Expand Up @@ -110,8 +121,8 @@ const writeDtsContent = async (file: string, content: string) => {
}
}

const addOrUpdateAction = async ( sassInclude: string[], objectIndex: boolean, file: string ) => pipeline(
await getDtsContent( sassInclude, objectIndex, file ),
const addOrUpdateAction = async ( sassInclude: string[], sassData: string, objectIndex: boolean, file: string ) => pipeline(
await getDtsContent( sassInclude, sassData, objectIndex, file ),
await bind(writeDtsContent, file),
)

Expand All @@ -131,14 +142,14 @@ const deleteAction = async ( file: string ) => {
}
}

export const outputDtsFiles = ( { watchPattern = '*.module.scss', objectIndex = false, sassInclude = [ 'src/' ] } ) => {
export const outputDtsFiles = ( { watchPattern = '*.module.scss', objectIndex = false, sassInclude = [ 'src/' ], sassData = '' } ) => {
// log({watchPattern})

const watcher = chokidar.watch( watchPattern, { depth: 10 } )

watcher
.on('add', bind( addOrUpdateAction, sassInclude, objectIndex ) )
.on('change', bind( addOrUpdateAction, sassInclude, objectIndex ) )
.on('add', bind( addOrUpdateAction, sassInclude, sassData, objectIndex ) )
.on('change', bind( addOrUpdateAction, sassInclude, sassData, objectIndex ) )
.on('unlink', deleteAction )
}

Expand Down
18 changes: 11 additions & 7 deletions src/sass-module-types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ program
.version(version)
.usage('[options]')
.option('-b, --base <path>', `default base is ${ defaults.base }`)
.option('-i, --sass-include <paths>', `list of paths to includedefault is ${ defaults.sassInclude }`)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi, is this a typo?

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ah, I see, yes. Thanks

.option('-i, --sass-include <paths>', `list of paths to include. default is ${ defaults.sassInclude }`)
.option('-d, --sass-data <string>', `string to pass to LibSass to compile.`)
.option('-p, --pattern <pattern>', `default pattern is ${ defaults.pattern }`)
.option('-k, --includeIndexKeys', 'enable index look ups on default export (disabled by default)')
.parse(process.argv)
Expand All @@ -36,21 +37,24 @@ if( program.args.length > 0 ) {
// }
const trim = ( s: string ) => s.trim()
const id = ( i: string ) => i
const sassIncludeArray = program.sassInclude
const sassIncludeArray = program.sassInclude
? program.sassInclude
.trim()
.split(',')
.map( trim )
.filter( id )
: []

const sassInclude = (
sassIncludeArray.length > 0
? sassIncludeArray
: [ defaults.sassInclude ]
const sassInclude = (
sassIncludeArray.length > 0
? sassIncludeArray
: [ defaults.sassInclude ]
)

const sassData = program.sassData

const base = ( program.base || defaults.base ).trim() as string
const pattern = ( program.pattern || defaults.pattern ).trim() as string
const objectIndex = ( program.includeIndexKeys || false ) as boolean
const watchPattern = `${base}/${pattern}`.replace( /\/+/, '/' ) as string
processDts({watchPattern, objectIndex, sassInclude})
processDts({watchPattern, objectIndex, sassInclude, sassData})
Loading