An open source alternative to Tableau. Embeddable visual analytic
TypeScript bidatadata-analysisdata-miningdata-visualizationedak6skanarieslow-codepivot-tablereacttableautableau-alternativetypescriptvegavega-litevisualization
feat: add json data source support
ObservedObservere516b9f4a31d
diff --git a/packages/graphic-walker/package.json b/packages/graphic-walker/package.jsonindex 74e7d1e3..8c04857c 100644--- a/packages/graphic-walker/package.json+++ b/packages/graphic-walker/package.json@@ -35,7 +35,7 @@"@headlessui/react": "^1.7.12","@heroicons/react": "^2.0.8","@kanaries/react-beautiful-dnd": "0.0.1",- "@kanaries/web-data-loader": "0.1.5",+ "@kanaries/web-data-loader": "^0.1.7","autoprefixer": "^10.3.5","i18next": "^21.9.1","i18next-browser-languagedetector": "^6.1.5",diff --git a/packages/graphic-walker/src/components/dataTable/index.tsx b/packages/graphic-walker/src/components/dataTable/index.tsxindex 05e1a39e..28239c10 100644--- a/packages/graphic-walker/src/components/dataTable/index.tsx+++ b/packages/graphic-walker/src/components/dataTable/index.tsx@@ -153,7 +153,7 @@ const DataTable: React.FC<DataTableProps> = (props) => {</tr></thead><tbody className="divide-y divide-gray-100 dark:divide-gray-600 bg-white dark:bg-zinc-900">- {data.slice(from, to).map((row, index) => (+ {data.slice(from, to + 1).map((row, index) => (<tr className={"divide-x divide-gray-200 dark:divide-gray-600 " + (index % 2 ? "bg-gray-50 dark:bg-gray-800" : "")} key={index}>{metas.map((field) => (<td@@ -163,7 +163,7 @@ const DataTable: React.FC<DataTableProps> = (props) => {" whitespace-nowrap py-2 pl-4 pr-3 text-xs text-gray-500 dark:text-gray-300 sm:pl-6"}>- {row[field.fid]}+ {`${row[field.fid]}`}</td>))}</tr>diff --git a/packages/graphic-walker/src/dataSource/dataSelection/config.ts b/packages/graphic-walker/src/dataSource/dataSelection/config.tsindex 55378afd..7dc1a154 100644--- a/packages/graphic-walker/src/dataSource/dataSelection/config.ts+++ b/packages/graphic-walker/src/dataSource/dataSelection/config.ts@@ -25,4 +25,15 @@ export const charsetOptions: IDropdownSelectOption[] = [label: 'GB18030',value: 'GB18030',},+]++export const SUPPORTED_FILE_TYPES: IDropdownSelectOption[] = [+ {+ label: 'CSV',+ value: 'csv',+ },+ {+ label: 'JSON',+ value: 'json',+ }]\ No newline at end of filediff --git a/packages/graphic-walker/src/dataSource/dataSelection/csvData.tsx b/packages/graphic-walker/src/dataSource/dataSelection/csvData.tsxindex 07797d3f..02b5f3d7 100644--- a/packages/graphic-walker/src/dataSource/dataSelection/csvData.tsx+++ b/packages/graphic-walker/src/dataSource/dataSelection/csvData.tsx@@ -9,7 +9,10 @@ import { useTranslation } from "react-i18next";import DefaultButton from "../../components/button/default";import PrimaryButton from "../../components/button/primary";import DropdownSelect from "../../components/dropdownSelect";-import { charsetOptions } from "./config";+import { SUPPORTED_FILE_TYPES, charsetOptions } from "./config";+import { classNames } from "../../utils";+import { RadioGroup } from "@headlessui/react";+import { jsonReader } from "./utils";const Container = styled.div`overflow-x: auto;@@ -22,6 +25,7 @@ const CSVData: React.FC<ICSVData> = (props) => {const { commonStore } = useGlobalStore();const { tmpDSName, tmpDataSource, tmpDSRawFields } = commonStore;const [encoding, setEncoding] = useState<string>("utf-8");+ const [fileType, setFileType] = useState<string>("csv");const onSubmitData = useCallback(() => {commonStore.commitTempDS();@@ -30,6 +34,27 @@ const CSVData: React.FC<ICSVData> = (props) => {const { t } = useTranslation("translation", { keyPrefix: "DataSource.dialog.file" });const fileLoaded = tmpDataSource.length > 0 && tmpDSRawFields.length > 0;+ const fileUpload = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {+ const files = e.target.files;+ if (files !== null) {+ const file = files[0];+ if (fileType === 'csv') {+ FileReader.csvReader({+ file,+ config: { type: "reservoirSampling", size: Infinity },+ onLoading: () => {},+ encoding,+ }).then((data) => {+ commonStore.updateTempDS(data as IRow[]);+ });+ } else {+ jsonReader(file).then((data) => {+ commonStore.updateTempDS(data as IRow[]);+ });+ }+ }+ }, [fileType, encoding]);+return (<Container>{!fileLoaded && (@@ -49,49 +74,56 @@ const CSVData: React.FC<ICSVData> = (props) => {d="M9 13h6m-3-3v6m-9 1V7a2 2 0 012-2h6l2 2h6a2 2 0 012 2v8a2 2 0 01-2 2H5a2 2 0 01-2-2z"/></svg>- <h3 className="mt-2 text-sm font-semibold text-gray-900">{t('choose_file')}</h3>- <p className="mt-1 text-sm text-gray-500">{t('get_start_desc')}</p>+ <h3 className="mt-2 text-sm font-semibold text-gray-900">{t("choose_file")}</h3>+ <p className="mt-1 text-sm text-gray-500">{t("get_start_desc")}</p></div>)}- <input- style={{ display: "none" }}- type="file"- ref={fileRef}- onChange={(e) => {- const files = e.target.files;- if (files !== null) {- const file = files[0];- FileReader.csvReader({- file,- config: { type: "reservoirSampling", size: Infinity },- onLoading: () => {},- encoding,- }).then((data) => {- commonStore.updateTempDS(data as IRow[]);- });- }- }}- />+ <input style={{ display: "none" }} type="file" ref={fileRef} onChange={fileUpload} />{!fileLoaded && (- <div className="my-1 flex justify-center">- <DefaultButton- className="mr-2"- onClick={() => {- if (fileRef.current) {- fileRef.current.click();- }- }}- text={t("open")}- />- <div className="inline-block relative">- <DropdownSelect- buttonClassName="w-36"- options={charsetOptions}- selectedKey={encoding}- onSelect={(k) => {- setEncoding(k);+ <div className="my-1">+ <div className="flex justify-center">+ <RadioGroup value={fileType} onChange={setFileType} className="mt-2">+ <RadioGroup.Label className="sr-only"> Choose a memory option </RadioGroup.Label>+ <div className="grid grid-cols-2 gap-3">+ {SUPPORTED_FILE_TYPES.map((option) => (+ <RadioGroup.Option+ key={option.value}+ value={option.value}+ className={({ active, checked }) =>+ classNames(+ checked+ ? "bg-indigo-600 text-white hover:bg-indigo-500"+ : "ring-1 ring-inset ring-gray-300 bg-white text-gray-900 hover:bg-gray-50",+ "flex cursor-pointer items-center justify-center rounded py-1 px-8 text-sm font-semibold uppercase sm:flex-1"+ )+ }+ >+ <RadioGroup.Label as="span">{option.label}</RadioGroup.Label>+ </RadioGroup.Option>+ ))}+ </div>+ </RadioGroup>+ </div>+ <div className="my-1 flex justify-center">+ <DefaultButton+ className="mr-2"+ onClick={() => {+ if (fileRef.current) {+ fileRef.current.click();+ }}}+ text={t("open")}/>+ <div className="inline-block relative">+ <DropdownSelect+ buttonClassName="w-36"+ options={charsetOptions}+ selectedKey={encoding}+ onSelect={(k) => {+ setEncoding(k);+ }}+ />+ </div></div></div>)}diff --git a/packages/graphic-walker/src/dataSource/dataSelection/gwFile.tsx b/packages/graphic-walker/src/dataSource/dataSelection/gwFile.tsxindex 328a4969..8c06167a 100644--- a/packages/graphic-walker/src/dataSource/dataSelection/gwFile.tsx+++ b/packages/graphic-walker/src/dataSource/dataSelection/gwFile.tsx@@ -1,4 +1,4 @@-import React, { useRef, useCallback } from "react";+import React from "react";import { useGlobalStore } from "../../store";import { observer } from "mobx-react-lite";@@ -7,7 +7,7 @@ interface GWFileProps {fileRef: React.RefObject<HTMLInputElement>;}const GWFile: React.FC<GWFileProps> = (props) => {- const { commonStore, vizStore } = useGlobalStore();+ const { vizStore } = useGlobalStore();return (<inputdiff --git a/packages/graphic-walker/src/dataSource/dataSelection/utils.ts b/packages/graphic-walker/src/dataSource/dataSelection/utils.tsnew file mode 100644index 00000000..ba32eec8--- /dev/null+++ b/packages/graphic-walker/src/dataSource/dataSelection/utils.ts@@ -0,0 +1,28 @@+import { IDataSetInfo, IRow } from "../../interfaces";++export function jsonReader (file: File): Promise<IRow[]> {+ return new Promise((resolve, reject) => {+ const reader = new FileReader();+ reader.onload = () => {+ try {+ const data = JSON.parse(reader.result as string);+ if (!Array.isArray(data)) {+ throw new Error('Invalid JSON file');+ }+ resolve(data);+ } catch (e) {+ reject(e);+ }+ };+ reader.readAsText(file);+ });+}++// export function jsonArray2DatasetInfo (data: IRow[]): IDataSetInfo {+// const fields = Object.keys(data[0]);+// return {+// name: 'New Dataset',+// rawFields: fields.map(f => ({ name: f, type: 'number' })),+// dataSource: data+// }+// }\ No newline at end of filediff --git a/packages/graphic-walker/src/dataSource/pannel.tsx b/packages/graphic-walker/src/dataSource/pannel.tsxdeleted file mode 100644index 0f35501e..00000000--- a/packages/graphic-walker/src/dataSource/pannel.tsx+++ /dev/null@@ -1,71 +0,0 @@-import React, { useRef, useCallback } from 'react';-import { FileReader } from '@kanaries/web-data-loader';-import { IRow } from '../interfaces';-import Table from './table';-import styled from 'styled-components';-import { useGlobalStore } from '../store';-import { observer } from 'mobx-react-lite';--const Container = styled.div`- overflow-x: auto;-`;--interface DSPanelProps {-}-const DataSourcePanel: React.FC<DSPanelProps> = props => {- const fileRef = useRef<HTMLInputElement>(null);- const { commonStore } = useGlobalStore();- const { tmpDSName, tmpDataSource } = commonStore;-- const onSubmitData = useCallback(() => {- commonStore.commitTempDS();- }, [])- return (- <Container>- <input- style={{ display: 'none' }}- type="file"- ref={fileRef}- onChange={(e) => {- const files = e.target.files;- if (files !== null) {- const file = files[0];- FileReader.csvReader({- file,- config: { type: 'reservoirSampling', size: Infinity },- onLoading: () => {}- }).then((data) => {- commonStore.updateTempDS(data as IRow[]);- });- }- }}- />- <div className="mt-1 mb-1">- <button className="inline-block min-w-96 text-xs mr-2 pt-1 pb-1 pl-6 pr-6 border border-gray-500 rounded-sm cursor-pointer hover:bg-gray-200"- onClick={() => { if (fileRef.current) { fileRef.current.click(); }}}- >- 上传数据- </button>- <button className="inline-block min-w-96 text-xs mr-2 pt-1 pb-1 pl-6 pr-6 bg-yellow-600 rounded-sm hover:bg-yellow-500 text-white font-bold disabled:bg-gray-300"- disabled={tmpDataSource.length === 0}- onClick={() => { onSubmitData(); }}- >- 确认- </button>- </div>- <div className="mt-1 mb-1">- <label className="block text-xs text-gray-800">数据集名称</label>- <input type="text" placeholder="数据集名称"- value={tmpDSName}- onChange={e => {- commonStore.updateTempName(e.target.value)- }}- className="text-xs p-1 border border-gray-200 outline-none focus:outline-none focus:border-blue-500"- />- </div>- <Table />- </Container>- );-}--export default observer(DataSourcePanel);diff --git a/packages/graphic-walker/src/store/commonStore.ts b/packages/graphic-walker/src/store/commonStore.tsindex cc294b5c..2af178db 100644--- a/packages/graphic-walker/src/store/commonStore.ts+++ b/packages/graphic-walker/src/store/commonStore.ts@@ -116,11 +116,13 @@ export class CommonStore {public updateTempDS (rawData: IRow[]) {const result = transData(rawData);- // TODO: need fix web-data-loader issue #2- this.tmpDataSource = result.dataSource.slice(0, -1);+ this.tmpDataSource = result.dataSource;this.tmpDSRawFields = result.fields;}-+ /**+ * update temp dataset (standard) with dataset info+ * @param dataset+ */public updateTempSTDDS (dataset: IDataSetInfo) {this.tmpDataSource = dataset.dataSource;this.tmpDSRawFields = dataset.rawFields;diff --git a/packages/graphic-walker/src/utils/index.ts b/packages/graphic-walker/src/utils/index.tsindex 29d22be7..face5a72 100644--- a/packages/graphic-walker/src/utils/index.ts+++ b/packages/graphic-walker/src/utils/index.ts@@ -276,4 +276,8 @@ export function makeNumbersBeautiful (nums: number[]): number[] {return nums.map((num) => {return Math.round(num / step) * step;})+}++export function classNames(...classes: string[]) {+ return classes.filter(Boolean).join(' ')}\ No newline at end of filediff --git a/yarn.lock b/yarn.lockindex 074d30a4..d9873b28 100644--- a/yarn.lock+++ b/yarn.lock@@ -456,10 +456,10 @@redux "^4.0.4"use-memo-one "^1.1.1"-"@kanaries/[email protected]":- version "0.1.5"- resolved "https://registry.yarnpkg.com/@kanaries/web-data-loader/-/web-data-loader-0.1.5.tgz#10d8d677492919b0838b9429d28cbf2b7d726100"- integrity sha512-WVXBjhAgwCOItulV7oz2DOkX294bmgc2GDunxwtgK9cn4dUKg16EV1djkdpJy4r4VGQNXj89gPYECuHdMq4dkw==+"@kanaries/web-data-loader@^0.1.7":+ version "0.1.7"+ resolved "https://registry.yarnpkg.com/@kanaries/web-data-loader/-/web-data-loader-0.1.7.tgz#ce322bc4028f00a433a655fe631a148c51c875bc"+ integrity sha512-i+JadnZC0XZcOk72tvV1/ko2TKn9p8ogJ6TdGYJOn5sK6cToE3R9Kz1LJdbw50M7uNUQK+vEAHWi1MOguqlJKw==dependencies:"@types/papaparse" "^5.0.3"papaparse "^5.1.1"@@ -2971,16 +2971,16 @@ y18n@^5.0.5:resolved "https://registry.yarnpkg.com/y18n/-/y18n-5.0.8.tgz#7f4934d0f7ca8c56f95314939ddcd2dd91ce1d55"integrity sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==-yallist@*, yallist@^4.0.0:- version "4.0.0"- resolved "https://registry.yarnpkg.com/yallist/-/yallist-4.0.0.tgz#9bb92790d9c0effec63be73519e11a35019a3a72"- integrity sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==-yallist@^3.0.2:version "3.1.1"resolved "https://registry.yarnpkg.com/yallist/-/yallist-3.1.1.tgz#dbb7daf9bfd8bac9ab45ebf602b8cbad0d5d08fd"integrity sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==+yallist@^4.0.0:+ version "4.0.0"+ resolved "https://registry.yarnpkg.com/yallist/-/yallist-4.0.0.tgz#9bb92790d9c0effec63be73519e11a35019a3a72"+ integrity sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==+yaml@^1.10.2:version "1.10.2"resolved "https://registry.yarnpkg.com/yaml/-/yaml-1.10.2.tgz#2301c5ffbf12b467de8da2333a459e29e7920e4b"