@macrostrat/column-views 3.6.0 → 3.8.0

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 (107) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/dist/column-views.css +118 -89
  3. package/dist/column.cjs +1 -2
  4. package/dist/column.cjs.map +1 -1
  5. package/dist/column.js +1 -2
  6. package/dist/column.js.map +1 -1
  7. package/dist/column.module.sass.cjs +15 -15
  8. package/dist/column.module.sass.js +15 -15
  9. package/dist/correlation-chart/main.cjs +136 -34
  10. package/dist/correlation-chart/main.cjs.map +1 -1
  11. package/dist/correlation-chart/main.d.ts +33 -2
  12. package/dist/correlation-chart/main.js +118 -15
  13. package/dist/correlation-chart/main.js.map +1 -1
  14. package/dist/correlation-chart/main.module.sass.cjs +23 -20
  15. package/dist/correlation-chart/main.module.sass.cjs.map +1 -1
  16. package/dist/correlation-chart/main.module.sass.js +23 -20
  17. package/dist/correlation-chart/main.module.sass.js.map +1 -1
  18. package/dist/correlation-chart/prepare-data.cjs +0 -1
  19. package/dist/correlation-chart/prepare-data.cjs.map +1 -1
  20. package/dist/correlation-chart/prepare-data.js +0 -1
  21. package/dist/correlation-chart/prepare-data.js.map +1 -1
  22. package/dist/data-provider/store.cjs +10 -2
  23. package/dist/data-provider/store.cjs.map +1 -1
  24. package/dist/data-provider/store.d.ts +2 -2
  25. package/dist/data-provider/store.js +10 -2
  26. package/dist/data-provider/store.js.map +1 -1
  27. package/dist/data-provider/unit-selection.cjs +4 -1
  28. package/dist/data-provider/unit-selection.cjs.map +1 -1
  29. package/dist/data-provider/unit-selection.d.ts +1 -1
  30. package/dist/data-provider/unit-selection.js +4 -1
  31. package/dist/data-provider/unit-selection.js.map +1 -1
  32. package/dist/index.cjs +14 -4
  33. package/dist/index.cjs.map +1 -1
  34. package/dist/index.js +3 -2
  35. package/dist/maps/column-correlation/core.cjs +127 -6
  36. package/dist/maps/column-correlation/core.cjs.map +1 -1
  37. package/dist/maps/column-correlation/core.js +128 -7
  38. package/dist/maps/column-correlation/core.js.map +1 -1
  39. package/dist/maps/column-correlation/state.cjs +63 -2
  40. package/dist/maps/column-correlation/state.cjs.map +1 -1
  41. package/dist/maps/column-correlation/state.d.ts +31 -1
  42. package/dist/maps/column-correlation/state.js +63 -2
  43. package/dist/maps/column-correlation/state.js.map +1 -1
  44. package/dist/maps/layers/columns.cjs +5 -1
  45. package/dist/maps/layers/columns.cjs.map +1 -1
  46. package/dist/maps/layers/columns.js +5 -1
  47. package/dist/maps/layers/columns.js.map +1 -1
  48. package/dist/prepare-units/helpers.cjs +4 -2
  49. package/dist/prepare-units/helpers.cjs.map +1 -1
  50. package/dist/prepare-units/helpers.js +4 -2
  51. package/dist/prepare-units/helpers.js.map +1 -1
  52. package/dist/section.cjs +8 -2
  53. package/dist/section.cjs.map +1 -1
  54. package/dist/section.d.ts +2 -0
  55. package/dist/section.js +8 -2
  56. package/dist/section.js.map +1 -1
  57. package/dist/unit-details/age-range.cjs +2 -1
  58. package/dist/unit-details/age-range.cjs.map +1 -1
  59. package/dist/unit-details/age-range.js +2 -1
  60. package/dist/unit-details/age-range.js.map +1 -1
  61. package/dist/unit-details/index.d.ts +1 -1
  62. package/dist/unit-details/panel.cjs +2 -3
  63. package/dist/unit-details/panel.cjs.map +1 -1
  64. package/dist/unit-details/panel.js +1 -2
  65. package/dist/unit-details/panel.js.map +1 -1
  66. package/dist/unit-details/panel.module.sass.cjs +18 -22
  67. package/dist/unit-details/panel.module.sass.cjs.map +1 -1
  68. package/dist/unit-details/panel.module.sass.js +18 -22
  69. package/dist/unit-details/panel.module.sass.js.map +1 -1
  70. package/dist/unit-details/strat-names.cjs +1 -2
  71. package/dist/unit-details/strat-names.cjs.map +1 -1
  72. package/dist/unit-details/strat-names.js +1 -2
  73. package/dist/unit-details/strat-names.js.map +1 -1
  74. package/dist/units/boxes.cjs +2 -1
  75. package/dist/units/boxes.cjs.map +1 -1
  76. package/dist/units/boxes.js +2 -1
  77. package/dist/units/boxes.js.map +1 -1
  78. package/package.json +7 -7
  79. package/src/column.module.sass +6 -0
  80. package/src/correlation-chart/main.module.sass +46 -2
  81. package/src/correlation-chart/main.ts +180 -9
  82. package/src/correlation-chart/prepare-data.ts +0 -1
  83. package/src/data-provider/store.ts +11 -1
  84. package/src/data-provider/unit-selection.ts +13 -2
  85. package/src/maps/column-correlation/column-correlation-map.stories.ts +12 -0
  86. package/src/maps/column-correlation/core.ts +155 -9
  87. package/src/maps/column-correlation/state.ts +110 -2
  88. package/src/maps/layers/columns.ts +7 -1
  89. package/src/prepare-units/helpers.ts +4 -3
  90. package/src/section.ts +9 -1
  91. package/src/unit-details/age-range.ts +3 -1
  92. package/src/unit-details/index.ts +7 -1
  93. package/src/unit-details/panel.module.sass +0 -8
  94. package/src/unit-details/panel.ts +6 -6
  95. package/src/unit-details/strat-names.ts +1 -1
  96. package/src/units/boxes.ts +4 -2
  97. package/dist/correlation-chart/stories/utils.d.ts +0 -6
  98. package/dist/unit-details/identifiers.cjs +0 -56
  99. package/dist/unit-details/identifiers.cjs.map +0 -1
  100. package/dist/unit-details/identifiers.d.ts +0 -31
  101. package/dist/unit-details/identifiers.js +0 -54
  102. package/dist/unit-details/identifiers.js.map +0 -1
  103. package/src/correlation-chart/stories/correlation-chart.stories.ts +0 -228
  104. package/src/correlation-chart/stories/namibia-correlation.stories.ts +0 -151
  105. package/src/correlation-chart/stories/stories.module.sass +0 -18
  106. package/src/correlation-chart/stories/utils.ts +0 -24
  107. package/src/unit-details/identifiers.ts +0 -67
@@ -1 +1 @@
1
- {"version":3,"file":"store.cjs","sources":["../../src/data-provider/store.ts"],"sourcesContent":["import {\n createContext,\n ReactNode,\n RefObject,\n useContext,\n useMemo,\n} from \"react\";\nimport h from \"@macrostrat/hyper\";\nimport {\n CompositeColumnScale,\n createCompositeScale,\n} from \"../prepare-units/composite-scale\";\nimport { ColumnAxisType, ColumnProvider } from \"@macrostrat/column-components\";\nimport type { ExtUnit, PackageLayoutData } from \"../prepare-units\";\nimport {\n allowUnitSelectionAtom,\n selectedUnitIDAtom,\n UnitSelectionCallbacks,\n UnitSelectionCallbackManager,\n selectedUnitElementAtom,\n} from \"./unit-selection\";\nimport type { BaseUnit } from \"@macrostrat/api-types\";\nimport {\n type AtomMap,\n createScopedStore,\n StateIsolation,\n} from \"@macrostrat/scoped-store\";\nimport { atom } from \"jotai\";\nimport { useEffect } from \"react\";\n\nexport const scope: StateIsolation = createScopedStore();\n\nexport const columnUnitsAtom = atom<BaseUnit[]>();\n\nexport const columnUnitsMapAtom = atom<Map<number, BaseUnit> | null>((get) => {\n const units = get(columnUnitsAtom);\n if (!units) return null;\n const unitMap = new Map<number, BaseUnit>();\n units.forEach((unit) => {\n unitMap.set(unit.unit_id, unit);\n });\n return unitMap;\n});\n\nexport interface ColumnStateProviderProps<\n T extends BaseUnit,\n> extends Partial<UnitSelectionCallbacks> {\n children: ReactNode;\n units: T[];\n selectedUnit: number | null;\n allowUnitSelection?: boolean;\n}\n\nexport function MacrostratColumnStateProvider<T extends BaseUnit>({\n children,\n units,\n allowUnitSelection = false,\n onUnitSelected,\n selectedUnit,\n}: ColumnStateProviderProps<T>) {\n /** Top-level provider for Macrostrat column data.\n * It is either provided by the Column component itself, or\n * can be hoisted higher in the tree to provide a common data context\n */\n\n /* By default, unit selection is disabled. However, if any related props are passed,\n we enable it.\n */\n const _allowSelection = useMemo(() => {\n if (allowUnitSelection) {\n return true;\n }\n return selectedUnit != null || onUnitSelected != null;\n }, []);\n\n const atomMap: AtomMap = [\n [columnUnitsAtom, units],\n [allowUnitSelectionAtom, _allowSelection],\n [selectedUnitIDAtom, selectedUnit],\n ];\n\n let selectionHandlers: ReactNode = null;\n if (_allowSelection) {\n selectionHandlers = h(UnitSelectionCallbackManager, { onUnitSelected });\n }\n\n return h(\n scope.Provider,\n {\n atoms: atomMap,\n keepUpdated: true,\n inherit: true,\n },\n [selectionHandlers, children],\n );\n}\n\n/** Interface for imperative handlers that can\n * be invoked outside of the column's react context\n */\nexport interface ColumnRef {\n scrollSelectedUnitIntoView(): void;\n}\n\nexport interface MacrostratColumnDataContext<T extends BaseUnit> {\n units: T[];\n sections: PackageLayoutData[];\n totalHeight?: number;\n axisType?: ColumnAxisType;\n allowUnitSelection?: boolean;\n}\n\nexport interface ColumnDataProviderProps<T extends BaseUnit>\n extends MacrostratColumnDataContext<T>, ColumnStateProviderProps<T> {\n children: ReactNode;\n ref: RefObject<ColumnRef>;\n}\n\nconst MacrostratColumnDataContext =\n createContext<MacrostratColumnDataContext<any>>(null);\n\nexport function MacrostratColumnDataProvider<T extends BaseUnit>({\n children,\n units,\n sections,\n totalHeight,\n axisType,\n allowUnitSelection,\n onUnitSelected,\n selectedUnit,\n ref,\n}: ColumnDataProviderProps<T>) {\n /** Internal provider for Macrostrat column data.\n * As a general rule, we want to provide data and column-axis\n * height calculations through the context, since these need to\n * be accessed by any component that lays out information on the\n * column.\n *\n * Cross-axis layout and view configuration (e.g., showing and hiding\n * of different components or labels) should be handled through passing\n * props to the components themselves.\n * */\n\n const value = useMemo(() => {\n // For now, change ordinal axis types to age axis types\n return {\n units,\n sections,\n totalHeight,\n axisType,\n };\n }, [units, sections, totalHeight, axisType]);\n\n return h(\n MacrostratColumnStateProvider,\n {\n units,\n allowUnitSelection,\n onUnitSelected,\n selectedUnit,\n ref,\n },\n [\n h(ColumnRefManager, { ref }),\n h(MacrostratColumnDataContext.Provider, { value }, children),\n ],\n );\n}\n\nfunction ColumnRefManager({ ref }: { ref?: RefObject<ColumnRef> }) {\n const selectedUnitElement = scope.useAtomValue(selectedUnitElementAtom);\n useEffect(() => {\n if (ref == null) return;\n ref.current = {\n scrollSelectedUnitIntoView(opts?: ScrollIntoViewOptions) {\n selectedUnitElement?.scrollIntoView(\n opts ?? {\n behavior: \"smooth\",\n block: \"center\",\n inline: \"nearest\",\n },\n );\n },\n };\n }, [ref, selectedUnitElement]);\n\n return null;\n}\n\nexport function UnitSelectionProvider(props: ColumnStateProviderProps<any>) {\n /* A basic unit selection provider without column data context.\n Mostly for use with the CorrelationChart component.\n */\n return h(MacrostratColumnStateProvider, {\n ...props,\n allowUnitSelection: true,\n });\n}\n\nexport function useMacrostratColumnData() {\n const ctx = useContext(MacrostratColumnDataContext);\n if (!ctx) {\n throw new Error(\n \"useMacrostratColumnData must be used within a MacrostratColumnDataProvider\",\n );\n }\n return ctx;\n}\n\nexport function useMacrostratUnits() {\n return scope.useAtomValue(columnUnitsAtom);\n}\n\nexport function useColumnUnitsMap(): Map<number, ExtUnit> | null {\n try {\n return scope.useAtomValue(columnUnitsMapAtom) as Map<number, ExtUnit>;\n } catch {\n return null;\n }\n}\n\nexport function useCompositeScale(): CompositeColumnScale {\n const ctx = useMacrostratColumnData();\n return useMemo(\n () => createCompositeScale(ctx.sections, true),\n [ctx.sections],\n );\n}\n\nexport function MacrostratColumnProvider(props) {\n /** A column provider specialized the Macrostrat API. Maps more\n * generic concepts to Macrostrat-specific ones.\n */\n\n const { axisType } = useMacrostratColumnData();\n const { units, domain, pixelScale, scale, children } = props;\n return h(\n ColumnProvider,\n {\n axisType,\n divisions: units,\n range: domain,\n pixelsPerMeter: pixelScale,\n scale,\n },\n children,\n );\n}\n\n/** This is now a legacy provider */\nexport function LithologiesProvider({ children }) {\n useEffect(() => {\n console.warn(\n \"LithologiesProvider is deprecated. Replace with MacrostratDataProvider\",\n );\n }, []);\n return children;\n}\n"],"names":["createScopedStore","atom","useMemo","allowUnitSelectionAtom","selectedUnitIDAtom","h","UnitSelectionCallbackManager","createContext","selectedUnitElementAtom","useEffect","useContext","createCompositeScale","ColumnProvider"],"mappings":";;;;;;;;;;;AA8BO,MAAM,QAAwBA,YAAAA,kBAAA;AAE9B,MAAM,kBAAkBC,MAAAA,KAAA;AAExB,MAAM,qBAAqBA,MAAAA,KAAmC,CAAC,QAAQ;AAC5E,QAAM,QAAQ,IAAI,eAAe;AACjC,MAAI,CAAC,MAAO,QAAO;AACnB,QAAM,8BAAc,IAAA;AACpB,QAAM,QA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D,SAAON,WAAAA;AAAAA,IACLO,iBAAAA;AAAAA,IACA;AAAA,MACE;AAAA,MACA,WAAW;AAAA,MACX,OAAO;AAAA,MACP,gBAAgB;AAAA,MAChB;AAAA,IAAA;AAAA,IAEF;AAAA,EAAA;AAEJ;AAGO,SAAS,oBAAoB,EAAE,YAAY;AAChDH,QAAAA,UAAU,MAAM;AACd,YAAQ;AAAA,MACN;AAAA,IAAA;AAAA,EAEJ,GAAG,CAAA,CAAE;AACL,SAAO;AACT;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"store.cjs","sources":["../../src/data-provider/store.ts"],"sourcesContent":["import {\n createContext,\n ReactNode,\n RefObject,\n useContext,\n useMemo,\n} from \"react\";\nimport h from \"@macrostrat/hyper\";\nimport {\n CompositeColumnScale,\n createCompositeScale,\n} from \"../prepare-units/composite-scale\";\nimport { ColumnAxisType, ColumnProvider } from \"@macrostrat/column-components\";\nimport type { ExtUnit, PackageLayoutData } from \"../prepare-units\";\nimport {\n allowUnitSelectionAtom,\n selectedUnitIDAtom,\n UnitSelectionCallbacks,\n UnitSelectionCallbackManager,\n selectedUnitElementAtom,\n} from \"./unit-selection\";\nimport type { BaseUnit } from \"@macrostrat/api-types\";\nimport {\n type AtomMap,\n createScopedStore,\n StateIsolation,\n} from \"@macrostrat/scoped-store\";\nimport { atom } from \"jotai\";\nimport { useEffect } from \"react\";\n\nexport const scope: StateIsolation = createScopedStore();\n\nexport const columnUnitsAtom = atom<BaseUnit[]>();\n\nexport const columnUnitsMapAtom = atom<Map<number, BaseUnit> | null>((get) => {\n const units = get(columnUnitsAtom);\n if (!units) return null;\n const unitMap = new Map<number, BaseUnit>();\n units.forEach((unit) => {\n unitMap.set(unit.unit_id, unit);\n });\n return unitMap;\n});\n\nexport interface ColumnStateProviderProps<\n T extends BaseUnit,\n> extends Partial<UnitSelectionCallbacks> {\n children: ReactNode;\n units: T[];\n selectedUnit: number | null;\n allowUnitSelection?: boolean;\n}\n\nexport function MacrostratColumnStateProvider<T extends BaseUnit>({\n children,\n units,\n allowUnitSelection = false,\n onUnitSelected,\n selectedUnit,\n}: ColumnStateProviderProps<T>) {\n /** Top-level provider for Macrostrat column data.\n * It is either provided by the Column component itself, or\n * can be hoisted higher in the tree to provide a common data context\n */\n\n /* By default, unit selection is disabled. However, if any related props are passed,\n we enable it.\n */\n const _allowSelection = useMemo(() => {\n if (allowUnitSelection) {\n return true;\n }\n return selectedUnit != null || onUnitSelected != null;\n }, []);\n\n // Check if we're already in a columnStateProvider, and render a no-op if so\n const existingUnits = scope.useAtomValueIfExists(columnUnitsAtom);\n if (existingUnits != null) {\n if (allowUnitSelection || onUnitSelected || selectedUnit != null) {\n console.warn(\n \"MacrostratColumnStateProvider: unit selection props are ignored because a provider already exists in the tree\",\n );\n }\n return children;\n }\n\n const atomMap: AtomMap = [\n [columnUnitsAtom, units],\n [allowUnitSelectionAtom, _allowSelection],\n [selectedUnitIDAtom, selectedUnit],\n ];\n\n let selectionHandlers: ReactNode = null;\n if (_allowSelection) {\n selectionHandlers = h(UnitSelectionCallbackManager, { onUnitSelected });\n }\n\n return h(\n scope.Provider,\n {\n atoms: atomMap,\n keepUpdated: true,\n },\n [selectionHandlers, children],\n );\n}\n\n/** Interface for imperative handlers that can\n * be invoked outside of the column's react context\n */\nexport interface ColumnRef {\n scrollSelectedUnitIntoView(): void;\n}\n\nexport interface MacrostratColumnDataContext<T extends BaseUnit> {\n units: T[];\n sections: PackageLayoutData[];\n totalHeight?: number;\n axisType?: ColumnAxisType;\n allowUnitSelection?: boolean;\n}\n\nexport interface ColumnDataProviderProps<T extends BaseUnit>\n extends MacrostratColumnDataContext<T>, ColumnStateProviderProps<T> {\n children: ReactNode;\n ref: RefObject<ColumnRef>;\n}\n\nconst MacrostratColumnDataContext =\n createContext<MacrostratColumnDataContext<any>>(null);\n\nexport function MacrostratColumnDataProvider<T extends BaseUnit>({\n children,\n units,\n sections,\n totalHeight,\n axisType,\n allowUnitSelection,\n onUnitSelected,\n selectedUnit,\n ref,\n}: ColumnDataProviderProps<T>) {\n /** Internal provider for Macrostrat column data.\n * As a general rule, we want to provide data and column-axis\n * height calculations through the context, since these need to\n * be accessed by any component that lays out information on the\n * column.\n *\n * Cross-axis layout and view configuration (e.g., showing and hiding\n * of different components or labels) should be handled through passing\n * props to the components themselves.\n * */\n\n const value = useMemo(() => {\n // For now, change ordinal axis types to age axis types\n return {\n units,\n sections,\n totalHeight,\n axisType,\n };\n }, [units, sections, totalHeight, axisType]);\n\n return h(\n MacrostratColumnStateProvider,\n {\n units,\n allowUnitSelection,\n onUnitSelected,\n selectedUnit,\n ref,\n },\n [\n h(ColumnRefManager, { ref }),\n h(MacrostratColumnDataContext.Provider, { value }, children),\n ],\n );\n}\n\nfunction ColumnRefManager({ ref }: { ref?: RefObject<ColumnRef> }) {\n const selectedUnitElement = scope.useAtomValue(selectedUnitElementAtom);\n useEffect(() => {\n if (ref == null) return;\n ref.current = {\n scrollSelectedUnitIntoView(opts?: ScrollIntoViewOptions) {\n selectedUnitElement?.scrollIntoView(\n opts ?? {\n behavior: \"smooth\",\n block: \"center\",\n inline: \"nearest\",\n },\n );\n },\n };\n }, [ref, selectedUnitElement]);\n\n return null;\n}\n\nexport function UnitSelectionProvider(props: ColumnStateProviderProps<any>) {\n /* A basic unit selection provider without column data context.\n Mostly for use with the CorrelationChart component.\n */\n return h(MacrostratColumnStateProvider, {\n ...props,\n allowUnitSelection: true,\n });\n}\n\nexport function useMacrostratColumnData() {\n const ctx = useContext(MacrostratColumnDataContext);\n if (!ctx) {\n throw new Error(\n \"useMacrostratColumnData must be used within a MacrostratColumnDataProvider\",\n );\n }\n return ctx;\n}\n\nexport function useMacrostratUnits() {\n return scope.useAtomValue(columnUnitsAtom);\n}\n\nexport function useColumnUnitsMap(): Map<number, ExtUnit> | null {\n try {\n return scope.useAtomValue(columnUnitsMapAtom) as Map<number, ExtUnit>;\n } catch {\n return null;\n }\n}\n\nexport function useCompositeScale(): CompositeColumnScale {\n const ctx = useMacrostratColumnData();\n return useMemo(\n () => createCompositeScale(ctx.sections, true),\n [ctx.sections],\n );\n}\n\nexport function MacrostratColumnProvider(props) {\n /** A column provider specialized the Macrostrat API. Maps more\n * generic concepts to Macrostrat-specific ones.\n */\n\n const { axisType } = useMacrostratColumnData();\n const { units, domain, pixelScale, scale, children } = props;\n return h(\n ColumnProvider,\n {\n axisType,\n divisions: units,\n range: domain,\n pixelsPerMeter: pixelScale,\n scale,\n },\n children,\n );\n}\n\n/** This is now a legacy provider */\nexport function LithologiesProvider({ children }) {\n useEffect(() => {\n console.warn(\n \"LithologiesProvider is deprecated. Replace with MacrostratDataProvider\",\n );\n }, []);\n return children;\n}\n"],"names":["createScopedStore","atom","useMemo","allowUnitSelectionAtom","selectedUnitIDAtom","h","UnitSelectionCallbackManager","createContext","selectedUnitElementAtom","useEffect","useContext","createCompositeScale","ColumnProvider"],"mappings":";;;;;;;;;;;AA8BO,MAAM,QAAwBA,YAAAA,kBAAA;AAE9B,MAAM,kBAAkBC,MAAAA,KAAA;AAExB,MAAM,qBAAqBA,MAAAA,KAAmC,CAAC,QAAQ;AAC5E,QAAM,QAAQ,IAAI,eAAe;AACjC,MAAI,CAAC,MAAO,QAAO;AACnB,QAAM,8BAAc,IAAA;AACpB,QAAM,QAAQ,CAAC,SAAS;AACtB,YAAQ,IAAI,KAAK,SAAS,IAAI;AAAA,EAChC,CAAC;AACD,SAAO;AACT,CAAC;AAWM,SAAS,8BAAkD;AAAA,EAChE;AAAA,EACA;AAAA,EACA,qBAAqB;AAAA,EACrB;AAAA,EACA;AACF,GAAgC;AAS9B,QAAM,kBAAkBC,MAAAA,QAAQ,MAAM;AACpC,QAAI,oBAAoB;AACtB,aAAO;AAAA,IACT;AACA,WAAO,gBAAgB,QAAQ,kBAAkB;AAAA,EACnD,GAAG,CAAA,CAAE;AAGL,QAAM,gBAAgB,MAAM,qBAAqB,eAAe;AAChE,MAAI,iBAAiB,MAAM;AACzB,QAAI,sBAAsB,kBAAkB,gBAAgB,MAA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,CAAE;AACL,SAAO;AACT;;;;;;;;;;;;;"}
@@ -16,12 +16,12 @@ export interface ColumnStateProviderProps<T extends BaseUnit> extends Partial<Un
16
16
  selectedUnit: number | null;
17
17
  allowUnitSelection?: boolean;
18
18
  }
19
- export declare function MacrostratColumnStateProvider<T extends BaseUnit>({ children, units, allowUnitSelection, onUnitSelected, selectedUnit, }: ColumnStateProviderProps<T>): import('react').FunctionComponentElement<{
19
+ export declare function MacrostratColumnStateProvider<T extends BaseUnit>({ children, units, allowUnitSelection, onUnitSelected, selectedUnit, }: ColumnStateProviderProps<T>): string | number | bigint | boolean | import('react').ReactElement<unknown, string | import('react').JSXElementConstructor<any>> | Iterable<ReactNode> | Promise<string | number | bigint | boolean | import('react').ReactPortal | import('react').ReactElement<unknown, string | import('react').JSXElementConstructor<any>> | Iterable<ReactNode> | null | undefined> | import('react').FunctionComponentElement<{
20
20
  children: ReactNode;
21
21
  atoms?: AtomMap;
22
22
  keepUpdated?: boolean;
23
23
  inherit?: boolean;
24
- }>;
24
+ }> | null | undefined;
25
25
  /** Interface for imperative handlers that can
26
26
  * be invoked outside of the column's react context
27
27
  */
@@ -29,6 +29,15 @@ function MacrostratColumnStateProvider({
29
29
  }
30
30
  return selectedUnit != null || onUnitSelected != null;
31
31
  }, []);
32
+ const existingUnits = scope.useAtomValueIfExists(columnUnitsAtom);
33
+ if (existingUnits != null) {
34
+ if (allowUnitSelection || onUnitSelected || selectedUnit != null) {
35
+ console.warn(
36
+ "MacrostratColumnStateProvider: unit selection props are ignored because a provider already exists in the tree"
37
+ );
38
+ }
39
+ return children;
40
+ }
32
41
  const atomMap = [
33
42
  [columnUnitsAtom, units],
34
43
  [allowUnitSelectionAtom, _allowSelection],
@@ -42,8 +51,7 @@ function MacrostratColumnStateProvider({
42
51
  scope.Provider,
43
52
  {
44
53
  atoms: atomMap,
45
- keepUpdated: true,
46
- inherit: true
54
+ keepUpdated: true
47
55
  },
48
56
  [selectionHandlers, children]
49
57
  );
@@ -1 +1 @@
1
- {"version":3,"file":"store.js","sources":["../../src/data-provider/store.ts"],"sourcesContent":["import {\n createContext,\n ReactNode,\n RefObject,\n useContext,\n useMemo,\n} from \"react\";\nimport h from \"@macrostrat/hyper\";\nimport {\n CompositeColumnScale,\n createCompositeScale,\n} from \"../prepare-units/composite-scale\";\nimport { ColumnAxisType, ColumnProvider } from \"@macrostrat/column-components\";\nimport type { ExtUnit, PackageLayoutData } from \"../prepare-units\";\nimport {\n allowUnitSelectionAtom,\n selectedUnitIDAtom,\n UnitSelectionCallbacks,\n UnitSelectionCallbackManager,\n selectedUnitElementAtom,\n} from \"./unit-selection\";\nimport type { BaseUnit } from \"@macrostrat/api-types\";\nimport {\n type AtomMap,\n createScopedStore,\n StateIsolation,\n} from \"@macrostrat/scoped-store\";\nimport { atom } from \"jotai\";\nimport { useEffect } from \"react\";\n\nexport const scope: StateIsolation = createScopedStore();\n\nexport const columnUnitsAtom = atom<BaseUnit[]>();\n\nexport const columnUnitsMapAtom = atom<Map<number, BaseUnit> | null>((get) => {\n const units = get(columnUnitsAtom);\n if (!units) return null;\n const unitMap = new Map<number, BaseUnit>();\n units.forEach((unit) => {\n unitMap.set(unit.unit_id, unit);\n });\n return unitMap;\n});\n\nexport interface ColumnStateProviderProps<\n T extends BaseUnit,\n> extends Partial<UnitSelectionCallbacks> {\n children: ReactNode;\n units: T[];\n selectedUnit: number | null;\n allowUnitSelection?: boolean;\n}\n\nexport function MacrostratColumnStateProvider<T extends BaseUnit>({\n children,\n units,\n allowUnitSelection = false,\n onUnitSelected,\n selectedUnit,\n}: ColumnStateProviderProps<T>) {\n /** Top-level provider for Macrostrat column data.\n * It is either provided by the Column component itself, or\n * can be hoisted higher in the tree to provide a common data context\n */\n\n /* By default, unit selection is disabled. However, if any related props are passed,\n we enable it.\n */\n const _allowSelection = useMemo(() => {\n if (allowUnitSelection) {\n return true;\n }\n return selectedUnit != null || onUnitSelected != null;\n }, []);\n\n const atomMap: AtomMap = [\n [columnUnitsAtom, units],\n [allowUnitSelectionAtom, _allowSelection],\n [selectedUnitIDAtom, selectedUnit],\n ];\n\n let selectionHandlers: ReactNode = null;\n if (_allowSelection) {\n selectionHandlers = h(UnitSelectionCallbackManager, { onUnitSelected });\n }\n\n return h(\n scope.Provider,\n {\n atoms: atomMap,\n keepUpdated: true,\n inherit: true,\n },\n [selectionHandlers, children],\n );\n}\n\n/** Interface for imperative handlers that can\n * be invoked outside of the column's react context\n */\nexport interface ColumnRef {\n scrollSelectedUnitIntoView(): void;\n}\n\nexport interface MacrostratColumnDataContext<T extends BaseUnit> {\n units: T[];\n sections: PackageLayoutData[];\n totalHeight?: number;\n axisType?: ColumnAxisType;\n allowUnitSelection?: boolean;\n}\n\nexport interface ColumnDataProviderProps<T extends BaseUnit>\n extends MacrostratColumnDataContext<T>, ColumnStateProviderProps<T> {\n children: ReactNode;\n ref: RefObject<ColumnRef>;\n}\n\nconst MacrostratColumnDataContext =\n createContext<MacrostratColumnDataContext<any>>(null);\n\nexport function MacrostratColumnDataProvider<T extends BaseUnit>({\n children,\n units,\n sections,\n totalHeight,\n axisType,\n allowUnitSelection,\n onUnitSelected,\n selectedUnit,\n ref,\n}: ColumnDataProviderProps<T>) {\n /** Internal provider for Macrostrat column data.\n * As a general rule, we want to provide data and column-axis\n * height calculations through the context, since these need to\n * be accessed by any component that lays out information on the\n * column.\n *\n * Cross-axis layout and view configuration (e.g., showing and hiding\n * of different components or labels) should be handled through passing\n * props to the components themselves.\n * */\n\n const value = useMemo(() => {\n // For now, change ordinal axis types to age axis types\n return {\n units,\n sections,\n totalHeight,\n axisType,\n };\n }, [units, sections, totalHeight, axisType]);\n\n return h(\n MacrostratColumnStateProvider,\n {\n units,\n allowUnitSelection,\n onUnitSelected,\n selectedUnit,\n ref,\n },\n [\n h(ColumnRefManager, { ref }),\n h(MacrostratColumnDataContext.Provider, { value }, children),\n ],\n );\n}\n\nfunction ColumnRefManager({ ref }: { ref?: RefObject<ColumnRef> }) {\n const selectedUnitElement = scope.useAtomValue(selectedUnitElementAtom);\n useEffect(() => {\n if (ref == null) return;\n ref.current = {\n scrollSelectedUnitIntoView(opts?: ScrollIntoViewOptions) {\n selectedUnitElement?.scrollIntoView(\n opts ?? {\n behavior: \"smooth\",\n block: \"center\",\n inline: \"nearest\",\n },\n );\n },\n };\n }, [ref, selectedUnitElement]);\n\n return null;\n}\n\nexport function UnitSelectionProvider(props: ColumnStateProviderProps<any>) {\n /* A basic unit selection provider without column data context.\n Mostly for use with the CorrelationChart component.\n */\n return h(MacrostratColumnStateProvider, {\n ...props,\n allowUnitSelection: true,\n });\n}\n\nexport function useMacrostratColumnData() {\n const ctx = useContext(MacrostratColumnDataContext);\n if (!ctx) {\n throw new Error(\n \"useMacrostratColumnData must be used within a MacrostratColumnDataProvider\",\n );\n }\n return ctx;\n}\n\nexport function useMacrostratUnits() {\n return scope.useAtomValue(columnUnitsAtom);\n}\n\nexport function useColumnUnitsMap(): Map<number, ExtUnit> | null {\n try {\n return scope.useAtomValue(columnUnitsMapAtom) as Map<number, ExtUnit>;\n } catch {\n return null;\n }\n}\n\nexport function useCompositeScale(): CompositeColumnScale {\n const ctx = useMacrostratColumnData();\n return useMemo(\n () => createCompositeScale(ctx.sections, true),\n [ctx.sections],\n );\n}\n\nexport function MacrostratColumnProvider(props) {\n /** A column provider specialized the Macrostrat API. Maps more\n * generic concepts to Macrostrat-specific ones.\n */\n\n const { axisType } = useMacrostratColumnData();\n const { units, domain, pixelScale, scale, children } = props;\n return h(\n ColumnProvider,\n {\n axisType,\n divisions: units,\n range: domain,\n pixelsPerMeter: pixelScale,\n scale,\n },\n children,\n );\n}\n\n/** This is now a legacy provider */\nexport function LithologiesProvider({ children }) {\n useEffect(() => {\n console.warn(\n \"LithologiesProvider is deprecated. Replace with MacrostratDataProvider\",\n );\n }, []);\n return children;\n}\n"],"names":[],"mappings":";;;;;;;AA8BO,MAAM,QAAwB,kBAAA;AAE9B,MAAM,kBAAkB,KAAA;AAExB,MAAM,qBAAqB,KAAmC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vD,SAAO;AAAA,IACL;AAAA,IACA;AAAA,MACE;AAAA,MACA,WAAW;AAAA,MACX,OAAO;AAAA,MACP,gBAAgB;AAAA,MAChB;AAAA,IAAA;AAAA,IAEF;AAAA,EAAA;AAEJ;AAGO,SAAS,oBAAoB,EAAE,YAAY;AAChD,YAAU,MAAM;AACd,YAAQ;AAAA,MACN;AAAA,IAAA;AAAA,EAEJ,GAAG,CAAA,CAAE;AACL,SAAO;AACT;"}
1
+ {"version":3,"file":"store.js","sources":["../../src/data-provider/store.ts"],"sourcesContent":["import {\n createContext,\n ReactNode,\n RefObject,\n useContext,\n useMemo,\n} from \"react\";\nimport h from \"@macrostrat/hyper\";\nimport {\n CompositeColumnScale,\n createCompositeScale,\n} from \"../prepare-units/composite-scale\";\nimport { ColumnAxisType, ColumnProvider } from \"@macrostrat/column-components\";\nimport type { ExtUnit, PackageLayoutData } from \"../prepare-units\";\nimport {\n allowUnitSelectionAtom,\n selectedUnitIDAtom,\n UnitSelectionCallbacks,\n UnitSelectionCallbackManager,\n selectedUnitElementAtom,\n} from \"./unit-selection\";\nimport type { BaseUnit } from \"@macrostrat/api-types\";\nimport {\n type AtomMap,\n createScopedStore,\n StateIsolation,\n} from \"@macrostrat/scoped-store\";\nimport { atom } from \"jotai\";\nimport { useEffect } from \"react\";\n\nexport const scope: StateIsolation = createScopedStore();\n\nexport const columnUnitsAtom = atom<BaseUnit[]>();\n\nexport const columnUnitsMapAtom = atom<Map<number, BaseUnit> | null>((get) => {\n const units = get(columnUnitsAtom);\n if (!units) return null;\n const unitMap = new Map<number, BaseUnit>();\n units.forEach((unit) => {\n unitMap.set(unit.unit_id, unit);\n });\n return unitMap;\n});\n\nexport interface ColumnStateProviderProps<\n T extends BaseUnit,\n> extends Partial<UnitSelectionCallbacks> {\n children: ReactNode;\n units: T[];\n selectedUnit: number | null;\n allowUnitSelection?: boolean;\n}\n\nexport function MacrostratColumnStateProvider<T extends BaseUnit>({\n children,\n units,\n allowUnitSelection = false,\n onUnitSelected,\n selectedUnit,\n}: ColumnStateProviderProps<T>) {\n /** Top-level provider for Macrostrat column data.\n * It is either provided by the Column component itself, or\n * can be hoisted higher in the tree to provide a common data context\n */\n\n /* By default, unit selection is disabled. However, if any related props are passed,\n we enable it.\n */\n const _allowSelection = useMemo(() => {\n if (allowUnitSelection) {\n return true;\n }\n return selectedUnit != null || onUnitSelected != null;\n }, []);\n\n // Check if we're already in a columnStateProvider, and render a no-op if so\n const existingUnits = scope.useAtomValueIfExists(columnUnitsAtom);\n if (existingUnits != null) {\n if (allowUnitSelection || onUnitSelected || selectedUnit != null) {\n console.warn(\n \"MacrostratColumnStateProvider: unit selection props are ignored because a provider already exists in the tree\",\n );\n }\n return children;\n }\n\n const atomMap: AtomMap = [\n [columnUnitsAtom, units],\n [allowUnitSelectionAtom, _allowSelection],\n [selectedUnitIDAtom, selectedUnit],\n ];\n\n let selectionHandlers: ReactNode = null;\n if (_allowSelection) {\n selectionHandlers = h(UnitSelectionCallbackManager, { onUnitSelected });\n }\n\n return h(\n scope.Provider,\n {\n atoms: atomMap,\n keepUpdated: true,\n },\n [selectionHandlers, children],\n );\n}\n\n/** Interface for imperative handlers that can\n * be invoked outside of the column's react context\n */\nexport interface ColumnRef {\n scrollSelectedUnitIntoView(): void;\n}\n\nexport interface MacrostratColumnDataContext<T extends BaseUnit> {\n units: T[];\n sections: PackageLayoutData[];\n totalHeight?: number;\n axisType?: ColumnAxisType;\n allowUnitSelection?: boolean;\n}\n\nexport interface ColumnDataProviderProps<T extends BaseUnit>\n extends MacrostratColumnDataContext<T>, ColumnStateProviderProps<T> {\n children: ReactNode;\n ref: RefObject<ColumnRef>;\n}\n\nconst MacrostratColumnDataContext =\n createContext<MacrostratColumnDataContext<any>>(null);\n\nexport function MacrostratColumnDataProvider<T extends BaseUnit>({\n children,\n units,\n sections,\n totalHeight,\n axisType,\n allowUnitSelection,\n onUnitSelected,\n selectedUnit,\n ref,\n}: ColumnDataProviderProps<T>) {\n /** Internal provider for Macrostrat column data.\n * As a general rule, we want to provide data and column-axis\n * height calculations through the context, since these need to\n * be accessed by any component that lays out information on the\n * column.\n *\n * Cross-axis layout and view configuration (e.g., showing and hiding\n * of different components or labels) should be handled through passing\n * props to the components themselves.\n * */\n\n const value = useMemo(() => {\n // For now, change ordinal axis types to age axis types\n return {\n units,\n sections,\n totalHeight,\n axisType,\n };\n }, [units, sections, totalHeight, axisType]);\n\n return h(\n MacrostratColumnStateProvider,\n {\n units,\n allowUnitSelection,\n onUnitSelected,\n selectedUnit,\n ref,\n },\n [\n h(ColumnRefManager, { ref }),\n h(MacrostratColumnDataContext.Provider, { value }, children),\n ],\n );\n}\n\nfunction ColumnRefManager({ ref }: { ref?: RefObject<ColumnRef> }) {\n const selectedUnitElement = scope.useAtomValue(selectedUnitElementAtom);\n useEffect(() => {\n if (ref == null) return;\n ref.current = {\n scrollSelectedUnitIntoView(opts?: ScrollIntoViewOptions) {\n selectedUnitElement?.scrollIntoView(\n opts ?? {\n behavior: \"smooth\",\n block: \"center\",\n inline: \"nearest\",\n },\n );\n },\n };\n }, [ref, selectedUnitElement]);\n\n return null;\n}\n\nexport function UnitSelectionProvider(props: ColumnStateProviderProps<any>) {\n /* A basic unit selection provider without column data context.\n Mostly for use with the CorrelationChart component.\n */\n return h(MacrostratColumnStateProvider, {\n ...props,\n allowUnitSelection: true,\n });\n}\n\nexport function useMacrostratColumnData() {\n const ctx = useContext(MacrostratColumnDataContext);\n if (!ctx) {\n throw new Error(\n \"useMacrostratColumnData must be used within a MacrostratColumnDataProvider\",\n );\n }\n return ctx;\n}\n\nexport function useMacrostratUnits() {\n return scope.useAtomValue(columnUnitsAtom);\n}\n\nexport function useColumnUnitsMap(): Map<number, ExtUnit> | null {\n try {\n return scope.useAtomValue(columnUnitsMapAtom) as Map<number, ExtUnit>;\n } catch {\n return null;\n }\n}\n\nexport function useCompositeScale(): CompositeColumnScale {\n const ctx = useMacrostratColumnData();\n return useMemo(\n () => createCompositeScale(ctx.sections, true),\n [ctx.sections],\n );\n}\n\nexport function MacrostratColumnProvider(props) {\n /** A column provider specialized the Macrostrat API. Maps more\n * generic concepts to Macrostrat-specific ones.\n */\n\n const { axisType } = useMacrostratColumnData();\n const { units, domain, pixelScale, scale, children } = props;\n return h(\n ColumnProvider,\n {\n axisType,\n divisions: units,\n range: domain,\n pixelsPerMeter: pixelScale,\n scale,\n },\n children,\n );\n}\n\n/** This is now a legacy provider */\nexport function LithologiesProvider({ children }) {\n useEffect(() => {\n console.warn(\n \"LithologiesProvider is deprecated. Replace with MacrostratDataProvider\",\n );\n }, []);\n return children;\n}\n"],"names":[],"mappings":";;;;;;;AA8BO,MAAM,QAAwB,kBAAA;AAE9B,MAAM,kBAAkB,KAAA;AAExB,MAAM,qBAAqB,KAAmC,CAAC,QAAQ;AAC5E,QAAM,QAAQ,IAAI,eAAe;AACjC,MAAI,CAAC,MAAO,QAAO;AACnB,QAAM,8BAAc,IAAA;AACpB,QAAM,QAAQ,CAAC,SAAS;AACtB,YAAQ,IAAI,KAAK,SAAS,IAAI;AAAA,EAChC,CAAC;AACD,SAAO;AACT,CAAC;AAWM,SAAS,8BAAkD;AAAA,EAChE;AAAA,EACA;AAAA,EACA,qBAAqB;AAAA,EACrB;AAAA,EACA;AACF,GAAgC;AAS9B,QAAM,kBAAkB,QAAQ,MAAM;AACpC,QAAI,oBAAoB;AACtB,aAAO;AAAA,IACT;AACA,WAAO,gBAAgB,QAAQ,kBAAkB;AAAA,EACnD,GAAG,CAAA,CAAE;AAGL,QAAM,gBAAgB,MAAM,qBAAqB,eAAe;AAChE,MAAI,iBAAiB,MAAM;AACzB,QAAI,sBAAsB,kBAAkB,gBAAgB,MAAM;AAChE,cAAQ;AAAA,QACN;AAAA,MAAA;AAAA,IAEJ;AACA,WAAO;AAAA,EACT;AAEA,QAAM,UAAmB;AAAA,IACvB,CAAC,iBAAiB,KAAK;AAAA,IACvB,CAAC,wBAAwB,eAAe;AAAA,IACxC,CAAC,oBAAoB,YAAY;AAAA,EA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IACtC,GAAG;AAAA,IACH,oBAAoB;AAAA,EAAA,CACrB;AACH;AAEO,SAAS,0BAA0B;AACxC,QAAM,MAAM,WAAW,2BAA2B;AAClD,MAAI,CAAC,KAAK;AACR,UAAM,IAAI;AAAA,MACR;AAAA,IAAA;AAAA,EAEJ;AACA,SAAO;AACT;AAEO,SAAS,qBAAqB;AACnC,SAAO,MAAM,aAAa,eAAe;AAC3C;AAEO,SAAS,oBAAiD;AAC/D,MAAI;AACF,WAAO,MAAM,aAAa,kBAAkB;AAAA,EAC9C,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEO,SAAS,oBAA0C;AACxD,QAAM,MAAM,wBAAA;AACZ,SAAO;AAAA,IACL,MAAM,qBAAqB,IAAI,UAAU,IAAI;AAAA,IAC7C,CAAC,IAAI,QAAQ;AAAA,EAAA;AAEjB;AAEO,SAAS,yBAAyB,OAAO;AAK9C,QAAM,EAAE,SAAA,IAAa,wBAAA;AACrB,QAAM,EAAE,OAAO,QAAQ,YAAY,OAAO,aAAa;AACvD,SAAO;AAAA,IACL;AAAA,IACA;AAAA,MACE;AAAA,MACA,WAAW;AAAA,MACX,OAAO;AAAA,MACP,gBAAgB;AAAA,MAChB;AAAA,IAAA;AAAA,IAEF;AAAA,EAAA;AAEJ;AAGO,SAAS,oBAAoB,EAAE,YAAY;AAChD,YAAU,MAAM;AACd,YAAQ;AAAA,MACN;AAAA,IAAA;AAAA,EAEJ,GAAG,CAAA,CAAE;AACL,SAAO;AACT;"}
@@ -88,6 +88,9 @@ function useUnitSelectionTarget(unit) {
88
88
  const [selectedUnit, selectUnit] = useUnitSelection();
89
89
  const selected = selectedUnit?.unit_id == unit.unit_id;
90
90
  const selectedUnitElement = store.scope.useAtomValue(selectedUnitElementAtom);
91
+ const selectedStratName = selectedUnit?.strat_name_id;
92
+ const unitStratName = unit?.strat_name_id;
93
+ const linked = !selected && selectedStratName != null && unitStratName != null && unitStratName === selectedStratName;
91
94
  const onClick = React.useCallback(
92
95
  (evt) => {
93
96
  selectUnit?.(unit, ref.current);
@@ -106,7 +109,7 @@ function useUnitSelectionTarget(unit) {
106
109
  inline: "nearest"
107
110
  });
108
111
  }, [selectedUnitElement]);
109
- return [ref, selected, onClick];
112
+ return [ref, selected, onClick, linked];
110
113
  }
111
114
  function UnitKeyboardNavigation({
112
115
  columnData,
@@ -1 +1 @@
1
- {"version":3,"file":"unit-selection.cjs","sources":["../../src/data-provider/unit-selection.ts"],"sourcesContent":["import type { BaseUnit, UnitLong } from \"@macrostrat/api-types\";\nimport { useKeyHandler } from \"@macrostrat/ui-components\";\nimport { useEffect, useRef, useCallback, useMemo } from \"react\";\nimport type { RectBounds, IUnit } from \"../units/types\";\nimport { atom } from \"jotai\";\nimport { scope, columnUnitsMapAtom } from \"./store\";\nimport {\n AgeRangeQuantifiedDifference,\n ageRangeQuantifiedDifference,\n AgeRangeRelationship,\n} from \"@macrostrat/stratigraphy-utils\";\nimport type { ColumnData } from \"@macrostrat/data-provider\";\n\ntype UnitSelectDispatch = (\n unit: number | BaseUnit | null,\n target: HTMLElement | null,\n) => void;\n\nexport function useUnitSelection() {\n return scope.use(selectedUnitAtom);\n}\n\nexport function useUnitSelectionDispatch(): UnitSelectDispatch {\n return scope.useSetAtom(selectedUnitAtom);\n}\n\nexport function useSelectedUnit() {\n return scope.useAtomValue(selectedUnitAtom);\n}\n\nexport interface ColumnClickData {\n unitID: number | null;\n unit: BaseUnit | null;\n target: HTMLElement | null;\n height: number;\n // Room for boundary IDs eventually\n}\n\nexport interface UnitSelectionCallbacks {\n // It's sort of unfortunate that we need to pass in the column ref here\n onClickedColumn?: (columnClickData: ColumnClickData, event: Event) => void;\n onUnitSelected?: <T extends BaseUnit>(\n unitID: number | null,\n unit: T | null,\n ) => void;\n}\n\nexport const allowUnitSelectionAtom = atom<boolean>(true);\n\nexport const selectedUnitIDAtom = atom<number | null>();\nexport const selectedUnitElementAtom = atom<HTMLElement | null>();\n\nconst overlayPositionAtom = atom<RectBounds | null>();\n\nconst columnRefAtom = atom<{ current: HTMLElement | null }>({ current: null });\n\nexport function useColumnRef() {\n return scope.useAtomValue(columnRefAtom);\n}\n\nconst selectedUnitAtom = atom(\n (get) => {\n if (!get(allowUnitSelectionAtom)) return null;\n\n const unitID = get(selectedUnitIDAtom);\n if (unitID == null) return null;\n const unitsMap = get(columnUnitsMapAtom);\n return unitsMap?.get(unitID) || null;\n },\n (\n get,\n set,\n selectedUnit: number | BaseUnit | null,\n target: HTMLElement | null = null,\n ): BaseUnit | null => {\n if (!get(allowUnitSelectionAtom)) {\n console.error(\"Unit selection is disabled.\");\n return null;\n }\n\n let unitID: number | null = null;\n let unit: BaseUnit | null = null;\n if (selectedUnit == null) {\n unitID = null;\n } else if (typeof selectedUnit === \"number\") {\n unitID = selectedUnit;\n } else if (\"unit_id\" in selectedUnit) {\n unitID = selectedUnit.unit_id;\n }\n\n if (unitID != null) {\n const unitsMap = get(columnUnitsMapAtom);\n // Verify that the unit exists in the current colum, else throw\n if (!unitsMap?.has(unitID)) {\n throw new Error(\n `Unit with ID ${unitID} not found in current column units.`,\n );\n }\n unit = unitsMap.get(unitID) ?? null;\n }\n\n let overlayPosition: RectBounds | null = null;\n\n const columnEl = get(columnRefAtom)?.current;\n\n if (unit != null && columnEl != null && target != null) {\n const rect = columnEl.getBoundingClientRect();\n const targetRect = target.getBoundingClientRect();\n overlayPosition = {\n x: targetRect.left - rect.left,\n y: targetRect.top - rect.top,\n width: targetRect.width,\n height: targetRect.height,\n };\n }\n\n set(selectedUnitElementAtom, target);\n set(selectedUnitIDAtom, unitID);\n set(overlayPositionAtom, overlayPosition);\n\n return unit;\n },\n);\n\nexport function useAtomOverlayPosition() {\n return scope.useAtomValue(overlayPositionAtom);\n}\n\nexport function UnitSelectionCallbackManager({\n onUnitSelected,\n}: UnitSelectionCallbacks) {\n const selectedUnit = scope.useAtomValue(selectedUnitAtom);\n useEffect(() => {\n onUnitSelected?.(selectedUnit?.unit_id ?? null, selectedUnit ?? null);\n }, [selectedUnit?.unit_id]);\n return null;\n}\n\n/** TODO: figure out if onClickedColumn is still needed\n /** This is not the natural place to get positions within the column,\n * but it will work for now.\nif (props.onClickedColumn) {\n // Infer height from top and bottom height of unit (because that's passed back with the call)\n //const py = event.y;\n //const [bottom, top] = getUnitHeightRange(unit, axisType);\n //const height = Math.abs(bottom - top);\n\n const columnClickData: ColumnClickData = {\n unitID: unit?.unit_id,\n unit,\n target,\n height: el?.getBoundingClientRect().height || 0,\n };\n props.onClickedColumn(columnClickData, event);\n}*/\n\nexport function useUnitSelectionTarget(\n unit: IUnit,\n): [React.RefObject<HTMLElement>, boolean, (evt: Event) => void] {\n const ref = useRef<HTMLElement>(null);\n const [selectedUnit, selectUnit] = useUnitSelection();\n const selected = selectedUnit?.unit_id == unit.unit_id;\n const selectedUnitElement = scope.useAtomValue(selectedUnitElementAtom);\n\n const onClick = useCallback(\n (evt: Event) => {\n selectUnit?.(unit, ref.current);\n evt.stopPropagation();\n },\n [unit, selectUnit],\n );\n\n useEffect(() => {\n // Sync selection with unit element...\n if (!selected) return;\n selectUnit?.(unit, ref.current);\n }, [ref.current, selected, selectUnit]);\n\n useEffect(() => {\n // Scroll the unit into view\n selectedUnitElement?.scrollIntoView({\n behavior: \"smooth\",\n block: \"center\",\n inline: \"nearest\",\n });\n }, [selectedUnitElement]);\n\n return [ref, selected, onClick];\n}\n\nexport function UnitKeyboardNavigation({\n columnData,\n units,\n allowHorizontalNavigation,\n}: {\n columnData?: ColumnData[];\n units?: UnitLong[];\n allowHorizontalNavigation?: boolean;\n}) {\n if (units == null && columnData == null) {\n throw new Error(\"Either units or columnData must be provided.\");\n }\n\n let _columnData: ColumnData[] = useMemo(() => {\n if (columnData != null) return columnData;\n // Build column data from units\n const colMap = new Map<number, UnitLong[]>();\n for (const unit of units!) {\n if (!colMap.has(unit.col_id)) {\n colMap.set(unit.col_id, []);\n }\n colMap.get(unit.col_id)!.push(unit);\n }\n const cols: ColumnData[] = [];\n for (const [colID, units] of colMap) {\n cols.push({ columnID: colID, units });\n }\n // Sort columns by columnID\n cols.sort((a, b) => a.columnID - b.columnID);\n return cols;\n }, [columnData, units]);\n\n // Default to allowing horizontal navigation only if columnData is provided\n const _allowHorizontalNavigation =\n allowHorizontalNavigation ?? columnData != null;\n\n const selectedUnit = useSelectedUnit() as UnitLong | null;\n const selectUnit = useUnitSelectionDispatch();\n\n const keyMap: Record<number, Direction> = {\n 38: \"up\",\n 40: \"down\",\n };\n if (_allowHorizontalNavigation) {\n keyMap[37] = \"left\";\n keyMap[39] = \"right\";\n }\n\n useKeyHandler(\n (event) => {\n const direction = keyMap[event.keyCode];\n if (direction == null) return;\n const nextUnit = getBestUnit(_columnData, selectedUnit, direction);\n if (nextUnit == null) return;\n selectUnit(nextUnit, null);\n event.stopPropagation();\n },\n [_columnData, selectedUnit],\n );\n return null;\n}\n\ntype Direction = \"up\" | \"down\" | \"left\" | \"right\";\n\nfunction getBestUnit(\n columnData: ColumnData[],\n targetUnit: UnitLong,\n direction: Direction,\n): UnitLong | null {\n const thisColIndex = columnData.findIndex(\n (col) => col.columnID === targetUnit.col_id,\n );\n if (thisColIndex === -1) return null;\n\n // If up or down, stay in the same column\n if (direction === \"up\" || direction === \"down\") {\n const units = columnData[thisColIndex].units;\n const ix = units.findIndex((unit) => unit.unit_id === targetUnit.unit_id);\n if (ix === -1) return null;\n if (direction === \"up\") {\n return units[ix - 1] || null;\n } else {\n return units[ix + 1] || null;\n }\n }\n\n // If left or right, move to adjacent column\n let adjacentColIndex: number;\n if (direction === \"left\") {\n adjacentColIndex =\n (thisColIndex - 1 + columnData.length) % columnData.length;\n } else {\n adjacentColIndex = (thisColIndex + 1) % columnData.length;\n }\n\n const adjacentColUnits = columnData[adjacentColIndex].units;\n return getMostOverlappingUnit(targetUnit, adjacentColUnits);\n}\n\ntype UnitAgeRangeRelationship = AgeRangeQuantifiedDifference & {\n unit: UnitLong;\n};\n\nfunction getMostOverlappingUnit(\n targetUnit: UnitLong,\n candidateUnits: UnitLong[],\n): UnitLong | null {\n const targetAgeRange = [targetUnit.b_age, targetUnit.t_age];\n\n const overlaps: UnitAgeRangeRelationship[] = [];\n for (const candidate of candidateUnits) {\n const candidateAgeRange = [candidate.b_age, candidate.t_age];\n\n const rel = ageRangeQuantifiedDifference(targetAgeRange, candidateAgeRange);\n if (rel.type === AgeRangeRelationship.Identical) {\n return candidate;\n }\n overlaps.push({ ...rel, unit: candidate });\n }\n\n let bestOverlaps = overlaps.filter(\n (d) => d.type === AgeRangeRelationship.Containing,\n );\n bestOverlaps.sort((a, b) => b.overlap - a.overlap);\n if (bestOverlaps.length > 0) {\n return bestOverlaps[0].unit;\n }\n\n bestOverlaps = overlaps.filter(\n (d) => d.type === AgeRangeRelationship.Contained,\n );\n bestOverlaps.sort((a, b) => b.overlap - a.overlap);\n if (bestOverlaps.length > 0) {\n return bestOverlaps[0].unit;\n }\n\n bestOverlaps = overlaps.filter(\n (d) => d.type === AgeRangeRelationship.PartialOverlap,\n );\n bestOverlaps.sort((a, b) => b.overlap - a.overlap);\n if (bestOverlaps.length > 0) {\n return bestOverlaps[0].unit;\n }\n\n bestOverlaps = overlaps.filter(\n (d) => d.type === AgeRangeRelationship.Disjoint,\n );\n bestOverlaps.sort((a, b) => a.distance - b.distance);\n if (bestOverlaps.length > 0) {\n return bestOverlaps[0].unit;\n }\n return null;\n}\n"],"names":["scope","atom","columnUnitsMapAtom","useEffect","useRef","useCallback","useMemo","units","useKeyHandler","ageRangeQuantifiedDifference","AgeRangeRelationship"],"mappings":";;;;;;;AAkBO,SAAS,mBAAmB;AACjC,SAAOA,MAAAA,MAAM,IAAI,gBAAgB;AACnC;AAEO,SAAS,2BAA+C;AAC7D,SAAOA,MAAAA,MAAM,WAAW,gBAAgB;AAC1C;AAEO,SAAS,kBAAkB;AAChC,SAAOA,MAAAA,MAAM,aAAa,gBAAgB;AAC5C;AAmBO,MAAM,yBAAyBC,MAAAA,KAAc,IAAI;AAEjD,MAAM,qBAAqBA,MAAAA,KAAA;AAC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AAA,EAAA;AAEzC,eAAa,KAAK,CAAC,GAAG,MAAM,EAAE,UAAU,EAAE,OAAO;AACjD,MAAI,aAAa,SAAS,GAAG;AAC3B,WAAO,aAAa,CAAC,EAAE;AAAA,EACzB;AAEA,iBAAe,SAAS;AAAA,IACtB,CAAC,MAAM,EAAE,SAASA,uCAAqB;AAAA,EAAA;AAEzC,eAAa,KAAK,CAAC,GAAG,MAAM,EAAE,UAAU,EAAE,OAAO;AACjD,MAAI,aAAa,SAAS,GAAG;AAC3B,WAAO,aAAa,CAAC,EAAE;AAAA,EACzB;AAEA,iBAAe,SAAS;AAAA,IACtB,CAAC,MAAM,EAAE,SAASA,uCAAqB;AAAA,EAAA;AAEzC,eAAa,KAAK,CAAC,GAAG,MAAM,EAAE,WAAW,EAAE,QAAQ;AACnD,MAAI,aAAa,SAAS,GAAG;AAC3B,WAAO,aAAa,CAAC,EAAE;AAAA,EACzB;AACA,SAAO;AACT;;;;;;;;;;;;"}
1
+ {"version":3,"file":"unit-selection.cjs","sources":["../../src/data-provider/unit-selection.ts"],"sourcesContent":["import type { BaseUnit, UnitLong } from \"@macrostrat/api-types\";\nimport { useKeyHandler } from \"@macrostrat/ui-components\";\nimport { useEffect, useRef, useCallback, useMemo } from \"react\";\nimport type { RectBounds, IUnit } from \"../units/types\";\nimport { atom } from \"jotai\";\nimport { scope, columnUnitsMapAtom } from \"./store\";\nimport {\n AgeRangeQuantifiedDifference,\n ageRangeQuantifiedDifference,\n AgeRangeRelationship,\n} from \"@macrostrat/stratigraphy-utils\";\nimport type { ColumnData } from \"@macrostrat/data-provider\";\n\ntype UnitSelectDispatch = (\n unit: number | BaseUnit | null,\n target: HTMLElement | null,\n) => void;\n\nexport function useUnitSelection() {\n return scope.use(selectedUnitAtom);\n}\n\nexport function useUnitSelectionDispatch(): UnitSelectDispatch {\n return scope.useSetAtom(selectedUnitAtom);\n}\n\nexport function useSelectedUnit() {\n return scope.useAtomValue(selectedUnitAtom);\n}\n\nexport interface ColumnClickData {\n unitID: number | null;\n unit: BaseUnit | null;\n target: HTMLElement | null;\n height: number;\n // Room for boundary IDs eventually\n}\n\nexport interface UnitSelectionCallbacks {\n // It's sort of unfortunate that we need to pass in the column ref here\n onClickedColumn?: (columnClickData: ColumnClickData, event: Event) => void;\n onUnitSelected?: <T extends BaseUnit>(\n unitID: number | null,\n unit: T | null,\n ) => void;\n}\n\nexport const allowUnitSelectionAtom = atom<boolean>(true);\n\nexport const selectedUnitIDAtom = atom<number | null>();\nexport const selectedUnitElementAtom = atom<HTMLElement | null>();\n\nconst overlayPositionAtom = atom<RectBounds | null>();\n\nconst columnRefAtom = atom<{ current: HTMLElement | null }>({ current: null });\n\nexport function useColumnRef() {\n return scope.useAtomValue(columnRefAtom);\n}\n\nconst selectedUnitAtom = atom(\n (get) => {\n if (!get(allowUnitSelectionAtom)) return null;\n\n const unitID = get(selectedUnitIDAtom);\n if (unitID == null) return null;\n const unitsMap = get(columnUnitsMapAtom);\n return unitsMap?.get(unitID) || null;\n },\n (\n get,\n set,\n selectedUnit: number | BaseUnit | null,\n target: HTMLElement | null = null,\n ): BaseUnit | null => {\n if (!get(allowUnitSelectionAtom)) {\n console.error(\"Unit selection is disabled.\");\n return null;\n }\n\n let unitID: number | null = null;\n let unit: BaseUnit | null = null;\n if (selectedUnit == null) {\n unitID = null;\n } else if (typeof selectedUnit === \"number\") {\n unitID = selectedUnit;\n } else if (\"unit_id\" in selectedUnit) {\n unitID = selectedUnit.unit_id;\n }\n\n if (unitID != null) {\n const unitsMap = get(columnUnitsMapAtom);\n // Verify that the unit exists in the current colum, else throw\n if (!unitsMap?.has(unitID)) {\n throw new Error(\n `Unit with ID ${unitID} not found in current column units.`,\n );\n }\n unit = unitsMap.get(unitID) ?? null;\n }\n\n let overlayPosition: RectBounds | null = null;\n\n const columnEl = get(columnRefAtom)?.current;\n\n if (unit != null && columnEl != null && target != null) {\n const rect = columnEl.getBoundingClientRect();\n const targetRect = target.getBoundingClientRect();\n overlayPosition = {\n x: targetRect.left - rect.left,\n y: targetRect.top - rect.top,\n width: targetRect.width,\n height: targetRect.height,\n };\n }\n\n set(selectedUnitElementAtom, target);\n set(selectedUnitIDAtom, unitID);\n set(overlayPositionAtom, overlayPosition);\n\n return unit;\n },\n);\n\nexport function useAtomOverlayPosition() {\n return scope.useAtomValue(overlayPositionAtom);\n}\n\nexport function UnitSelectionCallbackManager({\n onUnitSelected,\n}: UnitSelectionCallbacks) {\n const selectedUnit = scope.useAtomValue(selectedUnitAtom);\n useEffect(() => {\n onUnitSelected?.(selectedUnit?.unit_id ?? null, selectedUnit ?? null);\n }, [selectedUnit?.unit_id]);\n return null;\n}\n\n/** TODO: figure out if onClickedColumn is still needed\n /** This is not the natural place to get positions within the column,\n * but it will work for now.\nif (props.onClickedColumn) {\n // Infer height from top and bottom height of unit (because that's passed back with the call)\n //const py = event.y;\n //const [bottom, top] = getUnitHeightRange(unit, axisType);\n //const height = Math.abs(bottom - top);\n\n const columnClickData: ColumnClickData = {\n unitID: unit?.unit_id,\n unit,\n target,\n height: el?.getBoundingClientRect().height || 0,\n };\n props.onClickedColumn(columnClickData, event);\n}*/\n\nexport function useUnitSelectionTarget(\n unit: IUnit,\n): [React.RefObject<HTMLElement>, boolean, (evt: Event) => void, boolean] {\n const ref = useRef<HTMLElement>(null);\n const [selectedUnit, selectUnit] = useUnitSelection();\n const selected = selectedUnit?.unit_id == unit.unit_id;\n const selectedUnitElement = scope.useAtomValue(selectedUnitElementAtom);\n\n // \"Linked\" units share a stratigraphic name with the selected unit (e.g.\n // the same formation correlated across columns), but are not the selection\n // itself. They receive a subtler highlight.\n const selectedStratName = (selectedUnit as any)?.strat_name_id;\n const unitStratName = (unit as any)?.strat_name_id;\n const linked =\n !selected &&\n selectedStratName != null &&\n unitStratName != null &&\n unitStratName === selectedStratName;\n\n const onClick = useCallback(\n (evt: Event) => {\n selectUnit?.(unit, ref.current);\n evt.stopPropagation();\n },\n [unit, selectUnit],\n );\n\n useEffect(() => {\n // Sync selection with unit element...\n if (!selected) return;\n selectUnit?.(unit, ref.current);\n }, [ref.current, selected, selectUnit]);\n\n useEffect(() => {\n // Scroll the unit into view\n selectedUnitElement?.scrollIntoView({\n behavior: \"smooth\",\n block: \"center\",\n inline: \"nearest\",\n });\n }, [selectedUnitElement]);\n\n return [ref, selected, onClick, linked];\n}\n\nexport function UnitKeyboardNavigation({\n columnData,\n units,\n allowHorizontalNavigation,\n}: {\n columnData?: ColumnData[];\n units?: UnitLong[];\n allowHorizontalNavigation?: boolean;\n}) {\n if (units == null && columnData == null) {\n throw new Error(\"Either units or columnData must be provided.\");\n }\n\n let _columnData: ColumnData[] = useMemo(() => {\n if (columnData != null) return columnData;\n // Build column data from units\n const colMap = new Map<number, UnitLong[]>();\n for (const unit of units!) {\n if (!colMap.has(unit.col_id)) {\n colMap.set(unit.col_id, []);\n }\n colMap.get(unit.col_id)!.push(unit);\n }\n const cols: ColumnData[] = [];\n for (const [colID, units] of colMap) {\n cols.push({ columnID: colID, units });\n }\n // Sort columns by columnID\n cols.sort((a, b) => a.columnID - b.columnID);\n return cols;\n }, [columnData, units]);\n\n // Default to allowing horizontal navigation only if columnData is provided\n const _allowHorizontalNavigation =\n allowHorizontalNavigation ?? columnData != null;\n\n const selectedUnit = useSelectedUnit() as UnitLong | null;\n const selectUnit = useUnitSelectionDispatch();\n\n const keyMap: Record<number, Direction> = {\n 38: \"up\",\n 40: \"down\",\n };\n if (_allowHorizontalNavigation) {\n keyMap[37] = \"left\";\n keyMap[39] = \"right\";\n }\n\n useKeyHandler(\n (event) => {\n const direction = keyMap[event.keyCode];\n if (direction == null) return;\n const nextUnit = getBestUnit(_columnData, selectedUnit, direction);\n if (nextUnit == null) return;\n selectUnit(nextUnit, null);\n event.stopPropagation();\n },\n [_columnData, selectedUnit],\n );\n return null;\n}\n\ntype Direction = \"up\" | \"down\" | \"left\" | \"right\";\n\nfunction getBestUnit(\n columnData: ColumnData[],\n targetUnit: UnitLong,\n direction: Direction,\n): UnitLong | null {\n const thisColIndex = columnData.findIndex(\n (col) => col.columnID === targetUnit.col_id,\n );\n if (thisColIndex === -1) return null;\n\n // If up or down, stay in the same column\n if (direction === \"up\" || direction === \"down\") {\n const units = columnData[thisColIndex].units;\n const ix = units.findIndex((unit) => unit.unit_id === targetUnit.unit_id);\n if (ix === -1) return null;\n if (direction === \"up\") {\n return units[ix - 1] || null;\n } else {\n return units[ix + 1] || null;\n }\n }\n\n // If left or right, move to adjacent column\n let adjacentColIndex: number;\n if (direction === \"left\") {\n adjacentColIndex =\n (thisColIndex - 1 + columnData.length) % columnData.length;\n } else {\n adjacentColIndex = (thisColIndex + 1) % columnData.length;\n }\n\n const adjacentColUnits = columnData[adjacentColIndex].units;\n return getMostOverlappingUnit(targetUnit, adjacentColUnits);\n}\n\ntype UnitAgeRangeRelationship = AgeRangeQuantifiedDifference & {\n unit: UnitLong;\n};\n\nfunction getMostOverlappingUnit(\n targetUnit: UnitLong,\n candidateUnits: UnitLong[],\n): UnitLong | null {\n const targetAgeRange = [targetUnit.b_age, targetUnit.t_age];\n\n const overlaps: UnitAgeRangeRelationship[] = [];\n for (const candidate of candidateUnits) {\n const candidateAgeRange = [candidate.b_age, candidate.t_age];\n\n const rel = ageRangeQuantifiedDifference(targetAgeRange, candidateAgeRange);\n if (rel.type === AgeRangeRelationship.Identical) {\n return candidate;\n }\n overlaps.push({ ...rel, unit: candidate });\n }\n\n let bestOverlaps = overlaps.filter(\n (d) => d.type === AgeRangeRelationship.Containing,\n );\n bestOverlaps.sort((a, b) => b.overlap - a.overlap);\n if (bestOverlaps.length > 0) {\n return bestOverlaps[0].unit;\n }\n\n bestOverlaps = overlaps.filter(\n (d) => d.type === AgeRangeRelationship.Contained,\n );\n bestOverlaps.sort((a, b) => b.overlap - a.overlap);\n if (bestOverlaps.length > 0) {\n return bestOverlaps[0].unit;\n }\n\n bestOverlaps = overlaps.filter(\n (d) => d.type === AgeRangeRelationship.PartialOverlap,\n );\n bestOverlaps.sort((a, b) => b.overlap - a.overlap);\n if (bestOverlaps.length > 0) {\n return bestOverlaps[0].unit;\n }\n\n bestOverlaps = overlaps.filter(\n (d) => d.type === AgeRangeRelationship.Disjoint,\n );\n bestOverlaps.sort((a, b) => a.distance - b.distance);\n if (bestOverlaps.length > 0) {\n return bestOverlaps[0].unit;\n }\n return null;\n}\n"],"names":["scope","atom","columnUnitsMapAtom","useEffect","useRef","useCallback","useMemo","units","useKeyHandler","ageRangeQuantifiedDifference","AgeRangeRelationship"],"mappings":";;;;;;;AAkBO,SAAS,mBAAmB;AACjC,SAAOA,MAAAA,MAAM,IAAI,gBAAgB;AACnC;AAEO,SAAS,2BAA+C;AAC7D,SAAOA,MAAAA,MAAM,WAAW,gBAAgB;AAC1C;AAEO,SAAS,kBAAkB;AAChC,SAAOA,MAAAA,MAAM,aAAa,gBAAgB;AAC5C;AAmBO,MAAM,yBAAyBC,MAAAA,KAAc,IAAI;AAEjD,MAAM,qBAAqBA,MAAAA,KAAA;AAC3B,MAAM,0BAA0BA,MAAAA,KAAA;AAEvC,MAAM,sBAAsBA,MAAAA,KAAA;AAE5B,MAAM,gBAAgBA,MAAAA,KAAsC,EAAE,SAAS,MAAM;AAEtE,SAAS,eAAe;AAC7B,SAAOD,MAAAA,MAAM,aAAa,aAAa;AACzC;AAEA,MAAM,mBAAmBC,MAAAA;AAAAA,EACvB,CAAC,QAAQ;AACP,QAAI,CAAC,IAAI,sBAAsB,EAAG,QAAO;AAEzC,UAAM,SAAS,IAAI,kBAAkB;AACrC,QAAI,UAAU,KAAM,QAAO;AAC3B,UAAM,WAAW,IAAIC,wBAAkB;AACvC,WAAO,UAAU,IAAI,MAAM,KAAK;AAAA,EAClC;AAAA,EACA,CACE,KACA,KACA,cACA,SAA6B,SACT;AACpB,QAAI,CAAC,IAAI,sBAAsB,GAAG;AAChC,cAAQ,MAAM,6BAA6B;AAC3C,aAAO;AAAA,IACT;AAEA,QAAI,SAAwB;AAC5B,QAAI,OAAwB;AAC5B,QAAI,gBAAgB,MAAM;A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a,SAAS,GAAG;AAC3B,WAAO,aAAa,CAAC,EAAE;AAAA,EACzB;AACA,SAAO;AACT;;;;;;;;;;;;"}
@@ -44,7 +44,7 @@ if (props.onClickedColumn) {
44
44
  };
45
45
  props.onClickedColumn(columnClickData, event);
46
46
  }*/
47
- export declare function useUnitSelectionTarget(unit: IUnit): [React.RefObject<HTMLElement>, boolean, (evt: Event) => void];
47
+ export declare function useUnitSelectionTarget(unit: IUnit): [React.RefObject<HTMLElement>, boolean, (evt: Event) => void, boolean];
48
48
  export declare function UnitKeyboardNavigation({ columnData, units, allowHorizontalNavigation, }: {
49
49
  columnData?: ColumnData[];
50
50
  units?: UnitLong[];
@@ -86,6 +86,9 @@ function useUnitSelectionTarget(unit) {
86
86
  const [selectedUnit, selectUnit] = useUnitSelection();
87
87
  const selected = selectedUnit?.unit_id == unit.unit_id;
88
88
  const selectedUnitElement = scope.useAtomValue(selectedUnitElementAtom);
89
+ const selectedStratName = selectedUnit?.strat_name_id;
90
+ const unitStratName = unit?.strat_name_id;
91
+ const linked = !selected && selectedStratName != null && unitStratName != null && unitStratName === selectedStratName;
89
92
  const onClick = useCallback(
90
93
  (evt) => {
91
94
  selectUnit?.(unit, ref.current);
@@ -104,7 +107,7 @@ function useUnitSelectionTarget(unit) {
104
107
  inline: "nearest"
105
108
  });
106
109
  }, [selectedUnitElement]);
107
- return [ref, selected, onClick];
110
+ return [ref, selected, onClick, linked];
108
111
  }
109
112
  function UnitKeyboardNavigation({
110
113
  columnData,
@@ -1 +1 @@
1
- {"version":3,"file":"unit-selection.js","sources":["../../src/data-provider/unit-selection.ts"],"sourcesContent":["import type { BaseUnit, UnitLong } from \"@macrostrat/api-types\";\nimport { useKeyHandler } from \"@macrostrat/ui-components\";\nimport { useEffect, useRef, useCallback, useMemo } from \"react\";\nimport type { RectBounds, IUnit } from \"../units/types\";\nimport { atom } from \"jotai\";\nimport { scope, columnUnitsMapAtom } from \"./store\";\nimport {\n AgeRangeQuantifiedDifference,\n ageRangeQuantifiedDifference,\n AgeRangeRelationship,\n} from \"@macrostrat/stratigraphy-utils\";\nimport type { ColumnData } from \"@macrostrat/data-provider\";\n\ntype UnitSelectDispatch = (\n unit: number | BaseUnit | null,\n target: HTMLElement | null,\n) => void;\n\nexport function useUnitSelection() {\n return scope.use(selectedUnitAtom);\n}\n\nexport function useUnitSelectionDispatch(): UnitSelectDispatch {\n return scope.useSetAtom(selectedUnitAtom);\n}\n\nexport function useSelectedUnit() {\n return scope.useAtomValue(selectedUnitAtom);\n}\n\nexport interface ColumnClickData {\n unitID: number | null;\n unit: BaseUnit | null;\n target: HTMLElement | null;\n height: number;\n // Room for boundary IDs eventually\n}\n\nexport interface UnitSelectionCallbacks {\n // It's sort of unfortunate that we need to pass in the column ref here\n onClickedColumn?: (columnClickData: ColumnClickData, event: Event) => void;\n onUnitSelected?: <T extends BaseUnit>(\n unitID: number | null,\n unit: T | null,\n ) => void;\n}\n\nexport const allowUnitSelectionAtom = atom<boolean>(true);\n\nexport const selectedUnitIDAtom = atom<number | null>();\nexport const selectedUnitElementAtom = atom<HTMLElement | null>();\n\nconst overlayPositionAtom = atom<RectBounds | null>();\n\nconst columnRefAtom = atom<{ current: HTMLElement | null }>({ current: null });\n\nexport function useColumnRef() {\n return scope.useAtomValue(columnRefAtom);\n}\n\nconst selectedUnitAtom = atom(\n (get) => {\n if (!get(allowUnitSelectionAtom)) return null;\n\n const unitID = get(selectedUnitIDAtom);\n if (unitID == null) return null;\n const unitsMap = get(columnUnitsMapAtom);\n return unitsMap?.get(unitID) || null;\n },\n (\n get,\n set,\n selectedUnit: number | BaseUnit | null,\n target: HTMLElement | null = null,\n ): BaseUnit | null => {\n if (!get(allowUnitSelectionAtom)) {\n console.error(\"Unit selection is disabled.\");\n return null;\n }\n\n let unitID: number | null = null;\n let unit: BaseUnit | null = null;\n if (selectedUnit == null) {\n unitID = null;\n } else if (typeof selectedUnit === \"number\") {\n unitID = selectedUnit;\n } else if (\"unit_id\" in selectedUnit) {\n unitID = selectedUnit.unit_id;\n }\n\n if (unitID != null) {\n const unitsMap = get(columnUnitsMapAtom);\n // Verify that the unit exists in the current colum, else throw\n if (!unitsMap?.has(unitID)) {\n throw new Error(\n `Unit with ID ${unitID} not found in current column units.`,\n );\n }\n unit = unitsMap.get(unitID) ?? null;\n }\n\n let overlayPosition: RectBounds | null = null;\n\n const columnEl = get(columnRefAtom)?.current;\n\n if (unit != null && columnEl != null && target != null) {\n const rect = columnEl.getBoundingClientRect();\n const targetRect = target.getBoundingClientRect();\n overlayPosition = {\n x: targetRect.left - rect.left,\n y: targetRect.top - rect.top,\n width: targetRect.width,\n height: targetRect.height,\n };\n }\n\n set(selectedUnitElementAtom, target);\n set(selectedUnitIDAtom, unitID);\n set(overlayPositionAtom, overlayPosition);\n\n return unit;\n },\n);\n\nexport function useAtomOverlayPosition() {\n return scope.useAtomValue(overlayPositionAtom);\n}\n\nexport function UnitSelectionCallbackManager({\n onUnitSelected,\n}: UnitSelectionCallbacks) {\n const selectedUnit = scope.useAtomValue(selectedUnitAtom);\n useEffect(() => {\n onUnitSelected?.(selectedUnit?.unit_id ?? null, selectedUnit ?? null);\n }, [selectedUnit?.unit_id]);\n return null;\n}\n\n/** TODO: figure out if onClickedColumn is still needed\n /** This is not the natural place to get positions within the column,\n * but it will work for now.\nif (props.onClickedColumn) {\n // Infer height from top and bottom height of unit (because that's passed back with the call)\n //const py = event.y;\n //const [bottom, top] = getUnitHeightRange(unit, axisType);\n //const height = Math.abs(bottom - top);\n\n const columnClickData: ColumnClickData = {\n unitID: unit?.unit_id,\n unit,\n target,\n height: el?.getBoundingClientRect().height || 0,\n };\n props.onClickedColumn(columnClickData, event);\n}*/\n\nexport function useUnitSelectionTarget(\n unit: IUnit,\n): [React.RefObject<HTMLElement>, boolean, (evt: Event) => void] {\n const ref = useRef<HTMLElement>(null);\n const [selectedUnit, selectUnit] = useUnitSelection();\n const selected = selectedUnit?.unit_id == unit.unit_id;\n const selectedUnitElement = scope.useAtomValue(selectedUnitElementAtom);\n\n const onClick = useCallback(\n (evt: Event) => {\n selectUnit?.(unit, ref.current);\n evt.stopPropagation();\n },\n [unit, selectUnit],\n );\n\n useEffect(() => {\n // Sync selection with unit element...\n if (!selected) return;\n selectUnit?.(unit, ref.current);\n }, [ref.current, selected, selectUnit]);\n\n useEffect(() => {\n // Scroll the unit into view\n selectedUnitElement?.scrollIntoView({\n behavior: \"smooth\",\n block: \"center\",\n inline: \"nearest\",\n });\n }, [selectedUnitElement]);\n\n return [ref, selected, onClick];\n}\n\nexport function UnitKeyboardNavigation({\n columnData,\n units,\n allowHorizontalNavigation,\n}: {\n columnData?: ColumnData[];\n units?: UnitLong[];\n allowHorizontalNavigation?: boolean;\n}) {\n if (units == null && columnData == null) {\n throw new Error(\"Either units or columnData must be provided.\");\n }\n\n let _columnData: ColumnData[] = useMemo(() => {\n if (columnData != null) return columnData;\n // Build column data from units\n const colMap = new Map<number, UnitLong[]>();\n for (const unit of units!) {\n if (!colMap.has(unit.col_id)) {\n colMap.set(unit.col_id, []);\n }\n colMap.get(unit.col_id)!.push(unit);\n }\n const cols: ColumnData[] = [];\n for (const [colID, units] of colMap) {\n cols.push({ columnID: colID, units });\n }\n // Sort columns by columnID\n cols.sort((a, b) => a.columnID - b.columnID);\n return cols;\n }, [columnData, units]);\n\n // Default to allowing horizontal navigation only if columnData is provided\n const _allowHorizontalNavigation =\n allowHorizontalNavigation ?? columnData != null;\n\n const selectedUnit = useSelectedUnit() as UnitLong | null;\n const selectUnit = useUnitSelectionDispatch();\n\n const keyMap: Record<number, Direction> = {\n 38: \"up\",\n 40: \"down\",\n };\n if (_allowHorizontalNavigation) {\n keyMap[37] = \"left\";\n keyMap[39] = \"right\";\n }\n\n useKeyHandler(\n (event) => {\n const direction = keyMap[event.keyCode];\n if (direction == null) return;\n const nextUnit = getBestUnit(_columnData, selectedUnit, direction);\n if (nextUnit == null) return;\n selectUnit(nextUnit, null);\n event.stopPropagation();\n },\n [_columnData, selectedUnit],\n );\n return null;\n}\n\ntype Direction = \"up\" | \"down\" | \"left\" | \"right\";\n\nfunction getBestUnit(\n columnData: ColumnData[],\n targetUnit: UnitLong,\n direction: Direction,\n): UnitLong | null {\n const thisColIndex = columnData.findIndex(\n (col) => col.columnID === targetUnit.col_id,\n );\n if (thisColIndex === -1) return null;\n\n // If up or down, stay in the same column\n if (direction === \"up\" || direction === \"down\") {\n const units = columnData[thisColIndex].units;\n const ix = units.findIndex((unit) => unit.unit_id === targetUnit.unit_id);\n if (ix === -1) return null;\n if (direction === \"up\") {\n return units[ix - 1] || null;\n } else {\n return units[ix + 1] || null;\n }\n }\n\n // If left or right, move to adjacent column\n let adjacentColIndex: number;\n if (direction === \"left\") {\n adjacentColIndex =\n (thisColIndex - 1 + columnData.length) % columnData.length;\n } else {\n adjacentColIndex = (thisColIndex + 1) % columnData.length;\n }\n\n const adjacentColUnits = columnData[adjacentColIndex].units;\n return getMostOverlappingUnit(targetUnit, adjacentColUnits);\n}\n\ntype UnitAgeRangeRelationship = AgeRangeQuantifiedDifference & {\n unit: UnitLong;\n};\n\nfunction getMostOverlappingUnit(\n targetUnit: UnitLong,\n candidateUnits: UnitLong[],\n): UnitLong | null {\n const targetAgeRange = [targetUnit.b_age, targetUnit.t_age];\n\n const overlaps: UnitAgeRangeRelationship[] = [];\n for (const candidate of candidateUnits) {\n const candidateAgeRange = [candidate.b_age, candidate.t_age];\n\n const rel = ageRangeQuantifiedDifference(targetAgeRange, candidateAgeRange);\n if (rel.type === AgeRangeRelationship.Identical) {\n return candidate;\n }\n overlaps.push({ ...rel, unit: candidate });\n }\n\n let bestOverlaps = overlaps.filter(\n (d) => d.type === AgeRangeRelationship.Containing,\n );\n bestOverlaps.sort((a, b) => b.overlap - a.overlap);\n if (bestOverlaps.length > 0) {\n return bestOverlaps[0].unit;\n }\n\n bestOverlaps = overlaps.filter(\n (d) => d.type === AgeRangeRelationship.Contained,\n );\n bestOverlaps.sort((a, b) => b.overlap - a.overlap);\n if (bestOverlaps.length > 0) {\n return bestOverlaps[0].unit;\n }\n\n bestOverlaps = overlaps.filter(\n (d) => d.type === AgeRangeRelationship.PartialOverlap,\n );\n bestOverlaps.sort((a, b) => b.overlap - a.overlap);\n if (bestOverlaps.length > 0) {\n return bestOverlaps[0].unit;\n }\n\n bestOverlaps = overlaps.filter(\n (d) => d.type === AgeRangeRelationship.Disjoint,\n );\n bestOverlaps.sort((a, b) => a.distance - b.distance);\n if (bestOverlaps.length > 0) {\n return bestOverlaps[0].unit;\n }\n return null;\n}\n"],"names":["units"],"mappings":";;;;;AAkBO,SAAS,mBAAmB;AACjC,SAAO,MAAM,IAAI,gBAAgB;AACnC;AAEO,SAAS,2BAA+C;AAC7D,SAAO,MAAM,WAAW,gBAAgB;AAC1C;AAEO,SAAS,kBAAkB;AAChC,SAAO,MAAM,aAAa,gBAAgB;AAC5C;AAmBO,MAAM,yBAAyB,KAAc,IAAI;AAEjD,MAAM,qBAAqB,KAAA;AAC3B,MAAM,0BAA0B,KAAA;AAEvC,MAAM,sBAAsB,KAAA;AAE5B,MAAM,gBAAgB,KAAsC,EAAE,SAAS,MAAM;AAEtE,SAAS,eAAe;AAC7B,SAAO,MAAM,aAAa,aAAa;AACzC;AAEA,MAAM,mBAAmB;AAAA,EACvB,CAAC,QAAQ;AACP,QAAI,CAAC,IAAI,sBAAsB,EAAG,QAAO;AAEzC,UAAM,SAAS,IAAI,kBAAkB;AACrC,QAAI,UAAU,KAAM,QAAO;AAC3B,UAAM,WAAW,IAAI,kBAAkB;AACvC,WAAO,UAAU,IAAI,MAAM,KAAK;AAAA,EAClC;AAAA,EACA,CACE,KACA,KACA,cACA,SAA6B,SACT;AACpB,QAAI,CAAC,IAAI,sBAAsB,GAAG;AAChC,cAAQ,MAAM,6BAA6B;AAC3C,aAAO;AAAA,IACT;AAEA,QAAI,SAAwB;AAC5B,QAAI,OAAwB;AAC5B,QAAI,gBAAgB,MAAM;AACxB,eAAS;AAAA,IACX,WAAW,OAAO,iBAAiB,UAAU;AAC3C,e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M,6BAA6B,gBAAgB,iBAAiB;AAC1E,QAAI,IAAI,SAAS,qBAAqB,WAAW;AAC/C,aAAO;AAAA,IACT;AACA,aAAS,KAAK,EAAE,GAAG,KAAK,MAAM,WAAW;AAAA,EAC3C;AAEA,MAAI,eAAe,SAAS;AAAA,IAC1B,CAAC,MAAM,EAAE,SAAS,qBAAqB;AAAA,EAAA;AAEzC,eAAa,KAAK,CAAC,GAAG,MAAM,EAAE,UAAU,EAAE,OAAO;AACjD,MAAI,aAAa,SAAS,GAAG;AAC3B,WAAO,aAAa,CAAC,EAAE;AAAA,EACzB;AAEA,iBAAe,SAAS;AAAA,IACtB,CAAC,MAAM,EAAE,SAAS,qBAAqB;AAAA,EAAA;AAEzC,eAAa,KAAK,CAAC,GAAG,MAAM,EAAE,UAAU,EAAE,OAAO;AACjD,MAAI,aAAa,SAAS,GAAG;AAC3B,WAAO,aAAa,CAAC,EAAE;AAAA,EACzB;AAEA,iBAAe,SAAS;AAAA,IACtB,CAAC,MAAM,EAAE,SAAS,qBAAqB;AAAA,EAAA;AAEzC,eAAa,KAAK,CAAC,GAAG,MAAM,EAAE,UAAU,EAAE,OAAO;AACjD,MAAI,aAAa,SAAS,GAAG;AAC3B,WAAO,aAAa,CAAC,EAAE;AAAA,EACzB;AAEA,iBAAe,SAAS;AAAA,IACtB,CAAC,MAAM,EAAE,SAAS,qBAAqB;AAAA,EAAA;AAEzC,eAAa,KAAK,CAAC,GAAG,MAAM,EAAE,WAAW,EAAE,QAAQ;AACnD,MAAI,aAAa,SAAS,GAAG;AAC3B,WAAO,aAAa,CAAC,EAAE;AAAA,EACzB;AACA,SAAO;AACT;"}
1
+ {"version":3,"file":"unit-selection.js","sources":["../../src/data-provider/unit-selection.ts"],"sourcesContent":["import type { BaseUnit, UnitLong } from \"@macrostrat/api-types\";\nimport { useKeyHandler } from \"@macrostrat/ui-components\";\nimport { useEffect, useRef, useCallback, useMemo } from \"react\";\nimport type { RectBounds, IUnit } from \"../units/types\";\nimport { atom } from \"jotai\";\nimport { scope, columnUnitsMapAtom } from \"./store\";\nimport {\n AgeRangeQuantifiedDifference,\n ageRangeQuantifiedDifference,\n AgeRangeRelationship,\n} from \"@macrostrat/stratigraphy-utils\";\nimport type { ColumnData } from \"@macrostrat/data-provider\";\n\ntype UnitSelectDispatch = (\n unit: number | BaseUnit | null,\n target: HTMLElement | null,\n) => void;\n\nexport function useUnitSelection() {\n return scope.use(selectedUnitAtom);\n}\n\nexport function useUnitSelectionDispatch(): UnitSelectDispatch {\n return scope.useSetAtom(selectedUnitAtom);\n}\n\nexport function useSelectedUnit() {\n return scope.useAtomValue(selectedUnitAtom);\n}\n\nexport interface ColumnClickData {\n unitID: number | null;\n unit: BaseUnit | null;\n target: HTMLElement | null;\n height: number;\n // Room for boundary IDs eventually\n}\n\nexport interface UnitSelectionCallbacks {\n // It's sort of unfortunate that we need to pass in the column ref here\n onClickedColumn?: (columnClickData: ColumnClickData, event: Event) => void;\n onUnitSelected?: <T extends BaseUnit>(\n unitID: number | null,\n unit: T | null,\n ) => void;\n}\n\nexport const allowUnitSelectionAtom = atom<boolean>(true);\n\nexport const selectedUnitIDAtom = atom<number | null>();\nexport const selectedUnitElementAtom = atom<HTMLElement | null>();\n\nconst overlayPositionAtom = atom<RectBounds | null>();\n\nconst columnRefAtom = atom<{ current: HTMLElement | null }>({ current: null });\n\nexport function useColumnRef() {\n return scope.useAtomValue(columnRefAtom);\n}\n\nconst selectedUnitAtom = atom(\n (get) => {\n if (!get(allowUnitSelectionAtom)) return null;\n\n const unitID = get(selectedUnitIDAtom);\n if (unitID == null) return null;\n const unitsMap = get(columnUnitsMapAtom);\n return unitsMap?.get(unitID) || null;\n },\n (\n get,\n set,\n selectedUnit: number | BaseUnit | null,\n target: HTMLElement | null = null,\n ): BaseUnit | null => {\n if (!get(allowUnitSelectionAtom)) {\n console.error(\"Unit selection is disabled.\");\n return null;\n }\n\n let unitID: number | null = null;\n let unit: BaseUnit | null = null;\n if (selectedUnit == null) {\n unitID = null;\n } else if (typeof selectedUnit === \"number\") {\n unitID = selectedUnit;\n } else if (\"unit_id\" in selectedUnit) {\n unitID = selectedUnit.unit_id;\n }\n\n if (unitID != null) {\n const unitsMap = get(columnUnitsMapAtom);\n // Verify that the unit exists in the current colum, else throw\n if (!unitsMap?.has(unitID)) {\n throw new Error(\n `Unit with ID ${unitID} not found in current column units.`,\n );\n }\n unit = unitsMap.get(unitID) ?? null;\n }\n\n let overlayPosition: RectBounds | null = null;\n\n const columnEl = get(columnRefAtom)?.current;\n\n if (unit != null && columnEl != null && target != null) {\n const rect = columnEl.getBoundingClientRect();\n const targetRect = target.getBoundingClientRect();\n overlayPosition = {\n x: targetRect.left - rect.left,\n y: targetRect.top - rect.top,\n width: targetRect.width,\n height: targetRect.height,\n };\n }\n\n set(selectedUnitElementAtom, target);\n set(selectedUnitIDAtom, unitID);\n set(overlayPositionAtom, overlayPosition);\n\n return unit;\n },\n);\n\nexport function useAtomOverlayPosition() {\n return scope.useAtomValue(overlayPositionAtom);\n}\n\nexport function UnitSelectionCallbackManager({\n onUnitSelected,\n}: UnitSelectionCallbacks) {\n const selectedUnit = scope.useAtomValue(selectedUnitAtom);\n useEffect(() => {\n onUnitSelected?.(selectedUnit?.unit_id ?? null, selectedUnit ?? null);\n }, [selectedUnit?.unit_id]);\n return null;\n}\n\n/** TODO: figure out if onClickedColumn is still needed\n /** This is not the natural place to get positions within the column,\n * but it will work for now.\nif (props.onClickedColumn) {\n // Infer height from top and bottom height of unit (because that's passed back with the call)\n //const py = event.y;\n //const [bottom, top] = getUnitHeightRange(unit, axisType);\n //const height = Math.abs(bottom - top);\n\n const columnClickData: ColumnClickData = {\n unitID: unit?.unit_id,\n unit,\n target,\n height: el?.getBoundingClientRect().height || 0,\n };\n props.onClickedColumn(columnClickData, event);\n}*/\n\nexport function useUnitSelectionTarget(\n unit: IUnit,\n): [React.RefObject<HTMLElement>, boolean, (evt: Event) => void, boolean] {\n const ref = useRef<HTMLElement>(null);\n const [selectedUnit, selectUnit] = useUnitSelection();\n const selected = selectedUnit?.unit_id == unit.unit_id;\n const selectedUnitElement = scope.useAtomValue(selectedUnitElementAtom);\n\n // \"Linked\" units share a stratigraphic name with the selected unit (e.g.\n // the same formation correlated across columns), but are not the selection\n // itself. They receive a subtler highlight.\n const selectedStratName = (selectedUnit as any)?.strat_name_id;\n const unitStratName = (unit as any)?.strat_name_id;\n const linked =\n !selected &&\n selectedStratName != null &&\n unitStratName != null &&\n unitStratName === selectedStratName;\n\n const onClick = useCallback(\n (evt: Event) => {\n selectUnit?.(unit, ref.current);\n evt.stopPropagation();\n },\n [unit, selectUnit],\n );\n\n useEffect(() => {\n // Sync selection with unit element...\n if (!selected) return;\n selectUnit?.(unit, ref.current);\n }, [ref.current, selected, selectUnit]);\n\n useEffect(() => {\n // Scroll the unit into view\n selectedUnitElement?.scrollIntoView({\n behavior: \"smooth\",\n block: \"center\",\n inline: \"nearest\",\n });\n }, [selectedUnitElement]);\n\n return [ref, selected, onClick, linked];\n}\n\nexport function UnitKeyboardNavigation({\n columnData,\n units,\n allowHorizontalNavigation,\n}: {\n columnData?: ColumnData[];\n units?: UnitLong[];\n allowHorizontalNavigation?: boolean;\n}) {\n if (units == null && columnData == null) {\n throw new Error(\"Either units or columnData must be provided.\");\n }\n\n let _columnData: ColumnData[] = useMemo(() => {\n if (columnData != null) return columnData;\n // Build column data from units\n const colMap = new Map<number, UnitLong[]>();\n for (const unit of units!) {\n if (!colMap.has(unit.col_id)) {\n colMap.set(unit.col_id, []);\n }\n colMap.get(unit.col_id)!.push(unit);\n }\n const cols: ColumnData[] = [];\n for (const [colID, units] of colMap) {\n cols.push({ columnID: colID, units });\n }\n // Sort columns by columnID\n cols.sort((a, b) => a.columnID - b.columnID);\n return cols;\n }, [columnData, units]);\n\n // Default to allowing horizontal navigation only if columnData is provided\n const _allowHorizontalNavigation =\n allowHorizontalNavigation ?? columnData != null;\n\n const selectedUnit = useSelectedUnit() as UnitLong | null;\n const selectUnit = useUnitSelectionDispatch();\n\n const keyMap: Record<number, Direction> = {\n 38: \"up\",\n 40: \"down\",\n };\n if (_allowHorizontalNavigation) {\n keyMap[37] = \"left\";\n keyMap[39] = \"right\";\n }\n\n useKeyHandler(\n (event) => {\n const direction = keyMap[event.keyCode];\n if (direction == null) return;\n const nextUnit = getBestUnit(_columnData, selectedUnit, direction);\n if (nextUnit == null) return;\n selectUnit(nextUnit, null);\n event.stopPropagation();\n },\n [_columnData, selectedUnit],\n );\n return null;\n}\n\ntype Direction = \"up\" | \"down\" | \"left\" | \"right\";\n\nfunction getBestUnit(\n columnData: ColumnData[],\n targetUnit: UnitLong,\n direction: Direction,\n): UnitLong | null {\n const thisColIndex = columnData.findIndex(\n (col) => col.columnID === targetUnit.col_id,\n );\n if (thisColIndex === -1) return null;\n\n // If up or down, stay in the same column\n if (direction === \"up\" || direction === \"down\") {\n const units = columnData[thisColIndex].units;\n const ix = units.findIndex((unit) => unit.unit_id === targetUnit.unit_id);\n if (ix === -1) return null;\n if (direction === \"up\") {\n return units[ix - 1] || null;\n } else {\n return units[ix + 1] || null;\n }\n }\n\n // If left or right, move to adjacent column\n let adjacentColIndex: number;\n if (direction === \"left\") {\n adjacentColIndex =\n (thisColIndex - 1 + columnData.length) % columnData.length;\n } else {\n adjacentColIndex = (thisColIndex + 1) % columnData.length;\n }\n\n const adjacentColUnits = columnData[adjacentColIndex].units;\n return getMostOverlappingUnit(targetUnit, adjacentColUnits);\n}\n\ntype UnitAgeRangeRelationship = AgeRangeQuantifiedDifference & {\n unit: UnitLong;\n};\n\nfunction getMostOverlappingUnit(\n targetUnit: UnitLong,\n candidateUnits: UnitLong[],\n): UnitLong | null {\n const targetAgeRange = [targetUnit.b_age, targetUnit.t_age];\n\n const overlaps: UnitAgeRangeRelationship[] = [];\n for (const candidate of candidateUnits) {\n const candidateAgeRange = [candidate.b_age, candidate.t_age];\n\n const rel = ageRangeQuantifiedDifference(targetAgeRange, candidateAgeRange);\n if (rel.type === AgeRangeRelationship.Identical) {\n return candidate;\n }\n overlaps.push({ ...rel, unit: candidate });\n }\n\n let bestOverlaps = overlaps.filter(\n (d) => d.type === AgeRangeRelationship.Containing,\n );\n bestOverlaps.sort((a, b) => b.overlap - a.overlap);\n if (bestOverlaps.length > 0) {\n return bestOverlaps[0].unit;\n }\n\n bestOverlaps = overlaps.filter(\n (d) => d.type === AgeRangeRelationship.Contained,\n );\n bestOverlaps.sort((a, b) => b.overlap - a.overlap);\n if (bestOverlaps.length > 0) {\n return bestOverlaps[0].unit;\n }\n\n bestOverlaps = overlaps.filter(\n (d) => d.type === AgeRangeRelationship.PartialOverlap,\n );\n bestOverlaps.sort((a, b) => b.overlap - a.overlap);\n if (bestOverlaps.length > 0) {\n return bestOverlaps[0].unit;\n }\n\n bestOverlaps = overlaps.filter(\n (d) => d.type === AgeRangeRelationship.Disjoint,\n );\n bestOverlaps.sort((a, b) => a.distance - b.distance);\n if (bestOverlaps.length > 0) {\n return bestOverlaps[0].unit;\n }\n return null;\n}\n"],"names":["units"],"mappings":";;;;;AAkBO,SAAS,mBAAmB;AACjC,SAAO,MAAM,IAAI,gBAAgB;AACnC;AAEO,SAAS,2BAA+C;AAC7D,SAAO,MAAM,WAAW,gBAAgB;AAC1C;AAEO,SAAS,kBAAkB;AAChC,SAAO,MAAM,aAAa,gBAAgB;AAC5C;AAmBO,MAAM,yBAAyB,KAAc,IAAI;AAEjD,MAAM,qBAAqB,KAAA;AAC3B,MAAM,0BAA0B,KAAA;AAEvC,MAAM,sBAAsB,KAAA;AAE5B,MAAM,gBAAgB,KAAsC,EAAE,SAAS,MAAM;AAEtE,SAAS,eAAe;AAC7B,SAAO,MAAM,aAAa,aAAa;AACzC;AAEA,MAAM,mBAAmB;AAAA,EACvB,CAAC,QAAQ;AACP,QAAI,CAAC,IAAI,sBAAsB,EAAG,QAAO;AAEzC,UAAM,SAAS,IAAI,kBAAkB;AACrC,QAAI,UAAU,KAAM,QAAO;AAC3B,UAAM,WAAW,IAAI,kBAAkB;AACvC,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;AAAA,IACtB,CAAC,MAAM,EAAE,SAAS,qBAAqB;AAAA,EAAA;AAEzC,eAAa,KAAK,CAAC,GAAG,MAAM,EAAE,WAAW,EAAE,QAAQ;AACnD,MAAI,aAAa,SAAS,GAAG;AAC3B,WAAO,aAAa,CAAC,EAAE;AAAA,EACzB;AACA,SAAO;AACT;"}
package/dist/index.cjs CHANGED
@@ -10,7 +10,7 @@ const ageRange = require("./unit-details/age-range.cjs");
10
10
  const composite = require("./units/composite.cjs");
11
11
  const columns = require("./maps/layers/columns.cjs");
12
12
  const base = require("./facets/measurements/base.cjs");
13
- const identifiers = require("./unit-details/identifiers.cjs");
13
+ const dataComponents = require("@macrostrat/data-components");
14
14
  const layers = require("./maps/column-navigation/svg/layers.cjs");
15
15
  const core = require("./maps/column-correlation/core.cjs");
16
16
  const state = require("./maps/column-correlation/state.cjs");
@@ -81,9 +81,18 @@ exports.TruncatedList = base.TruncatedList;
81
81
  exports.groupNotesByPixelDistance = base.groupNotesByPixelDistance;
82
82
  exports.mergeHeightRanges = base.mergeHeightRanges;
83
83
  exports.standardizeMeasurementHeight = base.standardizeMeasurementHeight;
84
- exports.ClickableText = identifiers.ClickableText;
85
- exports.Identifier = identifiers.Identifier;
86
- exports.UnitIdentifier = identifiers.UnitIdentifier;
84
+ Object.defineProperty(exports, "ClickableText", {
85
+ enumerable: true,
86
+ get: () => dataComponents.ClickableText
87
+ });
88
+ Object.defineProperty(exports, "Identifier", {
89
+ enumerable: true,
90
+ get: () => dataComponents.Identifier
91
+ });
92
+ Object.defineProperty(exports, "UnitIdentifier", {
93
+ enumerable: true,
94
+ get: () => dataComponents.UnitIdentifier
95
+ });
87
96
  exports.ColumnCenters = layers.ColumnCenters;
88
97
  exports.ColumnFeatures = layers.ColumnFeatures;
89
98
  exports.ColumnKeyboardNavigation = layers.ColumnKeyboardNavigation;
@@ -92,6 +101,7 @@ exports.CurrentColumn = layers.CurrentColumn;
92
101
  exports.MeasurementsLayer = layers.MeasurementsLayer;
93
102
  exports.ColumnCorrelationMap = core.ColumnCorrelationMap;
94
103
  exports.ColumnCorrelationProvider = state.ColumnCorrelationProvider;
104
+ exports.useColumnMapLink = state.useColumnMapLink;
95
105
  exports.useCorrelationMapStore = state.useCorrelationMapStore;
96
106
  exports.ColumnHoverInteraction = index$1.ColumnHoverInteraction;
97
107
  exports.ColumnNavigationMap = index$1.ColumnNavigationMap;
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
1
+ {"version":3,"file":"index.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;"}
package/dist/index.js CHANGED
@@ -8,10 +8,10 @@ import { AgeField, AgeLabel, AgeRange, Duration, IntervalProportions, getAge, ge
8
8
  import { AnnotatedUnitsColumn, ColumnNotesProvider, CompositeUnitComponent, CompositeUnitsColumn, LabelTrackerProvider, SectionLabelsColumn, TrackedLabeledUnit } from "./units/composite.js";
9
9
  import { BaseColumnsLayer, SelectedColumnOverlay, buildColumnsStyle } from "./maps/layers/columns.js";
10
10
  import { BaseMeasurementsColumn, TruncatedList, groupNotesByPixelDistance, mergeHeightRanges, standardizeMeasurementHeight } from "./facets/measurements/base.js";
11
- import { ClickableText, Identifier, UnitIdentifier } from "./unit-details/identifiers.js";
11
+ import { ClickableText, Identifier, UnitIdentifier } from "@macrostrat/data-components";
12
12
  import { ColumnCenters, ColumnFeatures, ColumnKeyboardNavigation, Columns, CurrentColumn, MeasurementsLayer } from "./maps/column-navigation/svg/layers.js";
13
13
  import { ColumnCorrelationMap } from "./maps/column-correlation/core.js";
14
- import { ColumnCorrelationProvider, useCorrelationMapStore } from "./maps/column-correlation/state.js";
14
+ import { ColumnCorrelationProvider, useColumnMapLink, useCorrelationMapStore } from "./maps/column-correlation/state.js";
15
15
  import { ColumnHoverInteraction, ColumnNavigationMap, ColumnSelectionManager, ColumnsNavigationLayer } from "./maps/column-navigation/mapbox/index.js";
16
16
  import { ColumnNavProvider, useColumnNav } from "./data-provider/column-nav.js";
17
17
  import { ColumnNavigationSVGMap, ResizableMapFrame } from "./maps/column-navigation/svg/index.js";
@@ -148,6 +148,7 @@ export {
148
148
  stringifyLine,
149
149
  unitsOverlap,
150
150
  useAtomOverlayPosition,
151
+ useColumnMapLink,
151
152
  useColumnNav,
152
153
  useColumnRef,
153
154
  useColumnUnitsMap,
@@ -24,11 +24,40 @@ function ColumnCorrelationMap(props) {
24
24
  h__default.default(ColumnsLayer, { color: columnColor }),
25
25
  h__default.default(SelectedColumnsLayer),
26
26
  h__default.default(MapClickHandler),
27
+ h__default.default(ColumnInteractionHandler),
28
+ h__default.default(HoveredColumnHighlight),
29
+ h__default.default(ColumnZoomer, { padding }),
27
30
  h__default.default(SectionLine, { padding }),
28
31
  children
29
32
  ]
30
33
  );
31
34
  }
35
+ function ColumnZoomer({ padding }) {
36
+ const zoomColumn = state.useCorrelationMapStore((state2) => state2.zoomColumn);
37
+ const zoomNonce = state.useCorrelationMapStore((state2) => state2.zoomNonce);
38
+ const columns2 = state.useCorrelationMapStore((state2) => state2.columns);
39
+ const bounds = React.useMemo(() => {
40
+ if (zoomColumn == null || columns2 == null) return null;
41
+ const col = columns2.find((c) => c.properties?.col_id === zoomColumn);
42
+ if (col?.geometry == null) return null;
43
+ const b = new mapboxGl.LngLatBounds();
44
+ forEachCoordinate(col.geometry, (coord) => b.extend(coord));
45
+ return b.isEmpty() ? null : b;
46
+ }, [zoomColumn, zoomNonce, columns2]);
47
+ mapboxReact.useMapEaseTo({ bounds, padding: padding * 2 });
48
+ return null;
49
+ }
50
+ function forEachCoordinate(geometry, fn) {
51
+ const walk = (coords) => {
52
+ if (typeof coords[0] === "number") {
53
+ fn(coords);
54
+ } else {
55
+ for (const c of coords) walk(c);
56
+ }
57
+ };
58
+ if (geometry?.coordinates != null) walk(geometry.coordinates);
59
+ }
60
+ const columnLayers = ["columns-fill", "columns-points"];
32
61
  function MapClickHandler() {
33
62
  const onClickMap = state.useCorrelationMapStore((state2) => state2.onClickMap);
34
63
  mapboxReact.useMapClickHandler(
@@ -39,6 +68,90 @@ function MapClickHandler() {
39
68
  );
40
69
  return null;
41
70
  }
71
+ function ColumnInteractionHandler() {
72
+ const toggleColumn = state.useCorrelationMapStore((state2) => state2.toggleColumn);
73
+ const setHoveredColumn = state.useCorrelationMapStore(
74
+ (state2) => state2.setHoveredColumn
75
+ );
76
+ const isManual = state.useCorrelationMapStore(
77
+ (state2) => state2.selectionMode === "manual"
78
+ );
79
+ const hoveredRef = React.useRef(null);
80
+ mapboxReact.useMapStyleOperator(
81
+ (map) => {
82
+ if (!isManual) return;
83
+ const onClick = (e) => {
84
+ const colID = e.features?.[0]?.properties?.col_id;
85
+ if (colID != null) toggleColumn(colID);
86
+ };
87
+ map.on("click", columnLayers, onClick);
88
+ return () => map.off("click", columnLayers, onClick);
89
+ },
90
+ [isManual, toggleColumn]
91
+ );
92
+ mapboxReact.useMapStyleOperator(
93
+ (map) => {
94
+ const clearHover = () => {
95
+ if (hoveredRef.current != null) {
96
+ map.setFeatureState(
97
+ { source: "columns", id: hoveredRef.current },
98
+ { hover: false }
99
+ );
100
+ hoveredRef.current = null;
101
+ }
102
+ };
103
+ const onMove = (e) => {
104
+ const f = e.features?.[0];
105
+ if (f == null) return;
106
+ if (hoveredRef.current !== f.id) {
107
+ clearHover();
108
+ map.setFeatureState({ source: "columns", id: f.id }, { hover: true });
109
+ hoveredRef.current = f.id;
110
+ }
111
+ setHoveredColumn(f.properties?.col_id ?? null);
112
+ map.getCanvas().style.cursor = "pointer";
113
+ };
114
+ const onLeave = () => {
115
+ clearHover();
116
+ setHoveredColumn(null);
117
+ map.getCanvas().style.cursor = "";
118
+ };
119
+ map.on("mousemove", columnLayers, onMove);
120
+ map.on("mouseleave", columnLayers, onLeave);
121
+ return () => {
122
+ map.off("mousemove", columnLayers, onMove);
123
+ map.off("mouseleave", columnLayers, onLeave);
124
+ clearHover();
125
+ };
126
+ },
127
+ [setHoveredColumn]
128
+ );
129
+ return null;
130
+ }
131
+ function HoveredColumnHighlight() {
132
+ const hoveredColumn = state.useCorrelationMapStore((state2) => state2.hoveredColumn);
133
+ const columns2 = state.useCorrelationMapStore((state2) => state2.columns);
134
+ const appliedRef = React.useRef(null);
135
+ mapboxReact.useMapStyleOperator(
136
+ (map) => {
137
+ if (appliedRef.current != null) {
138
+ map.setFeatureState(
139
+ { source: "columns", id: appliedRef.current },
140
+ { highlighted: false }
141
+ );
142
+ appliedRef.current = null;
143
+ }
144
+ if (hoveredColumn == null || columns2 == null) return;
145
+ const col = columns2.find((c) => c.properties?.col_id === hoveredColumn);
146
+ const id = col?.id ?? col?.properties?.col_id;
147
+ if (id == null) return;
148
+ map.setFeatureState({ source: "columns", id }, { highlighted: true });
149
+ appliedRef.current = id;
150
+ },
151
+ [hoveredColumn, columns2]
152
+ );
153
+ return null;
154
+ }
42
155
  function SelectedColumnsLayer() {
43
156
  mapboxReact.useOverlayStyle(() => selectedColumnsStyle, []);
44
157
  const focusedColumns = state.useCorrelationMapStore(
@@ -123,9 +236,14 @@ const lineOfSectionStyle = {
123
236
  function SectionLine({ padding }) {
124
237
  mapboxReact.useOverlayStyle(() => lineOfSectionStyle, []);
125
238
  const focusedLine = state.useCorrelationMapStore((state2) => state2.focusedLine);
239
+ const focusedColumns = state.useCorrelationMapStore(
240
+ (state2) => state2.focusedColumns
241
+ );
126
242
  mapboxReact.useMapStyleOperator(
127
243
  (map) => {
128
244
  if (focusedLine == null) {
245
+ mapboxUtils.setGeoJSON(map, "crossSectionLine", emptyFeatureCollection);
246
+ mapboxUtils.setGeoJSON(map, "crossSectionEndpoints", emptyFeatureCollection);
129
247
  return;
130
248
  }
131
249
  const data = {
@@ -151,17 +269,20 @@ function SectionLine({ padding }) {
151
269
  [focusedLine]
152
270
  );
153
271
  const bounds = React.useMemo(() => {
154
- if (focusedLine == null || focusedLine?.coordinates.length < 2) {
155
- return null;
156
- }
157
- let bounds2 = new mapboxGl.LngLatBounds();
158
- for (let coord of focusedLine.coordinates) {
272
+ const coords = focusedLine != null && focusedLine.coordinates.length >= 2 ? focusedLine.coordinates : focusedColumns.map((c) => c.properties.centroid.geometry.coordinates);
273
+ if (coords.length < 2) return null;
274
+ const bounds2 = new mapboxGl.LngLatBounds();
275
+ for (const coord of coords) {
159
276
  bounds2.extend(coord);
160
277
  }
161
278
  return bounds2;
162
- }, [focusedLine]);
279
+ }, [focusedLine, focusedColumns]);
163
280
  mapboxReact.useMapEaseTo({ bounds, padding, trackResize: true });
164
281
  return null;
165
282
  }
283
+ const emptyFeatureCollection = {
284
+ type: "FeatureCollection",
285
+ features: []
286
+ };
166
287
  exports.ColumnCorrelationMap = ColumnCorrelationMap;
167
288
  //# sourceMappingURL=core.cjs.map