55 lines
2.3 KiB
Swift
55 lines
2.3 KiB
Swift
// ScratchSyntaxHighlighterTests.swift
|
|
// Lyrebird
|
|
//
|
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
|
// SPDX-License-Identifier: MIT
|
|
|
|
#if os(macOS)
|
|
import Testing
|
|
import AppKit
|
|
@testable import LyrebirdLiveCompileUI
|
|
|
|
@Suite("ScratchSyntaxHighlighter")
|
|
@MainActor
|
|
struct ScratchSyntaxHighlighterTests {
|
|
|
|
private func color(_ storage: NSTextStorage, at index: Int) -> NSColor? {
|
|
storage.attribute(.foregroundColor, at: index, effectiveRange: nil) as? NSColor
|
|
}
|
|
|
|
@Test func paintsTokenColorsOntoStorage() {
|
|
let source: String = "let x = 1 // note"
|
|
let storage: NSTextStorage = NSTextStorage(string: source)
|
|
let base: [NSAttributedString.Key: Any] = [.foregroundColor: NSColor.labelColor]
|
|
ScratchSyntaxHighlighter.apply(to: storage, baseAttributes: base)
|
|
|
|
let ns: NSString = source as NSString
|
|
// Keyword, number, comment each get their kind's color.
|
|
#expect(color(storage, at: ns.range(of: "let").location)
|
|
== ScratchSyntaxHighlighter.color(for: .keyword))
|
|
#expect(color(storage, at: ns.range(of: "1").location)
|
|
== ScratchSyntaxHighlighter.color(for: .number))
|
|
#expect(color(storage, at: ns.range(of: "// note").location)
|
|
== ScratchSyntaxHighlighter.color(for: .comment))
|
|
// A plain identifier keeps the base color.
|
|
#expect(color(storage, at: ns.range(of: "x").location) == NSColor.labelColor)
|
|
}
|
|
|
|
@Test func reapplyNormalizesAwayStaleColors() {
|
|
// Edit the source so a previously-colored keyword becomes a plain
|
|
// identifier; re-applying must reset it to the base color, not leave the
|
|
// old keyword color behind.
|
|
let storage: NSTextStorage = NSTextStorage(string: "let value = 1")
|
|
let base: [NSAttributedString.Key: Any] = [.foregroundColor: NSColor.labelColor]
|
|
ScratchSyntaxHighlighter.apply(to: storage, baseAttributes: base)
|
|
// "let" -> "lot" (no longer a keyword).
|
|
let ns0: NSString = "let value = 1" as NSString
|
|
storage.replaceCharacters(in: ns0.range(of: "let"), with: "lot")
|
|
ScratchSyntaxHighlighter.apply(to: storage, baseAttributes: base)
|
|
let ns1: NSString = storage.string as NSString
|
|
#expect(color(storage, at: ns1.range(of: "lot").location) == NSColor.labelColor)
|
|
}
|
|
}
|
|
|
|
#endif
|