From 6c6cec62988d5d9ca48d3a23843393ca613a567b Mon Sep 17 00:00:00 2001
From: Přemysl Janouch <p@janouch.name>
Date: Thu, 18 Apr 2019 05:59:13 +0200
Subject: sklad: highlight matches in the search

---
 cmd/sklad/main.go     | 15 +++++++++++++++
 cmd/sklad/search.tmpl |  4 ++--
 2 files changed, 17 insertions(+), 2 deletions(-)

(limited to 'cmd')

diff --git a/cmd/sklad/main.go b/cmd/sklad/main.go
index 5f10348..aebb5c1 100644
--- a/cmd/sklad/main.go
+++ b/cmd/sklad/main.go
@@ -2,6 +2,7 @@ package main
 
 import (
 	"errors"
+	"html"
 	"html/template"
 	"io"
 	"log"
@@ -11,6 +12,7 @@ import (
 	"os"
 	"path"
 	"path/filepath"
+	"regexp"
 	"strings"
 	"sync"
 	"time"
@@ -355,6 +357,19 @@ var funcMap = template.FuncMap{
 	"lines": func(s string) int {
 		return strings.Count(s, "\n") + 1
 	},
+	"highlight": func(highlight, s string) template.HTML {
+		b, last := strings.Builder{}, 0
+		for _, m := range regexp.MustCompile(
+			`(?i:`+regexp.QuoteMeta(highlight)+`)`).FindAllStringIndex(s, -1) {
+			b.WriteString(html.EscapeString(s[last:m[0]]))
+			b.WriteString(`<mark>`)
+			b.WriteString(html.EscapeString(s[m[0]:m[1]]))
+			b.WriteString(`</mark>`)
+			last = m[1]
+		}
+		b.WriteString(html.EscapeString(s[last:]))
+		return template.HTML(b.String())
+	},
 }
 
 func main() {
diff --git a/cmd/sklad/search.tmpl b/cmd/sklad/search.tmpl
index 0c58bf9..b7a890e 100644
--- a/cmd/sklad/search.tmpl
+++ b/cmd/sklad/search.tmpl
@@ -9,7 +9,7 @@
 <section>
 	<header>
 		<h3><a href="series?prefix={{ .Prefix }}">{{ .Prefix }}</a></h3>
-		<p>{{ .Description }}
+		<p>{{ .Description | highlight $.Query }}
 	</header>
 </section>
 {{ else }}
@@ -28,7 +28,7 @@
 		</h3>
 	</header>
 	{{- if .Description }}
-	<p>{{ .Description }}
+	<p>{{ .Description | highlight $.Query }}
 	{{- end }}
 </section>
 {{ else }}
-- 
cgit v1.2.3-70-g09d2