2021-01-30 07:33:04 +08:00
|
|
|
export function getAttributeOrThrow(element, attr, transform = null) {
|
|
|
|
if (!element.hasAttribute(attr)) {
|
|
|
|
throw new Error(
|
|
|
|
`Missing attribute '${attr}' on element <${element.tagName}:${element.id}>`
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
const value = element.getAttribute(attr);
|
|
|
|
|
|
|
|
return transform ? transform(value) : value;
|
|
|
|
}
|
|
|
|
|
2021-07-03 05:06:05 +08:00
|
|
|
export function getAttributeOrDefault(
|
|
|
|
element,
|
|
|
|
attr,
|
2022-03-19 19:22:36 +08:00
|
|
|
defaultValue,
|
2021-07-03 05:06:05 +08:00
|
|
|
transform = null
|
|
|
|
) {
|
2022-03-19 19:22:36 +08:00
|
|
|
if (element.hasAttribute(attr)) {
|
|
|
|
const value = element.getAttribute(attr);
|
|
|
|
return transform ? transform(value) : value;
|
|
|
|
} else {
|
|
|
|
return defaultValue;
|
|
|
|
}
|
2021-07-03 05:06:05 +08:00
|
|
|
}
|
|
|
|
|
2021-01-30 07:33:04 +08:00
|
|
|
export function parseBoolean(value) {
|
|
|
|
if (value === "true") {
|
|
|
|
return true;
|
|
|
|
}
|
|
|
|
|
|
|
|
if (value === "false") {
|
|
|
|
return false;
|
|
|
|
}
|
|
|
|
|
|
|
|
throw new Error(
|
|
|
|
`Invalid boolean attribute ${value}, should be either "true" or "false"`
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
export function parseInteger(value) {
|
|
|
|
const number = parseInt(value, 10);
|
|
|
|
|
|
|
|
if (Number.isNaN(number)) {
|
|
|
|
throw new Error(`Invalid integer value ${value}`);
|
|
|
|
}
|
|
|
|
|
|
|
|
return number;
|
|
|
|
}
|