Sha256: 5e4493fa2cc341aa2fc5681fc1820c538cd9c92186cdd99c4e0bc3a136a2cbc4

Contents?: true

Size: 1.35 KB

Versions: 10

Compression:

Stored size: 1.35 KB

Contents

import { Controller } from "@hotwired/stimulus";

export default class SelectionFormController extends Controller {
  static values = {
    count: Number,
    primaryKey: { type: String, default: "id" },
  };
  static targets = ["count", "singular", "plural"];

  connect() {
    this.countValue = this.inputs.length;
  }

  /**
   * @param id to toggle
   * @return {boolean} true if selected, false if unselected
   */
  toggle(id) {
    const input = this.input(id);

    if (input) {
      input.remove();
    } else {
      this.element.insertAdjacentHTML(
        "beforeend",
        `<input type="hidden" name="${this.primaryKeyValue}[]" value="${id}">`,
      );
    }

    this.countValue = this.inputs.length;

    return !input;
  }

  /**
   * @returns {boolean} true if the given id is currently selected
   */
  isSelected(id) {
    return !!this.input(id);
  }

  get inputs() {
    return this.element.querySelectorAll(
      `input[name="${this.primaryKeyValue}[]"]`,
    );
  }

  input(id) {
    return this.element.querySelector(
      `input[name="${this.primaryKeyValue}[]"][value="${id}"]`,
    );
  }

  countValueChanged(count) {
    this.element.toggleAttribute("hidden", count === 0);
    this.countTarget.textContent = count;
    this.singularTarget.toggleAttribute("hidden", count !== 1);
    this.pluralTarget.toggleAttribute("hidden", count === 1);
  }
}

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
katalyst-tables-3.3.4 app/javascript/tables/selection/form_controller.js
katalyst-tables-3.3.3 app/javascript/tables/selection/form_controller.js
katalyst-tables-3.3.2 app/javascript/tables/selection/form_controller.js
katalyst-tables-3.3.1 app/javascript/tables/selection/form_controller.js
katalyst-tables-3.3.0 app/javascript/tables/selection/form_controller.js
katalyst-tables-3.2.0 app/javascript/tables/selection/form_controller.js
katalyst-tables-3.1.0 app/javascript/tables/selection/form_controller.js
katalyst-tables-3.0.0.beta1 app/javascript/tables/selection/form_controller.js
katalyst-tables-2.6.0 app/javascript/tables/selection/form_controller.js
katalyst-tables-2.6.0.beta app/javascript/tables/selection/form_controller.js