From b2c7d496c5300c4172e959ebbc07e1bf8fee1077 Mon Sep 17 00:00:00 2001 From: dragoncoder047 <101021094+dragoncoder047@users.noreply.github.com> Date: Wed, 23 Oct 2024 11:26:01 -0400 Subject: [PATCH] fix: brackets causing issues in debug.log + enhance logging of single object (#475) --- examples/prettyDebug.js | 18 ++++++++++++++++++ src/gfx/draw/drawDebug.ts | 32 +++++++++++++++++++++++++++++--- src/kaplay.ts | 2 +- 3 files changed, 48 insertions(+), 4 deletions(-) create mode 100644 examples/prettyDebug.js diff --git a/examples/prettyDebug.js b/examples/prettyDebug.js new file mode 100644 index 00000000..ae2a3288 --- /dev/null +++ b/examples/prettyDebug.js @@ -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"); + diff --git a/src/gfx/draw/drawDebug.ts b/src/gfx/draw/drawDebug.ts index c67d59c9..3c509ea9 100644 --- a/src/gfx/draw/drawDebug.ts +++ b/src/gfx/draw/drawDebug.ts @@ -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); } @@ -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(/(? 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,