Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.
feat(layers): experimental Zarr raster layer (#3806)
Igor Dykhtafe8c55c196f1
diff --git a/SUMMARY.md b/SUMMARY.mdindex daa670db7..97b8bcd40 100644--- a/SUMMARY.md+++ b/SUMMARY.md@@ -29,6 +29,7 @@* [Trip layer](docs/user-guides/c-types-of-layers/k-trip.md)* [Vector Tile Layer](docs/user-guides/c-types-of-layers/m-vector-tile-layer.md)* [Raster Tile layer](docs/user-guides/c-types-of-layers/n-raster-tile-layer.md)+ * [Zarr Layer](docs/user-guides/c-types-of-layers/s-zarr-layer.md)* [WMS layer](docs/user-guides/c-types-of-layers/o-wms-layer.md)* [Layer Attributes](docs/user-guides/d-layer-attributes.md)* [Color Palettes](docs/user-guides/l-color-attributes.md)diff --git a/babel.config.js b/babel.config.jsindex 976bc1f4c..e6f5cee2c 100644--- a/babel.config.js+++ b/babel.config.js@@ -31,6 +31,9 @@ const getPlugins = isTest => {extensions: ['.js', '.ts', '.tsx', '.json'],root: ['./src'],alias: {+ // Zarrita exposes an import-only entry. Resolve just this dependency+ // for Tape's CommonJS loader, preserving other packages' conditions.+ ...(isTest ? {'^zarrita$': `${nodeModules}/zarrita/dist/src/index.js`} : {}),test: './test',enzyme: './test/helpers/enzyme-adapter.js','@cfaester/enzyme-adapter-react-18': './test/helpers/enzyme-mock.js',diff --git a/docs/user-guides/README.md b/docs/user-guides/README.mdindex 4246d36f1..749c68573 100644--- a/docs/user-guides/README.md+++ b/docs/user-guides/README.md@@ -41,6 +41,7 @@ This guide will teach you how to perform data analysis in Kepler.gl by adding da* [GeoHash](./c-types-of-layers/r-geohash.md)* [Vector Tile Layer](./c-types-of-layers/m-vector-tile-layer.md)* [Raster Tile Layer](./c-types-of-layers/n-raster-tile-layer.md)+* [Zarr Layer](./c-types-of-layers/s-zarr-layer.md)* [WMS Layer](./c-types-of-layers/o-wms-layer.md)#### [Layer attributes](./d-layer-attributes.md)diff --git a/docs/user-guides/c-types-of-layers/README.md b/docs/user-guides/c-types-of-layers/README.mdindex 8a8ec7891..0900878f6 100644--- a/docs/user-guides/c-types-of-layers/README.md+++ b/docs/user-guides/c-types-of-layers/README.md@@ -154,6 +154,14 @@ Supported URL templates:For step-by-step instructions, see [Raster Tile Layer — How to add](./n-raster-tile-layer.md).+## Zarr Layer (experimental)++Zarr layers display raster slices from remote climate and weather datasets. Select a variable and use numeric, categorical, or time coordinates as a timeline axis.++Zarr is enabled by default, including in the demo app. Set `enableZarrLayer: false` in the application configuration to hide it from Add Data and the layer type pickers. Existing saved Zarr layers can still render.++For setup, timeline controls, and save/load behavior, see [Zarr Layer](./s-zarr-layer.md).+## WMS Layer (experimental)diff --git a/docs/user-guides/c-types-of-layers/s-zarr-layer.md b/docs/user-guides/c-types-of-layers/s-zarr-layer.mdnew file mode 100644index 000000000..fc3175f3d--- /dev/null+++ b/docs/user-guides/c-types-of-layers/s-zarr-layer.md@@ -0,0 +1,33 @@+# Zarr Layer (experimental)++Zarr layers display raster slices from remote Zarr stores, including weather forecasts and climate datasets. The layer loads chunks for the current viewport and selected dimensions.++## Application flag++Zarr is enabled by default. The demo app also explicitly enables it in its startup defaults. To hide Zarr from **Add Data → Tilesets** and both layer type pickers, configure your application before mounting kepler.gl:++```js+import {initApplicationConfig} from '@kepler.gl/utils';++initApplicationConfig({enableZarrLayer: false});+```++Set `enableZarrLayer: true` to enable these controls. The flag controls the UI for adding layers; it does not prevent saved or programmatically supplied Zarr layers from rendering, and it does not remove Zarr code from a bundle.++For the demo app, put `{"applicationConfig": {"enableZarrLayer": false}}` in its runtime `config.json`. This overrides the demo default. See [demo runtime configuration](../../../examples/demo-app/README.md#optional-runtime-configjson).++## Add and configure a layer++1. Open **Add Data → Tilesets → Zarr**.+2. Enter a public Zarr store URL or choose the CMIP6, ECMWF IFS, or NOAA HRRR example.+3. Wait for the metadata summary, then click **Add Tileset**.+4. Choose the variable in the layer configurator. Adjust its color range, opacity, and pinned dimensions.+5. Choose a timeline axis to step through a dimension. Numeric and categorical coordinates are supported; recognized time coordinates can also use the shared timeline. Forecast coordinates can combine reference time and lead time into valid time.++The store must allow browser requests through CORS. Metadata loading in Add Data times out after 30 seconds. Closing the modal, changing the URL, or switching tileset tabs cancels the pending request.++## Saved maps++JSON and HTML exports save the store URL, default variable, and attribution instead of embedding the full variable metadata and coordinate lists. Layer settings retain the selected variable, timeline axis, frame, pinned dimensions, and color range.++Opening an export fetches the metadata again, so the store must remain accessible. This keeps exports small but does not reduce the metadata download required on reload. Older maps with embedded Zarr metadata remain supported.diff --git a/examples/demo-app/README.md b/examples/demo-app/README.mdindex eb6209bbc..b8e4caf5e 100644--- a/examples/demo-app/README.md+++ b/examples/demo-app/README.md@@ -71,3 +71,17 @@ yarn start:localAfter a production build (`yarn build`), you can override tokens and demo-app settings without rebuilding by placing a `config.json` next to `dist/index.html` (i.e. `examples/demo-app/dist/config.json`). The app fetches origin-root `/config.json` so SPA routes like `/demo/:id` still find it. To read the config from another location, set `window.__KEPLER_CONFIG_HREF__` (Docker: `KEPLER_CONFIG_HREF`) before `bundle.js` loads, or add a `<base href>` and `config.json` resolves against that base. Neither option hosts the app at a browser-visible sub-path — assets and router routes are root-absolute (see `docker/README.md`). Copy `docker/config.example.json` as a starter; see `docker/config.full-example.json` and `docker/README.md` for the full schema, Compose mounts, and `KEPLER_*` env overrides. `mapConfigUrl` only replaces the `samples.json` catalogue — sample rows still need absolute data/config URLs (see `docker/samples.example.json`). `ASSETS_URL` is the gallery tab thumbnail CDN and is not runtime-configurable.[yarn-install]: https://yarnpkg.com/getting-started/install++#### Zarr layer++The demo app enables the experimental Zarr layer by default. To hide Zarr from **Add Data → Tilesets** and the layer type pickers, set this in `config.json`:++```json+{+ "applicationConfig": {+ "enableZarrLayer": false+ }+}+```++Runtime configuration overrides the demo defaults before the app starts. Existing Zarr layers in saved maps can still render; this flag controls the UI for adding layers. See the [Zarr layer guide](../../docs/user-guides/c-types-of-layers/s-zarr-layer.md) for usage and library configuration.diff --git a/examples/demo-app/src/utils/runtime-config.js b/examples/demo-app/src/utils/runtime-config.jsindex bb3f1e8df..e0edd58ac 100644--- a/examples/demo-app/src/utils/runtime-config.js+++ b/examples/demo-app/src/utils/runtime-config.js@@ -66,6 +66,7 @@ const CREDENTIAL_TO_CLOUD_KEY = {*/export function applyDemoApplicationDefaults() {initApplicationConfig({+ enableZarrLayer: true,customIcons: [{id: 'custom-star',diff --git a/jest.config.js b/jest.config.jsindex b9df4c7cb..2c10d094c 100644--- a/jest.config.js+++ b/jest.config.js@@ -17,13 +17,40 @@ const config = {'<rootDir>/src/**/*.spec.js','<rootDir>/test/**/*.spec.js'],+ // zarrita and its dependencies publish an `exports` map with only `types` and+ // `import` conditions, which jest's CommonJS resolver cannot match. Point at+ // the ESM entry points directly; they are transpiled via+ // transformIgnorePatterns below.+ moduleNameMapper: {+ '^zarrita$': '<rootDir>/node_modules/zarrita/dist/src/index.js',+ '^@zarrita/storage$': '<rootDir>/node_modules/@zarrita/storage/dist/src/index.js',+ '^@zarrita/storage/(.*)$': '<rootDir>/node_modules/@zarrita/storage/dist/src/$1.js',+ '^numcodecs$': '<rootDir>/node_modules/numcodecs/dist/index.js',+ '^numcodecs/(.*)$': '<rootDir>/node_modules/numcodecs/dist/$1.js'+ },+ transform: {+ // zarrita decodes chunks with BigInt exponentiation. The repo's babel config+ // has no browserslist targets, so preset-env downlevels `2n ** n` into+ // `Math.pow`, which throws on BigInt. These packages only need the module+ // format changed, so transform them against the running node instead.+ '[\\\\/]node_modules[\\\\/](zarrita|@zarrita|numcodecs)[\\\\/].+\\.js$': [+ 'babel-jest',+ {+ configFile: false,+ babelrc: false,+ presets: [['@babel/preset-env', {targets: {node: 'current'}}]]+ }+ ],+ '\\.[jt]sx?$': 'babel-jest'+ },// Per https://jestjs.io/docs/configuration#transformignorepatterns-arraystring, transformIgnorePatterns ignores// node_modules and pnp folders by default so that they are not transpiled// Some libraries (even if transitive) are transitioning to ESM and need additional transpilation. Relevant issues:// - SQLRooms and cuid2/hashes: ESM dependencies used by the adapter hydration tests.// - tiny-sdf: https://github.com/visgl/deck.gl/issues/7735+ // - zarrita/@zarrita/@developmentseed: ESM-only, used by the Zarr layer.transformIgnorePatterns: [- '/node_modules\\/(?!(.*@mapbox\\/tiny-sdf\\.*|@loaders\\.gl|@deck\\.gl|@deck\\.gl-community|@luma\\.gl|@hubble\\.gl|@flowmap\\.gl|@math\\.gl|d3-.*|@sqlrooms|@paralleldrive/cuid2|@noble/hashes|kdbush|preact|maplibregl-mapbox-request-transformer|react-date-picker|react-time-picker|react-calendar|react-clock|react-fit|@wojtekmaj\\/date-utils|get-user-locale|make-event-props|update-input-width|detect-element-overflow|memoize|mimic-function))',+ '/node_modules\\/(?!(.*@mapbox\\/tiny-sdf\\.*|@loaders\\.gl|@deck\\.gl|@deck\\.gl-community|@luma\\.gl|@hubble\\.gl|@flowmap\\.gl|@math\\.gl|d3-.*|@sqlrooms|@paralleldrive/cuid2|@noble/hashes|kdbush|preact|maplibregl-mapbox-request-transformer|react-date-picker|react-time-picker|react-calendar|react-clock|react-fit|@wojtekmaj\\/date-utils|get-user-locale|make-event-props|update-input-width|detect-element-overflow|memoize|mimic-function|zarrita|@zarrita|numcodecs|@developmentseed))','\\.pnp\\.[^\\/]+$']};diff --git a/src/components/src/annotations/annotation-overlay.tsx b/src/components/src/annotations/annotation-overlay.tsxindex 19bf9395b..50e7476c7 100644--- a/src/components/src/annotations/annotation-overlay.tsx+++ b/src/components/src/annotations/annotation-overlay.tsx@@ -147,22 +147,10 @@ const AnnotationOverlay: FC<AnnotationOverlayProps> = ({changes = movePoint(draggedAnn, ev.delta, viewport, pickWorldPosition);break;case 'MOVE_RULER_START':- changes = moveRulerEndpoint(- draggedAnn,- 'start',- ev.delta,- viewport,- pickWorldPosition- );+ changes = moveRulerEndpoint(draggedAnn, 'start', ev.delta, viewport, pickWorldPosition);break;case 'MOVE_RULER_END':- changes = moveRulerEndpoint(- draggedAnn,- 'end',- ev.delta,- viewport,- pickWorldPosition- );+ changes = moveRulerEndpoint(draggedAnn, 'end', ev.delta, viewport, pickWorldPosition);break;case 'MOVE_TEXT':changes = moveText(draggedAnn, ev.delta, viewport, pickWorldPosition);diff --git a/src/components/src/annotations/annotation-panel.spec.tsx b/src/components/src/annotations/annotation-panel.spec.tsxindex 084b7d352..ff5086c18 100644--- a/src/components/src/annotations/annotation-panel.spec.tsx+++ b/src/components/src/annotations/annotation-panel.spec.tsx@@ -328,7 +328,8 @@ describe('AnnotationManager selectors', () => {});test.each(['Right', 'Above'])(- 'keeps %s unchanged when Enter is pressed without choosing an option', current => {+ 'keeps %s unchanged when Enter is pressed without choosing an option',+ current => {const state = makeState(true, true);Object.assign(state.visState.annotations[0], {kind: AnnotationKind.POINT,@@ -363,36 +364,39 @@ describe('AnnotationManager selectors', () => {next: 'Below',changes: {textSide: 'right', textVerticalPosition: 'below', angle: 45}}- ] as const)('changes $current to $next through a kepler.gl selector', ({current, next, changes}) => {- const state = makeState(true, true);- const store = mockStore({- ...state,- visState: {- ...state.visState,- annotations: [- {- ...state.visState.annotations[0],- kind: AnnotationKind.POINT,- armLength: 50,- angle: -45- }- ]- }- });- const {container} = renderWithTheme(- <IntlWrapper>- <Provider store={store}>- <AnnotationManager />- </Provider>- </IntlWrapper>- );+ ] as const)(+ 'changes $current to $next through a kepler.gl selector',+ ({current, next, changes}) => {+ const state = makeState(true, true);+ const store = mockStore({+ ...state,+ visState: {+ ...state.visState,+ annotations: [+ {+ ...state.visState.annotations[0],+ kind: AnnotationKind.POINT,+ armLength: 50,+ angle: -45+ }+ ]+ }+ });+ const {container} = renderWithTheme(+ <IntlWrapper>+ <Provider store={store}>+ <AnnotationManager />+ </Provider>+ </IntlWrapper>+ );- expect(container.querySelector('select')).not.toBeInTheDocument();- fireEvent.click(screen.getByText(current));- expect(screen.queryByPlaceholderText('Search')).not.toBeInTheDocument();- fireEvent.click(screen.getByText(next));+ expect(container.querySelector('select')).not.toBeInTheDocument();+ fireEvent.click(screen.getByText(current));+ expect(screen.queryByPlaceholderText('Search')).not.toBeInTheDocument();+ fireEvent.click(screen.getByText(next));- expect(store.getActions()).toEqual([VisStateActions.updateAnnotation('ruler-1', changes)]);- expect(screen.queryByText(next)).not.toBeInTheDocument();- });+ expect(store.getActions()).toEqual([VisStateActions.updateAnnotation('ruler-1', changes)]);+ expect(screen.queryByText(next)).not.toBeInTheDocument();+ }+ );});diff --git a/src/components/src/annotations/annotation-panel.tsx b/src/components/src/annotations/annotation-panel.tsxindex 8d0f02391..0822347dd 100644--- a/src/components/src/annotations/annotation-panel.tsx+++ b/src/components/src/annotations/annotation-panel.tsx@@ -293,8 +293,7 @@ const StyledAnnotationTypeButton = styled(Button)<{$active: boolean}>`padding: 0;background-color: ${props => props.theme.inputBgd};color: ${props => (props.$active ? props.theme.switchTrackBgdActive : props.theme.inputColor)};- border: 1px solid- ${props => (props.$active ? props.theme.switchTrackBgdActive : 'transparent')};+ border: 1px solid ${props => (props.$active ? props.theme.switchTrackBgdActive : 'transparent')};&:hover,&:focus,diff --git a/src/components/src/annotations/annotation-text.spec.tsx b/src/components/src/annotations/annotation-text.spec.tsxindex 95cb147aa..b360c0376 100644--- a/src/components/src/annotations/annotation-text.spec.tsx+++ b/src/components/src/annotations/annotation-text.spec.tsx@@ -77,10 +77,7 @@ describe('AnnotationText ruler labels', () => {expect(screen.queryByText('Measured span')).not.toBeInTheDocument();distanceOnly.unmount();- const hidden = renderRulerText(- makeRuler({showCustomText: false, showDistance: false}),- true- );+ const hidden = renderRulerText(makeRuler({showCustomText: false, showDistance: false}), true);expect(hidden.container.querySelector('[data-annotation-part="text"]')).toBeNull();});diff --git a/src/components/src/annotations/annotation-text.tsx b/src/components/src/annotations/annotation-text.tsxindex 65288a8f6..efe38ef73 100644--- a/src/components/src/annotations/annotation-text.tsx+++ b/src/components/src/annotations/annotation-text.tsx@@ -6,11 +6,7 @@ import styled from 'styled-components';import {useDraggable} from '@dnd-kit/core';import {Annotation} from '@kepler.gl/types';import {AnnotationKind} from '@kepler.gl/constants';-import {- getAnnotationTextBoxStyle,- getRulerDistanceLabel,- MapViewport-} from './annotation-utils';+import {getAnnotationTextBoxStyle, getRulerDistanceLabel, MapViewport} from './annotation-utils';import {LexicalRichTextEditor, LexicalToolbar} from './lexical-editor';import {SerializedEditorState} from 'lexical';@@ -111,8 +107,7 @@ const AnnotationText: FC<AnnotationTextProps> = ({}) => {const isRuler = annotation.kind === AnnotationKind.RULER;const showCustomText = !isRuler || annotation.showCustomText;- const distanceText =- isRuler && annotation.showDistance ? getRulerDistanceLabel(annotation) : '';+ const distanceText = isRuler && annotation.showDistance ? getRulerDistanceLabel(annotation) : '';const isDraggable = !isRuler;const {attributes, listeners, setNodeRef} = useDraggable({id: `${annotation.id}:MOVE_TEXT`,diff --git a/src/components/src/annotations/annotation-utils.ts b/src/components/src/annotations/annotation-utils.tsindex c9df9aa99..b670bb3dd 100644--- a/src/components/src/annotations/annotation-utils.ts+++ b/src/components/src/annotations/annotation-utils.ts@@ -274,10 +274,7 @@ export function isPointVisibleOnGlobe(}/** A ruler is safe to draw as a DOM overlay only while both endpoints are visible. */-export function isAnnotationVisibleOnGlobe(- annotation: Annotation,- viewport: MapViewport-): boolean {+export function isAnnotationVisibleOnGlobe(annotation: Annotation, viewport: MapViewport): boolean {return (isPointVisibleOnGlobe(annotation.anchorPoint, viewport) &&(annotation.kind !== AnnotationKind.RULER ||@@ -303,7 +300,7 @@ function moveCoordinate(}function normalizeRulerLongitude(point: LngLatAltitude): LngLatAltitude {- const longitude = (((point[0] + 180) % 360) + 360) % 360 - 180;+ const longitude = ((((point[0] + 180) % 360) + 360) % 360) - 180;return point.length === 3 ? [longitude, point[1], point[2]] : [longitude, point[1]];}diff --git a/src/components/src/bottom-widget.tsx b/src/components/src/bottom-widget.tsxindex b8b4f6b0d..d6d036f36 100644--- a/src/components/src/bottom-widget.tsx+++ b/src/components/src/bottom-widget.tsx@@ -14,6 +14,8 @@ import {bottomWidgetSelector} from './kepler-gl';import FilterAnimationControllerFactory from './filter-animation-controller';import LayerAnimationControllerFactory from './layer-animation-controller';import AnimationControlFactory from './common/animation-control/animation-control';+import ZarrAxisAnimationFactory from './zarr-axis-animation';+import {getZarrVariable, isExplicitZarrAxis} from '@kepler.gl/table';import {BaseComponentProps} from './types';const maxWidth = 1080;@@ -61,7 +63,8 @@ BottomWidgetFactory.deps = [TimeWidgetFactory,AnimationControlFactory,FilterAnimationControllerFactory,- LayerAnimationControllerFactory+ LayerAnimationControllerFactory,+ ZarrAxisAnimationFactory];/* eslint-disable complexity */@@ -69,7 +72,8 @@ export default function BottomWidgetFactory(TimeWidget: ReturnType<typeof TimeWidgetFactory>,AnimationControl: ReturnType<typeof AnimationControlFactory>,FilterAnimationController: ReturnType<typeof FilterAnimationControllerFactory>,- LayerAnimationController: ReturnType<typeof LayerAnimationControllerFactory>+ LayerAnimationController: ReturnType<typeof LayerAnimationControllerFactory>,+ ZarrAxisAnimation: ReturnType<typeof ZarrAxisAnimationFactory>): React.FC<BottomWidgetThemedProps> {const LayerAnimationControl = styled(AnimationControl)`background-color: ${props => props.theme.sidePanelBg};@@ -128,6 +132,14 @@ export default function BottomWidgetFactory([animationConfig.domain, animationConfig.currentTime]);+ const dimensionLayers = layers.filter(+ layer =>+ layer.type === 'zarr' &&+ layer.config.isVisible &&+ isExplicitZarrAxis(layer.config.visConfig.zarrAxis) &&+ layer.config.visConfig.zarrAxis.kind !== 'off'+ );+// if animation control is showing, hide time display in time sliderconst showFloatingTimeDisplay = !animatableLayer.length;const showAnimationControl =@@ -174,9 +186,27 @@ export default function BottomWidgetFactory(width={Math.min(maxWidth, enlargedFilterWidth)}style={{marginRight: spaceForLegendWidth}}className="bottom-widget--container"- $hasPadding={showAnimationControl || showTimeWidget}+ $hasPadding={showAnimationControl || showTimeWidget || dimensionLayers.length > 0}ref={rootRef}>+ {dimensionLayers.map(layer => {+ const {visConfig, dataId} = layer.config;+ const variable = getZarrVariable(+ datasets[dataId ?? '']?.metadata,+ visConfig.zarrVariable ?? undefined+ );+ return variable ? (+ <ZarrAxisAnimation+ key={layer.id}+ variable={variable}+ config={visConfig.zarrAxis}+ pins={visConfig.dimensionIndexes}+ frameIndex={visConfig.zarrFrame}+ label={layer.config.label}+ onFrameChange={zarrFrame => visStateActions.layerVisConfigChange(layer, {zarrFrame})}+ />+ ) : null;+ })}{!isTimelineLinkedWithFilter ? (<LayerAnimationControlleranimationConfig={enhancedAnimationConfig}diff --git a/src/components/src/common/animation-control/animation-control.tsx b/src/components/src/common/animation-control/animation-control.tsxindex 2fb390c63..3e322177c 100644--- a/src/components/src/common/animation-control/animation-control.tsx+++ b/src/components/src/common/animation-control/animation-control.tsx@@ -84,6 +84,7 @@ export type AnimationControlProps = {className?: string;style?: object;formatTimelineValue?: (value: number) => string;+ displayLabel?: string;};AnimationControlFactory.deps = [@@ -117,7 +118,8 @@ function AnimationControlFactory(showTimeline = true,showControls = true,showTimeDisplay = true,- formatTimelineValue+ formatTimelineValue,+ displayLabel}) => {if (!timeline) {return null;@@ -162,6 +164,8 @@ function AnimationControlFactory(defaultTimeFormat={defaultTimeFormat}timeFormat={timeFormat}timezone={timezone}+ formatValue={formatTimelineValue}+ displayLabel={displayLabel}/>) : null}</AnimationControlContainer>diff --git a/src/components/src/common/line-chart.tsx b/src/components/src/common/line-chart.tsxindex d5438d27d..d76249bdf 100644--- a/src/components/src/common/line-chart.tsx+++ b/src/components/src/common/line-chart.tsx@@ -250,9 +250,7 @@ function LineChartFactory() {const hintFormatter = useMemo(() =>- isTime- ? datetimeFormatter(timezone)(timeFormat)- : (value: number) => formatNumber(value),+ isTime ? datetimeFormatter(timezone)(timeFormat) : (value: number) => formatNumber(value),[isTime, timezone, timeFormat]);diff --git a/src/components/src/common/timeline-slider.tsx b/src/components/src/common/timeline-slider.tsxindex 5aec58ef3..7dbc4f1e6 100644--- a/src/components/src/common/timeline-slider.tsx+++ b/src/components/src/common/timeline-slider.tsx@@ -126,17 +126,16 @@ function TimelineSliderFactory() {return [null, null];}- const valueFormatter = formatValue || (() => {- const hasUserFormat = typeof timeFormat === 'string';- const currentFormat =- (hasUserFormat ? timeFormat : defaultTimeFormat) || DEFAULT_TIME_FORMAT;- return datetimeFormatter(timezone)(currentFormat);- })();-- return [- domain ? valueFormatter(domain[0]) : '',- domain ? valueFormatter(domain[1]) : ''- ];+ const valueFormatter =+ formatValue ||+ (() => {+ const hasUserFormat = typeof timeFormat === 'string';+ const currentFormat =+ (hasUserFormat ? timeFormat : defaultTimeFormat) || DEFAULT_TIME_FORMAT;+ return datetimeFormatter(timezone)(currentFormat);+ })();++ return [domain ? valueFormatter(domain[0]) : '', domain ? valueFormatter(domain[1]) : ''];}, [domain, timezone, timeFormat, defaultTimeFormat, showDomainTimes, formatValue]);const requiresRangeSlider = isRanged && animationWindow !== ANIMATION_WINDOW.interval;diff --git a/src/components/src/map-container.tsx b/src/components/src/map-container.tsxindex 551a62d90..6c3bbcfb6 100644--- a/src/components/src/map-container.tsx+++ b/src/components/src/map-container.tsx@@ -470,13 +470,7 @@ export default function MapContainerFactory(this.globeBackgroundColorSelector,this.globeStarsSelector,this.transparentBackgroundSelector,- (- backgroundColor,- isGlobeMode,- globeBackgroundColor,- globeStars,- transparentBackground- ) => ({+ (backgroundColor, isGlobeMode, globeBackgroundColor, globeStars, transparentBackground) => ({...MAP_STYLE.container,...(!transparentBackground && !isGlobeMode && backgroundColor? {backgroundColor: rgbToHex(backgroundColor)}@@ -1230,8 +1224,7 @@ export default function MapContainerFactory(mapboxApiAccessToken,mapboxApiUrl,layersForDeck,- isAnnotationMode:- Boolean(mapControls?.annotation?.active) && !Boolean(this.props.readOnly),+ isAnnotationMode: Boolean(mapControls?.annotation?.active) && !this.props.readOnly,editorInfo: primaryMap? {editor,@@ -1759,9 +1752,7 @@ export default function MapContainerFactory(}selectedAnnotationId={visState.selectedAnnotationId}isEditingAnnotationText={visState.isEditingAnnotationText}- isAnnotationMode={- Boolean(mapControls?.annotation?.active) && !Boolean(this.props.readOnly)- }+ isAnnotationMode={Boolean(mapControls?.annotation?.active) && !this.props.readOnly}mapIndex={index || 0}viewport={this._getAnnotationViewport(mapState, internalViewState)}isGlobeEnabled={Boolean(mapState.globe?.enabled)}diff --git a/src/components/src/map/camera-bookmark-control.spec.tsx b/src/components/src/map/camera-bookmark-control.spec.tsxindex f5731e365..4a8802a0d 100644--- a/src/components/src/map/camera-bookmark-control.spec.tsx+++ b/src/components/src/map/camera-bookmark-control.spec.tsx@@ -320,7 +320,10 @@ test.each([INITIAL_UI_STATE.mapControls, legacyMapControls, enabledMapControls])const commit = jest.fn();const visibility = jest.fn();function Harness() {- const [uiState, setUiState] = React.useState({...INITIAL_UI_STATE, mapControls: initialControls});+ const [uiState, setUiState] = React.useState({+ ...INITIAL_UI_STATE,+ mapControls: initialControls+ });const setMapControlVisibility: typeof UIStateActions.setMapControlVisibility = (id, show) => {visibility(id, show);const action = UIStateActions.setMapControlVisibility(id, show);diff --git a/src/components/src/modal-container.tsx b/src/components/src/modal-container.tsxindex ced760252..7470e9990 100644--- a/src/components/src/modal-container.tsx+++ b/src/components/src/modal-container.tsx@@ -348,15 +348,8 @@ export default function ModalContainerFactory(_onExportMap = () => {const {uiState} = this._propsWithMapInfoDraft();- const {- format,- includeLayerApiKeys,- fileName,- appName,- appWebsite,- appIcon,- appNameColor- } = uiState.exportMap;+ const {format, includeLayerApiKeys, fileName, appName, appWebsite, appIcon, appNameColor} =+ uiState.exportMap;(format === EXPORT_MAP_FORMATS.HTML ? exportHtml : exportJson)(this._propsWithMapInfoDraft(),{diff --git a/src/components/src/modals/export-data-modal.tsx b/src/components/src/modals/export-data-modal.tsxindex b54532906..5f0d94b90 100644--- a/src/components/src/modals/export-data-modal.tsx+++ b/src/components/src/modals/export-data-modal.tsx@@ -104,7 +104,8 @@ const ExportDataModalFactory = () => {datasets[datasetId].type === DatasetType.RASTER_TILE ||datasets[datasetId].type === DatasetType.WMS_TILE ||datasets[datasetId].type === DatasetType.TILE_3D ||- datasets[datasetId].type === DatasetType.BITMAP) &&+ datasets[datasetId].type === DatasetType.BITMAP ||+ datasets[datasetId].type === DatasetType.ZARR) &&(selectedDataset === datasetId || exportAllDatasets));});diff --git a/src/components/src/modals/export-map-modal/export-map-modal.tsx b/src/components/src/modals/export-map-modal/export-map-modal.tsxindex 6b59f3536..308bf5f33 100644--- a/src/components/src/modals/export-map-modal/export-map-modal.tsx+++ b/src/components/src/modals/export-map-modal/export-map-modal.tsx@@ -111,9 +111,7 @@ const BrandingPreview = styled.div`const DEFAULT_APP_NAME_COLOR = '#1FBAD6';function getAppNameColorInputValue(value: unknown): string {- return typeof value === 'string' && /^#[\da-f]{6}$/i.test(value)- ? value- : DEFAULT_APP_NAME_COLOR;+ return typeof value === 'string' && /^#[\da-f]{6}$/i.test(value) ? value : DEFAULT_APP_NAME_COLOR;}function getBrandingURL(value: unknown, fallback: string | null): string | null {diff --git a/src/components/src/modals/tilesets-modals/common.tsx b/src/components/src/modals/tilesets-modals/common.tsxindex 5efca6235..61214cb8e 100644--- a/src/components/src/modals/tilesets-modals/common.tsx+++ b/src/components/src/modals/tilesets-modals/common.tsx@@ -3,7 +3,8 @@import type {WMSCapabilities} from '@loaders.gl/wms';-import type {VectorTileMetadata} from '@kepler.gl/table';+import type {ZarrDatasetMetadata} from '@kepler.gl/constants';+import type {VectorTileMetadata, ZarrMetadataProgress} from '@kepler.gl/table';import type {StacTypes} from '@kepler.gl/types';export type DatasetCreationAttributes = {@@ -17,9 +18,11 @@ export type MetaResponse = {| VectorTileMetadata| StacTypes.CompleteSTACObject| WMSCapabilities+ | ZarrDatasetMetadata| Record<string, unknown>| null;dataset?: DatasetCreationAttributes | null;loading?: boolean;+ progress?: ZarrMetadataProgress | null;error?: Error | null;};diff --git a/src/components/src/modals/tilesets-modals/load-tileset.spec.tsx b/src/components/src/modals/tilesets-modals/load-tileset.spec.tsxnew file mode 100644index 000000000..a95ab29d6--- /dev/null+++ b/src/components/src/modals/tilesets-modals/load-tileset.spec.tsx@@ -0,0 +1,204 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++// @ts-nocheck+import React from 'react';+import {act, fireEvent, waitFor} from '@testing-library/react';+import {DatasetType} from '@kepler.gl/constants';+import {getApplicationConfig, initApplicationConfig} from '@kepler.gl/utils';+import {IntlWrapper, renderWithTheme} from 'test/helpers/component-jest-utils';+import LoadTilesetTabFactory from './load-tileset';+import {getZarrMetadataPreview} from './zarr-metadata-preview';++jest.mock('./tileset-vector-form', () => () => null);+jest.mock('react-virtualized', () => ({+ AutoSizer: ({children}) => children({height: 400, width: 500})+}));+jest.mock('@kepler.gl/table', () => ({+ getZarrMetadata: jest.fn(),+ selectZarrVariable: jest.fn(metadata => metadata)+}));++// eslint-disable-next-line @typescript-eslint/no-var-requires+const {getZarrMetadata} = require('@kepler.gl/table');+const LoadTilesetTab = LoadTilesetTabFactory();++describe('Zarr metadata preview', () => {+ let previousZarrFlag;+ beforeEach(() => {+ previousZarrFlag = getApplicationConfig().enableZarrLayer;+ initApplicationConfig({enableZarrLayer: true});+ getZarrMetadata.mockReset();+ });+ afterEach(() => initApplicationConfig({enableZarrLayer: previousZarrFlag}));++ it.each([true, false])('respects enableZarrLayer=%s in Add Data', enabled => {+ initApplicationConfig({enableZarrLayer: enabled});+ const {queryByText, getByText} = renderWithTheme(+ <IntlWrapper>+ <LoadTilesetTab onTilesetAdded={jest.fn()} isAddingDatasets={false} />+ </IntlWrapper>+ );+ expect(Boolean(queryByText('Zarr'))).toBe(enabled);+ expect(getByText('Vector Tile')).toBeTruthy();+ expect(getZarrMetadata).not.toHaveBeenCalled();+ });++ it('aborts metadata requests when switching away from the Zarr tab', async () => {+ getZarrMetadata.mockReturnValue(+ new Promise(() => {+ // Keep metadata pending until the user leaves the tab.+ })+ );+ const {getByText, getByRole} = renderWithTheme(+ <IntlWrapper>+ <LoadTilesetTab onTilesetAdded={jest.fn()} isAddingDatasets={false} />+ </IntlWrapper>+ );+ fireEvent.click(getByText('Zarr'));+ fireEvent.click(getByRole('button', {name: 'Use NOAA HRRR Forecast'}));+ await waitFor(() => expect(getZarrMetadata).toHaveBeenCalled());+ const {signal} = getZarrMetadata.mock.calls[0][1];+ expect(signal.aborted).toBe(false);+ fireEvent.click(getByText('Vector Tile'));+ expect(signal.aborted).toBe(true);+ });++ it('shows download progress and processing until the metadata is ready to add', async () => {+ let resolveMetadata;+ getZarrMetadata.mockReturnValue(new Promise(resolve => (resolveMetadata = resolve)));+ const {container, getByText, getByRole, findByRole, queryByRole} = renderWithTheme(+ <IntlWrapper>+ <LoadTilesetTab onTilesetAdded={jest.fn()} isAddingDatasets={false} />+ </IntlWrapper>+ );+ fireEvent.click(getByText('Zarr'));+ fireEvent.click(getByRole('button', {name: 'Use NOAA HRRR Forecast'}));+ await waitFor(() => expect(getZarrMetadata).toHaveBeenCalled());++ const bar = await findByRole('progressbar', {name: 'Zarr metadata loading'});+ expect(bar).not.toHaveAttribute('aria-valuenow');+ expect(bar).toHaveAttribute('aria-valuetext', expect.stringContaining('Connecting'));+ const {onProgress} = getZarrMetadata.mock.calls[0][1];+ act(() => onProgress({phase: 'downloading', loadedBytes: 5_000_000, totalBytes: 10_000_000}));+ expect(bar).toHaveAttribute('aria-valuenow', '50');+ expect(bar).toHaveAttribute('aria-valuetext', expect.stringContaining('5.0 MB / 10.0 MB'));+ expect(container.querySelector('.load-data-footer button')).toBeDisabled();++ act(() => onProgress({phase: 'downloading', loadedBytes: 6_000_000}));+ expect(bar).not.toHaveAttribute('aria-valuenow');+ expect(bar).toHaveAttribute(+ 'aria-valuetext',+ expect.stringContaining('total size unavailable')+ );+ act(() => onProgress({phase: 'processing', loadedBytes: 10_000_000}));+ expect(bar).not.toHaveAttribute('aria-valuenow');+ expect(bar).toHaveAttribute('aria-valuetext', expect.stringContaining('Reading variables'));++ act(() => onProgress({phase: 'connecting', loadedBytes: 10_000_000}));+ expect(bar).not.toHaveAttribute('aria-valuenow');+ expect(bar).toHaveAttribute(+ 'aria-valuetext',+ expect.stringContaining('Waiting for metadata response')+ );+ expect(bar).toHaveAttribute('aria-valuetext', expect.stringContaining('10.0 MB received'));++ await act(async () =>+ resolveMetadata({variable: 'climate', variables: [], levels: [], nonSpatialDims: []})+ );+ expect(queryByRole('progressbar')).not.toBeInTheDocument();+ expect(getByRole('button', {name: 'Add Tileset'})).toBeEnabled();+ });++ it.each([+ ['ECMWF IFS Ensemble', 935, 19],+ ['NOAA HRRR Forecast', 12094, 29]+ ])('bounds the %s preview while adding complete metadata', async (name, count, variableCount) => {+ const values = Array.from({length: count}, (_, i) => Date.UTC(2024, 0, 1) + i * 3600000);+ // Fail before creating a huge DOM if full-array serialization is reintroduced.+ values.toJSON = jest.fn(() => {+ throw new Error('The preview must not serialize full coordinate arrays');+ });+ const timeDimension = {+ name: 'init_time',+ size: count,+ kind: 'time',+ values,+ rawValues: values+ };+ const metadata = {+ url: 'https://example.com/forecast.zarr',+ variable: 'variable_0',+ axes: ['init_time', 'y', 'x'],+ xAxisIndex: 2,+ yAxisIndex: 1,+ levels: [{path: '.', shape: [2, 2], chunks: [2, 2]}],+ nonSpatialDims: [timeDimension],+ timeDimension,+ variables: Array.from({length: variableCount}, (_, i) => ({+ path: `variable_${i}`,+ name: `variable_${i}`,+ displayName: `Variable ${i}`,+ dtype: 'float32',+ shape: [count, 2, 2],+ chunks: [1, 2, 2],+ nonSpatialDims: [timeDimension],+ timeDimension+ }))+ };+ getZarrMetadata.mockResolvedValue(metadata);+ const onTilesetAdded = jest.fn();+ const {container, getByText, getByRole} = renderWithTheme(+ <IntlWrapper>+ <LoadTilesetTab onTilesetAdded={onTilesetAdded} isAddingDatasets={false} />+ </IntlWrapper>+ );+ fireEvent.click(getByText('Zarr'));+ fireEvent.click(getByRole('button', {name: `Use ${name}`}));+ await waitFor(() => expect(container.querySelector('#json-pretty')).not.toBeNull());++ const preview = JSON.parse(container.querySelector('#json-pretty').textContent);+ expect(preview.variableCount).toBe(variableCount);+ expect(preview.omittedVariables).toBe(Math.max(0, variableCount - 20));+ expect(preview.dimensions[0].coordinates).toEqual({+ count,+ first: values.slice(0, 3),+ last: values.slice(-3)+ });+ expect(container.querySelectorAll('#json-pretty span').length).toBeLessThan(500);+ expect(values.toJSON).not.toHaveBeenCalled();++ fireEvent.click(getByRole('button', {name: 'Add Tileset'}));+ const [dataset, addedMetadata] = onTilesetAdded.mock.calls[0];+ expect(dataset.type).toBe(DatasetType.ZARR);+ expect(addedMetadata).toBe(metadata);+ expect(addedMetadata.variables).toHaveLength(variableCount);+ expect(addedMetadata.variables[0].nonSpatialDims[0].values).toBe(values);+ expect(values).toHaveLength(count);+ });++ it('handles missing and empty coordinates and previews the selected variable', () => {+ const metadata = {+ url: 'https://example.com/empty.zarr',+ variable: 'second',+ levels: [],+ nonSpatialDims: [],+ variables: [+ {path: 'first', displayName: 'First', nonSpatialDims: []},+ {+ path: 'second',+ displayName: 'Second',+ nonSpatialDims: [+ {name: 'band', size: 2},+ {name: 'time', size: 0, values: []}+ ]+ }+ ]+ };+ const preview = getZarrMetadataPreview(metadata);+ expect(preview.selectedVariable.path).toBe('second');+ expect(preview.dimensions[0].coordinates).toBeUndefined();+ expect(preview.dimensions[1].coordinates).toEqual({count: 0, first: []});+ expect(getZarrMetadataPreview({...metadata, variables: []}).selectedVariable).toBeUndefined();+ });+});diff --git a/src/components/src/modals/tilesets-modals/load-tileset.tsx b/src/components/src/modals/tilesets-modals/load-tileset.tsxindex ae15af18a..c48c2eb6a 100644--- a/src/components/src/modals/tilesets-modals/load-tileset.tsx+++ b/src/components/src/modals/tilesets-modals/load-tileset.tsx@@ -12,9 +12,11 @@ import {RasterTileIcon,WMSLayerIcon,Tile3DLayerIcon,- BitmapLayerIcon+ BitmapLayerIcon,+ ZarrLayerIcon} from '@kepler.gl/layers';import {getError, getApplicationConfig} from '@kepler.gl/utils';+import {DatasetType, ZarrDatasetMetadata} from '@kepler.gl/constants';import LoadingSpinner from '../../common/loading-spinner';import {MetaResponse} from './common';@@ -26,8 +28,12 @@ import TilesetRasterForm from './tileset-raster-form';import TilesetWMSForm from './tileset-wms-form';import TilesetTile3DForm from './tileset-tile3d-form';import TilesetBitmapForm from './tileset-bitmap-form';+import TilesetZarrForm from './tileset-zarr-form';+import {getZarrMetadataPreview} from './zarr-metadata-preview';+import ZarrMetadataLoading from './zarr-metadata-progress';-const WIDTH_ICON = '70px';+const WIDTH_ICON = '60px';+const MemoizedJSONPretty = React.memo(JSONPretty);const LoadTilesetTabContainer = styled.div`color: ${props => props.theme.AZURE};@@ -42,9 +48,14 @@ const Container = styled.div`const TilesetTypeContainer = styled.div`display: grid;- grid-template-columns: repeat(6, ${WIDTH_ICON});- column-gap: 10px;+ grid-template-columns: repeat(6, minmax(0, ${WIDTH_ICON}));+ gap: 6px;margin-bottom: 20px;++ svg {+ max-width: 100%;+ height: auto;+ }`;const MetaContainer = styled.div`@@ -153,6 +164,12 @@ const TILE_TYPES = [label: 'Bitmap',Icon: BitmapLayerIcon,Component: TilesetBitmapForm+ },+ {+ id: 'zarr',+ label: 'Zarr',+ Icon: ZarrLayerIcon,+ Component: TilesetZarrForm}];@@ -173,7 +190,16 @@ function LoadTilesetTabFactory() {const error = response.error;const loading = response.loading;const data = response.metadata;- const jsonDataText = useMemo(() => JSON.stringify(data, null, 2), [data]);+ const isZarr = response.dataset?.type === DatasetType.ZARR;+ const jsonDataText = useMemo(+ () =>+ JSON.stringify(+ data && isZarr ? getZarrMetadataPreview(data as ZarrDatasetMetadata) : data,+ null,+ 2+ ),+ [data, isZarr]+ );const createTileDataset = useCallback(() => {const {dataset, metadata} = response;@@ -196,6 +222,7 @@ function LoadTilesetTabFactory() {const enableRasterTileLayer = getApplicationConfig().enableRasterTileLayer;const enableWMSLayer = getApplicationConfig().enableWMSLayer;const enableBitmapLayer = getApplicationConfig().enableBitmapLayer;+ const enableZarrLayer = getApplicationConfig().enableZarrLayer;// Filter tile types based on application configconst tileTypes = useMemo(() => {@@ -209,10 +236,13 @@ function LoadTilesetTabFactory() {if (tileType.id === 'bitmap') {return enableBitmapLayer;}+ if (tileType.id === 'zarr') {+ return enableZarrLayer;+ }return true; // Include all other types by default});return types;- }, [enableRasterTileLayer, enableWMSLayer, enableBitmapLayer]);+ }, [enableRasterTileLayer, enableWMSLayer, enableBitmapLayer, enableZarrLayer]);const CurrentForm = tileTypes[typeIndex].Component;@@ -238,7 +268,11 @@ function LoadTilesetTabFactory() {<MetaContainer>{loading ? (<MetaLoading>- <LoadingSpinner />+ {response.progress ? (+ <ZarrMetadataLoading progress={response.progress} />+ ) : (+ <LoadingSpinner />+ )}</MetaLoading>) : data && 'imagePreviewUrl' in data ? (<BitmapPreviewContainer>@@ -248,7 +282,8 @@ function LoadTilesetTabFactory() {<AutoSizer>{({height, width}) => (<MetaInnerContainer height={height} width={width}>- <JSONPretty id="json-pretty" json={jsonDataText} />+ {isZarr ? <p>Metadata summary with coordinate samples.</p> : null}+ <MemoizedJSONPretty id="json-pretty" json={jsonDataText} /></MetaInnerContainer>)}</AutoSizer>diff --git a/src/components/src/modals/tilesets-modals/tileset-zarr-form.spec.tsx b/src/components/src/modals/tilesets-modals/tileset-zarr-form.spec.tsxnew file mode 100644index 000000000..0884c3914--- /dev/null+++ b/src/components/src/modals/tilesets-modals/tileset-zarr-form.spec.tsx@@ -0,0 +1,349 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++// @ts-nocheck+import React from 'react';+import {act, fireEvent, waitFor} from '@testing-library/react';+import {renderWithTheme} from 'test/helpers/component-jest-utils';++import TilesetZarrForm from './tileset-zarr-form';++jest.mock('@kepler.gl/table', () => ({+ getZarrMetadata: jest.fn()+}));++// eslint-disable-next-line @typescript-eslint/no-var-requires+const {getZarrMetadata} = require('@kepler.gl/table');++const VALID_URL = 'https://example.com/store.zarr';+const INVALID_URL = 'not a url';++const lastResponse = setResponse => setResponse.mock.calls[setResponse.mock.calls.length - 1][0];++function noop() {+ return;+}++describe('TilesetZarrForm', () => {+ beforeEach(() => {+ getZarrMetadata.mockReset();+ });++ it('keeps the default and all variables for layer configuration without showing variable controls or the spatial summary', async () => {+ const variables = [+ {path: 'FUTUR/qtot', displayName: 'Future runoff', nonSpatialDims: []},+ {path: 'HISTO/qtot', displayName: 'Historical runoff', nonSpatialDims: []}+ ];+ const metadata = {+ url: VALID_URL,+ variable: variables[1].path,+ variables,+ nonSpatialDims: [],+ levels: [{path: '.', shape: [2, 2], chunks: [2, 2]}],+ crs: {code: 'EPSG:4326'}+ };+ getZarrMetadata.mockResolvedValue(metadata);+ const setResponse = jest.fn();+ const {container, getByLabelText, queryByText} = renderWithTheme(+ <TilesetZarrForm setResponse={setResponse} />+ );++ fireEvent.change(getByLabelText('Zarr store URL'), {target: {value: VALID_URL}});+ await waitFor(() => {+ expect(lastResponse(setResponse).dataset).not.toBeNull();+ expect(lastResponse(setResponse).loading).toBe(false);+ });++ const response = lastResponse(setResponse);+ expect(response.metadata).toBe(metadata);+ expect(response.dataset.metadata).toBe(metadata);+ expect(response.dataset.metadata.variable).toBe(variables[1].path);+ expect(response.dataset.metadata.variables).toBe(variables);+ expect(getByLabelText('Name')).toHaveValue(variables[1].path);+ expect(queryByText('Variable')).not.toBeInTheDocument();+ for (const variable of variables) {+ expect(queryByText(variable.displayName)).not.toBeInTheDocument();+ }+ expect(container).not.toHaveTextContent(/resolution level|EPSG:4326/);+ });++ it.each([+ [+ 'CMIP6 Water Resources',+ 'https://data.source.coop/earthblox/cciwr/data/cciwr.zarr',+ /runoff.*groundwater recharge.*evapotranspiration/i,+ ['season', 'gcm', 'ghm', 'ssp', 'horizon'],+ undefined+ ],+ [+ 'ECMWF IFS Ensemble',+ 'https://data.source.coop/dynamical/ecmwf-ifs-ens-forecast-15-day-0-25-degree/v0.1.0.zarr',+ /temperature.*precipitation.*wind.*pressure/i,+ ['Valid time', 'init_time', 'lead_time', 'ensemble_member'],+ 'dew_point_temperature_2m'+ ],+ [+ 'NOAA HRRR Forecast',+ 'https://data.source.coop/dynamical/noaa-hrrr-forecast-48-hour/v0.1.0.zarr',+ /temperature.*rain.*snow.*wind.*radar reflectivity/i,+ ['Valid time', 'init_time', 'lead_time'],+ 'relative_humidity_2m'+ ]+ ])(+ 'shows details for %s on focus and loads it only when selected',+ async (name, url, data, axes, variable) => {+ getZarrMetadata.mockReturnValue(new Promise(noop));+ const {getByRole, getByLabelText} = renderWithTheme(+ <TilesetZarrForm setResponse={jest.fn()} />+ );++ fireEvent.focus(getByRole('button', {name: `About ${name}`}));+ await waitFor(() => {+ expect(getByRole('tooltip')).toHaveTextContent(name);+ expect(getByRole('tooltip')).toHaveTextContent(data);+ for (const axis of axes) {+ expect(getByRole('tooltip')).toHaveTextContent(axis);+ }+ });+ expect(getZarrMetadata).not.toHaveBeenCalled();+ expect(getByLabelText('Zarr store URL')).toHaveValue('');++ const example = getByRole('button', {name: `Use ${name}`});+ fireEvent.click(example);+ expect(getByLabelText('Name')).toHaveValue(name);+ expect(getByLabelText('Zarr store URL')).toHaveValue(url);+ expect(example).toHaveAttribute('aria-pressed', 'true');+ await waitFor(() =>+ expect(getZarrMetadata).toHaveBeenCalledWith(url, {+ variable,+ signal: expect.any(AbortSignal),+ onProgress: expect.any(Function)+ })+ );++ fireEvent.change(getByLabelText('Zarr store URL'), {target: {value: INVALID_URL}});+ expect(example).toHaveAttribute('aria-pressed', 'false');+ }+ );++ it('stops loading when the url is edited to an invalid one mid-request', async () => {+ // A request that never settles, standing in for one still in flight.+ getZarrMetadata.mockReturnValue(new Promise(noop));++ const setResponse = jest.fn();+ const {getByPlaceholderText} = renderWithTheme(<TilesetZarrForm setResponse={setResponse} />);+ const input = getByPlaceholderText('Enter Zarr store URL');++ fireEvent.change(input, {target: {value: VALID_URL}});+ await waitFor(() => expect(lastResponse(setResponse).loading).toBe(true), {timeout: 3000});++ fireEvent.change(input, {target: {value: INVALID_URL}});+ expect(getZarrMetadata.mock.calls[0][1].signal.aborted).toBe(true);+ expect(lastResponse(setResponse)).toMatchObject({loading: false, error: null, dataset: null});+ });++ describe('request lifecycle', () => {+ beforeEach(() => jest.useFakeTimers());+ afterEach(() => jest.useRealTimers());++ function startRequest() {+ const setResponse = jest.fn();+ const view = renderWithTheme(<TilesetZarrForm setResponse={setResponse} />);+ const input = view.getByLabelText('Zarr store URL');+ fireEvent.change(input, {target: {value: VALID_URL}});+ act(() => jest.advanceTimersByTime(500));+ return {...view, input, setResponse, signal: getZarrMetadata.mock.calls[0][1].signal};+ }++ it('uses each example default without carrying it to custom stores', async () => {+ getZarrMetadata.mockImplementation((url, {variable}) =>+ Promise.resolve({url, variable: variable ?? 'temperature', variables: [], levels: []})+ );+ const setResponse = jest.fn();+ const {getByRole, getByLabelText} = renderWithTheme(+ <TilesetZarrForm setResponse={setResponse} />+ );+ fireEvent.click(getByRole('button', {name: 'Use NOAA HRRR Forecast'}));+ await act(async () => jest.advanceTimersByTime(500));+ expect(lastResponse(setResponse).dataset.metadata.variable).toBe('relative_humidity_2m');++ fireEvent.click(getByRole('button', {name: 'Use ECMWF IFS Ensemble'}));+ await act(async () => jest.advanceTimersByTime(500));+ expect(lastResponse(setResponse).dataset.metadata.variable).toBe('dew_point_temperature_2m');++ fireEvent.change(getByLabelText('Zarr store URL'), {target: {value: VALID_URL}});+ await act(async () => jest.advanceTimersByTime(500));+ expect(lastResponse(setResponse).dataset.metadata.variable).toBe('temperature');+ });++ it('cancels the debounce when the form closes before a request starts', () => {+ const {getByLabelText, unmount} = renderWithTheme(+ <TilesetZarrForm setResponse={jest.fn()} />+ );+ fireEvent.change(getByLabelText('Zarr store URL'), {target: {value: VALID_URL}});+ unmount();+ act(() => jest.advanceTimersByTime(500));+ expect(getZarrMetadata).not.toHaveBeenCalled();+ });++ it('aborts immediately on a new URL and ignores a stale response', async () => {+ let resolveOld;+ getZarrMetadata.mockReturnValueOnce(new Promise(resolve => (resolveOld = resolve)));+ const latest = {variable: 'latest', variables: [], levels: []};+ getZarrMetadata.mockResolvedValueOnce(latest);+ const {input, signal, setResponse} = startRequest();+ const oldProgress = getZarrMetadata.mock.calls[0][1].onProgress;++ fireEvent.change(input, {target: {value: `${VALID_URL}/new`}});+ act(() => oldProgress({phase: 'downloading', loadedBytes: 100}));+ expect(signal.aborted).toBe(true);+ expect(getZarrMetadata).toHaveBeenCalledTimes(1);+ expect(lastResponse(setResponse).metadata).toBeNull();+ expect(lastResponse(setResponse).progress).toBeNull();+ await act(async () => jest.advanceTimersByTime(500));+ expect(lastResponse(setResponse).metadata).toBe(latest);++ await act(async () => resolveOld({variable: 'stale', variables: [], levels: []}));+ expect(lastResponse(setResponse).metadata).toBe(latest);+ expect(lastResponse(setResponse).error).toBeNull();+ });++ it('aborts on unmount and clears the timeout without reporting an error', () => {+ getZarrMetadata.mockReturnValue(new Promise(noop));+ const {signal, setResponse, unmount} = startRequest();+ unmount();+ expect(signal.aborted).toBe(true);+ setResponse.mockClear();+ act(() => jest.advanceTimersByTime(120_000));+ expect(setResponse).not.toHaveBeenCalled();+ });++ it('aborts a timed-out load, ignores late results, and allows another URL', async () => {+ let resolveLate;+ getZarrMetadata.mockReturnValueOnce(new Promise(resolve => (resolveLate = resolve)));+ const {signal, input, setResponse} = startRequest();+ act(() => jest.advanceTimersByTime(119_999));+ expect(signal.aborted).toBe(false);+ expect(lastResponse(setResponse).loading).toBe(true);+ act(() => jest.advanceTimersByTime(1));+ expect(signal.aborted).toBe(true);+ expect(lastResponse(setResponse)).toMatchObject({loading: false, dataset: null});+ expect(lastResponse(setResponse).error.message).toMatch(/timed out/i);++ await act(async () => resolveLate({variable: 'late', variables: [], levels: []}));+ expect(lastResponse(setResponse).metadata).toBeNull();+ expect(lastResponse(setResponse).error.message).toMatch(/timed out/i);++ const metadata = {variable: 'retry', variables: [], levels: []};+ getZarrMetadata.mockResolvedValueOnce(metadata);+ fireEvent.change(input, {target: {value: `${VALID_URL}/retry`}});+ await act(async () => jest.advanceTimersByTime(500));+ expect(lastResponse(setResponse)).toMatchObject({metadata, loading: false, error: null});+ });++ it('continues while bytes arrive and aborts only after 2 minutes without progress', () => {+ getZarrMetadata.mockReturnValue(new Promise(noop));+ const {signal, setResponse} = startRequest();+ const {onProgress} = getZarrMetadata.mock.calls[0][1];++ for (const loadedBytes of [100, 200, 300]) {+ act(() => jest.advanceTimersByTime(119_000));+ act(() => onProgress({phase: 'downloading', loadedBytes, totalBytes: 1000}));+ expect(signal.aborted).toBe(false);+ expect(lastResponse(setResponse).progress.loadedBytes).toBe(loadedBytes);+ }+ act(() => jest.advanceTimersByTime(119_999));+ // Repeating the same status is not progress and must not extend the deadline.+ act(() => onProgress({phase: 'downloading', loadedBytes: 300, totalBytes: 1000}));+ expect(signal.aborted).toBe(false);+ act(() => jest.advanceTimersByTime(1));+ expect(signal.aborted).toBe(true);+ expect(lastResponse(setResponse).loading).toBe(false);+ expect(lastResponse(setResponse).error.message).toMatch(/2 minutes without progress/);++ const response = lastResponse(setResponse);+ act(() => onProgress({phase: 'downloading', loadedBytes: 400, totalBytes: 1000}));+ expect(lastResponse(setResponse)).toBe(response);+ });++ it('clears the deadline after a successful load', async () => {+ const metadata = {variable: 'success', variables: [], levels: []};+ getZarrMetadata.mockResolvedValue(metadata);+ const {signal, setResponse} = startRequest();+ await act(async () => {+ // Flush the already-resolved metadata promise and its state updates.+ });+ act(() => jest.advanceTimersByTime(120_000));+ expect(signal.aborted).toBe(false);+ expect(lastResponse(setResponse)).toMatchObject({metadata, loading: false, error: null});+ });++ it.each(['timeout', 'request error'])(+ 'retries the same example after a %s and ignores the old response',+ async failure => {+ let resolveOld;+ const oldRequest = new Promise(resolve => (resolveOld = resolve));+ if (failure === 'timeout') {+ getZarrMetadata.mockReturnValueOnce(oldRequest);+ } else {+ getZarrMetadata.mockRejectedValueOnce(new Error('Temporary network failure'));+ }+ let resolveRetry;+ getZarrMetadata.mockReturnValueOnce(new Promise(resolve => (resolveRetry = resolve)));+ const setResponse = jest.fn();+ const {getByRole} = renderWithTheme(<TilesetZarrForm setResponse={setResponse} />);+ const example = getByRole('button', {name: 'Use NOAA HRRR Forecast'});+ fireEvent.click(example);+ await act(async () => jest.advanceTimersByTime(500));+ if (failure === 'timeout') {+ act(() => jest.advanceTimersByTime(120_000));+ }+ expect(lastResponse(setResponse).error).toBeInstanceOf(Error);+ expect(lastResponse(setResponse).loading).toBe(false);+ const [url, {signal: oldSignal}] = getZarrMetadata.mock.calls[0];++ fireEvent.click(example);+ expect(lastResponse(setResponse).error).toBeNull();+ expect(oldSignal.aborted).toBe(true);+ act(() => jest.advanceTimersByTime(500));+ expect(getZarrMetadata).toHaveBeenCalledTimes(2);+ const [retriedUrl, {signal: retrySignal}] = getZarrMetadata.mock.calls[1];+ expect(retriedUrl).toBe(url);+ expect(retrySignal).not.toBe(oldSignal);+ expect(retrySignal.aborted).toBe(false);+ expect(lastResponse(setResponse).loading).toBe(true);++ // Clicking a pending request must not restart it or its timeout.+ fireEvent.click(example);+ act(() => jest.advanceTimersByTime(500));+ expect(getZarrMetadata).toHaveBeenCalledTimes(2);+ const metadata = {variable: 'retry', variables: [], levels: []};+ await act(async () => resolveRetry(metadata));+ await act(async () => resolveOld({variable: 'stale', variables: [], levels: []}));+ expect(lastResponse(setResponse)).toMatchObject({metadata, loading: false, error: null});++ fireEvent.click(example);+ act(() => jest.advanceTimersByTime(500));+ expect(getZarrMetadata).toHaveBeenCalledTimes(2);+ }+ );+ });++ it('reports the error from a store it cannot read', async () => {+ getZarrMetadata.mockRejectedValue(new Error('bad store'));++ const setResponse = jest.fn();+ const {getByPlaceholderText} = renderWithTheme(<TilesetZarrForm setResponse={setResponse} />);++ fireEvent.change(getByPlaceholderText('Enter Zarr store URL'), {target: {value: VALID_URL}});++ await waitFor(+ () => {+ const response = lastResponse(setResponse);+ expect(response.loading).toBe(false);+ expect(response.error?.message).toBe('bad store');+ },+ {timeout: 3000}+ );+ });+});diff --git a/src/components/src/modals/tilesets-modals/tileset-zarr-form.tsx b/src/components/src/modals/tilesets-modals/tileset-zarr-form.tsxnew file mode 100644index 000000000..bb0fbf62c--- /dev/null+++ b/src/components/src/modals/tilesets-modals/tileset-zarr-form.tsx@@ -0,0 +1,333 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import React, {useCallback, useEffect, useState} from 'react';+import styled from 'styled-components';++import {validateUrl} from '@kepler.gl/common-utils';+import {DatasetType, ZarrDatasetMetadata} from '@kepler.gl/constants';+import {getZarrMetadata, ZarrMetadataProgress} from '@kepler.gl/table';+import {getApplicationConfig} from '@kepler.gl/utils';++import {MetaResponse} from './common';+import {InputLight} from '../../common';+import {Help} from '../../common/icons';+import TippyTooltip from '../../common/tippy-tooltip';++const TilesetInputContainer = styled.div`+ display: grid;+ grid-template-rows: repeat(3, auto);+ row-gap: 18px;+ font-size: 12px;+`;++const TilesetInputDescription = styled.div`+ text-align: center;+ color: ${props => props.theme.AZURE200};+ font-size: 11px;+`;++const Tab = styled.div<{$active: boolean}>`+ padding: 3px 8px;+ border-radius: 3px;+ cursor: pointer;+ font-size: 11px;+ white-space: nowrap;+ background: ${props => (props.$active ? props.theme.AZURE400 : 'transparent')};+ color: ${props => (props.$active ? props.theme.WHITE : props.theme.AZURE200)};+ border: 1px solid ${props => props.theme.AZURE400};++ &:hover {+ background: ${props => (props.$active ? props.theme.AZURE400 : props.theme.AZURE500)};+ }+`;++const ExamplesRow = styled.div`+ display: flex;+ justify-content: center;+ gap: 12px;+ margin: 6px 0;+`;++const ExampleItem = styled(Tab)`+ display: flex;+ align-items: center;+ gap: 4px;+ padding: 0 6px 0 0;+ cursor: default;+`;++const ExampleName = styled.button`+ padding: 3px 8px;+ border: 0;+ background: transparent;+ color: inherit;+ font: inherit;+ white-space: nowrap;+ cursor: pointer;+`;++const ExampleInfoButton = styled.button`+ display: inline-flex;+ padding: 0;+ border: 0;+ background: transparent;+ color: inherit;+ cursor: help;++ &:hover {+ color: ${props => props.theme.AZURE100};+ }+`;++const ExampleDetails = styled.div`+ display: flex;+ flex-direction: column;+ gap: 6px;+ max-width: 280px;+ white-space: normal;+ overflow-wrap: anywhere;+`;++/** Avoid firing a store read on every keystroke of a long object-storage URL. */+const URL_DEBOUNCE_MS = 500;+const METADATA_IDLE_TIMEOUT_MS = 120_000;++/**+ * Public Zarr stores on Source Cooperative. Note the `data.` host: `source.coop`+ * serves the web UI, not the objects.+ */+const ZARR_EXAMPLES = [+ {+ // https://source.coop/earthblox/cciwr/README.md+ label: 'CMIP6',+ name: 'CMIP6 Water Resources',+ description:+ 'Global runoff, groundwater recharge, and evapotranspiration: historical baselines, future projections, and relative changes.',+ timeline:+ 'Choose season, gcm (climate model), or ghm (hydrological model). FUTUR and RC also offer ssp (emissions scenario) and horizon (30-year periods centered on 2030, 2055, and 2085). Only the selected dimension changes during playback.',+ url: 'https://data.source.coop/earthblox/cciwr/data/cciwr.zarr'+ },+ {+ // https://dynamical.org/catalog/ecmwf-ifs-ens-forecast-15-day-0-25-degree/+ label: 'ECMWF IFS',+ name: 'ECMWF IFS Ensemble',+ description:+ 'Global weather forecasts up to 15 days ahead, including temperature, precipitation, wind, and pressure, across 51 ensemble members.',+ timeline:+ 'Choose Valid time (init_time + lead_time) to play one forecast run with a fixed ensemble member. You can also select init_time (run date), lead_time (forecast step), or ensemble_member individually.',+ url: 'https://data.source.coop/dynamical/ecmwf-ifs-ens-forecast-15-day-0-25-degree/v0.1.0.zarr',+ defaultVariable: 'dew_point_temperature_2m'+ },+ {+ // https://dynamical.org/catalog/noaa-hrrr-forecast-48-hour/+ label: 'NOAA HRRR',+ name: 'NOAA HRRR Forecast',+ description:+ 'Hourly weather forecasts up to 48 hours ahead for the continental US at 3 km resolution, including temperature, rain, snow, wind, and radar reflectivity.',+ timeline:+ 'Choose Valid time (init_time + lead_time) to play through one forecast run. You can also select init_time (run date) or lead_time (forecast step) individually.',+ url: 'https://data.source.coop/dynamical/noaa-hrrr-forecast-48-hour/v0.1.0.zarr',+ defaultVariable: 'relative_humidity_2m'+ }+];++type ZarrFormProps = {+ setResponse: (response: MetaResponse) => void;+};++const TilesetZarrForm: React.FC<ZarrFormProps> = ({setResponse}) => {+ const [datasetName, setDatasetName] = useState<string>('');+ const [url, setUrl] = useState<string>('');+ const [metadata, setMetadata] = useState<ZarrDatasetMetadata | null>(null);+ const [loading, setLoading] = useState<boolean>(false);+ const [progress, setProgress] = useState<ZarrMetadataProgress | null>(null);+ const [error, setError] = useState<Error | null>(null);+ const [retryCount, setRetryCount] = useState(0);++ const onExampleClick = useCallback(+ (index: number) => {+ const example = ZARR_EXAMPLES[index];+ if (url === example.url && error) {+ setRetryCount(count => count + 1);+ }+ setUrl(example.url);+ setDatasetName(example.name);+ },+ [url, error]+ );++ const onDatasetNameChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {+ event.preventDefault();+ setDatasetName(event.target.value);+ }, []);++ const onUrlChange = useCallback((event: React.ChangeEvent<HTMLInputElement>) => {+ event.preventDefault();+ setUrl(event.target.value);+ }, []);++ useEffect(() => {+ setMetadata(null);+ setError(null);+ setLoading(false);+ setProgress(null);+ if (!validateUrl(url.trim())) {+ return;+ }++ const controller = new AbortController();+ let cancelled = false;+ let deadline: ReturnType<typeof setTimeout> | undefined;+ let previousProgress: ZarrMetadataProgress = {phase: 'connecting', loadedBytes: 0};+ const resetDeadline = () => {+ clearTimeout(deadline);+ deadline = setTimeout(() => {+ const timeoutError = new Error(+ 'Zarr metadata loading timed out after 2 minutes without progress. Check the connection or try again.'+ );+ cancelled = true;+ controller.abort(timeoutError);+ setError(timeoutError);+ setLoading(false);+ }, METADATA_IDLE_TIMEOUT_MS);+ };+ const debounce = setTimeout(() => {+ setLoading(true);+ setProgress({phase: 'connecting', loadedBytes: 0});+ resetDeadline();++ getZarrMetadata(url.trim(), {+ variable: ZARR_EXAMPLES.find(example => example.url === url.trim())?.defaultVariable,+ signal: controller.signal,+ onProgress: nextProgress => {+ if (cancelled) return;+ if (+ nextProgress.loadedBytes > previousProgress.loadedBytes ||+ nextProgress.phase !== previousProgress.phase+ ) {+ resetDeadline();+ }+ previousProgress = nextProgress;+ setProgress(nextProgress);+ }+ })+ .then(zarrMetadata => {+ if (cancelled) {+ return;+ }+ setMetadata(zarrMetadata);+ })+ .catch((err: unknown) => {+ if (!cancelled) {+ setError(err instanceof Error ? err : new Error('Failed to read Zarr store'));+ }+ })+ .finally(() => {+ clearTimeout(deadline);+ if (!cancelled) {+ setLoading(false);+ }+ });+ }, URL_DEBOUNCE_MS);++ return () => {+ cancelled = true;+ clearTimeout(debounce);+ clearTimeout(deadline);+ controller.abort();+ };+ }, [url, retryCount]);++ useEffect(() => {+ if (!metadata || !datasetName) {+ setResponse({metadata: null, dataset: null, loading, error, progress});+ return;+ }+ setResponse({+ metadata,+ dataset: {+ name: datasetName,+ type: DatasetType.ZARR,+ metadata+ },+ loading,+ error,+ progress+ });+ }, [setResponse, datasetName, metadata, loading, error, progress]);++ // Default the dataset name to the default variable so the Add button is+ // reachable without extra typing.+ useEffect(() => {+ if (!datasetName && metadata?.variable) {+ setDatasetName(metadata.variable);+ }+ // Only react to the variable, not to the user editing the name.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [metadata?.variable]);++ return (+ <TilesetInputContainer>+ <div>+ <label htmlFor="zarr-dataset-name">Name</label>+ <InputLight+ id="zarr-dataset-name"+ placeholder="Name your Zarr layer"+ value={datasetName}+ onChange={onDatasetNameChange}+ />+ </div>+ <div>+ <label htmlFor="zarr-url">Zarr store URL</label>+ <InputLight+ id="zarr-url"+ placeholder="Enter Zarr store URL"+ value={url}+ onChange={onUrlChange}+ />+ <TilesetInputDescription>+ Provide a Zarr store with a GeoZarr or CF-conventions spatial grid.+ </TilesetInputDescription>+ </div>+ {getApplicationConfig().showInlineTilesetExamples && (+ <div>+ <TilesetInputDescription>For example, try a public Zarr store:</TilesetInputDescription>+ <ExamplesRow>+ {ZARR_EXAMPLES.map((example, index) => (+ <ExampleItem key={example.name} $active={url === example.url}>+ <ExampleName+ type="button"+ aria-label={`Use ${example.name}`}+ aria-pressed={url === example.url}+ onClick={() => onExampleClick(index)}+ >+ {example.label}+ </ExampleName>+ <TippyTooltip+ placement="top"+ isLightTheme+ render={() => (+ <ExampleDetails role="tooltip">+ <strong>{example.name}</strong>+ <div>{example.description}</div>+ <div>+ <strong>Timeline:</strong> {example.timeline}+ </div>+ </ExampleDetails>+ )}+ >+ <ExampleInfoButton type="button" aria-label={`About ${example.name}`}>+ <Help height="14px" />+ </ExampleInfoButton>+ </TippyTooltip>+ </ExampleItem>+ ))}+ </ExamplesRow>+ </div>+ )}+ </TilesetInputContainer>+ );+};++export default TilesetZarrForm;diff --git a/src/components/src/modals/tilesets-modals/zarr-metadata-preview.ts b/src/components/src/modals/tilesets-modals/zarr-metadata-preview.tsnew file mode 100644index 000000000..4ca1ba746--- /dev/null+++ b/src/components/src/modals/tilesets-modals/zarr-metadata-preview.ts@@ -0,0 +1,63 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import type {ZarrDatasetMetadata, ZarrDimensionInfo} from '@kepler.gl/constants';++const MAX_PREVIEW_ITEMS = 20;+const COORDINATE_SAMPLE_SIZE = 3;++function previewDimension(dimension: ZarrDimensionInfo) {+ const values = dimension.values;+ return {+ name: dimension.name,+ size: dimension.size,+ kind: dimension.kind,+ units: dimension.units,+ calendar: dimension.calendar,+ coordinates: values+ ? {+ count: values.length,+ first: values.slice(0, COORDINATE_SAMPLE_SIZE),+ ...(values.length > COORDINATE_SAMPLE_SIZE+ ? {+ last: values.slice(+ -Math.min(COORDINATE_SAMPLE_SIZE, values.length - COORDINATE_SAMPLE_SIZE)+ )+ }+ : {})+ }+ : undefined+ };+}++/** Keep the preview small without serializing or modifying the full coordinate arrays. */+export function getZarrMetadataPreview(metadata: ZarrDatasetMetadata) {+ const variable =+ metadata.variables.find(item => item.path === metadata.variable) ?? metadata.variables[0];+ const dimensions = variable?.nonSpatialDims ?? metadata.nonSpatialDims;+ return {+ url: metadata.url,+ variableCount: metadata.variables.length,+ variables: metadata.variables.slice(0, MAX_PREVIEW_ITEMS).map(item => item.displayName),+ omittedVariables: Math.max(0, metadata.variables.length - MAX_PREVIEW_ITEMS),+ selectedVariable: variable+ ? {+ path: variable.path,+ name: variable.displayName,+ dtype: variable.dtype,+ shape: variable.shape,+ chunks: variable.chunks,+ dataRange: variable.dataRange,+ nodataValue: variable.nodataValue+ }+ : undefined,+ dimensionCount: dimensions.length,+ dimensions: dimensions.slice(0, MAX_PREVIEW_ITEMS).map(previewDimension),+ omittedDimensions: Math.max(0, dimensions.length - MAX_PREVIEW_ITEMS),+ timeDimension: variable?.timeDimension?.name,+ crs: metadata.crs,+ resolutionLevelCount: metadata.levels.length,+ levels: metadata.levels.slice(0, MAX_PREVIEW_ITEMS),+ omittedLevels: Math.max(0, metadata.levels.length - MAX_PREVIEW_ITEMS)+ };+}diff --git a/src/components/src/modals/tilesets-modals/zarr-metadata-progress.tsx b/src/components/src/modals/tilesets-modals/zarr-metadata-progress.tsxnew file mode 100644index 000000000..a71e2a98f--- /dev/null+++ b/src/components/src/modals/tilesets-modals/zarr-metadata-progress.tsx@@ -0,0 +1,90 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import React from 'react';+import styled, {keyframes, useTheme} from 'styled-components';+import type {ZarrMetadataProgress} from '@kepler.gl/table';+import ProgressBar from '../../common/progress-bar';++const move = keyframes`+ from { transform: translateX(-100%); }+ to { transform: translateX(300%); }+`;++const Container = styled.div<{$indeterminate: boolean}>`+ width: 100%;+ padding: 24px;+ color: ${props => props.theme.textColor};+ font-size: 12px;++ .progress-bar {+ margin: 12px 0;+ overflow: hidden;+ }++ .progress-bar__bar {+ animation: ${props => (props.$indeterminate ? move : 'none')} 1.5s linear infinite;+ }++ @media (prefers-reduced-motion: reduce) {+ .progress-bar__bar {+ animation: none;+ }+ }+`;++function formatBytes(bytes: number): string {+ if (bytes < 1000) return `${bytes} B`;+ if (bytes < 1_000_000) return `${(bytes / 1000).toFixed(1)} kB`;+ return `${(bytes / 1_000_000).toFixed(1)} MB`;+}++export default function ZarrMetadataLoading({progress}: {progress: ZarrMetadataProgress}) {+ const theme = useTheme();+ const {phase, loadedBytes, totalBytes} = progress;+ const percent =+ phase === 'downloading' && totalBytes+ ? Math.min(99, Math.floor((loadedBytes / totalBytes) * 100))+ : undefined;+ const label =+ phase === 'connecting'+ ? loadedBytes+ ? 'Waiting for metadata response…'+ : 'Connecting to Zarr store…'+ : phase === 'downloading'+ ? 'Downloading metadata…'+ : 'Reading variables and coordinates…';+ const detail =+ phase === 'connecting'+ ? `${+ loadedBytes ? `${formatBytes(loadedBytes)} received · ` : ''+ }Waiting for the server to respond.`+ : percent !== undefined && totalBytes !== undefined+ ? `${formatBytes(loadedBytes)} / ${formatBytes(totalBytes)} received (${percent}%)`+ : `${formatBytes(loadedBytes)} received${+ phase === 'downloading' ? ' · total size unavailable' : ''+ }`;++ return (+ <Container $indeterminate={percent === undefined}>+ <div role="status">{label}</div>+ <div+ role="progressbar"+ aria-label="Zarr metadata loading"+ aria-valuemin={0}+ aria-valuemax={100}+ aria-valuenow={percent}+ aria-valuetext={`${label} ${detail}`}+ >+ <ProgressBar+ percent={percent === undefined ? '35%' : `${percent}%`}+ height={6}+ isLoading+ barColor={theme.activeColor || ''}+ theme={theme}+ />+ </div>+ <div>{detail}</div>+ </Container>+ );+}diff --git a/src/components/src/side-panel/common/dataset-info.tsx b/src/components/src/side-panel/common/dataset-info.tsxindex 8833ca44e..bcdded6cc 100644--- a/src/components/src/side-panel/common/dataset-info.tsx+++ b/src/components/src/side-panel/common/dataset-info.tsx@@ -229,6 +229,8 @@ export default function DatasetInfoFactory() {? 'datasetInfo.tile3d': dataset.type === DatasetType.BITMAP? 'datasetInfo.bitmap'+ : dataset.type === DatasetType.ZARR+ ? 'datasetInfo.zarr': isRemote? 'datasetInfo.remoteFile': 'datasetInfo.rowCount'diff --git a/src/components/src/side-panel/layer-manager.tsx b/src/components/src/side-panel/layer-manager.tsxindex 892b16a10..7b6e84324 100644--- a/src/components/src/side-panel/layer-manager.tsx+++ b/src/components/src/side-panel/layer-manager.tsx@@ -209,6 +209,7 @@ function LayerManagerFactory(const enableA5Layer = getApplicationConfig().enableA5Layer;const enableGeohashLayer = getApplicationConfig().enableGeohashLayer;const enableFlowFieldLayer = getApplicationConfig().enableFlowFieldLayer;+ const enableZarrLayer = getApplicationConfig().enableZarrLayer;const enableLayerGroups = getApplicationConfig().enableLayerGroups;const filteredLayerClasses = useMemo(() => {@@ -237,6 +238,10 @@ function LayerManagerFactory(const {flowField: _flowField, ...rest} = filteredClasses;filteredClasses = rest as LayerClassesType;}+ if (!enableZarrLayer) {+ const {zarr: _zarr, ...rest} = filteredClasses;+ filteredClasses = rest as LayerClassesType;+ }return filteredClasses as LayerClassesType;}, [enableRasterTileLayer,@@ -245,6 +250,7 @@ function LayerManagerFactory(enableA5Layer,enableGeohashLayer,enableFlowFieldLayer,+ enableZarrLayer,layerClasses]);diff --git a/src/components/src/side-panel/layer-panel/dataset-layer-section.tsx b/src/components/src/side-panel/layer-panel/dataset-layer-section.tsxindex 4ca46829b..26ee720a7 100644--- a/src/components/src/side-panel/layer-panel/dataset-layer-section.tsx+++ b/src/components/src/side-panel/layer-panel/dataset-layer-section.tsx@@ -69,6 +69,7 @@ function DatasetLayerSectionFactory(const enableA5Layer = getApplicationConfig().enableA5Layer;const enableGeohashLayer = getApplicationConfig().enableGeohashLayer;const enableFlowFieldLayer = getApplicationConfig().enableFlowFieldLayer;+ const enableZarrLayer = getApplicationConfig().enableZarrLayer;const filteredLayerClasses = useMemo(() => {let filteredClasses = layerClasses;@@ -100,6 +101,10 @@ function DatasetLayerSectionFactory(const {flowField: _flowField, ...rest} = filteredClasses;filteredClasses = rest as LayerClassesType;}+ if (!enableZarrLayer) {+ const {zarr: _zarr, ...rest} = filteredClasses;+ filteredClasses = rest as LayerClassesType;+ }return filteredClasses as LayerClassesType;}, [enableRasterTileLayer,@@ -109,6 +114,7 @@ function DatasetLayerSectionFactory(enableA5Layer,enableGeohashLayer,enableFlowFieldLayer,+ enableZarrLayer,layerClasses]);diff --git a/src/components/src/side-panel/layer-panel/layer-configurator.tsx b/src/components/src/side-panel/layer-panel/layer-configurator.tsxindex 848d620ee..53331e16f 100644--- a/src/components/src/side-panel/layer-panel/layer-configurator.tsx+++ b/src/components/src/side-panel/layer-panel/layer-configurator.tsx@@ -33,6 +33,7 @@ import ScenegraphModelSelectorFactory, {import RasterTileLayerConfiguratorFactory from './raster-tile-layer-configurator';import VectorTileLayerConfiguratorFactory from './vector-tile-layer-configurator';import LayerApiKeyInput from './layer-api-key-input';+import ZarrAxisSelector from './zarr-axis-selector';import {ActionHandler, toggleModal, updateDatasetProps} from '@kepler.gl/actions';import {@@ -50,7 +51,13 @@ import {createPointCountLabelField} from '@kepler.gl/layers';-import {matchDatasetType, Datasets} from '@kepler.gl/table';+import {+ matchDatasetType,+ Datasets,+ getZarrAxisDimensions,+ isExplicitZarrAxis,+ formatZarrCoordinate+} from '@kepler.gl/table';import {ColorUI, LayerVisConfig, NestedPartial} from '@kepler.gl/types';import {capitalizeFirstLetter} from '@kepler.gl/utils';@@ -1832,6 +1839,106 @@ export default function LayerConfiguratorFactory();}+ _renderZarrLayerConfig({layer, dataset, visConfiguratorProps}) {+ const {visConfig} = layer.config;+ const metadata = dataset?.metadata ?? {};+ const variables = metadata.variables ?? [];+ const selectedPath = visConfig.zarrVariable ?? metadata.variable;+ const activeVariable = variables.find(v => v.path === selectedPath) ?? variables[0] ?? null;+ const animatedDimensions = isExplicitZarrAxis(visConfig.zarrAxis)+ ? getZarrAxisDimensions(visConfig.zarrAxis)+ : [activeVariable?.timeDimension?.name];+ const pinnableDims = (activeVariable?.nonSpatialDims ?? []).filter(+ dim => !animatedDimensions.includes(dim.name)+ );+ const dimensionIndexes = visConfig.dimensionIndexes ?? {};++ return (+ <StyledLayerVisualConfigurator>+ {variables.length > 1 ? (+ <LayerConfigGroup label={'layer.variable'}>+ <ItemSelector+ className="zarr-variable-selector"+ selectedItems={activeVariable}+ options={variables}+ displayOption="displayName"+ getOptionValue="path"+ multiSelect={false}+ searchable={variables.length > 10}+ onChange={value => {+ if (typeof value !== 'string') {+ return;+ }+ visConfiguratorProps.onChange({zarrVariable: value, zarrFrame: 0});+ }}+ />+ </LayerConfigGroup>+ ) : null}+ <LayerConfigGroup label={'layer.color'} collapsible>+ <LayerColorRangeSelector {...visConfiguratorProps} />+ <ConfigGroupCollapsibleContent>+ <VisConfigSlider+ {...layer.visConfigSettings.rescale}+ {...visConfiguratorProps}+ layer={{+ ...layer,+ config: {+ ...layer.config,+ visConfig: {+ ...visConfig,+ rescale: visConfig.rescale ?? layer.visConfigSettings.rescale.range+ }+ }+ }}+ />+ </ConfigGroupCollapsibleContent>+ </LayerConfigGroup>+ <LayerConfigGroup label={'layer.appearance'}>+ <VisConfigSlider {...layer.visConfigSettings.opacity} {...visConfiguratorProps} />+ </LayerConfigGroup>+ <LayerConfigGroup label={'layerVisConfigs.zarrAxis'}>+ <ZarrAxisSelector+ variable={activeVariable}+ config={visConfig.zarrAxis}+ pins={dimensionIndexes}+ onChange={visConfiguratorProps.onChange}+ />+ </LayerConfigGroup>+ {pinnableDims.length ? (+ <LayerConfigGroup label={'layer.dimensions'} collapsible>+ {pinnableDims.map(dim => {+ const options = Array.from({length: dim.size}, (_, index) => ({+ index,+ label: formatZarrCoordinate(dim, index)+ }));+ const selectedIndex = Math.min(dimensionIndexes[dim.name] ?? 0, dim.size - 1);+ return (+ <div key={dim.name}>+ <PanelLabel>{dim.name}</PanelLabel>+ <ItemSelector+ className="zarr-dimension-selector"+ selectedItems={options[selectedIndex] ?? null}+ options={options}+ displayOption="label"+ getOptionValue="index"+ multiSelect={false}+ searchable={dim.size > 10}+ onChange={index =>+ visConfiguratorProps.onChange({+ dimensionIndexes: {...dimensionIndexes, [dim.name]: index},+ zarrFrame: 0+ })+ }+ />+ </div>+ );+ })}+ </LayerConfigGroup>+ ) : null}+ </StyledLayerVisualConfigurator>+ );+ }+_renderFlowFieldLayerConfig({layer, visConfiguratorProps, layerConfiguratorProps}) {const colorBySpeed = Boolean(layer.config.visConfig.colorBySpeed);return (diff --git a/src/components/src/side-panel/layer-panel/zarr-axis-selector.spec.tsx b/src/components/src/side-panel/layer-panel/zarr-axis-selector.spec.tsxnew file mode 100644index 000000000..0d5a992b7--- /dev/null+++ b/src/components/src/side-panel/layer-panel/zarr-axis-selector.spec.tsx@@ -0,0 +1,143 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++// @ts-nocheck+import React, {useState} from 'react';+import {fireEvent, screen, within} from '@testing-library/react';+import {IntlWrapper, renderWithTheme} from 'test/helpers/component-jest-utils';+import ZarrAxisSelector from './zarr-axis-selector';++const variable = {+ nonSpatialDims: [+ {name: 'band', size: 2, values: ['tavg', 'prec'], kind: 'category'},+ {name: 'year', size: 2, values: [2023, 2024]},+ {name: 'month', size: 2, values: [1, 2]},+ {name: 'day', size: 2, values: [28, 29]}+ ]+};++beforeAll(() => {+ window.IntersectionObserver = class {+ observe() {+ return undefined;+ }+ unobserve() {+ return undefined;+ }+ disconnect() {+ return undefined;+ }+ };+});++const renderSelector = component => renderWithTheme(<IntlWrapper>{component}</IntlWrapper>);++function openSelector(name) {+ const trigger = within(screen.getByRole('group', {name})).getByRole('button');+ fireEvent.keyDown(trigger, {key: 'Enter', keyCode: 13});+ expect(trigger).toHaveAttribute('aria-expanded', 'true');+ return trigger;+}++function selectOption(name, label) {+ const trigger = openSelector(name);+ fireEvent.click(within(document.querySelector('.list-selector')).getByText(label));+ expect(trigger).toHaveAttribute('aria-expanded', 'false');+}++describe('ZarrAxisSelector', () => {+ it('selects categorical/numeric axes and automatic/off modes, resetting the frame', () => {+ const onChange = jest.fn();+ function Editor() {+ const [config, setConfig] = useState({});+ return (+ <ZarrAxisSelector+ variable={variable}+ config={config}+ onChange={value => {+ onChange(value);+ setConfig(value.zarrAxis);+ }}+ />+ );+ }+ renderSelector(<Editor />);+ const select = label => selectOption('Timeline axis', label);+ for (const dimension of ['band', 'year', 'month', 'day']) {+ select(dimension);+ expect(onChange).toHaveBeenLastCalledWith({+ zarrAxis: {kind: 'dimension', dimension},+ zarrFrame: 0+ });+ }+ for (const kind of ['off', 'auto']) {+ select(kind === 'off' ? 'Off' : 'Automatic time');+ expect(onChange).toHaveBeenLastCalledWith({zarrAxis: {kind}, zarrFrame: 0});+ }+ });++ it('omits calendar composition controls and allows choosing an individual dimension', () => {+ const onChange = jest.fn();+ renderSelector(<ZarrAxisSelector variable={variable} onChange={onChange} />);+ for (const name of ['year dimension', 'month dimension', 'day dimension', 'Calendar']) {+ expect(screen.queryByRole('group', {name})).toBeNull();+ }+ expect(onChange).not.toHaveBeenCalled();+ const trigger = openSelector('Timeline axis');+ const list = within(document.querySelector('.list-selector'));+ expect(list.queryByText('Combined calendar date')).toBeNull();+ fireEvent.click(list.getByText('month'));+ expect(trigger).toHaveAttribute('aria-expanded', 'false');+ expect(onChange).toHaveBeenCalledWith({+ zarrAxis: {kind: 'dimension', dimension: 'month'},+ zarrFrame: 0+ });+ });++ it('offers forecast valid time and restores it regardless of saved property order', () => {+ const forecast = {+ nonSpatialDims: [+ {+ name: 'init_time',+ size: 1,+ values: [0],+ kind: 'time',+ standardName: 'forecast_reference_time'+ },+ {+ name: 'lead_time',+ size: 2,+ values: [0, 3600],+ kind: 'duration',+ standardName: 'forecast_period',+ units: 'seconds'+ }+ ]+ };+ const config = {leadTime: 'lead_time', kind: 'forecast', referenceTime: 'init_time'};+ const onChange = jest.fn();+ renderSelector(<ZarrAxisSelector variable={forecast} config={config} onChange={onChange} />);+ expect(+ within(screen.getByRole('group', {name: 'Timeline axis'})).getByRole('button')+ ).toHaveTextContent('Valid time: init_time + lead_time');+ selectOption('Timeline axis', 'Valid time: init_time + lead_time');+ expect(onChange).toHaveBeenLastCalledWith({zarrAxis: config, zarrFrame: 0});+ });++ it('searches long dimension lists using the shared dropdown', () => {+ const onChange = jest.fn();+ const manyDimensions = {+ nonSpatialDims: Array.from({length: 20}, (_, i) => ({name: `dim_${i}`, size: 2}))+ };+ renderSelector(<ZarrAxisSelector variable={manyDimensions} onChange={onChange} />);+ openSelector('Timeline axis');+ fireEvent.change(screen.getByPlaceholderText('Search'), {target: {value: 'dim_19'}});+ const list = within(document.querySelector('.list-selector'));+ expect(list.queryByText('dim_0')).toBeNull();+ fireEvent.click(list.getByText('dim_19'));+ expect(onChange).toHaveBeenLastCalledWith({+ zarrAxis: {kind: 'dimension', dimension: 'dim_19'},+ zarrFrame: 0+ });+ });+});diff --git a/src/components/src/side-panel/layer-panel/zarr-axis-selector.tsx b/src/components/src/side-panel/layer-panel/zarr-axis-selector.tsxnew file mode 100644index 000000000..2870cc675--- /dev/null+++ b/src/components/src/side-panel/layer-panel/zarr-axis-selector.tsx@@ -0,0 +1,70 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import React, {useMemo} from 'react';+import type {ZarrAxisConfig, ZarrVariableInfo} from '@kepler.gl/constants';+import {getZarrAxis, getZarrForecastAxes} from '@kepler.gl/table';+import ItemSelector from '../../common/item-selector/item-selector';+import {SidePanelSection} from '../../common/styled-components';++export default function ZarrAxisSelector({+ variable,+ config = {},+ pins = {},+ onChange+}: {+ variable: ZarrVariableInfo | null;+ config?: ZarrAxisConfig;+ pins?: Record<string, number>;+ onChange: (config: {zarrAxis: ZarrAxisConfig; zarrFrame: number}) => void;+}) {+ const forecasts = useMemo(() => (variable ? getZarrForecastAxes(variable) : []), [variable]);+ const axis = useMemo(() => getZarrAxis(variable, config, pins), [variable, config, pins]);+ const dims = variable?.nonSpatialDims ?? [];+ const value =+ config.kind === 'dimension'+ ? `dimension:${config.dimension}`+ : config.kind === 'forecast'+ ? `forecast:${forecasts.findIndex(+ f =>+ f.kind === 'forecast' &&+ f.referenceTime === config.referenceTime &&+ f.leadTime === config.leadTime+ )}`+ : config.kind ?? 'auto';+ const update = (zarrAxis: ZarrAxisConfig) => onChange({zarrAxis, zarrFrame: 0});+ const axisOptions = [+ {value: 'auto', label: 'Automatic time'},+ {value: 'off', label: 'Off'},+ ...dims.map(d => ({value: `dimension:${d.name}`, label: d.name})),+ ...forecasts.flatMap((f, index) =>+ f.kind === 'forecast'+ ? [{value: `forecast:${index}`, label: `Valid time: ${f.referenceTime} + ${f.leadTime}`}]+ : []+ )+ ];+ return (+ <div>+ <SidePanelSection role="group" aria-label="Timeline axis">+ <ItemSelector+ options={axisOptions}+ selectedItems={axisOptions.find(option => option.value === value) ?? null}+ getOptionValue="value"+ displayOption="label"+ filterOption="label"+ multiSelect={false}+ searchable={axisOptions.length > 10}+ showArrow+ onChange={next => {+ if (typeof next !== 'string') return;+ if (next.startsWith('dimension:'))+ update({kind: 'dimension', dimension: next.slice(10)});+ else if (next.startsWith('forecast:')) update(forecasts[Number(next.slice(9))]);+ else update({kind: next as 'auto' | 'off'});+ }}+ />+ </SidePanelSection>+ {axis.error ? <div role="status">{axis.error}</div> : null}+ </div>+ );+}diff --git a/src/components/src/side-panel/map-manager.spec.tsx b/src/components/src/side-panel/map-manager.spec.tsxindex f486bab31..824c87790 100644--- a/src/components/src/side-panel/map-manager.spec.tsx+++ b/src/components/src/side-panel/map-manager.spec.tsx@@ -33,20 +33,14 @@ describe('MapManager', () => {test('shows one background color picker for a selected basemap style', () => {const {container} = renderWithTheme(<MapManager {...defaultProps} />);- expect(- container.querySelectorAll('[data-for="update-color-Background"]')- ).toHaveLength(1);+ expect(container.querySelectorAll('[data-for="update-color-Background"]')).toHaveLength(1);});test('preserves the existing No Basemap background color picker', () => {const mapStyle = {...INITIAL_MAP_STYLE, styleType: NO_MAP_ID};- const {container} = renderWithTheme(- <MapManager {...defaultProps} mapStyle={mapStyle} />- );+ const {container} = renderWithTheme(<MapManager {...defaultProps} mapStyle={mapStyle} />);- expect(- container.querySelectorAll('[data-for="update-color-Background"]')- ).toHaveLength(1);+ expect(container.querySelectorAll('[data-for="update-color-Background"]')).toHaveLength(1);});test('preserves the separate globe background color picker', () => {@@ -54,13 +48,11 @@ describe('MapManager', () => {...INITIAL_MAP_STATE,globe: {...INITIAL_MAP_STATE.globe, enabled: true}};- const {container} = renderWithTheme(- <MapManager {...defaultProps} mapState={mapState} />- );+ const {container} = renderWithTheme(<MapManager {...defaultProps} mapState={mapState} />);expect(container.querySelector('[data-for="update-color-Background"]')).toBeNull();- expect(- container.querySelectorAll('[data-for="update-color-globe-background"]')- ).toHaveLength(1);+ expect(container.querySelectorAll('[data-for="update-color-globe-background"]')).toHaveLength(+ 1+ );});});diff --git a/src/components/src/zarr-axis-animation.spec.tsx b/src/components/src/zarr-axis-animation.spec.tsxnew file mode 100644index 000000000..fbca74e9b--- /dev/null+++ b/src/components/src/zarr-axis-animation.spec.tsx@@ -0,0 +1,134 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++// @ts-nocheck+import React, {useState} from 'react';+import {act, fireEvent} from '@testing-library/react';+import {renderWithTheme} from 'test/helpers/component-jest-utils';+import {appInjector} from '@kepler.gl/components';+import ZarrAxisAnimationFactory from './zarr-axis-animation';+import BottomWidgetFactory from './bottom-widget';+import {InitialState} from 'test/helpers/mock-state';+import {KeplerGlLayers} from '@kepler.gl/layers';++const ZarrAxisAnimation = appInjector.get(ZarrAxisAnimationFactory);+const BottomWidget = appInjector.get(BottomWidgetFactory);+const variable = {+ path: 'climate',+ name: 'climate',+ nonSpatialDims: [+ {name: 'band', size: 2, values: ['tavg', 'prec'], kind: 'category'},+ {name: 'month', size: 3, values: [1, 6, 12], kind: 'number'}+ ]+};+const config = {kind: 'dimension', dimension: 'band'};+const pins = {month: 1};++describe('Zarr axis playback', () => {+ beforeEach(() => jest.useFakeTimers());+ afterEach(() => jest.useRealTimers());++ it('uses existing play/reset controls to advance source frames and displays category labels', () => {+ const onFrameChange = jest.fn();+ function Player() {+ const [frameIndex, setFrame] = useState(0);+ return (+ <ZarrAxisAnimation+ variable={variable}+ config={config}+ pins={pins}+ frameIndex={frameIndex}+ label="Climate"+ onFrameChange={index => {+ onFrameChange(index);+ setFrame(index);+ }}+ />+ );+ }+ const {container} = renderWithTheme(<Player />);+ expect(container.textContent).toContain('tavg');+ expect(container.textContent).toContain('prec');+ const buttons = container.querySelectorAll('.playback-control-button');+ fireEvent.click(buttons[0]);+ act(() => jest.advanceTimersByTime(5100));+ expect(onFrameChange).toHaveBeenLastCalledWith(1);+ act(() => jest.advanceTimersByTime(5100));+ expect(onFrameChange).toHaveBeenLastCalledWith(0);+ act(() => jest.advanceTimersByTime(5100));+ expect(onFrameChange).toHaveBeenLastCalledWith(1);+ fireEvent.click(buttons[0]);+ const count = onFrameChange.mock.calls.length;+ act(() => jest.advanceTimersByTime(6000));+ expect(onFrameChange).toHaveBeenCalledTimes(count);+ fireEvent.click(buttons[2]);+ expect(onFrameChange).toHaveBeenCalledTimes(count + 1);+ expect(onFrameChange).toHaveBeenLastCalledWith(0);+ });++ it('does not render an invalid axis', () => {+ const {container} = renderWithTheme(+ <ZarrAxisAnimation+ variable={variable}+ config={{kind: 'dimension', dimension: 'missing'}}+ pins={pins}+ frameIndex={0}+ label="Climate"+ onFrameChange={jest.fn()}+ />+ );+ expect(container.querySelector('section')).toBeNull();+ });++ it('displays a singleton coordinate without an unusable slider or play button', () => {+ const singleton = {...variable, nonSpatialDims: [{name: 'band', size: 1, values: ['tavg']}]};+ const {container} = renderWithTheme(+ <ZarrAxisAnimation+ variable={singleton}+ config={config}+ pins={pins}+ frameIndex={99}+ label="Climate"+ onFrameChange={jest.fn()}+ />+ );+ expect(container.textContent).toContain('tavg');+ expect(container.querySelector('.playback-control-button')).toBeNull();+ expect(container.querySelector('.animation-control__time-slider')).toBeNull();+ });++ it('connects independent visible layer timelines to layer state without advancing the global clock', () => {+ const createLayer = (label, zarrAxis, isVisible = true) =>+ new KeplerGlLayers.ZarrLayer({+ dataId: 'zarr',+ label,+ isVisible,+ visConfig: {zarrAxis, zarrFrame: 0}+ });+ const layers = [+ createLayer('Band', config),+ createLayer('Month', {kind: 'dimension', dimension: 'month'}),+ createLayer('Hidden', config, false),+ createLayer('Automatic', {}),+ createLayer('Disabled', {kind: 'off'})+ ];+ const visStateActions = {layerVisConfigChange: jest.fn(), setLayerAnimationTime: jest.fn()};+ const {getAllByRole, container} = renderWithTheme(+ <BottomWidget+ datasets={{zarr: {metadata: {variable: 'climate', variables: [variable]}}}}+ filters={[]}+ layers={layers}+ animationConfig={InitialState.visState.animationConfig}+ uiState={InitialState.uiState}+ containerW={900}+ sidePanelWidth={300}+ visStateActions={visStateActions}+ />+ );+ expect(getAllByRole('region')).toHaveLength(2);+ fireEvent.click(container.querySelector('.playback-control-button'));+ act(() => jest.advanceTimersByTime(5100));+ expect(visStateActions.layerVisConfigChange).toHaveBeenCalledWith(layers[0], {zarrFrame: 1});+ expect(visStateActions.setLayerAnimationTime).not.toHaveBeenCalled();+ });+});diff --git a/src/components/src/zarr-axis-animation.tsx b/src/components/src/zarr-axis-animation.tsxnew file mode 100644index 000000000..fb9664712--- /dev/null+++ b/src/components/src/zarr-axis-animation.tsx@@ -0,0 +1,90 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import React, {useEffect, useMemo, useState} from 'react';+import styled from 'styled-components';+import type {ZarrAxisConfig, ZarrVariableInfo} from '@kepler.gl/constants';+import {getZarrAxis} from '@kepler.gl/table';+import LayerAnimationControllerFactory from './layer-animation-controller';+import AnimationControlFactory from './common/animation-control/animation-control';++const Container = styled.section`+ position: relative;+ margin-top: 52px;++ .animation-control-container {+ background: ${props => props.theme.sidePanelBg};+ }+`;++export type ZarrAxisAnimationProps = {+ variable: ZarrVariableInfo;+ config: ZarrAxisConfig;+ pins: Record<string, number>;+ frameIndex: number;+ label: string;+ onFrameChange: (index: number) => void;+};++ZarrAxisAnimationFactory.deps = [LayerAnimationControllerFactory, AnimationControlFactory];++export default function ZarrAxisAnimationFactory(+ LayerAnimationController: ReturnType<typeof LayerAnimationControllerFactory>,+ AnimationControl: ReturnType<typeof AnimationControlFactory>+) {+ return function ZarrAxisAnimation({+ variable,+ config,+ pins,+ frameIndex,+ label,+ onFrameChange+ }: ZarrAxisAnimationProps) {+ const axis = useMemo(() => getZarrAxis(variable, config, pins), [variable, config, pins]);+ const [isAnimating, setAnimating] = useState(false);+ const [speed, setSpeed] = useState(1);+ useEffect(() => setAnimating(false), [axis]);+ const index = Math.max(+ 0,+ Math.min(axis.frames.length - 1, Number.isFinite(frameIndex) ? Math.round(frameIndex) : 0)+ );+ const steps = useMemo(() => axis.frames.map(f => f.value), [axis]);+ const labels = useMemo(() => new Map(axis.frames.map(f => [f.value, f.label])), [axis]);+ if (!axis.frames.length) return null;+ const animationConfig = {+ domain: [steps[0], steps[steps.length - 1]] as [number, number],+ currentTime: steps[index],+ timeSteps: steps,+ defaultTimeFormat: null,+ isAnimating,+ speed+ };+ return (+ <Container aria-label={`${label}: ${axis.label}`}>+ <LayerAnimationController+ animationConfig={animationConfig}+ setLayerAnimationTime={value => {+ const next = steps.indexOf(value);+ if (next >= 0) onFrameChange(next);+ }}+ >+ {(_playing, _start, _pause, resetAnimation, timeline, setTimelineValue) => (+ <AnimationControl+ timeline={timeline ? {...timeline, marks: steps} : undefined}+ setTimelineValue={setTimelineValue}+ isAnimating={isAnimating}+ isAnimatable={steps.length > 1}+ showTimeline={steps.length > 1}+ showControls={steps.length > 1}+ resetAnimation={resetAnimation}+ toggleAnimation={() => setAnimating(playing => !playing)}+ updateAnimationSpeed={setSpeed}+ formatTimelineValue={value => labels.get(value) ?? ''}+ displayLabel={`${label}: ${axis.label}`}+ />+ )}+ </LayerAnimationController>+ </Container>+ );+ };+}diff --git a/src/constants/src/dataset.ts b/src/constants/src/dataset.tsindex 2e123d613..572a8f385 100644--- a/src/constants/src/dataset.ts+++ b/src/constants/src/dataset.ts@@ -8,7 +8,8 @@ export enum DatasetType {RASTER_TILE = 'raster-tile',WMS_TILE = 'wms-tile',TILE_3D = 'tile-3d',- BITMAP = 'bitmap'+ BITMAP = 'bitmap',+ ZARR = 'zarr'}export const REMOTE_FILE_FORMATS = [@@ -253,6 +254,100 @@ export type WMSDatasetMetadata = {attribution?: string;};+/** A non-spatial dimension of a Zarr variable, e.g. `time`, `band`, `depth`. */+export type ZarrDimensionInfo = {+ name: string;+ size: number;+ /**+ * Coordinate values for the dimension, when the store exposes a matching+ * coordinate array. Time coordinates are decoded to epoch milliseconds.+ */+ values?: (number | string | boolean)[];+ /** Preserve coordinate semantics instead of guessing from its name or dtype. */+ kind?: 'time' | 'duration' | 'number' | 'category';+ units?: string;+ calendar?: string;+ standardName?: string;+ /** Original offsets for decoded CF time coordinates. */+ rawValues?: (number | string | boolean)[];+};++/** Empty/missing keeps the original automatic layer time axis. */+export type ZarrAxisConfig =+ | {kind?: 'auto' | 'off'}+ | {kind: 'dimension'; dimension: string}+ | {kind: 'forecast'; referenceTime: string; leadTime: string};++export type ZarrVariableInfo = {+ /** Path of the variable within the Zarr group. Empty for a root-level array. */+ path: string;+ /**+ * Node to open for rendering, when it differs from `path`. A pyramid keeps+ * its levels under a shared parent, so the renderer is handed that parent+ * while each variable keeps its own identity.+ */+ nodePath?: string;+ /** Name of the array itself, i.e. the last path segment. */+ name: string;+ /**+ * Label to show in variable pickers. Equal to `name`, qualified with enough+ * leading path segments to stay unique when sibling groups hold arrays of the+ * same name, e.g. `FUTUR/evap_total` and `HISTO/evap_total`.+ */+ displayName: string;+ /**+ * GeoZarr-convention attributes describing the spatial grid. Taken from the+ * store when it declares them, otherwise derived from CF/GDAL metadata.+ */+ geoAttrs?: Record<string, unknown>;+ /** Parsed grid and pyramid settings for this variable, independent of the active variable. */+ spatialMetadata?: Pick<+ ZarrDatasetMetadata,+ 'crs' | 'axes' | 'xAxisIndex' | 'yAxisIndex' | 'levels' | 'webMercatorPyramid'+ >;+ /** Shape of the finest resolution level. */+ shape: number[];+ /** Chunk shape of the finest resolution level. */+ chunks: number[];+ dtype: string;+ /** Non-spatial dimensions, in array order. */+ nonSpatialDims: ZarrDimensionInfo[];+ /** The non-spatial dimension recognized as time, when present. */+ timeDimension?: ZarrDimensionInfo;+ /** Value range advertised by the array attrs, used as the default rescale. */+ dataRange?: [number, number];+ /** Fill value advertised by the array attrs or zarr metadata. */+ nodataValue?: number;+};++export type ZarrDatasetMetadata = {+ /** Root URL of the Zarr store. */+ url: string;+ /** Path of the selected variable within the store. */+ variable?: string;+ crs?: {code?: string; wkt2?: string};+ /** Axis names of the selected variable, e.g. `['time', 'y', 'x']`. */+ axes: string[];+ xAxisIndex: number;+ yAxisIndex: number;+ /** Resolution levels, finest first. */+ levels: {path: string; shape: number[]; chunks: number[]}[];+ /**+ * Set when every level is reprojected to EPSG:3857 and spans the whole world,+ * which is what `ndpyramid`'s `pyramid_reproject` writes. The level to draw+ * then follows the map zoom rather than the data's own resolution.+ */+ webMercatorPyramid?: boolean;+ /** Every renderable variable in the store, for the variable picker. */+ variables: ZarrVariableInfo[];+ nonSpatialDims: ZarrDimensionInfo[];+ timeDimension?: ZarrDimensionInfo;+ dataRange?: [number, number];+ nodataValue?: number;+ label?: string;+ attribution?: string;+};+export type Tile3DProviderAttribution = {title: string;url: string;diff --git a/src/constants/src/layers.ts b/src/constants/src/layers.tsindex a31a5739b..274be3175 100644--- a/src/constants/src/layers.ts+++ b/src/constants/src/layers.ts@@ -674,7 +674,8 @@ export const LAYER_TYPES = keyMirror({rasterTile: null,wms: null,tile3d: null,- bitmap: null+ bitmap: null,+ zarr: null});export const EDITOR_AVAILABLE_LAYERS: string[] = [diff --git a/src/layers/babel.config.js b/src/layers/babel.config.jsindex 3b4d402a3..89a9b4ed8 100644--- a/src/layers/babel.config.js+++ b/src/layers/babel.config.js@@ -33,9 +33,12 @@ module.exports = function babel(api) {const isDebug = api.env('debug');// ESM build: modules:false preserves import/export so Vite/esbuild can tree-shake.- // CJS build (default / test): transforms import/export to require/module.exports.+ // CJS transforms static imports, but keeps native import() for ESM-only Zarr dependencies.const presets = [- ['@babel/preset-env', isEsm ? {modules: false} : {}],+ [+ '@babel/preset-env',+ isEsm ? {modules: false} : {exclude: ['@babel/plugin-transform-dynamic-import']}+ ],'@babel/preset-react','@babel/preset-typescript'];diff --git a/src/layers/package.json b/src/layers/package.jsonindex a159173e6..066c22f5d 100644--- a/src/layers/package.json+++ b/src/layers/package.json@@ -35,6 +35,9 @@"@deck.gl/geo-layers": "^9.3.1","@deck.gl/layers": "^9.3.1","@deck.gl/mesh-layers": "^9.3.1",+ "@developmentseed/deck.gl-zarr": "0.7.0",+ "@developmentseed/geozarr": "0.7.0",+ "@developmentseed/morecantile": "0.7.0","@flowmap.gl/data": "^9.2.0","@flowmap.gl/layers": "^9.2.0","@kepler.gl/common-utils": "3.3.0-alpha.18",@@ -88,7 +91,9 @@"reselect": "^5.0.0","s2-geometry": "^1.2.10","styled-components": "6.4.3",- "type-analyzer": "0.4.0"+ "type-analyzer": "0.4.0",+ "viewport-mercator-project": "^6.0.0",+ "zarrita": "^0.7.3"},"nyc": {"sourceMap": false,diff --git a/src/layers/src/base-layer.ts b/src/layers/src/base-layer.tsindex ef0959ab7..b8d3f5d46 100644--- a/src/layers/src/base-layer.ts+++ b/src/layers/src/base-layer.ts@@ -61,6 +61,7 @@ import {Filter,GetVisChannelScaleReturnType,LayerVisConfigSettings,+ LayerVisConfigTypes,MapState,AnimationConfig,KeplerLayer,@@ -73,7 +74,6 @@ import {FieldPair,NestedPartial,RGBColor,- ValueOf,VisualChannel,VisualChannels,VisualChannelDomain,@@ -249,7 +249,7 @@ class Layer implements KeplerLayer {id: string;meta: Record<string, any>;visConfigSettings: {- [key: string]: ValueOf<LayerVisConfigSettings>;+ [key: string]: LayerVisConfigTypes;};config: LayerBaseConfig & Partial<LayerColorConfig & LayerSizeConfig>;// TODO: define _oldDataUpdateTriggers@@ -723,7 +723,7 @@ class Layer implements KeplerLayer {*/assignConfigToLayer(configToCopy: LayerBaseConfig & Partial<LayerColorConfig & LayerSizeConfig>,- visConfigSettings: {[key: string]: ValueOf<LayerVisConfigSettings>},+ visConfigSettings: {[key: string]: LayerVisConfigTypes},datasets?: Datasets,defaultLayerProps?: FindDefaultLayerPropsReturnValue | null) {@@ -819,6 +819,8 @@ class Layer implements KeplerLayer {if (isPlainObject(currentConfig[key]) &&isPlainObject(configToCopy[key]) &&+ // Object vis settings contain runtime keys absent from their defaults.+ this.visConfigSettings[key]?.type !== 'object' &&!shallowCopy.includes(key) &&!notToCopy.includes(key)) {@@ -840,7 +842,7 @@ class Layer implements KeplerLayer {}registerVisConfig(layerVisConfigs: {- [key: string]: keyof LayerVisConfigSettings | ValueOf<LayerVisConfigSettings>;+ [key: string]: keyof LayerVisConfigSettings | LayerVisConfigTypes;}) {Object.keys(layerVisConfigs).forEach(item => {const configItem = layerVisConfigs[item];diff --git a/src/layers/src/geojson-layer/geojson-layer.spec.ts b/src/layers/src/geojson-layer/geojson-layer.spec.tsindex 7c1d2cd1c..27cd459c5 100644--- a/src/layers/src/geojson-layer/geojson-layer.spec.ts+++ b/src/layers/src/geojson-layer/geojson-layer.spec.ts@@ -228,7 +228,9 @@ describe('GeoJsonLayer default color field', () => {});test('keeps a single-feature dataset uniformly colored', async () => {- const {layer} = await initializeGeoJsonLayer([{geometry: polygon(0), properties: {score: 0.5}}]);+ const {layer} = await initializeGeoJsonLayer([+ {geometry: polygon(0), properties: {score: 0.5}}+ ]);expect(layer.config.colorField).toBeNull();expect(layer.config.strokeColorField).toBeNull();diff --git a/src/layers/src/index.ts b/src/layers/src/index.tsindex 9e6428e02..3709f0daf 100644--- a/src/layers/src/index.ts+++ b/src/layers/src/index.ts@@ -78,6 +78,20 @@ export {BitmapBoundsEditMode,BITMAP_MOVE_HANDLE_TYPE} from './bitmap-layer/bitmap-bounds-edit-mode';++import {default as ZarrLayer} from './zarr-layer/zarr-layer';+export {+ default as ZarrLayer,+ findNearestTimeIndex,+ getZarrSelection,+ getZarrMaxZoom,+ getZarrSublayerId,+ getZarrTileByteLength,+ zarrVisConfigs+} from './zarr-layer/zarr-layer';+export {default as ZarrLayerIcon} from './zarr-layer/zarr-layer-icon';+export {applyZarrColormap, estimateZarrDataRange} from './zarr-layer/zarr-colormap';+export type {ZarrColormapOptions, ZarrTileImage} from './zarr-layer/zarr-colormap';export {CATEGORICAL_COLORMAP_ID,DATA_SOURCE_COLOR_DEFAULTS,@@ -143,7 +157,8 @@ export const KeplerGlLayers = {RasterTileLayer,WMSLayer,Tile3DLayer,- BitmapOverlayLayer+ BitmapOverlayLayer,+ ZarrLayer};export type LayerClassesType = typeof LayerClasses;@@ -169,7 +184,8 @@ export const LayerClasses = {[LAYER_TYPES['rasterTile']]: RasterTileLayer,[LAYER_TYPES.wms]: WMSLayer,[LAYER_TYPES.tile3d]: Tile3DLayer,- [LAYER_TYPES.bitmap]: BitmapOverlayLayer+ [LAYER_TYPES.bitmap]: BitmapOverlayLayer,+ [LAYER_TYPES.zarr]: ZarrLayer};export * from './mapbox-utils';diff --git a/src/layers/src/zarr-layer/index.ts b/src/layers/src/zarr-layer/index.tsnew file mode 100644index 000000000..80239ba99--- /dev/null+++ b/src/layers/src/zarr-layer/index.ts@@ -0,0 +1,5 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++export {default, default as ZarrLayer, zarrVisConfigs} from './zarr-layer';+export {default as ZarrLayerIcon} from './zarr-layer-icon';diff --git a/src/layers/src/zarr-layer/zarr-colormap.spec.ts b/src/layers/src/zarr-layer/zarr-colormap.spec.tsnew file mode 100644index 000000000..0e619e794--- /dev/null+++ b/src/layers/src/zarr-layer/zarr-colormap.spec.ts@@ -0,0 +1,130 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import {applyZarrColormap, estimateZarrDataRange} from './zarr-colormap';++const BLACK_TO_WHITE = ['#000000', '#ffffff'];++function pixelAt(data: Uint8ClampedArray, index: number): number[] {+ const offset = index * 4;+ return [data[offset], data[offset + 1], data[offset + 2], data[offset + 3]];+}++describe('applyZarrColormap', () => {+ it('maps the rescale range onto the full ramp', () => {+ const {data, width, height} = applyZarrColormap([0, 0.5, 1], 3, 1, {+ rescale: [0, 1],+ colors: BLACK_TO_WHITE+ });++ expect(width).toBe(3);+ expect(height).toBe(1);+ expect(pixelAt(data, 0)).toEqual([0, 0, 0, 255]);+ expect(pixelAt(data, 1)).toEqual([128, 128, 128, 255]);+ expect(pixelAt(data, 2)).toEqual([255, 255, 255, 255]);+ });++ it('clamps values outside the rescale range', () => {+ const {data} = applyZarrColormap([-10, 10], 2, 1, {+ rescale: [0, 1],+ colors: BLACK_TO_WHITE+ });++ expect(pixelAt(data, 0)).toEqual([0, 0, 0, 255]);+ expect(pixelAt(data, 1)).toEqual([255, 255, 255, 255]);+ });++ it('renders NaN and the nodata value transparent', () => {+ const {data} = applyZarrColormap([Number.NaN, -9999, 1], 3, 1, {+ rescale: [0, 1],+ colors: BLACK_TO_WHITE,+ nodataValue: -9999+ });++ expect(pixelAt(data, 0)).toEqual([0, 0, 0, 0]);+ expect(pixelAt(data, 1)).toEqual([0, 0, 0, 0]);+ expect(pixelAt(data, 2)).toEqual([255, 255, 255, 255]);+ });++ it('puts every value at the bottom of the ramp for a degenerate range', () => {+ const {data} = applyZarrColormap([3, 3, 3], 3, 1, {+ rescale: [3, 3],+ colors: BLACK_TO_WHITE+ });++ expect(pixelAt(data, 0)).toEqual([0, 0, 0, 255]);+ expect(pixelAt(data, 2)).toEqual([0, 0, 0, 255]);+ });++ it('snaps to the containing band when interpolate is off', () => {+ const {data} = applyZarrColormap([0, 0.9], 2, 1, {+ rescale: [0, 1],+ colors: BLACK_TO_WHITE,+ interpolate: false+ });++ expect(pixelAt(data, 0)).toEqual([0, 0, 0, 255]);+ expect(pixelAt(data, 1)).toEqual([255, 255, 255, 255]);+ });++ it('leaves pixels transparent when the ramp is empty', () => {+ const {data} = applyZarrColormap([0.5], 1, 1, {rescale: [0, 1], colors: []});++ expect(pixelAt(data, 0)).toEqual([0, 0, 0, 0]);+ });++ it('leaves trailing pixels transparent when the chunk is short', () => {+ const {data} = applyZarrColormap([1], 2, 1, {rescale: [0, 1], colors: BLACK_TO_WHITE});++ expect(pixelAt(data, 0)).toEqual([255, 255, 255, 255]);+ expect(pixelAt(data, 1)).toEqual([0, 0, 0, 0]);+ });++ it('reads BigInt chunks', () => {+ const {data} = applyZarrColormap(new BigInt64Array([0n, 10n]), 2, 1, {+ rescale: [0, 10],+ colors: BLACK_TO_WHITE+ });++ expect(pixelAt(data, 0)).toEqual([0, 0, 0, 255]);+ expect(pixelAt(data, 1)).toEqual([255, 255, 255, 255]);+ });++ it.each([+ new BigInt64Array([-9999n, 4n, 8n]),+ new BigUint64Array([18446744073709551615n, 4n, 8n])+ ])('masks BigInt fill cells and excludes them from the automatic range', values => {+ const nodataValue = Number(values[0]);+ const range = estimateZarrDataRange(values, nodataValue);+ expect(range).toEqual([4, 8]);+ const {data} = applyZarrColormap(values, 3, 1, {+ rescale: range!,+ colors: BLACK_TO_WHITE,+ nodataValue+ });+ expect(pixelAt(data, 0)).toEqual([0, 0, 0, 0]);+ expect(pixelAt(data, 1)).toEqual([0, 0, 0, 255]);+ expect(pixelAt(data, 2)).toEqual([255, 255, 255, 255]);+ expect(estimateZarrDataRange(values.subarray(0, 1), nodataValue)).toBeNull();+ });+});++describe('estimateZarrDataRange', () => {+ it('returns the min and max of the finite values', () => {+ expect(estimateZarrDataRange([3, -1, 7, 2])).toEqual([-1, 7]);+ });++ it('ignores NaN and nodata', () => {+ expect(estimateZarrDataRange([Number.NaN, -9999, 4, 8], -9999)).toEqual([4, 8]);+ });++ it('returns null when nothing usable is left', () => {+ expect(estimateZarrDataRange([])).toBeNull();+ expect(estimateZarrDataRange([Number.NaN, Number.NaN])).toBeNull();+ expect(estimateZarrDataRange([-9999, -9999], -9999)).toBeNull();+ });++ it('returns null for a constant chunk so the caller can keep its own range', () => {+ expect(estimateZarrDataRange([5, 5, 5])).toBeNull();+ });+});diff --git a/src/layers/src/zarr-layer/zarr-colormap.ts b/src/layers/src/zarr-layer/zarr-colormap.tsnew file mode 100644index 000000000..8364a6764--- /dev/null+++ b/src/layers/src/zarr-layer/zarr-colormap.ts@@ -0,0 +1,136 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import {hexToRgb} from '@kepler.gl/utils';++export type ZarrColormapOptions = {+ /** Value range mapped onto the full color ramp. Values outside it are clamped. */+ rescale: [number, number];+ /** Hex colors of the ramp, coarsest first. */+ colors: string[];+ /** Value rendered transparent, in addition to NaN and the array fill value. */+ nodataValue?: number;+ /**+ * Interpolate between ramp stops instead of snapping to the nearest one.+ * Continuous data reads better interpolated; categorical data does not.+ */+ interpolate?: boolean;+};++export type ZarrTileImage = {+ width: number;+ height: number;+ /** RGBA, 4 bytes per pixel, row major from the top-left of the tile. */+ data: Uint8ClampedArray;+};++type Rgb = [number, number, number];++function toRgbRamp(colors: string[]): Rgb[] {+ const ramp: Rgb[] = [];+ for (const color of colors) {+ const rgb = hexToRgb(color);+ if (rgb) {+ ramp.push([rgb[0], rgb[1], rgb[2]]);+ }+ }+ return ramp;+}++/**+ * Map a 0-1 position onto the ramp. `interpolate` blends adjacent stops;+ * otherwise the position snaps to the containing band, which keeps discrete+ * class values from bleeding into each other.+ */+function sampleRamp(ramp: Rgb[], t: number, interpolate: boolean): Rgb {+ if (ramp.length === 1) {+ return ramp[0];+ }+ if (!interpolate) {+ const index = Math.min(ramp.length - 1, Math.floor(t * ramp.length));+ return ramp[index];+ }+ const scaled = t * (ramp.length - 1);+ const lower = Math.floor(scaled);+ const upper = Math.min(ramp.length - 1, lower + 1);+ const frac = scaled - lower;+ const from = ramp[lower];+ const to = ramp[upper];+ return [+ from[0] + (to[0] - from[0]) * frac,+ from[1] + (to[1] - from[1]) * frac,+ from[2] + (to[2] - from[2]) * frac+ ];+}++/**+ * Colorize a single-band Zarr chunk into an RGBA buffer.+ *+ * Done on the CPU rather than in a shader: a chunk is at most a few hundred+ * pixels square, and this keeps the color ramp identical to every other kepler+ * layer without maintaining a second shader pipeline.+ */+export function applyZarrColormap(+ values: ArrayLike<number | bigint>,+ width: number,+ height: number,+ options: ZarrColormapOptions+): ZarrTileImage {+ const pixelCount = width * height;+ const data = new Uint8ClampedArray(pixelCount * 4);+ const ramp = toRgbRamp(options.colors);++ if (ramp.length === 0 || pixelCount === 0) {+ return {width, height, data};+ }++ const [min, max] = options.rescale;+ const span = max - min;+ const {nodataValue, interpolate = true} = options;++ for (let i = 0; i < pixelCount; i++) {+ const raw = i < values.length ? Number(values[i]) : Number.NaN;+ if (!Number.isFinite(raw) || (nodataValue !== undefined && raw === nodataValue)) {+ continue;+ }+ // A degenerate rescale range would divide by zero; put everything at the+ // bottom of the ramp instead of producing NaN colors.+ const t = span > 0 ? Math.min(1, Math.max(0, (raw - min) / span)) : 0;+ const [r, g, b] = sampleRamp(ramp, t, interpolate);+ const offset = i * 4;+ data[offset] = r;+ data[offset + 1] = g;+ data[offset + 2] = b;+ data[offset + 3] = 255;+ }++ return {width, height, data};+}++/**+ * Fall back to a sensible rescale range when the store advertises none.+ * Scans the chunk so the first tiles are not rendered as a flat color.+ */+export function estimateZarrDataRange(+ values: ArrayLike<number | bigint>,+ nodataValue?: number+): [number, number] | null {+ let min = Number.POSITIVE_INFINITY;+ let max = Number.NEGATIVE_INFINITY;+ for (let i = 0; i < values.length; i++) {+ const raw = Number(values[i]);+ if (!Number.isFinite(raw) || (nodataValue !== undefined && raw === nodataValue)) {+ continue;+ }+ if (raw < min) {+ min = raw;+ }+ if (raw > max) {+ max = raw;+ }+ }+ if (min === Number.POSITIVE_INFINITY || min === max) {+ return null;+ }+ return [min, max];+}diff --git a/src/layers/src/zarr-layer/zarr-layer-icon.tsx b/src/layers/src/zarr-layer/zarr-layer-icon.tsxnew file mode 100644index 000000000..ca8d95b27--- /dev/null+++ b/src/layers/src/zarr-layer/zarr-layer-icon.tsx@@ -0,0 +1,32 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import React from 'react';+import {Base, BaseProps} from '../base';++/** Stacked chunk grid, evoking a chunked multi-dimensional array. */+const ZarrLayerIcon: React.FC<Partial<BaseProps>> = ({+ height = '16px',+ predefinedClassName = 'zarr-layer-icon',+ totalColor = 2,+ viewBox = '0 0 30 30',+ ...props+}) => (+ <Base+ height={height}+ predefinedClassName={predefinedClassName}+ totalColor={totalColor}+ viewBox={viewBox}+ {...props}+ >+ <path d="M14.76 2L1 9.75L15.24 17.76L29 10.02L14.76 2Z" fill="#BFC0D1" />+ <path d="M14.76 7.67L1 15.42L15.24 23.43L29 15.69L14.76 7.67Z" fill="#9DA0B9" />+ <path d="M14.76 12.24L1 19.98L15.24 28L29 20.25L14.76 12.24Z" fill="currentColor" />+ <g fill="white" fillOpacity="0.85">+ <rect x="9.6" y="18.2" width="3.4" height="2" transform="skewY(29.5)" />+ <rect x="16.4" y="14.4" width="3.4" height="2" transform="skewY(-29.5)" />+ </g>+ </Base>+);++export default ZarrLayerIcon;diff --git a/src/layers/src/zarr-layer/zarr-layer.ts b/src/layers/src/zarr-layer/zarr-layer.tsnew file mode 100644index 000000000..074682946--- /dev/null+++ b/src/layers/src/zarr-layer/zarr-layer.ts@@ -0,0 +1,756 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import type * as zarr from 'zarrita';++import {+ DatasetType,+ LAYER_TYPES,+ LAYER_VIS_CONFIGS,+ ZarrDatasetMetadata,+ ZarrAxisConfig,+ ZarrDimensionInfo,+ ZarrVariableInfo+} from '@kepler.gl/constants';+import {+ KeplerTable as KeplerDataset,+ Datasets as KeplerDatasets,+ getZarrTimeDomain,+ getZarrAxis,+ isExplicitZarrAxis,+ ZarrAxis,+ getZarrVariable,+ selectZarrVariable,+ openZarrNode+} from '@kepler.gl/table';+import {+ ColorRange,+ LayerBaseConfig,+ VisConfigColorRange,+ VisConfigInput,+ VisConfigNumber,+ VisConfigObject,+ VisConfigRange+} from '@kepler.gl/types';++import Layer from '../base-layer';+import {FindDefaultLayerPropsReturnValue} from '../layer-utils';+import ZarrLayerIcon from './zarr-layer-icon';+import {applyZarrColormap, estimateZarrDataRange} from './zarr-colormap';++import {loadZarrRuntime, ZarrRuntime} from './zarr-runtime';++export type ZarrLayerVisConfigSettings = {+ opacity: VisConfigNumber;+ colorRange: VisConfigColorRange;+ rescale: VisConfigRange;+ zarrVariable: VisConfigInput;+ dimensionIndexes: VisConfigObject;+ zarrAxis: VisConfigObject;+ zarrFrame: VisConfigNumber;+};++export type ZarrLayerVisConfig = {+ opacity: number;+ colorRange: ColorRange;+ /** Null means automatic: use advertised statistics or sample the first tile. */+ rescale: [number, number] | null;+ /** Path of the rendered variable. Null falls back to the dataset's default. */+ zarrVariable: string | null;+ /** Indices of non-spatial dimensions not currently driven by an axis. */+ dimensionIndexes: Record<string, number>;+ zarrAxis: ZarrAxisConfig;+ zarrFrame: number;+};++export type ZarrLayerConfig = LayerBaseConfig & {+ visConfig: ZarrLayerVisConfig;+};++export type ZarrLayerData = {+ metadata: ZarrDatasetMetadata | null;+ variable: ZarrVariableInfo | null;+};++/** What `getTileData` hands to `renderTile`. */+type ZarrTileData = {+ width: number;+ height: number;+ values: ArrayLike<number | bigint>;+ byteLength?: number;+};++/**+ * Bytes a decoded tile occupies, which is what deck's tile cache holds its+ * memory budget against. Zarr dtypes run from one byte per sample to eight, so+ * only the typed array's own size is accurate.+ */+export function getZarrTileByteLength(+ values: ArrayLike<number | bigint>,+ width: number,+ height: number+): number {+ const {byteLength} = values as {byteLength?: number};+ return typeof byteLength === 'number' ? byteLength : width * height * 4;+}++/** Slider bounds and rendering fallback until an automatic range is available. */+export const DEFAULT_RESCALE: [number, number] = [0, 1];++function isUsableRange(range?: [number, number] | null): range is [number, number] {+ return Boolean(+ range && Number.isFinite(range[0]) && Number.isFinite(range[1]) && range[0] < range[1]+ );+}++export const zarrVisConfigs = {+ zarrAxis: {+ type: 'object',+ defaultValue: {},+ group: '',+ property: 'zarrAxis',+ label: 'layerVisConfigs.zarrAxis'+ } as VisConfigObject,+ zarrFrame: {+ type: 'number',+ defaultValue: 0,+ group: '',+ property: 'zarrFrame',+ label: 'layerVisConfigs.zarrFrame',+ range: [0, 100000],+ step: 1+ } as VisConfigNumber,+ opacity: {+ ...LAYER_VIS_CONFIGS.opacity,+ defaultValue: 1,+ property: 'opacity'+ } as VisConfigNumber,+ colorRange: 'colorRange' as const,+ rescale: {+ type: 'number',+ defaultValue: DEFAULT_RESCALE,+ isRanged: true,+ range: DEFAULT_RESCALE,+ step: 0.01,+ label: 'layerVisConfigs.zarrRescale',+ group: 'color',+ property: 'rescale'+ } as VisConfigRange,+ zarrVariable: {+ type: 'input',+ defaultValue: null,+ label: 'layerVisConfigs.zarrVariable',+ group: '',+ property: 'zarrVariable'+ } as VisConfigInput,+ dimensionIndexes: {+ type: 'object',+ defaultValue: {},+ label: 'layerVisConfigs.zarrDimensionIndexes',+ group: '',+ property: 'dimensionIndexes'+ } as VisConfigObject+};++/** Width in CSS pixels of deck.gl's world at zoom 0. */+const DECK_WORLD_SIZE = 512;++/**+ * Deepest pyramid level worth drawing at this map zoom, or `undefined` to leave+ * the choice to the renderer.+ *+ * The renderer picks a level per tile by comparing the level's resolution in+ * projected metres against the viewport's in ground metres. Under Mercator the+ * two differ by a factor of 1/cos(latitude), so away from the equator it keeps+ * subdividing past anything the screen can resolve — at low zoom that reaches+ * the finest level across most of the map and asks for thousands of chunks.+ *+ * A web-mercator pyramid covers the whole world at every level, so the level+ * that matches the screen follows from the map zoom alone.+ */+export function getZarrMaxZoom(+ levels: {shape: number[]}[],+ mapZoom?: number | null+): number | undefined {+ if (levels.length < 2 || !Number.isFinite(mapZoom)) {+ return undefined;+ }+ // `levels` is finest first; the renderer indexes them coarsest first.+ const worldPixels = levels[levels.length - 1].shape[1];+ if (!worldPixels) {+ return undefined;+ }+ const coarsestZoom = Math.log2(worldPixels / DECK_WORLD_SIZE);+ const level = Math.round((mapZoom as number) - coarsestZoom);+ return Math.min(levels.length - 1, Math.max(0, level));+}++/** Nearest index in a sorted list of timestamps. */+export function findNearestTimeIndex(+ timeSteps: NonNullable<ZarrDimensionInfo['values']>,+ currentTime: number+): number {+ if (timeSteps.length === 0) {+ return 0;+ }+ let nearest = 0;+ let smallestDelta = Number.POSITIVE_INFINITY;+ for (let i = 0; i < timeSteps.length; i++) {+ const value = timeSteps[i];+ if (typeof value !== 'number') continue;+ const delta = Math.abs(value - currentTime);+ if (delta < smallestDelta) {+ smallestDelta = delta;+ nearest = i;+ }+ }+ return nearest;+}++/**+ * Build the `selection` prop for `ZarrLayer`, which requires exactly one entry+ * per non-spatial dimension. Explicit frames override their component pins;+ * automatic mode follows the shared time clock. Other pins default to index 0.+ */+export function getZarrSelection({+ variable,+ dimensionIndexes,+ currentTime,+ axis,+ frameIndex = 0+}: {+ variable: ZarrVariableInfo | null;+ dimensionIndexes?: Record<string, number>;+ currentTime?: number | null;+ axis?: ZarrAxis;+ frameIndex?: number;+}): Record<string, number> {+ const selection: Record<string, number> = {};+ if (!variable) {+ return selection;+ }+ for (const dimension of variable.nonSpatialDims) {+ const isTime = !axis && variable.timeDimension?.name === dimension.name;+ if (isTime && Number.isFinite(currentTime)) {+ const timeSteps = dimension.values ?? [];+ selection[dimension.name] = clampIndex(+ findNearestTimeIndex(timeSteps, currentTime as number),+ dimension+ );+ continue;+ }+ selection[dimension.name] = clampIndex(dimensionIndexes?.[dimension.name] ?? 0, dimension);+ }+ const frame =+ axis?.frames[+ Math.max(+ 0,+ Math.min(axis.frames.length - 1, Number.isFinite(frameIndex) ? Math.round(frameIndex) : 0)+ )+ ];+ return {...selection, ...frame?.selection};+}++/**+ * Id for the deck sublayer, keyed on the selection.+ *+ * deck.gl's `TileLayer` caches tile data by tile index and only refetches when+ * its own `getTileData` update trigger changes, which `RasterTileLayer` does not+ * forward — it forwards `renderTile`, and that only recolors data already in the+ * cache. So there is no way to invalidate fetched chunks in place. Changing the+ * id makes deck replace the layer instead, which is what lets a dimension or+ * time change actually load the new slice.+ */+export function getZarrSublayerId(layerId: string, selection: Record<string, number>): string {+ const key = getZarrSelectionKey(selection);+ return key ? `${layerId}-ZarrLayer-${key}` : `${layerId}-ZarrLayer`;+}++/** Order-independent key for a selection. */+function getZarrSelectionKey(selection: Record<string, number>): string {+ return Object.keys(selection)+ .sort()+ .map(name => `${name}=${selection[name]}`)+ .join(',');+}++function clampIndex(index: number, dimension: ZarrDimensionInfo): number {+ if (!Number.isFinite(index)) {+ return 0;+ }+ return Math.min(Math.max(0, Math.round(index)), Math.max(0, dimension.size - 1));+}++export default class ZarrLayer extends Layer {+ declare config: ZarrLayerConfig;+ declare visConfigSettings: ZarrLayerVisConfigSettings;++ /** Key of the currently opened store node, so it is opened once per source. */+ private _nodeKey: string | null = null;+ private _node: zarr.Array<zarr.DataType> | zarr.Group<zarr.Readable> | null = null;+ private _nodeError: Error | null = null;+ private _runtime: ZarrRuntime | null = null;++ private async _loadRuntime(): Promise<ZarrRuntime> {+ this._runtime = await loadZarrRuntime();+ return this._runtime;+ }++ /**+ * Rescale fallback derived from the first tile, used when the store does not+ * advertise a value range. Without it the first tiles render as flat color.+ */+ private _sampledRange: [number, number] | null = null;++ /**+ * Inputs the tile callbacks need, held on the instance instead of captured in+ * closures. See `_tileCallbackContext` for why the callbacks have to keep a+ * stable identity.+ */+ private _tileContext: {+ colors: string[];+ rescale?: [number, number] | null;+ nodataValue?: number;+ needsSampling: boolean;+ } = {colors: [], needsSampling: false};++ /** Last selection object handed to deck, reused while the contents match. */+ private _selection: Record<string, number> = {};+ private _selectionKey = '';+ private _axisCache?: {variable: ZarrVariableInfo | null; key: string; axis: ZarrAxis};++ private _getAxis(variable: ZarrVariableInfo | null): ZarrAxis | undefined {+ const {zarrAxis, dimensionIndexes} = this.config.visConfig;+ if (!isExplicitZarrAxis(zarrAxis)) return undefined;+ const key = JSON.stringify([zarrAxis, dimensionIndexes]);+ if (this._axisCache?.variable !== variable || this._axisCache?.key !== key) {+ this._axisCache = {variable, key, axis: getZarrAxis(variable, zarrAxis, dimensionIndexes)};+ }+ return this._axisCache?.axis;+ }++ /**+ * Last selection whose tiles finished loading, and the selection currently on+ * screen. While they differ, both are drawn: see `_renderDeckLayer`.+ */+ private _loadedSelection: Record<string, number> | null = null;+ private _loadedKey: string | null = null;+ private _onRedrawNeeded: (() => void) | undefined;++ constructor(props: {dataId: string; visConfig?: Record<string, any>} & Record<string, any>) {+ super(props);+ this.registerVisConfig(zarrVisConfigs);+ // Keep automatic selection distinct from every explicit range, including+ // [0, 1], in saved configs and duplicated layers.+ this.config.visConfig.rescale = null;+ // `registerVisConfig` resets every entry to its default, so anything the+ // layer was constructed with — the range from `findDefaultLayerProps`, or a+ // saved map's config — has to be put back afterwards.+ if (props.visConfig) {+ this.updateLayerVisConfig(props.visConfig);+ }+ this.meta = {};+ }++ get type(): string {+ return LAYER_TYPES.zarr;+ }++ get name(): string {+ return 'Zarr';+ }++ get requireData(): boolean {+ return false;+ }++ get requiredLayerColumns(): string[] {+ return [];+ }++ get layerIcon(): typeof ZarrLayerIcon {+ return ZarrLayerIcon;+ }++ get supportedDatasetTypes(): DatasetType[] {+ return [DatasetType.ZARR];+ }++ get visualChannels() {+ return {};+ }++ static findDefaultLayerProps(dataset: KeplerDataset): FindDefaultLayerPropsReturnValue {+ if (dataset.type !== DatasetType.ZARR) {+ return {props: []};+ }+ const metadata = (dataset.metadata || {}) as ZarrDatasetMetadata;+ const variable = getZarrVariable(metadata);+ const visConfig: Record<string, any> = {};+ const dataRange = variable?.dataRange ?? metadata.dataRange;+ if (dataRange) {+ visConfig.rescale = dataRange;+ }++ return {+ props: [+ {+ label: metadata.label || dataset.label || variable?.name || 'Zarr',+ isVisible: true,+ visConfig+ }+ ]+ };+ }++ shouldRenderLayer(): boolean {+ return Boolean(this.type && this.config.isVisible);+ }++ getHoverData(): null {+ return null;+ }++ /**+ * The variable is a layer choice rather than a dataset property, so two+ * layers can render two variables from the same store.+ */+ private _resolveVariable(metadata?: ZarrDatasetMetadata | null): ZarrVariableInfo | null {+ if (!metadata) {+ return null;+ }+ return getZarrVariable(metadata, this.config.visConfig?.zarrVariable ?? undefined) ?? null;+ }++ getDataUpdateTriggers(dataset: KeplerDataset): any {+ return {+ ...super.getDataUpdateTriggers(dataset),+ // Switching the variable changes the time coordinate, so the meta has to+ // be recomputed even though the dataset itself did not change.+ getMeta: {+ datasetId: dataset.id,+ metadata: dataset.metadata,+ zarrVariable: this.config.visConfig?.zarrVariable ?? null,+ zarrAxis: this.config.visConfig?.zarrAxis+ }+ };+ }++ formatLayerData(datasets: KeplerDatasets): ZarrLayerData {+ const {dataId} = this.config;+ if (!dataId || !datasets[dataId]) {+ return {metadata: null, variable: null};+ }+ const dataset = datasets[dataId];++ // Tileset layers have no rows, so `updateData` never runs. Drive+ // `updateLayerMeta` off the meta trigger directly.+ const triggerChanged = this.getChangedTriggers(this.getDataUpdateTriggers(dataset));+ if (triggerChanged && triggerChanged.getMeta) {+ this.updateLayerMeta(dataset);+ }++ const sourceMetadata = (dataset.metadata || null) as ZarrDatasetMetadata | null;+ const variable = this._resolveVariable(sourceMetadata);+ return {+ metadata:+ sourceMetadata && variable+ ? selectZarrVariable(sourceMetadata, variable.path)+ : sourceMetadata,+ variable+ };+ }++ updateLayerMeta(dataset: KeplerDataset): void {+ if (dataset.type !== DatasetType.ZARR) {+ return;+ }+ const sourceMetadata = (dataset.metadata || {}) as ZarrDatasetMetadata;+ const variable = this._resolveVariable(sourceMetadata);+ const metadata = variable ? selectZarrVariable(sourceMetadata, variable.path) : sourceMetadata;+ const timeDomain = isExplicitZarrAxis(this.config.visConfig.zarrAxis)+ ? null+ : getZarrTimeDomain(variable?.timeDimension);++ this._syncRescaleToVariable(variable, metadata);++ // A Zarr time coordinate is a discrete list of instants, so publishing both+ // `domain` and `timeSteps` lets the shared playback bar step through slices+ // instead of scrubbing continuously.+ if (timeDomain) {+ this.updateLayerConfig({+ animation: {+ ...this.config.animation,+ enabled: true,+ domain: timeDomain.domain,+ timeSteps: timeDomain.timeSteps,+ startTime: timeDomain.domain[0]+ }+ });+ } else {+ this.updateLayerConfig({+ animation: {...this.config.animation, enabled: false, domain: null, timeSteps: null}+ });+ }++ this.updateMeta({+ zarrUrl: metadata.url,+ variable: variable?.path,+ crs: metadata.crs?.code+ });+ }++ /**+ * Point the rescale control at the variable being rendered.+ *+ * Values are in whatever unit the store uses — Kelvin, millimetres, a count —+ * so a control fixed to 0-1 can neither show the data nor be dragged onto it.+ * Both the slider bounds and the value follow the variable, except for a+ * range the user chose for this same variable.+ */+ private _syncRescaleToVariable(+ variable: ZarrVariableInfo | null,+ metadata: ZarrDatasetMetadata+ ): void {+ // Dataset-level statistics describe its default variable, not every variable.+ const advertisedRange = variable ? variable.dataRange : metadata.dataRange;+ const dataRange = isUsableRange(advertisedRange) ? advertisedRange : null;+ this.visConfigSettings.rescale = {+ ...this.visConfigSettings.rescale,+ range: dataRange ?? DEFAULT_RESCALE,+ step: dataRange ? (dataRange[1] - dataRange[0]) / 100 : 0.01+ };++ // `meta.variable` still holds the previous render's variable here.+ const variableChanged =+ this.meta.zarrUrl !== undefined &&+ (this.meta.zarrUrl !== metadata.url || this.meta.variable !== variable?.path);+ if (variableChanged) {+ this._sampledRange = null;+ }++ const current = this.config.visConfig?.rescale;+ const unset = !isUsableRange(current);+ if (variableChanged || unset) {+ this.updateLayerVisConfig({rescale: dataRange});+ }+ }++ /**+ * Opening a Zarr store is async but `renderLayer` is not, so the node is+ * opened once per source and the map is asked to redraw when it lands.+ */+ private _getNode(+ metadata: ZarrDatasetMetadata,+ variable: ZarrVariableInfo | null,+ onReady?: () => void+ ): zarr.Array<zarr.DataType> | zarr.Group<zarr.Readable> | null {+ // Keyed on the variable rather than the node, because a pyramid's variables+ // share one node and each still needs its own sampled range.+ const key = `${metadata.url}#${variable?.path ?? ''}`;+ if (this._nodeKey === key) {+ return this._node;+ }+ this._nodeKey = key;+ this._node = null;+ this._nodeError = null;+ this._sampledRange = null;+ this._getTileData = this._createTileDataLoader();+ // Another variable's tiles are not a usable backdrop for this one.+ this._loadedKey = null;+ this._loadedSelection = null;++ Promise.all([+ openZarrNode(metadata.url, variable?.nodePath ?? variable?.path),+ this._loadRuntime()+ ])+ .then(([node]) => {+ if (this._nodeKey !== key) {+ return;+ }+ this._node = node;+ onReady?.();+ })+ .catch((error: unknown) => {+ if (this._nodeKey !== key) {+ return;+ }+ this._nodeError = error instanceof Error ? error : new Error(String(error));+ // eslint-disable-next-line no-console+ console.warn(`Failed to open Zarr store ${metadata.url}:`, this._nodeError);+ onReady?.();+ });++ return null;+ }++ renderLayer(opts: any) {+ const {data, mapState, layerCallbacks, animationConfig} = opts;+ const metadata = data?.metadata as ZarrDatasetMetadata | null;+ const variable = (data?.variable as ZarrVariableInfo | null) ?? null;+ if (!metadata?.url) {+ return [];+ }++ // ZarrLayer reprojects each chunk into Web Mercator on the CPU, which the+ // globe view's draping pipeline does not support.+ if (mapState?.globe?.enabled) {+ return [];+ }++ const node = this._getNode(metadata, variable, layerCallbacks?.onRedrawNeeded);+ if (!node || !this._runtime) {+ return [];+ }++ const {visConfig} = this.config;+ const selection = getZarrSelection({+ variable,+ dimensionIndexes: visConfig.dimensionIndexes,+ currentTime: this.config.animation?.enabled ? animationConfig?.currentTime : null,+ axis: this._getAxis(variable),+ frameIndex: visConfig.zarrFrame+ });++ const nodataValue = variable?.nodataValue ?? metadata.nodataValue;+ const colors = visConfig.colorRange?.colors ?? [];+ const rescale = visConfig.rescale;+ const defaultLayerProps = this.getDefaultDeckLayerProps(opts);++ this._tileContext = {+ colors,+ rescale,+ nodataValue,+ // Nothing has picked a range, so the first tile has to supply one.+ needsSampling: !isUsableRange(rescale)+ };+ const effectiveRescale = this._effectiveRescale(rescale);++ this._onRedrawNeeded = layerCallbacks?.onRedrawNeeded;+ const common = {+ node,+ // Stores that do not declare the GeoZarr conventions get attributes+ // derived at metadata time; passing them keeps the renderer agnostic.+ metadata: variable?.geoAttrs,+ opacity: visConfig.opacity,+ visible: defaultLayerProps.visible,+ parameters: defaultLayerProps.parameters,+ ...(metadata.webMercatorPyramid && {+ maxZoom: getZarrMaxZoom(metadata.levels, mapState?.zoom)+ }),+ // Colormap changes only need the cached tiles recolored. The selection+ // is not listed here because it is handled by the id instead.+ updateTriggers: {+ renderTile: [colors.join(','), effectiveRescale[0], effectiveRescale[1], nodataValue]+ }+ };++ const selectionKey = getZarrSelectionKey(selection);+ // A new slice means a new deck layer with an empty tile cache, so the map+ // would blink to nothing until the first tiles arrive. Keep the last loaded+ // slice underneath until the new one has something to show.+ const backdrop =+ this._loadedSelection && this._loadedKey !== selectionKey+ ? this._renderDeckLayer(this._runtime, common, this._loadedSelection)+ : null;++ const current = this._stableSelection(selection);+ const top = this._renderDeckLayer(this._runtime, common, current, () => {+ // Only the top layer retires the backdrop, and only once it is the one+ // holding tiles. `onViewportLoad` is ignored by deck's prop comparison,+ // so a fresh closure per render costs nothing.+ if (this._loadedKey === selectionKey) {+ return;+ }+ this._loadedKey = selectionKey;+ this._loadedSelection = current;+ this._onRedrawNeeded?.();+ });++ return backdrop ? [backdrop, top] : [top];+ }++ private _renderDeckLayer(+ {DeckZarrLayer}: ZarrRuntime,+ common: Record<string, any>,+ selection: Record<string, number>,+ onViewportLoad?: () => void+ ) {+ return new DeckZarrLayer({+ ...common,+ id: getZarrSublayerId(this.id, selection),+ selection,+ pickable: false,+ getTileData: this._getTileData,+ renderTile: this._renderTile,+ ...(onViewportLoad && {onViewportLoad})+ });+ }++ /**+ * deck.gl compares undeclared props by reference, and `RasterTileLayer` builds+ * its inner `TileLayer` from scratch whenever the props change, which drops+ * every tile's rendered sublayer and re-runs the CPU colormap. kepler rebuilds+ * its deck layers on every pan frame, so a fresh `selection` object or tile+ * callback would recolor every visible tile each frame.+ */+ private _stableSelection(selection: Record<string, number>): Record<string, number> {+ const key = getZarrSelectionKey(selection);+ if (key !== this._selectionKey) {+ this._selectionKey = key;+ this._selection = selection;+ }+ return this._selection;+ }++ private _createTileDataLoader() {+ const getTileData = async (+ arr: zarr.Array<zarr.DataType, zarr.Readable>,+ {sliceSpec, width, height}: {sliceSpec: unknown; width: number; height: number}+ ): Promise<ZarrTileData> => {+ const {nodataValue, needsSampling} = this._tileContext;+ const {get} = await this._loadRuntime();+ const chunk = await get(arr, sliceSpec as any);+ const values = (chunk as {data: ArrayLike<number | bigint>}).data;+ // A callback belongs to one source opening. Even after switching A -> B+ // -> A, an older request must not set the current source's color range.+ if (this._getTileData === getTileData && !this._sampledRange && needsSampling) {+ this._sampledRange = estimateZarrDataRange(values, nodataValue);+ if (this._sampledRange) {+ // Earlier constant tiles may already be colored with the provisional+ // range. Invalidate their rendered colors without refetching data.+ this._onRedrawNeeded?.();+ }+ }+ return {width, height, values, byteLength: getZarrTileByteLength(values, width, height)};+ };+ return getTileData;+ }++ private _getTileData = this._createTileDataLoader();++ private _renderTile = (tile: ZarrTileData) => {+ if (!tile) {+ // A failed tile load still has to produce a texture source.+ return {image: new ImageData(1, 1)};+ }+ const {colors, rescale, nodataValue} = this._tileContext;+ const image = applyZarrColormap(tile.values, tile.width, tile.height, {+ rescale: this._effectiveRescale(rescale),+ colors,+ nodataValue+ });+ return {image: new ImageData(image.data, image.width, image.height)};+ };++ /** Prefer the chosen rescale, falling back to what the first tile showed. */+ private _effectiveRescale(rescale?: [number, number] | null): [number, number] {+ if (this._tileContext.needsSampling && this._sampledRange) {+ return this._sampledRange;+ }+ if (isUsableRange(rescale)) {+ return rescale;+ }+ return this._sampledRange ?? DEFAULT_RESCALE;+ }+}diff --git a/src/layers/src/zarr-layer/zarr-runtime.ts b/src/layers/src/zarr-layer/zarr-runtime.tsnew file mode 100644index 000000000..722c0ae6f--- /dev/null+++ b/src/layers/src/zarr-layer/zarr-runtime.ts@@ -0,0 +1,21 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++export type ZarrRuntime = {+ DeckZarrLayer: typeof import('@developmentseed/deck.gl-zarr')['ZarrLayer'];+ get: typeof import('zarrita')['get'];+};++let runtimePromise: Promise<ZarrRuntime> | undefined;++export function loadZarrRuntime(): Promise<ZarrRuntime> {+ return (runtimePromise ??= Promise.all([+ import('@developmentseed/deck.gl-zarr'),+ import('zarrita')+ ])+ .then(([{ZarrLayer: DeckZarrLayer}, {get}]) => ({DeckZarrLayer, get}))+ .catch(error => {+ runtimePromise = undefined;+ throw error;+ }));+}diff --git a/src/localization/src/translations/en.ts b/src/localization/src/translations/en.tsindex 214f96dfe..6e368c39b 100644--- a/src/localization/src/translations/en.ts+++ b/src/localization/src/translations/en.ts@@ -130,6 +130,8 @@ export default {'3D tiles failed to load. The access token may be missing, invalid, or expired. Enter a new access token below.',tile3dLoadError: '3D tiles failed to load. Check the tileset URL and try again.',bounds: 'Bounds',+ variable: 'Variable',+ dimensions: 'Dimensions',imageSource: 'Image Source',alignment: 'Alignment',uniqueIdField: 'Unique ID Field',@@ -159,7 +161,8 @@ export default {rastertile: 'raster tile',wms: 'WMS',tile3d: '3D tile',- bitmap: 'bitmap'+ bitmap: 'bitmap',+ zarr: 'Zarr'},wms: {hover: 'Value:'@@ -199,6 +202,11 @@ export default {coverage: 'Coverage',outline: 'Outline',colorRange: 'Color range',+ zarrRescale: 'Value range',+ zarrVariable: 'Variable',+ zarrAxis: 'Timeline axis',+ zarrFrame: 'Timeline frame',+ zarrDimensionIndexes: 'Dimensions',stroke: 'Stroke',strokeColor: 'Stroke Color',strokeColorRange: 'Stroke Color range',@@ -552,6 +560,7 @@ export default {wmsTile: 'WMS tile',tile3d: '3D tile',bitmap: 'Bitmap image',+ zarr: 'Zarr',remoteFile: '{rowCount} rows (remote)',refreshInterval: 'Refresh',refreshCustomSeconds: 'Seconds',diff --git a/src/processors/src/export/geoparquet-writer.ts b/src/processors/src/export/geoparquet-writer.tsindex 562db0aa6..dc8fedcdd 100644--- a/src/processors/src/export/geoparquet-writer.ts+++ b/src/processors/src/export/geoparquet-writer.ts@@ -74,8 +74,8 @@ function int64Vector(values: unknown[]): arrow.Vector | null {typeof value === 'bigint'? value: typeof value === 'number' && Number.isSafeInteger(value)- ? BigInt(value)- : null;+ ? BigInt(value)+ : null;if (integer === null || integer < MIN_INT64 || integer > MAX_INT64) {return null;}diff --git a/src/processors/src/export/vector-export.spec.ts b/src/processors/src/export/vector-export.spec.tsindex dd690caae..ae55a7681 100644--- a/src/processors/src/export/vector-export.spec.ts+++ b/src/processors/src/export/vector-export.spec.ts@@ -147,10 +147,7 @@ describe('dataset export', () => {])('writes $dimension GeoPackage points with matching Z metadata',async ({altitudes, expectedZ, expectedCoordinates}) => {- const altitudeFields = [- ...fields,- {name: 'altitude', type: ALL_FIELD_TYPES.real}- ] as Field[];+ const altitudeFields = [...fields, {name: 'altitude', type: ALL_FIELD_TYPES.real}] as Field[];const altitudeFieldPairs = [{defaultName: 'point',diff --git a/src/reducers/src/vis-state-updaters.ts b/src/reducers/src/vis-state-updaters.tsindex 864cc8dc0..8cb0be399 100644--- a/src/reducers/src/vis-state-updaters.ts+++ b/src/reducers/src/vis-state-updaters.ts@@ -1399,7 +1399,10 @@ export function layerVisConfigChangeUpdater(if (newLayer.shouldCalculateLayerData(props)) {const oldLayerData = nextState.layerData[idx];const {layerData, layer} = calculateLayerData(newLayer, nextState, oldLayerData);- return updateStateWithLayerAndData(nextState, {layerData, layer, idx});+ const updatedState = updateStateWithLayerAndData(nextState, {layerData, layer, idx});+ return newLayer.type === 'zarr' && props.some(p => p === 'zarrAxis' || p === 'zarrVariable')+ ? updateAnimationDomain(updatedState)+ : updatedState;}return updateStateWithLayerAndData(nextState, {layer: newLayer, idx});@@ -1481,11 +1484,7 @@ export function setFilterAnimationWindowUpdater<S extends VisState>(const filterIndex = state.filters.indexOf(filter);return setFilterUpdater(state,- setFilter(- filterIndex,- ['animationWindow', 'value'],- [animationWindow, nextFilter.value]- )+ setFilter(filterIndex, ['animationWindow', 'value'], [animationWindow, nextFilter.value]));}diff --git a/src/schemas/src/dataset-schema.ts b/src/schemas/src/dataset-schema.tsindex 595c09f44..829c568c9 100644--- a/src/schemas/src/dataset-schema.ts+++ b/src/schemas/src/dataset-schema.ts@@ -169,6 +169,17 @@ export class DatasetSchema extends Schema {key = 'dataset';save(dataset: KeplerTable): SavedDatasetV1['data'] {+ if (dataset.type === DatasetType.ZARR && dataset.metadata?.url) {+ // Rebuild variable grids and coordinate lists from the store on load,+ // using the same remote metadata refresh as other tiled datasets.+ return this.savePropertiesOrApplySchema({+ ...dataset,+ allData: [],+ fields: [],+ metadata: pick(dataset.metadata, ['url', 'variable', 'label', 'attribution'])+ })[this.key];+ }+if (dataset.type === DatasetType.EXTERNALLY_HOSTED && dataset.metadata?.source) {// Keep the remote URL instead of inlining rows so shared map configs stay small.const sourceFormat = getRemoteSourceFormat(dataset.metadata);diff --git a/src/sqlrooms/src/components/CustomLayerManager.tsx b/src/sqlrooms/src/components/CustomLayerManager.tsxindex d9344def1..83e97b899 100644--- a/src/sqlrooms/src/components/CustomLayerManager.tsx+++ b/src/sqlrooms/src/components/CustomLayerManager.tsx@@ -201,6 +201,7 @@ export const CustomLayerManager: React.FC<CustomLayerManagerProps> = ({const enableRasterTileLayer = getApplicationConfig().enableRasterTileLayer;const enableWMSLayer = getApplicationConfig().enableWMSLayer;+ const enableZarrLayer = getApplicationConfig().enableZarrLayer;const filteredLayerClasses = useMemo(() => {let filteredClasses = keplerState?.visState.layerClasses || {};@@ -212,8 +213,12 @@ export const CustomLayerManager: React.FC<CustomLayerManagerProps> = ({const {wms: _wms, ...rest} = filteredClasses;filteredClasses = rest as LayerClassesType;}+ if (!enableZarrLayer && 'zarr' in filteredClasses) {+ const {zarr: _zarr, ...rest} = filteredClasses;+ filteredClasses = rest as LayerClassesType;+ }return filteredClasses as LayerClassesType;- }, [enableRasterTileLayer, enableWMSLayer, keplerState?.visState.layerClasses]);+ }, [enableRasterTileLayer, enableWMSLayer, enableZarrLayer, keplerState?.visState.layerClasses]);if (!keplerState || !keplerActions) {return null;diff --git a/src/sqlrooms/src/components/CustomMapManager.tsx b/src/sqlrooms/src/components/CustomMapManager.tsxindex 83b286a9a..cc022552e 100644--- a/src/sqlrooms/src/components/CustomMapManager.tsx+++ b/src/sqlrooms/src/components/CustomMapManager.tsx@@ -199,8 +199,8 @@ export const CustomMapManager: React.FC<CustomMapManagerProps> = ({mapId}) => {const editableLayers = keplerState.mapState.globe?.enabled? configuredLayerGroups.filter(({slug}) => slug !== BACKGROUND_LAYER_GROUP_SLUG): configuredLayerGroups.some(({slug}) => slug === BACKGROUND_LAYER_GROUP_SLUG)- ? configuredLayerGroups- : [...configuredLayerGroups, BACKGROUND_LAYER_GROUP];+ ? configuredLayerGroups+ : [...configuredLayerGroups, BACKGROUND_LAYER_GROUP];return (<CustomMapManagerContainer>diff --git a/src/table/babel.config.js b/src/table/babel.config.jsindex 3b4d402a3..89a9b4ed8 100644--- a/src/table/babel.config.js+++ b/src/table/babel.config.js@@ -33,9 +33,12 @@ module.exports = function babel(api) {const isDebug = api.env('debug');// ESM build: modules:false preserves import/export so Vite/esbuild can tree-shake.- // CJS build (default / test): transforms import/export to require/module.exports.+ // CJS transforms static imports, but keeps native import() for ESM-only Zarr dependencies.const presets = [- ['@babel/preset-env', isEsm ? {modules: false} : {}],+ [+ '@babel/preset-env',+ isEsm ? {modules: false} : {exclude: ['@babel/plugin-transform-dynamic-import']}+ ],'@babel/preset-react','@babel/preset-typescript'];diff --git a/src/table/package.json b/src/table/package.jsonindex a4e162e49..f4129c7cd 100644--- a/src/table/package.json+++ b/src/table/package.json@@ -28,6 +28,7 @@"dist"],"dependencies": {+ "@developmentseed/geozarr": "0.7.0","@kepler.gl/common-utils": "3.3.0-alpha.18","@kepler.gl/constants": "3.3.0-alpha.18","@kepler.gl/tasks-core": "3.3.0-alpha.18",@@ -46,7 +47,8 @@"es-toolkit": "^1.39.10","global": "^4.3.0","moment": "^2.10.6",- "type-analyzer": "0.4.0"+ "type-analyzer": "0.4.0",+ "zarrita": "^0.7.3"},"nyc": {"sourceMap": false,diff --git a/src/table/src/dataset-utils.ts b/src/table/src/dataset-utils.tsindex 0a666398e..b40d352a1 100644--- a/src/table/src/dataset-utils.ts+++ b/src/table/src/dataset-utils.ts@@ -13,7 +13,8 @@ import {PMTilesType,RemoteTileFormat,VectorTileDatasetMetadata,- WMSDatasetMetadata+ WMSDatasetMetadata,+ ZarrDatasetMetadata} from '@kepler.gl/constants';import {withPublicTitilerCorsCacheKey} from '@kepler.gl/common-utils';import {@@ -36,6 +37,7 @@ import {VectorTileMetadata} from './tileset/vector-tile-utils';import {buildWmsGetCapabilitiesUrl, wmsCapabilitiesToDatasetMetadata} from './tileset/wms-utils';+import {clearZarrStoreCache, getZarrMetadata} from './tileset/zarr-utils';// apply a color for each dataset// to use as label colors@@ -166,6 +168,8 @@ async function refreshRemoteData(datasetInfo: CreateTableProps): Promise<objectreturn await refreshRasterTileMetadata(datasetInfo);case DatasetType.WMS_TILE:return await refreshWMSMetadata(datasetInfo);+ case DatasetType.ZARR:+ return await refreshZarrMetadata(datasetInfo);case DatasetType.TILE_3D:return null;case DatasetType.BITMAP:@@ -271,6 +275,25 @@ async function refreshWMSMetadata(datasetInfo: CreateTableProps): Promise<any |return null;}+async function refreshZarrMetadata(datasetInfo: CreateTableProps): Promise<any | null> {+ const {url, variable, variables} = (datasetInfo.opts.metadata as ZarrDatasetMetadata) || {};++ if (typeof url !== 'string') {+ return null;+ }++ // Metadata built by the Add Data form is already complete; only re-read the+ // store when a saved map config carries just the URL.+ if (Array.isArray(variables) && variables.length > 0) {+ return null;+ }++ // URL-only saves have no usable metadata to fall back to. Let failures reach+ // the dataset-loading task's error handler instead of creating an empty table.+ clearZarrStoreCache(url);+ return await getZarrMetadata(url, {variable});+}+export async function getWMSCapabilities(wsmUrl: string): Promise<WMSCapabilities> {const capabilitiesUrl = buildWmsGetCapabilitiesUrl(wsmUrl) || wsmUrl;return (await load(capabilitiesUrl, WMSCapabilitiesLoader, {diff --git a/src/table/src/index.ts b/src/table/src/index.tsindex 1869a7be4..316eaede3 100644--- a/src/table/src/index.ts+++ b/src/table/src/index.ts@@ -29,4 +29,22 @@ export * from './tileset/wms-utils';export * from './tileset/tileset-utils';export * from './tileset/vector-tile-utils';export * from './tileset/raster-tile-utils';+// Named rather than `export *`: the rest of `zarr-utils` is internal, exported+// only so its tests can reach it, and should not become package API.+export {+ getZarrMetadata,+ getZarrTimeDomain,+ getZarrVariable,+ openZarrNode,+ selectZarrVariable+} from './tileset/zarr-utils';+export type {ZarrMetadataProgress} from './tileset/zarr-utils';export * from './dataset-ops';+export {+ getZarrAxis,+ getZarrAxisDimensions,+ getZarrForecastAxes,+ isExplicitZarrAxis,+ formatZarrCoordinate+} from './tileset/zarr-axis';+export type {ZarrAxis, ZarrAxisFrame} from './tileset/zarr-axis';diff --git a/src/table/src/tileset/zarr-axis.ts b/src/table/src/tileset/zarr-axis.tsnew file mode 100644index 000000000..fab7bac54--- /dev/null+++ b/src/table/src/tileset/zarr-axis.ts@@ -0,0 +1,172 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import type {ZarrAxisConfig, ZarrDimensionInfo, ZarrVariableInfo} from '@kepler.gl/constants';++export type ZarrAxisFrame = {+ /** Numeric slider position; categorical/duplicate values use ordinal positions. */+ value: number;+ label: string;+ /** Original array indices, independent of axis sorting and display labels. */+ selection: Record<string, number>;+};++export type ZarrAxis = {+ label: string;+ dimensions: string[];+ frames: ZarrAxisFrame[];+ error?: string;+};++const MAX_FRAMES = 100_000;+const DAY_MS = 86_400_000;++export function isExplicitZarrAxis(axis?: ZarrAxisConfig): boolean {+ return Boolean(axis?.kind && axis.kind !== 'auto');+}++export function getZarrAxisDimensions(axis?: ZarrAxisConfig): string[] {+ switch (axis?.kind) {+ case 'dimension':+ return [axis.dimension];+ case 'forecast':+ // The forecast run is pinned. Only the lead varies during playback.+ return [axis.leadTime];+ default:+ return [];+ }+}++export function getZarrForecastAxes(variable: ZarrVariableInfo): ZarrAxisConfig[] {+ const dims = variable.nonSpatialDims;+ const references = dims.filter(+ d => d.kind === 'time' && d.standardName === 'forecast_reference_time'+ );+ const leads = dims.filter(d => d.standardName === 'forecast_period');+ return references.flatMap(reference =>+ leads.map(lead => ({+ kind: 'forecast' as const,+ referenceTime: reference.name,+ leadTime: lead.name+ }))+ );+}++export function formatZarrCoordinate(dimension: ZarrDimensionInfo, index: number): string {+ const value = dimension.values?.[index];+ if (value === undefined || (typeof value === 'number' && !Number.isFinite(value))) {+ return String(index);+ }+ if (dimension.kind === 'time' && typeof value === 'number') {+ const date = new Date(value);+ return Number.isFinite(date.getTime()) ? date.toISOString() : String(index);+ }+ return typeof value === 'number' ? String(Number(value.toPrecision(12))) : String(value);+}++function durationMilliseconds(units?: string): number | undefined {+ return {+ seconds: 1000,+ second: 1000,+ s: 1000,+ minutes: 60_000,+ minute: 60_000,+ hours: 3_600_000,+ hour: 3_600_000,+ days: DAY_MS,+ day: DAY_MS,+ milliseconds: 1,+ millisecond: 1,+ microseconds: 0.001,+ microsecond: 0.001+ }[units?.toLowerCase() ?? ''];+}++/**+ * A small, per-variable table of playable slices. Never expands unrelated+ * dimensions (ensemble, band, scenario, etc.) or raster pixels into rows.+ */+export function getZarrAxis(+ variable: ZarrVariableInfo | null | undefined,+ config?: ZarrAxisConfig,+ pins: Record<string, number> = {}+): ZarrAxis {+ const dimensions = getZarrAxisDimensions(config);+ const empty = (error?: string): ZarrAxis => ({label: '', dimensions, frames: [], error});+ if (!variable || !isExplicitZarrAxis(config) || config?.kind === 'off') return empty();+ const source = variable.nonSpatialDims.find(d => d.name === dimensions[0]);+ if (!source) {+ return empty('Choose a dimension belonging to this variable.');+ }+ if (!Number.isSafeInteger(source.size) || source.size < 0) {+ return empty('The selected axis has an invalid dimension size.');+ }+ const size = source.size;+ if (!size) return empty('The selected axis has no values.');+ if (size > MAX_FRAMES) return empty('The selected axis has too many frames for playback.');++ let frames: ZarrAxisFrame[] = [];+ let label = dimensions.join(' / ');+ let ordinal = false;+ if (config?.kind === 'dimension') {+ const dim =+ source.name === variable.timeDimension?.name ? {...source, kind: 'time' as const} : source;+ label = dim.units && dim.kind !== 'time' ? `${dim.name} (${dim.units})` : dim.name;+ ordinal = dim.kind === 'category' || !dim.values;+ for (let index = 0; index < dim.size; index++) {+ const value = dim.values ? dim.values[index] : index;+ if (value === undefined || (typeof value === 'number' && !Number.isFinite(value))) continue;+ if (dim.kind === 'time' && !Number.isFinite(new Date(Number(value)).getTime())) continue;+ ordinal ||= typeof value !== 'number';+ frames.push({+ value: typeof value === 'number' ? value : index,+ label: formatZarrCoordinate(dim, index),+ selection: {[dim.name]: index}+ });+ }+ } else if (config?.kind === 'forecast') {+ const reference = variable.nonSpatialDims.find(d => d.name === config.referenceTime);+ const lead = source;+ const index = Math.max(+ 0,+ Math.min(+ reference ? reference.size - 1 : 0,+ Number.isFinite(pins[config.referenceTime]) ? Math.round(pins[config.referenceTime]) : 0+ )+ );+ const start = reference?.values?.[index];+ const scale = durationMilliseconds(lead.units);+ if (+ reference?.kind !== 'time' ||+ typeof start !== 'number' ||+ !scale ||+ reference.name === lead.name+ ) {+ return empty(+ 'Valid time requires a decoded reference time and a lead time with duration units.'+ );+ }+ label = `Valid time (${reference.name} + ${lead.name})`;+ for (let i = 0; i < lead.size; i++) {+ const offset = lead.values?.[i];+ const value = typeof offset === 'number' ? start + offset * scale : NaN;+ if (!Number.isFinite(value) || !Number.isFinite(new Date(value).getTime())) continue;+ frames.push({+ value,+ label: new Date(value).toISOString(),+ selection: {[reference.name]: index, [lead.name]: i}+ });+ }+ }+ if (!ordinal) frames.sort((a, b) => a.value - b.value);+ // Keep every slice even when coordinate labels/values repeat.+ if (ordinal || new Set(frames.map(f => f.value)).size !== frames.length) {+ frames = frames.map((frame, index) => ({...frame, value: index}));+ }+ return {+ label,+ dimensions,+ frames,+ ...(frames.length ? {} : {error: 'The selected axis has no usable coordinates.'})+ };+}diff --git a/src/table/src/tileset/zarr-runtime.ts b/src/table/src/tileset/zarr-runtime.tsnew file mode 100644index 000000000..c77761f0d--- /dev/null+++ b/src/table/src/tileset/zarr-runtime.ts@@ -0,0 +1,19 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++// Keep ESM-only dependencies out of the package's synchronous CommonJS entry.+let runtimePromise:+ | Promise<{+ zarr: typeof import('zarrita');+ parseGeoZarrMetadata: typeof import('@developmentseed/geozarr')['parseGeoZarrMetadata'];+ }>+ | undefined;++export function loadZarrRuntime() {+ return (runtimePromise ??= Promise.all([import('zarrita'), import('@developmentseed/geozarr')])+ .then(([zarr, {parseGeoZarrMetadata}]) => ({zarr, parseGeoZarrMetadata}))+ .catch(error => {+ runtimePromise = undefined;+ throw error;+ }));+}diff --git a/src/table/src/tileset/zarr-utils.spec.ts b/src/table/src/tileset/zarr-utils.spec.tsnew file mode 100644index 000000000..7a8490252--- /dev/null+++ b/src/table/src/tileset/zarr-utils.spec.ts@@ -0,0 +1,1188 @@+/**+ * SPDX-License-Identifier: MIT+ * Copyright contributors to the kepler.gl project+ * @jest-environment node+ */++import type {ZarrDatasetMetadata, ZarrVariableInfo} from '@kepler.gl/constants';++import {parseGeoZarrMetadata} from '@developmentseed/geozarr';+import {BoolArray, UnicodeStringArray} from 'zarrita';++import {+ ZarrMetadataProgress,+ affineFromCellCenters,+ assignVariableDisplayNames,+ buildMultiscaleAttrs,+ childPrefix,+ clearZarrStoreCache,+ decodeCfTime,+ decodeZarrCoordinate,+ isWebMercatorPyramid,+ multiscaleVariableNames,+ orderLevelsFinestFirst,+ parseOmeMultiscaleLevels,+ getZarrDimensionNames,+ getZarrMetadata,+ openZarrStore,+ getZarrTimeDomain,+ axisSpacingFromValues,+ getZarrVariable,+ parseCfTimeUnits,+ parseGdalGeoTransform,+ resolveCoordinatePath,+ selectZarrVariable+} from './zarr-utils';+import {getZarrAxis, getZarrForecastAxes, formatZarrCoordinate} from './zarr-axis';++const HOUR = 3_600_000;+const DAY = 86_400_000;++function axisVariable(nonSpatialDims: ZarrVariableInfo['nonSpatialDims']): ZarrVariableInfo {+ return {+ path: 'climate',+ name: 'climate',+ displayName: 'climate',+ dtype: 'float32',+ shape: [...nonSpatialDims.map(d => d.size), 2, 2],+ chunks: [1, 2, 2],+ nonSpatialDims+ };+}++describe('Zarr metadata', () => {+ const url = 'https://example.com/cancellable.zarr';+ const originalGlobals = {+ fetch: globalThis.fetch,+ Request: globalThis.Request,+ Headers: globalThis.Headers+ };+ const fetchMock = jest.fn();+ const array = {+ zarr_format: 2,+ shape: [2, 2, 2],+ chunks: [1, 2, 2],+ dtype: '<f8',+ compressor: null,+ fill_value: null,+ order: 'C',+ filters: null+ };+ const consolidated = {+ zarr_consolidated_format: 1,+ metadata: {+ '.zgroup': {zarr_format: 2},+ '.zattrs': {},+ 'climate/.zarray': array,+ 'climate/.zattrs': {+ _ARRAY_DIMENSIONS: ['month', 'lat', 'lon'],+ 'spatial:dimensions': ['lat', 'lon'],+ 'spatial:transform': [1, 0, 0, 0, -1, 2],+ 'spatial:shape': [2, 2],+ 'proj:code': 'EPSG:4326'+ },+ 'month/.zarray': {...array, shape: [2], chunks: [2]},+ 'month/.zattrs': {_ARRAY_DIMENSIONS: ['month']}+ }+ };++ function serve(request: Request) {+ if (request.url.endsWith('/.zmetadata')) {+ return new Response(JSON.stringify(consolidated));+ }+ if (request.url.endsWith('/month/0')) {+ return new Response(Buffer.from(new Float64Array([1, 2]).buffer));+ }+ return new Response(null, {status: 404});+ }++ function pendingUntilAbort(signal: AbortSignal) {+ return new Promise<never>((_, reject) => {+ if (signal.aborted) {+ reject(signal.reason);+ } else {+ signal.addEventListener('abort', () => reject(signal.reason), {once: true});+ }+ });+ }++ beforeAll(() => Object.assign(globalThis, {Request, Headers, fetch: fetchMock}));+ afterAll(() => Object.assign(globalThis, originalGlobals));+ beforeEach(() => {+ clearZarrStoreCache();+ fetchMock.mockReset();+ });+ afterEach(() => clearZarrStoreCache());++ it.each(['known', 'unknown', 'encoded'])(+ 'reports streamed metadata and coordinate bytes with %s response size',+ async size => {+ const bytes = new TextEncoder().encode(JSON.stringify(consolidated));+ const headers: Record<string, string> = {};+ if (size === 'known') headers['content-length'] = String(bytes.length);+ if (size === 'encoded') {+ headers['content-length'] = '500';+ headers['content-encoding'] = 'gzip';+ }+ let bodyController: ReadableStreamDefaultController<Uint8Array> | undefined;+ const body = new ReadableStream<Uint8Array>({+ start(controller) {+ bodyController = controller;+ }+ });+ fetchMock.mockImplementation((request: Request) =>+ Promise.resolve(+ request.url.endsWith('/.zmetadata') ? new Response(body, {headers}) : serve(request)+ )+ );+ let started: () => void;+ const downloading = new Promise<void>(resolve => {+ started = resolve;+ });+ let received: () => void;+ const firstChunk = new Promise<void>(resolve => {+ received = resolve;+ });+ const updates: ZarrMetadataProgress[] = [];+ let now = 1000;+ const clock = jest.spyOn(Date, 'now').mockImplementation(() => now);+ try {+ const pending = getZarrMetadata(url, {+ onProgress: progress => {+ updates.push(progress);+ if (progress.phase === 'downloading') started();+ if (progress.loadedBytes === 100) received();+ }+ });+ await downloading;+ if (!bodyController) throw new Error('Response body controller was not initialized');+ now += 250;+ bodyController.enqueue(bytes.subarray(0, 100));+ await firstChunk;+ expect(updates[updates.length - 1]).toEqual({+ phase: 'downloading',+ loadedBytes: 100,+ totalBytes: size === 'known' ? bytes.length : undefined+ });++ now += 250;+ bodyController.enqueue(bytes.subarray(100));+ bodyController.close();+ const metadata = await pending;+ expect(metadata.variable).toBe('climate');+ expect(metadata.nonSpatialDims[0].values).toEqual([1, 2]);+ expect(updates[0]).toEqual({phase: 'connecting', loadedBytes: 0});+ expect(updates[updates.length - 1]).toMatchObject({+ phase: 'processing',+ loadedBytes: bytes.length + new Float64Array([1, 2]).byteLength+ });+ } finally {+ clock.mockRestore();+ }+ }+ );++ it('cancels a stalled response body and stops reporting progress after abort', async () => {+ const cancel = jest.fn();+ const body = new ReadableStream<Uint8Array>({cancel});+ fetchMock.mockResolvedValue(new Response(body));+ let started: () => void;+ const downloading = new Promise<void>(resolve => {+ started = resolve;+ });+ const onProgress = jest.fn((progress: ZarrMetadataProgress) => {+ if (progress.phase === 'downloading') started();+ });+ const controller = new AbortController();+ const pending = getZarrMetadata(url, {signal: controller.signal, onProgress});+ const rejected = expect(pending).rejects.toMatchObject({name: 'AbortError'});+ await downloading;+ const count = onProgress.mock.calls.length;+ controller.abort();+ await rejected;+ expect(cancel).toHaveBeenCalled();+ expect(onProgress).toHaveBeenCalledTimes(count);+ });++ it.each(['v2', 'v3'])(+ 'loads %s CF variables without redundant format probes or shared coordinate downloads',+ async format => {+ const dimensions = ['month', 'lat', 'lon'];+ const arrays = {+ climate: {shape: [2, 2, 2], dimensions},+ rain: {shape: [2, 2, 2], dimensions},+ lat: {shape: [2], dimensions: ['lat']},+ lon: {shape: [2], dimensions: ['lon']},+ month: {shape: [2], dimensions: ['month']}+ };+ const v2Metadata: Record<string, unknown> = {'.zgroup': {zarr_format: 2}, '.zattrs': {}};+ const v3Metadata: Record<string, unknown> = {};+ for (const [name, entry] of Object.entries(arrays)) {+ v2Metadata[`${name}/.zarray`] = {...array, shape: entry.shape, chunks: entry.shape};+ v2Metadata[`${name}/.zattrs`] = {_ARRAY_DIMENSIONS: entry.dimensions};+ v3Metadata[name] = {+ zarr_format: 3,+ node_type: 'array',+ shape: entry.shape,+ data_type: 'float64',+ dimension_names: entry.dimensions,+ chunk_grid: {name: 'regular', configuration: {chunk_shape: entry.shape}},+ chunk_key_encoding: {name: 'default', configuration: {separator: '/'}},+ codecs: [{name: 'bytes', configuration: {endian: 'little'}}],+ fill_value: 0,+ attributes: {}+ };+ }+ fetchMock.mockImplementation(async (request: Request) => {+ const key = request.url.slice(url.length);+ if (key === '/.zmetadata') {+ return format === 'v2'+ ? Response.json({zarr_consolidated_format: 1, metadata: v2Metadata})+ : new Response(null, {status: 404});+ }+ if (format === 'v3' && key === '/zarr.json') {+ return Response.json({+ zarr_format: 3,+ node_type: 'group',+ attributes: {},+ consolidated_metadata: {kind: 'inline', must_understand: false, metadata: v3Metadata}+ });+ }+ const chunkKey = format === 'v3' ? 'c/0' : '0';+ if (['lat', 'lon', 'month'].some(name => key === `/${name}/${chunkKey}`)) {+ const values = key.startsWith('/lat/') ? [1.5, 0.5] : [0.5, 1.5];+ return new Response(new Float64Array(values).buffer);+ }+ throw new Error(`Unexpected metadata or coordinate request: ${key}`);+ });++ const metadata = await getZarrMetadata(url, {signal: new AbortController().signal});+ expect(metadata.variables.map(variable => variable.path)).toEqual(['climate', 'rain']);+ for (const variable of metadata.variables) {+ expect(variable.geoAttrs?.['spatial:transform']).toEqual([1, 0, 0, 0, -1, 2]);+ expect(variable.nonSpatialDims[0].values).toEqual([0.5, 1.5]);+ }+ const requested = fetchMock.mock.calls.map(([request]) => request.url.slice(url.length));+ const chunkKey = format === 'v3' ? 'c/0' : '0';+ expect(requested.sort()).toEqual(+ [+ '/.zmetadata',+ ...(format === 'v3' ? ['/zarr.json'] : []),+ ...['lat', 'lon', 'month'].map(name => `/${name}/${chunkKey}`)+ ].sort()+ );+ }+ );++ it('reports waiting for coordinate headers instead of processing downloaded metadata', async () => {+ const controller = new AbortController();+ let started: () => void;+ const coordinatesRequested = new Promise<void>(resolve => {+ started = resolve;+ });+ fetchMock.mockImplementation((request: Request) => {+ if (request.url.endsWith('/month/0')) {+ started();+ return pendingUntilAbort(controller.signal);+ }+ return Promise.resolve(serve(request));+ });+ const onProgress = jest.fn();+ const pending = getZarrMetadata(url, {signal: controller.signal, onProgress});+ const rejected = expect(pending).rejects.toMatchObject({name: 'AbortError'});+ await coordinatesRequested;+ expect(onProgress.mock.calls[onProgress.mock.calls.length - 1][0]).toMatchObject({+ phase: 'connecting',+ loadedBytes: new TextEncoder().encode(JSON.stringify(consolidated)).length+ });+ controller.abort();+ await rejected;+ });++ it.each([+ ['<i8', -9999, -9999],+ ['<u8', 0, 0],+ ['<u8', '18446744073709551615', Number(18446744073709551615n)],+ ['<i8', null, undefined],+ ['<f8', 'NaN', undefined]+ ])(+ 'normalizes %s fill value %s for numeric tile rendering',+ async (dtype, fillValue, expected) => {+ fetchMock.mockImplementation((request: Request) =>+ Promise.resolve(+ request.url.endsWith('/.zmetadata')+ ? new Response(+ JSON.stringify({+ ...consolidated,+ metadata: {+ ...consolidated.metadata,+ 'climate/.zarray': {...array, dtype, fill_value: fillValue}+ }+ })+ )+ : serve(request)+ )+ );+ const metadata = await getZarrMetadata(url);+ expect(metadata.nodataValue).toBe(expected);+ expect(metadata.variables[0].nodataValue).toBe(expected);+ expect(() => JSON.stringify(metadata)).not.toThrow();+ }+ );++ it('keeps spatial metadata and pyramid zoom settings with each variable', async () => {+ const contents: Record<string, unknown> = {+ ...consolidated.metadata,+ 'pyramid/.zgroup': {zarr_format: 2},+ 'pyramid/.zattrs': {+ multiscales: [+ {+ datasets: [128, 256, 512].map((_, level) => ({+ path: String(level),+ crs: 'EPSG:3857',+ pixels_per_tile: 128+ }))+ }+ ]+ }+ };+ [128, 256, 512].forEach((size, level) => {+ contents[`pyramid/${level}/.zgroup`] = {zarr_format: 2};+ contents[`pyramid/${level}/rain/.zarray`] = {+ ...array,+ shape: [size, size],+ chunks: [128, 128]+ };+ contents[`pyramid/${level}/rain/.zattrs`] = {+ _ARRAY_DIMENSIONS: ['y', 'x'],+ grid_mapping: 'spatial_ref'+ };+ contents[`pyramid/${level}/spatial_ref/.zarray`] = {+ ...array,+ shape: [],+ chunks: []+ };+ contents[`pyramid/${level}/spatial_ref/.zattrs`] = {+ epsg_code: 3857,+ GeoTransform: [-20037508, 40075016 / size, 0, 20037508, 0, -40075016 / size].join(' ')+ };+ });+ fetchMock.mockImplementation((request: Request) =>+ Promise.resolve(+ request.url.endsWith('/.zmetadata')+ ? new Response(JSON.stringify({...consolidated, metadata: contents}))+ : serve(request)+ )+ );++ const metadata = await getZarrMetadata(url, {variable: 'climate'});+ expect(metadata.variables.map(variable => variable.path)).toEqual(['climate', 'pyramid/rain']);+ expect(metadata.webMercatorPyramid).toBe(false);+ expect(metadata.crs).toEqual({code: 'EPSG:4326'});+ expect(metadata.axes).toEqual(['lat', 'lon']);+ expect(metadata.levels).toEqual([{path: '.', shape: [2, 2], chunks: [2, 2]}]);+ const requestCount = fetchMock.mock.calls.length;++ // Switching also works after a save/load, without reopening the store.+ const selected = selectZarrVariable(JSON.parse(JSON.stringify(metadata)), 'pyramid/rain');+ expect(selected.webMercatorPyramid).toBe(true);+ expect(selected.crs).toEqual({code: 'EPSG:3857'});+ expect(selected.axes).toEqual(['y', 'x']);+ expect(selected.xAxisIndex).toBe(1);+ expect(selected.yAxisIndex).toBe(0);+ expect(selected.levels).toEqual(+ [512, 256, 128].map((size, i) => ({+ path: `${2 - i}/rain`,+ shape: [size, size],+ chunks: [128, 128]+ }))+ );+ expect(selectZarrVariable(selected, 'climate')).toEqual(metadata);+ expect(fetchMock).toHaveBeenCalledTimes(requestCount);+ expect(metadata.crs).toEqual({code: 'EPSG:4326'});+ });++ it('does not start requests for an already-aborted load', async () => {+ const controller = new AbortController();+ controller.abort();+ await expect(getZarrMetadata(url, {signal: controller.signal})).rejects.toBe(+ controller.signal.reason+ );+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('does not start requests when cancelled while awaiting the runtime', async () => {+ const controller = new AbortController();+ const pending = getZarrMetadata(url, {signal: controller.signal});+ controller.abort();+ await expect(pending).rejects.toBe(controller.signal.reason);+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it.each([+ ['consolidated metadata', '/.zmetadata'],+ ['coordinate chunks', '/month/0']+ ])('aborts %s requests without returning partial metadata and permits retry', async (_, path) => {+ let started: () => void;+ const requestStarted = new Promise<void>(resolve => {+ started = resolve;+ });+ const controller = new AbortController();+ fetchMock.mockImplementation((request: Request, options?: RequestInit) => {+ if (request.url.endsWith(path)) {+ expect(options?.signal).toBe(controller.signal);+ started();+ return pendingUntilAbort(controller.signal);+ }+ return Promise.resolve(serve(request));+ });+ const pending = getZarrMetadata(url, {signal: controller.signal});+ const rejected = expect(pending).rejects.toMatchObject({name: 'AbortError'});+ await requestStarted;+ const requestCount = fetchMock.mock.calls.length;+ controller.abort();+ await rejected;+ expect(fetchMock).toHaveBeenCalledTimes(requestCount);++ fetchMock.mockImplementation((request: Request) => Promise.resolve(serve(request)));+ const retry = await getZarrMetadata(url, {signal: new AbortController().signal});+ expect(retry.variable).toBe('climate');+ expect(retry.nonSpatialDims[0].values).toEqual([1, 2]);+ });++ it('does not cancel or poison the shared layer store at the same URL', async () => {+ const controller = new AbortController();+ fetchMock.mockImplementation((request: Request, options?: RequestInit) =>+ options?.signal === controller.signal+ ? pendingUntilAbort(controller.signal)+ : Promise.resolve(serve(request))+ );+ const preview = getZarrMetadata(url, {signal: controller.signal});+ const rejected = expect(preview).rejects.toMatchObject({name: 'AbortError'});+ const layerStore = await openZarrStore(url);+ controller.abort();+ await rejected;++ expect(await openZarrStore(url)).toBe(layerStore);+ const chunk = await layerStore.get('/month/0');+ expect(chunk).toEqual(new Uint8Array(new Float64Array([1, 2]).buffer));+ const metadata = await getZarrMetadata(url);+ expect(metadata.nonSpatialDims[0].values).toEqual([1, 2]);+ });+});++describe('Zarr dimension axes', () => {+ it('decodes Zarr iterable string and boolean coordinates without coercing their labels', () => {+ const strings = decodeZarrCoordinate(+ 'band',+ 2,+ new UnicodeStringArray(4, ['tavg', 'prec']),+ {}+ );+ expect(strings.dimension.values).toEqual(['tavg', 'prec']);+ const booleans = decodeZarrCoordinate('enabled', 2, new BoolArray([true, false]), {});+ expect(+ getZarrAxis(axisVariable([booleans.dimension]), {kind: 'dimension', dimension: 'enabled'})+ .frames+ ).toEqual([+ {value: 0, label: 'true', selection: {enabled: 0}},+ {value: 1, label: 'false', selection: {enabled: 1}}+ ]);+ expect(+ decodeZarrCoordinate('member', 2, [0, 1], {standard_name: 'realization'}).dimension.kind+ ).toBe('category');+ });++ it('decodes large CF offsets while preserving exact raw offsets for saved metadata', () => {+ const offset = 10000000000000000n;+ const {dimension} = decodeZarrCoordinate('time', 1, [offset], {+ units: 'microseconds since 1970-01-01'+ });+ expect(dimension.kind).toBe('time');+ expect(dimension.values).toEqual([10000000000000]);+ expect(dimension.rawValues).toEqual([String(offset)]);+ });+ it('preserves CarbonPlan band labels and maps months to their original slices', () => {+ const band = decodeZarrCoordinate('band', 2, ['tavg', 'prec'], {}).dimension;+ const month = decodeZarrCoordinate(+ 'month',+ 12,+ Array.from({length: 12}, (_, i) => i + 1),+ {}+ ).dimension;+ const variable = axisVariable([band, month]);+ expect(band.kind).toBe('category');+ expect(formatZarrCoordinate(band, 1)).toBe('prec');+ expect(getZarrAxis(variable, {kind: 'dimension', dimension: 'month'}).frames[2]).toEqual({+ value: 3,+ label: '3',+ selection: {month: 2}+ });+ expect(getZarrAxis(variable, {kind: 'dimension', dimension: 'band'}).frames).toEqual([+ {value: 0, label: 'tavg', selection: {band: 0}},+ {value: 1, label: 'prec', selection: {band: 1}}+ ]);+ });++ it('keeps CMIP6 seasons, scenarios and models categorical, and horizons numeric', () => {+ const variable = axisVariable([+ decodeZarrCoordinate('season', 5, ['yearly', 'DJF', 'MAM', 'JJA', 'SON'], {}).dimension,+ decodeZarrCoordinate('ssp', 3, ['ssp126', 'ssp370', 'ssp585'], {}).dimension,+ decodeZarrCoordinate('gcm', 2, ['gfdl-esm4', 'ipsl-cm6a-lr'], {}).dimension,+ decodeZarrCoordinate('horizon', 3, [2030n, 2055n, 2085n], {}).dimension+ ]);+ const seasons = getZarrAxis(variable, {kind: 'dimension', dimension: 'season'});+ expect(seasons.frames.map(f => f.label)).toEqual(['yearly', 'DJF', 'MAM', 'JJA', 'SON']);+ expect(seasons.frames[3].selection).toEqual({season: 3});+ expect(getZarrAxis(variable, {kind: 'dimension', dimension: 'ssp'}).frames[2].label).toBe(+ 'ssp585'+ );+ expect(getZarrAxis(variable, {kind: 'dimension', dimension: 'gcm'}).frames[1].label).toBe(+ 'ipsl-cm6a-lr'+ );+ expect(+ getZarrAxis(variable, {kind: 'dimension', dimension: 'horizon'}).frames.map(f => f.value)+ ).toEqual([2030, 2055, 2085]);+ expect(getZarrForecastAxes(variable)).toEqual([]);+ });++ it.each(['ECMWF IFS Ensemble', 'NOAA HRRR Forecast'])(+ '%s varies forecast lead, not every run/member',+ name => {+ const isEcmwf = name.startsWith('ECMWF');+ const initCount = isEcmwf ? 935 : 12093;+ const leads = isEcmwf+ ? [+ ...Array.from({length: 49}, (_, i) => i * 3),+ ...Array.from({length: 36}, (_, i) => 150 + i * 6)+ ]+ : Array.from({length: 49}, (_, i) => i);+ const reference = decodeZarrCoordinate(+ 'init_time',+ initCount,+ Array.from({length: initCount}, (_, i) => i * 86400),+ {+ units: 'seconds since 2024-04-01',+ calendar: 'proleptic_gregorian',+ standard_name: 'forecast_reference_time'+ }+ ).dimension;+ const lead = decodeZarrCoordinate(+ 'lead_time',+ leads.length,+ leads.map(h => h * 3600),+ {units: 'seconds', standard_name: 'forecast_period', dtype: 'timedelta64[us]'}+ ).dimension;+ const variable = axisVariable([+ reference,+ lead,+ ...(isEcmwf ? [{name: 'ensemble_member', size: 51}] : [])+ ]);+ const [config] = getZarrForecastAxes(variable);+ expect(config).toEqual({kind: 'forecast', referenceTime: 'init_time', leadTime: 'lead_time'});+ const axis = getZarrAxis(variable, config, {init_time: 1, ensemble_member: 7});+ expect(axis.frames).toHaveLength(isEcmwf ? 85 : 49);+ expect(axis.frames[0].label).toBe('2024-04-02T00:00:00.000Z');+ expect(axis.frames[1].value - axis.frames[0].value).toBe((isEcmwf ? 3 : 1) * HOUR);+ expect(axis.frames[1].selection).toEqual({init_time: 1, lead_time: 1});+ expect(reference.rawValues?.[1]).toBe(86400);+ expect(lead.units).toBe('seconds');+ }+ );++ it('plays year, month and day as independent numeric axes', () => {+ const variable = axisVariable([+ {name: 'year', size: 2, values: [2025, 2024]},+ {name: 'month', size: 2, values: [3, 2]},+ {name: 'day', size: 3, values: [1, 29, 30]}+ ]);+ expect(getZarrAxis(variable, {kind: 'dimension', dimension: 'year'}).frames).toEqual([+ {value: 2024, label: '2024', selection: {year: 1}},+ {value: 2025, label: '2025', selection: {year: 0}}+ ]);+ expect(getZarrAxis(variable, {kind: 'dimension', dimension: 'month'}).frames).toEqual([+ {value: 2, label: '2', selection: {month: 1}},+ {value: 3, label: '3', selection: {month: 0}}+ ]);+ expect(getZarrAxis(variable, {kind: 'dimension', dimension: 'day'}).frames).toEqual([+ {value: 1, label: '1', selection: {day: 0}},+ {value: 29, label: '29', selection: {day: 1}},+ {value: 30, label: '30', selection: {day: 2}}+ ]);+ });++ it('keeps slices distinguishable with duplicate labels and sorts numeric values safely', () => {+ const variable = axisVariable([{name: 'sample', size: 3, values: [30, 10, 20]}]);+ expect(+ getZarrAxis(variable, {kind: 'dimension', dimension: 'sample'}).frames.map(+ f => f.selection.sample+ )+ ).toEqual([1, 2, 0]);+ variable.nonSpatialDims[0].values = ['A', 'A', 'B'];+ expect(+ getZarrAxis(variable, {kind: 'dimension', dimension: 'sample'}).frames.map(f => f.value)+ ).toEqual([0, 1, 2]);+ variable.nonSpatialDims[0].values = [2, 2, 3];+ expect(+ getZarrAxis(variable, {kind: 'dimension', dimension: 'sample'}).frames.map(+ f => f.selection.sample+ )+ ).toEqual([0, 1, 2]);+ });++ it('handles missing coordinates and rejects invalid or oversized axes', () => {+ const variable = axisVariable([+ {name: 'band', size: 2},+ {name: 'empty', size: 0},+ {name: 'sample', size: 100001},+ {name: 'invalid', size: -1}+ ]);+ expect(+ getZarrAxis(variable, {kind: 'dimension', dimension: 'band'}).frames.map(f => f.label)+ ).toEqual(['0', '1']);+ expect(getZarrAxis(variable, {kind: 'dimension', dimension: 'missing'}).error).toBeTruthy();+ expect(getZarrAxis(variable, {kind: 'dimension', dimension: 'empty'}).frames).toEqual([]);+ expect(getZarrAxis(variable, {kind: 'dimension', dimension: 'sample'}).error).toMatch(+ /too many frames/i+ );+ expect(getZarrAxis(variable, {kind: 'dimension', dimension: 'invalid'}).error).toBeTruthy();+ variable.nonSpatialDims[0].values = [NaN, Infinity];+ expect(getZarrAxis(variable, {kind: 'dimension', dimension: 'band'}).frames).toEqual([]);+ expect(getZarrAxis(variable, {kind: 'off'}).frames).toEqual([]);+ });+});++describe('parseCfTimeUnits', () => {+ it('parses the fixed-length units', () => {+ expect(parseCfTimeUnits('seconds since 1970-01-01')).toEqual({stepMs: 1000, originMs: 0});+ expect(parseCfTimeUnits('hours since 1970-01-01')).toEqual({stepMs: HOUR, originMs: 0});+ expect(parseCfTimeUnits('days since 1970-01-01')).toEqual({stepMs: DAY, originMs: 0});+ expect(parseCfTimeUnits('milliseconds since 1970-01-01')).toEqual({stepMs: 1, originMs: 0});+ });++ it('parses non-epoch origins, with and without a time of day', () => {+ expect(parseCfTimeUnits('days since 2020-01-01')).toEqual({+ stepMs: DAY,+ originMs: Date.UTC(2020, 0, 1)+ });+ expect(parseCfTimeUnits('hours since 2020-03-05 06:30:00')).toEqual({+ stepMs: HOUR,+ originMs: Date.UTC(2020, 2, 5, 6, 30, 0)+ });+ expect(parseCfTimeUnits('hours since 2020-03-05T06:30:00Z')).toEqual({+ stepMs: HOUR,+ originMs: Date.UTC(2020, 2, 5, 6, 30, 0)+ });+ // Single-digit month/day, as written by several CF producers.+ expect(parseCfTimeUnits('days since 2020-1-1 0:0:0')).toEqual({+ stepMs: DAY,+ originMs: Date.UTC(2020, 0, 1)+ });+ });++ it('applies the UTC offset of the origin', () => {+ expect(parseCfTimeUnits('hours since 2020-01-01T00:00:00+02:00')).toEqual({+ stepMs: HOUR,+ originMs: Date.UTC(2020, 0, 1) - 2 * HOUR+ });+ });++ it('keeps years below 100 instead of mapping them into the 1900s', () => {+ const parsed = parseCfTimeUnits('days since 0001-01-01');+ expect(parsed).not.toBeNull();+ expect(parsed && new Date(parsed.originMs).getUTCFullYear()).toBe(1);+ });++ it('returns null for units that are not fixed length or not parseable', () => {+ expect(parseCfTimeUnits('months since 1970-01-01')).toBeNull();+ expect(parseCfTimeUnits('years since 1970-01-01')).toBeNull();+ expect(parseCfTimeUnits('meters')).toBeNull();+ expect(parseCfTimeUnits('seconds since not-a-date')).toBeNull();+ expect(parseCfTimeUnits(undefined)).toBeNull();+ expect(parseCfTimeUnits('')).toBeNull();+ });+});++describe('decodeCfTime', () => {+ it('decodes numeric offsets to epoch milliseconds', () => {+ expect(decodeCfTime([0, 3600, 7200], 'seconds since 1970-01-01')).toEqual([0, HOUR, 2 * HOUR]);+ });++ it('decodes a typed array of bigints', () => {+ expect(decodeCfTime(new BigInt64Array([0n, 1n, 2n]), 'days since 2020-01-01')).toEqual([+ Date.UTC(2020, 0, 1),+ Date.UTC(2020, 0, 2),+ Date.UTC(2020, 0, 3)+ ]);+ });++ it('returns null for calendars that have no real-world timeline', () => {+ expect(decodeCfTime([0, 1], 'days since 2020-01-01', '360_day')).toBeNull();+ expect(decodeCfTime([0, 1], 'days since 2020-01-01', 'noleap')).toBeNull();+ expect(decodeCfTime([0, 1], 'days since 2020-01-01', 'proleptic_gregorian')).not.toBeNull();+ });++ it('returns null for missing units, empty input, or non-finite values', () => {+ expect(decodeCfTime([0, 1], undefined)).toBeNull();+ expect(decodeCfTime([], 'seconds since 1970-01-01')).toBeNull();+ expect(decodeCfTime(null, 'seconds since 1970-01-01')).toBeNull();+ expect(decodeCfTime([0, Number.NaN], 'seconds since 1970-01-01')).toBeNull();+ });+});++describe('getZarrTimeDomain', () => {+ it('derives a sorted, de-duplicated domain and step list', () => {+ expect(getZarrTimeDomain({name: 'time', size: 4, values: [30, 10, 20, 10]})).toEqual({+ domain: [10, 30],+ timeSteps: [10, 20, 30]+ });+ });++ it('returns null when there is nothing to animate', () => {+ expect(getZarrTimeDomain(undefined)).toBeNull();+ expect(getZarrTimeDomain({name: 'time', size: 1})).toBeNull();+ expect(getZarrTimeDomain({name: 'time', size: 1, values: [5]})).toBeNull();+ expect(getZarrTimeDomain({name: 'time', size: 2, values: [5, 5]})).toBeNull();+ });+});++describe('getZarrDimensionNames', () => {+ it('reads zarr v3 dimension_names', () => {+ expect(getZarrDimensionNames({dimensionNames: ['time', 'y', 'x'], shape: [3, 4, 5]})).toEqual([+ 'time',+ 'y',+ 'x'+ ]);+ });++ it('falls back to the xarray _ARRAY_DIMENSIONS attribute', () => {+ expect(getZarrDimensionNames({attrs: {_ARRAY_DIMENSIONS: ['y', 'x']}, shape: [4, 5]})).toEqual([+ 'y',+ 'x'+ ]);+ });++ it('returns null when a dimension is unnamed or the rank does not match', () => {+ expect(getZarrDimensionNames({dimensionNames: [null, 'y', 'x'], shape: [3, 4, 5]})).toBeNull();+ expect(getZarrDimensionNames({dimensionNames: ['y', 'x'], shape: [3, 4, 5]})).toBeNull();+ expect(getZarrDimensionNames({shape: [4, 5]})).toBeNull();+ });+});++describe('resolveCoordinatePath', () => {+ // Zarr over HTTP has no directory listing, so a guess at a path that is not+ // in the store costs a 404 round trip. The listing has to be consulted first.+ const index = new Map<string, 'array' | 'group'>([+ ['', 'group'],+ ['FUTUR', 'group'],+ ['FUTUR/qtot', 'array'],+ ['FUTUR/lat', 'array'],+ ['time', 'array']+ ]);++ it('prefers a coordinate stored beside the variable', () => {+ expect(resolveCoordinatePath(index, 'FUTUR/qtot', 'lat')).toBe('/FUTUR/lat');+ });++ it('falls back to a coordinate hoisted to the store root', () => {+ expect(resolveCoordinatePath(index, 'FUTUR/qtot', 'time')).toBe('/time');+ });++ it('returns null when the listing has no such coordinate', () => {+ expect(resolveCoordinatePath(index, 'FUTUR/qtot', 'lead_time')).toBeNull();+ });++ it('does not mistake a group for a coordinate array', () => {+ expect(resolveCoordinatePath(index, 'FUTUR/qtot', 'FUTUR')).toBeNull();+ });++ it('returns null without a listing so the caller probes instead', () => {+ expect(resolveCoordinatePath(null, 'FUTUR/qtot', 'lat')).toBeNull();+ });+});++describe('parseGdalGeoTransform', () => {+ // GDAL writes [c, a, b, f, d, e]; the affine convention is [a, b, c, d, e, f].+ it('reorders a GDAL GeoTransform string into affine order', () => {+ expect(parseGdalGeoTransform('-180 0.5 0 90 0 -0.5')).toEqual([0.5, 0, -180, 0, -0.5, 90]);+ });++ it('accepts an array as well as a string', () => {+ expect(parseGdalGeoTransform([-180, 0.5, 0, 90, 0, -0.5])).toEqual([0.5, 0, -180, 0, -0.5, 90]);+ });++ it('tolerates irregular whitespace', () => {+ expect(parseGdalGeoTransform(' -180 0.5 0\n90 0 -0.5 ')).toEqual([+ 0.5, 0, -180, 0, -0.5, 90+ ]);+ });++ it('rejects anything that is not six finite numbers', () => {+ expect(parseGdalGeoTransform('-180 0.5 0 90 0')).toBeNull();+ expect(parseGdalGeoTransform('-180 0.5 0 90 0 -0.5 1')).toBeNull();+ expect(parseGdalGeoTransform('-180 nope 0 90 0 -0.5')).toBeNull();+ expect(parseGdalGeoTransform(undefined)).toBeNull();+ expect(parseGdalGeoTransform({})).toBeNull();+ });+});++describe('affineFromCellCenters', () => {+ it('steps the origin back by half a cell', () => {+ // Global 0.5 degree grid, north-up: centers start at -179.75 / 89.75.+ expect(affineFromCellCenters({first: -179.75, step: 0.5}, {first: 89.75, step: -0.5})).toEqual([+ 0.5, 0, -180, 0, -0.5, 90+ ]);+ });++ it('handles a south-up grid', () => {+ expect(affineFromCellCenters({first: 0.5, step: 1}, {first: 0.5, step: 1})).toEqual([+ 1, 0, 0, 0, 1, 0+ ]);+ });+});++describe('axisSpacingFromValues', () => {+ it('derives the step from an evenly spaced axis', () => {+ expect(axisSpacingFromValues([10, 20, 30, 40])).toEqual({first: 10, step: 10});+ expect(axisSpacingFromValues([50, 40, 30])).toEqual({first: 50, step: -10});+ });++ it.each([+ {first: -179.95, step: 0.1, count: 3600},+ {first: 89.95, step: -0.1, count: 1800}+ ])('accepts a float32-rounded geographic axis with step $step', ({first, step, count}) => {+ const coordinates = new Float32Array(Array.from({length: count}, (_, i) => first + step * i));+ const spacing = axisSpacingFromValues(coordinates);+ expect(spacing).not.toBeNull();+ if (!spacing) throw new Error('Expected uniform float32 coordinates to be accepted');+ expect(spacing.first).toBe(coordinates[0]);+ expect(spacing.step).toBeCloseTo(step, 7);+ const maxError = Math.max(+ ...Array.from(coordinates, (value, i) => Math.abs(value - (spacing.first + spacing.step * i)))+ );+ expect(maxError).toBeLessThan(0.00002);+ });++ it('rejects nonuniform spacing beyond floating-point rounding', () => {+ expect(axisSpacingFromValues([0, 1, 2.1, 2.9, 4.05])).toBeNull();+ expect(axisSpacingFromValues([0, 1, 2.49, 3.49])).toBeNull();+ expect(axisSpacingFromValues(new Float32Array([0, 0.9, 2, 3]))).toBeNull();+ });++ it('rejects an axis that drifts in the middle but lands on the expected end', () => {+ // A check that only compared the last value would accept this and derive an+ // affine that places the interior cells wrong.+ expect(axisSpacingFromValues([0, 1, 3, 3])).toBeNull();+ expect(axisSpacingFromValues([0, 10, 90, 30, 40])).toBeNull();+ });++ it('rejects an axis it cannot describe with one step', () => {+ expect(axisSpacingFromValues([5])).toBeNull();+ expect(axisSpacingFromValues([5, 5, 5])).toBeNull();+ expect(axisSpacingFromValues([0, 1, NaN, 3])).toBeNull();+ expect(+ axisSpacingFromValues(new Float32Array([100_000_000, 100_000_000, 100_000_008]))+ ).toBeNull();+ });+});++describe('parseOmeMultiscaleLevels', () => {+ it('reads the level paths ndpyramid writes', () => {+ expect(+ parseOmeMultiscaleLevels({+ multiscales: [{datasets: [{path: '0'}, {path: '1'}, {path: '2'}], type: 'reduce'}]+ })+ ).toEqual(['0', '1', '2']);+ });++ it('accepts a bare descriptor as well as a list', () => {+ expect(parseOmeMultiscaleLevels({multiscales: {datasets: [{path: '0'}]}})).toEqual(['0']);+ });++ it('ignores the zarr-conventions layout form', () => {+ expect(+ parseOmeMultiscaleLevels({multiscales: {layout: [{asset: '0'}, {asset: '1'}]}})+ ).toBeNull();+ });++ it('rejects a descriptor without usable paths', () => {+ expect(parseOmeMultiscaleLevels({})).toBeNull();+ expect(parseOmeMultiscaleLevels({multiscales: [{datasets: []}]})).toBeNull();+ expect(parseOmeMultiscaleLevels({multiscales: [{datasets: [{path: 2}]}]})).toBeNull();+ expect(parseOmeMultiscaleLevels({multiscales: [{datasets: [{path: '/'}]}]})).toBeNull();+ });+});++describe('childPrefix', () => {+ it('matches only the children of a matched node', () => {+ expect('FUTUR/qtot'.startsWith(childPrefix('FUTUR'))).toBe(true);+ expect('FUTURE/qtot'.startsWith(childPrefix('FUTUR'))).toBe(false);+ });++ it('matches everything when the root itself matched', () => {+ // A pyramid at the root owns every remaining path, so its levels must not+ // be offered as variables of their own.+ expect('0/temperature'.startsWith(childPrefix(''))).toBe(true);+ expect('lat'.startsWith(childPrefix('/'))).toBe(true);+ });+});++describe('isWebMercatorPyramid', () => {+ it('recognises a pyramid reprojected to web mercator', () => {+ // What CarbonPlan publishes, from `ndpyramid`'s `pyramid_reproject`.+ const attrs = {+ multiscales: [+ {+ datasets: [+ {path: '0', crs: 'EPSG:3857', pixels_per_tile: 128},+ {path: '1', crs: 'EPSG:3857', pixels_per_tile: 128}+ ],+ type: 'reduce'+ }+ ]+ };++ expect(isWebMercatorPyramid(attrs)).toBe(true);+ });++ it('rejects a pyramid that only coarsens the source grid', () => {+ const attrs = {+ multiscales: [{datasets: [{path: '0'}, {path: '1'}], type: 'reduce'}]+ };++ expect(isWebMercatorPyramid(attrs)).toBe(false);+ });++ it('rejects a single level and the zarr-conventions layout form', () => {+ expect(+ isWebMercatorPyramid({+ multiscales: [{datasets: [{path: '0', crs: 'EPSG:3857', pixels_per_tile: 128}]}]+ })+ ).toBe(false);+ expect(isWebMercatorPyramid({multiscales: {layout: [{asset: '0'}]}})).toBe(false);+ expect(isWebMercatorPyramid({})).toBe(false);+ });+});++describe('orderLevelsFinestFirst', () => {+ const assets = (levels: {asset: string}[]) => levels.map(level => level.asset);++ it('reverses a web-mercator pyramid, which numbers its levels by zoom', () => {+ // What CarbonPlan publishes: `0` is one 128px tile for the whole world.+ const declared = [+ {asset: '0/climate', shape: [128, 128]},+ {asset: '1/climate', shape: [256, 256]},+ {asset: '2/climate', shape: [512, 512]}+ ];++ expect(assets(orderLevelsFinestFirst(declared))).toEqual([+ '2/climate',+ '1/climate',+ '0/climate'+ ]);+ });++ it('leaves a pyramid that already declares the finest level first', () => {+ const declared = [+ {asset: '0', shape: [512, 1024]},+ {asset: '1', shape: [256, 512]},+ {asset: '2', shape: [128, 256]}+ ];++ expect(assets(orderLevelsFinestFirst(declared))).toEqual(['0', '1', '2']);+ });++ it('does not mutate the levels it was given', () => {+ const declared = [+ {asset: 'a', shape: [1, 1]},+ {asset: 'b', shape: [4, 4]}+ ];+ orderLevelsFinestFirst(declared);++ expect(assets(declared)).toEqual(['a', 'b']);+ });+});++describe('multiscaleVariableNames', () => {+ it('returns one unnamed variable when the level is the array', () => {+ const index = new Map<string, 'array' | 'group'>([['pyramid/0', 'array']]);+ expect(multiscaleVariableNames(index, 'pyramid/0')).toEqual(['']);+ });++ it('lists the arrays an ndpyramid level group holds', () => {+ const index = new Map<string, 'array' | 'group'>([+ ['pyramid/0', 'group'],+ ['pyramid/0/qtot', 'array'],+ ['pyramid/0/evap_total', 'array'],+ ['pyramid/0/x', 'array'],+ ['pyramid/0/nested', 'group'],+ ['pyramid/0/nested/deep', 'array'],+ ['pyramid/1/qtot', 'array']+ ]);+ expect(multiscaleVariableNames(index, 'pyramid/0').sort()).toEqual(['evap_total', 'qtot', 'x']);+ });++ it('returns nothing without a listing', () => {+ expect(multiscaleVariableNames(null, 'pyramid/0')).toEqual([]);+ });+});++describe('buildMultiscaleAttrs', () => {+ const base = {+ 'spatial:dimensions': ['y', 'x'],+ 'spatial:transform': [1, 0, -180, 0, -1, 90],+ 'spatial:shape': [180, 360],+ 'proj:code': 'EPSG:4326'+ };++ it('produces a layout the GeoZarr parser reads back, finest first', () => {+ const attrs = buildMultiscaleAttrs(base, [+ {asset: '0/qtot', transform: [1, 0, -180, 0, -1, 90], shape: [180, 360]},+ {asset: '1/qtot', transform: [2, 0, -180, 0, -2, 90], shape: [90, 180]}+ ]);++ const {levels, crs, axes} = parseGeoZarrMetadata(attrs);+ expect(levels.map(level => level.path)).toEqual(['0/qtot', '1/qtot']);+ expect([levels[0].arrayHeight, levels[0].arrayWidth]).toEqual([180, 360]);+ expect([levels[1].arrayHeight, levels[1].arrayWidth]).toEqual([90, 180]);+ expect(crs.code).toBe('EPSG:4326');+ expect(axes).toEqual(['y', 'x']);+ });++ it('keeps the finest grid at the top level as a fallback', () => {+ const attrs = buildMultiscaleAttrs(base, [+ {asset: '0', transform: [1, 0, -180, 0, -1, 90], shape: [180, 360]}+ ]);+ expect(attrs['spatial:transform']).toEqual(base['spatial:transform']);+ expect(attrs['spatial:shape']).toEqual(base['spatial:shape']);+ });+});++describe('assignVariableDisplayNames', () => {+ const variable = (path: string) => ({+ path,+ name: path.split('/').filter(Boolean).pop() as string,+ displayName: path.split('/').filter(Boolean).pop() as string+ });++ it('leaves unique names untouched', () => {+ const result = assignVariableDisplayNames([+ variable('FUTUR/qtot'),+ variable('HISTO/evap_total')+ ]);+ expect(result.map(v => v.displayName)).toEqual(['qtot', 'evap_total']);+ });++ it('qualifies names repeated across sibling groups', () => {+ const result = assignVariableDisplayNames([+ variable('FUTUR/evap_total'),+ variable('HISTO/evap_total'),+ variable('RCP/evap_total')+ ]);+ expect(result.map(v => v.displayName)).toEqual([+ 'FUTUR/evap_total',+ 'HISTO/evap_total',+ 'RCP/evap_total'+ ]);+ });++ it('adds only as many path segments as it takes to disambiguate', () => {+ const result = assignVariableDisplayNames([+ variable('cciwr/FUTUR/data/evap_total'),+ variable('cciwr/HISTO/data/evap_total')+ ]);+ expect(result.map(v => v.displayName)).toEqual([+ 'FUTUR/data/evap_total',+ 'HISTO/data/evap_total'+ ]);+ });++ it('keeps the array name when the path has nothing left to add', () => {+ const result = assignVariableDisplayNames([+ variable('evap_total'),+ {...variable('evap_total')}+ ]);+ expect(result.map(v => v.displayName)).toEqual(['evap_total', 'evap_total']);+ });+});++describe('variable selection', () => {+ const temperature: ZarrVariableInfo = {+ path: 'temperature',+ name: 'temperature',+ displayName: 'temperature',+ shape: [12, 180, 360],+ chunks: [1, 90, 90],+ dtype: 'float32',+ nonSpatialDims: [{name: 'time', size: 12, values: [0, DAY]}],+ timeDimension: {name: 'time', size: 12, values: [0, DAY]},+ dataRange: [-40, 40]+ };+ const elevation: ZarrVariableInfo = {+ path: 'elevation',+ name: 'elevation',+ displayName: 'elevation',+ shape: [180, 360],+ chunks: [90, 90],+ dtype: 'int16',+ nonSpatialDims: [],+ dataRange: [0, 8000]+ };+ const metadata: ZarrDatasetMetadata = {+ url: 'https://example.com/store.zarr',+ variable: 'temperature',+ axes: ['time', 'y', 'x'],+ xAxisIndex: 2,+ yAxisIndex: 1,+ levels: [{path: '0', shape: [180, 360], chunks: [90, 90]}],+ variables: [temperature, elevation],+ nonSpatialDims: temperature.nonSpatialDims,+ timeDimension: temperature.timeDimension,+ dataRange: temperature.dataRange+ };++ it('resolves a variable by path and falls back to the first one', () => {+ expect(getZarrVariable(metadata, 'elevation')).toBe(elevation);+ expect(getZarrVariable(metadata)).toBe(temperature);+ expect(getZarrVariable(metadata, 'missing')).toBe(temperature);+ expect(getZarrVariable({variables: []})).toBeUndefined();+ expect(getZarrVariable(undefined)).toBeUndefined();+ });++ it('switches the active variable without refetching', () => {+ const next = selectZarrVariable(metadata, 'elevation');+ expect(next.variable).toBe('elevation');+ expect(next.nonSpatialDims).toEqual([]);+ expect(next.timeDimension).toBeUndefined();+ expect(next.dataRange).toEqual([0, 8000]);+ // The source metadata is untouched.+ expect(metadata.variable).toBe('temperature');+ });++ it('is a no-op when no variables are available', () => {+ expect(selectZarrVariable({...metadata, variables: []}, 'elevation').variable).toBe(+ 'temperature'+ );+ });++ it('falls back to the first available variable when a requested path is missing', () => {+ const active = selectZarrVariable(metadata, 'elevation');+ const next = selectZarrVariable(active, 'missing');+ expect(next.variable).toBe('temperature');+ expect(next.nonSpatialDims).toEqual(temperature.nonSpatialDims);+ expect(next.timeDimension).toEqual(temperature.timeDimension);+ expect(next.dataRange).toEqual(temperature.dataRange);+ expect(active.variable).toBe('elevation');+ });++ it('does not reuse another variable grid when spatial metadata is missing', () => {+ const next = selectZarrVariable(+ {...metadata, crs: {code: 'EPSG:4326'}, webMercatorPyramid: true},+ 'elevation'+ );+ expect(next.crs).toBeUndefined();+ expect(next.axes).toEqual([]);+ expect(next.levels).toEqual([]);+ expect(next.webMercatorPyramid).toBe(false);+ });+});diff --git a/src/table/src/tileset/zarr-utils.ts b/src/table/src/tileset/zarr-utils.tsnew file mode 100644index 000000000..d7a4a603c--- /dev/null+++ b/src/table/src/tileset/zarr-utils.ts@@ -0,0 +1,1466 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import type * as zarr from 'zarrita';++import type {ZarrDatasetMetadata, ZarrDimensionInfo, ZarrVariableInfo} from '@kepler.gl/constants';++import {loadZarrRuntime} from './zarr-runtime';++/** Dimension names treated as time when the store does not advertise CF units. */+const TIME_DIMENSION_NAMES = new Set(['time', 't', 'valid_time', 'datetime', 'date']);++/** CF calendars with a fixed-length day that map cleanly onto epoch milliseconds. */+const SUPPORTED_CALENDARS = new Set(['standard', 'gregorian', 'proleptic_gregorian', 'julian']);++/** Milliseconds per CF time unit. Months and years are omitted: they are not fixed length. */+const CF_UNIT_MS: Record<string, number> = {+ microsecond: 0.001,+ microseconds: 0.001,+ microsec: 0.001,+ us: 0.001,+ millisecond: 1,+ milliseconds: 1,+ millisec: 1,+ msec: 1,+ ms: 1,+ second: 1000,+ seconds: 1000,+ sec: 1000,+ secs: 1000,+ s: 1000,+ minute: 60_000,+ minutes: 60_000,+ min: 60_000,+ mins: 60_000,+ hour: 3_600_000,+ hours: 3_600_000,+ hr: 3_600_000,+ hrs: 3_600_000,+ h: 3_600_000,+ day: 86_400_000,+ days: 86_400_000,+ d: 86_400_000,+ week: 604_800_000,+ weeks: 604_800_000+};++/** Guard against walking an unbounded hierarchy when a store lists thousands of nodes. */+const MAX_VARIABLE_CANDIDATES = 200;++/**+ * Axis labels `@developmentseed/geozarr` accepts for the spatial dimensions.+ * Anything else cannot be rendered, so it is not worth deriving metadata for.+ */+const Y_AXIS_LABELS = new Set(['y', 'latitude', 'lat']);+const X_AXIS_LABELS = new Set(['x', 'longitude', 'lon']);++/** Variable names conventionally holding the CF grid mapping when none is named. */+const GRID_MAPPING_FALLBACK_NAMES = ['spatial_ref', 'crs', 'transverse_mercator', 'projection'];++/** Coordinate arrays longer than this are not worth materializing for a time slider. */+const MAX_COORDINATE_LENGTH = 20_000;++export type CfTimeUnits = {+ /** Milliseconds represented by one coordinate step. */+ stepMs: number;+ /** Epoch milliseconds of coordinate value zero. */+ originMs: number;+};++type AnyAttrs = Record<string, unknown>;++type StoreContents = {path: string; kind: 'array' | 'group'}[];++type ListableStore = zarr.Readable & {contents?: () => StoreContents; signal?: AbortSignal};++/**+ * Node kinds by normalized path, built from the store's consolidated metadata.+ *+ * Zarr over plain HTTP has no directory listing, so without this every guess at+ * a coordinate or grid-mapping path costs a round trip that usually 404s. When+ * the store publishes a listing we consult it instead of probing. Null means+ * the store has no consolidated metadata and probing is the only option.+ */+type StoreIndex = Map<string, 'array' | 'group'> | null;++function normalizePath(path: string): string {+ return path.replace(/^\/+/, '').replace(/\/+$/, '');+}++function buildStoreIndex(store: ListableStore): StoreIndex {+ if (typeof store.contents !== 'function') {+ return null;+ }+ const index = new Map<string, 'array' | 'group'>();+ for (const entry of store.contents()) {+ index.set(normalizePath(entry.path), entry.kind);+ }+ return index;+}++/** True when the path is known to be absent, so opening it would only 404. */+function isKnownMissing(index: StoreIndex, path: string, kind?: 'array' | 'group'): boolean {+ if (!index) {+ return false;+ }+ const found = index.get(normalizePath(path));+ return kind ? found !== kind : found === undefined;+}++/**+ * Parse a CF `units` string of the form `"<unit> since <timestamp>"`.+ *+ * Returns null for units that are not fixed-length (months, years) or for a+ * timestamp the runtime cannot parse, so callers can fall back to treating the+ * dimension as non-temporal instead of producing nonsense dates.+ */+export function parseCfTimeUnits(units?: string | null): CfTimeUnits | null {+ if (typeof units !== 'string') {+ return null;+ }+ const match = units.trim().match(/^([a-zA-Z]+)\s+since\s+(.+)$/);+ if (!match) {+ return null;+ }+ const stepMs = CF_UNIT_MS[match[1].toLowerCase()];+ if (!stepMs) {+ return null;+ }+ const originMs = parseCfTimeOrigin(match[2]);+ if (originMs === null) {+ return null;+ }+ return {stepMs, originMs};+}++/**+ * CF reference dates come in many shapes: `1970-01-01`, `1970-1-1 0:0:0`,+ * `2020-01-01T00:00:00Z`, sometimes with a trailing offset. Normalize to+ * something `Date.parse` accepts and default to UTC when no zone is given.+ */+function parseCfTimeOrigin(origin: string): number | null {+ const trimmed = origin.trim();+ const match = trimmed.match(+ /^(\d{1,4})-(\d{1,2})-(\d{1,2})(?:[T ](\d{1,2}):(\d{1,2})(?::(\d{1,2}(?:\.\d+)?))?)?\s*(Z|UTC|GMT|[+-]\d{1,2}:?\d{0,2})?$/i+ );+ if (!match) {+ return null;+ }+ const [, year, month, day, hour = '0', minute = '0', second = '0', zone] = match;+ const seconds = Number.parseFloat(second);+ const base = Date.UTC(+ Number(year),+ Number(month) - 1,+ Number(day),+ Number(hour),+ Number(minute),+ Math.trunc(seconds),+ Math.round((seconds % 1) * 1000)+ );+ if (!Number.isFinite(base)) {+ return null;+ }+ // Date.UTC maps years 0-99 into the 1900s, which is wrong for CF epochs like `0001-01-01`.+ const utc = Number(year) < 100 ? adjustLowYear(base, Number(year)) : base;+ return utc - parseUtcOffsetMs(zone);+}++function adjustLowYear(base: number, year: number): number {+ const date = new Date(base);+ date.setUTCFullYear(year);+ return date.getTime();+}++function parseUtcOffsetMs(zone?: string): number {+ if (!zone || /^(Z|UTC|GMT)$/i.test(zone)) {+ return 0;+ }+ const match = zone.match(/^([+-])(\d{1,2}):?(\d{0,2})$/);+ if (!match) {+ return 0;+ }+ const sign = match[1] === '-' ? -1 : 1;+ const hours = Number(match[2]);+ const minutes = match[3] ? Number(match[3]) : 0;+ return sign * (hours * 3_600_000 + minutes * 60_000);+}++/**+ * Decode CF-encoded time coordinates into epoch milliseconds.+ *+ * Returns null when the units are missing, not fixed-length, or the calendar is+ * one of the synthetic CF calendars (`360_day`, `noleap`, ...) that cannot be+ * represented on a real timeline.+ */+export function decodeCfTime(+ values: ArrayLike<number | bigint> | null | undefined,+ units?: string | null,+ calendar?: string | null+): number[] | null {+ if (!values || values.length === 0) {+ return null;+ }+ if (typeof calendar === 'string' && !SUPPORTED_CALENDARS.has(calendar.toLowerCase())) {+ return null;+ }+ const parsed = parseCfTimeUnits(units);+ if (!parsed) {+ return null;+ }+ const decoded: number[] = [];+ for (let i = 0; i < values.length; i++) {+ const raw = Number(values[i]);+ if (!Number.isFinite(raw)) {+ return null;+ }+ decoded.push(parsed.originMs + raw * parsed.stepMs);+ }+ return decoded;+}++/**+ * Animation domain for a decoded time dimension, or null when the dimension+ * carries fewer than two usable timestamps.+ */+export function getZarrTimeDomain(+ dimension?: ZarrDimensionInfo | null+): {domain: [number, number]; timeSteps: number[]} | null {+ const values = dimension?.values;+ if (!values || values.length < 2) {+ return null;+ }+ const timeSteps = [...new Set(values)]+ .filter((value): value is number => typeof value === 'number' && Number.isFinite(value))+ .sort((a, b) => a - b);+ if (timeSteps.length < 2) {+ return null;+ }+ return {domain: [timeSteps[0], timeSteps[timeSteps.length - 1]], timeSteps};+}++/** Find a variable by path, falling back to the dataset's active variable. */+export function getZarrVariable(+ metadata?: Partial<ZarrDatasetMetadata> | null,+ variablePath?: string+): ZarrVariableInfo | undefined {+ const variables = metadata?.variables;+ if (!variables || variables.length === 0) {+ return undefined;+ }+ const path = variablePath ?? metadata?.variable;+ return variables.find(variable => variable.path === path) ?? variables[0];+}++/**+ * Switch the active variable of an already-fetched dataset metadata. Pure, so+ * the layer can react to the variable dropdown without refetching the store.+ */+export function selectZarrVariable(+ metadata: ZarrDatasetMetadata,+ variablePath: string+): ZarrDatasetMetadata {+ const variable = getZarrVariable(metadata, variablePath);+ if (!variable) {+ return metadata;+ }+ return {+ ...metadata,+ ...(variable.spatialMetadata ??+ (variable.path === metadata.variable+ ? {}+ : {+ crs: undefined,+ axes: [],+ xAxisIndex: -1,+ yAxisIndex: -1,+ levels: [],+ webMercatorPyramid: false+ })),+ variable: variable.path,+ nonSpatialDims: variable.nonSpatialDims,+ timeDimension: variable.timeDimension,+ dataRange: variable.dataRange,+ nodataValue: variable.nodataValue+ };+}++function throwIfAborted(signal?: AbortSignal): void {+ if (signal?.aborted) {+ throw signal.reason ?? new DOMException('The operation was aborted.', 'AbortError');+ }+}++const storeCache = new Map<string, Promise<ListableStore>>();++export type ZarrMetadataProgress = {+ phase: 'connecting' | 'downloading' | 'processing';+ loadedBytes: number;+ /** Total for completed and active downloads, when every active size is known. */+ totalBytes?: number;+};++function createMetadataFetch(+ signal: AbortSignal | undefined,+ onProgress: (progress: ZarrMetadataProgress) => void+): typeof fetch {+ let loadedBytes = 0;+ let lastUpdate = 0;+ let waitingForHeaders = 0;+ const active = new Set<{loaded: number; total?: number}>();+ const report = (force = false) => {+ if (signal?.aborted || (!force && Date.now() - lastUpdate < 200)) return;+ lastUpdate = Date.now();+ const downloads = [...active];+ const totalBytes =+ !waitingForHeaders &&+ downloads.length &&+ downloads.every(download => download.total !== undefined)+ ? loadedBytes ++ downloads.reduce((sum, download) => sum + (download.total ?? 0) - download.loaded, 0)+ : undefined;+ onProgress({+ phase: downloads.length ? 'downloading' : waitingForHeaders ? 'connecting' : 'processing',+ loadedBytes,+ totalBytes+ });+ };++ return async (request, init) => {+ throwIfAborted(signal);+ waitingForHeaders++;+ report(true);+ let response: Response;+ try {+ response = await fetch(request, {...init, signal});+ } catch (error) {+ waitingForHeaders--;+ report(true);+ throw error;+ }+ waitingForHeaders--;+ throwIfAborted(signal);+ if (!response.ok || !response.body) {+ report(true);+ return response;+ }++ // Fetch streams contain decoded bytes. An encoded Content-Length cannot+ // be compared to them, and some servers do not expose a length at all.+ const length = Number(response.headers.get('content-length'));+ const encoding = response.headers.get('content-encoding');+ const download = {+ loaded: 0,+ total:+ (!encoding || encoding === 'identity') && Number.isFinite(length) && length > 0+ ? length+ : undefined+ };+ active.add(download);+ report(true);+ const reader = response.body.getReader();+ const abort = () => {+ void reader.cancel(signal?.reason).catch(() => undefined);+ };+ signal?.addEventListener('abort', abort, {once: true});+ const finish = () => {+ active.delete(download);+ signal?.removeEventListener('abort', abort);+ };+ const body = new ReadableStream<Uint8Array>({+ async pull(controller) {+ try {+ throwIfAborted(signal);+ const {done, value} = await reader.read();+ throwIfAborted(signal);+ if (done) {+ finish();+ reader.releaseLock();+ report(true);+ controller.close();+ return;+ }+ download.loaded += value.byteLength;+ loadedBytes += value.byteLength;+ // A proxy may hide Content-Encoding while exposing the encoded size.+ if (download.total !== undefined && download.loaded > download.total) {+ download.total = undefined;+ }+ report();+ controller.enqueue(value);+ } catch (error) {+ finish();+ await reader.cancel(error).catch(() => undefined);+ controller.error(error);+ }+ },+ cancel(reason) {+ finish();+ return reader.cancel(reason);+ }+ });+ return new Response(body, {+ status: response.status,+ statusText: response.statusText,+ headers: response.headers+ });+ };+}++async function withDetectedZarrMetadata(store: zarr.FetchStore): Promise<ListableStore> {+ const {zarr} = await loadZarrRuntime();+ for (const format of ['v2', 'v3'] as const) {+ const consolidated = await zarr.withMaybeConsolidatedMetadata(store, {format});+ if (consolidated === store) continue;+ if (format === 'v3') {+ // Open the cached root with the known format. Otherwise Zarrita initially+ // probes .zattrs/.zarray/.zgroup, which can each take seconds to return 404.+ await zarr.open.v3(consolidated, {kind: 'group'});+ }+ return consolidated as ListableStore;+ }+ return store;+}++/**+ * Open a Zarr store, preferring consolidated metadata so variable discovery+ * costs one request instead of one per node. Memoized per URL because the+ * dataset refresh and the layer open the same store. Cancellable metadata+ * previews use their own store so aborting a preview cannot affect a layer.+ */+export function openZarrStore(url: string): Promise<ListableStore> {+ const existing = storeCache.get(url);+ if (existing) {+ return existing;+ }+ const opening = (async () => {+ const {zarr} = await loadZarrRuntime();+ const store = new zarr.FetchStore(url);+ return withDetectedZarrMetadata(store);+ })().catch((error: unknown) => {+ storeCache.delete(url);+ throw error;+ });+ storeCache.set(url, opening);+ return opening;+}++/**+ * Open the node that backs a variable: a multiscale group, or the array itself+ * for a single-resolution dataset. This is what `ZarrLayer` takes as its `node`+ * prop, already resolved so the layer does not need a `variable` path.+ */+export async function openZarrNode(+ url: string,+ variablePath?: string+): Promise<zarr.Array<zarr.DataType, zarr.Readable> | zarr.Group<zarr.Readable>> {+ const store = await openZarrStore(url);+ const {zarr} = await loadZarrRuntime();+ return zarr.open(new zarr.Location(store, toAbsolutePath(variablePath ?? '')));+}++/** Drop a cached store so a refresh re-reads the consolidated metadata. */+export function clearZarrStoreCache(url?: string): void {+ if (url === undefined) {+ storeCache.clear();+ } else {+ storeCache.delete(url);+ }+}++function toAbsolutePath(path: string): `/${string}` {+ const trimmed = path.replace(/^\/+/, '').replace(/\/+$/, '');+ return (trimmed ? `/${trimmed}` : '/') as `/${string}`;+}++function getAttrs(node: {attrs?: AnyAttrs}): AnyAttrs {+ return (node.attrs ?? {}) as AnyAttrs;+}++function readNumber(attrs: AnyAttrs, keys: string[]): number | undefined {+ for (const key of keys) {+ const value = attrs[key];+ if (typeof value === 'number' && Number.isFinite(value)) {+ return value;+ }+ if (typeof value === 'bigint') {+ return Number(value);+ }+ }+ return undefined;+}++function readString(attrs: AnyAttrs, keys: string[]): string | undefined {+ for (const key of keys) {+ const value = attrs[key];+ if (typeof value === 'string' && value) {+ return value;+ }+ }+ return undefined;+}++function readDataRange(attrs: AnyAttrs): [number, number] | undefined {+ const range = attrs.actual_range ?? attrs.valid_range;+ if (Array.isArray(range) && range.length === 2) {+ const [min, max] = range.map(Number);+ if (Number.isFinite(min) && Number.isFinite(max) && min < max) {+ return [min, max];+ }+ }+ const min = readNumber(attrs, ['valid_min', 'vmin', 'min', 'minimum']);+ const max = readNumber(attrs, ['valid_max', 'vmax', 'max', 'maximum']);+ if (min !== undefined && max !== undefined && min < max) {+ return [min, max];+ }+ return undefined;+}++/**+ * Dimension names for a zarr array. Zarr v3 stores them in `dimension_names`;+ * xarray-written v2 stores put them in the `_ARRAY_DIMENSIONS` attribute.+ */+export function getZarrDimensionNames(arr: {+ dimensionNames?: (string | null)[];+ attrs?: AnyAttrs;+ shape: number[];+}): string[] | null {+ const fromMetadata = arr.dimensionNames;+ if (fromMetadata && fromMetadata.length === arr.shape.length) {+ const named = fromMetadata.filter((name): name is string => Boolean(name));+ if (named.length === fromMetadata.length) {+ return named;+ }+ }+ const fromAttrs = getAttrs(arr)._ARRAY_DIMENSIONS;+ if (Array.isArray(fromAttrs) && fromAttrs.length === arr.shape.length) {+ const named = fromAttrs.filter((name): name is string => typeof name === 'string' && !!name);+ if (named.length === fromAttrs.length) {+ return named;+ }+ }+ return null;+}++/**+ * Candidate locations for a coordinate array. Coordinates usually sit next to+ * the variable, but xarray and the GeoZarr examples also hoist shared+ * coordinates to the store root.+ */+function coordinateCandidates(variablePath: string, name: string): `/${string}`[] {+ const parent = variablePath.split('/').slice(0, -1).join('/');+ return [+ toAbsolutePath(`${variablePath}/${name}`),+ toAbsolutePath(`${parent}/${name}`),+ toAbsolutePath(name)+ ];+}++/**+ * Resolve a coordinate array to a concrete path using the store listing, with+ * no network access. Returns null when the store has no listing (the caller+ * must probe) or when no candidate exists.+ */+export function resolveCoordinatePath(+ index: StoreIndex,+ variablePath: string,+ name: string+): string | null {+ if (!index) {+ return null;+ }+ for (const path of new Set(coordinateCandidates(variablePath, name))) {+ if (index.get(normalizePath(path)) === 'array') {+ return path;+ }+ }+ return null;+}++/** Open a 1-D coordinate array for `name`, or null when there is not one. */+async function openCoordinateArray(+ store: ListableStore,+ index: StoreIndex,+ variablePath: string,+ name: string,+ size?: number+): Promise<zarr.Array<zarr.DataType, zarr.Readable> | null> {+ const {zarr} = await loadZarrRuntime();+ for (const path of new Set(coordinateCandidates(variablePath, name))) {+ if (isKnownMissing(index, path, 'array')) {+ continue;+ }+ try {+ const arr = await zarr.open(new zarr.Location(store, path), {kind: 'array'});+ if (arr.shape.length !== 1 || (size !== undefined && arr.shape[0] !== size)) {+ continue;+ }+ return arr;+ } catch {+ throwIfAborted(store.signal);+ // Not every dimension has a coordinate array; try the next candidate.+ }+ }+ return null;+}++/**+ * GDAL writes its six-element `GeoTransform` as a space-separated string in+ * `[c, a, b, f, d, e]` order. `@developmentseed/affine` wants `[a, b, c, d, e, f]`.+ */+export function parseGdalGeoTransform(value: unknown): number[] | null {+ const parts =+ typeof value === 'string'+ ? value.trim().split(/\s+/).map(Number)+ : Array.isArray(value)+ ? value.map(Number)+ : null;+ if (!parts || parts.length !== 6 || !parts.every(Number.isFinite)) {+ return null;+ }+ const [c, a, b, f, d, e] = parts;+ return [a, b, c, d, e, f];+}++type GridMapping = {crs?: AnyAttrs; transform?: number[]};++/**+ * Read the CF grid-mapping variable, which is where GDAL-written stores keep+ * the CRS (`crs_wkt` / `spatial_ref`) and the affine (`GeoTransform`).+ */+async function readGridMapping(+ store: ListableStore,+ index: StoreIndex,+ variablePath: string,+ arrayAttrs: AnyAttrs+): Promise<GridMapping | null> {+ const {zarr} = await loadZarrRuntime();+ const named = readString(arrayAttrs, ['grid_mapping']);+ const names = named ? [named, ...GRID_MAPPING_FALLBACK_NAMES] : GRID_MAPPING_FALLBACK_NAMES;+ const parent = variablePath.split('/').slice(0, -1).join('/');++ for (const name of new Set(names)) {+ for (const base of new Set([variablePath, parent, ''])) {+ const path = toAbsolutePath(`${base}/${name}`);+ if (isKnownMissing(index, path)) {+ continue;+ }+ let attrs: AnyAttrs;+ try {+ const node = await zarr.open(new zarr.Location(store, path));+ attrs = getAttrs(node);+ } catch {+ throwIfAborted(store.signal);+ continue;+ }+ const wkt2 = readString(attrs, ['crs_wkt', 'spatial_ref', 'esri_pe_string']);+ const epsg = readNumber(attrs, ['epsg_code', 'EPSG_code']);+ const crs = epsg ? {'proj:code': `EPSG:${epsg}`} : wkt2 ? {'proj:wkt2': wkt2} : undefined;+ const transform = parseGdalGeoTransform(attrs.GeoTransform ?? attrs.geotransform);+ if (crs || transform) {+ return {crs, transform: transform ?? undefined};+ }+ }+ }+ return null;+}++/**+ * Derive the affine from 1-D coordinate arrays, which is how most CF stores+ * describe a regular grid. Coordinate values are cell centers, so the origin is+ * stepped back by half a cell to reach the outer edge the affine expects.+ *+ * Returns null for irregular spacing, which an affine cannot represent.+ */+async function deriveAffineFromCoordinates(+ store: ListableStore,+ index: StoreIndex,+ variablePath: string,+ yName: string,+ xName: string,+ height: number,+ width: number,+ cache: CoordinateCache+): Promise<number[] | null> {+ const [yArr, xArr] = await Promise.all([+ openCoordinateArray(store, index, variablePath, yName, height),+ openCoordinateArray(store, index, variablePath, xName, width)+ ]);+ if (!yArr || !xArr) {+ return null;+ }+ const [yStats, xStats] = await Promise.all([+ readAxisSpacing(yArr, cache),+ readAxisSpacing(xArr, cache)+ ]);+ if (!yStats || !xStats) {+ return null;+ }+ return affineFromCellCenters(xStats, yStats);+}++export type AxisSpacing = {first: number; step: number};++/**+ * Build an affine from the spacing of two cell-center axes. The affine maps the+ * outer edge of the first cell, so each origin is stepped back by half a cell.+ */+export function affineFromCellCenters(x: AxisSpacing, y: AxisSpacing): number[] {+ return [x.step, 0, x.first - x.step / 2, 0, y.step, y.first - y.step / 2];+}++/**+ * Derive a constant step from a cell-center coordinate array, rejecting any grid+ * the affine would misrepresent. Every coordinate is checked rather than just+ * the last, because an axis that drifts in the middle yet lands on the expected+ * endpoint would otherwise yield a silently wrong georeference.+ */+export function axisSpacingFromValues(raw: ArrayLike<number | bigint>): AxisSpacing | null {+ if (raw.length < 2) {+ return null;+ }+ const first = Number(raw[0]);+ const last = Number(raw[raw.length - 1]);+ // Average over the whole axis so rounding the first two float32 coordinates+ // does not accumulate into a large positional error at the far end.+ const step = (last - first) / (raw.length - 1);+ if (!Number.isFinite(first) || !Number.isFinite(step) || step === 0) {+ return null;+ }+ // Allow coordinate rounding and affine arithmetic, not a fraction of a cell.+ const precision = raw instanceof Float32Array ? 2 ** -23 : Number.EPSILON;+ const tolerance = Math.max(Math.abs(first), Math.abs(last), Math.abs(step)) * precision * 2;+ let previous = first;+ for (let i = 1; i < raw.length; i++) {+ const value = Number(raw[i]);+ if (+ !Number.isFinite(value) ||+ (step > 0 ? value <= previous : value >= previous) ||+ Math.abs(value - (first + step * i)) > tolerance+ ) {+ return null;+ }+ previous = value;+ }+ return {first, step};+}++async function readAxisSpacing(+ arr: zarr.Array<zarr.DataType, zarr.Readable>,+ cache: CoordinateCache+): Promise<AxisSpacing | null> {+ if (arr.shape[0] < 2 || arr.shape[0] > MAX_COORDINATE_LENGTH) {+ return null;+ }+ let pending = cache.spatialAxes.get(arr.path);+ if (!pending) {+ pending = (async () => {+ const {zarr} = await loadZarrRuntime();+ const chunk = await zarr.get(arr, null);+ return axisSpacingFromValues(chunk.data as ArrayLike<number | bigint>);+ })();+ cache.spatialAxes.set(arr.path, pending);+ }+ return pending;+}++/**+ * Synthesize GeoZarr-convention attributes for a store that does not declare+ * them, using the CF/GDAL metadata that real-world Zarr publishers actually+ * write: a grid-mapping variable and/or 1-D coordinate arrays.+ *+ * `ZarrLayer` re-parses whatever is passed as its `metadata` prop, so the+ * result is attributes rather than a parsed descriptor.+ */+async function deriveGeoZarrAttrs(+ store: ListableStore,+ index: StoreIndex,+ variablePath: string,+ arr: zarr.Array<zarr.DataType, zarr.Readable>,+ dimensionNames: string[],+ cache: CoordinateCache+): Promise<AnyAttrs | null> {+ if (dimensionNames.length < 2) {+ return null;+ }+ const yName = dimensionNames[dimensionNames.length - 2];+ const xName = dimensionNames[dimensionNames.length - 1];+ // The renderer requires the spatial dims last, in [y, x] order, and labeled+ // with names the GeoZarr parser recognizes.+ if (!Y_AXIS_LABELS.has(yName.toLowerCase()) || !X_AXIS_LABELS.has(xName.toLowerCase())) {+ return null;+ }++ const height = arr.shape[arr.shape.length - 2];+ const width = arr.shape[arr.shape.length - 1];+ const gridMapping = await readGridMapping(store, index, variablePath, getAttrs(arr));++ const transform =+ gridMapping?.transform ??+ (await deriveAffineFromCoordinates(+ store,+ index,+ variablePath,+ yName,+ xName,+ height,+ width,+ cache+ ));+ if (!transform) {+ return null;+ }++ // Lat/lon axis names imply geographic coordinates when nothing declares a CRS.+ const isGeographic = yName.toLowerCase() !== 'y' && xName.toLowerCase() !== 'x';+ const crs = gridMapping?.crs ?? (isGeographic ? {'proj:code': 'EPSG:4326'} : null);+ if (!crs) {+ return null;+ }++ return {+ 'spatial:dimensions': [yName, xName],+ 'spatial:transform': transform,+ 'spatial:shape': [height, width],+ ...crs+ };+}++/**+ * Level paths of an OME-NGFF style `multiscales` attribute, finest first.+ *+ * `ndpyramid` and `xarray-multiscale` write a pyramid this way: a list of+ * multiscale descriptors, each holding a `datasets` array of child paths. The+ * zarr-conventions form the GeoZarr parser reads is instead an object with a+ * `layout`, so the two have to be told apart and the OME form rewritten.+ */+export function parseOmeMultiscaleLevels(attrs: AnyAttrs): string[] | null {+ const raw = attrs.multiscales;+ const entry = Array.isArray(raw) ? raw[0] : raw;+ if (!entry || typeof entry !== 'object') {+ return null;+ }+ const datasets = (entry as {datasets?: unknown}).datasets;+ if (!Array.isArray(datasets) || datasets.length === 0) {+ return null;+ }+ const paths: string[] = [];+ for (const dataset of datasets) {+ const path = (dataset as {path?: unknown})?.path;+ if (typeof path !== 'string' || !normalizePath(path)) {+ return null;+ }+ paths.push(normalizePath(path));+ }+ return paths;+}++/**+ * Whether `multiscales` describes a web-mercator tile pyramid.+ *+ * This is what `ndpyramid`'s `pyramid_reproject` writes and what CarbonPlan+ * publishes: every level is reprojected to EPSG:3857 and covers the whole world+ * in `pixels_per_tile * 2 ** level` pixels. Knowing that lets the renderer tie+ * the level it draws to the map zoom, which is how such a pyramid is meant to+ * be read.+ */+export function isWebMercatorPyramid(attrs: AnyAttrs): boolean {+ const raw = attrs?.multiscales;+ const entry = Array.isArray(raw) ? raw[0] : raw;+ const datasets = (entry as {datasets?: unknown})?.datasets;+ if (!Array.isArray(datasets) || datasets.length < 2) {+ return false;+ }+ return datasets.every(dataset => {+ const {crs, pixels_per_tile: pixelsPerTile} = (dataset ?? {}) as {+ crs?: unknown;+ pixels_per_tile?: unknown;+ };+ return crs === 'EPSG:3857' && typeof pixelsPerTile === 'number' && pixelsPerTile > 0;+ });+}++/**+ * Order pyramid levels finest first, which is what the renderer expects.+ *+ * OME-NGFF asks for that order in the declaration, but a web-mercator pyramid —+ * what `ndpyramid`'s `pyramid_reproject` writes, and what CarbonPlan publishes —+ * numbers its levels by zoom, so `0` is the coarsest. Sorting by resolution+ * rather than trusting the declared order reads either convention right.+ */+export function orderLevelsFinestFirst<T extends {shape: number[]}>(levels: T[]): T[] {+ return [...levels].sort((a, b) => b.shape[0] * b.shape[1] - a.shape[0] * a.shape[1]);+}++/**+ * Names of the data arrays a pyramid level holds.+ *+ * An OME-NGFF level path points straight at the array, so there is nothing to+ * name and the result is a single empty string. `ndpyramid` instead writes an+ * xarray dataset per level, so the level is a group and each array inside it is+ * a separate variable sharing the same pyramid.+ */+export function multiscaleVariableNames(index: StoreIndex, levelPath: string): string[] {+ if (!index) {+ return [];+ }+ const normalized = normalizePath(levelPath);+ if (index.get(normalized) === 'array') {+ return [''];+ }+ const prefix = `${normalized}/`;+ const names: string[] = [];+ for (const [path, kind] of index) {+ if (kind !== 'array' || !path.startsWith(prefix)) {+ continue;+ }+ const rest = path.slice(prefix.length);+ if (!rest.includes('/')) {+ names.push(rest);+ }+ }+ return names;+}++/**+ * Rewrite per-level grids into the `multiscales.layout` the GeoZarr parser+ * reads. Levels stay finest-first, which is the order it expects.+ */+export function buildMultiscaleAttrs(+ base: AnyAttrs,+ levels: {asset: string; transform: number[]; shape: number[]}[]+): AnyAttrs {+ // The finest grid stays at the top level as well, because the convention+ // allows per-level values to be omitted and falls back to it.+ return {+ ...base,+ multiscales: {+ layout: levels.map(level => ({+ asset: level.asset,+ 'spatial:transform': level.transform,+ 'spatial:shape': level.shape+ }))+ }+ };+}++type CoordinateResult = {dimension: ZarrDimensionInfo; isCfTime: boolean};++/** Decode coordinates without losing categorical labels or duration/calendar metadata. */+export function decodeZarrCoordinate(+ name: string,+ size: number,+ raw: ArrayLike<unknown> | Iterable<unknown>,+ attrs: AnyAttrs+): CoordinateResult {+ const units = readString(attrs, ['units']);+ const calendar = readString(attrs, ['calendar']);+ const standardName = readString(attrs, ['standard_name']);+ const source = Array.from(raw);+ const values = source.map(value =>+ typeof value === 'bigint'+ ? Number.isSafeInteger(Number(value))+ ? Number(value)+ : String(value)+ : value+ );+ const dimension: ZarrDimensionInfo = {name, size, units, calendar, standardName};+ if (!values.every(v => ['number', 'string', 'boolean'].includes(typeof v))) {+ return {dimension, isCfTime: false};+ }+ const numeric = values.every(v => typeof v === 'number');+ const decoded = source.every(v => typeof v === 'number' || typeof v === 'bigint')+ ? decodeCfTime(source as (number | bigint)[], units, calendar)+ : null;+ return {+ dimension: {+ ...dimension,+ values: decoded ?? (values as NonNullable<ZarrDimensionInfo['values']>),+ ...(decoded ? {rawValues: values as NonNullable<ZarrDimensionInfo['values']>} : {}),+ kind: decoded+ ? 'time'+ : !numeric || standardName === 'realization'+ ? 'category'+ : standardName === 'forecast_period' || String(attrs.dtype).startsWith('timedelta')+ ? 'duration'+ : 'number'+ },+ isCfTime: Boolean(decoded)+ };+}++/**+ * Coordinate arrays are shared across the variables of a store, and a time axis+ * can run to thousands of values. Read each one once per metadata fetch.+ */+type CoordinateCache = {+ dimensions: Map<string, Promise<CoordinateResult>>;+ spatialAxes: Map<string, Promise<AxisSpacing | null>>;+};++function readCoordinateDimension(+ store: ListableStore,+ index: StoreIndex,+ variablePath: string,+ name: string,+ size: number,+ cache: CoordinateCache+): Promise<CoordinateResult> {+ const resolved = resolveCoordinatePath(index, variablePath, name);+ if (index && !resolved) {+ // The listing says this dimension has no coordinate array; do not probe.+ return Promise.resolve({dimension: {name, size}, isCfTime: false});+ }+ const key = `${resolved ?? variablePath}|${name}|${size}`;+ const cached = cache.dimensions.get(key);+ if (cached) {+ return cached;+ }+ const pending = loadCoordinateDimension(store, index, variablePath, name, size);+ cache.dimensions.set(key, pending);+ return pending;+}++async function loadCoordinateDimension(+ store: ListableStore,+ index: StoreIndex,+ variablePath: string,+ name: string,+ size: number+): Promise<CoordinateResult> {+ const dimension: ZarrDimensionInfo = {name, size};+ if (size > MAX_COORDINATE_LENGTH) {+ return {dimension, isCfTime: false};+ }++ const arr = await openCoordinateArray(store, index, variablePath, name, size);+ if (!arr) {+ return {dimension, isCfTime: false};+ }++ try {+ const {zarr} = await loadZarrRuntime();+ const chunk = await zarr.get(arr, null);+ return decodeZarrCoordinate(name, size, chunk.data, getAttrs(arr));+ } catch {+ throwIfAborted(store.signal);+ return {dimension, isCfTime: false};+ }+}++/**+ * A dimension decoded through CF units is temporal regardless of its name.+ * Otherwise fall back to the conventional time dimension names.+ */+function isTimeDimension(dimension: ZarrDimensionInfo, decodedFromCf: boolean): boolean {+ if (!dimension.values || dimension.values.length < 2) {+ return false;+ }+ // Unsupported calendars/units must not be mistaken for epoch milliseconds.+ return (+ decodedFromCf ||+ (!dimension.units &&+ dimension.kind !== 'category' &&+ TIME_DIMENSION_NAMES.has(dimension.name.toLowerCase()))+ );+}++async function buildVariableInfo(+ store: ListableStore,+ index: StoreIndex,+ path: string,+ geoAttrs: AnyAttrs,+ cache: CoordinateCache,+ options: {+ preopened?: zarr.Array<zarr.DataType, zarr.Readable>;+ nodePath?: string;+ webMercatorPyramid?: boolean;+ } = {}+): Promise<ZarrVariableInfo | null> {+ const {zarr, parseGeoZarrMetadata} = await loadZarrRuntime();+ const geo = parseGeoZarrMetadata(geoAttrs);+ const spatialDims = [geo.axes[geo.yAxisIndex], geo.axes[geo.xAxisIndex]];++ const nodePath = options.nodePath ?? path;+ const basePath = toAbsolutePath(nodePath);+ const finest = geo.levels[0];+ const arrayPath =+ !finest || finest.path === '.' ? basePath : toAbsolutePath(`${nodePath}/${finest.path}`);+ const arr =+ options.preopened ?? (await zarr.open(new zarr.Location(store, arrayPath), {kind: 'array'}));++ const dimensionNames = getZarrDimensionNames(arr);+ if (!dimensionNames) {+ throw new Error(+ `Zarr array "${arrayPath}" does not name every dimension. ` ++ 'Rendering requires zarr v3 `dimension_names` or an `_ARRAY_DIMENSIONS` attribute.'+ );+ }++ const nonSpatialDims: ZarrDimensionInfo[] = [];+ let timeDimension: ZarrDimensionInfo | undefined;+ for (let i = 0; i < dimensionNames.length; i++) {+ const name = dimensionNames[i];+ if (spatialDims.includes(name)) {+ continue;+ }+ // Coordinates live beside the array, which for a pyramid is inside the+ // finest level rather than next to the node the layer is handed.+ const {dimension, isCfTime} = await readCoordinateDimension(+ store,+ index,+ arrayPath,+ name,+ arr.shape[i],+ cache+ );+ nonSpatialDims.push(dimension);+ if (!timeDimension && isTimeDimension(dimension, isCfTime)) {+ timeDimension = dimension;+ }+ }++ const arrayAttrs = getAttrs(arr);+ const fillValue = arr.fillValue;++ const name = path.split('/').filter(Boolean).pop() || path || 'data';++ return {+ path,+ ...(options.nodePath !== undefined && {nodePath: options.nodePath}),+ name,+ // Qualified later, once every sibling variable is known.+ displayName: name,+ geoAttrs,+ spatialMetadata: {+ crs: geo.crs,+ axes: geo.axes,+ xAxisIndex: geo.xAxisIndex,+ yAxisIndex: geo.yAxisIndex,+ levels: geo.levels.map(level => ({+ path: level.path,+ shape: [level.arrayHeight, level.arrayWidth],+ chunks: arr.chunks.slice(-2)+ })),+ webMercatorPyramid: options.webMercatorPyramid ?? false+ },+ shape: [...arr.shape],+ chunks: [...arr.chunks],+ dtype: String(arr.dtype),+ nonSpatialDims,+ timeDimension,+ dataRange: readDataRange(arrayAttrs) ?? readDataRange(geoAttrs),+ nodataValue:+ readNumber(arrayAttrs, ['_FillValue', 'missing_value', 'nodata']) ??+ readNumber({fillValue}, ['fillValue'])+ };+}++/**+ * Build one variable per data array of an OME-NGFF style pyramid.+ *+ * Each level holds the same arrays at a lower resolution, so a variable's+ * identity is the group plus the array name while the node handed to the+ * renderer is the group itself. A level whose grid cannot be derived ends the+ * pyramid rather than discarding it, leaving the finer levels usable.+ */+async function buildPyramidVariables(+ store: ListableStore,+ index: StoreIndex,+ groupPath: string,+ levelPaths: string[],+ cache: CoordinateCache,+ webMercatorPyramid: boolean+): Promise<ZarrVariableInfo[]> {+ const {zarr} = await loadZarrRuntime();+ const base = normalizePath(groupPath);+ const resolve = (rest: string) => (base ? `${base}/${rest}` : rest);+ const names = multiscaleVariableNames(index, resolve(levelPaths[0]));+ const variables: ZarrVariableInfo[] = [];++ for (const name of names.slice(0, MAX_VARIABLE_CANDIDATES)) {+ const asset = (level: string) => (name ? `${level}/${name}` : level);+ const collected: {+ asset: string;+ transform: number[];+ shape: number[];+ arr: zarr.Array<zarr.DataType, zarr.Readable>;+ attrs: AnyAttrs;+ }[] = [];++ for (const level of levelPaths) {+ const levelPath = resolve(asset(level));+ if (isKnownMissing(index, levelPath, 'array')) {+ break;+ }+ let arr: zarr.Array<zarr.DataType, zarr.Readable>;+ try {+ arr = await zarr.open(new zarr.Location(store, toAbsolutePath(levelPath)), {kind: 'array'});+ } catch {+ throwIfAborted(store.signal);+ break;+ }+ const dimensionNames = getZarrDimensionNames(arr);+ const attrs = dimensionNames+ ? await deriveGeoZarrAttrs(store, index, levelPath, arr, dimensionNames, cache)+ : null;+ if (!attrs) {+ break;+ }+ collected.push({+ asset: asset(level),+ transform: attrs['spatial:transform'] as number[],+ shape: attrs['spatial:shape'] as number[],+ arr,+ attrs+ });+ }++ if (!collected.length) {+ continue;+ }+ const ordered = orderLevelsFinestFirst(collected);+ const finest = ordered[0];+ const variable = await buildVariableInfo(+ store,+ index,+ name ? resolve(name) : base,+ buildMultiscaleAttrs(+ finest.attrs,+ ordered.map(({asset: a, transform, shape}) => ({asset: a, transform, shape}))+ ),+ cache,+ {preopened: finest.arr, nodePath: base, webMercatorPyramid}+ );+ if (variable) {+ variables.push(variable);+ }+ }+ return variables;+}++function pathSuffix(path: string, depth: number): string {+ return path.split('/').filter(Boolean).slice(-depth).join('/');+}++/**+ * Stores often repeat a variable across scenario groups, e.g. `FUTUR/evap_total`+ * and `HISTO/evap_total`. Listing those by array name alone shows the same label+ * several times, so prepend the fewest leading path segments that tell them+ * apart. Names that are already unique are left alone.+ */+export function assignVariableDisplayNames<+ T extends {path: string; name: string; displayName: string}+>(variables: T[]): T[] {+ const byName = new Map<string, T[]>();+ for (const variable of variables) {+ const group = byName.get(variable.name);+ if (group) {+ group.push(variable);+ } else {+ byName.set(variable.name, [variable]);+ }+ }++ const labels = new Map<T, string>();+ for (const group of byName.values()) {+ if (group.length < 2) {+ continue;+ }+ const maxDepth = Math.max(+ ...group.map(variable => variable.path.split('/').filter(Boolean).length)+ );+ let depth = 2;+ let candidates = group.map(variable => pathSuffix(variable.path, depth));+ while (new Set(candidates).size < group.length && depth < maxDepth) {+ depth += 1;+ candidates = group.map(variable => pathSuffix(variable.path, depth));+ }+ group.forEach((variable, i) => labels.set(variable, candidates[i] || variable.name));+ }++ return variables.map(variable => {+ const label = labels.get(variable);+ return label ? {...variable, displayName: label} : variable;+ });+}++/**+ * Prefix matching everything below a matched node, so its resolution levels are+ * not offered as variables of their own. When the root matched, every remaining+ * path is one of its children.+ */+export function childPrefix(path: string): string {+ const normalized = normalizePath(path);+ return normalized ? `${normalized}/` : '';+}++async function listCandidatePaths(store: ListableStore): Promise<string[]> {+ if (typeof store.contents !== 'function') {+ return [''];+ }+ const contents = store.contents();+ const paths = contents+ .filter(entry => entry.kind === 'group' || entry.kind === 'array')+ .map(entry => entry.path.replace(/^\/+/, ''))+ // Shallow nodes first so a multiscale parent is matched before its levels.+ .sort((a, b) => a.split('/').length - b.split('/').length || a.localeCompare(b));+ return paths.length ? paths : [''];+}++/**+ * Discover every renderable variable in a store.+ *+ * Nodes that declare the GeoZarr `spatial` and `geo-proj` conventions are used+ * as-is. Very little published data does yet, so an array that does not declare+ * them is still accepted when its CF/GDAL metadata is enough to derive the same+ * information. Children of a matched node are skipped so resolution levels are+ * not offered as separate variables.+ */+export async function getZarrMetadata(+ url: string,+ options: {+ variable?: string;+ signal?: AbortSignal;+ onProgress?: (progress: ZarrMetadataProgress) => void;+ } = {}+): Promise<ZarrDatasetMetadata> {+ const {signal, onProgress} = options;+ throwIfAborted(signal);+ onProgress?.({phase: 'connecting', loadedBytes: 0});+ const {zarr, parseGeoZarrMetadata} = await loadZarrRuntime();+ throwIfAborted(signal);+ // Keep the signal out of the shared cache. All reads, including coordinate+ // chunks and range requests, go through this request-scoped fetch function.+ const store: ListableStore =+ signal || onProgress+ ? Object.assign(+ await withDetectedZarrMetadata(+ new zarr.FetchStore(url, {+ fetch: onProgress+ ? createMetadataFetch(signal, onProgress)+ : request => fetch(request, {signal})+ })+ ),+ {signal}+ )+ : await openZarrStore(url);+ throwIfAborted(signal);+ const index = buildStoreIndex(store);+ const paths = await listCandidatePaths(store);++ const variables: ZarrVariableInfo[] = [];+ const coordinateCache: CoordinateCache = {dimensions: new Map(), spatialAxes: new Map()};+ const matchedPrefixes: string[] = [];+ const errors: string[] = [];++ for (const path of paths.slice(0, MAX_VARIABLE_CANDIDATES)) {+ throwIfAborted(signal);+ if (matchedPrefixes.some(prefix => path.startsWith(prefix))) {+ continue;+ }+ let node: Awaited<ReturnType<typeof zarr.open>>;+ try {+ node = await zarr.open(new zarr.Location(store, toAbsolutePath(path)), {+ kind: index?.get(normalizePath(path))+ });+ } catch {+ throwIfAborted(signal);+ continue;+ }++ const declared = getAttrs(node);++ // A pyramid written in the OME-NGFF style has to be rewritten before the+ // GeoZarr parser can read it, and yields one variable per array in a level.+ const levelPaths = 'shape' in node ? null : parseOmeMultiscaleLevels(declared);+ if (levelPaths) {+ try {+ const pyramid = await buildPyramidVariables(+ store,+ index,+ path,+ levelPaths,+ coordinateCache,+ isWebMercatorPyramid(declared)+ );+ if (pyramid.length) {+ variables.push(...pyramid);+ matchedPrefixes.push(childPrefix(path));+ continue;+ }+ } catch (error) {+ throwIfAborted(signal);+ errors.push(error instanceof Error ? error.message : String(error));+ }+ }++ let geoAttrs: AnyAttrs | null = null;+ let preopened: zarr.Array<zarr.DataType, zarr.Readable> | undefined;+ try {+ parseGeoZarrMetadata(declared);+ geoAttrs = declared;+ } catch {+ // Not a declared GeoZarr node. Most nodes in a store are not, so fall+ // back to deriving the spatial metadata from a data array's own attrs.+ if ('shape' in node) {+ const arr = node as zarr.Array<zarr.DataType, zarr.Readable>;+ const dimensionNames = getZarrDimensionNames(arr);+ geoAttrs = dimensionNames+ ? await deriveGeoZarrAttrs(store, index, path, arr, dimensionNames, coordinateCache)+ : null;+ preopened = arr;+ }+ }+ if (!geoAttrs) {+ continue;+ }++ try {+ const variable = await buildVariableInfo(store, index, path, geoAttrs, coordinateCache, {+ preopened+ });+ if (variable) {+ variables.push(variable);+ matchedPrefixes.push(childPrefix(path));+ }+ } catch (error) {+ throwIfAborted(signal);+ errors.push(error instanceof Error ? error.message : String(error));+ }+ }++ throwIfAborted(signal);+ if (variables.length === 0) {+ if (errors.length) {+ throw new Error(errors[0]);+ }+ // Zarr over plain HTTP cannot be listed, so without consolidated metadata+ // only the node the URL points at is reachable.+ throw new Error(+ index+ ? 'No renderable variables found. The store must either declare the GeoZarr `spatial` ' ++ 'and `geo-proj` conventions, or expose a data array whose last two dimensions are ' ++ 'named y/x (or lat/lon) with coordinate arrays or a CF grid mapping.'+ : 'This store has no consolidated metadata, so its variables cannot be listed. Point ' ++ 'the URL directly at a data array, or use a store written with consolidated metadata.'+ );+ }++ const labeled = assignVariableDisplayNames(variables);+ const active =+ labeled.find(variable => variable.path === options.variable) ??+ (labeled[0] as ZarrVariableInfo);+ return selectZarrVariable(+ {+ url,+ axes: [],+ xAxisIndex: -1,+ yAxisIndex: -1,+ levels: [],+ variables: labeled,+ nonSpatialDims: []+ },+ active.path+ );+}diff --git a/src/types/layers.d.ts b/src/types/layers.d.tsindex 52cbdfda5..2e7762f39 100644--- a/src/types/layers.d.ts+++ b/src/types/layers.d.ts@@ -26,6 +26,10 @@ export type LayerBaseConfig = {animation: {enabled: boolean;domain?: [number, number] | null;+ /** Discrete instants the layer can render, for layers without continuous time. */+ timeSteps?: number[] | null;+ startTime?: number | null;+ duration?: number | null;};// for aggregate layer, aggregatedBins is returned for custom color scale@@ -318,6 +322,15 @@ export type VisConfigColorRange = VisConfig & {defaultValue: ColorRange;};+/**+ * A plain JSON value whose keys are not known until runtime. The layer renders+ * its own UI for it; the value is saved and restored with the rest of visConfig.+ */+export type VisConfigObject = VisConfig & {+ type: 'object';+ defaultValue: Record<string, any>;+};+export type LayerVisConfigTypes =| VisConfigBoolean| VisConfigNumber@@ -326,6 +339,7 @@ export type LayerVisConfigTypes =| VisConfigColorSelect| VisConfigInput| VisConfigSelect+ | VisConfigObject| VisConfigObjectSelection;export type LayerVisConfigSettings = {diff --git a/src/utils/src/application-config.ts b/src/utils/src/application-config.tsindex cb755348f..2ae91381e 100644--- a/src/utils/src/application-config.ts+++ b/src/utils/src/application-config.ts@@ -167,6 +167,11 @@ export type KeplerApplicationConfig = {// WMS layer is under development and not ready for production use. Disabled by default.enableWMSLayer?: boolean;+ // Zarr layer config -- Experimental+ // Enabled by default. Set false to hide Zarr in Add Data and layer type pickers.+ // Existing Zarr layers in saved maps can still render.+ enableZarrLayer?: boolean;+// Flow layer configenableFlowLayer?: boolean;@@ -454,6 +459,9 @@ const DEFAULT_APPLICATION_CONFIG: Required<KeplerApplicationConfig> = {// WMS layer configenableWMSLayer: true,+ // Zarr layer config -- experimental, disable via initApplicationConfig+ enableZarrLayer: true,+// Flow layer configenableFlowLayer: true,diff --git a/src/utils/src/export-map-html.ts b/src/utils/src/export-map-html.tsindex 9935d1c59..1318edcdf 100644--- a/src/utils/src/export-map-html.ts+++ b/src/utils/src/export-map-html.ts@@ -93,9 +93,7 @@ function normalizeAppIcon(value: unknown): string | null {}function normalizeAppNameColor(value: unknown): string {- return typeof value === 'string' && /^#[\da-f]{6}$/i.test(value)- ? value- : DEFAULT_APP_NAME_COLOR;+ return typeof value === 'string' && /^#[\da-f]{6}$/i.test(value) ? value : DEFAULT_APP_NAME_COLOR;}/**@@ -618,7 +616,7 @@ export const exportMapToHTML = (options, version = KEPLER_GL_VERSION) => {{style: {position: 'absolute', left: 0, width: '100vw', height: '100vh'}},${options.mode === EXPORT_HTML_MAP_MODES.READ- ? "react.createElement(BrandLogo, {fixed: true}),"+ ? 'react.createElement(BrandLogo, {fixed: true}),': ''}react.createElement(KeplerGlComponent, {diff --git a/src/utils/src/extract-dataset-utils.ts b/src/utils/src/extract-dataset-utils.tsindex 1c1f96e68..3a57f49fe 100644--- a/src/utils/src/extract-dataset-utils.ts+++ b/src/utils/src/extract-dataset-utils.ts@@ -17,7 +17,8 @@ const NON_EXTRACTABLE_DATASET_TYPES = new Set<string>([DatasetType.RASTER_TILE,DatasetType.WMS_TILE,DatasetType.TILE_3D,- DatasetType.BITMAP+ DatasetType.BITMAP,+ DatasetType.ZARR]);const VECTOR_TILE_ID_FIELDS = [diff --git a/test/browser/components/common/animation-control-test.js b/test/browser/components/common/animation-control-test.jsindex d97dc40ca..620641d95 100644--- a/test/browser/components/common/animation-control-test.js+++ b/test/browser/components/common/animation-control-test.js@@ -336,10 +336,7 @@ test('Components -> FilterAnimationController -> numeric incremental bins stay iconst AnimationController = AnimationControllerFactory();const FilterAnimationController = FilterAnimationControllerFactory(AnimationController);let visState = reducer(StateWFilters.visState, setFilter(0, 'name', 'gps_data.lat'));- visState = reducer(- visState,- setFilterPlot(0, {plotType: {numericInterval: 0.01}})- );+ visState = reducer(visState, setFilterPlot(0, {plotType: {numericInterval: 0.01}}));visState = reducer(visState,setFilterAnimationWindow({diff --git a/test/browser/components/side-panel/layer-configurator-test.js b/test/browser/components/side-panel/layer-configurator-test.jsindex 0495c7075..167f9fcf1 100644--- a/test/browser/components/side-panel/layer-configurator-test.js+++ b/test/browser/components/side-panel/layer-configurator-test.js@@ -6,6 +6,8 @@import React from 'react';import test from 'tape';import sinon from 'sinon';+import {fireEvent} from '@testing-library/react';+import {renderWithTheme} from 'test/helpers/component-jest-utils';import {LayerConfiguratorFactory,@@ -21,6 +23,7 @@ import {getLayerFields,getLayerDataset} from '@kepler.gl/components';+import {LayerClasses} from '@kepler.gl/layers';import {StateWFiles, StateWTripGeojson, testCsvDataId} from 'test/helpers/mock-state';import {@@ -442,3 +445,161 @@ test('Components -> LayerConfigurator -> getLayerDataset', t => {t.end();});++const ZARR_DATASET = {+ id: 'zarr_data',+ type: 'zarr',+ label: 'Zarr Dataset',+ color: [143, 47, 191],+ fields: [],+ metadata: {+ url: 'https://example.com/store.zarr',+ variable: 'FUTUR/qtot',+ crs: {code: 'EPSG:4326'},+ axes: ['lat', 'lon'],+ xAxisIndex: 1,+ yAxisIndex: 0,+ levels: [{path: '.', shape: [360, 720], chunks: [360, 720]}],+ // Same array name under two scenario groups, so the picker has to show the+ // qualified display name to tell them apart.+ variables: [+ {+ path: 'FUTUR/qtot',+ name: 'qtot',+ displayName: 'FUTUR/qtot',+ shape: [3, 360, 720],+ chunks: [1, 360, 720],+ dtype: 'float32',+ nonSpatialDims: [{name: 'season', size: 3, values: [0.5, 1.5, 2.5]}]+ },+ {+ path: 'HISTO/qtot',+ name: 'qtot',+ displayName: 'HISTO/qtot',+ shape: [3, 360, 720],+ chunks: [1, 360, 720],+ dtype: 'float32',+ nonSpatialDims: [{name: 'season', size: 3, values: [0.5, 1.5, 2.5]}]+ }+ ],+ nonSpatialDims: [{name: 'season', size: 3, values: [0.5, 1.5, 2.5]}]+ }+};++function mountZarrConfigurator(layer, updateLayerVisConfigSpy) {+ return mountWithTheme(+ <IntlWrapper>+ <LayerConfigurator+ {...defaultProps}+ layer={layer}+ datasets={{zarr_data: ZARR_DATASET}}+ updateLayerVisConfig={updateLayerVisConfigSpy}+ />+ </IntlWrapper>+ );+}++test('Components -> LayerConfigurator -> automatic Zarr range remains editable', t => {+ const layer = new LayerClasses.zarr({id: 'zarr-layer', dataId: 'zarr_data'});+ const updateLayerVisConfigSpy = sinon.spy();+ const {container, unmount} = renderWithTheme(+ <IntlWrapper>+ <LayerConfigurator+ {...defaultProps}+ layer={layer}+ datasets={{zarr_data: ZARR_DATASET}}+ updateLayerVisConfig={updateLayerVisConfigSpy}+ />+ </IntlWrapper>+ );+ try {+ const [minimum, maximum] = container.querySelectorAll('.kg-range-slider__input');+ t.equal(minimum.value, '0', 'shows the fallback lower bound while automatic');+ t.equal(maximum.value, '1', 'shows the fallback upper bound while automatic');+ t.equal(+ layer.config.visConfig.rescale,+ null,+ 'displaying fallback bounds does not select them'+ );+ fireEvent.change(minimum, {target: {value: '0.25'}});+ fireEvent.blur(minimum);+ t.deepEqual(+ updateLayerVisConfigSpy.lastCall.args[0],+ {rescale: [0.25, 1]},+ 'editing the slider selects an explicit color range'+ );+ } finally {+ unmount();+ t.end();+ }+});++test('Components -> LayerConfigurator -> zarr variable selector shows the active variable', t => {+ const ZarrLayer = LayerClasses.zarr;+ const layer = new ZarrLayer({id: 'zarr-layer', dataId: 'zarr_data'});++ let wrapper;+ t.doesNotThrow(() => {+ wrapper = mountZarrConfigurator(layer, () => {});+ }, 'should render the zarr layer config');++ // Regression: selectedItems used to be the variable path string, which the+ // display accessor could not read, so the dropdown rendered no selection.+ const value = wrapper+ .find('.zarr-variable-selector')+ .find('.item-selector__dropdown__value')+ .at(0);+ t.equal(+ value.text(),+ 'FUTUR/qtot',+ 'should display the dataset variable as the current selection'+ );++ t.end();+});++test('Components -> LayerConfigurator -> zarr dimension selector shows the pinned index', t => {+ const ZarrLayer = LayerClasses.zarr;+ const layer = new ZarrLayer({id: 'zarr-layer', dataId: 'zarr_data'});+ layer.updateLayerVisConfig({dimensionIndexes: {season: 2}});++ const wrapper = mountZarrConfigurator(layer, () => {});+ const value = wrapper+ .find('.zarr-dimension-selector')+ .find('.item-selector__dropdown__value')+ .at(0);++ // Labeled by coordinate value rather than raw index.+ t.equal(value.text(), '2.5', 'should display the pinned coordinate value');++ t.end();+});++test('Components -> LayerConfigurator -> zarr variable selector changes the variable and resets its frame', t => {+ const ZarrLayer = LayerClasses.zarr;+ const layer = new ZarrLayer({id: 'zarr-layer', dataId: 'zarr_data'});+ layer.updateLayerVisConfig({zarrFrame: 2});+ const updateLayerVisConfig = sinon.spy();++ const wrapper = mountZarrConfigurator(layer, updateLayerVisConfig);++ const variableSelector = () => wrapper.find('.zarr-variable-selector').at(0);++ clickItemSelector(variableSelector());+ wrapper.update();+ t.deepEqual(+ getItemSelectorListText(variableSelector(), 1),+ 'HISTO/qtot',+ 'should list variables by their qualified display name'+ );+ clickItemSelectList(variableSelector(), 1);++ t.ok(updateLayerVisConfig.calledOnce, 'should call updateLayerVisConfig once');+ t.deepEqual(+ updateLayerVisConfig.firstCall.args[0],+ {zarrVariable: 'HISTO/qtot', zarrFrame: 0},+ 'should emit the selected variable path and start at its first frame'+ );++ t.end();+});diff --git a/test/browser/components/side-panel/layer-list.spec.js b/test/browser/components/side-panel/layer-list.spec.jsindex 2dc39ff05..2b1fa9879 100644--- a/test/browser/components/side-panel/layer-list.spec.js+++ b/test/browser/components/side-panel/layer-list.spec.js@@ -272,8 +272,7 @@ describe('Components -> SidePanel -> LayerPanel -> LayerList', () => {});it('keeps confirmed group and child-layer deletion isolated between map instances', () => {- const {container, store, firstMapVisState, secondMapVisState} =- renderLayerListForInstances();+ const {container, store, firstMapVisState, secondMapVisState} = renderLayerListForInstances();fireEvent.click(container.querySelector('.layer-group__delete svg'));@@ -292,8 +291,9 @@ describe('Components -> SidePanel -> LayerPanel -> LayerList', () => {});it('keeps immediate empty-group deletion isolated between map instances', () => {- const {container, store, firstMapVisState, secondMapVisState} =- renderLayerListForInstances({emptySharedGroup: true});+ const {container, store, firstMapVisState, secondMapVisState} = renderLayerListForInstances({+ emptySharedGroup: true+ });fireEvent.click(container.querySelector('.layer-group__delete svg'));diff --git a/test/browser/layer-tests/index.js b/test/browser/layer-tests/index.jsindex 812504e14..22a067e30 100644--- a/test/browser/layer-tests/index.js+++ b/test/browser/layer-tests/index.js@@ -21,6 +21,7 @@ import './a5-layer-specs';import './geohash-layer-specs';import './flow-field-layer-specs';import './wms-layer-specs';+import './zarr-layer-specs';import './vector-tile-layer-specs';import './flow-layer-specs';import './aggregation-layer-geojson-specs';diff --git a/test/browser/layer-tests/zarr-layer-specs.js b/test/browser/layer-tests/zarr-layer-specs.jsnew file mode 100644index 000000000..7f71a0639--- /dev/null+++ b/test/browser/layer-tests/zarr-layer-specs.js@@ -0,0 +1,1257 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import test from 'tape-catch';+import {+ KeplerGlLayers,+ findNearestTimeIndex,+ getZarrMaxZoom,+ getZarrSelection,+ getZarrSublayerId,+ getZarrTileByteLength+} from '@kepler.gl/layers';+import {DatasetType} from '@kepler.gl/constants';+import {createNewDataEntry, getZarrAxis, getZarrMetadata} from '@kepler.gl/table';+import SchemaManager from '@kepler.gl/schemas';+import {InitialState} from 'test/helpers/mock-state';+import {+ duplicateLayerUpdater,+ layerVisConfigChangeUpdater,+ validateLayerWithData+} from '@kepler.gl/reducers';++const {ZarrLayer} = KeplerGlLayers;++const DAY = 24 * 60 * 60 * 1000;+const T0 = Date.UTC(2020, 0, 27);++const TIME_DIMENSION = {+ name: 'time',+ size: 3,+ values: [T0, T0 + DAY, T0 + 2 * DAY]+};++const BAND_DIMENSION = {name: 'band', size: 4};++const TEMPERATURE = {+ path: 'temperature',+ name: 'temperature',+ shape: [3, 4, 256, 256],+ chunks: [1, 1, 256, 256],+ dtype: 'float32',+ nonSpatialDims: [TIME_DIMENSION, BAND_DIMENSION],+ timeDimension: TIME_DIMENSION,+ dataRange: [250, 320],+ nodataValue: -9999+};++const PRECIPITATION = {+ path: 'precipitation',+ name: 'precipitation',+ shape: [256, 256],+ chunks: [256, 256],+ dtype: 'float32',+ nonSpatialDims: []+};++const MOCK_ZARR_DATASET = {+ id: 'zarr-dataset',+ type: DatasetType.ZARR,+ label: 'Test Zarr Dataset',+ fields: [],+ metadata: {+ url: 'https://example.com/store.zarr',+ variable: 'temperature',+ crs: {code: 'EPSG:4326'},+ axes: ['time', 'band', 'y', 'x'],+ xAxisIndex: 3,+ yAxisIndex: 2,+ levels: [{path: '0', shape: [3, 4, 256, 256], chunks: [1, 1, 256, 256]}],+ variables: [TEMPERATURE, PRECIPITATION],+ nonSpatialDims: [TIME_DIMENSION, BAND_DIMENSION],+ timeDimension: TIME_DIMENSION,+ dataRange: TEMPERATURE.dataRange+ }+};++test('#ZarrLayer -> constructor and basic properties', t => {+ const layer = new ZarrLayer({dataId: 'zarr-dataset'});++ t.equal(layer.type, 'zarr', 'should be a zarr layer');+ t.equal(layer.name, 'Zarr', 'should have a display name');+ t.equal(layer.requireData, false, 'should render without rows');+ t.deepEqual(layer.requiredLayerColumns, [], 'should require no columns');+ t.deepEqual(layer.supportedDatasetTypes, [DatasetType.ZARR], 'should only accept zarr datasets');+ t.deepEqual(layer.visualChannels, {}, 'should have no visual channels');+ t.deepEqual(layer.config.visConfig.dimensionIndexes, {}, 'should start with no pinned indexes');+ t.equal(layer.config.visConfig.zarrVariable, null, 'should follow the dataset variable');++ t.end();+});++test('#ZarrLayer -> findDefaultLayerProps', t => {+ const {props} = ZarrLayer.findDefaultLayerProps(MOCK_ZARR_DATASET);++ t.equal(props.length, 1, 'should return one layer prop');+ t.equal(props[0].label, 'Test Zarr Dataset', 'should use the dataset label');+ t.equal(props[0].isVisible, true, 'should be visible by default');+ t.deepEqual(+ props[0].visConfig.rescale,+ [250, 320],+ 'should seed the rescale from the advertised data range'+ );++ const nonZarr = ZarrLayer.findDefaultLayerProps({type: 'csv'});+ t.deepEqual(nonZarr.props, [], 'should return no props for a non-zarr dataset');++ t.end();+});++test('#ZarrLayer -> constructor keeps the visConfig it was built with', t => {+ const {props} = ZarrLayer.findDefaultLayerProps(MOCK_ZARR_DATASET);+ const layer = new ZarrLayer({dataId: 'zarr-dataset', ...props[0]});++ t.deepEqual(+ layer.config.visConfig.rescale,+ [250, 320],+ 'should keep the advertised range instead of the 0-1 placeholder'+ );++ const restored = new ZarrLayer({+ dataId: 'zarr-dataset',+ visConfig: {zarrVariable: 'precipitation', rescale: [0, 50]}+ });+ t.equal(+ restored.config.visConfig.zarrVariable,+ 'precipitation',+ 'should restore a saved variable'+ );+ t.deepEqual(restored.config.visConfig.rescale, [0, 50], 'should restore a saved rescale');++ t.end();+});++test('#ZarrLayer -> updateLayerMeta points the rescale control at the variable', t => {+ const layer = new ZarrLayer({dataId: 'zarr-dataset'});+ layer.updateLayerMeta(MOCK_ZARR_DATASET);++ t.deepEqual(+ layer.config.visConfig.rescale,+ [250, 320],+ 'should replace the placeholder with the variable range'+ );+ t.deepEqual(+ layer.visConfigSettings.rescale.range,+ [250, 320],+ 'should let the slider reach the data'+ );++ layer.updateLayerVisConfig({rescale: [260, 300]});+ layer.updateLayerMeta(MOCK_ZARR_DATASET);+ t.deepEqual(+ layer.config.visConfig.rescale,+ [260, 300],+ 'should leave a range chosen for the same variable alone'+ );++ // `precipitation` advertises no range, so the first tile has to supply one.+ layer.updateLayerVisConfig({zarrVariable: 'precipitation'});+ layer.updateLayerMeta(MOCK_ZARR_DATASET);+ t.deepEqual(+ layer.config.visConfig.rescale,+ null,+ 'should not keep the previous variable range after a switch'+ );+ t.deepEqual(+ layer.visConfigSettings.rescale.range,+ [0, 1],+ 'should not use the dataset default variable statistics as slider bounds'+ );++ layer.updateLayerVisConfig({rescale: [0, 50]});+ layer.updateLayerMeta(MOCK_ZARR_DATASET);+ t.deepEqual(layer.config.visConfig.rescale, [0, 50], 'keeps a custom range for the new variable');+ layer.updateLayerVisConfig({zarrVariable: 'temperature'});+ layer.updateLayerMeta(MOCK_ZARR_DATASET);+ t.deepEqual(+ layer.config.visConfig.rescale,+ [250, 320],+ 'restores the selected variable statistics'+ );++ t.end();+});++function renderTileColors(deckLayer, values) {+ const originalImageData = globalThis.ImageData;+ // jsdom does not implement ImageData; retain the pixels produced by the real colormap.+ globalThis.ImageData = class {+ constructor(data) {+ this.data = data;+ }+ };+ try {+ return Array.from(+ deckLayer.props.renderTile({values, width: values.length, height: 1}).image.data+ );+ } finally {+ globalThis.ImageData = originalImageData;+ }+}++test('#ZarrLayer -> advertised and explicit 0-1 ranges are not sampled', async t => {+ const values = new Float32Array([0.25, 0.75]);+ const expectedColors = [64, 64, 64, 255, 191, 191, 191, 255];+ for (const mode of ['advertised', 'saved', 'selected', 'automatic', 'invalid']) {+ const variable = {+ ...TEMPERATURE,+ dataRange: mode === 'advertised' ? [0, 1] : mode === 'saved' ? [250, 320] : undefined+ };+ const dataset = {+ ...MOCK_ZARR_DATASET,+ metadata: {...MOCK_ZARR_DATASET.metadata, variables: [variable]}+ };+ const layer = new ZarrLayer({+ dataId: dataset.id,+ visConfig: {+ colorRange: {colors: ['#000000', '#ffffff']},+ ...(mode === 'saved' ? {rescale: [0, 1]} : {}),+ ...(mode === 'invalid' ? {rescale: [NaN, Infinity]} : {})+ }+ });+ layer.updateLayerMeta(dataset);+ if (mode === 'selected') {+ layer.updateLayerVisConfig({rescale: [0, 1]});+ layer.updateLayerMeta(dataset);+ }+ const runtime = await layer._loadRuntime();+ layer._loadRuntime = async () => ({...runtime, get: async () => ({data: values})});+ layer._nodeKey = `${dataset.metadata.url}#${variable.path}`;+ layer._node = {};+ const [deckLayer] = layer.renderLayer({+ data: {metadata: dataset.metadata, variable},+ mapState: {},+ visible: true+ });+ const tile = await deckLayer.props.getTileData(layer._node, {+ sliceSpec: [],+ width: 2,+ height: 1+ });+ const automatic = mode === 'automatic' || mode === 'invalid';+ t.deepEqual(+ renderTileColors(deckLayer, tile.values),+ automatic ? [0, 0, 0, 255, 255, 255, 255, 255] : expectedColors,+ `${mode}: uses the configured range or samples only when no usable range exists`+ );+ t.deepEqual(+ layer.config.visConfig.rescale,+ automatic ? null : [0, 1],+ `${mode}: keeps range intent`+ );+ }+ t.end();+});++test('#ZarrLayer -> recolors cached tiles when a later tile supplies the automatic range', async t => {+ const variable = {...TEMPERATURE, dataRange: undefined};+ const dataset = {+ ...MOCK_ZARR_DATASET,+ metadata: {...MOCK_ZARR_DATASET.metadata, variables: [variable]}+ };+ const layer = new ZarrLayer({+ dataId: dataset.id,+ visConfig: {colorRange: {colors: ['#000000', '#ffffff']}}+ });+ layer.updateLayerMeta(dataset);+ const runtime = await layer._loadRuntime();+ const chunks = [new Float32Array([-10, -10]), new Float32Array([-20, 0])];+ layer._loadRuntime = async () => ({...runtime, get: async () => ({data: chunks.shift()})});+ layer._nodeKey = `${dataset.metadata.url}#${variable.path}`;+ layer._node = {};+ let redraws = 0;+ const render = () =>+ layer.renderLayer({+ data: {metadata: dataset.metadata, variable},+ mapState: {},+ visible: true,+ layerCallbacks: {onRedrawNeeded: () => redraws++}+ })[0];+ const initial = render();+ const load = () => initial.props.getTileData(layer._node, {sliceSpec: [], width: 2, height: 1});+ const first = await load();+ t.deepEqual(+ renderTileColors(initial, first.values),+ [0, 0, 0, 255, 0, 0, 0, 255],+ 'a constant first tile uses the provisional range'+ );+ t.equal(redraws, 0, 'a constant tile cannot supply an automatic range');+ await load();+ t.equal(redraws, 1, 'the first usable range requests a redraw of already loaded tiles');+ const updated = render();+ t.notDeepEqual(+ updated.props.updateTriggers.renderTile,+ initial.props.updateTriggers.renderTile,+ 'the sampled range invalidates cached tile colors'+ );+ t.deepEqual(+ renderTileColors(updated, first.values),+ [128, 128, 128, 255, 128, 128, 128, 255],+ 'the cached first tile now uses the same range as its neighbors'+ );+ t.equal(updated.id, initial.id, 'keeps the decoded tile cache');+ t.equal(updated.props.getTileData, initial.props.getTileData, 'does not refetch the tiles');+ t.deepEqual(+ render().props.updateTriggers.renderTile,+ updated.props.updateTriggers.renderTile,+ 'subsequent renders keep the color cache stable'+ );+ t.end();+});++test('#ZarrLayer -> stale tile requests cannot set another source opening color range', async t => {+ const originalFetch = globalThis.fetch;+ const url = 'https://example.com/range-race.zarr';+ const variables = ['a', 'b'].map(path => ({...PRECIPITATION, path}));+ const metadata = {...MOCK_ZARR_DATASET.metadata, url, variable: 'a', variables};+ const dataset = {...MOCK_ZARR_DATASET, metadata};+ const array = {+ zarr_format: 2,+ shape: [1, 2],+ chunks: [1, 2],+ dtype: '<f8',+ compressor: null,+ fill_value: null,+ order: 'C',+ filters: null+ };+ globalThis.fetch = async request =>+ request.url.endsWith('/.zmetadata')+ ? new Response(+ JSON.stringify({+ zarr_consolidated_format: 1,+ metadata: {+ '.zgroup': {zarr_format: 2},+ 'a/.zarray': array,+ 'a/.zattrs': {},+ 'b/.zarray': array,+ 'b/.zattrs': {}+ }+ })+ )+ : new Response(null, {status: 404});+ try {+ const layer = new ZarrLayer({+ dataId: dataset.id,+ visConfig: {colorRange: {colors: ['#000000', '#ffffff']}}+ });+ const runtime = await layer._loadRuntime();+ const pending = [];+ layer._loadRuntime = async () => ({+ ...runtime,+ get: () => new Promise(resolve => pending.push(resolve))+ });+ const render = async path => {+ layer.updateLayerVisConfig({zarrVariable: path});+ const data = layer.formatLayerData({[dataset.id]: dataset});+ const options = {data, mapState: {}, visible: true};+ await new Promise(resolve => {+ const layers = layer.renderLayer({+ ...options,+ layerCallbacks: {onRedrawNeeded: resolve}+ });+ if (layers.length) resolve();+ });+ return layer.renderLayer(options)[0];+ };+ const load = deckLayer =>+ deckLayer.props.getTileData(deckLayer.props.node, {+ sliceSpec: [null, null],+ width: 2,+ height: 1+ });+ const firstA = await render('a');+ const staleA = load(firstA);+ await Promise.resolve();+ const b = await render('b');+ pending.shift()({data: new Float64Array([100, 200])});+ await staleA;+ const freshB = load(b);+ await Promise.resolve();+ pending.shift()({data: new Float64Array([1, 2])});+ await freshB;+ t.deepEqual(+ renderTileColors(b, [1, 2]),+ [0, 0, 0, 255, 255, 255, 255, 255],+ 'B samples its own tiles after A finishes late'+ );++ const secondA = await render('a');+ const staleSecondA = load(secondA);+ await Promise.resolve();+ await render('b');+ const thirdA = await render('a');+ pending.shift()({data: new Float64Array([100, 200])});+ await staleSecondA;+ // An old deck layer may also invoke its callback after the switch.+ const lateInvocation = load(firstA);+ await Promise.resolve();+ pending.shift()({data: new Float64Array([100, 200])});+ await lateInvocation;+ const freshA = load(thirdA);+ await Promise.resolve();+ pending.shift()({data: new Float64Array([3, 4])});+ await freshA;+ t.deepEqual(+ renderTileColors(thirdA, [3, 4]),+ [0, 0, 0, 255, 255, 255, 255, 255],+ 'A samples the current opening after A -> B -> A, ignoring old callbacks'+ );+ } finally {+ globalThis.fetch = originalFetch;+ t.end();+ }+});++test('#ZarrLayer -> updateLayerMeta populates the animation domain', t => {+ const layer = new ZarrLayer({dataId: 'zarr-dataset'});+ layer.updateLayerMeta(MOCK_ZARR_DATASET);++ const {animation} = layer.config;+ t.equal(animation.enabled, true, 'should enable animation for a time dimension');+ t.deepEqual(animation.domain, [T0, T0 + 2 * DAY], 'should span the time coordinate');+ t.deepEqual(animation.timeSteps, TIME_DIMENSION.values, 'should expose the discrete instants');+ t.equal(animation.startTime, T0, 'should start at the first instant');+ t.equal(layer.meta.crs, 'EPSG:4326', 'should record the store crs');++ t.end();+});++test('#ZarrLayer -> updateLayerMeta disables animation without a time dimension', t => {+ const layer = new ZarrLayer({dataId: 'zarr-dataset'});+ layer.updateLayerVisConfig({zarrVariable: 'precipitation'});+ layer.updateLayerMeta(MOCK_ZARR_DATASET);++ t.equal(layer.config.animation.enabled, false, 'should leave animation off');+ t.equal(layer.config.animation.domain, null, 'should clear the domain');++ t.end();+});++test('#ZarrLayer -> formatLayerData resolves the layer variable', t => {+ const datasets = {'zarr-dataset': MOCK_ZARR_DATASET};++ const layer = new ZarrLayer({dataId: 'zarr-dataset'});+ t.equal(+ layer.formatLayerData(datasets).variable.path,+ 'temperature',+ 'should default to the dataset variable'+ );++ const second = new ZarrLayer({dataId: 'zarr-dataset'});+ second.updateLayerVisConfig({zarrVariable: 'precipitation'});+ t.equal(+ second.formatLayerData(datasets).variable.path,+ 'precipitation',+ 'should honor the layer variable override'+ );++ t.deepEqual(+ new ZarrLayer({dataId: 'missing'}).formatLayerData(datasets),+ {metadata: null, variable: null},+ 'should return empty data for an unknown dataset'+ );++ t.end();+});++test('#ZarrLayer -> findNearestTimeIndex', t => {+ const steps = TIME_DIMENSION.values;++ t.equal(findNearestTimeIndex(steps, T0), 0, 'should match the first instant');+ t.equal(findNearestTimeIndex(steps, T0 + 2 * DAY), 2, 'should match the last instant');+ t.equal(findNearestTimeIndex(steps, T0 + 0.4 * DAY), 0, 'should round down to the nearest');+ t.equal(findNearestTimeIndex(steps, T0 + 0.6 * DAY), 1, 'should round up to the nearest');+ t.equal(findNearestTimeIndex(steps, T0 - 10 * DAY), 0, 'should clamp below the domain');+ t.equal(findNearestTimeIndex(steps, T0 + 99 * DAY), 2, 'should clamp above the domain');+ t.equal(findNearestTimeIndex([], T0), 0, 'should fall back to index 0 without steps');++ t.end();+});++test('#ZarrLayer -> getZarrTileByteLength', t => {+ // deck caps its tile cache by reported bytes, so a fixed four bytes per pixel+ // would halve a float64 tile and quadruple an int8 one.+ t.equal(+ getZarrTileByteLength(new Float64Array(16), 4, 4),+ 128,+ 'should report the full size of a 64-bit tile'+ );+ t.equal(+ getZarrTileByteLength(new Int8Array(16), 4, 4),+ 16,+ 'should report the smaller size of an 8-bit tile'+ );+ t.equal(+ getZarrTileByteLength(new BigInt64Array(16), 4, 4),+ 128,+ 'should report the full size of a BigInt tile'+ );+ t.equal(+ getZarrTileByteLength([1, 2, 3, 4], 2, 2),+ 16,+ 'should fall back to four bytes per pixel for a plain array'+ );++ t.end();+});++test('#ZarrLayer -> getZarrSelection', t => {+ t.deepEqual(+ getZarrSelection({variable: TEMPERATURE}),+ {time: 0, band: 0},+ 'should default every non-spatial dimension to index 0'+ );++ t.deepEqual(+ getZarrSelection({variable: TEMPERATURE, currentTime: T0 + 2 * DAY}),+ {time: 2, band: 0},+ 'should map the animation time onto the time index'+ );++ t.deepEqual(+ getZarrSelection({variable: TEMPERATURE, dimensionIndexes: {band: 2}}),+ {time: 0, band: 2},+ 'should pin non-time dimensions from the config'+ );++ t.deepEqual(+ getZarrSelection({variable: TEMPERATURE, dimensionIndexes: {band: 99}}),+ {time: 0, band: 3},+ 'should clamp a pinned index to the dimension size'+ );++ t.deepEqual(+ getZarrSelection({variable: PRECIPITATION, currentTime: T0}),+ {},+ 'should be empty when the variable is purely spatial'+ );++ t.deepEqual(getZarrSelection({variable: null}), {}, 'should be empty without a variable');++ t.end();+});++test('#ZarrLayer -> getZarrSublayerId', t => {+ t.equal(+ getZarrSublayerId('layer-1', {}),+ 'layer-1-ZarrLayer',+ 'should leave a purely spatial variable with a plain id'+ );++ t.equal(+ getZarrSublayerId('layer-1', {band: 2, time: 1}),+ getZarrSublayerId('layer-1', {time: 1, band: 2}),+ 'should not depend on key order'+ );++ t.notEqual(+ getZarrSublayerId('layer-1', {time: 1, band: 2}),+ getZarrSublayerId('layer-1', {time: 1, band: 3}),+ 'should change when a pinned index changes'+ );++ t.end();+});++test('#ZarrLayer -> renderLayer reloads tiles when a dimension changes', async t => {+ const layer = new ZarrLayer({dataId: 'zarr-dataset'});+ // The store opens asynchronously; stand in for an opened node so renderLayer+ // gets as far as building the deck sublayer.+ await layer._loadRuntime();+ layer._nodeKey = `${MOCK_ZARR_DATASET.metadata.url}#temperature`;+ layer._node = {shape: [3, 4, 256, 256]};++ const render = () =>+ layer.renderLayer({+ data: {metadata: MOCK_ZARR_DATASET.metadata, variable: TEMPERATURE},+ mapState: {},+ idx: 0,+ gpuFilter: null,+ layerCallbacks: {},+ visible: true+ });++ const [first] = render();+ t.deepEqual(first.props.selection, {time: 0, band: 0}, 'should select the first slice');++ layer.updateLayerVisConfig({dimensionIndexes: {band: 2}});+ const [second] = render();++ t.deepEqual(second.props.selection, {time: 0, band: 2}, 'should select the pinned slice');+ // deck.gl caches tile data per layer, so only a new id refetches the chunks.+ t.notEqual(second.id, first.id, 'should render under a new sublayer id');++ t.end();+});++test('#ZarrLayer -> renderLayer forwards default and custom map parameters to every slice', async t => {+ const layer = new ZarrLayer({dataId: 'zarr-dataset'});+ await layer._loadRuntime();+ layer._nodeKey = `${MOCK_ZARR_DATASET.metadata.url}#temperature`;+ layer._node = {shape: TEMPERATURE.shape};+ const render = mapState =>+ layer.renderLayer({+ data: {metadata: MOCK_ZARR_DATASET.metadata, variable: TEMPERATURE},+ mapState,+ idx: 0,+ gpuFilter: null,+ layerCallbacks: {},+ visible: true+ });++ const [first] = render({});+ t.deepEqual(+ first.props.parameters,+ {depthTest: true, depthMask: false},+ 'uses the common 2D depth defaults'+ );+ t.deepEqual(+ render({dragRotate: true})[0].props.parameters,+ {depthTest: true, depthMask: true},+ 'uses the common 3D depth defaults'+ );+ first.props.onViewportLoad();+ layer.updateLayerVisConfig({dimensionIndexes: {band: 2}});++ const parameters = {depthTest: false, depthMask: true, blend: false};+ const slices = render({layerParameters: parameters});+ t.equal(slices.length, 2, 'renders the loaded backdrop and the new slice');+ for (const slice of slices) {+ t.deepEqual(+ slice.props.parameters,+ parameters,+ 'honors map depth and blending overrides on each slice'+ );+ }+ t.end();+});++test('#ZarrLayer -> explicit axes fetch source slices independently of the shared clock', async t => {+ const band = {...BAND_DIMENSION, values: ['tavg', 'prec', 'tavg', 'snow'], kind: 'category'};+ const variable = {...TEMPERATURE, nonSpatialDims: [TIME_DIMENSION, band]};+ const layer = new ZarrLayer({+ dataId: 'zarr-dataset',+ visConfig: {+ zarrAxis: {kind: 'dimension', dimension: 'band'},+ dimensionIndexes: {time: 1}+ }+ });+ await layer._loadRuntime();+ layer._nodeKey = `${MOCK_ZARR_DATASET.metadata.url}#temperature`;+ layer._node = {shape: variable.shape};+ layer.updateLayerMeta(MOCK_ZARR_DATASET);+ t.equal(+ layer.config.animation.enabled,+ false,+ 'does not contribute categorical positions to the global time domain'+ );+ const render = () =>+ layer.renderLayer({+ data: {metadata: MOCK_ZARR_DATASET.metadata, variable},+ animationConfig: {currentTime: T0 + 2 * DAY},+ mapState: {},+ idx: 0,+ gpuFilter: null,+ layerCallbacks: {},+ visible: true+ })[0];+ const first = render();+ layer.updateLayerVisConfig({zarrFrame: 2});+ const next = render();+ t.deepEqual(+ next.props.selection,+ {time: 1, band: 2},+ 'duplicate labels keep their distinct array indices and pinned time'+ );+ t.notEqual(next.id, first.id, 'a frame change fetches a different tile slice');+ t.equal(+ render().props.selection,+ next.props.selection,+ 'unchanged frames reuse cached selection'+ );+ layer.updateLayerVisConfig({zarrFrame: 100});+ t.deepEqual(+ render().props.selection,+ {time: 1, band: 3},+ 'out of range saved frames clamp safely'+ );+ layer.updateLayerVisConfig({zarrFrame: NaN});+ t.deepEqual(render().props.selection, {time: 1, band: 0}, 'invalid frames use the first slice');+ t.end();+});++test('#ZarrLayer -> a month axis retains year, day and band pins', t => {+ const variable = {+ ...TEMPERATURE,+ nonSpatialDims: [+ {name: 'year', size: 2, values: [2023, 2024]},+ {name: 'month', size: 2, values: [1, 2]},+ {name: 'day', size: 2, values: [28, 29]},+ BAND_DIMENSION+ ],+ timeDimension: undefined+ };+ const axis = getZarrAxis(variable, {kind: 'dimension', dimension: 'month'});+ t.deepEqual(+ getZarrSelection({+ variable,+ axis,+ frameIndex: 1,+ dimensionIndexes: {year: 1, day: 1, band: 3}+ }),+ {year: 1, month: 1, day: 1, band: 3},+ 'only the selected month varies while the other dimensions remain pinned'+ );+ t.end();+});++test('#ZarrLayer -> save/load and duplication retain axes and pins; old maps keep automatic time', t => {+ const zarrAxis = {kind: 'dimension', dimension: 'time'};+ const layer = new ZarrLayer({+ dataId: 'zarr-dataset',+ visConfig: {+ zarrAxis,+ zarrFrame: 1,+ dimensionIndexes: {band: 2},+ rescale: [0, 1]+ }+ });+ const state = {+ ...InitialState,+ visState: {+ ...InitialState.visState,+ datasets: {'zarr-dataset': MOCK_ZARR_DATASET},+ layers: [layer],+ layerOrder: [layer.id],+ layerData: [layer.formatLayerData({'zarr-dataset': MOCK_ZARR_DATASET})]+ }+ };+ const saved = SchemaManager.getConfigToSave(state);+ const parsed = SchemaManager.parseSavedConfig(saved).visState.layers[0];+ const restored = validateLayerWithData(+ MOCK_ZARR_DATASET,+ parsed,+ InitialState.visState.layerClasses+ );+ t.deepEqual(restored.config.visConfig.zarrAxis, zarrAxis, 'saves the selected dimension axis');+ t.equal(restored.config.visConfig.zarrFrame, 1, 'restores the selected frame');+ t.deepEqual(+ restored.config.visConfig.dimensionIndexes,+ {band: 2},+ 'restores other pinned dimensions'+ );+ const duplicated = duplicateLayerUpdater(state.visState, {id: layer.id});+ const copy = duplicated.layers.find(candidate => candidate.id !== layer.id);+ t.deepEqual(copy.config.visConfig.zarrAxis, zarrAxis, 'duplicates the selected axis');+ t.equal(copy.config.visConfig.zarrFrame, 1, 'duplicates the selected frame');+ t.deepEqual(copy.config.visConfig.dimensionIndexes, {band: 2}, 'duplicates pinned dimensions');+ for (const candidate of [restored, copy]) {+ candidate.updateLayerMeta(MOCK_ZARR_DATASET);+ t.deepEqual(candidate.config.visConfig.rescale, [0, 1], 'retains an explicit 0-1 color range');+ const {zarrAxis: axisConfig, zarrFrame, dimensionIndexes} = candidate.config.visConfig;+ t.deepEqual(+ getZarrSelection({+ variable: TEMPERATURE,+ axis: getZarrAxis(TEMPERATURE, axisConfig, dimensionIndexes),+ frameIndex: zarrFrame,+ dimensionIndexes+ }),+ {time: 1, band: 2},+ 'the restored or duplicated layer selects the original raster slice'+ );+ }+ delete parsed.config.visConfig.zarrAxis;+ delete parsed.config.visConfig.zarrFrame;+ const legacy = validateLayerWithData(+ MOCK_ZARR_DATASET,+ parsed,+ InitialState.visState.layerClasses+ );+ legacy.updateLayerMeta(MOCK_ZARR_DATASET);+ t.equal(legacy.config.animation.enabled, true, 'old configs still enable the shared timeline');+ t.deepEqual(+ legacy.config.animation.timeSteps,+ TIME_DIMENSION.values,+ 'retains the existing time steps'+ );+ layer.updateLayerVisConfig({zarrVariable: 'precipitation', rescale: null});+ layer.updateLayerMeta(MOCK_ZARR_DATASET);+ const automaticConfig = SchemaManager.parseSavedConfig(SchemaManager.getConfigToSave(state))+ .visState.layers[0];+ const automaticRestored = validateLayerWithData(+ MOCK_ZARR_DATASET,+ automaticConfig,+ InitialState.visState.layerClasses+ );+ const automaticCopy = duplicateLayerUpdater(state.visState, {id: layer.id}).layers.find(+ candidate => candidate.id !== layer.id+ );+ for (const candidate of [automaticRestored, automaticCopy]) {+ candidate.updateLayerMeta(MOCK_ZARR_DATASET);+ t.equal(+ candidate.config.visConfig.rescale,+ null,+ 'retains automatic sampling on save/load and duplication'+ );+ }+ t.end();+});++test('#ZarrLayer -> URL-only saved maps refetch metadata and restore variable and timeline settings', async t => {+ const originalFetch = globalThis.fetch;+ const url = 'https://example.com/saved-forecast.zarr';+ const array = {+ zarr_format: 2,+ shape: [3, 4, 2, 2],+ chunks: [1, 1, 2, 2],+ dtype: '<f8',+ compressor: null,+ fill_value: null,+ order: 'C',+ filters: null+ };+ const attrs = {+ _ARRAY_DIMENSIONS: ['time', 'band', 'y', 'x'],+ 'spatial:dimensions': ['y', 'x'],+ 'spatial:transform': [1, 0, 0, 0, -1, 2],+ 'spatial:shape': [2, 2],+ 'proj:code': 'EPSG:4326',+ actual_range: [0, 100]+ };+ const consolidated = {+ zarr_consolidated_format: 1,+ metadata: {+ '.zgroup': {zarr_format: 2},+ '.zattrs': {},+ 'temperature/.zarray': array,+ 'temperature/.zattrs': attrs,+ 'precipitation/.zarray': array,+ 'precipitation/.zattrs': attrs,+ 'time/.zarray': {...array, shape: [3], chunks: [3]},+ 'time/.zattrs': {_ARRAY_DIMENSIONS: ['time'], units: 'days since 2020-01-27'}+ }+ };+ let metadataRequests = 0;+ globalThis.fetch = async request => {+ if (request.url === `${url}/.zmetadata`) {+ metadataRequests++;+ return new Response(JSON.stringify(consolidated));+ }+ if (request.url === `${url}/time/0`) {+ return new Response(new Float64Array([0, 1, 2]).buffer);+ }+ return new Response(null, {status: 404});+ };+ try {+ const metadata = await getZarrMetadata(url, {variable: 'temperature'});+ const dataset = {...MOCK_ZARR_DATASET, metadata};+ const layer = new ZarrLayer({+ dataId: dataset.id,+ visConfig: {+ zarrVariable: 'precipitation',+ zarrAxis: {kind: 'dimension', dimension: 'time'},+ zarrFrame: 2,+ dimensionIndexes: {band: 1},+ rescale: [10, 80]+ }+ });+ const saved = SchemaManager.save({+ ...InitialState,+ visState: {+ ...InitialState.visState,+ datasets: {[dataset.id]: dataset},+ layers: [layer],+ layerOrder: [layer.id]+ }+ });+ t.deepEqual(+ saved.datasets[0].data.metadata,+ {url, variable: 'temperature'},+ 'stores the default source separately from the layer selection'+ );+ const loaded = SchemaManager.load(JSON.parse(JSON.stringify(saved)));+ const workingFetch = globalThis.fetch;+ for (const failure of ['network', 'missing store']) {+ globalThis.fetch = async () => {+ if (failure === 'network') throw new Error('Store unavailable');+ return new Response(null, {status: 404});+ };+ const failedTask = createNewDataEntry(loaded.datasets[0]);+ try {+ await new Promise((resolve, reject) => {+ failedTask.run(+ (effect, onSuccess, onError) => effect(onSuccess, onError),+ resolve,+ reject+ );+ });+ t.fail(`${failure}: must not restore an empty dataset`);+ } catch (error) {+ t.ok(error instanceof Error, `${failure}: reaches the dataset task error handler`);+ }+ }+ globalThis.fetch = workingFetch;+ const task = createNewDataEntry(loaded.datasets[0]);+ const restoredDataset = await new Promise((resolve, reject) => {+ task.run((effect, onSuccess, onError) => effect(onSuccess, onError), resolve, reject);+ });+ t.equal(+ metadataRequests,+ 2,+ 'reload fetches fresh metadata instead of relying on the in-memory cache'+ );+ t.equal(+ restoredDataset.metadata.variable,+ 'temperature',+ 'restores the dataset default variable'+ );+ t.deepEqual(+ restoredDataset.metadata.timeDimension.values,+ TIME_DIMENSION.values,+ 'rebuilds decoded time coordinates'+ );+ t.equal(restoredDataset.metadata.variables.length, 2, 'rebuilds the variable picker');+ const restored = validateLayerWithData(+ restoredDataset,+ loaded.config.visState.layers[0],+ InitialState.visState.layerClasses+ );+ const data = restored.formatLayerData({[restoredDataset.id]: restoredDataset});+ t.equal(data.variable.path, 'precipitation', 'restores the layer variable override');+ t.deepEqual(restored.config.visConfig.rescale, [10, 80], 'keeps the user color range');+ t.deepEqual(+ getZarrSelection({+ variable: data.variable,+ axis: getZarrAxis(data.variable, restored.config.visConfig.zarrAxis),+ frameIndex: restored.config.visConfig.zarrFrame,+ dimensionIndexes: restored.config.visConfig.dimensionIndexes+ }),+ {time: 2, band: 1},+ 'restores the axis, frame and dimension pins against refreshed metadata'+ );+ } finally {+ globalThis.fetch = originalFetch;+ t.end();+ }+});++test('#ZarrLayer -> switching axes reconciles the global animation domain', t => {+ const layer = new ZarrLayer({dataId: 'zarr-dataset'});+ const datasets = {'zarr-dataset': MOCK_ZARR_DATASET};+ const data = layer.formatLayerData(datasets);+ let state = {+ ...InitialState.visState,+ datasets,+ layers: [layer],+ layerOrder: [layer.id],+ layerData: [data],+ animationConfig: {+ ...InitialState.visState.animationConfig,+ domain: [T0, T0 + 2 * DAY],+ currentTime: T0,+ timeSteps: TIME_DIMENSION.values+ }+ };+ state = layerVisConfigChangeUpdater(state, {+ oldLayer: state.layers[0],+ newVisConfig: {+ zarrAxis: {kind: 'dimension', dimension: 'band'},+ zarrFrame: 0+ }+ });+ t.equal(+ state.animationConfig.domain,+ null,+ 'removes an explicit dimension from the global clock'+ );+ state = layerVisConfigChangeUpdater(state, {+ oldLayer: state.layers[0],+ newVisConfig: {zarrAxis: {kind: 'auto'}}+ });+ t.deepEqual(+ state.animationConfig.domain,+ [T0, T0 + 2 * DAY],+ 'restores automatic time when selected'+ );+ state = layerVisConfigChangeUpdater(state, {+ oldLayer: state.layers[0],+ newVisConfig: {zarrVariable: 'precipitation'}+ });+ t.equal(+ state.animationConfig.domain,+ null,+ 'clears the clock when switching to a timeless variable'+ );+ t.end();+});++test('#ZarrLayer -> getZarrMaxZoom', t => {+ // A CarbonPlan pyramid: 128px for the whole world at the coarsest level,+ // doubling to 4096px. Levels are listed finest first.+ const levels = [4096, 2048, 1024, 512, 256, 128].map(size => ({shape: [size, size]}));++ t.equal(getZarrMaxZoom(levels, 0), 2, 'should match the 512px world at zoom 0');+ t.equal(getZarrMaxZoom(levels, 1), 3, 'should take one level per zoom');+ t.equal(getZarrMaxZoom(levels, 3), 5, 'should reach the finest level');+ t.equal(getZarrMaxZoom(levels, 9), 5, 'should not ask for a level the pyramid lacks');+ t.equal(getZarrMaxZoom(levels, -4), 0, 'should not ask for a level below the coarsest');++ t.equal(getZarrMaxZoom(levels, undefined), undefined, 'should defer without a map zoom');+ t.equal(+ getZarrMaxZoom([{shape: [256, 256]}], 4),+ undefined,+ 'should defer when there is nothing to choose between'+ );++ t.end();+});++test('#ZarrLayer -> renderLayer caps the level only for a web mercator pyramid', async t => {+ const layer = new ZarrLayer({dataId: 'zarr-dataset'});+ await layer._loadRuntime();+ layer._nodeKey = `${MOCK_ZARR_DATASET.metadata.url}#temperature`;+ layer._node = {shape: [3, 4, 256, 256]};++ const render = metadata =>+ layer.renderLayer({+ data: {metadata, variable: TEMPERATURE},+ mapState: {zoom: 1},+ idx: 0,+ gpuFilter: null,+ layerCallbacks: {},+ visible: true+ })[0];++ const levels = [1024, 512, 256, 128].map(size => ({+ path: String(size),+ shape: [size, size],+ chunks: [128, 128]+ }));++ // deck.gl's own default, i.e. no cap.+ t.equal(+ render({...MOCK_ZARR_DATASET.metadata, levels}).props.maxZoom,+ null,+ 'should leave the level to the renderer for an ordinary pyramid'+ );+ t.equal(+ render({...MOCK_ZARR_DATASET.metadata, levels, webMercatorPyramid: true}).props.maxZoom,+ 3,+ 'should tie the level to the map zoom for a web mercator pyramid'+ );++ t.end();+});++test('#ZarrLayer -> variable switches use the selected grid and pyramid zoom limits', async t => {+ const variable = (path, sizes, webMercatorPyramid) => ({+ ...PRECIPITATION,+ path,+ spatialMetadata: {+ crs: {code: webMercatorPyramid ? 'EPSG:3857' : 'EPSG:4326'},+ axes: webMercatorPyramid ? ['y', 'x'] : ['lat', 'lon'],+ xAxisIndex: 1,+ yAxisIndex: 0,+ levels: sizes.map(size => ({path: String(size), shape: [size, size], chunks: [128, 128]})),+ webMercatorPyramid+ }+ });+ const large = variable('large', [1024, 512, 256, 128], true);+ const small = variable('small', [512, 256], true);+ const plain = variable('plain', [256], false);+ const metadata = {+ ...MOCK_ZARR_DATASET.metadata,+ ...large.spatialMetadata,+ variable: large.path,+ variables: [large, small, plain]+ };+ const datasets = {'zarr-dataset': {...MOCK_ZARR_DATASET, metadata}};+ const layer = new ZarrLayer({dataId: 'zarr-dataset'});+ await layer._loadRuntime();+ const render = selected => {+ layer.updateLayerVisConfig({zarrVariable: selected.path});+ const data = layer.formatLayerData(datasets);+ t.equal(layer.meta.crs, selected.spatialMetadata.crs.code, 'updates the layer CRS');+ t.deepEqual(+ data.metadata.levels,+ selected.spatialMetadata.levels,+ 'updates the resolution levels'+ );+ t.deepEqual(data.metadata.axes, selected.spatialMetadata.axes, 'updates the spatial axes');+ layer._nodeKey = `${metadata.url}#${selected.path}`;+ layer._node = {shape: selected.shape};+ return layer.renderLayer({data, mapState: {zoom: 1}, visible: true})[0];+ };+ t.equal(render(large).props.maxZoom, 3, 'uses the default pyramid zoom limit');+ t.equal(render(small).props.maxZoom, 1, 'uses the smaller pyramid zoom limit after switching');+ t.equal(render(plain).props.maxZoom, null, 'clears the pyramid limit for a plain grid');+ t.equal(render(large).props.maxZoom, 3, 'restores the original pyramid limit');+ t.equal(metadata.variable, large.path, 'does not change the shared dataset default');+ t.deepEqual(+ metadata.levels,+ large.spatialMetadata.levels,+ 'does not change the shared dataset grid'+ );+ t.end();+});++test('#ZarrLayer -> renderLayer holds the loaded slice while the next one loads', async t => {+ const layer = new ZarrLayer({dataId: 'zarr-dataset'});+ await layer._loadRuntime();+ layer._nodeKey = `${MOCK_ZARR_DATASET.metadata.url}#temperature`;+ layer._node = {shape: [3, 4, 256, 256]};++ const render = () =>+ layer.renderLayer({+ data: {metadata: MOCK_ZARR_DATASET.metadata, variable: TEMPERATURE},+ mapState: {},+ idx: 0,+ gpuFilter: null,+ layerCallbacks: {},+ visible: true+ });++ const first = render();+ t.equal(first.length, 1, 'should render one layer before any slice has loaded');++ // deck reports every tile in the viewport is in.+ first[0].props.onViewportLoad();++ layer.updateLayerVisConfig({dimensionIndexes: {band: 2}});+ const second = render();++ t.equal(second.length, 2, 'should keep the loaded slice while the next one loads');+ t.deepEqual(+ second[0].props.selection,+ {time: 0, band: 0},+ 'should draw the loaded slice underneath'+ );+ t.deepEqual(second[1].props.selection, {time: 0, band: 2}, 'should draw the new slice on top');+ t.notOk(second[0].props.onViewportLoad, 'should not let the backdrop retire itself');++ second[1].props.onViewportLoad();+ const third = render();++ t.equal(third.length, 1, 'should drop the backdrop once the new slice has loaded');+ t.deepEqual(third[0].props.selection, {time: 0, band: 2}, 'should keep the new slice');++ t.end();+});++test('#ZarrLayer -> renderLayer forwards the pyramid description to the renderer', async t => {+ // A pyramid keeps its levels under a shared parent, so a variable's identity+ // is the group plus the array name while the node opened is the group.+ const pyramid = {+ ...PRECIPITATION,+ path: 'pyramid/qtot',+ name: 'qtot',+ displayName: 'qtot',+ nodePath: 'pyramid',+ geoAttrs: {+ 'spatial:dimensions': ['y', 'x'],+ 'proj:code': 'EPSG:4326',+ multiscales: {+ layout: [+ {+ asset: '0/qtot',+ 'spatial:transform': [1, 0, -180, 0, -1, 90],+ 'spatial:shape': [180, 360]+ },+ {+ asset: '1/qtot',+ 'spatial:transform': [2, 0, -180, 0, -2, 90],+ 'spatial:shape': [90, 180]+ }+ ]+ }+ }+ };++ const layer = new ZarrLayer({dataId: 'zarr-dataset'});+ await layer._loadRuntime();+ layer._nodeKey = `${MOCK_ZARR_DATASET.metadata.url}#pyramid/qtot`;+ layer._node = {attrs: {}};++ const [deckLayer] = layer.renderLayer({+ data: {metadata: MOCK_ZARR_DATASET.metadata, variable: pyramid},+ mapState: {},+ idx: 0,+ gpuFilter: null,+ layerCallbacks: {},+ visible: true+ });++ t.deepEqual(+ deckLayer.props.metadata.multiscales.layout.map(level => level.asset),+ ['0/qtot', '1/qtot'],+ 'should hand the renderer every level of the pyramid'+ );++ t.end();+});++test('#ZarrLayer -> renderLayer keeps its deck props stable across redraws', async t => {+ const layer = new ZarrLayer({dataId: 'zarr-dataset'});+ await layer._loadRuntime();+ layer._nodeKey = `${MOCK_ZARR_DATASET.metadata.url}#temperature`;+ layer._node = {shape: [3, 4, 256, 256]};++ const render = () =>+ layer.renderLayer({+ data: {metadata: MOCK_ZARR_DATASET.metadata, variable: TEMPERATURE},+ mapState: {},+ idx: 0,+ gpuFilter: null,+ layerCallbacks: {},+ visible: true+ })[0];++ const [first, second] = [render(), render()];++ // kepler rebuilds its deck layers on every pan frame. deck compares these+ // props by reference, and a change makes RasterTileLayer rebuild its inner+ // TileLayer, which re-runs the CPU colormap over every visible tile.+ t.equal(second.id, first.id, 'should keep the same sublayer id');+ t.equal(second.props.selection, first.props.selection, 'should reuse the selection object');+ t.equal(second.props.renderTile, first.props.renderTile, 'should reuse the renderTile callback');+ t.equal(+ second.props.getTileData,+ first.props.getTileData,+ 'should reuse the getTileData callback'+ );+ t.equal(second.props.node, first.props.node, 'should reuse the opened node');++ t.end();+});++test('#ZarrLayer -> renderLayer returns nothing before the store opens', t => {+ const layer = new ZarrLayer({dataId: 'zarr-dataset'});++ t.deepEqual(+ layer.renderLayer({data: {metadata: null, variable: null}, mapState: {}}),+ [],+ 'should render nothing without metadata'+ );++ t.deepEqual(+ layer.renderLayer({+ data: {metadata: MOCK_ZARR_DATASET.metadata, variable: TEMPERATURE},+ mapState: {globe: {enabled: true}}+ }),+ [],+ 'should render nothing in the globe view'+ );++ t.end();+});diff --git a/test/node/docker/get-runtime-config-href-test.js b/test/node/docker/get-runtime-config-href-test.jsindex 609596bec..5adf9c56e 100644--- a/test/node/docker/get-runtime-config-href-test.js+++ b/test/node/docker/get-runtime-config-href-test.js@@ -2,6 +2,7 @@// Copyright contributors to the kepler.gl projectimport test from 'tape';+import {getApplicationConfig, initApplicationConfig} from '@kepler.gl/utils';import {getRuntimeConfigHref} from '../../../examples/demo-app/src/utils/get-runtime-config-href';@@ -52,3 +53,47 @@ test('getRuntimeConfigHref resolves config.json against <base href>', t => {);t.end();});++test('demo runtime config respects Zarr availability and explicit overrides', async t => {+ const originalConfig = {...getApplicationConfig()};+ const originalFetch = globalThis.fetch;+ // Import inside the test so demo startup defaults do not affect other tests.+ const {loadAndApplyRuntimeConfig, getRuntimeConfig, applyRuntimeConfig} = await import(+ '../../../examples/demo-app/src/utils/runtime-config'+ );+ const originalRuntimeConfig = getRuntimeConfig();+ try {+ initApplicationConfig({enableZarrLayer: false});+ globalThis.fetch = async () => ({ok: false});+ await loadAndApplyRuntimeConfig();+ if (getApplicationConfig().enableZarrLayer === false) {+ t.skip('Zarr layer is disabled (enableZarrLayer=false); enabled-default check skipped');+ } else {+ t.equal(+ getApplicationConfig().enableZarrLayer,+ true,+ 'demo defaults enable Zarr without config.json'+ );+ }++ for (const enabled of [true, false]) {+ globalThis.fetch = async () => ({+ ok: true,+ json: async () => ({applicationConfig: {enableZarrLayer: enabled}})+ });+ await loadAndApplyRuntimeConfig();+ t.equal(+ getApplicationConfig().enableZarrLayer,+ enabled,+ `config.json can explicitly ${enabled ? 'enable' : 'disable'} Zarr`+ );+ }+ } catch (error) {+ t.fail(error.message);+ } finally {+ applyRuntimeConfig(originalRuntimeConfig);+ initApplicationConfig(originalConfig);+ globalThis.fetch = originalFetch;+ t.end();+ }+});diff --git a/test/node/fixtures/zarr-package-consumer.cjs b/test/node/fixtures/zarr-package-consumer.cjsnew file mode 100644index 000000000..3842e4584--- /dev/null+++ b/test/node/fixtures/zarr-package-consumer.cjs@@ -0,0 +1,189 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++const assert = require('node:assert/strict');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const {createRequire} = require('node:module');+const {transformFileSync} = require('@babel/core');++const root = path.resolve(__dirname, '../../..');+const consumer = fs.mkdtempSync(path.join(os.tmpdir(), 'kepler-zarr-consumer-'));+const modules = path.join(consumer, 'node_modules');+const readJson = filename => JSON.parse(fs.readFileSync(filename, 'utf8'));++// Isolate the Zarr dependency graph so the repository's fix-dependencies script+// cannot make require('zarrita') work in this consumer. Other dependencies are+// reused offline; no Babel register, Jest aliases or source stubs are involved.+function installDependencies(source, target) {+ fs.mkdirSync(target, {recursive: true});+ for (const entry of fs.readdirSync(source, {withFileTypes: true})) {+ if (entry.name.startsWith('.') || entry.name === '@kepler.gl') continue;+ const from = path.join(source, entry.name);+ const to = path.join(target, entry.name);+ if (+ entry.name === 'zarrita' ||+ entry.name === '@zarrita' ||+ entry.name === '@developmentseed'+ ) {+ fs.cpSync(from, to, {recursive: true});+ } else {+ fs.symlinkSync(from, to);+ }+ }+ for (const name of ['zarrita', '@zarrita/storage']) {+ const filename = path.join(target, name, 'package.json');+ const pkg = readJson(filename);+ for (const entry of Object.values(pkg.exports)) {+ delete entry.default;+ delete entry.require;+ }+ fs.writeFileSync(filename, JSON.stringify(pkg));+ }+}++// Build the public packages and their workspace dependencies with the same+// package-local Babel configs used for publication. Keep generated files in+// this disposable consumer, never in the checkout's dist directories.+const built = new Set();+function buildPackage(name) {+ if (built.has(name)) return;+ built.add(name);+ const source = path.join(root, 'src', name.replace('@kepler.gl/', ''));+ const pkg = readJson(path.join(source, 'package.json'));+ if (!pkg.main) return; // @kepler.gl/types publishes declarations only.+ const target = path.join(modules, name);+ fs.mkdirSync(target, {recursive: true});+ fs.writeFileSync(path.join(target, 'package.json'), JSON.stringify(pkg));+ function buildDirectory(from, to) {+ fs.mkdirSync(to, {recursive: true});+ for (const entry of fs.readdirSync(from, {withFileTypes: true})) {+ const input = path.join(from, entry.name);+ if (entry.isDirectory()) {+ buildDirectory(input, path.join(to, entry.name));+ } else if (!/\.(d\.ts|spec\.[jt]sx?)$/.test(entry.name)) {+ if (/\.[jt]sx?$/.test(entry.name)) {+ const {code} = transformFileSync(input, {+ configFile: path.join(source, 'babel.config.js'),+ babelrc: false,+ envName: 'production'+ });+ fs.writeFileSync(path.join(to, entry.name.replace(/\.[jt]sx?$/, '.js')), code);+ } else {+ fs.copyFileSync(input, path.join(to, entry.name));+ }+ }+ }+ }+ buildDirectory(path.join(source, 'src'), path.join(target, 'dist/cjs'));+ for (const dependency of Object.keys({...pkg.dependencies, ...pkg.peerDependencies})) {+ if (dependency.startsWith('@kepler.gl/')) buildPackage(dependency);+ }+}++async function run() {+ installDependencies(path.join(root, 'node_modules'), modules);+ buildPackage('@kepler.gl/table');+ buildPackage('@kepler.gl/layers');+ const requireConsumer = createRequire(path.join(consumer, 'index.cjs'));+ assert.throws(() => requireConsumer('zarrita'), {code: 'ERR_PACKAGE_PATH_NOT_EXPORTED'});+ assert.throws(() => requireConsumer('@zarrita/storage'), {code: 'ERR_PACKAGE_PATH_NOT_EXPORTED'});++ const {getZarrMetadata} = requireConsumer('@kepler.gl/table');+ // Test the compiled Zarr layer without importing every other layer. The full+ // layers entry also imports Flowmap, whose extensionless ESM imports fail in+ // native Node on master. This is Zarr regression coverage, not a full-package+ // native Node compatibility check.+ const layersDirectory = path.dirname(requireConsumer.resolve('@kepler.gl/layers'));+ const {default: ZarrLayer} = requireConsumer(+ path.join(layersDirectory, 'zarr-layer/zarr-layer.js')+ );+ const layer = new ZarrLayer({dataId: 'climate'});+ assert.deepEqual(layer.renderLayer({data: null}), []);++ const array = {+ zarr_format: 2,+ shape: [2, 2, 2],+ chunks: [1, 2, 2],+ dtype: '<f8',+ compressor: null,+ fill_value: null,+ order: 'C',+ filters: null+ };+ const consolidated = {+ zarr_consolidated_format: 1,+ metadata: {+ '.zgroup': {zarr_format: 2},+ '.zattrs': {},+ 'climate/.zarray': array,+ 'climate/.zattrs': {+ _ARRAY_DIMENSIONS: ['month', 'lat', 'lon'],+ 'spatial:dimensions': ['lat', 'lon'],+ 'spatial:transform': [1, 0, 0, 0, -1, 2],+ 'spatial:shape': [2, 2],+ 'proj:code': 'EPSG:4326'+ },+ 'month/.zarray': {...array, shape: [2], chunks: [2]},+ 'month/.zattrs': {_ARRAY_DIMENSIONS: ['month']}+ }+ };+ let requests = 0;+ globalThis.fetch = async request => {+ requests++;+ if (request.url.endsWith('/.zmetadata')) return Response.json(consolidated);+ if (request.url.endsWith('/month/0')) return new Response(new Float64Array([1, 2]).buffer);+ if (request.url.endsWith('/climate/0.0.0'))+ return new Response(new Float64Array([5, 6, 7, 8]).buffer);+ return new Response(null, {status: 404});+ };++ // Cancellation while the initial import is pending must not start a fetch.+ const controller = new AbortController();+ const cancelled = getZarrMetadata('https://example.com/cancelled.zarr', {+ signal: controller.signal+ });+ controller.abort();+ await assert.rejects(cancelled, {name: 'AbortError'});+ assert.equal(requests, 0);++ const metadata = await getZarrMetadata('https://example.com/climate.zarr');+ assert.equal(metadata.variable, 'climate');+ assert.deepEqual(metadata.nonSpatialDims[0].values, [1, 2]);+ let redraw;+ const ready = new Promise(resolve => {+ redraw = resolve;+ });+ const options = {+ data: {metadata, variable: metadata.variables[0]},+ mapState: {},+ idx: 0,+ gpuFilter: null,+ visible: true,+ layerCallbacks: {onRedrawNeeded: redraw}+ };+ assert.deepEqual(layer.renderLayer(options), []);+ await ready;+ const [rendered] = layer.renderLayer(options);+ assert.ok(rendered, 'lazy renderer must be ready when it asks for a redraw');+ assert.deepEqual(rendered.props.selection, {month: 0});+ const tile = await rendered.props.getTileData(rendered.props.node, {+ sliceSpec: [0, null, null],+ width: 2,+ height: 2+ });+ assert.deepEqual(Array.from(tile.values), [5, 6, 7, 8]);+}++run().then(+ () => {+ fs.rmSync(consumer, {recursive: true, force: true});+ console.log('CommonJS Zarr consumer passed');+ },+ error => {+ fs.rmSync(consumer, {recursive: true, force: true});+ console.error(error);+ process.exitCode = 1;+ }+);diff --git a/test/node/reducers/annotation-updater-test.js b/test/node/reducers/annotation-updater-test.jsindex 92f5a22b2..f251008bf 100644--- a/test/node/reducers/annotation-updater-test.js+++ b/test/node/reducers/annotation-updater-test.js@@ -322,7 +322,11 @@ test('#visStateReducer -> kind changes preserve rich text, including conversionsAnnotationKind.TEXT]) {state = reducer(state, VisStateActions.updateAnnotation('formatted', {kind}));- t.deepEqual(state.annotations[0].editorState, editorState, `${kind} keeps rich-text formatting`);+ t.deepEqual(+ state.annotations[0].editorState,+ editorState,+ `${kind} keeps rich-text formatting`+ );t.equal(state.annotations[0].label, 'Formatted label', `${kind} keeps the plain text label`);}diff --git a/test/node/reducers/composer-state-test.js b/test/node/reducers/composer-state-test.jsindex 39e6f93ae..5cf784904 100644--- a/test/node/reducers/composer-state-test.js+++ b/test/node/reducers/composer-state-test.js@@ -874,8 +874,16 @@ test('#composerStateReducer - replaceDataInMapUpdater: same dataId', t => {test('#composerStateReducer - dataset replacement preserves data-independent bookmarks', t => {const bookmarks = [- {id: 'first', name: 'Home', camera: {longitude: 10, latitude: 20, zoom: 6, bearing: 30, pitch: 45}},- {id: 'second', name: 'Away', camera: {longitude: -20, latitude: 30, zoom: 8, bearing: 0, pitch: 0}}+ {+ id: 'first',+ name: 'Home',+ camera: {longitude: 10, latitude: 20, zoom: 6, bearing: 30, pitch: 45}+ },+ {+ id: 'second',+ name: 'Away',+ camera: {longitude: -20, latitude: 30, zoom: 8, bearing: 0, pitch: 0}+ }];for (const [dataId, replacementId] of [['id', 'id'],@@ -912,7 +920,11 @@ test('#composerStateReducer - dataset replacement preserves data-independent boo2,`${dataId}: replaces rows`);- t.deepEqual(result.visState.cameraBookmarks, bookmarks, `${dataId}: preserves every saved view`);+ t.deepEqual(+ result.visState.cameraBookmarks,+ bookmarks,+ `${dataId}: preserves every saved view`+ );t.deepEqual(KeplerGlSchema.getConfigToSave(result).config.visState.cameraBookmarks,bookmarks,@@ -925,7 +937,11 @@ test('#composerStateReducer - dataset replacement preserves data-independent bootest('#composerStateReducer - legacy bookmarks do not opt in or reset an explicit host preference', t => {const initial = keplerGlReducer(undefined, registerEntry({id: 'test'})).test;const bookmarks = [- {id: 'home', name: 'Home', camera: {longitude: 10, latitude: 20, zoom: 6, bearing: 30, pitch: 45}}+ {+ id: 'home',+ name: 'Home',+ camera: {longitude: 10, latitude: 20, zoom: 6, bearing: 30, pitch: 45}+ }];const config = KeplerGlSchema.getConfigToSave({...initial,@@ -952,7 +968,6 @@ test('#composerStateReducer - legacy bookmarks do not opt in or reset an explicit.end();});-test('#composerStateReducer - project JSON bookmark visibility and layout survive file import', t => {const initial = keplerGlReducer(undefined, registerEntry({id: 'test'})).test;const bookmarks = [diff --git a/test/node/schemas/dataset-schema-test.js b/test/node/schemas/dataset-schema-test.jsindex a4cc93ff1..73ade93a1 100644--- a/test/node/schemas/dataset-schema-test.js+++ b/test/node/schemas/dataset-schema-test.js@@ -155,6 +155,68 @@ test('#DatasetSchema -> save externally-hosted dataset without inlining rows', tt.end();});+test('#DatasetSchema -> Zarr saves its source without embedding metadata or coordinate rows', t => {+ const values = Array.from({length: 20_000}, (_, index) => index);+ const dimension = {name: 'time', size: values.length, values};+ const source = {+ url: 'https://example.com/forecast.zarr',+ variable: 'temperature',+ label: 'Forecast',+ attribution: 'Weather provider'+ };+ const metadata = {+ ...source,+ variables: [{path: 'temperature', nonSpatialDims: [dimension]}],+ nonSpatialDims: [dimension],+ timeDimension: dimension,+ levels: [{path: '.', shape: [2048, 2048], chunks: [128, 128]}]+ };+ const dataset = {+ id: 'forecast',+ label: 'My forecast',+ type: DatasetType.ZARR,+ color: [1, 2, 3],+ disableDataOperation: true,+ metadata,+ fields: [{name: 'time', type: 'timestamp'}],+ dataContainer: {+ flattenData() {+ t.fail('must not materialize coordinate rows during export');+ return values.map(value => [value]);+ }+ }+ };++ const saved = datasetSchema[VERSIONS.v1].save(dataset);+ t.deepEqual(saved.metadata, source, 'saves only the source, default variable and attribution');+ t.deepEqual(saved.allData, [], 'does not save coordinate rows');+ t.deepEqual(saved.fields, [], 'does not save synthetic coordinate fields');+ t.equal(saved.disableDataOperation, true, 'preserves dataset behavior');+ t.ok(JSON.stringify(saved).length < 1000, 'export size is independent of large coordinate lists');+ t.equal(dataset.metadata, metadata, 'does not replace live metadata');+ t.equal(dataset.metadata.timeDimension.values, values, 'keeps live coordinates available');++ const [loaded] = SchemaManager.parseSavedData([{version: 'v1', data: saved}]);+ t.deepEqual(loaded.metadata, source, 'retains what the metadata refresh needs');+ t.equal(loaded.info.id, dataset.id, 'preserves dataset identity');+ t.equal(loaded.info.label, dataset.label, 'preserves the user label');+ t.equal(loaded.info.type, DatasetType.ZARR, 'restores the remote dataset type');++ const root = datasetSchema[VERSIONS.v1].save({...dataset, metadata: {...metadata, variable: ''}});+ t.equal(root.metadata.variable, '', 'retains a root-array variable path');+ const automatic = datasetSchema[VERSIONS.v1].save({...dataset, metadata: {url: source.url}});+ t.deepEqual(automatic.metadata, {url: source.url}, 'allows restoring the default variable');++ const legacy = SchemaManager.parseSavedData([+ {+ version: 'v1',+ data: {...saved, metadata}+ }+ ])[0];+ t.deepEqual(legacy.metadata, metadata, 'older maps with embedded metadata still load');+ t.end();+});+test('#DatasetSchema -> save externally-hosted dataset refresh interval', t => {const dataset = {id: 'remote-1',diff --git a/test/node/utils/annotation-utils-test.js b/test/node/utils/annotation-utils-test.jsindex 9b8c754a0..1bd345b07 100644--- a/test/node/utils/annotation-utils-test.js+++ b/test/node/utils/annotation-utils-test.js@@ -413,20 +413,10 @@ test('#movePoint -> falls back to ground plane when pick returns no altitude', ttest('#moveRulerEndpoint -> moves endpoints independently using 3D surface picks', t => {const ruler = makeRulerAnnotation({anchorPoint: [0, 0, 5], endPoint: [1, 1, 10]});- const movedStart = moveRulerEndpoint(- ruler,- 'start',- {x: 5, y: 5},- mockViewport,- () => [2, 3, 40]- );- const movedEnd = moveRulerEndpoint(- ruler,- 'end',- {x: 5, y: 5},- mockViewport,- () => [4, 5, 80]- );+ const movedStart = moveRulerEndpoint(ruler, 'start', {x: 5, y: 5}, mockViewport, () => [+ 2, 3, 40+ ]);+ const movedEnd = moveRulerEndpoint(ruler, 'end', {x: 5, y: 5}, mockViewport, () => [4, 5, 80]);t.deepEqual(movedStart.anchorPoint, [2, 3, 40], 'start should snap to its picked surface');t.notOk('endPoint' in movedStart, 'moving start should not change end');@@ -454,16 +444,10 @@ test('#moveRulerEndpoint -> drags from the rendered world copy across the dateli};const ruler = makeRulerAnnotation({anchorPoint: [179, 0], endPoint: [-179, 0]});let pickedScreen;- const changes = moveRulerEndpoint(- ruler,- 'end',- {x: 1, y: 0},- wrappingViewport,- screen => {- pickedScreen = screen;- return null;- }- );+ const changes = moveRulerEndpoint(ruler, 'end', {x: 1, y: 0}, wrappingViewport, screen => {+ pickedScreen = screen;+ return null;+ });t.deepEqual(pickedScreen, [182, 0], 'surface pick should start at the visible +181 handle');t.deepEqual(changes.endPoint, [-178, 0], 'stored longitude should remain normalized');diff --git a/test/node/utils/export-utils-test.js b/test/node/utils/export-utils-test.jsindex d687b639e..47a3ab70d 100644--- a/test/node/utils/export-utils-test.js+++ b/test/node/utils/export-utils-test.js@@ -179,8 +179,7 @@ test('exportUtils -> ExportHtml escapes script terminators in map info', t => {test('exportUtils -> ExportHtml safely serializes inline data', t => {const datasetValue = '</script><div data-kepler-export-test="dataset"></div>\u2028\u2029';const configValue = '</script><div data-kepler-export-test="config"></div>\u2028\u2029';- const savedStyleType =- '</script><div data-kepler-export-test="style-type"></div>\u2028\u2029';+ const savedStyleType = '</script><div data-kepler-export-test="style-type"></div>\u2028\u2029';const mapboxApiAccessToken ='\'</script><div data-kepler-export-test="mapbox-token"></div>\u2028\u2029';const version = 'test"></script><div data-kepler-export-test="version"></div>';@@ -293,7 +292,9 @@ test('exportUtils -> ExportHtml preserves custom branding', t => {'the read-only logo should link to the app website');t.ok(- html.includes('react.createElement("span", {style: {color: branding.appNameColor}}, branding.appName)'),+ html.includes(+ 'react.createElement("span", {style: {color: branding.appNameColor}}, branding.appName)'+ ),'the exported logo should render the app name using its selected color');t.ok(diff --git a/test/node/zarr-package.spec.js b/test/node/zarr-package.spec.jsnew file mode 100644index 000000000..ef807f29f--- /dev/null+++ b/test/node/zarr-package.spec.js@@ -0,0 +1,17 @@+// SPDX-License-Identifier: MIT+// Copyright contributors to the kepler.gl project++import {execFileSync} from 'child_process';+import path from 'path';++// Use plain Node: Jest's ESM aliases and Babel register hide export-map failures.+test('CommonJS table and compiled Zarr layer work with unpatched ESM dependencies', () => {+ expect(+ execFileSync(process.execPath, [path.join(__dirname, 'fixtures/zarr-package-consumer.cjs')], {+ env: {...process.env, NODE_ENV: 'production', BABEL_ENV: 'production', NODE_OPTIONS: ''},+ timeout: 90000,+ encoding: 'utf8',+ stdio: 'pipe'+ })+ ).toContain('CommonJS Zarr consumer passed');+}, 100000);diff --git a/yarn.lock b/yarn.lockindex 012cab775..a6b8e47d8 100644--- a/yarn.lock+++ b/yarn.lock@@ -2015,7 +2015,7 @@ __metadata:languageName: nodelinkType: hard-"@babel/runtime@npm:^7.12.0, @babel/runtime@npm:^7.12.1, @babel/runtime@npm:^7.12.5, @babel/runtime@npm:^7.26.10, @babel/runtime@npm:^7.7.2, @babel/runtime@npm:^7.8.4, @babel/runtime@npm:^7.8.7, @babel/runtime@npm:^7.9.2":+"@babel/runtime@npm:^7.0.0, @babel/runtime@npm:^7.12.0, @babel/runtime@npm:^7.12.1, @babel/runtime@npm:^7.12.5, @babel/runtime@npm:^7.26.10, @babel/runtime@npm:^7.7.2, @babel/runtime@npm:^7.8.4, @babel/runtime@npm:^7.8.7, @babel/runtime@npm:^7.9.2":version: 7.29.7resolution: "@babel/runtime@npm:7.29.7"checksum: 10c0/ca11572f7146b21e0bde6a9ed4bb6a89eafbee5f0944c7eb54d0d8a2dac962c33638a1d611e14faa71dfbb92b4b5f9236232208568a6b7d5c6f3f39ddb91771e@@ -2534,6 +2534,92 @@ __metadata:languageName: nodelinkType: hard+"@developmentseed/affine@npm:^0.7.0":+ version: 0.7.0+ resolution: "@developmentseed/affine@npm:0.7.0"+ checksum: 10c0/69117f72443462c23dd83f80d12e872d4647646b308fda519a52e25958a373d9fae11f853b8d31c364de34fe3f99c6f1b5ac511a28db3ae5f528819b1b842b03+ languageName: node+ linkType: hard++"@developmentseed/deck.gl-raster@npm:^0.7.0":+ version: 0.7.0+ resolution: "@developmentseed/deck.gl-raster@npm:0.7.0"+ dependencies:+ "@developmentseed/affine": "npm:^0.7.0"+ "@developmentseed/proj": "npm:^0.7.0"+ "@developmentseed/raster-reproject": "npm:^0.7.0"+ "@math.gl/core": "npm:^4.1.0"+ "@math.gl/culling": "npm:^4.1.0"+ "@math.gl/web-mercator": "npm:^4.1.0"+ peerDependencies:+ "@deck.gl/core": ^9.3.0+ "@deck.gl/geo-layers": ^9.3.0+ "@deck.gl/layers": ^9.3.0+ "@deck.gl/mesh-layers": ^9.3.0+ "@developmentseed/morecantile": ^0.7.0+ "@luma.gl/core": ^9.3.2+ "@luma.gl/shadertools": ^9.3.2+ checksum: 10c0/3812135c53044a6f783d715c0a43a38511903002ed09a4ee9084a9bd3bb27da85015a9b06374278008e03558cdf7a56ef47efe4d1cb77312f112f3ebf8a8786a+ languageName: node+ linkType: hard++"@developmentseed/deck.gl-zarr@npm:0.7.0":+ version: 0.7.0+ resolution: "@developmentseed/deck.gl-zarr@npm:0.7.0"+ dependencies:+ "@developmentseed/affine": "npm:^0.7.0"+ "@developmentseed/deck.gl-raster": "npm:^0.7.0"+ "@developmentseed/geozarr": "npm:^0.7.0"+ "@developmentseed/proj": "npm:^0.7.0"+ "@developmentseed/raster-reproject": "npm:^0.7.0"+ proj4: "npm:^2.20.8"+ wkt-parser: "npm:^1.5.5"+ zarrita: "npm:^0.7.3"+ peerDependencies:+ "@deck.gl/core": ^9.3.0+ "@deck.gl/geo-layers": ^9.3.0+ "@deck.gl/layers": ^9.3.0+ "@luma.gl/core": ^9.3.2+ checksum: 10c0/05fd41ca6ac27b67bb89d9a7fe6987278d0d27b352761c7f98ebe4f3244b25750441ea70668700b1c9a5fa3ecb5cd3ee45e574db1f9b4551d62ce43bedfedda3+ languageName: node+ linkType: hard++"@developmentseed/geozarr@npm:0.7.0, @developmentseed/geozarr@npm:^0.7.0":+ version: 0.7.0+ resolution: "@developmentseed/geozarr@npm:0.7.0"+ dependencies:+ "@developmentseed/affine": "npm:^0.7.0"+ zarrita: "npm:^0.7.3"+ zod: "npm:^4.4.3"+ checksum: 10c0/436496b5529935f1e1c68f673f42bcb2c4ffddea7876ceda167dbc6d435a53f003255f8a1dd3f4b2dc47c9e28c79e3e6e14b7296181fc0f438552f739e5dbe9f+ languageName: node+ linkType: hard++"@developmentseed/morecantile@npm:0.7.0":+ version: 0.7.0+ resolution: "@developmentseed/morecantile@npm:0.7.0"+ dependencies:+ "@developmentseed/affine": "npm:^0.7.0"+ checksum: 10c0/9e5f0c2a9a7effa5a66bf0d9e82641ebc75433e02e3d170a2da021fcf48c030ef59b0d82d3ae1232521c8295d0baf806176ee7e69124dbf9e0e0b01713ff9123+ languageName: node+ linkType: hard++"@developmentseed/proj@npm:^0.7.0":+ version: 0.7.0+ resolution: "@developmentseed/proj@npm:0.7.0"+ dependencies:+ wkt-parser: "npm:1.5.5"+ checksum: 10c0/721857ce8b4acdbee864a80391f8337c03bfd333250fe2ee53c073adea70cc351ec3a410bfe76465b3bec01d99e823593e5cb7b31d67b3d49e09ae7c513d2189+ languageName: node+ linkType: hard++"@developmentseed/raster-reproject@npm:^0.7.0":+ version: 0.7.0+ resolution: "@developmentseed/raster-reproject@npm:0.7.0"+ checksum: 10c0/5bd3062f9e69d525a30374844917b2ad2e28ace3c1b33c3acc28bb4032cce6acab052b371f199009ab72448a2cc0fb527165879e318f2873621e982b1e6b3781+ languageName: node+ linkType: hard+"@discoveryjs/json-ext@npm:0.5.7, @discoveryjs/json-ext@npm:^0.5.0":version: 0.5.7resolution: "@discoveryjs/json-ext@npm:0.5.7"@@ -4257,6 +4343,9 @@ __metadata:"@deck.gl/geo-layers": "npm:^9.3.1""@deck.gl/layers": "npm:^9.3.1""@deck.gl/mesh-layers": "npm:^9.3.1"+ "@developmentseed/deck.gl-zarr": "npm:0.7.0"+ "@developmentseed/geozarr": "npm:0.7.0"+ "@developmentseed/morecantile": "npm:0.7.0""@flowmap.gl/data": "npm:^9.2.0""@flowmap.gl/layers": "npm:^9.2.0""@kepler.gl/common-utils": "npm:3.3.0-alpha.18"@@ -4311,6 +4400,8 @@ __metadata:s2-geometry: "npm:^1.2.10"styled-components: "npm:6.4.3"type-analyzer: "npm:0.4.0"+ viewport-mercator-project: "npm:^6.0.0"+ zarrita: "npm:^0.7.3"languageName: unknownlinkType: soft@@ -4479,6 +4570,7 @@ __metadata:version: 0.0.0-use.localresolution: "@kepler.gl/table@workspace:src/table"dependencies:+ "@developmentseed/geozarr": "npm:0.7.0""@kepler.gl/common-utils": "npm:3.3.0-alpha.18""@kepler.gl/constants": "npm:3.3.0-alpha.18""@kepler.gl/tasks-core": "npm:3.3.0-alpha.18"@@ -4498,6 +4590,7 @@ __metadata:global: "npm:^4.3.0"moment: "npm:^2.10.6"type-analyzer: "npm:0.4.0"+ zarrita: "npm:^0.7.3"languageName: unknownlinkType: soft@@ -11638,6 +11731,16 @@ __metadata:languageName: nodelinkType: hard+"@zarrita/storage@npm:^0.2.0":+ version: 0.2.0+ resolution: "@zarrita/storage@npm:0.2.0"+ dependencies:+ reference-spec-reader: "npm:^0.2.0"+ unzipit: "npm:2.0.0"+ checksum: 10c0/9f433cb8ab404741f05c842b57e03710cc8add4f58826a001099a7b0eff7f2bb3fd3a87c9c038655d479abc9a50368eaf0685898433e313c9cf587b6d51b03a8+ languageName: node+ linkType: hard+"@zkochan/js-yaml@npm:0.0.7":version: 0.0.7resolution: "@zkochan/js-yaml@npm:0.0.7"@@ -25539,6 +25642,15 @@ __metadata:languageName: nodelinkType: hard+"numcodecs@npm:^0.3.2":+ version: 0.3.2+ resolution: "numcodecs@npm:0.3.2"+ dependencies:+ fflate: "npm:^0.8.0"+ checksum: 10c0/38e6e60ee063f63f6530f78f9dd4c1b4e347989b29950ddcf3307e43579ad1bc1ba17a6faf0e5cb9786517ac1489c02ee86a77ca8c19fbd70d0d20a23e7d6a81+ languageName: node+ linkType: hard+"nwsapi@npm:^2.2.12, nwsapi@npm:^2.2.2":version: 2.2.12resolution: "nwsapi@npm:2.2.12"@@ -27416,6 +27528,21 @@ __metadata:languageName: nodelinkType: hard+"proj4@npm:^2.20.8":+ version: 2.22.0+ resolution: "proj4@npm:2.22.0"+ dependencies:+ mgrs: "npm:1.0.0"+ wkt-parser: "npm:^1.5.5"+ peerDependencies:+ geotiff: "*"+ peerDependenciesMeta:+ geotiff:+ optional: true+ checksum: 10c0/11452d48cda44ff6011e7af9879b4881d7010c7be763785c319819362bb13ffed986174f72cf540c8e3854691f573fcb7fe95d8a5cec3dddd2091f6f92e307a9+ languageName: node+ linkType: hard+"proj4@npm:^2.9.2":version: 2.12.1resolution: "proj4@npm:2.12.1"@@ -28688,6 +28815,13 @@ __metadata:languageName: nodelinkType: hard+"reference-spec-reader@npm:^0.2.0":+ version: 0.2.0+ resolution: "reference-spec-reader@npm:0.2.0"+ checksum: 10c0/8d966a0124978edf910aae10fcc56c13c2b66393ce0217819296ff1ff1b626754698c6edc4b2bfe6171acfac827979eb8ef7a884f521794798304be4a523ccd0+ languageName: node+ linkType: hard+"reflect-metadata@npm:^0.2.2":version: 0.2.2resolution: "reflect-metadata@npm:0.2.2"@@ -32919,6 +33053,13 @@ __metadata:languageName: nodelinkType: hard+"unzipit@npm:2.0.0":+ version: 2.0.0+ resolution: "unzipit@npm:2.0.0"+ checksum: 10c0/7ee6af8bf1b8a978c08cebbe65d7e0dfab8a0889d20ef89c1b2219389cad255074611f895242f34087cb0cf428719dd8251734d0e8fa4033c618c9ff21d67445+ languageName: node+ linkType: hard+"upath@npm:2.0.1":version: 2.0.1resolution: "upath@npm:2.0.1"@@ -33371,6 +33512,16 @@ __metadata:languageName: nodelinkType: hard+"viewport-mercator-project@npm:^6.0.0":+ version: 6.2.3+ resolution: "viewport-mercator-project@npm:6.2.3"+ dependencies:+ "@babel/runtime": "npm:^7.0.0"+ gl-matrix: "npm:^3.0.0"+ checksum: 10c0/787b02f89d60c4e71fd1faa9391853502339cc65159b7b3a70c4ee79f232187daad24e0e3694dded836cee9a69a19138981735361c50ac4172c15e4100c1891a+ languageName: node+ linkType: hard+"vinyl-fs@npm:^3.0.2":version: 3.0.3resolution: "vinyl-fs@npm:3.0.3"@@ -34044,7 +34195,14 @@ __metadata:languageName: nodelinkType: hard-"wkt-parser@npm:^1.2.4":+"wkt-parser@npm:1.5.5":+ version: 1.5.5+ resolution: "wkt-parser@npm:1.5.5"+ checksum: 10c0/4ed71c407a7f13b2ea49441f3e9607eb421fac513c384b71a52a33abbeafeeb67ab32ffce327894a2b276fadaa352f204c21d0a02e34183644fe41d3282fd735+ languageName: node+ linkType: hard++"wkt-parser@npm:^1.2.4, wkt-parser@npm:^1.5.5":version: 1.5.6resolution: "wkt-parser@npm:1.5.6"checksum: 10c0/67f938ffb6a1721dbc733823677327ff858a0a1f2f0d224e2ecbdf9e879f27764434dd6e44c89a2e94e3d37cc6e5f9874f878e4a1b1e2fd29a1279be38c322ca@@ -34515,6 +34673,16 @@ __metadata:languageName: nodelinkType: hard+"zarrita@npm:^0.7.3":+ version: 0.7.5+ resolution: "zarrita@npm:0.7.5"+ dependencies:+ "@zarrita/storage": "npm:^0.2.0"+ numcodecs: "npm:^0.3.2"+ checksum: 10c0/b2579c24869cc792ab49e77027d867bdde59c245b29c5182b86fc1b738ecccbcf8ec983bdf47f7d77d38d434d71197ea9ddf314ad290aa732d968a61119bb9dd+ languageName: node+ linkType: hard+"zod@npm:^3.24.1":version: 3.25.76resolution: "zod@npm:3.25.76"@@ -34536,6 +34704,13 @@ __metadata:languageName: nodelinkType: hard+"zod@npm:^4.4.3":+ version: 4.6.5+ resolution: "zod@npm:4.6.5"+ checksum: 10c0/32eb6c5e98becbe045675b2141c3611451c16ba567f9779231d79af41c4d651ca1c22f154aef7e6c6e77b929f23e43f1154ca05b82e119e922353725d6776af5+ languageName: node+ linkType: hard+"zstd-codec@npm:^0.1":version: 0.1.5resolution: "zstd-codec@npm:0.1.5"