Skip to content

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

feat: load CSV, GeoJSON, Arrow, and Parquet from a remote URL (#3662)

Igor Dykhta7dec2e70885e
diff --git a/src/components/src/common/file-uploader/file-upload.tsx b/src/components/src/common/file-uploader/file-upload.tsx
index 9523581be..7da590359 100644
--- a/src/components/src/common/file-uploader/file-upload.tsx
+++ b/src/components/src/common/file-uploader/file-upload.tsx
@@ -10,13 +10,18 @@ import FileUploadProgress from './file-upload-progress';
import FileDrop from './file-drop';
import {FileLoading, FileLoadingProgress} from '@kepler.gl/types';
-import {isChrome} from '@kepler.gl/utils';
-import {GUIDES_FILE_FORMAT_DOC} from '@kepler.gl/constants';
-import Markdown from 'markdown-to-jsx';
-// Breakpoints
+import {GUIDES_FILE_FORMAT_DOC, REMOTE_FILE_FORMATS} from '@kepler.gl/constants';
import {FormattedMessage} from '@kepler.gl/localization';
+import {
+ fetchRemoteFileAsKeplerFile,
+ getFileNameForRemoteUrl,
+ isRemoteDatasetUrl
+} from '@kepler.gl/processors';
import {media} from '@kepler.gl/styles';
+import {isChrome, getApplicationConfig} from '@kepler.gl/utils';
+import Markdown from 'markdown-to-jsx';
+import {Button, InputLight} from '../styled-components';
import LinkRenderer from '../link-renderer';
const fileIconColor = '#D3D8E0';
@@ -49,51 +54,54 @@ const StyledFileDrop = styled.div<StyledFileDropProps>`
border-color: ${props => (props.$dragOver ? props.theme.textColorLT : props.theme.subtextColorLT)};
text-align: center;
width: 100%;
- padding: 48px 8px 0;
- height: 360px;
-
- .file-upload-or {
- color: ${props => props.theme.linkBtnColor};
- padding-right: 4px;
- }
+ min-height: 360px;
+ padding: 24px 12px 16px;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
.file-type-row {
opacity: 0.5;
}
${media.portable`
- padding: 16px 4px 0;
+ padding: 16px 8px 12px;
+ min-height: 280px;
`};
`;
-const MsgWrapper = styled.div`
+const StyledDropBody = styled.div`
+ flex: 1;
+ width: 100%;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: space-evenly;
+`;
+
+const StyledActionLine = styled.div`
color: ${props => props.theme.modalTitleColor};
- font-size: 20px;
- height: 36px;
+ font-size: 14px;
+ font-weight: 600;
+ line-height: 20px;
+
+ .upload-button {
+ font-size: 14px;
+ font-weight: 600;
+ color: ${props => props.theme.linkBtnColor};
+ text-decoration: none;
+ }
`;
const StyledDragNDropIcon = styled.div`
color: ${fileIconColor};
- margin-bottom: 48px;
-
display: flex;
+ flex-direction: column;
+ align-items: center;
justify-content: center;
-
- ${media.portable`
- margin-bottom: 16px;
- `};
- ${media.palm`
- margin-bottom: 8px;
- `};
`;
const StyledFileTypeFow = styled.div`
- margin-bottom: 24px;
- ${media.portable`
- margin-bottom: 16px;
- `};
- ${media.palm`
- margin-bottom: 8px;
- `};
+ width: 100%;
`;
const StyledFileUpload = styled.div`
@@ -117,19 +125,95 @@ const StyledMessage = styled.div`
`;
const StyledDragFileWrapper = styled.div`
- margin-bottom: 32px;
- ${media.portable`
- margin-bottom: 24px;
- `};
- ${media.portable`
- margin-bottom: 16px;
- `};
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ width: 100%;
`;
const StyledDisclaimer = styled(StyledMessage)`
- margin: 0 auto;
+ flex-shrink: 0;
+ margin: 12px 12px 0;
+`;
+
+const StyledRemoteUrlForm = styled.div`
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ gap: 4px;
+ width: 100%;
+ max-width: 420px;
+ margin: 8px auto 0;
`;
+const StyledRemoteUrlRow = styled.div`
+ display: flex;
+ flex-direction: row;
+ gap: 8px;
+ align-items: stretch;
+ justify-content: center;
+ width: 100%;
+`;
+
+const StyledRemoteUrlInput = styled(InputLight)`
+ flex: 1;
+ min-width: 0;
+ max-width: 300px;
+`;
+
+const StyledRemoteFormatSelect = styled.select`
+ ${props => props.theme.inputLT};
+ width: 88px;
+ flex-shrink: 0;
+ height: auto;
+ box-sizing: border-box;
+ padding: 0 6px;
+ cursor: pointer;
+`;
+
+const StyledRemoteFetchButton = styled(Button)`
+ height: auto;
+ box-sizing: border-box;
+ padding: 0 12px;
+ flex-shrink: 0;
+`;
+
+const REMOTE_DOWNLOAD_SHARE = 0.85;
+
+function scaleFileProgress(
+ progress: FileLoadingProgress,
+ start: number,
+ end: number
+): FileLoadingProgress {
+ return Object.keys(progress).reduce<FileLoadingProgress>((accu, key) => {
+ const item = progress[key];
+ accu[key] = {
+ ...item,
+ percent: start + (item.percent || 0) * (end - start)
+ };
+ return accu;
+ }, {});
+}
+
+function getCombinedLoadProgress({
+ fileLoading,
+ fileLoadingProgress,
+ remoteProgress
+}: {
+ fileLoading: FileLoading | false;
+ fileLoadingProgress: FileLoadingProgress;
+ remoteProgress: FileLoadingProgress;
+}): FileLoadingProgress {
+ const isRemoteFetch = Object.keys(remoteProgress).length > 0;
+ if (!isRemoteFetch) {
+ return fileLoadingProgress;
+ }
+ if (fileLoading) {
+ return scaleFileProgress(fileLoadingProgress, REMOTE_DOWNLOAD_SHARE, 1);
+ }
+ return scaleFileProgress(remoteProgress, 0, REMOTE_DOWNLOAD_SHARE);
+}
+
type FileUploadProps = {
onFileUpload: (files: File[]) => void;
fileLoading: FileLoading | false;
@@ -143,25 +227,45 @@ type FileUploadProps = {
disableExtensionFilter?: boolean;
} & WrappedComponentProps;
+type FileUploadState = {
+ dragOver: boolean;
+ fileLoading: FileLoading | false;
+ files: File[];
+ errorFiles: string[];
+ remoteUrl: string;
+ remoteFormat: string;
+ remoteError: {message: string} | null;
+ remoteLoading: boolean;
+ remoteProgress: FileLoadingProgress;
+};
+
function FileUploadFactory() {
/** @augments {Component<FileUploadProps>} */
- class FileUpload extends Component<FileUploadProps> {
- state = {
+ class FileUpload extends Component<FileUploadProps, FileUploadState> {
+ state: FileUploadState = {
dragOver: false,
fileLoading: false,
files: [],
- errorFiles: []
+ errorFiles: [],
+ remoteUrl: '',
+ remoteFormat: 'auto',
+ remoteError: null,
+ remoteLoading: false,
+ remoteProgress: {}
};
static getDerivedStateFromProps(props, state) {
if (state.fileLoading && props.fileLoading === false && state.files.length) {
return {
files: [],
- fileLoading: props.fileLoading
+ fileLoading: props.fileLoading,
+ remoteLoading: false,
+ remoteProgress: {}
};
}
return {
- fileLoading: props.fileLoading
+ fileLoading: props.fileLoading,
+ ...(props.fileLoading ? {remoteLoading: false} : {})
};
}
@@ -206,10 +310,104 @@ function FileUploadFactory() {
this.setState({dragOver: newState});
};
+ _onRemoteUrlChange = (event: React.ChangeEvent<HTMLInputElement>) => {
+ const remoteUrl = event.target.value;
+ this.setState({
+ remoteUrl,
+ remoteError: remoteUrl && !isRemoteDatasetUrl(remoteUrl) ? {message: 'Incorrect URL'} : null
+ });
+ };
+
+ _onRemoteFormatChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
+ this.setState({remoteFormat: event.target.value});
+ };
+
+ _onRemoteUrlKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
+ if (event.key === 'Enter') {
+ event.preventDefault();
+ this._handleLoadRemoteFile();
+ }
+ };
+
+ _handleLoadRemoteFile = async () => {
+ const {remoteUrl, remoteFormat, remoteError} = this.state;
+ const {intl} = this.props;
+ const showFormatSelector = getApplicationConfig().enableRemoteFileFormatSelector;
+ const format =
+ showFormatSelector && remoteFormat !== 'auto' ? remoteFormat : undefined;
+ if (!remoteUrl || remoteError || this.state.remoteLoading) {
+ if (!remoteUrl) {
+ this.setState({remoteError: {message: 'Incorrect URL'}});
+ }
+ return;
+ }
+ if (!isRemoteDatasetUrl(remoteUrl)) {
+ this.setState({remoteError: {message: 'Incorrect URL'}});
+ return;
+ }
+
+ const fileName = getFileNameForRemoteUrl(remoteUrl, format);
+ const downloading = intl.formatMessage({id: 'fileUploader.downloading'});
+ this.setState({
+ remoteLoading: true,
+ remoteError: null,
+ remoteProgress: {
+ [fileName]: {
+ fileName,
+ percent: 0,
+ message: downloading,
+ error: null
+ }
+ }
+ });
+
+ try {
+ let lastUpdate = 0;
+ const file = await fetchRemoteFileAsKeplerFile(remoteUrl, format, ({percent}) => {
+ const now = Date.now();
+ if (percent < 1 && now - lastUpdate < 100) {
+ return;
+ }
+ lastUpdate = now;
+ this.setState(prev => {
+ const name = Object.keys(prev.remoteProgress)[0] || fileName;
+ return {
+ remoteProgress: {
+ [name]: {
+ fileName: name,
+ percent,
+ message: downloading,
+ error: null
+ }
+ }
+ };
+ });
+ });
+ this.setState(
+ {
+ files: [file],
+ errorFiles: [],
+ dragOver: false
+ },
+ () => this.props.onFileUpload([file])
+ );
+ } catch (error) {
+ this.setState({
+ remoteLoading: false,
+ remoteProgress: {},
+ remoteError: {
+ message: error instanceof Error ? error.message : `Failed to load ${remoteUrl}`
+ }
+ });
+ }
+ };
+
render() {
- const {dragOver, files, errorFiles} = this.state;
+ const {dragOver, files, errorFiles, remoteUrl, remoteFormat, remoteError, remoteLoading, remoteProgress} =
+ this.state;
const {fileLoading, fileLoadingProgress, theme, intl} = this.props;
const {fileExtensions = [], fileFormatNames = []} = this.props;
+ const showFormatSelector = getApplicationConfig().enableRemoteFileFormatSelector;
const fileUploadInfoText = `${intl.formatMessage(
{
id: 'fileUploader.configUploadMessage'
@@ -242,50 +440,106 @@ function FileUploadFactory() {
</Markdown>
</StyledUploadMessage>
<StyledFileDrop $dragOver={dragOver}>
- <StyledFileTypeFow className="file-type-row">
- {fileExtensions.map(ext => (
- <FileType key={ext} ext={ext} height="50px" fontSize="9px" />
- ))}
- </StyledFileTypeFow>
- {fileLoading ? (
- <FileUploadProgress fileLoadingProgress={fileLoadingProgress} theme={theme} />
- ) : (
- <>
- <div
- style={{opacity: dragOver ? 0.5 : 1}}
- className="file-upload-display-message"
- >
- <StyledDragNDropIcon>
- <DragNDrop height="44px" />
+ <StyledDropBody>
+ <StyledFileTypeFow className="file-type-row">
+ {fileExtensions.map(ext => (
+ <FileType key={ext} ext={ext} height="50px" fontSize="9px" />
+ ))}
+ </StyledFileTypeFow>
+ {fileLoading || remoteLoading ? (
+ <FileUploadProgress
+ fileLoadingProgress={getCombinedLoadProgress({
+ fileLoading,
+ fileLoadingProgress,
+ remoteProgress
+ })}
+ theme={theme}
+ />
+ ) : (
+ <>
+ <StyledDragNDropIcon
+ style={{opacity: dragOver ? 0.5 : 1}}
+ className="file-upload-display-message"
+ >
+ <DragNDrop height="36px" />
+ {errorFiles.length ? (
+ <WarningMsg>
+ <FormattedMessage
+ id={'fileUploader.fileNotSupported'}
+ values={{errorFiles: errorFiles.join(', ')}}
+ />
+ </WarningMsg>
+ ) : null}
</StyledDragNDropIcon>
-
- {errorFiles.length ? (
- <WarningMsg>
- <FormattedMessage
- id={'fileUploader.fileNotSupported'}
- values={{errorFiles: errorFiles.join(', ')}}
- />
- </WarningMsg>
+ {!files.length ? (
+ <StyledDragFileWrapper>
+ <StyledActionLine>
+ <FormattedMessage
+ id={'fileUploader.dropMessage'}
+ values={{
+ browse: (
+ <UploadButton key="browse" onUpload={this._handleFileInput}>
+ {intl.formatMessage({id: 'fileUploader.browseFiles'})}
+ </UploadButton>
+ )
+ }}
+ />
+ </StyledActionLine>
+ <StyledRemoteUrlForm
+ className="file-uploader__remote-url"
+ onClick={event => event.stopPropagation()}
+ >
+ <StyledRemoteUrlRow>
+ <StyledRemoteUrlInput
+ type="url"
+ value={remoteUrl}
+ aria-label={intl.formatMessage({
+ id: 'fileUploader.urlPlaceholder'
+ })}
+ placeholder={intl.formatMessage({
+ id: 'fileUploader.urlPlaceholder'
+ })}
+ onChange={this._onRemoteUrlChange}
+ onKeyDown={this._onRemoteUrlKeyDown}
+ disabled={remoteLoading}
+ />
+ {showFormatSelector ? (
+ <StyledRemoteFormatSelect
+ aria-label={intl.formatMessage({id: 'fileUploader.format'})}
+ value={remoteFormat}
+ onChange={this._onRemoteFormatChange}
+ disabled={remoteLoading}
+ >
+ {REMOTE_FILE_FORMATS.map(format => (
+ <option key={format} value={format}>
+ {format === 'auto'
+ ? intl.formatMessage({id: 'fileUploader.formatAuto'})
+ : format.toUpperCase()}
+ </option>
+ ))}
+ </StyledRemoteFormatSelect>
+ ) : null}
+ <StyledRemoteFetchButton
+ type="button"
+ cta
+ small
+ disabled={!remoteUrl || remoteLoading}
+ onClick={this._handleLoadRemoteFile}
+ >
+ <FormattedMessage id={'fileUploader.fetch'} />
+ </StyledRemoteFetchButton>
+ </StyledRemoteUrlRow>
+ {remoteError ? <WarningMsg>{remoteError.message}</WarningMsg> : null}
+ </StyledRemoteUrlForm>
+ </StyledDragFileWrapper>
) : null}
- </div>
- {!files.length ? (
- <StyledDragFileWrapper>
- <MsgWrapper>
- <FormattedMessage id={'fileUploader.message'} />
- </MsgWrapper>
- <span className="file-upload-or">
- <FormattedMessage id={'fileUploader.or'} />
- </span>
- <UploadButton onUpload={this._handleFileInput}>
- <FormattedMessage id={'fileUploader.browseFiles'} />
- </UploadButton>
- </StyledDragFileWrapper>
- ) : null}
-
- <StyledDisclaimer>
- <FormattedMessage id={'fileUploader.disclaimer'} />
- </StyledDisclaimer>
- </>
+ </>
+ )}
+ </StyledDropBody>
+ {fileLoading || remoteLoading ? null : (
+ <StyledDisclaimer>
+ <FormattedMessage id={'fileUploader.disclaimer'} />
+ </StyledDisclaimer>
)}
</StyledFileDrop>
</FileDrop>
diff --git a/src/components/src/modals/load-data-modal.tsx b/src/components/src/modals/load-data-modal.tsx
index 4bcfd24bd..c456c2c61 100644
--- a/src/components/src/modals/load-data-modal.tsx
+++ b/src/components/src/modals/load-data-modal.tsx
@@ -19,7 +19,7 @@ const StyledLoadDataModal = styled.div.attrs({
className: 'load-data-modal'
})`
padding: ${props => props.theme.modalPadding};
- min-height: 440px;
+ min-height: 360px;
display: flex;
flex-direction: column;
`;
diff --git a/src/components/src/side-panel/common/dataset-info.tsx b/src/components/src/side-panel/common/dataset-info.tsx
index 1a8d27f98..495b79a2b 100644
--- a/src/components/src/side-panel/common/dataset-info.tsx
+++ b/src/components/src/side-panel/common/dataset-info.tsx
@@ -41,6 +41,8 @@ export default function DatasetInfoFactory() {
? 'datasetInfo.tile3d'
: dataset.type === DatasetType.BITMAP
? 'datasetInfo.bitmap'
+ : dataset.type === DatasetType.EXTERNALLY_HOSTED
+ ? 'datasetInfo.remoteFile'
: 'datasetInfo.rowCount'
}
values={{rowCount: numFormat(dataset.dataContainer.numRows())}}
diff --git a/src/constants/src/dataset.ts b/src/constants/src/dataset.ts
index 60533a086..e18509a1b 100644
--- a/src/constants/src/dataset.ts
+++ b/src/constants/src/dataset.ts
@@ -3,6 +3,7 @@
export enum DatasetType {
LOCAL = 'local',
+ EXTERNALLY_HOSTED = 'externally-hosted',
VECTOR_TILE = 'vector-tile',
RASTER_TILE = 'raster-tile',
WMS_TILE = 'wms-tile',
@@ -10,6 +11,71 @@ export enum DatasetType {
BITMAP = 'bitmap'
}
+export const REMOTE_FILE_FORMATS = ['auto', 'csv', 'geojson', 'json', 'arrow', 'parquet'] as const;
+export type RemoteFileFormat = (typeof REMOTE_FILE_FORMATS)[number];
+
+export const REMOTE_FILE_MIME_TYPES: Record<Exclude<RemoteFileFormat, 'auto'>, string> = {
+ csv: 'text/csv',
+ geojson: 'application/geo+json',
+ json: 'application/json',
+ arrow: 'application/vnd.apache.arrow.file',
+ parquet: 'application/vnd.apache.parquet'
+};
+
+export const REMOTE_FILE_EXTENSIONS: Record<Exclude<RemoteFileFormat, 'auto'>, string> = {
+ csv: 'csv',
+ geojson: 'geojson',
+ json: 'json',
+ arrow: 'arrow',
+ parquet: 'parquet'
+};
+
+export const MIME_TO_REMOTE_FILE_EXTENSION: Record<string, string> = {
+ 'text/csv': 'csv',
+ 'text/tab-separated-values': 'tsv',
+ 'application/geo+json': 'geojson',
+ 'application/vnd.geo+json': 'geojson',
+ 'application/json': 'json',
+ 'application/vnd.apache.arrow.file': 'arrow',
+ 'application/vnd.apache.arrow.stream': 'arrow',
+ 'application/vnd.apache.parquet': 'parquet',
+ 'application/x-parquet': 'parquet'
+};
+
+export type ExternalDatasetMetadata = {
+ /** Remote URL of the dataset file. */
+ source: string;
+ /** Optional format hint for extensionless URLs (SAS keys, etc). */
+ format?: Exclude<RemoteFileFormat, 'auto'> | string;
+ /** Last known size of the hosted resource, in bytes. */
+ size?: number;
+};
+
+/** Runtime copy of {@link ExternalDatasetMetadata} with `format` renamed to avoid colliding with DATASET_FORMATS. */
+export type ExternalDatasetRuntimeMetadata = {
+ source: string;
+ sourceFormat?: Exclude<RemoteFileFormat, 'auto'> | string;
+ size?: number;
+};
+
+export function getRemoteSourceFormat(metadata?: {
+ sourceFormat?: unknown;
+ format?: unknown;
+}): string | undefined {
+ const candidate =
+ (typeof metadata?.sourceFormat === 'string' && metadata.sourceFormat) ||
+ (typeof metadata?.format === 'string' && metadata.format) ||
+ undefined;
+ if (
+ candidate &&
+ candidate !== 'auto' &&
+ Object.prototype.hasOwnProperty.call(REMOTE_FILE_EXTENSIONS, candidate)
+ ) {
+ return candidate;
+ }
+ return undefined;
+}
+
export enum RemoteTileFormat {
MVT = 'mvt',
PMTILES = 'pmtiles',
diff --git a/src/localization/src/formatted-message.tsx b/src/localization/src/formatted-message.tsx
index c7b33755b..32e4281c1 100644
--- a/src/localization/src/formatted-message.tsx
+++ b/src/localization/src/formatted-message.tsx
@@ -9,7 +9,7 @@ type EnhancedFormattedMessageProps = {
defaultMessage?: string;
defaultValue?: string;
values?: {
- [key: string]: string | number | null;
+ [key: string]: React.ReactNode;
};
children?: (chunks: React.ReactNode[]) => React.ReactElement;
};
diff --git a/src/localization/src/translations/ca.ts b/src/localization/src/translations/ca.ts
index 25d0c122a..a9622125e 100644
--- a/src/localization/src/translations/ca.ts
+++ b/src/localization/src/translations/ca.ts
@@ -297,7 +297,8 @@ export default {
vectorTile: 'Mosaic vectorial',
rasterTile: 'Mosaic ràster',
wmsTile: 'Mosaic WMS',
- tile3d: 'Mosaic 3D'
+ tile3d: 'Mosaic 3D',
+ remoteFile: '{rowCount} files (remot)'
},
tooltip: {
hideLayer: 'oculta la capa',
@@ -687,8 +688,15 @@ export default {
'Carrega {fileFormatNames} o un mapa desat en **Json**. Més informació sobre [**supported file formats**]',
browseFiles: 'navega pels teus arxius',
uploading: 'Carregant',
+ downloading: 'Descarregant',
fileNotSupported: "L'arxiu {errorFiles} no és compatible.",
- or: 'o'
+ or: 'o',
+ dropMessage: "Arrossega i deixa anar l'arxiu aquí, {browse}, o",
+ urlPlaceholder: 'Introdueix l’URL del conjunt de dades',
+ fetch: 'Carrega',
+ format: 'Format',
+ formatAuto: 'Auto',
+ cors: 'L’URL ha de permetre [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS).'
},
tilesetSetup: {
header: 'Configurar mosaics vectorials',
diff --git a/src/localization/src/translations/cn.ts b/src/localization/src/translations/cn.ts
index d79812555..a15097005 100644
--- a/src/localization/src/translations/cn.ts
+++ b/src/localization/src/translations/cn.ts
@@ -284,7 +284,8 @@ export default {
vectorTile: '矢量瓦片',
rasterTile: '栅格瓦片',
wmsTile: 'WMS瓦片',
- tile3d: '3D瓦片'
+ tile3d: '3D瓦片',
+ remoteFile: '{rowCount}行(远程)'
},
tooltip: {
hideLayer: '隐藏图层',
@@ -669,8 +670,15 @@ export default {
'上传 {fileFormatNames} 或保存的地图 **Json**。阅读更多关于[**支持的文件格式**]',
browseFiles: '浏览你的文件',
uploading: '上传',
+ downloading: '下载中',
fileNotSupported: '不支持文件 {errorFiles}。',
- or: '或'
+ or: '或',
+ dropMessage: '将您的文件拖放到此处,{browse},或',
+ urlPlaceholder: '输入数据集 URL',
+ fetch: '获取',
+ format: '格式',
+ formatAuto: '自动',
+ cors: 'URL 必须允许 [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS)。'
},
tilesetSetup: {
header: '设置矢量瓦片',
diff --git a/src/localization/src/translations/en.ts b/src/localization/src/translations/en.ts
index cfdf7915d..762c48a92 100644
--- a/src/localization/src/translations/en.ts
+++ b/src/localization/src/translations/en.ts
@@ -342,7 +342,8 @@ export default {
rasterTile: 'Raster tile',
wmsTile: 'WMS tile',
tile3d: '3D tile',
- bitmap: 'Bitmap image'
+ bitmap: 'Bitmap image',
+ remoteFile: '{rowCount} rows (remote)'
},
tooltip: {
hideLayer: 'Hide layer',
@@ -796,8 +797,15 @@ ${'```'}
'Upload {fileFormatNames} or saved map **Json**. Read more about [**supported file formats**]',
browseFiles: 'browse your files',
uploading: 'Uploading',
+ downloading: 'Downloading',
fileNotSupported: 'File {errorFiles} is not supported.',
- or: 'or'
+ or: 'or',
+ dropMessage: 'Drag & Drop Your File(s) Here, {browse}, or',
+ urlPlaceholder: 'Enter your dataset URL',
+ fetch: 'Fetch',
+ format: 'Format',
+ formatAuto: 'Auto',
+ cors: 'The URL must allow [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS).'
},
tilesetSetup: {
header: 'Setup Vector Tiles',
diff --git a/src/localization/src/translations/es.ts b/src/localization/src/translations/es.ts
index ca38601fa..d5462ef18 100644
--- a/src/localization/src/translations/es.ts
+++ b/src/localization/src/translations/es.ts
@@ -298,7 +298,8 @@ export default {
vectorTile: 'Mosaico vectorial',
rasterTile: 'Mosaico ráster',
wmsTile: 'Mosaico WMS',
- tile3d: 'Mosaico 3D'
+ tile3d: 'Mosaico 3D',
+ remoteFile: '{rowCount} filas (remoto)'
},
tooltip: {
hideLayer: 'Ocultar la capa',
@@ -688,8 +689,15 @@ export default {
'Cargar {fileFormatNames} o un mapa guardado en **Json**. Más información sobre [**supported file formats**]',
browseFiles: 'navega por tus archivos',
uploading: 'Cargando',
+ downloading: 'Descargando',
fileNotSupported: 'El archivo {errorFiles} no es compatible.',
- or: 'o'
+ or: 'o',
+ dropMessage: 'Arrastra y suelta el archivo aquí, {browse}, o',
+ urlPlaceholder: 'Introduce la URL del conjunto de datos',
+ fetch: 'Cargar',
+ format: 'Formato',
+ formatAuto: 'Auto',
+ cors: 'La URL debe permitir [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS).'
},
tilesetSetup: {
header: 'Configurar mosaicos vectoriales',
diff --git a/src/localization/src/translations/fi.ts b/src/localization/src/translations/fi.ts
index 04f1e24d9..0b7547075 100644
--- a/src/localization/src/translations/fi.ts
+++ b/src/localization/src/translations/fi.ts
@@ -296,7 +296,8 @@ export default {
vectorTile: 'Vektoritiili',
rasterTile: 'Rasteritiili',
wmsTile: 'WMS-tiili',
- tile3d: '3D-tiili'
+ tile3d: '3D-tiili',
+ remoteFile: '{rowCount} riviä (etä)'
},
tooltip: {
hideLayer: 'Piilota taso',
@@ -685,8 +686,15 @@ export default {
'Lisää {fileFormatNames} tai tallennettu kartta **Json**. Lue lisää [**tuetuista formaateista**]',
browseFiles: 'selaa tiedostojasi',
uploading: 'ladataan',
+ downloading: 'Ladataan',
fileNotSupported: 'Tiedosto {errorFiles} ei ole tuettu.',
- or: 'tai'
+ or: 'tai',
+ dropMessage: 'Raahaa ja pudota tiedostosi tänne, {browse} tai',
+ urlPlaceholder: 'Syötä aineiston URL',
+ fetch: 'Hae',
+ format: 'Muoto',
+ formatAuto: 'Auto',
+ cors: 'URL-osoitteen on sallittava [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS).'
},
density: 'tiheys',
'Bug Report': 'Bugiraportointi',
diff --git a/src/localization/src/translations/ja.ts b/src/localization/src/translations/ja.ts
index 0389c4112..696eb6a8e 100644
--- a/src/localization/src/translations/ja.ts
+++ b/src/localization/src/translations/ja.ts
@@ -295,7 +295,8 @@ export default {
vectorTile: 'ベクタータイル',
rasterTile: 'ラスタータイル',
wmsTile: 'WMSタイル',
- tile3d: '3Dタイル'
+ tile3d: '3Dタイル',
+ remoteFile: '{rowCount}行(リモート)'
},
tooltip: {
hideLayer: 'レイヤを非表示',
@@ -684,8 +685,15 @@ export default {
'{fileFormatNames} または保存済地図の**Json**をアップロードします。詳細は以下を参照してください:[**対応ファイル形式**]',
browseFiles: 'デバイスのファイルを選択',
uploading: 'アップロード中',
+ downloading: 'ダウンロード中',
fileNotSupported: '{errorFiles} はサポートされていないファイルです。',
- or: 'または'
+ or: 'または',
+ dropMessage: 'ここにファイルをドロップ(複数可)、{browse}、または',
+ urlPlaceholder: 'データセットの URL を入力',
+ fetch: '取得',
+ format: '形式',
+ formatAuto: '自動',
+ cors: 'URL は [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS) を許可する必要があります。'
},
geocoder: {
title: '住所または座標を入力(例: 37.79,-122.40)'
diff --git a/src/localization/src/translations/pt.ts b/src/localization/src/translations/pt.ts
index 2b745adc0..f950cf1d9 100644
--- a/src/localization/src/translations/pt.ts
+++ b/src/localization/src/translations/pt.ts
@@ -298,7 +298,8 @@ export default {
vectorTile: 'Mosaico vetorial',
rasterTile: 'Mosaico raster',
wmsTile: 'Mosaico WMS',
- tile3d: 'Mosaico 3D'
+ tile3d: 'Mosaico 3D',
+ remoteFile: '{rowCount} linhas (remoto)'
},
tooltip: {
hideLayer: 'esconder camada',
@@ -689,8 +690,15 @@ export default {
'Envie {fileFormatNames} ou mapas salvos **Json**. Leia mais sobre [**tipos de arquivos suportados**]',
browseFiles: 'procure seus arquivos',
uploading: 'Enviando',
+ downloading: 'Baixando',
fileNotSupported: 'Arquivo {errorFiles} não é suportado.',
- or: 'ou'
+ or: 'ou',
+ dropMessage: 'Arraste e solte seu(s) arquivo(s) aqui, {browse}, ou',
+ urlPlaceholder: 'Insira a URL do conjunto de dados',
+ fetch: 'Buscar',
+ format: 'Formato',
+ formatAuto: 'Auto',
+ cors: 'A URL deve permitir [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS).'
},
tilesetSetup: {
header: 'Configurar mosaicos vetoriais',
diff --git a/src/localization/src/translations/ru.ts b/src/localization/src/translations/ru.ts
index a006a1bba..91fee7bde 100644
--- a/src/localization/src/translations/ru.ts
+++ b/src/localization/src/translations/ru.ts
@@ -297,7 +297,8 @@ export default {
vectorTile: 'Векторный тайл',
rasterTile: 'Растровый тайл',
wmsTile: 'WMS тайл',
- tile3d: '3D тайл'
+ tile3d: '3D тайл',
+ remoteFile: '{rowCount} строк (удалённый)'
},
tooltip: {
hideLayer: 'скрыть слой',
@@ -689,8 +690,15 @@ export default {
'Загрузите {fileFormatNames} или сохраненную карту **Json**. Подробнее [**supported file formats**]',
browseFiles: 'Просматреть файлы',
uploading: 'Загрузка',
+ downloading: 'Загрузка',
fileNotSupported: 'Файл {errorFiles} не поддерживается.',
- or: 'или'
+ or: 'или',
+ dropMessage: 'Перетащите сюда ваши файлы, {browse} или',
+ urlPlaceholder: 'Введите URL набора данных',
+ fetch: 'Загрузить',
+ format: 'Формат',
+ formatAuto: 'Авто',
+ cors: 'URL должен разрешать [CORS](https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS).'
},
tilesetSetup: {
header: 'Настройка векторных тайлов',
diff --git a/src/processors/src/file-handler.ts b/src/processors/src/file-handler.ts
index b548bd5ed..2e229c93b 100644
--- a/src/processors/src/file-handler.ts
+++ b/src/processors/src/file-handler.ts
@@ -15,7 +15,7 @@ import {
isArrowTable
} from '@kepler.gl/utils';
import {generateHashId} from '@kepler.gl/common-utils';
-import {DATASET_FORMATS} from '@kepler.gl/constants';
+import {DATASET_FORMATS, DatasetType, REMOTE_FILE_EXTENSIONS} from '@kepler.gl/constants';
import {AddDataToMapPayload, Feature, LoadedMap, ProcessorResult} from '@kepler.gl/types';
import {KeplerTable} from '@kepler.gl/table';
import type {FeatureCollection} from 'geojson';
@@ -66,6 +66,10 @@ export type ProcessFileDataContent = {
progress?: {rowCount?: number; rowCountInBatch?: number; percent?: number};
/** metadata e.g. for arrow data, metadata could be the schema.fields */
metadata?: Map<string, string>;
+ /** Remote URL this file was fetched from, if any. */
+ sourceUrl?: string;
+ /** User-selected or inferred remote file format (csv, geojson, parquet, …). */
+ keplerFormat?: string;
};
export {isArrowTable};
@@ -132,9 +136,29 @@ export async function* makeProgressIterator(
}
// eslint-disable-next-line complexity
+function getPersistedRemoteFormat(
+ keplerFormat?: string,
+ fileName?: string
+): string | undefined {
+ if (
+ keplerFormat &&
+ keplerFormat !== 'auto' &&
+ Object.prototype.hasOwnProperty.call(REMOTE_FILE_EXTENSIONS, keplerFormat)
+ ) {
+ return keplerFormat;
+ }
+ const ext = fileName?.match(/\.([a-z0-9]+)$/i)?.[1]?.toLowerCase();
+ if (ext && Object.prototype.hasOwnProperty.call(REMOTE_FILE_EXTENSIONS, ext)) {
+ return ext;
+ }
+ return undefined;
+}
+
export async function* readBatch(
asyncIterator: AsyncIterable<any>,
- fileName: string
+ fileName: string,
+ sourceUrl?: string,
+ keplerFormat?: string
): AsyncGenerator {
let result = null;
const batches = <any>[];
@@ -174,7 +198,9 @@ export async function* readBatch(
: {}),
fileName,
// if dataset is CSV, data is set to the raw batches
- data: result ? result : batches
+ data: result ? result : batches,
+ ...(sourceUrl ? {sourceUrl} : {}),
+ ...(keplerFormat ? {keplerFormat} : {})
};
}
}
@@ -190,19 +216,24 @@ export async function readFileInBatches({
loadOptions: any;
}): Promise<AsyncGenerator> {
loaders = [JSONLoader, CSVLoader, GeoArrowLoader, ParquetArrowLoader, ...loaders];
+ const hasExtension = /\.[a-z0-9]+$/i.test(file.name);
+ const mimeType = !hasExtension && file.type ? file.type : undefined;
loadOptions = {
csv: CSV_LOADER_OPTIONS,
arrow: ARROW_LOADER_OPTIONS,
json: JSON_LOADER_OPTIONS,
parquet: PARQUET_LOADER_OPTIONS,
metadata: true,
+ ...(mimeType ? {mimeType} : {}),
...loadOptions
};
const batchIterator = await parseInBatches(file, loaders, loadOptions);
const progressIterator = makeProgressIterator(batchIterator, {size: file.size});
+ const sourceUrl = (file as File & {keplerSourceUrl?: string}).keplerSourceUrl;
+ const keplerFormat = (file as File & {keplerFormat?: string}).keplerFormat;
- return readBatch(progressIterator, file.name);
+ return readBatch(progressIterator, file.name, sourceUrl, keplerFormat);
}
export async function processFileData({
@@ -215,8 +246,10 @@ export async function processFileData({
const {fileName, data} = content;
let format: string | undefined;
let processor: ((data: any) => ProcessorResult | LoadedMap | null) | undefined;
- // generate unique id with length of 4 using fileName string
- const id = generateHashIdFromString(fileName);
+ // Hash the source URL when present so two remote files that share a filename
+ // (or a local file and a remote URL with the same name) do not collide and
+ // overwrite each other. The UI shows `label` (the filename), not this id.
+ const id = generateHashIdFromString(content.sourceUrl || fileName);
// decide on which table class to use based on application config
const table = getApplicationConfig().table ?? KeplerTable;
@@ -251,6 +284,8 @@ export async function processFileData({
throw new Error(`Can not process uploaded file, ${getError(error as Error)}`);
}
+ const sourceUrl = content.sourceUrl;
+ const remoteFormat = getPersistedRemoteFormat(content.keplerFormat, content.fileName);
return [
...fileCache,
{
@@ -258,8 +293,17 @@ export async function processFileData({
info: {
id,
label: content.fileName,
- format
- }
+ format,
+ ...(sourceUrl ? {type: DatasetType.EXTERNALLY_HOSTED} : {})
+ },
+ ...(sourceUrl
+ ? {
+ metadata: {
+ source: sourceUrl,
+ ...(remoteFormat ? {sourceFormat: remoteFormat} : {})
+ }
+ }
+ : {})
}
];
} else {
@@ -290,7 +334,8 @@ export function filesToDataPayload(fileCache: FileCacheItem[]): AddDataToMapPayl
info: {
id: info?.id || generateHashId(4),
...(info || {})
- }
+ },
+ ...(file.metadata ? {metadata: file.metadata} : {})
};
accu.datasets.push(newDataset);
}
diff --git a/src/processors/src/index.ts b/src/processors/src/index.ts
index 493620cc6..dc99eaccf 100644
--- a/src/processors/src/index.ts
+++ b/src/processors/src/index.ts
@@ -3,4 +3,5 @@
export * from './data-processor';
export * from './file-handler';
+export * from './remote-file';
export * from './types';
diff --git a/src/processors/src/remote-file.ts b/src/processors/src/remote-file.ts
new file mode 100644
index 000000000..1520e240e
--- /dev/null
+++ b/src/processors/src/remote-file.ts
@@ -0,0 +1,218 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import {parseUri} from '@kepler.gl/common-utils';
+import {
+ MIME_TO_REMOTE_FILE_EXTENSION,
+ REMOTE_FILE_EXTENSIONS,
+ REMOTE_FILE_MIME_TYPES,
+ RemoteFileFormat
+} from '@kepler.gl/constants';
+import {ProcessorResult} from '@kepler.gl/types';
+
+import {processFileData, ProcessFileDataContent, readFileInBatches} from './file-handler';
+
+export type KeplerRemoteFile = File & {
+ keplerSourceUrl?: string;
+ keplerFormat?: string;
+};
+
+function getPathFileName(url: string): string {
+ try {
+ const parsed = new URL(url);
+ const segments = parsed.pathname.split('/').filter(Boolean);
+ const last = segments.length ? decodeURIComponent(segments[segments.length - 1]) : '';
+ return last.split('?')[0];
+ } catch {
+ const {file} = parseUri(url);
+ return decodeURIComponent(String(file || '')).split('?')[0];
+ }
+}
+
+export function getExtensionFromUrl(url: string): string {
+ const file = getPathFileName(url);
+ const match = file.match(/\.([a-z0-9]+)$/i);
+ return match ? match[1].toLowerCase() : '';
+}
+
+export function getMimeTypeForFormat(format?: string | null): string | undefined {
+ if (!format || format === 'auto') {
+ return undefined;
+ }
+ return REMOTE_FILE_MIME_TYPES[format as Exclude<RemoteFileFormat, 'auto'>];
+}
+
+export function isRemoteDatasetUrl(url: string): boolean {
+ try {
+ const {protocol} = new URL(url);
+ return protocol === 'http:' || protocol === 'https:';
+ } catch {
+ return false;
+ }
+}
+
+/**
+ * Build a filename loaders.gl can use to pick a parser.
+ * Prefers an explicit format, then the URL path extension, then Content-Type.
+ */
+export function getFileNameForRemoteUrl(
+ url: string,
+ format?: string | null,
+ mimeType?: string | null
+): string {
+ let base = getPathFileName(url) || 'dataset';
+
+ const formatExt =
+ format && format !== 'auto'
+ ? REMOTE_FILE_EXTENSIONS[format as Exclude<RemoteFileFormat, 'auto'>]
+ : undefined;
+ const urlExt = getExtensionFromUrl(url);
+ const mimeExt = mimeType
+ ? MIME_TO_REMOTE_FILE_EXTENSION[mimeType.split(';')[0].trim().toLowerCase()]
+ : undefined;
+ const ext = formatExt || urlExt || mimeExt;
+
+ if (!ext) {
+ return base;
+ }
+
+ if (/\.[a-z0-9]+$/i.test(base)) {
+ if (formatExt && !base.toLowerCase().endsWith(`.${formatExt}`)) {
+ return `${base.replace(/\.[^.]+$/, '')}.${formatExt}`;
+ }
+ return base;
+ }
+
+ return `${base}.${ext}`;
+}
+
+/**
+ * Fetch a remote dataset URL and wrap it as a File the existing loadFiles pipeline can parse.
+ * Sets File.type from an explicit format or the response Content-Type so extensionless
+ * URLs (SAS keys) still select the right loader.
+ */
+export async function fetchRemoteFileAsKeplerFile(
+ url: string,
+ format?: string | null,
+ onProgress?: (progress: {loaded: number; total?: number; percent: number}) => void
+): Promise<KeplerRemoteFile> {
+ if (!isRemoteDatasetUrl(url)) {
+ throw new Error('Remote dataset URL must use http or https');
+ }
+ const response = await fetch(url);
+ if (!response.ok) {
+ // Don't put the response body in the error: 404 HTML pages would dump into the UI.
+ response.body?.cancel?.().catch(() => undefined);
+ const status = response.statusText
+ ? `${response.status} ${response.statusText}`
+ : String(response.status);
+ throw new Error(`Failed to fetch ${url} (${status})`);
+ }
+
+ const blob = await readResponseBlob(response, onProgress);
+ const headerType = response.headers.get('content-type') || blob.type || '';
+ const mimeType = getMimeTypeForFormat(format) || headerType.split(';')[0].trim();
+ const fileName = getFileNameForRemoteUrl(url, format, mimeType);
+ const file = new File([blob], fileName, mimeType ? {type: mimeType} : undefined) as KeplerRemoteFile;
+ file.keplerSourceUrl = url;
+ if (format && format !== 'auto') {
+ file.keplerFormat = format;
+ }
+ return file;
+}
+
+async function readResponseBlob(
+ response: Response,
+ onProgress?: (progress: {loaded: number; total?: number; percent: number}) => void
+): Promise<Blob> {
+ const contentLength = Number(response.headers.get('content-length'));
+ const total = Number.isFinite(contentLength) && contentLength > 0 ? contentLength : undefined;
+
+ const emit = (loaded: number, complete = false) => {
+ onProgress?.({
+ loaded,
+ total,
+ percent: complete ? 1 : total ? Math.min(1, loaded / total) : 0
+ });
+ };
+
+ if (!response.body) {
+ const blob = await response.blob();
+ emit(blob.size, true);
+ return blob;
+ }
+
+ const reader = response.body.getReader();
+ const chunks: Uint8Array[] = [];
+ let loaded = 0;
+ emit(0);
+
+ while (true) {
+ const {done, value} = await reader.read();
+ if (done) {
+ break;
+ }
+ chunks.push(value);
+ loaded += value.byteLength;
+ emit(loaded);
+ }
+
+ emit(loaded, true);
+ return new Blob(chunks);
+}
+
+function isTabularProcessorResult(
+ data: unknown
+): data is NonNullable<ProcessorResult> {
+ return Boolean(
+ data &&
+ typeof data === 'object' &&
+ Array.isArray((data as ProcessorResult)?.fields) &&
+ Array.isArray((data as ProcessorResult)?.rows)
+ );
+}
+
+/**
+ * Fetch, parse, and process a remote file into Kepler dataset data.
+ * Used when reloading an `externally-hosted` dataset from a saved map config.
+ */
+export async function loadExternallyHostedDataset(metadata: {
+ source: string;
+ format?: string;
+ size?: number;
+}): Promise<NonNullable<ProcessorResult>> {
+ const {source, format} = metadata;
+ const file = await fetchRemoteFileAsKeplerFile(source, format);
+ const batches = await readFileInBatches({
+ file,
+ fileCache: [],
+ loaders: [],
+ loadOptions: {}
+ });
+
+ let content: ProcessFileDataContent | undefined;
+ for await (const batch of batches) {
+ content = batch as ProcessFileDataContent;
+ }
+ if (!content) {
+ throw new Error(`No data loaded from ${source}`);
+ }
+
+ const processed = await processFileData({
+ content: {
+ ...content,
+ fileName: content.fileName,
+ sourceUrl: source
+ },
+ fileCache: []
+ });
+ const data = processed[processed.length - 1]?.data;
+ if (!isTabularProcessorResult(data)) {
+ throw new Error(`Remote file is not a dataset: ${source}`);
+ }
+ return data;
+}
+
+export function isExternallyHostedFile(file: File): file is KeplerRemoteFile {
+ return Boolean((file as KeplerRemoteFile).keplerSourceUrl);
+}
diff --git a/src/processors/src/types.ts b/src/processors/src/types.ts
index 879209350..3e9cbab37 100644
--- a/src/processors/src/types.ts
+++ b/src/processors/src/types.ts
@@ -7,6 +7,13 @@ export type FileCacheItem = {
id?: string;
label: string;
format: string;
+ type?: string;
+ };
+ metadata?: {
+ source?: string;
+ format?: string;
+ sourceFormat?: string;
+ [key: string]: unknown;
};
};
diff --git a/src/reducers/src/vis-state-updaters.ts b/src/reducers/src/vis-state-updaters.ts
index 3fccfa7f0..d037d9186 100644
--- a/src/reducers/src/vis-state-updaters.ts
+++ b/src/reducers/src/vis-state-updaters.ts
@@ -111,7 +111,9 @@ import {
INITIAL_ANNOTATION_TEXT_HEIGHT,
INITIAL_ANNOTATION_LINE_WIDTH,
INITIAL_ANNOTATION_LINE_COLOR,
- AnnotationKind
+ AnnotationKind,
+ DatasetType,
+ getRemoteSourceFormat
} from '@kepler.gl/constants';
import {LAYER_ID_LENGTH, Layer, LayerClasses} from '@kepler.gl/layers';
import {
@@ -136,7 +138,7 @@ import {
} from './vis-state-merger';
import KeplerGLSchema, {Merger, PostMergerPayload, VisState} from '@kepler.gl/schemas';
-import {processGeojson} from '@kepler.gl/processors';
+import {loadExternallyHostedDataset, processGeojson} from '@kepler.gl/processors';
import {
Filter,
@@ -149,7 +151,8 @@ import {
LayerVisConfig,
TimeRangeFilter,
Annotation,
- AnnotationPropsPartial
+ AnnotationPropsPartial,
+ ProtoDataset
} from '@kepler.gl/types';
import {Loader} from '@loaders.gl/loader-utils';
@@ -2887,6 +2890,52 @@ export const toggleLayerForMapUpdater = (
};
};
+function hasTabularDatasetData(data?: ProtoDataset['data'] | null): boolean {
+ return Boolean(data?.rows?.length || data?.cols?.length || (data as {arrowTable?: unknown})?.arrowTable);
+}
+
+function needsExternallyHostedHydrate(dataset: ProtoDataset): boolean {
+ return (
+ dataset.info?.type === DatasetType.EXTERNALLY_HOSTED &&
+ typeof dataset.metadata?.source === 'string' &&
+ !hasTabularDatasetData(dataset.data)
+ );
+}
+
+async function hydrateExternallyHostedProtoDataset(dataset: ProtoDataset): Promise<ProtoDataset> {
+ if (!needsExternallyHostedHydrate(dataset)) {
+ return dataset;
+ }
+ const data = await loadExternallyHostedDataset({
+ source: dataset.metadata?.source as string,
+ format: getRemoteSourceFormat(dataset.metadata),
+ size: typeof dataset.metadata?.size === 'number' ? dataset.metadata.size : undefined
+ });
+ return {...dataset, data};
+}
+
+const HYDRATE_EXTERNALLY_HOSTED_DATASET_TASK = Task.fromPromise(
+ hydrateExternallyHostedProtoDataset,
+ 'HYDRATE_EXTERNALLY_HOSTED_DATASET_TASK'
+);
+
+const FAIL_CREATE_DATASET_TASK = Task.fromPromise(async (message: string) => {
+ throw new Error(message);
+}, 'FAIL_CREATE_DATASET_TASK');
+
+function createNewDataEntryTask(dataset: ProtoDataset, datasets: Datasets) {
+ if (!needsExternallyHostedHydrate(dataset)) {
+ return createNewDataEntry(dataset, datasets);
+ }
+ return HYDRATE_EXTERNALLY_HOSTED_DATASET_TASK(dataset).chain(hydrated => {
+ const task = createNewDataEntry(hydrated, datasets);
+ return (
+ task ||
+ FAIL_CREATE_DATASET_TASK('Failed to create a new dataset due to data verification errors')
+ );
+ });
+}
+
/**
* Add new dataset to `visState`, with option to load a map config along with the datasets
* @memberof visStateUpdaters
@@ -2917,7 +2966,7 @@ export const updateVisDataUpdater = (
const notificationTasks: Task[] = [];
datasets.forEach(({info = {}, ...rest}, datasetIndex) => {
- const task = createNewDataEntry({info, ...rest}, state.datasets);
+ const task = createNewDataEntryTask({info, ...rest}, state.datasets);
if (task) {
createDatasetTasks.push(task);
} else {
diff --git a/src/schemas/src/dataset-schema.ts b/src/schemas/src/dataset-schema.ts
index 7fc6ca888..2bbf85d32 100644
--- a/src/schemas/src/dataset-schema.ts
+++ b/src/schemas/src/dataset-schema.ts
@@ -5,7 +5,7 @@ import pick from 'es-toolkit/compat/pick';
import {console as globalConsole} from 'global/window';
import * as arrow from 'apache-arrow';
-import {ALL_FIELD_TYPES, DATASET_FORMATS} from '@kepler.gl/constants';
+import {ALL_FIELD_TYPES, DATASET_FORMATS, DatasetType, getRemoteSourceFormat} from '@kepler.gl/constants';
import {ProtoDataset, RGBColor, JsonObject} from '@kepler.gl/types';
import {KeplerTable} from '@kepler.gl/table';
import {VERSIONS} from './versions';
@@ -164,6 +164,23 @@ export class DatasetSchema extends Schema {
key = 'dataset';
save(dataset: KeplerTable): SavedDatasetV1['data'] {
+ 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);
+ return this.savePropertiesOrApplySchema({
+ id: dataset.id,
+ label: dataset.label,
+ color: dataset.color,
+ type: dataset.type,
+ allData: [],
+ fields: getFieldsForSaving(dataset.fields || []),
+ metadata: {
+ source: dataset.metadata.source,
+ ...(sourceFormat ? {format: sourceFormat} : {})
+ }
+ })[this.key];
+ }
+
const datasetFlattened = dataset.dataContainer
? {
...dataset,
@@ -190,6 +207,8 @@ export class DatasetSchema extends Schema {
// because we have updated type-analyzer
// we need to add format to each field
const needCalculateMeta =
+ Array.isArray(allData) &&
+ allData.length > 0 &&
fields[0] &&
(!Object.prototype.hasOwnProperty.call(fields[0], 'format') ||
!Object.prototype.hasOwnProperty.call(fields[0], 'analyzerType'));
@@ -218,10 +237,20 @@ export class DatasetSchema extends Schema {
}
// get format of all fields
+ let metadata = dataset.metadata;
+ if (dataset.type === DatasetType.EXTERNALLY_HOSTED && dataset.metadata) {
+ const sourceFormat = getRemoteSourceFormat(dataset.metadata);
+ metadata = {
+ source: dataset.metadata.source,
+ ...(sourceFormat ? {sourceFormat} : {}),
+ ...(typeof dataset.metadata.size === 'number' ? {size: dataset.metadata.size} : {})
+ };
+ }
+
return {
- data: {fields: updatedFields, rows: dataset.allData},
+ data: {fields: updatedFields || [], rows: dataset.allData || []},
info: pick(dataset, ['id', 'label', 'color', 'type']),
- ...(dataset.metadata ? {metadata: dataset.metadata} : {}),
+ ...(metadata ? {metadata} : {}),
...(dataset.disableDataOperation ? {disableDataOperation: dataset.disableDataOperation} : {})
};
}
diff --git a/src/table/src/dataset-utils.ts b/src/table/src/dataset-utils.ts
index f9f967387..da6c0f5e6 100644
--- a/src/table/src/dataset-utils.ts
+++ b/src/table/src/dataset-utils.ts
@@ -117,7 +117,8 @@ type CreateTableProps = {
};
async function createTable(datasetInfo: CreateTableProps) {
- const {info, color, opts, data} = datasetInfo;
+ const {info, color, opts} = datasetInfo;
+ let {data} = datasetInfo;
// update metadata for remote tiled datasets
const refreshedMetadata = await refreshRemoteData(datasetInfo);
@@ -166,6 +167,8 @@ async function refreshRemoteData(datasetInfo: CreateTableProps): Promise<object
return null;
case DatasetType.BITMAP:
return null;
+ case DatasetType.EXTERNALLY_HOSTED:
+ return null;
default:
return null;
}
diff --git a/src/utils/src/application-config.ts b/src/utils/src/application-config.ts
index 047383098..0245f4057 100644
--- a/src/utils/src/application-config.ts
+++ b/src/utils/src/application-config.ts
@@ -180,6 +180,12 @@ export type KeplerApplicationConfig = {
/** Whether to show column statistics in the data table modal. Enabled by default. */
enableColumnStats?: boolean;
+ /**
+ * Show a format dropdown next to the remote dataset URL field (Auto / CSV / GeoJSON / JSON / Arrow / Parquet).
+ * Useful for extensionless URLs such as Azure SAS blobs. Disabled by default.
+ */
+ enableRemoteFileFormatSelector?: boolean;
+
/**
* Custom SVG icons to be made available in the icon layer.
* These icons will be merged with the default icons fetched from CDN.
@@ -307,6 +313,8 @@ const DEFAULT_APPLICATION_CONFIG: Required<KeplerApplicationConfig> = {
enableColumnStats: true,
+ enableRemoteFileFormatSelector: false,
+
customIcons: [],
customIconUrl: '',
diff --git a/test/browser/components/common/file-uploader-test.js b/test/browser/components/common/file-uploader-test.js
index e3fc448ba..948108d60 100644
--- a/test/browser/components/common/file-uploader-test.js
+++ b/test/browser/components/common/file-uploader-test.js
@@ -7,6 +7,7 @@ import sinon from 'sinon';
import {IntlWrapper, mountWithTheme} from 'test/helpers/component-utils';
import {FileUpload, WarningMsg, FileDrop, UploadButton} from '@kepler.gl/components';
+import {initApplicationConfig} from '@kepler.gl/utils';
test('Components -> FileUploader.render', t => {
let wrapper;
@@ -230,3 +231,41 @@ test('Components -> UploadButton fileInput', t => {
t.end();
});
+
+test('Components -> FileUpload remote URL form', t => {
+ const wrapper = mountWithTheme(
+ <IntlWrapper>
+ <FileUpload onFileUpload={() => {}} fileExtensions={['csv', 'geojson']} />
+ </IntlWrapper>
+ );
+
+ t.ok(wrapper.find('.file-uploader__remote-url').exists(), 'should render remote URL form');
+ const urlInput = wrapper.find('.file-uploader__remote-url input').hostNodes();
+ t.equal(urlInput.length, 1, 'should render URL input');
+ t.ok(urlInput.first().prop('aria-label'), 'should set aria-label on URL input');
+ t.equal(
+ wrapper.find('.file-uploader__remote-url select').hostNodes().length,
+ 0,
+ 'format selector is hidden by default'
+ );
+
+ t.end();
+});
+
+test('Components -> FileUpload remote URL format selector flag', t => {
+ initApplicationConfig({enableRemoteFileFormatSelector: true});
+ const wrapper = mountWithTheme(
+ <IntlWrapper>
+ <FileUpload onFileUpload={() => {}} fileExtensions={['csv', 'geojson']} />
+ </IntlWrapper>
+ );
+
+ t.equal(
+ wrapper.find('.file-uploader__remote-url select').hostNodes().length,
+ 1,
+ 'should render format select when the flag is enabled'
+ );
+
+ initApplicationConfig({enableRemoteFileFormatSelector: false});
+ t.end();
+});
diff --git a/test/node/processors/file-handler-test.js b/test/node/processors/file-handler-test.js
index d92a0e558..fdb6cd782 100644
--- a/test/node/processors/file-handler-test.js
+++ b/test/node/processors/file-handler-test.js
@@ -2,7 +2,7 @@
// Copyright contributors to the kepler.gl project
import test from 'tape';
-import {isKeplerGlMap, makeProgressIterator, filesToDataPayload} from '@kepler.gl/processors';
+import {isKeplerGlMap, makeProgressIterator, filesToDataPayload, processFileData} from '@kepler.gl/processors';
import {parsedFields, parsedRows} from 'test/fixtures/row-object';
import {
savedStateV1InteractionCoordinate as keplerglMap,
@@ -155,3 +155,125 @@ test('#file-handler -> filesToDataPayload', t => {
t.end();
});
+
+test('#file-handler -> filesToDataPayload remote metadata', t => {
+ const fileCache = [
+ {
+ data: {
+ fields: parsedFields,
+ rows: parsedRows
+ },
+ info: {
+ id: 'remote-ds',
+ label: 'quakes.csv',
+ format: 'row',
+ type: 'externally-hosted'
+ },
+ metadata: {
+ source: 'https://example.com/quakes.csv',
+ sourceFormat: 'csv'
+ }
+ }
+ ];
+
+ const result = filesToDataPayload(fileCache);
+ t.equal(result.length, 1, 'result should have 1 entry');
+ t.equal(result[0].datasets[0].info.type, 'externally-hosted', 'should pass type');
+ t.deepEqual(
+ result[0].datasets[0].metadata,
+ {source: 'https://example.com/quakes.csv', sourceFormat: 'csv'},
+ 'should pass remote source metadata'
+ );
+
+ t.end();
+});
+
+test('#file-handler -> processFileData persists remote file format', async t => {
+ const cache = await processFileData({
+ content: {
+ fileName: 'quakes.csv',
+ data: [{lat: 1, lng: 2}],
+ sourceUrl: 'https://example.com/abc123?sv=1',
+ keplerFormat: 'csv'
+ },
+ fileCache: []
+ });
+
+ t.equal(cache[0].info.type, 'externally-hosted', 'should mark the dataset as externally-hosted');
+ t.equal(cache[0].info.format, 'row', 'processor format stays row for CSV');
+ t.deepEqual(
+ cache[0].metadata,
+ {source: 'https://example.com/abc123?sv=1', sourceFormat: 'csv'},
+ 'should persist the file format, not the processor format'
+ );
+
+ const parquetCache = await processFileData({
+ content: {
+ fileName: 'data.parquet',
+ data: [{lat: 1, lng: 2}],
+ sourceUrl: 'https://example.com/data.parquet'
+ },
+ fileCache: []
+ });
+
+ t.equal(
+ parquetCache[0].metadata.sourceFormat,
+ 'parquet',
+ 'should infer parquet from the filename when no format was selected'
+ );
+
+ t.end();
+});
+
+test('#file-handler -> processFileData remote ids do not collide on filename', async t => {
+ const rows = [{lat: 1, lng: 2}];
+ const local = await processFileData({
+ content: {fileName: 'quakes.csv', data: rows},
+ fileCache: []
+ });
+ const remoteA = await processFileData({
+ content: {
+ fileName: 'quakes.csv',
+ data: rows,
+ sourceUrl: 'https://a.example.com/quakes.csv'
+ },
+ fileCache: []
+ });
+ const remoteB = await processFileData({
+ content: {
+ fileName: 'quakes.csv',
+ data: rows,
+ sourceUrl: 'https://b.example.com/quakes.csv'
+ },
+ fileCache: []
+ });
+ const remoteAAgain = await processFileData({
+ content: {
+ fileName: 'quakes.csv',
+ data: rows,
+ sourceUrl: 'https://a.example.com/quakes.csv'
+ },
+ fileCache: []
+ });
+
+ t.equal(local[0].info.label, 'quakes.csv', 'local label stays the filename');
+ t.equal(remoteA[0].info.label, 'quakes.csv', 'remote label stays the filename');
+ t.notEqual(
+ local[0].info.id,
+ remoteA[0].info.id,
+ 'local and remote files with the same name get different ids'
+ );
+ t.notEqual(
+ remoteA[0].info.id,
+ remoteB[0].info.id,
+ 'two remote URLs with the same filename get different ids'
+ );
+ t.equal(
+ remoteA[0].info.id,
+ remoteAAgain[0].info.id,
+ 'reloading the same URL keeps a stable id so progressive batches can update in place'
+ );
+ t.ok(!String(remoteA[0].info.id).includes('http'), 'id is a hash, not the raw URL');
+
+ t.end();
+});
diff --git a/test/node/processors/index.js b/test/node/processors/index.js
index d5db2032c..1d0970ead 100644
--- a/test/node/processors/index.js
+++ b/test/node/processors/index.js
@@ -2,3 +2,4 @@
// Copyright contributors to the kepler.gl project
import './file-handler-test';
+import './remote-file-test';
diff --git a/test/node/processors/remote-file-test.js b/test/node/processors/remote-file-test.js
new file mode 100644
index 000000000..33b18a84a
--- /dev/null
+++ b/test/node/processors/remote-file-test.js
@@ -0,0 +1,144 @@
+// SPDX-License-Identifier: MIT
+// Copyright contributors to the kepler.gl project
+
+import test from 'tape';
+import {
+ fetchRemoteFileAsKeplerFile,
+ getExtensionFromUrl,
+ getFileNameForRemoteUrl,
+ getMimeTypeForFormat,
+ isRemoteDatasetUrl
+} from '@kepler.gl/processors';
+
+test('#remote-file -> getExtensionFromUrl', t => {
+ t.equal(getExtensionFromUrl('https://example.com/data.geojson'), 'geojson');
+ t.equal(
+ getExtensionFromUrl('https://example.com/data.csv?sv=2020-08-04&sig=abc'),
+ 'csv',
+ 'should ignore SAS query params'
+ );
+ t.equal(
+ getExtensionFromUrl('https://account.blob.core.windows.net/container/abc123?sv=1&sig=2'),
+ '',
+ 'should return empty string when the blob name has no extension'
+ );
+ t.end();
+});
+
+test('#remote-file -> getMimeTypeForFormat', t => {
+ t.equal(getMimeTypeForFormat('auto'), undefined);
+ t.equal(getMimeTypeForFormat(undefined), undefined);
+ t.equal(getMimeTypeForFormat('csv'), 'text/csv');
+ t.equal(getMimeTypeForFormat('parquet'), 'application/vnd.apache.parquet');
+ t.equal(getMimeTypeForFormat('arrow'), 'application/vnd.apache.arrow.file');
+ t.end();
+});
+
+test('#remote-file -> getFileNameForRemoteUrl', t => {
+ t.equal(
+ getFileNameForRemoteUrl('https://example.com/path/quakes.csv'),
+ 'quakes.csv',
+ 'should use the URL path filename'
+ );
+ t.equal(
+ getFileNameForRemoteUrl('https://example.com/path/quakes.csv?sv=2020&sig=abc'),
+ 'quakes.csv',
+ 'should strip query params'
+ );
+ t.equal(
+ getFileNameForRemoteUrl(
+ 'https://account.blob.core.windows.net/container/abc123?sv=1',
+ 'geojson'
+ ),
+ 'abc123.geojson',
+ 'should append an explicit format when the blob name has no extension'
+ );
+ t.equal(
+ getFileNameForRemoteUrl('https://example.com/container/blob', 'auto', 'text/csv'),
+ 'blob.csv',
+ 'should use Content-Type when format is auto and the URL has no extension'
+ );
+ t.equal(
+ getFileNameForRemoteUrl('https://example.com/data.json', 'geojson'),
+ 'data.geojson',
+ 'should replace the extension when an explicit format is provided'
+ );
+ t.end();
+});
+
+test('#remote-file -> isRemoteDatasetUrl', t => {
+ t.ok(isRemoteDatasetUrl('https://example.com/data.csv'), 'https is allowed');
+ t.ok(isRemoteDatasetUrl('http://example.com/data.csv'), 'http is allowed');
+ t.notOk(isRemoteDatasetUrl('javascript:alert(1)'), 'javascript: is rejected');
+ t.notOk(isRemoteDatasetUrl('file:///tmp/data.csv'), 'file: is rejected');
+ t.notOk(isRemoteDatasetUrl('ftp://example.com/data.csv'), 'ftp is rejected');
+ t.notOk(isRemoteDatasetUrl('not a url'), 'invalid URLs are rejected');
+ t.end();
+});
+
+test('#remote-file -> fetchRemoteFileAsKeplerFile rejects non-http URLs', async t => {
+ try {
+ await fetchRemoteFileAsKeplerFile('javascript:alert(1)');
+ t.fail('should reject javascript: URLs');
+ } catch (error) {
+ t.ok(error instanceof Error, 'should throw');
+ t.ok(/http or https/i.test(error.message), 'should mention http or https');
+ }
+ t.end();
+});
+
+test('#remote-file -> fetchRemoteFileAsKeplerFile does not dump error bodies', async t => {
+ const origFetch = global.fetch;
+ global.fetch = async () =>
+ new Response('<!DOCTYPE html><html><body>Not Found '.repeat(500) + '</body></html>', {
+ status: 404,
+ statusText: 'Not Found'
+ });
+
+ try {
+ await fetchRemoteFileAsKeplerFile('https://example.com/missing.csv');
+ t.fail('should reject HTTP errors');
+ } catch (error) {
+ t.ok(error instanceof Error, 'should throw');
+ t.equal(
+ error.message,
+ 'Failed to fetch https://example.com/missing.csv (404 Not Found)',
+ 'should report status without the response body'
+ );
+ t.ok(!error.message.includes('<html>'), 'should not include HTML from the error page');
+ } finally {
+ global.fetch = origFetch;
+ }
+ t.end();
+});
+
+test('#remote-file -> fetchRemoteFileAsKeplerFile progress without Content-Length', async t => {
+ const origFetch = global.fetch;
+ const chunks = [new Uint8Array([1, 2, 3]), new Uint8Array([4, 5, 6])];
+ let i = 0;
+ global.fetch = async () =>
+ new Response(
+ new ReadableStream({
+ pull(controller) {
+ if (i < chunks.length) {
+ controller.enqueue(chunks[i++]);
+ } else {
+ controller.close();
+ }
+ }
+ }),
+ {status: 200}
+ );
+
+ try {
+ const percents = [];
+ await fetchRemoteFileAsKeplerFile('https://example.com/data.csv', 'csv', ({percent}) => {
+ percents.push(percent);
+ });
+ t.ok(percents.length, 'should emit progress');
+ t.equal(percents[percents.length - 1], 1, 'should emit 100% when the blob is fully read');
+ } finally {
+ global.fetch = origFetch;
+ }
+ t.end();
+});
diff --git a/test/node/schemas/dataset-schema-test.js b/test/node/schemas/dataset-schema-test.js
index 06b64cb0a..db084a420 100644
--- a/test/node/schemas/dataset-schema-test.js
+++ b/test/node/schemas/dataset-schema-test.js
@@ -3,7 +3,8 @@
import test from 'tape';
import cloneDeep from 'es-toolkit/compat/cloneDeep';
-import SchemaManager from '@kepler.gl/schemas';
+import SchemaManager, {datasetSchema, VERSIONS} from '@kepler.gl/schemas';
+import {DatasetType} from '@kepler.gl/constants';
// fixtures
import {
@@ -117,3 +118,39 @@ test('#DatasetSchema -> SchemaManager.parseSavedData.v1 with ts', t => {
t.end();
});
+
+test('#DatasetSchema -> save externally-hosted dataset without inlining rows', t => {
+ const dataset = {
+ id: 'remote-1',
+ label: 'quakes.csv',
+ color: [1, 2, 3],
+ type: DatasetType.EXTERNALLY_HOSTED,
+ fields: [{name: 'lat', type: 'real', format: '', analyzerType: 'FLOAT'}],
+ metadata: {
+ source: 'https://example.com/quakes.csv',
+ sourceFormat: 'csv',
+ extra: 'should-not-save'
+ }
+ };
+
+ const saved = datasetSchema[VERSIONS.v1].save(dataset);
+
+ t.deepEqual(saved.allData, [], 'should not inline remote rows');
+ t.equal(saved.type, DatasetType.EXTERNALLY_HOSTED, 'should persist dataset type');
+ t.deepEqual(
+ saved.metadata,
+ {source: 'https://example.com/quakes.csv', format: 'csv'},
+ 'should persist source URL without extra metadata'
+ );
+
+ const loaded = SchemaManager.parseSavedData([{version: 'v1', data: saved}]);
+ t.equal(loaded.length, 1, 'should parse one dataset');
+ t.equal(loaded[0].info.type, DatasetType.EXTERNALLY_HOSTED, 'should restore type');
+ t.equal(loaded[0].info.id, 'remote-1', 'should restore id');
+ t.equal(loaded[0].metadata.source, 'https://example.com/quakes.csv', 'should restore source');
+ t.equal(loaded[0].metadata.sourceFormat, 'csv', 'should map saved format to sourceFormat');
+ t.equal(loaded[0].metadata.format, undefined, 'should not collide with DATASET_FORMATS');
+ t.deepEqual(loaded[0].data.rows, [], 'loaded rows should stay empty until refetch');
+
+ t.end();
+});