From 3ae246d0302d3ce0ee7d0d4794c933eb42723927 Mon Sep 17 00:00:00 2001 From: Johannes Millan Date: Sat, 25 Apr 2026 22:39:22 +0200 Subject: [PATCH] Feat/issue 7362 9d46d3 (#7363) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * test(e2e): open attachment dialog via detail panel after #7314 The attach-dialog entry point moved out of the task context menu in PR #7314 and now lives in the detail panel. Update the WebDAV sync attachment test to use openTaskDetailPanel() and click the attachment input-item instead of right-clicking and looking for an "Attach" menu item that no longer exists. * refactor(tasks): drop dead addAttachment from task context menu Leftover from #7314, which moved the attach dialog into the detail panel. The method, its TaskAttachmentService injection, and the DialogEditTaskAttachmentComponent import are unreachable from the template. * fix(api): reject inherited fields when creating subtask via REST POST /tasks with parentId silently dropped any supplied projectId/tagIds (the reducer forces tagIds=[] and projectId=parent.projectId), so callers got 201 with values different from what they sent. Reject the request with 400 UNSUPPORTED_FIELD instead, symmetric with how subTaskIds and parentId-on-PATCH are handled. * refactor(simple-counter): inline countdown wrapper, document set invariant Inline the single-call-site `_hasStartedRepeatedCountdown` private wrapper. Promote the `setCountdownRemaining` invariant note to JSDoc so it surfaces in IDE tooltips at every call site — paused-display is gated by `hasStartedCountdown`, and writing through `setCountdownRemaining` without a prior `startCountdown` call would silently leave the value invisible. * ci(plugins): run unit tests when plugin code changes New workflow runs each plugin's `npm test` in a parallel matrix when its directory or a shared package (plugin-api, vite-plugin) changes on a PR. Detects per-plugin changes via three-dot `git diff` against the PR base. * fix(sync): break iOS WebDAV conflict-dialog loop (#7339) Two compounding bugs trapped iOS WebDAV users in a per-minute conflict dialog that no button could resolve: 1. FileBasedSyncAdapter's snapshotReplacement heuristic re-fires gapDetected on every sync from a non-writing client (clientId \!= excludeClient is true forever), so the download keeps coming back with snapshotState and OperationLogSyncService keeps throwing LocalDataConflictError despite the local clock already dominating the remote snapshot. Skip hydration and conflict when compareVectorClocks(local, remote) is EQUAL or GREATER_THAN, gated on both clocks being non-empty so a fresh client still hydrates a legacy/clockless snapshot. 2. SyncWrapperService._openConflictDialog$ filtered undefined out of the afterClosed() stream, so a programmatic close (iOS WebView lifecycle, re-entry) collapsed the observable and firstValueFrom threw EmptyError — the user's Use Local/Use Remote/Cancel click never reached the resolution branches. Drop the filter so undefined flows through to the existing cancellation path. The dominate-skip deliberately does NOT append result.newOps to the op log: VectorClockService.getEntityFrontier is last-write-wins by seq, and writing historical remote ops at the current tail would regress per-entity frontiers and let future LWW resolution overwrite local data. Trade-off documented inline. Adds an adapter-level integration reproducer that asserts gapDetected re-fires forever for a non-writing client (the upstream loop trigger), a 3-client WebDAV e2e that reproduces the loop end-to-end against a real provider, plus service-level tests for the dominate-skip, the empty-clock guard, the concurrent-clock conservative path, and consecutive-sync loop prevention. * fix(sync): improve Dropbox auth dialog UX on sandboxed Linux (#7139) The "Get Authorization Code" button silently failed on Flatpak because shell.openExternal rejects without renderer feedback when the org.freedesktop.portal.Desktop talk-name isn't granted. After the user gave up and reopened the dialog, the second attempt failed again with `invalid_grant: invalid code verifier` because each call to Dropbox.getAuthHelper() generated a fresh PKCE verifier that no longer matched the originally-shown URL's challenge. Three changes: - Cache the in-flight PKCE Promise on the Dropbox provider so concurrent callers and consecutive dialog opens share one verifier+URL pair. Cleared on successful exchange, on clearAuthCredentials(), and on a rejected generation (so a one-time crypto failure doesn't poison the session). Five regression tests cover reuse, success-clear, explicit clear, concurrent calls, and rejection-recovery. - Render the auth URL as user-selectable text under a
disclosure. Escape hatch when both shell.openExternal and the clipboard portal are denied — the user can triple-click to select and Ctrl+C the URL into a manually-opened browser. Adds D_AUTH_CODE.MANUAL_URL_HINT translation key. - Pipe shell.openExternal rejections through errorHandlerWithFrontendInform so the existing IPC.ERROR snack channel surfaces a "Could not open the link in your browser" message instead of swallowing the failure to electron-log. Wrapped in a try/catch since errorHandlerWithFrontendInform throws synchronously if the renderer isn't ready. The Flathub manifest also needs --talk-name=org.freedesktop.portal.Desktop and --socket=wayland to fully fix the user-reported issue, but that change lives in the flathub repo. * refactor(sync): rename dialog-sync-initial-cfg to dialog-sync-cfg Pure rename — no behavior change. The component is the canonical sync config dialog, used both for first-time setup and editing. The "Initial" qualifier was misleading once it became the only sync-config surface (see #7362). * refactor(sync): consolidate sync actions into the sync dialog Move Re-authenticate, Force overwrite, and Restore from history into DialogSyncCfgComponent so the dialog is the canonical surface for sync configuration and management. - Re-authenticate (OAuth providers, currently Dropbox) shown inline when the active provider has getAuthHelper() and is already authed. Bypasses the dirty-form gate so credentials can refresh without losing in-progress edits. - Force overwrite and Restore from history live in a new "Advanced" section gated on isWasEnabled() (existing config) and disabled when the form is dirty with a "Save changes first" tooltip. Restore stays SuperSync-only. - Force overwrite reuses the existing native confirm in SyncWrapperService.forceUpload() — no extra confirmation dialog to avoid double-confirm on the other 5 internal callers. The legacy buttons on the settings page are removed in a follow-up commit. Refs #7362 * refactor(sync): move WebDAV Test Connection button into the sync dialog Test Connection was previously injected into the inline sync form on the settings page. It needs to live wherever the sync form is rendered. The next commit removes the inline form, so move the injection into DialogSyncCfgComponent first. No user-visible change: the button still appears in the WebDAV section of the sync form, just sourced from the dialog component now. * refactor(config-page): replace inline sync form with status row + buttons The Sync & Backup tab now hosts a compact status surface, not a full form clone: - When sync is disabled or unconfigured: empty-state hint + "Set up sync" primary button. - When configured: provider name, optional "Authentication required" pill (OAuth providers) and "Encrypted" pill, then "Sync now" primary button + "Configure" secondary button. The dialog is the canonical sync config surface — reachable from this tab, the header sync icon (right-click / long-press), or SyncWrapperService when first-time setup is needed. Force overwrite and Restore from history live inside the dialog now (see prior commit). Removes _buildSyncFormConfig (~250 lines of formly button injection), the empty authStatus placeholder field in SYNC_FORM, and the unused tour-syncSection class. Refs #7362 * refactor(sync): consolidate BTN_FORCE_OVERWRITE translation key The SUPER_SYNC.BTN_FORCE_OVERWRITE key was a duplicate with no consumers — its English copy ("Force Overwrite Server") even drifted from the canonical F.SYNC.S.BTN_FORCE_OVERWRITE ("Force Overwrite"). The third occurrence under D_ENTER_PASSWORD ("Use Local Data") stays — that's a different conflict-resolution action, not a duplicate. Refs #7362 * refactor(sync): simplify sync dialog — collapse advanced fields, kebab menu The previous "Advanced" zone (hr + heading + hint + button stack) plus always-visible interval/manual-only/compression toggles made the dialog visually noisy. Two changes: - Move syncInterval and isManualSyncOnly into the existing "Advanced Config" collapsible alongside compression. The collapsible is hidden for SuperSync (which uses fixed settings) — most users never need to expand it. - Move Force overwrite + Restore from history out of the dialog body into a kebab (more_vert) menu in the dialog title row. They act on saved config — the kebab placement makes that scope clear and removes the dirty-form gate / "Save changes first" ambiguity. The kebab is hidden during first-time setup (gated on isWasEnabled). The Re-authenticate button stays inline as before. Drops three translation keys added in the prior commit (ADVANCED, ADVANCED_HINT, SAVE_FIRST_HINT) — no longer referenced. Refs #7362 * fix(sync): drop primary color from Cancel button in sync dialog Cancel is a secondary action; only the affirmative button (Save) should carry the primary color. * fix(sync): clarify Dropbox info text for the new dialog flow The previous copy said "Click the button below to authenticate" — but in the consolidated dialog there is no inline Authenticate button for first-time setup; OAuth runs as part of Save. Make the copy describe the actual flow instead of pointing at a button that no longer exists. * refactor(sync): move Force overwrite + Restore into the Advanced collapsible The kebab menu introduced earlier hid Force overwrite and Restore from history behind a small icon and required users to know that "more_vert" in the dialog title contained sync actions. Fold them into the existing top-level collapsible instead — the same one that already hosts sync interval, manual-only, and compression toggles. - Rename the collapsible's label from "Advanced Config" to "Advanced" via a new sync-specific translation key (the global ADVANCED_CFG key is shared with issue providers, so we don't touch it). - The dialog component appends Force overwrite (warn) and Restore from history (SuperSync only) to the collapsible's fieldGroup in edit mode. First-time setup keeps the original SuperSync hide so the collapsible never appears empty. Re-authenticate stays as an inline button below the form because its visibility depends on an async provider.isReady() check that doesn't fit Formly's sync hideExpression. Refs #7362 * refactor(sync): single Advanced collapsible per provider, all actions inside Each provider now has exactly one "Advanced" collapsible: - non-SuperSync: top-level (interval, manual-only, compression, enable-encryption, plus injected Re-authenticate / Force overwrite in edit mode) - SuperSync: nested in the SuperSync section (server URL, plus injected Force overwrite / Restore from history in edit mode) The inner SuperSync collapsible's label switches from "Advanced Config" to "Advanced" so both surfaces read the same. Re-authenticate moves from a button below the form into the non-SuperSync Advanced collapsible as a Formly button gated on `syncProvider === Dropbox`. Drops the async provider.isReady() check — re-auth is shown for Dropbox in edit mode regardless, since `force=true` works for both stale-token and switching accounts. Honors the rule that no buttons sit below the Advanced collapsible inside the dialog. Refs #7362 * refactor(sync): use stroked style for all dialog buttons + add Nextcloud test - Every action button inside the sync dialog now uses btnStyle: 'stroked' for a consistent outlined appearance: Re-authenticate, Force overwrite, Restore from history, WebDAV/Nextcloud Test connection, file-based and SuperSync Enable encryption, SuperSync Get token, LocalFile folder pickers. - Force overwrite keeps btnType: 'warn' so it stays warn-coloured but as an outline rather than a filled warn button. - The conditional stroked-when-token-set toggle on Get token is dropped in favour of always-stroked. - Re-authenticate and Restore previously misused btnType: 'stroked' (a color slot) instead of btnStyle: 'stroked' (the actual style flag) — the formly-btn template ignored the unrecognised color, so they rendered as filled buttons. Fixed. - Adds a Test Connection button to the Nextcloud section, matching the WebDAV one — Nextcloud's serverUrl + userName are translated into the WebDAV-shaped baseUrl client-side before invoking WebdavApi.testConnection. Refs #7362 * refactor(sync): apply multi-review fixes — fragility, races, dedup, lifecycle Cross-validated findings from the multi-agent review: **Correctness / lifecycle** - `fields` becomes a `computed` signal of `_getFields(isWasEnabled())`, removing the manual `fields.set()` re-sync after the enabled flag flips. Single source of truth. - Reset `_tmpUpdatedCfg._isInitialSetup = false` when the dialog opens in edit mode so SuperSync encryption-warning hideExpressions stop treating returning users as first-timers. - Replace ad-hoc `Subscription` aggregator with `takeUntilDestroyed` on both subscriptions in the dialog component. **Race conditions** - `syncSettingsForm$` subscription on the settings page now goes through `switchMap` so a fresh emission cancels any in-flight `provider.isReady()` probe — late callbacks can no longer overwrite newer state. - Drop the redundant `_cd.markForCheck()` after `signal.set()` — signals integrate with OnPush automatically. - Use `??` instead of `||` when preserving `globalCfg` flags during provider switch, so an explicit `false` is honoured. **De-duplication** - Promote `NextcloudProvider._buildNextcloudBaseUrl` to a public static `buildBaseUrl()`. Dialog's `_testNextcloudConnection` now imports it rather than duplicating the URL-building logic. - New `OAUTH_SYNC_PROVIDERS` set in `provider.const.ts`. Re-auth button's hideExpression and the settings-page `requiresAuth` derivation can both reference it instead of hard-coding `Dropbox`. **Simplicity** - Settings page `syncStatus` collapses from 5 fields to 3 (providerId, needsAuth, isEncrypted) — empty state derives from `providerId === null`. - Drop redundant `D_INITIAL_CFG.ADVANCED` translation key in favour of the existing `T.G.ADVANCED_CFG`. **Security / logging** - Re-auth catch path now logs `{ name: e.name }` instead of the raw error object — log history is exportable, no auth detail leakage. Refs #7362 * refactor(sync): apply pass-2 review fixes — error paths, marker, factory Cross-validated findings from the second multi-agent review: **Correctness — keep the syncStatus stream alive on probe failure** - Wrap the inner async block in try/catch. Previously, a rejected `provider.isReady()` would propagate as an observable error through switchMap, killing the outer subscription and freezing the status pill. On failure, default to `needsAuth: true` so the row stays meaningful. - Replace the imperative `subscribe + .set` bridge with `toSignal()`. **Security — finish the redaction** - The first pass only redacted SyncLog.err; the snack `translateParams` still passed raw `e.message` into a `[innerHtml]` sink. Snack copy now uses the same `_redactErrorName(e)` helper so neither surface carries token/URL/stack details. Helper handles `null`/`undefined` thrown values explicitly. **Architecture — structural marker decouples routing from i18n** - Both Advanced collapsibles now carry `props.syncRole: 'advanced'`. The dialog routes on this stable identifier instead of the shared `T.G.ADVANCED_CFG` translation key (also used by Jira/Azure DevOps forms — a global rename would have silently broken sync). **Simplicity — collapse 5 button factories into one** - New `_actionBtn({ text, onClick, btnType?, hideExpression?, className? })` helper. Each per-action factory becomes a 3-4 line call site. ~60 lines net reduction in the dialog component. - Drop the orphan `props: { dropboxAuth: true }` marker on the Dropbox fieldGroup — its consumer (`_buildSyncFormConfig`) was deleted. Refs #7362 * refactor(sync): apply pass-3 review fixes — auth label asymmetry, dead snack param Pass-3 review surfaced two real findings on top of polish: **Correctness — non-OAuth providers no longer mislabelled "needs auth"** - The pass-2 try/catch returned `needsAuth: true` unconditionally on probe failure, which would surface "Authentication required" for WebDAV/Nextcloud/LocalFile — providers that don't have an auth helper. Now we capture `requiresAuth` BEFORE the throwable `isReady()` call and reuse it in the catch, so non-OAuth providers fall through to `needsAuth: false` even on transient failures. **Simplicity — drop the dead snack translateParams** - The `INCOMPLETE_CFG` translation key has no `{{error}}` placeholder, so the redacted error name was silently dropped by the translation pipe. Removing the param documents the actual contract: the snack shows static credentials-missing copy; the discriminator goes only to the (redacted) log. **Polish — cleaner types, tighter helper** - `_redactErrorName` collapses to two-arm helper: `Error.name` for Error instances, `'UnknownError'` for everything else. The null/undefined/typeof branches were exporting internal jargon to the user. - The `props.syncRole` marker now uses a typed `SyncCollapsibleProps extends FormlyFieldProps` interface (exported from sync-form.const) instead of a `Record` cast. Eliminates the cast at both write and read sites. Refs #7362 * refactor(sync): polish round — shareReplay, subscription cleanup, doc tightening Three deferred items from prior reviews now applied: - shareReplay({bufferSize:1, refCount:true}) on syncSettingsForm$. The config-page subscribes long-term and the dialog re-subscribes per open; previously the no-provider branch re-fetched the sync-config-default-override.json asset on every fresh subscription. Cold-start cost is now amortised across both consumers. - Drop the manual Subscription aggregator on ConfigPageComponent. The remaining cfg$ + queryParams subscriptions now use takeUntilDestroyed(this._destroyRef); ngOnDestroy + OnDestroy go away. - Tighten dialog _isInitialSetup handling. Pass-3 review noted the pre-set + Object.assign pattern reads as if order matters when it doesn't. Move the flag into the spread payload so the intent is obvious at the call site, and use \!v.isEnabled directly so the semantics are explicit (true ⇔ first-time setup). - JSDoc on forceOverwrite() documenting why no Material confirm is added — SyncWrapperService.forceUpload already gates the action with a native confirmDialog, and that gate also serves the 5 internal snackbar callers (LockPresentError / EmptyRemoteBody / JsonParse / LegacySyncFormatDetected / retry). Wrapping here would double-confirm. Refs #7362 * refactor(sync): pass-4 polish — refCount:false, widen updateTmpCfg, trim docs Cross-validated findings from the fourth review pass: - shareReplay flips to refCount:false. Pass-4 reviewer noted that refCount:true only deduplicated the rare case where the dialog opens *while the settings page is mounted*. The far more common path — header-icon → dialog with no settings page open — saw the dialog become the sole subscriber, complete via .pipe(first()), and drop refCount to 0, so the next open re-fetched the JSON default-override anyway. With refCount:false the cached value is retained for the lifetime of SyncConfigService, matching the comment's stated intent at negligible memory cost. - updateTmpCfg signature widens to `SyncConfig & { _isInitialSetup?: boolean }`. Drops the call-site cast (a code smell that pretended the type was wider than it was) and documents that _isInitialSetup is a real, expected payload field. - Trim the misleading comment around `_isInitialSetup: \!v.isEnabled`. The "Spread last so Object.assign honours this" line wasn't true — it's an object literal property, not a spread. New comment states the actual semantics: first-time setup ⇔ sync was previously disabled. - Trim forceOverwrite() JSDoc from 6 lines to 2 — same content, matches the project's preference for terse method comments. Refs #7362 --- e2e/pages/supersync.page.ts | 4 +- .../main-header/main-header.component.ts | 6 +- .../config/form-cfgs/sync-form.const.ts | 98 ++-- .../dialog-sync-cfg.component.html} | 2 - .../dialog-sync-cfg.component.scss} | 0 .../dialog-sync-cfg.component.spec.ts} | 26 +- .../dialog-sync-cfg.component.ts | 510 ++++++++++++++++++ .../dialog-sync-initial-cfg.component.ts | 249 --------- src/app/imex/sync/sync-config.service.ts | 7 +- src/app/imex/sync/sync-wrapper.service.ts | 12 +- .../file-based/webdav/nextcloud.ts | 4 +- .../op-log/sync-providers/provider.const.ts | 9 + .../config-page/config-page.component.html | 62 ++- .../config-page/config-page.component.scss | 57 ++ .../config-page/config-page.component.spec.ts | 95 +--- .../config-page/config-page.component.ts | 376 ++----------- src/app/t.const.ts | 8 +- src/assets/i18n/en.json | 10 +- 18 files changed, 816 insertions(+), 719 deletions(-) rename src/app/imex/sync/{dialog-sync-initial-cfg/dialog-sync-initial-cfg.component.html => dialog-sync-cfg/dialog-sync-cfg.component.html} (89%) rename src/app/imex/sync/{dialog-sync-initial-cfg/dialog-sync-initial-cfg.component.scss => dialog-sync-cfg/dialog-sync-cfg.component.scss} (100%) rename src/app/imex/sync/{dialog-sync-initial-cfg/dialog-sync-initial-cfg.component.spec.ts => dialog-sync-cfg/dialog-sync-cfg.component.spec.ts} (89%) create mode 100644 src/app/imex/sync/dialog-sync-cfg/dialog-sync-cfg.component.ts delete mode 100644 src/app/imex/sync/dialog-sync-initial-cfg/dialog-sync-initial-cfg.component.ts diff --git a/e2e/pages/supersync.page.ts b/e2e/pages/supersync.page.ts index 52a60276d8..a28d70538e 100644 --- a/e2e/pages/supersync.page.ts +++ b/e2e/pages/supersync.page.ts @@ -331,7 +331,7 @@ export class SuperSyncPage extends BasePage { await this.page.waitForTimeout(1000); // Define locators for dialogs we might see - const configDialog = this.page.locator('dialog-sync-initial-cfg'); + const configDialog = this.page.locator('dialog-sync-cfg'); const passwordDialog = this.page.locator('dialog-enter-encryption-password'); const enableEncryptionDialog = this.page.locator('dialog-enable-encryption'); @@ -903,7 +903,7 @@ export class SuperSyncPage extends BasePage { } // Client B: legacy password dialog (dialog-enter-encryption-password vs - // dialog-sync-initial-cfg password prompt) + // dialog-sync-cfg password prompt) const legacyPwVisible = await passwordDialog.isVisible().catch(() => false); if (legacyPwVisible) { console.log('[SuperSyncPage] Password dialog — entering password'); diff --git a/src/app/core-ui/main-header/main-header.component.ts b/src/app/core-ui/main-header/main-header.component.ts index 2c78b835e3..1cbd4473b1 100644 --- a/src/app/core-ui/main-header/main-header.component.ts +++ b/src/app/core-ui/main-header/main-header.component.ts @@ -222,9 +222,9 @@ export class MainHeaderComponent implements OnDestroy { if (this.dialogSyncCfgRef) { return; } - const { DialogSyncInitialCfgComponent } = - await import('../../imex/sync/dialog-sync-initial-cfg/dialog-sync-initial-cfg.component'); - this.dialogSyncCfgRef = this.matDialog.open(DialogSyncInitialCfgComponent); + const { DialogSyncCfgComponent } = + await import('../../imex/sync/dialog-sync-cfg/dialog-sync-cfg.component'); + this.dialogSyncCfgRef = this.matDialog.open(DialogSyncCfgComponent); this._subs.add( this.dialogSyncCfgRef.afterClosed().subscribe(() => { this.dialogSyncCfgRef = null; diff --git a/src/app/features/config/form-cfgs/sync-form.const.ts b/src/app/features/config/form-cfgs/sync-form.const.ts index 6010db703c..402c0eaee7 100644 --- a/src/app/features/config/form-cfgs/sync-form.const.ts +++ b/src/app/features/config/form-cfgs/sync-form.const.ts @@ -8,7 +8,16 @@ import { loadSyncProviders, LocalFileSyncPicker, } from '../../../op-log/sync-providers/sync-providers.factory'; -import { FormlyFieldConfig } from '@ngx-formly/core'; +import { FormlyFieldConfig, FormlyFieldProps } from '@ngx-formly/core'; + +/** + * Stable structural marker on the "Advanced" collapsibles so the dialog + * component can route action-button injection without depending on the + * (globally shared) translation key in `props.label`. + */ +export interface SyncCollapsibleProps extends FormlyFieldProps { + syncRole?: 'advanced'; +} import { IS_NATIVE_PLATFORM } from '../../../util/is-native-platform'; import { SUPER_SYNC_DEFAULT_BASE_URL } from '../../../op-log/sync-providers/super-sync/super-sync.model'; import { @@ -168,6 +177,7 @@ export const SYNC_FORM: ConfigFormSection = { key: 'syncFolderPath', templateOptions: { text: T.F.SYNC.FORM.LOCAL_FILE.L_SYNC_FOLDER_PATH, + btnStyle: 'stroked', onClick: async () => { const providers = await loadSyncProviders(); const localProvider = providers.find( @@ -203,6 +213,7 @@ export const SYNC_FORM: ConfigFormSection = { key: 'safFolderUri', templateOptions: { text: T.F.SYNC.FORM.LOCAL_FILE.L_SYNC_FOLDER_PATH, + btnStyle: 'stroked', onClick: async () => { // NOTE: this actually sets the value in the model const providers = await loadSyncProviders(); @@ -309,8 +320,6 @@ export const SYNC_FORM: ConfigFormSection = { hideExpression: (m, v, field) => field?.parent?.model.syncProvider !== SyncProviderId.Dropbox, resetOnHide: false, - // Custom marker for identifying this field group in config-page.component.ts - props: { dropboxAuth: true } as any, fieldGroup: [ { type: 'tpl', @@ -319,49 +328,9 @@ export const SYNC_FORM: ConfigFormSection = { text: T.F.SYNC.FORM.DROPBOX.INFO_TEXT, }, }, - { - type: 'tpl', - key: 'authStatus', - className: 'auth-status-indicator', - templateOptions: { - tag: 'p', - // Text will be set dynamically in config-page.component.ts - text: '', - }, - }, - // Authentication button will be added programmatically in config-page.component.ts ], }, - { - key: 'syncInterval', - type: 'duration', - // NOTE: we don't hide because model updates don't seem to work properly for this - // hideExpression: ((model: DropboxSyncConfig) => !model.accessToken), - // Hide for SuperSync (uses fixed interval) and when manual sync only is enabled - hideExpression: (m, v, field) => - field?.parent?.model.syncProvider === SyncProviderId.SuperSync || - field?.parent?.model.isManualSyncOnly === true, - resetOnHide: true, - templateOptions: { - required: true, - isAllowSeconds: true, - label: T.F.SYNC.FORM.L_SYNC_INTERVAL, - description: T.G.DURATION_DESCRIPTION, - }, - }, - { - key: 'isManualSyncOnly', - type: 'checkbox', - // Only show for file-based providers (Dropbox, WebDAV, LocalFile) - hideExpression: (m, v, field) => - field?.parent?.model.syncProvider === SyncProviderId.SuperSync || - field?.parent?.model.syncProvider === null, - templateOptions: { - label: T.F.SYNC.FORM.L_MANUAL_SYNC_ONLY, - }, - }, - // Encryption status box - shown when encryption is enabled (for any provider) { hideExpression: (m: any, v: any, field?: FormlyFieldConfig) => @@ -423,13 +392,40 @@ export const SYNC_FORM: ConfigFormSection = { }, // COMMON SETTINGS - // Hide for SuperSync - uses fixed settings (no compression config, encryption handled separately) + // Hide for SuperSync during first-time setup (uses fixed settings; no buttons to host). + // The dialog component drops this hide in edit mode and appends action buttons. { type: 'collapsible', hideExpression: (m, v, field) => field?.parent?.model.syncProvider === SyncProviderId.SuperSync, - props: { label: T.G.ADVANCED_CFG }, + // syncRole is a stable structural marker the dialog routes on, so a + // future global rename of T.G.ADVANCED_CFG cannot silently break it. + props: { label: T.G.ADVANCED_CFG, syncRole: 'advanced' } as SyncCollapsibleProps, fieldGroup: [ + { + key: 'syncInterval', + type: 'duration', + // Hide when manual sync only is enabled (parent.parent reaches the form root) + hideExpression: (m, v, field) => + field?.parent?.parent?.model?.isManualSyncOnly === true, + resetOnHide: true, + templateOptions: { + required: true, + isAllowSeconds: true, + label: T.F.SYNC.FORM.L_SYNC_INTERVAL, + description: T.G.DURATION_DESCRIPTION, + }, + }, + { + key: 'isManualSyncOnly', + type: 'checkbox', + // Only show for file-based providers (Dropbox, WebDAV, LocalFile, Nextcloud) + hideExpression: (m, v, field) => + field?.parent?.parent?.model?.syncProvider === null, + templateOptions: { + label: T.F.SYNC.FORM.L_MANUAL_SYNC_ONLY, + }, + }, { key: 'isCompressionEnabled', type: 'checkbox', @@ -447,6 +443,7 @@ export const SYNC_FORM: ConfigFormSection = { templateOptions: { text: T.F.SYNC.FORM.FILE_BASED.BTN_ENABLE_ENCRYPTION, btnType: 'primary', + btnStyle: 'stroked', onClick: async (field: FormlyFieldConfig) => { const result = await openEnableEncryptionDialogForFileBased(); if (result?.success && field?.model) { @@ -473,16 +470,13 @@ export const SYNC_FORM: ConfigFormSection = { text: T.F.SYNC.FORM.SUPER_SYNC.BTN_GET_TOKEN, tooltip: T.F.SYNC.FORM.SUPER_SYNC.LOGIN_INSTRUCTIONS, btnType: 'primary', + btnStyle: 'stroked', centerBtn: true, onClick: (field: any) => { const baseUrl = field.model.baseUrl || SUPER_SYNC_DEFAULT_BASE_URL; window.open(baseUrl, '_blank'); }, }, - expressionProperties: { - 'templateOptions.btnStyle': (model: any) => - model.accessToken ? 'stroked' : undefined, - }, }, { hideExpression: (m, v, field) => @@ -526,6 +520,7 @@ export const SYNC_FORM: ConfigFormSection = { templateOptions: { text: T.F.SYNC.FORM.SUPER_SYNC.BTN_ENABLE_ENCRYPTION, btnType: 'primary', + btnStyle: 'stroked', onClick: async (field: FormlyFieldConfig) => { const result = await openEnableEncryptionDialog(); if (result?.success && field?.model) { @@ -540,7 +535,10 @@ export const SYNC_FORM: ConfigFormSection = { type: 'collapsible', hideExpression: (m, v, field) => field?.parent?.parent?.model.syncProvider !== SyncProviderId.SuperSync, - props: { label: T.G.ADVANCED_CFG }, + props: { + label: T.G.ADVANCED_CFG, + syncRole: 'advanced', + } as SyncCollapsibleProps, fieldGroup: [ // Server URL { diff --git a/src/app/imex/sync/dialog-sync-initial-cfg/dialog-sync-initial-cfg.component.html b/src/app/imex/sync/dialog-sync-cfg/dialog-sync-cfg.component.html similarity index 89% rename from src/app/imex/sync/dialog-sync-initial-cfg/dialog-sync-initial-cfg.component.html rename to src/app/imex/sync/dialog-sync-cfg/dialog-sync-cfg.component.html index b4beff04e0..b3a3c0bd42 100644 --- a/src/app/imex/sync/dialog-sync-initial-cfg/dialog-sync-initial-cfg.component.html +++ b/src/app/imex/sync/dialog-sync-cfg/dialog-sync-cfg.component.html @@ -1,4 +1,3 @@ -

{{ T.F.SYNC.D_INITIAL_CFG.TITLE | translate }}

@@ -19,7 +18,6 @@
+
+ } @else { +
+ + cloud_sync + {{ status.providerId }} + + @if (status.needsAuth) { + + {{ 'PS.SYNC.NEEDS_AUTH' | translate }} + + } + @if (status.isEncrypted) { + + lock + {{ 'PS.SYNC.ENCRYPTED' | translate }} + + } +
+
+ + +
} diff --git a/src/app/pages/config-page/config-page.component.scss b/src/app/pages/config-page/config-page.component.scss index 4e866e6904..2c4b93a903 100644 --- a/src/app/pages/config-page/config-page.component.scss +++ b/src/app/pages/config-page/config-page.component.scss @@ -106,6 +106,63 @@ } } +.sync-summary { + padding: var(--s2); + + &__intro { + margin: 0 0 var(--s2); + color: var(--text-color-muted); + } + + &__status { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: var(--s2); + margin-bottom: var(--s2); + } + + &__provider { + display: inline-flex; + align-items: center; + gap: var(--s-half); + font-weight: 500; + + mat-icon { + font-size: 20px; + width: 20px; + height: 20px; + } + } + + &__pill { + display: inline-flex; + align-items: center; + gap: var(--s-half); + padding: var(--s-half) var(--s); + border: 1px solid var(--divider-color); + border-radius: 999px; + font-size: 12px; + + mat-icon { + font-size: 14px; + width: 14px; + height: 14px; + } + + &--warn { + border-color: var(--color-warning); + color: var(--color-warning); + } + } + + &__actions { + display: flex; + flex-wrap: wrap; + gap: var(--s); + } +} + .version-footer { margin-top: auto; text-align: center; diff --git a/src/app/pages/config-page/config-page.component.spec.ts b/src/app/pages/config-page/config-page.component.spec.ts index 190defe759..bf440dc56e 100644 --- a/src/app/pages/config-page/config-page.component.spec.ts +++ b/src/app/pages/config-page/config-page.component.spec.ts @@ -6,28 +6,39 @@ import { SyncProviderManager } from '../../op-log/sync-providers/provider-manage import { GlobalConfigService } from '../../features/config/global-config.service'; import { ActivatedRoute } from '@angular/router'; import { PluginBridgeService } from '../../plugins/plugin-bridge.service'; -import { WebdavApi } from '../../op-log/sync-providers/file-based/webdav/webdav-api'; import { of } from 'rxjs'; import { signal } from '@angular/core'; import { SyncWrapperService } from '../../imex/sync/sync-wrapper.service'; import { ShareService } from '../../core/share/share.service'; import { UserProfileService } from '../../features/user-profile/user-profile.service'; import { MatDialog } from '@angular/material/dialog'; -import { SyncProviderId } from '../../op-log/sync-providers/provider.const'; import { TranslateService } from '@ngx-translate/core'; describe('ConfigPageComponent', () => { let component: ConfigPageComponent; - let mockSyncConfigService: jasmine.SpyObj; + let mockSyncWrapperService: jasmine.SpyObj; + let mockMatDialog: jasmine.SpyObj; + let mockProviderManager: jasmine.SpyObj; beforeEach(async () => { - mockSyncConfigService = jasmine.createSpyObj( + const mockSyncConfigService = jasmine.createSpyObj( 'SyncConfigService', ['updateSettingsFromForm'], { syncSettingsForm$: of({}) }, ); mockSyncConfigService.updateSettingsFromForm.and.returnValue(Promise.resolve()); + mockSyncWrapperService = jasmine.createSpyObj('SyncWrapperService', ['sync']); + mockMatDialog = jasmine.createSpyObj('MatDialog', ['open']); + mockProviderManager = jasmine.createSpyObj( + 'SyncProviderManager', + ['getProviderById'], + { + currentProviderPrivateCfg$: of(null), + }, + ); + mockProviderManager.getProviderById.and.returnValue(Promise.resolve(undefined)); + await TestBed.configureTestingModule({ providers: [ { provide: SyncConfigService, useValue: mockSyncConfigService }, @@ -35,16 +46,7 @@ describe('ConfigPageComponent', () => { provide: SnackService, useValue: jasmine.createSpyObj('SnackService', ['open']), }, - { - provide: SyncProviderManager, - useValue: (() => { - const spy = jasmine.createSpyObj('SyncProviderManager', ['getProviderById'], { - currentProviderPrivateCfg$: of(null), - }); - spy.getProviderById.and.returnValue(Promise.resolve(undefined)); - return spy; - })(), - }, + { provide: SyncProviderManager, useValue: mockProviderManager }, { provide: GlobalConfigService, useValue: jasmine.createSpyObj('GlobalConfigService', ['updateSection'], { @@ -54,13 +56,10 @@ describe('ConfigPageComponent', () => { }, { provide: ActivatedRoute, useValue: { queryParams: of({}) } }, { provide: PluginBridgeService, useValue: { shortcuts: signal([]) } }, - { provide: SyncWrapperService, useValue: {} }, + { provide: SyncWrapperService, useValue: mockSyncWrapperService }, { provide: ShareService, useValue: {} }, { provide: UserProfileService, useValue: {} }, - { - provide: MatDialog, - useValue: jasmine.createSpyObj('MatDialog', ['open']), - }, + { provide: MatDialog, useValue: mockMatDialog }, { provide: TranslateService, useValue: jasmine.createSpyObj('TranslateService', ['instant']), @@ -75,54 +74,18 @@ describe('ConfigPageComponent', () => { component = TestBed.createComponent(ConfigPageComponent).componentInstance; }); - describe('WebDAV Test Connection button', () => { - it('should save settings after successful connection test', async () => { - // Arrange - spyOn(WebdavApi.prototype, 'testConnection').and.returnValue( - Promise.resolve({ - success: true, - fullUrl: 'https://webdav.example.com/sp-test', - }), - ); + it('should expose an empty syncStatus by default', () => { + expect(component.syncStatus().providerId).toBeNull(); + expect(component.syncStatus().needsAuth).toBe(false); + }); - const webDavCfg = { - baseUrl: 'https://webdav.example.com', - userName: 'testuser', - password: 'testpass', - syncFolderPath: '/sp-test', - }; + it('triggerSync() should call SyncWrapperService.sync()', () => { + component.triggerSync(); + expect(mockSyncWrapperService.sync).toHaveBeenCalled(); + }); - const fullSyncModel = { - isEnabled: true, - syncProvider: SyncProviderId.WebDAV, - syncInterval: 600000, - webDav: webDavCfg, - }; - - const mockField = { - parent: { parent: { model: fullSyncModel } }, - }; - - // Wait for async sync form config to be built - await new Promise((resolve) => setTimeout(resolve, 0)); - - // Find the WebDAV Test Connection button onClick handler - const webDavItem = component - .globalSyncConfigFormCfg()! - .items!.find((item: any) => item.key === 'webDav'); - const testConnectionBtn = webDavItem!.fieldGroup!.find( - (item: any) => item.type === 'btn', - ); - const onClick = testConnectionBtn!.templateOptions!.onClick; - - // Act - await onClick(mockField, {}, webDavCfg); - - // Assert - expect(mockSyncConfigService.updateSettingsFromForm).toHaveBeenCalledWith( - fullSyncModel, - true, - ); - }); + it('openSyncCfgDialog() should open DialogSyncCfgComponent', async () => { + await component.openSyncCfgDialog(); + expect(mockMatDialog.open).toHaveBeenCalled(); }); }); diff --git a/src/app/pages/config-page/config-page.component.ts b/src/app/pages/config-page/config-page.component.ts index 30374439cb..64a4a31c3d 100644 --- a/src/app/pages/config-page/config-page.component.ts +++ b/src/app/pages/config-page/config-page.component.ts @@ -2,11 +2,10 @@ import { ChangeDetectionStrategy, ChangeDetectorRef, Component, + DestroyRef, effect, inject, - OnDestroy, OnInit, - signal, } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { GlobalConfigService } from '../../features/config/global-config.service'; @@ -20,13 +19,13 @@ import { } from '../../features/config/global-config-form-config.const'; import { ConfigFormConfig, - ConfigFormSection, GlobalConfigSectionKey, GlobalConfigState, GlobalSectionConfig, - SyncConfig, } from '../../features/config/global-config.model'; -import { combineLatest, firstValueFrom, Observable, Subscription } from 'rxjs'; +import { firstValueFrom, from, of } from 'rxjs'; +import { switchMap } from 'rxjs/operators'; +import { takeUntilDestroyed, toSignal } from '@angular/core/rxjs-interop'; import { ProjectCfgFormKey } from '../../features/project/project.model'; import { T } from '../../t.const'; import { versions } from '../../../environments/versions'; @@ -36,15 +35,10 @@ import { getAutomaticBackUpFormCfg } from '../../features/config/form-cfgs/autom import { getAppVersionStr } from '../../util/get-app-version-str'; import { ConfigSectionComponent } from '../../features/config/config-section/config-section.component'; import { ConfigSoundFormComponent } from '../../features/config/config-sound-form/config-sound-form.component'; -import { TranslatePipe, TranslateService } from '@ngx-translate/core'; -import { SYNC_FORM } from '../../features/config/form-cfgs/sync-form.const'; +import { TranslatePipe } from '@ngx-translate/core'; import { EXPERIMENTAL_APP_FEATURE_KEYS } from '../../features/config/form-cfgs/app-features-form.const'; import { SyncProviderManager } from '../../op-log/sync-providers/provider-manager.service'; -import { map } from 'rxjs/operators'; import { SyncConfigService } from '../../imex/sync/sync-config.service'; -import { WebdavApi } from '../../op-log/sync-providers/file-based/webdav/webdav-api'; -import { WebdavPrivateCfg } from '../../op-log/sync-providers/file-based/webdav/webdav.model'; -import { AsyncPipe } from '@angular/common'; import { PluginManagementComponent } from '../../plugins/ui/plugin-management/plugin-management.component'; import { PluginBridgeService } from '../../plugins/plugin-bridge.service'; import { createPluginShortcutFormItems } from '../../features/config/form-cfgs/plugin-keyboard-shortcuts'; @@ -58,12 +52,12 @@ import { SyncWrapperService } from '../../imex/sync/sync-wrapper.service'; import { UserProfileService } from '../../features/user-profile/user-profile.service'; import { MatDialog } from '@angular/material/dialog'; import { DialogDisableProfilesConfirmationComponent } from '../../features/user-profile/dialog-disable-profiles-confirmation/dialog-disable-profiles-confirmation.component'; -import { DialogRestorePointComponent } from '../../imex/sync/dialog-restore-point/dialog-restore-point.component'; import { SyncProviderId } from '../../op-log/sync-providers/provider.const'; import { DialogConfirmComponent } from '../../ui/dialog-confirm/dialog-confirm.component'; import { MatTab, MatTabGroup, MatTabLabel } from '@angular/material/tabs'; import { MatIcon } from '@angular/material/icon'; import { MatTooltip } from '@angular/material/tooltip'; +import { MatButton } from '@angular/material/button'; @Component({ selector: 'config-page', @@ -75,16 +69,16 @@ import { MatTooltip } from '@angular/material/tooltip'; ConfigSectionComponent, ConfigSoundFormComponent, TranslatePipe, - AsyncPipe, PluginManagementComponent, MatTabGroup, MatTab, MatTabLabel, MatIcon, MatTooltip, + MatButton, ], }) -export class ConfigPageComponent implements OnInit, OnDestroy { +export class ConfigPageComponent implements OnInit { private readonly _cd = inject(ChangeDetectorRef); private readonly _route = inject(ActivatedRoute); private readonly _providerManager = inject(SyncProviderManager); @@ -94,7 +88,6 @@ export class ConfigPageComponent implements OnInit, OnDestroy { private readonly _shareService = inject(ShareService); private readonly _userProfileService = inject(UserProfileService); private readonly _matDialog = inject(MatDialog); - private readonly _translateService = inject(TranslateService); readonly configService = inject(GlobalConfigService); readonly syncSettingsService = inject(SyncConfigService); @@ -112,31 +105,47 @@ export class ConfigPageComponent implements OnInit, OnDestroy { pluginsShortcutsFormCfg: ConfigFormConfig; globalImexFormCfg: ConfigFormConfig; globalProductivityConfigFormCfg: ConfigFormConfig; - globalSyncConfigFormCfg = signal | undefined>(undefined); - globalCfg?: GlobalConfigState; + // `providerId === null` ⇒ empty state (sync disabled or no provider chosen). + // switchMap drops stale signal writes if a new sync-config emission arrives + // before the previous provider probe resolves — the underlying probe promise + // still runs to completion in the background; only the result is ignored. + // try/catch keeps the stream alive when isReady() rejects (otherwise the + // observable error would kill the subscription and freeze the status). + syncStatus = toSignal( + this.syncSettingsService.syncSettingsForm$.pipe( + switchMap((sync) => { + const providerId = sync.isEnabled + ? (sync.syncProvider as SyncProviderId | null) + : null; + const isEncrypted = !!sync.isEncryptionEnabled; + if (!providerId) { + return of({ providerId: null, needsAuth: false, isEncrypted }); + } + return from( + (async () => { + const provider = await this._providerManager.getProviderById(providerId); + const requiresAuth = !!provider?.getAuthHelper; + try { + const isAuthed = !!(await provider?.isReady()); + return { providerId, needsAuth: requiresAuth && !isAuthed, isEncrypted }; + } catch { + // Don't claim a non-OAuth provider needs auth — only surface + // the auth pill if the provider could plausibly require it. + return { providerId, needsAuth: requiresAuth, isEncrypted }; + } + })(), + ); + }), + ), + { initialValue: { providerId: null, needsAuth: false, isEncrypted: false } }, + ); + appVersion: string = getAppVersionStr(); versions?: typeof versions = versions; - // TODO needs to contain all sync providers.... - // TODO maybe handling this in an effect would be better???? - syncFormCfg$: Observable> = combineLatest([ - this._providerManager.currentProviderPrivateCfg$, - this.configService.sync$, - ]).pipe( - map(([currentProviderCfg, syncCfg]) => { - if (!currentProviderCfg) { - return syncCfg as unknown as Record; - } - return { - ...(syncCfg as unknown as Record), - [currentProviderCfg.providerId]: currentProviderCfg.privateCfg, - }; - }), - ); - - private _subs: Subscription = new Subscription(); + private readonly _destroyRef = inject(DestroyRef); constructor() { // Initialize tab-specific form configurations @@ -147,17 +156,6 @@ export class ConfigPageComponent implements OnInit, OnDestroy { this.globalProductivityConfigFormCfg = GLOBAL_PRODUCTIVITY_FORM_CONFIG.slice(); this.globalTasksFormCfg = GLOBAL_TASKS_FORM_CONFIG.slice(); - // Build sync form config asynchronously (providers are lazy-loaded) - this._buildSyncFormConfig() - .then((cfg) => this.globalSyncConfigFormCfg.set(cfg)) - .catch((err) => { - Log.err('Failed to build sync form config:', err); - this._snackService.open({ - type: 'ERROR', - msg: T.GLOBAL_SNACK.OPEN_SETTINGS_ERROR, - }); - }); - // NOTE: needs special handling cause of the async stuff if (IS_ANDROID_WEB_VIEW) { this.globalImexFormCfg = [...this.globalImexFormCfg, getAutomaticBackUpFormCfg()]; @@ -180,16 +178,16 @@ export class ConfigPageComponent implements OnInit, OnDestroy { } ngOnInit(): void { - this._subs.add( - this.configService.cfg$.subscribe((cfg) => { + this.configService.cfg$ + .pipe(takeUntilDestroyed(this._destroyRef)) + .subscribe((cfg) => { this.globalCfg = cfg; - // this._cd.detectChanges(); - }), - ); + }); // Check for tab query parameter and set selected tab - this._subs.add( - this._route.queryParams.subscribe((params) => { + this._route.queryParams + .pipe(takeUntilDestroyed(this._destroyRef)) + .subscribe((params) => { if (params['tab'] !== undefined) { const tabIndex = parseInt(params['tab'], 10); if (!isNaN(tabIndex) && tabIndex >= 0 && tabIndex < 5) { @@ -201,8 +199,7 @@ export class ConfigPageComponent implements OnInit, OnDestroy { this.expandedSection = params['section']; this._cd.detectChanges(); } - }), - ); + }); } private _updateKeyboardFormWithPluginShortcuts(shortcuts: PluginShortcutCfg[]): void { @@ -263,264 +260,14 @@ export class ConfigPageComponent implements OnInit, OnDestroy { this._cd.detectChanges(); } - ngOnDestroy(): void { - this._subs.unsubscribe(); + async openSyncCfgDialog(): Promise { + const { DialogSyncCfgComponent } = + await import('../../imex/sync/dialog-sync-cfg/dialog-sync-cfg.component'); + this._matDialog.open(DialogSyncCfgComponent); } - private async _buildSyncFormConfig(): Promise { - // Pre-load dropbox provider for use in the form config - await this._providerManager.getProviderById(SyncProviderId.Dropbox); - - // Deep clone the SYNC_FORM items to avoid mutating the original - const items = SYNC_FORM.items!.map((item) => { - // Find the WebDAV fieldGroup and add the Test Connection button - if (item.key === 'webDav' && item.fieldGroup) { - return { - ...item, - fieldGroup: [ - ...item.fieldGroup, - { - type: 'btn', - className: 'mt3 block', - templateOptions: { - text: T.F.SYNC.FORM.WEB_DAV.L_TEST_CONNECTION, - required: false, - onClick: async (_field: unknown, _form: unknown, model: unknown) => { - const webDavCfg = model as WebdavPrivateCfg; - if ( - !webDavCfg?.baseUrl || - !webDavCfg?.userName || - !webDavCfg?.password || - !webDavCfg?.syncFolderPath - ) { - this._snackService.open({ - type: 'ERROR', - msg: T.F.SYNC.FORM.WEB_DAV.S_FILL_ALL_FIELDS, - }); - return; - } - - try { - // Create a temporary WebdavApi instance for testing - const api = new WebdavApi(async () => webDavCfg); - const result = await api.testConnection(webDavCfg); - - if (result.success) { - this._snackService.open({ - type: 'SUCCESS', - msg: T.F.SYNC.FORM.WEB_DAV.S_TEST_SUCCESS, - translateParams: { url: result.fullUrl }, - }); - - // Save settings after successful connection test. - // Formly hierarchy: _field (button) -> parent (group wrapper) -> parent (root form) -> model - const fullSyncModel = ( - _field as { parent?: { parent?: { model?: SyncConfig } } } - )?.parent?.parent?.model; - if (fullSyncModel) { - await this.syncSettingsService.updateSettingsFromForm( - fullSyncModel, - true, - ); - } - } else { - this._snackService.open({ - type: 'ERROR', - msg: T.F.SYNC.FORM.WEB_DAV.S_TEST_FAIL, - translateParams: { - error: result.error || 'Unknown error', - url: result.fullUrl, - }, - }); - } - } catch (e) { - this._snackService.open({ - type: 'ERROR', - msg: T.F.SYNC.FORM.WEB_DAV.S_TEST_FAIL, - translateParams: { - error: e instanceof Error ? e.message : 'Unexpected error', - url: (webDavCfg.baseUrl as string) || 'N/A', - }, - }); - } - }, - }, - }, - ], - }; - } - - // Find the Dropbox fieldGroup and add the authentication button - if ((item as any).props?.dropboxAuth && item.fieldGroup) { - // Check if Dropbox is already authenticated - // We need to check auth status asynchronously, so we'll set initial state - // and update it when the form is rendered - let isAuthenticated = false; - this._providerManager - .getProviderById(SyncProviderId.Dropbox) - .then(async (dropboxProvider) => { - const ready = await dropboxProvider?.isReady(); - isAuthenticated = !!ready; - // Update the status field text after checking - const statusField = item.fieldGroup?.find( - (f: any) => f.key === 'authStatus', - ) as any; - if (statusField?.templateOptions) { - statusField.templateOptions.text = isAuthenticated - ? '✓ ' + - this._translateService.instant(T.F.SYNC.FORM.DROPBOX.STATUS_CONFIGURED) - : '⚠ ' + - this._translateService.instant( - T.F.SYNC.FORM.DROPBOX.STATUS_NOT_CONFIGURED, - ); - } - }) - .catch((e) => console.error('Failed to check Dropbox auth status:', e)); - - return { - ...item, - fieldGroup: [ - ...item.fieldGroup, - { - type: 'btn', - className: 'mt3 block e2e-dropbox-auth-btn', - templateOptions: { - // Button text will be determined by checking if already authenticated - text: T.F.SYNC.FORM.DROPBOX.BTN_AUTHENTICATE, - btnType: 'primary', - onClick: async (_field: unknown, _form: unknown, model: unknown) => { - try { - // Check current auth status before opening dialog - const dropboxProvider = await this._providerManager.getProviderById( - SyncProviderId.Dropbox, - ); - const isCurrentlyAuth = await dropboxProvider?.isReady(); - - const result = - await this._syncWrapperService.configuredAuthForSyncProviderIfNecessary( - SyncProviderId.Dropbox, - true, // force re-authentication even if already configured - ); - - if (result.wasConfigured) { - this._snackService.open({ - type: 'SUCCESS', - msg: isCurrentlyAuth - ? T.F.SYNC.FORM.DROPBOX.REAUTH_SUCCESS - : T.F.SYNC.FORM.DROPBOX.AUTH_SUCCESS, - }); - - // Update the status field to show configured - const statusField = item.fieldGroup?.find( - (f: any) => f.key === 'authStatus', - ) as any; - if (statusField?.templateOptions) { - statusField.templateOptions.text = - '✓ ' + - this._translateService.instant( - T.F.SYNC.FORM.DROPBOX.STATUS_CONFIGURED, - ); - } - - // Update button text to "Re-authenticate" - const btnField = _field as any; - if (btnField?.templateOptions) { - btnField.templateOptions.text = - T.F.SYNC.FORM.DROPBOX.BTN_REAUTHENTICATE; - } - - // Save the updated credentials to persist them - const fullSyncModel = ( - _field as { parent?: { parent?: { model?: SyncConfig } } } - )?.parent?.parent?.model; - if (fullSyncModel) { - await this.syncSettingsService.updateSettingsFromForm( - fullSyncModel!, - true, - ); - } - } - } catch (e) { - // Log error for debugging (storage failures, auth errors, etc.) - Log.err('Dropbox authentication failed:', e); - // Show user-friendly error with actual error message for context - this._snackService.open({ - type: 'ERROR', - msg: T.F.SYNC.S.INCOMPLETE_CFG, - translateParams: { - error: e instanceof Error ? e.message : String(e), - }, - }); - } - }, - }, - hooks: { - // Update button text based on auth status when form initializes - onInit: async (field: any) => { - const dropboxProv = await this._providerManager.getProviderById( - SyncProviderId.Dropbox, - ); - const isAuth = await dropboxProv?.isReady(); - if (field?.templateOptions && isAuth) { - field.templateOptions.text = T.F.SYNC.FORM.DROPBOX.BTN_REAUTHENTICATE; - } - }, - }, - }, - ], - }; - } - - return item; - }); - - return { - ...SYNC_FORM, - items: [ - ...items, - { - hideExpression: (m: Record, _v: unknown, field: unknown) => - !m.isEnabled || !(field as { form?: { valid?: boolean } })?.form?.valid, - type: 'btn', - className: 'mt3 block', - templateOptions: { - text: T.F.SYNC.BTN_SYNC_NOW, - required: false, - onClick: () => { - this._syncWrapperService.sync(); - }, - }, - }, - { - hideExpression: (m: Record, _v: unknown, field: unknown) => - !m.isEnabled || !(field as { form?: { valid?: boolean } })?.form?.valid, - type: 'btn', - className: 'mt2 block', - templateOptions: { - text: T.F.SYNC.S.BTN_FORCE_OVERWRITE, - btnType: 'warn', - required: false, - onClick: () => { - this._syncWrapperService.forceUpload(); - }, - }, - }, - { - hideExpression: (m: Record) => - !m.isEnabled || m.syncProvider !== SyncProviderId.SuperSync, - type: 'btn', - className: 'mt2 block', - templateOptions: { - text: T.F.SYNC.BTN_RESTORE_FROM_HISTORY, - btnType: 'stroked', - required: false, - onClick: () => { - this._openRestoreDialog(); - }, - }, - }, - ], - } as typeof SYNC_FORM; + triggerSync(): void { + this._syncWrapperService.sync(); } async saveGlobalCfg($event: { @@ -633,11 +380,4 @@ export class ConfigPageComponent implements OnInit, OnDestroy { }); } } - - private _openRestoreDialog(): void { - this._matDialog.open(DialogRestorePointComponent, { - width: '500px', - maxWidth: '90vw', - }); - } } diff --git a/src/app/t.const.ts b/src/app/t.const.ts index 62bc7319b2..7e5a03cabd 100644 --- a/src/app/t.const.ts +++ b/src/app/t.const.ts @@ -1281,7 +1281,6 @@ const T = { BTN_CHANGE_PASSWORD: 'F.SYNC.FORM.SUPER_SYNC.BTN_CHANGE_PASSWORD', BTN_DISABLE_ENCRYPTION: 'F.SYNC.FORM.SUPER_SYNC.BTN_DISABLE_ENCRYPTION', BTN_ENABLE_ENCRYPTION: 'F.SYNC.FORM.SUPER_SYNC.BTN_ENABLE_ENCRYPTION', - BTN_FORCE_OVERWRITE: 'F.SYNC.FORM.SUPER_SYNC.BTN_FORCE_OVERWRITE', BTN_GET_TOKEN: 'F.SYNC.FORM.SUPER_SYNC.BTN_GET_TOKEN', CHANGE_PASSWORD_SUCCESS: 'F.SYNC.FORM.SUPER_SYNC.CHANGE_PASSWORD_SUCCESS', CHANGE_PASSWORD_WARNING: 'F.SYNC.FORM.SUPER_SYNC.CHANGE_PASSWORD_WARNING', @@ -2698,6 +2697,13 @@ const T = { PROJECT_SETTINGS: 'PS.PROJECT_SETTINGS', PROVIDE_FEEDBACK: 'PS.PROVIDE_FEEDBACK', RELOAD: 'PS.RELOAD', + SYNC: { + CONFIGURE: 'PS.SYNC.CONFIGURE', + EMPTY_STATE_HINT: 'PS.SYNC.EMPTY_STATE_HINT', + ENCRYPTED: 'PS.SYNC.ENCRYPTED', + NEEDS_AUTH: 'PS.SYNC.NEEDS_AUTH', + SET_UP_SYNC: 'PS.SYNC.SET_UP_SYNC', + }, SYNC_EXPORT: 'PS.SYNC_EXPORT', TABS: { GENERAL: 'PS.TABS.GENERAL', diff --git a/src/assets/i18n/en.json b/src/assets/i18n/en.json index 71f7374c00..fed1a93bdd 100644 --- a/src/assets/i18n/en.json +++ b/src/assets/i18n/en.json @@ -1177,7 +1177,7 @@ "AUTH_SUCCESS": "Dropbox authentication successful! Credentials saved.", "BTN_AUTHENTICATE": "Authenticate with Dropbox", "BTN_REAUTHENTICATE": "Re-authenticate with Dropbox", - "INFO_TEXT": "Dropbox authentication uses OAuth. Click the button below to authenticate with your Dropbox account.", + "INFO_TEXT": "Dropbox uses OAuth. Saving your settings will open Dropbox in your browser to authorize access.", "L_ACCESS_TOKEN": "Access Token (generated from Auth Code)", "REAUTH_SUCCESS": "Dropbox re-authentication successful! Credentials updated.", "STATUS_CONFIGURED": "Dropbox is configured and ready to sync", @@ -1255,7 +1255,6 @@ "BTN_CHANGE_PASSWORD": "Change Password", "BTN_DISABLE_ENCRYPTION": "Disable Encryption", "BTN_ENABLE_ENCRYPTION": "Enable Encryption", - "BTN_FORCE_OVERWRITE": "Force Overwrite Server", "BTN_GET_TOKEN": "Open Server & Get Token", "CHANGE_PASSWORD_SUCCESS": "Encryption password changed successfully", "CHANGE_PASSWORD_WARNING": "WARNING: This will permanently delete ALL sync history and backups on the server! Previous versions cannot be recovered. Your current data will be re-uploaded with the new password. All other devices will need the new password.", @@ -2645,6 +2644,13 @@ "PROJECT_SETTINGS": "Project Specific Settings", "PROVIDE_FEEDBACK": "Provide Feedback", "RELOAD": "Reload", + "SYNC": { + "CONFIGURE": "Configure", + "EMPTY_STATE_HINT": "Sync your data with Dropbox, WebDAV, Nextcloud, or a local file.", + "ENCRYPTED": "Encrypted", + "NEEDS_AUTH": "Authentication required", + "SET_UP_SYNC": "Set up sync" + }, "SYNC_EXPORT": "Sync & Export", "TABS": { "GENERAL": "General",