mirror of
https://github.com/skidoodle/pastebin
synced 2026-04-28 03:07:40 +02:00
overhaul syntax highlighting and line numbering for large pastes
This commit is contained in:
@@ -98,9 +98,6 @@ func (h *HttpHandler) HandleSet(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
func (h *HttpHandler) HandleGet(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.PathValue("id")
|
||||
if index := strings.LastIndex(id, "."); index > 0 {
|
||||
id = id[:index]
|
||||
}
|
||||
|
||||
paste, exists, err := h.store.Get(id)
|
||||
if err != nil {
|
||||
@@ -131,9 +128,6 @@ func (h *HttpHandler) HandleGet(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
func (h *HttpHandler) HandleRaw(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.PathValue("id")
|
||||
if index := strings.LastIndex(id, "."); index > 0 {
|
||||
id = id[:index]
|
||||
}
|
||||
|
||||
paste, exists, err := h.store.Get(id)
|
||||
if err != nil {
|
||||
|
||||
@@ -207,18 +207,6 @@ func TestHandleGet(t *testing.T) {
|
||||
h.HandleGet(rr, req)
|
||||
assert.Equal(t, http.StatusInternalServerError, rr.Code)
|
||||
})
|
||||
|
||||
t.Run("With Extension", func(t *testing.T) {
|
||||
id := "testid"
|
||||
s.On("Get", id).Return(&store.Paste{Content: "hello", CreatedAt: time.Now()}, true, nil).Once()
|
||||
req := httptest.NewRequest("GET", "/"+id+".go", nil)
|
||||
req.SetPathValue("id", id+".go")
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
h.HandleGet(rr, req)
|
||||
assert.Equal(t, http.StatusOK, rr.Code)
|
||||
assert.Contains(t, rr.Body.String(), "hello")
|
||||
})
|
||||
}
|
||||
|
||||
type FailingResponseWriter struct {
|
||||
@@ -262,19 +250,6 @@ func TestHandleRaw(t *testing.T) {
|
||||
assert.Equal(t, "text/plain; charset=utf-8", rr.Header().Get("Content-Type"))
|
||||
})
|
||||
|
||||
t.Run("With Extension", func(t *testing.T) {
|
||||
id := "testid"
|
||||
content := "raw content"
|
||||
s.On("Get", id).Return(&store.Paste{Content: content}, true, nil).Once()
|
||||
req := httptest.NewRequest("GET", "/raw/"+id+".txt", nil)
|
||||
req.SetPathValue("id", id+".txt")
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
h.HandleRaw(rr, req)
|
||||
assert.Equal(t, http.StatusOK, rr.Code)
|
||||
assert.Equal(t, content, rr.Body.String())
|
||||
})
|
||||
|
||||
t.Run("Not Found", func(t *testing.T) {
|
||||
s.On("Get", "missing").Return(nil, false, nil).Once()
|
||||
req := httptest.NewRequest("GET", "/raw/missing", nil)
|
||||
|
||||
@@ -41,7 +41,7 @@ func securityHeadersMiddleware(next http.Handler) http.Handler {
|
||||
w.Header().Set("Strict-Transport-Security", "max-age=63072000; includeSubDomains")
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.Header().Set("X-Frame-Options", "DENY")
|
||||
w.Header().Set("Content-Security-Policy", "default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'")
|
||||
w.Header().Set("Content-Security-Policy", "default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline'; worker-src 'self' blob:")
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 1.1 KiB |
@@ -1 +0,0 @@
|
||||
!function(r,o){"use strict";var e,a="hljs-ln",l="hljs-ln-line",h="hljs-ln-code",s="hljs-ln-numbers",c="hljs-ln-n",m="data-line-number",i=/\r\n|\r|\n/g;function u(e){for(var n=e.toString(),t=e.anchorNode;"TD"!==t.nodeName;)t=t.parentNode;for(var r=e.focusNode;"TD"!==r.nodeName;)r=r.parentNode;var o=parseInt(t.dataset.lineNumber),i=parseInt(r.dataset.lineNumber);if(o==i)return n;var a,l=t.textContent,s=r.textContent;for(i<o&&(a=o,o=i,i=a,a=l,l=s,s=a);0!==n.indexOf(l);)l=l.slice(1);for(;-1===n.lastIndexOf(s);)s=s.slice(0,-1);for(var c=l,u=function(e){for(var n=e;"TABLE"!==n.nodeName;)n=n.parentNode;return n}(t),d=o+1;d<i;++d){var f=p('.{0}[{1}="{2}"]',[h,m,d]);c+="\n"+u.querySelector(f).textContent}return c+="\n"+s}function n(e){try{var n=o.querySelectorAll("code.hljs,code.nohighlight");for(var t in n)n.hasOwnProperty(t)&&(n[t].classList.contains("nohljsln")||d(n[t],e))}catch(e){r.console.error("LineNumbers error: ",e)}}function d(e,n){"object"==typeof e&&r.setTimeout(function(){e.innerHTML=f(e,n)},0)}function f(e,n){var t,r,o=(t=e,{singleLine:function(e){return!!e.singleLine&&e.singleLine}(r=(r=n)||{}),startFrom:function(e,n){var t=1;isFinite(n.startFrom)&&(t=n.startFrom);var r=function(e,n){return e.hasAttribute(n)?e.getAttribute(n):null}(e,"data-ln-start-from");return null!==r&&(t=function(e,n){if(!e)return n;var t=Number(e);return isFinite(t)?t:n}(r,1)),t}(t,r)});return function e(n){var t=n.childNodes;for(var r in t){var o;t.hasOwnProperty(r)&&(o=t[r],0<(o.textContent.trim().match(i)||[]).length&&(0<o.childNodes.length?e(o):v(o.parentNode)))}}(e),function(e,n){var t=g(e);""===t[t.length-1].trim()&&t.pop();if(1<t.length||n.singleLine){for(var r="",o=0,i=t.length;o<i;o++)r+=p('<tr><td class="{0} {1}" {3}="{5}"><div class="{2}" {3}="{5}"></div></td><td class="{0} {4}" {3}="{5}">{6}</td></tr>',[l,s,c,m,h,o+n.startFrom,0<t[o].length?t[o]:" "]);return p('<table class="{0}">{1}</table>',[a,r])}return e}(e.innerHTML,o)}function v(e){var n=e.className;if(/hljs-/.test(n)){for(var t=g(e.innerHTML),r=0,o="";r<t.length;r++){o+=p('<span class="{0}">{1}</span>\n',[n,0<t[r].length?t[r]:" "])}e.innerHTML=o.trim()}}function g(e){return 0===e.length?[]:e.split(i)}function p(e,t){return e.replace(/\{(\d+)\}/g,function(e,n){return void 0!==t[n]?t[n]:e})}r.hljs?(r.hljs.initLineNumbersOnLoad=function(e){"interactive"===o.readyState||"complete"===o.readyState?n(e):r.addEventListener("DOMContentLoaded",function(){n(e)})},r.hljs.lineNumbersBlock=d,r.hljs.lineNumbersBlockSync=function(e,n){if("object"!=typeof e)return;e.innerHTML=f(e,n)},r.hljs.lineNumbersValue=function(e,n){if("string"!=typeof e)return;var t=document.createElement("code");return t.innerHTML=e,f(t,n)},(e=o.createElement("style")).type="text/css",e.innerHTML=p(".{0}{border-collapse:collapse}.{0} td{padding:0}.{1}:before{content:attr({2})}",[a,c,m]),o.getElementsByTagName("head")[0].appendChild(e)):r.console.error("highlight.js not detected!"),document.addEventListener("copy",function(e){var n,t=window.getSelection();!function(e){for(var n=e;n;){if(n.className&&-1!==n.className.indexOf("hljs-ln-code"))return 1;n=n.parentNode}}(t.anchorNode)||(n=-1!==window.navigator.userAgent.indexOf("Edge")?u(t):t.toString(),e.clipboardData.setData("text/plain",n),e.preventDefault())})}(window,document);
|
||||
@@ -0,0 +1,80 @@
|
||||
(function () {
|
||||
const code = document.getElementById('code-block');
|
||||
if (code) {
|
||||
const ln = document.getElementById('line-numbers');
|
||||
const lineCount = parseInt(code.getAttribute('data-line-count'));
|
||||
|
||||
const nums = [];
|
||||
for (let i = 1; i <= lineCount; i++) {
|
||||
nums.push('<a href="#L' + i + '" id="L' + i + '">' + i + '</a>');
|
||||
}
|
||||
ln.innerHTML = nums.join('');
|
||||
|
||||
const rawText = code.textContent;
|
||||
const workerCode = `
|
||||
self.window = self;
|
||||
self.document = {
|
||||
readyState: 'complete',
|
||||
querySelectorAll: function() { return []; },
|
||||
addEventListener: function() {}
|
||||
};
|
||||
importScripts('${window.location.origin}/static/highlight.min.js');
|
||||
onmessage = function(e) {
|
||||
try {
|
||||
const result = self.hljs.highlightAuto(e.data);
|
||||
postMessage(result.value);
|
||||
} catch (err) {
|
||||
postMessage(e.data);
|
||||
}
|
||||
}
|
||||
`;
|
||||
const blob = new Blob([workerCode], { type: 'application/javascript' });
|
||||
const workerUrl = URL.createObjectURL(blob);
|
||||
const worker = new Worker(workerUrl);
|
||||
|
||||
worker.onmessage = function (e) {
|
||||
code.innerHTML = e.data;
|
||||
URL.revokeObjectURL(workerUrl);
|
||||
};
|
||||
worker.postMessage(rawText);
|
||||
|
||||
function updateActiveLine() {
|
||||
const active = document.querySelector('.line-numbers a.active');
|
||||
if (active) active.classList.remove('active');
|
||||
|
||||
if (window.location.hash) {
|
||||
const target = document.getElementById(window.location.hash.substring(1));
|
||||
if (target) {
|
||||
target.scrollIntoView({ block: 'center', behavior: 'smooth' });
|
||||
target.classList.add('active');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
updateActiveLine();
|
||||
window.addEventListener('hashchange', updateActiveLine);
|
||||
|
||||
document.addEventListener('keydown', (e) => {
|
||||
if ((e.ctrlKey || e.metaKey) && e.key === 'a') {
|
||||
if (e.target.tagName !== 'TEXTAREA' && e.target.tagName !== 'INPUT') {
|
||||
e.preventDefault();
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(code);
|
||||
const selection = window.getSelection();
|
||||
selection.removeAllRanges();
|
||||
selection.addRange(range);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
document.addEventListener('keydown', (e) => {
|
||||
if ((e.ctrlKey || e.metaKey) && e.key === 's') {
|
||||
const form = document.getElementById('paste-form');
|
||||
if (form) {
|
||||
e.preventDefault();
|
||||
form.submit();
|
||||
}
|
||||
}
|
||||
});
|
||||
})();
|
||||
+43
-45
@@ -4,9 +4,7 @@
|
||||
--text-dim: #8b949e;
|
||||
--border: #30363d;
|
||||
--primary: #238636;
|
||||
--primary-hover: #2ea043;
|
||||
--secondary: #21262d;
|
||||
--secondary-hover: #30363d;
|
||||
--accent: #58a6ff;
|
||||
--highlight: rgba(241, 250, 140, 0.1);
|
||||
|
||||
@@ -138,77 +136,81 @@ textarea {
|
||||
flex-grow: 1;
|
||||
width: 100%;
|
||||
font-family: inherit;
|
||||
font-size: 0.95rem;
|
||||
font-size: 0.9rem;
|
||||
line-height: var(--line-height);
|
||||
border: none;
|
||||
outline: none;
|
||||
background-color: transparent !important;
|
||||
color: inherit;
|
||||
resize: none;
|
||||
padding: 0.5rem;
|
||||
white-space: pre;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
pre,
|
||||
pre {
|
||||
background: transparent !important;
|
||||
padding: 0 !important;
|
||||
margin: 0 !important;
|
||||
font-family: inherit !important;
|
||||
font-size: 0.9rem !important;
|
||||
line-height: var(--line-height) !important;
|
||||
flex-grow: 1;
|
||||
padding-left: 1rem !important;
|
||||
overflow: visible;
|
||||
}
|
||||
|
||||
code {
|
||||
background: transparent !important;
|
||||
padding: 0 !important;
|
||||
margin: 0 !important;
|
||||
font-family: inherit !important;
|
||||
font-size: inherit !important;
|
||||
font-size: 0.9rem !important;
|
||||
line-height: var(--line-height) !important;
|
||||
}
|
||||
|
||||
code.with-line-numbers {
|
||||
white-space: pre !important;
|
||||
word-wrap: normal !important;
|
||||
display: block;
|
||||
}
|
||||
|
||||
.line {
|
||||
display: grid;
|
||||
grid-template-columns: calc(var(--digits, 1) * 1ch + 2rem) minmax(0, 1fr);
|
||||
width: 100%;
|
||||
min-height: calc(1em * var(--line-height));
|
||||
scroll-margin-top: 2rem;
|
||||
content-visibility: auto;
|
||||
contain-intrinsic-size: 1px calc(1em * var(--line-height));
|
||||
contain: paint;
|
||||
#paste-content {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.line-number {
|
||||
grid-column: 1;
|
||||
.line-numbers {
|
||||
flex-shrink: 0;
|
||||
text-align: right;
|
||||
padding-right: 1rem;
|
||||
color: var(--text-dim);
|
||||
opacity: 0.3;
|
||||
border-right: 1px solid var(--border);
|
||||
user-select: none;
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
font-size: 0.9rem;
|
||||
line-height: var(--line-height);
|
||||
min-width: calc(var(--digits, 1) * 1ch + 2rem);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.line-number:hover {
|
||||
.line-numbers a {
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
display: block;
|
||||
opacity: 0.3;
|
||||
}
|
||||
|
||||
.line-numbers a:hover {
|
||||
opacity: 0.8;
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.line-code {
|
||||
grid-column: 2;
|
||||
padding-left: 1rem;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.line:target {
|
||||
background-color: var(--highlight);
|
||||
}
|
||||
|
||||
.line:target .line-number {
|
||||
.line-numbers a:target,
|
||||
.line-numbers a.active {
|
||||
opacity: 1;
|
||||
color: #f1fa8c;
|
||||
border-right-color: #f1fa8c;
|
||||
border-right-width: 2px;
|
||||
border-right: 2px solid #f1fa8c;
|
||||
margin-right: -1px;
|
||||
}
|
||||
|
||||
::selection {
|
||||
@@ -258,15 +260,11 @@ code.with-line-numbers {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.line {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.line-number {
|
||||
.line-numbers {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.line-code {
|
||||
pre {
|
||||
padding-left: 0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,7 +5,9 @@
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<link rel="icon" type="image/vnd.microsoft.icon" href="/static/favicon.ico" />
|
||||
<title>{{ .Title }}</title>
|
||||
<link rel="preload" href="/static/highlight.min.js" as="script">
|
||||
<link rel="stylesheet" href="/static/github-dark.min.css">
|
||||
<link rel="stylesheet" href="/static/style.css">
|
||||
<script src="/static/highlight.min.js"></script>
|
||||
|
||||
+2
-46
@@ -24,46 +24,9 @@
|
||||
<main>
|
||||
{{ if .IsPreview }}
|
||||
<div id="paste-content" class="content-wrapper" style="--digits: {{ .GutterSize }};">
|
||||
<div id="line-numbers" class="line-numbers" aria-hidden="true"></div>
|
||||
<pre><code id="code-block" data-line-count="{{ .LineCount }}">{{ .Content }}</code></pre>
|
||||
</div>
|
||||
<script>
|
||||
(function () {
|
||||
const code = document.getElementById('code-block');
|
||||
const lineCount = parseInt(code.getAttribute('data-line-count'));
|
||||
|
||||
hljs.highlightElement(code);
|
||||
|
||||
const lines = code.innerHTML.split(/\r?\n/);
|
||||
const fragment = [];
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const num = i + 1;
|
||||
fragment.push('<div class="line" id="L' + num + '"><a href="#L' + num + '" class="line-number">' + num + '</a><div class="line-code">' + (lines[i] || ' ') + '</div></div>');
|
||||
}
|
||||
|
||||
requestAnimationFrame(() => {
|
||||
code.innerHTML = fragment.join('');
|
||||
code.classList.add('with-line-numbers');
|
||||
|
||||
if (window.location.hash) {
|
||||
const target = document.querySelector(window.location.hash);
|
||||
if (target) target.scrollIntoView();
|
||||
}
|
||||
});
|
||||
|
||||
document.addEventListener('keydown', (e) => {
|
||||
if ((e.ctrlKey || e.metaKey) && e.key === 'a') {
|
||||
if (e.target.tagName !== 'TEXTAREA' && e.target.tagName !== 'INPUT') {
|
||||
e.preventDefault();
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(code);
|
||||
const selection = window.getSelection();
|
||||
selection.removeAllRanges();
|
||||
selection.addRange(range);
|
||||
}
|
||||
}
|
||||
});
|
||||
})();
|
||||
</script>
|
||||
{{ else }}
|
||||
<div class="content-wrapper">
|
||||
{{ if .Error }}
|
||||
@@ -77,14 +40,7 @@
|
||||
autocomplete="off" autocorrect="off" autocapitalize="off" spellcheck="false">{{ .Content }}</textarea>
|
||||
</form>
|
||||
</div>
|
||||
<script>
|
||||
document.addEventListener('keydown', (e) => {
|
||||
if ((e.ctrlKey || e.metaKey) && e.key === 's') {
|
||||
e.preventDefault();
|
||||
document.getElementById('paste-form').submit();
|
||||
}
|
||||
});
|
||||
</script>
|
||||
{{ end }}
|
||||
<script src="/static/script.js"></script>
|
||||
</main>
|
||||
{{ end }}
|
||||
|
||||
Reference in New Issue
Block a user