Debian Codegraph @

tpl/strings/truncate.go

raw
1 // Copyright 2016 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 strings
15
16 import (
17 "errors"
18 "html"
19 "html/template"
20 "regexp"
21 "strings"
22 "unicode"
23 "unicode/utf8"
24
25 "github.com/spf13/cast"
26 )
27
28 var (
29 tagRE = regexp.MustCompile(`^<(/)?([^ ]+?)(?:(\s*/)| .*?)?>`)
30 htmlSinglets = map[string]bool{
31 "br": true, "col": true, "link": true,
32 "base": true, "img": true, "param": true,
33 "area": true, "hr": true, "input": true,
34 }
35 )
36
37 type htmlTag struct {
38 name string
39 pos int
40 openTag bool
41 }
42
43 // Truncate truncates the string in s to the specified length.
44 func (ns *Namespace) Truncate(s any, options ...any) (template.HTML, error) {
45 length, err := cast.ToIntE(s)
46 if err != nil {
47 return "", err
48 }
49 var textParam any
50 var ellipsis string
51
52 switch len(options) {
53 case 0:
54 return "", errors.New("truncate requires a length and a string")
55 case 1:
56 textParam = options[0]
57 ellipsis = " …"
58 case 2:
59 textParam = options[1]
60 ellipsis, err = cast.ToStringE(options[0])
61 if err != nil {
62 return "", errors.New("ellipsis must be a string")
63 }
64 if _, ok := options[0].(template.HTML); !ok {
65 ellipsis = html.EscapeString(ellipsis)
66 }
67 default:
68 return "", errors.New("too many arguments passed to truncate")
69 }
70
71 text, err := cast.ToStringE(textParam)
72 if err != nil {
73 return "", errors.New("text must be a string")
74 }
75
76 _, isHTML := textParam.(template.HTML)
77
78 if utf8.RuneCountInString(text) <= length {
79 if isHTML {
80 return template.HTML(text), nil
81 }
82 return template.HTML(html.EscapeString(text)), nil
83 }
84
85 tags := []htmlTag{}
86 var lastWordIndex, lastNonSpace, currentLen, endTextPos, nextTag int
87
88 for i, r := range text {
89 if i < nextTag {
90 continue
91 }
92
93 if isHTML {
94 // Make sure we keep tagname of HTML tags
95 slice := text[i:]
96 m := tagRE.FindStringSubmatchIndex(slice)
97 if len(m) > 0 && m[0] == 0 {
98 nextTag = i + m[1]
99 tagname := strings.Fields(slice[m[4]:m[5]])[0]
100 lastWordIndex = lastNonSpace
101 _, singlet := htmlSinglets[tagname]
102 if !singlet && m[6] == -1 {
103 tags = append(tags, htmlTag{name: tagname, pos: i, openTag: m[2] == -1})
104 }
105
106 continue
107 }
108 }
109
110 currentLen++
111 if unicode.IsSpace(r) {
112 lastWordIndex = lastNonSpace
113 } else if unicode.In(r, unicode.Han, unicode.Hangul, unicode.Hiragana, unicode.Katakana) {
114 lastWordIndex = lastNonSpace
115 lastNonSpace = i + utf8.RuneLen(r)
116 if currentLen <= length {
117 lastWordIndex = lastNonSpace
118 }
119 } else {
120 lastNonSpace = i + utf8.RuneLen(r)
121 }
122
123 if currentLen > length {
124 if lastWordIndex == 0 {
125 endTextPos = i
126 } else {
127 endTextPos = lastWordIndex
128 }
129 var out strings.Builder
130 out.WriteString(text[0:endTextPos])
131 if isHTML {
132 out.WriteString(ellipsis)
133 // Close out any open HTML tags
134 var currentTag *htmlTag
135 for i := len(tags) - 1; i >= 0; i-- {
136 tag := tags[i]
137 if tag.pos >= endTextPos || currentTag != nil {
138 if currentTag != nil && currentTag.name == tag.name {
139 currentTag = nil
140 }
141 continue
142 }
143
144 if tag.openTag {
145 out.WriteString(("</" + tag.name + ">"))
146 } else {
147 currentTag = &tag
148 }
149 }
150
151 return template.HTML(out.String()), nil
152 }
153 return template.HTML(html.EscapeString(out.String()) + ellipsis), nil
154 }
155 }
156
157 if isHTML {
158 return template.HTML(text), nil
159 }
160 return template.HTML(html.EscapeString(text)), nil
161 }