Skip to content

Commit 7179005

Browse files
committed
feat: add colour support for browsers
1 parent 82da940 commit 7179005

File tree

3 files changed

+16
-3
lines changed

3 files changed

+16
-3
lines changed

src/colours.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
// Inherited from https://github.com/grammyjs/debug/blob/502f75667a64391adb9a73b1312a52a8e9ba5f64/colors.ts
2+
13
// https://github.com/debug-js/debug/blob/4.3.7/src/browser.js
24
const colors = [
35
0x0000cc, 0x0000ff, 0x0033cc, 0x0033ff, 0x0066cc, 0x0066ff, 0x0099cc, 0x0099ff, 0x00cc00, 0x00cc33, 0x00cc66,

src/types.ts

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
// type-safe way to access global values that may not be available in all runtimes
22

33
export const context = globalThis as unknown as {
4+
// browsers
5+
document?: any;
46
// Node, Deno, Bun
57
process?: {
68
env: { [key: string]: string };

src/w.ts

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { context } from "./types.ts";
2-
import { colourNs } from "./colours.ts";
2+
import { colourNs, selectColour } from "./colours.ts";
33
import { getEnv } from "./env.ts";
44
import { Namespaces } from "./namespacing.ts";
55
const DEBUG = getEnv("DEBUG");
@@ -18,9 +18,18 @@ export interface DebugFn {
1818
export const w = (namespace: string = ""): DebugFn => {
1919
const debugfn = (...args: unknown[]) => {
2020
if (debugfn.enabled) {
21-
const ns = useColour ? colourNs(namespace) : namespace;
2221
const [p0, ...rest] = args;
23-
debugfn.logger(`${ns} ${p0}`, ...rest);
22+
if (context.document) {
23+
debugfn.logger(
24+
`%c${namespace}%c ${p0}`,
25+
`color: #${selectColour(namespace).toString(16)}`,
26+
"color: inherit",
27+
...rest,
28+
);
29+
} else {
30+
let ns = useColour ? colourNs(namespace) : namespace;
31+
debugfn.logger(`${ns} ${p0}`, ...rest);
32+
}
2433
}
2534
};
2635

0 commit comments

Comments
 (0)