An open source alternative to Tableau. Embeddable visual analytic
TypeScript bidatadata-analysisdata-miningdata-visualizationedak6skanarieslow-codepivot-tablereacttableautableau-alternativetypescriptvegavega-litevisualization
feat: custom color palette
islxyqwe1870ed1d995e
diff --git a/packages/graphic-walker/src/App.tsx b/packages/graphic-walker/src/App.tsxindex 83f4d10b..0fa147fa 100644--- a/packages/graphic-walker/src/App.tsx+++ b/packages/graphic-walker/src/App.tsx@@ -1,7 +1,7 @@import React, { useEffect, useRef, useMemo, useState, useCallback } from 'react';import { observer } from 'mobx-react-lite';import { useTranslation } from 'react-i18next';-import { IGeographicData, IComputationFunction, IDarkMode, IMutField, IRow, ISegmentKey, IThemeKey, Specification, IGeoDataItem } from './interfaces';+import { IGeographicData, IComputationFunction, IDarkMode, IMutField, IRow, ISegmentKey, IThemeKey, Specification, IGeoDataItem, VegaGlobalConfig, IChannelScales } from './interfaces';import type { IReactVegaHandler } from './vis/react-vega';import VisualSettings from './visualSettings';import PosFields from './fields/posFields';@@ -48,7 +48,7 @@ export interface IGWProps {fieldKeyGuard?: boolean;/** @default "vega" */themeKey?: IThemeKey;- themeConfig?: any;+ themeConfig?: VegaGlobalConfig;dark?: IDarkMode;storeRef?: React.MutableRefObject<IGlobalStore | null>;computation?: IComputationFunction;@@ -68,6 +68,7 @@ export interface IGWProps {computationTimeout?: number;onError?: (err: Error) => void;geoList?: IGeoDataItem[];+ channelScales?: IChannelScales;}const App = observer<IGWProps>(function App(props) {@@ -238,7 +239,7 @@ const App = observer<IGWProps>(function App(props) {}}>{datasets.length > 0 && (- <ReactiveRenderer ref={rendererRef} themeKey={themeKey} themeConfig={themeConfig} dark={dark} computationFunction={vizStore.computationFunction} />+ <ReactiveRenderer ref={rendererRef} themeKey={themeKey} themeConfig={themeConfig} dark={dark} computationFunction={vizStore.computationFunction} channelScales={props.channelScales} />)}{vizEmbededMenu.show && (<ClickMenu x={vizEmbededMenu.position[0]} y={vizEmbededMenu.position[1]}>diff --git a/packages/graphic-walker/src/interfaces.ts b/packages/graphic-walker/src/interfaces.tsindex 2d2254d9..15812bac 100644--- a/packages/graphic-walker/src/interfaces.ts+++ b/packages/graphic-walker/src/interfaces.ts@@ -502,3 +502,138 @@ export type IGeoDataItem = {name: string;url: string;};++function toDict<T extends string>(a: readonly T[]) {+ return Object.fromEntries(a.map((x) => [x, x])) as {+ [k in T]: k;+ };+}++export const ColorSchemes = {+ /**+ * @name Categorical Schemes+ * @summary For nominal data.+ * @description Categorical color schemes can be used to encode discrete data values, each representing a distinct category.+ */+ discrete: toDict([+ 'accent',+ 'category10',+ 'category20',+ 'category20b',+ 'category20c',+ 'dark2',+ 'paired',+ 'pastel1',+ 'pastel2',+ 'set1',+ 'set2',+ 'set3',+ 'tableau10',+ 'tableau20',+ ] as const),+ /**+ * @name Sequential Single-Hue Schemes+ * @summary For increasing quantitative data.+ * @description Sequential color schemes can be used to encode quantitative values. These color ramps are designed to encode increasing numeric values.+ */+ single: toDict(['blues', 'tealblues', 'teals', 'greens', 'browns', 'oranges', 'reds', 'purples', 'warmgreys', 'greys'] as const),+ /**+ * @name Sequential Multi-Hue Schemes+ * @summary For quantitative data in heatmaps.+ * @description Sequential color schemes can be used to encode quantitative values. These color ramps are designed to encode increasing numeric values, but use additional hues for more color discrimination, which may be useful for visualizations such as heatmaps. However, beware that using multiple hues may cause viewers to inaccurately see the data range as grouped into color-coded clusters.+ */+ multi: toDict([+ 'viridis',+ 'magma',+ 'inferno',+ 'plasma',+ 'cividis',+ 'turbo',+ 'bluegreen',+ 'bluepurple',+ 'goldgreen',+ 'goldorange',+ 'goldred',+ 'greenblue',+ 'orangered',+ 'purplebluegreen',+ 'purpleblue',+ 'purplered',+ 'redpurple',+ 'yellowgreenblue',+ 'yellowgreen',+ 'yelloworangebrown',+ 'yelloworangered',+ 'darkblue',+ 'darkgold',+ 'darkgreen',+ 'darkmulti',+ 'darkred',+ 'lightgreyred',+ 'lightgreyteal',+ 'lightmulti',+ 'lightorange',+ 'lighttealblue',+ ] as const),+ /**+ * @name Diverging Schemes+ * @summary For quantitative data with meaningful mid-point.+ * @description Diverging color schemes can be used to encode quantitative values with a meaningful mid-point, such as zero or the average value. Color ramps with different hues diverge with increasing saturation to highlight the values below and above the mid-point.+ */+ deiverging: toDict([+ 'blueorange',+ 'brownbluegreen',+ 'purplegreen',+ 'pinkyellowgreen',+ 'purpleorange',+ 'redblue',+ 'redgrey',+ 'redyellowblue',+ 'redyellowgreen',+ 'spectral',+ ] as const),+ /**+ * @name Cyclical Schemes+ * @summary For quantitative data with periodic patterns.+ * @description Cyclical color schemes may be used to highlight periodic patterns in continuous data. However, these schemes are not well suited to accurately convey value differences.+ */+ cyclical: toDict(['rainbow', 'sinebow'] as const),+};++export type IPreDefinedColorSchemes =+ | keyof (typeof ColorSchemes)['discrete']+ | keyof (typeof ColorSchemes)['single']+ | keyof (typeof ColorSchemes)['multi']+ | keyof (typeof ColorSchemes)['deiverging']+ | keyof (typeof ColorSchemes)['cyclical'];++export type IColorSchemes =+ | IPreDefinedColorSchemes+ | {+ name: IPreDefinedColorSchemes;+ extent?: [number, number];+ count?: number;+ };++export type IScale = {+ domain?: [number, number] | string[],+ domainMin?: number,+ domainMax?: number,+ range?: [number, number] | string[],+ rangeMin?: number,+ rangeMax?: number,+}++export type IColorScale = IScale & { scheme?: IColorSchemes }++export type IFieldInfos = {+ semanticType: ISemanticType,+ theme: 'dark' | 'light',+ values: any[],+}++export interface IChannelScales {+ color?: IColorScale | ((info: IFieldInfos) => IColorScale);+ opacity?: IScale | ((info: IFieldInfos) => IScale);+ size?: IScale | ((info: IFieldInfos) => IScale);+}diff --git a/packages/graphic-walker/src/main.tsx b/packages/graphic-walker/src/main.tsxindex 16bfb91f..44e5a40c 100644--- a/packages/graphic-walker/src/main.tsx+++ b/packages/graphic-walker/src/main.tsx@@ -14,4 +14,9 @@ embedGraphicWalker(document.getElementById('root') as HTMLElement, {url: 'https://raw.githubusercontent.com/drei01/geojson-world-cities/f2a988af4bc15463df55586afbbffbd3068b7218/cities.geojson',},],+ channelScales: {+ color: {+ scheme: 'bluegreen'+ }+ }});diff --git a/packages/graphic-walker/src/renderer/index.tsx b/packages/graphic-walker/src/renderer/index.tsxindex 40ebf5c2..ee2a4476 100644--- a/packages/graphic-walker/src/renderer/index.tsx+++ b/packages/graphic-walker/src/renderer/index.tsx@@ -1,6 +1,6 @@import { observer } from 'mobx-react-lite';import React, { useState, useEffect, forwardRef, useRef, useCallback } from 'react';-import { DeepReadonly, DraggableFieldState, IDarkMode, IRow, IThemeKey, IVisualConfig, IComputationFunction } from '../interfaces';+import { DeepReadonly, DraggableFieldState, IDarkMode, IRow, IThemeKey, IVisualConfig, IComputationFunction, IChannelScales } from '../interfaces';import { useTranslation } from 'react-i18next';import SpecRenderer from './specRenderer';import { runInAction, toJS } from 'mobx';@@ -18,6 +18,7 @@ interface RendererProps {themeConfig?: any;dark?: IDarkMode;computationFunction: IComputationFunction;+ channelScales?: IChannelScales;}/*** Renderer of GraphicWalker editor.@@ -142,6 +143,7 @@ const Renderer = forwardRef<IReactVegaHandler, RendererProps>(function (props, ronGeomClick={handleGeomClick}onChartResize={handleChartResize}computationFunction={computationFunction}+ channelScales={props.channelScales}/>);});diff --git a/packages/graphic-walker/src/renderer/pureRenderer.tsx b/packages/graphic-walker/src/renderer/pureRenderer.tsxindex 75680ab5..131eb14e 100644--- a/packages/graphic-walker/src/renderer/pureRenderer.tsx+++ b/packages/graphic-walker/src/renderer/pureRenderer.tsx@@ -5,7 +5,7 @@ import { observer } from 'mobx-react-lite';import { ShadowDom } from '../shadow-dom';import LeafletRenderer, { LEAFLET_DEFAULT_HEIGHT, LEAFLET_DEFAULT_WIDTH } from '../components/leafletRenderer';import { withAppRoot } from '../components/appRoot';-import type { IDarkMode, IViewField, IRow, IThemeKey, DraggableFieldState, IVisualConfig, IComputationFunction } from '../interfaces';+import type { IDarkMode, IViewField, IRow, IThemeKey, DraggableFieldState, IVisualConfig, IComputationFunction, IChannelScales } from '../interfaces';import type { IReactVegaHandler } from '../vis/react-vega';import SpecRenderer from './specRenderer';import { useRenderer } from './hooks';@@ -22,6 +22,7 @@ type IPureRendererProps =sort?: 'none' | 'ascending' | 'descending';limit?: number;locale?: string;+ channelScales?: IChannelScales;} & (| {type: 'remote';@@ -38,7 +39,7 @@ type IPureRendererProps =* This is a pure component, which means it will not depend on any global state.*/const PureRenderer = forwardRef<IReactVegaHandler, IPureRendererProps>(function PureRenderer(props, ref) {- const { name, themeKey, dark, visualState, visualConfig, type, locale, sort, limit, themeConfig } = props;+ const { name, themeKey, dark, visualState, visualConfig, type, locale, sort, limit, themeConfig, channelScales } = props;const computation = useMemo(() => {if (props.type === 'remote') {return props.computation;@@ -115,6 +116,7 @@ const PureRenderer = forwardRef<IReactVegaHandler, IPureRendererProps>(functionvisualConfig={visualConfig}locale={locale ?? 'en-US'}computationFunction={computation}+ channelScales={channelScales}/>)}</div>diff --git a/packages/graphic-walker/src/renderer/specRenderer.tsx b/packages/graphic-walker/src/renderer/specRenderer.tsxindex c51f8975..89741ba8 100644--- a/packages/graphic-walker/src/renderer/specRenderer.tsx+++ b/packages/graphic-walker/src/renderer/specRenderer.tsx@@ -5,7 +5,7 @@ import React, { forwardRef, useMemo } from 'react';import PivotTable from '../components/pivotTable';import LeafletRenderer from '../components/leafletRenderer';import ReactVega, { IReactVegaHandler } from '../vis/react-vega';-import { DeepReadonly, DraggableFieldState, IDarkMode, IRow, IThemeKey, IVisualConfig, VegaGlobalConfig, IComputationFunction } from '../interfaces';+import { DeepReadonly, DraggableFieldState, IDarkMode, IRow, IThemeKey, IVisualConfig, VegaGlobalConfig, IComputationFunction, IChannelScales } from '../interfaces';import LoadingLayer from '../components/loadingLayer';import { useCurrentMediaTheme } from '../utils/media';import { builtInThemes } from '../vis/theme';@@ -23,14 +23,15 @@ interface SpecRendererProps {onChartResize?: ((width: number, height: number) => void) | undefined;locale?: string;computationFunction: IComputationFunction;- themeConfig?: any;+ themeConfig?: VegaGlobalConfig;+ channelScales?: IChannelScales;}/*** Sans-store renderer of GraphicWalker.* This is a pure component, which means it will not depend on any global state.*/const SpecRenderer = forwardRef<IReactVegaHandler, SpecRendererProps>(function (- { name, themeKey, dark, data, loading, draggableFieldState, visualConfig, onGeomClick, onChartResize, locale, computationFunction, themeConfig: customizedThemeConfig },+ { name, themeKey, dark, data, loading, draggableFieldState, visualConfig, onGeomClick, onChartResize, locale, computationFunction, themeConfig: customizedThemeConfig, channelScales },ref) {// const { draggableFieldState, visualConfig } = vizStore;@@ -144,10 +145,10 @@ const SpecRenderer = forwardRef<IReactVegaHandler, SpecRendererProps>(function (topLeft: false,}}- size={{+ size={(size.mode === 'fixed' || isSpatial) ? {width: size.width + 'px',height: size.height + 'px',- }}+ }: undefined}>{loading && <LoadingLayer />}{isSpatial && (@@ -187,6 +188,8 @@ const SpecRenderer = forwardRef<IReactVegaHandler, SpecRendererProps>(function (onGeomClick={onGeomClick}locale={locale}useSvg={useSvg}+ channelScales={channelScales}+ dark={dark}/>)}</Resizable>diff --git a/packages/graphic-walker/src/vis/react-vega.tsx b/packages/graphic-walker/src/vis/react-vega.tsxindex 1a5ca197..5828ee14 100644--- a/packages/graphic-walker/src/vis/react-vega.tsx+++ b/packages/graphic-walker/src/vis/react-vega.tsx@@ -6,12 +6,13 @@ import type { ScenegraphEvent } from 'vega';import styled from 'styled-components';import { NonPositionChannelConfigList, PositionChannelConfigList } from '../config';import { useVegaExportApi } from '../utils/vegaApiExport';-import { IViewField, IRow, IStackMode, VegaGlobalConfig, IVegaChartRef } from '../interfaces';+import { IViewField, IRow, IStackMode, VegaGlobalConfig, IVegaChartRef, IChannelScales, IDarkMode } from '../interfaces';import { getVegaTimeFormatRules } from './temporalFormat';-import { getSingleView } from './spec/view';+import { getSingleView, resolveScales } from './spec/view';import { NULL_FIELD } from './spec/field';import canvasSize from 'canvas-size';import { Errors, useReporter } from '../utils/reportError';+import { useCurrentMediaTheme } from '../utils/media';const CanvaContainer = styled.div<{rowSize: number; colSize: number;}>`display: grid;@@ -52,6 +53,8 @@ interface ReactVegaProps {/** @default "en-US" */locale?: string;useSvg?: boolean;+ dark?: IDarkMode;+ channelScales?: IChannelScales;}const click$ = new Subject<ScenegraphEvent>();@@ -101,14 +104,15 @@ const ReactVega = forwardRef<IReactVegaHandler, ReactVegaProps>(function ReactVeheight,details = [],// themeKey = 'vega',- // dark = 'media',+ dark = 'media',vegaConfig,// formatlocale = 'en-US',- useSvg+ useSvg,+ channelScales,} = props;const [viewPlaceholders, setViewPlaceholders] = useState<React.MutableRefObject<HTMLDivElement>[]>([]);- // const mediaTheme = useCurrentMediaTheme(dark);+ const mediaTheme = useCurrentMediaTheme(dark);// const themeConfig = builtInThemes[themeKey]?.[mediaTheme];// const vegaConfig = useMemo(() => {@@ -203,7 +207,7 @@ const ReactVega = forwardRef<IReactVegaHandler, ReactVegaProps>(function ReactVespec.width = width;spec.height = height;}- const singleView = getSingleView({+ const v = getSingleView({x: xField,y: yField,color: color ? color : NULL_FIELD,@@ -222,6 +226,7 @@ const ReactVega = forwardRef<IReactVegaHandler, ReactVegaProps>(function ReactVestack,geomType,});+ const singleView = channelScales ? resolveScales(channelScales, v, dataSource, mediaTheme) : v;spec.mark = singleView.mark;if ('encoding' in singleView) {@@ -301,7 +306,7 @@ const ReactVega = forwardRef<IReactVegaHandler, ReactVegaProps>(function ReactVefor (let j = 0; j < colRepeatFields.length; j++, index++) {const sourceId = index;const hasLegend = i === 0 && j === colRepeatFields.length - 1;- const singleView = getSingleView({+ const v = getSingleView({x: colRepeatFields[j] || NULL_FIELD,y: rowRepeatFields[i] || NULL_FIELD,color: color ? color : NULL_FIELD,@@ -321,6 +326,7 @@ const ReactVega = forwardRef<IReactVegaHandler, ReactVegaProps>(function ReactVegeomType,hideLegend: !hasLegend,});+ const singleView = channelScales ? resolveScales(channelScales, v, dataSource, mediaTheme) : v;const node = i * colRepeatFields.length + j < viewPlaceholders.length ? viewPlaceholders[i * colRepeatFields.length + j].current : nulllet commonSpec = { ...spec };@@ -444,7 +450,9 @@ const ReactVega = forwardRef<IReactVegaHandler, ReactVegaProps>(function ReactVevegaConfig,details,text,- useSvg+ useSvg,+ channelScales,+ mediaTheme]);const containerRef = useRef<HTMLDivElement>(null);diff --git a/packages/graphic-walker/src/vis/spec/view.ts b/packages/graphic-walker/src/vis/spec/view.tsindex 770cd8e2..2f496c48 100644--- a/packages/graphic-walker/src/vis/spec/view.ts+++ b/packages/graphic-walker/src/vis/spec/view.ts@@ -1,4 +1,4 @@-import { ISemanticType, IStackMode, IViewField } from '../../interfaces';+import { IChannelScales, ISemanticType, IStackMode, IViewField } from '../../interfaces';import { autoMark } from './mark';import { NULL_FIELD } from './field';import { channelAggregate } from './aggregate';@@ -80,3 +80,31 @@ export function getSingleView(props: SingleViewProps) {encoding,};}++export function resolveScales(scale: IChannelScales, view: any, data: readonly any[], theme: 'dark' | 'light') {+ const newEncoding = {...view.encoding};+ function addScale(c: string) {+ if (scale[c] && newEncoding[c]) {+ if (typeof scale[c] === 'function') {+ const field = newEncoding[c].field;+ const values = data.map(x => x[field]);+ newEncoding[c].scale = scale[c]({+ semanticType: newEncoding[c].type,+ theme,+ values,+ })+ } else {+ newEncoding[c].scale = scale[c];+ }++ }+ }+ addScale('color');+ addScale('opacity');+ addScale('size');+ console.log(newEncoding)+ return {+ ...view,+ encoding: newEncoding+ };+}\ No newline at end of file