fix(progress-indicator): allow currentIndex to be programmatically updated

This commit is contained in:
Eric Liu 2020-11-20 06:21:27 -08:00
commit c513279751
6 changed files with 110 additions and 36 deletions

View file

@ -8,7 +8,7 @@
/** Set to `true` to specify whether the progress steps should be split equally in size in the div */
export let spaceEqually = false;
/** Set to `true` to prevent updating `currentIndex` */
/** Set to `true` to prevent `currentIndex` from updating */
export let preventChangeOnClick = false;
import { createEventDispatcher, setContext } from "svelte";
@ -24,28 +24,40 @@
steps,
stepsById,
add: (step) => {
steps.update((_) => [
..._,
{
...step,
index: _.length,
current: _.length === currentIndex,
complete: _.length <= currentIndex,
},
]);
steps.update((_) => {
if (step.id in $stepsById) {
return _.map((_step) => {
if (_step.id === step.id) return { ..._step, ...step };
return _step;
});
}
return [
..._,
{
...step,
index: _.length,
current: _.length === currentIndex,
complete: step.complete,
},
];
});
},
change: (index) => {
if (preventChangeOnClick) return;
currentIndex = index;
steps.update((_) =>
[..._].map((step, i) => ({
...step,
current: i === index,
}))
);
/** @event {number} change */
dispatch("change", index);
},
});
$: steps.update((_) =>
_.map((step, i) => ({
...step,
current: i === currentIndex,
}))
);
</script>
<ul

View file

@ -23,19 +23,29 @@
/** Set an id for the top-level element */
export let id = "ccs-" + Math.random().toString(36);
import { getContext } from "svelte";
import { onMount, getContext } from "svelte";
import CheckmarkOutline16 from "carbon-icons-svelte/lib/CheckmarkOutline16";
import Warning16 from "carbon-icons-svelte/lib/Warning16";
let step = {};
const { stepsById, add, change } = getContext("ProgressIndicator");
add({ id, disabled });
$: add({ id, complete, disabled });
$: step = $stepsById[id];
$: {
current = step.current;
complete = step.complete;
}
const unsubscribe = stepsById.subscribe((value) => {
if (value[id]) {
step = value[id];
current = step.current;
complete = step.complete;
}
});
onMount(() => {
return () => {
unsubscribe();
};
});
</script>
<li