impress/app/assets/javascripts/outfit-rename-field.js

48 lines
1.5 KiB
JavaScript
Raw Normal View History

/**
* OutfitRenameField web component
*
* Progressive enhancement for the outfit name field:
* - Shows a static text header with a pencil icon button
* - Pencil appears on hover/focus of the container
* - Clicking pencil switches to the editable form
* - Enter submits, Escape/blur reverts to static display
*
* State is managed via the `editing` attribute, which CSS uses to toggle
* visibility. Turbo morphs naturally reset this attribute (since it's not in
* the server HTML), so no morph-specific handling is needed.
*/
class OutfitRenameField extends HTMLElement {
connectedCallback() {
const pencil = this.querySelector(".outfit-rename-pencil");
const input = this.querySelector("input[type=text]");
if (!pencil || !input) return;
pencil.addEventListener("click", () => {
this.dataset.originalValue = input.value;
this.setAttribute("editing", "");
input.focus();
input.select();
});
this.addEventListener("keydown", (e) => {
if (e.key === "Escape" && this.hasAttribute("editing")) {
e.preventDefault();
this.#cancelEditing(input);
}
});
this.addEventListener("focusout", (e) => {
if (this.hasAttribute("editing") && !this.contains(e.relatedTarget)) {
this.#cancelEditing(input);
}
});
}
#cancelEditing(input) {
input.value = this.dataset.originalValue ?? input.value;
this.removeAttribute("editing");
}
}
customElements.define("outfit-rename-field", OutfitRenameField);