@italia/chip 1.0.0-alpha.9 → 1.0.0-beta.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.
package/README.md CHANGED
@@ -1,75 +1,11 @@
1
- # \<it-chip>
1
+ # <it-chip>
2
2
 
3
- This webcomponent follows the [open-wc](https://github.com/open-wc/open-wc) recommendation.
3
+ This package is part of [dev-kit-italia](https://italia.github.io/dev-kit-italia), a Web Components kit for the **.italia** design-system.
4
4
 
5
- ## Installation
5
+ ## Installation and usage
6
6
 
7
- ```bash
8
- npm i @italia/chip
9
- ```
7
+ Most users want to install the full kit by installing [`@italia/dev-kit-italia`](https://npmjs.com/package/@italia/dev-kit-italia), but you have the option of installing this single Web Component separately if needed. Please find detailed installation and usage instructions in the [official documentation](https://italia.github.io/dev-kit-italia/?path=/docs/introduzione--documentazione).
10
8
 
11
- ## Usage
9
+ ## Documentation
12
10
 
13
- ```html
14
- <script type="module">
15
- import '@italia/chip';
16
- </script>
17
-
18
- <it-chip></it-chip>
19
- ```
20
-
21
- ## Linting and formatting
22
-
23
- To scan the project for linting and formatting errors, run
24
-
25
- ```bash
26
- npm run lint
27
- ```
28
-
29
- To automatically fix linting and formatting errors, run
30
-
31
- ```bash
32
- npm run format
33
- ```
34
-
35
- ## Testing with Web Test Runner
36
-
37
- To execute a single test run:
38
-
39
- ```bash
40
- npm run test
41
- ```
42
-
43
- To run the tests in interactive watch mode run:
44
-
45
- ```bash
46
- npm run test:watch
47
- ```
48
-
49
- ## Demoing with Storybook
50
-
51
- To run a local instance of Storybook for your component, run
52
-
53
- ```bash
54
- npm run storybook
55
- ```
56
-
57
- To build a production version of Storybook, run
58
-
59
- ```bash
60
- npm run storybook:build
61
- ```
62
-
63
- ## Tooling configs
64
-
65
- For most of the tools, the configuration is in the `package.json` to reduce the amount of files in your project.
66
-
67
- If you customize the configuration a lot, you can consider moving them to individual files.
68
-
69
- ## Local Demo with `web-dev-server`
70
-
71
- ```bash
72
- npm start
73
- ```
74
-
75
- To run a local development server that serves the basic demo located in `demo/index.html`
11
+ Find the usage instructions for this specific component in its [dedicated documentation page](https://italia.github.io/dev-kit-italia/?path=/docs/componenti-chip--documentazione).
@@ -14,6 +14,14 @@
14
14
  "name": "ItChip",
15
15
  "module": "./it-chip.js"
16
16
  }
17
+ },
18
+ {
19
+ "kind": "js",
20
+ "name": "ChipCloseEventDetail",
21
+ "declaration": {
22
+ "name": "ChipCloseEventDetail",
23
+ "module": "./types.js"
24
+ }
17
25
  }
18
26
  ]
19
27
  },
@@ -23,8 +31,14 @@
23
31
  "declarations": [
24
32
  {
25
33
  "kind": "class",
26
- "description": "",
34
+ "description": "Componente Chip.",
27
35
  "name": "ItChip",
36
+ "slots": [
37
+ {
38
+ "description": "Pulsante di rimozione (richiesto quando `dismissable`)",
39
+ "name": "dismiss-button"
40
+ }
41
+ ],
28
42
  "members": [
29
43
  {
30
44
  "kind": "field",
@@ -138,6 +152,77 @@
138
152
  "kind": "method",
139
153
  "name": "updateIcon",
140
154
  "privacy": "private"
155
+ },
156
+ {
157
+ "kind": "field",
158
+ "name": "_onHostClick",
159
+ "privacy": "private"
160
+ },
161
+ {
162
+ "kind": "method",
163
+ "name": "_requestClose",
164
+ "privacy": "private",
165
+ "return": {
166
+ "type": {
167
+ "text": "void"
168
+ }
169
+ }
170
+ },
171
+ {
172
+ "kind": "method",
173
+ "name": "close",
174
+ "privacy": "public",
175
+ "return": {
176
+ "type": {
177
+ "text": "void"
178
+ }
179
+ },
180
+ "description": "Rimuove la chip dal DOM spostando il focus su una chip adiacente, se presente.\nUtile dopo aver intercettato `it-chip-close` con `preventDefault()`."
181
+ },
182
+ {
183
+ "kind": "method",
184
+ "name": "_removeWithFocusShift",
185
+ "privacy": "private",
186
+ "return": {
187
+ "type": {
188
+ "text": "void"
189
+ }
190
+ }
191
+ },
192
+ {
193
+ "kind": "method",
194
+ "name": "_adjacentChip",
195
+ "privacy": "private",
196
+ "return": {
197
+ "type": {
198
+ "text": "ItChip | null"
199
+ }
200
+ }
201
+ },
202
+ {
203
+ "kind": "method",
204
+ "name": "_focusChip",
205
+ "privacy": "private",
206
+ "static": true,
207
+ "return": {
208
+ "type": {
209
+ "text": "void"
210
+ }
211
+ },
212
+ "parameters": [
213
+ {
214
+ "name": "chip",
215
+ "type": {
216
+ "text": "ItChip"
217
+ }
218
+ }
219
+ ]
220
+ }
221
+ ],
222
+ "events": [
223
+ {
224
+ "description": "Quando si clicca il pulsante di rimozione (cancelable: `preventDefault()` impedisce la rimozione)",
225
+ "name": "it-chip-close"
141
226
  }
142
227
  ],
143
228
  "attributes": [
@@ -343,7 +428,15 @@
343
428
  "type": {
344
429
  "text": "Story"
345
430
  },
346
- "default": "{ name: 'Chip con chiusura', render: () => html` <it-chip label=\"Etichetta\" size=\"sm\" variant=\"primary\" dismissable id=\"chip-dismissable\"> <it-button slot=\"dismiss-button\" it-aria-label=\"Elimina etichetta\" it-aria-description=\"Puoi premere per eliminare la chip.\" @click=${(e: Event) => { const chip = (e.currentTarget as HTMLElement).closest('it-chip'); if (chip) chip.remove(); }} @keydown=${(e: KeyboardEvent) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); const chip = (e.currentTarget as HTMLElement).closest('it-chip'); if (chip) chip.remove(); } }} > <it-icon name=\"it-close\" size=\"sm\"></it-icon> </it-button> </it-chip> `, parameters: { docs: { canvas: { sourceState: 'shown', }, source: { code: `<it-chip label=\"Etichetta\" size=\"sm\" variant=\"primary\" dismissable id=\"chip-dismissable\"> <it-button slot=\"dismiss-button\" it-aria-label=\"Elimina etichetta\" it-aria-description=\"Puoi premere per eliminare la chip.\" > <it-icon name=\"it-close\" size=\"sm\"></it-icon> </it-button> </it-chip> <script type=\"module\"> const dismissButtons = document.querySelectorAll('it-chip#chip-dismissable [slot=\"dismiss-button\"]'); dismissButtons.forEach((btn) => { const removeChip = (e) => { const chip = btn.closest('it-chip'); if (chip) chip.remove(); }; btn.addEventListener('click', removeChip); btn.addEventListener('keydown', (e) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); removeChip(e); } }); }); </script> `, language: 'html', }, }, }, }"
431
+ "default": "{ name: 'Chip con chiusura', render: () => html` <it-chip label=\"Etichetta\" size=\"sm\" variant=\"primary\" dismissable id=\"chip-dismissable\"> <it-button slot=\"dismiss-button\" it-aria-label=\"Elimina etichetta\" it-aria-description=\"Puoi premere per eliminare la chip.\" @click=${(e: Event) => { const chip = (e.currentTarget as HTMLElement).closest('it-chip'); if (chip) chip.remove(); }} @keydown=${(e: KeyboardEvent) => { if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); const chip = (e.currentTarget as HTMLElement).closest('it-chip'); if (chip) chip.remove(); } }} > <it-icon name=\"it-close\" size=\"sm\"></it-icon> </it-button> </it-chip> `, parameters: { docs: { canvas: { sourceState: 'shown', }, source: { code: `<it-chip label=\"Etichetta\" size=\"sm\" variant=\"primary\" dismissable id=\"chip-dismissable\"> <it-button slot=\"dismiss-button\" it-aria-label=\"Elimina etichetta\" it-aria-description=\"Puoi premere per eliminare la chip.\" > <it-icon name=\"it-close\" size=\"sm\"></it-icon> </it-button> </it-chip> `, language: 'html', }, }, }, }"
432
+ },
433
+ {
434
+ "kind": "variable",
435
+ "name": "ChiusuraConLogicaPersonalizzata",
436
+ "type": {
437
+ "text": "Story"
438
+ },
439
+ "default": "{ name: 'Logica di rimozione personalizzata', tags: ['!autodocs', '!dev'], parameters: { docs: { canvas: { sourceState: 'shown', }, source: { code: `<it-chip label=\"Etichetta\" size=\"sm\" variant=\"primary\" dismissable id=\"chip-conferma\" > <it-button slot=\"dismiss-button\" it-aria-label=\"Elimina etichetta\"> <it-icon name=\"it-close\" size=\"sm\"></it-icon> </it-button> </it-chip> <script type=\"module\"> const chip = document.getElementById('chip-conferma'); chip.addEventListener('it-chip-close', (e) => { e.preventDefault(); // impedisce la rimozione di default if (confirm('Rimuovere questa chip?')) chip.close(); }); </script> `, language: 'html', }, }, }, render: () => html` <it-chip label=\"Etichetta\" size=\"sm\" variant=\"primary\" dismissable @it-chip-close=${(e: Event) => { e.preventDefault(); // eslint-disable-next-line no-alert if (window.confirm('Rimuovere questa chip?')) { (e.currentTarget as HTMLElement & { close: () => void }).close(); } }} > <it-button slot=\"dismiss-button\" it-aria-label=\"Elimina etichetta\" it-aria-description=\"La rimozione richiede conferma.\" > <it-icon name=\"it-close\" size=\"sm\"></it-icon> </it-button> </it-chip> `, }"
347
440
  },
348
441
  {
349
442
  "kind": "variable",
@@ -435,6 +528,14 @@
435
528
  "module": "stories/it-chip.stories.ts"
436
529
  }
437
530
  },
531
+ {
532
+ "kind": "js",
533
+ "name": "ChiusuraConLogicaPersonalizzata",
534
+ "declaration": {
535
+ "name": "ChiusuraConLogicaPersonalizzata",
536
+ "module": "stories/it-chip.stories.ts"
537
+ }
538
+ },
438
539
  {
439
540
  "kind": "js",
440
541
  "name": "ChipDisabilitata",
@@ -1,2 +1,3 @@
1
1
  export { ItChip } from './it-chip.js';
2
+ export type { ChipCloseEventDetail } from './types.js';
2
3
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AACtC,YAAY,EAAE,oBAAoB,EAAE,MAAM,YAAY,CAAC"}
package/dist/src/index.js CHANGED
File without changes
File without changes
@@ -1,6 +1,15 @@
1
1
  import { BaseComponent } from '@italia/globals';
2
2
  import type { ItIcon } from '@italia/icon';
3
3
  import { ChipSize, ChipVariant } from './types.js';
4
+ /**
5
+ * Componente Chip.
6
+ *
7
+ * @element it-chip
8
+ *
9
+ * @slot dismiss-button - Pulsante di rimozione (richiesto quando `dismissable`)
10
+ *
11
+ * @fires it-chip-close - Quando si clicca il pulsante di rimozione (cancelable: `preventDefault()` impedisce la rimozione)
12
+ */
4
13
  export declare class ItChip extends BaseComponent {
5
14
  static styles: import("lit").CSSResultGroup;
6
15
  dismissable: boolean;
@@ -17,6 +26,18 @@ export declare class ItChip extends BaseComponent {
17
26
  private getAvatarSize;
18
27
  private updateIcon;
19
28
  updated(): void;
29
+ connectedCallback(): void;
30
+ disconnectedCallback(): void;
31
+ private _onHostClick;
32
+ private _requestClose;
33
+ /**
34
+ * Rimuove la chip dal DOM spostando il focus su una chip adiacente, se presente.
35
+ * Utile dopo aver intercettato `it-chip-close` con `preventDefault()`.
36
+ */
37
+ close(): void;
38
+ private _removeWithFocusShift;
39
+ private _adjacentChip;
40
+ private static _focusChip;
20
41
  render(): import("lit").TemplateResult<1>;
21
42
  }
22
43
  declare global {
@@ -1 +1 @@
1
- {"version":3,"file":"it-chip.d.ts","sourceRoot":"","sources":["../../src/it-chip.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAGhD,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,QAAQ,EAAE,WAAW,EAAE,MAAM,YAAY,CAAC;AAInD,qBACa,MAAO,SAAQ,aAAa;IACvC,MAAM,CAAC,MAAM,+BAAU;IAEqB,WAAW,UAAS;IAErB,IAAI,EAAE,QAAQ,CAAQ;IAEtB,MAAM,SAAM;IAEa,SAAS,SAAM;IAExC,KAAK,SAAM;IAEX,IAAI,SAAM;IAEqB,eAAe,SAAM;IAEpD,OAAO,CAAC,EAAE,WAAW,CAAC;IAEK,UAAU,UAAS;IAGzF,WAAW,EAAG,iBAAiB,EAAE,CAAC;IAGlC,IAAI,EAAG,MAAM,EAAE,CAAC;IAEhB,OAAO,CAAC,aAAa;IAKrB,OAAO,CAAC,UAAU;IAaT,OAAO;IAmChB,MAAM;CAyCP;AAED,OAAO,CAAC,MAAM,CAAC;IACb,UAAU,qBAAqB;QAC7B,SAAS,EAAE,MAAM,CAAC;KACnB;CACF"}
1
+ {"version":3,"file":"it-chip.d.ts","sourceRoot":"","sources":["../../src/it-chip.ts"],"names":[],"mappings":"AACA,OAAO,EACL,aAAa,EAId,MAAM,iBAAiB,CAAC;AAGzB,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,cAAc,CAAC;AAC3C,OAAO,EAAE,QAAQ,EAAE,WAAW,EAA6B,MAAM,YAAY,CAAC;AAI9E;;;;;;;;GAQG;AACH,qBACa,MAAO,SAAQ,aAAa;IACvC,MAAM,CAAC,MAAM,+BAAU;IAEqB,WAAW,UAAS;IAErB,IAAI,EAAE,QAAQ,CAAQ;IAEtB,MAAM,SAAM;IAEa,SAAS,SAAM;IAExC,KAAK,SAAM;IAEX,IAAI,SAAM;IAEqB,eAAe,SAAM;IAEpD,OAAO,CAAC,EAAE,WAAW,CAAC;IAEK,UAAU,UAAS;IAGzF,WAAW,EAAG,iBAAiB,EAAE,CAAC;IAGlC,IAAI,EAAG,MAAM,EAAE,CAAC;IAEhB,OAAO,CAAC,aAAa;IAKrB,OAAO,CAAC,UAAU;IAaT,OAAO;IAmCP,iBAAiB,IAAI,IAAI;IAOzB,oBAAoB,IAAI,IAAI;IAKrC,OAAO,CAAC,YAAY,CAQlB;IAEF,OAAO,CAAC,aAAa;IAIrB;;;OAGG;IACI,KAAK,IAAI,IAAI;IAIpB,OAAO,CAAC,qBAAqB;IAW7B,OAAO,CAAC,aAAa;IAcrB,OAAO,CAAC,MAAM,CAAC,UAAU;IAUzB,MAAM;CAyCP;AAED,OAAO,CAAC,MAAM,CAAC;IACb,UAAU,qBAAqB;QAC7B,SAAS,EAAE,MAAM,CAAC;KACnB;CACF"}
@@ -36,14 +36,80 @@ typeof SuppressedError === "function" ? SuppressedError : function (error, suppr
36
36
  return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
37
37
  };
38
38
 
39
+ const ARIA_IDREF_ATTRIBUTES = new Map([
40
+ ['aria-activedescendant', 'ariaActivedescendantElement'],
41
+ ['aria-controls', 'ariaControlsElements'],
42
+ ['aria-describedby', 'ariaDescribedByElements'],
43
+ ['aria-details', 'ariaDetailsElements'],
44
+ ['aria-errormessage', 'ariaErrormessageElements'],
45
+ ['aria-flowto', 'ariaFlowtoElements'],
46
+ ['aria-labelledby', 'ariaLabelledByElements'],
47
+ ['aria-owns', 'ariaOwnsElements'],
48
+ ]);
49
+ function resolveAriaIdRefs(element, value) {
50
+ const ids = value
51
+ .trim()
52
+ .split(/\s+/)
53
+ .filter((id) => id.length > 0);
54
+ if (ids.length === 0)
55
+ return null;
56
+ const root = element.getRootNode();
57
+ let resolvedElements = [];
58
+ if (root instanceof ShadowRoot) {
59
+ resolvedElements = ids.map((id) => root.getElementById(id));
60
+ }
61
+ else if (root instanceof Document) {
62
+ resolvedElements = ids.map((id) => root.getElementById(id));
63
+ }
64
+ else {
65
+ resolvedElements = ids.map((id) => document.getElementById(id));
66
+ }
67
+ if (resolvedElements.filter((el) => el !== null).length === 0) {
68
+ resolvedElements = ids.map((id) => document.getElementById(id));
69
+ }
70
+ const validElements = resolvedElements.filter((el) => el !== null);
71
+ return validElements.length === ids.length ? validElements : null;
72
+ }
73
+ function setInternalsProperty(el, name, resolvedElements) {
74
+ if (name === 'aria-activedescendant') {
75
+ const [firstElement] = resolvedElements;
76
+ // eslint-disable-next-line no-param-reassign
77
+ el[name] = firstElement;
78
+ }
79
+ else {
80
+ // eslint-disable-next-line no-param-reassign
81
+ el[name] = resolvedElements;
82
+ }
83
+ }
39
84
  class SetAttributesDirective extends Directive {
40
85
  update(part, [attributes]) {
41
86
  const el = part.element;
87
+ const internals = el.internals ?? null;
42
88
  for (const [name, value] of Object.entries(attributes)) {
43
- if (value != null)
44
- el.setAttribute(name, value);
45
- else
89
+ if (value == null) {
46
90
  el.removeAttribute(name);
91
+ }
92
+ else {
93
+ const internalsPropertyName = ARIA_IDREF_ATTRIBUTES.get(name);
94
+ if (internalsPropertyName) {
95
+ const resolvedElements = resolveAriaIdRefs(el, String(value));
96
+ if (resolvedElements) {
97
+ if (internals) {
98
+ // Set on ElementInternals
99
+ setInternalsProperty(internals, internalsPropertyName, resolvedElements);
100
+ }
101
+ else {
102
+ // Set internals property on shadowdom item
103
+ el.setAttribute(name, String(value));
104
+ setInternalsProperty(el, internalsPropertyName, resolvedElements);
105
+ }
106
+ }
107
+ }
108
+ else {
109
+ // Non-ARIA IDREF attributes: set normally
110
+ el.setAttribute(name, String(value));
111
+ }
112
+ }
47
113
  }
48
114
  return null;
49
115
  }
@@ -114,7 +180,9 @@ function registerTranslation(...translation) {
114
180
  });
115
181
  update();
116
182
  }
117
- window.registerTranslation = registerTranslation;
183
+ if (typeof window !== 'undefined') {
184
+ window.registerTranslation = registerTranslation;
185
+ }
118
186
  /**
119
187
  * Localize Reactive Controller for components built with Lit
120
188
  *
@@ -409,6 +477,26 @@ class BaseComponent extends LitElement {
409
477
  // generate internal _id
410
478
  const prefix = this.id?.length > 0 ? this.id : this.tagName.toLowerCase();
411
479
  this._id = this.generateId(prefix);
480
+ this.ariaAttributesObserver = new MutationObserver((mutations) => {
481
+ const shouldUpdate = mutations.some((mutation) => {
482
+ if (mutation.type !== 'attributes' || !mutation.attributeName) {
483
+ return false;
484
+ }
485
+ return mutation.attributeName === 'it-role' || mutation.attributeName.startsWith('it-aria-');
486
+ });
487
+ if (shouldUpdate) {
488
+ this.requestUpdate();
489
+ }
490
+ });
491
+ this.ariaAttributesObserver.observe(this, {
492
+ attributes: true,
493
+ attributeOldValue: true,
494
+ });
495
+ }
496
+ disconnectedCallback() {
497
+ this.ariaAttributesObserver?.disconnect();
498
+ this.ariaAttributesObserver = undefined;
499
+ super.disconnectedCallback();
412
500
  }
413
501
  }
414
502
  const BaseLocalizedComponent = LocalizeMixin(BaseComponent);
@@ -841,7 +929,7 @@ class FormControl extends BaseLocalizedComponent {
841
929
  });
842
930
  // TODO: verificare se serve davvero con il fatto che usiamo form-controller
843
931
  // static formAssociated = true;
844
- // @property()
932
+ // @property()
845
933
  // internals = this.attachInternals();
846
934
  this._touched = false;
847
935
  /** The name of the input, submitted as a name/value pair with form data. */
@@ -1085,28 +1173,121 @@ __decorate([
1085
1173
  __metadata("design:type", Object)
1086
1174
  ], FormControl.prototype, "validationMessage", void 0);
1087
1175
 
1176
+ /**
1177
+ * Dispatches a cancelable custom event and runs the provided default action
1178
+ * only if the consumer did not call `event.preventDefault()`.
1179
+ *
1180
+ * This is the shared convention used across components (Tabs, Modal, Chip, Alert,
1181
+ * Forward, Back) to provide a sensible default JavaScript behavior out of the box
1182
+ * while letting consumers intercept and override it. Notification deliberately does
1183
+ * NOT use this: its show/close are always caller-initiated (no default markup-driven
1184
+ * trigger to override), so there was no real use case for blocking them — see
1185
+ * it-notification.ts for the plain (non-cancelable) events it fires instead.
1186
+ *
1187
+ * ```js
1188
+ * el.addEventListener('it-alert-close', (e) => {
1189
+ * e.preventDefault(); // block the default removal
1190
+ * fetchConfirmation().then((ok) => { // async logic runs after prevention
1191
+ * if (ok) e.target.close();
1192
+ * });
1193
+ * });
1194
+ * ```
1195
+ *
1196
+ * Note: `preventDefault()` must be called synchronously inside the listener.
1197
+ * Async code can run afterward; call the component's public method when ready.
1198
+ *
1199
+ * @param host the element dispatching the event
1200
+ * @param name the event name (kebab-case, `it-` prefixed)
1201
+ * @param detail the event `detail` payload
1202
+ * @param defaultAction the behavior executed when the event is not prevented
1203
+ * @returns the dispatched event (inspect `defaultPrevented` if needed)
1204
+ */
1205
+ function dispatchCancelable(host, name, detail, defaultAction) {
1206
+ const event = new CustomEvent(name, {
1207
+ bubbles: true,
1208
+ composed: true,
1209
+ cancelable: true,
1210
+ detail,
1211
+ });
1212
+ host.dispatchEvent(event);
1213
+ if (!event.defaultPrevented) {
1214
+ defaultAction();
1215
+ }
1216
+ return event;
1217
+ }
1218
+
1219
+ /**
1220
+ * Returns the nearest focusable ancestor of `el` by walking up parentElement.
1221
+ * Used as the last-resort fallback when a self-removing component (chip, alert)
1222
+ * has no adjacent sibling of the same type to shift focus to.
1223
+ *
1224
+ * "Focusable ancestor" means an element with tabindex >= 0. The container that
1225
+ * wraps a chip group or alert list is the expected target; authors following the
1226
+ * WAI-ARIA pattern should give it tabindex="0".
1227
+ */
1228
+ function focusableFallbackAncestor(el) {
1229
+ let current = el.parentElement;
1230
+ while (current) {
1231
+ const tab = current.getAttribute('tabindex');
1232
+ if (tab !== null && parseInt(tab, 10) >= 0)
1233
+ return current;
1234
+ current = current.parentElement;
1235
+ }
1236
+ return null;
1237
+ }
1238
+ /** Mirrors FocusTrapController's notion of "focusable", scoped to the handful of
1239
+ * interactive elements consumers actually place next to alert/chip/notification. */
1240
+ const FOCUSABLE_SELECTORS = [
1241
+ 'a[href]',
1242
+ 'button:not([disabled])',
1243
+ 'input:not([disabled]):not([type="hidden"])',
1244
+ 'select:not([disabled])',
1245
+ 'textarea:not([disabled])',
1246
+ '[tabindex]:not([tabindex="-1"])',
1247
+ 'it-button:not([disabled])',
1248
+ ].join(',');
1249
+ /**
1250
+ * True last-resort fallback for when a self-removing component (alert, chip,
1251
+ * notification) has neither an adjacent sibling of the same type nor a
1252
+ * `focusableFallbackAncestor` (i.e. no author-provided `tabindex="0"` wrapper) —
1253
+ * the common case in practice, since most real usages don't add that wrapper.
1254
+ * Without this, focus silently drops to `<body>` with no way for a keyboard/AT
1255
+ * user to tell where they ended up.
1256
+ *
1257
+ * Finds the closest focusable element to `el` anywhere in the document, walking
1258
+ * outward in document order: the nearest one that comes before `el` (closer to
1259
+ * where the user's attention already was), falling back to the nearest one after.
1260
+ * This is a coarse, page-wide search — it may land focus on something not
1261
+ * visually adjacent — but it is deterministic and strictly better than silently
1262
+ * losing focus.
1263
+ */
1264
+ function nearestFocusableInDocument(el) {
1265
+ const candidates = Array.from(document.querySelectorAll(FOCUSABLE_SELECTORS)).filter((candidate) => candidate !== el && !el.contains(candidate));
1266
+ if (!candidates.length)
1267
+ return null;
1268
+ let closestBefore = null;
1269
+ let closestAfter = null;
1270
+ candidates.forEach((candidate) => {
1271
+ // eslint-disable-next-line no-bitwise
1272
+ if (el.compareDocumentPosition(candidate) & Node.DOCUMENT_POSITION_PRECEDING) {
1273
+ closestBefore = candidate; // querySelectorAll returns document order, so the last match wins
1274
+ }
1275
+ else if (!closestAfter) {
1276
+ closestAfter = candidate; // first match after `el` in document order
1277
+ }
1278
+ });
1279
+ return closestBefore ?? closestAfter;
1280
+ }
1281
+
1088
1282
  if (typeof window !== 'undefined') {
1089
1283
  window._itAnalytics = window._itAnalytics || {};
1090
1284
  window._itAnalytics = {
1091
1285
  ...window._itAnalytics,
1092
- version: '1.0.0-alpha.9',
1286
+ version: '1.0.0-beta.1',
1093
1287
  };
1094
1288
  }
1095
1289
 
1096
- var styles = css`/***************************** 1 ****************************************/
1097
- /***************************** 2 ****************************************/
1098
- /***************************** 1 ****************************************/
1099
- /***************************** 2 ****************************************/
1100
- /***************************** 1 ****************************************/
1101
- /***************************** 2 ****************************************/
1102
- /***************************** 3 ****************************************/
1103
- /***************************** 1 ****************************************/
1104
- /***************************** 2 ****************************************/
1105
- /***************************** 3 ****************************************/
1106
- /***************************** NEUTRAL 1 ****************************************/
1107
- /***************************** NEUTRAL 2 ****************************************/
1108
- /***************************** NEUTRAL 2 / 3 ****************************************/
1109
- .visually-hidden,
1290
+ var styles = css`.visually-hidden,
1110
1291
  .visually-hidden-focusable:not(:focus):not(:focus-within) {
1111
1292
  position: absolute !important;
1112
1293
  width: 1px !important;
@@ -1301,7 +1482,17 @@ a.chip:hover:not(.chip-disabled).chip-warning {
1301
1482
  --bsi-chip-icon-color: var(--bsi-chip-text-color);
1302
1483
  }`;
1303
1484
 
1304
- let ItChip = class ItChip extends BaseComponent {
1485
+ var ItChip_1;
1486
+ /**
1487
+ * Componente Chip.
1488
+ *
1489
+ * @element it-chip
1490
+ *
1491
+ * @slot dismiss-button - Pulsante di rimozione (richiesto quando `dismissable`)
1492
+ *
1493
+ * @fires it-chip-close - Quando si clicca il pulsante di rimozione (cancelable: `preventDefault()` impedisce la rimozione)
1494
+ */
1495
+ let ItChip = ItChip_1 = class ItChip extends BaseComponent {
1305
1496
  constructor() {
1306
1497
  super(...arguments);
1307
1498
  this.dismissable = false;
@@ -1312,6 +1503,17 @@ let ItChip = class ItChip extends BaseComponent {
1312
1503
  this.href = '';
1313
1504
  this.a11yDescription = '';
1314
1505
  this.isDisabled = false;
1506
+ this._onHostClick = (event) => {
1507
+ if (!this.dismissable)
1508
+ return;
1509
+ const buttons = this.closeButton;
1510
+ if (!buttons?.length)
1511
+ return;
1512
+ const path = event.composedPath();
1513
+ if (buttons.some((btn) => path.includes(btn))) {
1514
+ this._requestClose();
1515
+ }
1516
+ };
1315
1517
  }
1316
1518
  getAvatarSize() {
1317
1519
  // Per chip lg usa avatar sm, per gli altri usa avatar xs
@@ -1355,6 +1557,62 @@ let ItChip = class ItChip extends BaseComponent {
1355
1557
  }
1356
1558
  this.updateIcon();
1357
1559
  }
1560
+ connectedCallback() {
1561
+ super.connectedCallback?.();
1562
+ // Clicks on the slotted dismiss button bubble through the host (light DOM child),
1563
+ // so a single host-level listener covers it without re-binding on every render.
1564
+ this.addEventListener('click', this._onHostClick);
1565
+ }
1566
+ disconnectedCallback() {
1567
+ this.removeEventListener('click', this._onHostClick);
1568
+ super.disconnectedCallback?.();
1569
+ }
1570
+ _requestClose() {
1571
+ dispatchCancelable(this, 'it-chip-close', { chip: this }, () => this._removeWithFocusShift());
1572
+ }
1573
+ /**
1574
+ * Rimuove la chip dal DOM spostando il focus su una chip adiacente, se presente.
1575
+ * Utile dopo aver intercettato `it-chip-close` con `preventDefault()`.
1576
+ */
1577
+ close() {
1578
+ this._removeWithFocusShift();
1579
+ }
1580
+ _removeWithFocusShift() {
1581
+ const adjacent = this._adjacentChip();
1582
+ // No adjacent chip of the same type: fall back to a tabindex-bearing ancestor,
1583
+ // and if the author didn't provide one (the common case), to the nearest
1584
+ // focusable element anywhere in the document — better than losing focus to <body>.
1585
+ const fallback = !adjacent ? (focusableFallbackAncestor(this) ?? nearestFocusableInDocument(this)) : null;
1586
+ this.remove();
1587
+ if (adjacent)
1588
+ ItChip_1._focusChip(adjacent);
1589
+ else
1590
+ fallback?.focus();
1591
+ }
1592
+ _adjacentChip() {
1593
+ // Only a dismissable neighbor is an equivalent "next item to remove" — shifting
1594
+ // focus onto a plain label or link chip just because it's spatially adjacent
1595
+ // would steal focus onto an unrelated control the user never asked to interact with.
1596
+ const isDismissableChip = (el) => !!el && el.tagName.toLowerCase() === 'it-chip' && el.hasAttribute('dismissable');
1597
+ let el = this.nextElementSibling;
1598
+ while (el && !isDismissableChip(el))
1599
+ el = el.nextElementSibling;
1600
+ if (isDismissableChip(el))
1601
+ return el;
1602
+ el = this.previousElementSibling;
1603
+ while (el && !isDismissableChip(el))
1604
+ el = el.previousElementSibling;
1605
+ return isDismissableChip(el) ? el : null;
1606
+ }
1607
+ static _focusChip(chip) {
1608
+ const btn = chip.closeButton?.[0];
1609
+ if (btn) {
1610
+ btn.focus();
1611
+ return;
1612
+ }
1613
+ const link = chip.shadowRoot?.querySelector('a');
1614
+ link?.focus();
1615
+ }
1358
1616
  render() {
1359
1617
  const avatarSize = this.getAvatarSize();
1360
1618
  const avatarHeights = {
@@ -1438,7 +1696,7 @@ __decorate([
1438
1696
  queryAssignedElements({ slot: 'icon', flatten: true }),
1439
1697
  __metadata("design:type", Array)
1440
1698
  ], ItChip.prototype, "icon", void 0);
1441
- ItChip = __decorate([
1699
+ ItChip = ItChip_1 = __decorate([
1442
1700
  customElement('it-chip')
1443
1701
  ], ItChip);
1444
1702