All files / src/list TembaList.ts

60.74% Statements 311/512
75% Branches 45/60
72% Functions 18/25
60.74% Lines 311/512

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 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 51392x 95x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 52x 92x 92x 184x 177x 177x 177x 177x 177x 177x 177x 177x 92x 12x 12x 92x 52x 52x 52x 52x 52x 52x           92x 52x 92x 102x 102x 102x 102x 102x 65x 65x 65x 65x 65x 65x 65x 102x 102x 11x 11x 92x 102x 102x 102x 11x 11x 11x 102x 102x 102x 102x 67x 56x 67x 102x 52x 52x 102x 102x 102x 10x 10x 10x 10x 10x 10x 102x 66x 66x 66x 102x 102x 69x 69x 92x 92x 92x 92x 92x 92x 5x 5x 5x 92x                   92x                     92x     92x                               92x 92x 92x             92x     1x 1x 1x 1x 1x 92x 10x 10x 92x 92x 92x 92x 92x 45x 45x 45x 45x 45x 45x 45x                                                                                                                                                             45x 92x 11x 11x 11x 11x     11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 10x 10x 10x 10x 11x       10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 11x 1x 1x 11x 10x 10x 10x 10x 10x 10x 10x 10x 10x     11x 10x 10x 11x                                                       10x 10x 10x 10x           10x 10x 10x 11x   11x     10x             92x 17x                                                     92x 13x 92x 13x 92x 92x 92x 92x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x 92x  
import { css, html, PropertyValues, TemplateResult } from 'lit';
import { property } from 'lit/decorators.js';
import { CustomEventType } from '../interfaces';
import { RapidElement } from '../RapidElement';
import { Store } from '../store/Store';
import { fetchResultsPage, ResultsPage } from '../utils';
 
const DEFAULT_REFRESH = 10000;
 
export class TembaList extends RapidElement {
  @property({ type: Array, attribute: false })
  items: any[] = [];
 
  @property({ type: Object, attribute: false })
  selected: any;
 
  @property({ type: Number })
  cursorIndex = -1;
 
  @property({ type: String })
  endpoint: string;
 
  @property({ type: String })
  nextSelection: any;
 
  @property({ type: Number })
  tabIndex = 1;
 
  @property({ type: String })
  valueKey = 'id';
 
  @property({ type: String })
  value: string;
 
  @property({ type: Boolean })
  loading = false;
 
  @property({ type: Boolean })
  collapsed: boolean;
 
  @property({ type: Boolean })
  hideShadow: boolean;
 
  @property({ type: Boolean })
  paused = false;
 
  @property({ type: Boolean })
  internalFocusDisabled = false;
 
  @property({ attribute: false })
  getNextRefresh: (firstOption: any) => any;
 
  @property({ attribute: false })
  sanitizeOption: (option: any) => any;
 
  @property({ attribute: false })
  renderOption: (option: any, selected: boolean) => TemplateResult;
 
  @property({ attribute: false })
  renderOptionDetail: (option: any, selected: boolean) => TemplateResult;
 
  @property({ attribute: false, type: Object })
  mostRecentItem: any;
 
  // changes to the refresh key force a refresh
  @property({ type: String })
  refreshKey = '0';
 
  reverseRefresh = true;
 
  // our next page from our endpoint
  nextPage: string = null;
 
  pages = 0;
  clearRefreshTimeout: any;
  pending: AbortController[] = [];
 
  store: Store;
 
  // used for testing only
  preserve: boolean;
 
  static get styles() {
    return css`
      temba-options {
        display: block;
        width: 100%;
        flex-grow: 1;
      }
    `;
  }
 
  constructor() {
    super();
    this.store = document.querySelector('temba-store') as Store;
    this.handleSelection.bind(this);
  }
 
  private reset(): void {
    this.selected = null;
    this.nextPage = null;
    this.cursorIndex = -1;
    this.mostRecentItem = null;
    this.items = [];
  }
 
  refreshInterval = null;
 
  public connectedCallback() {
    super.connectedCallback();
    this.refreshInterval = setInterval(() => {
      if (!this.paused) {
        this.refreshKey = 'default_' + new Date().getTime();
      }
    }, DEFAULT_REFRESH);
  }
 
  public disconnectedCallback() {
    clearInterval(this.refreshInterval);
  }

  public willUpdate(changedProperties: PropertyValues): void {
    super.willUpdate(changedProperties);

    if (changedProperties.has('cursorIndex')) {
      if (this.cursorIndex > -1) {
        this.selected = this.items[this.cursorIndex];
      }
    }
 
    if (changedProperties.has('endpoint') && this.endpoint) {
      this.loading = true;
      this.reset();
    }
  }
 
  public updated(changedProperties: Map<string, any>) {
    super.updated(changedProperties);
 
    if (changedProperties.has('endpoint') && this.endpoint) {
      this.fetchItems();
    }
 
    if (changedProperties.has('loading')) {
      if (!this.loading) {
        this.fireCustomEvent(CustomEventType.FetchComplete);
      }
    }
 
    if (
      changedProperties.has('refreshKey') &&
      !changedProperties.has('endpoint')
    ) {
      this.refreshTop();
    }
 
    if (changedProperties.has('mostRecentItem') && this.mostRecentItem) {
      this.fireCustomEvent(CustomEventType.Refreshed);
    }
 
    if (changedProperties.has('cursorIndex')) {
      if (this.cursorIndex > -1) {
        this.handleSelected(this.selected);
      }
    }
 
    if (changedProperties.has('items')) {
      //
    }
  }
 
  // eslint-disable-next-line @typescript-eslint/no-unused-vars
  public handleSelected(selected: any) {
    const evt = new Event('change', { bubbles: true });
    this.dispatchEvent(evt);
  }
 
  private getValue(obj: any): any {
    if (!obj) {
      return null;
    }
 
    const path = this.valueKey.split('.');
    let current = obj;
    while (path.length > 0) {
      const key = path.shift();
      current = current[key];
    }
    return current;
  }

  public setSelection(value: string) {
    const index = this.items.findIndex((item) => {
      return this.getValue(item) === value;
    });
    this.cursorIndex = index;
    this.selected = this.items[index];
    const evt = new Event('change', { bubbles: true });
    this.dispatchEvent(evt);
  }

  public getItemIndex(value: string) {
    return this.items.findIndex((option) => this.getValue(option) === value);
  }

  public removeItem(value: string) {
    const index = this.getItemIndex(value);
    this.items.splice(index, 1);
    this.items = [...this.items];
    if (this.cursorIndex === index) {
      this.cursorIndex = -1;
    }

    // request a change even if it is the same, the item is different
    this.requestUpdate('cursorIndex');
    this.requestUpdate('items');
  }

  public getSelection(): any {
    return this.selected;
  }

  public refresh(): void {
    this.refreshKey = 'requested_' + new Date().getTime();
  }

  public setEndpoint(endpoint: string, nextSelection: any = null) {
    this.endpoint = endpoint;
    this.nextSelection = nextSelection;
  }

  public getRefreshEndpoint() {
    return this.endpoint;
  }

  protected sanitizeResults(results: any[]): Promise<any[]> {
    return Promise.resolve(results);
  }
 
  /**
   * Refreshes the first page, updating any found items in our list
   */
  private async refreshTop(): Promise<void> {
    const refreshEndpoint = this.getRefreshEndpoint();
    if (!refreshEndpoint) {
      return;
    }
 
    // cancel any outstanding requests
    while (this.pending.length > 0) {
      const pending = this.pending.pop();
      pending.abort();
    }
 
    const controller = new AbortController();
    this.pending.push(controller);
 
    const prevItem = this.items[this.cursorIndex];

    try {
      const page = await fetchResultsPage(
        this.getRefreshEndpoint(),
        controller
      );

      const sanitizedResults = await this.sanitizeResults(page.results);
      const items = [...this.items];

      // remove any dupes already in our list
      if (sanitizedResults) {
        sanitizedResults.forEach((newOption: any) => {
          if (this.sanitizeOption) {
            this.sanitizeOption(newOption);
          }
          const newValue = this.getValue(newOption);
          const removeIndex = items.findIndex(
            (option) => this.getValue(option) === newValue
          );

          if (removeIndex > -1) {
            items.splice(removeIndex, 1);
          }
        });

        // insert our new items at the front
        let results = sanitizedResults;
        if (this.reverseRefresh) {
          results = sanitizedResults.reverse();
        }
        const newItems = [...results, ...items];

        const topItem = newItems[0];
        if (
          !this.mostRecentItem ||
          JSON.stringify(this.mostRecentItem) !== JSON.stringify(topItem)
        ) {
          this.mostRecentItem = topItem;
        }

        if (prevItem) {
          const newItem = newItems[this.cursorIndex];
          const prevValue = this.getValue(prevItem);
          if (prevValue !== this.getValue(newItem)) {
            const newIndex = newItems.findIndex(
              (option) => this.getValue(option) === prevValue
            );
            this.cursorIndex = newIndex;

            // make sure our focused item is visible
            window.setTimeout(() => {
              const options = this.shadowRoot.querySelector('temba-options');
              if (options) {
                const option =
                  options.shadowRoot.querySelector('.option.focused');
                if (option) {
                  option.scrollIntoView({ block: 'end', inline: 'nearest' });
                }
              }
            }, 0);
          }
        }

        this.items = newItems;
      }
    } catch (error) {
      this.paused = true;
    }
  }

  private async fetchItems(): Promise<void> {
    // cancel any outstanding requests
    while (this.pending.length > 0) {
      const pending = this.pending.pop();
      pending.abort();
    }

    let endpoint = this.endpoint;
    let pagesToFetch = this.pages || 1;
    let pages = 0;
    let nextPage = null;
 
    let fetchedItems: any[] = [];

    while (pagesToFetch > 0 && endpoint) {
      const controller = new AbortController();
      this.pending.push(controller);
 
      try {
        const page = await fetchResultsPage(endpoint, controller);
        const sanitizedResults = await this.sanitizeResults(page.results);
 
        // sanitize our options if necessary
        if (this.sanitizeOption) {
          sanitizedResults.forEach(this.sanitizeOption);
        }
 
        if (sanitizedResults) {
          fetchedItems = fetchedItems.concat(sanitizedResults);
        }
 
        // save our next pages
        nextPage = page.next;
        endpoint = nextPage;
        pagesToFetch--;
        pages++;
      } catch (error) {
        // aborted
        this.reset();
        this.paused = true;
        this.loading = false;
        return;
      }
      this.nextPage = nextPage;
    }
    this.pages = pages;
 
    const topItem = fetchedItems[0];
    if (
      !this.mostRecentItem ||
      JSON.stringify(this.mostRecentItem) !== JSON.stringify(topItem)
    ) {
      this.mostRecentItem = topItem;
    }
 
    // see if our cursor needs to move to stay on the same item
    const newItem = fetchedItems[this.cursorIndex];
 
    if (
      !this.nextSelection &&
      this.selected &&
      newItem &&
      this.getValue(newItem) !== this.getValue(this.selected)
    ) {
      const index = fetchedItems.findIndex((item) => {
        return this.getValue(item) === this.getValue(this.selected);
      });

      // old selection is in the new fetch
      if (index > -1) {
        this.cursorIndex = index;
      }
      // old selection is missing from the new fetch
      else {
        // if our index didn't change, our item still did, fire change
        if (this.cursorIndex === 0) {
          this.requestUpdate('cursorIndex');
        }
        // otherwise select the first item
        else {
          this.cursorIndex = 0;
        }
      }
    }

    // save our results
    this.items = fetchedItems;
    this.loading = false;
    this.pending = [];

    if (this.nextSelection) {
      this.setSelection(this.nextSelection);
      this.nextSelection = false;
    } else {
      if (this.cursorIndex === -1 && !this.isMobile()) {
        this.cursorIndex = 0;
      }
    }

    if (this.value) {
      this.setSelection(this.value);
      this.value = null;
    } else if (this.isMobile() && !this.selected) {
      this.cursorIndex = -1;
      this.value = null;
      this.selected = null;
      const evt = new Event('change', { bubbles: true });
      this.dispatchEvent(evt);
    }

    return Promise.resolve();
  }

  private handleScrollThreshold() {
    if (this.nextPage && !this.loading) {
      this.loading = true;
      fetchResultsPage(this.nextPage).then((page: ResultsPage) => {
        this.sanitizeResults(page.results).then((sanitizedResults) => {
          if (this.sanitizeOption) {
            sanitizedResults.forEach(this.sanitizeOption);
          }

          this.items = [...this.items, ...sanitizedResults];
          this.nextPage = page.next;
          this.pages++;
          this.loading = false;
        });
      });
    }
  }

  public renderHeader(): TemplateResult {
    return null;
  }

  public renderFooter(): TemplateResult {
    return null;
  }

  public getListStyle() {
    return '';
  }

  protected handleSelection(event: CustomEvent) {
    let index = event.detail.index;
    const selected = event.detail.selected;
 
    if (index === -1) {
      index = 0;
    }
 
    this.selected = selected;
    this.cursorIndex = index;
 
    event.stopPropagation();
    event.preventDefault();
  }
 
  public render(): TemplateResult {
    return html`
      ${this.renderHeader()}
      <temba-options
        style="${this.getListStyle()}"
        visible
        block
        cursorSelection
        ?hideShadow=${this.hideShadow}
        ?collapsed=${this.collapsed}
        ?loading=${this.loading}
        ?internalFocusDisabled=${this.internalFocusDisabled}
        .renderOption=${this.renderOption}
        .renderOptionDetail=${this.renderOptionDetail}
        @temba-scroll-threshold=${this.handleScrollThreshold}
        @temba-selection=${this.handleSelection.bind(this)}
        .options=${this.items}
        .cursorIndex=${this.cursorIndex}
      >
        <slot></slot>
      </temba-options>
      ${this.renderFooter()}
    `;
  }
}