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