Skip to content

Commit

Permalink
Improved generation of opacity attributes
Browse files Browse the repository at this point in the history
  • Loading branch information
PKief committed May 25, 2018
1 parent 58d7a73 commit ca788af
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 5 deletions.
24 changes: 21 additions & 3 deletions src/icons/generator/iconOpacity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,13 @@ export const setIconOpacity = (opacity: string) => {
const svgRootElement = getSVGRootElement(svg);
if (!svgRootElement) return;

const updatedRootElement = addOpacityAttribute(svgRootElement, opacity);
let updatedRootElement: string;
if (+opacity !== 1) {
updatedRootElement = addOpacityAttribute(svgRootElement, opacity);
} else {
// if the opacity equals 1 then remove the attribute
updatedRootElement = removeOpacityAttribute(svgRootElement);
}
const updatedSVG = svg.replace(/<svg[^>]*>/, updatedRootElement);

fs.writeFileSync(svgFilePath, updatedSVG);
Expand All @@ -50,8 +56,7 @@ export const setIconOpacity = (opacity: string) => {
* @param opacity Opacity value
*/
export const validateOpacityValue = (opacity: string) => {
const pattern = new RegExp(/^([0]?\.\d+)|(1(.0)?)$/);
return pattern.test(opacity);
return +opacity >= 0 && +opacity <= 1;
};

/**
Expand Down Expand Up @@ -81,3 +86,16 @@ const addOpacityAttribute = (svgRoot: string, opacity: string) => {
return svgRoot.replace(/^<svg/, `<svg opacity="${opacity}"`);
}
};

/**
* Remove the opacity attribute of the SVG icon.
* @param svgRoot Root element of the SVG icon.
*/
const removeOpacityAttribute = (svgRoot: string) => {
const pattern = new RegExp(/\sopacity="[\d.]+"/);
// check if the opacity attribute exists
if (pattern.test(svgRoot)) {
return svgRoot.replace(pattern, '');
}
return svgRoot;
};
1 change: 1 addition & 0 deletions src/icons/generator/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,4 @@ export * from './folderGenerator';
export * from './languageGenerator';
export * from './constants';
export * from './jsonGenerator';
export * from './iconOpacity';
3 changes: 1 addition & 2 deletions src/icons/generator/jsonGenerator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,7 @@ import { fileIcons } from '../fileIcons';
import { folderIcons } from '../folderIcons';
import { languageIcons } from '../languageIcons';
import { iconJsonName } from './constants';
import { setIconOpacity } from './iconOpacity';
import { generateFolderIcons, getFileIconDefinitions, getFolderIconDefinitions, getLanguageIconDefinitions } from './index';
import { generateFolderIcons, getFileIconDefinitions, getFolderIconDefinitions, getLanguageIconDefinitions, setIconOpacity } from './index';

/**
* Generate the complete icon configuration object that can be written as JSON file.
Expand Down

0 comments on commit ca788af

Please sign in to comment.