Useful snippets

Prosjekt som bruker WSL? Hvordan bytte til Git Bash

Sun 22. October 2023 | 2023-10-22

Hvordan bytte fra wsl til git bash i et prosjekt

I et prosjekt hvor du allerede har installert npm modules med wsl er det litt tricky å gå over til git bash. Har opplevd det i hvert fall.

Her er et forsøk som funket, men det er sannsynigvis unødvendige steg her.

Hvorfor bytte? Vel... react-snap og bruk av chromium er visst ikke helt akseptert av WSL

WSL

  1. npm cache verify
  2. delete node_modules
  3. npm cache clean --force

Git bash

  1. npm rebuild
  2. lukk VS Code og åpne som Admin
  3. npm i
  4. npm start

Og det funker! "React-scripts is not recognised" – no more!

https://coder-coder.com/npm-clear-cache/
https://stackoverflow.com/questions/47928735/react-scripts-is-not-recognized-as-an-internal-or-external-command

why not multiple BrowserRouters

Sun 22. October 2023 | 2023-10-22

why not use multiple browserrouters


React Router error - 
    Error: You cannot render a <Router> inside another <Router>. You should never have more than one in your app.
    at Router (/vendors-node_modules_restart_hooks_esm_useForceUpdate_js-node_modules_restart_hooks_esm_usePr-cdac26.iframe.bundle.js:6709:103)
    at renderWithHooks (/vendors-node_modules_storybook_addon-a11y_dist_preview_mjs-node_modules_storybook_addon-essen-d391cf.iframe.bundle.js:38091:27)
    at mountIndeterminateComponent (/vendors-node_modules_storybook_addon-a11y_dist_preview_mjs-node_modules_storybook_addon-essen-d391cf.iframe.bundle.js:41855:13)
at beginWork (/vendors-node_modules_storybook_addon-a11y_dist_preview_mjs-node_modules_storybook_addon-essen-d391cf.iframe.bundle.js:43368:16)
    at beginWork$1 (/vendors-node_modules_storybook

Drew Reese - . There becomes an issue when you start nesting routers within routers, or rather it's the routing contexts within other routing contexts. The contexts of "outer" routers are unaware of what nested "inner" routers have handled.

https://stackoverflow.com/questions/67175039/is-it-possible-to-have-multiple-browserrouter-in-react-app

scriptedalchemy - Dont think you want have multiple browser routers. Youd want to use switch or something else. Only hosts should implement browser router, and only once. Usually I have a standalone wrapper that has like a mini shell for each app. Then I federate the inner component. So browser router stays on the shell layer

nebarf - Single source of truth: having a single "component" updating the browser history brings a lot of flexibility (e.g. it could really help in case you're gradually migrating a legacy system following the strangler pattern).

https://github.com/module-federation/module-federation-examples/issues/1986

Test storybook krasj

Sun 22. October 2023 | 2023-10-22

krasjer npm run test-storybook ? Får du error-meldinger som folk på internettet sier betyr at du har gått tom for RAM?

Prøv:

  • kjør _pre-merge-request.sh i wsl-terminalen?
  • prøv noe av det som blir foreslått her: https://github.com/storybookjs/storybook/issues/12348

Task warrior (CLI todo app)

Sun 22. October 2023 | 2023-10-22

Installer på Ubuntu (WSL)

sudo apt-get install taskwarrior

https://taskwarrior.org/download/

Oppstart

task version

yes for å lage config file (.taskrc)

Bruk

📍 Legg til task

task add bla bla bla bla

📌 - med priority

task priority:H add bla bla bla bla

📅📃 List opp alle tasks

task next

next kan sløyfes

✔ Gjennomfør task nr X

task X done

❌ 🗑 Slett

task X delete

https://taskwarrior.org/docs/30second/

💬🗨 Se og rediger alle detalljer

task X edit

🗃 Opprett i prosjekter

task add project:Kitchen Select floor tiles
task add project:Kitchen Measure counter-top
task add project:Kitchen Design placement of electrical outlets
task add project:Kitchen Locate ideal placement for extractor duct
task add project:Kitchen Select and order counter-top material
task add project:Kitchen Talk to the Electrician about when the work can start

https://taskwarrior.org/docs/best-practices/

Interessant

  • visual interactive taskwarrior - https://gothenburgbitfactory.org/vit/

table of contents with IntersectionOvserver (not perfect)

Sun 22. October 2023 | 2023-10-22

useScrollSpy.ts

import { useEffect, useRef, useState } from "react";

export function useScrollSpy(ids: string[]) {
  const [activeId, setActiveId] = useState();
  const observer = useRef();

  useEffect(() => {
    const elements = ids.map((id) => document.getElementById(id));

    observer.current?.disconnect();

    elements.forEach((heading) => {
      if (heading) {
        observer.current?.observe(heading);
      }
    });

    observer.current = new IntersectionObserver(
      (entries) => {
        console.group("executing intersectionobserver callback");

        entries.forEach((entry) => {
          if (entry?.isIntersecting) {
            console.log(entry.target.id, "is intersecting");

            setActiveId(entry.target.id);
          }
        });
        console.groupEnd();
      },
      { rootMargin: "0% 0% -80% 0%", threshold: 0.1 }
    );

    return () => observer.current?.disconnect();
  }, [ids]);
  return activeId;
}

TableOfContents.tsx

import React, { useEffect, useState } from "react";
import classes from "./TableOfContents.module.css";
import { useScrollSpy } from "@/hooks/useScrollSpy";

interface TableOfContentsProps {
  isLoading: boolean;
}

export type heading = { text: string | null; id: string };

export const TableOfContents = ({ isLoading }: TableOfContentsProps) => {
  const [headings, setHeadings] = useState<heading[]>([]);
  const activeId = useScrollSpy(headings.map(({ id }) => id));
  useEffect(() => {
    if (!isLoading) {
      const elements: heading[] = Array.from(
        document.querySelectorAll("h3")
      ).map((element) => ({ text: element.textContent, id: element.id }));
      setHeadings(elements);
    }
  }, [isLoading]);

  return (
    <div
      className={`${classes.root} d-none d-lg-block sticky-with-gutter list-group small`}
    >
      <nav>
        {headings.map((heading) => {
          const maybeActive = activeId === heading.id ? "active" : "";
          return (
            <li key={heading.id}>
              <a
                className={`list-group-item list-group-item-action ${maybeActive}`}
                href={`#${heading.id}`}
              >
                {heading.text}
              </a>
            </li>
          );
        })}
      </nav>
    </div>
  );
};

SSH-keys

Sun 22. October 2023 | 2023-10-22

Hvordan opprette og bruke

Github

Fint for å slippe å skrive inn brukernavn og passord hver eneste gang

  1. ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/home/paalss/.ssh/id_rsa):

  1. [Enter]
...
Your public key has been saved in /home/paalss/.ssh/id_rsa.pub
...
  1. cat /home/paalss/.ssh/id_rsa.pub
ssh-rsa <Hererenlanghashcode> paalss@Asus-VivoBook
  1. Gå til Add new ssh keys

  2. Lim inn ssh-rsa <Hererenlanghashcode>

Resten er rett frem

https://docs.oracle.com/en/cloud/cloud-at-customer/occ-get-started/generate-ssh-key-pair.html

Blir du spurt om username og password (PAT) ved git push?

Da bruker du sannsynligvis HTTPS:

Slik bytter du til SSH:

git remote set-url origin git@github.com:paalss/<repo>.git

Bitbucket

https://peter-whyte.com/setup-ssh-keys-in-wsl/

eval $(ssh-agent -s) && ssh-add ../pw_bitbucket

Personal Access Token for http https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/creating-a-personal-access-token Kan brukes til authentication i stedet for passord

https://docs.github.com/en/authentication/connecting-to-github-with-ssh/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent

eval "$(ssh-agent -s)"
ssh-add ~/.ssh/id_ed25519

eller:

ssh-add ~/.ssh/github_pw

show commit hash

Sun 22. October 2023 | 2023-10-22

Vise kort commit hash

git rev-parse --short HEAD

Rename React component

Sun 22. October 2023 | 2023-10-22

# ask in what path the component resides in
# if no answer is provided, use default value
# -e flag is for giving `cd`-code completion while answering the question
defaultValue=src/stories/default/
read -e -p "Where is component located? (default: $defaultValue): " location
location=${location:-$defaultValue}

read -p "Enter component name you want to rename: " currentName

componentPath=$location/$currentName
index=$componentPath/index.ts
component=$componentPath/$currentName.tsx
story=$componentPath/$currentName.stories.tsx
stylesheet=$componentPath/$currentName.module.css

if [[ $currentName != "" ]]; then
    filesInThatFolder=$(cd $componentPath && ls)
    echo
    echo "This will affect:"
    echo "---- folder -----"
    echo $componentPath
    echo
    echo "---- files -----"
    echo $filesInThatFolder
    echo
    
    read -p "Enter new name: " newName
    if [[ $newName != "" ]]; then
        
        # update code
        sed -i "s/$currentName/$newName/g" $index
        sed -i "s/$currentName/$newName/g" $component
        sed -i "s/$currentName/$newName/g" $story
        sed -i "s/$currentName/$newName/g" $stylesheet
        
        # rename files and folder
        mv $component $componentPath/$newName.tsx
        mv $story $componentPath/$newName.stories.tsx
        mv $stylesheet $componentPath/$newName.module.css
        mv $componentPath $location/$newName/
    fi
fi