GithubHelp home page GithubHelp logo

chartjs-adapter-luxon's Introduction

chartjs-adapter-luxon

release travis awesome

Overview

This adapter allows the use of Luxon with Chart.js. Luxon provides built-in support for time zones and internationalization.

Requires Chart.js 2.8.0 or later and Luxon 1.0.0 or later.

Note: once loaded, this adapter overrides the default date-adapter provided in Chart.js (as a side-effect).

Installation

npm

npm install luxon chartjs-adapter-luxon --save
import {Chart} from 'chart.js';
import 'chartjs-adapter-luxon';

CDN

By default, https://cdn.jsdelivr.net/npm/chartjs-adapter-luxon returns the latest (minified) version, however it's highly recommended to always specify a version in order to avoid breaking changes. This can be achieved by appending @{version} to the URL:

<script src="https://cdn.jsdelivr.net/npm/chart.js@^3"></script>
<script src="https://cdn.jsdelivr.net/npm/luxon@^2"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-luxon@^1"></script>

Read more about jsDelivr versioning on their website.

Configuration

Any date adapter options in the chart configuration will be passed through to Luxon's factory functions.

The following table describes the supported options that these functions accept.

Namespace: options.scales[scaleId].adapters.date

Name Type Default Description
locale string undefined Set a locale to use on the resulting DateTime instance. If not set, the adapter will use the locale, defined at chart options level. By default, Luxon uses the system's locale. See Intl locale.
numberingSystem string undefined Set the numbering system to set on the resulting DateTime instance. See Luxon and Intl numberingSystem documentation.
outputCalendar string undefined Set the output calendar to set on the resulting DateTime instance. See Luxon and Intl calendar documentation.
setZone boolean undefined Override the zone with a zone specified in the string itself, if it specifies one. By default, Luxon uses options.setZone=false.
zone string|Zone undefined Set the zone to place the DateTime into. By default, Luxon uses options.zone='local'. See Luxon and Intl timeZone documentation.

Read the Chart.js documention for other possible date/time related options. For example, the time scale time.* options can be overridden using the Luxon formats.

Development

You first need to install node dependencies (requires Node.js):

> npm install

The following commands will then be available from the repository root:

> npm run build         // build dist files
> npm test              // perfom code testing
> npm run lint          // perform code linting

License

chartjs-adapter-luxon is available under the MIT license.

chartjs-adapter-luxon's People

Contributors

benmccann avatar billiam avatar dependabot[bot] avatar etimberg avatar iddings avatar jonrimmer avatar krumware avatar kurkle avatar maennchen avatar mphfish avatar simonbrunel avatar stockinail avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

chartjs-adapter-luxon's Issues

Support timezone config

We need to display our charts in UTC, so will have to fork this adapter to do this. Would be useful if there was some way to supply a timezone param to be used in the create function. E.g.

function create(time) {
  return DateTime.fromMillis(time, { zone: config.zone });
}

Import issue with ChartJS 3.8

After updating from ChartJS 3.7.1 to ChartJS 3.8, any charts that would use the Luxon adapter stopped working. It seems that ChartJS changed the way their modules are exported slightly and the patches that chartjs-adapter-luxon is making don't register any more, at least in my project.

Any charts that use datetimes don't display any more and the console shows this error message:

Uncaught (in promise) Error: This method is not implemented: Check that a complete date adapter is provided.
    at abstract (chart.esm.js:56:62367)
    at DateAdapter.formats (chart.esm.js:56:62543)
    at TimeScale.init (chart.esm.js:56:280572)
    at eval (chart.esm.js:56:148422)
    at each (helpers.segment.js:129:2545)
    at Chart.buildOrUpdateScales (chart.esm.js:56:147793)
    at Chart._updateScales (chart.esm.js:56:152142)
    at Chart.update (chart.esm.js:56:150911)
    at new Chart (chart.esm.js:56:145260)
    at ChartsPremadeAppVersionsComponent.render (app-versions.js:180:1)

My workaround for this right now has been to create a new helper file, chart-js.js, and doing the patching manually by copy/pasting the code from the adapter source. Then I can import the new Chart object from that helper file.

I realise this is probably very hacky, but I don't really have the experience to find out what the actual problem is.

Here's my new import:

import { Chart } from 'ui/utils/chart-js';

And here's my ui/utils/chart-js.js:

import { Chart, registerables, _adapters } from 'chart.js';

import { DateTime } from 'luxon';

const FORMATS = {
  datetime: DateTime.DATETIME_MED_WITH_SECONDS,
  millisecond: 'h:mm:ss.SSS a',
  second: DateTime.TIME_WITH_SECONDS,
  minute: DateTime.TIME_SIMPLE,
  hour: { hour: 'numeric' },
  day: { day: 'numeric', month: 'short' },
  week: 'DD',
  month: { month: 'short', year: 'numeric' },
  quarter: "'Q'q - yyyy",
  year: { year: 'numeric' },
};

_adapters._date.override({
  _id: 'luxon', // DEBUG

  /**
   * @private
   */
  _create: function (time) {
    return DateTime.fromMillis(time, this.options);
  },

  formats: function () {
    return FORMATS;
  },

  parse: function (value, format) {
    const options = this.options;

    if (value === null || typeof value === 'undefined') {
      return null;
    }

    const type = typeof value;
    if (type === 'number') {
      value = this._create(value);
    } else if (type === 'string') {
      if (typeof format === 'string') {
        value = DateTime.fromFormat(value, format, options);
      } else {
        value = DateTime.fromISO(value, options);
      }
    } else if (value instanceof Date) {
      value = DateTime.fromJSDate(value, options);
    } else if (type === 'object' && !(value instanceof DateTime)) {
      value = DateTime.fromObject(value);
    }

    return value.isValid ? value.valueOf() : null;
  },

  format: function (time, format) {
    const datetime = this._create(time);
    return typeof format === 'string'
      ? datetime.toFormat(format, this.options)
      : datetime.toLocaleString(format);
  },

  add: function (time, amount, unit) {
    const args = {};
    args[unit] = amount;
    return this._create(time).plus(args).valueOf();
  },

  diff: function (max, min, unit) {
    return this._create(max).diff(this._create(min)).as(unit).valueOf();
  },

  startOf: function (time, unit, weekday) {
    if (unit === 'isoWeek') {
      weekday = Math.trunc(Math.min(Math.max(0, weekday), 6));
      const dateTime = this._create(time);
      return dateTime
        .minus({ days: (dateTime.weekday - weekday + 7) % 7 })
        .startOf('day')
        .valueOf();
    }
    return unit ? this._create(time).startOf(unit).valueOf() : time;
  },

  endOf: function (time, unit) {
    return this._create(time).endOf(unit).valueOf();
  },
});

Chart.register(...registerables);

export { Chart };

chartjs-adapter-luxon 1.1.0 is incompatible with luxon 3.0.1

I'm seeing the following npm warning when I attempt to update to today's release of luxon 3.0.1:

D:\GitHub\chart>npm install luxon@latest
npm WARN ERESOLVE overriding peer dependency
npm WARN While resolving: [email protected]
npm WARN Found: [email protected]
npm WARN node_modules/luxon
npm WARN   peer luxon@"^1.0.0 || ^2.0.0" from [email protected]
npm WARN   node_modules/chartjs-adapter-luxon
npm WARN     chartjs-adapter-luxon@"^1.1.0" from the root project
npm WARN   1 more (the root project)
npm WARN 
npm WARN Could not resolve dependency:
npm WARN peer luxon@"^1.0.0 || ^2.0.0" from [email protected]
npm WARN node_modules/chartjs-adapter-luxon
npm WARN   chartjs-adapter-luxon@"^1.1.0" from the root project

changed 1 package, and audited 81 packages in 457ms

10 packages are looking for funding
  run `npm fund` for details

found 0 vulnerabilities

This may be related to:

"luxon": "^1.0.0 || ^2.0.0"

It appears that chartjs-adapter-luxon needs to be updated to accept the luxon 3.x series.

(Thanks again for your great work! I use it in the microsoft/STL Status Chart. 😸)

displayFormats unexpected result

Hi!
I'm trying to display the weekday but the result is unexpected.

I'm not sure if it's an error with this plugin, with Chartjs or I'm doing something wrong.

https://codesandbox.io/s/jovial-hermann-pnb72?file=/src/index.js

I expect to get the label monday, tuesday but I get monday, 29 nov, tuesday, 30 nov

import { Chart, registerables } from "chart.js";
import "chartjs-adapter-luxon";

Chart.register(...registerables);

const canvas = document.getElementById("chart");

const chart = new Chart(canvas, {
  type: "bar",
  data: {
    datasets: [
      {
        data: [
          { x: "1", y: 10 }, // monday
          { x: "2", y: 10 } // tuesday
        ]
      }
    ]
  },
  options: {
    scales: {
      x: {
        type: "time",
        time: {
          unit: "day",
          parser: "E",
          displayFormats: {
            day: { weekday: "long" } // expected monday/tuesday
          }
        }
      }
    }
  }
});

Thanks!

Unable to parse Unix millisecond time

Hi,

I am trying to parse time that's stored in Unix millisecond format (integer) in JSON and getting this error:

Uncaught (in promise) Error: fromMillis requires a numerical input, but received a string with value 11:55:00.000 PM

This is very strange because I'm pretty dang certain that my time is formatted correctly and indeed, when I do a console.log(thsiodata), I can see that it is formatted correctly.

Here is the code in question:

const weatherURL = "https://carlisleweather.com/rest/span/24h";

function makeGraphConfig(label,dataKey) {
    graphData = {
        datasets: [{
            label: label,
            data: fetchData,
            fill: false,
            borderColor: 'rgb(75, 192, 192)',
            tension: 0.1
        }]
    }

    graphConfig = {
        type: "line",
        data: graphData,
        options: {
            responsive: false,
            maintainAspectRatio: true,
            elements:{
                point:{
                    borderWidth: 0,
                    radius: 10,
                    backgroundColor: 'rgba(0,0,0,0)'
                }
            },
            scales: {
                x: {
                    type: 'time',
                    ticks: {
                        callback: function(val, index) {
                            return index % 20 === 0 ? this.getLabelForValue(val) : '';
                        }
                    }
                }
            },
            plugins: {
                decimation: {
                    enabled: true,
                    threshold: 200
                }
            },
            parsing: {
                xAxisKey: "ts",
                yAxisKey: dataKey
            }
        }   
    }

    return graphConfig

}


getData();

async function getData() {
    axios
        .get(weatherURL,{}).then(function (response) {
                fetchData = response.data;
                console.log("wx data:", fetchData)
                var outsideTemperatureConfig = makeGraphConfig("Outside Temperature", "otemp");
                const tempCtx = document.getElementById('outsideTemperatureChart').getContext('2d');
                const outsideTemperatureChart = new Chart(tempCtx, outsideTemperatureConfig);
            }
        )
};

I'm pulling in the adapter like this:

    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/chart.js@^3"></script>
    <script src="https://cdn.jsdelivr.net/npm/luxon@^2"></script>
    <script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-luxon@^1"></script>

You can see the live data here: https://carlisleweather.com/rest/span/1h

I'm very new to frontend work and Javascript in general. Is there something I'm missing about how JS interprets timestamps?

`isoWeekday` is not a function

I got an error isoWeekday is not a function when I try to use the startOf method of the adapter.

return this._create(time).isoWeekday(weekday).valueOf();

Having a look to Luxon documentation, the isoWeekday(weekday) sounds to belong to Moment and not to Luxon.

The doc https://github.com/moment/luxon/blob/master/docs/moment.md#unit-getters

EDIT
Chart.js version: dist/master
Luxon adapter: 0.2.1
Luxon lib: 1.24.1

chartjs-adapter-luxon 1.2.0 is incompatible with chart.js 4.x

I'm seeing the following error when I attempt to update to chart.js 4.x, released ~5 hours ago:

D:\GitHub\chart>npm install chart.js@latest chartjs-adapter-luxon@latest
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR! 
npm ERR! While resolving: [email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/chart.js
npm ERR!   chart.js@"4.0.1" from the root project
npm ERR! 
npm ERR! Could not resolve dependency:
npm ERR! peer chart.js@"^3.0.0" from [email protected]
npm ERR! node_modules/chartjs-adapter-luxon
npm ERR!   chartjs-adapter-luxon@"1.2.0" from the root project
npm ERR! 
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.

This is similar to #61 which happened when luxon updated its major version.

Detect when loaded

Hello, I'm loading:
https://cdn.jsdelivr.net/npm/chart.js
https://cdn.jsdelivr.net/npm/luxon
https://cdn.jsdelivr.net/npm/chartjs-adapter-luxon

asnchronously and I need to detect when they are loaded, since each one depends on the previous and drawing the chart depends on all three. For chart and luxon, I'm able to find out when they are loaded using:

typeof Chart != "undefined"
and
// typeof Chart._adapters._date == "undefined"
typeof luxon !== "undefined"

however I'm not able to figure out a way to tell when chartjs-adapter-luxon was loaded. It seems to override some methods in Chart._adapters._date, but I don't know which ones. Do you have any advice?

Note: I cannot use the <script onload> event reliably, since it doesn't trigger on cached versions (i.e. when the browser requests witj If-modified-since and the server responds with status code 304 not modified).

Jest ESM import (resolved)

Versions:
"chart.js": "^4.2.1",
"chartjs-adapter-luxon": "^1.3.1",

Issue:
import 'chartjs-adapter-luxon' crashes on jest tests.

Error:

Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation


/Users/dev/project-x/node_modules/chartjs-adapter-luxon/dist/chartjs-adapter-luxon.esm.js:7
    import { _adapters } from 'chart.js';
    ^^^^^^

    SyntaxError: Cannot use import statement outside a module
      12 | } from 'chart.js'
      13 |
    > 14 | import 'chartjs-adapter-luxon'
         | ^

I already found a workaround for this myself but I think it could be helpful for other people here trying to do the same in a typescript esm project:

in jest.config.ts add:

const esModules = ['chartjs-adapter-luxon'].join('|')
// inside config object
transformIgnorePatterns: [`/node_modules/(?!${esModules})`],

in tsconfig.json make sure you have:

"compilerOptions": {"allowJs": true, ... }

Passing Zone object to options.adapters.date causes invalid dates.

This isn't really a bug with this adapter, but it doesn't seem like this warrants an issue in the Chart.js main repo.

Because of the way Chart.js merges options, things like a luxon FixedOffsetZone get broken. I.e. if you pass a FixedOffsetZone object as the "zone" option to this adapter, Chart.js will convert it to an object like this:
{ fixed: -300 }. Luxon will then see that as an invalid zone.

One fix for this could be catching that edge case converting the zone from (e.g.) { fixed: -300 } to simply -300, which Luxon will handle properly.

Locally I've worked this out by adding:

/**
 * @private
 */
_normalizedOptions: function () {
    if (
        'object' === typeof this.options &&
        'zone' in this.options &&
        'object' === typeof this.options.zone &&
        'fixed' in this.options.zone &&
        'number' === typeof this.options.zone.fixed
    ) {
        const merged = Chart.helpers.merge({}, this.options);
        merged.zone = this.options.zone.fixed;
        return merged;
    }
    return this.options;
},

and replacing references to this.options with this._normalizedOptions() elsewhere.

If this is deemed not applicable to this repo, then I would suggest updating the documentation to indicate that only certain types of Zones are allowed.

I can make sure all types of Zones are supported and submit a PR if that's preferred.

Update: changed FixedOffset => FixedOffsetZone

Parser Error for Luxon Objects

Versions:

  • Chart.js: 2.9.3
  • Chart.js adapter luxon: 0.2.0
  • Luxon: 1.22.0

When I try to use Luxon DateTime Objects in my Datasets Data, the chartjs-adapter-luxon parser has an error on line 57 when it tries to parse the incoming DateTime object. I do not know if I missed something on how to use this adapter, but as soon as I just remove line 57 for testing purposes, the DateTime objects work.

Should the parser not be invoked if the datasets already have DateTime Objects as dates? Or does the parser get invoked in any case and should be altered to just return an already working Luxon Object? Sorry if I missed something. Thank you!

missing typing declaration

Importing chartjs-adapter-luxon in a TypeScript module you get a complain about missing typings declaration.

I solved adding an chartjs-adapter.luxon.d.ts file with content

declare module "chartjs-adapter-luxon";

I do not know if it is the right solution, but for sure including an index.d.ts file in this package would save time to many other developers, in particular those that are starting with TypeScript.

Import error

I am facing the following error when importing the library from an ES module:

image

In addition, VSCode fails to navigate to the js sources when CTRL+clicking the library name.
Both import and navigation errors can be fixed by adding the main property in package.json as of line 10 in the following:

image

Chart display broken after upgrading to Chart.js 4.0.1 and chart-adapter-luxon 1.2.1

Hi all, great project! Really appreciate the integration between Chart.js and Luxon. However, I just updated my application to Chart.js 4.0.1 (was 3.9.1) and chartjs-adapter-luxon 1.2.1 (was 1.2.0). Luxon library is same version. Unfortunately, now my charts display is broken and browser console shows:

chart.min.js:13 Uncaught SyntaxError: Cannot use import statement outside a module (at chart.min.js:13:1)
chartjs-adapter-luxon.min.js:7 Uncaught TypeError: Cannot read properties of undefined (reading '_adapters')
    at chartjs-adapter-luxon.min.js:7:582
    at chartjs-adapter-luxon.min.js:7:178
    at chartjs-adapter-luxon.min.js:7:249
(anonymous) @ chartjs-adapter-luxon.min.js:7
(anonymous) @ chartjs-adapter-luxon.min.js:7
(anonymous) @ chartjs-adapter-luxon.min.js:7
chartjs-plugin-datalabels.min.js:7 Uncaught TypeError: Cannot read properties of undefined (reading 'helpers')
    at chartjs-plugin-datalabels.min.js:7:295
    at chartjs-plugin-datalabels.min.js:7:312
(anonymous) @ chartjs-plugin-datalabels.min.js:7
(anonymous) @ chartjs-plugin-datalabels.min.js:7
jquery.min.js:2 jQuery.Deferred exception: Chart is not defined ReferenceError: Chart is not defined
    at HTMLDocument.<anonymous> (http://192.168.1.129:8926/index:1569:15)
    at e (http://192.168.1.129:8926/static/3rd_party/jquery.min.js:2:30038)
    at t (http://192.168.1.129:8926/static/3rd_party/jquery.min.js:2:30340) undefined

Any tips on overcoming this? Should I just rollback to older versions for now?

Thanks,
Guy

chartjs-adapter-luxon v1.3.1 throws an "Unknown file extension ".ts" " error when executing unit tests

Hi team. Previously, I had chartjs-adapter-luxon node module version set to v1.2.0. Works without any issues with NodejS v.18.16.1. Since I've updated the node module to v1.3.1, something in this module seems to throw an "Unkown file extension ".ts" " error when I execute unit tests (no related to chartjs or luxon). When I revert back this node module to v1.2.0, my unit tests works fine

C:\Users\AnUser\Desktop\Projects\Web-Server>yarn test
yarn run v1.22.19
$ npm run initDBTest && npm run execTests

> [email protected] initDBTest
> run-script-os

$ .\scripts\initDBTest.sh

> [email protected] execTests
> cross-env DEBUG=undefined nyc mocha --timeout 999999 --colors --reporter mocha-jenkins-reporter --require ts-node/register 'test/**/*.spec.ts' --unit-tests


TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for C:\Users\AnUser\Desktop\Projects\Web-Server\test\AlarmLimitRepository.spec.ts
    at new NodeError (node:internal/errors:399:5)
    at Object.getFileProtocolModuleFormat [as file:] (node:internal/modules/esm/get_format:79:11)
    at defaultGetFormat (node:internal/modules/esm/get_format:121:38)
    at defaultLoad (node:internal/modules/esm/load:81:20)
    at nextLoad (node:internal/modules/esm/loader:163:28)
    at ESMLoader.load (node:internal/modules/esm/loader:605:26)
    at ESMLoader.moduleProvider (node:internal/modules/esm/loader:457:22)
    at new ModuleJob (node:internal/modules/esm/module_job:64:26)
    at ESMLoader.#createModuleJob (node:internal/modules/esm/loader:480:17)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:434:34)
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

Here's my dependencies:

"dependencies": {
    "@types/cls-hooked": "4.3.4",
    "@vvo/tzdb": "6.108.0",
    "archiver": "5.3.1",
    "bcryptjs": "2.4.3",
    "chart.js": "4.3.0",
    "chartjs-adapter-luxon": "1.3.1",
    "chartjs-node-canvas": "4.1.6",
    "cls-hooked": "4.2.2",
    "commander": "11.0.0",
    "compare-versions": "6.0.0",
    "cors": "2.8.5",
    "csv": "6.3.1",
    "dbus-next": "0.10.2",
    "debug": "4.3.4",
    "express": "4.18.2",
    "fast-xml-parser": "4.2.5",
    "flatbuffers": "2.0.4",
    "formidable": "3.5.0",
    "fs-extra": "11.1.1",
    "helmet": "5.0.2",
    "hpp": "0.2.3",
    "http-proxy": "1.18.1",
    "ini": "4.1.1",
    "inversify": "6.0.1",
    "ip-address": "8.1.0",
    "ip-range-check": "0.2.0",
    "ip-to-int": "0.3.1",
    "jsonwebtoken": "9.0.1",
    "lodash": "4.17.21",
    "luxon": "3.3.0",
    "morgan": "1.10.0",
    "network": "0.6.1",
    "node-sequelize-stream": "2.0.3",
    "nodemailer": "6.9.3",
    "pdfkit": "0.13.0",
    "pg": "8.11.1",
    "pg-hstore": "2.3.4",
    "reflect-metadata": "0.1.13",
    "rxjs": "7.8.1",
    "sequelize": "6.32.1",
    "serve-favicon": "2.5.0",
    "serve-static": "1.15.0",
    "winston": "3.9.0",
    "winston-syslog": "2.7.0",
    "winston-transport": "4.5.0",
    "ws": "8.13.0",
    "zeromq": "6.0.0-beta.6"
  },
  "devDependencies": {
    "@redocly/cli": "1.0.0-beta.131",
    "@types/archiver": "5.3.2",
    "@types/bcryptjs": "2.4.2",
    "@types/bluebird": "3.5.38",
    "@types/chai": "4.3.5",
    "@types/chai-as-promised": "7.1.5",
    "@types/cors": "2.8.13",
    "@types/debug": "4.1.8",
    "@types/express": "4.17.17",
    "@types/formidable": "3.4.0",
    "@types/fs-extra": "11.0.1",
    "@types/hpp": "0.2.2",
    "@types/http-proxy": "1.17.11",
    "@types/ini": "1.3.31",
    "@types/jsonwebtoken": "9.0.2",
    "@types/lodash": "4.14.195",
    "@types/luxon": "3.3.0",
    "@types/mocha": "10.0.1",
    "@types/morgan": "1.9.4",
    "@types/node": "20.4.1",
    "@types/nodemailer": "6.4.8",
    "@types/pdfkit": "0.12.10",
    "@types/pg": "8.10.2",
    "@types/supertest": "2.0.12",
    "@types/winston-syslog": "2.4.0",
    "@types/ws": "8.5.5",
    "@types/zeromq": "5.2.2",
    "@typescript-eslint/eslint-plugin": "6.0.0",
    "@typescript-eslint/parser": "6.0.0",
    "chai": "4.3.7",
    "chai-as-promised": "7.1.1",
    "chai-events": "0.0.3",
    "cross-env": "7.0.3",
    "dotenv": "16.3.1",
    "eslint": "8.44.0",
    "eslint-plugin-header": "3.1.1",
    "eslint-plugin-import": "2.27.5",
    "mocha": "10.2.0",
    "mocha-jenkins-reporter": "0.4.8",
    "nyc": "15.1.0",
    "rimraf": "5.0.1",
    "run-script-os": "1.1.6",
    "supertest": "6.3.3",
    "ts-node": "10.9.1",
    "typedoc": "0.24.8",
    "typescript": "5.1.6"
  }

Here's the command I use to run my unit tests: "cross-env DEBUG=undefined nyc mocha --timeout 999999 --colors --reporter mocha-jenkins-reporter --require ts-node/register 'test/**/*.spec.ts' --unit-tests"

When running my unit tests, it fails at the first unit tests file in the list of unit tests to execute. And as I said, when reverting chartjs-adapter-luxon to v1.2.0, my unit tests works without any problem.

Can you please help me to resolve this issue ?

OS: Windows 10
NodeJS: v18.16.1

Thanks

luxon module not found.

I am getting a error "luxon module not found" during build on AWS but it's work on local.

Support for Chart.js v3 - import error: 'chart.js' does not contain a default export (imported as 'Chart')

@benmccann I'm trying to use Chart.js 3.x with current version of chartjs-adapter-luxon (v0.2.2), and it seems like Chartjs-v3 isn't yet supported.

I get an import error while compiling:

./node_modules/chartjs-adapter-luxon/dist/chartjs-adapter-luxon.esm.js
Attempted import error: 'chart.js' does not contain a default export (imported as 'Chart').

Module Versions:

"chart.js": "3.0.0-beta.9",
"chartjs-adapter-luxon": "^0.2.2",

Is it possible to add support for v3, if the fix is only in making the right import and doesn't need lot of changes? I would be happy to send a PR if you can let me know the scope of change needed here.

How to use in angular project?

I'm using chart.js wrapped in an angular module (I'm using PrimeNG's ChartModule).

Now I'd like to use the chartjs-adapter-luxon. I added luxon and chartjs-adapter-luxon to my package.json.
What else do I need to do, so that chart.js recognizes the date adapter?

I tried adding "node_modules/luxon/build/es6/luxon.js" and "node_modules/chartjs-adapter-luxon/dist/chartjs-adapter-luxon.js" to the list of scripts in angular.json, but still no luck.

Here is a minimal example to reproduce the problem:
https://stackblitz.com/edit/angular-ivy-wp9ejg?file=src/app/app.component.ts
When changing the type of the x scale to 'time' on app.component.ts:23, the problem with the missing adapter can be reproduced.

Import issue with chartjs-adapter-luxon 1.2.1

After upgrading to [email protected] (and [email protected]), I get the following error:

Error: Failed to resolve entry for package "chart.js". The package may have incorrect main/module/exports specified in its package.json: No known conditions for "." entry in "chart.js" package

Edit: upon a bit more digging, it seems to only throw this error when running server-side (eg, SSR). No error when run client-side.

Improve ChartJS Tooltip to contain the dataset label name, similar to ChartJs Linear Axis default.

When using a ChartJs Linear Axis I see a default tooltip with the dataset label name in it:

image

When using ChartJs (3.6.2 with Luxon 3.0 and chartjs-adapter-luxon 1.1.0) Time Cartesian Axis I see a default tooltip without the dataset label name in it:

image

Similar issue as described here, which contains a workaround and a fiddle example:
https://stackoverflow.com/questions/68022814/does-the-chart-js-tooltip-not-work-with-logarithmic-or-the-cartesian-time-axis

I am suspecting the chartjs-adapter to influence this (because I also tried https://github.com/chartjs/chartjs-adapter-date-fns adapter, which does not even have the colour icon in the tooltip).

Without the dataset name it makes it hard to read the tooltip and relate it to the correct data.
It would be very nice if the default could also show the dataset name.

I tried using callbacks myself to influence the behaviour, like instruct ChartJs to use something like:
https://stackoverflow.com/questions/72374970/how-to-provide-different-labels-in-chart-js-for-toolbox-and-axis

                 label: function(context) {
                    let label = context.dataset.label + ": " + context.dataset.data[context.datasetIndex];
                    return label;
                 }

but I could not get it to work. So I cannot give you a more precise example.

Breaking change released as feature

Sharing this here because it cased me many hours of investigation and head scratching hoping to save time for others.

As I now know - this PR https://github.com/chartjs/chartjs-adapter-luxon/pull/79/files#diff-7ae45ad102eab3b6d7e7896acd08c427a9b25b346470d7bc6507b6481575d519 broken our application due to the changes in package.json.

require() of ES Module ./node_modules/chartjs-adapter-luxon/dist/chartjs-adapter-luxon.esm.js from ./node_modules/chartjs-node-canvas/dist/freshRequire.js not supported. Instead change the require of chartjs-adapter-luxon.esm.js in ./node_modules/chartjs-node-canvas/dist/freshRequire.js to a dynamic import() which is available in all CommonJS modules.

I have tried to narrow it down for a long time, then finally figured that one ^ character in the beginning was hidden it ^v1.2.1 = 1.3.1 but 1.2.1 = 1.2.1.

Specifying 1.2.1 in package.json made it work again as before.

Support internationalizable date formats

format right now:

	format: function(time, format) {
		return create(time).toFormat(format);
	},

Luxon recommends toLocaleString and discourages toFormat

Ideally the datetime adapter would support both:

	format: function(time, format) {
		return typeof format === 'string' ? create(time).toFormat(format) : create(time).toLocaleString(format);
	},

We may also want to change the default formats to something like:

var FORMATS = {
	millisecond: 'h:mm:ss.SSS a',
	second: DateTime.TIME_WITH_SECONDS,
	minute: DateTime.TIME_SIMPLE,
	hour: { hour: 'numeric' }, // or DateTime.TIME_SIMPLE?
	day: DateTime.DATE_FULL,
	week: 'DD',
	month: DateTime.DATE_MED,
	quarter: "'Q'q - yyyy",
	year: { year: 'numeric' }
};

This is a mix of internationalizable and non-internationalizable datetime formats since Intl.DateTimeFormat does not support quarters, weeks, or milliseconds. However, users will not see any impact of mixing internationalizable and non-internationalizable datetime formats unless they set a locale and use one of these formats. By default, the week and quarter formats are not used and the millisecond format is not heavily used either, so this would allow users to more easily internationalize the majority of the time.

Object parsing ignores the user options

Developing #66, I have discovered a bug in the parse method of the adapter.

To create a Luxon DateTime object, you must use DateTime.from* methods which are all receiving the options in order to set the locale, zone, numbering and calendar systems.

Currently the adapter is not passing the user options (and therefore it's ignoring it) in the parse method when the value to parse is an object which represents a date time ({ year: ..., month: ..., day:...}). I think this way to map a timestamp is not so used (I have never seen it used with Chart,js), nevertheless, being there, it should be adjusted.

    } else if (type === 'object' && !(value instanceof DateTime)) {
      value = DateTime.fromObject(value);
    }

I'll submit a PR.

EDIT

PR #64 is fixing it.

Provide ES6 version

I'm sorry if this has an obvious answer, I wanted to give this a shot with the recent update to support Chart.js 3.0.0-alpha (thanks!!) using chartjs-adapter-luxon v0.2.1.

I'm importing only at this point (commented out chart initialization to remove that variable)

import Chart from 'chart.js/dist/Chart.esm.js';
import 'luxon';
import 'chartjs-adapter-luxon';

and receiving

chartjs-adapter-luxon.js:16 Uncaught TypeError: Cannot read property 'DateTime' of undefined
    at chartjs-adapter-luxon.js:16
    at chartjs-adapter-luxon.js:10
    at chartjs-adapter-luxon.js:11

Am I missing an intermediate step?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.