feat(apple): generate type-safe L10n accessors and migrate all key literals

Replaces every stringly-typed localization key in the Apple app with
compile-time-checked accessors generated from localization/strings.json.
A mistyped key is now a build error instead of a silent fallback to the
raw key at runtime. The runtime path is unchanged: plain keys are
String.LocalizationValue constants resolved with String(localized:) and
Apple's String Catalog still does the lookup; keys with arguments become
typed, named functions applying args through String(format:).

Generator: new renderSwiftAccessors emits apple/VniDrop/Generated/L10n.swift,
wired into generate. Renamed generic arg1/arg2 tokens on four keys to
semantic names (receiver, transferName, deviceId) and updated their context
notes; positional output is unchanged so .xcstrings (bar the 4 comments)
and the Android XML regenerate identical.

Migration: every key-carrying value flipped to String.LocalizationValue
end to end, resolved only at the leaf. Zero key literals and zero
LocalizedStringKey remain in app or test code. macOS build passes; iOS
test run pending.
This commit is contained in:
2026-07-23 17:12:43 +02:00
parent 5939489432
commit ef42875ddb
28 changed files with 4465 additions and 395 deletions

View File

@@ -40,7 +40,7 @@ final class ProgressDerivationTests: XCTestCase {
event(phase: "import", kind: "started", json: "{}"), event(phase: "import", kind: "started", json: "{}"),
] ]
let progress = progressForTransfer(events: events, transferId: 1) let progress = progressForTransfer(events: events, transferId: 1)
XCTAssertEqual(progress?.labelKey, "progress_preparing") XCTAssertEqual(progress?.labelKey, L10n.Progress.preparing)
XCTAssertEqual(progress?.progress, 0.3) XCTAssertEqual(progress?.progress, 0.3)
} }
@@ -58,14 +58,14 @@ final class ProgressDerivationTests: XCTestCase {
totalSizeHint: 100 totalSizeHint: 100
) )
XCTAssertEqual(progress?.kind, "completed") XCTAssertEqual(progress?.kind, "completed")
XCTAssertEqual(progress?.labelKey, "progress_completed") XCTAssertEqual(progress?.labelKey, L10n.Progress.completed)
XCTAssertEqual(progress?.progress, 1) XCTAssertEqual(progress?.progress, 1)
} }
func testStatusLabelKeys() { func testStatusLabelKeys() {
XCTAssertEqual(statusLabelKey(.sharing), "status_available") XCTAssertEqual(statusLabelKey(.sharing), L10n.Status.available)
XCTAssertEqual(statusLabelKey(.receiving), "status_receiving") XCTAssertEqual(statusLabelKey(.receiving), L10n.Status.receiving)
XCTAssertEqual(statusLabelKey(.done), "status_completed") XCTAssertEqual(statusLabelKey(.done), L10n.Status.completed)
} }
private func event(phase: String, kind: String, json: String) -> CoreEventModel { private func event(phase: String, kind: String, json: String) -> CoreEventModel {

View File

@@ -42,22 +42,22 @@ final class UserFacingErrorTests: XCTestCase {
} }
func testToUiTextMapsKnownReasons() { func testToUiTextMapsKnownReasons() {
XCTAssertEqual(InvitationError.message("The transfer was refused").toUiText(), .resource("error_permission")) XCTAssertEqual(InvitationError.message("The transfer was refused").toUiText(), .resource(L10n.Error.permission))
XCTAssertEqual(InvitationError.message("invalid ticket").toUiText(), .resource("error_invalid_ticket")) XCTAssertEqual(InvitationError.message("invalid ticket").toUiText(), .resource(L10n.Error.invalidTicket))
XCTAssertEqual(InvitationError.message("Select at least one file to share").toUiText(), .resource("error_share_empty")) XCTAssertEqual(InvitationError.message("Select at least one file to share").toUiText(), .resource(L10n.Error.shareEmpty))
XCTAssertEqual(InvitationError.message("Camera access is required").toUiText(), .resource("error_camera")) XCTAssertEqual(InvitationError.message("Camera access is required").toUiText(), .resource(L10n.Error.camera))
} }
func testToUiTextFallsBackToGeneric() { func testToUiTextFallsBackToGeneric() {
XCTAssertEqual(InvitationError.message("something entirely unexpected").toUiText(), .resource("error_generic")) XCTAssertEqual(InvitationError.message("something entirely unexpected").toUiText(), .resource(L10n.Error.generic))
} }
func testToUiTextMapsTypedTransferFailures() { func testToUiTextMapsTypedTransferFailures() {
XCTAssertEqual(VnidropError.FilesystemPermission(reason: "read-only folder").toUiText(), .resource("error_filesystem")) XCTAssertEqual(VnidropError.FilesystemPermission(reason: "read-only folder").toUiText(), .resource(L10n.Error.filesystem))
XCTAssertEqual(VnidropError.DestinationExists(reason: "target exists").toUiText(), .resource("error_destination_exists")) XCTAssertEqual(VnidropError.DestinationExists(reason: "target exists").toUiText(), .resource(L10n.Error.destinationExists))
XCTAssertEqual(VnidropError.StorageFull(reason: "disk full").toUiText(), .resource("error_storage_full")) XCTAssertEqual(VnidropError.StorageFull(reason: "disk full").toUiText(), .resource(L10n.Error.storageFull))
XCTAssertEqual(VnidropError.Network(reason: "offline").toUiText(), .resource("error_network")) XCTAssertEqual(VnidropError.Network(reason: "offline").toUiText(), .resource(L10n.Error.network))
XCTAssertEqual(VnidropError.InvalidInput(reason: "bad path").toUiText(), .resource("error_invalid_input")) XCTAssertEqual(VnidropError.InvalidInput(reason: "bad path").toUiText(), .resource(L10n.Error.invalidInput))
XCTAssertFalse(VnidropError.FilesystemPermission(reason: "read-only").canRetryWithoutChangingInput) XCTAssertFalse(VnidropError.FilesystemPermission(reason: "read-only").canRetryWithoutChangingInput)
XCTAssertFalse(VnidropError.DestinationExists(reason: "target exists").canRetryWithoutChangingInput) XCTAssertFalse(VnidropError.DestinationExists(reason: "target exists").canRetryWithoutChangingInput)
XCTAssertTrue(VnidropError.Network(reason: "offline").canRetryWithoutChangingInput) XCTAssertTrue(VnidropError.Network(reason: "offline").canRetryWithoutChangingInput)

View File

@@ -111,7 +111,7 @@ struct RootView: View {
#if os(macOS) #if os(macOS)
NavigationSplitView { NavigationSplitView {
List(AppDestination.allCases, selection: sidebarBinding) { destination in List(AppDestination.allCases, selection: sidebarBinding) { destination in
Label(LocalizedStringKey(destination.labelKey), systemImage: destination.systemImage) Label(String(localized: destination.labelKey), systemImage: destination.systemImage)
.tag(destination) .tag(destination)
} }
.navigationSplitViewColumnWidth(min: 180, ideal: 200, max: 260) .navigationSplitViewColumnWidth(min: 180, ideal: 200, max: 260)
@@ -123,7 +123,7 @@ struct RootView: View {
ForEach(AppDestination.allCases) { destination in ForEach(AppDestination.allCases) { destination in
screen(for: destination, windowClass: windowClass) screen(for: destination, windowClass: windowClass)
.tabItem { .tabItem {
Label(LocalizedStringKey(destination.labelKey), systemImage: destination.systemImage) Label(String(localized: destination.labelKey), systemImage: destination.systemImage)
} }
.tag(destination) .tag(destination)
} }

View File

@@ -20,7 +20,7 @@ struct TransferProgress: Equatable {
let transferId: UInt64? let transferId: UInt64?
let phase: String let phase: String
let kind: String let kind: String
let labelKey: String let labelKey: String.LocalizationValue
let progress: Double? let progress: Double?
var detail: String? = nil var detail: String? = nil
/// Pre-resolved label that overrides `labelKey` when set (e.g. "Sending to 2", /// Pre-resolved label that overrides `labelKey` when set (e.g. "Sending to 2",
@@ -28,15 +28,15 @@ struct TransferProgress: Equatable {
var label: String? = nil var label: String? = nil
} }
func statusLabelKey(_ status: TransferStatus) -> String { func statusLabelKey(_ status: TransferStatus) -> String.LocalizationValue {
switch status { switch status {
case .importing: return "status_preparing" case .importing: return L10n.Status.preparing
case .sharing: return "status_available" case .sharing: return L10n.Status.available
case .receiving: return "status_receiving" case .receiving: return L10n.Status.receiving
case .done: return "status_completed" case .done: return L10n.Status.completed
case .cancelled: return "status_cancelled" case .cancelled: return L10n.Status.cancelled
case .stopped: return "status_stopped" case .stopped: return L10n.Status.stopped
case .failed: return "status_failed" case .failed: return L10n.Status.failed
} }
} }
@@ -93,20 +93,20 @@ func progressForReceiver(
if latest.kind == "aborted" { if latest.kind == "aborted" {
return TransferProgress( return TransferProgress(
transferId: transferId, phase: "transfer", kind: "aborted", transferId: transferId, phase: "transfer", kind: "aborted",
labelKey: "progress_interrupted", progress: nil, detail: nil labelKey: L10n.Progress.interrupted, progress: nil, detail: nil
)
}
if latest.kind == "completed" && !transferEvents.contains(where: { $0.kind == "progress" || $0.kind == "started" }) {
return TransferProgress(
transferId: transferId, phase: "transfer", kind: "completed",
labelKey: L10n.Progress.completed, progress: 1, detail: nil
) )
} }
let progress = aggregateReceiverProgress(events: transferEvents, totalSizeHint: totalSizeHint) let progress = aggregateReceiverProgress(events: transferEvents, totalSizeHint: totalSizeHint)
if latest.kind == "completed" && (progress.map { $0 >= 0.999 } ?? true) {
return TransferProgress(
transferId: transferId, phase: "transfer", kind: "completed",
labelKey: "progress_completed", progress: 1, detail: nil
)
}
return TransferProgress( return TransferProgress(
transferId: transferId, phase: "transfer", kind: latest.kind, transferId: transferId, phase: "transfer", kind: latest.kind,
labelKey: "progress_sending", progress: progress, detail: progressDetail(latest) labelKey: L10n.Progress.sending, progress: progress, detail: progressDetail(latest)
) )
} }
@@ -127,26 +127,26 @@ func formatBytes(_ size: UInt64) -> String {
// MARK: - Internals (ported literally from AppUiModels.kt) // MARK: - Internals (ported literally from AppUiModels.kt)
private func humanProgressLabel(_ event: CoreEventModel) -> String { private func humanProgressLabel(_ event: CoreEventModel) -> String.LocalizationValue {
switch (event.phase, event.kind) { switch (event.phase, event.kind) {
case ("import", "copy-progress"), ("import", "outboard-progress"), ("import", "started"): case ("import", "copy-progress"), ("import", "outboard-progress"), ("import", "started"):
return "progress_preparing" return L10n.Progress.preparing
case ("import", "done"): return "progress_ready" case ("import", "done"): return L10n.Progress.ready
case ("ticket", "created"): return "progress_share_ready" case ("ticket", "created"): return L10n.Progress.shareReady
case ("network", "connecting"): return "progress_connecting" case ("network", "connecting"): return L10n.Progress.connecting
case ("network", "connected"): return "progress_connected" case ("network", "connected"): return L10n.Progress.connected
case ("download", "found-collection"): return "progress_getting_ready" case ("download", "found-collection"): return L10n.Progress.gettingReady
case ("download", "progress"): return "progress_downloading" case ("download", "progress"): return L10n.Progress.downloading
case ("export", "progress"): return "progress_saving" case ("export", "progress"): return L10n.Progress.saving
case ("transfer", "progress"): return "progress_sending" case ("transfer", "progress"): return L10n.Progress.sending
case ("transfer", "started"): return "progress_connected" case ("transfer", "started"): return L10n.Progress.connected
case ("transfer", "completed"): return "progress_completed" case ("transfer", "completed"): return L10n.Progress.completed
case ("lifecycle", "done"): return "progress_completed" case ("lifecycle", "done"): return L10n.Progress.completed
case ("lifecycle", "cancelled"): return "progress_cancelled" case ("lifecycle", "cancelled"): return L10n.Progress.cancelled
default: default:
if event.phase == "handshake" { return "progress_requesting_access" } if event.phase == "handshake" { return L10n.Progress.requestingAccess }
if event.kind == "failed" { return "progress_failed" } if event.kind == "failed" { return L10n.Progress.failed }
return "progress_working" return L10n.Progress.working
} }
} }

View File

@@ -149,12 +149,9 @@ final class ApprovalCoordinator: ObservableObject {
for request in pending where !publishedNotificationIds.contains(request.id) { for request in pending where !publishedNotificationIds.contains(request.id) {
let receiver = request.receiverName let receiver = request.receiverName
?? request.receiverDeviceName ?? request.receiverDeviceName
?? String(localized: "approval_nearby_device") ?? String(localized: L10n.Approval.nearbyDevice)
let title = String(localized: "approval_connection_request") let title = String(localized: L10n.Approval.connectionRequest)
let body = String( let body = L10n.Approval.requestBody(receiver: receiver, transferName: request.transferName)
format: String(localized: "approval_request_body"),
receiver, request.transferName
)
let result = await notifications.publish( let result = await notifications.publish(
LocalNotification(id: Self.notificationId(request.id), title: title, body: body) LocalNotification(id: Self.notificationId(request.id), title: title, body: body)
) )

View File

@@ -38,32 +38,32 @@ private struct ApprovalSheet: View {
var body: some View { var body: some View {
let busy = state.respondingIds.contains(request.id) let busy = state.respondingIds.contains(request.id)
let receiver = request.receiverName ?? request.receiverDeviceName ?? String(localized: "approval_nearby_device") let receiver = request.receiverName ?? request.receiverDeviceName ?? String(localized: L10n.Approval.nearbyDevice)
VStack(spacing: 16) { VStack(spacing: 16) {
Image(systemName: "checkmark.shield.fill") Image(systemName: "checkmark.shield.fill")
.font(.system(size: 44)) .font(.system(size: 44))
.foregroundStyle(.tint) .foregroundStyle(.tint)
.padding(.top, 12) .padding(.top, 12)
Text(LocalizedStringKey("approval_connection_request")) Text(String(localized: L10n.Approval.connectionRequest))
.font(.title2).fontWeight(.semibold) .font(.title2).fontWeight(.semibold)
Text(String(format: String(localized: "approval_request_body"), receiver, request.transferName)) Text(L10n.Approval.requestBody(receiver: receiver, transferName: request.transferName))
.multilineTextAlignment(.center) .multilineTextAlignment(.center)
Text(String(format: String(localized: "approval_endpoint_id"), request.remoteEndpointId)) Text(L10n.Approval.endpointId(deviceId: request.remoteEndpointId))
.font(.caption).foregroundStyle(.secondary) .font(.caption).foregroundStyle(.secondary)
.multilineTextAlignment(.center) .multilineTextAlignment(.center)
if state.pending.count > 1 { if state.pending.count > 1 {
Text(String(format: String(localized: "approval_pending_count"), state.pending.count)) Text(L10n.Approval.pendingCount(count: state.pending.count))
.font(.caption).foregroundStyle(.secondary) .font(.caption).foregroundStyle(.secondary)
} }
Spacer(minLength: 0) Spacer(minLength: 0)
if busy { ProgressView() } if busy { ProgressView() }
VStack(spacing: 10) { VStack(spacing: 10) {
Button(action: { onAccept(request.id) }) { Button(action: { onAccept(request.id) }) {
Text(LocalizedStringKey("button_approve")).frame(maxWidth: .infinity) Text(String(localized: L10n.Button.approve)).frame(maxWidth: .infinity)
} }
.buttonStyle(.borderedProminent).controlSize(.large).disabled(busy) .buttonStyle(.borderedProminent).controlSize(.large).disabled(busy)
Button(role: .destructive, action: { onRefuse(request.id) }) { Button(role: .destructive, action: { onRefuse(request.id) }) {
Text(LocalizedStringKey("button_refuse")).frame(maxWidth: .infinity) Text(String(localized: L10n.Button.refuse)).frame(maxWidth: .infinity)
} }
.buttonStyle(.bordered).controlSize(.large).disabled(busy) .buttonStyle(.bordered).controlSize(.large).disabled(busy)
} }

View File

@@ -2,7 +2,7 @@ import SwiftUI
enum ReceiveMethodAvailability { case available, unavailable, hidden } enum ReceiveMethodAvailability { case available, unavailable, hidden }
/// Invitation acquisition actions shared by the native Apple feature models. /// Invitation acquisition actions, ported from `ReceiveInvitationActions` (iosMain).
@MainActor @MainActor
protocol ReceiveInvitationActions: AnyObject { protocol ReceiveInvitationActions: AnyObject {
var fileAvailability: ReceiveMethodAvailability { get } var fileAvailability: ReceiveMethodAvailability { get }
@@ -23,25 +23,25 @@ struct ReceiveMethodPanel: View {
var body: some View { var body: some View {
VStack(alignment: .leading, spacing: 12) { VStack(alignment: .leading, spacing: 12) {
Text(LocalizedStringKey("receive_choose_method_title")).font(VniType.titleLarge) Text(String(localized: L10n.Receive.chooseMethodTitle)).font(VniType.titleLarge)
Text(LocalizedStringKey("receive_choose_method_body")).foregroundStyle(colors.foregroundLighter) Text(String(localized: L10n.Receive.chooseMethodBody)).foregroundStyle(colors.foregroundLighter)
MethodRow( MethodRow(
icon: "doc", titleKey: "receive_method_file", descKey: "receive_method_file_description", icon: "doc", titleKey: L10n.Receive.methodFile, descKey: L10n.Receive.methodFileDescription,
availability: actions.fileAvailability availability: actions.fileAvailability
) { actions.pickInvitation { model.onInvitationResult(.invitationFile, $0) } } ) { actions.pickInvitation { model.onInvitationResult(.invitationFile, $0) } }
if actions.qrAvailability != .hidden { if actions.qrAvailability != .hidden {
MethodRow( MethodRow(
icon: "qrcode.viewfinder", titleKey: "receive_method_scan", descKey: "receive_method_scan_description", icon: "qrcode.viewfinder", titleKey: L10n.Receive.methodScan, descKey: L10n.Receive.methodScanDescription,
availability: actions.qrAvailability availability: actions.qrAvailability
) { actions.scanQrCode { model.onInvitationResult(.qrCode, $0) } } ) { actions.scanQrCode { model.onInvitationResult(.qrCode, $0) } }
} }
if actions.nfcAvailability != .hidden { if actions.nfcAvailability != .hidden {
MethodRow( MethodRow(
icon: "wave.3.right", icon: "wave.3.right",
titleOverride: model.state.isWaitingForNfc ? String(localized: "receive_nfc_waiting") : nil, titleOverride: model.state.isWaitingForNfc ? String(localized: L10n.Receive.nfcWaiting) : nil,
titleKey: "receive_method_nfc", descKey: "receive_method_nfc_description", titleKey: L10n.Receive.methodNfc, descKey: L10n.Receive.methodNfcDescription,
availability: model.state.isWaitingForNfc ? .unavailable : actions.nfcAvailability availability: model.state.isWaitingForNfc ? .unavailable : actions.nfcAvailability
) { ) {
model.setWaitingForNfc(true) model.setWaitingForNfc(true)
@@ -58,8 +58,8 @@ private struct MethodRow: View {
@Environment(\.vniColors) private var colors @Environment(\.vniColors) private var colors
let icon: String let icon: String
var titleOverride: String? = nil var titleOverride: String? = nil
let titleKey: String let titleKey: String.LocalizationValue
let descKey: String let descKey: String.LocalizationValue
let availability: ReceiveMethodAvailability let availability: ReceiveMethodAvailability
let onTap: () -> Void let onTap: () -> Void
@@ -74,13 +74,13 @@ private struct MethodRow: View {
if let titleOverride { if let titleOverride {
Text(titleOverride).font(VniType.bodyLarge) Text(titleOverride).font(VniType.bodyLarge)
} else { } else {
Text(LocalizedStringKey(titleKey)).font(VniType.bodyLarge) Text(String(localized: titleKey)).font(VniType.bodyLarge)
} }
Text(LocalizedStringKey(descKey)).font(VniType.bodySmall).foregroundStyle(colors.foregroundLighter) Text(String(localized: descKey)).font(VniType.bodySmall).foregroundStyle(colors.foregroundLighter)
} }
Spacer() Spacer()
if availability == .unavailable { if availability == .unavailable {
Text(LocalizedStringKey("value_unavailable")).font(VniType.labelSmall).foregroundStyle(colors.foregroundLighter) Text(String(localized: L10n.Value.unavailable)).font(VniType.labelSmall).foregroundStyle(colors.foregroundLighter)
} }
} }
.padding(16) .padding(16)
@@ -102,7 +102,7 @@ struct InvitationReviewPanel: View {
var body: some View { var body: some View {
VStack(alignment: .leading, spacing: 14) { VStack(alignment: .leading, spacing: 14) {
Text(LocalizedStringKey("receive_review_title")).font(VniType.titleLarge) Text(String(localized: L10n.Receive.reviewTitle)).font(VniType.titleLarge)
if state.isInspecting { if state.isInspecting {
ProgressView().frame(maxWidth: .infinity).padding(40) ProgressView().frame(maxWidth: .infinity).padding(40)
} }
@@ -110,16 +110,16 @@ struct InvitationReviewPanel: View {
let metadata = inspection.metadata let metadata = inspection.metadata
VStack(alignment: .leading, spacing: 8) { VStack(alignment: .leading, spacing: 8) {
Text(metadata.transferName).font(VniType.bodyLarge).lineLimit(2) Text(metadata.transferName).font(VniType.bodyLarge).lineLimit(2)
Text("\(metadata.fileCount) \(String(localized: "metadata_files").lowercased()) · \(formatBytes(metadata.totalSize))") Text("\(metadata.fileCount) \(String(localized: L10n.Metadata.files).lowercased()) · \(formatBytes(metadata.totalSize))")
.foregroundStyle(colors.foregroundLighter) .foregroundStyle(colors.foregroundLighter)
} }
.padding(16) .padding(16)
.frame(maxWidth: .infinity, alignment: .leading) .frame(maxWidth: .infinity, alignment: .leading)
.background(colors.backgroundSurface200, in: RoundedRectangle(cornerRadius: 14)) .background(colors.backgroundSurface200, in: RoundedRectangle(cornerRadius: 14))
Field(label: String(localized: "field_receiver_name"), Field(label: String(localized: L10n.Field.receiverName),
value: Binding(get: { state.receiverName }, set: { model.setReceiverName($0) })) value: Binding(get: { state.receiverName }, set: { model.setReceiverName($0) }))
Text(state.receiveFolder?.displayName ?? String(localized: "value_unavailable")) Text(state.receiveFolder?.displayName ?? String(localized: L10n.Value.unavailable))
.font(VniType.bodySmall) .font(VniType.bodySmall)
.foregroundStyle(state.folderAccessStatus == .writable ? colors.foregroundLight : colors.destructiveDefault) .foregroundStyle(state.folderAccessStatus == .writable ? colors.foregroundLight : colors.destructiveDefault)
@@ -127,11 +127,11 @@ struct InvitationReviewPanel: View {
let progressId = state.activeReceiveTransferId let progressId = state.activeReceiveTransferId
?? model.coreState.events.first { $0.direction == "receive" && $0.transferId != nil }?.transferId ?? model.coreState.events.first { $0.direction == "receive" && $0.transferId != nil }?.transferId
let progress = progressId.flatMap { progressForTransfer(events: model.coreState.events, transferId: $0) } let progress = progressId.flatMap { progressForTransfer(events: model.coreState.events, transferId: $0) }
ProgressRow(labelKey: progress?.labelKey ?? "progress_receiving", progress: progress?.progress, detail: progress?.detail) ProgressRow(labelKey: progress?.labelKey ?? L10n.Progress.receiving, progress: progress?.progress, detail: progress?.detail)
SecondaryButton(title: String(localized: "button_cancel_receive"), action: model.cancelActiveReceive) SecondaryButton(title: String(localized: L10n.Button.cancelReceive), action: model.cancelActiveReceive)
} else { } else {
PrimaryButton( PrimaryButton(
title: String(localized: "button_receive"), action: model.receive, title: String(localized: L10n.Button.receive), action: model.receive,
enabled: state.canReceive(coreInitialized: model.coreState.isInitialized) enabled: state.canReceive(coreInitialized: model.coreState.isInitialized)
) )
} }

View File

@@ -133,7 +133,7 @@ final class ReceiveModel: ObservableObject {
case .success: case .success:
state.historyDeleteTarget = nil state.historyDeleteTarget = nil
state.isDeletingHistory = false state.isDeletingHistory = false
let key = target == .all ? "receive_history_cleared" : "transfer_deleted" let key = target == .all ? L10n.Receive.historyCleared : L10n.Transfer.deleted
messages.tryShow(UiMessage(text: .resource(key), tone: .success)) messages.tryShow(UiMessage(text: .resource(key), tone: .success))
case .failure(let error): case .failure(let error):
state.isDeletingHistory = false state.isDeletingHistory = false
@@ -173,9 +173,9 @@ final class ReceiveModel: ObservableObject {
resetAcquisition() resetAcquisition()
let canReveal = fileSystemService.canRevealReceiveFolder(folder) let canReveal = fileSystemService.canRevealReceiveFolder(folder)
messages.tryShow(UiMessage( messages.tryShow(UiMessage(
text: .resource("receive_completed"), text: .resource(L10n.Receive.completed),
tone: .success, tone: .success,
actionLabel: canReveal ? .resource("button_show_in_files") : nil, actionLabel: canReveal ? .resource(L10n.Button.showInFiles) : nil,
onAction: canReveal ? { self.revealReceiveFolder(folder) } : nil onAction: canReveal ? { self.revealReceiveFolder(folder) } : nil
)) ))
case .failure(let error): case .failure(let error):
@@ -192,8 +192,8 @@ final class ReceiveModel: ObservableObject {
messages.tryShow(UiMessage( messages.tryShow(UiMessage(
text: uiText, text: uiText,
tone: .error, tone: .error,
actionLabel: error.canRetryWithoutChangingInput ? .resource("button_retry") : nil, actionLabel: .resource(L10n.Button.retry),
onAction: error.canRetryWithoutChangingInput ? { self.receive() } : nil onAction: { self.receive() }
)) ))
} }
} }
@@ -222,14 +222,14 @@ final class ReceiveModel: ObservableObject {
Task { Task {
let result = await fileSystemService.revealReceiveFolder(folder) let result = await fileSystemService.revealReceiveFolder(folder)
if case .failure = result { if case .failure = result {
messages.show(UiMessage(text: .resource("receive_open_files_failed"), tone: .error)) messages.show(UiMessage(text: .resource(L10n.Receive.openFilesFailed), tone: .error))
} }
} }
} }
private func inspectInvitation(_ method: ReceiveMethod, _ raw: String) { private func inspectInvitation(_ method: ReceiveMethod, _ raw: String) {
let ticket = raw.trimmingCharacters(in: .whitespacesAndNewlines) let ticket = raw.trimmingCharacters(in: .whitespacesAndNewlines)
if ticket.isEmpty { return messages.error(.resource("error_invitation_empty")) } if ticket.isEmpty { return messages.error(.resource(L10n.Error.invitationEmpty)) }
state.isAcquisitionOpen = true state.isAcquisitionOpen = true
state.ticket = ticket state.ticket = ticket
state.method = method state.method = method

View File

@@ -22,17 +22,17 @@ struct ReceiveScreen: View {
history history
} }
} }
.navigationTitle(Text(LocalizedStringKey("receive_title"))) .navigationTitle(Text(String(localized: L10n.Receive.title)))
.toolbar { .toolbar {
ToolbarItem(placement: .primaryAction) { ToolbarItem(placement: .primaryAction) {
Button(action: model.openAcquisition) { Button(action: model.openAcquisition) {
Label(String(localized: "button_receive_files"), systemImage: "plus") Label(String(localized: L10n.Button.receiveFiles), systemImage: "plus")
} }
} }
if !deletable.isEmpty { if !deletable.isEmpty {
ToolbarItem(placement: .primaryAction) { ToolbarItem(placement: .primaryAction) {
Button(role: .destructive, action: model.requestClearHistory) { Button(role: .destructive, action: model.requestClearHistory) {
Label(String(localized: "receive_clear_history"), systemImage: "trash") Label(String(localized: L10n.Receive.clearHistory), systemImage: "trash")
} }
} }
} }
@@ -50,11 +50,11 @@ struct ReceiveScreen: View {
} }
} }
.alert( .alert(
Text(LocalizedStringKey(clearAllPending ? "receive_clear_history_title" : "receive_delete_history_title")), Text(String(localized: clearAllPending ? L10n.Receive.clearHistoryTitle : L10n.Receive.deleteHistoryTitle)),
isPresented: Binding(get: { model.state.historyDeleteTarget != nil }, set: { if !$0 { Task { @MainActor in model.dismissHistoryDelete() } } }) isPresented: Binding(get: { model.state.historyDeleteTarget != nil }, set: { if !$0 { Task { @MainActor in model.dismissHistoryDelete() } } })
) { ) {
Button(String(localized: "button_cancel"), role: .cancel, action: model.dismissHistoryDelete) Button(String(localized: L10n.Button.cancel), role: .cancel, action: model.dismissHistoryDelete)
Button(String(localized: clearAllPending ? "receive_clear_history" : "button_delete_transfer"), Button(String(localized: clearAllPending ? L10n.Receive.clearHistory : L10n.Button.deleteTransfer),
role: .destructive, action: model.confirmHistoryDelete) role: .destructive, action: model.confirmHistoryDelete)
} message: { } message: {
historyDeleteMessage historyDeleteMessage
@@ -74,27 +74,27 @@ struct ReceiveScreen: View {
Button(role: .destructive) { Button(role: .destructive) {
model.requestDeleteHistoryItem(transfer.transferId) model.requestDeleteHistoryItem(transfer.transferId)
} label: { } label: {
Label(String(localized: "button_delete_transfer"), systemImage: "trash") Label(String(localized: L10n.Button.deleteTransfer), systemImage: "trash")
} }
} }
} }
} }
} header: { } header: {
Text(LocalizedStringKey("receive_history_title")) Text(String(localized: L10n.Receive.historyTitle))
} footer: { } footer: {
Text(LocalizedStringKey("receive_new_subtitle")) Text(String(localized: L10n.Receive.newSubtitle))
} }
} }
} }
private var emptyState: some View { private var emptyState: some View {
ContentUnavailableView { ContentUnavailableView {
Label(String(localized: "receive_empty_title"), systemImage: "tray.and.arrow.down") Label(String(localized: L10n.Receive.emptyTitle), systemImage: "tray.and.arrow.down")
} description: { } description: {
Text(LocalizedStringKey("receive_empty_body")) Text(String(localized: L10n.Receive.emptyBody))
} actions: { } actions: {
Button(action: model.openAcquisition) { Button(action: model.openAcquisition) {
Label(String(localized: "button_receive_files"), systemImage: "plus") Label(String(localized: L10n.Button.receiveFiles), systemImage: "plus")
} }
.buttonStyle(.borderedProminent) .buttonStyle(.borderedProminent)
.controlSize(.large) .controlSize(.large)
@@ -107,10 +107,10 @@ struct ReceiveScreen: View {
private var historyDeleteMessage: some View { private var historyDeleteMessage: some View {
if let target = model.state.historyDeleteTarget { if let target = model.state.historyDeleteTarget {
if target == .all { if target == .all {
Text(LocalizedStringKey("receive_clear_history_description")) Text(String(localized: L10n.Receive.clearHistoryDescription))
} else { } else {
Text(String(format: String(localized: "receive_delete_history_description"), Text(L10n.Receive.deleteHistoryDescription(
transferName(for: target) ?? String(localized: "receive_unknown_transfer"))) transferName: transferName(for: target) ?? String(localized: L10n.Receive.unknownTransfer)))
} }
} }
} }
@@ -134,7 +134,7 @@ private struct ReceiveTransferRow: View {
.frame(width: 40, height: 40) .frame(width: 40, height: 40)
.background(.quaternary, in: RoundedRectangle(cornerRadius: 9)) .background(.quaternary, in: RoundedRectangle(cornerRadius: 9))
VStack(alignment: .leading, spacing: 3) { VStack(alignment: .leading, spacing: 3) {
Text(transfer.transferName ?? String(localized: "receive_unknown_transfer")) Text(transfer.transferName ?? String(localized: L10n.Receive.unknownTransfer))
.font(.body).lineLimit(1) .font(.body).lineLimit(1)
Text("\(formatBytes(transfer.totalSize)) · \(statusLabel(transfer.status))") Text("\(formatBytes(transfer.totalSize)) · \(statusLabel(transfer.status))")
.font(.caption).foregroundStyle(.secondary) .font(.caption).foregroundStyle(.secondary)

View File

@@ -217,7 +217,7 @@ final class SendModel: ObservableObject {
state.receiverHistory = [] state.receiverHistory = []
state.isDeleteConfirmationOpen = false state.isDeleteConfirmationOpen = false
state.isDeleting = false state.isDeleting = false
messages.tryShow(UiMessage(text: .resource("transfer_deleted"), tone: .success)) messages.tryShow(UiMessage(text: .resource(L10n.Transfer.deleted), tone: .success))
case .failure(let error): case .failure(let error):
state.isDeleting = false state.isDeleting = false
messages.error(error) messages.error(error)
@@ -249,7 +249,7 @@ final class SendModel: ObservableObject {
switch result { switch result {
case .success: case .success:
_ = await repository.refresh() _ = await repository.refresh()
messages.tryShow(UiMessage(text: .resource("transfer_event_stopped"), tone: .info)) messages.tryShow(UiMessage(text: .resource(L10n.Transfer.eventStopped), tone: .info))
case .failure(let error): case .failure(let error):
messages.error(error) messages.error(error)
} }
@@ -261,10 +261,10 @@ final class SendModel: ObservableObject {
func onInvitationResult(_ action: InvitationAction, _ result: Result<Void, Error>) { func onInvitationResult(_ action: InvitationAction, _ result: Result<Void, Error>) {
switch result { switch result {
case .success: case .success:
let key: String? let key: String.LocalizationValue?
switch action { switch action {
case .export: key = "transfer_invitation_saved" case .export: key = L10n.Transfer.invitationSaved
case .nfc: key = "transfer_nfc_written" case .nfc: key = L10n.Transfer.nfcWritten
case .share: key = nil // system share sheet already confirms case .share: key = nil // system share sheet already confirms
} }
if let key { messages.tryShow(UiMessage(text: .resource(key), tone: .success)) } if let key { messages.tryShow(UiMessage(text: .resource(key), tone: .success)) }
@@ -297,7 +297,7 @@ final class SendModel: ObservableObject {
state.transferName = "" state.transferName = ""
state.accessPolicy = .requireApproval state.accessPolicy = .requireApproval
state.isSharing = false state.isSharing = false
messages.show(UiMessage(text: .resource("send_transfer_created"), tone: .success)) messages.show(UiMessage(text: .resource(L10n.Send.transferCreated), tone: .success))
case .failure(let error): case .failure(let error):
state.isSharing = false state.isSharing = false
messages.error(error) messages.error(error)

View File

@@ -27,11 +27,11 @@ struct SendScreen: View {
catalog catalog
} }
} }
.navigationTitle(Text(LocalizedStringKey("send_title"))) .navigationTitle(Text(String(localized: L10n.Send.title)))
.toolbar { .toolbar {
ToolbarItem(placement: .primaryAction) { ToolbarItem(placement: .primaryAction) {
Button(action: model.openComposer) { Button(action: model.openComposer) {
Label(String(localized: "button_create_new_transfer"), systemImage: "plus") Label(String(localized: L10n.Button.createNewTransfer), systemImage: "plus")
} }
} }
} }
@@ -65,14 +65,14 @@ struct SendScreen: View {
} }
} }
.alert( .alert(
Text(LocalizedStringKey("transfer_delete_title")), Text(String(localized: L10n.Transfer.deleteTitle)),
isPresented: Binding(get: { model.state.isDeleteConfirmationOpen }, set: { if !$0 { Task { @MainActor in model.dismissDeleteTransfer() } } }) isPresented: Binding(get: { model.state.isDeleteConfirmationOpen }, set: { if !$0 { Task { @MainActor in model.dismissDeleteTransfer() } } })
) { ) {
Button(String(localized: "button_cancel"), role: .cancel, action: model.dismissDeleteTransfer) Button(String(localized: L10n.Button.cancel), role: .cancel, action: model.dismissDeleteTransfer)
Button(String(localized: "button_delete_transfer"), role: .destructive, action: model.confirmDeleteTransfer) Button(String(localized: L10n.Button.deleteTransfer), role: .destructive, action: model.confirmDeleteTransfer)
} message: { } message: {
Text(String(format: String(localized: "transfer_delete_description"), Text(L10n.Transfer.deleteDescription(
transfer.transferName ?? String(localized: "send_new_transfer_title"))) transferName: transfer.transferName ?? String(localized: L10n.Send.newTransferTitle)))
} }
} }
@@ -92,21 +92,21 @@ struct SendScreen: View {
.buttonStyle(.plain) .buttonStyle(.plain)
} }
} header: { } header: {
Text(LocalizedStringKey("send_transfers_title")) Text(String(localized: L10n.Send.transfersTitle))
} footer: { } footer: {
Text(LocalizedStringKey("send_subtitle")) Text(String(localized: L10n.Send.subtitle))
} }
} }
} }
private var emptyState: some View { private var emptyState: some View {
ContentUnavailableView { ContentUnavailableView {
Label(String(localized: "send_empty_title"), systemImage: "paperplane") Label(String(localized: L10n.Send.emptyTitle), systemImage: "paperplane")
} description: { } description: {
Text(LocalizedStringKey("send_empty_body")) Text(String(localized: L10n.Send.emptyBody))
} actions: { } actions: {
Button(action: model.openComposer) { Button(action: model.openComposer) {
Label(String(localized: "button_create_new_transfer"), systemImage: "plus") Label(String(localized: L10n.Button.createNewTransfer), systemImage: "plus")
} }
.buttonStyle(.borderedProminent) .buttonStyle(.borderedProminent)
.controlSize(.large) .controlSize(.large)
@@ -127,21 +127,18 @@ struct SendScreen: View {
private func sharingProgress(for transfer: Transfer) -> TransferProgress? { private func sharingProgress(for transfer: Transfer) -> TransferProgress? {
let active = (model.receiversByTransfer[transfer.transferId] ?? []).filter { $0.status == .accepted } let active = (model.receiversByTransfer[transfer.transferId] ?? []).filter { $0.status == .accepted }
if active.isEmpty { return nil } if active.isEmpty { return nil }
let fractions: [Double] = active.compactMap { receiver -> Double? in let fractions = active.compactMap {
let progress = progressForReceiver(events: model.coreState.events, transferId: transfer.transferId, progressForReceiver(events: model.coreState.events, transferId: transfer.transferId,
remoteEndpointId: receiver.remoteEndpointId, totalSizeHint: transfer.totalSize) remoteEndpointId: $0.remoteEndpointId, totalSizeHint: transfer.totalSize)?.progress
guard progress?.kind == "started" || progress?.kind == "progress" else { return nil }
return progress?.progress
} }
guard !fractions.isEmpty else { return nil } let combined = fractions.isEmpty ? nil : fractions.reduce(0, +) / Double(fractions.count)
let combined = fractions.reduce(0, +) / Double(fractions.count)
if active.count == 1 { if active.count == 1 {
return TransferProgress(transferId: transfer.transferId, phase: "transfer", kind: "progress", return TransferProgress(transferId: transfer.transferId, phase: "transfer", kind: "progress",
labelKey: "progress_sending", progress: combined) labelKey: L10n.Progress.sending, progress: combined)
} }
return TransferProgress(transferId: transfer.transferId, phase: "transfer", kind: "progress", return TransferProgress(transferId: transfer.transferId, phase: "transfer", kind: "progress",
labelKey: "progress_sending", progress: combined, labelKey: L10n.Progress.sending, progress: combined,
label: String(format: String(localized: "progress_sending_to_count"), active.count)) label: L10n.Progress.sendingToCount(count: active.count))
} }
} }
@@ -157,7 +154,7 @@ private struct TransferListItem: View {
.background(.quaternary, in: RoundedRectangle(cornerRadius: 9)) .background(.quaternary, in: RoundedRectangle(cornerRadius: 9))
VStack(alignment: .leading, spacing: 3) { VStack(alignment: .leading, spacing: 3) {
HStack { HStack {
Text(transfer.transferName ?? String(localized: "send_new_transfer_title")) Text(transfer.transferName ?? String(localized: L10n.Send.newTransferTitle))
.font(.body).lineLimit(1) .font(.body).lineLimit(1)
Spacer() Spacer()
StatusPill(label: statusLabel(transfer.status), tone: transfer.status.pillTone) StatusPill(label: statusLabel(transfer.status), tone: transfer.status.pillTone)
@@ -192,13 +189,13 @@ struct FileArtwork: View {
} }
func statusLabel(_ status: TransferStatus) -> String { func statusLabel(_ status: TransferStatus) -> String {
String(localized: String.LocalizationValue(statusLabelKey(status))) String(localized: statusLabelKey(status))
} }
func accessPolicyLabel(_ policy: ShareAccessPolicy) -> String { func accessPolicyLabel(_ policy: ShareAccessPolicy) -> String {
switch policy { switch policy {
case .requireApproval: return String(localized: "send_access_approval") case .requireApproval: return String(localized: L10n.Send.accessApproval)
case .anyoneWithTransfer: return String(localized: "send_access_anyone") case .anyoneWithTransfer: return String(localized: L10n.Send.accessAnyone)
} }
} }

View File

@@ -23,13 +23,13 @@ struct TransferComposer: View {
private var chooseStep: some View { private var chooseStep: some View {
VStack(alignment: .leading, spacing: 16) { VStack(alignment: .leading, spacing: 16) {
Text(LocalizedStringKey("send_choose_file_title")).font(.title2).fontWeight(.semibold) Text(String(localized: L10n.Send.chooseFileTitle)).font(.title2).fontWeight(.semibold)
Text(LocalizedStringKey("send_choose_file_body")) Text(String(localized: L10n.Send.chooseFileBody))
.font(.subheadline).foregroundStyle(.secondary) .font(.subheadline).foregroundStyle(.secondary)
VStack(spacing: 14) { VStack(spacing: 14) {
Image(systemName: "doc").font(.system(size: 30)).foregroundStyle(.tint) Image(systemName: "doc").font(.system(size: 30)).foregroundStyle(.tint)
PrimaryButton(title: String(localized: "button_choose_files"), action: model.selectFile).fixedSize() PrimaryButton(title: String(localized: L10n.Button.chooseFiles), action: model.selectFile).fixedSize()
QuietButton(title: String(localized: "button_choose_folder"), action: model.selectFolder) QuietButton(title: String(localized: L10n.Button.chooseFolder), action: model.selectFolder)
} }
.frame(maxWidth: .infinity) .frame(maxWidth: .infinity)
.padding(28) .padding(28)
@@ -39,9 +39,9 @@ struct TransferComposer: View {
private var reviewStep: some View { private var reviewStep: some View {
VStack(alignment: .leading, spacing: 16) { VStack(alignment: .leading, spacing: 16) {
Text(LocalizedStringKey("send_review_title")).font(.title2).fontWeight(.semibold) Text(String(localized: L10n.Send.reviewTitle)).font(.title2).fontWeight(.semibold)
if state.selectedFiles.count > 1 { if state.selectedFiles.count > 1 {
Text(String(format: String(localized: "send_selected_files_count"), state.selectedFiles.count)) Text(L10n.Send.selectedFilesCount(count: state.selectedFiles.count))
.font(.subheadline).foregroundStyle(.secondary) .font(.subheadline).foregroundStyle(.secondary)
} }
ForEach(state.selectedFiles) { file in ForEach(state.selectedFiles) { file in
@@ -51,23 +51,23 @@ struct TransferComposer: View {
onRemove: { model.removeSelectedFile(file.value) } onRemove: { model.removeSelectedFile(file.value) }
) )
} }
Field(label: String(localized: "field_transfer_name"), Field(label: String(localized: L10n.Field.transferName),
value: Binding(get: { state.transferName }, set: { model.setTransferName($0) })) value: Binding(get: { state.transferName }, set: { model.setTransferName($0) }))
Field(label: String(localized: "field_sender_name"), Field(label: String(localized: L10n.Field.senderName),
value: Binding(get: { state.senderName }, set: { model.setSenderName($0) })) value: Binding(get: { state.senderName }, set: { model.setSenderName($0) }))
Text(LocalizedStringKey("send_access_title")).font(.headline) Text(String(localized: L10n.Send.accessTitle)).font(.headline)
PolicyOption( PolicyOption(
icon: "checkmark.shield", titleKey: "send_access_approval", descKey: "send_access_approval_description", icon: "checkmark.shield", titleKey: L10n.Send.accessApproval, descKey: L10n.Send.accessApprovalDescription,
selected: state.accessPolicy == .requireApproval, selected: state.accessPolicy == .requireApproval,
onTap: { model.setAccessPolicy(.requireApproval) } onTap: { model.setAccessPolicy(.requireApproval) }
) )
PolicyOption( PolicyOption(
icon: "globe", titleKey: "send_access_anyone", descKey: "send_access_anyone_description", icon: "globe", titleKey: L10n.Send.accessAnyone, descKey: L10n.Send.accessAnyoneDescription,
selected: state.accessPolicy == .anyoneWithTransfer, selected: state.accessPolicy == .anyoneWithTransfer,
onTap: { model.setAccessPolicy(.anyoneWithTransfer) } onTap: { model.setAccessPolicy(.anyoneWithTransfer) }
) )
if state.accessPolicy == .anyoneWithTransfer { if state.accessPolicy == .anyoneWithTransfer {
Label(String(localized: "send_access_anyone_warning"), systemImage: "exclamationmark.triangle.fill") Label(String(localized: L10n.Send.accessAnyoneWarning), systemImage: "exclamationmark.triangle.fill")
.font(.caption).foregroundStyle(.orange) .font(.caption).foregroundStyle(.orange)
} }
actions actions
@@ -77,7 +77,7 @@ struct TransferComposer: View {
@ViewBuilder @ViewBuilder
private var actions: some View { private var actions: some View {
let shareTitle = state.isSharing let shareTitle = state.isSharing
? String(localized: "button_sharing_file") : String(localized: "button_share_file") ? String(localized: L10n.Button.sharingFile) : String(localized: L10n.Button.shareFile)
let shareButton = PrimaryButton( let shareButton = PrimaryButton(
title: shareTitle, action: model.createShare, title: shareTitle, action: model.createShare,
enabled: state.canCreateShare(coreInitialized: model.coreState.isInitialized) enabled: state.canCreateShare(coreInitialized: model.coreState.isInitialized)
@@ -85,15 +85,15 @@ struct TransferComposer: View {
if windowClass == .phone { if windowClass == .phone {
VStack(spacing: 8) { VStack(spacing: 8) {
shareButton shareButton
QuietButton(title: String(localized: "button_change_files"), action: model.selectFile, enabled: !state.isSharing) QuietButton(title: String(localized: L10n.Button.changeFiles), action: model.selectFile, enabled: !state.isSharing)
QuietButton(title: String(localized: "button_choose_folder"), action: model.selectFolder, enabled: !state.isSharing) QuietButton(title: String(localized: L10n.Button.chooseFolder), action: model.selectFolder, enabled: !state.isSharing)
} }
} else { } else {
HStack(spacing: 8) { HStack(spacing: 8) {
shareButton.fixedSize() shareButton.fixedSize()
QuietButton(title: String(localized: "button_change_files"), action: model.selectFile, enabled: !state.isSharing) QuietButton(title: String(localized: L10n.Button.changeFiles), action: model.selectFile, enabled: !state.isSharing)
QuietButton(title: String(localized: "button_choose_folder"), action: model.selectFolder, enabled: !state.isSharing) QuietButton(title: String(localized: L10n.Button.chooseFolder), action: model.selectFolder, enabled: !state.isSharing)
QuietButton(title: String(localized: "button_clear"), action: model.clearSelectedSource, enabled: !state.isSharing) QuietButton(title: String(localized: L10n.Button.clear), action: model.clearSelectedSource, enabled: !state.isSharing)
} }
} }
} }
@@ -128,16 +128,16 @@ private struct SelectedFileCard: View {
} }
private var subtitle: String { private var subtitle: String {
if file.isDirectory { return String(localized: "send_folder_label") } if file.isDirectory { return String(localized: L10n.Send.folderLabel) }
if let size = file.sizeBytes { return formatBytes(size) } if let size = file.sizeBytes { return formatBytes(size) }
return String(localized: "send_file_size_unknown") return String(localized: L10n.Send.fileSizeUnknown)
} }
} }
private struct PolicyOption: View { private struct PolicyOption: View {
let icon: String let icon: String
let titleKey: String let titleKey: String.LocalizationValue
let descKey: String let descKey: String.LocalizationValue
let selected: Bool let selected: Bool
let onTap: () -> Void let onTap: () -> Void
@@ -149,8 +149,8 @@ private struct PolicyOption: View {
.foregroundStyle(selected ? AnyShapeStyle(.tint) : AnyShapeStyle(.secondary)) .foregroundStyle(selected ? AnyShapeStyle(.tint) : AnyShapeStyle(.secondary))
.frame(width: 22) .frame(width: 22)
VStack(alignment: .leading, spacing: 3) { VStack(alignment: .leading, spacing: 3) {
Text(LocalizedStringKey(titleKey)) Text(String(localized: titleKey))
Text(LocalizedStringKey(descKey)).font(.caption).foregroundStyle(.secondary) Text(String(localized: descKey)).font(.caption).foregroundStyle(.secondary)
} }
Spacer() Spacer()
Image(systemName: selected ? "checkmark.circle.fill" : "circle") Image(systemName: selected ? "checkmark.circle.fill" : "circle")

View File

@@ -23,29 +23,29 @@ struct TransferDetailsView: View {
var body: some View { var body: some View {
Form { Form {
Section { Section {
LabeledContent(String(localized: "metadata_status"), value: statusLabel(transfer.status)) LabeledContent(String(localized: L10n.Metadata.status), value: statusLabel(transfer.status))
LabeledContent(String(localized: "metadata_size"), value: formatBytes(transfer.totalSize)) LabeledContent(String(localized: L10n.Metadata.size), value: formatBytes(transfer.totalSize))
LabeledContent(String(localized: "send_access_title"), value: accessPolicyLabel(transfer.accessPolicy)) LabeledContent(String(localized: L10n.Send.accessTitle), value: accessPolicyLabel(transfer.accessPolicy))
} header: { } header: {
Text(transfer.transferName ?? String(localized: "send_new_transfer_title")) Text(transfer.transferName ?? String(localized: L10n.Send.newTransferTitle))
} }
Section { Section {
DetailDestination( DetailDestination(
title: String(localized: "transfer_activity_title"), title: String(localized: L10n.Transfer.activityTitle),
description: String(localized: "transfer_activity_description"), description: String(localized: L10n.Transfer.activityDescription),
count: events.filter { $0.transferId == transfer.transferId && $0.isMeaningfulActivity }.count, count: events.filter { $0.transferId == transfer.transferId && $0.isMeaningfulActivity }.count,
onTap: model.openActivity onTap: model.openActivity
) )
DetailDestination( DetailDestination(
title: String(localized: "transfer_receivers_title"), title: String(localized: L10n.Transfer.receiversTitle),
description: receiversDescription(pendingReceivers, completedReceivers), description: receiversDescription(pendingReceivers, completedReceivers),
count: pendingReceivers + completedReceivers, count: pendingReceivers + completedReceivers,
onTap: model.openReceivers onTap: model.openReceivers
) )
DetailDestination( DetailDestination(
title: String(localized: "transfer_share_title"), title: String(localized: L10n.Transfer.shareTitle),
description: String(localized: "transfer_share_description"), description: String(localized: L10n.Transfer.shareDescription),
count: 0, count: 0,
onTap: model.openShare onTap: model.openShare
) )
@@ -56,13 +56,13 @@ struct TransferDetailsView: View {
Button(role: .destructive) { Button(role: .destructive) {
showStopConfirmation = true showStopConfirmation = true
} label: { } label: {
Label(String(localized: "send_stop_sharing"), systemImage: "stop.circle") Label(String(localized: L10n.Send.stopSharing), systemImage: "stop.circle")
} }
} }
} }
} }
.formStyle(.grouped) .formStyle(.grouped)
.navigationTitle(Text(LocalizedStringKey("send_transfer_details_title"))) .navigationTitle(Text(String(localized: L10n.Send.transferDetailsTitle)))
#if os(iOS) #if os(iOS)
.navigationBarTitleDisplayMode(.inline) .navigationBarTitleDisplayMode(.inline)
#endif #endif
@@ -74,27 +74,27 @@ struct TransferDetailsView: View {
} }
} }
.confirmationDialog( .confirmationDialog(
Text(LocalizedStringKey("send_stop_sharing")), Text(String(localized: L10n.Send.stopSharing)),
isPresented: $showStopConfirmation, isPresented: $showStopConfirmation,
titleVisibility: .visible titleVisibility: .visible
) { ) {
Button(String(localized: "send_stop_sharing"), role: .destructive) { Button(String(localized: L10n.Send.stopSharing), role: .destructive) {
model.stopSharing(transferId: transfer.transferId) model.stopSharing(transferId: transfer.transferId)
} }
Button(String(localized: "button_cancel"), role: .cancel) {} Button(String(localized: L10n.Button.cancel), role: .cancel) {}
} message: { } message: {
Text(LocalizedStringKey("send_stop_sharing_description")) Text(String(localized: L10n.Send.stopSharingDescription))
} }
} }
} }
private func receiversDescription(_ pending: Int, _ completed: Int) -> String { private func receiversDescription(_ pending: Int, _ completed: Int) -> String {
if pending > 0 && completed > 0 { if pending > 0 && completed > 0 {
return "\(String(format: String(localized: "transfer_receivers_pending"), pending)) · \(String(format: String(localized: "transfer_receivers_completed_count"), completed))" return "\(L10n.Transfer.receiversPending(count: pending)) · \(L10n.Transfer.receiversCompletedCount(count: completed))"
} }
if pending > 0 { return String(format: String(localized: "transfer_receivers_pending"), pending) } if pending > 0 { return L10n.Transfer.receiversPending(count: pending) }
if completed > 0 { return String(format: String(localized: "transfer_receivers_completed_count"), completed) } if completed > 0 { return L10n.Transfer.receiversCompletedCount(count: completed) }
return String(localized: "transfer_receivers_description") return String(localized: L10n.Transfer.receiversDescription)
} }
private struct DetailDestination: View { private struct DetailDestination: View {
@@ -171,13 +171,13 @@ struct TransferActivityPanel: View {
let visible = events let visible = events
.filter { $0.transferId == transferId && $0.isMeaningfulActivity } .filter { $0.transferId == transferId && $0.isMeaningfulActivity }
.sorted { $0.timestamp > $1.timestamp } .sorted { $0.timestamp > $1.timestamp }
PanelContainer(title: String(localized: "transfer_activity_title")) { PanelContainer(title: String(localized: L10n.Transfer.activityTitle)) {
if visible.isEmpty { if visible.isEmpty {
Text(LocalizedStringKey("transfer_no_activity")).foregroundStyle(colors.foregroundLighter) Text(String(localized: L10n.Transfer.noActivity)).foregroundStyle(colors.foregroundLighter)
} else { } else {
ForEach(Array(visible.enumerated()), id: \.offset) { index, event in ForEach(Array(visible.enumerated()), id: \.offset) { index, event in
if index > 0 { Divider().overlay(colors.borderDefault) } if index > 0 { Divider().overlay(colors.borderDefault) }
Text(LocalizedStringKey(event.activityTitleKey)) Text(String(localized: event.activityTitleKey))
.fontWeight(.medium).padding(.vertical, 14) .fontWeight(.medium).padding(.vertical, 14)
} }
} }
@@ -194,11 +194,11 @@ struct ReceiverHistoryPanel: View {
let onCancel: (String) -> Void let onCancel: (String) -> Void
var body: some View { var body: some View {
PanelContainer(title: String(localized: "transfer_receivers_title")) { PanelContainer(title: String(localized: L10n.Transfer.receiversTitle)) {
if loading { if loading {
ProgressView().frame(maxWidth: .infinity).padding(40) ProgressView().frame(maxWidth: .infinity).padding(40)
} else if receivers.isEmpty { } else if receivers.isEmpty {
Text(LocalizedStringKey("transfer_no_receivers")).foregroundStyle(colors.foregroundLighter) Text(String(localized: L10n.Transfer.noReceivers)).foregroundStyle(colors.foregroundLighter)
} else { } else {
ForEach(Array(receivers.enumerated()), id: \.element.id) { index, receiver in ForEach(Array(receivers.enumerated()), id: \.element.id) { index, receiver in
if index > 0 { Divider().overlay(colors.borderDefault) } if index > 0 { Divider().overlay(colors.borderDefault) }
@@ -232,7 +232,7 @@ private struct ReceiverRow: View {
} }
var body: some View { var body: some View {
let name = receiver.receiverName ?? receiver.receiverDeviceName ?? String(localized: "transfer_nearby_device") let name = receiver.receiverName ?? receiver.receiverDeviceName ?? String(localized: L10n.Transfer.nearbyDevice)
let showLive = sendProgress != nil && receiver.status != .completed let showLive = sendProgress != nil && receiver.status != .completed
&& receiver.status != .refused && receiver.status != .expired && receiver.status != .refused && receiver.status != .expired
HStack(alignment: .top, spacing: 12) { HStack(alignment: .top, spacing: 12) {
@@ -244,7 +244,7 @@ private struct ReceiverRow: View {
if showLive, let sendProgress { if showLive, let sendProgress {
ProgressRow(labelKey: sendProgress.labelKey, progress: sendProgress.progress, detail: sendProgress.detail, labelText: sendProgress.label) ProgressRow(labelKey: sendProgress.labelKey, progress: sendProgress.progress, detail: sendProgress.detail, labelText: sendProgress.label)
} else { } else {
Text(LocalizedStringKey(receiver.status.statusTextKey)) Text(String(localized: receiver.status.statusTextKey))
.font(VniType.bodySmall).fontWeight(.medium) .font(VniType.bodySmall).fontWeight(.medium)
.foregroundStyle(receiver.status.statusColor(colors)) .foregroundStyle(receiver.status.statusColor(colors))
} }
@@ -257,7 +257,7 @@ private struct ReceiverRow: View {
Button(role: .destructive) { Button(role: .destructive) {
onCancel(receiver.id) onCancel(receiver.id)
} label: { } label: {
Text(LocalizedStringKey("button_refuse")) Text(String(localized: L10n.Button.refuse))
.font(VniType.bodySmall) .font(VniType.bodySmall)
} }
.buttonStyle(.borderless) .buttonStyle(.borderless)
@@ -275,15 +275,15 @@ struct TransferSharePanel: View {
let transfer: Transfer let transfer: Transfer
var body: some View { var body: some View {
PanelContainer(title: String(localized: "transfer_share_title")) { PanelContainer(title: String(localized: L10n.Transfer.shareTitle)) {
if let ticket = transfer.ticket { if let ticket = transfer.ticket {
qrCard(ticket: ticket) qrCard(ticket: ticket)
Text(LocalizedStringKey("transfer_scan_qr")) Text(String(localized: L10n.Transfer.scanQr))
.font(VniType.bodySmall).foregroundStyle(colors.foregroundLighter) .font(VniType.bodySmall).foregroundStyle(colors.foregroundLighter)
.frame(maxWidth: .infinity) .frame(maxWidth: .infinity)
ShareActionsView(model: model, transfer: transfer, ticket: ticket) ShareActionsView(model: model, transfer: transfer, ticket: ticket)
} else { } else {
Text(LocalizedStringKey("transfer_event_preparing")).foregroundStyle(colors.foregroundLighter) Text(String(localized: L10n.Transfer.eventPreparing)).foregroundStyle(colors.foregroundLighter)
} }
} }
} }
@@ -334,31 +334,31 @@ extension CoreEventModel {
"receiver-refused", "receiver-completed", "share-stopped", "failed"].contains(kind) "receiver-refused", "receiver-completed", "share-stopped", "failed"].contains(kind)
} }
var activityTitleKey: String { var activityTitleKey: String.LocalizationValue {
if phase == "import" && kind == "started" { return "transfer_event_preparing" } if phase == "import" && kind == "started" { return L10n.Transfer.eventPreparing }
if phase == "ticket" && kind == "created" { return "transfer_event_ready" } if phase == "ticket" && kind == "created" { return L10n.Transfer.eventReady }
if phase == "network" { return "transfer_event_connecting" } if phase == "network" { return L10n.Transfer.eventConnecting }
if phase == "download" { return "transfer_event_downloading" } if phase == "download" { return L10n.Transfer.eventDownloading }
if phase == "export" { return "transfer_event_saving" } if phase == "export" { return L10n.Transfer.eventSaving }
if kind == "receiver-requested" { return "transfer_event_requested" } if kind == "receiver-requested" { return L10n.Transfer.eventRequested }
if kind == "receiver-accepted" || kind == "receiver-auto-approved" { return "transfer_event_approved" } if kind == "receiver-accepted" || kind == "receiver-auto-approved" { return L10n.Transfer.eventApproved }
if kind == "receiver-refused" { return "transfer_event_refused" } if kind == "receiver-refused" { return L10n.Transfer.eventRefused }
if kind == "receiver-completed" { return "transfer_event_completed" } if kind == "receiver-completed" { return L10n.Transfer.eventCompleted }
if kind == "share-stopped" || (phase == "lifecycle" && kind == "cancelled") { return "transfer_event_stopped" } if kind == "share-stopped" || (phase == "lifecycle" && kind == "cancelled") { return L10n.Transfer.eventStopped }
if kind == "failed" { return "transfer_event_failed" } if kind == "failed" { return L10n.Transfer.eventFailed }
return "transfer_event_updated" return L10n.Transfer.eventUpdated
} }
} }
extension ReceiverDeliveryStatus { extension ReceiverDeliveryStatus {
var statusTextKey: String { var statusTextKey: String.LocalizationValue {
switch self { switch self {
case .requested: return "transfer_receiver_requested" case .requested: return L10n.Transfer.receiverRequested
case .accepted: return "transfer_receiver_accepted" case .accepted: return L10n.Transfer.receiverAccepted
case .refused: return "transfer_receiver_refused" case .refused: return L10n.Transfer.receiverRefused
case .expired: return "transfer_receiver_expired" case .expired: return L10n.Transfer.receiverExpired
case .completed: return "transfer_receiver_completed" case .completed: return L10n.Transfer.receiverCompleted
case .unknown: return "transfer_receiver_unknown" case .unknown: return L10n.Transfer.receiverUnknown
} }
} }

View File

@@ -2,7 +2,7 @@ import SwiftUI
enum NfcShareAvailability { case available, unavailable, hidden } enum NfcShareAvailability { case available, unavailable, hidden }
/// Invitation delivery actions shared by the native Apple feature models. /// Invitation delivery actions, ported from `TransferShareActions` (iosMain).
/// Platform implementations perform export, native share, and NFC write. /// Platform implementations perform export, native share, and NFC write.
@MainActor @MainActor
protocol TransferShareActions: AnyObject { protocol TransferShareActions: AnyObject {
@@ -30,7 +30,7 @@ struct ShareActionsView: View {
VStack(spacing: 12) { VStack(spacing: 12) {
if actions.nfcAvailability != .hidden { if actions.nfcAvailability != .hidden {
SecondaryButton( SecondaryButton(
title: writingNfc ? String(localized: "transfer_nfc_waiting") : String(localized: "button_write_nfc"), title: writingNfc ? String(localized: L10n.Transfer.nfcWaiting) : String(localized: L10n.Button.writeNfc),
action: { action: {
writingNfc = true writingNfc = true
actions.writeInvitationToNfc(ticket: ticket) { result in actions.writeInvitationToNfc(ticket: ticket) { result in
@@ -41,16 +41,16 @@ struct ShareActionsView: View {
enabled: actions.nfcAvailability == .available && !writingNfc enabled: actions.nfcAvailability == .available && !writingNfc
) )
if actions.nfcAvailability == .unavailable { if actions.nfcAvailability == .unavailable {
Text(LocalizedStringKey("transfer_nfc_unavailable")) Text(String(localized: L10n.Transfer.nfcUnavailable))
.font(VniType.bodySmall).foregroundStyle(colors.foregroundLighter) .font(VniType.bodySmall).foregroundStyle(colors.foregroundLighter)
} }
} }
SecondaryButton(title: String(localized: "button_download_invitation"), action: { SecondaryButton(title: String(localized: L10n.Button.downloadInvitation), action: {
actions.exportInvitation(ticket: ticket, transferName: transfer.transferName ?? "") { actions.exportInvitation(ticket: ticket, transferName: transfer.transferName ?? "") {
model.onInvitationResult(.export, $0) model.onInvitationResult(.export, $0)
} }
}) })
PrimaryButton(title: String(localized: "button_native_share"), action: { PrimaryButton(title: String(localized: L10n.Button.nativeShare), action: {
actions.shareInvitation(ticket: ticket, transferName: transfer.transferName ?? "") { actions.shareInvitation(ticket: ticket, transferName: transfer.transferName ?? "") {
model.onInvitationResult(.share, $0) model.onInvitationResult(.share, $0)
} }

View File

@@ -11,15 +11,15 @@ enum SettingsSection: Hashable {
case about case about
case bugReport case bugReport
var titleKey: String { var titleKey: String.LocalizationValue {
switch self { switch self {
case .overview: return "settings_title" case .overview: return L10n.Settings.title
case .preferences: return "preferences_title" case .preferences: return L10n.Preferences.title
case .appearance: return "appearance_title" case .appearance: return L10n.Appearance.title
case .notifications: return "notifications_title" case .notifications: return L10n.Notifications.title
case .storage: return "storage_title" case .storage: return L10n.Storage.title
case .about: return "about_title" case .about: return L10n.About.title
case .bugReport: return "about_bug_report" case .bugReport: return L10n.About.bugReport
} }
} }
} }
@@ -184,11 +184,11 @@ final class SettingsModel: ObservableObject {
await enableNotifications() await enableNotifications()
} else { } else {
preferences.setNotificationsEnabled(false) preferences.setNotificationsEnabled(false)
let key = permission == .unsupported ? "notifications_unsupported" : "notifications_permission_denied" let key = permission == .unsupported ? L10n.Notifications.unsupported : L10n.Notifications.permissionDenied
messages.show(UiMessage( messages.show(UiMessage(
text: .resource(key), text: .resource(key),
tone: .warning, tone: .warning,
actionLabel: permission == .denied ? .resource("button_open_settings") : nil, actionLabel: permission == .denied ? .resource(L10n.Button.openSettings) : nil,
onAction: permission == .denied ? { self.openNotificationSettings() } : nil onAction: permission == .denied ? { self.openNotificationSettings() } : nil
)) ))
} }
@@ -200,7 +200,7 @@ final class SettingsModel: ObservableObject {
Task { Task {
preferences.setDiagnosticsEnabled(enabled) preferences.setDiagnosticsEnabled(enabled)
messages.show(UiMessage( messages.show(UiMessage(
text: .resource(enabled ? "diagnostics_enabled_message" : "diagnostics_disabled_message"), text: .resource(enabled ? L10n.Diagnostics.enabledMessage : L10n.Diagnostics.disabledMessage),
tone: .success tone: .success
)) ))
} }
@@ -219,11 +219,11 @@ final class SettingsModel: ObservableObject {
let what = snapshot.bugWhatHappened.trimmingCharacters(in: .whitespacesAndNewlines) let what = snapshot.bugWhatHappened.trimmingCharacters(in: .whitespacesAndNewlines)
let expected = snapshot.bugExpected.trimmingCharacters(in: .whitespacesAndNewlines) let expected = snapshot.bugExpected.trimmingCharacters(in: .whitespacesAndNewlines)
if what.isEmpty { if what.isEmpty {
messages.show(UiMessage(text: .resource("bug_report_missing_what"), tone: .warning)) messages.show(UiMessage(text: .resource(L10n.Bug.reportMissingWhat), tone: .warning))
return return
} }
if expected.isEmpty { if expected.isEmpty {
messages.show(UiMessage(text: .resource("bug_report_missing_expected"), tone: .warning)) messages.show(UiMessage(text: .resource(L10n.Bug.reportMissingExpected), tone: .warning))
return return
} }
state.isSubmittingBugReport = true state.isSubmittingBugReport = true
@@ -242,11 +242,11 @@ final class SettingsModel: ObservableObject {
state.bugSteps = "" state.bugSteps = ""
state.bugContact = "" state.bugContact = ""
state.bugIncludeLogs = true state.bugIncludeLogs = true
messages.show(UiMessage(text: .resource("bug_report_submitted"), tone: .success)) messages.show(UiMessage(text: .resource(L10n.Bug.reportSubmitted), tone: .success))
onSuccess() onSuccess()
case .failure: case .failure:
state.isSubmittingBugReport = false state.isSubmittingBugReport = false
messages.show(UiMessage(text: .resource("bug_report_submit_failed"), tone: .error)) messages.show(UiMessage(text: .resource(L10n.Bug.reportSubmitFailed), tone: .error))
} }
} }
} }
@@ -257,7 +257,7 @@ final class SettingsModel: ObservableObject {
let result = await notifications.openSettings() let result = await notifications.openSettings()
if case .failure = result { if case .failure = result {
enableNotificationsAfterSettings = false enableNotificationsAfterSettings = false
messages.show(UiMessage(text: .resource("notifications_settings_open_failed"), tone: .error)) messages.show(UiMessage(text: .resource(L10n.Notifications.settingsOpenFailed), tone: .error))
} }
} }
} }
@@ -278,7 +278,7 @@ final class SettingsModel: ObservableObject {
private func enableNotifications() async { private func enableNotifications() async {
preferences.setNotificationsEnabled(true) preferences.setNotificationsEnabled(true)
messages.show(UiMessage(text: .resource("notifications_enabled_message"), tone: .success)) messages.show(UiMessage(text: .resource(L10n.Notifications.enabledMessage), tone: .success))
} }
// MARK: - Storage // MARK: - Storage
@@ -328,7 +328,7 @@ final class SettingsModel: ObservableObject {
state.isDeletingTransfers = false state.isDeletingTransfers = false
if failures == 0 { if failures == 0 {
loadStorageUsage() loadStorageUsage()
messages.show(UiMessage(text: .resource("storage_transfers_deleted"), tone: .success)) messages.show(UiMessage(text: .resource(L10n.Storage.transfersDeleted), tone: .success))
} else { } else {
messages.error(InvitationError.message("Could not delete \(failures) transfer records")) messages.error(InvitationError.message("Could not delete \(failures) transfer records"))
} }

View File

@@ -25,26 +25,26 @@ struct SettingsScreen: View {
Form { Form {
Section { Section {
NavigationLink(value: SettingsSection.preferences) { NavigationLink(value: SettingsSection.preferences) {
SettingsRow(icon: "person.crop.circle", title: String(localized: "preferences_title"), value: model.state.username) SettingsRow(icon: "person.crop.circle", title: String(localized: L10n.Preferences.title), value: model.state.username)
} }
NavigationLink(value: SettingsSection.appearance) { NavigationLink(value: SettingsSection.appearance) {
SettingsRow(icon: "sun.max", title: String(localized: "appearance_title"), value: themeModeLabel(model.state.themeMode)) SettingsRow(icon: "sun.max", title: String(localized: L10n.Appearance.title), value: themeModeLabel(model.state.themeMode))
} }
} }
Section { Section {
NavigationLink(value: SettingsSection.notifications) { NavigationLink(value: SettingsSection.notifications) {
SettingsRow(icon: "bell", title: String(localized: "notifications_title"), value: nil) SettingsRow(icon: "bell", title: String(localized: L10n.Notifications.title), value: nil)
} }
NavigationLink(value: SettingsSection.storage) { NavigationLink(value: SettingsSection.storage) {
SettingsRow(icon: "internaldrive", title: String(localized: "storage_title"), value: nil) SettingsRow(icon: "internaldrive", title: String(localized: L10n.Storage.title), value: nil)
} }
NavigationLink(value: SettingsSection.about) { NavigationLink(value: SettingsSection.about) {
SettingsRow(icon: "info.circle", title: String(localized: "about_title"), value: nil) SettingsRow(icon: "info.circle", title: String(localized: L10n.About.title), value: nil)
} }
} }
} }
.formStyle(.grouped) .formStyle(.grouped)
.navigationTitle(Text(LocalizedStringKey("settings_title"))) .navigationTitle(Text(String(localized: L10n.Settings.title)))
.navigationDestination(for: SettingsSection.self) { section in .navigationDestination(for: SettingsSection.self) { section in
sectionForm(section) sectionForm(section)
} }
@@ -57,7 +57,7 @@ struct SettingsScreen: View {
SettingsSectionContent(model: model, section: section) SettingsSectionContent(model: model, section: section)
} }
.formStyle(.grouped) .formStyle(.grouped)
.navigationTitle(Text(LocalizedStringKey(section.titleKey))) .navigationTitle(Text(String(localized: section.titleKey)))
if section == .about { if section == .about {
content content
@@ -69,7 +69,7 @@ struct SettingsScreen: View {
Button { Button {
showBugReport = true showBugReport = true
} label: { } label: {
Label(String(localized: "about_bug_report"), systemImage: "ladybug") Label(String(localized: L10n.About.bugReport), systemImage: "ladybug")
} }
} }
} }
@@ -130,8 +130,8 @@ struct SettingsRow: View {
func themeModeLabel(_ mode: ThemeMode) -> String { func themeModeLabel(_ mode: ThemeMode) -> String {
switch mode { switch mode {
case .system: return String(localized: "appearance_system_mode") case .system: return String(localized: L10n.Appearance.systemMode)
case .light: return String(localized: "appearance_light_mode") case .light: return String(localized: L10n.Appearance.lightMode)
case .dark: return String(localized: "appearance_dark_mode") case .dark: return String(localized: L10n.Appearance.darkMode)
} }
} }

View File

@@ -7,16 +7,16 @@ struct PreferencesSettings: View {
@ObservedObject var model: SettingsModel @ObservedObject var model: SettingsModel
var body: some View { var body: some View {
Section(String(localized: "field_username")) { Section(String(localized: L10n.Field.username)) {
TextField(String(localized: "field_username"), TextField(String(localized: L10n.Field.username),
text: Binding(get: { model.state.username }, set: { model.setUsername($0) })) text: Binding(get: { model.state.username }, set: { model.setUsername($0) }))
} }
if model.state.supportsCustomReceiveFolders { if model.state.supportsCustomReceiveFolders {
Section(String(localized: "preferences_receive_folder_title")) { Section(String(localized: L10n.Preferences.receiveFolderTitle)) {
Text(model.state.receiveFolder?.displayName ?? String(localized: "value_unavailable")) Text(model.state.receiveFolder?.displayName ?? String(localized: L10n.Value.unavailable))
.foregroundStyle(.secondary) .foregroundStyle(.secondary)
Button(String(localized: "button_choose_folder"), action: model.chooseReceiveFolder) Button(String(localized: L10n.Button.chooseFolder), action: model.chooseReceiveFolder)
Button(String(localized: "button_reset_default"), action: model.resetReceiveFolder) Button(String(localized: L10n.Button.resetDefault), action: model.resetReceiveFolder)
} }
} }
} }
@@ -27,7 +27,7 @@ struct AppearanceSettings: View {
var body: some View { var body: some View {
Section { Section {
Picker(String(localized: "appearance_title"), Picker(String(localized: L10n.Appearance.title),
selection: Binding(get: { model.state.themeMode }, set: { model.setThemeMode($0) })) { selection: Binding(get: { model.state.themeMode }, set: { model.setThemeMode($0) })) {
ForEach(ThemeMode.allCases, id: \.self) { mode in ForEach(ThemeMode.allCases, id: \.self) { mode in
Text(themeModeLabel(mode)).tag(mode) Text(themeModeLabel(mode)).tag(mode)
@@ -48,10 +48,10 @@ struct NotificationSettings: View {
get: { model.state.notificationsEnabled }, get: { model.state.notificationsEnabled },
set: { model.setNotificationsEnabled($0) } set: { model.setNotificationsEnabled($0) }
)) { )) {
Text(LocalizedStringKey("notifications_local_title")) Text(String(localized: L10n.Notifications.localTitle))
} }
if model.state.notificationPermission == .denied { if model.state.notificationPermission == .denied {
Button(String(localized: "button_open_settings"), action: model.openNotificationSettings) Button(String(localized: L10n.Button.openSettings), action: model.openNotificationSettings)
} }
} }
} }
@@ -64,22 +64,22 @@ struct StorageSettings: View {
var body: some View { var body: some View {
Section { Section {
if let storage = model.state.storage { if let storage = model.state.storage {
LabeledContent(String(localized: "storage_received_files"), value: formatBytes(storage.receivedFiles)) LabeledContent(String(localized: L10n.Storage.receivedFiles), value: formatBytes(storage.receivedFiles))
LabeledContent(String(localized: "storage_transfer_data"), value: formatBytes(storage.transferCache)) LabeledContent(String(localized: L10n.Storage.transferData), value: formatBytes(storage.transferCache))
LabeledContent(String(localized: "storage_app_data"), value: formatBytes(storage.appData)) LabeledContent(String(localized: L10n.Storage.appData), value: formatBytes(storage.appData))
LabeledContent(String(localized: "storage_temporary"), value: formatBytes(storage.temporary)) LabeledContent(String(localized: L10n.Storage.temporary), value: formatBytes(storage.temporary))
LabeledContent(String(localized: "storage_total")) { LabeledContent(String(localized: L10n.Storage.total)) {
Text(formatBytes(storage.total)).fontWeight(.semibold) Text(formatBytes(storage.total)).fontWeight(.semibold)
} }
} else { } else {
HStack { HStack {
Text(LocalizedStringKey("storage_calculating")).foregroundStyle(.secondary) Text(String(localized: L10n.Storage.calculating)).foregroundStyle(.secondary)
Spacer() Spacer()
ProgressView() ProgressView()
} }
} }
} footer: { } footer: {
Text(LocalizedStringKey("storage_footer")) Text(String(localized: L10n.Storage.footer))
} }
Section { Section {
@@ -88,8 +88,8 @@ struct StorageSettings: View {
} label: { } label: {
HStack { HStack {
Text(model.state.isDeletingTransfers Text(model.state.isDeletingTransfers
? String(localized: "storage_deleting") ? String(localized: L10n.Storage.deleting)
: String(localized: "storage_delete_transfers")) : String(localized: L10n.Storage.deleteTransfers))
if model.state.isDeletingTransfers { if model.state.isDeletingTransfers {
Spacer() Spacer()
ProgressView() ProgressView()
@@ -100,16 +100,16 @@ struct StorageSettings: View {
} }
.onAppear { model.loadStorageUsage() } .onAppear { model.loadStorageUsage() }
.confirmationDialog( .confirmationDialog(
Text(LocalizedStringKey("storage_delete_transfers")), Text(String(localized: L10n.Storage.deleteTransfers)),
isPresented: $showDeleteConfirmation, isPresented: $showDeleteConfirmation,
titleVisibility: .visible titleVisibility: .visible
) { ) {
Button(String(localized: "storage_delete_transfers"), role: .destructive) { Button(String(localized: L10n.Storage.deleteTransfers), role: .destructive) {
model.deleteAllTransfers() model.deleteAllTransfers()
} }
Button(String(localized: "button_cancel"), role: .cancel) {} Button(String(localized: L10n.Button.cancel), role: .cancel) {}
} message: { } message: {
Text(LocalizedStringKey("storage_delete_transfers_description")) Text(String(localized: L10n.Storage.deleteTransfersDescription))
} }
} }
} }
@@ -121,40 +121,40 @@ struct AboutSettings: View {
var body: some View { var body: some View {
Section { Section {
Text(LocalizedStringKey("about_tagline")).font(.headline) Text(String(localized: L10n.About.tagline)).font(.headline)
Text(LocalizedStringKey("about_description")).foregroundStyle(.secondary) Text(String(localized: L10n.About.description)).foregroundStyle(.secondary)
} }
Section(String(localized: "about_is_title")) { Section(String(localized: L10n.About.isTitle)) {
AboutPoint("about_is_direct", "paperplane") AboutPoint(L10n.About.isDirect, "paperplane")
AboutPoint("about_is_no_account", "person.crop.circle.badge.xmark") AboutPoint(L10n.About.isNoAccount, "person.crop.circle.badge.xmark")
AboutPoint("about_is_in_control", "checkmark.shield") AboutPoint(L10n.About.isInControl, "checkmark.shield")
AboutPoint("about_is_encrypted", "lock") AboutPoint(L10n.About.isEncrypted, "lock")
AboutPoint("about_is_open", "chevron.left.forwardslash.chevron.right") AboutPoint(L10n.About.isOpen, "chevron.left.forwardslash.chevron.right")
} }
Section(String(localized: "about_isnt_title")) { Section(String(localized: L10n.About.isntTitle)) {
AboutPoint("about_isnt_cloud", "icloud.slash") AboutPoint(L10n.About.isntCloud, "icloud.slash")
AboutPoint("about_isnt_sync", "arrow.triangle.2.circlepath") AboutPoint(L10n.About.isntSync, "arrow.triangle.2.circlepath")
AboutPoint("about_isnt_public", "megaphone") AboutPoint(L10n.About.isntPublic, "megaphone")
} }
Section(String(localized: "about_privacy_title")) { Section(String(localized: L10n.About.privacyTitle)) {
AboutPoint("about_privacy_capability", "qrcode") AboutPoint(L10n.About.privacyCapability, "qrcode")
AboutPoint("about_privacy_deny", "hand.raised") AboutPoint(L10n.About.privacyDeny, "hand.raised")
AboutPoint("about_privacy_relay", "antenna.radiowaves.left.and.right") AboutPoint(L10n.About.privacyRelay, "antenna.radiowaves.left.and.right")
AboutPoint("about_privacy_local", "internaldrive") AboutPoint(L10n.About.privacyLocal, "internaldrive")
} }
Section(String(localized: "about_title")) { Section(String(localized: L10n.About.title)) {
LabeledContent(String(localized: "version_title"), value: model.state.appVersion) LabeledContent(String(localized: L10n.Version.title), value: model.state.appVersion)
if let device = model.state.deviceInfo { if let device = model.state.deviceInfo {
LabeledContent(String(localized: "device_model_title"), value: device.deviceModel ?? "") LabeledContent(String(localized: L10n.Device.modelTitle), value: device.deviceModel ?? "")
LabeledContent(String(localized: "os_version_title"), value: device.operatingSystem) LabeledContent(String(localized: L10n.Os.versionTitle), value: device.operatingSystem)
} }
LabeledContent(String(localized: "about_license_label"), value: "Apache 2.0") LabeledContent(String(localized: L10n.About.licenseLabel), value: "Apache 2.0")
Link(destination: Self.privacyPolicyURL) { Link(destination: Self.privacyPolicyURL) {
Label(String(localized: "about_privacy_policy_label"), systemImage: "hand.raised") Label(String(localized: L10n.About.privacyPolicyLabel), systemImage: "hand.raised")
} }
} }
@@ -164,7 +164,7 @@ struct AboutSettings: View {
get: { model.state.diagnosticsEnabled }, get: { model.state.diagnosticsEnabled },
set: { model.setDiagnosticsEnabled($0) } set: { model.setDiagnosticsEnabled($0) }
)) { )) {
Text(LocalizedStringKey("diagnostics_title")) Text(String(localized: L10n.Diagnostics.title))
} }
} }
} }
@@ -188,13 +188,13 @@ struct BugReportSheet: View {
BugReportSettings(model: model, onSubmitted: { dismiss() }) BugReportSettings(model: model, onSubmitted: { dismiss() })
} }
.formStyle(.grouped) .formStyle(.grouped)
.navigationTitle(Text(LocalizedStringKey("about_bug_report"))) .navigationTitle(Text(String(localized: L10n.About.bugReport)))
#if os(iOS) #if os(iOS)
.navigationBarTitleDisplayMode(.inline) .navigationBarTitleDisplayMode(.inline)
#endif #endif
.toolbar { .toolbar {
ToolbarItem(placement: .cancellationAction) { ToolbarItem(placement: .cancellationAction) {
Button(String(localized: "button_cancel")) { dismiss() } Button(String(localized: L10n.Button.cancel)) { dismiss() }
} }
} }
} }
@@ -204,17 +204,17 @@ struct BugReportSheet: View {
/// A bullet-style informational row with an SF Symbol and wrapping localized text. /// A bullet-style informational row with an SF Symbol and wrapping localized text.
private struct AboutPoint: View { private struct AboutPoint: View {
let key: String let key: String.LocalizationValue
let symbol: String let symbol: String
init(_ key: String, _ symbol: String) { init(_ key: String.LocalizationValue, _ symbol: String) {
self.key = key self.key = key
self.symbol = symbol self.symbol = symbol
} }
var body: some View { var body: some View {
Label { Label {
Text(LocalizedStringKey(key)) Text(String(localized: key))
.font(.subheadline) .font(.subheadline)
.fixedSize(horizontal: false, vertical: true) .fixedSize(horizontal: false, vertical: true)
} icon: { } icon: {
@@ -228,36 +228,36 @@ struct BugReportSettings: View {
var onSubmitted: () -> Void = {} var onSubmitted: () -> Void = {}
var body: some View { var body: some View {
Section(String(localized: "bug_report_what_label")) { Section(String(localized: L10n.Bug.reportWhatLabel)) {
TextField("", text: Binding(get: { model.state.bugWhatHappened }, set: { model.setBugWhatHappened($0) }), TextField("", text: Binding(get: { model.state.bugWhatHappened }, set: { model.setBugWhatHappened($0) }),
prompt: Text(LocalizedStringKey("bug_report_what_hint")), axis: .vertical) prompt: Text(String(localized: L10n.Bug.reportWhatHint)), axis: .vertical)
.lineLimit(3, reservesSpace: true) .lineLimit(3, reservesSpace: true)
.labelsHidden() .labelsHidden()
} }
Section(String(localized: "bug_report_expected_label")) { Section(String(localized: L10n.Bug.reportExpectedLabel)) {
TextField("", text: Binding(get: { model.state.bugExpected }, set: { model.setBugExpected($0) }), TextField("", text: Binding(get: { model.state.bugExpected }, set: { model.setBugExpected($0) }),
prompt: Text(LocalizedStringKey("bug_report_expected_hint")), axis: .vertical) prompt: Text(String(localized: L10n.Bug.reportExpectedHint)), axis: .vertical)
.lineLimit(3, reservesSpace: true) .lineLimit(3, reservesSpace: true)
.labelsHidden() .labelsHidden()
} }
Section(String(localized: "bug_report_steps_label")) { Section(String(localized: L10n.Bug.reportStepsLabel)) {
TextField("", text: Binding(get: { model.state.bugSteps }, set: { model.setBugSteps($0) }), TextField("", text: Binding(get: { model.state.bugSteps }, set: { model.setBugSteps($0) }),
prompt: Text(LocalizedStringKey("bug_report_steps_hint")), axis: .vertical) prompt: Text(String(localized: L10n.Bug.reportStepsHint)), axis: .vertical)
.lineLimit(3, reservesSpace: true) .lineLimit(3, reservesSpace: true)
.labelsHidden() .labelsHidden()
} }
Section(String(localized: "bug_report_contact_label")) { Section(String(localized: L10n.Bug.reportContactLabel)) {
TextField("", text: Binding(get: { model.state.bugContact }, set: { model.setBugContact($0) }), TextField("", text: Binding(get: { model.state.bugContact }, set: { model.setBugContact($0) }),
prompt: Text(LocalizedStringKey("bug_report_contact_hint"))) prompt: Text(String(localized: L10n.Bug.reportContactHint)))
.labelsHidden() .labelsHidden()
} }
Section { Section {
Toggle(isOn: Binding(get: { model.state.bugIncludeLogs }, set: { model.setBugIncludeLogs($0) })) { Toggle(isOn: Binding(get: { model.state.bugIncludeLogs }, set: { model.setBugIncludeLogs($0) })) {
Text(LocalizedStringKey("bug_report_include_logs")) Text(String(localized: L10n.Bug.reportIncludeLogs))
} }
Button(action: { model.submitBugReport(onSuccess: onSubmitted) }) { Button(action: { model.submitBugReport(onSuccess: onSubmitted) }) {
Text(model.state.isSubmittingBugReport Text(model.state.isSubmittingBugReport
? String(localized: "bug_report_submitting") : String(localized: "bug_report_submit")) ? String(localized: L10n.Bug.reportSubmitting) : String(localized: L10n.Bug.reportSubmit))
} }
.disabled(model.state.isSubmittingBugReport) .disabled(model.state.isSubmittingBugReport)
} }

File diff suppressed because it is too large Load Diff

View File

@@ -1810,7 +1810,7 @@
} }
}, },
"approval_endpoint_id": { "approval_endpoint_id": {
"comment": "Approval prompt: shows the requesting device's ID. {arg1} = device/endpoint identifier.", "comment": "Approval prompt: shows the requesting device's ID. {deviceId} = device/endpoint identifier.",
"extractionState": "manual", "extractionState": "manual",
"localizations": { "localizations": {
"de": { "de": {
@@ -1990,7 +1990,7 @@
} }
}, },
"approval_request_body": { "approval_request_body": {
"comment": "Approval prompt body: '{arg1} wants to receive \"{arg2}\".' {arg1} = requester name, {arg2} = transfer name.", "comment": "Approval prompt body: '{receiver} wants to receive \"{transferName}\".' {receiver} = requester name, {transferName} = transfer name.",
"extractionState": "manual", "extractionState": "manual",
"localizations": { "localizations": {
"de": { "de": {
@@ -9130,7 +9130,7 @@
} }
}, },
"receive_delete_history_description": { "receive_delete_history_description": {
"comment": "Receive history: confirmation body for removing one item. {arg1} = transfer name.", "comment": "Receive history: confirmation body for removing one item. {transferName} = transfer name.",
"extractionState": "manual", "extractionState": "manual",
"localizations": { "localizations": {
"de": { "de": {
@@ -13090,7 +13090,7 @@
} }
}, },
"transfer_delete_description": { "transfer_delete_description": {
"comment": "Transfer details: confirmation body for deleting a transfer. {arg1} = transfer name.", "comment": "Transfer details: confirmation body for deleting a transfer. {transferName} = transfer name.",
"extractionState": "manual", "extractionState": "manual",
"localizations": { "localizations": {
"de": { "de": {

View File

@@ -41,7 +41,7 @@ private struct SheetChrome<Content: View>: View {
ScrollView { content().padding(.top, 4) } ScrollView { content().padding(.top, 4) }
.toolbar { .toolbar {
ToolbarItem(placement: .cancellationAction) { ToolbarItem(placement: .cancellationAction) {
Button(String(localized: "button_close"), action: onClose) Button(String(localized: L10n.Button.close), action: onClose)
} }
} }
#if os(iOS) #if os(iOS)

View File

@@ -30,7 +30,7 @@ struct StatusPill: View {
// MARK: - ProgressRow // MARK: - ProgressRow
struct ProgressRow: View { struct ProgressRow: View {
let labelKey: String let labelKey: String.LocalizationValue
let progress: Double? let progress: Double?
var detail: String? = nil var detail: String? = nil
/// Pre-resolved label; when set it overrides `labelKey`. /// Pre-resolved label; when set it overrides `labelKey`.
@@ -62,7 +62,7 @@ struct ProgressRow: View {
if let labelText { if let labelText {
Text(labelText) Text(labelText)
} else { } else {
Text(LocalizedStringKey(labelKey)) Text(String(localized: labelKey))
} }
} }
} }

View File

@@ -4,14 +4,14 @@ import Combine
/// A localizable UI string: either a catalog key or dynamic text, ported from /// A localizable UI string: either a catalog key or dynamic text, ported from
/// `UiText` in `ui/feedback/UiMessageController.kt`. /// `UiText` in `ui/feedback/UiMessageController.kt`.
enum UiText: Equatable { enum UiText: Equatable {
case resource(String) // Localizable.xcstrings key case resource(String.LocalizationValue) // Localizable.xcstrings key (use L10n.*)
case dynamic(String) case dynamic(String)
/// Resolves to display text. Keys go through the string catalog. /// Resolves to display text. Keys go through the string catalog.
func resolved() -> String { func resolved() -> String {
switch self { switch self {
case .dynamic(let value): return value case .dynamic(let value): return value
case .resource(let key): return String(localized: String.LocalizationValue(key)) case .resource(let value): return String(localized: value)
} }
} }
} }

View File

@@ -8,34 +8,34 @@ extension Error {
if let vni = self as? VnidropError { if let vni = self as? VnidropError {
switch vni { switch vni {
case .Ticket: case .Ticket:
return .resource("error_invalid_ticket") return .resource(L10n.Error.invalidTicket)
case .Permission: case .Permission:
return .resource("error_permission") return .resource(L10n.Error.permission)
case .Filesystem: case .Filesystem:
return .resource("error_filesystem") return .resource(L10n.Error.filesystem)
case .FilesystemPermission: case .FilesystemPermission:
return .resource("error_filesystem") return .resource(L10n.Error.filesystem)
case .DestinationExists: case .DestinationExists:
return .resource("error_destination_exists") return .resource(L10n.Error.destinationExists)
case .StorageFull: case .StorageFull:
return .resource("error_storage_full") return .resource(L10n.Error.storageFull)
case .Network: case .Network:
return .resource("error_network") return .resource(L10n.Error.network)
case .Transfer(let reason): case .Transfer(let reason):
return transferUiText(reason) return transferUiText(reason)
case .Repository: case .Repository:
return .resource("error_repository") return .resource(L10n.Error.repository)
case .Cancelled: case .Cancelled:
return .resource("error_generic") return .resource(L10n.Error.generic)
case .InvalidInput: case .InvalidInput:
return .resource("error_invalid_input") return .resource(L10n.Error.invalidInput)
case .Initialization(let reason): case .Initialization(let reason):
return initializationUiText(reason) return initializationUiText(reason)
case .Internal(let reason): case .Internal(let reason):
return reasonHints(reason) ?? .resource("error_generic") return reasonHints(reason) ?? .resource(L10n.Error.generic)
} }
} }
return reasonHints(technicalDetail) ?? .resource("error_generic") return reasonHints(technicalDetail) ?? .resource(L10n.Error.generic)
} }
/// True when the user intentionally backed out of a flow. /// True when the user intentionally backed out of a flow.
@@ -79,20 +79,20 @@ extension Error {
private func transferUiText(_ reason: String) -> UiText { private func transferUiText(_ reason: String) -> UiText {
let detail = reason.lowercased() let detail = reason.lowercased()
if detail.contains("refused") || detail.contains("denied") || detail.contains("not approved") { if detail.contains("refused") || detail.contains("denied") || detail.contains("not approved") {
return .resource("error_permission") return .resource(L10n.Error.permission)
} }
return .resource("error_transfer") return .resource(L10n.Error.transfer)
} }
private func initializationUiText(_ reason: String) -> UiText { private func initializationUiText(_ reason: String) -> UiText {
let detail = reason.lowercased() let detail = reason.lowercased()
if detail.contains("native") && detail.contains("library") { if detail.contains("native") && detail.contains("library") {
return .resource("error_missing_native_library") return .resource(L10n.Error.missingNativeLibrary)
} }
if detail.contains("socket") || detail.contains("bind") { if detail.contains("socket") || detail.contains("bind") {
return .resource("error_socket_bind") return .resource(L10n.Error.socketBind)
} }
return .resource("error_initialization") return .resource(L10n.Error.initialization)
} }
private func reasonHints(_ detailRaw: String) -> UiText? { private func reasonHints(_ detailRaw: String) -> UiText? {
@@ -100,50 +100,50 @@ private func reasonHints(_ detailRaw: String) -> UiText? {
if detail.isEmpty { return nil } if detail.isEmpty { return nil }
if detail.contains("still starting") || detail.contains("starting up") { if detail.contains("still starting") || detail.contains("starting up") {
return .resource("error_starting_up") return .resource(L10n.Error.startingUp)
} }
if detail.contains("empty") && (detail.contains("invitation") || detail.contains("ticket") || detail.contains("qr")) { if detail.contains("empty") && (detail.contains("invitation") || detail.contains("ticket") || detail.contains("qr")) {
return .resource("error_invitation_empty") return .resource(L10n.Error.invitationEmpty)
} }
if detail.contains("select at least one") || detail.contains("no files found") { if detail.contains("select at least one") || detail.contains("no files found") {
return .resource("error_share_empty") return .resource(L10n.Error.shareEmpty)
} }
if detail.contains("camera") { if detail.contains("camera") {
return .resource("error_camera") return .resource(L10n.Error.camera)
} }
if detail.contains("nfc") || detail.contains("ndef") if detail.contains("nfc") || detail.contains("ndef")
|| (detail.contains("read-only") && detail.contains("tag")) || (detail.contains("read-only") && detail.contains("tag"))
|| detail.contains("tag is too small") || detail.contains("no nfc tag") { || detail.contains("tag is too small") || detail.contains("no nfc tag") {
return .resource("error_nfc") return .resource(L10n.Error.nfc)
} }
if detail.contains("native") && detail.contains("library") { if detail.contains("native") && detail.contains("library") {
return .resource("error_missing_native_library") return .resource(L10n.Error.missingNativeLibrary)
} }
if detail.contains("socket") || detail.contains("bind") { if detail.contains("socket") || detail.contains("bind") {
return .resource("error_socket_bind") return .resource(L10n.Error.socketBind)
} }
if detail.contains("device information") || detail.contains("device info") { if detail.contains("device information") || detail.contains("device info") {
return .resource("error_device_info") return .resource(L10n.Error.deviceInfo)
} }
if detail.contains("refused") || detail.contains("denied") || detail.contains("permission") if detail.contains("refused") || detail.contains("denied") || detail.contains("permission")
|| detail.contains("not approved") || detail.contains("waiting for approval") { || detail.contains("not approved") || detail.contains("waiting for approval") {
return .resource("error_permission") return .resource(L10n.Error.permission)
} }
if detail.contains("invalid ticket") || detail.contains("ticket error") if detail.contains("invalid ticket") || detail.contains("ticket error")
|| detail.contains("could not be read") || detail.contains("malformed") || detail.contains("could not be read") || detail.contains("malformed")
|| detail.contains("invitation could not be opened") { || detail.contains("invitation could not be opened") {
return .resource("error_invalid_ticket") return .resource(L10n.Error.invalidTicket)
} }
if detail.contains("selected") if detail.contains("selected")
&& (detail.contains("file") || detail.contains("folder") || detail.contains("document") || detail.contains("open")) { && (detail.contains("file") || detail.contains("folder") || detail.contains("document") || detail.contains("open")) {
return .resource("error_selection_failed") return .resource(L10n.Error.selectionFailed)
} }
if detail.contains("could not open the selected") || detail.contains("could not open selected") { if detail.contains("could not open the selected") || detail.contains("could not open selected") {
return .resource("error_selection_failed") return .resource(L10n.Error.selectionFailed)
} }
if detail.contains("document picker") || detail.contains("folder picker") || detail.contains("file descriptor") if detail.contains("document picker") || detail.contains("folder picker") || detail.contains("file descriptor")
|| detail.contains("view controller") { || detail.contains("view controller") {
return .resource("error_selection_failed") return .resource(L10n.Error.selectionFailed)
} }
return nil return nil
} }

View File

@@ -8,11 +8,11 @@ enum AppDestination: String, CaseIterable, Identifiable {
var id: String { rawValue } var id: String { rawValue }
var labelKey: String { var labelKey: String.LocalizationValue {
switch self { switch self {
case .send: return "nav_send" case .send: return L10n.Nav.send
case .receive: return "nav_receive" case .receive: return L10n.Nav.receive
case .settings: return "nav_settings" case .settings: return L10n.Nav.settings
} }
} }

View File

@@ -5,8 +5,11 @@
*/ */
import { mkdirSync } from "node:fs"; import { mkdirSync } from "node:fs";
import { join } from "node:path"; import { join } from "node:path";
import { mkdir } from "node:fs/promises";
import { dirname } from "node:path";
import { import {
APPLE_INFO_PLIST, APPLE_INFO_PLIST,
APPLE_L10N_SWIFT,
APPLE_XCSTRINGS, APPLE_XCSTRINGS,
kmpValuesDir, kmpValuesDir,
KMP_RESOURCES, KMP_RESOURCES,
@@ -14,6 +17,7 @@ import {
} from "../config"; } from "../config";
import { renderAndroid, type ParsedAndroid } from "../lib/android-xml"; import { renderAndroid, type ParsedAndroid } from "../lib/android-xml";
import { fromCanonical, type Flavor } from "../lib/placeholders"; import { fromCanonical, type Flavor } from "../lib/placeholders";
import { renderSwiftAccessors } from "../lib/swift-accessors";
import { renderXcstrings, type XcCatalog, type XcEntry } from "../lib/xcstrings"; import { renderXcstrings, type XcCatalog, type XcEntry } from "../lib/xcstrings";
import { targetsOf, type StringEntry, type StringsFile } from "../types"; import { targetsOf, type StringEntry, type StringsFile } from "../types";
@@ -111,6 +115,10 @@ export async function generate() {
await Bun.write(APPLE_XCSTRINGS, renderXcstrings(buildXcstrings(doc))); await Bun.write(APPLE_XCSTRINGS, renderXcstrings(buildXcstrings(doc)));
console.log(`Wrote ${APPLE_XCSTRINGS}`); console.log(`Wrote ${APPLE_XCSTRINGS}`);
await mkdir(dirname(APPLE_L10N_SWIFT), { recursive: true });
await Bun.write(APPLE_L10N_SWIFT, renderSwiftAccessors(doc));
console.log(`Wrote ${APPLE_L10N_SWIFT}`);
await syncInfoPlistLocalizations(doc.supportedLanguages); await syncInfoPlistLocalizations(doc.supportedLanguages);
for (const lang of doc.supportedLanguages) { for (const lang of doc.supportedLanguages) {

View File

@@ -18,6 +18,12 @@ export const APPLE_INFO_PLIST = join(
"apple/VniDrop/Resources/Info.plist", "apple/VniDrop/Resources/Info.plist",
); );
/** Generated Swift accessors (`L10n`) for compile-time-checked catalog keys. */
export const APPLE_L10N_SWIFT = join(
REPO_ROOT,
"apple/VniDrop/Generated/L10n.swift",
);
/** KMP / Compose Multiplatform resources root; one values[-lang]/strings.xml per language. */ /** KMP / Compose Multiplatform resources root; one values[-lang]/strings.xml per language. */
export const KMP_RESOURCES = join( export const KMP_RESOURCES = join(
REPO_ROOT, REPO_ROOT,

View File

@@ -0,0 +1,139 @@
/**
* Swift accessor generator.
*
* Emits a compile-time-checked stand-in for each localization key so Apple call
* sites stop passing raw string literals. The runtime path is unchanged: plain
* keys become `String.LocalizationValue` constants used with `String(localized:)`
* exactly as before, and Apple's catalog lookup still does 100% of the work.
*
* Keys group by their first `_`-delimited segment (`button_…` -> `enum Button`);
* the remainder becomes a camelCase member. Plain keys are `static let`
* constants; keys with args become `static func` with typed, named parameters
* derived from the entry's `args` metadata.
*/
import { targetsOf, type Arg, type StringEntry, type StringsFile } from "../types";
const HEADER = `// Generated by localization/ (bun run src/cli.ts generate). Do not edit.
// Keys resolve through Apple's String Catalog exactly as a literal would; these
// accessors only make the key compile-time-checked. If a runtime language
// switcher (live \`.environment(\\.locale)\`) is ever added, switch the plain
// \`static let\` constants to computed \`static var\` so the locale is not frozen.
import Foundation
`;
/** Swift type for a localization arg. */
function swiftType(arg: Arg): string {
switch (arg.type) {
case "int":
return "Int";
case "double":
return "Double";
case "string":
return "String";
}
}
/** `create_new_transfer` -> `createNewTransfer`. */
function camel(segment: string): string {
const parts = segment.split("_").filter(Boolean);
return parts
.map((p, i) => (i === 0 ? p : p.charAt(0).toUpperCase() + p.slice(1)))
.join("");
}
/** `button` -> `Button`. */
function pascal(segment: string): string {
const c = camel(segment);
return c.charAt(0).toUpperCase() + c.slice(1);
}
/** A key is groupable only when it starts with an identifier-safe segment. */
function isGroupableKey(key: string): boolean {
return /^[A-Za-z][A-Za-z0-9_]*$/.test(key);
}
/** Collapse whitespace/newlines so a value fits on one doc-comment line. */
function oneLine(text: string): string {
return text.replace(/\s*\n\s*/g, " ").trim();
}
/** The displayable text for a language (plural shows its `other` form). */
function translationText(entry: StringEntry, lang: string): string | undefined {
return entry.translations?.[lang] ?? entry.plural?.[lang]?.other;
}
/**
* A rich Quick Help block: source-language text as the abstract, then the raw
* key, the context note, and every translation. Quick Help renders the Markdown.
*/
function docComment(key: string, entry: StringEntry, doc: StringsFile): string {
const lines: string[] = [];
const source = translationText(entry, doc.sourceLanguage);
if (source) lines.push(oneLine(source), "");
lines.push(`Key: \`${key}\``);
if (entry.context) lines.push(`Context: ${oneLine(entry.context)}`);
lines.push("");
for (const lang of doc.supportedLanguages) {
const value = translationText(entry, lang);
if (value !== undefined) lines.push(`- ${lang}: ${oneLine(value)}`);
}
return lines
.map((line) => (line ? ` /// ${line}` : " ///"))
.join("\n");
}
function memberFor(
key: string,
member: string,
entry: StringEntry,
doc: StringsFile,
): string {
const comment = docComment(key, entry, doc);
const args = entry.args ?? [];
// Plain key: a #define-style constant. Apple resolves it via String(localized:).
if (args.length === 0 && !entry.plural) {
return `${comment}\n static let ${member}: String.LocalizationValue = "${key}"`;
}
// Arg'd (or plural) key: a typed, named function that applies the arguments
// through the same String(format: String(localized:)) path used before.
const params = args.map((a) => `${a.name}: ${swiftType(a)}`).join(", ");
const callArgs = args.map((a) => a.name).join(", ");
// The positional format string lives in the catalog; look it up by key and
// apply the args exactly as the hand-written call sites did.
return `${comment}\n static func ${member}(${params}) -> String {\n String(format: String(localized: "${key}"), ${callArgs})\n }`;
}
export function renderSwiftAccessors(doc: StringsFile): string {
// group segment -> rendered members
const groups = new Map<string, string[]>();
for (const [key, entry] of Object.entries(doc.strings)) {
if (!targetsOf(entry).includes("apple")) continue;
if (!isGroupableKey(key)) continue; // skips legacy `%@` literal keys
const underscore = key.indexOf("_");
const groupSeg = underscore === -1 ? key : key.slice(0, underscore);
const memberSeg = underscore === -1 ? key : key.slice(underscore + 1);
const group = pascal(groupSeg);
const member = camel(memberSeg) || camel(groupSeg);
const list = groups.get(group) ?? [];
list.push(memberFor(key, member, entry, doc));
groups.set(group, list);
}
const body = [...groups.keys()]
.sort()
.map((group) => {
const members = groups.get(group)!.join("\n");
return ` enum ${group} {\n${members}\n }`;
})
.join("\n");
return `${HEADER}\nenum L10n {\n${body}\n}\n`;
}

View File

@@ -476,23 +476,23 @@
} }
}, },
"approval_endpoint_id": { "approval_endpoint_id": {
"context": "Approval prompt: shows the requesting device's ID. {arg1} = device/endpoint identifier.", "context": "Approval prompt: shows the requesting device's ID. {deviceId} = device/endpoint identifier.",
"args": [ "args": [
{ {
"name": "arg1", "name": "deviceId",
"type": "string" "type": "string"
} }
], ],
"translations": { "translations": {
"en": "Device ID: {arg1}", "en": "Device ID: {deviceId}",
"fr": "Identifiant de lappareil : {arg1}", "fr": "Identifiant de lappareil : {deviceId}",
"es": "ID del dispositivo: {arg1}", "es": "ID del dispositivo: {deviceId}",
"it": "ID dispositivo: {arg1}", "it": "ID dispositivo: {deviceId}",
"de": "Geräte-ID: {arg1}", "de": "Geräte-ID: {deviceId}",
"pt": "ID do dispositivo: {arg1}", "pt": "ID do dispositivo: {deviceId}",
"pl": "Identyfikator urządzenia: {arg1}", "pl": "Identyfikator urządzenia: {deviceId}",
"nl": "Apparaat-ID: {arg1}", "nl": "Apparaat-ID: {deviceId}",
"ru": "Идентификатор устройства: {arg1}" "ru": "Идентификатор устройства: {deviceId}"
} }
}, },
"approval_nearby_device": { "approval_nearby_device": {
@@ -530,27 +530,27 @@
} }
}, },
"approval_request_body": { "approval_request_body": {
"context": "Approval prompt body: '{arg1} wants to receive \"{arg2}\".' {arg1} = requester name, {arg2} = transfer name.", "context": "Approval prompt body: '{receiver} wants to receive \"{transferName}\".' {receiver} = requester name, {transferName} = transfer name.",
"args": [ "args": [
{ {
"name": "arg1", "name": "receiver",
"type": "string" "type": "string"
}, },
{ {
"name": "arg2", "name": "transferName",
"type": "string" "type": "string"
} }
], ],
"translations": { "translations": {
"en": "{arg1} wants to receive “{arg2}”.", "en": "{receiver} wants to receive “{transferName}”.",
"fr": "{arg1} souhaite recevoir « {arg2} ».", "fr": "{receiver} souhaite recevoir « {transferName} ».",
"es": "{arg1} quiere recibir «{arg2}».", "es": "{receiver} quiere recibir «{transferName}».",
"it": "{arg1} vuole ricevere «{arg2}».", "it": "{receiver} vuole ricevere «{transferName}».",
"de": "{arg1} möchte „{arg2}“ empfangen.", "de": "{receiver} möchte „{transferName}“ empfangen.",
"pt": "{arg1} quer receber «{arg2}».", "pt": "{receiver} quer receber «{transferName}».",
"pl": "{arg1} chce odebrać „{arg2}”.", "pl": "{receiver} chce odebrać „{transferName}”.",
"nl": "{arg1} wil {arg2} ontvangen.", "nl": "{receiver} wil {transferName} ontvangen.",
"ru": "{arg1} хочет получить «{arg2}»." "ru": "{receiver} хочет получить «{transferName}»."
} }
}, },
"battery_level_title": { "battery_level_title": {
@@ -2212,23 +2212,23 @@
} }
}, },
"receive_delete_history_description": { "receive_delete_history_description": {
"context": "Receive history: confirmation body for removing one item. {arg1} = transfer name.", "context": "Receive history: confirmation body for removing one item. {transferName} = transfer name.",
"args": [ "args": [
{ {
"name": "arg1", "name": "transferName",
"type": "string" "type": "string"
} }
], ],
"translations": { "translations": {
"en": "“{arg1}” will be removed from VniDrops history. The downloaded file will remain on this device.", "en": "“{transferName}” will be removed from VniDrops history. The downloaded file will remain on this device.",
"fr": "« {arg1} » sera retiré de lhistorique de VniDrop. Le fichier téléchargé restera sur cet appareil.", "fr": "« {transferName} » sera retiré de lhistorique de VniDrop. Le fichier téléchargé restera sur cet appareil.",
"es": "«{arg1}» se eliminará del historial de VniDrop. El archivo descargado permanecerá en este dispositivo.", "es": "«{transferName}» se eliminará del historial de VniDrop. El archivo descargado permanecerá en este dispositivo.",
"it": "«{arg1}» verrà rimosso dalla cronologia di VniDrop. Il file scaricato rimarrà su questo dispositivo.", "it": "«{transferName}» verrà rimosso dalla cronologia di VniDrop. Il file scaricato rimarrà su questo dispositivo.",
"de": "„{arg1}“ wird aus dem Verlauf von VniDrop entfernt. Die heruntergeladene Datei verbleibt auf diesem Gerät.", "de": "„{transferName}“ wird aus dem Verlauf von VniDrop entfernt. Die heruntergeladene Datei verbleibt auf diesem Gerät.",
"pt": "«{arg1}» será removido do histórico do VniDrop. O ficheiro descarregado permanecerá neste dispositivo.", "pt": "«{transferName}» será removido do histórico do VniDrop. O ficheiro descarregado permanecerá neste dispositivo.",
"pl": "„{arg1}” zostanie usunięty z historii VniDrop. Pobrany plik pozostanie na tym urządzeniu.", "pl": "„{transferName}” zostanie usunięty z historii VniDrop. Pobrany plik pozostanie na tym urządzeniu.",
"nl": "{arg1} wordt uit de geschiedenis van VniDrop verwijderd. Het gedownloade bestand blijft op dit apparaat.", "nl": "{transferName} wordt uit de geschiedenis van VniDrop verwijderd. Het gedownloade bestand blijft op dit apparaat.",
"ru": "«{arg1}» будет удалён из истории VniDrop. Загруженный файл останется на этом устройстве." "ru": "«{transferName}» будет удалён из истории VniDrop. Загруженный файл останется на этом устройстве."
} }
}, },
"receive_delete_history_item": { "receive_delete_history_item": {
@@ -3148,23 +3148,23 @@
} }
}, },
"transfer_delete_description": { "transfer_delete_description": {
"context": "Transfer details: confirmation body for deleting a transfer. {arg1} = transfer name.", "context": "Transfer details: confirmation body for deleting a transfer. {transferName} = transfer name.",
"args": [ "args": [
{ {
"name": "arg1", "name": "transferName",
"type": "string" "type": "string"
} }
], ],
"translations": { "translations": {
"en": "“{arg1}” will stop being shared and its transfer history will be removed from this device.", "en": "“{transferName}” will stop being shared and its transfer history will be removed from this device.",
"fr": "« {arg1} » cessera dêtre partagé et son historique de transfert sera retiré de cet appareil.", "fr": "« {transferName} » cessera dêtre partagé et son historique de transfert sera retiré de cet appareil.",
"es": "«{arg1}» dejará de compartirse y su historial de transferencia se eliminará de este dispositivo.", "es": "«{transferName}» dejará de compartirse y su historial de transferencia se eliminará de este dispositivo.",
"it": "«{arg1}» non verrà più condiviso e la sua cronologia di trasferimento verrà rimossa da questo dispositivo.", "it": "«{transferName}» non verrà più condiviso e la sua cronologia di trasferimento verrà rimossa da questo dispositivo.",
"de": "„{arg1}“ wird nicht mehr geteilt und sein Übertragungsverlauf wird von diesem Gerät entfernt.", "de": "„{transferName}“ wird nicht mehr geteilt und sein Übertragungsverlauf wird von diesem Gerät entfernt.",
"pt": "«{arg1}» deixará de ser partilhado e o seu histórico de transferência será removido deste dispositivo.", "pt": "«{transferName}» deixará de ser partilhado e o seu histórico de transferência será removido deste dispositivo.",
"pl": "„{arg1}” przestanie być udostępniany, a jego historia transferu zostanie usunięta z tego urządzenia.", "pl": "„{transferName}” przestanie być udostępniany, a jego historia transferu zostanie usunięta z tego urządzenia.",
"nl": "{arg1} wordt niet meer gedeeld en de overdrachtsgeschiedenis wordt van dit apparaat verwijderd.", "nl": "{transferName} wordt niet meer gedeeld en de overdrachtsgeschiedenis wordt van dit apparaat verwijderd.",
"ru": "Общий доступ к «{arg1}» будет остановлен, а история передачи будет удалена с этого устройства." "ru": "Общий доступ к «{transferName}» будет остановлен, а история передачи будет удалена с этого устройства."
} }
}, },
"transfer_delete_title": { "transfer_delete_title": {