sketch-hq / SketchAPI

The JavaScript plugin library embedded in Sketch
https://developer.sketch.com/reference/api
MIT License
842 stars 126 forks source link

APIs missing: Find existing styles by Name (both Layer and Text styles) #883

Closed matteogratton closed 1 year ago

matteogratton commented 2 years ago

In order to apply a style to a layer, we need the Style ID, but we usually know the Name.

It is pretty annoying to search for the ID and usually I create a series of variables that help me handle this. Example with Text styles (but it applies to Layer styles too):

var textStyles = document.sharedTextStyles;
var arrayTextStyleIDs = textStyles.map((sharedstyle) => sharedstyle["id"]);
var arrayTextStyleNames = textStyles.map((sharedstyle) => sharedstyle["name"]);

[...]

function createTextWithStyleName(textName = "My Text", textValue = "Text here", parentLayer, paddingHorizontal = 8, paddingVertical = 4, styleName) {
    let textStyleID = getTextStyleIDFromName(styleName);
    let index = arrayTextStyleIDs.indexOf(textStyleID);

    let newText = new Text({
        parent: parentLayer,
        text: textValue,
        name: textName 
    });

    newText.frame.x = paddingHorizontal;
    newText.frame.y = paddingVertical;
    newText.sharedStyleId = textStyleID;
    newText.style = textStyles[index].style;

    return newText;
}

function getTextStyleIDFromName(name) {
    let styleID = "";
    for (let i = 0; i < arrayTextStyleIDs.length; i++) {
        if (arrayTextStyleNames[i] === name) {
            styleID = arrayTextStyleIDs[i];
        }
    }
    return styleID;
}

function getTextStyleNameFromID(id) {
    let textName = "";
    for (let i = 0; i < arrayTextStyleStyles.length; i++) {
         if (arrayTextStyleIDs[i] === id) {
            textName = arrayTextStyleStyles[i];
        }
    }
    return textName;
}

It would be nice to have some APIs that permit to search for a Style starting from their name (and IDs too).