Skip to content

Instantly share code, notes, and snippets.

export const OrgResource = RBAC.defineResource({
name: dev`Organization`,
idSchema: OrgID,
permissions: {
CreateWorkspace: (its) => its.Member,
},
roles: {
Admin: true,
Member: true,
Guest: true,
@colelawrence
colelawrence / loop-protection-counter.ts
Last active March 5, 2025 14:13
Loop protection counter in TypeScript
import { DevError, debounce } from "@project/prelude";
export class LoopError extends DevError {
constructor(
message: string,
public readonly debounceMs: number,
public readonly maxCount: number,
) {
super(`${message} (exceeded ${maxCount} calls in ${(debounceMs * 0.001).toFixed(1)}s)`);
}
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 April 3, 2025 00:07
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;
};