@digital-realty/ix-select 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +91 -0
  3. package/demo/index.html +58 -0
  4. package/dist/src/IxSelect.d.ts +57 -0
  5. package/dist/src/IxSelect.js +215 -0
  6. package/dist/src/IxSelect.js.map +1 -0
  7. package/dist/src/index.d.ts +2 -0
  8. package/dist/src/index.js +3 -0
  9. package/dist/src/index.js.map +1 -0
  10. package/dist/src/ix-select.d.ts +1 -0
  11. package/dist/src/ix-select.js +3 -0
  12. package/dist/src/ix-select.js.map +1 -0
  13. package/dist/src/react/IxSelect.d.ts +4 -0
  14. package/dist/src/react/IxSelect.js +13 -0
  15. package/dist/src/react/IxSelect.js.map +1 -0
  16. package/dist/src/react/IxSelectOption.d.ts +4 -0
  17. package/dist/src/react/IxSelectOption.js +13 -0
  18. package/dist/src/react/IxSelectOption.js.map +1 -0
  19. package/dist/src/selectoption/IxSelectOption.d.ts +83 -0
  20. package/dist/src/selectoption/IxSelectOption.js +187 -0
  21. package/dist/src/selectoption/IxSelectOption.js.map +1 -0
  22. package/dist/src/selectoption/ix-select-option.d.ts +1 -0
  23. package/dist/src/selectoption/ix-select-option.js +3 -0
  24. package/dist/src/selectoption/ix-select-option.js.map +1 -0
  25. package/dist/src/selectoption/selectOptionController.d.ts +91 -0
  26. package/dist/src/selectoption/selectOptionController.js +118 -0
  27. package/dist/src/selectoption/selectOptionController.js.map +1 -0
  28. package/dist/test/ix-select.test.d.ts +1 -0
  29. package/dist/test/ix-select.test.js +58 -0
  30. package/dist/test/ix-select.test.js.map +1 -0
  31. package/dist/tsconfig.tsbuildinfo +1 -0
  32. package/package.json +97 -0
  33. package/src/IxSelect.ts +218 -0
  34. package/src/index.ts +2 -0
  35. package/src/ix-select.ts +3 -0
  36. package/src/react/IxSelect.ts +14 -0
  37. package/src/react/IxSelectOption.ts +14 -0
  38. package/src/selectoption/IxSelectOption.ts +192 -0
  39. package/src/selectoption/ix-select-option.ts +3 -0
  40. package/src/selectoption/selectOptionController.ts +179 -0
  41. package/test/ix-select.test.ts +79 -0
  42. package/tsconfig.json +21 -0
  43. package/web-dev-server.config.mjs +27 -0
  44. package/web-test-runner.config.mjs +41 -0
@@ -0,0 +1,192 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2023 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import '@material/web/ripple/ripple.js';
8
+ import '@material/web/focus/md-focus-ring.js';
9
+ import '@material/web/labs/item/item.js';
10
+
11
+ import { html, LitElement, nothing } from 'lit';
12
+ import { property, query, queryAssignedElements } from 'lit/decorators.js';
13
+ import { ClassInfo, classMap } from 'lit/directives/class-map.js';
14
+
15
+ import { ARIAMixinStrict } from '@material/web/internal/aria/aria.js';
16
+ import { requestUpdateOnAriaChange } from '@material/web/internal/aria/delegate.js';
17
+
18
+ import {
19
+ SelectOption,
20
+ SelectOptionController,
21
+ } from './selectOptionController.js';
22
+
23
+ /**
24
+ * @fires close-menu Closes the encapsulating menu on
25
+ * @fires request-selection Requests the parent md-select to select this element
26
+ * (and deselect others if single-selection) when `selected` changed to `true`.
27
+ * @fires request-deselection Requests the parent md-select to deselect this
28
+ * element when `selected` changed to `false`.
29
+ */
30
+ export class IxSelectOption extends LitElement implements SelectOption {
31
+ static {
32
+ requestUpdateOnAriaChange(IxSelectOption);
33
+ }
34
+
35
+ /** @nocollapse */
36
+ static override shadowRootOptions = {
37
+ ...LitElement.shadowRootOptions,
38
+ delegatesFocus: true,
39
+ };
40
+
41
+ /**
42
+ * Disables the item and makes it non-selectable and non-interactive.
43
+ */
44
+ @property({ type: Boolean, reflect: true }) disabled = false;
45
+
46
+ /**
47
+ * READONLY: self-identifies as a menu item and sets its identifying attribute
48
+ */
49
+ @property({ type: Boolean, attribute: 'md-menu-item', reflect: true })
50
+ isMenuItem = true;
51
+
52
+ /**
53
+ * Sets the item in the selected visual state when a submenu is opened.
54
+ */
55
+ @property({ type: Boolean }) selected = false;
56
+
57
+ /**
58
+ * Form value of the option.
59
+ */
60
+ @property() value = '';
61
+
62
+ @query('.list-item') protected readonly listItemRoot!: HTMLElement | null;
63
+
64
+ @queryAssignedElements({ slot: 'headline' })
65
+ protected readonly headlineElements!: HTMLElement[];
66
+
67
+ type = 'option' as const;
68
+
69
+ /**
70
+ * The text that is selectable via typeahead. If not set, defaults to the
71
+ * innerText of the item slotted into the `"headline"` slot.
72
+ */
73
+ get typeaheadText() {
74
+ return this.selectOptionController.typeaheadText;
75
+ }
76
+
77
+ @property({ attribute: 'typeahead-text' })
78
+ set typeaheadText(text: string) {
79
+ this.selectOptionController.setTypeaheadText(text);
80
+ }
81
+
82
+ /**
83
+ * The text that is displayed in the select field when selected. If not set,
84
+ * defaults to the textContent of the item slotted into the `"headline"` slot.
85
+ */
86
+ get displayText() {
87
+ return this.selectOptionController.displayText;
88
+ }
89
+
90
+ @property({ attribute: 'display-text' })
91
+ set displayText(text: string) {
92
+ this.selectOptionController.setDisplayText(text);
93
+ }
94
+
95
+ private readonly selectOptionController = new SelectOptionController(this, {
96
+ getHeadlineElements: () => this.headlineElements,
97
+ });
98
+
99
+ protected override render() {
100
+ return this.renderListItem(html`
101
+ <md-item>
102
+ <div slot="container">
103
+ ${this.renderRipple()} ${this.renderFocusRing()}
104
+ </div>
105
+ <slot name="start" slot="start"></slot>
106
+ <slot name="end" slot="end"></slot>
107
+ ${this.renderBody()}
108
+ </md-item>
109
+ `);
110
+ }
111
+
112
+ /**
113
+ * Renders the root list item.
114
+ *
115
+ * @param content the child content of the list item.
116
+ */
117
+ protected renderListItem(content: unknown) {
118
+ return html`
119
+ <li
120
+ id="item"
121
+ tabindex=${this.disabled ? -1 : 0}
122
+ role=${this.selectOptionController.role}
123
+ aria-label=${(this as ARIAMixinStrict).ariaLabel || nothing}
124
+ aria-selected=${(this as ARIAMixinStrict).ariaSelected || nothing}
125
+ aria-checked=${(this as ARIAMixinStrict).ariaChecked || nothing}
126
+ aria-expanded=${(this as ARIAMixinStrict).ariaExpanded || nothing}
127
+ aria-haspopup=${(this as ARIAMixinStrict).ariaHasPopup || nothing}
128
+ class="list-item ${classMap(this.getRenderClasses())}"
129
+ @click=${this.selectOptionController.onClick}
130
+ @keydown=${this.selectOptionController.onKeydown}
131
+ >
132
+ ${content}
133
+ </li>
134
+ `;
135
+ }
136
+
137
+ /**
138
+ * Handles rendering of the ripple element.
139
+ */
140
+ protected renderRipple() {
141
+ return html` <md-ripple
142
+ part="ripple"
143
+ for="item"
144
+ ?disabled=${this.disabled}
145
+ ></md-ripple>`;
146
+ }
147
+
148
+ /**
149
+ * Handles rendering of the focus ring.
150
+ */
151
+ // eslint-disable-next-line class-methods-use-this
152
+ protected renderFocusRing() {
153
+ return html` <md-focus-ring
154
+ part="focus-ring"
155
+ for="item"
156
+ inward
157
+ ></md-focus-ring>`;
158
+ }
159
+
160
+ /**
161
+ * Classes applied to the list item root.
162
+ */
163
+ protected getRenderClasses(): ClassInfo {
164
+ return {
165
+ disabled: this.disabled,
166
+ selected: this.selected,
167
+ };
168
+ }
169
+
170
+ /**
171
+ * Handles rendering the headline and supporting text.
172
+ */
173
+ // eslint-disable-next-line class-methods-use-this
174
+ protected renderBody() {
175
+ return html`
176
+ <slot></slot>
177
+ <slot name="overline" slot="overline"></slot>
178
+ <slot name="headline" slot="headline"></slot>
179
+ <slot name="supporting-text" slot="supporting-text"></slot>
180
+ <slot
181
+ name="trailing-supporting-text"
182
+ slot="trailing-supporting-text"
183
+ ></slot>
184
+ `;
185
+ }
186
+
187
+ override focus() {
188
+ // TODO(b/300334509): needed for some cases where delegatesFocus doesn't
189
+ // work programmatically like in FF and select-option
190
+ this.listItemRoot?.focus();
191
+ }
192
+ }
@@ -0,0 +1,3 @@
1
+ import { IxSelectOption } from './IxSelectOption.js';
2
+
3
+ window.customElements.define('ix-select-option', IxSelectOption);
@@ -0,0 +1,179 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2023 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { ReactiveController, ReactiveControllerHost } from 'lit';
8
+
9
+ import {
10
+ MenuItem,
11
+ MenuItemController,
12
+ MenuItemControllerConfig,
13
+ } from '@material/web/menu/internal/controllers/menuItemController.js';
14
+
15
+ /**
16
+ * The interface specific to a Select Option
17
+ */
18
+ interface SelectOptionSelf {
19
+ /**
20
+ * The form value associated with the Select Option. (Note: the visual portion
21
+ * of the SelectOption is the headline defined in ListItem)
22
+ */
23
+ value: string;
24
+ /**
25
+ * Whether or not the SelectOption is selected.
26
+ */
27
+ selected: boolean;
28
+ /**
29
+ * The text to display in the select when selected. Defaults to the
30
+ * textContent of the Element slotted into the headline.
31
+ */
32
+ displayText: string;
33
+ }
34
+
35
+ /**
36
+ * The interface to implement for a select option. Additionally, the element
37
+ * must have `md-list-item` and `md-menu-item` attributes on the host.
38
+ */
39
+ export type SelectOption = SelectOptionSelf & MenuItem;
40
+
41
+ /**
42
+ * Creates an event fired by a SelectOption to request selection from md-select.
43
+ * Typically fired after `selected` changes from `false` to `true`.
44
+ */
45
+ export function createRequestSelectionEvent() {
46
+ return new Event('request-selection', {
47
+ bubbles: true,
48
+ composed: true,
49
+ });
50
+ }
51
+
52
+ /**
53
+ * Creates an event fired by a SelectOption to request deselection from
54
+ * md-select. Typically fired after `selected` changes from `true` to `false`.
55
+ */
56
+ export function createRequestDeselectionEvent() {
57
+ return new Event('request-deselection', {
58
+ bubbles: true,
59
+ composed: true,
60
+ });
61
+ }
62
+
63
+ /**
64
+ * The options used to inialize SelectOptionController.
65
+ */
66
+ export type SelectOptionConfig = MenuItemControllerConfig;
67
+
68
+ /**
69
+ * A controller that provides most functionality and md-select compatibility for
70
+ * an element that implements the SelectOption interface.
71
+ */
72
+ export class SelectOptionController implements ReactiveController {
73
+ private readonly menuItemController: MenuItemController;
74
+
75
+ private readonly getHeadlineElements: SelectOptionConfig['getHeadlineElements'];
76
+
77
+ private internalDisplayText: string | null = null;
78
+
79
+ private lastSelected = this.host.selected;
80
+
81
+ private firstUpdate = true;
82
+
83
+ /**
84
+ * The recommended role of the select option.
85
+ */
86
+ get role() {
87
+ return this.menuItemController.role;
88
+ }
89
+
90
+ /**
91
+ * The text that is selectable via typeahead. If not set, defaults to the
92
+ * innerText of the item slotted into the `"headline"` slot.
93
+ */
94
+ get typeaheadText() {
95
+ return this.menuItemController.typeaheadText;
96
+ }
97
+
98
+ setTypeaheadText(text: string) {
99
+ this.menuItemController.setTypeaheadText(text);
100
+ }
101
+
102
+ /**
103
+ * The text that is displayed in the select field when selected. If not set,
104
+ * defaults to the textContent of the item slotted into the `"headline"` slot.
105
+ */
106
+ get displayText() {
107
+ if (this.internalDisplayText !== null) {
108
+ return this.internalDisplayText;
109
+ }
110
+
111
+ const headlineElements = this.getHeadlineElements();
112
+
113
+ const textParts: string[] = [];
114
+ headlineElements.forEach(headlineElement => {
115
+ if (headlineElement.textContent && headlineElement.textContent.trim()) {
116
+ textParts.push(headlineElement.textContent.trim());
117
+ }
118
+ });
119
+
120
+ return textParts.join(' ');
121
+ }
122
+
123
+ setDisplayText(text: string) {
124
+ this.internalDisplayText = text;
125
+ }
126
+
127
+ /**
128
+ * @param host The SelectOption in which to attach this controller to.
129
+ * @param config The object that configures this controller's behavior.
130
+ */
131
+ constructor(
132
+ private readonly host: ReactiveControllerHost & SelectOption,
133
+ config: SelectOptionConfig
134
+ ) {
135
+ this.menuItemController = new MenuItemController(host, config);
136
+ this.getHeadlineElements = config.getHeadlineElements;
137
+ host.addController(this);
138
+ }
139
+
140
+ hostUpdate() {
141
+ if (this.lastSelected !== this.host.selected) {
142
+ this.host.ariaSelected = this.host.selected ? 'true' : 'false';
143
+ }
144
+ }
145
+
146
+ hostUpdated() {
147
+ // Do not dispatch event on first update / boot-up.
148
+ if (this.lastSelected !== this.host.selected && !this.firstUpdate) {
149
+ // This section is really useful for when the user sets selected on the
150
+ // option programmatically. Most other cases (click and keyboard) are
151
+ // handled by md-select because it needs to coordinate the
152
+ // single-selection behavior.
153
+ if (this.host.selected) {
154
+ this.host.dispatchEvent(createRequestSelectionEvent());
155
+ } else {
156
+ this.host.dispatchEvent(createRequestDeselectionEvent());
157
+ }
158
+ }
159
+
160
+ this.lastSelected = this.host.selected;
161
+ this.firstUpdate = false;
162
+ }
163
+
164
+ /**
165
+ * Bind this click listener to the interactive element. Handles closing the
166
+ * menu.
167
+ */
168
+ onClick = () => {
169
+ this.menuItemController.onClick();
170
+ };
171
+
172
+ /**
173
+ * Bind this click listener to the interactive element. Handles closing the
174
+ * menu.
175
+ */
176
+ onKeydown = (e: KeyboardEvent) => {
177
+ this.menuItemController.onKeydown(e);
178
+ };
179
+ }
@@ -0,0 +1,79 @@
1
+ import { html } from 'lit';
2
+ import { fixture, expect } from '@open-wc/testing';
3
+ import { IxSelect } from '../src/IxSelect.js';
4
+ import '../src/ix-select.js';
5
+
6
+ describe('IxSelect', () => {
7
+ it('should show the outlined field by default', async () => {
8
+ const el = await fixture<IxSelect>(html`<ix-select></ix-select>`);
9
+
10
+ expect(el.materialRoot.tagName.toLowerCase()).to.be.string(
11
+ 'md-outlined-select'
12
+ );
13
+ });
14
+ });
15
+
16
+ describe('IxSelect', () => {
17
+ it('should render the appearance specified by property', async () => {
18
+ const el = await fixture<IxSelect>(
19
+ html`<ix-select appearance="filled"></ix-select>`
20
+ );
21
+
22
+ expect(el.materialRoot.tagName.toLowerCase()).to.be.string(
23
+ 'md-filled-select'
24
+ );
25
+ });
26
+ });
27
+
28
+ describe('IxSelect', () => {
29
+ it('form should submit with data', async () => {
30
+ let formData: FormData;
31
+
32
+ const select = await fixture<IxSelect>(html`
33
+ <ix-select name="theForm" label="theLabel">
34
+ <ix-select-option value="1">
35
+ <div slot="headline">Test Value</div>
36
+ </ix-select-option>
37
+ </ix-select>
38
+ `);
39
+
40
+ const handleSubmit = (e: Event & { target: HTMLFormElement }) => {
41
+ e.preventDefault();
42
+ formData = new FormData(e.target);
43
+ };
44
+ const form = await fixture<HTMLFormElement>(html`
45
+ <form @submit=${handleSubmit}>
46
+ ${select}
47
+ <button type="submit">Submit</button>
48
+ </form>
49
+ `);
50
+
51
+ form.addEventListener('submit', () => {
52
+ formData.forEach((value, key) => console.log(`${key}: ${value}`));
53
+ });
54
+
55
+ select.materialRoot.options[0].shadowRoot?.querySelector('li')?.click();
56
+
57
+ // Wait for 'request-selection' event to propogate to select after dropdown item 'clicked'
58
+ // Form will not contain any data if we submit before event is received
59
+ // eslint-disable-next-line no-use-before-define
60
+ await waitForEvent(select, 'request-selection');
61
+
62
+ form.querySelector('button')?.click();
63
+
64
+ expect(
65
+ formData!.get('theForm'),
66
+ 'Form data did not contain expected result'
67
+ ).is.string('1');
68
+ });
69
+ });
70
+
71
+ function waitForEvent(target: EventTarget, eventName: string): Promise<Event> {
72
+ return new Promise(resolve => {
73
+ const handler = (event: Event) => {
74
+ resolve(event);
75
+ target.removeEventListener(eventName, handler);
76
+ };
77
+ target.addEventListener(eventName, handler);
78
+ });
79
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,21 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "es2018",
4
+ "module": "esnext",
5
+ "moduleResolution": "node",
6
+ "noEmitOnError": true,
7
+ "lib": ["es2017", "dom"],
8
+ "strict": true,
9
+ "esModuleInterop": false,
10
+ "allowSyntheticDefaultImports": true,
11
+ "experimentalDecorators": true,
12
+ "importHelpers": true,
13
+ "outDir": "dist",
14
+ "sourceMap": true,
15
+ "inlineSources": true,
16
+ "rootDir": "./",
17
+ "declaration": true,
18
+ "incremental": true
19
+ },
20
+ "include": ["**/*.ts"]
21
+ }
@@ -0,0 +1,27 @@
1
+ // import { hmrPlugin, presets } from '@open-wc/dev-server-hmr';
2
+
3
+ /** Use Hot Module replacement by adding --hmr to the start command */
4
+ const hmr = process.argv.includes('--hmr');
5
+
6
+ export default /** @type {import('@web/dev-server').DevServerConfig} */ ({
7
+ open: '/demo/',
8
+ /** Use regular watch mode if HMR is not enabled. */
9
+ watch: !hmr,
10
+ /** Resolve bare module imports */
11
+ nodeResolve: {
12
+ exportConditions: ['browser', 'development'],
13
+ },
14
+
15
+ /** Compile JS for older browsers. Requires @web/dev-server-esbuild plugin */
16
+ // esbuildTarget: 'auto'
17
+
18
+ /** Set appIndex to enable SPA routing */
19
+ // appIndex: 'demo/index.html',
20
+
21
+ plugins: [
22
+ /** Use Hot Module Replacement by uncommenting. Requires @open-wc/dev-server-hmr plugin */
23
+ // hmr && hmrPlugin({ exclude: ['**/*/node_modules/**/*'], presets: [presets.litElement] }),
24
+ ],
25
+
26
+ // See documentation for all available options
27
+ });
@@ -0,0 +1,41 @@
1
+ // import { playwrightLauncher } from '@web/test-runner-playwright';
2
+
3
+ const filteredLogs = ['Running in dev mode', 'lit-html is in dev mode'];
4
+
5
+ export default /** @type {import("@web/test-runner").TestRunnerConfig} */ ({
6
+ /** Test files to run */
7
+ files: 'dist/test/**/*.test.js',
8
+
9
+ /** Resolve bare module imports */
10
+ nodeResolve: {
11
+ exportConditions: ['browser', 'development'],
12
+ },
13
+
14
+ /** Filter out lit dev mode logs */
15
+ filterBrowserLogs(log) {
16
+ for (const arg of log.args) {
17
+ if (typeof arg === 'string' && filteredLogs.some(l => arg.includes(l))) {
18
+ return false;
19
+ }
20
+ }
21
+ return true;
22
+ },
23
+
24
+ /** Compile JS for older browsers. Requires @web/dev-server-esbuild plugin */
25
+ // esbuildTarget: 'auto',
26
+
27
+ /** Amount of browsers to run concurrently */
28
+ // concurrentBrowsers: 2,
29
+
30
+ /** Amount of test files per browser to test concurrently */
31
+ // concurrency: 1,
32
+
33
+ /** Browsers to run tests on */
34
+ // browsers: [
35
+ // playwrightLauncher({ product: 'chromium' }),
36
+ // playwrightLauncher({ product: 'firefox' }),
37
+ // playwrightLauncher({ product: 'webkit' }),
38
+ // ],
39
+
40
+ // See documentation for all available options
41
+ });