{"version":3,"file":"utils.cjs","names":["extractPObjectId","readAnnotation","Annotation","uniqBy","ColumnsCollection","hasColumnData","deriveDistinctLabels"],"sources":["../../../../src/components/PlDataTable/createPlDataTable/utils.ts"],"sourcesContent":["import {\n  type AnnotationDataStatus,\n  type ColumnUniversalId,\n  type PColumn,\n  type PColumnSpec,\n  type PObjectId,\n  Annotation,\n  extractPObjectId,\n  readAnnotation,\n} from \"@milaboratories/pl-model-common\";\nimport {\n  deriveDistinctLabels,\n  type DeriveLabelsOptions,\n} from \"../../../labels/derive_distinct_labels\";\nimport {\n  deriveDistinctTooltips,\n  type TooltipEntry,\n} from \"../../../labels/derive_distinct_tooltips\";\nimport type { ColumnOrderRule, ColumnVisibilityRule } from \"./createPlDataTableV3\";\nimport type { ColumnSelector, MatchQualifications } from \"@milaboratories/pl-model-common\";\nimport { ColumnsCollection, hasColumnData, type ColumnRecipe } from \"../../../columns\";\nimport type { GlobalCfgRenderCtx } from \"../../../render/internal\";\nimport { isNil, uniqBy } from \"es-toolkit\";\nimport { getField } from \"@milaboratories/helpers\";\n\n/** Adapt a {@link ColumnRecipe} to the plain {@link RuleColumn} shape. */\nexport function toRuleColumn(col: ColumnRecipe): RuleColumn {\n  return { id: extractPObjectId(col.id), spec: col.getSpec() };\n}\n\n/** Check if column should be omitted from the table */\nexport function isColumnHidden(spec: { annotations?: Annotation }): boolean {\n  return readAnnotation(spec, Annotation.Table.Visibility) === \"hidden\";\n}\n\n/** Check if column is hidden by default */\nexport function isColumnOptional(spec: { annotations?: Annotation }): boolean {\n  return readAnnotation(spec, Annotation.Table.Visibility) === \"optional\";\n}\n\n/** Column shape consumed by rule evaluation. */\nexport type RuleColumn = Pick<PColumn<PObjectId>, \"id\" | \"spec\">;\n\n/** Get effective visibility for a column. Rule map lookup first, then annotation fallback. */\nexport function getEffectiveVisibility(\n  col: RuleColumn,\n  visibilityByColId?: Map<PObjectId, ColumnVisibilityRule>,\n): undefined | \"default\" | \"optional\" | \"hidden\" {\n  const rule = visibilityByColId?.get(col.id);\n  if (rule !== undefined) return rule.visibility;\n  if (isColumnHidden(col.spec)) return \"hidden\";\n  if (isColumnOptional(col.spec)) return \"optional\";\n  return undefined;\n}\n\n/** Get ordering priority for a column. Rule map lookup first, then annotation fallback. */\nexport function getOrderPriority(\n  col: RuleColumn,\n  orderByColId?: Map<PObjectId, ColumnOrderRule>,\n): undefined | number {\n  const rule = orderByColId?.get(col.id);\n  if (rule !== undefined) return rule.priority;\n  const annotation = Number(readAnnotation(col.spec, Annotation.Table.OrderPriority));\n  return isNaN(annotation) ? undefined : annotation;\n}\n\n/**\n * Evaluate display rules against a set of columns and return a map of `colId → winning rule`\n * (first-match-wins, preserving original rule order).\n *\n * Predicate-based rules (`ColumnMatcher`) are evaluated directly on the spec.\n * Selector-based rules (`ColumnSelector`) are matched via the\n * `columnsCollection` service — the inline column ids must be resolvable in\n * the active render ctx for the host to read their specs.\n */\nexport function evaluateRules<R extends { match: ColumnSelector }>(\n  rules: R[],\n  columns: ColumnRecipe[],\n): Map<PObjectId, R> {\n  const result = new Map<PObjectId, R>();\n  if (rules.length === 0 || columns.length === 0) return result;\n\n  const selectorRules = rules.filter((rule) => typeof rule.match !== \"function\");\n  const selectorHitsByRule = new Map<R, Set<PObjectId>>();\n\n  if (selectorRules.length > 0) {\n    const baseColumns = uniqBy(columns, (col) => col.id);\n    const baseCollection = ColumnsCollection([{ columns: baseColumns, isFinal: true }]);\n    for (const rule of selectorRules) {\n      const hitIds = baseCollection.filter({ include: rule.match }).getColumnIds();\n      // A rule matching nothing simply contributes no entries — it must not\n      // discard the rules evaluated alongside it. The lookup below is\n      // null-safe, so leaving this rule out of the map is enough.\n      if (hitIds.length === 0) continue;\n      selectorHitsByRule.set(rule, new Set(hitIds.map((id) => extractPObjectId(id))));\n    }\n  }\n\n  for (const col of columns) {\n    const colKey = extractPObjectId(col.id);\n    for (const rule of rules) {\n      const matches = selectorHitsByRule.get(rule)?.has(colKey) ?? false;\n      if (matches) {\n        result.set(colKey, rule);\n        break;\n      }\n    }\n  }\n  return result;\n}\n\n/**\n * Build a sidecar map `columnId → AnnotationDataStatus` derived from each\n * recipe's own status. This is *rendering* metadata — kept out of the spec\n * so it cannot perturb column identity (id-bearing spec overrides would\n * diverge the visible PTable's column ids from the full table / pframe).\n *\n * Mapping `ColumnFieldStatus` × actual byte-presence → `AnnotationDataStatus`:\n *   - `absent`                       → `\"absent\"`\n *   - `resolving`                    → `\"computing\"`\n *   - `present` + `hasColumnData()`  → `\"ready\"`\n *   - `present` + no bytes yet       → `\"computing\"`\n *\n * Intentionally scoped to visible columns — the probe is meaningful only for\n * what the user will actually see.\n */\nexport function buildDataStatusMap(\n  columns: ColumnRecipe[],\n  opts: { ctx?: GlobalCfgRenderCtx } = {},\n): Record<ColumnUniversalId, AnnotationDataStatus> {\n  return columns.reduce(\n    (acc, c) => ((acc[c.id] = deriveDataStatus(c, opts)), acc),\n    {} as Record<ColumnUniversalId, AnnotationDataStatus>,\n  );\n}\n\nfunction deriveDataStatus(\n  column: ColumnRecipe,\n  opts: { ctx?: GlobalCfgRenderCtx },\n): AnnotationDataStatus {\n  const field = column.getDataStatus();\n  if (field === \"absent\") return \"absent\";\n  if (field === \"resolving\") return \"computing\";\n  return hasColumnData(column, opts) ? \"ready\" : \"computing\";\n}\n\n/** Column shape required by label derivation. */\nexport type LabelableColumn = {\n  readonly id: ColumnUniversalId;\n  readonly spec: PColumnSpec;\n  readonly linkerPath?: ReadonlyArray<{ readonly linker: { readonly spec: PColumnSpec } }>;\n  readonly qualifications?: MatchQualifications;\n  /** Columns with different markers are told apart without a \"via\" postfix. */\n  readonly marker?: string;\n};\n\n/** Derive labels for all table elements: columns via deriveDistinctLabels, axes from label columns. */\nexport function deriveAllLabels(options: {\n  columns: LabelableColumn[];\n  deriveLabelsOptions?: DeriveLabelsOptions;\n}): Record<string, string> {\n  const { columns, deriveLabelsOptions } = options;\n  const entries = columns.map((c) => ({\n    spec: c.spec,\n    linkerPath: c.linkerPath?.map((step) => ({ spec: step.linker.spec })),\n    qualifications: c.qualifications,\n    marker: c.marker,\n  }));\n  const columnLabels = deriveDistinctLabels(entries, deriveLabelsOptions).reduce(\n    (acc, label, index) => ((acc[columns[index].id] = label), acc),\n    {} as Record<string, string>,\n  );\n  return columnLabels;\n}\n\n/** Column shape required by tooltip derivation. */\nexport type TooltipableColumn = {\n  readonly id: ColumnUniversalId;\n  readonly spec: PColumnSpec;\n  readonly originalId?: PObjectId;\n  readonly linkerPath?: ReadonlyArray<{ readonly linker: { readonly spec: PColumnSpec } }>;\n  readonly qualifications?: MatchQualifications;\n};\n\n/** Derive origin tooltips for columns whose qualifications or linker path carry info. */\nexport function deriveAllTooltips(options: {\n  columns: TooltipableColumn[];\n}): Record<ColumnUniversalId, string> {\n  const { columns } = options;\n\n  const variantCountByOriginal = columns.reduce<Map<ColumnUniversalId, number>>((acc, c) => {\n    return acc.set(getField(c, \"originalId\") ?? c.id, (acc.get(c.originalId ?? c.id) ?? 0) + 1);\n  }, new Map());\n\n  const { entries } = columns.reduce(\n    ({ entries, variantSeen }, c) => {\n      const id = getField(c, \"originalId\") ?? c.id;\n      const variantCount = variantCountByOriginal.get(id);\n      const variantIndex =\n        (variantSeen.set(id, (variantSeen.get(id) ?? 0) + 1), variantSeen.get(id));\n\n      entries.push({\n        spec: c.spec,\n        linkerPath: c.linkerPath,\n        qualifications: c.qualifications,\n        variantIndex,\n        variantCount,\n      });\n\n      return { entries, variantSeen };\n    },\n    { entries: [] as TooltipEntry[], variantSeen: new Map<ColumnUniversalId, number>() },\n  );\n\n  const tooltips = deriveDistinctTooltips(entries);\n\n  return Object.fromEntries(\n    tooltips.flatMap((t, i) => (isNil(t) ? [] : [[columns[i].id, t] as const])),\n  );\n}\n"],"mappings":";;;;;;;;;;AA0BA,SAAgB,aAAa,KAA+B;CAC1D,OAAO;EAAE,KAAA,GAAIA,gCAAAA,iBAAAA,CAAiB,IAAI,EAAE;EAAG,MAAM,IAAI,QAAQ;CAAE;AAC7D;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