Skip to content

Instantly share code, notes, and snippets.

@codenameone
Created July 16, 2018 19:05
Show Gist options
  • Save codenameone/6c80e2f822a0b9498bbe9ebed1ab0758 to your computer and use it in GitHub Desktop.
Save codenameone/6c80e2f822a0b9498bbe9ebed1ab0758 to your computer and use it in GitHub Desktop.
Small Script used to merge code in PDF from asciidoc in Sketch
log('Merge text layers starting');
const sketch = require('sketch');
var Rectangle = require('sketch/dom').Rectangle;
var Text = require('sketch/dom').Text;
const document = sketch.fromNative(context.document);
var fullText = "";
var x = 10000000;
var y = -1000;
var style;
var parent;
var lastColor;
document.selectedLayers.forEach(layer => {
if (layer.type === String(sketch.Types.Text)) {
if(fullText !== "") {
if(layer.frame.y != y) {
createText(fullText, x, y, style, parent);
fullText = "";
x = 10000000;
y = layer.frame.y;
} else {
color = getTextColor(layer);
if(!lastColor.isEqual(color)) {
x = createText(fullText, x, y, style, parent);
fullText = "";
lastColor = color;
}
}
} else {
y = layer.frame.y;
lastColor = getTextColor(layer);
}
fullText += layer.text;
if(x > layer.frame.x) x = layer.frame.x;
parent = layer.parent;
style = layer.style;
layer.remove();
}
});
createText(fullText, x, y, style, parent);
function getTextColor(layer) {
var attributes = layer.sketchObject.attributedString().treeAsDictionary().value.attributes
var color = "";
attributes.forEach(function(attr) {
color = attr.MSAttributedStringColorAttribute.value;
});
return color;
}
function createText(fullText, x, y, style, parent) {
log('Merging: ' + fullText);
var rect = new Rectangle(x, y, 10, 500);
var newText = new Text({
text: fullText,
parent: parent,
style: style,
alignment: Text.Alignment.left,
lineSpacing: 15,
fixedWidth: false,
frame: rect
});
newText.adjustToFit();
newText.moveToFront();
return newText.frame.x + newText.frame.width;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment