Skip to content
This repository was archived by the owner on Aug 26, 2021. It is now read-only.
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,11 @@
"name": "Adam Zerella",
"email": "hello@adamzerella.com",
"url": "https://adamzerella.com/"
},
{
"name": "Michael Arthur",
"email": "michael@jumblesoft.co.nz",
"url": "https://github.com/mikey0000"
}
],
"license": "MIT",
Expand Down
10 changes: 9 additions & 1 deletion packages/pancake-svg/.babelrc
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
{
"presets": ["@babel/preset-env"],
"presets": [
[
"@babel/preset-env", {
"targets": {
"node": "current"
}
}
]
]
}
15 changes: 11 additions & 4 deletions packages/pancake-svg/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@gov.au/pancake-svg",
"version": "1.2.0",
"version": "1.2.1",
"description": "A Pancake plugin to generate svg sprites and png fallbacks.",
"keywords": [
"npm",
Expand All @@ -17,7 +17,7 @@
"engines": {
"npm": ">=6.0.0"
},
"main": "./dist/pancake.js",
"main": "./lib/pancake.js",
"scripts": {
"prepublish": "npm run build && npm run test",
"build": "npm run build:js",
Expand Down Expand Up @@ -46,8 +46,10 @@
],
"dependencies": {
"@gov.au/pancake": "~1",

"babel-runtime": "6.26.0"
"babel-runtime": "6.26.0",
"svg-sprite": "^1.5.0",
"svg-to-img": "^2.0.9",
"svgo": "^1.3.2"
},
"devDependencies": {
"@babel/cli": "^7.2.3",
Expand Down Expand Up @@ -77,6 +79,11 @@
"name": "Dominik Wilkowski",
"email": "hi@dominik-wilkowski.com",
"url": "https://dominik-wilkowski.com/"
},
{
"name": "Michael Arthur",
"email": "michael@jumblesoft.co.nz",
"url": "https://github.com/mikey0000"
}
],
"license": "MIT"
Expand Down
81 changes: 14 additions & 67 deletions packages/pancake-svg/src/pancake.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* Move SVGs and generate SVG sprites and fallback PNGs
*
* @repo - https://github.com/govau/pancake
* @author - Dominik Wilkowski
* @author - Michael Arthur
* @license - https://raw.githubusercontent.com/govau/pancake/master/LICENSE (MIT)
*
**************************************************************************************************************************************************************/
Expand All @@ -23,7 +23,9 @@ const Fs = require( 'fs' );
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
// Module imports
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
const { Log, Style, Loading, CopyFile, ReadFile, WriteFile } = require( '@gov.au/pancake' );

import { Log, Style, Loading, CopyFile, ReadFile, WriteFile } from '@gov.au/pancake';
import { CompileAllSvgs } from './svg';


//--------------------------------------------------------------------------------------------------------------------------------------------------------------
Expand Down Expand Up @@ -95,21 +97,24 @@ module.exports.pancake = ( version, modules, settings, GlobalSettings, cwd ) =>
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
let compiledAll = []; //for collect all promises


//--------------------------------------------------------------------------------------------------------------------------------------------------------------
// Iterate over each module
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
for( const modulePackage of modules ) {
Log.verbose(`SVG: Building ${ Style.yellow( modulePackage.name ) }`);

//check if there are svg files
const sassModulePath = Path.normalize(`${ modulePackage.path }/${ modulePackage.pancake['pancake-module'].svg.path }`);

if( !Fs.existsSync( sassModulePath ) ) {
Log.verbose(`SVG: No SVG found in ${ Style.yellow( sassModulePath ) }`)
let svgModulePath;
if( modulePackage.pancake['pancake-module'].svg !== undefined ) {
svgModulePath = Path.normalize(`${ modulePackage.path }/${ modulePackage.pancake['pancake-module'].svg.path }`);
}
if( !Fs.existsSync( svgModulePath ) ) {
Log.verbose(`SVG: No SVG found in ${ Style.yellow( modulePackage.name ) }`);
}
else {
Log.verbose(`SVG: ${ Style.green('⌘') } Found SVG files in ${ Style.yellow( sassModulePath ) }`);
Log.verbose(`SVG: ${ Style.green('⌘') } Found SVG files in ${ Style.yellow( svgModulePath ) }`);

compiledAll.push(Promise.resolve(svgModulePath));
}
}

Expand All @@ -122,66 +127,8 @@ module.exports.pancake = ( version, modules, settings, GlobalSettings, cwd ) =>
}
else {

//get all svgs
const svgs = Fs
.readdirSync( SVGModulePath ) //read all files in the svg folder
.filter( name => !name.startsWith('.') ) //let’s hide hidden files
.map( name => Path.normalize(`${ SVGModulePath }/${ name }`) ); //making them absolute paths

//convert svg to png
if( SettingsSVG.pngs !== false ) {
Log.verbose(`Converting svgs to PNGs for ${ Style.yellow( modulePackage.name ) }`);

const location = Path.normalize(`${ pkgPath }/${ SettingsSVG.pngs }/`);

CreateDir( location ); //create directory

console.log = text => {}; //temporarily display console

compiledAll.push( SvgToPng.convert( svgs, location ) );

console.log = function( text ) { //enable again
process.stdout.write(`${ Util.format.apply( null, arguments ) }\n`);
};
}

//create svg sprite
if( SettingsSVG.name !== false ) {
Log.verbose(`Converting svgs to sprite for ${ Style.yellow( modulePackage.name ) }`);

const location = Path.normalize(`${ pkgPath }/${ SettingsSVG.location }/${ SettingsSVG.name }`);

// console.log(SvgGenerator);

SvgGenerator.spriteFromFiles([ SVGModulePath, location ])
.then(function (rs) {
console.log(rs);
});

// console.log(result);

// const spriter = new SVGSpriter({
// dest: location,
// });

// svgs.map( svg => {
// spriter.add( svg, null, Fs.readFileSync( svg, { encoding: 'utf-8' } ) );
// });

// spriter.compile( ( error, result ) => {
// console.log(result);
// // for (var mode in result) {
// // for (var resource in result[mode]) {
// // mkdirp.sync(path.dirname(result[mode][resource].path));
// // fs.writeFileSync(result[mode][resource].path, result[mode][resource].contents);
// // }
// // }
// });
}


//after all files have been compiled and written
Promise.all( compiledAll )
CompileAllSvgs(compiledAll, SETTINGS.svg, cwd)
.catch( error => {
Loading.stop('pancake-svg'); //stop loading animation

Expand Down
123 changes: 123 additions & 0 deletions packages/pancake-svg/src/svg.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
/***************************************************************************************************************************************************************
*
* Generate and compile SVG's
*
* @repo - https://github.com/govau/pancake
* @author - Michael Arthur
* @license - https://raw.githubusercontent.com/govau/pancake/master/LICENSE (MIT)
*
**************************************************************************************************************************************************************/


//--------------------------------------------------------------------------------------------------------------------------------------------------------------
// Dependencies
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
import Path from 'path';
import fs from 'fs';
import SVGSpriter from 'svg-sprite';
import { from as svgToImgFrom } from 'svg-to-img';
import {promisify} from 'util';

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note: this is available since node v8

const readdir = promisify(fs.readdir);

//--------------------------------------------------------------------------------------------------------------------------------------------------------------
// Included modules
//--------------------------------------------------------------------------------------------------------------------------------------------------------------
import { Log, ReadFile, WriteFile, CreateDir } from '@gov.au/pancake';


export const SvgToPng = async (svgs, location) => {
await CreateDir(location);

svgs.map(async svg => {
const png = await ReadFile( svg, { encoding: 'utf-8' } );
svgToImgFrom(png).to({
type: 'png',
path: Path.join(location, Path.basename(svg, '.svg') + '.png')
});
});
};


export const CompileAllSvgs = ( compiledAll, SettingsSVG, pkgPath ) => {
return new Promise( ( resolve, reject ) => {
Promise.all( compiledAll )
.catch( error => {
Log.error(`SVG: Compiling SVG ran into an error: ${ error }`);
})
.then(async ( svgModulePath ) => {

//get all svgs
const svglist = await readdir( `${svgModulePath}` ); //read all files in the svg folder
const svgs = svglist.filter( name => !name.startsWith('.') ) //let’s hide hidden files
.map( name => Path.normalize(`${ svgModulePath }/${ name }`) ); //making them absolute paths

//convert svg to png
if( SettingsSVG.pngs !== false ) {
Log.verbose(`SVG: Converting svgs to PNGs`);

const location = Path.normalize(`${ pkgPath }/${ SettingsSVG.pngs }/`);

SvgToPng( svgs, location );

}

//create svg sprite
if( SettingsSVG.name !== false ) {

const location = Path.normalize(`${ pkgPath }/${ SettingsSVG.location }/`);

const spriter = new SVGSpriter({
dest: location,
log: null, // Logging verbosity (default: no logging),
shape: { // SVG shape related options
id: { // SVG shape ID related options
separator: '--', // Separator for directory name traversal
generator: (name) => (name.split('.')[0]), // SVG shape ID generator callback
pseudo: '~' // File name separator for shape states (e.g. ':hover')
},
transform: ['svgo'], // List of transformations / optimizations
meta: null, // Path to YAML file with meta / accessibility data
align: null, // Path to YAML file with extended alignment data
dest: 'opt' // Output directory for optimized intermediate SVG shapes
},
svg: { // General options for created SVG files
xmlDeclaration: true, // Add XML declaration to SVG sprite
doctypeDeclaration: true, // Add DOCTYPE declaration to SVG sprite
namespaceIDs: true, // Add namespace token to all IDs in SVG shapes
namespaceClassnames: true, // Add namespace token to all CSS class names in SVG shapes
dimensionAttributes: true // Width and height attributes on the sprite
},
variables: {}, // Custom Mustache templating variables and functions
mode: {
symbol: {
sprite: SettingsSVG.name,
},
shapes: false
}
});
Log.verbose(`SVG: Adding sprites to the sprite machine`);
svgs.map(svg => {
spriter.add( svg, null, fs.readFileSync( svg, { encoding: 'utf-8' } ) );
});

Log.verbose(`SVG: Compile sprites into spritesheet`);
spriter.compile( async ( error, result ) => {
if( error ) {
Log.error( error );
return reject( error );
}

for (let mode in result) {
for (let resource in result[mode]) {
await WriteFile(result[mode][resource].path, result[mode][resource].contents);
}
}

resolve( true );


});
}
});
});
};
Loading