github.com/laof/lite-speed-test@v0.0.0-20230930011949-1f39b7037845/web/render/wrap.go (about) 1 package render 2 3 import ( 4 "strings" 5 "unicode" 6 ) 7 8 type measureStringer interface { 9 MeasureString(s string) (w, h float64) 10 } 11 12 func splitOnSpace(x string) []string { 13 var result []string 14 pi := 0 15 ps := false 16 for i, c := range x { 17 s := unicode.IsSpace(c) 18 if s != ps && i > 0 { 19 result = append(result, x[pi:i]) 20 pi = i 21 } 22 ps = s 23 } 24 result = append(result, x[pi:]) 25 return result 26 } 27 28 func wordWrap(m measureStringer, s string, width float64) []string { 29 var result []string 30 for _, line := range strings.Split(s, "\n") { 31 fields := splitOnSpace(line) 32 if len(fields)%2 == 1 { 33 fields = append(fields, "") 34 } 35 x := "" 36 for i := 0; i < len(fields); i += 2 { 37 w, _ := m.MeasureString(x + fields[i]) 38 if w > width { 39 if x == "" { 40 result = append(result, fields[i]) 41 x = "" 42 continue 43 } else { 44 result = append(result, x) 45 x = "" 46 } 47 } 48 x += fields[i] + fields[i+1] 49 } 50 if x != "" { 51 result = append(result, x) 52 } 53 } 54 for i, line := range result { 55 result[i] = strings.TrimSpace(line) 56 } 57 return result 58 }