colette
Version:
A CSS and JS starter kit for 20 Minutes web projects
67 lines (58 loc) • 2.11 kB
text/stylus
// Inline SVG
//
// Returns encoded inline svg
//
// $svg - svg code
//
// ```stylus
// .foo
// background-image _inlineSvg('<svg viewBox="0 0 90 30" width="30" height="30"><circle cx="15" cy="15" r="10" class="bounce1"/></svg>')
// ```
// will return
// ```css
// .foo {
// background-image url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 90 30' width='30' height='30'%3E%3Ccircle cx='15' cy='15' r='10' class='bounce1'/%3E%3C/svg%3E");
// }
// ```
//
// Deprecated
//
// Styleguide: Mixins.Inline-SVG
_inlineSvg($svg)
// Add missing namespace
if not match('xmlns', $svg)
$svg = replace('<svg', '<svg xmlns="http://www.w3.org/2000/svg"', $svg) // @stylint ignore
// Chunk up string in order to avoid
// "stack level too deep" error
$encoded = ''
$slice = 2000
$index = 0
$loops = ceil(length($svg) / $slice)
for $i in 1..$loops
$chunk = slice($svg, $index, $index + $slice - 1)
// Encode
$chunk = replace('"', "'", $chunk) // @stylint ignore
$chunk = replace('%', '%25', $chunk)
$chunk = replace('&', '%26', $chunk)
$chunk = replace('#', '%23', $chunk)
$chunk = replace('{', '%7B', $chunk)
$chunk = replace('}', '%7D', $chunk)
$chunk = replace('<', '%3C', $chunk)
$chunk = replace('>', '%3E', $chunk)
// The maybe list
//
// Keep size and compile time down
// … only add on documented fail
// $chunk = replace('|', '%7C', $chunk)
// $chunk = replace('[', '%5B', $chunk)
// $chunk = replace(']', '%5D', $chunk)
// $chunk = replace('^', '%5E', $chunk)
// $chunk = replace('`', '%60', $chunk)
// $chunk = replace(';', '%3B', $chunk)
// $chunk = replace('?', '%3F', $chunk)
// $chunk = replace(':', '%3A', $chunk)
// $chunk = replace('@', '%40', $chunk)
// $chunk = replace('=', '%3D', $chunk)
$encoded = $encoded+$chunk
$index = $index + $slice
return url(s('data:image/svg+xml,%s', unquote($encoded)))