Skip to content

Instantly share code, notes, and snippets.

export class MapOrSetDefault<K, T> extends Map<K, T> {
#setDefault(key: K): T {
const val = this.getDefault(key);
this.set(key, val);
return val;
}
constructor(public getDefault: (key: K) => T) {
super();
}
@colelawrence
colelawrence / downloadFileBinary.ts
Created February 10, 2025 22:11
Download a Uint8Array to file
export function downloadFileBinary(filename: string, data: Uint8Array, mimeType = "application/octet-stream") {
const blob = new Blob([data], { type: mimeType });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
}
@colelawrence
colelawrence / useClickByHoverToAvoidChangingFocus.tsx
Last active February 4, 2025 20:39
React helper for when you want to enable "clicking" a button without changing the document active element/focus
import { useEffect } from "react";
import { listen } from "./zlisten";
/** For when you want to do something without breaking the focus of the active element */
export const useClickByHoverToAvoidChangingFocus = (element: HTMLElement | null | undefined, callback: null | undefined | (() => void)) => {
useEffect(() => {
if (!element || !callback) return;
let openTimeout: (Animation | any)[] = [];
const DURATION = 1000;
@colelawrence
colelawrence / pipeNonNull.ts
Created January 18, 2025 20:26
Like a pipe function, but early return if any function returns a null-ish value
type Fn<T, U> = (t: T) => U | null | undefined;
/** like pipe, but returns early if any of the functions return a nullish value */
export function pipeNonNull<A, B>(a: A, b: Fn<A, B>): B | null | undefined;
export function pipeNonNull<A, B, C>(a: A, b: Fn<A, B>, c: Fn<B, C>): C | null | undefined;
export function pipeNonNull<A, B, C, D>(a: A, b: Fn<A, B>, c: Fn<B, C>, d: Fn<C, D>): D | null | undefined;
export function pipeNonNull<A, B, C, D, E>(a: A, b: Fn<A, B>, c: Fn<B, C>, d: Fn<C, D>, e: Fn<D, E>): E | null | undefined;
export function pipeNonNull<A, B, C, D, E, F>(
a: A,
b: Fn<A, B>,
c: Fn<B, C>,
@colelawrence
colelawrence / objectPredicateMacro.ts
Created January 16, 2025 15:26
Simple object predicate macro - fast check for an object you need to check many keys exist on
const objectPredicateMacro = <T>(keys: (keyof T | (string & {}))[]): ((obj: unknown) => obj is T) => {
return new Function(
"isObject",
"value",
`return isObject(value) ${keys.map((key) => `&& ${JSON.stringify(key)} in value`).join(" ")};`,
).bind(null, isObject);
};
const isStore = objectPredicateMacro<JotaiStore>(["get", "set", "sub", "unstable_derive"]);
@colelawrence
colelawrence / feature-doc-guidelines.md
Created November 17, 2024 18:46
Feature doc guidelines example

Feature Documentation Guidelines

Feature docs are files in docs/my-idea-feature.md files.

(Product Values)

When considering the details for any given product feature keep in mind our values:

  1. Privacy and Security: Prioritize user data protection and system security in all feature designs
  2. Transparency: Ensure clear communication of data usage and consent processes
@colelawrence
colelawrence / listen.ts
Created July 30, 2024 18:15
Listen to event targets, returning the unsubscribe function. TypeScript types included for DOM
interface listen {
<K extends keyof HTMLElementEventMap>(
target: HTMLElement,
type: K,
listener: (this: HTMLElement, ev: HTMLElementEventMap[K]) => void,
options?: boolean | AddEventListenerOptions,
): () => void;
(
target: EventTarget,
type: string,
@colelawrence
colelawrence / unindent-template.ts
Last active July 21, 2024 17:18
unindent-template-array.ts
const INDENTATION_RE = /^\n( +)/;
const unindentTemplate = (
template: TemplateStringsArray,
): { readonly raw: readonly string[] } => {
const indentation = INDENTATION_RE.exec(template.raw[0])?.[1];
return indentation
? { raw: template.raw.map((a) => a.replaceAll(`\n${indentation}`, "\n")) }
: template;
};
@colelawrence
colelawrence / objMap.ts
Last active June 5, 2024 17:39
Record mapping as a map function (e.g. `[P in keyof T]: Transform<T[P]>`)
export function objMap<T extends Record<string, any>, U>(
template: T,
eachKey: <P extends Extract<keyof T, string>>(name: P, value: T[P]) => U,
): {
[P in Extract<keyof T, string>]: U;
} {
// @ts-ignore
return Object.fromEntries(
Object.entries(template)
.filter(([name]) => typeof name === "string")
pub mod prelude {
// some custom proc macros
pub use i_app_types_proc::shared;
// a "concepts" module that is purely for documenting through doc links
pub use crate::concepts;
// other common shared modules re-exported...
pub use crate::runtime;
pub use crate::testing;