Skip to content

Instantly share code, notes, and snippets.

@taylorzane
Created May 27, 2015 04:57
Show Gist options
  • Save taylorzane/75b7c8c20153fa470d19 to your computer and use it in GitHub Desktop.
Save taylorzane/75b7c8c20153fa470d19 to your computer and use it in GitHub Desktop.
Mithril + Snap.svg Sliders
# Simple Slider for use with Mithril,
# and written with Snap.svg
# Written by: Taylor Zane Glaeser
#
# Disclaimer: Code is very crufty. I have no plans of updating this.
# cont: This is being posted as preservation of a direction
# cont: I decided to abandon.
# cont: SVGs were _WAY_ too laggy for 20+ elements.
#
# This code was wrapped in a for loop,
# i.e. why I'm referencing some undefined variables (obj)
m 'svg',
id: "svg-#{obj.id}"
width: 130
height: 40
config: (el, isInit, context) ->
objId = el.id.split('svg-').join('')
context.obj = Layout.vm.objs[objId]
if context.thumb isnt undefined
context.thumb.attr({fill: '#' + (context.obj.magnitude() * 1000).toString().slice(0,3)})
moveSlider = (t, d = 100) ->
maxDrag = parseInt(context.track.node.attributes.width.value)
return (t / d) * maxDrag
if context.magnitude isnt undefined and context.magnitude isnt context.obj.magnitude()
context.thumb.transform 't' + moveSlider context.obj.magnitude()
context.trackFill.attr width: moveSlider context.obj.magnitude()
unless isInit
generateSlider = () ->
context.origTrans = ''
context.svg = Snap document.getElementById("svg-#{objId}")
context.track = _.filter(context.svg.children(), (i) -> return i.node.id is 'track')[0]
context.trackFill = _.filter(context.svg.children(), (i) -> return i.node.id is 'trackFill')[0]
context.thumb = _.filter(context.svg.children(), (i) -> return i.node.id is 'thumb')[0]
dragStart = (svg) ->
return () ->
context.origTrans = @transform().local
dragMove = (svg) ->
return (dx) ->
maxDrag = parseInt(svg.track.node.attributes.width.value)
trans = (t, d) ->
transformMatch = t.match(/t(\d+),?/) # Match the pattern tNUMBER, (e.g. 't127,0' or 't900')
transformInt = 0
if transformMatch isnt null
transformInt = parseInt(transformMatch[1])
return maxDrag if transformInt + d > maxDrag
return 0 if transformInt + d < 0
return transformInt + d
@transform 't' + trans(context.origTrans, dx)
context.trackFill.attr({width: @transform().globalMatrix.e}) if @transform().globalMatrix.e >= 0
context.obj.magnitude Math.round(@transform().globalMatrix.e * (100 / maxDrag))
m.redraw()
generateSlider()
context.thumb.drag dragMove(context), dragStart(context)
context.magnitude = context.obj.magnitude()
, [
m 'rect',
id: 'track'
width: 120
height: 4
fill: '#ccc'
x: 8
y: 10
m 'rect',
id: 'trackFill'
width: 0
height: 4
fill: '#00AAFF'
x: 8
y: 10
m 'circle',
id: 'thumb'
r: 5
cx: 8
cy: 12.5
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment