chartjs / chartjs-adapter-date-fns Goto Github PK
View Code? Open in Web Editor NEWdate-fns adapter for Chart.js
License: MIT License
date-fns adapter for Chart.js
License: MIT License
Hi, I updated our project our project dependecies to
chart.js@>=3.0.2, chart.js@^3.0.2:
version "3.0.2"
resolved "https://registry.yarnpkg.com/chart.js/-/chart.js-3.0.2.tgz#5893b0548714445b5190cbda9ac307357a56a0c7"
integrity sha512-DR0GmFSlxcFJp/w//ZmbxSduAkH/AqwxoiZxK97KHnWZf6gvsKWS3160WvNMMHYvzW9OXqGWjPjVh1Qu+xDabg==
chartjs-adapter-date-fns@>=2.0.0:
version "2.0.0"
resolved "https://registry.yarnpkg.com/chartjs-adapter-date-fns/-/chartjs-adapter-date-fns-2.0.0.tgz#5e53b2f660b993698f936f509c86dddf9ed44c6b"
integrity sha512-rmZINGLe+9IiiEB0kb57vH3UugAtYw33anRiw5kS2Tu87agpetDDoouquycWc9pRsKtQo5j+vLsYHyr8etAvFw==
and have (testing) graph like
async renderChart2() {
var speedCanvas = document.querySelector("#chart-2 canvas")
var speedData = {
labels: ["2021-01-01T23:00:00.000Z", "2021-01-02T23:00:00.000Z", "2021-01-03T23:00:00.000Z", "2021-01-04T23:00:00.000Z", "2021-01-05T23:00:00.000Z", "2021-01-06T23:00:00.000Z", "2021-01-07T23:00:00.000Z"],
datasets: [{
label: "Car Speed",
data: [0, 59, 75, 20, 20, 55, 40],
lineTension: 0,
fill: false,
borderColor: 'orange',
backgroundColor: 'transparent',
pointBorderColor: 'orange',
pointBackgroundColor: 'rgba(255,150,0,0.5)',
borderDash: [5, 5],
pointRadius: 5,
pointHoverRadius: 10,
pointHitRadius: 30,
pointBorderWidth: 2,
pointStyle: 'rectRounded'
}]
}
var chartOptions = {
responsive: true,
legend: {
display: true,
position: 'top',
labels: {
boxWidth: 80,
fontColor: 'black'
}
},
scales: {
x: {
type: "time",
grid: {
display: false,
color: "black"
},
title: {
display: true,
text: "Time in Seconds",
color: "red"
}
},
y: {
grid: {
color: "black",
borderDash: [2, 5],
},
title: {
display: true,
text: "Speed in Miles per Hour",
color: "green"
}
}
}
}
const Chart = await this.chart()
var lineChart = new Chart(speedCanvas, {
type: 'line',
data: speedData,
options: chartOptions
})
}
async chart() {
const { Chart, registerables } = await import('chart.js')
Chart.register(...registerables)
return Chart
}
And when I set some axis to be type: "time"
, rendering of graphs fails
I am not strong in JS, but I digg deep and it seems to me that this
import { toDate, parse, parseISO, isValid, format, addYears, addQuarters, addMonths, addWeeks, addDays, addHours, addMinutes, addSeconds, addMilliseconds, differenceInYears, differenceInQuarters, differenceInMonths, differenceInWeeks, differenceInDays, differenceInHours, differenceInMinutes, differenceInSeconds, differenceInMilliseconds, startOfYear, startOfQuarter, startOfMonth, startOfWeek, startOfDay, startOfHour, startOfMinute, startOfSecond, endOfYear, endOfQuarter, endOfMonth, endOfWeek, endOfDay, endOfHour, endOfMinute, endOfSecond } from 'date-fns';
....
_adapters._date.override({
....
format: function(time, fmt) {
return format(time, fmt, this.options);
},
do not call date-fns.format
but itself again.
When I did litlle rename and change call in chart.js _tickFormatFunction(time, index, ticks, format)
:
xformat: function(time, fmt) {
return format(time, fmt, this.options);
},
all went OK
This error keeps popping up,
Error: No "exports" main defined in C:\Users\info\3D Objects\4-Soft\investors\node_modules\chart.js\package.json
My code looks like this and it works without date fns:
import {
Chart as ChartJS,
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend,
Filler,
TimeScale,
} from "chart.js";
ChartJS.register(
CategoryScale,
LinearScale,
PointElement,
LineElement,
Title,
Tooltip,
Legend,
Filler,
TimeScale
);
import "chartjs-adapter-date-fns";
import { Line } from "react-chartjs-2";
if i remove the import the code works fine
The startOf function is accepting a boolean for Sunday(false) and Monday(true).
Instead it should get the the week day (number) between 0 (Sunday) and 6(Saturday) in order to be more flexible to provide the startOf the week based on the parameter.
Currently migrating to Chart.js v3-beta and it seem like both latest/next versions at NPM doesn't contain #16 .
Without this commit the adapter doesn't work at all with v3.
Is it possible to update NPM version or at least update the "latest" version there?
It appears [email protected] is no longer listed in peerDependencies, so when this is used in a project that has other things that depend on [email protected], it fails to load with the error:
since [email protected] doesn't have toDate
.
I would really love to use this adapter with chartjs 3.0.0-beta.
The current release does not have this commit: 14916b6 and thus does not work with chartjs v3.
Hi there! I'm getting the following error when I try to render a chart with version 3.0.0 of chartjs-adapter-date-fns, though it works just fine with version 2.0.1. Looks like something might be misconfigured with package.json?
chartjs-adapter-date-fns.min.js is treated as an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which declares all .js files in that package scope as ES modules.
Instead rename chartjs-adapter-date-fns.min.js to end in .cjs, change the requiring code to use dynamic import() which is available in all CommonJS modules, or change "type": "module" to "type": "commonjs" in /myproject/node_modules/chartjs-adapter-date-fns/package.json to treat all .js files as CommonJS (using .mjs for all ES modules instead).
Running vitest in a project that uses chart.js v4 and chartjs-adapter-date-fns
v2.0.1 results in:
Error: No "exports" main defined in [redacted]/node_modules/chart.js/package.json
❯ node_modules/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.js:8:72
6| */
7| (function (global, factory) {
8| typeof exports === 'object' && typeof module !== 'undefined' ? factory(require('chart.js'), require('date-fns')) :
| ^
9| typeof define === 'function' && define.amd ? define(['chart.js', 'date-fns'], factory) :
10| (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.Chart, global.dateFns));
This is similar to this other comment
Here is a repro using stackblitz: https://stackblitz.com/edit/vitest-dev-vitest-7iyfoz?file=test/basic.test.ts
The test just imports chartjs-adapter-date-fns
.
A potential fix is to add the exports field to the adapter package.json:
"exports": {
".": {
"import": "./dist/chartjs-adapter-date-fns.esm.js",
"require": "./dist/chartjs-adapter-date-fns.js"
}
}
I'm trying to use this with Chart.js in my Stencil web component project, which also uses date-fns (not moment.js).
Per the instructions, here is what I added to the particular component.tsx
file:
import Chart from 'chart.js';
import 'chartjs-adapter-date-fns';
Still, NG throws this warning:
Module not found: Error: Can't resolve './locale' in '/Users/..../stencil/oia-collection/dist/esm/es5/build'
Anything I missed?
Btw I'm using date-fns v2 - not sure if that makes a difference as it indeed is different to date-fns in some areas, such as a new formats API (Unicode Technical Standard #35).
Re. date-fns v2 support, I will open a new issue, perhaps I can contribute a PR - shouldn't be a big change.
EDIT:
The error is thrown on the Ionic project level, not during the Stencil build process.
I use chart.js and just found out that I can also use date-fns with it by installing this adapter. I install it and imported it as instructed...
import { Chart } from 'chart.js';
import 'chartjs-adapter-date-fns';
But now I receive the following error:
TypeError: 3 arguments required, but only 2 present
at Module.parse (index.js:350)
at DateAdapter.parse (chartjs-adapter-date-fns.js:37)
at toTimestamp (Chart.js:12736)
at parse (Chart.js:12763)
at ChartElement.determineDataLimits (Chart.js:13056)
at ChartElement.update (Chart.js:10310)
at ChartElement.update (Chart.js:13027)
at getMinimumBoxSize (Chart.js:6368)
at Object.each (Chart.js:1801)
at Object.update (Chart.js:6382)
at resolvePromise (zone.js:852)
at resolvePromise (zone.js:809)
at zone.js:913
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:423)
at Object.onInvokeTask (core.js:25999)
at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (zone.js:422)
at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (zone.js:195)
at drainMicroTaskQueue (zone.js:601)
I use date-fns 2.4.1. This could be an issue since there were some breaking changes when upgrading to v2 and this error seems to be a result of the new parse function that I guess requires a 3rd argument https://date-fns.org/v2.4.1/docs/parse
With that being said I suppose this is more a feature request to upgrade the adapter to handle date-fns v2
chartjs-adapter-date-fns.bundle.js:6225 Uncaught TypeError: Cannot read properties of undefined (reading '_adapters')
at chartjs-adapter-date-fns.bundle.js:6225:10
at chartjs-adapter-date-fns.bundle.js:4:76
at chartjs-adapter-date-fns.bundle.js:5:2
(anonymous) @ chartjs-adapter-date-fns.bundle.js:6225
(anonymous) @ chartjs-adapter-date-fns.bundle.js:4
(anonymous) @ chartjs-adapter-date-fns.bundle.js:5
Hii,
I recently tried to install chartjs-adapter-date-fns using npm install date-fns chartjs-adapter-date-fns --save
. But I am using React with typecript and it is giving me following error "Could not find declaration file for module". I tried to install the module with @types/
but the type version of the adapter is not available.
Question: How do add this adapter to my .tsx file?
I have a react app that uses react-chartjs-2.
On production chart.js includes the whole moment library, and even without locales is still big; Chart.js has the chance to not use moment, and use date-fns instead, via adapters. but I have no idea how to implement it on my project via webpack.
Any idea?
Readme says Chart.js 2.8.0 however 3.0 is required.
Hi,
This adapter doesn't allow to specify a timezone when parsing/formatting dates, since, unline Luxon, date-fns
options don't support timezones. There is an official complementary library, date-fns-tz, that adds functions with timezone support:
zonedTimeToUtc
- Given a date and any time zone, returns a Date with the equivalent UTC timeutcToZonedTime
- Get a date/time representing local time in a given time zone from the UTC dategetTimezoneOffset
- Gets the offset in milliseconds between the time zone and UTC timeformat
- Extends date-fns/format with full time zone supporttoDate
- Can be used to create a zoned Date from a string containing an offset or IANA time zone
I wonder what is the best strategy to support timezones:
chartjs-adapter-date-fns-tz
adapter that extends this one,date-fns-tz
functions (I guess we should then make the dependency optional)?Since there is no too much logic in date adapters (i.e we just pass options
to the underlying library), creating a distinct adapter may be a cleaner option?
Can we please push out a new release of this package? I would like to install this package whilst using npm 8, but it doesn't let me install because peerDependencies
aren't met on the current version. #48 was merged to fix this, but it needs to be released so consumers can install it correctly.
I'm using the bundled version of chartjs-adapter-date-fns from the CDN (chartjs-adapter-date-fns.bundle.min.js).
Is it still possible to configure locale support as per https://github.com/chartjs/chartjs-adapter-date-fns#locale-support-via-scale-options? If so, please can you give me an example of how to access the locale class to pass to adapters.date.locale in the scale options.
In order to support npm aliases, please let us pass the Chart object to a register function of this plugin. This helps to use this plugin if the chart.js version in use is not installed via chart.js
specifically but for example an npm alias or other means.
Please update Chart.js dependency to chart.js@"^4.0.0".
Thank you.
Hello
The adapter need an update for version 2.0 of date-fns
Its explain here: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md
Old:
chartjs-adapter-date-fns/src/index.js
Lines 15 to 26 in 46c3bb8
New version
var FORMATS = {
datetime: 'MMM d, yyyy, h:mm:ss a',
millisecond: 'h:mm:ss.SSS a',
second: 'h:mm:ss a',
minute: 'h:mm a',
hour: 'ha',
day: 'MMM d',
week: 'w',
month: 'MMM yyyy',
quarter: '[Q]Q - yyyy',
year: 'yyyy'
};
May be show the version of date-fns for backward compatibility
i get this error whenever i add
<script src="https://cdn.jsdelivr.net/npm/chart.js/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
``` in my code
chart.min.js:13 Uncaught SyntaxError: Cannot use import statement outside a module (at chart.min.js:13:1)
I just added chartjs date fns to cdnjs. Would you like me to change the links shown in the readme.md to the cdnjs version? Thanks
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.