diff --git a/.bowerrc b/.bowerrc deleted file mode 100644 index 466a5a7e9..000000000 --- a/.bowerrc +++ /dev/null @@ -1,3 +0,0 @@ -{ - "directory": "source/bower_components" -} diff --git a/.browserslistrc b/.browserslistrc new file mode 100644 index 000000000..3427f9a3f --- /dev/null +++ b/.browserslistrc @@ -0,0 +1,3 @@ +defaults +not ie 11 +not ie_mob 11 diff --git a/.clean-publish b/.clean-publish new file mode 100644 index 000000000..711387ffe --- /dev/null +++ b/.clean-publish @@ -0,0 +1,4 @@ +{ + "withoutPublish": true, + "tempDir": "package" +} diff --git a/.commitlintrc.json b/.commitlintrc.json new file mode 100644 index 000000000..23e264859 --- /dev/null +++ b/.commitlintrc.json @@ -0,0 +1,6 @@ +{ + "extends": ["@commitlint/config-conventional"], + "rules": { + "body-max-line-length": [0] + } +} diff --git a/.czrc b/.czrc new file mode 100644 index 000000000..11f040658 --- /dev/null +++ b/.czrc @@ -0,0 +1,3 @@ +{ + "path": "@commitlint/cz-commitlint" +} diff --git a/.eslintrc.json b/.eslintrc.json new file mode 100644 index 000000000..305293158 --- /dev/null +++ b/.eslintrc.json @@ -0,0 +1,68 @@ +{ + "extends": ["eslint:recommended", "plugin:prettier/recommended"], + "parser": "@babel/eslint-parser", + "parserOptions": { + "ecmaVersion": "latest", + "requireConfigFile": false + }, + "env": { + "es6": true, + "browser": true, + "node": true + }, + "rules": { + "no-console": 2, + "curly": 2, + "dot-notation": 1, + "eqeqeq": 2, + "no-alert": 2, + "no-caller": 2, + "no-eval": 2, + "no-extra-bind": 2, + "no-implied-eval": 2, + "no-multi-spaces": 2, + "no-with": 2, + "no-shadow": 2, + "no-shadow-restricted-names": 2, + "brace-style": ["error", "1tbs"], + "camelcase": 2, + "comma-style": ["error", "last"], + "eol-last": 2, + "key-spacing": 2, + "new-cap": 1, + "no-array-constructor": 2, + "no-mixed-spaces-and-tabs": 2, + "no-multiple-empty-lines": 2, + "semi-spacing": 2, + "no-spaced-func": 2, + "no-trailing-spaces": 2, + "space-before-blocks": 2, + "spaced-comment": 1, + "no-var": 2 + }, + "overrides": [ + { + "files": ["**/*.ts"], + "parser": "@typescript-eslint/parser", + "plugins": ["@typescript-eslint"], + "extends": ["plugin:@typescript-eslint/recommended"] + }, + { + "files": ["test/**/*.{js,ts}", "*.spec.{js,ts}", "*.stories.{js,ts}"], + "plugins": [ + "jest", + "testing-library", + "jest-dom" + ], + "extends": ["plugin:jest-dom/recommended"], + "env": { + "jest/globals": true + }, + "rules": { + "no-console": 0, + "no-shadow": 0, + "@typescript-eslint/no-explicit-any": 0 + } + } + ] +} diff --git a/.gitattributes b/.gitattributes index 212566614..176a458f9 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1 @@ -* text=auto \ No newline at end of file +* text=auto diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 000000000..041fac64f --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,3 @@ +# These are supported funding model platforms + +github: gionkunz diff --git a/.github/ISSUE_TEMPLATE/bug-report.yml b/.github/ISSUE_TEMPLATE/bug-report.yml new file mode 100644 index 000000000..24617de4b --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug-report.yml @@ -0,0 +1,44 @@ +name: "šŸ› Bug Report" +description: "If something isn't working as expected." +title: "[Bug]: " +labels: ["bug"] +body: + - type: markdown + attributes: + value: Thanks for taking the time to file a bug report! Please fill out this form as completely as possible. + + - type: checkboxes + id: input1 + attributes: + label: Would you like to work on a fix? + options: + - label: Check this if you would like to implement a PR, we are more than happy to help you go through the process. + + - type: textarea + attributes: + label: Current and expected behavior + description: A clear and concise description of what the library is doing and what you would expect. + validations: + required: true + + - type: input + attributes: + label: Reproduction + description: | + Please provide issue reproduction. + You can give a link to a repository with the reproduction or make a [sandbox](https://codesandbox.io/) and reproduce the issue there. + validations: + required: true + + - type: input + attributes: + label: Chartist version + description: Which version of Chartist are you using? + placeholder: v0.0.0 + validations: + required: true + + - type: textarea + attributes: + label: Possible solution + description: If you have suggestions on a fix for the bug. diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml new file mode 100644 index 000000000..d735f21bb --- /dev/null +++ b/.github/ISSUE_TEMPLATE/config.yml @@ -0,0 +1,5 @@ +blank_issues_enabled: false +contact_links: + - name: šŸ¤” Have a Question? + url: https://stackoverflow.com/questions/tagged/chartist.js + about: Feel free to ask questions on Stack Overflow. diff --git a/.github/ISSUE_TEMPLATE/feature-request.yml b/.github/ISSUE_TEMPLATE/feature-request.yml new file mode 100644 index 000000000..6d9a48205 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature-request.yml @@ -0,0 +1,40 @@ +name: "šŸš€ Feature Request" +description: "I have a specific suggestion!" +labels: ["enhancement"] +body: + - type: markdown + attributes: + value: Thanks for taking the time to suggest a new feature! Please fill out this form as completely as possible. + + - type: checkboxes + id: input1 + attributes: + label: Would you like to work on this feature? + options: + - label: Check this if you would like to implement a PR, we are more than happy to help you go through the process. + + - type: textarea + attributes: + label: What problem are you trying to solve? + description: | + A concise description of what the problem is. + placeholder: | + I have an issue when [...] + validations: + required: true + + - type: textarea + attributes: + label: Describe the solution you'd like + validations: + required: true + + - type: textarea + attributes: + label: Describe alternatives you've considered + + - type: textarea + attributes: + label: Documentation, Adoption, Migration Strategy + description: | + If you can, explain how users will be able to use this and how it might be documented. Maybe a mock-up? diff --git a/.github/renovate.json b/.github/renovate.json new file mode 100644 index 000000000..5fcce1121 --- /dev/null +++ b/.github/renovate.json @@ -0,0 +1,6 @@ +{ + "extends": [ + "config:base", + ":preserveSemverRanges" + ] +} diff --git a/.github/workflows/checks.yml b/.github/workflows/checks.yml new file mode 100644 index 000000000..7f693ed3e --- /dev/null +++ b/.github/workflows/checks.yml @@ -0,0 +1,72 @@ +name: Checks +on: + pull_request: + branches: + - main +jobs: + size: + runs-on: ubuntu-latest + name: size-limit + steps: + - name: Checkout the repository + uses: actions/checkout@v5 + - name: Install pnpm + uses: pnpm/action-setup@v4 + with: + version: 7 + - name: Install Node.js + uses: actions/setup-node@v5 + with: + node-version: 16 + cache: 'pnpm' + - name: Check size + uses: andresz1/size-limit-action@master + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + storybook: + runs-on: ubuntu-latest + name: storybook + steps: + - name: Checkout the repository + uses: actions/checkout@v5 + - name: Install pnpm + uses: pnpm/action-setup@v4 + with: + version: 7 + - name: Install Node.js + uses: actions/setup-node@v5 + with: + node-version: 16 + cache: 'pnpm' + - name: Install dependencies + run: pnpm install + - name: Check storybook + run: pnpm build:storybook + editorconfig: + runs-on: ubuntu-latest + name: editorconfig + steps: + - name: Checkout the repository + uses: actions/checkout@v5 + - name: Check editorconfig + uses: editorconfig-checker/action-editorconfig-checker@v1 + website: + runs-on: ubuntu-latest + name: website + steps: + - name: Checkout the repository + uses: actions/checkout@v5 + - name: Install pnpm + uses: pnpm/action-setup@v4 + with: + version: 7 + - name: Install Node.js + uses: actions/setup-node@v5 + with: + node-version: 16 + cache: 'pnpm' + - name: Install dependencies + run: pnpm install + - name: Check website + run: pnpm build + working-directory: ./website diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 000000000..1b79ffe7a --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,43 @@ +name: CI +on: + pull_request: + push: + branches: + - main +jobs: + test: + runs-on: ubuntu-latest + strategy: + matrix: + stage: + - unit + - storyshots + fail-fast: false + name: ${{ matrix.stage }} tests + steps: + - name: Checkout the repository + uses: actions/checkout@v5 + - name: Install pnpm + uses: pnpm/action-setup@v4 + with: + version: 7 + - name: Install Node.js + uses: actions/setup-node@v5 + with: + node-version: 16 + cache: 'pnpm' + - name: Install dependencies + run: pnpm install + - name: Run tests + run: pnpm test:${{ matrix.stage }} + - name: Collect coverage + uses: codecov/codecov-action@v5 + if: "success() && matrix.stage == 'unit'" + with: + files: ./coverage/lcov.info + - name: Collect artifacts + uses: actions/upload-artifact@v4 + if: "failure() && matrix.stage != 'unit'" + with: + name: Image snapshots (${{ matrix.stage }}) + path: test/__image_snapshots__/ diff --git a/.github/workflows/commit.yml b/.github/workflows/commit.yml new file mode 100644 index 000000000..7ee48d506 --- /dev/null +++ b/.github/workflows/commit.yml @@ -0,0 +1,14 @@ +name: Commit +on: + push: +jobs: + commitlint: + runs-on: ubuntu-latest + name: commitlint + steps: + - name: Checkout the repository + uses: actions/checkout@v5 + with: + fetch-depth: 0 + - name: Run commitlint + uses: wagoid/commitlint-github-action@v4 diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 000000000..447fa7e76 --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,62 @@ +name: Release +on: + issue_comment: + types: [created, deleted] + push: + branches: + - main +jobs: + check: + runs-on: ubuntu-latest + name: Context check + outputs: + continue: ${{ steps.check.outputs.continue }} + workflow: ${{ steps.check.outputs.workflow }} + steps: + - name: Checkout the repository + uses: actions/checkout@v5 + - name: Context check + id: check + uses: trigensoftware/simple-release-action@latest + with: + workflow: check + github-token: ${{ secrets.GITHUB_TOKEN }} + pull-request: + runs-on: ubuntu-latest + name: Pull request + needs: check + if: needs.check.outputs.workflow == 'pull-request' + steps: + - name: Checkout the repository + uses: actions/checkout@v5 + - name: Create or update pull request + uses: trigensoftware/simple-release-action@latest + with: + workflow: pull-request + github-token: ${{ secrets.GITHUB_TOKEN }} + release: + runs-on: ubuntu-latest + name: Release + needs: check + if: needs.check.outputs.workflow == 'release' + steps: + - name: Checkout the repository + uses: actions/checkout@v5 + - name: Install pnpm + uses: pnpm/action-setup@v4 + with: + version: 7 + - name: Install Node.js + uses: actions/setup-node@v5 + with: + node-version: 16 + cache: 'pnpm' + registry-url: 'https://registry.npmjs.org/' + - name: Install dependencies + run: pnpm install + - name: Release + uses: trigensoftware/simple-release-action@latest + with: + workflow: release + github-token: ${{ secrets.GITHUB_TOKEN }} + npm-token: ${{ secrets.NPM_TOKEN }} diff --git a/.github/workflows/update-storyshots.yml b/.github/workflows/update-storyshots.yml new file mode 100644 index 000000000..8b1fda6c0 --- /dev/null +++ b/.github/workflows/update-storyshots.yml @@ -0,0 +1,28 @@ +name: Update storyshots +on: workflow_dispatch +jobs: + update-storyshots: + runs-on: ubuntu-latest + name: storyshots + steps: + - name: Checkout the repository + uses: actions/checkout@v5 + - name: Install pnpm + uses: pnpm/action-setup@v4 + with: + version: 7 + - name: Install Node.js + uses: actions/setup-node@v5 + with: + node-version: 16 + cache: 'pnpm' + - name: Install dependencies + run: pnpm install + - name: Update snapshots + run: pnpm test:storyshots -u + - name: Collect artifacts + uses: actions/upload-artifact@v4 + if: always() + with: + name: Updated storyshots + path: test/__image_snapshots__/ diff --git a/.github/workflows/website.yml b/.github/workflows/website.yml new file mode 100644 index 000000000..b058d18b4 --- /dev/null +++ b/.github/workflows/website.yml @@ -0,0 +1,47 @@ +name: Website +on: + push: + branches: + - main +# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages +permissions: + contents: read + pages: write + id-token: write +# Allow one concurrent deployment +concurrency: + group: "pages" + cancel-in-progress: true +jobs: + deploy: + environment: + name: github-pages + url: ${{ steps.deployment.outputs.page_url }} + runs-on: ubuntu-latest + name: deploy website + steps: + - name: Checkout the repository + uses: actions/checkout@v5 + - name: Install pnpm + uses: pnpm/action-setup@v4 + with: + version: 7 + - name: Install Node.js + uses: actions/setup-node@v5 + with: + node-version: 16 + cache: 'pnpm' + - name: Install dependencies + run: pnpm install + - name: Build website + run: pnpm build + working-directory: ./website + - name: Setup Pages + uses: actions/configure-pages@v5 + - name: Upload artifact + uses: actions/upload-pages-artifact@v3 + with: + path: './website/build' + - name: Deploy to GitHub Pages + id: deployment + uses: actions/deploy-pages@v4 diff --git a/.gitignore b/.gitignore index 6e524438f..9b242abb8 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,17 @@ +# See https://help.github.com/ignore-files/ for more about ignoring files. + +# dependencies node_modules -sitedist -.tmp -.sass-cache -source/bower_components + +# builds +package +dist +storybook-static + +# misc +.DS_Store + +npm-debug.log* + +# testing +coverage diff --git a/.jshintrc b/.jshintrc deleted file mode 100644 index 373fed11d..000000000 --- a/.jshintrc +++ /dev/null @@ -1,29 +0,0 @@ -{ - "node": true, - "browser": true, - "esnext": true, - "bitwise": true, - "camelcase": false, - "curly": true, - "eqeqeq": true, - "immed": true, - "indent": 2, - "latedef": true, - "newcap": false, - "noarg": true, - "quotmark": "single", - "regexp": true, - "undef": true, - "unused": true, - "strict": true, - "trailing": true, - "smarttabs": true, - "globals": { - "angular": false, - "jQuery": false, - "$": false, - "SVG": false, - "Snap": false, - "Foundation": false - } -} diff --git a/.nano-staged.json b/.nano-staged.json new file mode 100644 index 000000000..f9993ff47 --- /dev/null +++ b/.nano-staged.json @@ -0,0 +1,3 @@ +{ + "**/*.{js,ts}": ["prettier --write", "eslint"] +} diff --git a/.npmrc b/.npmrc new file mode 100644 index 000000000..319e41e69 --- /dev/null +++ b/.npmrc @@ -0,0 +1 @@ +strict-peer-dependencies=false diff --git a/.nvmrc b/.nvmrc new file mode 100644 index 000000000..b009dfb9d --- /dev/null +++ b/.nvmrc @@ -0,0 +1 @@ +lts/* diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 000000000..c79ed740a --- /dev/null +++ b/.prettierrc @@ -0,0 +1,9 @@ +{ + "singleQuote": true, + "jsxSingleQuote": true, + "semi": true, + "tabWidth": 2, + "bracketSpacing": true, + "arrowParens": "avoid", + "trailingComma": "none" +} diff --git a/.simple-git-hooks.json b/.simple-git-hooks.json new file mode 100644 index 000000000..06e40b963 --- /dev/null +++ b/.simple-git-hooks.json @@ -0,0 +1,5 @@ +{ + "commit-msg": "pnpm commitlint --edit \"$1\"", + "pre-commit": "pnpm nano-staged", + "pre-push": "pnpm test" +} diff --git a/.simple-release.json b/.simple-release.json new file mode 100644 index 000000000..f7509e8d6 --- /dev/null +++ b/.simple-release.json @@ -0,0 +1,3 @@ +{ + "project": "@simple-release/pnpm#PnpmProject" +} diff --git a/.size-limit.json b/.size-limit.json new file mode 100644 index 000000000..840211bfb --- /dev/null +++ b/.size-limit.json @@ -0,0 +1,30 @@ +[ + { + "path": "dist/index.cjs", + "limit": "36.76 kB", + "webpack": false, + "running": false + }, + { + "path": "dist/index.cjs", + "limit": "7.45 kB", + "import": "{ BarChart }" + }, + { + "path": "dist/index.js", + "limit": "36.48 kB", + "webpack": false, + "running": false + }, + { + "path": "dist/index.js", + "limit": "7.4 kB", + "import": "{ BarChart }" + }, + { + "path": "dist/index.css", + "limit": "1.3 kB", + "webpack": false, + "running": false + } +] diff --git a/.storybook/main.js b/.storybook/main.js new file mode 100644 index 000000000..0e7c7d096 --- /dev/null +++ b/.storybook/main.js @@ -0,0 +1,35 @@ +const path = require('path'); + +module.exports = { + stories: ['../src/**/*.stories.@(js|jsx|ts|tsx)'], + addons: [ + '@storybook/addon-docs', + '@storybook/addon-controls', + '@storybook/addon-actions', + '@storybook/addon-viewport' + ], + webpackFinal: async config => { + config.module.rules[0].use = [require.resolve('swc-loader')]; + config.module.rules.push({ + test: /\.scss$/, + use: ['style-loader', 'css-loader', 'postcss-loader', 'sass-loader'].map( + require.resolve + ) + }); + + config.resolve.alias['chartist-dev/styles$'] = path.resolve( + __dirname, + '..', + 'src', + 'styles', + 'index.scss' + ); + config.resolve.alias['chartist-dev$'] = path.resolve( + __dirname, + '..', + 'src' + ); + + return config; + } +}; diff --git a/.storybook/manager.js b/.storybook/manager.js new file mode 100644 index 000000000..79890c478 --- /dev/null +++ b/.storybook/manager.js @@ -0,0 +1,8 @@ +import { addons } from '@storybook/addons'; + +import { theme } from './theme'; + +addons.setConfig({ + theme, + panelPosition: 'right' +}); diff --git a/.storybook/package.json b/.storybook/package.json new file mode 100644 index 000000000..5bbefffba --- /dev/null +++ b/.storybook/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/.storybook/preview.js b/.storybook/preview.js new file mode 100644 index 000000000..320ceb465 --- /dev/null +++ b/.storybook/preview.js @@ -0,0 +1,20 @@ +import { INITIAL_VIEWPORTS } from '@storybook/addon-viewport'; +import { configureActions } from '@storybook/addon-actions'; +import faker from 'faker'; + +const SEED_VALUE = 584; + +if (process.env.STORYBOOK_STORYSHOTS) { + // Make faker values reproducible. + faker.seed(SEED_VALUE); +} + +configureActions({ + depth: 5 +}); + +export const parameters = { + viewport: { + viewports: INITIAL_VIEWPORTS + } +}; diff --git a/.storybook/theme.js b/.storybook/theme.js new file mode 100644 index 000000000..f5c687897 --- /dev/null +++ b/.storybook/theme.js @@ -0,0 +1,7 @@ +import { create } from '@storybook/theming'; + +export const theme = create({ + base: 'light', + brandTitle: 'chartist', + brandUrl: 'https://github.com/chartist-js/chartist' +}); diff --git a/.tool-versions b/.tool-versions new file mode 100644 index 000000000..08e5c52b1 --- /dev/null +++ b/.tool-versions @@ -0,0 +1,2 @@ +pnpm 7.33.7 +nodejs 18.18.0 diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 83f4e22f0..000000000 --- a/.travis.yml +++ /dev/null @@ -1,7 +0,0 @@ -language: node_js -node_js: - - '0.8' - - '0.10' -before_script: - - 'npm install -g bower grunt-cli' - - 'bower install' diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 000000000..a8aacbb5d --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,337 @@ +# Changelog + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + +## [1.5.0](https://github.com/chartist-js/chartist/compare/v1.4.0...v1.5.0) (2025-09-30) + +### Features + +* support for viewport in SVG only providing width and height ([#1403](https://github.com/chartist-js/chartist/issues/1403)) ([752f0a7](https://github.com/chartist-js/chartist/commit/752f0a780cbff77e18ed43c1f1f9b9b4c63507b6)) + +## [1.4.0](https://github.com/chartist-js/chartist/compare/v1.3.1...v1.4.0) (2025-06-27) + +### Features + +* add option to prevent overlapping labels ([#1428](https://github.com/chartist-js/chartist/issues/1428)) ([552bfca](https://github.com/chartist-js/chartist/commit/552bfca452c97a2733bbf813832cefb6dd10fddc)) + +### [1.3.1](https://github.com/chartist-js/chartist/compare/v1.3.0...v1.3.1) (2025-04-07) + +### Bug Fixes + +* add an error message when chart container is not found ([#1392](https://github.com/chartist-js/chartist/issues/1392)) ([6ee19be](https://github.com/chartist-js/chartist/commit/6ee19be3a1936a3c1761aa2f3651683a02495543)) +* prototype pollution vulnerability in extend (CVE-2024-45435) ([#1433](https://github.com/chartist-js/chartist/issues/1433)) ([5a24b93](https://github.com/chartist-js/chartist/commit/5a24b933d2ab4a97c30a24e9fa1da21c9c8083f1)), closes [#1427](https://github.com/chartist-js/chartist/issues/1427) +* use clientWidth/clientHeight instead of getBoundingClientRect ([#1395](https://github.com/chartist-js/chartist/issues/1395)) ([1067900](https://github.com/chartist-js/chartist/commit/10679003a8cec24f9c1f559bdd0c241ec02319a4)) + +## [1.3.0](https://github.com/chartist-js/chartist/compare/v1.2.1...v1.3.0) (2022-11-03) + + +### Features + +* accumulate-relative stacked bar chart stack mode ([#1375](https://github.com/chartist-js/chartist/issues/1375)) ([ce13067](https://github.com/chartist-js/chartist/commit/ce13067acec9cee050af979d323dae5e728292c4)), closes [#1167](https://github.com/chartist-js/chartist/issues/1167) + + +### Bug Fixes + +* add dist exports ([#1374](https://github.com/chartist-js/chartist/issues/1374)) ([1438bad](https://github.com/chartist-js/chartist/commit/1438bad5b8754fe0744c4c1c8540c08a4c4e6862)), closes [#1368](https://github.com/chartist-js/chartist/issues/1368) +* add missing default for text-line-height ([#1373](https://github.com/chartist-js/chartist/issues/1373)) ([f94e559](https://github.com/chartist-js/chartist/commit/f94e559c2414d17002ee52421b860d91b6eae0af)) + +### [1.2.1](https://github.com/chartist-js/chartist/compare/v1.2.0...v1.2.1) (2022-10-05) + + +### Bug Fixes + +* data normalization with alignment ([#1365](https://github.com/chartist-js/chartist/issues/1365)) ([fe11d2f](https://github.com/chartist-js/chartist/commit/fe11d2f6d9e55455286bc34d3eed93b587f1313c)), closes [#1235](https://github.com/chartist-js/chartist/issues/1235) +* reverse data correctly [#1250](https://github.com/chartist-js/chartist/issues/1250) ([#1364](https://github.com/chartist-js/chartist/issues/1364)) ([0223b1f](https://github.com/chartist-js/chartist/commit/0223b1ff2c69a919e3d776b58fb9b5cc96654987)) + +## [1.2.0](https://github.com/chartist-js/chartist/compare/v1.1.3...v1.2.0) (2022-10-03) + + +### Features + +* dist scss styles sources ([#1362](https://github.com/chartist-js/chartist/issues/1362)) ([d0efcb0](https://github.com/chartist-js/chartist/commit/d0efcb00aa45e1d4611a16472da758ead8148f7b)) +* remove legacy styles fallbacks ([#1363](https://github.com/chartist-js/chartist/issues/1363)) ([831673f](https://github.com/chartist-js/chartist/commit/831673f9dff080d1c762db2bc5da397eb0b55ab9)) + + +### Bug Fixes + +* SvgPath.parse fails on negative values ([#1360](https://github.com/chartist-js/chartist/issues/1360)) ([cf6831d](https://github.com/chartist-js/chartist/commit/cf6831d2f7e08dddb497d6b7ce5354e0976779ab)) + +### [1.1.3](https://github.com/chartist-js/chartist/compare/v1.1.2...v1.1.3) (2022-09-23) + + +### Bug Fixes + +* B and I series have the same color value ([#1356](https://github.com/chartist-js/chartist/issues/1356)) ([6f5ad92](https://github.com/chartist-js/chartist/commit/6f5ad92795755b1e50775cf7b837d20700f3e334)) +* label position fix ([#1357](https://github.com/chartist-js/chartist/issues/1357)) ([fbc13e2](https://github.com/chartist-js/chartist/commit/fbc13e22c334a46e9097f7115c1616fc0cc1077d)), closes [#1266](https://github.com/chartist-js/chartist/issues/1266) + +### [1.1.2](https://github.com/chartist-js/chartist/compare/v1.1.1...v1.1.2) (2022-08-14) + + +### Bug Fixes + +* add id field to AnimationDefinition interface ([#1351](https://github.com/chartist-js/chartist/issues/1351)) ([4012c43](https://github.com/chartist-js/chartist/commit/4012c43942e2dd243a4e5983f25bf4c22ea42d91)) + +### [1.1.1](https://github.com/chartist-js/chartist/compare/v1.1.0...v1.1.1) (2022-08-13) + + +### Bug Fixes + +* add styles to side effects ([#1350](https://github.com/chartist-js/chartist/issues/1350)) ([053bf97](https://github.com/chartist-js/chartist/commit/053bf978d825c6285da93af3558b8c0667676212)) + +## [1.1.0](https://github.com/chartist-js/chartist/compare/v1.0.0...v1.1.0) (2022-08-13) + + +### Features + +* add ResponsiveOptions type helper, add generic type to Svg#getNode method ([#1347](https://github.com/chartist-js/chartist/issues/1347)) ([7dd3ba2](https://github.com/chartist-js/chartist/commit/7dd3ba2992751976bfdff9603021afa8fad140d8)) + + +### Bug Fixes + +* add Date type to members of Multi type ([#1348](https://github.com/chartist-js/chartist/issues/1348)) ([9bd8679](https://github.com/chartist-js/chartist/commit/9bd867958dd457b26cb697cf6b4d101944443755)) + +## [1.0.0](https://github.com/chartist-js/chartist/compare/v0.11.4...v1.0.0) (2022-08-08) + + +### ⚠ BREAKING CHANGES + +* [new exports names](https://github.com/chartist-js/chartist#esm) +* methods in EventEmitter were renamed: `addEventHandler` -> `on`, `removeEventHandler` -> `off` ([73e1c44](https://github.com/chartist-js/chartist/commit/73e1c44dc1abab4938dc623a3dc22caad92af6a8)) + +### Features + +* [TypeScript support](https://github.com/chartist-js/chartist#typescript) ([ee4106e](https://github.com/chartist-js/chartist/commit/ee4106e04f3c081805dd79675340378f895c8290)) +* [ESM support](https://github.com/chartist-js/chartist#esm) + + +v0.11.0 - 11 Apr 2017 +- Added CSP compatibility by using CSSOM instead of style attributes (Francisco Silva) +- Added feature to render pie / donut chart as solid shape, allowing outlines (Sergey Kovalyov, Chris Carson) +- Fixed XMLNS for foreignObjet content (Alfredo Matos) + +v0.10.0 - 23 Oct 2016 +--------------------- + +- Added dominant-baseline styles for pie and donut charts (Gion Kunz) +- Added public getNode on SVG api (Gion Kunz) +- Added support for bar charts to have auto narrowing on AutoScaleAxis by overriding referenceValue (Jonathan Dumaine) +- Added amdModuleId for better integration into webpack (Chris) +- Added grid background to line and bar chart (hansmaad) +- Added new LTS node version and included NPM run scripts (Gion Kunz) +- Added correct meta data emission in events (Gion Kunz) +- Fixed rounding issues where raw value was added instead of rounded (Gion Kunz) +- Fixed step axis issue with axis stretch and series count 0 (Gion Kunz) +- Fixed label position of single series pie / donut charts to be centered (Gion Kunz) +- Fixed order or drawing pie and donut slices (Gion Kunz) +- Fixed calculations of stepLength to only stretch ticksLength if > 1 (Alexander van Eck) +- Fixed better handling of axisOptions.position and fallback to 'end' position (Alexander van Eck) +- Fixed handling of holes in interpolation for multi-value series (James Watmuff) +- Fixed function StepAxis() returning NaN (Joao Milton) +- Fixed NaN issues in SVG when rendering Pie chart with only 0s (Alexander van Eck) +- Fixed infinite loop in getBounds with a more robust increment (hansmaad) +- Fixed performance of Chartist.extend (cheese83) +- Fixed license reference issues in package.json (Jacob Quant) +- Cleanup of data normalization changes and allows Date objects and booleans as values (Gion Kunz) +- Cleanup refactoring for data management and normalization (Gion Kunz) + +v0.9.8 - 22 Jun 2016 +-------------------- +- Added monotone cubic interpolation which is now the default interpolation for line charts (James Watmuff) +- Update zoom plugin to 0.2.1 (hansmaad) +- Bugfix: Prevent infinite loop in getBounds if bounds.valueRange is very small, fixes #643 (hansmaad) +- Bugfix: Correct update events during media changes (Rory Hunter) +- Bugfix: prevent negative value for foreignObject width attribute (Jose Ignacio) +- Fixed example line chart in getting started documentation (Robin Edbom) +- Updated development pipeline dependencies (Gion Kunz) +- Updated chartist tooltip plugin and example styles (Gion Kunz) +- Fixed WTFPL License issue (Gion Kunz) + +v0.9.7 - 23 Feb 2016 +-------------------- +- Fixed bug with label and grid rendering on axis, fixes #621 + +v0.9.6 - 22 Feb 2016 +-------------------- +- Added dual licensing WTFPL and MIT, built new version (Gion Kunz) +- Adding unminified CSS to dist output, fixes #506 (Gion Kunz) +- Refactored namespaced attribute handling, fixes #584 (Gion Kunz) +- Allow charts to be created without data and labels, fixes #598, fixes #588, fixes #537, fixes #425 (Gion Kunz> -``` - -**Recommended** -``` - -``` - -**Not recommended** -``` -.example { - background: url(http://static.example.com/images/bg.jpg); -} -``` - -**Recommended** -``` -.example { - background: url(http://static.example.com/images/bg.jpg); -} -``` - -*** - -### Text indentation - -Indent by 2 spaces at a time. - -``` - -``` - -``` -@media screen and (min-width: 1100px) { - body { - font-size: 100%; - } -} -``` - -``` -(function(){ - var x = 10; - - function y(a, b) { - return { - result: (a + b) * x - } - - } -}()); -``` - -*** - -### Comments - -Comments are the only way others and **YOURSELF** know why a particular code was written and why it was written in the -way it was. It's crucial that you comment your code parts and specially code that is not trivial. - -Self explaining code is a **MYTH**. There is no such thing as self explaining code. Also there is no such thing as too -many comments. There is only too little comments. - -When you comment code don't comment what's coded, comment why it was coded this way and comment the thinking behind. -Also include links in your comments to open issues, specifications etc. - -**Not recommended** -``` -var offset = 0; - -if(includeLabels) { - // Add offset of 20 - offset = 20; -} -``` - -**Recommended** -``` -var offset = 0; - -if(includeLabels) { - // If the labels are included we need to have a minimum offset of 20 pixels - // We need to set it explicitly because of the following bug: http://somebrowservendor.com/issue-tracker/ISSUE-1 - offset = 20; -} -``` - -Consider using annotations in your comments that help to structure commends and add meta information. For Javascript -use [JSDoc](http://usejsdoc.org/) or [YUIDoc](http://yui.github.io/yuidoc/). You can also use tools to generate -documentation from these comments. This is also a great way to encourage developers to write comments. Once comments -will be used to generate a living documentation they often start to spend more time for detailed comments. - -*** - -### Code linting - -For programming languages with less strictness it's important to enforce style rules and formatting guidelines. -Writing and following a style guide is a good practice but having an automated process that is enforcing it is even -better. Trust is good, control is better. - -For Javascript we recommend to use JSLint / JSHint. In the repository for this styleguide you can also find a -[dotfile for jshint (.jshintrc)](.jshintrc). You can use this file with JSHint to enforce style -checking in your Javascript projects. - -*** - -## HTML style rules - -*** - -### Document type - -HTML5 (HTML syntax) is preferred for all HTML documents: ``. - -(It’s recommended to use HTML, as text/html. Do not use XHTML. XHTML, as application/xhtml+xml, -lacks both browser and infrastructure support and offers less room for optimization than HTML.) - -Although fine with HTML, do not close void elements, i.e. write `
`, not `
`. - -*** - -### HTML validity - -Use valid HTML code unless that is not possible due to otherwise unattainable performance goals regarding file size. - -Use tools such as the W3C HTML validator to test. - -Using valid HTML is a measurable baseline quality attribute that contributes to learning about technical requirements -and constraints, and that ensures proper HTML usage. - -**Not recommended** -``` -Test -
This is only a test. -``` - -**Recommended** -``` - - -Test -
This is only a test.
-``` - -*** - -### Optional Tags - -The HTML5 specification defines what tags can be omitted in the HTML markup. For readability purpose the raw source -file should **NOT** omit optional tags. Omitting optional tags can lead to readability and scannability issues, and -therefore should not be used in the raw source files. - -Omitting tags can lead to significant page size reductions specially on large scale sites. For this purpose you should -consider an HTML minification post processing of your raw files for distribution purpose. - -*** - -### Script loading - -For performance reasons it's important to load scripts asynchronously. A script loaded in the `` like this -`` will block the whole DOM parsing until the script has fully loaded and executed. This -will delay the page to be displayed until the script has fully loaded. With larger scripts this can have a big impact -on user experience. - -Asynchronous script loading helps to minimize this performance impact. If browser support is only concerned about IE10+ -the HTML5 async attribute on scripts should be used. This will prevent DOM parser blocking and you can even place your -script element into the `` element. - -If you need to support older browsers it's common practice to use script loaders that will make use of dynamic script -injection. You should consider [yepnope](http://yepnopejs.com/) or [labjs](http://labjs.com/). The problem with injected -scripts though is that [they will not start loading until CSS Object Model is ready](https://www.igvita.com/2014/05/20/script-injected-async-scripts-considered-harmful/) -(shortly after the CSS from the head is loaded). This can also load to delay of your behavior added by these javascript -which can again affect the user experience. - -As a result of the above described behaviors you should always consider the following best practice if you need to -support old browsers (IE9-). - -Add your script element just before the body close tag and add them with a async attribute. This will not load the -scripts asynchronously on old browsers but they will only block the DOM parser just before the body close which is not -affecting the user experience too much. On modern browsers this will delay the script load until the DOM parser -discovers the script element at the end of the body, but they will then asynchronously load the script and don't wait -for CSSOM to complete before loading (execution will still happen after CSSOM). - -**Recommended for modern and old browsers** -``` - - - - - - - - - - -``` - -**Recommended for only modern browsers** -``` - - - - - - - - - -``` - -*** - -### Semantics - -Use elements (sometimes incorrectly called ā€œtagsā€) for what they have been created for. For example, use heading -elements for headings, p elements for paragraphs, a elements for anchors, etc. - -Using HTML according to its purpose is important for accessibility, reuse, and code efficiency reasons. - -The following bad / good example should outline some of the major important semantic HTML cases: - -**Not recommended** -``` -My page title -
- - - -
- -
-
-
All news articles
-
-

Bad article

-
Introduction sub-title
-
This is a very bad example for HTML semantics
-
I think I'm more on the side and should not receive the main credits
-
- This article was created by David
2014-01-01 00:00
-
-
- - -
-
- - -``` - -**Recommended** -``` - -
- -

My page title

-
- - - - - -
- -
- -
- -

All news articles

-
- - -
- -
- -
Good article
- - Introduction sub-title -
- - -
-

This is a good example for HTML semantics

-
- - - -
- -

This article was created by David

-
-
- - -
-

Related sections: Events, Public holidays

-
-
-
- - -
- Copyright 2014 -
- -``` - -*** - -### Multimedia fallback - -For multimedia, such as images, videos, animated objects via canvas, make sure to offer alternative access. For images -that means use of meaningful alternative text (alt) and for video and audio transcripts and captions, if available. - -Providing alternative contents is important for accessibility reasons: A blind user has few cues to tell what an -image is about without @alt, and other users may have no way of understanding what video or audio contents are about -either. - -(For images whose alt attributes would introduce redundancy, and for images whose purpose is purely decorative which -you cannot immediately use CSS for, use no alternative text, as in alt="".) - -**Not recommended** -``` - -``` - -**Recommended** -``` -Luke skywalker riding an alien horse -``` - -When writing alt tags always try to describe the image as if you'd need to describe what's on the image to somebody -over the phone or who can't see the real picture. - -**Not recommended** -``` -Header image -``` - -**Recommended** -``` -A huge spaceship that is approaching the earth -``` - -*** - -### Separation of Concerns - -It's very important that you understand the different concerns in web and that you know how to and why to separate them. -In the web we have information (html markup), appearance (css) and behavior (Javascript) and we need to separate them as -far as possible in order to keep a maintainable and clean code. - -Strictly keep structure (markup), presentation (styling), and behavior (scripting) apart, and try to keep the -interaction between the three to an absolute minimum. - -That is, make sure documents and templates contain only HTML and HTML that is solely serving structural purposes. -Move everything presentational into style sheets, and everything behavioral into scripts. - -In addition, keep the contact area as small as possible by linking as few style sheets and scripts as possible from -documents and templates. - -Clean separation of concerns implies the following things: - -1. Don't use more than one or two stylesheets (i.e. main.css, vendor.css) -1. Don't use more than one or two scripts (use concatination) -1. Don't use inline styles (``) -1. Don't use element style attributes (`
`) -1. Don't use inline scripts (``) -1. Don't use presentational elements (i.e. ``, ``, `
`, ``, `` -1. Don't use presentational class names (i.e. red, left, center) - -**Not recommended** -``` - - - - - - - - - -

- I'm a subtitle and I'm bold! -
Dare you center me!
- -
I'm important!
- - -``` - -**Recommended** -``` - - - - - - - - -

- -
I'm a subtitle and I'm bold!
- - Dare you center me! - -
I'm important!
- - - - - -``` - -*** - -### HTML is content only - -Don't pollute your HTML markup with non-content information. There is a tendency to solve design problems at -the information's cost. The HTML markup should only contain content relevant information and design problems should -never be solved within the markup. - -The only purpose of HTML markup is to represent content information. - -- Don't introduce a specific HTML structure just to solve some visual design problems -- Don't use `` elements for visual design elements - -The following examples show two common things that are done wrong when it comes to solving design problems. - -**Not recommended** -``` - - - - See the square next to me? - - -``` -``` -.text-box > .square { - display: inline-block; - width: 1rem; - height: 1rem; - background-color: red; -} -``` - - -**Recommended** -``` - - - See the square next to me? - - -``` -``` -// We use a :before pseudo element to solve the design problem of placing a colored square in front of the text content -.text-box:before { - content: ""; - display: inline-block; - width: 1rem; - height: 1rem; - background-color: red; -} -``` - -The only reason for images and svg graphics to be included in the markup is because they represent content relevant -information. - -**Not recommended** -``` - - - Square - See the square next to me? - -``` - -**Recommended** -``` - - - See the square next to me? - - -``` -``` -// We use a :before pseudo element with a background image to solve the problem -.text-box:before { - content: ""; - display: inline-block; - width: 1rem; - height: 1rem; - background: url(http://github.com/square.svg) no-repeat; - background-size: 100%; -} -``` - -*** - -### Type attributes - -Omit type attributes for style sheets and scripts. Do not use type attributes for style sheets (unless not using CSS) -and scripts (unless not using JavaScript). Specifying type attributes in these contexts is not necessary as -HTML5 implies text/css and text/javascript as defaults. This can be safely done even for older browsers. - -**Not recommended** -``` - - -``` - -**Recommended** -``` - - -``` - -*** - -### General Accessibility - -If you use proper HTML5 semantics a lot of accessibility issues are already solved. ARIA is using some default roles -for most of the semantic elements which, if used correctly, solves a lot of the issues already. If you use `nav`, -`aside`, `main`, `footer` etc. ARIA will use some related default roles. For more details you can reference the -[ARIA specification](http://rawgit.com/w3c/aria-in-html/master/index.html#recommendations-table) recommendation table -which contains the defaults for the HTML semantic elements. - -Additional roles can be used to give more accessibility context (i.e. `role="tab"`). - -*** - -### Tab Index for Accessibility - -Check your document for tab order and assign tabindex values in order to change the tab flow based on priority. You -can disable the tab index of an element by setting `tabindex="-1"` on any element. - -If you add functionality to a element that is not focusable by default, you should always add a `tabindex` in order to -make the element focusable. This will also enable the CSS pseudo selector `:focus`. Choose an appropriate index value -for `tabindex` or use `tabindex="0"` to group elements into one tab order level and enforce ordering in natural reading -order. - -*** - -### Microdata for SEO and Accessibility - -If the SEO relevance and / or accessibility environment is given then you should consider to use microdata where -possible. Microdata is a way to annotate your data in your markup that follows some specific semantics. - -Google, Microsoft and Yahoo! have more or less agreed on how to use this additional data and using it correctly has -great influence on your searches. - -You can visit [schema.org](http://schema.org/) for more details. - -Simple example of a movie on a web page: - -**Without microdata** -``` -
-

Avatar

- Director: James Cameron (born August 16, 1954) - Science fiction - Trailer -
-``` - -**With microdata** -``` -
-

Avatar

-
- Director: James Cameron (born August 16, 1954) -
- Science fiction - Trailer -
-``` - -*** - -### IDs for anchors - -It's generally a good practice to give all headings on a page a ID. With these ID's on headings you can use the -browsers default behavior and include the ID names as hash tags in the URL. By default this causes the browser to scroll -to the position this element. - -If you'd enter the URL `http://your-site.com/about#best-practices` in your browser then the browser would scroll down -so that the H3 below would be scrolled into the view. - -``` -

Best practices

-``` - -*** - -### General formatting - -Use a new line for every block, list, or table element, and indent every such child element. -Independent of the styling of an element (as CSS allows elements to assume a different role per display property), -put every block, list, or table element on a new line. - -Also, indent them if they are child elements of a block, list, or table element. - -(If you run into issues around whitespace between list items it’s acceptable to put all li elements in one line. -A linter is encouraged to throw a warning instead of an error.) - -**Recommended** -``` -
-

Space, the final frontier.

-
- -
    -
  • Moe
  • -
  • Larry
  • -
  • Curly
  • -
- - - - - - - - - - - - - - -
IncomeTaxes
$ 5.00$ 4.50
-``` - -*** - -### HTML quotation marks - -When quoting attributes values, use double quotation marks. Use double ("") rather than single quotation marks ('') -around attribute values. - -**Not recommended** -``` -
-``` - -**Recommended** -``` -
-``` - -*** - -## Javascript style guide - -*** - -### Global namespace pollution and IIFE - -Always wrap your code into a IIFE (Immediately-Invoked Function Expression) in order to create an isolated closure -scope. This prevents you from polluting the global namespace. - -IIFE can also secure your code from modifications that happened in the global namespace (i.e. 3rd party libraries, -window reference, overridden undefined keyword etc.) - -**Not recommended** -``` -var x = 10, - y = 100; - -// Declaring variables in the global scope is resulting in global scope pollution. All variables declared like this -// will be stored in the window object. This is very unclean and needs to be avoided. -console.log(window.x + ' ' + window.y); -``` - -**Recommended** -``` -// We declare a IIFE and pass parameters into the function that we will use from the global space -(function(log, w, undefined){ - 'use strict'; - - var x = 10, - y = 100; - - // Will output 'true true' - log((w.x === undefined) + ' ' + (w.y === undefined)); - -}(window.console.log, window)); -``` - -*** - -### IIFE (Immediately-Executed Function Expression) - -Use IIFE whenever you want to create a new closure scope. This can be used to create privacy and to keep memory clean. - -Every javascript file should start with an IIFE. - -The IIFE should be written so you're keeping the execution brackets inside of the surrounding brackets. Although the -writing the executing brackets outside of the surrounding brackets is valid the second example should be used as this -sets clear boundaries for the IIFE as the surrounding brackets isolate the whole IIFE. - -**Not recommended** -``` -(function(){})(); -``` - -**Recommended** -``` -(function(){}()); -``` - -The following pattern should be used to format your IIFE: - -``` -(function(){ - 'use strict'; - - // Code goes here - -}()); -``` - -If you want to use global variables or variables form an outer IIFE you should pass them as parameters to your IIFE: -``` -(function($, w, d){ - 'use strict'; - - $(function() { - w.alert(d.querySelectorAll('div').length); - }); -}(jQuery, window, document)); -``` - -*** - -### Strict mode - -ECMAScript 5 strict mode can be enabled globally in your script or on function level. It enables more strict error -handling as well different javascript semantics. Strict mode also enforces a syntax that allows engines to optimize -the javascript better and strict more scripts can run faster than normal scripts. - -Strict mode also blocks the usage of reserved words that possibly get introduced in the future. - -You should always enforce strict mode in your scripts. Do so by applying it in your isolation IIFE. Don't apply it to -your whole script by include it as first statement in your script. This could possibly cause issues with 3rd party -libraries. - -**Not recommended** -``` -// Script starts here -'use strict'; - -(function(){ - - // Your code starts here - -}()); -``` - -**Recommended** -``` -(function(){ - 'use strict'; - - // Your code starts here - -}()); -``` - -*** - -### Variable declarations - -Always use `var` to declare your variables. When you fail to specify var, the variable gets placed in the global -context, potentially clobbering existing values. Also, if there's no declaration, it's hard to tell in what scope a -variable lives (e.g., it could be in the Document or Window just as easily as in the local scope). -So always declare with var. - -Using strict mode can help to identify issues where you might mistyped a variable name resulting in a ReferenceError. - -**Not recommended** -``` -x = 10; -y = 100; -``` - -**Recommended** -``` -var x = 10, - y = 100; -``` - -*** - -### Understand Javascript scope and hoisting - -In Javascript variable and function declarations will be hoisted before execution. Javascript only knows function scope -and there is no block scope as you know it from other programming languages. This means that if you declare a variable -inside a if statement or for loop this variable is declared for the whole function scope and not only locally in the -block statement. - -To illustrate this check the following example that will show how a javascript interpreter is hoisting the declarations -in a function scope: - -**Raw function** -``` -(function(log){ - 'use strict'; - - var a = 10; - - for(var i = 0; i < a; i++) { - var b = i * i; - log(b); - } - - if(a === 10) { - var f = function() { - log(a); - }; - f(); - } - - function x() { - log('Mr. X!'); - } - x(); - -}(window.console.log)); -``` - -**Hoisted by Javscript engine** -``` -(function(log){ - 'use strict'; - // All variables used in the closure will be hoisted to the top of the function - var a, - i, - b, - f; - // All functions in the closure will be hoisted to the top - function x() { - log('Mr. X!'); - } - - a = 10; - - for(i = 0; i < a; i++) { - b = i * i; - log(b); - } - - if(a === 10) { - // Function assignments will only result in hoisted variables but the function body will not be hoisted - // Only by using a real function declaration the whole function will be hoisted with its body - f = function() { - log(a); - }; - f(); - } - - x(); - -}(window.console.log)); -``` - -Considering now the hoisting above you can now see that you could also run the following code without any exceptions: - -**Valid code** -``` -(function(log){ - 'use strict'; - - var a = 10; - - i = 5; - - x(); - - for(var i; i < a; i++) { - log(b); - var b = i * i; - } - - if(a === 10) { - f = function() { - log(a); - }; - f(); - - var f; - } - - function x() { - log('Mr. X!'); - } - -}(window.console.log)); -``` - -As you can see this looks very confusing and misunderstanding hoisting can lead to unexpected results. To minimize the -risk of errors and bugs that resulted from misunderstanding hoisting your should follow the style rule of hoisted -declarations in the next section. - -*** - -### Use hoisted declarations - -To minimize risk of misunderstanding and misinterpreting results from hoisted variable and function declarations (see -previous section) you should always try to hoist your variable and function declarations manually. This means that -you should declare all your variables that you're using in a function as a fist statement in the function. - -Use only one `var` keyword and comma separate multiple declarations. - -**Not recommended** -``` -(function(log){ - 'use strict'; - - var a = 10; - var b = 10; - - for(var i = 0; i < 10; i++) { - var c = a * b * i; - } - - function f() { - - } - - var d = 100; - var x = function() { - return d * d; - }; - log(x()); - -}(window.console.log)); -``` - -**Recommended** -``` -(function(log){ - 'use strict'; - - var a = 10, - b = 10, - i, - c, - d, - x; - - function f() { - - } - - for(i = 0; i < 10; i++) { - c = a * b * i; - } - - - - d = 100; - x = function() { - return d * d; - }; - log(x()); - -}(window.console.log)); -``` - -Being pragmatic you should directly initialize your variables during hoisted declaration. - -**Not recommended** -``` -var a, - b, - c; - -a = 10; -b = 10; -c = 100; -``` - -**Recommended** -``` -var a = 10, - b = 10, - c = 100; -``` - -*** - -### Always use strict equal - -Always use `===` explicit comparison operators and avoid the hassle you can go through by debugging issues resulted -from the very much overcomplicated javascript type coercion. - -If you're using `===` operators both operands need to be from the same type in order to be valid and there will no -type coercion be performed. - -If you'd like to get more information on type coercion you should read -[this article by Dmitry Soshnikov](http://dmitrysoshnikov.com/notes/note-2-ecmascript-equality-operators/). - -By using only `==` you're telling javascript to use type coercion where needed which can be very complicated to trace -down. A few examples can be seen below that should give you a indication how strange type coercion can feel: - -``` -(function(log){ - 'use strict'; - - log('0' == 0); // true - log('' == false); // true - log('1' == true); // true - log(null == undefined); // true - - var x = { - valueOf: function() { - return 'X'; - } - }; - - log(x == 'X'); - -}(window.console.log)); -``` - -*** - -### Use truthy / falsy checks wisely - -By only putting one variable or expression into a if statement you're creating a truthy / falsy check. The expression -`if(a == true)` is not the same as `if(a)`. The later expression is creating a special check which is called truthy / -falsy check. This check performs some special operations in order to evaluate to true or false. The following -expressions are falsy in javascript `false`, `0`, `undefined`, `null`, `NaN`, `''` (empty string). - -Truthy / falsy checks are very helpful as they allow you to quickly react on a group of conditions that you'd like to -take care of but you need to be sure about what you actually want to do. - -The following example shows how truthy / falsy checks work: - -``` -(function(log){ - 'use strict'; - - function logTruthyFalsy(expr) { - if(expr) { - log('truthy'); - } else { - log('falsy'); - } - } - - logTruthyFalsy(true); // truthy - logTruthyFalsy(1); // truthy - logTruthyFalsy({}); // truthy - logTruthyFalsy([]); // truthy - logTruthyFalsy('0'); // truthy - - logTruthyFalsy(false); // falsy - logTruthyFalsy(0); // falsy - logTruthyFalsy(undefined); // falsy - logTruthyFalsy(null); // falsy - logTruthyFalsy(NaN); // falsy - logTruthyFalsy(''); // falsy - -}(window.console.log)); -``` - -*** - -### Logical operators for variable assignments - -The logical operators `||` and `&&` can also be used to return non-boolean values. If used with non booleans the -operands will evaluate each expression from left to right and performs a falsy check. Depending on the operation, one -of the expressions will be returned. This can be very helpful for variable assignments and should be considered in -order to simplify your code. - -**Not recommended** -``` -if(!x) { - if(!y) { - x = 1; - } else { - x = y; - } -} -``` - -**Recommended** -``` -x = x || y || 1; -``` - -This shorthand is often used to validated function parameters. The following example illustrates one usage example: - -``` -(function(log){ - 'use strict'; - - function multiply(a, b) { - a = a || 1; - b = b || 1; - - log('Result ' + a * b); - } - - multiply(); // Result 1 - multiply(10); // Result 10 - multiply(3, NaN); // Result 3 - multiply(9, 5); // Result 45 - -}(window.console.log)); -``` - -*** - -### Semicolons - -Always use semicolons. Relying on implicit insertion can cause subtle, hard to debug problems. Don't do it. -You're better than that. There are a couple places where missing semicolons are particularly dangerous: - -``` -// 1. -MyClass.prototype.myMethod = function() { - return 42; -} // No semicolon here. - -(function() { - // Some initialization code wrapped in a function to create a scope for locals. -})(); - - -var x = { - 'i': 1, - 'j': 2 -} // No semicolon here. - -// 2. Trying to do one thing on Internet Explorer and another on Firefox. -// I know you'd never write code like this, but throw me a bone. -[ffVersion, ieVersion][isIE](); - - -var THINGS_TO_EAT = [apples, oysters, sprayOnCheese] // No semicolon here. - -// 3. conditional execution a la bash --1 == resultOfOperation() || die(); -``` - -**So what happens?** - -1. JavaScript error - first the function returning 42 is called with the second function as a parameter, then -the number 42 is "called" resulting in an error. -1. You will most likely get a 'no such property in undefined' error at runtime as it tries to -call `x[ffVersion, ieVersion][isIE]()`. -1. `die` is always called since the array minus 1 is `NaN` which is never equal to anything (not even if -`resultOfOperation()` returns `NaN`) and `THINGS_TO_EAT` gets assigned the result of `die()`. - -**Why?** - -JavaScript requires statements to end with a semicolon, except when it thinks it can safely infer their existence. -In each of these examples, a function declaration or object or array literal is used inside a statement. The closing -brackets are not enough to signal the end of the statement. Javascript never ends a statement if the next token is an -infix or bracket operator. - -This has really surprised people, so make sure your assignments end with semicolons. - -**Clarification: Semicolons and functions** - -Semicolons should be included at the end of function expressions, but not at the end of function declarations. -The distinction is best illustrated with an example: - -``` -var foo = function() { - return true; -}; // semicolon here. - -function foo() { - return true; -} // no semicolon here. -``` - -*** - -### Nested functions - -Nested functions can be very useful, for example in the creation of continuations and for the task of hiding helper -functions. Feel free to use them. - -*** - -### Function declaration within blocks - -Do not declare functions in blocks. This is not valid in ECMAScript 5 strict mode. Functions should be declared on -top level. Don't hesitate to use variables initialized with function expressions inside of blocks though: - -**Not recommended** -``` -if (x) { - function foo() {} -} -``` - -**Recommended** -``` -if (x) { - var foo = function() {}; -} -``` - -*** - -### Exceptions - -You basically can't avoid exceptions if you're doing something non-trivial (using an application development framework, -etc.). - -Without custom exceptions, returning error information from a function that also returns a value can be tricky, not to -mention inelegant. Bad solutions include passing in a reference type to hold error information or always returning -Objects with a potential error member. These basically amount to a primitive exception handling hack. -Feel free to use custom exceptions when appropriate. - -In complex environments you should consider throwing objects rather than just strings (default throws). - -``` -if(name === undefined) { - throw { - name: 'System Error', - message: 'A name should always be specified!' - } -} -``` - -*** - -### Standard features - -Always preferred over non-standards features. For maximum portability and compatibility, always prefer standards -features over non-standards features (e.g., `string.charAt(3)` over `string[3]` and element access with DOM functions -instead of using an application-specific shorthand). - -*** - -### Simple prototypical inheritance - -If you need inheritance of your objects in Javascript follow a simple pattern to create inheritance. If you know that -you'll end up with complex object inheritance consider a inheritance library like -[Proto.js by Axel Rauschmayer](https://github.com/rauschma/proto-js). - -For simple cases use like the bellow. - -``` -(function(log){ - 'use strict'; - - // Constructor function - function Apple(name) { - this.name = name; - } - // Defining a method of apple - Apple.prototype.eat = function() { - log('Eating ' + this.name); - }; - - // Constructor function - function GrannySmithApple() { - // Invoking parent constructor - Apple.prototype.constructor.call(this, 'Granny Smith'); - } - // Set parent prototype while creating a copy with Object.create - GrannySmithApple.prototype = Object.create(Apple.prototype); - // Set constructor to the sub type, otherwise points to Apple - GrannySmithApple.prototype.constructor = GrannySmithApple; - - // Calling a super method - GrannySmithApple.prototype.eat = function() { - // Be sure to apply it onto our current object with call(this) - Apple.prototype.eat.call(this); - - log('Poor Grany Smith'); - }; - - // Instantiation - var apple = new Apple('Test Apple'); - var grannyApple = new GrannySmithApple(); - - log(apple.name); // Test Apple - log(grannyApple.name); // Granny Smith - - // Instance checks - log(apple instanceof Apple); // true - log(apple instanceof GrannySmithApple); // false - - log(grannyApple instanceof Apple); // true - log(grannyApple instanceof GrannySmithApple); // true - - // Calling method that calls super method - grannyApple.eat(); // Eating Granny Smith\nPoor Grany Smith - -}(window.console.log)); -``` - -*** - -### Use Closures - -The ability to create closures is perhaps the most useful and often overlooked feature of JS. -Here is [a good description of how closures work](http://jibbering.com/faq/faq_notes/closures.html). - -*** - -### Don't create functions in loops - -It's generally a potential source for bugs if you write functions that create a closure inside of simple loops. The -following example illustrates a common pitfall. - -**Not recommended** -``` -(function(log, w){ - 'use strict'; - - // numbers and i is defined in the current function closure - var numbers = [1, 2, 3], - i; - - for(i = 0; i < numbers.length; i++) { - w.setTimeout(function() { - // At the moment when this gets executed the i variable, coming from the outer function scope - // is set to 3 and the current program is alerting the message 3 times - // 'Index 3 with number undefined - // If you understand closures in javascript you know how to deal with those cases - // It's best to just avoid functions / new closures in loops as this prevents those issues - - w.alert('Index ' + i + ' with number ' + numbers[i]); - }, 0); - } - -}(window.console.log, window)); -``` - -The following variation of the above example solves our problem / bug but still violates our policy to not create -functions / closures inside of loops. - -**Not recommended** -``` -(function(log, w){ - 'use strict'; - - // numbers and i is defined in the current function closure - var numbers = [1, 2, 3], - i; - - for(i = 0; i < numbers.length; i++) { - // Creating a new closure scope with an IIFE solves the problem - // The delayed function will use index and number which are - // in their own closure scope (one closure per loop iteration). - // --- - // Still this is not recommended as we violate our rule to not - // create functions within loops and we are creating two! - - (function(index, number){ - w.setTimeout(function() { - // Will output as expected 0 > 1, 1 > 2, 2 > 3 - w.alert('Index ' + index + ' with number ' + number); - }, 0); - }(i, numbers[i])); - } - -}(window.console.log, window)); -``` - -The following variation solves our problem / bug and we also comply with our style guide. However, this seems to be -heavily overcomplicated and we should look for a better / easier way. - -**Partially recommended** -``` -(function(log, w){ - 'use strict'; - - // numbers and i is defined in the current function closure - var numbers = [1, 2, 3], - i; - - // Create a function outside of the loop that will accept arguments to create a - // function closure scope. This function will return a function that executes in this - // closure parent scope. - function alertIndexWithNumber(index, number) { - return function() { - w.alert('Index ' + index + ' with number ' + number); - }; - } - - // First parameter is a function call that returns a function. - // --- - // This solves our problem and we don't create a function inside our loop - for(i = 0; i < numbers.length; i++) { - w.setTimeout(alertIndexWithNumber(i, numbers[i]), 0); - } - -}(window.console.log, window)); -``` - -By using a functional approach for our loop we solve the problem immediately as we create a new closure with every loop. -Functional style is recommended and will also lead to more natural and expected results. - -**Recommended** -``` -(function(log, w){ - 'use strict'; - - // numbers and i is defined in the current function closure - var numbers = [1, 2, 3], - i; - - numbers.forEach(function(number, index) { - w.setTimeout(function() { - w.alert('Index ' + index + ' with number ' + number); - }, 0); - }); - -}(window.console.log, window)); -``` - -*** - -### The (evil) eval function - -`eval()` makes for confusing semantics and is dangerous to use if the string being eval()'d contains user input. -There's usually a better, clearer, and safer way to write your code, so its use is generally not permitted. - -*** - -### The this keyword - -Use the `this` keyword only in object constructors, methods, and in setting up closures. The semantics of this can be -tricky. At times it refers to the global object (in most places), the scope of the caller (in eval), a node in the DOM -tree (when attached using an event handler HTML attribute), a newly created object (in a constructor), or some other -object (if function was call()ed or apply()ed). - -Because this is so easy to get wrong, limit its use to those places where it is required: - -- in constructors -- in methods of objects (including in the creation of closures) - -*** - -### Functional is preferred - -Using functional style programming you can simplify your code and reduce maintenance cost by gaining easy re-usability, -proper isolation and less dependencies. - -The following example compares two solutions for the same problem of summing up all number elements in an array. The -first example is a classical procedural approach while the second one makes use of functional style programming and the -ECMA Script 5.1 array functions. - -Exception: In situations where performance is considered to be more important than maintainability then you might -consider the most performant solution over the most maintainable (i.e. using simple for loop over forEach) - -**Not recommended** -``` -(function(log){ - 'use strict'; - - var arr = [10, 3, 7, 9, 100, 20], - sum = 0, - i; - - - for(i = 0; i < arr.length; i++) { - sum += arr[i]; - } - - log('The sum of array ' + arr + ' is: ' + sum) - -}(window.console.log)); -``` - -**Recommended** -``` -(function(log){ - 'use strict'; - - var arr = [10, 3, 7, 9, 100, 20]; - - var sum = arr.reduce(function(prevValue, currentValue) { - return prevValue + currentValue; - }, 0); - - log('The sum of array ' + arr + ' is: ' + sum); - -}(window.console.log)); -``` - -An other example would be to filter an array for certain criteria so that we can create a new array that only contains -those elements that match the criteria. - -**Not recommended** -``` -(function(log){ - 'use strict'; - - var numbers = [11, 3, 7, 9, 100, 20, 14, 10], - numbersGreaterTen = [], - i; - - - for(i = 0; i < numbers.length; i++) { - if(numbers[i] > 10) { - numbersGreaterTen.push(numbers[i]); - } - } - - log('From the list of numbers ' + numbers + ' only ' + numbersGreaterTen + ' are greater than ten'); - -}(window.console.log)); -``` - -**Recommended** -``` -(function(log){ - 'use strict'; - - var numbers = [11, 3, 7, 9, 100, 20, 14, 10]; - - var numbersGreaterTen = numbers.filter(function(element) { - return element > 10; - }); - - log('From the list of numbers ' + numbers + ' only ' + numbersGreaterTen + ' are greater than ten'); - -}(window.console.log)); -``` - -*** - -### Use ECMA Script 5 - -Use the syntactical sugar and functional style that was added with ECMA Script 5. It's simplifying your programming -style and makes your code more flexible and re-usable. - -*** - -### Array and object property iteration - -The ECMA5 way to iterate over an array is preferred. Use Array.forEach or Array.every if you would like to cancel the -iteration at a certain condition. - -``` -(function(log){ - 'use strict'; - - // Iterate over an array and break at a certain condition - [1, 2, 3, 4, 5].every(function(element, index, arr) { - log(element + ' at index ' + index + ' in array ' + arr); - - if(index !== 5) { - return true; - } - }); - - // Defining a simple javascript object - var obj = { - a: 'A', - b: 'B', - 'c-d-e': 'CDE' - }; - - // Iterating over the object keys - Object.keys(obj).forEach(function(element, index, arr) { - log('Key ' + element + ' has value ' + obj[element]); - }); - -}(window.console.log)); -``` - -*** - -### Don't use switch - -switch is a very error prone control statement in every programming language. Use if else if instead. - -*** - -### Array and Object literals - -Use Array and Object literals instead of Array and Object constructors. Array constructors are error-prone due to their -arguments. - -**Not recommended** -``` -// Length is 3. -var a1 = new Array(x1, x2, x3); - -// Length is 2. -var a2 = new Array(x1, x2); - -// If x1 is a number and it is a natural number the length will be x1. -// If x1 is a number but not a natural number this will throw an exception. -// Otherwise the array will have one element with x1 as its value. -var a3 = new Array(x1); - -// Length is 0. -var a4 = new Array(); -``` - -Because of this, if someone changes the code to pass 1 argument instead of 2 arguments, the array might not have the -expected length. To avoid these kinds of weird cases, always use the more readable array literal. - -**Recommended** -``` -var a = [x1, x2, x3]; -var a2 = [x1, x2]; -var a3 = [x1]; -var a4 = []; -``` - -Object constructors don't have the same problems, but for readability and consistency object literals should be used. - -**Not recommended** -``` -var o = new Object(); - -var o2 = new Object(); -o2.a = 0; -o2.b = 1; -o2.c = 2; -o2['strange key'] = 3; -``` - -Should be written as: - -**Recommended** -``` -var o = {}; - -var o2 = { - a: 0, - b: 1, - c: 2, - 'strange key': 3 -}; -``` - -*** - -### Modifying prototypes of builtin objects - -Modifying builtins like `Object.prototype` and `Array.prototype` are strictly forbidden. Modifying other builtins like -`Function.prototype` is less dangerous but still leads to hard to debug issues in production and should be avoided. - -*** - -### Custom toString() methods - -You can control how your objects string-ify themselves by defining a custom `toString()` method. This is fine, but you -need to ensure that your method (1) always succeeds and (2) does not have side-effects. If your method doesn't meet -these criteria, it's very easy to run into serious problems. For example, if `toString()` calls a method that does an -assert, assert might try to output the name of the object in which it failed, which of course requires -calling `toString()`. - -*** - -### Parentheses - -Use sparingly and in general only where required by the syntax and semantics. Never use parentheses for unary -operators such as `delete`, `typeof` and `void` or after keywords such as `return`, `throw` as well -as others (`case`, in or `new`). - -*** - -### Strings - -For consistency single-quotes (') are preferred to double-quotes ("). This is helpful when creating -strings that include HTML: - -``` -var msg = 'This is some HTML
'; -``` - -*** - -### Conditional Ternary Operator (shorthand if) - -Use the ternary operator for assignments or return statements. Use it only in simple conditions and avoid it in complex -ones. No body likes to wrap his brain around 10 lines of nested ternary operators. - -**Not recommended** -``` -if(x === 10) { - return 'valid'; -} else { - return 'invalid'; -} -``` - -**Recommended** -``` -return x === 10 ? 'valid' : 'invalid'; -``` - -*** - -## CSS and SASS (SCSS) style rules - -*** - -### ID and class naming - -Instead of presentational or cryptic names, always use ID and class names that reflect the purpose of the element in -question, or that are otherwise generic. - -Names that are specific and reflect the purpose of the element should be preferred as these are most understandable -and the least likely to change. - -Generic names are simply a fallback for elements that have no particular or no meaning different from their siblings. -They are typically needed as ā€œhelpers.ā€ - -Even though class names and ID's have no semantic meaning to computer interpreters, semantic names are often the right -choice as they represent the information meaning and don't introduce presentational constraints. - -**Not recommended** -``` -.fw-800 { - font-weight: 800; -} - -.red { - color: red; -} -``` - -**Recommended** -``` -.heavy { - font-weight: 800; -} - -.important { - color: red; -} -``` - -*** - -### Avoid ID's where possible - -In general ID's should not be used to apply style. Styles on ID's can't be re-used and you can only use them once per -page. The only valid location for using an ID would be to identify a page or a whole site. Still you should always -consider using a class that you use once instead of an id. - -**Not recommended** -``` -#content .title { - font-size: 2em; -} -``` - -**Recommended** -``` -.content .title { - font-size: 2em; -} -``` - -One other argument against using ID's would be that selector chains containing ID's are over-prioritized. A selector -containing just one ID is weighted higher than a selector containing 1000 class names only which makes it very odd. - -``` -// This selecor is considered with higher priority -#content .title { - color: red; -} - -// than this selector! -html body div.content.news-content .title.content-title.important { - color: blue; -} -``` - -*** - -### Avoid elements in CSS selectors - -When building your selectors use clear, precise and sensible class names. Don't use element selectors. If you're only -concerned about your class names and not about your elements your code gets a lot more maintainable. - -From a separation of concerns perspective you don't want to dictate the markup / semantics from the presentation layer. -It might be that a ordered list needs to be changed to an unordered list or that a div will be converted to an article. -If you only care about sensible class names and don't use element selectors you'd only need to change your markup and -not your css. - -**Not recommended** -``` -div.content > header.content-header > h2.title { - font-size: 2em; -} -``` - -**Recommended** -``` -.content > .content-header > .title { - font-size: 2em; -} -``` - -*** - -### Be as precise as possible - -A lot of front-end developers don't use direct child selectors when they write their selector chains. Sometimes this -can cause painful design issues and other times it's just a performance eater. However, in any case, it's a very bad -practice. If you don't write very generic selectors that need to match down to the bottom of the DOM you should always -consider direct child selectors. - -Consider the following DOM: - -``` -
- News event -
-
- Check this out -
- -

This is a news article content

- -
-
Buy this
-
Yey!
-
-
-
-``` - -The following CSS would apply to all three elements that have a title class. This then would need to be overridden again -with more granular selectors in order to fix the content title and the teaser title. - -**Not recommended** -``` -.content .title { - font-size: 2rem; -} -``` - -**Recommended** -``` -.content > .title { - font-size: 2rem; -} - -.content > .content-body > .title { - font-size: 1.5rem; -} - -.content > .content-body > .teaser > .title { - font-size: 1.2rem; -} -``` - -*** - -### Shorthand Properties - -CSS offers a variety of shorthand properties (like font) that should be used whenever possible, even in cases where -only one value is explicitly set. - -Using shorthand properties is useful for code efficiency and understandability. - -**Not recommended** -``` -border-top-style: none; -font-family: palatino, georgia, serif; -font-size: 100%; -line-height: 1.6; -padding-bottom: 2em; -padding-left: 1em; -padding-right: 1em; -padding-top: 0; -``` - -**Recommended** -``` -border-top: 0; -font: 100%/1.6 palatino, georgia, serif; -padding: 0 1em 2em; -``` - -*** - -### 0 and units - -Omit unit specification after ā€œ0ā€ values. Do not use units after 0 values unless they are required. - -**Not recommended** -``` -padding-bottom: 0px; -margin: 0em; -``` - -**Recommended** -``` -padding-bottom: 0; -margin: 0; -``` - -*** - -### Hexadecimal Notation - -Use 3 character hexadecimal notation where possible. For color values that permit it, 3 character hexadecimal notation -is shorter and more succinct. - -Always use lower case hex digits. - -**Not recommended** -``` -color: #FF33AA; -``` - -**Recommended** -``` -color: #f3a; -``` - -*** - -### ID and Class Name Delimiters - -Separate words in ID and class names by a hyphen. Do not concatenate words and abbreviations in selectors by any -characters (including none at all) other than hyphens, in order to improve understanding and scannability. - -Also as the standard foresees attribute selectors that recognise hyphens as separator of words `[attribute|=value]` -it's best to stick to the hyphen as separator. - -**Not recommended** -``` -.demoimage {} -.error_status {} -``` - -**Recommended** -``` -#video-id {} -.ads-sample {} -``` - -*** - -### Hacks - -Avoid user agent detection as well as CSS ā€œhacksā€ā€”try a different approach first. It’s tempting to address styling -differences over user agent detection or special CSS filters, workarounds, and hacks. Both approaches should be -considered last resort in order to achieve and maintain an efficient and manageable code base. Put another way, giving -detection and hacks a free pass will hurt projects in the long run as projects tend to take the way of least -resistance. That is, allowing and making it easy to use detection and hacks means using detection and hacks more -frequently—and more frequently is too frequently. - -*** - -### Declaration Order - -This example should give a rough outline of how to order CSS properties within a selector. This is important in order -to guarantee better readability and better scannability. - -As a best practice we should follow the following ordering (in the same order as the listing): - -1. structural - 1. display - 1. position, left, top, right etc. - 1. overflow, float, clear etc. - 1. margin, padding -1. skin - 1. background, border etc. - 1. font, text - -**Not recommended** -``` -.box { - font-family: 'Arial', sans-serif; - border: 3px solid #ddd; - left: 30%; - position: absolute; - text-transform: uppercase; - background-color: #eee; - right: 30%; - isplay: block; - font-size: 1.5rem; - overflow: hidden; - padding: 1em; - margin: 1em; -} -``` - -**Recommended** -``` -.box { - display: block; - position: absolute; - left: 30%; - right: 30%; - overflow: hidden; - margin: 1em; - padding: 1em; - background-color: #eee; - border: 3px solid #ddd; - font-family: 'Arial', sans-serif; - font-size: 1.5rem; - text-transform: uppercase; -} -``` - -*** - -### Declaration Stops - -End every declaration with a semicolon for consistency and extensibility reasons and put each declaration on a new line. - -**Not recommended** -``` -.test { - display: block; height: 100px -} -``` - -**Recommended** -``` -.test { - display: block; - height: 100px; -} -``` - -*** - -### Property Name Stops - -Use a space after a property name’s colon. Always use a single space between property and value (but no space between -property and colon) for consistency reasons. - -**Not recommended** -``` -h3 { - font-weight:bold; -} -``` - -**Recommended** -``` -h3 { - font-weight: bold; -} -``` - -*** - -### Selector and Declaration Separation - -Always start a new line for each selector and declaration. - -**Not recommended** -``` -a:focus, a:active { - position: relative; top: 1px; -} -``` - -**Recommended** -``` -h1, -h2, -h3 { - font-weight: normal; - line-height: 1.2; -} -``` - -*** - -### Rule Separation - -Always put a blank line (two line breaks) between rules. - -**Recommended** -``` -html { - background: #fff; -} - -body { - margin: auto; - width: 50%; -} -``` - -*** - -### CSS Quotation Marks - -Use double ("") rather than single ('') quotation marks for attribute selectors or property values. -Do not use quotation marks in URI values (url()). - -**Not recommended** -``` -@import url('http://cdn.com/foundation.css'); - -html { - font-family: 'open sans', arial, sans-serif; -} - -body:after { - content: 'pause'; -} -``` - -**Recommended** -``` -@import url(http://cdn.com/foundation.css); - -html { - font-family: "open sans", arial, sans-serif; -} - -body:after { - content: "pause"; -} -``` - -*** - -### Nested selectors (SCSS) - -In SASS you can nest selectors which is much cleaner and the code becomes much more readable. Nest all selectors but -try to avoid nesting without any content. If you need to specify some style attributes for a child element where the -parent element will not receive any styling use a regular CSS selector chain. This will prevent your script to look -overcomplicated. - -**Not recommended** -```scss -// Not a good example by not making use of nesting at all -.content { - display: block; -} - -.content > .news-article > .title { - font-size: 1.2em; -} -``` - -**Not recommended** -```scss -// Using nesting is better but not in all cases -// Avoid nesting when there is no attributes and use selector chains instead -.content { - display: block; - - > .news-article { - > .title { - font-size: 1.2em; - } - } -} -``` - -**Recommended** -```scss -// This example takes the best approach while nesting but use selector chains where possible -.content { - display: block; - - > .news-article > .title { - font-size: 1.2em; - } -} -``` - -*** - -### Introducing space while nesting (SCSS) - -If you nest your selectors introduce blank line between your nested selectors and the css attributes. - -**Not recommended** -```scss -.content { - display: block; - > .news-article { - background-color: #eee; - > .title { - font-size: 1.2em; - } - > .article-footnote { - font-size: 0.8em; - } - } -} -``` - -**Recommended** -```scss -.content { - display: block; - - > .news-article { - background-color: #eee; - - > .title { - font-size: 1.2em; - } - - > .article-footnote { - font-size: 0.8em; - } - } -} -``` - -*** - -### Contextual media queries (SCSS) - -While nesting your selectors you can also make use of contextual media queries within SASS. With SASS you can use media -queries at any given nesting level. The resulting CSS will be converted so that the media query gets rendered around the -selector. - -This technique is very handy and helps to keep media queries in the context where they belong to. With a mobile first -approach this allows you to write your mobile styles first and then use contextual media queries where ever you need -them in order to provide the desktop styles. - -**Not recommended** -```scss -// This mobile first example looks like plain CSS where the whole structure of SCSS is repeated -// on the bottom in a media query. This is error prone and makes maintenance harder as it's not so easy to relate -// the content in the media query to the content in the upper part (mobile style) - -.content-page { - font-size: 1.2rem; - - > .main { - background-color: whitesmoke; - - > .latest-news { - padding: 1rem; - - > .news-article { - padding: 1rem; - - > .title { - font-size: 2rem; - } - } - } - - > .content { - margin-top: 2rem; - padding: 1rem; - } - } - - > .page-footer { - margin-top: 2rem; - font-size: 1rem; - } -} - -@media screen and (min-width: 641px) { - .content-page { - font-size: 1rem; - - > .main > .latest-news > .news-article > .title { - font-size: 3rem; - } - - > .page-footer { - font-size: 0.8rem; - } - } -} -``` - -**Recommended** -```scss -// This is the same example as above but here we use contextual media queries in order to put the different styles -// for different media into the right context. - -.content-page { - font-size: 1.2rem; - - @media screen and (min-width: 641px) { - font-size: 1rem; - } - - > .main { - background-color: whitesmoke; - - > .latest-news { - padding: 1rem; - - > .news-article { - padding: 1rem; - - > .title { - font-size: 2rem; - - @media screen and (min-width: 641px) { - font-size: 3rem; - } - } - } - } - - > .content { - margin-top: 2rem; - padding: 1rem; - } - } - - > .page-footer { - margin-top: 2rem; - font-size: 1rem; - - @media screen and (min-width: 641px) { - font-size: 0.8rem; - } - } -} -``` - -*** - -### Nesting order and the parent selector (SCSS) - -While using the nesting features of SASS it's important to have a clear order to put your nesting in. A SCSS block -should have the following content order. - -1. Current selector's style attributes -1. Pseudo selectors with parent selector (:first-letter, :hover, :active etc) -1. Pseudo elements (:before and :after) -1. State classe with parent selector (.selected, .active, .enlarged etc.) -1. Contextual media queries with SASS -1. Sub selectors as the last part - -The following example should illustrate how this ordering will achieve a clear structure while making use of the SASS -parent selector. - -**Recommended** -```scss -.product-teaser { - // 1. Style attributes - display: inline-block; - padding: 1rem; - background-color: whitesmoke; - color: grey; - - // 2. Pseudo selectors with parent selector - &:hover { - color: black; - } - - // 3. Pseudo elements with parent selector - &:before { - content: ""; - display: block; - border-top: 1px solid grey; - } - - &:after { - content: ""; - display: block; - border-top: 1px solid grey; - } - - // 4. State classes with parent selector - &.active { - background-color: pink; - color: red; - - // 4.2. Pseuso selector in state class selector - &:hover { - color: darkred; - } - } - - // 5. Contextual media queries - @media screen and (max-width: 640px) { - display: block; - font-size: 2em; - } - - // 6. Sub selectors - > .content > .title { - font-size: 1.2em; - - // 6.5. Contextual media queries in sub selector - @media screen and (max-width: 640px) { - letter-spacing: 0.2em; - text-transform: uppercase; - } - } -} -``` - diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index f6fca7ce2..f131704ff 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,8 +1,7 @@ -# Contributing to chartist-js +# Contributing to Chartist - - [Issues and Bugs](#issue) - - [Submission Guidelines](#submit) - - [Coding Conventions](#conventions) +- [Issues and Bugs](#issue) +- [Submission Guidelines](#submit) ## Found an Issue? @@ -15,47 +14,15 @@ with a fix. You will need the following to run a local development enviroment. - Node.js & npm -- Bower (`sudo npm install bower -g`) -- Grunt (`sudo npm install grunt-cli -g`) +- pnpm (`npm install -g pnpm`) - Text editor of your choice - ## How to Run a Local Distribution 1. `cd` into your local copy of the repository. -2. Run `npm install` to install dependencies located in `package.json`. -3. Run `bower update` to install bower dependencies. -5. Run `grunt serve` to start the watch task, and the web server should automatically open. Congrats, you should now be able to see your local copy of the demo site. +2. Run `pnpm i` to install dependencies located in `package.json`. +5. Run `pnpm start:storybook` to start Storybook, or run `pnpm jest --watch` to run tests in watch mode. Congrats, you should now be able to see your local copy of the Chartist testbed. ## Submission Guidelines If you are creating a Pull Request, fork the repository and make any changes on the `develop` branch. - -### Conventions - -Check out the [Coding Style document](CODINGSTYLE.md) - -### Grunt - -We have three grunt tasks: - -1. `grunt build` - Creates the distribution of the example / demo site which is used as visual development help of the charts but also serves as the documentation site / gh-pages. -2. `grunt serve` - Starts watch with livereload that is executing the same things as the site dist default task but for live development. -3. `grunt test` - Executes jasmine tests separately, although we have a very big lack of tests. -4. `grunt serve:dist` - Executes a dist and serves the directory statically in order to serve with the production example / demo site. - -`libdist` should **not** be included in any Pull Requests. So please ensure that code is not being committed as part of the Pull Request. - -### Documentation - -- Everything is already in place and in the `sitedist` there is a `apidoc` folder generated by [doxication](https://github.com/gionkunz/grunt-doxication) generator that uses JSDoc like comments to generate documentation meta files. Always use proper JSDoc comments when documenting methods and API interfaces. Also assign documentation blocks using @memberof to the virtual module they belong to. -- The site documentation is built with [Assemble.io](http://assemble.io/). Generally a component based approach should be followed where there are already Handlebar partials / helpers in order to create whole sites based on components that can be specified by type and with their data in yaml files. - -### Important missing stuff - -1. Jasmine Tests! -2. Documentation: JSDoc, Getting started documentation and landing page -3. Better accessibility using ARIA and other optimizations -4. Better interfaces to the library (i.e. jQuery with data-* attributes for configuration), Angular.js directive etc. -5. Richer SASS / CSS framework -6. Other charts types (spider etc.) diff --git a/Gruntfile.js b/Gruntfile.js deleted file mode 100644 index 879055986..000000000 --- a/Gruntfile.js +++ /dev/null @@ -1,488 +0,0 @@ -'use strict'; - -module.exports = function (grunt) { - - // Load grunt tasks automatically - require('load-grunt-tasks')(grunt); - - // Time how long tasks take. Can help when optimizing build times - require('time-grunt')(grunt); - - var pkg = require('./package.json'); - - grunt.loadNpmTasks('assemble'); - - // Define the configuration for all the tasks - grunt.initConfig({ - - // Grunt package with settings - pkg: grunt.file.readJSON('package.json'), - year: new Date().getFullYear(), - - // Watches files for changes and runs tasks based on the changed files - watch: { - assemble: { - files: ['<%= pkg.config.source %>/site/**/*.{hbs,yml,json,js}'], - tasks: ['doxication', 'assemble'] - }, - doxication: { - files: ['.tmp/data/**/*.{yml,json}'], - tasks: ['doxication', 'assemble'] - }, - js: { - files: ['<%= pkg.config.source %>/scripts/{,*/}*.js'], - tasks: ['newer:jshint:all'], - options: { - livereload: true - } - }, - jsTest: { - files: ['test/spec/{,*/}*.js'], - tasks: ['newer:jshint:test', 'jasmine'] - }, - sass: { - files: ['<%= pkg.config.source %>/styles/**/*.{scss,sass}'], - tasks: ['sass:server'] - }, - gruntfile: { - files: ['Gruntfile.js'] - }, - livereload: { - options: { - livereload: '<%= connect.options.livereload %>' - }, - files: [ - '.tmp/{,*/}*.html', - '.tmp/styles/{,*/}*.css', - '<%= pkg.config.source %>/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}' - ] - } - }, - - // The actual grunt server settings - connect: { - options: { - port: 9000, - // Change this to '0.0.0.0' to access the server from outside. - hostname: '0.0.0.0', - livereload: 35729 - }, - livereload: { - options: { - open: true, - base: [ - '.tmp', - '<%= pkg.config.source %>' - ] - } - }, - test: { - options: { - port: 9001, - base: [ - '.tmp', - 'test', - '<%= pkg.config.source %>' - ] - } - }, - dist: { - options: { - base: '<%= pkg.config.dist %>' - } - } - }, - - // Make sure code styles are up to par and there are no obvious mistakes - jshint: { - options: { - jshintrc: '.jshintrc', - reporter: require('jshint-stylish') - }, - all: [ - 'Gruntfile.js', - '<%= pkg.config.source %>/scripts/{,*/}*.js' - ], - test: { - options: { - jshintrc: 'test/.jshintrc' - }, - src: ['test/spec/{,*/}*.js'] - } - }, - - // Empties folders to start fresh - clean: { - dist: { - files: [ - { - dot: true, - src: [ - '.tmp', - '<%= pkg.config.dist %>/*', - '!<%= pkg.config.dist %>/.git*' - ] - } - ] - }, - server: '.tmp' - }, - - assemble: { - options: { - helpers: ['<%= pkg.config.source %>/site/helpers/**/*.js'], - partials: ['<%= pkg.config.source %>/site/partials/**/*.hbs'], - layoutdir: '<%= pkg.config.source %>/site/layouts', - layoutext: '.hbs', - layout: ['default'], - data: ['<%= pkg.config.source %>/site/data/**/*.{json,yml}', '.tmp/data/**/*.{json,yml}'] - }, - pages: { - expand: true, - cwd: '<%= pkg.config.source %>/site', - src: ['*.hbs'], - dest: '.tmp' - } - }, - - // Compile SASS into CSS with libsass (node-sass) - sass: { - options: { - includePaths: ['<%= pkg.config.source %>/bower_components'], - imagePath: '<%= pkg.config.source %>/images' - }, - dist: { - options: { - sourceComments: 'none' - }, - files: [ - { - expand: true, - cwd: '<%= pkg.config.source %>/styles', - src: '{,*/}*.{scss,sass}', - ext: '.css', - dest: '.tmp/styles' - } - ] - }, - server: { - options: { - sourceComments: 'map' - }, - files: [ - { - expand: true, - cwd: '<%= pkg.config.source %>/styles', - src: '{,*/}*.{scss,sass}', - ext: '.css', - dest: '.tmp/styles' - } - ] - } - }, - - - // Reads HTML for usemin blocks to enable smart builds that automatically - // concat, minify and revision files. Creates configurations in memory so - // additional tasks can operate on them - useminPrepare: { - html: '.tmp/index.html', - options: { - dest: '<%= pkg.config.dist %>' - } - }, - - // Performs rewrites based on rev and the useminPrepare configuration - usemin: { - html: ['<%= pkg.config.dist %>/{,*/}*.html'], - css: ['<%= pkg.config.dist %>/styles/{,*/}*.css'], - options: { - assetsDirs: ['<%= pkg.config.dist %>'], - blockReplacements: { - js: function (block) { - - var asyncScripts = [ - 'scripts/all.js' - ]; - - var isAsync = block.async || asyncScripts.indexOf(block.dest) > -1; - - return isAsync ? - ' + + +
+ + diff --git a/sandboxes/bar/bi-polar-interpolated/index.ts b/sandboxes/bar/bi-polar-interpolated/index.ts new file mode 100644 index 000000000..3733a0fc7 --- /dev/null +++ b/sandboxes/bar/bi-polar-interpolated/index.ts @@ -0,0 +1,19 @@ +import 'chartist/dist/index.css'; +import { BarChart, BarChartOptions } from 'chartist'; + +const data = { + labels: ['W1', 'W2', 'W3', 'W4', 'W5', 'W6', 'W7', 'W8', 'W9', 'W10'], + series: [[1, 2, 4, 8, 6, -2, -1, -4, -6, -2]] +}; + +const options: BarChartOptions = { + high: 10, + low: -10, + axisX: { + labelInterpolationFnc(value, index) { + return index % 2 === 0 ? value : null; + } + } +}; + +new BarChart('#chart', data, options); diff --git a/sandboxes/bar/bi-polar-interpolated/package.json b/sandboxes/bar/bi-polar-interpolated/package.json new file mode 100644 index 000000000..71bb7b80b --- /dev/null +++ b/sandboxes/bar/bi-polar-interpolated/package.json @@ -0,0 +1,8 @@ +{ + "name": "bar-bi-polar-interpolated", + "description": "Bi-polar bar chart", + "main": "index.ts", + "dependencies": { + "chartist": "^1.0.0" + } +} diff --git a/sandboxes/bar/bi-polar-interpolated/sandbox.config.json b/sandboxes/bar/bi-polar-interpolated/sandbox.config.json new file mode 100644 index 000000000..6c650a896 --- /dev/null +++ b/sandboxes/bar/bi-polar-interpolated/sandbox.config.json @@ -0,0 +1,6 @@ +{ + "infiniteLoopProtection": true, + "hardReloadOnChange": true, + "view": "browser", + "template": "parcel" +} diff --git a/sandboxes/bar/distributed-series/index.html b/sandboxes/bar/distributed-series/index.html new file mode 100644 index 000000000..e650efa09 --- /dev/null +++ b/sandboxes/bar/distributed-series/index.html @@ -0,0 +1,9 @@ + + + + + + +
+ + diff --git a/sandboxes/bar/distributed-series/index.ts b/sandboxes/bar/distributed-series/index.ts new file mode 100644 index 000000000..e1e85cac6 --- /dev/null +++ b/sandboxes/bar/distributed-series/index.ts @@ -0,0 +1,13 @@ +import 'chartist/dist/index.css'; +import { BarChart } from 'chartist'; + +new BarChart( + '#chart', + { + labels: ['XS', 'S', 'M', 'L', 'XL', 'XXL', 'XXXL'], + series: [20, 60, 120, 200, 180, 20, 10] + }, + { + distributeSeries: true + } +); diff --git a/sandboxes/bar/distributed-series/package.json b/sandboxes/bar/distributed-series/package.json new file mode 100644 index 000000000..a54b1f3f3 --- /dev/null +++ b/sandboxes/bar/distributed-series/package.json @@ -0,0 +1,8 @@ +{ + "name": "bar-distributed-series", + "description": "Distributed series", + "main": "index.ts", + "dependencies": { + "chartist": "^1.0.0" + } +} diff --git a/sandboxes/bar/distributed-series/sandbox.config.json b/sandboxes/bar/distributed-series/sandbox.config.json new file mode 100644 index 000000000..6c650a896 --- /dev/null +++ b/sandboxes/bar/distributed-series/sandbox.config.json @@ -0,0 +1,6 @@ +{ + "infiniteLoopProtection": true, + "hardReloadOnChange": true, + "view": "browser", + "template": "parcel" +} diff --git a/sandboxes/bar/extreme-responsive/index.html b/sandboxes/bar/extreme-responsive/index.html new file mode 100644 index 000000000..e650efa09 --- /dev/null +++ b/sandboxes/bar/extreme-responsive/index.html @@ -0,0 +1,9 @@ + + + + + + +
+ + diff --git a/sandboxes/bar/extreme-responsive/index.ts b/sandboxes/bar/extreme-responsive/index.ts new file mode 100644 index 000000000..037e846d5 --- /dev/null +++ b/sandboxes/bar/extreme-responsive/index.ts @@ -0,0 +1,63 @@ +import 'chartist/dist/index.css'; +import { BarChart, noop } from 'chartist'; + +new BarChart( + '#chart', + { + labels: ['Quarter 1', 'Quarter 2', 'Quarter 3', 'Quarter 4'], + series: [ + [5, 4, 3, 7], + [3, 2, 9, 5], + [1, 5, 8, 4], + [2, 3, 4, 6], + [4, 1, 2, 1] + ] + }, + { + // Default mobile configuration + stackBars: true, + axisX: { + labelInterpolationFnc: value => + String(value) + .split(/\s+/) + .map(word => word[0]) + .join('') + }, + axisY: { + offset: 20 + } + }, + [ + // Options override for media > 400px + [ + 'screen and (min-width: 400px)', + { + reverseData: true, + horizontalBars: true, + axisX: { + labelInterpolationFnc: noop + }, + axisY: { + offset: 60 + } + } + ], + // Options override for media > 800px + [ + 'screen and (min-width: 800px)', + { + stackBars: false, + seriesBarDistance: 10 + } + ], + // Options override for media > 1000px + [ + 'screen and (min-width: 1000px)', + { + reverseData: false, + horizontalBars: false, + seriesBarDistance: 15 + } + ] + ] +); diff --git a/sandboxes/bar/extreme-responsive/package.json b/sandboxes/bar/extreme-responsive/package.json new file mode 100644 index 000000000..b041e5bcc --- /dev/null +++ b/sandboxes/bar/extreme-responsive/package.json @@ -0,0 +1,8 @@ +{ + "name": "bar-extreme-responsive", + "description": "Extreme responsive configuration", + "main": "index.ts", + "dependencies": { + "chartist": "^1.0.0" + } +} diff --git a/sandboxes/bar/extreme-responsive/sandbox.config.json b/sandboxes/bar/extreme-responsive/sandbox.config.json new file mode 100644 index 000000000..6c650a896 --- /dev/null +++ b/sandboxes/bar/extreme-responsive/sandbox.config.json @@ -0,0 +1,6 @@ +{ + "infiniteLoopProtection": true, + "hardReloadOnChange": true, + "view": "browser", + "template": "parcel" +} diff --git a/sandboxes/bar/horizontal/index.html b/sandboxes/bar/horizontal/index.html new file mode 100644 index 000000000..e650efa09 --- /dev/null +++ b/sandboxes/bar/horizontal/index.html @@ -0,0 +1,9 @@ + + + + + + +
+ + diff --git a/sandboxes/bar/horizontal/index.ts b/sandboxes/bar/horizontal/index.ts new file mode 100644 index 000000000..ddc05c07e --- /dev/null +++ b/sandboxes/bar/horizontal/index.ts @@ -0,0 +1,29 @@ +import 'chartist/dist/index.css'; +import { BarChart } from 'chartist'; + +new BarChart( + '#chart', + { + labels: [ + 'Monday', + 'Tuesday', + 'Wednesday', + 'Thursday', + 'Friday', + 'Saturday', + 'Sunday' + ], + series: [ + [5, 4, 3, 7, 5, 10, 3], + [3, 2, 9, 5, 4, 6, 4] + ] + }, + { + seriesBarDistance: 10, + reverseData: true, + horizontalBars: true, + axisY: { + offset: 70 + } + } +); diff --git a/sandboxes/bar/horizontal/package.json b/sandboxes/bar/horizontal/package.json new file mode 100644 index 000000000..5be21ad8a --- /dev/null +++ b/sandboxes/bar/horizontal/package.json @@ -0,0 +1,8 @@ +{ + "name": "bar-horizontal", + "description": "Horizontal bar chart", + "main": "index.ts", + "dependencies": { + "chartist": "^1.0.0" + } +} diff --git a/sandboxes/bar/horizontal/sandbox.config.json b/sandboxes/bar/horizontal/sandbox.config.json new file mode 100644 index 000000000..6c650a896 --- /dev/null +++ b/sandboxes/bar/horizontal/sandbox.config.json @@ -0,0 +1,6 @@ +{ + "infiniteLoopProtection": true, + "hardReloadOnChange": true, + "view": "browser", + "template": "parcel" +} diff --git a/sandboxes/bar/label-position/index.html b/sandboxes/bar/label-position/index.html new file mode 100644 index 000000000..e650efa09 --- /dev/null +++ b/sandboxes/bar/label-position/index.html @@ -0,0 +1,9 @@ + + + + + + +
+ + diff --git a/sandboxes/bar/label-position/index.ts b/sandboxes/bar/label-position/index.ts new file mode 100644 index 000000000..f4b86ff3b --- /dev/null +++ b/sandboxes/bar/label-position/index.ts @@ -0,0 +1,23 @@ +import 'chartist/dist/index.css'; +import { BarChart } from 'chartist'; + +new BarChart( + '#chart', + { + labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], + series: [ + [5, 4, 3, 7, 5, 10, 3], + [3, 2, 9, 5, 4, 6, 4] + ] + }, + { + axisX: { + // On the x-axis start means top and end means bottom + position: 'start' + }, + axisY: { + // On the y-axis start means left and end means right + position: 'end' + } + } +); diff --git a/sandboxes/bar/label-position/package.json b/sandboxes/bar/label-position/package.json new file mode 100644 index 000000000..612164466 --- /dev/null +++ b/sandboxes/bar/label-position/package.json @@ -0,0 +1,8 @@ +{ + "name": "bar-label-position", + "description": "Label placement", + "main": "index.ts", + "dependencies": { + "chartist": "^1.0.0" + } +} diff --git a/sandboxes/bar/label-position/sandbox.config.json b/sandboxes/bar/label-position/sandbox.config.json new file mode 100644 index 000000000..6c650a896 --- /dev/null +++ b/sandboxes/bar/label-position/sandbox.config.json @@ -0,0 +1,6 @@ +{ + "infiniteLoopProtection": true, + "hardReloadOnChange": true, + "view": "browser", + "template": "parcel" +} diff --git a/sandboxes/bar/multiline/index.html b/sandboxes/bar/multiline/index.html new file mode 100644 index 000000000..e650efa09 --- /dev/null +++ b/sandboxes/bar/multiline/index.html @@ -0,0 +1,9 @@ + + + + + + +
+ + diff --git a/sandboxes/bar/multiline/index.ts b/sandboxes/bar/multiline/index.ts new file mode 100644 index 000000000..4acbd12ea --- /dev/null +++ b/sandboxes/bar/multiline/index.ts @@ -0,0 +1,30 @@ +import 'chartist/dist/index.css'; +import { BarChart } from 'chartist'; + +new BarChart( + '#chart', + { + labels: [ + 'First quarter of the year', + 'Second quarter of the year', + 'Third quarter of the year', + 'Fourth quarter of the year' + ], + series: [ + [60000, 40000, 80000, 70000], + [40000, 30000, 70000, 65000], + [8000, 3000, 10000, 6000] + ] + }, + { + seriesBarDistance: 10, + axisX: { + offset: 60 + }, + axisY: { + offset: 80, + labelInterpolationFnc: value => value + ' CHF', + scaleMinSpace: 15 + } + } +); diff --git a/sandboxes/bar/multiline/package.json b/sandboxes/bar/multiline/package.json new file mode 100644 index 000000000..8fb4b0908 --- /dev/null +++ b/sandboxes/bar/multiline/package.json @@ -0,0 +1,8 @@ +{ + "name": "bar-multiline", + "description": "Multi-line labels", + "main": "index.ts", + "dependencies": { + "chartist": "^1.0.0" + } +} diff --git a/sandboxes/bar/multiline/sandbox.config.json b/sandboxes/bar/multiline/sandbox.config.json new file mode 100644 index 000000000..6c650a896 --- /dev/null +++ b/sandboxes/bar/multiline/sandbox.config.json @@ -0,0 +1,6 @@ +{ + "infiniteLoopProtection": true, + "hardReloadOnChange": true, + "view": "browser", + "template": "parcel" +} diff --git a/sandboxes/bar/overlapping-bars/index.html b/sandboxes/bar/overlapping-bars/index.html new file mode 100644 index 000000000..e650efa09 --- /dev/null +++ b/sandboxes/bar/overlapping-bars/index.html @@ -0,0 +1,9 @@ + + + + + + +
+ + diff --git a/sandboxes/bar/overlapping-bars/index.ts b/sandboxes/bar/overlapping-bars/index.ts new file mode 100644 index 000000000..d6aba31f6 --- /dev/null +++ b/sandboxes/bar/overlapping-bars/index.ts @@ -0,0 +1,50 @@ +import 'chartist/dist/index.css'; +import { BarChart, BarChartOptions, ResponsiveOptions } from 'chartist'; + +const data = { + labels: [ + 'Jan', + 'Feb', + 'Mar', + 'Apr', + 'Mai', + 'Jun', + 'Jul', + 'Aug', + 'Sep', + 'Oct', + 'Nov', + 'Dec' + ], + series: [ + [5, 4, 3, 7, 5, 10, 3, 4, 8, 10, 6, 8], + [3, 2, 9, 5, 4, 6, 4, 6, 7, 8, 7, 4] + ] +}; + +const options = { + seriesBarDistance: 15 +}; + +const responsiveOptions: ResponsiveOptions = [ + [ + 'screen and (min-width: 641px) and (max-width: 1024px)', + { + seriesBarDistance: 10, + axisX: { + labelInterpolationFnc: value => value + } + } + ], + [ + 'screen and (max-width: 640px)', + { + seriesBarDistance: 5, + axisX: { + labelInterpolationFnc: value => String(value)[0] + } + } + ] +]; + +new BarChart('#chart', data, options, responsiveOptions); diff --git a/sandboxes/bar/overlapping-bars/package.json b/sandboxes/bar/overlapping-bars/package.json new file mode 100644 index 000000000..ca44fa845 --- /dev/null +++ b/sandboxes/bar/overlapping-bars/package.json @@ -0,0 +1,8 @@ +{ + "name": "bar-overlapping-bars", + "description": "Overlapping bars on mobile", + "main": "index.ts", + "dependencies": { + "chartist": "^1.0.0" + } +} diff --git a/sandboxes/bar/overlapping-bars/sandbox.config.json b/sandboxes/bar/overlapping-bars/sandbox.config.json new file mode 100644 index 000000000..6c650a896 --- /dev/null +++ b/sandboxes/bar/overlapping-bars/sandbox.config.json @@ -0,0 +1,6 @@ +{ + "infiniteLoopProtection": true, + "hardReloadOnChange": true, + "view": "browser", + "template": "parcel" +} diff --git a/sandboxes/bar/stacked-accumulate-relative/index.html b/sandboxes/bar/stacked-accumulate-relative/index.html new file mode 100644 index 000000000..e650efa09 --- /dev/null +++ b/sandboxes/bar/stacked-accumulate-relative/index.html @@ -0,0 +1,9 @@ + + + + + + +
+ + diff --git a/sandboxes/bar/stacked-accumulate-relative/index.ts b/sandboxes/bar/stacked-accumulate-relative/index.ts new file mode 100644 index 000000000..9157dca00 --- /dev/null +++ b/sandboxes/bar/stacked-accumulate-relative/index.ts @@ -0,0 +1,17 @@ +import 'chartist/dist/index.css'; +import { BarChart } from 'chartist'; + +new BarChart( + '#chart', + { + labels: ['Monday', 'Tuesday', 'Wednesday', 'Thursday'], + series: [ + [5, 4, -3, -5], + [5, -4, 3, -5] + ] + }, + { + stackBars: true, + stackMode: 'accumulate-relative' + } +); diff --git a/sandboxes/bar/stacked-accumulate-relative/package.json b/sandboxes/bar/stacked-accumulate-relative/package.json new file mode 100644 index 000000000..b51da0ef9 --- /dev/null +++ b/sandboxes/bar/stacked-accumulate-relative/package.json @@ -0,0 +1,8 @@ +{ + "name": "bar-stacked", + "description": "Stacked bar chart with accumulate-relative stack mode", + "main": "index.ts", + "dependencies": { + "chartist": "^1.0.0" + } +} diff --git a/sandboxes/bar/stacked-accumulate-relative/sandbox.config.json b/sandboxes/bar/stacked-accumulate-relative/sandbox.config.json new file mode 100644 index 000000000..6c650a896 --- /dev/null +++ b/sandboxes/bar/stacked-accumulate-relative/sandbox.config.json @@ -0,0 +1,6 @@ +{ + "infiniteLoopProtection": true, + "hardReloadOnChange": true, + "view": "browser", + "template": "parcel" +} diff --git a/sandboxes/bar/stacked/index.html b/sandboxes/bar/stacked/index.html new file mode 100644 index 000000000..e650efa09 --- /dev/null +++ b/sandboxes/bar/stacked/index.html @@ -0,0 +1,9 @@ + + + + + + +
+ + diff --git a/sandboxes/bar/stacked/index.ts b/sandboxes/bar/stacked/index.ts new file mode 100644 index 000000000..0046bde95 --- /dev/null +++ b/sandboxes/bar/stacked/index.ts @@ -0,0 +1,26 @@ +import 'chartist/dist/index.css'; +import { BarChart } from 'chartist'; + +new BarChart( + '#chart', + { + labels: ['Q1', 'Q2', 'Q3', 'Q4'], + series: [ + [800000, 1200000, 1400000, 1300000], + [200000, 400000, 500000, 300000], + [100000, 200000, 400000, 600000] + ] + }, + { + stackBars: true, + axisY: { + labelInterpolationFnc: value => +value / 1000 + 'k' + } + } +).on('draw', data => { + if (data.type === 'bar') { + data.element.attr({ + style: 'stroke-width: 30px' + }); + } +}); diff --git a/sandboxes/bar/stacked/package.json b/sandboxes/bar/stacked/package.json new file mode 100644 index 000000000..879605f64 --- /dev/null +++ b/sandboxes/bar/stacked/package.json @@ -0,0 +1,8 @@ +{ + "name": "bar-stacked", + "description": "Stacked bar chart", + "main": "index.ts", + "dependencies": { + "chartist": "^1.0.0" + } +} diff --git a/sandboxes/bar/stacked/sandbox.config.json b/sandboxes/bar/stacked/sandbox.config.json new file mode 100644 index 000000000..6c650a896 --- /dev/null +++ b/sandboxes/bar/stacked/sandbox.config.json @@ -0,0 +1,6 @@ +{ + "infiniteLoopProtection": true, + "hardReloadOnChange": true, + "view": "browser", + "template": "parcel" +} diff --git a/sandboxes/bar/with-circle-modify-drawing/index.html b/sandboxes/bar/with-circle-modify-drawing/index.html new file mode 100644 index 000000000..e650efa09 --- /dev/null +++ b/sandboxes/bar/with-circle-modify-drawing/index.html @@ -0,0 +1,9 @@ + + + + + + +
+ + diff --git a/sandboxes/bar/with-circle-modify-drawing/index.ts b/sandboxes/bar/with-circle-modify-drawing/index.ts new file mode 100644 index 000000000..444ede8ae --- /dev/null +++ b/sandboxes/bar/with-circle-modify-drawing/index.ts @@ -0,0 +1,37 @@ +import 'chartist/dist/index.css'; +import { BarChart, Svg, getMultiValue } from 'chartist'; + +// Create a simple bi-polar bar chart +const chart = new BarChart( + '#chart', + { + labels: ['W1', 'W2', 'W3', 'W4', 'W5', 'W6', 'W7', 'W8', 'W9', 'W10'], + series: [[1, 2, 4, 8, 6, -2, -1, -4, -6, -2]] + }, + { + high: 10, + low: -10, + axisX: { + labelInterpolationFnc: (value, index) => (index % 2 === 0 ? value : null) + } + } +); + +// Listen for draw events on the bar chart +chart.on('draw', data => { + // If this draw event is of type bar we can use the data to create additional content + if (data.type === 'bar') { + // We use the group element of the current series to append a simple circle with the bar peek coordinates and a circle radius that is depending on the value + data.group.append( + new Svg( + 'circle', + { + cx: data.x2, + cy: data.y2, + r: Math.abs(Number(getMultiValue(data.value))) * 2 + 5 + }, + 'ct-slice-pie' + ) + ); + } +}); diff --git a/sandboxes/bar/with-circle-modify-drawing/package.json b/sandboxes/bar/with-circle-modify-drawing/package.json new file mode 100644 index 000000000..ea4758805 --- /dev/null +++ b/sandboxes/bar/with-circle-modify-drawing/package.json @@ -0,0 +1,8 @@ +{ + "name": "bar-with-circle-modify-drawing", + "description": "Add peak circles using the draw events", + "main": "index.ts", + "dependencies": { + "chartist": "^1.0.0" + } +} diff --git a/sandboxes/bar/with-circle-modify-drawing/sandbox.config.json b/sandboxes/bar/with-circle-modify-drawing/sandbox.config.json new file mode 100644 index 000000000..6c650a896 --- /dev/null +++ b/sandboxes/bar/with-circle-modify-drawing/sandbox.config.json @@ -0,0 +1,6 @@ +{ + "infiniteLoopProtection": true, + "hardReloadOnChange": true, + "view": "browser", + "template": "parcel" +} diff --git a/sandboxes/line/area/index.html b/sandboxes/line/area/index.html new file mode 100644 index 000000000..e650efa09 --- /dev/null +++ b/sandboxes/line/area/index.html @@ -0,0 +1,9 @@ + + + + + + +
+ + diff --git a/sandboxes/line/area/index.ts b/sandboxes/line/area/index.ts new file mode 100644 index 000000000..11ea89883 --- /dev/null +++ b/sandboxes/line/area/index.ts @@ -0,0 +1,14 @@ +import 'chartist/dist/index.css'; +import { LineChart } from 'chartist'; + +new LineChart( + '#chart', + { + labels: [1, 2, 3, 4, 5, 6, 7, 8], + series: [[5, 9, 7, 8, 5, 3, 5, 4]] + }, + { + low: 0, + showArea: true + } +); diff --git a/sandboxes/line/area/package.json b/sandboxes/line/area/package.json new file mode 100644 index 000000000..c2096aa2c --- /dev/null +++ b/sandboxes/line/area/package.json @@ -0,0 +1,8 @@ +{ + "name": "line-area", + "description": "Line chart with area", + "main": "index.ts", + "dependencies": { + "chartist": "^1.0.0" + } +} diff --git a/sandboxes/line/area/sandbox.config.json b/sandboxes/line/area/sandbox.config.json new file mode 100644 index 000000000..6c650a896 --- /dev/null +++ b/sandboxes/line/area/sandbox.config.json @@ -0,0 +1,6 @@ +{ + "infiniteLoopProtection": true, + "hardReloadOnChange": true, + "view": "browser", + "template": "parcel" +} diff --git a/sandboxes/line/axis-auto/index.html b/sandboxes/line/axis-auto/index.html new file mode 100644 index 000000000..e650efa09 --- /dev/null +++ b/sandboxes/line/axis-auto/index.html @@ -0,0 +1,9 @@ + + + + + + +
+ + diff --git a/sandboxes/line/axis-auto/index.ts b/sandboxes/line/axis-auto/index.ts new file mode 100644 index 000000000..67a5d9ffd --- /dev/null +++ b/sandboxes/line/axis-auto/index.ts @@ -0,0 +1,23 @@ +import 'chartist/dist/index.css'; +import { LineChart, AutoScaleAxis } from 'chartist'; + +new LineChart( + '#chart', + { + series: [ + [ + { x: 1, y: 100 }, + { x: 2, y: 50 }, + { x: 3, y: 25 }, + { x: 5, y: 12.5 }, + { x: 8, y: 6.25 } + ] + ] + }, + { + axisX: { + type: AutoScaleAxis, + onlyInteger: true + } + } +); diff --git a/sandboxes/line/axis-auto/package.json b/sandboxes/line/axis-auto/package.json new file mode 100644 index 000000000..cd0f1f1ba --- /dev/null +++ b/sandboxes/line/axis-auto/package.json @@ -0,0 +1,8 @@ +{ + "name": "line-axis-auto", + "description": "Auto scale axis", + "main": "index.ts", + "dependencies": { + "chartist": "^1.0.0" + } +} diff --git a/sandboxes/line/axis-auto/sandbox.config.json b/sandboxes/line/axis-auto/sandbox.config.json new file mode 100644 index 000000000..6c650a896 --- /dev/null +++ b/sandboxes/line/axis-auto/sandbox.config.json @@ -0,0 +1,6 @@ +{ + "infiniteLoopProtection": true, + "hardReloadOnChange": true, + "view": "browser", + "template": "parcel" +} diff --git a/sandboxes/line/axis-fixed-and-auto/index.html b/sandboxes/line/axis-fixed-and-auto/index.html new file mode 100644 index 000000000..e650efa09 --- /dev/null +++ b/sandboxes/line/axis-fixed-and-auto/index.html @@ -0,0 +1,9 @@ + + + + + + +
+ + diff --git a/sandboxes/line/axis-fixed-and-auto/index.ts b/sandboxes/line/axis-fixed-and-auto/index.ts new file mode 100644 index 000000000..c0de94c8e --- /dev/null +++ b/sandboxes/line/axis-fixed-and-auto/index.ts @@ -0,0 +1,35 @@ +import 'chartist/dist/index.css'; +import { + LineChart, + AutoScaleAxis, + FixedScaleAxis, + Interpolation +} from 'chartist'; + +new LineChart( + '#chart', + { + series: [ + [ + { x: 1, y: 100 }, + { x: 2, y: 50 }, + { x: 3, y: 25 }, + { x: 5, y: 12.5 }, + { x: 8, y: 6.25 } + ] + ] + }, + { + axisX: { + type: AutoScaleAxis, + onlyInteger: true + }, + axisY: { + type: FixedScaleAxis, + ticks: [0, 50, 75, 87.5, 100], + low: 0 + }, + lineSmooth: Interpolation.step(), + showPoint: false + } +); diff --git a/sandboxes/line/axis-fixed-and-auto/package.json b/sandboxes/line/axis-fixed-and-auto/package.json new file mode 100644 index 000000000..078ce64ee --- /dev/null +++ b/sandboxes/line/axis-fixed-and-auto/package.json @@ -0,0 +1,8 @@ +{ + "name": "line-axis-fixed-and-auto", + "description": "Fixed and auto scale axis", + "main": "index.ts", + "dependencies": { + "chartist": "^1.0.0" + } +} diff --git a/sandboxes/line/axis-fixed-and-auto/sandbox.config.json b/sandboxes/line/axis-fixed-and-auto/sandbox.config.json new file mode 100644 index 000000000..6c650a896 --- /dev/null +++ b/sandboxes/line/axis-fixed-and-auto/sandbox.config.json @@ -0,0 +1,6 @@ +{ + "infiniteLoopProtection": true, + "hardReloadOnChange": true, + "view": "browser", + "template": "parcel" +} diff --git a/sandboxes/line/bipolar-area/index.html b/sandboxes/line/bipolar-area/index.html new file mode 100644 index 000000000..e650efa09 --- /dev/null +++ b/sandboxes/line/bipolar-area/index.html @@ -0,0 +1,9 @@ + + + + + + +
+ + diff --git a/sandboxes/line/bipolar-area/index.ts b/sandboxes/line/bipolar-area/index.ts new file mode 100644 index 000000000..da0aece3f --- /dev/null +++ b/sandboxes/line/bipolar-area/index.ts @@ -0,0 +1,27 @@ +import 'chartist/dist/index.css'; +import { LineChart } from 'chartist'; + +new LineChart( + '#chart', + { + labels: [1, 2, 3, 4, 5, 6, 7, 8], + series: [ + [1, 2, 3, 1, -2, 0, 1, 0], + [-2, -1, -2, -1, -2.5, -1, -2, -1], + [0, 0, 0, 1, 2, 2.5, 2, 1], + [2.5, 2, 1, 0.5, 1, 0.5, -1, -2.5] + ] + }, + { + high: 3, + low: -3, + showArea: true, + showLine: false, + showPoint: false, + fullWidth: true, + axisX: { + showLabel: false, + showGrid: false + } + } +); diff --git a/sandboxes/line/bipolar-area/package.json b/sandboxes/line/bipolar-area/package.json new file mode 100644 index 000000000..a5b53a724 --- /dev/null +++ b/sandboxes/line/bipolar-area/package.json @@ -0,0 +1,8 @@ +{ + "name": "line-bipolar-area", + "description": "Bi-polar Line chart with area only", + "main": "index.ts", + "dependencies": { + "chartist": "^1.0.0" + } +} diff --git a/sandboxes/line/bipolar-area/sandbox.config.json b/sandboxes/line/bipolar-area/sandbox.config.json new file mode 100644 index 000000000..6c650a896 --- /dev/null +++ b/sandboxes/line/bipolar-area/sandbox.config.json @@ -0,0 +1,6 @@ +{ + "infiniteLoopProtection": true, + "hardReloadOnChange": true, + "view": "browser", + "template": "parcel" +} diff --git a/sandboxes/line/data-fill-holes/index.html b/sandboxes/line/data-fill-holes/index.html new file mode 100644 index 000000000..e650efa09 --- /dev/null +++ b/sandboxes/line/data-fill-holes/index.html @@ -0,0 +1,9 @@ + + + + + + +
+ + diff --git a/sandboxes/line/data-fill-holes/index.ts b/sandboxes/line/data-fill-holes/index.ts new file mode 100644 index 000000000..93e57583b --- /dev/null +++ b/sandboxes/line/data-fill-holes/index.ts @@ -0,0 +1,50 @@ +import 'chartist/dist/index.css'; +import { LineChart, Interpolation } from 'chartist'; + +new LineChart( + '#chart', + { + labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], + series: [ + [5, 5, 10, 8, 7, 5, 4, null, null, null, 10, 10, 7, 8, 6, 9], + [ + 10, + 15, + null, + 12, + null, + 10, + 12, + 15, + null, + null, + 12, + null, + 14, + null, + null, + null + ], + [null, null, null, null, 3, 4, 1, 3, 4, 6, 7, 9, 5, null, null, null], + [ + { x: 3, y: 3 }, + { x: 4, y: 3 }, + { x: 5, y: undefined }, + { x: 6, y: 4 }, + { x: 7, y: null }, + { x: 8, y: 4 }, + { x: 9, y: 4 } + ] + ] + }, + { + fullWidth: true, + chartPadding: { + right: 10 + }, + lineSmooth: Interpolation.cardinal({ + fillHoles: true + }), + low: 0 + } +); diff --git a/sandboxes/line/data-fill-holes/package.json b/sandboxes/line/data-fill-holes/package.json new file mode 100644 index 000000000..0340ada5b --- /dev/null +++ b/sandboxes/line/data-fill-holes/package.json @@ -0,0 +1,8 @@ +{ + "name": "line-data-fill-holes", + "description": "Filled holes in data", + "main": "index.ts", + "dependencies": { + "chartist": "^1.0.0" + } +} diff --git a/sandboxes/line/data-fill-holes/sandbox.config.json b/sandboxes/line/data-fill-holes/sandbox.config.json new file mode 100644 index 000000000..6c650a896 --- /dev/null +++ b/sandboxes/line/data-fill-holes/sandbox.config.json @@ -0,0 +1,6 @@ +{ + "infiniteLoopProtection": true, + "hardReloadOnChange": true, + "view": "browser", + "template": "parcel" +} diff --git a/sandboxes/line/data-holes/index.html b/sandboxes/line/data-holes/index.html new file mode 100644 index 000000000..e650efa09 --- /dev/null +++ b/sandboxes/line/data-holes/index.html @@ -0,0 +1,9 @@ + + + + + + +
+ + diff --git a/sandboxes/line/data-holes/index.ts b/sandboxes/line/data-holes/index.ts new file mode 100644 index 000000000..1988e755a --- /dev/null +++ b/sandboxes/line/data-holes/index.ts @@ -0,0 +1,47 @@ +import 'chartist/dist/index.css'; +import { LineChart } from 'chartist'; + +new LineChart( + '#chart', + { + labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], + series: [ + [5, 5, 10, 8, 7, 5, 4, null, null, null, 10, 10, 7, 8, 6, 9], + [ + 10, + 15, + null, + 12, + null, + 10, + 12, + 15, + null, + null, + 12, + null, + 14, + null, + null, + null + ], + [null, null, null, null, 3, 4, 1, 3, 4, 6, 7, 9, 5, null, null, null], + [ + { x: 3, y: 3 }, + { x: 4, y: 3 }, + { x: 5, y: undefined }, + { x: 6, y: 4 }, + { x: 7, y: null }, + { x: 8, y: 4 }, + { x: 9, y: 4 } + ] + ] + }, + { + fullWidth: true, + chartPadding: { + right: 10 + }, + low: 0 + } +); diff --git a/sandboxes/line/data-holes/package.json b/sandboxes/line/data-holes/package.json new file mode 100644 index 000000000..5a762d94a --- /dev/null +++ b/sandboxes/line/data-holes/package.json @@ -0,0 +1,8 @@ +{ + "name": "line-data-holes", + "description": "Holes in data", + "main": "index.ts", + "dependencies": { + "chartist": "^1.0.0" + } +} diff --git a/sandboxes/line/data-holes/sandbox.config.json b/sandboxes/line/data-holes/sandbox.config.json new file mode 100644 index 000000000..6c650a896 --- /dev/null +++ b/sandboxes/line/data-holes/sandbox.config.json @@ -0,0 +1,6 @@ +{ + "infiniteLoopProtection": true, + "hardReloadOnChange": true, + "view": "browser", + "template": "parcel" +} diff --git a/sandboxes/line/modify-drawing/index.html b/sandboxes/line/modify-drawing/index.html new file mode 100644 index 000000000..e650efa09 --- /dev/null +++ b/sandboxes/line/modify-drawing/index.html @@ -0,0 +1,9 @@ + + + + + + +
+ + diff --git a/sandboxes/line/modify-drawing/index.ts b/sandboxes/line/modify-drawing/index.ts new file mode 100644 index 000000000..8586ad5b7 --- /dev/null +++ b/sandboxes/line/modify-drawing/index.ts @@ -0,0 +1,37 @@ +import 'chartist/dist/index.css'; +import { LineChart, Svg } from 'chartist'; + +const chart = new LineChart('#chart', { + labels: [1, 2, 3, 4, 5], + series: [[12, 9, 7, 8, 5]] +}); + +// Listening for draw events that get emitted by the Chartist chart +chart.on('draw', data => { + // If the draw event was triggered from drawing a point on the line chart + if (data.type === 'point') { + // We are creating a new path SVG element that draws a triangle around the point coordinates + const triangle = new Svg( + 'path', + { + d: [ + 'M', + data.x, + data.y - 15, + 'L', + data.x - 15, + data.y + 8, + 'L', + data.x + 15, + data.y + 8, + 'z' + ].join(' '), + style: 'fill-opacity: 1' + }, + 'ct-area' + ); + + // With data.element we get the Chartist SVG wrapper and we can replace the original point drawn by Chartist with our newly created triangle + data.element.replace(triangle); + } +}); diff --git a/sandboxes/line/modify-drawing/package.json b/sandboxes/line/modify-drawing/package.json new file mode 100644 index 000000000..80adf00ef --- /dev/null +++ b/sandboxes/line/modify-drawing/package.json @@ -0,0 +1,8 @@ +{ + "name": "line-modify-drawing", + "description": "Using events to replace graphics", + "main": "index.ts", + "dependencies": { + "chartist": "^1.0.0" + } +} diff --git a/sandboxes/line/modify-drawing/sandbox.config.json b/sandboxes/line/modify-drawing/sandbox.config.json new file mode 100644 index 000000000..6c650a896 --- /dev/null +++ b/sandboxes/line/modify-drawing/sandbox.config.json @@ -0,0 +1,6 @@ +{ + "infiniteLoopProtection": true, + "hardReloadOnChange": true, + "view": "browser", + "template": "parcel" +} diff --git a/sandboxes/line/only-integer/index.html b/sandboxes/line/only-integer/index.html new file mode 100644 index 000000000..e650efa09 --- /dev/null +++ b/sandboxes/line/only-integer/index.html @@ -0,0 +1,9 @@ + + + + + + +
+ + diff --git a/sandboxes/line/only-integer/index.ts b/sandboxes/line/only-integer/index.ts new file mode 100644 index 000000000..068e19f61 --- /dev/null +++ b/sandboxes/line/only-integer/index.ts @@ -0,0 +1,25 @@ +import 'chartist/dist/index.css'; +import { LineChart } from 'chartist'; + +new LineChart( + '#chart', + { + labels: [1, 2, 3, 4, 5, 6, 7, 8], + series: [ + [1, 2, 3, 1, -2, 0, 1, 0], + [-2, -1, -2, -1, -3, -1, -2, -1], + [0, 0, 0, 1, 2, 3, 2, 1], + [3, 2, 1, 0.5, 1, 0, -1, -3] + ] + }, + { + high: 3, + low: -3, + fullWidth: true, + // As this is axis specific we need to tell Chartist to use whole numbers only on the concerned axis + axisY: { + onlyInteger: true, + offset: 20 + } + } +); diff --git a/sandboxes/line/only-integer/package.json b/sandboxes/line/only-integer/package.json new file mode 100644 index 000000000..aa320238c --- /dev/null +++ b/sandboxes/line/only-integer/package.json @@ -0,0 +1,8 @@ +{ + "name": "line-only-integer", + "description": "Only whole numbers", + "main": "index.ts", + "dependencies": { + "chartist": "^1.0.0" + } +} diff --git a/sandboxes/line/only-integer/sandbox.config.json b/sandboxes/line/only-integer/sandbox.config.json new file mode 100644 index 000000000..6c650a896 --- /dev/null +++ b/sandboxes/line/only-integer/sandbox.config.json @@ -0,0 +1,6 @@ +{ + "infiniteLoopProtection": true, + "hardReloadOnChange": true, + "view": "browser", + "template": "parcel" +} diff --git a/sandboxes/line/path-animation/index.html b/sandboxes/line/path-animation/index.html new file mode 100644 index 000000000..e650efa09 --- /dev/null +++ b/sandboxes/line/path-animation/index.html @@ -0,0 +1,9 @@ + + + + + + +
+ + diff --git a/sandboxes/line/path-animation/index.ts b/sandboxes/line/path-animation/index.ts new file mode 100644 index 000000000..cdfe2d029 --- /dev/null +++ b/sandboxes/line/path-animation/index.ts @@ -0,0 +1,38 @@ +import 'chartist/dist/index.css'; +import { LineChart, easings } from 'chartist'; + +const chart = new LineChart( + '#chart', + { + labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], + series: [ + [1, 5, 2, 5, 4, 3], + [2, 3, 4, 8, 1, 2], + [5, 4, 3, 2, 1, 0.5] + ] + }, + { + low: 0, + showArea: true, + showPoint: false, + fullWidth: true + } +); + +chart.on('draw', data => { + if (data.type === 'line' || data.type === 'area') { + data.element.animate({ + d: { + begin: 2000 * data.index, + dur: 2000, + from: data.path + .clone() + .scale(1, 0) + .translate(0, data.chartRect.height()) + .stringify(), + to: data.path.clone().stringify(), + easing: easings.easeOutQuint + } + }); + } +}); diff --git a/sandboxes/line/path-animation/package.json b/sandboxes/line/path-animation/package.json new file mode 100644 index 000000000..7c583dd08 --- /dev/null +++ b/sandboxes/line/path-animation/package.json @@ -0,0 +1,8 @@ +{ + "name": "line-path-animation", + "description": "SVG Path animation", + "main": "index.ts", + "dependencies": { + "chartist": "^1.0.0" + } +} diff --git a/sandboxes/line/path-animation/sandbox.config.json b/sandboxes/line/path-animation/sandbox.config.json new file mode 100644 index 000000000..6c650a896 --- /dev/null +++ b/sandboxes/line/path-animation/sandbox.config.json @@ -0,0 +1,6 @@ +{ + "infiniteLoopProtection": true, + "hardReloadOnChange": true, + "view": "browser", + "template": "parcel" +} diff --git a/sandboxes/line/scatter-random/index.html b/sandboxes/line/scatter-random/index.html new file mode 100644 index 000000000..e650efa09 --- /dev/null +++ b/sandboxes/line/scatter-random/index.html @@ -0,0 +1,9 @@ + + + + + + +
+ + diff --git a/sandboxes/line/scatter-random/index.ts b/sandboxes/line/scatter-random/index.ts new file mode 100644 index 000000000..873266a81 --- /dev/null +++ b/sandboxes/line/scatter-random/index.ts @@ -0,0 +1,45 @@ +import 'chartist/dist/index.css'; +import { LineChart, times } from 'chartist'; + +const data = times(52).reduce<{ + labels: number[]; + series: number[][]; +}>( + (accData, _, index) => { + accData.labels.push(index + 1); + accData.series.forEach(series => { + series.push(Math.random() * 100); + }); + + return accData; + }, + { + labels: [], + series: times(4).map(() => []) + } +); + +new LineChart( + '#chart', + data, + { + showLine: false, + axisX: { + labelInterpolationFnc(value, index) { + return index % 13 === 0 ? 'W' + value : null; + } + } + }, + [ + [ + 'screen and (min-width: 640px)', + { + axisX: { + labelInterpolationFnc(value, index) { + return index % 4 === 0 ? 'W' + value : null; + } + } + } + ] + ] +); diff --git a/sandboxes/line/scatter-random/package.json b/sandboxes/line/scatter-random/package.json new file mode 100644 index 000000000..fe8e03683 --- /dev/null +++ b/sandboxes/line/scatter-random/package.json @@ -0,0 +1,8 @@ +{ + "name": "line-scatter-random", + "description": "Line scatter diagram with responsive settings", + "main": "index.ts", + "dependencies": { + "chartist": "^1.0.0" + } +} diff --git a/sandboxes/line/scatter-random/sandbox.config.json b/sandboxes/line/scatter-random/sandbox.config.json new file mode 100644 index 000000000..6c650a896 --- /dev/null +++ b/sandboxes/line/scatter-random/sandbox.config.json @@ -0,0 +1,6 @@ +{ + "infiniteLoopProtection": true, + "hardReloadOnChange": true, + "view": "browser", + "template": "parcel" +} diff --git a/sandboxes/line/series-override/index.html b/sandboxes/line/series-override/index.html new file mode 100644 index 000000000..e650efa09 --- /dev/null +++ b/sandboxes/line/series-override/index.html @@ -0,0 +1,9 @@ + + + + + + +
+ + diff --git a/sandboxes/line/series-override/index.ts b/sandboxes/line/series-override/index.ts new file mode 100644 index 000000000..273681bf9 --- /dev/null +++ b/sandboxes/line/series-override/index.ts @@ -0,0 +1,64 @@ +import 'chartist/dist/index.css'; +import { LineChart, Interpolation } from 'chartist'; + +new LineChart( + '#chart', + { + labels: ['1', '2', '3', '4', '5', '6', '7', '8'], + // Naming the series with the series object array notation + series: [ + { + name: 'series-1', + data: [5, 2, -4, 2, 0, -2, 5, -3] + }, + { + name: 'series-2', + data: [4, 3, 5, 3, 1, 3, 6, 4] + }, + { + name: 'series-3', + data: [2, 4, 3, 1, 4, 5, 3, 2] + } + ] + }, + { + fullWidth: true, + // Within the series options you can use the series names + // to specify configuration that will only be used for the + // specific series. + series: { + 'series-1': { + lineSmooth: Interpolation.step() + }, + 'series-2': { + lineSmooth: Interpolation.simple(), + showArea: true + }, + 'series-3': { + showPoint: false + } + } + }, + [ + // You can even use responsive configuration overrides to + // customize your series configuration even further! + [ + 'screen and (max-width: 320px)', + { + series: { + 'series-1': { + lineSmooth: Interpolation.none() + }, + 'series-2': { + lineSmooth: Interpolation.none(), + showArea: false + }, + 'series-3': { + lineSmooth: Interpolation.none(), + showPoint: true + } + } + } + ] + ] +); diff --git a/sandboxes/line/series-override/package.json b/sandboxes/line/series-override/package.json new file mode 100644 index 000000000..6a49f9f6a --- /dev/null +++ b/sandboxes/line/series-override/package.json @@ -0,0 +1,8 @@ +{ + "name": "line-series-override", + "description": "Series Overrides", + "main": "index.ts", + "dependencies": { + "chartist": "^1.0.0" + } +} diff --git a/sandboxes/line/series-override/sandbox.config.json b/sandboxes/line/series-override/sandbox.config.json new file mode 100644 index 000000000..6c650a896 --- /dev/null +++ b/sandboxes/line/series-override/sandbox.config.json @@ -0,0 +1,6 @@ +{ + "infiniteLoopProtection": true, + "hardReloadOnChange": true, + "view": "browser", + "template": "parcel" +} diff --git a/sandboxes/line/simple-responsive/index.html b/sandboxes/line/simple-responsive/index.html new file mode 100644 index 000000000..e650efa09 --- /dev/null +++ b/sandboxes/line/simple-responsive/index.html @@ -0,0 +1,9 @@ + + + + + + +
+ + diff --git a/sandboxes/line/simple-responsive/index.ts b/sandboxes/line/simple-responsive/index.ts new file mode 100644 index 000000000..156d7a5d8 --- /dev/null +++ b/sandboxes/line/simple-responsive/index.ts @@ -0,0 +1,44 @@ +import 'chartist/dist/index.css'; +import { LineChart, LineChartOptions, ResponsiveOptions } from 'chartist'; + +/* Add a basic data series with six labels and values */ +const data = { + labels: ['1', '2', '3', '4', '5', '6'], + series: [ + { + data: [1, 2, 3, 5, 8, 13] + } + ] +}; + +/* Set some base options (settings will override the default settings in js *see default settings*). We are adding a basic label interpolation function for the xAxis labels. */ +const options: LineChartOptions = { + axisX: { + labelInterpolationFnc: value => 'Calendar Week ' + value + } +}; + +/* Now we can specify multiple responsive settings that will override the base settings based on order and if the media queries match. In this example we are changing the visibility of dots and lines as well as use different label interpolations for space reasons. */ +const responsiveOptions: ResponsiveOptions = [ + [ + 'screen and (min-width: 641px) and (max-width: 1024px)', + { + showPoint: false, + axisX: { + labelInterpolationFnc: value => 'Week ' + value + } + } + ], + [ + 'screen and (max-width: 640px)', + { + showLine: false, + axisX: { + labelInterpolationFnc: value => 'W' + value + } + } + ] +]; + +/* Initialize the chart with the above settings */ +new LineChart('#chart', data, options, responsiveOptions); diff --git a/sandboxes/line/simple-responsive/package.json b/sandboxes/line/simple-responsive/package.json new file mode 100644 index 000000000..c24bbd011 --- /dev/null +++ b/sandboxes/line/simple-responsive/package.json @@ -0,0 +1,8 @@ +{ + "name": "line-simple-responsive", + "description": "Simple responsive options", + "main": "index.ts", + "dependencies": { + "chartist": "^1.0.0" + } +} diff --git a/sandboxes/line/simple-responsive/sandbox.config.json b/sandboxes/line/simple-responsive/sandbox.config.json new file mode 100644 index 000000000..6c650a896 --- /dev/null +++ b/sandboxes/line/simple-responsive/sandbox.config.json @@ -0,0 +1,6 @@ +{ + "infiniteLoopProtection": true, + "hardReloadOnChange": true, + "view": "browser", + "template": "parcel" +} diff --git a/sandboxes/line/simple-smoothing/index.html b/sandboxes/line/simple-smoothing/index.html new file mode 100644 index 000000000..e650efa09 --- /dev/null +++ b/sandboxes/line/simple-smoothing/index.html @@ -0,0 +1,9 @@ + + + + + + +
+ + diff --git a/sandboxes/line/simple-smoothing/index.ts b/sandboxes/line/simple-smoothing/index.ts new file mode 100644 index 000000000..15867255a --- /dev/null +++ b/sandboxes/line/simple-smoothing/index.ts @@ -0,0 +1,25 @@ +import 'chartist/dist/index.css'; +import { LineChart, Interpolation } from 'chartist'; + +new LineChart( + '#chart', + { + labels: [1, 2, 3, 4, 5], + series: [ + [1, 5, 10, 0, 1], + [10, 15, 0, 1, 2] + ] + }, + { + // Remove this configuration to see that chart rendered with cardinal spline interpolation + // Sometimes, on large jumps in data values, it's better to use simple smoothing. + lineSmooth: Interpolation.simple({ + divisor: 2 + }), + fullWidth: true, + chartPadding: { + right: 20 + }, + low: 0 + } +); diff --git a/sandboxes/line/simple-smoothing/package.json b/sandboxes/line/simple-smoothing/package.json new file mode 100644 index 000000000..df93f3676 --- /dev/null +++ b/sandboxes/line/simple-smoothing/package.json @@ -0,0 +1,8 @@ +{ + "name": "line-simple-smoothing", + "description": "Line Interpolation / Smoothing", + "main": "index.ts", + "dependencies": { + "chartist": "^1.0.0" + } +} diff --git a/sandboxes/line/simple-smoothing/sandbox.config.json b/sandboxes/line/simple-smoothing/sandbox.config.json new file mode 100644 index 000000000..6c650a896 --- /dev/null +++ b/sandboxes/line/simple-smoothing/sandbox.config.json @@ -0,0 +1,6 @@ +{ + "infiniteLoopProtection": true, + "hardReloadOnChange": true, + "view": "browser", + "template": "parcel" +} diff --git a/sandboxes/line/simple-svg-animation/index.html b/sandboxes/line/simple-svg-animation/index.html new file mode 100644 index 000000000..e650efa09 --- /dev/null +++ b/sandboxes/line/simple-svg-animation/index.html @@ -0,0 +1,9 @@ + + + + + + +
+ + diff --git a/sandboxes/line/simple-svg-animation/index.ts b/sandboxes/line/simple-svg-animation/index.ts new file mode 100644 index 000000000..80f18ce9e --- /dev/null +++ b/sandboxes/line/simple-svg-animation/index.ts @@ -0,0 +1,71 @@ +import 'chartist/dist/index.css'; +import { LineChart, easings } from 'chartist'; + +const chart = new LineChart( + '#chart', + { + labels: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'], + series: [ + [12, 4, 2, 8, 5, 4, 6, 2, 3, 3, 4, 6], + [4, 8, 9, 3, 7, 2, 10, 5, 8, 1, 7, 10] + ] + }, + { + low: 0, + showLine: false, + axisX: { + showLabel: false, + offset: 0 + }, + axisY: { + showLabel: false, + offset: 0 + } + } +); + +// Let's put a sequence number aside so we can use it in the event callbacks +let seq = 0; + +// Once the chart is fully created we reset the sequence +chart.on('created', () => { + seq = 0; +}); + +// On each drawn element by Chartist we use the Svg API to trigger SMIL animations +chart.on('draw', data => { + if (data.type === 'point') { + // If the drawn element is a line we do a simple opacity fade in. This could also be achieved using CSS3 animations. + data.element.animate({ + opacity: { + // The delay when we like to start the animation + begin: seq++ * 80, + // Duration of the animation + dur: 500, + // The value where the animation should start + from: 0, + // The value where it should end + to: 1 + }, + x1: { + begin: seq++ * 80, + dur: 500, + from: data.x - 100, + to: data.x, + // You can specify an easing function name or use easing functions from `easings` directly + easing: easings.easeOutQuart + } + }); + } +}); + +let timerId: any; + +// For the sake of the example we update the chart every time it's created with a delay of 8 seconds +chart.on('created', () => { + if (timerId) { + clearTimeout(timerId); + } + + timerId = setTimeout(chart.update.bind(chart), 8000); +}); diff --git a/sandboxes/line/simple-svg-animation/package.json b/sandboxes/line/simple-svg-animation/package.json new file mode 100644 index 000000000..fc71b8175 --- /dev/null +++ b/sandboxes/line/simple-svg-animation/package.json @@ -0,0 +1,8 @@ +{ + "name": "line-simple-svg-animation", + "description": "Simple SMIL Animations", + "main": "index.ts", + "dependencies": { + "chartist": "^1.0.0" + } +} diff --git a/sandboxes/line/simple-svg-animation/sandbox.config.json b/sandboxes/line/simple-svg-animation/sandbox.config.json new file mode 100644 index 000000000..6c650a896 --- /dev/null +++ b/sandboxes/line/simple-svg-animation/sandbox.config.json @@ -0,0 +1,6 @@ +{ + "infiniteLoopProtection": true, + "hardReloadOnChange": true, + "view": "browser", + "template": "parcel" +} diff --git a/sandboxes/line/simple/index.html b/sandboxes/line/simple/index.html new file mode 100644 index 000000000..e650efa09 --- /dev/null +++ b/sandboxes/line/simple/index.html @@ -0,0 +1,9 @@ + + + + + + +
+ + diff --git a/sandboxes/line/simple/index.ts b/sandboxes/line/simple/index.ts new file mode 100644 index 000000000..48606d211 --- /dev/null +++ b/sandboxes/line/simple/index.ts @@ -0,0 +1,20 @@ +import 'chartist/dist/index.css'; +import { LineChart } from 'chartist'; + +new LineChart( + '#chart', + { + labels: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'], + series: [ + [12, 9, 7, 8, 5], + [2, 1, 3.5, 7, 3], + [1, 3, 4, 5, 6] + ] + }, + { + fullWidth: true, + chartPadding: { + right: 40 + } + } +); diff --git a/sandboxes/line/simple/package.json b/sandboxes/line/simple/package.json new file mode 100644 index 000000000..1e1eb5625 --- /dev/null +++ b/sandboxes/line/simple/package.json @@ -0,0 +1,8 @@ +{ + "name": "line-simple", + "description": "Simple line chart", + "main": "index.ts", + "dependencies": { + "chartist": "^1.0.0" + } +} diff --git a/sandboxes/line/simple/sandbox.config.json b/sandboxes/line/simple/sandbox.config.json new file mode 100644 index 000000000..6c650a896 --- /dev/null +++ b/sandboxes/line/simple/sandbox.config.json @@ -0,0 +1,6 @@ +{ + "infiniteLoopProtection": true, + "hardReloadOnChange": true, + "view": "browser", + "template": "parcel" +} diff --git a/sandboxes/line/svg-animation/index.html b/sandboxes/line/svg-animation/index.html new file mode 100644 index 000000000..e650efa09 --- /dev/null +++ b/sandboxes/line/svg-animation/index.html @@ -0,0 +1,9 @@ + + + + + + +
+ + diff --git a/sandboxes/line/svg-animation/index.ts b/sandboxes/line/svg-animation/index.ts new file mode 100644 index 000000000..38744efa9 --- /dev/null +++ b/sandboxes/line/svg-animation/index.ts @@ -0,0 +1,142 @@ +import 'chartist/dist/index.css'; +import { LineChart } from 'chartist'; + +const chart = new LineChart( + '#chart', + { + labels: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'], + series: [ + [12, 9, 7, 8, 5, 4, 6, 2, 3, 3, 4, 6], + [4, 5, 3, 7, 3, 5, 5, 3, 4, 4, 5, 5], + [5, 3, 4, 5, 6, 3, 3, 4, 5, 6, 3, 4], + [3, 4, 5, 6, 7, 6, 4, 5, 6, 7, 6, 3] + ] + }, + { + low: 0 + } +); + +// Let's put a sequence number aside so we can use it in the event callbacks +let seq = 0; +const delays = 80; +const durations = 500; + +// Once the chart is fully created we reset the sequence +chart.on('created', () => { + seq = 0; +}); + +// On each drawn element by Chartist we use the Svg API to trigger SMIL animations +chart.on('draw', data => { + seq++; + + if (data.type === 'line') { + // If the drawn element is a line we do a simple opacity fade in. This could also be achieved using CSS3 animations. + data.element.animate({ + opacity: { + // The delay when we like to start the animation + begin: seq * delays + 1000, + // Duration of the animation + dur: durations, + // The value where the animation should start + from: 0, + // The value where it should end + to: 1 + } + }); + } else if (data.type === 'label' && data.axis.counterUnits.pos === 'x') { + data.element.animate({ + y: { + begin: seq * delays, + dur: durations, + from: data.y + 100, + to: data.y, + // We can specify an easing function from Svg.Easing + easing: 'easeOutQuart' + } + }); + } else if (data.type === 'label' && data.axis.counterUnits.pos === 'y') { + data.element.animate({ + x: { + begin: seq * delays, + dur: durations, + from: data.x - 100, + to: data.x, + easing: 'easeOutQuart' + } + }); + } else if (data.type === 'point') { + data.element.animate({ + x1: { + begin: seq * delays, + dur: durations, + from: data.x - 10, + to: data.x, + easing: 'easeOutQuart' + }, + x2: { + begin: seq * delays, + dur: durations, + from: data.x - 10, + to: data.x, + easing: 'easeOutQuart' + }, + opacity: { + begin: seq * delays, + dur: durations, + from: 0, + to: 1, + easing: 'easeOutQuart' + } + }); + } else if (data.type === 'grid') { + // Using data.axis we get x or y which we can use to construct our animation definition objects + const pos1Key = (data.axis.units.pos + + '1') as `${typeof data.axis.units.pos}1`; + const pos1Value = data[pos1Key]; + const pos1Animation = { + begin: seq * delays, + dur: durations, + from: pos1Value - 30, + to: pos1Value, + easing: 'easeOutQuart' as const + }; + + const pos2Key = (data.axis.units.pos + + '2') as `${typeof data.axis.units.pos}2`; + const pos2Value = data[pos2Key]; + const pos2Animation = { + begin: seq * delays, + dur: durations, + from: pos2Value - 100, + to: pos2Value, + easing: 'easeOutQuart' as const + }; + + const animations = { + [data.axis.units.pos + '1']: pos1Animation, + [data.axis.units.pos + '2']: pos2Animation, + opacity: { + begin: seq * delays, + dur: durations, + from: 0, + to: 1, + easing: 'easeOutQuart' as const + } + }; + + data.element.animate(animations); + } +}); + +let timerId: any; + +// For the sake of the example we update the chart every time it's created with a delay of 8 seconds +chart.on('created', () => { + if (timerId) { + clearTimeout(timerId); + } + + timerId = setTimeout(chart.update.bind(chart), 12000); +}); diff --git a/sandboxes/line/svg-animation/package.json b/sandboxes/line/svg-animation/package.json new file mode 100644 index 000000000..89e011a96 --- /dev/null +++ b/sandboxes/line/svg-animation/package.json @@ -0,0 +1,8 @@ +{ + "name": "line-svg-animation", + "description": "Advanced SMIL Animations", + "main": "index.ts", + "dependencies": { + "chartist": "^1.0.0" + } +} diff --git a/sandboxes/line/svg-animation/sandbox.config.json b/sandboxes/line/svg-animation/sandbox.config.json new file mode 100644 index 000000000..6c650a896 --- /dev/null +++ b/sandboxes/line/svg-animation/sandbox.config.json @@ -0,0 +1,6 @@ +{ + "infiniteLoopProtection": true, + "hardReloadOnChange": true, + "view": "browser", + "template": "parcel" +} diff --git a/sandboxes/line/timeseries/index.html b/sandboxes/line/timeseries/index.html new file mode 100644 index 000000000..e650efa09 --- /dev/null +++ b/sandboxes/line/timeseries/index.html @@ -0,0 +1,9 @@ + + + + + + +
+ + diff --git a/sandboxes/line/timeseries/index.ts b/sandboxes/line/timeseries/index.ts new file mode 100644 index 000000000..55c1fe1c2 --- /dev/null +++ b/sandboxes/line/timeseries/index.ts @@ -0,0 +1,44 @@ +import 'chartist/dist/index.css'; +import { LineChart, FixedScaleAxis } from 'chartist'; + +new LineChart( + '#chart', + { + series: [ + { + name: 'series-1', + data: [ + { x: new Date(143134652600), y: 53 }, + { x: new Date(143234652600), y: 40 }, + { x: new Date(143340052600), y: 45 }, + { x: new Date(143366652600), y: 40 }, + { x: new Date(143410652600), y: 20 }, + { x: new Date(143508652600), y: 32 }, + { x: new Date(143569652600), y: 18 }, + { x: new Date(143579652600), y: 11 } + ] + }, + { + name: 'series-2', + data: [ + { x: new Date(143134652600), y: 53 }, + { x: new Date(143234652600), y: 35 }, + { x: new Date(143334652600), y: 30 }, + { x: new Date(143384652600), y: 30 }, + { x: new Date(143568652600), y: 10 } + ] + } + ] + }, + { + axisX: { + type: FixedScaleAxis, + divisor: 5, + labelInterpolationFnc: value => + new Date(value).toLocaleString(undefined, { + month: 'short', + day: 'numeric' + }) + } + } +); diff --git a/sandboxes/line/timeseries/package.json b/sandboxes/line/timeseries/package.json new file mode 100644 index 000000000..d85348727 --- /dev/null +++ b/sandboxes/line/timeseries/package.json @@ -0,0 +1,8 @@ +{ + "name": "line-timeseries", + "description": "Timeseries", + "main": "index.ts", + "dependencies": { + "chartist": "^1.0.0" + } +} diff --git a/sandboxes/line/timeseries/sandbox.config.json b/sandboxes/line/timeseries/sandbox.config.json new file mode 100644 index 000000000..6c650a896 --- /dev/null +++ b/sandboxes/line/timeseries/sandbox.config.json @@ -0,0 +1,6 @@ +{ + "infiniteLoopProtection": true, + "hardReloadOnChange": true, + "view": "browser", + "template": "parcel" +} diff --git a/sandboxes/pie/custom-labels/index.html b/sandboxes/pie/custom-labels/index.html new file mode 100644 index 000000000..e650efa09 --- /dev/null +++ b/sandboxes/pie/custom-labels/index.html @@ -0,0 +1,9 @@ + + + + + + +
+ + diff --git a/sandboxes/pie/custom-labels/index.ts b/sandboxes/pie/custom-labels/index.ts new file mode 100644 index 000000000..4ac3ac652 --- /dev/null +++ b/sandboxes/pie/custom-labels/index.ts @@ -0,0 +1,32 @@ +import 'chartist/dist/index.css'; +import { PieChart, PieChartOptions, ResponsiveOptions } from 'chartist'; + +const data = { + labels: ['Bananas', 'Apples', 'Grapes'], + series: [20, 15, 40] +}; + +const options: PieChartOptions = { + labelInterpolationFnc: value => String(value)[0] +}; + +const responsiveOptions: ResponsiveOptions = [ + [ + 'screen and (min-width: 640px)', + { + chartPadding: 30, + labelOffset: 100, + labelDirection: 'explode', + labelInterpolationFnc: value => value + } + ], + [ + 'screen and (min-width: 1024px)', + { + labelOffset: 80, + chartPadding: 20 + } + ] +]; + +new PieChart('#chart', data, options, responsiveOptions); diff --git a/sandboxes/pie/custom-labels/package.json b/sandboxes/pie/custom-labels/package.json new file mode 100644 index 000000000..8f5ad0d4a --- /dev/null +++ b/sandboxes/pie/custom-labels/package.json @@ -0,0 +1,8 @@ +{ + "name": "pie-custom-labels", + "description": "Pie chart with custom labels", + "main": "index.ts", + "dependencies": { + "chartist": "^1.0.0" + } +} diff --git a/sandboxes/pie/custom-labels/sandbox.config.json b/sandboxes/pie/custom-labels/sandbox.config.json new file mode 100644 index 000000000..6c650a896 --- /dev/null +++ b/sandboxes/pie/custom-labels/sandbox.config.json @@ -0,0 +1,6 @@ +{ + "infiniteLoopProtection": true, + "hardReloadOnChange": true, + "view": "browser", + "template": "parcel" +} diff --git a/sandboxes/pie/donut-animation/index.html b/sandboxes/pie/donut-animation/index.html new file mode 100644 index 000000000..e650efa09 --- /dev/null +++ b/sandboxes/pie/donut-animation/index.html @@ -0,0 +1,9 @@ + + + + + + +
+ + diff --git a/sandboxes/pie/donut-animation/index.ts b/sandboxes/pie/donut-animation/index.ts new file mode 100644 index 000000000..ad0f809ad --- /dev/null +++ b/sandboxes/pie/donut-animation/index.ts @@ -0,0 +1,66 @@ +import 'chartist/dist/index.css'; +import { PieChart, easings, AnimationDefinition } from 'chartist'; + +const chart = new PieChart( + '#chart', + { + series: [10, 20, 50, 20, 5, 50, 15], + labels: [1, 2, 3, 4, 5, 6, 7] + }, + { + donut: true, + showLabel: false + } +); + +chart.on('draw', data => { + if (data.type === 'slice') { + // Get the total path length in order to use for dash array animation + const pathLength = data.element + .getNode() + .getTotalLength(); + + // Set a dasharray that matches the path length as prerequisite to animate dashoffset + data.element.attr({ + 'stroke-dasharray': pathLength + 'px ' + pathLength + 'px' + }); + + // Create animation definition while also assigning an ID to the animation for later sync usage + const animationDefinition: Record = { + 'stroke-dashoffset': { + id: 'anim' + data.index, + dur: 1000, + from: -pathLength + 'px', + to: '0px', + easing: easings.easeOutQuint, + // We need to use `fill: 'freeze'` otherwise our animation will fall back to initial (not visible) + fill: 'freeze' + } + }; + + // If this was not the first slice, we need to time the animation so that it uses the end sync event of the previous animation + if (data.index !== 0) { + animationDefinition['stroke-dashoffset'].begin = + 'anim' + (data.index - 1) + '.end'; + } + + // We need to set an initial value before the animation starts as we are not in guided mode which would do that for us + data.element.attr({ + 'stroke-dashoffset': -pathLength + 'px' + }); + + // We can't use guided mode as the animations need to rely on setting begin manually + data.element.animate(animationDefinition, false); + } +}); + +let timerId: any; + +// For the sake of the example we update the chart every time it's created with a delay of 8 seconds +chart.on('created', () => { + if (timerId) { + clearTimeout(timerId); + } + + timerId = setTimeout(chart.update.bind(chart), 10000); +}); diff --git a/sandboxes/pie/donut-animation/package.json b/sandboxes/pie/donut-animation/package.json new file mode 100644 index 000000000..abc678bf5 --- /dev/null +++ b/sandboxes/pie/donut-animation/package.json @@ -0,0 +1,8 @@ +{ + "name": "pie-donut-animation", + "description": "Animating a Donut with Svg.animate", + "main": "index.ts", + "dependencies": { + "chartist": "^1.0.0" + } +} diff --git a/sandboxes/pie/donut-animation/sandbox.config.json b/sandboxes/pie/donut-animation/sandbox.config.json new file mode 100644 index 000000000..6c650a896 --- /dev/null +++ b/sandboxes/pie/donut-animation/sandbox.config.json @@ -0,0 +1,6 @@ +{ + "infiniteLoopProtection": true, + "hardReloadOnChange": true, + "view": "browser", + "template": "parcel" +} diff --git a/sandboxes/pie/donut-chart/index.html b/sandboxes/pie/donut-chart/index.html new file mode 100644 index 000000000..e650efa09 --- /dev/null +++ b/sandboxes/pie/donut-chart/index.html @@ -0,0 +1,9 @@ + + + + + + +
+ + diff --git a/sandboxes/pie/donut-chart/index.ts b/sandboxes/pie/donut-chart/index.ts new file mode 100644 index 000000000..0b8c6d228 --- /dev/null +++ b/sandboxes/pie/donut-chart/index.ts @@ -0,0 +1,15 @@ +import 'chartist/dist/index.css'; +import { PieChart } from 'chartist'; + +new PieChart( + '#chart', + { + series: [20, 10, 30, 40] + }, + { + donut: true, + donutWidth: 60, + startAngle: 270, + showLabel: true + } +); diff --git a/sandboxes/pie/donut-chart/package.json b/sandboxes/pie/donut-chart/package.json new file mode 100644 index 000000000..a7d91bed9 --- /dev/null +++ b/sandboxes/pie/donut-chart/package.json @@ -0,0 +1,8 @@ +{ + "name": "pie-donut-chart", + "description": "Donut chart", + "main": "index.ts", + "dependencies": { + "chartist": "^1.0.0" + } +} diff --git a/sandboxes/pie/donut-chart/sandbox.config.json b/sandboxes/pie/donut-chart/sandbox.config.json new file mode 100644 index 000000000..6c650a896 --- /dev/null +++ b/sandboxes/pie/donut-chart/sandbox.config.json @@ -0,0 +1,6 @@ +{ + "infiniteLoopProtection": true, + "hardReloadOnChange": true, + "view": "browser", + "template": "parcel" +} diff --git a/sandboxes/pie/simple-gauge/index.html b/sandboxes/pie/simple-gauge/index.html new file mode 100644 index 000000000..e650efa09 --- /dev/null +++ b/sandboxes/pie/simple-gauge/index.html @@ -0,0 +1,9 @@ + + + + + + +
+ + diff --git a/sandboxes/pie/simple-gauge/index.ts b/sandboxes/pie/simple-gauge/index.ts new file mode 100644 index 000000000..563dd8289 --- /dev/null +++ b/sandboxes/pie/simple-gauge/index.ts @@ -0,0 +1,16 @@ +import 'chartist/dist/index.css'; +import { PieChart } from 'chartist'; + +new PieChart( + '#chart', + { + series: [20, 10, 30, 40] + }, + { + donut: true, + donutWidth: 60, + startAngle: 270, + total: 200, + showLabel: false + } +); diff --git a/sandboxes/pie/simple-gauge/package.json b/sandboxes/pie/simple-gauge/package.json new file mode 100644 index 000000000..769611bd6 --- /dev/null +++ b/sandboxes/pie/simple-gauge/package.json @@ -0,0 +1,8 @@ +{ + "name": "pie-simple-gauge", + "description": "Gauge chart", + "main": "index.ts", + "dependencies": { + "chartist": "^1.0.0" + } +} diff --git a/sandboxes/pie/simple-gauge/sandbox.config.json b/sandboxes/pie/simple-gauge/sandbox.config.json new file mode 100644 index 000000000..6c650a896 --- /dev/null +++ b/sandboxes/pie/simple-gauge/sandbox.config.json @@ -0,0 +1,6 @@ +{ + "infiniteLoopProtection": true, + "hardReloadOnChange": true, + "view": "browser", + "template": "parcel" +} diff --git a/sandboxes/pie/simple/index.html b/sandboxes/pie/simple/index.html new file mode 100644 index 000000000..e650efa09 --- /dev/null +++ b/sandboxes/pie/simple/index.html @@ -0,0 +1,9 @@ + + + + + + +
+ + diff --git a/sandboxes/pie/simple/index.ts b/sandboxes/pie/simple/index.ts new file mode 100644 index 000000000..4f56dfa5c --- /dev/null +++ b/sandboxes/pie/simple/index.ts @@ -0,0 +1,11 @@ +import 'chartist/dist/index.css'; +import { PieChart } from 'chartist'; + +const data = { + series: [5, 3, 4] +}; + +new PieChart('#chart', data, { + labelInterpolationFnc: value => + Math.round((+value / data.series.reduce((a, b) => a + b)) * 100) + '%' +}); diff --git a/sandboxes/pie/simple/package.json b/sandboxes/pie/simple/package.json new file mode 100644 index 000000000..93a1ee296 --- /dev/null +++ b/sandboxes/pie/simple/package.json @@ -0,0 +1,8 @@ +{ + "name": "pie-simple", + "description": "Simple pie chart", + "main": "index.ts", + "dependencies": { + "chartist": "^1.0.0" + } +} diff --git a/sandboxes/pie/simple/sandbox.config.json b/sandboxes/pie/simple/sandbox.config.json new file mode 100644 index 000000000..6c650a896 --- /dev/null +++ b/sandboxes/pie/simple/sandbox.config.json @@ -0,0 +1,6 @@ +{ + "infiniteLoopProtection": true, + "hardReloadOnChange": true, + "view": "browser", + "template": "parcel" +} diff --git a/sandboxes/tsconfig.json b/sandboxes/tsconfig.json new file mode 100644 index 000000000..b1bf825e0 --- /dev/null +++ b/sandboxes/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../tsconfig.json", + "compilerOptions": { + "baseUrl": ".", + "paths": { + "chartist": ["../src"] + } + }, + "include": ["."] +} diff --git a/scripts/styles.cjs b/scripts/styles.cjs new file mode 100755 index 000000000..951b91b76 --- /dev/null +++ b/scripts/styles.cjs @@ -0,0 +1,60 @@ +#!/usr/bin/env node + +const fs = require('fs').promises; +const path = require('path'); +const sass = require('sass'); +const postcss = require('postcss'); + +const { plugins } = require('../postcss.config.cjs'); +const pkg = require('../package.json'); + +const cwd = process.cwd(); +const input = process.argv[2]; +const output = pkg.style; +const sourceMapOutput = output.replace('.css', '.css.map'); + +async function compile() { + let styles; + + styles = sass.compile(input, { + sourceMap: true + }); + + styles.sourceMap.sources = styles.sourceMap.sources.map(_ => + _.replace(cwd, '') + ); + + styles = await postcss(plugins).process(styles.css, { + from: input, + to: output, + map: { + prev: styles.sourceMap + } + }); + + const map = styles.map.toString(); + const css = + styles.css + `\n/*# sourceMappingURL=${path.basename(sourceMapOutput)} */`; + + await fs.mkdir(path.dirname(output), { + recursive: true + }); + await Promise.all([ + fs.writeFile(output, css), + fs.writeFile(sourceMapOutput, map) + ]); +} + +async function copySrc() { + const srcDir = path.dirname(input); + const distDir = path.dirname(output); + const srcFiles = await fs.readdir(srcDir); + + await Promise.all( + srcFiles.map(file => + fs.copyFile(path.join(srcDir, file), path.join(distDir, file)) + ) + ); +} + +Promise.all([compile(), copySrc()]); diff --git a/source/.buildignore b/source/.buildignore deleted file mode 100644 index fc98b8eb5..000000000 --- a/source/.buildignore +++ /dev/null @@ -1 +0,0 @@ -*.coffee \ No newline at end of file diff --git a/source/404.html b/source/404.html deleted file mode 100644 index ec98e3c26..000000000 --- a/source/404.html +++ /dev/null @@ -1,157 +0,0 @@ - - - - - Page Not Found :( - - - -
-

Not found :(

-

Sorry, but the page you were trying to view does not exist.

-

It looks like this was the result of either:

-
    -
  • a mistyped address
  • -
  • an out-of-date link
  • -
- - -
- - diff --git a/source/images/chartist-guy.svg b/source/images/chartist-guy.svg deleted file mode 100755 index d2f338fac..000000000 --- a/source/images/chartist-guy.svg +++ /dev/null @@ -1,125 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/source/images/chartist-icon.svg b/source/images/chartist-icon.svg deleted file mode 100755 index 2f72bb41d..000000000 --- a/source/images/chartist-icon.svg +++ /dev/null @@ -1,28 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - diff --git a/source/robots.txt b/source/robots.txt deleted file mode 100644 index 941749507..000000000 --- a/source/robots.txt +++ /dev/null @@ -1,3 +0,0 @@ -# robotstxt.org - -User-agent: * diff --git a/source/scripts/chartist.bar.js b/source/scripts/chartist.bar.js deleted file mode 100644 index 7ebc9aeab..000000000 --- a/source/scripts/chartist.bar.js +++ /dev/null @@ -1,306 +0,0 @@ -/** - * The bar chart module of Chartist that can be used to draw unipolar or bipolar bar and grouped bar charts. - * - * @module Chartist.Bar - */ -/* global Chartist */ -(function(window, document, Chartist){ - 'use strict'; - - /** - * This method creates a new bar chart and returns an object handle with delegations to the internal closure of the bar chart. You can use the returned object to redraw the chart. - * - * @memberof Chartist.Bar - * @param {String|Node} query A selector query string or directly a DOM element - * @param {Object} data The data object that needs to consist of a labels and a series array - * @param {Object} [options] The options object with options that override the default options. Check the examples for a detailed list. - * @param {Array} [responsiveOptions] Specify an array of responsive option arrays which are a media query and options object pair => [[mediaQueryString, optionsObject],[more...]] - * @return {Object} An object with a version and an update method to manually redraw the chart - * - * @example - * // These are the default options of the line chart - * var options = { - * // Options for X-Axis - * axisX: { - * // The offset of the labels to the chart area - * offset: 10, - * // If labels should be shown or not - * showLabel: true, - * // If the axis grid should be drawn or not - * showGrid: true, - * // Interpolation function that allows you to intercept the value from the axis label - * labelInterpolationFnc: function(value){return value;} - * }, - * // Options for Y-Axis - * axisY: { - * // The offset of the labels to the chart area - * offset: 15, - * // If labels should be shown or not - * showLabel: true, - * // If the axis grid should be drawn or not - * showGrid: true, - * // For the Y-Axis you can set a label alignment property of right or left - * labelAlign: 'right', - * // Interpolation function that allows you to intercept the value from the axis label - * labelInterpolationFnc: function(value){return value;}, - * // This value specifies the minimum height in pixel of the scale steps - * scaleMinSpace: 30 - * }, - * // Specify a fixed width for the chart as a string (i.e. '100px' or '50%') - * width: undefined, - * // Specify a fixed height for the chart as a string (i.e. '100px' or '50%') - * height: undefined, - * // If the line should be drawn or not - * showLine: true, - * // If dots should be drawn or not - * showPoint: true, - * // Specify if the lines should be smoothed (Catmull-Rom-Splines will be used) - * lineSmooth: true, - * // Overriding the natural low of the chart allows you to zoom in or limit the charts lowest displayed value - * low: undefined, - * // Overriding the natural high of the chart allows you to zoom in or limit the charts highest displayed value - * high: undefined, - * // Padding of the chart drawing area to the container element and labels - * chartPadding: 5, - * // Specify the distance in pixel of bars in a group - * seriesBarDistance: 15, - * // Override the class names that get used to generate the SVG structure of the chart - * classNames: { - * chart: 'ct-chart-bar', - * label: 'ct-label', - * series: 'ct-series', - * bar: 'ct-bar', - * point: 'ct-point', - * grid: 'ct-grid', - * vertical: 'ct-vertical', - * horizontal: 'ct-horizontal' - * } - * }; - * - * @example - * // Create a simple bar chart - * var data = { - * labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'], - * series: [ - * [5, 2, 4, 2, 0] - * ] - * }; - * - * // In the global name space Chartist we call the Bar function to initialize a bar chart. As a first parameter we pass in a selector where we would like to get our chart created and as a second parameter we pass our data object. - * Chartist.Bar('.ct-chart', data); - * - * @example - * // This example creates a bipolar grouped bar chart where the boundaries are limitted to -10 and 10 - * Chartist.Bar('.ct-chart', { - * labels: [1, 2, 3, 4, 5, 6, 7], - * series: [ - * [1, 3, 2, -5, -3, 1, -6], - * [-5, -2, -4, -1, 2, -3, 1] - * ] - * }, { - * seriesBarDistance: 12, - * low: -10, - * heigh: 10 - * }); - * - */ - Chartist.Bar = function (query, data, options, responsiveOptions) { - - var defaultOptions = { - axisX: { - offset: 10, - showLabel: true, - showGrid: true, - labelInterpolationFnc: Chartist.noop - }, - axisY: { - offset: 15, - showLabel: true, - showGrid: true, - labelAlign: 'right', - labelInterpolationFnc: Chartist.noop, - scaleMinSpace: 40 - }, - width: undefined, - height: undefined, - high: undefined, - low: undefined, - chartPadding: 5, - seriesBarDistance: 15, - classNames: { - chart: 'ct-chart-bar', - label: 'ct-label', - series: 'ct-series', - bar: 'ct-bar', - thin: 'ct-thin', - thick: 'ct-thick', - grid: 'ct-grid', - vertical: 'ct-vertical', - horizontal: 'ct-horizontal' - } - }, - optionsProvider, - container = Chartist.querySelector(query), - svg; - - function createChart(options) { - var xAxisOffset, - yAxisOffset, - seriesGroups = [], - bounds, - normalizedData = Chartist.normalizeDataArray(Chartist.getDataArray(data), data.labels.length); - - // Create new svg element - svg = Chartist.createSvg(container, options.width, options.height, options.classNames.chart); - - // initialize bounds - bounds = Chartist.getBounds(svg, normalizedData, options, 0); - - xAxisOffset = options.axisX.offset; - if (options.axisX.showLabel) { - xAxisOffset += Chartist.calculateLabelOffset( - svg, - data.labels, - [options.classNames.label, options.classNames.horizontal].join(' '), - options.axisX.labelInterpolationFnc, - Chartist.getHeight - ); - } - - yAxisOffset = options.axisY.offset; - if (options.axisY.showLabel) { - yAxisOffset += Chartist.calculateLabelOffset( - svg, - bounds.values, - [options.classNames.label, options.classNames.horizontal].join(' '), - options.axisY.labelInterpolationFnc, - Chartist.getWidth - ); - } - - var chartRect = Chartist.createChartRect(svg, options, xAxisOffset, yAxisOffset); - // Start drawing - var labels = svg.elem('g'), - grid = svg.elem('g'), - // Projected 0 point - zeroPoint = Chartist.projectPoint(chartRect, bounds, [0], 0); - - Chartist.createXAxis(chartRect, data, grid, labels, options); - Chartist.createYAxis(chartRect, bounds, grid, labels, yAxisOffset, options); - - // Draw the series - // initialize series groups - for (var i = 0; i < data.series.length; i++) { - // Calculating bi-polar value of index for seriesOffset. For i = 0..4 biPol will be -1.5, -0.5, 0.5, 1.5 etc. - var biPol = i - (data.series.length - 1) / 2, - // Half of the period with between vertical grid lines used to position bars - periodHalfWidth = chartRect.width() / normalizedData[i].length / 2; - - seriesGroups[i] = svg.elem('g'); - - // If the series is an object and contains a name we add a custom attribute - if(data.series[i].name) { - seriesGroups[i].attr({ - 'series-name': data.series[i].name - }, Chartist.xmlNs.uri); - } - - // Use series class from series data or if not set generate one - seriesGroups[i].addClass([ - options.classNames.series, - (data.series[i].className || options.classNames.series + '-' + Chartist.alphaNumerate(i)) - ].join(' ')); - - for(var j = 0; j < normalizedData[i].length; j++) { - var p = Chartist.projectPoint(chartRect, bounds, normalizedData[i], j), - bar; - - // Offset to center bar between grid lines and using bi-polar offset for multiple series - // TODO: Check if we should really be able to add classes to the series. Should be handles with SASS and semantic / specific selectors - p.x += periodHalfWidth + (biPol * options.seriesBarDistance); - - bar = seriesGroups[i].elem('line', { - x1: p.x, - y1: zeroPoint.y, - x2: p.x, - y2: p.y - }, options.classNames.bar).attr({ - 'value': normalizedData[i][j] - }, Chartist.xmlNs.uri); - } - } - } - - /** - * Updates the chart which currently does a full reconstruction of the SVG DOM - * - * @memberof Chartist.Bar - * - */ - function update() { - createChart(optionsProvider.currentOptions); - } - - /** - * This method will detach the chart from any event listeners that have been added. This includes window.resize and media query listeners for the responsive options. Call this method in order to de-initialize dynamically created / removed charts. - * - * @memberof Chartist.Bar - */ - function detach() { - window.removeEventListener('resize', update); - optionsProvider.clear(); - } - - /** - * Add a listener for the responsive options updates. Once the chart will switch to a new option set the listener will be called with the new options. - * - * @memberof Chartist.Bar - * @param {Function} callback Callback function that will have the new options as first parameter - */ - function addOptionsListener(callback) { - optionsProvider.addOptionsListener(callback); - } - - /** - * Remove a responsive options listener that was previously added using the addOptionsListener method. - * - * @memberof Chartist.Bar - * @param {Function} callback The callback function that was registered earlier with addOptionsListener - */ - function removeOptionsListener(callback) { - optionsProvider.removeOptionsListener(callback); - } - - // If this container already contains chartist, let's try to detach first and unregister all event listeners - if(container.chartist) { - container.chartist.detach(); - } - - // Obtain current options based on matching media queries (if responsive options are given) - // This will also register a listener that is re-creating the chart based on media changes - optionsProvider = Chartist.optionsProvider(defaultOptions, options, responsiveOptions); - createChart(optionsProvider.currentOptions); - - // TODO: Currently we need to re-draw the chart on window resize. This is usually very bad and will affect performance. - // This is done because we can't work with relative coordinates when drawing the chart because SVG Path does not - // work with relative positions yet. We need to check if we can do a viewBox hack to switch to percentage. - // See http://mozilla.6506.n7.nabble.com/Specyfing-paths-with-percentages-unit-td247474.html - // Update: can be done using the above method tested here: http://codepen.io/gionkunz/pen/KDvLj - // The problem is with the label offsets that can't be converted into percentage and affecting the chart container - window.addEventListener('resize', update); - - // Public members - var api = { - version: Chartist.version, - update: update, - detach: detach, - addOptionsListener: addOptionsListener, - removeOptionsListener: removeOptionsListener - }; - - container.chartist = api; - - return api; - }; - -}(window, document, Chartist)); diff --git a/source/scripts/chartist.core.js b/source/scripts/chartist.core.js deleted file mode 100644 index 55aa63807..000000000 --- a/source/scripts/chartist.core.js +++ /dev/null @@ -1,613 +0,0 @@ -/** - * The core module of Chartist that is mainly providing static functions and higher level functions for chart modules. - * - * @module Chartist.Core - */ -var Chartist = {}; -Chartist.version = '0.1.14'; - -(function (window, document, Chartist) { - 'use strict'; - - /** - * Helps to simplify functional style code - * - * @memberof Chartist.Core - * @param {*} n This exact value will be returned by the noop function - * @return {*} The same value that was provided to the n parameter - */ - Chartist.noop = function (n) { - return n; - }; - - /** - * Generates a-z from a number 0 to 26 - * - * @memberof Chartist.Core - * @param {Number} n A number from 0 to 26 that will result in a letter a-z - * @return {String} A character from a-z based on the input number n - */ - Chartist.alphaNumerate = function (n) { - // Limit to a-z - return String.fromCharCode(97 + n % 26); - }; - - /** - * Simple recursive object extend - * - * @memberof Chartist.Core - * @param {Object} target Target object where the source will be merged into - * @param {Object} source This object will be merged into target and then target is returned - * @return {Object} An object that has the same reference as target but is extended and merged with the properties of source - */ - Chartist.extend = function (target, source) { - target = target || {}; - for (var prop in source) { - if (typeof source[prop] === 'object') { - target[prop] = Chartist.extend(target[prop], source[prop]); - } else { - target[prop] = source[prop]; - } - } - return target; - }; - - //TODO: move into Chartist.svg - /** - * Get element height with fallback to svg BoundingBox or parent container dimensions: - * See [bugzilla.mozilla.org](https://bugzilla.mozilla.org/show_bug.cgi?id=530985) - * - * @memberof Chartist.Core - * @param {Node} svgElement The svg element from which we want to retrieve its height - * @return {Number} The elements height in pixels - */ - Chartist.getHeight = function (svgElement) { - return svgElement.clientHeight || Math.round(svgElement.getBBox().height) || svgElement.parentNode.clientHeight; - }; - - //TODO: move into Chartist.svg - /** - * Get element width with fallback to svg BoundingBox or parent container dimensions: - * See [bugzilla.mozilla.org](https://bugzilla.mozilla.org/show_bug.cgi?id=530985) - * - * @memberof Chartist.Core - * @param {Node} svgElement The svg element from which we want to retrieve its width - * @return {Number} The elements width in pixels - */ - Chartist.getWidth = function (svgElement) { - return svgElement.clientWidth || Math.round(svgElement.getBBox().width) || svgElement.parentNode.clientWidth; - }; - - /** - * This is a wrapper around document.querySelector that will return the query if it's already of type Node - * - * @memberof Chartist.Core - * @param {String|Node} query The query to use for selecting a Node or a DOM node that will be returned directly - * @return {Node} - */ - Chartist.querySelector = function(query) { - return query instanceof Node ? query : document.querySelector(query); - }; - - /** - * Create or reinitialize the SVG element for the chart - * - * @memberof Chartist.Core - * @param {Node} container The containing DOM Node object that will be used to plant the SVG element - * @param {String} width Set the width of the SVG element. Default is 100% - * @param {String} height Set the height of the SVG element. Default is 100% - * @param {String} className Specify a class to be added to the SVG element - * @return {Object} The created/reinitialized SVG element - */ - Chartist.createSvg = function (container, width, height, className) { - var svg; - - // If already contains our svg object we clear it, set width / height and return - if (container.chartistSvg !== undefined) { - svg = container.chartistSvg.attr({ - width: width || '100%', - height: height || '100%' - }).removeAllClasses().addClass(className); - // Clear the draw if its already used before so we start fresh - svg.empty(); - - } else { - // Create svg object with width and height or use 100% as default - svg = Chartist.svg('svg').attr({ - width: width || '100%', - height: height || '100%' - }).addClass(className); - - // Add the DOM node to our container - container.appendChild(svg._node); - container.chartistSvg = svg; - } - - return svg; - }; - - /** - * Convert data series into plain array - * - * @memberof Chartist.Core - * @param {Object} data The series object that contains the data to be visualized in the chart - * @return {Array} A plain array that contains the data to be visualized in the chart - */ - Chartist.getDataArray = function (data) { - var array = []; - - for (var i = 0; i < data.series.length; i++) { - // If the series array contains an object with a data property we will use the property - // otherwise the value directly (array or number) - array[i] = typeof(data.series[i]) === 'object' && data.series[i].data !== undefined ? - data.series[i].data : data.series[i]; - } - - return array; - }; - - /** - * Adds missing values at the end of the array. This array contains the data, that will be visualized in the chart - * - * @memberof Chartist.Core - * @param {Array} dataArray The array that contains the data to be visualized in the chart. The array in this parameter will be modified by function. - * @param {Number} length The length of the x-axis data array. - * @return {Array} The array that got updated with missing values. - */ - Chartist.normalizeDataArray = function (dataArray, length) { - for (var i = 0; i < dataArray.length; i++) { - if (dataArray[i].length === length) { - continue; - } - - for (var j = dataArray[i].length; j < length; j++) { - dataArray[i][j] = 0; - } - } - - return dataArray; - }; - - /** - * Calculate the order of magnitude for the chart scale - * - * @memberof Chartist.Core - * @param {Number} value The value Range of the chart - * @return {Number} The order of magnitude - */ - Chartist.orderOfMagnitude = function (value) { - return Math.floor(Math.log(Math.abs(value)) / Math.LN10); - }; - - /** - * Project a data length into screen coordinates (pixels) - * - * @memberof Chartist.Core - * @param {Object} svg The svg element for the chart - * @param {Number} length Single data value from a series array - * @param {Object} bounds All the values to set the bounds of the chart - * @param {Object} options The Object that contains all the optional values for the chart - * @return {Number} The projected data length in pixels - */ - Chartist.projectLength = function (svg, length, bounds, options) { - var availableHeight = Chartist.getAvailableHeight(svg, options); - return (length / bounds.range * availableHeight); - }; - - /** - * Get the height of the area in the chart for the data series - * - * @memberof Chartist.Core - * @param {Object} svg The svg element for the chart - * @param {Object} options The Object that contains all the optional values for the chart - * @return {Number} The height of the area in the chart for the data series - */ - Chartist.getAvailableHeight = function (svg, options) { - return Chartist.getHeight(svg._node) - (options.chartPadding * 2) - options.axisX.offset; - }; - - /** - * Get highest and lowest value of data array. This Array contains the data that will be visualized in the chart. - * - * @memberof Chartist.Core - * @param {Array} dataArray The array that contains the data to be visualized in the chart - * @return {Array} The array that contains the highest and lowest value that will be visualized on the chart. - */ - Chartist.getHighLow = function (dataArray) { - var i, - j, - highLow = { - high: -Number.MAX_VALUE, - low: Number.MAX_VALUE - }; - - for (i = 0; i < dataArray.length; i++) { - for (j = 0; j < dataArray[i].length; j++) { - if (dataArray[i][j] > highLow.high) { - highLow.high = dataArray[i][j]; - } - - if (dataArray[i][j] < highLow.low) { - highLow.low = dataArray[i][j]; - } - } - } - - return highLow; - }; - - // Find the highest and lowest values in a two dimensional array and calculate scale based on order of magnitude - /** - * Calculate and retrieve all the bounds for the chart and return them in one array - * - * @memberof Chartist.Core - * @param {Object} svg The svg element for the chart - * @param {Array} normalizedData The array that got updated with missing values. - * @param {Object} options The Object that contains all the optional values for the chart - * @param {Number} referenceValue The reference value for the chart. - * @return {Object} All the values to set the bounds of the chart - */ - Chartist.getBounds = function (svg, normalizedData, options, referenceValue) { - var i, - newMin, - newMax, - bounds = Chartist.getHighLow(normalizedData); - - // Overrides of high / low from settings - bounds.high = options.high || (options.high === 0 ? 0 : bounds.high); - bounds.low = options.low || (options.low === 0 ? 0 : bounds.low); - - // If high and low are the same because of misconfiguration or flat data (only the same value) we need - // to set the high or low to 0 depending on the polarity - if(bounds.high === bounds.low) { - // If both values are 0 we set high to 1 - if(bounds.low === 0) { - bounds.high = 1; - } else if(bounds.low < 0) { - // If we have the same negative value for the bounds we set bounds.high to 0 - bounds.high = 0; - } else { - // If we have the same positive value for the bounds we set bounds.low to 0 - bounds.low = 0; - } - } - - // Overrides of high / low based on reference value, it will make sure that the invisible reference value is - // used to generate the chart. This is useful when the chart always needs to contain the position of the - // invisible reference value in the view i.e. for bipolar scales. - if (referenceValue || referenceValue === 0) { - bounds.high = Math.max(referenceValue, bounds.high); - bounds.low = Math.min(referenceValue, bounds.low); - } - - bounds.valueRange = bounds.high - bounds.low; - bounds.oom = Chartist.orderOfMagnitude(bounds.valueRange); - bounds.min = Math.floor(bounds.low / Math.pow(10, bounds.oom)) * Math.pow(10, bounds.oom); - bounds.max = Math.ceil(bounds.high / Math.pow(10, bounds.oom)) * Math.pow(10, bounds.oom); - bounds.range = bounds.max - bounds.min; - bounds.step = Math.pow(10, bounds.oom); - bounds.numberOfSteps = Math.round(bounds.range / bounds.step); - - // Optimize scale step by checking if subdivision is possible based on horizontalGridMinSpace - while (true) { - var length = Chartist.projectLength(svg, bounds.step / 2, bounds, options); - if (length >= options.axisY.scaleMinSpace) { - bounds.step /= 2; - } else { - break; - } - } - - // Narrow min and max based on new step - newMin = bounds.min; - newMax = bounds.max; - for (i = bounds.min; i <= bounds.max; i += bounds.step) { - if (i + bounds.step < bounds.low) { - newMin += bounds.step; - } - - if (i - bounds.step > bounds.high) { - newMax -= bounds.step; - } - } - bounds.min = newMin; - bounds.max = newMax; - bounds.range = bounds.max - bounds.min; - - bounds.values = []; - for (i = bounds.min; i <= bounds.max; i += bounds.step) { - bounds.values.push(i); - } - - return bounds; - }; - - /** - * Calculate the needed offset to fit in the labels - * - * @memberof Chartist.Core - * @param {Object} svg The svg element for the chart - * @param {Array} data The array that contains the data to be visualized in the chart - * @param {Object} labelClass All css classes of the label - * @param {Function} labelInterpolationFnc The function that interpolates the label value - * @param {Function} offsetFnc Function to find greatest value of either the width or the height of the label, depending on the context - * @return {Number} The number that represents the label offset in pixels - */ - Chartist.calculateLabelOffset = function (svg, data, labelClass, labelInterpolationFnc, offsetFnc) { - var offset = 0; - for (var i = 0; i < data.length; i++) { - // If interpolation function returns falsy value we skipp this label - var interpolated = labelInterpolationFnc(data[i], i); - if (!interpolated && interpolated !== 0) { - continue; - } - - var label = svg.elem('text', { - dx: 0, - dy: 0 - }, labelClass).text('' + interpolated); - - // Check if this is the largest label and update offset - offset = Math.max(offset, offsetFnc(label._node)); - // Remove label after offset Calculation - label.remove(); - } - - return offset; - }; - - /** - * Calculate cartesian coordinates of polar coordinates - * - * @memberof Chartist.Core - * @param {Number} centerX X-axis coordinates of center point of circle segment - * @param {Number} centerY X-axis coordinates of center point of circle segment - * @param {Number} radius Radius of circle segment - * @param {Number} angleInDegrees Angle of circle segment in degrees - * @return {Number} Coordinates of point on circumference - */ - Chartist.polarToCartesian = function (centerX, centerY, radius, angleInDegrees) { - var angleInRadians = (angleInDegrees - 90) * Math.PI / 180.0; - - return { - x: centerX + (radius * Math.cos(angleInRadians)), - y: centerY + (radius * Math.sin(angleInRadians)) - }; - }; - - /** - * Initialize chart drawing rectangle (area where chart is drawn) x1,y1 = bottom left / x2,y2 = top right - * - * @memberof Chartist.Core - * @param {Object} svg The svg element for the chart - * @param {Object} options The Object that contains all the optional values for the chart - * @param {Number} xAxisOffset The offset of the x-axis to the border of the svg element - * @param {Number} yAxisOffset The offset of the y-axis to the border of the svg element - * @return {Object} The chart rectangles coordinates inside the svg element plus the rectangles measurements - */ - Chartist.createChartRect = function (svg, options, xAxisOffset, yAxisOffset) { - return { - x1: options.chartPadding + yAxisOffset, - y1: (options.height || Chartist.getHeight(svg._node)) - options.chartPadding - xAxisOffset, - x2: (options.width || Chartist.getWidth(svg._node)) - options.chartPadding, - y2: options.chartPadding, - width: function () { - return this.x2 - this.x1; - }, - height: function () { - return this.y1 - this.y2; - } - }; - }; - - /** - * Generate grid lines and labels for the x-axis into grid and labels group SVG elements - * - * @memberof Chartist.Core - * @param {Object} chartRect The rectangle that sets the bounds for the chart in the svg element - * @param {Object} data The Object that contains the data to be visualized in the chart - * @param {Object} grid Chartist.svg wrapper object to be filled with the grid lines of the chart - * @param {Object} labels Chartist.svg wrapper object to be filled with the lables of the chart - * @param {Object} options The Object that contains all the optional values for the chart - */ - Chartist.createXAxis = function (chartRect, data, grid, labels, options) { - // Create X-Axis - data.labels.forEach(function (value, index) { - var interpolatedValue = options.axisX.labelInterpolationFnc(value, index), - pos = chartRect.x1 + chartRect.width() / data.labels.length * index; - - // If interpolated value returns falsey (except 0) we don't draw the grid line - if (!interpolatedValue && interpolatedValue !== 0) { - return; - } - - if (options.axisX.showGrid) { - grid.elem('line', { - x1: pos, - y1: chartRect.y1, - x2: pos, - y2: chartRect.y2 - }, [options.classNames.grid, options.classNames.horizontal].join(' ')); - } - - if (options.axisX.showLabel) { - // Use config offset for setting labels of - var label = labels.elem('text', { - dx: pos + 2 - }, [options.classNames.label, options.classNames.horizontal].join(' ')).text('' + interpolatedValue); - - // TODO: should use 'alignment-baseline': 'hanging' but not supported in firefox. Instead using calculated height to offset y pos - label.attr({ - dy: chartRect.y1 + Chartist.getHeight(label._node) + options.axisX.offset - }); - } - }); - }; - - /** - * Generate grid lines and labels for the y-axis into grid and labels group SVG elements - * - * @memberof Chartist.Core - * @param {Object} chartRect The rectangle that sets the bounds for the chart in the svg element - * @param {Object} bounds All the values to set the bounds of the chart - * @param {Object} grid Chartist.svg wrapper object to be filled with the grid lines of the chart - * @param {Object} labels Chartist.svg wrapper object to be filled with the lables of the chart - * @param {Number} offset Offset for the y-axis - * @param {Object} options The Object that contains all the optional values for the chart - */ - Chartist.createYAxis = function (chartRect, bounds, grid, labels, offset, options) { - // Create Y-Axis - bounds.values.forEach(function (value, index) { - var interpolatedValue = options.axisY.labelInterpolationFnc(value, index), - pos = chartRect.y1 - chartRect.height() / bounds.values.length * index; - - // If interpolated value returns falsey (except 0) we don't draw the grid line - if (!interpolatedValue && interpolatedValue !== 0) { - return; - } - - if (options.axisY.showGrid) { - grid.elem('line', { - x1: chartRect.x1, - y1: pos, - x2: chartRect.x2, - y2: pos - }, [options.classNames.grid, options.classNames.vertical].join(' ')); - } - - if (options.axisY.showLabel) { - labels.elem('text', { - dx: options.axisY.labelAlign === 'right' ? offset - options.axisY.offset + options.chartPadding : options.chartPadding, - dy: pos - 2, - 'text-anchor': options.axisY.labelAlign === 'right' ? 'end' : 'start' - }, [options.classNames.label, options.classNames.vertical].join(' ')).text('' + interpolatedValue); - } - }); - }; - - /** - * Determine the current point on the svg element to draw the data series - * - * @memberof Chartist.Core - * @param {Object} chartRect The rectangle that sets the bounds for the chart in the svg element - * @param {Object} bounds All the values to set the bounds of the chart - * @param {Array} data The array that contains the data to be visualized in the chart - * @param {Number} index The index of the current project point - * @return {Object} The coordinates object of the current project point containing an x and y number property - */ - Chartist.projectPoint = function (chartRect, bounds, data, index) { - return { - x: chartRect.x1 + chartRect.width() / data.length * index, - y: chartRect.y1 - chartRect.height() * (data[index] - bounds.min) / (bounds.range + bounds.step) - }; - }; - - // TODO: With multiple media queries the handleMediaChange function is triggered too many times, only need one - /** - * Provides options handling functionality with callback for options changes triggered by responsive options and media query matches - * - * @memberof Chartist.Core - * @param {Object} defaultOptions Default options from Chartist - * @param {Object} options Options set by user - * @param {Array} responsiveOptions Optional functions to add responsive behavior to chart - * @param {Function} optionsChangedCallbackFnc The callback that will be executed when a media change triggered new options to be used. The callback function will receive the new options as first parameter. - * @return {Object} The consolidated options object from the defaults, base and matching responsive options - */ - Chartist.optionsProvider = function (defaultOptions, options, responsiveOptions) { - var baseOptions = Chartist.extend(Chartist.extend({}, defaultOptions), options), - currentOptions, - mediaQueryListeners = [], - optionsListeners = [], - i; - - function updateCrrentOptions() { - currentOptions = Chartist.extend({}, baseOptions); - - if (responsiveOptions) { - for (i = 0; i < responsiveOptions.length; i++) { - var mql = window.matchMedia(responsiveOptions[i][0]); - if (mql.matches) { - currentOptions = Chartist.extend(currentOptions, responsiveOptions[i][1]); - } - } - } - } - - function clearMediaQueryListeners() { - mediaQueryListeners.forEach(function(mql) { - mql.removeListener(updateCrrentOptions); - }); - } - - if (!window.matchMedia) { - throw 'window.matchMedia not found! Make sure you\'re using a polyfill.'; - } else if (responsiveOptions) { - - for (i = 0; i < responsiveOptions.length; i++) { - var mql = window.matchMedia(responsiveOptions[i][0]); - mql.addListener(updateCrrentOptions); - mediaQueryListeners.push(mql); - } - } - // Execute initially so we get the correct current options - updateCrrentOptions(); - - return { - get currentOptions() { - return Chartist.extend({}, currentOptions); - }, - addOptionsListener: function(callback) { - optionsListeners.push(callback); - }, - removeOptionsListener: function(callback) { - optionsListeners.splice(optionsListeners.indexOf(callback), 1); - }, - clear: function() { - optionsListeners = []; - clearMediaQueryListeners(); - } - }; - }; - - //http://schepers.cc/getting-to-the-point - Chartist.catmullRom2bezier = function (crp, z) { - var d = []; - for (var i = 0, iLen = crp.length; iLen - 2 * !z > i; i += 2) { - var p = [ - {x: +crp[i - 2], y: +crp[i - 1]}, - {x: +crp[i], y: +crp[i + 1]}, - {x: +crp[i + 2], y: +crp[i + 3]}, - {x: +crp[i + 4], y: +crp[i + 5]} - ]; - if (z) { - if (!i) { - p[0] = {x: +crp[iLen - 2], y: +crp[iLen - 1]}; - } else if (iLen - 4 === i) { - p[3] = {x: +crp[0], y: +crp[1]}; - } else if (iLen - 2 === i) { - p[2] = {x: +crp[0], y: +crp[1]}; - p[3] = {x: +crp[2], y: +crp[3]}; - } - } else { - if (iLen - 4 === i) { - p[3] = p[2]; - } else if (!i) { - p[0] = {x: +crp[i], y: +crp[i + 1]}; - } - } - d.push( - [ - (-p[0].x + 6 * p[1].x + p[2].x) / 6, - (-p[0].y + 6 * p[1].y + p[2].y) / 6, - (p[1].x + 6 * p[2].x - p[3].x) / 6, - (p[1].y + 6 * p[2].y - p[3].y) / 6, - p[2].x, - p[2].y - ] - ); - } - - return d; - }; - -}(window, document, Chartist)); \ No newline at end of file diff --git a/source/scripts/chartist.line.js b/source/scripts/chartist.line.js deleted file mode 100644 index b737fef3e..000000000 --- a/source/scripts/chartist.line.js +++ /dev/null @@ -1,361 +0,0 @@ -/** - * The Chartist line chart can be used to draw Line or Scatter charts. If used in the browser you can access the global `Chartist` namespace where you find the `Line` function as a main entry point. - * - * For examples on how to use the line chart please check the examples of the `Chartist.Line` method. - * - * @module Chartist.Line - */ -/* global Chartist */ -(function(window, document, Chartist){ - 'use strict'; - - /** - * This method creates a new line chart and returns an object handle to the internal closure. Currently you can use the returned object only for updating / redrawing the chart. - * - * @memberof Chartist.Line - * @param {String|Node} query A selector query string or directly a DOM element - * @param {Object} data The data object that needs to consist of a labels and a series array - * @param {Object} [options] The options object with options that override the default options. Check the examples for a detailed list. - * @param {Array} [responsiveOptions] Specify an array of responsive option arrays which are a media query and options object pair => [[mediaQueryString, optionsObject],[more...]] - * @return {Object} An object with a version and an update method to manually redraw the chart - * - * @example - * // These are the default options of the line chart - * var options = { - * // Options for X-Axis - * axisX: { - * // The offset of the labels to the chart area - * offset: 10, - * // If labels should be shown or not - * showLabel: true, - * // If the axis grid should be drawn or not - * showGrid: true, - * // Interpolation function that allows you to intercept the value from the axis label - * labelInterpolationFnc: function(value){return value;} - * }, - * // Options for Y-Axis - * axisY: { - * // The offset of the labels to the chart area - * offset: 15, - * // If labels should be shown or not - * showLabel: true, - * // If the axis grid should be drawn or not - * showGrid: true, - * // For the Y-Axis you can set a label alignment property of right or left - * labelAlign: 'right', - * // Interpolation function that allows you to intercept the value from the axis label - * labelInterpolationFnc: function(value){return value;}, - * // This value specifies the minimum height in pixel of the scale steps - * scaleMinSpace: 30 - * }, - * // Specify a fixed width for the chart as a string (i.e. '100px' or '50%') - * width: undefined, - * // Specify a fixed height for the chart as a string (i.e. '100px' or '50%') - * height: undefined, - * // If the line should be drawn or not - * showLine: true, - * // If dots should be drawn or not - * showPoint: true, - * // Specify if the lines should be smoothed (Catmull-Rom-Splines will be used) - * lineSmooth: true, - * // Overriding the natural low of the chart allows you to zoom in or limit the charts lowest displayed value - * low: undefined, - * // Overriding the natural high of the chart allows you to zoom in or limit the charts highest displayed value - * high: undefined, - * // Padding of the chart drawing area to the container element and labels - * chartPadding: 5, - * // Override the class names that get used to generate the SVG structure of the chart - * classNames: { - * chart: 'ct-chart-line', - * label: 'ct-label', - * series: 'ct-series', - * line: 'ct-line', - * point: 'ct-point', - * grid: 'ct-grid', - * vertical: 'ct-vertical', - * horizontal: 'ct-horizontal' - * } - * }; - * - * @example - * // Create a simple line chart - * var data = { - * // A labels array that can contain any sort of values - * labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'], - * // Our series array that contains series objects or in this case series data arrays - * series: [ - * [5, 2, 4, 2, 0] - * ] - * }; - * - * // As options we currently only set a static size of 300x200 px - * var options = { - * width: '300px', - * height: '200px' - * }; - * - * // In the global name space Chartist we call the Line function to initialize a line chart. As a first parameter we pass in a selector where we would like to get our chart created. Second parameter is the actual data object and as a third parameter we pass in our options - * Chartist.Line('.ct-chart', data, options); - * - * @example - * // Create a line chart with responsive options - * - * var data = { - * // A labels array that can contain any sort of values - * labels: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'], - * // Our series array that contains series objects or in this case series data arrays - * series: [ - * [5, 2, 4, 2, 0] - * ] - * }; - * - * // In adition to the regular options we specify responsive option overrides that will override the default configutation based on the matching media queries. - * var responsiveOptions = [ - * ['screen and (min-width: 641px) and (max-width: 1024px)', { - * showPoint: false, - * axisX: { - * labelInterpolationFnc: function(value) { - * // Will return Mon, Tue, Wed etc. on medium screens - * return value.slice(0, 3); - * } - * } - * }], - * ['screen and (max-width: 640px)', { - * showLine: false, - * axisX: { - * labelInterpolationFnc: function(value) { - * // Will return M, T, W etc. on small screens - * return value[0]; - * } - * } - * }] - * ]; - * - * Chartist.Line('.ct-chart', data, null, responsiveOptions); - * - */ - Chartist.Line = function (query, data, options, responsiveOptions) { - - var defaultOptions = { - axisX: { - offset: 10, - showLabel: true, - showGrid: true, - labelInterpolationFnc: Chartist.noop - }, - axisY: { - offset: 15, - showLabel: true, - showGrid: true, - labelAlign: 'right', - labelInterpolationFnc: Chartist.noop, - scaleMinSpace: 30 - }, - width: undefined, - height: undefined, - showLine: true, - showPoint: true, - lineSmooth: true, - low: undefined, - high: undefined, - chartPadding: 5, - classNames: { - chart: 'ct-chart-line', - label: 'ct-label', - series: 'ct-series', - line: 'ct-line', - point: 'ct-point', - grid: 'ct-grid', - vertical: 'ct-vertical', - horizontal: 'ct-horizontal' - } - }, - optionsProvider, - container = Chartist.querySelector(query), - svg; - - function createChart(options) { - var xAxisOffset, - yAxisOffset, - seriesGroups = [], - bounds, - normalizedData = Chartist.normalizeDataArray(Chartist.getDataArray(data), data.labels.length); - - // Create new svg object - svg = Chartist.createSvg(container, options.width, options.height, options.classNames.chart); - - // initialize bounds - bounds = Chartist.getBounds(svg, normalizedData, options); - - xAxisOffset = options.axisX.offset; - if (options.axisX.showLabel) { - xAxisOffset += Chartist.calculateLabelOffset( - svg, - data.labels, - [options.classNames.label, options.classNames.horizontal].join(' '), - options.axisX.labelInterpolationFnc, - Chartist.getHeight - ); - } - - yAxisOffset = options.axisY.offset; - if (options.axisY.showLabel) { - yAxisOffset += Chartist.calculateLabelOffset( - svg, - bounds.values, - [options.classNames.label, options.classNames.horizontal].join(' '), - options.axisY.labelInterpolationFnc, - Chartist.getWidth - ); - } - - var chartRect = Chartist.createChartRect(svg, options, xAxisOffset, yAxisOffset); - // Start drawing - var labels = svg.elem('g'), - grid = svg.elem('g'); - - Chartist.createXAxis(chartRect, data, grid, labels, options); - Chartist.createYAxis(chartRect, bounds, grid, labels, yAxisOffset, options); - - // Draw the series - // initialize series groups - for (var i = 0; i < data.series.length; i++) { - seriesGroups[i] = svg.elem('g'); - - // If the series is an object and contains a name we add a custom attribute - if(data.series[i].name) { - seriesGroups[i].attr({ - 'series-name': data.series[i].name - }, Chartist.xmlNs.uri); - } - - // Use series class from series data or if not set generate one - seriesGroups[i].addClass([ - options.classNames.series, - (data.series[i].className || options.classNames.series + '-' + Chartist.alphaNumerate(i)) - ].join(' ')); - - var p, - pathCoordinates = [], - point; - - for (var j = 0; j < normalizedData[i].length; j++) { - p = Chartist.projectPoint(chartRect, bounds, normalizedData[i], j); - pathCoordinates.push(p.x, p.y); - - //If we should show points we need to create them now to avoid secondary loop - // Small offset for Firefox to render squares correctly - if (options.showPoint) { - point = seriesGroups[i].elem('line', { - x1: p.x, - y1: p.y, - x2: p.x + 0.01, - y2: p.y - }, options.classNames.point).attr({ - 'value': normalizedData[i][j] - }, Chartist.xmlNs.uri); - } - } - - if (options.showLine) { - var svgPathString = 'M' + pathCoordinates[0] + ',' + pathCoordinates[1] + ' '; - - // If smoothed path and path has more than two points then use catmull rom to bezier algorithm - if (options.lineSmooth && pathCoordinates.length > 4) { - - var cr = Chartist.catmullRom2bezier(pathCoordinates); - for(var k = 0; k < cr.length; k++) { - svgPathString += 'C' + cr[k].join(); - } - } else { - for(var l = 3; l < pathCoordinates.length; l += 2) { - svgPathString += 'L ' + pathCoordinates[l - 1] + ',' + pathCoordinates[l]; - } - } - - seriesGroups[i].elem('path', { - d: svgPathString - }, options.classNames.line, true).attr({ - 'values': normalizedData[i] - }, Chartist.xmlNs.uri); - } - } - } - - /** - * Updates the chart which currently does a full reconstruction of the SVG DOM - * - * @memberof Chartist.Line - * - */ - function update() { - createChart(optionsProvider.currentOptions); - } - - /** - * This method will detach the chart from any event listeners that have been added. This includes window.resize and media query listeners for the responsive options. Call this method in order to de-initialize dynamically created / removed charts. - * - * @memberof Chartist.Line - */ - function detach() { - window.removeEventListener('resize', update); - optionsProvider.clear(); - } - - /** - * Add a listener for the responsive options updates. Once the chart will switch to a new option set the listener will be called with the new options. - * - * @memberof Chartist.Line - * @param {Function} callback Callback function that will have the new options as first parameter - */ - function addOptionsListener(callback) { - optionsProvider.addOptionsListener(callback); - } - - /** - * Remove a responsive options listener that was previously added using the addOptionsListener method. - * - * @memberof Chartist.Line - * @param {Function} callback The callback function that was registered earlier with addOptionsListener - */ - function removeOptionsListener(callback) { - optionsProvider.removeOptionsListener(callback); - } - - // If this container already contains chartist, let's try to detach first and unregister all event listeners - if(container.chartist) { - container.chartist.detach(); - } - - // Obtain current options based on matching media queries (if responsive options are given) - // This will also register a listener that is re-creating the chart based on media changes - optionsProvider = Chartist.optionsProvider(defaultOptions, options, responsiveOptions); - createChart(optionsProvider.currentOptions); - - // TODO: Currently we need to re-draw the chart on window resize. This is usually very bad and will affect performance. - // This is done because we can't work with relative coordinates when drawing the chart because SVG Path does not - // work with relative positions yet. We need to check if we can do a viewBox hack to switch to percentage. - // See http://mozilla.6506.n7.nabble.com/Specyfing-paths-with-percentages-unit-td247474.html - // Update: can be done using the above method tested here: http://codepen.io/gionkunz/pen/KDvLj - // The problem is with the label offsets that can't be converted into percentage and affecting the chart container - function updateChart() { - createChart(optionsProvider.currentOptions); - } - - window.addEventListener('resize', updateChart); - - // Public members - var api = { - version: Chartist.version, - update: update, - detach: detach, - addOptionsListener: addOptionsListener, - removeOptionsListener: removeOptionsListener - }; - - container.chartist = api; - - return api; - }; - -}(window, document, Chartist)); diff --git a/source/scripts/chartist.pie.js b/source/scripts/chartist.pie.js deleted file mode 100644 index 20eb05e7f..000000000 --- a/source/scripts/chartist.pie.js +++ /dev/null @@ -1,321 +0,0 @@ -/** - * The pie chart module of Chartist that can be used to draw pie, donut or gauge charts - * - * @module Chartist.Pie - */ -/* global Chartist */ -(function(window, document, Chartist) { - 'use strict'; - - /** - * This method creates a new pie chart and returns an object that can be used to redraw the chart. - * - * @memberof Chartist.Pie - * @param {String|Node} query A selector query string or directly a DOM element - * @param {Object} data The data object in the pie chart needs to have a series property with a one dimensional data array. The values will be normalized against each other and don't necessarily need to be in percentage. - * @param {Object} [options] The options object with options that override the default options. Check the examples for a detailed list. - * @param {Array} [responsiveOptions] Specify an array of responsive option arrays which are a media query and options object pair => [[mediaQueryString, optionsObject],[more...]] - * @return {Object} An object with a version and an update method to manually redraw the chart - * - * @example - * // Default options of the pie chart - * var defaultOptions = { - * // Specify a fixed width for the chart as a string (i.e. '100px' or '50%') - * width: undefined, - * // Specify a fixed height for the chart as a string (i.e. '100px' or '50%') - * height: undefined, - * // Padding of the chart drawing area to the container element and labels - * chartPadding: 5, - * // Override the class names that get used to generate the SVG structure of the chart - * classNames: { - * chart: 'ct-chart-pie', - * series: 'ct-series', - * slice: 'ct-slice', - * donut: 'ct-donut', - label: 'ct-label' - * }, - * // The start angle of the pie chart in degrees where 0 points north. A higher value offsets the start angle clockwise. - * startAngle: 0, - * // An optional total you can specify. By specifying a total value, the sum of the values in the series must be this total in order to draw a full pie. You can use this parameter to draw only parts of a pie or gauge charts. - * total: undefined, - * // If specified the donut CSS classes will be used and strokes will be drawn instead of pie slices. - * donut: false, - * // Specify the donut stroke width, currently done in javascript for convenience. May move to CSS styles in the future. - * donutWidth: 60, - * // If a label should be shown or not - * showLabel: true, - * // Label position offset from the standard position which is half distance of the radius. This value can be either positive or negative. Positive values will position the label away from the center. - * labelOffset: 0, - * // An interpolation function for the label value - * labelInterpolationFnc: function(value, index) {return value;}, - * // Label direction can be 'neutral', 'explode' or 'implode'. The labels anchor will be positioned based on those settings as well as the fact if the labels are on the right or left side of the center of the chart. Usually explode is useful when labels are positioned far away from the center. - * labelDirection: 'neutral' - * }; - * - * @example - * // Simple pie chart example with four series - * Chartist.Pie('.ct-chart', { - * series: [10, 2, 4, 3] - * }); - * - * @example - * // Drawing a donut chart - * Chartist.Pie('.ct-chart', { - * series: [10, 2, 4, 3] - * }, { - * donut: true - * }); - * - * @example - * // Using donut, startAngle and total to draw a gauge chart - * Chartist.Pie('.ct-chart', { - * series: [20, 10, 30, 40] - * }, { - * donut: true, - * donutWidth: 20, - * startAngle: 270, - * total: 200 - * }); - * - * @example - * // Drawing a pie chart with padding and labels that are outside the pie - * Chartist.Pie('.ct-chart', { - * series: [20, 10, 30, 40] - * }, { - * chartPadding: 30, - * labelOffset: 50, - * labelDirection: 'explode' - * }); - */ - Chartist.Pie = function (query, data, options, responsiveOptions) { - - var defaultOptions = { - width: undefined, - height: undefined, - chartPadding: 5, - classNames: { - chart: 'ct-chart-pie', - series: 'ct-series', - slice: 'ct-slice', - donut: 'ct-donut', - label: 'ct-label' - }, - startAngle: 0, - total: undefined, - donut: false, - donutWidth: 60, - showLabel: true, - labelOffset: 0, - labelInterpolationFnc: Chartist.noop, - labelOverflow: false, - labelDirection: 'neutral' - }, - optionsProvider, - container = Chartist.querySelector(query), - svg; - - function determineAnchorPosition(center, label, direction) { - var toTheRight = label.x > center.x; - - if(toTheRight && direction === 'explode' || - !toTheRight && direction === 'implode') { - return 'start'; - } else if(toTheRight && direction === 'implode' || - !toTheRight && direction === 'explode') { - return 'end'; - } else { - return 'middle'; - } - } - - function createChart(options) { - var seriesGroups = [], - chartRect, - radius, - labelRadius, - totalDataSum, - startAngle = options.startAngle, - dataArray = Chartist.getDataArray(data); - - // Create SVG.js draw - svg = Chartist.createSvg(container, options.width, options.height, options.classNames.chart); - // Calculate charting rect - chartRect = Chartist.createChartRect(svg, options, 0, 0); - // Get biggest circle radius possible within chartRect - radius = Math.min(chartRect.width() / 2, chartRect.height() / 2); - // Calculate total of all series to get reference value or use total reference from optional options - totalDataSum = options.total || dataArray.reduce(function(previousValue, currentValue) { - return previousValue + currentValue; - }, 0); - - // If this is a donut chart we need to adjust our radius to enable strokes to be drawn inside - // Unfortunately this is not possible with the current SVG Spec - // See this proposal for more details: http://lists.w3.org/Archives/Public/www-svg/2003Oct/0000.html - radius -= options.donut ? options.donutWidth / 2 : 0; - - // If a donut chart then the label position is at the radius, if regular pie chart it's half of the radius - // see https://github.com/gionkunz/chartist-js/issues/21 - labelRadius = options.donut ? radius : radius / 2; - // Add the offset to the labelRadius where a negative offset means closed to the center of the chart - labelRadius += options.labelOffset; - - // Calculate end angle based on total sum and current data value and offset with padding - var center = { - x: chartRect.x1 + chartRect.width() / 2, - y: chartRect.y2 + chartRect.height() / 2 - }; - - // Draw the series - // initialize series groups - for (var i = 0; i < data.series.length; i++) { - seriesGroups[i] = svg.elem('g', null, null, true); - - // If the series is an object and contains a name we add a custom attribute - if(data.series[i].name) { - seriesGroups[i].attr({ - 'series-name': data.series[i].name - }, Chartist.xmlNs.uri); - } - - // Use series class from series data or if not set generate one - seriesGroups[i].addClass([ - options.classNames.series, - (data.series[i].className || options.classNames.series + '-' + Chartist.alphaNumerate(i)) - ].join(' ')); - - var endAngle = startAngle + dataArray[i] / totalDataSum * 360; - // If we need to draw the arc for all 360 degrees we need to add a hack where we close the circle - // with Z and use 359.99 degrees - if(endAngle - startAngle === 360) { - endAngle -= 0.01; - } - - var start = Chartist.polarToCartesian(center.x, center.y, radius, startAngle - (i === 0 ? 0 : 0.2)), - end = Chartist.polarToCartesian(center.x, center.y, radius, endAngle), - arcSweep = endAngle - startAngle <= 180 ? '0' : '1', - d = [ - // Start at the end point from the cartesian coordinates - 'M', end.x, end.y, - // Draw arc - 'A', radius, radius, 0, arcSweep, 0, start.x, start.y - ]; - - // If regular pie chart (no donut) we add a line to the center of the circle for completing the pie - if(options.donut === false) { - d.push('L', center.x, center.y); - } - - // Create the SVG path - // If this is a donut chart we add the donut class, otherwise just a regular slice - var path = seriesGroups[i].elem('path', { - d: d.join(' ') - }, options.classNames.slice + (options.donut ? ' ' + options.classNames.donut : '')); - - // Adding the pie series value to the path - path.attr({ - 'value': dataArray[i] - }, Chartist.xmlNs.uri); - - // If this is a donut, we add the stroke-width as style attribute - if(options.donut === true) { - path.attr({ - 'style': 'stroke-width: ' + (+options.donutWidth) + 'px' - }); - } - - // If we need to show labels we need to add the label for this slice now - if(options.showLabel) { - // Position at the labelRadius distance from center and between start and end angle - var labelPosition = Chartist.polarToCartesian(center.x, center.y, labelRadius, startAngle + (endAngle - startAngle) / 2), - interpolatedValue = options.labelInterpolationFnc(data.labels ? data.labels[i] : dataArray[i], i); - - seriesGroups[i].elem('text', { - dx: labelPosition.x, - dy: labelPosition.y, - 'text-anchor': determineAnchorPosition(center, labelPosition, options.labelDirection) - }, options.classNames.label).text('' + interpolatedValue); - } - - // Set next startAngle to current endAngle. Use slight offset so there are no transparent hairline issues - // (except for last slice) - startAngle = endAngle; - } - } - - /** - * Updates the chart which currently does a full reconstruction of the SVG DOM - * - * @memberof Chartist.Pie - * - */ - function update() { - createChart(optionsProvider.currentOptions); - } - - /** - * This method will detach the chart from any event listeners that have been added. This includes window.resize and media query listeners for the responsive options. Call this method in order to de-initialize dynamically created / removed charts. - * - * @memberof Chartist.Pie - */ - function detach() { - window.removeEventListener('resize', update); - optionsProvider.clear(); - } - - /** - * Add a listener for the responsive options updates. Once the chart will switch to a new option set the listener will be called with the new options. - * - * @memberof Chartist.Pie - * @param {Function} callback Callback function that will have the new options as first parameter - */ - function addOptionsListener(callback) { - optionsProvider.addOptionsListener(callback); - } - - /** - * Remove a responsive options listener that was previously added using the addOptionsListener method. - * - * @memberof Chartist.Pie - * @param {Function} callback The callback function that was registered earlier with addOptionsListener - */ - function removeOptionsListener(callback) { - optionsProvider.removeOptionsListener(callback); - } - - // If this container already contains chartist, let's try to detach first and unregister all event listeners - if(container.chartist) { - container.chartist.detach(); - } - - // Obtain current options based on matching media queries (if responsive options are given) - // This will also register a listener that is re-creating the chart based on media changes - optionsProvider = Chartist.optionsProvider(defaultOptions, options, responsiveOptions); - createChart(optionsProvider.currentOptions); - - // TODO: Currently we need to re-draw the chart on window resize. This is usually very bad and will affect performance. - // This is done because we can't work with relative coordinates when drawing the chart because SVG Path does not - // work with relative positions yet. We need to check if we can do a viewBox hack to switch to percentage. - // See http://mozilla.6506.n7.nabble.com/Specyfing-paths-with-percentages-unit-td247474.html - // Update: can be done using the above method tested here: http://codepen.io/gionkunz/pen/KDvLj - // The problem is with the label offsets that can't be converted into percentage and affecting the chart container - function updateChart() { - createChart(optionsProvider.currentOptions); - } - - window.addEventListener('resize', updateChart); - - // Public members - var api = { - version: Chartist.version, - update: update, - detach: detach, - addOptionsListener: addOptionsListener, - removeOptionsListener: removeOptionsListener - }; - - container.chartist = api; - - return api; - }; - -}(window, document, Chartist)); \ No newline at end of file diff --git a/source/scripts/chartist.svg.js b/source/scripts/chartist.svg.js deleted file mode 100644 index df26dfdca..000000000 --- a/source/scripts/chartist.svg.js +++ /dev/null @@ -1,143 +0,0 @@ -/** - * Chartist SVG module for simple SVG DOM abstraction - * - * @module Chartist.svg - */ -/* global Chartist */ -(function(window, document, Chartist) { - 'use strict'; - - Chartist.xmlNs = { - qualifiedName: 'xmlns:ct', - prefix: 'ct', - uri: 'http://gionkunz.github.com/chartist-js/ct' - }; - - Chartist.svg = function(name, attributes, className, insertFirst, parent) { - - var svgNs = 'http://www.w3.org/2000/svg', - xmlNs = 'http://www.w3.org/2000/xmlns/'; - - function attr(node, attributes, ns) { - Object.keys(attributes).forEach(function(key) { - if(ns) { - node.setAttributeNS(ns, [Chartist.xmlNs.prefix, ':', key].join(''), attributes[key]); - } else { - node.setAttribute(key, attributes[key]); - } - }); - - return node; - } - - function elem(svg, name, attributes, className, insertFirst, parentNode) { - var node = document.createElementNS(svgNs, name); - - // If this is an SVG element created then custom namespace - if(name === 'svg') { - node.setAttributeNS(xmlNs, Chartist.xmlNs.qualifiedName, Chartist.xmlNs.uri); - } - - if(parentNode) { - if(insertFirst && parentNode.firstChild) { - parentNode.insertBefore(node, parentNode.firstChild); - } else { - parentNode.appendChild(node); - } - } - - if(attributes) { - attr(node, attributes); - } - - if(className) { - addClass(node, className); - } - - return node; - } - - function text(node, t) { - node.appendChild(document.createTextNode(t)); - } - - function empty(node) { - while (node.firstChild) { - node.removeChild(node.firstChild); - } - } - - function remove(node) { - node.parentNode.removeChild(node); - } - - function classes(node) { - return node.getAttribute('class') ? node.getAttribute('class').trim().split(/\s+/) : []; - } - - function addClass(node, names) { - node.setAttribute('class', - classes(node) - .concat(names.trim().split(/\s+/)) - .filter(function(elem, pos, self) { - return self.indexOf(elem) === pos; - }).join(' ') - ); - } - - function removeClass(node, names) { - var removedClasses = names.trim().split(/\s+/); - - node.setAttribute('class', classes(node).filter(function(name) { - return removedClasses.indexOf(name) === -1; - }).join(' ')); - } - - function removeAllClasses(node) { - node.setAttribute('class', ''); - } - - return { - _node: elem(this, name, attributes, className, insertFirst, parent ? parent._node : undefined), - _parent: parent, - parent: function() { - return this._parent; - }, - attr: function(attributes, ns) { - attr(this._node, attributes, ns); - return this; - }, - empty: function() { - empty(this._node); - return this; - }, - remove: function() { - remove(this._node); - return this; - }, - elem: function(name, attributes, className, insertFirst) { - return Chartist.svg(name, attributes, className, insertFirst, this); - }, - text: function(t) { - text(this._node, t); - return this; - }, - addClass: function(names) { - addClass(this._node, names); - return this; - }, - removeClass: function(names) { - removeClass(this._node, names); - return this; - }, - removeAllClasses: function() { - removeAllClasses(this._node); - return this; - }, - classes: function() { - return classes(this._node); - } - }; - }; - -}(window, document, Chartist)); \ No newline at end of file diff --git a/source/scripts/site/chartist-guy.js b/source/scripts/site/chartist-guy.js deleted file mode 100644 index c3c87856d..000000000 --- a/source/scripts/site/chartist-guy.js +++ /dev/null @@ -1,54 +0,0 @@ -(function(){ - 'use strict'; - - // Chartist guy data chart data and options - var optionsChartistGuy = { - width: 195, - height: 137, - chartPadding: 10, - axisX: { - offset: 0, - showLabel: true, - showGrid: true, - labelInterpolationFnc: function(n) { - return n; - } - }, - axisY: { - offset: 5, - showLabel: true, - showGrid: true, - labelInterpolationFnc: function(n) { - return Math.round(n / 100000) / 10 + 'm.'; - } - } - }; - - var chartistGuyData = { - labels: ['1st', '2nd', '3rd'], - series: [ - { - name: 'Workers', - data: [1283000, 1500000, 5706000] - }, - { - name: 'Nobles', - data: [1883000, 2050000, 3706000] - } - ] - }; - - var $chartistGuyElement = $('#chartist-guy'); - if($chartistGuyElement.length > 0) { - - // Create new snap object from SVG - var chartistGuySnap = Snap($chartistGuyElement.get(0)); - // Load Chartist guy SVG - Snap.load($chartistGuyElement.data('svgSrc'), function (fragment) { - chartistGuySnap.append(fragment); - - // Add line chart to canvas of Chartist guy :-) - window.Chartist.Line($chartistGuyElement.find('#chart-canvas').get(0), chartistGuyData, optionsChartistGuy); - }); - } -}()); diff --git a/source/scripts/site/main.js b/source/scripts/site/main.js deleted file mode 100644 index 88b87167d..000000000 --- a/source/scripts/site/main.js +++ /dev/null @@ -1,121 +0,0 @@ -'use strict'; - -// Initialize highlight.js -window.hljs.initHighlightingOnLoad(); - -function evalChartistCode(code, chartElement) { - // Modify the code to use a proper selector using the ID of the example as well as return the Chartist object - var modified = code.replace(/Chartist\s*\.\s*(.+)\(\s*['"](.+)['"]/, function(match, type) { - return ['var chartist = Chartist.', type, '(chartElement'].join(''); - }) + '; return chartist;'; - - // Remove any declaration of $chart as we are passing $chart to our function eval - modified = modified.replace(/var \$chart.+;/, ''); - - try { - // Create function from the modified code and execute it - return (new Function(['chartElement', '$chart'], modified)(chartElement, $(chartElement))); // jshint ignore:line - } catch(err) { - // Maybe show error in the future - } -} - -// Generic data-* driven control behaviour -$(function() { - $('[data-toggle-visible]').each(function() { - var $element = $(this), - $target = $($element.data('toggleVisible')); - - $target.addClass('invisible'); - $element.on('click', function(e) { - $target.toggleClass('invisible'); - e.preventDefault(); - }); - }); - - $('[data-sticky]').each(function() { - var $element = $(this), - initialOffset = $element.offset().top, - margin = $element.data('sticky') || 0; - - $(window).on('scroll', function() { - var scrollTop = $(window).scrollTop(); - - if(scrollTop > initialOffset - margin) { - $element.css({ - position: 'relative', - top: scrollTop + margin - initialOffset - }); - } else { - $element.css({ - position: '', - top: '' - }); - } - }); - }); - - $('[data-example]').each(function() { - var $element = $(this), - code = window.atob($element.data('example')); - - // Execute the Chartist code immediately - evalChartistCode(code, $element.get(0)); - }); - - $('[data-live-example]').each(function() { - var $element = $(this), - $editor = $element.find('.code-editor'), - initialCode = window.atob($element.data('liveExample')), - chartist, - cm; - - function updateChart() { - if(chartist) { - chartist.update(); - } - } - - function initializeCodeMirror() { - if(cm) { - return; - } - - cm = window.CodeMirror.fromTextArea($editor.get(0), { - mode: 'javascript', - theme: 'chartist', - lineWrapping: true, - indentUnit: 2, - tabSize: 2 - }); - - cm.on('change', function(event) { - // Execute the Chartist code once the code gets updated - chartist = evalChartistCode(event.doc.getValue(), $element.find('.ct-chart').get(0)); - }); - } - - $element.find('.edit-button').on('click', function() { - $element.addClass('edit-mode'); - updateChart(); - initializeCodeMirror(); - }); - - $element.find('.close-edit-button').on('click', function() { - $element.removeClass('edit-mode'); - updateChart(); - }); - - $editor.val(initialCode); - - // Execute the Chartist code immediately - chartist = evalChartistCode(initialCode, $element.find('.ct-chart').get(0)); - }); -}); - -// Initialize foundation -$(document).foundation({ - topbar: { - scrolltop: false - } -}); \ No newline at end of file diff --git a/source/site/api-documentation.hbs b/source/site/api-documentation.hbs deleted file mode 100644 index 688435e27..000000000 --- a/source/site/api-documentation.hbs +++ /dev/null @@ -1,10 +0,0 @@ ---- -layout: content -side-nav: api-side-navigation -page-class: api-documentation -title: Chartist - API Documentation -description: Detailed documentation of the Chartist.js code and API ---- -{{#each (doxTransform apidox)}} - {{>dox-section}} -{{/each}} \ No newline at end of file diff --git a/source/site/code-snippets/aspect-ratio-container.html b/source/site/code-snippets/aspect-ratio-container.html deleted file mode 100644 index c774467b6..000000000 --- a/source/site/code-snippets/aspect-ratio-container.html +++ /dev/null @@ -1 +0,0 @@ -
\ No newline at end of file diff --git a/source/site/code-snippets/custom-include.scss b/source/site/code-snippets/custom-include.scss deleted file mode 100644 index a9bcf228a..000000000 --- a/source/site/code-snippets/custom-include.scss +++ /dev/null @@ -1,2 +0,0 @@ -@import "http://github.com/_my-chartist-settings.scss"; -@import "http://github.com/chartist/libdist/scss/chartist.scss"; \ No newline at end of file diff --git a/source/site/code-snippets/simple-start-aspect-ratio-chart.js b/source/site/code-snippets/simple-start-aspect-ratio-chart.js deleted file mode 100644 index 873ee0f51..000000000 --- a/source/site/code-snippets/simple-start-aspect-ratio-chart.js +++ /dev/null @@ -1,13 +0,0 @@ -var data = { - // A labels array that can contain any sort of values - labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'], - // Our series array that contains series objects or in this case series data arrays - series: [ - [5, 2, 4, 2, 0] - ] -}; - -// In the global name space Chartist we call the Line function to initialize a line chart -// As a first parameter we pass in a selector where we would like to get our chart created -// Second parameter is the actual data object -Chartist.Line('.ct-chart', data); \ No newline at end of file diff --git a/source/site/code-snippets/simple-start-fixed-chart.js b/source/site/code-snippets/simple-start-fixed-chart.js deleted file mode 100644 index a7b3a25ea..000000000 --- a/source/site/code-snippets/simple-start-fixed-chart.js +++ /dev/null @@ -1,20 +0,0 @@ -var data = { - // A labels array that can contain any sort of values - labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'], - // Our series array that contains series objects or in this case series data arrays - series: [ - [5, 2, 4, 2, 0] - ] -}; - -// As options we currently only set a static size of 300x200 px. We can also omit this and use aspect ratio containers -// as you saw in the previous example -var options = { - width: 300, - height: 200 -}; - -// In the global name space Chartist we call the Bar function to initialize a bar chart -// As a first parameter we pass in a selector where we would like to get our chart created -// Second parameter is the actual data object and as a third parameter we pass in our options -Chartist.Bar('.ct-chart', data, options); \ No newline at end of file diff --git a/source/site/code-snippets/simple-start.html b/source/site/code-snippets/simple-start.html deleted file mode 100644 index 7f3280942..000000000 --- a/source/site/code-snippets/simple-start.html +++ /dev/null @@ -1,7 +0,0 @@ - - - - - - - \ No newline at end of file diff --git a/source/site/data/pages/examples.yml b/source/site/data/pages/examples.yml deleted file mode 100644 index 7f8b22979..000000000 --- a/source/site/data/pages/examples.yml +++ /dev/null @@ -1,81 +0,0 @@ -sections: - - title: Line chart examples - level: 3 - items: - - type: live-example - data: - title: Simple line chart - level: 4 - id: simple-line-chart - classes: ct-golden-section - intro: An example of a simple line chart with three series. You can edit this example in realtime. - - type: live-example - data: - title: Line scatter diagram with responsive settings - level: 4 - id: line-scatter-random - classes: ct-golden-section - intro: > - This advanced example uses a line chart to draw a scatter diagram. The data object is created - with a functional style random mechanism. There is a mobile first responsive configuration using - the responsive options to show less labels on small screens. - - type: live-example - data: - title: Line chart with tooltips - level: 4 - id: behavior-with-jquery - classes: ct-golden-section - intro: > - Adding behavior to your chart with JavaScript is a breeze and is just like any other DOM manipulation - you do to your site. This is just one of many benefits of using inline-SVG and provides you with the - freedom you need in order to create exactly the experience you're looking for. - - title: Bar chart examples - level: 3 - items: - - type: live-example - data: - title: Bi-polar bar chart - level: 4 - id: bi-polar-bar-interpolated - classes: ct-golden-section - intro: > - A bi-plar bar chart with a range limit set with low and high. There is also an interpolation - function used to skip every odd grid line / label. - - type: live-example - data: - title: Overlapping bars on mobile - level: 4 - id: overlapping-bars - classes: ct-golden-section - intro: > - This example makes use of label interpolation and the seriesBarDistance property that allows you - to make bars overlap over each other. This then can be used to use the avialable space on mobile better. - Resize your browser to see the effect of the responsive configuration. - - title: Pie chart examples - level: 3 - items: - - type: live-example - data: - title: Simple pie chart - level: 4 - id: simple-pie-chart - classes: ct-golden-section ct-negative-labels - intro: A very simple pie chart with label interpolation to show percentage instead of the actual data series value. - - type: live-example - data: - title: Pie chart with custom labels - level: 4 - id: pie-with-custom-labels - classes: ct-golden-section - intro: > - This pie chart is configured with custom labels specified in the data object. On desktop we use the labelOffset - property to offset the labels from the center. Also labelDirection can be used to control the direction - in which the labels are expanding. - - - type: live-example - data: - title: Gauge chart - level: 4 - id: simple-gauge-chart - classes: ct-golden-section ct-negative-labels - intro: This pie chart uses donut, startAngle and total to draw a gauge chart. diff --git a/source/site/data/pages/getting-started.yml b/source/site/data/pages/getting-started.yml deleted file mode 100644 index 8fd5f2854..000000000 --- a/source/site/data/pages/getting-started.yml +++ /dev/null @@ -1,378 +0,0 @@ -sections: - - title: Download and set-up - level: 3 - items: - - type: sub-section - data: - title: Bower - level: 4 - items: - - type: text - data: - text: 'The easiest way to get started with Chartist.js is by using bower:' - - - type: code - data: - lang: bash - code: bower install chartist --save - - - type: text - data: - text: > - The bower package contains the JavaScript library, CSS as well as the SASS (SCSS) files. - You can then integrate the desired dependencies in your project and start using them - immediately. - - - type: sub-section - data: - title: One, two, three, CSS! - level: 4 - items: - - type: text - data: - text: > - The quickest way to get things up and running is by using the Chartist.js CSS files. - The CSS is compiled from the SASS files with de default class names which are also - configured in the JavaScript library. You can then override the default styles or - modify the CSS file, however, for customization it's recommended to use the SASS - version of Chartist.js. - - - type: code-snippet - data: - id: simple-start - lang: html - - - type: sub-section - data: - title: The SASS way - level: 4 - items: - - type: text - data: - text: > - If you like to customize your charts you can either remove the CSS fully and write your - own selectors using the Chartist.js SASS mixins or you just use the Chartist.js SASS - settings file to customize the look and feel of your charts. - - - type: text - data: - text: > - Styling inline SVG with CSS is a breeze and you should also consider writing your own - selectors for your charts and using the SASS mixins. You can read more about using the - SASS mixins in the advanced section. - - - type: text - data: - text: > - To customize the style of your charts using the SASS settings file you should copy the - settings file to your own SASS folder. - - - type: code - data: - lang: bash - code: cp bower_components/chartist/libdist/scss/settings/_chartist-settings.scss styles - - - type: text - data: - text: > - Then just import your copy of the settings file before you import the chartist.scss - file and change the settings in your copy as desired. - - - type: code-snippet - data: - id: custom-include - lang: scss - - - type: heading - data: - level: 5 - title: Default settings - - - type: text - data: - text: > - The settings file contains all relevant variables used in the mixins and while - generating the default classes. You can simply change the settings for styling your - own charts. If you want to override certain settings based on state or pseeudo - selectors, you can use the individual mixins to only override specific styles. - - - type: text - data: - text: > - Take a look at the settings to see how to customize the style of the defalt Chartist.js - class selectors. - - - type: code-snippet - data: - id: default-sass-settings - button: Show default settings - path: source/styles/settings/_chartist-settings.scss - lang: scss - - - title: Create your first chart - level: 3 - items: - - type: text - data: - text: > - In this section you'll go through a simple example of how to use Chartist.js in your project. - You'll learn the default stages you go through when creating and customizing a basic line chart. - If you'd like to see more in depth and advanced examples you should check out - the advanced section or the examples page. - - - type: sub-section - data: - title: As simple as it can get - level: 4 - items: - - type: text - data: - text: > - Chartist provides you a very simple API to get started, however, while trying to follow the - best practice of relying on standards and clear separation of concerns it sometimes needs a small mind - shift in order to understand how things are meant to work within Chartist. Instead of specifying - your colors, line width and other style related things in the JavaScript API, you'll need to use - CSS in order to control your appearance. - - - type: sub-section - data: - title: Creating a chart using aspect ratios - level: 5 - items: - - type: text - data: - text: > - Because of the nature of responsive design it's important to understand that blocks in design like images, - videos and similar content need to be able to scale and adapt to the media. In order for an element to scale, you - need to rely on a certain aspect ratios (like 4:3, 3:2, 16:9 etc.) rather than specifying a fixed width and height. - - - type: text - data: - text: > - To designers this Idea is absolutely not new, but to developers this might be at first. However, when a designer talks - to a developer about the images being 320x240 on this page and 300x200 on that element, he actually just - translated his idea of using 4:3 and 3:2 images into pixels. - - - type: text - data: - text: > - With Chartist you can specify those ratios directly on containers without the need to calculate any fixed dimensions. - In order to create a chart that is using the aspect ratio of a golden section you can just add the class .ct-golden-section - to your container where you initialize Chartist. - - - type: text - data: - text: > - Here is a list of all available container ratios (If using the SASS version of Chartist you can also easily add others): - - - type: table - data: - id: container-aspect-ratio-classes - button: Show available aspect ratios - header: - - Container class - - Ratio - rows: - - - - .ct-square - - '1' - - - - .ct-minor-second - - '15:16' - - - - .ct-major-second - - '8:9' - - - - .ct-minor-third - - '5:6' - - - - .ct-major-third - - '4:5' - - - - .ct-perfect-fourth - - '3:4' - - - - .ct-perfect-fifth - - '2:3' - - - - .ct-minor-sixth - - '5:8' - - - - .ct-golden-section - - '1:1.618' - - - - .ct-major-sixth - - '3:5' - - - - .ct-minor-seventh - - '9:16' - - - - .ct-major-seventh - - '8:15' - - - - .ct-octave - - '1:2' - - - - .ct-major-tenth - - '2:5' - - - - .ct-major-eleventh - - '3:8' - - - - .ct-major-twelfth - - '1:3' - - - - .ct-double-octave - - '1:4' - - - type: text - data: - text: > - Use the following HTML code to specify a container with one of the above aspect ratio classes. - - - type: code - data: - code: '
' - lang: html - - - type: text - data: - text: > - When using a fixed aspect ratio container you can then simply initialize your chart without - specifying any width or height in the options. - - - type: code-snippet - data: - id: simple-start-aspect-ratio-chart - lang: js - - - type: sub-section - data: - title: Creating a chart with fixed dimensions - level: 5 - items: - - type: text - data: - text: > - In order to create a simple line chart with fixed width and height you only need to have a - container element and initialize Chartist.js on it. - Give the container the class ct-chart so that it will get the default styles (if you don't - use your own classes). - - - type: code-snippet - data: - id: simple-start-fixed-chart - lang: js - - - type: sub-section - data: - title: The configuration of your chart - level: 4 - items: - - type: text - data: - text: > - Chartist.js is built very flexible and almost everything within your charts can be configured. - In the default settings (that you can check in the API Documentation) - you'll get some predefined defaults applied to your charts. - - - type: text - data: - text: > - You can always override the default settings of your charts by passing in a configuration - object at creation time. - - - type: example-chart - data: - id: simple-configuration-chart - classes: ct-golden-section - show-code-button: Show code and comments - - - type: sub-section - data: - title: Responsive sugar topping - level: 4 - items: - - type: text - data: - text: > - Responsive web design is all based on - media queries - as you are probably already aware. Media queries are great and they help you to define media related - conditions that you can use to apply different styles for different media. - - type: text - data: - text: > - Sometimes it's also required to have different behavior on certain media and it's possible that - a specific component of your web site should behave in an other way on a small media than on a - large one. Luckily there is window.matchMedia in your browser that comes to the rescue. With - matchMedia it's possible to let your javascript react differently based on CSS3 media queries. - - - type: heading - data: - level: 5 - title: Responsive setting overrides - - - type: text - data: - text: > - Configuring different chart behavior for various media is made simple with an override - mechanism. The priority of the override mechanism is based on order of specification of - the matching media queries. - - - type: text - data: - text: > - The following example uses different label interpolations (to save some space) on small media - as well as different spacing between the bars of the bar chart series. Resize your browser window - to see the effect. - - - type: example-chart - data: - id: example-simple-bar - classes: ct-golden-section - type: Bar - show-code-button: Show code and comments - - - type: hint - data: - title: Cross-browser support - classes: hint-cross-browser - text: > - For IE9 you need to use a matchMedia polyfill. You should take a look at - Paul Irish's matchMedia polyfill. - - - title: Advanced - level: 3 - items: - - type: text - data: - text: > - In the following chapter you'll find some advanced usage examples that might be of interesst for you. - Chartist is very flexible because it relies on standard technology. This also means that you will need - to implement certain things yourself. This topic should cover some of these use-cases and give you some - basic idea why and how to implement certain functionality. - - - type: sub-section - data: - title: Adding behavior to your charts - level: 4 - items: - - type: text - data: - text: > - This example shows you how you can easily build a tool tip on top of Chartist using jQuery and some - basic styling. It makes use of the ct-series-name and ct-value custom attributes that are present - on all SVG elements generated by Chartist. - - type: text - data: - text: > - We actually do a few things here that would go against a proper style guide (like animating with - JavaScript and changing styles instead of switching classes etc.), but this example is only for - illustrating how easy behavior could be attached to Chartist. - - - type: example-chart - data: - id: behavior-with-jquery - classes: ct-golden-section - show-code-button: Show code \ No newline at end of file diff --git a/source/site/data/pages/index.yml b/source/site/data/pages/index.yml deleted file mode 100644 index 8716e7ec7..000000000 --- a/source/site/data/pages/index.yml +++ /dev/null @@ -1,65 +0,0 @@ -gallery-examples: - - id: example-gallery-one - classes: ct-golden-section - - id: example-gallery-two - classes: ct-golden-section - - id: example-gallery-three - classes: ct-golden-section - - id: example-gallery-four - classes: ct-golden-section - -sections: - - title: Chart CSS animation example - level: 3 - items: - - type: example-chart - data: - id: example-line-months-interpolation - classes: ct-golden-section dark - - type: hint - data: - title: Cross-browser support - classes: hint-cross-browser - text: Note that CSS3 animations on SVG CSS attributes are not supported on all browsers and the appearance may vary. - side-notes: - - type: text - data: - text: Specifying the style of your chart in CSS is not only cleaner but also enables you to use awesome CSS animations and transitions to be applied to your SVG elements! - - - title: New bar chart type! - level: 3 - items: - - type: example-chart - data: - id: example-simple-bar - classes: ct-golden-section - side-notes: - - type: text - data: - text: We are constantly working on enhancements of our existing charts and adding new chart types. While we only have two chart types currently available you can customize them to your own needs while getting a huge vaiarity of configurations and designs. - - - title: Responsive charts configuration - level: 3 - items: - - type: example-chart - data: - id: example-line-simple-responsive - classes: ct-golden-section - show-code-button: Show code - - type: sub-section - data: - title: Configuration overrides based on media queries - level: 4 - items: - - type: text - data: - text: Configuring different chart behavior for various media is made simple with an override mechanism. The priority of the override mechanism is based on order of specification of the matching media queries. - - type: hint - data: - title: Cross-browser support - classes: hint-cross-browser - text: For IE9 you need to use a matchMedia polyfill. You should take a look at Paul Irish's matchMedia polyfill. - side-notes: - - type: text - data: - text: With the clear separation of concerns within Chartist.js you're able to style your charts with CSS in @media queries. However, sometimes it requires to also control the behaviour of your charts depending on the media. For this purpose Chartist.js provides you with a simple configuration override mechanism based on media queries. diff --git a/source/site/examples.hbs b/source/site/examples.hbs deleted file mode 100644 index 8c0fb1d48..000000000 --- a/source/site/examples.hbs +++ /dev/null @@ -1,9 +0,0 @@ ---- -layout: content -page-class: examples -title: Chartist - Examples -description: Demos and examples of Chartist.js with live editing functionality ---- -{{#each page.sections}} - {{>section}} -{{/each}} \ No newline at end of file diff --git a/source/site/examples/behavior-with-jquery.js b/source/site/examples/behavior-with-jquery.js deleted file mode 100644 index 640d6c81e..000000000 --- a/source/site/examples/behavior-with-jquery.js +++ /dev/null @@ -1,47 +0,0 @@ -Chartist.Line('.ct-chart', { - labels: ['1', '2', '3', '4', '5', '6'], - series: [ - { - name: 'Fibonacci sequence', - data: [1, 2, 3, 5, 8, 13] - }, - { - name: 'Golden section', - data: [1, 1.618, 2.618, 4.236, 6.854, 11.09] - } - ] -}); - -var easeOutQuad = function (x, t, b, c, d) { - return -c * (t /= d) * (t - 2) + b; -}; - -var $chart = $('.ct-chart'); - -var $toolTip = $chart - .append('
') - .find('.tooltip') - .hide(); - -$chart.on('mouseenter', '.ct-point', function() { - var $point = $(this), - value = $point.attr('ct:value'), - seriesName = $point.parent().attr('ct:series-name'); - - $point.animate({'stroke-width': '50px'}, 300, easeOutQuad); - $toolTip.html(seriesName + '
' + value).show(); -}); - -$chart.on('mouseleave', '.ct-point', function() { - var $point = $(this); - - $point.animate({'stroke-width': '20px'}, 300, easeOutQuad); - $toolTip.hide(); -}); - -$chart.on('mousemove', function(event) { - $toolTip.css({ - left: event.offsetX - $toolTip.width() / 2 - 10, - top: event.offsetY - $toolTip.height() - 40 - }); -}); \ No newline at end of file diff --git a/source/site/examples/bi-polar-bar-interpolated.js b/source/site/examples/bi-polar-bar-interpolated.js deleted file mode 100644 index 63452f081..000000000 --- a/source/site/examples/bi-polar-bar-interpolated.js +++ /dev/null @@ -1,18 +0,0 @@ -var data = { - labels: ['W1', 'W2', 'W3', 'W4', 'W5', 'W6', 'W7', 'W8', 'W9', 'W10'], - series: [ - [1, 2, 4, 8, 6, -2, -1, -4, -6, -2] - ] -}; - -var options = { - high: 10, - low: -10, - axisX: { - labelInterpolationFnc: function(value, index) { - return index % 2 === 0 ? value : null; - } - } -}; - -Chartist.Bar('.ct-chart', data, options); \ No newline at end of file diff --git a/source/site/examples/example-gallery-four.js b/source/site/examples/example-gallery-four.js deleted file mode 100644 index 021af93d5..000000000 --- a/source/site/examples/example-gallery-four.js +++ /dev/null @@ -1,33 +0,0 @@ -var data = { - series: [60, 20] -}; - -var options = { - donut: true, - donutWidth: 40, - total: 100, - labelInterpolationFnc: function(value) { - return value + '%'; - } -}; - -var responsiveOptions = [ - [ - Foundation.media_queries.medium, - { - labelOffset: 30, - chartPadding: 10, - labelDirection: 'explode' - } - ], - [ - Foundation.media_queries.large, - { - labelOffset: -30, - chartPadding: 0, - labelDirection: 'implode' - } - ] -]; - -Chartist.Pie('.ct-chart', data, options, responsiveOptions); \ No newline at end of file diff --git a/source/site/examples/example-gallery-one.js b/source/site/examples/example-gallery-one.js deleted file mode 100644 index 6def30d9a..000000000 --- a/source/site/examples/example-gallery-one.js +++ /dev/null @@ -1,20 +0,0 @@ -var data = { - labels: ['W1', 'W2', 'W3', 'W4', 'W5', 'W6', 'W7', 'W8', 'W9'], - series: [ - [12, 9, 7, 8, 6, 4, 3, 2, 0], - [2, 1, 3.5, 7, 9, 8, 7.7, 4, 7], - [1, 3, 4, 5, 6, 8, 9, 10, 11], - [11, 7.5, 5.5, 5.5, 4, 3.5, 2, 1, 0] - ] -}; - -var options = { - axisX: { - offset: 15 - }, - axisY: { - offset: 15 - } -}; - -Chartist.Line('.ct-chart', data, options); \ No newline at end of file diff --git a/source/site/examples/example-gallery-three.js b/source/site/examples/example-gallery-three.js deleted file mode 100644 index a84d07dfd..000000000 --- a/source/site/examples/example-gallery-three.js +++ /dev/null @@ -1,40 +0,0 @@ -var data = { - labels: ['Day one', 'Day two', 'Day three', 'Day four'], - series: [20, 15, 40, 10] -}; - -var options = { - labelInterpolationFnc: function(value) { - return value.split(/\s+/).reduce(function(str, elem) { - return str + elem[0] + '.'; - }, ''); - } -}; - -var responsiveOptions = [ - [ - Foundation.media_queries.medium, - { - chartPadding: 30, - labelOffset: 50, - labelDirection: 'explode', - labelInterpolationFnc: function(value) { - return value; - } - } - ], - [ - Foundation.media_queries.large, - { - labelOffset: 80 - } - ], - [ - Foundation.media_queries.xlarge, - { - labelOffset: 100 - } - ] -]; - -Chartist.Pie('.ct-chart', data, options, responsiveOptions); \ No newline at end of file diff --git a/source/site/examples/example-gallery-two.js b/source/site/examples/example-gallery-two.js deleted file mode 100644 index 50ade3740..000000000 --- a/source/site/examples/example-gallery-two.js +++ /dev/null @@ -1,19 +0,0 @@ -var data = { - labels: ['1938', '1939', '1940', '1941', '1942', '1943'], - series: [ - [12000, 9000, 7000, 8000, 12000, 10000], - [2000, 1000, 3500, 7000, 5000, 9000] - ] -}; - -var options = { - seriesBarDistance: 5, - axisX: { - offset: 15 - }, - axisY: { - offset: 15 - } -}; - -Chartist.Bar('.ct-chart', data, options); \ No newline at end of file diff --git a/source/site/examples/example-line-months-interpolation.js b/source/site/examples/example-line-months-interpolation.js deleted file mode 100644 index cb82c5e73..000000000 --- a/source/site/examples/example-line-months-interpolation.js +++ /dev/null @@ -1,28 +0,0 @@ -var data = { - labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], - series: [ - [1, 2, 2.7, 0, 3, 5, 3, 4, 8, 10, 12, 7], - [0, 1.2, 2, 7, 2.5, 9, 5, 8, 9, 11, 14, 4], - [10, 9, 8, 6.5, 6.8, 6, 5.4, 5.3, 4.5, 4.4, 3, 2.8] - ] -}; - -var responsiveOptions = [ - [ - Foundation.media_queries.small, - { - axisX: { - labelInterpolationFnc: function (value, index) { - // Interpolation function causes only every 2nd label to be displayed - if (index % 2 !== 0) { - return false; - } else { - return value; - } - } - } - } - ] -]; - -Chartist.Line('.ct-chart', data, null, responsiveOptions); \ No newline at end of file diff --git a/source/site/examples/example-line-simple-responsive.js b/source/site/examples/example-line-simple-responsive.js deleted file mode 100644 index a3ddef6ad..000000000 --- a/source/site/examples/example-line-simple-responsive.js +++ /dev/null @@ -1,41 +0,0 @@ -/* Add a basic data series with six labels and values */ -var data = { - labels: ['1', '2', '3', '4', '5', '6'], - series: [ - { - data: [1, 2, 3, 5, 8, 13] - } - ] -}; - -/* Set some base options (settings will override the default settings in Chartist.js *see default settings*). We are adding a basic label interpolation function for the xAxis labels. */ -var options = { - axisX: { - labelInterpolationFnc: function(value) { - return 'Calendar Week ' + value; - } - } -}; - -/* Now we can specify multiple responsive settings that will override the base settings based on order and if the media queries match. In this example we are changing the visibility of dots and lines as well as use different label interpolations for space reasons. */ -var responsiveOptions = [ - ['screen and (min-width: 641px) and (max-width: 1024px)', { - showPoint: false, - axisX: { - labelInterpolationFnc: function(value) { - return 'Week ' + value; - } - } - }], - ['screen and (max-width: 640px)', { - showLine: false, - axisX: { - labelInterpolationFnc: function(value) { - return 'W' + value; - } - } - }] -]; - -/* Initialize the chart with the above settings */ -Chartist.Line('#my-chart', data, options, responsiveOptions); \ No newline at end of file diff --git a/source/site/examples/example-simple-bar.js b/source/site/examples/example-simple-bar.js deleted file mode 100644 index 0e1c945ac..000000000 --- a/source/site/examples/example-simple-bar.js +++ /dev/null @@ -1,32 +0,0 @@ -var data = { - labels: ['Jan', 'Feb', 'Mar', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], - series: [ - [5, 4, 3, 7, 5, 10, 3, 4, 8, 10, 6, 8], - [3, 2, 9, 5, 4, 6, 4, 6, 7, 8, 7, 4] - ] -}; - -var options = { - seriesBarDistance: 15 -}; - -var responsiveOptions = [ - ['screen and (min-width: 641px) and (max-width: 1024px)', { - seriesBarDistance: 10, - axisX: { - labelInterpolationFnc: function (value) { - return value; - } - } - }], - ['screen and (max-width: 640px)', { - seriesBarDistance: 5, - axisX: { - labelInterpolationFnc: function (value) { - return value[0]; - } - } - }] -]; - -Chartist.Bar('.ct-chart', data, options, responsiveOptions); \ No newline at end of file diff --git a/source/site/examples/line-scatter-random.js b/source/site/examples/line-scatter-random.js deleted file mode 100644 index 2bf32446e..000000000 --- a/source/site/examples/line-scatter-random.js +++ /dev/null @@ -1,36 +0,0 @@ -var times = function(n) { - return Array.apply(null, new Array(n)); -}; - -var data = times(52).map(Math.random).reduce(function(data, rnd, index) { - data.labels.push(index + 1); - data.series.forEach(function(series) { - series.push(Math.random() * 100) - }); - - return data; -}, { - labels: [], - series: times(4).map(function() { return new Array() }) -}); - -var options = { - showLine: false, - axisX: { - labelInterpolationFnc: function(value, index) { - return index % 13 === 0 ? 'W' + value : null; - } - } -}; - -var responsiveOptions = [ - ['screen and (min-width: 640px)', { - axisX: { - labelInterpolationFnc: function(value, index) { - return index % 4 === 0 ? 'W' + value : null; - } - } - }] -]; - -Chartist.Line('.ct-chart', data, options, responsiveOptions); \ No newline at end of file diff --git a/source/site/examples/overlapping-bars.js b/source/site/examples/overlapping-bars.js deleted file mode 100644 index 38877e41e..000000000 --- a/source/site/examples/overlapping-bars.js +++ /dev/null @@ -1,24 +0,0 @@ -var data = { - labels: ['Jan', 'Feb', 'Mar', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], - series: [ - [5, 4, 3, 7, 5, 10, 3, 4, 8, 10, 6, 8], - [3, 2, 9, 5, 4, 6, 4, 6, 7, 8, 7, 4] - ] -}; - -var options = { - seriesBarDistance: 10 -}; - -var responsiveOptions = [ - ['screen and (max-width: 640px)', { - seriesBarDistance: 5, - axisX: { - labelInterpolationFnc: function (value) { - return value[0]; - } - } - }] -]; - -Chartist.Bar('.ct-chart', data, options, responsiveOptions); \ No newline at end of file diff --git a/source/site/examples/pie-with-custom-labels.js b/source/site/examples/pie-with-custom-labels.js deleted file mode 100644 index 765023565..000000000 --- a/source/site/examples/pie-with-custom-labels.js +++ /dev/null @@ -1,27 +0,0 @@ -var data = { - labels: ['Bananas', 'Apples', 'Grapes'], - series: [20, 15, 40] -}; - -var options = { - labelInterpolationFnc: function(value) { - return value[0] - } -}; - -var responsiveOptions = [ - ['screen and (min-width: 640px)', { - chartPadding: 30, - labelOffset: 100, - labelDirection: 'explode', - labelInterpolationFnc: function(value) { - return value; - } - }], - ['screen and (min-width: 1024px)', { - labelOffset: 80, - chartPadding: 20 - }] -]; - -Chartist.Pie('.ct-chart', data, options, responsiveOptions); \ No newline at end of file diff --git a/source/site/examples/simple-configuration-chart.js b/source/site/examples/simple-configuration-chart.js deleted file mode 100644 index 270e3133b..000000000 --- a/source/site/examples/simple-configuration-chart.js +++ /dev/null @@ -1,38 +0,0 @@ -// Our labels and three data series -var data = { - labels: ['Week1', 'Week2', 'Week3', 'Week4', 'Week5', 'Week6'], - series: [ - [5, 4, 3, 7, 5, 10], - [3, 2, 9, 5, 4, 6], - [2, 1, -3, -4, -2, 0] - ] -}; - -// We are setting a few options for our chart and override the defaults -var options = { - // Don't draw the line chart points - showPoint: false, - // Disable line smoothing - lineSmooth: false, - // X-Axis specific configuration - axisX: { - // We can disable the grid for this axis - showGrid: false, - // and also don't show the label - showLabel: false - }, - // Y-Axis specific configuration - axisY: { - // Lets offset the chart a bit from the labels - offset: 40, - // The label interpolation function enables you to modify the values - // used for the labels on each axis. Here we are converting the - // values into million pound. - labelInterpolationFnc: function(value) { - return '$' + value + 'm'; - } - } -}; - -// All you need to do is pass your configuration as third parameter to the chart function -Chartist.Line('.ct-chart', data, options); \ No newline at end of file diff --git a/source/site/examples/simple-gauge-chart.js b/source/site/examples/simple-gauge-chart.js deleted file mode 100644 index eb21ffcc7..000000000 --- a/source/site/examples/simple-gauge-chart.js +++ /dev/null @@ -1,9 +0,0 @@ -Chartist.Pie('.ct-chart', { - series: [20, 10, 30, 40] -}, { - donut: true, - donutWidth: 60, - startAngle: 270, - total: 200, - showLabel: false -}); \ No newline at end of file diff --git a/source/site/examples/simple-line-chart.js b/source/site/examples/simple-line-chart.js deleted file mode 100644 index ae35681e1..000000000 --- a/source/site/examples/simple-line-chart.js +++ /dev/null @@ -1,8 +0,0 @@ -Chartist.Line('.ct-chart', { - labels: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'], - series: [ - [12, 9, 7, 8, 5], - [2, 1, 3.5, 7, 3], - [1, 3, 4, 5, 6] - ] -}); \ No newline at end of file diff --git a/source/site/examples/simple-pie-chart.js b/source/site/examples/simple-pie-chart.js deleted file mode 100644 index 6899fb245..000000000 --- a/source/site/examples/simple-pie-chart.js +++ /dev/null @@ -1,11 +0,0 @@ -var data = { - series: [5, 3, 4] -}; - -var sum = function(a, b) { return a + b }; - -Chartist.Pie('.ct-chart', data, { - labelInterpolationFnc: function(value) { - return Math.round(value / data.series.reduce(sum) * 100) + '%'; - } -}); \ No newline at end of file diff --git a/source/site/getting-started.hbs b/source/site/getting-started.hbs deleted file mode 100644 index f417c7a0a..000000000 --- a/source/site/getting-started.hbs +++ /dev/null @@ -1,9 +0,0 @@ ---- -layout: content -page-class: getting-started -title: Chartist - Getting started -description: Learn how to use Chartist.js ---- -{{#each page.sections}} - {{>section}} -{{/each}} \ No newline at end of file diff --git a/source/site/helpers/chartist-helpers.js b/source/site/helpers/chartist-helpers.js deleted file mode 100644 index 465f9d567..000000000 --- a/source/site/helpers/chartist-helpers.js +++ /dev/null @@ -1,27 +0,0 @@ -'use strict'; - -var fs = require('fs'); - -// Export helpers -module.exports.register = function (Handlebars, opt, params) { - // The helpers to be exported - var helpers = { - - snippetPath: function (snippetId, snippetLang) { - return 'source/site/code-snippets/' + snippetId + '.' + snippetLang || 'js'; - }, - - exampleCode: function(exampleId) { - return new Buffer(fs.readFileSync('source/site/examples/' + exampleId + '.js', { - encoding: 'utf8' - }), 'utf8').toString('base64'); - } - }; - - opt = opt || {}; - for (var helper in helpers) { - if (helpers.hasOwnProperty(helper)) { - Handlebars.registerHelper(helper, helpers[helper]); - } - } -}; diff --git a/source/site/helpers/common-helpers.js b/source/site/helpers/common-helpers.js deleted file mode 100644 index 374221e0b..000000000 --- a/source/site/helpers/common-helpers.js +++ /dev/null @@ -1,83 +0,0 @@ -/** - * Common Handlebars Helpers - * Copyright (c) 2014 Gion Kunz - * Licensed under the WTFPL License (WTFPL). - */ -'use strict'; - -var path = require('path'); -var fs = require('fs'); - -// Export helpers -module.exports.register = function (Handlebars, opt, params) { - // Loading package.json for later use - var pkg = JSON.parse(fs.readFileSync(path.join(process.cwd(), 'package.json'))); - - function slugify(str) { - return str - .toLowerCase() - .replace(/[^\w ]+/g,'') - .replace(/ +/g,'-'); - } - - // The helpers to be exported - var helpers = { - - pkg: function (key) { - return pkg[key]; - }, - - escape: function(str) { - return Handlebars.Utils.escapeExpression(str); - }, - - jsonStringify: function(obj) { - return JSON.stringify(obj); - }, - - slugify: function(str) { - return slugify(str); - }, - - concat: function() { - var arr = []; - for(var i = 0; i < arguments.length - 1; i++) { - arr[i] = arguments[i]; - } - - return arr.join(''); - }, - - partial: function(name, context) { - var partial = Handlebars.partials[name]; - - // Check if partial is not found, invalid or un-compiled and handle accordingly - if(!partial) { - throw 'Could not find partial with name "' + name + '".'; - } else if(typeof partial === 'string') { - // Compile partial as its still a string and update Handlebars - partial = Handlebars.partials[name] = Handlebars.compile(Handlebars.partials[name]); - } else if(typeof partial !== 'function') { - throw 'Found unknown type of partial "' + name + '" (' + typeof Handlebars.partials[name] + - ') in Handlebars partial Array => ' + Handlebars.partials; - } - - return new Handlebars.SafeString(partial(context || this)); - }, - - atob: function(a) { - return new Buffer(a, 'base64').toString('utf8'); - }, - - btoa: function(b) { - return new Buffer(b, 'utf8').toString('base64'); - } - }; - - opt = opt || {}; - for (var helper in helpers) { - if (helpers.hasOwnProperty(helper)) { - Handlebars.registerHelper(helper, helpers[helper]); - } - } -}; diff --git a/source/site/helpers/dox-helpers.js b/source/site/helpers/dox-helpers.js deleted file mode 100644 index edaf3ea67..000000000 --- a/source/site/helpers/dox-helpers.js +++ /dev/null @@ -1,70 +0,0 @@ -'use strict'; - -var path = require('path'), - _ = require('lodash'); - -// Export helpers -module.exports.register = function (Handlebars, opt, params) { - // The helpers to be exported - var helpers = { - - doxTag: function(doxElement, doxTagType) { - return _.find(doxElement.tags, {type: doxTagType}); - }, - - doxTagProperty: function(doxElement, doxTagType, doxTagProperty) { - var doxTag = helpers.doxTag(doxElement, doxTagType); - - if(doxTag) { - return doxTag[doxTagProperty]; - } else { - return doxTag; - } - }, - - doxHash: function(doxElement) { - return [helpers.doxTagProperty(doxElement, 'memberof', 'string'), - doxElement.ctx.type, - doxElement.ctx.name].join(' ') - .toLowerCase() - .replace(/[^\w ]+/g,'') - .replace(/ +/g,'-'); - }, - - doxTagsOfType: function(doxElement, doxTagType) { - return _.filter(doxElement.tags, {type: doxTagType}); - }, - - doxTransform: function(dox) { - return dox.map(function(doxFile) { - return { - fileName: path.basename(doxFile.file), - modules: doxFile.dox.reduce(function(arr, doxElement) { - var doxModuleName = helpers.doxTagProperty(doxElement, 'module', 'string'); - - if(doxModuleName) { - arr.push({ - name: doxModuleName, - description: doxElement.description.summary, - isPrivate: doxElement.isPrivate, - members: doxFile.dox.filter(function(doxFilterElement) { - return helpers.doxTagProperty(doxFilterElement, 'memberof', 'string') === doxModuleName; - }) - }); - } - - return arr; - }, []) - }; - }); - } - - }; - - opt = opt || {}; - for (var helper in helpers) { - if (helpers.hasOwnProperty(helper)) { - Handlebars.registerHelper(helper, helpers[helper]); - } - } -}; diff --git a/source/site/helpers/lorem-helper.js b/source/site/helpers/lorem-helper.js deleted file mode 100644 index 9ee422797..000000000 --- a/source/site/helpers/lorem-helper.js +++ /dev/null @@ -1,91 +0,0 @@ -/** - * Lorem Handlebars Helpers - * Copyright (c) 2014 Gion Kunz - * Licensed under the WTFPL License (WTFPL). - */ -'use strict'; - -var seed = require('seed-random'); - -// Export helpers -module.exports.register = function (Handlebars, opt, params) { - var loremText = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit Nullam in pharetra nisl Mauris dictum fermentum malesuada Donec tincidunt, lectus nec tempor eleifend, sem enim rhoncus nibh, nec ultricies ante lectus sit amet mi Proin cursus dolor in nisl varius elementum Aliquam blandit lobortis adipiscing Proin euismod est non feugiat venenatis Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Aliquam ac neque consectetur, ullamcorper neque quis, commodo ligula In ornare tempus feugiat Suspendisse ut pretium dui, at egestas velit Etiam ultricies, nisl quis gravida condimentum, dui nisl congue ligula, porta consectetur est sapien viverra est Donec quis ipsum quis metus luctus porttitor sed id justo Proin ultricies adipiscing dolor, luctus interdum urna ullamcorper sit amet Phasellus mollis erat egestas urna tincidunt viverra Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas Nam est ante, blandit vitae porta sed, consectetur vitae libero Sed sit amet auctor diam, eu ullamcorper nulla Aenean interdum, augue nec ullamcorper aliquam, libero justo pellentesque libero, vitae venenatis velit justo pellentesque enim Nam lobortis tortor non sagittis mollis Integer commodo eget nulla vel tincidunt Cras vitae vestibulum ipsum, a sollicitudin erat Cras feugiat vehicula magna, nec vehicula massa lacinia in Nam cursus arcu cursus felis feugiat, vel tincidunt eros aliquet Sed magna est, tincidunt a porta id, aliquam eu orci Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus Donec nec tempus eros Mauris placerat, nisi sit amet varius venenatis, arcu felis cursus risus, ut ultricies tortor lorem nec massa Integer molestie mattis tortor, nec pretium augue accumsan at Mauris nisi risus, hendrerit in libero a, accumsan tincidunt nunc Ut id volutpat massa Duis mattis tellus ut massa ultricies volutpat Curabitur non ante vel odio tempor condimentum Duis eu sollicitudin risus Pellentesque eget metus'; - var loremWords = loremText.split(' '); - var random = seed(loremText); - - function initCap(str) { - return str.toLowerCase().replace(/(?:^|\s)[a-z]/g, function (m) { - return m.toUpperCase(); - }); - } - - function randomInt(min, max) { - min = min || (min === 0 ? 0 : -Math.pow(2, 53)); - max = max || (max === 0 ? 0 : Math.pow(2, 53)); - - return Math.floor(random() * (max - min + 1)) + min; - } - - function n(c, fnc) { - for(var i = 0; i < c; i++) fnc(i, c); - } - - function validifyNumber(number, fallback) { - // If valid number in string, will be converted - number = +number; - // undefined, Object, NaN, null etc is not > 0 - if(number > 0) { - return number; - } else { - return fallback; - } - } - - // The helpers to be exported - var helpers = { - - loremWord: function () { - return initCap(loremWords[randomInt(0) % loremWords.length].replace(/[,]/g, '')); - }, - - loremWords: function (count) { - count = validifyNumber(count, 1); - - var words = []; - n(count, function() { - words.push(loremWords[randomInt(0, loremWords.length)]); - }); - - return words.join(' '); - }, - - loremSentence: function() { - return helpers.loremWords(randomInt(5, 20)).replace(/^[a-z]/, function(m) { - return m.toUpperCase(); - }) + '.'; - }, - - loremSentences: function(count) { - count = validifyNumber(count, 1); - - var sentences = []; - - n(count, function() { - sentences.push(helpers.loremSentence()); - }); - - return sentences.join(' '); - }, - - loremParagraph: function () { - return helpers.loremSentences(randomInt(4, 10)); - } - }; - - opt = opt || {}; - for (var helper in helpers) { - if (helpers.hasOwnProperty(helper)) { - Handlebars.registerHelper(helper, helpers[helper]); - } - } -}; diff --git a/source/site/index.hbs b/source/site/index.hbs deleted file mode 100644 index 2e6010ac9..000000000 --- a/source/site/index.hbs +++ /dev/null @@ -1,34 +0,0 @@ ---- -layout: landing -page-class: full -title: Chartist - Simple responsive charts -description: Create responsive, scalable and good looking charts with chartist.js. ---- -

You may think that this is just yet an other charting library. But Chartist.js is the product of -a community that was disappointed about the abilities provided by other charting libraries. Of course there are hundreds -of other great charting libraries but after using them there were always tweaks you would have wished for that were not - included.

- -

Highly customizable responsive charts

- - -

Facts about Chartist

-

The following facts should give you an overview why to choose Chartists as your front-end chart generator:

-
    -
  • Simple handling while using convention over configuration
  • -
  • Great flexibility while using clear separation of concerns (Style with CSS & control with JS)
  • -
  • Usage of SVG (Yes! SVG is the future of illustration in web!)
  • -
  • Fully responsive and DPI independent
  • -
  • Responsive configuration with media queries
  • -
  • Fully built and customizable with SASS
  • -
- -{{#each page.sections}} - {{>section}} -{{/each}} \ No newline at end of file diff --git a/source/site/layouts/content.hbs b/source/site/layouts/content.hbs deleted file mode 100644 index 444128129..000000000 --- a/source/site/layouts/content.hbs +++ /dev/null @@ -1,21 +0,0 @@ ---- -layout: default ---- -
- {{>navigation}} -
-
-

{{title}}

-
- - {{#if page.side-nav}} - {{partial page.side-nav this}} - {{else}} - {{>side-navigation}} - {{/if}} - -
- {{>body}} -
-
-
\ No newline at end of file diff --git a/source/site/layouts/default.hbs b/source/site/layouts/default.hbs deleted file mode 100644 index 8dcf50571..000000000 --- a/source/site/layouts/default.hbs +++ /dev/null @@ -1,98 +0,0 @@ - - - - - - - - - - {{ title }} - - - - - - - - - - - - - - -{{> body }} - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/source/site/layouts/landing.hbs b/source/site/layouts/landing.hbs deleted file mode 100644 index f1e29a36d..000000000 --- a/source/site/layouts/landing.hbs +++ /dev/null @@ -1,30 +0,0 @@ ---- -layout: default ---- -
-
-
Chartist.js - Simple responsive charts -
-
-
- -
-
- -
- - {{> navigation }} - -
-
-

{{title}}

-
-
- {{> body }} -
-
-
\ No newline at end of file diff --git a/source/site/partials/api-side-navigation.hbs b/source/site/partials/api-side-navigation.hbs deleted file mode 100644 index 2a2d71669..000000000 --- a/source/site/partials/api-side-navigation.hbs +++ /dev/null @@ -1,14 +0,0 @@ - \ No newline at end of file diff --git a/source/site/partials/code-snippet.hbs b/source/site/partials/code-snippet.hbs deleted file mode 100644 index adc2f44b6..000000000 --- a/source/site/partials/code-snippet.hbs +++ /dev/null @@ -1,4 +0,0 @@ -{{#if button}}{{/if}} -{{! if path is there then we load the file and escape in path otherwise we lookup a file called id.lang (index.html, - test.js etc.) }} -
{{#if path}}{{glob path}}{{else}}{{glob (snippetPath id lang)}}{{/if}}
\ No newline at end of file diff --git a/source/site/partials/code.hbs b/source/site/partials/code.hbs deleted file mode 100644 index 6405be6b3..000000000 --- a/source/site/partials/code.hbs +++ /dev/null @@ -1,2 +0,0 @@ -{{#if button}}{{/if}} -{{code}} \ No newline at end of file diff --git a/source/site/partials/dox/dox-member.hbs b/source/site/partials/dox/dox-member.hbs deleted file mode 100644 index 546d7b34c..000000000 --- a/source/site/partials/dox/dox-member.hbs +++ /dev/null @@ -1,50 +0,0 @@ -
-
-
{{ctx.type}} {{ctx.string}}
- -
-
-    {{code}}
-  
-
-
{{{description.summary}}}
- - {{#is ctx.type 'method'}} - {{#if (doxTagsOfType this 'param')}} -
Parameters
- {{#each (doxTagsOfType this 'param')}} -
- {{name}} - ({{#each types}} - {{this}} - {{/each}}) -
{{description}}
-
- {{/each}} - {{/if}} - - {{#if (doxTagsOfType this 'return')}} - {{#with (doxTag this 'return')}} -
Returns
- -
- ({{#each types}} - {{this}} - {{/each}}) -
{{description}}
-
- {{/with}} - {{/if}} - - {{/is}} - - {{#if (doxTagsOfType this 'example')}} -
Examples
- {{#each (doxTagsOfType this 'example')}} -
{{string}}
- {{/each}} - {{/if}} - -
- -
\ No newline at end of file diff --git a/source/site/partials/dox/dox-module.hbs b/source/site/partials/dox/dox-module.hbs deleted file mode 100644 index 771c74c6e..000000000 --- a/source/site/partials/dox/dox-module.hbs +++ /dev/null @@ -1,15 +0,0 @@ -
-
-

- Module {{name}} -

-
- {{{description}}} -
-
- {{#each members}} - {{>dox-member}} - {{/each}} -
-
-
\ No newline at end of file diff --git a/source/site/partials/dox/dox-section.hbs b/source/site/partials/dox/dox-section.hbs deleted file mode 100644 index d25b69da9..000000000 --- a/source/site/partials/dox/dox-section.hbs +++ /dev/null @@ -1,14 +0,0 @@ -
-
-

{{fileName}}

-
-
- {{#each modules}} - {{>dox-module}} - {{/each}} -
- - -
\ No newline at end of file diff --git a/source/site/partials/example-chart.hbs b/source/site/partials/example-chart.hbs deleted file mode 100644 index ba765dde4..000000000 --- a/source/site/partials/example-chart.hbs +++ /dev/null @@ -1,5 +0,0 @@ -
-{{#if show-code-button}} - -
{{atob (exampleCode id)}}
-{{/if}} \ No newline at end of file diff --git a/source/site/partials/heading.hbs b/source/site/partials/heading.hbs deleted file mode 100644 index e4d128af4..000000000 --- a/source/site/partials/heading.hbs +++ /dev/null @@ -1,2 +0,0 @@ -{{title}} \ No newline at end of file diff --git a/source/site/partials/hint.hbs b/source/site/partials/hint.hbs deleted file mode 100644 index ff66bbde0..000000000 --- a/source/site/partials/hint.hbs +++ /dev/null @@ -1,4 +0,0 @@ -
-
{{title}}
-
{{{text}}}
-
\ No newline at end of file diff --git a/source/site/partials/live-example.hbs b/source/site/partials/live-example.hbs deleted file mode 100644 index 09f4af29d..000000000 --- a/source/site/partials/live-example.hbs +++ /dev/null @@ -1,19 +0,0 @@ -
-
- {{title}} -
-
-
-
- -
\ No newline at end of file diff --git a/source/site/partials/navigation.hbs b/source/site/partials/navigation.hbs deleted file mode 100644 index 7a15d6cff..000000000 --- a/source/site/partials/navigation.hbs +++ /dev/null @@ -1,23 +0,0 @@ - \ No newline at end of file diff --git a/source/site/partials/section.hbs b/source/site/partials/section.hbs deleted file mode 100644 index 1f74a6d95..000000000 --- a/source/site/partials/section.hbs +++ /dev/null @@ -1,18 +0,0 @@ -
-
- {{>heading}} -
-
- {{#each items}} - {{partial type data}} - {{/each}} -
- - {{#if side-notes}} - - {{/if}} -
\ No newline at end of file diff --git a/source/site/partials/side-navigation.hbs b/source/site/partials/side-navigation.hbs deleted file mode 100644 index 9d9d3f903..000000000 --- a/source/site/partials/side-navigation.hbs +++ /dev/null @@ -1,18 +0,0 @@ - \ No newline at end of file diff --git a/source/site/partials/sub-section.hbs b/source/site/partials/sub-section.hbs deleted file mode 100644 index fba1e5bf3..000000000 --- a/source/site/partials/sub-section.hbs +++ /dev/null @@ -1,6 +0,0 @@ -
- {{>heading}} - {{#each items}} - {{partial type data}} - {{/each}} -
\ No newline at end of file diff --git a/source/site/partials/table.hbs b/source/site/partials/table.hbs deleted file mode 100644 index 1f295202f..000000000 --- a/source/site/partials/table.hbs +++ /dev/null @@ -1,22 +0,0 @@ -{{#if button}}{{button}}{{/if}} - - {{#if header}} - - - {{#each header}} - - {{/each}} - - - {{/if}} - - - {{#each rows}} - - {{#each this}} - - {{/each}} - - {{/each}} - -
{{this}}
{{this}}
\ No newline at end of file diff --git a/source/site/partials/text.hbs b/source/site/partials/text.hbs deleted file mode 100644 index a90816d34..000000000 --- a/source/site/partials/text.hbs +++ /dev/null @@ -1 +0,0 @@ -

{{{text}}}

\ No newline at end of file diff --git a/source/styles/_modules.scss b/source/styles/_modules.scss deleted file mode 100644 index 41ecb6cac..000000000 --- a/source/styles/_modules.scss +++ /dev/null @@ -1,3 +0,0 @@ -@import "http://github.com/modules/common"; -@import "http://github.com/modules/scale"; -@import "http://github.com/modules/animation"; diff --git a/source/styles/chartist.scss b/source/styles/chartist.scss deleted file mode 100644 index a9fb74985..000000000 --- a/source/styles/chartist.scss +++ /dev/null @@ -1,132 +0,0 @@ -@import "http://github.com/modules"; -@import "http://github.com/settings/chartist-settings"; - -@mixin ct-responsive-svg-container($width: 100%, $ratio: $ct-container-ratio) { - display: block; - position: relative; - width: $width; - - &:before { - display: block; - float: left; - content: ""; - width: 0; - height: 0; - padding-bottom: $ratio * 100%; - } - - &:after { - content: ""; - display: table; - clear: both; - } - - > svg { - display: block; - position: absolute; - top: 0; - left: 0; - width: 100%; - height: 100%; - } -} - -@mixin ct-chart-label($ct-text-color: $ct-text-color, $ct-text-size: $ct-text-size) { - fill: $ct-text-color; - font-size: $ct-text-size; -} - -@mixin ct-chart-grid($ct-grid-color: $ct-grid-color, $ct-grid-width: $ct-grid-width, $ct-grid-dasharray: $ct-grid-dasharray) { - stroke: $ct-grid-color; - stroke-width: $ct-grid-width; - - @if ($ct-grid-dasharray) { - stroke-dasharray: $ct-grid-dasharray; - } -} - -@mixin ct-chart-point($ct-point-size: $ct-point-size, $ct-point-shape: $ct-point-shape) { - stroke-width: $ct-point-size; - stroke-linecap: $ct-point-shape; -} - -@mixin ct-chart-line($ct-line-width: $ct-line-width, $ct-line-dasharray: $ct-line-dasharray) { - fill: none; - stroke-width: $ct-line-width; - - @if ($ct-line-dasharray) { - stroke-dasharray: $ct-line-dasharray; - } -} - -@mixin ct-chart-bar($ct-bar-width: $ct-bar-width) { - fill: none; - stroke-width: $ct-bar-width; -} - -@mixin ct-chart-donut($ct-donut-width: $ct-donut-width) { - fill: none; - stroke-width: $ct-donut-width; -} - -@mixin ct-chart-series-color($color) { - .#{$ct-class-point}, .#{$ct-class-line}, .#{$ct-class-bar}, .#{$ct-class-slice}.#{$ct-class-donut} { - stroke: $color; - } - - .#{$ct-class-slice}:not(.#{$ct-class-donut}) { - fill: $color; - } -} - -@mixin ct-chart($ct-container-ratio: $ct-container-ratio, $ct-text-color: $ct-text-color, $ct-text-size: $ct-text-size, $ct-grid-color: $ct-grid-color, $ct-grid-width: $ct-grid-width, $ct-grid-dasharray: $ct-grid-dasharray, $ct-point-size: $ct-point-size, $ct-point-shape: $ct-point-shape, $ct-line-width: $ct-line-width, $ct-bar-width: $ct-bar-width, $ct-donut-width: $ct-donut-width, $ct-series-names: $ct-series-names, $ct-series-colors: $ct-series-colors) { - .#{$ct-class-label} { - @include ct-chart-label($ct-text-color, $ct-text-size); - } - - .#{$ct-class-grid} { - @include ct-chart-grid($ct-grid-color, $ct-grid-width, $ct-grid-dasharray); - } - - .#{$ct-class-point} { - @include ct-chart-point($ct-point-size, $ct-point-shape); - } - - .#{$ct-class-line} { - @include ct-chart-line($ct-line-width); - } - - .#{$ct-class-bar} { - @include ct-chart-bar($ct-bar-width); - } - - .#{$ct-class-slice}.#{$ct-class-donut} { - @include ct-chart-donut($ct-donut-width); - } - - @if $ct-include-colored-series { - .#{$ct-class-series} { - @for $i from 0 to length($ct-series-names) { - &.#{$ct-class-series}-#{nth($ct-series-names, $i + 1)} { - $color: nth($ct-series-colors, $i + 1); - - @include ct-chart-series-color($color); - } - } - } - } -} - -@if $ct-include-classes { - .#{$ct-class-chart} { - @include ct-chart(); - - @if $ct-include-alternative-responsive-containers { - @for $i from 0 to length($ct-scales-names) { - &.#{nth($ct-scales-names, $i + 1)} { - @include ct-responsive-svg-container($ratio: nth($ct-scales, $i + 1)); - } - } - } - } -} \ No newline at end of file diff --git a/source/styles/modules/_animation.scss b/source/styles/modules/_animation.scss deleted file mode 100644 index 1af626a1a..000000000 --- a/source/styles/modules/_animation.scss +++ /dev/null @@ -1,21 +0,0 @@ -@mixin keyframes($name) { - @-webkit-keyframes #{$name} { - @content; - } - @-moz-keyframes #{$name} { - @content; - } - @-ms-keyframes #{$name} { - @content; - } - @keyframes #{$name} { - @content; - } -} - -@mixin animation($name, $params) { - -webkit-animation: #{$name} $params; /* Safari 4+ */ - -moz-animation: #{$name} $params; /* Fx 5+ */ - -o-animation: #{$name} $params; /* Opera 12+ */ - animation: #{$name} $params; /* IE 10+ */ -} \ No newline at end of file diff --git a/source/styles/modules/_common.scss b/source/styles/modules/_common.scss deleted file mode 100644 index e29cd020a..000000000 --- a/source/styles/modules/_common.scss +++ /dev/null @@ -1,15 +0,0 @@ -@function reverse($list, $recursive: false) { - $result: (); - - @for $i from length($list)*-1 through -1 { - @if type-of(nth($list, abs($i))) == list and $recursive { - $result: append($result, reverse(nth($list, abs($i)), $recursive)); - } - - @else { - $result: append($result, nth($list, abs($i))); - } - } - - @return $result; -} \ No newline at end of file diff --git a/source/styles/modules/_scale.scss b/source/styles/modules/_scale.scss deleted file mode 100644 index 1a7a3b7d5..000000000 --- a/source/styles/modules/_scale.scss +++ /dev/null @@ -1,41 +0,0 @@ -$scale-minor-second: 15/16; -$scale-major-second: 8/9; -$scale-minor-third: 5/6; -$scale-major-third: 4/5; -$scale-perfect-fourth: 3/4; -$scale-perfect-fifth: 2/3; -$scale-minor-sixth: 5/8; -$scale-golden-section: 1/1.618; -$scale-major-sixth: 3/5; -$scale-minor-seventh: 9/16; -$scale-major-seventh: 8/15; -$scale-octave: 1/2; -$scale-major-tenth: 2/5; -$scale-major-eleventh: 3/8; -$scale-major-twelfth: 1/3; -$scale-double-octave: 1/4; - -@function generateScale($base: 16, $scale-type: $scale-golden-section, $limit-lower: 6, $limit-upper: 100) { - $scale: (); - $value: $base; - - @while $value > $limit-lower { - $value: $value * $scale-type; - @if $value > $limit-lower { - $scale: append($scale, $value); - } - } - - $scale: reverse($scale); - $scale: append($scale, $base); - - $value: $base; - @while $value < $limit-upper { - $value: $value / $scale-type; - @if $value < $limit-upper { - $scale: append($scale, $value); - } - } - - @return $scale; -} \ No newline at end of file diff --git a/source/styles/site/_api-doc.scss b/source/styles/site/_api-doc.scss deleted file mode 100644 index c38b6907a..000000000 --- a/source/styles/site/_api-doc.scss +++ /dev/null @@ -1,75 +0,0 @@ -.module-member { - margin-bottom: 2em; - background-color: mix(black, $color-white, 5%); - box-shadow: 3px 3px 0 rgba(0, 0, 0, 0.1); - padding: 10px; - - .member-header { - position: relative; - - .api-code-button { - @include button(); - text-transform: uppercase; - width: calc(100% + 20px); - margin: 0 -10px; - - - @media #{$medium-up} { - position: absolute; - width: auto; - margin: 0; - top: 0; - right: -10px; - padding: 0 10px; - height: 100%; - } - } - } - - .description { - margin-top: 1em; - margin-bottom: 2em; - } - - .member-title { - background: #453D3F; - padding: 10px; - margin: -10px -10px 0 -10px; - color: lighten($color-white, 10%); - text-transform: none; - } - - .api-example { - margin-top: 2em; - } - - .param { - margin-bottom: 0.5em; - - > code { - font-weight: bold; - } - } - - .param-type { - - > code { - background-color: rgba(255, 255, 255, 0.2); - padding: 0.1em 0.2em; - } - - &:after { - content: "╱"; - } - - &:last-of-type { - &:after { - content: none; - } - } - } - - pre { - margin: 0 -10px; - } -} \ No newline at end of file diff --git a/source/styles/site/_base.scss b/source/styles/site/_base.scss deleted file mode 100644 index 754b39076..000000000 --- a/source/styles/site/_base.scss +++ /dev/null @@ -1,128 +0,0 @@ -$modular-scale: generateScale(16, $scale-perfect-fourth); - -body { - line-height: 1.54; - background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADIAAAAyCAYAAAAeP4ixAAAIoElEQVRoQ23a7bETOxCE4eNfJxEIBnKBYCAXCAZy4bpVPK4X1XWVWe+uPkYz3T0jHR6/fv16f3t+Pn369Pb8vZ9vP3/+fPv9+/d59uHDh/P748ePb1++fDnXvd937ff+69ev53nH2O+12btd9/n27dtps/vv37+fvnu233tm/I1rfvbs3Z65bly/N8ZjC2HMefB4vAxk8CbfZJuAwfrsGcMsxDg/fvw47TepBTByRqzdjNuzz58/n4WtnUXPlrXbs73veMbZs30ez0bvG3CT7crzovLnz58z2d7tu88G3eC7t5Ddr90+G0t0d7/nM3JjGkNERYyztOOU2dMI7b6fvdv38TT0QGur3+oYaSId5xlGisaitAnvcFuUPmu3T2G4BYn4novC5tsXDG+IQcUcrN3GeTwHeN+Em4yHYRHG17ket0jexZE9X7t994yBu78NFAk8mQPBjYPKm7U3pghxxPo9nv+8M3wT4gjI7B0D/4lpyAv/oLMFMmyTg5boFnbmwTORGjpEcmPsgw9gL2oHWuMIQwqRhQ4BZ8gGQdrd40GVjiDMy3OICNebFIxzyh/PtuCNYZFbhCjjnHkh4HCkqlMJrXQyblcTEQmRgmeT3oJAoTih44NNpbryjV91iggf257GHI7MgyIjZFUxYlAjQXHR2/sSsCrIo/qScE7j1UapqkWmZ/CiDna4chby/OdwZEYg/CYme5VMyWsdB7v1oWR4Jm8Uv+AgQiKC1FUs0V1b0SfrFNJiKveH7F2xRcic87REJZ/I9p2oWf7/8k2rAbmKE6gaR20sBN+7fcguJQSxjXsissxOTkuoarQwU6BFgnKQyIa8ULVoWVniK78Y3nnArVCupJNzue9ExOplVZ7nsV1n3OBUqPGOdq23kHbv9htUW7uBj/mbFwgQ+LrHo5Yzs+uoloRmUlhcAx8lCkFoUcloOWeTi17H4j2QxA2OQGbvIYUjtJfAFZmb65+EOMNhcZ14T701o0go73Vy+aayKZdsvMFvk8tHKmAwLgdV2e0v4kgut23sf1RrC6E2SHQaRZphl1csGHSqWnhQwhaeFQBtKaIM3zE4YHODmMT7eK7qFI3C12wMPgYFge4NZngTHQgyUhTnPbBE4NZb5pf4umUAKbmpOWvtFtnDkXLhzsbIfReGSoQZTqJvkUDUliHkXQQtrsbuHdg06a2NfQnnK4tOrVWF2QC8A88w7NrSYgtp2QKGhZ5MTJblBeOo61TZ99ZBBMBc1HHlFI3L7LRdSU2pLAhMNgAZtmDhVkjWaIaKMrJ6brHNXxxDGETBItlSDr9Uq+UIzLXmbw2FuMp0RnRvwgGEQZUAYozs9rkQolhbxBzTYrSqyZazkEFLYiKRMwQ516jlOYnmZfmCAMwg4kBeK7Ptt/koEA6KtFquiXDt5SV83HwnITazrxFviIK6SEli+7q2xW5LFp7CsW7OWhmAi1OUe5EkVuLT3qKb804Zvxc9ZKDXrTqVIyX82nUnx0hXOaEFn7wAZjjWOqpOKxxbEkGJyv11HGS/AV4mF/ritAluz220SCjxUAyq4dRUpBNhuxNVTYCqqDRaxuWEzX8iAqsiUQIjLo/JG/q09mIYLzF8V1iWW8CpUZQGNiaSN7FyqoW3TDoRoctICf+wWfUhBEgucd11U0sLcGzyAzse7x6n0muvtHbykLyF+IfsiwjsyZpVIrtGE5LJlhAWKtsPpqQTVBkqAgxshIzNgfKO6NuDiBiInkT5/L7fW1aTKiBBY/c9uqwE2ra2r0iTcIpnHA7ALcc/EvKdweWqXbvxO5l98gsWFML+Gx9kdFHZRJXAPRchk1EeC5vRcsz6tswh08hrHm1EWj8VAViv/atoRNSqBDViNA92J2hRnRwpi29Khxvr5/QFlERm/XryiVu2CERB/9eeXdJTqth/bwCliER5e0+YqRu+Vfn2W1L0nndxiXNEtAJxn9TL9o3y2Y8gt9KCcZukpIZZHtt7OaLPkFDoQZWXGd1Dc326zUVyTlBQgi2oTlxep/EGR7h16p7jKMPfo6EmPpGS5e1tJDBwxD81FGVTCuGH7XLrNGe+PeieDVRs719bXcZV0lo6W6g8ghPdq/AmbvSKoBwE5yBZjh4Vus6OQQ5MRUMRe+SX56vxapkS7az87/7dORWptCBjSaoMx0Oe7zmA7W35YXzP1H0SI7tUD6/ql4fkDKGDY1zpbm5tW4brC264xnsihFu83vIH9PAWB1Xmu7eIRvWUKLzqRbM3Y9RhJaUkaDHe2fysr8WprXrgxsv1esui5hoRsmjbYVA/EYE7k/J0t68iZPAWdrhxY5taySHln3H0ZSCoNIfham0gvbj6Ovut7OFKC7kNUhlcG0rVUxT7/h4lKQLLN1zq9mDGO6UUJerWqEvCuHXK+EVEIuQl4YL1e0MjKZrMoZtaCgxnLPjVw7J7YSZrF+b/V1ByAHGR605EeAL5bGqEuaRtXbX3zQPai+7GKTElRIT198pGF7/AaG3x695p1jmnjFdOrPN+C1nrpzvrW9Da87rMv3tbZ/mh+t+q2WJ4li2M7O7RH6OoXkXlZPZm525t10GZAXY9LVHSW4ykirgMJiI9hAARzrsr6FvlCA9FxUV2HY5Udr2QwBRoDhkaCVzAMd4sR0S1BO2f7Rycg2PnNRe1U6IQnkbmpVogoMYxSHnSMy2evMsRELEYGJ8nlSPgu/suVNW9vlLArreorP+QYWEb49RaQm/Q+xyqRz5C2xKCXKvHdu1envrU+/DNaOPeXOy2d79V2UoVtHjVWpQDYVtmkFHhv//ypI8oURzR4XmVdc+HVcXgyRmqZl4v37xTYW/cc2SqGGw9VW44USSfd7kCw/YL3svoFtKECrKMAmVOKxSJThMvfhjnddLYfbH0j6DdWzRjN9uDAEwr9rqpaja3xzCHxZ5t69//fICTajLnwlTSHBvjP9uuEN4BiDLbAAAAAElFTkSuQmCC); - background-position: 50% 50%; - background-repeat: repeat repeat; -} - -html { - box-sizing: border-box; -} - -*, *:before, *:after { - box-sizing: inherit; -} - -p:first-child { - margin-top: 0; -} - -a { - color: $color-red; - text-decoration: none; - - &:hover { - color: lighten($color-red, 10%); - } -} - -ul { - padding: 0; - - &.list { - list-style: disc outside none; - padding-left: 1em; - } -} - -pre { - white-space: normal; - - code { - white-space: pre-wrap; - } -} - -h1, h2, h3, h4, h5, h6 { - font-weight: 300; - text-transform: uppercase; - line-height: 1.2; - margin-top: 1em; - margin-bottom: 0.5em; - - &:first-child { - margin-top: 0; - } -} - -h2 { - font-size: rem-calc(nth($modular-scale, 6)); - font-weight: 400; - - @media #{$medium-up} { - font-size: rem-calc(nth($modular-scale, 8)); - font-weight: 300; - } -} - -h3 { - font-size: rem-calc(nth($modular-scale, 5)); - font-weight: 400; - - @media #{$medium-up} { - font-size: rem-calc(nth($modular-scale, 7)); - font-weight: 300; - } -} - -h4 { - font-size: rem-calc(nth($modular-scale, 4)); - font-weight: 700; - - @media #{$medium-up} { - font-size: rem-calc(nth($modular-scale, 6)); - font-weight: 400; - } -} - -h5 { - font-size: rem-calc(nth($modular-scale, 4)); - font-weight: 700; - margin-top: 2em; - - @media #{$medium-up} { - font-size: rem-calc(nth($modular-scale, 4)); - } -} - -h6 { - font-size: rem-calc(nth($modular-scale, 4)); - font-weight: 700; - margin-top: 2em; - - @media #{$medium-up} { - font-size: rem-calc(nth($modular-scale, 4)); - } -} - -table { - min-width: 50%; - text-align: left; - border-collapse: collapse; - - th, td { - padding: 0.5em 1em; - } - - tr { - th, td { - border-bottom: 1px solid rgba(0, 0, 0, 0.1); - } - } - - thead th { - padding: 0.8em 1em; - } -} \ No newline at end of file diff --git a/source/styles/site/_code-mirror-theme.scss b/source/styles/site/_code-mirror-theme.scss deleted file mode 100644 index b5209ec8b..000000000 --- a/source/styles/site/_code-mirror-theme.scss +++ /dev/null @@ -1,99 +0,0 @@ -.cm-s-chartist.CodeMirror { - background: $color-black; - color: lighten($color-white, 10%); - padding: rem-calc(nth($modular-scale, 5)); - font-family: "Source Code Pro", "Courier New", monospace !important; - line-height: 1.4; - word-wrap: break-word; - height: auto; - margin-bottom: rem-calc(nth($modular-scale, 5)); -} - -.cm-s-chartist div.CodeMirror-selected { - background: darken($color-black, 10%) !important; -} - -.cm-s-chartist .CodeMirror-gutters { - background: #f7f7f7; - border-right: 0px; -} - -.cm-s-chartist .CodeMirror-guttermarker { - color: $color-grapefruit; -} - -.cm-s-chartist .CodeMirror-guttermarker-subtle { - color: darken($color-black, 10%); -} - -.cm-s-chartist .CodeMirror-linenumber { - color: darken($color-black, 20%); -} - -.cm-s-chartist .CodeMirror-cursor { - border-left: 2px solid lighten($color-black, 10%) !important; -} - -.cm-s-chartist span.cm-comment { - color: lighten($color-black, 20%); -} - -.cm-s-chartist span.cm-atom { - color: $color-yellow; -} - -.cm-s-chartist span.cm-number { - color: $color-yellow; -} - -.cm-s-chartist span.cm-property, .cm-s-3024-day span.cm-attribute { - color: lighten($color-white, 10%); -} - -.cm-s-chartist span.cm-keyword { - color: $color-grapefruit; - font-weight: bold; -} - -.cm-s-chartist span.cm-string { - color: $color-yellow; -} - -.cm-s-chartist span.cm-variable { - color: lighten($color-white, 10%); -} - -.cm-s-chartist span.cm-variable-2 { - color: lighten($color-grapefruit, 20%); -} - -.cm-s-chartist span.cm-def { - color: lighten($color-grapefruit, 20%); -} - -.cm-s-chartist span.cm-bracket { - color: #3a3432; -} - -.cm-s-chartist span.cm-tag { - color: $color-grapefruit; - font-weight: bold; -} - -.cm-s-chartist span.cm-link { - color: $color-yellow; -} - -.cm-s-chartist span.cm-error { - background-color: $color-grapefruit; - color: $color-black; -} - -.cm-s-chartist .CodeMirror-activeline-background { - background: #e8f2ff !important; -} - -.cm-s-chartist .CodeMirror-matchingbracket { - text-decoration: underline; - color: white !important; -} diff --git a/source/styles/site/_example-charts.scss b/source/styles/site/_example-charts.scss deleted file mode 100644 index 63fa9a9fb..000000000 --- a/source/styles/site/_example-charts.scss +++ /dev/null @@ -1,59 +0,0 @@ -#chartist-guy #chart-canvas { - @include ct-chart($ct-text-color: darken($color-white, 50%), $ct-grid-color: darken($color-white, 20%)); - - .ct-series { - &.ct-series-a { - .ct-point { - @include ct-chart-point($ct-point-shape: square, $ct-point-size: 8px); - } - - .ct-line { - @include ct-chart-line($ct-line-dasharray: 5px); - @include animation(dashoffset, 1s linear infinite); - } - } - } -} - -#example-line-months-interpolation { - @include ct-chart($ct-text-color: lighten($color-gray, 30%), $ct-grid-color: lighten($color-gray, 5%), $ct-grid-dasharray: 3px); - - .ct-series { - &.ct-series-a { - .ct-point { - @include ct-chart-point($ct-point-shape: square); - } - - .ct-line { - @include ct-chart-line($ct-line-width: 4px, $ct-line-dasharray: 5px); - @include animation(dashoffset, 1s linear infinite); - } - } - - &.ct-series-b { - .ct-point { - @include animation(bouncing-stroke, 0.5s ease infinite); - } - - .ct-line { - @include ct-chart-line($ct-line-width: 3px); - } - } - - &.ct-series-c { - .ct-point { - @include animation(exploding-stroke, 1s ease-out infinite); - } - - .ct-line { - @include ct-chart-line($ct-line-width: 2px, $ct-line-dasharray: 40px 3px); - } - } - } -} - -#behavior-with-jquery { - .ct-point { - @include ct-chart-point($ct-point-size: 20px); - } -} \ No newline at end of file diff --git a/source/styles/site/_highlight.scss b/source/styles/site/_highlight.scss deleted file mode 100644 index 2d12f6422..000000000 --- a/source/styles/site/_highlight.scss +++ /dev/null @@ -1,130 +0,0 @@ -/* -Chartist style - Licensed under WTFPL by Gion Kunz https://github.com/gionkunz/chartist-js -*/ - -.hljs { - display: block; - padding: rem-calc(nth($modular-scale, 5)); - background: $color-black; -} - -.hljs-tag, -.hljs-tag .hljs-title, -.hljs-keyword, -.hljs-literal, -.hljs-strong, -.hljs-change, -.hljs-winutils, -.hljs-flow, -.lisp .hljs-title, -.clojure .hljs-built_in, -.nginx .hljs-title, -.tex .hljs-special { - color: $color-grapefruit; -} - -.hljs { - color: lighten($color-white, 10%); -} - -.hljs .hljs-constant, -.asciidoc .hljs-code { - color: $color-grapefruit; -} - -.hljs-code, -.hljs-class .hljs-title, -.hljs-header { - color: lighten($color-white, 10%); -} - -.hljs-link_label, -.hljs-attribute, -.hljs-symbol, -.hljs-symbol .hljs-string, -.hljs-value, -.hljs-regexp { - color: $color-grapefruit; -} - -.hljs-link_url, -.hljs-tag .hljs-value, -.hljs-string, -.hljs-bullet, -.hljs-subst, -.hljs-title, -.hljs-emphasis, -.haskell .hljs-type, -.hljs-preprocessor, -.hljs-pragma, -.ruby .hljs-class .hljs-parent, -.hljs-built_in, -.sql .hljs-aggregate, -.django .hljs-template_tag, -.django .hljs-variable, -.smalltalk .hljs-class, -.hljs-javadoc, -.django .hljs-filter .hljs-argument, -.smalltalk .hljs-localvars, -.smalltalk .hljs-array, -.hljs-attr_selector, -.hljs-pseudo, -.hljs-addition, -.hljs-stream, -.hljs-envvar, -.apache .hljs-tag, -.apache .hljs-cbracket, -.tex .hljs-command, -.hljs-prompt, -.hljs-number, -.hljs-hexcolor { - color: $color-yellow; -} - -.hljs-comment, -.java .hljs-annotation, -.smartquote, -.hljs-blockquote, -.hljs-horizontal_rule, -.python .hljs-decorator, -.hljs-template_comment, -.hljs-pi, -.hljs-doctype, -.hljs-deletion, -.hljs-shebang, -.apache .hljs-sqbracket, -.tex .hljs-formula { - color: lighten($color-black, 20%); -} - -.hljs-keyword, -.hljs-literal, -.css .hljs-id, -.hljs-phpdoc, -.hljs-title, -.hljs-header, -.haskell .hljs-type, -.vbscript .hljs-built_in, -.sql .hljs-aggregate, -.rsl .hljs-built_in, -.smalltalk .hljs-class, -.diff .hljs-header, -.hljs-chunk, -.hljs-winutils, -.bash .hljs-variable, -.apache .hljs-tag, -.tex .hljs-special, -.hljs-request, -.hljs-status { - font-weight: bold; -} - -.coffeescript .javascript, -.javascript .xml, -.tex .hljs-formula, -.xml .javascript, -.xml .vbscript, -.xml .css, -.xml .hljs-cdata { - opacity: 0.5; -} diff --git a/source/styles/site/_landing.scss b/source/styles/site/_landing.scss deleted file mode 100644 index ccf0ff6d7..000000000 --- a/source/styles/site/_landing.scss +++ /dev/null @@ -1,80 +0,0 @@ -.landing-page-header { - background-color: $color-yellow; - text-align: center; - - > .introduction-title { - text-transform: uppercase; - font-size: rem-calc(nth($modular-scale, 8)); - margin: 0; - display: inline-block; - width: 100%; - font-weight: 700; - color: white; - line-height: 0.5; - margin-top: 2rem; - - @include text-shadow(1px 1px mix(black, $color-yellow, 15%), 2px 2px mix(black, $color-yellow, 15%), 3px 3px mix(black, $color-yellow, 15%)); - - @media #{$medium-up} { - font-size: rem-calc(nth($modular-scale, 10)); - } - - > small { - font-size: rem-calc(nth($modular-scale, 4)); - display: inline-block; - width: 100%; - @include text-shadow(1px 1px mix(black, $color-yellow, 15%), 2px 2px mix(black, $color-yellow, 15%)); - } - } - - > .limiter { - position: relative; - max-width: 480px; - margin: 0 auto; - - > figure { - @include ct-responsive-svg-container($ratio: (1/1)); - } - } - - > .call-to-action { - text-align: center; - padding-bottom: $column-gutter; - padding-left: $column-gutter / 2; - padding-right: $column-gutter / 2; - - > .button { - color: white; - color: rgba(255, 255, 255, 0.9); - font-weight: 300 !important; - - &:before { - padding-right: 0.5em; - } - - &.download { - background-color: $color-red; - &:hover, - &:focus { background-color: darken($color-red, 10%); color: rgba(255, 255, 255, 1);} - } - - &.contribute { - background-color: $color-grapefruit; - &:hover, - &:focus { background-color: darken($color-grapefruit, 10%); color: rgba(255, 255, 255, 1);} - } - - @media #{$small-only} { - width: 100%; - font-size: 1em; - font-weight: 700 !important; - } - - @media #{$medium-up} { - &.download { - margin-right: $column-gutter / 2; - } - } - } - } -} \ No newline at end of file diff --git a/source/styles/site/_live-example.scss b/source/styles/site/_live-example.scss deleted file mode 100644 index bb3eae43a..000000000 --- a/source/styles/site/_live-example.scss +++ /dev/null @@ -1,57 +0,0 @@ -.live-example { - @include grid-row(nest); - - margin-bottom: rem-calc(nth($modular-scale, 8)); - - &.edit-mode { - .chart { - @media #{$large-up} { - @include grid-column(12); - } - } - - .live-code { - @media #{$large-up} { - @include grid-column(12); - } - - .introduction { - display: none; - } - - .editor-area { - display: block; - } - } - } - - .live-example-header { - @include grid-column(12); - } - - .chart { - @include grid-column(12); - - @media #{$large-up} { - @include grid-column(8); - } - } - - .live-code { - @include grid-column(12); - - .editor-area { - display: none; - } - - @media #{$large-up} { - @include grid-column(4); - } - } - - .ct-negative-labels { - .ct-label { - fill: rgba(255, 255, 255, 0.8); - } - } -} \ No newline at end of file diff --git a/source/styles/site/_modules.scss b/source/styles/site/_modules.scss deleted file mode 100644 index 28a0babbc..000000000 --- a/source/styles/site/_modules.scss +++ /dev/null @@ -1,2 +0,0 @@ -@import "http://github.com/modules/font"; -@import "http://github.com/modules/icon"; \ No newline at end of file diff --git a/source/styles/site/main.scss b/source/styles/site/main.scss deleted file mode 100644 index eddcbb712..000000000 --- a/source/styles/site/main.scss +++ /dev/null @@ -1,326 +0,0 @@ -@import "http://github.com/settings/chartist-docs"; -@import "http://github.com/settings/foundation"; -@import "http://github.com/settings/font-awesome-variables"; - -@import "http://github.com/modules"; - -@import "http://github.com/settings/chartist-settings"; -@import "http://github.com/chartist"; - -@import "http://github.com/compass-mixins/lib/compass/css3"; -@import "http://github.com/foundation/scss/normalize"; -@import "http://github.com/foundation/scss/foundation"; -@import "http://github.com/base"; -@import "http://github.com/landing"; -@import "http://github.com/highlight"; -@import "http://github.com/code-mirror-theme"; -@import "http://github.com/api-doc"; -@import "http://github.com/live-example"; -@import "http://github.com/example-charts"; - -.button { - text-transform: uppercase; - box-shadow: 3px 3px 0 rgba(0, 0, 0, 0.1); -} - -.invisible { - display: block !important; - max-height: 0; - overflow: hidden; - visibility: hidden; -} - -.text-clipping { - white-space: nowrap; - text-overflow: ellipsis; - overflow: hidden; -} - -.hint { - position: relative; - margin-top: rem-calc(nth($modular-scale, 5)); - margin-bottom: rem-calc(nth($modular-scale, 5)); - padding: rem-calc(nth($modular-scale, 5)); - background: $color-gray; - color: lighten($color-white, 10%); - - > .title { - font-size: rem-calc(nth($modular-scale, 4)); - text-transform: uppercase; - font-weight: 600; - margin-bottom: 0.5rem; - color: lighten($color-black, 20%); - } - - a { - color: $color-yellow; - &:hover { - color: lighten($color-yellow, 10%); - } - } - - &[class*="hint-"] { - padding-left: 5.2rem; - - &.hint-cross-browser { - @include icon($fa-var-arrows-alt, 3rem); - } - - &:before { - position: absolute; - left: rem-calc(nth($modular-scale, 5)); - top: rem-calc(nth($modular-scale, 5)); - font-size: 3rem; - color: lighten($color-black, 5%); - } - } -} - -.tooltip { - position: absolute; - display: inline-block; - min-width: 5em; - padding: 0.5em; - background: $color-yellow; - color: $color-black; - font-weight: 700; - text-align: center; - pointer-events: none; - - &:after { - content: ""; - position: absolute; - top: 100%; - left: 50%; - width: 0; - height: 0; - margin-left: -15px; - border: 15px solid transparent; - border-top-color: $color-yellow; - } -} - -code { - font-family: "Source Code Pro", "Courier New", monospace !important; - word-wrap: break-word; -} - -.sticky.contain-to-grid { - box-shadow: 0 3px 0 rgba(0, 0, 0, 0.3); - - &.fixed, .page-content & { - .top-bar .name h1 a:before { - content: ""; - display: inline-block; - width: 34px; - height: 34px; - margin-top: -4px; - margin-right: 10px; - vertical-align: middle; - border-radius: 50%; - border: 2px solid #F4C63D; - background-size: 32px 32px; - background: #F4C63D url("http://github.com/images/chartist-icon.svg") no-repeat center; - } - } -} - -.ct-chart { - margin-bottom: 1rem; -} - -.ct-chart-pie { - .ct-label { - font-size: 1em; - - @media #{$small-only} { - fill: rgba(255, 255, 255, 0.8); - } - } -} - -.main { - @include grid-row(); - - @media #{$medium-up} { - margin-top: rem-calc(nth($modular-scale, 8)); - } - - > header { - @include grid-column(12); - margin-top: rem-calc(nth($modular-scale, 5)); - - .page-content & { - margin-bottom: rem-calc(nth($modular-scale, 8)); - } - } - - > .side-navigation { - display: none; - - @media #{$medium-up} { - display: block; - @include grid-column(4); - - > nav { - max-width: 250px; - - > .side-nav { - background-color: mix(black, $color-white, 5%); - box-shadow: 3px 3px 0 rgba(0, 0, 0, 0.1); - - > .heading { - font-size: rem-calc(nth($modular-scale, 4)); - text-transform: uppercase; - font-weight: 600; - margin-top: rem-calc(nth($modular-scale, 7)); - margin-bottom: rem-calc(nth($modular-scale, 4)); - color: $color-black; - - &:first-child { - margin-top: 0; - } - } - - > li:not(.heading) > a { - - &:before { - content: "\2013\00A0"; - } - } - } - } - } - } - - > .content { - @include grid-column(12); - - @media #{$medium-up} { - @include grid-column(8); - } - - > .documentation-section { - @include grid-row(nest); - - margin-top: rem-calc(nth($modular-scale, 4)); - margin-bottom: rem-calc(nth($modular-scale, 6)); - - &:first-child { - margin-top: 0; - } - - @media #{$medium-up} { - margin-top: rem-calc(nth($modular-scale, 6)); - margin-bottom: rem-calc(nth($modular-scale, 8)); - } - - > header { - @include grid-column(12); - } - - > .content { - @include grid-column(12); - - @media #{$medium-up} { - @include grid-column(8); - } - - @media #{$large-up} { - @include grid-column(9); - } - - .sub-section { - margin-bottom: 3rem; - } - - > .ct-chart { - &.dark { - background-color: $color-gray; - } - } - } - - > .side-notes { - @include grid-column(12); - - @media #{$medium-up} { - @include grid-column(4); - } - - @media #{$large-up} { - @include grid-column(3); - } - } - - &.full { - > .content { - @media #{$medium-up} { - @include grid-column(12); - } - } - - > .side-notes { - @media #{$medium-up} { - @include grid-column(12); - } - } - } - } - - > ul.example-gallery { - @include block-grid(1); - - @media #{$medium-up} { - @include block-grid(2); - } - } - } - - .full & { - > .side-navigation { - @include grid-column(12); - } - - > .content { - @include grid-column(12); - } - } -} - -@include keyframes(dashoffset) { - 0% { - stroke-dashoffset: 0px; - } - - 100% { - stroke-dashoffset: -20px; - } -} - -@include keyframes(bouncing-stroke) { - 0% { - stroke-width: 5px; - } - - 50% { - stroke-width: 10px; - } - - 100% { - stroke-width: 5px; - } -} - -@include keyframes(exploding-stroke) { - 0% { - stroke-width: 2px; - opacity: 1; - } - - 100% { - stroke-width: 20px; - opacity: 0; - } -} - diff --git a/source/styles/site/modules/_font.scss b/source/styles/site/modules/_font.scss deleted file mode 100644 index 05507f36b..000000000 --- a/source/styles/site/modules/_font.scss +++ /dev/null @@ -1,14 +0,0 @@ -$font-path: "/fonts" !default; - -@mixin embed-font($font-name, $font-file, $font-path: $font-path) { - @font-face { - font-family: $font-name; - src: url('#{$font-path}/#{$font-file}.eot'); - src: url('#{$font-path}/#{$font-file}.eot?#iefix') format('embedded-opentype'), - url('#{$font-path}/#{$font-file}.woff') format('woff'), - url('#{$font-path}/#{$font-file}.ttf') format('truetype'), - url('#{$font-path}/#{$font-file}.svg') format('svg'); - font-weight: normal; - font-style: normal; - } -} \ No newline at end of file diff --git a/source/styles/site/modules/_icon.scss b/source/styles/site/modules/_icon.scss deleted file mode 100644 index 3d53aa628..000000000 --- a/source/styles/site/modules/_icon.scss +++ /dev/null @@ -1,32 +0,0 @@ -$icon-font-name: "FontAwesome" !default; -$icon-location: before !default; -$icon-vertical-align: baseline !default; - -$icon-attr-name: data-icon !default; -$icon-include-classes: true !default; - -@mixin icon($icon: "", $icon-size: 1em, $icon-location: $icon-location, $icon-font-name: $icon-font-name, $icon-vertical-align: $icon-vertical-align) { - &:#{$icon-location} { - content: $icon; - display: inline-block; - vertical-align: $icon-vertical-align; - font-family: $icon-font-name; - font-style: normal; - font-weight: normal; - font-size: $icon-size; - line-height: 1; - -webkit-font-smoothing: antialiased; - -moz-osx-font-smoothing: grayscale; - - // In usage with google font loader we will hide and unhide based on status class on html element - .wf-loading & { - visibility: hidden; - } - } -} - -@if ($icon-include-classes) { - [#{$icon-attr-name}] { - @include icon(attr(#{$icon-attr-name})); - } -} \ No newline at end of file diff --git a/source/styles/site/settings/_chartist-docs.scss b/source/styles/site/settings/_chartist-docs.scss deleted file mode 100644 index 05a2fdb0f..000000000 --- a/source/styles/site/settings/_chartist-docs.scss +++ /dev/null @@ -1,8 +0,0 @@ -$color-white: #EADBC4; -$color-grapefruit: #F05B4F; -$color-red: #D70206; -$color-yellow: #F4C63D; -$color-gray: #453D3F; -$color-black: $color-gray; - -$font-body: "Oxygen", Helvetica, Arial, sans-serif; \ No newline at end of file diff --git a/source/styles/site/settings/_font-awesome-variables.scss b/source/styles/site/settings/_font-awesome-variables.scss deleted file mode 100644 index 719d0c2c4..000000000 --- a/source/styles/site/settings/_font-awesome-variables.scss +++ /dev/null @@ -1,369 +0,0 @@ -$fa-var-glass: "\f000"; -$fa-var-music: "\f001"; -$fa-var-search: "\f002"; -$fa-var-envelope-o: "\f003"; -$fa-var-heart: "\f004"; -$fa-var-star: "\f005"; -$fa-var-star-o: "\f006"; -$fa-var-user: "\f007"; -$fa-var-film: "\f008"; -$fa-var-th-large: "\f009"; -$fa-var-th: "\f00a"; -$fa-var-th-list: "\f00b"; -$fa-var-check: "\f00c"; -$fa-var-times: "\f00d"; -$fa-var-search-plus: "\f00e"; -$fa-var-search-minus: "\f010"; -$fa-var-power-off: "\f011"; -$fa-var-signal: "\f012"; -$fa-var-cog: "\f013"; -$fa-var-trash-o: "\f014"; -$fa-var-home: "\f015"; -$fa-var-file-o: "\f016"; -$fa-var-clock-o: "\f017"; -$fa-var-road: "\f018"; -$fa-var-download: "\f019"; -$fa-var-arrow-circle-o-down: "\f01a"; -$fa-var-arrow-circle-o-up: "\f01b"; -$fa-var-inbox: "\f01c"; -$fa-var-play-circle-o: "\f01d"; -$fa-var-repeat: "\f01e"; -$fa-var-refresh: "\f021"; -$fa-var-list-alt: "\f022"; -$fa-var-lock: "\f023"; -$fa-var-flag: "\f024"; -$fa-var-headphones: "\f025"; -$fa-var-volume-off: "\f026"; -$fa-var-volume-down: "\f027"; -$fa-var-volume-up: "\f028"; -$fa-var-qrcode: "\f029"; -$fa-var-barcode: "\f02a"; -$fa-var-tag: "\f02b"; -$fa-var-tags: "\f02c"; -$fa-var-book: "\f02d"; -$fa-var-bookmark: "\f02e"; -$fa-var-print: "\f02f"; -$fa-var-camera: "\f030"; -$fa-var-font: "\f031"; -$fa-var-bold: "\f032"; -$fa-var-italic: "\f033"; -$fa-var-text-height: "\f034"; -$fa-var-text-width: "\f035"; -$fa-var-align-left: "\f036"; -$fa-var-align-center: "\f037"; -$fa-var-align-right: "\f038"; -$fa-var-align-justify: "\f039"; -$fa-var-list: "\f03a"; -$fa-var-outdent: "\f03b"; -$fa-var-indent: "\f03c"; -$fa-var-video-camera: "\f03d"; -$fa-var-picture-o: "\f03e"; -$fa-var-pencil: "\f040"; -$fa-var-map-marker: "\f041"; -$fa-var-adjust: "\f042"; -$fa-var-tint: "\f043"; -$fa-var-pencil-square-o: "\f044"; -$fa-var-share-square-o: "\f045"; -$fa-var-check-square-o: "\f046"; -$fa-var-arrows: "\f047"; -$fa-var-step-backward: "\f048"; -$fa-var-fast-backward: "\f049"; -$fa-var-backward: "\f04a"; -$fa-var-play: "\f04b"; -$fa-var-pause: "\f04c"; -$fa-var-stop: "\f04d"; -$fa-var-forward: "\f04e"; -$fa-var-fast-forward: "\f050"; -$fa-var-step-forward: "\f051"; -$fa-var-eject: "\f052"; -$fa-var-chevron-left: "\f053"; -$fa-var-chevron-right: "\f054"; -$fa-var-plus-circle: "\f055"; -$fa-var-minus-circle: "\f056"; -$fa-var-times-circle: "\f057"; -$fa-var-check-circle: "\f058"; -$fa-var-question-circle: "\f059"; -$fa-var-info-circle: "\f05a"; -$fa-var-crosshairs: "\f05b"; -$fa-var-times-circle-o: "\f05c"; -$fa-var-check-circle-o: "\f05d"; -$fa-var-ban: "\f05e"; -$fa-var-arrow-left: "\f060"; -$fa-var-arrow-right: "\f061"; -$fa-var-arrow-up: "\f062"; -$fa-var-arrow-down: "\f063"; -$fa-var-share: "\f064"; -$fa-var-expand: "\f065"; -$fa-var-compress: "\f066"; -$fa-var-plus: "\f067"; -$fa-var-minus: "\f068"; -$fa-var-asterisk: "\f069"; -$fa-var-exclamation-circle: "\f06a"; -$fa-var-gift: "\f06b"; -$fa-var-leaf: "\f06c"; -$fa-var-fire: "\f06d"; -$fa-var-eye: "\f06e"; -$fa-var-eye-slash: "\f070"; -$fa-var-exclamation-triangle: "\f071"; -$fa-var-plane: "\f072"; -$fa-var-calendar: "\f073"; -$fa-var-random: "\f074"; -$fa-var-comment: "\f075"; -$fa-var-magnet: "\f076"; -$fa-var-chevron-up: "\f077"; -$fa-var-chevron-down: "\f078"; -$fa-var-retweet: "\f079"; -$fa-var-shopping-cart: "\f07a"; -$fa-var-folder: "\f07b"; -$fa-var-folder-open: "\f07c"; -$fa-var-arrows-v: "\f07d"; -$fa-var-arrows-h: "\f07e"; -$fa-var-bar-chart-o: "\f080"; -$fa-var-twitter-square: "\f081"; -$fa-var-facebook-square: "\f082"; -$fa-var-camera-retro: "\f083"; -$fa-var-key: "\f084"; -$fa-var-cogs: "\f085"; -$fa-var-comments: "\f086"; -$fa-var-thumbs-o-up: "\f087"; -$fa-var-thumbs-o-down: "\f088"; -$fa-var-star-half: "\f089"; -$fa-var-heart-o: "\f08a"; -$fa-var-sign-out: "\f08b"; -$fa-var-linkedin-square: "\f08c"; -$fa-var-thumb-tack: "\f08d"; -$fa-var-external-link: "\f08e"; -$fa-var-sign-in: "\f090"; -$fa-var-trophy: "\f091"; -$fa-var-github-square: "\f092"; -$fa-var-upload: "\f093"; -$fa-var-lemon-o: "\f094"; -$fa-var-phone: "\f095"; -$fa-var-square-o: "\f096"; -$fa-var-bookmark-o: "\f097"; -$fa-var-phone-square: "\f098"; -$fa-var-twitter: "\f099"; -$fa-var-facebook: "\f09a"; -$fa-var-github: "\f09b"; -$fa-var-unlock: "\f09c"; -$fa-var-credit-card: "\f09d"; -$fa-var-rss: "\f09e"; -$fa-var-hdd-o: "\f0a0"; -$fa-var-bullhorn: "\f0a1"; -$fa-var-bell: "\f0f3"; -$fa-var-certificate: "\f0a3"; -$fa-var-hand-o-right: "\f0a4"; -$fa-var-hand-o-left: "\f0a5"; -$fa-var-hand-o-up: "\f0a6"; -$fa-var-hand-o-down: "\f0a7"; -$fa-var-arrow-circle-left: "\f0a8"; -$fa-var-arrow-circle-right: "\f0a9"; -$fa-var-arrow-circle-up: "\f0aa"; -$fa-var-arrow-circle-down: "\f0ab"; -$fa-var-globe: "\f0ac"; -$fa-var-wrench: "\f0ad"; -$fa-var-tasks: "\f0ae"; -$fa-var-filter: "\f0b0"; -$fa-var-briefcase: "\f0b1"; -$fa-var-arrows-alt: "\f0b2"; -$fa-var-users: "\f0c0"; -$fa-var-link: "\f0c1"; -$fa-var-cloud: "\f0c2"; -$fa-var-flask: "\f0c3"; -$fa-var-scissors: "\f0c4"; -$fa-var-files-o: "\f0c5"; -$fa-var-paperclip: "\f0c6"; -$fa-var-floppy-o: "\f0c7"; -$fa-var-square: "\f0c8"; -$fa-var-bars: "\f0c9"; -$fa-var-list-ul: "\f0ca"; -$fa-var-list-ol: "\f0cb"; -$fa-var-strikethrough: "\f0cc"; -$fa-var-underline: "\f0cd"; -$fa-var-table: "\f0ce"; -$fa-var-magic: "\f0d0"; -$fa-var-truck: "\f0d1"; -$fa-var-pinterest: "\f0d2"; -$fa-var-pinterest-square: "\f0d3"; -$fa-var-google-plus-square: "\f0d4"; -$fa-var-google-plus: "\f0d5"; -$fa-var-money: "\f0d6"; -$fa-var-caret-down: "\f0d7"; -$fa-var-caret-up: "\f0d8"; -$fa-var-caret-left: "\f0d9"; -$fa-var-caret-right: "\f0da"; -$fa-var-columns: "\f0db"; -$fa-var-sort: "\f0dc"; -$fa-var-sort-asc: "\f0dd"; -$fa-var-sort-desc: "\f0de"; -$fa-var-envelope: "\f0e0"; -$fa-var-linkedin: "\f0e1"; -$fa-var-undo: "\f0e2"; -$fa-var-gavel: "\f0e3"; -$fa-var-tachometer: "\f0e4"; -$fa-var-comment-o: "\f0e5"; -$fa-var-comments-o: "\f0e6"; -$fa-var-bolt: "\f0e7"; -$fa-var-sitemap: "\f0e8"; -$fa-var-umbrella: "\f0e9"; -$fa-var-clipboard: "\f0ea"; -$fa-var-lightbulb-o: "\f0eb"; -$fa-var-exchange: "\f0ec"; -$fa-var-cloud-download: "\f0ed"; -$fa-var-cloud-upload: "\f0ee"; -$fa-var-user-md: "\f0f0"; -$fa-var-stethoscope: "\f0f1"; -$fa-var-suitcase: "\f0f2"; -$fa-var-bell-o: "\f0a2"; -$fa-var-coffee: "\f0f4"; -$fa-var-cutlery: "\f0f5"; -$fa-var-file-text-o: "\f0f6"; -$fa-var-building-o: "\f0f7"; -$fa-var-hospital-o: "\f0f8"; -$fa-var-ambulance: "\f0f9"; -$fa-var-medkit: "\f0fa"; -$fa-var-fighter-jet: "\f0fb"; -$fa-var-beer: "\f0fc"; -$fa-var-h-square: "\f0fd"; -$fa-var-plus-square: "\f0fe"; -$fa-var-angle-double-left: "\f100"; -$fa-var-angle-double-right: "\f101"; -$fa-var-angle-double-up: "\f102"; -$fa-var-angle-double-down: "\f103"; -$fa-var-angle-left: "\f104"; -$fa-var-angle-right: "\f105"; -$fa-var-angle-up: "\f106"; -$fa-var-angle-down: "\f107"; -$fa-var-desktop: "\f108"; -$fa-var-laptop: "\f109"; -$fa-var-tablet: "\f10a"; -$fa-var-mobile: "\f10b"; -$fa-var-circle-o: "\f10c"; -$fa-var-quote-left: "\f10d"; -$fa-var-quote-right: "\f10e"; -$fa-var-spinner: "\f110"; -$fa-var-circle: "\f111"; -$fa-var-reply: "\f112"; -$fa-var-github-alt: "\f113"; -$fa-var-folder-o: "\f114"; -$fa-var-folder-open-o: "\f115"; -$fa-var-smile-o: "\f118"; -$fa-var-frown-o: "\f119"; -$fa-var-meh-o: "\f11a"; -$fa-var-gamepad: "\f11b"; -$fa-var-keyboard-o: "\f11c"; -$fa-var-flag-o: "\f11d"; -$fa-var-flag-checkered: "\f11e"; -$fa-var-terminal: "\f120"; -$fa-var-code: "\f121"; -$fa-var-reply-all: "\f122"; -$fa-var-mail-reply-all: "\f122"; -$fa-var-star-half-o: "\f123"; -$fa-var-location-arrow: "\f124"; -$fa-var-crop: "\f125"; -$fa-var-code-fork: "\f126"; -$fa-var-chain-broken: "\f127"; -$fa-var-question: "\f128"; -$fa-var-info: "\f129"; -$fa-var-exclamation: "\f12a"; -$fa-var-superscript: "\f12b"; -$fa-var-subscript: "\f12c"; -$fa-var-eraser: "\f12d"; -$fa-var-puzzle-piece: "\f12e"; -$fa-var-microphone: "\f130"; -$fa-var-microphone-slash: "\f131"; -$fa-var-shield: "\f132"; -$fa-var-calendar-o: "\f133"; -$fa-var-fire-extinguisher: "\f134"; -$fa-var-rocket: "\f135"; -$fa-var-maxcdn: "\f136"; -$fa-var-chevron-circle-left: "\f137"; -$fa-var-chevron-circle-right: "\f138"; -$fa-var-chevron-circle-up: "\f139"; -$fa-var-chevron-circle-down: "\f13a"; -$fa-var-html5: "\f13b"; -$fa-var-css3: "\f13c"; -$fa-var-anchor: "\f13d"; -$fa-var-unlock-alt: "\f13e"; -$fa-var-bullseye: "\f140"; -$fa-var-ellipsis-h: "\f141"; -$fa-var-ellipsis-v: "\f142"; -$fa-var-rss-square: "\f143"; -$fa-var-play-circle: "\f144"; -$fa-var-ticket: "\f145"; -$fa-var-minus-square: "\f146"; -$fa-var-minus-square-o: "\f147"; -$fa-var-level-up: "\f148"; -$fa-var-level-down: "\f149"; -$fa-var-check-square: "\f14a"; -$fa-var-pencil-square: "\f14b"; -$fa-var-external-link-square: "\f14c"; -$fa-var-share-square: "\f14d"; -$fa-var-compass: "\f14e"; -$fa-var-caret-square-o-down: "\f150"; -$fa-var-caret-square-o-up: "\f151"; -$fa-var-caret-square-o-right: "\f152"; -$fa-var-eur: "\f153"; -$fa-var-gbp: "\f154"; -$fa-var-usd: "\f155"; -$fa-var-inr: "\f156"; -$fa-var-jpy: "\f157"; -$fa-var-rub: "\f158"; -$fa-var-krw: "\f159"; -$fa-var-btc: "\f15a"; -$fa-var-file: "\f15b"; -$fa-var-file-text: "\f15c"; -$fa-var-sort-alpha-asc: "\f15d"; -$fa-var-sort-alpha-desc: "\f15e"; -$fa-var-sort-amount-asc: "\f160"; -$fa-var-sort-amount-desc: "\f161"; -$fa-var-sort-numeric-asc: "\f162"; -$fa-var-sort-numeric-desc: "\f163"; -$fa-var-thumbs-up: "\f164"; -$fa-var-thumbs-down: "\f165"; -$fa-var-youtube-square: "\f166"; -$fa-var-youtube: "\f167"; -$fa-var-xing: "\f168"; -$fa-var-xing-square: "\f169"; -$fa-var-youtube-play: "\f16a"; -$fa-var-dropbox: "\f16b"; -$fa-var-stack-overflow: "\f16c"; -$fa-var-instagram: "\f16d"; -$fa-var-flickr: "\f16e"; -$fa-var-adn: "\f170"; -$fa-var-bitbucket: "\f171"; -$fa-var-bitbucket-square: "\f172"; -$fa-var-tumblr: "\f173"; -$fa-var-tumblr-square: "\f174"; -$fa-var-long-arrow-down: "\f175"; -$fa-var-long-arrow-up: "\f176"; -$fa-var-long-arrow-left: "\f177"; -$fa-var-long-arrow-right: "\f178"; -$fa-var-apple: "\f179"; -$fa-var-windows: "\f17a"; -$fa-var-android: "\f17b"; -$fa-var-linux: "\f17c"; -$fa-var-dribbble: "\f17d"; -$fa-var-skype: "\f17e"; -$fa-var-foursquare: "\f180"; -$fa-var-trello: "\f181"; -$fa-var-female: "\f182"; -$fa-var-male: "\f183"; -$fa-var-gittip: "\f184"; -$fa-var-sun-o: "\f185"; -$fa-var-moon-o: "\f186"; -$fa-var-archive: "\f187"; -$fa-var-bug: "\f188"; -$fa-var-vk: "\f189"; -$fa-var-weibo: "\f18a"; -$fa-var-renren: "\f18b"; -$fa-var-pagelines: "\f18c"; -$fa-var-stack-exchange: "\f18d"; -$fa-var-arrow-circle-o-right: "\f18e"; -$fa-var-arrow-circle-o-left: "\f190"; -$fa-var-caret-square-o-left: "\f191"; -$fa-var-dot-circle-o: "\f192"; -$fa-var-wheelchair: "\f193"; -$fa-var-vimeo-square: "\f194"; -$fa-var-try: "\f195"; -$fa-var-plus-square-o: "\f196"; \ No newline at end of file diff --git a/source/styles/site/settings/_foundation.scss b/source/styles/site/settings/_foundation.scss deleted file mode 100644 index 3147ae130..000000000 --- a/source/styles/site/settings/_foundation.scss +++ /dev/null @@ -1,1194 +0,0 @@ -// -// FOUNDATION SETTINGS -// - -// This is the default html and body font-size for the base rem value. -// $rem-base: 16px; - -// Allows the use of rem-calc() or lower-bound() in your settings -@import "http://github.com/foundation/scss/foundation/functions"; - -// $experimental: true; - -// The default font-size is set to 100% of the browser style sheet (usually 16px) -// for compatibility with browser-based text zoom or user-set defaults. - -// Since the typical default browser font-size is 16px, that makes the calculation for grid size. -// If you want your base font-size to be different and not have it affect the grid breakpoints, -// set $rem-base to $base-font-size and make sure $base-font-size is a px value. -// $base-font-size: 100%; - -// The $base-line-height is 100% while $base-font-size is 150% -$base-line-height: 150%; - -// We use this to control whether or not CSS classes come through in the gem files. -$include-html-classes: false; -// $include-print-styles: true; -$include-html-global-classes: true; - -// Grid - -// $include-html-grid-classes: $include-html-classes; -// $include-xl-html-grid-classes: false; - -$row-width: rem-calc(1200); -$column-gutter: rem-calc(50); -$total-columns: 12; - -// We use these to control various global styles -$body-bg: $color-white; -$body-font-color: darken($color-white, 60%); -$body-font-family: $font-body; -// $body-font-weight: normal; -// $body-font-style: normal; - -// We use this to control font-smoothing -// $font-smoothing: antialiased; - -// We use these to control text direction settings -// $text-direction: ltr; -// $opposite-direction: right; -// $default-float: left; - -// We use these as default colors throughout -$primary-color: $color-yellow; -$secondary-color: $color-gray; -$alert-color: $color-red; -$success-color: $color-yellow; -$warning-color: $color-grapefruit; -$info-color: $color-gray; - -// We use these to make sure border radius matches unless we want it different. -// $global-radius: 3px; -// $global-rounded: 1000px; - -// We use these to control inset shadow shiny edges and depressions. -// $shiny-edge-size: 0 1px 0; -// $shiny-edge-color: rgba(#fff, .5); -// $shiny-edge-active-color: rgba(#000, .2); - -// Media Query Ranges -$small-range: (0em, 40em); -$medium-range: (40.063em, 64em); -$large-range: (64.063em, 90em); -$xlarge-range: (90.063em, 120em); -$xxlarge-range: (120.063em); - -$screen: "only screen"; - -$landscape: "#{$screen} and (orientation: landscape)"; -$portrait: "#{$screen} and (orientation: portrait)"; - -$small-up: $screen; -$small-only: "#{$screen} and (max-width: #{upper-bound($small-range)})"; - -$medium-up: "#{$screen} and (min-width:#{lower-bound($medium-range)})"; -$medium-only: "#{$screen} and (min-width:#{lower-bound($medium-range)}) and (max-width:#{upper-bound($medium-range)})"; - -$large-up: "#{$screen} and (min-width:#{lower-bound($large-range)})"; -$large-only: "#{$screen} and (min-width:#{lower-bound($large-range)}) and (max-width:#{upper-bound($large-range)})"; - -$xlarge-up: "#{$screen} and (min-width:#{lower-bound($xlarge-range)})"; -$xlarge-only: "#{$screen} and (min-width:#{lower-bound($xlarge-range)}) and (max-width:#{upper-bound($xlarge-range)})"; - -$xxlarge-up: "#{$screen} and (min-width:#{lower-bound($xxlarge-range)})"; -$xxlarge-only: "#{$screen} and (min-width:#{lower-bound($xxlarge-range)}) and (max-width:#{upper-bound($xxlarge-range)})"; - -// Legacy -// $small: $medium-up; -// $medium: $medium-up; -// $large: $large-up; - -//We use this as cursors values for enabling the option of having custom cursors in the whole site's stylesheet -// $cursor-crosshair-value: crosshair; -// $cursor-default-value: default; -// $cursor-pointer-value: pointer; -// $cursor-help-value: help; -// $cursor-text-value: text; - -// -// TYPOGRAPHY -// - -// $include-html-type-classes: $include-html-classes; - -// We use these to control header font styles -// $header-font-family: $body-font-family; -// $header-font-weight: 300; -// $header-font-style: normal; -// $header-font-color: #222; -// $header-line-height: 1.4; -// $header-top-margin: .2rem; -// $header-bottom-margin: .5rem; -// $header-text-rendering: optimizeLegibility; - -// We use these to control header font sizes -// $h1-font-size: rem-calc(44); -// $h2-font-size: rem-calc(37); -// $h3-font-size: rem-calc(27); -// $h4-font-size: rem-calc(23); -// $h5-font-size: rem-calc(18); -// $h6-font-size: 1rem; - -// These control how subheaders are styled. -// $subheader-line-height: 1.4; -// $subheader-font-color: scale-color($header-font-color, $lightness: 35%); -// $subheader-font-weight: 300; -// $subheader-top-margin: .2rem; -// $subheader-bottom-margin: .5rem; - -// A general styling -// $small-font-size: 60%; -// $small-font-color: scale-color($header-font-color, $lightness: 35%); - -// We use these to style paragraphs -// $paragraph-font-family: inherit; -// $paragraph-font-weight: normal; -// $paragraph-font-size: 1rem; -// $paragraph-line-height: 1.6; -// $paragraph-margin-bottom: rem-calc(20); -// $paragraph-aside-font-size: rem-calc(14); -// $paragraph-aside-line-height: 1.35; -// $paragraph-aside-font-style: italic; -// $paragraph-text-rendering: optimizeLegibility; - -// We use these to style tags -// $code-color: scale-color($alert-color, $lightness: -27%); -// $code-font-family: Consolas, 'Liberation Mono', Courier, monospace; -// $code-font-weight: bold; - -// We use these to style anchors -// $anchor-text-decoration: none; -// $anchor-font-color: $primary-color; -// $anchor-font-color-hover: scale-color($primary-color, $lightness: -14%); - -// We use these to style the
element -// $hr-border-width: 1px; -// $hr-border-style: solid; -// $hr-border-color: #ddd; -// $hr-margin: rem-calc(20); - -// We use these to style lists -// $list-style-position: outside; -// $list-side-margin: 1.1rem; -// $list-ordered-side-margin: 1.4rem; -// $list-side-margin-no-bullet: 0; -// $list-nested-margin: rem-calc(20); -// $definition-list-header-weight: bold; -// $definition-list-header-margin-bottom: .3rem; -// $definition-list-margin-bottom: rem-calc(12); - -// We use these to style blockquotes -// $blockquote-font-color: scale-color($header-font-color, $lightness: 35%); -// $blockquote-padding: rem-calc(9 20 0 19); -// $blockquote-border: 1px solid #ddd; -// $blockquote-cite-font-size: rem-calc(13); -// $blockquote-cite-font-color: scale-color($header-font-color, $lightness: 23%); -// $blockquote-cite-link-color: $blockquote-cite-font-color; - -// Acronym styles -// $acronym-underline: 1px dotted #ddd; - -// We use these to control padding and margin -// $microformat-padding: rem-calc(10 12); -// $microformat-margin: rem-calc(0 0 20 0); - -// We use these to control the border styles -// $microformat-border-width: 1px; -// $microformat-border-style: solid; -// $microformat-border-color: #ddd; - -// We use these to control full name font styles -// $microformat-fullname-font-weight: bold; -// $microformat-fullname-font-size: rem-calc(15); - -// We use this to control the summary font styles -// $microformat-summary-font-weight: bold; - -// We use this to control abbr padding -// $microformat-abbr-padding: rem-calc(0 1); - -// We use this to control abbr font styles -// $microformat-abbr-font-weight: bold; -// $microformat-abbr-font-decoration: none; - -// Accordion - -// $include-html-accordion-classes: $include-html-classes; - -// $accordion-navigation-padding: rem-calc(16); -// $accordion-navigation-bg-color: #efefef ; -// $accordion-navigation-hover-bg-color: scale-color($accordion-navigation-bg-color, $lightness: -5%); -// $accordion-navigation-active-bg-color: scale-color($accordion-navigation-bg-color, $lightness: -3%); -// $accordion-navigation-font-color: #222; -// $accordion-navigation-font-size: rem-calc(16); -// $accordion-navigation-font-family: $body-font-family; - -// $accordion-content-padding: $column-gutter/2; -// $accordion-content-active-bg-color: #fff; - -// Alert Boxes - -// $include-html-alert-classes: $include-html-classes; - -// We use this to control alert padding. -// $alert-padding-top: rem-calc(14); -// $alert-padding-default-float: $alert-padding-top; -// $alert-padding-opposite-direction: $alert-padding-top + rem-calc(10); -// $alert-padding-bottom: $alert-padding-top; - -// We use these to control text style. -// $alert-font-weight: normal; -// $alert-font-size: rem-calc(13); -// $alert-font-color: #fff; -// $alert-font-color-alt: scale-color($secondary-color, $lightness: -66%); - -// We use this for close hover effect. -// $alert-function-factor: -14%; - -// We use these to control border styles. -// $alert-border-style: solid; -// $alert-border-width: 1px; -// $alert-border-color: scale-color($primary-color, $lightness: $alert-function-factor); -// $alert-bottom-margin: rem-calc(20); - -// We use these to style the close buttons -// $alert-close-color: #333; -// $alert-close-top: 50%; -// $alert-close-position: rem-calc(5); -// $alert-close-font-size: rem-calc(22); -// $alert-close-opacity: 0.3; -// $alert-close-opacity-hover: 0.5; -// $alert-close-padding: 9px 6px 4px; - -// We use this to control border radius -// $alert-radius: $global-radius; - -// Block Grid - -// $include-html-grid-classes: $include-html-classes; - -// We use this to control the maximum number of block grid elements per row -// $block-grid-elements: 12; -// $block-grid-default-spacing: rem-calc(20); - -// Enables media queries for block-grid classes. Set to false if writing semantic HTML. -// $block-grid-media-queries: true; - -// Breadcrumbs - -$include-html-nav-classes: $include-html-classes; - -// We use this to set the background color for the breadcrumb container. -// $crumb-bg: scale-color($secondary-color, $lightness: 55%); - -// We use these to set the padding around the breadcrumbs. -// $crumb-padding: rem-calc(9 14 9); -// $crumb-side-padding: rem-calc(12); - -// We use these to control border styles. -// $crumb-function-factor: -10%; -// $crumb-border-size: 1px; -// $crumb-border-style: solid; -// $crumb-border-color: scale-color($crumb-bg, $lightness: $crumb-function-factor); -// $crumb-radius: $global-radius; - -// We use these to set various text styles for breadcrumbs. -// $crumb-font-size: rem-calc(11); -// $crumb-font-color: $primary-color; -// $crumb-font-color-current: #333; -// $crumb-font-color-unavailable: #999; -// $crumb-font-transform: uppercase; -// $crumb-link-decor: underline; - -// We use these to control the slash between breadcrumbs -// $crumb-slash-color: #aaa; -// $crumb-slash: "/"; - -// -// BUTTONS -// - -$include-html-button-classes: true; - -// We use these to build padding for buttons. -// $button-tny: rem-calc(10); -// $button-sml: rem-calc(14); -// $button-med: rem-calc(16); -// $button-lrg: rem-calc(18); - -// We use this to control the display property. -// $button-display: inline-block; -// $button-margin-bottom: rem-calc(20); - -// We use these to control button text styles. -// $button-font-family: $body-font-family; -$button-font-color: $color-black; -// $button-font-color-alt: #333; -// $button-font-tny: rem-calc(11); -// $button-font-sml: rem-calc(13); -// $button-font-med: rem-calc(16); -// $button-font-lrg: rem-calc(20); -// $button-font-weight: normal; -// $button-font-align: center; - -// We use these to control various hover effects. -// $button-function-factor: 5%; - -// We use these to control button border styles. -// $button-border-width: 1px; -// $button-border-style: solid; - -// We use this to set the default radius used throughout the core. -// $button-radius: $global-radius; -// $button-round: $global-rounded; - -// We use this to set default opacity for disabled buttons. -// $button-disabled-opacity: 0.7; - -// Button Groups - -// $include-html-button-classes: $include-html-classes; - -// Sets the margin for the right side by default, and the left margin if right-to-left direction is used -// $button-bar-margin-opposite: rem-calc(10); -// $button-group-border-width: 1px; - -// Clearing - -// $include-html-clearing-classes: $include-html-classes; - -// We use these to set the background colors for parts of Clearing. -// $clearing-bg: #333; -// $clearing-caption-bg: $clearing-bg; -// $clearing-carousel-bg: rgba (51,51,51,0.8); -// $clearing-img-bg: $clearing-bg; - -// We use these to style the close button -// $clearing-close-color: #ccc; -// $clearing-close-size: 30px; - -// We use these to style the arrows -// $clearing-arrow-size: 12px; -// $clearing-arrow-color: $clearing-close-color; - -// We use these to style captions -// $clearing-caption-font-color: #ccc; -// $clearing-caption-font-size: 0.875em; -// $clearing-caption-padding: 10px 30px 20px; - -// We use these to make the image and carousel height and style -// $clearing-active-img-height: 85%; -// $clearing-carousel-height: 120px; -// $clearing-carousel-thumb-width: 120px; -// $clearing-carousel-thumb-active-border: 1px solid rgb(255,255,255); - -// Dropdown - -// $include-html-dropdown-classes: $include-html-classes; - -// We use these to controls height and width styles. -// $f-dropdown-max-width: 200px; -// $f-dropdown-height: auto; -// $f-dropdown-max-height: none; -// $f-dropdown-margin-top: 2px; - -// We use this to control the background color -// $f-dropdown-bg: #fff; - -// We use this to set the border styles for dropdowns. -// $f-dropdown-border-style: solid; -// $f-dropdown-border-width: 1px; -// $f-dropdown-border-color: scale-color(#fff, $lightness: -20%); - -// We use these to style the triangle pip. -// $f-dropdown-triangle-size: 6px; -// $f-dropdown-triangle-color: #fff; -// $f-dropdown-triangle-side-offset: 10px; - -// We use these to control styles for the list elements. -// $f-dropdown-list-style: none; -// $f-dropdown-font-color: #555; -// $f-dropdown-font-size: rem-calc(14); -// $f-dropdown-list-padding: rem-calc(5, 10); -// $f-dropdown-line-height: rem-calc(18); -// $f-dropdown-list-hover-bg: #eeeeee ; -// $dropdown-mobile-default-float: 0; - -// We use this to control the styles for when the dropdown has custom content. -// $f-dropdown-content-padding: rem-calc(20); - -// Dropdown Buttons - -// $include-html-button-classes: $include-html-classes; - -// We use these to set the color of the pip in dropdown buttons -// $dropdown-button-pip-color: #fff; -// $dropdown-button-pip-color-alt: #333; - -// $button-pip-tny: rem-calc(6); -// $button-pip-sml: rem-calc(7); -// $button-pip-med: rem-calc(9); -// $button-pip-lrg: rem-calc(11); - -// We use these to style tiny dropdown buttons -// $dropdown-button-padding-tny: $button-pip-tny * 7; -// $dropdown-button-pip-size-tny: $button-pip-tny; -// $dropdown-button-pip-opposite-tny: $button-pip-tny * 3; -// $dropdown-button-pip-top-tny: -$button-pip-tny / 2 + rem-calc(1); - -// We use these to style small dropdown buttons -// $dropdown-button-padding-sml: $button-pip-sml * 7; -// $dropdown-button-pip-size-sml: $button-pip-sml; -// $dropdown-button-pip-opposite-sml: $button-pip-sml * 3; -// $dropdown-button-pip-top-sml: -$button-pip-sml / 2 + rem-calc(1); - -// We use these to style medium dropdown buttons -// $dropdown-button-padding-med: $button-pip-med * 6 + rem-calc(3); -// $dropdown-button-pip-size-med: $button-pip-med - rem-calc(3); -// $dropdown-button-pip-opposite-med: $button-pip-med * 2.5; -// $dropdown-button-pip-top-med: -$button-pip-med / 2 + rem-calc(2); - -// We use these to style large dropdown buttons -// $dropdown-button-padding-lrg: $button-pip-lrg * 5 + rem-calc(3); -// $dropdown-button-pip-size-lrg: $button-pip-lrg - rem-calc(6); -// $dropdown-button-pip-opposite-lrg: $button-pip-lrg * 2.5; -// $dropdown-button-pip-top-lrg: -$button-pip-lrg / 2 + rem-calc(3); - -// Flex Video - -// $include-html-media-classes: $include-html-classes; - -// We use these to control video container padding and margins -// $flex-video-padding-top: rem-calc(25); -// $flex-video-padding-bottom: 67.5%; -// $flex-video-margin-bottom: rem-calc(16); - -// We use this to control widescreen bottom padding -// $flex-video-widescreen-padding-bottom: 57.25%; - -// Forms - -// $include-html-form-classes: $include-html-classes; - -// We use this to set the base for lots of form spacing and positioning styles -// $form-spacing: rem-calc(16); - -// We use these to style the labels in different ways -// $form-label-pointer: pointer; -// $form-label-font-size: rem-calc(14); -// $form-label-font-weight: normal; -// $form-label-line-height: 1.5; -// $form-label-font-color: scale-color(#000, $lightness: 30%); -// $form-label-bottom-margin: 0; -// $input-font-family: inherit; -// $input-font-color: rgba(0,0,0,0.75); -// $input-font-size: rem-calc(14); -// $input-bg-color: #fff; -// $input-focus-bg-color: scale-color(#fff, $lightness: -2%); -// $input-border-color: scale-color(#fff, $lightness: -20%); -// $input-focus-border-color: scale-color(#fff, $lightness: -40%); -// $input-border-style: solid; -// $input-border-width: 1px; -// $input-border-radius: $global-radius; -// $input-disabled-bg: #ddd; -// $input-box-shadow: inset 0 1px 2px rgba(0,0,0,0.1); -// $input-include-glowing-effect: true; - -// We use these to style the fieldset border and spacing. -// $fieldset-border-style: solid; -// $fieldset-border-width: 1px; -// $fieldset-border-color: #ddd; -// $fieldset-padding: rem-calc(20); -// $fieldset-margin: rem-calc(18 0); - -// We use these to style the legends when you use them -// $legend-bg: #fff; -// $legend-font-weight: bold; -// $legend-padding: rem-calc(0 3); - -// We use these to style the prefix and postfix input elements -// $input-prefix-bg: scale-color(#fff, $lightness: -5%); -// $input-prefix-border-color: scale-color(#fff, $lightness: -20%); -// $input-prefix-border-size: 1px; -// $input-prefix-border-type: solid; -// $input-prefix-overflow: hidden; -// $input-prefix-font-color: #333; -// $input-prefix-font-color-alt: #fff; - -// We use these to style the error states for inputs and labels -// $input-error-message-padding: rem-calc(6 9 9); -// $input-error-message-top: -1px; -// $input-error-message-font-size: rem-calc(12); -// $input-error-message-font-weight: normal; -// $input-error-message-font-style: italic; -// $input-error-message-font-color: #fff; -// $input-error-message-font-color-alt: #333; - -// We use this to style the glowing effect of inputs when focused -// $glowing-effect-fade-time: 0.45s; -// $glowing-effect-color: $input-focus-border-color; - -// Select variables -// $select-bg-color: #fafafa; - -// Inline Lists - -// $include-html-inline-list-classes: $include-html-classes; - -// We use this to control the margins and padding of the inline list. -// $inline-list-top-margin: 0; -// $inline-list-opposite-margin: 0; -// $inline-list-bottom-margin: rem-calc(17); -// $inline-list-default-float-margin: rem-calc(-22); - -// $inline-list-padding: 0; - -// We use this to control the overflow of the inline list. -// $inline-list-overflow: hidden; - -// We use this to control the list items -// $inline-list-display: block; - -// We use this to control any elments within list items -// $inline-list-children-display: block; - -// Joyride - -// $include-html-joyride-classes: $include-html-classes; - -// Controlling default Joyride styles -// $joyride-tip-bg: #333; -// $joyride-tip-default-width: 300px; -// $joyride-tip-padding: rem-calc(18 20 24); -// $joyride-tip-border: solid 1px #555; -// $joyride-tip-radius: 4px; -// $joyride-tip-position-offset: 22px; - -// Here, we're setting the tip dont styles -// $joyride-tip-font-color: #fff; -// $joyride-tip-font-size: rem-calc(14); -// $joyride-tip-header-weight: bold; - -// This changes the nub size -// $joyride-tip-nub-size: 10px; - -// This adjusts the styles for the timer when its enabled -// $joyride-tip-timer-width: 50px; -// $joyride-tip-timer-height: 3px; -// $joyride-tip-timer-color: #666; - -// This changes up the styles for the close button -// $joyride-tip-close-color: #777; -// $joyride-tip-close-size: 24px; -// $joyride-tip-close-weight: normal; - -// When Joyride is filling the screen, we use this style for the bg -// $joyride-screenfill: rgba(0,0,0,0.5); - -// Keystrokes - -// $include-html-type-classes: $include-html-classes; - -// We use these to control text styles. -// $keystroke-font: "Consolas", "Menlo", "Courier", monospace; -// $keystroke-font-size: rem-calc(14); -// $keystroke-font-color: #222; -// $keystroke-font-color-alt: #fff; -// $keystroke-function-factor: -7%; - -// We use this to control keystroke padding. -// $keystroke-padding: rem-calc(2 4 0); - -// We use these to control background and border styles. -// $keystroke-bg: scale-color(#fff, $lightness: $keystroke-function-factor); -// $keystroke-border-style: solid; -// $keystroke-border-width: 1px; -// $keystroke-border-color: scale-color($keystroke-bg, $lightness: $keystroke-function-factor); -// $keystroke-radius: $global-radius; - -// Labels - -// $include-html-label-classes: $include-html-classes; - -// We use these to style the labels -// $label-padding: rem-calc(4 8 6); -// $label-radius: $global-radius; - -// We use these to style the label text -// $label-font-sizing: rem-calc(11); -// $label-font-weight: normal; -// $label-font-color: #333; -// $label-font-color-alt: #fff; -// $label-font-family: $body-font-family; - -// Magellan - -// $include-html-magellan-classes: $include-html-classes; - -// $magellan-bg: #fff; -// $magellan-padding: 10px; - -// Off-canvas - -// $tabbar-bg: #333; -// $tabbar-height: rem-calc(45); -// $tabbar-line-height: $tabbar-height; -// $tabbar-color: #FFF; -// $tabbar-middle-padding: 0 rem-calc(10); - -// Off Canvas Divider Styles -// $tabbar-right-section-border: solid 1px scale-color($tabbar-bg, $lightness: 13%); -// $tabbar-left-section-border: solid 1px scale-color($tabbar-bg, $lightness: -50%); - -// Off Canvas Tab Bar Headers -// $tabbar-header-color: #FFF; -// $tabbar-header-weight: bold; -// $tabbar-header-line-height: $tabbar-height; -// $tabbar-header-margin: 0; - -// Off Canvas Menu Variables -// $off-canvas-width: 250px; -// $off-canvas-bg: #333; - -// Off Canvas Menu List Variables -// $off-canvas-label-padding: 0.3rem rem-calc(15); -// $off-canvas-label-color: #999; -// $off-canvas-label-text-transform: uppercase; -// $off-canvas-label-font-weight: bold; -// $off-canvas-label-bg: #444; -// $off-canvas-label-border-top: 1px solid scale-color(#444, $lightness: 14%); -// $off-canvas-label-border-bottom: none; -// $off-canvas-label-margin:0; -// $off-canvas-link-padding: rem-calc(10, 15); -// $off-canvas-link-color: rgba(#FFF, 0.7); -// $off-canvas-link-border-bottom: 1px solid scale-color($off-canvas-bg, $lightness: -25%); - -// Off Canvas Menu Icon Variables -// $tabbar-menu-icon-color: #FFF; -// $tabbar-menu-icon-hover: scale-color($tabbar-menu-icon-color, $lightness: -30%); - -// $tabbar-menu-icon-text-indent: rem-calc(35); -// $tabbar-menu-icon-width: $tabbar-height; -// $tabbar-menu-icon-height: $tabbar-height; -// $tabbar-menu-icon-line-height: rem-calc(33); -// $tabbar-menu-icon-padding: 0; - -// $tabbar-hamburger-icon-width: rem-calc(16); -// $tabbar-hamburger-icon-left: rem-calc(13); -// $tabbar-hamburger-icon-top: rem-calc(5); - -// Off Canvas Back-Link Overlay -// $off-canvas-overlay-transition: background 300ms ease; -// $off-canvas-overlay-cursor: pointer; -// $off-canvas-overlay-box-shadow: -4px 0 4px rgba(#000, 0.5), 4px 0 4px rgba(#000, 0.5); -// $off-canvas-overlay-background: rgba(#FFF, 0.2); -// $off-canvas-overlay-background-hover: rgba(#FFF, 0.05); - -// Transition Variables -// $menu-slide: "transform 500ms ease"; - -// Orbit - -// $include-html-orbit-classes: $include-html-classes; - -// We use these to control the caption styles -// $orbit-container-bg: none; -// $orbit-caption-bg: rgba(51,51,51, 0.8); -// $orbit-caption-font-color: #fff; -// $orbit-caption-font-size: rem-calc(14); -// $orbit-caption-position: "bottom"; // Supported values: "bottom", "under" -// $orbit-caption-padding: rem-calc(10 14); -// $orbit-caption-height: auto; - -// We use these to control the left/right nav styles -// $orbit-nav-bg: none; -// $orbit-nav-bg-hover: rgba(0,0,0,0.3); -// $orbit-nav-arrow-color: #fff; -// $orbit-nav-arrow-color-hover: #fff; - -// We use these to control the timer styles -// $orbit-timer-bg: rgba(255,255,255,0.3); -// $orbit-timer-show-progress-bar: true; - -// We use these to control the bullet nav styles -// $orbit-bullet-nav-color: #ccc; -// $orbit-bullet-nav-color-active: #999; -// $orbit-bullet-radius: rem-calc(9); - -// We use these to controls the style of slide numbers -// $orbit-slide-number-bg: rgba(0,0,0,0); -// $orbit-slide-number-font-color: #fff; -// $orbit-slide-number-padding: rem-calc(5); - -// Graceful Loading Wrapper and preloader -// $wrapper-class: "slideshow-wrapper"; -// $preloader-class: "preloader"; - -// Pagination - -// $include-html-nav-classes: $include-html-classes; - -// We use these to control the pagination container -// $pagination-height: rem-calc(24); -// $pagination-margin: rem-calc(-5); - -// We use these to set the list-item properties -// $pagination-li-float: $default-float; -// $pagination-li-height: rem-calc(24); -// $pagination-li-font-color: #222; -// $pagination-li-font-size: rem-calc(14); -// $pagination-li-margin: rem-calc(5); - -// We use these for the pagination anchor links -// $pagination-link-pad: rem-calc(1 10 1); -// $pagination-link-font-color: #999; -// $pagination-link-active-bg: scale-color(#fff, $lightness: -10%); - -// We use these for disabled anchor links -// $pagination-link-unavailable-cursor: default; -// $pagination-link-unavailable-font-color: #999; -// $pagination-link-unavailable-bg-active: transparent; - -// We use these for currently selected anchor links -// $pagination-link-current-background: $primary-color; -// $pagination-link-current-font-color: #fff; -// $pagination-link-current-font-weight: bold; -// $pagination-link-current-cursor: default; -// $pagination-link-current-active-bg: $primary-color; - -// Panels - -// $include-html-panel-classes: $include-html-classes; - -// We use these to control the background and border styles -// $panel-bg: scale-color(#fff, $lightness: -5%); -// $panel-border-style: solid; -// $panel-border-size: 1px; - -// We use this % to control how much we darken things on hover -// $panel-function-factor: -11%; -// $panel-border-color: scale-color($panel-bg, $lightness: $panel-function-factor); - -// We use these to set default inner padding and bottom margin -// $panel-margin-bottom: rem-calc(20); -// $panel-padding: rem-calc(20); - -// We use these to set default font colors -// $panel-font-color: #333; -// $panel-font-color-alt: #fff; - -// $panel-header-adjust: true; -// $callout-panel-link-color: $primary-color; - -// Pricing Tables - -// $include-html-pricing-classes: $include-html-classes; - -// We use this to control the border color -// $price-table-border: solid 1px #ddd; - -// We use this to control the bottom margin of the pricing table -// $price-table-margin-bottom: rem-calc(20); - -// We use these to control the title styles -// $price-title-bg: #333; -// $price-title-padding: rem-calc(15 20); -// $price-title-align: center; -// $price-title-color: #eee; -// $price-title-weight: normal; -// $price-title-size: rem-calc(16); -// $price-title-font-family: $body-font-family; - -// We use these to control the price styles -// $price-money-bg: #f6f6f6 ; -// $price-money-padding: rem-calc(15 20); -// $price-money-align: center; -// $price-money-color: #333; -// $price-money-weight: normal; -// $price-money-size: rem-calc(32); -// $price-money-font-family: $body-font-family; - - -// We use these to control the description styles -// $price-bg: #fff; -// $price-desc-color: #777; -// $price-desc-padding: rem-calc(15); -// $price-desc-align: center; -// $price-desc-font-size: rem-calc(12); -// $price-desc-weight: normal; -// $price-desc-line-height: 1.4; -// $price-desc-bottom-border: dotted 1px #ddd; - -// We use these to control the list item styles -// $price-item-color: #333; -// $price-item-padding: rem-calc(15); -// $price-item-align: center; -// $price-item-font-size: rem-calc(14); -// $price-item-weight: normal; -// $price-item-bottom-border: dotted 1px #ddd; - -// We use these to control the CTA area styles -// $price-cta-bg: #fff; -// $price-cta-align: center; -// $price-cta-padding: rem-calc(20 20 0); - -// Progress Meters - -// $include-html-media-classes: $include-html-classes; - -// We use this to se the prog bar height -// $progress-bar-height: rem-calc(25); -// $progress-bar-color: #f6f6f6 ; - -// We use these to control the border styles -// $progress-bar-border-color: scale-color(#fff, $lightness: -20%); -// $progress-bar-border-size: 1px; -// $progress-bar-border-style: solid; -// $progress-bar-border-radius: $global-radius; - -// We use these to control the margin & padding -// $progress-bar-pad: rem-calc(2); -// $progress-bar-margin-bottom: rem-calc(10); - -// We use these to set the meter colors -// $progress-meter-color: $primary-color; -// $progress-meter-secondary-color: $secondary-color; -// $progress-meter-success-color: $success-color; -// $progress-meter-alert-color: $alert-color; - -// Reveal - -// $include-html-reveal-classes: $include-html-classes; - -// We use these to control the style of the reveal overlay. -// $reveal-overlay-bg: rgba(#000, .45); -// $reveal-overlay-bg-old: #000; - -// We use these to control the style of the modal itself. -// $reveal-modal-bg: #fff; -// $reveal-position-top: 50px; -// $reveal-default-width: 80%; -// $reveal-modal-padding: rem-calc(20); -// $reveal-box-shadow: 0 0 10px rgba(#000,.4); - -// We use these to style the reveal close button -// $reveal-close-font-size: rem-calc(22); -// $reveal-close-top: rem-calc(8); -// $reveal-close-side: rem-calc(11); -// $reveal-close-color: #aaa; -// $reveal-close-weight: bold; - -// We use these to control the modal border -// $reveal-border-style: solid; -// $reveal-border-width: 1px; -// $reveal-border-color: #666; - -// $reveal-modal-class: "reveal-modal"; -// $close-reveal-modal-class: "close-reveal-modal"; - -// Side Nav - -$include-html-nav-classes: true; - -// We use this to control padding. -$side-nav-padding: 1rem 1rem; - -// We use these to control list styles. -$side-nav-list-type: none; -$side-nav-list-position: inside; -$side-nav-list-margin: rem-calc(0 0 7 0); - -// We use these to control link styles. -$side-nav-link-color: $color-red; -$side-nav-link-color-active: scale-color($side-nav-link-color, $lightness: 30%); -$side-nav-link-color-hover: scale-color($side-nav-link-color, $lightness: 30%); -$side-nav-font-size: rem-calc(14); -$side-nav-font-weight: normal; -$side-nav-font-family: $body-font-family; -$side-nav-active-font-family: $side-nav-font-family; - - - -// We use these to control border styles -$side-nav-divider-size: 1px; -$side-nav-divider-style: solid; -$side-nav-divider-color: scale-color(#fff, $lightness: -10%); - -// Split Buttons - -// $include-html-button-classes: $include-html-classes; - -// We use these to control different shared styles for Split Buttons -// $split-button-function-factor: 10%; -// $split-button-pip-color: #fff; -// $split-button-pip-color-alt: #333; -// $split-button-active-bg-tint: rgba(0,0,0,0.1); - -// We use these to control tiny split buttons -// $split-button-padding-tny: $button-pip-tny * 10; -// $split-button-span-width-tny: $button-pip-tny * 6; -// $split-button-pip-size-tny: $button-pip-tny; -// $split-button-pip-top-tny: $button-pip-tny * 2; -// $split-button-pip-default-float-tny: rem-calc(-6); - -// We use these to control small split buttons -// $split-button-padding-sml: $button-pip-sml * 10; -// $split-button-span-width-sml: $button-pip-sml * 6; -// $split-button-pip-size-sml: $button-pip-sml; -// $split-button-pip-top-sml: $button-pip-sml * 1.5; -// $split-button-pip-default-float-sml: rem-calc(-6); - -// We use these to control medium split buttons -// $split-button-padding-med: $button-pip-med * 9; -// $split-button-span-width-med: $button-pip-med * 5.5; -// $split-button-pip-size-med: $button-pip-med - rem-calc(3); -// $split-button-pip-top-med: $button-pip-med * 1.5; -// $split-button-pip-default-float-med: rem-calc(-6); - -// We use these to control large split buttons -// $split-button-padding-lrg: $button-pip-lrg * 8; -// $split-button-span-width-lrg: $button-pip-lrg * 5; -// $split-button-pip-size-lrg: $button-pip-lrg - rem-calc(6); -// $split-button-pip-top-lrg: $button-pip-lrg + rem-calc(5); -// $split-button-pip-default-float-lrg: rem-calc(-6); - -// Sub Nav - -// $include-html-nav-classes: $include-html-classes; - -// We use these to control margin and padding -// $sub-nav-list-margin: rem-calc(-4 0 18); -// $sub-nav-list-padding-top: rem-calc(4); - -// We use this to control the definition -// $sub-nav-font-family: $body-font-family; -// $sub-nav-font-size: rem-calc(14); -// $sub-nav-font-color: #999; -// $sub-nav-font-weight: normal; -// $sub-nav-text-decoration: none; -// $sub-nav-border-radius: 3px; -// $sub-nav-font-color-hover: scale-color($sub-nav-font-color, $lightness: -25%); - - -// We use these to control the active item styles - -// $sub-nav-active-font-weight: normal; -// $sub-nav-active-bg: $primary-color; -// $sub-nav-active-bg-hover: scale-color($sub-nav-active-bg, $lightness: -14%); -// $sub-nav-active-color: #fff; -// $sub-nav-active-padding: rem-calc(3 16); -// $sub-nav-active-cursor: default; - -// $sub-nav-item-divider: ""; -// $sub-nav-item-divider-margin: rem-calc(12); - -// -// SWITCH -// - -// $include-html-form-classes: $include-html-classes; - -// Controlling border styles and background colors for the switch container -// $switch-border-color: scale-color(#fff, $lightness: -20%); -// $switch-border-style: solid; -// $switch-border-width: 1px; -// $switch-bg: #fff; - -// We use these to control the switch heights for our default classes -// $switch-height-tny: 22px; -// $switch-height-sml: 28px; -// $switch-height-med: 36px; -// $switch-height-lrg: 44px; -// $switch-bottom-margin: rem-calc(20); - -// We use these to control default font sizes for our classes. -// $switch-font-size-tny: 11px; -// $switch-font-size-sml: 12px; -// $switch-font-size-med: 14px; -// $switch-font-size-lrg: 17px; -// $switch-label-side-padding: 6px; - -// We use these to style the switch-paddle -// $switch-paddle-bg: #fff; -// $switch-paddle-fade-to-color: scale-color($switch-paddle-bg, $lightness: -10%); -// $switch-paddle-border-color: scale-color($switch-paddle-bg, $lightness: -35%); -// $switch-paddle-border-width: 1px; -// $switch-paddle-border-style: solid; -// $switch-paddle-transition-speed: .1s; -// $switch-paddle-transition-ease: ease-out; -// $switch-positive-color: scale-color($success-color, $lightness: 94%); -// $switch-negative-color: #f5f5f5; - -// Outline Style for tabbing through switches -// $switch-label-outline: 1px dotted #888; - -// Tables - -// $include-html-table-classes: $include-html-classes; - -// These control the background color for the table and even rows -// $table-bg: #fff; -// $table-even-row-bg: #f9f9f9 ; - -// These control the table cell border style -// $table-border-style: solid; -// $table-border-size: 1px; -// $table-border-color: #ddd; - -// These control the table head styles -// $table-head-bg: #f5f5f5 ; -// $table-head-font-size: rem-calc(14); -// $table-head-font-color: #222; -// $table-head-font-weight: bold; -// $table-head-padding: rem-calc(8 10 10); - -// These control the row padding and font styles -// $table-row-padding: rem-calc(9 10); -// $table-row-font-size: rem-calc(14); -// $table-row-font-color: #222; -// $table-line-height: rem-calc(18); - -// These are for controlling the display and margin of tables -// $table-display: table-cell; -// $table-margin-bottom: rem-calc(20); - -// -// TABS -// - -// $include-html-tabs-classes: $include-html-classes; - -// $tabs-navigation-padding: rem-calc(16); -// $tabs-navigation-bg-color: #efefef ; -// $tabs-navigation-active-bg-color: #fff; -// $tabs-navigation-hover-bg-color: scale-color($tabs-navigation-bg-color, $lightness: -6%); -// $tabs-navigation-font-color: #222; -// $tabs-navigation-font-size: rem-calc(16); -// $tabs-navigation-font-family: $body-font-family; - -// $tabs-content-margin-bottom: rem-calc(24); -// $tabs-content-padding: $column-gutter/2; - -// $tabs-vertical-navigation-margin-bottom: 1.25rem; - -// -// THUMBNAILS -// - -// $include-html-media-classes: $include-html-classes; - -// We use these to control border styles -// $thumb-border-style: solid; -// $thumb-border-width: 4px; -// $thumb-border-color: #fff; -// $thumb-box-shadow: 0 0 0 1px rgba(#000,.2); -// $thumb-box-shadow-hover: 0 0 6px 1px rgba($primary-color,0.5); - -// Radius and transition speed for thumbs -// $thumb-radius: $global-radius; -// $thumb-transition-speed: 200ms; - -// -// TOOLTIPS -// - -// $include-html-tooltip-classes: $include-html-classes; - -// $has-tip-border-bottom: dotted 1px #ccc; -// $has-tip-font-weight: bold; -// $has-tip-font-color: #333; -// $has-tip-border-bottom-hover: dotted 1px scale-color($primary-color, $lightness: -55%); -// $has-tip-font-color-hover: $primary-color; -// $has-tip-cursor-type: help; - -// $tooltip-padding: rem-calc(12); -// $tooltip-bg: #333; -// $tooltip-font-size: rem-calc(14); -// $tooltip-font-weight: normal; -// $tooltip-font-color: #fff; -// $tooltip-line-height: 1.3; -// $tooltip-close-font-size: rem-calc(10); -// $tooltip-close-font-weight: normal; -// $tooltip-close-font-color: #777; -// $tooltip-font-size-sml: rem-calc(14); -// $tooltip-radius: $global-radius; -// $tooltip-rounded: $global-rounded; -// $tooltip-pip-size: 5px; - -// -// TOP BAR -// - -$include-html-top-bar-classes: true; - -// Background color for the top bar -$topbar-bg-color: $color-gray; -$topbar-bg: $topbar-bg-color; - -// Height and margin -$topbar-height: 45px; -$topbar-margin-bottom: 0; - -// Controlling the styles for the title in the top bar -$topbar-title-weight: normal; -$topbar-title-font-size: rem-calc(17); - -// Style the top bar dropdown elements -$topbar-dropdown-bg: $color-gray; -$topbar-dropdown-link-color: #fff; -$topbar-dropdown-link-bg: $color-gray; -$topbar-dropdown-link-weight: normal; -$topbar-dropdown-toggle-size: 5px; -$topbar-dropdown-toggle-color: #fff; -$topbar-dropdown-toggle-alpha: 0.4; - -// Set the link colors and styles for top-level nav -$topbar-link-color: #fff; -$topbar-link-color-hover: #fff; -$topbar-link-color-active: #fff; -$topbar-link-color-active-hover: #fff; -$topbar-link-weight: normal; -$topbar-link-font-size: rem-calc(13); -$topbar-link-hover-lightness: -10%; // Darken by 10% -$topbar-link-bg-hover: #272727; -$topbar-link-bg-active: $color-red; -$topbar-link-bg-active-hover: scale-color($color-red, $lightness: -14%); -$topbar-link-font-family: $body-font-family; - -$topbar-button-font-size: 0.75rem; - -$topbar-dropdown-label-color: #777; -$topbar-dropdown-label-text-transform: uppercase; -$topbar-dropdown-label-font-weight: bold; -$topbar-dropdown-label-font-size: rem-calc(10); -$topbar-dropdown-label-bg: #333; - -// Top menu icon styles -$topbar-menu-link-transform: uppercase; -$topbar-menu-link-font-size: rem-calc(13); -$topbar-menu-link-weight: bold; -$topbar-menu-link-color: #fff; -$topbar-menu-icon-color: #fff; -$topbar-menu-link-color-toggled: #888; -$topbar-menu-icon-color-toggled: #888; - -// Transitions and breakpoint styles -$topbar-transition-speed: 300ms; -// Using rem-calc for the below breakpoint causes issues with top bar -$topbar-breakpoint: #{upper-bound($medium-range)}; // Change to 9999px for always mobile layout -$topbar-media-query: "only screen and (min-width: #{upper-bound($medium-range)})"; - -// Divider Styles -$topbar-divider-border-bottom: solid 1px scale-color($topbar-bg-color, $lightness: 13%); -$topbar-divider-border-top: solid 1px scale-color($topbar-bg-color, $lightness: -50%); - -// Sticky Class -$topbar-sticky-class: ".sticky"; -$topbar-arrows: true; //Set false to remove the triangle icon from the menu item - -// -// VISIBILITY CLASSES -// - -// $include-html-visibility-classes: $include-html-classes; diff --git a/src/axes/AutoScaleAxis.ts b/src/axes/AutoScaleAxis.ts new file mode 100644 index 000000000..26d9d7a02 --- /dev/null +++ b/src/axes/AutoScaleAxis.ts @@ -0,0 +1,50 @@ +import type { + ChartRect, + AxisOptions, + Bounds, + NormalizedSeries, + NormalizedSeriesPrimitiveValue +} from '../core'; +import { getBounds, getHighLow, getMultiValue } from '../core'; +import { AxisUnits, Axis } from './Axis'; + +export class AutoScaleAxis extends Axis { + private readonly bounds: Bounds; + public override readonly range: { + min: number; + max: number; + }; + + constructor( + axisUnit: AxisUnits, + data: NormalizedSeries[], + chartRect: ChartRect, + options: AxisOptions + ) { + // Usually we calculate highLow based on the data but this can be overriden by a highLow object in the options + const highLow = options.highLow || getHighLow(data, options, axisUnit.pos); + const bounds = getBounds( + chartRect[axisUnit.rectEnd] - chartRect[axisUnit.rectStart], + highLow, + options.scaleMinSpace || 20, + options.onlyInteger + ); + const range = { + min: bounds.min, + max: bounds.max + }; + + super(axisUnit, chartRect, bounds.values); + + this.bounds = bounds; + this.range = range; + } + + projectValue(value: NormalizedSeriesPrimitiveValue) { + const finalValue = Number(getMultiValue(value, this.units.pos)); + + return ( + (this.axisLength * (finalValue - this.bounds.min)) / this.bounds.range + ); + } +} diff --git a/src/axes/Axis.spec.ts b/src/axes/Axis.spec.ts new file mode 100644 index 000000000..8b95eea59 --- /dev/null +++ b/src/axes/Axis.spec.ts @@ -0,0 +1,135 @@ +import type { ChartRect } from '../core'; +import { Svg } from '../svg'; +import { EventEmitter } from '../event'; +import { Axis, axisUnits } from './Axis'; + +class MockAxis extends Axis { + projectValue(value: number) { + return value; + } +} + +describe('Axes', () => { + describe('Axis', () => { + let ticks: number[]; + let chartRect: ChartRect; + let chartOptions: any; + let eventEmitter: EventEmitter; + let gridGroup: Svg; + let labelGroup: Svg; + + beforeEach(() => { + eventEmitter = new EventEmitter(); + gridGroup = new Svg('g'); + labelGroup = new Svg('g'); + ticks = [1, 2]; + chartRect = { + padding: { + bottom: 5, + left: 10, + right: 15, + top: 15 + }, + y2: 15, + y1: 250, + x1: 50, + x2: 450, + width() { + return this.x2 - this.x1; + }, + height() { + return this.y1 - this.y2; + } + }; + + chartOptions = { + axisX: { + offset: 30, + position: 'end', + labelOffset: { + x: 0, + y: 0 + }, + showLabel: true, + showGrid: true + }, + classNames: { + label: 'ct-label', + labelGroup: 'ct-labels', + grid: 'ct-grid', + gridGroup: 'ct-grids', + vertical: 'ct-vertical', + horizontal: 'ct-horizontal', + start: 'ct-start', + end: 'ct-end' + } + }; + }); + + it('should skip all grid lines and labels for interpolated value of null', () => { + chartOptions.axisX.labelInterpolationFnc = ( + value: number, + index: number + ) => (index === 0 ? null : value); + + const axis = new MockAxis(axisUnits.x, chartRect, ticks); + + axis.createGridAndLabels( + gridGroup, + labelGroup, + chartOptions, + eventEmitter + ); + expect( + (gridGroup.querySelectorAll('.ct-grid') as any).svgElements.length + ).toBe(1); + expect( + (labelGroup.querySelectorAll('.ct-label') as any).svgElements.length + ).toBe(1); + }); + + it('should skip all grid lines and labels for interpolated value of undefined', () => { + chartOptions.axisX.labelInterpolationFnc = ( + value: number, + index: number + ) => (index === 0 ? undefined : value); + + const axis = new MockAxis(axisUnits.x, chartRect, ticks); + + axis.createGridAndLabels( + gridGroup, + labelGroup, + chartOptions, + eventEmitter + ); + expect( + (gridGroup.querySelectorAll('.ct-grid') as any).svgElements.length + ).toBe(1); + expect( + (labelGroup.querySelectorAll('.ct-label') as any).svgElements.length + ).toBe(1); + }); + + it('should include all grid lines and labels for interpolated value of empty strings', () => { + chartOptions.axisX.labelInterpolationFnc = ( + value: number, + index: number + ) => (index === 0 ? '' : value); + + const axis = new MockAxis(axisUnits.x, chartRect, ticks); + + axis.createGridAndLabels( + gridGroup, + labelGroup, + chartOptions, + eventEmitter + ); + expect( + (gridGroup.querySelectorAll('.ct-grid') as any).svgElements.length + ).toBe(2); + expect( + (labelGroup.querySelectorAll('.ct-label') as any).svgElements.length + ).toBe(2); + }); + }); +}); diff --git a/src/axes/Axis.ts b/src/axes/Axis.ts new file mode 100644 index 000000000..f0313a682 --- /dev/null +++ b/src/axes/Axis.ts @@ -0,0 +1,173 @@ +import type { + Label, + ChartRect, + OptionsWithDefaults, + NormalizedSeriesPrimitiveValue, + NormalizedSeries +} from '../core'; +import type { Svg } from '../svg'; +import type { EventEmitter } from '../event'; +import { isFalseyButZero } from '../utils'; +import { createGrid, createLabel } from '../core'; + +export const axisUnits = { + x: { + pos: 'x', + len: 'width', + dir: 'horizontal', + rectStart: 'x1', + rectEnd: 'x2', + rectOffset: 'y2' + }, + y: { + pos: 'y', + len: 'height', + dir: 'vertical', + rectStart: 'y2', + rectEnd: 'y1', + rectOffset: 'x1' + } +} as const; + +export type XAxisUnits = typeof axisUnits.x; +export type YAxisUnits = typeof axisUnits.y; +export type AxisUnits = XAxisUnits | YAxisUnits; + +export abstract class Axis { + public readonly counterUnits: AxisUnits; + public readonly range: + | { + min: number; + max: number; + } + | undefined; + readonly axisLength: number; + private readonly gridOffset: number; + + constructor( + public readonly units: AxisUnits, + private readonly chartRect: ChartRect, + private readonly ticks: Label[] + ) { + this.counterUnits = units === axisUnits.x ? axisUnits.y : axisUnits.x; + this.axisLength = + chartRect[this.units.rectEnd] - chartRect[this.units.rectStart]; + this.gridOffset = chartRect[this.units.rectOffset]; + } + + abstract projectValue( + value: NormalizedSeriesPrimitiveValue | Label, + index?: number, + series?: NormalizedSeries + ): number; + + createGridAndLabels( + gridGroup: Svg, + labelGroup: Svg, + chartOptions: OptionsWithDefaults, + eventEmitter: EventEmitter + ) { + const axisOptions = + this.units.pos === 'x' ? chartOptions.axisX : chartOptions.axisY; + const projectedValues = this.ticks.map((tick, i) => + this.projectValue(tick, i) + ); + const labelValues = this.ticks.map(axisOptions.labelInterpolationFnc); + + projectedValues.forEach((projectedValue, index) => { + const labelValue = labelValues[index]; + const labelOffset = { + x: 0, + y: 0 + }; + + // TODO: Find better solution for solving this problem + // Calculate how much space we have available for the label + let labelLength; + if (projectedValues[index + 1]) { + // If we still have one label ahead, we can calculate the distance to the next tick / label + labelLength = projectedValues[index + 1] - projectedValue; + } else { + // If we don't have a label ahead and we have only two labels in total, we just take the remaining distance to + // on the whole axis length. We limit that to a minimum of 30 pixel, so that labels close to the border will + // still be visible inside of the chart padding. + labelLength = Math.max( + this.axisLength - projectedValue, + this.axisLength / this.ticks.length + ); + } + + // Skip grid lines and labels where interpolated label values are falsey (except for 0) + if (labelValue !== '' && isFalseyButZero(labelValue)) { + return; + } + + // Transform to global coordinates using the chartRect + // We also need to set the label offset for the createLabel function + if (this.units.pos === 'x') { + projectedValue = this.chartRect.x1 + projectedValue; + labelOffset.x = chartOptions.axisX.labelOffset.x; + + // If the labels should be positioned in start position (top side for vertical axis) we need to set a + // different offset as for positioned with end (bottom) + if (chartOptions.axisX.position === 'start') { + labelOffset.y = + this.chartRect.padding.top + chartOptions.axisX.labelOffset.y + 5; + } else { + labelOffset.y = + this.chartRect.y1 + chartOptions.axisX.labelOffset.y + 5; + } + } else { + projectedValue = this.chartRect.y1 - projectedValue; + labelOffset.y = chartOptions.axisY.labelOffset.y - labelLength; + + // If the labels should be positioned in start position (left side for horizontal axis) we need to set a + // different offset as for positioned with end (right side) + if (chartOptions.axisY.position === 'start') { + labelOffset.x = + this.chartRect.padding.left + chartOptions.axisY.labelOffset.x; + } else { + labelOffset.x = + this.chartRect.x2 + chartOptions.axisY.labelOffset.x + 10; + } + } + + if (axisOptions.showGrid) { + createGrid( + projectedValue, + index, + this, + this.gridOffset, + this.chartRect[this.counterUnits.len](), + gridGroup, + [ + chartOptions.classNames.grid, + chartOptions.classNames[this.units.dir] + ], + eventEmitter + ); + } + + if (axisOptions.showLabel) { + createLabel( + projectedValue, + labelLength, + index, + labelValue, + this, + axisOptions.offset, + labelOffset, + labelGroup, + [ + chartOptions.classNames.label, + chartOptions.classNames[this.units.dir], + axisOptions.position === 'start' + ? chartOptions.classNames[axisOptions.position] + : chartOptions.classNames.end + ], + eventEmitter + ); + } + }); + } +} diff --git a/src/axes/FixedScaleAxis.spec.ts b/src/axes/FixedScaleAxis.spec.ts new file mode 100644 index 000000000..c9075b71d --- /dev/null +++ b/src/axes/FixedScaleAxis.spec.ts @@ -0,0 +1,53 @@ +import { FixedScaleAxis } from './FixedScaleAxis'; + +describe('Axes', () => { + describe('FixedScaleAxis', () => { + it('should order the tick array', () => { + const ticks = [10, 5, 0, -5, -10]; + const axisUnit = { + pos: 'y', + len: 'height', + dir: 'vertical', + rectStart: 'y2', + rectEnd: 'y1', + rectOffset: 'x1' + } as const; + const data = [ + [ + { x: 1, y: 10 }, + { x: 2, y: 5 }, + { x: 3, y: -5 } + ] + ]; + const chartRect: any = { + padding: { + top: 15, + right: 15, + bottom: 5, + left: 10 + }, + y2: 15, + y1: 141, + x1: 50, + x2: 269 + }; + const options = { + offset: 40, + position: 'start' as const, + labelOffset: { x: 0, y: 0 }, + showLabel: true, + showGrid: true, + scaleMinSpace: 20, + onlyInteger: false, + ticks + }; + const fsaxis: any = new FixedScaleAxis( + axisUnit, + data, + chartRect, + options + ); + expect(fsaxis.ticks).toEqual([-10, -5, 0, 5, 10]); + }); + }); +}); diff --git a/src/axes/FixedScaleAxis.ts b/src/axes/FixedScaleAxis.ts new file mode 100644 index 000000000..8bf774fde --- /dev/null +++ b/src/axes/FixedScaleAxis.ts @@ -0,0 +1,50 @@ +import type { + ChartRect, + AxisOptions, + NormalizedSeries, + NormalizedSeriesPrimitiveValue +} from '../core'; +import { getMultiValue, getHighLow } from '../core/data'; +import { times } from '../utils'; +import { AxisUnits, Axis } from './Axis'; + +export class FixedScaleAxis extends Axis { + public override readonly range: { + min: number; + max: number; + }; + + constructor( + axisUnit: AxisUnits, + data: NormalizedSeries[], + chartRect: ChartRect, + options: AxisOptions + ) { + const highLow = options.highLow || getHighLow(data, options, axisUnit.pos); + const divisor = options.divisor || 1; + const ticks = ( + options.ticks || + times( + divisor, + index => highLow.low + ((highLow.high - highLow.low) / divisor) * index + ) + ).sort((a, b) => Number(a) - Number(b)); + const range = { + min: highLow.low, + max: highLow.high + }; + + super(axisUnit, chartRect, ticks); + + this.range = range; + } + + projectValue(value: NormalizedSeriesPrimitiveValue) { + const finalValue = Number(getMultiValue(value, this.units.pos)); + + return ( + (this.axisLength * (finalValue - this.range.min)) / + (this.range.max - this.range.min) + ); + } +} diff --git a/src/axes/StepAxis.spec.ts b/src/axes/StepAxis.spec.ts new file mode 100644 index 000000000..473de0256 --- /dev/null +++ b/src/axes/StepAxis.spec.ts @@ -0,0 +1,29 @@ +import { StepAxis } from './StepAxis'; + +describe('Axes', () => { + describe('StepAxis', () => { + it('should return 0 if options.ticks.length == 1', () => { + const ticks = [1]; + const axisUnit = { + pos: 'y', + len: 'height', + dir: 'vertical', + rectStart: 'y2', + rectEnd: 'y1', + rectOffset: 'x1' + } as const; + const data = [[1]]; + const chartRect: any = { + y2: 0, + y1: 15, + x1: 50, + x2: 100 + }; + const options = { + ticks + }; + const stepAxis: any = new StepAxis(axisUnit, data, chartRect, options); + expect(stepAxis.stepLength).toEqual(15); + }); + }); +}); diff --git a/src/axes/StepAxis.ts b/src/axes/StepAxis.ts new file mode 100644 index 000000000..4a4ad9609 --- /dev/null +++ b/src/axes/StepAxis.ts @@ -0,0 +1,26 @@ +import type { ChartRect, AxisOptions } from '../core'; +import { AxisUnits, Axis } from './Axis'; + +export class StepAxis extends Axis { + private readonly stepLength: number; + public readonly stretch: boolean; + + constructor( + axisUnit: AxisUnits, + _data: unknown, + chartRect: ChartRect, + options: AxisOptions + ) { + const ticks = options.ticks || []; + + super(axisUnit, chartRect, ticks); + + const calc = Math.max(1, ticks.length - (options.stretch ? 1 : 0)); + this.stepLength = this.axisLength / calc; + this.stretch = Boolean(options.stretch); + } + + projectValue(_value: unknown, index: number) { + return this.stepLength * index; + } +} diff --git a/src/axes/index.ts b/src/axes/index.ts new file mode 100644 index 000000000..1e237b223 --- /dev/null +++ b/src/axes/index.ts @@ -0,0 +1,5 @@ +export * from './Axis'; +export * from './AutoScaleAxis'; +export * from './FixedScaleAxis'; +export * from './StepAxis'; +export * from './types'; diff --git a/src/axes/types.ts b/src/axes/types.ts new file mode 100644 index 000000000..978023d38 --- /dev/null +++ b/src/axes/types.ts @@ -0,0 +1,8 @@ +import type { AutoScaleAxis } from './AutoScaleAxis'; +import type { FixedScaleAxis } from './FixedScaleAxis'; +import type { StepAxis } from './StepAxis'; + +export type AxisType = + | typeof AutoScaleAxis + | typeof FixedScaleAxis + | typeof StepAxis; diff --git a/src/charts/BarChart/BarChart.spec.ts b/src/charts/BarChart/BarChart.spec.ts new file mode 100644 index 000000000..d3ce6070a --- /dev/null +++ b/src/charts/BarChart/BarChart.spec.ts @@ -0,0 +1,431 @@ +import { AutoScaleAxis } from '../../axes'; +import { BarChartOptions, BarChartData, BarChart } from '.'; +import { namespaces, deserialize } from '../../core'; +import { + Fixture, + addMockWrapper, + destroyMockDom, + mockDom, + mockDomRects, + destroyMockDomRects +} from '../../../test/mock/dom'; + +describe('Charts', () => { + describe('BarChart', () => { + let fixture: Fixture; + let chart: BarChart; + let options: BarChartOptions; + let data: BarChartData; + + function createChart() { + return new Promise(resolve => { + fixture = addMockWrapper( + '
' + ); + const { wrapper } = fixture; + chart = new BarChart( + wrapper.querySelector('.ct-chart'), + data, + options + ).on('created', () => { + resolve(); + chart.off('created'); + }); + }); + } + + beforeEach(() => { + mockDom(); + mockDomRects(); + }); + afterEach(() => { + destroyMockDom(); + destroyMockDomRects(); + data = { series: [] }; + options = {}; + }); + + describe('grids', () => { + beforeEach(() => { + data = { + series: [ + [ + { x: 1, y: 1 }, + { x: 3, y: 5 } + ] + ] + }; + options = { + axisX: { + type: AutoScaleAxis, + onlyInteger: true + }, + axisY: { + type: AutoScaleAxis, + onlyInteger: true + } + }; + }); + + it('should contain ct-grids group', async () => { + data = { series: [] }; + options = {}; + await createChart(); + + expect(fixture.wrapper.querySelectorAll('g.ct-grids').length).toBe(1); + }); + + it('should draw grid lines', async () => { + await createChart(); + + expect( + fixture.wrapper.querySelectorAll( + 'g.ct-grids line.ct-grid.ct-horizontal' + ).length + ).toBe(3); + expect( + fixture.wrapper.querySelectorAll( + 'g.ct-grids line.ct-grid.ct-vertical' + ).length + ).toBe(6); + }); + + it('should draw grid background', async () => { + options.showGridBackground = true; + await createChart(); + + expect( + fixture.wrapper.querySelectorAll('g.ct-grids rect.ct-grid-background') + .length + ).toBe(1); + }); + + it('should not draw grid background if option set to false', async () => { + options.showGridBackground = false; + await createChart(); + + expect( + fixture.wrapper.querySelectorAll('g.ct-grids rect.ct-grid-background') + .length + ).toBe(0); + }); + }); + + describe('ct:value attribute', () => { + it('should contain x and y value for each bar', async () => { + data = { + series: [ + [ + { x: 1, y: 2 }, + { x: 3, y: 4 } + ] + ] + }; + options = { + axisX: { + type: AutoScaleAxis + } + }; + await createChart(); + + const bars = fixture.wrapper.querySelectorAll('.ct-bar'); + expect(bars[0].getAttributeNS(namespaces.ct, 'value')).toEqual('1,2'); + expect(bars[1].getAttributeNS(namespaces.ct, 'value')).toEqual('3,4'); + }); + + it('should render values that are zero', async () => { + data = { + series: [ + [ + { x: 0, y: 1 }, + { x: 2, y: 0 }, + { x: 0, y: 0 } + ] + ] + }; + options = { + axisX: { + type: AutoScaleAxis + } + }; + await createChart(); + + const bars = fixture.wrapper.querySelectorAll('.ct-bar'); + expect(bars[0].getAttributeNS(namespaces.ct, 'value')).toEqual('0,1'); + expect(bars[1].getAttributeNS(namespaces.ct, 'value')).toEqual('2,0'); + expect(bars[2].getAttributeNS(namespaces.ct, 'value')).toEqual('0,0'); + }); + }); + + describe('Meta data tests', () => { + it('should render meta data correctly with mixed value array', async () => { + const meta = { + test: 'Serialized Test' + }; + + data = { + labels: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu'], + series: [ + [ + 5, + 2, + 4, + { + value: 2, + meta: meta + }, + 0 + ] + ] + }; + await createChart(); + + const bar = fixture.wrapper.querySelectorAll('.ct-bar')[3]; + expect(deserialize(bar.getAttributeNS(namespaces.ct, 'meta'))).toEqual( + meta + ); + }); + + it('should render meta data correctly with mixed value array and different normalized data length', async () => { + const meta = { + test: 'Serialized Test' + }; + + data = { + labels: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], + series: [ + [ + 5, + 2, + 4, + { + value: 2, + meta: meta + }, + 0 + ] + ] + }; + await createChart(); + + const bar = fixture.wrapper.querySelectorAll('.ct-bar')[3]; + expect(deserialize(bar.getAttributeNS(namespaces.ct, 'meta'))).toEqual( + meta + ); + }); + + it('should render meta data correctly with mixed value array and mixed series notation', async () => { + const seriesMeta = 9999; + const valueMeta = { + test: 'Serialized Test' + }; + + data = { + labels: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], + series: [ + [ + 5, + 2, + 4, + { + value: 2, + meta: valueMeta + }, + 0 + ], + { + meta: seriesMeta, + data: [ + 5, + 2, + { + value: 2, + meta: valueMeta + }, + 0 + ] + } + ] + }; + await createChart(); + + expect( + deserialize( + fixture.wrapper + .querySelectorAll('.ct-series-a .ct-bar')[3] + .getAttributeNS(namespaces.ct, 'meta') + ) + ).toEqual(valueMeta); + + expect( + deserialize( + fixture.wrapper + .querySelector('.ct-series-b') + ?.getAttributeNS(namespaces.ct, 'meta') + ) + ).toEqual(seriesMeta); + + expect( + deserialize( + fixture.wrapper + .querySelectorAll('.ct-series-b .ct-bar')[2] + .getAttributeNS(namespaces.ct, 'meta') + ) + ).toEqual(valueMeta); + }); + }); + + describe('Empty data tests', () => { + it('should render empty grid with no data', async () => { + data = { series: [] }; + options = {}; + await createChart(); + + // Find at least one vertical grid line + expect( + document.querySelector('.ct-grids .ct-grid.ct-vertical') + ).toBeDefined(); + }); + + it('should render empty grid with only labels', async () => { + data = { + labels: [1, 2, 3, 4], + series: [] + }; + await createChart(); + + // Find at least one vertical grid line + expect( + document.querySelector('.ct-grids .ct-grid.ct-vertical') + ).toBeDefined(); + // Find exactly as many horizontal grid lines as labels were specified (Step Axis) + expect( + document.querySelectorAll('.ct-grids .ct-grid.ct-horizontal').length + ).toBe(data.labels?.length); + }); + + it('should generate labels and render empty grid with only series in data', async () => { + data = { + series: [ + [1, 2, 3, 4], + [2, 3, 4], + [3, 4] + ] + }; + await createChart(); + + // Find at least one vertical grid line + expect( + document.querySelector('.ct-grids .ct-grid.ct-vertical') + ).toBeDefined(); + // Should generate the labels using the largest series count + expect( + document.querySelectorAll('.ct-grids .ct-grid.ct-horizontal').length + ).toBe( + Math.max( + ...data.series.map(series => + Array.isArray(series) ? series.length : 0 + ) + ) + ); + }); + + it('should render empty grid with no data and specified high low', async () => { + options = { + width: 400, + height: 300, + high: 100, + low: -100 + }; + await createChart(); + + // Find first and last label + const labels = document.querySelectorAll( + '.ct-labels .ct-label.ct-vertical' + ); + const firstLabel = labels[0]; + const lastLabel = labels[labels.length - 1]; + + expect(firstLabel.textContent?.trim()).toBe('-100'); + expect(lastLabel.textContent?.trim()).toBe('100'); + }); + + it('should render empty grid with no data and reverseData option', async () => { + options = { + reverseData: true + }; + await createChart(); + + // Find at least one vertical grid line + expect( + document.querySelector('.ct-grids .ct-grid.ct-vertical') + ).toBeDefined(); + }); + + it('should render empty grid with no data and stackBars option', async () => { + options = { + stackBars: true + }; + await createChart(); + + // Find at least one vertical grid line + expect( + document.querySelector('.ct-grids .ct-grid.ct-vertical') + ).toBeDefined(); + }); + + it('should render empty grid with no data and horizontalBars option', async () => { + options = { + horizontalBars: true + }; + await createChart(); + + // Find at least one vertical grid line + // TODO: In theory the axis should be created with ct-horizontal class + expect( + document.querySelector('.ct-grids .ct-grid.ct-vertical') + ).toBeDefined(); + }); + + it('should render empty grid with no data and distributeSeries option', async () => { + options = { + distributeSeries: true + }; + await createChart(); + + // Find at least one vertical grid line + expect( + document.querySelector('.ct-grids .ct-grid.ct-vertical') + ).toBeDefined(); + }); + }); + + it('should correct apply class names', async () => { + data = { + labels: ['A', 'B', 'C'], + series: [ + { + className: 'series-1', + data: [1, 2, 3] + }, + { + className: 'series-2', + data: [4, 5, 6] + } + ] + }; + options = { + reverseData: true + }; + await createChart(); + + const seriesElements = document.querySelectorAll('.ct-series'); + + expect(seriesElements[0]).toHaveClass('series-2'); + expect(seriesElements[0]).toContainHTML('ct:value="6"'); + + expect(seriesElements[1]).toHaveClass('series-1'); + expect(seriesElements[1]).toContainHTML('ct:value="3"'); + }); + }); +}); diff --git a/src/charts/BarChart/BarChart.stories.ts b/src/charts/BarChart/BarChart.stories.ts new file mode 100644 index 000000000..2a468f117 --- /dev/null +++ b/src/charts/BarChart/BarChart.stories.ts @@ -0,0 +1,490 @@ +import 'chartist-dev/styles'; +import { BarChart, AutoScaleAxis, Svg, getMultiValue } from 'chartist-dev'; +import { Viewport } from '../../../test/utils/storyshots/viewport'; + +export default { + title: 'BarChart', + argTypes: {} +}; + +export function Default() { + const root = document.createElement('div'); + + new BarChart( + root, + { + series: [ + [ + { x: 1, y: 1 }, + { x: 3, y: 5 } + ] + ] + }, + { + axisX: { + type: AutoScaleAxis, + onlyInteger: true + }, + axisY: { + type: AutoScaleAxis, + onlyInteger: true + } + } + ); + + return root; +} + +export function BiPolar() { + const root = document.createElement('div'); + + new BarChart( + root, + { + labels: ['W1', 'W2', 'W3', 'W4', 'W5', 'W6', 'W7', 'W8', 'W9', 'W10'], + series: [[1, 2, 4, 8, 6, -2, -1, -4, -6, -2]] + }, + { + high: 10, + low: -10, + axisX: { + labelInterpolationFnc(value, index) { + return index % 2 === 0 ? value : null; + } + } + } + ); + + return root; +} + +export function Labels() { + const root = document.createElement('div'); + + new BarChart( + root, + { + labels: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu'], + series: [[5, 2, 4, 2, 0]] + }, + {} + ); + + return root; +} + +export function MultilineLabels() { + const root = document.createElement('div'); + + new BarChart( + root, + { + labels: [ + 'First quarter of the year', + 'Second quarter of the year', + 'Third quarter of the year', + 'Fourth quarter of the year' + ], + series: [ + [60000, 40000, 80000, 70000], + [40000, 30000, 70000, 65000], + [8000, 3000, 10000, 6000] + ] + }, + { + seriesBarDistance: 10, + axisX: { + offset: 60 + }, + axisY: { + offset: 80, + labelInterpolationFnc(value) { + return value + ' CHF'; + }, + scaleMinSpace: 15 + } + } + ); + + return root; +} + +export function LabelsPlacement() { + const root = document.createElement('div'); + + new BarChart( + root, + { + labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], + series: [ + [5, 4, 3, 7, 5, 10, 3], + [3, 2, 9, 5, 4, 6, 4] + ] + }, + { + axisX: { + // On the x-axis start means top and end means bottom + position: 'start' + }, + axisY: { + // On the y-axis start means left and end means right + position: 'end' + } + } + ); + + return root; +} + +export function MultiSeries() { + const root = document.createElement('div'); + + new BarChart( + root, + { + series: [ + [1, 2, 3, 4], + [2, 3, 4], + [3, 4] + ] + }, + {} + ); + + return root; +} + +export function DistributedSeries() { + const root = document.createElement('div'); + + new BarChart( + root, + { + labels: ['XS', 'S', 'M', 'L', 'XL', 'XXL', 'XXXL'], + series: [20, 60, 120, 200, 180, 20, 10] + }, + { + distributeSeries: true + } + ); + + return root; +} + +export function ReverseData() { + const root = document.createElement('div'); + + new BarChart( + root, + { + series: [ + [1, 2, 3, 4], + [2, 3, 4], + [3, 4] + ] + }, + { + reverseData: true + } + ); + + return root; +} + +export function Stack() { + const root = document.createElement('div'); + + new BarChart( + root, + { + labels: ['Q1', 'Q2', 'Q3', 'Q4'], + series: [ + [800000, 1200000, 1400000, 1300000], + [200000, 400000, 500000, 300000], + [100000, 200000, 400000, 600000] + ] + }, + { + stackBars: true, + axisY: { + labelInterpolationFnc(value) { + return Number(value) / 1000 + 'k'; + } + } + } + ).on('draw', data => { + if (data.type === 'bar') { + data.element.attr({ + style: 'stroke-width: 30px' + }); + } + }); + + return root; +} + +export function Horizontal() { + const root = document.createElement('div'); + + new BarChart( + root, + { + labels: [ + 'Monday', + 'Tuesday', + 'Wednesday', + 'Thursday', + 'Friday', + 'Saturday', + 'Sunday' + ], + series: [ + [5, 4, 3, 7, 5, 10, 3], + [3, 2, 9, 5, 4, 6, 4] + ] + }, + { + seriesBarDistance: 10, + reverseData: true, + horizontalBars: true, + axisY: { + offset: 70 + } + } + ); + + return root; +} + +export function Adaptive() { + const root = document.createElement('div'); + + new BarChart( + root, + { + labels: ['Quarter 1', 'Quarter 2', 'Quarter 3', 'Quarter 4'], + series: [ + [5, 4, 3, 7], + [3, 2, 9, 5], + [1, 5, 8, 4], + [2, 3, 4, 6], + [4, 1, 2, 1] + ] + }, + { + // Default mobile configuration + stackBars: true, + axisX: { + labelInterpolationFnc: value => + String(value) + .split(/\s+/) + .map(word => word[0]) + .join('') + }, + axisY: { + offset: 20 + } + }, + [ + // Options override for media > 400px + [ + 'screen and (min-width: 400px)', + { + reverseData: true, + horizontalBars: true, + axisX: { + labelInterpolationFnc: () => undefined + }, + axisY: { + offset: 60 + } + } + ], + // Options override for media > 800px + [ + 'screen and (min-width: 800px)', + { + stackBars: false, + seriesBarDistance: 10 + } + ], + // Options override for media > 1000px + [ + 'screen and (min-width: 1000px)', + { + reverseData: false, + horizontalBars: false, + seriesBarDistance: 15 + } + ] + ] + ); + + return root; +} + +Adaptive.parameters = { + storyshots: { + viewports: [ + Viewport.Default, + Viewport.Tablet, + Viewport.MobileLandscape, + Viewport.Mobile + ] + } +}; + +export function OverlappingBarsOnMobile() { + const root = document.createElement('div'); + + new BarChart( + root, + { + labels: [ + 'Jan', + 'Feb', + 'Mar', + 'Apr', + 'May', + 'Jun', + 'Jul', + 'Aug', + 'Sep', + 'Oct', + 'Nov', + 'Dec' + ], + series: [ + [5, 4, 3, 7, 5, 10, 3, 4, 8, 10, 6, 8], + [3, 2, 9, 5, 4, 6, 4, 6, 7, 8, 7, 4] + ] + }, + { + seriesBarDistance: 10 + }, + [ + [ + 'screen and (max-width: 640px)', + { + seriesBarDistance: 5, + axisX: { + labelInterpolationFnc(value) { + return String(value)[0]; + } + } + } + ] + ] + ); + + return root; +} + +OverlappingBarsOnMobile.parameters = { + storyshots: { + viewports: [Viewport.Default, Viewport.Mobile] + } +}; + +export function PeakCircles() { + const root = document.createElement('div'); + + new BarChart( + root, + { + labels: ['W1', 'W2', 'W3', 'W4', 'W5', 'W6', 'W7', 'W8', 'W9', 'W10'], + series: [[1, 2, 4, 8, 6, -2, -1, -4, -6, -2]] + }, + { + high: 10, + low: -10, + axisX: { + labelInterpolationFnc(value, index) { + return index % 2 === 0 ? value : null; + } + } + } + ).on('draw', data => { + // If this draw event is of type bar we can use the data to create additional content + if (data.type === 'bar') { + // We use the group element of the current series to append a simple circle with the bar peek coordinates and a circle radius that is depending on the value + data.group.append( + new Svg( + 'circle', + { + cx: data.x2, + cy: data.y2, + r: Math.abs(Number(getMultiValue(data.value))) * 2 + 5 + }, + 'ct-slice-pie' + ) + ); + } + }); + + return root; +} + +export function AccumulateRelativeStack() { + const root = document.createElement('div'); + + new BarChart( + root, + { + labels: ['Monday', 'Tuesday', 'Wednesday', 'Thursday'], + series: [ + [5, 4, -3, -5], + [5, -4, 3, -5] + ] + }, + { + stackBars: true, + stackMode: 'accumulate-relative' + } + ); + + return root; +} + +export function ViewBox() { + const root = document.createElement('div'); + + new BarChart( + root, + { + series: [ + [ + { x: 1, y: 1 }, + { x: 3, y: 5 } + ] + ] + }, + { + axisX: { + type: AutoScaleAxis, + onlyInteger: true + }, + axisY: { + type: AutoScaleAxis, + onlyInteger: true + }, + viewBox: { + width: 800, + height: 300 + } + }, + [ + [ + 'screen and (max-width: 575px)', + { + viewBox: { + width: 400, + height: 150 + } + } + ] + ] + ); + + return root; +} diff --git a/src/charts/BarChart/BarChart.ts b/src/charts/BarChart/BarChart.ts new file mode 100644 index 000000000..7a22758e8 --- /dev/null +++ b/src/charts/BarChart/BarChart.ts @@ -0,0 +1,611 @@ +import type { Axis } from '../../axes'; +import type { + BarChartData, + BarChartOptions, + BarChartOptionsWithDefaults, + BarChartCreatedEvent, + BarDrawEvent, + BarChartEventsTypes +} from './BarChart.types'; +import type { + NormalizedSeries, + ResponsiveOptions, + AllSeriesTypes +} from '../../core'; +import { + isNumeric, + noop, + serialMap, + extend, + safeHasProperty, + each +} from '../../utils'; +import { + alphaNumerate, + normalizeData, + serialize, + getMetaData, + getHighLow, + createSvg, + createChartRect, + createGridBackground +} from '../../core'; +import { AutoScaleAxis, StepAxis, axisUnits } from '../../axes'; +import { BaseChart } from '../BaseChart'; + +function getSerialSums(series: NormalizedSeries[]) { + return serialMap(series, (...args) => + Array.from(args).reduce<{ x: number; y: number }>( + (prev, curr) => { + return { + x: prev.x + (safeHasProperty(curr, 'x') ? curr.x : 0), + y: prev.y + (safeHasProperty(curr, 'y') ? curr.y : 0) + }; + }, + { x: 0, y: 0 } + ) + ); +} + +/** + * Default options in bar charts. Expand the code view to see a detailed list of options with comments. + */ +const defaultOptions = { + // Options for X-Axis + axisX: { + // The offset of the chart drawing area to the border of the container + offset: 30, + // Position where labels are placed. Can be set to `start` or `end` where `start` is equivalent to left or top on vertical axis and `end` is equivalent to right or bottom on horizontal axis. + position: 'end' as const, + // Allows you to correct label positioning on this axis by positive or negative x and y offset. + labelOffset: { + x: 0, + y: 0 + }, + // If labels should be shown or not + showLabel: true, + // If the axis grid should be drawn or not + showGrid: true, + // Interpolation function that allows you to intercept the value from the axis label + labelInterpolationFnc: noop, + // This value specifies the minimum width in pixel of the scale steps + scaleMinSpace: 30, + // Use only integer values (whole numbers) for the scale steps + onlyInteger: false + }, + // Options for Y-Axis + axisY: { + // The offset of the chart drawing area to the border of the container + offset: 40, + // Position where labels are placed. Can be set to `start` or `end` where `start` is equivalent to left or top on vertical axis and `end` is equivalent to right or bottom on horizontal axis. + position: 'start' as const, + // Allows you to correct label positioning on this axis by positive or negative x and y offset. + labelOffset: { + x: 0, + y: 0 + }, + // If labels should be shown or not + showLabel: true, + // If the axis grid should be drawn or not + showGrid: true, + // Interpolation function that allows you to intercept the value from the axis label + labelInterpolationFnc: noop, + // This value specifies the minimum height in pixel of the scale steps + scaleMinSpace: 20, + // Use only integer values (whole numbers) for the scale steps + onlyInteger: false + }, + // Specify a fixed width for the chart as a string (i.e. '100px' or '50%') + width: undefined, + // Specify a fixed height for the chart as a string (i.e. '100px' or '50%') + height: undefined, + // Overriding the natural high of the chart allows you to zoom in or limit the charts highest displayed value + high: undefined, + // Overriding the natural low of the chart allows you to zoom in or limit the charts lowest displayed value + low: undefined, + // Unless low/high are explicitly set, bar chart will be centered at zero by default. Set referenceValue to null to auto scale. + referenceValue: 0, + // Padding of the chart drawing area to the container element and labels as a number or padding object {top: 5, right: 5, bottom: 5, left: 5} + chartPadding: { + top: 15, + right: 15, + bottom: 5, + left: 10 + }, + // Specify the distance in pixel of bars in a group + seriesBarDistance: 15, + // If set to true this property will cause the series bars to be stacked. Check the `stackMode` option for further stacking options. + stackBars: false, + // If set to true this property will force the stacked bars to draw from the zero line. + // If set to 'accumulate' this property will form a total for each series point. This will also influence the y-axis and the overall bounds of the chart. In stacked mode the seriesBarDistance property will have no effect. + // If set to 'accumulate-relative' positive and negative values will be handled separately. + stackMode: 'accumulate' as const, + // Inverts the axes of the bar chart in order to draw a horizontal bar chart. Be aware that you also need to invert your axis settings as the Y Axis will now display the labels and the X Axis the values. + horizontalBars: false, + // If set to true then each bar will represent a series and the data array is expected to be a one dimensional array of data values rather than a series array of series. This is useful if the bar chart should represent a profile rather than some data over time. + distributeSeries: false, + // If true the whole data is reversed including labels, the series order as well as the whole series data arrays. + reverseData: false, + // If the bar chart should add a background fill to the .ct-grids group. + showGridBackground: false, + // Override the class names that get used to generate the SVG structure of the chart + classNames: { + chart: 'ct-chart-bar', + horizontalBars: 'ct-horizontal-bars', + label: 'ct-label', + labelGroup: 'ct-labels', + series: 'ct-series', + bar: 'ct-bar', + grid: 'ct-grid', + gridGroup: 'ct-grids', + gridBackground: 'ct-grid-background', + vertical: 'ct-vertical', + horizontal: 'ct-horizontal', + start: 'ct-start', + end: 'ct-end' + } +}; + +export class BarChart extends BaseChart { + /** + * This method creates a new bar chart and returns API object that you can use for later changes. + * @param query A selector query string or directly a DOM element + * @param data The data object that needs to consist of a labels and a series array + * @param options The options object with options that override the default options. Check the examples for a detailed list. + * @param responsiveOptions Specify an array of responsive option arrays which are a media query and options object pair => [[mediaQueryString, optionsObject],[more...]] + * @return An object which exposes the API for the created chart + * + * @example + * ```ts + * // Create a simple bar chart + * const data = { + * labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'], + * series: [ + * [5, 2, 4, 2, 0] + * ] + * }; + * + * // In the global name space Chartist we call the Bar function to initialize a bar chart. As a first parameter we pass in a selector where we would like to get our chart created and as a second parameter we pass our data object. + * new BarChart('.ct-chart', data); + * ``` + * + * @example + * ```ts + * // This example creates a bipolar grouped bar chart where the boundaries are limitted to -10 and 10 + * new BarChart('.ct-chart', { + * labels: [1, 2, 3, 4, 5, 6, 7], + * series: [ + * [1, 3, 2, -5, -3, 1, -6], + * [-5, -2, -4, -1, 2, -3, 1] + * ] + * }, { + * seriesBarDistance: 12, + * low: -10, + * high: 10 + * }); + * ``` + */ + constructor( + query: string | Element | null, + protected override data: BarChartData, + options?: BarChartOptions, + responsiveOptions?: ResponsiveOptions + ) { + super( + query, + data, + defaultOptions, + extend({}, defaultOptions, options), + responsiveOptions + ); + } + + /** + * Creates a new chart + */ + createChart(options: BarChartOptionsWithDefaults) { + const { data } = this; + const normalizedData = normalizeData( + data, + options.reverseData, + options.horizontalBars ? 'x' : 'y', + true + ); + // Create new svg element + const svg = createSvg( + this.container, + options.width, + options.height, + options.classNames.chart + + (options.horizontalBars ? ' ' + options.classNames.horizontalBars : ''), + options.viewBox + ); + const highLow = + options.stackBars && + options.stackMode !== true && + normalizedData.series.length + ? // If stacked bars we need to calculate the high low from stacked values from each series + getHighLow( + [getSerialSums(normalizedData.series)], + options, + options.horizontalBars ? 'x' : 'y' + ) + : getHighLow( + normalizedData.series, + options, + options.horizontalBars ? 'x' : 'y' + ); + + this.svg = svg; + + // Drawing groups in correct order + const gridGroup = svg.elem('g').addClass(options.classNames.gridGroup); + const seriesGroup = svg.elem('g'); + const labelGroup = svg.elem('g').addClass(options.classNames.labelGroup); + + // Overrides of high / low from settings + if (typeof options.high === 'number') { + highLow.high = options.high; + } + + if (typeof options.low === 'number') { + highLow.low = options.low; + } + + const chartRect = createChartRect(svg, options); + let valueAxis: Axis; + const labelAxisTicks = // We need to set step count based on some options combinations + options.distributeSeries && options.stackBars + ? // If distributed series are enabled and bars need to be stacked, we'll only have one bar and therefore should + // use only the first label for the step axis + normalizedData.labels.slice(0, 1) + : // If distributed series are enabled but stacked bars aren't, we should use the series labels + // If we are drawing a regular bar chart with two dimensional series data, we just use the labels array + // as the bars are normalized + normalizedData.labels; + let labelAxis: Axis; + let axisX: Axis; + let axisY: Axis; + + // Set labelAxis and valueAxis based on the horizontalBars setting. This setting will flip the axes if necessary. + if (options.horizontalBars) { + if (options.axisX.type === undefined) { + valueAxis = axisX = new AutoScaleAxis( + axisUnits.x, + normalizedData.series, + chartRect, + { ...options.axisX, highLow: highLow, referenceValue: 0 } + ); + } else { + // eslint-disable-next-line new-cap + valueAxis = axisX = new options.axisX.type( + axisUnits.x, + normalizedData.series, + chartRect, + { ...options.axisX, highLow: highLow, referenceValue: 0 } + ); + } + + if (options.axisY.type === undefined) { + labelAxis = axisY = new StepAxis( + axisUnits.y, + normalizedData.series, + chartRect, + { + ticks: labelAxisTicks + } + ); + } else { + // eslint-disable-next-line new-cap + labelAxis = axisY = new options.axisY.type( + axisUnits.y, + normalizedData.series, + chartRect, + options.axisY + ); + } + } else { + if (options.axisX.type === undefined) { + labelAxis = axisX = new StepAxis( + axisUnits.x, + normalizedData.series, + chartRect, + { + ticks: labelAxisTicks + } + ); + } else { + // eslint-disable-next-line new-cap + labelAxis = axisX = new options.axisX.type( + axisUnits.x, + normalizedData.series, + chartRect, + options.axisX + ); + } + + if (options.axisY.type === undefined) { + valueAxis = axisY = new AutoScaleAxis( + axisUnits.y, + normalizedData.series, + chartRect, + { ...options.axisY, highLow: highLow, referenceValue: 0 } + ); + } else { + // eslint-disable-next-line new-cap + valueAxis = axisY = new options.axisY.type( + axisUnits.y, + normalizedData.series, + chartRect, + { ...options.axisY, highLow: highLow, referenceValue: 0 } + ); + } + } + + // Projected 0 point + const zeroPoint = options.horizontalBars + ? chartRect.x1 + valueAxis.projectValue(0) + : chartRect.y1 - valueAxis.projectValue(0); + const isAccumulateStackMode = options.stackMode === 'accumulate'; + const isAccumulateRelativeStackMode = + options.stackMode === 'accumulate-relative'; + // Used to track the screen coordinates of stacked bars + const posStackedBarValues: number[] = []; + const negStackedBarValues: number[] = []; + let stackedBarValues = posStackedBarValues; + + labelAxis.createGridAndLabels( + gridGroup, + labelGroup, + options, + this.eventEmitter + ); + valueAxis.createGridAndLabels( + gridGroup, + labelGroup, + options, + this.eventEmitter + ); + + if (options.showGridBackground) { + createGridBackground( + gridGroup, + chartRect, + options.classNames.gridBackground, + this.eventEmitter + ); + } + + // Draw the series + each( + data.series, + (series, seriesIndex) => { + // Calculating bi-polar value of index for seriesOffset. For i = 0..4 biPol will be -1.5, -0.5, 0.5, 1.5 etc. + const biPol = seriesIndex - (data.series.length - 1) / 2; + // Half of the period width between vertical grid lines used to position bars + let periodHalfLength: number; + + // We need to set periodHalfLength based on some options combinations + if (options.distributeSeries && !options.stackBars) { + // If distributed series are enabled but stacked bars aren't, we need to use the length of the normaizedData array + // which is the series count and divide by 2 + periodHalfLength = + labelAxis.axisLength / normalizedData.series.length / 2; + } else if (options.distributeSeries && options.stackBars) { + // If distributed series and stacked bars are enabled we'll only get one bar so we should just divide the axis + // length by 2 + periodHalfLength = labelAxis.axisLength / 2; + } else { + // On regular bar charts we should just use the series length + periodHalfLength = + labelAxis.axisLength / + normalizedData.series[seriesIndex].length / + 2; + } + + // Adding the series group to the series element + const seriesElement = seriesGroup.elem('g'); + const seriesName = safeHasProperty(series, 'name') && series.name; + const seriesClassName = + safeHasProperty(series, 'className') && series.className; + const seriesMeta = safeHasProperty(series, 'meta') + ? series.meta + : undefined; + + // Write attributes to series group element. If series name or meta is undefined the attributes will not be written + if (seriesName) { + seriesElement.attr({ + 'ct:series-name': seriesName + }); + } + + if (seriesMeta) { + seriesElement.attr({ + 'ct:meta': serialize(seriesMeta) + }); + } + + // Use series class from series data or if not set generate one + seriesElement.addClass( + [ + options.classNames.series, + seriesClassName || + `${options.classNames.series}-${alphaNumerate(seriesIndex)}` + ].join(' ') + ); + + normalizedData.series[seriesIndex].forEach((value, valueIndex) => { + const valueX = safeHasProperty(value, 'x') && value.x; + const valueY = safeHasProperty(value, 'y') && value.y; + let labelAxisValueIndex; + // We need to set labelAxisValueIndex based on some options combinations + if (options.distributeSeries && !options.stackBars) { + // If distributed series are enabled but stacked bars aren't, we can use the seriesIndex for later projection + // on the step axis for label positioning + labelAxisValueIndex = seriesIndex; + } else if (options.distributeSeries && options.stackBars) { + // If distributed series and stacked bars are enabled, we will only get one bar and therefore always use + // 0 for projection on the label step axis + labelAxisValueIndex = 0; + } else { + // On regular bar charts we just use the value index to project on the label step axis + labelAxisValueIndex = valueIndex; + } + + let projected; + // We need to transform coordinates differently based on the chart layout + if (options.horizontalBars) { + projected = { + x: + chartRect.x1 + + valueAxis.projectValue( + valueX || 0, + valueIndex, + normalizedData.series[seriesIndex] + ), + y: + chartRect.y1 - + labelAxis.projectValue( + valueY || 0, + labelAxisValueIndex, + normalizedData.series[seriesIndex] + ) + }; + } else { + projected = { + x: + chartRect.x1 + + labelAxis.projectValue( + valueX || 0, + labelAxisValueIndex, + normalizedData.series[seriesIndex] + ), + y: + chartRect.y1 - + valueAxis.projectValue( + valueY || 0, + valueIndex, + normalizedData.series[seriesIndex] + ) + }; + } + + // If the label axis is a step based axis we will offset the bar into the middle of between two steps using + // the periodHalfLength value. Also we do arrange the different series so that they align up to each other using + // the seriesBarDistance. If we don't have a step axis, the bar positions can be chosen freely so we should not + // add any automated positioning. + if (labelAxis instanceof StepAxis) { + // Offset to center bar between grid lines, but only if the step axis is not stretched + if (!labelAxis.stretch) { + projected[labelAxis.units.pos] += + periodHalfLength * (options.horizontalBars ? -1 : 1); + } + // Using bi-polar offset for multiple series if no stacked bars or series distribution is used + projected[labelAxis.units.pos] += + options.stackBars || options.distributeSeries + ? 0 + : biPol * + options.seriesBarDistance * + (options.horizontalBars ? -1 : 1); + } + + // distinguish between positive and negative values in relative stack mode + if (isAccumulateRelativeStackMode) { + stackedBarValues = + valueY >= 0 || valueX >= 0 + ? posStackedBarValues + : negStackedBarValues; + } + + // Enter value in stacked bar values used to remember previous screen value for stacking up bars + const previousStack = stackedBarValues[valueIndex] || zeroPoint; + stackedBarValues[valueIndex] = + previousStack - (zeroPoint - projected[labelAxis.counterUnits.pos]); + + // Skip if value is undefined + if (value === undefined) { + return; + } + + const positions = { + [`${labelAxis.units.pos}1`]: projected[labelAxis.units.pos], + [`${labelAxis.units.pos}2`]: projected[labelAxis.units.pos] + } as Record<'x1' | 'y1' | 'x2' | 'y2', number>; + + if ( + options.stackBars && + (isAccumulateStackMode || + isAccumulateRelativeStackMode || + !options.stackMode) + ) { + // Stack mode: accumulate (default) + // If bars are stacked we use the stackedBarValues reference and otherwise base all bars off the zero line + // We want backwards compatibility, so the expected fallback without the 'stackMode' option + // to be the original behaviour (accumulate) + positions[`${labelAxis.counterUnits.pos}1`] = previousStack; + positions[`${labelAxis.counterUnits.pos}2`] = + stackedBarValues[valueIndex]; + } else { + // Draw from the zero line normally + // This is also the same code for Stack mode: overlap + positions[`${labelAxis.counterUnits.pos}1`] = zeroPoint; + positions[`${labelAxis.counterUnits.pos}2`] = + projected[labelAxis.counterUnits.pos]; + } + + // Limit x and y so that they are within the chart rect + positions.x1 = Math.min( + Math.max(positions.x1, chartRect.x1), + chartRect.x2 + ); + positions.x2 = Math.min( + Math.max(positions.x2, chartRect.x1), + chartRect.x2 + ); + positions.y1 = Math.min( + Math.max(positions.y1, chartRect.y2), + chartRect.y1 + ); + positions.y2 = Math.min( + Math.max(positions.y2, chartRect.y2), + chartRect.y1 + ); + + const metaData = getMetaData(series, valueIndex); + + // Create bar element + const bar = seriesElement + .elem('line', positions, options.classNames.bar) + .attr({ + 'ct:value': [valueX, valueY].filter(isNumeric).join(','), + 'ct:meta': serialize(metaData) + }); + + this.eventEmitter.emit('draw', { + type: 'bar', + value, + index: valueIndex, + meta: metaData, + series, + seriesIndex, + axisX, + axisY, + chartRect, + group: seriesElement, + element: bar, + ...positions + }); + }); + }, + options.reverseData + ); + + this.eventEmitter.emit('created', { + chartRect, + axisX, + axisY, + svg, + options + }); + } +} diff --git a/src/charts/BarChart/BarChart.types.ts b/src/charts/BarChart/BarChart.types.ts new file mode 100644 index 000000000..65590bfd2 --- /dev/null +++ b/src/charts/BarChart/BarChart.types.ts @@ -0,0 +1,115 @@ +import type { + Options, + AxisOptions, + Data, + CreatedEvent, + DrawEvent, + NormalizedMulti, + AxesDrawEvent +} from '../../core'; +import type { RequiredKeys } from '../../utils'; +import type { BaseChartEventsTypes } from '../types'; + +export type BarChartData = Data; + +export interface BarChartOptions< + TXAxisOptions = AxisOptions, + TYAxisOptions = TXAxisOptions +> extends Options { + /** + * Override the class names that get used to generate the SVG structure of the chart + */ + classNames?: { + chart?: string; + horizontalBars?: string; + label?: string; + labelGroup?: string; + series?: string; + bar?: string; + grid?: string; + gridGroup?: string; + gridBackground?: string; + vertical?: string; + horizontal?: string; + start?: string; + end?: string; + }; + /** + * Specify the distance in pixel of bars in a group + */ + seriesBarDistance?: number; + /** + * If set to true this property will cause the series bars to be stacked. Check the `stackMode` option for further stacking options. + */ + stackBars?: boolean; + /** + * If set to true this property will force the stacked bars to draw from the zero line. + * If set to 'accumulate' this property will form a total for each series point. This will also influence the y-axis and the overall bounds of the chart. In stacked mode the seriesBarDistance property will have no effect. + * If set to 'accumulate-relative' positive and negative values will be handled separately. + */ + stackMode?: 'accumulate' | 'accumulate-relative' | boolean; + /** + * Inverts the axes of the bar chart in order to draw a horizontal bar chart. Be aware that you also need to invert your axis settings as the Y Axis will now display the labels and the X Axis the values. + */ + horizontalBars?: boolean; + /** + * If set to true then each bar will represent a series and the data array is expected to be a one dimensional array of data values rather than a series array of series. This is useful if the bar chart should represent a profile rather than some data over time. + */ + distributeSeries?: boolean; + /** + * If true the whole data is reversed including labels, the series order as well as the whole series data arrays. + */ + reverseData?: boolean; + /** + * If the bar chart should add a background fill to the .ct-grids group. + */ + showGridBackground?: boolean; +} + +export type BarChartOptionsWithDefaults = RequiredKeys< + BarChartOptions< + RequiredKeys< + AxisOptions, + | 'offset' + | 'position' + | 'labelOffset' + | 'showLabel' + | 'showGrid' + | 'labelInterpolationFnc' + | 'scaleMinSpace' + >, + RequiredKeys< + AxisOptions, + | 'offset' + | 'position' + | 'labelOffset' + | 'showLabel' + | 'showGrid' + | 'labelInterpolationFnc' + | 'scaleMinSpace' + > + >, + | 'referenceValue' + | 'chartPadding' + | 'seriesBarDistance' + | 'stackMode' + | 'axisX' + | 'axisY', + 'classNames' +>; + +export type BarChartCreatedEvent = CreatedEvent; + +export interface BarDrawEvent extends DrawEvent { + type: 'bar'; + value: number | NormalizedMulti; + x1: number; + y1: number; + x2: number; + y2: number; +} + +export type BarChartEventsTypes = BaseChartEventsTypes< + BarChartCreatedEvent, + AxesDrawEvent | BarDrawEvent +>; diff --git a/src/charts/BarChart/index.ts b/src/charts/BarChart/index.ts new file mode 100644 index 000000000..340742b55 --- /dev/null +++ b/src/charts/BarChart/index.ts @@ -0,0 +1,2 @@ +export * from './BarChart'; +export * from './BarChart.types'; diff --git a/src/charts/BaseChart.ts b/src/charts/BaseChart.ts new file mode 100644 index 000000000..46c25049e --- /dev/null +++ b/src/charts/BaseChart.ts @@ -0,0 +1,198 @@ +import type { Data, Options, DataEvent, ResponsiveOptions } from '../core'; +import type { Svg } from '../svg'; +import type { BaseChartEventsTypes } from './types'; +import { OptionsProvider, optionsProvider } from '../core'; +import { extend } from '../utils'; +import { EventListener, AllEventsListener, EventEmitter } from '../event'; + +const instances = new WeakMap>(); + +export abstract class BaseChart { + protected svg?: Svg; + protected readonly container: Element; + protected readonly eventEmitter = new EventEmitter(); + private readonly resizeListener = () => this.update(); + // Using event loop for first draw to make it possible to register event listeners in the same call stack where + // the chart was created. + private initializeTimeoutId: NodeJS.Timer | null = setTimeout( + () => this.initialize(), + 0 + ); + private optionsProvider?: OptionsProvider; + + constructor( + query: string | Element | null, + protected data: Data, + private readonly defaultOptions: Options, + private options: Options, + private readonly responsiveOptions?: ResponsiveOptions + ) { + const container = + typeof query === 'string' ? document.querySelector(query) : query; + + if (!container) { + throw new Error( + `Target element ${ + typeof query === 'string' ? `"${query}"` : '' + } is not found` + ); + } + + this.container = container; + + const prevInstance = instances.get(container); + + // If chartist was already initialized in this container we are detaching all event listeners first + if (prevInstance) { + prevInstance.detach(); + } + + instances.set(container, this); + } + + abstract createChart(options: Options): void; + + // TODO: Currently we need to re-draw the chart on window resize. This is usually very bad and will affect performance. + // This is done because we can't work with relative coordinates when drawing the chart because SVG Path does not + // work with relative positions yet. We need to check if we can do a viewBox hack to switch to percentage. + // See http://mozilla.6506.n7.nabble.com/Specyfing-paths-with-percentages-unit-td247474.html + // Update: can be done using the above method tested here: http://codepen.io/gionkunz/pen/KDvLj + // The problem is with the label offsets that can't be converted into percentage and affecting the chart container + /** + * Updates the chart which currently does a full reconstruction of the SVG DOM + * @param data Optional data you'd like to set for the chart before it will update. If not specified the update method will use the data that is already configured with the chart. + * @param options Optional options you'd like to add to the previous options for the chart before it will update. If not specified the update method will use the options that have been already configured with the chart. + * @param override If set to true, the passed options will be used to extend the options that have been configured already. Otherwise the chart default options will be used as the base + */ + update(data?: Data, options?: Options, override = false) { + if (data) { + this.data = data || {}; + this.data.labels = this.data.labels || []; + this.data.series = this.data.series || []; + // Event for data transformation that allows to manipulate the data before it gets rendered in the charts + this.eventEmitter.emit('data', { + type: 'update', + data: this.data + }); + } + + if (options) { + this.options = extend( + {}, + override ? this.options : this.defaultOptions, + options + ); + + // If chartist was not initialized yet, we just set the options and leave the rest to the initialization + // Otherwise we re-create the optionsProvider at this point + if (!this.initializeTimeoutId) { + this.optionsProvider?.removeMediaQueryListeners(); + this.optionsProvider = optionsProvider( + this.options, + this.responsiveOptions, + this.eventEmitter + ); + } + } + + // Only re-created the chart if it has been initialized yet + if (!this.initializeTimeoutId && this.optionsProvider) { + this.createChart(this.optionsProvider.getCurrentOptions()); + } + + // Return a reference to the chart object to chain up calls + return this; + } + + /** + * This method can be called on the API object of each chart and will un-register all event listeners that were added to other components. This currently includes a window.resize listener as well as media query listeners if any responsive options have been provided. Use this function if you need to destroy and recreate Chartist charts dynamically. + */ + detach() { + // Only detach if initialization already occurred on this chart. If this chart still hasn't initialized (therefore + // the initializationTimeoutId is still a valid timeout reference, we will clear the timeout + if (!this.initializeTimeoutId) { + window.removeEventListener('resize', this.resizeListener); + this.optionsProvider?.removeMediaQueryListeners(); + } else { + window.clearTimeout(this.initializeTimeoutId); + } + + instances.delete(this.container); + + return this; + } + + /** + * Use this function to register event handlers. The handler callbacks are synchronous and will run in the main thread rather than the event loop. + * @param event Name of the event. Check the examples for supported events. + * @param listener The handler function that will be called when an event with the given name was emitted. This function will receive a data argument which contains event data. See the example for more details. + */ + on( + event: T, + listener: EventListener + ): this; + on(event: '*', listener: AllEventsListener): this; + on(event: string, listener: EventListener): this; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + on(event: string, listener: any) { + this.eventEmitter.on(event, listener); + return this; + } + + /** + * Use this function to un-register event handlers. If the handler function parameter is omitted all handlers for the given event will be un-registered. + * @param event Name of the event for which a handler should be removed + * @param listener The handler function that that was previously used to register a new event handler. This handler will be removed from the event handler list. If this parameter is omitted then all event handlers for the given event are removed from the list. + */ + off( + event: T, + listener?: EventListener + ): this; + off(event: '*', listener?: AllEventsListener): this; + off(event: string, listener?: EventListener): this; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + off(event: string, listener?: any) { + this.eventEmitter.off(event, listener); + return this; + } + + initialize() { + // Add window resize listener that re-creates the chart + window.addEventListener('resize', this.resizeListener); + + // Obtain current options based on matching media queries (if responsive options are given) + // This will also register a listener that is re-creating the chart based on media changes + this.optionsProvider = optionsProvider( + this.options, + this.responsiveOptions, + this.eventEmitter + ); + // Register options change listener that will trigger a chart update + this.eventEmitter.on('optionsChanged', () => this.update()); + + // Before the first chart creation we need to register us with all plugins that are configured + // Initialize all relevant plugins with our chart object and the plugin options specified in the config + if (this.options.plugins) { + this.options.plugins.forEach(plugin => { + if (Array.isArray(plugin)) { + plugin[0](this, plugin[1]); + } else { + plugin(this); + } + }); + } + + // Event for data transformation that allows to manipulate the data before it gets rendered in the charts + this.eventEmitter.emit('data', { + type: 'initial', + data: this.data + }); + + // Create the first chart + this.createChart(this.optionsProvider.getCurrentOptions()); + + // As chart is initialized from the event loop now we can reset our timeout reference + // This is important if the chart gets initialized on the same element twice + this.initializeTimeoutId = null; + } +} diff --git a/src/charts/LineChart/LineChart.spec.ts b/src/charts/LineChart/LineChart.spec.ts new file mode 100644 index 000000000..d372440e5 --- /dev/null +++ b/src/charts/LineChart/LineChart.spec.ts @@ -0,0 +1,1060 @@ +import { AutoScaleAxis, FixedScaleAxis } from '../../axes'; +import { LineChartOptions, LineChartData, LineChart } from '.'; +import * as Interpolation from '../../interpolation'; +import { namespaces, deserialize } from '../../core'; +import { + Fixture, + addMockWrapper, + destroyMockDom, + mockDom, + mockDomRects, + destroyMockDomRects +} from '../../../test/mock/dom'; + +describe('Charts', () => { + describe('LineChart', () => { + let fixture: Fixture; + let chart: LineChart; + let options: LineChartOptions; + let data: LineChartData; + + function createChart() { + return new Promise(resolve => { + fixture = addMockWrapper( + '
' + ); + const { wrapper } = fixture; + chart = new LineChart( + wrapper.querySelector('.ct-chart'), + data, + options + ).on('created', () => { + resolve(); + chart.off('created'); + }); + }); + } + + beforeEach(() => { + mockDom(); + mockDomRects(); + }); + afterEach(() => { + destroyMockDom(); + destroyMockDomRects(); + data = { series: [] }; + options = {}; + }); + + describe('grids', () => { + beforeEach(() => { + data = { + series: [ + [ + { x: 1, y: 1 }, + { x: 3, y: 5 } + ] + ] + }; + options = { + axisX: { + type: AutoScaleAxis, + onlyInteger: true + }, + axisY: { + type: AutoScaleAxis, + onlyInteger: true + } + }; + }); + + it('should contain ct-grids group', async () => { + await createChart(); + + expect(fixture.wrapper.querySelectorAll('.ct-grids').length).toBe(1); + }); + + it('should draw grid lines', async () => { + await createChart(); + + expect( + fixture.wrapper.querySelectorAll('.ct-grids .ct-grid.ct-horizontal') + .length + ).toBe(3); + expect( + fixture.wrapper.querySelectorAll('.ct-grids .ct-grid.ct-vertical') + .length + ).toBe(5); + }); + + it('should draw grid background', async () => { + options.showGridBackground = true; + await createChart(); + + expect( + fixture.wrapper.querySelectorAll('.ct-grids .ct-grid-background') + .length + ).toBe(1); + }); + + it('should not draw grid background if option set to false', async () => { + options.showGridBackground = false; + await createChart(); + + expect( + fixture.wrapper.querySelectorAll('.ct-grids .ct-grid-background') + .length + ).toBe(0); + }); + }); + + describe('AxisY position tests', () => { + beforeEach(() => { + data = { + series: [ + [ + { x: 1, y: 1 }, + { x: 3, y: 5 } + ] + ] + }; + options = {}; + }); + + it('should have ct-start class if position start', async () => { + options = { + axisY: { + position: 'start' + } + }; + await createChart(); + + Array.from( + fixture.wrapper.querySelectorAll('.ct-label.ct-vertical') + ).forEach(element => + expect(element).toHaveAttribute( + 'class', + 'ct-label ct-vertical ct-start' + ) + ); + }); + + it('should have ct-end class if position is any other value than start', async () => { + options = { + axisY: { + position: 'end' as const + } + }; + await createChart(); + + Array.from( + fixture.wrapper.querySelectorAll('.ct-label.ct-vertical') + ).forEach(element => + expect(element).toHaveAttribute( + 'class', + 'ct-label ct-vertical ct-end' + ) + ); + }); + }); + + describe('ct:value attribute', () => { + it('should contain x and y value for each datapoint', async () => { + data = { + series: [ + [ + { x: 1, y: 2 }, + { x: 3, y: 4 } + ] + ] + }; + options = { + axisX: { + type: FixedScaleAxis + } + }; + await createChart(); + + const points = fixture.wrapper.querySelectorAll('.ct-point'); + expect(points[0].getAttributeNS(namespaces.ct, 'value')).toBe('1,2'); + expect(points[1].getAttributeNS(namespaces.ct, 'value')).toBe('3,4'); + }); + + it('should render values that are zero', async () => { + data = { + series: [ + [ + { x: 0, y: 1 }, + { x: 1, y: 0 }, + { x: 0, y: 0 } + ] + ] + }; + options = { + axisX: { + type: FixedScaleAxis + } + }; + await createChart(); + + const points = fixture.wrapper.querySelectorAll('.ct-point'); + expect(points[0].getAttributeNS(namespaces.ct, 'value')).toBe('0,1'); + expect(points[1].getAttributeNS(namespaces.ct, 'value')).toBe('1,0'); + expect(points[2].getAttributeNS(namespaces.ct, 'value')).toBe('0,0'); + }); + }); + + describe('Meta data tests', () => { + it('should render meta data correctly with mixed value array', async () => { + const meta = { + test: 'Serialized Test' + }; + + data = { + labels: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu'], + series: [ + [ + 5, + 2, + 4, + { + value: 2, + meta: meta + }, + 0 + ] + ] + }; + await createChart(); + + const points = fixture.wrapper.querySelectorAll('.ct-point'); + expect( + deserialize(points[3].getAttributeNS(namespaces.ct, 'meta')) + ).toEqual(meta); + }); + + it('should render meta data correctly with mixed value array and different normalized data length', async () => { + const meta = { + test: 'Serialized Test' + }; + + data = { + labels: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], + series: [ + [ + 5, + 2, + 4, + { + value: 2, + meta: meta + }, + 0 + ] + ] + }; + await createChart(); + + const points = fixture.wrapper.querySelectorAll('.ct-point'); + expect( + deserialize(points[3].getAttributeNS(namespaces.ct, 'meta')) + ).toEqual(meta); + }); + + it('should render meta data correctly with mixed value array and mixed series notation', async () => { + const seriesMeta = 9999; + const valueMeta = { + test: 'Serialized Test' + }; + + data = { + labels: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], + series: [ + [ + 5, + 2, + 4, + { + value: 2, + meta: valueMeta + }, + 0 + ], + { + meta: seriesMeta, + data: [ + 5, + 2, + { + value: 2, + meta: valueMeta + }, + 0 + ] + } + ] + }; + await createChart(); + + expect( + deserialize( + fixture.wrapper + .querySelectorAll('.ct-series-a .ct-point')[3] + .getAttributeNS(namespaces.ct, 'meta') + ) + ).toEqual(valueMeta); + + expect( + deserialize( + fixture.wrapper + .querySelector('.ct-series-b') + ?.getAttributeNS(namespaces.ct, 'meta') + ) + ).toEqual(seriesMeta); + + expect( + deserialize( + fixture.wrapper + .querySelectorAll('.ct-series-b .ct-point')[2] + .getAttributeNS(namespaces.ct, 'meta') + ) + ).toEqual(valueMeta); + }); + }); + + describe('Line charts with holes', () => { + it('should render correctly with Interpolation.none and holes everywhere', async () => { + data = { + labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], + series: [ + [ + NaN, + 15, + 0, + null, + 2, + 3, + 4, + undefined, + { value: 1, meta: 'meta data' }, + null + ] + ] + }; + options = { + lineSmooth: false + }; + + await createChart(); + + chart.on('draw', context => { + if (context.type === 'line') { + expect( + context.path.pathElements.map(pathElement => { + return { + command: pathElement.command, + data: pathElement.data + }; + }) + ).toEqual([ + { + command: 'M', + data: { + valueIndex: 1, + value: { x: undefined, y: 15 }, + meta: undefined + } + }, + { + command: 'L', + data: { + valueIndex: 2, + value: { x: undefined, y: 0 }, + meta: undefined + } + }, + { + command: 'M', + data: { + valueIndex: 4, + value: { x: undefined, y: 2 }, + meta: undefined + } + }, + { + command: 'L', + data: { + valueIndex: 5, + value: { x: undefined, y: 3 }, + meta: undefined + } + }, + { + command: 'L', + data: { + valueIndex: 6, + value: { x: undefined, y: 4 }, + meta: undefined + } + }, + { + command: 'M', + data: { + valueIndex: 8, + value: { x: undefined, y: 1 }, + meta: 'meta data' + } + } + ]); + } + }); + }); + + it('should render correctly with Interpolation.cardinal and holes everywhere', async () => { + data = { + labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], + series: [ + [ + NaN, + 15, + 0, + null, + 2, + 3, + 4, + undefined, + { value: 1, meta: 'meta data' }, + null + ] + ] + }; + options = { + lineSmooth: true + }; + + await createChart(); + + chart.on('draw', context => { + if (context.type === 'line') { + expect( + context.path.pathElements.map(pathElement => { + return { + command: pathElement.command, + data: pathElement.data + }; + }) + ).toEqual([ + { + command: 'M', + data: { + valueIndex: 1, + value: { x: undefined, y: 15 }, + meta: undefined + } + }, + // Cardinal should create Line path segment if only one connection + { + command: 'L', + data: { + valueIndex: 2, + value: { x: undefined, y: 0 }, + meta: undefined + } + }, + { + command: 'M', + data: { + valueIndex: 4, + value: { x: undefined, y: 2 }, + meta: undefined + } + }, + // Cardinal should create Curve path segment for 2 or more connections + { + command: 'C', + data: { + valueIndex: 5, + value: { x: undefined, y: 3 }, + meta: undefined + } + }, + { + command: 'C', + data: { + valueIndex: 6, + value: { x: undefined, y: 4 }, + meta: undefined + } + }, + { + command: 'M', + data: { + valueIndex: 8, + value: { x: undefined, y: 1 }, + meta: 'meta data' + } + } + ]); + } + }); + }); + + it('should render correctly with Interpolation.monotoneCubic and holes everywhere', async () => { + data = { + labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], + series: [ + [ + NaN, + 15, + 0, + null, + 2, + 3, + 4, + undefined, + { value: 1, meta: 'meta data' }, + null + ] + ] + }; + options = { + lineSmooth: Interpolation.monotoneCubic() + }; + + await createChart(); + + chart.on('draw', context => { + if (context.type === 'line') { + expect( + context.path.pathElements.map(pathElement => { + return { + command: pathElement.command, + data: pathElement.data + }; + }) + ).toEqual([ + { + command: 'M', + data: { + valueIndex: 1, + value: { x: undefined, y: 15 }, + meta: undefined + } + }, + // Monotone cubic should create Line path segment if only one connection + { + command: 'L', + data: { + valueIndex: 2, + value: { x: undefined, y: 0 }, + meta: undefined + } + }, + { + command: 'M', + data: { + valueIndex: 4, + value: { x: undefined, y: 2 }, + meta: undefined + } + }, + // Monotone cubic should create Curve path segment for 2 or more connections + { + command: 'C', + data: { + valueIndex: 5, + value: { x: undefined, y: 3 }, + meta: undefined + } + }, + { + command: 'C', + data: { + valueIndex: 6, + value: { x: undefined, y: 4 }, + meta: undefined + } + }, + { + command: 'M', + data: { + valueIndex: 8, + value: { x: undefined, y: 1 }, + meta: 'meta data' + } + } + ]); + } + }); + }); + + it('should render correctly with Interpolation.simple and holes everywhere', async () => { + data = { + labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], + series: [ + [ + NaN, + 15, + 0, + null, + 2, + 3, + 4, + undefined, + { value: 1, meta: 'meta data' }, + null + ] + ] + }; + options = { + lineSmooth: Interpolation.simple() + }; + + await createChart(); + + chart.on('draw', context => { + if (context.type === 'line') { + expect( + context.path.pathElements.map(pathElement => { + return { + command: pathElement.command, + data: pathElement.data + }; + }) + ).toEqual([ + { + command: 'M', + data: { + valueIndex: 1, + value: { x: undefined, y: 15 }, + meta: undefined + } + }, + { + command: 'C', + data: { + valueIndex: 2, + value: { x: undefined, y: 0 }, + meta: undefined + } + }, + { + command: 'M', + data: { + valueIndex: 4, + value: { x: undefined, y: 2 }, + meta: undefined + } + }, + { + command: 'C', + data: { + valueIndex: 5, + value: { x: undefined, y: 3 }, + meta: undefined + } + }, + { + command: 'C', + data: { + valueIndex: 6, + value: { x: undefined, y: 4 }, + meta: undefined + } + }, + { + command: 'M', + data: { + valueIndex: 8, + value: { x: undefined, y: 1 }, + meta: 'meta data' + } + } + ]); + } + }); + }); + + it('should render correctly with postponed Interpolation.step and holes everywhere', async () => { + data = { + labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], + series: [ + [ + NaN, + 15, + 0, + null, + 2, + 3, + 4, + undefined, + { value: 1, meta: 'meta data' }, + null + ] + ] + }; + options = { + lineSmooth: Interpolation.step() + }; + + await createChart(); + + chart.on('draw', context => { + if (context.type === 'line') { + expect( + context.path.pathElements.map(pathElement => { + return { + command: pathElement.command, + data: pathElement.data + }; + }) + ).toEqual([ + { + command: 'M', + data: { + valueIndex: 1, + value: { x: undefined, y: 15 }, + meta: undefined + } + }, + { + command: 'L', + data: { + valueIndex: 1, + value: { x: undefined, y: 15 }, + meta: undefined + } + }, + { + command: 'L', + data: { + valueIndex: 2, + value: { x: undefined, y: 0 }, + meta: undefined + } + }, + { + command: 'M', + data: { + valueIndex: 4, + value: { x: undefined, y: 2 }, + meta: undefined + } + }, + { + command: 'L', + data: { + valueIndex: 4, + value: { x: undefined, y: 2 }, + meta: undefined + } + }, + { + command: 'L', + data: { + valueIndex: 5, + value: { x: undefined, y: 3 }, + meta: undefined + } + }, + { + command: 'L', + data: { + valueIndex: 5, + value: { x: undefined, y: 3 }, + meta: undefined + } + }, + { + command: 'L', + data: { + valueIndex: 6, + value: { x: undefined, y: 4 }, + meta: undefined + } + }, + { + command: 'M', + data: { + valueIndex: 8, + value: { x: undefined, y: 1 }, + meta: 'meta data' + } + } + ]); + } + }); + }); + + it('should render correctly with preponed Interpolation.step and holes everywhere', async () => { + data = { + labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], + series: [ + [ + NaN, + 15, + 0, + null, + 2, + 3, + 4, + undefined, + { value: 1, meta: 'meta data' }, + null + ] + ] + }; + options = { + lineSmooth: Interpolation.step({ + postpone: false + }) + }; + + await createChart(); + + chart.on('draw', context => { + if (context.type === 'line') { + expect( + context.path.pathElements.map(pathElement => { + return { + command: pathElement.command, + data: pathElement.data + }; + }) + ).toEqual([ + { + command: 'M', + data: { + valueIndex: 1, + value: { x: undefined, y: 15 }, + meta: undefined + } + }, + { + command: 'L', + data: { + valueIndex: 2, + value: { x: undefined, y: 0 }, + meta: undefined + } + }, + { + command: 'L', + data: { + valueIndex: 2, + value: { x: undefined, y: 0 }, + meta: undefined + } + }, + { + command: 'M', + data: { + valueIndex: 4, + value: { x: undefined, y: 2 }, + meta: undefined + } + }, + { + command: 'L', + data: { + valueIndex: 5, + value: { x: undefined, y: 3 }, + meta: undefined + } + }, + { + command: 'L', + data: { + valueIndex: 5, + value: { x: undefined, y: 3 }, + meta: undefined + } + }, + { + command: 'L', + data: { + valueIndex: 6, + value: { x: undefined, y: 4 }, + meta: undefined + } + }, + { + command: 'L', + data: { + valueIndex: 6, + value: { x: undefined, y: 4 }, + meta: undefined + } + }, + { + command: 'M', + data: { + valueIndex: 8, + value: { x: undefined, y: 1 }, + meta: 'meta data' + } + } + ]); + } + }); + }); + }); + + describe('Single value data tests', () => { + beforeEach(() => { + data = { + labels: [1], + series: [[1]] + }; + }); + + it('should render without NaN values and points', async () => { + await createChart(); + + expect(document.querySelector('.ct-line')).toHaveAttribute( + 'd', + 'M50,15' + ); + expect(document.querySelector('.ct-point')).toHaveAttribute('x1', '50'); + expect(document.querySelector('.ct-point')).toHaveAttribute( + 'x2', + '50.01' + ); + }); + }); + + describe('Empty data tests', () => { + it('should render empty grid with no data', async () => { + await createChart(); + // Find at least one vertical grid line + expect( + document.querySelector('.ct-grids .ct-grid.ct-vertical') + ).toBeDefined(); + }); + + it('should render empty grid with only labels', async () => { + data = { + labels: [1, 2, 3, 4], + series: [] + }; + await createChart(); + + // Find at least one vertical grid line + expect( + document.querySelector('.ct-grids .ct-grid.ct-vertical') + ).toBeDefined(); + // Find exactly as many horizontal grid lines as labels were specified (Step Axis) + expect( + document.querySelectorAll('.ct-grids .ct-grid.ct-horizontal').length + ).toBe(data.labels?.length); + }); + + it('should generate labels and render empty grid with only series in data', async () => { + data = { + series: [ + [1, 2, 3, 4], + [2, 3, 4], + [3, 4] + ] + }; + await createChart(); + + // Find at least one vertical grid line + expect( + document.querySelector('.ct-grids .ct-grid.ct-vertical') + ).toBeDefined(); + // Should generate the labels using the largest series count + expect( + document.querySelectorAll('.ct-grids .ct-grid.ct-horizontal').length + ).toBe( + Math.max( + ...data.series.map(series => + Array.isArray(series) ? series.length : 0 + ) + ) + ); + }); + + it('should render empty grid with no data and specified high low', async () => { + data = { series: [] }; + options = { + width: 400, + height: 300, + high: 100, + low: -100 + }; + await createChart(); + + // Find first and last label + const labels = document.querySelectorAll( + '.ct-labels .ct-label.ct-vertical' + ); + const firstLabel = labels[0]; + const lastLabel = labels[labels.length - 1]; + + expect(firstLabel.textContent?.trim()).toBe('-100'); + expect(lastLabel.textContent?.trim()).toBe('100'); + }); + + it('should render empty grid with no data and reverseData option', async () => { + data = { series: [] }; + options = { + reverseData: true + }; + await createChart(); + + // Find at least one vertical grid line + expect( + document.querySelector('.ct-grids .ct-grid.ct-vertical') + ).toBeDefined(); + }); + }); + + describe('x1 and x2 attribute', () => { + it('should contain just a datapoint', async () => { + data = { + series: [[{ x: 1, y: 2 }]] + }; + options = { + fullWidth: true + }; + await createChart(); + + expect( + document.querySelector('.ct-point')?.getAttribute('x1') + ).not.toBe('NaN'); + expect( + document.querySelector('.ct-point')?.getAttribute('x2') + ).not.toBe('NaN'); + }); + }); + + it('should correct apply class names', async () => { + data = { + labels: ['A', 'B', 'C'], + series: [ + { + className: 'series-1', + data: [1, 2, 3] + }, + { + className: 'series-2', + data: [4, 5, 6] + } + ] + }; + options = { + reverseData: true + }; + await createChart(); + + const seriesElements = document.querySelectorAll('.ct-series'); + + expect(seriesElements[0]).toHaveClass('series-2'); + expect(seriesElements[0]).toContainHTML('ct:value="6"'); + + expect(seriesElements[1]).toHaveClass('series-1'); + expect(seriesElements[1]).toContainHTML('ct:value="3"'); + }); + }); +}); diff --git a/src/charts/LineChart/LineChart.stories.ts b/src/charts/LineChart/LineChart.stories.ts new file mode 100644 index 000000000..95fd79677 --- /dev/null +++ b/src/charts/LineChart/LineChart.stories.ts @@ -0,0 +1,664 @@ +import 'chartist-dev/styles'; +import faker from 'faker'; +import { + LineChart, + AutoScaleAxis, + Interpolation, + Svg, + easings +} from 'chartist-dev'; + +export default { + title: 'LineChart', + argTypes: {} +}; + +export function Default() { + const root = document.createElement('div'); + + new LineChart( + root, + { + labels: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'], + series: [ + [12, 9, 7, 8, 5], + [2, 1, 3.5, 7, 3], + [1, 3, 4, 5, 6] + ] + }, + { + fullWidth: true, + chartPadding: { + right: 40 + } + } + ); + + return root; +} + +export function AutoScale() { + const root = document.createElement('div'); + + new LineChart( + root, + { + series: [ + [ + { x: 1, y: 1 }, + { x: 3, y: 5 } + ] + ] + }, + { + axisX: { + type: AutoScaleAxis, + onlyInteger: true + }, + axisY: { + type: AutoScaleAxis, + onlyInteger: true + } + } + ); + + return root; +} + +export function Labels() { + const root = document.createElement('div'); + + new LineChart( + root, + { + labels: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu'], + series: [[5, 2, 4, 2, 0]] + }, + {} + ); + + return root; +} + +export function MultiSeries() { + const root = document.createElement('div'); + + new LineChart( + root, + { + labels: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'], + series: [ + [5, 2, 4, 2, 0], + [5, 2, 2, 0] + ] + }, + {} + ); + + return root; +} + +export function Holes() { + const root = document.createElement('div'); + + new LineChart( + root, + { + labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], + series: [ + [5, 5, 10, 8, 7, 5, 4, null, null, null, 10, 10, 7, 8, 6, 9], + [ + 10, + 15, + null, + 12, + null, + 10, + 12, + 15, + null, + null, + 12, + null, + 14, + null, + null, + null + ], + [null, null, null, null, 3, 4, 1, 3, 4, 6, 7, 9, 5, null, null, null], + [ + { x: 3, y: 3 }, + { x: 4, y: 3 }, + { x: 5, y: undefined }, + { x: 6, y: 4 }, + { x: 7, y: null }, + { x: 8, y: 4 }, + { x: 9, y: 4 } + ] + ] + }, + { + fullWidth: true, + chartPadding: { + right: 10 + }, + low: 0 + } + ); + + return root; +} + +export function FilledHoles() { + const root = document.createElement('div'); + + new LineChart( + root, + { + labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], + series: [ + [5, 5, 10, 8, 7, 5, 4, null, null, null, 10, 10, 7, 8, 6, 9], + [ + 10, + 15, + null, + 12, + null, + 10, + 12, + 15, + null, + null, + 12, + null, + 14, + null, + null, + null + ], + [null, null, null, null, 3, 4, 1, 3, 4, 6, 7, 9, 5, null, null, null], + [ + { x: 3, y: 3 }, + { x: 4, y: 3 }, + { x: 5, y: undefined }, + { x: 6, y: 4 }, + { x: 7, y: null }, + { x: 8, y: 4 }, + { x: 9, y: 4 } + ] + ] + }, + { + fullWidth: true, + chartPadding: { + right: 10 + }, + lineSmooth: Interpolation.cardinal({ + fillHoles: true + }), + low: 0 + } + ); + + return root; +} + +export function OnlyWholeNumbers() { + const root = document.createElement('div'); + + new LineChart( + root, + { + labels: [1, 2, 3, 4, 5, 6, 7, 8], + series: [ + [1, 2, 3, 1, -2, 0, 1, 0], + [-2, -1, -2, -1, -3, -1, -2, -1], + [0, 0, 0, 1, 2, 3, 2, 1], + [3, 2, 1, 0.5, 1, 0, -1, -3] + ] + }, + { + high: 3, + low: -3, + fullWidth: true, + // As this is axis specific we need to tell Chartist to use whole numbers only on the concerned axis + axisY: { + onlyInteger: true, + offset: 20 + } + } + ); + + return root; +} + +export function NoInterpolationWithHoles() { + const root = document.createElement('div'); + + new LineChart( + root, + { + labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], + series: [[NaN, 15, 0, null, 2, 3, 4, undefined, 1, null]] + }, + { + lineSmooth: false + } + ); + + return root; +} + +export function CardinalInterpolationWithHoles() { + const root = document.createElement('div'); + + new LineChart( + root, + { + labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], + series: [[NaN, 15, 0, null, 2, 3, 4, undefined, 1, null]] + }, + { + lineSmooth: true + } + ); + + return root; +} + +export function MonotoneCubicInterpolationWithHoles() { + const root = document.createElement('div'); + + new LineChart( + root, + { + labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], + series: [[NaN, 15, 0, null, 2, 3, 4, undefined, 1, null]] + }, + { + lineSmooth: Interpolation.monotoneCubic() + } + ); + + return root; +} + +export function SimpleInterpolationWithHoles() { + const root = document.createElement('div'); + + new LineChart( + root, + { + labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], + series: [[NaN, 15, 0, null, 2, 3, 4, undefined, 1, null]] + }, + { + lineSmooth: Interpolation.simple() + } + ); + + return root; +} + +export function StepInterpolationWithHoles() { + const root = document.createElement('div'); + + new LineChart( + root, + { + labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], + series: [[NaN, 15, 0, null, 2, 3, 4, undefined, 1, null]] + }, + { + lineSmooth: Interpolation.step() + } + ); + + return root; +} + +export function StepNoPostponeInterpolationWithHoles() { + const root = document.createElement('div'); + + new LineChart( + root, + { + labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], + series: [[NaN, 15, 0, null, 2, 3, 4, undefined, 1, null]] + }, + { + lineSmooth: Interpolation.step({ + postpone: false + }) + } + ); + + return root; +} + +export function SeriesOverrides() { + const root = document.createElement('div'); + + new LineChart( + root, + { + labels: ['1', '2', '3', '4', '5', '6', '7', '8'], + // Naming the series with the series object array notation + series: [ + { + name: 'series-1', + data: [5, 2, -4, 2, 0, -2, 5, -3] + }, + { + name: 'series-2', + data: [4, 3, 5, 3, 1, 3, 6, 4] + }, + { + name: 'series-3', + data: [2, 4, 3, 1, 4, 5, 3, 2] + } + ] + }, + { + fullWidth: true, + // Within the series options you can use the series names + // to specify configuration that will only be used for the + // specific series. + series: { + 'series-1': { + lineSmooth: Interpolation.step() + }, + 'series-2': { + lineSmooth: Interpolation.simple(), + showArea: true + }, + 'series-3': { + showPoint: false + } + } + }, + [ + // You can even use responsive configuration overrides to + // customize your series configuration even further! + [ + 'screen and (max-width: 320px)', + { + series: { + 'series-1': { + lineSmooth: Interpolation.none() + }, + 'series-2': { + lineSmooth: Interpolation.none(), + showArea: false + }, + 'series-3': { + lineSmooth: Interpolation.none(), + showPoint: true + } + } + } + ] + ] + ); + + return root; +} + +export function ReverseData() { + const root = document.createElement('div'); + + new LineChart( + root, + { + series: [ + [ + { x: 1, y: 1 }, + { x: 3, y: 5 } + ] + ] + }, + { + reverseData: true + } + ); + + return root; +} + +export function FullWidth() { + const root = document.createElement('div'); + + new LineChart( + root, + { + series: [ + [ + { x: 1, y: 1 }, + { x: 3, y: 5 } + ] + ] + }, + { + fullWidth: true + } + ); + + return root; +} + +export function Scatter() { + const root = document.createElement('div'); + const data = Array.from({ length: 52 }).reduce<{ + labels: number[]; + series: number[][]; + }>( + (data, _, index) => { + data.labels.push(index + 1); + data.series.forEach(series => { + series.push(faker.datatype.number({ min: 0, max: 100 })); + }); + + return data; + }, + { + labels: [], + series: Array.from({ length: 4 }, () => []) + } + ); + + new LineChart( + root, + data, + { + showLine: false, + axisX: { + labelInterpolationFnc(value, index) { + return index % 13 === 0 ? 'W' + value : null; + } + } + }, + [ + [ + 'screen and (min-width: 640px)', + { + axisX: { + labelInterpolationFnc(value, index) { + return index % 4 === 0 ? 'W' + value : null; + } + } + } + ] + ] + ); + + return root; +} + +export function Area() { + const root = document.createElement('div'); + + new LineChart( + root, + { + labels: [1, 2, 3, 4, 5, 6, 7, 8], + series: [[5, 9, 7, 8, 5, 3, 5, 4]] + }, + { + low: 0, + showArea: true + } + ); + + return root; +} + +export function BiPolarArea() { + const root = document.createElement('div'); + + new LineChart( + root, + { + labels: [1, 2, 3, 4, 5, 6, 7, 8], + series: [ + [1, 2, 3, 1, -2, 0, 1, 0], + [-2, -1, -2, -1, -2.5, -1, -2, -1], + [0, 0, 0, 1, 2, 2.5, 2, 1], + [2.5, 2, 1, 0.5, 1, 0.5, -1, -2.5] + ] + }, + { + high: 3, + low: -3, + showArea: true, + showLine: false, + showPoint: false, + fullWidth: true, + axisX: { + showLabel: false, + showGrid: false + } + } + ); + + return root; +} + +export function CustomPoints() { + const root = document.createElement('div'); + + new LineChart(root, { + labels: [1, 2, 3, 4, 5], + series: [[12, 9, 7, 8, 5]] + }).on('draw', data => { + // If the draw event was triggered from drawing a point on the line chart + if (data.type === 'point') { + // We are creating a new path SVG element that draws a triangle around the point coordinates + const triangle = new Svg( + 'path', + { + d: [ + 'M', + data.x, + data.y - 15, + 'L', + data.x - 15, + data.y + 8, + 'L', + data.x + 15, + data.y + 8, + 'z' + ].join(' '), + style: 'fill-opacity: 1' + }, + 'ct-area' + ); + + // With data.element we get the Chartist SVG wrapper and we can replace the original point drawn by Chartist with our newly created triangle + data.element.replace(triangle); + } + }); + + return root; +} + +export function PathAnimation() { + const root = document.createElement('div'); + + new LineChart( + root, + { + labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], + series: [ + [1, 5, 2, 5, 4, 3], + [2, 3, 4, 8, 1, 2], + [5, 4, 3, 2, 1, 0.5] + ] + }, + { + low: 0, + showArea: true, + showPoint: false, + fullWidth: true + } + ).on('draw', data => { + if ( + !process.env.STORYBOOK_STORYSHOTS && + (data.type === 'line' || data.type === 'area') + ) { + data.element.animate({ + d: { + begin: 2000 * data.index, + dur: 2000, + from: data.path + .clone() + .scale(1, 0) + .translate(0, data.chartRect.height()) + .stringify(), + to: data.path.clone().stringify(), + easing: easings.easeOutQuint + } + }); + } + }); + + return root; +} + +export function ViewBox() { + const root = document.createElement('div'); + + new LineChart( + root, + { + labels: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'], + series: [ + [12, 9, 7, 8, 5], + [2, 1, 3.5, 7, 3], + [1, 3, 4, 5, 6] + ] + }, + { + fullWidth: true, + chartPadding: { + right: 40 + }, + viewBox: { + width: 800, + height: 400 + } + }, + [ + [ + 'screen and (max-width: 575px)', + { + viewBox: { + width: 400, + height: 300 + } + } + ] + ] + ); + + return root; +} diff --git a/src/charts/LineChart/LineChart.ts b/src/charts/LineChart/LineChart.ts new file mode 100644 index 000000000..ce0bd80d0 --- /dev/null +++ b/src/charts/LineChart/LineChart.ts @@ -0,0 +1,574 @@ +import type { Axis } from '../../axes'; +import type { + LineChartData, + LineChartOptions, + LineChartOptionsWithDefaults, + LineChartCreatedEvent, + PointDrawEvent, + LineDrawEvent, + AreaDrawEvent, + LineChartEventsTypes +} from './LineChart.types'; +import type { + SegmentData, + Series, + SeriesObject, + ResponsiveOptions +} from '../../core'; +import { + alphaNumerate, + normalizeData, + serialize, + getMetaData, + createSvg, + createChartRect, + createGridBackground +} from '../../core'; +import { isNumeric, noop, extend, safeHasProperty, each } from '../../utils'; +import { StepAxis, AutoScaleAxis, axisUnits } from '../../axes'; +import { monotoneCubic, none } from '../../interpolation'; +import { BaseChart } from './../BaseChart'; + +export function getSeriesOption< + T extends keyof Omit +>( + series: Series | SeriesObject, + options: LineChartOptionsWithDefaults, + key: T +) { + if ( + safeHasProperty(series, 'name') && + series.name && + options.series?.[series.name] + ) { + const seriesOptions = options?.series[series.name]; + const value = seriesOptions[key]; + const result = value === undefined ? options[key] : value; + + return result as LineChartOptionsWithDefaults[T]; + } else { + return options[key]; + } +} + +/** + * Default options in line charts. Expand the code view to see a detailed list of options with comments. + */ +const defaultOptions = { + // Options for X-Axis + axisX: { + // The offset of the labels to the chart area + offset: 30, + // Position where labels are placed. Can be set to `start` or `end` where `start` is equivalent to left or top on vertical axis and `end` is equivalent to right or bottom on horizontal axis. + position: 'end' as const, + // Allows you to correct label positioning on this axis by positive or negative x and y offset. + labelOffset: { + x: 0, + y: 0 + }, + // If labels should be shown or not + showLabel: true, + // If the axis grid should be drawn or not + showGrid: true, + // Interpolation function that allows you to intercept the value from the axis label + labelInterpolationFnc: noop, + // Set the axis type to be used to project values on this axis. If not defined, Chartist.StepAxis will be used for the X-Axis, where the ticks option will be set to the labels in the data and the stretch option will be set to the global fullWidth option. This type can be changed to any axis constructor available (e.g. Chartist.FixedScaleAxis), where all axis options should be present here. + type: undefined + }, + // Options for Y-Axis + axisY: { + // The offset of the labels to the chart area + offset: 40, + // Position where labels are placed. Can be set to `start` or `end` where `start` is equivalent to left or top on vertical axis and `end` is equivalent to right or bottom on horizontal axis. + position: 'start' as const, + // Allows you to correct label positioning on this axis by positive or negative x and y offset. + labelOffset: { + x: 0, + y: 0 + }, + // If labels should be shown or not + showLabel: true, + // If the axis grid should be drawn or not + showGrid: true, + // Interpolation function that allows you to intercept the value from the axis label + labelInterpolationFnc: noop, + // Set the axis type to be used to project values on this axis. If not defined, Chartist.AutoScaleAxis will be used for the Y-Axis, where the high and low options will be set to the global high and low options. This type can be changed to any axis constructor available (e.g. Chartist.FixedScaleAxis), where all axis options should be present here. + type: undefined, + // This value specifies the minimum height in pixel of the scale steps + scaleMinSpace: 20, + // Use only integer values (whole numbers) for the scale steps + onlyInteger: false + }, + // Specify a fixed width for the chart as a string (i.e. '100px' or '50%') + width: undefined, + // Specify a fixed height for the chart as a string (i.e. '100px' or '50%') + height: undefined, + // If the line should be drawn or not + showLine: true, + // If dots should be drawn or not + showPoint: true, + // If the line chart should draw an area + showArea: false, + // The base for the area chart that will be used to close the area shape (is normally 0) + areaBase: 0, + // Specify if the lines should be smoothed. This value can be true or false where true will result in smoothing using the default smoothing interpolation function Chartist.Interpolation.cardinal and false results in Chartist.Interpolation.none. You can also choose other smoothing / interpolation functions available in the Chartist.Interpolation module, or write your own interpolation function. Check the examples for a brief description. + lineSmooth: true, + // If the line chart should add a background fill to the .ct-grids group. + showGridBackground: false, + // Overriding the natural low of the chart allows you to zoom in or limit the charts lowest displayed value + low: undefined, + // Overriding the natural high of the chart allows you to zoom in or limit the charts highest displayed value + high: undefined, + // Padding of the chart drawing area to the container element and labels as a number or padding object {top: 5, right: 5, bottom: 5, left: 5} + chartPadding: { + top: 15, + right: 15, + bottom: 5, + left: 10 + }, + // When set to true, the last grid line on the x-axis is not drawn and the chart elements will expand to the full available width of the chart. For the last label to be drawn correctly you might need to add chart padding or offset the last label with a draw event handler. + fullWidth: false, + // If true the whole data is reversed including labels, the series order as well as the whole series data arrays. + reverseData: false, + // Override the class names that get used to generate the SVG structure of the chart + classNames: { + chart: 'ct-chart-line', + label: 'ct-label', + labelGroup: 'ct-labels', + series: 'ct-series', + line: 'ct-line', + point: 'ct-point', + area: 'ct-area', + grid: 'ct-grid', + gridGroup: 'ct-grids', + gridBackground: 'ct-grid-background', + vertical: 'ct-vertical', + horizontal: 'ct-horizontal', + start: 'ct-start', + end: 'ct-end' + } +}; + +export class LineChart extends BaseChart { + /** + * This method creates a new line chart. + * @param query A selector query string or directly a DOM element + * @param data The data object that needs to consist of a labels and a series array + * @param options The options object with options that override the default options. Check the examples for a detailed list. + * @param responsiveOptions Specify an array of responsive option arrays which are a media query and options object pair => [[mediaQueryString, optionsObject],[more...]] + * @return An object which exposes the API for the created chart + * + * @example + * ```ts + * // Create a simple line chart + * const data = { + * // A labels array that can contain any sort of values + * labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'], + * // Our series array that contains series objects or in this case series data arrays + * series: [ + * [5, 2, 4, 2, 0] + * ] + * }; + * + * // As options we currently only set a static size of 300x200 px + * const options = { + * width: '300px', + * height: '200px' + * }; + * + * // In the global name space Chartist we call the Line function to initialize a line chart. As a first parameter we pass in a selector where we would like to get our chart created. Second parameter is the actual data object and as a third parameter we pass in our options + * new LineChart('.ct-chart', data, options); + * ``` + * + * @example + * ```ts + * // Use specific interpolation function with configuration from the Chartist.Interpolation module + * + * const chart = new LineChart('.ct-chart', { + * labels: [1, 2, 3, 4, 5], + * series: [ + * [1, 1, 8, 1, 7] + * ] + * }, { + * lineSmooth: Chartist.Interpolation.cardinal({ + * tension: 0.2 + * }) + * }); + * ``` + * + * @example + * ```ts + * // Create a line chart with responsive options + * + * const data = { + * // A labels array that can contain any sort of values + * labels: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'], + * // Our series array that contains series objects or in this case series data arrays + * series: [ + * [5, 2, 4, 2, 0] + * ] + * }; + * + * // In addition to the regular options we specify responsive option overrides that will override the default configutation based on the matching media queries. + * const responsiveOptions = [ + * ['screen and (min-width: 641px) and (max-width: 1024px)', { + * showPoint: false, + * axisX: { + * labelInterpolationFnc: function(value) { + * // Will return Mon, Tue, Wed etc. on medium screens + * return value.slice(0, 3); + * } + * } + * }], + * ['screen and (max-width: 640px)', { + * showLine: false, + * axisX: { + * labelInterpolationFnc: function(value) { + * // Will return M, T, W etc. on small screens + * return value[0]; + * } + * } + * }] + * ]; + * + * new LineChart('.ct-chart', data, null, responsiveOptions); + * ``` + */ + constructor( + query: string | Element | null, + protected override data: LineChartData, + options?: LineChartOptions, + responsiveOptions?: ResponsiveOptions + ) { + super( + query, + data, + defaultOptions, + extend({}, defaultOptions, options), + responsiveOptions + ); + } + + /** + * Creates a new chart + */ + createChart(options: LineChartOptionsWithDefaults) { + const { data } = this; + const normalizedData = normalizeData(data, options.reverseData, true); + + // Create new svg object + const svg = createSvg( + this.container, + options.width, + options.height, + options.classNames.chart, + options.viewBox + ); + + this.svg = svg; + + // Create groups for labels, grid and series + const gridGroup = svg.elem('g').addClass(options.classNames.gridGroup); + const seriesGroup = svg.elem('g'); + const labelGroup = svg.elem('g').addClass(options.classNames.labelGroup); + + const chartRect = createChartRect(svg, options); + let axisX: Axis; + let axisY: Axis; + + if (options.axisX.type === undefined) { + axisX = new StepAxis(axisUnits.x, normalizedData.series, chartRect, { + ...options.axisX, + ticks: normalizedData.labels, + stretch: options.fullWidth + }); + } else { + // eslint-disable-next-line new-cap + axisX = new options.axisX.type( + axisUnits.x, + normalizedData.series, + chartRect, + options.axisX + ); + } + + if (options.axisY.type === undefined) { + axisY = new AutoScaleAxis(axisUnits.y, normalizedData.series, chartRect, { + ...options.axisY, + high: isNumeric(options.high) ? options.high : options.axisY.high, + low: isNumeric(options.low) ? options.low : options.axisY.low + }); + } else { + // eslint-disable-next-line new-cap + axisY = new options.axisY.type( + axisUnits.y, + normalizedData.series, + chartRect, + options.axisY + ); + } + + axisX.createGridAndLabels( + gridGroup, + labelGroup, + options, + this.eventEmitter + ); + axisY.createGridAndLabels( + gridGroup, + labelGroup, + options, + this.eventEmitter + ); + + if (options.showGridBackground) { + createGridBackground( + gridGroup, + chartRect, + options.classNames.gridBackground, + this.eventEmitter + ); + } + + // Draw the series + each( + data.series, + (series, seriesIndex) => { + const seriesElement = seriesGroup.elem('g'); + const seriesName = safeHasProperty(series, 'name') && series.name; + const seriesClassName = + safeHasProperty(series, 'className') && series.className; + const seriesMeta = safeHasProperty(series, 'meta') + ? series.meta + : undefined; + + // Write attributes to series group element. If series name or meta is undefined the attributes will not be written + if (seriesName) { + seriesElement.attr({ + 'ct:series-name': seriesName + }); + } + + if (seriesMeta) { + seriesElement.attr({ + 'ct:meta': serialize(seriesMeta) + }); + } + + // Use series class from series data or if not set generate one + seriesElement.addClass( + [ + options.classNames.series, + seriesClassName || + `${options.classNames.series}-${alphaNumerate(seriesIndex)}` + ].join(' ') + ); + + const pathCoordinates: number[] = []; + const pathData: SegmentData[] = []; + + normalizedData.series[seriesIndex].forEach((value, valueIndex) => { + const p = { + x: + chartRect.x1 + + axisX.projectValue( + value, + valueIndex, + normalizedData.series[seriesIndex] + ), + y: + chartRect.y1 - + axisY.projectValue( + value, + valueIndex, + normalizedData.series[seriesIndex] + ) + }; + pathCoordinates.push(p.x, p.y); + pathData.push({ + value, + valueIndex, + meta: getMetaData(series, valueIndex) + }); + }); + + const seriesOptions = { + lineSmooth: getSeriesOption(series, options, 'lineSmooth'), + showPoint: getSeriesOption(series, options, 'showPoint'), + showLine: getSeriesOption(series, options, 'showLine'), + showArea: getSeriesOption(series, options, 'showArea'), + areaBase: getSeriesOption(series, options, 'areaBase') + }; + + let smoothing; + if (typeof seriesOptions.lineSmooth === 'function') { + smoothing = seriesOptions.lineSmooth; + } else { + smoothing = seriesOptions.lineSmooth ? monotoneCubic() : none(); + } + + // Interpolating path where pathData will be used to annotate each path element so we can trace back the original + // index, value and meta data + const path = smoothing(pathCoordinates, pathData); + + // If we should show points we need to create them now to avoid secondary loop + // Points are drawn from the pathElements returned by the interpolation function + // Small offset for Firefox to render squares correctly + if (seriesOptions.showPoint) { + path.pathElements.forEach(pathElement => { + const { data: pathElementData } = pathElement; + const point = seriesElement.elem( + 'line', + { + x1: pathElement.x, + y1: pathElement.y, + x2: pathElement.x + 0.01, + y2: pathElement.y + }, + options.classNames.point + ); + + if (pathElementData) { + let x: number | undefined; + let y: number | undefined; + + if (safeHasProperty(pathElementData.value, 'x')) { + x = pathElementData.value.x; + } + + if (safeHasProperty(pathElementData.value, 'y')) { + y = pathElementData.value.y; + } + + point.attr({ + 'ct:value': [x, y].filter(isNumeric).join(','), + 'ct:meta': serialize(pathElementData.meta) + }); + } + + this.eventEmitter.emit('draw', { + type: 'point', + value: pathElementData?.value, + index: pathElementData?.valueIndex || 0, + meta: pathElementData?.meta, + series, + seriesIndex, + axisX, + axisY, + group: seriesElement, + element: point, + x: pathElement.x, + y: pathElement.y, + chartRect + }); + }); + } + + if (seriesOptions.showLine) { + const line = seriesElement.elem( + 'path', + { + d: path.stringify() + }, + options.classNames.line, + true + ); + + this.eventEmitter.emit('draw', { + type: 'line', + values: normalizedData.series[seriesIndex], + path: path.clone(), + chartRect, + // TODO: Remove redundant + index: seriesIndex, + series, + seriesIndex, + meta: seriesMeta, + axisX, + axisY, + group: seriesElement, + element: line + }); + } + + // Area currently only works with axes that support a range! + if (seriesOptions.showArea && axisY.range) { + // If areaBase is outside the chart area (< min or > max) we need to set it respectively so that + // the area is not drawn outside the chart area. + const areaBase = Math.max( + Math.min(seriesOptions.areaBase, axisY.range.max), + axisY.range.min + ); + + // We project the areaBase value into screen coordinates + const areaBaseProjected = chartRect.y1 - axisY.projectValue(areaBase); + + // In order to form the area we'll first split the path by move commands so we can chunk it up into segments + path + .splitByCommand('M') + // We filter only "solid" segments that contain more than one point. Otherwise there's no need for an area + .filter(pathSegment => pathSegment.pathElements.length > 1) + .map(solidPathSegments => { + // Receiving the filtered solid path segments we can now convert those segments into fill areas + const firstElement = solidPathSegments.pathElements[0]; + const lastElement = + solidPathSegments.pathElements[ + solidPathSegments.pathElements.length - 1 + ]; + + // Cloning the solid path segment with closing option and removing the first move command from the clone + // We then insert a new move that should start at the area base and draw a straight line up or down + // at the end of the path we add an additional straight line to the projected area base value + // As the closing option is set our path will be automatically closed + return solidPathSegments + .clone(true) + .position(0) + .remove(1) + .move(firstElement.x, areaBaseProjected) + .line(firstElement.x, firstElement.y) + .position(solidPathSegments.pathElements.length + 1) + .line(lastElement.x, areaBaseProjected); + }) + .forEach(areaPath => { + // For each of our newly created area paths, we'll now create path elements by stringifying our path objects + // and adding the created DOM elements to the correct series group + const area = seriesElement.elem( + 'path', + { + d: areaPath.stringify() + }, + options.classNames.area, + true + ); + + // Emit an event for each area that was drawn + this.eventEmitter.emit('draw', { + type: 'area', + values: normalizedData.series[seriesIndex], + path: areaPath.clone(), + series, + seriesIndex, + axisX, + axisY, + chartRect, + // TODO: Remove redundant + index: seriesIndex, + group: seriesElement, + element: area, + meta: seriesMeta + }); + }); + } + }, + options.reverseData + ); + + this.eventEmitter.emit('created', { + chartRect, + axisX, + axisY, + svg, + options + }); + } +} diff --git a/src/charts/LineChart/LineChart.types.ts b/src/charts/LineChart/LineChart.types.ts new file mode 100644 index 000000000..86231cea8 --- /dev/null +++ b/src/charts/LineChart/LineChart.types.ts @@ -0,0 +1,145 @@ +import type { + Options, + AxisOptions, + Data, + Series, + SeriesObject, + SegmentData, + CreatedEvent, + DrawEvent, + NormalizedSeriesValue, + NormalizedSeries, + AxesDrawEvent +} from '../../core'; +import type { SvgPath } from '../../svg'; +import type { RequiredKeys } from '../../utils'; +import type { BaseChartEventsTypes } from '../types'; + +export type LineInterpolation = ( + pathCoordinates: number[], + valueData: SegmentData[] +) => SvgPath; + +export type LineChartData = Data<(Series | SeriesObject)[]>; + +export interface LineChartOptions< + TXAxisOptions = AxisOptions, + TYAxisOptions = TXAxisOptions +> extends Options { + /** + * Override the class names that get used to generate the SVG structure of the chart + */ + classNames?: { + chart?: string; + label?: string; + labelGroup?: string; + series?: string; + line?: string; + point?: string; + area?: string; + grid?: string; + gridGroup?: string; + gridBackground?: string; + vertical?: string; + horizontal?: string; + start?: string; + end?: string; + }; + /** + * If the line should be drawn or not + */ + showLine?: boolean; + /** + * If dots should be drawn or not + */ + showPoint?: boolean; + /** + * If the line chart should draw an area + */ + showArea?: boolean; + /** + * The base for the area chart that will be used to close the area shape (is normally 0) + */ + areaBase?: number; + /** + * Specify if the lines should be smoothed. + * This value can be true or false where true will result in smoothing using the default smoothing interpolation function Chartist.Interpolation.cardinal and false results in Chartist.Interpolation.none. + * You can also choose other smoothing / interpolation functions available in the Chartist.Interpolation module, or write your own interpolation function. + * Check the examples for a brief description. + */ + lineSmooth?: boolean | LineInterpolation; + /** + * If the line chart should add a background fill to the .ct-grids group. + */ + showGridBackground?: boolean; + /** + * When set to true, the last grid line on the x-axis is not drawn and the chart elements will expand to the full available width of the chart. For the last label to be drawn correctly you might need to add chart padding or offset the last label with a draw event handler. + */ + fullWidth?: boolean; + /** + * If true the whole data is reversed including labels, the series order as well as the whole series data arrays. + */ + reverseData?: boolean; + series?: Record< + string, + Omit, 'series'> + >; +} + +export type LineChartOptionsWithDefaults = RequiredKeys< + LineChartOptions< + RequiredKeys< + AxisOptions, + | 'offset' + | 'position' + | 'labelOffset' + | 'showLabel' + | 'showGrid' + | 'labelInterpolationFnc' + >, + RequiredKeys< + AxisOptions, + | 'offset' + | 'position' + | 'labelOffset' + | 'showLabel' + | 'showGrid' + | 'labelInterpolationFnc' + | 'scaleMinSpace' + > + >, + | 'showLine' + | 'showPoint' + | 'areaBase' + | 'lineSmooth' + | 'chartPadding' + | 'axisX' + | 'axisY', + 'classNames' +>; + +export type LineChartCreatedEvent = CreatedEvent; + +export interface PointDrawEvent extends DrawEvent { + type: 'point'; + value: NormalizedSeriesValue; + x: number; + y: number; +} + +export interface LineDrawEvent extends DrawEvent { + type: 'line'; + values: NormalizedSeries; + path: SvgPath; +} + +export interface AreaDrawEvent extends DrawEvent { + type: 'area'; + values: NormalizedSeries; + path: SvgPath; +} + +export type LineChartEventsTypes = BaseChartEventsTypes< + LineChartCreatedEvent, + AxesDrawEvent | PointDrawEvent | LineDrawEvent | AreaDrawEvent +>; diff --git a/src/charts/LineChart/index.ts b/src/charts/LineChart/index.ts new file mode 100644 index 000000000..ec51482d2 --- /dev/null +++ b/src/charts/LineChart/index.ts @@ -0,0 +1,2 @@ +export * from './LineChart'; +export * from './LineChart.types'; diff --git a/src/charts/PieChart/PieChart.spec.ts b/src/charts/PieChart/PieChart.spec.ts new file mode 100644 index 000000000..8ec742bc5 --- /dev/null +++ b/src/charts/PieChart/PieChart.spec.ts @@ -0,0 +1,472 @@ +import { namespaces, deserialize } from '../../core'; +import { PieChartOptions, PieChartData, PieChart } from '.'; +import { + Fixture, + addMockWrapper, + destroyMockDom, + mockDom +} from '../../../test/mock/dom'; + +describe('Charts', () => { + describe('PieChart', () => { + let fixture: Fixture; + let chart: PieChart; + let options: PieChartOptions; + let data: PieChartData; + + function createChart() { + return new Promise(resolve => { + fixture = addMockWrapper( + '
' + ); + const { wrapper } = fixture; + chart = new PieChart( + wrapper.querySelector('.ct-chart'), + data, + options + ).on('created', () => { + resolve(); + chart.off('created'); + }); + }); + } + + beforeEach(() => { + mockDom(); + }); + afterEach(() => { + destroyMockDom(); + data = { series: [] }; + options = {}; + }); + + describe('Meta data tests', () => { + it('should render meta data correctly on slice with mixed value array', async () => { + const fixture = addMockWrapper( + '
' + ); + const meta = { + test: 'Serialized Test' + }; + + const data = { + labels: ['A', 'B', 'C'], + series: [ + 5, + { + value: 8, + meta: meta + }, + 1 + ] + }; + + const chartContainer = fixture.wrapper.querySelector('.ct-chart'); + const chart = new PieChart(chartContainer, data); + + chart.on('created', () => { + const metaAttribute = chartContainer + ?.querySelectorAll('.ct-slice-pie')[1] + .getAttributeNS(namespaces.ct, 'meta'); + expect(deserialize(metaAttribute)).toEqual(meta); + chart.off('created'); + }); + }); + }); + + describe('Simple Pie Chart', () => { + const num = '\\d+(\\.\\d*)?'; + const sum = (a: number, b: number) => a + b; + + beforeEach(() => { + const series = [5, 3, 4]; + + data = { + series + }; + options = { + width: 100, + height: 100, + chartPadding: 10, + labelInterpolationFnc: value => + `${Math.round((Number(value) / series.reduce(sum)) * 100)}%` + }; + }); + + it('should render three slices', async () => { + await createChart(); + + expect(fixture.wrapper.querySelectorAll('.ct-slice-pie').length).toBe( + 3 + ); + }); + + it('should set value attribute', async () => { + await createChart(); + + const slices = fixture.wrapper.querySelectorAll('.ct-slice-pie'); + expect(slices[0].getAttributeNS(namespaces.ct, 'value')).toBe('5'); + expect(slices[1].getAttributeNS(namespaces.ct, 'value')).toBe('3'); + expect(slices[2].getAttributeNS(namespaces.ct, 'value')).toBe('4'); + }); + + it('should create slice path', async () => { + await createChart(); + + Array.from(fixture.wrapper.querySelectorAll('.ct-slice-pie')).forEach( + element => { + const pattern = new RegExp( + `M${num},${num}A40,40,0,0,0,${num},${num}L50,50Z$` + ); + const path = element.getAttribute('d'); + expect(path).toMatch(pattern); + } + ); + }); + + it('should add labels', async () => { + await createChart(); + + const labels = fixture.wrapper.querySelectorAll('.ct-label'); + expect(labels[0]).toHaveTextContent('42%'); + expect(labels[1]).toHaveTextContent('25%'); + expect(labels[2]).toHaveTextContent('33%'); + }); + + it('should overlap slices', async () => { + data = { + series: [1, 1] + }; + await createChart(); + + const [slice1, slice2] = Array.from( + fixture.wrapper.querySelectorAll('.ct-slice-pie') + ); + + expect(slice1).toHaveAttribute( + 'd', + expect.stringMatching(/^M50,90A40,40,0,0,0,50,10L50,50Z/) + ); + expect(slice2).toHaveAttribute( + 'd', + expect.stringMatching(/^M50,10A40,40,0,0,0,50.\d+,90L50,50Z/) + ); + }); + + it('should set large arc sweep flag', async () => { + data = { + series: [1, 2] + }; + await createChart(); + + const slice = fixture.wrapper.querySelectorAll('.ct-slice-pie')[1]; + expect(slice).toHaveAttribute( + 'd', + expect.stringMatching(/^M50,10A40,40,0,1,0/) + ); + }); + + it('should draw complete circle with gap', async () => { + data = { + series: [1] + }; + await createChart(); + + const slice = fixture.wrapper.querySelectorAll('.ct-slice-pie')[0]; + expect(slice).toHaveAttribute( + 'd', + expect.stringMatching(/^M49.9\d+,10A40,40,0,1,0,50,10L50,50Z/) + ); + }); + + it('should draw complete circle with startAngle', async () => { + data.series = [100]; + options.startAngle = 90; + await createChart(); + + const slice = fixture.wrapper.querySelectorAll('.ct-slice-pie')[0]; + expect(slice).toHaveAttribute( + 'd', + expect.stringMatching(/^M90,49.9\d+A40,40,0,1,0,90,50L50,50Z/) + ); + }); + + it('should draw complete circle if values are 0', async () => { + data = { + series: [0, 1, 0] + }; + await createChart(); + + const slice = fixture.wrapper.querySelectorAll('.ct-slice-pie')[1]; + expect(slice).toHaveAttribute( + 'd', + expect.stringMatching(/^M49.9\d+,10A40,40,0,1,0,50,10L50,50Z/) + ); + }); + }); + + describe('Pie with small slices', () => { + beforeEach(() => { + data = { + series: [0.001, 2] + }; + options = { + width: 100, + height: 100, + chartPadding: 0 + }; + }); + + it('should render correctly with very small slices', async () => { + await createChart(); + + const [slice1, slice2] = Array.from( + fixture.wrapper.querySelectorAll('.ct-slice-pie') + ); + + expect(slice1).toHaveAttribute( + 'd', + expect.stringMatching(/^M50.1\d+,0A50,50,0,0,0,50,0/) + ); + expect(slice2).toHaveAttribute( + 'd', + expect.stringMatching(/^M49.9\d*,0A50,50,0,1,0,50,0/) + ); + }); + + it('should render correctly with very small slices on startAngle', async () => { + options.startAngle = 90; + await createChart(); + + const [slice1, slice2] = Array.from( + fixture.wrapper.querySelectorAll('.ct-slice-pie') + ); + + expect(slice1).toHaveAttribute( + 'd', + expect.stringMatching(/^M100,50.1\d*A50,50,0,0,0,100,50/) + ); + expect(slice2).toHaveAttribute( + 'd', + expect.stringMatching(/^M100,49.97\d*A50,50,0,1,0,100,49.98\d*/) + ); + }); + + it('should render correctly with very small slices', async () => { + options.donut = true; + await createChart(); + + const [slice1, slice2] = Array.from( + fixture.wrapper.querySelectorAll('.ct-slice-donut') + ); + + expect(slice1).toHaveAttribute( + 'd', + expect.stringMatching(/^M50.\d+,30A20,20,0,0,0,50,30/) + ); + expect(slice2).toHaveAttribute( + 'd', + expect.stringMatching(/^M49.9\d*,30A20,20,0,1,0,50,30/) + ); + }); + }); + + describe('Pie with empty values', () => { + beforeEach(() => { + data = { + series: [1, 2, 0, 4] + }; + options = { + width: 100, + height: 100, + ignoreEmptyValues: true + }; + }); + + it('should not render empty slices', async () => { + await createChart(); + + const slices = fixture.wrapper.querySelectorAll('.ct-slice-pie'); + + expect(slices.length).toBe(3); + expect(slices[0].getAttributeNS(namespaces.ct, 'value')).toBe('1'); + expect(slices[1].getAttributeNS(namespaces.ct, 'value')).toBe('2'); + expect(slices[2].getAttributeNS(namespaces.ct, 'value')).toBe('4'); + }); + + it('should render without NaN values and points', async () => { + data = { + series: [0, 0, 0] + }; + options = { + width: 400, + height: 400 + }; + await createChart(); + + const slices = fixture.wrapper.querySelectorAll('.ct-slice-pie'); + + expect(slices.length).toBe(3); + + expect(slices[0].getAttributeNS(namespaces.ct, 'value')).toBe('0'); + expect(slices[1].getAttributeNS(namespaces.ct, 'value')).toBe('0'); + expect(slices[2].getAttributeNS(namespaces.ct, 'value')).toBe('0'); + + expect(slices[0]).toHaveAttribute( + 'd', + 'M200,5A195,195,0,0,0,200,5L200,200Z' + ); + expect(slices[1]).toHaveAttribute( + 'd', + 'M200,5A195,195,0,0,0,200,5L200,200Z' + ); + expect(slices[2]).toHaveAttribute( + 'd', + 'M200,5A195,195,0,0,0,200,5L200,200Z' + ); + }); + + it('should render empty slices', async () => { + data = { + series: [1, 2, 0, 4] + }; + options = { + width: 100, + height: 100, + ignoreEmptyValues: false + }; + await createChart(); + + const slices = fixture.wrapper.querySelectorAll('.ct-slice-pie'); + + expect(slices.length).toBe(4); + + expect(slices[0].getAttributeNS(namespaces.ct, 'value')).toBe('1'); + expect(slices[1].getAttributeNS(namespaces.ct, 'value')).toBe('2'); + expect(slices[2].getAttributeNS(namespaces.ct, 'value')).toBe('0'); + expect(slices[3].getAttributeNS(namespaces.ct, 'value')).toBe('4'); + }); + }); + + describe('Gauge Chart', () => { + beforeEach(() => { + data = { + series: [20, 10, 30, 40] + }; + options = { + chartPadding: 50, + height: 500, + width: 500, + donut: true, + donutWidth: 60, + startAngle: 270, + total: 200, + showLabel: false + }; + }); + + it('should render four strokes', async () => { + await createChart(); + + expect(fixture.wrapper.querySelectorAll('.ct-slice-donut').length).toBe( + 4 + ); + }); + + it('should set value attribute', async () => { + await createChart(); + + const slices = fixture.wrapper.querySelectorAll('.ct-slice-donut'); + expect(slices[0].getAttributeNS(namespaces.ct, 'value')).toBe('20'); + expect(slices[1].getAttributeNS(namespaces.ct, 'value')).toBe('10'); + expect(slices[2].getAttributeNS(namespaces.ct, 'value')).toBe('30'); + expect(slices[3].getAttributeNS(namespaces.ct, 'value')).toBe('40'); + }); + + it('should create slice path', async () => { + const num = '\\d+(\\.\\d*)?'; + const pattern = new RegExp( + `^M${num},${num}A170,170,0,0,0,${num},${num}$` + ); + await createChart(); + + Array.from(fixture.wrapper.querySelectorAll('.ct-slice-donut')).forEach( + element => + expect(element).toHaveAttribute('d', expect.stringMatching(pattern)) + ); + }); + + it('should set stroke-width', async () => { + const strokeWidth = new RegExp('stroke-width:\\s*60px'); + await createChart(); + + Array.from(fixture.wrapper.querySelectorAll('.ct-slice-donut')).forEach( + element => + expect(element).toHaveAttribute( + // eslint-disable-next-line jest-dom/prefer-to-have-style + 'style', + expect.stringMatching(strokeWidth) + ) + ); + }); + + it('should not add labels', async () => { + await createChart(); + + const labels = fixture.wrapper.querySelectorAll('.ct-label'); + expect(labels.length).toBe(0); + }); + }); + + describe('Pie Chart with relative donutWidth', () => { + beforeEach(() => { + data = { + series: [20, 10, 30, 40] + }; + options = { + chartPadding: 50, + height: 500, + width: 500, + donut: true, + donutWidth: '25%', + showLabel: false + }; + }); + + it('should render four strokes', async () => { + await createChart(); + + expect(fixture.wrapper.querySelectorAll('.ct-slice-donut').length).toBe( + 4 + ); + }); + + it('should create slice path', async () => { + const num = '\\d+(\\.\\d*)?'; + const pattern = new RegExp( + `^M${num},${num}A175,175,0,0,0,${num},${num}$` + ); + await createChart(); + + Array.from(fixture.wrapper.querySelectorAll('.ct-slice-donut')).forEach( + element => + expect(element).toHaveAttribute('d', expect.stringMatching(pattern)) + ); + }); + + it('should set stroke-width', async () => { + const strokeWidth = new RegExp('stroke-width:\\s?50px'); + await createChart(); + + Array.from(fixture.wrapper.querySelectorAll('.ct-slice-donut')).forEach( + element => + expect(element).toHaveAttribute( + // eslint-disable-next-line jest-dom/prefer-to-have-style + 'style', + expect.stringMatching(strokeWidth) + ) + ); + }); + }); + }); +}); diff --git a/src/charts/PieChart/PieChart.stories.ts b/src/charts/PieChart/PieChart.stories.ts new file mode 100644 index 000000000..d9026e07b --- /dev/null +++ b/src/charts/PieChart/PieChart.stories.ts @@ -0,0 +1,236 @@ +import 'chartist-dev/styles'; +import { PieChart } from 'chartist-dev'; + +export default { + title: 'PieChart', + argTypes: {} +}; + +export function Default() { + const root = document.createElement('div'); + + new PieChart( + root, + { + series: [5, 3, 4] + }, + { + width: 100, + height: 100, + chartPadding: 10 + } + ); + + return root; +} + +export function Labels() { + const root = document.createElement('div'); + + new PieChart( + root, + { + labels: ['A', 'B', 'C'], + series: [5, 8, 1] + }, + {} + ); + + return root; +} + +export function OverlappingLabels() { + const root = document.createElement('div'); + + new PieChart( + root, + { + labels: ['Big Slice', 11231231, 'Test the string', new Date(), 124124124], + series: [96, 1, 1, 1, 1] + }, + { + preventOverlappingLabelOffset: 12 + } + ); + + return root; +} + +export function LabelInterpolation() { + const root = document.createElement('div'); + const data = { + series: [5, 3, 4] + }; + const sum = (a: number, b: number) => a + b; + + new PieChart(root, data, { + width: 100, + height: 100, + chartPadding: 10, + labelInterpolationFnc: value => + `${Math.round((Number(value) / data.series.reduce(sum)) * 100)}%` + }); + + return root; +} + +export function StartAngle() { + const root = document.createElement('div'); + + new PieChart( + root, + { + series: [5, 3, 4] + }, + { + startAngle: 90 + } + ); + + return root; +} + +export function SmallSlices() { + const root = document.createElement('div'); + + new PieChart( + root, + { + series: [0.001, 2] + }, + { + width: 100, + height: 100, + chartPadding: 0 + } + ); + + return root; +} + +export function IgnoreEmptyValues() { + const root = document.createElement('div'); + + new PieChart( + root, + { + series: [1, 2, 0, 4] + }, + { + ignoreEmptyValues: true + } + ); + + return root; +} + +export function Donut() { + const root = document.createElement('div'); + + new PieChart( + root, + { + series: [5, 3, 4] + }, + { + donut: true + } + ); + + return root; +} + +export function GaugeDonut() { + const root = document.createElement('div'); + + new PieChart( + root, + { + series: [20, 10, 30, 40] + }, + { + chartPadding: 50, + height: 500, + width: 500, + donut: true, + donutWidth: 60, + startAngle: 270, + total: 200, + showLabel: false + } + ); + + return root; +} + +export function RelativeDonutWidth() { + const root = document.createElement('div'); + + new PieChart( + root, + { + series: [20, 10, 30, 40] + }, + { + chartPadding: 50, + height: 500, + width: 500, + donut: true, + donutWidth: '25%', + showLabel: false + } + ); + + return root; +} + +export function Solid() { + const root = document.createElement('div'); + + new PieChart( + root, + { + series: [20, 10, 30, 40] + }, + { + donut: true, + donutWidth: 60, + // donutSolid: true, + startAngle: 270, + showLabel: true + } + ); + + return root; +} + +export function ViewBox() { + const root = document.createElement('div'); + + new PieChart( + root, + { + series: [5, 3, 4] + }, + { + chartPadding: 10, + viewBox: { + width: 350, + height: 350 + } + }, + [ + [ + 'screen and (max-width: 575px)', + { + viewBox: { + width: 250, + height: 250 + } + } + ] + ] + ); + + return root; +} diff --git a/src/charts/PieChart/PieChart.ts b/src/charts/PieChart/PieChart.ts new file mode 100644 index 000000000..eb53c57ec --- /dev/null +++ b/src/charts/PieChart/PieChart.ts @@ -0,0 +1,505 @@ +import type { + LabelDirection, + AnchorPosition, + Dot, + PieChartData, + PieChartOptions, + PieChartOptionsWithDefaults, + PieChartCreatedEvent, + SliceDrawEvent, + SliceLabelDrawEvent, + PieChartEventsTypes +} from './PieChart.types'; +import type { Svg } from '../../svg'; +import type { ResponsiveOptions } from '../../core'; +import { + alphaNumerate, + quantity, + normalizeData, + serialize, + createSvg, + createChartRect, + polarToCartesian +} from '../../core'; +import { + noop, + sum, + extend, + isFalseyButZero, + safeHasProperty +} from '../../utils'; +import { SvgPath } from '../../svg'; +import { BaseChart } from '../BaseChart'; + +/** + * Default options in line charts. Expand the code view to see a detailed list of options with comments. + */ +const defaultOptions = { + // Specify a fixed width for the chart as a string (i.e. '100px' or '50%') + width: undefined, + // Specify a fixed height for the chart as a string (i.e. '100px' or '50%') + height: undefined, + // Padding of the chart drawing area to the container element and labels as a number or padding object {top: 5, right: 5, bottom: 5, left: 5} + chartPadding: 5, + // Override the class names that are used to generate the SVG structure of the chart + classNames: { + chartPie: 'ct-chart-pie', + chartDonut: 'ct-chart-donut', + series: 'ct-series', + slicePie: 'ct-slice-pie', + sliceDonut: 'ct-slice-donut', + label: 'ct-label' + }, + // The start angle of the pie chart in degrees where 0 points north. A higher value offsets the start angle clockwise. + startAngle: 0, + // An optional total you can specify. By specifying a total value, the sum of the values in the series must be this total in order to draw a full pie. You can use this parameter to draw only parts of a pie or gauge charts. + total: undefined, + // If specified the donut CSS classes will be used and strokes will be drawn instead of pie slices. + donut: false, + // Specify the donut stroke width, currently done in javascript for convenience. May move to CSS styles in the future. + // This option can be set as number or string to specify a relative width (i.e. 100 or '30%'). + donutWidth: 60, + // If a label should be shown or not + showLabel: true, + // Label position offset from the standard position which is half distance of the radius. This value can be either positive or negative. Positive values will position the label away from the center. + labelOffset: 0, + // This option can be set to 'inside', 'outside' or 'center'. Positioned with 'inside' the labels will be placed on half the distance of the radius to the border of the Pie by respecting the 'labelOffset'. The 'outside' option will place the labels at the border of the pie and 'center' will place the labels in the absolute center point of the chart. The 'center' option only makes sense in conjunction with the 'labelOffset' option. + labelPosition: 'inside', + // An interpolation function for the label value + labelInterpolationFnc: noop, + // Label direction can be 'neutral', 'explode' or 'implode'. The labels anchor will be positioned based on those settings as well as the fact if the labels are on the right or left side of the center of the chart. Usually explode is useful when labels are positioned far away from the center. + labelDirection: 'neutral', + // If true empty values will be ignored to avoid drawing unnecessary slices and labels + ignoreEmptyValues: false, + // If Nonzero check if a label has overlapping text then move it the number of pixels up and left (Should be half of label font size + 1 but you can tweak it as you prefer) + preventOverlappingLabelOffset: 0 +}; + +/** + * Determines SVG anchor position based on direction and center parameter + */ +export function determineAnchorPosition( + center: Dot, + label: Dot, + direction: LabelDirection +): AnchorPosition { + const toTheRight = label.x > center.x; + + if ( + (toTheRight && direction === 'explode') || + (!toTheRight && direction === 'implode') + ) { + return 'start'; + } else if ( + (toTheRight && direction === 'implode') || + (!toTheRight && direction === 'explode') + ) { + return 'end'; + } else { + return 'middle'; + } +} + +export class PieChart extends BaseChart { + /** + * This method creates a new pie chart and returns an object that can be used to redraw the chart. + * @param query A selector query string or directly a DOM element + * @param data The data object in the pie chart needs to have a series property with a one dimensional data array. The values will be normalized against each other and don't necessarily need to be in percentage. The series property can also be an array of value objects that contain a value property and a className property to override the CSS class name for the series group. + * @param options The options object with options that override the default options. Check the examples for a detailed list. + * @param responsiveOptions Specify an array of responsive option arrays which are a media query and options object pair => [[mediaQueryString, optionsObject],[more...]] + * + * @example + * ```ts + * // Simple pie chart example with four series + * new PieChart('.ct-chart', { + * series: [10, 2, 4, 3] + * }); + * ``` + * + * @example + * ```ts + * // Drawing a donut chart + * new PieChart('.ct-chart', { + * series: [10, 2, 4, 3] + * }, { + * donut: true + * }); + * ``` + * + * @example + * ```ts + * // Using donut, startAngle and total to draw a gauge chart + * new PieChart('.ct-chart', { + * series: [20, 10, 30, 40] + * }, { + * donut: true, + * donutWidth: 20, + * startAngle: 270, + * total: 200 + * }); + * ``` + * + * @example + * ```ts + * // Drawing a pie chart with padding and labels that are outside the pie + * new PieChart('.ct-chart', { + * series: [20, 10, 30, 40] + * }, { + * chartPadding: 30, + * labelOffset: 50, + * labelDirection: 'explode' + * }); + * ``` + * + * @example + * ```ts + * // Overriding the class names for individual series as well as a name and meta data. + * // The name will be written as ct:series-name attribute and the meta data will be serialized and written + * // to a ct:meta attribute. + * new PieChart('.ct-chart', { + * series: [{ + * value: 20, + * name: 'Series 1', + * className: 'my-custom-class-one', + * meta: 'Meta One' + * }, { + * value: 10, + * name: 'Series 2', + * className: 'my-custom-class-two', + * meta: 'Meta Two' + * }, { + * value: 70, + * name: 'Series 3', + * className: 'my-custom-class-three', + * meta: 'Meta Three' + * }] + * }); + * ``` + */ + constructor( + query: string | Element | null, + protected override data: PieChartData, + options?: PieChartOptions, + responsiveOptions?: ResponsiveOptions + ) { + super( + query, + data, + defaultOptions, + extend({}, defaultOptions, options), + responsiveOptions + ); + } + + /** + * Check if a label has overlapping text then move it the number of pixels up and left based on textSize. + * @param labelPos - Label position that chartist will be checking does not overlap with the list of LabelPositions. + * @param existingLabelPos - Label position that has already been placed that chartist will check against. + * @param textOffset - this is configured with preventOverlappingLabelOffset option. + * @param length - How many characters long the label is. + */ + moveLabel( + labelPos: Dot, + existingLabelPos: Dot, + textOffset: number, + length: number + ) { + if ( + labelPos.y > existingLabelPos.y - textOffset && + labelPos.y < existingLabelPos.y + textOffset && + labelPos.x > existingLabelPos.x - length * textOffset && + labelPos.x < existingLabelPos.x + length * textOffset + ) { + labelPos.y -= textOffset; + labelPos.x -= textOffset; + this.moveLabel(labelPos, existingLabelPos, textOffset, length); + } + } + + /** + * Creates the pie chart + * + * @param options + */ + createChart(options: PieChartOptionsWithDefaults) { + const { data } = this; + const normalizedData = normalizeData(data); + const seriesGroups: Svg[] = []; + let labelsGroup: Svg; + const labelPositions: Dot[] = []; + let labelRadius: number; + let startAngle = options.startAngle; + + // Create SVG.js draw + const svg = createSvg( + this.container, + options.width, + options.height, + options.donut + ? options.classNames.chartDonut + : options.classNames.chartPie, + options.viewBox + ); + + this.svg = svg; + + // Calculate charting rect + const chartRect = createChartRect(svg, options); + // Get biggest circle radius possible within chartRect + let radius = Math.min(chartRect.width() / 2, chartRect.height() / 2); + // Calculate total of all series to get reference value or use total reference from optional options + const totalDataSum = options.total || normalizedData.series.reduce(sum, 0); + + const donutWidth = quantity(options.donutWidth); + if (donutWidth.unit === '%') { + donutWidth.value *= radius / 100; + } + + // If this is a donut chart we need to adjust our radius to enable strokes to be drawn inside + // Unfortunately this is not possible with the current SVG Spec + // See this proposal for more details: http://lists.w3.org/Archives/Public/www-svg/2003Oct/0000.html + radius -= options.donut ? donutWidth.value / 2 : 0; + + // If labelPosition is set to `outside` or a donut chart is drawn then the label position is at the radius, + // if regular pie chart it's half of the radius + if (options.labelPosition === 'outside' || options.donut) { + labelRadius = radius; + } else if (options.labelPosition === 'center') { + // If labelPosition is center we start with 0 and will later wait for the labelOffset + labelRadius = 0; + } else { + // Default option is 'inside' where we use half the radius so the label will be placed in the center of the pie + // slice + labelRadius = radius / 2; + } + // Add the offset to the labelRadius where a negative offset means closed to the center of the chart + if (options.labelOffset) { + labelRadius += options.labelOffset; + } + + // Calculate end angle based on total sum and current data value and offset with padding + const center = { + x: chartRect.x1 + chartRect.width() / 2, + y: chartRect.y2 + chartRect.height() / 2 + }; + + // Check if there is only one non-zero value in the series array. + const hasSingleValInSeries = + data.series.filter(val => + safeHasProperty(val, 'value') ? val.value !== 0 : val !== 0 + ).length === 1; + + // Creating the series groups + data.series.forEach((_, index) => (seriesGroups[index] = svg.elem('g'))); + // if we need to show labels we create the label group now + if (options.showLabel) { + labelsGroup = svg.elem('g'); + } + + // Draw the series + // initialize series groups + data.series.forEach((series, index) => { + // If current value is zero and we are ignoring empty values then skip to next value + if (normalizedData.series[index] === 0 && options.ignoreEmptyValues) { + return; + } + + const seriesName = safeHasProperty(series, 'name') && series.name; + const seriesClassName = + safeHasProperty(series, 'className') && series.className; + const seriesMeta = safeHasProperty(series, 'meta') + ? series.meta + : undefined; + + // If the series is an object and contains a name or meta data we add a custom attribute + if (seriesName) { + seriesGroups[index].attr({ + 'ct:series-name': seriesName + }); + } + + // Use series class from series data or if not set generate one + seriesGroups[index].addClass( + [ + options.classNames?.series, + seriesClassName || + `${options.classNames?.series}-${alphaNumerate(index)}` + ].join(' ') + ); + + // If the whole dataset is 0 endAngle should be zero. Can't divide by 0. + let endAngle = + totalDataSum > 0 + ? startAngle + (normalizedData.series[index] / totalDataSum) * 360 + : 0; + + // Use slight offset so there are no transparent hairline issues + const overlappigStartAngle = Math.max( + 0, + startAngle - (index === 0 || hasSingleValInSeries ? 0 : 0.2) + ); + + // If we need to draw the arc for all 360 degrees we need to add a hack where we close the circle + // with Z and use 359.99 degrees + if (endAngle - overlappigStartAngle >= 359.99) { + endAngle = overlappigStartAngle + 359.99; + } + + const start = polarToCartesian( + center.x, + center.y, + radius, + overlappigStartAngle + ); + const end = polarToCartesian(center.x, center.y, radius, endAngle); + + // Create a new path element for the pie chart. If this isn't a donut chart we should close the path for a correct stroke + const path = new SvgPath(!options.donut) + .move(end.x, end.y) + .arc( + radius, + radius, + 0, + Number(endAngle - startAngle > 180), + 0, + start.x, + start.y + ); + + // If regular pie chart (no donut) we add a line to the center of the circle for completing the pie + if (!options.donut) { + path.line(center.x, center.y); + } + + // Create the SVG path + // If this is a donut chart we add the donut class, otherwise just a regular slice + const pathElement = seriesGroups[index].elem( + 'path', + { + d: path.stringify() + }, + options.donut + ? options.classNames.sliceDonut + : options.classNames.slicePie + ); + + // Adding the pie series value to the path + pathElement.attr({ + 'ct:value': normalizedData.series[index], + 'ct:meta': serialize(seriesMeta) + }); + + // If this is a donut, we add the stroke-width as style attribute + if (options.donut) { + pathElement.attr({ + style: 'stroke-width: ' + donutWidth.value + 'px' + }); + } + + // Fire off draw event + this.eventEmitter.emit('draw', { + type: 'slice', + value: normalizedData.series[index], + totalDataSum: totalDataSum, + index, + meta: seriesMeta, + series, + group: seriesGroups[index], + element: pathElement, + path: path.clone(), + center, + radius, + startAngle, + endAngle, + chartRect + }); + + // If we need to show labels we need to add the label for this slice now + if (options.showLabel) { + let labelPosition: Dot; + + if (data.series.length === 1) { + // If we have only 1 series, we can position the label in the center of the pie + labelPosition = { + x: center.x, + y: center.y + }; + } else { + // Position at the labelRadius distance from center and between start and end angle + labelPosition = polarToCartesian( + center.x, + center.y, + labelRadius, + startAngle + (endAngle - startAngle) / 2 + ); + } + + let rawValue; + if ( + normalizedData.labels && + !isFalseyButZero(normalizedData.labels[index]) + ) { + rawValue = normalizedData.labels[index]; + } else { + rawValue = normalizedData.series[index]; + } + + const interpolatedValue = options.labelInterpolationFnc( + rawValue, + index + ); + + if (interpolatedValue || interpolatedValue === 0) { + if (options.preventOverlappingLabelOffset) { + const textOffset = options.preventOverlappingLabelOffset; + const length = String(normalizedData.labels[index]).length; + + labelPositions.forEach(item => { + this.moveLabel(labelPosition, item, textOffset, length); + }); + labelPositions.push(labelPosition); + } + + const labelElement = labelsGroup + .elem( + 'text', + { + dx: labelPosition.x, + dy: labelPosition.y, + 'text-anchor': determineAnchorPosition( + center, + labelPosition, + options.labelDirection + ) + }, + options.classNames.label + ) + .text(String(interpolatedValue)); + + // Fire off draw event + this.eventEmitter.emit('draw', { + type: 'label', + index, + group: labelsGroup, + element: labelElement, + text: '' + interpolatedValue, + chartRect, + series, + meta: seriesMeta, + ...labelPosition + }); + } + } + + // Set next startAngle to current endAngle. + // (except for last slice) + startAngle = endAngle; + }); + + this.eventEmitter.emit('created', { + chartRect, + svg: svg, + options + }); + } +} diff --git a/src/charts/PieChart/PieChart.types.ts b/src/charts/PieChart/PieChart.types.ts new file mode 100644 index 000000000..08165eb5d --- /dev/null +++ b/src/charts/PieChart/PieChart.types.ts @@ -0,0 +1,133 @@ +import type { + Options, + Label, + Data, + FlatSeries, + CreatedEvent, + DrawEvent, + NormalizedSeriesValue +} from '../../core'; +import type { RequiredKeys } from '../../utils'; +import type { SvgPath } from '../../svg'; +import type { BaseChartEventsTypes } from '../types'; + +export type PieChartData = Data; + +export type LabelDirection = 'implode' | 'neutral' | 'explode'; + +export type AnchorPosition = 'start' | 'middle' | 'end'; + +export type RadialLabelPosition = 'inside' | 'center' | 'outside'; + +export interface Dot { + x: number; + y: number; +} + +export interface PieChartOptions extends Omit { + /** + * Override the class names that are used to generate the SVG structure of the chart + */ + classNames?: { + chartPie?: string; + chartDonut?: string; + series?: string; + slicePie?: string; + sliceDonut?: string; + label?: string; + }; + /** + * The start angle of the pie chart in degrees where 0 points north. A higher value offsets the start angle clockwise. + */ + startAngle?: number; + /** + * An optional total you can specify. By specifying a total value, the sum of the values in the series must be this total in order to draw a full pie. You can use this parameter to draw only parts of a pie or gauge charts. + */ + total?: number; + /** + * If specified the donut CSS classes will be used and strokes will be drawn instead of pie slices. + */ + donut?: boolean; + /** + * Specify the donut stroke width, currently done in javascript for convenience. May move to CSS styles in the future. + * This option can be set as number or string to specify a relative width (i.e. 100 or '30%'). + */ + donutWidth?: number | string; + /** + * If a label should be shown or not + */ + showLabel?: boolean; + /** + * Label position offset from the standard position which is half distance of the radius. This value can be either positive or negative. Positive values will position the label away from the center. + */ + labelOffset?: number; + /** + * This option can be set to 'inside', 'outside' or 'center'. + * Positioned with 'inside' the labels will be placed on half the distance of the radius to the border of the Pie by respecting the 'labelOffset'. + * The 'outside' option will place the labels at the border of the pie and 'center' will place the labels in the absolute center point of the chart. + * The 'center' option only makes sense in conjunction with the 'labelOffset' option. + */ + labelPosition?: RadialLabelPosition; + /** + * An interpolation function for the label value + */ + labelInterpolationFnc?(value: Label, index: number): Label | null | undefined; + /** + * Label direction can be 'neutral', 'explode' or 'implode'. + * The labels anchor will be positioned based on those settings as well as the fact if the labels are on the right or left side of the center of the chart. + * Usually explode is useful when labels are positioned far away from the center. + */ + labelDirection?: LabelDirection; + /** + * If true empty values will be ignored to avoid drawing unnecessary slices and labels + */ + ignoreEmptyValues?: boolean; + /** + * If nonzero labels will not overlap. + */ + preventOverlappingLabelOffset?: number; +} + +export type PieChartOptionsWithDefaults = RequiredKeys< + PieChartOptions, + | 'chartPadding' + | 'startAngle' + | 'donutWidth' + | 'showLabel' + | 'labelOffset' + | 'labelPosition' + | 'labelInterpolationFnc' + | 'labelDirection' + | 'preventOverlappingLabelOffset', + 'classNames' +>; + +export type PieChartCreatedEvent = Omit< + CreatedEvent, + 'axisX' | 'axisY' +>; + +export interface SliceDrawEvent + extends Omit { + type: 'slice'; + value: NormalizedSeriesValue; + totalDataSum: number; + path: SvgPath; + center: Dot; + radius: number; + startAngle: number; + endAngle: number; +} + +export interface SliceLabelDrawEvent + extends Omit { + type: 'label'; + text: string; + x: number; + y: number; +} + +export type PieChartEventsTypes = BaseChartEventsTypes< + PieChartCreatedEvent, + SliceDrawEvent | SliceLabelDrawEvent +>; diff --git a/src/charts/PieChart/index.ts b/src/charts/PieChart/index.ts new file mode 100644 index 000000000..70a6c91eb --- /dev/null +++ b/src/charts/PieChart/index.ts @@ -0,0 +1,2 @@ +export * from './PieChart'; +export * from './PieChart.types'; diff --git a/src/charts/index.ts b/src/charts/index.ts new file mode 100644 index 000000000..a4ec210b3 --- /dev/null +++ b/src/charts/index.ts @@ -0,0 +1,5 @@ +export * from './BaseChart'; +export * from './LineChart'; +export * from './BarChart'; +export * from './PieChart'; +export * from './types'; diff --git a/src/charts/types.ts b/src/charts/types.ts new file mode 100644 index 000000000..b76059f76 --- /dev/null +++ b/src/charts/types.ts @@ -0,0 +1,19 @@ +import type { + DataEvent, + OptionsChangedEvent, + DrawEvent, + CreatedEvent +} from '../core'; +import type { AnimationEvent } from '../svg'; + +export interface BaseChartEventsTypes< + TCreateEvent = CreatedEvent, + TDrawEvents = DrawEvent +> { + data: DataEvent; + options: OptionsChangedEvent; + animationBegin: AnimationEvent; + animationEnd: AnimationEvent; + created: TCreateEvent; + draw: TDrawEvents; +} diff --git a/src/core/constants.ts b/src/core/constants.ts new file mode 100644 index 000000000..10c55df9f --- /dev/null +++ b/src/core/constants.ts @@ -0,0 +1,26 @@ +/** + * This object contains all namespaces used within Chartist. + */ +export const namespaces: Record = { + svg: 'http://www.w3.org/2000/svg', + xmlns: 'http://www.w3.org/2000/xmlns/', + xhtml: 'http://www.w3.org/1999/xhtml', + xlink: 'http://www.w3.org/1999/xlink', + ct: 'http://gionkunz.github.com/chartist-js/ct' +}; + +/** + * Precision level used internally in Chartist for rounding. If you require more decimal places you can increase this number. + */ +export const precision = 8; + +/** + * A map with characters to escape for strings to be safely used as attribute values. + */ +export const escapingMap: Record = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' +}; diff --git a/src/core/creation.spec.ts b/src/core/creation.spec.ts new file mode 100644 index 000000000..ea483abcd --- /dev/null +++ b/src/core/creation.spec.ts @@ -0,0 +1,238 @@ +import { addMockWrapper, mockDom, destroyMockDom } from '../../test/mock/dom'; +import { + createSvg, + createGrid, + createGridBackground, + normalizePadding +} from './creation'; +import { EventEmitter } from '../event'; +import { Svg } from '../svg'; + +describe('Core', () => { + describe('Creation', () => { + beforeEach(() => mockDom()); + afterEach(() => destroyMockDom()); + + describe('createSvg', () => { + it('should not remove non-chartist svg elements', () => { + const fixture = addMockWrapper(` +
+ +
+ +
+
+ `); + + const container: any = + fixture.wrapper.querySelector('#chart-container'); + const svg = createSvg(container, '500px', '400px', 'ct-fish-bar'); + + expect(svg).toBeDefined(); + expect(svg.classes()).toContain('ct-fish-bar'); + expect(svg.attr('viewBox')).toBeFalsy(); + expect(container).toContainElement(document.querySelector('#foo')); + expect(container).toContainElement(document.querySelector('#bar')); + }); + + it('should remove previous chartist svg elements', () => { + const fixture = addMockWrapper('
'); + + const container: any = + fixture.wrapper.querySelector('#chart-container'); + const svg1 = createSvg(container, '500px', '400px', 'ct-fish-bar'); + const svg2 = createSvg(container, '800px', '200px', 'ct-snake-bar'); + + expect(svg1).toBeDefined(); + expect(svg1.classes()).toContain('ct-fish-bar'); + expect(svg2).toBeDefined(); + expect(svg2.classes()).toContain('ct-snake-bar'); + expect(container).not.toContainElement( + document.querySelector('.ct-fish-bar') + ); + expect(container).toContainElement( + document.querySelector('.ct-snake-bar') + ); + }); + + it('should add viewBox to svg elements', () => { + const fixture = addMockWrapper(` +
+
+ `); + + const container: any = + fixture.wrapper.querySelector('#chart-container'); + const svg = createSvg(container, '500px', '400px', 'ct-fish-bar', { + width: 300, + height: 200 + }); + + expect(svg).toBeDefined(); + expect(svg.classes()).toContain('ct-fish-bar'); + expect(svg.attr('viewBox')).toEqual('0 0 300 200'); + expect(container).toContainElement( + document.querySelector('.ct-fish-bar') + ); + }); + }); + + describe('createGrid', () => { + let group: any; + let axis: any; + let classes: any; + let eventEmitter: EventEmitter; + let position: any; + let length: any; + let offset: any; + + beforeEach(() => { + eventEmitter = new EventEmitter(); + group = new Svg('g'); + axis = { + units: { + pos: 'x' + }, + counterUnits: { + pos: 'y' + } + }; + classes = []; + position = 10; + length = 100; + offset = 20; + }); + + function onCreated(fn: any, done: any) { + eventEmitter.on('draw', grid => { + fn(grid); + done(); + }); + createGrid( + position, + 1, + axis, + offset, + length, + group, + classes, + eventEmitter + ); + } + + it('should add single grid line to group', done => { + onCreated( + () => + expect(group.querySelectorAll('line').svgElements.length).toBe(1), + done + ); + }); + + it('should draw line', done => { + onCreated(() => { + const line = group.querySelector('line'); + expect(line.attr('x1')).toBe('10'); + expect(line.attr('x2')).toBe('10'); + expect(line.attr('y1')).toBe('20'); + expect(line.attr('y2')).toBe('120'); + }, done); + }); + + it('should draw horizontal line', done => { + axis.units.pos = 'y'; + axis.counterUnits.pos = 'x'; + onCreated(() => { + const line = group.querySelector('line'); + expect(line.attr('y1')).toBe('10'); + expect(line.attr('y2')).toBe('10'); + expect(line.attr('x1')).toBe('20'); + expect(line.attr('x2')).toBe('120'); + }, done); + }); + }); + + describe('createGridBackground', () => { + let group: any; + let chartRect: any; + let className: any; + let eventEmitter: any; + + beforeEach(() => { + eventEmitter = new EventEmitter(); + group = new Svg('g'); + className = 'ct-test'; + chartRect = { + x1: 5, + y2: 10, + _width: 100, + _height: 50, + width() { + return this._width; + }, + height() { + return this._height; + } + }; + }); + + function onCreated(fn: any, done: any) { + eventEmitter.on('draw', (data: any) => { + fn(data); + done(); + }); + createGridBackground(group, chartRect, className, eventEmitter); + } + + it('should add rect', done => { + onCreated(() => { + const rects = group.querySelectorAll('rect').svgElements; + expect(rects.length).toBe(1); + const rect = rects[0]; + expect(rect.attr('x')).toBe('5'); + expect(rect.attr('y')).toBe('10'); + expect(rect.attr('width')).toBe('100'); + expect(rect.attr('height')).toBe('50'); + expect(rect.classes()).toEqual(['ct-test']); + }, done); + }); + + it('should pass grid to event', done => { + onCreated((data: any) => { + expect(data.type).toBe('gridBackground'); + const rect = data.element; + expect(rect.attr('x')).toBe('5'); + expect(rect.attr('y')).toBe('10'); + }, done); + }); + }); + + describe('padding normalization', () => { + it('should normalize number padding', () => { + expect(normalizePadding(10)).toEqual({ + top: 10, + right: 10, + bottom: 10, + left: 10 + }); + }); + + it('should normalize number padding when 0 is passed', () => { + expect(normalizePadding(0)).toEqual({ + top: 0, + right: 0, + bottom: 0, + left: 0 + }); + }); + + it('should normalize empty padding object with default fallback', () => { + expect(normalizePadding({})).toEqual({ + top: 0, + right: 0, + bottom: 0, + left: 0 + }); + }); + }); + }); +}); diff --git a/src/core/creation.ts b/src/core/creation.ts new file mode 100644 index 000000000..b6c7b9573 --- /dev/null +++ b/src/core/creation.ts @@ -0,0 +1,288 @@ +import type { + ChartPadding, + ChartRect, + Options, + Label, + GridDrawEvent, + GridBackgroundDrawEvent, + LabelDrawEvent, + ViewBox +} from './types'; +import type { EventEmitter } from '../event'; +import type { Axis } from '../axes'; +import { namespaces } from './constants'; +import { Svg } from '../svg/Svg'; +import { quantity } from './lang'; + +/** + * Create or reinitialize the SVG element for the chart + * @param container The containing DOM Node object that will be used to plant the SVG element + * @param width Set the width of the SVG element. Default is 100% + * @param height Set the height of the SVG element. Default is 100% + * @param className Specify a class to be added to the SVG element + * @return The created/reinitialized SVG element + */ +export function createSvg( + container: Element, + width: number | string = '100%', + height: number | string = '100%', + className?: string, + viewBox?: ViewBox +) { + if (!container) { + throw new Error('Container element is not found'); + } + + // Check if there is a previous SVG element in the container that contains the Chartist XML namespace and remove it + // Since the DOM API does not support namespaces we need to manually search the returned list http://www.w3.org/TR/selectors-api/ + Array.from(container.querySelectorAll('svg')) + .filter(svg => svg.getAttributeNS(namespaces.xmlns, 'ct')) + .forEach(svg => container.removeChild(svg)); + + // Create svg object with width and height or use 100% as default + const svg = new Svg('svg') + .attr({ + width, + height + }) + .attr({ + // TODO: Check better solution (browser support) and remove inline styles due to CSP + style: `width: ${width}; height: ${height};` + }); + + if (className) { + svg.addClass(className); + } + + if (viewBox) { + svg.attr({ viewBox: `0 0 ${viewBox.width} ${viewBox.height}` }); + } + + // Add the DOM node to our container + container.appendChild(svg.getNode()); + + return svg; +} + +/** + * Converts a number into a padding object. + * @param padding + * @param fallback This value is used to fill missing values if a incomplete padding object was passed + * @returns Returns a padding object containing top, right, bottom, left properties filled with the padding number passed in as argument. If the argument is something else than a number (presumably already a correct padding object) then this argument is directly returned. + */ +export function normalizePadding( + padding: number | Partial | undefined +) { + return typeof padding === 'number' + ? { + top: padding, + right: padding, + bottom: padding, + left: padding + } + : padding === undefined + ? { top: 0, right: 0, bottom: 0, left: 0 } + : { + top: typeof padding.top === 'number' ? padding.top : 0, + right: typeof padding.right === 'number' ? padding.right : 0, + bottom: typeof padding.bottom === 'number' ? padding.bottom : 0, + left: typeof padding.left === 'number' ? padding.left : 0 + }; +} + +/** + * Initialize chart drawing rectangle (area where chart is drawn) x1,y1 = bottom left / x2,y2 = top right + * @param svg The svg element for the chart + * @param options The Object that contains all the optional values for the chart + * @return The chart rectangles coordinates inside the svg element plus the rectangles measurements + */ +export function createChartRect(svg: Svg, options: Options) { + const hasAxis = Boolean(options.axisX || options.axisY); + const yAxisOffset = options.axisY?.offset || 0; + const xAxisOffset = options.axisX?.offset || 0; + const yAxisPosition = options.axisY?.position; + const xAxisPosition = options.axisX?.position; + // If width or height results in invalid value (including 0) we fallback to the unitless settings or even 0 + let width = + options.viewBox?.width || svg.width() || quantity(options.width).value || 0; + let height = + options.viewBox?.height || + svg.height() || + quantity(options.height).value || + 0; + const normalizedPadding = normalizePadding(options.chartPadding); + + // If settings were to small to cope with offset (legacy) and padding, we'll adjust + width = Math.max( + width, + yAxisOffset + normalizedPadding.left + normalizedPadding.right + ); + height = Math.max( + height, + xAxisOffset + normalizedPadding.top + normalizedPadding.bottom + ); + + const chartRect = { + x1: 0, + x2: 0, + y1: 0, + y2: 0, + padding: normalizedPadding, + width() { + return this.x2 - this.x1; + }, + height() { + return this.y1 - this.y2; + } + }; + + if (hasAxis) { + if (xAxisPosition === 'start') { + chartRect.y2 = normalizedPadding.top + xAxisOffset; + chartRect.y1 = Math.max( + height - normalizedPadding.bottom, + chartRect.y2 + 1 + ); + } else { + chartRect.y2 = normalizedPadding.top; + chartRect.y1 = Math.max( + height - normalizedPadding.bottom - xAxisOffset, + chartRect.y2 + 1 + ); + } + + if (yAxisPosition === 'start') { + chartRect.x1 = normalizedPadding.left + yAxisOffset; + chartRect.x2 = Math.max( + width - normalizedPadding.right, + chartRect.x1 + 1 + ); + } else { + chartRect.x1 = normalizedPadding.left; + chartRect.x2 = Math.max( + width - normalizedPadding.right - yAxisOffset, + chartRect.x1 + 1 + ); + } + } else { + chartRect.x1 = normalizedPadding.left; + chartRect.x2 = Math.max(width - normalizedPadding.right, chartRect.x1 + 1); + chartRect.y2 = normalizedPadding.top; + chartRect.y1 = Math.max( + height - normalizedPadding.bottom, + chartRect.y2 + 1 + ); + } + + return chartRect; +} + +/** + * Creates a grid line based on a projected value. + */ +export function createGrid( + position: number, + index: number, + axis: Axis, + offset: number, + length: number, + group: Svg, + classes: string[], + eventEmitter: EventEmitter +) { + const positionalData = { + [`${axis.units.pos}1`]: position, + [`${axis.units.pos}2`]: position, + [`${axis.counterUnits.pos}1`]: offset, + [`${axis.counterUnits.pos}2`]: offset + length + } as Record<'x1' | 'y1' | 'x2' | 'y2', number>; + + const gridElement = group.elem('line', positionalData, classes.join(' ')); + + // Event for grid draw + eventEmitter.emit('draw', { + type: 'grid', + axis, + index, + group, + element: gridElement, + ...positionalData + }); +} + +/** + * Creates a grid background rect and emits the draw event. + */ +export function createGridBackground( + gridGroup: Svg, + chartRect: ChartRect, + className: string, + eventEmitter: EventEmitter +) { + const gridBackground = gridGroup.elem( + 'rect', + { + x: chartRect.x1, + y: chartRect.y2, + width: chartRect.width(), + height: chartRect.height() + }, + className, + true + ); + + // Event for grid background draw + eventEmitter.emit('draw', { + type: 'gridBackground', + group: gridGroup, + element: gridBackground + }); +} + +/** + * Creates a label based on a projected value and an axis. + */ +export function createLabel( + position: number, + length: number, + index: number, + label: Label, + axis: Axis, + axisOffset: number, + labelOffset: { x: number; y: number }, + group: Svg, + classes: string[], + eventEmitter: EventEmitter +) { + const positionalData = { + [axis.units.pos]: position + labelOffset[axis.units.pos], + [axis.counterUnits.pos]: labelOffset[axis.counterUnits.pos], + [axis.units.len]: length, + [axis.counterUnits.len]: Math.max(0, axisOffset - 10) + } as Record<'x' | 'y' | 'width' | 'height', number>; + // We need to set width and height explicitly to px as span will not expand with width and height being + // 100% in all browsers + const stepLength = Math.round(positionalData[axis.units.len]); + const stepCounterLength = Math.round(positionalData[axis.counterUnits.len]); + const content = document.createElement('span'); + + content.className = classes.join(' '); + content.style[axis.units.len] = stepLength + 'px'; + content.style[axis.counterUnits.len] = stepCounterLength + 'px'; + content.textContent = String(label); + + const labelElement = group.foreignObject(content, { + style: 'overflow: visible;', + ...positionalData + }); + + eventEmitter.emit('draw', { + type: 'label', + axis, + index, + group, + element: labelElement, + text: label, + ...positionalData + }); +} diff --git a/src/core/data/bound.spec.ts b/src/core/data/bound.spec.ts new file mode 100644 index 000000000..5760c8e15 --- /dev/null +++ b/src/core/data/bound.spec.ts @@ -0,0 +1,113 @@ +import { getBounds } from './bounds'; +import { roundWithPrecision } from '../math'; + +describe('Core', () => { + describe('Data', () => { + describe('Bounds', () => { + it('should return 10 steps', () => { + const bounds = getBounds(100, { high: 10, low: 1 }, 10, false); + expect(bounds.min).toBe(1); + expect(bounds.max).toBe(10); + expect(bounds.values).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); + }); + + it('should return 5 steps', () => { + const bounds = getBounds(100, { high: 10, low: 1 }, 20, false); + expect(bounds.min).toBe(1); + expect(bounds.max).toBe(10); + expect(bounds.values).toEqual([1, 3, 5, 7, 9]); + }); + + it('should return non integer steps', () => { + const bounds = getBounds(100, { high: 2, low: 1 }, 20, false); + expect(bounds.min).toBe(1); + expect(bounds.max).toBe(2); + expect(bounds.values).toEqual([1, 1.25, 1.5, 1.75, 2]); + }); + + it('should return integer steps only', () => { + const bounds = getBounds(100, { high: 3, low: 1 }, 20, true); + expect(bounds.min).toBe(1); + expect(bounds.max).toBe(3); + expect(bounds.values).toEqual([1, 2, 3]); + }); + + it('should return single integer step', () => { + const bounds = getBounds(100, { high: 2, low: 1 }, 20, true); + expect(bounds.min).toBe(1); + expect(bounds.max).toBe(2); + expect(bounds.values).toEqual([1, 2]); + }); + + it('should floor/ceil min/max', () => { + const bounds = getBounds(100, { high: 9.9, low: 1.01 }, 20, false); + expect(bounds.min).toBe(1); + expect(bounds.max).toBe(10); + expect(bounds.values).toEqual([1, 3, 5, 7, 9]); + }); + + it('should floor/ceil min/max for non integers', () => { + const bounds = getBounds(100, { high: 2.9, low: 1.01 }, 20, false); + expect(bounds.min).toBe(1); + expect(bounds.max).toBe(3); + expect(bounds.values).toEqual([1, 1.5, 2, 2.5, 3]); + }); + + it('should floor/ceil min/max if integers only', () => { + const bounds = getBounds(100, { high: 2.9, low: 1.01 }, 20, true); + expect(bounds.min).toBe(1); + expect(bounds.max).toBe(3); + expect(bounds.values).toEqual([1, 2, 3]); + }); + + it('should return neg and pos values', () => { + const bounds = getBounds(100, { high: 1.9, low: -0.9 }, 20, false); + expect(bounds.min).toBe(-1); + expect(bounds.max).toBe(2); + expect(bounds.values).toEqual([-1, 0, 1, 2]); + }); + + it('should return two steps if no space', () => { + const bounds = getBounds(100, { high: 5, low: 0 }, 45, false); + expect(bounds.min).toBe(0); + expect(bounds.max).toBe(5); + expect(bounds.values).toEqual([0, 4]); + }); + + it('should return single step if no space', () => { + const bounds = getBounds(100, { high: 5, low: 0 }, 80, false); + expect(bounds.min).toBe(0); + expect(bounds.max).toBe(5); + expect(bounds.values).toEqual([0]); + }); + + it('should return single step if range is less than epsilon', () => { + const bounds = getBounds( + 100, + { high: 1.0000000000000002, low: 1 }, + 20, + false + ); + expect(bounds.min).toBe(1); + expect(bounds.max).toBe(1.0000000000000002); + expect(bounds.low).toBe(1); + expect(bounds.high).toBe(1.0000000000000002); + expect(bounds.values).toEqual([1]); + }); + + it('should return single step if range is less than smallest increment', () => { + const bounds = getBounds( + 613.234375, + { high: 1000.0000000000001, low: 999.9999999999997 }, + 50, + false + ); + expect(bounds.min).toBe(999.9999999999999); + expect(bounds.max).toBe(1000); + expect(bounds.low).toBe(999.9999999999997); + expect(bounds.high).toBe(1000.0000000000001); + expect(bounds.values).toEqual([roundWithPrecision(999.9999999999999)]); + }); + }); + }); +}); diff --git a/src/core/data/bounds.ts b/src/core/data/bounds.ts new file mode 100644 index 000000000..69a3ea23c --- /dev/null +++ b/src/core/data/bounds.ts @@ -0,0 +1,125 @@ +import type { Bounds } from '../types'; +import { + orderOfMagnitude, + projectLength, + roundWithPrecision, + rho, + EPSILON +} from '../math'; + +/** + * Calculate and retrieve all the bounds for the chart and return them in one array + * @param axisLength The length of the Axis used for + * @param highLow An object containing a high and low property indicating the value range of the chart. + * @param scaleMinSpace The minimum projected length a step should result in + * @param onlyInteger + * @return All the values to set the bounds of the chart + */ +export function getBounds( + axisLength: number, + highLow: { high: number; low: number }, + scaleMinSpace: number, + onlyInteger = false +) { + const bounds: Bounds = { + high: highLow.high, + low: highLow.low, + valueRange: 0, + oom: 0, + step: 0, + min: 0, + max: 0, + range: 0, + numberOfSteps: 0, + values: [] + }; + + bounds.valueRange = bounds.high - bounds.low; + bounds.oom = orderOfMagnitude(bounds.valueRange); + bounds.step = Math.pow(10, bounds.oom); + bounds.min = Math.floor(bounds.low / bounds.step) * bounds.step; + bounds.max = Math.ceil(bounds.high / bounds.step) * bounds.step; + bounds.range = bounds.max - bounds.min; + bounds.numberOfSteps = Math.round(bounds.range / bounds.step); + + // Optimize scale step by checking if subdivision is possible based on horizontalGridMinSpace + // If we are already below the scaleMinSpace value we will scale up + const length = projectLength(axisLength, bounds.step, bounds); + const scaleUp = length < scaleMinSpace; + const smallestFactor = onlyInteger ? rho(bounds.range) : 0; + + // First check if we should only use integer steps and if step 1 is still larger than scaleMinSpace so we can use 1 + if (onlyInteger && projectLength(axisLength, 1, bounds) >= scaleMinSpace) { + bounds.step = 1; + } else if ( + onlyInteger && + smallestFactor < bounds.step && + projectLength(axisLength, smallestFactor, bounds) >= scaleMinSpace + ) { + // If step 1 was too small, we can try the smallest factor of range + // If the smallest factor is smaller than the current bounds.step and the projected length of smallest factor + // is larger than the scaleMinSpace we should go for it. + bounds.step = smallestFactor; + } else { + // Trying to divide or multiply by 2 and find the best step value + let optimizationCounter = 0; + for (;;) { + if ( + scaleUp && + projectLength(axisLength, bounds.step, bounds) <= scaleMinSpace + ) { + bounds.step *= 2; + } else if ( + !scaleUp && + projectLength(axisLength, bounds.step / 2, bounds) >= scaleMinSpace + ) { + bounds.step /= 2; + if (onlyInteger && bounds.step % 1 !== 0) { + bounds.step *= 2; + break; + } + } else { + break; + } + + if (optimizationCounter++ > 1000) { + throw new Error( + 'Exceeded maximum number of iterations while optimizing scale step!' + ); + } + } + } + + bounds.step = Math.max(bounds.step, EPSILON); + function safeIncrement(value: number, increment: number) { + // If increment is too small use *= (1+EPSILON) as a simple nextafter + if (value === (value += increment)) { + value *= 1 + (increment > 0 ? EPSILON : -EPSILON); + } + return value; + } + + // Narrow min and max based on new step + let newMin = bounds.min; + let newMax = bounds.max; + while (newMin + bounds.step <= bounds.low) { + newMin = safeIncrement(newMin, bounds.step); + } + while (newMax - bounds.step >= bounds.high) { + newMax = safeIncrement(newMax, -bounds.step); + } + bounds.min = newMin; + bounds.max = newMax; + bounds.range = bounds.max - bounds.min; + + const values: number[] = []; + for (let i = bounds.min; i <= bounds.max; i = safeIncrement(i, bounds.step)) { + const value = roundWithPrecision(i); + if (value !== values[values.length - 1]) { + values.push(value); + } + } + bounds.values = values; + + return bounds; +} diff --git a/src/core/data/data.ts b/src/core/data/data.ts new file mode 100644 index 000000000..b63398b26 --- /dev/null +++ b/src/core/data/data.ts @@ -0,0 +1,73 @@ +import type { + Multi, + AxisName, + FlatSeriesValue, + Series, + SeriesObject +} from '../types'; +import { safeHasProperty, getNumberOrUndefined } from '../../utils'; + +/** + * Get meta data of a specific value in a series. + */ +export function getMetaData( + seriesData: FlatSeriesValue | Series | SeriesObject, + index: number +) { + const value = Array.isArray(seriesData) + ? seriesData[index] + : safeHasProperty(seriesData, 'data') + ? seriesData.data[index] + : null; + return safeHasProperty(value, 'meta') ? value.meta : undefined; +} + +/** + * Checks if a value is considered a hole in the data series. + * @returns True if the value is considered a data hole + */ +export function isDataHoleValue(value: unknown): value is null | undefined; +export function isDataHoleValue(value: unknown) { + return ( + value === null || + value === undefined || + (typeof value === 'number' && isNaN(value)) + ); +} + +/** + * Checks if value is array of series objects. + */ +export function isArrayOfSeries( + value: unknown +): value is (Series | SeriesObject)[] { + return ( + Array.isArray(value) && + value.every(_ => Array.isArray(_) || safeHasProperty(_, 'data')) + ); +} + +/** + * Checks if provided value object is multi value (contains x or y properties) + */ +export function isMultiValue(value: unknown): value is Multi { + return ( + typeof value === 'object' && + value !== null && + (Reflect.has(value, 'x') || Reflect.has(value, 'y')) + ); +} + +/** + * Gets a value from a dimension `value.x` or `value.y` while returning value directly if it's a valid numeric value. If the value is not numeric and it's falsey this function will return `defaultValue`. + */ +export function getMultiValue( + value: Multi | number | unknown, + dimension: AxisName = 'y' +) { + if (isMultiValue(value) && safeHasProperty(value, dimension)) { + return getNumberOrUndefined(value[dimension]); + } else { + return getNumberOrUndefined(value); + } +} diff --git a/src/core/data/highLow.ts b/src/core/data/highLow.ts new file mode 100644 index 000000000..a1edbdd90 --- /dev/null +++ b/src/core/data/highLow.ts @@ -0,0 +1,95 @@ +import type { + Options, + AxisName, + NormalizedSeries, + NormalizedSeriesValue +} from '../types'; +import { safeHasProperty } from '../../utils'; +import { isDataHoleValue } from './data'; + +/** + * Get highest and lowest value of data array. This Array contains the data that will be visualized in the chart. + * @param data The array that contains the data to be visualized in the chart + * @param options The Object that contains the chart options + * @param dimension Axis dimension 'x' or 'y' used to access the correct value and high / low configuration + * @return An object that contains the highest and lowest value that will be visualized on the chart. + */ +export function getHighLow( + data: NormalizedSeries[], + options: Options, + dimension?: AxisName +) { + // TODO: Remove workaround for deprecated global high / low config. Axis high / low configuration is preferred + options = { + ...options, + ...(dimension ? (dimension === 'x' ? options.axisX : options.axisY) : {}) + }; + + const highLow = { + high: options.high === undefined ? -Number.MAX_VALUE : +options.high, + low: options.low === undefined ? Number.MAX_VALUE : +options.low + }; + const findHigh = options.high === undefined; + const findLow = options.low === undefined; + + // Function to recursively walk through arrays and find highest and lowest number + function recursiveHighLow( + sourceData: NormalizedSeriesValue | NormalizedSeries | NormalizedSeries[] + ) { + if (isDataHoleValue(sourceData)) { + return; + } else if (Array.isArray(sourceData)) { + for (let i = 0; i < sourceData.length; i++) { + recursiveHighLow(sourceData[i]); + } + } else { + const value = Number( + dimension && safeHasProperty(sourceData, dimension) + ? sourceData[dimension] + : sourceData + ); + + if (findHigh && value > highLow.high) { + highLow.high = value; + } + + if (findLow && value < highLow.low) { + highLow.low = value; + } + } + } + + // Start to find highest and lowest number recursively + if (findHigh || findLow) { + recursiveHighLow(data); + } + + // Overrides of high / low based on reference value, it will make sure that the invisible reference value is + // used to generate the chart. This is useful when the chart always needs to contain the position of the + // invisible reference value in the view i.e. for bipolar scales. + if (options.referenceValue || options.referenceValue === 0) { + highLow.high = Math.max(options.referenceValue, highLow.high); + highLow.low = Math.min(options.referenceValue, highLow.low); + } + + // If high and low are the same because of misconfiguration or flat data (only the same value) we need + // to set the high or low to 0 depending on the polarity + if (highLow.high <= highLow.low) { + // If both values are 0 we set high to 1 + if (highLow.low === 0) { + highLow.high = 1; + } else if (highLow.low < 0) { + // If we have the same negative value for the bounds we set bounds.high to 0 + highLow.high = 0; + } else if (highLow.high > 0) { + // If we have the same positive value for the bounds we set bounds.low to 0 + highLow.low = 0; + } else { + // If data array was empty, values are Number.MAX_VALUE and -Number.MAX_VALUE. Set bounds to prevent errors + highLow.high = 1; + highLow.low = 0; + } + } + + return highLow; +} diff --git a/src/core/data/index.ts b/src/core/data/index.ts new file mode 100644 index 000000000..6803b91b2 --- /dev/null +++ b/src/core/data/index.ts @@ -0,0 +1,6 @@ +export * from './bounds'; +export * from './data'; +export * from './highLow'; +export * from './normalize'; +export * from './segments'; +export * from './serialize'; diff --git a/src/core/data/normalize.spec.ts b/src/core/data/normalize.spec.ts new file mode 100644 index 000000000..f589deb92 --- /dev/null +++ b/src/core/data/normalize.spec.ts @@ -0,0 +1,222 @@ +import { normalizeData } from './normalize'; + +describe('Core', () => { + describe('Data', () => { + describe('Normalize', () => { + it('should normalize mixed series types correctly', () => { + const data = { + labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], + series: [ + { data: [1, 0, 3, 4, 5, 6] }, + [1, { value: 0 }, 3, { value: 4 }, 5, 6, 7, 8], + { data: [1, 0, { value: 3 }] } + ] + }; + + expect(normalizeData(data).series).toEqual([ + [1, 0, 3, 4, 5, 6, undefined, undefined, undefined, undefined], + [1, 0, 3, 4, 5, 6, 7, 8, undefined, undefined], + [ + 1, + 0, + 3, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined + ] + ]); + }); + + it('should normalize mixed series for pie chart correctly', () => { + const data = { + series: [1, { value: 0 }, 3, { value: 4 }, 5, 6, 7, 8] + }; + + expect(normalizeData(data).series).toEqual([1, 0, 3, 4, 5, 6, 7, 8]); + }); + + it('should normalize mixed series with string values for pie chart correctly', () => { + const data = { + series: ['1', { value: '0' }, '3', { value: '4' }, '5', '6', '7', '8'] + }; + + expect(normalizeData(data).series).toEqual([1, 0, 3, 4, 5, 6, 7, 8]); + }); + + it('should normalize mixed series types with string values correctly', () => { + const data = { + labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], + series: [ + { data: ['1', '0', '3', '4', '5', '6'] }, + ['1', { value: '0' }, '3', { value: '4' }, '5', '6', '7', '8'], + { data: ['1', '0', { value: '3' }] } + ] + }; + + expect(normalizeData(data).series).toEqual([ + [1, 0, 3, 4, 5, 6, undefined, undefined, undefined, undefined], + [1, 0, 3, 4, 5, 6, 7, 8, undefined, undefined], + [ + 1, + 0, + 3, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined + ] + ]); + }); + + it('should normalize mixed series types with weird values correctly', () => { + const data = { + labels: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], + series: [ + { data: [null, NaN, undefined, '4', '5', '6'] }, + ['1', { value: null }, '3', { value: NaN }, '5', '6', '7', '8'], + { data: ['1', '0', { value: undefined }] } + ] + }; + + expect(normalizeData(data).series).toEqual([ + [ + undefined, + undefined, + undefined, + 4, + 5, + 6, + undefined, + undefined, + undefined, + undefined + ], + [1, undefined, 3, undefined, 5, 6, 7, 8, undefined, undefined], + [ + 1, + 0, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined, + undefined + ] + ]); + }); + + it('should normalize correctly with 0 values in data series array objects', () => { + const data = { + labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'], + series: [ + { + data: [ + { value: 1 }, + { value: 4 }, + { value: 2 }, + { value: 7 }, + { value: 2 }, + { value: 0 } + ] + } + ] + }; + + expect(normalizeData(data).series).toEqual([[1, 4, 2, 7, 2, 0]]); + }); + + it('should normalize correctly with mixed dimensional input into multi dimensional output', () => { + const data = { + labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'], + series: [ + { + data: [ + { value: 1 }, + { value: { y: 4, x: 1 } }, + { y: 2, x: 2 }, + NaN, + null, + { value: 7 }, + { value: 2 }, + { value: null }, + { y: undefined, x: NaN } + ] + } + ] + }; + + expect(normalizeData(data, false, true).series).toEqual([ + [ + { x: undefined, y: 1 }, + { x: 1, y: 4 }, + { x: 2, y: 2 }, + undefined, + undefined, + { x: undefined, y: 7 }, + { x: undefined, y: 2 }, + undefined, + undefined + ] + ]); + }); + + it('should normalize boolean series correctly', () => { + const data = { + series: [[true, false, false, true]] + }; + + expect(normalizeData(data).series).toEqual([[1, 0, 0, 1]]); + }); + + it('should normalize date series correctly', () => { + const data = { + series: [[new Date(0), new Date(1), new Date(2), new Date(3)]] + }; + + expect(normalizeData(data).series).toEqual([[0, 1, 2, 3]]); + }); + + it('should align series data by holes', () => { + const data = { + series: [ + [1, 2, 3, 4], + [1, 2, 3], + [1, 2] + ] + }; + + expect(normalizeData(data).series).toEqual([ + [1, 2, 3, 4], + [1, 2, 3, undefined], + [1, 2, undefined, undefined] + ]); + }); + + it('should align series data with lables by holes', () => { + const data = { + labels: ['a', 'b', 'c', 'd', 'e', 'f'], + series: [ + [1, 2, 3, 4], + [1, 2, 3], + [1, 2] + ] + }; + + expect(normalizeData(data).series).toEqual([ + [1, 2, 3, 4, undefined, undefined], + [1, 2, 3, undefined, undefined, undefined], + [1, 2, undefined, undefined, undefined, undefined] + ]); + }); + }); + }); +}); diff --git a/src/core/data/normalize.ts b/src/core/data/normalize.ts new file mode 100644 index 000000000..3416a3205 --- /dev/null +++ b/src/core/data/normalize.ts @@ -0,0 +1,219 @@ +import type { + Data, + NormalizedData, + Multi, + AxisName, + NormalizedMulti, + Series, + FlatSeries, + NormalizedSeries, + NormalizedFlatSeries, + SeriesObject, + SeriesPrimitiveValue +} from '../types'; +import { + isArrayOfArrays, + times, + safeHasProperty, + getNumberOrUndefined +} from '../../utils'; +import { isDataHoleValue, isArrayOfSeries } from './data'; + +/** + * Ensures that the data object passed as second argument to the charts is present and correctly initialized. + * @param data The data object that is passed as second argument to the charts + * @return The normalized data object + */ +export function normalizeData( + data: Data, + reverse?: boolean, + multi?: false +): NormalizedData; +export function normalizeData( + data: Data<(Series | SeriesObject)[]>, + reverse: boolean | undefined, + multi: true | AxisName +): NormalizedData; +export function normalizeData( + data: Data, + reverse: boolean | undefined, + multi: boolean | AxisName, + distributed: true +): NormalizedData; +export function normalizeData( + data: Data, + reverse?: boolean, + multi?: boolean | AxisName +): NormalizedData; +export function normalizeData( + data: Data, + reverse = false, + multi?: boolean | AxisName, + distributed?: boolean +) { + let labelCount: number; + const normalized: NormalizedData = { + labels: (data.labels || []).slice(), + series: normalizeSeries(data.series, multi, distributed) + }; + const inputLabelCount = normalized.labels.length; + + // If all elements of the normalized data array are arrays we're dealing with + // multi series data and we need to find the largest series if they are un-even + if (isArrayOfArrays(normalized.series)) { + // Getting the series with the the most elements + labelCount = Math.max( + inputLabelCount, + ...normalized.series.map(series => series.length) + ); + + normalized.series.forEach(series => { + series.push(...times(Math.max(0, labelCount - series.length))); + }); + } else { + // We're dealing with Pie data so we just take the normalized array length + labelCount = normalized.series.length; + } + + // Padding the labels to labelCount with empty strings + normalized.labels.push( + ...times(Math.max(0, labelCount - inputLabelCount), () => '') + ); + + if (reverse) { + reverseData(normalized); + } + + return normalized; +} + +/** + * Reverses the series, labels and series data arrays. + */ +function reverseData(data: Data) { + data.labels?.reverse(); + data.series.reverse(); + for (const series of data.series) { + if (safeHasProperty(series, 'data')) { + series.data.reverse(); + } else if (Array.isArray(series)) { + series.reverse(); + } + } +} + +function normalizeMulti( + value: number | string | boolean | Date | Multi, + multi?: boolean | AxisName +) { + // We need to prepare multi value output (x and y data) + let x: number | undefined; + let y: number | undefined; + + // Single series value arrays are assumed to specify the Y-Axis value + // For example: [1, 2] => [{x: undefined, y: 1}, {x: undefined, y: 2}] + // If multi is a string then it's assumed that it specified which dimension should be filled as default + if (typeof value !== 'object') { + const num = getNumberOrUndefined(value); + + if (multi === 'x') { + x = num; + } else { + y = num; + } + } else { + if (safeHasProperty(value, 'x')) { + x = getNumberOrUndefined(value.x); + } + + if (safeHasProperty(value, 'y')) { + y = getNumberOrUndefined(value.y); + } + } + + if (x === undefined && y === undefined) { + return undefined; + } + + return { x, y } as NormalizedMulti; +} + +function normalizePrimitive( + value: SeriesPrimitiveValue, + multi?: boolean | AxisName +) { + if (isDataHoleValue(value)) { + // We're dealing with a hole in the data and therefore need to return undefined + // We're also returning undefined for multi value output + return undefined; + } + + if (multi) { + return normalizeMulti(value, multi); + } + + return getNumberOrUndefined(value); +} + +function normalizeSingleSeries( + series: Series | SeriesObject, + multi?: boolean | AxisName +): NormalizedSeries { + if (!Array.isArray(series)) { + // We are dealing with series object notation so we need to recurse on data property + return normalizeSingleSeries(series.data, multi); + } + + return series.map(value => { + if (safeHasProperty(value, 'value')) { + // We are dealing with value object notation so we need to recurse on value property + return normalizePrimitive(value.value, multi); + } + + return normalizePrimitive(value, multi); + }); +} + +/** + * Convert data series into plain array + * @param series The series object that contains the data to be visualized in the chart + * @param multi Create a multi dimensional array from a series data array where a value object with `x` and `y` values will be created. + * @return A plain array that contains the data to be visualized in the chart + */ +function normalizeSeries( + series: FlatSeries, + multi?: false, + distributed?: false +): NormalizedFlatSeries; +function normalizeSeries( + series: (Series | SeriesObject)[], + multi: true | AxisName, + distributed?: false +): NormalizedSeries[]; +function normalizeSeries( + series: FlatSeries | (Series | SeriesObject)[], + multi: boolean | undefined | AxisName, + distributed: true +): NormalizedSeries[]; +function normalizeSeries( + series: FlatSeries | (Series | SeriesObject)[], + multi?: boolean | undefined | AxisName, + distributed?: boolean +): NormalizedFlatSeries | NormalizedSeries[]; +function normalizeSeries( + series: FlatSeries | (Series | SeriesObject)[], + multi?: boolean | undefined | AxisName, + distributed?: boolean +) { + if (isArrayOfSeries(series)) { + return series.map(_ => normalizeSingleSeries(_, multi)); + } + + const normalizedSeries = normalizeSingleSeries(series, multi); + + if (distributed) { + return normalizedSeries.map(value => [value]); + } + + return normalizedSeries; +} diff --git a/src/core/data/segments.spec.ts b/src/core/data/segments.spec.ts new file mode 100644 index 000000000..2052e29a9 --- /dev/null +++ b/src/core/data/segments.spec.ts @@ -0,0 +1,84 @@ +import { splitIntoSegments } from './segments'; + +describe('Core', () => { + describe('Data', () => { + describe('Segments', () => { + function makeValues(arr: T[]) { + return arr.map((x, i) => ({ value: x, valueIndex: i })); + } + + it('should return empty array for empty input', () => { + expect(splitIntoSegments([], [])).toEqual([]); + }); + + it('should remove undefined values', () => { + const coords = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; + const values = makeValues([1, undefined, undefined, 4, undefined, 6]); + + expect(splitIntoSegments(coords, values)).toEqual([ + { + pathCoordinates: [1, 2], + valueData: [{ value: 1, valueIndex: 0 }] + }, + { + pathCoordinates: [7, 8], + valueData: [{ value: 4, valueIndex: 3 }] + }, + { + pathCoordinates: [11, 12], + valueData: [{ value: 6, valueIndex: 5 }] + } + ]); + }); + + it('should respect fillHoles option', () => { + const coords = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]; + const values = makeValues([1, undefined, undefined, 4, undefined, 6]); + const options = { + fillHoles: true + }; + + expect(splitIntoSegments(coords, values, options)).toEqual([ + { + pathCoordinates: [1, 2, 7, 8, 11, 12], + valueData: [ + { value: 1, valueIndex: 0 }, + { value: 4, valueIndex: 3 }, + { value: 6, valueIndex: 5 } + ] + } + ]); + }); + + it('should respect increasingX option', () => { + const coords = [1, 2, 3, 4, 5, 6, 5, 6, 7, 8, 1, 2]; + const values = makeValues([1, 2, 3, 4, 5, 6]); + const options = { + increasingX: true + }; + + expect(splitIntoSegments(coords, values, options)).toEqual([ + { + pathCoordinates: [1, 2, 3, 4, 5, 6], + valueData: [ + { value: 1, valueIndex: 0 }, + { value: 2, valueIndex: 1 }, + { value: 3, valueIndex: 2 } + ] + }, + { + pathCoordinates: [5, 6, 7, 8], + valueData: [ + { value: 4, valueIndex: 3 }, + { value: 5, valueIndex: 4 } + ] + }, + { + pathCoordinates: [1, 2], + valueData: [{ value: 6, valueIndex: 5 }] + } + ]); + }); + }); + }); +}); diff --git a/src/core/data/segments.ts b/src/core/data/segments.ts new file mode 100644 index 000000000..778671890 --- /dev/null +++ b/src/core/data/segments.ts @@ -0,0 +1,81 @@ +import type { Segment, SegmentData } from '../types'; +import { getMultiValue } from './data'; + +/** + * Splits a list of coordinates and associated values into segments. Each returned segment contains a pathCoordinates + * valueData property describing the segment. + * + * With the default options, segments consist of contiguous sets of points that do not have an undefined value. Any + * points with undefined values are discarded. + * + * **Options** + * The following options are used to determine how segments are formed + * ```javascript + * var options = { + * // If fillHoles is true, undefined values are simply discarded without creating a new segment. Assuming other options are default, this returns single segment. + * fillHoles: false, + * // If increasingX is true, the coordinates in all segments have strictly increasing x-values. + * increasingX: false + * }; + * ``` + * + * @param pathCoordinates List of point coordinates to be split in the form [x1, y1, x2, y2 ... xn, yn] + * @param valueData List of associated point values in the form [v1, v2 .. vn] + * @param options Options set by user + * @return List of segments, each containing a pathCoordinates and valueData property. + */ +export function splitIntoSegments( + pathCoordinates: number[], + valueData: SegmentData[], + options?: { + increasingX?: boolean; + fillHoles?: boolean; + } +) { + const finalOptions = { + increasingX: false, + fillHoles: false, + ...options + }; + + const segments: Segment[] = []; + let hole = true; + + for (let i = 0; i < pathCoordinates.length; i += 2) { + // If this value is a "hole" we set the hole flag + if (getMultiValue(valueData[i / 2].value) === undefined) { + // if(valueData[i / 2].value === undefined) { + if (!finalOptions.fillHoles) { + hole = true; + } + } else { + if ( + finalOptions.increasingX && + i >= 2 && + pathCoordinates[i] <= pathCoordinates[i - 2] + ) { + // X is not increasing, so we need to make sure we start a new segment + hole = true; + } + + // If it's a valid value we need to check if we're coming out of a hole and create a new empty segment + if (hole) { + segments.push({ + pathCoordinates: [], + valueData: [] + }); + // As we have a valid value now, we are not in a "hole" anymore + hole = false; + } + + // Add to the segment pathCoordinates and valueData + segments[segments.length - 1].pathCoordinates.push( + pathCoordinates[i], + pathCoordinates[i + 1] + ); + segments[segments.length - 1].valueData.push(valueData[i / 2]); + } + } + + return segments; +} diff --git a/src/core/data/serialize.spec.ts b/src/core/data/serialize.spec.ts new file mode 100644 index 000000000..7c1126d5f --- /dev/null +++ b/src/core/data/serialize.spec.ts @@ -0,0 +1,48 @@ +import { serialize, deserialize } from './serialize'; + +describe('Core', () => { + describe('Data', () => { + describe('Serialize', () => { + it('should serialize and deserialize regular strings', () => { + const input = 'String test'; + expect(input).toMatch(deserialize(serialize(input))); + }); + + it('should serialize and deserialize strings with critical characters', () => { + const input = 'String test with critical characters " < > \' & &'; + expect(input).toMatch(deserialize(serialize(input))); + }); + + it('should serialize and deserialize numbers', () => { + const input = 12345.6789; + expect(input).toEqual(deserialize(serialize(input))); + }); + + it('should serialize and deserialize dates', () => { + const input = new Date(0); + expect(+input).toEqual(+new Date(deserialize(serialize(input)))); + }); + + it('should serialize and deserialize complex object types', () => { + const input = { + a: { + b: 100, + c: 'String test', + d: 'String test with critical characters " < > \' & &', + e: { + f: 'String test' + } + } + }; + + expect(input).toEqual(deserialize(serialize(input))); + }); + + it('should serialize and deserialize null, undefined and NaN', () => { + expect(null).toEqual(deserialize(serialize(null))); + expect(undefined).toEqual(deserialize(serialize(undefined))); + expect(deserialize(serialize(NaN))).toBeNaN(); + }); + }); + }); +}); diff --git a/src/core/data/serialize.ts b/src/core/data/serialize.ts new file mode 100644 index 000000000..ac27d44ac --- /dev/null +++ b/src/core/data/serialize.ts @@ -0,0 +1,68 @@ +import { escapingMap } from '../constants'; + +/** + * This function serializes arbitrary data to a string. In case of data that can't be easily converted to a string, this function will create a wrapper object and serialize the data using JSON.stringify. The outcoming string will always be escaped using Chartist.escapingMap. + * If called with null or undefined the function will return immediately with null or undefined. + */ +export function serialize(data: number | string | object): string; +export function serialize( + data: number | string | object | null | undefined | unknown +): string | null | undefined; +export function serialize( + data: number | string | object | null | undefined | unknown +) { + let serialized = ''; + + if (data === null || data === undefined) { + return data; + } else if (typeof data === 'number') { + serialized = '' + data; + } else if (typeof data === 'object') { + serialized = JSON.stringify({ data: data }); + } else { + serialized = String(data); + } + + return Object.keys(escapingMap).reduce( + (result, key) => result.replaceAll(key, escapingMap[key]), + serialized + ); +} + +/** + * This function de-serializes a string previously serialized with Chartist.serialize. The string will always be unescaped using Chartist.escapingMap before it's returned. Based on the input value the return type can be Number, String or Object. JSON.parse is used with try / catch to see if the unescaped string can be parsed into an Object and this Object will be returned on success. + */ +export function deserialize( + data: string +): T; +export function deserialize( + data: string | null | undefined +): T | null | undefined; +export function deserialize(data: unknown) { + if (typeof data !== 'string') { + return data; + } + + if (data === 'NaN') { + return NaN; + } + + data = Object.keys(escapingMap).reduce( + (result, key) => result.replaceAll(escapingMap[key], key), + data + ); + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let parsedData: any = data; + + if (typeof data === 'string') { + try { + parsedData = JSON.parse(data); + parsedData = parsedData.data !== undefined ? parsedData.data : parsedData; + } catch (e) { + /* Ingore */ + } + } + + return parsedData; +} diff --git a/src/core/index.ts b/src/core/index.ts new file mode 100644 index 000000000..17cbb96f2 --- /dev/null +++ b/src/core/index.ts @@ -0,0 +1,7 @@ +export * from './constants'; +export * from './lang'; +export * from './math'; +export * from './data'; +export * from './creation'; +export * from './optionsProvider'; +export * from './types'; diff --git a/src/core/lang.spec.ts b/src/core/lang.spec.ts new file mode 100644 index 000000000..92c8708f6 --- /dev/null +++ b/src/core/lang.spec.ts @@ -0,0 +1,26 @@ +import { quantity } from './lang'; + +describe('Core', () => { + describe('Lang', () => { + describe('quantity', () => { + it('should return value for numbers', () => { + expect(quantity(100)).toEqual({ value: 100 }); + expect(quantity(0)).toEqual({ value: 0 }); + expect(quantity(NaN)).toEqual({ value: NaN }); + expect(quantity(null)).toEqual({ value: 0 }); + expect(quantity(undefined)).toEqual({ value: NaN }); + }); + + it('should return value without unit from string', () => { + expect(quantity('100')).toEqual({ value: 100, unit: undefined }); + expect(quantity('0')).toEqual({ value: 0, unit: undefined }); + }); + + it('should return value and unit from string', () => { + expect(quantity('100%')).toEqual({ value: 100, unit: '%' }); + expect(quantity('100 %')).toEqual({ value: 100, unit: '%' }); + expect(quantity('0px')).toEqual({ value: 0, unit: 'px' }); + }); + }); + }); +}); diff --git a/src/core/lang.ts b/src/core/lang.ts new file mode 100644 index 000000000..311876a47 --- /dev/null +++ b/src/core/lang.ts @@ -0,0 +1,39 @@ +/** + * Converts a number to a string with a unit. If a string is passed then this will be returned unmodified. + * @return Returns the passed number value with unit. + */ +export function ensureUnit(value: T, unit: string) { + if (typeof value === 'number') { + return value + unit; + } + + return value; +} + +/** + * Converts a number or string to a quantity object. + * @return Returns an object containing the value as number and the unit as string. + */ +export function quantity(input: T) { + if (typeof input === 'string') { + const match = /^(\d+)\s*(.*)$/g.exec(input); + return { + value: match ? +match[1] : 0, + unit: match?.[2] || undefined + }; + } + + return { + value: Number(input) + }; +} + +/** + * Generates a-z from a number 0 to 26 + * @param n A number from 0 to 26 that will result in a letter a-z + * @return A character from a-z based on the input number n + */ +export function alphaNumerate(n: number) { + // Limit to a-z + return String.fromCharCode(97 + (n % 26)); +} diff --git a/src/core/math.ts b/src/core/math.ts new file mode 100644 index 000000000..66797ab34 --- /dev/null +++ b/src/core/math.ts @@ -0,0 +1,100 @@ +import type { Bounds } from './types'; +import { precision as globalPrecision } from './constants'; + +export const EPSILON = 2.221e-16; + +/** + * Calculate the order of magnitude for the chart scale + * @param value The value Range of the chart + * @return The order of magnitude + */ +export function orderOfMagnitude(value: number) { + return Math.floor(Math.log(Math.abs(value)) / Math.LN10); +} + +/** + * Project a data length into screen coordinates (pixels) + * @param axisLength The svg element for the chart + * @param length Single data value from a series array + * @param bounds All the values to set the bounds of the chart + * @return The projected data length in pixels + */ +export function projectLength( + axisLength: number, + length: number, + bounds: Bounds +) { + return (length / bounds.range) * axisLength; +} + +/** + * This helper function can be used to round values with certain precision level after decimal. This is used to prevent rounding errors near float point precision limit. + * @param value The value that should be rounded with precision + * @param [digits] The number of digits after decimal used to do the rounding + * @returns Rounded value + */ +export function roundWithPrecision(value: number, digits?: number) { + const precision = Math.pow(10, digits || globalPrecision); + return Math.round(value * precision) / precision; +} + +/** + * Pollard Rho Algorithm to find smallest factor of an integer value. There are more efficient algorithms for factorization, but this one is quite efficient and not so complex. + * @param num An integer number where the smallest factor should be searched for + * @returns The smallest integer factor of the parameter num. + */ +export function rho(num: number) { + if (num === 1) { + return num; + } + + function gcd(p: number, q: number): number { + if (p % q === 0) { + return q; + } else { + return gcd(q, p % q); + } + } + + function f(x: number) { + return x * x + 1; + } + + let x1 = 2; + let x2 = 2; + let divisor: number; + + if (num % 2 === 0) { + return 2; + } + + do { + x1 = f(x1) % num; + x2 = f(f(x2)) % num; + divisor = gcd(Math.abs(x1 - x2), num); + } while (divisor === 1); + + return divisor; +} + +/** + * Calculate cartesian coordinates of polar coordinates + * @param centerX X-axis coordinates of center point of circle segment + * @param centerY X-axis coordinates of center point of circle segment + * @param radius Radius of circle segment + * @param angleInDegrees Angle of circle segment in degrees + * @return Coordinates of point on circumference + */ +export function polarToCartesian( + centerX: number, + centerY: number, + radius: number, + angleInDegrees: number +) { + const angleInRadians = ((angleInDegrees - 90) * Math.PI) / 180.0; + + return { + x: centerX + radius * Math.cos(angleInRadians), + y: centerY + radius * Math.sin(angleInRadians) + }; +} diff --git a/src/core/optionsProvider.ts b/src/core/optionsProvider.ts new file mode 100644 index 000000000..05f91d2a9 --- /dev/null +++ b/src/core/optionsProvider.ts @@ -0,0 +1,72 @@ +import type { EventEmitter } from '../event'; +import type { OptionsChangedEvent, ResponsiveOptions } from './types'; +import { extend } from '../utils'; + +export interface OptionsProvider { + removeMediaQueryListeners(): void; + getCurrentOptions(): T; +} + +/** + * Provides options handling functionality with callback for options changes triggered by responsive options and media query matches + * @param options Options set by user + * @param responsiveOptions Optional functions to add responsive behavior to chart + * @param eventEmitter The event emitter that will be used to emit the options changed events + * @return The consolidated options object from the defaults, base and matching responsive options + */ +export function optionsProvider( + options: T, + responsiveOptions: ResponsiveOptions | undefined, + eventEmitter: EventEmitter +): OptionsProvider { + let currentOptions: T; + const mediaQueryListeners: MediaQueryList[] = []; + + function updateCurrentOptions(mediaEvent?: Event) { + const previousOptions = currentOptions; + currentOptions = extend({}, options); + + if (responsiveOptions) { + responsiveOptions.forEach(responsiveOption => { + const mql = window.matchMedia(responsiveOption[0]); + if (mql.matches) { + currentOptions = extend({}, currentOptions, responsiveOption[1]); + } + }); + } + + if (eventEmitter && mediaEvent) { + eventEmitter.emit>('optionsChanged', { + previousOptions, + currentOptions + }); + } + } + + function removeMediaQueryListeners() { + mediaQueryListeners.forEach(mql => + mql.removeEventListener('change', updateCurrentOptions) + ); + } + + if (!window.matchMedia) { + throw new Error( + "window.matchMedia not found! Make sure you're using a polyfill." + ); + } else if (responsiveOptions) { + responsiveOptions.forEach(responsiveOption => { + const mql = window.matchMedia(responsiveOption[0]); + mql.addEventListener('change', updateCurrentOptions); + mediaQueryListeners.push(mql); + }); + } + // Execute initially without an event argument so we get the correct options + updateCurrentOptions(); + + return { + removeMediaQueryListeners, + getCurrentOptions() { + return currentOptions; + } + }; +} diff --git a/src/core/types.ts b/src/core/types.ts new file mode 100644 index 000000000..a6fbefb1f --- /dev/null +++ b/src/core/types.ts @@ -0,0 +1,372 @@ +import type { RequiredKeys } from '../utils'; +import type { Axis, AxisType } from '../axes'; +import type { Svg } from '../svg'; + +export interface ChartPadding { + top: number; + right: number; + bottom: number; + left: number; +} + +export interface ChartRect { + x1: number; + x2: number; + y1: number; + y2: number; + padding: ChartPadding; + width(): number; + height(): number; +} + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export type Plugin = (chart: any, options?: any) => void; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export type Meta = any; + +export interface ViewBox { + width: number; + height: number; +} + +export interface Options< + TXAxisOptions = AxisOptions, + TYAxisOptions = TXAxisOptions +> { + /** + * Specify a fixed width for the chart as a string (i.e. '100px' or '50%') + */ + width?: number | string; + /** + * Specify a fixed height for the chart as a string (i.e. '100px' or '50%') + */ + height?: number | string; + /** + * Overriding the natural low of the chart allows you to zoom in or limit the charts lowest displayed value + */ + low?: number; + /** + * Overriding the natural high of the chart allows you to zoom in or limit the charts highest displayed value + */ + high?: number; + /** + * Unless low/high are explicitly set, bar chart will be centered at zero by default. Set referenceValue to null to auto scale. + */ + referenceValue?: number; + /** + * Padding of the chart drawing area to the container element and labels as a number or padding object. + */ + chartPadding?: number | Partial; + /** + * Options for X-Axis + */ + axisX?: TXAxisOptions; + /** + * Options for Y-Axis + */ + axisY?: TYAxisOptions; + /** + * Override the class names that get used to generate the SVG structure of the chart + */ + classNames?: Record; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + plugins?: (Plugin | [Plugin, any])[]; + /** + * Define the ViewBox for an SVG, this is optional and only required if you need a scalable chart. This should be used together with responsive options to ensure a proper text size. + */ + viewBox?: ViewBox; +} + +export interface AxisOptions { + type?: AxisType; + /** + * Overriding the natural low of the chart allows you to zoom in or limit the charts lowest displayed value + */ + low?: number; + /** + * Overriding the natural high of the chart allows you to zoom in or limit the charts highest displayed value + */ + high?: number; + /** + * Unless low/high are explicitly set, bar chart will be centered at zero by default. Set referenceValue to null to auto scale. + */ + referenceValue?: number; + /** + * The offset of the chart drawing area to the border of the container + */ + offset?: number; + /** + * Position where labels are placed. + * Can be set to `start` or `end` where `start` is equivalent to left or top on vertical axis and `end` is equivalent to right or bottom on horizontal axis. + */ + position?: 'start' | 'end'; + /** + * Allows you to correct label positioning on this axis by positive or negative x and y offset. + */ + labelOffset?: { + x: number; + y: number; + }; + /** + * If labels should be shown or not + */ + showLabel?: boolean; + /** + * If the axis grid should be drawn or not + */ + showGrid?: boolean; + /** + * Interpolation function that allows you to intercept the value from the axis label + */ + labelInterpolationFnc?(value: Label, index: number): Label | null | undefined; + /** + * This value specifies the minimum width in pixel of the scale steps + */ + scaleMinSpace?: number; + /** + * Use only integer values (whole numbers) for the scale steps + */ + onlyInteger?: boolean; + ticks?: Label[]; + stretch?: boolean; + divisor?: number; + highLow?: { + high: number; + low: number; + }; +} + +export type OptionsWithDefaults = RequiredKeys< + Options< + RequiredKeys< + AxisOptions, + 'offset' | 'labelOffset' | 'labelInterpolationFnc' + >, + RequiredKeys< + AxisOptions, + 'offset' | 'labelOffset' | 'labelInterpolationFnc' + > + >, + 'axisX' | 'axisY' | 'classNames' +>; + +export type ResponsiveOptions = [string, T][]; + +export interface Bounds { + high: number; + low: number; + valueRange: number; + oom: number; + step: number; + min: number; + max: number; + range: number; + numberOfSteps: number; + values: number[]; +} + +export interface Segment { + pathCoordinates: number[]; + valueData: SegmentData[]; +} + +export interface SegmentData { + value: NormalizedSeriesValue; + valueIndex: number; + meta?: Meta; +} + +export type AxisName = 'x' | 'y'; + +export type Multi = + | { + x: number | string | Date | null; + y: number | string | Date | null; + } + | { + x: number | string | Date | null; + } + | { + y: number | string | Date | null; + }; + +export type NormalizedMulti = + | { + x: number; + y: number; + } + | { + x: number; + } + | { + y: number; + }; + +/** + * Data + */ + +export type Label = string | number | Date; + +export type AllSeriesTypes = FlatSeries | (Series | SeriesObject)[]; + +export interface Data { + labels?: Label[] | undefined; + series: T; +} + +/** + * Series + */ + +export type Series = SeriesValue[]; + +export interface SeriesObject { + name?: string; + className?: string; + meta?: Meta; + data: SeriesValue[]; +} + +export type SeriesValue = SeriesObjectValue | T; + +export type SeriesPrimitiveValue = + | number + | string + | boolean + | Date + | Multi + | null + | undefined; + +export interface SeriesObjectValue { + meta?: Meta; + value: T; +} + +/** + * Flat Series + */ + +export type FlatSeries = FlatSeriesValue[]; + +export type FlatSeriesValue = + | SeriesValue + | FlatSeriesObjectValue; + +export type FlatSeriesPrimitiveValue = number | string | null | undefined; + +export interface FlatSeriesObjectValue { + name?: string; + className?: string; + meta?: Meta; + value: T; +} + +/** + * Normalized Data + */ + +export type AllNormalizedSeriesTypes = + | NormalizedFlatSeries + | NormalizedSeries[]; + +export interface NormalizedData< + T extends AllNormalizedSeriesTypes = AllNormalizedSeriesTypes +> extends Data { + labels: Label[]; + series: T; +} + +/** + * Normalized Series + */ + +export type NormalizedSeries = NormalizedSeriesValue[]; + +export type NormalizedSeriesValue = NormalizedSeriesPrimitiveValue; + +export type NormalizedSeriesPrimitiveValue = + | number + | NormalizedMulti + | undefined; + +/** + * Normalized Flat Series + */ + +export type NormalizedFlatSeries = number[]; + +/** + * Events + */ + +export interface CreatedEvent { + chartRect: ChartRect; + axisX: Axis; + axisY: Axis; + svg: Svg; + options: TOptions; +} + +export interface DrawEvent { + type: string; + element: Svg; + group: Svg; + chartRect: ChartRect; + axisX: Axis; + axisY: Axis; + meta: Meta; + index: number; + series: FlatSeriesValue | Series | SeriesObject; + seriesIndex: number; +} + +export interface DataEvent { + type: 'initial' | 'update'; + data: Data; +} + +export interface OptionsChangedEvent { + previousOptions: T; + currentOptions: T; +} + +export interface GridDrawEvent + extends Omit< + DrawEvent, + 'chartRect' | 'axisX' | 'axisY' | 'meta' | 'series' | 'seriesIndex' + > { + type: 'grid'; + axis: Axis; + x1: number; + y1: number; + x2: number; + y2: number; +} + +export interface GridBackgroundDrawEvent { + type: 'gridBackground'; + group: Svg; + element: Svg; +} + +export interface LabelDrawEvent + extends Omit< + DrawEvent, + 'chartRect' | 'axisX' | 'axisY' | 'meta' | 'series' | 'seriesIndex' + > { + type: 'label'; + axis: Axis; + text: Label; + x: number; + y: number; + width: number; + height: number; +} + +export type AxesDrawEvent = + | GridDrawEvent + | GridBackgroundDrawEvent + | LabelDrawEvent; diff --git a/src/event/EventEmitter.ts b/src/event/EventEmitter.ts new file mode 100644 index 000000000..923aca876 --- /dev/null +++ b/src/event/EventEmitter.ts @@ -0,0 +1,82 @@ +/* eslint-disable @typescript-eslint/no-explicit-any */ +export type EventListener = (data: T) => void; + +export type AllEventsListener = (event: string, data: T) => void; + +export class EventEmitter { + private readonly listeners = new Map>(); + private readonly allListeners = new Set(); + + /** + * Add an event handler for a specific event + * @param event The event name + * @param listener A event handler function + */ + on(event: '*', listener: AllEventsListener): void; + on(event: string, listener: EventListener): void; + on(event: string, listener: EventListener | AllEventsListener) { + const { allListeners, listeners } = this; + + if (event === '*') { + allListeners.add(listener); + } else { + if (!listeners.has(event)) { + listeners.set(event, new Set()); + } + + (listeners.get(event) as Set).add( + listener as EventListener + ); + } + } + + /** + * Remove an event handler of a specific event name or remove all event handlers for a specific event. + * @param event The event name where a specific or all handlers should be removed + * @param [listener] An optional event handler function. If specified only this specific handler will be removed and otherwise all handlers are removed. + */ + off(event: '*', listener?: AllEventsListener): void; + off(event: string, listener?: EventListener): void; + off(event: string, listener?: EventListener | AllEventsListener) { + const { allListeners, listeners } = this; + + if (event === '*') { + if (listener) { + allListeners.delete(listener); + } else { + allListeners.clear(); + } + } else if (listeners.has(event)) { + const eventListeners = listeners.get(event) as Set; + + if (listener) { + eventListeners.delete(listener as EventListener); + } else { + eventListeners.clear(); + } + + if (!eventListeners.size) { + listeners.delete(event); + } + } + } + + /** + * Use this function to emit an event. All handlers that are listening for this event will be triggered with the data parameter. + * @param event The event name that should be triggered + * @param data Arbitrary data that will be passed to the event handler callback functions + */ + emit(event: string, data: T) { + const { allListeners, listeners } = this; + + // Only do something if there are event handlers with this name existing + if (listeners.has(event)) { + (listeners.get(event) as Set).forEach(listener => + listener(data) + ); + } + + // Emit event to star event handlers + allListeners.forEach(listener => listener(event, data)); + } +} diff --git a/src/event/index.ts b/src/event/index.ts new file mode 100644 index 000000000..1a0d45706 --- /dev/null +++ b/src/event/index.ts @@ -0,0 +1 @@ +export * from './EventEmitter'; diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 000000000..0564dee9d --- /dev/null +++ b/src/index.ts @@ -0,0 +1,7 @@ +export * from './core'; +export * from './event'; +export * from './charts'; +export * from './axes'; +export * as Interpolation from './interpolation'; +export * from './svg'; +export * from './utils'; diff --git a/src/interpolation/cardinal.ts b/src/interpolation/cardinal.ts new file mode 100644 index 000000000..46a53d1aa --- /dev/null +++ b/src/interpolation/cardinal.ts @@ -0,0 +1,132 @@ +import type { SegmentData } from '../core'; +import { splitIntoSegments } from '../core'; +import { SvgPath } from '../svg'; +import { none } from './none'; + +export interface CardinalInterpolationOptions { + tension?: number; + fillHoles?: boolean; +} + +/** + * Cardinal / Catmull-Rome spline interpolation is the default smoothing function in Chartist. It produces nice results where the splines will always meet the points. It produces some artifacts though when data values are increased or decreased rapidly. The line may not follow a very accurate path and if the line should be accurate this smoothing function does not produce the best results. + * + * Cardinal splines can only be created if there are more than two data points. If this is not the case this smoothing will fallback to `Chartist.Smoothing.none`. + * + * All smoothing functions within Chartist are factory functions that accept an options parameter. The cardinal interpolation function accepts one configuration parameter `tension`, between 0 and 1, which controls the smoothing intensity. + * + * @example + * ```ts + * const chart = new LineChart('.ct-chart', { + * labels: [1, 2, 3, 4, 5], + * series: [[1, 2, 8, 1, 7]] + * }, { + * lineSmooth: Interpolation.cardinal({ + * tension: 1, + * fillHoles: false + * }) + * }); + * ``` + * + * @param options The options of the cardinal factory function. + */ +export function cardinal(options?: CardinalInterpolationOptions) { + const finalOptions = { + tension: 1, + fillHoles: false, + ...options + }; + + const t = Math.min(1, Math.max(0, finalOptions.tension)); + const c = 1 - t; + + return function cardinalInterpolation( + pathCoordinates: number[], + valueData: SegmentData[] + ): SvgPath { + // First we try to split the coordinates into segments + // This is necessary to treat "holes" in line charts + const segments = splitIntoSegments(pathCoordinates, valueData, { + fillHoles: finalOptions.fillHoles + }); + + if (!segments.length) { + // If there were no segments return 'none' interpolation + return none()([], []); + } else if (segments.length > 1) { + // If the split resulted in more that one segment we need to interpolate each segment individually and join them + // afterwards together into a single path. + // For each segment we will recurse the cardinal function + // Join the segment path data into a single path and return + return SvgPath.join( + segments.map(segment => + cardinalInterpolation(segment.pathCoordinates, segment.valueData) + ) + ); + } else { + // If there was only one segment we can proceed regularly by using pathCoordinates and valueData from the first + // segment + pathCoordinates = segments[0].pathCoordinates; + valueData = segments[0].valueData; + + // If less than two points we need to fallback to no smoothing + if (pathCoordinates.length <= 4) { + return none()(pathCoordinates, valueData); + } + + const path = new SvgPath().move( + pathCoordinates[0], + pathCoordinates[1], + false, + valueData[0] + ); + const z = false; + + for ( + let i = 0, iLen = pathCoordinates.length; + iLen - 2 * Number(!z) > i; + i += 2 + ) { + const p = [ + { x: +pathCoordinates[i - 2], y: +pathCoordinates[i - 1] }, + { x: +pathCoordinates[i], y: +pathCoordinates[i + 1] }, + { x: +pathCoordinates[i + 2], y: +pathCoordinates[i + 3] }, + { x: +pathCoordinates[i + 4], y: +pathCoordinates[i + 5] } + ]; + + if (z) { + if (!i) { + p[0] = { + x: +pathCoordinates[iLen - 2], + y: +pathCoordinates[iLen - 1] + }; + } else if (iLen - 4 === i) { + p[3] = { x: +pathCoordinates[0], y: +pathCoordinates[1] }; + } else if (iLen - 2 === i) { + p[2] = { x: +pathCoordinates[0], y: +pathCoordinates[1] }; + p[3] = { x: +pathCoordinates[2], y: +pathCoordinates[3] }; + } + } else { + if (iLen - 4 === i) { + p[3] = p[2]; + } else if (!i) { + p[0] = { x: +pathCoordinates[i], y: +pathCoordinates[i + 1] }; + } + } + + path.curve( + (t * (-p[0].x + 6 * p[1].x + p[2].x)) / 6 + c * p[2].x, + (t * (-p[0].y + 6 * p[1].y + p[2].y)) / 6 + c * p[2].y, + (t * (p[1].x + 6 * p[2].x - p[3].x)) / 6 + c * p[2].x, + (t * (p[1].y + 6 * p[2].y - p[3].y)) / 6 + c * p[2].y, + p[2].x, + p[2].y, + false, + valueData[(i + 2) / 2] + ); + } + + return path; + } + }; +} diff --git a/src/interpolation/index.ts b/src/interpolation/index.ts new file mode 100644 index 000000000..5ed6a30c6 --- /dev/null +++ b/src/interpolation/index.ts @@ -0,0 +1,5 @@ +export * from './none'; +export * from './simple'; +export * from './step'; +export * from './cardinal'; +export * from './monotoneCubic'; diff --git a/src/interpolation/monotoneCubic.ts b/src/interpolation/monotoneCubic.ts new file mode 100644 index 000000000..9f664bbca --- /dev/null +++ b/src/interpolation/monotoneCubic.ts @@ -0,0 +1,138 @@ +import type { SegmentData } from '../core'; +import { splitIntoSegments } from '../core'; +import { SvgPath } from '../svg'; +import { none } from './none'; + +export interface MonotoneCubicInterpolationOptions { + fillHoles?: boolean; +} + +/** + * Monotone Cubic spline interpolation produces a smooth curve which preserves monotonicity. Unlike cardinal splines, the curve will not extend beyond the range of y-values of the original data points. + * + * Monotone Cubic splines can only be created if there are more than two data points. If this is not the case this smoothing will fallback to `Chartist.Smoothing.none`. + * + * The x-values of subsequent points must be increasing to fit a Monotone Cubic spline. If this condition is not met for a pair of adjacent points, then there will be a break in the curve between those data points. + * + * All smoothing functions within Chartist are factory functions that accept an options parameter. + * + * @example + * ```ts + * const chart = new LineChart('.ct-chart', { + * labels: [1, 2, 3, 4, 5], + * series: [[1, 2, 8, 1, 7]] + * }, { + * lineSmooth: Interpolation.monotoneCubic({ + * fillHoles: false + * }) + * }); + * ``` + * + * @param options The options of the monotoneCubic factory function. + */ +export function monotoneCubic(options?: MonotoneCubicInterpolationOptions) { + const finalOptions = { + fillHoles: false, + ...options + }; + + return function monotoneCubicInterpolation( + pathCoordinates: number[], + valueData: SegmentData[] + ): SvgPath { + // First we try to split the coordinates into segments + // This is necessary to treat "holes" in line charts + const segments = splitIntoSegments(pathCoordinates, valueData, { + fillHoles: finalOptions.fillHoles, + increasingX: true + }); + + if (!segments.length) { + // If there were no segments return 'Chartist.Interpolation.none' + return none()([], []); + } else if (segments.length > 1) { + // If the split resulted in more that one segment we need to interpolate each segment individually and join them + // afterwards together into a single path. + // For each segment we will recurse the monotoneCubic fn function + // Join the segment path data into a single path and return + return SvgPath.join( + segments.map(segment => + monotoneCubicInterpolation(segment.pathCoordinates, segment.valueData) + ) + ); + } else { + // If there was only one segment we can proceed regularly by using pathCoordinates and valueData from the first + // segment + pathCoordinates = segments[0].pathCoordinates; + valueData = segments[0].valueData; + + // If less than three points we need to fallback to no smoothing + if (pathCoordinates.length <= 4) { + return none()(pathCoordinates, valueData); + } + + const xs = []; + const ys = []; + const n = pathCoordinates.length / 2; + const ms = []; + const ds = []; + const dys = []; + const dxs = []; + + // Populate x and y coordinates into separate arrays, for readability + for (let i = 0; i < n; i++) { + xs[i] = pathCoordinates[i * 2]; + ys[i] = pathCoordinates[i * 2 + 1]; + } + + // Calculate deltas and derivative + for (let i = 0; i < n - 1; i++) { + dys[i] = ys[i + 1] - ys[i]; + dxs[i] = xs[i + 1] - xs[i]; + ds[i] = dys[i] / dxs[i]; + } + + // Determine desired slope (m) at each point using Fritsch-Carlson method + // See: http://math.stackexchange.com/questions/45218/implementation-of-monotone-cubic-interpolation + ms[0] = ds[0]; + ms[n - 1] = ds[n - 2]; + + for (let i = 1; i < n - 1; i++) { + if (ds[i] === 0 || ds[i - 1] === 0 || ds[i - 1] > 0 !== ds[i] > 0) { + ms[i] = 0; + } else { + ms[i] = + (3 * (dxs[i - 1] + dxs[i])) / + ((2 * dxs[i] + dxs[i - 1]) / ds[i - 1] + + (dxs[i] + 2 * dxs[i - 1]) / ds[i]); + + if (!isFinite(ms[i])) { + ms[i] = 0; + } + } + } + + // Now build a path from the slopes + const path = new SvgPath().move(xs[0], ys[0], false, valueData[0]); + + for (let i = 0; i < n - 1; i++) { + path.curve( + // First control point + xs[i] + dxs[i] / 3, + ys[i] + (ms[i] * dxs[i]) / 3, + // Second control point + xs[i + 1] - dxs[i] / 3, + ys[i + 1] - (ms[i + 1] * dxs[i]) / 3, + // End point + xs[i + 1], + ys[i + 1], + + false, + valueData[i + 1] + ); + } + + return path; + } + }; +} diff --git a/src/interpolation/none.ts b/src/interpolation/none.ts new file mode 100644 index 000000000..b4e074e65 --- /dev/null +++ b/src/interpolation/none.ts @@ -0,0 +1,57 @@ +import type { SegmentData } from '../core'; +import { getMultiValue } from '../core'; +import { SvgPath } from '../svg'; + +export interface NoneInterpolationOptions { + fillHoles?: boolean; +} + +/** + * This interpolation function does not smooth the path and the result is only containing lines and no curves. + * + * @example + * ```ts + * const chart = new LineChart('.ct-chart', { + * labels: [1, 2, 3, 4, 5], + * series: [[1, 2, 8, 1, 7]] + * }, { + * lineSmooth: Interpolation.none({ + * fillHoles: false + * }) + * }); + * ``` + */ +export function none(options?: NoneInterpolationOptions) { + const finalOptions = { + fillHoles: false, + ...options + }; + + return function noneInterpolation( + pathCoordinates: number[], + valueData: SegmentData[] + ) { + const path = new SvgPath(); + let hole = true; + + for (let i = 0; i < pathCoordinates.length; i += 2) { + const currX = pathCoordinates[i]; + const currY = pathCoordinates[i + 1]; + const currData = valueData[i / 2]; + + if (getMultiValue(currData.value) !== undefined) { + if (hole) { + path.move(currX, currY, false, currData); + } else { + path.line(currX, currY, false, currData); + } + + hole = false; + } else if (!finalOptions.fillHoles) { + hole = true; + } + } + + return path; + }; +} diff --git a/src/interpolation/simple.ts b/src/interpolation/simple.ts new file mode 100644 index 000000000..a5c25c4f2 --- /dev/null +++ b/src/interpolation/simple.ts @@ -0,0 +1,82 @@ +import type { SegmentData } from '../core/types'; +import { SvgPath } from '../svg'; + +export interface SimpleInteractionOptions { + divisor?: number; + fillHoles?: boolean; +} + +/** + * Simple smoothing creates horizontal handles that are positioned with a fraction of the length between two data points. You can use the divisor option to specify the amount of smoothing. + * + * Simple smoothing can be used instead of `Chartist.Smoothing.cardinal` if you'd like to get rid of the artifacts it produces sometimes. Simple smoothing produces less flowing lines but is accurate by hitting the points and it also doesn't swing below or above the given data point. + * + * All smoothing functions within Chartist are factory functions that accept an options parameter. The simple interpolation function accepts one configuration parameter `divisor`, between 1 and āˆž, which controls the smoothing characteristics. + * + * @example + * ```ts + * const chart = new LineChart('.ct-chart', { + * labels: [1, 2, 3, 4, 5], + * series: [[1, 2, 8, 1, 7]] + * }, { + * lineSmooth: Interpolation.simple({ + * divisor: 2, + * fillHoles: false + * }) + * }); + * ``` + * + * @param options The options of the simple interpolation factory function. + */ +export function simple(options?: SimpleInteractionOptions) { + const finalOptions = { + divisor: 2, + fillHoles: false, + ...options + }; + + const d = 1 / Math.max(1, finalOptions.divisor); + + return function simpleInterpolation( + pathCoordinates: number[], + valueData: SegmentData[] + ) { + const path = new SvgPath(); + let prevX = 0; + let prevY = 0; + let prevData; + + for (let i = 0; i < pathCoordinates.length; i += 2) { + const currX = pathCoordinates[i]; + const currY = pathCoordinates[i + 1]; + const length = (currX - prevX) * d; + const currData = valueData[i / 2]; + + if (currData.value !== undefined) { + if (prevData === undefined) { + path.move(currX, currY, false, currData); + } else { + path.curve( + prevX + length, + prevY, + currX - length, + currY, + currX, + currY, + false, + currData + ); + } + + prevX = currX; + prevY = currY; + prevData = currData; + } else if (!finalOptions.fillHoles) { + prevX = prevY = 0; + prevData = undefined; + } + } + + return path; + }; +} diff --git a/src/interpolation/step.ts b/src/interpolation/step.ts new file mode 100644 index 000000000..3357c01b2 --- /dev/null +++ b/src/interpolation/step.ts @@ -0,0 +1,76 @@ +import type { SegmentData } from '../core'; +import { SvgPath } from '../svg'; + +export interface StepInterpolationOptions { + postpone?: boolean; + fillHoles?: boolean; +} + +/** + * Step interpolation will cause the line chart to move in steps rather than diagonal or smoothed lines. This interpolation will create additional points that will also be drawn when the `showPoint` option is enabled. + * + * All smoothing functions within Chartist are factory functions that accept an options parameter. The step interpolation function accepts one configuration parameter `postpone`, that can be `true` or `false`. The default value is `true` and will cause the step to occur where the value actually changes. If a different behaviour is needed where the step is shifted to the left and happens before the actual value, this option can be set to `false`. + * + * @example + * ```ts + * const chart = new Chartist.Line('.ct-chart', { + * labels: [1, 2, 3, 4, 5], + * series: [[1, 2, 8, 1, 7]] + * }, { + * lineSmooth: Interpolation.step({ + * postpone: true, + * fillHoles: false + * }) + * }); + * ``` + */ +export function step(options?: StepInterpolationOptions) { + const finalOptions = { + postpone: true, + fillHoles: false, + ...options + }; + + return function stepInterpolation( + pathCoordinates: number[], + valueData: SegmentData[] + ) { + const path = new SvgPath(); + + let prevX = 0; + let prevY = 0; + let prevData; + + for (let i = 0; i < pathCoordinates.length; i += 2) { + const currX = pathCoordinates[i]; + const currY = pathCoordinates[i + 1]; + const currData = valueData[i / 2]; + + // If the current point is also not a hole we can draw the step lines + if (currData.value !== undefined) { + if (prevData === undefined) { + path.move(currX, currY, false, currData); + } else { + if (finalOptions.postpone) { + // If postponed we should draw the step line with the value of the previous value + path.line(currX, prevY, false, prevData); + } else { + // If not postponed we should draw the step line with the value of the current value + path.line(prevX, currY, false, currData); + } + // Line to the actual point (this should only be a Y-Axis movement + path.line(currX, currY, false, currData); + } + + prevX = currX; + prevY = currY; + prevData = currData; + } else if (!finalOptions.fillHoles) { + prevX = prevY = 0; + prevData = undefined; + } + } + + return path; + }; +} diff --git a/source/styles/settings/_chartist-settings.scss b/src/styles/_settings.scss similarity index 64% rename from source/styles/settings/_chartist-settings.scss rename to src/styles/_settings.scss index b96888da7..8e456a2df 100644 --- a/source/styles/settings/_chartist-settings.scss +++ b/src/styles/_settings.scss @@ -1,34 +1,46 @@ +@use "sass:math"; + // Scales for responsive SVG containers -$ct-scales: ((1), (15/16), (8/9), (5/6), (4/5), (3/4), (2/3), (5/8), (1/1.618), (3/5), (9/16), (8/15), (1/2), (2/5), (3/8), (1/3), (1/4)) !default; +$ct-scales: ((1), math.div(15, 16), math.div(8, 9), math.div(5, 6), math.div(4, 5), math.div(3, 4), math.div(2, 3), math.div(5, 8), math.div(1, 1.618), math.div(3, 5), math.div(9, 16), math.div(8, 15), math.div(1, 2), math.div(2, 5), math.div(3, 8), math.div(1, 3), math.div(1, 4)) !default; $ct-scales-names: (ct-square, ct-minor-second, ct-major-second, ct-minor-third, ct-major-third, ct-perfect-fourth, ct-perfect-fifth, ct-minor-sixth, ct-golden-section, ct-major-sixth, ct-minor-seventh, ct-major-seventh, ct-octave, ct-major-tenth, ct-major-eleventh, ct-major-twelfth, ct-double-octave) !default; // Class names to be used when generating CSS $ct-class-chart: ct-chart !default; $ct-class-chart-line: ct-chart-line !default; $ct-class-chart-bar: ct-chart-bar !default; +$ct-class-horizontal-bars: ct-horizontal-bars !default; $ct-class-chart-pie: ct-chart-pie !default; +$ct-class-chart-donut: ct-chart-donut !default; $ct-class-label: ct-label !default; $ct-class-series: ct-series !default; $ct-class-line: ct-line !default; $ct-class-point: ct-point !default; +$ct-class-area: ct-area !default; $ct-class-bar: ct-bar !default; -$ct-class-slice: ct-slice !default; -$ct-class-donut: ct-donut !default; +$ct-class-slice-pie: ct-slice-pie !default; +$ct-class-slice-donut: ct-slice-donut !default; $ct-class-grid: ct-grid !default; +$ct-class-grid-background: ct-grid-background !default; $ct-class-vertical: ct-vertical !default; $ct-class-horizontal: ct-horizontal !default; +$ct-class-start: ct-start !default; +$ct-class-end: ct-end !default; // Container ratio -$ct-container-ratio: (1/1.618) !default; +$ct-container-ratio: math.div(1, 1.618) !default; // Text styles for labels $ct-text-color: rgba(0, 0, 0, 0.4) !default; $ct-text-size: 0.75rem !default; +$ct-text-align: flex-start !default; +$ct-text-justify: flex-start !default; +$ct-text-line-height: 1 !default; // Grid styles $ct-grid-color: rgba(0, 0, 0, 0.2) !default; $ct-grid-dasharray: 2px !default; $ct-grid-width: 1px !default; +$ct-grid-background-fill: none !default; // Line chart properties $ct-line-width: 4px !default; @@ -36,6 +48,8 @@ $ct-line-dasharray: false !default; $ct-point-size: 10px !default; // Line chart point, can be either round or square $ct-point-shape: round !default; +// Area fill transparency between 0 and 1 +$ct-area-opacity: 0.1 !default; // Bar chart bar width $ct-bar-width: 10px !default; @@ -55,5 +69,21 @@ $ct-include-colored-series: $ct-include-classes !default; $ct-include-alternative-responsive-containers: $ct-include-classes !default; // Series names and colors. This can be extended or customized as desired. Just add more series and colors. -$ct-series-names: (a, b, c, d) !default; -$ct-series-colors: (#d70206, #F05B4F, #F4C63D, #453D3F) !default; +$ct-series-names: (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) !default; +$ct-series-colors: ( + #d70206, + #f05b4f, + #f4c63d, + #d17905, + #453d3f, + #59922b, + #0544d3, + #6b0392, + #e6805e, + #dda458, + #eacf7d, + #86797d, + #b2c326, + #6188e2, + #a748ca +) !default; diff --git a/src/styles/index.scss b/src/styles/index.scss new file mode 100644 index 000000000..612533ecb --- /dev/null +++ b/src/styles/index.scss @@ -0,0 +1,204 @@ +@import "http://github.com/settings"; + +@mixin ct-responsive-svg-container($width: 100%, $ratio: $ct-container-ratio) { + display: block; + position: relative; + width: $width; + + &:before { + display: block; + float: left; + content: ""; + width: 0; + height: 0; + padding-bottom: $ratio * 100%; + } + + &:after { + content: ""; + display: table; + clear: both; + } + + > svg { + display: block; + position: absolute; + top: 0; + left: 0; + } +} + +@mixin ct-align-justify($ct-text-align: $ct-text-align, $ct-text-justify: $ct-text-justify) { + align-items: $ct-text-align; + justify-content: $ct-text-justify; + // Fallback to text-align for non-flex browsers + @if ($ct-text-justify == 'flex-start') { + text-align: left; + } @else if ($ct-text-justify == 'flex-end') { + text-align: right; + } @else { + text-align: center; + } +} + +@mixin ct-chart-label($ct-text-color: $ct-text-color, $ct-text-size: $ct-text-size, $ct-text-line-height: $ct-text-line-height) { + fill: $ct-text-color; + color: $ct-text-color; + font-size: $ct-text-size; + line-height: $ct-text-line-height; +} + +@mixin ct-chart-grid($ct-grid-color: $ct-grid-color, $ct-grid-width: $ct-grid-width, $ct-grid-dasharray: $ct-grid-dasharray) { + stroke: $ct-grid-color; + stroke-width: $ct-grid-width; + + @if ($ct-grid-dasharray) { + stroke-dasharray: $ct-grid-dasharray; + } +} + +@mixin ct-chart-point($ct-point-size: $ct-point-size, $ct-point-shape: $ct-point-shape) { + stroke-width: $ct-point-size; + stroke-linecap: $ct-point-shape; +} + +@mixin ct-chart-line($ct-line-width: $ct-line-width, $ct-line-dasharray: $ct-line-dasharray) { + fill: none; + stroke-width: $ct-line-width; + + @if ($ct-line-dasharray) { + stroke-dasharray: $ct-line-dasharray; + } +} + +@mixin ct-chart-area($ct-area-opacity: $ct-area-opacity) { + stroke: none; + fill-opacity: $ct-area-opacity; +} + +@mixin ct-chart-bar($ct-bar-width: $ct-bar-width) { + fill: none; + stroke-width: $ct-bar-width; +} + +@mixin ct-chart-donut($ct-donut-width: $ct-donut-width) { + fill: none; + stroke-width: $ct-donut-width; +} + +@mixin ct-chart-series-color($color) { + .#{$ct-class-point}, .#{$ct-class-line}, .#{$ct-class-bar}, .#{$ct-class-slice-donut} { + stroke: $color; + } + + .#{$ct-class-slice-pie}, .#{$ct-class-area} { + fill: $color; + } +} + +@mixin ct-chart($ct-container-ratio: $ct-container-ratio, $ct-text-color: $ct-text-color, $ct-text-size: $ct-text-size, $ct-grid-color: $ct-grid-color, $ct-grid-width: $ct-grid-width, $ct-grid-dasharray: $ct-grid-dasharray, $ct-point-size: $ct-point-size, $ct-point-shape: $ct-point-shape, $ct-line-width: $ct-line-width, $ct-bar-width: $ct-bar-width, $ct-donut-width: $ct-donut-width, $ct-series-names: $ct-series-names, $ct-series-colors: $ct-series-colors) { + + .#{$ct-class-label} { + @include ct-chart-label($ct-text-color, $ct-text-size); + } + + .#{$ct-class-chart-line} .#{$ct-class-label}, + .#{$ct-class-chart-bar} .#{$ct-class-label} { + display: flex; + } + + .#{$ct-class-chart-pie} .#{$ct-class-label}, + .#{$ct-class-chart-donut} .#{$ct-class-label} { + dominant-baseline: central; + } + + .#{$ct-class-label}.#{$ct-class-horizontal}.#{$ct-class-start} { + @include ct-align-justify(flex-end, flex-start); + } + + .#{$ct-class-label}.#{$ct-class-horizontal}.#{$ct-class-end} { + @include ct-align-justify(flex-start, flex-start); + } + + .#{$ct-class-label}.#{$ct-class-vertical}.#{$ct-class-start} { + @include ct-align-justify(flex-end, flex-end); + } + + .#{$ct-class-label}.#{$ct-class-vertical}.#{$ct-class-end} { + @include ct-align-justify(flex-end, flex-start); + } + + .#{$ct-class-chart-bar} .#{$ct-class-label}.#{$ct-class-horizontal}.#{$ct-class-start} { + @include ct-align-justify(flex-end, center); + } + + .#{$ct-class-chart-bar} .#{$ct-class-label}.#{$ct-class-horizontal}.#{$ct-class-end} { + @include ct-align-justify(flex-start, center); + } + + .#{$ct-class-chart-bar}.#{$ct-class-horizontal-bars} .#{$ct-class-label}.#{$ct-class-horizontal}.#{$ct-class-start} { + @include ct-align-justify(flex-end, flex-start); + } + + .#{$ct-class-chart-bar}.#{$ct-class-horizontal-bars} .#{$ct-class-label}.#{$ct-class-horizontal}.#{$ct-class-end} { + @include ct-align-justify(flex-start, flex-start); + } + + .#{$ct-class-chart-bar}.#{$ct-class-horizontal-bars} .#{$ct-class-label}.#{$ct-class-vertical}.#{$ct-class-start} { + @include ct-align-justify(center, flex-end); + } + + .#{$ct-class-chart-bar}.#{$ct-class-horizontal-bars} .#{$ct-class-label}.#{$ct-class-vertical}.#{$ct-class-end} { + @include ct-align-justify(center, flex-start); + } + + .#{$ct-class-grid} { + @include ct-chart-grid($ct-grid-color, $ct-grid-width, $ct-grid-dasharray); + } + + .#{$ct-class-grid-background} { + fill: $ct-grid-background-fill; + } + + .#{$ct-class-point} { + @include ct-chart-point($ct-point-size, $ct-point-shape); + } + + .#{$ct-class-line} { + @include ct-chart-line($ct-line-width); + } + + .#{$ct-class-area} { + @include ct-chart-area(); + } + + .#{$ct-class-bar} { + @include ct-chart-bar($ct-bar-width); + } + + .#{$ct-class-slice-donut} { + @include ct-chart-donut($ct-donut-width); + } + + @if $ct-include-colored-series { + @for $i from 0 to length($ct-series-names) { + .#{$ct-class-series}-#{nth($ct-series-names, $i + 1)} { + $color: nth($ct-series-colors, $i + 1); + + @include ct-chart-series-color($color); + } + } + } +} + +@if $ct-include-classes { + @include ct-chart(); + + @if $ct-include-alternative-responsive-containers { + @for $i from 0 to length($ct-scales-names) { + .#{nth($ct-scales-names, $i + 1)} { + @include ct-responsive-svg-container($ratio: nth($ct-scales, $i + 1)); + } + } + } +} diff --git a/src/svg/Svg.spec.ts b/src/svg/Svg.spec.ts new file mode 100644 index 000000000..a58bd6c13 --- /dev/null +++ b/src/svg/Svg.spec.ts @@ -0,0 +1,219 @@ +import { Svg } from './Svg'; +import { namespaces } from '../core'; + +describe('Svg', () => { + it('should create a valid svg dom element', () => { + const svg = new Svg('svg'); + + expect(svg).toBeDefined(); + expect(svg.getNode()).toBeDefined(); + expect(svg.getNode().nodeName.toLowerCase()).toBe('svg'); + }); + + it('should create a valid svg dom element with attributes', () => { + const svg = new Svg('svg', { + width: '100%', + height: '100%' + }); + + expect(svg).toBeDefined(); + expect(svg.getNode()).toBeDefined(); + expect(svg.getNode().nodeName.toLowerCase()).toBe('svg'); + expect(svg.getNode()).toHaveAttribute('width', '100%'); + expect(svg.getNode()).toHaveAttribute('height', '100%'); + }); + + it('should create nested objects with attributes', () => { + const svg = new Svg('svg'); + svg.elem('g').elem('g').elem('circle', { + cx: 100, + cy: 100, + r: 10 + }); + + expect(svg.getNode()).toBeDefined(); + expect( + svg.getNode().firstElementChild?.firstElementChild?.firstElementChild + ).toBeDefined(); + expect( + svg + .getNode() + .firstElementChild?.firstElementChild?.firstElementChild?.getAttribute( + 'cx' + ) + ).toBe('100'); + expect( + svg + .getNode() + .firstElementChild?.firstElementChild?.firstElementChild?.getAttribute( + 'cy' + ) + ).toBe('100'); + expect( + svg + .getNode() + .firstElementChild?.firstElementChild?.firstElementChild?.getAttribute( + 'r' + ) + ).toBe('10'); + }); + + it('should allow to set attributes manually', () => { + const svg = new Svg('svg'); + svg.elem('circle').attr({ + cx: 100, + cy: 100, + r: 10 + }); + + expect(svg.getNode()).toBeDefined(); + expect(svg.getNode().firstElementChild).toBeDefined(); + expect(svg.getNode().firstElementChild?.getAttribute('cx')).toBe('100'); + expect(svg.getNode().firstElementChild?.getAttribute('cy')).toBe('100'); + expect(svg.getNode().firstElementChild?.getAttribute('r')).toBe('10'); + }); + + it('should allow to set namespaced attributes', () => { + const svg = new Svg('image'); + svg.elem('image').attr({ + x: 100, + y: 100, + height: 100, + width: 100, + 'xlink:href': 'image.jpg' + }); + + expect(svg.getNode()).toBeDefined(); + expect(svg.getNode().firstElementChild).toBeDefined(); + expect(svg.getNode().firstElementChild).toHaveAttribute('x', '100'); + expect(svg.getNode().firstElementChild).toHaveAttribute('y', '100'); + expect(svg.getNode().firstElementChild).toHaveAttribute('width', '100'); + expect(svg.getNode().firstElementChild).toHaveAttribute('height', '100'); + expect( + svg.getNode().firstElementChild?.getAttributeNS(namespaces.xlink, 'href') + ).toBe('image.jpg'); + }); + + it('should clear on each nesting level', () => { + const svg = new Svg('svg'); + const group = svg.elem('g'); + group.elem('circle'); + group.elem('circle'); + group.elem('circle'); + + expect(svg.getNode()).toBeDefined(); + expect(svg.getNode().firstElementChild?.childNodes.length).toBe(3); + + group.empty(); + expect(svg.getNode().firstElementChild?.childNodes.length).toBe(0); + + svg.empty(); + expect(svg.getNode()).toBeEmptyDOMElement(); + }); + + it('should allow to remove a certain element', () => { + const svg = new Svg('svg'); + const text = svg.elem('text'); + + expect(svg.getNode()).toBeDefined(); + expect(svg.getNode().childNodes.length).toBe(1); + expect(svg.getNode().firstElementChild?.nodeName.toLowerCase()).toBe( + 'text' + ); + + text.remove(); + expect(svg.getNode().childNodes.length).toBe(0); + }); + + it('should allow to write text content into elements', () => { + const svg = new Svg('svg'); + svg.elem('text').text('Hello World'); + + expect(svg.getNode()).toBeDefined(); + expect(svg.getNode().childNodes.length).toBe(1); + expect(svg.getNode().firstElementChild?.nodeName.toLowerCase()).toBe( + 'text' + ); + expect(svg.getNode().firstElementChild?.firstChild?.nodeType).toBe(3); + expect(svg.getNode().firstElementChild?.firstChild).toHaveTextContent( + 'Hello World' + ); + }); + + it('should allow to add and remove classes on elements', () => { + const svg = new Svg('svg') + .addClass('test-class-1') + .addClass('test-class-2') + // Should not allow duplicates + .addClass('test-class-2') + // Should allow multiple classes with white spaces + .addClass('test-class-3 test-class-4'); + + expect(svg.getNode()).toBeDefined(); + expect(svg.getNode().getAttribute('class')?.split(' ')).toEqual([ + 'test-class-1', + 'test-class-2', + 'test-class-3', + 'test-class-4' + ]); + + svg.removeClass('test-class-1'); + // Should allow multiple classes with whitespaces + svg.removeClass('test-class-2 test-class-3'); + + expect(svg.getNode()).toHaveAttribute('class', 'test-class-4'); + }); + + it('should allow to travers up in the fluent API chain and set attributes on the way', () => { + const svg = new Svg('svg'); + svg + .elem('g') + .elem('g') + .elem('g') + .elem('circle') + .parent() + ?.attr({ + transform: 'rotate(10 10 10)' + }) + .parent() + ?.attr({ + transform: 'rotate(20 20 20)' + }) + .parent() + ?.attr({ + transform: 'rotate(30 30 30)' + }) + .parent() + ?.attr({ + width: '100%', + height: '100%' + }); + + expect(svg.getNode()).toBeDefined(); + expect(svg.getNode()).toHaveAttribute('width', '100%'); + expect(svg.getNode()).toHaveAttribute('height', '100%'); + + expect(svg.getNode().firstElementChild).toBeDefined(); + expect(svg.getNode().firstElementChild?.getAttribute('transform')).toBe( + 'rotate(30 30 30)' + ); + + expect(svg.getNode().firstElementChild?.firstElementChild).toBeDefined(); + expect( + svg + .getNode() + .firstElementChild?.firstElementChild?.getAttribute('transform') + ).toBe('rotate(20 20 20)'); + + expect( + svg.getNode().firstElementChild?.firstElementChild?.firstElementChild + ).toBeDefined(); + expect( + svg + .getNode() + .firstElementChild?.firstElementChild?.firstElementChild?.getAttribute( + 'transform' + ) + ).toBe('rotate(10 10 10)'); + }); +}); diff --git a/src/svg/Svg.ts b/src/svg/Svg.ts new file mode 100644 index 000000000..1fbd0f33b --- /dev/null +++ b/src/svg/Svg.ts @@ -0,0 +1,419 @@ +import type { EventEmitter } from '../event'; +import { namespaces } from '../core/constants'; +import type { Attributes, AnimationDefinition } from './types'; +import { SvgList } from './SvgList'; +import { createAnimation, easings } from './animation'; + +/** + * Svg creates a new SVG object wrapper with a starting element. You can use the wrapper to fluently create sub-elements and modify them. + */ +export class Svg { + /** + * @todo Only there for chartist <1 compatibility. Remove after deprecation warining. + * @deprecated Use the animation module export `easings` directly. + */ + static readonly Easing = easings; + + private _node: Element; + + /** + * @param name The name of the SVG element to create or an SVG dom element which should be wrapped into Svg + * @param attributes An object with properties that will be added as attributes to the SVG element that is created. Attributes with undefined values will not be added. + * @param className This class or class list will be added to the SVG element + * @param parent The parent SVG wrapper object where this newly created wrapper and it's element will be attached to as child + * @param insertFirst If this param is set to true in conjunction with a parent element the newly created element will be added as first child element in the parent element + */ + constructor( + name: string | Element, + attributes?: Attributes, + className?: string, + parent?: Svg, + insertFirst = false + ) { + // If Svg is getting called with an SVG element we just return the wrapper + if (name instanceof Element) { + this._node = name; + } else { + this._node = document.createElementNS(namespaces.svg, name); + + // If this is an SVG element created then custom namespace + if (name === 'svg') { + this.attr({ + 'xmlns:ct': namespaces.ct + }); + } + } + + if (attributes) { + this.attr(attributes); + } + + if (className) { + this.addClass(className); + } + + if (parent) { + if (insertFirst && parent._node.firstChild) { + parent._node.insertBefore(this._node, parent._node.firstChild); + } else { + parent._node.appendChild(this._node); + } + } + } + + /** + * Set attributes on the current SVG element of the wrapper you're currently working on. + * @param attributes An object with properties that will be added as attributes to the SVG element that is created. Attributes with undefined values will not be added. If this parameter is a String then the function is used as a getter and will return the attribute value. + * @param ns If specified, the attribute will be obtained using getAttributeNs. In order to write namepsaced attributes you can use the namespace:attribute notation within the attributes object. + * @return The current wrapper object will be returned so it can be used for chaining or the attribute value if used as getter function. + */ + attr(attributes: string, ns?: string): string | null; + attr(attributes: Attributes): this; + attr(attributes: string | Attributes, ns?: string) { + if (typeof attributes === 'string') { + if (ns) { + return this._node.getAttributeNS(ns, attributes); + } else { + return this._node.getAttribute(attributes); + } + } + + Object.keys(attributes).forEach(key => { + // If the attribute value is undefined we can skip this one + if (attributes[key] === undefined) { + return; + } + + if (key.indexOf(':') !== -1) { + const namespacedAttribute = key.split(':'); + this._node.setAttributeNS( + namespaces[namespacedAttribute[0]], + key, + String(attributes[key]) + ); + } else { + this._node.setAttribute(key, String(attributes[key])); + } + }); + + return this; + } + + /** + * Create a new SVG element whose wrapper object will be selected for further operations. This way you can also create nested groups easily. + * @param name The name of the SVG element that should be created as child element of the currently selected element wrapper + * @param attributes An object with properties that will be added as attributes to the SVG element that is created. Attributes with undefined values will not be added. + * @param className This class or class list will be added to the SVG element + * @param insertFirst If this param is set to true in conjunction with a parent element the newly created element will be added as first child element in the parent element + * @return Returns a Svg wrapper object that can be used to modify the containing SVG data + */ + elem( + name: string, + attributes?: Attributes, + className?: string, + insertFirst = false + ) { + return new Svg(name, attributes, className, this, insertFirst); + } + + /** + * Returns the parent Chartist.SVG wrapper object + * @return Returns a Svg wrapper around the parent node of the current node. If the parent node is not existing or it's not an SVG node then this function will return null. + */ + parent() { + return this._node.parentNode instanceof SVGElement + ? new Svg(this._node.parentNode) + : null; + } + + /** + * This method returns a Svg wrapper around the root SVG element of the current tree. + * @return The root SVG element wrapped in a Svg element + */ + root() { + let node = this._node; + + while (node.nodeName !== 'svg') { + if (node.parentElement) { + node = node.parentElement; + } else { + break; + } + } + + return new Svg(node); + } + + /** + * Find the first child SVG element of the current element that matches a CSS selector. The returned object is a Svg wrapper. + * @param selector A CSS selector that is used to query for child SVG elements + * @return The SVG wrapper for the element found or null if no element was found + */ + querySelector(selector: string) { + const foundNode = this._node.querySelector(selector); + return foundNode ? new Svg(foundNode) : null; + } + + /** + * Find the all child SVG elements of the current element that match a CSS selector. The returned object is a Svg.List wrapper. + * @param selector A CSS selector that is used to query for child SVG elements + * @return The SVG wrapper list for the element found or null if no element was found + */ + querySelectorAll(selector: string) { + const foundNodes = this._node.querySelectorAll(selector); + return new SvgList(foundNodes); + } + + /** + * Returns the underlying SVG node for the current element. + */ + getNode() { + return this._node as T; + } + + /** + * This method creates a foreignObject (see https://developer.mozilla.org/en-US/docs/Web/SVG/Element/foreignObject) that allows to embed HTML content into a SVG graphic. With the help of foreignObjects you can enable the usage of regular HTML elements inside of SVG where they are subject for SVG positioning and transformation but the Browser will use the HTML rendering capabilities for the containing DOM. + * @param content The DOM Node, or HTML string that will be converted to a DOM Node, that is then placed into and wrapped by the foreignObject + * @param attributes An object with properties that will be added as attributes to the foreignObject element that is created. Attributes with undefined values will not be added. + * @param className This class or class list will be added to the SVG element + * @param insertFirst Specifies if the foreignObject should be inserted as first child + * @return New wrapper object that wraps the foreignObject element + */ + foreignObject( + content: string | Node, + attributes?: Attributes, + className?: string, + insertFirst = false + ) { + let contentNode: Node; + // If content is string then we convert it to DOM + // TODO: Handle case where content is not a string nor a DOM Node + if (typeof content === 'string') { + const container = document.createElement('div'); + container.innerHTML = content; + contentNode = container.firstChild as Node; + } else { + contentNode = content; + } + + if (contentNode instanceof Element) { + // Adding namespace to content element + contentNode.setAttribute('xmlns', namespaces.xmlns); + } + + // Creating the foreignObject without required extension attribute (as described here + // http://www.w3.org/TR/SVG/extend.html#ForeignObjectElement) + const fnObj = this.elem( + 'foreignObject', + attributes, + className, + insertFirst + ); + + // Add content to foreignObjectElement + fnObj._node.appendChild(contentNode); + + return fnObj; + } + + /** + * This method adds a new text element to the current Svg wrapper. + * @param t The text that should be added to the text element that is created + * @return The same wrapper object that was used to add the newly created element + */ + text(t: string) { + this._node.appendChild(document.createTextNode(t)); + return this; + } + + /** + * This method will clear all child nodes of the current wrapper object. + * @return The same wrapper object that got emptied + */ + empty() { + while (this._node.firstChild) { + this._node.removeChild(this._node.firstChild); + } + + return this; + } + + /** + * This method will cause the current wrapper to remove itself from its parent wrapper. Use this method if you'd like to get rid of an element in a given DOM structure. + * @return The parent wrapper object of the element that got removed + */ + remove() { + this._node.parentNode?.removeChild(this._node); + return this.parent(); + } + + /** + * This method will replace the element with a new element that can be created outside of the current DOM. + * @param newElement The new Svg object that will be used to replace the current wrapper object + * @return The wrapper of the new element + */ + replace(newElement: Svg) { + this._node.parentNode?.replaceChild(newElement._node, this._node); + return newElement; + } + + /** + * This method will append an element to the current element as a child. + * @param element The Svg element that should be added as a child + * @param insertFirst Specifies if the element should be inserted as first child + * @return The wrapper of the appended object + */ + append(element: Svg, insertFirst = false) { + if (insertFirst && this._node.firstChild) { + this._node.insertBefore(element._node, this._node.firstChild); + } else { + this._node.appendChild(element._node); + } + + return this; + } + + /** + * Returns an array of class names that are attached to the current wrapper element. This method can not be chained further. + * @return A list of classes or an empty array if there are no classes on the current element + */ + classes() { + const classNames = this._node.getAttribute('class'); + + return classNames ? classNames.trim().split(/\s+/) : []; + } + + /** + * Adds one or a space separated list of classes to the current element and ensures the classes are only existing once. + * @param names A white space separated list of class names + * @return The wrapper of the current element + */ + addClass(names: string) { + this._node.setAttribute( + 'class', + this.classes() + .concat(names.trim().split(/\s+/)) + .filter(function (elem, pos, self) { + return self.indexOf(elem) === pos; + }) + .join(' ') + ); + + return this; + } + + /** + * Removes one or a space separated list of classes from the current element. + * @param names A white space separated list of class names + * @return The wrapper of the current element + */ + removeClass(names: string) { + const removedClasses = names.trim().split(/\s+/); + + this._node.setAttribute( + 'class', + this.classes() + .filter(name => removedClasses.indexOf(name) === -1) + .join(' ') + ); + + return this; + } + + /** + * Removes all classes from the current element. + * @return The wrapper of the current element + */ + removeAllClasses() { + this._node.setAttribute('class', ''); + return this; + } + + /** + * Get element height using `clientHeight` + * @return The elements height in pixels + */ + height() { + return this._node.clientHeight; + } + + /** + * Get element width using `clientWidth` + * @return The elements width in pixels + */ + width() { + return this._node.clientWidth; + } + + /** + * The animate function lets you animate the current element with SMIL animations. You can add animations for multiple attributes at the same time by using an animation definition object. This object should contain SMIL animation attributes. Please refer to http://www.w3.org/TR/SVG/animate.html for a detailed specification about the available animation attributes. Additionally an easing property can be passed in the animation definition object. This can be a string with a name of an easing function in `Svg.Easing` or an array with four numbers specifying a cubic BĆ©zier curve. + * **An animations object could look like this:** + * ```javascript + * element.animate({ + * opacity: { + * dur: 1000, + * from: 0, + * to: 1 + * }, + * x1: { + * dur: '1000ms', + * from: 100, + * to: 200, + * easing: 'easeOutQuart' + * }, + * y1: { + * dur: '2s', + * from: 0, + * to: 100 + * } + * }); + * ``` + * **Automatic unit conversion** + * For the `dur` and the `begin` animate attribute you can also omit a unit by passing a number. The number will automatically be converted to milli seconds. + * **Guided mode** + * The default behavior of SMIL animations with offset using the `begin` attribute is that the attribute will keep it's original value until the animation starts. Mostly this behavior is not desired as you'd like to have your element attributes already initialized with the animation `from` value even before the animation starts. Also if you don't specify `fill="freeze"` on an animate element or if you delete the animation after it's done (which is done in guided mode) the attribute will switch back to the initial value. This behavior is also not desired when performing simple one-time animations. For one-time animations you'd want to trigger animations immediately instead of relative to the document begin time. That's why in guided mode Svg will also use the `begin` property to schedule a timeout and manually start the animation after the timeout. If you're using multiple SMIL definition objects for an attribute (in an array), guided mode will be disabled for this attribute, even if you explicitly enabled it. + * If guided mode is enabled the following behavior is added: + * - Before the animation starts (even when delayed with `begin`) the animated attribute will be set already to the `from` value of the animation + * - `begin` is explicitly set to `indefinite` so it can be started manually without relying on document begin time (creation) + * - The animate element will be forced to use `fill="freeze"` + * - The animation will be triggered with `beginElement()` in a timeout where `begin` of the definition object is interpreted in milli seconds. If no `begin` was specified the timeout is triggered immediately. + * - After the animation the element attribute value will be set to the `to` value of the animation + * - The animate element is deleted from the DOM + * @param animations An animations object where the property keys are the attributes you'd like to animate. The properties should be objects again that contain the SMIL animation attributes (usually begin, dur, from, and to). The property begin and dur is auto converted (see Automatic unit conversion). You can also schedule multiple animations for the same attribute by passing an Array of SMIL definition objects. Attributes that contain an array of SMIL definition objects will not be executed in guided mode. + * @param guided Specify if guided mode should be activated for this animation (see Guided mode). If not otherwise specified, guided mode will be activated. + * @param eventEmitter If specified, this event emitter will be notified when an animation starts or ends. + * @return The current element where the animation was added + */ + animate( + animations: Record, + guided = true, + eventEmitter?: EventEmitter + ) { + Object.keys(animations).forEach(attribute => { + const attributeAnimation = animations[attribute]; + + // If current attribute is an array of definition objects we create an animate for each and disable guided mode + if (Array.isArray(attributeAnimation)) { + attributeAnimation.forEach(animationDefinition => + createAnimation( + this, + attribute, + animationDefinition, + false, + eventEmitter + ) + ); + } else { + createAnimation( + this, + attribute, + attributeAnimation, + guided, + eventEmitter + ); + } + }); + + return this; + } +} diff --git a/src/svg/SvgList.ts b/src/svg/SvgList.ts new file mode 100644 index 000000000..e0d562610 --- /dev/null +++ b/src/svg/SvgList.ts @@ -0,0 +1,90 @@ +import { Svg } from './Svg'; + +type SvgMethods = Exclude< + keyof Svg, + | 'constructor' + | 'parent' + | 'querySelector' + | 'querySelectorAll' + | 'replace' + | 'append' + | 'classes' + | 'height' + | 'width' +>; + +type SvgListMethods = { + [method in SvgMethods]: (...args: Parameters) => SvgList; +}; + +/** + * This helper class is to wrap multiple `Svg` elements into a list where you can call the `Svg` functions on all elements in the list with one call. This is helpful when you'd like to perform calls with `Svg` on multiple elements. + * An instance of this class is also returned by `Svg.querySelectorAll`. + */ +export class SvgList implements SvgListMethods { + private svgElements: Svg[] = []; + + /** + * @param nodeList An Array of SVG DOM nodes or a SVG DOM NodeList (as returned by document.querySelectorAll) + */ + constructor(nodeList: ArrayLike) { + for (let i = 0; i < nodeList.length; i++) { + this.svgElements.push(new Svg(nodeList[i])); + } + } + + private call(method: T, args: Parameters) { + this.svgElements.forEach(element => + Reflect.apply(element[method], element, args) + ); + return this; + } + + attr(...args: Parameters) { + return this.call('attr', args); + } + + elem(...args: Parameters) { + return this.call('elem', args); + } + + root(...args: Parameters) { + return this.call('root', args); + } + + getNode(...args: Parameters) { + return this.call('getNode', args); + } + + foreignObject(...args: Parameters) { + return this.call('foreignObject', args); + } + + text(...args: Parameters) { + return this.call('text', args); + } + + empty(...args: Parameters) { + return this.call('empty', args); + } + + remove(...args: Parameters) { + return this.call('remove', args); + } + + addClass(...args: Parameters) { + return this.call('addClass', args); + } + + removeClass(...args: Parameters) { + return this.call('removeClass', args); + } + + removeAllClasses(...args: Parameters) { + return this.call('removeAllClasses', args); + } + + animate(...args: Parameters) { + return this.call('animate', args); + } +} diff --git a/src/svg/SvgPath.spec.ts b/src/svg/SvgPath.spec.ts new file mode 100644 index 000000000..e3aab8b22 --- /dev/null +++ b/src/svg/SvgPath.spec.ts @@ -0,0 +1,207 @@ +import { SvgPath } from './SvgPath'; + +describe('Svg', () => { + describe('SvgPath', () => { + it('should handle position updates correctly', () => { + const path: any = new SvgPath(); + expect(path.position()).toBe(0); + expect(path.position(100).position()).toBe(0); + expect(path.position(-1).position()).toBe(0); + + path.pathElements = [1, 2, 3]; + expect(path.position(100).position()).toBe(3); + }); + + it('should add absolute and relative path elements correctly', () => { + const path: any = new SvgPath() + .move(1, 2) + .move(3, 4, true) + .line(5, 6) + .line(7, 8, true) + .curve(9, 10, 11, 12, 13, 14) + .curve(15, 16, 17, 18, 19, 20, true); + + expect(path.pathElements.length).toBe(6); + expect(path.pathElements).toEqual([ + { command: 'M', x: 1, y: 2 }, + { command: 'm', x: 3, y: 4 }, + { command: 'L', x: 5, y: 6 }, + { command: 'l', x: 7, y: 8 }, + { command: 'C', x1: 9, y1: 10, x2: 11, y2: 12, x: 13, y: 14 }, + { command: 'c', x1: 15, y1: 16, x2: 17, y2: 18, x: 19, y: 20 } + ]); + }); + + it('should insert new elements at correct position', () => { + const path: any = new SvgPath() + .move(1, 2) + .move(7, 8) + .move(9, 10) + .position(1) + .move(3, 4) + .move(5, 6) + .position(100000) + .move(11, 12) + .position(-100000) + .move(-1, 0); + + expect(path.pathElements.length).toBe(7); + expect(path.pathElements).toEqual([ + { command: 'M', x: -1, y: 0 }, + { command: 'M', x: 1, y: 2 }, + { command: 'M', x: 3, y: 4 }, + { command: 'M', x: 5, y: 6 }, + { command: 'M', x: 7, y: 8 }, + { command: 'M', x: 9, y: 10 }, + { command: 'M', x: 11, y: 12 } + ]); + }); + + it('should stringify simple shape correctly', () => { + const path = new SvgPath(true) + .move(10, 10) + .line(10, 100) + .line(100, 100) + .line(100, 10); + expect(path.stringify()).toEqual('M10,10L10,100L100,100L100,10Z'); + }); + + it('should stringify with configured precision', () => { + const path = new SvgPath(false, { + accuracy: 2 + }) + .move(10.12345, 10.14345) + .line(10.14545, 10) + .line(10.14000000645, 10.3333333333); + expect(path.stringify()).toEqual('M10.12,10.14L10.15,10L10.14,10.33'); + }); + + it('should parse Chartist SVG path style correctly', () => { + const path = new SvgPath().parse('M10,10L10,100L100,100L100,10'); + expect(path.stringify()).toEqual('M10,10L10,100L100,100L100,10'); + }); + + it('should parse MDN SVG path style correctly', () => { + const path = new SvgPath().parse( + 'M10 10 L 10 100 L 100 100 L 100 10 C 1 1, 1 1, 1 1' + ); + expect(path.stringify()).toEqual( + 'M10,10L10,100L100,100L100,10C1,1,1,1,1,1' + ); + }); + + it('should parse path with closing command', () => { + const path = new SvgPath().parse( + 'M10 10 L 10 100 L 100 100 L 100 10 C 1 1, 1 1, 1 1 Z' + ); + expect(path.stringify()).toEqual( + 'M10,10L10,100L100,100L100,10C1,1,1,1,1,1' + ); + }); + + it('should parse complex path correctly', () => { + const path = new SvgPath(false, { + accuracy: 0 + }).parse( + 'M7.566371681415929,313.5870318472049L15.132743362831858,322.1479887268699L22.699115044247787,292.49058976570063L30.265486725663717,284.9469379116152L37.83185840707964,277.62070141556273L45.39823008849557,285.4043086222666L52.9646017699115,295.16905806058617L60.530973451327434,288.5395967440654L68.09734513274336,282.3023155078293L75.66371681415929,276.9420221519757L83.23008849557522,271.31296300227655L90.79646017699115,273.1827546735411L98.36283185840708,282.72148250847295L105.929203539823,276.55760703185683L113.49557522123892,278.16318930715545L121.06194690265487,279.67913384762466L128.6283185840708,296.53529757775897L136.1946902654867,324.4003397770142L143.76106194690263,317.1376004332516L151.32743362831857,323.3390406432677L158.89380530973452,328.5597479599146L166.46017699115043,329.67851354926904L174.02654867256635,327.71837583373326L181.5929203539823,335.05972598190976L189.15929203539824,334.29372633331286L196.72566371681415,332.68724934321176L204.29203539823007,330.6752327006325L211.858407079646,325.971917329413L219.42477876106196,328.13057177790404L226.99115044247785,309.6546479835954L234.5575221238938,310.6637826993739L242.12389380530973,310.65221523366176L249.69026548672568,318.40285733188773L257.2566371681416,298.18154267575227L264.8230088495575,307.4788389000347L272.3893805309734,304.189264255087L279.95575221238937,289.0288876874009L287.52212389380526,300.20654714775424L295.0884955752212,298.0164127652739L302.65486725663715,287.69192345832175L310.2212389380531,293.1860711045035L317.78761061946904,300.4760502113585L325.3539823008849,297.94852206276937L332.92035398230087,305.6594311405378L340.4867256637168,306.7859423144216L348.0530973451327,275.68998851331963L355.61946902654864,286.5550640745874L363.1858407079646,288.4952543187362L370.75221238938053,290.1896066608983L378.3185840707965,277.8447927515142L385.88495575221236,282.46018876596827L393.4513274336283,261.617847596371L401.01769911504425,265.06101027918726L408.58407079646014,264.60492966286677L416.1504424778761,252.35288845280365L423.716814159292,239.29220756750195L431.283185840708,229.73170018586225L438.8495575221239,224.1580859168795L446.41592920353986,217.20551113129414L453.9823008849557,212.63435660265037L461.54867256637164,210.4425212857057L469.1150442477876,201.0077146146342L476.6814159292035,182.3934004122068L484.24778761061947,176.98732946386616L491.8141592920354,175.3660655079267L499.38053097345136,181.1589144624976L506.9469026548673,172.81581557677976L514.5132743362832,177.82343674256106L522.079646017699,183.5573714672562L529.646017699115,184.4980688436067L537.2123893805309,201.60789339862924L544.7787610619469,193.42268767053048L552.3451327433628,209.9219909677575L559.9115044247787,221.1318944868172L567.4778761061947,222.47350026973174L575.0442477876105,229.94061399967882L582.6106194690265,213.57676800697396L590.1769911504424,232.97280246785252L597.7433628318583,232.8915724787845L605.3097345132743,231.486089735319L612.8761061946902,234.26534000120475L620.4424778761062,219.90951817170736L628.0088495575221,214.36149678900725L635.5752212389381,204.7245641444236L643.1415929203539,205.04759319834227L650.7079646017698,178.61624621480792L658.2743362831858,174.30656351022486L665.8407079646017,194.06864637030463L673.4070796460177,191.38404795482728L680.9734513274336,188.88380371217903L688.5398230088496,182.47430260433697L696.1061946902654,192.70175438596493L703.6725663716813,182.37945067166908L711.2389380530973,163.80499447227572L718.8053097345132,157.4839718811134L726.3716814159292,149.57403342725343L733.9380530973451,142.6076734278762L741.5044247787611,144.9954413314636L749.070796460177,152.29112878815386L756.637168141593,150.02544379977235L764.2035398230088,139.40203164917125L771.7699115044247,149.22935357717972L779.3362831858407,155.78116263659354L786.9026548672566,145.09966219897575L794.4690265486726,157.52407467202426L802.0353982300885,147.01645902195105L809.6017699115044,141.8658056183404L817.1681415929203,134.36135158737966L824.7345132743362,127.49269525433283L832.3008849557522,120.25886939571154L839.8672566371681,118.26230310074709L847.433628318584,98.76959064327474' + ); + expect(path.stringify()).toEqual( + 'M7.566371681415929,313.5870318472049L15.132743362831858,322.1479887268699L22.699115044247787,292.49058976570063L30.265486725663717,284.9469379116152L37.83185840707964,277.62070141556273L45.39823008849557,285.4043086222666L52.9646017699115,295.16905806058617L60.530973451327434,288.5395967440654L68.09734513274336,282.3023155078293L75.66371681415929,276.9420221519757L83.23008849557522,271.31296300227655L90.79646017699115,273.1827546735411L98.36283185840708,282.72148250847295L105.929203539823,276.55760703185683L113.49557522123892,278.16318930715545L121.06194690265487,279.67913384762466L128.6283185840708,296.53529757775897L136.1946902654867,324.4003397770142L143.76106194690263,317.1376004332516L151.32743362831857,323.3390406432677L158.89380530973452,328.5597479599146L166.46017699115043,329.67851354926904L174.02654867256635,327.71837583373326L181.5929203539823,335.05972598190976L189.15929203539824,334.29372633331286L196.72566371681415,332.68724934321176L204.29203539823007,330.6752327006325L211.858407079646,325.971917329413L219.42477876106196,328.13057177790404L226.99115044247785,309.6546479835954L234.5575221238938,310.6637826993739L242.12389380530973,310.65221523366176L249.69026548672568,318.40285733188773L257.2566371681416,298.18154267575227L264.8230088495575,307.4788389000347L272.3893805309734,304.189264255087L279.95575221238937,289.0288876874009L287.52212389380526,300.20654714775424L295.0884955752212,298.0164127652739L302.65486725663715,287.69192345832175L310.2212389380531,293.1860711045035L317.78761061946904,300.4760502113585L325.3539823008849,297.94852206276937L332.92035398230087,305.6594311405378L340.4867256637168,306.7859423144216L348.0530973451327,275.68998851331963L355.61946902654864,286.5550640745874L363.1858407079646,288.4952543187362L370.75221238938053,290.1896066608983L378.3185840707965,277.8447927515142L385.88495575221236,282.46018876596827L393.4513274336283,261.617847596371L401.01769911504425,265.06101027918726L408.58407079646014,264.60492966286677L416.1504424778761,252.35288845280365L423.716814159292,239.29220756750195L431.283185840708,229.73170018586225L438.8495575221239,224.1580859168795L446.41592920353986,217.20551113129414L453.9823008849557,212.63435660265037L461.54867256637164,210.4425212857057L469.1150442477876,201.0077146146342L476.6814159292035,182.3934004122068L484.24778761061947,176.98732946386616L491.8141592920354,175.3660655079267L499.38053097345136,181.1589144624976L506.9469026548673,172.81581557677976L514.5132743362832,177.82343674256106L522.079646017699,183.5573714672562L529.646017699115,184.4980688436067L537.2123893805309,201.60789339862924L544.7787610619469,193.42268767053048L552.3451327433628,209.9219909677575L559.9115044247787,221.1318944868172L567.4778761061947,222.47350026973174L575.0442477876105,229.94061399967882L582.6106194690265,213.57676800697396L590.1769911504424,232.97280246785252L597.7433628318583,232.8915724787845L605.3097345132743,231.486089735319L612.8761061946902,234.26534000120475L620.4424778761062,219.90951817170736L628.0088495575221,214.36149678900725L635.5752212389381,204.7245641444236L643.1415929203539,205.04759319834227L650.7079646017698,178.61624621480792L658.2743362831858,174.30656351022486L665.8407079646017,194.06864637030463L673.4070796460177,191.38404795482728L680.9734513274336,188.88380371217903L688.5398230088496,182.47430260433697L696.1061946902654,192.70175438596493L703.6725663716813,182.37945067166908L711.2389380530973,163.80499447227572L718.8053097345132,157.4839718811134L726.3716814159292,149.57403342725343L733.9380530973451,142.6076734278762L741.5044247787611,144.9954413314636L749.070796460177,152.29112878815386L756.637168141593,150.02544379977235L764.2035398230088,139.40203164917125L771.7699115044247,149.22935357717972L779.3362831858407,155.78116263659354L786.9026548672566,145.09966219897575L794.4690265486726,157.52407467202426L802.0353982300885,147.01645902195105L809.6017699115044,141.8658056183404L817.1681415929203,134.36135158737966L824.7345132743362,127.49269525433283L832.3008849557522,120.25886939571154L839.8672566371681,118.26230310074709L847.433628318584,98.76959064327474' + ); + }); + + it('should scale path along both axes', () => { + const path: any = new SvgPath() + .move(1, 2) + .line(3, 4) + .curve(5, 6, 7, 8, 9, 10) + .scale(10, 100); + + expect(path.pathElements).toEqual([ + { command: 'M', x: 10, y: 200 }, + { command: 'L', x: 30, y: 400 }, + { command: 'C', x1: 50, y1: 600, x2: 70, y2: 800, x: 90, y: 1000 } + ]); + }); + + it('should translate path along both axes', () => { + const path: any = new SvgPath() + .move(1, 2) + .line(3, 4) + .curve(5, 6, 7, 8, 9, 10) + .translate(10, 100); + + expect(path.pathElements).toEqual([ + { command: 'M', x: 11, y: 102 }, + { command: 'L', x: 13, y: 104 }, + { command: 'C', x1: 15, y1: 106, x2: 17, y2: 108, x: 19, y: 110 } + ]); + }); + + it('should transform path correctly with custom function', () => { + const path: any = new SvgPath() + .move(1, 2) + .line(3, 4) + .curve(5, 6, 7, 8, 9, 10) + .transform((_element, paramName, _elementIndex, paramIndex) => { + if (paramIndex > 3) { + return 0; + } else if (String(paramName)[0] === 'y') { + return 100; + } + + return undefined; + }); + + expect(path.pathElements).toEqual([ + { command: 'M', x: 1, y: 100 }, + { command: 'L', x: 3, y: 100 }, + { command: 'C', x1: 5, y1: 100, x2: 7, y2: 100, x: 0, y: 0 } + ]); + }); + + it('should split correctly by move command', () => { + const paths: any = new SvgPath() + .parse('M0,0L0,0L0,0L0,0M0,0L0,0L0,0L0,0') + .splitByCommand('M'); + expect(paths.length).toBe(2); + expect(paths[0].pathElements[0].command).toBe('M'); + expect(paths[0].pathElements.length).toBe(4); + expect(paths[1].pathElements[0].command).toBe('M'); + expect(paths[1].pathElements.length).toBe(4); + }); + + it('should split correctly by move command and tailing move element', () => { + const paths: any = new SvgPath() + .parse('M0,0L0,0L0,0L0,0M0,0L0,0L0,0L0,0M0,0') + .splitByCommand('M'); + expect(paths.length).toBe(3); + expect(paths[2].pathElements[0].command).toBe('M'); + }); + + it('should split correctly by move command and leading other commands', () => { + const paths: any = new SvgPath() + .parse('L0,0C0,0,0,0,0,0M0,0L0,0L0,0L0,0M0,0L0,0L0,0L0,0') + .splitByCommand('M'); + expect(paths.length).toBe(3); + expect(paths[0].pathElements.length).toBe(2); + expect(paths[0].pathElements[0].command).toBe('L'); + expect(paths[0].pathElements[1].command).toBe('C'); + + expect(paths[1].pathElements.length).toBe(4); + expect(paths[1].pathElements[0].command).toBe('M'); + }); + + it('should correctly parse negative values', () => { + const paths: any = new SvgPath().parse('M-10,10L-100,-100'); + expect(paths.pathElements.length).toBe(2); + expect(paths.pathElements[0].command).toBe('M'); + expect(paths.pathElements[1].command).toBe('L'); + + expect(paths.pathElements[0].x).toBe(-10); + expect(paths.pathElements[0].y).toBe(10); + expect(paths.pathElements[1].x).toBe(-100); + expect(paths.pathElements[1].y).toBe(-100); + }); + }); +}); diff --git a/src/svg/SvgPath.ts b/src/svg/SvgPath.ts new file mode 100644 index 000000000..6eac827ca --- /dev/null +++ b/src/svg/SvgPath.ts @@ -0,0 +1,421 @@ +import type { SegmentData } from '../core'; +import type { SvgPathOptions, PathCommand, PathParams } from './types'; + +/** + * Contains the descriptors of supported element types in a SVG path. Currently only move, line and curve are supported. + */ +const elementDescriptions: Record = { + m: ['x', 'y'], + l: ['x', 'y'], + c: ['x1', 'y1', 'x2', 'y2', 'x', 'y'], + a: ['rx', 'ry', 'xAr', 'lAf', 'sf', 'x', 'y'] +}; + +/** + * Default options for newly created SVG path objects. + */ +const defaultOptions = { + // The accuracy in digit count after the decimal point. This will be used to round numbers in the SVG path. If this option is set to false then no rounding will be performed. + accuracy: 3 +}; + +function element( + command: string, + params: PathParams, + pathElements: PathCommand[], + pos: number, + relative: boolean, + data?: SegmentData +) { + const pathElement: PathCommand = { + command: relative ? command.toLowerCase() : command.toUpperCase(), + ...params, + ...(data ? { data } : {}) + }; + + pathElements.splice(pos, 0, pathElement); +} + +function forEachParam( + pathElements: PathCommand[], + cb: ( + cmd: PathCommand, + param: keyof T, + cmdIndex: number, + paramIndex: number, + cmds: PathCommand[] + ) => void +) { + pathElements.forEach((pathElement, pathElementIndex) => { + elementDescriptions[pathElement.command.toLowerCase()].forEach( + (paramName, paramIndex) => { + cb( + pathElement, + paramName as keyof PathParams, + pathElementIndex, + paramIndex, + pathElements + ); + } + ); + }); +} + +export class SvgPath { + /** + * This static function on `SvgPath` is joining multiple paths together into one paths. + * @param paths A list of paths to be joined together. The order is important. + * @param close If the newly created path should be a closed path + * @param options Path options for the newly created path. + */ + static join(paths: SvgPath[], close = false, options?: SvgPathOptions) { + const joinedPath = new SvgPath(close, options); + for (let i = 0; i < paths.length; i++) { + const path = paths[i]; + for (let j = 0; j < path.pathElements.length; j++) { + joinedPath.pathElements.push(path.pathElements[j]); + } + } + return joinedPath; + } + + pathElements: PathCommand[] = []; + private pos = 0; + private options: Required; + + /** + * Used to construct a new path object. + * @param close If set to true then this path will be closed when stringified (with a Z at the end) + * @param options Options object that overrides the default objects. See default options for more details. + */ + constructor(private readonly close = false, options?: SvgPathOptions) { + this.options = { ...defaultOptions, ...options }; + } + + /** + * Gets or sets the current position (cursor) inside of the path. You can move around the cursor freely but limited to 0 or the count of existing elements. All modifications with element functions will insert new elements at the position of this cursor. + * @param pos If a number is passed then the cursor is set to this position in the path element array. + * @return If the position parameter was passed then the return value will be the path object for easy call chaining. If no position parameter was passed then the current position is returned. + */ + position(pos: number): this; + position(): number; + position(pos?: number) { + if (pos !== undefined) { + this.pos = Math.max(0, Math.min(this.pathElements.length, pos)); + return this; + } else { + return this.pos; + } + } + + /** + * Removes elements from the path starting at the current position. + * @param count Number of path elements that should be removed from the current position. + * @return The current path object for easy call chaining. + */ + remove(count: number) { + this.pathElements.splice(this.pos, count); + return this; + } + + /** + * Use this function to add a new move SVG path element. + * @param x The x coordinate for the move element. + * @param y The y coordinate for the move element. + * @param relative If set to true the move element will be created with relative coordinates (lowercase letter) + * @param data Any data that should be stored with the element object that will be accessible in pathElement + * @return The current path object for easy call chaining. + */ + move(x: number, y: number, relative = false, data?: SegmentData) { + element( + 'M', + { + x: +x, + y: +y + }, + this.pathElements, + this.pos++, + relative, + data + ); + return this; + } + + /** + * Use this function to add a new line SVG path element. + * @param x The x coordinate for the line element. + * @param y The y coordinate for the line element. + * @param relative If set to true the line element will be created with relative coordinates (lowercase letter) + * @param data Any data that should be stored with the element object that will be accessible in pathElement + * @return The current path object for easy call chaining. + */ + line(x: number, y: number, relative = false, data?: SegmentData) { + element( + 'L', + { + x: +x, + y: +y + }, + this.pathElements, + this.pos++, + relative, + data + ); + return this; + } + + /** + * Use this function to add a new curve SVG path element. + * @param x1 The x coordinate for the first control point of the bezier curve. + * @param y1 The y coordinate for the first control point of the bezier curve. + * @param x2 The x coordinate for the second control point of the bezier curve. + * @param y2 The y coordinate for the second control point of the bezier curve. + * @param x The x coordinate for the target point of the curve element. + * @param y The y coordinate for the target point of the curve element. + * @param relative If set to true the curve element will be created with relative coordinates (lowercase letter) + * @param data Any data that should be stored with the element object that will be accessible in pathElement + * @return The current path object for easy call chaining. + */ + curve( + x1: number, + y1: number, + x2: number, + y2: number, + x: number, + y: number, + relative = false, + data?: SegmentData + ) { + element( + 'C', + { + x1: +x1, + y1: +y1, + x2: +x2, + y2: +y2, + x: +x, + y: +y + }, + this.pathElements, + this.pos++, + relative, + data + ); + return this; + } + + /** + * Use this function to add a new non-bezier curve SVG path element. + * @param rx The radius to be used for the x-axis of the arc. + * @param ry The radius to be used for the y-axis of the arc. + * @param xAr Defines the orientation of the arc + * @param lAf Large arc flag + * @param sf Sweep flag + * @param x The x coordinate for the target point of the curve element. + * @param y The y coordinate for the target point of the curve element. + * @param relative If set to true the curve element will be created with relative coordinates (lowercase letter) + * @param data Any data that should be stored with the element object that will be accessible in pathElement + * @return The current path object for easy call chaining. + */ + arc( + rx: number, + ry: number, + xAr: number, + lAf: number, + sf: number, + x: number, + y: number, + relative = false, + data?: SegmentData + ) { + element( + 'A', + { + rx, + ry, + xAr, + lAf, + sf, + x, + y + }, + this.pathElements, + this.pos++, + relative, + data + ); + return this; + } + + /** + * Parses an SVG path seen in the d attribute of path elements, and inserts the parsed elements into the existing path object at the current cursor position. Any closing path indicators (Z at the end of the path) will be ignored by the parser as this is provided by the close option in the options of the path object. + * @param path Any SVG path that contains move (m), line (l) or curve (c) components. + * @return The current path object for easy call chaining. + */ + parse(path: string) { + // Parsing the SVG path string into an array of arrays [['M', '10', '10'], ['L', '100', '100']] + const chunks = path + .replace(/([A-Za-z])(-?[0-9])/g, '$1 $2') + .replace(/([0-9])([A-Za-z])/g, '$1 $2') + .split(/[\s,]+/) + .reduce((result, pathElement) => { + if (pathElement.match(/[A-Za-z]/)) { + result.push([]); + } + + result[result.length - 1].push(pathElement); + return result; + }, []); + + // If this is a closed path we remove the Z at the end because this is determined by the close option + if (chunks[chunks.length - 1][0].toUpperCase() === 'Z') { + chunks.pop(); + } + + // Using svgPathElementDescriptions to map raw path arrays into objects that contain the command and the parameters + // For example {command: 'M', x: '10', y: '10'} + const elements = chunks.map(chunk => { + const command = chunk.shift() as string; + const description = elementDescriptions[command.toLowerCase()]; + + return { + command, + ...description.reduce>( + (result, paramName, index) => { + result[paramName] = +chunk[index]; + return result; + }, + {} + ) + } as PathCommand; + }); + + // Preparing a splice call with the elements array as var arg params and insert the parsed elements at the current position + this.pathElements.splice(this.pos, 0, ...elements); + // Increase the internal position by the element count + this.pos += elements.length; + + return this; + } + + /** + * This function renders to current SVG path object into a final SVG string that can be used in the d attribute of SVG path elements. It uses the accuracy option to round big decimals. If the close parameter was set in the constructor of this path object then a path closing Z will be appended to the output string. + */ + stringify() { + const accuracyMultiplier = Math.pow(10, this.options.accuracy); + + return ( + this.pathElements.reduce((path, pathElement) => { + const params = elementDescriptions[ + pathElement.command.toLowerCase() + ].map(paramName => { + const value = pathElement[paramName as keyof PathCommand] as number; + + return this.options.accuracy + ? Math.round(value * accuracyMultiplier) / accuracyMultiplier + : value; + }); + + return path + pathElement.command + params.join(','); + }, '') + (this.close ? 'Z' : '') + ); + } + + /** + * Scales all elements in the current SVG path object. There is an individual parameter for each coordinate. Scaling will also be done for control points of curves, affecting the given coordinate. + * @param x The number which will be used to scale the x, x1 and x2 of all path elements. + * @param y The number which will be used to scale the y, y1 and y2 of all path elements. + * @return The current path object for easy call chaining. + */ + scale(x: number, y: number) { + forEachParam(this.pathElements, (pathElement, paramName) => { + pathElement[paramName] *= paramName[0] === 'x' ? x : y; + }); + return this; + } + + /** + * Translates all elements in the current SVG path object. The translation is relative and there is an individual parameter for each coordinate. Translation will also be done for control points of curves, affecting the given coordinate. + * @param x The number which will be used to translate the x, x1 and x2 of all path elements. + * @param y The number which will be used to translate the y, y1 and y2 of all path elements. + * @return The current path object for easy call chaining. + */ + translate(x: number, y: number) { + forEachParam(this.pathElements, (pathElement, paramName) => { + pathElement[paramName] += paramName[0] === 'x' ? x : y; + }); + return this; + } + + /** + * This function will run over all existing path elements and then loop over their attributes. The callback function will be called for every path element attribute that exists in the current path. + * The method signature of the callback function looks like this: + * ```javascript + * function(pathElement, paramName, pathElementIndex, paramIndex, pathElements) + * ``` + * If something else than undefined is returned by the callback function, this value will be used to replace the old value. This allows you to build custom transformations of path objects that can't be achieved using the basic transformation functions scale and translate. + * @param transformFnc The callback function for the transformation. Check the signature in the function description. + * @return The current path object for easy call chaining. + */ + transform( + transformFnc: ( + cmd: PathCommand, + param: keyof T, + cmdIndex: number, + paramIndex: number, + cmds: PathCommand[] + ) => number | void + ) { + forEachParam( + this.pathElements, + (pathElement, paramName, pathElementIndex, paramIndex, pathElements) => { + const transformed = transformFnc( + pathElement, + paramName, + pathElementIndex, + paramIndex, + pathElements + ); + if (transformed || transformed === 0) { + pathElement[paramName] = transformed; + } + } + ); + return this; + } + + /** + * This function clones a whole path object with all its properties. This is a deep clone and path element objects will also be cloned. + * @param close Optional option to set the new cloned path to closed. If not specified or false, the original path close option will be used. + */ + clone(close = false) { + const clone = new SvgPath(close || this.close); + clone.pos = this.pos; + clone.pathElements = this.pathElements + .slice() + .map(pathElement => ({ ...pathElement })); + clone.options = { ...this.options }; + return clone; + } + + /** + * Split a Svg.Path object by a specific command in the path chain. The path chain will be split and an array of newly created paths objects will be returned. This is useful if you'd like to split an SVG path by it's move commands, for example, in order to isolate chunks of drawings. + * @param command The command you'd like to use to split the path + */ + splitByCommand(command: string) { + const split = [new SvgPath()]; + + this.pathElements.forEach(pathElement => { + if ( + pathElement.command === command.toUpperCase() && + split[split.length - 1].pathElements.length !== 0 + ) { + split.push(new SvgPath()); + } + + split[split.length - 1].pathElements.push(pathElement); + }); + + return split; + } +} diff --git a/src/svg/animation.ts b/src/svg/animation.ts new file mode 100644 index 000000000..c7a1c78a2 --- /dev/null +++ b/src/svg/animation.ts @@ -0,0 +1,134 @@ +import type { EventEmitter } from '../event'; +import { ensureUnit, quantity } from '../core/lang'; +import type { Attributes, AnimationDefinition, AnimationEvent } from './types'; +import type { Svg } from './Svg'; + +/** + * This Object contains some standard easing cubic bezier curves. + * Then can be used with their name in the `Svg.animate`. + * You can also extend the list and use your own name in the `animate` function. + * Click the show code button to see the available bezier functions. + */ +export const easings = { + easeInSine: [0.47, 0, 0.745, 0.715], + easeOutSine: [0.39, 0.575, 0.565, 1], + easeInOutSine: [0.445, 0.05, 0.55, 0.95], + easeInQuad: [0.55, 0.085, 0.68, 0.53], + easeOutQuad: [0.25, 0.46, 0.45, 0.94], + easeInOutQuad: [0.455, 0.03, 0.515, 0.955], + easeInCubic: [0.55, 0.055, 0.675, 0.19], + easeOutCubic: [0.215, 0.61, 0.355, 1], + easeInOutCubic: [0.645, 0.045, 0.355, 1], + easeInQuart: [0.895, 0.03, 0.685, 0.22], + easeOutQuart: [0.165, 0.84, 0.44, 1], + easeInOutQuart: [0.77, 0, 0.175, 1], + easeInQuint: [0.755, 0.05, 0.855, 0.06], + easeOutQuint: [0.23, 1, 0.32, 1], + easeInOutQuint: [0.86, 0, 0.07, 1], + easeInExpo: [0.95, 0.05, 0.795, 0.035], + easeOutExpo: [0.19, 1, 0.22, 1], + easeInOutExpo: [1, 0, 0, 1], + easeInCirc: [0.6, 0.04, 0.98, 0.335], + easeOutCirc: [0.075, 0.82, 0.165, 1], + easeInOutCirc: [0.785, 0.135, 0.15, 0.86], + easeInBack: [0.6, -0.28, 0.735, 0.045], + easeOutBack: [0.175, 0.885, 0.32, 1.275], + easeInOutBack: [0.68, -0.55, 0.265, 1.55] +}; + +export function createAnimation( + element: Svg, + attribute: string, + animationDefinition: AnimationDefinition, + createGuided = false, + eventEmitter?: EventEmitter +) { + const { easing, ...def } = animationDefinition; + const attributeProperties: Attributes = {}; + let animationEasing; + let timeout; + + // Check if an easing is specified in the definition object and delete it from the object as it will not + // be part of the animate element attributes. + if (easing) { + // If already an easing BĆ©zier curve array we take it or we lookup a easing array in the Easing object + animationEasing = Array.isArray(easing) ? easing : easings[easing]; + } + + // If numeric dur or begin was provided we assume milli seconds + def.begin = ensureUnit(def.begin, 'ms'); + def.dur = ensureUnit(def.dur, 'ms'); + + if (animationEasing) { + def.calcMode = 'spline'; + def.keySplines = animationEasing.join(' '); + def.keyTimes = '0;1'; + } + + // Adding "fill: freeze" if we are in guided mode and set initial attribute values + if (createGuided) { + def.fill = 'freeze'; + // Animated property on our element should already be set to the animation from value in guided mode + attributeProperties[attribute] = def.from; + element.attr(attributeProperties); + + // In guided mode we also set begin to indefinite so we can trigger the start manually and put the begin + // which needs to be in ms aside + timeout = quantity(def.begin || 0).value; + def.begin = 'indefinite'; + } + + const animate = element.elem('animate', { + attributeName: attribute, + ...def + }); + + if (createGuided) { + // If guided we take the value that was put aside in timeout and trigger the animation manually with a timeout + setTimeout(() => { + // If beginElement fails we set the animated attribute to the end position and remove the animate element + // This happens if the SMIL ElementTimeControl interface is not supported or any other problems occurred in + // the browser. (Currently FF 34 does not support animate elements in foreignObjects) + try { + // @ts-expect-error Try legacy API. + animate._node.beginElement(); + } catch (err) { + // Set animated attribute to current animated value + attributeProperties[attribute] = def.to; + element.attr(attributeProperties); + // Remove the animate element as it's no longer required + animate.remove(); + } + }, timeout); + } + + const animateNode = animate.getNode(); + + if (eventEmitter) { + animateNode.addEventListener('beginEvent', () => + eventEmitter.emit('animationBegin', { + element: element, + animate: animateNode, + params: animationDefinition + }) + ); + } + + animateNode.addEventListener('endEvent', () => { + if (eventEmitter) { + eventEmitter.emit('animationEnd', { + element: element, + animate: animateNode, + params: animationDefinition + }); + } + + if (createGuided) { + // Set animated attribute to current animated value + attributeProperties[attribute] = def.to; + element.attr(attributeProperties); + // Remove the animate element as it's no longer required + animate.remove(); + } + }); +} diff --git a/src/svg/index.ts b/src/svg/index.ts new file mode 100644 index 000000000..e49993cf7 --- /dev/null +++ b/src/svg/index.ts @@ -0,0 +1,5 @@ +export { easings } from './animation'; +export * from './Svg'; +export * from './SvgPath'; +export * from './SvgList'; +export * from './types'; diff --git a/src/svg/types.ts b/src/svg/types.ts new file mode 100644 index 000000000..abda31351 --- /dev/null +++ b/src/svg/types.ts @@ -0,0 +1,65 @@ +import type { SegmentData } from '../core'; +import type { easings } from './animation'; +import type { Svg } from './Svg'; + +export interface BasePathParams { + x: number; + y: number; +} + +export type MoveParams = BasePathParams; + +export type LineParams = BasePathParams; + +export interface CurveParams extends BasePathParams { + x1: number; + y1: number; + x2: number; + y2: number; +} + +export interface ArcParams extends BasePathParams { + rx: number; + ry: number; + xAr: number; + lAf: number; + sf: number; +} + +export type PathParams = MoveParams | LineParams | CurveParams | ArcParams; + +export type PathCommand = { + command: string; + data?: SegmentData; +} & T; + +export interface SvgPathOptions { + accuracy?: number; +} + +export type Attributes = Record; + +export interface AnimationDefinition { + id?: string; + easing?: number[] | keyof typeof easings; + calcMode?: 'discrete' | 'linear' | 'paced' | 'spline'; + restart?: 'always' | 'whenNotActive' | 'never'; + repeatCount?: number | 'indefinite'; + repeatDur?: string | 'indefinite'; + keySplines?: string; + keyTimes?: string; + fill?: string; + min?: number | string; + max?: number | string; + begin?: number | string; + end?: number | string; + dur: number | string; + from: number | string; + to: number | string; +} + +export interface AnimationEvent { + element: Svg; + animate: Element; + params: AnimationDefinition; +} diff --git a/src/utils/extend.ts b/src/utils/extend.ts new file mode 100644 index 000000000..77f4b4a69 --- /dev/null +++ b/src/utils/extend.ts @@ -0,0 +1,33 @@ +/** + * Simple recursive object extend + * @param target Target object where the source will be merged into + * @param sources This object (objects) will be merged into target and then target is returned + * @return An object that has the same reference as target but is extended and merged with the properties of source + */ +export function extend(target: T): T; +export function extend(target: T, a: A): T & A; +export function extend(target: T, a: A, b: B): T & A & B; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export function extend(target: any = {}, ...sources: any[]) { + for (let i = 0; i < sources.length; i++) { + const source = sources[i]; + const targetProto = Object.getPrototypeOf(target); + for (const prop in source) { + if (targetProto !== null && prop in targetProto) { + continue; // prevent prototype pollution + } + const sourceProp = source[prop]; + if ( + typeof sourceProp === 'object' && + sourceProp !== null && + !(sourceProp instanceof Array) + ) { + target[prop] = extend(target[prop], sourceProp); + } else { + target[prop] = sourceProp; + } + } + } + + return target; +} diff --git a/src/utils/functional.ts b/src/utils/functional.ts new file mode 100644 index 000000000..846bdc608 --- /dev/null +++ b/src/utils/functional.ts @@ -0,0 +1,46 @@ +/** + * Helps to simplify functional style code + * @param n This exact value will be returned by the noop function + * @return The same value that was provided to the n parameter + */ +export const noop = (n: T) => n; + +/** + * Functional style helper to produce array with given length initialized with undefined values + */ +export function times(length: number): undefined[]; +export function times( + length: number, + filler: (index: number) => T +): T[]; +export function times( + length: number, + filler?: (index: number) => T +) { + return Array.from({ length }, filler ? (_, i) => filler(i) : () => void 0); +} + +/** + * Sum helper to be used in reduce functions + */ +export const sum = (previous: number, current: number) => + previous + (current ? current : 0); + +/** + * Map for multi dimensional arrays where their nested arrays will be mapped in serial. The output array will have the length of the largest nested array. The callback function is called with variable arguments where each argument is the nested array value (or undefined if there are no more values). + * + * For example: + * @example + * ```ts + * const data = [[1, 2], [3], []]; + * serialMap(data, cb); + * + * // where cb will be called 2 times + * // 1. call arguments: (1, 3, undefined) + * // 2. call arguments: (2, undefined, undefined) + * ``` + */ +export const serialMap = (array: T[][], callback: (...args: T[]) => K) => + times(Math.max(...array.map(element => element.length)), index => + callback(...array.map(element => element[index])) + ); diff --git a/src/utils/index.ts b/src/utils/index.ts new file mode 100644 index 000000000..61e35e3b6 --- /dev/null +++ b/src/utils/index.ts @@ -0,0 +1,4 @@ +export * from './types'; +export * from './extend'; +export * from './functional'; +export * from './utils'; diff --git a/src/utils/types.ts b/src/utils/types.ts new file mode 100644 index 000000000..141dca172 --- /dev/null +++ b/src/utils/types.ts @@ -0,0 +1,8 @@ +export type FilterByKey = T extends Record + ? T + : T extends Partial> + ? T & { [key in K]: T[K] } + : never; + +export type RequiredKeys = T & + Required> & { [key in V]: Required }; diff --git a/src/utils/utils.ts b/src/utils/utils.ts new file mode 100644 index 000000000..2e8ad2151 --- /dev/null +++ b/src/utils/utils.ts @@ -0,0 +1,73 @@ +import type { FilterByKey } from './types'; + +/** + * This function safely checks if an objects has an owned property. + * @param target The object where to check for a property + * @param property The property name + * @returns Returns true if the object owns the specified property + */ +export function safeHasProperty( + target: T, + property: K +): target is FilterByKey; +export function safeHasProperty(target: unknown, property: string) { + return ( + target !== null && + typeof target === 'object' && + Reflect.has(target, property) + ); +} + +/** + * Checks if a value can be safely coerced to a number. This includes all values except null which result in finite numbers when coerced. This excludes NaN, since it's not finite. + */ +export function isNumeric(value: number): true; +export function isNumeric(value: unknown): boolean; +export function isNumeric(value: unknown) { + return value !== null && isFinite(value as number); +} + +/** + * Returns true on all falsey values except the numeric value 0. + */ +export function isFalseyButZero( + value: unknown +): value is undefined | null | false | '' { + return !value && value !== 0; +} + +/** + * Returns a number if the passed parameter is a valid number or the function will return undefined. On all other values than a valid number, this function will return undefined. + */ +export function getNumberOrUndefined(value: number): number; +export function getNumberOrUndefined(value: unknown): number | undefined; +export function getNumberOrUndefined(value: unknown) { + return isNumeric(value) ? Number(value) : undefined; +} + +/** + * Checks if value is array of arrays or not. + */ +export function isArrayOfArrays(data: unknown): data is unknown[][] { + if (!Array.isArray(data)) { + return false; + } + + return data.every(Array.isArray); +} + +/** + * Loop over array. + */ +export function each( + list: T[], + callback: (item: T, index: number, itemIndex: number) => void, + reverse = false +) { + let index = 0; + + list[reverse ? 'reduceRight' : 'reduce']( + (_, item, itemIndex) => callback(item, index++, itemIndex), + void 0 + ); +} diff --git a/test/.jshintrc b/test/.jshintrc deleted file mode 100644 index b1be025b8..000000000 --- a/test/.jshintrc +++ /dev/null @@ -1,36 +0,0 @@ -{ - "node": true, - "browser": true, - "esnext": true, - "bitwise": true, - "camelcase": true, - "curly": true, - "eqeqeq": true, - "immed": true, - "indent": 2, - "latedef": true, - "newcap": true, - "noarg": true, - "quotmark": "single", - "regexp": true, - "undef": true, - "unused": true, - "strict": true, - "trailing": true, - "smarttabs": true, - "globals": { - "after": false, - "afterEach": false, - "angular": false, - "before": false, - "beforeEach": false, - "browser": false, - "describe": false, - "expect": false, - "inject": false, - "it": false, - "jasmine": false, - "spyOn": false - } -} - diff --git a/test/__image_snapshots__/BarChart__Accumulate-Relative-Stack-snap.png b/test/__image_snapshots__/BarChart__Accumulate-Relative-Stack-snap.png new file mode 100644 index 000000000..0515878ce Binary files /dev/null and b/test/__image_snapshots__/BarChart__Accumulate-Relative-Stack-snap.png differ diff --git a/test/__image_snapshots__/BarChart__Adaptive-snap.png b/test/__image_snapshots__/BarChart__Adaptive-snap.png new file mode 100644 index 000000000..3207acb97 Binary files /dev/null and b/test/__image_snapshots__/BarChart__Adaptive-snap.png differ diff --git a/test/__image_snapshots__/BarChart__Adaptive__iPad-snap.png b/test/__image_snapshots__/BarChart__Adaptive__iPad-snap.png new file mode 100644 index 000000000..c224a00c3 Binary files /dev/null and b/test/__image_snapshots__/BarChart__Adaptive__iPad-snap.png differ diff --git a/test/__image_snapshots__/BarChart__Adaptive__iPhone-X-landscape-snap.png b/test/__image_snapshots__/BarChart__Adaptive__iPhone-X-landscape-snap.png new file mode 100644 index 000000000..c29da124c Binary files /dev/null and b/test/__image_snapshots__/BarChart__Adaptive__iPhone-X-landscape-snap.png differ diff --git a/test/__image_snapshots__/BarChart__Adaptive__iPhone-X-snap.png b/test/__image_snapshots__/BarChart__Adaptive__iPhone-X-snap.png new file mode 100644 index 000000000..61705ad55 Binary files /dev/null and b/test/__image_snapshots__/BarChart__Adaptive__iPhone-X-snap.png differ diff --git a/test/__image_snapshots__/BarChart__Bi-Polar-snap.png b/test/__image_snapshots__/BarChart__Bi-Polar-snap.png new file mode 100644 index 000000000..0be568b47 Binary files /dev/null and b/test/__image_snapshots__/BarChart__Bi-Polar-snap.png differ diff --git a/test/__image_snapshots__/BarChart__Default-snap.png b/test/__image_snapshots__/BarChart__Default-snap.png new file mode 100644 index 000000000..7286701a2 Binary files /dev/null and b/test/__image_snapshots__/BarChart__Default-snap.png differ diff --git a/test/__image_snapshots__/BarChart__Distributed-Series-snap.png b/test/__image_snapshots__/BarChart__Distributed-Series-snap.png new file mode 100644 index 000000000..af1443b27 Binary files /dev/null and b/test/__image_snapshots__/BarChart__Distributed-Series-snap.png differ diff --git a/test/__image_snapshots__/BarChart__Horizontal-snap.png b/test/__image_snapshots__/BarChart__Horizontal-snap.png new file mode 100644 index 000000000..a0b62a933 Binary files /dev/null and b/test/__image_snapshots__/BarChart__Horizontal-snap.png differ diff --git a/test/__image_snapshots__/BarChart__Labels-Placement-snap.png b/test/__image_snapshots__/BarChart__Labels-Placement-snap.png new file mode 100644 index 000000000..e96177749 Binary files /dev/null and b/test/__image_snapshots__/BarChart__Labels-Placement-snap.png differ diff --git a/test/__image_snapshots__/BarChart__Labels-snap.png b/test/__image_snapshots__/BarChart__Labels-snap.png new file mode 100644 index 000000000..694b2be43 Binary files /dev/null and b/test/__image_snapshots__/BarChart__Labels-snap.png differ diff --git a/test/__image_snapshots__/BarChart__Multi-Series-snap.png b/test/__image_snapshots__/BarChart__Multi-Series-snap.png new file mode 100644 index 000000000..06b6b57a9 Binary files /dev/null and b/test/__image_snapshots__/BarChart__Multi-Series-snap.png differ diff --git a/test/__image_snapshots__/BarChart__Multiline-Labels-snap.png b/test/__image_snapshots__/BarChart__Multiline-Labels-snap.png new file mode 100644 index 000000000..eb6f46152 Binary files /dev/null and b/test/__image_snapshots__/BarChart__Multiline-Labels-snap.png differ diff --git a/test/__image_snapshots__/BarChart__Overlapping-Bars-On-Mobile-snap.png b/test/__image_snapshots__/BarChart__Overlapping-Bars-On-Mobile-snap.png new file mode 100644 index 000000000..92ee2983c Binary files /dev/null and b/test/__image_snapshots__/BarChart__Overlapping-Bars-On-Mobile-snap.png differ diff --git a/test/__image_snapshots__/BarChart__Overlapping-Bars-On-Mobile__iPhone-X-snap.png b/test/__image_snapshots__/BarChart__Overlapping-Bars-On-Mobile__iPhone-X-snap.png new file mode 100644 index 000000000..c60f8cce3 Binary files /dev/null and b/test/__image_snapshots__/BarChart__Overlapping-Bars-On-Mobile__iPhone-X-snap.png differ diff --git a/test/__image_snapshots__/BarChart__Peak-Circles-snap.png b/test/__image_snapshots__/BarChart__Peak-Circles-snap.png new file mode 100644 index 000000000..0acdc885b Binary files /dev/null and b/test/__image_snapshots__/BarChart__Peak-Circles-snap.png differ diff --git a/test/__image_snapshots__/BarChart__Reverse-Data-snap.png b/test/__image_snapshots__/BarChart__Reverse-Data-snap.png new file mode 100644 index 000000000..225e08137 Binary files /dev/null and b/test/__image_snapshots__/BarChart__Reverse-Data-snap.png differ diff --git a/test/__image_snapshots__/BarChart__Stack-snap.png b/test/__image_snapshots__/BarChart__Stack-snap.png new file mode 100644 index 000000000..ae6a3e4c8 Binary files /dev/null and b/test/__image_snapshots__/BarChart__Stack-snap.png differ diff --git a/test/__image_snapshots__/LineChart__Area-snap.png b/test/__image_snapshots__/LineChart__Area-snap.png new file mode 100644 index 000000000..195db70af Binary files /dev/null and b/test/__image_snapshots__/LineChart__Area-snap.png differ diff --git a/test/__image_snapshots__/LineChart__Auto-Scale-snap.png b/test/__image_snapshots__/LineChart__Auto-Scale-snap.png new file mode 100644 index 000000000..3229d2a68 Binary files /dev/null and b/test/__image_snapshots__/LineChart__Auto-Scale-snap.png differ diff --git a/test/__image_snapshots__/LineChart__Bi-Polar-Area-snap.png b/test/__image_snapshots__/LineChart__Bi-Polar-Area-snap.png new file mode 100644 index 000000000..41d4ef02d Binary files /dev/null and b/test/__image_snapshots__/LineChart__Bi-Polar-Area-snap.png differ diff --git a/test/__image_snapshots__/LineChart__Cardinal-Interpolation-With-Holes-snap.png b/test/__image_snapshots__/LineChart__Cardinal-Interpolation-With-Holes-snap.png new file mode 100644 index 000000000..7d01b58f1 Binary files /dev/null and b/test/__image_snapshots__/LineChart__Cardinal-Interpolation-With-Holes-snap.png differ diff --git a/test/__image_snapshots__/LineChart__Custom-Points-snap.png b/test/__image_snapshots__/LineChart__Custom-Points-snap.png new file mode 100644 index 000000000..ba4ca33a2 Binary files /dev/null and b/test/__image_snapshots__/LineChart__Custom-Points-snap.png differ diff --git a/test/__image_snapshots__/LineChart__Default-snap.png b/test/__image_snapshots__/LineChart__Default-snap.png new file mode 100644 index 000000000..b8cb76ce0 Binary files /dev/null and b/test/__image_snapshots__/LineChart__Default-snap.png differ diff --git a/test/__image_snapshots__/LineChart__Filled-Holes-snap.png b/test/__image_snapshots__/LineChart__Filled-Holes-snap.png new file mode 100644 index 000000000..16beed08d Binary files /dev/null and b/test/__image_snapshots__/LineChart__Filled-Holes-snap.png differ diff --git a/test/__image_snapshots__/LineChart__Full-Width-snap.png b/test/__image_snapshots__/LineChart__Full-Width-snap.png new file mode 100644 index 000000000..28e7a3ac4 Binary files /dev/null and b/test/__image_snapshots__/LineChart__Full-Width-snap.png differ diff --git a/test/__image_snapshots__/LineChart__Holes-snap.png b/test/__image_snapshots__/LineChart__Holes-snap.png new file mode 100644 index 000000000..34e2a126f Binary files /dev/null and b/test/__image_snapshots__/LineChart__Holes-snap.png differ diff --git a/test/__image_snapshots__/LineChart__Labels-snap.png b/test/__image_snapshots__/LineChart__Labels-snap.png new file mode 100644 index 000000000..84986cbb8 Binary files /dev/null and b/test/__image_snapshots__/LineChart__Labels-snap.png differ diff --git a/test/__image_snapshots__/LineChart__Monotone-Cubic-Interpolation-With-Holes-snap.png b/test/__image_snapshots__/LineChart__Monotone-Cubic-Interpolation-With-Holes-snap.png new file mode 100644 index 000000000..7d01b58f1 Binary files /dev/null and b/test/__image_snapshots__/LineChart__Monotone-Cubic-Interpolation-With-Holes-snap.png differ diff --git a/test/__image_snapshots__/LineChart__Multi-Series-snap.png b/test/__image_snapshots__/LineChart__Multi-Series-snap.png new file mode 100644 index 000000000..4000c8446 Binary files /dev/null and b/test/__image_snapshots__/LineChart__Multi-Series-snap.png differ diff --git a/test/__image_snapshots__/LineChart__No-Interpolation-With-Holes-snap.png b/test/__image_snapshots__/LineChart__No-Interpolation-With-Holes-snap.png new file mode 100644 index 000000000..725e23cea Binary files /dev/null and b/test/__image_snapshots__/LineChart__No-Interpolation-With-Holes-snap.png differ diff --git a/test/__image_snapshots__/LineChart__Only-Whole-Numbers-snap.png b/test/__image_snapshots__/LineChart__Only-Whole-Numbers-snap.png new file mode 100644 index 000000000..deb68cfd6 Binary files /dev/null and b/test/__image_snapshots__/LineChart__Only-Whole-Numbers-snap.png differ diff --git a/test/__image_snapshots__/LineChart__Path-Animation-snap.png b/test/__image_snapshots__/LineChart__Path-Animation-snap.png new file mode 100644 index 000000000..bef06c594 Binary files /dev/null and b/test/__image_snapshots__/LineChart__Path-Animation-snap.png differ diff --git a/test/__image_snapshots__/LineChart__Reverse-Data-snap.png b/test/__image_snapshots__/LineChart__Reverse-Data-snap.png new file mode 100644 index 000000000..d6a6fe670 Binary files /dev/null and b/test/__image_snapshots__/LineChart__Reverse-Data-snap.png differ diff --git a/test/__image_snapshots__/LineChart__Scatter-snap.png b/test/__image_snapshots__/LineChart__Scatter-snap.png new file mode 100644 index 000000000..15570fc49 Binary files /dev/null and b/test/__image_snapshots__/LineChart__Scatter-snap.png differ diff --git a/test/__image_snapshots__/LineChart__Series-Overrides-snap.png b/test/__image_snapshots__/LineChart__Series-Overrides-snap.png new file mode 100644 index 000000000..dd1589ef7 Binary files /dev/null and b/test/__image_snapshots__/LineChart__Series-Overrides-snap.png differ diff --git a/test/__image_snapshots__/LineChart__Simple-Interpolation-With-Holes-snap.png b/test/__image_snapshots__/LineChart__Simple-Interpolation-With-Holes-snap.png new file mode 100644 index 000000000..dc2e4108a Binary files /dev/null and b/test/__image_snapshots__/LineChart__Simple-Interpolation-With-Holes-snap.png differ diff --git a/test/__image_snapshots__/LineChart__Step-Interpolation-With-Holes-snap.png b/test/__image_snapshots__/LineChart__Step-Interpolation-With-Holes-snap.png new file mode 100644 index 000000000..9be3e6698 Binary files /dev/null and b/test/__image_snapshots__/LineChart__Step-Interpolation-With-Holes-snap.png differ diff --git a/test/__image_snapshots__/LineChart__Step-No-Postpone-Interpolation-With-Holes-snap.png b/test/__image_snapshots__/LineChart__Step-No-Postpone-Interpolation-With-Holes-snap.png new file mode 100644 index 000000000..ca47a0314 Binary files /dev/null and b/test/__image_snapshots__/LineChart__Step-No-Postpone-Interpolation-With-Holes-snap.png differ diff --git a/test/__image_snapshots__/PieChart__Default-snap.png b/test/__image_snapshots__/PieChart__Default-snap.png new file mode 100644 index 000000000..8eecfb007 Binary files /dev/null and b/test/__image_snapshots__/PieChart__Default-snap.png differ diff --git a/test/__image_snapshots__/PieChart__Donut-snap.png b/test/__image_snapshots__/PieChart__Donut-snap.png new file mode 100644 index 000000000..0625c107d Binary files /dev/null and b/test/__image_snapshots__/PieChart__Donut-snap.png differ diff --git a/test/__image_snapshots__/PieChart__Gauge-Donut-snap.png b/test/__image_snapshots__/PieChart__Gauge-Donut-snap.png new file mode 100644 index 000000000..cb27df6fb Binary files /dev/null and b/test/__image_snapshots__/PieChart__Gauge-Donut-snap.png differ diff --git a/test/__image_snapshots__/PieChart__Ignore-Empty-Values-snap.png b/test/__image_snapshots__/PieChart__Ignore-Empty-Values-snap.png new file mode 100644 index 000000000..a948a05ba Binary files /dev/null and b/test/__image_snapshots__/PieChart__Ignore-Empty-Values-snap.png differ diff --git a/test/__image_snapshots__/PieChart__Label-Interpolation-snap.png b/test/__image_snapshots__/PieChart__Label-Interpolation-snap.png new file mode 100644 index 000000000..ccd6d72ee Binary files /dev/null and b/test/__image_snapshots__/PieChart__Label-Interpolation-snap.png differ diff --git a/test/__image_snapshots__/PieChart__Labels-snap.png b/test/__image_snapshots__/PieChart__Labels-snap.png new file mode 100644 index 000000000..e4b05aee0 Binary files /dev/null and b/test/__image_snapshots__/PieChart__Labels-snap.png differ diff --git a/test/__image_snapshots__/PieChart__Relative-Donut-Width-snap.png b/test/__image_snapshots__/PieChart__Relative-Donut-Width-snap.png new file mode 100644 index 000000000..6d1a893a0 Binary files /dev/null and b/test/__image_snapshots__/PieChart__Relative-Donut-Width-snap.png differ diff --git a/test/__image_snapshots__/PieChart__Small-Slices-snap.png b/test/__image_snapshots__/PieChart__Small-Slices-snap.png new file mode 100644 index 000000000..6140a2aea Binary files /dev/null and b/test/__image_snapshots__/PieChart__Small-Slices-snap.png differ diff --git a/test/__image_snapshots__/PieChart__Solid-snap.png b/test/__image_snapshots__/PieChart__Solid-snap.png new file mode 100644 index 000000000..061dae578 Binary files /dev/null and b/test/__image_snapshots__/PieChart__Solid-snap.png differ diff --git a/test/__image_snapshots__/PieChart__Start-Angle-snap.png b/test/__image_snapshots__/PieChart__Start-Angle-snap.png new file mode 100644 index 000000000..bcae00048 Binary files /dev/null and b/test/__image_snapshots__/PieChart__Start-Angle-snap.png differ diff --git a/test/mock/cssModule.js b/test/mock/cssModule.js new file mode 100644 index 000000000..475289e28 --- /dev/null +++ b/test/mock/cssModule.js @@ -0,0 +1,10 @@ +const mock = new Proxy( + {}, + { + get() { + return ''; + } + } +); + +module.exports = mock; diff --git a/test/mock/dom.ts b/test/mock/dom.ts new file mode 100644 index 000000000..aa9a87595 --- /dev/null +++ b/test/mock/dom.ts @@ -0,0 +1,73 @@ +export type Fixture = ReturnType; + +export let container: HTMLDivElement | null = null; + +const getBoundingClientRect = SVGElement.prototype.getBoundingClientRect; + +export function mockDom() { + if (!container) { + container = document.createElement('div'); + container.setAttribute('data-fixture-container', `${+new Date()}`); + document.body.appendChild(container); + } +} + +export function destroyMockDom() { + if (container) { + document.body.removeChild(container); + container = null; + } +} + +export function addMockWrapper(fixture: string) { + const wrapper = document.createElement('div'); + wrapper.innerHTML += fixture; + container?.appendChild(wrapper); + return { + wrapper, + container, + fixture + }; +} + +export function mockDomRects() { + // @ts-expect-error Mock DOM API. + SVGElement.prototype.getBoundingClientRect = () => ({ + x: 0, + y: 0, + width: 500, + height: 500, + top: 0, + right: 0, + bottom: 0, + left: 0 + }); + + Object.defineProperties(SVGElement.prototype, { + clientWidth: { + configurable: true, + get: () => 500 + }, + clientHeight: { + configurable: true, + get: () => 500 + } + }); +} + +export function destroyMockDomRects() { + SVGElement.prototype.getBoundingClientRect = getBoundingClientRect; + + // Redefine clientWidth and clientHeight properties from the prototype of SVGElement + const ElementPrototype = Object.getPrototypeOf(SVGElement.prototype); + Object.defineProperties(SVGElement.prototype, { + clientWidth: Object.getOwnPropertyDescriptor( + ElementPrototype, + 'clientWidth' + )!, + clientHeight: Object.getOwnPropertyDescriptor( + ElementPrototype, + 'clientHeight' + )! + }); +} diff --git a/test/runner.html b/test/runner.html deleted file mode 100644 index 964130166..000000000 --- a/test/runner.html +++ /dev/null @@ -1,36 +0,0 @@ - - - - End2end Test Runner - - - - -
-
-
-

Chart CSS animation example

-
-
-
- -
-
- -
-
- - \ No newline at end of file diff --git a/test/setup.js b/test/setup.js new file mode 100644 index 000000000..b69ed17ea --- /dev/null +++ b/test/setup.js @@ -0,0 +1,3 @@ +import '@testing-library/jest-dom/extend-expect'; + +window.matchMedia = () => ({}); diff --git a/test/spec/spec-line-chart.js b/test/spec/spec-line-chart.js deleted file mode 100644 index e57678ee6..000000000 --- a/test/spec/spec-line-chart.js +++ /dev/null @@ -1,16 +0,0 @@ -//TODO: Add tests! -describe('Line chart tests', function() { - 'use strict'; - - beforeEach(function() { - - }); - - afterEach(function() { - - }); - - it('should not give an error because we have 0% test coverage ;-)', function() { - expect(true).toBe(true); - }); -}); \ No newline at end of file diff --git a/test/spec/spec-svg.js b/test/spec/spec-svg.js deleted file mode 100644 index ee28ae7a9..000000000 --- a/test/spec/spec-svg.js +++ /dev/null @@ -1,162 +0,0 @@ -//TODO: Add tests! -describe('Chartist SVG', function () { - 'use strict'; - - beforeEach(function () { - - }); - - afterEach(function () { - - }); - - it('should exist in global namespace', function () { - expect(window.Chartist.svg).toBeDefined(); - }); - - it('should create a valid svg dom element', function () { - var svg = window.Chartist.svg('svg'); - - expect(svg).toBeDefined(); - expect(svg._node).toBeDefined(); - expect(svg._node.nodeName.toLowerCase()).toBe('svg'); - }); - - it('should create a valid svg dom element with attributes', function () { - var svg = window.Chartist.svg('svg', { - width: '100%', - height: '100%' - }); - - expect(svg).toBeDefined(); - expect(svg._node).toBeDefined(); - expect(svg._node.nodeName.toLowerCase()).toBe('svg'); - expect(svg._node.attributes.width.textContent).toBe('100%'); - expect(svg._node.attributes.height.textContent).toBe('100%'); - }); - - it('should create nested objects with attributes', function () { - var svg = window.Chartist.svg('svg'); - svg.elem('g').elem('g').elem('circle', { - cx: 100, - cy: 100, - r: 10 - }); - - expect(svg._node).toBeDefined(); - expect(svg._node.firstChild.firstChild.firstChild).toBeDefined(); - expect(svg._node.firstChild.firstChild.firstChild.attributes.cx.textContent).toBe('100'); - expect(svg._node.firstChild.firstChild.firstChild.attributes.cy.textContent).toBe('100'); - expect(svg._node.firstChild.firstChild.firstChild.attributes.r.textContent).toBe('10'); - }); - - it('should allow to set attributes manually', function () { - var svg = window.Chartist.svg('svg'); - svg.elem('circle').attr({ - cx: 100, - cy: 100, - r: 10 - }); - - expect(svg._node).toBeDefined(); - expect(svg._node.firstChild).toBeDefined(); - expect(svg._node.firstChild.attributes.cx.textContent).toBe('100'); - expect(svg._node.firstChild.attributes.cy.textContent).toBe('100'); - expect(svg._node.firstChild.attributes.r.textContent).toBe('10'); - }); - - it('should clear on each nesting level', function () { - var svg = window.Chartist.svg('svg'); - var group = svg.elem('g'); - group.elem('circle'); - group.elem('circle'); - group.elem('circle'); - - expect(svg._node).toBeDefined(); - expect(svg._node.firstChild.childNodes.length).toBe(3); - - group.empty(); - expect(svg._node.firstChild.childNodes.length).toBe(0); - - svg.empty(); - expect(svg._node.firstChild).toBeNull(); - }); - - it('should allow to remove a certain element', function () { - var svg = window.Chartist.svg('svg'); - var text = svg.elem('text'); - - expect(svg._node).toBeDefined(); - expect(svg._node.childNodes.length).toBe(1); - expect(svg._node.firstChild.nodeName.toLowerCase()).toBe('text'); - - text.remove(); - expect(svg._node.childNodes.length).toBe(0); - }); - - it('should allow to write text content into elements', function () { - var svg = window.Chartist.svg('svg'); - svg.elem('text').text('Hello World'); - - expect(svg._node).toBeDefined(); - expect(svg._node.childNodes.length).toBe(1); - expect(svg._node.firstChild.nodeName.toLowerCase()).toBe('text'); - expect(svg._node.firstChild.firstChild.nodeType).toBe(3); - expect(svg._node.firstChild.firstChild.textContent).toBe('Hello World'); - }); - - it('should allow to add and remove classes on elements', function () { - var svg = window.Chartist.svg('svg') - .addClass('test-class-1') - .addClass('test-class-2') - // Should not allow duplicates - .addClass('test-class-2') - // Should allow multiple classes with white spaces - .addClass('test-class-3 test-class-4'); - - expect(svg._node).toBeDefined(); - expect(svg._node.getAttribute('class').split(' ')).toEqual([ - 'test-class-1', - 'test-class-2', - 'test-class-3', - 'test-class-4' - ]); - - svg.removeClass('test-class-1'); - // Should allow multiple classes with whitespaces - svg.removeClass('test-class-2 test-class-3'); - - expect(svg._node.getAttribute('class')).toBe('test-class-4'); - }); - - it('should allow to travers up in the fluent API chain and set attributes on the way', function () { - var svg = window.Chartist.svg('svg'); - svg.elem('g').elem('g').elem('g').elem('circle') - .parent().attr({ - transform: 'rotate(10 10 10)' - }) - .parent().attr({ - transform: 'rotate(20 20 20)' - }) - .parent().attr({ - transform: 'rotate(30 30 30)' - }) - .parent().attr({ - width: '100%', - height: '100%' - }); - - expect(svg._node).toBeDefined(); - expect(svg._node.attributes.width.textContent).toBe('100%'); - expect(svg._node.attributes.height.textContent).toBe('100%'); - - expect(svg._node.firstChild).toBeDefined(); - expect(svg._node.firstChild.attributes.transform.textContent).toBe('rotate(30 30 30)'); - - expect(svg._node.firstChild.firstChild).toBeDefined(); - expect(svg._node.firstChild.firstChild.attributes.transform.textContent).toBe('rotate(20 20 20)'); - - expect(svg._node.firstChild.firstChild.firstChild).toBeDefined(); - expect(svg._node.firstChild.firstChild.firstChild.attributes.transform.textContent).toBe('rotate(10 10 10)'); - }); -}); \ No newline at end of file diff --git a/test/storyshots.spec.js b/test/storyshots.spec.js new file mode 100644 index 000000000..d146e27cf --- /dev/null +++ b/test/storyshots.spec.js @@ -0,0 +1,24 @@ +import { skipable } from './utils/skipable'; +import { initStoryshots } from './utils/storyshots'; + +const testTimeout = 60 * 1000 * 10; +const config = { + url: 'http://localhost:6006/', + setupTimeout: testTimeout, + testTimeout, + getGotoOptions() { + return { + waitUntil: 'networkidle0', + timeout: 0 + }; + } +}; + +const describeWhenLinux = skipable( + describe, + process.platform !== 'linux' || Boolean(process.env.STORYSHOTS_SKIP) +); + +describeWhenLinux('Storyshots', () => { + initStoryshots(config); +}); diff --git a/test/utils/skipable.js b/test/utils/skipable.js new file mode 100644 index 000000000..fa8a11ef3 --- /dev/null +++ b/test/utils/skipable.js @@ -0,0 +1,9 @@ +/** + * Make block definition method skipable. + * @param fn - Jest's block definition method. + * @param skip - Skip test block. + * @returns Skipable block definition methid. + */ +export function skipable(fn, skip) { + return skip ? fn.skip : fn; +} diff --git a/test/utils/storyshots/imageSnapshotWithStoryParameters.js b/test/utils/storyshots/imageSnapshotWithStoryParameters.js new file mode 100644 index 000000000..96b374995 --- /dev/null +++ b/test/utils/storyshots/imageSnapshotWithStoryParameters.js @@ -0,0 +1,108 @@ +import { devices } from 'puppeteer'; +import { imageSnapshot } from '@storybook/addon-storyshots-puppeteer'; + +import { Viewport } from './viewport'; + +const captureRoot = true; +const offset = '40'; + +/** + * Handle story parameters. + * @param page - Page instance. + * @param options - Story options. + * @returns Promise. + */ +async function beforeScreenshotHook(page, options) { + const { + storyshots: { currentViewport } = {}, + parameters: { storyshots: { beforeScreenshot } = {} } + } = options.context; + + if (currentViewport && currentViewport !== Viewport.Default) { + await page.emulate(devices[currentViewport]); + } + + if (beforeScreenshot) { + await beforeScreenshot(page, options); + } + + if (captureRoot) { + await page.$eval( + '#root', + (root, offset) => { + root.style.padding = `${offset}px`; + }, + offset + ); + + return page.$('#root'); + } + + return null; +} + +function getCaptureRootScreenshotOptions() { + return { + encoding: 'base64', // encoding: 'base64' is a property required by puppeteer + fullPage: !captureRoot + }; +} + +/** + * Create snapshot tests function with story parameters. + * @param config - Snapshots config. + * @returns Snapshot tests function. + */ +export function imageSnapshotWithStoryParameters(config) { + const { beforeScreenshot, getScreenshotOptions } = config; + const configWithBeforeScreenshot = { + ...config, + getScreenshotOptions: getScreenshotOptions + ? options => ({ + ...getCaptureRootScreenshotOptions(options), + ...getScreenshotOptions(options) + }) + : getCaptureRootScreenshotOptions, + beforeScreenshot: beforeScreenshot + ? async (page, options) => { + const captureTarget = await beforeScreenshotHook(page, options); + + await beforeScreenshot(page, options); + + return captureTarget; + } + : beforeScreenshotHook + }; + const test = imageSnapshot(configWithBeforeScreenshot); + const testFn = async options => { + const { context } = options; + const { storyshots: { viewports = [] } = {} } = context.parameters; + + if (!viewports.length) { + await test(options); + return; + } + + for (const viewport of viewports) { + const currentViewport = + viewport === Viewport.Default ? undefined : viewport; + const originalId = context.id; + + context.storyshots = { + currentViewport + }; + + await test(options); + + context.id = originalId; + } + + expect.assertions(viewports.length); + }; + + testFn.timeout = test.timeout; + testFn.beforeAll = test.beforeAll; + testFn.afterAll = test.afterAll; + + return testFn; +} diff --git a/test/utils/storyshots/index.js b/test/utils/storyshots/index.js new file mode 100644 index 000000000..d1620f4ba --- /dev/null +++ b/test/utils/storyshots/index.js @@ -0,0 +1,3 @@ +export * from './initStoryshots'; +export * from './imageSnapshotWithStoryParameters'; +export * from './storybook'; diff --git a/test/utils/storyshots/initStoryshots.js b/test/utils/storyshots/initStoryshots.js new file mode 100644 index 000000000..28daaae91 --- /dev/null +++ b/test/utils/storyshots/initStoryshots.js @@ -0,0 +1,91 @@ +import baseInitStoryshots from '@storybook/addon-storyshots'; + +import { imageSnapshotWithStoryParameters } from './imageSnapshotWithStoryParameters'; +import { startStorybook } from './storybook'; + +/** + * Default page customizer. + * @param page - Puppeteer's page instance. + * @returns Task promise. + */ +export function defaultCustomizePage(page) { + return page.setViewport({ + width: 1920, + height: 1080 + }); +} + +/** + * Prepare identifier for use in filename. + * @param indentifierPart - Identifier string part. + * @returns Sanitized identifier ready for use in filename. + */ +export function sanitizeSnapshotIdentifierPart(indentifierPart) { + return indentifierPart.replace(/[\s/]|%20/g, '-').replace(/"|%22/g, ''); +} + +/** + * Default match options creator. + * @param storyOptions - Story info. + * @param storyOptions.context - Story context. + * @param storyOptions.context.kind - Story kind. + * @param storyOptions.context.story - Story name. + * @param storyOptions.context.storyshots - Storyshots metadata. + * @returns Match options. + */ +export function defaultGetMatchOptions({ + context: { kind, story, storyshots } +}) { + const currentViewport = storyshots?.currentViewport; + const sanitizedKind = sanitizeSnapshotIdentifierPart(kind); + const sanitizedStory = sanitizeSnapshotIdentifierPart(story); + const sanitizedParams = currentViewport + ? `__${sanitizeSnapshotIdentifierPart(currentViewport)}` + : ''; + + process.stdout.write(`šŸ“· ${kind} ${story} ${currentViewport || ''}\n`); + + return { + customSnapshotIdentifier: `${sanitizedKind}__${sanitizedStory}${sanitizedParams}` + }; +} + +/** + * Initialize and run storyshots. + * @param config - Storyshots config. + */ +export function initStoryshots(config) { + process.env.STORYBOOK_STORYSHOTS = JSON.stringify(true); + + const finalOptions = { + getMatchOptions: defaultGetMatchOptions, + customizePage: defaultCustomizePage, + ...config + }; + const storybook = startStorybook(config); + const test = imageSnapshotWithStoryParameters({ + storybookUrl: config.url, + ...finalOptions + }); + const { beforeAll, afterAll } = test; + const { warn } = console; + + test.beforeAll = async () => { + await storybook.start(); + await beforeAll(); + }; + test.beforeAll.timeout = beforeAll.timeout; + + test.afterAll = async () => { + await storybook.stop(); + await afterAll(); + }; + + console.warn = () => undefined; + baseInitStoryshots({ + framework: 'html', + suite: 'Storyshots', + test + }); + console.warn = warn; +} diff --git a/test/utils/storyshots/storybook.js b/test/utils/storyshots/storybook.js new file mode 100644 index 000000000..184173c03 --- /dev/null +++ b/test/utils/storyshots/storybook.js @@ -0,0 +1,86 @@ +import { spawn } from 'child_process'; + +import { createServer } from 'http-server'; +import del from 'del'; + +const STORYBOOK_STATIC = 'storybook-static'; +const errorMatcher = /ERR!|Error:|ERROR in|UnhandledPromiseRejectionWarning/; + +/** + * Run storybook static build. + * @param options - Build options. + * @param [options.env] - Environment variables. + * @param [options.verbose] - Print verbose messages. + * @returns Build process promise. + */ +export async function buildStorybook({ env = {}, verbose = false }) { + return new Promise((resolve, reject) => { + const buildProcess = spawn('build-storybook', [], { + cwd: process.cwd(), + env: { + ...process.env, + NODE_ENV: 'production', + ...env + }, + detached: true + }); + const onData = data => { + const message = data.toString('utf8'); + + if (verbose) { + process.stdout.write(message); + } + + if (errorMatcher.test(message)) { + reject(new Error(message)); + } + }; + + buildProcess.on('exit', (code, signal) => { + if (code === 0) { + resolve(); + return; + } + + reject(new Error(`Exit code: ${code || signal || 'unknown'}`)); + }); + buildProcess.stdout.on('data', onData); + buildProcess.stderr.on('data', onData); + }); +} + +/** + * Build static and start storybook server. + * @param options - Storybook build and start options. + * @returns Server controls. + */ +export function startStorybook(options) { + const { url, skipBuild } = options; + const parsedUrl = new URL(url); + const server = createServer({ + root: STORYBOOK_STATIC + }); + + return { + async start() { + if (!skipBuild) { + await buildStorybook(options); + } + + await new Promise(resolve => { + server.listen( + parseInt(parsedUrl.port, 10), + parsedUrl.hostname, + resolve + ); + }); + }, + async stop() { + server.close(); + + if (!skipBuild) { + await del(STORYBOOK_STATIC); + } + } + }; +} diff --git a/test/utils/storyshots/viewport.ts b/test/utils/storyshots/viewport.ts new file mode 100644 index 000000000..b2163bb44 --- /dev/null +++ b/test/utils/storyshots/viewport.ts @@ -0,0 +1,11 @@ +export const Viewport = { + Default: 'default', + Mobile: 'iPhone X', + MobileLandscape: 'iPhone X landscape', + SmallMobile: 'iPhone SE', + SmallMobileLandscape: 'iPhone SE landscape', + Tablet: 'iPad', + TabletLandscape: 'iPad landscape', + SmallTablet: 'Nexus 7', + SmallTabletLandscape: 'Nexus 7 landscape' +}; diff --git a/tsconfig.build.json b/tsconfig.build.json new file mode 100644 index 000000000..60ecc2f2f --- /dev/null +++ b/tsconfig.build.json @@ -0,0 +1,7 @@ +{ + "extends": "./tsconfig.json", + "exclude": [ + "**/*.stories.ts", + "**/*.spec.ts" + ] +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 000000000..c2ce442d4 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,39 @@ +{ + "compilerOptions": { + /* Type Checking */ + "strict": true, + "strictBindCallApply": true, + "noFallthroughCasesInSwitch": true, + "noImplicitOverride": true, + "noImplicitReturns": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + /* Modules */ + "baseUrl": ".", + "module": "esnext", + "moduleResolution": "node", + "resolveJsonModule": true, + "paths": { + "chartist-dev": ["src"] + }, + /* Emit */ + "declaration": true, + "declarationMap": true, + "inlineSourceMap": true, + "outDir": "dist", + /* Interop Constraints */ + "allowSyntheticDefaultImports": true, + "isolatedModules": true, + /* Language and Environment */ + "lib": [ + "dom", + "esnext" + ], + "target": "esnext", + /* Completeness */ + "skipLibCheck": true + }, + "include": [ + "src" + ] +} diff --git a/website/.gitignore b/website/.gitignore new file mode 100644 index 000000000..4ba260174 --- /dev/null +++ b/website/.gitignore @@ -0,0 +1,15 @@ +# Dependencies +/node_modules + +# Production +/build + +# Generated files +.docusaurus +.cache-loader + +# Misc +.DS_Store +.env.* + +npm-debug.log* diff --git a/website/CNAME b/website/CNAME new file mode 100644 index 000000000..8fbd97bc2 --- /dev/null +++ b/website/CNAME @@ -0,0 +1 @@ +chartist.js.org diff --git a/website/README.md b/website/README.md new file mode 100644 index 000000000..0e97a2ea6 --- /dev/null +++ b/website/README.md @@ -0,0 +1,33 @@ +# Website + +This website is built using [Docusaurus 2](https://docusaurus.io/), a modern static website generator. + +### Installation + +``` +$ pnpm install +``` + +### Local Development + +``` +$ pnpm start +``` + +This command starts a local development server and opens up a browser window. Most changes are reflected live without having to restart the server. + +### Build + +``` +$ pnpm build +``` + +This command generates static content into the `build` directory and can be served using any static contents hosting service. + +### Deployment + +``` +$ GIT_USER= USE_SSH=true pnpm deploy +``` + +If you are using GitHub pages for hosting, this command is a convenient way to build the website and push to the `gh-pages` branch. diff --git a/website/babel.config.js b/website/babel.config.js new file mode 100644 index 000000000..6bf8d26f1 --- /dev/null +++ b/website/babel.config.js @@ -0,0 +1,3 @@ +module.exports = { + presets: [require.resolve('@docusaurus/core/lib/babel/preset')] +}; diff --git a/website/docs/api/.gitignore b/website/docs/api/.gitignore new file mode 100644 index 000000000..3e91f8c09 --- /dev/null +++ b/website/docs/api/.gitignore @@ -0,0 +1,4 @@ +* +!.gitignore +!docs.js +!basics.md diff --git a/website/docs/api/basics.md b/website/docs/api/basics.md new file mode 100644 index 000000000..24074af44 --- /dev/null +++ b/website/docs/api/basics.md @@ -0,0 +1,21 @@ +--- +slug: /api/basics +description: List of Chartist basic APIs. +--- + +# List of basic APIs: + +- Charts + - [BarChart](/api/classes/BarChart) + - [LineChart](/api/classes/LineChart) + - [PieChart](/api/classes/PieChart) +- Axes types + - [AutoScaleAxis](/api/classes/AutoScaleAxis) + - [FixedScaleAxis](/api/classes/FixedScaleAxis) + - [StepAxis](/api/classes/StepAxis) +- Svg wrappers + - [Svg](/api/classes/Svg) + - [SvgPath](/api/classes/SvgPath) + - [SvgList](/api/classes/SvgList) +- [Interpolation](/api/namespaces/Interpolation) +- [EventEmitter](/api/classes/EventEmitter) diff --git a/website/docs/api/docs.js b/website/docs/api/docs.js new file mode 100644 index 000000000..94a72d60b --- /dev/null +++ b/website/docs/api/docs.js @@ -0,0 +1,14 @@ +exports.docs = [ + { title: 'Table of Contents', slug: '/api/basics' }, + { title: 'BarChart', slug: '/api/classes/BarChart' }, + { title: 'LineChart', slug: '/api/classes/LineChart' }, + { title: 'PieChart', slug: '/api/classes/PieChart' }, + { title: 'AutoScaleAxis', slug: '/api/classes/AutoScaleAxis' }, + { title: 'FixedScaleAxis', slug: '/api/classes/FixedScaleAxis' }, + { title: 'StepAxis', slug: '/api/classes/StepAxis' }, + { title: 'Svg', slug: '/api/classes/Svg' }, + { title: 'SvgPath', slug: '/api/classes/SvgPath' }, + { title: 'SvgList', slug: '/api/classes/SvgList' }, + { title: 'Interpolation', slug: '/api/namespaces/Interpolation' }, + { title: 'EventEmitter', slug: '/api/classes/EventEmitter' } +]; diff --git a/website/docs/docs.js b/website/docs/docs.js new file mode 100644 index 000000000..6ae675cac --- /dev/null +++ b/website/docs/docs.js @@ -0,0 +1,4 @@ +exports.docs = [ + { title: "What's new in v1?", slug: '/docs/whats-new-in-v1' }, + { title: 'What is it made for?', slug: '/docs/what-is-it-made-for' } +]; diff --git a/website/docs/examples/bar-chart.mdx b/website/docs/examples/bar-chart.mdx new file mode 100644 index 000000000..1249d1067 --- /dev/null +++ b/website/docs/examples/bar-chart.mdx @@ -0,0 +1,196 @@ +--- +description: Bar chart examples +--- + +import ContextProvider from '../../src/components/ContextProvider'; + +# Bar chart examples + +## Bi-polar bar chart + + + {({ branch, theme }) => ( + + )} + + +## Distributed series + + + {({ branch, theme }) => ( + + )} + + +## Extreme responsive configuration + + + {({ branch, theme }) => ( + + )} + + +## Horizontal bar chart + + + {({ branch, theme }) => ( + + )} + + +## Label placement + + + {({ branch, theme }) => ( + + )} + + +## Multi-line labels + + + {({ branch, theme }) => ( + + )} + + +## Overlapping bars on mobile + + + {({ branch, theme }) => ( + + )} + + +## Stacked bar chart + + + {({ branch, theme }) => ( + + )} + + +## Add peak circles using the draw events + + + {({ branch, theme }) => ( + + )} + diff --git a/website/docs/examples/docs.js b/website/docs/examples/docs.js new file mode 100644 index 000000000..7c3aa03c7 --- /dev/null +++ b/website/docs/examples/docs.js @@ -0,0 +1,5 @@ +exports.docs = [ + { title: 'Bar Chart', slug: '/examples/bar-chart' }, + { title: 'Line Chart', slug: '/examples/line-chart' }, + { title: 'Pie Chart', slug: '/examples/pie-chart' } +]; diff --git a/website/docs/examples/index.mdx b/website/docs/examples/index.mdx new file mode 100644 index 000000000..bf3567399 --- /dev/null +++ b/website/docs/examples/index.mdx @@ -0,0 +1,17 @@ +--- +slug: /examples +description: List of Chartist usage examples. +--- + +import Link from '@docusaurus/Link'; +import { docs } from './docs'; + +# Examples + +
    + {docs.map(({ title, slug }, i) => ( +
  • + {title} +
  • + ))} +
diff --git a/website/docs/examples/line-chart.mdx b/website/docs/examples/line-chart.mdx new file mode 100644 index 000000000..992bdfab0 --- /dev/null +++ b/website/docs/examples/line-chart.mdx @@ -0,0 +1,364 @@ +--- +description: Line chart examples +--- + +import ContextProvider from '../../src/components/ContextProvider'; + +# Line chart examples + +## Line chart with area + + + {({ branch, theme }) => ( + + )} + + +## Auto scale axis + + + {({ branch, theme }) => ( + + )} + + +## Fixed and auto scale axis + + + {({ branch, theme }) => ( + + )} + + +## Bi-polar Line chart with area only + + + {({ branch, theme }) => ( + + )} + + +## Filled holes in data + + + {({ branch, theme }) => ( + + )} + + +## Holes in data + + + {({ branch, theme }) => ( + + )} + + +## Using events to replace graphics + + + {({ branch, theme }) => ( + + )} + + +## Only whole numbers + + + {({ branch, theme }) => ( + + )} + + +## SVG Path animation + + + {({ branch, theme }) => ( + + )} + + +## Line scatter diagram with responsive settings + + + {({ branch, theme }) => ( + + )} + + +## Series Overrides + + + {({ branch, theme }) => ( + + )} + + +## Simple line chart + + + {({ branch, theme }) => ( + + )} + + +## Simple responsive options + + + {({ branch, theme }) => ( + + )} + + +## Line Interpolation / Smoothing + + + {({ branch, theme }) => ( + + )} + + +## Simple SMIL Animations + + + {({ branch, theme }) => ( + + )} + + +## Advanced SMIL Animations + + + {({ branch, theme }) => ( + + )} + + +## Timeseries + + + {({ branch, theme }) => ( + + )} + diff --git a/website/docs/examples/pie-chart.mdx b/website/docs/examples/pie-chart.mdx new file mode 100644 index 000000000..3b858933f --- /dev/null +++ b/website/docs/examples/pie-chart.mdx @@ -0,0 +1,112 @@ +--- +description: Pie chart examples +--- + +import ContextProvider from '../../src/components/ContextProvider'; + +# Pie chart examples + +## Pie chart with custom labels + + + {({ branch, theme }) => ( + + )} + + +## Animating a Donut with Svg.animate + + + {({ branch, theme }) => ( + + )} + + +## Donut chart + + + {({ branch, theme }) => ( + + )} + + +## Simple pie chart + + + {({ branch, theme }) => ( + + )} + + +## Gauge chart + + + {({ branch, theme }) => ( + + )} + diff --git a/website/docs/index.mdx b/website/docs/index.mdx new file mode 100644 index 000000000..08fcc3625 --- /dev/null +++ b/website/docs/index.mdx @@ -0,0 +1,113 @@ +--- +slug: / +description: A simple responsive charting library built with SVG +--- + +import Tabs from '@theme/Tabs'; +import TabItem from '@theme/TabItem'; +import logoUrl from '@site/static/img/chartist-guy.gif'; + +# Big welcome by the Chartist Guy + +[![NPM version][npm]][npm-url] +[![Downloads][downloads]][downloads-url] +[![Build status][build]][build-url] +[![Coverage status][coverage]][coverage-url] +[![Bundle size][size]][size-url] +[![Join the chat at https://gitter.im/gionkunz/chartist-js][chat]][chat-url] + +[npm]: https://img.shields.io/npm/v/chartist.svg +[npm-url]: https://www.npmjs.com/package/chartist + +[downloads]: https://img.shields.io/npm/dm/chartist.svg +[downloads-url]: https://www.npmjs.com/package/chartist + +[build]: https://img.shields.io/github/actions/workflow/status/chartist-js/chartist/ci.yml +[build-url]: https://github.com/chartist-js/chartist/actions + +[coverage]: https://img.shields.io/codecov/c/github/chartist-js/chartist.svg +[coverage-url]: https://app.codecov.io/gh/chartist-js/chartist + +[size]: https://img.shields.io/bundlephobia/minzip/chartist +[size-url]: https://bundlephobia.com/package/chartist + +[chat]: https://badges.gitter.im/gionkunz/chartist-js.svg +[chat-url]: https://gitter.im/gionkunz/chartist-js?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge + +

+ The Chartist Guy +

+ +Chartist is a simple responsive charting library built with SVG. There are hundreds of nice charting libraries already +out there, but they are either: + +- use the wrong technologies for illustration (canvas) +- weighs hundreds of kilobytes +- are not flexible enough while keeping the configuration simple +- are not friendly to designers +- more annoying things + +That's why we started Chartist and our goal is to solve all of the above issues. + +## Quickstart + +Install this library using your favorite package manager: + + + + + ```bash + pnpm add chartist + ``` + + + + + ```bash + yarn add chartist + ``` + + + + + ```bash + npm install --save chartist + ``` + + + + +Then, just import chart you want and use it: + +```js +import { BarChart } from 'chartist'; + +new BarChart('#chart', { + labels: ['W1', 'W2', 'W3', 'W4', 'W5', 'W6', 'W7', 'W8', 'W9', 'W10'], + series: [ + [1, 2, 4, 8, 6, -2, -1, -4, -6, -2] + ] +}, { + high: 10, + low: -10, + axisX: { + labelInterpolationFnc: (value, index) => (index % 2 === 0 ? value : null) + } +}); +``` + +:::tip Need an API to fetch data? +Please consider [Cube](https://cube.dev/?ref=eco-chartist), an open-source API for data apps. +::: + +[![supported by Cube](https://user-images.githubusercontent.com/986756/154330861-d79ab8ec-aacb-4af8-9e17-1b28f1eccb01.svg)](https://cube.dev/?ref=eco-chartist) + +## Examples + +Please see [live examples](/examples). + +## Getting Help + +Need help? Ask your question on [Gitter](https://gitter.im/gionkunz/chartist-js), [GitHub Discussions](https://github.com/chartist-js/chartist/discussions) or [Stack Overflow](https://stackoverflow.com/questions/tagged/chartist.js). + +If you've encountered an issue, please [file it on GitHub](https://github.com/chartist-js/chartist/issues). diff --git a/website/docs/plugins.md b/website/docs/plugins.md new file mode 100644 index 000000000..7f76d3819 --- /dev/null +++ b/website/docs/plugins.md @@ -0,0 +1,8 @@ +--- +slug: /docs/plugins +description: Plugins +--- + +# Plugins + +Coming soon. diff --git a/website/docs/what-is-it-made-for.md b/website/docs/what-is-it-made-for.md new file mode 100644 index 000000000..eab3d4bf4 --- /dev/null +++ b/website/docs/what-is-it-made-for.md @@ -0,0 +1,16 @@ +--- +slug: /docs/what-is-it-made-for +description: What is Chartist made for? +--- + +# What is it made for? + +Chartist's goal is to provide a simple, lightweight and unintrusive library to responsively craft charts on your website. +It's important to understand that one of the main intentions of Chartist is to rely on standards rather than providing +it's own solution to a problem which is already solved by those standards. We need to leverage the power of browsers +today and say good bye to the idea of solving all problems ourselves. + +Chartist works with inline-SVG and therefore leverages the power of the DOM to provide parts of its functionality. This +also means that Chartist does not provide it's own event handling, labels, behaviors or anything else that can just be +done with plain HTML, JavaScript and CSS. The single and only responsibility of Chartist is to help you drawing "Simple +responsive Charts" using inline-SVG in the DOM, CSS to style and JavaScript to provide an API for configuring your charts. diff --git a/website/docs/whats-new-in-v1.md b/website/docs/whats-new-in-v1.md new file mode 100644 index 000000000..61220e4e4 --- /dev/null +++ b/website/docs/whats-new-in-v1.md @@ -0,0 +1,55 @@ +--- +slug: /docs/whats-new-in-v1 +description: What's new in Chartist v1? +--- + +# What's new in v1? + +## ESM + +Now Chartist is truly an ES module and exposes its API through the exports, thus making Chartist [tree-shakable](https://developer.mozilla.org/en-US/docs/Glossary/Tree_shaking). + +### Migration from v0.11 + +- Each property of Chartist object now is named export. +- Chart classes were renamed. +- Easing object now is named export. + +```js +const Chartist = require('chartist') + +new Chartist.Bar(/* ... */); +new Chartist.Line(/* ... */); +new Chartist.Pie(/* ... */); +new Chartist.Svg(/* ... */); +Chartist.Svg.Easing +// ... + +// -> + +import { BarChart, LineChart, PieChart, Svg, easings } from 'chartist' + +new BarChart(/* ... */) +new LineChart(/* ... */) +new PieChart(/* ... */) +new Svg(/* ... */) +easings +// ... +``` + +## TypeScript + +Chartist was rewritten and fully typed with TypeScript. + +### Some of exposed types + +```ts +import type { + BarChartData, + BarChartOptions, + LineChartData, + LineChartOptions, + PieChartData, + PieChartOptions +} from 'chartist' +``` diff --git a/website/docusaurus.config.js b/website/docusaurus.config.js new file mode 100644 index 000000000..3b89a9f22 --- /dev/null +++ b/website/docusaurus.config.js @@ -0,0 +1,126 @@ +// @ts-check + +const branch = require('git-branch'); +const codeTheme = require('./src/prism-theme'); + +const currentBranch = process.env.BRANCH || branch.sync(); +/** @type {import('@docusaurus/types').Config} */ +const config = { + title: 'Chartist', + tagline: 'A simple responsive charting library built with SVG', + url: 'https://chartist.dev/', + baseUrl: '/', + onBrokenLinks: 'throw', + onBrokenMarkdownLinks: 'warn', + favicon: 'img/favicon.ico', + trailingSlash: false, + organizationName: 'chartist-js', + projectName: 'chartist', + noIndex: currentBranch !== 'main', + + customFields: { + branch: currentBranch + }, + + presets: [ + [ + '@docusaurus/preset-classic', + /** @type {import('@docusaurus/preset-classic').Options} */ + { + docs: { + routeBasePath: '/', + sidebarPath: require.resolve('./sidebars.js'), + editUrl: 'https://github.com/chartist-js/chartist/edit/main/website/' + }, + theme: { + customCss: [ + require.resolve('./src/css/custom.css'), + require.resolve('./src/css/recoloring.css') + ] + } + } + ] + ], + + themeConfig: + /** @type {import('@docusaurus/preset-classic').ThemeConfig} */ + { + navbar: { + title: 'Chartist', + logo: { + alt: 'Chartist logo', + src: 'img/logo.svg' + }, + items: [ + { + type: 'doc', + docId: 'api/basics', + position: 'left', + label: 'API' + }, + { + type: 'doc', + docId: 'examples/index', + position: 'left', + label: 'Examples' + }, + { + type: 'doc', + docId: 'plugins', + position: 'left', + label: 'Plugins' + }, + { + href: 'https://stackoverflow.com/questions/tagged/chartist.js', + label: 'Stack Overflow', + position: 'right' + }, + { + href: 'https://gitter.im/gionkunz/chartist-js', + label: 'Gitter', + position: 'right' + }, + { + href: 'https://github.com/chartist-js/chartist/discussions', + label: 'Discussions', + position: 'right' + }, + { + href: 'https://github.com/chartist-js/chartist', + label: 'GitHub', + position: 'right' + } + ] + }, + colorMode: { + defaultMode: 'light', + disableSwitch: true, + respectPrefersColorScheme: false + }, + prism: { + theme: codeTheme + } + // algolia: { + // appId: '', + // apiKey: '', + // indexName: '' + // } + }, + + plugins: [ + [ + 'docusaurus-plugin-typedoc', + + // Plugin / TypeDoc options + { + entryPoints: ['../src/index.ts'], + tsconfig: '../tsconfig.json', + excludeExternals: true, + readme: 'none', + sort: ['source-order'] + } + ] + ] +}; + +module.exports = config; diff --git a/website/package.json b/website/package.json new file mode 100644 index 000000000..552728295 --- /dev/null +++ b/website/package.json @@ -0,0 +1,54 @@ +{ + "name": "website", + "version": "0.0.0", + "private": true, + "scripts": { + "docusaurus": "docusaurus", + "start": "docusaurus start", + "build": "docusaurus build", + "swizzle": "docusaurus swizzle", + "deploy": "docusaurus deploy", + "clear": "docusaurus clear", + "serve": "docusaurus serve", + "write-translations": "docusaurus write-translations", + "write-heading-ids": "docusaurus write-heading-ids", + "typecheck": "tsc" + }, + "dependencies": { + "@algolia/client-search": "^4.11.0", + "@docusaurus/core": "2.0.0-beta.14", + "@docusaurus/preset-classic": "2.0.0-beta.14", + "@docusaurus/theme-search-algolia": "^2.0.0-beta.9", + "@mdx-js/react": "^1.6.21", + "@svgr/webpack": "^6.0.0", + "clsx": "^1.1.1", + "file-loader": "^6.2.0", + "git-branch": "^2.0.1", + "prism-react-renderer": "^1.2.1", + "react": "^17.0.1", + "react-dom": "^17.0.1", + "url-loader": "^4.1.1" + }, + "devDependencies": { + "@docusaurus/module-type-aliases": "2.0.0-beta.14", + "@tsconfig/docusaurus": "^1.0.4", + "@types/react": "^17.0.36", + "docusaurus-plugin-typedoc": "^0.17.4", + "typedoc": "^0.23.0", + "typedoc-plugin-markdown": "^3.12.1", + "typescript": "^4.3.5", + "webpack": "^5.64.2" + }, + "browserslist": { + "production": [ + ">0.5%", + "not dead", + "not op_mini all" + ], + "development": [ + "last 1 chrome version", + "last 1 firefox version", + "last 1 safari version" + ] + } +} diff --git a/website/sidebars.js b/website/sidebars.js new file mode 100644 index 000000000..35f8adefa --- /dev/null +++ b/website/sidebars.js @@ -0,0 +1,49 @@ +// @ts-check + +const { docs } = require('./docs/docs'); +const { docs: api } = require('./docs/api/docs'); +const { docs: examples } = require('./docs/examples/docs'); + +/** @type {import('@docusaurus/plugin-content-docs').SidebarsConfig} */ +const sidebars = { + docsSidebar: [ + { + type: 'doc', + id: 'index', + label: 'Quickstart' + }, + ...docs.map(({ slug, title }) => ({ + /** @type {'doc'} */ + type: 'doc', + id: slug.replace('/docs/', ''), + label: title + })) + ], + apiSidebar: [ + ...api.map(({ slug, title }) => ({ + /** @type {'doc'} */ + type: 'doc', + id: slug.replace('/', ''), + label: title + })), + { + type: 'doc', + id: 'api/index' + } + ], + examplesSidebar: [ + { + type: 'doc', + id: 'examples/index', + label: 'Table of Contents' + }, + ...examples.map(({ slug, title }) => ({ + /** @type {'doc'} */ + type: 'doc', + id: slug.replace('/', ''), + label: title + })) + ] +}; + +module.exports = sidebars; diff --git a/website/src/components/ContextProvider.tsx b/website/src/components/ContextProvider.tsx new file mode 100644 index 000000000..2f8054c1a --- /dev/null +++ b/website/src/components/ContextProvider.tsx @@ -0,0 +1,23 @@ +import { ReactNode } from 'react'; +import useDocusaurusContext from '@docusaurus/useDocusaurusContext'; +import useThemeContext from '@theme/hooks/useThemeContext'; + +interface IContext { + branch: string; + theme: 'light' | 'dark'; +} + +export default function ContextProvider({ + children, +}: { + children(context: IContext): ReactNode; +}) { + const ctx = useDocusaurusContext(); + const { isDarkTheme } = useThemeContext(); + const context = { + branch: ctx.siteConfig.customFields.branch as string, + theme: isDarkTheme ? ('dark' as const) : ('light' as const), + }; + + return children(context); +} diff --git a/website/src/css/custom.css b/website/src/css/custom.css new file mode 100644 index 000000000..5ba19e538 --- /dev/null +++ b/website/src/css/custom.css @@ -0,0 +1,40 @@ +/** + * Any CSS included here will be global. The classic template + * bundles Infima by default. Infima is a CSS framework designed to + * work well for content-centric websites. + */ + +/* You can override the default Infima variables here. */ +:root { + --ifm-color-primary: #7a77ff; + --ifm-color-primary-dark: #5552ff; + --ifm-color-primary-darker: #433fff; + --ifm-color-primary-darkest: #0c07ff; + --ifm-color-primary-light: #9f9cff; + --ifm-color-primary-lighter: #b1afff; + --ifm-color-primary-lightest: #e8e7ff; + --ifm-code-font-size: 95%; +} + +.docusaurus-highlight-code-line { + background-color: rgba(0, 0, 0, 0.1); + display: block; + margin: 0 calc(-1 * var(--ifm-pre-padding)); + padding: 0 var(--ifm-pre-padding); +} + +html[data-theme='dark'] .docusaurus-highlight-code-line { + background-color: rgba(0, 0, 0, 0.3); +} + +.logo { + float: right; +} + +@media (max-width: 768px) { + .logo { + float: none; + display: block; + margin: 0 auto; + } +} diff --git a/website/src/css/recoloring.css b/website/src/css/recoloring.css new file mode 100644 index 000000000..3e21ff396 --- /dev/null +++ b/website/src/css/recoloring.css @@ -0,0 +1,193 @@ +/* palette */ +:root { + --brown-dark: #5B4421; + --red: #D70205; + --red_light: #F05B4F; + --white-dirty: #F7F2E9; + --white: #FFFFFF; + --brown-light: #e3d8c3; + --brown-lighter: #DFCFBB; + --brown-ligher_a08: #f7f2e980; + --brown-light_a02: rgba(68, 61, 63, 0.2); + --brown-darken: #443D3F; + --yellow: #f4c63e; + + --dark: #363133; + --dark-01: #2e2929; + --dark_03_a01: rgba(247, 242, 233, 0.1); + --white_a02: rgba(255, 255, 255, 0.2); +} + + +:root[data-theme='light'] { + --accent: var(--red); + + --text-primary: var(--brown-dark); + --text-link: var(--red); + --text_header: var(--white-dirty); + + --bg_main: var(--brown-light); + --bg-highlithed: var(--brown-ligher_a08); + --bg-header: var(--brown-darken); + --bg_menu: var(--brown-lighter); + + --separator: var(--brown-light_a02); +} + +:root[data-theme='dark'] { + --accent: var(--red_light); + + --text-primary: var(--white); + --text-link: var(--red_light); + + --separator: var(--white_a02); + + --text_header: var(--white-dirty); + + --bg_main: var(--dark-01); + --bg-highlithed: var(--dark_03_a01); + --bg-header: var(--brown-darken); + --bg_menu: var(--dark); +} + +html { + background-color: var(--bg_main) !important; + color: var(--text-primary) !important; +} + +a { + color: var(--text-link); +} + +a:hover { + color: var(--text-link); +} + +/* nav */ + +.navbar { + background-color: var(--bg-header); + color: var(--text_header); +} + +.navbar a { + color: var(--white); +} + +.menu__list-item a { + color: var(--text-primary); +} + +.navbar .navbar__link:hover, +.navbar .navbar__brand:hover { + color: var(--yellow); +} + +.menu { + background-color: var(--bg_menu); +} + +.menu__link { + color: var(--text-primary); +} + +.menu__link:hover { + color: var(--text-link); + background-color: initial; +} + +.menu__link.menu__link--active { + background-color: var(--bg-highlithed); +} + +.table-of-contents { + border-left: 3px solid var(--separator); +} + +.table-of-contents__link { + color: inherit; +} + +.table-of-contents__link:hover { + color: var(--text-link); +} + +.hash-link { + text-decoration: none; +} + +.hash-link:hover { + text-decoration: underline currentColor; +} + +.pagination-nav__link { + border-color: var(--separator); + transition: background-color 0.3s; +} + +.pagination-nav__link:hover { + border-color: var(--separator); + background-color: var(--bg-highlithed); +} + +.pagination-nav__sublabel { + color: var(--text-primary); +} + +.alert { + background-color: var(--bg-highlithed); + border-color: var(--accent); + color: var(--text-primary); +} + +.alert a { + text-decoration-color: currentColor; +} + +.tabs__item--active { + color: var(--text-link); + border-color: var(--accent); +} + +.tabs__item { + color: var(--text-primary); +} + +.admonition-icon svg { + stroke: var(--accent); + fill: var(--accent); +} + +hr { + border-color: var(--separator); +} + +table th, table td, table thead tr { + border-color: var(--separator); +} + +code { + background-color: var(--bg-highlithed); + border-color: var(--separator); +} + +table tr:nth-child(2n) { + background-color: var(--bg_menu); +} + +.navbar__logo { + background-color: var(--yellow); + padding: 3px; + height: calc(2em + 6px); + border-radius: 50%; + box-sizing: border-box; +} + +.navbar-sidebar__back { + background-color: var(--bg-highlithed); + color: var(--text-primary); +} + +.navbar-sidebar__brand { + background-color: var(--dark-01); +} diff --git a/website/src/prism-theme.js b/website/src/prism-theme.js new file mode 100644 index 000000000..f1824c5b9 --- /dev/null +++ b/website/src/prism-theme.js @@ -0,0 +1,69 @@ +module.exports = { + plain: { + color: '#f7f2ea', + backgroundColor: '#453D3F' + }, + styles: [ + { + types: ['prolog', 'constant', 'builtin'], + style: { + color: '#F05B4F' + } + }, + { + types: ['inserted', 'function'], + style: { + color: '#F05B4F' + } + }, + { + types: ['deleted'], + style: { + color: 'rgb(255, 85, 85)' + } + }, + { + types: ['changed'], + style: { + color: 'rgb(255, 184, 108)' + } + }, + { + types: ['punctuation', 'symbol'], + style: { + color: '#f7f2ea' + } + }, + { + types: ['number'], + style: { + color: '#F4C63D' + } + }, + { + types: ['string', 'char', 'tag', 'selector'], + style: { + color: '#F4C63D' + } + }, + { + types: ['keyword', 'variable'], + style: { + color: '#F05B4F', + fontStyle: 'italic' + } + }, + { + types: ['comment'], + style: { + color: '#7b6d70' + } + }, + { + types: ['attr-name'], + style: { + color: '#F4C63D' + } + } + ] +}; diff --git a/website/static/.nojekyll b/website/static/.nojekyll new file mode 100644 index 000000000..e69de29bb diff --git a/source/images/chartist-guy.gif b/website/static/img/chartist-guy.gif similarity index 100% rename from source/images/chartist-guy.gif rename to website/static/img/chartist-guy.gif diff --git a/source/favicon.ico b/website/static/img/favicon.ico old mode 100755 new mode 100644 similarity index 100% rename from source/favicon.ico rename to website/static/img/favicon.ico diff --git a/website/static/img/logo.svg b/website/static/img/logo.svg new file mode 100644 index 000000000..281ae7a82 --- /dev/null +++ b/website/static/img/logo.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/website/tsconfig.json b/website/tsconfig.json new file mode 100644 index 000000000..6f4756980 --- /dev/null +++ b/website/tsconfig.json @@ -0,0 +1,7 @@ +{ + // This file is not used in compilation. It is here just for a nice editor experience. + "extends": "@tsconfig/docusaurus/tsconfig.json", + "compilerOptions": { + "baseUrl": "." + } +}