Skip to content

Instantly share code, notes, and snippets.

View deavial's full-sized avatar
😈
Up to no good, probably.

Deavial deavial

😈
Up to no good, probably.
View GitHub Profile
@sergiodxa
sergiodxa / entry.server.tsx
Last active May 7, 2024 12:30
Dynamically generate a PDF with Remix
import { renderToStream } from "@react-pdf/renderer";
import ReactDOMServer from "react-dom/server";
import { EntryContext, Headers, RemixServer, Request, Response } from "remix";
import PDF, { loader } from "./pdfs/my-pdf.server";
async function handlePDFRequest(request: Request, headers: Headers) {
// get the data for the PDF
let response = await loader({ request, context: {}, params: {} });
// if it's a response return it, this means we redirected
if (response instanceof Response) return response;
@sergiodxa
sergiodxa / .eslintrc.js
Created July 30, 2021 22:45
My favorite ESLint configuration
/* eslint-disable unicorn/prefer-module */
module.exports = {
root: true,
parser: "@typescript-eslint/parser",
plugins: [
"@typescript-eslint",
"unicorn",
"import",
"react",
"prettier",
@sergiodxa
sergiodxa / remix-auth.ts
Created July 21, 2021 23:25
Remix authentication library usage example
// create a session storage instance
let sessionStorage = createCookieSessionStorage();
// create authenticator instance
let authenticator = new Authenticator<User>(
sessionStorage
);
// configure the authenticator to use the Auth0 strategy for sign-in
authenticator.use(
@sergiodxa
sergiodxa / csrf.tsx
Last active September 9, 2022 18:03
A module with the implementation for CSRF protection in Remix
import { randomBytes } from 'crypto';
import * as React from 'react';
import { Request, Session } from 'remix';
import { parseBody, parseParams } from './parse-body';
/**
* An error that is thrown when a CSRF token is missing or invalid.
* @example
* throw new InvalidAuthenticityToken("Can't verify CSRF token authenticity.");
* @example
@sergiodxa
sergiodxa / react-feature-flags.js
Created October 24, 2019 17:55
React feature flags context, custom hook, hoc and render prop
import React from "react";
const FeatureFlags = React.createContext(null);
export function FeatureProvider({ features = null, children }) {
if (features === null || typeof features !== "object") {
throw new TypeError("The features prop must be an object or an array.");
}
return (
<FeatureFlags.Provider value={features}>{children}</FeatureFlags.Provider>
@sergiodxa
sergiodxa / human-readable-duration-format.js
Created September 10, 2018 21:07
Human readable duration format
const messages = {
year: { singular: 'year', plural: 'years', denominator: 365, inSeconds: 31536000 },
day: { singular: 'day', plural: 'days', denominator: 24, inSeconds: 86400 },
hour: { singular: 'hour', plural: 'hours', denominator: 60, inSeconds: 3600 },
minute: { singular: 'minute', plural: 'minutes', denominator: 60, inSeconds: 60 },
second: { singular: 'second', plural: 'seconds', inSeconds: 1 }
}
function pluralize(value, unit) {
if (value === 1) return messages[unit].singular;
@sergiodxa
sergiodxa / regex.js
Last active September 9, 2022 18:11
Match and replace Gist anchor with script tags
const regEx = /<a.*href=\"(https?\:\/\/gist\.github\.com\/\w*\/\w*)".*>.*<\/a>/gi;
const html = 'hola <a href="https://gist.github.com/sergiodxa/478eb21b6eb27d77e44bdd7d9732a46f" target="_blank" rel="nofollow">https://gist.github.com/sergiodxa/478eb21b6eb27d77e44bdd7d9732a46f</a> mundo';
const finalHTML = html.replace(regEx, '<script src="$1.js"></script><noscript>Github Gist <a href="$1" target="_blank" rel="nofollow">$1</a></noscript>');
document.write(finalHTML);
// result
// hola <script src="https://gist.github.com/sergiodxa/478eb21b6eb27d77e44bdd7d9732a46f.js"></script><noscript>Github Gist <a href="https://gist.github.com/sergiodxa/478eb21b6eb27d77e44bdd7d9732a46f" target="_blank" rel="nofollow">https://gist.github.com/sergiodxa/478eb21b6eb27d77e44bdd7d9732a46f</a></noscript> mundo
const vkeys = {
0: 'unk',
1: 'mouse1',
2: 'mouse2',
3: 'break',
4: 'mouse3',
5: 'mouse4',
6: 'mouse5',
8: 'backspace',
9: 'tab',
@sergiodxa
sergiodxa / async-thread.js
Last active June 27, 2023 05:38
Use WebWorkers and promises to run sync heavy functions in a worker (process) and get the result in a promise
function asyncThread(fn, ...args) {
if (!window.Worker) throw Promise.reject(
new ReferenceError(`WebWorkers aren't available.`)
);
const fnWorker = `
self.onmessage = function(message) {
(${fn.toString()})
.apply(null, message.data)
.then(result => self.postMessage(result));
@sebmarkbage
sebmarkbage / asyncToReact.js
Last active March 31, 2023 15:57
Convert Async Function to React Component
function asyncToReact(fn) {
class PromiseComponent extends React.Component {
state = { waiting: true, result: null };
componentDidMount() {
fn(...this.props.args).then(result => this.setState({ waiting: false, result }));
}
componentDidUpdate() {
fn(...this.props.args).then(result => this.setState({ waiting: false, result }));
}
shouldComponentUpdate(newProps) {