Skip to content

Commit

Permalink
fix: brackets causing issues in debug.log + enhance logging of single…
Browse files Browse the repository at this point in the history
… object (#475)
  • Loading branch information
dragoncoder047 authored Oct 23, 2024
1 parent 9a1ba74 commit 4433162
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 5 deletions.
18 changes: 18 additions & 0 deletions examples/prettyDebug.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
kaplay();

const pretty = {
i: "am pretty",
all: "own properties are shown",
even: {
nested: "objects",
},
arrays: ["show", "like", "you", "would", "write", "them"],
"own toString is used": vec2(10, 10)
}

debug.log("Text in [brackets] doesn't cause issues");

debug.log(pretty);

debug.error("This is an error message");

34 changes: 30 additions & 4 deletions src/gfx/draw/drawDebug.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { DBG_FONT, LOG_TIME } from "../../constants";
import { app, debug, game, globalOpt } from "../../kaplay";
import { rgb } from "../../math/color";
import { Vec2, vec2, wave } from "../../math/math";
import { vec2, wave } from "../../math/math";
import { formatText } from "../formatText";
import {
contentToView,
Expand Down Expand Up @@ -178,9 +178,7 @@ export function drawDebug() {
const style = log.msg instanceof Error ? "error" : "info";
str += `[time]${log.time.toFixed(2)}[/time]`;
str += " ";
str += `[${style}]${
typeof log?.msg === "string" ? log.msg : String(log.msg)
}[/${style}]`;
str += `[${style}]${prettyDebug(log.msg)}[/${style}]`;
logs.push(str);
}

Expand Down Expand Up @@ -220,3 +218,31 @@ export function drawDebug() {
});
}
}

function prettyDebug(object: any | undefined, inside: boolean = false): string {
var outStr = "", tmp;
if (inside && typeof object === "string") {
object = JSON.stringify(object);
}
if (Array.isArray(object)) {
outStr = [
"[",
object.map(e => prettyDebug(e, true)).join(", "),
"]"
].join("");
object = outStr;
}
if (typeof object === "object"
&& object.toString === Object.prototype.toString) {
if (object.constructor !== Object) outStr += object.constructor.name + " ";
outStr += [
"{",
(tmp = Object.getOwnPropertyNames(object)
.map(p => `${/^\w+$/.test(p) ? p : JSON.stringify(p)}: ${prettyDebug(object[p], true)}`)
.join(", ")) ? ` ${tmp} ` : "",
"}"
].join("");
object = outStr;
}
return String(object).replaceAll(/(?<!\\)\[/g, "\\[");
}
2 changes: 1 addition & 1 deletion src/kaplay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -546,7 +546,7 @@ const kaplay = <
clearLog: () => game.logs = [],
log: (...msgs) => {
const max = gopt.logMax ?? LOG_MAX;
const msg = msgs.concat(" ").join(" ");
const msg = msgs.length > 1 ? msgs.concat(" ").join(" ") : msgs[0];

game.logs.unshift({
msg: msg,
Expand Down

0 comments on commit 4433162

Please sign in to comment.