ChWebsiteApp/CHDataManagement/Page Elements/PostFeedPageNavigation.swift
Christoph Hagen dd2b7d6cd2 Fix page paths
Update PostListPageGenerator.swift
2025-01-07 10:33:33 +01:00

80 lines
2.7 KiB
Swift

import Foundation
struct PostFeedPageNavigation {
/// Includes a leading slash
let linkPrefix: String
let currentPage: Int
let numberOfPages: Int
init(linkPrefix: String, currentPage: Int, numberOfPages: Int) {
self.linkPrefix = linkPrefix
self.currentPage = currentPage
self.numberOfPages = numberOfPages
}
private func pageLink(_ page: Int) -> String {
"href='\(linkPrefix)/\(page)'"
}
private func addPreviousButton(to result: inout String) {
if currentPage == 1 {
// Disable the previous button if we are on the first page
result += "<a class='tag prev disabled' href='' aria-label='Previous'>"
} else {
let link = pageLink(currentPage - 1)
result += "<a class='tag prev' \(link) aria-label='Previous'>"
}
result += "<svg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='currentColor'>"
result += "<path stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M15 19l-7-7 7-7' />"
result += "</svg></a>"
}
private func addNextButton(to result: inout String) {
if currentPage == numberOfPages {
// Disable the previous button if we are on the first page
result += "<a class='tag next disabled' href='' aria-label='Next'>"
} else {
let link = pageLink(currentPage + 1)
result += "<a class='tag next' \(link) aria-label='Next'>"
}
result += "<svg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='currentColor'>"
result += "<path stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M9 5l7 7-7 7' />"
result += "</svg></a>"
}
private func addLink(page: Int, to result: inout String) {
result += "<a class='tag' \(pageLink(page))>\(page)</a>"
}
var content: String {
var result = "<div class='pagination'>"
addPreviousButton(to: &result)
// Add a maximum of two buttons before the current page
if currentPage > 2 {
addLink(page: currentPage - 2, to: &result)
}
if currentPage > 1 {
addLink(page: currentPage - 1, to: &result)
}
// Add the current page
result += "<span class='tag current'>\(currentPage)</span>"
// Add a maximum of two buttons after the current page
if currentPage < numberOfPages {
addLink(page: currentPage + 1, to: &result)
}
if currentPage + 1 < numberOfPages {
addLink(page: currentPage + 2, to: &result)
}
addNextButton(to: &result)
result += "</div>" // Close pagination
return result
}
}