-
Notifications
You must be signed in to change notification settings - Fork 0
[refactor] WebView 브릿지 개별 채널 아키텍처 #5
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| /// WebView에 주입되는 JavaScript 브릿지 스크립트 | ||
| class BridgeSetupScript { | ||
| BridgeSetupScript._(); | ||
|
|
||
| static const String script = """ | ||
| (function() { | ||
| window.AppBridge = window.AppBridge || {}; | ||
|
|
||
| function _setupChannel(name) { | ||
| window.AppBridge[name] = { | ||
| postMessage: function(...args) { | ||
| return window.flutter_inappwebview.callHandler('AppBridge.' + name, ...args); | ||
| } | ||
| }; | ||
| } | ||
|
|
||
| // Legacy FlutterMessageQueue (구버전 웹 호환) | ||
| if (typeof window.FlutterMessageQueue === 'undefined') { | ||
| window.FlutterMessageQueue = { | ||
| postMessage: function(message, ...args) { | ||
| return window.flutter_inappwebview.callHandler('FlutterMessageQueue', message, ...args); | ||
| } | ||
| }; | ||
| } | ||
|
|
||
| // 개별 채널 인터페이스 | ||
| _setupChannel('deviceToken'); | ||
| _setupChannel('platform'); | ||
| _setupChannel('album'); | ||
| _setupChannel('albumMultiple'); | ||
| _setupChannel('camera'); | ||
| _setupChannel('kakaoLogin'); | ||
| _setupChannel('appleLogin'); | ||
| _setupChannel('haptic'); | ||
| _setupChannel('env'); | ||
| _setupChannel('share'); | ||
|
|
||
| // 로깅 채널 | ||
| if (typeof window.LogToFlutter === 'undefined') { | ||
| window.LogToFlutter = { | ||
| postMessage: function(message) { | ||
| window.flutter_inappwebview.callHandler('LogToFlutter', message); | ||
| } | ||
| }; | ||
| } | ||
|
|
||
| window.isInApp = true; | ||
|
|
||
| console.log('[Flutter Bridge] AppBridge channels:', Object.keys(window.AppBridge)); | ||
|
|
||
| if (window.LogToFlutter && typeof window.LogToFlutter.postMessage === 'function') { | ||
| try { | ||
| window.addEventListener('error', function(event) { | ||
| window.LogToFlutter.postMessage('[WindowError] ' + event.message + ' at ' + event.filename + ':' + event.lineno); | ||
| }); | ||
| } catch (bridgeLoggingError) { | ||
| console.error('[Flutter Bridge] Failed to wire logging listeners', bridgeLoggingError); | ||
| } | ||
| } | ||
| })(); | ||
| """; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,62 @@ | ||
| import 'dart:convert'; | ||
|
|
||
| import 'package:app/bridge/handlers/bridge_handler_base.dart'; | ||
| import 'package:app/bridge/social_login_handler.dart'; | ||
|
|
||
| /// 소셜 로그인 관련 브릿지 핸들러 | ||
| mixin AuthBridgeHandler on BridgeHandlerBase { | ||
| Future<void> handleKakaoLogin() async { | ||
| try { | ||
| onShowLoading?.call('카카오 로그인 중...'); | ||
| KakaoLoginResult? kakaoLoginResult = await loginWithKakao(); | ||
|
|
||
| if (kakaoLoginResult == null) { | ||
| return; | ||
| } | ||
|
|
||
| await controller.evaluateJavascript( | ||
| source: "onKakaoLoginSuccess('${kakaoLoginResult.accessToken}')", | ||
| ); | ||
| } catch (error) { | ||
| try { | ||
| await controller.evaluateJavascript( | ||
| source: "onKakaoLoginError('$error')", | ||
| ); | ||
| } catch (_) {} | ||
| } finally { | ||
| onHideLoading?.call(); | ||
| } | ||
| } | ||
|
|
||
| Future<void> handleAppleLogin(List<dynamic> arguments) async { | ||
| try { | ||
| onShowLoading?.call('애플 로그인 중...'); | ||
|
|
||
| String nonce = arguments[0]['nonce']; | ||
| AppleLoginResult? appleLoginResult = await loginWithApple(nonce); | ||
|
|
||
| if (appleLoginResult == null) { | ||
| return; | ||
| } | ||
|
|
||
| final json = jsonEncode({ | ||
| 'idToken': appleLoginResult.idToken, | ||
| 'nonce': nonce, | ||
| }); | ||
|
|
||
| logger.d('appleLoginResult: ${appleLoginResult.idToken}, $nonce'); | ||
|
|
||
| await controller.evaluateJavascript( | ||
| source: "onAppleLoginSuccess('$json')", | ||
| ); | ||
| } catch (error) { | ||
| try { | ||
| await controller.evaluateJavascript( | ||
| source: "onAppleLoginError('$error')", | ||
| ); | ||
| } catch (_) {} | ||
| } finally { | ||
| onHideLoading?.call(); | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,71 @@ | ||
| import 'dart:io'; | ||
|
|
||
| import 'package:app/main.dart'; | ||
| import 'package:flutter/cupertino.dart'; | ||
| import 'package:flutter/material.dart'; | ||
| import 'package:flutter_inappwebview/flutter_inappwebview.dart'; | ||
| import 'package:logger/logger.dart'; | ||
|
|
||
| /// 브릿지 핸들러 공통 의존성 및 유틸리티 | ||
| abstract class BridgeHandlerBase { | ||
| InAppWebViewController get controller; | ||
| Logger get logger; | ||
| Function(String)? get onShowLoading; | ||
| VoidCallback? get onHideLoading; | ||
| BuildContext get context; | ||
|
|
||
| /// 권한 요청 다이얼로그 (iOS: Cupertino, Android: Material) | ||
| void showPermissionDialog({ | ||
| required String title, | ||
| required String content, | ||
| required VoidCallback onConfirm, | ||
| }) { | ||
| final ctx = navigatorKey.currentContext; | ||
| if (ctx == null) return; | ||
|
|
||
| Widget dialog = Platform.isIOS | ||
| ? CupertinoAlertDialog( | ||
| title: Text(title), | ||
| content: Text(content), | ||
| actions: <Widget>[ | ||
| CupertinoDialogAction( | ||
| child: const Text('취소'), | ||
| onPressed: () { | ||
| Navigator.of(ctx).pop(); | ||
| }, | ||
| ), | ||
| CupertinoDialogAction( | ||
| child: const Text('설정으로 이동'), | ||
| onPressed: () { | ||
| onConfirm(); | ||
| Navigator.of(ctx).pop(); | ||
| }, | ||
| ), | ||
| ], | ||
| ) | ||
| : AlertDialog( | ||
| title: Text(title), | ||
| content: Text(content), | ||
| actions: <Widget>[ | ||
| TextButton( | ||
| child: const Text('취소'), | ||
| onPressed: () { | ||
| Navigator.of(ctx).pop(); | ||
| }, | ||
| ), | ||
| TextButton( | ||
| child: const Text('설정으로 이동'), | ||
| onPressed: () { | ||
| onConfirm(); | ||
| Navigator.of(ctx).pop(); | ||
| }, | ||
| ), | ||
| ], | ||
| ); | ||
|
|
||
| showDialog( | ||
| context: ctx, | ||
| builder: (BuildContext context) => dialog, | ||
| ); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,89 @@ | ||
| import 'dart:io'; | ||
|
|
||
| import 'package:app/bridge/handlers/bridge_handler_base.dart'; | ||
| import 'package:app/permissions/FirebaseConfig.dart'; | ||
| import 'package:app/utils/env/env.dart'; | ||
| import 'package:flutter/services.dart'; | ||
| import 'package:flutter_inappwebview/flutter_inappwebview.dart'; | ||
|
|
||
| /// 디바이스 토큰, 햅틱, 환경 전환 관련 브릿지 핸들러 | ||
| mixin DeviceBridgeHandler on BridgeHandlerBase { | ||
| Future<void> sendDeviceToken() async { | ||
| try { | ||
| String? token = await getDeviceToken(); | ||
|
|
||
| if (token == null) { | ||
| logger.w("Device token is null"); | ||
| return; | ||
| } | ||
|
|
||
| String platformType = Platform.isIOS ? "IOS" : "ANDROID"; | ||
| await controller.evaluateJavascript( | ||
| source: "getDeviceToken('$token', '$platformType')", | ||
| ); | ||
| } catch (e) { | ||
| logger.e("Error getting device token: $e"); | ||
| } | ||
| } | ||
|
|
||
| Future<void> triggerHaptic(List<dynamic> arguments) async { | ||
| if (arguments.isEmpty) { | ||
| logger.w('햅틱 피드백 타입이 전달되지 않았습니다.'); | ||
| return; | ||
| } | ||
|
|
||
| try { | ||
| if (arguments[0] is Map) { | ||
| final Map<String, dynamic> hapticArgs = | ||
| Map<String, dynamic>.from(arguments[0]); | ||
| final hapticType = (hapticArgs['type'] as String?)?.toLowerCase(); | ||
|
|
||
| if (hapticType == null) { | ||
| logger.w('Haptic feedback type not specified in arguments'); | ||
| return; | ||
| } | ||
|
|
||
| switch (hapticType) { | ||
| case 'light': | ||
| await HapticFeedback.lightImpact(); | ||
| break; | ||
| case 'medium': | ||
| await HapticFeedback.mediumImpact(); | ||
| break; | ||
| case 'heavy': | ||
| await HapticFeedback.heavyImpact(); | ||
| break; | ||
| case 'selection': | ||
| await HapticFeedback.selectionClick(); | ||
| break; | ||
| case 'vibrate': | ||
| await HapticFeedback.vibrate(); | ||
| break; | ||
| default: | ||
| logger.w('Unknown haptic feedback type: $hapticType'); | ||
| } | ||
| } else { | ||
| logger.w( | ||
| 'Haptic feedback arguments should be an object with type property'); | ||
| } | ||
| } catch (e) { | ||
| logger.e('Error triggering haptic feedback: $e'); | ||
| } | ||
| } | ||
|
|
||
| Future<void> switchEnvironment(List<dynamic> arguments) async { | ||
| logger.d('switchEnvironment called with arguments: $arguments'); | ||
| if (arguments.isNotEmpty && arguments[0] is String) { | ||
| final env = arguments[0] as String; | ||
| String url; | ||
| if (env == 'prod') { | ||
| url = 'https://bottle-note.com/'; | ||
| } else if (env == 'dev') { | ||
| url = 'https://development.bottle-note.com/'; | ||
| } else { | ||
| url = Env.webViewUrl; | ||
| } | ||
| await controller.loadUrl(urlRequest: URLRequest(url: WebUri(url))); | ||
| } | ||
| } | ||
| } |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[P1]
onHideLoading이evaluateJavascript성공을 전제로 호출되고 있어, JS 실행이 실패하면 로딩이 영구히 남을 수 있습니다.try/finally로onHideLoading?.call()을 보장하고, 에러 시 JS 호출도 실패할 수 있으니 그 부분도 별도 보호 로직이 필요합니다.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Resolved in
0bc0dba변경 내용:
handleKakaoLogin/handleAppleLogin에서onHideLoading을finally블록으로 이동하여 로딩 해제를 보장합니다. JS 에러 콜백도 별도 try-catch로 보호했습니다.