Site LogoReverie

Notes are memory anchors.

Light Dark

Web/CSS

Most modern operating systems let us control the preferred color theme. Luckily for us web developers, you can simply adjust the look of our sites by using the light-dark() function.

This function allows you to define two colors for a property, in which your browser automatically show the appropriate value based on your preferences.

To enable support for the light-dark() color function, the color-scheme must have a value of light dark, usually set on the :root pseudo-class.

:root {
  color-scheme: light dark;
}
  
body {
  --color-base: light-dark(hsl(32deg 57% 95%), hsl(249deg 22% 12%));
  --color-surface: light-dark(hsl(35deg 100% 98%), hsl(247deg 23% 15%));
  --color-overlay: light-dark(hsl(33deg 43% 91%), hsl(248deg 25% 18%));
}

Ref: light-dark()


Trim Text

TypeScript/String

Many text truncation implementations often cut words abruptly in the middle, resulting in poor readability. The code below offers an elegant solution by ensuring the truncation occurs at word boundaries and adds ellipsis appropriately. It returns a tuple containing both the processed text and a flag indicating whether truncation was performed.

const trimText = (
  input: string,
  length: number = 80,
): [text: string, trimmed: boolean] => {
  const trimmed = input.length >= length
  const text = trimmed
    ? `${input.slice(0, input.lastIndexOf(' ', length))}…`
    : input
 
  return [text, trimmed]
}
 
trimText(
  'This is some trimmed text that will not cut off half way through a word.',
  35,
)
// => ['This is some trimmed text that will…', true]

Ref: trimText


Cross Fade

Web/CSS

The cross-fade() CSS function can be used to blend two or more images at a defined transparency.

The cross-fade() function takes a list of images with a percentage defining how much of each image is retained in terms of opacity when it is blended with the other images.

cross-fade(url(white.png) 0%, url(black.png) 100%); /* fully black */
cross-fade(url(white.png) 25%, url(black.png) 75%); /* 25% white, 75% black */
cross-fade(url(white.png) 50%, url(black.png) 50%); /* 50% white, 50% black */
cross-fade(url(white.png) 75%, url(black.png) 25%); /* 75% white, 25% black */
cross-fade(url(white.png) 100%, url(black.png) 0%); /* fully white */
cross-fade(url(green.png) 75%, url(red.png) 75%); /* both green and red at 75% */

So we can use cross-fade() to achieve the background image translucency effect.

body {
    --transparent: url(data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==);
    background-size: cover;
    background-image: cross-fade(
        var(--transparent),
        url("./images/bg.jpg"),
        50%
    );
    background-image: -webkit-cross-fade(
        var(--transparent),
        url("./images/bg.jpg"),
        50%
    );
}      

Ref: cross-fade()


Create 2D Array

TypeScript/Array

A 2D array is also known as a matrix. It's arranged in a table-like structure that consists of rows and columns. In TypeScript, we can create 2D arrays in several ways, Array.from() being one of the most elegant solutions.

The Array.from() method creates a shallow-copied array from an array-like or iterable object. It accepts two main parameters:

  • An iterable or array-like object to convert
  • A optional mapping function that transforms each element
Array.from(arrayLike, mapFn)

Here's a utility function that creates a 2D array with specified dimensions and initial values:

function create2DArray<T>(rows: number, cols: number, initialValue: T): T[][] {
  return Array.from({ length: rows }, () => Array(cols).fill(initialValue))
}
 
const array = create2DArray<number>(3, 4, 0)
console.table(array) // [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]

Debugging Tips: When working with 2D arrays, use console.table() for better visualization.

Ref: Array.from()


Document DesignMode

Web/HTML

document.designMode controls whether the entire document is editable. Valid values are "on" and "off".

// Get the designMode
const mode = document.designMode
 
// Make the document editable
document.designMode = 'on' 

Ref: Document: designMode property


Convert String To Html

Web/HTML

To convert an HTML string into real HTML or DOM, we can use the DOMParser Web API using JavaScript. The DOMParser helps us to parse HTML or XML string into real Document or DOM nodes.

const convertStringToHTML = (htmlString: string): Element | null => {
  try {
    const parser = new DOMParser()
    const doc = parser.parseFromString(htmlString, "text/html")
 
    const parseError = doc.querySelector("parsererror")
    if (parseError) {
      throw new Error("HTML parsing failed")
    }
 
    const element = doc.body.firstElementChild
    return element
  } catch (error) {
    throw new Error(`Failed to convert HTML string: ${error.message}`)
  }
}

There are other mime types we can use such as:

  • text/html
  • text/xml
  • application/xml
  • application/xhtml+xml
  • image/svg+xml

Ref:


React Conditional Rendering

TypeScript/Record

Using Record for conditional rendering provides a more elegant and maintainable solution compared to traditional methods like if/else or switch statements.

This approach offers several key advantages:

  1. Type Safety - The Record type ensures all possible Fruit values have corresponding components at compile time.
  2. Clean Code - Replaces verbose if/else or switch statements with a concise object lookup.
  3. Performance - Direct object lookups are more efficient than evaluating multiple conditions, and React only renders the relevant component.
  4. Readability - A single mapping object clearly visualizes all fruit-to-icon relationships.
  5. Scalability - Adding new fruit types only requires updating the type and mapping, not the component logic.
import type { ReactNode } from 'react'
 
export type Fruit = 'apple' | 'kiwi' | 'cherry' | 'grape'
 
const Apple = () => <span>🍎</span>
const Kiwi = () => <span>🥝</span>
const Cherry = () => <span>🍒</span>
const Grape = () => <span>🍇</span>
 
const icon: Record<Fruit, ReactNode> = {
  apple: <Apple />,
  kiwi: <Kiwi />,
  cherry: <Cherry />,
  grape: <Grape />,
}
 
export const ConditionalFruitFacts = ({ fruit }: { fruit: Fruit }) => {
  return <>{icon[fruit]}</>
}

Ref: React Conditional Rendering With Type Safety and Exhaustive Checking