base-ui icon indicating copy to clipboard operation
base-ui copied to clipboard

Can Number Field be used to evaluate equations?

Open woodward54 opened this issue 6 months ago • 3 comments

I'd like to make a Number Field that can also evaluate equations using math.js.

"5 + 20" -> "25"

"sqrt(16)" -> "4"

Is this possible with the current Number Field? I can't seem to find a way to let the input accept special characters. I'd also need to extend the parse function to attempt to evaluate with math.js before the base-ui parse function takes over.

woodward54 avatar Jun 23 '25 22:06 woodward54

I can't seem to find a way to let the input accept special characters.

Generally event handlers have a preventBaseUIHandler method that you can call to skip the component's internal logic and override it with your own:

<NumberField.Input
  onKeyDown={(event) => {
    event.preventBaseUIHandler();
    // your logic instead
  }}
/>

However for this case I'm not sure if this is possible because it may skip so much that it could affect other features

Can Number Field be used to evaluate equations?

This isn't really a use-case we considered for Numberfield 😅 are you making something like a spreadsheet app? @woodward54

mj12albert avatar Jun 24 '25 08:06 mj12albert

I'm working on a 3d web editor, I was hoping to have a rich numeric text box (similar to how the Unity editor does it). But it looks like I might need to make a custom input for this case. Itd be an awesome feature for base-ui if I could pass in my own custom "preparse" function as a prop to the Number Field, but not sure if that would conflict with the existing parse system.

woodward54 avatar Jun 24 '25 14:06 woodward54

a rich numeric text box (similar to how the Unity editor does it

My guess we would prefer to make an actual component for this rather than adding the functionality to NumberField 🤔

What do you think @colmtuite ?

mj12albert avatar Jun 25 '25 05:06 mj12albert

How does Unity do it? Got a screenshot?

colmtuite avatar Jul 02 '25 22:07 colmtuite

It's more of a text field that parses the input as the user types, and evaluates in realtime. Here's a screenshot, but best if you can play around with it yourself to get a feel for it.

I ended up forking the base-ui NumberField to add this functionality in my project- It required heavy modifications that changed some of the core behavior (user can now type anything in the input, including characters and symbols, but only numbers & equations will be parsed and committed).

Image

woodward54 avatar Jul 04 '25 18:07 woodward54

@woodward54 In Unity, is this a number field? Or just a text input?

colmtuite avatar Jul 08 '25 03:07 colmtuite

It's a text input, that resolves to a number

woodward54 avatar Jul 09 '25 17:07 woodward54