Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

react: nivo #1160

Merged
merged 3 commits into from
Jan 19, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions packages/chart-react-nivo/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module.exports = {
extends: "../react/.eslintrc.js",
};
47 changes: 47 additions & 0 deletions packages/chart-react-nivo/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
{
"name": "@tony/cv-chart-react-nivo",
"license": "All rights reserved",
"private": true,
"version": "0.0.1",
"main": "dist/index.js",
"module": "src/index.ts",
"scripts": {
"start": "echo 'noop'",
"build": "echo 'noop'",
"test": "echo 'noop'",
"lint": "eslint . -c .eslintrc.js --ext .ts,.tsx",
"prettier": "prettier src webpack --write",
"format": "yarn run prettier",
"update": "yarn run ncu",
"ncu": "ncu",
"clean": "rm -rf dist/"
},
"devDependencies": {
"@types/node": "^14.14.21",
"@types/react": "^17.0.0",
"@types/react-dom": "^17.0.0",
"cross-env": "^7.0.3",
"eslint-plugin-react": "^7.22.0",
"prettier": "^2.2.1",
"typescript": "^4.1.3"
},
"peerDependencies": {
"@typescript-eslint/eslint-plugin": "^4.13.0",
"@typescript-eslint/parser": "^4.13.0",
"eslint": "^7.18.0",
"eslint-plugin-import": "^2.22.1",
"eslint-plugin-promise": "^4.2.1"
},
"dependencies": {
"@datorama/akita": "^6.0.0",
"@nivo/bar": "^0.67.0",
"@nivo/core": "^0.67.0",
"@nivo/line": "^0.67.0",
"@nivo/pie": "^0.67.0",
"@tony/cv-lib": "*",
"fast-deep-equal": "^3.1.3",
"react": "^17.0.1",
"react-dom": "^17.0.1",
"rxjs": "^6.6.3"
}
}
100 changes: 100 additions & 0 deletions packages/chart-react-nivo/src/charts.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import React from "react";

import { ResponsivePie } from "@nivo/pie";
import { ResponsiveLine } from "@nivo/line";
import type { Observable, Subscription } from "rxjs";

import { nivoChartQuery as query } from "./hub";
import { DonutChartProps, LineChartProps } from "./query";
import equal from "fast-deep-equal";

// Todo consolidate this into common code somewhere
export function onEmit<T>(
source$: Observable<T>,
nextFn: (value: T) => void
): Subscription {
return source$.subscribe(nextFn, console.error);
}

// Same as onEmit
export const useAsyncEffect = (
effect: React.EffectCallback | (() => Promise<void>),
dependencies?: unknown[]
): void =>
React.useEffect(() => {
effect();
return () => void 0;
}, dependencies);

export const LanguagePieChart: React.FC<
// Partial<React.ComponentProps<typeof ResponsivePie>>
Partial<DonutChartProps>
> = (props) => {
const [chartData, setChartData] = React.useState<DonutChartProps>();
useAsyncEffect(async () => {
if (!chartData) {
setChartData((await query.getDonutChart()) as DonutChartProps);
}
return void 0;
});

React.useEffect(() => void 0, [chartData]);
React.useEffect(() => {
const subscriptions: Subscription[] = [
onEmit<DonutChartProps>(query.subDonutChart$(), (newChart) => {
const isChanged = !equal(newChart, chartData);
console.log("pie published", newChart, chartData, { isChanged });

if (isChanged) {
setChartData(newChart);
}
}),
];

return () => {
subscriptions.map((it) => it.unsubscribe());
};
}, []);

if (!chartData) {
return null;
}

return <ResponsivePie {...chartData} {...props} />;
};

export const ActivityLineChart: React.FC<
Partial<React.ComponentProps<typeof ResponsiveLine>>
> = (props) => {
const [chartData, setChartData] = React.useState<LineChartProps>();
useAsyncEffect(async () => {
if (!chartData) {
setChartData((await query.getLineChart()) as LineChartProps);
}
return void 0;
});

React.useEffect(() => void 0, [chartData]);
React.useEffect(() => {
const subscriptions: Subscription[] = [
onEmit<LineChartProps>(query.subLineChart$(), (newChart) => {
const isChanged = !equal(newChart, chartData);
console.log("pie published", newChart, chartData, { isChanged });

if (isChanged) {
setChartData(newChart);
}
}),
];

return () => {
subscriptions.map((it) => it.unsubscribe());
};
}, []);

if (!chartData) {
return null;
}

return <ResponsiveLine {...chartData} {...props} />;
};
20 changes: 20 additions & 0 deletions packages/chart-react-nivo/src/hub.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import {
activitiesQuery,
activityTypesQuery,
cvStore,
query,
orgsQuery,
orgTypesQuery,
languagesQuery,
} from "@tony/cv-lib/hub";
import { NivoChartQuery } from "./query";

export const nivoChartQuery = new NivoChartQuery(
cvStore,
query,
activitiesQuery,
activityTypesQuery,
languagesQuery,
orgsQuery,
orgTypesQuery
);
176 changes: 176 additions & 0 deletions packages/chart-react-nivo/src/query.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,176 @@
import type { Observable } from "rxjs";

import { combineQueries } from "@datorama/akita";
import type { LineSvgProps } from "@nivo/line";
import type { PieSvgProps } from "@nivo/pie";
import { map, take } from "rxjs/operators";

import { CVQuery } from "@tony/cv-lib/search/query";
import type {
OrgsQuery,
OrgTypesQuery,
LanguagesQuery,
ActivityTypesQuery,
ActivitiesQuery,
} from "@tony/cv-lib/search/query";

import { CVStore } from "@tony/cv-lib/search/store";

function isString(x: unknown): x is string {
return typeof x === "string";
}

export type DonutChartProps = PieSvgProps<{
id: string;
label: string;
value: number;
}>;
export type LineChartProps = LineSvgProps;

export interface Results {
// Charts
donutChart: DonutChartProps;
lineChart: LineChartProps;
}

export const DEFAULT_RESULTS: Results = {
// Charts
donutChart: { data: [], height: 400, width: 400 },
lineChart: { data: [] },
};

export class NivoChartQuery extends CVQuery {
constructor(
protected store: CVStore,
protected cvQuery: CVQuery,
protected activitiesQuery: ActivitiesQuery,
protected activityTypesQuery: ActivityTypesQuery,
protected languagesQuery: LanguagesQuery,
protected orgsQuery: OrgsQuery,
protected orgTypesQuery: OrgTypesQuery
) {
super(
store,
activitiesQuery,
activityTypesQuery,
languagesQuery,
orgsQuery,
orgTypesQuery
);
}

//
// Chart
//
subDonutChart$(): Observable<DonutChartProps> {
return combineQueries([
this.visibleLanguageCount$(),
this.visibleLanguages$(),
]).pipe(
map(([languageCount, languages]) => {
return {
data: Object.entries(languageCount).map(([languageName, count]) => {
return {
id: languageName,
label: languageName,
value: count,
};
}),
colors: (item) => {
const color = languages.find((language) => language.id == item.id)
?.ui?.backgroundColor;

if (color && isString(color)) {
return color;
}
return "gray";
},
margin: { top: 60, right: 80, bottom: 60, left: 80 },
innerRadius: 0.5,
padAngle: 0.7,
cornerRadius: 3,
borderWidth: 1,
radialLabelsSkipAngle: 15,
radialLabelsLinkOffset: 0.1,
radialLabelsLinkDiagonalLength: 0.1,
radialLabelsLinkColor: { from: "color" },
radialLabelsTextColor: "#333333",
sortByValue: true,
sliceLabelsSkipAngle: 10,
sliceLabelsTextColor: (item) => {
const color = languages.find((language) => language.id == item.id)
?.ui?.color;

if (color && isString(color)) {
return color;
}
return "gray";
},
} as PieSvgProps<{ id: string; label: string; value: number }>;
})
);
}

// await $queries.CV.getDonutChart()
getDonutChart(): Promise<DonutChartProps> {
return this.subDonutChart$().pipe(take(1)).toPromise();
}

subLineChart$(): Observable<LineChartProps> {
return this.visibleActivityYearCount$().pipe(
map((activityCount) => {
return {
// @ts-ignore
data: [
{
id: "Year",
data: Object.entries(activityCount).map(([year, count]) => {
return {
x: `${year.toString()}-01-01`,
y: count,
};
}),
},
],
colors: "rgb(53, 114, 165)",
pointColor: "rgb(37, 80, 115)",
xScale: {
type: "time",
format: "%Y-%m-%d",
precision: "year",
},
xFormat: "time:%Y-%m-%d",
yScale: {
type: "linear",
stacked: false,
},
margin: { top: 20, bottom: 20, left: 20, right: 20 },
axisLeft: {
legend: "linear scale",
legendOffset: 12,
},
axisBottom: {
format: "%Y",
tickValues: "every 1 year",
legend: "time scale",
legendOffset: -12,
},
enablePointLabel: true,
pointSize: 16,
pointBorderWidth: 1,
pointBorderColor: {
from: "color",
modifiers: [["darker", 0.3]],
},
useMesh: true,
enableSlices: false,
};
})
);
}

// await $queries.CV.getLineChart()
getLineChart(): Promise<LineChartProps> {
return this.subLineChart$().pipe(take(1)).toPromise();
}
}
4 changes: 4 additions & 0 deletions packages/chart-react-nivo/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"extends": "../react/tsconfig.json",
"include": ["src/*"]
}
Loading