|
| 1 | +--- |
| 2 | +title: Customizing MathJS |
| 3 | +description: An example on how to import customizations into mathjs |
| 4 | +--- |
| 5 | + |
| 6 | +You may find yourself wanting to add functionality to the [math view fields](/obsidian-meta-bind-plugin-docs/reference/viewfields/math/). |
| 7 | +And as they use [mathjs](https://mathjs.org/) internally, you actually can! |
| 8 | + |
| 9 | +## Importing new options into mathJS |
| 10 | + |
| 11 | +The mathjs library allows the user to define his own functions and constants, as described in [their documentation](https://mathjs.org/docs/core/extension.html). |
| 12 | + |
| 13 | +To leverage that, Meta Bind exposed its mathjs instance for you to modify. |
| 14 | +The most sensible place to do this, is inside a [JS-Engine startup-script](/obsidian-js-engine-plugin-docs/guides/startupscripts/). |
| 15 | +This ensures the modifications are loaded early and will be immediately available when the first documents gets rendered. |
| 16 | + |
| 17 | +:::caution |
| 18 | +Modifying mathJS via a js-engine codeblock inside a document may cause timing problems and is not recommended! |
| 19 | +::: |
| 20 | + |
| 21 | +### Adding a custom function `clamp` |
| 22 | + |
| 23 | +As an example, we defined the `clamp()` function, which is not part of default mathJS, but can be very helpful. |
| 24 | +It takes in three parameters, the current value, a minimum and a maximum. It returns the current value as long as its inside the range otherwise the boundary-value. |
| 25 | + |
| 26 | +```js |
| 27 | +clamp: (val, min, max) => Math.min(Math.max(min, val), max) |
| 28 | +``` |
| 29 | + |
| 30 | +Add this definitions inside a JavaScrypt file stored in you Vault and enable that file to be [run as a startup script](/obsidian-js-engine-plugin-docs/guides/startupscripts/). |
| 31 | +Inside the file you use the `mathJSimport(dict, options)` function from the API to import you definitions into mathjs. |
| 32 | + |
| 33 | +```js |
| 34 | +const mb = engine.getPlugin('obsidian-meta-bind-plugin').api; |
| 35 | + |
| 36 | +mb.mathJSimport({ |
| 37 | + // we define the function 'clamp' |
| 38 | + clamp: (val, min, max) => Math.min(Math.max(min, val), max), |
| 39 | + |
| 40 | + // and a constant 'foo' |
| 41 | + foo: 42 |
| 42 | +}); |
| 43 | +``` |
| 44 | + |
| 45 | +Now you can create a view field using that function. |
| 46 | +This example will always display values between 0 and 10, even if `num` gets outside that range. |
| 47 | + |
| 48 | +```meta-bind |
| 49 | +VIEW[clamp({num}, 0, 10)] |
| 50 | +``` |
| 51 | + |
| 52 | +You can also use the new constant `foo`. This will display 52: |
| 53 | + |
| 54 | +```meta-bind |
| 55 | +VIEW[foo + 10] |
| 56 | +``` |
0 commit comments