Commit c0705d8719

c0705d8719597acbf63c1fce6418bbbe2bf30c8d

parent: 36835f99e6

Verified · cmc

cmc <hello@cleberg.net> · 2026-10-22 23:09 UTC

Add Qlty config; fix diff header crash; share repeated views

- UnifiedDiff read every token of a hunk header as a range, including the
  enclosing-code text after the closing @@: a lone "-" there crashed the
  parser, and a "-5" renumbered the hunk. Only the two ranges are read now.
- A "+ " bullet under a paragraph was absorbed into it; it ends the
  paragraph like "- " and "* " do.
- Issue and MR comments share one ThreadComment model and CommentsSection
  view; MilestoneMenu, AddField, ListToolbar and DeleteSection replace
  copies across screens; Binding.isPresent replaces 28 hand-built
  optional-presentation bindings.
- Merge gates are computed as MRDetail.Gates.rows; splitMarkdownMath,
  swiftMath, UnifiedDiff.parse, the markdown list parser and several view
  sections split into helpers. Parse, split, TeX and diff output match
  main on 15k markdown and 7k diff inputs.
- Qlty: switch statements excluded from Swift duplication,
  return_statements and file_complexity disabled.

Layout: unified · split

.qlty/.gitignore added +7
@@ -0,0 +1,7 @@
1*
2!configs
3!configs/**
4!hooks
5!hooks/**
6!qlty.toml
7!.gitignore
.qlty/qlty.toml added +48
@@ -0,0 +1,48 @@
1config_version = "0"
2
3exclude_patterns = [
4 "**/vendor/**",
5 "**/node_modules/**",
6 "**/testdata/**",
7 "**/dist/**",
8 "**/.build/**",
9 "**/build/**",
10 "**/*.min.*",
11 "**/generated/**",
12 ".claude/**",
13 "**/Pods/**",
14]
15
16test_patterns = [
17 "**/test/**",
18 "**/tests/**",
19 "**/Tests/**",
20 "**/*_test.*",
21 "**/test_*.*",
22 "**/*.test.*",
23 "**/*Tests.swift",
24 "e2e/**",
25]
26
27[[source]]
28name = "default"
29default = true
30
31[[plugin]]
32name = "osv-scanner"
33
34[[plugin]]
35name = "trufflehog"
36
37# Early returns are guard clauses, which keep the happy path unindented.
38[smells.return_statements]
39enabled = false
40
41# Total file complexity is the sum of its functions, which function_complexity
42# already checks.
43[smells.file_complexity]
44enabled = false
45
46# Exhaustive switch-over-enum lookup tables share shape but not content.
47[language.swift.smells.duplication]
48filter_patterns = ["(import_declaration _)", "(switch_statement _)"]
gitbay/Issues/IssueModels.swift +1 −25
@@ -44,29 +44,5 @@ nonisolated struct IssueDetail: Decodable, Sendable, Hashable {
4444
4545 var isOpen: Bool { state == "open" }
4646
47 nonisolated struct Comment: Decodable, Sendable, Hashable, Identifiable {
48 /// What `--comment` names. Absent from a server older than v1.39.0.
49 let commentID: Int64?
50 let author: String
51 let body: String
52 let bodyFormat: String?
53 let createdAt: Date
54 let reactions: [ReactionCount]?
55 /// "system" for a line the server posted (a retarget, a queued
56 /// merge), which takes no reactions (krz/gitbay#332).
57 let kind: String?
58
59 enum CodingKeys: String, CodingKey {
60 case author, body, reactions, kind
61 case commentID = "id"
62 case bodyFormat = "body_format"
63 case createdAt = "created_at"
64 }
65
66 /// A server without `kind` names the author "system" on those lines;
67 /// an account can carry that name too, so `kind` wins when present.
68 var isSystem: Bool { kind.map { $0 == "system" } ?? (author == "system") }
69
70 var id: String { author + createdAt.timeIntervalSince1970.description + body }
71 }
47 typealias Comment = ThreadComment
7248}
gitbay/Issues/ThreadComment.swift added +28
@@ -0,0 +1,28 @@
1import Foundation
2
3/// A comment on an issue or a merge request; the two decode alike.
4nonisolated struct ThreadComment: Decodable, Sendable, Hashable, Identifiable {
5 /// What `--comment` names. Absent from a server older than v1.39.0.
6 let commentID: Int64?
7 let author: String
8 let body: String
9 let bodyFormat: String?
10 let createdAt: Date
11 let reactions: [ReactionCount]?
12 /// "system" for a line the server posted (a retarget, a queued
13 /// merge), which takes no reactions (krz/gitbay#332).
14 let kind: String?
15
16 enum CodingKeys: String, CodingKey {
17 case author, body, reactions, kind
18 case commentID = "id"
19 case bodyFormat = "body_format"
20 case createdAt = "created_at"
21 }
22
23 /// A server without `kind` names the author "system" on those lines;
24 /// an account can carry that name too, so `kind` wins when present.
25 var isSystem: Bool { kind.map { $0 == "system" } ?? (author == "system") }
26
27 var id: String { author + createdAt.timeIntervalSince1970.description + body }
28}
gitbay/MRs/MRModels.swift +50 −25
@@ -227,6 +227,55 @@ nonisolated struct MRDetail: Decodable, Sendable, Hashable {
227227 unmet = try c.decodeIfPresent([String].self, forKey: .unmet) ?? []
228228 }
229229
230 /// One gate as the merge request shows it: met or not, and what it says.
231 nonisolated struct Row: Hashable, Sendable {
232 let met: Bool
233 let text: String
234 }
235
236 /// The gates this repository sets, each met or not; fast-forward is always judged.
237 var rows: [Row] {
238 var rows: [Row] = []
239 if draft {
240 rows.append(Row(met: false, text: "Draft — not asking to merge"))
241 }
242 if approvalsRequired > 0 {
243 rows.append(Row(met: approvals.count >= approvalsRequired, text: approvalsText))
244 }
245 if !changesRequested.isEmpty {
246 rows.append(Row(met: false, text: "Changes requested by " + changesRequested.joined(separator: ", ")))
247 }
248 if codeownersRequired {
249 rows += ownersRows
250 }
251 if resolvedRequired {
252 rows.append(Row(met: openThreads == 0, text: threadsText))
253 }
254 if checksRequired {
255 rows.append(Row(met: checks == "success", text: "Checks " + (checks ?? "not reported")))
256 }
257 rows.append(Row(met: fastForward,
258 text: fastForward ? "Fast-forward possible" : "Behind the target — rebase first"))
259 return rows
260 }
261
262 private var approvalsText: String {
263 "\(approvals.count) of \(approvalsRequired) approval\(approvalsRequired == 1 ? "" : "s")"
264 + (approvals.isEmpty ? "" : " — " + approvals.joined(separator: ", "))
265 }
266
267 /// One row per set of files still waiting on its owners, or one met row.
268 private var ownersRows: [Row] {
269 guard !ownersOutstanding.isEmpty else { return [Row(met: true, text: "Code owners approved")] }
270 return ownersOutstanding.map {
271 Row(met: false, text: $0.files.joined(separator: ", ") + " — " + $0.owners.joined(separator: ", "))
272 }
273 }
274
275 private var threadsText: String {
276 openThreads == 0 ? "Threads resolved" : "\(openThreads) thread\(openThreads == 1 ? "" : "s") open"
277 }
278
230279 /// Files whose owners have not approved, and who those owners are.
231280 nonisolated struct Owners: Decodable, Sendable, Hashable, Identifiable {
232281 let files: [String]
@@ -258,31 +307,7 @@ nonisolated struct MRDetail: Decodable, Sendable, Hashable {
258307 var shortSHA: String { String(sha.prefix(10)) }
259308 }
260309
261 nonisolated struct MRComment: Decodable, Sendable, Hashable, Identifiable {
262 /// What `--comment` names. Absent from a server older than v1.39.0.
263 let commentID: Int64?
264 let author: String
265 let body: String
266 let bodyFormat: String?
267 let createdAt: Date
268 let reactions: [ReactionCount]?
269 /// "system" for a line the server posted (a retarget, a queued
270 /// merge), which takes no reactions (krz/gitbay#332).
271 let kind: String?
272
273 enum CodingKeys: String, CodingKey {
274 case author, body, reactions, kind
275 case commentID = "id"
276 case bodyFormat = "body_format"
277 case createdAt = "created_at"
278 }
279
280 /// A server without `kind` names the author "system" on those lines;
281 /// an account can carry that name too, so `kind` wins when present.
282 var isSystem: Bool { kind.map { $0 == "system" } ?? (author == "system") }
283
284 var id: String { author + createdAt.timeIntervalSince1970.description + body }
285 }
310 typealias MRComment = ThreadComment
286311
287312 nonisolated struct Review: Decodable, Sendable, Hashable, Identifiable {
288313 let reviewer: String
gitbay/MRs/UnifiedDiff.swift +65 −59
@@ -95,64 +95,67 @@ nonisolated struct UnifiedDiff: Sendable, Hashable {
9595 var lines = text.components(separatedBy: "\n")[...]
9696
9797 while let line = lines.first {
98 guard line.hasPrefix("diff --git ") else {
99 lines = lines.dropFirst()
100 continue
101 }
10298 lines = lines.dropFirst()
103
104 var oldPath = ""
105 var newPath = ""
106 var isBinary = false
107 var hunks: [Hunk] = []
108
109 // Header lines up to the first hunk or the next file.
110 while let header = lines.first, !header.hasPrefix("diff --git ") {
111 if header.hasPrefix("--- ") {
112 oldPath = Self.stripPrefix(String(header.dropFirst(4)))
113 } else if header.hasPrefix("+++ ") {
114 newPath = Self.stripPrefix(String(header.dropFirst(4)))
115 } else if header.hasPrefix("Binary files ") || header.hasPrefix("GIT binary patch") {
116 isBinary = true
117 } else if header.hasPrefix("@@") {
118 break
119 }
120 lines = lines.dropFirst()
99 if line.hasPrefix("diff --git ") {
100 files.append(parseFile(&lines))
121101 }
102 }
103 return UnifiedDiff(files: files)
104 }
122105
123 // Hunks.
124 while let hunkHeader = lines.first, hunkHeader.hasPrefix("@@") {
125 lines = lines.dropFirst()
126 var (oldNumber, newNumber) = Self.startNumbers(hunkHeader)
127 var hunkLines: [Line] = []
128 loop: while let bodyLine = lines.first {
129 switch bodyLine.first {
130 case "+":
131 hunkLines.append(Line(kind: .addition, oldNumber: nil,
132 newNumber: newNumber, text: String(bodyLine.dropFirst())))
133 newNumber += 1
134 case "-":
135 hunkLines.append(Line(kind: .deletion, oldNumber: oldNumber,
136 newNumber: nil, text: String(bodyLine.dropFirst())))
137 oldNumber += 1
138 case " ":
139 hunkLines.append(Line(kind: .context, oldNumber: oldNumber,
140 newNumber: newNumber, text: String(bodyLine.dropFirst())))
141 oldNumber += 1
142 newNumber += 1
143 case "\\": // "\ No newline at end of file"
144 break
145 default:
146 break loop
147 }
148 lines = lines.dropFirst()
149 }
150 hunks.append(Hunk(header: hunkHeader, lines: hunkLines))
106 /// One file's headers and hunks, from just past its `diff --git` line up
107 /// to the next file.
108 private static func parseFile(_ lines: inout ArraySlice<String>) -> File {
109 var oldPath = ""
110 var newPath = ""
111 var isBinary = false
112
113 // Header lines up to the first hunk or the next file.
114 while let header = lines.first, !header.hasPrefix("diff --git "), !header.hasPrefix("@@") {
115 if header.hasPrefix("--- ") {
116 oldPath = Self.stripPrefix(String(header.dropFirst(4)))
117 } else if header.hasPrefix("+++ ") {
118 newPath = Self.stripPrefix(String(header.dropFirst(4)))
119 } else if header.hasPrefix("Binary files ") || header.hasPrefix("GIT binary patch") {
120 isBinary = true
151121 }
122 lines = lines.dropFirst()
123 }
152124
153 files.append(File(oldPath: oldPath, newPath: newPath, hunks: hunks, isBinary: isBinary))
125 var hunks: [Hunk] = []
126 while let hunkHeader = lines.first, hunkHeader.hasPrefix("@@") {
127 lines = lines.dropFirst()
128 hunks.append(parseHunk(hunkHeader, &lines))
154129 }
155 return UnifiedDiff(files: files)
130 return File(oldPath: oldPath, newPath: newPath, hunks: hunks, isBinary: isBinary)
131 }
132
133 /// The body of the hunk `header` opens, up to the first line that is not
134 /// part of one.
135 private static func parseHunk(_ header: String, _ lines: inout ArraySlice<String>) -> Hunk {
136 var (oldNumber, newNumber) = Self.startNumbers(header)
137 var hunkLines: [Line] = []
138 while let bodyLine = lines.first {
139 let text = String(bodyLine.dropFirst())
140 switch bodyLine.first {
141 case "+":
142 hunkLines.append(Line(kind: .addition, oldNumber: nil, newNumber: newNumber, text: text))
143 newNumber += 1
144 case "-":
145 hunkLines.append(Line(kind: .deletion, oldNumber: oldNumber, newNumber: nil, text: text))
146 oldNumber += 1
147 case " ":
148 hunkLines.append(Line(kind: .context, oldNumber: oldNumber, newNumber: newNumber, text: text))
149 oldNumber += 1
150 newNumber += 1
151 case "\\": // "\ No newline at end of file"
152 break
153 default:
154 return Hunk(header: header, lines: hunkLines)
155 }
156 lines = lines.dropFirst()
157 }
158 return Hunk(header: header, lines: hunkLines)
156159 }
157160
158161 /// "a/path" → "path"; "/dev/null" stays.
@@ -164,16 +167,19 @@ nonisolated struct UnifiedDiff: Sendable, Hashable {
164167 return path
165168 }
166169
167 /// "@@ -12,5 +14,6 @@ …" → (12, 14)
170 /// "@@ -12,5 +14,6 @@ …" → (12, 14). Only the two ranges are read: the
171 /// text after the closing `@@` is the enclosing line of code, and a `-5`
172 /// or a lone `+` in it is not a range.
168173 private static func startNumbers(_ header: String) -> (Int, Int) {
169174 var old = 1
170175 var new = 1
171 let parts = header.split(separator: " ")
172 for part in parts {
173 if part.hasPrefix("-"), let n = Int(part.dropFirst().split(separator: ",")[0]) {
174 old = n
175 } else if part.hasPrefix("+"), let n = Int(part.dropFirst().split(separator: ",")[0]) {
176 new = n
176 let ranges = header.split(separator: " ").dropFirst().prefix { $0 != "@@" }
177 for part in ranges {
178 let start = Int(part.dropFirst().prefix { $0 != "," })
179 if part.hasPrefix("-"), let start {
180 old = start
181 } else if part.hasPrefix("+"), let start {
182 new = start
177183 }
178184 }
179185 return (old, new)
gitbay/Views/Account/AccountView.swift +5 −17
@@ -73,7 +73,7 @@ struct AccountView: View {
7373 .task { await model.loadNotificationPreferences() }
7474 .task { await model.loadEmails() }
7575 .task { model.loadPendingDeletion(username: username) }
76 .alert("Not deleted", isPresented: Binding(get: { deletionRefusal != nil }, set: { if !$0 { deletionRefusal = nil } })) {
76 .alert("Not deleted", isPresented: .isPresent($deletionRefusal)) {
7777 Button("OK", role: .cancel) {}
7878 } message: {
7979 Text(deletionRefusal ?? "")
@@ -96,10 +96,7 @@ struct AccountView: View {
9696 }
9797 .confirmationDialog(
9898 "Remove \(removingEmail?.address ?? "")?",
99 isPresented: Binding(
100 get: { removingEmail != nil },
101 set: { if !$0 { removingEmail = nil } }
102 ),
99 isPresented: .isPresent($removingEmail),
103100 titleVisibility: .visible
104101 ) {
105102 Button("Remove", role: .destructive) {
@@ -145,10 +142,7 @@ struct AccountView: View {
145142 }
146143 .alert(
147144 "Label this key",
148 isPresented: Binding(
149 get: { labellingSSH != nil },
150 set: { if !$0 { labellingSSH = nil } }
151 ),
145 isPresented: .isPresent($labellingSSH),
152146 presenting: labellingSSH
153147 ) { key in
154148 TextField("Label", text: $sshLabelText)
@@ -164,10 +158,7 @@ struct AccountView: View {
164158 }
165159 .alert(
166160 "Remove this SSH key?",
167 isPresented: Binding(
168 get: { removingSSH != nil },
169 set: { if !$0 { removingSSH = nil } }
170 ),
161 isPresented: .isPresent($removingSSH),
171162 presenting: removingSSH
172163 ) { key in
173164 TextField("type \(key.confirmation) to confirm", text: $sshConfirmText)
@@ -184,10 +175,7 @@ struct AccountView: View {
184175 }
185176 .confirmationDialog(
186177 "Remove this PGP key? Commits it signed become unverifiable.",
187 isPresented: Binding(
188 get: { removingPGP != nil },
189 set: { if !$0 { removingPGP = nil } }
190 )
178 isPresented: .isPresent($removingPGP)
191179 ) {
192180 Button("Remove", role: .destructive) {
193181 if let key = removingPGP {
gitbay/Views/Account/TokensView.swift +1 −1
@@ -55,7 +55,7 @@ struct TokensView: View {
5555 }
5656 .confirmationDialog(
5757 revoking.map { "Revoke \($0.name)?" } ?? "",
58 isPresented: Binding(get: { revoking != nil }, set: { if !$0 { revoking = nil } }),
58 isPresented: .isPresent($revoking),
5959 titleVisibility: .visible,
6060 presenting: revoking
6161 ) { token in
gitbay/Views/Account/WebSessionsView.swift +1 −1
@@ -53,7 +53,7 @@ struct WebSessionsView: View {
5353 .navigationBarTitleDisplayMode(.inline)
5454 .confirmationDialog(
5555 "Sign this browser out? It will need to sign in again.",
56 isPresented: Binding(get: { revoking != nil }, set: { if !$0 { revoking = nil } }),
56 isPresented: .isPresent($revoking),
5757 titleVisibility: .visible
5858 ) {
5959 Button("Sign Out", role: .destructive) {
gitbay/Views/Admin/AdminAccountView.swift +1 −1
@@ -80,7 +80,7 @@ struct AdminAccountView: View {
8080 } message: {
8181 Text("Its keys, addresses and sessions go with it. Type the username to confirm.")
8282 }
83 .alert("Not done", isPresented: Binding(get: { refusal != nil }, set: { if !$0 { refusal = nil } })) {
83 .alert("Not done", isPresented: .isPresent($refusal)) {
8484 Button("OK", role: .cancel) {}
8585 } message: {
8686 Text(refusal ?? "")
gitbay/Views/Admin/AdminInstanceViews.swift +1 −1
@@ -170,7 +170,7 @@ struct AdminRunnersView: View {
170170 .navigationBarTitleDisplayMode(.inline)
171171 .confirmationDialog(
172172 removing.map { "Remove \($0.username)'s runner row?" } ?? "",
173 isPresented: Binding(get: { removing != nil }, set: { if !$0 { removing = nil } }),
173 isPresented: .isPresent($removing),
174174 titleVisibility: .visible,
175175 presenting: removing
176176 ) { runner in
gitbay/Views/Admin/AdminReposViews.swift +28 −23
@@ -79,7 +79,7 @@ struct AdminReposView: View {
7979 .refreshable { await model.load() }
8080 .onChange(of: model.visibility) { Task { await model.load() } }
8181 .confirmationDialog(confirming?.title ?? "",
82 isPresented: Binding(get: { confirming != nil }, set: { if !$0 { confirming = nil } }),
82 isPresented: .isPresent($confirming),
8383 titleVisibility: .visible, presenting: confirming) { pending in
8484 Button(pending.action == .makePublic ? "Make public" : "Confirm",
8585 role: pending.action == .makePublic || pending.action == .archive ? .destructive : nil) {
@@ -89,7 +89,7 @@ struct AdminReposView: View {
8989 } message: { pending in
9090 Text(pending.message)
9191 }
92 .alert("Delete \(deleting?.path ?? "")?", isPresented: Binding(get: { deleting != nil }, set: { if !$0 { deleting = nil } }),
92 .alert("Delete \(deleting?.path ?? "")?", isPresented: .isPresent($deleting),
9393 presenting: deleting) { repo in
9494 TextField(repo.path, text: $typed)
9595 .autocorrectionDisabled()
@@ -119,29 +119,34 @@ struct AdminReposView: View {
119119 .foregroundStyle(.secondary)
120120 }
121121 Spacer()
122 Menu {
123 Button(repo.isArchived ? "Unarchive" : "Archive") {
124 confirming = Pending(action: repo.isArchived ? .unarchive : .archive, repo: repo)
125 }
126 Button(repo.visibility == "private" ? "Make public" : "Make private") {
127 confirming = Pending(action: repo.visibility == "private" ? .makePublic : .makePrivate, repo: repo)
128 }
129 Button("Rebuild symbol index") {
130 Task { await model.perform(.reindex, on: repo) }
131 }
132 Divider()
133 Button("Delete", role: .destructive) {
134 typed = ""
135 deleting = repo
136 }
137 } label: {
138 Image(systemName: "ellipsis.circle")
139 .frame(minWidth: 44, minHeight: 44)
122 actions(repo)
123 }
124 }
125
126 private func actions(_ repo: AdminRepo) -> some View {
127 let isPrivate = repo.visibility == "private"
128 return Menu {
129 Button(repo.isArchived ? "Unarchive" : "Archive") {
130 confirming = Pending(action: repo.isArchived ? .unarchive : .archive, repo: repo)
131 }
132 Button(isPrivate ? "Make public" : "Make private") {
133 confirming = Pending(action: isPrivate ? .makePublic : .makePrivate, repo: repo)
134 }
135 Button("Rebuild symbol index") {
136 Task { await model.perform(.reindex, on: repo) }
137 }
138 Divider()
139 Button("Delete", role: .destructive) {
140 typed = ""
141 deleting = repo
140142 }
141 .disabled(model.working)
142 .accessibilityLabel("Actions for \(repo.path)")
143 .accessibilityIdentifier("admin-repo-menu-\(repo.path)")
143 } label: {
144 Image(systemName: "ellipsis.circle")
145 .frame(minWidth: 44, minHeight: 44)
144146 }
147 .disabled(model.working)
148 .accessibilityLabel("Actions for \(repo.path)")
149 .accessibilityIdentifier("admin-repo-menu-\(repo.path)")
145150 }
146151}
147152
gitbay/Views/Admin/AdminUsersView.swift +1 −1
@@ -91,7 +91,7 @@ struct AdminUsersView: View {
9191 }
9292 .alert(
9393 pending.map { "\($0.action.title) \($0.username)?" } ?? "",
94 isPresented: Binding(get: { pending != nil }, set: { if !$0 { pending = nil } }),
94 isPresented: .isPresent($pending),
9595 presenting: pending
9696 ) { pending in
9797 if pending.action.needsTypedName {
gitbay/Views/Builds/BuildDetailView.swift +18 −11
@@ -173,17 +173,7 @@ struct BuildDetailView: View {
173173 ScrollView {
174174 LazyVStack(alignment: .leading, spacing: 0, pinnedViews: [.sectionHeaders]) {
175175 ForEach(sections) { section in
176 if log.stepped {
177 Section {
178 if !query.isEmpty || isOpen(section, in: detail) {
179 lines(section)
180 }
181 } header: {
182 stepHeader(section, in: detail)
183 }
184 } else {
185 lines(section)
186 }
176 logSection(section, in: detail)
187177 }
188178 }
189179 .padding(.bottom, 12)
@@ -198,6 +188,23 @@ struct BuildDetailView: View {
198188 }
199189 }
200190
191 /// A stepped log folds each step under a pinned header; an unstepped one
192 /// is a single run of lines.
193 @ViewBuilder
194 private func logSection(_ section: BuildLog.Section, in detail: BuildDetail) -> some View {
195 if detail.lines.stepped {
196 Section {
197 if !query.isEmpty || isOpen(section, in: detail) {
198 lines(section)
199 }
200 } header: {
201 stepHeader(section, in: detail)
202 }
203 } else {
204 lines(section)
205 }
206 }
207
201208 private func lines(_ section: BuildLog.Section) -> some View {
202209 ForEach(section.lines) { line in
203210 Text(line.text.isEmpty ? " " : line.text)
gitbay/Views/Discovery/ProfileView.swift +59 −49
@@ -119,27 +119,33 @@ struct ProfileView: View {
119119 .font(.gbSans(.subheadline))
120120 .foregroundStyle(.secondary)
121121 }
122 if let website = profile.website, !website.isEmpty,
123 let url = URL(string: website) {
122 profileLinks(profile)
123 }
124 .padding(.vertical, 4)
125 }
126 }
127
128 /// The profile's website, then its other links, each openable.
129 @ViewBuilder
130 private func profileLinks(_ profile: ProfileViewModel.Profile) -> some View {
131 if let website = profile.website, !website.isEmpty,
132 let url = URL(string: website) {
133 Link(destination: url) {
134 Label(website, systemImage: "link")
135 .font(.gbSans(.caption))
136 .lineLimit(1)
137 }
138 }
139 if let links = profile.links, !links.isEmpty {
140 ForEach(Array(links.enumerated()), id: \.offset) { _, link in
141 if let url = URL(string: link.url) {
124142 Link(destination: url) {
125 Label(website, systemImage: "link")
143 Label(link.title, systemImage: "arrow.up.right")
126144 .font(.gbSans(.caption))
127145 .lineLimit(1)
128146 }
129147 }
130 if let links = profile.links, !links.isEmpty {
131 ForEach(Array(links.enumerated()), id: \.offset) { _, link in
132 if let url = URL(string: link.url) {
133 Link(destination: url) {
134 Label(link.title, systemImage: "arrow.up.right")
135 .font(.gbSans(.caption))
136 .lineLimit(1)
137 }
138 }
139 }
140 }
141148 }
142 .padding(.vertical, 4)
143149 }
144150 }
145151
@@ -222,44 +228,48 @@ struct ProfileView: View {
222228 .foregroundStyle(.secondary)
223229 } else {
224230 ForEach(profile.repos) { repo in
225 NavigationLink(value: RepoRoute.repo(repo.path)) {
226 VStack(alignment: .leading, spacing: 3) {
227 HStack(spacing: 6) {
228 Text(repo.name)
229 .font(.gbSans(.subheadline).weight(.medium))
230 if repo.isPrivate {
231 Image(systemName: "lock.fill")
232 .font(.gbSans(.caption2))
233 .foregroundStyle(.secondary)
234 }
235 if repo.isArchived {
236 GBChip("archived", .secondary)
237 }
238 }
239 if let description = repo.description, !description.isEmpty {
240 Text(description)
241 .font(.gbSans(.caption))
242 .foregroundStyle(.secondary)
243 .lineLimit(2)
244 }
245 if let topics = repo.topics, !topics.isEmpty {
246 ScrollView(.horizontal, showsIndicators: false) {
247 HStack(spacing: 6) {
248 ForEach(topics, id: \.self) { topic in
249 GBChip(topic, .gbAccent)
250 }
251 }
252 }
253 }
254 if !repo.meta.isEmpty {
255 Text(repo.meta)
256 .font(.gbSans(.caption2))
257 .foregroundStyle(.secondary)
258 .lineLimit(1)
231 repoRow(repo)
232 }
233 }
234 }
235 }
236
237 private func repoRow(_ repo: ProfileViewModel.Profile.Repo) -> some View {
238 NavigationLink(value: RepoRoute.repo(repo.path)) {
239 VStack(alignment: .leading, spacing: 3) {
240 HStack(spacing: 6) {
241 Text(repo.name)
242 .font(.gbSans(.subheadline).weight(.medium))
243 if repo.isPrivate {
244 Image(systemName: "lock.fill")
245 .font(.gbSans(.caption2))
246 .foregroundStyle(.secondary)
247 }
248 if repo.isArchived {
249 GBChip("archived", .secondary)
250 }
251 }
252 if let description = repo.description, !description.isEmpty {
253 Text(description)
254 .font(.gbSans(.caption))
255 .foregroundStyle(.secondary)
256 .lineLimit(2)
257 }
258 if let topics = repo.topics, !topics.isEmpty {
259 ScrollView(.horizontal, showsIndicators: false) {
260 HStack(spacing: 6) {
261 ForEach(topics, id: \.self) { topic in
262 GBChip(topic, .gbAccent)
259263 }
260264 }
261265 }
262266 }
267 if !repo.meta.isEmpty {
268 Text(repo.meta)
269 .font(.gbSans(.caption2))
270 .foregroundStyle(.secondary)
271 .lineLimit(1)
272 }
263273 }
264274 }
265275 }
gitbay/Views/Discovery/SavedQueriesView.swift +1 −1
@@ -88,7 +88,7 @@ struct SavedQueriesView: View {
8888 }
8989 .confirmationDialog(
9090 removing.map { "Remove \($0.name)?" } ?? "",
91 isPresented: Binding(get: { removing != nil }, set: { if !$0 { removing = nil } }),
91 isPresented: .isPresent($removing),
9292 titleVisibility: .visible,
9393 presenting: removing
9494 ) { query in
gitbay/Views/Issues/IssueListView.swift +2 −20
@@ -44,26 +44,8 @@ struct IssueListView: View {
4444 .navigationTitle("Issues")
4545 .navigationBarTitleDisplayMode(.inline)
4646 .toolbar {
47 ToolbarItem(placement: .topBarTrailing) {
48 Button {
49 filtering = true
50 } label: {
51 Image(systemName: model.filter.isNarrowed
52 ? "line.3.horizontal.decrease.circle.fill"
53 : "line.3.horizontal.decrease.circle")
54 }
55 .accessibilityLabel("Filter")
56 .accessibilityIdentifier("issue-filter-button")
57 }
58 ToolbarItem(placement: .topBarTrailing) {
59 Button {
60 composing = true
61 } label: {
62 Image(systemName: "plus")
63 }
64 .accessibilityLabel("New Issue")
65 .accessibilityIdentifier("issue-create-button")
66 }
47 ListToolbar(filtering: $filtering, composing: $composing, narrowed: model.filter.isNarrowed,
48 newLabel: "New Issue", idPrefix: "issue")
6749 }
6850 .sheet(isPresented: $filtering) {
6951 FilterSheet(
gitbay/Views/Issues/IssueView.swift +7 −76
@@ -135,86 +135,17 @@ struct IssueView: View {
135135 }
136136 }
137137 Section("Milestone") {
138 Menu {
139 Button("None") {
140 Task { await model.setMilestone(nil) }
141 }
142 ForEach(model.availableMilestones ?? []) { milestone in
143 Button("\(milestone.title) (\(milestone.closed)/\(milestone.open + milestone.closed))") {
144 Task { await model.setMilestone(milestone.title) }
145 }
146 }
147 } label: {
148 HStack {
149 Label(issue.milestone ?? "None", systemImage: "flag")
150 .font(.gbSans(.subheadline))
151 Spacer()
152 Image(systemName: "chevron.up.chevron.down")
153 .font(.gbSans(.caption2))
154 .foregroundStyle(.secondary)
155 }
156 }
157 .disabled(model.working)
158 .task { await model.loadMilestones() }
159 .accessibilityIdentifier("milestone-menu")
138 MilestoneMenu(current: issue.milestone, milestones: model.availableMilestones,
139 working: model.working, identifier: "milestone-menu",
140 set: { await model.setMilestone($0) }, load: { await model.loadMilestones() })
160141 }
161142 }
162143
163144 private func commentsSection(_ comments: [IssueDetail.Comment]) -> some View {
164 Section("Comments") {
165 ForEach(comments) { comment in
166 VStack(alignment: .leading, spacing: 4) {
167 HStack {
168 Text(comment.author)
169 .font(.gbSans(.caption).weight(.semibold))
170 Text(comment.createdAt, format: .relative(presentation: .named))
171 .font(.gbSans(.caption))
172 .foregroundStyle(.tertiary)
173 }
174 FormattedBodyView(text: comment.body, format: comment.bodyFormat, repo: model.repoPath)
175 .font(.gbSans(.subheadline))
176 if let id = comment.commentID, !comment.isSystem {
177 ReactionBar(reactions: comment.reactions ?? [], disabled: model.working,
178 idPrefix: "issue-comment-\(id)-reaction") { name in
179 Task { await model.react(name, comment: id) }
180 }
181 }
182 }
183 .padding(.vertical, 2)
184 }
185
186 HStack {
187 TextField("Comment", text: $commentText, axis: .vertical)
188 .lineLimit(1...5)
189 .accessibilityIdentifier("issue-comment-field")
190 Picker("Format", selection: $commentFormat) {
191 Text("Markdown").tag("md")
192 Text("Org").tag("org")
193 }
194 .pickerStyle(.segmented)
195 .labelsHidden()
196 .fixedSize()
197 .accessibilityIdentifier("issue-comment-format")
198 Button {
199 let text = commentText
200 commentText = ""
201 Task { await model.comment(text, format: commentFormat) }
202 } label: {
203 Image(systemName: "arrow.up.circle.fill")
204 .font(.title)
205 .frame(minWidth: 44, minHeight: 44)
206 .contentShape(Rectangle())
207 }
208 .accessibilityLabel("Send comment")
209 .disabled(commentText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
210 || model.working)
211 }
212 if !commentText.isEmpty {
213 MarkupPreview(text: commentText, format: commentFormat,
214 identifier: "issue-comment-preview")
215 .font(.gbSans(.subheadline))
216 }
217 }
145 CommentsSection(comments: comments, repo: model.repoPath, working: model.working,
146 idPrefix: "issue", text: $commentText, format: $commentFormat,
147 react: { await model.react($0, comment: $1) },
148 send: { await model.comment($0, format: $1) })
218149 }
219150
220151 @ToolbarContentBuilder
gitbay/Views/MRs/DiffView.swift +1 −1
@@ -156,7 +156,7 @@ private struct HunkView: View {
156156 .listRowInsets(EdgeInsets(top: 2, leading: 8, bottom: 2, trailing: 8))
157157 .confirmationDialog(
158158 picked.map { "\($0.path):\($0.line)\($0.old ? " (old)" : "")" } ?? "",
159 isPresented: Binding(get: { picked != nil }, set: { if !$0 { picked = nil } }),
159 isPresented: .isPresent($picked),
160160 titleVisibility: .visible,
161161 presenting: picked
162162 ) { draft in
gitbay/Views/MRs/MRListView.swift +2 −20
@@ -37,26 +37,8 @@ struct MRListView: View {
3737 .navigationTitle("Merge requests")
3838 .navigationBarTitleDisplayMode(.inline)
3939 .toolbar {
40 ToolbarItem(placement: .topBarTrailing) {
41 Button {
42 filtering = true
43 } label: {
44 Image(systemName: model.filter.isNarrowed
45 ? "line.3.horizontal.decrease.circle.fill"
46 : "line.3.horizontal.decrease.circle")
47 }
48 .accessibilityLabel("Filter")
49 .accessibilityIdentifier("mr-filter-button")
50 }
51 ToolbarItem(placement: .topBarTrailing) {
52 Button {
53 composing = true
54 } label: {
55 Image(systemName: "plus")
56 }
57 .accessibilityLabel("New Merge Request")
58 .accessibilityIdentifier("mr-create-button")
59 }
40 ListToolbar(filtering: $filtering, composing: $composing, narrowed: model.filter.isNarrowed,
41 newLabel: "New Merge Request", idPrefix: "mr")
6042 }
6143 .sheet(isPresented: $filtering) {
6244 FilterSheet(
gitbay/Views/MRs/MRView.swift +32 −132
@@ -242,26 +242,9 @@ struct MRView: View {
242242
243243 private func milestoneSection(_ mr: MRDetail) -> some View {
244244 Section("Milestone") {
245 Menu {
246 Button("None") { Task { await model.setMilestone(nil) } }
247 ForEach(model.availableMilestones ?? []) { milestone in
248 Button("\(milestone.title) (\(milestone.closed)/\(milestone.open + milestone.closed))") {
249 Task { await model.setMilestone(milestone.title) }
250 }
251 }
252 } label: {
253 HStack {
254 Label(mr.milestone ?? "None", systemImage: "flag")
255 .font(.gbSans(.subheadline))
256 Spacer()
257 Image(systemName: "chevron.up.chevron.down")
258 .font(.gbSans(.caption2))
259 .foregroundStyle(.secondary)
260 }
261 }
262 .disabled(model.working)
263 .task { await model.loadMilestones() }
264 .accessibilityIdentifier("mr-milestone-menu")
245 MilestoneMenu(current: mr.milestone, milestones: model.availableMilestones,
246 working: model.working, identifier: "mr-milestone-menu",
247 set: { await model.setMilestone($0) }, load: { await model.loadMilestones() })
265248 }
266249 }
267250
@@ -270,21 +253,9 @@ struct MRView: View {
270253 RemovableChips(items: mr.labels, idPrefix: "mr-label",
271254 disabled: model.working, color: { model.colors.color($0) },
272255 remove: { label in Task { await model.removeLabel(label) } })
273 HStack {
274 TextField("Add label", text: $editingLabel)
275 .autocorrectionDisabled()
276 .textInputAutocapitalization(.never)
277 .accessibilityIdentifier("mr-label-field")
278 Button {
279 let label = editingLabel.trimmingCharacters(in: .whitespaces)
280 editingLabel = ""
281 Task { await model.addLabel(label) }
282 } label: {
283 Image(systemName: "plus.circle.fill")
284 }
285 .accessibilityLabel("Add label")
286 .disabled(editingLabel.trimmingCharacters(in: .whitespaces).isEmpty || model.working)
287 .accessibilityIdentifier("mr-label-add")
256 AddField(placeholder: "Add label", text: $editingLabel, buttonLabel: "Add label",
257 fieldID: "mr-label-field", buttonID: "mr-label-add", working: model.working) {
258 await model.addLabel($0)
288259 }
289260 }
290261 .task { await model.loadLabels() }
@@ -460,34 +431,9 @@ struct MRView: View {
460431 if let queued = model.state.value?.queued {
461432 queuedRow(queued)
462433 }
463 if gates.draft {
464 gateRow(false, "Draft — not asking to merge")
465 }
466 if gates.approvalsRequired > 0 {
467 gateRow(gates.approvals.count >= gates.approvalsRequired,
468 "\(gates.approvals.count) of \(gates.approvalsRequired) approval\(gates.approvalsRequired == 1 ? "" : "s")"
469 + (gates.approvals.isEmpty ? "" : " — " + gates.approvals.joined(separator: ", ")))
470 }
471 if !gates.changesRequested.isEmpty {
472 gateRow(false, "Changes requested by " + gates.changesRequested.joined(separator: ", "))
473 }
474 if gates.codeownersRequired {
475 if gates.ownersOutstanding.isEmpty {
476 gateRow(true, "Code owners approved")
477 } else {
478 ForEach(gates.ownersOutstanding) { owners in
479 gateRow(false, owners.files.joined(separator: ", ") + " — " + owners.owners.joined(separator: ", "))
480 }
481 }
482 }
483 if gates.resolvedRequired {
484 gateRow(gates.openThreads == 0,
485 gates.openThreads == 0 ? "Threads resolved" : "\(gates.openThreads) thread\(gates.openThreads == 1 ? "" : "s") open")
434 ForEach(Array(gates.rows.enumerated()), id: \.offset) { _, row in
435 gateRow(row.met, row.text)
486436 }
487 if gates.checksRequired {
488 gateRow(gates.checks == "success", "Checks " + (gates.checks ?? "not reported"))
489 }
490 gateRow(gates.fastForward, gates.fastForward ? "Fast-forward possible" : "Behind the target — rebase first")
491437 } header: {
492438 Text("Gates")
493439 } footer: {
@@ -520,24 +466,28 @@ struct MRView: View {
520466 private func reviewsSection(_ reviews: [MRDetail.Review]) -> some View {
521467 Section("Reviews") {
522468 ForEach(reviews) { review in
523 VStack(alignment: .leading, spacing: 2) {
524 HStack {
525 Image(systemName: review.verdict == "approve"
526 ? "checkmark.circle.fill" : "exclamationmark.circle.fill")
527 .foregroundStyle(review.verdict == "approve" ? Color.gbOK : Color.gbWarn)
528 Text(review.reviewer)
529 .font(.gbSans(.subheadline))
530 Spacer()
531 if review.stale {
532 GBChip("stale", .gbWarn)
533 }
534 if !review.counts {
535 GBChip("advisory", .secondary)
536 }
537 }
538 timing(review.createdAt)
469 reviewRow(review)
470 }
471 }
472 }
473
474 private func reviewRow(_ review: MRDetail.Review) -> some View {
475 let approved = review.verdict == "approve"
476 return VStack(alignment: .leading, spacing: 2) {
477 HStack {
478 Image(systemName: approved ? "checkmark.circle.fill" : "exclamationmark.circle.fill")
479 .foregroundStyle(approved ? Color.gbOK : Color.gbWarn)
480 Text(review.reviewer)
481 .font(.gbSans(.subheadline))
482 Spacer()
483 if review.stale {
484 GBChip("stale", .gbWarn)
485 }
486 if !review.counts {
487 GBChip("advisory", .secondary)
539488 }
540489 }
490 timing(review.createdAt)
541491 }
542492 }
543493
@@ -568,60 +518,10 @@ struct MRView: View {
568518 }
569519
570520 private func commentsSection(_ comments: [MRDetail.MRComment]) -> some View {
571 Section("Comments") {
572 ForEach(comments) { comment in
573 VStack(alignment: .leading, spacing: 4) {
574 HStack {
575 Text(comment.author)
576 .font(.gbSans(.caption).weight(.semibold))
577 Text(comment.createdAt, format: .relative(presentation: .named))
578 .font(.gbSans(.caption))
579 .foregroundStyle(.tertiary)
580 }
581 FormattedBodyView(text: comment.body, format: comment.bodyFormat, repo: model.repoPath)
582 .font(.gbSans(.subheadline))
583 if let id = comment.commentID, !comment.isSystem {
584 ReactionBar(reactions: comment.reactions ?? [], disabled: model.working,
585 idPrefix: "mr-comment-\(id)-reaction") { name in
586 Task { await model.react(name, comment: id) }
587 }
588 }
589 }
590 .padding(.vertical, 2)
591 }
592
593 HStack {
594 TextField("Comment", text: $commentText, axis: .vertical)
595 .lineLimit(1...5)
596 .accessibilityIdentifier("mr-comment-field")
597 Picker("Format", selection: $commentFormat) {
598 Text("Markdown").tag("md")
599 Text("Org").tag("org")
600 }
601 .pickerStyle(.segmented)
602 .labelsHidden()
603 .fixedSize()
604 .accessibilityIdentifier("mr-comment-format")
605 Button {
606 let text = commentText
607 commentText = ""
608 Task { await model.comment(text, format: commentFormat) }
609 } label: {
610 Image(systemName: "arrow.up.circle.fill")
611 .font(.title)
612 .frame(minWidth: 44, minHeight: 44)
613 .contentShape(Rectangle())
614 }
615 .accessibilityLabel("Send comment")
616 .disabled(commentText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
617 || model.working)
618 }
619 if !commentText.isEmpty {
620 MarkupPreview(text: commentText, format: commentFormat,
621 identifier: "mr-comment-preview")
622 .font(.gbSans(.subheadline))
623 }
624 }
521 CommentsSection(comments: comments, repo: model.repoPath, working: model.working,
522 idPrefix: "mr", text: $commentText, format: $commentFormat,
523 react: { await model.react($0, comment: $1) },
524 send: { await model.comment($0, format: $1) })
625525 }
626526
627527 @ToolbarContentBuilder
gitbay/Views/Orgs/OrgView.swift +11 −36
@@ -67,7 +67,7 @@ struct OrgView: View {
6767 guard !deleted else { return }
6868 await model.load()
6969 }
70 .alert("Not done", isPresented: Binding(get: { refusal != nil }, set: { if !$0 { refusal = nil } })) {
70 .alert("Not done", isPresented: .isPresent($refusal)) {
7171 Button("OK", role: .cancel) {}
7272 } message: {
7373 Text(refusal ?? "")
@@ -100,10 +100,7 @@ struct OrgView: View {
100100 }
101101 .confirmationDialog(
102102 "Remove \(removingMember?.user ?? "") from \(model.orgName)?",
103 isPresented: Binding(
104 get: { removingMember != nil },
105 set: { if !$0 { removingMember = nil } }
106 )
103 isPresented: .isPresent($removingMember)
107104 ) {
108105 Button("Remove", role: .destructive) {
109106 if let member = removingMember {
@@ -115,10 +112,7 @@ struct OrgView: View {
115112 }
116113 .confirmationDialog(
117114 "Delete team \(deletingTeam ?? "")? Its repo grants go with it.",
118 isPresented: Binding(
119 get: { deletingTeam != nil },
120 set: { if !$0 { deletingTeam = nil } }
121 )
115 isPresented: .isPresent($deletingTeam)
122116 ) {
123117 Button("Delete", role: .destructive) {
124118 if let team = deletingTeam {
@@ -178,18 +172,11 @@ struct OrgView: View {
178172 }
179173
180174 private var deleteSection: some View {
181 Section {
182 Button(role: .destructive) {
183 deleteConfirm = ""
184 deletingOrg = true
185 } label: {
186 Label("Delete organization", systemImage: "trash")
187 .font(.gbSans(.subheadline))
188 }
189 .disabled(model.working)
190 .accessibilityIdentifier("org-delete-button")
191 } footer: {
192 Text("Only an organization that owns no repositories can be deleted.")
175 DeleteSection(title: "Delete organization",
176 footer: "Only an organization that owns no repositories can be deleted.",
177 identifier: "org-delete-button", working: model.working) {
178 deleteConfirm = ""
179 deletingOrg = true
193180 }
194181 }
195182
@@ -225,21 +212,9 @@ struct OrgView: View {
225212 }
226213 }
227214 }
228 HStack {
229 TextField("New team", text: $newTeam)
230 .autocorrectionDisabled()
231 .textInputAutocapitalization(.never)
232 .accessibilityIdentifier("org-new-team")
233 Button {
234 let team = newTeam.trimmingCharacters(in: .whitespaces)
235 newTeam = ""
236 Task { await model.createTeam(team) }
237 } label: {
238 Image(systemName: "plus.circle.fill")
239 }
240 .accessibilityLabel("Create team")
241 .disabled(newTeam.trimmingCharacters(in: .whitespaces).isEmpty || model.working)
242 .accessibilityIdentifier("org-new-team-submit")
215 AddField(placeholder: "New team", text: $newTeam, buttonLabel: "Create team",
216 fieldID: "org-new-team", buttonID: "org-new-team-submit", working: model.working) {
217 await model.createTeam($0)
243218 }
244219 } header: {
245220 Text("Teams")
gitbay/Views/Orgs/TeamView.swift +2 −8
@@ -97,10 +97,7 @@ struct TeamView: View {
9797 .task { await model.load() }
9898 .confirmationDialog(
9999 "Remove \(removingMember ?? "") from \(model.teamName)?",
100 isPresented: Binding(
101 get: { removingMember != nil },
102 set: { if !$0 { removingMember = nil } }
103 )
100 isPresented: .isPresent($removingMember)
104101 ) {
105102 Button("Remove", role: .destructive) {
106103 if let user = removingMember {
@@ -112,10 +109,7 @@ struct TeamView: View {
112109 }
113110 .confirmationDialog(
114111 "Revoke \(model.teamName)'s \(revokingGrant?.role ?? "") access to \(revokingGrant?.repo ?? "")?",
115 isPresented: Binding(
116 get: { revokingGrant != nil },
117 set: { if !$0 { revokingGrant = nil } }
118 )
112 isPresented: .isPresent($revokingGrant)
119113 ) {
120114 Button("Revoke", role: .destructive) {
121115 if let grant = revokingGrant {
gitbay/Views/Releases/ReleaseView.swift +1 −4
@@ -126,10 +126,7 @@ struct ReleaseView: View {
126126 }
127127 .confirmationDialog(
128128 "Remove \(removingAsset?.name ?? "") from \(model.tag)?",
129 isPresented: Binding(
130 get: { removingAsset != nil },
131 set: { if !$0 { removingAsset = nil } }
132 ),
129 isPresented: .isPresent($removingAsset),
133130 titleVisibility: .visible
134131 ) {
135132 Button("Remove", role: .destructive) {
gitbay/Views/Repos/MarkdownView.swift +43 −29
@@ -96,34 +96,12 @@ struct MarkdownView: View {
9696 blocks.append(.quote(quote.joined(separator: " ")))
9797 continue
9898 }
99 if trimmed.hasPrefix("- ") || trimmed.hasPrefix("* ") || trimmed.hasPrefix("+ ") {
100 var items: [String] = []
101 while let next = lines.first?.trimmingCharacters(in: .whitespaces) {
102 if next.hasPrefix("- ") || next.hasPrefix("* ") || next.hasPrefix("+ ") {
103 items.append(String(next.dropFirst(2)))
104 } else if Self.continuesItem(lines) {
105 items[items.count - 1] += " " + next
106 } else {
107 break
108 }
109 lines = lines.dropFirst()
110 }
111 blocks.append(.bullet(items))
99 if Self.bulletItem(trimmed) != nil {
100 blocks.append(.bullet(Self.listItems(&lines, item: Self.bulletItem)))
112101 continue
113102 }
114 if trimmed.range(of: #"^\d+\. "#, options: .regularExpression) != nil {
115 var items: [String] = []
116 while let next = lines.first?.trimmingCharacters(in: .whitespaces) {
117 if let range = next.range(of: #"^\d+\. "#, options: .regularExpression) {
118 items.append(String(next[range.upperBound...]))
119 } else if Self.continuesItem(lines) {
120 items[items.count - 1] += " " + next
121 } else {
122 break
123 }
124 lines = lines.dropFirst()
125 }
126 blocks.append(.ordered(items))
103 if Self.orderedItem(trimmed) != nil {
104 blocks.append(.ordered(Self.listItems(&lines, item: Self.orderedItem)))
127105 continue
128106 }
129107 if let table = Self.tableStart(lines) {
@@ -151,7 +129,7 @@ struct MarkdownView: View {
151129 while let next = lines.first {
152130 let t = next.trimmingCharacters(in: .whitespaces)
153131 if t.isEmpty || Self.atxHeading(t) != nil || t.hasPrefix("```") || t.hasPrefix(">")
154 || t.hasPrefix("- ") || t.hasPrefix("* ") || Self.tableStart(lines) != nil
132 || Self.bulletItem(t) != nil || Self.tableStart(lines) != nil
155133 || markdownMathBlock(lines) != nil {
156134 break
157135 }
@@ -197,15 +175,42 @@ struct MarkdownView: View {
197175 return (level, rest.trimmingCharacters(in: .whitespaces))
198176 }
199177
178 /// The text of a `-`, `*` or `+` list item, or nil for any other line.
179 private static func bulletItem(_ line: String) -> String? {
180 line.hasPrefix("- ") || line.hasPrefix("* ") || line.hasPrefix("+ ") ? String(line.dropFirst(2)) : nil
181 }
182
183 /// The text of a `1.` list item, or nil for any other line.
184 private static func orderedItem(_ line: String) -> String? {
185 line.range(of: #"^\d+\. "#, options: .regularExpression).map { String(line[$0.upperBound...]) }
186 }
187
188 /// The items of the list at the head of `lines`, each with the lines that
189 /// wrap it joined on, consuming them. `item` reads one item's text.
190 private static func listItems(_ lines: inout ArraySlice<String>, item: (String) -> String?) -> [String] {
191 var items: [String] = []
192 while let next = lines.first?.trimmingCharacters(in: .whitespaces) {
193 if let text = item(next) {
194 items.append(text)
195 } else if continuesItem(lines) {
196 items[items.count - 1] += " " + next
197 } else {
198 break
199 }
200 lines = lines.dropFirst()
201 }
202 return items
203 }
204
200205 /// A line that wraps the list item above it: anything but a blank line or
201206 /// the start of another block, indented or not, as in CommonMark.
202207 private static func continuesItem(_ lines: ArraySlice<String>) -> Bool {
203208 guard let line = lines.first?.trimmingCharacters(in: .whitespaces), !line.isEmpty
204209 else { return false }
205210 let startsBlock = atxHeading(line) != nil || line.hasPrefix("```") || line.hasPrefix(">")
206 || line.hasPrefix("- ") || line.hasPrefix("* ") || line.hasPrefix("+ ")
211 || bulletItem(line) != nil
207212 || line == "---" || line == "***" || line == "___"
208 || line.range(of: #"^\d+\. "#, options: .regularExpression) != nil
213 || orderedItem(line) != nil
209214 || tableStart(lines) != nil
210215 return !startsBlock
211216 }
@@ -361,7 +366,16 @@ struct MarkdownView: View {
361366 }.joined()
362367 let rendered = attributed(marked, codeStyle: codeStyle, linkOptions: linkOptions,
363368 referenceRepo: referenceRepo)
369 return spliced(maths, at: mark, into: rendered, pointSize: mathSize)
370 }
364371
372 /// `rendered` with each `mark` replaced by the next of `maths`, typeset.
373 private static func spliced(
374 _ maths: [MathExpression],
375 at mark: Unicode.Scalar,
376 into rendered: AttributedString,
377 pointSize mathSize: CGFloat
378 ) -> Text {
365379 // Display math sits on a line of its own, as the web's block-level
366380 // <math> does. A mark compares by its first scalar, since a combining
367381 // character after it joins the same Character.
gitbay/Views/Repos/RepoCredentialViews.swift +2 −2
@@ -48,7 +48,7 @@ struct BuildSecretsView: View {
4848 }
4949 .confirmationDialog(
5050 "Remove \(removing ?? "")? Builds that read it will no longer find it.",
51 isPresented: Binding(get: { removing != nil }, set: { if !$0 { removing = nil } }),
51 isPresented: .isPresent($removing),
5252 titleVisibility: .visible
5353 ) {
5454 Button("Remove", role: .destructive) {
@@ -196,7 +196,7 @@ struct DeployKeysView: View {
196196 }
197197 .confirmationDialog(
198198 "Remove the deploy key \(removing.map { $0.label.isEmpty ? $0.fingerprint : $0.label } ?? "")?",
199 isPresented: Binding(get: { removing != nil }, set: { if !$0 { removing = nil } }),
199 isPresented: .isPresent($removing),
200200 titleVisibility: .visible
201201 ) {
202202 Button("Remove", role: .destructive) {
gitbay/Views/Repos/RepoMirrorDomainViews.swift +2 −2
@@ -68,7 +68,7 @@ struct MirrorsView: View {
6868 }
6969 .confirmationDialog(
7070 "Remove the mirror \(removing?.isPull == true ? "from" : "to") \(removing?.url ?? "")?",
71 isPresented: Binding(get: { removing != nil }, set: { if !$0 { removing = nil } }),
71 isPresented: .isPresent($removing),
7272 titleVisibility: .visible
7373 ) {
7474 Button("Remove", role: .destructive) {
@@ -266,7 +266,7 @@ struct PageDomainsView: View {
266266 }
267267 .confirmationDialog(
268268 "Remove \(removing?.domain ?? "")? It stops serving this repository's pages.",
269 isPresented: Binding(get: { removing != nil }, set: { if !$0 { removing = nil } }),
269 isPresented: .isPresent($removing),
270270 titleVisibility: .visible
271271 ) {
272272 Button("Remove", role: .destructive) {
gitbay/Views/Repos/RepoSettingsView.swift +88 −119
@@ -110,10 +110,7 @@ struct RepoSettingsView: View {
110110 }
111111 .confirmationDialog(
112112 "Revoke \(revokingGrant?.user ?? "")'s \(revokingGrant?.role ?? "") access?",
113 isPresented: Binding(
114 get: { revokingGrant != nil },
115 set: { if !$0 { revokingGrant = nil } }
116 )
113 isPresented: .isPresent($revokingGrant)
117114 ) {
118115 Button("Revoke", role: .destructive) {
119116 if let grant = revokingGrant {
@@ -124,51 +121,21 @@ struct RepoSettingsView: View {
124121 Button("Cancel", role: .cancel) {}
125122 }
126123 .alert("Rename \(model.repoPath)", isPresented: $renaming) {
127 TextField("New name", text: $newName)
128 .autocorrectionDisabled()
129 .textInputAutocapitalization(.never)
130 TextField("type \(model.repoPath) to confirm", text: $renameConfirm)
131 .autocorrectionDisabled()
132 .textInputAutocapitalization(.never)
133 Button("Rename") {
134 Task {
135 if let path = await model.rename(to: newName) {
136 renamedTo = path
137 } else {
138 refusal = model.actionError
139 }
140 }
124 moveActions("New name", value: $newName, confirm: $renameConfirm, button: "Rename") {
125 await model.rename(to: $0)
141126 }
142 .disabled(newName.trimmingCharacters(in: .whitespaces).isEmpty
143 || renameConfirm != model.repoPath)
144 Button("Cancel", role: .cancel) {}
145127 } message: {
146128 Text("Clone URLs change. The old path stops resolving. Type \(model.repoPath) to confirm.")
147129 }
148 .alert("Not done", isPresented: Binding(get: { refusal != nil }, set: { if !$0 { refusal = nil } })) {
130 .alert("Not done", isPresented: .isPresent($refusal)) {
149131 Button("OK", role: .cancel) {}
150132 } message: {
151133 Text(refusal ?? "")
152134 }
153135 .alert("Transfer \(model.repoPath)", isPresented: $transferring) {
154 TextField("New owner", text: $newOwner)
155 .autocorrectionDisabled()
156 .textInputAutocapitalization(.never)
157 TextField("type \(model.repoPath) to confirm", text: $transferConfirm)
158 .autocorrectionDisabled()
159 .textInputAutocapitalization(.never)
160 Button("Transfer") {
161 Task {
162 if let path = await model.transfer(to: newOwner) {
163 renamedTo = path
164 } else {
165 refusal = model.actionError
166 }
167 }
136 moveActions("New owner", value: $newOwner, confirm: $transferConfirm, button: "Transfer") {
137 await model.transfer(to: $0)
168138 }
169 .disabled(newOwner.trimmingCharacters(in: .whitespaces).isEmpty
170 || transferConfirm != model.repoPath)
171 Button("Cancel", role: .cancel) {}
172139 } message: {
173140 Text("The repository moves to another account or organization, and its clone URLs change. Type \(model.repoPath) to confirm.")
174141 }
@@ -188,10 +155,7 @@ struct RepoSettingsView: View {
188155 }
189156 .confirmationDialog(
190157 "Remove topic \(removingTopic ?? "")?",
191 isPresented: Binding(
192 get: { removingTopic != nil },
193 set: { if !$0 { removingTopic = nil } }
194 )
158 isPresented: .isPresent($removingTopic)
195159 ) {
196160 Button("Remove", role: .destructive) {
197161 if let topic = removingTopic {
@@ -265,21 +229,9 @@ struct RepoSettingsView: View {
265229 }
266230 }
267231 }
268 HStack {
269 TextField("Add topic", text: $newTopic)
270 .autocorrectionDisabled()
271 .textInputAutocapitalization(.never)
272 .accessibilityIdentifier("settings-add-topic")
273 Button {
274 let topic = newTopic.trimmingCharacters(in: .whitespaces)
275 newTopic = ""
276 Task { await model.addTopic(topic) }
277 } label: {
278 Image(systemName: "plus.circle.fill")
279 }
280 .accessibilityLabel("Add topic")
281 .disabled(newTopic.trimmingCharacters(in: .whitespaces).isEmpty || model.working)
282 .accessibilityIdentifier("settings-add-topic-submit")
232 AddField(placeholder: "Add topic", text: $newTopic, buttonLabel: "Add topic",
233 fieldID: "settings-add-topic", buttonID: "settings-add-topic-submit", working: model.working) {
234 await model.addTopic($0)
283235 }
284236 }
285237 }
@@ -384,21 +336,9 @@ struct RepoSettingsView: View {
384336 .accessibilityIdentifier("settings-unprotect-tag-\(glob)")
385337 }
386338 }
387 HStack {
388 TextField("Protect tags matching", text: $newTagGlob)
389 .autocorrectionDisabled()
390 .textInputAutocapitalization(.never)
391 .accessibilityIdentifier("settings-protect-tag")
392 Button {
393 let glob = newTagGlob.trimmingCharacters(in: .whitespaces)
394 newTagGlob = ""
395 Task { await model.protectTag(glob) }
396 } label: {
397 Image(systemName: "plus.circle.fill")
398 }
399 .accessibilityLabel("Protect tag")
400 .disabled(newTagGlob.trimmingCharacters(in: .whitespaces).isEmpty || model.working)
401 .accessibilityIdentifier("settings-protect-tag-submit")
339 AddField(placeholder: "Protect tags matching", text: $newTagGlob, buttonLabel: "Protect tag",
340 fieldID: "settings-protect-tag", buttonID: "settings-protect-tag-submit", working: model.working) {
341 await model.protectTag($0)
402342 }
403343 } header: {
404344 Text("Protected tags")
@@ -610,19 +550,42 @@ struct RepoSettingsView: View {
610550 }
611551 }
612552
613 private var deleteSection: some View {
614 Section {
615 Button(role: .destructive) {
616 deleteConfirm = ""
617 deleting = true
618 } label: {
619 Label("Delete repository", systemImage: "trash")
620 .font(.gbSans(.subheadline))
553 /// Rename's and transfer's fields: the new value, and the current path
554 /// typed to confirm, then the button that moves the repository there.
555 @ViewBuilder
556 private func moveActions(
557 _ field: String,
558 value: Binding<String>,
559 confirm: Binding<String>,
560 button: String,
561 move: @escaping (String) async -> String?
562 ) -> some View {
563 TextField(field, text: value)
564 .autocorrectionDisabled()
565 .textInputAutocapitalization(.never)
566 TextField("type \(model.repoPath) to confirm", text: confirm)
567 .autocorrectionDisabled()
568 .textInputAutocapitalization(.never)
569 Button(button) {
570 Task {
571 if let path = await move(value.wrappedValue) {
572 renamedTo = path
573 } else {
574 refusal = model.actionError
575 }
621576 }
622 .disabled(model.working)
623 .accessibilityIdentifier("settings-delete-button")
624 } footer: {
625 Text("Deletes it with everything in it. Only its owner or an admin can.")
577 }
578 .disabled(value.wrappedValue.trimmingCharacters(in: .whitespaces).isEmpty
579 || confirm.wrappedValue != model.repoPath)
580 Button("Cancel", role: .cancel) {}
581 }
582
583 private var deleteSection: some View {
584 DeleteSection(title: "Delete repository",
585 footer: "Deletes it with everything in it. Only its owner or an admin can.",
586 identifier: "settings-delete-button", working: model.working) {
587 deleteConfirm = ""
588 deleting = true
626589 }
627590 }
628591
@@ -635,40 +598,7 @@ struct RepoSettingsView: View {
635598 .disabled(model.working)
636599
637600 if deps.enabled {
638 if let lastCheck = deps.lastCheck {
639 (Text("Last checked ") + Text(lastCheck, format: .relative(presentation: .named)))
640 .font(.gbSans(.caption))
641 .foregroundStyle(.secondary)
642 } else {
643 Text("Never checked")
644 .font(.gbSans(.caption))
645 .foregroundStyle(.secondary)
646 }
647 if let lastError = deps.lastError {
648 GBNotice(lastError, .gbWarn)
649 }
650 if let issueNumber = deps.issueNumber {
651 NavigationLink(value: IssueRoute.issue(repo: model.repoPath, number: issueNumber)) {
652 Text("Tracking issue #\(issueNumber)")
653 }
654 }
655 if deps.behind.isEmpty {
656 if deps.lastCheck != nil {
657 Text("Everything is current.")
658 .font(.gbSans(.caption))
659 .foregroundStyle(.secondary)
660 }
661 } else {
662 ForEach(deps.behind) { dep in
663 VStack(alignment: .leading, spacing: 2) {
664 Text(dep.name)
665 .font(.gbSans(.subheadline))
666 Text("\(dep.ecosystem) · \(dep.current) → \(dep.latest)")
667 .font(.gbSans(.caption))
668 .foregroundStyle(.secondary)
669 }
670 }
671 }
601 depsStatus(deps)
672602 }
673603 } else if let depsError = model.depsError {
674604 GBNotice(depsError, .gbWarn)
@@ -686,6 +616,45 @@ struct RepoSettingsView: View {
686616 }
687617 }
688618
619 /// When the checks last ran and what they found.
620 @ViewBuilder
621 private func depsStatus(_ deps: DepsStatus) -> some View {
622 if let lastCheck = deps.lastCheck {
623 (Text("Last checked ") + Text(lastCheck, format: .relative(presentation: .named)))
624 .font(.gbSans(.caption))
625 .foregroundStyle(.secondary)
626 } else {
627 Text("Never checked")
628 .font(.gbSans(.caption))
629 .foregroundStyle(.secondary)
630 }
631 if let lastError = deps.lastError {
632 GBNotice(lastError, .gbWarn)
633 }
634 if let issueNumber = deps.issueNumber {
635 NavigationLink(value: IssueRoute.issue(repo: model.repoPath, number: issueNumber)) {
636 Text("Tracking issue #\(issueNumber)")
637 }
638 }
639 if deps.behind.isEmpty {
640 if deps.lastCheck != nil {
641 Text("Everything is current.")
642 .font(.gbSans(.caption))
643 .foregroundStyle(.secondary)
644 }
645 } else {
646 ForEach(deps.behind) { dep in
647 VStack(alignment: .leading, spacing: 2) {
648 Text(dep.name)
649 .font(.gbSans(.subheadline))
650 Text("\(dep.ecosystem) · \(dep.current) → \(dep.latest)")
651 .font(.gbSans(.caption))
652 .foregroundStyle(.secondary)
653 }
654 }
655 }
656 }
657
689658 private func toggle(
690659 _ title: String,
691660 _ value: Bool,
gitbay/Views/Repos/RepoView.swift +22 −17
@@ -238,23 +238,7 @@ struct RepoView: View {
238238 private func header(_ detail: RepoDetail) -> some View {
239239 Section {
240240 VStack(alignment: .leading, spacing: 8) {
241 HStack(spacing: 6) {
242 HStack(spacing: 0) {
243 Button(owner) { open(.owner) }
244 .buttonStyle(.borderless)
245 .accessibilityIdentifier("repo-owner-link")
246 Text("/" + (detail.path.split(separator: "/").last.map(String.init) ?? ""))
247 }
248 .font(.gbSans(.headline))
249 if detail.visibility == "private" {
250 Image(systemName: "lock.fill")
251 .font(.gbSans(.caption))
252 .foregroundStyle(.secondary)
253 }
254 if detail.isArchived {
255 GBChip("archived", .secondary)
256 }
257 }
241 titleLine(detail)
258242 if let description = detail.description, !description.isEmpty {
259243 Text(description)
260244 .font(.gbSans(.subheadline))
@@ -286,6 +270,27 @@ struct RepoView: View {
286270 }
287271 }
288272
273 /// `owner/name`, the owner openable, with the repository's lock and archive marks.
274 private func titleLine(_ detail: RepoDetail) -> some View {
275 HStack(spacing: 6) {
276 HStack(spacing: 0) {
277 Button(owner) { open(.owner) }
278 .buttonStyle(.borderless)
279 .accessibilityIdentifier("repo-owner-link")
280 Text("/" + (detail.path.split(separator: "/").last.map(String.init) ?? ""))
281 }
282 .font(.gbSans(.headline))
283 if detail.visibility == "private" {
284 Image(systemName: "lock.fill")
285 .font(.gbSans(.caption))
286 .foregroundStyle(.secondary)
287 }
288 if detail.isArchived {
289 GBChip("archived", .secondary)
290 }
291 }
292 }
293
289294 private var owner: String { String(path.split(separator: "/").first ?? "") }
290295
291296 /// Files, merge requests, issues and builds in one row; two rows at
gitbay/Views/Repos/WebhookListView.swift +1 −4
@@ -72,10 +72,7 @@ struct WebhookListView: View {
7272 }
7373 .confirmationDialog(
7474 "Remove the webhook for \(removingHook?.url ?? "")?",
75 isPresented: Binding(
76 get: { removingHook != nil },
77 set: { if !$0 { removingHook = nil } }
78 ),
75 isPresented: .isPresent($removingHook),
7976 titleVisibility: .visible
8077 ) {
8178 Button("Remove", role: .destructive) {
gitbay/Views/Shared/AddField.swift added +32
@@ -0,0 +1,32 @@
1import SwiftUI
2
3/// A one-line field and the button that adds what was typed, trimmed; the
4/// field clears on adding.
5struct AddField: View {
6 let placeholder: String
7 @Binding var text: String
8 let buttonLabel: String
9 let fieldID: String
10 let buttonID: String
11 let working: Bool
12 let add: (String) async -> Void
13
14 var body: some View {
15 HStack {
16 TextField(placeholder, text: $text)
17 .autocorrectionDisabled()
18 .textInputAutocapitalization(.never)
19 .accessibilityIdentifier(fieldID)
20 Button {
21 let value = text.trimmingCharacters(in: .whitespaces)
22 text = ""
23 Task { await add(value) }
24 } label: {
25 Image(systemName: "plus.circle.fill")
26 }
27 .accessibilityLabel(buttonLabel)
28 .disabled(text.trimmingCharacters(in: .whitespaces).isEmpty || working)
29 .accessibilityIdentifier(buttonID)
30 }
31 }
32}
gitbay/Views/Shared/CommentsSection.swift added +78
@@ -0,0 +1,78 @@
1import SwiftUI
2
3/// An issue's or merge request's comments, each with its reactions, and
4/// the field that adds one. `idPrefix` ("issue", "mr") keeps the
5/// accessibility identifiers of the two screens apart.
6struct CommentsSection: View {
7 let comments: [ThreadComment]
8 let repo: String
9 let working: Bool
10 let idPrefix: String
11 @Binding var text: String
12 @Binding var format: String
13 let react: (String, Int64) async -> Void
14 let send: (String, String) async -> Void
15
16 var body: some View {
17 Section("Comments") {
18 ForEach(comments) { comment in
19 row(comment)
20 }
21 composer
22 if !text.isEmpty {
23 MarkupPreview(text: text, format: format,
24 identifier: "\(idPrefix)-comment-preview")
25 .font(.gbSans(.subheadline))
26 }
27 }
28 }
29
30 private func row(_ comment: ThreadComment) -> some View {
31 VStack(alignment: .leading, spacing: 4) {
32 HStack {
33 Text(comment.author)
34 .font(.gbSans(.caption).weight(.semibold))
35 Text(comment.createdAt, format: .relative(presentation: .named))
36 .font(.gbSans(.caption))
37 .foregroundStyle(.tertiary)
38 }
39 FormattedBodyView(text: comment.body, format: comment.bodyFormat, repo: repo)
40 .font(.gbSans(.subheadline))
41 if let id = comment.commentID, !comment.isSystem {
42 ReactionBar(reactions: comment.reactions ?? [], disabled: working,
43 idPrefix: "\(idPrefix)-comment-\(id)-reaction") { name in
44 Task { await react(name, id) }
45 }
46 }
47 }
48 .padding(.vertical, 2)
49 }
50
51 private var composer: some View {
52 HStack {
53 TextField("Comment", text: $text, axis: .vertical)
54 .lineLimit(1...5)
55 .accessibilityIdentifier("\(idPrefix)-comment-field")
56 Picker("Format", selection: $format) {
57 Text("Markdown").tag("md")
58 Text("Org").tag("org")
59 }
60 .pickerStyle(.segmented)
61 .labelsHidden()
62 .fixedSize()
63 .accessibilityIdentifier("\(idPrefix)-comment-format")
64 Button {
65 let sent = text
66 text = ""
67 Task { await send(sent, format) }
68 } label: {
69 Image(systemName: "arrow.up.circle.fill")
70 .font(.title)
71 .frame(minWidth: 44, minHeight: 44)
72 .contentShape(Rectangle())
73 }
74 .accessibilityLabel("Send comment")
75 .disabled(text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || working)
76 }
77 }
78}
gitbay/Views/Shared/DeleteSection.swift added +24
@@ -0,0 +1,24 @@
1import SwiftUI
2
3/// A section holding one destructive button, with what deleting means
4/// underneath.
5struct DeleteSection: View {
6 let title: String
7 let footer: String
8 let identifier: String
9 let working: Bool
10 let delete: () -> Void
11
12 var body: some View {
13 Section {
14 Button(role: .destructive, action: delete) {
15 Label(title, systemImage: "trash")
16 .font(.gbSans(.subheadline))
17 }
18 .disabled(working)
19 .accessibilityIdentifier(identifier)
20 } footer: {
21 Text(footer)
22 }
23 }
24}
gitbay/Views/Shared/ListToolbar.swift added +35
@@ -0,0 +1,35 @@
1import SwiftUI
2
3/// A list's filter and new-item buttons. The filter icon fills while the
4/// filter narrows the list.
5struct ListToolbar: ToolbarContent {
6 @Binding var filtering: Bool
7 @Binding var composing: Bool
8 let narrowed: Bool
9 let newLabel: String
10 /// "issue", "mr": the prefix of the two buttons' identifiers.
11 let idPrefix: String
12
13 var body: some ToolbarContent {
14 ToolbarItem(placement: .topBarTrailing) {
15 Button {
16 filtering = true
17 } label: {
18 Image(systemName: narrowed
19 ? "line.3.horizontal.decrease.circle.fill"
20 : "line.3.horizontal.decrease.circle")
21 }
22 .accessibilityLabel("Filter")
23 .accessibilityIdentifier("\(idPrefix)-filter-button")
24 }
25 ToolbarItem(placement: .topBarTrailing) {
26 Button {
27 composing = true
28 } label: {
29 Image(systemName: "plus")
30 }
31 .accessibilityLabel(newLabel)
32 .accessibilityIdentifier("\(idPrefix)-create-button")
33 }
34 }
35}
gitbay/Views/Shared/MathRendering.swift +30 −25
@@ -120,31 +120,7 @@ enum MathRenderer {
120120 while let c = chars.popFirst() {
121121 switch c {
122122 case "\\":
123 let name = chars.prefix(while: \.isLetter)
124 guard !name.isEmpty else {
125 out.append(c)
126 if let next = chars.popFirst() { out.append(next) }
127 continue
128 }
129 chars = chars.dropFirst(name.count)
130 if name == "operatorname", chars.first == "*" { chars = chars.dropFirst() }
131 // An operator name is upright with a thin space after it.
132 if name == "operatorname", chars.first == "{", let close = chars.firstIndex(of: "}") {
133 out += "\\mathrm" + chars[...close] + "\\,"
134 chars = chars[chars.index(after: close)...]
135 continue
136 }
137 if name == "begin" || name == "end", chars.first == "{",
138 let close = chars.firstIndex(of: "}") {
139 let env = chars[chars.index(after: chars.startIndex)..<close]
140 if let renamed = environments[env] {
141 chars = chars[chars.index(after: close)...]
142 if !renamed.isEmpty { out += "\\\(name){\(renamed)}" }
143 continue
144 }
145 }
146 let renamed = commands[name] ?? String(name)
147 if !renamed.isEmpty { out += "\\" + renamed }
123 out += command(after: &chars)
148124 case "'":
149125 var primes = 1
150126 while chars.first == "'" { primes += 1; chars = chars.dropFirst() }
@@ -158,6 +134,35 @@ enum MathRenderer {
158134 return out
159135 }
160136
137 /// The SwiftMath spelling of the command whose backslash was just read,
138 /// consuming its name and, for an operator name or an environment, its
139 /// braced argument. A backslash before a non-letter passes through with
140 /// that character.
141 private static func command(after chars: inout Substring) -> String {
142 let name = chars.prefix(while: \.isLetter)
143 guard !name.isEmpty else {
144 return "\\" + (chars.popFirst().map(String.init) ?? "")
145 }
146 chars = chars.dropFirst(name.count)
147 if name == "operatorname", chars.first == "*" { chars = chars.dropFirst() }
148 // An operator name is upright with a thin space after it.
149 if name == "operatorname", chars.first == "{", let close = chars.firstIndex(of: "}") {
150 let argument = chars[...close]
151 chars = chars[chars.index(after: close)...]
152 return "\\mathrm" + argument + "\\,"
153 }
154 if name == "begin" || name == "end", chars.first == "{",
155 let close = chars.firstIndex(of: "}") {
156 let env = chars[chars.index(after: chars.startIndex)..<close]
157 if let renamed = environments[env] {
158 chars = chars[chars.index(after: close)...]
159 return renamed.isEmpty ? "" : "\\\(name){\(renamed)}"
160 }
161 }
162 let renamed = commands[name] ?? String(name)
163 return renamed.isEmpty ? "" : "\\" + renamed
164 }
165
161166 /// The expression as text: the image, set on the baseline and tinted
162167 /// like the text around it, or the source where it is refused.
163168 static func text(_ math: MathExpression, pointSize: CGFloat) -> Text {
gitbay/Views/Shared/MilestoneMenu.swift added +35
@@ -0,0 +1,35 @@
1import SwiftUI
2
3/// The milestone an issue or merge request is filed under, and the menu
4/// that moves it. The repository's milestones load when the menu appears.
5struct MilestoneMenu: View {
6 let current: String?
7 let milestones: [Milestone]?
8 let working: Bool
9 let identifier: String
10 let set: (String?) async -> Void
11 let load: () async -> Void
12
13 var body: some View {
14 Menu {
15 Button("None") { Task { await set(nil) } }
16 ForEach(milestones ?? []) { milestone in
17 Button("\(milestone.title) (\(milestone.closed)/\(milestone.open + milestone.closed))") {
18 Task { await set(milestone.title) }
19 }
20 }
21 } label: {
22 HStack {
23 Label(current ?? "None", systemImage: "flag")
24 .font(.gbSans(.subheadline))
25 Spacer()
26 Image(systemName: "chevron.up.chevron.down")
27 .font(.gbSans(.caption2))
28 .foregroundStyle(.secondary)
29 }
30 }
31 .disabled(working)
32 .task { await load() }
33 .accessibilityIdentifier(identifier)
34 }
35}
gitbay/Views/Shared/PresentedItem.swift added +9
@@ -0,0 +1,9 @@
1import SwiftUI
2
3extension Binding where Value == Bool {
4 /// True while `item` holds a value; dismissing clears it. Presents a
5 /// dialog or alert about whatever `item` names.
6 static func isPresent<Item>(_ item: Binding<Item?>) -> Binding<Bool> {
7 Binding(get: { item.wrappedValue != nil }, set: { if !$0 { item.wrappedValue = nil } })
8 }
9}
gitbay/Views/Shared/TeXMath.swift +94 −78
@@ -54,32 +54,108 @@ nonisolated struct MathBudget: Sendable {
5454/// digit after it, so "$5 and $10" is prose. A backslash escapes the next
5555/// character, and code spans and link destinations are never math.
5656nonisolated func splitMarkdownMath(_ text: String) -> [MathPiece] {
57 let chars = Array(text)
57 let scanner = MathScanner(chars: Array(text))
5858 var pieces: [MathPiece] = []
5959 var prose = ""
6060 var i = 0
61 while i < scanner.chars.count {
62 let (end, math) = scanner.token(at: i)
63 if let math {
64 if !prose.isEmpty { pieces.append(.text(prose)) }
65 prose = ""
66 pieces.append(.math(math))
67 } else {
68 prose += String(scanner.chars[i..<end])
69 }
70 i = end
71 }
72 if !prose.isEmpty { pieces.append(.text(prose)) }
73 return pieces
74}
75
76/// The token scanner behind ``splitMarkdownMath(_:)``.
77private nonisolated struct MathScanner {
78 let chars: [Character]
79 /// Every `$` that can close inline math, found in one pass so each opener
80 /// looks its closer up rather than rescanning the rest of the text.
81 let closers: [Int]
82
83 init(chars: [Character]) {
84 self.chars = chars
85 var closers: [Int] = []
86 var k = 1
87 while k < chars.count {
88 if chars[k] == "\\" {
89 k += 2
90 continue
91 }
92 if chars[k] == "$", !Self.isSpace(chars[k - 1]),
93 !(k + 1 < chars.count && chars[k + 1].isASCII && chars[k + 1].isNumber) {
94 closers.append(k)
95 }
96 k += 1
97 }
98 self.closers = closers
99 }
61100
62 func flush() {
63 if !prose.isEmpty { pieces.append(.text(prose)) }
64 prose = ""
101 static func isSpace(_ c: Character) -> Bool { c == " " || c == "\t" || c == "\n" || c == "\r" }
102
103 /// The token starting at `i`: where it ends, and the math it is, if any.
104 /// Everything that is not math is prose, copied through as written.
105 func token(at i: Int) -> (end: Int, math: MathExpression?) {
106 let next = i + 1 < chars.count ? chars[i + 1] : nil
107 switch chars[i] {
108 case "\\":
109 return (min(i + 2, chars.count), nil)
110 case "`":
111 return (codeSpanEnd(at: i), nil)
112 case "]" where next == "(":
113 return (chars[(i + 2)...].firstIndex(of: ")").map { $0 + 1 } ?? chars.count, nil)
114 case "$" where next == "$":
115 return displayMath(at: i)
116 case "$" where next.map { !Self.isSpace($0) } ?? false:
117 return inlineMath(at: i)
118 default:
119 return (i + 1, nil)
120 }
65121 }
66 func isSpace(_ c: Character) -> Bool { c == " " || c == "\t" || c == "\n" || c == "\r" }
67
68 // Every `$` that can close inline math, found in one pass so each opener
69 // looks its closer up rather than rescanning the rest of the text.
70 var closers: [Int] = []
71 var k = 1
72 while k < chars.count {
73 if chars[k] == "\\" {
74 k += 2
75 continue
122
123 /// The end of the code span opening at `i`: past the run of backticks
124 /// that closes it, or past the opening run when nothing does.
125 func codeSpanEnd(at i: Int) -> Int {
126 var run = 1
127 while i + run < chars.count, chars[i + run] == "`" { run += 1 }
128 var j = i + run
129 while j < chars.count {
130 guard chars[j] == "`" else { j += 1; continue }
131 var k = 1
132 while j + k < chars.count, chars[j + k] == "`" { k += 1 }
133 if k == run { return j + k }
134 j += k
76135 }
77 if chars[k] == "$", !isSpace(chars[k - 1]),
78 !(k + 1 < chars.count && chars[k + 1].isASCII && chars[k + 1].isNumber) {
79 closers.append(k)
136 return i + run
137 }
138
139 /// `$$…$$` at `i`, or the two dollars as prose when it is not closed or empty.
140 func displayMath(at i: Int) -> (end: Int, math: MathExpression?) {
141 var j = i + 2
142 while j + 1 < chars.count {
143 if chars[j] == "\\" { j += 2; continue }
144 if chars[j] == "$", chars[j + 1] == "$" { break }
145 j += 1
80146 }
81 k += 1
147 guard j + 1 < chars.count, j > i + 2 else { return (i + 2, nil) }
148 let tex = String(chars[(i + 2)..<j])
149 return (j + 2, MathExpression(tex: tex, display: true, source: "$$" + tex + "$$"))
150 }
151
152 /// `$…$` at `i`, or the dollar as prose when nothing closes it.
153 func inlineMath(at i: Int) -> (end: Int, math: MathExpression?) {
154 guard let close = firstCloser(atOrAfter: i + 2) else { return (i + 1, nil) }
155 let tex = String(chars[(i + 1)..<close])
156 return (close + 1, MathExpression(tex: tex, display: false, source: "$" + tex + "$"))
82157 }
158
83159 func firstCloser(atOrAfter offset: Int) -> Int? {
84160 var low = 0, high = closers.count
85161 while low < high {
@@ -88,66 +164,6 @@ nonisolated func splitMarkdownMath(_ text: String) -> [MathPiece] {
88164 }
89165 return low < closers.count ? closers[low] : nil
90166 }
91
92 while i < chars.count {
93 let c = chars[i]
94 switch c {
95 case "\\":
96 prose += String(chars[i..<min(i + 2, chars.count)])
97 i += 2
98 case "`":
99 var run = 1
100 while i + run < chars.count, chars[i + run] == "`" { run += 1 }
101 var j = i + run
102 var close: Int?
103 while j < chars.count {
104 guard chars[j] == "`" else { j += 1; continue }
105 var k = 1
106 while j + k < chars.count, chars[j + k] == "`" { k += 1 }
107 if k == run { close = j + k; break }
108 j += k
109 }
110 let end = close ?? i + run
111 prose += String(chars[i..<end])
112 i = end
113 case "]" where i + 1 < chars.count && chars[i + 1] == "(":
114 let end = chars[(i + 2)...].firstIndex(of: ")").map { $0 + 1 } ?? chars.count
115 prose += String(chars[i..<end])
116 i = end
117 case "$" where i + 1 < chars.count && chars[i + 1] == "$":
118 var j = i + 2
119 var close: Int?
120 while j + 1 < chars.count {
121 if chars[j] == "\\" { j += 2; continue }
122 if chars[j] == "$", chars[j + 1] == "$" { close = j; break }
123 j += 1
124 }
125 if let close, close > i + 2 {
126 flush()
127 let tex = String(chars[(i + 2)..<close])
128 pieces.append(.math(MathExpression(tex: tex, display: true, source: "$$" + tex + "$$")))
129 i = close + 2
130 } else {
131 prose += "$$"
132 i += 2
133 }
134 case "$" where i + 1 < chars.count && !isSpace(chars[i + 1]):
135 if let close = firstCloser(atOrAfter: i + 2) {
136 flush()
137 let tex = String(chars[(i + 1)..<close])
138 pieces.append(.math(MathExpression(tex: tex, display: false, source: "$" + tex + "$")))
139 i = close + 1
140 } else {
141 prose.append(c)
142 i += 1
143 }
144 default:
145 prose.append(c)
146 i += 1
147 }
148 }
149 flush()
150 return pieces
151167}
152168
153169/// A display block at the head of `lines`, by the web's rules: a line that
gitbayTests/MRViewModelTests.swift +23
@@ -133,6 +133,23 @@ struct UnifiedDiffParserTests {
133133 #expect(diff.deletions == 2)
134134 }
135135
136 /// The text after a hunk's closing `@@` is the enclosing line of code:
137 /// a lone `-` in it crashed the parser, and a `-5` renumbered the hunk.
138 @Test func hunkContextIsNotReadAsARange() {
139 let diff = UnifiedDiff.parse("""
140 diff --git a/README.md b/README.md
141 --- a/README.md
142 +++ b/README.md
143 @@ -12,2 +14,3 @@ Setup - quick start, offset -5 +9
144 keep
145 +add
146 """)
147 let lines = diff.files[0].hunks[0].lines
148 #expect(lines[0].oldNumber == 12)
149 #expect(lines[0].newNumber == 14)
150 #expect(lines[1].newNumber == 15)
151 }
152
136153 @Test func binaryFilesAreRecognised() {
137154 let diff = UnifiedDiff.parse("""
138155 diff --git a/logo.png b/logo.png
@@ -274,6 +291,12 @@ struct MRDetailViewModelTests {
274291 #expect(!gates.fastForward)
275292 #expect(gates.unmet == ["approvals", "codeowners", "threads", "fast-forward"])
276293 #expect(!gates.isMet)
294 #expect(gates.rows == [
295 .init(met: false, text: "0 of 1 approval"),
296 .init(met: false, text: "widget.go — alice"),
297 .init(met: false, text: "2 threads open"),
298 .init(met: false, text: "Behind the target — rebase first"),
299 ])
277300 #expect(mr.reviews?.first?.counts == false)
278301 }
279302
gitbayTests/MarkdownTests.swift +6
@@ -174,6 +174,12 @@ struct MarkdownListTests {
174174 let parsed = blocks("- one\n## Next")
175175 #expect(parsed == [.bullet(["one"]), .heading(level: 2, text: "Next")])
176176 }
177
178 /// Every bullet marker starts a list under a paragraph, `+` as much as `-`.
179 @Test(arguments: ["-", "*", "+"]) func aBulletEndsTheParagraphAboveIt(_ marker: String) {
180 let parsed = blocks("Steps:\n\(marker) one\n\(marker) two")
181 #expect(parsed == [.paragraph("Steps:"), .bullet(["one", "two"])])
182 }
177183}
178184
179185@MainActor