Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,13 @@ All notable changes to this project will be documented in this file.

The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)

## [Unreleased]

### Added

- **SingleSelect**: Added the ability to update the state of an already initialized component
by modifying its child options.

## [1.10.0] - 2025-01-11

### Fixed
Expand Down
55 changes: 55 additions & 0 deletions dev/vscode-single-select/sync-options.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>VSCode Elements</title>
<link
rel="stylesheet"
href="/node_modules/@vscode/codicons/dist/codicon.css"
id="vscode-codicon-stylesheet"
/>
<script
type="module"
src="/node_modules/@vscode-elements/webview-playground/dist/index.js"
></script>
<script type="module" src="/dist/main.js"></script>
<script>
const logEvents = (selector, eventType) => {
document.querySelector(selector).addEventListener(eventType, (ev) => {
console.log(ev);
});
};
</script>
</head>

<body>
<h1>Sync options</h1>
<main>
<vscode-demo>
<select id="select-1">
<option>Lorem</option>
<option>Ipsum</option>
<option>Dolor</option>
</select>
<vscode-single-select id="select">
<vscode-option>Lorem</vscode-option>
<vscode-option>Ipsum</vscode-option>
<vscode-option>Dolor</vscode-option>
</vscode-single-select>
<button id="button">Change</button>
<script>
logEvents('#select', 'change');

document.querySelector('#button').addEventListener('click', () => {
const op = document.querySelectorAll('vscode-option')[2];
const op1 = document.querySelectorAll('vscode-option')[1];

op.description = 'aaa';
op1.disabled = true;
});
</script>
</vscode-demo>
</main>
</body>
</html>
2 changes: 1 addition & 1 deletion src/includes/vscode-select/styles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,7 +207,7 @@ export default [
color: var(--vscode-list-focusHighlightForeground);
}

.option:hover {
.option:not(.disabled):hover {
background-color: var(--vscode-list-hoverBackground);
color: var(--vscode-list-hoverForeground);
}
Expand Down
60 changes: 34 additions & 26 deletions src/includes/vscode-select/vscode-select-base.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,15 @@ export class VscodeSelectBase extends VscElement {
})
private _assignedOptions!: VscodeOption[];

constructor() {
super();
this.addEventListener('vsc-option-state-change', (ev) => {
ev.stopPropagation();
this._setStateFromSlottedElements();
this.requestUpdate();
});
}

connectedCallback(): void {
super.connectedCallback();
this.addEventListener('keydown', this._onComponentKeyDown);
Expand Down Expand Up @@ -219,14 +228,12 @@ export class VscodeSelectBase extends VscElement {
return this.combobox ? this._filteredOptions : this._options;
}

protected _addOptionsFromSlottedElements(): OptionListStat {
protected _setStateFromSlottedElements() {
const options: InternalOption[] = [];
let nextIndex = 0;
const optionElements = this._assignedOptions ?? [];
const optionsListStat: OptionListStat = {
selectedIndexes: [],
values: [],
};
const selectedIndexes: number[] = [];
const values: string[] = [];
this._valueOptionIndexMap = {};

optionElements.forEach((el) => {
Expand All @@ -245,16 +252,29 @@ export class VscodeSelectBase extends VscElement {
nextIndex = options.push(op);

if (selected) {
optionsListStat.selectedIndexes.push(options.length - 1);
optionsListStat.values.push(value);
selectedIndexes.push(options.length - 1);
values.push(value);
}

this._valueOptionIndexMap[op.value] = op.index;
});

this._options = options;

return optionsListStat;
if (selectedIndexes.length > 0) {
this._selectedIndex = selectedIndexes[0];
this._selectedIndexes = selectedIndexes;
this._value = values[0];
this._values = values;
}

if (
!this._multiple &&
!this.combobox &&
selectedIndexes.length === 0
) {
this._selectedIndex = this._options.length > 0 ? 0 : -1;
}
}

protected async _toggleDropdown(visible: boolean): Promise<void> {
Expand Down Expand Up @@ -513,23 +533,7 @@ export class VscodeSelectBase extends VscElement {
}

protected _onSlotChange(): void {
const stat = this._addOptionsFromSlottedElements();

if (stat.selectedIndexes.length > 0) {
this._selectedIndex = stat.selectedIndexes[0];
this._selectedIndexes = stat.selectedIndexes;
this._value = stat.values[0];
this._values = stat.values;
}

if (
!this._multiple &&
!this.combobox &&
stat.selectedIndexes.length === 0
) {
this._selectedIndex = this._options.length > 0 ? 0 : -1;
}

this._setStateFromSlottedElements();
this.requestUpdate();
}

Expand Down Expand Up @@ -575,14 +579,18 @@ export class VscodeSelectBase extends VscElement {
return html`${nothing}`;
}

private _onPropChange = () => {
console.log('ONPROPCHANGE');
};

private _renderDropdown() {
const classes = classMap({
dropdown: true,
multiple: this._multiple,
});

return html`
<div class="${classes}">
<div class="${classes}" @vsc-property-change=${this._onPropChange}>
${this.position === 'above' ? this._renderDescription() : nothing}
${this._renderOptions()} ${this._renderDropdownControls()}
${this.position === 'below' ? this._renderDescription() : nothing}
Expand Down
45 changes: 40 additions & 5 deletions src/vscode-option/vscode-option.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {html, TemplateResult} from 'lit';
import {html, PropertyValues, TemplateResult} from 'lit';
import {customElement, property} from 'lit/decorators.js';
import {VscElement} from '../includes/VscElement.js';
import styles from './vscode-option.styles.js';
Expand All @@ -13,12 +13,47 @@ export class VscodeOption extends VscElement {
@property({type: String})
value?: string | undefined;

@property({type: String}) description = '';
@property({type: Boolean, reflect: true}) selected = false;
@property({type: Boolean, reflect: true}) disabled = false;
@property({type: String})
description = '';

@property({type: Boolean, reflect: true})
selected = false;

@property({type: Boolean, reflect: true})
disabled = false;

private _initialized = false;

connectedCallback(): void {
super.connectedCallback();

this.updateComplete.then(() => {
this._initialized = true;
});
}

protected willUpdate(changedProperties: PropertyValues): void {
if (
this._initialized &&
(changedProperties.has('description') ||
changedProperties.has('value') ||
changedProperties.has('selected') ||
changedProperties.has('disabled'))
) {
/** @internal */
this.dispatchEvent(new Event('vsc-option-state-change', {bubbles: true}));
}
}

private _handleSlotChange = () => {
if (this._initialized) {
/** @internal */
this.dispatchEvent(new Event('vsc-option-state-change', {bubbles: true}));
}
};

render(): TemplateResult {
return html`<slot></slot>`;
return html`<slot @slotchange=${this._handleSlotChange}></slot>`;
}
}

Expand Down
85 changes: 75 additions & 10 deletions src/vscode-single-select/vscode-single-select.test.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import {clickOnElement, moveMouseOnElement} from '../includes/test-helpers.js';
import type {VscodeOption} from '../vscode-option/vscode-option.js';
import {VscodeSingleSelect} from './index.js';
import {aTimeout, expect, fixture, html} from '@open-wc/testing';
import sinon from 'sinon';
Expand Down Expand Up @@ -69,13 +71,9 @@ describe('vscode-single-select', () => {
});

it('should return the validation message', async () => {
const el = document.createElement(
'vscode-single-select'
) as VscodeSingleSelect;
el.required = true;
document.body.appendChild(el);

await aTimeout(0);
const el = await fixture<VscodeSingleSelect>(
html`<vscode-single-select required></vscode-single-select>`
);

expect(el.validationMessage).to.eql('Please select an item in the list.');
});
Expand Down Expand Up @@ -843,10 +841,11 @@ describe('vscode-single-select', () => {
expect(el.tabIndex).to.eq(2);
});

it('should not throw error when selectedIndex points to a non-existent option', () => {
const el = document.createElement('vscode-single-select');
it('should not throw error when selectedIndex points to a non-existent option', async () => {
const el = await fixture<VscodeSingleSelect>(
html`<vscode-single-select></vscode-single-select>`
);
el.selectedIndex = 2;
document.body.appendChild(el);

expect(() => {
// trigger a slot change event
Expand Down Expand Up @@ -925,4 +924,70 @@ describe('vscode-single-select', () => {

expect(sl.shadowRoot?.querySelector('ul.options')).to.be.ok;
});

it('changes the description of an option in an existing select', async () => {
const el = await fixture<VscodeSingleSelect>(html`
<vscode-single-select>
<vscode-option>Lorem</vscode-option>
<vscode-option>Ipsum</vscode-option>
<vscode-option>Dolor</vscode-option>
</vscode-single-select>
`);
const secondOption = el.querySelectorAll<VscodeOption>('vscode-option')[1];

secondOption.description = 'Test description';
await el.updateComplete;

await clickOnElement(el);
await el.updateComplete;

await moveMouseOnElement(el.shadowRoot!.querySelectorAll('li')[1]);
await el.updateComplete;

const desc = el.shadowRoot!.querySelector<HTMLDivElement>('.description');

expect(desc).lightDom.to.eq('Test description');
});

it('changes the label of an option in an existing select', async () => {
const el = await fixture<VscodeSingleSelect>(html`
<vscode-single-select>
<vscode-option>Lorem</vscode-option>
<vscode-option>Ipsum</vscode-option>
<vscode-option>Dolor</vscode-option>
</vscode-single-select>
`);
const secondOption = el.querySelectorAll<VscodeOption>('vscode-option')[1];

secondOption.innerHTML = 'Test label';
await el.updateComplete;

await clickOnElement(el);
await el.updateComplete;

const li = el.shadowRoot!.querySelectorAll<HTMLLIElement>('li')[1];

expect(li).lightDom.to.eq('Test label');
});

it('changes the disabled state of an option in an existing select', async () => {
const el = await fixture<VscodeSingleSelect>(html`
<vscode-single-select>
<vscode-option>Lorem</vscode-option>
<vscode-option>Ipsum</vscode-option>
<vscode-option>Dolor</vscode-option>
</vscode-single-select>
`);
const secondOption = el.querySelectorAll<VscodeOption>('vscode-option')[1];

secondOption.disabled = true;
await el.updateComplete;

await clickOnElement(el);
await el.updateComplete;

const li = el.shadowRoot!.querySelectorAll<HTMLLIElement>('li')[1];

expect(li.classList.contains('disabled')).to.be.true;
});
});
Loading