Replace toggle_button_disable ctrller with generic toggle_control ctrller

- add enableIfPresent method in toggle_control_controller.js to handle enabling on toggle
- add testing in the corresponding spec
- replace in view previous ctrler with intended generic toggle-control
This commit is contained in:
cyrillefr
2024-01-16 18:46:55 +01:00
parent dd502f0883
commit 8eb5ac990e
3 changed files with 38 additions and 3 deletions

View File

@@ -1,7 +1,7 @@
%div#voucher-section
.checkout-title
= t("checkout.step2.voucher.apply_voucher")
.checkout-input{"data-controller": "toggle-button-disabled"}
.checkout-input{"data-controller": "toggle-control"}
= form_with url: voucher_adjustments_path, model: @order, method: :post, data: { remote: true } do |form|
- if voucher_adjustment.present?
.two-columns-inputs.voucher
@@ -18,8 +18,8 @@
- else
.two-columns-inputs
%div.checkout-input
= form.text_field :voucher_code, value: params.dig(:order, :voucher_code), data: { action: "input->toggle-button-disabled#inputIsChanged" }, placeholder: t("checkout.step2.voucher.placeholder"), class: "voucher"
= form.text_field :voucher_code, value: params.dig(:order, :voucher_code), data: { action: "input->toggle-control#enableIfPresent" }, placeholder: t("checkout.step2.voucher.placeholder"), class: "voucher"
= form.error_message_on :voucher_code
%div.checkout-input
= form.submit t("checkout.step2.voucher.apply"), disabled: true, class: "button cancel voucher-button", "data-disable-with": false, data: { "toggle-button-disabled-target": "button" }
= form.submit t("checkout.step2.voucher.apply"), disabled: true, class: "button cancel voucher-button", "data-disable-with": false, data: { "toggle-control-target": "control" }

View File

@@ -17,6 +17,14 @@ export default class extends Controller {
}
}
enableIfPresent(event) {
const input = event.currentTarget;
const enable = !!this.#inputValue(input);
this.controlTargets.forEach((target) => {
target.disabled = !enable;
});
}
//todo: can a new method disableIfBlank replace ButtonDisabledController?
//todo: can a new method toggleDisplay replace ToggleController?
//todo: can toggleDisplay with optional chevron-target replace RemoteToggleController?

View File

@@ -61,4 +61,31 @@ describe("ToggleControlController", () => {
});
});
});
describe("#enableIfPresent", () => {
describe("with input", () => {
beforeEach(() => {
document.body.innerHTML = `<div data-controller="toggle-control">
<input id="input" value="" data-action="input->toggle-control#enableIfPresent" />
<input id="control" data-toggle-control-target="control">
</div>`;
});
it("Enables when input is filled", () => {
input.value = "a"
input.dispatchEvent(new Event("input"));
expect(control.disabled).toBe(false);
});
it("Disables when input is emptied", () => {
input.value = "test"
input.dispatchEvent(new Event("input"));
input.value = ""
input.dispatchEvent(new Event("input"));
expect(control.disabled).toBe(true);
});
});
});
});