@dative-gpi/foundation-shared-services 1.0.191-add-unit-formatter → 1.0.191-add-unit-formatter-2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,72 +1,87 @@
1
- import { UnitPrefix } from "@dative-gpi/foundation-shared-domain/enums/units";
2
1
  import { useAppLanguageCode } from "@dative-gpi/foundation-shared-services/composables";
2
+ import { SI_PREFIXES } from "@dative-gpi/foundation-shared-services/config/units";
3
3
  import { type UnitDefinition, unitRegistry } from "@dative-gpi/foundation-shared-domain/models";
4
4
 
5
5
  export function useUnitFormatter() {
6
6
  const { languageCode } = useAppLanguageCode();
7
7
 
8
- const SI_PREFIXES = [
9
- { prefix: UnitPrefix.Nano, factor: 1e-9 },
10
- { prefix: UnitPrefix.Micro, factor: 1e-6 },
11
- { prefix: UnitPrefix.Milli, factor: 1e-3 },
12
- { prefix: UnitPrefix.None, factor: 1 },
13
- { prefix: UnitPrefix.Kilo, factor: 1e3 },
14
- { prefix: UnitPrefix.Mega, factor: 1e6 },
15
- { prefix: UnitPrefix.Giga, factor: 1e9 },
16
- { prefix: UnitPrefix.Tera, factor: 1e12 },
17
- { prefix: UnitPrefix.Peta, factor: 1e15 },
18
- ];
19
-
20
- function scaleUpByParent(value: number, unit: string, fixedUnit?: string): { value: number; unit: string } {
21
- let currentValue = value;
22
- let currentUnit = unit;
23
- const SCALE_FACTOR = 1000;
24
-
25
- while (true) {
26
- const unitDefinition = unitRegistry[currentUnit];
27
-
28
- if (!unitDefinition?.parent) {
29
- break;
30
- }
31
-
32
- if (fixedUnit && currentUnit === fixedUnit) {
33
- break;
34
- }
35
-
36
- const scaledValue = currentValue / SCALE_FACTOR;
37
-
38
- if (Math.abs(scaledValue) >= 1) {
39
- currentValue = scaledValue;
40
- currentUnit = unitDefinition.parent;
41
- } else {
42
- break;
43
- }
8
+ /**
9
+ * Converts a value from one unit to another of the same family
10
+ */
11
+ function convert(value: number, fromUnit: string, toUnit: string): number {
12
+ const sourceUnitDefinition = unitRegistry[fromUnit];
13
+ const targetUnitDefinition = unitRegistry[toUnit];
14
+
15
+ if (!sourceUnitDefinition?.family || !targetUnitDefinition?.family) {
16
+ throw new Error(`Cannot convert between ${fromUnit} and ${toUnit}: missing family`);
44
17
  }
45
-
46
- return { value: currentValue, unit: currentUnit };
18
+
19
+ if (sourceUnitDefinition.family !== targetUnitDefinition.family) {
20
+ throw new Error(`Cannot convert between different families: ${sourceUnitDefinition.family} vs ${targetUnitDefinition.family}`);
21
+ }
22
+
23
+ // Conversion via the pivot: pivot_value = sourceUnitDefinition_value * sourceUnitDefinition_factor
24
+ // targetUnitDefinition_value = pivot_value / targetUnitDefinition_factor
25
+ return (value * (sourceUnitDefinition.factor ?? 1)) / (targetUnitDefinition.factor ?? 1);
47
26
  }
48
27
 
49
- function applySIScale(value: number, unit: string) {
50
- const absoluteValue = Math.abs(value);
28
+ /**
29
+ * Finds the best unit in a family to display a value
30
+ * (the one that gives a result between 1 and 999)
31
+ */
32
+ function findBestUnit(value: number, currentUnit: string, fixedUnit?: string): string {
33
+ const unitDef = unitRegistry[currentUnit];
34
+
35
+ if (!unitDef?.family) {
36
+ return currentUnit;
37
+ }
38
+
39
+ // Convert the value to the pivot (in absolute value)
40
+ const absoluteValueInPivot = Math.abs(value * (unitDef.factor ?? 1));
51
41
 
52
- let selectedPrefix = SI_PREFIXES[3];
42
+ // Find all units in the same family
43
+ const unitsInSameFamily = Object.entries(unitRegistry)
44
+ .filter(([, def]) => def.family === unitDef.family)
45
+ .map(([unit, def]) => ({
46
+ unit,
47
+ factor: def.factor ?? 1,
48
+ precision: def.precision,
49
+ }))
50
+ .sort((a, b) => a.factor - b.factor); // Sort by ascending factor
51
+
52
+ // Determine the maximum allowed factor
53
+ const maxFactor = fixedUnit && unitRegistry[fixedUnit]?.family === unitDef.family
54
+ ? unitRegistry[fixedUnit]?.factor ?? Infinity
55
+ : Infinity;
56
+
57
+ // Find the unit that gives a result >= 1 and < 1000
58
+ let bestUnit = unitsInSameFamily[0]?.unit ?? currentUnit; // Default: the smallest unit
53
59
 
54
- for (let i = SI_PREFIXES.length - 1; i >= 0; i--) {
55
- const prefix = SI_PREFIXES[i];
60
+ for (let i = unitsInSameFamily.length - 1; i >= 0; i--) {
61
+ const candidateUnit = unitsInSameFamily[i];
62
+
63
+ // Do not exceed fixedUnit
64
+ if (candidateUnit.factor > maxFactor) {
65
+ continue;
66
+ }
67
+
68
+ const valueInCandidateUnit = absoluteValueInPivot / candidateUnit.factor;
56
69
 
57
- if (absoluteValue >= prefix.factor) {
58
- selectedPrefix = prefix;
70
+ // Find the unit that gives a result >= 1
71
+ if (valueInCandidateUnit >= 1) {
72
+ bestUnit = candidateUnit.unit;
59
73
  break;
60
74
  }
61
75
  }
62
-
63
- return {
64
- value: value / selectedPrefix.factor,
65
- unit: `${selectedPrefix.prefix}${unit}`,
66
- };
76
+
77
+ return bestUnit;
67
78
  }
68
79
 
69
- function applyConversions(value: number, unit: string, unitDefinition: UnitDefinition) {
80
+ /**
81
+ * Applies alternative conversions (non-family)
82
+ * These conversions take priority over the family system
83
+ */
84
+ function applyAlternativeConversions(value: number, unit: string, unitDefinition: UnitDefinition) {
70
85
  if (!unitDefinition.conversions?.length) {
71
86
  return { value, unit };
72
87
  }
@@ -85,6 +100,29 @@ export function useUnitFormatter() {
85
100
  return { value, unit };
86
101
  }
87
102
 
103
+ /**
104
+ * Applies SI prefixes for unknown units
105
+ */
106
+ function applySIScale(value: number, unit: string) {
107
+ const absoluteValue = Math.abs(value);
108
+
109
+ let selectedPrefix = SI_PREFIXES[3]; // None
110
+
111
+ for (let i = SI_PREFIXES.length - 1; i >= 0; i--) {
112
+ const currentPrefix = SI_PREFIXES[i];
113
+
114
+ if (absoluteValue >= currentPrefix.factor) {
115
+ selectedPrefix = currentPrefix;
116
+ break;
117
+ }
118
+ }
119
+
120
+ return {
121
+ value: value / selectedPrefix.factor,
122
+ unit: `${selectedPrefix.prefix}${unit}`,
123
+ };
124
+ }
125
+
88
126
  function formatNumber(value: number, decimalPrecision: number, locale?: string) {
89
127
  return new Intl.NumberFormat(locale, {
90
128
  minimumFractionDigits: 0,
@@ -92,61 +130,72 @@ export function useUnitFormatter() {
92
130
  }).format(value);
93
131
  }
94
132
 
95
- const formatQuantity = (value: number, unit: string, options?: { decimalPrecision?: number; fixedUnit?: string;} ): string => {
133
+ const formatQuantity = (value: number, unit: string, options?: { decimalPrecision?: number; fixedUnit?: string; } ): string => {
96
134
  if (!isFinite(value)) {
97
135
  return "—";
98
136
  }
99
137
 
100
- const unitDefinition = unitRegistry[unit];
101
- let result: { value: number; unit: string };
138
+ const originalUnitDefinition = unitRegistry[unit];
139
+ let convertedResult: { value: number; unit: string };
102
140
  let decimalPrecision: number;
103
141
 
104
- if (unitDefinition) {
105
- result = applyConversions(value, unit, unitDefinition);
142
+ if (originalUnitDefinition) {
143
+ convertedResult = applyAlternativeConversions(value, unit, originalUnitDefinition);
106
144
 
107
- result = scaleUpByParent(result.value, result.unit, options?.fixedUnit);
145
+ const convertedUnitDefinition = unitRegistry[convertedResult.unit];
146
+ if (convertedUnitDefinition?.family) {
147
+ const bestUnit = findBestUnit(convertedResult.value, convertedResult.unit, options?.fixedUnit);
148
+
149
+ if (bestUnit !== convertedResult.unit) {
150
+ convertedResult.value = convert(convertedResult.value, convertedResult.unit, bestUnit);
151
+ convertedResult.unit = bestUnit;
152
+ }
153
+ }
108
154
 
109
- decimalPrecision = options?.decimalPrecision ?? (unitRegistry[result.unit]?.precision ?? 2);
155
+ decimalPrecision = options?.decimalPrecision ?? (unitRegistry[convertedResult.unit]?.precision ?? 2);
110
156
  } else {
111
- result = applySIScale(value, unit);
157
+ convertedResult = applySIScale(value, unit);
112
158
  decimalPrecision = options?.decimalPrecision ?? 2;
113
159
  }
114
160
 
115
- const unitSymbol = unitRegistry[result.unit]?.symbol ?? result.unit;
116
- return `${formatNumber(result.value, decimalPrecision, languageCode.value)} ${unitSymbol}`;
161
+ const finalUnitSymbol = unitRegistry[convertedResult.unit]?.symbol ?? convertedResult.unit;
162
+ const formattedValue = formatNumber(convertedResult.value, decimalPrecision, languageCode.value);
163
+
164
+ return `${formattedValue} ${finalUnitSymbol}`;
117
165
  };
118
166
 
119
- const formatQuantityParts = (value: number, unit: string, options?: { decimalPrecision?: number;fixedUnit?: string;} ): { value: string; unit: string } => {
167
+ const formatQuantityParts = (value: number, unit: string, options?: { decimalPrecision?: number; fixedUnit?: string; } ): { value: string; unit: string } => {
120
168
 
121
- const formattedQuantity = formatQuantity(value, unit, {
122
- decimalPrecision: options?.decimalPrecision,
123
- fixedUnit: options?.fixedUnit
124
- });
169
+ const fullFormattedQuantity = formatQuantity(value, unit, { decimalPrecision: options?.decimalPrecision,fixedUnit: options?.fixedUnit});
125
170
 
126
- if (formattedQuantity === "—") {
171
+ if (fullFormattedQuantity === "—") {
127
172
  return {
128
173
  value: "—",
129
174
  unit: ""
130
175
  };
131
176
  }
132
177
 
133
- const lastSpaceIndex = formattedQuantity.lastIndexOf(" ");
178
+ const indexOfLastSpace = fullFormattedQuantity.lastIndexOf(" ");
134
179
 
135
- if (lastSpaceIndex === -1) {
180
+ if (indexOfLastSpace === -1) {
136
181
  return {
137
- value: formattedQuantity,
182
+ value: fullFormattedQuantity,
138
183
  unit: ""
139
184
  };
140
185
  }
141
186
 
187
+ const valueWithoutUnit = fullFormattedQuantity.slice(0, indexOfLastSpace);
188
+ const unitOnly = fullFormattedQuantity.slice(indexOfLastSpace + 1);
189
+
142
190
  return {
143
- value: formattedQuantity.slice(0, lastSpaceIndex),
144
- unit: formattedQuantity.slice(lastSpaceIndex + 1)
191
+ value: valueWithoutUnit,
192
+ unit: unitOnly
145
193
  };
146
194
  };
147
195
 
148
196
  return {
149
197
  formatQuantity,
150
198
  formatQuantityParts,
199
+ convert
151
200
  };
152
201
  }
package/config/index.ts CHANGED
@@ -1,3 +1,4 @@
1
1
  export * from "./literals";
2
2
  export * from "./timeDuration";
3
+ export * from "./units";
3
4
  export * from "./urls";
@@ -0,0 +1 @@
1
+ export * from "./unitPrefixes";
@@ -0,0 +1,13 @@
1
+ import { UnitPrefix } from "@dative-gpi/foundation-shared-domain/enums/units";
2
+
3
+ export const SI_PREFIXES = [
4
+ { prefix: UnitPrefix.Nano, factor: 1e-9 },
5
+ { prefix: UnitPrefix.Micro, factor: 1e-6 },
6
+ { prefix: UnitPrefix.Milli, factor: 1e-3 },
7
+ { prefix: UnitPrefix.None, factor: 1 },
8
+ { prefix: UnitPrefix.Kilo, factor: 1e3 },
9
+ { prefix: UnitPrefix.Mega, factor: 1e6 },
10
+ { prefix: UnitPrefix.Giga, factor: 1e9 },
11
+ { prefix: UnitPrefix.Tera, factor: 1e12 },
12
+ { prefix: UnitPrefix.Peta, factor: 1e15 },
13
+ ];
package/package.json CHANGED
@@ -4,7 +4,7 @@
4
4
  "url": "https://github.com/Dative-GPI/foundation-shared-ui.git"
5
5
  },
6
6
  "sideEffects": false,
7
- "version": "1.0.191-add-unit-formatter",
7
+ "version": "1.0.191-add-unit-formatter-2",
8
8
  "description": "",
9
9
  "publishConfig": {
10
10
  "access": "public"
@@ -13,7 +13,7 @@
13
13
  "author": "",
14
14
  "license": "ISC",
15
15
  "dependencies": {
16
- "@dative-gpi/foundation-shared-domain": "1.0.191-add-unit-formatter",
16
+ "@dative-gpi/foundation-shared-domain": "1.0.191-add-unit-formatter-2",
17
17
  "@vueuse/core": "^14.0.0"
18
18
  },
19
19
  "peerDependencies": {
@@ -22,5 +22,5 @@
22
22
  "vue": "^3.4.38",
23
23
  "vue-router": "^4.3.0"
24
24
  },
25
- "gitHead": "0a19e29a6ff02531f7a54c712d7fcd27c328fc27"
25
+ "gitHead": "7c34bcea5b12a9461c14adbdb2227f6dda0d46aa"
26
26
  }