Debian Codegraph @

transform/livereloadinject/livereloadinject.go

raw
1 // Copyright 2018 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 livereloadinject
15
16 import (
17 "fmt"
18 "html"
19 "net/url"
20 "regexp"
21 "strings"
22
23 "github.com/gohugoio/hugo/common/loggers"
24
25 "github.com/gohugoio/hugo/transform"
26 )
27
28 var (
29 ignoredSyntax = regexp.MustCompile(`(?s)^(?:\s+|<!--.*?-->|<\?.*?\?>)*`)
30 tagsBeforeHead = []*regexp.Regexp{
31 regexp.MustCompile(`(?is)^<!doctype\s[^>]*>`),
32 regexp.MustCompile(`(?is)^<html(?:\s[^>]*)?>`),
33 regexp.MustCompile(`(?is)^<head(?:\s[^>]*)?>`),
34 }
35 )
36
37 // New creates a function that can be used to inject a script tag for
38 // the livereload JavaScript at the start of an HTML document's head.
39 func New(baseURL *url.URL) transform.Transformer {
40 return func(ft transform.FromTo) error {
41 b := ft.From().Bytes()
42
43 // We find the start of the head by reading past (in order)
44 // the doctype declaration, HTML start tag and head start tag,
45 // all of which are optional, and any whitespace, comments, or
46 // XML instructions in-between.
47 idx := 0
48 for _, tag := range tagsBeforeHead {
49 idx += len(ignoredSyntax.Find(b[idx:]))
50 idx += len(tag.Find(b[idx:]))
51 }
52 if idx == 0 {
53 // doctype is required for HTML5, we did not find it,
54 // and neither did we find html or head tags, so
55 // skip injection.
56 // This allows us to render partial HTML documents to be used in
57 // e.g. JS frameworks.
58 ft.To().Write(b)
59 return nil
60 }
61
62 path := strings.TrimSuffix(baseURL.Path, "/")
63
64 src := path + "/livereload.js?mindelay=10&v=2"
65 src += "&port=" + baseURL.Port()
66 src += "&path=" + strings.TrimPrefix(path+"/livereload", "/")
67
68 script := fmt.Appendf(nil, `<script src="%s" data-no-instant defer></script>`, html.EscapeString(src))
69
70 c := make([]byte, len(b)+len(script))
71 copy(c, b[:idx])
72 copy(c[idx:], script)
73 copy(c[idx+len(script):], b[idx:])
74
75 if _, err := ft.To().Write(c); err != nil {
76 loggers.Log().Warnf("Failed to inject LiveReload script: %s", err)
77 }
78 return nil
79 }
80 }