An open source alternative to Tableau. Embeddable visual analytic
TypeScript bidatadata-analysisdata-miningdata-visualizationedak6skanarieslow-codepivot-tablereacttableautableau-alternativetypescriptvegavega-litevisualization
Feat: Add new size mode `container` (#284)
islxyqwe359a12cdbc18
diff --git a/packages/graphic-walker/package.json b/packages/graphic-walker/package.jsonindex cf346dd3..7078bfb3 100644--- a/packages/graphic-walker/package.json+++ b/packages/graphic-walker/package.json@@ -68,6 +68,7 @@"react-error-boundary": "^4.0.11","react-i18next": "^11.18.6","react-leaflet": "^4.2.1",+ "react-resize-detector": "^9.1.1","react-shadow": "^20.0.0","rxjs": "^7.3.0","tailwindcss": "^3.2.4",diff --git a/packages/graphic-walker/src/App.tsx b/packages/graphic-walker/src/App.tsxindex 7b91a93a..f0190f5c 100644--- a/packages/graphic-walker/src/App.tsx+++ b/packages/graphic-walker/src/App.tsx@@ -191,7 +191,7 @@ export const VizApp = observer(function VizApp(props: BaseVizProps) {</div><divclassName="m-0.5 p-1 border border-gray-200 dark:border-gray-700"- style={{ minHeight: '600px', overflow: 'auto' }}+ style={{ minHeight: '600px', height: 1, maxHeight: '100vh', overflow: 'auto' }}onMouseLeave={() => {vizEmbededMenu.show && vizStore.closeEmbededMenu();}}diff --git a/packages/graphic-walker/src/config.ts b/packages/graphic-walker/src/config.tsindex 3a8ecd67..73c8ae84 100644--- a/packages/graphic-walker/src/config.ts+++ b/packages/graphic-walker/src/config.ts@@ -9,7 +9,7 @@ const COORD_TYPES: ICoordMode[] = ['generic', 'geographic'];const STACK_MODE: IStackMode[] = ['none', 'stack', 'normalize', 'center'];-const CHART_LAYOUT_TYPE: ('auto' | 'fixed')[] = ['auto', 'fixed'];+const CHART_LAYOUT_TYPE: ('auto' | 'fixed' | 'full')[] = ['auto', 'fixed', 'full'];const COLORS = {// tableau stylediff --git a/packages/graphic-walker/src/interfaces.ts b/packages/graphic-walker/src/interfaces.tsindex 1f6799b6..b2ad7314 100644--- a/packages/graphic-walker/src/interfaces.ts+++ b/packages/graphic-walker/src/interfaces.ts@@ -354,7 +354,7 @@ export interface IVisualLayout {size?: boolean;};size: {- mode: 'auto' | 'fixed';+ mode: 'auto' | 'fixed' | 'full';width: number;height: number;};@@ -419,7 +419,7 @@ export interface IVegaChartRef {innerWidth: number;innerHeight: number;view: View;- canvas: HTMLCanvasElement | null;+ canvas: HTMLCanvasElement | SVGSVGElement | null;}export interface IChartExportResult<T extends 'svg' | 'data-url' = 'svg' | 'data-url'> {@@ -435,7 +435,7 @@ export interface IChartExportResult<T extends 'svg' | 'data-url' = 'svg' | 'datacanvasWidth: number;canvasHeight: number;data: string;- canvas(): HTMLCanvasElement | null;+ canvas(): HTMLCanvasElement | SVGSVGElement | null;}[];container(): HTMLDivElement | null;chartType?: string;diff --git a/packages/graphic-walker/src/lib/vega.ts b/packages/graphic-walker/src/lib/vega.tsindex 67127b38..d6a1e16f 100644--- a/packages/graphic-walker/src/lib/vega.ts+++ b/packages/graphic-walker/src/lib/vega.ts@@ -87,13 +87,18 @@ export function toVegaSpec({});}if (rowRepeatFields.length <= 1 && colRepeatFields.length <= 1) {- if (layoutMode === 'fixed') {- if (rowFacetField === NULL_FIELD && colFacetField === NULL_FIELD) {- spec.autosize = 'fit';- }- spec.width = width;- spec.height = height;+ if (layoutMode === 'auto') {+ } else if (rowFacetField === NULL_FIELD && colFacetField === NULL_FIELD) {+ spec.autosize = 'fit';+ spec.width = width - 5;+ spec.height = height - 5;+ } else {+ const rowNums = rowFacetField !== NULL_FIELD ? new Set(dataSource.map((x) => x[rowFacetField.fid])).size : 1;+ const colNums = colFacetField !== NULL_FIELD ? new Set(dataSource.map((x) => x[colFacetField.fid])).size : 1;+ spec.width = Math.floor((width - (rowFacetField === NULL_FIELD ? 40 : 94)) / colNums - 23);+ spec.height = Math.floor((height - (colFacetField === NULL_FIELD ? 24 : 94)) / rowNums - 23);}+const v = getSingleView({x: xField,y: yField,@@ -134,11 +139,18 @@ export function toVegaSpec({}return [spec];} else {- if (layoutMode === 'fixed') {+ if (layoutMode === 'auto') {+ } else if (rowFacetField === NULL_FIELD && colFacetField === NULL_FIELD) {spec.width = Math.floor(width / colRepeatFields.length) - 5;spec.height = Math.floor(height / rowRepeatFields.length) - 5;spec.autosize = 'fit';+ } else {+ const rowNums = rowFacetField !== NULL_FIELD ? new Set(dataSource.map((x) => x[rowFacetField.fid])).size : 1;+ const colNums = colFacetField !== NULL_FIELD ? new Set(dataSource.map((x) => x[colFacetField.fid])).size : 1;+ spec.width = Math.floor((width / colRepeatFields.length - (rowFacetField === NULL_FIELD ? 40 : 94)) / colNums - 23);+ spec.height = Math.floor((height / rowRepeatFields.length - (colFacetField === NULL_FIELD ? 24 : 94)) / rowNums - 23);}+let index = 0;let result = new Array(rowRepeatFields.length * colRepeatFields.length);for (let i = 0; i < rowRepeatFields.length; i++) {diff --git a/packages/graphic-walker/src/locales/en-US.json b/packages/graphic-walker/src/locales/en-US.jsonindex 824170f3..4ac6eb17 100644--- a/packages/graphic-walker/src/locales/en-US.json+++ b/packages/graphic-walker/src/locales/en-US.json@@ -73,7 +73,8 @@"layout_type": {"__enum__": "Layout Mode","auto": "Auto",- "fixed": "Fixed"+ "fixed": "Fixed",+ "full": "Container"},"exploration_mode": {"__enum__": "Exploration Mode",diff --git a/packages/graphic-walker/src/locales/ja-JP.json b/packages/graphic-walker/src/locales/ja-JP.jsonindex 9f51477f..ac54d21e 100644--- a/packages/graphic-walker/src/locales/ja-JP.json+++ b/packages/graphic-walker/src/locales/ja-JP.json@@ -68,7 +68,8 @@"layout_type": {"__enum__": "レイアウトタイプ","auto": "自動",- "fixed": "固定"+ "fixed": "固定",+ "full": "コンテナー"},"exploration_mode": {"__enum__": "探索モード",diff --git a/packages/graphic-walker/src/locales/zh-CN.json b/packages/graphic-walker/src/locales/zh-CN.jsonindex 2ce8faf1..7ca0caf4 100644--- a/packages/graphic-walker/src/locales/zh-CN.json+++ b/packages/graphic-walker/src/locales/zh-CN.json@@ -66,7 +66,8 @@"layout_type": {"__enum__": "尺寸模式","auto": "自动",- "fixed": "固定"+ "fixed": "固定",+ "full": "容器"},"exploration_mode": {"__enum__": "探索交互",diff --git a/packages/graphic-walker/src/models/visSpecHistory.ts b/packages/graphic-walker/src/models/visSpecHistory.tsindex 6b666057..3faaed07 100644--- a/packages/graphic-walker/src/models/visSpecHistory.ts+++ b/packages/graphic-walker/src/models/visSpecHistory.ts@@ -442,6 +442,7 @@ type reducerMiddleware<T> = (item: T, original: T) => T;const diffLinter: reducerMiddleware<IChart> = (item, original) => {const diffs = diffChangedEncodings(original, item);+ if (Object.keys(diffs).length === 0) return item;return mutPath(item, 'encodings', (x) => ({ ...x, ...algebraLint(diffs), ...lintExtraFields(diffs) }));};diff --git a/packages/graphic-walker/src/renderer/pureRenderer.tsx b/packages/graphic-walker/src/renderer/pureRenderer.tsxindex a3d6d83f..2664c1a0 100644--- a/packages/graphic-walker/src/renderer/pureRenderer.tsx+++ b/packages/graphic-walker/src/renderer/pureRenderer.tsx@@ -4,7 +4,18 @@ import { observer } from 'mobx-react-lite';import { ShadowDom } from '../shadow-dom';import LeafletRenderer, { LEAFLET_DEFAULT_HEIGHT } from '../components/leafletRenderer';import { withAppRoot } from '../components/appRoot';-import type { IDarkMode, IViewField, IRow, IThemeKey, DraggableFieldState, IVisualConfig, IVisualConfigNew, IComputationFunction, IVisualLayout, IChannelScales } from '../interfaces';+import type {+ IDarkMode,+ IViewField,+ IRow,+ IThemeKey,+ DraggableFieldState,+ IVisualConfig,+ IVisualConfigNew,+ IComputationFunction,+ IVisualLayout,+ IChannelScales,+} from '../interfaces';import type { IReactVegaHandler } from '../vis/react-vega';import SpecRenderer from './specRenderer';import { useRenderer } from './hooks';@@ -24,6 +35,7 @@ type IPureRendererProps =visualLayout?: IVisualLayout;locale?: string;channelScales?: IChannelScales;+ overrideSize?: IVisualLayout['size'];} & (| {type: 'remote';@@ -40,7 +52,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, className, themeKey, dark, visualState, visualConfig, visualLayout: layout, locale, type, themeConfig, channelScales } = props;+ const { name, className, themeKey, dark, visualState, visualConfig, visualLayout: layout, overrideSize, locale, type, themeConfig, channelScales } = props;const computation = useMemo(() => {if (props.type === 'remote') {return props.computation;@@ -48,7 +60,17 @@ const PureRenderer = forwardRef<IReactVegaHandler, IPureRendererProps>(functionreturn getComputation(props.rawData);}, [type, type === 'remote' ? props.computation : props.rawData]);- const visualLayout = layout ?? (visualConfig as IVisualConfig);+ const rawLayout = layout ?? (visualConfig as IVisualConfig);++ const visualLayout = useMemo(+ () => ({+ ...rawLayout,+ ...(overrideSize ? { size: overrideSize } : {}),+ }),+ [rawLayout, overrideSize]+ );++ const sizeMode = visualLayout.size.mode;const sort = getSort(visualState);const limit = visualConfig.limit ?? -1;@@ -103,8 +125,8 @@ const PureRenderer = forwardRef<IReactVegaHandler, IPureRendererProps>(functionconst isSpatial = coordSystem === 'geographic';return (- <ShadowDom className={className}>- <div className="relative">+ <ShadowDom style={sizeMode === 'full' ? {width: '100%', height: '100%'} : undefined} className={className}>+ <div className="relative" style={sizeMode === 'full' ? {width: '100%', height: '100%'} : undefined}>{isSpatial && (<div className="max-w-full" style={{ height: LEAFLET_DEFAULT_HEIGHT, flexGrow: 1 }}><LeafletRenderer data={data} draggableFieldState={visualState} visualConfig={visualConfig} visualLayout={visualLayout} />diff --git a/packages/graphic-walker/src/renderer/specRenderer.tsx b/packages/graphic-walker/src/renderer/specRenderer.tsxindex 041ba72a..966602c5 100644--- a/packages/graphic-walker/src/renderer/specRenderer.tsx+++ b/packages/graphic-walker/src/renderer/specRenderer.tsx@@ -44,7 +44,7 @@ const SpecRenderer = forwardRef<IReactVegaHandler, SpecRendererProps>(function (onGeomClick,onChartResize,locale,- onReportSpec,+ onReportSpec,themeConfig: customizedThemeConfig,channelScales,},@@ -148,7 +148,9 @@ const SpecRenderer = forwardRef<IReactVegaHandler, SpecRendererProps>(function (return (<Resizable- className={enableResize ? 'border-blue-400 border-2 overflow-hidden inline-block' : 'inline-block'}+ className={+ enableResize ? 'border-blue-400 border-2 overflow-hidden inline-block max-h-screen max-w-[100vw]' : 'inline-block max-h-screen max-w-[100vw]'+ }style={{ padding: '12px' }}onResizeStop={(e, direction, ref, d) => {onChartResize?.(size.width + d.width, size.height + d.height);@@ -179,6 +181,11 @@ const SpecRenderer = forwardRef<IReactVegaHandler, SpecRendererProps>(function (width: LEAFLET_DEFAULT_WIDTH + 'px',height: LEAFLET_DEFAULT_HEIGHT + 'px',}+ : size.mode === 'full'+ ? {+ width: '100%',+ height: '100%',+ }: { width: 'auto', height: 'auto' }}>diff --git a/packages/graphic-walker/src/vis/react-vega.tsx b/packages/graphic-walker/src/vis/react-vega.tsxindex e282d393..9fdeb8b0 100644--- a/packages/graphic-walker/src/vis/react-vega.tsx+++ b/packages/graphic-walker/src/vis/react-vega.tsx@@ -1,4 +1,4 @@-import React, { useEffect, useState, useMemo, forwardRef, useRef } from 'react';+import React, { useEffect, useState, useMemo, forwardRef, useRef, useCallback } from 'react';import embed from 'vega-embed';import { Subject, Subscription } from 'rxjs';import * as op from 'rxjs/operators';@@ -11,6 +11,7 @@ import canvasSize from 'canvas-size';import { Errors, useReporter } from '../utils/reportError';import { useCurrentMediaTheme } from '../utils/media';import { toVegaSpec } from '../lib/vega';+import { useResizeDetector } from 'react-resize-detector';const CanvaContainer = styled.div<{ rowSize: number; colSize: number }>`display: grid;@@ -18,6 +19,26 @@ const CanvaContainer = styled.div<{ rowSize: number; colSize: number }>`grid-template-rows: repeat(${(props) => props.rowSize}, 1fr);`;+function parseRect(el: HTMLCanvasElement | SVGSVGElement) {+ if (el instanceof HTMLCanvasElement) {+ return {+ width: parseInt(el.style.width),+ height: parseInt(el.style.height),+ renderWidth: el.width,+ renderHeight: el.height,+ };+ } else if (el instanceof SVGSVGElement) {+ const width = el.width.baseVal.value;+ const height = el.height.baseVal.value;+ return {+ width,+ height,+ renderWidth: 0,+ renderHeight: 0,+ };+ }+}+const SELECTION_NAME = 'geom';export interface IReactVegaHandler {getSVGData: () => Promise<string[]>;@@ -182,6 +203,44 @@ const ReactVega = forwardRef<IReactVegaHandler, ReactVegaProps>(function ReactVeconst vegaRefs = useRef<IVegaChartRef[]>([]);const renderTaskRefs = useRef<Promise<unknown>[]>([]);+ const { width: areaWidth, height: areaHeight, ref: areaRef } = useResizeDetector();++ const modifierDeps = [+ columns,+ dataSource,+ defaultAggregate,+ geomType,+ interactiveScale,+ layoutMode,+ mediaTheme,+ rows,+ stack,+ channelScales,+ color,+ details,+ opacity,+ radius,+ shape,+ size,+ text,+ theta,+ ];++ const modifierDepsRef = useRef(modifierDeps);++ const [modifierRaw, setModifier] = useState({ width: 0, height: 0 });++ let modifier: typeof modifierRaw;++ if (modifierDepsRef.current.map((x, i) => x === modifierDeps[i]).every((x) => x)) {+ modifier = modifierRaw;+ } else {+ modifier = { width: 0, height: 0 };+ }++ const vegaWidth = (areaWidth || width) - modifier.width;+ const vegaHeight = (areaHeight || height) - modifier.height;+const specs = useMemo(() =>toVegaSpec({@@ -189,13 +248,13 @@ const ReactVega = forwardRef<IReactVegaHandler, ReactVegaProps>(function ReactVedataSource,defaultAggregated: defaultAggregate,geomType,- height,+ height: vegaHeight,interactiveScale,layoutMode,mediaTheme,rows,stack,- width,+ width: vegaWidth,channelScales,color,details,@@ -212,13 +271,13 @@ const ReactVega = forwardRef<IReactVegaHandler, ReactVegaProps>(function ReactVedataSource,defaultAggregate,geomType,- height,+ vegaHeight,interactiveScale,layoutMode,mediaTheme,rows,stack,- width,+ vegaWidth,channelScales,color,details,@@ -254,8 +313,9 @@ const ReactVega = forwardRef<IReactVegaHandler, ReactVegaProps>(function ReactVeconfig: vegaConfig,}).then((res) => {const container = res.view.container();- const canvas = container?.querySelector('canvas') ?? null;- const success = useSvg || (canvas && canvasSize.test({ width: canvas.width, height: canvas.height }));+ const canvas = container?.querySelector('canvas') ?? container?.querySelector('svg') ?? null;+ const rect = canvas ? parseRect(canvas): null;+ const success = useSvg || (rect && canvasSize.test({ width: rect.renderWidth || 1, height: rect.renderHeight || 1 }));if (!success) {if (canvas) {reportGWError('canvas exceed max size', Errors.canvasExceedSize);@@ -263,6 +323,14 @@ const ReactVega = forwardRef<IReactVegaHandler, ReactVegaProps>(function ReactVereportGWError('canvas not found', Errors.canvasExceedSize);}}+ if (rect && !modifier.width && !modifier.height && specs[0].width > 0 && specs[0].height > 0) {+ const modifier = {+ width: Math.max(rect.width- (areaWidth || width), 0),+ height: Math.max(rect.height - (areaHeight || height), 0),+ };+ setModifier(modifier);+ modifierDepsRef.current = modifierDeps;+ }vegaRefs.current = [{w: container?.clientWidth ?? res.view.width(),@@ -299,6 +367,7 @@ const ReactVega = forwardRef<IReactVegaHandler, ReactVegaProps>(function ReactVeconst subscribe = (cb: (entry: ParamStoreEntry) => void) => {subscriptions.push(throttledParamStore$.subscribe(cb));};+ const newModifier = { width: 0, height: 0 };for (let i = 0; i < rowRepeatFields.length; i++) {for (let j = 0; j < colRepeatFields.length; j++, index++) {@@ -315,8 +384,9 @@ const ReactVega = forwardRef<IReactVegaHandler, ReactVegaProps>(function ReactVeconfig: vegaConfig,}).then((res) => {const container = res.view.container();- const canvas = container?.querySelector('canvas') ?? null;- const success = useSvg || (canvas && canvasSize.test({ width: canvas.width, height: canvas.height }));+ const canvas = container?.querySelector('canvas') ?? container?.querySelector('svg') ?? null;+ const rect = canvas ? parseRect(canvas): null;+ const success = useSvg || (rect && canvasSize.test({ width: rect.renderWidth || 1, height: rect.renderHeight || 1 }));if (!success) {if (canvas) {reportGWError('canvas exceed max size', Errors.canvasExceedSize);@@ -324,6 +394,16 @@ const ReactVega = forwardRef<IReactVegaHandler, ReactVegaProps>(function ReactVereportGWError('canvas not found', Errors.canvasExceedSize);}}+ if (rect && !modifier.width && !modifier.height) {+ const modifier = {+ width: Math.max(rect.width - (areaWidth || width) / colRepeatFields.length, 0),+ height: Math.max(rect.height - (areaHeight || height) / rowRepeatFields.length, 0),+ };+ newModifier.width = Math.max(newModifier.width, modifier.width);+ newModifier.height = Math.max(newModifier.height, modifier.height);+ setModifier(newModifier);+ modifierDepsRef.current = modifierDeps;+ }vegaRefs.current[id] = {w: container?.clientWidth ?? res.view.width(),h: container?.clientHeight ?? res.view.height(),@@ -410,12 +490,20 @@ const ReactVega = forwardRef<IReactVegaHandler, ReactVegaProps>(function ReactVeuseVegaExportApi(name, vegaRefs, ref, renderTaskRefs, containerRef);return (- <CanvaContainer rowSize={Math.max(rowRepeatFields.length, 1)} colSize={Math.max(colRepeatFields.length, 1)} ref={containerRef}>- {/* <div ref={container}></div> */}- {viewPlaceholders.map((view, i) => (- <div key={i} ref={view}></div>- ))}- </CanvaContainer>+ <div className="w-full h-full relative" style={{ overflow: layoutMode === 'auto' ? 'visible' : 'hidden' }}>+ <div ref={areaRef} className="inset-0 absolute" />+ <CanvaContainer+ style={layoutMode === 'full' ? { width: '100%', height: '100%' } : {}}+ rowSize={Math.max(rowRepeatFields.length, 1)}+ colSize={Math.max(colRepeatFields.length, 1)}+ ref={containerRef}+ >+ {/* <div ref={container}></div> */}+ {viewPlaceholders.map((view, i) => (+ <div key={i} ref={view}></div>+ ))}+ </CanvaContainer>+ </div>);});diff --git a/yarn.lock b/yarn.lockindex 2f434c1a..f8fa5da5 100644--- a/yarn.lock+++ b/yarn.lock@@ -1339,7 +1339,7 @@"@types/react" "*""@types/reactcss" "*"-"@types/react-dom@*", "@types/react-dom@^18.2.15":+"@types/react-dom@*", "@types/react-dom@^18.2.15", "@types/react-dom@^18.x":version "18.2.18"resolved "https://registry.npmmirror.com/@types/react-dom/-/react-dom-18.2.18.tgz#16946e6cd43971256d874bc3d0a72074bb8571dd"integrity sha512-TJxDm6OfAX2KJWJdMEVTwWke5Sc/E/RlnPGvGfS0W7+6ocy2xhDVQVh/KvC2Uf7kACs+gDytdusDSdWfWkaNzw==@@ -1353,10 +1353,10 @@dependencies:"@types/react" "*"-"@types/react@*", "@types/react@^18.2.37":- version "18.2.45"- resolved "https://registry.npmmirror.com/@types/react/-/react-18.2.45.tgz#253f4fac288e7e751ab3dc542000fb687422c15c"- integrity sha512-TtAxCNrlrBp8GoeEp1npd5g+d/OejJHFxS3OWmrPBMFaVQMSN0OFySozJio5BHxTuTeug00AVXVAjfDSfk+lUg==+"@types/react@*", "@types/react@^18.2.37", "@types/react@^18.x":+ version "18.2.46"+ resolved "https://registry.npmmirror.com/@types/react/-/react-18.2.46.tgz#f04d6c528f8f136ea66333bc66abcae46e2680df"+ integrity sha512-nNCvVBcZlvX4NU1nRRNV/mFl1nNRuTuslAJglQsq+8ldXe5Xv0Wd2f7WTE3jOxhLH2BFfiZGC6GCp+kHQbgG+w==dependencies:"@types/prop-types" "*""@types/scheduler" "*"@@ -4057,6 +4057,13 @@ react-refresh@^0.14.0:resolved "https://registry.npmjs.org/react-refresh/-/react-refresh-0.14.0.tgz#4e02825378a5f227079554d4284889354e5f553e"integrity sha512-wViHqhAd8OHeLS/IRMJjTSDHF3U9eWi62F/MledQGPdJGDhodXJ9PBLNGr6WWL7qlH12Mt3TyTpbS+hGXMjCzQ==+react-resize-detector@^9.1.1:+ version "9.1.1"+ resolved "https://registry.npmmirror.com/react-resize-detector/-/react-resize-detector-9.1.1.tgz#ce13cf55b9b09d9978fc51e0c87bb3639704921e"+ integrity sha512-siLzop7i4xIvZIACE/PHTvRegA8QRCEt0TfmvJ/qCIFQJ4U+3NuYcF8tNDmDWxfIn+X1eNCyY2rauH4KRxge8w==+ dependencies:+ lodash "^4.17.21"+react-router-dom@^6.20.0:version "6.20.0"resolved "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.20.0.tgz#7b9527a1e29c7fb90736a5f89d54ca01f40e264b"