Git Product home page Git Product logo

grunticon's Introduction

⚠️ This project is archived and the repository is no longer maintained.

Grunticon Build Status

         /'
        //
    .  //
    |\//7
   /' " \
  .   . .
  | (    \
  |  '._  '
  /    \'-'

Filament Group

A mystical CSS icon solution

grunticon is a Grunt.js task that makes it easy to manage icons and background images for all devices, preferring HD (retina) SVG icons but also provides fallback support for standard definition browsers, and old browsers alike. From a CSS perspective, it's easy to use, as it generates a class referencing each icon, and doesn't use CSS sprites.

grunticon takes a folder of SVG/PNG files (typically, icons that you've drawn in an application like Adobe Illustrator), and outputs them to CSS in 3 formats: svg data urls, png data urls, and a third fallback CSS file with references to regular png images, which are also automatically generated and placed in a folder.

grunticon also generates a small bit of JavaScript to drop into your site, which asynchronously loads the appropriate icon CSS depending on a browser's capabilities, and a preview HTML file with that loader script in place.

You can see a demonstration of the output here.

Version 2.0 updates

With Grunticon version 2.0, we've added the enhanceSVG option which allows you to easily style and animate your SVGs with CSS or add interactivity with JavaScript. Standard Grunticons are static background images that can't be styled or scripted because SVG only supports this ability if the SVG data is in the HTML document. In 2.0, you can now choose which icons you want to "enhance" and the new loader script will copy the icon SVG paths from the cached Grunticon stylesheet and inject them as an embedded SVG element for you to script and style as needed. This allows us to offer the best of both worlds: the full power of embedded SVGs but with none the wasted bandwidth of including SVGs in your page markup.

Remember that only browsers that support SVGs will see these effects so use them only for "enhancements" that don't break the experience when not present. Embedding icons also has some degree of execution overhead so we recommend using this feature sparingly: only embed an icon if you need to apply style or scripting, otherwise use the classic background-image icon.

To start - in your Gruntfile.js, set the value for enhanceSVG to true so the loader will parse the markup for icons that should be embedded at runtime:

grunticon: {
  foo: {
    files: {
      // Handle files here
    },
    options: {
      // Handle your options as you normally would here
      enhanceSVG: true
    }
  }
}

Then, make sure you get the new loader that's produced for you when you run grunt (it should be in the same place as before) and inline that script in the <head>.

Just after the loader, you'll need to call grunticon and pass your 3 CSS file paths to it as usual. Additionally though, you'll want to add a fourth argument to kick off the SVG embedding, which we've pre-defined for you as grunticon.svgLoadedCallback. In all, your call to grunticon will now look something like this:

grunticon(["icons.data.svg.css", "icons.data.png.css", "icons.fallback.css"], grunticon.svgLoadedCallback );

After you've done this, you can have any icon embedded in the page and ready for styling just by adding a data-grunticon-embed attribute.

<div class="icon-burger alt" data-grunticon-embed></div>

Once the loader runs, the SVG will be embedded:

<div style="background-image: none;" class="icon-burger alt">
  <svg class="svg-source" xmlns="http://www.w3.org/2000/svg" width="32" height="30" viewBox="170.6 12.6 32 30" enable-background="new 170.6 12.6 32 30">
    <g class="hamburger">
      <path class="buns" fill="#DDAF6D" d="M188.6 12.6h-4c-5.5 0-13 4.5-13 10v1c0 .6.4 1 1 1h28c.6 0 1-.4 1-1v-1c0-5.5-7.5-10-13-10zm-17 28c0 1.1.9 2 2 2h26c1.1 0 2-.9 2-2v-2h-30v2z">
      </path>
      <path class="burger" fill="#BB6F39" d="M172.6 34.6h28c1.1 0 2 .9 2 2s-.9 2-2 2h-28c-1.1 0-2-.9-2-2s.9-2 2-2z">
      </path>
      <path class="cheese" fill="#EFC75E" d="M172.6 30.6h28v4h-2l-3 3-3-3h-20v-4z">
      </path>
      <path class="lettuce" fill="#3DB39E" d="M200.6 27.6l-28-.1v.1c-1.1.2-2 1.2-2 2.4 0 1.4 1.1 2.5 2.5 2.5 1.2 0 2.2-.9 2.4-2h4.1c0 1.1 1.1 2 2.5 2s2.5-.9 2.5-2h4c0 1.1 1.1 2 2.5 2s2.5-.9 2.5-2h4.1c.2 1.1 1.2 2 2.4 2 1.4 0 2.5-1.1 2.5-2.5 0-1.1-.9-2.1-2-2.4z">
      </path>
      <path class="tomato" fill="#BF392C" d="M172.6 24.6h28v3h-28v-3z"></path>
      <path class="shadows" fill="#C69D63" d="M172.6 24.6h2c-.6 0-1-.4-1-1v-1c0-5.5 7.5-10 13-10h-2c-5.5 0-13 4.5-13 10v1c0 .5.4 1 1 1zm1 16v-2h-2v2c0 1.1.9 2 2 2h2c-1.1 0-2-.9-2-2z">
      </path>
      <path class="burger-shadow" fill="#A86433" d="M172.6 36.6c0-1.1.9-2 2-2h-2c-1.1 0-2 .9-2 2s.9 2 2 2h2c-1.1 0-2-.9-2-2z">
      </path>
      <path fill="#37A18E" d="M172.6 30.1c0-1.2.9-2.2 2-2.4v-.1h-2v.1c-1.1.2-2 1.2-2 2.4 0 1.4 1.1 2.5 2.5 2.5.4 0 .7-.1 1-.2-.9-.4-1.5-1.3-1.5-2.3zm9 .5h-2c0 1.1 1.1 2 2.5 2 .4 0 .7-.1 1-.2-.9-.3-1.5-1-1.5-1.8zm9 0h-2c0 1.1 1.1 2 2.5 2 .4 0 .7-.1 1-.2-.9-.3-1.5-1-1.5-1.8zm9 0h-2c.2 1.1 1.2 2 2.4 2 .4 0 .7-.1 1-.2-.7-.4-1.2-1-1.4-1.8z" class="lettuce-shadow">
      </path>
    </g>
  </svg>
</div>

Now, style appropriately:

  .icon-burger {
    width: 32px;
    height: 30px;
    display: inline-block;
  }
  .icon-burger.alt .cheese {
    fill: red;
  }
  .icon-burger.alt .buns {
    fill: orange;
  }
  .icon-burger.alt .burger {
    fill: yellow;
  }
  .icon-burger.alt .lettuce {
    fill: green;
  }

And voila! Styled SVG icons!

Check out our example at http://filamentgroup.github.io/grunticon/example/output/preview.html

Also: How to use SVG Embedding across domains

If you're hosting your grunticon CSS on a different domain than your HTML, you will need to do a little extra configuration to use SVG Embedding.

  1. Set the corsEmbed option to true in your gruntfile. This adds a little extra scripting to the grunticon loader so that it can make a cross-domain request.
  2. Once that's in, change the callback at the end of your grunticon call to reference svgLoadedCORSCallback instead of the one listed above.
  3. That might be enough, but if not, you'll need to enable cross-domain requests on the server where the CSS is hosted. Here's how that looks in Apache .htaccess for example:
<IfModule mod_headers.c>
    Header add Access-Control-Allow-Origin "*"
</IfModule>

(That "*" can be a particular domain if you want)

Getting Started

This plugin requires Grunt ~0.4.2

If you haven't used Grunt before, be sure to check out the Getting Started guide, as it explains how to create a Gruntfile as well as install and use Grunt plugins. You might also check out Chris Coyier’s great article, Grunt for People Who Think Things Like Grunt are Weird and Hard.

Once you're familiar with that process, you may install this plugin with this command:

npm install grunt-grunticon --save-dev

Once the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript:

grunt.loadNpmTasks('grunt-grunticon');

The "grunticon" task

For a brief overview of the Grunticon workflow, particularly from a designer's perspective, you might check out Todd Parker's article, A Designer’s Guide to Grumpicon, which covers basic SVG workflow tips for both Grunticon and Grumpicon.

Required configuration properties

grunticon has a files object that needs to be filled in order to run, this files object currently requires that a cwd, and a dest dir are placed, and therefore will blow up without it. This will be fixed to better fit the pattern set by Grunt for this.

These can be set in your Gruntfile.js config file. Grunticon is a multitask, making it easy to create as many export batches as you'd like. Just create one or more custom named objects within the grunticon object, and configure Grunticon options within it, like so:

grunticon: {
	myIcons: {
		files: [{
			expand: true,
			cwd: 'example/source',
			src: ['*.svg', '*.png'],
			dest: "example/output"
		}],
		options: {
		}
	}
}

IMPORTANT NOTE: grunticon will overwrite any files in the dest directory if they are of the same name as a file that grunticon needs to create. For easiest results, you can set dest to a folder that does not yet exist in your directory and grunticon will create that folder, or set it to an existing folder and be sure to configure grunticon to create file names that do not already exist in that folder.

With these configuration properties set, you can add grunticon to your default tasks list. That'll look something like this:

grunt.registerTask('default', ['jshint', 'qunit', 'concat', 'uglify', 'grunticon:myIcons']);

grunticon will now batch your icons whenever you run grunt.

Options

options.datasvgcss

Type: String Default value: "icons.data.svg.css"

The name of the generated CSS file containing SVG data uris.

options.datapngcss

Type: String Default value: "icons.data.png.css"

The name of the generated CSS file containing PNG data uris

options.urlpngcss

Type: String Default value: "icons.fallback.css"

The name of the generated CSS file containing external png url references.

options.previewhtml

Type: String Default value: "preview.html"

The name of the generated HTML file containing PNG data uris.

options.loadersnippet

Type: String Default value: "grunticon.loader.js"

The name of the generated text file containing the grunticon loading snippet.

options.enhanceSVG

Type: Boolean Default value: False

Include additional methods in the loader script to offer SVG embedding

options.corsEmbed

Type: Boolean Default value: False

Include additional methods in the loader script to offer cross-domain SVG embedding. options.enhanceSVG must be true for this option to be respected.

options.pngfolder

Type: String Default value: "png/"

The name of the generated folder containing the generated PNG images.

options.pngpath

Type: String Default value: value of options.pngfolder

Allows you to specify a custom URL to serve fallback PNGs at.

Example:

{
    pngpath: "/assets/icons/png"
}

Will generate PNG fallbacks like:

.icon-bar {
	background-image: url('/assets/icons/png/bar.png');
	background-repeat: no-repeat;
}

options.cssprefix

Type: String Default value: ".icon-"

a string to prefix all icon selectors with (currently only classes or ids are guaranteed to work with the preview)

options.customselectors

Type: Object

Allows you to specify custom selectors for individual files. This is in addition to the selectors generated using cssprefix + filename - extension.

Example:

{
	"foo": [".icon-bar", ".baz"]
}

will produce:

.icon-bar,
.baz,
.icon-foo {
	//css
}

You can also use an asterisk in your custom selector. The filename can be referenced with $1.

Examples:

...
customselectors: {
  "*": [".icon-$1:before", ".icon-$1-what", ".hey-$1"]
},
cssprefix: ".icon-"
...

Should give the file bear.svg the css

.icon-bear:before,
.icon-bear-what,
.hey-bear,
.icon-bear {
 // CSS THINGS
}

And if there are files bear.svg and cat.svg, the css should be like:

.icon-bear:before,
.icon-bear-what,
.hey-bear,
.icon-bear {
 // CSS THINGS
}

.icon-cat:before,
.icon-cat-what,
.hey-cat,
.icon-cat {
 // CSS THINGS
}

This should give you more flexibility with your selectors.

options.defaultWidth

Type: String Default value: "400px"

a string that MUST be defined in px that will be the size of the PNG if there is no width given in the SVG element.

options.defaultHeight

Type: String Default value: "300px"

similar to defaultWidth, but for height

options.previewTemplate

Type: String Default value: Goes to the example/preview.hbs file

Takes a path to the template that will be used for the preview.html. Example of .hbs file contents:

<!doctype HTML>
<html>
  <head>
    <title>Icons Preview!</title>
    <style>
      body {
        background-image: linear-gradient(#eee 25%, transparent 25%, transparent), linear-gradient(#eee 25%, transparent 25%, transparent), linear-gradient(transparent 75%, #eee 75%), linear-gradient(transparent 75%, #eee 75%);
        width: 100%;
        background-size: 10px 10px;
      }
    </style>
    <script>
      {{{loaderText}}}
      grunticon(["icons.data.svg.css", "icons.data.png.css", "icons.fallback.css"]);
    </script>
  <noscript><link href="icons.fallback.css" rel="stylesheet"></noscript>
  </head>
  <body>
    {{#each icons}}
      {{#with this}}
      <pre><code>{{prefix}}{{name}}:</code></pre><div class="{{prefixClass}}{{name}}" style="width: {{width}}px; height: {{height}}px;" ></div><hr/>
      {{/with}}
    {{/each}}
</body>
</html>

options.tmpPath

Type: String Default value: os.tmpDir()

Let's you specify an absolute tmp-path (options.tmpDir will still be appended).

options.tmpDir

Type: String Default value: "grunticon-tmp"

Let's you specify a tmp-folder. Useful when having multiple grunticon tasks and using grunt-concurrent.

options.template

Type: String Default value: ""

Location of a handlebars template that will allow you to structure your CSS file the way that you choose. As more data becomes available via directory-encoder, more options will be available for you to tap into during templating.

Example of .hbs file contents:

{{#each customselectors}}{{this}},{{/each}}
{{prefix}}{{name}} {
	background-image: url('{{datauri}}');
	background-repeat: no-repeat;
}

options.compressPNG

Type: Boolean Default value: false

Will compress the converted png files using optipng

options.optimizationLevel

Type: Integer Default value: 3

If compress is set to true, this will set the optimationLevel for optipng

Automating color variations

Grunticon allows you to output any icon in different colors simply by changing its filename to the following syntax: myfilename.colors-red-aa0000-gray.svg. In this example, any color names or hexidecimal values that follow colors- and are separated by a dash will be used to generate additional icons of that color. By default, each icon will be assigned a numbered class name for CSS use. You can improve the class naming conventions by defining color variables in your Gruntfile's colors option shown below. When defined, you can reference a color variable in place of a color in your file names, and the generated classes will use that variable name as well. See the Gruntfile.js's colors and dynamicColorOnly options for an example of how color automation.

A note on filesize impact: Adding color variations of an icon involves creating duplicates of that icon's SVG source in the CSS, so unfortunately, each color variation will cause an increase in filesize. However, transferring CSS with gzip compression can negate much of this filesize increase, and we highly recommend always transferring with gzip. In testing, we found that creating a color variation of every icon in our example set increased overall size by 25%, rather than 100% as a raw text duplicate would increase. That said, size increases for non-SVG-supporting browsers will be more dramatic, as the fallback PNGs will not have the heavy transfer compression as SVG enjoys. We advise using this feature on a case-by-case basis to ensure overhead is kept to a minimum.

options.colors

Allows you to predefine colors as variables that can be used in filename color configuration.

options: {
	colors: {
		myAwesomeRed: "#fc3d39",
		coolBlue: "#6950ff"
	}

options.dynamicColorOnly

Type: Boolean Default value: false

Allows you to tell directory-colorfy to ignore the original file when using colors.

For example, if given a file named like so:

bear.colors-white.svg

And dynamicColorOnly is set to true:

{
	dynamicColorOnly: true
}

Then only a single file: bear-white.svg, will be generated, rather than two: bear.svg with the original colors and bear-white.svg with white colors.

Grunticon Loader Methods

With enhanceSVG turned on, the Grunticon loader has a few exposed methods and attributes on the grunticon object that you can use:

href

Type: String

The url that is being loaded by Grunticon.

method

Type: String

Is "svg" if the page loaded the SVG-based css. Is "datapng" if the page loaded the png with datauri-based css. Is "png" if the page loaded the plain link to png-based css.

loadCSS

See: https://github.com/filamentgroup/loadcss

getCSS

Arguments: String Returns: Object

Fetch a stylesheet link by its href.

getIcons

Arguments: String Returns: Object

Takes a stylesheet node (link or style) and returns all of the icon selectors and the svgs contained within it in an object formatted in this way:

{
  grunticon:selector: "SVG Content in String"
}

embedIcons

Arguments: Object Returns: NodeList

Takes icons in the object format outputted by getIcons and then queries the page for all icons with the data-grunticon-embed attribute. For each of these that it finds, it places the SVG contents associated with the relevant selector in the icons. It then returns the NodeList of all of the elements that had SVGs embedded in them.

ready

Arguments: Function Returns: None

An alternative to listening for the DOMContentLoaded event. Takes a function as a callback and calls the function when the DOM is ready.

svgLoadedCallback

Arguments: Function Returns: None

Uses the above methods to call:

var svgLoadedCallback = function( embedComplete ){
  ready(function(){
    embedIcons(getIcons(grunticon.href));
    embedComplete();
  });
}

If embedComplete is defined, the loader will call it when SVG embedding is complete. This is true for both local and CORS embedding. So if you need to run logic after SVG markup is appended to the DOM, just pass a callback to grunticon.svgLoadedCallback or grunticon.svgLoadedCORSCallback.

Cross-domain SVG Embedding Methods

With enhanceSVG and corsEmbed turned on, the Grunticon loader has a few exposed 2 more methods and attributes on the grunticon object that you can use:

ajaxGet

Arguments: String, Function Returns: Object

First argument is a string reference to a url to request via cross-domain Ajax. Second argument is an optional callback when the request finishes loading. (In the callback, this refers to the XHR object).

svgLoadedCORSCallback

Arguments: Function Returns: None

Uses the above methods to make SVG embedding work when CSS is hosted on another domain. (CORS must be allowed on the external domain.)

Browser testing results for icon output

The generated asynchronous CSS loader script delivers an appropriate icon stylesheet depending on a device/browser's capabilities. Grunticon is supported in cases where icon fonts fail.

Browsers that render the SVG data url stylesheet:

  • IE9
  • Chrome 14+ (maybe older too?)
  • Safari 4+ (maybe older too?)
  • Firefox 3.6+ (maybe older too?)
  • Opera 15+
  • iOS 3+ Safari and Chrome
  • Android 4.0 Chrome (caveat: SVG icons do not scale in vector, but do appear to draw in high-resolution)
  • Android 4.0 ICS Browser
  • BlackBerry Playbook

Browsers that receive the PNG data url stylesheet:

  • IE8
  • All versions of Opera, Opera Mini, and Opera Mobile before Chrome integration (v 15)
  • Android 2.3 Browser
  • Android 2.2 Browser
  • Android 2.1 Browser
  • Android 1.6 Browser
  • Android 1.5 Browser

Browsers that receive the fallback png request:

  • IE7
  • IE6
  • Non-JavaScript environments

View the full support spreadsheet here. Feel free to edit it if you find anything new.

The test page can be found here.

Tips

Cleaning the cruft out of your SVGs

In earlier versions of Grunticon, we included SVGO to optimize the SVG output. In the 1.0 version, we removed this dependency to ease the installation complexity but still recommend that SVG optimization is part of the Grunticon workflow.

When producing SVGs through a tool like Illustrator, there is a lot of unnecessary markup, comments, and general code written into your SVG files. Because of that, we strongly recommend using a tool like grunt-svgmin. If run before running Grunticon, it can greatly reduce your filesizes!

Here's an example:

svgmin: {
	dist: {
		options: {
			plugins: [
				// Don't remove XML declaration (needed to avoid errors creating PNG on Win 7)
				{ removeXMLProcInst: false }
			]
		},
		files: [{
			expand: true,
			cwd: 'example/svgs',
			src: ['*.svg'],
			dest: 'example/source'
		}]
	}
},
grunticon: {
	foo: {
		files: [{
			expand: true,
			cwd: 'example/source',
			src: ['*.svg', '*.png'],
			dest: "example/output"
		}],
		options: {
		}
	}
}

The svgmin options section is only needed to avoid errors under windows and can be omitted for smaller svg files on other platforms. For a more extensive example, check out our Gruntfile example project.

Serving compressed CSS

One of the great benefits to data uris is the ability to compress the images heavily via gzip compression. Be sure to enable gzip of CSS on your server, as it'll cut your icon transfer size greatly.

Creating SVG Artwork

The workflow we've been using so far involves creating a new Illustrator file with the artboard set to the desired size of the icon you want set in the CSS.

Export the artwork by choosing File > Save as... In the dialog, choose "SVG" as the format and enter a name for the file (this wil be used as your class name later, so keep it free of any disallowed CSS class characters like ., {, (, ), etc.

In the Save SVG dialog that opens up, there are lots of options. SVG has a ton of formats, so here are a few tips we've learned.

  • SVG Profile: Seems like SVG 1.1 Tiny is really well supported across even older mobile platforms so if you have simple artwork that doesn't use gradients or opacity this will yield a smaller and more compatible graphic. If you want to use all the fancy effects, save artwork as SVG 1.1.
  • Type: Convert to outline before export.
  • Subsetting: None, I usually convert all text to outlines ahead of time
  • Images: Embed
  • Don't check "Preserve Illustrator editing" to reduce file size

Warnings

  • If your files have #, ., >, or any other css selecting character in their names, they will likely be improperly processed.

Roadmap

This repository is now using lodash style issue management for enhancements. This means enhancement issues will now be closed instead of leaving them open.

View the enhancement backlog here. Don’t forget to upvote the top comment with 👍!

Dependents and Dependencies

Release History

  • Version 2.1.0: Add ability to embed SVGs with cross-domain requested CSS files via corsEmbed option
  • Version 2.0.0: Add ability to enhance SVGs by embedding them inside of the element instead of using a background-image
  • Version 1.4.0: Add tmpPath option
  • Version 1.3.0: Add dynamicColorOnly support from directory-colorfy
  • Version 1.2.0: Update directory-encoder version, this allows the pngpath option
  • Version 1.1.0: Add previewTemplate option
  • Version 1.0.0: Some alpha and beta bugs taken care of.
  • Version 1.0.0-alpha: Almost complete rewrite. Breaking out pieces of this project into other areas. Removed SVGO and PNGCrush. SVGO is better served through the svgmin plugin.
  • Version 0.6.5: CSS Writing has been moved from Phantom to Node, in order to decrease base64 datauri sizes
  • Version 0.6.0: Grunticon now comes with PNG Crush. This will reduce the size of your PNGs
  • Version 0.5.0: Grunticon now comes with SVGO. This cleans up your SVGs, greatly reducing the size of your CSS file.
  • Version 0.4.1: Opera browsers prior to version 15 are given fallback PNG due to SVG scaling troubles.
  • Version 0.4.0: Automated filename-driven color variations were added, along with the colors option
  • Version 0.3.4: SVGs without width and height can be used
  • Version 0.3.2: Added PhantomJS as a Node dependency, easing installation
  • Version 0.3.1: Documentation updates
  • Version 0.3.0: Grunticon becomes a multitask - syntax change involved in Gruntfile
  • Version 0.2.1: Custom selectors feature added
  • Version 0.2.0: Compatibility rewrite for Grunt 0.4x
  • Version 0.1.6: Switched from base64 encoding to escaping raw SVG text in data uris. Fixes to cssprefix setting. If fallback png data uri is > 32768 chars, link to ext png instead for IE issues.

grunticon's People

Contributors

aetherpoint avatar alanburke avatar alyssais avatar andrewmaier avatar benebun avatar cromwellryan avatar cust0dian avatar danielsundman avatar davidlwarner avatar edwardgronroos avatar eschwartz avatar gitter-badger avatar jbrad avatar jefflembeck avatar jelmerdemaat avatar johnbender avatar jtbr avatar keeganstreet avatar manovotny avatar meodai avatar nschonni avatar rnarian avatar scottjehl avatar tillre avatar toddparker avatar travi avatar tylerball avatar wilto avatar zachleat avatar zigotica avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

grunticon's Issues

Multiple class names support?

Would it be possible to support multiple class names for SVG icons that look the same but are named differently?

ie. the same SVG icon with different file names will become something like:

.ico_lightbulb.off, .ico_lightbulb.disabled {
 background-image: url(...);
}

Possible to constrain size of output PNG files (when SVG is width and height 100%)?

We tend to produce our SVGs using the viewbox to size proportionally and the width and height attributes set to 100% (to allow nice scaling when the user pinch/zooms on tablets).

By default Grunticon is making these PNGs at 400px x 300px size. Is there any way to constrain this size with a setting? A width and height option would be preferable to the image can be sized proportionally based on preference.

So for example:

limit-png-width: "60px"

Does such a thing already exist? Or would it be possible to add?

allow for the ability to specify that certain icons that should remain PNG

Sometimes complex artwork is too large in file size to deliver as SVG, and a png image may be preferable. An options hash of icons that should be written to the SVG data css file as PNG data uris would be handy for this case.

// export the following icons as png data URIs only
pngOnly: [ "Home_Media.svg", "Image_Exchange.svg" ] 

Also, if it's possible, we may want to specify 2x output for HD displays.

avoid classitis and allow use with pseudo elements

Hi Scott,

As promised, here's my proposal to avoid classitis and allow use with pseudo elements: Sassify it! We're already using grunt so why not use sass/compass as well? (don't know if the following would work for LESS, too). Adding Sass to the recipe we could create a workflow as follows:

1). icons.txt:
This file will be used to hold a list of icons. Original method allows only for setting a general class for each icon, now we will be able to use whatever rule for each. We can copy the empty list into our main.scss file and we will edit the rules for each icon:

$icon-delete: ".delete, .close:after";
$icon-add: ".add:before";

We just have to make sure our icon files dont get renamed (or keep track of renames, manually) so that our main file has the correct vars.

2). the three CSS files will actually need to be created from scss as well, since we use the magic here:

svgurl.scss

{$icon-delete} { background-image: url(data:image/svg+xml;base64,… }

{$icon-add} { background-image: url(data:image/svg+xml;base64,… }

pngurl.scss

{$icon-delete} { background-image: url(data:image/png;base64,… }

{$icon-add} { background-image: url(data:image/png;base64,… }

fallback.scss

{$icon-delete} { background-image: url(png/… }

{$icon-add} { background-image: url(png/… }

3). watch/compile that will create 4 files:
icons.txt actually wont be used in production, since only holds a list of variables
svgurl.css
pngurl.css
fallback.css

I just hope this makes sense. If you find this workflow useful I can try to workaround it and send a pull request, but I wanted to know your opinion first since you created the tool and I might have missed something.

Way of processing - just PNG to DataUri

By default GruntIcon work in this way: SVG folder -> SVG(datauri) + PNG(datauri) + PNG.
In case i have no SVG files (can't draw or other reason), how can i do the same work with GruntIcon to conwert just PNG folder -> PNG(datauri) + PNG?

grunt-grunticon task is run, but nothing happens.

I am running grunt-grunticon in my project using npm. I run grunt-grunticon and it gives me the output:

Running "grunticon" task
Done, without errors.

If I change to using

grunt.loadTasks('tasks')

instead of

grunt.loadNpmTasks('grunt-grunticon');

It works great. I copied the tasks dir from the grunt project into my project folder to get this working. Any ideas? I have put log messages in different places to see what is happening, but no luck.

Grunt 0.4 Release

I'm posting this issue to let you know that we will be publishing Grunt 0.4 on Monday, February 18th.

If your plugin is not already Grunt 0.4 compatible, would you please consider updating it? For an overview of what's changed, please see our migration guide.

If you'd like to develop against the final version of Grunt before Monday, please specify "grunt": "0.4.0rc8" as a devDependency in your project. After Monday's release, you'll be able to use "grunt": "~0.4.0" to actually publish your plugin. If you depend on any plugins from the grunt-contrib series, please see our list of release candidates for compatible versions. All of these will be updated to final status when Grunt 0.4 is published.

Also, in an effort to reduce duplication of effort and fragmentation in the developer community, could you review the grunt-contrib series of plugins to see if any of your functionality overlaps significantly with them? Grunt-contrib is community maintained with 40+ contributors—we'd love to discuss any additions you'd like to make.

Finally, we're working on a new task format that doesn't depend on Grunt: it's called node-task. Once this is complete, there will be one more conversion, and then we'll never ask you to upgrade your plugins to support our changes again. Until that happens, thanks for bearing with us!

If you have any questions about how to proceed, please respond here, or join us in #grunt on irc.freenode.net.

Thanks, we really appreciate your work!

config.cssprefix defaults

When config.cssprefix === "", the CSS prefix defaults to "icon-". I would think an empty string would override the default icon-, maybe? Just me? Hello!

:D

Use external URLs in PNG data URI stylesheet if the data URI would be greater than 32,768 chars

I came across an issue today where an icon was not displaying in IE8. This icon was about 9KB as an SVG but had quite large dimensions so when rendered out as a PNG data URI it was greater than 32,768 characters. IE8 does not support data URIs longer than 32,768 characters, and therefore the image was not displayed. For an example, visit http://codepen.io/keeganstreet/full/Ltdxy in IE8.

If a developer did not know about this IE8 limitation, I imagine it could be quite difficult for them to figure out why their icon was not displaying.

Therefore I suggest that we update grunticon to count the characters in PNG data URIs, and if there are more than 32,768, it should output a link to the external URL instead of the data URI.

I have developed a fix and will submit a pull request. I’m happy to hear feedback and make changes to the fix.

Output an icon to several colors

We're looking to add a convenience shortcut for outputting a single svg file in several colors without manually creating the files for each color.

Our first attempt does this through a file naming pattern that allows for specifying various colors, like this: myicon.colors-red-#aa0000-#fff-blue.svg.

In the example output, you can see the file bear.colors-#000-red-#666.svg outputs to 3 different icons (numbered 1, 2, 3) for each color in the CSS and png fallbacks, with numbered classnames for each icon color too (svg output here).

The full commit is here. 12c338f#L10R54

Open questions

  • We thought configuring per-file would be convenient, as opposed to grunt.js configuration. Thoughts on that?
  • The class names are numbered. Ideally, we'd want control over the names that are used for each color so that the classes are more meaningful. We're looking for ideas on syntax for this.

Fatal error: spawn EACCES

Running grunticon task I always get Fatal error: spawn EACCES

I also tried to run your example. Here is the complete terminal log

Running "grunticon:foo" (grunticon) task
Look, it's a grunticon!

grunticon now minifying the stylesheet loader source.
grunticon loader file created.
grunticon now spawning phantomjs...(using path: /app/node_modules/grunt- grunticon/node_modules/phantomjs/lib/phantom/bin/phantomjs)Fatal error: spawn EACCES

I don't know if it helps but I'm on a MacBook Pro Mac OS X 10.8.4

Thanks in advance,
Adriano

css prefix missing a hyphen..

Gonna get a bit nit-picky here but...

In unicon.js:

    // css class prefix
    var cssprefix = config.cssprefix || "icon";

Shouldn't this read...

    // css class prefix
    var cssprefix = config.cssprefix || "icon-";

Just sayin'.

Grunt 0.4 src dest error

I've got grunticon setup with v 0.4 of grunt, but I keep getting this error:

Fatal error: Oops! Please provide grunticon configuration for src and dest in your grunt.js file

Anything I'm doing wrong? My Gruntfile:

module.exports = function(grunt) {

  // Project configuration.
  grunt.initConfig({

    // Grunticon settings
    grunticon: {
      options: {
        src: 'images/icons/',
        dest: 'modules/WebCommon/webcommon.war/stylesheets/icons/'
      }
    }

  });

  grunt.loadNpmTasks('grunt-grunticon');

  grunt.registerTask('icon', ['grunticon']);

};

Grunticon stuck on 'grunticon now spawning phantomjs...'

I guess this is probably not an issue with Grunticon per say, but when I run 'grunt' my grunticon task gets stuck on the message 'grunticon now spawning phantomjs...'.

The weird thing is that everything was working fine yesterday and I haven't touched the Gruntfile.js.

I have had other problems that seem to be related to phantomjs as well (I've disabled mocha as this also errors in the build process - something to do with phantomjs), but I can't seem to find any solution and as I said, grunticon was working perfectly yesterday (and on other older projects).

Any suggestions?

I'm on Mac OS X 10.8.3.

Error when creating icons

Hi,

Im getting this error when trying to run the grunticon task:

→ grunt grunticon
Running "grunticon:myIcons" (grunticon) task
Look, it's a grunticon!

grunticon now minifying the stylesheet loader source.
grunticon loader file created.
grunticon now spawning phantomjs...(using path: /Users/luismartins/Sites/idomlive2/themes/idomlive_desktop/node_modules/grunt-grunticon/node_modules/phantomjs/lib/phantom/bin/phantomjs)Fatal error: spawn ENOENT

I just installed PhantomJS using homebrew.

Any ideias of what is happening?

Files that don't follow naming conventions do not work

If a filename has a hash, period, or space in it (anything that is considered special in CSS), the CSS produced will not reference it properly.

We should either document this or get into renaming files (not so sure about that part).

Remove SASS fork from readme

Not sure if @zigotica has plans to update but grunt-grunticon-sass hasn't been touched in the better part of a year. Upon installing and trying to run grunt-grunticon-sass, #28 is thrown. Having the fork in grunticon docs is potentially confusing since the repo is broken in most recent stable grunt.

That said, if someone can point me in the direction of what needs to change for 0.4.x, I'm happy to take a stab at resolving the issue in the fork when my workload slows down a bit :)

PNGs are created but no CSS (no error message)

I'm very new (3 hours in) to Grunt so its probable I'm doing something obviously stupid. However, when I run grunt I get the generated PNGs in the output folder but no accompanying CSS files.

I get the 'Done, without errors.' message but no CSS in the output folder.

I have tried explicitly listing the outputs:

datasvgcss: "icons.data.svg.css",
            datapngcss: "icons.data.png.css",
            urlpngcss: "icons.fallback.css",

But it makes no difference. I only get the PNGs and no CSS - any ideas?

Use image file as input

Currently, only SVG files are accepted as input. But I want image files are also accepted too.

Globally install grunt-unicon

I can't seem to call the plugin from my global npm directory - is this possible?

It seemed to install ok with the -g command added. But when I "grunt" it throws the following error:

Local Npm module "grunt-unicon" not found. Is it installed?

Got it working great with a local install - but would be nice to not have to install the package on every project I want to use it ... which is pretty much every project from now on ;}~

Altering params 'datasvgcss', 'datapngcss' and 'urlpng_css' shows no effect

I'm trying to output the CSS-files as SCSS partials so I can include all three of them in a single SCSS-file in order to be able to use @extend.

My grunt.js looks like this:

module.exports = function(grunt) {

   // Project configuration.
   grunt.initConfig({
      grunticon: {
         src:           "img/svg/grunticons/",
         dest:          "sass/styles/grunticon/",      
         datasvgcss:    "_data-svg.scss",
         datapngcss:    "_data-png.scss",
         urlpng_css:    "_fallback.scss",
         previewhtml:   "preview.html",
         loadersnippet: "grunticon.loader.txt",
         pngfolder:     "/img/grunticons",
         cssprefix:     "grunticon-"
      } 
   });

   grunt.loadNpmTasks('grunt-grunticon');

   // Default task.
   grunt.registerTask('default','grunticon');

};

All other changed parameters worked just fine. But CSS stays to be output with the default filenames.
To make sure it's not the file-extension that messes thing up I also tried using datasvgcss: "svgtest.css" – but without any luck.

.PNG Artifacts

Having some issues with some very weird artifacts in the created .png files. I've tried a few things, primarily concerned with trying different .svg settings. I even went so far as to use one of the .svgs (star.svg) that can be found in the main directory.

Since a picture is worth a thousand words, here's a quick image illustrating the artifacts that I'm getting with the png export in grunticon.

(Exported to .png from Illustrator on left, vs. grunticon created on right--notice the odd yellow stray pixels and general edge artifacts)

comparison

I would paste code from our build, but it is pretty much a carbon copy (at least for now) ofthe suggested structure.

Build a client-side Grunticon web app

It'd be cool if we could drop a folder of svgs on the browser and get a zip file of typical Grunticon output in return. Maybe it could be built without a server using browser tech alone, I'm not sure...

  • drag and drop the folder of SVGs onto the browser
  • create the first css file based on the escaped contents of the svg
  • use canvas's data uri functions to create the png fallback CSS and images from the svg source files
  • zip the generated output files using something like https://github.com/Stuk/jszip
  • offer a data uri of the zip for download

Anyone want to help build this thing?

Repo is here for PRs :)

https://github.com/filamentgroup/grunticon-app

Compiles but wont create the css or image files

Hi, im trying to use Unicon but im running into some issues that im not certain if they are bugs or misuse.

I've install all requirements and Unicon, i now have on my Grunt file minimal setup:

module.exports = function(grunt) {

// Project configuration.
grunt.initConfig({
    unicon: {
        src: "images/icons-src",
        dest: "images/icons-dist"
    }
});

// Load tasks from "grunt-sample" grunt plugin installed via Npm.
grunt.loadNpmTasks('grunt-unicon');

// Default task.
grunt.registerTask('default', 'unicon');

};

When i run grunt, the output folder is created terminal says "Done, without errors." but nothing shows up in the output folder.
Am i missing something?

Thanks for any help you may provide.

Object #<Task> has no method 'getFile'

I can't seem to run this task at all, it always halts on an error (see below). Tried this in an existing project, then started from scratch to make sure I didn't have any config conflicts... I've read the readme multiple times but just can't find what's wrong here... Is this a version mismatch somewhere or something? I tried both the npm version (0.1.4) as well as the latest github version (0.1.6).

//edit, just noticed that the latest grunticon uses grunt 0.3.9, I suppose that is the base of the problem? task.getFile has been moved into grunt-init as of v0.4. Tried with grunt and grunt-init as dev dependency, but the same problem occured. I suppose more work is needed to make grunticon v0.4+ compatible?

Result when running "grunt":

Running "grunticon" task
Look, it's a grunticon!
Warning: Object #<Task> has no method 'getFile' Use --force to continue.

Aborted due to warnings.

Grunt config:

module.exports = function (grunt) {

// load additional config (next to config in tasks directory)
grunt.initConfig({
    pkg:grunt.file.readJSON('package.json'),
    clean:{
        all:['target'],
        temp:['target/temp']
    },
    grunticon: {
        src: "src/icons/",
        dest: "target/staging/icons/"
    }
});
grunt.registerTask('default', ['grunticon']);

grunt.loadNpmTasks('grunt-grunticon');
};

Workstation config

node --version >>
v0.8.18

npm ls >>
[email protected] /home/badabing/git/grunticon
├─┬ [email protected]
└─┬ [email protected]

Also tried with v0.1.6, no dice.

phantomjs --version >>
1.7.0

PNG fallback folder and path seperation

It would be nice to have two different parameter for the png fallback path and the folder. You should have one parameter which tells grunticon what the path in the icons.fallback.css should be and another where it should put the generated pngs.
I always struggle with the problem that the paths of the icons.fallback.css aren't correct if I move the folder after generation. This makes it also easier to use it with css preprocessors like less or sass.

Here is an example how I would expect it to work:
Gruntfile.js

options: {
    src:        "svg/",
    pngfolder:  "img/grunticons/",
    pngpath:    "../img/grunticons"
}

icons.fallback.css

.grunticon-cross { background-image: url(../img/grunticons/cross.png); background-repeat: no-repeat; }

folder
folder

IE background-size: broken!

In order to have complete control over my icons I've added background-size: cover and then set the width & height of their container depending on the situation (and with a different class) in my global CSS.

It mostly looks like this:

HTML:

<span class="icon-myicon someclass"></span>

Unicon CSS:

.icon-myicon { 
  background-image: url( - a whole bunch of data - );
  background-repeat: no-repeat;
}

Global CSS:

.someclass { 
  display: block;
  width: 4em;
  height: 4em;
  background-position: center center;
  background-size: 4em; /* fallback for browsers that don't support 'cover' */
  background-size: cover;
}

This method has been working great for me until I got to IE (of course)... which doesn't support background-size at all below IE 9.

There is this fix: http://stackoverflow.com/questions/2991623/make-background-size-work-in-ie

filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(
src='images/logo.gif',
sizingMethod='scale');

-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(
src='images/logo.gif',
sizingMethod='scale')";

Which does the trick. But I certainly do not want to be referencing the images in my global CSS for reasons I think are obvious.

The easiest solution I can see is creating a fourth output file for unicon which is delivered only to the required IE versions (so that the standard png URI's are still sent to android etc).

A quick note: In testing IE 7 on IE 9 in developer mode it seemed to load the URI PNG file, but you've listed IE7 as needing the raw .png files... so perhaps if that is the case there will need to be a fifth file generated for this context (which includes the filter on the .png backgrounds).

To be perfectly honest I'm not too knowledgeable in any of the stuff that makes up unicons (grunt, node, phantom, javascript in general...) but I'm certainly willing to give it a crack. So I've forked the unicon repo and started working through it to make some of these changes.

Any advice would be great and please if anyone can show me a better way to manage my icons in the CSS than what I'm already doing then I'm all ears - but this did seem like the best solution to me.

Cheers,
David.

Percentage sizing

Hey guys!

I'm trying to replace my svg stuff in a site for grunticon-based icons. But I can't apply a percentage based sizing anymore. Any ideas?

Thank you

PhantomJS hangs on SVG with missing width and height attributes

When an SVG file without a width attribute, such as this fishing-hook.svg exists in the source directory, grunticon hangs with the following output.

Running "grunticon:all" (grunticon) task
Look, it's a grunticon!

grunticon now minifying the stylesheet loader source.
grunticon loader file created.
grunticon now spawning phantomjs...(using path: /usr/bin/phantomjs)

Running the node_modules/grunt-grunticon/tasks/grunticon/phantom.js script manually with the same arguments revealed the actual error:

TypeError: 'null' is not an object (evaluating 'width.replace')
grunt-grunticon/lib/grunticoner.js:50
grunt-grunticon/lib/grunticoner.js:211
grunt-grunticon/tasks/grunticon/phantom.js:62

After editing this file's SVG element to set width and height to "512px", grunticon ran successfully. Both width and height must be present.

This behavior occurs using [email protected].

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.