Skip to content

Commit

Permalink
add support for sprite-names fixes #192 (#194)
Browse files Browse the repository at this point in the history
  • Loading branch information
drewwells committed Nov 26, 2016
1 parent fc8f480 commit d8477cf
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
31 changes: 31 additions & 0 deletions handlers/spriting.go
Expand Up @@ -21,6 +21,7 @@ func init() {
libsass.RegisterSassFunc("sprite-map($glob, $spacing: 0px)", SpriteMap)
libsass.RegisterSassFunc("sprite-file($map, $name)", SpriteFile)
libsass.RegisterSassFunc("sprite-position($map, $file)", SpritePosition)
libsass.RegisterSassFunc("sprite-names($map)", SpriteNames)
}

// SpritePosition returns the position of the image in the sprite-map.
Expand Down Expand Up @@ -89,6 +90,36 @@ func SpriteFile(ctx context.Context, usv libsass.SassValue) (rsv *libsass.SassVa
return &res, err
}

func fileName(path string) string {
return strings.TrimSuffix(path, filepath.Ext(path))
}

// SpriteNames returns the names of all images in a sprite map
func SpriteNames(ctx context.Context, usv libsass.SassValue) (*libsass.SassValue, error) {
comp, err := libsass.CompFromCtx(ctx)
if err != nil {
return nil, err
}
sprites := payload.Sprite(comp.Payload())

var glob string
if err := libsass.Unmarshal(usv, &glob); err != nil {
return nil, err
}

imgs := sprites.Get(glob)
if imgs == nil {
return nil, fmt.Errorf("sprite-map (%s) not found", glob)
}
paths := imgs.Paths()
for i := range paths {
paths[i] = fileName(paths[i])
}

lst, err := libsass.Marshal(paths)
return &lst, err
}

// Sprite returns the source and background position for an image in the
// spritesheet.
func Sprite(ctx context.Context, usv libsass.SassValue) (rsv *libsass.SassValue, err error) {
Expand Down
37 changes: 37 additions & 0 deletions handlers/spriting_test.go
Expand Up @@ -44,6 +44,43 @@ div.retina {
// background-position: 10px -74px; }
}

func TestSpriteNames(t *testing.T) {
in := bytes.NewBufferString(`
$map: sprite-map("*.png", 10px); // One argument
@each $color in sprite_names($map) {
.#{$color} {
width:0px;
}
}
`)

var out bytes.Buffer
comp, err := libsass.New(&out, in,
libsass.Payload(payload.New()),
libsass.ImgDir("../test/img"),
libsass.BuildDir("../test/build"),
libsass.ImgBuildDir("../test/build/img"),
)
if err != nil {
t.Fatal(err)
}

if err := comp.Run(); err != nil {
t.Fatal(err)
}

e := `.139 {
width: 0px; }
.140 {
width: 0px; }
`

if out.String() != e {
t.Errorf("got: %q\nwanted: %q\n", out.String(), e)
}
}

func TestFuncSpriteFile(t *testing.T) {

comp, err := libsass.New(nil, nil,
Expand Down

0 comments on commit d8477cf

Please sign in to comment.