diff --git a/docs/getting-started/upgrading.md b/docs/getting-started/upgrading.md
index ed2b4e93..63979f23 100644
--- a/docs/getting-started/upgrading.md
+++ b/docs/getting-started/upgrading.md
@@ -138,7 +138,7 @@ layout, and new options.
| **Breaking:** the view schema refuses a blank label | you validate stored view files against `view-2.json` or `view-file-2.json`, and a value's `label` or a name in `fieldLabels` is blank | give it a character or remove it; `normalize()` dropped such a label already |
| **Breaking:** header values refuse the control characters U+0080 to U+009F | a header value in your configuration or secret holds one of them | remove the character. The start or the log names the header |
| **Breaking:** reports are written with mode 0600 | another user reads the output directory without `output.baseUrl`, such as a backup job | run that reader as the server's user, or set `output.baseUrl`; `chmod 600` older reports to match |
-| Numbers in loaded files read by their decimal mark | people load CSV or Excel files with text numbers such as `1,234` or `1.500` | check the column the note `DECIMAL_MARK` names. A comma-separated file reads `"1,234"` as 1234, where it read as 1.234; an Excel text cell `"1.500"` reads as 1500 in a German locale, where it read as 1.5 |
+| Numbers in loaded files read by their decimal mark | people load CSV or Excel files with text numbers such as `1,234` or `1.500` | check the column the note `DECIMAL_MARK` names; pick its mark in the preview, or with `retype`'s `decimal` ([Changing types and decimal marks](../reference/import.md#retype)). A comma-separated file reads `"1,234"` as 1234, where it read as 1.234; an Excel text cell `"1.500"` reads as 1500 in a German locale, where it read as 1.5 |
| pivotkit-server answers a little differently | a client keeps `list_sources` file names, relies on the order of `files.list`, or calls `/openapi.json` or the REST metadata with a method other than GET or HEAD | read file names of the second and later `files.allowDirs` without their path; sort `files.list` yourself if you need another order; use GET (other methods get 405 with `Allow: GET, HEAD`). The [pivotkit-server changelog](https://github.com/eizedev/pivotkit/blob/main/packages/pivotkit-server/CHANGELOG.md) has the details |
| [Versions move together](#update) | you list pivotkit-core, pivotkit-report or pivotkit-xlsx yourself | update them to the release of pivotkit-react 0.10: core 0.10.0, report 0.6.0, xlsx 0.7.0 |
diff --git a/docs/reference/import.md b/docs/reference/import.md
index 96768ab0..840da83e 100644
--- a/docs/reference/import.md
+++ b/docs/reference/import.md
@@ -34,6 +34,7 @@ const table = await readFile(file, { // a File from Returns `Promise` |
-| `retype(table, types)` | The table with other column types, from `table.raw`. Returns `ImportTable` |
+| `retype(table, types, options)` | The table with other column types, from `table.raw`. Options: `decimal` (the decimal mark of number columns, by name or position). Returns `ImportTable` |
| `readerFor(file, plugins)` | The plugin that accepts a `{ name, type }`, or `undefined`. |
| `loadReader(plugin)` | The plugin's reader module, loaded once and checked (`read`, optional `sheets`). |
| `validatePlugin(plugin)` | Checks a plugin against the [contract](write-a-plugin.md#the-contract); throws `INVALID_ARGUMENT` that says what is wrong. |
diff --git a/docs/reference/localisation.md b/docs/reference/localisation.md
index 66153aaf..52bc7971 100644
--- a/docs/reference/localisation.md
+++ b/docs/reference/localisation.md
@@ -102,6 +102,15 @@ The texts of [loading data](../use/load-data.md) are `labels.dataImport`. They c
- the readers' notes per note code, in `labels.dataImport.notes`
- a file over a limit, in `overLimit`, with the limit's words in `limitWhat`
- `workbookCells`, for when a workbook's texts and formats reach `importCells`
+- the decimal mark choice of a column whose numbers fit both marks, such as `1,234`:
+ - `markQuestion` is the question above the choice, with the note's value as written in `{example}`.
+ - `markOf` names the column, in `{column}`. A screen reader reads it right after the question.
+ - `markOption.thousands` and `markOption.decimal` are the two options: the separator read as a
+ thousands separator or as the decimal mark. Both get the characters of the value as written:
+ `{whole}` and `{fraction}` on each side of the separator, and `{value}`, both joined without it.
+ - The decimal text must not show the separator. "“1,234” means 1,234" answers nothing. Spell the
+ mark out instead, as in `"{whole} point {fraction}"`.
+ - Without one of these texts, the preview shows no choice.
They load with the import UI, English and German in one file. A host's own language takes English
there unless its `labels` give `dataImport`.
diff --git a/docs/use/load-data.md b/docs/use/load-data.md
index 0849390e..5bf73d38 100644
--- a/docs/use/load-data.md
+++ b/docs/use/load-data.md
@@ -47,15 +47,17 @@ The Data menu says which formats the report reads, for example
| Sheet | A workbook with more than one sheet: which one to read. A hidden sheet says "(hidden)". Another sheet reads the file again. |
| The first rows | Eight rows as they will be loaded, numbers in your language's notation. |
| Type | Under each column name: **Text**, **Number**, **Date** or **Yes/No**. The report picks one from the values. You can change it here. A value that does not fit the type you pick stays empty, and a note counts these values. |
+| Decimal mark | When a value such as `1,234` can be read two ways, its column asks what it means: 1234 (thousands) or 1 point 234. |
| Notes | How the report read the file and what it changed: the encoding, the separator, lines skipped above the column names, empty rows left out, columns renamed, values cut, and numbers that could read two ways or were too long or too large. |
While the report reads a large file, the preview shows the progress, with **Cancel**. The preview
-shows up to 60 columns. The others keep the type the report found.
+shows up to 60 columns. The others keep the type and decimal mark the report found.
??? info "How the types are found"
- A column of whole and decimal numbers is a **Number**, in German (`1.234,5`) or English
(`1,234.5`) notation. When some values read as different numbers in the two, such as
- `1,234`, a note names the decimal mark the report used. If it is wrong, change the file.
+ `1,234`, a note names the decimal mark the report used. To change it, pick what the value means
+ under the column name. A column after the first 60 keeps it; change the file for that one.
- Dates such as `10.11.2026`, `2026-11-10` or `11/10/2026` are a **Date**.
- `true` and `false`, and also `WAHR` and `FALSCH`, are **Yes/No**.
- A number stays **Text** when it has a leading zero, such as the postcode `01067`, or more than
@@ -144,7 +146,9 @@ next file.
- The preview is a dialog. The focus moves in, Tab stays inside, and Escape cancels. Afterwards the
focus goes back to where it was.
- When the first rows are there, the focus is on **Load data**, so Enter loads. Tab from there goes
- to the sheet and the types, each a list named like "Type of Hours". Shift+Tab goes to **Cancel**.
+ to the sheet and the types, each a list named like "Type of Hours", and to the decimal marks, each
+ named by its question and column, like "“1,234” means (decimal mark of Sales)". Shift+Tab goes to
+ **Cancel**.
- After you pick another sheet, the focus stays on the sheet list.
- The dialog's description is its line of rows and columns and its notes, so a screen reader reads
them out.
diff --git a/packages/pivotkit-core/CHANGELOG.md b/packages/pivotkit-core/CHANGELOG.md
index 35bc20be..727ae5a1 100644
--- a/packages/pivotkit-core/CHANGELOG.md
+++ b/packages/pivotkit-core/CHANGELOG.md
@@ -8,6 +8,11 @@ All notable changes to `pivotkit-core` are documented in this file. The format i
### Added
+- `retype(table, types, { decimal })` picks the decimal mark of number columns, `"."` or `","`, by
+ name or position. Their text reads in that mark alone; a value that does not fit it is blank, with
+ a note. The note `DECIMAL_MARK` stays with the mark picked, and its new params `point` and
+ `comma` give the example's number with each mark
+ ([#787](https://github.com/eizedev/pivotkit/issues/787)).
- `describeView(view, schema, { labels, locale })` writes its texts in German too: `DESCRIBE_LABELS.de`,
or `describeLabels(locale)` for a locale's language. German quotes text values („North“) and names
one whole unit of a relative range as the engine keeps it ("heute", "gestern", "im Vorjahr"; from
diff --git a/packages/pivotkit-core/src/import-table.js b/packages/pivotkit-core/src/import-table.js
index 1deb199f..8bc9af14 100644
--- a/packages/pivotkit-core/src/import-table.js
+++ b/packages/pivotkit-core/src/import-table.js
@@ -382,7 +382,8 @@ export function dateToIso(d) {
/**
* Converters per type: a cleaned value as read -> a value of the type, or undefined when it does not
- * convert (null stays null).
+ * convert (null stays null). Text a number reads in the hint's decimal mark first, then in the other
+ * one; with `onlyDecimal` (a mark the caller picked for the column) in the hint's mark alone.
*/
const TO = {
string(v) {
@@ -390,12 +391,12 @@ const TO = {
if (v instanceof Date) return dateToIso(v) ?? undefined;
return String(v);
},
- number(v, hints) {
+ number(v, hints, onlyDecimal) {
if (typeof v === "number") return v;
if (typeof v === "boolean") return v ? 1 : 0;
if (typeof v === "string") {
const first = textToNumber(v, hints.decimal);
- return first ?? textToNumber(v, hints.decimal === "," ? "." : ",") ?? undefined;
+ return first ?? (onlyDecimal ? undefined : textToNumber(v, hints.decimal === "," ? "." : ",")) ?? undefined;
}
return undefined;
},
@@ -426,9 +427,10 @@ const TO = {
* @param {unknown[]} raw
* @param {ImportType} type
* @param {ImportHints} hints
+ * @param {boolean} [onlyDecimal] numbers in text read in `hints.decimal` alone
* @returns {{ values: unknown[], failed: number }}
*/
-export function convertColumn(raw, type, hints) {
+export function convertColumn(raw, type, hints, onlyDecimal = false) {
if (type === "string" && raw.every((v) => v === null || typeof v === "string")) {
return { values: raw, failed: 0 };
}
@@ -441,7 +443,7 @@ export function convertColumn(raw, type, hints) {
values[i] = null;
continue;
}
- const out = to(v, hints);
+ const out = to(v, hints, onlyDecimal);
if (out === undefined) {
values[i] = null;
failed++;
@@ -458,7 +460,7 @@ export function convertColumn(raw, type, hints) {
* notation the column's text fits (the hint's decimal mark first when it fits both).
* @param {unknown[]} raw
* @param {ImportHints} hints
- * @returns {{ type: ImportType, dateOrder?: "dmy" | "mdy", ambiguousOrder?: boolean, decimal?: "." | ",", ambiguousDecimal?: boolean, example?: string }}
+ * @returns {{ type: ImportType, dateOrder?: "dmy" | "mdy", ambiguousOrder?: boolean, decimal?: "." | ",", ambiguousDecimal?: boolean, example?: string, point?: number, comma?: number }}
*/
export function inferColumn(raw, hints) {
let numbers = 0;
@@ -502,8 +504,8 @@ export function inferColumn(raw, hints) {
* a person makes a text column a number (applyTypes).
*/
function numberNotations() {
- /** @type {{ en: boolean, de: boolean, example: string | null }} example: the first value both notations read, as different numbers */
- const fits = { en: true, de: true, example: null };
+ /** @type {{ en: boolean, de: boolean, example: string | null, point: number, comma: number }} example: the first value both notations read, as different numbers; point, comma: its number in each */
+ const fits = { en: true, de: true, example: null, point: 0, comma: 0 };
return {
fits,
/** @param {string} t */
@@ -517,7 +519,11 @@ function numberNotations() {
const de = textToNumber(t, ",");
if (en === null) fits.en = false;
if (de === null) fits.de = false;
- if (fits.example === null && en !== null && de !== null && en !== de) fits.example = t;
+ if (fits.example === null && en !== null && de !== null && en !== de) {
+ fits.example = t;
+ fits.point = en;
+ fits.comma = de;
+ }
},
/** @param {ImportHints} hints */
result(hints) {
@@ -527,7 +533,7 @@ function numberNotations() {
// the column fits both and a value reads as different numbers in them: the choice needs a note.
// A value only one notation fits ("5,5") decides the column: "1,234" next to it is 1.234, no note.
const ambiguous = fits.en && fits.de && fits.example !== null;
- return { type: /** @type {const} */ ("number"), decimal, ...(ambiguous ? { ambiguousDecimal: true, example: fits.example } : {}) };
+ return { type: /** @type {const} */ ("number"), decimal, ...(ambiguous ? { ambiguousDecimal: true, example: fits.example, point: fits.point, comma: fits.comma } : {}) };
}
};
}
@@ -536,7 +542,7 @@ function numberNotations() {
* The type of a column of text.
* @param {Array} raw
* @param {ImportHints} hints
- * @returns {{ type: ImportType, dateOrder?: "dmy" | "mdy", ambiguousOrder?: boolean, decimal?: "." | ",", ambiguousDecimal?: boolean, example?: string }}
+ * @returns {{ type: ImportType, dateOrder?: "dmy" | "mdy", ambiguousOrder?: boolean, decimal?: "." | ",", ambiguousDecimal?: boolean, example?: string, point?: number, comma?: number }}
*/
function inferText(raw, hints) {
let bool = true;
@@ -883,39 +889,59 @@ function finishTable({ header, columns, rowCount, notes, counts, hints, limits,
/**
* The table with its columns typed: `types` (by position, or by name case-insensitively) where given,
- * else the inferred type.
+ * else the inferred type; a number column with a mark in `marks` reads its text in that mark alone.
* @param {ImportTable} table
* @param {ReadOptions["types"]} types
* @param {Array>} [inferred]
+ * @param {Array<"." | "," | undefined>} [marks] the decimal mark picked per column, by position
* @returns {ImportTable}
*/
-function applyTypes(table, types, inferred) {
- const wanted = typesByPosition(table.columns, types);
+function applyTypes(table, types, inferred, marks = []) {
+ const wanted = /** @type {Array} */ (byPosition(table.columns, types, IMPORT_TYPES));
const notes = table.notes.filter((x) => !COLUMN_NOTES.has(x.code));
const outTypes = [];
const data = [];
for (let c = 0; c < table.columns.length; c++) {
const type = wanted[c] ?? table.detected[c];
- if (table.types[c] === type && table.data[c] !== undefined) {
+ const mark = type === "number" ? marks[c] : undefined;
+ if (table.types[c] === type && table.data[c] !== undefined && !mark) {
// the column keeps its type: its values and its notes stay as they are
outTypes.push(type);
data.push(table.data[c]);
notes.push(...table.notes.filter((x) => COLUMN_NOTES.has(x.code) && x.params.column === table.columns[c]));
continue;
}
- const read = readingOf(table.raw[c], type, inferred?.[c], table.hints);
- // a column read in another notation than the table's hint converts in that notation first
- const hints = { ...table.hints, ...(read?.decimal ? { decimal: read.decimal } : {}), ...(read?.dateOrder ? { dateOrder: read.dateOrder } : {}) };
- if (read?.ambiguousOrder) notes.push(note("DATE_ORDER", { column: table.columns[c], order: read.dateOrder }));
- if (read?.ambiguousDecimal) notes.push(note("DECIMAL_MARK", { column: table.columns[c], decimal: read.decimal, example: read.example }));
- const { values, failed } = convertColumn(table.raw[c], type, hints);
- if (failed > 0) notes.push(note("VALUES_NOT_CONVERTED", { column: table.columns[c], type, count: failed }));
+ const typed = typeColumn(table, c, type, inferred?.[c], mark);
+ notes.push(...typed.notes);
outTypes.push(type);
- data.push(values);
+ data.push(typed.values);
}
return { ...table, types: outTypes, data, notes };
}
+/**
+ * One column's values as `type`, with the notes about how they were read.
+ * @param {ImportTable} table
+ * @param {number} c
+ * @param {ImportType} type
+ * @param {ReturnType | undefined} own the column's inferred reading, when its type is the detected one
+ * @param {"." | "," | undefined} mark the decimal mark picked for the column
+ */
+function typeColumn(table, c, type, own, mark) {
+ const column = table.columns[c];
+ const found = readingOf(table.raw[c], type, own, table.hints);
+ // a picked mark replaces the one found; the note stays while the values fit both, so the choice can go back
+ const read = mark ? { ...(found ?? { type }), decimal: mark } : found;
+ // a column read in another notation than the table's hint converts in that notation first
+ const hints = { ...table.hints, ...(read?.decimal ? { decimal: read.decimal } : {}), ...(read?.dateOrder ? { dateOrder: read.dateOrder } : {}) };
+ const notes = [];
+ if (read?.ambiguousOrder) notes.push(note("DATE_ORDER", { column, order: read.dateOrder }));
+ if (read?.ambiguousDecimal) notes.push(note("DECIMAL_MARK", { column, decimal: read.decimal, example: read.example, point: read.point, comma: read.comma }));
+ const { values, failed } = convertColumn(table.raw[c], type, hints, Boolean(mark));
+ if (failed > 0) notes.push(note("VALUES_NOT_CONVERTED", { column, type, count: failed }));
+ return { values, notes };
+}
+
/** The notes about one column's reading; applyTypes makes them again when the column's type changes. */
const COLUMN_NOTES = new Set(["VALUES_NOT_CONVERTED", "DATE_ORDER", "DECIMAL_MARK"]);
@@ -940,17 +966,26 @@ function readingOf(raw, type, own, hints) {
return read.type === "number" ? read : undefined;
}
-/** `types` (an array by position or an object by name) as one entry per column; invalid entries are ignored. */
-function typesByPosition(columns, types) {
+/**
+ * A setting per column (`types`, `decimal`) as one entry per column: an array by position or an
+ * object by column name (case-insensitively); entries not in `allowed` are ignored.
+ * @template T
+ * @param {string[]} columns
+ * @param {unknown} given
+ * @param {readonly T[]} allowed
+ * @returns {Array}
+ */
+function byPosition(columns, given, allowed) {
+ const ok = (v) => allowed.includes(/** @type {T} */ (v));
const out = new Array(columns.length).fill(undefined);
- if (Array.isArray(types)) {
+ if (Array.isArray(given)) {
for (let c = 0; c < columns.length; c++) {
- if (IMPORT_TYPES.includes(types[c])) out[c] = types[c];
+ if (ok(given[c])) out[c] = given[c];
}
- } else if (types && typeof types === "object") {
+ } else if (given && typeof given === "object") {
const byName = new Map();
- for (const k of Object.keys(types)) {
- if (IMPORT_TYPES.includes(types[k])) byName.set(k.toLowerCase(), types[k]);
+ for (const k of Object.keys(given)) {
+ if (ok(given[k])) byName.set(k.toLowerCase(), given[k]);
}
columns.forEach((name, c) => {
out[c] = byName.get(name.toLowerCase());
@@ -959,19 +994,27 @@ function typesByPosition(columns, types) {
return out;
}
+/** @type {ReadonlyArray<"." | ",">} the decimal marks a caller can pick for a column */
+const MARKS = Object.freeze([".", ","]);
+
/**
* The table with other column types, from the values as read (`raw`): what the user picks in a
* preview, without reading the file again. Values that do not convert are blank, with a note.
+ * `options.decimal` picks the decimal mark of number columns ("." or ","), by position or by column
+ * name: their text reads in that mark alone, a value that does not fit it is blank, with a note. A
+ * column without one keeps its mark while its type stays, and reads in its values' notation again
+ * when its type changes.
* @param {ImportTable} table
* @param {ReadOptions["types"]} types by position or by column name; a missing entry keeps the column's current type
+ * @param {{ decimal?: Array<"." | "," | null | undefined> | Record }} [options]
* @returns {ImportTable}
*/
-export function retype(table, types) {
+export function retype(table, types, options = {}) {
if (!table || !Array.isArray(table.columns) || !Array.isArray(table.raw) || table.raw.length !== table.columns.length) {
throw new PivotkitError("INVALID_ARGUMENT", "retype(table, types): table must be a table read by a reader, with its raw values");
}
- const wanted = typesByPosition(table.columns, types);
+ const wanted = /** @type {Array} */ (byPosition(table.columns, types, IMPORT_TYPES));
const merged = table.columns.map((_, c) => wanted[c] ?? table.types[c] ?? table.detected[c]);
const inferred = table.raw.map((values, c) => (merged[c] === table.detected[c] ? inferColumn(values, table.hints) : undefined));
- return applyTypes(table, merged, inferred);
+ return applyTypes(table, merged, inferred, byPosition(table.columns, options?.decimal, MARKS));
}
diff --git a/packages/pivotkit-core/test/import.test.js b/packages/pivotkit-core/test/import.test.js
index 86209081..9c1cd116 100644
--- a/packages/pivotkit-core/test/import.test.js
+++ b/packages/pivotkit-core/test/import.test.js
@@ -271,6 +271,51 @@ test("retype: a column made a number reads in its values' notation, and notes of
assert.deepEqual(codes(both).filter((c) => c === "DECIMAL_MARK" || c === "VALUES_NOT_CONVERTED"), ["DECIMAL_MARK", "VALUES_NOT_CONVERTED"]);
});
+test("retype with decimal: a caller picks a number column's mark; the note stays, with the mark picked and the example's two numbers", async () => {
+ const t = await readFile(text("a.csv", 'Sales,Kg\n"1,234","1,5"\n"-5,678",\n'));
+ assert.deepEqual(col(t, "Sales"), [1234, -5678]);
+ assert.deepEqual(t.notes.find((n) => n.code === "DECIMAL_MARK").params, { column: "Sales", decimal: ".", example: "1,234", point: 1234, comma: 1.234 });
+ // by name, case-insensitively: the comma is the decimal mark, the sign stays, the other column keeps its values
+ const de = retype(t, {}, { decimal: { sales: "," } });
+ assert.deepEqual(col(de, "Sales"), [1.234, -5.678]);
+ assert.equal(col(de, "Kg"), col(t, "Kg"));
+ const mark = de.notes.filter((n) => n.code === "DECIMAL_MARK");
+ assert.deepEqual(mark.map((n) => n.params), [{ column: "Sales", decimal: ",", example: "1,234", point: 1234, comma: 1.234 }]);
+ assert.equal(mark[0].message, 'Numbers in "Sales" were read with "," as the decimal mark; some, such as "1,234", also fit the other mark.');
+ // and back, by position; the mark stays while the column keeps its type, a type change reads the values again
+ assert.deepEqual(col(retype(de, {}, { decimal: ["."] }), "Sales"), [1234, -5678]);
+ assert.deepEqual(col(retype(de, { Kg: "string" }), "Sales"), [1.234, -5.678]);
+ assert.deepEqual(col(retype(retype(de, { Sales: "string" }), { Sales: "number" }), "Sales"), [1234, -5678]);
+ // a column made a number and its mark in one call; a mark for a column that is no number is ignored
+ const asText = retype(t, { Sales: "string" });
+ assert.deepEqual(col(retype(asText, { Sales: "number" }, { decimal: { Sales: "," } }), "Sales"), [1.234, -5.678]);
+ assert.deepEqual(col(retype(asText, {}, { decimal: { Sales: "," } }), "Sales"), ["1,234", "-5,678"]);
+ // invalid marks are ignored, as invalid types are
+ assert.deepEqual(col(retype(t, {}, { decimal: { Sales: ";" } }), "Sales"), [1234, -5678]);
+ assert.deepEqual(col(retype(t, {}, { decimal: "," }), "Sales"), [1234, -5678]);
+});
+
+test("retype with decimal: the picked mark reads text in that mark alone; what does not fit it is empty, with a note", async () => {
+ // both notations, a sign, a leading zero, a column that mixes them, an empty value
+ const t = await readFile(text("a.csv", 'Kg,N\n"1,234",1\n"-2.500",2\n"0,125",3\n"5,5",4\n,5\n"1.234,5",6\n'), { types: { Kg: "string" } });
+ const cases = [
+ // "." alone: "1,234" groups thousands; "0,125", "5,5" and "1.234,5" are no number with a decimal point
+ [".", [1234, -2.5, null, null, null, null], 3],
+ // "," alone: "-2.500" groups thousands; "0,125" is a decimal, a first group never starts with 0
+ [",", [1.234, -2500, 0.125, 5.5, null, 1234.5], 0]
+ ];
+ for (const [mark, values, failed] of cases) {
+ const n = retype(t, { Kg: "number" }, { decimal: [mark] });
+ assert.deepEqual(col(n, "Kg"), values, mark);
+ // the empty value stays empty and is not counted
+ assert.equal(n.notes.find((x) => x.code === "VALUES_NOT_CONVERTED")?.params.count ?? 0, failed, mark);
+ // "5,5" fits only the comma: the column does not fit both, so no note about the mark
+ assert.ok(!codes(n).includes("DECIMAL_MARK"), mark);
+ }
+ // without a mark, the same column reads each value as it fits ("5,5" decides German)
+ assert.deepEqual(col(retype(t, { Kg: "number" }), "Kg"), [1.234, -2500, 0.125, 5.5, null, 1234.5]);
+});
+
test("JSON numbers a double cannot hold are noted: too large ones are empty, long whole numbers may have lost digits", async () => {
const big = await readFile(text("a.json", '[{"a":1e999,"b":1},{"a":5,"b":2}]'));
assert.deepEqual(col(big, "a"), [null, 5]);
diff --git a/packages/pivotkit-core/test/types/consumer.ts b/packages/pivotkit-core/test/types/consumer.ts
index 4cf15021..dd149df3 100644
--- a/packages/pivotkit-core/test/types/consumer.ts
+++ b/packages/pivotkit-core/test/types/consumer.ts
@@ -65,6 +65,16 @@ const plugin: ReaderPlugin = validatePlugin({ apiVersion: 1, kind: "reader", nam
export async function load(file: File): Promise {
const table: ImportTable = await readFile(file, { plugins: [plugin, ...BUILT_IN_READERS], limits: { fileBytes: 1_000_000 }, signal: new AbortController().signal, onProgress: (p) => void p.phase, types: { Zip: "string" } });
const again: ImportTable = retype(table, ["string", "number"]);
+ // the decimal mark of number columns, by name or by position
+ const comma: ImportTable = retype(table, {}, { decimal: { Sales: "," } });
+ const byPosition: ImportTable = retype(table, ["number"], { decimal: [","] });
+ void comma;
+ void byPosition;
+ // a decimal mark is "." or ",", by name in an object or by position in an array
+ // @ts-expect-error ";" is no decimal mark
+ retype(table, {}, { decimal: { Sales: ";" } });
+ // @ts-expect-error one mark is not a list or a record of marks
+ retype(table, {}, { decimal: "," });
const columnar: ColumnarData = { columns: again.columns, types: again.types, data: again.data };
return encode(columnar).length + encode(table).length + table.notes.filter((n) => n.code === "TEXT_CUT").length;
}
diff --git a/packages/pivotkit-element/CHANGELOG.md b/packages/pivotkit-element/CHANGELOG.md
index b23bf3af..3fda0719 100644
--- a/packages/pivotkit-element/CHANGELOG.md
+++ b/packages/pivotkit-element/CHANGELOG.md
@@ -6,6 +6,12 @@ All notable changes to `pivotkit-element` are documented in this file. The forma
## [Unreleased]
+### Added
+
+- The import preview lets a person pick a column's decimal mark. See pivotkit-react's changelog.
+ The import group grows to 23.7 KiB gzip on an official Node 24 build, its budget to 23.9 KiB
+ ([#787](https://github.com/eizedev/pivotkit/issues/787)).
+
### Changed
- The first load is 3.3 KiB smaller: 179.0 KiB gzip on an official Node 24 build, in 13 files as
diff --git a/packages/pivotkit-element/build.js b/packages/pivotkit-element/build.js
index 5e881bff..70452403 100644
--- a/packages/pivotkit-element/build.js
+++ b/packages/pivotkit-element/build.js
@@ -208,7 +208,7 @@ async function licenses(metafile) {
* can make the first load larger.
* `--size` fails above it.
*/
-export const SIZE_BUDGET_KIB = { initial: 182.5, chart: 262.0, export: 13.7, link: 7.5, menus: 59.6, texts: 8.5, unused: 6.5, import: 23.2, report: 29.7, template: 3, lang: 6.2, tips: 1.8 };
+export const SIZE_BUDGET_KIB = { initial: 182.5, chart: 262.0, export: 13.7, link: 7.5, menus: 59.6, texts: 8.5, unused: 6.5, import: 23.9, report: 29.7, template: 3, lang: 6.2, tips: 1.8 };
/**
* The load group of each chunk a page loads on demand, by its file name (esbuild's `[name]-[hash]`),
diff --git a/packages/pivotkit-react/CHANGELOG.md b/packages/pivotkit-react/CHANGELOG.md
index 191dba7f..83d58817 100644
--- a/packages/pivotkit-react/CHANGELOG.md
+++ b/packages/pivotkit-react/CHANGELOG.md
@@ -15,6 +15,12 @@ All notable changes to `pivotkit-react` are documented in this file. The format
- The package exports `TIP_IDS` and `NOTICE_IDS`, the ids of the tips and of the notices. A host
that checks a `tips` list no longer reads them from an internal chunk
([#720](https://github.com/eizedev/pivotkit/issues/720)).
+- The import preview lets a person pick a column's decimal mark. Under a number column with the
+ note `DECIMAL_MARK`, a label asks what the note's example means, such as "“1,234” means". It
+ names the choice, which offers "1234 (thousands)" and "1 point 234" ("1 Komma 234" in German).
+ The note points there first. New texts `markOf`, `markQuestion` and `markOption` in
+ `labels.dataImport`
+ ([#787](https://github.com/eizedev/pivotkit/issues/787)).
### Changed
diff --git a/packages/pivotkit-react/src/import-labels.js b/packages/pivotkit-react/src/import-labels.js
index a6c32618..36e0317f 100644
--- a/packages/pivotkit-react/src/import-labels.js
+++ b/packages/pivotkit-react/src/import-labels.js
@@ -30,9 +30,15 @@ export const en = {
sheet: "Sheet",
hiddenSheet: "{name} (hidden)",
firstRows: "The first rows",
- someColumns: "The first {shown} of {count} columns are shown; the others keep the type found.",
+ someColumns: "The first {shown} of {count} columns are shown; the others keep the type and decimal mark found.",
typeOf: "Type of {column}",
types: { string: "Text", number: "Number", date: "Date", boolean: "Yes/No" },
+ // a number column whose values fit both decimal marks: the question above its choice and the
+ // choice's two options; docs/reference/localisation.md has their placeholders. The decimal reading
+ // is spelt out: "1,234" next to “1,234” means would read as "1,234 means 1,234"
+ markOf: "(decimal mark of {column})",
+ markQuestion: "“{example}” means",
+ markOption: { decimal: "{whole} point {fraction}", thousands: "{value} (thousands)" },
yes: "Yes",
no: "No",
noRows: "The file holds no rows.",
@@ -72,7 +78,7 @@ export const en = {
TEXT_CUT: { one: "{count} value longer than {max} characters was cut.", other: "{count} values longer than {max} characters were cut." },
CHARACTERS_REMOVED: { one: "Control or text direction characters were removed from {count} value.", other: "Control or text direction characters were removed from {count} values." },
DATE_ORDER: "Dates in “{column}” were read as {order}; the values fit both.",
- DECIMAL_MARK: "Numbers in “{column}” were read with “{decimal}” as the decimal mark; some, such as “{example}”, also fit the other mark. If that is wrong, write them with the other mark in the file.",
+ DECIMAL_MARK: "Numbers in “{column}” were read with “{decimal}” as the decimal mark; some, such as “{example}”, also fit the other mark. To change it, pick what “{example}” means under the column's name, or write the numbers with the other mark in the file.",
VALUES_NOT_CONVERTED: { one: "{count} value in “{column}” cannot be read as {type} and is empty.", other: "{count} values in “{column}” cannot be read as {type} and are empty." },
NUMBERS_TOO_LARGE: "Numbers in “{column}” too large to hold are empty: {count}.",
NUMBERS_ROUNDED: "Long whole numbers in “{column}” may have lost digits: {count}. Write IDs as text in the file.",
@@ -111,9 +117,12 @@ export const de = {
sheet: "Blatt",
hiddenSheet: "{name} (ausgeblendet)",
firstRows: "Die ersten Zeilen",
- someColumns: "Die ersten {shown} von {count} Spalten werden gezeigt; die anderen behalten den erkannten Typ.",
+ someColumns: "Die ersten {shown} von {count} Spalten werden gezeigt; die anderen behalten den erkannten Typ und das erkannte Dezimalzeichen.",
typeOf: "Typ von {column}",
types: { string: "Text", number: "Zahl", date: "Datum", boolean: "Ja/Nein" },
+ markOf: "(Dezimalzeichen von {column})",
+ markQuestion: "„{example}“ bedeutet",
+ markOption: { decimal: "{whole} Komma {fraction}", thousands: "{value} (Tausender)" },
yes: "Ja",
no: "Nein",
noRows: "Die Datei enthält keine Zeilen.",
@@ -146,7 +155,7 @@ export const de = {
TEXT_CUT: { one: "{count} Wert mit mehr als {max} Zeichen wurde gekürzt.", other: "{count} Werte mit mehr als {max} Zeichen wurden gekürzt." },
CHARACTERS_REMOVED: { one: "Aus {count} Wert wurden Steuer- oder Richtungszeichen entfernt.", other: "Aus {count} Werten wurden Steuer- oder Richtungszeichen entfernt." },
DATE_ORDER: "Datumswerte in „{column}“ wurden als {order} gelesen; die Werte passen zu beidem.",
- DECIMAL_MARK: "Zahlen in „{column}“ wurden mit „{decimal}“ als Dezimalzeichen gelesen; einige, etwa „{example}“, passen auch zum anderen Zeichen. Stimmt das nicht, schreib sie in der Datei mit dem anderen Zeichen.",
+ DECIMAL_MARK: "Zahlen in „{column}“ wurden mit „{decimal}“ als Dezimalzeichen gelesen; einige, etwa „{example}“, passen auch zum anderen Zeichen. Zum Ändern wähl unter dem Namen der Spalte, was „{example}“ bedeutet, oder schreib die Zahlen in der Datei mit dem anderen Zeichen.",
VALUES_NOT_CONVERTED: { one: "{count} Wert in „{column}“ lässt sich nicht als {type} lesen und bleibt leer.", other: "{count} Werte in „{column}“ lassen sich nicht als {type} lesen und bleiben leer." },
NUMBERS_TOO_LARGE: "Zu große Zahlen in „{column}“ bleiben leer: {count}.",
NUMBERS_ROUNDED: "Lange ganze Zahlen in „{column}“ haben vielleicht Stellen verloren: {count}. Schreib Kennungen in der Datei als Text.",
@@ -184,6 +193,43 @@ export function importLabels(labels) {
return out;
}
+/**
+ * The texts of a column's decimal mark choice from its note DECIMAL_MARK: the mark read, the question with the note's
+ * example, the full text for a tooltip and the two options, what the example reads as with each mark.
+ * Null when the params lack a finite number for either mark or a mark of "." or "," (a plugin's own
+ * note), or the texts lack `markQuestion`, `markOption` or `markOf`: such a note offers no choice.
+ * @param {Record} params the note's params: decimal, example, point, comma
+ * @param {ImportTexts} texts
+ * @returns {{ decimal: "." | ",", question: string, title: string, options: Array<{ value: "." | ",", text: string }> } | null}
+ */
+export function markTexts(params, texts) {
+ const { decimal, example, point, comma } = params;
+ if (typeof point !== "number" || typeof comma !== "number" || !Number.isFinite(point) || !Number.isFinite(comma)) {
+ return null;
+ }
+ if (decimal !== "." && decimal !== ",") {
+ return null;
+ }
+ const forms = /** @type {Record} */ (texts.markOption ?? {});
+ if (typeof texts.markQuestion !== "string" || typeof texts.markOf !== "string" || typeof forms.decimal !== "string" || typeof forms.thousands !== "string") {
+ return null;
+ }
+ // the separator in the example (it has one: only "1,234" or "1.234" with a sign read as different
+ // numbers): the decimal mark when the option's mark is that character. Both readings are built from
+ // the example as written, sign and trailing zeros kept: "-2.500" is "-2 point 500" or "-2500", not
+ // the -2.5 of `point` in the locale's notation. The question and both options then show the same
+ // digits and signs, and no locale puts its mark back in
+ const text = String(example);
+ const separator = text.includes(",") ? "," : ".";
+ const at = text.lastIndexOf(separator);
+ const sides = { whole: text.slice(0, at) || "0", fraction: text.slice(at + 1), value: text.slice(0, at) + text.slice(at + 1) };
+ const option = (/** @type {"." | ","} */ mark) => ({ value: mark, text: fill(texts.markOption[separator === mark ? "decimal" : "thousands"], sides) });
+ const options = [option("."), option(",")];
+ const question = fill(texts.markQuestion, { example: text });
+ const chosen = options.find((o) => o.value === decimal);
+ return { decimal, question, title: `${question} ${chosen?.text}`, options };
+}
+
/**
* A reader's note in the report's language: the text of its code with its params (numbers in the
* locale's digits, a count in its plural form), else the reader's own English message (a plugin's
diff --git a/packages/pivotkit-react/src/import-ui.jsx b/packages/pivotkit-react/src/import-ui.jsx
index 2317c444..efa91c18 100644
--- a/packages/pivotkit-react/src/import-ui.jsx
+++ b/packages/pivotkit-react/src/import-ui.jsx
@@ -6,9 +6,9 @@
* result. Loaded on first use (lazy-import.js), with its texts (import-labels.js); the report itself
* keeps only the button, the drop handlers and the file input.
*
- * The preview reads the file once; another type for a column is pivotkit-core's retype() of the
- * values as read, another sheet reads the file again. "Load data" encodes the table (the columns as
- * the preview shows them) and hands it to the report, which records the step for Undo.
+ * The preview reads the file once; another type or decimal mark for a column is pivotkit-core's
+ * retype() of the values as read, another sheet reads the file again. "Load data" encodes the table
+ * (the columns as the preview shows them) and hands it to the report, which records the step for Undo.
*/
import React, { useContext, useEffect, useId, useMemo, useRef, useState } from "react";
@@ -17,7 +17,7 @@ import { encode } from "pivotkit-core";
import { IMPORT_TYPES, fileName, retype, shownName, sourceIdOf } from "pivotkit-core/import";
import { useFormName, useModal } from "./dom.js";
import { Icon } from "./icons.jsx";
-import { errorText, importLabels, noteText } from "./import-labels.js";
+import { errorText, importLabels, markTexts, noteText } from "./import-labels.js";
import { formatsOf, readImport, sheetsOf } from "./import-run.js";
import { fill, messageOf, plural } from "./labels.js";
import { Group, LayerContext, Option, hasTopLayer, useTopLayer } from "./popover.jsx";
@@ -145,6 +145,78 @@ function cellText(value, type, t, locale) {
return text.length > 80 ? `${text.slice(0, 79)}…` : text;
}
+/**
+ * The table as the preview shows it: the types and decimal marks the person picked, from the values
+ * as read (a pick that cannot be read that way keeps the table as it was and says why).
+ * @param {import("pivotkit-core/import").ImportTable | null} base
+ * @param {import("pivotkit-core/import").ImportType[] | null} types
+ * @param {Array<"." | "," | undefined> | null} marks
+ */
+function pickedTable(base, types, marks) {
+ if (!base || ((!types || types.every((ty, i) => ty === base.types[i])) && !marks)) {
+ return { table: base, error: null };
+ }
+ try {
+ return { table: retype(base, types ?? base.types, { decimal: marks ?? [] }), error: null };
+ } catch (e) {
+ return { table: base, error: messageOf(e) };
+ }
+}
+
+/**
+ * Which decimal mark a column's numbers are written in, while they fit both (the reader's note
+ * DECIMAL_MARK): a question with the note's example above a choice of what it reads as with each
+ * mark (markTexts), such as "1234 (thousands)" and "1 point 234". The question is the select's
+ * label, so clicking it focuses the select. A note without the example's two numbers offers no choice.
+ * @param {{ name: string, index: number, mark: Record, t: import("./import-labels.js").ImportTexts,
+ * formName: string, onMark: (mark: string) => void }} props `mark`: the note's params
+ */
+function MarkChoice({ name, index, mark, t, formName, onMark }) {
+ const id = useId();
+ const texts = markTexts(mark, t);
+ if (!texts) {
+ return null;
+ }
+ // the visible question names the select, the column follows for a screen reader (Label in Name)
+ return (
+ <>
+
+
+ >
+ );
+}
+
+/**
+ * A column's head in the preview: its name, its type, and the decimal mark of its numbers while
+ * they fit both (MarkChoice).
+ * @param {{ name: string, index: number, type: string, mark: Record | null, t: import("./import-labels.js").ImportTexts,
+ * formName: string, onType: (type: string) => void, onMark: (mark: string) => void }} props `mark`: the note's params
+ */
+function ColumnHead({ name, index, type, mark, t, formName, onType, onMark }) {
+ return (
+
+ {name}
+
+ {mark ? : null}
+
+ );
+}
+
/**
* @typedef {object} LoadedData what "Load data" hands the report
* @property {import("pivotkit-core").Encoded} encoded
@@ -182,6 +254,8 @@ export function ImportDialog({ job, labels, locale, plugins, worker, limits, tim
const [sheets, setSheets] = useState(/** @type {import("pivotkit-core/import").SheetInfo[]} */ ([]));
const [read, setRead] = useState(/** @type {{ table: import("pivotkit-core/import").ImportTable, sheet: number | string | undefined } | null} */ (null));
const [types, setTypes] = useState(/** @type {import("pivotkit-core/import").ImportType[] | null} */ (null));
+ // the decimal marks the person picked, by column; the others as the reader found them
+ const [marks, setMarks] = useState(/** @type {Array<"." | "," | undefined> | null} */ (null));
const [progress, setProgress] = useState(/** @type {import("pivotkit-core/import").ImportProgress | null} */ (null));
const [error, setError] = useState(/** @type {string | null} */ (null));
const [busy, setBusy] = useState(false);
@@ -221,6 +295,7 @@ export function ImportDialog({ job, labels, locale, plugins, worker, limits, tim
if (!controller.signal.aborted) {
setRead({ table, sheet });
setTypes(null);
+ setMarks(null);
}
},
(e) => {
@@ -251,18 +326,7 @@ export function ImportDialog({ job, labels, locale, plugins, worker, limits, tim
}, [file]);
const base = current?.table ?? null;
- // the table as the preview shows it: the types the person picked, from the values as read (a type
- // that cannot be read that way keeps the types as they were and says why)
- const typed = useMemo(() => {
- if (!base || !types || types.every((ty, i) => ty === base.types[i])) {
- return { table: base, error: null };
- }
- try {
- return { table: retype(base, types), error: null };
- } catch (e) {
- return { table: base, error: messageOf(e) };
- }
- }, [base, types]);
+ const typed = useMemo(() => pickedTable(base, types, marks), [base, types, marks]);
const shown = typed.table;
const box = useRef(/** @type {HTMLDivElement | null} */ (null));
@@ -374,6 +438,7 @@ export function ImportDialog({ job, labels, locale, plugins, worker, limits, tim
setError(null);
setFailed(null);
setTypes(null);
+ setMarks(null);
setSheet(Number(e.target.value));
}} data-testid="import-sheet">
{sheets.map((s) => (
@@ -404,22 +469,17 @@ export function ImportDialog({ job, labels, locale, plugins, worker, limits, tim