Skip to content

Instantly share code, notes, and snippets.

@dceddia
Created July 29, 2020 16:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dceddia/0a669466821b6f3c3dcbc2a5e2b3af04 to your computer and use it in GitHub Desktop.
Save dceddia/0a669466821b6f3c3dcbc2a5e2b3af04 to your computer and use it in GitHub Desktop.
Transform an SVG element into something ready to be animated with Svelte + animejs
#!/usr/bin/env ruby
require 'open3'
# Copy the SVG from Sketch, then run this
# It will clean up the SVG, insert bind:this={whatever} for any objects named `b:whatever` in the svg,
# and print out the variables to declare in Svelte
# To use:
# 1. copy the SVG from Sketch
# 2. svg-to-svelte | pbcopy
# 3. the clipboard will have the SVG output: paste this into the Svelte component
# 4. copy-paste the list of variables that this prints out, and paste those into the <script> of the Svelte component
clipboard=`pbpaste`
# Replace id's with classes
cleaned = clipboard.gsub(/id="/, 'class="')
# Remove width and height
cleaned = cleaned.gsub(/<svg width="\d+" height="\d+"/, '<svg')
# Run it through svgo
output, e, s = Open3.capture3("svgo -i - --pretty --disable=removeViewBox,removeHiddenElems,convertShapeToPath,convertTransform", stdin_data: cleaned)
# Find every occurrence of `b:` and insert a `bind:this`
vars = []
final_svg = output.gsub(/b:([^"]*)"/) do |match|
variable_name = $1
vars << variable_name
%Q[b:#{variable_name}" bind:this={#{variable_name}}]
end
# Turn the variables into declarations for Svelte
STDERR.puts "let #{vars.join(', ')};"
puts final_svg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment