diagrams.go (1759B)
1 // Copyright 2022 The Hugo Authors. All rights reserved. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // http://www.apache.org/licenses/LICENSE-2.0 7 // 8 // Unless required by applicable law or agreed to in writing, software 9 // distributed under the License is distributed on an "AS IS" BASIS, 10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 package diagrams 15 16 import ( 17 "bytes" 18 "html/template" 19 "io" 20 "strings" 21 22 "github.com/bep/goat" 23 "github.com/gohugoio/hugo/deps" 24 "github.com/spf13/cast" 25 ) 26 27 type SVGDiagram interface { 28 // Wrapped returns the diagram as an SVG, including the <svg> container. 29 Wrapped() template.HTML 30 31 // Inner returns the inner markup of the SVG. 32 // This allows for the <svg> container to be created manually. 33 Inner() template.HTML 34 35 // Width returns the width of the SVG. 36 Width() int 37 38 // Height returns the height of the SVG. 39 Height() int 40 } 41 42 type goatDiagram struct { 43 d goat.SVG 44 } 45 46 func (d goatDiagram) Inner() template.HTML { 47 return template.HTML(d.d.Body) 48 } 49 50 func (d goatDiagram) Wrapped() template.HTML { 51 return template.HTML(d.d.String()) 52 } 53 54 func (d goatDiagram) Width() int { 55 return d.d.Width 56 } 57 58 func (d goatDiagram) Height() int { 59 return d.d.Height 60 } 61 62 type Diagrams struct { 63 d *deps.Deps 64 } 65 66 func (d *Diagrams) Goat(v any) SVGDiagram { 67 var r io.Reader 68 69 switch vv := v.(type) { 70 case io.Reader: 71 r = vv 72 case []byte: 73 r = bytes.NewReader(vv) 74 default: 75 r = strings.NewReader(cast.ToString(v)) 76 } 77 78 return goatDiagram{ 79 d: goat.BuildSVG(r), 80 } 81 }