ignite-html-material/editable-image.js

123 lines
3.7 KiB
JavaScript
Raw Normal View History

import { IgniteElement } from "../ignite-html/ignite-element.js";
import { IgniteTemplate, button, div, img, input } from "../ignite-html/ignite-template.js";
class EditableImage extends IgniteElement {
constructor() {
super();
}
get styles() {
return `
mt-editable-image {
position: relative;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
mt-editable-image > img {
width: 100%;
max-width: 100%;
max-height: 100%;
height: auto;
flex: 1;
}
mt-editable-image.source:hover:after {
position: absolute;
font-family: 'Font Awesome 5 Pro';
font-weight: 900;
content: '\\f332';
color: #fff;
font-size: 2.2em;
display: flex;
align-items: center;
justify-content: center;
}
mt-editable-image.source:hover {
cursor: pointer;
filter: brightness(0.9);
}
`;
}
get properties() {
return {
source: null,
fileInput: null,
objectFit: "contain",
objectPosition: "center",
width: null,
maxWidth: null,
height: null,
maxHeight: null,
placeholder: null
};
}
render() {
return this.template
.onClick(() => this.onClick())
.class(this.source, value => { return value != null ? "source" : null; })
.child(
new div()
.hide(this.source, value => { return value != null; })
.child(this.placeholder),
new img()
.src(this.source)
.style("object-fit", this.objectFit)
.style("object-position", this.objectPosition)
.style("width", this.width)
.style("max-width", this.maxWidth)
.style("height", this.height)
.style("max-height", this.maxHeight)
2020-11-14 11:34:35 -08:00
.hide(this.source, value => { return value == null; })
.on("load", () => this.dispatchEvent(new Event("load"))),
new input()
.type("file")
.style("display", "none", true)
.attribute("accept", "image/*")
.onChange((event) => this.onFileChange(event)).ref(this.fileInput)
);
}
onFileChange(event) {
//Prevent this event from bubbling up since we haven't
//actually changed anything yet, just the inner input changed.
event.stopPropagation();
//Get the uploaded file from the file input.
var file = this.fileInput.files[0];
//Create a reader to read in the file.
var reader = new FileReader();
reader.onload = (event) => {
this.source = event.target.result;
//Invoke a native change event now that we have
//the image file ready.
this.dispatchEvent(new Event("change"));
};
//Read it.
reader.readAsDataURL(file);
}
onClick() {
this.fileInput.click();
}
}
class EditableImageTemplate extends IgniteTemplate {
constructor(...children) {
super("mt-editable-image", children);
}
}
customElements.define("mt-editable-image", EditableImage);
export {
EditableImageTemplate as EditableImage
};