Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions DOM/Sources/DOM.swift
Original file line number Diff line number Diff line change
Expand Up @@ -257,9 +257,11 @@ extension DOM {
case ideographic
case textBeforeEdge = "text-before-edge"
case textAfterEdge = "text-after-edge"
/// the parent's value; `alignment-baseline` is not inherited otherwise
case inherit

/// A value, with the aliases SVG 1.1 and CSS Inline 3 give some of them. nil for `inherit`
/// and unknown values, which leave the inherited baseline.
/// A value, with the aliases SVG 1.1 and CSS Inline 3 give some of them. nil for unknown
/// values, which leave the inherited baseline.
package init?(css value: String) {
switch value.trimmingCharacters(in: .whitespaces).lowercased() {
case "auto", "baseline", "use-script": self = .auto
Expand Down
24 changes: 17 additions & 7 deletions DOM/Sources/Parser.XML.Element.swift
Original file line number Diff line number Diff line change
Expand Up @@ -348,15 +348,25 @@ extension XMLParser {
return result
}

/// The `marker` shorthand sets `marker-start`, `marker-mid` and `marker-end` (SVG 2 §11.6.4).
/// It is a CSS property only, not a presentation attribute; expanded in place so a later
/// longhand still overrides it, and an earlier one is overridden.
/// The `marker` shorthand sets `marker-start`, `marker-mid` and `marker-end` (SVG 2 §11.6.4), and
/// `font` sets `font-style`, `font-weight`, `font-size` and `font-family` (CSS Fonts 4 §2.8).
/// They are CSS properties only, not presentation attributes (SVG 2 §6.6); expanded in place so a
/// later longhand still overrides them, and an earlier one is overridden. An invalid `font` is dropped.
static func expandingShorthands(_ declarations: [CSSDeclaration]) -> [CSSDeclaration] {
guard declarations.contains(where: { $0.name == "marker" }) else { return declarations }
guard declarations.contains(where: { $0.name == "marker" || $0.name == "font" }) else { return declarations }
return declarations.flatMap { d -> [CSSDeclaration] in
guard d.name == "marker" else { return [d] }
return ["marker-start", "marker-mid", "marker-end"].map {
CSSDeclaration(name: $0, value: d.value, important: d.important)
switch d.name {
case "marker":
return ["marker-start", "marker-mid", "marker-end"].map {
CSSDeclaration(name: $0, value: d.value, important: d.important)
}
case "font":
let value = XMLParser.Attributes.removingImportant(from: d.value)
return (parseFontShorthand(value) ?? []).map {
CSSDeclaration(name: $0.name, value: $0.value, important: d.important)
}
default:
return [d]
}
}
}
Expand Down
166 changes: 166 additions & 0 deletions DOM/Sources/Parser.XML.FontShorthand.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
//
// Parser.XML.FontShorthand.swift
// SwiftDraw
//
// Created by Simon Whitty on 18/11/26.
// Copyright 2026 Simon Whitty
//
// Distributed under the permissive zlib license
// Get the latest version from here:
//
// https://github.com/swhitty/SwiftDraw
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//

import Foundation

extension XMLParser {

/// The longhands of the CSS `font` shorthand (CSS Fonts 4 §2.8):
/// `[ <font-style> || <font-variant-css2> || <font-weight> || <font-stretch-css3> ]? <font-size> [ / <line-height> ]? <font-family>`,
/// or a system font keyword. The parts it leaves out are reset to their initial values. Only the
/// longhands SwiftDraw draws are returned (`font-variant`, `font-stretch` and `line-height` are
/// checked but dropped). nil when the value is invalid, so the declaration is ignored.
static func parseFontShorthand(_ value: String) -> [(name: String, value: String)]? {
let text = value.trimmingCharacters(in: .whitespacesAndNewlines)
let lowercased = text.lowercased()

// system fonts: the platform's UI font, approximated by 13px sans-serif as macOS draws it
if systemFontKeywords.contains(lowercased) {
return longhands(style: "normal", weight: "normal", size: "13px", family: "sans-serif")
}

var style: String?
var variant: String?
var weight: String?
var stretch: String?

var tokens = Tokens(text)
var preambleCount = 0
while let token = tokens.peek() {
let word = token.lowercased()
let next = tokens.peek(offset: 1)
if word == "normal" {
// `normal` sets whichever of the four is still unset to its initial value
guard preambleCount < 4 else { return nil }
} else if style == nil, word == "italic" || word == "oblique" {
style = word
// `oblique <angle>`: drawn as oblique
if word == "oblique", let angle = next, isAngle(angle) {
tokens.advance()
}
} else if variant == nil, word == "small-caps" {
variant = word
} else if weight == nil, isWeight(word), next != nil, DOM.FontWeight(word) != nil {
// a unitless number is a weight when a size still follows it
weight = word
} else if stretch == nil, stretchKeywords.contains(word) {
stretch = word
} else {
break
}
preambleCount += 1
guard preambleCount <= 4 else { return nil }
tokens.advance()
}

// <font-size> [ / <line-height> ]?
guard let sizeToken = tokens.peek() else { return nil }
tokens.advance()
let sizeParts = sizeToken.split(separator: "/", maxSplits: 1, omittingEmptySubsequences: false).map(String.init)
let size = sizeParts[0]
guard DOM.FontSize(size) != nil else { return nil }
if sizeParts.count == 2 {
// `12px/1.5` or `12px/ 1.5`
if sizeParts[1].isEmpty {
guard tokens.peek() != nil else { return nil }
tokens.advance()
}
} else if let slash = tokens.peek(), slash.hasPrefix("/") {
// `12px /1.5` or `12px / 1.5`
tokens.advance()
if slash == "/" {
guard tokens.peek() != nil else { return nil }
tokens.advance()
}
}

let family = tokens.remainder.trimmingCharacters(in: .whitespacesAndNewlines)
guard !family.isEmpty else { return nil }

return longhands(style: style ?? "normal", weight: weight ?? "normal", size: size, family: family)
}

private static func longhands(style: String, weight: String, size: String, family: String) -> [(name: String, value: String)] {
[("font-style", style), ("font-weight", weight), ("font-size", size), ("font-family", family)]
}

private static let systemFontKeywords: Set<String> = [
"caption", "icon", "menu", "message-box", "small-caption", "status-bar"
]

private static let stretchKeywords: Set<String> = [
"ultra-condensed", "extra-condensed", "condensed", "semi-condensed",
"semi-expanded", "expanded", "extra-expanded", "ultra-expanded"
]

private static func isWeight(_ word: String) -> Bool {
switch word {
case "bold", "bolder", "lighter": return true
default: return Double(word) != nil
}
}

private static func isAngle(_ token: String) -> Bool {
let token = token.lowercased()
for unit in ["deg", "grad", "rad", "turn"] where token.hasSuffix(unit) {
return Double(token.dropLast(unit.count)) != nil
}
return false
}

/// Whitespace-separated words of the value, keeping the unscanned rest (the family list) as written.
private struct Tokens {
private let text: Substring
private var position: Substring.Index

init(_ text: String) {
self.text = Substring(text)
self.position = self.text.startIndex
}

/// The words from the current position, the first `offset + 1` of them
private func words(_ count: Int) -> [Substring] {
Array(text[position...].split(whereSeparator: \.isWhitespace).prefix(count))
}

func peek(offset: Int = 0) -> String? {
let words = words(offset + 1)
return words.count > offset ? String(words[offset]) : nil
}

mutating func advance() {
guard let word = words(1).first else { return }
position = word.endIndex
}

var remainder: Substring { text[position...] }
}
}
134 changes: 134 additions & 0 deletions DOM/Tests/Parser.FontShorthandTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
//
// Parser.FontShorthandTests.swift
// SwiftDraw
//
// Distributed under the permissive zlib license
// Get the latest version from here:
//
// https://github.com/swhitty/SwiftDraw
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would be
// appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not be
// misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//

@testable import SwiftDrawDOM
@testable import SwiftDrawDOM
import Foundation
import Testing

/// The CSS `font` shorthand (CSS Fonts 4 §2.8)
struct ParserFontShorthandTests {

private typealias Longhands = [String]

private func longhands(_ value: String) -> Longhands? {
XMLParser.parseFontShorthand(value)?.map { "\($0.name): \($0.value)" }
}

@Test(arguments: [
// matplotlib's SVG output with svg.fonttype='none'
("12px 'DejaVu Sans'", ["normal", "normal", "12px", "'DejaVu Sans'"]),
("italic bold 20px/1.5 Helvetica, sans-serif", ["italic", "bold", "20px", "Helvetica, sans-serif"]),
("bold italic 20px serif", ["italic", "bold", "20px", "serif"]),
("small-caps 650 condensed 2em monospace", ["normal", "650", "2em", "monospace"]),
("oblique 10deg 12px serif", ["oblique", "normal", "12px", "serif"]),
("normal normal 12px serif", ["normal", "normal", "12px", "serif"]),
("12px / 2 serif", ["normal", "normal", "12px", "serif"]),
("12px/ 2 serif", ["normal", "normal", "12px", "serif"]),
("12px /2 serif", ["normal", "normal", "12px", "serif"]),
("x-large \"Times New Roman\"", ["normal", "normal", "x-large", "\"Times New Roman\""]),
("0 serif", ["normal", "normal", "0", "serif"]),
// system fonts
("menu", ["normal", "normal", "13px", "sans-serif"]),
("Caption", ["normal", "normal", "13px", "sans-serif"]),
] as [(String, [String])])
func expandsToLonghands(value: String, expected: [String]) {
let names = ["font-style", "font-weight", "font-size", "font-family"]
#expect(longhands(value) == zip(names, expected).map { "\($0): \($1)" })
}

@Test(arguments: [
"", "serif", "12px", "bold serif", "-12px serif", "12px/ serif", "big serif",
"italic italic 12px serif", "normal normal normal normal normal 12px serif", "inherit"
])
func rejectsInvalidValues(value: String) {
#expect(longhands(value) == nil)
}

private func element(_ body: String) throws -> DOM.GraphicsElement {
let svg = try DOM.SVG.parse(xml: """
<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">\(body)</svg>
""")
return try #require(svg.childElements.last)
}

@Test
func styleAttributeSetsTheLonghands() throws {
let text = try element(#"<text style="font: italic bold 12px 'DejaVu Sans'">a</text>"#)
#expect(text.style.fontStyle == .italic)
#expect(text.style.fontWeight == .bold)
#expect(text.style.fontSize == .length(12))
#expect(text.style.fontFamily == [.name("DejaVu Sans")])
}

// parts left out are reset to their initial values, overriding inherited and earlier ones
@Test
func resetsTheOmittedParts() throws {
let text = try element(#"<text style="font-weight: bold; font: 12px serif">a</text>"#)
#expect(text.style.fontWeight == .normal)
#expect(text.style.fontStyle == .normal)
}

@Test
func laterLonghandOverridesTheShorthand() throws {
let text = try element(#"<text style="font: 12px serif; font-weight: bold">a</text>"#)
#expect(text.style.fontWeight == .bold)
#expect(text.style.fontSize == .length(12))
}

@Test
func invalidShorthandIsIgnored() throws {
let text = try element(#"<text style="font-size: 10px; font: bold serif">a</text>"#)
#expect(text.style.fontSize == .length(10))
#expect(text.style.fontWeight == nil)
}

@Test
func stylesheetRuleSetsTheLonghands() throws {
let text = try element(#"<style>text { font: bold 30px monospace }</style><text>a</text>"#)
let matched = try #require(text.matchedStyle)
#expect(matched.attributes.fontWeight == .bold)
#expect(matched.attributes.fontSize == .length(30))
#expect(matched.attributes.fontFamily == [.keyword(.monospace)])
}

// SVG 2 §6.6: shorthands are not presentation attributes
@Test
func isNotAPresentationAttribute() throws {
let text = try element(#"<text font="bold 30px monospace">a</text>"#)
#expect(text.attributes.fontSize == nil)
#expect(text.attributes.fontWeight == nil)
}

// em lengths of the element resolve against the shorthand's size
@Test
func sizeSetsTheFontSizeOfEmLengths() throws {
let text = try #require(try element(#"<text style="font: 20px serif" x="2em">a</text>"#) as? DOM.Text)
#expect(text.x == 40)
}
}
29 changes: 29 additions & 0 deletions Samples.bundle/text-filter.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Loading