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

invalid rules generated #14 #15

Merged
merged 2 commits into from
Aug 22, 2023
Merged
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
426 changes: 234 additions & 192 deletions dist/index-umd-web.js

Large diffs are not rendered by default.

426 changes: 234 additions & 192 deletions dist/index.cjs

Large diffs are not rendered by default.

7 changes: 4 additions & 3 deletions dist/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -633,7 +633,7 @@ type AstNode =
| AstDeclaration;

declare const combinators: string[];
declare function minify(ast: AstNode, options?: ParserOptions, recursive?: boolean, errors?: ErrorDescription[]): AstNode;
declare function minify(ast: AstNode, options?: ParserOptions, recursive?: boolean, errors?: ErrorDescription[], nestingContent?: boolean): AstNode;
declare function reduceSelector(selector: string[][]): {
match: boolean;
optimized: string[];
Expand All @@ -644,7 +644,7 @@ declare function hasDeclaration(node: AstRule): boolean;
declare function minifyRule(ast: AstRule | AstAtRule): AstRule | AstAtRule;
declare function splitRule(buffer: string): string[][];

declare function walk(node: AstNode): Generator<{
declare function walk(node: AstNode, parent?: AstRuleList, root?: AstRuleList): Generator<{
node: AstNode;
parent?: AstRuleList;
root?: AstRuleList;
Expand All @@ -655,6 +655,7 @@ declare function walkValues(values: Token[], parent?: Token): Generator<{
}>;

declare function expand(ast: AstNode): AstNode;
declare function replaceCompound(input: string, replace: string): string;

declare const colorsFunc: string[];
declare function render(data: AstNode, opt?: RenderOptions): RenderResult;
Expand Down Expand Up @@ -707,4 +708,4 @@ declare function resolve(url: string, currentDirectory: string, cwd?: string): {
declare function parse(iterator: string, opt?: ParserOptions): Promise<ParseResult>;
declare function transform(css: string, options?: TransformOptions): Promise<TransformResult>;

export { colorsFunc, combinators, dirname, expand, funcList, getConfig, hasDeclaration, isAngle, isAtKeyword, isColor, isDigit, isDimension, isFrequency, isFunction, isHash, isHexColor, isIdent, isIdentCodepoint, isIdentStart, isLength, isNewLine, isNonPrintable, isNumber, isPercentage, isPseudo, isResolution, isTime, isWhiteSpace, load, matchType, matchUrl, minify, minifyRule, parse, parseDimension, parseString, reduceSelector, render, renderToken, resolve, splitRule, tokenize, transform, urlTokenMatcher, walk, walkValues };
export { colorsFunc, combinators, dirname, expand, funcList, getConfig, hasDeclaration, isAngle, isAtKeyword, isColor, isDigit, isDimension, isFrequency, isFunction, isHash, isHexColor, isIdent, isIdentCodepoint, isIdentStart, isLength, isNewLine, isNonPrintable, isNumber, isPercentage, isPseudo, isResolution, isTime, isWhiteSpace, load, matchType, matchUrl, minify, minifyRule, parse, parseDimension, parseString, reduceSelector, render, renderToken, replaceCompound, resolve, splitRule, tokenize, transform, urlTokenMatcher, walk, walkValues };
8 changes: 4 additions & 4 deletions dist/lib/ast/expand.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ function expandRule(node) {
}, []).join(',');
}
else {
rule.sel = replaceCompount(rule.sel, ast.sel);
rule.sel = replaceCompound(rule.sel, ast.sel);
}
delete rule.raw;
delete rule.optimized;
Expand All @@ -80,7 +80,7 @@ function expandRule(node) {
const values = [];
if (astAtRule.nam == 'scope') {
if (astAtRule.val.includes('&')) {
astAtRule.val = replaceCompount(astAtRule.val, ast.sel);
astAtRule.val = replaceCompound(astAtRule.val, ast.sel);
}
// @ts-ignore
astAtRule = expand(astAtRule);
Expand Down Expand Up @@ -122,7 +122,7 @@ function expandRule(node) {
// @ts-ignore
return ast.chi.length > 0 ? [ast].concat(result) : result;
}
function replaceCompount(input, replace) {
function replaceCompound(input, replace) {
const tokens = parseString(input);
for (const t of walkValues(tokens)) {
if (t.value.typ == 'Literal') {
Expand Down Expand Up @@ -156,4 +156,4 @@ function replaceCompoundLiteral(selector, replace) {
}).reduce((acc, curr) => acc + (curr == '&' ? replace : curr), '');
}

export { expand };
export { expand, replaceCompound };
72 changes: 57 additions & 15 deletions dist/lib/ast/minify.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
import { isIdentStart, isWhiteSpace, isIdent, isFunction } from '../parser/utils/syntax.js';
import { PropertyList } from '../parser/declaration/list.js';
import { eq } from '../parser/utils/eq.js';
import { render } from '../renderer/render.js';
import '../renderer/utils/color.js';
import { render, renderToken } from '../renderer/render.js';
import { parseString } from '../parser/parse.js';
import { replaceCompound } from './expand.js';
import { walkValues } from './walk.js';

const combinators = ['+', '>', '~'];
const notEndingWith = ['(', '['].concat(combinators);
const definedPropertySettings = { configurable: true, enumerable: false, writable: true };
function minify(ast, options = {}, recursive = false, errors) {
function minify(ast, options = {}, recursive = false, errors, nestingContent) {
function wrapNodes(previous, node, match, ast, i, nodeIndex) {
// @ts-ignore
let pSel = match.selector1.reduce(reducer, []).join(',');
Expand Down Expand Up @@ -296,8 +298,28 @@ function minify(ast, options = {}, recursive = false, errors) {
selector2
};
}
function fixSelector(node) {
// @ts-ignore
if (node.sel.includes('&')) {
const attributes = parseString(node.sel);
for (const attr of walkValues(attributes)) {
if (attr.value.typ == 'Pseudo-class-func' && attr.value.val == ':is') {
let i = attr.value.chi.length;
while (i--) {
if (attr.value.chi[i].typ == 'Literal' && attr.value.chi[i].val == '&') {
attr.value.chi.splice(i, 1);
}
}
}
}
node.sel = attributes.reduce((acc, curr) => acc + renderToken(curr), '');
}
}
// @ts-ignore
if (('chi' in ast) && ast.chi?.length > 0) {
if (!nestingContent) {
nestingContent = options.nestingRules && ast.typ == 'Rule';
}
let i = 0;
let previous;
let node;
Expand All @@ -312,7 +334,6 @@ function minify(ast, options = {}, recursive = false, errors) {
node = ast.chi[i];
// @ts-ignore
if (previous == node) {
// console.error('idem!');
// @ts-ignore
ast.chi.splice(i, 1);
i--;
Expand All @@ -328,7 +349,6 @@ function minify(ast, options = {}, recursive = false, errors) {
i--;
continue;
}
// console.debug({previous, node});
// @ts-ignore
if (previous?.typ == 'AtRule' &&
previous.nam == node.nam &&
Expand All @@ -348,7 +368,7 @@ function minify(ast, options = {}, recursive = false, errors) {
minifyRule(node);
}
else {
minify(node, options, recursive, errors);
minify(node, options, recursive, errors, nestingContent);
}
previous = node;
nodeIndex = i;
Expand Down Expand Up @@ -402,7 +422,7 @@ function minify(ast, options = {}, recursive = false, errors) {
nodeIndex = --i;
// @ts-ignore
previous = ast.chi[nodeIndex];
minify(wrapper, options, recursive, errors);
minify(wrapper, options, recursive, errors, nestingContent);
continue;
}
// @ts-ignore
Expand Down Expand Up @@ -435,7 +455,7 @@ function minify(ast, options = {}, recursive = false, errors) {
let wrap = true;
// @ts-ignore
const selector = node.optimized.selector.reduce((acc, curr) => {
if (curr[0] == '&') {
if (curr[0] == '&' && curr.length > 1) {
if (curr[1] == ' ') {
curr.splice(0, 2);
}
Expand All @@ -459,15 +479,22 @@ function minify(ast, options = {}, recursive = false, errors) {
if (!wrap) {
wrap = selector.some(s => s[0] != '&');
}
const rule = selector.map(s => {
let rule = selector.map(s => {
if (s[0] == '&') {
// @ts-ignore
s[0] = node.optimized.optimized[0];
}
return s.join('');
}).join(',');
// @ts-ignore
node.sel = wrap ? node.optimized.optimized[0] + `:is(${rule})` : rule;
let sel = wrap ? node.optimized.optimized[0] + `:is(${rule})` : rule;
if (rule.includes('&')) {
// @ts-ignore
rule = replaceCompound(rule, node.optimized.optimized[0]);
}
if (sel.length < node.sel.length) {
node.sel = sel;
}
}
}
// @ts-ignore
Expand Down Expand Up @@ -503,7 +530,7 @@ function minify(ast, options = {}, recursive = false, errors) {
minifyRule(node);
}
else {
minify(node, options, recursive, errors);
minify(node, options, recursive, errors, nestingContent);
}
i--;
previous = node;
Expand Down Expand Up @@ -548,7 +575,7 @@ function minify(ast, options = {}, recursive = false, errors) {
minifyRule(previous);
}
else {
minify(previous, options, recursive, errors);
minify(previous, options, recursive, errors, nestingContent);
}
}
}
Expand All @@ -560,11 +587,19 @@ function minify(ast, options = {}, recursive = false, errors) {
minifyRule(previous);
}
else {
minify(previous, options, recursive, errors);
minify(previous, options, recursive, errors, nestingContent);
}
}
}
}
if (!nestingContent &&
// @ts-ignore
previous != null &&
// previous.optimized != null &&
previous.typ == 'Rule' &&
previous.sel.includes('&')) {
fixSelector(previous);
}
previous = node;
nodeIndex = i;
}
Expand All @@ -577,10 +612,18 @@ function minify(ast, options = {}, recursive = false, errors) {
else {
// @ts-ignore
if (!(node.typ == 'AtRule' && node.nam != 'font-face')) {
minify(node, options, recursive, errors);
minify(node, options, recursive, errors, nestingContent);
}
}
}
if (!nestingContent &&
// @ts-ignore
node != null &&
// previous.optimized != null &&
node.typ == 'Rule' &&
node.sel.includes('&')) {
fixSelector(node);
}
}
return ast;
}
Expand Down Expand Up @@ -819,7 +862,6 @@ function reduceRuleSelector(node) {
Object.defineProperty(node, 'raw', { ...definedPropertySettings, value: raw });
}
}
// }
}

export { combinators, hasDeclaration, minify, minifyRule, reduceSelector, splitRule };
8 changes: 2 additions & 6 deletions dist/lib/ast/walk.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,8 @@
function* walk(node) {
// @ts-ignore
yield* doWalk(node, null, null);
}
function* doWalk(node, parent, root) {
function* walk(node, parent, root) {
yield { node, parent, root };
if ('chi' in node) {
for (const child of node.chi) {
yield* doWalk(child, node, (root ?? node));
yield* walk(child, node, (root ?? node));
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions dist/lib/parser/parse.js
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ async function parse(iterator, opt = {}) {
if (delim.typ == 'Block-start') {
const position = map.get(tokens[0]);
const uniq = new Map;
parseTokens(tokens, { minify: options.minify }).reduce((acc, curr, index, array) => {
parseTokens(tokens, { minify: true }).reduce((acc, curr, index, array) => {
if (curr.typ == 'Whitespace') {
if (trimWhiteSpace.includes(array[index - 1]?.typ) ||
trimWhiteSpace.includes(array[index + 1]?.typ) ||
Expand All @@ -213,7 +213,7 @@ async function parse(iterator, opt = {}) {
return acc;
}
}
let t = renderToken(curr, { minify: true });
let t = renderToken(curr, { minify: false });
if (t == ',') {
acc.push([]);
}
Expand Down
8 changes: 6 additions & 2 deletions dist/lib/parser/tokenize.js
Original file line number Diff line number Diff line change
Expand Up @@ -121,12 +121,16 @@ function* tokenize(iterator) {
}
function next(count = 1) {
let char = '';
while (count-- > 0 && ind < iterator.length) {
let chr = '';
if (count < 0) {
return '';
}
while (count-- && (chr = iterator.charAt(ind + 1))) {
char += chr;
const codepoint = iterator.charCodeAt(++ind);
if (isNaN(codepoint)) {
return char;
}
char += iterator.charAt(ind);
if (isNewLine(codepoint)) {
lin++;
col = 0;
Expand Down
3 changes: 2 additions & 1 deletion dist/lib/renderer/render.js
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,8 @@ function renderToken(token, options = {}, reducer, errors) {
}
return val + unit;
case 'Perc':
return token.val + '%';
const perc = reduceNumber(token.val);
return options.minify && perc == '0' ? '0' : perc + '%';
case 'Number':
return reduceNumber(token.val);
case 'Comment':
Expand Down
2 changes: 1 addition & 1 deletion dist/node/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export { combinators, hasDeclaration, minify, minifyRule, reduceSelector, splitRule } from '../lib/ast/minify.js';
export { walk, walkValues } from '../lib/ast/walk.js';
export { expand } from '../lib/ast/expand.js';
export { expand, replaceCompound } from '../lib/ast/expand.js';
export { colorsFunc, render, renderToken } from '../lib/renderer/render.js';
import { parse as parse$1 } from '../lib/parser/parse.js';
export { parseString, urlTokenMatcher } from '../lib/parser/parse.js';
Expand Down
2 changes: 1 addition & 1 deletion dist/web/index.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export { combinators, hasDeclaration, minify, minifyRule, reduceSelector, splitRule } from '../lib/ast/minify.js';
export { walk, walkValues } from '../lib/ast/walk.js';
export { expand } from '../lib/ast/expand.js';
export { expand, replaceCompound } from '../lib/ast/expand.js';
export { colorsFunc, render, renderToken } from '../lib/renderer/render.js';
import { parse as parse$1 } from '../lib/parser/parse.js';
export { parseString, urlTokenMatcher } from '../lib/parser/parse.js';
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@tbela99/css-parser",
"description": "CSS parser for node and the browser",
"version": "0.0.1-rc6",
"version": "0.0.1-rc7",
"exports": {
".": "./dist/node/index.js",
"./umd": "./dist/index-umd-web.js",
Expand Down
6 changes: 3 additions & 3 deletions src/lib/ast/expand.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ function expandRule(node: AstRule): Array<AstRule | AstAtRule> {
}, <string[]>[]).join(',');
} else {

rule.sel = replaceCompount(rule.sel, ast.sel);
rule.sel = replaceCompound(rule.sel, ast.sel);
}

delete rule.raw;
Expand All @@ -115,7 +115,7 @@ function expandRule(node: AstRule): Array<AstRule | AstAtRule> {

if (astAtRule.val.includes('&')) {

astAtRule.val = replaceCompount(astAtRule.val, ast.sel);
astAtRule.val = replaceCompound(astAtRule.val, ast.sel);
}

// @ts-ignore
Expand Down Expand Up @@ -172,7 +172,7 @@ function expandRule(node: AstRule): Array<AstRule | AstAtRule> {
return ast.chi.length > 0 ? [ast].concat(result) : result;
}

function replaceCompount(input: string, replace: string) {
export function replaceCompound(input: string, replace: string) {

const tokens = parseString(input);

Expand Down
Loading