chartjs-plugin-annotation icon indicating copy to clipboard operation
chartjs-plugin-annotation copied to clipboard

Avoid mutating annotation object for Lightning Web Security (LWS)

Open nwcm opened this issue 4 months ago • 0 comments

I'm looking to ensure the plugin is compatible with the LWS restrictions so it can be implemented in LWC. While I'm sure an uncommon usage here it would be nice if it can be compatible.

https://github.com/chartjs/chartjs-plugin-annotation/issues/979

The main issue is setting of value.id = key in beforeUpdate

I have simply removed the assignment to the object to avoid mutation, I'm unclear on any downstream impacts of removing this assignment. It looks that the id is used in element.js getContext. However, annotations seem to function without the assignment.

function getContext(chart, element, elements, annotation) {
  return element.$context || (element.$context = Object.assign(Object.create(chart.getContext()), {
    element,
    get elements() {
      return elements.filter((el) => el && el.options);
    },
    id: annotation.id,
    type: 'annotation'
  }));
}

I tried cloning the object however afterUpdate -> updateElements fails on annotationOptions.setContext(getContext(chart, element, elements, annotationOptions)); where setContext is now undefined. So cloning would require a deeper fix

Reading for LWS restrictions.

A common problematic coding practice is mutating objects that the namespace doesn’t own. When you mutate an object, you add or remove properties of the object or change values of properties. You change the "shape" of the object. When you mutate an object in a component that’s running in Lightning Web Security (LWS), that change isn’t propagated outside the namespace sandbox, which leads to errors.

https://developer.salesforce.com/docs/platform/lightning-components-security/guide/lws-mutation-alternatives.html https://developer.salesforce.com/docs/platform/lightning-components-security/guide/lws-proxies.html https://developer.salesforce.com/docs/platform/lightning-components-security/guide/lws-proxies.html

nwcm avatar Aug 04 '25 02:08 nwcm