Skip to content

Commit

Permalink
feat(plugin): add getLuminance
Browse files Browse the repository at this point in the history
  • Loading branch information
wzc520pyfm committed Mar 28, 2024
1 parent 73bd59e commit 34667ed
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
32 changes: 32 additions & 0 deletions src/plugin/getLuminance/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import type { MyColorPlugin, MyColor, MyColorFn } from "../..";

interface OhColorClass extends MyColor {
getLuminance: () => number;
}

interface OhColorFactory extends MyColorFn {
(...args: unknown[]): OhColorClass;
}

const f = (x: number) => {
const channel = x / 255;
return channel <= 0.040_45
? channel / 12.92
: Math.pow(((channel + 0.055) / 1.055), 2.4);
}

/**
* Returns a number (float) representing the luminance of a color.
*/
export const getLuminance: MyColorPlugin<OhColorFactory> = (_, c, cf) => {
const proto = c.prototype as OhColorClass;
const getRGB = proto.rgba;
proto.getLuminance = function() {
const [r, g, b] = getRGB.bind(this)();
return 0.2126 * f(r) + 0.7152 * f(g) + 0.0722 * f(b);
}

return cf as OhColorFactory;
}

export default getLuminance
1 change: 1 addition & 0 deletions src/plugin/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export { inputHex } from "./inputHex";
export { outputHex } from "./outputHex";
export { inputNamed } from './inputNamed';
export { getLuminance } from './getLuminance';
11 changes: 11 additions & 0 deletions test/plugin/get-luminance.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { expect, it, describe } from "vitest";
import { mycolor } from "../../src";
import { getLuminance } from "../../src/plugin"

describe("mycolor plugin: getLuminance", () => {
it("should get luminance", () => {
const mycolor2 = mycolor.extend(getLuminance);

expect(mycolor2(255, 255, 0, 1).getLuminance()).toBe(0.9278);
});
})

0 comments on commit 34667ed

Please sign in to comment.