Skip to content

Instantly share code, notes, and snippets.

View crashmax-dev's full-sized avatar
:octocat:
Meow

Vitalij Ryndin crashmax-dev

:octocat:
Meow
  • Russia
  • 13:12 (UTC +08:00)
View GitHub Profile
@heyqbnk
heyqbnk / createImageLoader.ts
Created December 29, 2024 15:12
A Vite plugin to process images.
import sharp, { type Sharp } from 'sharp';
import { readFileSync } from 'node:fs';
/**
* Creates a key for cache.
* @param path - original image absolute path
* @param initialScale - original image initial scale
* @param scale - target image scale
*/
function formatKey(path: string, initialScale: number, scale: number): string {
@OrionReed
OrionReed / dom3d.js
Last active April 19, 2025 12:06
3D DOM viewer, copy-paste this into your console to visualise the DOM topographically.
// 3D Dom viewer, copy-paste this into your console to visualise the DOM as a stack of solid blocks.
// You can also minify and save it as a bookmarklet (https://www.freecodecamp.org/news/what-are-bookmarklets/)
(() => {
const SHOW_SIDES = false; // color sides of DOM nodes?
const COLOR_SURFACE = true; // color tops of DOM nodes?
const COLOR_RANDOM = false; // randomise color?
const COLOR_HUE = 190; // hue in HSL (https://hslpicker.com)
const MAX_ROTATION = 180; // set to 360 to rotate all the way round
const THICKNESS = 20; // thickness of layers
const DISTANCE = 10000; // ¯\\_(ツ)_/¯
@KristofferEriksson
KristofferEriksson / useTextSelection.ts
Last active March 24, 2025 14:37
A React Typescript hook that tracks user text selections & their screen positions
import { useEffect, useState } from "react";
type UseTextSelectionReturn = {
text: string;
rects: DOMRect[];
ranges: Range[];
selection: Selection | null;
};
const getRangesFromSelection = (selection: Selection): Range[] => {
@mishushakov
mishushakov / client.tsx
Last active June 5, 2024 04:40
A React hook for calling Next.js Server Actions from client components
'use client'
import { test } from './server'
import { useServerAction } from './hook'
export default function Home() {
const { data, loading, error, execute: testAction } = useServerAction(test)
if (loading) return <div>Loading...</div>
if (error) return <div>Error: {error.message}</div>
@kinda-neat
kinda-neat / how-long-did-you-think-about-useLayoutEffect.md
Last active September 5, 2024 06:00
Уверены что понимаете как работает useLayoutEffect?

В доке по useLayoutEffect можно найти следующие отрывки:

  • React guarantees that the code inside useLayoutEffect and any state updates scheduled inside it will be processed before the browser repaints the screen.
  • Call useLayoutEffect perform the layout measurements before the browser repaints the screen:
  • The code inside useLayoutEffect and all state updates scheduled from it block the browser from repainting the screen. When used excessively, this makes your app slow. When possible, prefer useEffect.

Как это возможно? Как Реакт может гарантировать что код внутри useLayoutEffect и стейт апдейты запланированные внутри него будут выполнены до перерисовки экрана браузером? Как Реакт может влиять на перерисовку браузером, как может ее блокировать? Как Реакт это делает и как вы

@skinnyfads
skinnyfads / downloadFile.ts
Last active March 6, 2023 19:34
Download any files from direct link using Node.js
import fs from "node:fs";
import https from "node:https";
import http from "node:http";
function getFileName(url: string) {
return new URL(url).pathname.split("/").pop();
}
async function downloadFile(url: string): Promise<string> {
const urlProtocol = new URL(url).protocol;
const request = urlProtocol === "https:" ? https : http;
// https://reactjs.org/docs/hooks-faq.html#how-to-read-an-often-changing-value-from-usecallback
// https://github.com/reactjs/rfcs/pull/220#issuecomment-1259938816
import React from 'react';
// Allow to access a fresh closures in the function but returns stable reference during rerenders
export function useCallbackRef<T extends (...args: unknown[]) => unknown>(callback: T): T {
const ref: React.MutableRefObject<{
stableFn: T;
callback: T;
@epicbytes
epicbytes / example.api.ts
Last active January 20, 2025 20:45
NextJS Authorization Files
/*** function that used as middleware ***/
accessToken: async (name) => {
if (typeof document === "undefined") return "";
let token = document.cookie
.split(";")
.filter((cookie) => cookie.startsWith("token"))[0];
if (!token) {
const response = await fetch("/api/refresh", { method: "POST" });
{"version":2,"type":"full","values":{"exp-lock":1658571974582,"p:0:chat.filtering.highlight-mentions":true,"p:0:tooltip.badge-images":false,"p:0:player.vod.autoplay":false,"p:0:player.home.autoplay":false,"p:0:chat.badges.hidden":{"1":false,"2":true,"3":false},"profiles":[{"id":1,"name":"Moderation","i18n_key":"setting.profiles.moderation","description":"Settings that apply when you are a moderator of the current channel.","context":[{"type":"Moderator","data":true}],"uuid":"ffz_profile_moderation"},{"id":0,"name":"Default Profile","i18n_key":"setting.profiles.default","description":"Settings that apply everywhere on Twitch.","uuid":"ffz_profile_default"}],"p:0:chat.emote-menu.icon":false,"p:0:channel.auto-click-chat":true,"p:0:channel.auto-skip-trailer":true,"p:0:chat.delay":0,"p:0:chat.emote-menu.show-search":false,"p:0:addon.seventv_emotes.unlisted_emotes":true,"cfg-seen":["i18n.debug.capture","i18n.debug.transform","i18n.locale","i18n.format.date","i18n.format.time","i18n.format.datetime","data.use-stagin
@mmazzarolo
mmazzarolo / localstorage-error-handling.ts
Created June 29, 2022 16:49
Handling localStorage errors (such as quota exceeded errors)
/**
* Determines whether an error is a QuotaExceededError.
*
* Browsers love throwing slightly different variations of QuotaExceededError
* (this is especially true for old browsers/versions), so we need to check
* different fields and values to ensure we cover every edge-case.
*
* @param err - The error to check
* @return Is the error a QuotaExceededError?
*/