@loccal/ui 0.2.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +9 -0
- package/dist/components/ui/code-view.d.ts +31 -0
- package/dist/components/ui/code-view.js +62 -0
- package/dist/components/ui/file-tree.js +4 -1
- package/dist/components/ui/file-type-icon.d.ts +16 -0
- package/dist/components/ui/file-type-icon.js +19 -0
- package/dist/lib/file-icons.d.ts +18 -0
- package/dist/lib/file-icons.js +136 -0
- package/dist/lib/icon-data.d.ts +1 -1
- package/dist/lib/syntax.d.ts +16 -0
- package/dist/lib/syntax.js +540 -0
- package/package.json +21 -1
- package/styles.css +50 -0
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,15 @@
|
|
|
2
2
|
|
|
3
3
|
Gerado por changesets a cada release. Entradas prefixadas pelo nome do componente.
|
|
4
4
|
|
|
5
|
+
## 0.3.0
|
|
6
|
+
|
|
7
|
+
### Minor
|
|
8
|
+
|
|
9
|
+
- file-type-icon: componente novo. Icones de arquivo por linguagem e formato (HTML, CSS, JS, TS, Go, Rust, C, C++, Python, Java e dezenas de outros), por extensao ou nome completo
|
|
10
|
+
- code-view: componente novo. Visualizador de codigo com realce de sintaxe proprio, numeracao de linhas, quebra opcional e virtualizacao para arquivos grandes
|
|
11
|
+
- file-tree: arquivos passam a usar os icones de `file-type-icon`
|
|
12
|
+
- core: `tokenize`, `tokenizeLinesOf`, `highlightToHtml`, `languageForFile`, `fileIconFor` e `fileIconSvg` (0.1.1)
|
|
13
|
+
|
|
5
14
|
## 0.2.0
|
|
6
15
|
|
|
7
16
|
### Minor
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import * as React from "react";
|
|
2
|
+
import { type LanguageId } from "../../lib/syntax.js";
|
|
3
|
+
type CodeViewProps = {
|
|
4
|
+
/** Texto do arquivo. */
|
|
5
|
+
code: string;
|
|
6
|
+
/** Linguagem (ex.: "go", "html", "ts"). Sem valor, e deduzida de `fileName`. */
|
|
7
|
+
language?: LanguageId | string;
|
|
8
|
+
/** Nome do arquivo, usado para deduzir a linguagem. */
|
|
9
|
+
fileName?: string;
|
|
10
|
+
/** Numeracao de linhas (padrao: ligada). */
|
|
11
|
+
lineNumbers?: boolean;
|
|
12
|
+
/** Quebra de linha longa; desligada, rola na horizontal. */
|
|
13
|
+
wrap?: boolean;
|
|
14
|
+
/** Primeira linha exibida na numeracao. */
|
|
15
|
+
startLine?: number;
|
|
16
|
+
/** Linhas a destacar (1-based, relativas a `startLine`). */
|
|
17
|
+
highlightLines?: number[];
|
|
18
|
+
/** Rola ate esta linha (numero exibido, ja considerando `startLine`) e a destaca. */
|
|
19
|
+
scrollToLine?: number;
|
|
20
|
+
/** Altura de cada linha em px (usada na virtualizacao; padrao 20). */
|
|
21
|
+
lineHeight?: number;
|
|
22
|
+
className?: string;
|
|
23
|
+
"aria-label"?: string;
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* Visualizador de codigo com realce de sintaxe proprio (sem dependencias) e numeracao.
|
|
27
|
+
* Sem quebra de linha, so as linhas visiveis entram no DOM, entao arquivos com dezenas de milhares de linhas rolam suave.
|
|
28
|
+
*/
|
|
29
|
+
declare function CodeView({ code, language, fileName, lineNumbers, wrap, startLine, highlightLines, scrollToLine, lineHeight, className, ...props }: CodeViewProps): React.JSX.Element;
|
|
30
|
+
export { CodeView };
|
|
31
|
+
export type { CodeViewProps };
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
import * as React from "react";
|
|
4
|
+
import { languageForFile, tokenizeLinesOf } from "../../lib/syntax.js";
|
|
5
|
+
import { cn } from "../../lib/utils.js";
|
|
6
|
+
const OVERSCAN = 40;
|
|
7
|
+
/**
|
|
8
|
+
* Visualizador de codigo com realce de sintaxe proprio (sem dependencias) e numeracao.
|
|
9
|
+
* Sem quebra de linha, so as linhas visiveis entram no DOM, entao arquivos com dezenas de milhares de linhas rolam suave.
|
|
10
|
+
*/
|
|
11
|
+
function CodeView({ code, language, fileName, lineNumbers = true, wrap = false, startLine = 1, highlightLines, scrollToLine, lineHeight = 20, className, ...props }) {
|
|
12
|
+
const lang = language ?? (fileName ? languageForFile(fileName) : "plaintext");
|
|
13
|
+
const lines = React.useMemo(() => tokenizeLinesOf(code, lang), [code, lang]);
|
|
14
|
+
const marked = React.useMemo(() => new Set([...(highlightLines ?? []), ...(scrollToLine ? [scrollToLine - startLine + 1] : [])]), [highlightLines, scrollToLine, startLine]);
|
|
15
|
+
const ref = React.useRef(null);
|
|
16
|
+
const [range, setRange] = React.useState({ from: 0, to: 120 });
|
|
17
|
+
const virtual = !wrap && lines.length > 400;
|
|
18
|
+
const update = React.useCallback(() => {
|
|
19
|
+
const el = ref.current;
|
|
20
|
+
if (!el)
|
|
21
|
+
return;
|
|
22
|
+
const from = Math.max(0, Math.floor(el.scrollTop / lineHeight) - OVERSCAN);
|
|
23
|
+
const to = Math.min(lines.length, Math.ceil((el.scrollTop + el.clientHeight) / lineHeight) + OVERSCAN);
|
|
24
|
+
setRange((r) => (r.from === from && r.to === to ? r : { from, to }));
|
|
25
|
+
}, [lineHeight, lines.length]);
|
|
26
|
+
React.useLayoutEffect(update, [update, virtual]);
|
|
27
|
+
React.useEffect(() => {
|
|
28
|
+
const el = ref.current;
|
|
29
|
+
if (!el || !virtual || typeof ResizeObserver === "undefined")
|
|
30
|
+
return;
|
|
31
|
+
const ro = new ResizeObserver(update);
|
|
32
|
+
ro.observe(el);
|
|
33
|
+
return () => ro.disconnect();
|
|
34
|
+
}, [update, virtual]);
|
|
35
|
+
// Rola ate a linha pedida (centralizada): por conta propria quando virtualizado, pela linha real quando nao.
|
|
36
|
+
React.useEffect(() => {
|
|
37
|
+
const el = ref.current;
|
|
38
|
+
if (!el || !scrollToLine)
|
|
39
|
+
return;
|
|
40
|
+
const idx = scrollToLine - startLine;
|
|
41
|
+
if (idx < 0 || idx >= lines.length)
|
|
42
|
+
return;
|
|
43
|
+
if (virtual) {
|
|
44
|
+
el.scrollTop = Math.max(0, idx * lineHeight - el.clientHeight / 3);
|
|
45
|
+
update();
|
|
46
|
+
}
|
|
47
|
+
else {
|
|
48
|
+
el.querySelector(`[data-line="${scrollToLine}"]`)?.scrollIntoView({ block: "center" });
|
|
49
|
+
}
|
|
50
|
+
}, [scrollToLine, startLine, lines, virtual, lineHeight, update]);
|
|
51
|
+
const gutter = String(startLine + lines.length - 1).length;
|
|
52
|
+
const from = virtual ? range.from : 0;
|
|
53
|
+
const to = virtual ? Math.min(range.to, lines.length) : lines.length;
|
|
54
|
+
const rows = [];
|
|
55
|
+
for (let i = from; i < to; i++) {
|
|
56
|
+
rows.push(_jsxs("div", { "data-line": startLine + i, "data-marked": marked.has(i + 1) || undefined, className: cn("flex min-w-max", wrap && "min-w-0", "data-[marked]:bg-accent/60"), style: { minHeight: lineHeight, lineHeight: `${lineHeight}px` }, children: [lineNumbers ? (_jsx("span", { "aria-hidden": true, className: "sticky left-0 shrink-0 select-none bg-card pr-3 pl-3 text-right text-muted-foreground/70 tabular-nums", style: { minWidth: `${gutter + 3}ch` }, children: startLine + i })) : (_jsx("span", { className: "shrink-0 pl-3" })), _jsx("span", { className: cn("pr-4", wrap ? "break-words whitespace-pre-wrap" : "whitespace-pre"), children: lines[i].length === 0
|
|
57
|
+
? ""
|
|
58
|
+
: lines[i].map((t, k) => (t.type === "plain" ? t.text : _jsx("span", { "data-t": t.type, children: t.text }, k))) })] }, i));
|
|
59
|
+
}
|
|
60
|
+
return (_jsx("div", { ref: ref, role: "region", tabIndex: 0, "aria-label": props["aria-label"] ?? fileName, "data-slot": "code-view", "data-language": lang, onScroll: virtual ? update : undefined, className: cn("h-full overflow-auto bg-card font-mono text-[13px] text-foreground outline-none focus-visible:ring-2 focus-visible:ring-ring/60", className), children: virtual ? (_jsx("div", { style: { height: lines.length * lineHeight, position: "relative" }, children: _jsx("div", { style: { position: "absolute", top: from * lineHeight, left: 0, right: 0 }, children: rows }) })) : (_jsx("div", { className: "py-2", children: rows })) }));
|
|
61
|
+
}
|
|
62
|
+
export { CodeView };
|
|
@@ -3,7 +3,9 @@ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
|
3
3
|
import * as React from "react";
|
|
4
4
|
import { ArchiveIcon, BracesIcon, ChevronRightIcon, DatabaseIcon, FileCogIcon, FileIcon, FileTextIcon, FolderIcon, FolderOpenIcon, ImageIcon, LockIcon, TerminalSquareIcon as SquareTerminalIcon, BinaryIcon } from "./icons.js";
|
|
5
5
|
import { cn } from "../../lib/utils.js";
|
|
6
|
+
import { FileTypeIcon } from "./file-type-icon.js";
|
|
6
7
|
import { fileKind } from "../../lib/file-kind.js";
|
|
8
|
+
import { fileIconFor } from "../../lib/file-icons.js";
|
|
7
9
|
const DEFAULT_LABELS = {
|
|
8
10
|
loading: "Carregando…",
|
|
9
11
|
empty: "Pasta vazia",
|
|
@@ -60,6 +62,7 @@ function FileTreeRow({ node, depth, open, selectedPath, onToggle, onSelect, onOp
|
|
|
60
62
|
const isOpen = node.isDir && open.has(node.path);
|
|
61
63
|
const selected = selectedPath === node.path;
|
|
62
64
|
const Icon = node.isDir ? (isOpen ? FolderOpenIcon : FolderIcon) : kindIcon[fileKind(node.name)];
|
|
65
|
+
const typed = !node.isDir && fileIconFor(node.name) !== undefined;
|
|
63
66
|
const actions = renderActions?.(node);
|
|
64
67
|
return (_jsxs("li", { role: "treeitem", "aria-expanded": node.isDir ? isOpen : undefined, "aria-selected": selected, children: [_jsxs("div", { "data-selected": selected, className: cn("group/row flex h-7 items-center rounded-md pr-1 text-muted-foreground transition-colors", "hover:bg-accent hover:text-foreground data-[selected=true]:bg-accent data-[selected=true]:text-foreground"), children: [_jsxs("button", { type: "button", style: { paddingLeft: `calc(${depth} * 0.875rem + 0.375rem)` }, onClick: () => {
|
|
65
68
|
onSelect?.(node);
|
|
@@ -80,6 +83,6 @@ function FileTreeRow({ node, depth, open, selectedPath, onToggle, onSelect, onOp
|
|
|
80
83
|
else if (!node.isDir && e.key === "Enter") {
|
|
81
84
|
onOpen?.(node);
|
|
82
85
|
}
|
|
83
|
-
}, className: "flex h-full min-w-0 flex-1 items-center gap-1.5 rounded-md text-left outline-none focus-visible:ring-2 focus-visible:ring-ring/60", children: [_jsx(ChevronRightIcon, { "aria-hidden": true, className: cn("size-3.5 shrink-0 transition-transform duration-150", node.isDir ? "opacity-70" : "opacity-0", isOpen && "rotate-90") }), _jsx(Icon, { className: cn("size-4 shrink-0", node.isDir && "text-brand") }), _jsx("span", { className: cn("truncate", node.gitStatus && statusTone[node.gitStatus]), children: node.name })] }), node.sizeLabel ? (_jsx("span", { className: "ml-1 shrink-0 font-mono text-[10px] text-muted-foreground tabular", children: node.sizeLabel })) : null, node.gitStatus ? (_jsx("span", { title: labels.status[node.gitStatus], "aria-label": labels.status[node.gitStatus], className: cn("ml-1 w-3 shrink-0 text-center font-mono text-[10px] font-semibold", statusTone[node.gitStatus]), children: statusLetter[node.gitStatus] })) : null, actions ? _jsx("span", { className: "ml-1 shrink-0 opacity-0 group-hover/row:opacity-100 focus-within:opacity-100", children: actions }) : null] }), isOpen ? (node.children === undefined ? (_jsx("p", { style: { paddingLeft: `calc(${depth + 1} * 0.875rem + 1.5rem)` }, className: "py-1 text-xs text-muted-foreground", children: labels.loading })) : node.children.length === 0 ? (_jsx("p", { style: { paddingLeft: `calc(${depth + 1} * 0.875rem + 1.5rem)` }, className: "py-1 text-xs text-muted-foreground", children: labels.empty })) : (_jsx("ul", { role: "group", className: "flex flex-col", children: node.children.map((child) => (_jsx(FileTreeRow, { node: child, depth: depth + 1, open: open, selectedPath: selectedPath, onToggle: onToggle, onSelect: onSelect, onOpen: onOpen, renderActions: renderActions, labels: labels }, child.path))) }))) : null] }));
|
|
86
|
+
}, className: "flex h-full min-w-0 flex-1 items-center gap-1.5 rounded-md text-left outline-none focus-visible:ring-2 focus-visible:ring-ring/60", children: [_jsx(ChevronRightIcon, { "aria-hidden": true, className: cn("size-3.5 shrink-0 transition-transform duration-150", node.isDir ? "opacity-70" : "opacity-0", isOpen && "rotate-90") }), typed ? _jsx(FileTypeIcon, { name: node.name, className: "size-4" }) : _jsx(Icon, { className: cn("size-4 shrink-0", node.isDir && "text-brand") }), _jsx("span", { className: cn("truncate", node.gitStatus && statusTone[node.gitStatus]), children: node.name })] }), node.sizeLabel ? (_jsx("span", { className: "ml-1 shrink-0 font-mono text-[10px] text-muted-foreground tabular", children: node.sizeLabel })) : null, node.gitStatus ? (_jsx("span", { title: labels.status[node.gitStatus], "aria-label": labels.status[node.gitStatus], className: cn("ml-1 w-3 shrink-0 text-center font-mono text-[10px] font-semibold", statusTone[node.gitStatus]), children: statusLetter[node.gitStatus] })) : null, actions ? _jsx("span", { className: "ml-1 shrink-0 opacity-0 group-hover/row:opacity-100 focus-within:opacity-100", children: actions }) : null] }), isOpen ? (node.children === undefined ? (_jsx("p", { style: { paddingLeft: `calc(${depth + 1} * 0.875rem + 1.5rem)` }, className: "py-1 text-xs text-muted-foreground", children: labels.loading })) : node.children.length === 0 ? (_jsx("p", { style: { paddingLeft: `calc(${depth + 1} * 0.875rem + 1.5rem)` }, className: "py-1 text-xs text-muted-foreground", children: labels.empty })) : (_jsx("ul", { role: "group", className: "flex flex-col", children: node.children.map((child) => (_jsx(FileTreeRow, { node: child, depth: depth + 1, open: open, selectedPath: selectedPath, onToggle: onToggle, onSelect: onSelect, onOpen: onOpen, renderActions: renderActions, labels: labels }, child.path))) }))) : null] }));
|
|
84
87
|
}
|
|
85
88
|
export { FileTree };
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import * as React from "react";
|
|
2
|
+
type FileTypeIconProps = {
|
|
3
|
+
/** Nome ou caminho do arquivo; a extensao (ou o nome completo, como Dockerfile) escolhe o icone. */
|
|
4
|
+
name: string;
|
|
5
|
+
/** Desenha uma pasta em vez de um arquivo. */
|
|
6
|
+
isDir?: boolean;
|
|
7
|
+
/** Pasta aberta (so vale com isDir). */
|
|
8
|
+
open?: boolean;
|
|
9
|
+
/** Tamanho em px; sem valor, o icone herda o tamanho do CSS (por exemplo size-4). */
|
|
10
|
+
size?: number;
|
|
11
|
+
className?: string;
|
|
12
|
+
};
|
|
13
|
+
/** Icone de arquivo por linguagem e formato (HTML, CSS, JS, TS, Go, Rust, C, C++ e dezenas de outros). */
|
|
14
|
+
declare function FileTypeIcon({ name, isDir, open, size, className }: FileTypeIconProps): React.JSX.Element;
|
|
15
|
+
export { FileTypeIcon };
|
|
16
|
+
export type { FileTypeIconProps };
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
3
|
+
import { FileIcon, FolderIcon, FolderOpenIcon } from "./icons.js";
|
|
4
|
+
import { fileIconFor } from "../../lib/file-icons.js";
|
|
5
|
+
import { cn } from "../../lib/utils.js";
|
|
6
|
+
/** Icone de arquivo por linguagem e formato (HTML, CSS, JS, TS, Go, Rust, C, C++ e dezenas de outros). */
|
|
7
|
+
function FileTypeIcon({ name, isDir = false, open = false, size, className }) {
|
|
8
|
+
if (isDir) {
|
|
9
|
+
const Folder = open ? FolderOpenIcon : FolderIcon;
|
|
10
|
+
return _jsx(Folder, { "aria-hidden": true, className: cn("shrink-0 text-brand", className), ...(size ? { width: size, height: size } : {}) });
|
|
11
|
+
}
|
|
12
|
+
const spec = fileIconFor(name);
|
|
13
|
+
if (!spec)
|
|
14
|
+
return _jsx(FileIcon, { "aria-hidden": true, className: cn("shrink-0", className), ...(size ? { width: size, height: size } : {}) });
|
|
15
|
+
const n = [...spec.label].length;
|
|
16
|
+
const fs = n === 1 ? 9.5 : n === 2 ? 7 : 5.5;
|
|
17
|
+
return (_jsxs("svg", { "aria-hidden": true, focusable: "false", "data-slot": "file-type-icon", "data-file-type": spec.id, viewBox: "0 0 16 16", width: size, height: size, className: cn("shrink-0", className), children: [_jsx("rect", { x: "0.75", y: "0.75", width: "14.5", height: "14.5", rx: "3.25", fill: spec.color }), _jsx("text", { x: "8", y: 8 + fs * 0.36, textAnchor: "middle", fontFamily: "ui-monospace,SFMono-Regular,Menlo,Consolas,monospace", fontSize: fs, fontWeight: 700, fill: spec.ink, children: spec.label })] }));
|
|
18
|
+
}
|
|
19
|
+
export { FileTypeIcon };
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export type FileIconSpec = {
|
|
2
|
+
/** Identificador estavel do tipo (ex.: "typescript", "image"). */
|
|
3
|
+
id: string;
|
|
4
|
+
/** Sigla de 1 a 3 caracteres desenhada no selo. */
|
|
5
|
+
label: string;
|
|
6
|
+
/** Cor do selo (hex). */
|
|
7
|
+
color: string;
|
|
8
|
+
/** Cor da sigla (hex), escolhida pelo contraste com o selo. */
|
|
9
|
+
ink: string;
|
|
10
|
+
};
|
|
11
|
+
/** Tipo do arquivo pelo nome completo e depois pela extensao; undefined = sem icone especifico. */
|
|
12
|
+
export declare function fileTypeId(name: string): string | undefined;
|
|
13
|
+
/** Especificacao do icone de um arquivo, ou undefined para o icone generico de arquivo. */
|
|
14
|
+
export declare function fileIconFor(name: string): FileIconSpec | undefined;
|
|
15
|
+
/** Todos os tipos com icone (para galerias e testes). */
|
|
16
|
+
export declare const fileIconTypes: readonly string[];
|
|
17
|
+
/** SVG do selo (string). `size` em px. */
|
|
18
|
+
export declare function fileIconSvg(spec: FileIconSpec, size?: number): string;
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
// Icones de tipo de arquivo (linguagens, formatos e extensoes mais usadas). Vanilla e sem DOM:
|
|
2
|
+
// `fileIconFor` escolhe o icone pelo nome; `fileIconSvg` o desenha como um selo colorido de 16x16 com a sigla do tipo.
|
|
3
|
+
// As formas sao proprias da Loccal UI (selo + sigla), nao reproduzem logotipos de terceiros.
|
|
4
|
+
const DARK = "#1b1b1f";
|
|
5
|
+
const LIGHT = "#ffffff";
|
|
6
|
+
const BY_TYPE = {
|
|
7
|
+
javascript: ["JS", "#f0db4f", DARK],
|
|
8
|
+
typescript: ["TS", "#3178c6"],
|
|
9
|
+
jsx: ["JX", "#f0db4f", DARK],
|
|
10
|
+
tsx: ["TX", "#3178c6"],
|
|
11
|
+
json: ["{}", "#d4a72c", DARK],
|
|
12
|
+
html: ["<>", "#e34f26"],
|
|
13
|
+
xml: ["<>", "#d9822b", DARK],
|
|
14
|
+
svg: ["SV", "#e8912d", DARK],
|
|
15
|
+
css: ["#", "#1572b6"],
|
|
16
|
+
scss: ["S", "#cd6799"],
|
|
17
|
+
less: ["L", "#2b4a7a"],
|
|
18
|
+
vue: ["V", "#41b883", DARK],
|
|
19
|
+
svelte: ["SV", "#ff3e00"],
|
|
20
|
+
go: ["GO", "#00a7c4"],
|
|
21
|
+
rust: ["RS", "#b7410e"],
|
|
22
|
+
c: ["C", "#5560bf"],
|
|
23
|
+
cpp: ["C+", "#00599c"],
|
|
24
|
+
header: ["H", "#7c6fcf"],
|
|
25
|
+
csharp: ["C#", "#8a3f96"],
|
|
26
|
+
java: ["JV", "#d9730d"],
|
|
27
|
+
kotlin: ["KT", "#7f52ff"],
|
|
28
|
+
swift: ["SW", "#f05138"],
|
|
29
|
+
dart: ["DT", "#0175c2"],
|
|
30
|
+
php: ["PH", "#777bb3"],
|
|
31
|
+
python: ["PY", "#3776ab"],
|
|
32
|
+
ruby: ["RB", "#cc342d"],
|
|
33
|
+
lua: ["LU", "#2c2d72"],
|
|
34
|
+
perl: ["PL", "#39457e"],
|
|
35
|
+
elixir: ["EX", "#6e4a7e"],
|
|
36
|
+
haskell: ["HS", "#5e5086"],
|
|
37
|
+
scala: ["SC", "#dc322f"],
|
|
38
|
+
zig: ["ZG", "#f7a41d", DARK],
|
|
39
|
+
r: ["R", "#276dc3"],
|
|
40
|
+
shell: [">_", "#3d9a3a"],
|
|
41
|
+
powershell: ["PS", "#2671be"],
|
|
42
|
+
batch: [">_", "#5a6169"],
|
|
43
|
+
sql: ["DB", "#e38c00", DARK],
|
|
44
|
+
yaml: ["YM", "#c2353a"],
|
|
45
|
+
toml: ["TM", "#9c4221"],
|
|
46
|
+
config: ["CF", "#6b7280"],
|
|
47
|
+
env: ["EN", "#6b7280"],
|
|
48
|
+
markdown: ["MD", "#3b82a0"],
|
|
49
|
+
text: ["TX", "#6b7280"],
|
|
50
|
+
log: ["LG", "#6b7280"],
|
|
51
|
+
docker: ["DK", "#2496ed"],
|
|
52
|
+
make: ["MK", "#6d8086"],
|
|
53
|
+
git: ["GT", "#e0432b"],
|
|
54
|
+
diff: ["±", "#6b7280"],
|
|
55
|
+
license: ["LI", "#6b7280"],
|
|
56
|
+
lock: ["LK", "#7a6f5c"],
|
|
57
|
+
csv: ["CS", "#2e9d6a"],
|
|
58
|
+
database: ["DB", "#7b61a8"],
|
|
59
|
+
pdf: ["PD", "#d63a35"],
|
|
60
|
+
doc: ["DC", "#2b6cb0"],
|
|
61
|
+
sheet: ["XL", "#1f8a4c"],
|
|
62
|
+
slides: ["PP", "#d2562a"],
|
|
63
|
+
image: ["IM", "#1f9e91"],
|
|
64
|
+
video: ["VD", "#9c3fb0"],
|
|
65
|
+
audio: ["AU", "#d6336c"],
|
|
66
|
+
font: ["Aa", "#6b7280"],
|
|
67
|
+
archive: ["ZP", "#8a6d52"],
|
|
68
|
+
binary: ["01", "#4b5563"],
|
|
69
|
+
executable: ["EX", "#4b5563"],
|
|
70
|
+
};
|
|
71
|
+
const EXT = {
|
|
72
|
+
js: "javascript", mjs: "javascript", cjs: "javascript", jsx: "jsx", ts: "typescript", mts: "typescript", cts: "typescript", tsx: "tsx",
|
|
73
|
+
json: "json", jsonc: "json", json5: "json", map: "json", webmanifest: "json", ipynb: "json",
|
|
74
|
+
html: "html", htm: "html", xhtml: "html", xml: "xml", xsd: "xml", xsl: "xml", plist: "xml", csproj: "xml", xaml: "xml", rss: "xml", svg: "svg",
|
|
75
|
+
css: "css", scss: "scss", sass: "scss", less: "less", vue: "vue", svelte: "svelte", astro: "html",
|
|
76
|
+
go: "go", rs: "rust", c: "c", h: "header", hpp: "header", hh: "header", cpp: "cpp", cc: "cpp", cxx: "cpp", ino: "cpp", cs: "csharp",
|
|
77
|
+
java: "java", kt: "kotlin", kts: "kotlin", swift: "swift", dart: "dart", php: "php", py: "python", pyw: "python", pyi: "python",
|
|
78
|
+
rb: "ruby", rake: "ruby", lua: "lua", pl: "perl", pm: "perl", ex: "elixir", exs: "elixir", hs: "haskell", scala: "scala", sc: "scala",
|
|
79
|
+
zig: "zig", r: "r",
|
|
80
|
+
sh: "shell", bash: "shell", zsh: "shell", fish: "shell", ksh: "shell", ps1: "powershell", psm1: "powershell", psd1: "powershell", bat: "batch", cmd: "batch",
|
|
81
|
+
sql: "sql", yaml: "yaml", yml: "yaml", toml: "toml", ini: "config", cfg: "config", conf: "config", properties: "config", editorconfig: "config", env: "env",
|
|
82
|
+
md: "markdown", markdown: "markdown", mdx: "markdown", rst: "text", txt: "text", log: "log", diff: "diff", patch: "diff",
|
|
83
|
+
mk: "make", mak: "make", lock: "lock", csv: "csv", tsv: "csv", db: "database", sqlite: "database", sqlite3: "database", parquet: "database",
|
|
84
|
+
pdf: "pdf", doc: "doc", docx: "doc", odt: "doc", rtf: "doc", xls: "sheet", xlsx: "sheet", ods: "sheet", ppt: "slides", pptx: "slides", odp: "slides",
|
|
85
|
+
png: "image", jpg: "image", jpeg: "image", gif: "image", webp: "image", bmp: "image", ico: "image", avif: "image", tif: "image", tiff: "image", heic: "image", icns: "image",
|
|
86
|
+
mp4: "video", mkv: "video", mov: "video", avi: "video", webm: "video", m4v: "video",
|
|
87
|
+
mp3: "audio", wav: "audio", flac: "audio", ogg: "audio", m4a: "audio", aac: "audio", opus: "audio",
|
|
88
|
+
ttf: "font", otf: "font", woff: "font", woff2: "font", eot: "font",
|
|
89
|
+
zip: "archive", tar: "archive", gz: "archive", tgz: "archive", bz2: "archive", xz: "archive", "7z": "archive", rar: "archive", zst: "archive", iso: "archive", jar: "archive", war: "archive",
|
|
90
|
+
exe: "executable", msi: "executable", app: "executable", apk: "executable", bin: "binary", dll: "binary", so: "binary", dylib: "binary", o: "binary", obj: "binary", class: "binary", wasm: "binary", pyc: "binary",
|
|
91
|
+
};
|
|
92
|
+
const NAME = {
|
|
93
|
+
dockerfile: "docker", ".dockerignore": "docker", "docker-compose.yml": "docker", "docker-compose.yaml": "docker", "compose.yaml": "docker", "compose.yml": "docker",
|
|
94
|
+
makefile: "make", gnumakefile: "make", ".gitignore": "git", ".gitattributes": "git", ".gitmodules": "git", ".gitconfig": "git",
|
|
95
|
+
license: "license", "license.md": "license", "license.txt": "license", copying: "license", notice: "license",
|
|
96
|
+
"package-lock.json": "lock", "pnpm-lock.yaml": "lock", "yarn.lock": "lock", "go.sum": "lock", "cargo.lock": "lock", "poetry.lock": "lock", "composer.lock": "lock", gemfile: "ruby", rakefile: "ruby",
|
|
97
|
+
"go.mod": "go", "go.work": "go", ".env": "env", ".npmrc": "config", ".editorconfig": "config", ".prettierrc": "json", ".eslintrc": "json",
|
|
98
|
+
".bashrc": "shell", ".zshrc": "shell", ".profile": "shell", readme: "markdown",
|
|
99
|
+
};
|
|
100
|
+
/** Tipo do arquivo pelo nome completo e depois pela extensao; undefined = sem icone especifico. */
|
|
101
|
+
export function fileTypeId(name) {
|
|
102
|
+
const base = name.replace(/\\/g, "/").split("/").pop().toLowerCase();
|
|
103
|
+
if (NAME[base])
|
|
104
|
+
return NAME[base];
|
|
105
|
+
if (base.startsWith(".env."))
|
|
106
|
+
return "env";
|
|
107
|
+
const dot = base.lastIndexOf(".");
|
|
108
|
+
if (dot <= 0)
|
|
109
|
+
return undefined;
|
|
110
|
+
const ext = base.slice(dot + 1);
|
|
111
|
+
if (base.endsWith(".d.ts"))
|
|
112
|
+
return "typescript";
|
|
113
|
+
return EXT[ext];
|
|
114
|
+
}
|
|
115
|
+
/** Especificacao do icone de um arquivo, ou undefined para o icone generico de arquivo. */
|
|
116
|
+
export function fileIconFor(name) {
|
|
117
|
+
const id = fileTypeId(name);
|
|
118
|
+
if (!id)
|
|
119
|
+
return undefined;
|
|
120
|
+
const e = BY_TYPE[id];
|
|
121
|
+
if (!e)
|
|
122
|
+
return undefined;
|
|
123
|
+
return { id, label: e[0], color: e[1], ink: e[2] ?? LIGHT };
|
|
124
|
+
}
|
|
125
|
+
/** Todos os tipos com icone (para galerias e testes). */
|
|
126
|
+
export const fileIconTypes = Object.keys(BY_TYPE);
|
|
127
|
+
const escXml = (s) => s.replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]);
|
|
128
|
+
/** SVG do selo (string). `size` em px. */
|
|
129
|
+
export function fileIconSvg(spec, size = 16) {
|
|
130
|
+
const n = [...spec.label].length;
|
|
131
|
+
const fs = n === 1 ? 9.5 : n === 2 ? 7 : 5.5;
|
|
132
|
+
return (`<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 16 16" aria-hidden="true" focusable="false" data-file-type="${spec.id}">` +
|
|
133
|
+
`<rect x="0.75" y="0.75" width="14.5" height="14.5" rx="3.25" fill="${spec.color}"/>` +
|
|
134
|
+
`<text x="8" y="${(8 + fs * 0.36).toFixed(2)}" text-anchor="middle" font-family="ui-monospace,SFMono-Regular,Menlo,Consolas,monospace" font-size="${fs}" font-weight="700" fill="${spec.ink}">${escXml(spec.label)}</text>` +
|
|
135
|
+
`</svg>`);
|
|
136
|
+
}
|
package/dist/lib/icon-data.d.ts
CHANGED
|
@@ -270,7 +270,7 @@ export declare const iconNames: IconName[];
|
|
|
270
270
|
export declare function isIconName(name: string): name is IconName;
|
|
271
271
|
export declare function iconEntries(): {
|
|
272
272
|
name: "function" | "circle" | "x" | "tag" | "target" | "type" | "filter" | "key" | "code" | "link" | "menu" | "search" | "table" | "video" | "image" | "stop" | "repeat" | "bold" | "square" | "heading" | "list" | "log" | "radio" | "tab" | "timer" | "terminal" | "copy" | "move" | "arrow-up" | "arrow-down" | "arrow-left" | "arrow-right" | "arrow-up-right" | "arrow-up-left" | "arrow-down-right" | "arrow-down-left" | "arrow-up-down" | "arrow-left-right" | "chevron-up" | "chevron-down" | "chevron-left" | "chevron-right" | "chevrons-up" | "chevrons-down" | "chevrons-up-down" | "chevrons-left-right" | "corner-down-left" | "corner-down-right" | "undo" | "redo" | "refresh" | "expand" | "shrink" | "external-link" | "log-in" | "log-out" | "trending-up" | "trending-down" | "check" | "check-check" | "check-circle" | "x-circle" | "x-octagon" | "alert-triangle" | "alert-circle" | "info" | "help-circle" | "plus-circle" | "minus-circle" | "ban" | "loader" | "clock" | "bell" | "bell-off" | "circle-dot" | "dot" | "star" | "heart" | "flag" | "bookmark" | "pin" | "eye" | "eye-off" | "zap" | "activity" | "gauge" | "flame" | "power" | "prompt" | "shell" | "terminal-square" | "command" | "history" | "text-cursor" | "hash" | "at-sign" | "braces" | "brackets" | "bug" | "cpu" | "server" | "box" | "layers" | "eraser" | "wrench" | "play" | "pause" | "list-tree" | "split-vertical" | "split-horizontal" | "file" | "file-text" | "file-code" | "file-cog" | "binary" | "file-json" | "file-terminal" | "file-image" | "file-archive" | "file-plus" | "file-minus" | "file-check" | "file-x" | "file-lock" | "folder" | "folder-open" | "folder-plus" | "folder-tree" | "home" | "archive" | "download" | "upload" | "save" | "paperclip" | "inbox" | "trash" | "clipboard" | "clipboard-check" | "scissors" | "zoom-in" | "zoom-out" | "printer" | "git-branch" | "git-commit" | "git-merge" | "git-pull-request" | "git-fork" | "diff" | "git-compare" | "bot" | "sparkles" | "brain" | "wand" | "message-square" | "message-circle" | "send" | "lightbulb" | "workflow" | "stop-circle" | "rocket" | "window" | "window-minimize" | "window-maximize" | "window-restore" | "window-close" | "panel-left" | "panel-right" | "panel-bottom" | "layout-grid" | "layout-dashboard" | "pip" | "plus" | "minus" | "more-horizontal" | "more-vertical" | "grip" | "settings" | "sliders" | "sun" | "moon" | "monitor" | "palette" | "keyboard" | "mouse-pointer" | "wifi" | "wifi-off" | "globe" | "cloud" | "cloud-upload" | "cloud-download" | "plug" | "signal" | "router" | "share" | "network" | "mail" | "qr-code" | "route" | "lock" | "unlock" | "shield" | "shield-check" | "shield-alert" | "shield-question" | "shield-x" | "badge-check" | "scan" | "asterisk" | "italic" | "underline" | "strikethrough" | "align-left" | "align-center" | "align-right" | "align-justify" | "quote" | "pencil" | "list-ordered" | "list-checks" | "indent" | "outdent" | "wrap" | "case-sensitive" | "regex" | "book-open" | "calendar" | "percent" | "sigma" | "check-square" | "plus-square" | "minus-square" | "toggle-off" | "toggle-on" | "sort-asc" | "sort-desc" | "user" | "users" | "user-plus" | "user-check" | "circle-user" | "credit-card" | "map-pin" | "compass" | "camera" | "mic" | "droplet" | "umbrella" | "volume" | "volume-x" | "skip-forward" | "skip-back" | "play-circle" | "laptop" | "smartphone" | "hard-drive" | "battery" | "thermometer" | "disc" | "database" | "bar-chart" | "line-chart" | "pie-chart";
|
|
273
|
-
category: "status" | "terminal" | "
|
|
273
|
+
category: "status" | "terminal" | "git" | "arquivos" | "ia" | "janela" | "setas" | "editor" | "rede" | "seguranca" | "interface" | "midia" | "dispositivos" | "dados";
|
|
274
274
|
tags: string;
|
|
275
275
|
shapes: string[];
|
|
276
276
|
}[];
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
export type TokenType = "comment" | "string" | "number" | "keyword" | "type" | "function" | "constant" | "operator" | "punctuation" | "tag" | "attr" | "property" | "variable" | "meta" | "heading" | "inserted" | "deleted" | "plain";
|
|
2
|
+
export type Token = {
|
|
3
|
+
type: TokenType;
|
|
4
|
+
text: string;
|
|
5
|
+
};
|
|
6
|
+
export type LanguageId = "javascript" | "typescript" | "jsx" | "tsx" | "json" | "html" | "xml" | "css" | "scss" | "less" | "go" | "rust" | "c" | "cpp" | "csharp" | "java" | "kotlin" | "swift" | "dart" | "php" | "python" | "ruby" | "lua" | "shell" | "powershell" | "batch" | "sql" | "yaml" | "toml" | "ini" | "markdown" | "dockerfile" | "makefile" | "diff" | "zig" | "scala" | "r" | "perl" | "elixir" | "haskell" | "plaintext";
|
|
7
|
+
/** Linguagem de um arquivo pelo nome (nome completo primeiro, depois extensao). */
|
|
8
|
+
export declare function languageForFile(name: string): LanguageId;
|
|
9
|
+
/** Normaliza um identificador de linguagem (aceita extensoes e apelidos). */
|
|
10
|
+
export declare function resolveLanguage(lang: string): LanguageId;
|
|
11
|
+
/** Tokeniza o texto inteiro. A concatenacao dos tokens sempre reproduz exatamente a entrada. */
|
|
12
|
+
export declare function tokenize(code: string, lang: LanguageId | string): Token[];
|
|
13
|
+
/** Divide os tokens por linha (sem o "\n"), preservando tokens que atravessam linhas (comentarios de bloco, strings). */
|
|
14
|
+
export declare function tokenizeLinesOf(code: string, lang: LanguageId | string): Token[][];
|
|
15
|
+
/** HTML com <span class="lt-<tipo">; as cores vem do CSS (ver --code-* nos tokens). */
|
|
16
|
+
export declare function highlightToHtml(code: string, lang: LanguageId | string): string;
|
|
@@ -0,0 +1,540 @@
|
|
|
1
|
+
// Realce de sintaxe vanilla: sem dependencias e sem DOM. Um tokenizador de uma passada por linguagem, pensado para
|
|
2
|
+
// visualizar arquivos (nao e um parser). Cobre as linguagens mais usadas e cai em texto simples nas demais.
|
|
3
|
+
const words = (s) => new Set(s.split(/\s+/).filter(Boolean));
|
|
4
|
+
const esc = (s) => s.replace(/[.*+?^${}()|[\]\\/-]/g, "\\$&");
|
|
5
|
+
const sticky = (re) => new RegExp(re.source, re.flags.includes("y") ? re.flags : re.flags + "y");
|
|
6
|
+
const NUMBER = /(?:0[xX][0-9a-fA-F_]+|0[bB][01_]+|0[oO][0-7_]+|(?:\d[\d_]*\.?\d*|\.\d+)(?:[eE][+-]?\d+)?)[a-zA-Z]{0,3}\b/;
|
|
7
|
+
const OPERATOR = /[+\-*/%=<>!&|^~?:]+/;
|
|
8
|
+
const PUNCT = /[{}()[\];,.]/;
|
|
9
|
+
function compile(def) {
|
|
10
|
+
const rules = [];
|
|
11
|
+
const flag = def.caseInsensitive ? "i" : "";
|
|
12
|
+
for (const b of def.block ?? [])
|
|
13
|
+
rules.push(["comment", sticky(new RegExp(`${esc(b[0])}[\\s\\S]*?(?:${esc(b[1])}|$)`))]);
|
|
14
|
+
for (const l of def.line ?? [])
|
|
15
|
+
rules.push(["comment", sticky(new RegExp(`${esc(l)}.*`))]);
|
|
16
|
+
for (const q of def.multiline ?? [])
|
|
17
|
+
rules.push(["string", sticky(new RegExp(`${esc(q)}[\\s\\S]*?(?:${esc(q)}|$)`))]);
|
|
18
|
+
for (const q of def.strings ?? []) {
|
|
19
|
+
const multi = q === "`";
|
|
20
|
+
rules.push(["string", sticky(new RegExp(`${esc(q)}(?:\\\\[\\s\\S]|[^\\\\${multi ? "" : "\\n"}${esc(q)}])*(?:${esc(q)}|$)`))]);
|
|
21
|
+
}
|
|
22
|
+
for (const q of def.rawStrings ?? [])
|
|
23
|
+
rules.push(["string", sticky(new RegExp(`${esc(q)}[^${esc(q)}]*(?:${esc(q)}|$)`))]);
|
|
24
|
+
if (def.regex)
|
|
25
|
+
rules.push(["string", sticky(/\/(?![/*])(?:\\.|\[(?:\\.|[^\]\\\n])*\]|[^/\\\n[])+\/[dgimsuvy]*/)]);
|
|
26
|
+
if (def.meta)
|
|
27
|
+
rules.push(["meta", sticky(def.meta)]);
|
|
28
|
+
rules.push(["number", sticky(NUMBER)]);
|
|
29
|
+
if (def.varPrefix)
|
|
30
|
+
rules.push(["variable", sticky(new RegExp(`[${esc(def.varPrefix)}][A-Za-z_][\\w]*|\\$\\{[^}\\n]*\\}`))]);
|
|
31
|
+
rules.push(["plain", sticky(/[A-Za-z_À-][\wÀ-]*/)]);
|
|
32
|
+
rules.push(["operator", sticky(def.operators ?? OPERATOR)]);
|
|
33
|
+
rules.push(["punctuation", sticky(PUNCT)]);
|
|
34
|
+
const norm = (s) => (flag ? s.toLowerCase() : s);
|
|
35
|
+
const classify = (id, next) => {
|
|
36
|
+
const k = norm(id);
|
|
37
|
+
if (def.keywords?.has(k))
|
|
38
|
+
return "keyword";
|
|
39
|
+
if (def.constants?.has(k))
|
|
40
|
+
return "constant";
|
|
41
|
+
if (def.types?.has(k))
|
|
42
|
+
return "type";
|
|
43
|
+
if (next === "(")
|
|
44
|
+
return "function";
|
|
45
|
+
if (def.pascalTypes && /^[A-Z][A-Za-z0-9_]*[a-z]/.test(id))
|
|
46
|
+
return "type";
|
|
47
|
+
return "plain";
|
|
48
|
+
};
|
|
49
|
+
return { rules, classify };
|
|
50
|
+
}
|
|
51
|
+
const JS_KW = "as async await break case catch class const continue debugger default delete do else enum export extends finally for from function get if implements import in instanceof interface let new of package private protected public readonly return set static super switch this throw try type typeof var void while with yield declare namespace abstract satisfies keyof infer is override";
|
|
52
|
+
const JS_CONST = "true false null undefined NaN Infinity";
|
|
53
|
+
const JS_TYPES = "string number boolean any unknown never object symbol bigint Array Promise Map Set Record Partial Readonly Date Error RegExp";
|
|
54
|
+
const DEFS = {
|
|
55
|
+
javascript: { line: ["//"], block: [["/*", "*/"]], strings: ['"', "'", "`"], regex: true, keywords: words(JS_KW), constants: words(JS_CONST), pascalTypes: true, meta: /@[A-Za-z_]\w*/ },
|
|
56
|
+
go: { line: ["//"], block: [["/*", "*/"]], strings: ['"', "'"], rawStrings: ["`"], keywords: words("break case chan const continue default defer else fallthrough for func go goto if import interface map package range return select struct switch type var"), constants: words("true false nil iota"), types: words("string int int8 int16 int32 int64 uint uint8 uint16 uint32 uint64 uintptr float32 float64 complex64 complex128 bool byte rune error any comparable") },
|
|
57
|
+
rust: { line: ["//"], block: [["/*", "*/"]], strings: ['"', "'"], keywords: words("as async await break const continue crate dyn else enum extern fn for if impl in let loop match mod move mut pub ref return self Self static struct super trait type unsafe use where while"), constants: words("true false None Some Ok Err"), types: words("i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize f32 f64 bool char str String Vec Option Result Box Rc Arc"), pascalTypes: true, meta: /#!?\[[^\]\n]*\]/, operators: /[+\-*/%=<>!&|^~?:]+/ },
|
|
58
|
+
c: { line: ["//"], block: [["/*", "*/"]], strings: ['"', "'"], keywords: words("auto break case const continue default do else enum extern for goto if inline register restrict return sizeof static struct switch typedef union volatile while"), constants: words("true false NULL"), types: words("void char short int long float double signed unsigned size_t bool uint8_t uint16_t uint32_t uint64_t int8_t int16_t int32_t int64_t FILE"), meta: /#\s*[a-z]+(?:[ \t]*<[^>\n]*>)?/ },
|
|
59
|
+
cpp: { line: ["//"], block: [["/*", "*/"]], strings: ['"', "'"], keywords: words("alignas alignof and asm auto break case catch class concept const consteval constexpr constinit const_cast continue co_await co_return co_yield decltype default delete do dynamic_cast else enum explicit export extern for friend goto if inline mutable namespace new noexcept not operator or private protected public register reinterpret_cast requires return sizeof static static_assert static_cast struct switch template this throw try typedef typeid typename union using virtual volatile while override final"), constants: words("true false nullptr NULL"), types: words("void char short int long float double signed unsigned bool size_t wchar_t string vector map set unique_ptr shared_ptr optional"), meta: /#\s*[a-z]+(?:[ \t]*<[^>\n]*>)?/ },
|
|
60
|
+
csharp: { line: ["//"], block: [["/*", "*/"]], strings: ['"', "'"], keywords: words("abstract as async await base break case catch checked class const continue default delegate do else enum event explicit extern finally fixed for foreach goto if implicit in interface internal is lock namespace new operator out override params private protected public readonly ref return sealed sizeof stackalloc static struct switch this throw try typeof unchecked unsafe using virtual volatile while var record get set init yield where"), constants: words("true false null"), types: words("bool byte char decimal double float int long object sbyte short string uint ulong ushort void dynamic"), pascalTypes: true, meta: /#\s*[a-z]+/ },
|
|
61
|
+
java: { line: ["//"], block: [["/*", "*/"]], strings: ['"', "'"], keywords: words("abstract assert break case catch class const continue default do else enum extends final finally for goto if implements import instanceof interface native new package private protected public return static strictfp super switch synchronized this throw throws transient try var volatile while record sealed permits"), constants: words("true false null"), types: words("boolean byte char double float int long short void String Object Integer List Map Set"), pascalTypes: true, meta: /@[A-Za-z_]\w*/ },
|
|
62
|
+
kotlin: { line: ["//"], block: [["/*", "*/"]], strings: ['"', "'"], multiline: ['"""'], keywords: words("abstract annotation as break by catch class companion const constructor continue crossinline data delegate do else enum expect external final finally for fun get if import in infix init inline inner interface internal is lateinit noinline object open operator out override package private protected public reified return sealed set super suspend tailrec this throw try typealias val var vararg when where while"), constants: words("true false null"), types: words("Int Long Short Byte Float Double Boolean Char String Unit Any Nothing List Map Set Array"), pascalTypes: true, meta: /@[A-Za-z_]\w*/ },
|
|
63
|
+
swift: { line: ["//"], block: [["/*", "*/"]], strings: ['"'], multiline: ['"""'], keywords: words("actor as associatedtype async await break case catch class continue default defer deinit do else enum extension fallthrough fileprivate for func guard if import in init inout internal is let nil open operator override private protocol public repeat rethrows return self Self static struct subscript super switch throw throws try typealias var where while"), constants: words("true false nil"), types: words("Int Double Float Bool String Character Array Dictionary Set Optional Any AnyObject Void"), pascalTypes: true, meta: /[@#][A-Za-z_]\w*/ },
|
|
64
|
+
dart: { line: ["//"], block: [["/*", "*/"]], strings: ['"', "'"], keywords: words("abstract as assert async await break case catch class const continue covariant default deferred do dynamic else enum export extends extension external factory final finally for Function get hide if implements import in interface is late library mixin new on operator part required rethrow return set show static super switch sync this throw try typedef var void while with yield"), constants: words("true false null"), types: words("int double num bool String List Map Set Future Stream Object dynamic void"), pascalTypes: true, meta: /@[A-Za-z_]\w*/ },
|
|
65
|
+
php: { line: ["//", "#"], block: [["/*", "*/"]], strings: ['"', "'"], varPrefix: "$", caseInsensitive: true, keywords: words("abstract and as break callable case catch class clone const continue declare default do echo else elseif empty enddeclare endfor endforeach endif endswitch endwhile enum extends final finally fn for foreach function global goto if implements include include_once instanceof insteadof interface isset list match namespace new or print private protected public readonly require require_once return static switch throw trait try unset use var while xor yield"), constants: words("true false null"), types: words("int float string bool array object mixed void never iterable callable self parent"), meta: /<\?php|<\?=|\?>/ },
|
|
66
|
+
python: { line: ["#"], strings: ['"', "'"], multiline: ['"""', "'''"], keywords: words("and as assert async await break class continue def del elif else except finally for from global if import in is lambda nonlocal not or pass raise return try while with yield match case"), constants: words("True False None self cls"), types: words("int float str bool list dict set tuple bytes object type complex range"), pascalTypes: true, meta: /@[A-Za-z_][\w.]*/ },
|
|
67
|
+
ruby: { line: ["#"], block: [["=begin", "=end"]], strings: ['"', "'", "`"], keywords: words("alias and begin break case class def defined? do else elsif end ensure for if in module next not or redo rescue retry return self super then undef unless until when while yield require require_relative include extend attr_accessor attr_reader attr_writer private protected public"), constants: words("true false nil"), pascalTypes: true, varPrefix: "@$" },
|
|
68
|
+
lua: { line: ["--"], block: [["--[[", "]]"]], strings: ['"', "'"], multiline: ["[[", "[=["], keywords: words("and break do else elseif end for function goto if in local not or repeat return then until while"), constants: words("true false nil self") },
|
|
69
|
+
shell: { line: ["#"], strings: ['"', "'", "`"], varPrefix: "$", keywords: words("if then else elif fi for while until do done case esac in function select time return exit break continue export local readonly declare unset source alias set shift trap eval exec cd echo printf read test"), constants: words("true false"), operators: /[|&;<>=!]+/ },
|
|
70
|
+
powershell: { line: ["#"], block: [["<#", "#>"]], strings: ['"', "'"], varPrefix: "$", caseInsensitive: true, keywords: words("begin break catch class continue data do dynamicparam else elseif end enum exit filter finally for foreach from function if in param process return switch throw trap try until using var while workflow"), constants: words("true false null"), operators: /[|&;<>=!+\-*/%]+/ },
|
|
71
|
+
batch: { line: ["rem ", "::"], strings: ['"'], caseInsensitive: true, keywords: words("echo set if else for in do goto call exit not exist defined errorlevel pause start setlocal endlocal shift cd mkdir rmdir copy move del type cls"), varPrefix: "%" },
|
|
72
|
+
sql: { line: ["--"], block: [["/*", "*/"]], strings: ["'", '"'], caseInsensitive: true, keywords: words("add all alter and as asc between by case check column commit constraint create cross database default delete desc distinct drop else end exists foreign from full group having if in index inner insert into is join key left like limit not null offset on or order outer primary references replace right rollback select set table then top union unique update values view when where with returning begin transaction"), constants: words("true false null"), types: words("int integer bigint smallint varchar char text boolean date datetime timestamp numeric decimal float real json uuid serial") },
|
|
73
|
+
zig: { line: ["//"], strings: ['"', "'"], keywords: words("align allowzero and anyframe anytype asm async await break callconv catch comptime const continue defer else enum errdefer error export extern fn for if inline linksection noalias nosuspend opaque or orelse packed pub resume return struct suspend switch test threadlocal try union unreachable usingnamespace var volatile while"), constants: words("true false null undefined"), types: words("u8 u16 u32 u64 i8 i16 i32 i64 usize isize f32 f64 bool void type anyerror"), meta: /@[A-Za-z_]\w*/ },
|
|
74
|
+
scala: { line: ["//"], block: [["/*", "*/"]], strings: ['"', "'"], multiline: ['"""'], keywords: words("abstract case catch class def do else extends final finally for forSome if implicit import lazy match new object override package private protected return sealed super this throw trait try type val var while with yield given using enum then"), constants: words("true false null"), pascalTypes: true, meta: /@[A-Za-z_]\w*/ },
|
|
75
|
+
r: { line: ["#"], strings: ['"', "'"], keywords: words("if else repeat while function for next break in library require return"), constants: words("TRUE FALSE NULL NA NA_integer_ NA_real_ NA_character_ Inf NaN") },
|
|
76
|
+
perl: { line: ["#"], strings: ['"', "'"], varPrefix: "$@%", keywords: words("my our local use no package sub if elsif else unless while until for foreach last next redo return die warn print say require do eval and or not"), },
|
|
77
|
+
elixir: { line: ["#"], strings: ['"', "'"], multiline: ['"""'], keywords: words("def defp defmodule defmacro defstruct defprotocol defimpl do end fn if else unless case cond when with for in import require alias use quote unquote raise rescue try catch after receive send spawn and or not"), constants: words("true false nil"), pascalTypes: true, meta: /@[a-z_]\w*/ },
|
|
78
|
+
haskell: { line: ["--"], block: [["{-", "-}"]], strings: ['"', "'"], keywords: words("case class data default deriving do else family forall foreign if import in infix infixl infixr instance let module newtype of qualified then type where"), constants: words("True False Nothing Just Left Right"), pascalTypes: true },
|
|
79
|
+
};
|
|
80
|
+
/** TS/JSX/TSX compartilham a definicao do JS. */
|
|
81
|
+
DEFS.typescript = DEFS.javascript;
|
|
82
|
+
DEFS.jsx = DEFS.javascript;
|
|
83
|
+
DEFS.tsx = DEFS.javascript;
|
|
84
|
+
const ALIASES = {
|
|
85
|
+
js: "javascript", mjs: "javascript", cjs: "javascript", ts: "typescript", mts: "typescript", cts: "typescript",
|
|
86
|
+
jsx: "jsx", tsx: "tsx", json: "json", jsonc: "json", json5: "json", webmanifest: "json", map: "json", ipynb: "json",
|
|
87
|
+
html: "html", htm: "html", xhtml: "html", vue: "html", svelte: "html", astro: "html", xml: "xml", svg: "xml", xsd: "xml", xsl: "xml",
|
|
88
|
+
plist: "xml", csproj: "xml", props: "xml", targets: "xml", rss: "xml", atom: "xml", xaml: "xml",
|
|
89
|
+
css: "css", scss: "scss", sass: "scss", less: "less", go: "go", rs: "rust", c: "c", h: "c", cpp: "cpp", cc: "cpp", cxx: "cpp",
|
|
90
|
+
hpp: "cpp", hh: "cpp", hxx: "cpp", ino: "cpp", cs: "csharp", java: "java", kt: "kotlin", kts: "kotlin", swift: "swift", dart: "dart",
|
|
91
|
+
php: "php", py: "python", pyw: "python", pyi: "python", rb: "ruby", rake: "ruby", gemspec: "ruby", lua: "lua", sh: "shell", bash: "shell",
|
|
92
|
+
zsh: "shell", fish: "shell", ksh: "shell", ps1: "powershell", psm1: "powershell", psd1: "powershell", bat: "batch", cmd: "batch",
|
|
93
|
+
sql: "sql", yaml: "yaml", yml: "yaml", toml: "toml", ini: "ini", cfg: "ini", conf: "ini", properties: "ini", env: "ini", editorconfig: "ini",
|
|
94
|
+
md: "markdown", markdown: "markdown", mdx: "markdown", dockerfile: "dockerfile", mk: "makefile", mak: "makefile",
|
|
95
|
+
diff: "diff", patch: "diff", zig: "zig", scala: "scala", sc: "scala", r: "r", pl: "perl", pm: "perl", ex: "elixir", exs: "elixir", hs: "haskell",
|
|
96
|
+
txt: "plaintext", log: "plaintext", csv: "plaintext", tsv: "plaintext",
|
|
97
|
+
};
|
|
98
|
+
const BY_NAME = {
|
|
99
|
+
dockerfile: "dockerfile", makefile: "makefile", gnumakefile: "makefile", ".bashrc": "shell", ".zshrc": "shell", ".profile": "shell",
|
|
100
|
+
".gitignore": "ini", ".gitattributes": "ini", ".gitconfig": "ini", ".npmrc": "ini", ".env": "ini", "cargo.lock": "toml", "go.mod": "go", "go.work": "go",
|
|
101
|
+
gemfile: "ruby", rakefile: "ruby", "tsconfig.json": "json", "package.json": "json", ".eslintrc": "json", ".prettierrc": "json",
|
|
102
|
+
};
|
|
103
|
+
/** Linguagem de um arquivo pelo nome (nome completo primeiro, depois extensao). */
|
|
104
|
+
export function languageForFile(name) {
|
|
105
|
+
const base = name.replace(/\\/g, "/").split("/").pop().toLowerCase();
|
|
106
|
+
if (BY_NAME[base])
|
|
107
|
+
return BY_NAME[base];
|
|
108
|
+
const dot = base.lastIndexOf(".");
|
|
109
|
+
if (dot < 0)
|
|
110
|
+
return "plaintext";
|
|
111
|
+
if (dot === 0)
|
|
112
|
+
return BY_NAME[base] ?? "plaintext";
|
|
113
|
+
return ALIASES[base.slice(dot + 1)] ?? "plaintext";
|
|
114
|
+
}
|
|
115
|
+
/** Normaliza um identificador de linguagem (aceita extensoes e apelidos). */
|
|
116
|
+
export function resolveLanguage(lang) {
|
|
117
|
+
const l = lang.toLowerCase();
|
|
118
|
+
return (ALIASES[l] ?? (l in DEFS || ["json", "html", "xml", "css", "scss", "less", "yaml", "toml", "ini", "markdown", "dockerfile", "makefile", "diff", "plaintext"].includes(l) ? l : "plaintext"));
|
|
119
|
+
}
|
|
120
|
+
const cache = new Map();
|
|
121
|
+
function compiled(lang) {
|
|
122
|
+
let c = cache.get(lang);
|
|
123
|
+
if (!c) {
|
|
124
|
+
c = compile(DEFS[lang]);
|
|
125
|
+
cache.set(lang, c);
|
|
126
|
+
}
|
|
127
|
+
return c;
|
|
128
|
+
}
|
|
129
|
+
function push(out, type, text) {
|
|
130
|
+
if (!text)
|
|
131
|
+
return;
|
|
132
|
+
const last = out[out.length - 1];
|
|
133
|
+
if (last && last.type === type)
|
|
134
|
+
last.text += text;
|
|
135
|
+
else
|
|
136
|
+
out.push({ type, text });
|
|
137
|
+
}
|
|
138
|
+
function scan(code, lang, out) {
|
|
139
|
+
const { rules, classify } = compiled(lang);
|
|
140
|
+
let i = 0;
|
|
141
|
+
while (i < code.length) {
|
|
142
|
+
let hit = false;
|
|
143
|
+
for (const [type, re] of rules) {
|
|
144
|
+
re.lastIndex = i;
|
|
145
|
+
const m = re.exec(code);
|
|
146
|
+
if (!m || m[0].length === 0)
|
|
147
|
+
continue;
|
|
148
|
+
let t = type;
|
|
149
|
+
if (type === "plain")
|
|
150
|
+
t = classify(m[0], code[i + m[0].length] ?? "");
|
|
151
|
+
push(out, t, m[0]);
|
|
152
|
+
i += m[0].length;
|
|
153
|
+
hit = true;
|
|
154
|
+
break;
|
|
155
|
+
}
|
|
156
|
+
if (!hit) {
|
|
157
|
+
push(out, "plain", code[i]);
|
|
158
|
+
i++;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
// ---------- linguagens com gramatica propria
|
|
163
|
+
function tokenizeJson(code, out) {
|
|
164
|
+
const re = /("(?:\\.|[^"\\\n])*")(\s*:)?|(-?\d+\.?\d*(?:[eE][+-]?\d+)?)|(\btrue\b|\bfalse\b|\bnull\b)|(\/\/.*|\/\*[\s\S]*?\*\/)|([{}[\],:])|(\s+)|([\s\S])/gy;
|
|
165
|
+
let m;
|
|
166
|
+
while ((m = re.exec(code))) {
|
|
167
|
+
if (m[1]) {
|
|
168
|
+
push(out, m[2] ? "property" : "string", m[1]);
|
|
169
|
+
if (m[2])
|
|
170
|
+
push(out, "punctuation", m[2]);
|
|
171
|
+
}
|
|
172
|
+
else if (m[3])
|
|
173
|
+
push(out, "number", m[3]);
|
|
174
|
+
else if (m[4])
|
|
175
|
+
push(out, "constant", m[4]);
|
|
176
|
+
else if (m[5])
|
|
177
|
+
push(out, "comment", m[5]);
|
|
178
|
+
else if (m[6])
|
|
179
|
+
push(out, "punctuation", m[6]);
|
|
180
|
+
else
|
|
181
|
+
push(out, "plain", m[7] ?? m[8]);
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
function tokenizeMarkup(code, out) {
|
|
185
|
+
let i = 0;
|
|
186
|
+
while (i < code.length) {
|
|
187
|
+
if (code.startsWith("<!--", i)) {
|
|
188
|
+
const end = code.indexOf("-->", i + 4);
|
|
189
|
+
const stop = end < 0 ? code.length : end + 3;
|
|
190
|
+
push(out, "comment", code.slice(i, stop));
|
|
191
|
+
i = stop;
|
|
192
|
+
}
|
|
193
|
+
else if (/^<!\[CDATA\[/.test(code.slice(i, i + 9))) {
|
|
194
|
+
const end = code.indexOf("]]>", i);
|
|
195
|
+
const stop = end < 0 ? code.length : end + 3;
|
|
196
|
+
push(out, "string", code.slice(i, stop));
|
|
197
|
+
i = stop;
|
|
198
|
+
}
|
|
199
|
+
else if (code[i] === "<" && /[A-Za-z/!?]/.test(code[i + 1] ?? "")) {
|
|
200
|
+
const open = /^<(\/?)([!?]?[A-Za-z][\w:.-]*|[!?])/.exec(code.slice(i, i + 80));
|
|
201
|
+
if (!open) {
|
|
202
|
+
push(out, "plain", code[i]);
|
|
203
|
+
i++;
|
|
204
|
+
continue;
|
|
205
|
+
}
|
|
206
|
+
push(out, "punctuation", "<" + open[1]);
|
|
207
|
+
push(out, "tag", open[2]);
|
|
208
|
+
i += open[0].length;
|
|
209
|
+
// atributos ate o fecha-tag
|
|
210
|
+
const attr = /\s*(?:([A-Za-z_:@#.][\w:.@#-]*)(\s*=\s*)?("[^"]*"?|'[^']*'?|[^\s"'<>=`]+)?|(\/?>)|([\s\S]))/y;
|
|
211
|
+
let closed = false;
|
|
212
|
+
while (i < code.length && !closed) {
|
|
213
|
+
attr.lastIndex = i;
|
|
214
|
+
const a = attr.exec(code);
|
|
215
|
+
if (!a || a[0].length === 0)
|
|
216
|
+
break;
|
|
217
|
+
if (a[0].trim() === "") {
|
|
218
|
+
push(out, "plain", a[0]);
|
|
219
|
+
}
|
|
220
|
+
else {
|
|
221
|
+
const lead = a[0].match(/^\s*/)[0];
|
|
222
|
+
push(out, "plain", lead);
|
|
223
|
+
if (a[1]) {
|
|
224
|
+
push(out, "attr", a[1]);
|
|
225
|
+
if (a[2])
|
|
226
|
+
push(out, "operator", a[2]);
|
|
227
|
+
if (a[3])
|
|
228
|
+
push(out, "string", a[3]);
|
|
229
|
+
}
|
|
230
|
+
else if (a[4]) {
|
|
231
|
+
push(out, "punctuation", a[4]);
|
|
232
|
+
closed = true;
|
|
233
|
+
}
|
|
234
|
+
else if (a[5])
|
|
235
|
+
push(out, "plain", a[5].trim());
|
|
236
|
+
}
|
|
237
|
+
i += a[0].length;
|
|
238
|
+
}
|
|
239
|
+
const name = open[2].toLowerCase();
|
|
240
|
+
if (closed && !open[1] && (name === "script" || name === "style")) {
|
|
241
|
+
const end = code.toLowerCase().indexOf("</" + name, i);
|
|
242
|
+
const stop = end < 0 ? code.length : end;
|
|
243
|
+
const body = code.slice(i, stop);
|
|
244
|
+
if (name === "script")
|
|
245
|
+
scan(body, "javascript", out);
|
|
246
|
+
else
|
|
247
|
+
tokenizeCss(body, out);
|
|
248
|
+
i = stop;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
else if (code[i] === "&") {
|
|
252
|
+
const e = /^&#?\w+;/.exec(code.slice(i, i + 12));
|
|
253
|
+
if (e) {
|
|
254
|
+
push(out, "constant", e[0]);
|
|
255
|
+
i += e[0].length;
|
|
256
|
+
}
|
|
257
|
+
else {
|
|
258
|
+
push(out, "plain", "&");
|
|
259
|
+
i++;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
else {
|
|
263
|
+
let j = i + 1;
|
|
264
|
+
while (j < code.length && code[j] !== "<" && code[j] !== "&")
|
|
265
|
+
j++;
|
|
266
|
+
push(out, "plain", code.slice(i, j));
|
|
267
|
+
i = j;
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
const CSS_RE = /(\/\*[\s\S]*?(?:\*\/|$))|("(?:\\.|[^"\\\n])*"?|'(?:\\.|[^'\\\n])*'?)|(@[\w-]+)|(#[0-9a-fA-F]{3,8}\b)|(-?(?:\d+\.?\d*|\.\d+)(?:%|[a-zA-Z]{1,4})?)|([A-Za-z_-][\w-]*)(?=\s*\()|(--[\w-]+)|(!important)|([A-Za-z-]+)(?=\s*:(?!:))|([{}();,>+~*=[\]])|(\s+)|([\s\S])/gy;
|
|
272
|
+
function tokenizeCss(code, out, scss = false) {
|
|
273
|
+
CSS_RE.lastIndex = 0;
|
|
274
|
+
let m;
|
|
275
|
+
let depth = 0;
|
|
276
|
+
while ((m = CSS_RE.exec(code))) {
|
|
277
|
+
if (m[1])
|
|
278
|
+
push(out, "comment", m[1]);
|
|
279
|
+
else if (m[2])
|
|
280
|
+
push(out, "string", m[2]);
|
|
281
|
+
else if (m[3])
|
|
282
|
+
push(out, "keyword", m[3]);
|
|
283
|
+
else if (m[4])
|
|
284
|
+
push(out, "number", m[4]);
|
|
285
|
+
else if (m[5])
|
|
286
|
+
push(out, "number", m[5]);
|
|
287
|
+
else if (m[6])
|
|
288
|
+
push(out, "function", m[6]);
|
|
289
|
+
else if (m[7])
|
|
290
|
+
push(out, "variable", m[7]);
|
|
291
|
+
else if (m[8])
|
|
292
|
+
push(out, "keyword", m[8]);
|
|
293
|
+
else if (m[9])
|
|
294
|
+
push(out, depth > 0 ? "property" : "tag", m[9]);
|
|
295
|
+
else if (m[10]) {
|
|
296
|
+
if (m[10] === "{")
|
|
297
|
+
depth++;
|
|
298
|
+
else if (m[10] === "}")
|
|
299
|
+
depth = Math.max(0, depth - 1);
|
|
300
|
+
push(out, "punctuation", m[10]);
|
|
301
|
+
}
|
|
302
|
+
else if (m[11])
|
|
303
|
+
push(out, "plain", m[11]);
|
|
304
|
+
else {
|
|
305
|
+
// seletores fora de blocos: .classe, #id, tags, :pseudo
|
|
306
|
+
const rest = m[12];
|
|
307
|
+
if (scss && rest === "$")
|
|
308
|
+
push(out, "variable", rest);
|
|
309
|
+
else if (depth === 0 && /[.:&#]/.test(rest)) {
|
|
310
|
+
const w = /[\w-]*/y;
|
|
311
|
+
w.lastIndex = CSS_RE.lastIndex;
|
|
312
|
+
const word = w.exec(code)[0];
|
|
313
|
+
CSS_RE.lastIndex += word.length;
|
|
314
|
+
push(out, "tag", rest + word);
|
|
315
|
+
}
|
|
316
|
+
else
|
|
317
|
+
push(out, "plain", rest);
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
function tokenizeLines(code, out, rules) {
|
|
322
|
+
const lines = code.split("\n");
|
|
323
|
+
lines.forEach((line, i) => {
|
|
324
|
+
for (const t of rules(line))
|
|
325
|
+
push(out, t.type, t.text);
|
|
326
|
+
if (i < lines.length - 1)
|
|
327
|
+
push(out, "plain", "\n");
|
|
328
|
+
});
|
|
329
|
+
}
|
|
330
|
+
function tokenizeYamlLike(code, out, mode) {
|
|
331
|
+
tokenizeLines(code, out, (line) => {
|
|
332
|
+
const r = [];
|
|
333
|
+
const comment = mode === "ini" ? /^(\s*[;#].*)$/ : /^(\s*#.*)$/;
|
|
334
|
+
let m = comment.exec(line);
|
|
335
|
+
if (m)
|
|
336
|
+
return [{ type: "comment", text: m[1] }];
|
|
337
|
+
if (mode !== "yaml") {
|
|
338
|
+
m = /^(\s*)(\[\[?)([^\]\n]*)(\]\]?)(.*)$/.exec(line);
|
|
339
|
+
if (m)
|
|
340
|
+
return [{ type: "plain", text: m[1] }, { type: "punctuation", text: m[2] }, { type: "tag", text: m[3] }, { type: "punctuation", text: m[4] }, { type: "comment", text: m[5] }];
|
|
341
|
+
}
|
|
342
|
+
m = (mode === "yaml" ? /^(\s*(?:-\s+)*)([^\s#:'"][^:#]*?|"[^"]*"|'[^']*')(\s*:)(?=\s|$)(.*)$/ : /^(\s*)([^\s=#;][^=]*?)(\s*=)(.*)$/).exec(line);
|
|
343
|
+
let rest = line;
|
|
344
|
+
if (m) {
|
|
345
|
+
r.push({ type: "plain", text: m[1] }, { type: "property", text: m[2] }, { type: "punctuation", text: m[3] });
|
|
346
|
+
rest = m[4];
|
|
347
|
+
}
|
|
348
|
+
else {
|
|
349
|
+
const d = /^(\s*-\s+)(.*)$/.exec(line);
|
|
350
|
+
if (d) {
|
|
351
|
+
r.push({ type: "punctuation", text: d[1] });
|
|
352
|
+
rest = d[2];
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
const v = /^(\s*)(.*?)(\s+#.*)?$/.exec(rest);
|
|
356
|
+
if (!v)
|
|
357
|
+
return [...r, { type: "plain", text: rest }];
|
|
358
|
+
r.push({ type: "plain", text: v[1] });
|
|
359
|
+
const val = v[2];
|
|
360
|
+
let t = "plain";
|
|
361
|
+
if (/^("|')/.test(val))
|
|
362
|
+
t = "string";
|
|
363
|
+
else if (/^(true|false|null|~|yes|no|on|off)$/i.test(val))
|
|
364
|
+
t = "constant";
|
|
365
|
+
else if (/^[-+]?(\d[\d_]*\.?\d*|\.\d+)([eE][+-]?\d+)?$/.test(val) || /^0x[0-9a-f]+$/i.test(val))
|
|
366
|
+
t = "number";
|
|
367
|
+
else if (/^[&*!][\w-]+/.test(val))
|
|
368
|
+
t = "meta";
|
|
369
|
+
else if (/^[|>][+-]?$/.test(val))
|
|
370
|
+
t = "punctuation";
|
|
371
|
+
else if (m && mode !== "yaml" && val)
|
|
372
|
+
t = "string";
|
|
373
|
+
r.push({ type: t, text: val });
|
|
374
|
+
if (v[3])
|
|
375
|
+
r.push({ type: "comment", text: v[3] });
|
|
376
|
+
return r;
|
|
377
|
+
});
|
|
378
|
+
}
|
|
379
|
+
function tokenizeMarkdown(code, out) {
|
|
380
|
+
let fence = null;
|
|
381
|
+
const lines = code.split("\n");
|
|
382
|
+
lines.forEach((line, i) => {
|
|
383
|
+
const nl = i < lines.length - 1 ? "\n" : "";
|
|
384
|
+
const f = /^(\s*)(```+|~~~+)(.*)$/.exec(line);
|
|
385
|
+
if (f) {
|
|
386
|
+
fence = fence ? null : f[2];
|
|
387
|
+
push(out, "meta", line + nl);
|
|
388
|
+
}
|
|
389
|
+
else if (fence)
|
|
390
|
+
push(out, "string", line + nl);
|
|
391
|
+
else if (/^#{1,6}\s/.test(line))
|
|
392
|
+
push(out, "heading", line + nl);
|
|
393
|
+
else if (/^\s*>/.test(line))
|
|
394
|
+
push(out, "comment", line + nl);
|
|
395
|
+
else if (/^\s*([-*+]|\d+[.)])\s/.test(line)) {
|
|
396
|
+
const m = /^(\s*(?:[-*+]|\d+[.)])\s)(.*)$/.exec(line);
|
|
397
|
+
push(out, "punctuation", m[1]);
|
|
398
|
+
inlineMd(m[2] + nl, out);
|
|
399
|
+
}
|
|
400
|
+
else if (/^\s*(---+|\*\*\*+|___+)\s*$/.test(line))
|
|
401
|
+
push(out, "punctuation", line + nl);
|
|
402
|
+
else
|
|
403
|
+
inlineMd(line + nl, out);
|
|
404
|
+
});
|
|
405
|
+
}
|
|
406
|
+
function inlineMd(text, out) {
|
|
407
|
+
const re = /(`[^`\n]+`)|(\*\*[^*\n]+\*\*|__[^_\n]+__)|(\[[^\]\n]*\]\([^)\n]*\))|(\*[^*\n]+\*|_[^_\n]+_)|([\s\S])/gy;
|
|
408
|
+
let m;
|
|
409
|
+
while ((m = re.exec(text))) {
|
|
410
|
+
if (m[1])
|
|
411
|
+
push(out, "string", m[1]);
|
|
412
|
+
else if (m[2])
|
|
413
|
+
push(out, "keyword", m[2]);
|
|
414
|
+
else if (m[3])
|
|
415
|
+
push(out, "function", m[3]);
|
|
416
|
+
else if (m[4])
|
|
417
|
+
push(out, "type", m[4]);
|
|
418
|
+
else
|
|
419
|
+
push(out, "plain", m[5]);
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
function tokenizeDiff(code, out) {
|
|
423
|
+
const lines = code.split("\n");
|
|
424
|
+
lines.forEach((line, i) => {
|
|
425
|
+
const nl = i < lines.length - 1 ? "\n" : "";
|
|
426
|
+
if (/^(diff |index |--- |\+\+\+ )/.test(line))
|
|
427
|
+
push(out, "meta", line + nl);
|
|
428
|
+
else if (line.startsWith("@@"))
|
|
429
|
+
push(out, "heading", line + nl);
|
|
430
|
+
else if (line.startsWith("+"))
|
|
431
|
+
push(out, "inserted", line + nl);
|
|
432
|
+
else if (line.startsWith("-"))
|
|
433
|
+
push(out, "deleted", line + nl);
|
|
434
|
+
else
|
|
435
|
+
push(out, "plain", line + nl);
|
|
436
|
+
});
|
|
437
|
+
}
|
|
438
|
+
function tokenizeDockerfile(code, out) {
|
|
439
|
+
tokenizeLines(code, out, (line) => {
|
|
440
|
+
const m = /^(\s*)(FROM|RUN|CMD|LABEL|MAINTAINER|EXPOSE|ENV|ADD|COPY|ENTRYPOINT|VOLUME|USER|WORKDIR|ARG|ONBUILD|STOPSIGNAL|HEALTHCHECK|SHELL)\b(.*)$/i.exec(line);
|
|
441
|
+
if (/^\s*#/.test(line))
|
|
442
|
+
return [{ type: "comment", text: line }];
|
|
443
|
+
if (!m)
|
|
444
|
+
return [{ type: "plain", text: line }];
|
|
445
|
+
const rest = [];
|
|
446
|
+
for (const part of m[3].split(/(\$\{?\w+\}?|"[^"]*"|'[^']*')/)) {
|
|
447
|
+
if (!part)
|
|
448
|
+
continue;
|
|
449
|
+
rest.push({ type: /^\$/.test(part) ? "variable" : /^["']/.test(part) ? "string" : "plain", text: part });
|
|
450
|
+
}
|
|
451
|
+
return [{ type: "plain", text: m[1] }, { type: "keyword", text: m[2] }, ...rest];
|
|
452
|
+
});
|
|
453
|
+
}
|
|
454
|
+
function tokenizeMakefile(code, out) {
|
|
455
|
+
tokenizeLines(code, out, (line) => {
|
|
456
|
+
if (/^\s*#/.test(line))
|
|
457
|
+
return [{ type: "comment", text: line }];
|
|
458
|
+
let m = /^([A-Za-z_.][\w.-]*)(\s*[:+?]?=)(.*)$/.exec(line);
|
|
459
|
+
if (m)
|
|
460
|
+
return [{ type: "variable", text: m[1] }, { type: "operator", text: m[2] }, { type: "plain", text: m[3] }];
|
|
461
|
+
m = /^([^\s:#=][^:#=]*)(:)(?!=)(.*)$/.exec(line);
|
|
462
|
+
if (m)
|
|
463
|
+
return [{ type: "function", text: m[1] }, { type: "punctuation", text: m[2] }, { type: "plain", text: m[3] }];
|
|
464
|
+
m = /^(\s*)(ifn?eq|ifn?def|else|endif|include|-include|define|endef|export)\b(.*)$/.exec(line);
|
|
465
|
+
if (m)
|
|
466
|
+
return [{ type: "plain", text: m[1] }, { type: "keyword", text: m[2] }, { type: "plain", text: m[3] }];
|
|
467
|
+
return [{ type: "plain", text: line }];
|
|
468
|
+
});
|
|
469
|
+
}
|
|
470
|
+
/** Tokeniza o texto inteiro. A concatenacao dos tokens sempre reproduz exatamente a entrada. */
|
|
471
|
+
export function tokenize(code, lang) {
|
|
472
|
+
const id = (DEFS[lang] || ["json", "html", "xml", "css", "scss", "less", "yaml", "toml", "ini", "markdown", "dockerfile", "makefile", "diff", "plaintext", "batch", "shell"].includes(lang) ? lang : resolveLanguage(lang));
|
|
473
|
+
const text = code.replace(/\r\n?/g, "\n");
|
|
474
|
+
const out = [];
|
|
475
|
+
switch (id) {
|
|
476
|
+
case "plaintext":
|
|
477
|
+
return text ? [{ type: "plain", text }] : [];
|
|
478
|
+
case "json":
|
|
479
|
+
tokenizeJson(text, out);
|
|
480
|
+
break;
|
|
481
|
+
case "html":
|
|
482
|
+
case "xml":
|
|
483
|
+
tokenizeMarkup(text, out);
|
|
484
|
+
break;
|
|
485
|
+
case "css":
|
|
486
|
+
case "less":
|
|
487
|
+
tokenizeCss(text, out);
|
|
488
|
+
break;
|
|
489
|
+
case "scss":
|
|
490
|
+
tokenizeCss(text, out, true);
|
|
491
|
+
break;
|
|
492
|
+
case "yaml":
|
|
493
|
+
case "toml":
|
|
494
|
+
case "ini":
|
|
495
|
+
tokenizeYamlLike(text, out, id);
|
|
496
|
+
break;
|
|
497
|
+
case "markdown":
|
|
498
|
+
tokenizeMarkdown(text, out);
|
|
499
|
+
break;
|
|
500
|
+
case "diff":
|
|
501
|
+
tokenizeDiff(text, out);
|
|
502
|
+
break;
|
|
503
|
+
case "dockerfile":
|
|
504
|
+
tokenizeDockerfile(text, out);
|
|
505
|
+
break;
|
|
506
|
+
case "makefile":
|
|
507
|
+
tokenizeMakefile(text, out);
|
|
508
|
+
break;
|
|
509
|
+
default:
|
|
510
|
+
if (DEFS[id])
|
|
511
|
+
scan(text, id, out);
|
|
512
|
+
else
|
|
513
|
+
return text ? [{ type: "plain", text }] : [];
|
|
514
|
+
}
|
|
515
|
+
return out;
|
|
516
|
+
}
|
|
517
|
+
/** Divide os tokens por linha (sem o "\n"), preservando tokens que atravessam linhas (comentarios de bloco, strings). */
|
|
518
|
+
export function tokenizeLinesOf(code, lang) {
|
|
519
|
+
const lines = [[]];
|
|
520
|
+
for (const t of tokenize(code, lang)) {
|
|
521
|
+
const parts = t.text.split("\n");
|
|
522
|
+
parts.forEach((p, i) => {
|
|
523
|
+
if (i > 0)
|
|
524
|
+
lines.push([]);
|
|
525
|
+
if (p)
|
|
526
|
+
lines[lines.length - 1].push({ type: t.type, text: p });
|
|
527
|
+
});
|
|
528
|
+
}
|
|
529
|
+
return lines;
|
|
530
|
+
}
|
|
531
|
+
const HTML_ESC = { "&": "&", "<": "<", ">": ">", '"': """ };
|
|
532
|
+
/** HTML com <span class="lt-<tipo">; as cores vem do CSS (ver --code-* nos tokens). */
|
|
533
|
+
export function highlightToHtml(code, lang) {
|
|
534
|
+
return tokenize(code, lang)
|
|
535
|
+
.map((t) => {
|
|
536
|
+
const text = t.text.replace(/[&<>"]/g, (c) => HTML_ESC[c]);
|
|
537
|
+
return t.type === "plain" ? text : `<span class="lt-${t.type}">${text}</span>`;
|
|
538
|
+
})
|
|
539
|
+
.join("");
|
|
540
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@loccal/ui",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Loccal UI: biblioteca de componentes React com Tailwind 4, custom elements e CSS para web e desktop.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Marcelo Matzembacher",
|
|
@@ -179,6 +179,11 @@
|
|
|
179
179
|
"import": "./dist/components/ui/checkbox.js",
|
|
180
180
|
"default": "./dist/components/ui/checkbox.js"
|
|
181
181
|
},
|
|
182
|
+
"./code-view": {
|
|
183
|
+
"types": "./dist/components/ui/code-view.d.ts",
|
|
184
|
+
"import": "./dist/components/ui/code-view.js",
|
|
185
|
+
"default": "./dist/components/ui/code-view.js"
|
|
186
|
+
},
|
|
182
187
|
"./collapsible": {
|
|
183
188
|
"types": "./dist/components/ui/collapsible.d.ts",
|
|
184
189
|
"import": "./dist/components/ui/collapsible.js",
|
|
@@ -244,6 +249,11 @@
|
|
|
244
249
|
"import": "./dist/components/ui/file-tree.js",
|
|
245
250
|
"default": "./dist/components/ui/file-tree.js"
|
|
246
251
|
},
|
|
252
|
+
"./file-type-icon": {
|
|
253
|
+
"types": "./dist/components/ui/file-type-icon.d.ts",
|
|
254
|
+
"import": "./dist/components/ui/file-type-icon.js",
|
|
255
|
+
"default": "./dist/components/ui/file-type-icon.js"
|
|
256
|
+
},
|
|
247
257
|
"./hash-chain": {
|
|
248
258
|
"types": "./dist/components/ui/hash-chain.d.ts",
|
|
249
259
|
"import": "./dist/components/ui/hash-chain.js",
|
|
@@ -509,6 +519,11 @@
|
|
|
509
519
|
"import": "./dist/lib/command-risk.js",
|
|
510
520
|
"default": "./dist/lib/command-risk.js"
|
|
511
521
|
},
|
|
522
|
+
"./lib/file-icons": {
|
|
523
|
+
"types": "./dist/lib/file-icons.d.ts",
|
|
524
|
+
"import": "./dist/lib/file-icons.js",
|
|
525
|
+
"default": "./dist/lib/file-icons.js"
|
|
526
|
+
},
|
|
512
527
|
"./lib/file-kind": {
|
|
513
528
|
"types": "./dist/lib/file-kind.d.ts",
|
|
514
529
|
"import": "./dist/lib/file-kind.js",
|
|
@@ -564,6 +579,11 @@
|
|
|
564
579
|
"import": "./dist/lib/shell-meta.js",
|
|
565
580
|
"default": "./dist/lib/shell-meta.js"
|
|
566
581
|
},
|
|
582
|
+
"./lib/syntax": {
|
|
583
|
+
"types": "./dist/lib/syntax.d.ts",
|
|
584
|
+
"import": "./dist/lib/syntax.js",
|
|
585
|
+
"default": "./dist/lib/syntax.js"
|
|
586
|
+
},
|
|
567
587
|
"./lib/tab-order": {
|
|
568
588
|
"types": "./dist/lib/tab-order.d.ts",
|
|
569
589
|
"import": "./dist/lib/tab-order.js",
|
package/styles.css
CHANGED
|
@@ -424,3 +424,53 @@
|
|
|
424
424
|
radial-gradient(farthest-side at 100% 50%, color-mix(in oklch, var(--foreground) 16%, transparent), transparent) right / 10px 100% no-repeat scroll;
|
|
425
425
|
background-color: var(--scroll-bg);
|
|
426
426
|
}
|
|
427
|
+
|
|
428
|
+
/* Realce de sintaxe do CodeView (ver components/ui/code-view.tsx). Cores calibradas para os dois temas. */
|
|
429
|
+
[data-slot="code-view"] {
|
|
430
|
+
--code-keyword: oklch(0.52 0.2 300);
|
|
431
|
+
--code-string: oklch(0.5 0.14 150);
|
|
432
|
+
--code-comment: oklch(0.55 0.02 260);
|
|
433
|
+
--code-number: oklch(0.55 0.16 50);
|
|
434
|
+
--code-function: oklch(0.5 0.15 250);
|
|
435
|
+
--code-type: oklch(0.52 0.13 200);
|
|
436
|
+
--code-constant: oklch(0.55 0.17 30);
|
|
437
|
+
--code-tag: oklch(0.52 0.19 20);
|
|
438
|
+
--code-attr: oklch(0.55 0.15 70);
|
|
439
|
+
--code-property: oklch(0.5 0.14 240);
|
|
440
|
+
--code-variable: oklch(0.52 0.15 330);
|
|
441
|
+
--code-meta: oklch(0.55 0.1 280);
|
|
442
|
+
--code-inserted: oklch(0.5 0.15 150);
|
|
443
|
+
--code-deleted: oklch(0.55 0.2 25);
|
|
444
|
+
}
|
|
445
|
+
.dark [data-slot="code-view"] {
|
|
446
|
+
--code-keyword: oklch(0.72 0.2 305);
|
|
447
|
+
--code-string: oklch(0.78 0.16 150);
|
|
448
|
+
--code-comment: oklch(0.62 0.03 260);
|
|
449
|
+
--code-number: oklch(0.8 0.16 65);
|
|
450
|
+
--code-function: oklch(0.76 0.15 245);
|
|
451
|
+
--code-type: oklch(0.78 0.13 195);
|
|
452
|
+
--code-constant: oklch(0.76 0.17 35);
|
|
453
|
+
--code-tag: oklch(0.72 0.19 15);
|
|
454
|
+
--code-attr: oklch(0.8 0.15 75);
|
|
455
|
+
--code-property: oklch(0.76 0.13 235);
|
|
456
|
+
--code-variable: oklch(0.75 0.16 335);
|
|
457
|
+
--code-meta: oklch(0.7 0.1 285);
|
|
458
|
+
--code-inserted: oklch(0.78 0.16 150);
|
|
459
|
+
--code-deleted: oklch(0.72 0.19 25);
|
|
460
|
+
}
|
|
461
|
+
[data-slot="code-view"] [data-t="keyword"] { color: var(--code-keyword); }
|
|
462
|
+
[data-slot="code-view"] [data-t="string"] { color: var(--code-string); }
|
|
463
|
+
[data-slot="code-view"] [data-t="comment"] { color: var(--code-comment); font-style: italic; }
|
|
464
|
+
[data-slot="code-view"] [data-t="number"] { color: var(--code-number); }
|
|
465
|
+
[data-slot="code-view"] [data-t="function"] { color: var(--code-function); }
|
|
466
|
+
[data-slot="code-view"] [data-t="type"] { color: var(--code-type); }
|
|
467
|
+
[data-slot="code-view"] [data-t="constant"] { color: var(--code-constant); }
|
|
468
|
+
[data-slot="code-view"] [data-t="tag"] { color: var(--code-tag); }
|
|
469
|
+
[data-slot="code-view"] [data-t="attr"] { color: var(--code-attr); }
|
|
470
|
+
[data-slot="code-view"] [data-t="property"] { color: var(--code-property); }
|
|
471
|
+
[data-slot="code-view"] [data-t="variable"] { color: var(--code-variable); }
|
|
472
|
+
[data-slot="code-view"] [data-t="meta"] { color: var(--code-meta); }
|
|
473
|
+
[data-slot="code-view"] [data-t="heading"] { color: var(--code-function); font-weight: 600; }
|
|
474
|
+
[data-slot="code-view"] [data-t="inserted"] { color: var(--code-inserted); }
|
|
475
|
+
[data-slot="code-view"] [data-t="deleted"] { color: var(--code-deleted); }
|
|
476
|
+
[data-slot="code-view"] [data-t="operator"], [data-slot="code-view"] [data-t="punctuation"] { color: color-mix(in oklch, var(--foreground) 72%, transparent); }
|