Skip to content

Commit

Permalink
fix(range): update track width when value is changed programmatically
Browse files Browse the repository at this point in the history
fixes #157

the input event doesn't fire when the value is changed in code, so listen for the property change
  • Loading branch information
Ashley Ryan authored and ashleyryan committed Aug 24, 2022
1 parent 2243f2b commit 8c91050
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 4 deletions.
11 changes: 10 additions & 1 deletion projects/core/custom-elements.json
Expand Up @@ -45599,7 +45599,16 @@
{
"kind": "method",
"name": "setTrackWidth",
"privacy": "private"
"privacy": "private",
"parameters": [
{
"name": "val",
"optional": true,
"type": {
"text": "number"
}
}
]
},
{
"kind": "field",
Expand Down
10 changes: 10 additions & 0 deletions projects/core/src/range/range.element.spec.ts
Expand Up @@ -47,4 +47,14 @@ describe('cds-range', () => {
await componentIsStable(component);
expect(getCssPropertyValue('--track-width', component)).toBe('77%');
});

it('should update the track width style when the value is changed programmatically (no input event)', async () => {
await componentIsStable(component);
expect(getCssPropertyValue('--track-width', component)).toBe('50%');

component.inputControl.value = '75';

await componentIsStable(component);
expect(getCssPropertyValue('--track-width', component)).toBe('75%');
});
});
15 changes: 12 additions & 3 deletions projects/core/src/range/range.element.ts
Expand Up @@ -5,7 +5,7 @@
*/

import { html, PropertyValues } from 'lit';
import { globalStyle } from '@cds/core/internal';
import { getElementUpdates, globalStyle } from '@cds/core/internal';
import { CdsControl } from '@cds/core/forms';
import globalStyles from './range.global.scss';
import styles from './range.element.scss';
Expand Down Expand Up @@ -51,10 +51,19 @@ export class CdsRange extends CdsControl {
super.firstUpdated(props);
this.setTrackWidth();
this.inputControl.addEventListener('input', () => this.setTrackWidth());

// `input` event doesnt fire when the value is changed programmatically
// at this point, inputControl.valueAsNumber is still the old value
// https://github.com/vmware-clarity/core/issues/157
this.observers.push(
getElementUpdates(this.inputControl, 'value', (value: number) => {
this.setTrackWidth(value);
})
);
}

private setTrackWidth() {
const value = this.inputControl.valueAsNumber;
private setTrackWidth(val?: number) {
const value = val ?? this.inputControl.valueAsNumber;
const min = this.inputControl.min ? parseInt(this.inputControl.min) : 0;
const max = this.inputControl.max ? parseInt(this.inputControl.max) : 100;
this.style.setProperty('--track-width', `${Math.floor(((value - min) / (max - min)) * 100)}%`);
Expand Down

0 comments on commit 8c91050

Please sign in to comment.