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
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

A native spreadsheet app for the Mac and iPad, written entirely in Swift. Native file format
is XLSX; CSV imports and exports. The formula engine covers Google Sheets'
core feature set — 157 functions, real coercion semantics, incremental
core feature set — 158 functions, real coercion semantics, incremental
recalculation. The spreadsheet stack (model, formula engine, XLSX/ZIP/CSV I/O,
grid) is built from scratch with no third-party libraries; the sole external
dependency is [Sparkle](https://sparkle-project.org) for software updates
Expand Down Expand Up @@ -158,7 +158,7 @@ cd iOS && xcodegen && open SimpleSpread.xcodeproj # the iPad app
testing strategy, roadmap.
- [docs/RESEARCH.md](docs/RESEARCH.md) — the feature-set research (formula
semantics, XLSX internals, editing UX, CSV) the implementation follows.
- [docs/FUNCTIONS.md](docs/FUNCTIONS.md) — all 157 functions with semantics
- [docs/FUNCTIONS.md](docs/FUNCTIONS.md) — all 158 functions with semantics
notes and known deviations.
- [docs/PIVOTS.md](docs/PIVOTS.md) — using pivot tables: creating, the
Fields panel, grouping, refreshing, and Excel features not supported.
Expand Down
53 changes: 53 additions & 0 deletions Sources/SpreadsheetCore/CalculationEngine.swift
Original file line number Diff line number Diff line change
Expand Up @@ -423,6 +423,59 @@ public final class CalculationEngine {
asts[addr] != nil || workbook.sheet(withID: addr.sheetID)?.cells[addr.address]?.formula != nil
}

// MARK: Hyperlinks

/// True if the cell's formula is a HYPERLINK call (the grid draws it as a link).
public func isHyperlink(at addr: AbsoluteAddress) -> Bool {
hyperlinkTarget(at: addr) != nil
}

/// The URL a HYPERLINK formula at `addr` opens, or nil. Only a formula
/// whose outermost call is HYPERLINK is a link (as in Google Sheets); the
/// URL argument is evaluated in the cell's context, so it follows the
/// cells it reads.
public func hyperlinkURL(at addr: AbsoluteAddress) -> URL? {
guard let target = hyperlinkTarget(at: addr) else { return nil }
let context = EvalContext(workbook: workbook, sheetID: addr.sheetID, address: addr.address, clock: clock)
guard case .string(let text) = FormulaEvaluator.evaluate(target, context: context) else { return nil }
return Self.hyperlinkURL(from: text)
}

/// A link's text as a URL a click may open: `http://` is assumed when
/// there's no scheme (as in Sheets), and only web and mail links are
/// allowed, so a workbook can't launch files or other apps.
public static func hyperlinkURL(from text: String) -> URL? {
let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)
guard !trimmed.isEmpty, !trimmed.contains(where: \.isWhitespace) else { return nil }
let lower = trimmed.lowercased()
let hasScheme = ["http://", "https://", "mailto:"].contains { lower.hasPrefix($0) }
// Any other "scheme:" is refused rather than read as a host; a colon
// and digits after a host name are a port ("example.com:8080").
if !hasScheme, let colon = lower.firstIndex(of: ":") {
let host = lower[..<colon]
let isPort = (host.contains(".") || host == "localhost")
&& lower[lower.index(after: colon)...].first?.isNumber == true
if !isPort { return nil }
}
guard let url = URL(string: hasScheme ? trimmed : "http://" + trimmed),
let scheme = url.scheme?.lowercased(), ["http", "https", "mailto"].contains(scheme) else { return nil }
if scheme != "mailto", url.host?.isEmpty ?? true { return nil }
return url
}

/// The URL argument of the cell's outermost HYPERLINK call.
private func hyperlinkTarget(at addr: AbsoluteAddress) -> FormulaExpr? {
var expr = asts[addr]
while let e = expr {
switch e {
case .paren(let inner), .definedName(_, let inner): expr = inner
case .function("HYPERLINK", let args) where !args.isEmpty: return args[0]
default: return nil
}
}
return nil
}

// MARK: Graph maintenance

private func installFormula(_ text: String, at addr: AbsoluteAddress, replacing: Bool = true) {
Expand Down
9 changes: 9 additions & 0 deletions Sources/SpreadsheetCore/FunctionsText.swift
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,15 @@ enum TextFunctions {
withTemplate: replacement)
return .string(result)
},
// The label (or the URL); the grid opens the URL from the formula
// (CalculationEngine.hyperlinkURL). A number label stays a number.
.eager("HYPERLINK", min: 1, max: 2) { args, _ in
let url = try strArg(args[0])
guard args.count > 1 else { return .string(url) }
let label = try args[1].toScalar()
if case .error(let e) = label { throw e }
return label.isEmpty ? .string(url) : label
},
]

private static func joinAll(_ args: [EvalValue], separator: String) throws -> String {
Expand Down
12 changes: 9 additions & 3 deletions Sources/SpreadsheetUI/Mac/SpreadsheetGridView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,11 @@ final class SpreadsheetGridView: NSView, NSTextFieldDelegate {
}
window?.makeFirstResponder(self)
let point = convert(event.locationInWindow, from: nil)
// ⌘-click opens a HYPERLINK cell; a plain click only selects it.
if event.modifierFlags.contains(.command), let url = controller.hyperlink(at: point) {
LinkOpener.open(url)
return
}
let result = controller.press(at: point, extend: event.modifierFlags.contains(.shift),
clickCount: event.clickCount)
if case .showFilter(let columnOffset, let cell) = result {
Expand All @@ -117,11 +122,12 @@ final class SpreadsheetGridView: NSView, NSTextFieldDelegate {

// MARK: Context menu

/// Right-click on a chart (edit, copy, delete), or on a row/column
/// header (insert, delete, hide or unhide).
/// Right-click on a chart (edit, copy, delete), on a row/column
/// header (insert, delete, hide or unhide), or on a link cell (open, copy).
override func menu(for event: NSEvent) -> NSMenu? {
let point = convert(event.locationInWindow, from: nil)
guard let sections = controller.chartMenu(at: point) ?? controller.headerMenu(at: point) else {
let link = controller.hyperlink(at: point).map { [controller.linkMenuItems(for: $0)] }
guard let sections = controller.chartMenu(at: point) ?? controller.headerMenu(at: point) ?? link else {
return nil
}
let menu = NSMenu()
Expand Down
10 changes: 10 additions & 0 deletions Sources/SpreadsheetUI/Shared/Clipboard.swift
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,16 @@ enum SystemPasteboard {
#endif
}

/// Plain text alone (a copied link).
static func write(text: String) {
#if os(macOS)
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(text, forType: .string)
#else
UIPasteboard.general.string = text
#endif
}

/// A picture (a copied chart), as PNG.
static func write(png: Data) {
#if os(macOS)
Expand Down
22 changes: 22 additions & 0 deletions Sources/SpreadsheetUI/Shared/GridController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -454,6 +454,28 @@ final class GridController {
let action: () -> Void
}

/// The URL of the HYPERLINK formula in the cell at a view point (the
/// top-left cell of a merge), or nil.
func hyperlink(at point: CGPoint) -> URL? {
guard document != nil else { return nil }
let geometry = self.geometry
guard geometry.region(at: point) == .cells, chart(at: point) == nil else { return nil }
return hyperlink(in: geometry.address(at: point))
}

/// The URL of the HYPERLINK formula in a cell of the active sheet, or nil.
func hyperlink(in address: CellAddress) -> URL? {
guard let document else { return nil }
let cell = document.activeSheet.mergedRange(containing: address)?.start ?? address
return document.engine.hyperlinkURL(at: AbsoluteAddress(sheetID: document.activeSheetID, address: cell))
}

/// "Open Link" and "Copy Link" for a link cell's context menu.
func linkMenuItems(for url: URL) -> [MenuItem] {
[MenuItem(title: "Open Link") { LinkOpener.open(url) },
MenuItem(title: "Copy Link") { SystemPasteboard.write(text: url.absoluteString) }]
}

/// The menu for a right-click (or long press) on a row or column
/// header: insert, delete, hide or unhide, in sections. Like Excel,
/// pressing outside the current selection selects that row/column
Expand Down
6 changes: 6 additions & 0 deletions Sources/SpreadsheetUI/Shared/GridRenderer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -544,6 +544,12 @@ struct GridRenderer {
.foregroundColor: Self.textColor(for: style),
]
if style.underline { attributes[.underlineStyle] = NSUnderlineStyle.single.rawValue }
// A HYPERLINK formula looks like a link unless the cell sets its own colour.
if cell.formula != nil, cell.value.errorValue == nil,
document.engine.isHyperlink(at: AbsoluteAddress(sheetID: document.activeSheetID, address: address)) {
attributes[.underlineStyle] = NSUnderlineStyle.single.rawValue
if style.textColor == nil { attributes[.foregroundColor] = SystemColors.link }
}
if style.strikethrough { attributes[.strikethroughStyle] = NSUnderlineStyle.single.rawValue }

let paragraph = NSMutableParagraphStyle()
Expand Down
14 changes: 14 additions & 0 deletions Sources/SpreadsheetUI/Shared/Platform.swift
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ enum SystemColors {
static var controlBackground: PlatformColor { .controlBackgroundColor }
static var separator: PlatformColor { .separatorColor }
static var accent: PlatformColor { .controlAccentColor }
static var link: PlatformColor { .linkColor }
static var text: PlatformColor { .textColor }
static var label: PlatformColor { .labelColor }
static var secondaryLabel: PlatformColor { .secondaryLabelColor }
Expand All @@ -42,6 +43,7 @@ enum SystemColors {
static var controlBackground: PlatformColor { .systemBackground }
static var separator: PlatformColor { .separator }
static var accent: PlatformColor { .tintColor }
static var link: PlatformColor { .link }
static var text: PlatformColor { .label }
static var label: PlatformColor { .label }
static var secondaryLabel: PlatformColor { .secondaryLabel }
Expand All @@ -60,6 +62,18 @@ enum SystemColors {
}
}

/// Opening a link from a cell in the default browser or mail app.
@MainActor
enum LinkOpener {
static func open(_ url: URL) {
#if os(macOS)
NSWorkspace.shared.open(url)
#else
UIApplication.shared.open(url)
#endif
}
}

extension PlatformColor {
/// A cell's stored colour.
convenience init(rgba c: RGBAColor) {
Expand Down
3 changes: 2 additions & 1 deletion Sources/SpreadsheetUI/iOS/GridView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -671,7 +671,8 @@ extension GridView: UIContextMenuInteractionDelegate {
if SpreadsheetDocument.pasteboardHasContent {
clipboard.append(Item(title: "Paste") { [weak c] in c?.paste() })
}
return [
let link = c.document.flatMap { c.hyperlink(in: $0.selection.activeCell) }
return (link.map { [c.linkMenuItems(for: $0)] } ?? []) + [
clipboard,
[doc("Fill Down") { $0.fillDown() },
doc("Fill Right") { $0.fillRight() },
Expand Down
30 changes: 30 additions & 0 deletions Tests/SpreadsheetCoreTests/CalculationEngineTests.swift
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import Foundation
import Testing
@testable import SpreadsheetCore

Expand Down Expand Up @@ -331,4 +332,33 @@ struct WorkbookOperationTests {
#expect(WorkbookOperations.translatedFormula("A1", byRows: -5, columns: 0) == "#REF!")
#expect(WorkbookOperations.translatedFormula("1+", byRows: 1, columns: 0) == "1+") // unparseable unchanged
}

// MARK: Hyperlinks

@Test func hyperlinkURLFollowsTheFormula() {
let h = Harness(cells: ["A1": "https://example.com/a", "B1": "=HYPERLINK(A1,\"Link\")",
"B2": "=(HYPERLINK(\"example.com:8080/x\"))", "B3": "=UPPER(HYPERLINK(A1))",
"B4": "=A1"])
func url(_ a1: String) -> URL? {
h.engine.hyperlinkURL(at: AbsoluteAddress(sheetID: h.sheetID, address: CellAddress(a1: a1)!))
}
#expect(url("B1")?.absoluteString == "https://example.com/a")
#expect(url("B2")?.absoluteString == "http://example.com:8080/x") // no scheme: http
#expect(url("B3") == nil) // HYPERLINK isn't the outermost call
#expect(url("B4") == nil)
#expect(url("A1") == nil)
#expect(h.engine.isHyperlink(at: AbsoluteAddress(sheetID: h.sheetID, address: CellAddress(a1: "B1")!)))
h.set("A1", "https://example.org/b")
#expect(url("B1")?.absoluteString == "https://example.org/b")
}

@Test func hyperlinkURLAllowsOnlyWebAndMailLinks() {
#expect(CalculationEngine.hyperlinkURL(from: " HTTPS://example.com ")?.absoluteString == "HTTPS://example.com")
#expect(CalculationEngine.hyperlinkURL(from: "mailto:someone@example.com") != nil)
#expect(CalculationEngine.hyperlinkURL(from: "www.example.com")?.absoluteString == "http://www.example.com")
for refused in ["javascript:alert(1)", "file:///etc/passwd", "ftp://example.com", "tel:123",
"x-apple-reminder://", "", "two words", "https://"] {
#expect(CalculationEngine.hyperlinkURL(from: refused) == nil, "\(refused)")
}
}
}
10 changes: 10 additions & 0 deletions Tests/SpreadsheetCoreTests/FunctionLogicalTextTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,16 @@ struct LogicalFunctionTests {

@Suite("Text functions")
struct TextFunctionTests {
@Test func hyperlinkShowsItsLabel() {
#expect(evalString("HYPERLINK(\"https://example.com\",\"Example\")") == "Example")
#expect(evalString("HYPERLINK(\"https://example.com\")") == "https://example.com")
#expect(evalString("HYPERLINK(\"https://example.com\",A1)") == "https://example.com") // blank label
#expect(evalNumber("HYPERLINK(\"https://example.com\",42)") == 42)
#expect(evalError("HYPERLINK(1/0,\"x\")") == .div0)
#expect(evalError("HYPERLINK(\"https://example.com\",NA())") == .na)
#expect(evalString("HYPERLINK(A1,\"Docs\")", cells: ["A1": "example.com"]) == "Docs")
}

@Test func concatenateAndJoin() {
#expect(evalString("CONCATENATE(\"a\",\"b\",1)") == "ab1")
#expect(evalString("CONCAT(\"x\",\"y\")") == "xy")
Expand Down
14 changes: 14 additions & 0 deletions Tests/SpreadsheetFilesTests/XLSXTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,20 @@ struct XLSXRoundTripTests {
}
}

@Test func hyperlinkFormulaRoundTripsWithoutPrefix() throws {
let wb = Workbook.newDocument()
let engine = CalculationEngine(workbook: wb)
let addr = AbsoluteAddress(sheetID: wb.sheets[0].id, address: CellAddress(a1: "A1")!)
engine.setCellFormula("HYPERLINK(\"https://example.com\",\"Example\")", at: addr)
let data = try XLSXWriter.data(for: wb)
let xml = String(decoding: try ZipArchiveReader(data: data).contents(named: "xl/worksheets/sheet1.xml"), as: UTF8.self)
#expect(xml.contains("HYPERLINK"))
#expect(!xml.contains("_xlfn.HYPERLINK"))
let read = try roundTrip(wb)
#expect(read.sheets[0].cell(at: addr.address).formula == "HYPERLINK(\"https://example.com\",\"Example\")")
#expect(read.sheets[0].value(at: addr.address) == .string("Example"))
}

@Test func formulasRoundTripWithCachedValues() throws {
let wb = Workbook.newDocument()
let engine = CalculationEngine(workbook: wb)
Expand Down
18 changes: 18 additions & 0 deletions Tests/SpreadsheetUITests/GridEditingTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,24 @@ struct GridEditingTests {
keyCode: keyCode)!
}

// MARK: Hyperlinks

@Test func hyperlinkIsFoundUnderThePointer() {
let (doc, grid) = makeGrid()
doc.commitInput("=HYPERLINK(\"https://example.com\",\"Example\")", at: a("B2"))
doc.commitInput("plain", at: a("C2"))
let geometry = grid.controller.geometry
func center(_ a1: String) -> CGPoint {
let rect = geometry.cellRect(a(a1))
return CGPoint(x: rect.midX, y: rect.midY)
}
#expect(grid.controller.hyperlink(at: center("B2"))?.absoluteString == "https://example.com")
#expect(grid.controller.hyperlink(at: center("C2")) == nil)
#expect(grid.controller.hyperlink(in: a("B2")) != nil)
#expect(grid.controller.linkMenuItems(for: URL(string: "https://example.com")!).map(\.title)
== ["Open Link", "Copy Link"])
}

// MARK: The editor's target (#7)

@Test func editCommitsToTheSheetItWasTypedOn() {
Expand Down
4 changes: 2 additions & 2 deletions docs/APP-STORE-LISTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ Rules this text follows:

Can be changed at any time without a new build.

Open Excel files, work them with 157 functions, then chart and pivot the results, in an app that starts in under a second. One purchase covers Mac and iPad.
Open Excel files, work them with 158 functions, then chart and pivot the results, in an app that starts in under a second. One purchase covers Mac and iPad.

## Keywords (100)

Expand All @@ -46,7 +46,7 @@ aren't repeated.
• Imports CSV safely: it works out the delimiter and the text encoding, keeps leading zeros, and never runs a formula hidden in the data.

FORMULAS
• 157 functions, including SUMIFS, XLOOKUP, VLOOKUP, INDEX and MATCH, TEXTJOIN, NETWORKDAYS and IRR.
• 158 functions, including SUMIFS, XLOOKUP, VLOOKUP, INDEX and MATCH, TEXTJOIN, NETWORKDAYS and IRR.
• The same results and rules as Google Sheets, with Excel's operator precedence.
• Fill handle, Fill Down and Fill Right, with references that adjust as they should.

Expand Down
5 changes: 3 additions & 2 deletions docs/FUNCTIONS.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# SimpleSpread — Function Reference

157 built-in functions. Names are case-insensitive; arguments in square
158 built-in functions. Names are case-insensitive; arguments in square
brackets are optional; `...` is variadic. Semantics follow Google Sheets /
Excel shared behavior (see docs/RESEARCH.md for the coercion and criteria
rules that apply across all functions).
Expand Down Expand Up @@ -94,7 +94,7 @@ Rules that apply across the library:
| TRUE(), FALSE() | |
| SWITCH(subject, case1, val1, ..., [default]) | Case-insensitive equality; lazy |

## Text (26)
## Text (27)

| Function | Notes |
|---|---|
Expand All @@ -117,6 +117,7 @@ Rules that apply across the library:
| CHAR(n), CODE(text) | Unicode scalars |
| T(value) | Text passes through, else "" |
| REGEXMATCH / REGEXEXTRACT / REGEXREPLACE(text, pattern, [replacement]) | ICU regex (NSRegularExpression), not RE2; EXTRACT returns first capture group if present, miss → #N/A; REPLACE supports $1 templates |
| HYPERLINK(url, [link_label]) | Shows the label (or the URL when it's omitted or blank; a number label stays a number). The cell is drawn as a link; ⌘-click it on the Mac, or use Open Link in its context menu, to open the URL. Only when HYPERLINK is the formula's outermost call. A URL without a scheme gets `http://`; only http, https and mailto links open |

## Date & time (24)

Expand Down
2 changes: 1 addition & 1 deletion docs/PLAN.md
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ Sources/
FormulaEvaluator.swift EvalValue, resolved ranges, operator semantics
Coercion.swift the coercion table + criteria evaluator
FunctionRegistry.swift registry, GridArg, shared arg helpers
Functions*.swift 9 category files, 157 functions
Functions*.swift 9 category files, 158 functions
CalculationEngine.swift dependency graph, dirty propagation, cycles
RangeDependencyIndex.swift large-range dependents: per-column interval trees
WorkbookOperations.swift structural edits with formula rewriting
Expand Down
2 changes: 1 addition & 1 deletion docs/RESEARCH.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ real-world formulas use only operators plus a small set — SUM, IF, NOW,
AVERAGE, VLOOKUP, ROUND, TODAY, MONTH/YEAR, ISERROR, INDEX/MATCH. ~25
functions cover >90% of usage; ~120 covers essentially everything a
non-specialist writes. **Conclusion: invest in operator/coercion correctness
and the high-traffic functions before breadth.** SimpleSpread ships 157.
and the high-traffic functions before breadth.** SimpleSpread ships 158.

### Coercion table (the part clones get wrong)
- Arithmetic operators and *direct literal* arguments coerce: TRUE→1,
Expand Down
Loading