Syntax Highlighting tool, Markdown guide, unread share badge, Open in menu
- Syntax Highlighting (/syntax): highlight.js tokens rendered with VS Code (Dark/Light Modern, One Dark Pro, Monokai, Dracula, GitHub) and Android Studio (Darcula, Dark, IntelliJ Light) colors; copy as rich text (VS Code clipboard HTML), download RTF, share. Format via Prettier/sql-formatter (lazy-loaded), the JSON printer, or built-in whitespace-only formatters for brace languages, Python and XML. - Markdown: Guide dialog, source next to rendered output, with Insert. - Pastes created by Share count as unread on the Pastebin nav badge. - Paste view: Open in menu built from registry opensPaste tools. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
f4232ef9b5
commit
dc2b12a3c6
37 changed files with 3704 additions and 27 deletions
|
|
@ -65,13 +65,36 @@ function renderNav() {
|
|||
...grouped(TOOLS.filter((t) => matches(t, q))).map(([cat, tools]) =>
|
||||
el('div.nav-group', {},
|
||||
el('div.nav-heading', {}, cat),
|
||||
tools.map((t) => el('a.nav-item', { href: t.path, dataset: { path: t.path } }, el('span.nav-icon', {}, t.icon), t.name)),
|
||||
tools.map((t) => el('a.nav-item', { href: t.path, dataset: { path: t.path, tool: t.id } },
|
||||
el('span.nav-icon', {}, t.icon), el('span.nav-label', {}, t.name), t.badge ? el('span.badge', { hidden: true }) : null)),
|
||||
),
|
||||
),
|
||||
);
|
||||
markActive();
|
||||
updateBadges();
|
||||
}
|
||||
|
||||
// Counts on nav items (e.g. unread shared pastes), plus a dot on the mobile menu button.
|
||||
function updateBadges() {
|
||||
let total = 0;
|
||||
for (const t of TOOLS) {
|
||||
if (!t.badge) continue;
|
||||
let n = 0;
|
||||
try { n = t.badge() || 0; } catch {}
|
||||
total += n;
|
||||
const b = navList.querySelector(`.nav-item[data-tool="${t.id}"] .badge`);
|
||||
if (b) {
|
||||
b.hidden = !n;
|
||||
b.textContent = n > 99 ? '99+' : String(n);
|
||||
b.title = `${n} new`;
|
||||
}
|
||||
}
|
||||
menuBtn.classList.toggle('has-badge', total > 0);
|
||||
}
|
||||
window.addEventListener('tools:badges', updateBadges);
|
||||
window.addEventListener('storage', (e) => { if (!e.key || e.key.startsWith('tools:')) updateBadges(); }); // other tabs
|
||||
setInterval(updateBadges, 60000); // expiry
|
||||
|
||||
function markActive() {
|
||||
const tool = findTool(location.pathname);
|
||||
for (const a of navList.querySelectorAll('.nav-item')) {
|
||||
|
|
|
|||
|
|
@ -3,6 +3,13 @@
|
|||
// To add a tool: create js/tools/<id>.js exporting mount(el, ctx) (see app.js for ctx),
|
||||
// then add an entry here. A tool owns every path under its `path`, so /paste/abc123
|
||||
// goes to the paste tool with ctx.rest = "abc123".
|
||||
//
|
||||
// Optional fields:
|
||||
// opensPaste: true the tool loads <path>?paste=<id>; it then appears in a paste's "Open in" menu
|
||||
// badge: () => number a count shown on the tool's nav item (0 hides it); call
|
||||
// window.dispatchEvent(new Event('tools:badges')) when it changes
|
||||
import { unreadCount } from './tools/paste-state.js';
|
||||
|
||||
export const TOOLS = [
|
||||
{
|
||||
id: 'markdown',
|
||||
|
|
@ -11,8 +18,19 @@ export const TOOLS = [
|
|||
category: 'Text',
|
||||
icon: 'M↓',
|
||||
description: 'Write Markdown with a live preview: side by side, editor only or full-page preview.',
|
||||
opensPaste: true,
|
||||
load: () => import('./tools/markdown.js'),
|
||||
},
|
||||
{
|
||||
id: 'syntax',
|
||||
name: 'Syntax Highlighting',
|
||||
path: '/syntax',
|
||||
category: 'Code',
|
||||
icon: '</>',
|
||||
description: 'Highlight and format source code with VS Code and Android Studio themes, then copy it as rich text or RTF.',
|
||||
opensPaste: true,
|
||||
load: () => import('./tools/syntax.js'),
|
||||
},
|
||||
{
|
||||
id: 'json',
|
||||
name: 'JSON editor',
|
||||
|
|
@ -20,6 +38,7 @@ export const TOOLS = [
|
|||
category: 'Data',
|
||||
icon: '{ }',
|
||||
description: 'Validate, prettify and compact JSON, with a live tree view you can edit.',
|
||||
opensPaste: true,
|
||||
load: () => import('./tools/json.js'),
|
||||
},
|
||||
{
|
||||
|
|
@ -29,9 +48,10 @@ export const TOOLS = [
|
|||
category: 'Sharing',
|
||||
icon: '⎘',
|
||||
description: 'Share text with a short link. Pastes are deleted after 24 hours.',
|
||||
badge: unreadCount,
|
||||
load: () => import('./tools/paste.js'),
|
||||
},
|
||||
];
|
||||
|
||||
// Sidebar groups appear in this order; unknown categories go last, alphabetically.
|
||||
export const CATEGORY_ORDER = ['Text', 'Data', 'Sharing'];
|
||||
export const CATEGORY_ORDER = ['Text', 'Code', 'Data', 'Sharing'];
|
||||
|
|
|
|||
536
app/static/js/tools/code-format.js
Normal file
536
app/static/js/tools/code-format.js
Normal file
|
|
@ -0,0 +1,536 @@
|
|||
// "Format" for the Syntax Highlighting tool.
|
||||
//
|
||||
// - Prettier (loaded on demand) for JS/TS, CSS/SCSS/Less, HTML, YAML, Markdown, GraphQL
|
||||
// - sql-formatter (on demand) for SQL; json-core for JSON (lossless)
|
||||
// - our own whitespace-only formatters for brace languages (Kotlin, Java, C-family, Go,
|
||||
// Rust, Swift, Dart, PHP, Scala, Groovy), Python and XML. They re-indent, fix spacing and
|
||||
// brace placement, and never change anything but whitespace: strings and comments are
|
||||
// masked out first (tests check that removing all whitespace gives identical text).
|
||||
// - everything else: trailing whitespace and blank-line cleanup only
|
||||
import { tokenize } from './highlight-core.js';
|
||||
import { parse as parseJson, stringify as stringifyJson } from './json-core.js';
|
||||
|
||||
const PRETTIER = {
|
||||
javascript: ['babel', ['babel', 'estree']],
|
||||
typescript: ['babel-ts', ['babel', 'estree']],
|
||||
css: ['css', ['postcss']],
|
||||
scss: ['scss', ['postcss']],
|
||||
less: ['less', ['postcss']],
|
||||
markdown: ['markdown', ['markdown']],
|
||||
yaml: ['yaml', ['yaml']],
|
||||
graphql: ['graphql', ['graphql']],
|
||||
html: ['html', ['html', 'babel', 'estree', 'postcss']],
|
||||
};
|
||||
const BRACE = new Set(['kotlin', 'java', 'c', 'cpp', 'csharp', 'go', 'rust', 'swift', 'dart', 'objectivec', 'php', 'scala', 'groovy', 'protobuf']);
|
||||
// XML stays at 4 like Android Studio; HTML (via Prettier) uses 2.
|
||||
const TWO_SPACE = new Set(['javascript', 'typescript', 'css', 'scss', 'less', 'html', 'json', 'yaml', 'markdown', 'graphql', 'dart', 'ruby', 'sql']);
|
||||
|
||||
/** Which engine formats a language, for the UI ("Format (Prettier)"…). */
|
||||
export function formatterName(lang, code = '') {
|
||||
if (PRETTIER[lang] || (lang === 'xml' && looksLikeHtml(code))) return 'Prettier';
|
||||
if (lang === 'sql') return 'sql-formatter';
|
||||
if (lang === 'json' || lang === 'xml' || lang === 'python' || BRACE.has(lang)) return 'built-in';
|
||||
return 'whitespace cleanup';
|
||||
}
|
||||
|
||||
export function indentUnit(lang, indent) {
|
||||
if (indent === 'tab') return '\t';
|
||||
if (indent === '2') return ' ';
|
||||
if (indent === '4') return ' ';
|
||||
if (lang === 'go' || lang === 'makefile') return '\t';
|
||||
return TWO_SPACE.has(lang) ? ' ' : ' ';
|
||||
}
|
||||
|
||||
// HTML goes to Prettier; real XML (declaration or namespaces: Android layouts, Mallard, SVG…) to formatXml.
|
||||
const looksLikeHtml = (code) => /<!doctype html|<html[\s>]/i.test(code) ||
|
||||
(!/<\?xml|\sxmlns[:=]/.test(code) && /<(head|body|div|span|p|script|style|section|main|nav|ul|table)[\s>]/i.test(code));
|
||||
|
||||
export async function formatCode(code, lang, { indent = 'auto' } = {}) {
|
||||
code = code.replace(/\r\n?/g, '\n');
|
||||
const unit = indentUnit(lang, indent);
|
||||
if (lang === 'xml' && looksLikeHtml(code)) {
|
||||
try {
|
||||
return await prettierFormat(code, ...PRETTIER.html, unit);
|
||||
} catch {
|
||||
return formatXml(code, unit); // wasn't HTML after all
|
||||
}
|
||||
}
|
||||
if (PRETTIER[lang]) return prettierFormat(code, ...PRETTIER[lang], unit);
|
||||
if (lang === 'json') return stringifyJson(parseJson(code), unit) + '\n';
|
||||
if (lang === 'sql') {
|
||||
const { format } = await import('../../vendor/sql-formatter.mjs');
|
||||
return format(code, { language: 'sql', tabWidth: unit === '\t' ? 4 : unit.length, useTabs: unit === '\t' }) + '\n';
|
||||
}
|
||||
if (lang === 'xml') return formatXml(code, unit);
|
||||
if (lang === 'python') return formatPython(code, unit);
|
||||
if (BRACE.has(lang)) return formatBraces(code, lang, unit);
|
||||
return cleanupWhitespace(code);
|
||||
}
|
||||
|
||||
async function prettierFormat(code, parser, plugins, unit) {
|
||||
const [prettier, ...mods] = await Promise.all([
|
||||
import('../../vendor/prettier/standalone.mjs'),
|
||||
...plugins.map((p) => import(`../../vendor/prettier/${p}.mjs`)),
|
||||
]);
|
||||
try {
|
||||
return await prettier.format(code, {
|
||||
parser,
|
||||
plugins: mods.map((m) => m.default || m),
|
||||
printWidth: 100,
|
||||
tabWidth: unit === '\t' ? 4 : unit.length,
|
||||
useTabs: unit === '\t',
|
||||
});
|
||||
} catch (err) {
|
||||
// Prettier's messages include a code frame; the first line is enough for a toast.
|
||||
throw new Error(String(err.message).split('\n')[0]);
|
||||
}
|
||||
}
|
||||
|
||||
export function cleanupWhitespace(code, maxBlank = 2) {
|
||||
const out = [];
|
||||
let blanks = 0;
|
||||
for (const raw of code.split('\n')) {
|
||||
const line = raw.trimEnd();
|
||||
if (!line) {
|
||||
if (out.length && ++blanks <= maxBlank) out.push('');
|
||||
} else {
|
||||
blanks = 0;
|
||||
out.push(line);
|
||||
}
|
||||
}
|
||||
while (out.length && !out[out.length - 1]) out.pop();
|
||||
return out.join('\n') + '\n';
|
||||
}
|
||||
|
||||
// ---------- masking: hide strings and comments behind placeholders ----------
|
||||
|
||||
const PH_OPEN = '';
|
||||
const PH_CLOSE = '';
|
||||
const PH_RE = /([0-9a-z]+)/g;
|
||||
|
||||
function mask(code, lang) {
|
||||
const saved = [];
|
||||
let out = '';
|
||||
let buf = null;
|
||||
const flush = () => {
|
||||
if (buf == null) return;
|
||||
// Keep newlines at the edges of an opaque run outside the placeholder, so lines stay lines.
|
||||
const lead = buf.match(/^\n*/)[0];
|
||||
const trail = buf.slice(lead.length).match(/\n*$/)[0];
|
||||
const core = buf.slice(lead.length, buf.length - trail.length);
|
||||
out += lead + (core ? PH_OPEN + (saved.push(core) - 1).toString(36) + PH_CLOSE : '') + trail;
|
||||
buf = null;
|
||||
};
|
||||
for (const t of tokenize(code, lang)) {
|
||||
if (t.opaque) buf = (buf ?? '') + t.text;
|
||||
else {
|
||||
flush();
|
||||
out += t.text;
|
||||
}
|
||||
}
|
||||
flush();
|
||||
return { text: out, saved };
|
||||
}
|
||||
|
||||
const isLineComment = (s) => /^(\/\/|#)/.test(s);
|
||||
const phAt = (line, saved, where) => {
|
||||
const m = where === 'end' ? line.match(/([0-9a-z]+)$/) : line.match(/^([0-9a-z]+)/);
|
||||
return m ? saved[parseInt(m[1], 36)] : null;
|
||||
};
|
||||
|
||||
function unmask(lines, saved) {
|
||||
return lines.map((line) => {
|
||||
const indent = line.match(/^[ \t]*/)[0];
|
||||
return line.replace(PH_RE, (_, id) => {
|
||||
const text = saved[parseInt(id, 36)];
|
||||
// Re-align the "*" lines of a block comment with its (possibly re-indented) first line.
|
||||
if (text.startsWith('/*') && text.includes('\n')) {
|
||||
return text.split('\n').map((l, i) => (i && /^\s*\*/.test(l) ? indent + ' ' + l.trim() : i ? l.trimEnd() : l.trimEnd())).join('\n');
|
||||
}
|
||||
return text;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// ---------- spacing rules (operate on one masked line) ----------
|
||||
|
||||
const ASSIGN_OPS = ['>>>=', '<<=', '>>=', '<=>', '===', '!==', '**=', '??=', '//=', '==', '!=', '<=', '>=', '+=', '-=', '*=', '/=', '%=', '&=', '|=', '^=', '&&', '||', '??', '=>', ':=', '->', '='];
|
||||
const OP_CHARS = new Set('=!<>+-*/%&|^?:.~');
|
||||
const WORDISH = /[A-Za-z0-9_$)\]'"]/;
|
||||
const NOT_BINARY_AFTER = new Set(['return', 'case', 'yield', 'throw', 'in', 'is', 'else', 'await', 'typeof', 'delete', 'void', 'new', 'and', 'or', 'not', 'if', 'elif', 'while', 'print', 'echo']);
|
||||
|
||||
/**
|
||||
* Spaces operators, commas, semicolons and brackets in one masked line.
|
||||
* opts: lang; depth0 (Python: '=' unspaced inside brackets); colon (space after ':');
|
||||
* arith (space binary + - * / %); pointerLang (leave '*' alone); arrowSpaced ('->');
|
||||
* braceSpaceBefore ('){' → ') {'); innerBraceSpace ('{x}' → '{ x }');
|
||||
* compare (space < and > comparisons); generics (tell List<T> apart from a < b).
|
||||
*/
|
||||
function spaceLine(line, opts, startStack = []) {
|
||||
const stack = [...startStack];
|
||||
const top = () => stack[stack.length - 1];
|
||||
let out = '';
|
||||
let genericDepth = 0;
|
||||
const lastWord = () => (out.trimEnd().match(/[A-Za-z_]\w*$/) || [''])[0];
|
||||
const skipSpaces = (i) => {
|
||||
while (line[i] === ' ' || line[i] === '\t') i++;
|
||||
return i;
|
||||
};
|
||||
// A binary operator gets a space on both sides, except right after an opening bracket or comma.
|
||||
const spaced = (op) => {
|
||||
out = out.trimEnd();
|
||||
out += !out || /[([{,]$/.test(out) ? `${op} ` : ` ${op} `;
|
||||
};
|
||||
for (let i = 0; i < line.length; ) {
|
||||
const ch = line[i];
|
||||
if (ch === PH_OPEN) {
|
||||
const j = line.indexOf(PH_CLOSE, i);
|
||||
out += line.slice(i, j + 1);
|
||||
i = j + 1;
|
||||
continue;
|
||||
}
|
||||
if (ch === ' ' || ch === '\t') {
|
||||
if (out && !out.endsWith(' ')) out += ' ';
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (ch === '(' || ch === '[') {
|
||||
stack.push(ch);
|
||||
out += ch;
|
||||
i = skipSpaces(i + 1);
|
||||
continue;
|
||||
}
|
||||
if (ch === '{') {
|
||||
if (opts.braceSpaceBefore && /[\w)\]>"']$/.test(out) && !(opts.lang === 'go' && /\w$/.test(out))) out += ' ';
|
||||
stack.push(ch);
|
||||
out += ch;
|
||||
const j = skipSpaces(i + 1);
|
||||
if (j < line.length && line[j] !== '}' && (opts.innerBraceSpace || j > i + 1)) out += ' ';
|
||||
i = j;
|
||||
continue;
|
||||
}
|
||||
if (ch === ')' || ch === ']') {
|
||||
if (/[^([]\s+$/.test(out)) out = out.trimEnd();
|
||||
stack.pop();
|
||||
out += ch;
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (ch === '}') {
|
||||
if (opts.innerBraceSpace && out.trim() && !/[{\s]$/.test(out)) out += ' ';
|
||||
stack.pop();
|
||||
out += ch;
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (ch === ',' || ch === ';') {
|
||||
out = out.trimEnd() + ch;
|
||||
i = skipSpaces(i + 1);
|
||||
const next = line[i];
|
||||
if (next && (!')]};,'.includes(next) || (next === '}' && (opts.innerBraceSpace || line[i - 1] === ' ')))) out += ' ';
|
||||
continue;
|
||||
}
|
||||
// < and > : generics stay tight (List<String>), comparisons get spaces (a < b)
|
||||
if (opts.compare && (ch === '<' || ch === '>') && !OP_CHARS.has(line[i - 1] ?? ' ') && !OP_CHARS.has(line[i + 1] ?? ' ')) {
|
||||
if (ch === '<' && opts.generics && isGenericOpen(line, i)) {
|
||||
genericDepth++;
|
||||
out = out.trimEnd() + '<';
|
||||
i = skipSpaces(i + 1);
|
||||
continue;
|
||||
}
|
||||
if (ch === '>' && genericDepth > 0) {
|
||||
genericDepth--;
|
||||
out = out.trimEnd() + '>';
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
spaced(ch);
|
||||
i = skipSpaces(i + 1);
|
||||
continue;
|
||||
}
|
||||
if (ch === '>' && genericDepth > 0 && line[i + 1] === '>') {
|
||||
// closing nested generics: List<List<Int>>
|
||||
while (line[i] === '>' && genericDepth > 0) {
|
||||
genericDepth--;
|
||||
out += '>';
|
||||
i++;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// Assignment, comparison and logical operators. Only at the start of an operator run,
|
||||
// and only when the run is exactly a known operator (optionally followed by a unary - ! . ~).
|
||||
if (OP_CHARS.has(ch) && !OP_CHARS.has(line[i - 1] ?? ' ')) {
|
||||
const op = ASSIGN_OPS.find((o) => line.startsWith(o, i));
|
||||
const after = line[i + (op?.length || 0)];
|
||||
const usable = op && !(OP_CHARS.has(after ?? ' ') && !'-!.~&*'.includes(after)) && !(genericDepth && op.startsWith('>')) &&
|
||||
!(op === '->' && !opts.arrowSpaced) && !(op === '=' && top() === '[' && opts.lang === 'cpp');
|
||||
if (usable) {
|
||||
if (op === '=' && opts.depth0 && stack.length && top() !== '{') {
|
||||
// Python keyword argument / default: no spaces, unless it's annotated (PEP 8).
|
||||
const since = out.slice(Math.max(out.lastIndexOf('('), out.lastIndexOf(',')) + 1);
|
||||
if (!since.includes(':')) {
|
||||
out = out.trimEnd() + '=';
|
||||
i = skipSpaces(i + 1);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
spaced(op);
|
||||
i = skipSpaces(i + op.length);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// Binary arithmetic: only between two operands, never after keywords like return.
|
||||
if (opts.arith && '+-*/%'.includes(ch) && !OP_CHARS.has(line[i - 1] ?? ' ') && !OP_CHARS.has(line[i + 1] ?? ' ') &&
|
||||
!(opts.pointerLang && ch === '*')) {
|
||||
const before = out.trimEnd().slice(-1);
|
||||
const j = skipSpaces(i + 1);
|
||||
const exponent = (ch === '+' || ch === '-') && /\d[eE]$/.test(out);
|
||||
if (before && WORDISH.test(before) && line[j] && /[A-Za-z0-9_$('"]/.test(line[j]) && !exponent && !NOT_BINARY_AFTER.has(lastWord())) {
|
||||
spaced(ch);
|
||||
i = j;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (ch === ':' && opts.colon && line[i + 1] !== ':' && line[i - 1] !== ':' && top() !== '[') {
|
||||
if (opts.depth0) out = out.trimEnd(); // Python: no space before ':'
|
||||
out += ':';
|
||||
i = skipSpaces(i + 1);
|
||||
if (line[i] && /[A-Za-z0-9_$("'\[{@-]/.test(line[i])) out += ' ';
|
||||
continue;
|
||||
}
|
||||
out += ch;
|
||||
i++;
|
||||
}
|
||||
return { text: out.trimEnd(), stack };
|
||||
}
|
||||
|
||||
// Does the '<' at i open a generic type list? Scan to its matching '>' through type-ish text only.
|
||||
function isGenericOpen(line, i) {
|
||||
let depth = 0;
|
||||
for (let j = i; j < line.length; j++) {
|
||||
const c = line[j];
|
||||
if (c === '<') depth++;
|
||||
else if (c === '>') {
|
||||
if (--depth === 0) return j > i + 1;
|
||||
} else if (!/[\w\s,.?\[\]*:&@'$]/.test(c) || line.startsWith('&&', j)) return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// ---------- brace languages ----------
|
||||
|
||||
const CONTROL_PAREN = /\b(if|for|while|switch|catch|when|using|lock|foreach|synchronized|guard|elif)\(/g;
|
||||
const CONTINUATION_START = /^(\.(?!\.)|\?\.|&&|\|\||\?(?![?.])|:(?!:)|\+(?!\+)|-(?![->])|\|>)/;
|
||||
const CONTINUATION_END = /((?<![=!<>])=|&&|\|\||(?<!\+)\+|(?<!-)-|->|=>)$/;
|
||||
// An unbraced body: `if (x)` / `else` / `for (…)` alone on a line indents the next line.
|
||||
const UNBRACED = /^(\}\s*)?(if|else\s+if|for|foreach|while)\b.*\)$|^(\}\s*)?else$/;
|
||||
|
||||
export function formatBraces(code, lang, unit) {
|
||||
const { text, saved } = mask(code, lang);
|
||||
const allman = lang === 'csharp';
|
||||
const preproc = lang === 'c' || lang === 'cpp' || lang === 'objectivec';
|
||||
const caseAtSwitch = lang === 'go' || lang === 'swift';
|
||||
const opts = {
|
||||
lang,
|
||||
braceSpaceBefore: true,
|
||||
innerBraceSpace: ['kotlin', 'swift', 'rust', 'scala', 'groovy'].includes(lang),
|
||||
colon: ['kotlin', 'swift', 'rust', 'scala', 'go', 'dart'].includes(lang),
|
||||
arith: true,
|
||||
compare: true,
|
||||
generics: true,
|
||||
pointerLang: ['c', 'cpp', 'objectivec', 'rust', 'go'].includes(lang),
|
||||
arrowSpaced: lang !== 'c' && lang !== 'cpp' && lang !== 'objectivec' && lang !== 'php',
|
||||
};
|
||||
|
||||
// 1. spacing, per line
|
||||
let lines = text.split('\n').map((raw) => {
|
||||
const t = raw.trim();
|
||||
if (!t) return '';
|
||||
if (preproc && t.startsWith('#')) return t;
|
||||
return spaceLine(t.replace(CONTROL_PAREN, '$1 ('), opts).text.replace(/\}\s*(else|catch|finally)\b/g, '} $1');
|
||||
});
|
||||
|
||||
// 2. brace placement
|
||||
const placed = [];
|
||||
const lastCode = () => {
|
||||
for (let k = placed.length - 1; k >= 0; k--) if (placed[k]) return k;
|
||||
return -1;
|
||||
};
|
||||
for (let line of lines) {
|
||||
if (allman) {
|
||||
const m = line.match(/^\}\s*(else|catch|finally)\b(.*)$/);
|
||||
if (m) {
|
||||
placed.push('}');
|
||||
line = (m[1] + m[2]).trim();
|
||||
}
|
||||
if (line.endsWith('{') && line !== '{' && !(preproc && line.startsWith('#'))) {
|
||||
placed.push(line.slice(0, -1).trimEnd(), '{');
|
||||
continue;
|
||||
}
|
||||
placed.push(line);
|
||||
continue;
|
||||
}
|
||||
const p = lastCode();
|
||||
const prev = p >= 0 ? placed[p] : '';
|
||||
const prevEndsInComment = isLineComment(phAt(prev, saved, 'end') || '');
|
||||
if (/^\{(\s|$)/.test(line) && p >= 0 && !/[;{}:,]$/.test(prev) && !prevEndsInComment && !(preproc && prev.startsWith('#'))) {
|
||||
placed.length = p + 1; // drop blank lines between
|
||||
placed[p] = /[([]$/.test(prev) ? prev + line : `${prev} ${line}`;
|
||||
continue;
|
||||
}
|
||||
if (/^(else|catch|finally)\b/.test(line) && prev === '}') {
|
||||
placed.length = p + 1;
|
||||
placed[p] = `} ${line}`;
|
||||
continue;
|
||||
}
|
||||
placed.push(line);
|
||||
}
|
||||
|
||||
// 3. indentation: brackets left open by a line indent what follows by one level from that line
|
||||
// (a line opening several brackets still adds one level); continuation lines add one more.
|
||||
const out = [];
|
||||
let stack = [];
|
||||
let prevCode = '';
|
||||
let prevOpened = false;
|
||||
for (const line of placed) {
|
||||
if (!line) {
|
||||
out.push('');
|
||||
continue;
|
||||
}
|
||||
if (preproc && line.startsWith('#')) {
|
||||
out.push(line);
|
||||
continue;
|
||||
}
|
||||
const lead = line.match(/^[)\]}]+/)?.[0].length || 0;
|
||||
const visible = stack.slice(0, Math.max(0, stack.length - lead));
|
||||
let level = visible.length ? visible[visible.length - 1].indent : 0;
|
||||
const owner = visible[visible.length - 1];
|
||||
const isCase = /^(case\b[^>]*|default\s*):(\s*[0-9a-z]+)?$/.test(line) || /^(case\b.*|default\s*):\s*\S/.test(line) && !/->/.test(line);
|
||||
if (isCase && caseAtSwitch) level = Math.max(0, level - 1);
|
||||
else if (owner?.inCase && !isCase && !lead) level++;
|
||||
if (lang === 'cpp' && /^(public|private|protected)\s*:/.test(line)) level = Math.max(0, level - 1);
|
||||
const contStart = CONTINUATION_START.test(line) && !/^-\d/.test(line);
|
||||
const contEnd = prevCode && !prevOpened && (CONTINUATION_END.test(prevCode) || UNBRACED.test(prevCode)) && !line.startsWith('{');
|
||||
if (!lead && (contStart || contEnd)) level++;
|
||||
out.push(unit.repeat(level) + line);
|
||||
const depthBefore = stack.length;
|
||||
for (const ch of line.replace(PH_RE, '')) {
|
||||
if ('([{'.includes(ch)) stack.push({ indent: level + 1, inCase: false });
|
||||
else if (')]}'.includes(ch)) stack.pop();
|
||||
}
|
||||
prevOpened = stack.length > depthBefore;
|
||||
if (isCase && owner && !caseAtSwitch) owner.inCase = true;
|
||||
prevCode = line.replace(/\s*[0-9a-z]+$/, (m) => (isLineComment(phAt(line, saved, 'end') || '') ? '' : m));
|
||||
}
|
||||
|
||||
// 4. blank lines: none right inside braces, at most one in a row
|
||||
const tidy = [];
|
||||
for (let k = 0; k < out.length; k++) {
|
||||
const line = out[k];
|
||||
if (!line) {
|
||||
const prev = tidy[tidy.length - 1];
|
||||
const next = out.slice(k + 1).find((l) => l);
|
||||
if (!tidy.length || prev === '' || /[{(\[]$/.test(prev) || (next && /^\s*[}\])]/.test(next)) || next === undefined) continue;
|
||||
}
|
||||
tidy.push(line);
|
||||
}
|
||||
return unmask(tidy, saved).join('\n') + '\n';
|
||||
}
|
||||
|
||||
// ---------- Python ----------
|
||||
|
||||
export function formatPython(code, unit = ' ') {
|
||||
const { text, saved } = mask(code, 'python');
|
||||
const opts = { lang: 'python', depth0: true, colon: true, arith: true, arrowSpaced: true, compare: true };
|
||||
const out = [];
|
||||
const widths = [0]; // indentation widths of the enclosing blocks, as written
|
||||
const open = []; // brackets still open from earlier lines: {ch, level}
|
||||
let blanks = 0;
|
||||
for (const raw of text.split('\n')) {
|
||||
const t = raw.trim();
|
||||
if (!t) {
|
||||
if (out.length && ++blanks <= 2) out.push('');
|
||||
continue;
|
||||
}
|
||||
blanks = 0;
|
||||
let level;
|
||||
if (open.length) {
|
||||
// continuation inside brackets: one level deeper than the line that opened them
|
||||
level = open[open.length - 1].level + (/^[)\]}]/.test(t) ? 0 : 1);
|
||||
} else {
|
||||
const w = raw.match(/^[ \t]*/)[0].replace(/\t/g, ' ').length;
|
||||
if (w > widths[widths.length - 1]) widths.push(w);
|
||||
else while (widths.length > 1 && w < widths[widths.length - 1]) widths.pop();
|
||||
level = widths.length - 1;
|
||||
}
|
||||
let { text: line } = spaceLine(t.replace(CONTROL_PAREN, '$1 ('), opts, open.map((b) => b.ch));
|
||||
// PEP 8: two spaces before an inline comment
|
||||
const tail = phAt(line, saved, 'end');
|
||||
if (tail && isLineComment(tail) && !line.startsWith(PH_OPEN)) line = line.replace(/ ?([0-9a-z]+)$/, ' $1');
|
||||
for (const ch of line.replace(PH_RE, '')) {
|
||||
if ('([{'.includes(ch)) open.push({ ch, level });
|
||||
else if (')]}'.includes(ch)) open.pop();
|
||||
}
|
||||
out.push(unit.repeat(level) + line);
|
||||
}
|
||||
while (out.length && !out[out.length - 1]) out.pop();
|
||||
return unmask(out, saved).join('\n') + '\n';
|
||||
}
|
||||
|
||||
// ---------- XML ----------
|
||||
|
||||
const XML_TOKEN = /<!--[\s\S]*?-->|<!\[CDATA\[[\s\S]*?\]\]>|<\?[\s\S]*?\?>|<!DOCTYPE(?:[^>[]|\[[\s\S]*?\])*>|<\/?[A-Za-z_][^>"']*(?:(?:"[^"]*"|'[^']*')[^>"']*)*>|[^<]+|</g;
|
||||
|
||||
export function formatXml(code, unit = ' ', width = 100) {
|
||||
const tokens = code.match(XML_TOKEN) || [];
|
||||
if (tokens.includes('<')) throw new Error('Not well-formed XML: stray "<"');
|
||||
const out = [];
|
||||
let depth = 0;
|
||||
const pad = () => unit.repeat(depth);
|
||||
for (let i = 0; i < tokens.length; i++) {
|
||||
const tok = tokens[i];
|
||||
if (!tok.startsWith('<')) {
|
||||
const text = tok.trim();
|
||||
if (text) for (const l of text.split('\n')) out.push(pad() + l.trim());
|
||||
continue;
|
||||
}
|
||||
if (tok.startsWith('</')) {
|
||||
depth = Math.max(0, depth - 1);
|
||||
out.push(pad() + tok.replace(/\s+>$/, '>'));
|
||||
continue;
|
||||
}
|
||||
if (tok.startsWith('<!--') || tok.startsWith('<![CDATA[') || tok.startsWith('<?') || /^<!DOCTYPE/i.test(tok)) {
|
||||
out.push(pad() + tok);
|
||||
continue;
|
||||
}
|
||||
const m = tok.match(/^<([^\s/>]+)([\s\S]*?)(\s*\/)?>$/);
|
||||
const name = m[1];
|
||||
const selfClose = !!m[3];
|
||||
const attrs = [...m[2].matchAll(/([^\s=]+)(?:\s*=\s*("[^"]*"|'[^']*'|[^\s"'>]+))?/g)].map((a) => (a[2] ? `${a[1]}=${a[2]}` : a[1]));
|
||||
const end = selfClose ? (m[3].startsWith(' ') || attrs.length > 1 ? ' />' : '/>') : '>';
|
||||
const oneLine = `<${name}${attrs.map((a) => ' ' + a).join('')}${end}`;
|
||||
const androidish = attrs.some((a) => /^(android|app|tools|xmlns):/.test(a));
|
||||
let opening;
|
||||
if (attrs.length > 1 && (androidish || pad().length + oneLine.length > width)) {
|
||||
// Android Studio style: one attribute per line
|
||||
opening = [pad() + `<${name}`, ...attrs.map((a, k) => pad() + unit + a + (k === attrs.length - 1 ? end : ''))];
|
||||
} else opening = [pad() + oneLine];
|
||||
// <a>short text</a> stays on one line
|
||||
const text = tokens[i + 1];
|
||||
const close = tokens[i + 2];
|
||||
if (!selfClose && opening.length === 1 && text && !text.startsWith('<') && close === `</${name}>` && !text.trim().includes('\n')) {
|
||||
out.push(opening[0] + text.trim() + close);
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if (!selfClose && tokens[i + 1] === `</${name}>`) {
|
||||
opening[opening.length - 1] += `</${name}>`;
|
||||
out.push(...opening);
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
out.push(...opening);
|
||||
if (!selfClose) depth++;
|
||||
}
|
||||
return out.join('\n') + '\n';
|
||||
}
|
||||
239
app/static/js/tools/highlight-core.js
Normal file
239
app/static/js/tools/highlight-core.js
Normal file
|
|
@ -0,0 +1,239 @@
|
|||
// Turns source code into themed tokens (via highlight.js) and renders them as
|
||||
// rich-text HTML (inline styles, so it survives pasting into docs/mail/chat) or RTF.
|
||||
import hljs from '../../vendor/hljs/highlight.min.js';
|
||||
import dart from '../../vendor/hljs/dart.min.js';
|
||||
import dockerfile from '../../vendor/hljs/dockerfile.min.js';
|
||||
import groovy from '../../vendor/hljs/groovy.min.js';
|
||||
import nginx from '../../vendor/hljs/nginx.min.js';
|
||||
import powershell from '../../vendor/hljs/powershell.min.js';
|
||||
import protobuf from '../../vendor/hljs/protobuf.min.js';
|
||||
import scala from '../../vendor/hljs/scala.min.js';
|
||||
import { styleFor } from './highlight-themes.js';
|
||||
|
||||
for (const [name, lang] of Object.entries({ dart, dockerfile, groovy, nginx, powershell, protobuf, scala })) {
|
||||
hljs.registerLanguage(name, lang);
|
||||
}
|
||||
|
||||
// Offered in the language picker. exts: file extensions for Open.
|
||||
export const LANGUAGES = [
|
||||
['kotlin', 'Kotlin', 'kt kts'],
|
||||
['java', 'Java', 'java'],
|
||||
['javascript', 'JavaScript', 'js mjs cjs jsx'],
|
||||
['typescript', 'TypeScript', 'ts tsx mts cts'],
|
||||
['python', 'Python', 'py pyw'],
|
||||
['xml', 'XML / HTML', 'xml html htm svg xhtml plist'],
|
||||
['css', 'CSS', 'css'],
|
||||
['scss', 'SCSS', 'scss'],
|
||||
['less', 'Less', 'less'],
|
||||
['json', 'JSON', 'json jsonc'],
|
||||
['yaml', 'YAML', 'yaml yml'],
|
||||
['markdown', 'Markdown', 'md markdown'],
|
||||
['sql', 'SQL', 'sql'],
|
||||
['bash', 'Shell / Bash', 'sh bash zsh'],
|
||||
['c', 'C', 'c h'],
|
||||
['cpp', 'C++', 'cpp cc cxx hpp hh hxx'],
|
||||
['csharp', 'C#', 'cs'],
|
||||
['go', 'Go', 'go'],
|
||||
['rust', 'Rust', 'rs'],
|
||||
['swift', 'Swift', 'swift'],
|
||||
['dart', 'Dart', 'dart'],
|
||||
['objectivec', 'Objective-C', 'm mm'],
|
||||
['php', 'PHP', 'php'],
|
||||
['ruby', 'Ruby', 'rb'],
|
||||
['scala', 'Scala', 'scala sc'],
|
||||
['groovy', 'Groovy / Gradle', 'groovy gradle'],
|
||||
['lua', 'Lua', 'lua'],
|
||||
['perl', 'Perl', 'pl pm'],
|
||||
['r', 'R', 'r'],
|
||||
['graphql', 'GraphQL', 'graphql gql'],
|
||||
['protobuf', 'Protocol Buffers', 'proto'],
|
||||
['dockerfile', 'Dockerfile', 'dockerfile'],
|
||||
['nginx', 'Nginx', 'conf'],
|
||||
['ini', 'INI / TOML', 'ini toml cfg properties'],
|
||||
['powershell', 'PowerShell', 'ps1 psm1'],
|
||||
['makefile', 'Makefile', 'mk'],
|
||||
['diff', 'Diff', 'diff patch'],
|
||||
['plaintext', 'Plain text', 'txt'],
|
||||
].map(([id, name, exts]) => ({ id, name, exts: exts.split(' ') }));
|
||||
|
||||
export const languageName = (id) => LANGUAGES.find((l) => l.id === id)?.name || id;
|
||||
|
||||
export function languageForFile(name) {
|
||||
const lower = name.toLowerCase();
|
||||
if (lower === 'dockerfile' || lower.endsWith('.dockerfile')) return 'dockerfile';
|
||||
if (lower === 'makefile') return 'makefile';
|
||||
const ext = lower.includes('.') ? lower.split('.').pop() : '';
|
||||
return LANGUAGES.find((l) => l.exts.includes(ext))?.id || null;
|
||||
}
|
||||
|
||||
const AUTO_SUBSET = LANGUAGES.map((l) => l.id).filter((id) => id !== 'plaintext');
|
||||
|
||||
/** Best-guess language for a snippet. */
|
||||
export function detect(code) {
|
||||
if (!code.trim()) return 'plaintext';
|
||||
const r = hljs.highlightAuto(code.slice(0, 20000), AUTO_SUBSET);
|
||||
return r.language && r.relevance >= 3 ? r.language : 'plaintext';
|
||||
}
|
||||
|
||||
// ---------- tokens ----------
|
||||
|
||||
// highlight.js scope → token type; looked up innermost scope first, longest name first.
|
||||
const SCOPE_TYPE = {
|
||||
keyword: 'keyword', 'variable.language_': 'keyword', 'template-tag': 'keyword',
|
||||
built_in: 'builtin', type: 'type', 'title.class_': 'className', 'title.class_.inherited__': 'className',
|
||||
'title.function_': 'function', 'title.function.invoke__': 'functionCall', title: 'function',
|
||||
literal: 'literal', number: 'number', string: 'string', code: 'string', regexp: 'regexp',
|
||||
'char.escape_': 'escape', subst: 'plain', comment: 'comment', 'comment.doc': 'docComment', quote: 'comment',
|
||||
doctag: 'doctag', meta: 'meta', 'meta.prompt_': 'meta', params: 'params', attr: 'attr', attribute: 'attr',
|
||||
property: 'property', variable: 'variable', 'variable.constant_': 'constant', 'template-variable': 'variable',
|
||||
operator: 'operator', punctuation: 'punctuation', tag: 'tagPunct', name: 'tag', 'selector-tag': 'tag',
|
||||
'selector-id': 'selector', 'selector-class': 'selector', 'selector-attr': 'selector', 'selector-pseudo': 'selector',
|
||||
section: 'section', bullet: 'bullet', link: 'link', symbol: 'symbol', addition: 'addition', deletion: 'deletion',
|
||||
};
|
||||
// VS Code themes color control flow differently from declarations; hljs calls both "keyword".
|
||||
const CONTROL = new Set('if else elif for foreach while do return break continue switch case default try catch finally throw when yield await import export from goto in match loop guard defer select fallthrough raise except with pass assert'.split(' '));
|
||||
const OPAQUE = new Set(['string', 'comment', 'docComment', 'doctag', 'regexp', 'escape']);
|
||||
|
||||
function typeOf(scopes, text) {
|
||||
for (let i = scopes.length - 1; i >= 0; i--) {
|
||||
const parts = scopes[i].split('.');
|
||||
for (let n = parts.length; n > 0; n--) {
|
||||
const t = SCOPE_TYPE[parts.slice(0, n).join('.')];
|
||||
if (t) return t === 'keyword' && CONTROL.has(text.trim()) ? 'control' : t;
|
||||
}
|
||||
}
|
||||
return 'plain';
|
||||
}
|
||||
|
||||
const ENTITIES = { amp: '&', lt: '<', gt: '>', quot: '"', '#x27': "'", '#39': "'", nbsp: ' ' };
|
||||
const unescape = (s) => s.replace(/&(#x[0-9a-f]+|#\d+|\w+);/gi, (m, e) =>
|
||||
ENTITIES[e] ?? (e[0] === '#' ? String.fromCodePoint(e[1] === 'x' ? parseInt(e.slice(2), 16) : +e.slice(1)) : m));
|
||||
|
||||
/**
|
||||
* Splits code into tokens: [{text, type, scopes, bold, italic, opaque}]. `opaque` marks
|
||||
* strings, comments and regexes (anything a formatter must not change).
|
||||
*/
|
||||
export function tokenize(code, lang) {
|
||||
let html;
|
||||
try {
|
||||
html = hljs.highlight(code, { language: lang, ignoreIllegals: true }).value;
|
||||
} catch {
|
||||
return [{ text: code, type: 'plain', scopes: [], opaque: false }];
|
||||
}
|
||||
const tokens = [];
|
||||
const stack = [];
|
||||
const re = /<span class="([^"]*)">|<\/span>|([^<]+)/g;
|
||||
for (let m; (m = re.exec(html)); ) {
|
||||
if (m[1] != null) {
|
||||
// "hljs-title function_" → "title.function_"; doc comments get their own scope.
|
||||
let scope = m[1].split(' ').map((c) => c.replace(/^hljs-/, '')).join('.');
|
||||
if (scope === 'comment' && /^(\/\*\*|\/\/\/)/.test(unescape(html.slice(re.lastIndex, re.lastIndex + 12)))) scope = 'comment.doc';
|
||||
stack.push(scope);
|
||||
} else if (m[0] === '</span>') stack.pop();
|
||||
else {
|
||||
const text = unescape(m[2]);
|
||||
const type = typeOf(stack, text);
|
||||
tokens.push({
|
||||
text,
|
||||
type,
|
||||
scopes: [...stack],
|
||||
bold: stack.includes('strong'),
|
||||
italic: stack.includes('emphasis'),
|
||||
opaque: stack.some((s) => OPAQUE.has(typeOf([s], ''))),
|
||||
});
|
||||
}
|
||||
}
|
||||
return tokens;
|
||||
}
|
||||
|
||||
/** Tokens split into lines (a token spanning lines becomes several). */
|
||||
export function toLines(tokens, tabSize = 4) {
|
||||
const lines = [[]];
|
||||
for (const tok of tokens) {
|
||||
tok.text.split('\n').forEach((part, i) => {
|
||||
if (i) lines.push([]);
|
||||
if (part) lines[lines.length - 1].push({ ...tok, text: part.replace(/\t/g, ' '.repeat(tabSize)) });
|
||||
});
|
||||
}
|
||||
if (lines.length > 1 && !lines[lines.length - 1].length) lines.pop(); // trailing newline
|
||||
return lines;
|
||||
}
|
||||
|
||||
// ---------- renderers ----------
|
||||
|
||||
const esc = (s) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
|
||||
export const FONT_STACK = "'JetBrains Mono', Consolas, 'Cascadia Mono', Menlo, 'Courier New', monospace";
|
||||
|
||||
function styleOf(theme, tok) {
|
||||
const s = styleFor(theme, tok.type);
|
||||
return { color: s.color, bold: s.bold || tok.bold, italic: s.italic || tok.italic };
|
||||
}
|
||||
|
||||
/**
|
||||
* Rich-text HTML in the shape VS Code puts on the clipboard (a div per line, inline
|
||||
* styles only), which Google Docs, Word, Outlook, Slack and Notion all keep.
|
||||
*/
|
||||
export function toHtml(lines, theme, { lineNumbers = false, fontPx = 14 } = {}) {
|
||||
const width = String(lines.length).length;
|
||||
const lh = Math.round(fontPx * 1.45);
|
||||
const rows = lines.map((line, i) => {
|
||||
let inner = lineNumbers
|
||||
? `<span style="color:${theme.lineNo};">${String(i + 1).padStart(width)} </span>`
|
||||
: '';
|
||||
for (const tok of line) {
|
||||
const s = styleOf(theme, tok);
|
||||
inner += `<span style="color:${s.color};${s.bold ? 'font-weight:bold;' : ''}${s.italic ? 'font-style:italic;' : ''}">${esc(tok.text)}</span>`;
|
||||
}
|
||||
return `<div>${inner || '<br>'}</div>`;
|
||||
});
|
||||
return `<div style="color:${theme.fg};background-color:${theme.bg};font-family:${FONT_STACK.replace(/'/g, ''')};font-weight:normal;font-size:${fontPx}px;line-height:${lh}px;white-space:pre;padding:12px 16px;">${rows.join('')}</div>`;
|
||||
}
|
||||
|
||||
/** Plain text with optional line numbers (the text/plain flavor of a copy). */
|
||||
export function toText(lines, { lineNumbers = false } = {}) {
|
||||
const width = String(lines.length).length;
|
||||
return lines.map((l, i) => (lineNumbers ? `${String(i + 1).padStart(width)} ` : '') + l.map((t) => t.text).join('')).join('\n');
|
||||
}
|
||||
|
||||
const rgb = (hex) => {
|
||||
const n = parseInt(hex.slice(1), 16);
|
||||
return `\\red${(n >> 16) & 255}\\green${(n >> 8) & 255}\\blue${n & 255};`;
|
||||
};
|
||||
function rtfEscape(s) {
|
||||
let out = '';
|
||||
for (const ch of s) {
|
||||
const c = ch.codePointAt(0);
|
||||
if (ch === '\\' || ch === '{' || ch === '}') out += '\\' + ch;
|
||||
else if (c < 0x80) out += ch;
|
||||
else {
|
||||
// RTF \u takes signed 16-bit units; astral characters become surrogate pairs.
|
||||
for (const unit of ch.length === 2 ? [ch.charCodeAt(0), ch.charCodeAt(1)] : [c]) {
|
||||
out += `\\u${unit > 32767 ? unit - 65536 : unit}?`;
|
||||
}
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** RTF document (opens in Word, Pages, WordPad, LibreOffice) with the theme's colors. */
|
||||
export function toRtf(lines, theme, { lineNumbers = false, fontPx = 14 } = {}) {
|
||||
const colors = [theme.fg, theme.bg, theme.lineNo];
|
||||
const idx = (c) => {
|
||||
let i = colors.indexOf(c);
|
||||
if (i < 0) i = colors.push(c) - 1;
|
||||
return i + 1; // colortbl entry 0 is "auto"
|
||||
};
|
||||
const halfPts = Math.round(fontPx * 0.75 * 2); // px → pt → half-points
|
||||
const width = String(lines.length).length;
|
||||
const bg = idx(theme.bg);
|
||||
const body = lines.map((line, i) => {
|
||||
let row = `\\pard\\plain\\f0\\fs${halfPts}\\cbpat${bg} `;
|
||||
if (lineNumbers) row += `{\\cf${idx(theme.lineNo)}\\chcbpat${bg} ${rtfEscape(String(i + 1).padStart(width))} }`;
|
||||
for (const tok of line) {
|
||||
const s = styleOf(theme, tok);
|
||||
row += `{\\cf${idx(s.color)}\\chcbpat${bg}${s.bold ? '\\b' : ''}${s.italic ? '\\i' : ''} ${rtfEscape(tok.text)}}`;
|
||||
}
|
||||
return row + '\\par';
|
||||
});
|
||||
return `{\\rtf1\\ansi\\ansicpg1252\\deff0{\\fonttbl{\\f0\\fmodern\\fcharset0 Consolas;}}{\\colortbl ;${colors.map(rgb).join('')}}\n\\viewkind4\\uc1\n${body.join('\n')}\n}`;
|
||||
}
|
||||
158
app/static/js/tools/highlight-themes.js
Normal file
158
app/static/js/tools/highlight-themes.js
Normal file
|
|
@ -0,0 +1,158 @@
|
|||
// Editor color themes for the Syntax Highlighting tool, taken from each theme's own
|
||||
// token colors. A token color is '#rrggbb' or ['#rrggbb', 'b' | 'i' | 'bi'].
|
||||
//
|
||||
// Token types (see highlight-core.js for how highlight.js scopes map onto them):
|
||||
// keyword control builtin type className function functionCall literal number string
|
||||
// regexp escape comment docComment doctag meta params attr property variable constant
|
||||
// operator punctuation tag tagPunct selector section bullet link symbol addition deletion
|
||||
// A type a theme leaves out falls back along FALLBACK, and finally to the theme's fg.
|
||||
|
||||
export const FALLBACK = {
|
||||
control: 'keyword',
|
||||
className: 'type',
|
||||
builtin: 'type',
|
||||
functionCall: 'function',
|
||||
docComment: 'comment',
|
||||
doctag: 'docComment',
|
||||
constant: 'variable',
|
||||
selector: 'attr',
|
||||
bullet: 'keyword',
|
||||
section: 'keyword',
|
||||
link: 'string',
|
||||
symbol: 'literal',
|
||||
regexp: 'string',
|
||||
escape: 'string',
|
||||
tagPunct: 'punctuation',
|
||||
};
|
||||
|
||||
export const THEMES = [
|
||||
{
|
||||
id: 'vscode-dark', group: 'VS Code', name: 'Dark Modern',
|
||||
bg: '#1F1F1F', fg: '#CCCCCC', lineNo: '#6E7681',
|
||||
t: {
|
||||
keyword: '#569CD6', control: '#C586C0', builtin: '#4EC9B0', type: '#4EC9B0', function: '#DCDCAA',
|
||||
literal: '#569CD6', number: '#B5CEA8', string: '#CE9178', regexp: '#D16969', escape: '#D7BA7D',
|
||||
comment: '#6A9955', doctag: '#569CD6', meta: '#DCDCAA', attr: '#9CDCFE', property: '#9CDCFE',
|
||||
variable: '#9CDCFE', constant: '#4FC1FF', tag: '#569CD6', tagPunct: '#808080', selector: '#D7BA7D',
|
||||
section: ['#569CD6', 'b'], bullet: '#6796E6', link: '#CE9178', addition: '#B5CEA8', deletion: '#CE9178',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'vscode-light', group: 'VS Code', name: 'Light Modern',
|
||||
bg: '#FFFFFF', fg: '#3B3B3B', lineNo: '#6E7681',
|
||||
t: {
|
||||
keyword: '#0000FF', control: '#AF00DB', builtin: '#267F99', type: '#267F99', function: '#795E26',
|
||||
literal: '#0000FF', number: '#098658', string: '#A31515', regexp: '#811F3F', escape: '#EE0000',
|
||||
comment: '#008000', doctag: '#0000FF', meta: '#795E26', attr: '#E50000', property: '#001080',
|
||||
variable: '#001080', constant: '#0070C1', tag: '#800000', tagPunct: '#800000', selector: '#800000',
|
||||
section: ['#800000', 'b'], bullet: '#0451A5', addition: '#098658', deletion: '#A31515',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'one-dark-pro', group: 'VS Code', name: 'One Dark Pro',
|
||||
bg: '#282C34', fg: '#ABB2BF', lineNo: '#495162',
|
||||
t: {
|
||||
keyword: '#C678DD', builtin: '#E5C07B', type: '#E5C07B', function: '#61AFEF', literal: '#D19A66',
|
||||
number: '#D19A66', string: '#98C379', regexp: '#56B6C2', escape: '#56B6C2', comment: ['#7F848E', 'i'],
|
||||
doctag: ['#C678DD', 'i'], meta: '#61AFEF', attr: '#D19A66', property: '#E06C75', variable: '#E06C75',
|
||||
constant: '#D19A66', operator: '#56B6C2', tag: '#E06C75', tagPunct: '#ABB2BF', selector: '#D19A66',
|
||||
section: ['#E06C75', 'b'], bullet: '#E06C75', link: '#61AFEF', symbol: '#56B6C2',
|
||||
addition: '#98C379', deletion: '#E06C75',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'monokai', group: 'VS Code', name: 'Monokai',
|
||||
bg: '#272822', fg: '#F8F8F2', lineNo: '#90908A',
|
||||
t: {
|
||||
keyword: '#F92672', builtin: '#66D9EF', type: ['#66D9EF', 'i'], className: '#A6E22E', function: '#A6E22E',
|
||||
literal: '#AE81FF', number: '#AE81FF', string: '#E6DB74', escape: '#AE81FF', comment: '#88846F',
|
||||
doctag: '#66D9EF', meta: '#F92672', attr: '#A6E22E', operator: '#F92672', tag: '#F92672',
|
||||
tagPunct: '#F8F8F2', selector: '#A6E22E', section: '#A6E22E', link: '#66D9EF', constant: '#AE81FF',
|
||||
addition: '#A6E22E', deletion: '#F92672',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'dracula', group: 'VS Code', name: 'Dracula',
|
||||
bg: '#282A36', fg: '#F8F8F2', lineNo: '#6272A4',
|
||||
t: {
|
||||
keyword: '#FF79C6', builtin: '#8BE9FD', type: ['#8BE9FD', 'i'], function: '#50FA7B', literal: '#BD93F9',
|
||||
number: '#BD93F9', string: '#F1FA8C', regexp: '#FF5555', escape: '#FF79C6', comment: '#6272A4',
|
||||
doctag: '#FF79C6', meta: '#50FA7B', attr: '#50FA7B', operator: '#FF79C6', tag: '#FF79C6',
|
||||
tagPunct: '#F8F8F2', selector: '#50FA7B', section: ['#BD93F9', 'b'], link: '#8BE9FD', constant: '#BD93F9',
|
||||
addition: '#50FA7B', deletion: '#FF5555',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'github-dark', group: 'VS Code', name: 'GitHub Dark',
|
||||
bg: '#0D1117', fg: '#E6EDF3', lineNo: '#6E7681',
|
||||
t: {
|
||||
keyword: '#FF7B72', builtin: '#FFA657', type: '#FFA657', function: '#D2A8FF', literal: '#79C0FF',
|
||||
number: '#79C0FF', string: '#A5D6FF', escape: '#79C0FF', comment: '#8B949E', doctag: '#FF7B72',
|
||||
meta: '#D2A8FF', attr: '#79C0FF', property: '#79C0FF', variable: '#FFA657', constant: '#79C0FF',
|
||||
operator: '#FF7B72', tag: '#7EE787', tagPunct: '#E6EDF3', selector: '#7EE787', section: ['#79C0FF', 'b'],
|
||||
bullet: '#FFA657', addition: '#7EE787', deletion: '#FFA198',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'github-light', group: 'VS Code', name: 'GitHub Light',
|
||||
bg: '#FFFFFF', fg: '#1F2328', lineNo: '#8C959F',
|
||||
t: {
|
||||
keyword: '#CF222E', builtin: '#953800', type: '#953800', function: '#8250DF', literal: '#0550AE',
|
||||
number: '#0550AE', string: '#0A3069', escape: '#0550AE', comment: '#6E7781', doctag: '#CF222E',
|
||||
meta: '#8250DF', attr: '#0550AE', property: '#0550AE', variable: '#953800', constant: '#0550AE',
|
||||
operator: '#CF222E', tag: '#116329', tagPunct: '#1F2328', selector: '#116329', section: ['#0550AE', 'b'],
|
||||
bullet: '#953800', addition: '#116329', deletion: '#82071E',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'darcula', group: 'Android Studio', name: 'Darcula',
|
||||
bg: '#2B2B2B', fg: '#A9B7C6', lineNo: '#606366',
|
||||
t: {
|
||||
keyword: '#CC7832', builtin: '#A9B7C6', type: '#A9B7C6', function: '#FFC66D', functionCall: '#A9B7C6',
|
||||
literal: '#CC7832', number: '#6897BB', string: '#6A8759', escape: '#CC7832', comment: '#808080',
|
||||
docComment: ['#629755', 'i'], doctag: ['#629755', 'bi'], meta: '#BBB529', attr: '#BABABA',
|
||||
property: '#9876AA', constant: ['#9876AA', 'i'], tag: '#E8BF6A', tagPunct: '#E8BF6A', selector: '#E8BF6A',
|
||||
section: ['#CC7832', 'b'], link: '#287BDE', symbol: '#9876AA', addition: '#6A8759', deletion: '#CC7832',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'as-dark', group: 'Android Studio', name: 'Dark (new UI)',
|
||||
bg: '#1E1F22', fg: '#BCBEC4', lineNo: '#4B5059',
|
||||
t: {
|
||||
keyword: '#CF8E6D', builtin: '#BCBEC4', type: '#BCBEC4', function: '#56A8F5', functionCall: '#BCBEC4',
|
||||
literal: '#CF8E6D', number: '#2AACB8', string: '#6AAB73', regexp: '#42C3D4', escape: '#CF8E6D',
|
||||
comment: '#7A7E85', docComment: ['#5F826B', 'i'], doctag: ['#67A37C', 'bi'], meta: '#B3AE60',
|
||||
attr: '#BABABA', property: '#C77DBB', constant: ['#C77DBB', 'i'], tag: '#D5B778', tagPunct: '#D5B778',
|
||||
selector: '#D5B778', section: ['#CF8E6D', 'b'], link: '#548AF7', symbol: '#C77DBB',
|
||||
addition: '#6AAB73', deletion: '#CF8E6D',
|
||||
},
|
||||
},
|
||||
{
|
||||
id: 'intellij-light', group: 'Android Studio', name: 'Light (IntelliJ Light)',
|
||||
bg: '#FFFFFF', fg: '#080808', lineNo: '#ADADAD',
|
||||
t: {
|
||||
keyword: '#0033B3', builtin: '#080808', type: '#080808', function: '#00627A', functionCall: '#080808',
|
||||
literal: '#0033B3', number: '#1750EB', string: '#067D17', regexp: '#264EFF', escape: '#0037A6',
|
||||
comment: ['#8C8C8C', 'i'], doctag: ['#8C8C8C', 'bi'], meta: '#9E880D', attr: '#174AD4',
|
||||
property: '#871094', constant: ['#871094', 'i'], tag: '#0033B3', tagPunct: '#0033B3', selector: '#0033B3',
|
||||
section: ['#0033B3', 'b'], link: '#006DCC', symbol: '#871094', addition: '#067D17', deletion: '#0033B3',
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
export const themeById = (id) => THEMES.find((t) => t.id === id) || THEMES[0];
|
||||
|
||||
/** Resolved style for a token type: {color, bold, italic}. Cached per theme. */
|
||||
export function styleFor(theme, type) {
|
||||
theme._cache ||= {};
|
||||
if (theme._cache[type]) return theme._cache[type];
|
||||
let t = type;
|
||||
let v;
|
||||
for (let guard = 0; t && guard < 6; guard++) {
|
||||
v = theme.t[t];
|
||||
if (v) break;
|
||||
t = FALLBACK[t];
|
||||
}
|
||||
const [color, flags = ''] = Array.isArray(v) ? v : [v || theme.fg];
|
||||
return (theme._cache[type] = { color, bold: flags.includes('b'), italic: flags.includes('i') });
|
||||
}
|
||||
|
|
@ -1,6 +1,7 @@
|
|||
// JSON editor: a text pane and a live tree pane that stay in sync.
|
||||
// Text edits re-render the tree as you type; tree edits rewrite the text (undoable).
|
||||
import { parse, stringify, sortKeys, nodeFromInput, stringNode, pathToString, JsonSyntaxError } from './json-core.js';
|
||||
import { markRead } from './paste-state.js';
|
||||
import { el, segmented, store, copyText, downloadText, openTextFile, debounce, formatBytes, tabIndent, toast, onLeave } from '../ui.js';
|
||||
|
||||
const SAMPLE = `{
|
||||
|
|
@ -442,6 +443,7 @@ export async function mount(root, ctx) {
|
|||
if (!r.ok) throw new Error(body.detail);
|
||||
editor.value = body.content;
|
||||
fromPaste = true;
|
||||
markRead(pasteId);
|
||||
ctx.setTitle(`paste ${pasteId}`);
|
||||
toast('Opened a shared paste; edits here are not saved');
|
||||
} catch (err) {
|
||||
|
|
|
|||
|
|
@ -1,8 +1,9 @@
|
|||
// Markdown editor with live preview. Modes: edit only, side by side, full-page preview.
|
||||
import { marked } from '../../vendor/marked.esm.js';
|
||||
import DOMPurify from '../../vendor/purify.es.mjs';
|
||||
import { el, segmented, store, copyText, downloadText, openTextFile, debounce, tabIndent, toast, onLeave } from '../ui.js';
|
||||
import { el, segmented, store, copyText, downloadText, openTextFile, debounce, tabIndent, toast, onLeave, modal } from '../ui.js';
|
||||
import { createPaste } from './paste.js';
|
||||
import { markRead } from './paste-state.js';
|
||||
|
||||
const SAMPLE = `# Markdown
|
||||
|
||||
|
|
@ -47,6 +48,59 @@ export function render(md) {
|
|||
return DOMPurify.sanitize(marked.parse(md));
|
||||
}
|
||||
|
||||
// Cheat sheet for the Guide dialog: [section, [[label, source], ...]].
|
||||
const GUIDE = [
|
||||
['Text', [
|
||||
['Headings', '# Heading 1\n## Heading 2\n### Heading 3'],
|
||||
['Emphasis', '*italic* or _italic_\n**bold** or __bold__\n***bold italic***\n~~strikethrough~~'],
|
||||
['Paragraphs and line breaks', 'A blank line starts a new paragraph.\n\nEnd a line with two spaces \nfor a line break inside one.'],
|
||||
['Blockquote', '> Quoted text\n>\n> > Nested quote'],
|
||||
['Escaping', '\\*not italic\\* and \\# not a heading'],
|
||||
]],
|
||||
['Lists', [
|
||||
['Bulleted', '- Item\n- Another item\n - Nested (indent 2 spaces)'],
|
||||
['Numbered', '1. First\n2. Second\n 1. Nested'],
|
||||
['Task list', '- [x] Done\n- [ ] To do'],
|
||||
]],
|
||||
['Links and images', [
|
||||
['Link', '[Link text](https://example.com)\n[With a title](https://example.com "Title")'],
|
||||
['Automatic link', 'https://example.com\n<https://example.com>'],
|
||||
['Reference link', '[Link text][ref]\n\n[ref]: https://example.com'],
|
||||
['Image', ''],
|
||||
]],
|
||||
['Code', [
|
||||
['Inline code', 'Use `code` in a sentence.'],
|
||||
['Code block', '```js\nconst x = 1;\nconsole.log(x);\n```'],
|
||||
['Indented code block', ' four spaces of indent\n make a code block'],
|
||||
]],
|
||||
['Tables and rules', [
|
||||
['Table', '| Left | Center | Right |\n| :--- | :----: | ----: |\n| a | b | c |'],
|
||||
['Horizontal rule', 'Above\n\n---\n\nBelow'],
|
||||
['HTML', 'Basic <kbd>HTML</kbd> works: <sub>sub</sub>, <sup>sup</sup>, <mark>mark</mark>'],
|
||||
]],
|
||||
];
|
||||
|
||||
function showGuide(insert) {
|
||||
const body = el('div.guide');
|
||||
for (const [section, items] of GUIDE) {
|
||||
body.append(el('h3.guide-section', {}, section));
|
||||
for (const [label, src] of items) {
|
||||
body.append(
|
||||
el('div.guide-row', {},
|
||||
el('div.guide-label', {}, label,
|
||||
el('button.btn.small', { title: 'Insert at the cursor', onclick: () => { dlg.close(); insert(src); } }, 'Insert')),
|
||||
el('pre.guide-src.mono', {}, src),
|
||||
Object.assign(el('div.guide-out.prose'), { innerHTML: render(src) }), // sanitized by render()
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
const dlg = modal('Markdown guide', [
|
||||
el('div.guide-cols', {}, el('span', {}, 'You type'), el('span', {}, 'You get')),
|
||||
body,
|
||||
], { wide: true });
|
||||
}
|
||||
|
||||
export async function mount(root, ctx) {
|
||||
let mode = store.get('md:mode', window.innerWidth < 800 ? 'edit' : 'split');
|
||||
const editor = el('textarea.md-input.mono', {
|
||||
|
|
@ -78,8 +132,19 @@ export async function mount(root, ctx) {
|
|||
el('button.btn', { onclick: () => downloadText(editor.value, 'document.md', 'text/markdown'), title: 'Download as .md' }, 'Download'),
|
||||
el('button.btn', { onclick: () => copyText(render(editor.value), 'HTML copied'), title: 'Copy the rendered HTML' }, 'Copy HTML'),
|
||||
el('button.btn', { onclick: share, title: 'Create a 24-hour paste and copy its link' }, 'Share'),
|
||||
el('button.btn', { onclick: () => showGuide(insertAtCursor), title: 'Markdown syntax cheat sheet' }, '? Guide'),
|
||||
);
|
||||
|
||||
function insertAtCursor(text) {
|
||||
if (mode === 'preview') setMode('split');
|
||||
editor.focus();
|
||||
const atLineStart = editor.selectionStart === 0 || editor.value[editor.selectionStart - 1] === '\n';
|
||||
const snippet = (atLineStart ? '' : '\n\n') + text + '\n';
|
||||
if (!document.execCommand('insertText', false, snippet)) editor.setRangeText(snippet, editor.selectionStart, editor.selectionEnd, 'end');
|
||||
update();
|
||||
save();
|
||||
}
|
||||
|
||||
root.append(el('div.tool.md-tool', {}, toolbar, workspace));
|
||||
|
||||
function update() {
|
||||
|
|
@ -129,7 +194,7 @@ export async function mount(root, ctx) {
|
|||
|
||||
async function share() {
|
||||
if (!editor.value.trim()) return toast('Nothing to share', 'error');
|
||||
const p = await createPaste(editor.value);
|
||||
const p = await createPaste(editor.value, { share: true });
|
||||
if (p) copyText(`${location.origin}/markdown?paste=${p.id}`, 'Link copied (expires in 24 h)');
|
||||
}
|
||||
|
||||
|
|
@ -143,6 +208,7 @@ export async function mount(root, ctx) {
|
|||
editor.value = (await r.json()).content;
|
||||
ctx.setTitle(`paste ${pasteId}`);
|
||||
fromPaste = true;
|
||||
markRead(pasteId);
|
||||
mode = 'preview';
|
||||
toast('Opened a shared paste; edits here are not saved', 'info');
|
||||
} catch (err) {
|
||||
|
|
|
|||
38
app/static/js/tools/paste-state.js
Normal file
38
app/static/js/tools/paste-state.js
Normal file
|
|
@ -0,0 +1,38 @@
|
|||
// Pastes this browser made, and which shared ones are still unread. Kept tiny and
|
||||
// dependency-free: the registry imports it for the Pastebin badge on every page load.
|
||||
import { store } from '../ui.js';
|
||||
|
||||
const now = () => Date.now() / 1000;
|
||||
|
||||
export function mine() {
|
||||
return (store.get('paste:mine', []) || []).filter((p) => p.expires_at > now());
|
||||
}
|
||||
|
||||
export function remember(p, preview, { unread = false } = {}) {
|
||||
store.set('paste:mine', [{ id: p.id, expires_at: p.expires_at, delete_token: p.delete_token, preview, unread }, ...mine()].slice(0, 50));
|
||||
changed();
|
||||
}
|
||||
|
||||
export function forget(id) {
|
||||
store.set('paste:mine', mine().filter((p) => p.id !== id));
|
||||
changed();
|
||||
}
|
||||
|
||||
export function markRead(id) {
|
||||
const list = mine();
|
||||
const p = list.find((x) => x.id === id);
|
||||
if (p?.unread) {
|
||||
p.unread = false;
|
||||
store.set('paste:mine', list);
|
||||
changed();
|
||||
}
|
||||
}
|
||||
|
||||
/** Shared (not yet opened) pastes that haven't expired. */
|
||||
export function unreadCount() {
|
||||
return mine().filter((p) => p.unread).length;
|
||||
}
|
||||
|
||||
function changed() {
|
||||
window.dispatchEvent(new Event('tools:badges'));
|
||||
}
|
||||
|
|
@ -1,22 +1,17 @@
|
|||
// Pastebin: /paste to create, /paste/<id> to view. Pastes expire 24 h after creation.
|
||||
// Pastes made in this browser are remembered locally (with their delete tokens).
|
||||
import { el, store, copyText, downloadText, openTextFile, toast, timeLeft, formatBytes } from '../ui.js';
|
||||
import { el, store, copyText, downloadText, openTextFile, toast, timeLeft, formatBytes, dropdown } from '../ui.js';
|
||||
import { TOOLS } from '../registry.js';
|
||||
import { mine, remember, forget, markRead } from './paste-state.js';
|
||||
|
||||
const MAX_BYTES = 5 * 1024 * 1024; // keep in step with app/tools/paste.py
|
||||
|
||||
function mine() {
|
||||
const now = Date.now() / 1000;
|
||||
return (store.get('paste:mine', []) || []).filter((p) => p.expires_at > now);
|
||||
}
|
||||
function remember(p, preview) {
|
||||
store.set('paste:mine', [{ id: p.id, expires_at: p.expires_at, delete_token: p.delete_token, preview }, ...mine()].slice(0, 50));
|
||||
}
|
||||
function forget(id) {
|
||||
store.set('paste:mine', mine().filter((p) => p.id !== id));
|
||||
}
|
||||
|
||||
/** Creates a paste and remembers it locally. Resolves with {id, expires_at, delete_token} or null. */
|
||||
export async function createPaste(content) {
|
||||
/**
|
||||
* Creates a paste and remembers it locally. Resolves with {id, expires_at, delete_token} or null.
|
||||
* share: made by another tool's Share button, so it counts as unread on the Pastebin badge
|
||||
* until it's opened.
|
||||
*/
|
||||
export async function createPaste(content, { share = false } = {}) {
|
||||
try {
|
||||
const r = await fetch('/api/paste', {
|
||||
method: 'POST',
|
||||
|
|
@ -25,7 +20,7 @@ export async function createPaste(content) {
|
|||
});
|
||||
const body = await r.json().catch(() => ({}));
|
||||
if (!r.ok) throw new Error(body.detail || `HTTP ${r.status}`);
|
||||
remember(body, content.slice(0, 80).replace(/\s+/g, ' '));
|
||||
remember(body, content.slice(0, 80).replace(/\s+/g, ' '), { unread: share });
|
||||
return body;
|
||||
} catch (err) {
|
||||
toast(`Couldn't create paste: ${err.message}`, 'error');
|
||||
|
|
@ -94,6 +89,7 @@ function renderCreate(root, ctx, timers) {
|
|||
...items.map((p) =>
|
||||
el('div.paste-item', {},
|
||||
el('a.mono', { href: `/paste/${p.id}` }, p.id),
|
||||
p.unread && el('span.chip.new', { title: 'Shared from another tool and not opened yet' }, 'new'),
|
||||
el('span.paste-preview.muted', {}, p.preview || ''),
|
||||
el('span.muted.small.nowrap', {}, timeLeft(p.expires_at)),
|
||||
el('button.btn.small', { title: 'Delete now', onclick: async () => {
|
||||
|
|
@ -130,6 +126,7 @@ async function renderView(root, ctx, id, timers) {
|
|||
root.append(el('div.empty', {}, el('p', {}, err.message), el('a.btn.primary', { href: '/paste' }, 'New paste')));
|
||||
return;
|
||||
}
|
||||
markRead(id);
|
||||
const own = mine().find((m) => m.id === id);
|
||||
const left = el('span.muted.small', {}, timeLeft(p.expires_at));
|
||||
timers.push(setInterval(() => (left.textContent = timeLeft(p.expires_at)), 30000));
|
||||
|
|
@ -156,8 +153,12 @@ async function renderView(root, ctx, id, timers) {
|
|||
el('button.btn', { onclick: () => copyText(p.content) }, 'Copy text'),
|
||||
el('a.btn', { href: `/raw/${id}`, target: '_blank', rel: 'noopener' }, 'Raw'),
|
||||
el('button.btn', { onclick: () => downloadText(p.content, `${id}.txt`) }, 'Download'),
|
||||
el('a.btn', { href: `/markdown?paste=${id}`, title: 'Render this paste as Markdown' }, 'As Markdown'),
|
||||
el('a.btn', { href: `/json?paste=${id}`, title: 'Open this paste in the JSON editor' }, 'As JSON'),
|
||||
// Every tool that declares opensPaste in the registry can take ?paste=<id>.
|
||||
dropdown('Open in', TOOLS.filter((t) => t.opensPaste).map((t) => ({
|
||||
label: t.name,
|
||||
icon: t.icon,
|
||||
onSelect: () => ctx.navigate(`${t.path}?paste=${encodeURIComponent(id)}`),
|
||||
}))),
|
||||
wrapBtn,
|
||||
own && el('button.btn.danger', { onclick: async () => {
|
||||
if (!confirm('Delete this paste now?')) return;
|
||||
|
|
|
|||
252
app/static/js/tools/syntax.js
Normal file
252
app/static/js/tools/syntax.js
Normal file
|
|
@ -0,0 +1,252 @@
|
|||
// Syntax Highlighting: source on the left, themed output on the right. The output is
|
||||
// what gets copied (rich text) or downloaded (RTF), so what you see is what you paste.
|
||||
import { el, segmented, store, copyText, copyRich, downloadText, openTextFile, debounce, tabIndent, toast, onLeave } from '../ui.js';
|
||||
import { LANGUAGES, languageName, languageForFile, detect, tokenize, toLines, toHtml, toText, toRtf } from './highlight-core.js';
|
||||
import { THEMES, themeById } from './highlight-themes.js';
|
||||
import { formatCode, formatterName } from './code-format.js';
|
||||
import { createPaste } from './paste.js';
|
||||
import { markRead } from './paste-state.js';
|
||||
|
||||
const SAMPLE = `// Paste code here. Pick a theme on the right, then Copy rich text
|
||||
// and paste into Docs, Word, Slides, Outlook or Notion.
|
||||
data class Pokemon(val id:Int,val name:String, val types:List<String>)
|
||||
|
||||
class PokedexRepository(private val api:PokeApi, private val dao:PokemonDao){
|
||||
suspend fun pokemon(id:Int):Pokemon{
|
||||
dao.find(id)?.let{ return it } // cached
|
||||
val fresh=api.fetch(id)
|
||||
dao.insert(fresh)
|
||||
return fresh
|
||||
}
|
||||
}
|
||||
`;
|
||||
const SIZES = [['12', '9 pt'], ['13', '10 pt'], ['14', '10.5 pt'], ['15', '11 pt'], ['16', '12 pt'], ['18', '13.5 pt']];
|
||||
|
||||
export async function mount(root, ctx) {
|
||||
let mode = store.get('syntax:mode', window.innerWidth < 800 ? 'source' : 'split');
|
||||
let langChoice = store.get('syntax:lang', 'auto');
|
||||
let themeId = store.get('syntax:theme', 'vscode-dark');
|
||||
let lineNumbers = store.get('syntax:ln', false);
|
||||
let fontPx = store.get('syntax:size', '14');
|
||||
let indent = store.get('syntax:indent', 'auto');
|
||||
let fileBase = 'code';
|
||||
let detected = 'plaintext';
|
||||
let fromPaste = false;
|
||||
let lines = [];
|
||||
|
||||
const editor = el('textarea.md-input.mono.code-input', { spellcheck: false, wrap: 'off', 'aria-label': 'Source code', placeholder: 'Paste source code…' });
|
||||
tabIndent(editor, ' ');
|
||||
const output = el('div.syntax-output', { 'aria-label': 'Highlighted output' });
|
||||
const outPane = el('div.pane.syntax-out-pane', {});
|
||||
|
||||
// ---------- controls ----------
|
||||
|
||||
const langSel = el('select.select', { 'aria-label': 'Language', title: 'Language', onchange: () => {
|
||||
langChoice = langSel.value;
|
||||
if (!fromPaste) store.set('syntax:lang', langChoice);
|
||||
update();
|
||||
} },
|
||||
el('option', { value: 'auto' }, 'Auto-detect'),
|
||||
LANGUAGES.map((l) => el('option', { value: l.id }, l.name)));
|
||||
const themeSel = el('select.select', { 'aria-label': 'Theme', title: 'Theme', onchange: () => {
|
||||
themeId = themeSel.value;
|
||||
store.set('syntax:theme', themeId);
|
||||
render();
|
||||
} },
|
||||
[...new Set(THEMES.map((t) => t.group))].map((g) =>
|
||||
el('optgroup', { label: g }, THEMES.filter((t) => t.group === g).map((t) => el('option', { value: t.id }, t.name)))));
|
||||
const sizeSel = el('select.select', { 'aria-label': 'Text size', title: 'Text size when pasted', onchange: () => {
|
||||
fontPx = sizeSel.value;
|
||||
store.set('syntax:size', fontPx);
|
||||
render();
|
||||
} }, SIZES.map(([v, label]) => el('option', { value: v }, label)));
|
||||
const lnBox = el('input', { type: 'checkbox', checked: lineNumbers, onchange: () => {
|
||||
lineNumbers = lnBox.checked;
|
||||
store.set('syntax:ln', lineNumbers);
|
||||
render();
|
||||
} });
|
||||
const indentSel = el('select.select', { 'aria-label': 'Indentation', title: 'Indentation used by Format', onchange: () => {
|
||||
indent = indentSel.value;
|
||||
store.set('syntax:indent', indent);
|
||||
} },
|
||||
el('option', { value: 'auto' }, 'Auto indent'), el('option', { value: '2' }, '2 spaces'),
|
||||
el('option', { value: '4' }, '4 spaces'), el('option', { value: 'tab' }, 'Tabs'));
|
||||
langSel.value = langChoice;
|
||||
themeSel.value = themeById(themeId).id;
|
||||
sizeSel.value = fontPx;
|
||||
indentSel.value = indent;
|
||||
|
||||
const modes = segmented([['source', 'Source'], ['split', 'Split'], ['output', 'Output']], mode, setMode, 'View mode');
|
||||
const formatBtn = el('button.btn', { onclick: format }, 'Format');
|
||||
const stats = el('span.muted.small');
|
||||
|
||||
const toolbar = el('div.toolbar', {},
|
||||
modes,
|
||||
el('span.divider'),
|
||||
langSel,
|
||||
formatBtn,
|
||||
indentSel,
|
||||
el('span.spacer'),
|
||||
stats,
|
||||
el('button.btn', { onclick: openFile, title: 'Open a source file' }, 'Open'),
|
||||
el('button.btn', { onclick: downloadRtf, title: 'Download as RTF (opens in Word, Pages, LibreOffice)' }, 'Download RTF'),
|
||||
el('button.btn.primary', { onclick: copyRichText, title: 'Copy with colors, for pasting into documents and chat' }, 'Copy rich text'),
|
||||
el('button.btn', { onclick: share, title: 'Create a 24-hour paste and copy a link to it here' }, 'Share'),
|
||||
);
|
||||
outPane.append(
|
||||
el('div.tree-bar.syntax-bar', {},
|
||||
themeSel,
|
||||
el('label.check', {}, lnBox, 'Line numbers'),
|
||||
sizeSel,
|
||||
el('span.spacer'),
|
||||
el('button.btn.small', { onclick: () => copyText(toText(lines, { lineNumbers })), title: 'Copy as plain text' }, 'Copy text'),
|
||||
),
|
||||
output,
|
||||
);
|
||||
const workspace = el('div.md-workspace.syntax-workspace', {}, el('div.pane.md-edit-pane', {}, editor), outPane);
|
||||
root.append(el('div.tool.syntax-tool', {}, toolbar, workspace));
|
||||
|
||||
// ---------- rendering ----------
|
||||
|
||||
const lang = () => (langChoice === 'auto' ? detected : langChoice);
|
||||
|
||||
function update() {
|
||||
if (langChoice === 'auto') {
|
||||
detected = detect(editor.value);
|
||||
langSel.options[0].textContent = `Auto (${languageName(detected)})`;
|
||||
} else langSel.options[0].textContent = 'Auto-detect';
|
||||
lines = toLines(tokenize(editor.value, lang()));
|
||||
formatBtn.title = `Format with ${formatterName(lang(), editor.value)} (Ctrl+Shift+F)`;
|
||||
stats.textContent = `${lines.length} line${lines.length === 1 ? '' : 's'}`;
|
||||
render();
|
||||
}
|
||||
function render() {
|
||||
const theme = themeById(themeId);
|
||||
output.innerHTML = toHtml(lines, theme, { lineNumbers, fontPx: +fontPx }); // all text is escaped by toHtml
|
||||
outPane.style.background = theme.bg;
|
||||
outPane.classList.toggle('dark-out', isDark(theme.bg));
|
||||
}
|
||||
const isDark = (hex) => {
|
||||
const n = parseInt(hex.slice(1), 16);
|
||||
return 0.299 * (n >> 16) + 0.587 * ((n >> 8) & 255) + 0.114 * (n & 255) < 128;
|
||||
};
|
||||
|
||||
const save = debounce(() => !fromPaste && store.set('syntax:text', editor.value), 400);
|
||||
const live = debounce(update, 120);
|
||||
const slow = debounce(update, 600);
|
||||
editor.addEventListener('input', () => {
|
||||
(editor.value.length > 200_000 ? slow : live)();
|
||||
save();
|
||||
});
|
||||
|
||||
function setMode(m) {
|
||||
mode = m;
|
||||
workspace.dataset.mode = m;
|
||||
modes.set(m);
|
||||
if (!fromPaste) store.set('syntax:mode', m);
|
||||
}
|
||||
|
||||
// ---------- actions ----------
|
||||
|
||||
function replaceText(text) {
|
||||
editor.focus({ preventScroll: true });
|
||||
editor.select();
|
||||
if (document.activeElement !== editor || !document.execCommand('insertText', false, text)) {
|
||||
editor.value = text;
|
||||
editor.dispatchEvent(new Event('input'));
|
||||
}
|
||||
editor.setSelectionRange(0, 0);
|
||||
editor.scrollTop = 0;
|
||||
}
|
||||
|
||||
async function format() {
|
||||
if (!editor.value.trim()) return;
|
||||
const engine = formatterName(lang(), editor.value);
|
||||
formatBtn.disabled = true;
|
||||
try {
|
||||
const out = await formatCode(editor.value, lang(), { indent });
|
||||
if (out === editor.value) toast('Already formatted');
|
||||
else {
|
||||
replaceText(out);
|
||||
toast(engine === 'whitespace cleanup' ? `No formatter for ${languageName(lang())}; cleaned up whitespace` : 'Formatted (Ctrl+Z to undo)');
|
||||
}
|
||||
} catch (err) {
|
||||
toast(`Couldn't format: ${err.message}`, 'error');
|
||||
} finally {
|
||||
formatBtn.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function openFile() {
|
||||
const f = await openTextFile();
|
||||
if (!f) return;
|
||||
if (f.text.includes('\u0000')) return toast(`${f.name} looks like a binary file`, 'error');
|
||||
fileBase = f.name.replace(/\.[^.]*$/, '') || 'code';
|
||||
const l = languageForFile(f.name);
|
||||
if (l) {
|
||||
langChoice = l;
|
||||
langSel.value = l;
|
||||
store.set('syntax:lang', l);
|
||||
}
|
||||
replaceText(f.text);
|
||||
}
|
||||
|
||||
function downloadRtf() {
|
||||
downloadText(toRtf(lines, themeById(themeId), { lineNumbers, fontPx: +fontPx }), `${fileBase}.rtf`, 'application/rtf');
|
||||
}
|
||||
|
||||
function copyRichText() {
|
||||
const theme = themeById(themeId);
|
||||
copyRich(toHtml(lines, theme, { lineNumbers, fontPx: +fontPx }), toText(lines, { lineNumbers }), `Copied with ${theme.name} colors`);
|
||||
}
|
||||
|
||||
async function share() {
|
||||
if (!editor.value.trim()) return toast('Nothing to share', 'error');
|
||||
const p = await createPaste(editor.value, { share: true });
|
||||
if (!p) return;
|
||||
const q = new URLSearchParams({ paste: p.id, lang: lang(), theme: themeId });
|
||||
copyText(`${location.origin}/syntax?${q}`, 'Link copied (expires in 24 h)');
|
||||
}
|
||||
|
||||
function onKey(e) {
|
||||
if ((e.ctrlKey || e.metaKey) && e.shiftKey && e.key.toLowerCase() === 'f') {
|
||||
e.preventDefault();
|
||||
format();
|
||||
}
|
||||
}
|
||||
document.addEventListener('keydown', onKey);
|
||||
|
||||
// ---------- load ----------
|
||||
|
||||
editor.value = store.get('syntax:text', SAMPLE);
|
||||
const pasteId = ctx.query.get('paste');
|
||||
if (pasteId) {
|
||||
try {
|
||||
const r = await fetch(`/api/paste/${encodeURIComponent(pasteId)}`);
|
||||
const body = await r.json();
|
||||
if (!r.ok) throw new Error(body.detail);
|
||||
editor.value = body.content;
|
||||
fromPaste = true;
|
||||
markRead(pasteId);
|
||||
ctx.setTitle(`paste ${pasteId}`);
|
||||
const ql = ctx.query.get('lang');
|
||||
if (ql && LANGUAGES.some((l) => l.id === ql)) langSel.value = langChoice = ql;
|
||||
else langSel.value = langChoice = 'auto';
|
||||
const qt = ctx.query.get('theme');
|
||||
if (qt && THEMES.some((t) => t.id === qt)) themeSel.value = themeId = qt; // view only; not saved as your default
|
||||
mode = 'output';
|
||||
toast('Opened a shared paste; edits here are not saved');
|
||||
} catch (err) {
|
||||
toast(`Couldn't load paste: ${err.message}`, 'error');
|
||||
}
|
||||
}
|
||||
setMode(mode);
|
||||
update();
|
||||
|
||||
const off = onLeave(save.flush);
|
||||
return () => {
|
||||
save.flush();
|
||||
off();
|
||||
document.removeEventListener('keydown', onKey);
|
||||
};
|
||||
}
|
||||
|
|
@ -157,3 +157,75 @@ export function tabIndent(ta, unit = ' ') {
|
|||
ta.setSelectionRange(lineStart, lineStart + out.join('\n').length);
|
||||
});
|
||||
}
|
||||
|
||||
/** A modal dialog. Returns the <dialog>; it removes itself when closed. */
|
||||
export function modal(title, body, { wide = false } = {}) {
|
||||
const dlg = el(`dialog.modal${wide ? '.wide' : ''}`, { 'aria-label': title },
|
||||
el('div.modal-head', {},
|
||||
el('h2', {}, title),
|
||||
el('button.icon-btn', { 'aria-label': 'Close', onclick: () => dlg.close() }, '✕'),
|
||||
),
|
||||
el('div.modal-body', {}, body),
|
||||
);
|
||||
dlg.addEventListener('click', (e) => {
|
||||
if (e.target === dlg) dlg.close(); // click on the backdrop
|
||||
});
|
||||
dlg.addEventListener('close', () => dlg.remove());
|
||||
document.body.append(dlg);
|
||||
dlg.showModal();
|
||||
return dlg;
|
||||
}
|
||||
|
||||
/** A button that opens a menu: dropdown('Open in', [{label, icon?, onSelect}]). */
|
||||
export function dropdown(label, items) {
|
||||
const menu = el('div.menu', { role: 'menu', hidden: true });
|
||||
const btn = el('button.btn', { 'aria-haspopup': 'menu', 'aria-expanded': 'false', onclick: (e) => {
|
||||
e.stopPropagation();
|
||||
toggle(menu.hidden);
|
||||
} }, label, el('span.caret', { 'aria-hidden': 'true' }, '▾'));
|
||||
for (const it of items) {
|
||||
menu.append(el('button.menu-item', { role: 'menuitem', onclick: () => { toggle(false); it.onSelect(); } },
|
||||
it.icon ? el('span.nav-icon', {}, it.icon) : null, it.label));
|
||||
}
|
||||
const outside = (e) => { if (!wrap.contains(e.target)) toggle(false); };
|
||||
const onKey = (e) => { if (e.key === 'Escape') { toggle(false); btn.focus(); } };
|
||||
function toggle(open) {
|
||||
menu.hidden = !open;
|
||||
btn.setAttribute('aria-expanded', String(open));
|
||||
if (open) {
|
||||
document.addEventListener('click', outside);
|
||||
document.addEventListener('keydown', onKey);
|
||||
menu.querySelector('button')?.focus();
|
||||
} else {
|
||||
document.removeEventListener('click', outside);
|
||||
document.removeEventListener('keydown', onKey);
|
||||
}
|
||||
}
|
||||
const wrap = el('div.dropdown', {}, btn, menu);
|
||||
return wrap;
|
||||
}
|
||||
|
||||
/** Copies HTML as rich text (with a plain-text alternative) for pasting into docs and chat apps. */
|
||||
export async function copyRich(html, text, what = 'Copied') {
|
||||
try {
|
||||
if (!window.ClipboardItem || !navigator.clipboard?.write) throw new Error('no async clipboard');
|
||||
await navigator.clipboard.write([new ClipboardItem({
|
||||
'text/html': new Blob([html], { type: 'text/html' }),
|
||||
'text/plain': new Blob([text], { type: 'text/plain' }),
|
||||
})]);
|
||||
} catch {
|
||||
// Older browsers / insecure origins: select a rendered copy and use the legacy copy command.
|
||||
const holder = el('div', { contenteditable: 'true', style: 'position:fixed;left:-9999px;top:0' });
|
||||
holder.innerHTML = html;
|
||||
document.body.append(holder);
|
||||
const range = document.createRange();
|
||||
range.selectNodeContents(holder);
|
||||
const sel = getSelection();
|
||||
sel.removeAllRanges();
|
||||
sel.addRange(range);
|
||||
document.execCommand('copy');
|
||||
sel.removeAllRanges();
|
||||
holder.remove();
|
||||
}
|
||||
toast(what);
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue