css-kits
Version:
Parse css to javascript object. Support change class and id
109 lines (108 loc) • 3.78 kB
JavaScript
(function (factory) {
if (typeof module === "object" && typeof module.exports === "object") {
var v = factory(require, exports);
if (v !== undefined) module.exports = v;
}
else if (typeof define === "function" && define.amd) {
define(["require", "exports", "strkits", "./loader"], factory);
}
})(function (require, exports) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.toString = void 0;
const strkits_1 = require("strkits");
const loader_1 = require("./loader");
function declarationBlockToString(subject) {
const aggregate = [];
for (const property in subject) {
// if not a css variable
if (property.startsWith('--')) {
aggregate.push(`${property}: ${subject[property]}`);
}
else {
aggregate.push(`${(0, strkits_1.transformToKebabCase)(property)}: ${subject[property]}`);
}
}
if (aggregate.length === 0)
return '{ }';
return `{ ${aggregate.join('; ')}; }`;
}
function selectorsToString(subjects) {
return subjects.join(', ');
}
function concatRuleSet(subject, aggregate) {
if (Object.keys(subject.declarationBlock).length === 0) {
return aggregate;
}
aggregate.push(selectorsToString(subject.selectors));
aggregate.push(declarationBlockToString(subject.declarationBlock));
return aggregate;
}
function concatAtRule(subject, aggregate) {
const firstPart = `@${subject.identifier} ${subject.rule}`;
aggregate.push(firstPart);
switch (subject.type) {
case 'regular-at-rule': {
aggregate.push(';');
break;
}
case 'describes-at-rule': {
aggregate.push(declarationBlockToString(subject.declarationBlock));
break;
}
case 'nested-at-rule': {
aggregate.push('{');
concatStyleSheetList(subject.styleSheetList, aggregate);
aggregate.push('}');
break;
}
default: {
throw new Error('Invalid at-rule type');
}
}
return aggregate;
}
function concatStyleSheet(subject, aggregate) {
switch (subject.type) {
case 'rule-set': {
concatRuleSet(subject, aggregate);
break;
}
case 'regular-at-rule':
case 'describes-at-rule':
case 'nested-at-rule': {
concatAtRule(subject, aggregate);
break;
}
default: {
throw new Error('Invalid style sheet type');
}
}
return aggregate;
}
function concatStyleSheetList(subject, aggregate) {
for (const styleSheet of subject) {
concatStyleSheet(styleSheet, aggregate);
}
return aggregate;
}
function toString(subject, options) {
const results = [];
concatStyleSheetList(subject, results);
let strCss = results.join(' ');
if (!options) {
return strCss;
}
if (options.pretty === true) {
const formatFn = (0, loader_1.loadFormatFn)();
strCss = formatFn(strCss, {
parser: 'css',
semi: true,
tabWidth: options.tabWidth,
printWidth: options.printWidth,
});
}
return strCss;
}
exports.toString = toString;
});