@steveesamson/microform
Version:
`microform` is a tiny library for managing forms in `svelte/sveltekit`.
72 lines (71 loc) • 2.15 kB
JavaScript
export const getEditableContent = (e, isHtml) => {
const el = e.target;
const text = el.textContent?.trim() || '';
if (!isHtml) {
return { text, value: text };
}
if (!text) {
return { value: '', text };
}
let htm = el.innerHTML;
htm = htm.trim();
htm = htm.replace(/<br>/g, '');
htm = htm.replace(/<div><\/div>/g, '');
htm = htm.replace(/<p><\/p>/g, '');
htm = htm.replace(/<div>/g, '<p>');
htm = htm.replace(/<\/div>/g, '</p>');
htm = htm.trim() ? (htm.indexOf('<p>') === -1 ? `<p>${htm}</p>` : htm) : htm;
return { value: htm.trim(), text };
};
export const makeName = function (str) {
const index = str.indexOf('_');
if (index < 0) {
return str === 'id' ? str.toUpperCase() : str.charAt(0).toUpperCase() + str.substring(1);
}
const names = str.split('_');
let new_name = '';
names.forEach(function (s) {
new_name += new_name.length > 0 ? ' ' + makeName(s) : makeName(s);
});
return new_name;
};
export const isValidFileSize = (node, maxFileSizeInMB) => {
if (!node)
return '';
const { files } = node;
if (!files)
return `${node.name} is required`;
const max = maxFileSizeInMB * 1024 * 1024;
for (const file of files) {
if (file.size > max) {
return `File '${file.name}' is larger the ${maxFileSizeInMB}MB.`;
}
}
return '';
};
export const resetObject = (target, data = undefined) => {
if (data) {
const defaultKeys = Object.keys({ ...data });
for (const [key,] of Object.entries(target)) {
if (defaultKeys.includes(key)) {
target[key] = data[key];
}
else {
delete target[key];
}
}
}
else {
for (const [key,] of Object.entries(target)) {
target[key] = '';
}
}
};
export const debounce = (func, delay = 1000) => {
let timeoutId;
return function (...par) {
const context = this;
clearTimeout(timeoutId);
timeoutId = setTimeout(() => func.apply(context, par), delay);
};
};