Skip to content

docs(combobox): add story demonstrating controlled-component usage #3988

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Merged
merged 2 commits into from
Feb 1, 2024
Merged
Changes from 1 commit
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
54 changes: 53 additions & 1 deletion packages/combobox/stories/combobox.stories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,22 @@ OF ANY KIND, either express or implied. See the License for the specific languag
governing permissions and limitations under the License.
*/

import { html, TemplateResult } from '@spectrum-web-components/base';
import {
html,
LitElement,
TemplateResult,
} from '@spectrum-web-components/base';

import { countries, fruits } from './index.js';
import '@spectrum-web-components/combobox/sp-combobox.js';
import '@spectrum-web-components/field-label/sp-field-label.js';
import '@spectrum-web-components/help-text/sp-help-text.js';
import '@spectrum-web-components/tooltip/sp-tooltip.js';
import '@spectrum-web-components/menu/sp-menu-item.js';
import { Combobox, ComboboxOption } from '../src/Combobox.js';
import { defineElement } from '@spectrum-web-components/base/src/define-element.js';
import { query, state } from '@spectrum-web-components/base/src/decorators.js';
import { live } from '@spectrum-web-components/base/src/directives.js';

export default {
title: 'Combobox',
Expand Down Expand Up @@ -145,3 +153,47 @@ export const withHelpText = (): TemplateResult => {
</sp-combobox>
`;
};

class ControlledCombo extends LitElement {
static ages: ComboboxOption[] = Array.from({ length: 76 - 55 }, (_, n) => {
const age = `${n + 55}`;
return { value: age, itemText: age };
});

@state()
private value = {
raw: '',
validated: `${ControlledCombo.ages[0].itemText}`,
};

@query('#age')
private combobox!: Combobox;

override render(): TemplateResult {
return html`
<sp-field-label for="age">
Retirement age (try entering a non-number)
</sp-field-label>
<sp-combobox
id="age"
.options=${ControlledCombo.ages}
.value=${live(this.value.validated)}
@change=${this.onChange}
></sp-combobox>
`;
}

private onChange(): void {
this.value = {
raw: this.combobox.value,
validated: this.combobox.value.replace(/\D/g, '') || '55',
};
}
}
defineElement('controlled-combo', ControlledCombo);

export const controlled = (): TemplateResult => {
return html`
<controlled-combo></controlled-combo>
`;
};