All files / src SSVGPropertyNumber.js

76.92% Statements 20/26
45% Branches 9/20
100% Functions 4/4
76% Lines 19/25

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71          1x                       23x   23x 23x   23x 23x       23x       23x 61x                 615x     615x       615x 154x   615x         180x 180x 180x       180x         234x      
// @ts-check
 
import SSVGProperty from './SSVGProperty';
import { defaultTo, isNil } from './utils';
import d from 'debug';
const debug = d('ssvg:prop');
 
/**
 * @typedef {import('./SSVGState').default} SSVGState
 */
 
export default class SSVGPropertyNumber extends SSVGProperty {
  /**
   * @param {SSVGState} ssvg
   * @param {Element} element
   */
  constructor(ssvg, element) {
    super(ssvg, element);
 
    this.min = Number.parseFloat(element.getAttribute('min') || '0');
    this.max = Number.parseFloat(element.getAttribute('max') || '1');
    // @ts-ignore: of course we can parseFloat a number
    this._value = Number.parseFloat(defaultTo(element.getAttribute('initial'), this.min));
    Iif (Number.isNaN(this.min)) {
      throw new SyntaxError('invalid min value for number property: ' +
        (element.getAttribute('min') || ''));
    }
    else Iif (Number.isNaN(this.max)) {
      throw new SyntaxError('invalid max value for number property: ' +
        (element.getAttribute('max') || ''));
    }
    for (let i = 0; i < this.relations.length; ++i) {
      this.relations[i].setInitial(this);
    }
  }
 
  /**
   * @param {number?=} [value]
   * @return {number}
   */
  normalize(value) {
    Iif (this.min === this.max) {
      return this.min;
    }
    else Iif (!isNil(value)) {
      // @ts-ignore
      return (Number.parseFloat(value) - this.min) / (this.max - this.min);
    }
    else if (isNil(this._normalized)) {
      this._normalized = (this._value - this.min) / (this.max - this.min);
    }
    return this._normalized;
  }
 
  /** @param {number|any} value */
  set value(value) {
    this._normalized = null;
    var num = Number.parseFloat(value);
    Iif (Number.isNaN(num)) {
      debug('invalid number %o for property %s', value, this.name);
      num = this.min;
    }
    super.value = num;
  }
 
  /** @return {number|any} */
  get value() {
    return super.value;
  }
}