Skip to content

An open source alternative to Tableau. Embeddable visual analytic

[Feat] datetime drill down/up (#125)

Bobce6b4a09ae96
diff --git a/packages/graphic-walker/src/components/actionMenu/a11y.tsx b/packages/graphic-walker/src/components/actionMenu/a11y.tsx
new file mode 100644
index 00000000..c9707f73
--- /dev/null
+++ b/packages/graphic-walker/src/components/actionMenu/a11y.tsx
@@ -0,0 +1,48 @@
+import { type HTMLAttributes, type MouseEvent, useCallback, useMemo, type KeyboardEvent, type AriaAttributes, type ComponentPropsWithoutRef } from "react";
+
+
+export type ReactTag = keyof JSX.IntrinsicElements;
+export type ElementType<T extends ReactTag> = Parameters<NonNullable<ComponentPropsWithoutRef<T>['onClick']>>[0] extends MouseEvent<infer U, globalThis.MouseEvent> ? U : never;
+
+interface IUseMenuButtonOptions {
+ "aria-expanded": NonNullable<AriaAttributes['aria-expanded']>;
+ onPress?: () => void;
+ disabled?: boolean;
+}
+
+export const useMenuButton = <T extends ReactTag>(options: IUseMenuButtonOptions & Omit<ComponentPropsWithoutRef<T>, keyof IUseMenuButtonOptions>): HTMLAttributes<ElementType<T>> => {
+ const { ["aria-expanded"]: expanded, onPress, disabled, className = '', ...attrs } = options;
+
+ const onClick = useCallback((e: MouseEvent<any>) => {
+ e.preventDefault();
+ e.stopPropagation();
+ onPress?.();
+ }, [onPress]);
+
+ const onKeyDown = useCallback((e: KeyboardEvent<any>) => {
+ switch (e.key) {
+ case 'Enter':
+ case 'Space': {
+ onPress?.();
+ break;
+ }
+ default: {
+ return;
+ }
+ }
+ e.preventDefault();
+ e.stopPropagation();
+ }, [onPress]);
+
+ return useMemo(() => ({
+ ...attrs,
+ className: `${className} text-gray-500 dark:text-gray-400 ${disabled ? 'cursor-default text-opacity-50' : 'cursor-pointer rounded-full focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 dark:focus:ring-indigo-500 hover:bg-indigo-100/20 dark:hover:bg-indigo-800/20 hover:text-indigo-700 dark:hover:text-indigo-200'}`,
+ role: 'button',
+ "aria-haspopup": 'menu',
+ "aria-expanded": expanded,
+ "aria-disabled": disabled,
+ tabIndex: disabled ? undefined : 0,
+ onClick,
+ onKeyDown,
+ }) as HTMLAttributes<ElementType<T>>, [onClick, onKeyDown, expanded, disabled, className, attrs]);
+};
diff --git a/packages/graphic-walker/src/components/actionMenu/index.tsx b/packages/graphic-walker/src/components/actionMenu/index.tsx
new file mode 100644
index 00000000..eb804e02
--- /dev/null
+++ b/packages/graphic-walker/src/components/actionMenu/index.tsx
@@ -0,0 +1,167 @@
+import React, { Fragment, type HTMLAttributes, memo, type ReactElement, createContext, useState, useContext, useRef, useCallback, type ComponentPropsWithoutRef } from "react";
+import { Menu, Transition } from "@headlessui/react";
+import { type ReactTag, type ElementType, useMenuButton } from './a11y';
+import ActionMenuItemList, { type IActionMenuItem } from "./list";
+
+
+interface IActionMenuContext {
+ disabled: boolean;
+ expanded: boolean;
+ moveTo(x: number, y: number): void;
+ open(): void;
+ close(): void;
+ _items: readonly IActionMenuItem[];
+}
+
+const Context = createContext<IActionMenuContext | null>(null);
+
+interface IActionMenuProps {
+ menu?: IActionMenuItem[];
+ disabled?: boolean;
+ /** @default false */
+ enableContextMenu?: boolean;
+ title?: string;
+}
+
+const ActionMenu: React.FC<IActionMenuProps & Omit<HTMLAttributes<HTMLDivElement>, keyof IActionMenuProps>> = (props) => {
+ const { menu = [], disabled = false, enableContextMenu = false, title, ...attrs } = props;
+
+ const [coord, setCoord] = useState<[x: number, y: number]>([0, 0]);
+ const buttonRef = useRef<HTMLButtonElement>(null);
+
+ if (disabled || menu.length === 0) {
+ return (
+ <div {...attrs}>
+ {props.children}
+ </div>
+ );
+ }
+
+ return (
+ <Menu as={Fragment}>
+ {({ open, close }) => {
+ return (
+ <Context.Provider
+ value={{
+ disabled,
+ expanded: open,
+ moveTo(x, y) {
+ setCoord([x, y]);
+ },
+ open() {
+ if (!open) {
+ buttonRef.current?.click();
+ }
+ },
+ close,
+ _items: menu,
+ }}
+ >
+ <Menu.Button
+ ref={buttonRef}
+ className="sr-only"
+ aria-hidden
+ />
+ <div
+ onContextMenu={e => {
+ e.preventDefault();
+ e.stopPropagation();
+ setCoord([e.clientX, e.clientY]);
+ if (!open) {
+ buttonRef.current?.click();
+ }
+ }}
+ {...attrs}
+ >
+ {props.children}
+ </div>
+ {open && <div className="fixed inset-0 z-50 bg-transparent" aria-hidden="true" />}
+ <Transition
+ as={Fragment}
+ enter="transition ease-out duration-100"
+ enterFrom="transform opacity-0 scale-95"
+ enterTo="transform opacity-100 scale-100"
+ leave="transition ease-in duration-75"
+ leaveFrom="transform opacity-100 scale-100"
+ leaveTo="transform opacity-0 scale-95"
+ >
+ <Menu.Items
+ className="fixed z-50 mt-0.5 min-w-[8rem] max-w-[16rem] origin-top-left bg-white dark:bg-zinc-900 shadow-lg border border-gray-50 dark:border-gray-800 focus:outline-none"
+ style={{
+ left: coord[0],
+ top: coord[1],
+ }}
+ >
+ <ActionMenuItemList title={title} items={menu} onDismiss={close} />
+ </Menu.Items>
+ </Transition>
+ </Context.Provider>
+ );
+ }}
+ </Menu>
+ );
+};
+
+type IActionMenuButtonProps<T extends ReactTag> = (
+ | {
+ /** @default "button" */
+ as: T;
+ }
+ | {
+ /** @default "button" */
+ as?: ReactTag;
+ }
+) & {
+ onPress?: (ctx: IActionMenuContext | undefined) => void;
+ /** @deprecated use `onPress()` instead */
+ onClick?: () => void;
+};
+
+const ActionMenuButton = function ActionMenuButton<T extends ReactTag>(props: IActionMenuButtonProps<T> & Omit<ComponentPropsWithoutRef<T>, keyof IActionMenuProps>): ReactElement {
+ const { as: _as = 'button', onPress, children, ...attrs } = props;
+ const Component = _as as T;
+
+ const ctx = useContext(Context);
+ const buttonRef = useRef<ElementType<T>>(null);
+
+ const handlePress = useCallback(() => {
+ if (ctx?.disabled) {
+ return;
+ }
+ const btn = buttonRef.current;
+ if (btn) {
+ const rect = (btn as unknown as HTMLElement | SVGElement).getBoundingClientRect();
+ ctx?.moveTo(rect.x + rect.width, rect.y);
+ }
+ if (onPress) {
+ return onPress(ctx ?? undefined);
+ }
+ if (ctx?.expanded) {
+ ctx.close();
+ } else {
+ ctx?.open();
+ }
+ }, [ctx, onPress]);
+
+ const buttonProps = useMenuButton({
+ ...attrs,
+ "aria-expanded": ctx?.expanded ?? false,
+ onPress: handlePress,
+ });
+
+ if (ctx?.disabled || !ctx?._items.length) {
+ return <div aria-hidden />;
+ }
+
+ return (
+ // @ts-expect-error Expression produces a union type that is too complex to represent
+ <Component {...buttonProps} ref={buttonRef}>
+ {children}
+ </Component>
+ );
+};
+
+
+export default Object.assign(ActionMenu, {
+ Button: memo(ActionMenuButton),
+});
diff --git a/packages/graphic-walker/src/components/actionMenu/list.tsx b/packages/graphic-walker/src/components/actionMenu/list.tsx
new file mode 100644
index 00000000..dab28b8c
--- /dev/null
+++ b/packages/graphic-walker/src/components/actionMenu/list.tsx
@@ -0,0 +1,223 @@
+import React, { memo, type ComponentProps, type ReactElement, createContext, useState, useContext, useMemo, useEffect } from "react";
+import { ChevronRightIcon } from "@heroicons/react/24/outline";
+import styled from "styled-components";
+
+
+function classNames(...classes: string[]) {
+ return classes.filter(Boolean).join(" ");
+}
+
+export interface IActionMenuItem {
+ icon?: ReactElement;
+ label: string;
+ disabled?: boolean;
+ children?: IActionMenuItem[];
+ onPress?: () => void;
+}
+
+const List = styled.div`
+ display: grid;
+ grid-template-columns: max-content 1fr max-content;
+ & > div {
+ /* row */
+ display: contents;
+ > * {
+ background: inherit;
+ cursor: pointer;
+ width: 100%;
+ height: 100%;
+ display: flex;
+ align-items: center;
+ overflow: hidden;
+ padding-block: 0.2rem;
+ padding-inline: 0.2rem;
+ &:first-child {
+ padding-left: 0.4rem;
+ }
+ }
+ &[aria-disabled="true"] > * {
+ opacity: 0.5;
+ cursor: default;
+ }
+ }
+`;
+
+const FixedTarget = memo(function FixedTarget(props: ComponentProps<"div">) {
+ const { children, ...attrs } = props;
+
+ return (
+ <div className="absolute top-0 right-0">
+ <div
+ {...attrs}
+ style={{
+ ...attrs.style,
+ position: "fixed",
+ }}
+ >
+ {children}
+ </div>
+ </div>
+ );
+});
+
+interface IActionMenuRootContext {
+ path: number[];
+ setPath: (path: number[]) => void;
+ onDismiss: () => void;
+}
+
+const Context = createContext<IActionMenuRootContext>(null!);
+
+interface IActionMenuItemProps {
+ item: IActionMenuItem;
+ path: number[];
+}
+
+const ActionMenuItem = memo<IActionMenuItemProps>(function ActionMenuItem({ item, path }) {
+ const { icon, label, disabled = false, children = [], onPress } = item;
+ const [hover, setHover] = useState(false);
+ const [focus, setFocus] = useState(false);
+
+ const ctx = useContext(Context);
+
+ const expanded = children.length > 0 && ctx.path.length > 0 && path.length <= ctx.path.length && path.every((v, i) => v === ctx.path[i]);
+
+ const active = !disabled && (hover || focus || expanded);
+
+ const basePath = useMemo(() => {
+ let idx = ctx.path.findIndex((v, i) => v !== path[i]);
+ if (idx !== -1) {
+ return ctx.path.slice(0, idx);
+ }
+ return ctx.path;
+ }, [ctx.path, path]);
+
+ useEffect(() => {
+ if (children.length === 0 && (hover || focus)) {
+ if (basePath.join(".") !== ctx.path.join(".")) {
+ ctx.setPath(basePath);
+ }
+ }
+ }, [children.length, hover, focus, ctx, basePath]);
+
+ return (
+ <div
+ tabIndex={disabled ? undefined : 0}
+ role="button"
+ aria-haspopup={children.length ? "menu" : undefined}
+ aria-disabled={disabled}
+ className={classNames(
+ active ? "bg-gray-100/50 text-gray-900 dark:bg-gray-800/50 dark:text-gray-50" : "text-gray-700 dark:text-gray-200",
+ disabled ? "" : "cursor-pointer",
+ "text-xs",
+ )}
+ onClick={e => {
+ if (disabled || children.length) {
+ e.stopPropagation();
+ e.preventDefault();
+ return;
+ }
+ if (!disabled) {
+ onPress?.();
+ ctx.onDismiss();
+ }
+ }}
+ onFocus={() => {
+ if (!disabled) {
+ setFocus(true);
+ }
+ if (children.length && !expanded) {
+ ctx.setPath(path);
+ }
+ }}
+ onBlur={() => {
+ setFocus(false);
+ }}
+ onMouseEnter={() => {
+ setHover(true);
+ if (children.length && !expanded && !disabled) {
+ ctx.setPath(path);
+ }
+ }}
+ onMouseLeave={() => {
+ setHover(false);
+ }}
+ onKeyDown={e => {
+ if (disabled || children.length) {
+ return;
+ }
+ if (e.key === 'Enter' || e.key === 'Space') {
+ onPress?.();
+ ctx.onDismiss();
+ }
+ }}
+ >
+ <div aria-hidden="true">
+ {icon}
+ </div>
+ <div>
+ <span className="truncate self-start">
+ {label}
+ </span>
+ </div>
+ <div
+ aria-hidden="true"
+ className="relative"
+ >
+ {children.length > 0 && (
+ <>
+ <ChevronRightIcon className="w-4 h-4" aria-hidden="true" />
+ {expanded && (
+ <FixedTarget className="z-50 min-w-[8rem] max-w-[16rem] bg-white dark:bg-zinc-900 shadow-lg border border-gray-50 dark:border-gray-800 focus:outline-none">
+ <MenuItemList items={children} path={path} />
+ </FixedTarget>
+ )}
+ </>
+ )}
+ </div>
+ </div>
+ );
+});
+
+interface IActionMenuItemListProps {
+ title?: string;
+ items: IActionMenuItem[];
+ path: number[];
+}
+
+const MenuItemList = memo<IActionMenuItemListProps>(function ActionMenuItemList({ items, path, title }) {
+
+ return (
+ <div className="py-1 -mx-px">
+ {title && (
+ <header className="px-3 py-1 mb-1.5 text-xs text-gray-500/75 dark:text-gray-400/75 truncate">
+ {title}
+ </header>
+ )}
+ <List>
+ {items.map((item, index) => (
+ <ActionMenuItem key={index} item={item} path={[...path, index]} />
+ ))}
+ </List>
+ </div>
+ );
+});
+
+const ActionMenuItemRoot = memo<{ onDismiss: () => void; children: any }>(function ActionMenuItemRoot({ onDismiss, children }) {
+ const [path, setPath] = useState<number[]>([]);
+
+ return (
+ <Context.Provider value={{ path, setPath, onDismiss }}>
+ {children}
+ </Context.Provider>
+ );
+});
+
+
+export default memo<Omit<IActionMenuItemListProps, 'path'> & { onDismiss: () => void }>(function ActionMenuItemList({ onDismiss, items, title }) {
+ return (
+ <ActionMenuItemRoot onDismiss={onDismiss}>
+ <MenuItemList title={title} items={items} path={[]} />
+ </ActionMenuItemRoot>
+ );
+});
diff --git a/packages/graphic-walker/src/constants.ts b/packages/graphic-walker/src/constants.ts
index 5b0733fd..78495908 100644
--- a/packages/graphic-walker/src/constants.ts
+++ b/packages/graphic-walker/src/constants.ts
@@ -1 +1,4 @@
-export const COUNT_FIELD_ID = 'gw_count_fid';
\ No newline at end of file
+export const COUNT_FIELD_ID = 'gw_count_fid';
+export const DATE_TIME_DRILL_LEVELS = [
+ "year", "quarter", "month", "week", "day", "hour", "minute", "second"
+] as const;
diff --git a/packages/graphic-walker/src/fields/datasetFields/dimFields.tsx b/packages/graphic-walker/src/fields/datasetFields/dimFields.tsx
index c6342bcb..a523491b 100644
--- a/packages/graphic-walker/src/fields/datasetFields/dimFields.tsx
+++ b/packages/graphic-walker/src/fields/datasetFields/dimFields.tsx
@@ -1,9 +1,12 @@
import React from "react";
+import { EllipsisVerticalIcon } from "@heroicons/react/24/outline";
import { Draggable, DroppableProvided } from "@kanaries/react-beautiful-dnd";
import { observer } from "mobx-react-lite";
import { useGlobalStore } from "../../store";
import DataTypeIcon from "../../components/dataTypeIcon";
+import ActionMenu from "../../components/actionMenu";
import { FieldPill } from "./fieldPill";
+import { useMenuActions } from "./utils";
interface Props {
provided: DroppableProvided;
@@ -12,13 +15,19 @@ const DimFields: React.FC<Props> = (props) => {
const { provided } = props;
const { vizStore } = useGlobalStore();
const dimensions = vizStore.draggableFieldState.dimensions;
+ const menuActions = useMenuActions('dimensions');
return (
<div {...provided.droppableProps} ref={provided.innerRef}>
{dimensions.map((f, index) => (
<Draggable key={f.dragId} draggableId={f.dragId} index={index}>
{(provided, snapshot) => {
return (
- <>
+ <ActionMenu
+ title={f.name || f.fid}
+ menu={menuActions[index]}
+ enableContextMenu
+ disabled={snapshot.isDragging}
+ >
<FieldPill
className={`dark:text-white pt-0.5 pb-0.5 pl-2 pr-2 mx-0 m-1 text-xs hover:bg-blue-100 dark:hover:bg-blue-800 rounded-full truncate border border-transparent ${
snapshot.isDragging ? "bg-blue-100 dark:bg-blue-800" : ""
@@ -28,8 +37,11 @@ const DimFields: React.FC<Props> = (props) => {
{...provided.draggableProps}
{...provided.dragHandleProps}
>
- <DataTypeIcon dataType={f.semanticType} analyticType={f.analyticType} /> {f.name}
- &nbsp;
+ <DataTypeIcon dataType={f.semanticType} analyticType={f.analyticType} />
+ <span>{f.name}</span>
+ <ActionMenu.Button as="div">
+ <EllipsisVerticalIcon className="w-4 h-4" />
+ </ActionMenu.Button>
</FieldPill>
{
<FieldPill
@@ -38,11 +50,14 @@ const DimFields: React.FC<Props> = (props) => {
}`}
isDragging={snapshot.isDragging}
>
- <DataTypeIcon dataType={f.semanticType} analyticType={f.analyticType} />{" "}
- {f.name}&nbsp;
+ <DataTypeIcon dataType={f.semanticType} analyticType={f.analyticType} />
+ <span>{f.name}</span>
+ <ActionMenu.Button as="div">
+ <EllipsisVerticalIcon className="w-4 h-4" />
+ </ActionMenu.Button>
</FieldPill>
}
- </>
+ </ActionMenu>
);
}}
</Draggable>
diff --git a/packages/graphic-walker/src/fields/datasetFields/fieldPill.tsx b/packages/graphic-walker/src/fields/datasetFields/fieldPill.tsx
index 51694936..08eb7fc9 100644
--- a/packages/graphic-walker/src/fields/datasetFields/fieldPill.tsx
+++ b/packages/graphic-walker/src/fields/datasetFields/fieldPill.tsx
@@ -7,4 +7,22 @@ import styled from 'styled-components';
export const FieldPill = styled.div<{isDragging: boolean}>`
transform: ${props => !props.isDragging && 'translate(0px, 0px) !important'};
user-select: none;
+ display: flex;
+ align-items: center;
+ overflow: hidden;
+ > *:not(span) {
+ flex: 0 0 unset;
+ }
+ > span {
+ flex: 1;
+ display: inline-block;
+ padding-inline: 0.1em;
+ /* truncate */
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+ :has([role="button"]:hover) {
+ background-color: unset;
+ }
`
\ No newline at end of file
diff --git a/packages/graphic-walker/src/fields/datasetFields/meaFields.tsx b/packages/graphic-walker/src/fields/datasetFields/meaFields.tsx
index 75ccef59..574c81f2 100644
--- a/packages/graphic-walker/src/fields/datasetFields/meaFields.tsx
+++ b/packages/graphic-walker/src/fields/datasetFields/meaFields.tsx
@@ -5,6 +5,9 @@ import { useGlobalStore } from "../../store";
import DataTypeIcon from "../../components/dataTypeIcon";
import { FieldPill } from "./fieldPill";
import DropdownContext, { IDropdownContextOption } from "../../components/dropdownContext";
+import ActionMenu from "../../components/actionMenu";
+import { EllipsisVerticalIcon } from "@heroicons/react/24/outline";
+import { useMenuActions } from "./utils";
import { COUNT_FIELD_ID } from "../../constants";
interface Props {
@@ -35,6 +38,7 @@ const MeaFields: React.FC<Props> = (props) => {
},
];
}, []);
+ const menuActions = useMenuActions('measures');
const fieldActionHandler = useCallback((selectedValue: any, opIndex: number, meaIndex: number) => {
if (selectedValue === "bin" || selectedValue === 'binCount') {
@@ -50,37 +54,48 @@ const MeaFields: React.FC<Props> = (props) => {
{(provided, snapshot) => {
return (
<div className="block">
- <DropdownContext
- disable={snapshot.isDragging || f.fid === COUNT_FIELD_ID}
- options={MEA_ACTION_OPTIONS}
- onSelect={(v, opIndex) => {
- fieldActionHandler(v, opIndex, index);
- }}
+ <ActionMenu
+ title={f.name || f.fid}
+ menu={menuActions[index]}
+ enableContextMenu
+ disabled={snapshot.isDragging}
>
- <FieldPill
- className={`dark:text-white pt-0.5 pb-0.5 pl-2 pr-2 mx-0 m-1 text-xs hover:bg-purple-100 dark:hover:bg-purple-800 rounded-full truncate border border-transparent ${
- snapshot.isDragging ? "bg-purple-100 dark:bg-purple-800" : ""
- }`}
- isDragging={snapshot.isDragging}
- ref={provided.innerRef}
- {...provided.draggableProps}
- {...provided.dragHandleProps}
+ <DropdownContext
+ disable={snapshot.isDragging}
+ options={MEA_ACTION_OPTIONS}
+ onSelect={(v, opIndex) => {
+ fieldActionHandler(v, opIndex, index);
+ }}
>
- <DataTypeIcon dataType={f.semanticType} analyticType={f.analyticType} />{" "}
- {f.name}&nbsp;
- </FieldPill>
- </DropdownContext>
- {
- <FieldPill
- className={`dark:text-white pt-0.5 pb-0.5 pl-2 pr-2 mx-0 m-1 text-xs hover:bg-purple-100 dark:hover:bg-purple-800 rounded-full border-purple-400 border truncate ${
- snapshot.isDragging ? "bg-purple-100 dark:bg-purple-800" : "hidden"
- }`}
- isDragging={snapshot.isDragging}
- >
- <DataTypeIcon dataType={f.semanticType} analyticType={f.analyticType} />{" "}
- {f.name}&nbsp;
- </FieldPill>
- }
+ <FieldPill
+ className={`dark:text-white pt-0.5 pb-0.5 pl-2 pr-2 mx-0 m-1 text-xs hover:bg-purple-100 dark:hover:bg-purple-800 rounded-full truncate border border-transparent ${snapshot.isDragging ? "bg-purple-100 dark:bg-purple-800" : ""
+ }`}
+ isDragging={snapshot.isDragging}
+ ref={provided.innerRef}
+ {...provided.draggableProps}
+ {...provided.dragHandleProps}
+ >
+ <DataTypeIcon dataType={f.semanticType} analyticType={f.analyticType} />
+ <span>{f.name}</span>
+ <ActionMenu.Button as="div">
+ <EllipsisVerticalIcon className="w-4 h-4" />
+ </ActionMenu.Button>
+ </FieldPill>
+ </DropdownContext>
+ {
+ <FieldPill
+ className={`dark:text-white pt-0.5 pb-0.5 pl-2 pr-2 mx-0 m-1 text-xs hover:bg-purple-100 dark:hover:bg-purple-800 rounded-full border-purple-400 border truncate ${snapshot.isDragging ? "bg-purple-100 dark:bg-purple-800" : "hidden"
+ }`}
+ isDragging={snapshot.isDragging}
+ >
+ <DataTypeIcon dataType={f.semanticType} analyticType={f.analyticType} />
+ <span>{f.name}</span>
+ <ActionMenu.Button as="div">
+ <EllipsisVerticalIcon className="w-4 h-4" />
+ </ActionMenu.Button>
+ </FieldPill>
+ }
+ </ActionMenu>
</div>
);
}}
diff --git a/packages/graphic-walker/src/fields/datasetFields/utils.ts b/packages/graphic-walker/src/fields/datasetFields/utils.ts
new file mode 100644
index 00000000..d55c5267
--- /dev/null
+++ b/packages/graphic-walker/src/fields/datasetFields/utils.ts
@@ -0,0 +1,82 @@
+import { useMemo } from "react";
+import { useTranslation } from "react-i18next";
+import { useGlobalStore } from "../../store";
+import type { IActionMenuItem } from "../../components/actionMenu/list";
+import { COUNT_FIELD_ID, DATE_TIME_DRILL_LEVELS } from "../../constants";
+
+
+const keepTrue = <T extends string | number | object | Function | symbol>(array: (T | 0 | null | false | undefined | void)[]): T[] => {
+ return array.filter(Boolean) as T[];
+};
+
+export const useMenuActions = (channel: "dimensions" | "measures"): IActionMenuItem[][] => {
+ const { vizStore } = useGlobalStore();
+ const fields = vizStore.draggableFieldState[channel];
+ const { t } = useTranslation('translation', { keyPrefix: "field_menu" });
+
+ return useMemo<IActionMenuItem[][]>(() => {
+ return fields.map((f, index) => {
+ const isDateTimeDrilled = f.expression?.op === 'dateTimeDrill';
+
+ return keepTrue<IActionMenuItem>([
+ channel === 'dimensions' && {
+ label: t('to_dim'),
+ onPress() {
+ vizStore.moveField("dimensions", index, "measures", vizStore.draggableFieldState.measures.length);
+ },
+ },
+ channel === 'measures' && {
+ label: t('to_mea'),
+ disabled: f.fid === COUNT_FIELD_ID,
+ onPress() {
+ vizStore.moveField("measures", index, "dimensions", vizStore.draggableFieldState.dimensions.length);
+ },
+ },
+ {
+ label: t('new_calc'),
+ disabled: f.semanticType === 'nominal' || f.semanticType === 'ordinal',
+ children: [
+ {
+ label: "Bin",
+ onPress() {
+ vizStore.createBinField(channel, index, "bin");
+ },
+ },
+ {
+ label: "Bin Count",
+ disabled: f.semanticType === 'nominal' || f.semanticType === 'ordinal',
+ onPress() {
+ vizStore.createBinField(channel, index, "binCount");
+ },
+ },
+ {
+ label: "Log10",
+ disabled: f.semanticType === 'nominal' || f.semanticType === 'ordinal',
+ onPress() {
+ vizStore.createLogField(channel, index, "log10");
+ },
+ },
+ {
+ label: "Log2",
+ disabled: f.semanticType === 'nominal' || f.semanticType === 'ordinal',
+ onPress() {
+ vizStore.createLogField(channel, index, "log2");
+ },
+ },
+ ],
+ },
+ (f.semanticType === 'temporal' || isDateTimeDrilled) && {
+ label: t('drill.name'),
+ children: DATE_TIME_DRILL_LEVELS.map(level => ({
+ label: t(`drill.levels.${level}`),
+ disabled: isDateTimeDrilled && f.expression.params.find(p => p.type === 'value')?.value === level,
+ onPress() {
+ const originField = (isDateTimeDrilled ? vizStore.allFields.find(f => f.fid === f.expression?.params.find(p => p.type === 'field')?.value) : null) ?? f;
+ vizStore.createDateTimeDrilledField(channel, index, level, `${t(`drill.levels.${level}`)} (${originField.name || originField.fid})`);
+ },
+ })),
+ },
+ ]);
+ });
+ }, [channel, fields, vizStore, t]);
+};
diff --git a/packages/graphic-walker/src/interfaces.ts b/packages/graphic-walker/src/interfaces.ts
index 7ddc6b4b..7fbeb993 100644
--- a/packages/graphic-walker/src/interfaces.ts
+++ b/packages/graphic-walker/src/interfaces.ts
@@ -83,7 +83,7 @@ export type IExpParamter =
};
export interface IExpression {
- op: 'bin' | 'log2' | 'log10' | 'one' | 'binCount';
+ op: 'bin' | 'log2' | 'log10' | 'one' | 'binCount' | 'dateTimeDrill';
params: IExpParamter[];
as: string;
}
diff --git a/packages/graphic-walker/src/lib/execExp.ts b/packages/graphic-walker/src/lib/execExp.ts
index 34af9762..9293346b 100644
--- a/packages/graphic-walker/src/lib/execExp.ts
+++ b/packages/graphic-walker/src/lib/execExp.ts
@@ -1,6 +1,7 @@
import { IExpParamter, IExpression, IField, IRow } from "../interfaces";
+import dateTimeDrill from "./op/dateTimeDrill";
-interface IDataFrame {
+export interface IDataFrame {
[key: string]: any[];
}
@@ -38,6 +39,8 @@ export function execExpression (exp: IExpression, dataFrame: IDataFrame): IDataF
return log10(exp.as, params, subFrame);
case 'binCount':
return binCount(exp.as, params, subFrame);
+ case 'dateTimeDrill':
+ return dateTimeDrill(exp.as, params, subFrame);
default:
return subFrame;
}
diff --git a/packages/graphic-walker/src/lib/op/dateTimeDrill.ts b/packages/graphic-walker/src/lib/op/dateTimeDrill.ts
new file mode 100644
index 00000000..6eacf22e
--- /dev/null
+++ b/packages/graphic-walker/src/lib/op/dateTimeDrill.ts
@@ -0,0 +1,143 @@
+import { DATE_TIME_DRILL_LEVELS } from "../../constants";
+import type { IExpParamter } from "../../interfaces";
+import type { IDataFrame } from "../execExp";
+
+
+function dateTimeDrill(resKey: string, params: IExpParamter[], 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;
+ if (!fieldKey || !drillLevel) {
+ return data;
+ }
+ const fieldValues = data[fieldKey];
+ switch (drillLevel) {
+ case 'year': {
+ const newValues = fieldValues.map(v => {
+ const date = new Date(v);
+ const Y = date.getFullYear();
+ return Y;
+ });
+ return {
+ ...data,
+ [resKey]: newValues,
+ };
+ }
+ case 'quarter': {
+ const newValues = fieldValues.map(v => {
+ const date = new Date(v);
+ const Y = date.getFullYear();
+ const Q = Math.floor(date.getMonth() / 3) + 1;
+ return `${Y} Q${Q}`;
+ });
+ return {
+ ...data,
+ [resKey]: newValues,
+ };
+ }
+ case 'month': {
+ const newValues = fieldValues.map(v => {
+ const date = new Date(v);
+ const Y = date.getFullYear();
+ const M = date.getMonth() + 1;
+ return `${Y}-${M}`;
+ });
+ return {
+ ...data,
+ [resKey]: newValues,
+ };
+ }
+ case 'week': {
+ const newValues = fieldValues.map(v => {
+ const date = new Date(v);
+ const _Y = date.getFullYear();
+ const _firstDayOfYear = new Date(_Y, 0, 1);
+ const _SundayOfFirstWeek = new Date(
+ new Date(_firstDayOfYear).setDate(_firstDayOfYear.getDate() - _firstDayOfYear.getDay())
+ );
+ const Y = date.getTime() - _SundayOfFirstWeek.getTime() > 1_000 * 60 * 60 * 24 * 7 ? _Y : _SundayOfFirstWeek.getFullYear();
+ const firstDayOfYear = new Date(Y, 0, 1);
+ const SundayOfFirstWeek = new Date(
+ new Date(firstDayOfYear).setDate(firstDayOfYear.getDate() - firstDayOfYear.getDay())
+ );
+ const W = Math.floor((date.getTime() - SundayOfFirstWeek.getTime()) / (7 * 24 * 60 * 60 * 1_000)) + 1;
+ const SundayOfThisWeek = new Date(
+ new Date(date).setDate(date.getDate() - date.getDay())
+ );
+ const SaturdayOfThisWeek = new Date(
+ SundayOfThisWeek.getTime() + 6 * 24 * 60 * 60 * 1_000
+ );
+ const beginDay = SundayOfThisWeek.toLocaleDateString();
+ const endDay = SaturdayOfThisWeek.toLocaleDateString();
+ return `${Y} W${W < 10 ? ' ' : ''}${W} (${beginDay} ~ ${endDay})`;
+ });
+ return {
+ ...data,
+ [resKey]: newValues,
+ };
+ }
+ case 'day': {
+ const newValues = fieldValues.map(v => {
+ const date = new Date(v);
+ const Y = date.getFullYear();
+ const M = date.getMonth() + 1;
+ const D = date.getDate();
+ return `${Y}-${M}-${D}`;
+ });
+ return {
+ ...data,
+ [resKey]: newValues,
+ };
+ }
+ case 'hour': {
+ const newValues = fieldValues.map(v => {
+ const date = new Date(v);
+ const Y = date.getFullYear();
+ const M = date.getMonth() + 1;
+ const D = date.getDate();
+ const H = date.getHours();
+ return `${Y}-${M}-${D} ${H < 10 ? ' ' : ''}${H} o'clock`;
+ });
+ return {
+ ...data,
+ [resKey]: newValues,
+ };
+ }
+ case 'minute': {
+ const newValues = fieldValues.map(v => {
+ const date = new Date(v);
+ const Y = date.getFullYear();
+ const M = date.getMonth() + 1;
+ const D = date.getDate();
+ const H = date.getHours();
+ const m = date.getMinutes();
+ return `${Y}-${M}-${D} ${H < 10 ? ' ' : ''}${H}:${m < 10 ? '0' : ''}${m}`;
+ });
+ return {
+ ...data,
+ [resKey]: newValues,
+ };
+ }
+ case 'second': {
+ const newValues = fieldValues.map(v => {
+ const date = new Date(v);
+ const Y = date.getFullYear();
+ const M = date.getMonth() + 1;
+ const D = date.getDate();
+ const H = date.getHours();
+ const m = date.getMinutes();
+ const s = date.getSeconds();
+ return `${Y}-${M}-${D} ${H < 10 ? ' ' : ''}${H}:${m < 10 ? '0' : ''}${m}:${s < 10 ? '0' : ''}${s}`;
+ });
+ return {
+ ...data,
+ [resKey]: newValues,
+ };
+ }
+ default: {
+ return data;
+ }
+ }
+}
+
+
+export default dateTimeDrill;
diff --git a/packages/graphic-walker/src/locales/en-US.json b/packages/graphic-walker/src/locales/en-US.json
index d7f76aa4..eef10774 100644
--- a/packages/graphic-walker/src/locales/en-US.json
+++ b/packages/graphic-walker/src/locales/en-US.json
@@ -246,5 +246,23 @@
"drop_field": "Drop Field Here",
"confirm": "Confirm",
"cancel": "Cancel"
+ },
+ "field_menu": {
+ "to_dim": "Move to dimensions",
+ "to_mea": "Move to measures",
+ "new_calc": "New calculation",
+ "drill": {
+ "name": "Drill down / up",
+ "levels": {
+ "year": "Year",
+ "quarter": "Quarter",
+ "month": "Month",
+ "week": "Week",
+ "day": "Day",
+ "hour": "Hour",
+ "minute": "Minute",
+ "second": "Second"
+ }
+ }
}
}
\ No newline at end of file
diff --git a/packages/graphic-walker/src/locales/ja-JP.json b/packages/graphic-walker/src/locales/ja-JP.json
index 3927e029..7865f0a1 100644
--- a/packages/graphic-walker/src/locales/ja-JP.json
+++ b/packages/graphic-walker/src/locales/ja-JP.json
@@ -1,23 +1,23 @@
{
"config": {
- "format": "形式",
- "numberFormat": "数字の形式",
- "timeFormat": "時間の形式",
- "normalizedNumberFormat": "正規化された数字の形式",
+ "format": "フォーマット",
+ "numberFormat": "数字",
+ "timeFormat": "日付",
+ "normalizedNumberFormat": "正規化された数字",
"background": "背景",
"color":"色",
- "independence": "独立性",
+ "independence": "独立したスケーリング",
"x": "x軸",
"y": "y軸",
- "zeroScale": "ゼロ目盛",
+ "zeroScale": "0を含む",
"formatGuidesDocs": "フォーマットガイド",
"readHere": "ここを読む"
},
"constant": {
"row_count": "行数",
"analytic_type": {
- "dimension": "次元",
- "measure": "尺度"
+ "dimension": "ディメンション",
+ "measure": "メジャー"
},
"semantic_type": {
"nominal": "名義尺度",
@@ -38,16 +38,11 @@
"rect": "長方形",
"arc": "アーク",
"boxplot": "ボックスプロット",
- "table": "表",
- "text": "テキスト",
+ "table": "テーブル",
+ "text": "文字",
"poi": "POI",
"choropleth": "コロプレス"
},
- "coord_system": {
- "__enum__": "座標系",
- "generic": "ジェネリック",
- "geographic": "地理"
- },
"stack_mode": {
"__enum__": "スタックモード",
"none": "なし",
@@ -83,7 +78,7 @@
"theta": "角度",
"radius": "半径",
"filters": "フィルター",
- "text": "本文",
+ "text": "テキスト",
"longitude": "経度",
"latitude": "緯度",
"geoId": "地理ID"
@@ -147,9 +142,9 @@
},
"main": {
"tablist": {
- "new": "+ 新規作成",
- "auto_title": "グラフ {{idx}}",
- "chart_name": "グラフ名"
+ "new": "+ 新規ビュー",
+ "auto_title": "ビュー {{idx}}",
+ "chart_name": "ビュー名"
},
"tabpanel": {
"menubar": {
@@ -201,8 +196,8 @@
},
"filters": {
"to_edit": "このルールを編集",
- "empty_rule": "! (空のルール)",
- "editing": "フィルタールールの設定",
+ "empty_rule": "! (未設定)",
+ "editing": "フィルターの設定",
"form": {
"name": "フィールド",
"rule": "ルール"
@@ -221,8 +216,8 @@
"cancel": "キャンセル"
},
"range": {
- "start_value": "開始値",
- "end_value": "終了値"
+ "start_value": "最小",
+ "end_value": "最大"
}
},
"explain": {
@@ -245,5 +240,23 @@
"drop_field": "ここにフィールドをドロップ",
"confirm": "確認",
"cancel": "キャンセル"
+ },
+ "field_menu": {
+ "to_dim": "ディメンションに変更",
+ "to_mea": "メジャーに変更",
+ "new_calc": "計算フィールドを作成",
+ "drill": {
+ "name": "ドリルダウン/アップ",
+ "levels": {
+ "year": "年",
+ "quarter": "四半期",
+ "month": "月",
+ "week": "週",
+ "day": "日",
+ "hour": "時",
+ "minute": "分",
+ "second": "秒"
+ }
+ }
}
}
\ No newline at end of file
diff --git a/packages/graphic-walker/src/locales/zh-CN.json b/packages/graphic-walker/src/locales/zh-CN.json
index 835be0b9..24a4f8da 100644
--- a/packages/graphic-walker/src/locales/zh-CN.json
+++ b/packages/graphic-walker/src/locales/zh-CN.json
@@ -246,5 +246,23 @@
"drop_field": "拖拽字段至此",
"confirm": "确认",
"cancel": "取消"
+ },
+ "field_menu": {
+ "to_dim": "移动到维度",
+ "to_mea": "移动到度量",
+ "new_calc": "新的计算字段",
+ "drill": {
+ "name": "钻取",
+ "levels": {
+ "year": "年",
+ "quarter": "季度",
+ "month": "月",
+ "week": "周",
+ "day": "日",
+ "hour": "时",
+ "minute": "分",
+ "second": "秒"
+ }
+ }
}
}
\ No newline at end of file
diff --git a/packages/graphic-walker/src/store/visualSpecStore.ts b/packages/graphic-walker/src/store/visualSpecStore.ts
index d98e39f0..c1f3151a 100644
--- a/packages/graphic-walker/src/store/visualSpecStore.ts
+++ b/packages/graphic-walker/src/store/visualSpecStore.ts
@@ -1,4 +1,4 @@
-import { IReactionDisposer, makeAutoObservable, observable, computed, reaction, toJS } from 'mobx';
+import { IReactionDisposer, makeAutoObservable, observable, reaction, toJS } from 'mobx';
import produce from 'immer';
import { feature } from 'topojson-client';
import type { FeatureCollection } from 'geojson';
@@ -18,7 +18,8 @@ import {
IComputationFunction,
IGeoUrl,
} from '../interfaces';
-import { CHANNEL_LIMIT, GEMO_TYPES, MetaFieldKeys } from '../config';
+import { CHANNEL_LIMIT, MetaFieldKeys } from '../config';
+import { DATE_TIME_DRILL_LEVELS } from "../constants";
import { VisSpecWithHistory } from '../models/visSpecHistory';
import {
IStoInfo,
@@ -579,6 +580,40 @@ export class VizSpecStore {
encodings[stateKey].push(logField);
});
}
+ public createDateTimeDrilledField(stateKey: keyof DraggableFieldState, index: number, drillLevel: typeof DATE_TIME_DRILL_LEVELS[number], name: string | ((originFieldName: string) => string)) {
+ if (stateKey === "filters") {
+ return;
+ }
+
+ this.useMutable(({ encodings }) => {
+ const originField = encodings[stateKey][index];
+ const newVarKey = uniqueId();
+ const logField: IViewField = {
+ fid: newVarKey,
+ dragId: newVarKey,
+ name: typeof name === 'function' ? name(originField.name) : name,
+ semanticType: "ordinal",
+ analyticType: "dimension",
+ aggName: 'sum',
+ computed: true,
+ expression: {
+ op: "dateTimeDrill",
+ as: newVarKey,
+ params: [
+ {
+ type: 'field',
+ value: originField.fid,
+ },
+ {
+ type: 'value',
+ value: drillLevel,
+ },
+ ],
+ },
+ };
+ encodings[stateKey].push(logField);
+ });
+ }
public setFieldAggregator(stateKey: keyof DraggableFieldState, index: number, aggName: string) {
this.useMutable(({ encodings }) => {
const fields = encodings[stateKey];