想写一个 Sketch 插件 结果 一查不可收拾 ~~ 涉及到 Symbol 符号/ Layer 图层 / Overrides 可替换变量 等等
var sketch = context.api() var document = sketch.selectedDocument; var selection = document.selectedLayers; var command = context.command; var selectedLayer = context.document.selectedLayers().firstLayer() command.setValue_forKey_onLayer_forPluginIdentifier('chips!', 'testAgain',selectedLayer,'myplugin'); log(command.valueForKey_onLayer_forPluginIdentifier('testAgain', selectedLayer,'myplugin'));
//https://sketchplugins.com/d/41-saving-data-in-a-document
// [0] represents first override, replace with appropriate index if other override is desired symbolInstance.setValue_forOverridePoint("New text", symbolInstance.overridePoints()[0]);
//https://gist.github.com/sonburn/f16f61cc97f50db1fc2f7172fa218b10
var value = nil, key = "kModelPropertiesKey", layer = context.selection[0], plugin = "com.animaapp.stc-sketch-plugin"; // Get the value context.command.valueForKey_onLayer_forPluginIdentifier(key,layer,plugin); // Set the value context.command.setValue_forKey_onLayer_forPluginIdentifier(value,key,layer,plugin); //https://gist.github.com/sonburn/71e05c03ac02cfe10fea5042215dfacd //////////////////// var layer = context.selection[0] context.command.setValue_forKey_onLayer("foo", "bar", layer) log(context.command.valueForKey_onLayer("bar", layer)) // logs 'foo' //https://sketchplugins.com/d/93-unique-id-or-tag-to-identify-component-symbol // Set value on document context.command.setValue_forKey_onDocument_forPluginIdentifier( 1, "testKey", context.document.documentData(), "myPluginID" ); // Get value on document var val = context.command.valueForKey_onDocument_forPluginIdentifier( "testKey", context.document.documentData(), "myPluginID" ); log(val); //https://sketchplugins.com/d/18-msplugincommand //////////////////// var layer = context.selection[0] var path = "21A3FCD7-83C0-4601-8527-67AC81E99828.2AB56A50-4051-418D-8301-DC0A3A0ADB3C.6F98D4B3-0947-4C35-85CF-0214A7DC6F4A" log(layer.overrides().allValues().objectAtIndex(0).valueForKeyPath(path)) //https://sketchplugins.com/d/97-nested-overrides-get-value-at-key/3 symbolInstance.addOverrides_forCellAtIndex_ancestorIDs_( {"63BC953E-4D77-4F07-B82E-6C9672330B49" : "overrideText"}, 0, nil); /////////////////// // get the existing overrides and create a mutable copy of the parts we are interested in changing var existingOverrides = symbolInstance.overrides(); var mutableOverrides = NSMutableDictionary.dictionaryWithDictionary(existingOverrides) mutableOverrides.setObject_forKey(NSMutableDictionary.dictionaryWithDictionary(existingOverrides.objectForKey(0)),0) // update the mutable dictionary mutableOverrides.objectForKey(0).setObject_forKey("newText","63BC953E-4D77-4F07-B82E-6C9672330B49") // apply the overrides to the symbol instance symbolInstance.applyOverrides_allSymbols_(mutableOverrides,false); //////////////////// var imageData = NSImage.alloc().initWithData( getImage(imgURL) ); mutableOverrides.objectForKey(0).setObject_forKey(imageData,layerIDs.artwork_ID); //////////////////// // we need an MSImageData - let's create one from a base64 PNG var strEncodeData = "iVBORw0KGgoAAAANSUhEUgAAACEAAAAhCAIAAADYhlU4AAAHZklEQVRIx4WXW4xdVRnH//9vrb3PmdNzZqZlOszQ6YXpQLmUazEgIgIKkUgiIaghykONiSYYn0wIvpBgfDK+GDUhMcSYyMUHDBJCjIJECBchLRQqlFJKWzuddjqd+7ntvb+/D/v0altWzsPZ56y1f/9v7W99339TEs4xyr9ISg7PccZMGiyQdmLaue7DszJ6ywDJAdHiOXV4DpAWzkOK59EuiRYAFIuzxaEdPrXD5z9D3kTSsMHxMHJNGN1sKxo9EgNJSQRwOum0OCSVQuQFLADI976TvfuEDv0DxZRVo1VqCFFFplbTu45kjGvuTq/bGseuFAAvaKGUeWpAJxklQBJU0GJ+bLL7ymM68Ey8oB4vvo3DN7G+HskgLcozdGe1+Kkffj3f+69iruDG71e+8khoDMoLMJAn5Z5knAHo7nql+9JDsTaZbn6Aa+9FdRQglQPem8kABMDR3O+f/Tn74C+5X1H5+uPJ+mtP2zfyzDggp4XO+y9kL2+tbFgVr/wxVt4AdeEdQiKB49IgSAIRqlDEzKv5jt92ppje/VQ68UV5AdpZ4pDcLHT3vtN9/t7qeH+4/CHUJ1AslrN14valoB6pVCaEBubfzXf+rjNZrdz/QnLhuLvzOIY6PkgVzeXW0/dU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JEIQACNNMIY+8LqdZW0YqtrVu06uk5SPVkUjO1WOxuJG+8yQDSyV7cpFfX1m5cG7/ajs3KjUZFIDLEHU6QHomKLbT320317X1v42bdWbRpJ1ZElVGKKhAFuxfT88sj99ZE1cgdNkvW6ldAXZVt+Mn9syJaakMlMkYimaIiGQAYCSPt4212DedVe/ajVApBS0RiNwaTA+cXZ5Yn0hh+mVGkdenGQBE3uF2zYNH/JI829i2gVLAygjGWgvWlCJbFbvzt0+wNDT/xt4d8ft21FcEKAcuNyd3F/tnz1o6tGRuReLjrZo3rlmlrqcurFn48t/Lq6adgbKVNHAInS0oCaPpZv3740+Z/WSMVuvrnRvyZVYiiCLbSXP5o7tObRsTsfqrDXa8tNOq2flz1nvulTf//lmmO/qa8LGupXhYyClf1OR/Z3Fg50LqzZ4AUR1ahKBMCj83MH4uG1D6+5/Uf1xL30PsKZnuEUjC1lOPjWc/Vdvxpu7EpG+jCwwisRRkJ0oeta9jxXoFu72TnSPdy+tn3Vw+u23FE1SWe6xTP91fEvKmCTB6aW33uyceSvA5W91Xo3rghIA0DPHO28aHpruTrvly6N3jdw3XdGR1ZSXj658/nd0zByWOgI05PTS/vewZFtsflpzGdMXUclj0N5fQIXbmlsuH54ZFVSWstTnsHneOpT/JxIgQFAy9Fu5Vm77V6YhaRa7euLVSsXFKWnOCvg83w7e1lHlP7NTvFAgrxnaXgyd87q23me948TsP+/PIvYc79//A84gXp3VaMoBQAAAABJRU5ErkJggg==" var data = NSData.alloc().initWithBase64EncodedString_options_(strEncodeData,NSDataBase64DecodingIgnoreUnknownCharacters); var picture = NSImage.alloc().initWithData_(data); var imageData = MSImageData.alloc().initWithImage_convertColorSpace_(picture, nil); // get the selected layer as the symbolInstance var symbolInstance = context.selection.firstObject(); var existingOverrides = symbolInstance.overrides(); // turn the overrides mutable var mutableOverrides = NSMutableDictionary.dictionaryWithDictionary(existingOverrides); // get the first one var firstOverride = NSMutableDictionary.dictionaryWithDictionary(existingOverrides.objectForKey(0)); // set the first override to the imageData var overrideId = [firstOverride allKeys][0]; firstOverride.setObject_forKey(imageData,overrideId) // update the mutableOverrides mutableOverrides.setObject_forKey(firstOverride,0); // set the new overrides on the symbolInstance symbolInstance.applyOverrides_allSymbols_(mutableOverrides,false); ////////////////// // sectionDetailContent is an array with info function executePopulateSymbol(instace, index) { var layerIDs = getLayerIDs(instance); var values = instance.overrides(); if (!values){ values = NSMutableDictionary.dictionary(); } var existingOverrides = values; var mutableOverrides = NSMutableDictionary.dictionaryWithDictionary(existingOverrides) mutableOverrides.setObject_forKey(NSMutableDictionary.dictionaryWithDictionary(existingOverrides.objectForKey(0)),0) var imgURL = server + sectionDetailContent[index].thumb + "?" +token; var picture = NSImage.alloc().initWithData_( getImage(imgURL) ); var imageData = MSImageData.alloc().initWithImage_convertColorSpace_(picture, nil); mutableOverrides.objectForKey(0).setObject_forKey(sectionDetailContent[index].title,layerIDs.title_ID) mutableOverrides.objectForKey(0).setObject_forKey(sectionDetailContent[index].year.toString(),layerIDs.year_ID) mutableOverrides.objectForKey(0).setObject_forKey(imageData,layerIDs.artwork_ID); instance.applyOverrides_allSymbols_(mutableOverrides,false); } function getLayerIDs(instance){ var symbolMaster = instance.symbolMaster(); var children = symbolMaster.children(); var layerIDs = {}; for (var i = 0; i < [children count]; i++){ var layer = children[i]; if( layer.name() == "Title" ) { layerIDs.title_ID = layer.objectID() } if( layer.name() == "Year" ) { layerIDs.year_ID = layer.objectID() } if( layer.name() == "Artwork" ) { layerIDs.artwork_ID = layer.objectID() } } return layerIDs; } ////////////////////////// symbolInstance.overrides = overrideObject` const overrides = { exampleStringOverride: '<some-override-string-value>', exampleSymbolOverride: '<some-override-symbol-name-string>' } setOverrides(symbolInstance, overrides) const createMain = () => ({ symbolMasterMap: {}, createSymbolMasterMap () { let symbolMasterArray = context.document.documentData().allSymbols().reverse() this.symbolMasterMap = {} for (let i = 0, len = symbolMasterArray.length; i < len; i++) { this.symbolMasterMap[symbolMasterArray[i].name()] = symbolMasterArray[i] } }, buildOverrideTree (symbolMaster, tree, dept) { const loop = symbolMaster.children().objectEnumerator() let layer while (layer = loop.nextObject()) { let lookNoFurther const objectID = layer.objectID() const layerName = layer.name() for (let key of Object.keys(overrides)) { // Setting overrides with undefined results in an unsavable // sketch document, not sure this solves this though if (!key) return // Change this (remove`":`) to your own // layer override naming convention! if(!lookNoFurther && key + ':' == layerName) { const override = overrides[key] const overrideIsNestedSymbol = !!layer.symbolID if (overrideIsNestedSymbol) { const nestedSymbolMaster = this.symbolMasterMap[override] if (!nestedSymbolMaster) { log(`The nested Symbol override ’${override}’ is missing`) return false } const nestedOverrideSymbolID = nestedSymbolMaster.symbolID() lookNoFurther = nestedSymbolMaster if(!tree[objectID]) tree[objectID] = {} tree[objectID]['symbolID'] = nestedOverrideSymbolID } else { tree[objectID] = override } } } if (layer.className() == 'MSSymbolInstance') { dept++ const subSearch = this.buildOverrideTree(lookNoFurther || layer.symbolMaster(), {}, dept) if(Object.keys(subSearch).length) { if(tree[objectID]) { Object.assign(tree[objectID], subSearch) } else { tree[objectID] = subSearch } } } } return tree }, setOverrides (symbolInstance, overrides) { const symbolMaster = symbolInstance.symbolMaster() const overrideTree = this.buildOverrideTree(symbolMaster, {}, 0) symbolInstance.overrides = overrideTree } }) // To quickly try this: // Create 3 symbols // Add an instance of the 2nd symbol to the 1st symbol // Replace `exampleNestedOverrideName` with the name of the nested symbol layer // Replace `ExampleNestedSymbol3` with the name of the 3rd symbol // Select an instance of the 1st symbol // Run this code from the `RunScript` panel in Sketch. // Note that this also works when `exampleNestedOverrideName` is in some deeper nested symbol, but beware of duplicate override layer names. const symbolInstanceLayer = context.document.selectedLayers().layers().firstObject() const overrides = { exampleNestedOverrideName: 'ExampleNestedSymbol3' } const main = createMain() main.createSymbolMasterMap() main.setOverrides(symbolInstanceLayer, overrides) //https://sketchplugins.com/d/20-how-do-i-write-to-a-symbol-instance-override/20
if ( layerType == 'MSTextLayer' ) {
var copiedText = layer.stringValue() + "\n";
arr.push({'x': varX, 'y': varY, 'text': copiedText});
}
//https://github.com/explorador/sketch-copy-text-only/blob/master/CopyTextOnly.sketchplugin/Contents/Sketch/script.cocoascript
https://developer.sketchapp.com/reference/api/#symbol-master