From 846e811760eb79965a844546d50c49c31768fbee Mon Sep 17 00:00:00 2001 From: Daniel Silverstone Date: Sun, 5 May 2019 21:56:15 +0100 Subject: Generics: Add consoleFormatter In order to support the console logging formatting specification as per https://console.spec.whatwg.org/#logger we need to implement the Formatter(...) algorithm which is easier done within JavaScript Signed-off-by: Daniel Silverstone --- content/handlers/javascript/duktape/generics.js | 76 +++++++++++++++++++++++++ 1 file changed, 76 insertions(+) (limited to 'content') diff --git a/content/handlers/javascript/duktape/generics.js b/content/handlers/javascript/duktape/generics.js index ee5e8013b..6850c9b7d 100644 --- a/content/handlers/javascript/duktape/generics.js +++ b/content/handlers/javascript/duktape/generics.js @@ -27,4 +27,80 @@ var NetSurf = { }, }); }, + consoleFormatter: function Formatter() { + + if (arguments.length == 0) { + return new Array(""); + } else if (arguments.length == 1) { + return new Array(arguments[0].toString()); + } + + const target = arguments[0]; + const current = arguments[1]; + + if (typeof target !== "string") { + return Array.from(arguments); + } + + const offset = target.search("%"); + + if (offset == -1 || offset >= target.length) { + // We've a string, but the % either doesn't exist or is + // at the end of it, so give up + return Array.from(arguments); + } + + const specifier = target[offset + 1]; + + var converted = undefined; + + if (specifier === 's') { + // Stringification + converted = current.toString(); + } else if (specifier === 'd' || specifier === 'i') { + converted = parseInt(current, 10).toString(); + } else if (specifier === 'f') { + converted = parseFloat(current).toString(); + } else if (specifier === 'o') { + // TODO: Objectification? + converted = current.toString(); + } else if (specifier === 'O') { + // TODO: JSONification + converted = current.toString(); + } + + var result = new Array(); + + if (converted !== undefined) { + // We converted it, so we need to absorb the formatted thing + // and move on + var newtarget = ""; + if (offset > 0) { + newtarget = target.substring(0, offset); + } + newtarget = newtarget + converted; + if (offset < target.length - 2) { + newtarget = newtarget + target.substring(offset + 2, target.length); + } + result.push(newtarget); + } else { + // Undefined, so we drop this argument and move on + result.push(target); + } + + var i; + for (i = 2; i < arguments.length; i++) { + result.push(arguments[i]); + } + + if (result[0].search("%") == -1) { + return result; + } + + if (result.length === 1) { + return result; + } + + return Formatter.apply(result); + } }; -- cgit v1.2.3