Skip to content

Relative lighten/darken #90

@michal-kurz

Description

@michal-kurz

I replaced color with colord in my project, but found out I don't get the same results, because they treat lighten() and darken() differently: While color shifts color by a fraction of itself, while colord shifts color by a fraction of whole spectrum.

I prototyped this wrapper to implement this functionality:

import { AnyColor, Colord, HslaColor } from 'colord'
import { colord as nativeColord } from 'colord'

export const clamp = (number: number, min = 0, max = 1): number => {
  return number > max ? max : number > min ? number : min
}

export const lightenRelative = (color: AnyColor | Colord, amount: number): HslaColor => {
  const hsla = nativeColord(color).toHsl()

  return {
    h: hsla.h,
    s: hsla.s,
    l: clamp(hsla.l * (1 + amount), 0, 100),
    a: hsla.a
  }
}

class ExtendedColord extends Colord {
  public lightenRelative(amount: number = 0.1) {
    return extendedColord(lightenRelative(this.rgba, amount))
  }

  public darkenRelative(amount: number = 0.1) {
    return extendedColord(lightenRelative(this.rgba, -amount))
  }
}

export const extendedColord = (input: AnyColor | Colord): ExtendedColord => {
  if (input instanceof ExtendedColord) return input
  return new ExtendedColord(input as any)
}

and I will use it for now, but I'd prefer to merge it into the library itself - are you interested in this functionality? I would love to make a PR if so.

Thank you 🙏

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions