Sha256: d2d5902d7a772f0c5a31fb252502af00b7088b39d9ebfd52b02fc2571e8d12a4

Contents?: true

Size: 1.98 KB

Versions: 3

Compression:

Stored size: 1.98 KB

Contents

import { Controller as BaseController } from '@hotwired/stimulus';
import { findAll } from '@fretadao/f-js-dom';

export default class extends BaseController {
  static targets = ['desktopTable', 'mobileTable'];

  connect() {
    this.toggleDuplicatesHandler = this.toggleDuplicates.bind(this);

    this.checkboxes().forEach(checkbox => {
      checkbox.addEventListener('change', this.toggleDuplicatesHandler);
    });


    this.syncInputHandler = this.syncInput.bind(this)

    this.inputs().forEach(input => {
      input.addEventListener('input', this.syncInputHandler);
    })

    document.dispatchEvent(this.#loadedEvent());
  }

  disconnect() {
    this.checkboxes().forEach(checkbox => {
      checkbox.removeEventListener('change', this.toggleDuplicatesHandler);
    });

    this.inputs().forEach(input => {
      input.removeEventListener('change', this.syncInputHandler);
    })
  }

  toggleDuplicates(event) {
    const checkbox = event.currentTarget;

    this.checkboxes({ id: checkbox.id, value: checkbox.value }).forEach(dup => {
      dup.checked = checkbox.checked;
    });

    this.element.dispatchEvent(new CustomEvent('checkboxesChanged', { bubbles: true }));
  }

  syncInput(event) {
    const input = event.currentTarget;

    this.inputs(input.id).forEach(dup => {
      dup.value = input.value;
    });

    this.element.dispatchEvent(new CustomEvent('inputsChanged', { bubbles: true }));
  }

  checkboxes({ id, value } = {}) {
    let query = 'input[type=checkbox]';

    if(!!id) {
      query = `#${id}`;
    } else if (!!value) {
      query += `[value="${value}"]`;
    }

    return findAll(query, this.element);
  }

  inputs(id = null) {
    let query = 'input:not([type=checkbox])';

    if(!!id) {
      query = `#${id}`;
    }

    return findAll(query, this.element);
  }

  #loadedEvent() {
    return new CustomEvent(
      'f-components-table:loaded',
      {
        detail: { desktopTable: this.desktopTableTarget, mobileTable: this.mobileTableTarget }
      }
    );
  }
}

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
f_components-0.5.0 app/components/f_components/table/component_controller.js
f_components-0.3.0 app/components/f_components/table/component_controller.js
f_components-0.2.1 app/components/f_components/table/component_controller.js