Skip to content

Instantly share code, notes, and snippets.

@valterbarros
Last active June 13, 2023 20:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save valterbarros/c9f85911a0e85842aa4b5891c50d18d3 to your computer and use it in GitHub Desktop.
Save valterbarros/c9f85911a0e85842aa4b5891c50d18d3 to your computer and use it in GitHub Desktop.
import { query, emitEvent, setDaysToDate, getIsoDate } from '/static/assets/js/helpers.js';
class DateField extends HTMLElement {
constructor() {
super();
this.innerHTML = `
<style>
</style>
<input
type="date"
class="field ${this.klass}"
name="${this.name}"
id="${this.idField}"
value="${this.value}"
placeholder="${this.placeholder}"
required="${this.required}"
max="${this.max}"
/>
`;
this.currentInput?.addEventListener('blur', () => (
emitEvent(this, 'blur')
));
}
static get observedAttributes() {
return ['min-counting-from-today', 'max-counting-from-today'];
}
connectedCallback() {
this.setValidation();
}
setValidation() {
if (this.hasMaxCountingFromToday) {
const baseMaxDate = setDaysToDate(this.maxCountingFromToday);
const maxDate = getIsoDate(baseMaxDate);
this.currentInput.max = maxDate;
}
if (this.hasMinCountingFromToday) {
const baseMinDate = setDaysToDate(this.minCountingFromToday);
const minDate = getIsoDate(baseMinDate);
this.currentInput.min = minDate;
}
}
attributeChangedCallback(name, oldValue, newValue) {
if (name.includes('counting-from-today')) {
this.setValidation();
}
}
setDate(date) {
this.currentInput.valueAsDate = date;
}
get currentInput() {
return query('input', this);
}
// Input fields
get mask() {
return this.getAttribute('mask');
}
get name() {
return this.getAttribute('name');
}
get idField() {
return this.getAttribute('id');
}
get placeholder() {
return this.getAttribute('placeholder') || '';
}
get required() {
return this.hasAttribute('required');
}
get max() {
return this.getAttribute('max');
}
get value() {
return this.getAttribute('value');
}
get klass() {
return this.getAttribute('klass');
}
get maxCountingFromToday () {
return Number(this.getAttribute('max-counting-from-today') || 0);
}
get minCountingFromToday () {
return Number(this.getAttribute('min-counting-from-today') || 0);
}
get hasMaxCountingFromToday() {
return this.hasAttribute('max-counting-from-today')
}
get hasMinCountingFromToday() {
return this.hasAttribute('min-counting-from-today')
}
}
customElements.define('date-field', DateField);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment