All files / packages/sds-components/src/sds/comboboxManager comboboxManager.js

68.06% Statements 81/119
47.5% Branches 19/40
82.14% Functions 23/28
68.06% Lines 81/119

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331              7x 7x   7x 7x   7x 7x 7x 7x 7x 7x     7x               7x 7x     7x   6x       1x       7x                           7x     7x       7x           1x   1x           11x     2x           4x           5x     7x                       7x         7x                     7x                   7x         7x         7x     7x                                                                               7x 7x   7x 7x 7x 5x   2x     4x       5x 5x 5x             3x 3x           7x 7x 4x 4x   7x 1x 1x 1x       2x   4x           6x 6x 3x 3x 3x       6x         1x 2x     2x 2x 2x     2x 14x   2x     2x 2x                         7x 7x   6x 6x   1x 1x             2x 2x                                                                      
import { LightningElement, api } from 'lwc';
import {
  createControlAndTargetContract,
  handleSlotChangeWithState,
  normalizeBoolean,
  normalizeInput,
  oneOf,
} from 'sds/utils';
import 'sds/privateThemeProvider';
 
export default class ComboboxManager extends LightningElement {
  static shadowSupportMode = 'native';
 
  _valid = true;
  _slottedChildren;
  _selectMode = 'single';
  _ariaActivedescendant = '';
  E_autocomplete = false;
  _readonly = false;
  _value;
 
  /**
   * Get all slotted children.
   *
   * @returns {Array}
   */
  get slotChildren() {
    return this._slottedChildren;
  }
  set slotChildren(value) {
    if (!IArray.isArray(value)) {
      console.warn(`slotChildren must be an array. Received ${typeof value}.`);
      return;
    }
    this._slottedChildren = value;
  }
 
  @api id = 'combobox-id';
 
  @api
  get selectMode() {
    return this._selectMode;
  }
  set selectMode(value) {
    this._selectMode = normalizeInput(value);
    if (this._selectMode === 'multiple') {
      consoleI.error('Multiple select mode is not yet supported.');
    } else {
      oneOf(this._selectMode, ['single']);
    }
  }
 
  @api
  get autocomplete() {
    return this._autocomplete;
  }
  set autocomplete(value) {
    this._autocomplete = normalizeBoolean(value);
  }
 
  @Iapi
  get readOnly() {
    return this._readonly;
  }
  set readOnly(value) {
    this._readonly = normalizeBoolean(value);
  }
 
  @api
  get value() {
    return this._value;
  }
  set value(value) {
    this._value = normalizeInput(value);
  }
 
  connectedCallback() {
    this.handleRequiredAttributes();
  }
 
  /**
   * Event handler for keydown events on the listbox.
   * @param {KeyboardEvent} event
   */
  handleKeyDown(e) {
    this.target.handleListboxKeyboardNavigation?.(e);
    this.handleValidActiveDescendant();
  }
 
  handleRequiredAttributes() {
    switch (true) {
      case !this.selectMode:
        this._valid = false;
        console.error('A combobox type is required. Required options are: single, multiple.');
      default:
        this._valid = true;
    }
  }
 
  /**
   * Validates the role of the target element.
   *
   * @param {string} expectedRole - The expected role for the target element.
   * @return {void} No return value.
   */
  handleValidRole(expectedRole) {
    if (!this.target) {
      console.error(`A ${expectedRole} is required.`);
      this._valid = false;
      return;
    }
 
    if (this.target.role !== expectedRole) {
      console.error(`The target must have a role of ${expectedRole}.`);
      this._valid = false;
      return;
    }
 
    if (!this.target.id) {
      console.error(`The ${expectedRole} must have an id.`);
      this._valid = false;
      return;
    }
 
    Iif (this.target.id !== this.control.getAttribute('aria-controls')) {
      console.error(`The ${expectedRole} id must match the combobox aria-controls.`);
      this._valid = false;
      return;
    }
 
    this._valid = true;
  }
 
  handleValidCombobox() {
    Iif (!this.control) {
      console.error(`A combobox is required. Please specific aria-controls="id-of-listbox" on the combobox.`);
      this._valid = false;
      return;
    }
  I}
 
  /**
   * Validates the active descendant of the combobox based on its role.
   *
   * @return {void}
   */
  handleValidActiveDescendant() {
    Iconst roleValidators = {
      listbox: (target) => {
        if (!target.ariaActiveDescendant) {
          console.error('The listbox must have an aria-activedescendant.');
          return false;
        }
        return true;
      },
      grid: () => {
        // No aria-activedescendant check needed for grid type
        return true;
      },
      // More types will be added in the future
    };
 
    const roleValidator = roleValidators[this.target.role];
    if (roleValidator) {
      if (!roleValidator(this.target)) {
        this._valid = false;
      }
    }
  }
 
  /**
   * Set the initial state of the combobox.
   * @param {HTMLElement} combobox
   */
  handleComboboxAriaRoles(combobox) {
    combobox.setAttribute('role', 'combobox');
    combobox.setAttribute('tabindex', '0');
    combobox.setAttribute('aria-expanded', 'false');
    combobox.setAttribute('aria-activedescendant', this._ariaActivedescendant);
    combobox.id = this.id;
    if (!this.autocomplete) {
      combobox.setAttribute('aria-autocomplete', 'none');
    } else {
      combobox.setAttribute('aria-autocomplete', 'list');
    }
    if (this._readonly) {
      combobox.readOnly = true;
    }
  }
 
  setComboboxValue(value) {
    if ('value' in this.control) {
      this.control.value = value;
      this.value = value;
    } else {
      this.control.textContent = value;
      this.value = value;
    }
  }
 
  setActiveDescendent() {
    if (this.target.ariaActiveDescendant) {
      this.control.setAttribute('aria-activedescendant', this.target.ariaActiveDescendant);
    } else {
      this.control.setAttribute('aria-activedescendant', '');
    E}
  }
 
  handleComboboxUpgrade() {
    this.handleComboboxAriaRoles(this.control);
    this.control.addEventListener('focus', () => {
      this.control.setAttribute('aria-expanded', 'true');
      this.control.setAttribute('focus', '');
    })E;
    this.control.addEventListener('blur', () => {
      this.control.setAttribute('aria-expanded', 'false');
      this.control.removeAttribute('focus');
      this.target.clearFocused?.();
    });
    this.control.addEventListener('input', () => {
      if (this.autocomplete) {
        this.target.filterListbox?.(this.control.value);
      }
      if (this.control.value === '') {
        this.target.clearSelected?.();
      }
    });
  }
 
  handleListboxUpgrade() {
    this.target.tabIndex = '-1';
 
    Ithis.target.addEventListener('selectionchange', (e) => {
      if (e.detail === 'sds-listbox-manager') {
        this.setActiveDescendent();
        this.control.focus();
        this.setComboboxValue(this.target.value);
      }
    });
    this.target.addEventListener('click', () => {
      Ethis.control.focus();
    });
  }
 
  handleGridUpgrade() {
    this.target.addEventListener('click', (e) => {
      this.control.focus();
 
      // Find the closest 'data-value' ancestor of the clicked element (including itself)
      const clickedElement = e.target.closest('[data-value]');
 
      if (clickedElement) {
        const selectableItems = this.target.querySelectorAll('[data-value]');
 
        // Update aria-selected
        selectableItems.forEach((item) => {
      E    item.setAttribute('aria-selected', 'false');
        });
        clickedElement.setAttribute('aria-selected', 'true');
 
        // Retrieve the value from the clicked item
        const value = clickedElement.dataset.value;
        if (value) {
          this.setComboboxValue(value);
        }
      }
    });
  E}
 
  /**
   * Handles the setup of the combobox based on the target role.
   * Currently only supports listbox and grid.
   * Error handling for target is taken care of separately.
   */
  setup() {
    this.handleValidCombobox();
 
    switch (this.target.role) {
      case 'listbox':
        this.handleValidRole('listbox');
        break;
      case 'grid':
        this.handleValidRole('grid');
        break;
      default:
        console.error(`Unsupported role: ${this.target.role}, supported roles: listbox, grid`);
    }
  }
 
  handleSlotChange = handleSlotChangeWithState((state) => {
    if (state.changed) {
      this.slotChildren = state.newContent;
    }
 
    if (state.changed && !state.empty) {
      createControlAndTargetContract({
        element: this,
        content: this.slotChildren,
        callback: () => {
          /**
           * All the heavy lifting is done at this point, now we just need to
           * do a little minor setup unique to the component.
           */
          this.setup();
 
          if (!this._valid) {
            return;
          }
 
          switch (this.target.role) {
            case 'listbox':
              this.handleListboxUpgrade();
              break;
            case 'grid':
              this.handleGridUpgrade();
              break;
            default:
              console.error(`Unsupported role: ${this.target.role}, supported roles: listbox, grid`);
          }
 
          this.handleComboboxUpgrade();
        },
      });
    } else {
      console.error(
        'No slot children found. Please add an element with an ID and a button or input with the aria-controls attribute set to the ID.',
      );
    }
  });
}