Skip to content

Commit

Permalink
Clean up and code readability improvements (#57)
Browse files Browse the repository at this point in the history
  • Loading branch information
marcomontalbano committed Aug 26, 2020
1 parent fcd2b02 commit bc109c2
Show file tree
Hide file tree
Showing 32 changed files with 668 additions and 497 deletions.
4 changes: 3 additions & 1 deletion .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,9 @@ module.exports = {
ecmaVersion: 2018,
},
rules: {
indent: ['error', 4],
indent: ['error', 4, {
SwitchCase: 1,
}],
'max-len': ['error', 160],
'no-unused-expressions': 'off',
'chai-friendly/no-unused-expressions': 'error',
Expand Down
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@ lerna-debug.log
*.tsbuildinfo

/.figmaexportrc.js
/.figmaexportrc.ts
2 changes: 1 addition & 1 deletion lint-staged.config.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
module.exports = {
'!(*.d).{js,ts}': () => ['yarn lint --fix', 'yarn coverage'],
'!(*.d).{js,ts}': () => ['yarn lint --fix', 'yarn coverage', 'git add .'],
};
4 changes: 2 additions & 2 deletions packages/cli/src/commands/components.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { Command, flags as commandFlags } from '@oclif/command';

import * as figmaExport from '@figma-export/core';
import { FigmaExport } from '@figma-export/types';
import * as FigmaExport from '@figma-export/types';

import fs = require('fs');
import path = require('path');
Expand Down Expand Up @@ -51,7 +51,7 @@ class ComponentsCommand extends Command {
token: process.env.FIGMA_TOKEN || '',
onlyFromPages: page,
transformers: requirePackages<FigmaExport.StringTransformer>(transformer),
outputters: requirePackages<FigmaExport.Outputter>(outputter, { output }),
outputters: requirePackages<FigmaExport.ComponentOutputter>(outputter, { output }),
log: (message: string) => { spinner.text = message; },
}).then(() => {
spinner.stop();
Expand Down
12 changes: 6 additions & 6 deletions packages/cli/src/commands/use-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,12 @@ class UseConfigCommand extends Command {
spinner.start();

switch (commandName) {
case 'components':
return handlePromise(figmaExport.components, options);
case 'styles':
return handlePromise(figmaExport.styles, options);
default:
throw new Error(`Command ${commandName} is not found.`);
case 'components':
return handlePromise(figmaExport.components, options);
case 'styles':
return handlePromise(figmaExport.styles, options);
default:
throw new Error(`Command ${commandName} is not found.`);
}
}));
}
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/lib/_config.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { FigmaExport } from '@figma-export/types';
import * as FigmaExport from '@figma-export/types';
import * as Figma from 'figma-js';

const svg = {
Expand Down
10 changes: 3 additions & 7 deletions packages/core/src/lib/export-components.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,14 @@
import { FigmaExport } from '@figma-export/types';
import * as FigmaExport from '@figma-export/types';
import { Document } from 'figma-js';

import {
getClient,
getPages,
enrichPagesWithSvg,
} from './figma';
import { getClient, getPages, enrichPagesWithSvg } from './figma';

type Options = {
token: string;
fileId: string;
onlyFromPages?: string[];
transformers?: FigmaExport.StringTransformer[];
outputters?: FigmaExport.Outputter[];
outputters?: FigmaExport.ComponentOutputter[];
log?: (msg: string) => void;
}

Expand Down
86 changes: 86 additions & 0 deletions packages/core/src/lib/export-styles.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
import sinon from 'sinon';
import { expect } from 'chai';

import * as Figma from 'figma-js';

import * as FigmaExport from './figma';

import { styles as exportStyles } from './export-styles';

import file from './_mocks_/figma.files.json';
import fileNodes from './_mocks_/figma.fileNodes.json';

const nodeIds = Object.keys(fileNodes.nodes);

describe('export-styles', () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let logger: sinon.SinonSpy<any[], any>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let outputter: sinon.SinonSpy<any[], any>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let clientFileNodes: sinon.SinonStub<any[], any>;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let clientFile: sinon.SinonStub<any[], any>;

let client: Figma.ClientInterface;

beforeEach(() => {
logger = sinon.spy();
outputter = sinon.spy();

clientFile = sinon.stub().resolves({ data: file });
clientFileNodes = sinon.stub().resolves({ data: fileNodes });

client = {
...({} as Figma.ClientInterface),
file: clientFile,
fileNodes: clientFileNodes,
};

sinon.stub(FigmaExport, 'getClient').returns(client);
});

afterEach(() => {
sinon.restore();
});

it('should use outputter to export styles', async () => {
const pagesWithSvg = await exportStyles({
fileId: 'fileABCD',
token: 'token1234',
log: logger,
outputters: [outputter],
});

expect(FigmaExport.getClient).to.have.been.calledOnceWithExactly('token1234');
expect(clientFileNodes).to.have.been.calledOnceWith('fileABCD', { ids: nodeIds });
expect(clientFile).to.have.been.calledOnceWithExactly('fileABCD');

expect(logger).to.have.been.calledTwice;
expect(logger.firstCall).to.have.been.calledWith('fetching styles');
expect(logger.secondCall).to.have.been.calledWith('parsing styles');

expect(outputter).to.have.been.calledOnceWithExactly(pagesWithSvg);
});

it('should use default "logger" if not defined', async () => {
await exportStyles({
fileId: 'fileABCD',
token: 'token1234',
});

/* eslint-disable no-console */
expect(console.log).to.have.been.calledTwice;
expect((console.log as sinon.SinonSpy<unknown[], unknown>).firstCall).to.have.been.calledWith('fetching styles');
expect((console.log as sinon.SinonSpy<unknown[], unknown>).secondCall).to.have.been.calledWith('parsing styles');
});

it('should throw an error if fetching styles fails', async () => {
clientFile.returns({});

await expect(exportStyles({
fileId: 'fileABCD',
token: 'token1234',
})).to.be.rejectedWith(Error, '\'styles\' are missing.');
});
});
21 changes: 9 additions & 12 deletions packages/core/src/lib/export-styles.ts
Original file line number Diff line number Diff line change
@@ -1,39 +1,36 @@
import { FigmaExport } from '@figma-export/types';
import * as FigmaExport from '@figma-export/types';

import { getClient } from './figma';
import { fetchStyles, parseFigmaStyles } from './figmaStyles';
import { fetchStyles, parseStyles } from './figmaStyles';

type Options = {
token: string;
fileId: string;
onlyFromPages?: string[];
transformers?: FigmaExport.StringTransformer[];
outputters?: FigmaExport.Outputter[];
// transformers?: FigmaExport.StringTransformer[];
outputters?: FigmaExport.StyleOutputter[];
log?: (msg: string) => void;
}

export const styles = async ({
token,
fileId,
// transformers = [],
// outputters = [],
outputters = [],
log = (msg): void => {
// eslint-disable-next-line no-console
console.log(msg);
},
}: Options): Promise<number[]> => {
}: Options): Promise<FigmaExport.Style[]> => {
const client = getClient(token);

log('fetching styles');
const styleNodes = await fetchStyles(client, fileId);

log('parsing styles');
// TODO: convert figma Styles to CSS Like
const parsedStyles = await parseFigmaStyles(styleNodes);
console.log(JSON.stringify(parsedStyles, undefined, 4));
const parsedStyles = await parseStyles(styleNodes);

// TODO: send the parsed style to outputter
// await Promise.all(outputters.map((outputter) => outputter(parsedStyles)));
await Promise.all(outputters.map((outputter) => outputter(parsedStyles)));

return [];
return parsedStyles;
};
2 changes: 1 addition & 1 deletion packages/core/src/lib/figma.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import * as Figma from 'figma-js';

import { basename, dirname } from 'path';
import { FigmaExport } from '@figma-export/types';
import * as FigmaExport from '@figma-export/types';

import {
toArray,
Expand Down
Loading

0 comments on commit bc109c2

Please sign in to comment.