To retrieve the swatchID bound to a layer, crashes on macOS 14

This is my code

export function getLayerAttrColorSwatchName(attrObject: any, attr?: string) {
let swatchID = ‘’;
let swatchName = ‘’;

try {
    if (attr === 'text') {
        let textStyle = attrObject.sketchObject.textStyle();
        let msColor = textStyle.attributes().MSAttributedStringColorAttribute;
        swatchID = msColor.swatchID();
    } else {
        swatchID = attrObject.sketchObject.color().swatchID();
    }

    let swatches = context.document.sketchObject.documentData().allSwatches();

    if (swatchID && swatches?.length > 0) {
        let findSwatch = swatches.find((item) => String(swatchID) == String(item.objectID()));
        if (findSwatch) {
            swatchName = String(findSwatch.name());
        }
    }
} catch (error) {}

return swatchName;

}

I see two potential issues in your code:

  1. You don’t need the sketchObject part in the following line since context.document is already a native Sketch object:
    - let swatches = context.document.sketchObject.documentData().allSwatches();
    + let swatches = context.document.documentData().allSwatches();
    
  2. The swatches variable is not a JavaScript collection, so calling find() on it will lead to unexpected results. Consider converting it to a JS array first with util.toArray():
    const util = require('util')
    // [...]
    let swatches = util.toArray(context.document.documentData().allSwatches());
    

By the way, there’s an easier way to obtain a color swatch by its ID given you’re already down to native unsafe APIs:

let findSwatch = context.document.documentData().swatchWithID(swatchID)
5 Likes

It works! Thanks!

1 Like