Skip to content

Instantly share code, notes, and snippets.

@bryanberger
Last active November 3, 2021 17:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bryanberger/555b50e9c1c490a7b0be6618e276d057 to your computer and use it in GitHub Desktop.
Save bryanberger/555b50e9c1c490a7b0be6618e276d057 to your computer and use it in GitHub Desktop.
// how might this work outside of the local library? It looks like we may need to auth with and use the REST API todo this the most effcient way.
// This possibly means hardcoding the auth key in this plugin. It's private so that might be okay(?). We could ask for it up front but that seems counter productive https://www.figma.com/developers/api#get-file-styles-endpoint
const localStyles = figma.getLocalPaintStyles();
const selectedNodes = figma.currentPage.selection;
if (selectedNodes.length === 0) {
figma.notify("Nothing was selected...");
figma.closePlugin();
}
const getSwappedStyle = (style: PaintStyle) => {
const [_, currentTheme] = style.name.split("/");
const newTheme = currentTheme === "dark" ? "light" : "dark";
const newStyleName = style.name.replace(currentTheme, newTheme);
const newStyle = localStyles.find((style) => style.name === newStyleName);
return newStyle;
};
const swapTheme = (node: any) => {
console.log(node.type);
// Is this node a variant instance component?
if (node.type === "INSTANCE") {
// Does it have the `theme` property? If not then its not a themable variant
if (node.variantProperties && node.variantProperties["theme"]) {
console.log(node.variantProperties["theme"]);
const currentTheme = node.variantProperties["theme"].toLowerCase();
const newTheme = currentTheme === "dark" ? "light" : "dark";
// The node may not have another theme to switch to (if only dark or light is a property value on the component)
// This will throw an error currently
node.setProperties({ theme: newTheme });
} else {
forAllChildren(node);
}
return;
} else {
// Not a variant, so walk the tree instead (slower)
const fillStyle = localStyles.find(
(style) => style.id === node.fillStyleId
);
const strokeStyle = localStyles.find(
(style) => style.id === node.strokeStyleId
);
if (fillStyle && fillStyle.name.startsWith("themes/")) {
const newFillStyle = getSwappedStyle(fillStyle);
if (newFillStyle) node.fillStyleId = newFillStyle.id;
}
if (strokeStyle && strokeStyle.name.startsWith("themes/")) {
const newStrokeStyle = getSwappedStyle(strokeStyle);
if (newStrokeStyle) node.strokeStyleId = newStrokeStyle.id;
}
}
forAllChildren(node);
};
const forAllChildren = (node: any) => {
if (node.children) {
node.children.forEach((child) => {
swapTheme(child);
});
}
};
try {
selectedNodes.forEach((node: any) => swapTheme(node));
} catch (err) {
console.log(err);
}
figma.closePlugin();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment