github.com/powerman/golang-tools@v0.1.11-0.20220410185822-5ad214d8d803/present/image.go (about)

     1  // Copyright 2012 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package present
     6  
     7  import (
     8  	"fmt"
     9  	"strings"
    10  )
    11  
    12  func init() {
    13  	Register("image", parseImage)
    14  }
    15  
    16  type Image struct {
    17  	Cmd    string // original command from present source
    18  	URL    string
    19  	Width  int
    20  	Height int
    21  }
    22  
    23  func (i Image) PresentCmd() string   { return i.Cmd }
    24  func (i Image) TemplateName() string { return "image" }
    25  
    26  func parseImage(ctx *Context, fileName string, lineno int, text string) (Elem, error) {
    27  	args := strings.Fields(text)
    28  	if len(args) < 2 {
    29  		return nil, fmt.Errorf("incorrect image invocation: %q", text)
    30  	}
    31  	img := Image{Cmd: text, URL: args[1]}
    32  	a, err := parseArgs(fileName, lineno, args[2:])
    33  	if err != nil {
    34  		return nil, err
    35  	}
    36  	switch len(a) {
    37  	case 0:
    38  		// no size parameters
    39  	case 2:
    40  		// If a parameter is empty (underscore) or invalid
    41  		// leave the field set to zero. The "image" action
    42  		// template will then omit that img tag attribute and
    43  		// the browser will calculate the value to preserve
    44  		// the aspect ratio.
    45  		if v, ok := a[0].(int); ok {
    46  			img.Height = v
    47  		}
    48  		if v, ok := a[1].(int); ok {
    49  			img.Width = v
    50  		}
    51  	default:
    52  		return nil, fmt.Errorf("incorrect image invocation: %q", text)
    53  	}
    54  	return img, nil
    55  }