Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding 2 new actions: prevent tab close and simple shortcut #11

Merged
merged 4 commits into from
Jan 20, 2021
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
74 changes: 73 additions & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -161,4 +161,76 @@ export function lazyload(node: HTMLElement, attributes: Object): ReturnType<Acti
observer.unobserve(node);
}
};
}
}

/**
* Prevent current tab from beind closed by user
swyxio marked this conversation as resolved.
Show resolved Hide resolved
*
* Demo: https://svelte.dev/repl/a95db12c1b46433baac2817a0963dc93
*/
export const preventTabClose: Action = (_, enabled: boolean) => {
const handler = (e: BeforeUnloadEvent) => {
e.preventDefault();
e.returnValue = '';
},
setHandler = (shouldWork: boolean) =>
shouldWork ?
window.addEventListener('beforeunload', handler) :
window.removeEventListener('beforeunload', handler);
Comment on lines +178 to +179
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TIL about https://developers.google.com/web/updates/2018/07/page-lifecycle-api#the-unload-event looks like you implemented it in the correct way


setHandler(enabled);

return {
update: setHandler,
destroy: () => setHandler(false),
};
};

/**
* Simplest possible way to add a keyboard shortcut to a div or a button.
* It either calls a callback or clicks on the node it was put on.
*
* Demo: https://svelte.dev/repl/acd92c9726634ec7b3d8f5f759824d15
*/

export type ShortcutSetting = {
control?: boolean;
shift?: boolean;
alt?: boolean;

code: string;

callback?: () => void;
};
export const shortcut: Action = (node, params: ShortcutSetting | undefined) => {
let handler: ((e: KeyboardEvent) => void) | undefined;

const removeHandler = () => window.removeEventListener('keydown', handler!),
setHandler = () => {
removeHandler();
if (!params) return;

handler = (e: KeyboardEvent) => {
if (
(!!params.alt != e.altKey) ||
(!!params.shift != e.shiftKey) ||
(!!params.control != (e.ctrlKey || e.metaKey)) ||
params.code != e.code
)
return;

e.preventDefault();

params.callback ? params.callback() : node.click();
};
window.addEventListener('keydown', handler);
};

setHandler();

return {
update: setHandler,
destroy: removeHandler,
};
};