first implementation finished
This commit is contained in:
@@ -0,0 +1,23 @@
|
||||
import 'package:home_widget/home_widget.dart';
|
||||
import 'package:kagi_bang_bang/domain/entities/received_parameter.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:rxdart/rxdart.dart';
|
||||
|
||||
part 'home_widget.g.dart';
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
FutureOr<bool> widgetPinnable(WidgetPinnableRef ref) async {
|
||||
return await HomeWidget.isRequestPinWidgetSupported() ?? false;
|
||||
}
|
||||
|
||||
@riverpod
|
||||
Raw<Stream<ReceivedParameter>> appWidgetLaunchStream(
|
||||
AppWidgetLaunchStreamRef ref,
|
||||
) {
|
||||
// ignore: discarded_futures
|
||||
final initialStream = HomeWidget.initiallyLaunchedFromHomeWidget().asStream();
|
||||
|
||||
return ConcatStream([initialStream, HomeWidget.widgetClicked])
|
||||
.whereNotNull()
|
||||
.map((uri) => ReceivedParameter(null, uri.host));
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'home_widget.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
String _$widgetPinnableHash() => r'c39a8b473a92ff81fa772d7c235b10736e4a49bd';
|
||||
|
||||
/// See also [widgetPinnable].
|
||||
@ProviderFor(widgetPinnable)
|
||||
final widgetPinnableProvider = FutureProvider<bool>.internal(
|
||||
widgetPinnable,
|
||||
name: r'widgetPinnableProvider',
|
||||
debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product')
|
||||
? null
|
||||
: _$widgetPinnableHash,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
typedef WidgetPinnableRef = FutureProviderRef<bool>;
|
||||
String _$appWidgetLaunchStreamHash() =>
|
||||
r'1cda869c62e270be74efcb9b052bc498cfbd98a5';
|
||||
|
||||
/// See also [appWidgetLaunchStream].
|
||||
@ProviderFor(appWidgetLaunchStream)
|
||||
final appWidgetLaunchStreamProvider =
|
||||
AutoDisposeProvider<Raw<Stream<ReceivedParameter>>>.internal(
|
||||
appWidgetLaunchStream,
|
||||
name: r'appWidgetLaunchStreamProvider',
|
||||
debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product')
|
||||
? null
|
||||
: _$appWidgetLaunchStreamHash,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
typedef AppWidgetLaunchStreamRef
|
||||
= AutoDisposeProviderRef<Raw<Stream<ReceivedParameter>>>;
|
||||
// ignore_for_file: type=lint
|
||||
// ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member
|
||||
@@ -0,0 +1,37 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:exceptions/exceptions.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:kagi_bang_bang/core/http_error_handler.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
part 'autosuggest.g.dart';
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
class KagiAutosuggestService extends _$KagiAutosuggestService {
|
||||
static final _baseUrl = Uri.https('kagi.com', 'api/autosuggest');
|
||||
|
||||
late http.Client _client;
|
||||
|
||||
@override
|
||||
void build() {
|
||||
_client = http.Client();
|
||||
}
|
||||
|
||||
Future<Result<List<String>>> getSuggestions(String query) async {
|
||||
return Result.fromAsync(
|
||||
() async {
|
||||
final response =
|
||||
await _client.get(_baseUrl.replace(queryParameters: {'q': query}));
|
||||
|
||||
final results = jsonDecode(response.body) as List;
|
||||
return switch (results.last) {
|
||||
final String result => [result],
|
||||
final List resultList => resultList.cast(),
|
||||
_ => []
|
||||
};
|
||||
},
|
||||
exceptionHandler: handleHttpError,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'autosuggest.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
String _$kagiAutosuggestServiceHash() =>
|
||||
r'97fa2170d6756f55a2c6d8454cfc3d8c33ded914';
|
||||
|
||||
/// See also [KagiAutosuggestService].
|
||||
@ProviderFor(KagiAutosuggestService)
|
||||
final kagiAutosuggestServiceProvider =
|
||||
NotifierProvider<KagiAutosuggestService, void>.internal(
|
||||
KagiAutosuggestService.new,
|
||||
name: r'kagiAutosuggestServiceProvider',
|
||||
debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product')
|
||||
? null
|
||||
: _$kagiAutosuggestServiceHash,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
typedef _$KagiAutosuggestService = Notifier<void>;
|
||||
// ignore_for_file: type=lint
|
||||
// ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member
|
||||
@@ -0,0 +1,57 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:kagi_bang_bang/features/kagi/data/services/autosuggest.dart';
|
||||
import 'package:kagi_bang_bang/utils/lru_cache.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:rxdart/rxdart.dart';
|
||||
|
||||
part 'autosuggest.g.dart';
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
class AutosuggestRepository extends _$AutosuggestRepository {
|
||||
final LRUCache<String, List<String>> _cache;
|
||||
|
||||
late StreamController<String> _queryStreamController;
|
||||
|
||||
AutosuggestRepository() : _cache = LRUCache(100);
|
||||
|
||||
void addQuery(String query) {
|
||||
_queryStreamController.add(query);
|
||||
}
|
||||
|
||||
@override
|
||||
Raw<Stream<List<String>>> build() {
|
||||
_queryStreamController = StreamController();
|
||||
ref.onDispose(() async {
|
||||
await _queryStreamController.close();
|
||||
});
|
||||
|
||||
return _queryStreamController.stream
|
||||
.sampleTime(const Duration(milliseconds: 100))
|
||||
.switchMap<List<String>>(
|
||||
(query) {
|
||||
if (query.isEmpty) {
|
||||
return Stream.value([]);
|
||||
}
|
||||
|
||||
final cached = _cache.get(query);
|
||||
if (cached != null) {
|
||||
return Stream.value(cached);
|
||||
}
|
||||
|
||||
return ref
|
||||
.read(kagiAutosuggestServiceProvider.notifier)
|
||||
// ignore: discarded_futures
|
||||
.getSuggestions(query)
|
||||
// ignore: discarded_futures
|
||||
.then((result) {
|
||||
result.onSuccess((result) {
|
||||
_cache.set(query, result);
|
||||
});
|
||||
|
||||
return result.value;
|
||||
}).asStream();
|
||||
},
|
||||
).asBroadcastStream();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'autosuggest.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
String _$autosuggestRepositoryHash() =>
|
||||
r'48d6bf45d648871f8570edfe1e0b394019084695';
|
||||
|
||||
/// See also [AutosuggestRepository].
|
||||
@ProviderFor(AutosuggestRepository)
|
||||
final autosuggestRepositoryProvider =
|
||||
NotifierProvider<AutosuggestRepository, Raw<Stream<List<String>>>>.internal(
|
||||
AutosuggestRepository.new,
|
||||
name: r'autosuggestRepositoryProvider',
|
||||
debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product')
|
||||
? null
|
||||
: _$autosuggestRepositoryHash,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
typedef _$AutosuggestRepository = Notifier<Raw<Stream<List<String>>>>;
|
||||
// ignore_for_file: type=lint
|
||||
// ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member
|
||||
@@ -0,0 +1,46 @@
|
||||
enum KagiTool { search, assistant, summarizer }
|
||||
|
||||
enum AssistantMode {
|
||||
research(7),
|
||||
code(5),
|
||||
chat(4),
|
||||
custom(6);
|
||||
|
||||
final int value;
|
||||
|
||||
const AssistantMode(this.value);
|
||||
}
|
||||
|
||||
enum ResearchVariant {
|
||||
fast(1),
|
||||
expert(2);
|
||||
|
||||
final int value;
|
||||
|
||||
const ResearchVariant(this.value);
|
||||
}
|
||||
|
||||
enum ChatModel {
|
||||
gpt35Turbo('GPT 3.5 Turbo', 1),
|
||||
gpt4('GPT 4', 2),
|
||||
gpt4Turbo('GPT 4 Turbo', 7),
|
||||
claude3Haiku('Claude 3 Haiku', 13),
|
||||
claude3Sonnet('Claude 3 Sonnet', 14),
|
||||
claude3Opus('Claude 3 Opus', 12),
|
||||
mistralSmall('Mistral Small', 10),
|
||||
mistralLarge('Mistral Large', 11);
|
||||
|
||||
final int value;
|
||||
final String label;
|
||||
|
||||
const ChatModel(this.label, this.value);
|
||||
}
|
||||
|
||||
enum SummarizerMode {
|
||||
keyMoments('takeaway'),
|
||||
summary('summary');
|
||||
|
||||
final String value;
|
||||
|
||||
const SummarizerMode(this.value);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import 'package:kagi_bang_bang/features/search_browser/domain/entities/modes.dart';
|
||||
|
||||
sealed class Sheet {}
|
||||
|
||||
class CreateTab extends Sheet {
|
||||
final String? content;
|
||||
final KagiTool? preferredTool;
|
||||
|
||||
bool get hasParameters => content != null || preferredTool != null;
|
||||
|
||||
CreateTab({this.content, this.preferredTool});
|
||||
}
|
||||
|
||||
class ViewTabs extends Sheet {}
|
||||
@@ -0,0 +1,44 @@
|
||||
// ignore_for_file: use_setters_to_change_properties
|
||||
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:kagi_bang_bang/features/search_browser/domain/entities/sheet.dart';
|
||||
import 'package:kagi_bang_bang/features/search_browser/domain/services/create_tab.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
part 'providers.g.dart';
|
||||
|
||||
@Riverpod()
|
||||
class OverlayDialog extends _$OverlayDialog {
|
||||
@override
|
||||
Widget? build() {
|
||||
return null;
|
||||
}
|
||||
|
||||
void show(Widget dialog) {
|
||||
state = dialog;
|
||||
}
|
||||
|
||||
void dismiss() {
|
||||
state = null;
|
||||
}
|
||||
}
|
||||
|
||||
@Riverpod()
|
||||
class BottomSheet extends _$BottomSheet {
|
||||
@override
|
||||
Sheet? build() {
|
||||
return ref.watch(
|
||||
createTabStreamProvider.select(
|
||||
(value) => value.valueOrNull,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void show(Sheet sheet) {
|
||||
state = sheet;
|
||||
}
|
||||
|
||||
void dismiss() {
|
||||
state = null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'providers.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
String _$overlayDialogHash() => r'7a0376fff0ba12c70a257a47391e7c049dabd36d';
|
||||
|
||||
/// See also [OverlayDialog].
|
||||
@ProviderFor(OverlayDialog)
|
||||
final overlayDialogProvider =
|
||||
AutoDisposeNotifierProvider<OverlayDialog, Widget?>.internal(
|
||||
OverlayDialog.new,
|
||||
name: r'overlayDialogProvider',
|
||||
debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product')
|
||||
? null
|
||||
: _$overlayDialogHash,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
typedef _$OverlayDialog = AutoDisposeNotifier<Widget?>;
|
||||
String _$bottomSheetHash() => r'31108d6d80d5b858024a8a8ae9ebb9c650eabe70';
|
||||
|
||||
/// See also [BottomSheet].
|
||||
@ProviderFor(BottomSheet)
|
||||
final bottomSheetProvider =
|
||||
AutoDisposeNotifierProvider<BottomSheet, Sheet?>.internal(
|
||||
BottomSheet.new,
|
||||
name: r'bottomSheetProvider',
|
||||
debugGetCreateSourceHash:
|
||||
const bool.fromEnvironment('dart.vm.product') ? null : _$bottomSheetHash,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
typedef _$BottomSheet = AutoDisposeNotifier<Sheet?>;
|
||||
// ignore_for_file: type=lint
|
||||
// ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member
|
||||
@@ -0,0 +1,53 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:collection/collection.dart';
|
||||
import 'package:kagi_bang_bang/domain/entities/received_parameter.dart';
|
||||
import 'package:kagi_bang_bang/features/app_widget/domain/services/home_widget.dart';
|
||||
import 'package:kagi_bang_bang/features/search_browser/domain/entities/modes.dart';
|
||||
import 'package:kagi_bang_bang/features/search_browser/domain/entities/sheet.dart';
|
||||
import 'package:kagi_bang_bang/features/share_intent/domain/services/sharing_intent.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:rxdart/rxdart.dart';
|
||||
|
||||
part 'create_tab.g.dart';
|
||||
|
||||
final _parameterToCreateTabTransformer =
|
||||
StreamTransformer<ReceivedParameter, CreateTab>.fromHandlers(
|
||||
handleData: (parameter, sink) {
|
||||
final createTab = CreateTab(
|
||||
preferredTool: KagiTool.values
|
||||
.firstWhereOrNull((tool) => tool.name == parameter.tool),
|
||||
content: parameter.content,
|
||||
);
|
||||
|
||||
if (createTab.hasParameters) {
|
||||
sink.add(createTab);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
@Riverpod()
|
||||
class CreateTabStream extends _$CreateTabStream {
|
||||
late StreamController<CreateTab> _streamController;
|
||||
|
||||
@override
|
||||
Stream<CreateTab> build() {
|
||||
_streamController = StreamController();
|
||||
ref.onDispose(() async {
|
||||
await _streamController.close();
|
||||
});
|
||||
|
||||
final sharingItentStream = ref.watch(sharingIntentStreamProvider);
|
||||
final appWidgetLaunchStream = ref.watch(appWidgetLaunchStreamProvider);
|
||||
|
||||
return MergeStream([
|
||||
sharingItentStream.transform(_parameterToCreateTabTransformer),
|
||||
appWidgetLaunchStream.transform(_parameterToCreateTabTransformer),
|
||||
_streamController.stream,
|
||||
]);
|
||||
}
|
||||
|
||||
void createTab(CreateTab parameter) {
|
||||
_streamController.add(parameter);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'create_tab.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
String _$createTabStreamHash() => r'3e85020edbebf3ec9927dba6d05af9f06a360a14';
|
||||
|
||||
/// See also [CreateTabStream].
|
||||
@ProviderFor(CreateTabStream)
|
||||
final createTabStreamProvider =
|
||||
AutoDisposeStreamNotifierProvider<CreateTabStream, CreateTab>.internal(
|
||||
CreateTabStream.new,
|
||||
name: r'createTabStreamProvider',
|
||||
debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product')
|
||||
? null
|
||||
: _$createTabStreamHash,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
typedef _$CreateTabStream = AutoDisposeStreamNotifier<CreateTab>;
|
||||
// ignore_for_file: type=lint
|
||||
// ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member
|
||||
@@ -0,0 +1,53 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
part 'session.g.dart';
|
||||
|
||||
@Riverpod()
|
||||
class SessionService extends _$SessionService {
|
||||
final _cookieManager = CookieManager.instance();
|
||||
|
||||
Future<void> setKagiSession(String session) async {
|
||||
await _cookieManager.setCookie(
|
||||
url: WebUri.uri(Uri.https('kagi.com')),
|
||||
name: 'kagi_session',
|
||||
value: session,
|
||||
domain: 'kagi.com',
|
||||
isHttpOnly: true,
|
||||
isSecure: true,
|
||||
sameSite: HTTPCookieSameSitePolicy.LAX,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> clearAllData() async {
|
||||
await _cookieManager.deleteAllCookies();
|
||||
|
||||
final webViewLoaded = Completer<void>();
|
||||
final headlessWebView = HeadlessInAppWebView(
|
||||
initialSettings: InAppWebViewSettings(
|
||||
//Clears all data on (just) Android
|
||||
incognito: true,
|
||||
//Clear other stuff
|
||||
clearCache: true,
|
||||
clearSessionCache: true,
|
||||
),
|
||||
onWebViewCreated: (controller) {
|
||||
//wait until settings are applied for sure
|
||||
webViewLoaded.complete();
|
||||
},
|
||||
);
|
||||
|
||||
unawaited(headlessWebView.run());
|
||||
|
||||
await webViewLoaded.future.whenComplete(() => headlessWebView..dispose());
|
||||
}
|
||||
|
||||
void initializationDone() {
|
||||
state = true;
|
||||
}
|
||||
|
||||
@override
|
||||
bool build() => false;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'session.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
String _$sessionServiceHash() => r'48126bad2cb8d5c38296307bede64bf549365acf';
|
||||
|
||||
/// See also [SessionService].
|
||||
@ProviderFor(SessionService)
|
||||
final sessionServiceProvider =
|
||||
AutoDisposeNotifierProvider<SessionService, bool>.internal(
|
||||
SessionService.new,
|
||||
name: r'sessionServiceProvider',
|
||||
debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product')
|
||||
? null
|
||||
: _$sessionServiceHash,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
typedef _$SessionService = AutoDisposeNotifier<bool>;
|
||||
// ignore_for_file: type=lint
|
||||
// ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member
|
||||
@@ -0,0 +1,344 @@
|
||||
import 'package:animations/animations.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_hooks/flutter_hooks.dart';
|
||||
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
|
||||
import 'package:flutter_material_design_icons/flutter_material_design_icons.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:kagi_bang_bang/core/routing/routes.dart';
|
||||
import 'package:kagi_bang_bang/features/search_browser/domain/entities/modes.dart';
|
||||
import 'package:kagi_bang_bang/features/search_browser/domain/entities/sheet.dart';
|
||||
import 'package:kagi_bang_bang/features/search_browser/domain/providers.dart';
|
||||
import 'package:kagi_bang_bang/features/search_browser/domain/services/create_tab.dart';
|
||||
import 'package:kagi_bang_bang/features/search_browser/domain/services/session.dart';
|
||||
import 'package:kagi_bang_bang/features/search_browser/presentation/widgets/app_bar_title.dart';
|
||||
import 'package:kagi_bang_bang/features/search_browser/presentation/widgets/sheets/shared_content_sheet.dart';
|
||||
import 'package:kagi_bang_bang/features/search_browser/presentation/widgets/sheets/view_tabs_sheet.dart';
|
||||
import 'package:kagi_bang_bang/features/search_browser/presentation/widgets/tabs_action_button.dart';
|
||||
import 'package:kagi_bang_bang/features/settings/data/repositories/settings_repository.dart';
|
||||
import 'package:kagi_bang_bang/features/web_view/domain/repositories/web_view.dart';
|
||||
import 'package:kagi_bang_bang/features/web_view/presentation/controllers/switch_new_tab.dart';
|
||||
import 'package:kagi_bang_bang/features/web_view/presentation/widgets/web_page_dialog.dart';
|
||||
import 'package:kagi_bang_bang/presentation/hooks/listenable_callback.dart';
|
||||
import 'package:kagi_bang_bang/presentation/hooks/overlay_portal_controller.dart';
|
||||
import 'package:kagi_bang_bang/presentation/widgets/animated_indexed_stack.dart';
|
||||
import 'package:kagi_bang_bang/utils/ui_helper.dart' as ui_helper;
|
||||
import 'package:share_plus/share_plus.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
class KagiScreen extends HookConsumerWidget {
|
||||
const KagiScreen({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final displayedSheet = ref.watch(bottomSheetProvider);
|
||||
final displayedOverlayDialog = ref.watch(overlayDialogProvider);
|
||||
|
||||
final lastBackButtonPress = useRef<DateTime?>(null);
|
||||
final webViewController = useRef<InAppWebViewController?>(null);
|
||||
|
||||
final overlayController = useOverlayPortalController();
|
||||
|
||||
ref.listen(
|
||||
overlayDialogProvider,
|
||||
(previous, next) {
|
||||
if (next != null) {
|
||||
overlayController.show();
|
||||
} else {
|
||||
overlayController.hide();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
ref.listen(
|
||||
settingsRepositoryProvider
|
||||
.select((value) => value.valueOrNull?.kagiSession),
|
||||
(previous, next) async {
|
||||
if (next != null && next.isNotEmpty) {
|
||||
await ref.read(sessionServiceProvider.notifier).setKagiSession(next);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
automaticallyImplyLeading: false,
|
||||
title: AppBarTitle(
|
||||
onTap: () {
|
||||
final page = ref.read(webViewTabControllerProvider)?.page.value;
|
||||
|
||||
if (page != null) {
|
||||
ref.watch(overlayDialogProvider.notifier).show(
|
||||
WebPageDialog(
|
||||
page: page,
|
||||
webViewController: webViewController.value,
|
||||
onDismiss:
|
||||
ref.watch(overlayDialogProvider.notifier).dismiss,
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
),
|
||||
actions: [
|
||||
TabsActionButton(
|
||||
onTap: () {
|
||||
if (displayedSheet case ViewTabs()) {
|
||||
ref.read(bottomSheetProvider.notifier).dismiss();
|
||||
} else {
|
||||
ref.read(bottomSheetProvider.notifier).show(ViewTabs());
|
||||
}
|
||||
},
|
||||
),
|
||||
MenuAnchor(
|
||||
builder: (context, controller, child) {
|
||||
return IconButton(
|
||||
onPressed: () {
|
||||
if (controller.isOpen) {
|
||||
controller.close();
|
||||
} else {
|
||||
controller.open();
|
||||
}
|
||||
},
|
||||
icon: const Icon(Icons.more_vert),
|
||||
);
|
||||
},
|
||||
menuChildren: [
|
||||
HookConsumer(
|
||||
builder: (context, ref, child) {
|
||||
final activeWebView = ref.watch(webViewTabControllerProvider);
|
||||
final history = useListenableSelector(
|
||||
activeWebView?.page,
|
||||
() =>
|
||||
activeWebView?.page.value.pageHistory ??
|
||||
(canGoBack: false, canGoForward: false),
|
||||
);
|
||||
|
||||
return Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: IconButton(
|
||||
onPressed: (history.canGoBack)
|
||||
? () async {
|
||||
await webViewController.value?.goBack();
|
||||
}
|
||||
: null,
|
||||
icon: const Icon(Icons.arrow_back),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 48, child: VerticalDivider()),
|
||||
Expanded(
|
||||
child: IconButton(
|
||||
onPressed: (history.canGoForward)
|
||||
? () async {
|
||||
await webViewController.value?.goForward();
|
||||
}
|
||||
: null,
|
||||
icon: const Icon(Icons.arrow_forward),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
const Divider(),
|
||||
MenuItemButton(
|
||||
onPressed: () async {
|
||||
await webViewController.value?.reload();
|
||||
},
|
||||
leadingIcon: const Icon(Icons.refresh),
|
||||
child: const Text('Reload'),
|
||||
),
|
||||
const Divider(),
|
||||
MenuItemButton(
|
||||
onPressed: () async {
|
||||
await context.push(SettingsRoute().location);
|
||||
},
|
||||
leadingIcon: const Icon(Icons.settings),
|
||||
child: const Text('Settings'),
|
||||
),
|
||||
const Divider(),
|
||||
MenuItemButton(
|
||||
onPressed: () async {
|
||||
final url = await webViewController.value?.getUrl();
|
||||
if (url != null) {
|
||||
await Share.shareUri(url);
|
||||
}
|
||||
},
|
||||
leadingIcon: const Icon(Icons.share),
|
||||
child: const Text('Share'),
|
||||
),
|
||||
MenuItemButton(
|
||||
onPressed: () async {
|
||||
final url = await webViewController.value?.getUrl();
|
||||
if (url != null) {
|
||||
if (!await launchUrl(
|
||||
url,
|
||||
mode: LaunchMode.externalApplication,
|
||||
)) {
|
||||
if (context.mounted) {
|
||||
ui_helper.showErrorMessage(
|
||||
context,
|
||||
'Could not launch URL ($url)',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
leadingIcon: const Icon(Icons.open_in_browser),
|
||||
child: const Text('Launch External'),
|
||||
),
|
||||
const Divider(),
|
||||
MenuItemButton(
|
||||
onPressed: () {
|
||||
ref.read(createTabStreamProvider.notifier).createTab(
|
||||
CreateTab(preferredTool: KagiTool.search),
|
||||
);
|
||||
},
|
||||
leadingIcon: const Icon(MdiIcons.searchWeb),
|
||||
child: const Text('Search'),
|
||||
),
|
||||
MenuItemButton(
|
||||
onPressed: () {
|
||||
ref.read(createTabStreamProvider.notifier).createTab(
|
||||
CreateTab(preferredTool: KagiTool.assistant),
|
||||
);
|
||||
},
|
||||
leadingIcon: const Icon(MdiIcons.brain),
|
||||
child: const Text('Assistant'),
|
||||
),
|
||||
MenuItemButton(
|
||||
onPressed: () {
|
||||
ref.read(createTabStreamProvider.notifier).createTab(
|
||||
CreateTab(preferredTool: KagiTool.summarizer),
|
||||
);
|
||||
},
|
||||
leadingIcon: const Icon(MdiIcons.text),
|
||||
child: const Text('Summarizer'),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
body: OverlayPortal(
|
||||
controller: overlayController,
|
||||
overlayChildBuilder: (context) {
|
||||
return displayedOverlayDialog!;
|
||||
},
|
||||
child: Listener(
|
||||
onPointerDown: (displayedSheet != null)
|
||||
? (_) {
|
||||
ref.read(bottomSheetProvider.notifier).dismiss();
|
||||
}
|
||||
: null,
|
||||
child: HookConsumer(
|
||||
builder: (context, ref, child) {
|
||||
final webViews = ref.watch(webViewRepositoryProvider);
|
||||
final activeWebView = ref.watch(webViewTabControllerProvider);
|
||||
useListenableCallback(activeWebView?.page, () {
|
||||
webViewController.value = activeWebView?.page.value.controller;
|
||||
});
|
||||
|
||||
return BackButtonListener(
|
||||
onBackButtonPressed: () async {
|
||||
if (activeWebView?.page.value.pageHistory.canGoBack == true) {
|
||||
await activeWebView?.page.value.controller?.goBack();
|
||||
return true;
|
||||
}
|
||||
|
||||
if (lastBackButtonPress.value != null &&
|
||||
lastBackButtonPress.value!.difference(DateTime.now()) <
|
||||
const Duration(seconds: 2)) {
|
||||
lastBackButtonPress.value = null;
|
||||
|
||||
return false;
|
||||
} else {
|
||||
lastBackButtonPress.value = DateTime.now();
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Please click BACK again to exit'),
|
||||
),
|
||||
);
|
||||
|
||||
return true;
|
||||
}
|
||||
},
|
||||
child: AnimatedIndexedStack(
|
||||
duration: const Duration(milliseconds: 250),
|
||||
transitionBuilder: (child, animation, secondaryAnimation) =>
|
||||
SharedAxisTransition(
|
||||
animation: animation,
|
||||
secondaryAnimation: secondaryAnimation,
|
||||
transitionType: SharedAxisTransitionType.horizontal,
|
||||
child: child,
|
||||
),
|
||||
key: ValueKey(
|
||||
(activeWebView != null)
|
||||
? webViews.keys
|
||||
.toList()
|
||||
.indexOf(activeWebView.page.value.key)
|
||||
: null,
|
||||
),
|
||||
index: (activeWebView != null)
|
||||
? webViews.keys
|
||||
.toList()
|
||||
.indexOf(activeWebView.page.value.key)
|
||||
: null,
|
||||
children: webViews.values.toList(),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
bottomSheet: (displayedSheet != null)
|
||||
? NotificationListener<DraggableScrollableNotification>(
|
||||
onNotification: (notification) {
|
||||
if (notification.extent <= 0.1) {
|
||||
ref.read(bottomSheetProvider.notifier).dismiss();
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
},
|
||||
child: switch (displayedSheet) {
|
||||
ViewTabs() => DraggableScrollableSheet(
|
||||
expand: false,
|
||||
minChildSize: 0.1,
|
||||
builder: (context, scrollController) {
|
||||
return SingleChildScrollView(
|
||||
controller: scrollController,
|
||||
child: ViewTabsSheet(
|
||||
onClose: () {
|
||||
ref.read(bottomSheetProvider.notifier).dismiss();
|
||||
},
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
final CreateTab parameter => DraggableScrollableSheet(
|
||||
expand: false,
|
||||
initialChildSize: 0.8,
|
||||
minChildSize: 0.1,
|
||||
builder: (context, scrollController) {
|
||||
return SingleChildScrollView(
|
||||
controller: scrollController,
|
||||
child: SharedContentSheet(
|
||||
key: ObjectKey(parameter),
|
||||
parameter: parameter,
|
||||
onSubmit: (url) async {
|
||||
await ref
|
||||
.read(switchNewTabControllerProvider.notifier)
|
||||
.add(url);
|
||||
|
||||
ref.read(bottomSheetProvider.notifier).dismiss();
|
||||
},
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
},
|
||||
)
|
||||
: null,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_hooks/flutter_hooks.dart';
|
||||
import 'package:flutter_material_design_icons/flutter_material_design_icons.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:kagi_bang_bang/features/web_view/domain/entities/web_view_page.dart';
|
||||
import 'package:kagi_bang_bang/features/web_view/domain/repositories/web_view.dart';
|
||||
import 'package:kagi_bang_bang/features/web_view/presentation/widgets/favicon.dart';
|
||||
import 'package:text_scroll/text_scroll.dart';
|
||||
|
||||
class AppBarTitle extends HookConsumerWidget {
|
||||
final void Function()? onTap;
|
||||
|
||||
const AppBarTitle({this.onTap, super.key});
|
||||
|
||||
Icon _securityStatusIcon(BuildContext context, WebViewPage page) {
|
||||
if (page.url.isScheme('http')) {
|
||||
return Icon(
|
||||
MdiIcons.lockOff,
|
||||
color: Theme.of(context).colorScheme.error,
|
||||
size: 14,
|
||||
);
|
||||
} else if (page.sslError != null) {
|
||||
return Icon(
|
||||
MdiIcons.lockAlert,
|
||||
color: Theme.of(context).colorScheme.errorContainer,
|
||||
size: 14,
|
||||
);
|
||||
} else {
|
||||
return const Icon(
|
||||
MdiIcons.lock,
|
||||
size: 14,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final activeWebView = ref.watch(webViewTabControllerProvider);
|
||||
if (activeWebView == null) {
|
||||
return SizedBox.shrink();
|
||||
}
|
||||
|
||||
final page = useValueListenable(activeWebView.page);
|
||||
|
||||
final theme = Theme.of(context);
|
||||
return GestureDetector(
|
||||
onTap: onTap,
|
||||
child: Row(
|
||||
children: [
|
||||
FaviconImage(
|
||||
webPageInfo: page,
|
||||
),
|
||||
const SizedBox(
|
||||
width: 8,
|
||||
),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
TextScroll(
|
||||
key: ValueKey(page.title),
|
||||
page.title ?? 'New Tab',
|
||||
style: theme.textTheme.bodyLarge
|
||||
?.copyWith(color: theme.colorScheme.onSurface),
|
||||
// mode: TextScrollMode.bouncing,
|
||||
velocity: const Velocity(pixelsPerSecond: Offset(75, 0)),
|
||||
delayBefore: const Duration(milliseconds: 500),
|
||||
pauseBetween: const Duration(milliseconds: 5000),
|
||||
fadedBorder: true,
|
||||
fadeBorderSide: FadeBorderSide.right,
|
||||
fadedBorderWidth: 0.05,
|
||||
intervalSpaces: 4,
|
||||
numberOfReps: 2,
|
||||
),
|
||||
Row(
|
||||
children: [
|
||||
_securityStatusIcon(context, page),
|
||||
const SizedBox(
|
||||
width: 4,
|
||||
),
|
||||
Text(
|
||||
page.url.authority,
|
||||
style: theme.textTheme.bodyMedium
|
||||
?.copyWith(color: theme.colorScheme.onSurface),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import 'package:expandable_page_view/expandable_page_view.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_hooks/flutter_hooks.dart';
|
||||
import 'package:flutter_material_design_icons/flutter_material_design_icons.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:kagi_bang_bang/features/search_browser/domain/entities/modes.dart';
|
||||
import 'package:kagi_bang_bang/features/search_browser/domain/entities/sheet.dart';
|
||||
import 'package:kagi_bang_bang/features/search_browser/presentation/widgets/tabs/assistant_tab.dart';
|
||||
import 'package:kagi_bang_bang/features/search_browser/presentation/widgets/tabs/search_tab.dart';
|
||||
import 'package:kagi_bang_bang/features/search_browser/presentation/widgets/tabs/summarize_tab.dart';
|
||||
import 'package:kagi_bang_bang/features/share_intent/domain/entities/shared_content.dart';
|
||||
import 'package:kagi_bang_bang/presentation/hooks/sync_page_tab.dart';
|
||||
|
||||
typedef OnSubmitUri = void Function(Uri url);
|
||||
|
||||
class SharedContentSheet extends HookConsumerWidget {
|
||||
final CreateTab parameter;
|
||||
final OnSubmitUri onSubmit;
|
||||
|
||||
const SharedContentSheet({
|
||||
required this.parameter,
|
||||
required this.onSubmit,
|
||||
super.key,
|
||||
});
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final sharedContent = useMemoized(
|
||||
() => (parameter.content != null)
|
||||
? SharedContent.parse(parameter.content!)
|
||||
: null,
|
||||
);
|
||||
|
||||
final tabController = useTabController(
|
||||
initialLength: KagiTool.values.length,
|
||||
initialIndex: parameter.preferredTool?.index ??
|
||||
switch (sharedContent) {
|
||||
SharedText(text: final text) => (text.length > 25)
|
||||
? KagiTool.assistant.index
|
||||
: KagiTool.search.index,
|
||||
SharedUrl() => KagiTool.summarizer.index,
|
||||
null => KagiTool.assistant.index,
|
||||
},
|
||||
);
|
||||
final pageController = usePageController(initialPage: tabController.index);
|
||||
|
||||
useSyncPageWithTab(tabController, pageController);
|
||||
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
TabBar(
|
||||
controller: tabController,
|
||||
tabs: const [
|
||||
Tab(
|
||||
icon: Icon(MdiIcons.searchWeb),
|
||||
text: 'Search',
|
||||
),
|
||||
Tab(
|
||||
icon: Icon(MdiIcons.brain),
|
||||
text: 'Assistant',
|
||||
),
|
||||
Tab(
|
||||
icon: Icon(MdiIcons.text),
|
||||
text: 'Summarize',
|
||||
),
|
||||
],
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8.0, horizontal: 12.0),
|
||||
child: ExpandablePageView(
|
||||
controller: pageController,
|
||||
children: [
|
||||
SearchTab(
|
||||
sharedContent: sharedContent,
|
||||
onSubmit: onSubmit,
|
||||
),
|
||||
AssistantTab(
|
||||
sharedContent: sharedContent,
|
||||
onSubmit: onSubmit,
|
||||
),
|
||||
SummarizeTab(
|
||||
sharedContent: sharedContent,
|
||||
onSubmit: onSubmit,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:kagi_bang_bang/features/web_view/domain/repositories/web_view.dart';
|
||||
import 'package:kagi_bang_bang/features/web_view/presentation/controllers/switch_new_tab.dart';
|
||||
import 'package:kagi_bang_bang/features/web_view/presentation/widgets/web_view_tab.dart';
|
||||
|
||||
class ViewTabsSheet extends HookConsumerWidget {
|
||||
final VoidCallback onClose;
|
||||
|
||||
const ViewTabsSheet({required this.onClose, super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
TextButton.icon(
|
||||
onPressed: () async {
|
||||
await ref
|
||||
.read(switchNewTabControllerProvider.notifier)
|
||||
.add(Uri.https('kagi.com'));
|
||||
|
||||
onClose();
|
||||
},
|
||||
icon: const Icon(Icons.add),
|
||||
label: const Text('New Tab'),
|
||||
),
|
||||
TextButton.icon(
|
||||
onPressed: () async {
|
||||
await ref
|
||||
.read(webViewRepositoryProvider.notifier)
|
||||
.closeAllTabs();
|
||||
},
|
||||
icon: const Icon(Icons.delete),
|
||||
label: const Text('Close All'),
|
||||
),
|
||||
],
|
||||
),
|
||||
Consumer(
|
||||
builder: (context, ref, child) {
|
||||
final tabs = ref.watch(
|
||||
webViewRepositoryProvider.select((tabs) => tabs.values),
|
||||
);
|
||||
final activeTab = ref.watch(
|
||||
webViewTabControllerProvider.select(
|
||||
(webView) => webView?.page.value.key,
|
||||
),
|
||||
);
|
||||
|
||||
return GridView.count(
|
||||
shrinkWrap: true,
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
childAspectRatio: 0.75,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 4.0),
|
||||
mainAxisSpacing: 8.0,
|
||||
crossAxisSpacing: 8.0,
|
||||
crossAxisCount: 2,
|
||||
children: tabs
|
||||
.map(
|
||||
(webView) => WebViewTab(
|
||||
webView: webView,
|
||||
isActive: webView.key == activeTab,
|
||||
onClose: onClose,
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
import 'package:expandable_page_view/expandable_page_view.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_hooks/flutter_hooks.dart';
|
||||
import 'package:flutter_material_design_icons/flutter_material_design_icons.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:kagi_bang_bang/features/search_browser/domain/entities/modes.dart';
|
||||
import 'package:kagi_bang_bang/features/search_browser/presentation/widgets/sheets/shared_content_sheet.dart';
|
||||
import 'package:kagi_bang_bang/features/search_browser/utils/url_builder.dart'
|
||||
as uri_builder;
|
||||
import 'package:kagi_bang_bang/features/share_intent/domain/entities/shared_content.dart';
|
||||
import 'package:kagi_bang_bang/presentation/hooks/sync_page_tab.dart';
|
||||
|
||||
class AssistantTab extends HookConsumerWidget {
|
||||
final SharedContent? sharedContent;
|
||||
final OnSubmitUri onSubmit;
|
||||
|
||||
const AssistantTab({
|
||||
required this.sharedContent,
|
||||
required this.onSubmit,
|
||||
super.key,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
useAutomaticKeepAlive();
|
||||
|
||||
final formKey = useMemoized(() => GlobalKey<FormState>());
|
||||
final textController =
|
||||
useTextEditingController(text: sharedContent?.toString());
|
||||
|
||||
final tabController =
|
||||
useTabController(initialLength: AssistantMode.values.length);
|
||||
final pageController = usePageController(initialPage: tabController.index);
|
||||
|
||||
useSyncPageWithTab(tabController, pageController);
|
||||
|
||||
final researchVariant = useState(ResearchVariant.expert);
|
||||
final chatModel = useState(ChatModel.gpt4Turbo);
|
||||
|
||||
return Form(
|
||||
key: formKey,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
TabBar.secondary(
|
||||
controller: tabController,
|
||||
tabs: const [
|
||||
Tab(
|
||||
text: 'Research',
|
||||
icon: Icon(MdiIcons.cloudSearch),
|
||||
),
|
||||
Tab(
|
||||
text: 'Code',
|
||||
icon: Icon(MdiIcons.codeJson),
|
||||
),
|
||||
Tab(
|
||||
text: 'Chat',
|
||||
icon: Icon(MdiIcons.commentTextMultiple),
|
||||
),
|
||||
Tab(
|
||||
text: 'Custom',
|
||||
icon: Icon(MdiIcons.creation),
|
||||
),
|
||||
],
|
||||
),
|
||||
ExpandablePageView(
|
||||
controller: pageController,
|
||||
children: [
|
||||
Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const SizedBox(
|
||||
height: 12,
|
||||
),
|
||||
SegmentedButton<ResearchVariant>(
|
||||
segments: const [
|
||||
ButtonSegment(
|
||||
value: ResearchVariant.expert,
|
||||
icon: Icon(MdiIcons.textSearch),
|
||||
label: Text('Research'),
|
||||
),
|
||||
ButtonSegment(
|
||||
value: ResearchVariant.fast,
|
||||
icon: Icon(MdiIcons.invoiceTextFast),
|
||||
label: Text('Fast'),
|
||||
),
|
||||
],
|
||||
selected: {researchVariant.value},
|
||||
onSelectionChanged: (value) {
|
||||
researchVariant.value = value.first;
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox.shrink(),
|
||||
Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const SizedBox(
|
||||
height: 12,
|
||||
),
|
||||
DropdownMenu<ChatModel>(
|
||||
initialSelection: chatModel.value,
|
||||
expandedInsets: EdgeInsets.zero,
|
||||
label: const Text('Model'),
|
||||
inputDecorationTheme: const InputDecorationTheme(),
|
||||
dropdownMenuEntries: ChatModel.values
|
||||
.map(
|
||||
(model) => DropdownMenuEntry(
|
||||
value: model,
|
||||
label: model.label,
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
onSelected: (value) {
|
||||
chatModel.value = value!;
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox.shrink(),
|
||||
],
|
||||
),
|
||||
const SizedBox(
|
||||
height: 12,
|
||||
),
|
||||
TextFormField(
|
||||
controller: textController,
|
||||
decoration: const InputDecoration(
|
||||
// border: OutlineInputBorder(),
|
||||
label: Text('Prompt'),
|
||||
),
|
||||
maxLines: null,
|
||||
validator: (value) {
|
||||
if (value?.isEmpty ?? true) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(
|
||||
height: 12,
|
||||
),
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: FilledButton.icon(
|
||||
onPressed: () {
|
||||
if (formKey.currentState?.validate() ?? false) {
|
||||
onSubmit(
|
||||
uri_builder.assistantUri(
|
||||
prompt: textController.text,
|
||||
assistantMode: AssistantMode.values[tabController.index],
|
||||
researchVariant: researchVariant.value,
|
||||
chatModel: chatModel.value,
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
label: const Text('Submit'),
|
||||
icon: const Icon(MdiIcons.invoiceTextSend),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_hooks/flutter_hooks.dart';
|
||||
import 'package:flutter_material_design_icons/flutter_material_design_icons.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:kagi_bang_bang/features/kagi/domain/repositories/autosuggest.dart';
|
||||
import 'package:kagi_bang_bang/features/search_browser/presentation/widgets/sheets/shared_content_sheet.dart';
|
||||
import 'package:kagi_bang_bang/features/search_browser/utils/url_builder.dart'
|
||||
as uri_builder;
|
||||
import 'package:kagi_bang_bang/features/share_intent/domain/entities/shared_content.dart';
|
||||
import 'package:kagi_bang_bang/presentation/widgets/autocomplete.dart';
|
||||
import 'package:kagi_bang_bang/utils/ui_helper.dart' as ui_helper;
|
||||
import 'package:speech_to_text_google_dialog/speech_to_text_google_dialog.dart';
|
||||
|
||||
// The default Material-style Autocomplete options.
|
||||
class _AutocompleteOptions<T extends Object> extends StatelessWidget {
|
||||
const _AutocompleteOptions({
|
||||
super.key,
|
||||
required this.displayStringForOption,
|
||||
required this.onSelected,
|
||||
required this.openDirection,
|
||||
required this.options,
|
||||
required this.maxOptionsHeight,
|
||||
});
|
||||
|
||||
final AutocompleteOptionToString<T> displayStringForOption;
|
||||
|
||||
final AutocompleteOnSelected<T> onSelected;
|
||||
final OptionsViewOpenDirection openDirection;
|
||||
|
||||
final Iterable<T> options;
|
||||
final double maxOptionsHeight;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final AlignmentDirectional optionsAlignment = switch (openDirection) {
|
||||
OptionsViewOpenDirection.up => AlignmentDirectional.bottomStart,
|
||||
OptionsViewOpenDirection.down => AlignmentDirectional.topStart,
|
||||
};
|
||||
return Align(
|
||||
alignment: optionsAlignment,
|
||||
child: Material(
|
||||
elevation: 4.0,
|
||||
child: ConstrainedBox(
|
||||
constraints: BoxConstraints(maxHeight: maxOptionsHeight),
|
||||
child: ListView.builder(
|
||||
padding: EdgeInsets.zero,
|
||||
shrinkWrap: true,
|
||||
reverse: switch (openDirection) {
|
||||
OptionsViewOpenDirection.up => true,
|
||||
OptionsViewOpenDirection.down => false,
|
||||
},
|
||||
itemCount: options.length,
|
||||
itemBuilder: (BuildContext context, int index) {
|
||||
final T option = options.elementAt(index);
|
||||
return InkWell(
|
||||
onTap: () {
|
||||
onSelected(option);
|
||||
},
|
||||
child: Builder(
|
||||
builder: (BuildContext context) {
|
||||
final bool highlight =
|
||||
AutocompleteHighlightedOption.of(context) == index;
|
||||
// if (highlight) {
|
||||
// SchedulerBinding.instance.addPostFrameCallback(
|
||||
// (Duration timeStamp) async {
|
||||
// await Scrollable.ensureVisible(
|
||||
// context,
|
||||
// alignment: 0.5,
|
||||
// );
|
||||
// },
|
||||
// debugLabel: 'AutocompleteOptions.ensureVisible',
|
||||
// );
|
||||
// }
|
||||
return Container(
|
||||
color: highlight ? Theme.of(context).focusColor : null,
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Text(displayStringForOption(option)),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class SearchTab extends HookConsumerWidget {
|
||||
final SharedContent? sharedContent;
|
||||
final OnSubmitUri onSubmit;
|
||||
|
||||
const SearchTab({
|
||||
required this.sharedContent,
|
||||
required this.onSubmit,
|
||||
super.key,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
useAutomaticKeepAlive();
|
||||
|
||||
final formKey = useMemoized(() => GlobalKey<FormState>());
|
||||
final focusNode = useFocusNode();
|
||||
final textController =
|
||||
useTextEditingController(text: sharedContent?.toString());
|
||||
final quickAnswer = useListenableSelector(
|
||||
textController,
|
||||
() => textController.text.endsWith('?'),
|
||||
);
|
||||
|
||||
return Form(
|
||||
key: formKey,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const SizedBox(height: 4),
|
||||
Consumer(
|
||||
builder: (context, ref, child) {
|
||||
final optionsStream = ref.watch(autosuggestRepositoryProvider);
|
||||
|
||||
return ExternalResultsAutocomplete<String>(
|
||||
textEditingController: textController,
|
||||
optionsStream: optionsStream,
|
||||
focusNode: focusNode,
|
||||
optionsViewOpenDirection: OptionsViewOpenDirection.up,
|
||||
displayStringForOption:
|
||||
// ignore: avoid_redundant_argument_values
|
||||
RawAutocomplete.defaultStringForOption,
|
||||
optionsViewBuilder: (context, onSelected, options) {
|
||||
return _AutocompleteOptions(
|
||||
//Must match RawAutocomplete parent
|
||||
displayStringForOption:
|
||||
RawAutocomplete.defaultStringForOption,
|
||||
onSelected: onSelected,
|
||||
options: options,
|
||||
//Must match RawAutocomplete parent
|
||||
openDirection: OptionsViewOpenDirection.up,
|
||||
maxOptionsHeight: 200.0,
|
||||
);
|
||||
},
|
||||
onTextChanged: (textEditingValue) {
|
||||
ref
|
||||
.read(autosuggestRepositoryProvider.notifier)
|
||||
.addQuery(textEditingValue.text);
|
||||
},
|
||||
fieldViewBuilder: (
|
||||
context,
|
||||
textEditingController,
|
||||
focusNode,
|
||||
onFieldSubmitted,
|
||||
) {
|
||||
return TextFormField(
|
||||
controller: textEditingController,
|
||||
focusNode: focusNode,
|
||||
decoration: InputDecoration(
|
||||
// border: OutlineInputBorder(),
|
||||
label: const Text('Query'),
|
||||
suffixIcon: IconButton(
|
||||
onPressed: () async {
|
||||
final isServiceAvailable =
|
||||
await SpeechToTextGoogleDialog.getInstance()
|
||||
.showGoogleDialog(
|
||||
onTextReceived: (data) {
|
||||
textEditingController.text = data.toString();
|
||||
},
|
||||
// locale: "en-US",
|
||||
);
|
||||
|
||||
if (!isServiceAvailable) {
|
||||
if (context.mounted) {
|
||||
ui_helper.showErrorMessage(
|
||||
context,
|
||||
'Service is not available',
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
icon: const Icon(Icons.mic),
|
||||
),
|
||||
),
|
||||
autovalidateMode: AutovalidateMode.onUserInteraction,
|
||||
validator: (value) {
|
||||
if (value?.isEmpty ?? true) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return null;
|
||||
},
|
||||
onTapOutside: (event) {
|
||||
focusNode.unfocus();
|
||||
},
|
||||
onFieldSubmitted: (value) {
|
||||
if (formKey.currentState?.validate() ?? false) {
|
||||
onSubmit(
|
||||
uri_builder.searchUri(
|
||||
searchQuery: textController.text,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// onFieldSubmitted();
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
SwitchListTile(
|
||||
value: quickAnswer,
|
||||
onChanged: (_) {
|
||||
if (textController.text.endsWith('?')) {
|
||||
textController.text = textController.text
|
||||
.substring(0, textController.text.length - 1);
|
||||
} else {
|
||||
textController.text = '${textController.text}?';
|
||||
}
|
||||
},
|
||||
contentPadding: EdgeInsets.zero,
|
||||
title: const Text('Quick Answer'),
|
||||
secondary: const Icon(MdiIcons.lightningBolt),
|
||||
),
|
||||
const SizedBox(
|
||||
height: 12,
|
||||
),
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: FilledButton.icon(
|
||||
onPressed: () {
|
||||
if (formKey.currentState?.validate() ?? false) {
|
||||
onSubmit(
|
||||
uri_builder.searchUri(
|
||||
searchQuery: textController.text,
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
label: const Text('Search'),
|
||||
icon: const Icon(MdiIcons.invoiceTextSend),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_hooks/flutter_hooks.dart';
|
||||
import 'package:flutter_material_design_icons/flutter_material_design_icons.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:kagi_bang_bang/features/search_browser/domain/entities/modes.dart';
|
||||
import 'package:kagi_bang_bang/features/search_browser/presentation/widgets/sheets/shared_content_sheet.dart';
|
||||
import 'package:kagi_bang_bang/features/search_browser/utils/url_builder.dart'
|
||||
as uri_builder;
|
||||
import 'package:kagi_bang_bang/features/share_intent/domain/entities/shared_content.dart';
|
||||
import 'package:kagi_bang_bang/presentation/widgets/website_title_tile.dart';
|
||||
import 'package:kagi_bang_bang/utils/uri_parser.dart' as uri_parser;
|
||||
|
||||
class SummarizeTab extends HookConsumerWidget {
|
||||
final SharedContent? sharedContent;
|
||||
final OnSubmitUri onSubmit;
|
||||
|
||||
const SummarizeTab({
|
||||
required this.sharedContent,
|
||||
required this.onSubmit,
|
||||
super.key,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
useAutomaticKeepAlive();
|
||||
|
||||
final formKey = useMemoized(() => GlobalKey<FormState>());
|
||||
final selectedMode = useState(SummarizerMode.keyMoments);
|
||||
final textController =
|
||||
useTextEditingController(text: sharedContent?.toString());
|
||||
|
||||
return Form(
|
||||
key: formKey,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
SegmentedButton<SummarizerMode>(
|
||||
segments: const [
|
||||
ButtonSegment(
|
||||
value: SummarizerMode.keyMoments,
|
||||
icon: Icon(MdiIcons.scriptTextKey),
|
||||
label: Text('Key Moments'),
|
||||
),
|
||||
ButtonSegment(
|
||||
value: SummarizerMode.summary,
|
||||
icon: Icon(MdiIcons.invoiceTextMinus),
|
||||
label: Text('Summary'),
|
||||
),
|
||||
],
|
||||
selected: {selectedMode.value},
|
||||
onSelectionChanged: (value) {
|
||||
selectedMode.value = value.first;
|
||||
},
|
||||
),
|
||||
const SizedBox(
|
||||
height: 12,
|
||||
),
|
||||
...switch (sharedContent) {
|
||||
SharedUrl() => [
|
||||
TextFormField(
|
||||
controller: textController,
|
||||
decoration: const InputDecoration(
|
||||
// border: OutlineInputBorder(),
|
||||
label: Text('Document'),
|
||||
),
|
||||
autovalidateMode: AutovalidateMode.onUserInteraction,
|
||||
validator: (value) {
|
||||
if (value?.isEmpty ?? true) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return null;
|
||||
},
|
||||
),
|
||||
HookBuilder(
|
||||
builder: (context) {
|
||||
final url =
|
||||
useState(uri_parser.tryParseUrl(textController.text));
|
||||
useEffect(
|
||||
() {
|
||||
Timer? timer;
|
||||
void debounce() {
|
||||
timer?.cancel();
|
||||
timer = Timer(const Duration(milliseconds: 250), () {
|
||||
url.value =
|
||||
uri_parser.tryParseUrl(textController.text);
|
||||
});
|
||||
}
|
||||
|
||||
textController.addListener(debounce);
|
||||
return () => textController.removeListener(debounce);
|
||||
},
|
||||
[textController],
|
||||
);
|
||||
|
||||
return Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (url.value != null) WebsiteTitleTile(url.value!),
|
||||
],
|
||||
);
|
||||
},
|
||||
),
|
||||
const SizedBox(
|
||||
height: 12,
|
||||
),
|
||||
],
|
||||
SharedText() || null => [
|
||||
TextFormField(
|
||||
controller: textController,
|
||||
decoration: const InputDecoration(
|
||||
// border: OutlineInputBorder(),
|
||||
label: Text('Document'),
|
||||
),
|
||||
maxLines: null,
|
||||
autovalidateMode: AutovalidateMode.onUserInteraction,
|
||||
validator: (value) {
|
||||
if (value?.isEmpty ?? true) {
|
||||
return '';
|
||||
}
|
||||
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(
|
||||
height: 12,
|
||||
),
|
||||
],
|
||||
},
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: FilledButton.icon(
|
||||
onPressed: () {
|
||||
if (formKey.currentState?.validate() ?? false) {
|
||||
onSubmit(
|
||||
uri_builder.summarizerUri(
|
||||
document: SharedContent.parse(textController.text),
|
||||
mode: selectedMode.value,
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
label: const Text('Summarize'),
|
||||
icon: const Icon(MdiIcons.invoiceTextSend),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:kagi_bang_bang/features/web_view/domain/repositories/web_view.dart';
|
||||
|
||||
class TabsActionButton extends HookConsumerWidget {
|
||||
final VoidCallback onTap;
|
||||
|
||||
const TabsActionButton({required this.onTap, super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final tabCount =
|
||||
ref.watch(webViewRepositoryProvider.select((tabs) => tabs.length));
|
||||
|
||||
return InkWell(
|
||||
onTap: onTap,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(
|
||||
left: 10.0,
|
||||
top: 15.0,
|
||||
right: 10.0,
|
||||
bottom: 15.0,
|
||||
),
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
border: Border.all(width: 2.0, color: Colors.white),
|
||||
borderRadius: BorderRadius.circular(5.0),
|
||||
),
|
||||
constraints: const BoxConstraints(minWidth: 25.0),
|
||||
child: Center(
|
||||
child: Text(
|
||||
tabCount.toString(),
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 14.0,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
import 'package:kagi_bang_bang/features/search_browser/domain/entities/modes.dart';
|
||||
import 'package:kagi_bang_bang/features/share_intent/domain/entities/shared_content.dart';
|
||||
|
||||
final _baseUrl = Uri.https('kagi.com');
|
||||
|
||||
Uri assistantUri({
|
||||
required String prompt,
|
||||
required AssistantMode assistantMode,
|
||||
ResearchVariant? researchVariant,
|
||||
ChatModel? chatModel,
|
||||
}) =>
|
||||
_baseUrl.replace(
|
||||
pathSegments: [
|
||||
'assistant',
|
||||
],
|
||||
queryParameters: {
|
||||
'mode': assistantMode.value.toString(),
|
||||
'q': prompt,
|
||||
...switch (assistantMode) {
|
||||
AssistantMode.research => {
|
||||
'sub_mode': researchVariant!.value.toString(),
|
||||
},
|
||||
AssistantMode.code => {},
|
||||
AssistantMode.chat => {
|
||||
'sub_mode': chatModel!.value.toString(),
|
||||
},
|
||||
AssistantMode.custom => {},
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
Uri summarizerUri({
|
||||
required SharedContent document,
|
||||
required SummarizerMode mode,
|
||||
}) =>
|
||||
_baseUrl.replace(
|
||||
pathSegments: [
|
||||
'summarizer',
|
||||
'index.html',
|
||||
],
|
||||
queryParameters: {
|
||||
'summary': mode.value,
|
||||
if (document case SharedUrl(url: final url)) 'url': url.toString(),
|
||||
},
|
||||
fragment: switch (document) {
|
||||
SharedText(text: final text) => text,
|
||||
_ => null,
|
||||
},
|
||||
);
|
||||
|
||||
Uri searchUri({required String searchQuery}) => _baseUrl.replace(
|
||||
pathSegments: ['search'],
|
||||
queryParameters: {'q': searchQuery},
|
||||
);
|
||||
@@ -0,0 +1,39 @@
|
||||
import 'package:copy_with_extension/copy_with_extension.dart';
|
||||
import 'package:fast_equatable/fast_equatable.dart';
|
||||
|
||||
part 'settings.g.dart';
|
||||
|
||||
@CopyWith()
|
||||
class Settings with FastEquatable {
|
||||
final String? kagiSession;
|
||||
final bool incognitoMode;
|
||||
final bool enableJavascript;
|
||||
final bool launchUrlExternal;
|
||||
|
||||
Settings({
|
||||
required this.kagiSession,
|
||||
required this.incognitoMode,
|
||||
required this.enableJavascript,
|
||||
required this.launchUrlExternal,
|
||||
});
|
||||
|
||||
Settings.withDefaults({
|
||||
required this.kagiSession,
|
||||
bool? incognitoMode,
|
||||
bool? enableJavascript,
|
||||
bool? launchUrlExternal,
|
||||
}) : incognitoMode = incognitoMode ?? true,
|
||||
enableJavascript = enableJavascript ?? true,
|
||||
launchUrlExternal = launchUrlExternal ?? false;
|
||||
|
||||
@override
|
||||
bool get cacheHash => true;
|
||||
|
||||
@override
|
||||
List<Object?> get hashParameters => [
|
||||
kagiSession,
|
||||
incognitoMode,
|
||||
enableJavascript,
|
||||
launchUrlExternal,
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'settings.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// CopyWithGenerator
|
||||
// **************************************************************************
|
||||
|
||||
abstract class _$SettingsCWProxy {
|
||||
Settings kagiSession(String? kagiSession);
|
||||
|
||||
Settings incognitoMode(bool incognitoMode);
|
||||
|
||||
Settings enableJavascript(bool enableJavascript);
|
||||
|
||||
Settings launchUrlExternal(bool launchUrlExternal);
|
||||
|
||||
/// This function **does support** nullification of nullable fields. All `null` values passed to `non-nullable` fields will be ignored. You can also use `Settings(...).copyWith.fieldName(...)` to override fields one at a time with nullification support.
|
||||
///
|
||||
/// Usage
|
||||
/// ```dart
|
||||
/// Settings(...).copyWith(id: 12, name: "My name")
|
||||
/// ````
|
||||
Settings call({
|
||||
String? kagiSession,
|
||||
bool? incognitoMode,
|
||||
bool? enableJavascript,
|
||||
bool? launchUrlExternal,
|
||||
});
|
||||
}
|
||||
|
||||
/// Proxy class for `copyWith` functionality. This is a callable class and can be used as follows: `instanceOfSettings.copyWith(...)`. Additionally contains functions for specific fields e.g. `instanceOfSettings.copyWith.fieldName(...)`
|
||||
class _$SettingsCWProxyImpl implements _$SettingsCWProxy {
|
||||
const _$SettingsCWProxyImpl(this._value);
|
||||
|
||||
final Settings _value;
|
||||
|
||||
@override
|
||||
Settings kagiSession(String? kagiSession) => this(kagiSession: kagiSession);
|
||||
|
||||
@override
|
||||
Settings incognitoMode(bool incognitoMode) =>
|
||||
this(incognitoMode: incognitoMode);
|
||||
|
||||
@override
|
||||
Settings enableJavascript(bool enableJavascript) =>
|
||||
this(enableJavascript: enableJavascript);
|
||||
|
||||
@override
|
||||
Settings launchUrlExternal(bool launchUrlExternal) =>
|
||||
this(launchUrlExternal: launchUrlExternal);
|
||||
|
||||
@override
|
||||
|
||||
/// This function **does support** nullification of nullable fields. All `null` values passed to `non-nullable` fields will be ignored. You can also use `Settings(...).copyWith.fieldName(...)` to override fields one at a time with nullification support.
|
||||
///
|
||||
/// Usage
|
||||
/// ```dart
|
||||
/// Settings(...).copyWith(id: 12, name: "My name")
|
||||
/// ````
|
||||
Settings call({
|
||||
Object? kagiSession = const $CopyWithPlaceholder(),
|
||||
Object? incognitoMode = const $CopyWithPlaceholder(),
|
||||
Object? enableJavascript = const $CopyWithPlaceholder(),
|
||||
Object? launchUrlExternal = const $CopyWithPlaceholder(),
|
||||
}) {
|
||||
return Settings(
|
||||
kagiSession: kagiSession == const $CopyWithPlaceholder()
|
||||
? _value.kagiSession
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: kagiSession as String?,
|
||||
incognitoMode:
|
||||
incognitoMode == const $CopyWithPlaceholder() || incognitoMode == null
|
||||
? _value.incognitoMode
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: incognitoMode as bool,
|
||||
enableJavascript: enableJavascript == const $CopyWithPlaceholder() ||
|
||||
enableJavascript == null
|
||||
? _value.enableJavascript
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: enableJavascript as bool,
|
||||
launchUrlExternal: launchUrlExternal == const $CopyWithPlaceholder() ||
|
||||
launchUrlExternal == null
|
||||
? _value.launchUrlExternal
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: launchUrlExternal as bool,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
extension $SettingsCopyWith on Settings {
|
||||
/// Returns a callable class that can be used as follows: `instanceOfSettings.copyWith(...)` or like so:`instanceOfSettings.copyWith.fieldName(...)`.
|
||||
// ignore: library_private_types_in_public_api
|
||||
_$SettingsCWProxy get copyWith => _$SettingsCWProxyImpl(this);
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
|
||||
import 'package:kagi_bang_bang/features/settings/data/models/settings.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
part 'settings_repository.g.dart';
|
||||
|
||||
typedef UpdateSettingsFunc = Settings Function(Settings currentSettings);
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
class SettingsRepository extends _$SettingsRepository {
|
||||
static const _sessionStorageKey = 'b4ng_kagi_session';
|
||||
static const _incognitoStorageKey = 'b4ng_settings_incognito';
|
||||
static const _javascriptStorageKey = 'b4ng_settings_js';
|
||||
static const _launchExternalStorageKey = 'b4ng_settings_launch_external';
|
||||
|
||||
final FlutterSecureStorage _flutterSecureStorage;
|
||||
final Future<SharedPreferences> _sharedPreferences;
|
||||
|
||||
SettingsRepository()
|
||||
: _flutterSecureStorage = const FlutterSecureStorage(),
|
||||
_sharedPreferences = SharedPreferences.getInstance();
|
||||
|
||||
Future<void> updateSettings(UpdateSettingsFunc updateWithCurrent) async {
|
||||
final oldSettings = state.value!;
|
||||
final newSettings = updateWithCurrent(oldSettings);
|
||||
|
||||
if (oldSettings != newSettings) {
|
||||
if (oldSettings.kagiSession != newSettings.kagiSession) {
|
||||
await _flutterSecureStorage.write(
|
||||
key: _sessionStorageKey,
|
||||
value: newSettings.kagiSession,
|
||||
);
|
||||
}
|
||||
|
||||
if (newSettings.incognitoMode != oldSettings.incognitoMode) {
|
||||
await _sharedPreferences.then(
|
||||
(s) => s.setBool(_incognitoStorageKey, newSettings.incognitoMode),
|
||||
);
|
||||
}
|
||||
|
||||
if (newSettings.enableJavascript != oldSettings.enableJavascript) {
|
||||
await _sharedPreferences.then(
|
||||
(s) => s.setBool(_javascriptStorageKey, newSettings.enableJavascript),
|
||||
);
|
||||
}
|
||||
|
||||
if (newSettings.launchUrlExternal != oldSettings.launchUrlExternal) {
|
||||
await _sharedPreferences.then(
|
||||
(s) => s.setBool(
|
||||
_launchExternalStorageKey,
|
||||
newSettings.launchUrlExternal,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
ref.invalidateSelf();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
FutureOr<Settings> build() async {
|
||||
final sharedPreferences = await _sharedPreferences;
|
||||
|
||||
return Settings.withDefaults(
|
||||
kagiSession: await _flutterSecureStorage.read(key: _sessionStorageKey),
|
||||
incognitoMode: sharedPreferences.getBool(_incognitoStorageKey),
|
||||
enableJavascript: sharedPreferences.getBool(_javascriptStorageKey),
|
||||
launchUrlExternal: sharedPreferences.getBool(_launchExternalStorageKey),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'settings_repository.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
String _$settingsRepositoryHash() =>
|
||||
r'1e1dc6c76bdcaf742335bf8e11a584093ec13f33';
|
||||
|
||||
/// See also [SettingsRepository].
|
||||
@ProviderFor(SettingsRepository)
|
||||
final settingsRepositoryProvider =
|
||||
AsyncNotifierProvider<SettingsRepository, Settings>.internal(
|
||||
SettingsRepository.new,
|
||||
name: r'settingsRepositoryProvider',
|
||||
debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product')
|
||||
? null
|
||||
: _$settingsRepositoryHash,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
typedef _$SettingsRepository = AsyncNotifier<Settings>;
|
||||
// ignore_for_file: type=lint
|
||||
// ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member
|
||||
@@ -0,0 +1,19 @@
|
||||
import 'package:kagi_bang_bang/features/settings/data/repositories/settings_repository.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
part 'save_settings.g.dart';
|
||||
|
||||
@riverpod
|
||||
class SaveSettingsController extends _$SaveSettingsController {
|
||||
@override
|
||||
FutureOr<void> build() {}
|
||||
|
||||
Future<void> save(UpdateSettingsFunc updateSettings) async {
|
||||
state = const AsyncLoading();
|
||||
state = await AsyncValue.guard(
|
||||
() => ref
|
||||
.read(settingsRepositoryProvider.notifier)
|
||||
.updateSettings(updateSettings),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'save_settings.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
String _$saveSettingsControllerHash() =>
|
||||
r'861664dc6e526737adff645597b141c2ba9d97c1';
|
||||
|
||||
/// See also [SaveSettingsController].
|
||||
@ProviderFor(SaveSettingsController)
|
||||
final saveSettingsControllerProvider =
|
||||
AutoDisposeAsyncNotifierProvider<SaveSettingsController, void>.internal(
|
||||
SaveSettingsController.new,
|
||||
name: r'saveSettingsControllerProvider',
|
||||
debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product')
|
||||
? null
|
||||
: _$saveSettingsControllerHash,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
typedef _$SaveSettingsController = AutoDisposeAsyncNotifier<void>;
|
||||
// ignore_for_file: type=lint
|
||||
// ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member
|
||||
@@ -0,0 +1,146 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_hooks/flutter_hooks.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:kagi_bang_bang/features/settings/data/models/settings.dart';
|
||||
import 'package:kagi_bang_bang/features/settings/data/repositories/settings_repository.dart';
|
||||
import 'package:kagi_bang_bang/features/settings/presentation/controllers/save_settings.dart';
|
||||
import 'package:kagi_bang_bang/features/settings/utils/session_link_extractor.dart';
|
||||
import 'package:kagi_bang_bang/presentation/hooks/listenable_callback.dart';
|
||||
|
||||
class SettingsScreen extends HookConsumerWidget {
|
||||
const SettingsScreen({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final kagiSessionTextController = useTextEditingController(
|
||||
text: ref.read(
|
||||
settingsRepositoryProvider
|
||||
.select((value) => value.valueOrNull?.kagiSession),
|
||||
),
|
||||
);
|
||||
final hideSessionText = useState(true);
|
||||
|
||||
// final isSavingSettings = ref.watch(
|
||||
// saveSettingsControllerProvider.select((value) => value.isLoading),
|
||||
// );
|
||||
|
||||
final incognitoEnabled = ref.watch(
|
||||
settingsRepositoryProvider
|
||||
.select((value) => value.valueOrNull?.incognitoMode ?? false),
|
||||
);
|
||||
|
||||
final javacsriptEnabled = ref.watch(
|
||||
settingsRepositoryProvider
|
||||
.select((value) => value.valueOrNull?.enableJavascript ?? false),
|
||||
);
|
||||
|
||||
final launchUrlExternal = ref.watch(
|
||||
settingsRepositoryProvider
|
||||
.select((value) => value.valueOrNull?.launchUrlExternal ?? false),
|
||||
);
|
||||
|
||||
useListenableCallback(kagiSessionTextController, () async {
|
||||
var text = kagiSessionTextController.text;
|
||||
if (Uri.tryParse(text) case final Uri uri) {
|
||||
if (extractKagiSession(uri) case final String session) {
|
||||
text = session;
|
||||
}
|
||||
}
|
||||
|
||||
await ref.read(saveSettingsControllerProvider.notifier).save(
|
||||
(currentSettings) => currentSettings.copyWith.kagiSession(text),
|
||||
);
|
||||
});
|
||||
|
||||
ref.listen(
|
||||
settingsRepositoryProvider.select(
|
||||
(settings) => settings.valueOrNull?.kagiSession,
|
||||
), (previous, next) {
|
||||
if (next != null &&
|
||||
next.isNotEmpty &&
|
||||
kagiSessionTextController.text != next) {
|
||||
kagiSessionTextController.text = next;
|
||||
}
|
||||
});
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Settings')),
|
||||
body: SafeArea(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(8.0),
|
||||
child: ListView(
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(
|
||||
left: 16,
|
||||
right: 16,
|
||||
bottom: 16,
|
||||
),
|
||||
child: TextField(
|
||||
controller: kagiSessionTextController,
|
||||
obscureText: hideSessionText.value,
|
||||
decoration: InputDecoration(
|
||||
label: const Text('Kagi Session Token'),
|
||||
hintText: 'https://kagi.com/search?token=...',
|
||||
helperMaxLines: 2,
|
||||
helperText:
|
||||
'You can visit your Kagi Account settings to get your Session Link.',
|
||||
suffixIcon: IconButton(
|
||||
onPressed: () {
|
||||
hideSessionText.value = !hideSessionText.value;
|
||||
},
|
||||
icon: Icon(
|
||||
hideSessionText.value
|
||||
? Icons.visibility
|
||||
: Icons.visibility_off,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
SwitchListTile.adaptive(
|
||||
title: const Text('Incognito Mode'),
|
||||
subtitle: const Text(
|
||||
'Deletes all browsing data upon app restart for enhanced privacy.',
|
||||
),
|
||||
value: incognitoEnabled,
|
||||
onChanged: (value) async {
|
||||
await ref.read(saveSettingsControllerProvider.notifier).save(
|
||||
(currentSettings) =>
|
||||
currentSettings.copyWith.incognitoMode(value),
|
||||
);
|
||||
},
|
||||
),
|
||||
SwitchListTile.adaptive(
|
||||
title: const Text('Enable JavaScript'),
|
||||
subtitle: const Text(
|
||||
'While turning off JavaScript boosts security, privacy, and speed, it may cause some sites to not work as intended.',
|
||||
),
|
||||
value: javacsriptEnabled,
|
||||
onChanged: (value) async {
|
||||
await ref.read(saveSettingsControllerProvider.notifier).save(
|
||||
(currentSettings) =>
|
||||
currentSettings.copyWith.enableJavascript(value),
|
||||
);
|
||||
},
|
||||
),
|
||||
SwitchListTile.adaptive(
|
||||
title: const Text('Launch Links Externally'),
|
||||
subtitle: const Text(
|
||||
'Opens all links (except for kagi.com) in your default browser.',
|
||||
),
|
||||
value: launchUrlExternal,
|
||||
onChanged: (value) async {
|
||||
await ref.read(saveSettingsControllerProvider.notifier).save(
|
||||
(currentSettings) =>
|
||||
currentSettings.copyWith.launchUrlExternal(value),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
String? extractKagiSession(Uri uri) {
|
||||
if (uri.authority == 'kagi.com') {
|
||||
return uri.queryParameters['token'];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import 'package:kagi_bang_bang/utils/uri_parser.dart' as uri_parser;
|
||||
|
||||
sealed class SharedContent {
|
||||
const SharedContent();
|
||||
|
||||
factory SharedContent.parse(String content) {
|
||||
if (uri_parser.tryParseUrl(content) case final Uri uri) {
|
||||
return SharedUrl(uri);
|
||||
} else {
|
||||
return SharedText(content);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final class SharedUrl extends SharedContent {
|
||||
final Uri url;
|
||||
|
||||
const SharedUrl(this.url);
|
||||
|
||||
@override
|
||||
String toString() => url.toString();
|
||||
}
|
||||
|
||||
final class SharedText extends SharedContent {
|
||||
final String text;
|
||||
|
||||
const SharedText(this.text);
|
||||
|
||||
@override
|
||||
String toString() => text;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:collection/collection.dart';
|
||||
import 'package:flutter_sharing_intent/flutter_sharing_intent.dart';
|
||||
import 'package:flutter_sharing_intent/model/sharing_file.dart';
|
||||
import 'package:kagi_bang_bang/domain/entities/received_parameter.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:rxdart/rxdart.dart';
|
||||
|
||||
part 'sharing_intent.g.dart';
|
||||
|
||||
@riverpod
|
||||
Raw<Stream<ReceivedParameter>> sharingIntentStream(SharingIntentStreamRef ref) {
|
||||
final initialStream = FlutterSharingIntent.instance
|
||||
// ignore: discarded_futures
|
||||
.getInitialSharing()
|
||||
// ignore: discarded_futures
|
||||
.then((event) async {
|
||||
FlutterSharingIntent.instance.reset();
|
||||
return event;
|
||||
}).asStream();
|
||||
|
||||
return ConcatStream(
|
||||
[initialStream, FlutterSharingIntent.instance.getMediaStream()],
|
||||
)
|
||||
.map(
|
||||
(event) => event
|
||||
.where(
|
||||
(shared) =>
|
||||
shared.type == SharedMediaType.TEXT ||
|
||||
shared.type == SharedMediaType.URL,
|
||||
)
|
||||
.map((shared) => shared.value)
|
||||
.whereNotNull()
|
||||
.firstOrNull,
|
||||
)
|
||||
.whereNotNull()
|
||||
.map((content) => ReceivedParameter(content, null));
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'sharing_intent.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
String _$sharingIntentStreamHash() =>
|
||||
r'6fca6ca6b4ac983397245a09cb61144cd5a4715d';
|
||||
|
||||
/// See also [sharingIntentStream].
|
||||
@ProviderFor(sharingIntentStream)
|
||||
final sharingIntentStreamProvider =
|
||||
AutoDisposeProvider<Raw<Stream<ReceivedParameter>>>.internal(
|
||||
sharingIntentStream,
|
||||
name: r'sharingIntentStreamProvider',
|
||||
debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product')
|
||||
? null
|
||||
: _$sharingIntentStreamHash,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
typedef SharingIntentStreamRef
|
||||
= AutoDisposeProviderRef<Raw<Stream<ReceivedParameter>>>;
|
||||
// ignore_for_file: type=lint
|
||||
// ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member
|
||||
@@ -0,0 +1,59 @@
|
||||
import 'package:copy_with_extension/copy_with_extension.dart';
|
||||
import 'package:fast_equatable/fast_equatable.dart';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/widgets.dart';
|
||||
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
|
||||
import 'package:kagi_bang_bang/domain/entities/web_page_info.dart';
|
||||
|
||||
part 'web_view_page.g.dart';
|
||||
|
||||
typedef PageHistory = ({bool canGoBack, bool canGoForward});
|
||||
|
||||
@CopyWith(constructor: '_')
|
||||
class WebViewPage extends WebPageInfo with FastEquatable {
|
||||
@CopyWithField(immutable: true)
|
||||
final Key key;
|
||||
|
||||
final InAppWebViewController? controller;
|
||||
|
||||
// ignore: missing_field_in_equatable_props
|
||||
final SslError? sslError;
|
||||
final Uint8List? screenshot;
|
||||
final PageHistory pageHistory;
|
||||
|
||||
WebViewPage({
|
||||
this.controller,
|
||||
required super.url,
|
||||
this.sslError,
|
||||
super.title,
|
||||
super.favicon,
|
||||
this.screenshot,
|
||||
this.pageHistory = (canGoBack: false, canGoForward: false),
|
||||
}) : key = GlobalKey();
|
||||
|
||||
WebViewPage._({
|
||||
required this.key,
|
||||
required this.controller,
|
||||
required super.url,
|
||||
required this.sslError,
|
||||
required super.title,
|
||||
required super.favicon,
|
||||
required this.screenshot,
|
||||
required this.pageHistory,
|
||||
});
|
||||
|
||||
@override
|
||||
bool get cacheHash => true;
|
||||
|
||||
@override
|
||||
List<Object?> get hashParameters => [
|
||||
key,
|
||||
controller,
|
||||
url,
|
||||
sslError?.toString(),
|
||||
title,
|
||||
favicon?.toString(),
|
||||
screenshot,
|
||||
pageHistory,
|
||||
];
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'web_view_page.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// CopyWithGenerator
|
||||
// **************************************************************************
|
||||
|
||||
abstract class _$WebViewPageCWProxy {
|
||||
WebViewPage controller(InAppWebViewController? controller);
|
||||
|
||||
WebViewPage url(Uri url);
|
||||
|
||||
WebViewPage sslError(SslError? sslError);
|
||||
|
||||
WebViewPage title(String? title);
|
||||
|
||||
WebViewPage favicon(Favicon? favicon);
|
||||
|
||||
WebViewPage screenshot(Uint8List? screenshot);
|
||||
|
||||
WebViewPage pageHistory(({bool canGoBack, bool canGoForward}) pageHistory);
|
||||
|
||||
/// This function **does support** nullification of nullable fields. All `null` values passed to `non-nullable` fields will be ignored. You can also use `WebViewPage(...).copyWith.fieldName(...)` to override fields one at a time with nullification support.
|
||||
///
|
||||
/// Usage
|
||||
/// ```dart
|
||||
/// WebViewPage(...).copyWith(id: 12, name: "My name")
|
||||
/// ````
|
||||
WebViewPage call({
|
||||
InAppWebViewController? controller,
|
||||
Uri? url,
|
||||
SslError? sslError,
|
||||
String? title,
|
||||
Favicon? favicon,
|
||||
Uint8List? screenshot,
|
||||
({bool canGoBack, bool canGoForward})? pageHistory,
|
||||
});
|
||||
}
|
||||
|
||||
/// Proxy class for `copyWith` functionality. This is a callable class and can be used as follows: `instanceOfWebViewPage.copyWith(...)`. Additionally contains functions for specific fields e.g. `instanceOfWebViewPage.copyWith.fieldName(...)`
|
||||
class _$WebViewPageCWProxyImpl implements _$WebViewPageCWProxy {
|
||||
const _$WebViewPageCWProxyImpl(this._value);
|
||||
|
||||
final WebViewPage _value;
|
||||
|
||||
@override
|
||||
WebViewPage controller(InAppWebViewController? controller) =>
|
||||
this(controller: controller);
|
||||
|
||||
@override
|
||||
WebViewPage url(Uri url) => this(url: url);
|
||||
|
||||
@override
|
||||
WebViewPage sslError(SslError? sslError) => this(sslError: sslError);
|
||||
|
||||
@override
|
||||
WebViewPage title(String? title) => this(title: title);
|
||||
|
||||
@override
|
||||
WebViewPage favicon(Favicon? favicon) => this(favicon: favicon);
|
||||
|
||||
@override
|
||||
WebViewPage screenshot(Uint8List? screenshot) => this(screenshot: screenshot);
|
||||
|
||||
@override
|
||||
WebViewPage pageHistory(({bool canGoBack, bool canGoForward}) pageHistory) =>
|
||||
this(pageHistory: pageHistory);
|
||||
|
||||
@override
|
||||
|
||||
/// This function **does support** nullification of nullable fields. All `null` values passed to `non-nullable` fields will be ignored. You can also use `WebViewPage(...).copyWith.fieldName(...)` to override fields one at a time with nullification support.
|
||||
///
|
||||
/// Usage
|
||||
/// ```dart
|
||||
/// WebViewPage(...).copyWith(id: 12, name: "My name")
|
||||
/// ````
|
||||
WebViewPage call({
|
||||
Object? controller = const $CopyWithPlaceholder(),
|
||||
Object? url = const $CopyWithPlaceholder(),
|
||||
Object? sslError = const $CopyWithPlaceholder(),
|
||||
Object? title = const $CopyWithPlaceholder(),
|
||||
Object? favicon = const $CopyWithPlaceholder(),
|
||||
Object? screenshot = const $CopyWithPlaceholder(),
|
||||
Object? pageHistory = const $CopyWithPlaceholder(),
|
||||
}) {
|
||||
return WebViewPage._(
|
||||
key: _value.key,
|
||||
controller: controller == const $CopyWithPlaceholder()
|
||||
? _value.controller
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: controller as InAppWebViewController?,
|
||||
url: url == const $CopyWithPlaceholder() || url == null
|
||||
? _value.url
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: url as Uri,
|
||||
sslError: sslError == const $CopyWithPlaceholder()
|
||||
? _value.sslError
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: sslError as SslError?,
|
||||
title: title == const $CopyWithPlaceholder()
|
||||
? _value.title
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: title as String?,
|
||||
favicon: favicon == const $CopyWithPlaceholder()
|
||||
? _value.favicon
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: favicon as Favicon?,
|
||||
screenshot: screenshot == const $CopyWithPlaceholder()
|
||||
? _value.screenshot
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: screenshot as Uint8List?,
|
||||
pageHistory:
|
||||
pageHistory == const $CopyWithPlaceholder() || pageHistory == null
|
||||
? _value.pageHistory
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: pageHistory as ({bool canGoBack, bool canGoForward}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
extension $WebViewPageCopyWith on WebViewPage {
|
||||
/// Returns a callable class that can be used as follows: `instanceOfWebViewPage.copyWith(...)` or like so:`instanceOfWebViewPage.copyWith.fieldName(...)`.
|
||||
// ignore: library_private_types_in_public_api
|
||||
_$WebViewPageCWProxy get copyWith => _$WebViewPageCWProxyImpl(this);
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import 'dart:collection';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:kagi_bang_bang/features/web_view/presentation/widgets/web_view.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
part 'web_view.g.dart';
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
class WebViewTabController extends _$WebViewTabController {
|
||||
late Map<Key, WebView> _webViewTabs;
|
||||
|
||||
@override
|
||||
WebView? build() {
|
||||
_webViewTabs = ref.watch(webViewRepositoryProvider);
|
||||
return (stateOrNull != null)
|
||||
? _webViewTabs[stateOrNull!.page.value.key] ??
|
||||
_webViewTabs.values.lastOrNull
|
||||
: null;
|
||||
}
|
||||
|
||||
void showTab(Key? key) {
|
||||
state = (key != null) ? _webViewTabs[key] : null;
|
||||
}
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
class WebViewRepository extends _$WebViewRepository {
|
||||
@override
|
||||
Map<Key, WebView> build() {
|
||||
return stateOrNull ?? {};
|
||||
}
|
||||
|
||||
void addTab(WebView webView) {
|
||||
state = {...state, webView.page.value.key: webView};
|
||||
}
|
||||
|
||||
Future<void> closeTab(Key key) async {
|
||||
state = Map.of(state)..remove(key);
|
||||
}
|
||||
|
||||
Future<void> closeAllTabs() async {
|
||||
state = {};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'web_view.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
String _$webViewTabControllerHash() =>
|
||||
r'45eaa10e6032b04717e8ba08b8dce8ed22764f46';
|
||||
|
||||
/// See also [WebViewTabController].
|
||||
@ProviderFor(WebViewTabController)
|
||||
final webViewTabControllerProvider =
|
||||
NotifierProvider<WebViewTabController, WebView?>.internal(
|
||||
WebViewTabController.new,
|
||||
name: r'webViewTabControllerProvider',
|
||||
debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product')
|
||||
? null
|
||||
: _$webViewTabControllerHash,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
typedef _$WebViewTabController = Notifier<WebView?>;
|
||||
String _$webViewRepositoryHash() => r'96c14f599df30f6828ecaae584a509225b10e2f1';
|
||||
|
||||
/// See also [WebViewRepository].
|
||||
@ProviderFor(WebViewRepository)
|
||||
final webViewRepositoryProvider =
|
||||
NotifierProvider<WebViewRepository, Map<Key, WebView>>.internal(
|
||||
WebViewRepository.new,
|
||||
name: r'webViewRepositoryProvider',
|
||||
debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product')
|
||||
? null
|
||||
: _$webViewRepositoryHash,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
typedef _$WebViewRepository = Notifier<Map<Key, WebView>>;
|
||||
// ignore_for_file: type=lint
|
||||
// ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member
|
||||
@@ -0,0 +1,30 @@
|
||||
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
|
||||
import 'package:kagi_bang_bang/features/web_view/domain/entities/web_view_page.dart';
|
||||
import 'package:kagi_bang_bang/features/web_view/domain/repositories/web_view.dart';
|
||||
import 'package:kagi_bang_bang/features/web_view/presentation/widgets/web_view.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
part 'switch_new_tab.g.dart';
|
||||
|
||||
@riverpod
|
||||
class SwitchNewTabController extends _$SwitchNewTabController {
|
||||
@override
|
||||
FutureOr<void> build() {}
|
||||
|
||||
Future<void> add(Uri url) async {
|
||||
state = const AsyncLoading();
|
||||
state = await AsyncValue.guard(
|
||||
() async {
|
||||
final newTab = WebViewPage(
|
||||
url: WebUri.uri(url),
|
||||
);
|
||||
|
||||
ref
|
||||
.read(webViewRepositoryProvider.notifier)
|
||||
.addTab(WebView(tab: newTab));
|
||||
|
||||
ref.read(webViewTabControllerProvider.notifier).showTab(newTab.key);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'switch_new_tab.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
String _$switchNewTabControllerHash() =>
|
||||
r'acc20371e95db182cfc5cdc924a289ff56981692';
|
||||
|
||||
/// See also [SwitchNewTabController].
|
||||
@ProviderFor(SwitchNewTabController)
|
||||
final switchNewTabControllerProvider =
|
||||
AutoDisposeAsyncNotifierProvider<SwitchNewTabController, void>.internal(
|
||||
SwitchNewTabController.new,
|
||||
name: r'switchNewTabControllerProvider',
|
||||
debugGetCreateSourceHash: const bool.fromEnvironment('dart.vm.product')
|
||||
? null
|
||||
: _$switchNewTabControllerHash,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
typedef _$SwitchNewTabController = AutoDisposeAsyncNotifier<void>;
|
||||
// ignore_for_file: type=lint
|
||||
// ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member
|
||||
@@ -0,0 +1,43 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_material_design_icons/flutter_material_design_icons.dart';
|
||||
import 'package:kagi_bang_bang/domain/entities/web_page_info.dart';
|
||||
import 'package:kagi_bang_bang/extensions/web_uri_favicon.dart';
|
||||
|
||||
class FaviconImage extends StatelessWidget {
|
||||
final double size;
|
||||
final Icon _iconPlaceholder;
|
||||
|
||||
final WebPageInfo webPageInfo;
|
||||
|
||||
FaviconImage({
|
||||
required this.webPageInfo,
|
||||
this.size = 16,
|
||||
super.key,
|
||||
}) : _iconPlaceholder = Icon(
|
||||
MdiIcons.webBox,
|
||||
size: size,
|
||||
);
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (webPageInfo.favicon != null) {
|
||||
return FadeInImage(
|
||||
placeholder: NetworkImage(
|
||||
webPageInfo.url.guessFavicon().toString(),
|
||||
),
|
||||
image: NetworkImage(webPageInfo.favicon!.url.toString()),
|
||||
placeholderErrorBuilder: (_, __, ___) => _iconPlaceholder,
|
||||
imageErrorBuilder: (_, __, ___) => _iconPlaceholder,
|
||||
height: size,
|
||||
width: size,
|
||||
);
|
||||
} else {
|
||||
return Image.network(
|
||||
webPageInfo.url.guessFavicon().toString(),
|
||||
errorBuilder: (_, __, ___) => _iconPlaceholder,
|
||||
height: size,
|
||||
width: size,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_hooks/flutter_hooks.dart';
|
||||
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
|
||||
import 'package:flutter_material_design_icons/flutter_material_design_icons.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:kagi_bang_bang/domain/entities/web_page_info.dart';
|
||||
import 'package:kagi_bang_bang/features/search_browser/domain/entities/modes.dart';
|
||||
import 'package:kagi_bang_bang/features/search_browser/utils/url_builder.dart'
|
||||
as uri_builder;
|
||||
import 'package:kagi_bang_bang/features/share_intent/domain/entities/shared_content.dart';
|
||||
import 'package:kagi_bang_bang/features/web_view/presentation/controllers/switch_new_tab.dart';
|
||||
import 'package:kagi_bang_bang/features/web_view/presentation/widgets/favicon.dart';
|
||||
import 'package:kagi_bang_bang/presentation/controllers/website_title.dart';
|
||||
import 'package:kagi_bang_bang/utils/ui_helper.dart' as ui_helper;
|
||||
import 'package:share_plus/share_plus.dart';
|
||||
import 'package:skeletonizer/skeletonizer.dart';
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
class LoadingWebPageDialog extends HookConsumerWidget {
|
||||
final Uri url;
|
||||
|
||||
final void Function()? onDismiss;
|
||||
|
||||
const LoadingWebPageDialog(this.url, {this.onDismiss});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final pageInfoAsync = ref.watch(pageInfoProvider(url));
|
||||
|
||||
return Skeletonizer(
|
||||
enabled: pageInfoAsync.isLoading,
|
||||
child: WebPageDialog(
|
||||
page: pageInfoAsync.valueOrNull ??
|
||||
WebPageInfo(url: url, favicon: null, title: ''),
|
||||
onDismiss: onDismiss,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class WebPageDialog extends HookConsumerWidget {
|
||||
final WebPageInfo page;
|
||||
final InAppWebViewController? webViewController;
|
||||
|
||||
final void Function()? onDismiss;
|
||||
|
||||
const WebPageDialog({
|
||||
required this.page,
|
||||
this.webViewController,
|
||||
this.onDismiss,
|
||||
super.key,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final formKey = useMemoized(() => GlobalKey<FormState>());
|
||||
final urlTextController =
|
||||
useTextEditingController(text: page.url.toString());
|
||||
|
||||
return Stack(
|
||||
children: [
|
||||
ModalBarrier(
|
||||
color: Theme.of(context).dialogTheme.barrierColor ?? Colors.black54,
|
||||
onDismiss: onDismiss,
|
||||
),
|
||||
SimpleDialog(
|
||||
titlePadding: const EdgeInsets.fromLTRB(24.0, 12.0, 24.0, 0.0),
|
||||
contentPadding: EdgeInsets.zero,
|
||||
insetPadding: const EdgeInsets.symmetric(
|
||||
horizontal: 20.0,
|
||||
vertical: 24.0,
|
||||
),
|
||||
title: ListTile(
|
||||
leading: FaviconImage(
|
||||
webPageInfo: page,
|
||||
size: 24,
|
||||
),
|
||||
contentPadding: EdgeInsets.zero,
|
||||
title: Text(page.title ?? 'Unknown Title'),
|
||||
subtitle: Text(page.url.authority),
|
||||
),
|
||||
children: [
|
||||
SizedBox(
|
||||
//We need this to stretch the dialog, then padding from dialog is applied
|
||||
width: double.maxFinite,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16.0),
|
||||
child: Form(
|
||||
key: formKey,
|
||||
child: TextFormField(
|
||||
controller: urlTextController,
|
||||
decoration: InputDecoration(
|
||||
suffixIcon: (webViewController != null)
|
||||
? IconButton(
|
||||
onPressed: () async {
|
||||
if (formKey.currentState?.validate() ?? false) {
|
||||
await webViewController!.loadUrl(
|
||||
urlRequest: URLRequest(
|
||||
url: WebUri.uri(
|
||||
Uri.parse(
|
||||
urlTextController.text,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
onDismiss?.call();
|
||||
}
|
||||
},
|
||||
icon: const Icon(Icons.send),
|
||||
)
|
||||
: null,
|
||||
),
|
||||
validator: (value) {
|
||||
if (value != null) {
|
||||
if (Uri.tryParse(value) case final Uri url) {
|
||||
if (url.hasScheme && url.hasAuthority) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return 'Invalid URL';
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
ListTile(
|
||||
leading: const Icon(MdiIcons.contentCopy),
|
||||
title: const Text('Copy address'),
|
||||
onTap: () async {
|
||||
await Clipboard.setData(
|
||||
ClipboardData(text: page.url.toString()),
|
||||
);
|
||||
onDismiss?.call();
|
||||
},
|
||||
),
|
||||
ListTile(
|
||||
onTap: () async {
|
||||
if (!await launchUrl(
|
||||
page.url,
|
||||
mode: LaunchMode.externalApplication,
|
||||
)) {
|
||||
if (context.mounted) {
|
||||
ui_helper.showErrorMessage(
|
||||
context,
|
||||
'Could not launch URL (${page.url})',
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
leading: const Icon(Icons.open_in_browser),
|
||||
title: const Text('Launch External'),
|
||||
),
|
||||
ListTile(
|
||||
leading: const Icon(MdiIcons.tabPlus),
|
||||
title: const Text('Open in new tab'),
|
||||
onTap: () async {
|
||||
await ref
|
||||
.read(switchNewTabControllerProvider.notifier)
|
||||
.add(page.url);
|
||||
|
||||
onDismiss?.call();
|
||||
},
|
||||
),
|
||||
ListTile(
|
||||
leading: const Icon(Icons.share),
|
||||
title: const Text('Share link'),
|
||||
onTap: () async {
|
||||
await Share.shareUri(page.url);
|
||||
|
||||
onDismiss?.call();
|
||||
},
|
||||
),
|
||||
const Divider(),
|
||||
ListTile(
|
||||
leading: const Icon(MdiIcons.text),
|
||||
title: const Text('Summarize'),
|
||||
onTap: () async {
|
||||
final url = uri_builder.summarizerUri(
|
||||
document: SharedUrl(page.url),
|
||||
mode: SummarizerMode.keyMoments,
|
||||
);
|
||||
|
||||
await ref
|
||||
.read(switchNewTabControllerProvider.notifier)
|
||||
.add(url);
|
||||
|
||||
onDismiss?.call();
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,359 @@
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_hooks/flutter_hooks.dart';
|
||||
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:kagi_bang_bang/core/logger.dart';
|
||||
import 'package:kagi_bang_bang/features/search_browser/domain/entities/modes.dart';
|
||||
import 'package:kagi_bang_bang/features/search_browser/domain/entities/sheet.dart';
|
||||
import 'package:kagi_bang_bang/features/search_browser/domain/providers.dart';
|
||||
import 'package:kagi_bang_bang/features/search_browser/utils/url_builder.dart'
|
||||
as uri_builder;
|
||||
import 'package:kagi_bang_bang/features/settings/data/repositories/settings_repository.dart';
|
||||
import 'package:kagi_bang_bang/features/web_view/domain/entities/web_view_page.dart';
|
||||
import 'package:kagi_bang_bang/features/web_view/presentation/controllers/switch_new_tab.dart';
|
||||
import 'package:kagi_bang_bang/features/web_view/presentation/widgets/web_page_dialog.dart';
|
||||
import 'package:kagi_bang_bang/features/web_view/utils/favicon_helper.dart';
|
||||
import 'package:kagi_bang_bang/utils/platform_util.dart' as platform_util;
|
||||
import 'package:kagi_bang_bang/utils/ui_helper.dart' as ui_helper;
|
||||
import 'package:url_launcher/url_launcher.dart';
|
||||
|
||||
const _webViewSupportedSchemes = [
|
||||
"http",
|
||||
"https",
|
||||
"file",
|
||||
"chrome",
|
||||
"data",
|
||||
"javascript",
|
||||
"about",
|
||||
];
|
||||
|
||||
class WebView extends StatefulHookConsumerWidget {
|
||||
final ValueNotifier<WebViewPage> _valueNotifier;
|
||||
|
||||
ValueListenable<WebViewPage> get page => _valueNotifier;
|
||||
|
||||
void updatePage(WebViewPage Function(WebViewPage page) update) {
|
||||
_valueNotifier.value = update(_valueNotifier.value);
|
||||
}
|
||||
|
||||
WebView({required WebViewPage tab})
|
||||
: _valueNotifier = ValueNotifier(tab),
|
||||
super(key: tab.key);
|
||||
|
||||
@override
|
||||
ConsumerState<ConsumerStatefulWidget> createState() => _WebViewState();
|
||||
}
|
||||
|
||||
class _WebViewState extends ConsumerState<WebView> {
|
||||
Timer? _onLoadStopDebounce;
|
||||
Timer? _periodicScreenshotUpdate;
|
||||
|
||||
Future<void> _updateScreenshot() async {
|
||||
final screenshot = await widget.page.value.controller
|
||||
?.takeScreenshot(
|
||||
screenshotConfiguration: ScreenshotConfiguration(
|
||||
compressFormat: CompressFormat.JPEG,
|
||||
quality: 20,
|
||||
),
|
||||
)
|
||||
.timeout(
|
||||
const Duration(milliseconds: 1500),
|
||||
onTimeout: () {
|
||||
logger.w('Screenshot timed out');
|
||||
return null;
|
||||
},
|
||||
);
|
||||
|
||||
widget.updatePage(
|
||||
(page) => page.copyWith.screenshot(screenshot),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> dispose() async {
|
||||
super.dispose();
|
||||
|
||||
_onLoadStopDebounce?.cancel();
|
||||
_periodicScreenshotUpdate?.cancel();
|
||||
|
||||
widget._valueNotifier.dispose();
|
||||
logger.i('Disposed ${widget.key} (${widget.page.value.title})');
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final initialSettings = useMemoized(
|
||||
() => InAppWebViewSettings(
|
||||
// isInspectable: kDebugMode,
|
||||
useOnDownloadStart: true,
|
||||
allowsLinkPreview: false,
|
||||
disableLongPressContextMenuOnLinks: true,
|
||||
useShouldOverrideUrlLoading: true,
|
||||
javaScriptEnabled: ref
|
||||
.read(settingsRepositoryProvider)
|
||||
.valueOrNull
|
||||
?.enableJavascript ??
|
||||
true,
|
||||
saveFormData: false,
|
||||
disabledActionModeMenuItems: ActionModeMenuItem.MENU_ITEM_WEB_SEARCH,
|
||||
),
|
||||
);
|
||||
|
||||
final webViewProgress = useValueNotifier(100);
|
||||
|
||||
useOnAppLifecycleStateChange((previous, current) async {
|
||||
switch (current) {
|
||||
case AppLifecycleState.paused:
|
||||
if (platform_util.isAndroid()) {
|
||||
await widget.page.value.controller?.pause();
|
||||
}
|
||||
if (platform_util.isAndroid() || platform_util.isIOS()) {
|
||||
await widget.page.value.controller?.pauseTimers();
|
||||
}
|
||||
case AppLifecycleState.resumed:
|
||||
if (platform_util.isAndroid()) {
|
||||
await widget.page.value.controller?.resume();
|
||||
}
|
||||
if (platform_util.isAndroid() || platform_util.isIOS()) {
|
||||
await widget.page.value.controller?.resumeTimers();
|
||||
}
|
||||
default:
|
||||
}
|
||||
});
|
||||
|
||||
ref.listen(
|
||||
settingsRepositoryProvider
|
||||
.select((value) => value.valueOrNull?.enableJavascript),
|
||||
(previous, next) async {
|
||||
await widget.page.value.controller?.setSettings(
|
||||
settings: initialSettings.copy()..javaScriptEnabled = next,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
return Stack(
|
||||
children: [
|
||||
InAppWebView(
|
||||
initialUrlRequest: URLRequest(url: WebUri.uri(widget.page.value.url)),
|
||||
initialSettings: initialSettings,
|
||||
contextMenu: ContextMenu(
|
||||
menuItems: [
|
||||
ContextMenuItem(
|
||||
id: 1,
|
||||
title: "Search",
|
||||
action: () async {
|
||||
final selectedText =
|
||||
await widget.page.value.controller?.getSelectedText();
|
||||
|
||||
if (selectedText != null && selectedText.isNotEmpty) {
|
||||
final url = uri_builder.searchUri(
|
||||
searchQuery: selectedText,
|
||||
);
|
||||
|
||||
await ref
|
||||
.read(switchNewTabControllerProvider.notifier)
|
||||
.add(url);
|
||||
}
|
||||
},
|
||||
),
|
||||
ContextMenuItem(
|
||||
id: 2,
|
||||
title: "Assistant",
|
||||
action: () async {
|
||||
final selectedText =
|
||||
await widget.page.value.controller?.getSelectedText();
|
||||
|
||||
if (selectedText != null && selectedText.isNotEmpty) {
|
||||
ref.read(bottomSheetProvider.notifier).show(
|
||||
CreateTab(
|
||||
content: selectedText,
|
||||
preferredTool: KagiTool.assistant,
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
onWebViewCreated: (controller) async {
|
||||
if (platform_util.isAndroid()) {
|
||||
await controller.startSafeBrowsing();
|
||||
}
|
||||
|
||||
widget.updatePage((page) => page.copyWith.controller(controller));
|
||||
},
|
||||
onReceivedServerTrustAuthRequest: (controller, challenge) async {
|
||||
final sslError = challenge.protectionSpace.sslError;
|
||||
|
||||
if (sslError != null && sslError.code != null) {
|
||||
if (challenge.protectionSpace.host ==
|
||||
await controller.getUrl().then((value) => value?.host)) {
|
||||
widget.updatePage((page) => page.copyWith.sslError(sslError));
|
||||
if (context.mounted) {
|
||||
ui_helper.showErrorMessage(
|
||||
context,
|
||||
'We detected an security issue and did not continue to ${widget.page.value.url.authority}: ${sslError.message}',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return ServerTrustAuthResponse(
|
||||
// ignore: avoid_redundant_argument_values
|
||||
action: ServerTrustAuthResponseAction.CANCEL,
|
||||
);
|
||||
}
|
||||
|
||||
widget.updatePage((page) => page.copyWith.sslError(null));
|
||||
return ServerTrustAuthResponse(
|
||||
action: ServerTrustAuthResponseAction.PROCEED,
|
||||
);
|
||||
},
|
||||
onProgressChanged: (controller, progress) {
|
||||
webViewProgress.value = progress;
|
||||
},
|
||||
onLoadStart: (controller, url) {
|
||||
if (url != null) {
|
||||
widget.updatePage(
|
||||
(page) => page.copyWith(
|
||||
url: url,
|
||||
// ignore: avoid_redundant_argument_values
|
||||
sslError: null,
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
onLoadStop: (controller, url) {
|
||||
if (url != null) {
|
||||
widget.updatePage((page) => page.copyWith.url(url));
|
||||
}
|
||||
|
||||
_onLoadStopDebounce?.cancel();
|
||||
_onLoadStopDebounce =
|
||||
Timer(const Duration(milliseconds: 150), () async {
|
||||
final favicon = await widget.page.value.controller
|
||||
?.getFavicons()
|
||||
.then((icons) => choseFavicon(icons));
|
||||
widget.updatePage((page) => page.copyWith.favicon(favicon));
|
||||
|
||||
await _updateScreenshot().whenComplete(() {
|
||||
_periodicScreenshotUpdate?.cancel();
|
||||
_periodicScreenshotUpdate =
|
||||
Timer.periodic(const Duration(seconds: 5), (timer) async {
|
||||
await _updateScreenshot().onError((error, stackTrace) {
|
||||
logger.e(error, stackTrace: stackTrace);
|
||||
timer.cancel();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
},
|
||||
onUpdateVisitedHistory: (controller, url, isReload) async {
|
||||
if (isReload != true) {
|
||||
final history = (
|
||||
canGoBack: await controller.canGoBack(),
|
||||
canGoForward: await controller.canGoForward()
|
||||
);
|
||||
|
||||
widget.updatePage((page) => page.copyWith.pageHistory(history));
|
||||
}
|
||||
},
|
||||
shouldOverrideUrlLoading: (controller, navigationAction) async {
|
||||
final url = navigationAction.request.url;
|
||||
if (url != null) {
|
||||
final launchExternal = ref
|
||||
.read(settingsRepositoryProvider)
|
||||
.valueOrNull
|
||||
?.launchUrlExternal ??
|
||||
false;
|
||||
|
||||
final unhandledScheme =
|
||||
!_webViewSupportedSchemes.contains(url.scheme);
|
||||
|
||||
if (unhandledScheme ||
|
||||
(launchExternal && url.host != 'kagi.com')) {
|
||||
if (await canLaunchUrl(url)) {
|
||||
var success = false;
|
||||
if (unhandledScheme) {
|
||||
success = await launchUrl(url);
|
||||
} else if (launchExternal) {
|
||||
success = await launchUrl(
|
||||
url,
|
||||
mode: LaunchMode.externalApplication,
|
||||
);
|
||||
}
|
||||
|
||||
if (!success) {
|
||||
if (context.mounted) {
|
||||
ui_helper.showErrorMessage(
|
||||
context,
|
||||
'Could not launch URL ($url)',
|
||||
);
|
||||
}
|
||||
}
|
||||
// and cancel the request
|
||||
return NavigationActionPolicy.CANCEL;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return NavigationActionPolicy.ALLOW;
|
||||
},
|
||||
onLongPressHitTestResult: (controller, hitTestResult) async {
|
||||
if (switch (hitTestResult.type) {
|
||||
InAppWebViewHitTestResultType.SRC_IMAGE_ANCHOR_TYPE ||
|
||||
InAppWebViewHitTestResultType.SRC_ANCHOR_TYPE ||
|
||||
InAppWebViewHitTestResultType.IMAGE_TYPE =>
|
||||
true,
|
||||
_ => false,
|
||||
}) {
|
||||
final requestFocusNodeHrefResult =
|
||||
await controller.requestFocusNodeHref();
|
||||
|
||||
final url = requestFocusNodeHrefResult?.url ??
|
||||
Uri.tryParse(requestFocusNodeHrefResult?.src ?? '');
|
||||
if (url?.hasScheme == true && url?.hasAuthority == true) {
|
||||
ref.read(overlayDialogProvider.notifier).show(
|
||||
LoadingWebPageDialog(
|
||||
url!,
|
||||
onDismiss:
|
||||
ref.watch(overlayDialogProvider.notifier).dismiss,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
onTitleChanged: (controller, title) {
|
||||
widget.updatePage((page) => page.copyWith.title(title));
|
||||
},
|
||||
|
||||
// onDownloadStartRequest: (controller, downloadStartRequest) {
|
||||
// final regex = RegExp(
|
||||
// r"filename\*=UTF-8''([\w%\-\.]+)(?:; ?|$)",
|
||||
// caseSensitive: false,
|
||||
// );
|
||||
|
||||
// final math =
|
||||
// regex.firstMatch(downloadStartRequest.contentDisposition!);
|
||||
|
||||
// print(math);
|
||||
// },
|
||||
),
|
||||
HookBuilder(
|
||||
builder: (context) {
|
||||
final value = useValueListenable(webViewProgress);
|
||||
|
||||
return Visibility(
|
||||
visible: value < 100,
|
||||
child: LinearProgressIndicator(
|
||||
value: value / 100,
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_hooks/flutter_hooks.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:kagi_bang_bang/features/web_view/domain/repositories/web_view.dart';
|
||||
import 'package:kagi_bang_bang/features/web_view/presentation/widgets/favicon.dart';
|
||||
import 'package:kagi_bang_bang/features/web_view/presentation/widgets/web_view.dart';
|
||||
|
||||
class WebViewTab extends HookConsumerWidget {
|
||||
final WebView webView;
|
||||
final bool isActive;
|
||||
|
||||
final VoidCallback onClose;
|
||||
|
||||
const WebViewTab({
|
||||
required this.webView,
|
||||
required this.isActive,
|
||||
required this.onClose,
|
||||
super.key,
|
||||
});
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
final page = useValueListenable(webView.page);
|
||||
|
||||
return Container(
|
||||
key: UniqueKey(),
|
||||
decoration: BoxDecoration(
|
||||
border: Border.all(
|
||||
color: isActive ? colorScheme.primary : colorScheme.outline,
|
||||
width: isActive ? 2.0 : 1.0,
|
||||
),
|
||||
borderRadius: const BorderRadius.all(Radius.circular(16.0)),
|
||||
),
|
||||
child: Material(
|
||||
color: colorScheme.surfaceContainerHighest,
|
||||
borderRadius: const BorderRadius.all(Radius.circular(16.0)),
|
||||
child: InkWell(
|
||||
borderRadius: const BorderRadius.all(Radius.circular(16.0)),
|
||||
onTap: () {
|
||||
if (!isActive) {
|
||||
ref.read(webViewTabControllerProvider.notifier).showTab(page.key);
|
||||
} else {
|
||||
onClose();
|
||||
}
|
||||
},
|
||||
child: Column(
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(left: 6.0),
|
||||
child: Text(
|
||||
overflow: TextOverflow.ellipsis,
|
||||
page.title ?? 'New Tab',
|
||||
maxLines: 2,
|
||||
),
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
visualDensity:
|
||||
const VisualDensity(horizontal: -4.0, vertical: -4.0),
|
||||
onPressed: () async {
|
||||
await ref
|
||||
.read(webViewRepositoryProvider.notifier)
|
||||
.closeTab(page.key);
|
||||
},
|
||||
icon: const Icon(Icons.close),
|
||||
),
|
||||
],
|
||||
),
|
||||
Row(
|
||||
children: [
|
||||
const SizedBox(
|
||||
width: 6.0,
|
||||
),
|
||||
FaviconImage(
|
||||
webPageInfo: page,
|
||||
),
|
||||
const SizedBox(
|
||||
width: 6.0,
|
||||
),
|
||||
Expanded(
|
||||
child: Text(
|
||||
page.url.authority,
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(
|
||||
height: 6,
|
||||
),
|
||||
if (page.screenshot != null)
|
||||
Expanded(
|
||||
child: ClipRRect(
|
||||
borderRadius: const BorderRadius.only(
|
||||
bottomLeft: Radius.circular(16.0),
|
||||
bottomRight: Radius.circular(16.0),
|
||||
),
|
||||
child: SizedBox(
|
||||
width: double.infinity,
|
||||
child: Image.memory(
|
||||
fit: BoxFit.fitWidth,
|
||||
page.screenshot!,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
//https://stackoverflow.com/a/67994693/20878798
|
||||
|
||||
import 'package:universal_io/io.dart';
|
||||
|
||||
final _utf8FilenameRegex = RegExp(
|
||||
r"filename\*=UTF-8''([\w%\-\.]+)(?:; ?|$)",
|
||||
caseSensitive: false,
|
||||
);
|
||||
|
||||
final _asciiFilenameRegex = RegExp(
|
||||
r"""^filename=(["']?)(.*?[^\\])\1(?:; ?|$)""",
|
||||
caseSensitive: false,
|
||||
);
|
||||
|
||||
String? getDispositionFileName(String contentDisposition) {
|
||||
if (_utf8FilenameRegex.hasMatch(contentDisposition)) {
|
||||
final file = Uri.decodeComponent(
|
||||
_utf8FilenameRegex.firstMatch(contentDisposition)!.group(1)!,
|
||||
);
|
||||
|
||||
return File(file).uri.pathSegments.last;
|
||||
} else {
|
||||
// Prevent ReDos attacks by anchoring the ascii regex to string start and
|
||||
// slicing off everything before 'filename='
|
||||
final filenameStart = contentDisposition.toLowerCase().indexOf('filename=');
|
||||
if (filenameStart >= 0) {
|
||||
final partialDisposition = contentDisposition.substring(filenameStart);
|
||||
final matches = _asciiFilenameRegex.firstMatch(partialDisposition);
|
||||
if (matches != null && matches.group(2) != null) {
|
||||
final file = matches.group(2);
|
||||
if (file != null) {
|
||||
return File(file).uri.pathSegments.last;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
|
||||
|
||||
Favicon? choseFavicon(Iterable<Favicon>? favicons, [Favicon? currentIcon]) {
|
||||
var selectedIcon = currentIcon;
|
||||
|
||||
if (favicons != null) {
|
||||
for (final icon in favicons) {
|
||||
if (selectedIcon == null) {
|
||||
selectedIcon = icon;
|
||||
} else {
|
||||
if ((selectedIcon.width == null &&
|
||||
!selectedIcon.url.toString().endsWith("favicon.ico")) ||
|
||||
(icon.width != null &&
|
||||
selectedIcon.width != null &&
|
||||
icon.width! > selectedIcon.width!)) {
|
||||
selectedIcon = icon;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return selectedIcon;
|
||||
}
|
||||
Reference in New Issue
Block a user