@platforma-sdk/model 1.87.0 → 1.88.8

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.
Files changed (54) hide show
  1. package/dist/block_api_v3.d.ts +9 -0
  2. package/dist/block_api_v3.d.ts.map +1 -1
  3. package/dist/block_model.cjs +89 -9
  4. package/dist/block_model.cjs.map +1 -1
  5. package/dist/block_model.d.ts +81 -19
  6. package/dist/block_model.d.ts.map +1 -1
  7. package/dist/block_model.js +89 -9
  8. package/dist/block_model.js.map +1 -1
  9. package/dist/block_storage_callbacks.cjs +128 -25
  10. package/dist/block_storage_callbacks.cjs.map +1 -1
  11. package/dist/block_storage_callbacks.js +129 -26
  12. package/dist/block_storage_callbacks.js.map +1 -1
  13. package/dist/block_storage_facade.cjs.map +1 -1
  14. package/dist/block_storage_facade.d.ts +37 -4
  15. package/dist/block_storage_facade.d.ts.map +1 -1
  16. package/dist/block_storage_facade.js.map +1 -1
  17. package/dist/columns/column_values.cjs +126 -0
  18. package/dist/columns/column_values.cjs.map +1 -0
  19. package/dist/columns/column_values.d.ts +65 -0
  20. package/dist/columns/column_values.d.ts.map +1 -0
  21. package/dist/columns/column_values.js +124 -0
  22. package/dist/columns/column_values.js.map +1 -0
  23. package/dist/columns/index.cjs +4 -0
  24. package/dist/columns/index.d.ts +2 -1
  25. package/dist/columns/index.js +2 -1
  26. package/dist/index.cjs +6 -0
  27. package/dist/index.d.ts +3 -1
  28. package/dist/index.js +3 -1
  29. package/dist/package.cjs +1 -1
  30. package/dist/package.js +1 -1
  31. package/dist/pframe_utils/column_value_options.cjs +85 -0
  32. package/dist/pframe_utils/column_value_options.cjs.map +1 -0
  33. package/dist/pframe_utils/column_value_options.d.ts +14 -0
  34. package/dist/pframe_utils/column_value_options.d.ts.map +1 -0
  35. package/dist/pframe_utils/column_value_options.js +85 -0
  36. package/dist/pframe_utils/column_value_options.js.map +1 -0
  37. package/dist/pframe_utils/index.cjs +2 -0
  38. package/dist/pframe_utils/index.cjs.map +1 -1
  39. package/dist/pframe_utils/index.d.ts +2 -1
  40. package/dist/pframe_utils/index.d.ts.map +1 -1
  41. package/dist/pframe_utils/index.js +2 -1
  42. package/dist/pframe_utils/index.js.map +1 -1
  43. package/package.json +15 -14
  44. package/src/args_issues.test.ts +532 -0
  45. package/src/block_api_v3.ts +10 -0
  46. package/src/block_model.ts +146 -32
  47. package/src/block_storage_callbacks.ts +174 -43
  48. package/src/block_storage_facade.ts +36 -6
  49. package/src/columns/column_values.test.ts +183 -0
  50. package/src/columns/column_values.ts +194 -0
  51. package/src/columns/index.ts +1 -0
  52. package/src/pframe_utils/column_value_options.test.ts +126 -0
  53. package/src/pframe_utils/column_value_options.ts +111 -0
  54. package/src/pframe_utils/index.ts +1 -0
@@ -50,7 +50,7 @@
50
50
  import type { MutateStoragePayload } from "./block_storage";
51
51
  import type { ConfigRenderLambda } from "./bconfig";
52
52
  import { createRenderLambda, tryRegisterCallback } from "./internal";
53
- import type { StringifiedJson } from "@milaboratories/pl-model-common";
53
+ import type { ArgsIssue, StringifiedJson } from "@milaboratories/pl-model-common";
54
54
 
55
55
  // =============================================================================
56
56
  // Facade Version
@@ -170,23 +170,53 @@ export interface BlockStorageFacade {
170
170
 
171
171
  /**
172
172
  * Derive args from storage.
173
- * Called to get block configuration args from storage.
173
+ * Called to get block configuration args from storage, and whether the block may run them.
174
+ *
175
+ * A middle layer that predates args issues reads only `error` and `value`, and each variant
176
+ * means the same to it as before: `value` is runnable args, `error` is no args. A block built
177
+ * with an SDK that predates args issues returns `{ error }` or `{ value }` with no `issues`.
178
+ *
174
179
  * @param storageJson - Storage as JSON string
175
- * @returns Args derivation result - either error or derived value
180
+ * @returns One of:
181
+ * - `{ error }`: `args()` threw, so there are no args;
182
+ * - `{ error, args, issues }`: args were built, but the block's `argsIssues()` found errors in
183
+ * them, so the block must not run; `error` joins the error messages, `issues` lists every
184
+ * issue;
185
+ * - `{ value, issues }`: args the block may run; `issues` holds the warnings.
176
186
  */
177
187
  [BlockStorageFacadeCallbacks.ArgsDerive]: (
178
188
  storageJson: StringifiedJson,
179
- ) => { error: string } | { error?: undefined; value: unknown };
189
+ ) =>
190
+ | { error: string }
191
+ | { error: string; args: unknown; issues: ArgsIssue[] }
192
+ | { error?: undefined; value: unknown; issues: ArgsIssue[] };
180
193
 
181
194
  /**
182
195
  * Derive prerunArgs from storage.
183
196
  * Called to get prerun args; falls back to args callback if not registered.
197
+ *
198
+ * A block with its own prerunArgs is staged with them unless its `prerunArgsIssues()` finds errors
199
+ * in them. A block without its own prerunArgs is staged with its args unless its `argsIssues()`
200
+ * finds errors in them.
201
+ *
202
+ * A middle layer that predates args issues reads only `error` and `value`: `value` is args to
203
+ * stage, `error` skips staging. A block built with an SDK that predates args issues returns
204
+ * `{ error }` or `{ value }` with no `issues`.
205
+ *
184
206
  * @param storageJson - Storage as JSON string
185
- * @returns Args derivation result - either error or derived value
207
+ * @returns One of:
208
+ * - `{ error }`: the lambda building the prerun args threw;
209
+ * - `{ error, issues }`: prerun args were built, but errors were found in them, so the block
210
+ * is not staged; `error` joins the error messages, `issues` lists every issue;
211
+ * - `{ value, issues }`: args to stage, `undefined` to skip staging; `issues` holds the
212
+ * warnings.
186
213
  */
187
214
  [BlockStorageFacadeCallbacks.PrerunArgsDerive]: (
188
215
  storageJson: StringifiedJson,
189
- ) => { error: string } | { error?: undefined; value: unknown };
216
+ ) =>
217
+ | { error: string }
218
+ | { error: string; issues: ArgsIssue[] }
219
+ | { error?: undefined; value: unknown; issues: ArgsIssue[] };
190
220
 
191
221
  /**
192
222
  * Get initial storage JSON for new blocks.
@@ -0,0 +1,183 @@
1
+ import { afterEach, describe, expect, test, vi } from "vitest";
2
+ import {
3
+ createColumnValueId,
4
+ createGlobalPObjectId,
5
+ type PColumn,
6
+ type PColumnValues,
7
+ type PFrameHandle,
8
+ } from "@milaboratories/pl-model-common";
9
+ import type { GlobalCfgRenderCtx } from "../render/internal";
10
+ import { ColumnRecipe } from "./column_recipes";
11
+ import {
12
+ createColumnValueOptions,
13
+ deriveColumnValueOptions,
14
+ deriveLabelledColumnValueOptions,
15
+ } from "./column_values";
16
+
17
+ afterEach(() => {
18
+ vi.restoreAllMocks();
19
+ });
20
+
21
+ describe("deriveColumnValueOptions", () => {
22
+ test("offers each distinct value once, in natural order of labels", () => {
23
+ expect(deriveColumnValueOptions(COLUMN_ID, ["R10", "R2", "R10", "Library"])).toEqual([
24
+ option("Library"),
25
+ option("R2"),
26
+ option("R10"),
27
+ ]);
28
+ });
29
+
30
+ test("does not offer an empty value", () => {
31
+ expect(deriveColumnValueOptions(COLUMN_ID, ["", "R1"])).toEqual([option("R1")]);
32
+ });
33
+
34
+ test("orders digit runs as numbers and text case-insensitively", () => {
35
+ const labels = deriveColumnValueOptions(COLUMN_ID, ["r10", "R009", "b", "A"]).map(
36
+ (o) => o.label,
37
+ );
38
+ expect(labels).toEqual(["A", "b", "R009", "r10"]);
39
+ });
40
+
41
+ test("works in a runtime without Intl", async () => {
42
+ vi.resetModules();
43
+ vi.stubGlobal("Intl", undefined);
44
+ try {
45
+ const fresh = await import("./column_values");
46
+ const labels = fresh.deriveColumnValueOptions(COLUMN_ID, ["R10", "R2"]).map((o) => o.label);
47
+ expect(labels).toEqual(["R2", "R10"]);
48
+ } finally {
49
+ vi.unstubAllGlobals();
50
+ }
51
+ });
52
+ });
53
+
54
+ describe("deriveLabelledColumnValueOptions", () => {
55
+ test("labels each value by the label of its first row, in natural order of labels", () => {
56
+ const rows = [
57
+ { value: "s2", label: "Donor 10" },
58
+ { value: "s1", label: "Donor 2" },
59
+ { value: "s2", label: "Donor 11" },
60
+ ];
61
+ expect(deriveLabelledColumnValueOptions(COLUMN_ID, rows)).toEqual([
62
+ option("s1", "Donor 2"),
63
+ option("s2", "Donor 10"),
64
+ ]);
65
+ });
66
+
67
+ test("leaves a value with an empty label to label itself, and offers no empty value", () => {
68
+ const rows = [
69
+ { value: "s1", label: "" },
70
+ { value: "", label: "Nobody" },
71
+ ];
72
+ expect(deriveLabelledColumnValueOptions(COLUMN_ID, rows)).toEqual([option("s1")]);
73
+ });
74
+ });
75
+
76
+ describe("createColumnValueOptions", () => {
77
+ test("holds a frame of the value column while it is there", () => {
78
+ vi.spyOn(ColumnRecipe, "getStatus").mockReturnValue("present");
79
+ const ctx = renderCtx();
80
+
81
+ expect(createColumnValueOptions({ valueColumn: COLUMN_ID }, { ctx })).toEqual({
82
+ type: "present",
83
+ valueColumn: COLUMN_ID,
84
+ frame: FRAME,
85
+ frameColumns: { value: COLUMN_ID, label: null },
86
+ });
87
+ expect(ctx.createPFrame).toHaveBeenCalledWith([COLUMN_ID]);
88
+ });
89
+
90
+ test("puts the label column into the frame beside the value column", () => {
91
+ vi.spyOn(ColumnRecipe, "getStatus").mockReturnValue("present");
92
+ const ctx = renderCtx();
93
+
94
+ expect(
95
+ createColumnValueOptions({ valueColumn: COLUMN_ID, labelColumn: LABEL_ID }, { ctx }),
96
+ ).toEqual({
97
+ type: "present",
98
+ valueColumn: COLUMN_ID,
99
+ frame: FRAME,
100
+ frameColumns: { value: COLUMN_ID, label: LABEL_ID },
101
+ });
102
+ expect(ctx.createPFrame).toHaveBeenCalledWith([COLUMN_ID, LABEL_ID]);
103
+ });
104
+
105
+ test("takes a materialised column as it is", () => {
106
+ const ctx = renderCtx();
107
+ const column: PColumn<PColumnValues> = {
108
+ id: COLUMN_ID,
109
+ spec: {
110
+ kind: "PColumn",
111
+ name: "pl7.app/metadata",
112
+ valueType: "String",
113
+ axesSpec: [{ name: "pl7.app/sampleId", type: "String" }],
114
+ },
115
+ data: [{ key: ["s1"], val: "R1" }],
116
+ };
117
+
118
+ expect(createColumnValueOptions({ valueColumn: column }, { ctx })).toMatchObject({
119
+ type: "present",
120
+ valueColumn: COLUMN_ID,
121
+ frameColumns: { value: COLUMN_ID, label: null },
122
+ });
123
+ expect(ctx.createPFrame).toHaveBeenCalledWith([column]);
124
+ });
125
+
126
+ test("is resolving while the value column or the label column is", () => {
127
+ vi.spyOn(ColumnRecipe, "getStatus").mockReturnValue("resolving");
128
+ expect(createColumnValueOptions({ valueColumn: COLUMN_ID }, { ctx: renderCtx() })).toEqual({
129
+ type: "resolving",
130
+ valueColumn: COLUMN_ID,
131
+ });
132
+
133
+ vi.spyOn(ColumnRecipe, "getStatus").mockImplementation((id) =>
134
+ id === LABEL_ID ? "resolving" : "present",
135
+ );
136
+ const ctx = renderCtx();
137
+ expect(
138
+ createColumnValueOptions({ valueColumn: COLUMN_ID, labelColumn: LABEL_ID }, { ctx }),
139
+ ).toEqual({ type: "resolving", valueColumn: COLUMN_ID });
140
+ expect(ctx.createPFrame).not.toHaveBeenCalled();
141
+ });
142
+
143
+ test("is absent once the value column is gone", () => {
144
+ vi.spyOn(ColumnRecipe, "getStatus").mockReturnValue("absent");
145
+ const ctx = renderCtx();
146
+
147
+ expect(createColumnValueOptions({ valueColumn: COLUMN_ID }, { ctx })).toEqual({
148
+ type: "absent",
149
+ valueColumn: COLUMN_ID,
150
+ });
151
+ expect(ctx.createPFrame).not.toHaveBeenCalled();
152
+ });
153
+
154
+ test("leaves the values to label themselves once the label column is gone", () => {
155
+ vi.spyOn(ColumnRecipe, "getStatus").mockImplementation((id) =>
156
+ id === LABEL_ID ? "absent" : "present",
157
+ );
158
+ const ctx = renderCtx();
159
+
160
+ expect(
161
+ createColumnValueOptions({ valueColumn: COLUMN_ID, labelColumn: LABEL_ID }, { ctx }),
162
+ ).toMatchObject({ type: "present", frameColumns: { value: COLUMN_ID, label: null } });
163
+ expect(ctx.createPFrame).toHaveBeenCalledWith([COLUMN_ID]);
164
+ });
165
+ });
166
+
167
+ // Internals
168
+
169
+ const COLUMN_ID = createGlobalPObjectId("samples", "pf.metadata.round");
170
+
171
+ const LABEL_ID = createGlobalPObjectId("samples", "pf.metadata.roundName");
172
+
173
+ const FRAME = "frame-of-round" as PFrameHandle;
174
+
175
+ function option(value: string, label = value) {
176
+ return { value: createColumnValueId({ column: COLUMN_ID, value }), label };
177
+ }
178
+
179
+ /** A render ctx that creates {@link FRAME} for any columns; only `createPFrame` is called. */
180
+ function renderCtx() {
181
+ const createPFrame = vi.fn(() => FRAME);
182
+ return Object.assign({ createPFrame } as GlobalCfgRenderCtx, { createPFrame });
183
+ }
@@ -0,0 +1,194 @@
1
+ import {
2
+ createColumnValueId,
3
+ extractPObjectId,
4
+ isPColumn,
5
+ type ColumnUniversalId,
6
+ type ColumnValueId,
7
+ type PColumn,
8
+ type PFrameHandle,
9
+ type PObjectId,
10
+ } from "@milaboratories/pl-model-common";
11
+ import { finalizePColumnData } from "../render/api";
12
+ import type { GlobalCfgRenderCtx, PColumnDataUniversal } from "../render/internal";
13
+ import { getCfgRenderCtx } from "../internal";
14
+ import { ColumnRecipe } from "./column_recipes";
15
+ import type { ColumnResolutionStatus } from "./column_recipes/types";
16
+ import type { DataColumnRecipe } from "./data_column";
17
+
18
+ /** Drop-down option for a value of a column — column-value-id valued. */
19
+ export type ColumnValueOption = {
20
+ readonly value: ColumnValueId;
21
+ readonly label: string;
22
+ };
23
+
24
+ /** A column a value picker offers the values of, or labels them by. */
25
+ export type ColumnValueOptionsColumn =
26
+ | ColumnUniversalId
27
+ | PColumn<undefined | PColumnDataUniversal>
28
+ | DataColumnRecipe
29
+ | ColumnRecipe;
30
+
31
+ /**
32
+ * What a UI reads the options of a value picker from: a frame holding the value column, and the
33
+ * label column while there is one, as long as the value column is there. `valueColumn` is the
34
+ * column the options are values of, so the UI can tell a model that still describes an earlier
35
+ * pick. `frameColumns` names both columns as the frame holds them.
36
+ */
37
+ export type ColumnValueOptionsModel =
38
+ | { readonly type: "resolving"; readonly valueColumn: ColumnUniversalId }
39
+ | { readonly type: "absent"; readonly valueColumn: ColumnUniversalId }
40
+ | {
41
+ readonly type: "present";
42
+ readonly valueColumn: ColumnUniversalId;
43
+ readonly frame: PFrameHandle;
44
+ readonly frameColumns: {
45
+ readonly value: PObjectId;
46
+ /** `null` when the values label themselves. */
47
+ readonly label: PObjectId | null;
48
+ };
49
+ };
50
+
51
+ /**
52
+ * The model of a value picker over the values of `valueColumn`, for a model output; the UI reads
53
+ * the options through it (`usePlColumnValueOptions`, `PlColumnValueDropdown`). Each option is a
54
+ * value of `valueColumn`, labelled by the value of `labelColumn` in the same row, or by the value
55
+ * itself when no label column is given.
56
+ *
57
+ * `absent` once the value column is gone: a stored id may name a column its upstream block no
58
+ * longer produces. A label column that is gone leaves the values to label themselves; one that is
59
+ * still resolving keeps the model resolving.
60
+ */
61
+ export function createColumnValueOptions(
62
+ columns: {
63
+ readonly valueColumn: ColumnValueOptionsColumn;
64
+ readonly labelColumn?: ColumnValueOptionsColumn;
65
+ },
66
+ deps?: { readonly ctx?: GlobalCfgRenderCtx },
67
+ ): ColumnValueOptionsModel {
68
+ const ctx = deps?.ctx ?? getCfgRenderCtx();
69
+ const value = frameEntryOf(columns.valueColumn, ctx);
70
+ const valueColumn = value.id;
71
+ if (value.status !== "present") return { type: value.status, valueColumn };
72
+
73
+ const label =
74
+ columns.labelColumn === undefined ? undefined : frameEntryOf(columns.labelColumn, ctx);
75
+ if (label?.status === "resolving") return { type: "resolving", valueColumn };
76
+ const labelled =
77
+ label?.status === "present" && label.frameId !== value.frameId ? label : undefined;
78
+
79
+ const frame = ctx.createPFrame(labelled === undefined ? [value.def] : [value.def, labelled.def]);
80
+ return {
81
+ type: "present",
82
+ valueColumn,
83
+ frame,
84
+ frameColumns: { value: value.frameId, label: labelled?.frameId ?? null },
85
+ };
86
+ }
87
+
88
+ /**
89
+ * Distinct `values` of `column` as options, each a column value id naming the column, labelled
90
+ * by the value itself and ordered naturally by label ("R2" before "R10"). Empty values are not
91
+ * offered.
92
+ */
93
+ export function deriveColumnValueOptions(
94
+ column: ColumnUniversalId,
95
+ values: readonly string[],
96
+ ): ColumnValueOption[] {
97
+ return deriveLabelledColumnValueOptions(
98
+ column,
99
+ values.map((value) => ({ value, label: value })),
100
+ );
101
+ }
102
+
103
+ /**
104
+ * Distinct values of `column` among `rows` as options, each a column value id naming the column,
105
+ * labelled by the label of the first row holding the value, and ordered naturally by label ("R2"
106
+ * before "R10"). Empty values are not offered; a value whose label is empty labels itself.
107
+ */
108
+ export function deriveLabelledColumnValueOptions(
109
+ column: ColumnUniversalId,
110
+ rows: readonly { readonly value: string; readonly label: string }[],
111
+ ): ColumnValueOption[] {
112
+ const options = new Map<string, ColumnValueOption>();
113
+ for (const { value, label } of rows) {
114
+ if (value === "" || options.has(value)) continue;
115
+ options.set(value, {
116
+ value: createColumnValueId({ column, value }),
117
+ label: label === "" ? value : label,
118
+ });
119
+ }
120
+ return [...options.values()].sort((a, b) => compareNatural(a.label, b.label));
121
+ }
122
+
123
+ // Internals
124
+
125
+ /** A column as a frame is made of it: its id, its status, and what the frame is created from. */
126
+ type FrameEntry = {
127
+ readonly id: ColumnUniversalId;
128
+ readonly status: ColumnResolutionStatus;
129
+ readonly frameId: PObjectId;
130
+ readonly def: Parameters<GlobalCfgRenderCtx["createPFrame"]>[0][number];
131
+ };
132
+
133
+ /**
134
+ * A column given by id or by a recipe goes into the frame by its id, which the frame holds as the
135
+ * bare id of its leaf; a materialised column goes in as it is.
136
+ */
137
+ function frameEntryOf(column: ColumnValueOptionsColumn, ctx: GlobalCfgRenderCtx): FrameEntry {
138
+ if (typeof column === "string") {
139
+ return {
140
+ id: column,
141
+ status: ColumnRecipe.getStatus(column, { ctx }),
142
+ frameId: extractPObjectId(column),
143
+ def: column,
144
+ };
145
+ }
146
+ if (isPColumn<undefined | PColumnDataUniversal>(column)) {
147
+ return {
148
+ id: column.id,
149
+ status: "present",
150
+ frameId: column.id,
151
+ def: finalizePColumnData(column),
152
+ };
153
+ }
154
+ return {
155
+ id: column.id,
156
+ status: column.getDataStatus(),
157
+ frameId: extractPObjectId(column.id),
158
+ def: column.id,
159
+ };
160
+ }
161
+
162
+ const CHUNKS = /\d+|\D+/g;
163
+
164
+ /**
165
+ * Natural order: runs of digits compare as numbers, other text case-insensitively, so "R2"
166
+ * comes before "R10". The model runtime has no `Intl`.
167
+ */
168
+ function compareNatural(a: string, b: string): number {
169
+ const chunksA = a.match(CHUNKS) ?? [];
170
+ const chunksB = b.match(CHUNKS) ?? [];
171
+ for (let i = 0; i < Math.min(chunksA.length, chunksB.length); i++) {
172
+ const order = compareChunks(chunksA[i], chunksB[i]);
173
+ if (order !== 0) return order;
174
+ }
175
+ return chunksA.length - chunksB.length || compareStrings(a, b);
176
+ }
177
+
178
+ function compareChunks(a: string, b: string): number {
179
+ if (isDigits(a) && isDigits(b)) {
180
+ // Compared as digit strings, so numbers of any length keep their order.
181
+ const numberA = a.replace(/^0+(?=\d)/, "");
182
+ const numberB = b.replace(/^0+(?=\d)/, "");
183
+ return numberA.length - numberB.length || compareStrings(numberA, numberB);
184
+ }
185
+ return compareStrings(a.toLowerCase(), b.toLowerCase());
186
+ }
187
+
188
+ function isDigits(chunk: string): boolean {
189
+ return chunk.charCodeAt(0) >= 48 && chunk.charCodeAt(0) <= 57;
190
+ }
191
+
192
+ function compareStrings(a: string, b: string): number {
193
+ return a < b ? -1 : a > b ? 1 : 0;
194
+ }
@@ -7,3 +7,4 @@ export * from "./column_recipes";
7
7
  export * from "./column";
8
8
  export * from "./utils";
9
9
  export * from "./peer_links";
10
+ export * from "./column_values";
@@ -0,0 +1,126 @@
1
+ import { afterEach, describe, expect, test, vi } from "vitest";
2
+ import {
3
+ createColumnValueId,
4
+ createGlobalPObjectId,
5
+ type FullPTableColumnData,
6
+ type PFrameHandle,
7
+ type UniqueValuesResponse,
8
+ } from "@milaboratories/pl-model-common";
9
+ import type { PresentColumnValueOptionsModel } from "./column_value_options";
10
+ import { readColumnValueOptions } from "./column_value_options";
11
+
12
+ afterEach(() => {
13
+ vi.unstubAllGlobals();
14
+ });
15
+
16
+ describe("readColumnValueOptions", () => {
17
+ test("offers the distinct values of the value column, without missing ones", async () => {
18
+ const driver = stubDriver({
19
+ unique: { values: { type: "String", data: ["R10", null, "R2"] }, overflow: false },
20
+ });
21
+
22
+ expect(await readColumnValueOptions(UNLABELLED)).toEqual([option("R2"), option("R10")]);
23
+ expect(driver.getUniqueValues).toHaveBeenCalledWith(FRAME, {
24
+ columnId: VALUE_ID,
25
+ filters: [],
26
+ limit: 100_000,
27
+ });
28
+ });
29
+
30
+ test("reads a number column as decimal strings", async () => {
31
+ stubDriver({
32
+ unique: { values: { type: "Int", data: new Int32Array([2, 10]) }, overflow: false },
33
+ });
34
+
35
+ expect(await readColumnValueOptions(UNLABELLED)).toEqual([option("2"), option("10")]);
36
+ });
37
+
38
+ test("rejects a column with more distinct values than a picker offers", async () => {
39
+ stubDriver({ unique: { values: { type: "String", data: [] }, overflow: true } });
40
+ await expect(readColumnValueOptions(UNLABELLED)).rejects.toThrow("more than 100000");
41
+ });
42
+
43
+ test("labels each value by the label column in the same row", async () => {
44
+ const driver = stubDriver({
45
+ table: [
46
+ columnData(VALUE_ID, ["s1", "s2", null, "s3"]),
47
+ columnData(LABEL_ID, ["Donor 2", "Donor 10", "Nobody", null]),
48
+ ],
49
+ });
50
+
51
+ expect(await readColumnValueOptions(LABELLED)).toEqual([
52
+ option("s1", "Donor 2"),
53
+ option("s2", "Donor 10"),
54
+ option("s3"),
55
+ ]);
56
+ expect(driver.calculateTableData).toHaveBeenCalledWith(
57
+ FRAME,
58
+ {
59
+ src: {
60
+ type: "outer",
61
+ primary: { type: "column", column: VALUE_ID },
62
+ secondary: [{ type: "column", column: LABEL_ID }],
63
+ },
64
+ filters: [],
65
+ sorting: [],
66
+ },
67
+ { offset: 0, length: 100_001 },
68
+ );
69
+ });
70
+
71
+ test("rejects a labelled column with more rows than a picker reads", async () => {
72
+ const values = Array.from({ length: 100_001 }, (_, i) => `s${i}`);
73
+ stubDriver({ table: [columnData(VALUE_ID, values), columnData(LABEL_ID, values)] });
74
+ await expect(readColumnValueOptions(LABELLED)).rejects.toThrow("more than 100000 rows");
75
+ });
76
+ });
77
+
78
+ // Internals
79
+
80
+ const VALUE_ID = createGlobalPObjectId("samples", "pf.metadata.round");
81
+
82
+ const LABEL_ID = createGlobalPObjectId("samples", "pf.metadata.roundName");
83
+
84
+ const FRAME = "frame-of-round" as PFrameHandle;
85
+
86
+ const UNLABELLED: PresentColumnValueOptionsModel = {
87
+ type: "present",
88
+ valueColumn: VALUE_ID,
89
+ frame: FRAME,
90
+ frameColumns: { value: VALUE_ID, label: null },
91
+ };
92
+
93
+ const LABELLED: PresentColumnValueOptionsModel = {
94
+ ...UNLABELLED,
95
+ frameColumns: { value: VALUE_ID, label: LABEL_ID },
96
+ };
97
+
98
+ function option(value: string, label = value) {
99
+ return { value: createColumnValueId({ column: VALUE_ID, value }), label };
100
+ }
101
+
102
+ function columnData(id: typeof VALUE_ID, data: (string | null)[]): FullPTableColumnData {
103
+ return {
104
+ spec: {
105
+ type: "column",
106
+ id,
107
+ spec: {
108
+ kind: "PColumn",
109
+ name: "pl7.app/metadata",
110
+ valueType: "String",
111
+ axesSpec: [{ name: "pl7.app/sampleId", type: "String" }],
112
+ },
113
+ },
114
+ data: { type: "String", data },
115
+ };
116
+ }
117
+
118
+ /** A platforma whose frame driver answers value requests with `unique` and joins with `table`. */
119
+ function stubDriver(answers: { unique?: UniqueValuesResponse; table?: FullPTableColumnData[] }) {
120
+ const driver = {
121
+ getUniqueValues: vi.fn(async () => answers.unique),
122
+ calculateTableData: vi.fn(async () => answers.table),
123
+ };
124
+ vi.stubGlobal("platforma", { pFrameDriver: driver });
125
+ return driver;
126
+ }
@@ -0,0 +1,111 @@
1
+ import {
2
+ pTableValue,
3
+ type CalculateTableDataRequest,
4
+ type FullPTableColumnData,
5
+ type PFrameHandle,
6
+ type PObjectId,
7
+ } from "@milaboratories/pl-model-common";
8
+ import type { ColumnValueOption, ColumnValueOptionsModel } from "../columns";
9
+ import { deriveColumnValueOptions, deriveLabelledColumnValueOptions } from "../columns";
10
+
11
+ /** A model whose value column is there to read. */
12
+ export type PresentColumnValueOptionsModel = Extract<ColumnValueOptionsModel, { type: "present" }>;
13
+
14
+ /**
15
+ * The options of a value picker, read in the UI through the frame of `model` (see
16
+ * `deriveColumnValueOptions` and `deriveLabelledColumnValueOptions`). Missing values are not
17
+ * offered; a value with a missing label labels itself. Rejects when the value column has more
18
+ * distinct values than a picker can offer, or, with a label column, more rows than it reads.
19
+ */
20
+ export async function readColumnValueOptions(
21
+ model: PresentColumnValueOptionsModel,
22
+ ): Promise<ColumnValueOption[]> {
23
+ const { value, label } = model.frameColumns;
24
+ if (label === null) {
25
+ return deriveColumnValueOptions(
26
+ model.valueColumn,
27
+ await readDistinctValues(model.frame, value),
28
+ );
29
+ }
30
+ return deriveLabelledColumnValueOptions(
31
+ model.valueColumn,
32
+ await readLabelledValues(model.frame, { value, label }),
33
+ );
34
+ }
35
+
36
+ // Internals
37
+
38
+ /** More distinct values than any picker can usefully list. */
39
+ const VALUES_LIMIT = 100_000;
40
+
41
+ async function readDistinctValues(frame: PFrameHandle, column: PObjectId): Promise<string[]> {
42
+ const response = await frameDriver().getUniqueValues(frame, {
43
+ columnId: column,
44
+ filters: [],
45
+ limit: VALUES_LIMIT,
46
+ });
47
+ if (response.overflow) {
48
+ throw new Error(`The column has more than ${VALUES_LIMIT} distinct values`);
49
+ }
50
+
51
+ const values: string[] = [];
52
+ for (let row = 0; row < response.values.data.length; row++) {
53
+ const value = pTableValue(response.values, row, { na: null });
54
+ if (value !== null) values.push(String(value));
55
+ }
56
+ return values;
57
+ }
58
+
59
+ /**
60
+ * Every row of the value column with the label the label column holds at the same keys, or an
61
+ * empty label where it holds none. Rows without a value are left out.
62
+ */
63
+ async function readLabelledValues(
64
+ frame: PFrameHandle,
65
+ columns: { readonly value: PObjectId; readonly label: PObjectId },
66
+ ): Promise<{ value: string; label: string }[]> {
67
+ const request: CalculateTableDataRequest<PObjectId> = {
68
+ src: {
69
+ type: "outer",
70
+ primary: { type: "column", column: columns.value },
71
+ secondary: [{ type: "column", column: columns.label }],
72
+ },
73
+ filters: [],
74
+ sorting: [],
75
+ };
76
+ // One row past the limit tells a column that has more rows than a picker reads.
77
+ const response = await frameDriver().calculateTableData(frame, request, {
78
+ offset: 0,
79
+ length: VALUES_LIMIT + 1,
80
+ });
81
+ const values = columnData(response, columns.value);
82
+ const labels = columnData(response, columns.label);
83
+ if (values.data.length > VALUES_LIMIT) {
84
+ throw new Error(`The column has more than ${VALUES_LIMIT} rows`);
85
+ }
86
+
87
+ const rows: { value: string; label: string }[] = [];
88
+ for (let row = 0; row < values.data.length; row++) {
89
+ const value = pTableValue(values, row, { na: null });
90
+ if (value === null) continue;
91
+ const label = pTableValue(labels, row, { na: null });
92
+ rows.push({ value: String(value), label: label === null ? "" : String(label) });
93
+ }
94
+ return rows;
95
+ }
96
+
97
+ function columnData(
98
+ response: readonly FullPTableColumnData[],
99
+ column: PObjectId,
100
+ ): FullPTableColumnData["data"] {
101
+ const entry = response.find((item) => item.spec.type === "column" && item.spec.id === column);
102
+ if (entry === undefined) throw new Error(`The frame did not return column ${column}`);
103
+ return entry.data;
104
+ }
105
+
106
+ function frameDriver() {
107
+ if (typeof platforma === "undefined" || platforma.pFrameDriver === undefined) {
108
+ throw new Error("The frame driver is not available");
109
+ }
110
+ return platforma.pFrameDriver;
111
+ }
@@ -27,6 +27,7 @@ import {
27
27
  } from "@milaboratories/pl-model-common";
28
28
 
29
29
  export * from "./columns";
30
+ export * from "./column_value_options";
30
31
 
31
32
  // Types
32
33
  type PValue = string | number | null;