Skip to content

Instantly share code, notes, and snippets.

@dz4k
Created October 25, 2025 13:23
Show Gist options
  • Save dz4k/24c6d3b9cf6c7de27f0246e500dc33fb to your computer and use it in GitHub Desktop.
Save dz4k/24c6d3b9cf6c7de27f0246e500dc33fb to your computer and use it in GitHub Desktop.
lume cms duration field
import { Component } from "lume_cms/components/component.js";
const skewerCamel = s => s.replace(/[A-Z]/g, (s) => "-" + s.toLowerCase())
const h = (tag, attrs, children) => {
const el = document.createElement(tag)
for (const [name, value] of Object.entries(attrs)) el.setAttribute(skewerCamel(name), value)
el.append(...children)
return el
}
const visuallyHidden = `
clip: rect(0 0 0 0);
clip-path: inset(50%);
height: 1px;
overflow: hidden;
position: absolute;
white-space: nowrap;
width: 1px;
`
customElements.define(
"percentage-field",
class extends Component {
init() {
const { schema, value, namePrefix, isNew } = this;
const name = `${namePrefix}.${schema.name}`;
const numId = `field_${name}/num`;
const unitId = `field_${name}/unit`;
const labelId = `field_${name}/label`;
const unitLabelId = `field_${name}/unitLabel`;
const val = isNew ? value ?? schema.value : value;
this.append(
this.label = h('label', { for: numId, id: labelId }, schema.label),
h('span', { id: unitLabelId, style: visuallyHidden }, 'birimi'),
this.numberInput = h('input', { id: numId, type: number, value: val }),
this.unitInput = h('select', { id: unitId, ariaLabelledby: [labelId, unitLabelId].join(" ") },
h('option', { value: 'T.S' }, 'Dakika'),
h('option', { value: 'T.M' }, 'Dakika'),
h('option', { value: 'T.H' }, 'Saat'),
h('option', { value: '.D', selected: '' }, 'Gün'),
h('option', { value: '.W' }, 'Hafta'),
h('option', { value: '.M' }, 'Ay'),
h('option', { value: '.Y' }, 'Yıl'),
),
);
}
get currentValue() {
if (this.numberInput.value === '') return ''
return `P${this.unitInput.value.replace('.', this.numberInput.value)}`
}
update(schema, value) {
if (value !== null && value !== undefined) {
const match = /P(?<time>T?)(?<number>\d+)(?<unit>[A-Z])/i.exec(value);
this.numberInput.value = match.groups.number;
this.unitInput.value = `${match.groups.time}.${match.groups.unit}`.toUpperCase();
} else {
this.numberInput.value = '';
this.unitInput.value = '.D';
}
this.label.innerHTML = schema.label;
}
},
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment