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

73.77% Statements 45/61
75% Branches 12/16
60.86% Functions 14/23
73.77% Lines 45/61

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              9x 9x 9x                             9x                                                   9x                             9x             16x 16x 16x           9x             9x               9x               9x       16x 16x                                                         9x 16x         80x     9x           40x                   22x 18x   22x         18x                 16x         16x 8x   16x 8x 8x                         18x     18x       18x     246x                       130x     18x                 64x     18x                       16x                         5x                 2x     9x 9x 9x                                                             2x                
import { LightningElement, api } from 'lwc';
import {
  autoResize,
  createControlAndTargetContract,
  validateControlType,
  validateIsButtonType,
  handleSlotChangeWithState,
  normalizeBoolean,
  getOverflowContainer,
  closePopover,
  openPopover,
} from 'sds/utils';
import 'sds/privateThemeProvider';
 
export default class TooltipManager extends LightningElement {
  static shadowSupportMode = 'native';
 
  _container;
  _slottedChildren;
 
  /**
   * 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.
   *
   * @returns {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);
  }
 
  /**
   * 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;
  }
 
  /**
   * 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);
  };
 
  /**
   * Sets the size of the target. Currently used for autoResize exclusively but
   * expandable to other sizing use cases.
   *
   * @public
   */
  @api
  setSize = () => {
    autoResize(this.popover);
  };
 
  /**
   * Sets any 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.
     */
    Ithis.target.setAttribute('popover', 'manual');
 
    this.control.setAttribute('aria-describedby', this.target.id);
    this.target.setAttribute('role', 'tooltip');
  };
 
  /**
   * 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();
    }
  };
 
  /**
   * 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.
   */
  getEventListeners = () => [
    { target: document, type: 'keydown', handler: this.handleKeydownEvent },
    { target: this.control, type: 'mouseover', handler: this.handleOpenEvent },
    { target: this.control, type: 'mouseout', handler: this.handleCloseEvent },
    { target: this.control, type: 'focus', handler: this.handleOpenEvent },
    { target: this.control, type: 'blur', handler: this.handleCloseEvent },
  ];
 
  attachEventListeners = () => {
    this.getEventListeners().forEach(({ target, type, handler }) => {
      target.addEventListener(type, handler);
    });
  };
 
  destroyEventListeners = () => {
    this.getEventListeners().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
   * Ereliant 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,
        validation: validateControlType([validateIsButtonType]),
        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();
          }
        },
      });
    }
  });
}