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

81.7% Statements 67/82
88% Branches 22/25
80% Functions 28/35
81.7% Lines 67/82

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 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401              14x 14x 14x 14x 14x                             14x                               14x 2x 2x               14x 24x               14x   14x               14x 16x         14x             13x 13x                 1x           14x 10x             14x 14x 13x   14x 1x 1x 1x               14x 11x 11x         14x       13x 13x                                                             26x                                                           13x         89x     14x                               15x 13x   15x         13x               13x         13x     13x             2x                   13x             13x     245x                       39x     13x                 38x     13x                 24x     13x                         2x                       15x 15x 15x                             1x                                           45x     23x                 13x     15x 15x     13x       1x      
import { LightningElement, api } from 'lwc';
import {
  autoResize,
  createControlAndTargetContract,
  handleSlotChangeWithState,
  normalizeBoolean,
  getOverflowContainer,
  closePopover,
  openPopover,
  togglePopover,
  normalizeInput,
  oneOf,
} from 'sds/utils';
import 'sds/privateThemeProvider';
 
export default class DropdownManager extends LightningElement {
  static shadowSupportMode = 'native';
 
  _container;
  _trigger;
  _slottedChildren;
  _ariaHasPopup;
 
  /**
   * The popover is powered by this object. The object standardizes the
   * popover interface which allows us to interact with our libraries to
   * assemble and update the popover.
   *
   * @type {Object}
   * @property {LightningElement} component - the component instance
   * @property {HTMLElement} control - the control element that triggers the target
   * @property {HTMLElement} target - the target element to be positioned by the control
   * @property {String} placement - the placement of the target relative to the control
   * @property {Number} offset - the offset amount of the target from the control
   * @property {Boolean} autoResize - if true, the target will resize to fit the control
   * @property {Function} observeResize - a function that cleans up the observer
   */
  _popover = {
    component: this,
    control: null,
    target: null,
    placement: 'block-start',
    offset: null,
    autoResize: false,
    observeResize: null,
  };
 
  /**
   * Get all slotted children.
   *
   * @returns {Array}
   */
  get slotChildren() {
    return this._slottedChildren;
  }
  set slotChildren(value) {
    if (!Array.isArray(value)) {
      console.warn(`slotChildren must be an array. Received ${typeof value}.`);
      return;
    }
    this._slottedChildren = value;
  }
 
  get popover() {
    return this._popover;
  }
  set popover(value) {
    this._popover[value] = value;
  }
 
  /**
   * Get the control element that triggers the target.
   *
   * @returns {HTMLElement}
   */
  get control() {
    return this.popover.control;
  }
  set control(value) {
    this.popover.control = value;
  }
 
  /**
   * Get the target element to be positioned by the control.
   *
   * @Ireturns {HTMLElement}
   */
  get target() {
    return this.popover.target;
  }
  set target(value) {
    this.popover.target = value;
  }
 
  /**
   * Get the closest containing element with overflow or default to the viewport.
   *
   * @returns {HTMLElement}
   */
  get container() {
    return this._container;
  }
  set container(value) {
    this._container = value;
  }
 
  /**
   * Sets the placement of the target relative to the control. Placement
   * validation checked in position library.
   *
   * @returns {String}
   */
  @api
  get placement() {
    return this.popover.placement;
  }
  set placement(value) {
    this.popover.placement = value;
  }
 
  /**
   * Sets the offset amount of the target from the control.
   *
   * @returns {Number}
   */
  @api
  get offset() {
    return this.popover.offset;
  }
  set offset(value) {
    const numberValue = Number(value);
    if (typeof numberValue === 'number') {
      this.popover.offset = numberValue;
    } else {
      console.warn(`offset must be a valid number. Received ${value}.`);
    }
  }
 
  /**
   * If true, the target will resize to fit the control.
   *
   * @returns {Boolean}
   */
  @api
  get autoResize() {
    return this.popover.autoResize;
  }
  set autoResize(value) {
    this.popover.autoResize = normalizeBoolean(value);
  }
 
  /**
   * Sets the ariaHasPopup value
   *
   * @returns {String} Enum
   */
  @api
  get ariaHasPopup() {
    return this._ariaHasPopup;
  }
  set ariaHasPopup(value) {
    this._ariaHasPopup = normalizeInput(value);
 
    oneOf(this._ariaHasPopup, ['dialog', 'menu', 'listbox', 'tree', 'grid']);
  }
 
  /**
   * Observe resizing of the target and reposition the target when it does.
   *
   * @returns {Function} - a function that cleans up the observer
   */
  get observeResize() {
    return this.popover.observeResize;
  }
  set observeResize(value) {
    this.popover.observeResize = value;
  }
 
  /**
   * The trigger type for the target. Valid values are 'click' and 'hover'.
   *
   * @returns {String} - the trigger type
   */
  @api
  get trigger() {
    return this._trigger;
  }
  set trigger(value) {
    const validValues = ['click', 'hover'];
    if (
      validValues.includes(value)
        ? (this._trigger = value)
        : console.warn(`Trigger must be one of ${validValues}. Received ${value}.`)
    );
  }
 
  /**
   * Open the target. Method of opening depends on the brower's support for
   * the popover API. setSize() must be called before openPopover() so that
   * the updated rendered layout is available for positioning.
   *
   * @public
   */
  @api
  open = () => {
    this.setSize();
    openPopover(this.popover);
  };
 
  /**
   * Close the target. Method of closing depends on the brower's support
   * for the popover API.
   *
   * @public
   */
  @api
  close = () => {
    closePopover(this.popover);
  };
 
  /**
   * Toggle the target between open and closed states. Method of toggling
   * depends on the brower's support for the popover API.
   *
   * @public
   */
  @api
  toggleOpenClose = () => {
    this.setSize();
    togglePopover(this.popover);
  };
 
  /**
   * Sets the size of the target. Currently used for autoResize exclusively but
   * expandable to other sizing use cases.
   *
   * @public
   */
  @api
  setSize = () => {
    autoResize(this.popover);
  }E;
 
  /**
   * Sets Iany required attributes not covered by other areas.
   */
  setAttributes = () => {
    /**
     * We need to manually set the popover attribute to precisely control
     * the position and dimensions. Also, we set the attribute and not the
     * property because browser's that don't support the popover API won't
     * reflect the attribute.
     */
    this.target.setAttribute('popover', 'manual');
 
    if (this._ariaHasPopup) {
      this.control.setAttribute('aria-haspopup', this._ariaHasPopup);
    }
  };
 
  /**
   * Event handler for the open event. Opens the target if it's closed.
   * This is primarily an abstraction for the event listener.
   */
  handleOpenEvent = () => {
    this.open();
  };
 
  /**
   * Event handler for the close event. Closes the target if it's open.
   * This is primarily an abstraction for the event listener.
   */
  handleCloseEvent = () => {
    this.close();
  };
 
  /**
   * Event handler for keydown events, closes the target if the escape key is pressed.
   *
   * @param {Event} e
   */
  handleKeydownEvent = (e) => {
    if (e.key === 'Escape') {
      this.close();
    }
    if (e.key === 'Enter' || e.key === ' ') {
      e.stopPropagation();
      e.preventDefault();
      this.toggleOpenClose();
    }
  };
 
  /**
   * Event handler for toggling the target between open and closed states.
   *
   * @param {Event} e - event object
   */
  handleToggleEvent = (e) => {
    e.stopPropagation();
    this.toggleOpenClose();
  };
 
  /**
   * Bespoke setup details for the component. Typically runs after a slot change.
   */
  setup = () => {
    /**
     * We find our container and wire up the attributes.
     */
    this.container = getOverflowContainer(this.template.host);
    this.setAttributes();
  };
 
  /**
   * Event Listeners
   *
   * Wire up our interactions. These are called within the slot change
   * handler depending on the render state.
   *
   * @TODO: Make hover logic smarter so we can introduce offset.
   */
  getHoverEventListeners = () => [
    { target: document, type: 'keydown', handler: this.handleKeydownEvent },
    { target: this, type: 'mouseover', handler: this.handleOpenEvent },
    { target: this, type: 'mouseout', handler: this.handleCloseEvent },
    { target: this.control, type: 'focus', handler: this.handleOpenEvent },
    { target: this.control, type: 'blur', handler: this.handleCloseEvent },
  ];
 
  getClickEventListeners = () => [
    { target: document, type: 'keydown', handler: this.handleKeydownEvent },
    { target: this.container, type: 'scroll', handler: this.handleCloseEvent },
    { target: this.container, type: 'click', handler: this.handleCloseEvent },
    { target: this.control, type: 'click', handler: this.handleToggleEvent },
    { target: this.control, type: 'keydown', handler: this.handleKeydownEvent },
    { target: this.target, type: 'click', handler: (e) => e.stopPropagation() },
    { target: this, type: 'close', handler: this.handleCloseEvent },
  ];
 
  getEventType(type) {
    return type === 'click' ? this.getClickEventListeners() : this.getHoverEventListeners();
  }
 
  attachEventListeners = () => {
    this.getEventType(this.trigger).forEach(({ target, type, handler }) => {
      target.addEventListener(type, handler);
    });
  };
 
  destroyEventListeners = () => {
    this.getEventType(this.trigger).forEach(({ target, type, handler }) => {
      target.removeEventListener(type, handler);
    });
  };
 
  /**
   * Slot Change Handler /w State
   *
   * This is the main entry point for the component since this manager is entirely
   * reliant on slot content. It's called whenever the slot changes.
   */
  handleSlotChange = handleSlotChangeWithState((state) => {
    if (state.changed) {
      this.slotChildren = state.newContent;
    }
 
    if (state.changed && !state.empty) {
      /**
       * If we have slot children, we can automatically create the control and
       * target contract and get to work below.
       */
      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();
 
          /**
           * Manage our event listeners depending on the render state.
           */
          if (state.firstRender) {
            this.attachEventListeners();
          }
          if (!state.firstRender) {
            this.destroyEventListeners();
            this.attachEventListeners();
          }
        },
      });
    } 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.',
      );
    }
  });
}