Skip to content

Instantly share code, notes, and snippets.

@nasheomirro
nasheomirro / importScript.ts
Created March 10, 2024 19:15
makeshift dynamic import for non-module third party scripts
async function importScript(src: string) {
const script = document.createElement('script');
script.src = src;
document.body.appendChild(script);
return new Promise((res, rej) => {
script.onload = () => res();
});
}
@nasheomirro
nasheomirro / flatNestedKeys.ts
Last active December 28, 2023 18:48
A utility to flatten keys just like how react-hook-form does it
type FlattenKeys<T extends Record<string, any>, prefix extends string = ''> = {
[key in keyof T]: key extends string
? T[key] extends object
? `${prefix}${key}` | FlattenKeys<T[key], `${prefix}${key}.`>
: `${prefix}${key}`
: never;
}[keyof T];
// and to use it:
type Data = {
@nasheomirro
nasheomirro / createForm.ts
Created May 13, 2023 13:46
utility for handling forms on the client side, I tried making it similar to traditional handling of form actions.
import type { FormEventHandler } from 'svelte/elements';
import { writable } from 'svelte/store';
type Message = {
type: 'error' | 'success';
text: string;
};
type FormStoreValues = {
loading: boolean;
@nasheomirro
nasheomirro / registerWithRef.ts
Created January 2, 2023 09:06
react-hook-form utility function for attaching refs on register
import { MutableRefObject } from "react";
import {
FieldPath,
FieldValues,
RegisterOptions,
UseFormRegister,
} from "react-hook-form";
/** attach your ref to the register function from react-hook-form */
export const registerWithRef = <T extends FieldValues = FieldValues>(
@nasheomirro
nasheomirro / getScrollbarWidth.ts
Last active January 2, 2023 09:04
react-hook: prevent body scrollbar from shifting layout
// Thank you SO
// https://stackoverflow.com/questions/13382516/getting-scroll-bar-width-using-javascript
export function getScrollbarWidth() {
// Creating invisible container
const outer = document.createElement("div");
outer.style.visibility = "hidden";
outer.style.overflow = "scroll"; // forcing scrollbar to appear
document.body.appendChild(outer);
// Creating inner element and placing it in the container