Skip to content

Remove type from the scriptable contexts #8642

Description

@simonbrunel

Following up on chartjs/chartjs-plugin-datalabels#229 which suggests to add type: 'datalabels' on the plugin context. The initial use case is explained in #8623 but I disagree on the way it should be resolved (see this comment). However this raised a few more concerns about (1) limitations that this type introduces but also (2) how we promote the use of scriptable options to our users.


1. ctx.type breaks abstraction of the options. It's suggested to use type (#8626) to verify if the received context is valid. However, it's not possible to check if (ctx.type instanceof 'dataset'), thus it doesn't allow to fallback to a context based logic. For example, the datalabels plugin fallbacks its color option to the root one. Let's say I would like to configure the root color to assign a different color to each data, it will not work because type === datalabels, not data:

// Would receive `type === 'datalabels'` when fallback from `datalabels.color`.
Chart.defaults.color = (ctx) => ctx.type === 'data' ? 
  ctx.dataIndex % 2 ? 'red' : 'green',
  'blue';

Checking for dataIndex instead seems a better choice in most cases:

// The datalabels context is a 'data' compatible context, so it works as expected.
Chart.defaults.color = (ctx) => ctx.dataIndex !== undefined ?
  ctx.dataIndex % 2 ? 'red' : 'green',
  'blue';

2. As explained in the same comment, there is no reason to check type === '<plugin_id>' | 'scale' | 'tick' | 'tooltip' in options. Also, recommending users to rely on type sounds like it's fine to put all the logic in "generic" options to distribute values across multiple features:

// WRONG
Chart.defaults.color = (ctx) => {
  return ctx.type === 'datalabels' ? 'red' :
     ctx.type === 'tooltip' ? 'green' :
     ctx.type === 'scale' ? 'blue' : 
     ctx.type === 'tick' ? 'yellow' : 
     'grey';
}

I really think this is an anti-pattern and we should not provide API to do that. Instead, users should use the plugin, scale, etc. options or write generic scriptable logic.


I'm probably missing some legit use cases but if not, I would suggest to remove type from core contexts before releasing v3:

  • type === 'chart': useless, all contexts should be a chart context
  • type === 'dataset': check datasetIndex instead
  • type === 'data': check dataIndex instead
  • type === 'scale': use the scale options instead
  • type === 'tick: use the tick options instead
  • type === 'tooltip: use the tooltip options instead

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions