diff --git a/.devcontainer/devcontainer-lock.json b/.devcontainer/devcontainer-lock.json index 08e3811..e71fffa 100644 --- a/.devcontainer/devcontainer-lock.json +++ b/.devcontainer/devcontainer-lock.json @@ -1,9 +1,9 @@ { "features": { "ghcr.io/devcontainers/features/node:2.1": { - "version": "2.1.1", - "resolved": "ghcr.io/devcontainers/features/node@sha256:2a19d3b0b3879437637cfd292eb29fee0afcfbe6364e33db9afc4f80c5c1f956", - "integrity": "sha256:2a19d3b0b3879437637cfd292eb29fee0afcfbe6364e33db9afc4f80c5c1f956" + "version": "2.1.2", + "resolved": "ghcr.io/devcontainers/features/node@sha256:20ac718cc67e7999a9d3fbb8387f1a3a5d53ecbd41fe7c075ebadb8e9b431b17", + "integrity": "sha256:20ac718cc67e7999a9d3fbb8387f1a3a5d53ecbd41fe7c075ebadb8e9b431b17" }, "ghcr.io/nordcominc/devcontainer-features/android-sdk:2": { "version": "2.0.0", diff --git a/.github/workflows/nightly-release.yml b/.github/workflows/nightly-release.yml index 1275bfa..4421aba 100644 --- a/.github/workflows/nightly-release.yml +++ b/.github/workflows/nightly-release.yml @@ -51,7 +51,7 @@ jobs: persist-credentials: true - name: Install cosign - uses: sigstore/cosign-installer@v4.1.2 + uses: sigstore/cosign-installer@v4.1.3 - name: Set Publish Metadata shell: bash diff --git a/.gitignore b/.gitignore index 4dc7cd1..2579441 100644 --- a/.gitignore +++ b/.gitignore @@ -19,6 +19,8 @@ tsconfig.tsbuildinfo .dev-cert.pem .dev-key.pem .pnpm-store/ +pnpm-workspace.yaml +pnpm-workspace.yml platforms/android/**/build/ platforms/android/.gradle/ platforms/**/bundle/ diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 106db87..62df3be 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -443,6 +443,16 @@ We use [Biome](https://biomejs.dev/) for linting and formatting: - Run `npm run check` before committing - Install the Biome VS Code extension for auto-formatting +### Performance Changes + +Performance PRs must show a real, measurable improvement in Acode itself: + +- Include a profile from the app (for example, Chrome DevTools connected to the Android WebView) showing that the code you change is an actual bottleneck in something the user waits on. +- Include before/after numbers measured in the app, with the device and steps used. +- Microbenchmark results from sites like jsbench or measurethat are not accepted on their own. They time a function in a tight loop and say nothing about its effect in the app. +- Keep the change focused on the bottleneck. Don't mix in rewrites of unrelated code, build scripts, Cordova hooks or vendored files. +- The change must not alter behavior. Point out any output that differs from before. + ### Commit Messages Use clear, descriptive messages: diff --git a/package-lock.json b/package-lock.json index e3e2d68..290845e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,7 +9,7 @@ "version": "1.13.6", "license": "MIT", "dependencies": { - "@acode.app/canvas-view": "^0.0.4", + "@acode.app/canvas-view": "^0.0.11", "@codemirror/autocomplete": "^6.20.3", "@codemirror/commands": "^6.11.0", "@codemirror/lang-angular": "^0.1.4", @@ -44,7 +44,7 @@ "@codemirror/view": "^6.43.14", "@deadlyjack/ajax": "^1.2.6", "@emmetio/codemirror6-plugin": "^0.4.1", - "@lezer/common": "^1.5.5", + "@lezer/common": "^1.5.6", "@lezer/highlight": "^1.2.5", "@lezer/lr": "^1.4.10", "@ungap/custom-elements": "^1.3.0", @@ -161,9 +161,9 @@ } }, "node_modules/@acode.app/canvas-view": { - "version": "0.0.4", - "resolved": "https://registry.npmjs.org/@acode.app/canvas-view/-/canvas-view-0.0.4.tgz", - "integrity": "sha512-o88sexJ31AywiloTxu1RRqD1JLcfO7zcfKEHoDwUOSdsmHd9bptO7K6j8dov7XK6PdVaXk3IGwa1s0egRtz1yQ==", + "version": "0.0.11", + "resolved": "https://registry.npmjs.org/@acode.app/canvas-view/-/canvas-view-0.0.11.tgz", + "integrity": "sha512-ohsVQatQfgn555ksFsLe7+nzLoACLJ93hF8yCDpWUeCMoN26k4idiH1MnZzHm8frl/ZOIyGxXCjL15no0pfKqQ==", "license": "MIT", "dependencies": { "@codemirror/language": "^6.13.1", @@ -3374,9 +3374,9 @@ } }, "node_modules/@lezer/common": { - "version": "1.5.5", - "resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.5.5.tgz", - "integrity": "sha512-Pw7PVCndruF1pb3ebCxpSVpkMHSDjwRCLcTRw+RizUKco5QbWylwq2g4lnG/RYN7yTTQDXE9F77MwtkAyphrjg==", + "version": "1.5.6", + "resolved": "https://registry.npmjs.org/@lezer/common/-/common-1.5.6.tgz", + "integrity": "sha512-NZxu3q49ck+YYbEJPuIPIyFP37XneBvzPIarBHEXBLBVfkZqQieZ/Y2boYnGNYtmjpOZLnAKs/lwqtmDpi365w==", "license": "MIT" }, "node_modules/@lezer/cpp": { diff --git a/package.json b/package.json index e482adf..68b446d 100644 --- a/package.json +++ b/package.json @@ -75,7 +75,7 @@ "ws": "^8.21.3" }, "dependencies": { - "@acode.app/canvas-view": "^0.0.4", + "@acode.app/canvas-view": "^0.0.11", "@codemirror/autocomplete": "^6.20.3", "@codemirror/commands": "^6.11.0", "@codemirror/lang-angular": "^0.1.4", @@ -110,7 +110,7 @@ "@codemirror/view": "^6.43.14", "@deadlyjack/ajax": "^1.2.6", "@emmetio/codemirror6-plugin": "^0.4.1", - "@lezer/common": "^1.5.5", + "@lezer/common": "^1.5.6", "@lezer/highlight": "^1.2.5", "@lezer/lr": "^1.4.10", "@ungap/custom-elements": "^1.3.0", @@ -163,7 +163,7 @@ "@codemirror/search": "^6.7.1", "@codemirror/state": "^6.7.6", "@codemirror/view": "^6.43.14", - "@lezer/common": "^1.5.5", + "@lezer/common": "^1.5.6", "@lezer/lr": "^1.4.10", "tar": "^7.5.22" }, diff --git a/platforms/android/app/src/main/java/com/foxdebug/acode/sdcard/WorkspaceIndex.java b/platforms/android/app/src/main/java/com/foxdebug/acode/sdcard/WorkspaceIndex.java index fca431d..eb23a64 100644 --- a/platforms/android/app/src/main/java/com/foxdebug/acode/sdcard/WorkspaceIndex.java +++ b/platforms/android/app/src/main/java/com/foxdebug/acode/sdcard/WorkspaceIndex.java @@ -1009,8 +1009,11 @@ private void runSearch(Job job, JSONObject options, Callback callback) } if ("replace".equals(mode)) { - String replacement = Matcher.quoteReplacement(replace == null ? "" : replace); - String text = pattern.matcher(new SearchInput(content, job)).replaceAll(replacement); + String replacement = replace == null ? "" : replace; + Matcher matcher = pattern.matcher(new SearchInput(content, job)); + String text = searchOptions.optBoolean("regExp", false) + ? replaceAllJs(matcher, content, replacement) + : matcher.replaceAll(Matcher.quoteReplacement(replacement)); JSONObject result = baseEvent(job.id, "replace-result"); result.put("file", file); result.put("text", text); @@ -1026,6 +1029,135 @@ private void runSearch(Job job, JSONObject options, Callback callback) send(callback, baseEvent(job.id, "replace".equals(mode) ? "done-replacing" : "done-searching"), false); } + /** + * Replaces every match using JavaScript String.prototype.replace substitution + * rules ($$, $&, $`, $', $1..$99, $), so regex replacements behave the + * same as the JS worker path. + */ + static String replaceAllJs(Matcher matcher, String content, String replace) { + StringBuilder out = new StringBuilder(content.length()); + boolean namedGroups = hasNamedGroups(matcher.pattern().pattern()); + int last = 0; + while (matcher.find()) { + out.append(content, last, matcher.start()); + appendJsSubstitution(out, matcher, content, replace, namedGroups); + last = matcher.end(); + } + out.append(content, last, content.length()); + return out.toString(); + } + + /** + * Whether the pattern declares a named capture group, ignoring escaped text, + * \Q...\E quotes and character classes. + */ + static boolean hasNamedGroups(String pattern) { + int len = pattern.length(); + int classDepth = 0; + for (int i = 0; i < len; i++) { + char c = pattern.charAt(i); + if (c == '\\') { + if (i + 1 < len && pattern.charAt(i + 1) == 'Q') { + int end = pattern.indexOf("\\E", i + 2); + if (end == -1) return false; + i = end + 1; + } else { + i++; + } + } else if (classDepth > 0) { + if (c == '[') classDepth++; + else if (c == ']') classDepth--; + } else if (c == '[') { + classDepth = 1; + if (i + 1 < len && pattern.charAt(i + 1) == '^') i++; + if (i + 1 < len && pattern.charAt(i + 1) == ']') i++; + } else if ( + c == '(' && + i + 3 < len && + pattern.charAt(i + 1) == '?' && + pattern.charAt(i + 2) == '<' && + Character.isLetter(pattern.charAt(i + 3)) + ) { + return true; + } + } + return false; + } + + private static void appendJsSubstitution( + StringBuilder out, + Matcher matcher, + String content, + String replace, + boolean namedGroups + ) { + int groups = matcher.groupCount(); + int len = replace.length(); + for (int i = 0; i < len; i++) { + char c = replace.charAt(i); + if (c != '$' || i + 1 >= len) { + out.append(c); + continue; + } + + char next = replace.charAt(i + 1); + if (next == '$') { + out.append('$'); + i++; + } else if (next == '&') { + out.append(content, matcher.start(), matcher.end()); + i++; + } else if (next == '`') { + out.append(content, 0, matcher.start()); + i++; + } else if (next == '\'') { + out.append(content, matcher.end(), content.length()); + i++; + } else if (next >= '0' && next <= '9') { + int index = next - '0'; + int consumed = 1; + if (i + 2 < len) { + char digit = replace.charAt(i + 2); + if (digit >= '0' && digit <= '9') { + int twoDigit = index * 10 + (digit - '0'); + if (twoDigit >= 1 && twoDigit <= groups) { + index = twoDigit; + consumed = 2; + } + } + } + if (index >= 1 && index <= groups) { + String group = matcher.group(index); + if (group != null) out.append(group); + i += consumed; + } else { + out.append(c); + } + } else if (next == '<') { + int close = replace.indexOf('>', i + 2); + boolean found = false; + String group = null; + if (close != -1) { + try { + group = matcher.group(replace.substring(i + 2, close)); + found = true; + } catch (IllegalArgumentException ignored) { + // JS: an unknown name is empty when the pattern has named groups. + found = namedGroups; + } + } + if (found) { + if (group != null) out.append(group); + i = close; + } else { + out.append(c); + } + } else { + out.append(c); + } + } + } + private Pattern compileSearchPattern(String search, JSONObject options) throws PatternSyntaxException { boolean regExp = options.optBoolean("regExp", false); diff --git a/platforms/ios/runner/lib/workspace/WorkspaceMatches.swift b/platforms/ios/runner/lib/workspace/WorkspaceMatches.swift index b94eae4..230a2f2 100644 --- a/platforms/ios/runner/lib/workspace/WorkspaceMatches.swift +++ b/platforms/ios/runner/lib/workspace/WorkspaceMatches.swift @@ -14,7 +14,8 @@ final class WorkspaceMatches { func search(_ emit: ([[String: Any]], Bool) -> Void) throws { var batch: [[String: Any]] = [] var count = 0, cursor = 0, row = 0, column = 0 - try enumerate { range in + try enumerate { match in + let range = match.range if count == 5000 { emit(batch, true); batch.removeAll(); return false } let word = self.source.substring(with: NSRange(location: range.location, length: min(160, range.length))) try self.advance(to: range.location, cursor: &cursor, row: &row, column: &column) @@ -28,25 +29,25 @@ final class WorkspaceMatches { if !batch.isEmpty { emit(batch, false) } } - func replace(_ replacement: String) throws -> String { + func replace(_ replacement: WorkspaceReplacement) throws -> String { let result = NSMutableString(capacity: source.length) var cursor = 0 - try enumerate { range in - result.append(self.source.substring(with: NSRange(location: cursor, length: range.location - cursor))) - result.append(replacement) - cursor = NSMaxRange(range) + try enumerate { match in + result.append(self.source.substring(with: NSRange(location: cursor, length: match.range.location - cursor))) + result.append(replacement.expand(match, in: self.source)) + cursor = NSMaxRange(match.range) return true } result.append(source.substring(from: cursor)) return result as String } - private func enumerate(_ match: (NSRange) throws -> Bool) throws { + private func enumerate(_ match: (NSTextCheckingResult) throws -> Bool) throws { var failure: Error? regex.enumerateMatches(in: text, options: [.reportProgress], range: NSRange(location: 0, length: source.length)) { result, flags, stop in do { try self.check() - if let result, try !match(result.range) { stop.pointee = true } + if let result, try !match(result) { stop.pointee = true } if flags.contains(.internalError) { throw WorkspaceFailure("Regular expression failed") } } catch { failure = error; stop.pointee = true } } diff --git a/platforms/ios/runner/lib/workspace/WorkspaceReplacement.swift b/platforms/ios/runner/lib/workspace/WorkspaceReplacement.swift new file mode 100644 index 0000000..33679bd --- /dev/null +++ b/platforms/ios/runner/lib/workspace/WorkspaceReplacement.swift @@ -0,0 +1,116 @@ +import Foundation + +/// Expands a replacement the way JavaScript's String.prototype.replace does +/// ($$, $&, $`, $', $1..$99, $), so native regex replacements match the +/// JS worker path. +struct WorkspaceReplacement { + let template: NSString + let groupNames: Set + let literal: Bool + + init(_ template: String, pattern: String, regExp: Bool) { + self.template = template as NSString + literal = !regExp + groupNames = regExp ? Self.groupNames(in: pattern) : [] + } + + func expand(_ match: NSTextCheckingResult, in source: NSString) -> String { + if literal { return template as String } + let out = NSMutableString(capacity: template.length) + let groups = match.numberOfRanges - 1 + let dollar: unichar = 36 + var index = 0 + while index < template.length { + let char = template.character(at: index) + guard char == dollar, index + 1 < template.length else { + out.append(template.substring(with: NSRange(location: index, length: 1))) + index += 1 + continue + } + let next = template.character(at: index + 1) + switch next { + case dollar: + out.append("$"); index += 2 + case 38: // & + out.append(source.substring(with: match.range)); index += 2 + case 96: // ` + out.append(source.substring(to: match.range.location)); index += 2 + case 39: // ' + out.append(source.substring(from: NSMaxRange(match.range))); index += 2 + case 48...57: + var group = Int(next) - 48 + var consumed = 1 + if index + 2 < template.length, case 48...57 = template.character(at: index + 2) { + let twoDigit = group * 10 + Int(template.character(at: index + 2)) - 48 + if twoDigit >= 1 && twoDigit <= groups { group = twoDigit; consumed = 2 } + } + if group >= 1 && group <= groups { + append(match.range(at: group), from: source, to: out) + index += 1 + consumed + } else { + out.append("$"); index += 1 + } + case 60 where !groupNames.isEmpty: // < + let close = template.range(of: ">", range: NSRange(location: index + 2, length: template.length - index - 2)) + guard close.location != NSNotFound else { out.append("$"); index += 1; continue } + let name = template.substring(with: NSRange(location: index + 2, length: close.location - index - 2)) + // JS: an unknown name expands to nothing once the pattern has named groups. + if groupNames.contains(name) { append(match.range(withName: name), from: source, to: out) } + index = close.location + 1 + default: + out.append("$"); index += 1 + } + } + return out as String + } + + private func append(_ range: NSRange, from source: NSString, to out: NSMutableString) { + if range.location != NSNotFound { out.append(source.substring(with: range)) } + } + + /// Named capture groups declared by the pattern, ignoring escaped text, + /// \Q...\E quotes and character classes. + static func groupNames(in pattern: String) -> Set { + let chars = Array(pattern.utf16) + var names = Set() + var classDepth = 0 + var index = 0 + while index < chars.count { + let char = chars[index] + if char == 92 { // backslash + if index + 1 < chars.count && chars[index + 1] == 81 { // Q + guard let end = quoteEnd(chars, from: index + 2) else { return names } + index = end + 1 + } else { + index += 1 + } + } else if classDepth > 0 { + if char == 91 { classDepth += 1 } else if char == 93 { classDepth -= 1 } + } else if char == 91 { // [ + classDepth = 1 + if index + 1 < chars.count && chars[index + 1] == 94 { index += 1 } + if index + 1 < chars.count && chars[index + 1] == 93 { index += 1 } + } else if char == 40, index + 3 < chars.count, chars[index + 1] == 63, chars[index + 2] == 60, isLetter(chars[index + 3]) { + var end = index + 3 + while end < chars.count && chars[end] != 62 { end += 1 } + names.insert(String(decoding: chars[(index + 3).. Int? { + var index = start + while index + 1 < chars.count { + if chars[index] == 92 && chars[index + 1] == 69 { return index } + index += 1 + } + return nil + } + + private static func isLetter(_ char: UInt16) -> Bool { + (65...90).contains(char) || (97...122).contains(char) + } +} diff --git a/platforms/ios/runner/lib/workspace/WorkspaceSearch.swift b/platforms/ios/runner/lib/workspace/WorkspaceSearch.swift index f88b263..dcc2263 100644 --- a/platforms/ios/runner/lib/workspace/WorkspaceSearch.swift +++ b/platforms/ios/runner/lib/workspace/WorkspaceSearch.swift @@ -11,6 +11,7 @@ extension WorkspaceIndex { if settings["wholeWord"] as? Bool == true { pattern = "\\b" + pattern + "\\b" } let flags: NSRegularExpression.Options = settings["caseSensitive"] as? Bool == true ? [.anchorsMatchLines] : [.anchorsMatchLines, .caseInsensitive] let regex = try NSRegularExpression(pattern: pattern, options: flags) + let replacement = WorkspaceReplacement(options["replace"] as? String ?? "", pattern: pattern, regExp: settings["regExp"] as? Bool == true) let files = try searchFiles(options) let content = WorkspaceContent(database: db) let overlays = options["overlays"] as? [String: String] ?? [:] @@ -32,8 +33,8 @@ extension WorkspaceIndex { } catch { try job.check(); continue } let matches = WorkspaceMatches(text: text, regex: regex, job: job) if replacing { - let replacement = try matches.replace(options["replace"] as? String ?? "") - job.emit("replace-result", ["file": file, "text": replacement], false) + let text = try matches.replace(replacement) + job.emit("replace-result", ["file": file, "text": text], false) } else { try matches.search { results, limited in let data: [String: Any] = ["file": file, "matches": results, "limited": limited] diff --git a/platforms/ios/runnerTests/WorkspaceReplacementTests.swift b/platforms/ios/runnerTests/WorkspaceReplacementTests.swift new file mode 100644 index 0000000..950b2c4 --- /dev/null +++ b/platforms/ios/runnerTests/WorkspaceReplacementTests.swift @@ -0,0 +1,43 @@ +import XCTest +@testable import runner + +final class WorkspaceReplacementTests: XCTestCase { + func testExpandsJavaScriptSubstitutions() throws { + XCTAssertEqual(try replace("foo bar", #"(\w+) (\w+)"#, "$2 $1"), "bar foo") + XCTAssertEqual(try replace("ab", "a", "[$&]"), "[a]b") + XCTAssertEqual(try replace("xay", "a", "$`|$'"), "xx|yy") + XCTAssertEqual(try replace("a", "a", "$$1"), "$1") + XCTAssertEqual(try replace("abcdefghijk", "(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)", "$11-$10-$1"), "k-j-a") + XCTAssertEqual(try replace("ab", "(a)(b)", "$3$0"), "$3$0") + } + + func testNamedGroups() throws { + XCTAssertEqual(try replace("2026-11", #"(?\d+)-(?\d+)"#, "$/$"), "11/2026") + XCTAssertEqual(try replace("a", "(?a)", "[$]"), "[]") + XCTAssertEqual(try replace("a", "(a)", "$"), "$") + XCTAssertEqual(try replace("a", "[(?)]?(a)", "$"), "$") + XCTAssertEqual(try replace("a", #"\Q(?\E|(a)"#, "$"), "$") + } + + func testLiteralModeLeavesReplacementUntouched() throws { + let regex = try NSRegularExpression(pattern: NSRegularExpression.escapedPattern(for: "a")) + let source = "a" as NSString + let match = try XCTUnwrap(regex.firstMatch(in: source as String, range: NSRange(location: 0, length: source.length))) + XCTAssertEqual(WorkspaceReplacement("$&$1", pattern: "a", regExp: false).expand(match, in: source), "$&$1") + } + + private func replace(_ text: String, _ pattern: String, _ template: String) throws -> String { + let regex = try NSRegularExpression(pattern: pattern) + let source = text as NSString + let replacement = WorkspaceReplacement(template, pattern: pattern, regExp: true) + let out = NSMutableString() + var cursor = 0 + for match in regex.matches(in: text, range: NSRange(location: 0, length: source.length)) { + out.append(source.substring(with: NSRange(location: cursor, length: match.range.location - cursor))) + out.append(replacement.expand(match, in: source)) + cursor = NSMaxRange(match.range) + } + out.append(source.substring(from: cursor)) + return out as String + } +} diff --git a/postcss.config.js b/postcss.config.js index c7db4e5..b0df55d 100644 --- a/postcss.config.js +++ b/postcss.config.js @@ -1,5 +1,6 @@ -module.exports = { - plugins: [ - require('autoprefixer')({}) - ] -}; \ No newline at end of file +module.exports = { + plugins: [ + require('./utils/postcss/colorMixSupports'), + require('autoprefixer')({}) + ] +}; diff --git a/src/cm/baseExtensions.ts b/src/cm/baseExtensions.ts index c429b20..4ea778b 100644 --- a/src/cm/baseExtensions.ts +++ b/src/cm/baseExtensions.ts @@ -20,6 +20,7 @@ import { crosshairCursor, drawSelection, dropCursor, + EditorView, highlightActiveLine, highlightActiveLineGutter, highlightSpecialChars, @@ -49,6 +50,30 @@ export interface BaseExtensionOptions { highlightSelectionMatches?: boolean; } +/** + * Android draws its native selection handles for a DOM selection inside + * the editor even after focus moves to a menu or page over it, so they + * float above the ⋮ menu or Settings and can still be dragged there + * (Acode issue #3059). Focus leaving the editor doesn't clear the DOM + * selection, so this does. With `drawSelection()` the visible selection + * is CodeMirror's own layer and stays; CodeMirror writes the DOM selection + * again from its state when the editor gets focus back. + */ +const releaseNativeSelection = EditorView.domEventHandlers({ + blur(_event, view) { + // Focus leaving the app (backgrounded) keeps it as it was. + if (!document.hasFocus()) return false; + const selection = document.getSelection(); + if ( + selection?.rangeCount && + view.contentDOM.contains(selection.anchorNode) + ) { + selection.removeAllRanges(); + } + return false; + }, +}); + /** * Base extensions roughly matching the useful parts of CodeMirror's basicSetup */ @@ -77,7 +102,9 @@ export default function createBaseExtensions( indentationFolding, ); } - if (!canvas) extensions.push(drawSelection(), dropCursor()); + if (!canvas) { + extensions.push(drawSelection(), dropCursor(), releaseNativeSelection); + } extensions.push(EditorState.allowMultipleSelections.of(true)); if (autoIndent) extensions.push(indentOnInput()); extensions.push( diff --git a/src/cm/canvasOptions.ts b/src/cm/canvasOptions.ts index fdaaac5..b25c505 100644 --- a/src/cm/canvasOptions.ts +++ b/src/cm/canvasOptions.ts @@ -3,13 +3,12 @@ import { CanvasView, type CanvasViewConfig, type FontSpec, + parseColor, type TokenStyleSpec, } from "@acode.app/canvas-view"; -import { HighlightStyle } from "@codemirror/language"; -import { oneDark } from "@codemirror/theme-one-dark"; import { tags as t } from "@lezer/highlight"; import { getRainbowBracketColors } from "cm/rainbowBrackets"; -import { getThemeById, getThemeConfig, getThemeExtensions } from "cm/themes"; +import { getThemeById, getThemeConfig } from "cm/themes"; /** * Maps Acode's editor settings and themes to @acode.app/canvas-view options. @@ -33,6 +32,7 @@ interface ThemeConfig { activeLine?: string; lineNumber?: string; lineNumberActive?: string; + gutterBorder?: string; matchingBracket?: string; selectionMatch?: string; [color: string]: unknown; @@ -68,40 +68,6 @@ function clampSetting( return Math.min(Math.max(Math.round(number), min), max); } -/** - * Find the HighlightStyle a theme passes to `syntaxHighlighting()`, by - * walking its extension tree (arrays, precedence wrappers, compartments, - * `facet.of(value)` providers). Returns null for themes that compute their - * highlighter (`themeType`) or don't have one. - */ -export function findHighlightStyle( - extension: unknown, - seen = new Set(), -): HighlightStyle | null { - if (!extension || typeof extension !== "object" || seen.has(extension)) { - return null; - } - seen.add(extension); - if (extension instanceof HighlightStyle) return extension; - if (Array.isArray(extension)) { - for (const item of extension) { - const found = findHighlightStyle(item, seen); - if (found) return found; - } - return null; - } - const node = extension as { - value?: unknown; - inner?: unknown; - extension?: unknown; - }; - return ( - findHighlightStyle(node.value, seen) || - findHighlightStyle(node.inner, seen) || - findHighlightStyle(node.extension, seen) - ); -} - /** Token colors from a theme config, for themes without a HighlightStyle. */ function highlightFromConfig(config: ThemeConfig): TokenStyleSpec[] { const color = (key: string) => @@ -128,53 +94,121 @@ function highlightFromConfig(config: ThemeConfig): TokenStyleSpec[] { return specs.filter((spec) => spec.color); } -/** - * Decoration colors the canvas draws natively, as the themes' CSS has them: - * selection matches use the theme's `selectionMatch`, else its selection. - */ -function themeClasses(config: ThemeConfig): CanvasThemeSpec["classes"] { - const classes: NonNullable = {}; - if (config.matchingBracket) { - classes["cm-matchingBracket"] = { background: config.matchingBracket }; - } - const selectionMatch = config.selectionMatch || config.selection; - if (selectionMatch) { - classes["cm-selectionMatch"] = { background: selectionMatch }; - } - return Object.keys(classes).length ? classes : undefined; -} +/** What `CanvasView`'s `theme` option and `setTheme` take. */ +export type CanvasThemeSource = NonNullable; /** - * The canvas theme for an Acode editor theme: colors from its config, syntax - * colors from the HighlightStyle in its extensions. The theme's - * EditorView.theme stays in the state, where it styles the DOM UI (tooltips, - * panels, autocomplete). + * The canvas theme for an Acode editor theme. canvas-view resolves the + * colors itself from the theme's own CSS (the `EditorView.theme` and + * highlight style in the state: background, text, cursor, selection, active + * line fill or frame, gutter, line numbers, matching brackets, selection + * matches), like the DOM editor shows them, and again when the theme + * compartment changes. The CSS is the only source for those: a theme's + * config doesn't override it, so both renderers draw a theme the same. + * This adds what the CSS doesn't say: Acode's own scrollbars, a + * see-through canvas over a picture, the gutter border and config-only + * syntax colors. */ -export function getCanvasTheme(themeId: string): CanvasThemeSpec { +export function getCanvasTheme( + themeId: string, + seeThrough = false, +): CanvasThemeSource { // Resolve ids like getThemeExtensions does ("one-dark" -> "one_dark"). const theme = getThemeById(themeId) || getThemeById(String(themeId).replace(/-/g, "_")); const config = (theme?.config || getThemeConfig(themeId) || {}) as ThemeConfig; - const highlight = - findHighlightStyle(getThemeExtensions(themeId, [oneDark])) || - highlightFromConfig(config); - return { - dark: config.dark !== false, - background: config.background || "#282c34", - foreground: config.foreground || "#abb2bf", - selection: config.selection, - cursor: config.cursor, - activeLine: config.activeLine, - // Like the DOM themes, which give the active gutter line no background. - activeLineGutter: config.background, - gutterForeground: config.lineNumber, - gutterActiveForeground: config.lineNumberActive, - // Acode draws its own (draggable) scrollbars over the editor. - scrollbar: "transparent", - highlight, - classes: themeClasses(config), + // Only used for a theme without a highlight style in its extensions. + const highlight = highlightFromConfig(config); + return (css: CanvasThemeSpec): CanvasThemeSpec => { + const framed = !!css.activeLineBorder; + return { + ...css, + ...(highlight.length ? { highlight } : null), + // With a picture behind the editor, the canvas is see-through. The + // editor element keeps the theme's CSS background under the + // picture, and sticky lines take it from there. + background: seeThrough ? "transparent" : css.background, + activeLine: + seeThrough && !framed + ? translucentActiveLine(css.activeLine, css.foreground) + : css.activeLine, + // Like the DOM themes, which give the active gutter line no background. + activeLineGutter: seeThrough + ? "transparent" + : (css.activeLineGutter ?? css.background), + gutterBackground: seeThrough ? undefined : css.gutterBackground, + // A line between the gutter and the code, when the theme asks. + gutterBorder: config.gutterBorder ?? css.gutterBorder, + // Acode draws its own (draggable) scrollbars over the editor. + scrollbar: "transparent", + }; + }; +} + +/** + * An active line that lets a picture behind the editor show: the theme's + * own when it already does, otherwise the text color at 8% (what the + * Backdrop plugin gives `.cm-activeLine` in the DOM editor). + */ +function translucentActiveLine( + activeLine: string | undefined, + foreground: string, +): string { + if (activeLine && parseColor(activeLine) >>> 24 < 255) return activeLine; + const c = parseColor(foreground); + return `rgba(${c & 255}, ${(c >>> 8) & 255}, ${(c >>> 16) & 255}, 0.08)`; +} + +/** + * Whether something draws a picture behind the editor's text, as the + * Backdrop plugin does with `.cm-editor::before` (the DOM editor's text has + * no background of its own, so it shows). A canvas view then needs a + * see-through background. Reads computed style: call it outside frames. + */ +export function hasPictureBehind(view: CanvasView): boolean { + if (!view.dom.isConnected) return false; + const before = getComputedStyle(view.dom, "::before"); + return ( + before.content !== "none" && + before.content !== "normal" && + before.display !== "none" && + before.backgroundImage !== "none" && + Number(before.opacity) > 0 + ); +} + +/** + * Call `onChange` (at most once per frame) when style sheets are added, + * removed or rewritten, which is how plugins restyle the editor (Backdrop + * keeps one `