sketch-hq / sketchapi Goto Github PK
View Code? Open in Web Editor NEWThe JavaScript plugin library embedded in Sketch
Home Page: https://developer.sketch.com/reference/api
License: MIT License
The JavaScript plugin library embedded in Sketch
Home Page: https://developer.sketch.com/reference/api
License: MIT License
I'm trying to write a plugin that will set overrides in symbol instances in specific layer groups based on data from a JSON file.
The first problem is that overrides in a symbol instance don't have any name or label, it looks like I can only reference them by index in overrides array. I figured out that maybe I could get these names from the symbol master. However, I can't figure out how to get an existing symbol master. The API only mentions how to create one, not how to find one.
It looks like the methods inherits from Group
, but it just not works.
I find it works by following script
document.sketchObject.actionsController().actionForID("MSResizeArtboardToFitAction").resizeArtboardToFit(nil)
but should ensure the artboard
layer is selected..
Did I miss something or is this a bug? Thanks!
I ask because Selection
wraps a collection of objects, it's strange that it has a .sketchObject
and that it returns a MSPage
.
I wonder if there should be an Object
that is the top level class that contains the tests
. WrapperObject
and Selection
could both inherit from this class.
It seems that the new API is absolutely different from the old one, can I just get the new API in old sketch version like release 48.2?
If not, does it mean that we have to rewrite our plugin and keep both two versions of plugin to adapt new release 49 and the older ones?
I follow the guide on this page, however the code below doesn't work
var sketch = context.api()
var document = sketch.selectedDocument
var selection = document.selectedLayers
selection.iterate( function (item) { log( item.name() ) } )
It would throw this error:
TypeError: undefined is not an object (evaluating 'this._object._application.wrapObject')
line: 1627
sourceURL: /Applications/Sketch.app/Contents/Resources/SketchAPI.js
column: 54
But this works as expected:
var selection = context.selection
for (var i = 0; i < selection.length; i++) {
var _selection = selection[i]
log(_selection.name())
}
And here is my env:
log(sketch.api_version) // 1.1
log(sketch.version) // 40.2
log(sketch.build) // 33826
At the time of writing I can't seem to locate any hints of the signature newPage()
within the context of a Document
.
I'm hopeful that selectedDocument.newPage() is a likely outcome here. Currently I've had to revert to older methods to achieve this (context.document.addBlankPage()
) then either find it by name or set it to being selected. So far i've been able to route back into the API layer but its quite cumbersome to retain this parity.
Also in the same line of thinking, given there is selectedPage
, selectedDocument
why is selectedArtboard
not appearing (is that in the backlog or something?).
So far it seems the input values can be changed by users which should be prevented.
How can we prevent that they change the available options?
sketch-api
is not yet available on npm.
In Application.js, line: 276 is:
app.displayDialog_withTitle(message, title)
but it should be:
app.displayDialog_withTitle(title, message)
Reference page is ok.
In my opinion it's strange to have the UI input functions hang off the Application class. Do you guys think it makes more sense to have them be part of a UserInterface class?
Something like this instead?
var sketch = context.api()
sketch.ui.input("Test", "default");
sketch.ui.select("Test", ["One", "Two"], 1);
sketch.ui.message("Hello mum!");
sketch.ui.alert("Title", "message");
select
is the one that really stands out to me, because "select" has a very understood meaning in Sketch, to select an object. In the develop
branch this function is getSelectionFromUser
which if you just read sketch. getSelectionFromUser
is very confusing, my first thought is this is a function to get the user's current layer selection.
Both colors and gradients
Proposal:
Application.globalColors - get/set
Application.globalGradients - get/set
because last commit in master is from 2016
Settings -> Branches -> Default branch -> develop
or merge develop to master?
@samdeane Guessing you may already have this well underway in a branch somewhere, but just hit this working with the JS API and wanted to documented it.
Issue:
Checking for object.isGroup
on a known Group
always returns false
.
Expected:
Checking for object.isGroup
on a known Group
should return true
.
Poked at the source and saw that in the Group
class it's is_group
and not isGroup
https://github.com/BohemianCoding/SketchAPI/blob/master/Source/Group.js#L17
Wondering if that can be updated to isGroup
to override the default https://github.com/BohemianCoding/SketchAPI/blob/master/Source/Layer.js#L43
var sketch = context.api()
log(sketch.api_version)
log(sketch.version)
log(sketch.build)
log(sketch.full_version)
var document = sketch.frontDocument;
var selection = document.selection;
var page = document.selectedPage;
var group = page.newGroup({frame:sketch.rectangle(0, 0, 100, 100), name:"Test"});
var rect = group.newShape({frame:sketch.rectangle(10, 10, 80, 80)});
log(selection.is_empty());
selection.iterate(function(item) { log(item.name); } );
selection.clear();
log(selection.is_empty());
group.select();
rect.add_to_selection();
sketch.input("Test", "default");
sketch.select("Test", ["One", "Two"], 1);
sketch.message("Hello mum!");
sketch.alert("Title", "message");
we got this error
1.1
40
33762
40 (33762)
TypeError: undefined is not an object (evaluating 'document.selection')
line: 15
sourceURL: /Users/tcmac/.atom/packages/sketchapp-scripter/scripting/run.sketchplugin
column: 25
stack: onRun@/Users/tcmac/.atom/packages/sketchapp-scripter/scripting/run.sketchplugin:15:25
and the page.addGroup
seems didn't work too
I'm modifing my plugin, flowmate, to fix errors and update new APIs. It's really hard to understand the new and old APIs because there is not useful example. Your example is just for few cases and most of plugin still use old API (Please add some example to API documents)
And I have one questions. Do you have a plan to change thinkness of shape using new API? I saw the "Style.js" source and the implement is not hard I guess. That's why I don't understand you don't implement thickness (and gradient)
P.S : Is this way to I modify the core script like Style.js and test directly on Sketch app?
Hey Guys, wondering about documentation about how to build and run this so that when we work on changes and want to submit pull requests we can test the changes in the Sketch app?
The tests are failing because Style.colorFromString
is using calling a function that appears to no longer exist: MSImmutableColor.colorWithSVGString_ is not a function.
To be able to listen to in plugins. Stuff like "on new layer created", "on symbol renamed", etc. ? Or is that too much regarding performance (which is hanging by a thread as it is ;) ).
Any plans to add a method for creating webview modal, something like:
Application.openWebview(URL, size, callback)
If anyone has created something like that, would love to hear about it.
The hexValue function throws an error when used in a plugin. "TypeError: hexValue is not a function."
This worked in previous versions of Sketch. Is there a new version of this function I can use? I searched through the documentation with no luck.
/* ... */
var copy = someLayer.duplicate();
var rect = new sketch.Rectangle(0, 0, 100, 200);
copy.frame = rect;
I'm trying to export a Page with the new API (Sketch 49). It works well when giving an artboard to the export method. But when giving a Page object it crash (the script, not the app).
http://developer.sketchapp.com/reference/api/#export
Create a plugin to test with this script :
var sketch = require('sketch/dom');
export default function(context) {
var document = sketch.Document.getSelectedDocument();
//I know I have 2 Pages on my test document in Sketch
log(document.pages);
for (var i = 0; i < document.pages.length; i++) {
var page = document.pages[i];
log(page);
log(page.name);
sketch.export(page, {
overwriting: true,
output: "~/Desktop/test_output"
});
}
}
// Logs
//
// // Pages
// (
// "<null>",
// "<null>"
// )
// // Page [0]
// (null) // page
// screen_1 // page.name
// // sketch.export error
// -[__NSSingleObjectArrayI name]: unrecognized selector sent to instance 0x60800001a150
An image should be created representing the full page
An error :
-[__NSSingleObjectArrayI name]: unrecognized selector sent to instance 0x60800001a150
It's weird, because when logging a page, null
is printed, but page.name
, print the name.
What am I missing here. Just happened to drop in here and it looks awesome. Is it me or is this gem a little hidden currently?
I'm getting up to speed with scripting for Sketch at the same time as going through everything in this project so the way it's structured may make the most sense and I'm probably missing something :)
But I can't help but ask, should the newShape
, newText
, newGroup
, and newImage
functions be on the Layer
class instead of the Group
class? Maybe this is just me thinking about it as a Sketch user, but it seems strange to me to have these factory methods on a group, to me a layer makes more sense because they are all layers.
Is there any way to access/manipulate layer and text styles? Is it just missing in the documentation, or it's something that'll be provided in the future?
Perhaps we need some lint rules to ensure the code style?
I am trying to upload the current sketch file to a URL.
I have looked through all the example code and don't see anything that would get me close to it.
Is there an API I'm not seeing to export the document to ZIP format?
Thanks,
In the manifest commands:
"script": "myscript.js",
"handlers": {
"actions": {
"SelectionChanged.finish": "onSelectionChanged"
}
}
in myscript.js
var onSelectionChanged = function(context) {
var sketch = context.api()
log(sketch.api_version)
log(sketch.version)
log(sketch.build)
log(sketch.full_version)
var document = sketch.selectedDocument;
log(document.selectedLayers);
}
When changing selection:
TypeError: null is not an object (evaluating 'this._object.currentPage')
line: 810
sourceURL: /Applications/Sketch.app/Contents/Resources/SketchAPI.js
column: 41
Looks like the code in question is:
{
key: 'selectedPage',
get: function get() {
return new _Page.Page(this._object.currentPage(), this);
}
}
Hello! So on, I have been working on my plugin for a while, and I have experienced the issue with exporting artboards.
I have an array of duplicated artboards:
var tmpArtboards = [];
rootLayers.forEach(function(rootLayer) {
var tmp = rootLayer.duplicate();
// ...
tmpArtboards.push(tmp);
});
I try to set the export options for the artboards:
var options = {'scales': '1', 'formats': 'png'};
tmpArtboards.forEach(function(artboard) {
artboard.export(options);
});
I get this:
TypeError: artboard.export is not a function. (In 'artboard.export(options)', 'artboard.export' is undefined)
As I know, Artboard inherits Layer and I should be able to use export
method, but it seems that these objects are not belong to Layer.
I'm currently having to hack around the lack of wrappers for these two Sketch objects in my plugin (see nefaurk/select-parent-artboards#6), and I'd prefer not to have to.
Ideally, I could write code such as:
var artboardForItem = function(document, item) {
if (item.isArtboard) {
return item;
} else if (item.container != null) {
return artboardForItem(document, item.container);
} else {
return null;
}
};
But instead, I'm having to write code such as:
var artboardForItem = function(document, item) {
if (item.isArtboard) {
return item;
} else if (item.sketchObject != null && item.sketchObject.className() == "MSSymbolInstance") {
var parent = item.sketchObject.parentGroup();
var container = document.wrapObject(parent);
return artboardForItem(document, container);
} else if (item.container != null) {
return artboardForItem(document, item.container);
} else {
return null;
}
};
For more info, see: http://sketchplugins.com/d/209-no-mapped-wrapper-for-mssymbolinstance
Can you implement a method to lock the layer? It will be useful.
npm WARN deprecated [email protected]: Babel's CLI commands have been moved from the babel package to the babel-cli package
npm WARN deprecated [email protected]: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
npm WARN deprecated [email protected]: Please update to minimatch 3.0.2 or higher to avoid a RegExp DoS issue
npm WARN deprecated [email protected]: graceful-fs v3.0.0 and before will fail on node releases >= v7.0. Please update to graceful-fs@^4.0.0 as soon as possible. Use 'npm ls graceful-fs' to find it in the tree.
Like Rectangle
I think it might make sense to have a javascript object for Font
. Right now text.font
has to be set to a NSFont
object, exposing the underlying obj-c objects. Also the systemFontSize
defined as set
is a bit strange because then it's usage is text.systemFontSize = 40
, but this will do more than just set the font size, it will override the font family to the system font, which kinda makes sense from the property name, but I think is still strange ;)
I just got the project building with the new instructions, but noticing a pretty dramatic difference between the file that ships with Sketch 40.3 (33839) and what builds.
The built js file has 1248 lines of code, while the file that ships with Sketch has 2111.
I'm trying to change the line spacing on some API generated text. There doesn't seem to be a way to do it with current JS API, but is there a way to add it using the old API?
var text = group.newText({alignment: NSTextAlignmentCenter, text:copy, fixedWidth: true, font: NSFont.fontWithName_size_("Gotham HTF Book", 68.5)})
After looking at the code for the Sketch Set Line Height plugin, I tried using text.lineHeight()
and text.setLineHeight()
to no success. They come back saying those functions do not exist.
Any ideas? If there's a way to do it we can see about adding it to the JS API
var document = sketch.selectedDocument;
does not seem to work anymore.
I can create an artboard by new Artboard({ flow: { target: anothorArtboard } })
and there will be a link between two artboards, but when I click preview it does not work.
And I find that I can not create link in sketch(from an artboard).
Did I miss something or the flow
property should be removed from document(in Artboard)?
I'm not sure what the end plan here is but given that the "types" that inherit from Layer.js
one would assume that when executing the layerNamed(string)
resolves to the API centric type.
for example
context.api().selectedDocument.layerNamed("Page 1").isPage yields true.
context.api().selectedDocument.layerNamed("Artboard 1").isArtboard yields true.
The tests are failing because Group.newShape
only makes rectangles and seems to be using a function that no longer exists: MSShapeGroup.shapeWithRect_ is not a function.
Hi, I don't know where else to turn. I did exactly as the Sketch page instructed, to start working on a tutorial for a plugin, but I all end up with in the terminal is this:
iMac:~ xxx$ sudo skpm create my-plugin
module.js:540
throw err;
^
Error: Cannot find module '../build/Release/keytar.node'
at Function.Module._resolveFilename (module.js:538:15)
at Function.Module._load (module.js:468:25)
at Module.require (module.js:587:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/usr/local/lib/node_modules/skpm/node_modules/keytar/lib/keytar.js:1:76)
at Module._compile (module.js:643:30)
at Object.Module._extensions..js (module.js:654:10)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
The skpm package says it is version 1.0.13; the Node installation and npm installation were all fine. It turned out that despite my command line tools being installed, the keytar node had never been built and compiled into the right place. (And got it to work by sheer accident, by finding a keytar version that actually compiled through a homebrew node install, which I copied over).
Can you verify that the current tutorial actually works on High Sierra Vanilla installations? It could still be that things were wrong with my installation somehow and it got fixed by fiddling, but it took me three hours to get this going, and I would not be surprised if many potential developers jump ship without telling you there is an issue if this is the case.
After following the steps in the readme, npm install
works fine, but then running gulp
gulp is not installed. Does gulp need to be installed globally and should that be mentioned in the readme?
I've been browsing the API docs and I can't find any properties that correlate to resizing masks on layers. Does this functionality exist? I'm hoping to developer a plugin that would export Sketch layers into a prototyping tool but would preserve the resizing behavior.
Rectangle is not exposed to the global space so parent.newGroup({"frame": new Rectangle(0, 44, 100, 44)});
fails.
Is it safe to add this to the top of Rectangle.js
?
function _Rectangle(x, y, width, height) {
return new Rectangle(x, y, width, height);
}
__globals.Rectangle = _Rectangle;
This fixes the issue, but I'm not sure if there should be a global object named Rectangle
, what do you guys think?
I can detach a symbol on right click dropdown list.
Is there any way to do this in code way?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.