@macrostrat/column-views 3.12.1 → 3.12.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 +1 @@
1
- {"version":3,"file":"helpers.js","sources":["../../src/prepare-units/helpers.ts"],"sourcesContent":["import type { BaseUnit, UnitLong } from \"@macrostrat/api-types\";\nimport { group } from \"d3-array\";\nimport { ColumnAxisType } from \"@macrostrat/column-components\";\nimport {\n createUnitSorter,\n ensureArray,\n ensureRealFloat,\n getUnitHeightRange,\n unitsOverlap,\n} from \"./utils\";\nimport {\n AgeRangeRelationship,\n compareAgeRanges,\n mergeAgeRanges,\n MergeMode,\n} from \"@macrostrat/stratigraphy-utils\";\nimport type { ExtUnit, SectionInfo, StratigraphicPackage } from \"./types\";\n\nconst dt = 0.001;\n\nexport type UnitWithLayoutParameters<T extends BaseUnit> = T & {\n layout: UnitLayoutData<T>;\n};\n\nexport type UnitWithLayoutHints<T extends BaseUnit> = T & {\n layoutHints?: UnitLayoutHints;\n};\n\ninterface UnitLayoutInfo {\n column: number;\n nColumns: number;\n}\n\ntype UnitLayoutHints = Partial<UnitLayoutInfo>;\n\ntype UnitLayoutData<T extends BaseUnit> = UnitLayoutInfo & {\n totalColumns: number;\n unitGroup: UnitGroup<T>;\n};\n\nclass UnitGroup<T extends BaseUnit> implements StratigraphicPackage {\n units: T[];\n axisType: ColumnAxisType;\n\n constructor(units: T[], axisType: ColumnAxisType = ColumnAxisType.AGE) {\n this.units = units;\n this.axisType = axisType;\n }\n\n get t_age(): number {\n return Math.min(...this.units.map((d) => d.t_age));\n }\n\n get b_age(): number {\n return Math.max(...this.units.map((d) => d.b_age));\n }\n\n getUnits(): UnitWithLayoutParameters<T>[] {\n return assignColumnsToUnitsWithinOverlappingGroup(this);\n }\n}\n\nfunction groupUnitsByMutualOverlap<T extends BaseUnit>(\n units: T[],\n tolerance: number = dt,\n axisType: ColumnAxisType = ColumnAxisType.AGE,\n): UnitGroup<T>[] {\n /** Group units within a section that have mutual overlap. */\n\n const sections = groupUnitsIntoSectionsByOverlap(units, axisType, tolerance);\n\n return sections.map((d) => {\n return new UnitGroup(d.units, axisType);\n });\n}\n\nconst sortByAge = createUnitSorter(ColumnAxisType.AGE);\n\nfunction assignColumnsToUnitsWithinOverlappingGroup<T extends BaseUnit>(\n group: UnitGroup<UnitWithLayoutHints<T>>,\n): UnitWithLayoutParameters<T>[] {\n /** A relatively naïve function to assign columns to units within a mutually overlapping group.\n * This gets the number of columns that would be needed to accommodate the units in the group.\n * It then assigns columns to units in the group based on the number of columns needed, with\n * lower units further to the left.\n */\n\n const sortedUnits = [...group.units].sort(createUnitSorter(group.axisType));\n\n const columns: T[][] = [];\n\n let nColumns = 1;\n\n for (const unit of sortedUnits) {\n let startIndex = 0;\n let endIndex = 0;\n // Find a column that is not already occupied by an overlapping unit\n const colHint = unit.layoutHints?.column;\n if (colHint != null) {\n columns[colHint] ??= [];\n columns[colHint].push(unit);\n continue;\n }\n let didAddToExistingColumn = false;\n\n for (const column of columns) {\n const lastUnit = column[column.length - 1];\n if (!unitsOverlap(unit, lastUnit, group.axisType, dt)) {\n column.push(unit);\n didAddToExistingColumn = true;\n break;\n }\n }\n if (!didAddToExistingColumn) {\n columns.push([unit]);\n }\n }\n\n const units: UnitWithLayoutParameters<T>[] = columns.flatMap(\n (column, columnIndex) =>\n column.map((unit) => {\n return {\n ...unit,\n layout: {\n column: columnIndex,\n nColumns: 1,\n totalColumns: columns.length,\n unitGroup: group,\n },\n };\n }),\n );\n\n return units.toSorted(sortByAge);\n}\n\nexport function preprocessUnits<T extends UnitLong = UnitLong>(\n section: SectionInfo<T>,\n axisType: ColumnAxisType = ColumnAxisType.AGE,\n): ExtUnit[] {\n /** Preprocess units to add overlapping units and columns. */\n let units = section.units;\n\n let tolerance = 0.001; // 1 kyr tolerance for age columns\n if (axisType != ColumnAxisType.AGE) {\n tolerance = 0.01; // 1cm tolerance for height/depth columns\n }\n\n const unitGroups = groupUnitsByMutualOverlap(units, tolerance, axisType);\n\n const divisions: any[] = [];\n // Serialize all groups' units to a single array\n for (const group of unitGroups) {\n divisions.push(...group.getUnits());\n }\n\n return divisions.map((d) =>\n enhanceUnitWithClippingPosition(section, d, axisType),\n );\n}\n\nexport function enhanceUnitWithClippingPosition(section, d, axisType) {\n const [b_pos, t_pos] = getUnitHeightRange(d, axisType);\n if (axisType == ColumnAxisType.AGE) {\n if (b_pos > section.b_age) {\n d.b_clip_pos = section.b_age;\n }\n if (t_pos < section.t_age) {\n d.t_clip_pos = section.t_age;\n }\n }\n if (axisType == ColumnAxisType.DEPTH) {\n if (b_pos > section.b_pos) {\n d.b_clip_pos = section.b_pos;\n }\n if (t_pos < section.t_pos) {\n d.t_clip_pos = section.t_pos;\n }\n }\n return d;\n}\n\nexport function groupUnitsIntoSectionsBySectionID<T extends UnitLong>(\n units: T[],\n axisType: ColumnAxisType = ColumnAxisType.AGE,\n): SectionInfo<T>[] {\n /** Group units into sections by section_id.\n * This works for large-scale Macrostrat columns, where units are grouped by section_id.\n * */\n let groups = Array.from(group(units, (d) => d.section_id));\n const unitComparator = createUnitSorter(axisType);\n\n const groups1 = groups.map(([section_id, sectionUnits]) => {\n const [b_age, t_age] = getSectionAgeRange(sectionUnits);\n const [b_pos, t_pos] = getSectionPosRange(sectionUnits, axisType);\n\n // sort units by position\n sectionUnits.sort(unitComparator);\n return { section_id, t_age, b_age, b_pos, t_pos, units: sectionUnits };\n });\n // Sort sections by increasing top age, then increasing bottom age.\n // Sections have no relative ordinal position other than age...\n const compareSections = createUnitSorter(axisType) as (\n a: StratigraphicPackage,\n b: StratigraphicPackage,\n ) => number;\n groups1.sort(compareSections);\n return groups1;\n}\n\ninterface WorkingSection {\n units: UnitLong[];\n // Position or age\n heightRange: [number, number];\n}\n\nexport function groupUnitsIntoSectionsByOverlap<T extends BaseUnit>(\n units: T[],\n axisType: ColumnAxisType = ColumnAxisType.AGE,\n tolerance: number = dt,\n): SectionInfo<T>[] {\n /** Group units into sections by overlap.\n * This creates \"synthetic\" sections that correspond to packages bound by scale gaps.\n * This is most useful in the height and depth domains, where gaps (e.g., missing core) are\n * common.\n * */\n // Start with each unit as its own \"section\", and progressively merge...\n const sectionList: WorkingSection[] = [];\n\n const initialSections: WorkingSection[] = units.map((unit) => {\n return {\n units: [unit],\n heightRange: getUnitHeightRange(unit, axisType),\n };\n });\n\n const isOverlapping = (a: WorkingSection, b: WorkingSection) => {\n const res = compareAgeRanges(a.heightRange, b.heightRange, tolerance);\n return res !== AgeRangeRelationship.Disjoint;\n };\n\n const mergeSections = (a: WorkingSection, b: WorkingSection) => {\n return {\n units: [...a.units, ...b.units],\n heightRange: mergeAgeRanges(\n [a.heightRange, b.heightRange],\n MergeMode.Outer,\n ),\n };\n };\n\n // Merge overlapping sections progressively until no more merges are possible\n let finalSectionList = initialSections;\n\n while (true) {\n let merged = false;\n const nextSections: WorkingSection[] = [];\n\n for (const section of finalSectionList) {\n if (nextSections.length === 0) {\n nextSections.push(section);\n } else {\n const lastSection = nextSections[nextSections.length - 1];\n if (isOverlapping(section, lastSection)) {\n // Merge with the last section\n nextSections[nextSections.length - 1] = mergeSections(\n lastSection,\n section,\n );\n merged = true;\n } else {\n nextSections.push(section);\n }\n }\n }\n\n finalSectionList = nextSections;\n\n // Stop when no more merges occurred in this pass\n if (!merged) {\n break;\n }\n }\n\n return finalSectionList.map((section, i) => {\n const [b_age, t_age] = getSectionAgeRange(section.units);\n const [b_pos, t_pos] = getSectionPosRange(section.units, axisType);\n return {\n // Negative section IDs are used to indicate that these are synthetic sections\n section_id: -i,\n t_age,\n b_age,\n t_pos,\n b_pos,\n units: section.units as T[],\n };\n });\n}\n\nexport function getSectionPosRange(\n units: BaseUnit[],\n axisType: ColumnAxisType,\n): [number, number] {\n /** Get the overall position range of a set of units. */\n const t_positions = units.map((d) => {\n switch (axisType) {\n case ColumnAxisType.AGE:\n return d.t_age;\n case ColumnAxisType.DEPTH:\n case ColumnAxisType.HEIGHT:\n case ColumnAxisType.ORDINAL:\n return d.t_pos;\n default:\n throw new Error(`Unknown axis type: ${axisType}`);\n }\n });\n const b_positions = units.map((d) => {\n switch (axisType) {\n case ColumnAxisType.AGE:\n return d.b_age;\n case ColumnAxisType.DEPTH:\n case ColumnAxisType.HEIGHT:\n case ColumnAxisType.ORDINAL:\n return d.b_pos;\n default:\n throw new Error(`Unknown axis type: ${axisType}`);\n }\n });\n if (axisType == ColumnAxisType.AGE || axisType == ColumnAxisType.DEPTH) {\n return [Math.max(...b_positions), Math.min(...t_positions)];\n } else {\n return [Math.min(...b_positions), Math.max(...t_positions)];\n }\n}\n\nexport function getSectionAgeRange(units: BaseUnit[]): [number, number] {\n /** Get the overall age range of a set of units. */\n return getSectionPosRange(units, ColumnAxisType.AGE);\n}\n\nexport function mergeOverlappingSections<T extends UnitLong>(\n sections: SectionInfo<T>[],\n): SectionInfo<T>[] {\n /** Columns can have sections that overlap in time. Here, we merge overlapping\n * sections into a single section to correctly render gap-bound packages.\n */\n const [firstSection, ...rest] = sections;\n const newSections = [firstSection];\n for (const section of rest) {\n const lastSection = newSections[newSections.length - 1];\n if (\n lastSection.b_age < section.t_age ||\n lastSection.t_age > section.b_age\n ) {\n // No overlap, add the section as normal\n newSections.push(section);\n continue;\n }\n\n // Overlap, merge the sections\n lastSection.section_id = [\n ...ensureArray(lastSection.section_id),\n ...ensureArray(section.section_id),\n ];\n lastSection.units.push(...section.units);\n lastSection.b_age = Math.max(lastSection.b_age, section.b_age);\n lastSection.t_age = Math.min(lastSection.t_age, section.t_age);\n }\n return newSections;\n}\n\nexport function preprocessSectionUnit(unit: UnitLong): UnitLong {\n /** Preprocess a single unit for a \"section\" column type.\n * This mostly handles vagaries of eODP-style columns.\n * */\n\n let b_pos = unit.b_pos;\n let t_pos = unit.t_pos;\n\n let unit_name = unit.unit_name;\n\n // eODP columns sometimes have overlapping core sections, which are encoded in the name field\n // Match eODP section names\n const match = unit.unit_name.match(/^(\\d+(\\.\\d+)?)-(\\d+(\\.\\d+)?): (.+)/);\n\n if (match) {\n // These values should already be set if we've used the show_positions flag\n t_pos ??= ensureRealFloat(match[1]);\n b_pos ??= ensureRealFloat(match[3]);\n unit_name = match[5];\n }\n\n return {\n ...unit,\n b_pos: ensureRealFloat(b_pos),\n t_pos: ensureRealFloat(t_pos),\n unit_name,\n };\n}\n"],"names":["group"],"mappings":";;;;AAkBA,MAAM,KAAK;AAsBX,MAAM,UAA8D;AAAA,EAClE;AAAA,EACA;AAAA,EAEA,YAAY,OAAY,WAA2B,eAAe,KAAK;AACrE,SAAK,QAAQ;AACb,SAAK,WAAW;AAAA,EAClB;AAAA,EAEA,IAAI,QAAgB;AAClB,WAAO,KAAK,IAAI,GAAG,KAAK,MAAM,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC;AAAA,EACnD;AAAA,EAEA,IAAI,QAAgB;AAClB,WAAO,KAAK,IAAI,GAAG,KAAK,MAAM,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC;AAAA,EACnD;AAAA,EAEA,WAA0C;AACxC,WAAO,2CAA2C,IAAI;AAAA,EACxD;AACF;AAEA,SAAS,0BACP,OACA,YAAoB,IACpB,WAA2B,eAAe,KAC1B;AAGhB,QAAM,WAAW,gCAAgC,OAAO,UAAU,SAAS;AAE3E,SAAO,SAAS,IAAI,CAAC,MAAM;AACzB,WAAO,IAAI,UAAU,EAAE,OAAO,QAAQ;AAAA,EACxC,CAAC;AACH;AAEA,MAAM,YAAY,iBAAiB,eAAe,GAAG;AAErD,SAAS,2CACPA,QAC+B;AAO/B,QAAM,cAAc,CAAC,GAAGA,OAAM,KAAK,EAAE,KAAK,iBAAiBA,OAAM,QAAQ,CAAC;AAE1E,QAAM,UAAiB,CAAA;AAIvB,aAAW,QAAQ,aAAa;AAI9B,UAAM,UAAU,KAAK,aAAa;AAClC,QAAI,WAAW,MAAM;AACnB,cAAQ,OAAO,MAAM,CAAA;AACrB,cAAQ,OAAO,EAAE,KAAK,IAAI;AAC1B;AAAA,IACF;AACA,QAA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,KAAK,UAAU,MAAM,oCAAoC;AAEvE,MAAI,OAAO;AAET,cAAU,gBAAgB,MAAM,CAAC,CAAC;AAClC,cAAU,gBAAgB,MAAM,CAAC,CAAC;AAClC,gBAAY,MAAM,CAAC;AAAA,EACrB;AAEA,SAAO;AAAA,IACL,GAAG;AAAA,IACH,OAAO,gBAAgB,KAAK;AAAA,IAC5B,OAAO,gBAAgB,KAAK;AAAA,IAC5B;AAAA,EAAA;AAEJ;"}
1
+ {"version":3,"file":"helpers.js","sources":["../../src/prepare-units/helpers.ts"],"sourcesContent":["import type { BaseUnit, UnitLong } from \"@macrostrat/api-types\";\nimport { group } from \"d3-array\";\nimport { ColumnAxisType } from \"@macrostrat/column-components\";\nimport {\n createUnitSorter,\n ensureArray,\n ensureRealFloat,\n getUnitHeightRange,\n unitsOverlap,\n} from \"./utils\";\nimport {\n AgeRangeRelationship,\n compareAgeRanges,\n mergeAgeRanges,\n MergeMode,\n} from \"@macrostrat/stratigraphy-utils\";\nimport type { ExtUnit, SectionInfo, StratigraphicPackage } from \"./types\";\n\nconst dt = 0.001;\n\nexport type UnitWithLayoutParameters<T extends BaseUnit> = T & {\n layout: UnitLayoutData<T>;\n};\n\nexport type UnitWithLayoutHints<T extends BaseUnit> = T & {\n layoutHints?: UnitLayoutHints;\n};\n\ninterface UnitLayoutInfo {\n column: number;\n nColumns: number;\n}\n\ntype UnitLayoutHints = Partial<UnitLayoutInfo>;\n\ntype UnitLayoutData<T extends BaseUnit> = UnitLayoutInfo & {\n totalColumns: number;\n unitGroup: UnitGroup<T>;\n};\n\nclass UnitGroup<T extends BaseUnit> implements StratigraphicPackage {\n units: T[];\n axisType: ColumnAxisType;\n\n constructor(units: T[], axisType: ColumnAxisType = ColumnAxisType.AGE) {\n this.units = units;\n this.axisType = axisType;\n }\n\n get t_age(): number {\n return Math.min(...this.units.map((d) => d.t_age));\n }\n\n get b_age(): number {\n return Math.max(...this.units.map((d) => d.b_age));\n }\n\n getUnits(): UnitWithLayoutParameters<T>[] {\n return assignColumnsToUnitsWithinOverlappingGroup(this);\n }\n}\n\nfunction groupUnitsByMutualOverlap<T extends BaseUnit>(\n units: T[],\n tolerance: number = dt,\n axisType: ColumnAxisType = ColumnAxisType.AGE,\n): UnitGroup<T>[] {\n /** Group units within a section that have mutual overlap. */\n\n const sections = groupUnitsIntoSectionsByOverlap(units, axisType, tolerance);\n\n return sections.map((d) => {\n return new UnitGroup(d.units, axisType);\n });\n}\n\nconst sortByAge = createUnitSorter(ColumnAxisType.AGE);\n\nfunction assignColumnsToUnitsWithinOverlappingGroup<T extends BaseUnit>(\n group: UnitGroup<UnitWithLayoutHints<T>>,\n): UnitWithLayoutParameters<T>[] {\n /** A relatively naïve function to assign columns to units within a mutually overlapping group.\n * This gets the number of columns that would be needed to accommodate the units in the group.\n * It then assigns columns to units in the group based on the number of columns needed, with\n * lower units further to the left.\n */\n\n const sortedUnits = [...group.units].sort(createUnitSorter(group.axisType));\n\n const columns: T[][] = [];\n\n let nColumns = 1;\n\n for (const unit of sortedUnits) {\n let startIndex = 0;\n let endIndex = 0;\n // Find a column that is not already occupied by an overlapping unit\n const colHint = unit.layoutHints?.column;\n if (colHint != null) {\n columns[colHint] ??= [];\n columns[colHint].push(unit);\n continue;\n }\n let didAddToExistingColumn = false;\n\n for (const column of columns) {\n const lastUnit = column[column.length - 1];\n if (!unitsOverlap(unit, lastUnit, group.axisType, dt)) {\n column.push(unit);\n didAddToExistingColumn = true;\n break;\n }\n }\n if (!didAddToExistingColumn) {\n columns.push([unit]);\n }\n }\n\n const units: UnitWithLayoutParameters<T>[] = columns.flatMap(\n (column, columnIndex) =>\n column.map((unit) => {\n return {\n ...unit,\n layout: {\n column: columnIndex,\n nColumns: 1,\n totalColumns: columns.length,\n unitGroup: group,\n },\n };\n }),\n );\n\n return units.toSorted(sortByAge);\n}\n\nexport function preprocessUnits<T extends UnitLong = UnitLong>(\n section: SectionInfo<T>,\n axisType: ColumnAxisType = ColumnAxisType.AGE,\n): ExtUnit[] {\n /** Preprocess units to add overlapping units and columns. */\n let units = section.units;\n\n let tolerance = 0.001; // 1 kyr tolerance for age columns\n if (axisType != ColumnAxisType.AGE) {\n tolerance = 0.01; // 1cm tolerance for height/depth columns\n }\n\n const unitGroups = groupUnitsByMutualOverlap(units, tolerance, axisType);\n\n const divisions: any[] = [];\n // Serialize all groups' units to a single array\n for (const group of unitGroups) {\n divisions.push(...group.getUnits());\n }\n\n return divisions.map((d) =>\n enhanceUnitWithClippingPosition(section, d, axisType),\n );\n}\n\nexport function enhanceUnitWithClippingPosition(section, d, axisType) {\n const [b_pos, t_pos] = getUnitHeightRange(d, axisType);\n if (axisType == ColumnAxisType.AGE) {\n if (b_pos > section.b_age) {\n d.b_clip_pos = section.b_age;\n }\n if (t_pos < section.t_age) {\n d.t_clip_pos = section.t_age;\n }\n }\n if (axisType == ColumnAxisType.DEPTH) {\n if (b_pos > section.b_pos) {\n d.b_clip_pos = section.b_pos;\n }\n if (t_pos < section.t_pos) {\n d.t_clip_pos = section.t_pos;\n }\n }\n return d;\n}\n\nexport function groupUnitsIntoSectionsBySectionID<T extends UnitLong>(\n units: T[],\n axisType: ColumnAxisType = ColumnAxisType.AGE,\n): SectionInfo<T>[] {\n /** Group units into sections by section_id.\n * This works for large-scale Macrostrat columns, where units are grouped by section_id.\n * */\n let groups = Array.from(group(units, (d) => d.section_id));\n const unitComparator = createUnitSorter(axisType);\n\n const groups1 = groups.map(([section_id, sectionUnits]) => {\n const [b_age, t_age] = getSectionAgeRange(sectionUnits);\n const [b_pos, t_pos] = getSectionPosRange(sectionUnits, axisType);\n\n // sort units by position\n sectionUnits.sort(unitComparator);\n return { section_id, t_age, b_age, b_pos, t_pos, units: sectionUnits };\n });\n // Sort sections by increasing top age, then increasing bottom age.\n // Sections have no relative ordinal position other than age...\n const compareSections = createUnitSorter(axisType) as (\n a: StratigraphicPackage,\n b: StratigraphicPackage,\n ) => number;\n groups1.sort(compareSections);\n return groups1;\n}\n\ninterface WorkingSection {\n units: UnitLong[];\n // Position or age\n heightRange: [number, number];\n}\n\nexport function groupUnitsIntoSectionsByOverlap<T extends BaseUnit>(\n units: T[],\n axisType: ColumnAxisType = ColumnAxisType.AGE,\n tolerance: number = dt,\n): SectionInfo<T>[] {\n /** Group units into sections by overlap.\n * This creates \"synthetic\" sections that correspond to packages bound by scale gaps.\n * This is most useful in the height and depth domains, where gaps (e.g., missing core) are\n * common.\n * */\n // Start with each unit as its own \"section\", and progressively merge...\n const sectionList: WorkingSection[] = [];\n\n const initialSections: WorkingSection[] = units.map((unit) => {\n return {\n units: [unit],\n heightRange: getUnitHeightRange(unit, axisType),\n };\n });\n\n const isOverlapping = (a: WorkingSection, b: WorkingSection) => {\n const res = compareAgeRanges(a.heightRange, b.heightRange, tolerance);\n return res !== AgeRangeRelationship.Disjoint;\n };\n\n const mergeSections = (a: WorkingSection, b: WorkingSection) => {\n return {\n units: [...a.units, ...b.units],\n heightRange: mergeAgeRanges(\n [a.heightRange, b.heightRange],\n MergeMode.Outer,\n ),\n };\n };\n\n // Merge overlapping sections progressively until no more merges are possible\n let finalSectionList = initialSections;\n\n while (true) {\n let merged = false;\n const nextSections: WorkingSection[] = [];\n\n for (const section of finalSectionList) {\n if (nextSections.length === 0) {\n nextSections.push(section);\n } else {\n const lastSection = nextSections[nextSections.length - 1];\n if (isOverlapping(section, lastSection)) {\n // Merge with the last section\n nextSections[nextSections.length - 1] = mergeSections(\n lastSection,\n section,\n );\n merged = true;\n } else {\n nextSections.push(section);\n }\n }\n }\n\n finalSectionList = nextSections;\n\n // Stop when no more merges occurred in this pass\n if (!merged) {\n break;\n }\n }\n\n const s1 = finalSectionList.map((section, i) => {\n const [b_age, t_age] = getSectionAgeRange(section.units);\n const [b_pos, t_pos] = getSectionPosRange(section.units, axisType);\n return {\n // Negative section IDs are used to indicate that these are synthetic sections\n section_id: -i,\n t_age,\n b_age,\n t_pos,\n b_pos,\n units: section.units as T[],\n };\n });\n\n return sortUnits(s1, axisType);\n}\n\nexport function getSectionPosRange(\n units: BaseUnit[],\n axisType: ColumnAxisType,\n): [number, number] {\n /** Get the overall position range of a set of units. */\n const t_positions = units.map((d) => {\n switch (axisType) {\n case ColumnAxisType.AGE:\n return d.t_age;\n case ColumnAxisType.DEPTH:\n case ColumnAxisType.HEIGHT:\n case ColumnAxisType.ORDINAL:\n return d.t_pos;\n default:\n throw new Error(`Unknown axis type: ${axisType}`);\n }\n });\n const b_positions = units.map((d) => {\n switch (axisType) {\n case ColumnAxisType.AGE:\n return d.b_age;\n case ColumnAxisType.DEPTH:\n case ColumnAxisType.HEIGHT:\n case ColumnAxisType.ORDINAL:\n return d.b_pos;\n default:\n throw new Error(`Unknown axis type: ${axisType}`);\n }\n });\n if (axisType == ColumnAxisType.AGE || axisType == ColumnAxisType.DEPTH) {\n return [Math.max(...b_positions), Math.min(...t_positions)];\n } else {\n return [Math.min(...b_positions), Math.max(...t_positions)];\n }\n}\n\nexport function getSectionAgeRange(units: BaseUnit[]): [number, number] {\n /** Get the overall age range of a set of units. */\n return getSectionPosRange(units, ColumnAxisType.AGE);\n}\n\nfunction forEachSection(fn, sections, ...args) {\n return sections.map((section) => {\n return {\n ...section,\n units: fn(section.units, ...args),\n };\n });\n}\n\nfunction sortUnits(units: BaseUnit[], axisType: ColumnAxisType) {\n return units.sort((a, b) => {\n if (\n axisType === ColumnAxisType.HEIGHT &&\n b.t_pos !== undefined &&\n a.t_pos !== undefined\n ) {\n return b.t_pos - a.t_pos;\n }\n if (\n axisType === ColumnAxisType.DEPTH &&\n b.t_pos !== undefined &&\n a.t_pos !== undefined\n ) {\n return a.t_pos - b.t_pos;\n }\n if (axisType === ColumnAxisType.AGE) {\n return a.t_age - b.t_age;\n }\n return 0;\n });\n}\n\nexport function mergeOverlappingSections<T extends UnitLong>(\n sections: SectionInfo<T>[],\n): SectionInfo<T>[] {\n /** Columns can have sections that overlap in time. Here, we merge overlapping\n * sections into a single section to correctly render gap-bound packages.\n */\n const [firstSection, ...rest] = sections;\n const newSections = [firstSection];\n for (const section of rest) {\n const lastSection = newSections[newSections.length - 1];\n if (\n lastSection.b_age < section.t_age ||\n lastSection.t_age > section.b_age\n ) {\n // No overlap, add the section as normal\n newSections.push(section);\n continue;\n }\n\n // Overlap, merge the sections\n lastSection.section_id = [\n ...ensureArray(lastSection.section_id),\n ...ensureArray(section.section_id),\n ];\n lastSection.units.push(...section.units);\n lastSection.b_age = Math.max(lastSection.b_age, section.b_age);\n lastSection.t_age = Math.min(lastSection.t_age, section.t_age);\n }\n return newSections;\n}\n\nexport function preprocessSectionUnit(unit: UnitLong): UnitLong {\n /** Preprocess a single unit for a \"section\" column type.\n * This mostly handles vagaries of eODP-style columns.\n * */\n\n let b_pos = unit.b_pos;\n let t_pos = unit.t_pos;\n\n let unit_name = unit.unit_name;\n\n // eODP columns sometimes have overlapping core sections, which are encoded in the name field\n // Match eODP section names\n const match = unit.unit_name.match(/^(\\d+(\\.\\d+)?)-(\\d+(\\.\\d+)?): (.+)/);\n\n if (match) {\n // These values should already be set if we've used the show_positions flag\n t_pos ??= ensureRealFloat(match[1]);\n b_pos ??= ensureRealFloat(match[3]);\n unit_name = match[5];\n }\n\n return {\n ...unit,\n b_pos: ensureRealFloat(b_pos),\n t_pos: ensureRealFloat(t_pos),\n unit_name,\n };\n}\n"],"names":["group"],"mappings":";;;;AAkBA,MAAM,KAAK;AAsBX,MAAM,UAA8D;AAAA,EAClE;AAAA,EACA;AAAA,EAEA,YAAY,OAAY,WAA2B,eAAe,KAAK;AACrE,SAAK,QAAQ;AACb,SAAK,WAAW;AAAA,EAClB;AAAA,EAEA,IAAI,QAAgB;AAClB,WAAO,KAAK,IAAI,GAAG,KAAK,MAAM,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC;AAAA,EACnD;AAAA,EAEA,IAAI,QAAgB;AAClB,WAAO,KAAK,IAAI,GAAG,KAAK,MAAM,IAAI,CAAC,MAAM,EAAE,KAAK,CAAC;AAAA,EACnD;AAAA,EAEA,WAA0C;AACxC,WAAO,2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BAAgB,KAAK;AAAA,IAC5B,OAAO,gBAAgB,KAAK;AAAA,IAC5B;AAAA,EAAA;AAEJ;"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":["../../src/prepare-units/index.ts"],"sourcesContent":["import {\n getSectionAgeRange,\n getSectionPosRange,\n groupUnitsIntoSectionsByOverlap,\n groupUnitsIntoSectionsBySectionID,\n mergeOverlappingSections,\n preprocessSectionUnit,\n preprocessUnits,\n UnitWithLayoutHints,\n} from \"./helpers\";\nimport { ColumnAxisType } from \"@macrostrat/column-components\";\nimport { useMemo } from \"react\";\nimport { UnitLong } from \"@macrostrat/api-types\";\nimport {\n collapseUnconformitiesByPixelHeight,\n computeSectionHeights,\n finalizeSectionHeights,\n padWindowByPixels,\n resolveWindowScales,\n trimSectionsToWindow,\n type CompositeColumnScale,\n} from \"./composite-scale\";\nimport {\n agesOverlap,\n MergeSectionsMode,\n PrepareColumnOptions,\n PreparedColumnData,\n unitsOverlap,\n} from \"./utils\";\nimport { type ColumnHeightScaleOptions, SectionInfo } from \"./types\";\n\nexport * from \"./utils\";\nexport * from \"./types\";\nexport * from \"./density\";\nexport { preprocessUnits };\nexport type { CompositeColumnScale };\n\nexport function usePreparedColumnUnits(\n data: UnitLong[],\n options: PrepareColumnOptions,\n): PreparedColumnData {\n /** This function wraps and memoizes all preparation steps for converting\n * an array of units from the /units route to a form ready for usage.\n */\n return useMemo(() => {\n return prepareColumnUnits(data, options);\n }, [data, ...Object.values(options)]);\n}\n\nexport function prepareColumnUnits(\n units: UnitWithLayoutHints<UnitLong>[],\n options: PrepareColumnOptions,\n): PreparedColumnData {\n /** Prepare units for rendering into Macrostrat columns */\n\n let { t_age, b_age, t_pos, b_pos } = options;\n\n const {\n mergeSections = MergeSectionsMode.OVERLAPPING,\n axisType,\n unconformityHeight,\n collapseSmallUnconformities = false,\n hybridScale,\n scale,\n windowPadding = 0,\n } = options;\n\n let _totalHeight: number | null = null;\n\n if (scale != null) {\n // Set t_age and b_age based on scale domain if not already set\n const domain = scale.domain();\n if (axisType == ColumnAxisType.AGE) {\n if (t_age == null) t_age = Math.min(...domain);\n if (b_age == null) b_age = Math.max(...domain);\n _totalHeight = Math.abs(scale(b_age) - scale(t_age));\n } else {\n if (t_pos == null) t_pos = Math.min(...domain);\n if (b_pos == null) b_pos = Math.max(...domain);\n _totalHeight = Math.abs(scale(b_pos) - scale(t_pos));\n }\n }\n\n /** Age columns lay every section out at its full extent and clip to the\n * window at the end (see below), so that a section abutting the window is\n * sized by its own content rather than by the sliver that survives the clip.\n * Hybrid and externally-supplied scales build their own mapping and can't be\n * re-derived that way, so they keep the original clip-then-lay-out path. */\n const clipBeforeLayout =\n axisType != ColumnAxisType.AGE || hybridScale != null || scale != null;\n\n // Start by ensuring that ages and positions are numbers\n // also set up some values for eODP-style columns\n let units1 = units.map(preprocessSectionUnit);\n\n /** A bound that isn't set doesn't bound anything. Passing `null` for one is\n * the ordinary way to say \"no window\", and comparing against it as though\n * it were an age would throw every unit out. */\n const window = {\n t_age: t_age ?? -Infinity,\n b_age: b_age ?? Infinity,\n t_pos: t_pos ?? -Infinity,\n b_pos: b_pos ?? Infinity,\n };\n const isWindowed =\n axisType == ColumnAxisType.AGE\n ? t_age != null || b_age != null\n : t_pos != null || b_pos != null;\n\n if (clipBeforeLayout && isWindowed) {\n /** Prototype filtering to age range */\n units1 = units1.filter((d) => {\n // Filter units by t_age and b_age, inclusive\n if (axisType == ColumnAxisType.AGE) {\n return agesOverlap(d, window);\n } else {\n return unitsOverlap(d, window as any, axisType);\n }\n });\n }\n\n let mergeMode = mergeSections;\n // if (axisType != ColumnAxisType.AGE) {\n // // For non-age columns, we always merge sections.\n // // This is because the \"groupUnitsIntoSections\" function is not well-defined\n // // for non-age columns.\n // mergeMode = MergeSectionsMode.ALL;\n // }\n\n let sections0: SectionInfo<UnitLong>[];\n if (mergeMode == MergeSectionsMode.ALL) {\n // For the \"merge sections\" mode, we need to create a single section\n const [b_unit_pos, t_unit_pos] = getSectionPosRange(units1, axisType);\n const [b_unit_age, t_unit_age] = getSectionAgeRange(units1);\n sections0 = [\n {\n section_id: 0,\n /**\n * If ages limits are directly specified, use them to define the section bounds.\n * */\n t_pos: t_unit_pos,\n b_pos: b_unit_pos,\n t_age: t_unit_age,\n b_age: b_unit_age,\n units: units1,\n },\n ];\n } else if (axisType == ColumnAxisType.AGE) {\n sections0 = groupUnitsIntoSectionsBySectionID(units1, axisType);\n } else {\n sections0 = groupUnitsIntoSectionsByOverlap(units1, axisType);\n }\n\n // Limit sections to the range specified by t_age/b_age or t_pos/b_pos global options\n for (let section of clipBeforeLayout ? sections0 : []) {\n if (axisType == ColumnAxisType.AGE) {\n section.t_age = Math.max(section.t_age, t_age ?? -Infinity);\n section.b_age = Math.min(section.b_age, b_age ?? Infinity);\n } else if (axisType == ColumnAxisType.DEPTH) {\n section.t_pos = Math.max(section.t_pos, t_pos ?? -Infinity);\n section.b_pos = Math.min(section.b_pos, b_pos ?? Infinity);\n } else if (axisType == ColumnAxisType.HEIGHT) {\n section.t_pos = Math.max(section.t_pos, t_pos ?? -Infinity);\n section.b_pos = Math.min(section.b_pos, b_pos ?? Infinity);\n }\n }\n\n /** Merging overlapping sections really only makes sense for age/height/depth\n * columns. Ordinal columns are numbered by section so merging them\n * results in collisions.\n */\n let sections = sections0;\n if (\n mergeSections == MergeSectionsMode.OVERLAPPING &&\n axisType == ColumnAxisType.AGE\n ) {\n sections = mergeOverlappingSections(sections);\n }\n // Filter out undefined sections just in case\n sections = sections.filter((d) => d != null);\n\n // SCALES\n\n /** The window we've been asked to render. Unit density is derived from what\n * it shows (see `findAverageUnitHeight`), so it has to be known before any\n * section is laid out — but nothing is *clipped* to it until the very end.\n */\n const focalWindow: [number, number] | null = clipBeforeLayout\n ? null\n : [b_age ?? Infinity, t_age ?? -Infinity];\n\n const layoutOptions = { ...options, visibleWindow: focalWindow };\n\n /* Compute pixel scales etc. for sections\n * We need to do this now to determine which unconformities\n * are small enough to collapse.\n */\n let sectionsWithScales = computeSectionHeights(sections, layoutOptions);\n\n if (collapseSmallUnconformities && hybridScale == null) {\n // Collapse small unconformities in pixel height space\n // TODO: this doesn't seem to work properly for non-age columns?\n let threshold = unconformityHeight ?? 30;\n if (typeof collapseSmallUnconformities == \"number\") {\n threshold = collapseSmallUnconformities;\n }\n\n sectionsWithScales = collapseUnconformitiesByPixelHeight(\n sectionsWithScales,\n threshold,\n layoutOptions,\n );\n }\n\n /** Now that every section is laid out at full extent — with its own density\n * and `minSectionHeight` already settled — apply the rendered window. Padding\n * is spent here, against real pixel heights, so `windowPadding` px of an\n * abutting section is exactly that many pixels.\n */\n if (focalWindow != null && (t_age != null || b_age != null)) {\n // Resolve final densities first (a section the window cuts short is\n // stretched to `minSectionHeight`), then spend the padding budget against\n // them, so a margin is the pixels asked for rather than those pixels times\n // whatever stretch its neighbor happened to need.\n const floor =\n layoutOptions.minSectionHeight ?? layoutOptions.targetUnitHeight ?? 0;\n const scales = resolveWindowScales(sectionsWithScales, focalWindow, floor);\n const natural = (section) =>\n scales.get(section) ?? section.scaleInfo.pixelScale;\n\n\n const scaleFor = natural;\n\n const window =\n windowPadding > 0\n ? padWindowByPixels(\n sectionsWithScales,\n focalWindow,\n windowPadding,\n scaleFor,\n )\n : focalWindow;\n\n sectionsWithScales = trimSectionsToWindow(\n sectionsWithScales,\n window,\n scaleFor,\n );\n }\n\n /** Prepare section scale information using groups.\n * Total height is computed from section scales.\n * */\n let { totalHeight, sections: sections2 } = finalizeSectionHeights(\n sectionsWithScales,\n unconformityHeight,\n );\n\n /** For each section, find units that are overlapping.\n * We do this after merging sections so that we can\n * handle cases where there are overlapping units across sections\n * */\n const sectionsOut = sections2.map((section) => {\n return {\n ...section,\n units: preprocessUnits(section, axisType),\n };\n });\n\n /** Reconstitute the units so that they are sorted by section and properly enhanced.\n * This is mostly important so that unit keyboard navigation\n * predictably selects adjacent units.\n */\n const units2 = sectionsOut.reduce((acc, group) => {\n const { units } = group;\n for (const unit of units) {\n acc.push(unit);\n }\n return acc;\n }, []);\n\n return {\n units: units2,\n totalHeight: _totalHeight ?? totalHeight,\n sections: sectionsOut,\n };\n}\n"],"names":["useMemo","MergeSectionsMode","ColumnAxisType","preprocessSectionUnit","agesOverlap","unitsOverlap","getSectionPosRange","getSectionAgeRange","groupUnitsIntoSectionsBySectionID","groupUnitsIntoSectionsByOverlap","mergeOverlappingSections","computeSectionHeights","collapseUnconformitiesByPixelHeight","resolveWindowScales","window","padWindowByPixels","trimSectionsToWindow","finalizeSectionHeights","preprocessUnits","units"],"mappings":";;;;;;;AAqCO,SAAS,uBACd,MACA,SACoB;AAIpB,SAAOA,MAAAA,QAAQ,MAAM;AACnB,WAAO,mBAAmB,MAAM,OAAO;AAAA,EACzC,GAAG,CAAC,MAAM,GAAG,OAAO,OAAO,OAAO,CAAC,CAAC;AACtC;AAEO,SAAS,mBACd,OACA,SACoB;AAGpB,MAAI,EAAE,OAAO,OAAO,OAAO,UAAU;AAErC,QAAM;AAAA,IACJ,gBAAgBC,MAAAA,kBAAkB;AAAA,IAClC;AAAA,IACA;AAAA,IACA,8BAA8B;AAAA,IAC9B;AAAA,IACA;AAAA,IACA,gBAAgB;AAAA,EAAA,IACd;AAEJ,MAAI,eAA8B;AAElC,MAAI,SAAS,MAAM;AAEjB,UAAM,SAAS,MAAM,OAAA;AACrB,QAAI,YAAYC,iBAAAA,eAAe,KAAK;AAClC,UAAI,SAAS,KAAM,SAAQ,KAAK,IAAI,GAAG,MAAM;AAC7C,UAAI,SAAS,KAAM,SAAQ,KAAK,IAAI,GAAG,MAAM;AAC7C,qBAAe,KAAK,IAAI,MAAM,KAAK,IAAI,MAAM,KAAK,CAAC;AAAA,IACrD,OAAO;AACL,UAAI,SAAS,KAAM,SAAQ,KAAK,IAAI,GAAG,MAAM;AAC7C,UAAI,SAAS,KAAM,SAAQ,KAAK,IAAI,GAAG,MAAM;AAC7C,qBAAe,KAAK,IAAI,MAAM,KAAK,IAAI,MAAM,KAAK,CAAC;AAAA,IACrD;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EjB,UAAMC,UACJ,gBAAgB,IACZC,eAAAA;AAAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IAAA,IAEF;AAEN,yBAAqBC,eAAAA;AAAAA,MACnB;AAAA,MACAF;AAAAA,MACA;AAAA,IAAA;AAAA,EAEJ;AAKA,MAAI,EAAE,aAAa,UAAU,UAAA,IAAcG,eAAAA;AAAAA,IACzC;AAAA,IACA;AAAA,EAAA;AAOF,QAAM,cAAc,UAAU,IAAI,CAAC,YAAY;AAC7C,WAAO;AAAA,MACL,GAAG;AAAA,MACH,OAAOC,QAAAA,gBAAgB,SAAS,QAAQ;AAAA,IAAA;AAAA,EAE5C,CAAC;AAMD,QAAM,SAAS,YAAY,OAAO,CAAC,KAAK,UAAU;AAChD,UAAM,EAAE,OAAAC,OAAAA,IAAU;AAClB,eAAW,QAAQA,QAAO;AACxB,UAAI,KAAK,IAAI;AAAA,IACf;AACA,WAAO;AAAA,EACT,GAAG,CAAA,CAAE;AAEL,SAAO;AAAA,IACL,OAAO;AAAA,IACP,aAAa,gBAAgB;AAAA,IAC7B,UAAU;AAAA,EAAA;AAEd;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.cjs","sources":["../../src/prepare-units/index.ts"],"sourcesContent":["import {\n getSectionAgeRange,\n getSectionPosRange,\n groupUnitsIntoSectionsByOverlap,\n groupUnitsIntoSectionsBySectionID,\n mergeOverlappingSections,\n preprocessSectionUnit,\n preprocessUnits,\n UnitWithLayoutHints,\n} from \"./helpers\";\nimport { ColumnAxisType } from \"@macrostrat/column-components\";\nimport { useMemo } from \"react\";\nimport { UnitLong } from \"@macrostrat/api-types\";\nimport {\n collapseUnconformitiesByPixelHeight,\n computeSectionHeights,\n finalizeSectionHeights,\n padWindowByPixels,\n resolveWindowScales,\n trimSectionsToWindow,\n type CompositeColumnScale,\n} from \"./composite-scale\";\nimport {\n agesOverlap,\n MergeSectionsMode,\n PrepareColumnOptions,\n PreparedColumnData,\n unitsOverlap,\n} from \"./utils\";\nimport { type ColumnHeightScaleOptions, SectionInfo } from \"./types\";\n\nexport * from \"./utils\";\nexport * from \"./types\";\nexport * from \"./density\";\nexport { preprocessUnits };\nexport type { CompositeColumnScale };\n\nexport function usePreparedColumnUnits(\n data: UnitLong[],\n options: PrepareColumnOptions,\n): PreparedColumnData {\n /** This function wraps and memoizes all preparation steps for converting\n * an array of units from the /units route to a form ready for usage.\n */\n return useMemo(() => {\n return prepareColumnUnits(data, options);\n }, [data, ...Object.values(options)]);\n}\n\nexport function prepareColumnUnits(\n units: UnitWithLayoutHints<UnitLong>[],\n options: PrepareColumnOptions,\n): PreparedColumnData {\n /** Prepare units for rendering into Macrostrat columns */\n\n let { t_age, b_age, t_pos, b_pos } = options;\n\n const {\n mergeSections = MergeSectionsMode.OVERLAPPING,\n axisType,\n unconformityHeight,\n collapseSmallUnconformities = false,\n hybridScale,\n scale,\n windowPadding = 0,\n } = options;\n\n let _totalHeight: number | null = null;\n\n if (scale != null) {\n // Set t_age and b_age based on scale domain if not already set\n const domain = scale.domain();\n if (axisType == ColumnAxisType.AGE) {\n if (t_age == null) t_age = Math.min(...domain);\n if (b_age == null) b_age = Math.max(...domain);\n _totalHeight = Math.abs(scale(b_age) - scale(t_age));\n } else {\n if (t_pos == null) t_pos = Math.min(...domain);\n if (b_pos == null) b_pos = Math.max(...domain);\n _totalHeight = Math.abs(scale(b_pos) - scale(t_pos));\n }\n }\n\n /** Age columns lay every section out at its full extent and clip to the\n * window at the end (see below), so that a section abutting the window is\n * sized by its own content rather than by the sliver that survives the clip.\n * Hybrid and externally-supplied scales build their own mapping and can't be\n * re-derived that way, so they keep the original clip-then-lay-out path. */\n const clipBeforeLayout =\n axisType != ColumnAxisType.AGE || hybridScale != null || scale != null;\n\n // Start by ensuring that ages and positions are numbers\n // also set up some values for eODP-style columns\n let units1 = units.map(preprocessSectionUnit);\n\n /** A bound that isn't set doesn't bound anything. Passing `null` for one is\n * the ordinary way to say \"no window\", and comparing against it as though\n * it were an age would throw every unit out. */\n const window = {\n t_age: t_age ?? -Infinity,\n b_age: b_age ?? Infinity,\n t_pos: t_pos ?? -Infinity,\n b_pos: b_pos ?? Infinity,\n };\n const isWindowed =\n axisType == ColumnAxisType.AGE\n ? t_age != null || b_age != null\n : t_pos != null || b_pos != null;\n\n if (clipBeforeLayout && isWindowed) {\n /** Prototype filtering to age range */\n units1 = units1.filter((d) => {\n // Filter units by t_age and b_age, inclusive\n if (axisType == ColumnAxisType.AGE) {\n return agesOverlap(d, window);\n } else {\n return unitsOverlap(d, window as any, axisType);\n }\n });\n }\n\n let mergeMode = mergeSections;\n // if (axisType != ColumnAxisType.AGE) {\n // // For non-age columns, we always merge sections.\n // // This is because the \"groupUnitsIntoSections\" function is not well-defined\n // // for non-age columns.\n // mergeMode = MergeSectionsMode.ALL;\n // }\n\n let sections0: SectionInfo<UnitLong>[];\n if (mergeMode == MergeSectionsMode.ALL) {\n // For the \"merge sections\" mode, we need to create a single section\n const [b_unit_pos, t_unit_pos] = getSectionPosRange(units1, axisType);\n const [b_unit_age, t_unit_age] = getSectionAgeRange(units1);\n sections0 = [\n {\n section_id: 0,\n /**\n * If ages limits are directly specified, use them to define the section bounds.\n * */\n t_pos: t_unit_pos,\n b_pos: b_unit_pos,\n t_age: t_unit_age,\n b_age: b_unit_age,\n units: units1,\n },\n ];\n } else if (axisType == ColumnAxisType.AGE) {\n sections0 = groupUnitsIntoSectionsBySectionID(units1, axisType);\n } else {\n sections0 = groupUnitsIntoSectionsByOverlap(units1, axisType);\n }\n\n // Limit sections to the range specified by t_age/b_age or t_pos/b_pos global options\n for (let section of clipBeforeLayout ? sections0 : []) {\n if (axisType == ColumnAxisType.AGE) {\n section.t_age = Math.max(section.t_age, t_age ?? -Infinity);\n section.b_age = Math.min(section.b_age, b_age ?? Infinity);\n } else if (axisType == ColumnAxisType.DEPTH) {\n section.t_pos = Math.max(section.t_pos, t_pos ?? -Infinity);\n section.b_pos = Math.min(section.b_pos, b_pos ?? Infinity);\n } else if (axisType == ColumnAxisType.HEIGHT) {\n section.t_pos = Math.max(section.t_pos, t_pos ?? -Infinity);\n section.b_pos = Math.min(section.b_pos, b_pos ?? Infinity);\n }\n }\n\n /** Merging overlapping sections really only makes sense for age/height/depth\n * columns. Ordinal columns are numbered by section so merging them\n * results in collisions.\n */\n let sections = sections0;\n if (\n mergeSections == MergeSectionsMode.OVERLAPPING &&\n axisType == ColumnAxisType.AGE\n ) {\n sections = mergeOverlappingSections(sections);\n }\n // Filter out undefined sections just in case\n sections = sections.filter((d) => d != null);\n\n // SCALES\n\n /** The window we've been asked to render. Unit density is derived from what\n * it shows (see `findAverageUnitHeight`), so it has to be known before any\n * section is laid out — but nothing is *clipped* to it until the very end.\n */\n const focalWindow: [number, number] | null = clipBeforeLayout\n ? null\n : [b_age ?? Infinity, t_age ?? -Infinity];\n\n const layoutOptions = { ...options, visibleWindow: focalWindow };\n\n /* Compute pixel scales etc. for sections\n * We need to do this now to determine which unconformities\n * are small enough to collapse.\n */\n let sectionsWithScales = computeSectionHeights(sections, layoutOptions);\n\n if (collapseSmallUnconformities && hybridScale == null) {\n // Collapse small unconformities in pixel height space\n // TODO: this doesn't seem to work properly for non-age columns?\n let threshold = unconformityHeight ?? 30;\n if (typeof collapseSmallUnconformities == \"number\") {\n threshold = collapseSmallUnconformities;\n }\n\n sectionsWithScales = collapseUnconformitiesByPixelHeight(\n sectionsWithScales,\n threshold,\n layoutOptions,\n );\n }\n\n /** Now that every section is laid out at full extent — with its own density\n * and `minSectionHeight` already settled — apply the rendered window. Padding\n * is spent here, against real pixel heights, so `windowPadding` px of an\n * abutting section is exactly that many pixels.\n */\n if (focalWindow != null && (t_age != null || b_age != null)) {\n // Resolve final densities first (a section the window cuts short is\n // stretched to `minSectionHeight`), then spend the padding budget against\n // them, so a margin is the pixels asked for rather than those pixels times\n // whatever stretch its neighbor happened to need.\n const floor =\n layoutOptions.minSectionHeight ?? layoutOptions.targetUnitHeight ?? 0;\n const scales = resolveWindowScales(sectionsWithScales, focalWindow, floor);\n const natural = (section) =>\n scales.get(section) ?? section.scaleInfo.pixelScale;\n\n const scaleFor = natural;\n\n const window =\n windowPadding > 0\n ? padWindowByPixels(\n sectionsWithScales,\n focalWindow,\n windowPadding,\n scaleFor,\n )\n : focalWindow;\n\n sectionsWithScales = trimSectionsToWindow(\n sectionsWithScales,\n window,\n scaleFor,\n );\n }\n\n /** Prepare section scale information using groups.\n * Total height is computed from section scales.\n * */\n let { totalHeight, sections: sections2 } = finalizeSectionHeights(\n sectionsWithScales,\n unconformityHeight,\n );\n\n /** For each section, find units that are overlapping.\n * We do this after merging sections so that we can\n * handle cases where there are overlapping units across sections\n * */\n const sectionsOut = sections2.map((section) => {\n return {\n ...section,\n units: preprocessUnits(section, axisType),\n };\n });\n\n /** Reconstitute the units so that they are sorted by section and properly enhanced.\n * This is mostly important so that unit keyboard navigation\n * predictably selects adjacent units.\n */\n const units2 = sectionsOut.reduce((acc, group) => {\n const { units } = group;\n for (const unit of units) {\n acc.push(unit);\n }\n return acc;\n }, []);\n\n return {\n units: units2,\n totalHeight: _totalHeight ?? totalHeight,\n sections: sectionsOut,\n };\n}\n"],"names":["useMemo","MergeSectionsMode","ColumnAxisType","preprocessSectionUnit","agesOverlap","unitsOverlap","getSectionPosRange","getSectionAgeRange","groupUnitsIntoSectionsBySectionID","groupUnitsIntoSectionsByOverlap","mergeOverlappingSections","computeSectionHeights","collapseUnconformitiesByPixelHeight","resolveWindowScales","window","padWindowByPixels","trimSectionsToWindow","finalizeSectionHeights","preprocessUnits","units"],"mappings":";;;;;;;AAqCO,SAAS,uBACd,MACA,SACoB;AAIpB,SAAOA,MAAAA,QAAQ,MAAM;AACnB,WAAO,mBAAmB,MAAM,OAAO;AAAA,EACzC,GAAG,CAAC,MAAM,GAAG,OAAO,OAAO,OAAO,CAAC,CAAC;AACtC;AAEO,SAAS,mBACd,OACA,SACoB;AAGpB,MAAI,EAAE,OAAO,OAAO,OAAO,UAAU;AAErC,QAAM;AAAA,IACJ,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AAEL,SAAO;AAAA,IACL,OAAO;AAAA,IACP,aAAa,gBAAgB;AAAA,IAC7B,UAAU;AAAA,EAAA;AAEd;;;;;;;;;;;;"}
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../../src/prepare-units/index.ts"],"sourcesContent":["import {\n getSectionAgeRange,\n getSectionPosRange,\n groupUnitsIntoSectionsByOverlap,\n groupUnitsIntoSectionsBySectionID,\n mergeOverlappingSections,\n preprocessSectionUnit,\n preprocessUnits,\n UnitWithLayoutHints,\n} from \"./helpers\";\nimport { ColumnAxisType } from \"@macrostrat/column-components\";\nimport { useMemo } from \"react\";\nimport { UnitLong } from \"@macrostrat/api-types\";\nimport {\n collapseUnconformitiesByPixelHeight,\n computeSectionHeights,\n finalizeSectionHeights,\n padWindowByPixels,\n resolveWindowScales,\n trimSectionsToWindow,\n type CompositeColumnScale,\n} from \"./composite-scale\";\nimport {\n agesOverlap,\n MergeSectionsMode,\n PrepareColumnOptions,\n PreparedColumnData,\n unitsOverlap,\n} from \"./utils\";\nimport { type ColumnHeightScaleOptions, SectionInfo } from \"./types\";\n\nexport * from \"./utils\";\nexport * from \"./types\";\nexport * from \"./density\";\nexport { preprocessUnits };\nexport type { CompositeColumnScale };\n\nexport function usePreparedColumnUnits(\n data: UnitLong[],\n options: PrepareColumnOptions,\n): PreparedColumnData {\n /** This function wraps and memoizes all preparation steps for converting\n * an array of units from the /units route to a form ready for usage.\n */\n return useMemo(() => {\n return prepareColumnUnits(data, options);\n }, [data, ...Object.values(options)]);\n}\n\nexport function prepareColumnUnits(\n units: UnitWithLayoutHints<UnitLong>[],\n options: PrepareColumnOptions,\n): PreparedColumnData {\n /** Prepare units for rendering into Macrostrat columns */\n\n let { t_age, b_age, t_pos, b_pos } = options;\n\n const {\n mergeSections = MergeSectionsMode.OVERLAPPING,\n axisType,\n unconformityHeight,\n collapseSmallUnconformities = false,\n hybridScale,\n scale,\n windowPadding = 0,\n } = options;\n\n let _totalHeight: number | null = null;\n\n if (scale != null) {\n // Set t_age and b_age based on scale domain if not already set\n const domain = scale.domain();\n if (axisType == ColumnAxisType.AGE) {\n if (t_age == null) t_age = Math.min(...domain);\n if (b_age == null) b_age = Math.max(...domain);\n _totalHeight = Math.abs(scale(b_age) - scale(t_age));\n } else {\n if (t_pos == null) t_pos = Math.min(...domain);\n if (b_pos == null) b_pos = Math.max(...domain);\n _totalHeight = Math.abs(scale(b_pos) - scale(t_pos));\n }\n }\n\n /** Age columns lay every section out at its full extent and clip to the\n * window at the end (see below), so that a section abutting the window is\n * sized by its own content rather than by the sliver that survives the clip.\n * Hybrid and externally-supplied scales build their own mapping and can't be\n * re-derived that way, so they keep the original clip-then-lay-out path. */\n const clipBeforeLayout =\n axisType != ColumnAxisType.AGE || hybridScale != null || scale != null;\n\n // Start by ensuring that ages and positions are numbers\n // also set up some values for eODP-style columns\n let units1 = units.map(preprocessSectionUnit);\n\n /** A bound that isn't set doesn't bound anything. Passing `null` for one is\n * the ordinary way to say \"no window\", and comparing against it as though\n * it were an age would throw every unit out. */\n const window = {\n t_age: t_age ?? -Infinity,\n b_age: b_age ?? Infinity,\n t_pos: t_pos ?? -Infinity,\n b_pos: b_pos ?? Infinity,\n };\n const isWindowed =\n axisType == ColumnAxisType.AGE\n ? t_age != null || b_age != null\n : t_pos != null || b_pos != null;\n\n if (clipBeforeLayout && isWindowed) {\n /** Prototype filtering to age range */\n units1 = units1.filter((d) => {\n // Filter units by t_age and b_age, inclusive\n if (axisType == ColumnAxisType.AGE) {\n return agesOverlap(d, window);\n } else {\n return unitsOverlap(d, window as any, axisType);\n }\n });\n }\n\n let mergeMode = mergeSections;\n // if (axisType != ColumnAxisType.AGE) {\n // // For non-age columns, we always merge sections.\n // // This is because the \"groupUnitsIntoSections\" function is not well-defined\n // // for non-age columns.\n // mergeMode = MergeSectionsMode.ALL;\n // }\n\n let sections0: SectionInfo<UnitLong>[];\n if (mergeMode == MergeSectionsMode.ALL) {\n // For the \"merge sections\" mode, we need to create a single section\n const [b_unit_pos, t_unit_pos] = getSectionPosRange(units1, axisType);\n const [b_unit_age, t_unit_age] = getSectionAgeRange(units1);\n sections0 = [\n {\n section_id: 0,\n /**\n * If ages limits are directly specified, use them to define the section bounds.\n * */\n t_pos: t_unit_pos,\n b_pos: b_unit_pos,\n t_age: t_unit_age,\n b_age: b_unit_age,\n units: units1,\n },\n ];\n } else if (axisType == ColumnAxisType.AGE) {\n sections0 = groupUnitsIntoSectionsBySectionID(units1, axisType);\n } else {\n sections0 = groupUnitsIntoSectionsByOverlap(units1, axisType);\n }\n\n // Limit sections to the range specified by t_age/b_age or t_pos/b_pos global options\n for (let section of clipBeforeLayout ? sections0 : []) {\n if (axisType == ColumnAxisType.AGE) {\n section.t_age = Math.max(section.t_age, t_age ?? -Infinity);\n section.b_age = Math.min(section.b_age, b_age ?? Infinity);\n } else if (axisType == ColumnAxisType.DEPTH) {\n section.t_pos = Math.max(section.t_pos, t_pos ?? -Infinity);\n section.b_pos = Math.min(section.b_pos, b_pos ?? Infinity);\n } else if (axisType == ColumnAxisType.HEIGHT) {\n section.t_pos = Math.max(section.t_pos, t_pos ?? -Infinity);\n section.b_pos = Math.min(section.b_pos, b_pos ?? Infinity);\n }\n }\n\n /** Merging overlapping sections really only makes sense for age/height/depth\n * columns. Ordinal columns are numbered by section so merging them\n * results in collisions.\n */\n let sections = sections0;\n if (\n mergeSections == MergeSectionsMode.OVERLAPPING &&\n axisType == ColumnAxisType.AGE\n ) {\n sections = mergeOverlappingSections(sections);\n }\n // Filter out undefined sections just in case\n sections = sections.filter((d) => d != null);\n\n // SCALES\n\n /** The window we've been asked to render. Unit density is derived from what\n * it shows (see `findAverageUnitHeight`), so it has to be known before any\n * section is laid out — but nothing is *clipped* to it until the very end.\n */\n const focalWindow: [number, number] | null = clipBeforeLayout\n ? null\n : [b_age ?? Infinity, t_age ?? -Infinity];\n\n const layoutOptions = { ...options, visibleWindow: focalWindow };\n\n /* Compute pixel scales etc. for sections\n * We need to do this now to determine which unconformities\n * are small enough to collapse.\n */\n let sectionsWithScales = computeSectionHeights(sections, layoutOptions);\n\n if (collapseSmallUnconformities && hybridScale == null) {\n // Collapse small unconformities in pixel height space\n // TODO: this doesn't seem to work properly for non-age columns?\n let threshold = unconformityHeight ?? 30;\n if (typeof collapseSmallUnconformities == \"number\") {\n threshold = collapseSmallUnconformities;\n }\n\n sectionsWithScales = collapseUnconformitiesByPixelHeight(\n sectionsWithScales,\n threshold,\n layoutOptions,\n );\n }\n\n /** Now that every section is laid out at full extent — with its own density\n * and `minSectionHeight` already settled — apply the rendered window. Padding\n * is spent here, against real pixel heights, so `windowPadding` px of an\n * abutting section is exactly that many pixels.\n */\n if (focalWindow != null && (t_age != null || b_age != null)) {\n // Resolve final densities first (a section the window cuts short is\n // stretched to `minSectionHeight`), then spend the padding budget against\n // them, so a margin is the pixels asked for rather than those pixels times\n // whatever stretch its neighbor happened to need.\n const floor =\n layoutOptions.minSectionHeight ?? layoutOptions.targetUnitHeight ?? 0;\n const scales = resolveWindowScales(sectionsWithScales, focalWindow, floor);\n const natural = (section) =>\n scales.get(section) ?? section.scaleInfo.pixelScale;\n\n\n const scaleFor = natural;\n\n const window =\n windowPadding > 0\n ? padWindowByPixels(\n sectionsWithScales,\n focalWindow,\n windowPadding,\n scaleFor,\n )\n : focalWindow;\n\n sectionsWithScales = trimSectionsToWindow(\n sectionsWithScales,\n window,\n scaleFor,\n );\n }\n\n /** Prepare section scale information using groups.\n * Total height is computed from section scales.\n * */\n let { totalHeight, sections: sections2 } = finalizeSectionHeights(\n sectionsWithScales,\n unconformityHeight,\n );\n\n /** For each section, find units that are overlapping.\n * We do this after merging sections so that we can\n * handle cases where there are overlapping units across sections\n * */\n const sectionsOut = sections2.map((section) => {\n return {\n ...section,\n units: preprocessUnits(section, axisType),\n };\n });\n\n /** Reconstitute the units so that they are sorted by section and properly enhanced.\n * This is mostly important so that unit keyboard navigation\n * predictably selects adjacent units.\n */\n const units2 = sectionsOut.reduce((acc, group) => {\n const { units } = group;\n for (const unit of units) {\n acc.push(unit);\n }\n return acc;\n }, []);\n\n return {\n units: units2,\n totalHeight: _totalHeight ?? totalHeight,\n sections: sectionsOut,\n };\n}\n"],"names":["window","units"],"mappings":";;;;;;AAqCO,SAAS,uBACd,MACA,SACoB;AAIpB,SAAO,QAAQ,MAAM;AACnB,WAAO,mBAAmB,MAAM,OAAO;AAAA,EACzC,GAAG,CAAC,MAAM,GAAG,OAAO,OAAO,OAAO,CAAC,CAAC;AACtC;AAEO,SAAS,mBACd,OACA,SACoB;AAGpB,MAAI,EAAE,OAAO,OAAO,OAAO,UAAU;AAErC,QAAM;AAAA,IACJ,gBAAgB,kBAAkB;AAAA,IAClC;AAAA,IACA;AAAA,IACA,8BAA8B;AAAA,IAC9B;AAAA,IACA;AAAA,IACA,gBAAgB;AAAA,EAAA,IACd;AAEJ,MAAI,eAA8B;AAElC,MAAI,SAAS,MAAM;AAEjB,UAAM,SAAS,MAAM,OAAA;AACrB,QAAI,YAAY,eAAe,KAAK;AAClC,UAAI,SAAS,KAAM,SAAQ,KAAK,IAAI,GAAG,MAAM;AAC7C,UAAI,SAAS,KAAM,SAAQ,KAAK,IAAI,GAAG,MAAM;AAC7C,qBAAe,KAAK,IAAI,MAAM,KAAK,IAAI,MAAM,KAAK,CAAC;AAAA,IACrD,OAAO;AACL,UAAI,SAAS,KAAM,SAAQ,KAAK,IAAI,GAAG,MAAM;AAC7C,UAAI,SAAS,KAAM,SAAQ,KAAK,IAAI,GAAG,MAAM;AAC7C,qBAAe,KAAK,IAAI,MAAM,KAAK,IAAI,MAAM,KAAK,CAAC;AAAA,IACrD;AAAA,EACF;AAOA,QAAM,mBACJ,YAAY,eAAe,OAAO,eAAe,QAAQ,SAAS;AAIpE,MAAI,SAAS,MAAM,IAAI,qBAAqB;AAK5C,QAAM,SAAS;AAAA,IACb,OAAO,SAAS;AAAA,IAChB,OAAO,SAAS;AAAA,IAChB,OAAO,SAAS;AAAA,IAChB,OAAO,SAAS;AAAA,EAAA;AAEl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OAAO,CAAC,KAAK,UAAU;AAChD,UAAM,EAAE,OAAAC,OAAAA,IAAU;AAClB,eAAW,QAAQA,QAAO;AACxB,UAAI,KAAK,IAAI;AAAA,IACf;AACA,WAAO;AAAA,EACT,GAAG,CAAA,CAAE;AAEL,SAAO;AAAA,IACL,OAAO;AAAA,IACP,aAAa,gBAAgB;AAAA,IAC7B,UAAU;AAAA,EAAA;AAEd;"}
1
+ {"version":3,"file":"index.js","sources":["../../src/prepare-units/index.ts"],"sourcesContent":["import {\n getSectionAgeRange,\n getSectionPosRange,\n groupUnitsIntoSectionsByOverlap,\n groupUnitsIntoSectionsBySectionID,\n mergeOverlappingSections,\n preprocessSectionUnit,\n preprocessUnits,\n UnitWithLayoutHints,\n} from \"./helpers\";\nimport { ColumnAxisType } from \"@macrostrat/column-components\";\nimport { useMemo } from \"react\";\nimport { UnitLong } from \"@macrostrat/api-types\";\nimport {\n collapseUnconformitiesByPixelHeight,\n computeSectionHeights,\n finalizeSectionHeights,\n padWindowByPixels,\n resolveWindowScales,\n trimSectionsToWindow,\n type CompositeColumnScale,\n} from \"./composite-scale\";\nimport {\n agesOverlap,\n MergeSectionsMode,\n PrepareColumnOptions,\n PreparedColumnData,\n unitsOverlap,\n} from \"./utils\";\nimport { type ColumnHeightScaleOptions, SectionInfo } from \"./types\";\n\nexport * from \"./utils\";\nexport * from \"./types\";\nexport * from \"./density\";\nexport { preprocessUnits };\nexport type { CompositeColumnScale };\n\nexport function usePreparedColumnUnits(\n data: UnitLong[],\n options: PrepareColumnOptions,\n): PreparedColumnData {\n /** This function wraps and memoizes all preparation steps for converting\n * an array of units from the /units route to a form ready for usage.\n */\n return useMemo(() => {\n return prepareColumnUnits(data, options);\n }, [data, ...Object.values(options)]);\n}\n\nexport function prepareColumnUnits(\n units: UnitWithLayoutHints<UnitLong>[],\n options: PrepareColumnOptions,\n): PreparedColumnData {\n /** Prepare units for rendering into Macrostrat columns */\n\n let { t_age, b_age, t_pos, b_pos } = options;\n\n const {\n mergeSections = MergeSectionsMode.OVERLAPPING,\n axisType,\n unconformityHeight,\n collapseSmallUnconformities = false,\n hybridScale,\n scale,\n windowPadding = 0,\n } = options;\n\n let _totalHeight: number | null = null;\n\n if (scale != null) {\n // Set t_age and b_age based on scale domain if not already set\n const domain = scale.domain();\n if (axisType == ColumnAxisType.AGE) {\n if (t_age == null) t_age = Math.min(...domain);\n if (b_age == null) b_age = Math.max(...domain);\n _totalHeight = Math.abs(scale(b_age) - scale(t_age));\n } else {\n if (t_pos == null) t_pos = Math.min(...domain);\n if (b_pos == null) b_pos = Math.max(...domain);\n _totalHeight = Math.abs(scale(b_pos) - scale(t_pos));\n }\n }\n\n /** Age columns lay every section out at its full extent and clip to the\n * window at the end (see below), so that a section abutting the window is\n * sized by its own content rather than by the sliver that survives the clip.\n * Hybrid and externally-supplied scales build their own mapping and can't be\n * re-derived that way, so they keep the original clip-then-lay-out path. */\n const clipBeforeLayout =\n axisType != ColumnAxisType.AGE || hybridScale != null || scale != null;\n\n // Start by ensuring that ages and positions are numbers\n // also set up some values for eODP-style columns\n let units1 = units.map(preprocessSectionUnit);\n\n /** A bound that isn't set doesn't bound anything. Passing `null` for one is\n * the ordinary way to say \"no window\", and comparing against it as though\n * it were an age would throw every unit out. */\n const window = {\n t_age: t_age ?? -Infinity,\n b_age: b_age ?? Infinity,\n t_pos: t_pos ?? -Infinity,\n b_pos: b_pos ?? Infinity,\n };\n const isWindowed =\n axisType == ColumnAxisType.AGE\n ? t_age != null || b_age != null\n : t_pos != null || b_pos != null;\n\n if (clipBeforeLayout && isWindowed) {\n /** Prototype filtering to age range */\n units1 = units1.filter((d) => {\n // Filter units by t_age and b_age, inclusive\n if (axisType == ColumnAxisType.AGE) {\n return agesOverlap(d, window);\n } else {\n return unitsOverlap(d, window as any, axisType);\n }\n });\n }\n\n let mergeMode = mergeSections;\n // if (axisType != ColumnAxisType.AGE) {\n // // For non-age columns, we always merge sections.\n // // This is because the \"groupUnitsIntoSections\" function is not well-defined\n // // for non-age columns.\n // mergeMode = MergeSectionsMode.ALL;\n // }\n\n let sections0: SectionInfo<UnitLong>[];\n if (mergeMode == MergeSectionsMode.ALL) {\n // For the \"merge sections\" mode, we need to create a single section\n const [b_unit_pos, t_unit_pos] = getSectionPosRange(units1, axisType);\n const [b_unit_age, t_unit_age] = getSectionAgeRange(units1);\n sections0 = [\n {\n section_id: 0,\n /**\n * If ages limits are directly specified, use them to define the section bounds.\n * */\n t_pos: t_unit_pos,\n b_pos: b_unit_pos,\n t_age: t_unit_age,\n b_age: b_unit_age,\n units: units1,\n },\n ];\n } else if (axisType == ColumnAxisType.AGE) {\n sections0 = groupUnitsIntoSectionsBySectionID(units1, axisType);\n } else {\n sections0 = groupUnitsIntoSectionsByOverlap(units1, axisType);\n }\n\n // Limit sections to the range specified by t_age/b_age or t_pos/b_pos global options\n for (let section of clipBeforeLayout ? sections0 : []) {\n if (axisType == ColumnAxisType.AGE) {\n section.t_age = Math.max(section.t_age, t_age ?? -Infinity);\n section.b_age = Math.min(section.b_age, b_age ?? Infinity);\n } else if (axisType == ColumnAxisType.DEPTH) {\n section.t_pos = Math.max(section.t_pos, t_pos ?? -Infinity);\n section.b_pos = Math.min(section.b_pos, b_pos ?? Infinity);\n } else if (axisType == ColumnAxisType.HEIGHT) {\n section.t_pos = Math.max(section.t_pos, t_pos ?? -Infinity);\n section.b_pos = Math.min(section.b_pos, b_pos ?? Infinity);\n }\n }\n\n /** Merging overlapping sections really only makes sense for age/height/depth\n * columns. Ordinal columns are numbered by section so merging them\n * results in collisions.\n */\n let sections = sections0;\n if (\n mergeSections == MergeSectionsMode.OVERLAPPING &&\n axisType == ColumnAxisType.AGE\n ) {\n sections = mergeOverlappingSections(sections);\n }\n // Filter out undefined sections just in case\n sections = sections.filter((d) => d != null);\n\n // SCALES\n\n /** The window we've been asked to render. Unit density is derived from what\n * it shows (see `findAverageUnitHeight`), so it has to be known before any\n * section is laid out — but nothing is *clipped* to it until the very end.\n */\n const focalWindow: [number, number] | null = clipBeforeLayout\n ? null\n : [b_age ?? Infinity, t_age ?? -Infinity];\n\n const layoutOptions = { ...options, visibleWindow: focalWindow };\n\n /* Compute pixel scales etc. for sections\n * We need to do this now to determine which unconformities\n * are small enough to collapse.\n */\n let sectionsWithScales = computeSectionHeights(sections, layoutOptions);\n\n if (collapseSmallUnconformities && hybridScale == null) {\n // Collapse small unconformities in pixel height space\n // TODO: this doesn't seem to work properly for non-age columns?\n let threshold = unconformityHeight ?? 30;\n if (typeof collapseSmallUnconformities == \"number\") {\n threshold = collapseSmallUnconformities;\n }\n\n sectionsWithScales = collapseUnconformitiesByPixelHeight(\n sectionsWithScales,\n threshold,\n layoutOptions,\n );\n }\n\n /** Now that every section is laid out at full extent — with its own density\n * and `minSectionHeight` already settled — apply the rendered window. Padding\n * is spent here, against real pixel heights, so `windowPadding` px of an\n * abutting section is exactly that many pixels.\n */\n if (focalWindow != null && (t_age != null || b_age != null)) {\n // Resolve final densities first (a section the window cuts short is\n // stretched to `minSectionHeight`), then spend the padding budget against\n // them, so a margin is the pixels asked for rather than those pixels times\n // whatever stretch its neighbor happened to need.\n const floor =\n layoutOptions.minSectionHeight ?? layoutOptions.targetUnitHeight ?? 0;\n const scales = resolveWindowScales(sectionsWithScales, focalWindow, floor);\n const natural = (section) =>\n scales.get(section) ?? section.scaleInfo.pixelScale;\n\n const scaleFor = natural;\n\n const window =\n windowPadding > 0\n ? padWindowByPixels(\n sectionsWithScales,\n focalWindow,\n windowPadding,\n scaleFor,\n )\n : focalWindow;\n\n sectionsWithScales = trimSectionsToWindow(\n sectionsWithScales,\n window,\n scaleFor,\n );\n }\n\n /** Prepare section scale information using groups.\n * Total height is computed from section scales.\n * */\n let { totalHeight, sections: sections2 } = finalizeSectionHeights(\n sectionsWithScales,\n unconformityHeight,\n );\n\n /** For each section, find units that are overlapping.\n * We do this after merging sections so that we can\n * handle cases where there are overlapping units across sections\n * */\n const sectionsOut = sections2.map((section) => {\n return {\n ...section,\n units: preprocessUnits(section, axisType),\n };\n });\n\n /** Reconstitute the units so that they are sorted by section and properly enhanced.\n * This is mostly important so that unit keyboard navigation\n * predictably selects adjacent units.\n */\n const units2 = sectionsOut.reduce((acc, group) => {\n const { units } = group;\n for (const unit of units) {\n acc.push(unit);\n }\n return acc;\n }, []);\n\n return {\n units: units2,\n totalHeight: _totalHeight ?? totalHeight,\n sections: sectionsOut,\n };\n}\n"],"names":["window","units"],"mappings":";;;;;;AAqCO,SAAS,uBACd,MACA,SACoB;AAIpB,SAAO,QAAQ,MAAM;AACnB,WAAO,mBAAmB,MAAM,OAAO;AAAA,EACzC,GAAG,CAAC,MAAM,GAAG,OAAO,OAAO,OAAO,CAAC,CAAC;AACtC;AAEO,SAAS,mBACd,OACA,SACoB;AAGpB,MAAI,EAAE,OAAO,OAAO,OAAO,UAAU;AAErC,QAAM;AAAA,IACJ,gBAAgB,kBAAkB;AAAA,IAClC;AAAA,IACA;AAAA,IACA,8BAA8B;AAAA,IAC9B;AAAA,IACA;AAAA,IACA,gBAAgB;AAAA,EAAA,IACd;AAEJ,MAAI,eAA8B;AAElC,MAAI,SAAS,MAAM;AAEjB,UAAM,SAAS,MAAM,OAAA;AACrB,QAAI,YAAY,eAAe,KAAK;AAClC,UAAI,SAAS,KAAM,SAAQ,KAAK,IAAI,GAAG,MAAM;AAC7C,UAAI,SAAS,KAAM,SAAQ,KAAK,IAAI,GAAG,MAAM;AAC7C,qBAAe,KAAK,IAAI,MAAM,KAAK,IAAI,MAAM,KAAK,CAAC;AAAA,IACrD,OAAO;AACL,UAAI,SAAS,KAAM,SAAQ,KAAK,IAAI,GAAG,MAAM;AAC7C,UAAI,SAAS,KAAM,SAAQ,KAAK,IAAI,GAAG,MAAM;AAC7C,qBAAe,KAAK,IAAI,MAAM,KAAK,IAAI,MAAM,KAAK,CAAC;AAAA,IACrD;AAAA,EACF;AAOA,QAAM,mBACJ,YAAY,eAAe,OAAO,eAAe,QAAQ,SAAS;AAIpE,MAAI,SAAS,MAAM,IAAI,qBAA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AC,YAAY;AAC7C,WAAO;AAAA,MACL,GAAG;AAAA,MACH,OAAO,gBAAgB,SAAS,QAAQ;AAAA,IAAA;AAAA,EAE5C,CAAC;AAMD,QAAM,SAAS,YAAY,OAAO,CAAC,KAAK,UAAU;AAChD,UAAM,EAAE,OAAAC,OAAAA,IAAU;AAClB,eAAW,QAAQA,QAAO;AACxB,UAAI,KAAK,IAAI;AAAA,IACf;AACA,WAAO;AAAA,EACT,GAAG,CAAA,CAAE;AAEL,SAAO;AAAA,IACL,OAAO;AAAA,IACP,aAAa,gBAAgB;AAAA,IAC7B,UAAU;AAAA,EAAA;AAEd;"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@macrostrat/column-views",
3
- "version": "3.12.1",
3
+ "version": "3.12.2",
4
4
  "description": "Data views for Macrostrat stratigraphic columns",
5
5
  "repository": {
6
6
  "type": "git",
@@ -50,7 +50,7 @@
50
50
  "@macrostrat/color-utils": "^1.2.2",
51
51
  "@macrostrat/column-components": "^2.2.0",
52
52
  "@macrostrat/data-components": "^1.7.0",
53
- "@macrostrat/data-provider": "^1.4.0",
53
+ "@macrostrat/data-provider": "^1.4.1",
54
54
  "@macrostrat/hyper": "^3.1.1",
55
55
  "@macrostrat/map-views": "^1.1.1",
56
56
  "@macrostrat/scoped-store": "^1.1.0",
package/src/column.ts CHANGED
@@ -169,6 +169,22 @@ export function Column(props: ColumnProps) {
169
169
  _axisType = ColumnAxisType.AGE;
170
170
  }
171
171
 
172
+ let _sectionOptions = sectionOptions;
173
+ if (_sectionOptions == undefined) {
174
+ // Build our own section options function based on targetUnitHeight
175
+ _sectionOptions = (ctx) => {
176
+ /** Scale targetUnitHeight by the number of units, so that a section with just a few units
177
+ * is drawn taller than a section with many units.
178
+ */
179
+ const n = ctx.units.length;
180
+ const expansionFactor = 8 / Math.min(Math.max(n, 1), 8);
181
+
182
+ return {
183
+ targetUnitHeight: targetUnitHeight * expansionFactor,
184
+ };
185
+ };
186
+ }
187
+
172
188
  const { sections, units, totalHeight } = usePreparedColumnUnits(rawUnits, {
173
189
  axisType: _axisType,
174
190
  t_age,
@@ -177,7 +193,7 @@ export function Column(props: ColumnProps) {
177
193
  b_pos,
178
194
  mergeSections,
179
195
  targetUnitHeight,
180
- sectionOptions,
196
+ sectionOptions: _sectionOptions,
181
197
  unconformityHeight,
182
198
  pixelScale,
183
199
  pixelsPerMyr,
@@ -4,7 +4,6 @@ import { ScaleContinuousNumeric, scaleLinear } from "d3-scale";
4
4
  import { UnitLong } from "@macrostrat/api-types";
5
5
  import { buildHybridScale } from "./dynamic-scales";
6
6
  import { sectionDensity } from "./density";
7
- import { ExtUnit, HybridScaleType, SectionInfo } from "./types";
8
7
  import type {
9
8
  ColumnScaleOptions,
10
9
  CompositeColumnData,
@@ -14,6 +13,8 @@ import type {
14
13
  PackageScaleLayoutData,
15
14
  SectionScaleOptions,
16
15
  } from "./types";
16
+ import { ExtUnit, HybridScaleType, SectionInfo } from "./types";
17
+ import { mergeAgeRanges, MergeMode } from "@macrostrat/stratigraphy-utils";
17
18
 
18
19
  // Composite scale information augmented with units in each package
19
20
 
@@ -144,7 +145,13 @@ function buildSectionScale<T extends UnitLong>(
144
145
  } = opts;
145
146
  const domain = opts.domain ?? findSectionHeightRange(data, axisType);
146
147
 
147
- const dAge = Math.abs(domain[0] - domain[1]);
148
+ const dAge = dx(domain);
149
+ let visibleExtent = dAge; // full section is visible
150
+ if (visibleWindow != null) {
151
+ visibleExtent = dx(
152
+ mergeAgeRanges([domain, visibleWindow], MergeMode.Inner),
153
+ );
154
+ }
148
155
 
149
156
  let _pixelScale: any = opts.pixelScale;
150
157
  let pixelHeight: number;
@@ -177,6 +184,7 @@ function buildSectionScale<T extends UnitLong>(
177
184
  * is what it's for, and never a sliver the window happens to cut. */
178
185
  _pixelScale = sectionDensity(opts)({
179
186
  extent: dAge,
187
+ visibleExtent,
180
188
  unitExtents: visibleUnitExtents(data, axisType, visibleWindow),
181
189
  units: data,
182
190
  sectionID,
@@ -194,6 +202,10 @@ function buildSectionScale<T extends UnitLong>(
194
202
  );
195
203
  }
196
204
 
205
+ function dx(range: [number, number]) {
206
+ return Math.abs(range[0] - range[1]);
207
+ }
208
+
197
209
  /**
198
210
  * The density each section will actually render at once the window is applied.
199
211
  *
@@ -275,9 +287,12 @@ function spendOutward<T extends UnitLong>(
275
287
  // Sections ordered outward from the edge, keeping only what lies beyond it.
276
288
  const beyond = sections
277
289
  .filter(
278
- (s) => direction * (s.b_age - edge) > 0 || direction * (s.t_age - edge) > 0,
290
+ (s) =>
291
+ direction * (s.b_age - edge) > 0 || direction * (s.t_age - edge) > 0,
279
292
  )
280
- .sort((a, b) => direction * (nearEdge(a, direction) - nearEdge(b, direction)));
293
+ .sort(
294
+ (a, b) => direction * (nearEdge(a, direction) - nearEdge(b, direction)),
295
+ );
281
296
 
282
297
  let bound = edge;
283
298
  let budget = padding;
@@ -290,7 +305,8 @@ function spendOutward<T extends UnitLong>(
290
305
  direction > 0
291
306
  ? Math.max(section.t_age, bound)
292
307
  : Math.min(section.b_age, bound);
293
- const available = direction > 0 ? section.b_age - from : from - section.t_age;
308
+ const available =
309
+ direction > 0 ? section.b_age - from : from - section.t_age;
294
310
  if (available <= 0) continue;
295
311
 
296
312
  const cost = available * pixelScale;
@@ -451,10 +467,7 @@ function visibleUnitExtents(
451
467
  const [b_pos, t_pos] = getUnitHeightRange(d, axisType);
452
468
  if (!clip) return Math.abs(b_pos - t_pos);
453
469
  const [b_win, t_win] = visibleWindow;
454
- return Math.max(
455
- 0,
456
- Math.min(b_pos, b_win) - Math.max(t_pos, t_win),
457
- );
470
+ return Math.max(0, Math.min(b_pos, b_win) - Math.max(t_pos, t_win));
458
471
  })
459
472
  .filter((d) => d > 0);
460
473
 
@@ -12,6 +12,8 @@ import type { UnitLong } from "@macrostrat/api-types";
12
12
  export interface SectionDensityContext {
13
13
  /** The section's extent, in axis units */
14
14
  extent: number;
15
+ /** The section's shown extent, in axis units */
16
+ visibleExtent: number;
15
17
  /** Extents of the units the render window actually shows, each clipped to
16
18
  * it. Measuring what's on screen is what makes a unit-height rule mean the
17
19
  * same thing at every zoom depth. */
@@ -28,23 +30,14 @@ export type SectionDensity = (ctx: SectionDensityContext) => number;
28
30
 
29
31
  export type SectionDensityLike = number | SectionDensity;
30
32
 
31
- /** Room for a typical unit on screen: `px` tall, whatever its duration.
32
- *
33
- * "Typical" is the median of the visible extents, which is the only summary
34
- * that survives both tails. Unit durations are spread over orders of
35
- * magnitude: the arithmetic mean sits above any unit you would point at, so a
36
- * couple of long ones squeeze everything else below the target — and the
37
- * geometric mean fails the other way, since a single hair-thin unit (a
38
- * Holocene sliver beside a Pliocene terrace, say) drags the log-average down
39
- * and stretches the whole section to give that sliver its 20 pixels.
40
- */
41
- export function unitHeight(px: number): SectionDensity {
42
- return (ctx) => px / typicalExtent(ctx.unitExtents);
33
+ enum UnitHeightMode {
34
+ MEDIAN = "median",
35
+ MEAN = "mean",
43
36
  }
44
37
 
45
38
  /** Room for the section: `px` tall, whatever its extent. */
46
39
  export function sectionHeight(px: number): SectionDensity {
47
- return (ctx) => px / ctx.extent;
40
+ return (ctx) => px / ctx.visibleExtent;
48
41
  }
49
42
 
50
43
  /** A density stated outright, in pixels per axis unit. */
@@ -75,15 +68,6 @@ export function resolveDensity(
75
68
  return rule(ctx);
76
69
  }
77
70
 
78
- function typicalExtent(extents: number[]): number {
79
- const sorted = extents.filter((d) => d > 0).sort((a, b) => a - b);
80
- if (sorted.length === 0) return NaN;
81
- const mid = (sorted.length - 1) / 2;
82
- const lower = Math.floor(mid);
83
- const upper = Math.ceil(mid);
84
- return (sorted[lower] + sorted[upper]) / 2;
85
- }
86
-
87
71
  /** Mirrors the default in `sectionDensity` */
88
72
  export const DEFAULT_TARGET_UNIT_HEIGHT = 20;
89
73
  /** Small sections often have a unit or two, and no room for axis labels */
@@ -131,8 +115,7 @@ export interface SectionSizeOptions {
131
115
  * holds. What it returns overrides the column-wide options for that section;
132
116
  * anything it leaves out keeps the column's value. */
133
117
  export type SectionOptionsLike =
134
- | SectionSizeOptions
135
- | ((ctx: SectionDensityContext) => SectionSizeOptions);
118
+ SectionSizeOptions | ((ctx: SectionDensityContext) => SectionSizeOptions);
136
119
 
137
120
  export interface SectionDensityOptions extends SectionSizeOptions {
138
121
  /** Sizing decided per section */
@@ -164,7 +147,7 @@ function densityRule(opts: SectionSizeOptions): SectionDensity {
164
147
  } = opts;
165
148
 
166
149
  const derived = atLeast(
167
- unitHeight(targetUnitHeight),
150
+ unitHeight(targetUnitHeight, UnitHeightMode.MEAN),
168
151
  fixedDensity(minPixelScale),
169
152
  sectionHeight(minSectionHeight ?? targetUnitHeight ?? 0),
170
153
  );
@@ -182,6 +165,34 @@ function densityRule(opts: SectionSizeOptions): SectionDensity {
182
165
  };
183
166
  }
184
167
 
168
+ /** Room for a typical unit on screen: `px` tall, whatever its duration.
169
+ *
170
+ * "Typical" is the median of the visible extents, which is the only summary
171
+ * that survives both tails. Unit durations are spread over orders of
172
+ * magnitude: the arithmetic mean sits above any unit you would point at, so a
173
+ * couple of long ones squeeze everything else below the target — and the
174
+ * geometric mean fails the other way, since a single hair-thin unit (a
175
+ * Holocene sliver beside a Pliocene terrace, say) drags the log-average down
176
+ * and stretches the whole section to give that sliver its 20 pixels.
177
+ */
178
+ export function unitHeight(px: number, mode: UnitHeightMode): SectionDensity {
179
+ return (ctx) => px / typicalExtent(ctx.unitExtents, mode);
180
+ }
181
+
182
+ function typicalExtent(extents: number[], mode: UnitHeightMode): number {
183
+ /** The typical extent for a unit, the median of its extents. */
184
+ const filtered = extents.filter((d) => d > 0);
185
+ if (filtered.length === 0) return NaN;
186
+ if (mode === UnitHeightMode.MEAN) {
187
+ return filtered.reduce((sum, val) => sum + val, 0) / filtered.length;
188
+ }
189
+ const sorted = filtered.sort((a, b) => a - b);
190
+ const mid = (sorted.length - 1) / 2;
191
+ const lower = Math.floor(mid);
192
+ const upper = Math.ceil(mid);
193
+ return (sorted[lower] + sorted[upper]) / 2;
194
+ }
195
+
185
196
  /** The density this axis was given, if any. The axis-specific spellings win
186
197
  * over the generic one, which is what lets both be held while the axis
187
198
  * changes. */
@@ -282,7 +282,7 @@ export function groupUnitsIntoSectionsByOverlap<T extends BaseUnit>(
282
282
  }
283
283
  }
284
284
 
285
- return finalSectionList.map((section, i) => {
285
+ const s1 = finalSectionList.map((section, i) => {
286
286
  const [b_age, t_age] = getSectionAgeRange(section.units);
287
287
  const [b_pos, t_pos] = getSectionPosRange(section.units, axisType);
288
288
  return {
@@ -295,6 +295,8 @@ export function groupUnitsIntoSectionsByOverlap<T extends BaseUnit>(
295
295
  units: section.units as T[],
296
296
  };
297
297
  });
298
+
299
+ return sortUnits(s1, axisType);
298
300
  }
299
301
 
300
302
  export function getSectionPosRange(
@@ -338,6 +340,38 @@ export function getSectionAgeRange(units: BaseUnit[]): [number, number] {
338
340
  return getSectionPosRange(units, ColumnAxisType.AGE);
339
341
  }
340
342
 
343
+ function forEachSection(fn, sections, ...args) {
344
+ return sections.map((section) => {
345
+ return {
346
+ ...section,
347
+ units: fn(section.units, ...args),
348
+ };
349
+ });
350
+ }
351
+
352
+ function sortUnits(units: BaseUnit[], axisType: ColumnAxisType) {
353
+ return units.sort((a, b) => {
354
+ if (
355
+ axisType === ColumnAxisType.HEIGHT &&
356
+ b.t_pos !== undefined &&
357
+ a.t_pos !== undefined
358
+ ) {
359
+ return b.t_pos - a.t_pos;
360
+ }
361
+ if (
362
+ axisType === ColumnAxisType.DEPTH &&
363
+ b.t_pos !== undefined &&
364
+ a.t_pos !== undefined
365
+ ) {
366
+ return a.t_pos - b.t_pos;
367
+ }
368
+ if (axisType === ColumnAxisType.AGE) {
369
+ return a.t_age - b.t_age;
370
+ }
371
+ return 0;
372
+ });
373
+ }
374
+
341
375
  export function mergeOverlappingSections<T extends UnitLong>(
342
376
  sections: SectionInfo<T>[],
343
377
  ): SectionInfo<T>[] {
@@ -228,7 +228,6 @@ export function prepareColumnUnits(
228
228
  const natural = (section) =>
229
229
  scales.get(section) ?? section.scaleInfo.pixelScale;
230
230
 
231
-
232
231
  const scaleFor = natural;
233
232
 
234
233
  const window =