Skip to content

An open source alternative to Tableau. Embeddable visual analytic

Feat delete chart (#172)

islxyqwe3ae153d985f1
diff --git a/packages/graphic-walker/src/components/removeConfirm.tsx b/packages/graphic-walker/src/components/removeConfirm.tsx
new file mode 100644
index 00000000..13683987
--- /dev/null
+++ b/packages/graphic-walker/src/components/removeConfirm.tsx
@@ -0,0 +1,39 @@
+import React from 'react';
+import Modal from './modal';
+import { observer } from 'mobx-react-lite';
+import { useGlobalStore } from '../store';
+import DefaultButton from './button/default';
+import PrimaryButton from './button/primary';
+import { useTranslation } from 'react-i18next';
+
+const RemoveConfirm = observer(function RemoveConfirm() {
+ const { t } = useTranslation();
+
+ const { vizStore } = useGlobalStore();
+ return (
+ <Modal onClose={() => vizStore.closeRemoveConfirmModal()} show={vizStore.removeConfirmIdx !== null}>
+ <div>
+ <span className="block text-sm font-medium leading-6">{t('main.tablist.remove_confirm')}</span>
+ <div className="mt-4 flex justify-end">
+ <DefaultButton
+ className="mr-2"
+ text={t('actions.cancel')}
+ onClick={() => {
+ vizStore.closeRemoveConfirmModal();
+ }}
+ />
+ <PrimaryButton
+ className="bg-red-600 hover:bg-red-700"
+ text={t('actions.confirm')}
+ onClick={() => {
+ vizStore.removeVisualization(vizStore.removeConfirmIdx!);
+ vizStore.closeRemoveConfirmModal();
+ }}
+ />
+ </div>
+ </div>
+ </Modal>
+ );
+});
+
+export default RemoveConfirm;
diff --git a/packages/graphic-walker/src/components/tabs/editableTab.tsx b/packages/graphic-walker/src/components/tabs/editableTab.tsx
index af004dcc..045e38e0 100644
--- a/packages/graphic-walker/src/components/tabs/editableTab.tsx
+++ b/packages/graphic-walker/src/components/tabs/editableTab.tsx
@@ -1,13 +1,15 @@
-import React, { useState } from "react";
-import { useTranslation } from "react-i18next";
-import { PencilSquareIcon } from "@heroicons/react/24/outline";
-import Modal from "../modal";
-import { unstable_batchedUpdates } from "react-dom";
-import DefaultButton from "../button/default";
-import PrimaryButton from "../button/primary";
+import React, { Fragment, useState, useCallback, useRef } from 'react';
+import { useTranslation } from 'react-i18next';
+import { EllipsisVerticalIcon } from '@heroicons/react/24/outline';
+import Modal from '../modal';
+import { unstable_batchedUpdates } from 'react-dom';
+import DefaultButton from '../button/default';
+import PrimaryButton from '../button/primary';
+import RemoveConfirm from '../removeConfirm';
+import { Popover, Transition } from '@headlessui/react';
function classNames(...classes: string[]) {
- return classes.filter(Boolean).join(" ");
+ return classes.filter(Boolean).join(' ');
}
export interface ITabOption {
@@ -18,17 +20,103 @@ export interface ITabOption {
interface EditableTabsProps {
tabs: ITabOption[];
selectedKey: string;
+ showRemove?: boolean;
onSelected: (selectedKey: string, index: number) => void;
onEditLabel?: (label: string, index: number) => void;
+ onDuplicate?: (index: number) => void;
+ onRemove?: (index: number) => void;
}
+
+const Slider = (props: { className?: string; children: React.ReactNode; safeDistance: number }) => {
+ const [x, setX] = useState(0);
+ const ref = useRef<HTMLDivElement>();
+ const childDisposeRef = useRef<() => void>();
+
+ const onWheel = useCallback(
+ (e: WheelEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ const rect = ref.current?.children[0]?.getBoundingClientRect();
+ if (rect) {
+ console.log(rect);
+ setX((x) => Math.min(rect.width - props.safeDistance, Math.max(0, x + e.deltaY)));
+ }
+ return false;
+ },
+ [props.safeDistance]
+ );
+
+ const refCB = useCallback(
+ (node) => {
+ if (node == null) {
+ if (ref.current != null) {
+ ref.current.removeEventListener('wheel', onWheel);
+ }
+ return;
+ }
+ ref.current = node;
+ node.addEventListener('wheel', onWheel, { passive: false });
+ },
+ [onWheel]
+ );
+
+ const onResize = useCallback(
+ (rect) => {
+ setX((x) => Math.min(x, rect.width - props.safeDistance));
+ },
+ [props.safeDistance]
+ );
+
+ const childRefCB = useCallback(
+ (node) => {
+ if (node === null) {
+ if (childDisposeRef.current != null) {
+ childDisposeRef.current();
+ }
+ return;
+ }
+ const r = new ResizeObserver((es) => {
+ for (const e of es) {
+ onResize(e.contentRect);
+ }
+ });
+ childDisposeRef.current = () => {
+ r.disconnect();
+ };
+ r.observe(node);
+ },
+ [onResize]
+ );
+
+ return (
+ <div
+ style={{ overflowX: 'clip' }}
+ ref={refCB}
+ onWheel={(e) => {
+ e.preventDefault();
+ e.stopPropagation();
+ e.nativeEvent.preventDefault();
+ setX((x) => Math.max(0, x + e.deltaY));
+ return false;
+ }}
+ className={props.className}
+ >
+ <div ref={childRefCB} style={{ left: `-${x}px`, width: 'min-content', position: 'relative' }}>
+ {props.children}
+ </div>
+ </div>
+ );
+};
+
export default function EditableTabs(props: EditableTabsProps) {
- const { tabs, selectedKey, onSelected, onEditLabel } = props;
+ const { tabs, selectedKey, onSelected, onEditLabel, onRemove, onDuplicate, showRemove } = props;
const [editingIndex, setEditingIndex] = useState<number>(-1);
- const [name, setName] = useState<string>("");
+ const [name, setName] = useState<string>('');
const { t } = useTranslation();
return (
- <div className="border-b border-gray-200 dark:border-gray-700 overflow-x-auto overflow-y-hidden">
+ <div className="border-b border-gray-200 dark:border-gray-700 overflow-y-visible">
+ <RemoveConfirm />
<Modal
show={editingIndex > -1}
onClose={() => {
@@ -51,61 +139,105 @@ export default function EditableTabs(props: EditableTabsProps) {
<div className="mt-4 flex justify-end">
<DefaultButton
className="mr-2"
- text={t("actions.cancel")}
+ text={t('actions.cancel')}
onClick={() => {
unstable_batchedUpdates(() => {
setEditingIndex(-1);
- setName("");
+ setName('');
});
}}
/>
<PrimaryButton
- text={t("actions.confirm")}
+ text={t('actions.confirm')}
onClick={() => {
unstable_batchedUpdates(() => {
onEditLabel && onEditLabel(name, editingIndex);
setEditingIndex(-1);
- setName("");
+ setName('');
});
}}
/>
</div>
</div>
</Modal>
- <nav className="-mb-px flex h-8 border-gray-200 dark:border-gray-700" role="tablist" aria-label="Tabs">
- {tabs.map((tab, tabIndex) => (
- <span
- role="tab"
- tabIndex={0}
- // dangerouslySetInnerHTML={{
- // __html: tab.label
- // }}
- onClick={() => {
- onSelected(tab.key, tabIndex);
- }}
- key={tab.key}
- className={classNames(
- tab.key === selectedKey
- ? "border rounded-t"
- : "text-gray-500 dark:text-gray-400 hover:text-gray-700 hover:bg-gray-50 dark:hover:text-gray-200 dark:hover:bg-gray-800",
- "whitespace-nowrap border-gray-200 dark:border-gray-700 py-1 px-2 pr-6 text-sm cursor-default dark:text-white"
- )}
- >
- {tab.label}{" "}
- {tab.key === selectedKey && tab.editable && (
- <PencilSquareIcon
- className="w-3 inline cursor-pointer"
- onClick={() => {
- unstable_batchedUpdates(() => {
- setEditingIndex(tabIndex);
- setName(tab.label);
- });
- }}
- />
- )}
- </span>
- ))}
- </nav>
+ <Slider safeDistance={120}>
+ <nav className="-mb-px flex h-8 border-gray-200 dark:border-gray-700" role="tablist" aria-label="Tabs">
+ {tabs.map((tab, tabIndex) => (
+ <span
+ role="tab"
+ tabIndex={0}
+ // dangerouslySetInnerHTML={{
+ // __html: tab.label
+ // }}
+ onClick={() => {
+ onSelected(tab.key, tabIndex);
+ }}
+ key={tab.key}
+ className={classNames(
+ tab.key === selectedKey
+ ? 'border rounded-t'
+ : 'text-gray-500 dark:text-gray-400 hover:text-gray-700 hover:bg-gray-50 dark:hover:text-gray-200 dark:hover:bg-gray-800',
+ 'flex whitespace-nowrap group border-gray-200 dark:border-gray-700 py-1 px-2 pr-2 text-sm cursor-default dark:text-white'
+ )}
+ >
+ {tab.label}
+ {tab.key === selectedKey && tab.editable && (
+ <Popover className="relative inline-flex">
+ <Popover.Button className="inline-flex items-center gap-x-1 text-sm font-semibold leading-6 text-gray-900">
+ <EllipsisVerticalIcon className="h-4 w-4" aria-hidden="true" />
+ </Popover.Button>
+ <Transition
+ as={Fragment}
+ enter="transition ease-out duration-200"
+ enterFrom="opacity-0 translate-y-1"
+ enterTo="opacity-100 translate-y-0"
+ leave="transition ease-in duration-150"
+ leaveFrom="opacity-100 translate-y-0"
+ leaveTo="opacity-0 translate-y-1"
+ >
+ <Popover.Panel className="absolute left-1/2 z-10 mt-5 flex w-screen max-w-min -translate-x-1/4 px-2">
+ <div className="shrink rounded p-1 bg-white text-xs font-semibold leading-2 text-gray-900 shadow-lg ring-1 ring-gray-900/5">
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ unstable_batchedUpdates(() => {
+ setEditingIndex(tabIndex);
+ setName(tab.label);
+ });
+ }}
+ className="block p-1 w-full hover:bg-gray-200 text-left"
+ >
+ {'Edit'}
+ </button>
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ onDuplicate?.(tabIndex);
+ }}
+ className="block p-1 w-full hover:bg-gray-200 text-left"
+ >
+ {'Duplicate'}
+ </button>
+ {showRemove && (
+ <button
+ onClick={(e) => {
+ e.stopPropagation();
+ onRemove?.(tabIndex);
+ }}
+ className="block p-1 w-full hover:bg-gray-200 text-red-500 text-left"
+ >
+ {'Remove'}
+ </button>
+ )}
+ </div>
+ </Popover.Panel>
+ </Transition>
+ </Popover>
+ )}
+ </span>
+ ))}
+ </nav>
+ </Slider>
</div>
);
-}
+}
\ No newline at end of file
diff --git a/packages/graphic-walker/src/locales/en-US.json b/packages/graphic-walker/src/locales/en-US.json
index 92a1e0c7..ccf1027c 100644
--- a/packages/graphic-walker/src/locales/en-US.json
+++ b/packages/graphic-walker/src/locales/en-US.json
@@ -160,7 +160,8 @@
"tablist": {
"new": "+ New",
"auto_title": "Chart {{idx}}",
- "chart_name": "Chart Name"
+ "chart_name": "Chart Name",
+ "remove_confirm": "Are you sure you want to remove this chart?"
},
"tabpanel": {
"menubar": {
diff --git a/packages/graphic-walker/src/locales/ja-JP.json b/packages/graphic-walker/src/locales/ja-JP.json
index 6b5d89ce..0e0fe97c 100644
--- a/packages/graphic-walker/src/locales/ja-JP.json
+++ b/packages/graphic-walker/src/locales/ja-JP.json
@@ -154,7 +154,8 @@
"tablist": {
"new": "+ 新規ビュー",
"auto_title": "ビュー {{idx}}",
- "chart_name": "ビュー名"
+ "chart_name": "グラフ名",
+ "remove_confirm": "このグラフを削除してもよろしいですか?"
},
"askviz": {
"placeholder": "データセットから描画したい視覚化は何ですか?"
diff --git a/packages/graphic-walker/src/locales/zh-CN.json b/packages/graphic-walker/src/locales/zh-CN.json
index f946a5bb..6c51b884 100644
--- a/packages/graphic-walker/src/locales/zh-CN.json
+++ b/packages/graphic-walker/src/locales/zh-CN.json
@@ -160,7 +160,8 @@
"tablist": {
"new": "+ 新建",
"auto_title": "图表 {{idx}}",
- "chart_name": "图表名称"
+ "chart_name": "图表名称",
+ "remove_confirm": "你确定要删除这个图表吗?"
},
"askviz": {
"placeholder": "想从数据集中绘制哪种可视化呢?"
diff --git a/packages/graphic-walker/src/segments/visNav.tsx b/packages/graphic-walker/src/segments/visNav.tsx
index 6cb5997c..8a8d0bfe 100644
--- a/packages/graphic-walker/src/segments/visNav.tsx
+++ b/packages/graphic-walker/src/segments/visNav.tsx
@@ -46,12 +46,23 @@ const VisNav: React.FC = (props) => {
vizStore.setVisName(tabIndex, content)
}, [])
+ const deleteHandler = useCallback((tabIndex: number) => {
+ vizStore.openRemoveConfirmModal(tabIndex);
+ }, [])
+
+ const dupHandler = useCallback((tabIndex: number) => {
+ vizStore.duplicateVisualization(tabIndex);
+ }, [])
+
return (
<EditableTabs
selectedKey={visList[visIndex].visId}
tabs={tabs}
onEditLabel={editLabelHandler}
onSelected={visSelectionHandler}
+ onDuplicate={dupHandler}
+ onRemove={deleteHandler}
+ showRemove={visList.length > 1}
/>
);
};
diff --git a/packages/graphic-walker/src/store/visualSpecStore.ts b/packages/graphic-walker/src/store/visualSpecStore.ts
index 81c06630..129147e3 100644
--- a/packages/graphic-walker/src/store/visualSpecStore.ts
+++ b/packages/graphic-walker/src/store/visualSpecStore.ts
@@ -17,9 +17,9 @@ import {
Specification,
IComputationFunction,
IGeoUrl,
- ISemanticType
+ ISemanticType,
} from '../interfaces';
-import { DATE_TIME_DRILL_LEVELS, DATE_TIME_FEATURE_LEVELS } from "../constants";
+import { DATE_TIME_DRILL_LEVELS, DATE_TIME_FEATURE_LEVELS } from '../constants';
import { GLOBAL_CONFIG } from '../config';
import { VisSpecWithHistory } from '../models/visSpecHistory';
import {
@@ -157,6 +157,7 @@ export class VizSpecStore {
public canUndo = false;
public canRedo = false;
public editingFilterIdx: number | null = null;
+ public removeConfirmIdx: number | null = null;
// TODO
public computationFunction: IComputationFunction = async () => [];
constructor(commonStore: CommonStore) {
@@ -331,6 +332,23 @@ export class VizSpecStore {
public selectVisualization(visIndex: number) {
this.visIndex = visIndex;
}
+ public removeVisualization(index: number) {
+ if (this.visList.length === 1) return;
+ if (this.visIndex >= index && this.visIndex > 0) this.visIndex -= 1;
+ this.visList.splice(index, 1);
+ }
+ public duplicateVisualization(index: number) {
+ const ori = this.visList[index].exportGW();
+ this.visList.push(
+ new VisSpecWithHistory({
+ ...ori,
+ name: ori.name + ' Copy',
+ visId: uniqueId(),
+ })
+ );
+ this.visIndex = this.visList.length - 1;
+ }
+
public setVisName(visIndex: number, name: string) {
this.visList[visIndex] = this.visList[visIndex].clone();
this.visList[visIndex].updateLatest({
@@ -387,7 +405,9 @@ export class VizSpecStore {
public setVisualConfig<K extends keyof IVisualConfig>(configKey: K, value: IVisualConfig[K]) {
this.useMutable(({ config }) => {
switch (true) {
- case ['defaultAggregated', 'defaultStack', 'showActions', 'interactiveScale', 'scaleIncludeUnmatchedChoropleth', 'useSvg'].includes(configKey): {
+ case ['defaultAggregated', 'defaultStack', 'showActions', 'interactiveScale', 'scaleIncludeUnmatchedChoropleth', 'useSvg'].includes(
+ configKey
+ ): {
return ((config as unknown as { [k: string]: boolean })[configKey] = Boolean(value));
}
case configKey === 'geoms' && Array.isArray(value):
@@ -522,11 +542,16 @@ export class VizSpecStore {
encodings.latitude = fieldsInCup2 as typeof encodings.latitude; // assume this as writable
});
}
- public createBinField(stateKey: keyof DraggableFieldState, index: number, binType: 'bin' | 'binCount', num:number|undefined=10): string {
+ public createBinField(stateKey: keyof DraggableFieldState, index: number, binType: 'bin' | 'binCount', num: number | undefined = 10): string {
const newVarKey = uniqueId();
const state = this.draggableFieldState;
const existedRelatedBinField = state.dimensions.find(
- (f) => f.computed && f.expression && f.expression.op === binType && f.expression.num === num && f.expression.params[0].value === state[stateKey][index].fid
+ (f) =>
+ f.computed &&
+ f.expression &&
+ f.expression.op === binType &&
+ f.expression.num === num &&
+ f.expression.params[0].value === state[stateKey][index].fid
);
if (existedRelatedBinField) {
return existedRelatedBinField.fid;
@@ -549,14 +574,14 @@ export class VizSpecStore {
value: originField.fid,
},
],
- num: num
+ num: num,
},
};
encodings.dimensions.push(binField);
});
return newVarKey;
}
- public createLogField(stateKey: keyof DraggableFieldState, index: number, scaleType: 'log', num: number|undefined = 10) {
+ public createLogField(stateKey: keyof DraggableFieldState, index: number, scaleType: 'log', num: number | undefined = 10) {
if (stateKey === 'filters') {
return;
}
@@ -591,14 +616,28 @@ export class VizSpecStore {
const originField = encodings[stateKey][index];
encodings[stateKey].splice(index, 1, {
...originField,
- semanticType: newSemanticType
- })
+ semanticType: newSemanticType,
+ });
});
}
- public createDateTimeDrilledField(stateKey: keyof DraggableFieldState, index: number, op: 'dateTimeDrill', drillLevel: typeof DATE_TIME_DRILL_LEVELS[number], name: string | ((originFieldName: string) => string), format: string)
- public createDateTimeDrilledField(stateKey: keyof DraggableFieldState, index: number, op: 'dateTimeFeature', drillLevel: typeof DATE_TIME_FEATURE_LEVELS[number], name: string | ((originFieldName: string) => string), format: string)
+ public createDateTimeDrilledField(
+ stateKey: keyof DraggableFieldState,
+ index: number,
+ op: 'dateTimeDrill',
+ drillLevel: (typeof DATE_TIME_DRILL_LEVELS)[number],
+ name: string | ((originFieldName: string) => string),
+ format: string
+ );
+ public createDateTimeDrilledField(
+ stateKey: keyof DraggableFieldState,
+ index: number,
+ op: 'dateTimeFeature',
+ drillLevel: (typeof DATE_TIME_FEATURE_LEVELS)[number],
+ name: string | ((originFieldName: string) => string),
+ format: string
+ );
public createDateTimeDrilledField(stateKey, index, op, drillLevel, name, format) {
- if (stateKey === "filters") {
+ if (stateKey === 'filters') {
return;
}
@@ -609,7 +648,7 @@ export class VizSpecStore {
fid: newVarKey,
dragId: newVarKey,
name: typeof name === 'function' ? name(originField.name) : name,
- semanticType: op === 'dateTimeDrill' ? "temporal" : "ordinal",
+ semanticType: op === 'dateTimeDrill' ? 'temporal' : 'ordinal',
analyticType: originField.analyticType,
aggName: 'sum',
computed: true,
@@ -628,8 +667,8 @@ export class VizSpecStore {
},
{
type: 'format',
- value: format
- }
+ value: format,
+ },
],
},
};
@@ -645,6 +684,14 @@ export class VizSpecStore {
}
});
}
+ public openRemoveConfirmModal(index: number) {
+ this.removeConfirmIdx = index;
+ }
+
+ public closeRemoveConfirmModal() {
+ this.removeConfirmIdx = null;
+ }
+
public get sortCondition() {
const { rows, columns } = this.draggableFieldState;
const yField = rows.length > 0 ? rows[rows.length - 1] : null;
@@ -936,8 +983,8 @@ export class VizSpecStore {
},
config: {
...visSpec.config,
- geojson: visSpec.config.geoUrl ? undefined : visSpec.config.geojson
- }
+ geojson: visSpec.config.geoUrl ? undefined : visSpec.config.geojson,
+ },
};
});
return updatedVisList;