first init react chart js library

This commit is contained in:
Sambo Chea 2020-10-15 08:43:27 +07:00
commit fdacd18b92
18 changed files with 495 additions and 0 deletions

3
.eslintignore Normal file
View File

@ -0,0 +1,3 @@
node_modules
dist

17
.eslintrc.js Normal file
View File

@ -0,0 +1,17 @@
module.exports = {
parser: "@typescript-eslint/parser", // Specifies the ESLint parser
parserOptions: {
ecmaVersion: 2020, // Allows for the parsing of modern ECMAScript features
sourceType: "module" // Allows for the use of imports
},
extends: [
"plugin:@typescript-eslint/recommended", // Uses the recommended rules from the @typescript-eslint/eslint-plugin
"prettier/@typescript-eslint", // Uses eslint-config-prettier to disable ESLint rules from @typescript-eslint/eslint-plugin that would conflict with prettier
"plugin:prettier/recommended" // Enables eslint-plugin-prettier and eslint-config-prettier. This will display prettier errors as ESLint errors. Make sure this is always the last configuration in the extends array.
],
rules: {
// Place to specify ESLint rules. Can be used to overwrite rules specified from the extended configs
// e.g. "@typescript-eslint/explicit-function-return-type": "off",
}
};

13
.gitignore vendored Normal file
View File

@ -0,0 +1,13 @@
# Code Editor
.idea
.vscode
# Lock File
**/yarn.lock
# Node Modules
**/node_modules
# Error File
yarn-error.log

10
.npmignore Normal file
View File

@ -0,0 +1,10 @@
# Ignore Node Module
**/node_modules
# Editor
.idea
.vscode
# Lock File
yarn.lock
package.lock.json

3
.prettierignore Normal file
View File

@ -0,0 +1,3 @@
node_modules
dist
build

6
.prettierrc Normal file
View File

@ -0,0 +1,6 @@
{
"printWidth": 120,
"tabWidth": 4,
"trailingComma": "all",
"singleQuote": true
}

6
babel.config.js Normal file
View File

@ -0,0 +1,6 @@
module.exports = {
presets: [
['@babel/preset-env', {targets: {node: 'current'}}],
'@babel/preset-typescript',
],
};

8
dist/ReactChartJs.d.ts vendored Normal file
View File

@ -0,0 +1,8 @@
import { ChartConfiguration } from 'chart.js';
import { FunctionComponent } from 'react';
interface ReactChartJSProps {
chartConfig?: ChartConfiguration;
}
declare const ReactChartJs: FunctionComponent<ReactChartJSProps>;
export default ReactChartJs;
//# sourceMappingURL=ReactChartJs.d.ts.map

1
dist/ReactChartJs.d.ts.map vendored Normal file
View File

@ -0,0 +1 @@
{"version":3,"file":"ReactChartJs.d.ts","sourceRoot":"","sources":["../src/ReactChartJs.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAS,kBAAkB,EAAE,MAAM,UAAU,CAAC;AACrD,OAAc,EAAE,iBAAiB,EAAqB,MAAM,OAAO,CAAC;AAEpE,UAAU,iBAAiB;IACvB,WAAW,CAAC,EAAE,kBAAkB,CAAC;CACpC;AAMD,QAAA,MAAM,YAAY,EAAE,iBAAiB,CAAC,iBAAiB,CAiCtD,CAAC;AAEF,eAAe,YAAY,CAAC"}

45
dist/ReactChartJs.js vendored Normal file
View File

@ -0,0 +1,45 @@
"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
var chart_js_1 = require("chart.js");
var react_1 = __importStar(require("react"));
var ReactChartJs = function (props) {
var chartConfig = props.chartConfig;
var canvasDomRef = react_1.useRef();
var chartInstanceRef = react_1.useRef({});
react_1.useEffect(function () {
var canvasDom = canvasDomRef.current;
var chartInstance = chartInstanceRef.current.chartInstance;
if (chartInstance) {
chartInstance.destroy();
}
chartInstanceRef.current.chartInstance = new chart_js_1.Chart(canvasDom, chartConfig);
// if (!chartInstance) {
// } else {
// chartInstanceRef.current!.chartInstance.update()
// }
}, [chartConfig]);
return (react_1.default.createElement("div", null,
react_1.default.createElement("canvas", { ref: function (instance) {
canvasDomRef.current = instance;
}, width: "400", height: "200" })));
};
exports.default = ReactChartJs;

2
dist/index.d.ts vendored Normal file
View File

@ -0,0 +1,2 @@
export { default as ReactChartJs } from "./ReactChartJs";
//# sourceMappingURL=index.d.ts.map

1
dist/index.d.ts.map vendored Normal file
View File

@ -0,0 +1 @@
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,OAAO,IAAI,YAAY,EAAE,MAAM,gBAAgB,CAAA"}

8
dist/index.js vendored Normal file
View File

@ -0,0 +1,8 @@
"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.ReactChartJs = void 0;
var ReactChartJs_1 = require("./ReactChartJs");
Object.defineProperty(exports, "ReactChartJs", { enumerable: true, get: function () { return __importDefault(ReactChartJs_1).default; } });

192
jest.config.js Normal file
View File

@ -0,0 +1,192 @@
// For a detailed explanation regarding each configuration property, visit:
// https://jestjs.io/docs/en/configuration.html
module.exports = {
// All imported modules in your tests should be mocked automatically
// automock: false,
// Stop running tests after `n` failures
// bail: 0,
// The directory where Jest should store its cached dependency information
// cacheDirectory: "/tmp/jest_rs",
// Automatically clear mock calls and instances between every test
clearMocks: true,
// Indicates whether the coverage information should be collected while executing the test
// collectCoverage: false,
// An array of glob patterns indicating a set of files for which coverage information should be collected
// collectCoverageFrom: undefined,
// The directory where Jest should output its coverage files
coverageDirectory: "coverage",
// An array of regexp pattern strings used to skip coverage collection
// coveragePathIgnorePatterns: [
// "/node_modules/"
// ],
// Indicates which provider should be used to instrument code for coverage
coverageProvider: "babel",
// A list of reporter names that Jest uses when writing coverage reports
// coverageReporters: [
// "json",
// "text",
// "lcov",
// "clover"
// ],
// An object that configures minimum threshold enforcement for coverage results
// coverageThreshold: undefined,
// A path to a custom dependency extractor
// dependencyExtractor: undefined,
// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,
// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],
// A path to a module which exports an async function that is triggered once before all test suites
// globalSetup: undefined,
// A path to a module which exports an async function that is triggered once after all test suites
// globalTeardown: undefined,
// A set of global variables that need to be available in all test environments
// globals: {},
// The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
// maxWorkers: "50%",
// An array of directory names to be searched recursively up from the requiring module's location
// moduleDirectories: [
// "node_modules"
// ],
// An array of file extensions your modules use
// moduleFileExtensions: [
// "js",
// "json",
// "jsx",
// "ts",
// "tsx",
// "node"
// ],
// A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
// moduleNameMapper: {},
// An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
// modulePathIgnorePatterns: [],
// Activates notifications for test results
// notify: false,
// An enum that specifies notification mode. Requires { notify: true }
// notifyMode: "failure-change",
// A preset that is used as a base for Jest's configuration
// preset: undefined,
// Run tests from one or more projects
// projects: undefined,
// Use this configuration option to add custom reporters to Jest
// reporters: undefined,
// Automatically reset mock state between every test
// resetMocks: false,
// Reset the module registry before running each individual test
// resetModules: false,
// A path to a custom resolver
// resolver: undefined,
// Automatically restore mock state between every test
// restoreMocks: false,
// The root directory that Jest should scan for tests and modules within
// rootDir: undefined,
// A list of paths to directories that Jest should use to search for files in
// roots: [
// "<rootDir>"
// ],
// Allows you to use a custom runner instead of Jest's default test runner
// runner: "jest-runner",
// The paths to modules that run some code to configure or set up the testing environment before each test
// setupFiles: [],
// A list of paths to modules that run some code to configure or set up the testing framework before each test
// setupFilesAfterEnv: [],
// The number of seconds after which a test is considered as slow and reported as such in the results.
// slowTestThreshold: 5,
// A list of paths to snapshot serializer modules Jest should use for snapshot testing
// snapshotSerializers: [],
// The test environment that will be used for testing
testEnvironment: "node",
// Options that will be passed to the testEnvironment
// testEnvironmentOptions: {},
// Adds a location field to test results
// testLocationInResults: false,
// The glob patterns Jest uses to detect test files
// testMatch: [
// "**/__tests__/**/*.[jt]s?(x)",
// "**/?(*.)+(spec|test).[tj]s?(x)"
// ],
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
// testPathIgnorePatterns: [
// "/node_modules/"
// ],
// The regexp pattern or array of patterns that Jest uses to detect test files
// testRegex: [],
// This option allows the use of a custom results processor
// testResultsProcessor: undefined,
// This option allows use of a custom test runner
// testRunner: "jasmine2",
// This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
// testURL: "http://localhost",
// Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
// timers: "real",
// A map from regular expressions to paths to transformers
// transform: undefined,
// An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
// transformIgnorePatterns: [
// "/node_modules/",
// "\\.pnp\\.[^\\/]+$"
// ],
// An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
// unmockedModulePathPatterns: undefined,
// Indicates whether each individual test should be reported during the run
// verbose: undefined,
// An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
// watchPathIgnorePatterns: [],
// Whether to use watchman for file crawling
// watchman: true,
};

63
package.json Normal file
View File

@ -0,0 +1,63 @@
{
"name": "@cubetiq/react-chart-js",
"version": "1.0.0",
"description": "Chart JS For React",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"author": "SL",
"license": "MIT",
"private": true,
"keywords": [
"javascript",
"typescript",
"boilerplate",
"library"
],
"repository": {
"url": "https://git.cubetiqs.com/s.long/js-lib-boilerplate"
},
"scripts": {
"build": "tsc",
"test": "jest",
"build:test": "yarn jest && yarn build",
"publish": "yarn build:test && npm publish --registry https://npm.osa.cubetiqs.com",
"run:example": "cd example && yarn start"
},
"devDependencies": {
"@babel/core": "^7.11.4",
"@babel/preset-env": "^7.11.0",
"@babel/preset-typescript": "^7.10.4",
"@types/chart.js": "^2.9.25",
"@types/jest": "^26.0.10",
"@types/node": "^14.6.1",
"@typescript-eslint/eslint-plugin": "^3.10.1",
"@typescript-eslint/parser": "^3.10.1",
"babel-jest": "^26.3.0",
"eslint": "^7.7.0",
"eslint-config-prettier": "^6.11.0",
"eslint-plugin-prettier": "^3.1.4",
"husky": "^4.2.5",
"jest": "^26.4.2",
"lint-staged": "^10.2.13",
"prettier": "^2.1.1",
"ts-jest": "^26.3.0",
"tsc": "^1.20150623.0",
"typescript": "^4.0.2"
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"src/**/*.{js,jsx,ts,tsx,json,css,scss,md}": [
"eslint --fix"
],
"test/**/*.{js,jsx,ts,tsx,json,css,scss,md}": [
"eslint --fix"
]
},
"dependencies": {
"chart.js": "^2.9.3"
}
}

43
src/ReactChartJs.tsx Normal file
View File

@ -0,0 +1,43 @@
import { Chart, ChartConfiguration } from 'chart.js';
import React, { FunctionComponent, useEffect, useRef } from 'react';
interface ReactChartJSProps {
chartConfig?: ChartConfiguration;
}
interface RefForChartInstance {
chartInstance?: Chart;
}
const ReactChartJs: FunctionComponent<ReactChartJSProps> = props => {
const { chartConfig } = props;
const canvasDomRef = useRef<HTMLCanvasElement>();
const chartInstanceRef = useRef<RefForChartInstance >({});
useEffect(() => {
const canvasDom = canvasDomRef.current;
const chartInstance = chartInstanceRef.current!.chartInstance;
if (chartInstance) {
chartInstance.destroy();
}
chartInstanceRef.current!.chartInstance = new Chart(canvasDom!, chartConfig!);
}, [chartConfig]);
return (
<div>
<canvas
ref={instance => {
canvasDomRef.current = instance!;
}}
width="400"
height="200"
/>
</div>
);
};
export default ReactChartJs;

3
src/index.ts Normal file
View File

@ -0,0 +1,3 @@
export { default as ReactChartJs } from "./ReactChartJs"

71
tsconfig.json Normal file
View File

@ -0,0 +1,71 @@
{
"compilerOptions": {
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es5", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
"jsx": "react", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
"declaration": true, /* Generates corresponding '.d.ts' file. */
"declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
"outDir": "./dist", /* Redirect output structure to the directory. */
"rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
"baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
},
"include": [
"src"
],
"exclude": ["node_modules", "**/*.spec.ts"]
}