package web import ( "bytes" "os" "path" "path/filepath" "regexp" "strings" ) // A preview page is sandboxed, so it has an origin of its own, and a // browser won't let it draw from a separate // file: that counts as cross-origin. inlineSprites copies each local sprite // file the page uses into the page itself, and points the elements // at the copy, so icons show as they do on the live site. var ( useHref = regexp.MustCompile(`(]*?\b(?:xlink:)?href=")([^"#:]+\.svg)#([^"]+)"`) svgOpen = regexp.MustCompile(`(?is)^.*?]*>`) svgClose = regexp.MustCompile(`(?is)\s*$`) bodyOpen = regexp.MustCompile(`(?i)]*>`) maxSprite = int64(2 << 20) ) // inlineSprites rewrites a page served from dir at urlPath (the page's // path within the preview, e.g. "/about/"). func inlineSprites(page []byte, dir, urlPath string) []byte { base := urlPath if !strings.HasSuffix(base, "/") { base = path.Dir(base) + "/" } sprites := map[string]string{} // file (within the preview) → its symbols var order []string out := useHref.ReplaceAllFunc(page, func(m []byte) []byte { g := useHref.FindSubmatch(m) ref := string(g[2]) file := path.Clean(path.Join(base, ref)) if strings.HasPrefix(ref, "/") { file = path.Clean(ref) } if _, ok := sprites[file]; !ok { sprites[file] = readSprite(dir, file) order = append(order, file) } if sprites[file] == "" { return m } return []byte(string(g[1]) + "#" + string(g[3]) + `"`) }) var inline strings.Builder for _, f := range order { if s := sprites[f]; s != "" { inline.WriteString(``) } } if inline.Len() == 0 { return page } loc := bodyOpen.FindIndex(out) if loc == nil { return page } return bytes.Join([][]byte{out[:loc[1]], []byte(inline.String()), out[loc[1]:]}, nil) } // readSprite is the inside of an SVG file in the preview, or "" if it // isn't one (or isn't inside the preview). func readSprite(dir, file string) string { p := filepath.Join(dir, filepath.FromSlash(file)) if rel, err := filepath.Rel(dir, p); err != nil || strings.HasPrefix(rel, "..") { return "" } st, err := os.Stat(p) if err != nil || st.IsDir() || st.Size() > maxSprite { return "" } raw, err := os.ReadFile(p) if err != nil { return "" } s := svgOpen.ReplaceAllString(string(raw), "") if s == string(raw) { return "" } return svgClose.ReplaceAllString(s, "") }