Skip to content
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 README.md
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,8 @@ Parsing of LESS variables is supported.

The AST will contain an `AtRule` node with a `variable: true` property.

_Note: LESS variables are strictly parsed - a colon (`:`) must immediately follow a variable name._
Whitespace is allowed on either side of the colon. Comments are allowed after
the colon, but not between the variable name and the colon.

## Stringify

Expand Down
62 changes: 61 additions & 1 deletion lib/less-parser.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,66 @@ class LessParser extends Parser {
}

atrule(token) {
const following = [];
let next = this.tokenizer.nextToken();
while (next && next[0] === 'space') {
following.push(next);
next = this.tokenizer.nextToken();
}

if (token[1].toLowerCase() === '@page' && next?.[0] === ':') {
const selector = [next];
let part = this.tokenizer.nextToken();
while (part && part[0] !== '{' && part[0] !== ';' && part[0] !== '}') {
selector.push(part);
part = this.tokenizer.nextToken();
}
if (part) {
selector.push(part);
}
const pageSelector =
part?.[0] === '{' &&
/^(?::[\w-]+)+(?:\s*,\s*(?::[\w-]+)+)*$/.test(
selector
.slice(0, -1)
.filter((item) => item[0] !== 'comment')
.map((item) => item[1])
.join('')
.trim(),
);
if (pageSelector && following.length === 0) {
token = [...token];
while (
selector.length > 1 &&
selector[0][0] !== 'space' &&
selector[0][0] !== 'comment'
) {
const item = selector.shift();
token[1] += item[1];
token[3] = item[3] ?? item[2];
}
}
for (const item of selector.reverse()) {
this.tokenizer.back(item);
}
next = pageSelector ? undefined : this.tokenizer.nextToken();
}

let beforeColon = '';
if (next?.[0] === ':') {
beforeColon = following.map((part) => part[1]).join('');
token = [...token];
token[1] += ':';
token[4] = 'variable';
} else {
if (next) {
following.push(next);
}
for (const part of following.reverse()) {
this.tokenizer.back(part);
}
}

if (token[4] !== 'variable') {
const tokens = [];
let token = this.tokenizer.nextToken();
Expand Down Expand Up @@ -52,7 +112,7 @@ class LessParser extends Parser {
raws.between = '';
}
}
raws.afterName = `:${raws.afterName || ''}`;
raws.afterName = `${beforeColon}:${raws.afterName || ''}`;
node.params =
(comment ? comment[2] : '') +
(raws.params ? raws.params.raw : node.params);
Expand Down
8 changes: 1 addition & 7 deletions lib/less-tokenize.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,8 @@ const ASTERISK = '*'.charCodeAt(0)
const COLON = ':'.charCodeAt(0)
const AT = '@'.charCodeAt(0)

const RE_AT_END = /[\t\n\f\r "#'()/;[\\\]{}]/g
// LESS PATCH {
const RE_AT_END = /[\t\n\f\r "#'():/;[\\\]{}]/g
const RE_WORD_END = /[\t\n\f\r !"#'():;@[\\\]{}]|\/(?=\*)|\$(?=\{)/g
// } LESS PATCH
const RE_BAD_BRACKET = /.[\r\n"'(/\\]/
Expand Down Expand Up @@ -245,12 +245,6 @@ export default function tokenizer(input, options = {}) {
}

currentToken = ['at-word', css.slice(pos, next + 1), pos, next]
// LESS PATCH {
if (currentToken[1].endsWith(':')) {
currentToken[4] = 'variable'
}
// } LESS PATCH

pos = next
break
}
Expand Down
91 changes: 82 additions & 9 deletions test/parser/variables.test.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,79 @@
import test from 'ava';
import less from 'less';
import { outdent } from 'outdent';
import AtRule from 'postcss/lib/at-rule';

import { parse } from '../../lib/index.js';
import { nodeToString } from '../helpers/node-to-string.js';

test('preserves at-rules with inline comments before a colon', (t) => {
for (const [less, params] of [
['@foo // comment\n: red;', '// comment\n: red'],
['@foo // first\n // second\n: red;', '// first\n // second\n: red'],
["@foo // it's; { not closed\n: red;", "// it's; { not closed\n: red"],
test('parses variables with whitespace and comments after the colon', (t) => {
for (const [less, afterName, value] of [
['@foo:red;', ':', 'red'],
['@foo :red;', ' :', 'red'],
['@foo : red;', ' : ', 'red'],
['@foo:/* after */red;', ':', '/* after */red'],
['@foo : /* after */ red;', ' : ', '/* after */ red'],
['@foo: // after\nred;', ': ', '// after\nred'],
]) {
const root = parse(less);
const node = root.first;

t.is(node.type, 'atrule');
t.is(node.name, 'foo');
t.is(node.variable, undefined);
t.is(node.value, undefined);
t.is(node.params, params);
t.deepEqual(node.raws, { before: '', between: '', afterName: ' ' });
t.true(node.variable);
t.is(node.value, value);
t.is(node.params, value);
t.is(node.raws.afterName, afterName);
t.is(nodeToString(root), less);

node.value = 'changed';
t.is(nodeToString(root), `@foo${afterName}changed;`);
}
});

test('matches Less variable classification around the colon', async (t) => {
for (const [source, isVariable] of [
['@foo:red;', true],
['@foo :red;', true],
['@foo : red;', true],
['@foo:/* after */red;', true],
['@foo: // after\nred;', true],
['@foo/* before */:red;', false],
['@foo /* first */ /* second */ : /* after */ red;', false],
['@foo // comment\n: red;', false],
['@foo // first\n // second\n: red;', false],
["@foo // it's; { not closed\n: red;", false],
]) {
const lessRoot = await less.parse(source);
const root = parse(source);

t.is(lessRoot.rules[0].type === 'Declaration', isVariable);
t.is(Boolean(root.first.variable), isVariable);
t.is(root.first.name, 'foo');
t.is(nodeToString(root), source);
}
});

test('parses nested and unterminated variable declarations', (t) => {
const less = '.rule {\n @foo :red;\n color: @foo;\n}';
const root = parse(less);
const variable = root.first.first;

t.true(variable.variable);
t.is(variable.name, 'foo');
t.is(variable.value, 'red');
t.is(variable.source.start.line, 2);
t.is(variable.source.start.column, 3);
t.is(variable.source.end.line, 2);
t.is(variable.source.end.column, 21);
t.is(root.first.last.value, '@foo');
t.is(nodeToString(root), less);

const withoutSemicolon = parse('@foo :red');
t.is(withoutSemicolon.first.value, 'red');
t.is(nodeToString(withoutSemicolon), '@foo :red');
});

test('preserves at-rule inline comments in params and raws', (t) => {
for (const [less, params, between] of [
['@media // comment\n screen {}', '// comment\n screen', ' '],
Expand Down Expand Up @@ -70,6 +120,29 @@ test('@pageXxx like variable but not @page selector', (t) => {
t.is(nodeToString(root), less);
});

test('distinguishes page variables from page pseudo-selectors', (t) => {
for (const less of ['@page:red;', '@page : red;']) {
const root = parse(less);
t.true(root.first.variable);
t.is(root.first.name, 'page');
t.is(root.first.value, 'red');
t.is(nodeToString(root), less);
}

for (const [less, name, params] of [
['@page :left {}', 'page', ':left'],
['@page:left {}', 'page:left', ''],
['@page :first:left /* comment */ {}', 'page', ':first:left'],
['@page :custom {}', 'page', ':custom'],
]) {
const root = parse(less);
t.is(root.first.variable, undefined);
t.is(root.first.name, name);
t.is(root.first.params, params);
t.is(nodeToString(root), less);
}
});

test('string values', (t) => {
const less = '@var: "test";';
const root = parse(less);
Expand Down