diff --git a/editor.js b/editor.js index a423bbfac..6d17babaf 100644 --- a/editor.js +++ b/editor.js @@ -1436,7 +1436,7 @@ class MenuBar extends QinoqMorph { } } -class Settings extends QinoqMorph { +export class Settings extends QinoqMorph { static get properties () { return { name: { @@ -1549,7 +1549,8 @@ class Settings extends QinoqMorph { inputLineUpdate (input) { try { - const newRatio = eval(input); + const newRatio = Settings.matchNumberOrFraction(input); + if (!newRatio) throw new Error('The input was not a number!'); this.interactive.fixedAspectRatio = newRatio; this.editor.onInteractiveZoomed(); success('Ratio updated!'); @@ -1558,6 +1559,15 @@ class Settings extends QinoqMorph { } } + static matchNumberOrFraction (inputString) { + // eslint-disable-next-line no-useless-escape + const match = inputString.match(RegExp('^(\\d+)((\\.\\d+)|(\\/\\d+))?$', 'i')); + if (!match) return null; + if (!match[2]) return Number(match[1]); + if (match[2].includes('.')) return Number(match[1].concat(match[3])); + if (match[2].includes('/')) return Number(match[1]) / Number(match[4].substring(1)); + } + dropDownSelectorUpdate (input) { if (input == 'Custom') { this.ui.inputLine.visible = true; diff --git a/tests/settings-test.js b/tests/settings-test.js new file mode 100644 index 000000000..0bc2872f6 --- /dev/null +++ b/tests/settings-test.js @@ -0,0 +1,23 @@ +/* global it, describe */ +import { expect } from 'mocha-es6'; +import { Settings } from '../editor.js'; + +describe('Settings', () => { + it('parses fractions and numbers in correct formats', () => { + expect(Settings.matchNumberOrFraction('3')).to.be.equal(3); + expect(Settings.matchNumberOrFraction('4/3')).to.be.equal(4 / 3); + expect(Settings.matchNumberOrFraction('3.5')).to.be.equal(3.5); + expect(Settings.matchNumberOrFraction('3123.123')).to.be.equal(3123.123); + expect(Settings.matchNumberOrFraction('3123/123')).to.be.equal(3123 / 123); + }); + + it('parses fractions and numbers in incorrect formats', () => { + expect(Settings.matchNumberOrFraction('123/456.789')).to.be.null; + expect(Settings.matchNumberOrFraction('123.456/789')).to.be.null; + expect(Settings.matchNumberOrFraction('3.')).to.be.null; + expect(Settings.matchNumberOrFraction('3/')).to.be.null; + expect(Settings.matchNumberOrFraction('[3/4]')).to.be.null; + expect(Settings.matchNumberOrFraction('[3/')).to.be.null; + expect(Settings.matchNumberOrFraction('{3/}')).to.be.null; + }); +});