ignite-html-material/editable-label.js

124 lines
3.5 KiB
JavaScript

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 {
editing: false,
value: new IgniteProperty(null, () => {
//Emulate a change event to support value reflection.
this.dispatchEvent(new Event("change"));
}),
editOnClick: true,
multiLine: false,
saveButton: true,
input: null,
placeholder: null
};
}
render() {
return this.template
.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)
.onClick(() => this.onClick())
.onBlur(() => this.onBlur())
.on("keydown", (e) => this.onKeyDown(e)),
new button(`<i class="fas fa-check"></i>`)
.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();
}
}
onClick() {
if (this.editOnClick) {
this.editing = true;
this.input.focus();
}
}
onBlur() {
if (this.editing) {
this.editing = false;
if (this.input.innerHTML !== this.value) {
this.value = this.input.innerHTML;
}
}
}
}
class EditableLabelTemplate extends IgniteTemplate {
constructor(...children) {
super("mt-editable-label", children);
}
}
customElements.define("mt-editable-label", EditableLabel);
export {
EditableLabelTemplate as EditableLabel
};