Skip to content

Commit

Permalink
organized messages and some cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
andreiinc committed Jun 10, 2020
1 parent c405be7 commit ee7888d
Show file tree
Hide file tree
Showing 6 changed files with 96 additions and 140 deletions.
89 changes: 42 additions & 47 deletions src/code/main.ts
Original file line number Diff line number Diff line change
@@ -1,52 +1,47 @@
import { clientStorageKey, Config } from './modules/config';
import { CMD } from './modules/globals';
import { CMD, counter, messages, showNofication } from './modules/globals';
import { changeAllStyles, extractAllStyles, updateStyleNames } from './modules/styles';

let currentConfig;

if (CMD === 'clear-cache') {
figma.clientStorage.setAsync(clientStorageKey, undefined).then(() => {
figma.closePlugin('🧹 Cleaned saved settings from cache.');
return;
});
}
//
else {
figma.clientStorage.getAsync(clientStorageKey).then((cachedSettings) => {
currentConfig = new Config(cachedSettings);

// creating layers based on styles
if (CMD === 'extract-all-styles') {
extractAllStyles(currentConfig);
}

//
else if (CMD === 'customize-plugin') {
figma.showUI(__html__, { width: 360, height: 480 });
figma.ui.postMessage(cachedSettings);
}

//
else {
changeAllStyles(currentConfig);
}
});

figma.ui.onmessage = (msg) => {
if (msg.type === 'cancel-modal') {
figma.closePlugin('🥺 Everything is as before.');
return;
}

// save
else if (msg.type === 'save-settings') {
figma.clientStorage.setAsync(clientStorageKey, msg.uiSettings).then(() => {
let newConfig = new Config(msg.uiSettings);

updateStyleNames(currentConfig, newConfig);
figma.closePlugin();
return;
});
}
};
}
figma.clientStorage.getAsync(clientStorageKey).then((cachedSettings) => {
currentConfig = new Config(cachedSettings);

if (CMD === 'clear-cache') {
figma.clientStorage.setAsync(clientStorageKey, undefined).then(() => {
showNofication(0, messages(counter).clearCache, currentConfig.notificationTimeout);
});
}
// creating layers based on styles
else if (CMD === 'extract-all-styles') {
extractAllStyles(currentConfig);
}

//
else if (CMD === 'customize-plugin') {
figma.showUI(__html__, { width: 360, height: 480 });
figma.ui.postMessage(cachedSettings);
}

//
else {
changeAllStyles(currentConfig);
}
});

figma.ui.onmessage = (msg) => {
if (msg.type === 'cancel-modal') {
showNofication(0, messages(counter).cancelSettings, currentConfig.notificationTimeout);
}

// save
else if (msg.type === 'save-settings') {
figma.clientStorage.setAsync(clientStorageKey, msg.uiSettings).then(() => {
const newConfig = new Config(msg.uiSettings);

updateStyleNames(currentConfig, newConfig);
});
} else {
figma.closePlugin('🤷‍♂️ This should not happen. Nothing was changed...');
}
};
4 changes: 2 additions & 2 deletions src/code/modules/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,8 +101,8 @@ export class Config {
suffix: effecterSuffix,
});

this.allStylers = [this.texter, this.grider, this.filler, this.strokeer, this.effecter];
this.stylersWithoutTexter = [this.grider, this.filler, this.strokeer, this.effecter];
this.allStylers = [this.texter, this.filler, this.strokeer, this.effecter, this.grider];
this.stylersWithoutTexter = [this.filler, this.strokeer, this.effecter, this.grider];
this.texterOnly = [this.texter];
}
}
4 changes: 2 additions & 2 deletions src/code/modules/default-settings.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
export const defaultSettings = {
addPrevToDescription: false,
framesPerSection: 5,
textsPerSection: 5,
framesPerSection: 8,
textsPerSection: 8,
notificationTimeout: 6000,
updateUsingLocalStyles: false,
partialMatch: false,
Expand Down
15 changes: 14 additions & 1 deletion src/code/modules/globals.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { defaultSettings } from './default-settings.js';
import { settings } from 'cluster';

export const CMD = figma.command;

export const counter = {
applied: 0,
created: 0,
customize: 0,
detached: 0,
extracted: 0,
generated: 0,
Expand Down Expand Up @@ -45,14 +47,25 @@ export const messages = (counter) => {
single: `🔥 Removed only ${counter.removed} style. Rrr...`,
multiple: `🔥 Removed ${counter.removed} styles. Rrr...`,
},
customize: {
empty: '🌟 Settings were saved, but there was nothing to update.',
single: '✅ Settings were saved and only 1 style was updated.',
multiple: `✅ Settings were saved and ${counter.customize} style was updated.`,
},
layers: {
empty: '🥰 You must select at least 1 layer. Yea...',
},
cancelSettings: {
empty: '🥺 Nothing was changed, everything is as before.',
},
clearCache: {
empty: '🧹 Cleaned saved settings from cache.',
},
};
};

export const showNofication = (
counter,
counter = 0,
messages: any = { empty: '', single: undefined, multiple: '' },
notificationTimeout: number,
) => {
Expand Down
6 changes: 1 addition & 5 deletions src/code/modules/styler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,7 @@ export class Styler {
this.getLocalStylesCommand = addAffixTo(ucFirst(styleType), 'getLocal', 'Styles');
}

applyStyle = (layer: SceneNode, style: BaseStyle, oldLayerName: string = layer.name) => {
// if (oldLayerName !== layer.name && this.isPropEmpty(layer)) {
// return;
// }

applyStyle = (layer: SceneNode, style: BaseStyle) => {
if (!style || layer[this.layerStyleID] === undefined || layer[this.layerStyleID] === style.id) {
console.log(`Apply: ${this.layerStyleID} not found || No style found for ${layer.name}`);
return;
Expand Down
118 changes: 35 additions & 83 deletions src/code/modules/styles.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,12 @@ export const getAllLocalStyles = (): BaseStyle[] => {

export const updateStyleNames = (currentConfig: Config, newConfig: Config) => {
const { allStylers } = currentConfig;
const { notificationTimeout } = newConfig;

allStylers.map((styler) => {
const styles = styler.getLocalStyles();
if (!styles) {
if (isArrayEmpty(styles)) {
showNofication(0, messages(counter).customize, notificationTimeout);
return;
}

Expand All @@ -26,19 +28,16 @@ export const updateStyleNames = (currentConfig: Config, newConfig: Config) => {
return;
}

const { name, prefix: currentPrefix, suffix: currentSuffix, layerPropType } = styler;
const { name } = styler;
const newPrefix = newConfig[name].prefix;
const newSuffix = newConfig[name].suffix;
const styleType = checkStyleType(style, currentConfig);

if (newPrefix !== currentPrefix) {
style.name = styler.replacePrefix(style.name, newPrefix);
}
if (newSuffix !== currentSuffix) {
style.name = styler.replaceSuffix(style.name, newSuffix);
}
style.name = styler.replaceAffix(style.name, newPrefix, newSuffix);
counter.customize++;
});
});

showNofication(counter.customize, messages(counter).customize, notificationTimeout);
};

export const changeAllStyles = (config) => {
Expand All @@ -51,23 +50,22 @@ export const changeAllStyles = (config) => {
updateUsingLocalStyles,
} = config;
const layers = cleanSelection();
const layersLength = layers.length;

if (layersLength === 0) {
showNofication(layersLength, messages(counter).layers, notificationTimeout);
if (isArrayEmpty(layers)) {
showNofication(0, messages(counter).layers, notificationTimeout);
return;
}

const layersLength = layers.length;
layers.map(async (layer, layerIndex) => {
let stylers = allStylers;
const oldLayerName = layer.name;

if (layer.type === 'TEXT') {
await figma.loadFontAsync(layer.fontName as FontName);

if (layer.name[0] !== '+') {
if (layer.name[0] === '-') {
stylers = texterOnly;
} else {
layer.name = layer.name.slice(1);
}
}
Expand All @@ -87,7 +85,7 @@ export const changeAllStyles = (config) => {

// apply
else if (CMD === 'apply-all-styles') {
styler.applyStyle(layer, styleNameMatch, oldLayerName);
styler.applyStyle(layer, styleNameMatch);
showNotificationAtArrayEnd('applied', notificationOptions);
}

Expand All @@ -101,6 +99,8 @@ export const changeAllStyles = (config) => {
else if (CMD.includes('remove')) {
styler.removeStyle(layer, styleIdMatch);
showNotificationAtArrayEnd('removed', notificationOptions);
} else {
figma.closePlugin('🤷‍♂️ This should not happen. Nothing was changed...');
}
});

Expand All @@ -110,6 +110,13 @@ export const changeAllStyles = (config) => {

export const extractAllStyles = async (config) => {
const { allStylers, framesPerSection, textsPerSection, notificationTimeout } = config;

if (isArrayEmpty(getAllLocalStyles())) {
showNofication(0, messages(counter).extracted, notificationTimeout);
return;
}

// preparing the template
const horizFlow: any = {
layoutProps: { layoutMode: 'HORIZONTAL', itemSpacing: 32 },
};
Expand All @@ -126,6 +133,9 @@ export const extractAllStyles = async (config) => {
const miscContainer = createFrameLayer('misc', mainContainer, vertFlow);

let createdLayers = [];
let newSection: FrameNode;
let textCount = 0;
let miscCount = 0;

for (let styler of allStylers) {
const styles = styler.getLocalStyles();
Expand All @@ -134,8 +144,7 @@ export const extractAllStyles = async (config) => {
return;
}

let newSection;
const promise = styles.map(async (style, index) => {
const promise = styles.map(async (style) => {
if (style.type !== styler.styleType || checkStyleType(style, config) !== styler.layerPropType) {
return;
}
Expand All @@ -144,91 +153,34 @@ export const extractAllStyles = async (config) => {
let layerMatch = createdLayers.find((layer) => layer.name === styleWithoutAffix);

if (!layerMatch && style.type === 'TEXT') {
index % textsPerSection === 0
? (newSection = createFrameLayer('section', textContainer, vertFlow))
: newSection;
if (textCount % textsPerSection === 0) {
newSection = createFrameLayer('section', textContainer, vertFlow);
}

textCount++;
layerMatch = await createTextLayer(styleWithoutAffix, newSection, { color: colors.black });
createdLayers.push(layerMatch);
}
//
else if (!layerMatch) {
if (index % framesPerSection === 0) {
if (miscCount % framesPerSection === 0) {
newSection = createFrameLayer('section', miscContainer, horizFlow);
}

miscCount++;
layerMatch = createFrameLayer(styleWithoutAffix, newSection, { size: 80, color: colors.white });
createdLayers.push(layerMatch);
}

styler.applyStyle(layerMatch, style);
counter.extracted++;
});

await Promise.all(promise);
}

ungroupToCanvas(createdLayers);

figma.closePlugin();
return;
figma.viewport.scrollAndZoomIntoView(createdLayers);
showNofication(counter.extracted, messages(counter).extracted, notificationTimeout);
};

// export const extractAllStyles = async (config) => {
// const { framesPerRow, notificationTimeout } = config;
// const styles = getAllLocalStyles();

// const selection = [];
// const styleguides = getStyleguides(styles);

// if (styleguides.length > 0) {
// const styleguidesByType = groupBy(styleguides, 'type');

// const mainContainer = createFrameLayer({
// layoutProps: { layoutMode: 'HORIZONTAL', itemSpacing: 128 },
// });

// if (styleguidesByType.TEXT) {
// const textsContainer = createFrameLayer({
// layoutProps: { layoutMode: 'VERTICAL', itemSpacing: 32 },
// parent: mainContainer,
// });

// await Promise.all(
// styleguidesByType.TEXT.map(async (styleguide) => {
// const newLayer = await createTextLayer({
// characters: styleguide.name,
// color: colors.black,
// parent: textsContainer,
// });

// selection.push(newLayer);
// counter.extracted++;
// }),
// );
// }

// if (styleguidesByType.FRAME) {
// const visualsContainer = createFrameLayer({
// layoutProps: { layoutMode: 'VERTICAL', itemSpacing: 32 },
// parent: mainContainer,
// });

// chunk(styleguidesByType.FRAME, framesPerRow).map((styleguides) => {
// const chunkContainer = createFrameLayer({
// layoutProps: { layoutMode: 'HORIZONTAL', itemSpacing: 32 },
// parent: visualsContainer,
// });

// styleguides.map((styleguide) => {
// const newLayer = createFrameLayer({ name: styleguide.name, size: 80, parent: chunkContainer });

// selection.push(newLayer);
// counter.extracted++;
// });
// });
// }
// }
// ungroupToCanvas(selection);

// // showNofication(counter.extracted, messages.extracted, notificationTimeout);
// };

0 comments on commit ee7888d

Please sign in to comment.