github.com/aarzilli/tools@v0.0.0-20151123112009-0d27094f75e0/net/http/domclean2/09_outline_and_id.go (about) 1 package domclean2 2 3 import ( 4 "fmt" 5 "strings" 6 7 "golang.org/x/net/html" 8 ) 9 10 func addOutlineAttr(n *html.Node, lvl int, argOutline []int) (outline []int) { 11 12 outline = argOutline 13 14 if n.Type == html.ElementNode && lvl > cScaffoldLvls { 15 16 outline[len(outline)-1]++ 17 18 s := "" 19 for _, v := range outline { 20 s = fmt.Sprintf("%v%v.", s, v) 21 } 22 if strings.HasSuffix(s, ".") { 23 s = s[:len(s)-1] 24 } 25 26 attr := html.Attribute{"", "ol", s} 27 28 newAttrs := make([]html.Attribute, 0, len(n.Attr)+2) // make space for outline now - and id later 29 newAttrs = append(newAttrs, attr) 30 newAttrs = append(newAttrs, n.Attr...) 31 n.Attr = newAttrs 32 33 outline = append(outline, 0) // add children lvl 34 } 35 36 // Children 37 for c := n.FirstChild; c != nil; c = c.NextSibling { 38 outline = addOutlineAttr(c, lvl+1, outline) 39 } 40 41 if n.Type == html.ElementNode && lvl > cScaffoldLvls { 42 outline = outline[:len(outline)-1] // reset children lvl 43 } 44 45 return 46 } 47 48 func addIdAttr(n *html.Node, lvl int, argNum int) (num int) { 49 50 num = argNum 51 52 if lvl > cScaffoldLvls { 53 if n.Type == html.ElementNode { 54 55 attr := html.Attribute{"", "id", spf("%v", num)} 56 57 prep := []html.Attribute{attr} 58 n.Attr = append(prep, n.Attr...) 59 60 } 61 } 62 63 // Children 64 for c := n.FirstChild; c != nil; c = c.NextSibling { 65 num = addIdAttr(c, lvl+1, num+1) 66 } 67 68 return 69 }