Skip to content

Commit f306e5f

Browse files
authored
Merge pull request #446 from ZeusWPI/calculate
calculate in the money request/give field
2 parents ce6ca4b + 9726576 commit f306e5f

3 files changed

Lines changed: 114 additions & 16 deletions

File tree

app/assets/javascript/react/src/components/TransactionForm.jsx

Lines changed: 24 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import React from "react";
22

33
import Select from 'react-select';
44
import Fuse from 'fuse.js';
5+
import { evaluate } from "mathjs";
56

67
const url = function (path) {
78
return (window.base_url || '') + "/" + path;
@@ -101,36 +102,45 @@ class Action extends React.Component {
101102
);
102103
}
103104
}
104-
105105
class Amount extends React.Component {
106-
onChange = (ref) => {
107-
return this.props.setAmount(ref.target.value);
106+
handleKeyDown = (ev) => {
107+
if (ev.key === 'Enter') {
108+
this.calculate(ev);
109+
}
108110
}
109111

110-
format(ref) {
111-
const { target } = ref;
112-
if (target.value) {
113-
return target.value = parseFloat(target.value).toFixed(2);
112+
calculate = (ev) => {
113+
try {
114+
const result = evaluate(ev.target.value);
115+
this.props.setAmount(result.toFixed(2));
116+
117+
ev.target.value = result.toFixed(2);
118+
} catch (err) {
119+
this.props.setAmount(null);
120+
console.error("Invalid expression", err);
114121
}
115122
}
116123

117124
render() {
118-
return(
125+
return (
119126
<div className="relative z-0 w-full mb-6 group">
120127
<div className="flex">
121128
<span className="inline-flex items-center px-3 text-sm text-gray-900 bg-gray-100 border border-r-0 border-gray-300 rounded-l-md">
122129
Ƶ
123130
</span>
124131
<input
125-
name={'transaction[euros]'}
126-
onBlur={this.format}
127-
onChange={this.onChange}
128-
placeholder={'0.00'}
129-
type={'number'}
130-
step="0.01"
132+
name="transaction[euros]"
133+
type="text"
134+
placeholder="0.00"
135+
onBlur={this.calculate}
136+
onChange={this.props.setAmount}
137+
onKeyDown={this.handleKeyDown}
131138
className="block flex-initial p-2 w-1/2 sm:text-sm rounded-none rounded-r-lg bg-white border border-gray-200 text-gray-900 focus:ring-blue-500 focus:border-blue-500 border-gray-300"
132139
/>
133140
</div>
141+
<p className="mt-1 text-xs text-gray-500 italic">
142+
Type a formula to do calculations (10 + 5 * 2)
143+
</p>
134144
</div>
135145
);
136146
}

package-lock.json

Lines changed: 89 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
"esbuild": "^0.27.2",
1111
"fuse.js": "^7.1.0",
1212
"luxon": "^3.7.2",
13+
"mathjs": "^15.1.1",
1314
"react": "^19.2.3",
1415
"react-dom": "^19.2.3",
1516
"react-select": "^5.10.2",

0 commit comments

Comments
 (0)