Skip to content

Instantly share code, notes, and snippets.

@colelawrence
colelawrence / use-rpc-hooks.ts
Created June 2, 2025 10:50
Effect RPC + TanStack Query with good types. Customize for your use case! Let me know if you fix failure extraction!
import { FetchHttpClient, HttpClient, HttpClientRequest } from "@effect/platform";
import { RpcResolver, type RpcRouter } from "@effect/rpc";
import { HttpRpcResolver } from "@effect/rpc-http";
import type { AppRouter, JWTAccessToken, OrgID } from "@phosphor/server";
import { type UseMutationOptions, type UseQueryOptions, useMutation, useQuery } from "@tanstack/react-query";
import { Effect, flow, identity, pipe } from "effect";
import { Option } from "effect";
import type * as EffectRequest from "effect/Request";
import type { FiberFailure } from "effect/Runtime";
import React from "react";
/**
* FNV-1a 32-bit hash – fast, non-cryptographic, browser-safe.
* Sufficient for generating repeatable fragment keys.
*/
export const fnv1aHash32 = (str: string): string => {
let h = 0x811c9dc5; // FNV offset basis
for (let i = 0; i < str.length; i++) {
h ^= str.charCodeAt(i);
h += (h << 1) + (h << 4) + (h << 7) + (h << 8) + (h << 24);
}
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