github.com/rezahousseini/hugo@v0.32.3/transform/livereloadinject.go (about)

     1  // Copyright 2015 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 transform
    15  
    16  import (
    17  	"bytes"
    18  	"fmt"
    19  )
    20  
    21  // LiveReloadInject returns a function that can be used
    22  // to inject a script tag for the livereload JavaScript in a HTML document.
    23  func LiveReloadInject(port int) func(ct contentTransformer) {
    24  	return func(ct contentTransformer) {
    25  		endBodyTag := "</body>"
    26  		match := []byte(endBodyTag)
    27  		replaceTemplate := `<script data-no-instant>document.write('<script src="/livereload.js?port=%d&mindelay=10"></' + 'script>')</script>%s`
    28  		replace := []byte(fmt.Sprintf(replaceTemplate, port, endBodyTag))
    29  
    30  		newcontent := bytes.Replace(ct.Content(), match, replace, 1)
    31  		if len(newcontent) == len(ct.Content()) {
    32  			endBodyTag = "</BODY>"
    33  			replace := []byte(fmt.Sprintf(replaceTemplate, port, endBodyTag))
    34  			match := []byte(endBodyTag)
    35  			newcontent = bytes.Replace(ct.Content(), match, replace, 1)
    36  		}
    37  
    38  		ct.Write(newcontent)
    39  	}
    40  }