Luxon adapter for Chart.js

Overview

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. See the Luxon API docs for the supported options, such as zone and locale, that these functions accept.

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:

> gulp build            // build dist files
> gulp build --watch    // build and watch for changes
> gulp lint             // perform code linting

License

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

Comments
  • Support timezone config

    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 });
    }
    
    enhancement 
    opened by jonrimmer 19
  • chartjs-adapter-luxon 1.1.0 is incompatible with luxon 3.0.1

    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:

    https://github.com/chartjs/chartjs-adapter-luxon/blob/1b1c23073eb364bd5bd25de6161a19be44d5b5fc/package.json#L56

    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. :smile_cat:)

    opened by StephanTLavavej 12
  • displayFormats unexpected result

    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!

    opened by ocarreterom 11
  • Use chart

    Use chart "locale" if it is not specified in the adatpter options

    Fix #71 Answer to comment https://github.com/chartjs/chartjs-adapter-luxon/issues/46#issuecomment-983796300

    Missing

    • [x] Release new CHART.JS version
    • [x] Add test cases using chart locale.
    • [x] Add doc in the README
    enhancement 
    opened by stockiNail 9
  • Add adapter options

    Add adapter options

    Fixes #3

    Passes through the adapter options to each of Luxon's factory methods (fromMillis(), fromFormat()`, etc.) so that they can be configured with a timezone and other parameters.

    Also adds a basic testing setup.

    enhancement 
    opened by jonrimmer 8
  • Improve ChartJS Tooltip to contain the dataset label name, similar to ChartJs Linear Axis default.

    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.

    opened by escay 6
  • Provide ES6 version

    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?

    opened by krumware 6
  • Parser Error for Luxon Objects

    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!

    opened by fmeyszies 6
  • Fix isoweek startOf returning incorrect date for the first day of the week.

    Fix isoweek startOf returning incorrect date for the first day of the week.

    This PR fixes an issue causing days that land on the isoweek day to round down to the previous week.

    I've added a spec that fails with the previous code.

    bug 
    opened by Billiam 5
  • `isoWeekday` is not a function

    `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.

    https://github.com/chartjs/chartjs-adapter-luxon/blob/18d1a9b5cd4a441e135a80c7505d4fb3bf089be9/src/index.js#L75

    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

    opened by stockiNail 5
  • Passing Zone object to options.adapters.date causes invalid dates.

    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

    opened by iddings 5
  • Import issue with ChartJS 3.8

    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 };
    
    opened by winsmith 2
  • missing typing declaration

    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.

    opened by fibo 6
Releases(v1.3.0)
Owner
Chart.js
Simple, clean and engaging charts for designers and developers
Chart.js
This adapter allows the use of Moment.js with Chart.js

chartjs-adapter-moment Overview This adapter allows the use of Moment.js with Chart.js. Moment.js is a very heavy library and thus not recommended for

Chart.js 26 Dec 27, 2022
date-fns adapter for Chart.js

chartjs-adapter-date-fns Overview This adapter allows the use of date-fns with Chart.js. Requires Chart.js 2.8.0 or later and date-fns 2.0.0 or later.

Chart.js 71 Dec 22, 2022
A Simple Dashboard Chart in Laravel Nova using Chart JS

A Simple Dashboard Chart in Laravel Nova using Chart JS. Starting create your own dashboard with Chart JS Integration can save your time and help you maintain consistency across standard elements such as Bar, Stacked, Line, Area, Doughnut and Pie Chart.

Kuncoro Wicaksono 177 Jan 4, 2023
Chart.js plugin to defer initial chart updates

Chart.js plugin to defer initial chart updates until the user scrolls and the canvas appears inside the viewport, and thus trigger the initial chart a

Chart.js 97 Nov 9, 2022
Bar Funnel Chart extension for Chart.js

Chart.BarFunnel.js Provides a Bar Funnel Chart for use with Chart.js Documentation To create a Bar Funnel Chart, include Chart.BarFunnel.js after Char

Chart.js 58 Nov 24, 2022
TradeX-chart is a trade chart written in plain (vanilla) JavaScript with minimal dependencies

TradeX-chart is a trade chart written in plain (vanilla) JavaScript with minimal dependencies; use it with any framework or backend.

null 24 Dec 12, 2022
Redefined chart library built with React and D3

Recharts Introduction Recharts is a Redefined chart library built with React and D3. The main purpose of this library is to help you to write charts i

recharts 19.4k Jan 2, 2023
:bar_chart: A D3-based reusable chart library

c3 c3 is a D3-based reusable chart library that enables deeper integration of charts into web applications. Follow the link for more information: http

C3.js 9.2k Jan 2, 2023
GPL version of Javascript Gantt Chart

dhtmlxGantt Getting started | Features | Follow us | License | Useful links dhtmlxGantt is an open source JavaScript Gantt chart that helps you illust

null 952 Dec 29, 2022
🍞📊 Beautiful chart for data visualization.

?? ?? Spread your data on TOAST UI Chart. TOAST UI Chart is Beautiful Statistical Data Visualization library. ?? Packages The functionality of TOAST U

NHN 5.2k Jan 2, 2023
:bar_chart: Re-usable, easy interface JavaScript chart library based on D3.js

billboard.js is a re-usable, easy interface JavaScript chart library, based on D3 v4+. The name "billboard" comes from the famous billboard chart whic

NAVER 5.4k Jan 1, 2023
:bar_chart: A library of modular chart components built on D3

Plottable Plottable is a library of chart components for creating flexible, custom charts for websites. It is built on top of D3.js and provides highe

Palantir Technologies 2.9k Dec 31, 2022
Chart image and QR code web API

QuickChart QuickChart is a service that generates images of charts from a URL. Because these charts are simple images, they are very easy to embed in

Ian Webster 1.3k Dec 25, 2022
📈 A small, fast chart for time series, lines, areas, ohlc & bars

?? μPlot A small (~35 KB min), fast chart for time series, lines, areas, ohlc & bars (MIT Licensed) Introduction μPlot is a fast, memory-efficient Can

Leon Sorokin 7.5k Jan 7, 2023
TChart.js - simple and configurable Bar and Line Chart library in Javascript

TChart.js Simple and configurable Bar and Line Chart library in Javascript Description TChart.js is a canvas-based simple Javascript Bar and Line Char

null 4 Mar 3, 2021
🍞📊 Beautiful chart for data visualization.

?? ?? Spread your data on TOAST UI Chart. TOAST UI Chart is Beautiful Statistical Data Visualization library. ?? Packages The functionality of TOAST U

NHN 5.2k Jan 6, 2023
The power of Chart.js in Jupyter !

The power of Chart.js in Jupyter Notebooks Installation You can install ipychart from your terminal using pip or conda: # using pip $ pip install ipyc

Nicolas H 68 Dec 8, 2022
Chart.js bindings for OCaml

chartjs-ocaml: OCaml bindings for Chart.js This library provides OCaml bindings for the Chart.js charting library and some popular plugins. Following

Alex Yanin 13 Aug 20, 2022
Java library for use with Chart.js javascript library

Chart.java Chart.java enables integration with the excellent Chart.js library from within a Java application. Usage example In Java: BarDataset datase

Marceau Dewilde 102 Dec 16, 2022