Skip to content

An open source alternative to Tableau. Embeddable visual analytic

feat: infer format from data

islxyqwee9ef4ac4657e
diff --git a/packages/graphic-walker/src/computation/serverComputation.ts b/packages/graphic-walker/src/computation/serverComputation.ts
index 5698a6ed..4fbb006f 100644
--- a/packages/graphic-walker/src/computation/serverComputation.ts
+++ b/packages/graphic-walker/src/computation/serverComputation.ts
@@ -1,11 +1,4 @@
-import type {
- IComputationFunction,
- IDataQueryPayload,
- IDataQueryWorkflowStep,
- IDatasetStats,
- IFieldStats,
- IRow,
-} from '../interfaces';
+import type { IComputationFunction, IDataQueryPayload, IDataQueryWorkflowStep, IDatasetStats, IFieldStats, IRow } from '../interfaces';
export const datasetStatsServer = async (service: IComputationFunction): Promise<IDatasetStats> => {
const res = (await service({
@@ -33,11 +26,7 @@ export const datasetStatsServer = async (service: IComputationFunction): Promise
};
};
-export const dataReadRawServer = async (
- service: IComputationFunction,
- pageSize: number,
- pageOffset = 0
-): Promise<IRow[]> => {
+export const dataReadRawServer = async (service: IComputationFunction, pageSize: number, pageOffset = 0): Promise<IRow[]> => {
const res = await service({
workflow: [
{
@@ -56,11 +45,7 @@ export const dataReadRawServer = async (
return res;
};
-export const dataQueryServer = async (
- service: IComputationFunction,
- workflow: IDataQueryWorkflowStep[],
- limit?: number,
-): Promise<IRow[]> => {
+export const dataQueryServer = async (service: IComputationFunction, workflow: IDataQueryWorkflowStep[], limit?: number): Promise<IRow[]> => {
if (
workflow.length === 1 &&
workflow[0].type === 'view' &&
@@ -77,11 +62,7 @@ export const dataQueryServer = async (
return res;
};
-export const fieldStatServer = async (
- service: IComputationFunction,
- field: string,
- options: { values?: boolean; range?: boolean }
-): Promise<IFieldStats> => {
+export const fieldStatServer = async (service: IComputationFunction, field: string, options: { values?: boolean; range?: boolean }): Promise<IFieldStats> => {
const { values = true, range = true } = options;
const COUNT_ID = `count_${field}`;
const MIN_ID = `min_${field}`;
@@ -156,3 +137,22 @@ export const fieldStatServer = async (
range: [rangeRes[MIN_ID], rangeRes[MAX_ID]],
};
};
+
+export async function getSample(service: IComputationFunction, field: string) {
+ const res = await service({
+ workflow: [
+ {
+ type: 'view',
+ query: [
+ {
+ op: 'raw',
+ fields: [field],
+ },
+ ],
+ },
+ ],
+ limit: 1,
+ offset: 0,
+ });
+ return res?.[0]?.[field];
+}
diff --git a/packages/graphic-walker/src/fields/datasetFields/utils.ts b/packages/graphic-walker/src/fields/datasetFields/utils.ts
index 5d02bc79..ab0c48a4 100644
--- a/packages/graphic-walker/src/fields/datasetFields/utils.ts
+++ b/packages/graphic-walker/src/fields/datasetFields/utils.ts
@@ -3,7 +3,9 @@ import { useTranslation } from "react-i18next";
import { useGlobalStore } from "../../store";
import type { IActionMenuItem } from "../../components/actionMenu/list";
import { COUNT_FIELD_ID, DATE_TIME_DRILL_LEVELS } from "../../constants";
-import { CommonStore } from "../../store/commonStore";
+import { useComputationFunc } from "../../renderer/hooks";
+import { getSample } from "../../computation/serverComputation";
+import { getTimeFormat } from "../../lib/inferMeta";
const keepTrue = <T extends string | number | object | Function | symbol>(array: (T | 0 | null | false | undefined | void)[]): T[] => {
@@ -14,6 +16,7 @@ export const useMenuActions = (channel: "dimensions" | "measures"): IActionMenuI
const { vizStore, commonStore } = useGlobalStore();
const fields = vizStore.draggableFieldState[channel];
const { t } = useTranslation('translation', { keyPrefix: "field_menu" });
+ const computation = useComputationFunc();
return useMemo<IActionMenuItem[][]>(() => {
return fields.map((f, index) => {
@@ -92,11 +95,11 @@ export const useMenuActions = (channel: "dimensions" | "measures"): IActionMenuI
const originField = (isDateTimeDrilled ? vizStore.allFields.find(field => field.fid === f.expression?.params.find(p => p.type === 'field')?.value) : null) ?? f;
const originChannel = originField.analyticType === 'dimension' ? 'dimensions' : 'measures';
const originIndex = vizStore.allFields.findIndex(x => x.fid === originField.fid);
- vizStore.createDateTimeDrilledField(originChannel, originIndex, level, `${t(`drill.levels.${level}`)} (${originField.name || originField.fid})`);
+ getSample(computation, originField.fid).then(getTimeFormat).then(format => vizStore.createDateTimeDrilledField(originChannel, originIndex, level, `${t(`drill.levels.${level}`)} (${originField.name || originField.fid})`, format));
},
})),
},
]);
});
- }, [channel, fields, vizStore, t]);
+ }, [channel, fields, vizStore, t, computation]);
};
diff --git a/packages/graphic-walker/src/interfaces.ts b/packages/graphic-walker/src/interfaces.ts
index a9bf4153..2d2254d9 100644
--- a/packages/graphic-walker/src/interfaces.ts
+++ b/packages/graphic-walker/src/interfaces.ts
@@ -1,8 +1,8 @@
-import {Config as VgConfig, View} from 'vega';
-import {Config as VlConfig} from 'vega-lite';
+import { Config as VgConfig, View } from 'vega';
+import { Config as VlConfig } from 'vega-lite';
import type { FeatureCollection } from 'geojson';
import type { feature } from 'topojson-client';
-import type {IViewQuery} from "./lib/viewQuery";
+import type { IViewQuery } from './lib/viewQuery';
import { DATE_TIME_DRILL_LEVELS } from './constants';
export type DeepReadonly<T extends Record<keyof any, any>> = {
@@ -35,8 +35,8 @@ export interface Filters {
}
export interface ICreateField {
- channel:"dimensions" | "measures";
- index:number;
+ channel: 'dimensions' | 'measures';
+ index: number;
}
export interface IMutField {
@@ -86,6 +86,10 @@ export type IExpParamter =
| {
type: 'constant';
value: any;
+ }
+ | {
+ type: 'format';
+ value: string;
};
export interface IExpression {
@@ -118,7 +122,7 @@ export interface IField {
expression?: IExpression;
timeUnit?: (typeof DATE_TIME_DRILL_LEVELS)[number];
basename?: string;
- path?: string[],
+ path?: string[];
}
export type ISortMode = 'none' | 'ascending' | 'descending';
export interface IViewField extends IField {
@@ -145,7 +149,7 @@ export interface IMeasure {
export interface IPredicate {
key: string;
- type: "discrete" | "continuous";
+ type: 'discrete' | 'continuous';
range: Set<any> | [number, number];
}
@@ -267,8 +271,8 @@ export interface IVisualConfig {
}
export interface IGeoUrl {
- type: 'GeoJSON' | 'TopoJSON',
- url: string,
+ type: 'GeoJSON' | 'TopoJSON';
+ url: string;
}
export interface IVisSpec {
@@ -278,11 +282,7 @@ export interface IVisSpec {
readonly config: DeepReadonly<IVisualConfig>;
}
-export type SetToArray<T> = (
- T extends object ? (
- T extends Set<infer U> ? Array<U> : { [K in keyof T]: SetToArray<T[K]> }
- ) : T
-);
+export type SetToArray<T> = T extends object ? (T extends Set<infer U> ? Array<U> : { [K in keyof T]: SetToArray<T[K]> }) : T;
export type IVisSpecForExport = SetToArray<IVisSpec>;
@@ -365,7 +365,7 @@ export interface IGWHandler {
openChart: (index: number) => void;
/**
* Returns the status of the current chart.
- *
+ *
* It is computed by the following rules:
* - If _GraphicWalker_ is computing the data view, it returns `computing`.
* - If _GraphicWalker_ is rendering the chart, it returns `rendering`.
@@ -375,20 +375,20 @@ export interface IGWHandler {
get renderStatus(): IRenderStatus;
/**
* Registers a callback function to listen to the status change of the current chart.
- *
+ *
* @param {(renderStatus: IRenderStatus) => void} cb - the callback function
* @returns {() => void} a dispose function to remove this callback
*/
- onRenderStatusChange: (cb: (renderStatus: IRenderStatus) => void) => (() => void);
+ onRenderStatusChange: (cb: (renderStatus: IRenderStatus) => void) => () => void;
/**
* Exports the current chart.
- *
+ *
* @param {IChartExportResult['mode']} [mode='svg'] - the export mode, either `svg` or `data-url`
*/
exportChart: IExportChart;
/**
* Exports all charts.
- *
+ *
* @param {IChartExportResult['mode']} [mode='svg'] - the export mode, either `svg` or `data-url`
* @returns {AsyncGenerator<IChartListExportResult, void, unknown>} an async generator to iterate over all charts
* @example
@@ -424,7 +424,7 @@ export type IVisFieldComputation = {
export interface IVisFilter {
fid: string;
rule: SetToArray<IFilterRule>;
-};
+}
export interface IFilterWorkflowStep {
type: 'filter';
@@ -467,40 +467,38 @@ export interface IGWDatasetStat {
count: number;
}
-export type IResponse<T> = (
+export type IResponse<T> =
| {
- success: true;
- data: T;
- }
+ success: true;
+ data: T;
+ }
| {
- success: false;
- message: string;
- error?: {
- code: `ERR_${Uppercase<string>}`;
- options?: Record<string, string>;
- };
- }
-);
+ success: false;
+ message: string;
+ error?: {
+ code: `ERR_${Uppercase<string>}`;
+ options?: Record<string, string>;
+ };
+ };
export type Topology = Parameters<typeof feature>[0];
-export type IGeographicData = (
+export type IGeographicData =
| {
- type: 'GeoJSON';
- data: FeatureCollection;
- }
+ type: 'GeoJSON';
+ data: FeatureCollection;
+ }
| {
- type: 'TopoJSON';
- data: Topology;
- /**
- * default to the first key of `objects` in Topology
- */
- objectKey?: string;
- }
-);
+ type: 'TopoJSON';
+ data: Topology;
+ /**
+ * default to the first key of `objects` in Topology
+ */
+ objectKey?: string;
+ };
export type IGeoDataItem = {
type: 'GeoJSON' | 'TopoJSON';
name: string;
url: string;
-}
\ No newline at end of file
+};
diff --git a/packages/graphic-walker/src/lib/inferMeta.ts b/packages/graphic-walker/src/lib/inferMeta.ts
index 32362f53..03e514b6 100644
--- a/packages/graphic-walker/src/lib/inferMeta.ts
+++ b/packages/graphic-walker/src/lib/inferMeta.ts
@@ -11,6 +11,23 @@ const COMMON_TIME_FORMAT: RegExp[] = [
/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}$/, // YYYY-MM-DDTHH:MM:SS (ISO-8601)
];
+const TIME_FORMAT = [
+ '%Y-%m-%d',
+ '%m/%d/%Y',
+ '%d/%m/%Y',
+ '%Y/%m/%d',
+ '%Y.%m.%d',
+ '%Y-%m-%d %H:%i:%s',
+ '%Y-%m-%dT%H:%i:%s',
+]
+
+export function getTimeFormat(data: string | number) {
+ if (typeof data === 'number') return 'timestamp';
+ const i = COMMON_TIME_FORMAT.findIndex(x => x.test(data));
+ if (i >= 0) return TIME_FORMAT[i];
+ return ''
+}
+
/**
* check if this array is a date time array based on some common date format
* @param data string array
diff --git a/packages/graphic-walker/src/main.tsx b/packages/graphic-walker/src/main.tsx
index d9c03450..16bfb91f 100644
--- a/packages/graphic-walker/src/main.tsx
+++ b/packages/graphic-walker/src/main.tsx
@@ -6,7 +6,6 @@ if (!import.meta.env.DEV) {
}
embedGraphicWalker(document.getElementById('root') as HTMLElement, {
- i18nLang: 'zh-CN',
geoList: [
{ name: 'World Countries', type: 'TopoJSON', url: 'https://cdn.jsdelivr.net/npm/world-atlas@2/countries-10m.json' },
{
diff --git a/packages/graphic-walker/src/store/visualSpecStore.ts b/packages/graphic-walker/src/store/visualSpecStore.ts
index e077494f..f065ff04 100644
--- a/packages/graphic-walker/src/store/visualSpecStore.ts
+++ b/packages/graphic-walker/src/store/visualSpecStore.ts
@@ -582,7 +582,7 @@ export class VizSpecStore {
encodings[stateKey].push(logField);
});
}
- public createDateTimeDrilledField(stateKey: keyof DraggableFieldState, index: number, drillLevel: typeof DATE_TIME_DRILL_LEVELS[number], name: string | ((originFieldName: string) => string)) {
+ public createDateTimeDrilledField(stateKey: keyof DraggableFieldState, index: number, drillLevel: typeof DATE_TIME_DRILL_LEVELS[number], name: string | ((originFieldName: string) => string), format: string) {
if (stateKey === "filters") {
return;
}
@@ -611,6 +611,10 @@ export class VizSpecStore {
type: 'value',
value: drillLevel,
},
+ {
+ type: 'format',
+ value: format
+ }
],
},
};