Skip to content

Commit

Permalink
feat(svelte): manually query DOM for chart holder element as fallback
Browse files Browse the repository at this point in the history
In the rollup configuration, we explicitly define svelte as an external dependency for UMD/ESM targets.
  • Loading branch information
metonym committed May 23, 2020
1 parent 825c407 commit 0732cd4
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 9 deletions.
7 changes: 3 additions & 4 deletions packages/svelte/rollup.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export default [
resolve(),
terser()
],
external: ["@carbon/charts"]
external: ["svelte", "@carbon/charts"]
},
{
input: "./src/index.js",
Expand All @@ -28,9 +28,8 @@ export default [
},
plugins: [
svelte(),
resolve(),
terser()
resolve()
],
external: ["@carbon/charts"]
external: ["svelte", "@carbon/charts"]
}
];
26 changes: 21 additions & 5 deletions packages/svelte/src/BaseChart.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -6,17 +6,33 @@
import { onMount, createEventDispatcher } from "svelte";
const dispatch = createEventDispatcher();
const id = "chart-" + Math.random().toString(36);
let ref = undefined;
let chart = undefined;
onMount(() => {
chart = new Chart(ref, { data, options });
dispatch("load", chart);
/**
* CodeSandbox does not resolve Svelte components from the `svelte` package.json entry.
* This causes `bind:ref` to be `undefined`; the chart can't mount to the element.
*
* We fallback to manually querying the DOM for the chart holder element because
* CodeSandbox does not use uncompiled Svelte source code.
*
* See https://github.com/sveltejs/svelte/issues/2937
*/
const element = ref || document.getElementById(id);
if (element) {
chart = new Chart(element, { data, options });
dispatch("load", chart);
}
return () => {
chart.destroy();
dispatch("destroy");
if (chart) {
chart.destroy();
dispatch("destroy");
}
};
});
Expand All @@ -27,4 +43,4 @@
}
</script>

<div {...$$restProps} bind:this={ref} on:load on:update on:destroy />
<div {...$$restProps} bind:this={ref} {id} />

0 comments on commit 0732cd4

Please sign in to comment.