Skip to content

Commit

Permalink
CORS support + raw HTML view + more.
Browse files Browse the repository at this point in the history
  • Loading branch information
alecthomas committed Jul 16, 2019
1 parent bdb587c commit ffa8a4f
Show file tree
Hide file tree
Showing 5 changed files with 58 additions and 32 deletions.
19 changes: 15 additions & 4 deletions cmd/chromad/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
"github.com/alecthomas/kong"
"github.com/alecthomas/kong-hcl"
"github.com/gorilla/csrf"
"github.com/gorilla/handlers"
"github.com/gorilla/mux"

"github.com/alecthomas/chroma"
Expand Down Expand Up @@ -48,6 +49,7 @@ type renderRequest struct {
Language string `json:"language"`
Style string `json:"style"`
Text string `json:"text"`
Classes bool `json:"classes"`
}

type renderResponse struct {
Expand Down Expand Up @@ -96,13 +98,21 @@ func render(req *renderRequest) (*renderResponse, error) {
}

buf := &strings.Builder{}
formatter := html.New()
options := []html.Option{}
if req.Classes {
options = append(options, html.WithClasses())
}
formatter := html.New(options...)
err = formatter.Format(buf, style, tokens)
if err != nil {
return nil, err
}
lang := language.Config().Name
if language == lexers.Fallback {
lang = ""
}
return &renderResponse{
Language: language.Config().Name,
Language: lang,
HTML: buf.String(),
Background: html.StyleEntryToCSS(style.Get(chroma.Background)),
}, nil
Expand Down Expand Up @@ -151,8 +161,9 @@ func main() {
if cli.CSRFKey == "" {
options = append(options, csrf.Secure(false))
}
CSRF := csrf.Protect([]byte(cli.CSRFKey), options...)

err := http.ListenAndServe(cli.Bind, CSRF(router))
root := handlers.CORS()(csrf.Protect([]byte(cli.CSRFKey), options...)(router))

err := http.ListenAndServe(cli.Bind, root)
ctx.FatalIfErrorf(err)
}
50 changes: 29 additions & 21 deletions cmd/chromad/static/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ document.addEventListener("DOMContentLoaded", function () {

var form = document.getElementById('chroma');
var textArea = form.elements["text"];
var styleSelect = form.elements["style"];
var languageSelect = form.elements["language"];
var csrfToken = form.elements["gorilla.csrf.Token"].value;
var elms = document.getElementsByTagName("select");
var output = document.getElementById("output");
var htmlCheckbox = document.getElementById("html");

function debounce(func, wait, immediate) {
var timeout;
Expand All @@ -22,52 +24,58 @@ document.addEventListener("DOMContentLoaded", function () {
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
}

function getFormJSON() {
return {
"language": document.getElementById("language").value,
"style": document.getElementById("style").value,
"text": document.getElementById("text").value,
"language": languageSelect.value,
"style": styleSelect.value,
"text": textArea.value,
"classes": htmlCheckbox.checked,
}
}

function update(event) {
fetch("api/render", {
method: 'POST', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, cors, *same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
method: 'POST',
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin',
headers: {
'X-CSRF-Token': csrfToken,
'Content-Type': 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrer: 'no-referrer', // no-referrer, *client
redirect: 'follow',
referrer: 'no-referrer',
body: JSON.stringify(getFormJSON()),

}).then(data => {
data.json().then(
value => {
if (value.language) {
languageSelect.value = value.language;
}
style.innerHTML = "#output { " + value.background + "}";
output.innerHTML = value.html;
if (htmlCheckbox.checked) {
output.innerText = value.html;
} else {
output.innerHTML = value.html;
}
}
);
}).catch(reason => {
console.log(reason);
})
});

event.preventDefault();
}

var eventHandler = (event) => update(event);
for (e of elms) {
e.addEventListener('change', eventHandler);
}
form.addEventListener('submit', eventHandler);

var debouncedEventHandler = debounce(eventHandler, 250);

languageSelect.addEventListener('change', eventHandler);
styleSelect.addEventListener('change', eventHandler);
htmlCheckbox.addEventListener('change', eventHandler);

textArea.addEventListener('input', debouncedEventHandler);
textArea.addEventListener('change', debouncedEventHandler)
textArea.addEventListener('change', debouncedEventHandler);
});
18 changes: 11 additions & 7 deletions cmd/chromad/templates/index.html.tmpl
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@

#output {
{{.Background}}

overflow-x: scroll;
}

#output pre {
Expand Down Expand Up @@ -63,15 +65,17 @@
</div>
</div>

<div class="field">
<div class="control">
<button type="submit" class="button is-link">Submit</button>
</div>
</div>

<hr>

<label class="label">Output</label>
<label class="checkbox is-pulled-right">
<input name="html" id="html" type="checkbox">
Show HTML
</label>

<label class="label">
Output
</label>

<div class="field box" id="output"></div>
</form>
</div>
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ require (
github.com/danwakefield/fnmatch v0.0.0-20160403171240-cbb64ac3d964
github.com/dlclark/regexp2 v1.1.6
github.com/gorilla/csrf v1.6.0
github.com/gorilla/handlers v1.4.1
github.com/gorilla/mux v1.7.3
github.com/mattn/go-colorable v0.0.9
github.com/mattn/go-isatty v0.0.4
Expand Down
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ github.com/dlclark/regexp2 v1.1.6 h1:CqB4MjHw0MFCDj+PHHjiESmHX+N7t0tJzKvC6M97BRg
github.com/dlclark/regexp2 v1.1.6/go.mod h1:2pZnwuY/m+8K6iRw6wQdMtk+rH5tNGR1i55kozfMjCc=
github.com/gorilla/csrf v1.6.0 h1:60oN1cFdncCE8tjwQ3QEkFND5k37lQPcRjnlvm7CIJ0=
github.com/gorilla/csrf v1.6.0/go.mod h1:7tSf8kmjNYr7IWDCYhd3U8Ck34iQ/Yw5CJu7bAkHEGI=
github.com/gorilla/handlers v1.4.1 h1:BHvcRGJe/TrL+OqFxoKQGddTgeibiOjaBssV5a/N9sw=
github.com/gorilla/handlers v1.4.1/go.mod h1:Qkdc/uu4tH4g6mTK6auzZ766c4CA0Ng8+o/OAirnOIQ=
github.com/gorilla/mux v1.7.3 h1:gnP5JzjVOuiZD07fKKToCAOjS0yOpj/qPETTXCCS6hw=
github.com/gorilla/mux v1.7.3/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs=
github.com/gorilla/securecookie v1.1.1 h1:miw7JPhV+b/lAHSXz4qd/nN9jRiAFV5FwjeKyCS8BvQ=
Expand Down

0 comments on commit ffa8a4f

Please sign in to comment.