Skip to content

Kepler.gl is a powerful open source geospatial analysis tool for large-scale data sets.

20.2 KB
Raw Blame
// SPDX-License-Identifier: MIT
// Copyright contributors to the kepler.gl project

import {Field, Millisecond, RGBColor} from './types';
import {ColorMap, ColorRange, ColorUI} from './layers';
import {MapSplitMode, MapViewMode} from '@kepler.gl/constants';
type MapViewState = {
  latitude: number;
  longitude: number;
  zoom: number;
  bearing?: number;
  pitch?: number;
  transitionDuration?: number;
  transitionInterpolator?: object;
};
import type {ExportResolutionOption} from '@kepler.gl/constants';

export type MapState = {
  pitch: number;
  bearing: number;
  latitude: number;
  longitude: number;
  zoom: number;
  dragRotate: boolean;
  width: number;
  height: number;
  minZoom?: number;
  maxZoom?: number;
  maxPitch?: number;
  maxBounds?: Bounds;
  initialState?: any;
  scale?: number;
  /** Layer rendering parameters forwarded from visState for use during layer construction in globe mode. */
  layerParameters?: Record<string, string | boolean>;

  // the following 4 properties assist with split viewports that can optionally have (un)synced viewports and zooms
  /**  Is the application split into 2 maps? */
  isSplit: boolean;
  /**  Are the 2 split maps having synced viewports? */
  isViewportSynced: boolean;
  /**  If split, are the zooms locked to each other or independent? */
  isZoomLocked: boolean;
  /**  An array of either 0 or 2 Viewport objects (index 0 for left map; index 1 for right map) */
  splitMapViewports: Viewport[];
  mapViewMode?: MapViewMode;
  globe?: {
    enabled: boolean;
    config: {
      atmosphere: boolean;
      hugeHalo: boolean;
      hugeHaloRadius: number;
      hugeHaloOpacity: number;
      azimuth: boolean;
      azimuthAngle: number;
      terminator: boolean;
      terminatorOpacity: number;
      basemap: boolean;
      labels: boolean;
      labelsColor: [number, number, number];
      adminLines: boolean;
      adminLinesColor: [number, number, number];
      water: boolean;
      waterColor: [number, number, number];
      surfaceColor: [number, number, number];
      surface: boolean;
      backgroundColor: [number, number, number];
      stars: boolean;
    };
  };
  /** The current split map mode (single, dual, swipe) */
  mapSplitMode: MapSplitMode;
  /** Swipe compare divider position as a percentage (0-100) */
  swipeComparePercentage: number;
};

export type Bounds = [number, number, number, number];

/**
 * Padding in pixels used when fitting the map viewport to bounds.
 * A number applies the same padding on all sides.
 */
export type ViewportPadding =
  | number
  | {
      top?: number;
      bottom?: number;
      left?: number;
      right?: number;
    };

export type RangeFieldDomain = {
  domain: number[];
  step: number;
  bins?: Bins;
};

export type SelectFieldDomain = {
  domain: boolean[];
};
export type MultiSelectFieldDomain = {
  domain: string[];
};

export type TimeRangeFieldDomain = {
  domain: [number, number];
  step: number;
  timeBins?: TimeBins;
  mappedValue: (Millisecond | null)[];
  // auto generated based on time domain
  defaultTimeFormat?: string | null;
  // custom ui input
  timeFormat?: string | null;
  // custom ui input
  timezone?: string | null;
};
export type FieldDomain =
  | RangeFieldDomain
  | TimeRangeFieldDomain
  | SelectFieldDomain
  | MultiSelectFieldDomain;

export interface LineDatum {
  x: number;
  y: number;
  delta: string;
  pct: number | null;
}

export type LineChartSeries = {
  lines: LineDatum[][];
  markers: LineDatum[];
  /** Stroke color for each line segment. Segments from one group share a color. */
  colors?: string[];
  /** Series name for each line segment. */
  names?: string[];
};

export type LineChartGroupBy = {
  fieldName: string;
  numGroups: number | 'ALL';
  groupOthers: boolean;
  colors: string[] | null;
  colorMap?: ColorMap | null;
};

export type PlotGroupBy = {
  fieldName?: string;
  numGroups: number | 'ALL';
  groupOthers: boolean;
  colorRange?: ColorRange;
  colorUI?: ColorUI;
};

export type LineChart = {
  series: {x: number; y: number}[] | LineChartSeries;
  yDomain: number[] | undefined[];
  xDomain: number[];

  // Is this a valid part of LineChart?
  aggregation: string;
  interval: string | number | null;
  yAxis: string;
  bins?: Bins | Bin[];
  /** Cache key for timeline series grouping. Null when the plot is a single series. */
  groupBy?: LineChartGroupBy | null;
};

type FilterViewType = 'side' | 'enlarged' | 'minified';

export type FilterBase<L extends LineChart> = {
  dataId: string[];
  id: string;
  enabled: boolean;
  /**
   * When true, rows that match the filter are hidden and the rest are kept.
   * Undefined is treated as false so older saved maps stay unchanged.
   */
  inverted?: boolean;

  // time range filter specific
  fixedDomain: boolean;
  view: FilterViewType;
  isAnimating: boolean;
  animationWindow?: string;
  speed: number;
  showTimeDisplay?: boolean;

  // field specific
  name: string[]; // string
  type: string | null;
  fieldIdx: number[]; // [integer]
  domain: any[] | null;
  value: any;
  mappedValue?: number[];

  // plot
  yAxis: Field | null;
  plotType: {
    [key: string]: any;
  };
  lineChart?: L;
  // gpu filter
  gpu: boolean;
  gpuChannel?: number[];
  gpuEndChannel?: number[];
  fieldType?: string;

  // Optional end timestamp for duration-based time filters (parallel to name/fieldIdx)
  endName?: (string | null | undefined)[];
  endFieldIdx?: (number | null | undefined)[];
  endMappedValue?: ((number | null)[] | null | undefined)[];

  // polygon
  layerId?: string[];
};

export type RangeFilter = FilterBase<LineChart> &
  RangeFieldDomain & {
    type: 'range';
    fieldType: 'real' | 'integer';
    value: [number, number];
    fixedDomain: true;
    typeOptions: ['range'];
    plotType: {
      [key: string]: any;
    };
  };

export type SelectFilter = FilterBase<LineChart> &
  SelectFieldDomain & {
    type: 'select';
    fieldType: 'boolean';
    value: boolean;
  };

export type MultiSelectFilter = FilterBase<LineChart> &
  MultiSelectFieldDomain & {
    type: 'multiSelect';
    fieldType: 'string' | 'date';
    value: string[];
  };

export type SyncTimelineMode = 0 | 1;

export type TimeRangeFilter = FilterBase<LineChart> &
  TimeRangeFieldDomain & {
    type: 'timeRange';
    fieldType: 'timestamp';
    fixedDomain: boolean;
    value: [number, number];
    plotType: {
      [key: string]: any;
    };
    syncedWithLayerTimeline: boolean;
    syncTimelineMode: SyncTimelineMode;
    animationWindow: string;
    invertTrendColor: boolean;
    /**
     * When set, a feature is visible while the playback window overlaps
     * [startField, endField] rather than requiring a single timestamp in range.
     */
    endName?: (string | null | undefined)[];
    endFieldIdx?: (number | null | undefined)[];
    endMappedValue?: ((number | null)[] | null | undefined)[];
    gpuEndChannel?: number[];
  };

export type PolygonFilter = FilterBase<LineChart> & {
  layerId: string[];
  type: 'polygon';
  fixedDomain: true;
  value: Feature;
};

export type Filter =
  | FilterBase<LineChart>
  | RangeFilter
  | TimeRangeFilter
  | SelectFilter
  | MultiSelectFilter
  | PolygonFilter;

export interface Bin {
  count: number;
  indexes: number[];
  x0: number;
  x1: number;
}

export interface Bins {
  [dataId: string]: Bin[];
}

export interface TimeBins {
  [dataId: string]: {
    [interval: string]: Bin[];
  };
}

export interface PlotType {
  interval: ValueOf<Interval>;
  numericInterval?: number;
  type: ValueOf<PlotTypes>;
  aggregation: ValueOf<AggregationTypes>;
  defaultTimeFormat: string;
  colorsByDataId?: {[dataId: string]: string};
  /** Categorical series split for the timeline line chart. */
  groupBy?: PlotGroupBy | null;
  yAxisAutoRange?: boolean;
}

export type Feature = {
  id: string;
  properties: any;
  geometry: {
    type: string;
    coordinates: any;
  };
  type?: string;
};
export type FeatureSelectionContext = {
  rightClick: boolean;
  position: {x: number; y: number};
  mapIndex?: number;
};
export type FeatureValue = {
  id: string;
  properties: {
    filterId: string;
  };
  geometry: {
    type: string;
    coordinates: any;
  };
};
export type Editor = {
  mode: string;
  features: Feature[];
  selectedFeature: any;
  selectionContext?: FeatureSelectionContext;
  visible: boolean;
};

export type SplitMapLayers = {[key: string]: boolean};
export type SplitMap = {
  id?: string;
  layers: SplitMapLayers;
};

export type LayerOrderGroup = {
  id: string;
  label: string;
  isVisible: boolean;
  layerOrder: LayerOrder;
  isIncludedInLegend: boolean;
};

export type LayerOrderEntry = string | LayerOrderGroup;
export type LayerOrder = LayerOrderEntry[];
export type FlatLayerOrder = string[];
export type LayerOrderHierarchyEntry = ['layer', any] | ['layerGroup', LayerOrderGroup];
export type LayerOrderHierarchy = LayerOrderHierarchyEntry[];

/** See "Locale aware formats" at https://momentjs.com/docs/#/parsing/string-format/ */
export type AnimationConfigTimeFormat = 'L' | 'L LT' | 'L LTS';

export type AnimationConfig = {
  domain: [number, number] | null;
  currentTime: number | null;
  speed: number;
  duration?: number | null;
  isAnimating?: boolean;
  timeSteps: number[] | null;
  // auto generated based on time domain
  defaultTimeFormat: AnimationTimeFormat | null;
  // custom ui input
  timeFormat?: AnimationTimeFormat | null;
  // custom ui input
  timezone?: string | null;
  // hide or show control
  hideControl?: boolean;
};

export type FilterAnimationConfig = Pick<Filter, 'dataId' | 'value' | 'speed'> &
  Required<Pick<Filter, 'animationWindow'>> &
  Partial<Pick<TimeRangeFilter, 'syncedWithLayerTimeline' | 'syncTimelineMode' | 'timezone'>>;

export type Timeline = {
  domain: [number, number] | null;
  value: number | [number, number];
  speed: number;
  isAnimating: boolean;
  step?: null | number;
  timeSteps?: null | number[];
  defaultTimeFormat?: null | string;
  timeFormat?: null | string;
  timezone?: null | string;
  timeBins?: null | Record<string, any>;
  animationWindow?: null | Filter['animationWindow'];
  marks?: null | number[];
} & Record<string, any>;

export type BaseInteraction = {
  label: string;
  enabled: boolean;
};
export type TooltipField = {
  name: string;
  format: string | null;
};
export type CompareType = string | null;
export type TooltipInfo = BaseInteraction & {
  id: 'tooltip';
  config: {
    fieldsToShow: {
      [key: string]: TooltipField[];
    };
    timezone?: string | null;
    compareMode: boolean;
    compareType: CompareType;
  };
};
export type Geocoder = BaseInteraction & {
  id: 'geocoder';
  position: number[] | null;
  config: {
    limitSearch: boolean;
    color: RGBColor;
  };
};
export type Brush = BaseInteraction & {
  id: 'brush';
  config: {
    size: number;
  };
};
export type Coordinate = BaseInteraction & {
  id: 'coordinate';
  position: number[] | null;
};
export type AnnotationInteraction = BaseInteraction & {
  id: 'annotation';
};
export type LegendInfo = BaseInteraction & {
  id: 'legend';
  config: {
    hideInvisibleLayers: boolean;
  };
};
/** Zoom stops for a fade envelope. Opacity is 0 outside [appear, gone]. */
export type ZoomOpacityStops = {
  /** Zoom where opacity leaves 0. */
  appear: number;
  /** Zoom where opacity reaches the layer's full opacity. */
  full: number;
  /** Zoom where opacity starts falling. */
  fade: number;
  /** Zoom where opacity returns to 0. */
  gone: number;
};
/** Layers and reserved map targets that share one zoom envelope. */
export type ZoomOpacityController = {
  id: string;
  layerIds: string[];
  stops: ZoomOpacityStops;
};
export type ZoomOpacityInteraction = BaseInteraction & {
  id: 'zoomOpacity';
  config: {
    controllers: ZoomOpacityController[];
  };
};
export type InteractionConfig = {
  tooltip: TooltipInfo;
  legend: LegendInfo;
  geocoder: Geocoder;
  brush: Brush;
  coordinate: Coordinate;
  annotation: AnnotationInteraction;
  zoomOpacity: ZoomOpacityInteraction;
};
export type MapInfo = {
  title?: string;
  description?: string;
};
/** Options captured when a file load starts and forwarded to `addDataToMap`. */
export type FileLoadingOptions = {
  autoCreateLayers?: boolean;
  /** Parse the files, then wait for an explicit add instead of calling `addDataToMap`. */
  deferAddToMap?: boolean;
};

export type FileLoading = {
  /** Identifies this load so a delayed finish from an older one can be ignored. */
  loadId: number;
  filesToLoad: FileList | File[];
  companionFiles?: File[];
  onFinish: (payload: any, options?: FileLoadingOptions) => any;
  fileCache: any[];
  options?: FileLoadingOptions;
};
export type FileLoadingProgress = {
  [key: string]: {
    percent: number;
    message: string;
    fileName: string;
    error: any;
  };
};

export type LayerGroup = {
  slug: string;
  filter(layer: {id: string}): boolean;
  defaultVisibility: boolean;
};

export type CustomStyleType =
  | 'LOCAL'
  | 'MANAGED'
  // boolean for backwards compatability with previous map configs
  | boolean;

export type BaseMapColorModes = 'NONE' | 'DARK' | 'LIGHT';

export type BaseMapStyle = {
  id: string;
  label: string;
  url: string;
  icon: string;
  style?: object;
  layerGroups: LayerGroup[];
  accessToken?: string;
  custom?: CustomStyleType;
  colorMode?: BaseMapColorModes;
  complimentaryStyleId?: string;
};

export declare type ExportImage = {
  ratio: EXPORT_IMG_RATIOS;
  resolution: ExportResolutionOption;
  legend: boolean;
  /** When true, include the charts panel in the exported image. */
  charts: boolean;
  /** When true, omit the basemap and preserve transparent pixels in the exported image. */
  transparentBackground?: boolean;
  mapH: number;
  mapW: number;
  imageSize: {
    zoomOffset: number;
    scale: number;
    imageW: number;
    imageH: number;
  };
  imageDataUri: string;
  exporting: boolean;
  processing: boolean;
  error: Error | false;
  center: boolean;
  escapeXhtmlForWebpack?: boolean;
  fileName: string;
};

export type ExportData = {
  selectedDataset: string;
  dataType: string;
  filtered: boolean;
};

export type ExportHtml = {
  exportMapboxAccessToken: null | string;
  userMapboxToken: string;
  mode: string;
};
export type ExportJson = {
  hasData: boolean;
};
export type ExportMap = {
  HTML: ExportHtml;
  JSON: ExportJson;
  format: 'HTML' | 'JSON';
  fileName: string;
  /** When false, dataset access tokens are omitted from exported HTML and JSON. */
  includeLayerApiKeys: boolean;
  /** Optional application name override for exported HTML and JSON. */
  appName?: string;
  /** Optional application website override for exported HTML and JSON. */
  appWebsite?: string;
  /** Optional application icon URL override for exported HTML and JSON. */
  appIcon?: string;
  /** Optional application name color override for exported HTML and JSON. */
  appNameColor?: string;
};

export type ExportVideo = {
  mediaType: string;
  cameraPreset: string;
  fileName: string;
  resolution: string;
  durationMs: number;
  swipeStartPct: number;
  swipeEndPct: number;
  swipeEasing: 'linear' | 'ease-in-out';
};

export type MapControlItem = {
  show: boolean;
  active: boolean;
  disableClose?: boolean;
  activeMapIndex?: number;
};

export type MapLegendControlSettings = {
  position: {
    x: number;
    y: number;
    anchorX: 'left' | 'right';
    anchorY: 'top' | 'bottom';
  };
  contentHeight: number;
};

export type MapControlMapLegend = MapControlItem & {
  disableEdit?: boolean;
  settings?: MapLegendControlSettings;
};
export type MapControls = {
  visibleLayers?: MapControlItem;
  mapLegend?: MapControlMapLegend;
  toggle3d?: MapControlItem;
  splitMap?: MapControlItem;
  mapDraw?: MapControlItem;
  mapLocale?: MapControlItem;
  mapTheme?: MapControlItem;
  effect?: MapControlItem;
  annotation?: MapControlItem;
  chart?: MapControlItem;
  viewportJson?: MapControlItem;
  mapInfo?: MapControlItem;
  sqlPanel?: MapControlItem;
  aiAssistant?: MapControlItem;
  [key: string]: MapControlItem | MapControlMapLegend | undefined;
};

export type LoadFiles = {
  fileLoading: boolean;
};

export type Notifications = {
  message: string;
  type: string;
  topic: string;
  id: string;
  count: number;
  isExpanded?: boolean;
};

export type Locale = string;

export type UiTheme = string;

export type PanelListView = string;

export type UiState = {
  readOnly: boolean;
  activeSidePanel: string | null;
  currentModal: string | null;
  datasetKeyToRemove: string | null;
  /** Dataset selected by the dataset-menu Replace action. Cleared when the modal closes. */
  datasetToReplaceId: string | null;
  visibleDropdown: string | null;
  // export image modal ui
  exportImage: ExportImage;
  // export data modal ui
  exportData: ExportData;
  // html export
  exportMap: ExportMap;
  // export video modal ui
  exportVideo: ExportVideo;
  // map control panels
  mapControls: MapControls;
  // ui notifications
  notifications: Notifications[];
  // load files
  loadFiles: LoadFiles;
  // Locale of the UI
  locale: Locale;
  // Theme of the UI (`light` | `dark` | `space`). First of `themes` is the default when set.
  theme: UiTheme;
  // view layers by list or dataset
  layerPanelListView: PanelListView;
  // view filters by list or dataset
  filterPanelListView: PanelListView;
  // side panel close button visibility
  isSidePanelCloseButtonVisible: boolean | null;
  // positive value indicates that something is loading
  loadingIndicatorValue?: number;
};

/** Width of viewport */
export type Viewport = {
  /**  Width of viewport */
  width?: number;
  /**  Height of viewport */
  height?: number;
  /**  Zoom of viewport */
  zoom?: number;
  /**  Camera angle in degrees (0 is straight down) */
  pitch?: number;
  /**  Map rotation in degrees (0 means north is up) */
  bearing?: number;
  /**  Latitude center of viewport on map in mercator projection */
  latitude?: number;
  /**  Longitude Center of viewport on map in mercator projection */
  longitude?: number;
  /**  Whether to enable drag and rotate map into perspective viewport */
  dragRotate?: boolean;
  /**  Minimum allowed viewport zoom */
  minZoom?: number;
  /**  Maximum allowed viewport zoom */
  maxZoom?: number;
  /**  Maximum pitch angle in degrees */
  maxPitch?: number;
  /**  Maximum geographical bounds, pan/zoom operations are constrained within those bounds */
  maxBounds?: Bounds;
  /** viewport transition duration use by geocoder panel **/
  transitionDuration?: MapViewState['transitionDuration'];
  /** viewport transition duration use by geocoder panel **/
  transitionInterpolator?: MapViewState['transitionInterpolator'];
};

export type MapStyles = {
  [key: string]: BaseMapStyle;
};

export type VisibleLayerGroups = {
  [key: string]: boolean;
};

export type InputStyle = {
  id?: string | null;
  accessToken: string | null;
  error: boolean;
  isValid: boolean;
  label: string | null;
  style: any | null;
  url: string | null;
  icon: string | null;
  custom: CustomStyleType;
  uploadedFile: File | null;
};

export type FilterRecord = {
  dynamicDomain: Filter[];
  fixedDomain: Filter[];
  cpu: Filter[];
  gpu: Filter[];
};

export type FilterDatasetOpt = {
  // only allow cpu filtering
  cpuOnly?: boolean;
  // ignore filter for domain calculation
  ignoreDomain?: boolean;
};

/* DUPLICATES OF FILTER TYPES ABOVE, REMOVE ONCE TYPES ABOVE ARE FIXED */

type FilterBaseOmitRedudant = Omit<FilterBase<LineChart>, 'type' | 'domain'>;

export type TypedRangeFilter = FilterBaseOmitRedudant &
  RangeFieldDomain & {
    type: 'range';
    fieldType: 'real' | 'integer';
    value: [number, number];
    fixedDomain: true;
    typeOptions: ['range'];
  };

export type TypedSelectFilter = FilterBaseOmitRedudant &
  SelectFieldDomain & {
    type: 'select';
    fieldType: 'boolean';
    value: boolean;
  };

export type TypedMultiSelectFilter = FilterBaseOmitRedudant &
  MultiSelectFieldDomain & {
    type: 'multiSelect';
    fieldType: 'string' | 'date';
    value: string[];
  };

export type TypedTimeRangeFilter = FilterBaseOmitRedudant &
  TimeRangeFieldDomain & {
    type: 'timeRange';
    fieldType: 'timestamp';
    fixedDomain: true;
    value: [number, number];
    plotType: {
      [key: string]: any;
    };
    animationWindow: string;
    invertTrendColor: boolean;
  };

export type TypedPolygonFilter = FilterBaseOmitRedudant & {
  layerId: string[];
  type: 'polygon';
  fixedDomain: true;
  value: Feature;
};

export type TypedFilter =
  | TypedRangeFilter
  | TypedTimeRangeFilter
  | TypedSelectFilter
  | TypedMultiSelectFilter
  | TypedPolygonFilter;