Skip to content

An open source alternative to Tableau. Embeddable visual analytic

feat: Add config to set timezone to displaying chart (#297)

islxyqwe52ade737d494
diff --git a/packages/duckdb-wasm-computation/src/index.ts b/packages/duckdb-wasm-computation/src/index.ts
index b4dc542b..ceb3a828 100644
--- a/packages/duckdb-wasm-computation/src/index.ts
+++ b/packages/duckdb-wasm-computation/src/index.ts
@@ -9,7 +9,8 @@ import initWasm, { parser_dsl_with_table } from '@kanaries-temp/gw-dsl-parser';
import dslWasm from '@kanaries-temp/gw-dsl-parser/gw_dsl_parser_bg.wasm?url';
import { nanoid } from 'nanoid';
import { IDataSourceProvider, IMutField, IDataSourceListener, exportFullRaw, fromFields } from '@kanaries/graphic-walker';
-import { MapRow } from 'apache-arrow';
+import { Table } from 'apache-arrow';
+import { bigNumToString } from 'apache-arrow/util/bn';
const MANUAL_BUNDLES: duckdb.DuckDBBundles = {
mvp: {
@@ -45,6 +46,19 @@ export async function init() {
await initWasm(dslWasm);
}
+const transformData = (table: Table) => {
+ return table
+ .toArray()
+ .map((r) =>
+ Object.fromEntries(
+ Object.entries(r.toJSON()).map(([k, v]) => [
+ k,
+ typeof v === 'object' ? parseInt(bigNumToString(v as any)) : typeof v === 'bigint' ? Number(v) : v,
+ ])
+ )
+ );
+};
+
export async function getMemoryProvider(): Promise<IDataSourceProvider> {
await init();
const conn = await db.connect();
@@ -94,11 +108,7 @@ export async function getMemoryProvider(): Promise<IDataSourceProvider> {
if (process.env.NODE_ENV !== 'production') {
console.log(query, sql);
}
- const res = await conn
- .query(sql)
- .then((x) =>
- x.toArray().map((r: MapRow) => Object.fromEntries(Object.entries(r.toJSON()).map(([k, v]) => [k, typeof v === 'bigint' ? Number(v) : v])))
- );
+ const res = await conn.query(sql).then(transformData);
return res;
},
registerCallback(cb) {
@@ -132,11 +142,7 @@ export async function getComputation(data: Record<string, number>[]) {
if (process.env.NODE_ENV !== 'production') {
console.log(query, sql);
}
- const res = await conn
- .query(sql)
- .then((x) =>
- x.toArray().map((r) => Object.fromEntries(Object.entries(r.toJSON()).map(([k, v]) => [k, typeof v === 'bigint' ? Number(v) : v])))
- );
+ const res = await conn.query(sql).then(transformData);
return res;
},
};
diff --git a/packages/graphic-walker/src/Table.tsx b/packages/graphic-walker/src/Table.tsx
index a610c38d..c3138eef 100644
--- a/packages/graphic-walker/src/Table.tsx
+++ b/packages/graphic-walker/src/Table.tsx
@@ -66,7 +66,7 @@ export const TableApp = observer(function VizApp(props: BaseTableProps) {
<ComputationContext.Provider value={wrappedComputation}>
<div className={`${darkMode === 'dark' ? 'dark' : ''} App font-sans bg-white dark:bg-zinc-900 dark:text-white m-0 p-0`}>
<div className="bg-white dark:bg-zinc-900 dark:text-white">
- <DatasetTable size={pageSize} metas={metas} computation={wrappedComputation} />
+ <DatasetTable size={pageSize} metas={metas} computation={wrappedComputation} displayOffset={props.displayOffset} />
</div>
</div>
<Errorpanel />
diff --git a/packages/graphic-walker/src/components/computedField/index.tsx b/packages/graphic-walker/src/components/computedField/index.tsx
index bafef0ce..8f08d5fc 100644
--- a/packages/graphic-walker/src/components/computedField/index.tsx
+++ b/packages/graphic-walker/src/components/computedField/index.tsx
@@ -4,7 +4,7 @@ import { useVizStore } from '../../store';
import DefaultButton from '../button/default';
import PrimaryButton from '../button/primary';
import Modal from '../modal';
-import { parseErrorMessage } from '../../utils';
+import { isNotEmpty, parseErrorMessage } from '../../utils';
import { highlightField } from '../highlightField';
import { aggFuncs, reservedKeywords, sqlFunctions } from '../../lib/sql';
import { COUNT_FIELD_ID, MEA_KEY_ID, MEA_VAL_ID, PAINT_FIELD_ID } from '../../constants';
@@ -53,7 +53,7 @@ const ComputedFieldDialog: React.FC = observer(() => {
}, [vizStore.allFields]);
useEffect(() => {
- if (editingComputedFieldFid !== undefined) {
+ if (isNotEmpty(editingComputedFieldFid)) {
if (editingComputedFieldFid === '') {
let idx = 1;
while (vizStore.allFields.find((x) => x.name === `Computed ${idx}`)) {
@@ -88,7 +88,7 @@ const ComputedFieldDialog: React.FC = observer(() => {
return (
<Modal
- show={editingComputedFieldFid !== undefined}
+ show={isNotEmpty(editingComputedFieldFid)}
onClose={() => {
vizStore.setComputedFieldFid();
}}
diff --git a/packages/graphic-walker/src/components/dataBoard.tsx b/packages/graphic-walker/src/components/dataBoard.tsx
index d1334b7f..b7a7ff82 100644
--- a/packages/graphic-walker/src/components/dataBoard.tsx
+++ b/packages/graphic-walker/src/components/dataBoard.tsx
@@ -6,16 +6,17 @@ import React, { useMemo } from 'react';
import { IComputationFunction, IVisFilter } from '../interfaces';
import { addFilterForQuery, addTransformForQuery, processExpression } from '../utils/workflow';
import { COUNT_FIELD_ID, MEA_KEY_ID, MEA_VAL_ID } from '../constants';
+import { isNotEmpty } from '../utils';
const DataBoard = observer(function DataBoardModal() {
const vizStore = useVizStore();
const computation = useCompututaion();
- const { showDataBoard, selectedMarkObject, allFields } = vizStore;
+ const { showDataBoard, selectedMarkObject, allFields, config } = vizStore;
const filters = useMemo(() => {
const entries: [string, string | number][] = Object.entries(selectedMarkObject).filter(
- (x): x is [string, string | number] => ![MEA_KEY_ID, MEA_VAL_ID, COUNT_FIELD_ID].includes(x[0]) && x[1] !== undefined
+ (x): x is [string, string | number] => ![MEA_KEY_ID, MEA_VAL_ID, COUNT_FIELD_ID].includes(x[0]) && isNotEmpty(x[1])
);
- if (selectedMarkObject[MEA_KEY_ID] !== undefined && selectedMarkObject[MEA_VAL_ID] !== undefined) {
+ if (isNotEmpty(selectedMarkObject[MEA_KEY_ID]) && isNotEmpty(selectedMarkObject[MEA_VAL_ID])) {
entries.push([selectedMarkObject[MEA_KEY_ID] as string, selectedMarkObject[MEA_VAL_ID]]);
}
return entries.map(([k, v]): IVisFilter => ({ fid: k, rule: { type: 'one of', value: [v] } }));
@@ -28,15 +29,15 @@ const DataBoard = observer(function DataBoardModal() {
addTransformForQuery(
addFilterForQuery(query, filters),
computedFileds.map((x) => ({
- expression: processExpression(x.expression!, allFields),
+ expression: processExpression(x.expression!, allFields, config),
key: x.fid!,
}))
)
);
- }, [computation, filters, computedFileds, allFields]);
+ }, [computation, filters, computedFileds, allFields, config]);
const metas = useMemo(() => {
- return allFields.filter(x => x.aggName !== 'expr').filter((x) => ![MEA_KEY_ID, MEA_VAL_ID, COUNT_FIELD_ID].includes(x.fid));
+ return allFields.filter((x) => x.aggName !== 'expr').filter((x) => ![MEA_KEY_ID, MEA_VAL_ID, COUNT_FIELD_ID].includes(x.fid));
}, [allFields]);
return (
@@ -47,7 +48,7 @@ const DataBoard = observer(function DataBoardModal() {
}}
>
<div className="mt-4">
- <DataTable size={100} computation={filteredComputation} metas={metas} disableFilter />
+ <DataTable size={100} computation={filteredComputation} metas={metas} disableFilter displayOffset={config.timezoneDisplayOffset} />
</div>
</Modal>
);
diff --git a/packages/graphic-walker/src/components/dataTable/index.tsx b/packages/graphic-walker/src/components/dataTable/index.tsx
index f3f601cb..ee240716 100644
--- a/packages/graphic-walker/src/components/dataTable/index.tsx
+++ b/packages/graphic-walker/src/components/dataTable/index.tsx
@@ -11,7 +11,7 @@ import { encodeFilterRule } from '../../utils/filter';
import { PureFilterEditDialog } from '../../fields/filterField/filterEditDialog';
import { BarsArrowDownIcon, BarsArrowUpIcon, FunnelIcon } from '@heroicons/react/24/outline';
import { ComputationContext } from '../../store';
-import { newOffsetDate } from '../../lib/op/offset';
+import { parsedOffsetDate } from '../../lib/op/offset';
import { formatDate } from '../../utils';
interface DataTableProps {
@@ -21,6 +21,7 @@ interface DataTableProps {
computation: IComputationFunction;
onMetaChange?: (fid: string, fIndex: number, meta: Partial<IMutField>) => void;
disableFilter?: boolean;
+ displayOffset?: number;
}
const Container = styled.div`
overflow-x: auto;
@@ -161,16 +162,16 @@ function useFilters(metas: IMutField[]) {
return { filters, options, editingFilterIdx, onSelectFilter, onDeleteFilter, onWriteFilter, onClose };
}
-function FieldValue(props: { field: IMutField; item: IRow }) {
+function FieldValue(props: { field: IMutField; item: IRow; displayOffset?: number }) {
const { field, item } = props;
if (field.semanticType === 'temporal') {
- return <>{formatDate(newOffsetDate(field.offset)(item[field.fid]))}</>;
+ return <>{formatDate(parsedOffsetDate(props.displayOffset, field.offset)(item[field.fid]))}</>;
}
return <>{`${item[field.fid]}`}</>;
}
const DataTable: React.FC<DataTableProps> = (props) => {
- const { size = 10, onMetaChange, metas, computation, disableFilter } = props;
+ const { size = 10, onMetaChange, metas, computation, disableFilter, displayOffset } = props;
const [pageIndex, setPageIndex] = useState(0);
const { t } = useTranslation();
const computationFunction = computation;
@@ -406,7 +407,7 @@ const DataTable: React.FC<DataTableProps> = (props) => {
key={field.fid + index}
className={getHeaderType(field) + ' whitespace-nowrap py-2 px-4 text-xs text-gray-500 dark:text-gray-300'}
>
- <FieldValue field={field} item={row} />
+ <FieldValue field={field} item={row} displayOffset={displayOffset} />
</td>
))}
</tr>
@@ -427,6 +428,7 @@ const DataTable: React.FC<DataTableProps> = (props) => {
onWriteFilter={onWriteFilter}
options={options}
viewFilters={filters}
+ displayOffset={displayOffset}
/>
</div>
</ComputationContext.Provider>
diff --git a/packages/graphic-walker/src/components/explainData/index.tsx b/packages/graphic-walker/src/components/explainData/index.tsx
index 62541504..dca68732 100644
--- a/packages/graphic-walker/src/components/explainData/index.tsx
+++ b/packages/graphic-walker/src/components/explainData/index.tsx
@@ -1,197 +1,193 @@
-import React, { useEffect, useState, useRef, useMemo } from "react";
-import Modal from "../modal";
-import { observer } from "mobx-react-lite";
-import { useCompututaion, useVizStore } from "../../store";
-import { useTranslation } from "react-i18next";
+import React, { useEffect, useState, useRef, useMemo } from 'react';
+import Modal from '../modal';
+import { observer } from 'mobx-react-lite';
+import { useCompututaion, useVizStore } from '../../store';
+import { useTranslation } from 'react-i18next';
import { getMeaAggKey } from '../../utils';
import styled from 'styled-components';
-import embed from "vega-embed";
-import { VegaGlobalConfig, IDarkMode, IThemeKey, IField, IRow, IPredicate } from "../../interfaces";
+import embed from 'vega-embed';
+import { VegaGlobalConfig, IDarkMode, IThemeKey, IField, IRow, IPredicate } from '../../interfaces';
import { builtInThemes } from '../../vis/theme';
-import { explainBySelection } from "../../lib/insights/explainBySelection"
+import { explainBySelection } from '../../lib/insights/explainBySelection';
const Container = styled.div`
- height: 50vh;
- overflow-y: hidden;
+ height: 50vh;
+ overflow-y: hidden;
`;
const TabsList = styled.div`
- display: flex;
- flex-direction: column;
- align-items: stretch;
- justify-content: stretch;
- height: 100%;
- overflow-y: scroll;
+ display: flex;
+ flex-direction: column;
+ align-items: stretch;
+ justify-content: stretch;
+ height: 100%;
+ overflow-y: scroll;
`;
const Tab = styled.div`
- margin-block: 0.2em;
- margin-inline: 0.2em;
- padding: 0.5em;
- border: 2px solid gray;
- cursor: pointer;
+ margin-block: 0.2em;
+ margin-inline: 0.2em;
+ padding: 0.5em;
+ border: 2px solid gray;
+ cursor: pointer;
`;
const getCategoryName = (row: IRow, field: IField) => {
- if (field.semanticType === "quantitative") {
- let id = field.fid;
- return `${row[id][0].toFixed(2)}-${row[id][1].toFixed(2)}`;
- } else {
- return row[field.fid];
- }
-}
+ if (field.semanticType === 'quantitative') {
+ let id = field.fid;
+ return `${row[id][0].toFixed(2)}-${row[id][1].toFixed(2)}`;
+ } else {
+ return row[field.fid];
+ }
+};
const ExplainData: React.FC<{
- dark: IDarkMode,
- themeKey: IThemeKey
-}> = observer(({dark, themeKey}) => {
+ dark: IDarkMode;
+ themeKey: IThemeKey;
+}> = observer(({ dark, themeKey }) => {
const vizStore = useVizStore();
const computationFunction = useCompututaion();
- const { allFields, viewMeasures, viewDimensions, viewFilters, showInsightBoard, selectedMarkObject } = vizStore;
- const [ explainDataInfoList, setExplainDataInfoList ] = useState<{
- score: number;
- measureField: IField;
- targetField: IField;
- normalizedData: IRow[];
- normalizedParentData: IRow[]
- }[]>([]);
- const [ selectedInfoIndex, setSelectedInfoIndex ] = useState(0);
+ const { allFields, viewMeasures, viewDimensions, viewFilters, showInsightBoard, selectedMarkObject, config } = vizStore;
+ const { timezoneDisplayOffset } = config;
+ const [explainDataInfoList, setExplainDataInfoList] = useState<
+ {
+ score: number;
+ measureField: IField;
+ targetField: IField;
+ normalizedData: IRow[];
+ normalizedParentData: IRow[];
+ }[]
+ >([]);
+ const [selectedInfoIndex, setSelectedInfoIndex] = useState(0);
const chartRef = useRef<HTMLDivElement>(null);
const vegaConfig = useMemo<VegaGlobalConfig>(() => {
- const config: VegaGlobalConfig = {
- ...builtInThemes[themeKey ?? 'vega']?.[dark],
- }
- return config;
- }, [themeKey, dark])
+ const config: VegaGlobalConfig = {
+ ...builtInThemes[themeKey ?? 'vega']?.[dark],
+ };
+ return config;
+ }, [themeKey, dark]);
const { t } = useTranslation();
-
+
const explain = async (predicates) => {
- const explainInfoList = await explainBySelection({predicates, viewFilters, allFields, viewMeasures, viewDimensions, computationFunction});
- setExplainDataInfoList(explainInfoList);
- }
+ const explainInfoList = await explainBySelection({ predicates, viewFilters, allFields, viewMeasures, viewDimensions, computationFunction, timezoneDisplayOffset });
+ setExplainDataInfoList(explainInfoList);
+ };
useEffect(() => {
- if (!showInsightBoard || Object.keys(selectedMarkObject).length === 0) return;
- const predicates: IPredicate[] = viewDimensions.map((field) => {
- return {
- key: field.fid,
- type: "discrete",
- range: new Set([selectedMarkObject[field.fid]])
- } as IPredicate
- });
- explain(predicates)
+ if (!showInsightBoard || Object.keys(selectedMarkObject).length === 0) return;
+ const predicates: IPredicate[] = viewDimensions.map((field) => {
+ return {
+ key: field.fid,
+ type: 'discrete',
+ range: new Set([selectedMarkObject[field.fid]]),
+ } as IPredicate;
+ });
+ explain(predicates);
}, [viewMeasures, viewDimensions, showInsightBoard, selectedMarkObject]);
useEffect(() => {
- if (chartRef.current && explainDataInfoList.length > 0) {
- const { normalizedData, normalizedParentData, targetField, measureField } = explainDataInfoList[selectedInfoIndex];
- const { semanticType: targetType, name: targetName, fid: targetId } = targetField;
- const data = [
- ...normalizedData.map((row) => ({
- category: getCategoryName(row, targetField),
- ...row,
- type: "child",
- })),
- ...normalizedParentData.map((row) => ({
- category: getCategoryName(row, targetField),
- ...row,
- type: "parent",
- })),
- ];
- const xField = {
- x: {
- field: "category",
- type: targetType === "quantitative" ? "ordinal" : targetType,
- axis: {
- title: `Distribution of Values for ${targetName}`,
- },
- },
- };
- const spec:any = {
- data: {
- values: data,
- },
- width: 320,
- height: 200,
- encoding: {
- ...xField,
- color: {
- legend: {
- orient: "bottom",
- },
- },
- },
- layer: [
- {
- mark: {
- type: "bar",
- width: 15,
- opacity: 0.7,
- },
- encoding: {
- y: {
- field: getMeaAggKey(measureField.fid, measureField.aggName),
- type: "quantitative",
- title: `${measureField.aggName} ${measureField.name} for All Marks`,
+ if (chartRef.current && explainDataInfoList.length > 0) {
+ const { normalizedData, normalizedParentData, targetField, measureField } = explainDataInfoList[selectedInfoIndex];
+ const { semanticType: targetType, name: targetName, fid: targetId } = targetField;
+ const data = [
+ ...normalizedData.map((row) => ({
+ category: getCategoryName(row, targetField),
+ ...row,
+ type: 'child',
+ })),
+ ...normalizedParentData.map((row) => ({
+ category: getCategoryName(row, targetField),
+ ...row,
+ type: 'parent',
+ })),
+ ];
+ const xField = {
+ x: {
+ field: 'category',
+ type: targetType === 'quantitative' ? 'ordinal' : targetType,
+ axis: {
+ title: `Distribution of Values for ${targetName}`,
+ },
},
- color: { datum: "All Marks" },
- },
- transform: [{ filter: "datum.type === 'parent'" }],
- },
- {
- mark: {
- type: "bar",
- width: 10,
- opacity: 0.7,
- },
- encoding: {
- y: {
- field: getMeaAggKey(measureField.fid, measureField.aggName),
- type: "quantitative",
- title: `${measureField.aggName} ${measureField.name} for Selected Mark`,
+ };
+ const spec: any = {
+ data: {
+ values: data,
},
- color: { datum: "Selected Mark" },
- },
- transform: [{ filter: "datum.type === 'child'" }],
- },
- ],
- resolve: { scale: { y: "independent" } },
- };
-
- embed(chartRef.current, spec, { mode: 'vega-lite', actions: false, config: vegaConfig });
- }
+ width: 320,
+ height: 200,
+ encoding: {
+ ...xField,
+ color: {
+ legend: {
+ orient: 'bottom',
+ },
+ },
+ },
+ layer: [
+ {
+ mark: {
+ type: 'bar',
+ width: 15,
+ opacity: 0.7,
+ },
+ encoding: {
+ y: {
+ field: getMeaAggKey(measureField.fid, measureField.aggName),
+ type: 'quantitative',
+ title: `${measureField.aggName} ${measureField.name} for All Marks`,
+ },
+ color: { datum: 'All Marks' },
+ },
+ transform: [{ filter: "datum.type === 'parent'" }],
+ },
+ {
+ mark: {
+ type: 'bar',
+ width: 10,
+ opacity: 0.7,
+ },
+ encoding: {
+ y: {
+ field: getMeaAggKey(measureField.fid, measureField.aggName),
+ type: 'quantitative',
+ title: `${measureField.aggName} ${measureField.name} for Selected Mark`,
+ },
+ color: { datum: 'Selected Mark' },
+ },
+ transform: [{ filter: "datum.type === 'child'" }],
+ },
+ ],
+ resolve: { scale: { y: 'independent' } },
+ };
+
+ embed(chartRef.current, spec, { mode: 'vega-lite', actions: false, config: vegaConfig });
+ }
}, [explainDataInfoList, chartRef.current, selectedInfoIndex, vegaConfig]);
return (
<Modal
- show={showInsightBoard}
- onClose={() => {
- vizStore.setShowInsightBoard(false);
- setSelectedInfoIndex(0);
- }}
+ show={showInsightBoard}
+ onClose={() => {
+ vizStore.setShowInsightBoard(false);
+ setSelectedInfoIndex(0);
+ }}
>
- <Container className="grid grid-cols-4">
- <TabsList className="col-span-1">
- {
- explainDataInfoList.map((option, i) => {
- return (
- <Tab
- key={i}
- className={`${selectedInfoIndex === i ? 'border-indigo-400' : ''
- } text-xs`}
- onClick={() => setSelectedInfoIndex(i)}
- >
- {option.targetField.name} {option.score.toFixed(2)}
- </Tab>
- )
- })
- }
- </TabsList>
- <div className="col-span-3 text-center overflow-y-scroll">
- <div ref={chartRef}></div>
- </div>
- </Container>
+ <Container className="grid grid-cols-4">
+ <TabsList className="col-span-1">
+ {explainDataInfoList.map((option, i) => {
+ return (
+ <Tab key={i} className={`${selectedInfoIndex === i ? 'border-indigo-400' : ''} text-xs`} onClick={() => setSelectedInfoIndex(i)}>
+ {option.targetField.name} {option.score.toFixed(2)}
+ </Tab>
+ );
+ })}
+ </TabsList>
+ <div className="col-span-3 text-center overflow-y-scroll">
+ <div ref={chartRef}></div>
+ </div>
+ </Container>
</Modal>
);
});
diff --git a/packages/graphic-walker/src/components/leafletRenderer/encodings.ts b/packages/graphic-walker/src/components/leafletRenderer/encodings.ts
index 74e6788f..86ed65d2 100644
--- a/packages/graphic-walker/src/components/leafletRenderer/encodings.ts
+++ b/packages/graphic-walker/src/components/leafletRenderer/encodings.ts
@@ -1,7 +1,7 @@
import { useCallback, useMemo } from 'react';
import { scaleLinear, scaleOrdinal } from 'd3-scale';
import type { IChannelScales, IRow, IScale, IViewField, VegaGlobalConfig } from '../../interfaces';
-import { getMeaAggKey } from '../../utils';
+import { getMeaAggKey, isNotEmpty } from '../../utils';
import { getColor } from '../../utils/useTheme';
import { resolveScale } from '../../vis/spec/view';
@@ -109,14 +109,14 @@ const useDomain = (key: string, data: IRow[], scale?: IScale) => {
minDomain = Number(scale.domain[0]);
maxDomain = Number(scale.domain[1]);
}
- if (scale.domainMin !== undefined) {
+ if (isNotEmpty(scale.domainMin)) {
minDomain = scale.domainMin;
}
- if (scale.domainMax !== undefined) {
+ if (isNotEmpty(scale.domainMax)) {
maxDomain = scale.domainMax;
}
}
- if (minDomain !== undefined && maxDomain !== undefined) {
+ if (isNotEmpty(minDomain) && isNotEmpty(maxDomain)) {
return [minDomain, maxDomain];
}
if (!key) {
@@ -151,10 +151,10 @@ const useRange = (defaultMin: number, defaultMax: number, scale?: IScale) => {
minRange = Number(scale.range[0]);
maxRange = Number(scale.range[1]);
}
- if (scale.rangeMin !== undefined) {
+ if (isNotEmpty(scale.rangeMin)) {
minRange = scale.rangeMin;
}
- if (scale.rangeMax !== undefined) {
+ if (isNotEmpty(scale.rangeMax)) {
maxRange = scale.rangeMax;
}
}
diff --git a/packages/graphic-walker/src/components/painter/index.tsx b/packages/graphic-walker/src/components/painter/index.tsx
index 9d1da0cd..336a518e 100644
--- a/packages/graphic-walker/src/components/painter/index.tsx
+++ b/packages/graphic-walker/src/components/painter/index.tsx
@@ -110,6 +110,7 @@ const PainterContent = (props: {
onChangeDict: (d: typeof defaultScheme) => void;
paintMapRef: React.MutableRefObject<Uint8Array | undefined>;
allFields: IViewField[];
+ displayOffset?: number;
onReset: () => void;
onDelete: () => void;
onCancel: () => void;
@@ -146,6 +147,7 @@ const PainterContent = (props: {
sort: 'none',
viewDimensions: emptyField,
viewMeasures: fields,
+ timezoneDisplayOffset: props.displayOffset,
});
const indexes = useMemo(() => viewData.map(calcIndexesByDimensions([props.domainY, props.domainX])), [viewData, props.domainX, props.domainY]);
const [data, loadingResult] = useAsyncMemo(async () => {
@@ -452,7 +454,7 @@ function toZeroscaled([min, max]: [number, number]): [number, number] {
const Painter = ({ dark, themeConfig, themeKey }: { dark?: IDarkMode; themeConfig?: GWGlobalConfig; themeKey?: IThemeKey }) => {
const vizStore = useVizStore();
const { showPainterPanel, allFields, layout, config } = vizStore;
- const { geoms } = config;
+ const { geoms, timezoneDisplayOffset } = config;
const { zeroScale } = layout;
const { t } = useTranslation();
const compuation = useCompututaion();
@@ -636,6 +638,7 @@ const Painter = ({ dark, themeConfig, themeKey }: { dark?: IDarkMode; themeConfi
onChangeDict={setDict}
paintMapRef={paintMapRef}
onReset={onReset}
+ displayOffset={timezoneDisplayOffset}
/>
)}
</Modal>
diff --git a/packages/graphic-walker/src/components/pivotTable/index.tsx b/packages/graphic-walker/src/components/pivotTable/index.tsx
index ddeb8809..c7025516 100644
--- a/packages/graphic-walker/src/components/pivotTable/index.tsx
+++ b/packages/graphic-walker/src/components/pivotTable/index.tsx
@@ -154,8 +154,19 @@ const PivotTable: React.FC<PivotTableProps> = observer(function PivotTableCompon
appRef.current?.updateRenderStatus('computing');
const groupbyPromises: Promise<IRow[]>[] = groupbyCombList.map((dimComb) => {
if (!vizStore) return Promise.resolve([]);
- const { viewFilters, allFields, viewMeasures, sort, limit } = vizStore;
- const workflow = toWorkflow(viewFilters, allFields, dimComb, viewMeasures, defaultAggregated, sort, folds ?? [], limit > 0 ? limit : undefined);
+ const { viewFilters, allFields, viewMeasures, sort, limit, config } = vizStore;
+ const { timezoneDisplayOffset } = config;
+ const workflow = toWorkflow(
+ viewFilters,
+ allFields,
+ dimComb,
+ viewMeasures,
+ defaultAggregated,
+ sort,
+ folds ?? [],
+ limit > 0 ? limit : undefined,
+ timezoneDisplayOffset
+ );
return dataQuery(computation, workflow, limit > 0 ? limit : undefined)
.then((res) => fold2(res, defaultAggregated, allFields, viewMeasures, dimComb, folds))
.catch((err) => {
diff --git a/packages/graphic-walker/src/components/visualConfig/index.tsx b/packages/graphic-walker/src/components/visualConfig/index.tsx
index 07cdfea8..0c38f4bd 100644
--- a/packages/graphic-walker/src/components/visualConfig/index.tsx
+++ b/packages/graphic-walker/src/components/visualConfig/index.tsx
@@ -17,6 +17,8 @@ import { ColorSchemes, extractRGBA } from './colorScheme';
import { RangeScale } from './range-scale';
import { ConfigItemContainer, ConfigItemContent, ConfigItemHeader, ConfigItemTitle } from './config-item';
import { KVTuple } from '../../models/utils';
+import { isNotEmpty } from '../../utils';
+import { timezones } from './timezone';
const DEFAULT_COLOR_SCHEME = ['#5B8FF9', '#FF6900', '#FCB900', '#7BDCB5', '#00D084', '#8ED1FC', '#0693E3', '#ABB8C3', '#EB144C', '#F78DA7', '#9900EF'];
@@ -30,9 +32,9 @@ function useScale(minRange: number, maxRange: number, defaultMinRange?: number,
const [rangeMax, setRangeMax] = useState(defaultMaxRange ?? maxRange);
const setValue = useCallback(
(value: IConfigScale) => {
- setEnableMaxDomain(value.domainMax !== undefined);
- setEnableMinDomain(value.domainMin !== undefined);
- setEnableRange(value.rangeMax !== undefined || value.rangeMin !== undefined);
+ setEnableMaxDomain(isNotEmpty(value.domainMax));
+ setEnableMinDomain(isNotEmpty(value.domainMin));
+ setEnableRange(isNotEmpty(value.rangeMax) || isNotEmpty(value.rangeMin));
setDomainMin(value.domainMin ?? 0);
setDomainMax(value.domainMax ?? 100);
setRangeMax(value.rangeMax ?? defaultMaxRange ?? maxRange);
@@ -72,7 +74,7 @@ function useScale(minRange: number, maxRange: number, defaultMinRange?: number,
const VisualConfigPanel: React.FC = () => {
const vizStore = useVizStore();
- const { layout, showVisualConfigPanel } = vizStore;
+ const { layout, showVisualConfigPanel, config } = vizStore;
const { t } = useTranslation();
const formatConfigList: (keyof IVisualConfig['format'])[] = ['numberFormat', 'timeFormat', 'normalizedNumberFormat'];
const [format, setFormat] = useState<IVisualConfig['format']>({
@@ -97,6 +99,9 @@ const VisualConfigPanel: React.FC = () => {
const [displayColorPicker, setDisplayColorPicker] = useState(false);
const [colorPalette, setColorPalette] = useState('');
const [geoMapTileUrl, setGeoMapTileUrl] = useState<string | undefined>(undefined);
+ const [displayOffset, setDisplayOffset] = useState<number | undefined>(undefined);
+ const [displayOffsetEdited, setDisplayOffsetEdited] = useState(false);
+
const opacityValue = useScale(0, 1, 0.3, 0.8);
const sizeValue = useScale(0, 100);
@@ -117,6 +122,8 @@ const VisualConfigPanel: React.FC = () => {
opacityValue.setValue(layout.scale?.opacity ?? {});
sizeValue.setValue(layout.scale?.size ?? {});
setGeoMapTileUrl(layout.geoMapTileUrl);
+ setDisplayOffset(config.timezoneDisplayOffset);
+ setDisplayOffsetEdited(false);
}, [showVisualConfigPanel]);
return (
@@ -301,47 +308,74 @@ const VisualConfigPanel: React.FC = () => {
<ConfigItemTitle>{t('config.misc')}</ConfigItemTitle>
</ConfigItemHeader>
<ConfigItemContent>
- <div className="flex flex-col space-y-2 mb-2">
- <Toggle
- label={t(`config.customTile`)}
- enabled={geoMapTileUrl !== undefined}
- onChange={(e) => {
- setGeoMapTileUrl(e ? 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png' : undefined);
- }}
- />
- {geoMapTileUrl !== undefined && (
- <input
- type="text"
- className="block w-full text-gray-700 dark:text-gray-200 rounded-md border-0 py-1 px-2 shadow-sm ring-1 ring-inset ring-gray-300 dark:ring-gray-600 placeholder:text-gray-400 focus:ring-1 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6 dark:bg-zinc-900 "
- value={geoMapTileUrl}
+ <div className="flex flex-col space-y-2">
+ <div className="flex flex-col space-y-2">
+ <Toggle
+ label={t(`config.customTile`)}
+ enabled={isNotEmpty(geoMapTileUrl)}
onChange={(e) => {
- setGeoMapTileUrl(e.target.value);
+ setGeoMapTileUrl(e ? 'https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png' : undefined);
}}
/>
- )}
- </div>
- <div className="flex space-x-6">
- <Toggle
- label={t(`config.zeroScale`)}
- enabled={zeroScale}
- onChange={(en) => {
- setZeroScale(en);
- }}
- />
- <Toggle
- label={t(`config.svg`)}
- enabled={svg}
- onChange={(en) => {
- setSvg(en);
- }}
- />
- <Toggle
- label="include unmatched choropleth in scale"
- enabled={scaleIncludeUnmatchedChoropleth}
- onChange={(en) => {
- setScaleIncludeUnmatchedChoropleth(en);
- }}
- />
+ {isNotEmpty(geoMapTileUrl) && (
+ <input
+ type="text"
+ className="block w-full text-gray-700 dark:text-gray-200 rounded-md border-0 py-1 px-2 shadow-sm ring-1 ring-inset ring-gray-300 dark:ring-gray-600 placeholder:text-gray-400 focus:ring-1 focus:ring-inset focus:ring-indigo-600 sm:text-sm sm:leading-6 dark:bg-zinc-900 "
+ value={geoMapTileUrl}
+ onChange={(e) => {
+ setGeoMapTileUrl(e.target.value);
+ }}
+ />
+ )}
+ </div>
+ <div className="flex space-x-6">
+ <Toggle
+ label={t(`config.zeroScale`)}
+ enabled={zeroScale}
+ onChange={(en) => {
+ setZeroScale(en);
+ }}
+ />
+ <Toggle
+ label={t(`config.svg`)}
+ enabled={svg}
+ onChange={(en) => {
+ setSvg(en);
+ }}
+ />
+ <Toggle
+ label="include unmatched choropleth in scale"
+ enabled={scaleIncludeUnmatchedChoropleth}
+ onChange={(en) => {
+ setScaleIncludeUnmatchedChoropleth(en);
+ }}
+ />
+ </div>
+ <div className="flex flex-col space-y-2">
+ <Toggle
+ label={t(`config.customOffset`)}
+ enabled={isNotEmpty(displayOffset)}
+ onChange={(e) => {
+ setDisplayOffsetEdited(true);
+ setDisplayOffset(e ? new Date().getTimezoneOffset() : undefined);
+ }}
+ />
+ {isNotEmpty(displayOffset) && (
+ <DropdownSelect
+ className="w-full "
+ buttonClassName="w-full"
+ selectedKey={`${displayOffset}`}
+ onSelect={(e) => {
+ setDisplayOffsetEdited(true);
+ setDisplayOffset(parseInt(e));
+ }}
+ options={timezones.map((tz) => ({
+ value: `${tz.value}`,
+ label: <span title={tz.name}>{tz.name}</span>,
+ }))}
+ />
+ )}
+ </div>
</div>
</ConfigItemContent>
</ConfigItemContainer>
@@ -371,6 +405,7 @@ const VisualConfigPanel: React.FC = () => {
: []),
['geoMapTileUrl', geoMapTileUrl]
);
+ displayOffsetEdited && vizStore.setVisualConfig('timezoneDisplayOffset', displayOffset);
vizStore.setShowVisualConfigPanel(false);
});
}}
diff --git a/packages/graphic-walker/src/components/visualConfig/timezone.ts b/packages/graphic-walker/src/components/visualConfig/timezone.ts
new file mode 100644
index 00000000..cb0c57b6
--- /dev/null
+++ b/packages/graphic-walker/src/components/visualConfig/timezone.ts
@@ -0,0 +1,80 @@
+export const timezones = [
+ { value: 720, name: '(UTC-12:00) Dateline Standard Time' },
+ { value: 660, name: '(UTC-11:00) Niue Time, Samoa Standard Time' },
+ { value: 600, name: '(UTC-10:00) Cook Is. Time, Hawaii Standard Time, Tahiti Time' },
+ { value: 570, name: '(UTC-09:30) Marquesas Time' },
+ { value: 540, name: '(UTC-09:00) Gambier Time, Hawaii Daylight Time' },
+ { value: 480, name: '(UTC-08:00) Alaska Daylight Time, Pacific Standard Time, Pitcairn Standard Time' },
+ { value: 420, name: '(UTC-07:00) Mountain Standard Time, Pacific Daylight Time' },
+ { value: 360, name: '(UTC-06:00) Central Standard Time, Galapagos Time, Mountain Daylight Time' },
+ { value: 300, name: '(UTC-05:00) Acre Time, Central Daylight Time, Colombia Time, Easter Is. Time, Eastern Standard Time, Ecuador Time, Peru Time' },
+ { value: 270, name: '(UTC-04:30) Venezuela Time' },
+ {
+ value: 240,
+ name: '(UTC-04:00) Amazon Time, Atlantic Standard Time, Bolivia Time, Cuba Daylight Time, Eastern Daylight Time, Guyana Time, Paraguay Time',
+ },
+ {
+ value: 180,
+ name: '(UTC-03:00) Argentine Time, Atlantic Daylight Time, Brasilia Time, Chile Time, Falkland Is. Time, French Guiana Time, Rothera Time, Suriname Time, Uruguay Time',
+ },
+ { value: 150, name: '(UTC-02:30) Newfoundland Daylight Time' },
+ {
+ value: 120,
+ name: '(UTC-02:00) Fernando de Noronha Time, Pierre & Miquelon Daylight Time, South Georgia Standard Time, Western Greenland Summer Time',
+ },
+ { value: 60, name: '(UTC-01:00) Cape Verde Time' },
+ { value: 0, name: '(UTC) Azores Summer Time, Coordinated Universal Time, Eastern Greenland Summer Time, Ghana Mean Time, Greenwich Mean Time' },
+ { value: -60, name: '(UTC+01:00) British Summer Time, Central European Time, Irish Summer Time, Western African Time, Western European Summer Time' },
+ {
+ value: -120,
+ name: '(UTC+02:00) Central African Time, Central European Summer Time, Eastern European Time, Middle Europe Summer Time, South Africa Standard Time',
+ },
+ {
+ value: -180,
+ name: '(UTC+03:00) Arabia Standard Time, Eastern African Time, Eastern European Summer Time, Israel Daylight Time, Moscow Standard Time, Syowa Time',
+ },
+ { value: -240, name: '(UTC+04:00) Armenia Time, Georgia Time, Gulf Standard Time, Mauritius Time, Reunion Time, Samara Time, Seychelles Time' },
+ { value: -270, name: '(UTC+04:30) Afghanistan Time, Iran Daylight Time' },
+ {
+ value: -300,
+ name: '(UTC+05:00) Aqtau Time, Aqtobe Time, Azerbaijan Summer Time, French Southern & Antarctic Lands Time, Maldives Time, Mawson Time, Oral Time, Pakistan Time, Tajikistan Time, Turkmenistan Time, Uzbekistan Time, Yekaterinburg Time',
+ },
+ { value: -330, name: '(UTC+05:30) India Standard Time' },
+ { value: -345, name: '(UTC+05:45) Nepal Time' },
+ {
+ value: -360,
+ name: '(UTC+06:00) Alma-Ata Time, Bangladesh Time, Bhutan Time, Indian Ocean Territory Time, Kirgizstan Time, Novosibirsk Time, Omsk Time, Qyzylorda Time, Vostok Time, Xinjiang Standard Time',
+ },
+ { value: -390, name: '(UTC+06:30) Cocos Islands Time, Myanmar Time' },
+ { value: -420, name: '(UTC+07:00) Christmas Island Time, Davis Time, Indochina Time, Krasnoyarsk Time, West Indonesia Time' },
+ {
+ value: -480,
+ name: '(UTC+08:00) Australian Western Standard Time, Brunei Time, Central Indonesia Time, China Standard Time, Hong Kong Time, Hovd Summer Time, Irkutsk Time, Malaysia Time, Philippines Time, Singapore Time',
+ },
+ { value: -525, name: '(UTC+08:45) Australian Central Western Standard Time' },
+ {
+ value: -540,
+ name: '(UTC+09:00) Choibalsan Summer Time, East Indonesia Time, Japan Standard Time, Khandyga Time, Korea Standard Time, Palau Time, Timor-Leste Time, Ulaanbaatar Summer Time, Yakutsk Time',
+ },
+ {
+ value: -570,
+ name: '(UTC+09:30) Australian Central Standard Time (Northern Territory), Australian Central Standard Time (South Australia), Australian Central Standard Time (South Australia/New South Wales)',
+ },
+ {
+ value: -600,
+ name: "(UTC+10:00) Australian Eastern Standard Time (New South Wales), Australian Eastern Standard Time (Queensland), Australian Eastern Standard Time (Tasmania), Australian Eastern Standard Time (Victoria), Chamorro Standard Time, Chuuk Time, Dumont-d'Urville Time, Magadan Time, Papua New Guinea Time, Sakhalin Time, Ust-Nera Time, Vladivostok Time",
+ },
+ { value: -630, name: '(UTC+10:30) Lord Howe Standard Time' },
+ {
+ value: -660,
+ name: '(UTC+11:00) Bougainville Standard Time, Kosrae Time, Macquarie Island Standard Time, New Caledonia Time, Pohnpei Time, Solomon Is. Time, Srednekolymsk Time, Vanuatu Time',
+ },
+ { value: -690, name: '(UTC+11:30) Norfolk Time' },
+ {
+ value: -720,
+ name: '(UTC+12:00) Anadyr Time, Fiji Time, Gilbert Is. Time, Marshall Islands Time, Nauru Time, New Zealand Standard Time, Petropavlovsk-Kamchatski Time, Tuvalu Time, Wake Time, Wallis & Futuna Time',
+ },
+ { value: -765, name: '(UTC+12:45) Chatham Standard Time' },
+ { value: -780, name: '(UTC+13:00) Phoenix Is. Time, Tokelau Time, Tonga Time, West Samoa Standard Time' },
+ { value: -840, name: '(UTC+14:00) Line Is. Time' },
+];
diff --git a/packages/graphic-walker/src/computation/index.ts b/packages/graphic-walker/src/computation/index.ts
index 16bf0739..0d9fca57 100644
--- a/packages/graphic-walker/src/computation/index.ts
+++ b/packages/graphic-walker/src/computation/index.ts
@@ -88,13 +88,8 @@ export const dataReadRaw = async (
};
export const dataQuery = async (service: IComputationFunction, workflow: IDataQueryWorkflowStep[], limit?: number): Promise<IRow[]> => {
- const viewWorkflow = workflow.find(x => x.type === 'view') as IViewWorkflowStep | undefined;
- if (
- viewWorkflow &&
- viewWorkflow.query.length === 1 &&
- viewWorkflow.query[0].op === 'raw' &&
- viewWorkflow.query[0].fields.length === 0
- ) {
+ const viewWorkflow = workflow.find((x) => x.type === 'view') as IViewWorkflowStep | undefined;
+ if (viewWorkflow && viewWorkflow.query.length === 1 && viewWorkflow.query[0].op === 'raw' && viewWorkflow.query[0].fields.length === 0) {
return [];
}
const res = await service({
@@ -115,10 +110,11 @@ export const fieldStat = async (
valuesLimit?: number;
valuesOffset?: number;
sortBy?: 'value' | 'value_dsc' | 'count' | 'count_dsc' | 'none';
+ timezoneDisplayOffset?: number;
},
allFields: IMutField[]
): Promise<IFieldStats> => {
- const { values = true, range = true, valuesMeta = true, sortBy = 'none' } = options;
+ const { values = true, range = true, valuesMeta = true, sortBy = 'none', timezoneDisplayOffset } = options;
const COUNT_ID = `count_${field.fid}`;
const TOTAL_DISTINCT_ID = `total_distinct_${field.fid}`;
const MIN_ID = `min_${field.fid}`;
@@ -129,7 +125,7 @@ export const fieldStat = async (
type: 'transform',
transform: [
{
- expression: processExpression(field.expression!, allFields),
+ expression: processExpression(field.expression!, allFields, { timezoneDisplayOffset }),
key: field.fid,
},
],
@@ -371,6 +367,31 @@ export async function getRange(service: IComputationFunction, field: string) {
return [rangeRes[MIN_ID], rangeRes[MAX_ID]] as [number, number];
}
+export function withComputedField(field: IField, allFields: IMutField[], service: IComputationFunction, config: { timezoneDisplayOffset?: number }) {
+ return <T>(builder: (service: IComputationFunction) => Promise<T>) => {
+ const transformWork: ITransformWorkflowStep[] = field.computed
+ ? [
+ {
+ type: 'transform',
+ transform: [
+ {
+ expression: processExpression(field.expression!, allFields, config),
+ key: field.fid,
+ },
+ ],
+ },
+ ]
+ : [];
+ return builder((queryPayload) => {
+ const transformedQueryPayload: IDataQueryPayload = {
+ ...queryPayload,
+ workflow: [...transformWork, ...queryPayload.workflow],
+ };
+ return service(transformedQueryPayload);
+ });
+ };
+}
+
export async function getSample(service: IComputationFunction, field: string) {
const res = await service({
workflow: [
@@ -393,8 +414,8 @@ export async function getSample(service: IComputationFunction, field: string) {
export async function getTemporalRange(service: IComputationFunction, field: string, offset?: number) {
const sample = await getSample(service, field);
const format = getTimeFormat(sample);
- const defaultOffset = new Date().getTimezoneOffset();
- const newDate = newOffsetDate(offset ?? defaultOffset);
+ const usedOffset = offset ?? new Date().getTimezoneOffset();
+ const newDate = newOffsetDate(usedOffset);
const MIN_ID = `min_${field}`;
const MAX_ID = `max_${field}`;
const rangeQueryPayload: IDataQueryPayload = {
@@ -411,12 +432,14 @@ export async function getTemporalRange(service: IComputationFunction, field: str
agg: 'min',
asFieldKey: MIN_ID,
format,
+ offset: usedOffset,
},
{
field,
agg: 'max',
asFieldKey: MAX_ID,
format,
+ offset: usedOffset,
},
],
},
diff --git a/packages/graphic-walker/src/dataSource/datasetConfig/index.tsx b/packages/graphic-walker/src/dataSource/datasetConfig/index.tsx
index 0f0416c1..fcd19924 100644
--- a/packages/graphic-walker/src/dataSource/datasetConfig/index.tsx
+++ b/packages/graphic-walker/src/dataSource/datasetConfig/index.tsx
@@ -15,6 +15,7 @@ const DatasetConfig: React.FC = () => {
size={100}
metas={metas}
computation={computation}
+ displayOffset={vizStore.config.timezoneDisplayOffset}
onMetaChange={(fid, fIndex, diffMeta) => {
vizStore.updateCurrentDatasetMetas(fid, diffMeta);
}}
diff --git a/packages/graphic-walker/src/dataSource/index.tsx b/packages/graphic-walker/src/dataSource/index.tsx
index b82a3011..4d666ab1 100644
--- a/packages/graphic-walker/src/dataSource/index.tsx
+++ b/packages/graphic-walker/src/dataSource/index.tsx
@@ -29,7 +29,7 @@ const DataSourceSegment: React.FC<DSSegmentProps> = observer((props) => {
const { showDSPanel } = commonStore;
return (
- <div className="flex items-center m-4 p-4 border border-gray-200 dark:border-gray-700">
+ <div className="font-sans flex items-center m-4 p-4 border border-gray-200 dark:border-gray-700">
{props.onLoad && <GwFile onImport={props.onLoad} fileRef={gwFileRef} />}
{/* <label className="text-xs mr-1 whitespace-nowrap self-center h-4">
{t("DataSource.labels.cur_dataset")}
@@ -96,6 +96,7 @@ function once<T extends (...args: any[]) => any>(register: (x: T) => () => void,
export function DataSourceSegmentComponent(props: {
provider: IDataSourceProvider;
+ displayOffset?: number;
children: (props: {
meta: IMutField[];
onMetaChange: (fid: string, meta: Partial<IMutField>) => void;
@@ -170,7 +171,11 @@ export function DataSourceSegmentComponent(props: {
[props.provider, selectedId]
);
- const commonStore = useMemo(() => new CommonStore(props.provider, setSelectedId), [props.provider]);
+ const commonStore = useMemo(() => new CommonStore(props.provider, setSelectedId, { displayOffset: props.displayOffset }), [props.provider]);
+
+ useEffect(() => {
+ commonStore.setDisplayOffset(props.displayOffset);
+ }, [props.displayOffset, commonStore]);
const onLoad = useMemo(() => {
const importFile = props.provider.onImportFile;
diff --git a/packages/graphic-walker/src/dataSource/table.tsx b/packages/graphic-walker/src/dataSource/table.tsx
index 89688a5e..50a0406e 100644
--- a/packages/graphic-walker/src/dataSource/table.tsx
+++ b/packages/graphic-walker/src/dataSource/table.tsx
@@ -11,7 +11,7 @@ interface TableProps {
}
const Table: React.FC<TableProps> = ({ commonStore, size = 10 }) => {
- const { tmpDSRawFields, tmpDataSource } = commonStore;
+ const { tmpDSRawFields, tmpDataSource, displayOffset } = commonStore;
const metas = toJS(tmpDSRawFields);
@@ -23,6 +23,7 @@ const Table: React.FC<TableProps> = ({ commonStore, size = 10 }) => {
size={size}
metas={metas}
computation={computation}
+ displayOffset={displayOffset}
onMetaChange={(fid, fIndex, diffMeta) => {
commonStore.updateTempDatasetMetas(fid, diffMeta);
}}
diff --git a/packages/graphic-walker/src/fields/datasetFields/utils.ts b/packages/graphic-walker/src/fields/datasetFields/utils.ts
index ef19ebab..bfa19e7a 100644
--- a/packages/graphic-walker/src/fields/datasetFields/utils.ts
+++ b/packages/graphic-walker/src/fields/datasetFields/utils.ts
@@ -15,7 +15,6 @@ export const useMenuActions = (channel: 'dimensions' | 'measures'): IActionMenuI
const fields = vizStore.currentVis.encodings[channel];
const { t } = useTranslation('translation', { keyPrefix: 'field_menu' });
const computation = useCompututaion();
- const defaultOffset = new Date().getTimezoneOffset();
return useMemo<IActionMenuItem[][]>(() => {
return fields.map((f, index) => {
@@ -119,7 +118,7 @@ export const useMenuActions = (channel: 'dimensions' | 'measures'): IActionMenuI
level,
`${t(`drill.levels.${level}`)} (${originField.name || originField.fid})`,
format,
- f.offset ?? defaultOffset
+ f.offset
)
);
},
@@ -147,7 +146,7 @@ export const useMenuActions = (channel: 'dimensions' | 'measures'): IActionMenuI
level,
`${t(`drill.levels.${level}`)} [${originField.name || originField.fid}]`,
format,
- f.offset ?? defaultOffset
+ f.offset
)
);
},
diff --git a/packages/graphic-walker/src/fields/filterField/filterEditDialog.tsx b/packages/graphic-walker/src/fields/filterField/filterEditDialog.tsx
index 9114c881..d7e624c5 100644
--- a/packages/graphic-walker/src/fields/filterField/filterEditDialog.tsx
+++ b/packages/graphic-walker/src/fields/filterField/filterEditDialog.tsx
@@ -21,20 +21,20 @@ const aggregationList = GLOBAL_CONFIG.AGGREGATOR_LIST.map(
})
).concat([{ label: '-', value: '' }]);
-const QuantitativeRuleForm: React.FC<RuleFormProps> = ({ rawFields, field, onChange }) => {
- return <Tabs field={field} onChange={onChange} tabs={['range', 'one of']} rawFields={rawFields} />;
+const QuantitativeRuleForm: React.FC<RuleFormProps> = ({ rawFields, field, onChange, displayOffset }) => {
+ return <Tabs field={field} onChange={onChange} tabs={['range', 'one of']} rawFields={rawFields} displayOffset={displayOffset} />;
};
-const NominalRuleForm: React.FC<RuleFormProps> = ({ rawFields, field, onChange }) => {
- return <Tabs field={field} onChange={onChange} tabs={['one of']} rawFields={rawFields} />;
+const NominalRuleForm: React.FC<RuleFormProps> = ({ rawFields, field, onChange, displayOffset }) => {
+ return <Tabs field={field} onChange={onChange} tabs={['one of']} rawFields={rawFields} displayOffset={displayOffset} />;
};
-const OrdinalRuleForm: React.FC<RuleFormProps> = ({ rawFields, field, onChange }) => {
- return <Tabs field={field} onChange={onChange} tabs={['range', 'one of']} rawFields={rawFields} />;
+const OrdinalRuleForm: React.FC<RuleFormProps> = ({ rawFields, field, onChange, displayOffset }) => {
+ return <Tabs field={field} onChange={onChange} tabs={['range', 'one of']} rawFields={rawFields} displayOffset={displayOffset} />;
};
-const TemporalRuleForm: React.FC<RuleFormProps> = ({ rawFields, field, onChange }) => {
- return <Tabs field={field} onChange={onChange} tabs={['temporal range', 'one of']} rawFields={rawFields} />;
+const TemporalRuleForm: React.FC<RuleFormProps> = ({ rawFields, field, onChange, displayOffset }) => {
+ return <Tabs field={field} onChange={onChange} tabs={['temporal range', 'one of']} rawFields={rawFields} displayOffset={displayOffset} />;
};
const EmptyForm: React.FC<RuleFormProps> = () => <React.Fragment />;
@@ -44,6 +44,7 @@ export const PureFilterEditDialog = (props: {
options: { label: string; value: string }[];
meta: IMutField[];
editingFilterIdx: number | null;
+ displayOffset?: number;
onSelectFilter: (field: string) => void;
onWriteFilter: (index: number, rule: IFilterRule | null) => void;
onSelectAgg?: (index: number, aggName: IAggregator | null) => void;
@@ -115,7 +116,7 @@ export const PureFilterEditDialog = (props: {
</div>
)}
</div>
- <Form rawFields={meta} key={getFilterMeaAggKey(uncontrolledField)} field={uncontrolledField} onChange={handleChange} />
+ <Form rawFields={meta} key={getFilterMeaAggKey(uncontrolledField)} field={uncontrolledField} onChange={handleChange} displayOffset={props.displayOffset} />
<div className="mt-4">
<PrimaryButton onClick={handleSubmit} text={t('btn.confirm')} />
<DefaultButton className="ml-2" onClick={onClose} text={t('btn.cancel')} />
@@ -127,7 +128,8 @@ export const PureFilterEditDialog = (props: {
const FilterEditDialog: React.FC = observer(() => {
const vizStore = useVizStore();
- const { editingFilterIdx, viewFilters, dimensions, measures, meta, allFields, viewDimensions } = vizStore;
+ const { editingFilterIdx, viewFilters, dimensions, measures, meta, allFields, viewDimensions, config } = vizStore;
+ const { timezoneDisplayOffset } = config;
const computation = useCompututaion();
@@ -142,7 +144,17 @@ const FilterEditDialog: React.FC = observer(() => {
const transformedComputation = useMemo((): IComputationFunction => {
if (originalField && viewDimensions.length > 0) {
- const preWorkflow = toWorkflow([], allFields, viewDimensions, [{ ...originalField, aggName: filterAggName }], true, 'none').map((x) => {
+ const preWorkflow = toWorkflow(
+ [],
+ allFields,
+ viewDimensions,
+ [{ ...originalField, aggName: filterAggName }],
+ true,
+ 'none',
+ [],
+ undefined,
+ timezoneDisplayOffset
+ ).map((x) => {
if (x.type === 'view') {
return {
...x,
@@ -209,6 +221,7 @@ const FilterEditDialog: React.FC = observer(() => {
<PureFilterEditDialog
options={allFieldOptions}
editingFilterIdx={editingFilterIdx}
+ displayOffset={timezoneDisplayOffset}
meta={meta}
onClose={handelClose}
onSelectFilter={handleSelectFilterField}
diff --git a/packages/graphic-walker/src/fields/filterField/filterPill.tsx b/packages/graphic-walker/src/fields/filterField/filterPill.tsx
index c7788b3e..670ed2d2 100644
--- a/packages/graphic-walker/src/fields/filterField/filterPill.tsx
+++ b/packages/graphic-walker/src/fields/filterField/filterPill.tsx
@@ -6,6 +6,8 @@ import styled from 'styled-components';
import { PencilSquareIcon } from '@heroicons/react/24/solid';
import { useVizStore } from '../../store';
import { refMapper } from '../fieldsContext';
+import { formatDate } from '../../utils';
+import { parsedOffsetDate } from '../../lib/op/offset';
interface FilterPillProps {
provided: DraggableProvided;
@@ -58,7 +60,9 @@ const Pill = styled.div`
const FilterPill: React.FC<FilterPillProps> = observer((props) => {
const { provided, fIndex } = props;
const vizStore = useVizStore();
- const { viewFilters } = vizStore;
+ const { viewFilters, config } = vizStore;
+
+ const { timezoneDisplayOffset } = config;
const field = viewFilters[fIndex];
@@ -77,15 +81,19 @@ const FilterPill: React.FC<FilterPillProps> = observer((props) => {
>
{field.rule ? (
<span className="flex-1">
- {field.rule.type === 'one of'
- ? `oneOf: [${[...field.rule.value].map((d) => JSON.stringify(d)).join(', ')}]`
- : field.rule.type === 'range'
- ? `range: [${field.rule.value[0]}, ${field.rule.value[1]}]`
- : field.rule.type === 'temporal range'
- ? `range: [${new Date(field.rule.value[0])}, ${new Date(field.rule.value[1])}]`
- : field.rule.type === 'not in'
- ? `notIn: [${[...field.rule.value].map((d) => JSON.stringify(d)).join(', ')}]`
- : null}
+ {field.rule.type === 'one of' && <>oneOf: [{[...field.rule.value].map((d) => JSON.stringify(d)).join(', ')}]</>}
+ {field.rule.type === 'range' && (
+ <>
+ range: [{field.rule.value[0]}, {field.rule.value[1]}]
+ </>
+ )}
+ {field.rule.type === 'not in' && <>notIn: [{[...field.rule.value].map((d) => JSON.stringify(d)).join(', ')}]</>}
+ {field.rule.type === 'temporal range' && (
+ <>
+ range: [{formatDate(parsedOffsetDate(timezoneDisplayOffset, field.rule.offset)(field.rule.value[0]))},{' '}
+ {formatDate(parsedOffsetDate(timezoneDisplayOffset, field.rule.offset)(field.rule.value[1]))}]
+ </>
+ )}
</span>
) : (
<span className="text-gray-600 flex-1">{t('empty_rule')}</span>
diff --git a/packages/graphic-walker/src/fields/filterField/tabs.tsx b/packages/graphic-walker/src/fields/filterField/tabs.tsx
index 6f9ac2bb..cfd951f4 100644
--- a/packages/graphic-walker/src/fields/filterField/tabs.tsx
+++ b/packages/graphic-walker/src/fields/filterField/tabs.tsx
@@ -6,16 +6,17 @@ import { ChevronDownIcon, ChevronUpIcon } from '@heroicons/react/24/outline';
import type { IFilterField, IFilterRule, IFieldStats, IMutField, IComputationFunction } from '../../interfaces';
import { useCompututaion } from '../../store';
import LoadingLayer from '../../components/loadingLayer';
-import { fieldStat, getTemporalRange } from '../../computation';
+import { fieldStat, getTemporalRange, withComputedField } from '../../computation';
import Slider from './slider';
import { getFilterMeaAggKey, formatDate } from '../../utils';
import { useVirtualizer } from '@tanstack/react-virtual';
-import { newOffsetDate } from '../../lib/op/offset';
+import { newOffsetDate, parsedOffsetDate } from '../../lib/op/offset';
export type RuleFormProps = {
rawFields: IMutField[];
field: IFilterField;
onChange: (rule: IFilterRule) => void;
+ displayOffset?: number;
};
const Container = styled.div`
@@ -143,12 +144,12 @@ const StatusCheckbox: React.FC<{ currentNum: number; totalNum: number; onChange:
const useFieldStats = (
field: IFilterField,
- attributes: { values: boolean; range: boolean; valuesMeta?: boolean; selectedCount?: Set<string | number> },
+ attributes: { values: boolean; range: boolean; valuesMeta?: boolean; selectedCount?: Set<string | number>; displayOffset: number | undefined },
sortBy: 'value' | 'value_dsc' | 'count' | 'count_dsc' | 'none',
computation: IComputationFunction,
allFields: IMutField[]
): IFieldStats | null => {
- const { values, range, valuesMeta, selectedCount } = attributes;
+ const { values, range, valuesMeta, selectedCount, displayOffset } = attributes;
const { fid } = field;
const [loading, setLoading] = React.useState(true);
const [stats, setStats] = React.useState<IFieldStats | null>(null);
@@ -158,7 +159,7 @@ const useFieldStats = (
React.useEffect(() => {
setLoading(true);
let isCancelled = false;
- fieldStat(computation, field, { values, range, valuesMeta, sortBy, selectedCount }, allFields)
+ fieldStat(computation, field, { values, range, valuesMeta, sortBy, selectedCount, timezoneDisplayOffset: displayOffset }, allFields)
.then((stats) => {
if (isCancelled) {
return;
@@ -212,14 +213,21 @@ const useVisualCount = (
sortBy: 'value' | 'value_dsc' | 'count' | 'count_dsc' | 'none',
computation: IComputationFunction,
onChange: (rule: IFilterRule) => void,
- allFields: IMutField[]
+ allFields: IMutField[],
+ displayOffset: number | undefined
) => {
// fetch metaData of filter field, only fetch once per fid.
const initRuleValue = useMemo(
() => (field.rule?.type === 'not in' || field.rule?.type === 'one of' ? field.rule.value : new Set<string | number>()),
[field.fid, computation]
);
- const metaData = useFieldStats(field, { values: false, range: false, selectedCount: initRuleValue, valuesMeta: true }, 'none', computation, allFields);
+ const metaData = useFieldStats(
+ field,
+ { values: false, range: false, selectedCount: initRuleValue, valuesMeta: true, displayOffset },
+ 'none',
+ computation,
+ allFields
+ );
// sum of count of rule.
const [selectedValueSum, setSelectedValueSum] = useState(0);
useEffect(() => {
@@ -257,6 +265,7 @@ const useVisualCount = (
sortBy,
valuesLimit: PAGE_SIZE,
valuesOffset: PAGE_SIZE * page,
+ timezoneDisplayOffset: displayOffset,
},
allFields
);
@@ -354,7 +363,7 @@ const Effecter = (props: { effect: () => void; effectId: any }) => {
return null;
};
-export const FilterOneOfRule: React.FC<RuleFormProps & { active: boolean }> = ({ active, field, onChange, rawFields }) => {
+export const FilterOneOfRule: React.FC<RuleFormProps & { active: boolean }> = ({ active, field, onChange, rawFields, displayOffset }) => {
interface SortConfig {
key: 'value' | 'count';
ascending: boolean;
@@ -378,7 +387,7 @@ export const FilterOneOfRule: React.FC<RuleFormProps & { active: boolean }> = ({
}, [active, onChange, field]);
const { currentCount, currentSum, data, distinctTotal, handleSelect, handleToggleFullOrEmptySet, handleToggleReverseSet, loadData, loading } =
- useVisualCount(field, `${sortConfig.key}${sortConfig.ascending ? '' : '_dsc'}`, computation, onChange, rawFields);
+ useVisualCount(field, `${sortConfig.key}${sortConfig.ascending ? '' : '_dsc'}`, computation, onChange, rawFields, displayOffset);
const parentRef = React.useRef<HTMLDivElement>(null);
@@ -484,7 +493,7 @@ export const FilterOneOfRule: React.FC<RuleFormProps & { active: boolean }> = ({
const id = `rule_checkbox_${idx}`;
const checked =
(field.rule?.type === 'one of' && field.rule.value.has(value)) || (field.rule?.type === 'not in' && !field.rule.value.has(value));
- const displayValue = field.semanticType === 'temporal' ? formatDate(newOffsetDate(field.offset)(value)) : `${value}`;
+ const displayValue = field.semanticType === 'temporal' ? formatDate(parsedOffsetDate(displayOffset, field.offset)(value)) : `${value}`;
return (
<TableRow
key={idx}
@@ -531,20 +540,22 @@ export const FilterOneOfRule: React.FC<RuleFormProps & { active: boolean }> = ({
interface CalendarInputProps {
min: number;
max: number;
+ displayOffset?: number;
value: number;
onChange: (value: number) => void;
}
export const CalendarInput: React.FC<CalendarInputProps> = (props) => {
- const { min, max, value, onChange } = props;
+ const { min, max, value, onChange, displayOffset } = props;
const dateStringFormatter = (timestamp: number) => {
- const date = new Date(timestamp);
+ const date = newOffsetDate(displayOffset)(timestamp);
if (Number.isNaN(date.getTime())) return '';
return formatDate(date);
};
const handleSubmitDate = (value: string) => {
- if (new Date(value).getTime() <= max && new Date(value).getTime() >= min) {
- onChange(new Date(value).getTime());
+ const timestamp = newOffsetDate(displayOffset)(value).getTime();
+ if (timestamp <= max && timestamp >= min) {
+ onChange(timestamp);
}
};
return (
@@ -559,7 +570,7 @@ export const CalendarInput: React.FC<CalendarInputProps> = (props) => {
);
};
-export const FilterTemporalRangeRule: React.FC<RuleFormProps & { active: boolean }> = ({ active, field, onChange }) => {
+export const FilterTemporalRangeRule: React.FC<RuleFormProps & { active: boolean }> = ({ active, field, rawFields, onChange, displayOffset }) => {
const { t } = useTranslation('translation');
const computationFunction = useCompututaion();
@@ -567,7 +578,9 @@ export const FilterTemporalRangeRule: React.FC<RuleFormProps & { active: boolean
const [res, setRes] = useState<[number, number, string, boolean]>(() => [0, 0, '', false]);
React.useEffect(() => {
- getTemporalRange(computationFunction, field.fid, field.offset).then(([min, max, format]) => setRes([min, max, format, true]));
+ withComputedField(field, rawFields, computationFunction, { timezoneDisplayOffset: displayOffset })((service) =>
+ getTemporalRange(service, field.fid, field.offset)
+ ).then(([min, max, format]) => setRes([min, max, format, true]));
}, [field.fid]);
const [min, max, format, loaded] = res;
@@ -613,6 +626,7 @@ export const FilterTemporalRangeRule: React.FC<RuleFormProps & { active: boolean
<div className="calendar-input">
<div className="my-1">{t('filters.range.start_value')}</div>
<CalendarInput
+ displayOffset={displayOffset}
min={min}
max={field.rule.value[1]}
value={field.rule.value[0]}
@@ -622,6 +636,7 @@ export const FilterTemporalRangeRule: React.FC<RuleFormProps & { active: boolean
<div className="calendar-input">
<div className="my-1">{t('filters.range.end_value')}</div>
<CalendarInput
+ displayOffset={displayOffset}
min={field.rule.value[0]}
max={max}
value={field.rule.value[1]}
@@ -633,11 +648,11 @@ export const FilterTemporalRangeRule: React.FC<RuleFormProps & { active: boolean
) : null;
};
-export const FilterRangeRule: React.FC<RuleFormProps & { active: boolean }> = ({ active, field, onChange, rawFields }) => {
+export const FilterRangeRule: React.FC<RuleFormProps & { active: boolean }> = ({ active, field, onChange, rawFields, displayOffset }) => {
const { t } = useTranslation('translation', { keyPrefix: 'constant.filter_type' });
const computation = useCompututaion();
- const stats = useFieldStats(field, { values: false, range: true, valuesMeta: false }, 'none', computation, rawFields);
+ const stats = useFieldStats(field, { values: false, range: true, valuesMeta: false, displayOffset }, 'none', computation, rawFields);
const range = stats?.range;
React.useEffect(() => {
@@ -706,7 +721,7 @@ const getType = (type?: 'range' | 'temporal range' | 'one of' | 'not in') => {
return type;
};
-const Tabs: React.FC<TabsProps> = ({ rawFields, field, onChange, tabs }) => {
+const Tabs: React.FC<TabsProps> = ({ rawFields, field, onChange, tabs, displayOffset }) => {
const { t } = useTranslation('translation', { keyPrefix: 'constant.filter_type' });
const [which, setWhich] = React.useState(getType(field.rule?.type) ?? tabs[0]!);
@@ -753,7 +768,7 @@ const Tabs: React.FC<TabsProps> = ({ rawFields, field, onChange, tabs }) => {
hidden={which !== tab}
tabIndex={0}
>
- <Component field={field} onChange={onChange} active={which === tab} rawFields={rawFields} />
+ <Component displayOffset={displayOffset} field={field} onChange={onChange} active={which === tab} rawFields={rawFields} />
</TabItem>
);
})}
diff --git a/packages/graphic-walker/src/interfaces.ts b/packages/graphic-walker/src/interfaces.ts
index 131befcc..ff6a2152 100644
--- a/packages/graphic-walker/src/interfaces.ts
+++ b/packages/graphic-walker/src/interfaces.ts
@@ -169,6 +169,10 @@ export type IExpParameter =
| {
type: 'newmap';
value: IPaintMapV2;
+ }
+ | {
+ type: 'displayOffset';
+ value: number;
};
export interface IExpression {
@@ -427,6 +431,7 @@ export interface IVisualConfigNew {
coordSystem?: ICoordMode;
limit: number;
folds?: string[];
+ timezoneDisplayOffset?: number;
}
export interface IGeoUrl {
@@ -645,7 +650,7 @@ export type IResponse<T> =
export interface IAggQuery {
op: 'aggregate';
groupBy: string[];
- measures: { field: string; agg: IAggregator; asFieldKey: string; format?: string }[];
+ measures: { field: string; agg: IAggregator; asFieldKey: string; format?: string; offset?: number }[];
}
export interface IFoldQuery {
@@ -914,7 +919,7 @@ export interface IComputationContextProps {
computationTimeout?: number;
}
-export type IComputationProps = XOR<IRemoteComputationProps,ILocalComputationProps>;
+export type IComputationProps = XOR<IRemoteComputationProps, ILocalComputationProps>;
export type IGWProps = IAppI18nProps &
IVizProps &
@@ -931,6 +936,7 @@ export interface ISpecProps {
export interface ITableSpecProps {
pageSize?: number;
+ displayOffset?: number;
}
export interface IVizAppProps extends IAppI18nProps, IVizProps, IThemeProps, IErrorHandlerProps, IVizStoreProps, ISpecProps {}
diff --git a/packages/graphic-walker/src/lib/inferMeta.ts b/packages/graphic-walker/src/lib/inferMeta.ts
index 3c660677..aeaf4391 100644
--- a/packages/graphic-walker/src/lib/inferMeta.ts
+++ b/packages/graphic-walker/src/lib/inferMeta.ts
@@ -12,22 +12,13 @@ const COMMON_TIME_FORMAT: RegExp[] = [
/^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])T\d{2}:\d{2}:\d{2}.\d{3}Z$/, // YYYY-MM-DDTHH:MM:SS.gggZ (ISO-8601)
];
-const TIME_FORMAT = [
- '%Y-%m-%d',
- '%m/%d/%Y',
- '%d/%m/%Y',
- '%Y/%m/%d',
- '%Y.%m.%d',
- '%Y-%m-%d %H:%M:%S',
- '%Y-%m-%dT%H:%M:%S',
- '%Y-%m-%dT%H:%M:%S.%gZ'
-]
+const TIME_FORMAT = ['%Y-%m-%d', '%m/%d/%Y', '%d/%m/%Y', '%Y/%m/%d', '%Y.%m.%d', '%Y-%m-%d %H:%M:%S', '%Y-%m-%dT%H:%M:%S', '%Y-%m-%dT%H:%M:%S.%gZ'];
export function getTimeFormat(data: string | number) {
if (typeof data === 'number') return 'timestamp';
- const i = COMMON_TIME_FORMAT.findIndex(x => x.test(data));
+ const i = COMMON_TIME_FORMAT.findIndex((x) => x.test(data));
if (i >= 0) return TIME_FORMAT[i];
- return ''
+ return '';
}
/**
@@ -100,6 +91,7 @@ export function inferMeta(props: { dataSource: IRow[]; fields: IUncertainMutFiel
semanticType,
basename: field.basename || field.name || field.fid,
path: field.path,
+ offset: semanticType === 'temporal' ? new Date().getTimezoneOffset() : undefined,
});
}
return finalFieldMetas;
diff --git a/packages/graphic-walker/src/lib/insights/explainBySelection.ts b/packages/graphic-walker/src/lib/insights/explainBySelection.ts
index 893ceaea..93fd69ff 100644
--- a/packages/graphic-walker/src/lib/insights/explainBySelection.ts
+++ b/packages/graphic-walker/src/lib/insights/explainBySelection.ts
@@ -3,7 +3,7 @@ import { filterByPredicates, getMeaAggKey } from '../../utils';
import { compareDistribution, compareDistributionKL, compareDistributionJS, normalizeWithParent } from '../../utils/normalization';
import { aggregate } from '../op/aggregate';
import { bin } from '../op/bin';
-import { VizSpecStore } from "../../store/visualSpecStore";
+import { VizSpecStore } from '../../store/visualSpecStore';
import { complementaryFields, groupByAnalyticTypes } from './utils';
import { toWorkflow } from '../../utils/workflow';
import { dataQuery } from '../../computation/index';
@@ -11,70 +11,64 @@ import { dataQuery } from '../../computation/index';
const QUANT_BIN_NUM = 10;
export async function explainBySelection(props: {
- predicates: IPredicate[],
- viewFilters: VizSpecStore['viewFilters'],
- allFields: IViewField[],
- viewMeasures: IViewField[],
- viewDimensions: IViewField[],
- computationFunction: IComputationFunction
+ predicates: IPredicate[];
+ viewFilters: VizSpecStore['viewFilters'];
+ allFields: IViewField[];
+ viewMeasures: IViewField[];
+ viewDimensions: IViewField[];
+ computationFunction: IComputationFunction;
+ timezoneDisplayOffset: number | undefined;
}) {
- const { allFields, viewFilters, viewMeasures, viewDimensions, predicates, computationFunction } = props;
+ const { allFields, viewFilters, viewMeasures, viewDimensions, predicates, computationFunction, timezoneDisplayOffset } = props;
const complementaryDimensions = complementaryFields({
all: allFields.filter((f) => f.analyticType === 'dimension'),
selection: viewDimensions,
});
- const outlierList: {
- score: number;
- measureField: IField;
- targetField: IField;
- normalizedData: IRow[];
+ const outlierList: {
+ score: number;
+ measureField: IField;
+ targetField: IField;
+ normalizedData: IRow[];
normalizedParentData: IRow[];
}[] = [];
for (let extendDim of complementaryDimensions) {
let extendDimFid = extendDim.fid;
let extraPreWorkflow: IViewWorkflowStep[] = [];
- if (extendDim.semanticType === "quantitative") {
+ if (extendDim.semanticType === 'quantitative') {
extraPreWorkflow.push({
- type: "view",
+ type: 'view',
query: [
{
- op: "bin",
+ op: 'bin',
binBy: extendDim.fid,
binSize: QUANT_BIN_NUM,
- newBinCol: extendDimFid
- }
- ]
- })
+ newBinCol: extendDimFid,
+ },
+ ],
+ });
}
for (let mea of viewMeasures) {
- const overallWorkflow = toWorkflow(viewFilters, allFields, [extendDim], [mea], true, 'none');
- const fullOverallWorkflow = extraPreWorkflow ? [...extraPreWorkflow, ...overallWorkflow] : overallWorkflow
- const overallData = await dataQuery(computationFunction, fullOverallWorkflow)
- const viewWorkflow = toWorkflow(viewFilters, allFields, [...viewDimensions, extendDim], [mea], true, 'none');
- const fullViewWorkflow = extraPreWorkflow ? [...extraPreWorkflow, ...viewWorkflow] : viewWorkflow
+ const overallWorkflow = toWorkflow(viewFilters, allFields, [extendDim], [mea], true, 'none', [], undefined, timezoneDisplayOffset);
+ const fullOverallWorkflow = extraPreWorkflow ? [...extraPreWorkflow, ...overallWorkflow] : overallWorkflow;
+ const overallData = await dataQuery(computationFunction, fullOverallWorkflow);
+ const viewWorkflow = toWorkflow(viewFilters, allFields, [...viewDimensions, extendDim], [mea], true, 'none', [], undefined, timezoneDisplayOffset);
+ const fullViewWorkflow = extraPreWorkflow ? [...extraPreWorkflow, ...viewWorkflow] : viewWorkflow;
const viewData = await dataQuery(computationFunction, fullViewWorkflow);
const subData = filterByPredicates(viewData, predicates);
- let outlierNormalization = normalizeWithParent(
- subData,
- overallData,
- [getMeaAggKey(mea.fid, (mea.aggName ?? 'sum'))],
- false
- );
+ let outlierNormalization = normalizeWithParent(subData, overallData, [getMeaAggKey(mea.fid, mea.aggName ?? 'sum')], false);
let outlierScore = compareDistributionJS(
outlierNormalization.normalizedData,
outlierNormalization.normalizedParentData,
[extendDim.fid],
- getMeaAggKey(mea.fid, (mea.aggName ?? 'sum'))
+ getMeaAggKey(mea.fid, mea.aggName ?? 'sum')
);
- outlierList.push(
- {
- measureField: mea,
- targetField: extendDim,
- score: outlierScore,
- normalizedData: subData,
- normalizedParentData: overallData
- }
- )
+ outlierList.push({
+ measureField: mea,
+ targetField: extendDim,
+ score: outlierScore,
+ normalizedData: subData,
+ normalizedParentData: overallData,
+ });
}
}
return outlierList.sort((a, b) => b.score - a.score);
diff --git a/packages/graphic-walker/src/lib/op/aggregate.ts b/packages/graphic-walker/src/lib/op/aggregate.ts
index abfbd142..749b3795 100644
--- a/packages/graphic-walker/src/lib/op/aggregate.ts
+++ b/packages/graphic-walker/src/lib/op/aggregate.ts
@@ -3,6 +3,7 @@ import { getMeaAggKey } from '../../utils';
import { IAggQuery } from '../../interfaces';
import { sum, mean, median, stdev, variance, max, min, count, distinctCount } from './stat';
import { expr } from '../sql';
+import { newOffsetDate } from './offset';
const aggregatorMap = {
sum,
@@ -50,11 +51,12 @@ export function aggregate(data: IRow[], query: IAggQuery): IRow[] {
}
aggRow[aggMeaKey] = result;
} else {
+ const newDate = newOffsetDate(mea.offset);
const values: number[] = subGroup
.map((r) => r[mea.field])
.map((x) => {
if (mea.format) {
- return new Date(x).getTime();
+ return newDate(x).getTime();
}
return x;
});
diff --git a/packages/graphic-walker/src/lib/op/dateTimeDrill.ts b/packages/graphic-walker/src/lib/op/dateTimeDrill.ts
index d18331ff..0c630ae3 100644
--- a/packages/graphic-walker/src/lib/op/dateTimeDrill.ts
+++ b/packages/graphic-walker/src/lib/op/dateTimeDrill.ts
@@ -8,18 +8,21 @@ const formatDate = (date: Date) => date.getTime();
function dateTimeDrill(resKey: string, params: IExpParameter[], data: IDataFrame): IDataFrame {
const fieldKey = params.find((p) => p.type === 'field')?.value;
const drillLevel = params.find((p) => p.type === 'value')?.value as (typeof DATE_TIME_DRILL_LEVELS)[number] | undefined;
- const offset = params.find((p) => p.type === 'offset')?.value ?? new Date().getTimezoneOffset();
+ const offset = params.find((p) => p.type === 'offset')?.value;
+ const displayOffset = params.find((p) => p.type === 'displayOffset')?.value;
if (!fieldKey || !drillLevel) {
return data;
}
const fieldValues = data[fieldKey];
- const newDate = newOffsetDate(offset);
+ const prepareDate = newOffsetDate(offset);
+ const toOffsetDate = newOffsetDate(displayOffset);
+ const newDate = ((...x: []) => toOffsetDate(prepareDate(...x))) as typeof prepareDate;
switch (drillLevel) {
case 'year': {
const newValues = fieldValues.map((v) => {
const date = newDate(v);
const Y = date.getFullYear();
- return formatDate(newDate(Y, 0, 1));
+ return formatDate(toOffsetDate(Y, 0, 1));
});
return {
...data,
@@ -31,7 +34,7 @@ function dateTimeDrill(resKey: string, params: IExpParameter[], data: IDataFrame
const date = newDate(v);
const Y = date.getFullYear();
const Q = Math.floor(date.getMonth() / 3);
- return formatDate(newDate(Y, Q * 3, 1));
+ return formatDate(toOffsetDate(Y, Q * 3, 1));
});
return {
...data,
@@ -43,7 +46,7 @@ function dateTimeDrill(resKey: string, params: IExpParameter[], data: IDataFrame
const date = newDate(v);
const Y = date.getFullYear();
const M = date.getMonth();
- return formatDate(newDate(Y, M, 1));
+ return formatDate(toOffsetDate(Y, M, 1));
});
return {
...data,
@@ -57,7 +60,7 @@ function dateTimeDrill(resKey: string, params: IExpParameter[], data: IDataFrame
const Y = date.getFullYear();
const M = date.getMonth();
const D = date.getDate();
- return formatDate(newDate(Y, M, D));
+ return formatDate(toOffsetDate(Y, M, D));
});
return {
...data,
@@ -70,7 +73,7 @@ function dateTimeDrill(resKey: string, params: IExpParameter[], data: IDataFrame
const Y = date.getFullYear();
const M = date.getMonth();
const D = date.getDate();
- return formatDate(newDate(Y, M, D));
+ return formatDate(toOffsetDate(Y, M, D));
});
return {
...data,
@@ -84,7 +87,7 @@ function dateTimeDrill(resKey: string, params: IExpParameter[], data: IDataFrame
const M = date.getMonth();
const D = date.getDate();
const H = date.getHours();
- return formatDate(newDate(Y, M, D, H));
+ return formatDate(toOffsetDate(Y, M, D, H));
});
return {
...data,
@@ -99,7 +102,7 @@ function dateTimeDrill(resKey: string, params: IExpParameter[], data: IDataFrame
const D = date.getDate();
const H = date.getHours();
const m = date.getMinutes();
- return formatDate(newDate(Y, M, D, H, m));
+ return formatDate(toOffsetDate(Y, M, D, H, m));
});
return {
...data,
@@ -115,7 +118,7 @@ function dateTimeDrill(resKey: string, params: IExpParameter[], data: IDataFrame
const H = date.getHours();
const m = date.getMinutes();
const s = date.getSeconds();
- return formatDate(newDate(Y, M, D, H, m, s));
+ return formatDate(toOffsetDate(Y, M, D, H, m, s));
});
return {
...data,
diff --git a/packages/graphic-walker/src/lib/op/dateTimeFeature.ts b/packages/graphic-walker/src/lib/op/dateTimeFeature.ts
index 94a05d0f..0f7110a1 100644
--- a/packages/graphic-walker/src/lib/op/dateTimeFeature.ts
+++ b/packages/graphic-walker/src/lib/op/dateTimeFeature.ts
@@ -6,12 +6,15 @@ import { newOffsetDate } from './offset';
function dateTimeDrill(resKey: string, params: IExpParameter[], data: IDataFrame): IDataFrame {
const fieldKey = params.find((p) => p.type === 'field')?.value;
const drillLevel = params.find((p) => p.type === 'value')?.value as (typeof DATE_TIME_FEATURE_LEVELS)[number] | undefined;
- const offset = params.find((p) => p.type === 'offset')?.value ?? new Date().getTimezoneOffset();
+ const offset = params.find((p) => p.type === 'offset')?.value;
+ const displayOffset = params.find((p) => p.type === 'displayOffset')?.value;
if (!fieldKey || !drillLevel) {
return data;
}
const fieldValues = data[fieldKey];
- const newDate = newOffsetDate(offset);
+ const prepareDate = newOffsetDate(offset);
+ const toOffsetDate = newOffsetDate(displayOffset);
+ const newDate = ((...x: []) => toOffsetDate(prepareDate(...x))) as typeof prepareDate;
switch (drillLevel) {
case 'year': {
const newValues = fieldValues.map((v) => {
diff --git a/packages/graphic-walker/src/lib/op/offset.ts b/packages/graphic-walker/src/lib/op/offset.ts
index 39f3be4f..6e88f928 100644
--- a/packages/graphic-walker/src/lib/op/offset.ts
+++ b/packages/graphic-walker/src/lib/op/offset.ts
@@ -19,11 +19,13 @@ export function getOffsetDate(date: Date, offset: number): OffsetDate {
}) as OffsetDate;
}
-const unexceptedUTCParsedPattern = [
+export const unexceptedUTCParsedPattern = [
/^\d{4}-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])$/, // YYYY-MM-DD
/^\d{4}-(0[1-9]|1[0-2])$/, // YYYY-MM
- /^\d{4}$/,// YYYY
-]
+ /^\d{4}$/, // YYYY
+];
+
+export const unexceptedUTCParsedPatternFormats = ['%Y', '%Y-%m', '%Y-%m-%d'];
export function newOffsetDate(offset = new Date().getTimezoneOffset()) {
function creator(): OffsetDate;
@@ -42,7 +44,7 @@ export function newOffsetDate(offset = new Date().getTimezoneOffset()) {
return getOffsetDate(v, offset);
}
if (typeof v === 'string') {
- if (unexceptedUTCParsedPattern.find(regex => regex.test(v))) {
+ if (unexceptedUTCParsedPattern.find((regex) => regex.test(v))) {
const utcDate = new Date(v).getTime();
return getOffsetDate(new Date(utcDate + offset * 60000), offset);
}
@@ -60,3 +62,15 @@ export function newOffsetDate(offset = new Date().getTimezoneOffset()) {
}
return creator;
}
+
+export function parsedOffsetDate(displayOffset = new Date().getTimezoneOffset(), parseOffset = new Date().getTimezoneOffset()) {
+ const toOffset = newOffsetDate(displayOffset);
+ const parse = newOffsetDate(parseOffset);
+ function creator(): OffsetDate;
+ function creator(value: number | string | Date): OffsetDate;
+ function creator(year: number, monthIndex: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): OffsetDate;
+ function creator(...args: []): OffsetDate {
+ return toOffset(parse(...args));
+ }
+ return creator;
+}
diff --git a/packages/graphic-walker/src/lib/op/stat.ts b/packages/graphic-walker/src/lib/op/stat.ts
index efd8ac81..d8549d68 100644
--- a/packages/graphic-walker/src/lib/op/stat.ts
+++ b/packages/graphic-walker/src/lib/op/stat.ts
@@ -1,3 +1,5 @@
+import { isNotEmpty } from "../../utils";
+
export function mean(nums: number[]): number {
return nums.reduce((a, b) => a + b, 0) / nums.length;
}
@@ -46,7 +48,7 @@ export function count(nums: any[]): number {
}
export function countTruly(nums: any[]): number {
- return nums.filter(x => x !== undefined && x !== null).length;
+ return nums.filter(isNotEmpty).length;
}
export function distinctCount(datas: any[]) {
diff --git a/packages/graphic-walker/src/lib/vega.ts b/packages/graphic-walker/src/lib/vega.ts
index 0a95aa47..9c779b5b 100644
--- a/packages/graphic-walker/src/lib/vega.ts
+++ b/packages/graphic-walker/src/lib/vega.ts
@@ -26,6 +26,7 @@ export function toVegaSpec({
channelScales,
mediaTheme,
vegaConfig,
+ displayOffset,
}: {
rows: readonly IViewField[];
columns: readonly IViewField[];
@@ -48,6 +49,7 @@ export function toVegaSpec({
channelScales?: IChannelScales;
mediaTheme: 'dark' | 'light';
vegaConfig: VegaGlobalConfig;
+ displayOffset?: number;
}) {
const guard = defaultAggregated ? (x?: IViewField) => x ?? NULL_FIELD : (x?: IViewField) => (x ? (x.aggName === 'expr' ? NULL_FIELD : x) : NULL_FIELD);
const rows = rowsRaw.map(guard).filter((x) => x !== NULL_FIELD);
@@ -123,6 +125,8 @@ export function toVegaSpec({
defaultAggregated,
stack,
geomType,
+ displayOffset,
+ dataSource
});
const singleView = channelScales ? resolveScales(channelScales, v, dataSource, mediaTheme) : v;
@@ -130,6 +134,9 @@ export function toVegaSpec({
if ('encoding' in singleView) {
spec.encoding = singleView.encoding;
}
+ if ('transform' in singleView && singleView.transform.length > 0) {
+ spec.transform = singleView.transform;
+ }
spec.resolve ||= {};
// @ts-ignore
@@ -181,6 +188,8 @@ export function toVegaSpec({
stack,
geomType,
hideLegend: !hasLegend,
+ displayOffset,
+ dataSource,
});
const singleView = channelScales ? resolveScales(channelScales, v, dataSource, mediaTheme) : v;
let commonSpec = { ...spec };
diff --git a/packages/graphic-walker/src/locales/en-US.json b/packages/graphic-walker/src/locales/en-US.json
index ac563d61..f915bbcb 100644
--- a/packages/graphic-walker/src/locales/en-US.json
+++ b/packages/graphic-walker/src/locales/en-US.json
@@ -23,7 +23,8 @@
"formatGuidesDocs": "Format guides docs",
"readHere": "read here",
"svg": "Use SVG",
- "customTile": "Use a Custom Tile for map"
+ "customTile": "Use a Custom Tile for map",
+ "customOffset": "Use a Specific timezone"
},
"constant": {
"row_count": "Row count",
diff --git a/packages/graphic-walker/src/locales/ja-JP.json b/packages/graphic-walker/src/locales/ja-JP.json
index 4ce5fe9d..38396832 100644
--- a/packages/graphic-walker/src/locales/ja-JP.json
+++ b/packages/graphic-walker/src/locales/ja-JP.json
@@ -23,7 +23,8 @@
"formatGuidesDocs": "フォーマットガイド",
"readHere": "ここを読む",
"svg": "SVGを使う",
- "customTile": "地図タイルをカスタマイズ"
+ "customTile": "地図タイルをカスタマイズ",
+ "customOffset": "タイムゾーンをカスタマイズ"
},
"constant": {
"row_count": "行数",
diff --git a/packages/graphic-walker/src/locales/zh-CN.json b/packages/graphic-walker/src/locales/zh-CN.json
index f1f37058..ffac5e5e 100644
--- a/packages/graphic-walker/src/locales/zh-CN.json
+++ b/packages/graphic-walker/src/locales/zh-CN.json
@@ -23,7 +23,8 @@
"formatGuidesDocs": "格式指南",
"readHere": "阅读此处",
"svg": "使用SVG",
- "customTile": "使用自定义的地图区块"
+ "customTile": "使用自定义的地图区块",
+ "customOffset": "使用自定义的时区"
},
"constant": {
"row_count": "行数",
diff --git a/packages/graphic-walker/src/main.tsx b/packages/graphic-walker/src/main.tsx
index 097579f0..891242f8 100644
--- a/packages/graphic-walker/src/main.tsx
+++ b/packages/graphic-walker/src/main.tsx
@@ -14,5 +14,5 @@ embedGraphicWalker(document.getElementById('root') as HTMLElement, {
type: 'GeoJSON',
url: 'https://raw.githubusercontent.com/drei01/geojson-world-cities/f2a988af4bc15463df55586afbbffbd3068b7218/cities.geojson',
},
- ]
+ ],
});
diff --git a/packages/graphic-walker/src/models/visSpecHistory.ts b/packages/graphic-walker/src/models/visSpecHistory.ts
index b2c3ef8c..7e6fbe83 100644
--- a/packages/graphic-walker/src/models/visSpecHistory.ts
+++ b/packages/graphic-walker/src/models/visSpecHistory.ts
@@ -22,7 +22,7 @@ import {
IPaintMapV2,
} from '../interfaces';
import type { FeatureCollection } from 'geojson';
-import { createCountField, createVirtualFields } from '../utils';
+import { createCountField, createVirtualFields, isNotEmpty } from '../utils';
import { decodeFilterRule, encodeFilterRule } from '../utils/filter';
import { emptyEncodings, emptyVisualConfig, emptyVisualLayout } from '../utils/save';
import { AssertSameKey, KVTuple, insert, mutPath, remove, replace, uniqueId } from './utils';
@@ -247,7 +247,7 @@ const actions: {
} as const,
]
: []),
- ...(offset !== undefined
+ ...(isNotEmpty(offset)
? [
{
type: 'offset',
@@ -290,7 +290,7 @@ const actions: {
} as const,
]
: []),
- ...(offset !== undefined
+ ...(isNotEmpty(offset)
? [
{
type: 'offset',
@@ -577,6 +577,7 @@ export function newChart(fields: IMutField[], name: string, visId?: string): ICh
basename: f.basename || f.name || f.fid,
semanticType: f.semanticType,
analyticType: f.analyticType,
+ offset: f.offset
})
)
.concat(extraDimensions),
@@ -591,6 +592,7 @@ export function newChart(fields: IMutField[], name: string, visId?: string): ICh
analyticType: f.analyticType,
semanticType: f.semanticType,
aggName: 'sum',
+ offset: f.offset
})
)
.concat(extraMeasures),
diff --git a/packages/graphic-walker/src/renderer/hooks.ts b/packages/graphic-walker/src/renderer/hooks.ts
index 0e22c071..dac83374 100644
--- a/packages/graphic-walker/src/renderer/hooks.ts
+++ b/packages/graphic-walker/src/renderer/hooks.ts
@@ -16,6 +16,7 @@ interface UseRendererProps {
limit: number;
computationFunction: IComputationFunction;
folds?: string[];
+ timezoneDisplayOffset?: number;
}
interface UseRendererResult {
@@ -27,12 +28,12 @@ interface UseRendererResult {
}
export const useRenderer = (props: UseRendererProps): UseRendererResult => {
- const { allFields, viewDimensions, viewMeasures, filters, defaultAggregated, sort, limit, computationFunction, folds } = props;
+ const { allFields, viewDimensions, viewMeasures, filters, defaultAggregated, sort, limit, computationFunction, folds, timezoneDisplayOffset } = props;
const [computing, setComputing] = useState(false);
const taskIdRef = useRef(0);
const workflow = useMemo(() => {
- return toWorkflow(filters, allFields, viewDimensions, viewMeasures, defaultAggregated, sort, folds, limit > 0 ? limit : undefined);
+ return toWorkflow(filters, allFields, viewDimensions, viewMeasures, defaultAggregated, sort, folds, limit > 0 ? limit : undefined, timezoneDisplayOffset);
}, [filters, allFields, viewDimensions, viewMeasures, defaultAggregated, sort, folds, limit]);
const [viewData, setViewData] = useState<IRow[]>([]);
diff --git a/packages/graphic-walker/src/renderer/index.tsx b/packages/graphic-walker/src/renderer/index.tsx
index fdd993d9..c125b61f 100644
--- a/packages/graphic-walker/src/renderer/index.tsx
+++ b/packages/graphic-walker/src/renderer/index.tsx
@@ -66,6 +66,7 @@ const Renderer = forwardRef<IReactVegaHandler, RendererProps>(function (props, r
limit: limit,
folds: visualConfig.folds,
computationFunction,
+ timezoneDisplayOffset: visualConfig.timezoneDisplayOffset,
});
useEffect(() => {
diff --git a/packages/graphic-walker/src/renderer/pureRenderer.tsx b/packages/graphic-walker/src/renderer/pureRenderer.tsx
index ba7da0cf..f9ac15e7 100644
--- a/packages/graphic-walker/src/renderer/pureRenderer.tsx
+++ b/packages/graphic-walker/src/renderer/pureRenderer.tsx
@@ -110,6 +110,7 @@ const PureRenderer = forwardRef<IReactVegaHandler, IPureRendererProps & (LocalPr
folds: visualConfig.folds,
limit,
computationFunction: computation,
+ timezoneDisplayOffset: visualConfig['timezoneDisplayOffset'],
});
// Dependencies that should not trigger effect individually
const latestFromRef = useRef({ data });
diff --git a/packages/graphic-walker/src/renderer/specRenderer.tsx b/packages/graphic-walker/src/renderer/specRenderer.tsx
index 966602c5..66311a77 100644
--- a/packages/graphic-walker/src/renderer/specRenderer.tsx
+++ b/packages/graphic-walker/src/renderer/specRenderer.tsx
@@ -51,7 +51,7 @@ const SpecRenderer = forwardRef<IReactVegaHandler, SpecRendererProps>(function (
ref
) {
// const { draggableFieldState, visualConfig } = vizStore;
- const { geoms, defaultAggregated, coordSystem } = visualConfig;
+ const { geoms, defaultAggregated, coordSystem, timezoneDisplayOffset } = visualConfig;
const {
interactiveScale,
@@ -234,6 +234,7 @@ const SpecRenderer = forwardRef<IReactVegaHandler, SpecRendererProps>(function (
dark={dark}
scale={scale}
onReportSpec={onReportSpec}
+ displayOffset={timezoneDisplayOffset}
/>
)}
</Resizable>
diff --git a/packages/graphic-walker/src/store/commonStore.ts b/packages/graphic-walker/src/store/commonStore.ts
index e328fb15..9753a3cd 100644
--- a/packages/graphic-walker/src/store/commonStore.ts
+++ b/packages/graphic-walker/src/store/commonStore.ts
@@ -9,9 +9,11 @@ export class CommonStore {
public showDSPanel: boolean = false;
public provider: IDataSourceProvider;
private onCommitDS: (datasetId: string) => void;
- constructor(provider: IDataSourceProvider, onCommitDS: (datasetId: string) => void) {
+ public displayOffset: number | undefined;
+ constructor(provider: IDataSourceProvider, onCommitDS: (datasetId: string) => void, config: {displayOffset?: number}) {
this.provider = provider;
this.onCommitDS = onCommitDS;
+ this.displayOffset = config.displayOffset;
makeAutoObservable(this, {
tmpDataSource: observable.ref,
});
@@ -81,4 +83,8 @@ export class CommonStore {
this.initTempDS();
this.showDSPanel = true;
}
+
+ public setDisplayOffset(displayOffset?: number) {
+ this.displayOffset = displayOffset;
+ }
}
diff --git a/packages/graphic-walker/src/store/visualSpecStore.ts b/packages/graphic-walker/src/store/visualSpecStore.ts
index e7349106..ab2d2deb 100644
--- a/packages/graphic-walker/src/store/visualSpecStore.ts
+++ b/packages/graphic-walker/src/store/visualSpecStore.ts
@@ -225,7 +225,8 @@ export class VizSpecStore {
this.config.defaultAggregated,
this.sort,
this.config.folds,
- this.config.limit
+ this.config.limit,
+ this.config.timezoneDisplayOffset
);
}
@@ -479,7 +480,7 @@ export class VizSpecStore {
drillLevel: (typeof DATE_TIME_DRILL_LEVELS)[number],
name: string,
format: string,
- offset: number
+ offset: number | undefined
) {
this.visList[this.visIndex] = performers.createDateDrillField(
this.visList[this.visIndex],
@@ -489,7 +490,7 @@ export class VizSpecStore {
uniqueId(),
name,
format,
- offset
+ offset ?? new Date().getTimezoneOffset()
);
}
@@ -499,7 +500,7 @@ export class VizSpecStore {
drillLevel: (typeof DATE_TIME_FEATURE_LEVELS)[number],
name: string,
format: string,
- offset: number
+ offset: number | undefined
) {
this.visList[this.visIndex] = performers.createDateFeatureField(
this.visList[this.visIndex],
@@ -509,7 +510,7 @@ export class VizSpecStore {
uniqueId(),
name,
format,
- offset
+ offset ?? new Date().getTimezoneOffset()
);
}
diff --git a/packages/graphic-walker/src/utils/index.ts b/packages/graphic-walker/src/utils/index.ts
index 24f8dca5..39b97c26 100644
--- a/packages/graphic-walker/src/utils/index.ts
+++ b/packages/graphic-walker/src/utils/index.ts
@@ -356,3 +356,7 @@ export const formatDate = (date: Date) => {
const pad = (x: number) => `${x}`.padStart(2, '0');
return `${Y}-${pad(M)}-${pad(D)} ${pad(H)}:${pad(m)}:${pad(s)}`;
};
+
+export const isNotEmpty = <T>(x: T | undefined | null): x is T => {
+ return x !== undefined && x !== null;
+};
diff --git a/packages/graphic-walker/src/utils/workflow.ts b/packages/graphic-walker/src/utils/workflow.ts
index 5d248526..9f10a9cf 100644
--- a/packages/graphic-walker/src/utils/workflow.ts
+++ b/packages/graphic-walker/src/utils/workflow.ts
@@ -15,7 +15,7 @@ import type {
IPaintMapV2,
} from '../interfaces';
import { viewEncodingKeys, type VizSpecStore } from '../store/visualSpecStore';
-import { getFilterMeaAggKey, getMeaAggKey, getSort } from '.';
+import { getFilterMeaAggKey, getMeaAggKey, getSort, isNotEmpty } from '.';
import { MEA_KEY_ID, MEA_VAL_ID } from '../constants';
import { decodeVisSpec } from '../models/visSpecHistory';
import { replaceFid, walkFid } from '../lib/sql';
@@ -74,7 +74,8 @@ export const toWorkflow = (
defaultAggregated: VizSpecStore['config']['defaultAggregated'],
sort: 'none' | 'ascending' | 'descending',
folds = [] as string[],
- limit?: number
+ limit?: number,
+ timezoneDisplayOffset?: number
): IDataQueryWorkflowStep[] => {
const hasFold = viewDimensionsRaw.find((x) => x.fid === MEA_KEY_ID) && viewMeasuresRaw.find((x) => x.fid === MEA_VAL_ID);
const viewDimensions = viewDimensionsRaw.filter((x) => x.fid !== MEA_KEY_ID);
@@ -112,12 +113,13 @@ export const toWorkflow = (
},
};
} else if (rule.type === 'temporal range') {
- const range = [new Date(rule.value[0]).getTime(), new Date(rule.value[1]).getTime()] as const;
return {
fid,
rule: {
type: 'temporal range',
- value: range,
+ value: rule.value,
+ offset: rule.offset,
+ format: rule.format,
},
};
} else if (rule.type === 'not in') {
@@ -163,7 +165,7 @@ export const toWorkflow = (
.map((f) => {
return {
key: f.fid,
- expression: processExpression(f.expression!, allFields),
+ expression: processExpression(f.expression!, allFields, { timezoneDisplayOffset }),
};
}),
[...viewKeys]
@@ -195,7 +197,7 @@ export const toWorkflow = (
.map((f) => {
return {
key: f.fid,
- expression: processExpression(f.expression!, allFields),
+ expression: processExpression(f.expression!, allFields, { timezoneDisplayOffset }),
};
}),
[...viewKeys]
@@ -243,7 +245,7 @@ export const toWorkflow = (
query: [
{
op: 'raw',
- fields: [...new Set([...viewDimensions, ...viewMeasures])].filter(f => f.aggName !== 'expr').map((f) => f.fid),
+ fields: [...new Set([...viewDimensions, ...viewMeasures])].filter((f) => f.aggName !== 'expr').map((f) => f.fid),
},
],
};
@@ -343,13 +345,14 @@ export function chartToWorkflow(chart: IChartForExport): IDataQueryPayload {
c.config?.defaultAggregated ?? true,
getSort({ rows, columns }),
c.config?.folds ?? [],
- limit
+ limit,
+ c.config?.timezoneDisplayOffset
),
limit: limit > 0 ? limit : undefined,
};
}
-export const processExpression = (exp: IExpression, allFields: IMutField[]): IExpression => {
+export const processExpression = (exp: IExpression, allFields: IMutField[], config: { timezoneDisplayOffset?: number }): IExpression => {
if (exp?.op === 'expr') {
return {
...exp,
@@ -361,6 +364,18 @@ export const processExpression = (exp: IExpression, allFields: IMutField[]): IEx
],
};
}
+ if (isNotEmpty(config.timezoneDisplayOffset) && (exp.op === 'dateTimeDrill' || exp.op === 'dateTimeFeature')) {
+ return {
+ ...exp,
+ params: [
+ ...exp.params,
+ {
+ type: 'displayOffset',
+ value: config.timezoneDisplayOffset,
+ },
+ ],
+ };
+ }
if (exp.op === 'paint') {
return {
...exp,
diff --git a/packages/graphic-walker/src/vis/react-vega.tsx b/packages/graphic-walker/src/vis/react-vega.tsx
index 3fbff221..8be13ea7 100644
--- a/packages/graphic-walker/src/vis/react-vega.tsx
+++ b/packages/graphic-walker/src/vis/react-vega.tsx
@@ -79,6 +79,7 @@ interface ReactVegaProps {
size: IConfigScale;
};
onReportSpec?: (spec: string) => void;
+ displayOffset?: number
}
const click$ = new Subject<ScenegraphEvent>();
@@ -134,6 +135,7 @@ const ReactVega = forwardRef<IReactVegaHandler, ReactVegaProps>(function ReactVe
useSvg,
channelScales: channelScaleRaw,
scale,
+ displayOffset,
} = props;
const [viewPlaceholders, setViewPlaceholders] = useState<React.MutableRefObject<HTMLDivElement>[]>([]);
const mediaTheme = useCurrentMediaTheme(dark);
@@ -267,6 +269,7 @@ const ReactVega = forwardRef<IReactVegaHandler, ReactVegaProps>(function ReactVe
text,
theta,
vegaConfig,
+ displayOffset
}),
[
guardedCols,
@@ -289,6 +292,7 @@ const ReactVega = forwardRef<IReactVegaHandler, ReactVegaProps>(function ReactVe
size,
text,
theta,
+ displayOffset,
]
);
// Render
diff --git a/packages/graphic-walker/src/vis/spec/encode.ts b/packages/graphic-walker/src/vis/spec/encode.ts
index f9f11225..2c7fd0a3 100644
--- a/packages/graphic-walker/src/vis/spec/encode.ts
+++ b/packages/graphic-walker/src/vis/spec/encode.ts
@@ -1,5 +1,6 @@
import { DATE_TIME_DRILL_LEVELS } from '../../constants';
import { IPaintMap, IPaintMapV2, IViewField } from '../../interfaces';
+import { isNotEmpty } from '../../utils';
import { NULL_FIELD } from './field';
export interface IEncodeProps {
geomType: string;
@@ -17,6 +18,7 @@ export interface IEncodeProps {
radius: IViewField;
details: Readonly<IViewField[]>;
text: IViewField;
+ displayOffset?: number;
}
export function availableChannels(geomType: string): Set<string> {
if (geomType === 'text') {
@@ -75,11 +77,14 @@ export function channelEncode(props: IEncodeProps) {
if (props[c].analyticType === 'measure') {
encoding[c].type = 'quantitative';
}
+ if (props[c].semanticType === 'temporal' && isNotEmpty(props.displayOffset)) {
+ encoding[c].scale = { type: 'utc' };
+ }
if (props[c].semanticType === 'temporal' && props[c].timeUnit) {
encoding[c].timeUnit = encodeTimeunit(props[c].timeUnit);
}
if (c === 'color' && props[c].expression?.op === 'paint') {
- const map: IPaintMap = props[c].expression!.params.find((x) => x.type === 'map' || x.type === 'newmap')!.value;
+ const map: IPaintMap | IPaintMapV2 = props[c].expression!.params.find((x) => x.type === 'map' || x.type === 'newmap')!.value;
const colors = map.usedColor.map((x) => map.dict[x]).filter(Boolean);
encoding[c].scale = {
domain: colors.map((x) => x.name),
diff --git a/packages/graphic-walker/src/vis/spec/tooltip.ts b/packages/graphic-walker/src/vis/spec/tooltip.ts
index 6e4bcaa7..4c3913ef 100644
--- a/packages/graphic-walker/src/vis/spec/tooltip.ts
+++ b/packages/graphic-walker/src/vis/spec/tooltip.ts
@@ -14,6 +14,11 @@ export function addTooltipEncode(encoding: { [key: string]: any }, details: Read
timeUnit: encoding[ck].timeUnit,
}
: {}),
+ ...(encoding[ck].scale
+ ? {
+ scale: encoding[ck].scale,
+ }
+ : {}),
};
})
.concat(
diff --git a/packages/graphic-walker/src/vis/spec/view.ts b/packages/graphic-walker/src/vis/spec/view.ts
index f9a96207..3b5e3ab2 100644
--- a/packages/graphic-walker/src/vis/spec/view.ts
+++ b/packages/graphic-walker/src/vis/spec/view.ts
@@ -2,15 +2,24 @@ import { IChannelScales, IField, IFieldInfos, IRow, ISemanticType, IStackMode, I
import { autoMark } from './mark';
import { NULL_FIELD } from './field';
import { channelAggregate } from './aggregate';
-import { IEncodeProps, channelEncode } from './encode';
+import { IEncodeProps, channelEncode, encodeFid } from './encode';
import { channelStack } from './stack';
import { addTooltipEncode } from './tooltip';
+import { getTimeFormat } from '../../lib/inferMeta';
+import { unexceptedUTCParsedPatternFormats } from '../../lib/op/offset';
export interface SingleViewProps extends IEncodeProps {
defaultAggregated: boolean;
stack: IStackMode;
hideLegend?: boolean;
+ dataSource: readonly IRow[];
}
+
+function formatOffset(offset: number) {
+ if (offset === 0) return '';
+ return `${offset > 0 ? '+' : '-'}${Math.abs(offset)}`;
+}
+
export function getSingleView(props: SingleViewProps) {
const {
x,
@@ -31,6 +40,8 @@ export function getSingleView(props: SingleViewProps) {
stack,
geomType,
hideLegend = false,
+ displayOffset,
+ dataSource,
} = props;
const fields: IViewField[] = [x, y, color, opacity, size, shape, row, column, xOffset, yOffset, theta, radius, text];
let markType = geomType;
@@ -47,6 +58,37 @@ export function getSingleView(props: SingleViewProps) {
markType = autoMark(types);
}
+ const transform = fields
+ .filter((f) => f.semanticType === 'temporal')
+ .map((f) => {
+ let offsetTime = (displayOffset ?? new Date().getTimezoneOffset() - (f.offset ?? new Date().getTimezoneOffset())) * -60000;
+ const fid = encodeFid(f.fid);
+ const sample = dataSource[0]?.[f.fid];
+ if (sample) {
+ const format = getTimeFormat(sample);
+ if (format !== 'timestamp') {
+ if (unexceptedUTCParsedPatternFormats.includes(format)) {
+ offsetTime += new Date().getTimezoneOffset() * 60000;
+ }
+ if (offsetTime === 0) {
+ return null;
+ }
+ return {
+ calculate: `toDate(datum.${fid})${formatOffset(offsetTime)}`,
+ as: fid,
+ };
+ }
+ }
+ if (offsetTime === 0) {
+ return null;
+ }
+ return {
+ calculate: `datum.${fid}${formatOffset(offsetTime)}`,
+ as: fid,
+ };
+ })
+ .filter(Boolean);
+
let encoding = channelEncode({
geomType: markType,
x,
@@ -63,6 +105,7 @@ export function getSingleView(props: SingleViewProps) {
radius,
details,
text,
+ displayOffset,
});
if (defaultAggregated) {
channelAggregate(encoding, fields);
@@ -76,12 +119,18 @@ export function getSingleView(props: SingleViewProps) {
};
return {
config,
+ transform,
mark,
encoding,
};
}
-export function resolveScale<T extends Object>(scale: T | ((info: IFieldInfos) => T), field: IField | null | undefined, data: readonly IRow[], theme: 'dark' | 'light') {
+export function resolveScale<T extends Object>(
+ scale: T | ((info: IFieldInfos) => T),
+ field: IField | null | undefined,
+ data: readonly IRow[],
+ theme: 'dark' | 'light'
+) {
if (typeof scale === 'function') {
if (!field) return undefined;
const values = data.map((x) => x[field.fid]);