Skip to content

Commit

Permalink
Merge pull request #115 from jsdom/feature/calc-simple
Browse files Browse the repository at this point in the history
Implement basic calc
  • Loading branch information
jsakas committed Mar 30, 2020
2 parents b4c49d6 + d8048a9 commit 62b3b1b
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 0 deletions.
6 changes: 6 additions & 0 deletions lib/CSSStyleDeclaration.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -547,4 +547,10 @@ describe('CSSStyleDeclaration', () => {
expect(style.getPropertyValue('--foo')).toEqual('');
expect(style.getPropertyValue('--fOo')).toEqual('purple');
});

test('supports calc', () => {
const style = new CSSStyleDeclaration();
style.setProperty('width', 'calc(100% - 100px)');
expect(style.getPropertyValue('width')).toEqual('calc(100% - 100px)');
});
});
11 changes: 11 additions & 0 deletions lib/parsers.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ exports.TYPES = {
ANGLE: 8,
KEYWORD: 9,
NULL_OR_EMPTY_STR: 10,
CALC: 11,
};

// rough regular expressions
Expand All @@ -30,6 +31,7 @@ var stringRegEx = /^("[^"]*"|'[^']*')$/;
var colorRegEx1 = /^#([0-9a-fA-F]{3,4}){1,2}$/;
var colorRegEx2 = /^rgb\(([^)]*)\)$/;
var colorRegEx3 = /^rgba\(([^)]*)\)$/;
var calcRegEx = /^calc\(([^)]*)\)$/;
var colorRegEx4 = /^hsla?\(\s*(-?\d+|-?\d*.\d+)\s*,\s*(-?\d+|-?\d*.\d+)%\s*,\s*(-?\d+|-?\d*.\d+)%\s*(,\s*(-?\d+|-?\d*.\d+)\s*)?\)/;
var angleRegEx = /^([-+]?[0-9]*\.?[0-9]+)(deg|grad|rad)$/;

Expand Down Expand Up @@ -61,6 +63,9 @@ exports.valueType = function valueType(val) {
if (urlRegEx.test(val)) {
return exports.TYPES.URL;
}
if (calcRegEx.test(val)) {
return exports.TYPES.CALC;
}
if (stringRegEx.test(val)) {
return exports.TYPES.STRING;
}
Expand All @@ -70,6 +75,7 @@ exports.valueType = function valueType(val) {
if (colorRegEx1.test(val)) {
return exports.TYPES.COLOR;
}

var res = colorRegEx2.exec(val);
var parts;
if (res !== null) {
Expand Down Expand Up @@ -201,6 +207,11 @@ exports.parsePercent = function parsePercent(val) {

// either a length or a percent
exports.parseMeasurement = function parseMeasurement(val) {
var type = exports.valueType(val);
if (type === exports.TYPES.CALC) {
return val;
}

var length = exports.parseLength(val);
if (length !== undefined) {
return length;
Expand Down
7 changes: 7 additions & 0 deletions lib/parsers.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,13 @@ describe('valueType', () => {

expect(output).toEqual(parsers.TYPES.LENGTH);
});

it('returns calc from calc(100px * 2)', () => {
let input = 'calc(100px * 2)';
let output = parsers.valueType(input);

expect(output).toEqual(parsers.TYPES.CALC);
});
});
describe('parseInteger', () => {
it.todo('test');
Expand Down

0 comments on commit 62b3b1b

Please sign in to comment.