From cf109c11ac6f801673a657c1fdf927873fb38be5 Mon Sep 17 00:00:00 2001 From: Hwi Kim <166241069+littlebit0@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:48:41 +0900 Subject: [PATCH 1/3] =?UTF-8?q?=EA=B3=84=EC=A0=95=EB=B3=84=20=ED=85=8D?= =?UTF-8?q?=EC=8A=A4=ED=8A=B8=20=EC=84=9C=EB=AA=85=20=EC=B6=94=EA=B0=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 계정에 서명을 저장하는 API(PUT /accounts/:id/signature)와 계정 화면 편집기, 작성 화면의 서명 자동 삽입·계정 변경 시 교체를 추가한다. --- .../lib/core/i18n/language_controller.dart | 6 ++ .../lib/features/accounts/accounts_page.dart | 70 +++++++++++++++++++ .../lib/features/message/compose_page.dart | 33 ++++++++- apps/client/lib/services/mail_api_client.dart | 12 ++++ apps/client/test/widget_test.dart | 61 ++++++++++++++++ apps/server/package.json | 2 +- apps/server/src/api/routes.ts | 18 +++++ apps/server/src/domain/types.ts | 1 + apps/server/test/accountSignature.test.ts | 62 ++++++++++++++++ 9 files changed, 263 insertions(+), 2 deletions(-) create mode 100644 apps/server/test/accountSignature.test.ts diff --git a/apps/client/lib/core/i18n/language_controller.dart b/apps/client/lib/core/i18n/language_controller.dart index 443bb5f..ad4b28e 100644 --- a/apps/client/lib/core/i18n/language_controller.dart +++ b/apps/client/lib/core/i18n/language_controller.dart @@ -189,6 +189,12 @@ class AppStrings { String get deleteAccountDescription => _ko ? '이 앱에 저장된 계정과 동기화된 메일 목록이 삭제됩니다.' : 'This removes the account and synced mail list from this app.'; + String get signature => _ko ? '서명' : 'Signature'; + String get signatureHint => _ko + ? '새 메일 끝에 자동으로 붙습니다. 비워 두면 서명을 붙이지 않습니다.' + : 'Added to the end of new messages. Leave empty for no signature.'; + String get signatureSaved => _ko ? '서명을 저장했습니다.' : 'Signature saved.'; + String get save => _ko ? '저장' : 'Save'; String get cancel => _ko ? '취소' : 'Cancel'; String get statusIdle => _ko ? '대기' : 'Idle'; String get statusValidating => _ko ? '검증 중' : 'Validating'; diff --git a/apps/client/lib/features/accounts/accounts_page.dart b/apps/client/lib/features/accounts/accounts_page.dart index bc7cd23..8be0e9a 100644 --- a/apps/client/lib/features/accounts/accounts_page.dart +++ b/apps/client/lib/features/accounts/accounts_page.dart @@ -7,6 +7,7 @@ import '../../core/i18n/language_controller.dart'; import '../../services/browser_launcher.dart'; import '../../services/mail_api_client.dart'; import '../../widgets/app_shell.dart'; +import '../message/compose_page.dart' show composeAccountsProvider; import 'account_providers.dart'; export 'account_providers.dart' show accountsProvider, accountMessagesProvider; @@ -454,6 +455,8 @@ class _AccountDetail extends ConsumerWidget { ? strings.neverSynced : account.lastSyncedAtLabel, ), + const SizedBox(height: 24), + _SignatureEditor(key: ValueKey(account.id), account: account), if (account.syncError != null) ...[ const SizedBox(height: 12), Text( @@ -466,6 +469,73 @@ class _AccountDetail extends ConsumerWidget { } } +class _SignatureEditor extends ConsumerStatefulWidget { + const _SignatureEditor({super.key, required this.account}); + + final MailAccountSummary account; + + @override + ConsumerState<_SignatureEditor> createState() => _SignatureEditorState(); +} + +class _SignatureEditorState extends ConsumerState<_SignatureEditor> { + late final _controller = TextEditingController(text: widget.account.signature); + bool _saving = false; + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + Future _save() async { + final strings = ref.read(appStringsProvider); + final messenger = ScaffoldMessenger.maybeOf(context); + setState(() => _saving = true); + try { + await ref.read(mailApiClientProvider).updateAccountSignature( + accountId: widget.account.id, + signature: _controller.text, + ); + ref.invalidate(accountsProvider); + ref.invalidate(composeAccountsProvider); + messenger?.showSnackBar(SnackBar(content: Text(strings.signatureSaved))); + } catch (error) { + messenger?.showSnackBar( + SnackBar(content: Text(friendlyError(error, strings))), + ); + } finally { + if (mounted) setState(() => _saving = false); + } + } + + @override + Widget build(BuildContext context) { + final strings = ref.watch(appStringsProvider); + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + TextField( + controller: _controller, + minLines: 3, + maxLines: 8, + maxLength: 2000, + decoration: InputDecoration( + labelText: strings.signature, + helperText: strings.signatureHint, + border: const OutlineInputBorder(), + ), + ), + const SizedBox(height: 8), + FilledButton( + onPressed: _saving ? null : _save, + child: Text(strings.save), + ), + ], + ); + } +} + class _InfoRow extends StatelessWidget { const _InfoRow({ required this.label, diff --git a/apps/client/lib/features/message/compose_page.dart b/apps/client/lib/features/message/compose_page.dart index c0f8a58..64e7e33 100644 --- a/apps/client/lib/features/message/compose_page.dart +++ b/apps/client/lib/features/message/compose_page.dart @@ -10,6 +10,21 @@ final composeAccountsProvider = FutureProvider>((ref) { return ref.watch(mailApiClientProvider).fetchAccounts(); }); +const _signatureSeparator = '\n\n-- \n'; + +/// Appends [signature] to [body], or swaps it for [previous] when the user +/// has not edited the old signature block. +String swapSignature(String body, String previous, String signature) { + final oldBlock = previous.isEmpty ? '' : _signatureSeparator + previous; + final newBlock = signature.isEmpty ? '' : _signatureSeparator + signature; + if (oldBlock.isNotEmpty) { + // Edited or deleted by the user: leave the body alone. + if (!body.endsWith(oldBlock)) return body; + return body.substring(0, body.length - oldBlock.length) + newBlock; + } + return body + newBlock; +} + class ComposePage extends ConsumerStatefulWidget { const ComposePage({ super.key, @@ -27,6 +42,8 @@ class _ComposePageState extends ConsumerState { final _subjectController = TextEditingController(); final _bodyController = TextEditingController(); String? _accountId; + String _signature = ''; + bool _signatureInitialized = false; @override void initState() { @@ -76,6 +93,10 @@ class _ComposePageState extends ConsumerState { !items.any((account) => account.id == _accountId)) { _accountId = items.firstOrNull?.id; } + if (!_signatureInitialized && items.isNotEmpty) { + _signatureInitialized = true; + _useSignatureOf(items, _accountId); + } return ListView( padding: const EdgeInsets.all(24), @@ -90,7 +111,10 @@ class _ComposePageState extends ConsumerState { child: Text(account.emailAddress), ), ], - onChanged: (value) => setState(() => _accountId = value), + onChanged: (value) => setState(() { + _accountId = value; + _useSignatureOf(items, value); + }), ), const SizedBox(height: 12), TextField( @@ -130,6 +154,13 @@ class _ComposePageState extends ConsumerState { ); } + void _useSignatureOf(List items, String? accountId) { + final next = + items.where((a) => a.id == accountId).firstOrNull?.signature ?? ''; + _bodyController.text = swapSignature(_bodyController.text, _signature, next); + _signature = next; + } + Future _send() async { final accountId = _accountId; if (accountId == null) return; diff --git a/apps/client/lib/services/mail_api_client.dart b/apps/client/lib/services/mail_api_client.dart index 721252c..778b78d 100644 --- a/apps/client/lib/services/mail_api_client.dart +++ b/apps/client/lib/services/mail_api_client.dart @@ -168,6 +168,15 @@ class MailApiClient { }); } + Future updateAccountSignature({ + required String accountId, + required String signature, + }) async { + await _dio.put('/accounts/$accountId/signature', data: { + 'signature': signature, + }); + } + Future validateStoredAccount(String accountId) async { await _dio.post('/accounts/$accountId/validate'); } @@ -338,11 +347,13 @@ class MailAccountSummary { this.syncErrorCode, required this.initialSync, required this.lastSyncedAtLabel, + this.signature = '', }); final String id; final String providerId; final String emailAddress; + final String signature; final String incomingProtocol; final String authMode; final String syncStatus; @@ -366,6 +377,7 @@ class MailAccountSummary { json['initialSync'] as Map) : null, lastSyncedAtLabel: _formatReceivedAt(json['lastSyncedAt'] as String?), + signature: json['signature'] as String? ?? '', ); } } diff --git a/apps/client/test/widget_test.dart b/apps/client/test/widget_test.dart index 52f8487..d5c36a3 100644 --- a/apps/client/test/widget_test.dart +++ b/apps/client/test/widget_test.dart @@ -4,6 +4,7 @@ import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:daily_postbox/features/accounts/accounts_page.dart'; +import 'package:daily_postbox/features/message/compose_page.dart'; import 'package:daily_postbox/features/message/linked_message_body.dart'; import 'package:daily_postbox/main.dart'; import 'package:daily_postbox/services/mail_api_client.dart'; @@ -492,6 +493,66 @@ void main() { expect(openedUri, Uri.parse(url)); }); + test('swaps the signature only when the user has not edited it', () { + expect(swapSignature('', '', 'A'), '\n\n-- \nA'); + expect(swapSignature('hi', '', ''), 'hi'); + expect(swapSignature('hi\n\n-- \nA', 'A', 'B'), 'hi\n\n-- \nB'); + expect(swapSignature('hi\n\n-- \nA', 'A', ''), 'hi'); + expect( + swapSignature('hi\n\n-- \nA edited', 'A', 'B'), + 'hi\n\n-- \nA edited', + ); + }); + + testWidgets('compose appends the account signature and swaps it', ( + WidgetTester tester, + ) async { + const accounts = [ + MailAccountSummary( + id: 'a', + providerId: 'gmail', + emailAddress: 'a@example.com', + incomingProtocol: 'imap', + authMode: 'oauth2', + syncStatus: 'idle', + syncError: null, + initialSync: InitialSyncOption.recommended, + lastSyncedAtLabel: 'now', + signature: 'Sig A', + ), + MailAccountSummary( + id: 'b', + providerId: 'gmail', + emailAddress: 'b@example.com', + incomingProtocol: 'imap', + authMode: 'oauth2', + syncStatus: 'idle', + syncError: null, + initialSync: InitialSyncOption.recommended, + lastSyncedAtLabel: 'now', + ), + ]; + await tester.pumpWidget( + ProviderScope( + overrides: [ + composeAccountsProvider.overrideWith((ref) async => accounts), + ], + child: const MaterialApp(home: ComposePage()), + ), + ); + await tester.pumpAndSettle(); + + String body() => + tester.widget(find.byType(TextField).last).controller!.text; + expect(body(), '\n\n-- \nSig A'); + + await tester.tap(find.byType(DropdownButtonFormField)); + await tester.pumpAndSettle(); + await tester.tap(find.text('b@example.com').last); + await tester.pumpAndSettle(); + expect(body(), ''); + }); + test('merges word boxes into one continuous underline per line', () { final merged = mergeLinkUnderlineBoxes(const [ TextBox.fromLTRBD(0, 0, 42, 20, TextDirection.ltr), diff --git a/apps/server/package.json b/apps/server/package.json index 982da57..3127b38 100644 --- a/apps/server/package.json +++ b/apps/server/package.json @@ -5,7 +5,7 @@ "type": "module", "scripts": { "dev": "tsx src/server.ts", - "test": "tsx --test test/imapSequenceRanges.test.ts test/mailSyncWorker.test.ts test/accountValidate.test.ts test/accountReconnect.test.ts test/oauthTokenManager.test.ts test/apnsPushNotifier.test.ts", + "test": "tsx --test test/imapSequenceRanges.test.ts test/mailSyncWorker.test.ts test/accountValidate.test.ts test/accountReconnect.test.ts test/oauthTokenManager.test.ts test/apnsPushNotifier.test.ts test/accountSignature.test.ts", "typecheck": "tsc --noEmit", "start": "node dist/server.js", "build": "tsc" diff --git a/apps/server/src/api/routes.ts b/apps/server/src/api/routes.ts index 6e2ebd1..85862a5 100644 --- a/apps/server/src/api/routes.ts +++ b/apps/server/src/api/routes.ts @@ -166,6 +166,24 @@ export async function registerRoutes( return reply.code(204).send(); }); + app.put("/accounts/:id/signature", async (request, reply) => { + const params = z.object({ id: z.string() }).parse(request.params); + const body = z.object({ signature: z.string().max(2000) }).parse(request.body); + const account = await deps.accounts.getAccount(params.id); + + if (!account || account.userId !== demoUserId) { + return reply.code(404).send({ error: "Account not found" }); + } + + const signature = body.signature.trim(); + account.signature = signature || undefined; + account.updatedAt = new Date(); + await deps.accounts.updateAccount(account); + + const { encryptedSecretRef: _secret, ...publicAccount } = account; + return publicAccount; + }); + app.post("/accounts/:id/validate", async (request, reply) => { const params = z.object({ id: z.string() }).parse(request.params); const account = await deps.accounts.getAccount(params.id); diff --git a/apps/server/src/domain/types.ts b/apps/server/src/domain/types.ts index ad7152b..b663338 100644 --- a/apps/server/src/domain/types.ts +++ b/apps/server/src/domain/types.ts @@ -38,6 +38,7 @@ export interface MailAccount { providerId: ProviderId; emailAddress: string; displayName?: string; + signature?: string; authMode: AuthMode; incomingProtocol: MailProtocol; encryptedSecretRef: string; diff --git a/apps/server/test/accountSignature.test.ts b/apps/server/test/accountSignature.test.ts new file mode 100644 index 0000000..e007144 --- /dev/null +++ b/apps/server/test/accountSignature.test.ts @@ -0,0 +1,62 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import Fastify from "fastify"; +import type { MailAccount } from "../src/domain/types.js"; +import { InMemoryAccountRepository } from "../src/workers/AccountRepository.js"; + +process.env.GOOGLE_OAUTH_CLIENT_ID = "test-client"; +const { registerRoutes } = await import("../src/api/routes.js"); + +async function setup() { + const now = new Date(); + const account: MailAccount = { + id: "account-1", + userId: "demo-user", + providerId: "naver", + emailAddress: "user@example.com", + authMode: "app-password", + incomingProtocol: "imap", + encryptedSecretRef: "secret", + createdAt: now, + updatedAt: now + }; + const accounts = new InMemoryAccountRepository(); + await accounts.addAccount(account); + const app = Fastify(); + await registerRoutes(app, { accounts } as never); + return { app, accounts }; +} + +test("saves, lists and clears an account signature", async () => { + const { app, accounts } = await setup(); + + const saved = await app.inject({ + method: "PUT", + url: "/accounts/account-1/signature", + payload: { signature: " Kim\nExample Corp " } + }); + assert.equal(saved.statusCode, 200); + assert.equal(saved.json().signature, "Kim\nExample Corp"); + assert.equal(saved.json().encryptedSecretRef, undefined); + assert.equal((await accounts.getAccount("account-1"))?.signature, "Kim\nExample Corp"); + + const listed = await app.inject({ method: "GET", url: "/accounts" }); + assert.equal(listed.json()[0].signature, "Kim\nExample Corp"); + + await app.inject({ + method: "PUT", + url: "/accounts/account-1/signature", + payload: { signature: " " } + }); + assert.equal((await accounts.getAccount("account-1"))?.signature, undefined); +}); + +test("rejects unknown accounts", async () => { + const { app } = await setup(); + const response = await app.inject({ + method: "PUT", + url: "/accounts/missing/signature", + payload: { signature: "x" } + }); + assert.equal(response.statusCode, 404); +}); From 8610ed7104d2c538a9ece819e17cd31bd062c8df Mon Sep 17 00:00:00 2001 From: Hwi Kim <166241069+littlebit0@users.noreply.github.com> Date: Sun, 22 Nov 2026 00:54:39 +0900 Subject: [PATCH 2/3] =?UTF-8?q?=EC=84=9C=EB=AA=85=20=ED=8E=B8=EC=A7=91=20?= =?UTF-8?q?=EC=86=8C=EC=9C=A0=EA=B6=8C=20=EC=9C=A0=EC=A7=80=EC=99=80=20?= =?UTF-8?q?=EC=A0=80=EC=9E=A5=20=ED=9B=84=20=EC=BA=90=EC=8B=9C=20=EB=AC=B4?= =?UTF-8?q?=ED=9A=A8=ED=99=94=EB=A5=BC=20=EC=9C=84=EC=A0=AF=20=EC=88=98?= =?UTF-8?q?=EB=AA=85=EA=B3=BC=20=EB=B6=84=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 사용자가 서명을 고쳐 교체가 건너뛰어지면 관리 중인 서명을 유지해 계정 재전환 시 중복 추가를 막음 - 서명 저장·캐시 무효화를 Provider로 옮겨 편집기가 dispose돼도 완료되게 하고 UI 처리는 mounted로 보호 --- .../lib/features/accounts/accounts_page.dart | 24 +++- .../lib/features/message/compose_page.dart | 9 +- apps/client/test/widget_test.dart | 109 ++++++++++++++++++ 3 files changed, 135 insertions(+), 7 deletions(-) diff --git a/apps/client/lib/features/accounts/accounts_page.dart b/apps/client/lib/features/accounts/accounts_page.dart index 8be0e9a..9d9333d 100644 --- a/apps/client/lib/features/accounts/accounts_page.dart +++ b/apps/client/lib/features/accounts/accounts_page.dart @@ -469,6 +469,20 @@ class _AccountDetail extends ConsumerWidget { } } +/// Saves a signature and refreshes caches; lives in the provider scope so it +/// completes even if the editor widget is disposed mid-request. +final _saveSignatureProvider = Provider< + Future Function(String accountId, String signature)>((ref) { + return (accountId, signature) async { + await ref.read(mailApiClientProvider).updateAccountSignature( + accountId: accountId, + signature: signature, + ); + ref.invalidate(accountsProvider); + ref.invalidate(composeAccountsProvider); + }; +}, name: 'saveSignature'); + class _SignatureEditor extends ConsumerStatefulWidget { const _SignatureEditor({super.key, required this.account}); @@ -491,16 +505,14 @@ class _SignatureEditorState extends ConsumerState<_SignatureEditor> { Future _save() async { final strings = ref.read(appStringsProvider); final messenger = ScaffoldMessenger.maybeOf(context); + final save = ref.read(_saveSignatureProvider); setState(() => _saving = true); try { - await ref.read(mailApiClientProvider).updateAccountSignature( - accountId: widget.account.id, - signature: _controller.text, - ); - ref.invalidate(accountsProvider); - ref.invalidate(composeAccountsProvider); + await save(widget.account.id, _controller.text); + if (!mounted) return; messenger?.showSnackBar(SnackBar(content: Text(strings.signatureSaved))); } catch (error) { + if (!mounted) return; messenger?.showSnackBar( SnackBar(content: Text(friendlyError(error, strings))), ); diff --git a/apps/client/lib/features/message/compose_page.dart b/apps/client/lib/features/message/compose_page.dart index 64e7e33..1aa5dd7 100644 --- a/apps/client/lib/features/message/compose_page.dart +++ b/apps/client/lib/features/message/compose_page.dart @@ -157,7 +157,14 @@ class _ComposePageState extends ConsumerState { void _useSignatureOf(List items, String? accountId) { final next = items.where((a) => a.id == accountId).firstOrNull?.signature ?? ''; - _bodyController.text = swapSignature(_bodyController.text, _signature, next); + final body = _bodyController.text; + // User edited the managed block: keep owning the old signature so later + // switches neither overwrite the edit nor append a duplicate. + if (_signature.isNotEmpty && + !body.endsWith(_signatureSeparator + _signature)) { + return; + } + _bodyController.text = swapSignature(body, _signature, next); _signature = next; } diff --git a/apps/client/test/widget_test.dart b/apps/client/test/widget_test.dart index d5c36a3..b1274f0 100644 --- a/apps/client/test/widget_test.dart +++ b/apps/client/test/widget_test.dart @@ -1,3 +1,4 @@ +import 'dart:async'; import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:flutter_riverpod/flutter_riverpod.dart'; @@ -553,6 +554,98 @@ void main() { expect(body(), ''); }); + testWidgets('compose keeps an edited signature without duplicating it', ( + WidgetTester tester, + ) async { + MailAccountSummary account(String id, String signature) => + MailAccountSummary( + id: id, + providerId: 'gmail', + emailAddress: '$id@example.com', + incomingProtocol: 'imap', + authMode: 'oauth2', + syncStatus: 'idle', + syncError: null, + initialSync: InitialSyncOption.recommended, + lastSyncedAtLabel: 'now', + signature: signature, + ); + final accounts = [account('a', 'Sig A'), account('b', '')]; + await tester.pumpWidget( + ProviderScope( + overrides: [ + composeAccountsProvider.overrideWith((ref) async => accounts), + ], + child: const MaterialApp(home: ComposePage()), + ), + ); + await tester.pumpAndSettle(); + + final bodyField = tester.widget(find.byType(TextField).last); + bodyField.controller!.text = '\n\n-- \nSig A edited'; + + Future pick(String email) async { + await tester.tap(find.byType(DropdownButtonFormField)); + await tester.pumpAndSettle(); + await tester.tap(find.text(email).last); + await tester.pumpAndSettle(); + } + + await pick('b@example.com'); + await pick('a@example.com'); + expect(bodyField.controller!.text, '\n\n-- \nSig A edited'); + }); + + testWidgets('signature save refreshes caches after switching accounts', ( + WidgetTester tester, + ) async { + MailAccountSummary account(String id) => MailAccountSummary( + id: id, + providerId: 'gmail', + emailAddress: '$id@example.com', + incomingProtocol: 'imap', + authMode: 'oauth2', + syncStatus: 'idle', + syncError: null, + initialSync: InitialSyncOption.recommended, + lastSyncedAtLabel: 'now', + ); + final api = _SlowSignatureApi(); + var accountLoads = 0; + await tester.binding.setSurfaceSize(const Size(1200, 1000)); + addTearDown(() => tester.binding.setSurfaceSize(null)); + await tester.pumpWidget( + ProviderScope( + overrides: [ + mailApiClientProvider.overrideWithValue(api), + accountsProvider.overrideWith((ref) async { + accountLoads += 1; + return [account('first'), account('second')]; + }), + providersProvider.overrideWith((ref) async => const []), + accountMessagesProvider.overrideWith((ref, id) async => const []), + ], + child: const DailyPostBoxApp(), + ), + ); + await tester.pumpAndSettle(); + await tester.tap(find.text('계정관리').first); + await tester.pumpAndSettle(); + await tester.enterText(find.byType(TextField).first, 'Sig'); + await tester.tap(find.widgetWithText(FilledButton, '저장')); + await tester.pump(); + + await tester.tap(find.text('second@example.com').first); + await tester.pumpAndSettle(); + final loadsBefore = accountLoads; + api.release.complete(); + await tester.pumpAndSettle(); + + expect(api.saved, [('first', 'Sig')]); + expect(accountLoads, greaterThan(loadsBefore)); + expect(tester.takeException(), isNull); + }); + test('merges word boxes into one continuous underline per line', () { final merged = mergeLinkUnderlineBoxes(const [ TextBox.fromLTRBD(0, 0, 42, 20, TextDirection.ltr), @@ -567,6 +660,22 @@ void main() { }); } +class _SlowSignatureApi extends MailApiClient { + _SlowSignatureApi() : super(baseUrl: 'http://127.0.0.1:1'); + + final release = Completer(); + final saved = <(String, String)>[]; + + @override + Future updateAccountSignature({ + required String accountId, + required String signature, + }) async { + await release.future; + saved.add((accountId, signature)); + } +} + class _CredentialRecordingApi extends MailApiClient { _CredentialRecordingApi() : super(baseUrl: 'http://127.0.0.1:1'); From 45a3cb4156ef9c306d22ca4e7cdb42278b6f6680 Mon Sep 17 00:00:00 2001 From: Hwi Kim <166241069+littlebit0@users.noreply.github.com> Date: Fri, 27 Nov 2026 02:04:28 +0900 Subject: [PATCH 3/3] =?UTF-8?q?=EC=84=9C=EB=AA=85=20=EC=82=BD=EC=9E=85?= =?UTF-8?q?=C2=B7=EA=B5=90=EC=B2=B4=20=EC=8B=9C=20=EB=B3=B8=EB=AC=B8=20?= =?UTF-8?q?=EC=BB=A4=EC=84=9C=EB=A5=BC=20=EC=84=9C=EB=AA=85=20=EC=95=9E?= =?UTF-8?q?=EC=97=90=20=EB=91=90=EA=B8=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit controller.text만 바꾸면 selection이 무효가 되어 포커스 시 커서가 서명 뒤로 가고, 그 뒤 입력하면 계정 전환 때 서명이 편집된 것으로 판정돼 교체되지 않았다. 기존 selection이 본문 범위 안이면 보존하고, 아니면 서명 앞에 둔다. --- .../lib/features/message/compose_page.dart | 12 ++++- apps/client/test/widget_test.dart | 47 +++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/apps/client/lib/features/message/compose_page.dart b/apps/client/lib/features/message/compose_page.dart index 1aa5dd7..db961d4 100644 --- a/apps/client/lib/features/message/compose_page.dart +++ b/apps/client/lib/features/message/compose_page.dart @@ -164,7 +164,17 @@ class _ComposePageState extends ConsumerState { !body.endsWith(_signatureSeparator + _signature)) { return; } - _bodyController.text = swapSignature(body, _signature, next); + final text = swapSignature(body, _signature, next); + final bodyEnd = text.length - + (next.isEmpty ? 0 : _signatureSeparator.length + next.length); + final selection = _bodyController.selection; + // An invalid selection jumps to the end on focus, i.e. after the signature. + _bodyController.value = TextEditingValue( + text: text, + selection: selection.isValid && selection.end <= bodyEnd + ? selection + : TextSelection.collapsed(offset: bodyEnd), + ); _signature = next; } diff --git a/apps/client/test/widget_test.dart b/apps/client/test/widget_test.dart index b1274f0..6065ca0 100644 --- a/apps/client/test/widget_test.dart +++ b/apps/client/test/widget_test.dart @@ -596,6 +596,53 @@ void main() { expect(bodyField.controller!.text, '\n\n-- \nSig A edited'); }); + testWidgets('compose types before the signature and still swaps it', ( + WidgetTester tester, + ) async { + MailAccountSummary account(String id, String signature) => + MailAccountSummary( + id: id, + providerId: 'gmail', + emailAddress: '$id@example.com', + incomingProtocol: 'imap', + authMode: 'oauth2', + syncStatus: 'idle', + syncError: null, + initialSync: InitialSyncOption.recommended, + lastSyncedAtLabel: 'now', + signature: signature, + ); + final accounts = [account('a', 'Sig A'), account('b', 'Sig B')]; + await tester.pumpWidget( + ProviderScope( + overrides: [ + composeAccountsProvider.overrideWith((ref) async => accounts), + ], + child: const MaterialApp(home: ComposePage()), + ), + ); + await tester.pumpAndSettle(); + + final controller = + tester.widget(find.byType(TextField).last).controller!; + await tester.showKeyboard(find.byType(TextField).last); + await tester.pump(); + // Type at the caret the way the platform IME does. + final value = controller.value; + tester.testTextInput.updateEditingValue( + value.replaced(value.selection, 'Hi'), + ); + await tester.pump(); + expect(controller.text, 'Hi\n\n-- \nSig A'); + + await tester.tap(find.byType(DropdownButtonFormField)); + await tester.pumpAndSettle(); + await tester.tap(find.text('b@example.com').last); + await tester.pumpAndSettle(); + expect(controller.text, 'Hi\n\n-- \nSig B'); + expect(controller.selection, const TextSelection.collapsed(offset: 2)); + }); + testWidgets('signature save refreshes caches after switching accounts', ( WidgetTester tester, ) async {