svelte-ux
Version:
- Increment version in `package.json` and commit as `Version bump to x.y.z` - `npm run publish`
81 lines (80 loc) • 2.24 kB
JavaScript
/**
* Auto focus node when rendered. Useful for inputs
*/
export function autoFocus(node, options) {
var _a;
// TODO: Add options to "restoreFocus" on destroy()
// const elementFocused = document.activeElement as HTMLElement;
setTimeout(() => {
node.focus();
}, (_a = options === null || options === void 0 ? void 0 : options.delay) !== null && _a !== void 0 ? _a : 0);
}
/**
* Selects the text inside a text node when the node is focused
*/
export function selectOnFocus(node) {
const handleFocus = (event) => {
node.select();
};
node.addEventListener('focus', handleFocus);
return {
destroy() {
node.removeEventListener('focus', handleFocus);
},
};
}
/**
* Blurs the node when Escape is pressed
*/
export function blurOnEscape(node) {
const handleKey = (event) => {
if (event.key === 'Escape') {
node.blur();
}
};
node.addEventListener('keydown', handleKey);
return {
destroy() {
node.removeEventListener('keydown', handleKey);
},
};
}
/**
* Automatically resize textarea based on content
* See:
* - https://svelte.dev/repl/ead0f1fcd2d4402bbbd64eca1d665341?version=3.14.1
* - https://svelte.dev/repl/f1a7e24a08a54947bb4447f295c741fb?version=3.14.1
*/
export function autoHeight(node) {
function resize({ target }) {
target.style.height = '1px';
target.style.height = +target.scrollHeight + 'px';
}
node.style.overflow = 'hidden';
node.addEventListener('input', resize);
// Resize initially
resize({ target: node });
return {
destroy() {
node.removeEventListener('input', resize);
},
};
}
/**
* Debounce event handler (change, input, etc)
*/
export function debounceEvent(node, { type, listener, timeout }) {
let lastTimeoutId;
function onEvent(e) {
clearTimeout(lastTimeoutId);
lastTimeoutId = setTimeout(() => {
listener(e);
}, timeout !== null && timeout !== void 0 ? timeout : 300);
}
node.addEventListener(type, onEvent);
return {
destroy() {
node.removeEventListener(type, onEvent);
},
};
}