import { IgniteElement } from "../ignite-html/ignite-element.js"; import { IgniteTemplate, button, ul, slot, span, div } from "../ignite-html/ignite-template.js"; import { IgniteProperty } from "../ignite-html/ignite-html.js"; class EditableLabel extends IgniteElement { constructor() { super(); } get styles() { return ` mt-editable-label { display: flex; flex-direction: row; align-items: center; } mt-editable-label>div.focus { border: solid 0.13rem #ced4da; padding: 0.2rem; border-radius: 0.3rem; } mt-editable-label:hover { cursor: pointer; } mt-editable-label>div { outline: unset; border: solid 0.13rem transparent; padding: 0.2rem; } mt-editable-label>div:empty:before { content: attr(data-placeholder); opacity: 0.5; } mt-editable-label>button { margin-left: 0.5em; background-color: #2196F3; color: #fff; border: none; border-radius: 0.3rem; padding: 0; width: 1.5em; height: 1.5em; min-width: 1.5em; min-height: 1.5em; font-size: 0.8rem; } `; } get properties() { return { stopEditingOnBlur: true, editing: false, value: new IgniteProperty(null, () => { //Emulate a change event to support value reflection. this.dispatchEvent(new Event("change")); }), multiLine: false, saveButton: true, input: null, placeholder: null }; } render() { return this.template .attribute("tabindex", "0") .onFocus(e => this.onFocus()) .child( new div() .innerHTML(this.value) .class(this.editing, (value) => { return value ? "focus" : null; }) .attribute("contenteditable", this.editing) .data("placeholder", this.placeholder) .ref(this.input) .onBlur(() => this.onBlur()) .on("keydown", (e) => this.onKeyDown(e)), new button(``) .onClick(() => this.onBlur()) .style("display", this.editing, true, (value) => { return value && this.saveButton ? null : "none" }) ); } onKeyDown(e) { if ((e.keyCode === 13 || e.keyCode === 27) && !this.multiLine) { this.input.blur(); e.preventDefault(); e.stopPropagation(); } } onBlur() { if (this.editing) { if (this.stopEditingOnBlur) { this.editing = false; } if (this.input.innerHTML !== this.value) { this.value = this.input.innerHTML; } } } onFocus() { this.editing = true; this.input.focus(); this.placeCaretAtEnd(this.input); } placeCaretAtEnd(el) { el.focus(); if (typeof window.getSelection != "undefined" && typeof document.createRange != "undefined") { var range = document.createRange(); range.selectNodeContents(el); range.collapse(false); var sel = window.getSelection(); sel.removeAllRanges(); sel.addRange(range); } else if (typeof document.body.createTextRange != "undefined") { var textRange = document.body.createTextRange(); textRange.moveToElementText(el); textRange.collapse(false); textRange.select(); } } } class EditableLabelTemplate extends IgniteTemplate { constructor(...children) { super("mt-editable-label", children); } } customElements.define("mt-editable-label", EditableLabel); export { EditableLabelTemplate as EditableLabel };