Skip to content

Commit

Permalink
dia.attributes: support negative number addition/subtraction in calc(…
Browse files Browse the repository at this point in the history
…) expression (#1571)
  • Loading branch information
kumilingus authored Nov 15, 2021
1 parent d75de7d commit 3e7fd63
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
18 changes: 16 additions & 2 deletions src/dia/attributes/calc.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const props = {
const propsList = Object.keys(props).map(key => props[key]).join('');
const numberPattern = '[-+]?[0-9]*\\.?[0-9]+(?:[eE][-+]?[0-9]+)?';
const findSpacesRegex = /\s/g;
const parseExpressionRegExp = new RegExp(`^(${numberPattern}\\*)?([${propsList}])([-+]${numberPattern})?$`, 'g');
const parseExpressionRegExp = new RegExp(`^(${numberPattern}\\*)?([${propsList}])([-+]{1,2}${numberPattern})?$`, 'g');

function throwInvalid(expression) {
throw new Error(`Invalid calc() expression: ${expression}`);
Expand Down Expand Up @@ -44,7 +44,21 @@ export function evalCalcExpression(expression, bbox) {
break;
}
}
return parseFloat(multiply) * dimension + parseFloat(add);
return parseFloat(multiply) * dimension + evalAddExpression(add);
}

function evalAddExpression(addExpression) {
if (!addExpression) return 0;
const [sign] = addExpression;
switch (sign) {
case '+': {
return parseFloat(addExpression.substr(1));
}
case '-': {
return -parseFloat(addExpression.substr(1));
}
}
return parseFloat(addExpression);
}

export function isCalcAttribute(value) {
Expand Down
4 changes: 3 additions & 1 deletion test/jointjs/dia/attributes.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ QUnit.module('Attributes', function() {

QUnit.module('getAttributeDefinition()', function() {

QUnit.test('will find correct defintion', function(assert) {
QUnit.test('will find correct definition', function(assert) {

joint.dia.attributes.globalTest = 'global';
joint.dia.attributes.priority = 'lower';
Expand Down Expand Up @@ -353,6 +353,8 @@ QUnit.module('Attributes', function() {
['calc(h-10)', String(HEIGHT - 10)],
['calc(2*w+10)', String(WIDTH * 2 + 10)],
['calc(2*h+10)', String(HEIGHT * 2 + 10)],
['calc(w+-10)', String(WIDTH - 10)],
['calc(h--10)', String(HEIGHT + 10)],
// spaces
['calc( 2 * w + 10 )', String(WIDTH * 2 + 10)],
['calc( 2 * h + 10 )', String(HEIGHT * 2 + 10)],
Expand Down

0 comments on commit 3e7fd63

Please sign in to comment.