Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save josephxbrick/090dae5bc58e617c81784b55abe450bf to your computer and use it in GitHub Desktop.
Save josephxbrick/090dae5bc58e617c81784b55abe450bf to your computer and use it in GitHub Desktop.
const {toArray} = require('util');
// returns a timestamp
const timeStamp = () => {
const now = new Date();
return `${'0'.concat(now.getHours()).slice(-2)}:${'0'.concat(now.getMinutes()).slice(-2)}:${'0'.concat(now.getSeconds()).slice(-2)}.${now.getMilliseconds().toString().concat('000').slice(0,3)}`;
}
// Assumes an existing text layer called 'debug_output' on the current page that's NOT in a group or artboard
// parameters: the Sketch page object, the thing (or an array of things) to log, whether or not to clear previous logs
const logIt = (page, args, clear = false) => {
// convert args to array if it's not already an array
args = [].concat(args || []);
// find the 'debug_output' text layer on page
const debugTextLayer = toArray(page.layers()).filter(item => item.name() == 'debug_output')[0];
if (debugTextLayer === undefined) {
return undefined;
}
// clear out previous logs
if (clear) {
debugTextLayer.setStringValue("Debug output:");
}
// construct debug string from args[], delimited by the pipe character
if (args.length > 0) {
let debugString = `(${timeStamp()}): `;
for (const arg of args) {
debugString = `${debugString}${arg.toString()} | `;
}
// get rid of trailing pipe delimiter
debugString = debugString.slice(0, debugString.length - 3);
// add debug string to debug_output text layer
debugTextLayer.setStringValue(`${debugTextLayer.stringValue()}\n${debugString}`);
}
}
// Example usage
const myFunction = (context) => {
const doc = context.document;
const page = doc.currentPage();
// clear previous log entries and log the name of the current page
logIt(page, page.name(), true);
// log both the name of the current page and a date object
logIt(page, [page.name, new Date()]);
}
// output (in debug_output text layer):
//
// Debug output:
// (16:01:36.902): Page 2
// (16:01:36.903): Page 2 | Wed Jan 22 2020 16:01:36 GMT-0800 (PST)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment