athena-ui-js 2.3.0 → 2.4.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/README.md CHANGED
@@ -5,7 +5,7 @@ layout (header, menu, content wrapper, footer) from a single `init()` call, load
5
5
  and theme, and ships the building blocks of a multipurpose application: forms, tables, charts,
6
6
  feedback, navigation, a router and more.
7
7
 
8
- Current version: **2.3.0**
8
+ Current version: **2.4.0**
9
9
 
10
10
  [Quick start](#usage) · [API](#api) · [Components](#charts) · [Themes](#themes) · [Tests](#tests) · [Release notes](#releases)
11
11
 
@@ -67,7 +67,7 @@ import { generateTable } from "athena-ui-js/table"; // or only what you u
67
67
  ```
68
68
 
69
69
  The entry points are `table`, `chart`, `dialog`, `menu`, `navigation`, `forms`, `feedback`, `components`, `inputs`, `router`, `session`, `theme`, `i18n`, `format`,
70
- `validation`, `motion`, `widgets`, `sanitize`, `csv`, `dom` and `controls`. TypeScript definitions are included (`types/`, generated from the JSDoc with `npm run types`).
70
+ `validation`, `motion`, `widgets`, `code`, `sanitize`, `csv`, `dom` and `controls`. TypeScript definitions are included (`types/`, generated from the JSDoc with `npm run types`).
71
71
  The package has `"sideEffects"` for `classic.js`, `theme-boot.js` and CSS only, so a bundler drops everything you do not import.
72
72
 
73
73
  Without npm, serve the `src` folder with any static web server and open `index.html` to see the example.
@@ -149,7 +149,7 @@ It takes the options of `init()`. The header and footer follow the settings `gen
149
149
  | `header_title_text` | `"Athena UI"` | Title in the header |
150
150
  | `header_img_url` | | Header logo URL |
151
151
  | `copyright` | placeholder text | Footer text, the version is appended |
152
- | `version` | `"2.3.0"` | Version shown in the footer |
152
+ | `version` | `"2.4.0"` | Version shown in the footer |
153
153
  | `bordered` | `true` | Draw a border around the layout blocks |
154
154
  | `generateHeader`, `generateFooter` | `true` | Generate the header / footer block |
155
155
  | `generateHeadercontent`, `generateFooterContent`, `generateWrappercontent` | `true` | Generate the content of the block |
@@ -196,6 +196,7 @@ Everything is exported from `athena-ui.js`:
196
196
  | `el`, `setContent`, `resolveElement`, `asHandle`, `createSafeBuilder` | See [Safe DOM building](#safe-dom-building) |
197
197
  | `animate`, `flip`, `stagger`, `spring`, `tween`, `transition`, `viewTransition`, `setMotion`, `prefersReducedMotion`, `easings`, `generateSkeleton` | See [Motion](#motion-animations-and-transitions) |
198
198
  | `registerWidget`, `createWidgetGrid`, `getWidgetTypes`, `placeItem`, `compact`, `findFreeSpot`, `normalize` | See [Widgets](#widgets-a-dashboard-that-can-be-built) |
199
+ | `highlightCode`, `generateCodeBlock`, `createCodeEditor`, `createDiffView`, `registerLanguage`, `tokenize`, `diffLines` | See [Code](#code-highlighting-an-editor-and-a-diff) |
199
200
  | `generateCard`, `generateSection`, `generateGrid`, `generateBadge`, `generateAvatar`, `generateStat`, `generateLink`, `generateTooltip` | See [Components](#components) |
200
201
  | `generateAutocomplete`, `generateMultiSelect`, `generateFileUpload`, `generateDropZone`, `generateStepper`, `generateDateRange`, `generateRichText`, `generateWysiwyg` | See [Inputs](#inputs) |
201
202
  | `sanitizeHtml(html)`, `htmlToText(html)`, `isSafeUrl(url)` | The allow-list sanitizer behind the rich text editor |
@@ -736,6 +737,42 @@ grid.setLayout(JSON.parse(localStorage.getItem("dashboard"))); // plain, ver
736
737
  - **Performance**: a widget is rendered only when it is first seen, `resize(context, size)` is called throttled when its body changes size, and nothing re-renders while it is out of view.
737
738
  - The grid maths (`placeItem`, `compact`, `findFreeSpot`, `normalize`, `collides`) is exported as well, for your own layouts.
738
739
 
740
+ ### Code: highlighting, an editor and a diff
741
+
742
+ `athena-ui-js/code`: no dependency, no inline style, and nothing is parsed as markup (the code is built with `el()`, so a `<img onerror>` in a comment stays text).
743
+
744
+ ```js
745
+ import { highlightCode, generateCodeBlock, createCodeEditor, createDiffView, registerLanguage } from "athena-ui-js/code";
746
+
747
+ // read only
748
+ document.body.append(highlightCode("const a = 1;", "js", { lineNumbers: true, highlightLines: [1] })); // a <pre><code> with token spans
749
+ generateCodeBlock({ parent: "docs", code: sql, language: "sql", lineNumbers: true }); // + the language label and a copy button
750
+
751
+ // an editor
752
+ const editor = createCodeEditor({
753
+ element: "editor", value: source, language: "ts", onChange: value => save(value),
754
+ markers: [{ line: 3, message: "Unexpected token", level: "error" }], // lint markers, shown in the status line
755
+ readOnlyRanges: [{ from: 1, to: 2 }], // lines that cannot be changed
756
+ provideCompletions: ({ prefix }) => words.filter(word => word.startsWith(prefix)).map(label => ({ label }))
757
+ });
758
+
759
+ // what changed
760
+ createDiffView({ parent: "review", original: before, modified: after, language: "json", mode: "split", context: 3 });
761
+ ```
762
+
763
+ - **Languages**: `javascript` (`js`), `typescript` (`ts`), `json`, `html` (`xml`, `svg`), `css` (`scss`, `less`), `sql`, `shell` (`sh`, `bash`), `yaml`, `csharp` (`c#`, `cs`), `python` (`py`).
764
+ A language is a plain object (`registerLanguage({ name, aliases, rules: [{ type, pattern }], lineComment, blockComment, pairs, indentAfter })`), so your own are one call.
765
+ The tokenizer is a set of regular expressions, not a parser: it is fast and tolerant (unfinished code still gets colours) but it does not know nested `${}` of a template string or the `<script>` inside HTML.
766
+ - **Colours** are the tokens `--athena-tok-comment`, `-string`, `-keyword` ... (light and dark); a test keeps every one at 4.5:1 contrast or more.
767
+ - **The editor is a real `<textarea>`** with the highlighted text behind it, so native input, selection, spell-check off, mobile keyboards, IME and screen readers all work.
768
+ Tab and Shift+Tab indent and outdent (also several lines), Enter keeps the indentation (and goes one level deeper after `{`, `(`, `:`), brackets and quotes are closed, stepped over, wrapped around a selection and
769
+ deleted together, Ctrl+/ comments, Alt+Up / Alt+Down move lines, Ctrl+Z / Ctrl+Y undo and redo (typing is grouped), Ctrl+F finds and Ctrl+H replaces (case, regular expression, all matches
770
+ highlighted, replace all is one undo step), Ctrl+Space suggests. The matching bracket is highlighted (CSS Custom Highlight API where the browser has it).
771
+ **Escape, then Tab, leaves the editor** (so the keyboard is never trapped); the way out is read to screen readers.
772
+ - **Size**: only the lines around a change are tokenized again, and a test checks that this gives exactly what tokenizing everything gives. On the (slow) development machine the work of the editor per key press is
773
+ about 13 ms in a 5,000 line file; the browser's own layout of two large text blocks is the larger part (about 90 ms per key at 5,000 lines; smaller files were not measured separately). Texts longer than 300,000 characters
774
+ (`maxHighlightLength`) are shown without highlighting. Not there yet: multiple cursors, minimap, folding.
775
+
739
776
  ### Safe DOM building
740
777
 
741
778
  `el(tag, { class, id, text, attrs, on, prop }, ...children)` is the way Athena builds its own pages, and it is exported. Strings are only ever inserted as **text**, children can be
package/docs/styling.md CHANGED
@@ -28,6 +28,23 @@ Start with the tokens, they cover most of what people want to change.
28
28
  | `--athena-warning` | `#9a6700` |
29
29
  | `--athena-info` | `#2471a3` |
30
30
  | `--athena-shadow` | `0 4px 14px rgb(0 0 0 / 18%)` |
31
+ | `--athena-tok-comment` | `#5a6270` |
32
+ | `--athena-tok-string` | `#0b6e3a` |
33
+ | `--athena-tok-number` | `#a24b00` |
34
+ | `--athena-tok-keyword` | `#7a2a9e` |
35
+ | `--athena-tok-literal` | `#0b5fa5` |
36
+ | `--athena-tok-function` | `#1f55b0` |
37
+ | `--athena-tok-type` | `#0f6b6b` |
38
+ | `--athena-tok-property` | `#9b2c5b` |
39
+ | `--athena-tok-tag` | `#a3201f` |
40
+ | `--athena-tok-attribute` | `#8a5300` |
41
+ | `--athena-tok-variable` | `#0a6a8a` |
42
+ | `--athena-tok-selector` | `#7a2a9e` |
43
+ | `--athena-tok-meta` | `#6b4eae` |
44
+ | `--athena-tok-entity` | `#0a6a8a` |
45
+ | `--athena-tok-builtin` | `#0b5fa5` |
46
+ | `--athena-tok-operator` | `#3b4048` |
47
+ | `--athena-tok-punctuation` | `#5a6270` |
31
48
  | `--athena-radius` | `6px` |
32
49
  | `--athena-border-width` | `1px` |
33
50
  | `--athena-space-1` | `4px` |
@@ -100,4 +117,7 @@ Dark colours: set `data-mode="dark"` on `<html>` (or let `createThemeManager` do
100
117
  | A place holder for what is loading: a skeleton with a shimmer (generateSkeleton) | `.athena-skeleton` `.athena-skeleton-line` | `--athena-hover` `--athena-radius` `--athena-space-2` `--athena-surface` |
101
118
  | A theme or mode change cross-fades instead of flashing (the theme manager sets the class for a moment) | `.athena-switching` | `--athena-duration-slow` `--athena-ease-standard` |
102
119
  | Page transitions of the router (router({ transition: true })) | - | `--athena-duration-base` `--athena-ease-standard` |
103
- | Charts draw themselves when they appear: bars grow, lines are drawn, slices pop in (only the first time, not when a chart streams or is zoomed) | `.athena-chart-animated` `.athena-widget-grid` `.chart-area` `.chart-bar` `.chart-line` `.chart-point` `.chart-slice` `.is-dragging` `.is-editable` `.is-failed` `.is-locked` `.is-unknown` `.widget` `.widget-action` `.widget-actions` `.widget-body` `.widget-handle` `.widget-header` `.widget-note` `.widget-resize` `.widget-resize-e` `.widget-resize-n` `.widget-resize-ne` `.widget-resize-nw` `.widget-resize-s` `.widget-resize-se` `.widget-resize-sw` `.widget-resize-w` `.widget-title` | `--athena-accent` `--athena-accent-fg` `--athena-border` `--athena-border-width` `--athena-duration-fast` `--athena-duration-slow` `--athena-ease-out` `--athena-ease-standard` `--athena-fg` `--athena-focus` `--athena-focus-width` `--athena-hover` `--athena-line` `--athena-muted` `--athena-radius` `--athena-shadow` `--athena-surface` `--athena-surface-alt` |
120
+ | Charts draw themselves when they appear: bars grow, lines are drawn, slices pop in (only the first time, not when a chart streams or is zoomed) | `.athena-chart-animated` `.athena-code` `.athena-widget-grid` `.chart-area` `.chart-bar` `.chart-line` `.chart-point` `.chart-slice` `.code-digits-1` `.code-digits-2` `.code-digits-3` `.code-digits-4` `.code-digits-5` `.code-digits-6` `.code-digits-7` `.code-editor` `.code-editor-input` `.code-line` `.code-tab-1` `.code-tab-10` `.code-tab-11` `.code-tab-12` `.code-tab-13` `.code-tab-14` `.code-tab-15` `.code-tab-16` `.code-tab-2` `.code-tab-3` `.code-tab-4` `.code-tab-5` `.code-tab-6` `.code-tab-7` `.code-tab-8` `.code-tab-9` `.code-wrap` `.has-line-numbers` `.is-dragging` `.is-editable` `.is-failed` `.is-highlighted` `.is-locked` `.is-unknown` `.tok-attribute` `.tok-builtin` `.tok-comment` `.tok-entity` `.tok-function` `.tok-keyword` `.tok-literal` `.tok-meta` `.tok-number` `.tok-operator` `.tok-property` `.tok-punctuation` `.tok-selector` `.tok-string` `.tok-tag` `.tok-type` `.tok-variable` `.widget` `.widget-action` `.widget-actions` `.widget-body` `.widget-handle` `.widget-header` `.widget-note` `.widget-resize` `.widget-resize-e` `.widget-resize-n` `.widget-resize-ne` `.widget-resize-nw` `.widget-resize-s` `.widget-resize-se` `.widget-resize-sw` `.widget-resize-w` `.widget-title` | `--athena-accent` `--athena-accent-fg` `--athena-border` `--athena-border-width` `--athena-duration-fast` `--athena-duration-slow` `--athena-ease-out` `--athena-ease-standard` `--athena-fg` `--athena-focus` `--athena-focus-width` `--athena-hover` `--athena-line` `--athena-muted` `--athena-radius` `--athena-shadow` `--athena-surface` `--athena-surface-alt` `--athena-tok-attribute` `--athena-tok-builtin` `--athena-tok-comment` `--athena-tok-entity` `--athena-tok-function` `--athena-tok-keyword` `--athena-tok-literal` `--athena-tok-meta` `--athena-tok-number` `--athena-tok-operator` `--athena-tok-property` `--athena-tok-punctuation` `--athena-tok-selector` `--athena-tok-string` `--athena-tok-tag` `--athena-tok-type` `--athena-tok-variable` `--code-gutter` |
121
+ | A block: the language, a copy button, the code | `.athena-code` `.code-block` `.code-block-copy` `.code-block-header` `.code-find-button` `.code-find-input` | `--athena-bg` `--athena-border-width` `--athena-fg` `--athena-focus` `--athena-focus-width` `--athena-hover` `--athena-line` `--athena-muted` `--athena-radius` `--athena-surface` |
122
+ | The editor | `.code-completion` `.code-completion-detail` `.code-completions` `.code-editor` `.code-editor-highlight` `.code-editor-input` `.code-editor-scroll` `.code-editor-status` `.code-find` `.code-find-button` `.code-find-count` `.code-find-input` `.code-find-row` `.code-line` `.code-wrap` `.has-line-numbers` `.has-marker` `.is-active` `.is-current` `.is-locked-line` `.is-plain` `.is-readonly` `.marker-error` `.marker-info` `.marker-warning` | `--athena-accent` `--athena-accent-fg` `--athena-bg` `--athena-border` `--athena-border-width` `--athena-danger` `--athena-fg` `--athena-focus` `--athena-focus-width` `--athena-info` `--athena-line` `--athena-muted` `--athena-radius` `--athena-shadow` `--athena-surface` `--athena-surface-alt` `--athena-warning` `--code-completion-left` `--code-completion-top` `--code-editor-max-height` `--code-editor-min-height` `--code-gutter` |
123
+ | The diff view | `.code-diff` `.code-diff-body` `.code-diff-cell` `.code-diff-code` `.code-diff-empty` `.code-diff-header` `.code-diff-mark` `.code-diff-number` `.code-diff-row` `.code-diff-skip` `.code-diff-stat` `.code-line` `.is-added` `.is-empty` `.is-removed` `.is-skip` `.is-split` | `--athena-accent` `--athena-border-width` `--athena-danger` `--athena-line` `--athena-muted` `--athena-radius` `--athena-success` `--athena-surface` |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "athena-ui-js",
3
- "version": "2.3.0",
3
+ "version": "2.4.0",
4
4
  "description": "A small, dependency-free UI framework: forms, tables, charts, menus, dialogs, themes and a router, written as ES modules.",
5
5
  "type": "module",
6
6
  "main": "./src/athena-ui.js",
@@ -95,6 +95,10 @@
95
95
  "types": "./types/widgets.d.ts",
96
96
  "default": "./src/widgets.js"
97
97
  },
98
+ "./code": {
99
+ "types": "./types/code.d.ts",
100
+ "default": "./src/code.js"
101
+ },
98
102
  "./sanitize": {
99
103
  "types": "./types/sanitize.d.ts",
100
104
  "default": "./src/sanitize.js"
package/src/athena-ui.js CHANGED
@@ -2,7 +2,7 @@
2
2
  //Author: Csaba Tóth https://github.com/csabatibortoth/
3
3
  //LICENCE: MIT
4
4
  //Repository: https://github.com/csabatibortoth/athena-ui
5
- //Version: 2.3.0
5
+ //Version: 2.4.0
6
6
 
7
7
  // The whole API as ES module exports. There are no side effects: importing this file does not touch the page, does not load a script and does not
8
8
  // put anything on globalThis. For pages that need globals use `athena-ui-js/classic`, and to download only what you use import from the entry points
@@ -126,6 +126,10 @@ export * from "./libs/core/format.js";
126
126
  export * from "./libs/core/motion.js";
127
127
  export * from "./libs/hephaestus/widgetGrid/widgetGrid.js";
128
128
  export * from "./libs/core/gridLayout.js";
129
+ export * from "./libs/hephaestus/codeGenerator/codeGenerator.js";
130
+ export * from "./libs/hephaestus/codeGenerator/codeEditor.js";
131
+ export * from "./libs/core/codeLanguages.js";
132
+ export * from "./libs/core/codeDiff.js";
129
133
  export * from "./libs/hephaestus/modalGenerator/modalGenerator.js";
130
134
  export * from "./libs/core/theme.js";
131
135
  export * from "./libs/hephaestus/componentGenerator/themePicker.js";
package/src/code.js ADDED
@@ -0,0 +1,9 @@
1
+ //code entry of Athena UI: highlightCode, generateCodeBlock, createCodeEditor, createDiffView and the languages
2
+ //Import only what you use: `import { highlightCode, createCodeEditor } from "athena-ui-js/code"`.
3
+ //LICENCE: MIT
4
+ //Repository: https://github.com/csabatibortoth/athena-ui
5
+
6
+ export * from "./libs/hephaestus/codeGenerator/codeGenerator.js";
7
+ export * from "./libs/hephaestus/codeGenerator/codeEditor.js";
8
+ export * from "./libs/core/codeLanguages.js";
9
+ export * from "./libs/core/codeDiff.js";
@@ -6,7 +6,7 @@
6
6
  export const BORDERED_CLASS = "default-cointainer-bordered";
7
7
 
8
8
  export const defaults = Object.freeze({
9
- version: "2.3.0",
9
+ version: "2.4.0",
10
10
  container_class: "container",
11
11
  header_class: "header-container",
12
12
  header_menu_class: "header-menu menu",
@@ -0,0 +1,119 @@
1
+ //Line diff of Athena UI (no DOM): the shortest edit script between two lists of lines (Myers), after the common start and end are cut off.
2
+ //LICENCE: MIT
3
+ //Repository: https://github.com/csabatibortoth/athena-ui
4
+
5
+ /**
6
+ * @typedef {{type: "equal", a: number, b: number} | {type: "remove", a: number} | {type: "add", b: number}} DiffOp
7
+ */
8
+
9
+ /** Splits text into lines the way an editor counts them (a text that ends with a newline has a last empty line). */
10
+ export const splitLines = text => String(text ?? "").replace(/\r\n?/g, "\n").split("\n");
11
+
12
+ /**
13
+ * The difference between two lists of lines, as operations in order. `a` and `b` are indexes into the two lists.
14
+ * When the two lists differ by more than `maxEdits` lines the result is coarse (everything removed, then everything added) instead of slow.
15
+ *
16
+ * @param {string[]} oldLines
17
+ * @param {string[]} newLines
18
+ * @param {{maxEdits?: number}} [options]
19
+ * @returns {DiffOp[]}
20
+ */
21
+ export function diffLines(oldLines, newLines, { maxEdits = 3000 } = {}) {
22
+ let start = 0;
23
+ while (start < oldLines.length && start < newLines.length && oldLines[start] === newLines[start]) start++;
24
+ let endOld = oldLines.length;
25
+ let endNew = newLines.length;
26
+ while (endOld > start && endNew > start && oldLines[endOld - 1] === newLines[endNew - 1]) {
27
+ endOld--;
28
+ endNew--;
29
+ }
30
+ const ops = [];
31
+ for (let i = 0; i < start; i++) ops.push({ type: "equal", a: i, b: i });
32
+ for (const op of myers(oldLines.slice(start, endOld), newLines.slice(start, endNew), maxEdits)) {
33
+ ops.push(op.type === "equal" ? { type: "equal", a: op.a + start, b: op.b + start } : op.type === "remove" ? { type: "remove", a: op.a + start } : { type: "add", b: op.b + start });
34
+ }
35
+ for (let i = 0; i < oldLines.length - endOld; i++) ops.push({ type: "equal", a: endOld + i, b: endNew + i });
36
+ return ops;
37
+ }
38
+
39
+ function myers(A, B, maxEdits) {
40
+ const N = A.length;
41
+ const M = B.length;
42
+ if (!N || !M || N + M === 0) return [...A.map((_, a) => ({ type: "remove", a })), ...B.map((_, b) => ({ type: "add", b }))];
43
+ const max = N + M;
44
+ const offset = max + 1;
45
+ const v = new Int32Array(2 * max + 3);
46
+ const trace = [];
47
+ let found = -1;
48
+ search: for (let d = 0; d <= max; d++) {
49
+ if (d > maxEdits) return [...A.map((_, a) => ({ type: "remove", a })), ...B.map((_, b) => ({ type: "add", b }))];
50
+ trace.push(v.slice(offset - d - 1, offset + d + 2));
51
+ for (let k = -d; k <= d; k += 2) {
52
+ let x = k === -d || (k !== d && v[offset + k - 1] < v[offset + k + 1]) ? v[offset + k + 1] : v[offset + k - 1] + 1;
53
+ let y = x - k;
54
+ while (x < N && y < M && A[x] === B[y]) {
55
+ x++;
56
+ y++;
57
+ }
58
+ v[offset + k] = x;
59
+ if (x >= N && y >= M) {
60
+ found = d;
61
+ break search;
62
+ }
63
+ }
64
+ }
65
+ const ops = [];
66
+ let x = N;
67
+ let y = M;
68
+ for (let d = found; d > 0; d--) {
69
+ const before = k => trace[d][k + d + 1];
70
+ const k = x - y;
71
+ const previousK = k === -d || (k !== d && before(k - 1) < before(k + 1)) ? k + 1 : k - 1;
72
+ const previousX = before(previousK);
73
+ const previousY = previousX - previousK;
74
+ while (x > previousX && y > previousY) {
75
+ ops.push({ type: "equal", a: x - 1, b: y - 1 });
76
+ x--;
77
+ y--;
78
+ }
79
+ ops.push(x === previousX ? { type: "add", b: y - 1 } : { type: "remove", a: x - 1 });
80
+ x = previousX;
81
+ y = previousY;
82
+ }
83
+ while (x > 0 && y > 0) {
84
+ ops.push({ type: "equal", a: x - 1, b: y - 1 });
85
+ x--;
86
+ y--;
87
+ }
88
+ return ops.reverse();
89
+ }
90
+
91
+ /**
92
+ * Groups the operations into hunks that show `context` unchanged lines around each change (Infinity: everything is one hunk).
93
+ * @returns {{ops: DiffOp[], skippedBefore: number}[]} `skippedBefore` is the number of unchanged lines left out before the hunk
94
+ */
95
+ export function hunksOf(ops, context = 3) {
96
+ if (!Number.isFinite(context)) return [{ ops, skippedBefore: 0 }];
97
+ const keep = new Array(ops.length).fill(false);
98
+ ops.forEach((op, index) => {
99
+ if (op.type === "equal") return;
100
+ for (let i = Math.max(0, index - context); i <= Math.min(ops.length - 1, index + context); i++) keep[i] = true;
101
+ });
102
+ const hunks = [];
103
+ let skipped = 0;
104
+ let current = null;
105
+ ops.forEach((op, index) => {
106
+ if (!keep[index]) {
107
+ skipped++;
108
+ current = null;
109
+ return;
110
+ }
111
+ if (!current) {
112
+ current = { ops: [], skippedBefore: skipped };
113
+ hunks.push(current);
114
+ skipped = 0;
115
+ }
116
+ current.ops.push(op);
117
+ });
118
+ return hunks;
119
+ }
@@ -0,0 +1,277 @@
1
+ //Tokenizers for code highlighting (no DOM): a language is a plain object, applications add their own with registerLanguage().
2
+ //LICENCE: MIT
3
+ //Repository: https://github.com/csabatibortoth/athena-ui
4
+
5
+ /**
6
+ * A language: an ordered list of rules. The text is scanned once; at every position the first rule that matches wins.
7
+ *
8
+ * @typedef {object} CodeLanguage
9
+ * @property {string} name
10
+ * @property {string} [label] shown in the label of a code block (default: the name)
11
+ * @property {string[]} [aliases] other names ("js" for "javascript")
12
+ * @property {{type: string, pattern: RegExp, inner?: (text: string) => {type: string|null, text: string}[]}[]} rules `type` becomes the class `tok-<type>`;
13
+ * the pattern must use non-capturing groups only; `inner` splits a match into smaller tokens (a tag into name and attributes)
14
+ * @property {boolean} [ignoreCase] the rules are case-insensitive (SQL)
15
+ * @property {boolean} [multiline] ^ and $ match at every line (YAML, C# preprocessor lines)
16
+ * @property {string} [lineComment] used by the editor to comment lines ("//")
17
+ * @property {[string, string]} [blockComment]
18
+ * @property {string[]} [pairs] characters the editor closes: ["()", "[]", "{}", "\"\"", "''"]
19
+ * @property {RegExp} [indentAfter] a line that matches this makes the next line one level deeper (/[{(\[:]\s*$/)
20
+ */
21
+
22
+ const languages = new Map();
23
+ const compiled = new WeakMap();
24
+
25
+ /** Registers a language (and its aliases). */
26
+ export function registerLanguage(language) {
27
+ if (typeof language?.name !== "string" || !Array.isArray(language.rules)) throw new TypeError("Athena UI: a language needs a name and rules");
28
+ for (const rule of language.rules) {
29
+ if (typeof rule?.type !== "string" || !(rule.pattern instanceof RegExp)) throw new TypeError(`Athena UI: a rule of "${language.name}" needs a type and a pattern`);
30
+ }
31
+ for (const name of [language.name, ...(language.aliases ?? [])]) languages.set(name.toLowerCase(), language);
32
+ compiled.delete(language);
33
+ }
34
+
35
+ /** The language registered under a name or alias, or undefined. */
36
+ export const getLanguage = name => (typeof name === "string" ? languages.get(name.toLowerCase()) : name && typeof name === "object" ? name : undefined);
37
+
38
+ /** The names of the registered languages (no aliases). */
39
+ export const getLanguages = () => [...new Set(languages.values())].map(language => language.name);
40
+
41
+ function compile(language) {
42
+ if (compiled.has(language)) return compiled.get(language);
43
+ const groups = [];
44
+ let index = 1;
45
+ const sources = language.rules.map(rule => {
46
+ groups.push(index);
47
+ index += new RegExp(`${rule.pattern.source}|`).exec("").length; // the group of the rule and the groups inside it
48
+ return `(${rule.pattern.source})`;
49
+ });
50
+ const result = { groups, expression: new RegExp(sources.join("|"), `g${language.ignoreCase ? "i" : ""}${language.multiline ? "m" : ""}`) };
51
+ compiled.set(language, result);
52
+ return result;
53
+ }
54
+
55
+ const MAX_LENGTH = 3_000_000;
56
+
57
+ /**
58
+ * Splits text into tokens: [{ type, text }]. `type` is null for plain text. Concatenating the texts gives the input back.
59
+ * An unknown language, or a text that is too long, gives one plain token.
60
+ */
61
+ export function tokenize(text, language) {
62
+ const source = String(text ?? "");
63
+ const lang = getLanguage(language);
64
+ if (!lang || source.length > MAX_LENGTH) return source ? [{ type: null, text: source }] : [];
65
+ const { groups, expression } = compile(lang);
66
+ const tokens = [];
67
+ const push = (type, value) => {
68
+ if (!value) return;
69
+ const last = tokens.at(-1);
70
+ if (last && last.type === type) last.text += value;
71
+ else tokens.push({ type, text: value });
72
+ };
73
+ expression.lastIndex = 0;
74
+ let position = 0;
75
+ let match;
76
+ while ((match = expression.exec(source))) {
77
+ if (match[0] === "") {
78
+ expression.lastIndex++;
79
+ continue;
80
+ }
81
+ const rule = lang.rules[groups.findLastIndex(start => match[start] !== undefined)];
82
+ push(null, source.slice(position, match.index));
83
+ if (rule.inner) for (const part of rule.inner(match[0])) push(part.type, part.text);
84
+ else push(rule.type, match[0]);
85
+ position = match.index + match[0].length;
86
+ }
87
+ push(null, source.slice(position));
88
+ return tokens;
89
+ }
90
+
91
+ /* ------------------LANGUAGES------------------- */
92
+
93
+ const words = list => new RegExp(`\\b(?:${list.join("|")})\\b`);
94
+ const rule = (type, pattern) => ({ type, pattern });
95
+
96
+ const STRING_DOUBLE = /"(?:[^"\\\n]|\\[\s\S])*"?/;
97
+ const STRING_SINGLE = /'(?:[^'\\\n]|\\[\s\S])*'?/;
98
+ const NUMBER_C = /\b(?:0[xX][\da-fA-F_]+|0[bB][01_]+|\d[\d_]*\.?\d*(?:[eE][+-]?\d+)?[fFdDmMuUlL]*)\b|\.\d+/;
99
+ const PUNCTUATION = /[{}()[\];,.]/;
100
+ const OPERATOR = /[=+\-*/%<>!&|^~?:]+/;
101
+
102
+ const JS_KEYWORDS = ["break", "case", "catch", "class", "const", "continue", "debugger", "default", "delete", "do", "else", "export", "extends", "finally", "for", "function", "if", "import", "in", "instanceof",
103
+ "let", "new", "of", "return", "static", "super", "switch", "throw", "try", "typeof", "var", "void", "while", "with", "yield", "async", "await", "from", "as", "get", "set"];
104
+ const TS_KEYWORDS = ["interface", "type", "enum", "implements", "namespace", "declare", "readonly", "abstract", "public", "private", "protected", "keyof", "infer", "satisfies", "is", "module", "override"];
105
+ const TS_TYPES = ["string", "number", "boolean", "any", "unknown", "never", "void", "object", "symbol", "bigint"];
106
+
107
+ const jsRules = (keywords, types = []) => [
108
+ rule("comment", /\/\/[^\n]*|\/\*[\s\S]*?(?:\*\/|$)/),
109
+ rule("string", new RegExp(`${STRING_DOUBLE.source}|${STRING_SINGLE.source}|\`(?:[^\`\\\\]|\\\\[\\s\\S])*\`?`)),
110
+ rule("string", /(?<=(?:^|[=(:,[!&|?{};]|\breturn)\s*)\/(?![*/])(?:[^/\\\n[]|\\.|\[(?:[^\]\\\n]|\\.)*\])+\/[a-z]*/),
111
+ rule("number", NUMBER_C),
112
+ rule("keyword", words(keywords)),
113
+ ...(types.length ? [rule("type", words(types))] : []),
114
+ rule("literal", words(["true", "false", "null", "undefined", "NaN", "Infinity", "this"])),
115
+ rule("function", /[A-Za-z_$][\w$]*(?=\s*\()/),
116
+ rule("type", /\b[A-Z][\w$]*\b/),
117
+ rule("punctuation", PUNCTUATION),
118
+ rule("operator", OPERATOR)
119
+ ];
120
+
121
+ const jsBase = { lineComment: "//", blockComment: ["/*", "*/"], pairs: ["()", "[]", "{}", "\"\"", "''", "``"], indentAfter: /[{([]\s*$/ };
122
+
123
+ const HTML_TAG_PARTS = text => {
124
+ const out = [];
125
+ const part = /^<\/?[\w:-]+|\/?>$|"[^"]*"|'[^']*'|[^\s"'<>/=]+(?=\s*=)|=|[^\s"'<>/=]+|\s+|[\s\S]/g;
126
+ for (const [piece] of text.matchAll(part)) {
127
+ let type = null;
128
+ if (/^<\/?[\w:-]+$/.test(piece) || /^\/?>$/.test(piece)) type = "tag";
129
+ else if (/^["']/.test(piece)) type = "string";
130
+ else if (piece === "=") type = "punctuation";
131
+ else if (/^[^\s]/.test(piece)) type = "attribute";
132
+ out.push({ type, text: piece });
133
+ }
134
+ return out;
135
+ };
136
+
137
+ const SQL_KEYWORDS = ["select", "from", "where", "and", "or", "not", "in", "is", "null", "like", "between", "exists", "insert", "into", "values", "update", "set", "delete", "create", "alter", "drop",
138
+ "table", "view", "index", "database", "schema", "join", "inner", "left", "right", "full", "outer", "cross", "on", "using", "group", "by", "order", "having", "limit", "offset", "union", "all", "distinct",
139
+ "as", "case", "when", "then", "else", "end", "with", "primary", "key", "foreign", "references", "constraint", "default", "unique", "check", "asc", "desc", "begin", "commit", "rollback", "transaction",
140
+ "grant", "revoke", "top", "over", "partition", "returning", "cascade", "if", "truncate", "explain", "declare", "exec", "execute", "procedure", "function", "trigger", "add", "column"];
141
+ const SQL_TYPES = ["int", "integer", "bigint", "smallint", "tinyint", "decimal", "numeric", "float", "real", "double", "varchar", "nvarchar", "char", "nchar", "text", "date", "datetime", "datetime2", "timestamp",
142
+ "time", "boolean", "bit", "uuid", "uniqueidentifier", "blob", "json", "jsonb", "money", "serial"];
143
+
144
+ const SHELL_KEYWORDS = ["if", "then", "else", "elif", "fi", "for", "in", "do", "done", "while", "until", "case", "esac", "function", "select", "return", "exit", "break", "continue", "local", "export", "readonly", "declare", "unset", "shift", "source", "time"];
145
+ const SHELL_BUILTINS = ["echo", "cd", "pwd", "ls", "cat", "grep", "sed", "awk", "mkdir", "rm", "cp", "mv", "chmod", "chown", "curl", "wget", "git", "npm", "node", "docker", "kubectl", "sudo", "ssh", "tar", "printf", "read", "test", "true", "false", "eval", "exec", "trap", "set"];
146
+
147
+ const CS_KEYWORDS = ["abstract", "as", "base", "break", "case", "catch", "checked", "class", "const", "continue", "default", "delegate", "do", "else", "enum", "event", "explicit", "extern", "finally", "fixed",
148
+ "for", "foreach", "goto", "if", "implicit", "in", "interface", "internal", "is", "lock", "namespace", "new", "operator", "out", "override", "params", "private", "protected", "public", "readonly", "ref",
149
+ "return", "sealed", "sizeof", "stackalloc", "static", "struct", "switch", "this", "throw", "try", "typeof", "unchecked", "unsafe", "using", "virtual", "volatile", "while", "async", "await", "var", "record",
150
+ "init", "get", "set", "where", "yield", "when", "partial", "required", "with", "global"];
151
+ const CS_TYPES = ["bool", "byte", "sbyte", "char", "decimal", "double", "float", "int", "uint", "long", "ulong", "short", "ushort", "object", "string", "void", "dynamic", "nint", "nuint"];
152
+
153
+ const PY_KEYWORDS = ["and", "as", "assert", "async", "await", "break", "class", "continue", "def", "del", "elif", "else", "except", "finally", "for", "from", "global", "if", "import", "in", "is", "lambda",
154
+ "nonlocal", "not", "or", "pass", "raise", "return", "try", "while", "with", "yield"];
155
+ const PY_BUILTINS = ["print", "len", "range", "list", "dict", "set", "tuple", "str", "int", "float", "bool", "type", "isinstance", "open", "enumerate", "zip", "map", "filter", "sorted", "sum", "min", "max", "abs", "super", "self", "cls"];
156
+
157
+ const BUILT_IN = [
158
+ {
159
+ name: "javascript", label: "JavaScript", aliases: ["js", "mjs", "jsx"], ...jsBase, rules: jsRules(JS_KEYWORDS)
160
+ },
161
+ {
162
+ name: "typescript", label: "TypeScript", aliases: ["ts", "tsx"], ...jsBase, rules: jsRules([...JS_KEYWORDS, ...TS_KEYWORDS], TS_TYPES)
163
+ },
164
+ {
165
+ name: "json", label: "JSON", aliases: ["jsonc"], pairs: ["[]", "{}", "\"\""], indentAfter: /[{[]\s*$/,
166
+ rules: [
167
+ rule("comment", /\/\/[^\n]*|\/\*[\s\S]*?(?:\*\/|$)/),
168
+ rule("property", /"(?:[^"\\\n]|\\.)*"(?=\s*:)/),
169
+ rule("string", STRING_DOUBLE),
170
+ rule("number", /-?\b\d+\.?\d*(?:[eE][+-]?\d+)?\b/),
171
+ rule("literal", words(["true", "false", "null"])),
172
+ rule("punctuation", /[{}[\],:]/)
173
+ ]
174
+ },
175
+ {
176
+ name: "html", label: "HTML", aliases: ["xml", "svg", "xhtml"], blockComment: ["<!--", "-->"], pairs: ["\"\"", "''"], indentAfter: /<[a-z][^>/]*>\s*$/i,
177
+ rules: [
178
+ rule("comment", /<!--[\s\S]*?(?:-->|$)/),
179
+ rule("meta", /<![A-Za-z][^>]*>|<\?[\s\S]*?(?:\?>|$)/),
180
+ { type: "tag", pattern: /<\/?[A-Za-z][\w:-]*(?:\s+[^\s"'<>/=]+(?:\s*=\s*(?:"[^"]*"|'[^']*'|[^\s"'<>]+))?)*\s*\/?>/, inner: HTML_TAG_PARTS },
181
+ rule("entity", /&(?:#\d+|#x[\da-fA-F]+|\w+);/)
182
+ ]
183
+ },
184
+ {
185
+ name: "css", label: "CSS", aliases: ["scss", "less"], blockComment: ["/*", "*/"], pairs: ["()", "[]", "{}", "\"\"", "''"], indentAfter: /\{\s*$/,
186
+ rules: [
187
+ rule("comment", /\/\*[\s\S]*?(?:\*\/|$)/),
188
+ rule("string", new RegExp(`${STRING_DOUBLE.source}|${STRING_SINGLE.source}`)),
189
+ rule("meta", /@[\w-]+/),
190
+ rule("variable", /--[\w-]+/),
191
+ rule("number", /#[\da-fA-F]{3,8}\b|-?(?:\d+\.?\d*|\.\d+)(?:%|[a-zA-Z]+)?/),
192
+ rule("property", /[-\w]+(?=\s*:\s*[^;{}]*[;}])/),
193
+ rule("selector", /[.#][-\w]+|::?[-\w]+|\*/),
194
+ rule("function", /[-\w]+(?=\()/),
195
+ rule("keyword", /!important\b/),
196
+ rule("punctuation", /[{}()[\];,:>+~]/)
197
+ ]
198
+ },
199
+ {
200
+ name: "sql", label: "SQL", aliases: ["tsql", "mysql", "postgres", "postgresql"], ignoreCase: true, lineComment: "--", blockComment: ["/*", "*/"], pairs: ["()", "''", "\"\""], indentAfter: /\(\s*$/,
201
+ rules: [
202
+ rule("comment", /--[^\n]*|\/\*[\s\S]*?(?:\*\/|$)/),
203
+ rule("string", /'(?:[^']|'')*'?/),
204
+ rule("variable", /"[^"\n]*"?|`[^`\n]*`?|\[[^\]\n]*\]|[@:][\w]+/),
205
+ rule("number", /\b\d+\.?\d*\b/),
206
+ rule("keyword", words(SQL_KEYWORDS)),
207
+ rule("type", words(SQL_TYPES)),
208
+ rule("function", /\b[A-Za-z_]\w*(?=\s*\()/),
209
+ rule("operator", /[=<>!+\-*/%|&^~]+/),
210
+ rule("punctuation", /[();,.]/)
211
+ ]
212
+ },
213
+ {
214
+ name: "shell", label: "Shell", aliases: ["sh", "bash", "zsh", "shellscript"], lineComment: "#", pairs: ["()", "[]", "{}", "\"\"", "''", "``"], indentAfter: /(?:\b(?:then|do|else)|[{(])\s*$/,
215
+ rules: [
216
+ rule("comment", /(?<=^|\s)#[^\n]*/),
217
+ rule("string", /"(?:[^"\\]|\\[\s\S])*"?|'[^']*'?/),
218
+ rule("variable", /\$(?:\w+|\{[^}\n]*\}?|\([^)\n]*\)?|[@*#?$!-])/),
219
+ rule("keyword", words(SHELL_KEYWORDS)),
220
+ rule("function", words(SHELL_BUILTINS)),
221
+ rule("attribute", /(?<=\s)--?[A-Za-z][\w-]*/),
222
+ rule("number", /\b\d+\b/),
223
+ rule("operator", /[|&;<>=!]+/)
224
+ ]
225
+ },
226
+ {
227
+ name: "yaml", label: "YAML", aliases: ["yml"], multiline: true, lineComment: "#", pairs: ["[]", "{}", "\"\"", "''"], indentAfter: /:\s*$/,
228
+ rules: [
229
+ rule("comment", /(?<=^|\s)#[^\n]*/),
230
+ rule("meta", /^(?:---|\.\.\.)(?=\s|$)/),
231
+ rule("property", /(?<=^[ \t-]*)(?:"[^"\n]*"|'[^'\n]*'|[^\s#:[\]{},"'-][^:\n#]*?)(?=\s*:(?:\s|$))/),
232
+ rule("string", /"(?:[^"\\\n]|\\.)*"?|'(?:[^'\n]|'')*'?/),
233
+ rule("variable", /[&*!][\w-]+/),
234
+ rule("number", /(?<=[\s:[,-]|^)-?\d[\d_]*\.?\d*(?:[eE][+-]?\d+)?(?=\s|$|[,\]}])/),
235
+ rule("literal", /(?<=[\s:[,-]|^)(?:true|false|null|yes|no|on|off|~)(?=\s|$|[,\]}])/i),
236
+ rule("punctuation", /[[\]{},|>]|(?<=^|\s)-(?=\s)/)
237
+ ]
238
+ },
239
+ {
240
+ name: "csharp", label: "C#", aliases: ["cs", "c#", "dotnet"], lineComment: "//", blockComment: ["/*", "*/"], pairs: ["()", "[]", "{}", "\"\"", "''"], indentAfter: /[{([]\s*$/, multiline: true,
241
+ rules: [
242
+ rule("comment", /\/\/[^\n]*|\/\*[\s\S]*?(?:\*\/|$)/),
243
+ rule("meta", /^[ \t]*#[a-z]+[^\n]*/),
244
+ rule("string", /@"(?:[^"]|"")*"?|[$@]{0,2}"(?:[^"\\\n]|\\.)*"?|'(?:[^'\\\n]|\\.)*'?/),
245
+ rule("number", NUMBER_C),
246
+ rule("keyword", words(CS_KEYWORDS)),
247
+ rule("type", words(CS_TYPES)),
248
+ rule("literal", words(["true", "false", "null"])),
249
+ rule("function", /[A-Za-z_]\w*(?=\s*[(<][^;{)]*\)?\s*[{;=(]|\()/),
250
+ rule("type", /\b[A-Z]\w*\b/),
251
+ rule("punctuation", PUNCTUATION),
252
+ rule("operator", OPERATOR)
253
+ ]
254
+ },
255
+ {
256
+ name: "python", label: "Python", aliases: ["py", "python3"], multiline: true, lineComment: "#", pairs: ["()", "[]", "{}", "\"\"", "''"], indentAfter: /:\s*$/,
257
+ rules: [
258
+ rule("comment", /#[^\n]*/),
259
+ rule("string", /[rRbBfFuU]{0,2}(?:"""[\s\S]*?(?:"""|$)|'''[\s\S]*?(?:'''|$)|"(?:[^"\\\n]|\\.)*"?|'(?:[^'\\\n]|\\.)*'?)/),
260
+ rule("meta", /^[ \t]*@[\w.]+/),
261
+ rule("number", /\b(?:0[xX][\da-fA-F_]+|0[bB][01_]+|\d[\d_]*\.?\d*(?:[eE][+-]?\d+)?j?)\b|\.\d+/),
262
+ rule("function", /(?<=\bdef\s+)\w+/),
263
+ rule("type", /(?<=\bclass\s+)\w+/),
264
+ rule("keyword", words(PY_KEYWORDS)),
265
+ rule("literal", words(["True", "False", "None"])),
266
+ rule("builtin", words(PY_BUILTINS)),
267
+ rule("function", /[A-Za-z_]\w*(?=\s*\()/),
268
+ rule("punctuation", /[{}()[\];,.:]/),
269
+ rule("operator", /[=+\-*/%<>!&|^~@]+/)
270
+ ]
271
+ }
272
+ ];
273
+
274
+ for (const language of BUILT_IN) registerLanguage(language);
275
+
276
+ /** The token types the default theme gives a colour to: the classes are `tok-<type>`. */
277
+ export const TOKEN_TYPES = ["comment", "string", "number", "keyword", "literal", "function", "type", "property", "tag", "attribute", "variable", "selector", "meta", "entity", "builtin", "operator", "punctuation"];