DSI Units JS Library is a JavaScript library for parsing, rendering, and interactively editing D‑SI unit strings. This library is a mainly LMM-generated version of the corresponding dsiunits Python package. (Repository: digitaldynamicmeasurement/dsiUnits).
The library includes two main components:
- DSIUnit – a class for parsing and rendering D‑SI unit strings.
-
DSIUnitInput – a custom web component (
<dsi-unit-input>
) that provides an auto‑complete interactive input field for D‑SI units.
This project is licensed under the LGPL-2.1 License.
You will be able to install the library via npm in near future:
npm install dsiunits-js
Or clone the repository and bundle the code with your preferred bundler (Webpack, Rollup, etc.).
For ES modules, import the classes as follows:
import { DSIUnit } from "dsiunits-js/src/dsiUnit.js";
import "dsiunits-js/src/dsiUnitInput.js"; // This registers the <dsi-unit-input> custom element.
The DSIUnit
class is used to parse and render a D‑SI unit string.
const unit = new DSIUnit("\\metre\\tothe{2}");
-
Parameters:
-
dsiString
(string): The raw D‑SI unit string (e.g.,"\metre\tothe{2}"
).
-
-
dsiString
– The original D‑SI string. -
tree
– The parsed representation of the D‑SI unit. -
warnings
– An array of warnings encountered during parsing. -
nonDsiUnit
– A boolean indicating whether the string was marked as a non‑DSI unit. -
valid
– A boolean indicating whether the parsed unit is valid. -
scaleFactor
– The overall scale factor (default: 1.0).
-
toHTML(options)
Renders the unit as an HTML string.
Parameters:
-
options
(object, optional):-
wrapper
(string): String to wrap the rendered output. -
prefix
(string): String to prepend. -
suffix
(string): String to append. -
oneLine
(boolean): Iftrue
, renders a compact, single‑line version (fractions with “/” and roots in inline format).
-
Example:
console.log(unit.toHTML({ oneLine: true }));
-
-
toString()
Returns the canonical D‑SI string representation.
console.log(unit.toString());
The DSIUnitInput
custom element provides an interactive auto‑complete input for D‑SI unit strings.
<dsi-unit-input suggestions-list="kilo,mega,milli,metre,second,per,tothe"></dsi-unit-input>
-
Auto‑Completion:
As you type after a backslash (\\
), suggestions are provided based on context:- If a prefix is accepted (e.g.,
\milli
), only allowed units are suggested. - If a unit is accepted, all allowed tokens (including
\per
and\tothe
) are suggested. - Arrow keys navigate suggestions; Tab, Enter, or Right Arrow accept a suggestion.
- If a prefix is accepted (e.g.,
-
Focus/Blur Behavior:
When the field loses focus, the rendered unit (usingDSIUnit.toHTML({ oneLine: true })
) is shown. Clicking the rendered output restores the raw input for editing. -
Customization:
Override the allowed tokens by setting thesuggestions-list
attribute with a comma‑separated list.
-
value
Returns the current raw D‑SI unit string. -
live
A boolean property (default:true
) to enable/disable live updating.