Merge remote-tracking branch 'upstream/main' into zh-Hant-localization

This commit is contained in:
sh95014 2024-03-23 11:14:58 -07:00
commit 45878a4d91
162 changed files with 4918 additions and 2275 deletions

View file

@ -940,7 +940,7 @@
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
MARKETING_VERSION = 1.10.32;
MARKETING_VERSION = 1.10.33;
PRODUCT_BUNDLE_IDENTIFIER = "$(BUNDLE_ID_PREFIX).IceCubesApp.IceCubesNotifications";
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = iphoneos;
@ -975,7 +975,7 @@
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
MARKETING_VERSION = 1.10.32;
MARKETING_VERSION = 1.10.33;
PRODUCT_BUNDLE_IDENTIFIER = "$(BUNDLE_ID_PREFIX).IceCubesApp.IceCubesNotifications";
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = iphoneos;
@ -1011,7 +1011,7 @@
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
MARKETING_VERSION = 1.10.32;
MARKETING_VERSION = 1.10.33;
PRODUCT_BUNDLE_IDENTIFIER = "$(BUNDLE_ID_PREFIX).IceCubesApp.IceCubesShareExtension";
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = iphoneos;
@ -1045,7 +1045,7 @@
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
MARKETING_VERSION = 1.10.32;
MARKETING_VERSION = 1.10.33;
PRODUCT_BUNDLE_IDENTIFIER = "$(BUNDLE_ID_PREFIX).IceCubesApp.IceCubesShareExtension";
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = iphoneos;
@ -1225,7 +1225,7 @@
LD_RUNPATH_SEARCH_PATHS = "@executable_path/Frameworks";
"LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = "@executable_path/../Frameworks";
MACOSX_DEPLOYMENT_TARGET = 13.0;
MARKETING_VERSION = 1.10.32;
MARKETING_VERSION = 1.10.33;
PRODUCT_BUNDLE_IDENTIFIER = "$(BUNDLE_ID_PREFIX).IceCubesApp";
PRODUCT_NAME = "Ice Cubes";
SDKROOT = auto;
@ -1279,7 +1279,7 @@
LD_RUNPATH_SEARCH_PATHS = "@executable_path/Frameworks";
"LD_RUNPATH_SEARCH_PATHS[sdk=macosx*]" = "@executable_path/../Frameworks";
MACOSX_DEPLOYMENT_TARGET = 13.0;
MARKETING_VERSION = 1.10.32;
MARKETING_VERSION = 1.10.33;
PRODUCT_BUNDLE_IDENTIFIER = "$(BUNDLE_ID_PREFIX).IceCubesApp";
PRODUCT_NAME = "Ice Cubes";
SDKROOT = auto;
@ -1314,7 +1314,7 @@
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
MARKETING_VERSION = 1.10.32;
MARKETING_VERSION = 1.10.33;
PRODUCT_BUNDLE_IDENTIFIER = "$(BUNDLE_ID_PREFIX).IceCubesApp.IceCubesActionExtension";
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = iphoneos;
@ -1349,7 +1349,7 @@
"@executable_path/Frameworks",
"@executable_path/../../Frameworks",
);
MARKETING_VERSION = 1.10.32;
MARKETING_VERSION = 1.10.33;
PRODUCT_BUNDLE_IDENTIFIER = "$(BUNDLE_ID_PREFIX).IceCubesApp.IceCubesActionExtension";
PRODUCT_NAME = "$(TARGET_NAME)";
SDKROOT = iphoneos;

View file

@ -68,8 +68,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/kean/Nuke",
"state" : {
"revision" : "15fde63470d782c897816a74bdd516a907e33147",
"version" : "12.3.0"
"revision" : "8ecbfc886da39bccb01c34abef5f2ff4073ad633",
"version" : "12.4.0"
}
},
{

View file

@ -140,6 +140,12 @@ extension View {
.presentationDetents([.medium])
.presentationBackground(.thinMaterial)
.withEnvironments()
case .accountEditInfo:
EditAccountView()
.withEnvironments()
case .accountFiltersList:
FiltersListView()
.withEnvironments()
}
}
}

View file

@ -17,29 +17,29 @@ struct AppView: View {
@Environment(UserPreferences.self) private var userPreferences
@Environment(Theme.self) private var theme
@Environment(StreamWatcher.self) private var watcher
@Environment(\.openWindow) var openWindow
@Environment(\.horizontalSizeClass) private var horizontalSizeClass
@Binding var selectedTab: Tab
@Binding var appRouterPath: RouterPath
@State var popToRootTab: Tab = .other
@State var iosTabs = iOSTabs.shared
@State var sidebarTabs = SidebarTabs.shared
var body: some View {
#if os(visionOS)
tabBarView
#else
if UIDevice.current.userInterfaceIdiom == .pad || UIDevice.current.userInterfaceIdiom == .mac {
sidebarView
} else {
tabBarView
}
#else
if UIDevice.current.userInterfaceIdiom == .pad || UIDevice.current.userInterfaceIdiom == .mac {
sidebarView
} else {
tabBarView
}
#endif
}
var availableTabs: [Tab] {
guard appAccountsManager.currentClient.isAuth else {
return Tab.loggedOutTab()
@ -49,7 +49,7 @@ struct AppView: View {
} else if UIDevice.current.userInterfaceIdiom == .vision {
return Tab.visionOSTab()
}
return sidebarTabs.tabs.map{ $0.tab }
return sidebarTabs.tabs.map { $0.tab }
}
var tabBarView: some View {
@ -58,9 +58,9 @@ struct AppView: View {
}, set: { newTab in
if newTab == .post {
#if os(visionOS)
openWindow(value: WindowDestinationEditor.newStatusEditor(visibility: userPreferences.postVisibility))
openWindow(value: WindowDestinationEditor.newStatusEditor(visibility: userPreferences.postVisibility))
#else
appRouterPath.presentedSheet = .newStatusEditor(visibility: userPreferences.postVisibility)
appRouterPath.presentedSheet = .newStatusEditor(visibility: userPreferences.postVisibility)
#endif
return
}
@ -104,40 +104,40 @@ struct AppView: View {
}
return 0
}
#if !os(visionOS)
var sidebarView: some View {
SideBarView(selectedTab: $selectedTab,
popToRootTab: $popToRootTab,
tabs: availableTabs)
{
HStack(spacing: 0) {
TabView(selection: $selectedTab) {
ForEach(availableTabs) { tab in
tab
.makeContentView(selectedTab: $selectedTab, popToRootTab: $popToRootTab)
.tabItem {
tab.label
}
.tag(tab)
var sidebarView: some View {
SideBarView(selectedTab: $selectedTab,
popToRootTab: $popToRootTab,
tabs: availableTabs)
{
HStack(spacing: 0) {
TabView(selection: $selectedTab) {
ForEach(availableTabs) { tab in
tab
.makeContentView(selectedTab: $selectedTab, popToRootTab: $popToRootTab)
.tabItem {
tab.label
}
.tag(tab)
}
}
.introspect(.tabView, on: .iOS(.v17)) { (tabview: UITabBarController) in
tabview.tabBar.isHidden = horizontalSizeClass == .regular
tabview.customizableViewControllers = []
tabview.moreNavigationController.isNavigationBarHidden = true
}
if horizontalSizeClass == .regular,
appAccountsManager.currentClient.isAuth,
userPreferences.showiPadSecondaryColumn
{
Divider().edgesIgnoringSafeArea(.all)
notificationsSecondaryColumn
}
}
.introspect(.tabView, on: .iOS(.v17)) { (tabview: UITabBarController) in
tabview.tabBar.isHidden = horizontalSizeClass == .regular
tabview.customizableViewControllers = []
tabview.moreNavigationController.isNavigationBarHidden = true
}
if horizontalSizeClass == .regular,
appAccountsManager.currentClient.isAuth,
userPreferences.showiPadSecondaryColumn
{
Divider().edgesIgnoringSafeArea(.all)
notificationsSecondaryColumn
}
}
.environment(appRouterPath)
}
.environment(appRouterPath)
}
#endif
var notificationsSecondaryColumn: some View {

View file

@ -26,10 +26,10 @@ struct IceCubesApp: App {
@State var watcher = StreamWatcher.shared
@State var quickLook = QuickLook.shared
@State var theme = Theme.shared
@State var selectedTab: Tab = .timeline
@State var appRouterPath = RouterPath()
@State var isSupporter: Bool = false
var body: some Scene {

View file

@ -36,37 +36,37 @@ public struct ReportView: View {
.navigationTitle("report.title")
.navigationBarTitleDisplayMode(.inline)
#if !os(visionOS)
.scrollContentBackground(.hidden)
.background(theme.secondaryBackgroundColor)
.scrollDismissesKeyboard(.immediately)
.scrollContentBackground(.hidden)
.background(theme.secondaryBackgroundColor)
.scrollDismissesKeyboard(.immediately)
#endif
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button {
isSendingReport = true
Task {
do {
let _: ReportSent =
try await client.post(endpoint: Statuses.report(accountId: status.account.id,
statusId: status.id,
comment: commentText))
dismiss()
isSendingReport = false
} catch {
isSendingReport = false
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button {
isSendingReport = true
Task {
do {
let _: ReportSent =
try await client.post(endpoint: Statuses.report(accountId: status.account.id,
statusId: status.id,
comment: commentText))
dismiss()
isSendingReport = false
} catch {
isSendingReport = false
}
}
} label: {
if isSendingReport {
ProgressView()
} else {
Text("report.action.send")
}
}
} label: {
if isSendingReport {
ProgressView()
} else {
Text("report.action.send")
}
}
}
CancelToolbarItem()
}
CancelToolbarItem()
}
}
}
}

View file

@ -18,7 +18,7 @@ private struct SafariRouter: ViewModifier {
@Environment(RouterPath.self) private var routerPath
#if !os(visionOS)
@State private var safariManager = InAppSafariManager()
@State private var safariManager = InAppSafariManager()
#endif
func body(content: Content) -> some View {
@ -52,78 +52,78 @@ private struct SafariRouter: ViewModifier {
return .systemAction
}
#if os(visionOS)
return .systemAction
return .systemAction
#else
return safariManager.open(url)
return safariManager.open(url)
#endif
#else
return .systemAction
#endif
}
}
#if !os(visionOS)
#if !os(visionOS)
.background {
WindowReader { window in
safariManager.windowScene = window.windowScene
}
}
#endif
#endif
}
}
#if !os(visionOS)
@MainActor
@Observable private class InAppSafariManager: NSObject, SFSafariViewControllerDelegate {
var windowScene: UIWindowScene?
let viewController: UIViewController = .init()
var window: UIWindow?
@MainActor
func open(_ url: URL) -> OpenURLAction.Result {
guard let windowScene else { return .systemAction }
@Observable private class InAppSafariManager: NSObject, SFSafariViewControllerDelegate {
var windowScene: UIWindowScene?
let viewController: UIViewController = .init()
var window: UIWindow?
window = setupWindow(windowScene: windowScene)
@MainActor
func open(_ url: URL) -> OpenURLAction.Result {
guard let windowScene else { return .systemAction }
let configuration = SFSafariViewController.Configuration()
configuration.entersReaderIfAvailable = UserPreferences.shared.inAppBrowserReaderView
window = setupWindow(windowScene: windowScene)
let safari = SFSafariViewController(url: url, configuration: configuration)
safari.preferredBarTintColor = UIColor(Theme.shared.primaryBackgroundColor)
safari.preferredControlTintColor = UIColor(Theme.shared.tintColor)
safari.delegate = self
let configuration = SFSafariViewController.Configuration()
configuration.entersReaderIfAvailable = UserPreferences.shared.inAppBrowserReaderView
DispatchQueue.main.async { [weak self] in
self?.viewController.present(safari, animated: true)
let safari = SFSafariViewController(url: url, configuration: configuration)
safari.preferredBarTintColor = UIColor(Theme.shared.primaryBackgroundColor)
safari.preferredControlTintColor = UIColor(Theme.shared.tintColor)
safari.delegate = self
DispatchQueue.main.async { [weak self] in
self?.viewController.present(safari, animated: true)
}
return .handled
}
return .handled
}
func setupWindow(windowScene: UIWindowScene) -> UIWindow {
let window = window ?? UIWindow(windowScene: windowScene)
func setupWindow(windowScene: UIWindowScene) -> UIWindow {
let window = window ?? UIWindow(windowScene: windowScene)
window.rootViewController = viewController
window.makeKeyAndVisible()
window.rootViewController = viewController
window.makeKeyAndVisible()
switch Theme.shared.selectedScheme {
case .dark:
window.overrideUserInterfaceStyle = .dark
case .light:
window.overrideUserInterfaceStyle = .light
}
switch Theme.shared.selectedScheme {
case .dark:
window.overrideUserInterfaceStyle = .dark
case .light:
window.overrideUserInterfaceStyle = .light
self.window = window
return window
}
self.window = window
return window
}
nonisolated func safariViewControllerDidFinish(_: SFSafariViewController) {
Task { @MainActor in
window?.resignKey()
window?.isHidden = false
window = nil
nonisolated func safariViewControllerDidFinish(_: SFSafariViewController) {
Task { @MainActor in
window?.resignKey()
window?.isHidden = false
window = nil
}
}
}
}
#endif
private struct WindowReader: UIViewRepresentable {

View file

@ -17,12 +17,12 @@ struct SideBarView<Content: View>: View {
@Environment(StreamWatcher.self) private var watcher
@Environment(UserPreferences.self) private var userPreferences
@Environment(RouterPath.self) private var routerPath
@Binding var selectedTab: Tab
@Binding var popToRootTab: Tab
var tabs: [Tab]
@ViewBuilder var content: () -> Content
@State private var sidebarTabs = SidebarTabs.shared
private func badgeFor(tab: Tab) -> Int {
@ -166,7 +166,7 @@ struct SideBarView<Content: View>: View {
.frame(width: .sidebarWidth)
.background(.thinMaterial)
})
Divider().edgesIgnoringSafeArea(.all)
Divider().edgesIgnoringSafeArea(.all)
}
content()
}

View file

@ -1,18 +1,18 @@
import SwiftUI
import Env
import AppAccount
import DesignSystem
import Env
import SwiftUI
@MainActor
struct NavigationSheet<Content: View>: View {
@Environment(\.dismiss) private var dismiss
var content: () -> Content
init(@ViewBuilder content: @escaping () -> Content) {
self.content = content
}
var body: some View {
NavigationStack {
content()

View file

@ -1,27 +1,27 @@
import SwiftUI
import Env
import AppAccount
import DesignSystem
import Env
import Network
import SwiftUI
@MainActor
struct NavigationTab<Content: View>: View {
@Environment(\.isSecondaryColumn) private var isSecondaryColumn: Bool
@Environment(AppAccountsManager.self) private var appAccount
@Environment(CurrentAccount.self) private var currentAccount
@Environment(UserPreferences.self) private var userPreferences
@Environment(Theme.self) private var theme
@Environment(Client.self) private var client
var content: () -> Content
@State private var routerPath = RouterPath()
init(@ViewBuilder content: @escaping () -> Content) {
self.content = content
}
var body: some View {
NavigationStack(path: $routerPath.path) {
content()

View file

@ -21,7 +21,7 @@ struct NotificationsTab: View {
@Environment(PushNotificationsService.self) private var pushNotificationsService
@State private var routerPath = RouterPath()
@State private var scrollToTopSignal: Int = 0
@Binding var selectedTab: Tab
@Binding var popToRootTab: Tab
@ -60,9 +60,9 @@ struct NotificationsTab: View {
}
}
}
.onChange(of: selectedTab, { _, newValue in
.onChange(of: selectedTab) { _, _ in
clearNotifications()
})
}
.onChange(of: pushNotificationsService.handledNotification) { _, newValue in
if let newValue, let type = newValue.notification.supportedType {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {

View file

@ -28,26 +28,26 @@ struct AboutView: View {
List {
Section {
#if !targetEnvironment(macCatalyst) && !os(visionOS)
HStack {
Spacer()
Image(uiImage: .init(named: "AppIconAlternate0")!)
.resizable()
.frame(width: 50, height: 50)
.cornerRadius(4)
Image(uiImage: .init(named: "AppIconAlternate4")!)
.resizable()
.frame(width: 50, height: 50)
.cornerRadius(4)
Image(uiImage: .init(named: "AppIconAlternate17")!)
.resizable()
.frame(width: 50, height: 50)
.cornerRadius(4)
Image(uiImage: .init(named: "AppIconAlternate23")!)
.resizable()
.frame(width: 50, height: 50)
.cornerRadius(4)
Spacer()
}
HStack {
Spacer()
Image(uiImage: .init(named: "AppIconAlternate0")!)
.resizable()
.frame(width: 50, height: 50)
.cornerRadius(4)
Image(uiImage: .init(named: "AppIconAlternate4")!)
.resizable()
.frame(width: 50, height: 50)
.cornerRadius(4)
Image(uiImage: .init(named: "AppIconAlternate17")!)
.resizable()
.frame(width: 50, height: 50)
.cornerRadius(4)
Image(uiImage: .init(named: "AppIconAlternate23")!)
.resizable()
.frame(width: 50, height: 50)
.cornerRadius(4)
Spacer()
}
#endif
Link(destination: URL(string: "https://github.com/Dimillian/IceCubesApp/blob/main/PRIVACY.MD")!) {
Label("settings.support.privacy-policy", systemImage: "lock")
@ -107,14 +107,14 @@ struct AboutView: View {
}
.listStyle(.insetGrouped)
#if !os(visionOS)
.scrollContentBackground(.hidden)
.background(theme.secondaryBackgroundColor)
.scrollContentBackground(.hidden)
.background(theme.secondaryBackgroundColor)
#endif
.navigationTitle(Text("settings.about.title"))
.navigationBarTitleDisplayMode(.large)
.environment(\.openURL, OpenURLAction { url in
routerPath.handle(url: url)
})
.navigationTitle(Text("settings.about.title"))
.navigationBarTitleDisplayMode(.large)
.environment(\.openURL, OpenURLAction { url in
routerPath.handle(url: url)
})
}
@ViewBuilder

View file

@ -17,9 +17,8 @@ struct AccountSettingsView: View {
@Environment(Theme.self) private var theme
@Environment(AppAccountsManager.self) private var appAccountsManager
@Environment(Client.self) private var client
@Environment(RouterPath.self) private var routerPath
@State private var isEditingAccount: Bool = false
@State private var isEditingFilters: Bool = false
@State private var cachedPostsCount: Int = 0
@State private var timelineCache = TimelineCache()
@ -30,7 +29,7 @@ struct AccountSettingsView: View {
Form {
Section {
Button {
isEditingAccount = true
routerPath.presentedSheet = .accountFiltersList
} label: {
Label("account.action.edit-info", systemImage: "pencil")
.frame(maxWidth: .infinity, alignment: .leading)
@ -40,7 +39,7 @@ struct AccountSettingsView: View {
if currentInstance.isFiltersSupported {
Button {
isEditingFilters = true
routerPath.presentedSheet = .accountFiltersList
} label: {
Label("account.action.edit-filters", systemImage: "line.3.horizontal.decrease.circle")
.frame(maxWidth: .infinity, alignment: .leading)
@ -96,12 +95,6 @@ struct AccountSettingsView: View {
}
.listRowBackground(theme.primaryBackgroundColor)
}
.sheet(isPresented: $isEditingAccount, content: {
EditAccountView()
})
.sheet(isPresented: $isEditingFilters, content: {
FiltersListView()
})
.toolbar {
ToolbarItem(placement: .principal) {
HStack {
@ -116,8 +109,8 @@ struct AccountSettingsView: View {
}
.navigationTitle(account.safeDisplayName)
#if !os(visionOS)
.scrollContentBackground(.hidden)
.background(theme.secondaryBackgroundColor)
.scrollContentBackground(.hidden)
.background(theme.secondaryBackgroundColor)
#endif
}
}

View file

@ -82,75 +82,75 @@ struct AddAccountView: View {
.navigationTitle("account.add.navigation-title")
.navigationBarTitleDisplayMode(.inline)
#if !os(visionOS)
.scrollContentBackground(.hidden)
.background(theme.secondaryBackgroundColor)
.scrollDismissesKeyboard(.immediately)
.scrollContentBackground(.hidden)
.background(theme.secondaryBackgroundColor)
.scrollDismissesKeyboard(.immediately)
#endif
.toolbar {
if !appAccountsManager.availableAccounts.isEmpty {
CancelToolbarItem()
}
}
.onAppear {
isInstanceURLFieldFocused = true
Task {
let instances = await instanceSocialClient.fetchInstances(keyword: instanceName)
withAnimation {
self.instances = instances
.toolbar {
if !appAccountsManager.availableAccounts.isEmpty {
CancelToolbarItem()
}
}
isSigninIn = false
}
.onChange(of: instanceName) {
searchingTask.cancel()
searchingTask = Task {
try? await Task.sleep(for: .seconds(0.1))
guard !Task.isCancelled else { return }
let instances = await instanceSocialClient.fetchInstances(keyword: instanceName)
withAnimation {
self.instances = instances
}
}
getInstanceDetailTask.cancel()
getInstanceDetailTask = Task {
try? await Task.sleep(for: .seconds(0.1))
guard !Task.isCancelled else { return }
do {
// bare bones preflight for domain validity
let instanceDetailClient = Client(server: sanitizedName)
if
instanceDetailClient.server.contains("."),
instanceDetailClient.server.last != "."
{
let instance: Instance = try await instanceDetailClient.get(endpoint: Instances.instance)
withAnimation {
self.instance = instance
instanceName = sanitizedName // clean up the text box, principally to chop off the username if present so it's clear that you might not wind up siging in as the thing in the box
}
instanceFetchError = nil
} else {
instance = nil
instanceFetchError = nil
.onAppear {
isInstanceURLFieldFocused = true
Task {
let instances = await instanceSocialClient.fetchInstances(keyword: instanceName)
withAnimation {
self.instances = instances
}
}
isSigninIn = false
}
.onChange(of: instanceName) {
searchingTask.cancel()
searchingTask = Task {
try? await Task.sleep(for: .seconds(0.1))
guard !Task.isCancelled else { return }
let instances = await instanceSocialClient.fetchInstances(keyword: instanceName)
withAnimation {
self.instances = instances
}
}
getInstanceDetailTask.cancel()
getInstanceDetailTask = Task {
try? await Task.sleep(for: .seconds(0.1))
guard !Task.isCancelled else { return }
do {
// bare bones preflight for domain validity
let instanceDetailClient = Client(server: sanitizedName)
if
instanceDetailClient.server.contains("."),
instanceDetailClient.server.last != "."
{
let instance: Instance = try await instanceDetailClient.get(endpoint: Instances.instance)
withAnimation {
self.instance = instance
instanceName = sanitizedName // clean up the text box, principally to chop off the username if present so it's clear that you might not wind up siging in as the thing in the box
}
instanceFetchError = nil
} else {
instance = nil
instanceFetchError = nil
}
} catch _ as DecodingError {
instance = nil
instanceFetchError = "account.add.error.instance-not-supported"
} catch {
instance = nil
}
} catch _ as DecodingError {
instance = nil
instanceFetchError = "account.add.error.instance-not-supported"
} catch {
instance = nil
}
}
}
.onChange(of: scenePhase) { _, newValue in
switch newValue {
case .active:
isSigninIn = false
default:
break
.onChange(of: scenePhase) { _, newValue in
switch newValue {
case .active:
isSigninIn = false
default:
break
}
}
}
}
}
@ -214,9 +214,9 @@ struct AddAccountView: View {
.foregroundColor(.primary)
Spacer()
(Text("instance.list.users-\(formatAsNumber(instance.users))")
+ Text("")
+ Text("instance.list.posts-\(formatAsNumber(instance.statuses))"))
.foregroundStyle(theme.tintColor)
+ Text("")
+ Text("instance.list.posts-\(formatAsNumber(instance.statuses))"))
.foregroundStyle(theme.tintColor)
}
.padding(.bottom, 5)
Text(instance.info?.shortDescription?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "")
@ -263,7 +263,7 @@ struct AddAccountView: View {
.redacted(reason: .placeholder)
.allowsHitTesting(false)
#if !os(visionOS)
.listRowBackground(theme.primaryBackgroundColor)
.listRowBackground(theme.primaryBackgroundColor)
#endif
}

View file

@ -5,14 +5,14 @@ import Models
import Network
import NukeUI
import SwiftUI
import UserNotifications
import Timeline
import UserNotifications
@MainActor
struct ContentSettingsView: View {
@Environment(UserPreferences.self) private var userPreferences
@Environment(Theme.self) private var theme
@State private var contentFilter = TimelineContentFilter.shared
var body: some View {
@ -41,7 +41,7 @@ struct ContentSettingsView: View {
}
}
}
#if !os(visionOS)
#if !os(visionOS)
.listRowBackground(theme.primaryBackgroundColor)
#endif
@ -113,7 +113,7 @@ struct ContentSettingsView: View {
Text("settings.content.default-sensitive")
}
.disabled(userPreferences.useInstanceContentSettings)
Toggle(isOn: $userPreferences.appRequireAltText) {
Text("settings.content.require-alt-text")
}
@ -121,7 +121,7 @@ struct ContentSettingsView: View {
#if !os(visionOS)
.listRowBackground(theme.primaryBackgroundColor)
#endif
Section("timeline.content-filter.title") {
Toggle(isOn: $contentFilter.showBoosts) {
Label("timeline.filter.show-boosts", image: "Rocket")
@ -142,8 +142,8 @@ struct ContentSettingsView: View {
}
.navigationTitle("settings.content.navigation-title")
#if !os(visionOS)
.scrollContentBackground(.hidden)
.background(theme.secondaryBackgroundColor)
.scrollContentBackground(.hidden)
.background(theme.secondaryBackgroundColor)
#endif
}
}

View file

@ -7,6 +7,7 @@ import Observation
import StatusKit
import SwiftUI
@MainActor
@Observable class DisplaySettingsLocalValues {
var tintColor = Theme.shared.tintColor
var primaryBackgroundColor = Theme.shared.primaryBackgroundColor
@ -36,11 +37,11 @@ struct DisplaySettingsView: View {
ZStack(alignment: .top) {
Form {
#if !os(visionOS)
StatusRowView(viewModel: previewStatusViewModel)
.allowsHitTesting(false)
.opacity(0)
.hidden()
themeSection
StatusRowView(viewModel: previewStatusViewModel)
.allowsHitTesting(false)
.opacity(0)
.hidden()
themeSection
#endif
fontSection
layoutSection
@ -49,35 +50,35 @@ struct DisplaySettingsView: View {
}
.navigationTitle("settings.display.navigation-title")
#if !os(visionOS)
.scrollContentBackground(.hidden)
.background(theme.secondaryBackgroundColor)
.scrollContentBackground(.hidden)
.background(theme.secondaryBackgroundColor)
#endif
.task(id: localValues.tintColor) {
do { try await Task.sleep(for: .microseconds(500)) } catch {}
theme.tintColor = localValues.tintColor
}
.task(id: localValues.primaryBackgroundColor) {
do { try await Task.sleep(for: .microseconds(500)) } catch {}
theme.primaryBackgroundColor = localValues.primaryBackgroundColor
}
.task(id: localValues.secondaryBackgroundColor) {
do { try await Task.sleep(for: .microseconds(500)) } catch {}
theme.secondaryBackgroundColor = localValues.secondaryBackgroundColor
}
.task(id: localValues.labelColor) {
do { try await Task.sleep(for: .microseconds(500)) } catch {}
theme.labelColor = localValues.labelColor
}
.task(id: localValues.lineSpacing) {
do { try await Task.sleep(for: .microseconds(500)) } catch {}
theme.lineSpacing = localValues.lineSpacing
}
.task(id: localValues.fontSizeScale) {
do { try await Task.sleep(for: .microseconds(500)) } catch {}
theme.fontSizeScale = localValues.fontSizeScale
}
.task(id: localValues.tintColor) {
do { try await Task.sleep(for: .microseconds(500)) } catch {}
theme.tintColor = localValues.tintColor
}
.task(id: localValues.primaryBackgroundColor) {
do { try await Task.sleep(for: .microseconds(500)) } catch {}
theme.primaryBackgroundColor = localValues.primaryBackgroundColor
}
.task(id: localValues.secondaryBackgroundColor) {
do { try await Task.sleep(for: .microseconds(500)) } catch {}
theme.secondaryBackgroundColor = localValues.secondaryBackgroundColor
}
.task(id: localValues.labelColor) {
do { try await Task.sleep(for: .microseconds(500)) } catch {}
theme.labelColor = localValues.labelColor
}
.task(id: localValues.lineSpacing) {
do { try await Task.sleep(for: .microseconds(500)) } catch {}
theme.lineSpacing = localValues.lineSpacing
}
.task(id: localValues.fontSizeScale) {
do { try await Task.sleep(for: .microseconds(500)) } catch {}
theme.fontSizeScale = localValues.fontSizeScale
}
#if !os(visionOS)
examplePost
examplePost
#endif
}
}

View file

@ -23,8 +23,8 @@ struct HapticSettingsView: View {
}
.navigationTitle("settings.haptic.navigation-title")
#if !os(visionOS)
.scrollContentBackground(.hidden)
.background(theme.secondaryBackgroundColor)
.scrollContentBackground(.hidden)
.background(theme.secondaryBackgroundColor)
#endif
}
}

View file

@ -14,8 +14,8 @@ struct InstanceInfoView: View {
}
.navigationTitle("instance.info.navigation-title")
#if !os(visionOS)
.scrollContentBackground(.hidden)
.background(theme.secondaryBackgroundColor)
.scrollContentBackground(.hidden)
.background(theme.secondaryBackgroundColor)
#endif
}
}

View file

@ -111,12 +111,12 @@ struct PushNotificationsView: View {
}
.navigationTitle("settings.push.navigation-title")
#if !os(visionOS)
.scrollContentBackground(.hidden)
.background(theme.secondaryBackgroundColor)
.scrollContentBackground(.hidden)
.background(theme.secondaryBackgroundColor)
#endif
.task {
await subscription.fetchSubscription()
}
.task {
await subscription.fetchSubscription()
}
}
private func updateSubscription() {

View file

@ -1,17 +1,17 @@
import SwiftUI
import SwiftData
import Models
import Env
import DesignSystem
import Env
import Models
import SwiftData
import SwiftUI
struct RecenTagsSettingView: View {
@Environment(\.modelContext) private var context
@Environment(RouterPath.self) private var routerPath
@Environment(Theme.self) private var theme
@Query(sort: \RecentTag.lastUse, order: .reverse) var tags: [RecentTag]
var body: some View {
Form {
ForEach(tags) { tag in
@ -35,10 +35,10 @@ struct RecenTagsSettingView: View {
.navigationTitle("settings.general.recent-tags")
.scrollContentBackground(.hidden)
#if !os(visionOS)
.background(theme.secondaryBackgroundColor)
.background(theme.secondaryBackgroundColor)
#endif
.toolbar {
EditButton()
}
.toolbar {
EditButton()
}
}
}

View file

@ -1,17 +1,17 @@
import SwiftUI
import SwiftData
import Models
import Env
import DesignSystem
import Env
import Models
import SwiftData
import SwiftUI
struct RemoteTimelinesSettingView: View {
@Environment(\.modelContext) private var context
@Environment(RouterPath.self) private var routerPath
@Environment(Theme.self) private var theme
@Query(sort: \LocalTimeline.creationDate, order: .reverse) var localTimelines: [LocalTimeline]
var body: some View {
Form {
ForEach(localTimelines) { timeline in
@ -36,10 +36,10 @@ struct RemoteTimelinesSettingView: View {
.navigationTitle("settings.general.remote-timelines")
.scrollContentBackground(.hidden)
#if !os(visionOS)
.background(theme.secondaryBackgroundColor)
.background(theme.secondaryBackgroundColor)
#endif
.toolbar {
EditButton()
}
.toolbar {
EditButton()
}
}
}

View file

@ -43,27 +43,27 @@ struct SettingsTabs: View {
}
.scrollContentBackground(.hidden)
#if !os(visionOS)
.background(theme.secondaryBackgroundColor)
.background(theme.secondaryBackgroundColor)
#endif
.navigationTitle(Text("settings.title"))
.navigationBarTitleDisplayMode(.inline)
.toolbarBackground(theme.primaryBackgroundColor.opacity(0.30), for: .navigationBar)
.toolbar {
if isModal {
ToolbarItem {
Button {
dismiss()
} label: {
Text("action.done").bold()
.navigationTitle(Text("settings.title"))
.navigationBarTitleDisplayMode(.inline)
.toolbarBackground(theme.primaryBackgroundColor.opacity(0.30), for: .navigationBar)
.toolbar {
if isModal {
ToolbarItem {
Button {
dismiss()
} label: {
Text("action.done").bold()
}
}
}
if UIDevice.current.userInterfaceIdiom == .pad, !preferences.showiPadSecondaryColumn, !isModal {
SecondaryColumnToolbarItem()
}
}
if UIDevice.current.userInterfaceIdiom == .pad, !preferences.showiPadSecondaryColumn, !isModal {
SecondaryColumnToolbarItem()
}
}
.withAppRouter()
.withSheetDestinations(sheetDestinations: $routerPath.presentedSheet)
.withAppRouter()
.withSheetDestinations(sheetDestinations: $routerPath.presentedSheet)
}
.onAppear {
routerPath.client = client

View file

@ -2,10 +2,11 @@ import DesignSystem
import Env
import SwiftUI
@MainActor
struct SidebarEntriesSettingsView: View {
@Environment(Theme.self) private var theme
@Environment(UserPreferences.self) private var userPreferences
@State private var sidebarTabs = SidebarTabs.shared
var body: some View {
@ -28,11 +29,11 @@ struct SidebarEntriesSettingsView: View {
.environment(\.editMode, .constant(.active))
.navigationTitle("settings.general.sidebarEntries")
#if !os(visionOS)
.scrollContentBackground(.hidden)
.background(theme.secondaryBackgroundColor)
.scrollContentBackground(.hidden)
.background(theme.secondaryBackgroundColor)
#endif
}
func move(from source: IndexSet, to destination: Int) {
sidebarTabs.tabs.move(fromOffsets: source, toOffset: destination)
}

View file

@ -69,24 +69,24 @@ struct SupportAppView: View {
}
.navigationTitle("settings.support.navigation-title")
#if !os(visionOS)
.scrollContentBackground(.hidden)
.background(theme.secondaryBackgroundColor)
.scrollContentBackground(.hidden)
.background(theme.secondaryBackgroundColor)
#endif
.alert("settings.support.alert.title", isPresented: $purchaseSuccessDisplayed, actions: {
Button { purchaseSuccessDisplayed = false } label: { Text("alert.button.ok") }
}, message: {
Text("settings.support.alert.message")
})
.alert("alert.error", isPresented: $purchaseErrorDisplayed, actions: {
Button { purchaseErrorDisplayed = false } label: { Text("alert.button.ok") }
}, message: {
Text("settings.support.alert.error.message")
})
.onAppear {
loadingProducts = true
fetchStoreProducts()
refreshUserInfo()
}
.alert("settings.support.alert.title", isPresented: $purchaseSuccessDisplayed, actions: {
Button { purchaseSuccessDisplayed = false } label: { Text("alert.button.ok") }
}, message: {
Text("settings.support.alert.message")
})
.alert("alert.error", isPresented: $purchaseErrorDisplayed, actions: {
Button { purchaseErrorDisplayed = false } label: { Text("alert.button.ok") }
}, message: {
Text("settings.support.alert.error.message")
})
.onAppear {
loadingProducts = true
fetchStoreProducts()
refreshUserInfo()
}
}
private func purchase(product: StoreProduct) async {

View file

@ -49,7 +49,7 @@ struct SwipeActionsSettingsView: View {
#if !os(visionOS)
.listRowBackground(theme.primaryBackgroundColor)
#endif
Section {
Picker(selection: $userPreferences.swipeActionsIconStyle, label: Text("settings.swipeactions.icon-style")) {
ForEach(UserPreferences.SwipeActionsIconStyle.allCases, id: \.rawValue) { style in
@ -70,8 +70,8 @@ struct SwipeActionsSettingsView: View {
}
.navigationTitle("settings.swipeactions.navigation-title")
#if !os(visionOS)
.scrollContentBackground(.hidden)
.background(theme.secondaryBackgroundColor)
.scrollContentBackground(.hidden)
.background(theme.secondaryBackgroundColor)
#endif
}

View file

@ -6,7 +6,7 @@ import SwiftUI
struct TabbarEntriesSettingsView: View {
@Environment(Theme.self) private var theme
@Environment(UserPreferences.self) private var userPreferences
@State private var tabs = iOSTabs.shared
var body: some View {
@ -42,7 +42,7 @@ struct TabbarEntriesSettingsView: View {
#if !os(visionOS)
.listRowBackground(theme.primaryBackgroundColor)
#endif
Section {
Toggle("settings.display.show-tab-label", isOn: $userPreferences.showiPhoneTabLabel)
}
@ -52,8 +52,8 @@ struct TabbarEntriesSettingsView: View {
}
.navigationTitle("settings.general.tabbarEntries")
#if !os(visionOS)
.scrollContentBackground(.hidden)
.background(theme.secondaryBackgroundColor)
.scrollContentBackground(.hidden)
.background(theme.secondaryBackgroundColor)
#endif
}
}

View file

@ -1,17 +1,17 @@
import SwiftUI
import SwiftData
import Models
import Env
import DesignSystem
import Env
import Models
import SwiftData
import SwiftUI
struct TagsGroupSettingView: View {
@Environment(\.modelContext) private var context
@Environment(RouterPath.self) private var routerPath
@Environment(Theme.self) private var theme
@Query(sort: \TagGroup.creationDate, order: .reverse) var tagGroups: [TagGroup]
var body: some View {
Form {
ForEach(tagGroups) { group in
@ -41,10 +41,10 @@ struct TagsGroupSettingView: View {
.navigationTitle("timeline.filter.tag-groups")
.scrollContentBackground(.hidden)
#if !os(visionOS)
.background(theme.secondaryBackgroundColor)
.background(theme.secondaryBackgroundColor)
#endif
.toolbar {
EditButton()
}
.toolbar {
EditButton()
}
}
}

View file

@ -24,7 +24,7 @@ struct TranslationSettingsView: View {
#if !os(visionOS)
.listRowBackground(theme.primaryBackgroundColor)
#endif
if apiKey.isEmpty {
Section {
Link(destination: URL(string: "https://www.deepl.com/pro-api")!) {
@ -41,13 +41,13 @@ struct TranslationSettingsView: View {
}
.navigationTitle("settings.translation.navigation-title")
#if !os(visionOS)
.scrollContentBackground(.hidden)
.background(theme.secondaryBackgroundColor)
.scrollContentBackground(.hidden)
.background(theme.secondaryBackgroundColor)
#endif
.onChange(of: apiKey) {
writeNewValue()
}
.onAppear(perform: updatePrefs)
.onChange(of: apiKey) {
writeNewValue()
}
.onAppear(perform: updatePrefs)
}
@ViewBuilder

View file

@ -24,7 +24,7 @@ enum Tab: Int, Identifiable, Hashable, CaseIterable, Codable {
static func loggedOutTab() -> [Tab] {
[.timeline, .settings]
}
static func visionOSTab() -> [Tab] {
[.profile, .timeline, .notifications, .mentions, .explore, .post, .settings]
}
@ -71,7 +71,7 @@ enum Tab: Int, Identifiable, Hashable, CaseIterable, Codable {
case .links:
NavigationTab { TrendingLinksListView(cards: []) }
case .post:
VStack { }
VStack {}
case .other:
EmptyView()
}
@ -114,7 +114,6 @@ enum Tab: Int, Identifiable, Hashable, CaseIterable, Codable {
Label("explore.section.trending.links", systemImage: iconName)
case .other:
EmptyView()
}
}
@ -158,13 +157,14 @@ enum Tab: Int, Identifiable, Hashable, CaseIterable, Codable {
}
}
@MainActor
@Observable
class SidebarTabs {
struct SidedebarTab: Hashable, Codable {
let tab: Tab
var enabled: Bool
}
class Storage {
@AppStorage("sidebar_tabs") var tabs: [SidedebarTab] = [
.init(tab: .timeline, enabled: true),
@ -179,36 +179,37 @@ class SidebarTabs {
.init(tab: .favorites, enabled: true),
.init(tab: .followedTags, enabled: true),
.init(tab: .lists, enabled: true),
.init(tab: .settings, enabled: true),
.init(tab: .profile, enabled: true),
]
}
private let storage = Storage()
public static let shared = SidebarTabs()
var tabs: [SidedebarTab] {
didSet {
storage.tabs = tabs
}
}
func isEnabled(_ tab: Tab) -> Bool {
tabs.first(where: { $0.tab.id == tab.id })?.enabled == true
}
private init() {
tabs = storage.tabs
}
}
@MainActor
@Observable
class iOSTabs {
enum TabEntries: String {
case first, second, third, fourth, fifth
}
class Storage {
@AppStorage(TabEntries.first.rawValue) var firstTab = Tab.timeline
@AppStorage(TabEntries.second.rawValue) var secondTab = Tab.notifications
@ -216,44 +217,44 @@ class iOSTabs {
@AppStorage(TabEntries.fourth.rawValue) var fourthTab = Tab.messages
@AppStorage(TabEntries.fifth.rawValue) var fifthTab = Tab.profile
}
private let storage = Storage()
public static let shared = iOSTabs()
var tabs: [Tab] {
[firstTab, secondTab, thirdTab, fourthTab, fifthTab]
}
var firstTab: Tab {
didSet {
storage.firstTab = firstTab
}
}
var secondTab: Tab {
didSet {
storage.secondTab = secondTab
}
}
var thirdTab: Tab {
didSet {
storage.thirdTab = thirdTab
}
}
var fourthTab: Tab {
didSet {
storage.fourthTab = fourthTab
}
}
var fifthTab: Tab {
didSet {
storage.fifthTab = fifthTab
}
}
private init() {
firstTab = storage.firstTab
secondTab = storage.secondTab

View file

@ -61,20 +61,20 @@ struct EditTagGroupView: View {
)
.navigationBarTitleDisplayMode(.inline)
#if !os(visionOS)
.scrollContentBackground(.hidden)
.background(theme.secondaryBackgroundColor)
.scrollDismissesKeyboard(.interactively)
.scrollContentBackground(.hidden)
.background(theme.secondaryBackgroundColor)
.scrollDismissesKeyboard(.interactively)
#endif
.toolbar {
CancelToolbarItem()
ToolbarItem(placement: .navigationBarTrailing) {
Button("action.save", action: { save() })
.disabled(!tagGroup.isValid)
.toolbar {
CancelToolbarItem()
ToolbarItem(placement: .navigationBarTrailing) {
Button("action.save", action: { save() })
.disabled(!tagGroup.isValid)
}
}
.onAppear {
focusedField = .title
}
}
.onAppear {
focusedField = .title
}
}
}

View file

@ -52,29 +52,29 @@ struct AddRemoteTimelineView: View {
.navigationTitle("timeline.add-remote.title")
.navigationBarTitleDisplayMode(.inline)
#if !os(visionOS)
.scrollContentBackground(.hidden)
.background(theme.secondaryBackgroundColor)
.scrollDismissesKeyboard(.immediately)
.scrollContentBackground(.hidden)
.background(theme.secondaryBackgroundColor)
.scrollDismissesKeyboard(.immediately)
#endif
.toolbar {
CancelToolbarItem()
}
.onChange(of: instanceName) { _, newValue in
instanceNamePublisher.send(newValue)
}
.onReceive(instanceNamePublisher.debounce(for: .milliseconds(500), scheduler: DispatchQueue.main)) { newValue in
Task {
let client = Client(server: newValue)
instance = try? await client.get(endpoint: Instances.instance)
.toolbar {
CancelToolbarItem()
}
}
.onAppear {
isInstanceURLFieldFocused = true
let client = InstanceSocialClient()
Task {
instances = await client.fetchInstances(keyword: instanceName)
.onChange(of: instanceName) { _, newValue in
instanceNamePublisher.send(newValue)
}
.onReceive(instanceNamePublisher.debounce(for: .milliseconds(500), scheduler: DispatchQueue.main)) { newValue in
Task {
let client = Client(server: newValue)
instance = try? await client.get(endpoint: Instances.instance)
}
}
.onAppear {
isInstanceURLFieldFocused = true
let client = InstanceSocialClient()
Task {
instances = await client.fetchInstances(keyword: instanceName)
}
}
}
}
}

View file

@ -95,7 +95,7 @@ struct TimelineTab: View {
}
switch newValue {
case let .tagGroup(title, _, _):
if let group = tagGroups.first(where: { $0.title == title}) {
if let group = tagGroups.first(where: { $0.title == title }) {
selectedTagGroup = group
}
default:
@ -185,7 +185,7 @@ struct TimelineTab: View {
}
}
}
@ViewBuilder
private var headerGroup: some View {
ControlGroup {
@ -209,10 +209,10 @@ struct TimelineTab: View {
pinButton
}
}
@ViewBuilder
private var pinButton: some View {
let index = pinnedFilters.firstIndex(where: { $0.id == timeline.id})
let index = pinnedFilters.firstIndex(where: { $0.id == timeline.id })
Button {
withAnimation {
if let index {
@ -222,14 +222,14 @@ struct TimelineTab: View {
}
}
} label: {
if index != nil {
if index != nil {
Label("status.action.unpin", systemImage: "pin.slash")
} else {
Label("status.action.pin", systemImage: "pin")
}
}
}
private var timelineFiltersButtons: some View {
ForEach(TimelineFilter.availableTimeline(client: client), id: \.self) { timeline in
Button {
@ -239,7 +239,7 @@ struct TimelineTab: View {
}
}
}
@ViewBuilder
private var listsFiltersButons: some View {
Menu("timeline.filter.lists") {
@ -257,7 +257,7 @@ struct TimelineTab: View {
}
}
}
@ViewBuilder
private var tagsFiltersButtons: some View {
if !currentAccount.tags.isEmpty {
@ -272,7 +272,7 @@ struct TimelineTab: View {
}
}
}
private var localTimelinesFiltersButtons: some View {
Menu("timeline.filter.local") {
ForEach(localTimelines) { remoteLocal in
@ -291,7 +291,7 @@ struct TimelineTab: View {
}
}
}
private var tagGroupsFiltersButtons: some View {
Menu("timeline.filter.tag-groups") {
ForEach(tagGroups) { group in
@ -312,7 +312,7 @@ struct TimelineTab: View {
}
}
}
private var contentFilterButton: some View {
Button(action: {
routerPath.presentedSheet = .timelineContentFilter

View file

@ -1,23 +1,24 @@
import SwiftUI
import Env
import AppAccount
import DesignSystem
import Env
import SwiftUI
@MainActor
struct ToolbarTab: ToolbarContent {
@Environment(\.isSecondaryColumn) private var isSecondaryColumn: Bool
@Environment(\.horizontalSizeClass) private var horizontalSizeClass
@Environment(UserPreferences.self) private var userPreferences
@Binding var routerPath: RouterPath
var body: some ToolbarContent {
if !isSecondaryColumn {
statusEditorToolbarItem(routerPath: routerPath,
visibility: userPreferences.postVisibility)
if UIDevice.current.userInterfaceIdiom != .pad ||
(UIDevice.current.userInterfaceIdiom == .pad && horizontalSizeClass == .compact) {
(UIDevice.current.userInterfaceIdiom == .pad && horizontalSizeClass == .compact)
{
ToolbarItem(placement: .navigationBarLeading) {
AppAccountsSelectorView(routerPath: routerPath)
}

File diff suppressed because it is too large Load diff

View file

@ -24,7 +24,7 @@ extension NotificationService {
var _plaintext: Data?
do {
_plaintext = try AES.GCM.open(sealedBox, using: key)
} catch { }
} catch {}
guard let plaintext = _plaintext else {
return nil
}

View file

@ -2,11 +2,11 @@ import Account
import AppAccount
import DesignSystem
import Env
import Models
import Network
import StatusKit
import SwiftUI
import UIKit
import Models
class ShareViewController: UIViewController {
override func viewDidLoad() {

View file

@ -31,7 +31,7 @@ let package = Package(
.product(name: "Models", package: "Models"),
.product(name: "StatusKit", package: "StatusKit"),
.product(name: "Env", package: "Env"),
.product(name: "ButtonKit", package: "ButtonKit")
.product(name: "ButtonKit", package: "ButtonKit"),
],
swiftSettings: [
.enableExperimentalFeature("StrictConcurrency"),

View file

@ -28,16 +28,16 @@ public struct AccountDetailContextMenu: View {
Label("account.action.message", systemImage: "tray.full")
}
#if !targetEnvironment(macCatalyst)
#if !targetEnvironment(macCatalyst)
Divider()
#endif
#endif
if viewModel.relationship?.blocking == true {
Button {
Task {
do {
viewModel.relationship = try await client.post(endpoint: Accounts.unblock(id: account.id))
} catch { }
} catch {}
}
} label: {
Label("account.action.unblock", systemImage: "person.crop.circle.badge.exclamationmark")
@ -55,7 +55,7 @@ public struct AccountDetailContextMenu: View {
Task {
do {
viewModel.relationship = try await client.post(endpoint: Accounts.unmute(id: account.id))
} catch { }
} catch {}
}
} label: {
Label("account.action.unmute", systemImage: "speaker")
@ -67,7 +67,7 @@ public struct AccountDetailContextMenu: View {
Task {
do {
viewModel.relationship = try await client.post(endpoint: Accounts.mute(id: account.id, json: MuteData(duration: duration.rawValue)))
} catch { }
} catch {}
}
}
}
@ -86,7 +86,7 @@ public struct AccountDetailContextMenu: View {
viewModel.relationship = try await client.post(endpoint: Accounts.follow(id: account.id,
notify: false,
reblogs: relationship.showingReblogs))
} catch { }
} catch {}
}
} label: {
Label("account.action.notify-disable", systemImage: "bell.fill")
@ -98,7 +98,7 @@ public struct AccountDetailContextMenu: View {
viewModel.relationship = try await client.post(endpoint: Accounts.follow(id: account.id,
notify: true,
reblogs: relationship.showingReblogs))
} catch { }
} catch {}
}
} label: {
Label("account.action.notify-enable", systemImage: "bell")
@ -111,7 +111,7 @@ public struct AccountDetailContextMenu: View {
viewModel.relationship = try await client.post(endpoint: Accounts.follow(id: account.id,
notify: relationship.notifying,
reblogs: false))
} catch { }
} catch {}
}
} label: {
Label("account.action.reboosts-hide", image: "Rocket.Fill")
@ -123,7 +123,7 @@ public struct AccountDetailContextMenu: View {
viewModel.relationship = try await client.post(endpoint: Accounts.follow(id: account.id,
notify: relationship.notifying,
reblogs: true))
} catch { }
} catch {}
}
} label: {
Label("account.action.reboosts-show", image: "Rocket")
@ -131,9 +131,9 @@ public struct AccountDetailContextMenu: View {
}
}
#if !targetEnvironment(macCatalyst)
#if !targetEnvironment(macCatalyst)
Divider()
#endif
#endif
}
if let lang = preferences.serverPreferences?.postLanguage ?? Locale.current.language.languageCode?.identifier {
@ -164,7 +164,7 @@ public struct AccountDetailContextMenu: View {
}
#if !targetEnvironment(macCatalyst)
Divider()
Divider()
#endif
}
}

View file

@ -207,6 +207,7 @@ struct AccountDetailHeaderView: View {
.foregroundStyle(.secondary)
.textSelection(.enabled)
.accessibilityRespondsToUserInteraction(false)
movedToView
joinedAtView
}
.accessibilityElement(children: .contain)
@ -311,6 +312,17 @@ struct AccountDetailHeaderView: View {
}
}
@ViewBuilder
private var movedToView: some View {
if let movedTo = viewModel.account?.moved {
Button("account.movedto.redirect-\("@\(movedTo.acct)")") {
routerPath.navigate(to: .accountDetailWithAccount(account: movedTo))
}
.font(.scaledCallout)
.foregroundColor(.accentColor)
}
}
@ViewBuilder
private func makeNoteView(_ note: String) -> some View {
VStack(alignment: .leading, spacing: 4) {
@ -372,15 +384,15 @@ struct AccountDetailHeaderView: View {
.accessibilityElement(children: .contain)
.accessibilityLabel("accessibility.tabs.profile.fields.container.label")
#if os(visionOS)
.background(Material.thick)
.background(Material.thick)
#else
.background(theme.secondaryBackgroundColor)
.background(theme.secondaryBackgroundColor)
#endif
.cornerRadius(4)
.overlay(
RoundedRectangle(cornerRadius: 4)
.stroke(.gray.opacity(0.35), lineWidth: 1)
)
.cornerRadius(4)
.overlay(
RoundedRectangle(cornerRadius: 4)
.stroke(.gray.opacity(0.35), lineWidth: 1)
)
}
}
}

View file

@ -23,11 +23,8 @@ public struct AccountDetailView: View {
@State private var viewModel: AccountDetailViewModel
@State private var isCurrentUser: Bool = false
@State private var showBlockConfirmation: Bool = false
@State private var isEditingAccount: Bool = false
@State private var isEditingFilters: Bool = false
@State private var isEditingRelationshipNote: Bool = false
@State private var displayTitle: Bool = false
@Binding var scrollToTopSignal: Int
@ -88,14 +85,14 @@ public struct AccountDetailView: View {
.environment(\.defaultMinListRowHeight, 1)
.listStyle(.plain)
#if !os(visionOS)
.scrollContentBackground(.hidden)
.background(theme.primaryBackgroundColor)
.scrollContentBackground(.hidden)
.background(theme.primaryBackgroundColor)
#endif
.onChange(of: scrollToTopSignal) {
withAnimation {
proxy.scrollTo(ScrollToView.Constants.scrollToTop, anchor: .top)
.onChange(of: scrollToTopSignal) {
withAnimation {
proxy.scrollTo(ScrollToView.Constants.scrollToTop, anchor: .top)
}
}
}
}
.onAppear {
guard reasons != .placeholder else { return }
@ -136,20 +133,14 @@ public struct AccountDetailView: View {
viewModel.handleEvent(event: latestEvent, currentAccount: currentAccount)
}
}
.onChange(of: isEditingAccount) { _, newValue in
if !newValue {
.onChange(of: routerPath.presentedSheet) { oldValue, newValue in
if oldValue == .accountEditInfo || newValue == .accountEditInfo {
Task {
await viewModel.fetchAccount()
await preferences.refreshServerPreferences()
}
}
}
.sheet(isPresented: $isEditingAccount, content: {
EditAccountView()
})
.sheet(isPresented: $isEditingFilters, content: {
FiltersListView()
})
.sheet(isPresented: $isEditingRelationshipNote, content: {
EditRelationshipNoteView(accountDetailViewModel: viewModel)
})
@ -220,7 +211,6 @@ public struct AccountDetailView: View {
AvatarView(account.avatar, config: .badge)
.padding(.leading, -4)
.accessibilityLabel(account.safeDisplayName)
}
.accessibilityAddTraits(.isImage)
.buttonStyle(.plain)
@ -247,18 +237,18 @@ public struct AccountDetailView: View {
bottom: 0,
trailing: .layoutPadding))
.listRowSeparator(.hidden)
#if !os(visionOS)
#if !os(visionOS)
.listRowBackground(theme.primaryBackgroundColor)
#endif
#endif
ForEach(viewModel.pinned) { status in
StatusRowView(viewModel: .init(status: status, client: client, routerPath: routerPath))
}
Rectangle()
#if os(visionOS)
#if os(visionOS)
.fill(Color.clear)
#else
#else
.fill(theme.secondaryBackgroundColor)
#endif
#endif
.frame(height: 12)
.listRowInsets(.init())
.listRowSeparator(.hidden)
@ -288,7 +278,6 @@ public struct AccountDetailView: View {
routerPath.presentedSheet = .mentionStatusEditor(account: account,
visibility: preferences.postVisibility)
#endif
}
} label: {
Image(systemName: "arrowshape.turn.up.left")
@ -308,7 +297,7 @@ public struct AccountDetailView: View {
if isCurrentUser {
Button {
isEditingAccount = true
routerPath.presentedSheet = .accountEditInfo
} label: {
Label("account.action.edit-info", systemImage: "pencil")
}
@ -323,7 +312,7 @@ public struct AccountDetailView: View {
if currentInstance.isFiltersSupported {
Button {
isEditingFilters = true
routerPath.presentedSheet = .accountFiltersList
} label: {
Label("account.action.edit-filters", systemImage: "line.3.horizontal.decrease.circle")
}
@ -370,7 +359,7 @@ public struct AccountDetailView: View {
Task {
do {
viewModel.relationship = try await client.post(endpoint: Accounts.block(id: account.id))
} catch { }
} catch {}
}
}
}
@ -382,12 +371,13 @@ public struct AccountDetailView: View {
}
extension View {
@MainActor
func applyAccountDetailsRowStyle(theme: Theme) -> some View {
listRowInsets(.init())
.listRowSeparator(.hidden)
#if !os(visionOS)
#if !os(visionOS)
.listRowBackground(theme.primaryBackgroundColor)
#endif
#endif
}
}

View file

@ -84,7 +84,7 @@ import SwiftUI
private var tabTask: Task<Void, Never>?
private(set) var statuses: [Status] = []
var boosts: [Status] = []
/// When coming from a URL like a mention tap in a status.
@ -151,7 +151,7 @@ import SwiftUI
self.familiarFollowers = familiarFollowers?.first?.accounts ?? []
}
func fetchNewestStatuses(pullToRefresh: Bool) async {
func fetchNewestStatuses(pullToRefresh _: Bool) async {
guard let client else { return }
do {
statusesState = .loading
@ -166,7 +166,7 @@ import SwiftUI
pinned: nil))
StatusDataControllerProvider.shared.updateDataControllers(for: statuses, client: client)
if selectedTab == .boosts {
boosts = statuses.filter{ $0.reblog != nil }
boosts = statuses.filter { $0.reblog != nil }
}
if selectedTab == .statuses {
pinned =
@ -197,17 +197,17 @@ import SwiftUI
case .statuses, .replies, .boosts, .media:
guard let lastId = statuses.last?.id else { return }
let newStatuses: [Status] =
try await client.get(endpoint: Accounts.statuses(id: accountId,
sinceId: lastId,
tag: nil,
onlyMedia: selectedTab == .media,
excludeReplies: selectedTab != .replies,
excludeReblogs: selectedTab != .boosts,
pinned: nil))
try await client.get(endpoint: Accounts.statuses(id: accountId,
sinceId: lastId,
tag: nil,
onlyMedia: selectedTab == .media,
excludeReplies: selectedTab != .replies,
excludeReblogs: selectedTab != .boosts,
pinned: nil))
statuses.append(contentsOf: newStatuses)
if selectedTab == .boosts {
let newBoosts = statuses.filter{ $0.reblog != nil }
self.boosts.append(contentsOf: newBoosts)
let newBoosts = statuses.filter { $0.reblog != nil }
boosts.append(contentsOf: newBoosts)
}
StatusDataControllerProvider.shared.updateDataControllers(for: newStatuses, client: client)
if selectedTab == .boosts {
@ -253,7 +253,8 @@ import SwiftUI
if let event = event as? StreamEventUpdate {
if event.status.account.id == currentAccount.account?.id {
if (event.status.inReplyToId == nil && selectedTab == .statuses) ||
(event.status.inReplyToId != nil && selectedTab == .replies) {
(event.status.inReplyToId != nil && selectedTab == .replies)
{
statuses.insert(event.status, at: 0)
statusesState = .display(statuses: statuses, nextPageState: .hasNextPage)
}

View file

@ -45,7 +45,7 @@ public struct AccountsListView: View {
await viewModel.fetch()
}
}
@ViewBuilder
private var listView: some View {
if currentAccount.account?.id == viewModel.accountId {
@ -54,7 +54,7 @@ public struct AccountsListView: View {
standardList
}
}
private var searchableList: some View {
List {
listContent
@ -74,13 +74,13 @@ public struct AccountsListView: View {
}
}
}
private var standardList: some View {
List {
listContent
}
}
@ViewBuilder
private var listContent: some View {
switch viewModel.state {
@ -89,9 +89,9 @@ public struct AccountsListView: View {
AccountsListRow(viewModel: .init(account: .placeholder(), relationShip: .placeholder()))
.redacted(reason: .placeholder)
.allowsHitTesting(false)
#if !os(visionOS)
#if !os(visionOS)
.listRowBackground(theme.primaryBackgroundColor)
#endif
#endif
}
case let .display(accounts, relationships, nextPageState):
if case .followers = viewModel.mode,
@ -125,9 +125,9 @@ public struct AccountsListView: View {
if let relationship = relationships.first(where: { $0.id == account.id }) {
AccountsListRow(viewModel: .init(account: account,
relationShip: relationship))
#if !os(visionOS)
#if !os(visionOS)
.listRowBackground(theme.primaryBackgroundColor)
#endif
#endif
}
}
}
@ -140,16 +140,26 @@ public struct AccountsListView: View {
#if !os(visionOS)
.listRowBackground(theme.primaryBackgroundColor)
#endif
case .none:
EmptyView()
}
case let .error(error):
Text(error.localizedDescription)
#if !os(visionOS)
#if !os(visionOS)
.listRowBackground(theme.primaryBackgroundColor)
#endif
#endif
}
}
}
#Preview {
List {
AccountsListRow(viewModel: .init(account: .placeholder(),
relationShip: .placeholder()))
}
.listStyle(.plain)
.withPreviewsEnv()
.environment(Theme.shared)
}

View file

@ -1,8 +1,8 @@
import Models
import Network
import Observation
import SwiftUI
import OSLog
import SwiftUI
public enum AccountsListMode {
case following(accountId: String), followers(accountId: String)
@ -49,7 +49,7 @@ public enum AccountsListMode {
var state = State.loading
var totalCount: Int?
var accountId: String?
var searchQuery: String = ""
private var nextPageId: String?
@ -125,7 +125,7 @@ public enum AccountsListMode {
relationships: relationships,
nextPageState: link?.maxId != nil ? .hasNextPage : .none)
}
func search() async {
guard let client, !searchQuery.isEmpty else { return }
do {
@ -144,8 +144,6 @@ public enum AccountsListMode {
relationships: relationships,
nextPageState: .none)
}
} catch {
}
} catch {}
}
}

View file

@ -2,8 +2,8 @@ import DesignSystem
import Env
import Models
import Network
import SwiftUI
import NukeUI
import SwiftUI
@MainActor
public struct EditAccountView: View {
@ -13,8 +13,8 @@ public struct EditAccountView: View {
@Environment(UserPreferences.self) private var userPrefs
@State private var viewModel = EditAccountViewModel()
public init() { }
public init() {}
public var body: some View {
NavigationStack {
@ -31,24 +31,24 @@ public struct EditAccountView: View {
}
.environment(\.editMode, .constant(.active))
#if !os(visionOS)
.scrollContentBackground(.hidden)
.background(theme.secondaryBackgroundColor)
.scrollDismissesKeyboard(.immediately)
.scrollContentBackground(.hidden)
.background(theme.secondaryBackgroundColor)
.scrollDismissesKeyboard(.immediately)
#endif
.navigationTitle("account.edit.navigation-title")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
toolbarContent
}
.alert("account.edit.error.save.title",
isPresented: $viewModel.saveError,
actions: {
Button("alert.button.ok", action: {})
}, message: { Text("account.edit.error.save.message") })
.task {
viewModel.client = client
await viewModel.fetchAccount()
}
.navigationTitle("account.edit.navigation-title")
.navigationBarTitleDisplayMode(.inline)
.toolbar {
toolbarContent
}
.alert("account.edit.error.save.title",
isPresented: $viewModel.saveError,
actions: {
Button("alert.button.ok", action: {})
}, message: { Text("account.edit.error.save.message") })
.task {
viewModel.client = client
await viewModel.fetchAccount()
}
}
}
@ -64,7 +64,7 @@ public struct EditAccountView: View {
.listRowBackground(theme.primaryBackgroundColor)
#endif
}
private var imagesSection: some View {
Section {
ZStack(alignment: .center) {

View file

@ -1,9 +1,9 @@
import Models
import Network
import Observation
import SwiftUI
import PhotosUI
import StatusKit
import SwiftUI
@MainActor
@Observable class EditAccountViewModel {
@ -30,22 +30,23 @@ import StatusKit
var fields: [FieldEditViewModel] = []
var avatar: URL?
var header: URL?
var isPhotoPickerPresented: Bool = false {
didSet {
if !isPhotoPickerPresented && mediaPickers.isEmpty {
if !isPhotoPickerPresented, mediaPickers.isEmpty {
isChangingAvatar = false
isChangingHeader = false
}
}
}
var isChangingAvatar: Bool = false
var isChangingHeader: Bool = false
var isLoading: Bool = true
var isSaving: Bool = false
var saveError: Bool = false
var mediaPickers: [PhotosPickerItem] = [] {
didSet {
if let item = mediaPickers.first {
@ -108,47 +109,47 @@ import StatusKit
saveError = true
}
}
private func uploadHeader(data: Data) async -> Bool {
guard let client else { return false }
do {
let response = try await client.mediaUpload(endpoint: Accounts.updateCredentialsMedia,
version: .v1,
method: "PATCH",
mimeType: "image/jpeg",
filename: "header",
data: data)
version: .v1,
method: "PATCH",
mimeType: "image/jpeg",
filename: "header",
data: data)
return response?.statusCode == 200
} catch {
return false
}
}
private func uploadAvatar(data: Data) async -> Bool {
guard let client else { return false }
do {
let response = try await client.mediaUpload(endpoint: Accounts.updateCredentialsMedia,
version: .v1,
method: "PATCH",
mimeType: "image/jpeg",
filename: "avatar",
data: data)
version: .v1,
method: "PATCH",
mimeType: "image/jpeg",
filename: "avatar",
data: data)
return response?.statusCode == 200
} catch {
return false
}
}
private func getItemImageData(item: PhotosPickerItem) async -> Data? {
guard let imageFile = try? await item.loadTransferable(type: StatusEditor.ImageFileTranseferable.self) else { return nil }
let compressor = StatusEditor.Compressor()
guard let compressedData = await compressor.compressImageFrom(url: imageFile.url),
let image = UIImage(data: compressedData),
let uploadData = try? await compressor.compressImageForUpload(image)
let image = UIImage(data: compressedData),
let uploadData = try? await compressor.compressImageForUpload(image)
else { return nil }
return uploadData
}
}

View file

@ -71,20 +71,20 @@ struct EditFilterView: View {
.navigationTitle(filter?.title ?? NSLocalizedString("filter.new", comment: ""))
.navigationBarTitleDisplayMode(.inline)
#if !os(visionOS)
.scrollContentBackground(.hidden)
.scrollDismissesKeyboard(.interactively)
.background(theme.secondaryBackgroundColor)
.scrollContentBackground(.hidden)
.scrollDismissesKeyboard(.interactively)
.background(theme.secondaryBackgroundColor)
#endif
.onAppear {
if filter == nil {
focusedField = .title
.onAppear {
if filter == nil {
focusedField = .title
}
}
}
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
saveButton
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
saveButton
}
}
}
}
private var expirySection: some View {

View file

@ -74,18 +74,18 @@ public struct FiltersListView: View {
.navigationTitle("filter.filters")
.navigationBarTitleDisplayMode(.inline)
#if !os(visionOS)
.scrollContentBackground(.hidden)
.background(theme.secondaryBackgroundColor)
.scrollContentBackground(.hidden)
.background(theme.secondaryBackgroundColor)
#endif
.task {
do {
isLoading = true
filters = try await client.get(endpoint: ServerFilters.filters, forceVersion: .v2)
isLoading = false
} catch {
isLoading = false
.task {
do {
isLoading = true
filters = try await client.get(endpoint: ServerFilters.filters, forceVersion: .v2)
isLoading = false
} catch {
isLoading = false
}
}
}
}
}

View file

@ -4,8 +4,8 @@ import Foundation
import Models
import Network
import Observation
import SwiftUI
import OSLog
import SwiftUI
@MainActor
@Observable public class FollowButtonViewModel {

View file

@ -1,14 +1,14 @@
import DesignSystem
import Env
import Models
import SwiftUI
import Env
public struct ListsListView: View {
@Environment(CurrentAccount.self) private var currentAccount
@Environment(Theme.self) private var theme
public init() {}
public var body: some View {
List {
ForEach(currentAccount.lists) { list in
@ -43,4 +43,3 @@ public struct ListsListView: View {
.navigationBarTitleDisplayMode(.inline)
}
}

View file

@ -1,50 +1,50 @@
import StatusKit
import Network
import SwiftUI
import DesignSystem
import Env
import Models
import DesignSystem
import Network
import StatusKit
import SwiftUI
@MainActor
public struct AccountStatusesListView: View {
@Environment(Theme.self) private var theme
@Environment(Client.self) private var client
@Environment(RouterPath.self) private var routerPath
@State private var viewModel: AccountStatusesListViewModel
@State private var isLoaded = false
public init(mode: AccountStatusesListViewModel.Mode) {
_viewModel = .init(initialValue: .init(mode: mode))
}
public var body: some View {
List {
StatusesListView(fetcher: viewModel, client: client, routerPath: routerPath)
}
.listStyle(.plain)
#if !os(visionOS)
.scrollContentBackground(.hidden)
.background(theme.primaryBackgroundColor)
.scrollContentBackground(.hidden)
.background(theme.primaryBackgroundColor)
#endif
.navigationTitle(viewModel.mode.title)
.navigationBarTitleDisplayMode(.inline)
.refreshable {
await viewModel.fetchNewestStatuses(pullToRefresh: true)
}
.task {
guard !isLoaded else { return }
viewModel.client = client
await viewModel.fetchNewestStatuses(pullToRefresh: false)
isLoaded = true
}
.onChange(of: client.id) { _, _ in
isLoaded = false
viewModel.client = client
Task {
.navigationTitle(viewModel.mode.title)
.navigationBarTitleDisplayMode(.inline)
.refreshable {
await viewModel.fetchNewestStatuses(pullToRefresh: true)
}
.task {
guard !isLoaded else { return }
viewModel.client = client
await viewModel.fetchNewestStatuses(pullToRefresh: false)
isLoaded = true
}
}
.onChange(of: client.id) { _, _ in
isLoaded = false
viewModel.client = client
Task {
await viewModel.fetchNewestStatuses(pullToRefresh: false)
isLoaded = true
}
}
}
}

View file

@ -1,15 +1,15 @@
import SwiftUI
import Models
import StatusKit
import Network
import Env
import Models
import Network
import StatusKit
import SwiftUI
@MainActor
@Observable
public class AccountStatusesListViewModel: StatusesFetcher {
public enum Mode {
public enum Mode {
case bookmarks, favorites
var title: LocalizedStringKey {
switch self {
case .bookmarks:
@ -18,7 +18,7 @@ public class AccountStatusesListViewModel: StatusesFetcher {
"accessibility.tabs.profile.picker.favorites"
}
}
func endpoint(sinceId: String?) -> Endpoint {
switch self {
case .bookmarks:
@ -28,19 +28,19 @@ public class AccountStatusesListViewModel: StatusesFetcher {
}
}
}
let mode: Mode
public var statusesState: StatusesState = .loading
var statuses: [Status] = []
var nextPage: LinkHandler?
var client: Client?
init(mode: Mode) {
self.mode = mode
}
public func fetchNewestStatuses(pullToRefresh: Bool) async {
public func fetchNewestStatuses(pullToRefresh _: Bool) async {
guard let client else { return }
statusesState = .loading
do {
@ -52,7 +52,7 @@ public class AccountStatusesListViewModel: StatusesFetcher {
statusesState = .error(error: error)
}
}
public func fetchNextPage() async throws {
guard let client, let nextId = nextPage?.maxId else { return }
var newStatuses: [Status] = []
@ -62,12 +62,8 @@ public class AccountStatusesListViewModel: StatusesFetcher {
statusesState = .display(statuses: statuses,
nextPageState: nextPage?.maxId != nil ? .hasNextPage : .none)
}
public func statusDidAppear(status: Status) {
}
public func statusDidDisappear(status: Status) {
}
public func statusDidAppear(status _: Status) {}
public func statusDidDisappear(status _: Status) {}
}

View file

@ -1,20 +1,20 @@
import DesignSystem
import Env
import Models
import SwiftUI
import Env
public struct FollowedTagsListView: View {
@Environment(CurrentAccount.self) private var currentAccount
@Environment(Theme.self) private var theme
public init() {}
public var body: some View {
List(currentAccount.tags) { tag in
TagRowView(tag: tag)
#if !os(visionOS)
#if !os(visionOS)
.listRowBackground(theme.primaryBackgroundColor)
#endif
#endif
.padding(.vertical, 4)
}
.task {
@ -32,4 +32,3 @@ public struct FollowedTagsListView: View {
.navigationBarTitleDisplayMode(.inline)
}
}

View file

@ -13,7 +13,7 @@ public struct AppAccountView: View {
@State var viewModel: AppAccountViewModel
@Binding var isParentPresented: Bool
public init(viewModel: AppAccountViewModel, isParentPresented: Binding<Bool>) {
self.viewModel = viewModel
_isParentPresented = isParentPresented

View file

@ -33,11 +33,11 @@ public struct AppAccountsSelectorView: View {
public init(routerPath: RouterPath,
accountCreationEnabled: Bool = true,
avatarConfig: AvatarView.FrameConfig = .badge)
avatarConfig: AvatarView.FrameConfig? = nil)
{
self.routerPath = routerPath
self.accountCreationEnabled = accountCreationEnabled
self.avatarConfig = avatarConfig
self.avatarConfig = avatarConfig ?? .badge
}
public var body: some View {
@ -97,11 +97,11 @@ public struct AppAccountsSelectorView: View {
}
addAccountButton
#if os(visionOS)
.foregroundStyle(theme.labelColor)
.foregroundStyle(theme.labelColor)
#endif
}
#if !os(visionOS)
.listRowBackground(theme.primaryBackgroundColor)
.listRowBackground(theme.primaryBackgroundColor)
#endif
if accountCreationEnabled {
@ -134,7 +134,7 @@ public struct AppAccountsSelectorView: View {
.environment(routerPath)
}
}
private var addAccountButton: some View {
Button {
isPresented = false
@ -158,7 +158,7 @@ public struct AppAccountsSelectorView: View {
Label("tab.settings", systemImage: "gear")
}
}
private var supportButton: some View {
Button {
isPresented = false
@ -170,7 +170,7 @@ public struct AppAccountsSelectorView: View {
Label("settings.app.support", systemImage: "wand.and.stars")
}
}
private var aboutButton: some View {
Button {
isPresented = false

View file

@ -71,35 +71,35 @@ public struct ConversationDetailView: View {
}
.navigationBarTitleDisplayMode(.inline)
#if !os(visionOS)
.scrollContentBackground(.hidden)
.background(theme.primaryBackgroundColor)
.scrollContentBackground(.hidden)
.background(theme.primaryBackgroundColor)
#endif
.toolbar {
ToolbarItem(placement: .principal) {
if viewModel.conversation.accounts.count == 1,
let account = viewModel.conversation.accounts.first
{
EmojiTextApp(.init(stringValue: account.safeDisplayName), emojis: account.emojis)
.font(.scaledHeadline)
.foregroundColor(theme.labelColor)
.emojiText.size(Font.scaledHeadlineFont.emojiSize)
.emojiText.baselineOffset(Font.scaledHeadlineFont.emojiBaselineOffset)
} else {
Text("Direct message with \(viewModel.conversation.accounts.count) people")
.font(.scaledHeadline)
}
}
}
.onChange(of: watcher.latestEvent?.id) {
if let latestEvent = watcher.latestEvent {
viewModel.handleEvent(event: latestEvent)
DispatchQueue.main.async {
withAnimation {
scrollProxy?.scrollTo(Constants.bottomAnchor, anchor: .bottom)
.toolbar {
ToolbarItem(placement: .principal) {
if viewModel.conversation.accounts.count == 1,
let account = viewModel.conversation.accounts.first
{
EmojiTextApp(.init(stringValue: account.safeDisplayName), emojis: account.emojis)
.font(.scaledHeadline)
.foregroundColor(theme.labelColor)
.emojiText.size(Font.scaledHeadlineFont.emojiSize)
.emojiText.baselineOffset(Font.scaledHeadlineFont.emojiBaselineOffset)
} else {
Text("Direct message with \(viewModel.conversation.accounts.count) people")
.font(.scaledHeadline)
}
}
}
.onChange(of: watcher.latestEvent?.id) {
if let latestEvent = watcher.latestEvent {
viewModel.handleEvent(event: latestEvent)
DispatchQueue.main.async {
withAnimation {
scrollProxy?.scrollTo(Constants.bottomAnchor, anchor: .bottom)
}
}
}
}
}
}
private var loadingView: some View {

View file

@ -205,12 +205,12 @@ struct ConversationMessageView: View {
.frame(height: 200)
.contentShape(Rectangle())
.onTapGesture {
#if targetEnvironment(macCatalyst) || os(visionOS)
openWindow(value: WindowDestinationMedia.mediaViewer(attachments: [attachement],
selectedAttachment: attachement))
#else
quickLook.prepareFor(selectedMediaAttachment: attachement, mediaAttachments: [attachement])
#endif
#if targetEnvironment(macCatalyst) || os(visionOS)
openWindow(value: WindowDestinationMedia.mediaViewer(attachments: [attachement],
selectedAttachment: attachement))
#else
quickLook.prepareFor(selectedMediaAttachment: attachement, mediaAttachments: [attachement])
#endif
}
}

View file

@ -7,7 +7,7 @@ import SwiftUI
@MainActor
struct ConversationsListRow: View {
@Environment(\.openWindow) private var openWindow
@Environment(Client.self) private var client
@Environment(RouterPath.self) private var routerPath
@Environment(Theme.self) private var theme

View file

@ -48,9 +48,9 @@ public struct ConversationsListView: View {
Divider()
}
} else if conversations.isEmpty, !viewModel.isLoadingFirstPage, !viewModel.isError {
EmptyView(iconName: "tray",
title: "conversations.empty.title",
message: "conversations.empty.message")
PlaceholderView(iconName: "tray",
title: "conversations.empty.title",
message: "conversations.empty.message")
} else if viewModel.isError {
ErrorView(title: "conversations.error.title",
message: "conversations.error.message",

View file

@ -19,7 +19,7 @@ let package = Package(
dependencies: [
.package(name: "Models", path: "../Models"),
.package(name: "Env", path: "../Env"),
.package(url: "https://github.com/kean/Nuke", from: "12.0.0"),
.package(url: "https://github.com/kean/Nuke", from: "12.4.0"),
.package(url: "https://github.com/divadretlaw/EmojiText", from: "4.0.0"),
],
targets: [

View file

@ -201,4 +201,3 @@ public struct ThreadsLight: ColorSet {
public init() {}
}

View file

@ -1,11 +1,11 @@
import SwiftUI
public extension View {
@ViewBuilder func `if`<Content: View>(_ condition: Bool, transform: (Self) -> Content) -> some View {
if condition {
transform(self)
} else {
self
}
@ViewBuilder func `if`<Content: View>(_ condition: Bool, transform: (Self) -> Content) -> some View {
if condition {
transform(self)
} else {
self
}
}
}

View file

@ -2,14 +2,14 @@ import Combine
import UIKit
@Observable
public class SceneDelegate: NSObject, UIWindowSceneDelegate, Sendable {
@MainActor public class SceneDelegate: NSObject, UIWindowSceneDelegate, Sendable {
public var window: UIWindow?
#if os(visionOS)
public private(set) var windowWidth: CGFloat = 0
public private(set) var windowHeight: CGFloat = 0
public private(set) var windowWidth: CGFloat = 0
public private(set) var windowHeight: CGFloat = 0
#else
public private(set) var windowWidth: CGFloat = UIScreen.main.bounds.size.width
public private(set) var windowHeight: CGFloat = UIScreen.main.bounds.size.height
public private(set) var windowWidth: CGFloat = UIScreen.main.bounds.size.width
public private(set) var windowHeight: CGFloat = UIScreen.main.bounds.size.height
#endif
public func scene(_ scene: UIScene,
@ -30,11 +30,11 @@ public class SceneDelegate: NSObject, UIWindowSceneDelegate, Sendable {
override public init() {
super.init()
#if os(visionOS)
windowWidth = window?.bounds.size.width ?? 0
windowHeight = window?.bounds.size.height ?? 0
windowWidth = window?.bounds.size.width ?? 0
windowHeight = window?.bounds.size.height ?? 0
#else
windowWidth = window?.bounds.size.width ?? UIScreen.main.bounds.size.width
windowHeight = window?.bounds.size.height ?? UIScreen.main.bounds.size.height
windowWidth = window?.bounds.size.width ?? UIScreen.main.bounds.size.width
windowHeight = window?.bounds.size.height ?? UIScreen.main.bounds.size.height
#endif
Self.observedSceneDelegate.insert(self)
_ = Self.observer // just for activating the lazy static property
@ -47,30 +47,29 @@ public class SceneDelegate: NSObject, UIWindowSceneDelegate, Sendable {
}
private static var observedSceneDelegate: Set<SceneDelegate> = []
private static let observer = Task {
private static let observer = Task { @MainActor in
while true {
try? await Task.sleep(for: .seconds(0.1))
for delegate in observedSceneDelegate {
#if os(visionOS)
let newWidth = delegate.window?.bounds.size.width ?? 0
if delegate.windowWidth != newWidth {
delegate.windowWidth = newWidth
}
let newHeight = delegate.window?.bounds.size.height ?? 0
if delegate.windowHeight != newHeight {
delegate.windowHeight = newHeight
}
let newWidth = delegate.window?.bounds.size.width ?? 0
if delegate.windowWidth != newWidth {
delegate.windowWidth = newWidth
}
let newHeight = delegate.window?.bounds.size.height ?? 0
if delegate.windowHeight != newHeight {
delegate.windowHeight = newHeight
}
#else
let newWidth = delegate.window?.bounds.size.width ?? UIScreen.main.bounds.size.width
if delegate.windowWidth != newWidth {
delegate.windowWidth = newWidth
}
let newHeight = delegate.window?.bounds.size.height ?? UIScreen.main.bounds.size.height
if delegate.windowHeight != newHeight {
delegate.windowHeight = newHeight
}
let newWidth = delegate.window?.bounds.size.width ?? UIScreen.main.bounds.size.width
if delegate.windowWidth != newWidth {
delegate.windowWidth = newWidth
}
let newHeight = delegate.window?.bounds.size.height ?? UIScreen.main.bounds.size.height
if delegate.windowHeight != newHeight {
delegate.windowHeight = newHeight
}
#endif
}
}
}

View file

@ -1,8 +1,10 @@
import Combine
import SwiftUI
@Observable public class Theme {
class ThemeStorage {
@MainActor
@Observable
public final class Theme {
final class ThemeStorage {
enum ThemeKey: String {
case colorScheme, tint, label, primaryBackground, secondaryBackground
case avatarPosition2, avatarShape2, statusActionsDisplay, statusDisplayStyle
@ -69,10 +71,10 @@ import SwiftUI
}
}
}
public enum StatusActionSecondary: String, CaseIterable {
case share, bookmark
public var description: LocalizedStringKey {
switch self {
case .share:
@ -167,12 +169,14 @@ import SwiftUI
public var tintColor: Color {
didSet {
themeStorage.tintColor = tintColor
computeContrastingTintColor()
}
}
public var primaryBackgroundColor: Color {
didSet {
themeStorage.primaryBackgroundColor = primaryBackgroundColor
computeContrastingTintColor()
}
}
@ -185,6 +189,31 @@ import SwiftUI
public var labelColor: Color {
didSet {
themeStorage.labelColor = labelColor
computeContrastingTintColor()
}
}
public private(set) var contrastingTintColor: Color
// set contrastingTintColor to either labelColor or primaryBackgroundColor, whichever contrasts
// better against the tintColor
private func computeContrastingTintColor() {
func luminance(_ color: Color.Resolved) -> Float {
return 0.299 * color.red + 0.587 * color.green + 0.114 * color.blue
}
let resolvedTintColor = tintColor.resolve(in: .init())
let resolvedLabelColor = labelColor.resolve(in: .init())
let resolvedPrimaryBackgroundColor = primaryBackgroundColor.resolve(in: .init())
let tintLuminance = luminance(resolvedTintColor)
let labelLuminance = luminance(resolvedLabelColor)
let primaryBackgroundLuminance = luminance(resolvedPrimaryBackgroundColor)
if abs(tintLuminance - labelLuminance) > abs(tintLuminance - primaryBackgroundLuminance) {
contrastingTintColor = labelColor
} else {
contrastingTintColor = primaryBackgroundColor
}
}
@ -217,7 +246,7 @@ import SwiftUI
themeStorage.statusDisplayStyle = statusDisplayStyle
}
}
public var statusActionSecondary: StatusActionSecondary {
didSet {
themeStorage.statusActionSecondary = statusActionSecondary
@ -273,7 +302,7 @@ import SwiftUI
chosenFontData = nil
statusActionSecondary = .share
}
private init() {
isThemePreviouslySet = themeStorage.isThemePreviouslySet
selectedScheme = themeStorage.selectedScheme
@ -281,6 +310,7 @@ import SwiftUI
primaryBackgroundColor = themeStorage.primaryBackgroundColor
secondaryBackgroundColor = themeStorage.secondaryBackgroundColor
labelColor = themeStorage.labelColor
contrastingTintColor = .red // real work done in computeContrastingTintColor()
avatarPosition = themeStorage.avatarPosition
avatarShape = themeStorage.avatarShape
storedSet = themeStorage.storedSet
@ -293,6 +323,8 @@ import SwiftUI
chosenFontData = themeStorage.chosenFontData
statusActionSecondary = themeStorage.statusActionSecondary
selectedSet = storedSet
computeContrastingTintColor()
}
public static var allColorSet: [ColorSet] {
@ -310,7 +342,7 @@ import SwiftUI
ConstellationLight(),
ConstellationDark(),
ThreadsLight(),
ThreadsDark()
ThreadsDark(),
]
}

View file

@ -4,7 +4,7 @@ import SwiftUI
#endif
public extension View {
func applyTheme(_ theme: Theme) -> some View {
@MainActor func applyTheme(_ theme: Theme) -> some View {
modifier(ThemeApplier(theme: theme))
}
}
@ -77,17 +77,15 @@ struct ThemeApplier: ViewModifier {
}
private func setWindowUserInterfaceStyle(_ userInterfaceStyle: UIUserInterfaceStyle) {
allWindows()
.forEach {
$0.overrideUserInterfaceStyle = userInterfaceStyle
}
for window in allWindows() {
window.overrideUserInterfaceStyle = userInterfaceStyle
}
}
private func setWindowTint(_ color: Color) {
allWindows()
.forEach {
$0.tintColor = UIColor(color)
}
for window in allWindows() {
window.tintColor = UIColor(color)
}
}
private func setBarsColor(_ color: Color) {

View file

@ -2,9 +2,9 @@ import SwiftUI
public struct CancelToolbarItem: ToolbarContent {
@Environment(\.dismiss) private var dismiss
public init() { }
public init() {}
public var body: some ToolbarContent {
ToolbarItem(placement: .navigationBarLeading) {
Button("action.cancel", role: .cancel, action: { dismiss() })

View file

@ -4,6 +4,7 @@ import Nuke
import NukeUI
import SwiftUI
@MainActor
struct AccountPopoverView: View {
let account: Account
let theme: Theme // using `@Environment(Theme.self) will crash the SwiftUI preview

View file

@ -33,7 +33,8 @@ public struct AvatarView: View {
self.config = config
}
public struct FrameConfig: Equatable {
@MainActor
public struct FrameConfig: Equatable, Sendable {
public let size: CGSize
public var width: CGFloat { size.width }
public var height: CGFloat { size.height }

View file

@ -1,32 +0,0 @@
import SwiftUI
public struct EmptyView: View {
public let iconName: String
public let title: LocalizedStringKey
public let message: LocalizedStringKey
public init(iconName: String, title: LocalizedStringKey, message: LocalizedStringKey) {
self.iconName = iconName
self.title = title
self.message = message
}
public var body: some View {
VStack {
Image(systemName: iconName)
.resizable()
.aspectRatio(contentMode: .fit)
.frame(maxHeight: 50)
Text(title)
.font(.scaledTitle)
.padding(.top, 16)
Text(message)
.font(.scaledSubheadline)
.multilineTextAlignment(.center)
.foregroundStyle(.secondary)
}
.padding(.top, 100)
.padding(.layoutPadding)
.fixedSize(horizontal: false, vertical: true)
}
}

View file

@ -42,3 +42,9 @@ public struct ErrorView: View {
}
}
}
#Preview {
ErrorView(title: "Error",
message: "Error loading. Please try again",
buttonTitle: "Retry") {}
}

View file

@ -1,15 +1,16 @@
import SwiftUI
@MainActor
public struct NextPageView: View {
@State private var isLoadingNextPage: Bool = false
@State private var showRetry: Bool = false
let loadNextPage: (() async throws -> Void)
let loadNextPage: () async throws -> Void
public init(loadNextPage: @escaping (() async throws -> Void)) {
self.loadNextPage = loadNextPage
}
public var body: some View {
HStack {
if showRetry {
@ -35,7 +36,7 @@ public struct NextPageView: View {
}
.listRowSeparator(.hidden, edges: .all)
}
private func executeTask() async {
showRetry = false
defer {
@ -50,3 +51,11 @@ public struct NextPageView: View {
}
}
}
#Preview {
List {
Text("Item 1")
NextPageView {}
}
.listStyle(.plain)
}

View file

@ -0,0 +1,25 @@
import SwiftUI
public struct PlaceholderView: View {
public let iconName: String
public let title: LocalizedStringKey
public let message: LocalizedStringKey
public init(iconName: String, title: LocalizedStringKey, message: LocalizedStringKey) {
self.iconName = iconName
self.title = title
self.message = message
}
public var body: some View {
ContentUnavailableView(title,
systemImage: iconName,
description: Text(message))
}
}
#Preview {
PlaceholderView(iconName: "square.and.arrow.up.trianglebadge.exclamationmark",
title: "Nothing to see",
message: "This is a preview. Please try again.")
}

View file

@ -11,7 +11,7 @@ public struct ScrollToView: View {
public init() {}
public var body: some View {
HStack { SwiftUI.EmptyView() }
HStack { EmptyView() }
.listRowBackground(Color.clear)
.listRowSeparator(.hidden)
.listRowInsets(.init())

View file

@ -1,44 +0,0 @@
/*! @copyright 2021 Medium */
import SwiftUI
// Source: https://www.fivestars.blog/articles/scrollview-offset/
public struct ScrollViewOffsetReader<Content: View>: View {
let onOffsetChange: (CGFloat) -> Void
let content: () -> Content
public init(
onOffsetChange: @escaping (CGFloat) -> Void,
@ViewBuilder content: @escaping () -> Content
) {
self.onOffsetChange = onOffsetChange
self.content = content
}
public var body: some View {
ScrollView {
offsetReader
content()
.padding(.top, -8)
}
.coordinateSpace(name: "frameLayer")
.onPreferenceChange(OffsetPreferenceKey.self, perform: onOffsetChange)
}
var offsetReader: some View {
GeometryReader { proxy in
Color.clear
.preference(
key: OffsetPreferenceKey.self,
value: proxy.frame(in: .named("frameLayer")).minY
)
}
.frame(height: 0)
}
}
private struct OffsetPreferenceKey: PreferenceKey {
static var defaultValue: CGFloat = .zero
static func reduce(value _: inout CGFloat, nextValue _: () -> CGFloat) {}
}

View file

@ -56,12 +56,12 @@ public extension EnvironmentValues {
get { self[IsCompact.self] }
set { self[IsCompact.self] = newValue }
}
var isMediaCompact: Bool {
get { self[IsMediaCompact.self] }
set { self[IsMediaCompact.self] = newValue }
}
var isModal: Bool {
get { self[IsModal.self] }
set { self[IsModal.self] = newValue }

View file

@ -6,65 +6,65 @@ public class HapticManager {
public static let shared: HapticManager = .init()
#if os(visionOS)
public enum FeedbackType: Int {
case success, warning, error
}
public enum FeedbackType: Int {
case success, warning, error
}
#endif
public enum HapticType {
case buttonPress
case dataRefresh(intensity: CGFloat)
#if os(visionOS)
case notification(_ type: FeedbackType)
case notification(_ type: FeedbackType)
#else
case notification(_ type: UINotificationFeedbackGenerator.FeedbackType)
case notification(_ type: UINotificationFeedbackGenerator.FeedbackType)
#endif
case tabSelection
case timeline
}
#if !os(visionOS)
private let selectionGenerator = UISelectionFeedbackGenerator()
private let impactGenerator = UIImpactFeedbackGenerator(style: .heavy)
private let notificationGenerator = UINotificationFeedbackGenerator()
private let selectionGenerator = UISelectionFeedbackGenerator()
private let impactGenerator = UIImpactFeedbackGenerator(style: .heavy)
private let notificationGenerator = UINotificationFeedbackGenerator()
#endif
private let userPreferences = UserPreferences.shared
private init() {
#if !os(visionOS)
selectionGenerator.prepare()
impactGenerator.prepare()
selectionGenerator.prepare()
impactGenerator.prepare()
#endif
}
@MainActor
public func fireHaptic(_ type: HapticType) {
#if !os(visionOS)
guard supportsHaptics else { return }
guard supportsHaptics else { return }
switch type {
case .buttonPress:
if userPreferences.hapticButtonPressEnabled {
impactGenerator.impactOccurred()
switch type {
case .buttonPress:
if userPreferences.hapticButtonPressEnabled {
impactGenerator.impactOccurred()
}
case let .dataRefresh(intensity):
if userPreferences.hapticTimelineEnabled {
impactGenerator.impactOccurred(intensity: intensity)
}
case let .notification(type):
if userPreferences.hapticButtonPressEnabled {
notificationGenerator.notificationOccurred(type)
}
case .tabSelection:
if userPreferences.hapticTabSelectionEnabled {
selectionGenerator.selectionChanged()
}
case .timeline:
if userPreferences.hapticTimelineEnabled {
selectionGenerator.selectionChanged()
}
}
case let .dataRefresh(intensity):
if userPreferences.hapticTimelineEnabled {
impactGenerator.impactOccurred(intensity: intensity)
}
case let .notification(type):
if userPreferences.hapticButtonPressEnabled {
notificationGenerator.notificationOccurred(type)
}
case .tabSelection:
if userPreferences.hapticTabSelectionEnabled {
selectionGenerator.selectionChanged()
}
case .timeline:
if userPreferences.hapticTimelineEnabled {
selectionGenerator.selectionChanged()
}
}
#endif
}

View file

@ -0,0 +1,15 @@
import Network
import SwiftUI
@MainActor
public extension View {
func withPreviewsEnv() -> some View {
environment(RouterPath())
.environment(Client(server: ""))
.environment(CurrentAccount.shared)
.environment(UserPreferences.shared)
.environment(CurrentInstance.shared)
.environment(PushNotificationsService.shared)
.environment(QuickLook.shared)
}
}

View file

@ -38,7 +38,15 @@ public enum WindowDestinationMedia: Hashable, Codable {
case mediaViewer(attachments: [MediaAttachment], selectedAttachment: MediaAttachment)
}
public enum SheetDestination: Identifiable {
public enum SheetDestination: Identifiable, Hashable {
public static func == (lhs: SheetDestination, rhs: SheetDestination) -> Bool {
lhs.id == rhs.id
}
public func hash(into hasher: inout Hasher) {
hasher.combine(id)
}
case newStatusEditor(visibility: Models.Visibility)
case editStatusEditor(status: Status)
case replyToStatusEditor(status: Status)
@ -60,11 +68,13 @@ public enum SheetDestination: Identifiable {
case shareImage(image: UIImage, status: Status)
case editTagGroup(tagGroup: TagGroup, onSaved: ((TagGroup) -> Void)?)
case timelineContentFilter
case accountEditInfo
case accountFiltersList
public var id: String {
switch self {
case .editStatusEditor, .newStatusEditor, .replyToStatusEditor, .quoteStatusEditor,
.mentionStatusEditor, .quoteLinkStatusEditor:
.mentionStatusEditor, .quoteLinkStatusEditor:
"statusEditor"
case .listCreate:
"listCreate"
@ -90,6 +100,10 @@ public enum SheetDestination: Identifiable {
"settings"
case .timelineContentFilter:
"timelineContentFilter"
case .accountEditInfo:
"accountEditInfo"
case .accountFiltersList:
"accountFiltersList"
}
}
}
@ -147,8 +161,9 @@ public enum SheetDestination: Identifiable {
navigate(to: .hashTag(tag: tag, account: nil))
return .handled
} else if url.lastPathComponent.first == "@",
let host = url.host,
!host.hasPrefix("www") {
let host = url.host,
!host.hasPrefix("www")
{
let acct = "\(url.lastPathComponent)@\(host)"
Task {
await navigateToAccountFrom(acct: acct, url: url)

View file

@ -27,11 +27,11 @@ import OSLog
public var events: [any StreamEvent] = []
public var unreadNotificationsCount: Int = 0
public var latestEvent: (any StreamEvent)?
private let logger = Logger(subsystem: "com.icecubesapp", category: "stream")
public static let shared = StreamWatcher()
private init() {
decoder.keyDecodingStrategy = .convertFromSnakeCase
}
@ -65,7 +65,7 @@ import OSLog
connect()
}
watchedStreams = streams
streams.forEach { stream in
for stream in streams {
sendMessage(message: StreamMessage(type: "subscribe", stream: stream.rawValue))
}
}
@ -156,22 +156,22 @@ import OSLog
return nil
}
}
public func emmitDeleteEvent(for status: String) {
let event = StreamEventDelete(status: status)
self.events.append(event)
self.latestEvent = event
events.append(event)
latestEvent = event
}
public func emmitEditEvent(for status: Status) {
let event = StreamEventStatusUpdate(status: status)
self.events.append(event)
self.latestEvent = event
events.append(event)
latestEvent = event
}
public func emmitPostEvent(for status: Status) {
let event = StreamEventUpdate(status: status)
self.events.append(event)
self.latestEvent = event
events.append(event)
latestEvent = event
}
}

View file

@ -53,7 +53,7 @@ import SwiftUI
@AppStorage("collapse-long-posts") public var collapseLongPosts = true
@AppStorage("share-button-behavior") public var shareButtonBehavior: PreferredShareButtonBehavior = .linkOnly
@AppStorage("fast_refresh") public var fastRefreshEnabled: Bool = false
@AppStorage("max_reply_indentation") public var maxReplyIndentation: UInt = 7
@ -164,7 +164,7 @@ import SwiftUI
storage.appDefaultPostsSensitive = appDefaultPostsSensitive
}
}
public var appRequireAltText: Bool {
didSet {
storage.appRequireAltText = appRequireAltText
@ -183,7 +183,6 @@ import SwiftUI
}
}
public var alwaysUseDeepl: Bool {
didSet {
storage.alwaysUseDeepl = alwaysUseDeepl
@ -303,7 +302,7 @@ import SwiftUI
storage.shareButtonBehavior = shareButtonBehavior
}
}
public var fastRefreshEnabled: Bool {
didSet {
storage.fastRefreshEnabled = fastRefreshEnabled
@ -415,7 +414,7 @@ import SwiftUI
}
public var totalNotificationsCount: Int {
notificationsCount.compactMap{ $0.value }.reduce(0, +)
notificationsCount.compactMap { $0.value }.reduce(0, +)
}
public func reloadNotificationsCount(tokens: [OauthToken]) {
@ -509,7 +508,7 @@ extension UInt: RawRepresentable {
public var rawValue: Int {
Int(self)
}
public init?(rawValue: Int) {
if rawValue >= 0 {
self.init(rawValue)

View file

@ -1,7 +1,7 @@
@testable import Env
import XCTest
import SwiftUI
import Network
import SwiftUI
import XCTest
@MainActor
final class RouterTests: XCTestCase {
@ -11,14 +11,14 @@ final class RouterTests: XCTestCase {
_ = router.handle(url: url)
XCTAssertTrue(router.path.isEmpty)
}
func testRouterTagsURL() {
let router = RouterPath()
let url = URL(string: "https://mastodon.social/tags/test")!
_ = router.handle(url: url)
XCTAssertTrue(router.path.first == .hashTag(tag: "test", account: nil))
}
func testRouterLocalStatusURL() {
let router = RouterPath()
let client = Client(server: "mastodon.social",
@ -29,7 +29,7 @@ final class RouterTests: XCTestCase {
_ = router.handle(url: url)
XCTAssertTrue(router.path.first == .statusDetail(id: "1010384"))
}
func testRouterRemoteStatusURL() {
let router = RouterPath()
let client = Client(server: "mastodon.social",
@ -40,7 +40,7 @@ final class RouterTests: XCTestCase {
_ = router.handle(url: url)
XCTAssertTrue(router.path.first == .remoteStatusDetail(url: url))
}
func testRouteRandomURL() {
let router = RouterPath()
let url = URL(string: "https://theweb.com/test/test/one")!

View file

@ -32,9 +32,9 @@ public struct ExploreView: View {
} else if !viewModel.searchQuery.isEmpty {
if let results = viewModel.results[viewModel.searchQuery] {
if results.isEmpty, !viewModel.isSearching {
EmptyView(iconName: "magnifyingglass",
title: "explore.search.empty.title",
message: "explore.search.empty.message")
PlaceholderView(iconName: "magnifyingglass",
title: "explore.search.empty.title",
message: "explore.search.empty.message")
.listRowBackground(theme.secondaryBackgroundColor)
.listRowSeparator(.hidden)
} else {
@ -53,12 +53,12 @@ public struct ExploreView: View {
.id(UUID())
}
} else if viewModel.allSectionsEmpty {
EmptyView(iconName: "magnifyingglass",
title: "explore.search.title",
message: "explore.search.message-\(client.server)")
#if !os(visionOS)
PlaceholderView(iconName: "magnifyingglass",
title: "explore.search.title",
message: "explore.search.message-\(client.server)")
#if !os(visionOS)
.listRowBackground(theme.secondaryBackgroundColor)
#endif
#endif
.listRowSeparator(.hidden)
} else {
quickAccessView
@ -94,32 +94,32 @@ public struct ExploreView: View {
}
.listStyle(.plain)
#if !os(visionOS)
.scrollContentBackground(.hidden)
.background(theme.secondaryBackgroundColor)
.scrollContentBackground(.hidden)
.background(theme.secondaryBackgroundColor)
#endif
.navigationTitle("explore.navigation-title")
.navigationBarTitleDisplayMode(.inline)
.searchable(text: $viewModel.searchQuery,
isPresented: $viewModel.isSearchPresented,
placement: .navigationBarDrawer(displayMode: .always),
prompt: Text("explore.search.prompt"))
.searchScopes($viewModel.searchScope) {
ForEach(ExploreViewModel.SearchScope.allCases, id: \.self) { scope in
Text(scope.localizedString)
}
}
.task(id: viewModel.searchQuery) {
await viewModel.search()
}
.onChange(of: scrollToTopSignal) {
if viewModel.scrollToTopVisible {
viewModel.isSearchPresented.toggle()
} else {
withAnimation {
proxy.scrollTo(ScrollToView.Constants.scrollToTop, anchor: .top)
.navigationTitle("explore.navigation-title")
.navigationBarTitleDisplayMode(.inline)
.searchable(text: $viewModel.searchQuery,
isPresented: $viewModel.isSearchPresented,
placement: .navigationBarDrawer(displayMode: .always),
prompt: Text("explore.search.prompt"))
.searchScopes($viewModel.searchScope) {
ForEach(ExploreViewModel.SearchScope.allCases, id: \.self) { scope in
Text(scope.localizedString)
}
}
.task(id: viewModel.searchQuery) {
await viewModel.search()
}
.onChange(of: scrollToTopSignal) {
if viewModel.scrollToTopVisible {
viewModel.isSearchPresented.toggle()
} else {
withAnimation {
proxy.scrollTo(ScrollToView.Constants.scrollToTop, anchor: .top)
}
}
}
}
}
}
@ -148,9 +148,9 @@ public struct ExploreView: View {
.scrollIndicators(.never)
.listRowInsets(EdgeInsets())
#if !os(visionOS)
.listRowBackground(theme.secondaryBackgroundColor)
.listRowBackground(theme.secondaryBackgroundColor)
#endif
.listRowSeparator(.hidden)
.listRowSeparator(.hidden)
}
private var loadingView: some View {
@ -159,9 +159,9 @@ public struct ExploreView: View {
.padding(.vertical, 8)
.redacted(reason: .placeholder)
.allowsHitTesting(false)
#if !os(visionOS)
#if !os(visionOS)
.listRowBackground(theme.primaryBackgroundColor)
#endif
#endif
}
}
@ -172,13 +172,13 @@ public struct ExploreView: View {
ForEach(results.accounts) { account in
if let relationship = results.relationships.first(where: { $0.id == account.id }) {
AccountsListRow(viewModel: .init(account: account, relationShip: relationship))
#if !os(visionOS)
#if !os(visionOS)
.listRowBackground(theme.primaryBackgroundColor)
#else
#else
.listRowBackground(RoundedRectangle(cornerRadius: 8)
.foregroundStyle(.background).hoverEffect())
.foregroundStyle(.background).hoverEffect())
.listRowHoverEffectDisabled()
#endif
#endif
}
}
}
@ -187,13 +187,13 @@ public struct ExploreView: View {
Section("explore.section.tags") {
ForEach(results.hashtags) { tag in
TagRowView(tag: tag)
#if !os(visionOS)
#if !os(visionOS)
.listRowBackground(theme.primaryBackgroundColor)
#else
#else
.listRowBackground(RoundedRectangle(cornerRadius: 8)
.foregroundStyle(.background).hoverEffect())
.foregroundStyle(.background).hoverEffect())
.listRowHoverEffectDisabled()
#endif
#endif
.padding(.vertical, 4)
}
}
@ -202,13 +202,13 @@ public struct ExploreView: View {
Section("explore.section.posts") {
ForEach(results.statuses) { status in
StatusRowView(viewModel: .init(status: status, client: client, routerPath: routerPath))
#if !os(visionOS)
#if !os(visionOS)
.listRowBackground(theme.primaryBackgroundColor)
#else
#else
.listRowBackground(RoundedRectangle(cornerRadius: 8)
.foregroundStyle(.background).hoverEffect())
.foregroundStyle(.background).hoverEffect())
.listRowHoverEffectDisabled()
#endif
#endif
.padding(.vertical, 8)
}
}
@ -222,13 +222,13 @@ public struct ExploreView: View {
{ account in
if let relationship = viewModel.suggestedAccountsRelationShips.first(where: { $0.id == account.id }) {
AccountsListRow(viewModel: .init(account: account, relationShip: relationship))
#if !os(visionOS)
#if !os(visionOS)
.listRowBackground(theme.primaryBackgroundColor)
#else
#else
.listRowBackground(RoundedRectangle(cornerRadius: 8)
.foregroundStyle(.background).hoverEffect())
.foregroundStyle(.background).hoverEffect())
.listRowHoverEffectDisabled()
#endif
#endif
}
}
NavigationLink(value: RouterDestination.accountsList(accounts: viewModel.suggestedAccounts)) {
@ -239,7 +239,7 @@ public struct ExploreView: View {
.listRowBackground(theme.primaryBackgroundColor)
#else
.listRowBackground(RoundedRectangle(cornerRadius: 8)
.foregroundStyle(.background).hoverEffect())
.foregroundStyle(.background).hoverEffect())
.listRowHoverEffectDisabled()
#endif
}
@ -251,13 +251,13 @@ public struct ExploreView: View {
.prefix(upTo: viewModel.trendingTags.count > 5 ? 5 : viewModel.trendingTags.count))
{ tag in
TagRowView(tag: tag)
#if !os(visionOS)
#if !os(visionOS)
.listRowBackground(theme.primaryBackgroundColor)
#else
#else
.listRowBackground(RoundedRectangle(cornerRadius: 8)
.foregroundStyle(.background).hoverEffect())
.foregroundStyle(.background).hoverEffect())
.listRowHoverEffectDisabled()
#endif
#endif
.padding(.vertical, 4)
}
NavigationLink(value: RouterDestination.tagsList(tags: viewModel.trendingTags)) {
@ -268,7 +268,7 @@ public struct ExploreView: View {
.listRowBackground(theme.primaryBackgroundColor)
#else
.listRowBackground(RoundedRectangle(cornerRadius: 8)
.foregroundStyle(.background).hoverEffect())
.foregroundStyle(.background).hoverEffect())
.listRowHoverEffectDisabled()
#endif
}
@ -280,13 +280,13 @@ public struct ExploreView: View {
.prefix(upTo: viewModel.trendingStatuses.count > 3 ? 3 : viewModel.trendingStatuses.count))
{ status in
StatusRowView(viewModel: .init(status: status, client: client, routerPath: routerPath))
#if !os(visionOS)
#if !os(visionOS)
.listRowBackground(theme.primaryBackgroundColor)
#else
#else
.listRowBackground(RoundedRectangle(cornerRadius: 8)
.foregroundStyle(.background).hoverEffect())
.foregroundStyle(.background).hoverEffect())
.listRowHoverEffectDisabled()
#endif
#endif
.padding(.vertical, 8)
}
@ -298,7 +298,7 @@ public struct ExploreView: View {
.listRowBackground(theme.primaryBackgroundColor)
#else
.listRowBackground(RoundedRectangle(cornerRadius: 8)
.foregroundStyle(.background).hoverEffect())
.foregroundStyle(.background).hoverEffect())
.listRowHoverEffectDisabled()
#endif
}
@ -311,13 +311,13 @@ public struct ExploreView: View {
{ card in
StatusRowCardView(card: card)
.environment(\.isCompact, true)
#if !os(visionOS)
#if !os(visionOS)
.listRowBackground(theme.primaryBackgroundColor)
#else
#else
.listRowBackground(RoundedRectangle(cornerRadius: 8)
.foregroundStyle(.background).hoverEffect())
.foregroundStyle(.background).hoverEffect())
.listRowHoverEffectDisabled()
#endif
#endif
.padding(.vertical, 8)
}
@ -329,7 +329,7 @@ public struct ExploreView: View {
.listRowBackground(theme.primaryBackgroundColor)
#else
.listRowBackground(RoundedRectangle(cornerRadius: 8)
.foregroundStyle(.background).hoverEffect())
.foregroundStyle(.background).hoverEffect())
.listRowHoverEffectDisabled()
#endif
}

View file

@ -15,9 +15,9 @@ public struct TagsListView: View {
List {
ForEach(tags) { tag in
TagRowView(tag: tag)
#if !os(visionOS)
#if !os(visionOS)
.listRowBackground(theme.primaryBackgroundColor)
#endif
#endif
.padding(.vertical, 4)
}
}

View file

@ -1,8 +1,8 @@
import DesignSystem
import Models
import Network
import StatusKit
import SwiftUI
import Network
public struct TrendingLinksListView: View {
@Environment(Theme.self) private var theme
@ -19,9 +19,9 @@ public struct TrendingLinksListView: View {
ForEach(links) { card in
StatusRowCardView(card: card)
.environment(\.isCompact, true)
#if !os(visionOS)
#if !os(visionOS)
.listRowBackground(theme.primaryBackgroundColor)
#endif
#endif
.padding(.vertical, 8)
}
NextPageView {

View file

@ -1,5 +1,5 @@
import SwiftUI
import Models
import SwiftUI
enum DisplayType {
case image

View file

@ -1,9 +1,9 @@
import AVKit
import DesignSystem
import Env
import Models
import Observation
import SwiftUI
import Models
@MainActor
@Observable public class MediaUIAttachmentVideoViewModel {
@ -21,9 +21,9 @@ import Models
player = .init(url: url)
player?.audiovisualBackgroundPlaybackPolicy = .pauses
#if !os(visionOS)
player?.preventsDisplaySleepDuringVideoPlayback = false
player?.preventsDisplaySleepDuringVideoPlayback = false
#endif
if (autoPlay || forceAutoPlay) && !isCompact {
if autoPlay || forceAutoPlay, !isCompact {
player?.play()
isPlaying = true
} else {
@ -41,7 +41,7 @@ import Models
}
}
}
func mute(_ mute: Bool) {
player?.isMuted = mute
}
@ -50,7 +50,7 @@ import Models
isPlaying = false
player?.pause()
}
func stop() {
isPlaying = false
player?.pause()
@ -62,15 +62,15 @@ import Models
player?.seek(to: CMTime.zero)
player?.play()
}
func resume() {
isPlaying = true
player?.play()
}
func preventSleep(_ preventSleep: Bool) {
#if !os(visionOS)
player?.preventsDisplaySleepDuringVideoPlayback = preventSleep
player?.preventsDisplaySleepDuringVideoPlayback = preventSleep
#endif
}
@ -96,90 +96,91 @@ public struct MediaUIAttachmentVideoView: View {
public var body: some View {
videoView
.onAppear {
viewModel.preparePlayer(autoPlay: isFullScreen ? true : preferences.autoPlayVideo,
isCompact: isCompact)
viewModel.mute(preferences.muteVideo)
}
.onDisappear {
viewModel.stop()
}
.onTapGesture {
if !preferences.autoPlayVideo && !viewModel.isPlaying {
viewModel.play()
return
}
#if targetEnvironment(macCatalyst)
viewModel.pause()
let attachement = MediaAttachment.videoWith(url: viewModel.url)
openWindow(value: WindowDestinationMedia.mediaViewer(attachments: [attachement], selectedAttachment: attachement))
#else
isFullScreen = true
#endif
}
.fullScreenCover(isPresented: $isFullScreen) {
NavigationStack {
videoView
.toolbar {
ToolbarItem(placement: .topBarLeading) {
Button { isFullScreen.toggle() } label: {
Image(systemName: "xmark.circle")
}
}
QuickLookToolbarItem(itemUrl: viewModel.url)
}
}
.onAppear {
DispatchQueue.global().async {
try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)
try? AVAudioSession.sharedInstance().setCategory(.playback, options: .duckOthers)
try? AVAudioSession.sharedInstance().setActive(true)
}
viewModel.preventSleep(true)
viewModel.mute(false)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
if isCompact || !preferences.autoPlayVideo {
viewModel.play()
} else {
viewModel.resume()
}
}
viewModel.preparePlayer(autoPlay: isFullScreen ? true : preferences.autoPlayVideo,
isCompact: isCompact)
viewModel.mute(preferences.muteVideo)
}
.onDisappear {
if isCompact || !preferences.autoPlayVideo {
viewModel.pause()
}
viewModel.preventSleep(false)
viewModel.mute(preferences.muteVideo)
DispatchQueue.global().async {
try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)
try? AVAudioSession.sharedInstance().setCategory(.ambient, options: .mixWithOthers)
try? AVAudioSession.sharedInstance().setActive(true)
}
viewModel.stop()
}
}
.cornerRadius(4)
.onChange(of: scenePhase) { _, newValue in
switch newValue {
case .background, .inactive:
viewModel.pause()
case .active:
if (preferences.autoPlayVideo || viewModel.forceAutoPlay || isFullScreen) && !isCompact {
.onTapGesture {
if !preferences.autoPlayVideo && !viewModel.isPlaying {
viewModel.play()
return
}
#if targetEnvironment(macCatalyst)
viewModel.pause()
let attachement = MediaAttachment.videoWith(url: viewModel.url)
openWindow(value: WindowDestinationMedia.mediaViewer(attachments: [attachement], selectedAttachment: attachement))
#else
isFullScreen = true
#endif
}
.fullScreenCover(isPresented: $isFullScreen) {
NavigationStack {
videoView
.toolbar {
ToolbarItem(placement: .topBarLeading) {
Button { isFullScreen.toggle() } label: {
Image(systemName: "xmark.circle")
}
}
QuickLookToolbarItem(itemUrl: viewModel.url)
}
}
.onAppear {
DispatchQueue.global().async {
try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)
try? AVAudioSession.sharedInstance().setCategory(.playback, options: .duckOthers)
try? AVAudioSession.sharedInstance().setActive(true)
}
viewModel.preventSleep(true)
viewModel.mute(false)
DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
if isCompact || !preferences.autoPlayVideo {
viewModel.play()
} else {
viewModel.resume()
}
}
}
.onDisappear {
if isCompact || !preferences.autoPlayVideo {
viewModel.pause()
}
viewModel.preventSleep(false)
viewModel.mute(preferences.muteVideo)
DispatchQueue.global().async {
try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation)
try? AVAudioSession.sharedInstance().setCategory(.ambient, options: .mixWithOthers)
try? AVAudioSession.sharedInstance().setActive(true)
}
}
}
.cornerRadius(4)
.onChange(of: scenePhase) { _, newValue in
switch newValue {
case .background, .inactive:
viewModel.pause()
case .active:
if (preferences.autoPlayVideo || viewModel.forceAutoPlay || isFullScreen) && !isCompact {
viewModel.play()
}
default:
break
}
default:
break
}
}
}
private var videoView: some View {
VideoPlayer(player: viewModel.player, videoOverlay: {
if !preferences.autoPlayVideo,
!viewModel.forceAutoPlay,
if !preferences.autoPlayVideo,
!viewModel.forceAutoPlay,
!isFullScreen,
!viewModel.isPlaying,
!isCompact {
!viewModel.isPlaying,
!isCompact
{
Button(action: {
viewModel.play()
}, label: {

View file

@ -1,8 +1,8 @@
import AVFoundation
import Models
import Nuke
import QuickLook
import SwiftUI
import AVFoundation
public struct MediaUIView: View, @unchecked Sendable {
private let data: [DisplayData]

View file

@ -1,6 +1,6 @@
import SwiftUI
import NukeUI
import Nuke
import NukeUI
import SwiftUI
struct QuickLookToolbarItem: ToolbarContent, @unchecked Sendable {
let itemUrl: URL

View file

@ -61,6 +61,7 @@ public final class Account: Codable, Identifiable, Hashable, Sendable, Equatable
public let source: Source?
public let bot: Bool
public let discoverable: Bool?
public let moved: Account?
public var haveAvatar: Bool {
avatar.lastPathComponent != "missing.png"
@ -70,7 +71,7 @@ public final class Account: Codable, Identifiable, Hashable, Sendable, Equatable
header.lastPathComponent != "missing.png"
}
public init(id: String, username: String, displayName: String?, avatar: URL, header: URL, acct: String, note: HTMLString, createdAt: ServerDate, followersCount: Int, followingCount: Int, statusesCount: Int, lastStatusAt: String? = nil, fields: [Account.Field], locked: Bool, emojis: [Emoji], url: URL? = nil, source: Account.Source? = nil, bot: Bool, discoverable: Bool? = nil) {
public init(id: String, username: String, displayName: String?, avatar: URL, header: URL, acct: String, note: HTMLString, createdAt: ServerDate, followersCount: Int, followingCount: Int, statusesCount: Int, lastStatusAt: String? = nil, fields: [Account.Field], locked: Bool, emojis: [Emoji], url: URL? = nil, source: Account.Source? = nil, bot: Bool, discoverable: Bool? = nil, moved: Account? = nil) {
self.id = id
self.username = username
self.displayName = displayName
@ -90,14 +91,15 @@ public final class Account: Codable, Identifiable, Hashable, Sendable, Equatable
self.source = source
self.bot = bot
self.discoverable = discoverable
self.moved = moved
if let displayName, !displayName.isEmpty {
self.cachedDisplayName = .init(stringValue: displayName)
cachedDisplayName = .init(stringValue: displayName)
} else {
self.cachedDisplayName = .init(stringValue: "@\(username)")
cachedDisplayName = .init(stringValue: "@\(username)")
}
}
public enum CodingKeys: CodingKey {
case id
case username
@ -118,33 +120,36 @@ public final class Account: Codable, Identifiable, Hashable, Sendable, Equatable
case source
case bot
case discoverable
case moved
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decode(String.self, forKey: .id)
self.username = try container.decode(String.self, forKey: .username)
self.displayName = try container.decodeIfPresent(String.self, forKey: .displayName)
self.avatar = try container.decode(URL.self, forKey: .avatar)
self.header = try container.decode(URL.self, forKey: .header)
self.acct = try container.decode(String.self, forKey: .acct)
self.note = try container.decode(HTMLString.self, forKey: .note)
self.createdAt = try container.decode(ServerDate.self, forKey: .createdAt)
self.followersCount = try container.decodeIfPresent(Int.self, forKey: .followersCount)
self.followingCount = try container.decodeIfPresent(Int.self, forKey: .followingCount)
self.statusesCount = try container.decodeIfPresent(Int.self, forKey: .statusesCount)
self.lastStatusAt = try container.decodeIfPresent(String.self, forKey: .lastStatusAt)
self.fields = try container.decode([Account.Field].self, forKey: .fields)
self.locked = try container.decode(Bool.self, forKey: .locked)
self.emojis = try container.decode([Emoji].self, forKey: .emojis)
self.url = try container.decodeIfPresent(URL.self, forKey: .url)
self.source = try container.decodeIfPresent(Account.Source.self, forKey: .source)
self.bot = try container.decode(Bool.self, forKey: .bot)
self.discoverable = try container.decodeIfPresent(Bool.self, forKey: .discoverable)
id = try container.decode(String.self, forKey: .id)
username = try container.decode(String.self, forKey: .username)
displayName = try container.decodeIfPresent(String.self, forKey: .displayName)
avatar = try container.decode(URL.self, forKey: .avatar)
header = try container.decode(URL.self, forKey: .header)
acct = try container.decode(String.self, forKey: .acct)
note = try container.decode(HTMLString.self, forKey: .note)
createdAt = try container.decode(ServerDate.self, forKey: .createdAt)
followersCount = try container.decodeIfPresent(Int.self, forKey: .followersCount)
followingCount = try container.decodeIfPresent(Int.self, forKey: .followingCount)
statusesCount = try container.decodeIfPresent(Int.self, forKey: .statusesCount)
lastStatusAt = try container.decodeIfPresent(String.self, forKey: .lastStatusAt)
fields = try container.decode([Account.Field].self, forKey: .fields)
locked = try container.decode(Bool.self, forKey: .locked)
emojis = try container.decode([Emoji].self, forKey: .emojis)
url = try container.decodeIfPresent(URL.self, forKey: .url)
source = try container.decodeIfPresent(Account.Source.self, forKey: .source)
bot = try container.decode(Bool.self, forKey: .bot)
discoverable = try container.decodeIfPresent(Bool.self, forKey: .discoverable)
moved = try container.decodeIfPresent(Account.self, forKey: .moved)
if let displayName, !displayName.isEmpty {
self.cachedDisplayName = .init(stringValue: displayName)
cachedDisplayName = .init(stringValue: displayName)
} else {
self.cachedDisplayName = .init(stringValue: "@\(username)")
cachedDisplayName = .init(stringValue: "@\(username)")
}
}

View file

@ -15,14 +15,14 @@ public struct ServerDate: Codable, Hashable, Equatable, Sendable {
relativeTo: Date())
} else {
return Duration.seconds(-date.timeIntervalSinceNow).formatted(.units(width: .narrow,
maximumUnitCount: 1))
maximumUnitCount: 1))
}
}
public var shortDateFormatted: String {
DateFormatterCache.shared.createdAtShortDateFormatted.string(from: asDate)
}
private static let calendar = Calendar(identifier: .gregorian)
public init() {
@ -41,7 +41,7 @@ public struct ServerDate: Codable, Hashable, Equatable, Sendable {
let container = try decoder.container(keyedBy: CodingKeys.self)
asDate = try container.decode(Date.self, forKey: .asDate)
}
let aDay: TimeInterval = 60 * 60 * 24
isOlderThanADay = Date().timeIntervalSince(asDate) >= aDay
}

View file

@ -38,8 +38,8 @@ public struct ConsolidatedNotification: Identifiable {
}
public static func placeholders() -> [ConsolidatedNotification] {
[.placeholder(), .placeholder(), .placeholder(),
.placeholder(), .placeholder(), .placeholder(),
[.placeholder(), .placeholder(), .placeholder(),
.placeholder(), .placeholder(), .placeholder(),
.placeholder(), .placeholder(), .placeholder(),
.placeholder(), .placeholder(), .placeholder()]
}

View file

@ -13,7 +13,7 @@ public struct List: Codable, Identifiable, Equatable, Hashable {
case followed, list, none
}
public init(id: String, title: String, repliesPolicy: RepliesPolicy? = nil, exclusive: Bool? = nil) {
self.id = id
self.title = title

View file

@ -6,7 +6,7 @@ public struct Marker: Codable, Sendable {
public let version: Int
public let updatedAt: ServerDate
}
public let notifications: Content?
public let home: Content?
}

View file

@ -53,7 +53,7 @@ public struct MediaAttachment: Codable, Identifiable, Hashable, Equatable {
description: nil,
meta: nil)
}
public static func videoWith(url: URL) -> MediaAttachment {
.init(id: UUID().uuidString,
type: "video",

View file

@ -5,7 +5,7 @@ public struct OauthToken: Codable, Hashable, Sendable {
public let tokenType: String
public let scope: String
public let createdAt: Double
public init(accessToken: String, tokenType: String, scope: String, createdAt: Double) {
self.accessToken = accessToken
self.tokenType = tokenType

View file

@ -1,15 +1,15 @@
import Foundation
public enum PostError: Error {
// Throw when any attached media is missing media description (alt text)
case missingAltText
// Throw when any attached media is missing media description (alt text)
case missingAltText
}
extension PostError: CustomStringConvertible {
public var description: String {
switch self {
case .missingAltText:
return NSLocalizedString("status.error.no-alt-text", comment: "media does not have media description")
}
public var description: String {
switch self {
case .missingAltText:
return NSLocalizedString("status.error.no-alt-text", comment: "media does not have media description")
}
}
}

View file

@ -73,7 +73,7 @@ public final class Status: AnyStatus, Codable, Identifiable, Equatable, Hashable
public let filtered: [Filtered]?
public let sensitive: Bool
public let language: String?
public var isHidden: Bool {
filtered?.first?.filter.filterAction == .hide
}
@ -214,7 +214,7 @@ public final class ReblogStatus: AnyStatus, Codable, Identifiable, Equatable, Ha
public let filtered: [Filtered]?
public let sensitive: Bool
public let language: String?
public var isHidden: Bool {
filtered?.first?.filter.filterAction == .hide
}

View file

@ -22,7 +22,7 @@ public struct StreamEventUpdate: StreamEvent {
public struct StreamEventStatusUpdate: StreamEvent {
public let date = Date()
public var id: String { status.id + (status.editedAt?.asDate.description ?? "")}
public var id: String { status.id + (status.editedAt?.asDate.description ?? "") }
public let status: Status
public init(status: Status) {
self.status = status

View file

@ -7,7 +7,7 @@ public struct Tag: Codable, Identifiable, Equatable, Hashable {
public static func == (lhs: Tag, rhs: Tag) -> Bool {
lhs.name == rhs.name &&
lhs.following == rhs.following
lhs.following == rhs.following
}
public var id: String {

View file

@ -3,8 +3,8 @@ import Foundation
import Models
import Observation
import os
import SwiftUI
import OSLog
import SwiftUI
@Observable public final class Client: Equatable, Identifiable, Hashable, @unchecked Sendable {
public static func == (lhs: Client, rhs: Client) -> Bool {
@ -44,7 +44,7 @@ import OSLog
public let version: Version
private let urlSession: URLSession
private let decoder = JSONDecoder()
private let logger = Logger(subsystem: "com.icecubesapp", category: "networking")
// Putting all mutable state inside an `OSAllocatedUnfairLock` makes `Client`
@ -263,7 +263,7 @@ import OSLog
throw error
}
}
public func mediaUpload(endpoint: Endpoint,
version: Version,
method: String,
@ -280,13 +280,14 @@ import OSLog
let (_, httpResponse) = try await urlSession.data(for: request)
return httpResponse as? HTTPURLResponse
}
private func makeFormDataRequest(endpoint: Endpoint,
version: Version,
method: String,
mimeType: String,
filename: String,
data: Data) throws -> URLRequest {
data: Data) throws -> URLRequest
{
let url = try makeURL(endpoint: endpoint, forceVersion: version)
var request = makeURLRequest(url: url, endpoint: endpoint, httpMethod: method)
let boundary = UUID().uuidString

View file

@ -98,11 +98,11 @@ public enum Accounts: Endpoint {
if let sinceId {
params.append(.init(name: "max_id", value: sinceId))
}
params.append(.init(name: "only_media", value: onlyMedia ? "true" : "false"))
params.append(.init(name: "exclude_replies", value: excludeReplies ? "true" : "false"))
params.append(.init(name: "exclude_reblogs", value: excludeReblogs ? "true" : "false"))
if let pinned {
params.append(.init(name: "pinned", value: pinned ? "true" : "false"))
}

Some files were not shown because too many files have changed in this diff Show more