ozdenui 0.1.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.
Files changed (149) hide show
  1. checksums.yaml +7 -0
  2. data/LICENSE +14 -0
  3. data/NOTICE +5 -0
  4. data/README.md +242 -0
  5. data/exe/ozdenui +17 -0
  6. data/lib/ozdenui/AGENTS.md +210 -0
  7. data/lib/ozdenui/COMPONENTS.md +3017 -0
  8. data/lib/ozdenui/app.rb +749 -0
  9. data/lib/ozdenui/command.rb +107 -0
  10. data/lib/ozdenui/components.rb +368 -0
  11. data/lib/ozdenui/dialogs.rb +212 -0
  12. data/lib/ozdenui/files.rb +124 -0
  13. data/lib/ozdenui/icon.png +0 -0
  14. data/lib/ozdenui/kit.json +1 -0
  15. data/lib/ozdenui/kit.rb +115 -0
  16. data/lib/ozdenui/look.rb +229 -0
  17. data/lib/ozdenui/objects.rb +652 -0
  18. data/lib/ozdenui/server.rb +270 -0
  19. data/lib/ozdenui/values.rb +273 -0
  20. data/lib/ozdenui/version.rb +15 -0
  21. data/lib/ozdenui/web/basic/LICENSE +14 -0
  22. data/lib/ozdenui/web/basic/basic.min.css +1 -0
  23. data/lib/ozdenui/web/basic/basic.min.js +78 -0
  24. data/lib/ozdenui/web/basic/font/open-sans/LICENSE.txt +206 -0
  25. data/lib/ozdenui/web/basic/font/open-sans/OpenSans-Bold.ttf +0 -0
  26. data/lib/ozdenui/web/basic/font/open-sans/OpenSans-Regular.ttf +0 -0
  27. data/lib/ozdenui/web/basic/scroll-bar.min.js +3 -0
  28. data/lib/ozdenui/web/bridge.js +584 -0
  29. data/lib/ozdenui/web/comp/accordion.js +659 -0
  30. data/lib/ozdenui/web/comp/action-button/add.png +0 -0
  31. data/lib/ozdenui/web/comp/action-button.js +521 -0
  32. data/lib/ozdenui/web/comp/action-tab-bar.js +383 -0
  33. data/lib/ozdenui/web/comp/app-bar.js +237 -0
  34. data/lib/ozdenui/web/comp/badge.js +292 -0
  35. data/lib/ozdenui/web/comp/bottom-bar.js +555 -0
  36. data/lib/ozdenui/web/comp/breadcrumbs.js +524 -0
  37. data/lib/ozdenui/web/comp/canvas.js +652 -0
  38. data/lib/ozdenui/web/comp/chat-view.js +827 -0
  39. data/lib/ozdenui/web/comp/check-box.js +490 -0
  40. data/lib/ozdenui/web/comp/code-editor.js +965 -0
  41. data/lib/ozdenui/web/comp/color-picker.js +636 -0
  42. data/lib/ozdenui/web/comp/context-menu.js +951 -0
  43. data/lib/ozdenui/web/comp/currency-field.js +209 -0
  44. data/lib/ozdenui/web/comp/data-table/arrow.svg +2 -0
  45. data/lib/ozdenui/web/comp/data-table.js +937 -0
  46. data/lib/ozdenui/web/comp/date-picker.js +1055 -0
  47. data/lib/ozdenui/web/comp/dialog.js +992 -0
  48. data/lib/ozdenui/web/comp/email-field.js +65 -0
  49. data/lib/ozdenui/web/comp/file-picker.js +920 -0
  50. data/lib/ozdenui/web/comp/filters.js +807 -0
  51. data/lib/ozdenui/web/comp/form.js +602 -0
  52. data/lib/ozdenui/web/comp/full-screen-select/arrow.svg +2 -0
  53. data/lib/ozdenui/web/comp/full-screen-select/cancel.svg +2 -0
  54. data/lib/ozdenui/web/comp/full-screen-select.js +614 -0
  55. data/lib/ozdenui/web/comp/gauge.js +439 -0
  56. data/lib/ozdenui/web/comp/graph-box.js +3911 -0
  57. data/lib/ozdenui/web/comp/grid-group.js +185 -0
  58. data/lib/ozdenui/web/comp/hold-to-confirm-button/trash-red.png +0 -0
  59. data/lib/ozdenui/web/comp/hold-to-confirm-button/trash.png +0 -0
  60. data/lib/ozdenui/web/comp/hold-to-confirm-button.js +289 -0
  61. data/lib/ozdenui/web/comp/image-view.js +598 -0
  62. data/lib/ozdenui/web/comp/item-list.js +1740 -0
  63. data/lib/ozdenui/web/comp/json-editor.js +3221 -0
  64. data/lib/ozdenui/web/comp/json-view.js +597 -0
  65. data/lib/ozdenui/web/comp/label-editor.js +1140 -0
  66. data/lib/ozdenui/web/comp/left-menu/data-table.png +0 -0
  67. data/lib/ozdenui/web/comp/left-menu/home.png +0 -0
  68. data/lib/ozdenui/web/comp/left-menu/reports.png +0 -0
  69. data/lib/ozdenui/web/comp/left-menu/setting.png +0 -0
  70. data/lib/ozdenui/web/comp/left-menu.js +548 -0
  71. data/lib/ozdenui/web/comp/line-progress-bar.js +343 -0
  72. data/lib/ozdenui/web/comp/loading-screen.js +413 -0
  73. data/lib/ozdenui/web/comp/log-view.js +530 -0
  74. data/lib/ozdenui/web/comp/login-page.js +685 -0
  75. data/lib/ozdenui/web/comp/markdown-view.js +1045 -0
  76. data/lib/ozdenui/web/comp/menu-bar.js +624 -0
  77. data/lib/ozdenui/web/comp/mini-graph-box.js +492 -0
  78. data/lib/ozdenui/web/comp/minimal-accent.js +208 -0
  79. data/lib/ozdenui/web/comp/notice.js +229 -0
  80. data/lib/ozdenui/web/comp/number-field.js +128 -0
  81. data/lib/ozdenui/web/comp/numeric-keyboard.js +298 -0
  82. data/lib/ozdenui/web/comp/page-control.js +762 -0
  83. data/lib/ozdenui/web/comp/page-header.js +191 -0
  84. data/lib/ozdenui/web/comp/password-field/hide-btn.png +0 -0
  85. data/lib/ozdenui/web/comp/password-field/hide-btn2.png +0 -0
  86. data/lib/ozdenui/web/comp/password-field/show-btn.png +0 -0
  87. data/lib/ozdenui/web/comp/password-field/show-btn2.png +0 -0
  88. data/lib/ozdenui/web/comp/password-field.js +192 -0
  89. data/lib/ozdenui/web/comp/period-bar.js +436 -0
  90. data/lib/ozdenui/web/comp/phone-field.js +322 -0
  91. data/lib/ozdenui/web/comp/progress-bar.js +992 -0
  92. data/lib/ozdenui/web/comp/property-panel.js +3639 -0
  93. data/lib/ozdenui/web/comp/radio-button.js +527 -0
  94. data/lib/ozdenui/web/comp/range-slider.js +569 -0
  95. data/lib/ozdenui/web/comp/rich-text-editor.js +1064 -0
  96. data/lib/ozdenui/web/comp/scroll-area.js +308 -0
  97. data/lib/ozdenui/web/comp/scrolling-text.js +297 -0
  98. data/lib/ozdenui/web/comp/search-input/clear-round.svg +1 -0
  99. data/lib/ozdenui/web/comp/search-input/clear.svg +1 -0
  100. data/lib/ozdenui/web/comp/search-input/filter.png +0 -0
  101. data/lib/ozdenui/web/comp/search-input/filter.svg +1 -0
  102. data/lib/ozdenui/web/comp/search-input/search.svg +1 -0
  103. data/lib/ozdenui/web/comp/search-input.js +725 -0
  104. data/lib/ozdenui/web/comp/search-results.js +596 -0
  105. data/lib/ozdenui/web/comp/select-box.js +1862 -0
  106. data/lib/ozdenui/web/comp/settings-row.js +299 -0
  107. data/lib/ozdenui/web/comp/side-panel.js +616 -0
  108. data/lib/ozdenui/web/comp/slider-field.js +952 -0
  109. data/lib/ozdenui/web/comp/slider.js +838 -0
  110. data/lib/ozdenui/web/comp/smart-button/alert-black.png +0 -0
  111. data/lib/ozdenui/web/comp/smart-button/clock.png +0 -0
  112. data/lib/ozdenui/web/comp/smart-button.js +981 -0
  113. data/lib/ozdenui/web/comp/smart-table/clock.png +0 -0
  114. data/lib/ozdenui/web/comp/smart-table/down.png +0 -0
  115. data/lib/ozdenui/web/comp/smart-table/scroll.png +0 -0
  116. data/lib/ozdenui/web/comp/smart-table/sort.png +0 -0
  117. data/lib/ozdenui/web/comp/smart-table/up.png +0 -0
  118. data/lib/ozdenui/web/comp/smart-table.js +1883 -0
  119. data/lib/ozdenui/web/comp/sortable-list.js +1181 -0
  120. data/lib/ozdenui/web/comp/spark-line-box.js +738 -0
  121. data/lib/ozdenui/web/comp/splitter.js +411 -0
  122. data/lib/ozdenui/web/comp/status-bar.js +408 -0
  123. data/lib/ozdenui/web/comp/step-bar.js +345 -0
  124. data/lib/ozdenui/web/comp/stepper.js +753 -0
  125. data/lib/ozdenui/web/comp/tabs.js +1366 -0
  126. data/lib/ozdenui/web/comp/tag-input.js +1107 -0
  127. data/lib/ozdenui/web/comp/tap-effect.js +170 -0
  128. data/lib/ozdenui/web/comp/text-area-field.js +233 -0
  129. data/lib/ozdenui/web/comp/text-field.js +1006 -0
  130. data/lib/ozdenui/web/comp/time-line.js +398 -0
  131. data/lib/ozdenui/web/comp/time-picker.js +1032 -0
  132. data/lib/ozdenui/web/comp/tiny-select/arrow.svg +1 -0
  133. data/lib/ozdenui/web/comp/tiny-select.js +322 -0
  134. data/lib/ozdenui/web/comp/tiny-table.js +283 -0
  135. data/lib/ozdenui/web/comp/toast.js +891 -0
  136. data/lib/ozdenui/web/comp/toggle.js +757 -0
  137. data/lib/ozdenui/web/comp/tool-bar.js +760 -0
  138. data/lib/ozdenui/web/comp/tooltip.js +534 -0
  139. data/lib/ozdenui/web/comp/tree-view.js +1179 -0
  140. data/lib/ozdenui/web/comp/ui-effects.js +1097 -0
  141. data/lib/ozdenui/web/comp/ui-standards.js +403 -0
  142. data/lib/ozdenui/web/comp/url-field.js +190 -0
  143. data/lib/ozdenui/web/comp/web-view.js +588 -0
  144. data/lib/ozdenui/web/components.js +123 -0
  145. data/lib/ozdenui/web/index.html +39 -0
  146. data/lib/ozdenui/window.rb +188 -0
  147. data/lib/ozdenui/window_cocoa.rb +221 -0
  148. data/lib/ozdenui.rb +32 -0
  149. metadata +200 -0
@@ -0,0 +1,965 @@
1
+ /* Bismillah */
2
+
3
+ /*
4
+
5
+ CodeEditor - v26.11
6
+
7
+ UI COMPONENT
8
+ - A text editor for code: line numbers, colors by language, the line of the cursor. A long line does not wrap: the
9
+ view scrolls sideways.
10
+ - Languages: "python", "javascript", "go", "json", "html", "css", "sql", "bash", "text". CodeEditor.languages takes
11
+ your own.
12
+ - The typing is the <textarea> of the browser: selection, copy, paste, undo and the input of every language work as
13
+ they do everywhere. The colors are drawn behind it, only for the lines that are seen, so a file of 100000 lines stays
14
+ fast.
15
+ - Keys: Tab and Shift + Tab indent (also many lines), Enter keeps the indent of its line (one more after ":" in Python,
16
+ after "{", "[" or "(" in the others), Backspace in the indent goes back one level, Ctrl (or Cmd) + / comments the
17
+ lines out. Undo takes all of them back. Escape, then Tab leaves the editor (for a keyboard user).
18
+ - changeDelay (ms): onChange waits for the typing to rest (for a big text sent to another place).
19
+ - Style packages: "light" (default), "dark". Select with styleName (CodeEditor.styles), or later with setTheme().
20
+
21
+ USAGE:
22
+ const editor = CodeEditor({
23
+ width: 600, height: 400,
24
+ language: "python",
25
+ value: "def hello():\n print('Hello')\n",
26
+ onChange: function (self) { println(self.value.length); },
27
+ onCursorChange: function (self) { println(self.cursorLine + ":" + self.cursorColumn); },
28
+ });
29
+ editor.setValue("x = 1\n"); // onChange is called; setValue(text, 1): silent. Undo starts again.
30
+ editor.getValue(); // the text now (self.value too)
31
+ editor.insertText("print(x)"); // at the cursor; undo takes it back
32
+ editor.getSelectedText();
33
+ editor.setLanguage("javascript");
34
+ editor.setReadOnly(1);
35
+ editor.setShowLineNumbers(0);
36
+ editor.setTabSize(2);
37
+ editor.goToLine(120);
38
+ editor.focusEditor();
39
+ editor.setTheme("dark");
40
+ CodeEditor({ styleName: "dark", placeholder: "Write here", changeDelay: 150 });
41
+
42
+ A NEW LANGUAGE:
43
+ CodeEditor.languages.toml = { lineComment: "#", strings: ['"""', '"', "'"], multiLineStrings: ['"""'], keywords: ["true", "false"], propertyWords: 1 };
44
+ Its keys: lineComment, blockComment: [start, end], strings (the longest first), multiLineStrings, keywords, builtins,
45
+ ignoreCase: 1, callWords: 1 (a word before "(" is a function), propertyWords: 1 (a word before ":" is a property),
46
+ propertyStrings: 1 (a string before ":" is a property), decorators: "@", variables: "$", indentAfter: ":" (the letters
47
+ at the end of a line that open one more level). tokenize: function (text, state): your own, instead of all of them:
48
+ returns { parts: [[kind, text], ...], state }. kind: "keyword", "string", "number", "comment", "builtin", "function",
49
+ "property", "tag", "attribute", "variable", "" (plain). state goes to the next line.
50
+
51
+ Started Date: November 2026
52
+ Webpage: https://bug7a.github.io/js-components/
53
+
54
+ Copyright 2020-2026 Bugra Ozden <bugra.ozden@gmail.com> (https://bug7a.github.io/)
55
+ Licensed under the Apache License, Version 2.0
56
+ SPDX-License-Identifier: Apache-2.0
57
+
58
+ */
59
+
60
+ "use strict";
61
+
62
+ // Default values:
63
+ const CodeEditorDefaults = {
64
+ key: "0", // Your name for this object: read it in a callback (self.key)
65
+ left: 0,
66
+ top: 0,
67
+ width: "100%",
68
+ height: 320,
69
+ value: "", // The text
70
+ language: "text", // A name of CodeEditor.languages
71
+ tabSize: 4, // The spaces of one level
72
+ readOnly: 0,
73
+ showLineNumbers: 1,
74
+ placeholder: "",
75
+ changeDelay: 0, // ms: onChange waits for the typing to rest
76
+ ariaLabel: "Code",
77
+ onChange: function (self) { }, // self.value changed. (Not at create time, not with silent: 1)
78
+ onCursorChange: function (self) { }, // self.cursorLine, self.cursorColumn (from 1)
79
+ styleName: "light", // "light", "dark" or a name added to CodeEditor.styles
80
+ style: { // Light style package (default)
81
+ box: { color: "white", border: 1, borderColor: Black(0.14), round: 8 },
82
+ text: {
83
+ fontSize: 13,
84
+ lineHeight: 20,
85
+ fontFamily: 'ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace',
86
+ color: "#2B2B2A",
87
+ caretColor: "#111111",
88
+ paddingX: 10,
89
+ paddingY: 8,
90
+ },
91
+ gutter: { color: "#F6F6F4", lineColor: Black(0.08), textColor: Black(0.38), activeTextColor: Black(0.8), space: 1 }, // space: letters at each side
92
+ activeLine: { color: "rgba(91, 186, 193, 0.1)" },
93
+ selection: { color: "rgba(91, 186, 193, 0.35)" },
94
+ placeholder: { color: Black(0.4) },
95
+ scrollBar: { color: Black(0.22), hoverColor: Black(0.4), size: 10 },
96
+ // The colors of the code
97
+ kinds: {
98
+ keyword: "#8A2F8E",
99
+ string: "#1F7A3D",
100
+ number: "#A85A00",
101
+ comment: "#7A7F87",
102
+ builtin: "#00717A",
103
+ function: "#2467B8",
104
+ property: "#2467B8",
105
+ tag: "#A32A4B",
106
+ attribute: "#A85A00",
107
+ variable: "#00717A",
108
+ },
109
+ },
110
+ };
111
+
112
+ const CodeEditor = function (params = {}) {
113
+
114
+ // Merge style package: params.style > CodeEditor.styles[styleName] > CodeEditorDefaults.style (light)
115
+ const pageStyle = params.style; // WHY: setTheme() puts it over another package.
116
+ basic.applyStylePackage(params, CodeEditor.styles, CodeEditorDefaults);
117
+
118
+ // Merge params:
119
+ mergeIntoIfMissing(params, CodeEditorDefaults);
120
+
121
+ // BOX: Component container
122
+ const box = startObject(params);
123
+
124
+ // *** PRIVATE VARIABLES:
125
+ let _s = box.style;
126
+ const BUFFER_LINES = 25; // Lines drawn over and under the ones that are seen: a small scroll draws nothing
127
+ const MAX_COLORED_LETTERS = 2000; // A longer line is colored up to here (a minified file)
128
+ const MIN_GUTTER_DIGITS = 2;
129
+ const CARET_MARGIN_LINES = 2; // goToLine() keeps this many lines around the line
130
+ let lines = [""];
131
+ let lineStates = [null]; // lineStates[i]: the state of the tokenizer at the start of line i
132
+ let validStateCount = 1; // The states up to here are right
133
+ let drawnFirstLine = -1; // The lines of the code layer now
134
+ let drawnLastLine = -1;
135
+ let cancelChange = null; // The waiting onChange (changeDelay)
136
+ let canLeaveWithTab = 0; // 1: Escape was pressed: the next Tab leaves the editor
137
+
138
+ // *** PUBLIC VARIABLES:
139
+ box.cursorLine = 1; // Read only (from 1)
140
+ box.cursorColumn = 1;
141
+ // NOTE: Default values are also public variables. (box.value, box.language, box.readOnly...)
142
+
143
+ // *** PRIVATE FUNCTIONS:
144
+
145
+ // The style of a package, with the style of the page over it. (setTheme)
146
+ const styleOfPackage = function (styleName) {
147
+ const fresh = { styleName: styleName, style: pageStyle };
148
+ basic.applyStylePackage(fresh, CodeEditor.styles, CodeEditorDefaults);
149
+ mergeIntoIfMissing(fresh, CodeEditorDefaults);
150
+ return fresh.style;
151
+ };
152
+
153
+ const languageDefinition = function () {
154
+ return CodeEditor.languages[box.language] || CodeEditor.languages.text;
155
+ };
156
+
157
+ const textarea = function () {
158
+ return box.textareaElem;
159
+ };
160
+
161
+ // WHY up to the line: a change only moves the states after it, and only the lines that are seen ask for them.
162
+ const makeStatesUpTo = function (lineIndex) {
163
+ const definition = languageDefinition();
164
+ for (let i = validStateCount; i <= lineIndex && i < lines.length; i++) {
165
+ const previousText = lines[i - 1].slice(0, MAX_COLORED_LETTERS);
166
+ lineStates[i] = CodeEditor.tokenizeLine(previousText, lineStates[i - 1], definition).state;
167
+ validStateCount = i + 1;
168
+ }
169
+ };
170
+
171
+ const lineHtml = function (lineIndex) {
172
+ const text = lines[lineIndex];
173
+ const colored = text.slice(0, MAX_COLORED_LETTERS);
174
+ const result = CodeEditor.tokenizeLine(colored, lineStates[lineIndex], languageDefinition());
175
+ const html = result.parts.map(CodeEditor.partHtml).join("");
176
+ return html + basic.escapeHtml(text.slice(MAX_COLORED_LETTERS));
177
+ };
178
+
179
+ const lineHeight = function () {
180
+ return _s.text.lineHeight;
181
+ };
182
+
183
+ // CONTENT: the lines that are seen and the ones around them. force: also when they are the same lines.
184
+ const drawVisibleLines = function (force) {
185
+ const elem = textarea();
186
+ const firstSeen = Math.floor(elem.scrollTop / lineHeight());
187
+ const seenCount = Math.ceil(elem.clientHeight / lineHeight()) + 1;
188
+ const lastSeen = Math.min(lines.length - 1, firstSeen + seenCount);
189
+ const isInDrawnLines = (firstSeen >= drawnFirstLine && lastSeen <= drawnLastLine);
190
+
191
+ if (force || !isInDrawnLines) {
192
+ drawnFirstLine = Math.max(0, firstSeen - BUFFER_LINES);
193
+ drawnLastLine = Math.min(lines.length - 1, lastSeen + BUFFER_LINES);
194
+ makeStatesUpTo(drawnLastLine);
195
+ drawCode();
196
+ drawGutter();
197
+ }
198
+ placeLayers();
199
+ };
200
+
201
+ const drawCode = function () {
202
+ const parts = [];
203
+ for (let i = drawnFirstLine; i <= drawnLastLine; i++) parts.push(lineHtml(i));
204
+ box.codeLayer.text = parts.join("\n");
205
+ };
206
+
207
+ const drawGutter = function () {
208
+ const numbers = [];
209
+ for (let i = drawnFirstLine; i <= drawnLastLine; i++) {
210
+ const isActive = (i + 1 === box.cursorLine);
211
+ numbers.push((isActive) ? '<span class="code-editor-active-number">' + (i + 1) + "</span>" : String(i + 1));
212
+ }
213
+ box.gutterLayer.text = numbers.join("\n");
214
+ };
215
+
216
+ // LAYOUT: the layers follow the scroll of the textarea
217
+ const placeLayers = function () {
218
+ const elem = textarea();
219
+ const top = _s.text.paddingY + drawnFirstLine * lineHeight() - elem.scrollTop;
220
+ const left = _s.text.paddingX - elem.scrollLeft;
221
+ box.codeLayer.css.transform = "translate(" + left + "px, " + top + "px)";
222
+ box.gutterLayer.css.transform = "translateY(" + top + "px)";
223
+ box.activeLine.top = _s.text.paddingY + (box.cursorLine - 1) * lineHeight() - elem.scrollTop;
224
+ };
225
+
226
+ // LAYOUT: the gutter is as wide as the number of the last line
227
+ const refreshGutterWidth = function () {
228
+ const digits = Math.max(MIN_GUTTER_DIGITS, String(lines.length).length);
229
+ const letters = digits + 2 * _s.gutter.space;
230
+ const width = (box.showLineNumbers == 1) ? "calc(" + letters + "ch + 1px)" : "0px";
231
+ box.gutter.visible = (box.showLineNumbers == 1) ? 1 : 0;
232
+ box.gutter.css.width = width;
233
+ box.gutterLayer.css.right = _s.gutter.space + "ch";
234
+ box.codeArea.css.left = width;
235
+ box.codeArea.css.width = "calc(100% - " + width + ")";
236
+ };
237
+
238
+ // The state of a changed text: the states before the first changed line stay.
239
+ const readValue = function () {
240
+ // WHY once: a big textarea makes its value again at every read (about 100 ms for 100000 lines in WebKit).
241
+ const value = textarea().value;
242
+ const newLines = value.split("\n");
243
+ let firstChanged = 0;
244
+ const shorter = Math.min(lines.length, newLines.length);
245
+ while (firstChanged < shorter && lines[firstChanged] === newLines[firstChanged]) firstChanged++;
246
+ lines = newLines;
247
+ lineStates.length = Math.min(lineStates.length, lines.length);
248
+ validStateCount = Math.min(validStateCount, firstChanged + 1, lines.length);
249
+ box.value = value;
250
+ };
251
+
252
+ // The line and the column of the cursor, and what shows them
253
+ const readCursor = function () {
254
+ const cursor = textarea().selectionStart;
255
+ let line = 1;
256
+ let lineStart = 0;
257
+ let lineBreak = box.value.indexOf("\n");
258
+ while (lineBreak >= 0 && lineBreak < cursor) {
259
+ line++;
260
+ lineStart = lineBreak + 1;
261
+ lineBreak = box.value.indexOf("\n", lineStart);
262
+ }
263
+ const column = cursor - lineStart + 1;
264
+ const isSame = (line === box.cursorLine && column === box.cursorColumn);
265
+ const isOtherLine = (line !== box.cursorLine);
266
+ box.cursorLine = line;
267
+ box.cursorColumn = column;
268
+ if (isOtherLine) drawGutter();
269
+ placeLayers();
270
+ if (!isSame) box.onCursorChange(box);
271
+ };
272
+
273
+ const tellChange = function () {
274
+ if (cancelChange) cancelChange();
275
+ cancelChange = null;
276
+ if (box.changeDelay <= 0) {
277
+ box.onChange(box);
278
+ return;
279
+ }
280
+ cancelChange = box.after(box.changeDelay, function () {
281
+ cancelChange = null;
282
+ box.onChange(box);
283
+ });
284
+ };
285
+
286
+ const onInput = function () {
287
+ readValue();
288
+ refreshGutterWidth();
289
+ drawVisibleLines(1);
290
+ readCursor();
291
+ tellChange();
292
+ };
293
+
294
+ // WHY execCommand: the only way that stays in the undo of the textarea (setRangeText and value do not).
295
+ const insertAtSelection = function (text) {
296
+ const elem = textarea();
297
+ elem.focus();
298
+ const isDone = (text === "") ? document.execCommand("delete") : document.execCommand("insertText", false, text);
299
+ if (!isDone) {
300
+ elem.setRangeText(text, elem.selectionStart, elem.selectionEnd, "end");
301
+ onInput();
302
+ }
303
+ };
304
+
305
+ // The start and the end of the whole lines of the selection, as places in the text
306
+ const selectedLineRange = function () {
307
+ const elem = textarea();
308
+ const value = elem.value;
309
+ const start = value.lastIndexOf("\n", elem.selectionStart - 1) + 1;
310
+ // WHY: A selection that ends at the start of a line does not take that line.
311
+ const lastPlace = (elem.selectionEnd > elem.selectionStart && value[elem.selectionEnd - 1] === "\n") ? elem.selectionEnd - 1 : elem.selectionEnd;
312
+ let end = value.indexOf("\n", lastPlace);
313
+ if (end < 0) end = value.length;
314
+ return { start: start, end: end };
315
+ };
316
+
317
+ // Changes the whole lines of the selection with one step of undo, and selects them.
318
+ const changeSelectedLines = function (changeLine) {
319
+ const elem = textarea();
320
+ const range = selectedLineRange();
321
+ const oldLines = elem.value.slice(range.start, range.end).split("\n");
322
+ const newText = oldLines.map(changeLine).join("\n");
323
+ elem.setSelectionRange(range.start, range.end);
324
+ insertAtSelection(newText);
325
+ elem.setSelectionRange(range.start, range.start + newText.length);
326
+ };
327
+
328
+ const indentOne = function () {
329
+ return " ".repeat(box.tabSize);
330
+ };
331
+
332
+ const isManyLines = function () {
333
+ const elem = textarea();
334
+ return elem.value.slice(elem.selectionStart, elem.selectionEnd).includes("\n");
335
+ };
336
+
337
+ const onTabKey = function () {
338
+ if (isManyLines()) {
339
+ changeSelectedLines(function (line) { return (line.length > 0) ? indentOne() + line : line; });
340
+ return;
341
+ }
342
+ const elem = textarea();
343
+ const lineStart = elem.value.lastIndexOf("\n", elem.selectionStart - 1) + 1;
344
+ const column = elem.selectionStart - lineStart;
345
+ insertAtSelection(" ".repeat(box.tabSize - (column % box.tabSize)));
346
+ };
347
+
348
+ const onShiftTabKey = function () {
349
+ changeSelectedLines(function (line) {
350
+ const spaces = line.match(/^ */)[0].length;
351
+ return line.slice(Math.min(spaces, box.tabSize));
352
+ });
353
+ };
354
+
355
+ const onEnterKey = function () {
356
+ const elem = textarea();
357
+ const lineStart = elem.value.lastIndexOf("\n", elem.selectionStart - 1) + 1;
358
+ const beforeCursor = elem.value.slice(lineStart, elem.selectionStart);
359
+ const indent = beforeCursor.match(/^[ \t]*/)[0];
360
+ const opensLevel = (languageDefinition().indentAfter || "").includes(beforeCursor.trimEnd().slice(-1) || " ");
361
+ insertAtSelection("\n" + indent + ((opensLevel) ? indentOne() : ""));
362
+ };
363
+
364
+ // In the indent, Backspace goes back to the level before. Returns 1 when it did.
365
+ const onBackspaceKey = function () {
366
+ const elem = textarea();
367
+ if (elem.selectionStart !== elem.selectionEnd) return 0;
368
+ const lineStart = elem.value.lastIndexOf("\n", elem.selectionStart - 1) + 1;
369
+ const beforeCursor = elem.value.slice(lineStart, elem.selectionStart);
370
+ if (beforeCursor.length === 0 || beforeCursor.trim().length > 0) return 0;
371
+ const count = ((beforeCursor.length - 1) % box.tabSize) + 1;
372
+ elem.setSelectionRange(elem.selectionStart - count, elem.selectionStart);
373
+ insertAtSelection("");
374
+ return 1;
375
+ };
376
+
377
+ const toggleLineComment = function () {
378
+ const mark = languageDefinition().lineComment;
379
+ if (!mark) return;
380
+ const elem = textarea();
381
+ const range = selectedLineRange();
382
+ const oldLines = elem.value.slice(range.start, range.end).split("\n");
383
+ const isCommented = oldLines.every(function (line) { return line.trim() === "" || line.trimStart().startsWith(mark); });
384
+ changeSelectedLines(function (line) {
385
+ if (line.trim() === "") return line;
386
+ if (!isCommented) return line.replace(/^(\s*)/, "$1" + mark + " ");
387
+ return line.replace(new RegExp("^(\\s*)" + CodeEditor.escapeRegExp(mark) + " ?"), "$1");
388
+ });
389
+ };
390
+
391
+ const onKeyDown = function (event) {
392
+ const isTab = (event.key === "Tab");
393
+ const isCommentKey = (event.key === "/" && (event.ctrlKey || event.metaKey));
394
+ if (event.key === "Escape") canLeaveWithTab = 1;
395
+ else if (!isTab) canLeaveWithTab = 0;
396
+
397
+ if (isTab && canLeaveWithTab) {
398
+ canLeaveWithTab = 0;
399
+ return; // WHY: The Tab of the browser: a keyboard user can leave the editor.
400
+ }
401
+ if (box.readOnly == 1) return;
402
+
403
+ if (isTab) {
404
+ event.preventDefault();
405
+ if (event.shiftKey) onShiftTabKey();
406
+ else onTabKey();
407
+ } else if (event.key === "Enter" && !event.isComposing) {
408
+ event.preventDefault();
409
+ onEnterKey();
410
+ } else if (event.key === "Backspace" && !event.isComposing) {
411
+ if (onBackspaceKey()) event.preventDefault();
412
+ } else if (isCommentKey) {
413
+ event.preventDefault();
414
+ toggleLineComment();
415
+ }
416
+ };
417
+
418
+ // LOOK: everything that comes from the style (the first drawing and setTheme)
419
+ const applyLook = function () {
420
+ const text = _s.text;
421
+ const fontCss = { fontFamily: text.fontFamily, fontSize: text.fontSize + "px", lineHeight: text.lineHeight + "px" };
422
+ box.props(_s.box);
423
+ box.gutter.color = _s.gutter.color;
424
+ // WHY the font of the code on these two: their widths are written in ch, the width of a letter of their own font.
425
+ box.gutter.css = { ...fontCss, borderRight: "1px solid " + _s.gutter.lineColor };
426
+ box.codeArea.css = fontCss;
427
+ box.gutterLayer.css = { ...fontCss, color: _s.gutter.textColor };
428
+ box.codeLayer.css = { ...fontCss, color: text.color, tabSize: box.tabSize };
429
+ box.activeLine.color = _s.activeLine.color;
430
+ box.activeLine.height = text.lineHeight;
431
+ Object.assign(textarea().style, fontCss, {
432
+ padding: text.paddingY + "px " + text.paddingX + "px",
433
+ caretColor: text.caretColor,
434
+ tabSize: box.tabSize,
435
+ });
436
+ const variables = { "--code-editor-selection": _s.selection.color, "--code-editor-placeholder": _s.placeholder.color,
437
+ "--code-editor-active-number": _s.gutter.activeTextColor, "--code-editor-bar": _s.scrollBar.color,
438
+ "--code-editor-bar-hover": _s.scrollBar.hoverColor, "--code-editor-bar-size": _s.scrollBar.size + "px" };
439
+ Object.keys(_s.kinds).forEach(function (kind) { variables["--code-editor-" + kind] = _s.kinds[kind]; });
440
+ Object.keys(variables).forEach(function (name) { box.elem.style.setProperty(name, variables[name]); });
441
+ refreshGutterWidth();
442
+ drawVisibleLines(1);
443
+ };
444
+
445
+ // Everything of a new text
446
+ const showValue = function () {
447
+ lines = [""];
448
+ lineStates = [null];
449
+ validStateCount = 1;
450
+ readValue();
451
+ textarea().scrollTop = 0;
452
+ textarea().scrollLeft = 0;
453
+ box.cursorLine = 1;
454
+ box.cursorColumn = 1;
455
+ refreshGutterWidth();
456
+ drawVisibleLines(1);
457
+ };
458
+
459
+ // *** PUBLIC FUNCTIONS:
460
+
461
+ // silent: 1 -> onChange is not called. NOTE: The undo of the browser starts again with a new text.
462
+ box.setValue = function (value, silent = 0) {
463
+ const text = (value === null || value === undefined) ? "" : String(value);
464
+ if (text === textarea().value) return; // the same text: nothing to draw, no onChange
465
+ textarea().value = text;
466
+ showValue();
467
+ if (!silent) tellChange();
468
+ };
469
+ // USAGE: get: editor.value (or editor.getValue()), set: editor.setValue("x = 1\n")
470
+
471
+ box.getValue = function () {
472
+ return textarea().value;
473
+ };
474
+
475
+ // At the cursor, over the selected text. Undo takes it back.
476
+ box.insertText = function (text) {
477
+ insertAtSelection(String(text));
478
+ };
479
+ // USAGE: editor.insertText("print(x)")
480
+
481
+ box.getSelectedText = function () {
482
+ const elem = textarea();
483
+ return elem.value.slice(elem.selectionStart, elem.selectionEnd);
484
+ };
485
+
486
+ box.setLanguage = function (language) {
487
+ box.language = language;
488
+ validStateCount = 1;
489
+ drawVisibleLines(1);
490
+ };
491
+ // USAGE: editor.setLanguage("python")
492
+
493
+ box.setReadOnly = function (value) {
494
+ box.readOnly = basic.isOn(value) ? 1 : 0;
495
+ textarea().readOnly = (box.readOnly == 1);
496
+ };
497
+ // USAGE: editor.setReadOnly(1)
498
+
499
+ box.setShowLineNumbers = function (value) {
500
+ box.showLineNumbers = basic.isOn(value) ? 1 : 0;
501
+ refreshGutterWidth();
502
+ };
503
+ // USAGE: editor.setShowLineNumbers(0)
504
+
505
+ box.setTabSize = function (size) {
506
+ box.tabSize = size;
507
+ textarea().style.tabSize = size;
508
+ box.codeLayer.css.tabSize = size;
509
+ };
510
+ // USAGE: editor.setTabSize(2)
511
+
512
+ // Puts the cursor at the start of a line (from 1) and shows it.
513
+ box.goToLine = function (lineNumber) {
514
+ const elem = textarea();
515
+ const line = basic.clamp(Math.round(lineNumber), 1, lines.length);
516
+ let place = 0;
517
+ for (let i = 0; i < line - 1; i++) place += lines[i].length + 1;
518
+ elem.focus({ preventScroll: true });
519
+ elem.setSelectionRange(place, place);
520
+ const top = (line - 1) * lineHeight();
521
+ const margin = CARET_MARGIN_LINES * lineHeight();
522
+ const isSeen = (top - margin >= elem.scrollTop && top + lineHeight() + margin <= elem.scrollTop + elem.clientHeight);
523
+ if (!isSeen) elem.scrollTop = Math.max(0, top - elem.clientHeight / 2);
524
+ drawVisibleLines(0);
525
+ readCursor();
526
+ };
527
+ // USAGE: editor.goToLine(120)
528
+
529
+ box.focusEditor = function () {
530
+ textarea().focus({ preventScroll: true });
531
+ };
532
+ // USAGE: editor.focusEditor()
533
+
534
+ // Another style package while it is on the page. A style given by the page stays over it.
535
+ box.setTheme = function (styleName) {
536
+ box.styleName = styleName;
537
+ _s = styleOfPackage(styleName);
538
+ box.style = _s;
539
+ applyLook();
540
+ };
541
+ // USAGE: editor.setTheme("dark")
542
+
543
+ // *** OBJECT VIEW:
544
+
545
+ basic.addCss("code-editor",
546
+ ".code-editor-textarea { position: absolute; left: 0; top: 0; width: 100%; height: 100%; margin: 0; border: 0; outline: none;" +
547
+ " resize: none; box-sizing: border-box; background: transparent; color: transparent; -webkit-text-fill-color: transparent;" +
548
+ " white-space: pre; overflow: auto; pointer-events: auto; user-select: text; -webkit-user-select: text; font-variant-ligatures: none; }" +
549
+ ".code-editor-textarea::selection { background: var(--code-editor-selection); }" +
550
+ ".code-editor-textarea::placeholder { color: var(--code-editor-placeholder); -webkit-text-fill-color: var(--code-editor-placeholder); }" +
551
+ ".code-editor-textarea::-webkit-scrollbar { width: var(--code-editor-bar-size); height: var(--code-editor-bar-size); }" +
552
+ ".code-editor-textarea::-webkit-scrollbar-thumb { background: var(--code-editor-bar); border-radius: 6px; border: 2px solid transparent; background-clip: padding-box; }" +
553
+ ".code-editor-textarea::-webkit-scrollbar-thumb:hover { background: var(--code-editor-bar-hover); border: 2px solid transparent; background-clip: padding-box; }" +
554
+ ".code-editor-textarea::-webkit-scrollbar-corner { background: transparent; }" +
555
+ ".code-editor-layer { white-space: pre; font-variant-ligatures: none; overflow: visible; width: max-content; }" +
556
+ ".code-editor-active-number { color: var(--code-editor-active-number); }" +
557
+ CodeEditor.KIND_NAMES.map(function (kind) { return ".code-editor-" + kind + " { color: var(--code-editor-" + kind + "); }"; }).join("")
558
+ );
559
+
560
+ // BOX: The line numbers
561
+ box.gutter = startBox({ left: 0, top: 0, height: "100%", css: { boxSizing: "border-box" } });
562
+
563
+ // LABEL: The numbers that are seen
564
+ box.gutterLayer = Label({ top: 0, textAlign: "right" });
565
+ box.gutterLayer.elem.classList.add("code-editor-layer");
566
+ box.gutterLayer.css.left = "auto";
567
+ box.gutterLayer.aria = { hidden: "true" };
568
+
569
+ endBox();
570
+
571
+ // BOX: The code
572
+ box.codeArea = startBox({ top: 0, height: "100%", color: "transparent" });
573
+
574
+ // BOX: The line of the cursor
575
+ box.activeLine = Box({ left: 0, width: "100%" });
576
+
577
+ // LABEL: The colored code that is seen (behind the textarea)
578
+ box.codeLayer = Label({ left: 0, top: 0 });
579
+ box.codeLayer.elem.classList.add("code-editor-layer");
580
+ box.codeLayer.aria = { hidden: "true" };
581
+
582
+ endBox();
583
+
584
+ // TEXTAREA: The typing. A raw element: basic.js has no object of more lines. Its text is transparent, over the colors.
585
+ box.textareaElem = document.createElement("textarea");
586
+ box.textareaElem.classList.add("code-editor-textarea");
587
+ box.textareaElem.wrap = "off";
588
+ box.textareaElem.spellcheck = false;
589
+ box.textareaElem.setAttribute("autocomplete", "off");
590
+ box.textareaElem.setAttribute("autocorrect", "off");
591
+ box.textareaElem.setAttribute("autocapitalize", "off");
592
+ box.textareaElem.setAttribute("aria-label", box.ariaLabel);
593
+ box.textareaElem.placeholder = box.placeholder;
594
+ box.textareaElem.readOnly = (box.readOnly == 1);
595
+ box.textareaElem.value = (box.value === null || box.value === undefined) ? "" : String(box.value);
596
+ box.codeArea.elem.appendChild(box.textareaElem);
597
+
598
+ // *** OBJECT INIT CODE:
599
+
600
+ box.listenTo(textarea(), "input", onInput);
601
+ box.listenTo(textarea(), "scroll", function () { drawVisibleLines(0); });
602
+ box.listenTo(textarea(), "keydown", function (self, event) { onKeyDown(event); });
603
+ box.listenTo(textarea(), "keyup", readCursor);
604
+ box.listenTo(textarea(), "mouseup", readCursor);
605
+ box.listenTo(textarea(), "focus", readCursor);
606
+ box.listenTo(document, "selectionchange", function () {
607
+ if (document.activeElement === textarea()) readCursor();
608
+ });
609
+ // WHY: The first drawing has no height when the box is not on the page yet; a new height shows more lines.
610
+ box.onResize(function () { drawVisibleLines(0); });
611
+
612
+ readValue();
613
+ applyLook();
614
+
615
+ return endObject(box);
616
+
617
+ };
618
+
619
+ // *** STATIC VARIABLES AND FUNCTIONS:
620
+
621
+ CodeEditor.KIND_NAMES = ["keyword", "string", "number", "comment", "builtin", "function", "property", "tag", "attribute", "variable"];
622
+
623
+ CodeEditor.escapeRegExp = function (text) {
624
+ return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
625
+ };
626
+
627
+ // [kind, text] as HTML
628
+ CodeEditor.partHtml = function (part) {
629
+ const text = basic.escapeHtml(part[1]);
630
+ return (part[0]) ? '<span class="code-editor-' + part[0] + '">' + text + "</span>" : text;
631
+ };
632
+
633
+ CodeEditor.NUMBER = /^(0[xX][0-9a-fA-F_]+|0[bB][01_]+|\d[\d_]*(\.\d*)?([eE][+-]?\d+)?|\.\d+([eE][+-]?\d+)?)/;
634
+ // WHY the letters of every language: "şif" is one word, not "ş" and the keyword "if".
635
+ CodeEditor.WORD = /^[\p{L}_][\p{L}\p{N}_]*/u;
636
+ CodeEditor.WORD_LETTER = /[\p{L}\p{N}_]/u;
637
+
638
+ // The text from a place to the end of a string, with the letters after a backslash skipped. -1: it does not end here.
639
+ CodeEditor.findStringEnd = function (text, from, mark) {
640
+ let index = from;
641
+ while (index < text.length) {
642
+ if (text[index] === "\\") {
643
+ index += 2;
644
+ } else if (text.startsWith(mark, index)) {
645
+ return index + mark.length;
646
+ } else {
647
+ index++;
648
+ }
649
+ }
650
+ return -1;
651
+ };
652
+
653
+ // The kind of a word by its place
654
+ CodeEditor.kindOfWord = function (word, restOfLine, definition) {
655
+ const lookedUp = (definition.ignoreCase) ? word.toLowerCase() : word;
656
+ if (definition.keywordSet.has(lookedUp)) return "keyword";
657
+ if (definition.builtinSet.has(lookedUp)) return "builtin";
658
+ if (definition.callWords && /^\s*\(/.test(restOfLine)) return "function";
659
+ if (definition.propertyWords && /^\s*:/.test(restOfLine)) return "property";
660
+ return "";
661
+ };
662
+
663
+ // WHY sets, made once: the words are looked up for every word of every line that is drawn.
664
+ CodeEditor.prepareDefinition = function (definition) {
665
+ if (definition.keywordSet) return;
666
+ definition.keywordSet = new Set(definition.keywords || []);
667
+ definition.builtinSet = new Set(definition.builtins || []);
668
+ };
669
+
670
+ // One line: { parts: [[kind, text], ...], state }. state: the end mark of what is still open at the end of the line.
671
+ CodeEditor.tokenizeLine = function (text, state, definition) {
672
+ if (definition.tokenize) return definition.tokenize(text, state);
673
+ CodeEditor.prepareDefinition(definition);
674
+
675
+ const parts = [];
676
+ const add = function (kind, value) {
677
+ if (value.length === 0) return;
678
+ const last = parts[parts.length - 1];
679
+ if (last && last[0] === kind) last[1] += value;
680
+ else parts.push([kind, value]);
681
+ };
682
+ let index = 0;
683
+ let openState = state;
684
+
685
+ // WHAT IS STILL OPEN from the lines before (a comment, a string of many lines)
686
+ if (openState) {
687
+ const isString = (definition.multiLineStrings || []).includes(openState);
688
+ const end = (isString) ? CodeEditor.findStringEnd(text, 0, openState) : text.indexOf(openState);
689
+ const kind = (isString) ? "string" : "comment";
690
+ if (end < 0) {
691
+ add(kind, text);
692
+ return { parts: parts, state: openState };
693
+ }
694
+ const stop = (isString) ? end : end + openState.length;
695
+ add(kind, text.slice(0, stop));
696
+ index = stop;
697
+ openState = null;
698
+ }
699
+
700
+ const lineComment = definition.lineComment;
701
+ const blockComment = definition.blockComment;
702
+ const strings = definition.strings || [];
703
+ const multiLine = definition.multiLineStrings || [];
704
+
705
+ while (index < text.length) {
706
+ const rest = text.slice(index);
707
+ const letter = text[index];
708
+
709
+ if (lineComment && rest.startsWith(lineComment)) {
710
+ add("comment", rest);
711
+ break;
712
+ }
713
+
714
+ if (blockComment && rest.startsWith(blockComment[0])) {
715
+ const end = text.indexOf(blockComment[1], index + blockComment[0].length);
716
+ if (end < 0) {
717
+ add("comment", rest);
718
+ openState = blockComment[1];
719
+ break;
720
+ }
721
+ add("comment", text.slice(index, end + blockComment[1].length));
722
+ index = end + blockComment[1].length;
723
+ continue;
724
+ }
725
+
726
+ const stringMark = strings.find(function (mark) { return rest.startsWith(mark); });
727
+ if (stringMark) {
728
+ const end = CodeEditor.findStringEnd(text, index + stringMark.length, stringMark);
729
+ if (end < 0) {
730
+ add("string", rest);
731
+ if (multiLine.includes(stringMark)) openState = stringMark;
732
+ break;
733
+ }
734
+ const isProperty = (definition.propertyStrings && /^\s*:/.test(text.slice(end)));
735
+ add((isProperty) ? "property" : "string", text.slice(index, end));
736
+ index = end;
737
+ continue;
738
+ }
739
+
740
+ const isAfterWord = (index > 0 && CodeEditor.WORD_LETTER.test(text[index - 1]));
741
+ const numberMatch = (isAfterWord) ? null : CodeEditor.NUMBER.exec(rest);
742
+ if (numberMatch) {
743
+ add("number", numberMatch[0]);
744
+ index += numberMatch[0].length;
745
+ continue;
746
+ }
747
+
748
+ if (definition.decorators && letter === definition.decorators) {
749
+ const decorator = CodeEditor.WORD.exec(rest.slice(1));
750
+ if (decorator) {
751
+ add("function", letter + decorator[0]);
752
+ index += 1 + decorator[0].length;
753
+ continue;
754
+ }
755
+ }
756
+
757
+ if (definition.variables && letter === definition.variables) {
758
+ const variable = CodeEditor.WORD.exec(rest.slice(1));
759
+ if (variable) {
760
+ add("variable", letter + variable[0]);
761
+ index += 1 + variable[0].length;
762
+ continue;
763
+ }
764
+ }
765
+
766
+ const wordMatch = CodeEditor.WORD.exec(rest);
767
+ if (wordMatch) {
768
+ const word = wordMatch[0];
769
+ add(CodeEditor.kindOfWord(word, rest.slice(word.length), definition), word);
770
+ index += word.length;
771
+ continue;
772
+ }
773
+
774
+ add("", letter);
775
+ index++;
776
+ }
777
+
778
+ return { parts: parts, state: openState };
779
+ };
780
+
781
+ // HTML has tags instead of words. state: "-->" (a comment), "tag" (the attributes of a tag go on)
782
+ CodeEditor.tokenizeHtml = function (text, state) {
783
+ const parts = [];
784
+ let index = 0;
785
+ let openState = state;
786
+
787
+ const readTagInside = function () {
788
+ while (index < text.length) {
789
+ const rest = text.slice(index);
790
+ const closing = /^\/?>/.exec(rest);
791
+ if (closing) {
792
+ parts.push(["tag", closing[0]]);
793
+ index += closing[0].length;
794
+ openState = null;
795
+ return;
796
+ }
797
+ const attribute = /^[A-Za-z_:@][\w:.-]*/.exec(rest);
798
+ const quoted = /^("[^"]*"?|'[^']*'?)/.exec(rest);
799
+ if (attribute) {
800
+ parts.push(["attribute", attribute[0]]);
801
+ index += attribute[0].length;
802
+ } else if (quoted) {
803
+ parts.push(["string", quoted[0]]);
804
+ index += quoted[0].length;
805
+ } else {
806
+ parts.push(["", text[index]]);
807
+ index++;
808
+ }
809
+ }
810
+ openState = "tag";
811
+ };
812
+
813
+ if (openState === "-->") {
814
+ const end = text.indexOf("-->");
815
+ if (end < 0) return { parts: [["comment", text]], state: "-->" };
816
+ parts.push(["comment", text.slice(0, end + 3)]);
817
+ index = end + 3;
818
+ openState = null;
819
+ } else if (openState === "tag") {
820
+ readTagInside();
821
+ }
822
+
823
+ while (index < text.length) {
824
+ const rest = text.slice(index);
825
+ if (rest.startsWith("<!--")) {
826
+ const end = text.indexOf("-->", index + 4);
827
+ if (end < 0) {
828
+ parts.push(["comment", rest]);
829
+ return { parts: parts, state: "-->" };
830
+ }
831
+ parts.push(["comment", text.slice(index, end + 3)]);
832
+ index = end + 3;
833
+ continue;
834
+ }
835
+ const opening = /^<\/?[A-Za-z!][\w:-]*/.exec(rest);
836
+ if (opening) {
837
+ parts.push(["tag", opening[0]]);
838
+ index += opening[0].length;
839
+ readTagInside();
840
+ continue;
841
+ }
842
+ const nextTag = rest.indexOf("<", 1);
843
+ const stop = (nextTag < 0) ? text.length : index + nextTag;
844
+ parts.push(["", text.slice(index, stop)]);
845
+ index = stop;
846
+ }
847
+
848
+ return { parts: parts, state: openState };
849
+ };
850
+
851
+ // *** LANGUAGES:
852
+ CodeEditor.languages = {
853
+
854
+ text: {
855
+ tokenize: function (line) { return { parts: [["", line]], state: null }; },
856
+ },
857
+
858
+ python: {
859
+ lineComment: "#",
860
+ strings: ['"""', "'''", '"', "'"],
861
+ multiLineStrings: ['"""', "'''"],
862
+ keywords: ["False", "None", "True", "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"],
863
+ builtins: ["abs", "all", "any", "bool", "bytes", "dict", "dir", "enumerate", "filter", "float", "format", "getattr", "hasattr", "input", "int", "isinstance", "iter", "len", "list", "map", "max", "min", "next", "object", "open", "print", "range", "repr", "reversed", "round", "set", "setattr", "sorted", "str", "sum", "super", "tuple", "type", "zip", "self", "cls"],
864
+ callWords: 1,
865
+ decorators: "@",
866
+ indentAfter: ":",
867
+ },
868
+
869
+ javascript: {
870
+ lineComment: "//",
871
+ blockComment: ["/*", "*/"],
872
+ strings: ['"', "'", "`"],
873
+ multiLineStrings: ["`"],
874
+ keywords: ["async", "await", "break", "case", "catch", "class", "const", "continue", "default", "delete", "do", "else", "export", "extends", "false", "finally", "for", "function", "if", "import", "in", "instanceof", "let", "new", "null", "of", "return", "static", "super", "switch", "this", "throw", "true", "try", "typeof", "undefined", "var", "void", "while", "yield"],
875
+ builtins: ["Array", "Boolean", "Date", "Error", "JSON", "Map", "Math", "Number", "Object", "Promise", "RegExp", "Set", "String", "console", "document", "window"],
876
+ callWords: 1,
877
+ indentAfter: "{[(",
878
+ },
879
+
880
+ go: {
881
+ lineComment: "//",
882
+ blockComment: ["/*", "*/"],
883
+ strings: ['"', "'", "`"],
884
+ multiLineStrings: ["`"],
885
+ keywords: ["break", "case", "chan", "const", "continue", "default", "defer", "else", "fallthrough", "false", "for", "func", "go", "goto", "if", "import", "interface", "iota", "map", "nil", "package", "range", "return", "select", "struct", "switch", "true", "type", "var"],
886
+ builtins: ["any", "append", "bool", "byte", "cap", "clear", "close", "complex", "copy", "delete", "error", "float32", "float64", "int", "int8", "int16", "int32", "int64", "len", "make", "max", "min", "new", "panic", "print", "println", "recover", "rune", "string", "uint", "uint8", "uint16", "uint32", "uint64", "uintptr"],
887
+ callWords: 1,
888
+ indentAfter: "{[(",
889
+ },
890
+
891
+ json: {
892
+ strings: ['"'],
893
+ keywords: ["true", "false", "null"],
894
+ propertyStrings: 1,
895
+ indentAfter: "{[",
896
+ },
897
+
898
+ css: {
899
+ blockComment: ["/*", "*/"],
900
+ strings: ['"', "'"],
901
+ propertyWords: 1,
902
+ variables: "#", // #fff, #title
903
+ indentAfter: "{",
904
+ },
905
+
906
+ sql: {
907
+ lineComment: "--",
908
+ blockComment: ["/*", "*/"],
909
+ strings: ["'", '"'],
910
+ ignoreCase: 1,
911
+ keywords: ["add", "all", "alter", "and", "as", "asc", "between", "by", "case", "create", "delete", "desc", "distinct", "drop", "else", "end", "exists", "from", "group", "having", "in", "index", "inner", "insert", "into", "is", "join", "key", "left", "like", "limit", "not", "null", "offset", "on", "or", "order", "outer", "primary", "right", "select", "set", "table", "then", "union", "unique", "update", "values", "view", "when", "where"],
912
+ builtins: ["avg", "count", "max", "min", "sum", "coalesce", "lower", "upper", "integer", "text", "real", "varchar", "boolean", "date"],
913
+ callWords: 1,
914
+ indentAfter: "(",
915
+ },
916
+
917
+ bash: {
918
+ lineComment: "#",
919
+ strings: ['"', "'"],
920
+ keywords: ["case", "do", "done", "elif", "else", "esac", "exit", "export", "fi", "for", "function", "if", "in", "local", "return", "set", "then", "until", "while"],
921
+ builtins: ["cat", "cd", "chmod", "cp", "echo", "find", "grep", "ls", "mkdir", "mv", "pwd", "read", "rm", "sed", "sudo", "touch"],
922
+ variables: "$",
923
+ indentAfter: "{(",
924
+ },
925
+
926
+ html: {
927
+ tokenize: CodeEditor.tokenizeHtml,
928
+ },
929
+
930
+ };
931
+
932
+ // *** STYLE PACKAGES:
933
+ // USAGE: CodeEditor({ styleName: "dark" })
934
+ // USAGE: CodeEditor({ styleName: "dark", style: { kinds: { keyword: "tomato" } } }) // Change only some keys.
935
+ // NOTE: A new package needs only the keys that differ from the default (light) style.
936
+ // USAGE: CodeEditor.styles.myStyle = { box: { color: "#FFFDF5" } };
937
+ CodeEditor.styles = {
938
+
939
+ // White, a soft gray for the numbers.
940
+ light: CodeEditorDefaults.style,
941
+
942
+ // For a dark window.
943
+ dark: {
944
+ box: { color: "#1C1C1B", borderColor: White(0.1) },
945
+ text: { color: "#E6E6E3", caretColor: "#FFFFFF" },
946
+ gutter: { color: "#232322", lineColor: White(0.08), textColor: White(0.38), activeTextColor: White(0.85) },
947
+ activeLine: { color: White(0.05) },
948
+ selection: { color: "rgba(111, 198, 205, 0.35)" },
949
+ placeholder: { color: White(0.42) },
950
+ scrollBar: { color: White(0.22), hoverColor: White(0.4) },
951
+ kinds: {
952
+ keyword: "#D7A2E8",
953
+ string: "#8FD694",
954
+ number: "#F0B56A",
955
+ comment: "#8D939B",
956
+ builtin: "#6FC6CD",
957
+ function: "#8CC4EE",
958
+ property: "#8CC4EE",
959
+ tag: "#F08FA8",
960
+ attribute: "#F0B56A",
961
+ variable: "#6FC6CD",
962
+ },
963
+ },
964
+
965
+ };