prepare for multiple apps
This commit is contained in:
1 parent
bd1600e8dc
commit
5afc323f04
904 files changed
+29
-29
No files matched your search
+164
@@ -0,0 +1,164 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:copy_with_extension/copy_with_extension.dart';
|
||||
import 'package:fast_equatable/fast_equatable.dart';
|
||||
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
|
||||
import 'package:json_annotation/json_annotation.dart';
|
||||
|
||||
part 'bookmark_item.g.dart';
|
||||
|
||||
sealed class BookmarkItem {
|
||||
abstract final String guid;
|
||||
abstract final String? parentGuid;
|
||||
abstract final String title;
|
||||
abstract final int dateAdded;
|
||||
abstract final int? position;
|
||||
|
||||
const BookmarkItem();
|
||||
|
||||
static BookmarkItem? parseRecursive(BookmarkNode node) {
|
||||
return switch (node.type) {
|
||||
BookmarkNodeType.item => BookmarkEntry(
|
||||
guid: node.guid,
|
||||
parentGuid: node.parentGuid,
|
||||
url: Uri.parse(node.url!),
|
||||
title: node.title ?? node.url!,
|
||||
previewImageUrl: Uri.parse(node.url!),
|
||||
position: node.position,
|
||||
dateAdded: node.dateAdded,
|
||||
),
|
||||
BookmarkNodeType.folder => BookmarkFolder(
|
||||
guid: node.guid,
|
||||
parentGuid: node.parentGuid,
|
||||
title: node.title ?? "Unnamed Folder",
|
||||
position: node.position,
|
||||
dateAdded: node.dateAdded,
|
||||
children: node.children?.map(parseRecursive).nonNulls.toList(),
|
||||
),
|
||||
BookmarkNodeType.separator => null,
|
||||
};
|
||||
}
|
||||
|
||||
factory BookmarkItem.fromJson(Map<String, dynamic> json) {
|
||||
return (json.containsKey('url'))
|
||||
? BookmarkEntry.fromJson(json)
|
||||
: BookmarkFolder.fromJson(json);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson();
|
||||
|
||||
BookmarkItem clone();
|
||||
}
|
||||
|
||||
@CopyWith()
|
||||
@JsonSerializable()
|
||||
class BookmarkEntry extends BookmarkItem with FastEquatable {
|
||||
@override
|
||||
final String guid;
|
||||
@override
|
||||
final String? parentGuid;
|
||||
final Uri url;
|
||||
@override
|
||||
final String title;
|
||||
final Uri previewImageUrl;
|
||||
@override
|
||||
final int? position;
|
||||
@override
|
||||
final int dateAdded;
|
||||
|
||||
BookmarkEntry({
|
||||
required this.guid,
|
||||
required this.parentGuid,
|
||||
required this.url,
|
||||
required this.title,
|
||||
required this.previewImageUrl,
|
||||
required this.position,
|
||||
required this.dateAdded,
|
||||
});
|
||||
|
||||
factory BookmarkEntry.fromJson(Map<String, dynamic> json) =>
|
||||
_$BookmarkEntryFromJson(json);
|
||||
|
||||
@override
|
||||
Map<String, dynamic> toJson() => _$BookmarkEntryToJson(this);
|
||||
|
||||
@override
|
||||
BookmarkItem clone() {
|
||||
return copyWith();
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get hashParameters => [
|
||||
guid,
|
||||
parentGuid,
|
||||
url,
|
||||
title,
|
||||
previewImageUrl,
|
||||
position,
|
||||
dateAdded,
|
||||
];
|
||||
}
|
||||
|
||||
@CopyWith()
|
||||
@JsonSerializable()
|
||||
class BookmarkFolder extends BookmarkItem with FastEquatable {
|
||||
@override
|
||||
final String guid;
|
||||
@override
|
||||
final String? parentGuid;
|
||||
@override
|
||||
final String title;
|
||||
@override
|
||||
final int? position;
|
||||
@override
|
||||
final int dateAdded;
|
||||
|
||||
final List<BookmarkItem>? children;
|
||||
|
||||
BookmarkFolder({
|
||||
required this.guid,
|
||||
required this.parentGuid,
|
||||
required String title,
|
||||
required this.position,
|
||||
required this.dateAdded,
|
||||
required this.children,
|
||||
}) : title = bookmarkRootDisplayNames[guid] ?? title;
|
||||
|
||||
factory BookmarkFolder.fromJson(Map<String, dynamic> json) =>
|
||||
_$BookmarkFolderFromJson(json);
|
||||
|
||||
@override
|
||||
Map<String, dynamic> toJson() => _$BookmarkFolderToJson(this);
|
||||
|
||||
@override
|
||||
BookmarkItem clone() {
|
||||
return copyWith();
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get hashParameters => [
|
||||
guid,
|
||||
parentGuid,
|
||||
title,
|
||||
position,
|
||||
dateAdded,
|
||||
children,
|
||||
];
|
||||
}
|
||||
+284
@@ -0,0 +1,284 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'bookmark_item.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// CopyWithGenerator
|
||||
// **************************************************************************
|
||||
|
||||
abstract class _$BookmarkEntryCWProxy {
|
||||
BookmarkEntry guid(String guid);
|
||||
|
||||
BookmarkEntry parentGuid(String? parentGuid);
|
||||
|
||||
BookmarkEntry url(Uri url);
|
||||
|
||||
BookmarkEntry title(String title);
|
||||
|
||||
BookmarkEntry previewImageUrl(Uri previewImageUrl);
|
||||
|
||||
BookmarkEntry position(int? position);
|
||||
|
||||
BookmarkEntry dateAdded(int dateAdded);
|
||||
|
||||
/// Creates a new instance with the provided field values.
|
||||
/// Passing `null` to a nullable field nullifies it, while `null` for a non-nullable field is ignored. To update a single field use `BookmarkEntry(...).copyWith.fieldName(value)`.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// BookmarkEntry(...).copyWith(id: 12, name: "My name")
|
||||
/// ```
|
||||
BookmarkEntry call({
|
||||
String guid,
|
||||
String? parentGuid,
|
||||
Uri url,
|
||||
String title,
|
||||
Uri previewImageUrl,
|
||||
int? position,
|
||||
int dateAdded,
|
||||
});
|
||||
}
|
||||
|
||||
/// Callable proxy for `copyWith` functionality.
|
||||
/// Use as `instanceOfBookmarkEntry.copyWith(...)` or call `instanceOfBookmarkEntry.copyWith.fieldName(value)` for a single field.
|
||||
class _$BookmarkEntryCWProxyImpl implements _$BookmarkEntryCWProxy {
|
||||
const _$BookmarkEntryCWProxyImpl(this._value);
|
||||
|
||||
final BookmarkEntry _value;
|
||||
|
||||
@override
|
||||
BookmarkEntry guid(String guid) => call(guid: guid);
|
||||
|
||||
@override
|
||||
BookmarkEntry parentGuid(String? parentGuid) => call(parentGuid: parentGuid);
|
||||
|
||||
@override
|
||||
BookmarkEntry url(Uri url) => call(url: url);
|
||||
|
||||
@override
|
||||
BookmarkEntry title(String title) => call(title: title);
|
||||
|
||||
@override
|
||||
BookmarkEntry previewImageUrl(Uri previewImageUrl) =>
|
||||
call(previewImageUrl: previewImageUrl);
|
||||
|
||||
@override
|
||||
BookmarkEntry position(int? position) => call(position: position);
|
||||
|
||||
@override
|
||||
BookmarkEntry dateAdded(int dateAdded) => call(dateAdded: dateAdded);
|
||||
|
||||
@override
|
||||
/// Creates a new instance with the provided field values.
|
||||
/// Passing `null` to a nullable field nullifies it, while `null` for a non-nullable field is ignored. To update a single field use `BookmarkEntry(...).copyWith.fieldName(value)`.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// BookmarkEntry(...).copyWith(id: 12, name: "My name")
|
||||
/// ```
|
||||
BookmarkEntry call({
|
||||
Object? guid = const $CopyWithPlaceholder(),
|
||||
Object? parentGuid = const $CopyWithPlaceholder(),
|
||||
Object? url = const $CopyWithPlaceholder(),
|
||||
Object? title = const $CopyWithPlaceholder(),
|
||||
Object? previewImageUrl = const $CopyWithPlaceholder(),
|
||||
Object? position = const $CopyWithPlaceholder(),
|
||||
Object? dateAdded = const $CopyWithPlaceholder(),
|
||||
}) {
|
||||
return BookmarkEntry(
|
||||
guid: guid == const $CopyWithPlaceholder() || guid == null
|
||||
? _value.guid
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: guid as String,
|
||||
parentGuid: parentGuid == const $CopyWithPlaceholder()
|
||||
? _value.parentGuid
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: parentGuid as String?,
|
||||
url: url == const $CopyWithPlaceholder() || url == null
|
||||
? _value.url
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: url as Uri,
|
||||
title: title == const $CopyWithPlaceholder() || title == null
|
||||
? _value.title
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: title as String,
|
||||
previewImageUrl:
|
||||
previewImageUrl == const $CopyWithPlaceholder() ||
|
||||
previewImageUrl == null
|
||||
? _value.previewImageUrl
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: previewImageUrl as Uri,
|
||||
position: position == const $CopyWithPlaceholder()
|
||||
? _value.position
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: position as int?,
|
||||
dateAdded: dateAdded == const $CopyWithPlaceholder() || dateAdded == null
|
||||
? _value.dateAdded
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: dateAdded as int,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
extension $BookmarkEntryCopyWith on BookmarkEntry {
|
||||
/// Returns a callable class used to build a new instance with modified fields.
|
||||
/// Example: `instanceOfBookmarkEntry.copyWith(...)` or `instanceOfBookmarkEntry.copyWith.fieldName(...)`.
|
||||
// ignore: library_private_types_in_public_api
|
||||
_$BookmarkEntryCWProxy get copyWith => _$BookmarkEntryCWProxyImpl(this);
|
||||
}
|
||||
|
||||
abstract class _$BookmarkFolderCWProxy {
|
||||
BookmarkFolder guid(String guid);
|
||||
|
||||
BookmarkFolder parentGuid(String? parentGuid);
|
||||
|
||||
BookmarkFolder title(String title);
|
||||
|
||||
BookmarkFolder position(int? position);
|
||||
|
||||
BookmarkFolder dateAdded(int dateAdded);
|
||||
|
||||
BookmarkFolder children(List<BookmarkItem>? children);
|
||||
|
||||
/// Creates a new instance with the provided field values.
|
||||
/// Passing `null` to a nullable field nullifies it, while `null` for a non-nullable field is ignored. To update a single field use `BookmarkFolder(...).copyWith.fieldName(value)`.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// BookmarkFolder(...).copyWith(id: 12, name: "My name")
|
||||
/// ```
|
||||
BookmarkFolder call({
|
||||
String guid,
|
||||
String? parentGuid,
|
||||
String title,
|
||||
int? position,
|
||||
int dateAdded,
|
||||
List<BookmarkItem>? children,
|
||||
});
|
||||
}
|
||||
|
||||
/// Callable proxy for `copyWith` functionality.
|
||||
/// Use as `instanceOfBookmarkFolder.copyWith(...)` or call `instanceOfBookmarkFolder.copyWith.fieldName(value)` for a single field.
|
||||
class _$BookmarkFolderCWProxyImpl implements _$BookmarkFolderCWProxy {
|
||||
const _$BookmarkFolderCWProxyImpl(this._value);
|
||||
|
||||
final BookmarkFolder _value;
|
||||
|
||||
@override
|
||||
BookmarkFolder guid(String guid) => call(guid: guid);
|
||||
|
||||
@override
|
||||
BookmarkFolder parentGuid(String? parentGuid) => call(parentGuid: parentGuid);
|
||||
|
||||
@override
|
||||
BookmarkFolder title(String title) => call(title: title);
|
||||
|
||||
@override
|
||||
BookmarkFolder position(int? position) => call(position: position);
|
||||
|
||||
@override
|
||||
BookmarkFolder dateAdded(int dateAdded) => call(dateAdded: dateAdded);
|
||||
|
||||
@override
|
||||
BookmarkFolder children(List<BookmarkItem>? children) =>
|
||||
call(children: children);
|
||||
|
||||
@override
|
||||
/// Creates a new instance with the provided field values.
|
||||
/// Passing `null` to a nullable field nullifies it, while `null` for a non-nullable field is ignored. To update a single field use `BookmarkFolder(...).copyWith.fieldName(value)`.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// BookmarkFolder(...).copyWith(id: 12, name: "My name")
|
||||
/// ```
|
||||
BookmarkFolder call({
|
||||
Object? guid = const $CopyWithPlaceholder(),
|
||||
Object? parentGuid = const $CopyWithPlaceholder(),
|
||||
Object? title = const $CopyWithPlaceholder(),
|
||||
Object? position = const $CopyWithPlaceholder(),
|
||||
Object? dateAdded = const $CopyWithPlaceholder(),
|
||||
Object? children = const $CopyWithPlaceholder(),
|
||||
}) {
|
||||
return BookmarkFolder(
|
||||
guid: guid == const $CopyWithPlaceholder() || guid == null
|
||||
? _value.guid
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: guid as String,
|
||||
parentGuid: parentGuid == const $CopyWithPlaceholder()
|
||||
? _value.parentGuid
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: parentGuid as String?,
|
||||
title: title == const $CopyWithPlaceholder() || title == null
|
||||
? _value.title
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: title as String,
|
||||
position: position == const $CopyWithPlaceholder()
|
||||
? _value.position
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: position as int?,
|
||||
dateAdded: dateAdded == const $CopyWithPlaceholder() || dateAdded == null
|
||||
? _value.dateAdded
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: dateAdded as int,
|
||||
children: children == const $CopyWithPlaceholder()
|
||||
? _value.children
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: children as List<BookmarkItem>?,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
extension $BookmarkFolderCopyWith on BookmarkFolder {
|
||||
/// Returns a callable class used to build a new instance with modified fields.
|
||||
/// Example: `instanceOfBookmarkFolder.copyWith(...)` or `instanceOfBookmarkFolder.copyWith.fieldName(...)`.
|
||||
// ignore: library_private_types_in_public_api
|
||||
_$BookmarkFolderCWProxy get copyWith => _$BookmarkFolderCWProxyImpl(this);
|
||||
}
|
||||
|
||||
// **************************************************************************
|
||||
// JsonSerializableGenerator
|
||||
// **************************************************************************
|
||||
|
||||
BookmarkEntry _$BookmarkEntryFromJson(Map<String, dynamic> json) =>
|
||||
BookmarkEntry(
|
||||
guid: json['guid'] as String,
|
||||
parentGuid: json['parentGuid'] as String?,
|
||||
url: Uri.parse(json['url'] as String),
|
||||
title: json['title'] as String,
|
||||
previewImageUrl: Uri.parse(json['previewImageUrl'] as String),
|
||||
position: (json['position'] as num?)?.toInt(),
|
||||
dateAdded: (json['dateAdded'] as num).toInt(),
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$BookmarkEntryToJson(BookmarkEntry instance) =>
|
||||
<String, dynamic>{
|
||||
'guid': instance.guid,
|
||||
'parentGuid': instance.parentGuid,
|
||||
'url': instance.url.toString(),
|
||||
'title': instance.title,
|
||||
'previewImageUrl': instance.previewImageUrl.toString(),
|
||||
'position': instance.position,
|
||||
'dateAdded': instance.dateAdded,
|
||||
};
|
||||
|
||||
BookmarkFolder _$BookmarkFolderFromJson(Map<String, dynamic> json) =>
|
||||
BookmarkFolder(
|
||||
guid: json['guid'] as String,
|
||||
parentGuid: json['parentGuid'] as String?,
|
||||
title: json['title'] as String,
|
||||
position: (json['position'] as num?)?.toInt(),
|
||||
dateAdded: (json['dateAdded'] as num).toInt(),
|
||||
children: (json['children'] as List<dynamic>?)
|
||||
?.map((e) => BookmarkItem.fromJson(e as Map<String, dynamic>))
|
||||
.toList(),
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$BookmarkFolderToJson(BookmarkFolder instance) =>
|
||||
<String, dynamic>{
|
||||
'guid': instance.guid,
|
||||
'parentGuid': instance.parentGuid,
|
||||
'title': instance.title,
|
||||
'position': instance.position,
|
||||
'dateAdded': instance.dateAdded,
|
||||
'children': instance.children?.map((e) => e.toJson()).toList(),
|
||||
};
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:copy_with_extension/copy_with_extension.dart';
|
||||
import 'package:fast_equatable/fast_equatable.dart';
|
||||
import 'package:weblibre/features/geckoview/features/bookmarks/domain/entities/bookmark_sort_type.dart';
|
||||
|
||||
part 'bookmark_list_ui_state.g.dart';
|
||||
|
||||
@CopyWith()
|
||||
class BookmarkListUiState with FastEquatable {
|
||||
final bool selectionMode;
|
||||
final Set<String> selectedGuids;
|
||||
final BookmarkSortType sortType;
|
||||
final bool foldersOnly;
|
||||
|
||||
BookmarkListUiState({
|
||||
this.selectionMode = false,
|
||||
this.selectedGuids = const {},
|
||||
this.sortType = BookmarkSortType.manual,
|
||||
this.foldersOnly = false,
|
||||
});
|
||||
|
||||
@override
|
||||
List<Object?> get hashParameters => [
|
||||
selectionMode,
|
||||
selectedGuids,
|
||||
sortType,
|
||||
foldersOnly,
|
||||
];
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'bookmark_list_ui_state.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// CopyWithGenerator
|
||||
// **************************************************************************
|
||||
|
||||
abstract class _$BookmarkListUiStateCWProxy {
|
||||
BookmarkListUiState selectionMode(bool selectionMode);
|
||||
|
||||
BookmarkListUiState selectedGuids(Set<String> selectedGuids);
|
||||
|
||||
BookmarkListUiState sortType(BookmarkSortType sortType);
|
||||
|
||||
BookmarkListUiState foldersOnly(bool foldersOnly);
|
||||
|
||||
/// Creates a new instance with the provided field values.
|
||||
/// Passing `null` to a nullable field nullifies it, while `null` for a non-nullable field is ignored. To update a single field use `BookmarkListUiState(...).copyWith.fieldName(value)`.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// BookmarkListUiState(...).copyWith(id: 12, name: "My name")
|
||||
/// ```
|
||||
BookmarkListUiState call({
|
||||
bool selectionMode,
|
||||
Set<String> selectedGuids,
|
||||
BookmarkSortType sortType,
|
||||
bool foldersOnly,
|
||||
});
|
||||
}
|
||||
|
||||
/// Callable proxy for `copyWith` functionality.
|
||||
/// Use as `instanceOfBookmarkListUiState.copyWith(...)` or call `instanceOfBookmarkListUiState.copyWith.fieldName(value)` for a single field.
|
||||
class _$BookmarkListUiStateCWProxyImpl implements _$BookmarkListUiStateCWProxy {
|
||||
const _$BookmarkListUiStateCWProxyImpl(this._value);
|
||||
|
||||
final BookmarkListUiState _value;
|
||||
|
||||
@override
|
||||
BookmarkListUiState selectionMode(bool selectionMode) =>
|
||||
call(selectionMode: selectionMode);
|
||||
|
||||
@override
|
||||
BookmarkListUiState selectedGuids(Set<String> selectedGuids) =>
|
||||
call(selectedGuids: selectedGuids);
|
||||
|
||||
@override
|
||||
BookmarkListUiState sortType(BookmarkSortType sortType) =>
|
||||
call(sortType: sortType);
|
||||
|
||||
@override
|
||||
BookmarkListUiState foldersOnly(bool foldersOnly) =>
|
||||
call(foldersOnly: foldersOnly);
|
||||
|
||||
@override
|
||||
/// Creates a new instance with the provided field values.
|
||||
/// Passing `null` to a nullable field nullifies it, while `null` for a non-nullable field is ignored. To update a single field use `BookmarkListUiState(...).copyWith.fieldName(value)`.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// BookmarkListUiState(...).copyWith(id: 12, name: "My name")
|
||||
/// ```
|
||||
BookmarkListUiState call({
|
||||
Object? selectionMode = const $CopyWithPlaceholder(),
|
||||
Object? selectedGuids = const $CopyWithPlaceholder(),
|
||||
Object? sortType = const $CopyWithPlaceholder(),
|
||||
Object? foldersOnly = const $CopyWithPlaceholder(),
|
||||
}) {
|
||||
return BookmarkListUiState(
|
||||
selectionMode:
|
||||
selectionMode == const $CopyWithPlaceholder() || selectionMode == null
|
||||
? _value.selectionMode
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: selectionMode as bool,
|
||||
selectedGuids:
|
||||
selectedGuids == const $CopyWithPlaceholder() || selectedGuids == null
|
||||
? _value.selectedGuids
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: selectedGuids as Set<String>,
|
||||
sortType: sortType == const $CopyWithPlaceholder() || sortType == null
|
||||
? _value.sortType
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: sortType as BookmarkSortType,
|
||||
foldersOnly:
|
||||
foldersOnly == const $CopyWithPlaceholder() || foldersOnly == null
|
||||
? _value.foldersOnly
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: foldersOnly as bool,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
extension $BookmarkListUiStateCopyWith on BookmarkListUiState {
|
||||
/// Returns a callable class used to build a new instance with modified fields.
|
||||
/// Example: `instanceOfBookmarkListUiState.copyWith(...)` or `instanceOfBookmarkListUiState.copyWith.fieldName(...)`.
|
||||
// ignore: library_private_types_in_public_api
|
||||
_$BookmarkListUiStateCWProxy get copyWith =>
|
||||
_$BookmarkListUiStateCWProxyImpl(this);
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:weblibre/core/sort_field.dart';
|
||||
import 'package:weblibre/features/geckoview/features/bookmarks/domain/entities/bookmark_item.dart';
|
||||
|
||||
enum BookmarkSortType {
|
||||
manual('Default', null),
|
||||
titleAsc('Title A-Z', SortField.titleAsc),
|
||||
titleDesc('Title Z-A', SortField.titleDesc),
|
||||
urlAsc('URL A-Z', SortField.urlAsc),
|
||||
urlDesc('URL Z-A', SortField.urlDesc),
|
||||
dateAddedDesc('Newest First', SortField.dateDesc),
|
||||
dateAddedAsc('Oldest First', SortField.dateAsc);
|
||||
|
||||
final String label;
|
||||
final SortField? sortField;
|
||||
|
||||
const BookmarkSortType(this.label, this.sortField);
|
||||
}
|
||||
|
||||
int compareBookmarkItems(
|
||||
BookmarkItem a,
|
||||
BookmarkItem b,
|
||||
BookmarkSortType sort,
|
||||
) {
|
||||
final sortField = sort.sortField;
|
||||
if (sortField == null) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return switch (sortField) {
|
||||
SortField.titleAsc => a.title.toLowerCase().compareTo(
|
||||
b.title.toLowerCase(),
|
||||
),
|
||||
SortField.titleDesc => b.title.toLowerCase().compareTo(
|
||||
a.title.toLowerCase(),
|
||||
),
|
||||
SortField.urlAsc => _urlKey(a).compareTo(_urlKey(b)),
|
||||
SortField.urlDesc => _urlKey(b).compareTo(_urlKey(a)),
|
||||
SortField.dateAsc => a.dateAdded.compareTo(b.dateAdded),
|
||||
SortField.dateDesc => b.dateAdded.compareTo(a.dateAdded),
|
||||
};
|
||||
}
|
||||
|
||||
String _urlKey(BookmarkItem item) =>
|
||||
item is BookmarkEntry ? item.url.toString() : item.title.toLowerCase();
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:weblibre/features/geckoview/features/bookmarks/domain/entities/bookmark_list_ui_state.dart';
|
||||
import 'package:weblibre/features/geckoview/features/bookmarks/domain/entities/bookmark_sort_type.dart';
|
||||
|
||||
part 'bookmark_list_ui_state.g.dart';
|
||||
|
||||
@Riverpod()
|
||||
class BookmarkListUiStateNotifier extends _$BookmarkListUiStateNotifier {
|
||||
@override
|
||||
BookmarkListUiState build() => BookmarkListUiState();
|
||||
|
||||
void enterSelectionMode({String? initialGuid}) {
|
||||
state = state.copyWith(
|
||||
selectionMode: true,
|
||||
selectedGuids: initialGuid != null ? {initialGuid} : {},
|
||||
);
|
||||
}
|
||||
|
||||
void exitSelectionMode() {
|
||||
state = state.copyWith(selectionMode: false, selectedGuids: {});
|
||||
}
|
||||
|
||||
void toggleSelection(String guid) {
|
||||
final updated = Set<String>.from(state.selectedGuids);
|
||||
if (updated.contains(guid)) {
|
||||
updated.remove(guid);
|
||||
} else {
|
||||
updated.add(guid);
|
||||
}
|
||||
if (updated.isEmpty) {
|
||||
exitSelectionMode();
|
||||
} else {
|
||||
state = state.copyWith(selectedGuids: updated);
|
||||
}
|
||||
}
|
||||
|
||||
void selectAll(Iterable<String> guids) {
|
||||
state = state.copyWith(
|
||||
selectionMode: true,
|
||||
selectedGuids: Set<String>.from(guids),
|
||||
);
|
||||
}
|
||||
|
||||
void clearSelection() {
|
||||
exitSelectionMode();
|
||||
}
|
||||
|
||||
void setSortType(BookmarkSortType sortType) {
|
||||
state = state.copyWith(sortType: sortType);
|
||||
}
|
||||
|
||||
void toggleFoldersOnly() {
|
||||
state = state.copyWith(foldersOnly: !state.foldersOnly);
|
||||
}
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'bookmark_list_ui_state.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(BookmarkListUiStateNotifier)
|
||||
final bookmarkListUiStateProvider = BookmarkListUiStateNotifierProvider._();
|
||||
|
||||
final class BookmarkListUiStateNotifierProvider
|
||||
extends
|
||||
$NotifierProvider<BookmarkListUiStateNotifier, BookmarkListUiState> {
|
||||
BookmarkListUiStateNotifierProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'bookmarkListUiStateProvider',
|
||||
isAutoDispose: true,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$bookmarkListUiStateNotifierHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
BookmarkListUiStateNotifier create() => BookmarkListUiStateNotifier();
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(BookmarkListUiState value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<BookmarkListUiState>(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$bookmarkListUiStateNotifierHash() =>
|
||||
r'7c764fc2f1deb178063ca95764775ca237471f9f';
|
||||
|
||||
abstract class _$BookmarkListUiStateNotifier
|
||||
extends $Notifier<BookmarkListUiState> {
|
||||
BookmarkListUiState build();
|
||||
@$mustCallSuper
|
||||
@override
|
||||
void runBuild() {
|
||||
final ref = this.ref as $Ref<BookmarkListUiState, BookmarkListUiState>;
|
||||
final element =
|
||||
ref.element
|
||||
as $ClassProviderElement<
|
||||
AnyNotifier<BookmarkListUiState, BookmarkListUiState>,
|
||||
BookmarkListUiState,
|
||||
Object?,
|
||||
Object?
|
||||
>;
|
||||
element.handleCreate(ref, build);
|
||||
}
|
||||
}
|
||||
+257
@@ -0,0 +1,257 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
|
||||
import 'package:nullability/nullability.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:weblibre/features/geckoview/features/bookmarks/domain/entities/bookmark_item.dart';
|
||||
import 'package:weblibre/features/geckoview/features/bookmarks/domain/repositories/bookmarks.dart';
|
||||
|
||||
part 'bookmarks.g.dart';
|
||||
|
||||
/// Check if a root folder is effectively empty (has no non-root children)
|
||||
bool _isEmptyRootFolder(BookmarkFolder folder) {
|
||||
if (folder.children == null) return true;
|
||||
// A root folder is empty if it has no children, or only contains other root folders
|
||||
return folder.children!.every(
|
||||
(child) => bookmarkRootIds.contains(child.guid),
|
||||
);
|
||||
}
|
||||
|
||||
T? _selectChildRecursive<T extends BookmarkItem>(
|
||||
List<BookmarkItem> children,
|
||||
String guid,
|
||||
) {
|
||||
for (final child in children) {
|
||||
if (child.guid == guid && child is T) {
|
||||
return child;
|
||||
}
|
||||
|
||||
if (child case final BookmarkFolder folder) {
|
||||
if (folder.children != null) {
|
||||
final result = _selectChildRecursive<T>(folder.children!, guid);
|
||||
if (result != null) {
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
T _cloneAndFilterChildrenType<T extends BookmarkItem>(T node) {
|
||||
if (node is BookmarkFolder) {
|
||||
if (node.children != null) {
|
||||
return node.copyWith.children(
|
||||
node.children
|
||||
?.whereType<T>()
|
||||
.map((e) => _cloneAndFilterChildrenType<T>(e))
|
||||
.toList(),
|
||||
)
|
||||
as T;
|
||||
}
|
||||
}
|
||||
|
||||
return node.clone() as T;
|
||||
}
|
||||
|
||||
BookmarkItem? _cloneAndFilterOnGuids(BookmarkItem node, Set<String> guids) {
|
||||
if (node is BookmarkFolder) {
|
||||
if (node.children != null) {
|
||||
final filtered = node.children
|
||||
?.where((e) => e is BookmarkFolder || guids.contains(e.guid))
|
||||
.map((e) => _cloneAndFilterOnGuids(e, guids))
|
||||
.nonNulls
|
||||
.toList();
|
||||
|
||||
if (filtered.isNotEmpty) {
|
||||
return node.copyWith.children(filtered);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (guids.contains(node.guid)) {
|
||||
return node.clone();
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
@Riverpod()
|
||||
class BookmarksSearch extends _$BookmarksSearch {
|
||||
final _service = GeckoBookmarksService();
|
||||
late StreamController<Set<String>> _streamController;
|
||||
|
||||
Future<void> search(String query, {int limit = 10}) async {
|
||||
if (query.isNotEmpty) {
|
||||
try {
|
||||
await _service.searchBookmarks(query, limit: limit).then((value) {
|
||||
if (!_streamController.isClosed) {
|
||||
_streamController.add(value.map((e) => e.guid).toSet());
|
||||
}
|
||||
});
|
||||
} on PlatformException catch (e) {
|
||||
if (e.code == 'OperationInterrupted') return;
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Stream<Set<String>> build() {
|
||||
_streamController = StreamController();
|
||||
|
||||
ref.onDispose(() async {
|
||||
await _streamController.close();
|
||||
});
|
||||
|
||||
return _streamController.stream;
|
||||
}
|
||||
}
|
||||
|
||||
@Riverpod()
|
||||
class BookmarkSearchResults extends _$BookmarkSearchResults {
|
||||
final _service = GeckoBookmarksService();
|
||||
|
||||
Future<void> search(String query, {int limit = 10}) async {
|
||||
if (query.isEmpty) {
|
||||
state = [];
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
final results = await _service.searchBookmarks(query, limit: limit);
|
||||
if (!ref.mounted) return;
|
||||
state = results
|
||||
.map(BookmarkItem.parseRecursive)
|
||||
.whereType<BookmarkEntry>()
|
||||
.toList();
|
||||
} on PlatformException catch (e) {
|
||||
if (e.code == 'OperationInterrupted') return;
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
List<BookmarkEntry> build() {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
@Riverpod()
|
||||
AsyncValue<T?> bookmarks<T extends BookmarkItem>(
|
||||
Ref ref,
|
||||
String entryGuid, {
|
||||
bool hideEmptyRoots = false,
|
||||
}) {
|
||||
final bookmarksAsync = ref.watch(bookmarksRepositoryProvider);
|
||||
|
||||
return bookmarksAsync.whenData((bookmarkNode) {
|
||||
T? selectedNode;
|
||||
|
||||
if (bookmarkNode != null && bookmarkNode is T) {
|
||||
if (bookmarkNode.guid == entryGuid) {
|
||||
selectedNode = bookmarkNode;
|
||||
} else if (bookmarkNode case final BookmarkFolder folder) {
|
||||
if (folder.children != null) {
|
||||
selectedNode = _selectChildRecursive<T>(folder.children!, entryGuid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (selectedNode != null) {
|
||||
var result = _cloneAndFilterChildrenType<T>(selectedNode);
|
||||
|
||||
// Filter empty root folders when viewing root level (excluding WebLibre root)
|
||||
if (hideEmptyRoots &&
|
||||
entryGuid == BookmarkRoot.root.id &&
|
||||
result is BookmarkFolder) {
|
||||
final filteredChildren = result.children
|
||||
?.where(
|
||||
(child) =>
|
||||
child is! BookmarkFolder ||
|
||||
child.guid == BookmarkRoot.mobile.id ||
|
||||
!_isEmptyRootFolder(child),
|
||||
)
|
||||
.toList();
|
||||
result = result.copyWith.children(filteredChildren) as T;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
@Riverpod()
|
||||
class SeamlessBookmarks extends _$SeamlessBookmarks {
|
||||
bool _hasSearch = false;
|
||||
|
||||
void search(String input) {
|
||||
if (input.isNotEmpty) {
|
||||
if (!_hasSearch) {
|
||||
_hasSearch = true;
|
||||
ref.invalidateSelf();
|
||||
}
|
||||
|
||||
//Don't block
|
||||
unawaited(ref.read(bookmarksSearchProvider.notifier).search(input));
|
||||
} else if (_hasSearch) {
|
||||
_hasSearch = false;
|
||||
ref.invalidateSelf();
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
AsyncValue<BookmarkItem?> build(
|
||||
String entryGuid, {
|
||||
bool hideEmptyRoots = false,
|
||||
}) {
|
||||
final bookmarks = ref.watch(
|
||||
bookmarksProvider<BookmarkItem>(
|
||||
entryGuid,
|
||||
hideEmptyRoots: hideEmptyRoots,
|
||||
),
|
||||
);
|
||||
|
||||
if (_hasSearch) {
|
||||
final filterGuids = ref.watch(bookmarksSearchProvider);
|
||||
return bookmarks.map(
|
||||
data: (node) =>
|
||||
node.value.mapNotNull(
|
||||
(node) => filterGuids.whenData(
|
||||
(results) => _cloneAndFilterOnGuids(node, results),
|
||||
),
|
||||
) ??
|
||||
const AsyncValue.data(null),
|
||||
error: (e) => e,
|
||||
loading: (s) => s,
|
||||
);
|
||||
} else {
|
||||
return bookmarks;
|
||||
}
|
||||
}
|
||||
}
|
||||
+330
@@ -0,0 +1,330 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'bookmarks.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(BookmarksSearch)
|
||||
final bookmarksSearchProvider = BookmarksSearchProvider._();
|
||||
|
||||
final class BookmarksSearchProvider
|
||||
extends $StreamNotifierProvider<BookmarksSearch, Set<String>> {
|
||||
BookmarksSearchProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'bookmarksSearchProvider',
|
||||
isAutoDispose: true,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$bookmarksSearchHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
BookmarksSearch create() => BookmarksSearch();
|
||||
}
|
||||
|
||||
String _$bookmarksSearchHash() => r'41053cbc1014e0fdd04d9510bf15c9896a9f752d';
|
||||
|
||||
abstract class _$BookmarksSearch extends $StreamNotifier<Set<String>> {
|
||||
Stream<Set<String>> build();
|
||||
@$mustCallSuper
|
||||
@override
|
||||
void runBuild() {
|
||||
final ref = this.ref as $Ref<AsyncValue<Set<String>>, Set<String>>;
|
||||
final element =
|
||||
ref.element
|
||||
as $ClassProviderElement<
|
||||
AnyNotifier<AsyncValue<Set<String>>, Set<String>>,
|
||||
AsyncValue<Set<String>>,
|
||||
Object?,
|
||||
Object?
|
||||
>;
|
||||
element.handleCreate(ref, build);
|
||||
}
|
||||
}
|
||||
|
||||
@ProviderFor(BookmarkSearchResults)
|
||||
final bookmarkSearchResultsProvider = BookmarkSearchResultsProvider._();
|
||||
|
||||
final class BookmarkSearchResultsProvider
|
||||
extends $NotifierProvider<BookmarkSearchResults, List<BookmarkEntry>> {
|
||||
BookmarkSearchResultsProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'bookmarkSearchResultsProvider',
|
||||
isAutoDispose: true,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$bookmarkSearchResultsHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
BookmarkSearchResults create() => BookmarkSearchResults();
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(List<BookmarkEntry> value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<List<BookmarkEntry>>(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$bookmarkSearchResultsHash() =>
|
||||
r'49ebd21a137bc09bbd67b692aacb2554b8364564';
|
||||
|
||||
abstract class _$BookmarkSearchResults extends $Notifier<List<BookmarkEntry>> {
|
||||
List<BookmarkEntry> build();
|
||||
@$mustCallSuper
|
||||
@override
|
||||
void runBuild() {
|
||||
final ref = this.ref as $Ref<List<BookmarkEntry>, List<BookmarkEntry>>;
|
||||
final element =
|
||||
ref.element
|
||||
as $ClassProviderElement<
|
||||
AnyNotifier<List<BookmarkEntry>, List<BookmarkEntry>>,
|
||||
List<BookmarkEntry>,
|
||||
Object?,
|
||||
Object?
|
||||
>;
|
||||
element.handleCreate(ref, build);
|
||||
}
|
||||
}
|
||||
|
||||
@ProviderFor(bookmarks)
|
||||
final bookmarksProvider = BookmarksFamily._();
|
||||
|
||||
final class BookmarksProvider<T extends BookmarkItem>
|
||||
extends $FunctionalProvider<AsyncValue<T?>, AsyncValue<T?>, AsyncValue<T?>>
|
||||
with $Provider<AsyncValue<T?>> {
|
||||
BookmarksProvider._({
|
||||
required BookmarksFamily super.from,
|
||||
required (String, {bool hideEmptyRoots}) super.argument,
|
||||
}) : super(
|
||||
retry: null,
|
||||
name: r'bookmarksProvider',
|
||||
isAutoDispose: true,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$bookmarksHash();
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return r'bookmarksProvider'
|
||||
'<${T}>'
|
||||
'$argument';
|
||||
}
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$ProviderElement<AsyncValue<T?>> $createElement($ProviderPointer pointer) =>
|
||||
$ProviderElement(pointer);
|
||||
|
||||
@override
|
||||
AsyncValue<T?> create(Ref ref) {
|
||||
final argument = this.argument as (String, {bool hideEmptyRoots});
|
||||
return bookmarks<T>(
|
||||
ref,
|
||||
argument.$1,
|
||||
hideEmptyRoots: argument.hideEmptyRoots,
|
||||
);
|
||||
}
|
||||
|
||||
$R _captureGenerics<$R>($R Function<T extends BookmarkItem>() cb) {
|
||||
return cb<T>();
|
||||
}
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(AsyncValue<T?> value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<AsyncValue<T?>>(value),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return other is BookmarksProvider &&
|
||||
other.runtimeType == runtimeType &&
|
||||
other.argument == argument;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return Object.hash(runtimeType, argument);
|
||||
}
|
||||
}
|
||||
|
||||
String _$bookmarksHash() => r'72b54c4ff18cfdb60824a57607628be6b61d25d4';
|
||||
|
||||
final class BookmarksFamily extends $Family {
|
||||
BookmarksFamily._()
|
||||
: super(
|
||||
retry: null,
|
||||
name: r'bookmarksProvider',
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
isAutoDispose: true,
|
||||
);
|
||||
|
||||
BookmarksProvider<T> call<T extends BookmarkItem>(
|
||||
String entryGuid, {
|
||||
bool hideEmptyRoots = false,
|
||||
}) => BookmarksProvider<T>._(
|
||||
argument: (entryGuid, hideEmptyRoots: hideEmptyRoots),
|
||||
from: this,
|
||||
);
|
||||
|
||||
@override
|
||||
String toString() => r'bookmarksProvider';
|
||||
|
||||
/// {@macro riverpod.override_with}
|
||||
Override overrideWith(
|
||||
AsyncValue<T?> Function<T extends BookmarkItem>(
|
||||
Ref ref,
|
||||
(String, {bool hideEmptyRoots}) args,
|
||||
)
|
||||
create,
|
||||
) => $FamilyOverride(
|
||||
from: this,
|
||||
createElement: (pointer) {
|
||||
final provider = pointer.origin as BookmarksProvider;
|
||||
return provider._captureGenerics(<T extends BookmarkItem>() {
|
||||
provider as BookmarksProvider<T>;
|
||||
final argument = provider.argument as (String, {bool hideEmptyRoots});
|
||||
return provider
|
||||
.$view(create: (ref) => create(ref, argument))
|
||||
.$createElement(pointer);
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@ProviderFor(SeamlessBookmarks)
|
||||
final seamlessBookmarksProvider = SeamlessBookmarksFamily._();
|
||||
|
||||
final class SeamlessBookmarksProvider
|
||||
extends $NotifierProvider<SeamlessBookmarks, AsyncValue<BookmarkItem?>> {
|
||||
SeamlessBookmarksProvider._({
|
||||
required SeamlessBookmarksFamily super.from,
|
||||
required (String, {bool hideEmptyRoots}) super.argument,
|
||||
}) : super(
|
||||
retry: null,
|
||||
name: r'seamlessBookmarksProvider',
|
||||
isAutoDispose: true,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$seamlessBookmarksHash();
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return r'seamlessBookmarksProvider'
|
||||
''
|
||||
'$argument';
|
||||
}
|
||||
|
||||
@$internal
|
||||
@override
|
||||
SeamlessBookmarks create() => SeamlessBookmarks();
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(AsyncValue<BookmarkItem?> value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<AsyncValue<BookmarkItem?>>(value),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return other is SeamlessBookmarksProvider && other.argument == argument;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return argument.hashCode;
|
||||
}
|
||||
}
|
||||
|
||||
String _$seamlessBookmarksHash() => r'240b213fa8fe595781ccc608c5d551be54c31992';
|
||||
|
||||
final class SeamlessBookmarksFamily extends $Family
|
||||
with
|
||||
$ClassFamilyOverride<
|
||||
SeamlessBookmarks,
|
||||
AsyncValue<BookmarkItem?>,
|
||||
AsyncValue<BookmarkItem?>,
|
||||
AsyncValue<BookmarkItem?>,
|
||||
(String, {bool hideEmptyRoots})
|
||||
> {
|
||||
SeamlessBookmarksFamily._()
|
||||
: super(
|
||||
retry: null,
|
||||
name: r'seamlessBookmarksProvider',
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
isAutoDispose: true,
|
||||
);
|
||||
|
||||
SeamlessBookmarksProvider call(
|
||||
String entryGuid, {
|
||||
bool hideEmptyRoots = false,
|
||||
}) => SeamlessBookmarksProvider._(
|
||||
argument: (entryGuid, hideEmptyRoots: hideEmptyRoots),
|
||||
from: this,
|
||||
);
|
||||
|
||||
@override
|
||||
String toString() => r'seamlessBookmarksProvider';
|
||||
}
|
||||
|
||||
abstract class _$SeamlessBookmarks
|
||||
extends $Notifier<AsyncValue<BookmarkItem?>> {
|
||||
late final _$args = ref.$arg as (String, {bool hideEmptyRoots});
|
||||
String get entryGuid => _$args.$1;
|
||||
bool get hideEmptyRoots => _$args.hideEmptyRoots;
|
||||
|
||||
AsyncValue<BookmarkItem?> build(
|
||||
String entryGuid, {
|
||||
bool hideEmptyRoots = false,
|
||||
});
|
||||
@$mustCallSuper
|
||||
@override
|
||||
void runBuild() {
|
||||
final ref =
|
||||
this.ref as $Ref<AsyncValue<BookmarkItem?>, AsyncValue<BookmarkItem?>>;
|
||||
final element =
|
||||
ref.element
|
||||
as $ClassProviderElement<
|
||||
AnyNotifier<AsyncValue<BookmarkItem?>, AsyncValue<BookmarkItem?>>,
|
||||
AsyncValue<BookmarkItem?>,
|
||||
Object?,
|
||||
Object?
|
||||
>;
|
||||
element.handleCreate(
|
||||
ref,
|
||||
() => build(_$args.$1, hideEmptyRoots: _$args.hideEmptyRoots),
|
||||
);
|
||||
}
|
||||
}
|
||||
+196
@@ -0,0 +1,196 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
|
||||
import 'package:nullability/nullability.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:weblibre/core/logger.dart';
|
||||
import 'package:weblibre/features/geckoview/features/bookmarks/domain/entities/bookmark_item.dart';
|
||||
import 'package:weblibre/features/geckoview/features/bookmarks/utils/bookmark_html_utils.dart';
|
||||
import 'package:weblibre/features/geckoview/features/bookmarks/utils/bookmark_json_utils.dart';
|
||||
|
||||
part 'bookmarks.g.dart';
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
class BookmarksRepository extends _$BookmarksRepository {
|
||||
final _service = GeckoBookmarksService();
|
||||
late final _jsonUtils = BookmarkJSONUtils(_service);
|
||||
late final _htmlUtils = BookmarkHTMLUtils(_service);
|
||||
|
||||
Future<void> addBookmark({
|
||||
required String parentGuid,
|
||||
required Uri url,
|
||||
required String title,
|
||||
int? position,
|
||||
}) async {
|
||||
await _service.addItem(parentGuid, url, title, position);
|
||||
ref.invalidateSelf();
|
||||
}
|
||||
|
||||
Future<void> addFolder({
|
||||
required String parentGuid,
|
||||
required String title,
|
||||
int? position,
|
||||
}) async {
|
||||
await _service.addFolder(parentGuid, title, position);
|
||||
ref.invalidateSelf();
|
||||
}
|
||||
|
||||
Future<void> editBookmark({
|
||||
required String guid,
|
||||
String? title,
|
||||
Uri? url,
|
||||
String? parentGuid,
|
||||
int? position,
|
||||
}) async {
|
||||
await _service.updateNode(
|
||||
guid,
|
||||
BookmarkInfo(
|
||||
title: title,
|
||||
url: url?.toString(),
|
||||
parentGuid: parentGuid,
|
||||
position: position,
|
||||
),
|
||||
);
|
||||
ref.invalidateSelf();
|
||||
}
|
||||
|
||||
Future<void> editFolder({
|
||||
required String guid,
|
||||
String? title,
|
||||
String? parentGuid,
|
||||
int? position,
|
||||
}) async {
|
||||
await _service.updateNode(
|
||||
guid,
|
||||
BookmarkInfo(title: title, parentGuid: parentGuid, position: position),
|
||||
);
|
||||
ref.invalidateSelf();
|
||||
}
|
||||
|
||||
Future<void> delete(String guid) async {
|
||||
await _service.deleteNode(guid);
|
||||
ref.invalidateSelf();
|
||||
}
|
||||
|
||||
Future<void> moveMany({
|
||||
required Iterable<BookmarkItem> items,
|
||||
required String targetParentGuid,
|
||||
}) async {
|
||||
for (final item in items) {
|
||||
if (bookmarkRootIds.contains(item.guid)) {
|
||||
logger.w('Skipping move of root folder: ${item.guid}');
|
||||
continue;
|
||||
}
|
||||
if (item.parentGuid == targetParentGuid) continue;
|
||||
await _service.updateNode(
|
||||
item.guid,
|
||||
BookmarkInfo(parentGuid: targetParentGuid),
|
||||
);
|
||||
}
|
||||
ref.invalidateSelf();
|
||||
}
|
||||
|
||||
Future<void> deleteMany(Iterable<String> guids) async {
|
||||
for (final guid in guids) {
|
||||
if (bookmarkRootIds.contains(guid)) {
|
||||
logger.w('Skipping delete of root folder: $guid');
|
||||
continue;
|
||||
}
|
||||
await _service.deleteNode(guid);
|
||||
}
|
||||
ref.invalidateSelf();
|
||||
}
|
||||
|
||||
Future<void> flattenFolder({required BookmarkFolder folder}) async {
|
||||
if (folder.parentGuid == null || bookmarkRootIds.contains(folder.guid)) {
|
||||
logger.w('Cannot flatten root or parentless folder: ${folder.guid}');
|
||||
return;
|
||||
}
|
||||
// Fetch the full folder tree from storage to avoid operating on a
|
||||
// filtered subset (e.g. when search is active), which would silently
|
||||
// delete children that were not moved.
|
||||
final fullNode = await _service.getTree(folder.guid);
|
||||
final children = fullNode?.children;
|
||||
if (children != null) {
|
||||
for (final child in children) {
|
||||
await _service.updateNode(
|
||||
child.guid,
|
||||
BookmarkInfo(parentGuid: folder.parentGuid),
|
||||
);
|
||||
}
|
||||
}
|
||||
await _service.deleteNode(folder.guid);
|
||||
ref.invalidateSelf();
|
||||
}
|
||||
|
||||
/// Returns the GUIDs of all descendant folders of [guid] by fetching the
|
||||
/// full subtree from storage. This is safe to call even when the UI tree is
|
||||
/// filtered (e.g. during search), unlike the pure-utility
|
||||
/// [collectDescendantFolderGuids] which only walks the in-memory tree.
|
||||
Future<Set<String>> getDescendantFolderGuids(String guid) async {
|
||||
final node = await _service.getTree(guid, recursive: true);
|
||||
if (node == null) return const {};
|
||||
final result = <String>{};
|
||||
void collect(BookmarkNode n) {
|
||||
for (final child in n.children ?? const <BookmarkNode>[]) {
|
||||
if (child.type == BookmarkNodeType.folder) {
|
||||
result.add(child.guid);
|
||||
collect(child);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
collect(node);
|
||||
return result;
|
||||
}
|
||||
|
||||
Future<void> eraseEverything(BookmarkRoot root) async {
|
||||
await _service.eraseEverything(root);
|
||||
ref.invalidateSelf();
|
||||
}
|
||||
|
||||
Future<int> importFromJSON(String jsonString, {bool replace = false}) async {
|
||||
final count = await _jsonUtils.importFromJSON(jsonString, replace: replace);
|
||||
ref.invalidateSelf();
|
||||
return count;
|
||||
}
|
||||
|
||||
Future<int> importFromHTML(String htmlString, {bool replace = false}) async {
|
||||
final count = await _htmlUtils.importFromHTML(htmlString, replace: replace);
|
||||
ref.invalidateSelf();
|
||||
return count;
|
||||
}
|
||||
|
||||
Future<Map<String, dynamic>?> exportToJson({
|
||||
required BookmarkRoot root,
|
||||
}) async {
|
||||
return await _jsonUtils.exportToJson(root: root);
|
||||
}
|
||||
|
||||
Future<String> exportToHTML({required BookmarkRoot root}) async {
|
||||
return await _htmlUtils.exportToHTML(root: root);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<BookmarkItem?> build() async {
|
||||
final node = await _service.getTree(BookmarkRoot.root.id, recursive: true);
|
||||
return node.mapNotNull(BookmarkItem.parseRecursive);
|
||||
}
|
||||
}
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'bookmarks.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(BookmarksRepository)
|
||||
final bookmarksRepositoryProvider = BookmarksRepositoryProvider._();
|
||||
|
||||
final class BookmarksRepositoryProvider
|
||||
extends $AsyncNotifierProvider<BookmarksRepository, BookmarkItem?> {
|
||||
BookmarksRepositoryProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'bookmarksRepositoryProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$bookmarksRepositoryHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
BookmarksRepository create() => BookmarksRepository();
|
||||
}
|
||||
|
||||
String _$bookmarksRepositoryHash() =>
|
||||
r'2169d5b354c4a22192096451c96ab1490cf55ab4';
|
||||
|
||||
abstract class _$BookmarksRepository extends $AsyncNotifier<BookmarkItem?> {
|
||||
FutureOr<BookmarkItem?> build();
|
||||
@$mustCallSuper
|
||||
@override
|
||||
void runBuild() {
|
||||
final ref = this.ref as $Ref<AsyncValue<BookmarkItem?>, BookmarkItem?>;
|
||||
final element =
|
||||
ref.element
|
||||
as $ClassProviderElement<
|
||||
AnyNotifier<AsyncValue<BookmarkItem?>, BookmarkItem?>,
|
||||
AsyncValue<BookmarkItem?>,
|
||||
Object?,
|
||||
Object?
|
||||
>;
|
||||
element.handleCreate(ref, build);
|
||||
}
|
||||
}
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
|
||||
import 'package:weblibre/features/geckoview/features/bookmarks/domain/entities/bookmark_item.dart';
|
||||
import 'package:weblibre/features/geckoview/features/bookmarks/domain/entities/bookmark_sort_type.dart';
|
||||
|
||||
/// Recursively sorts a bookmark tree by the given sort type.
|
||||
/// Root-level built-in folders are kept in their canonical order.
|
||||
BookmarkItem sortBookmarkTree(
|
||||
BookmarkItem item,
|
||||
BookmarkSortType sortType, {
|
||||
bool isRoot = false,
|
||||
}) {
|
||||
if (sortType == BookmarkSortType.manual) return item;
|
||||
|
||||
if (item is BookmarkFolder && item.children != null) {
|
||||
final sortedChildren = item.children!.map((child) {
|
||||
return sortBookmarkTree(child, sortType);
|
||||
}).toList();
|
||||
|
||||
// At root level, keep built-in root folders pinned in original order
|
||||
if (isRoot) {
|
||||
final rootFolders = <BookmarkItem>[];
|
||||
final nonRootItems = <BookmarkItem>[];
|
||||
for (final child in sortedChildren) {
|
||||
if (bookmarkRootIds.contains(child.guid)) {
|
||||
rootFolders.add(child);
|
||||
} else {
|
||||
nonRootItems.add(child);
|
||||
}
|
||||
}
|
||||
nonRootItems.sort((a, b) => compareBookmarkItems(a, b, sortType));
|
||||
return BookmarkFolder(
|
||||
guid: item.guid,
|
||||
parentGuid: item.parentGuid,
|
||||
title: item.title,
|
||||
position: item.position,
|
||||
dateAdded: item.dateAdded,
|
||||
children: [...rootFolders, ...nonRootItems],
|
||||
);
|
||||
}
|
||||
|
||||
sortedChildren.sort((a, b) => compareBookmarkItems(a, b, sortType));
|
||||
return BookmarkFolder(
|
||||
guid: item.guid,
|
||||
parentGuid: item.parentGuid,
|
||||
title: item.title,
|
||||
position: item.position,
|
||||
dateAdded: item.dateAdded,
|
||||
children: sortedChildren,
|
||||
);
|
||||
}
|
||||
|
||||
return item;
|
||||
}
|
||||
|
||||
/// Collects all descendant folder GUIDs from a folder (not including the folder itself).
|
||||
Set<String> collectDescendantFolderGuids(BookmarkFolder folder) {
|
||||
final result = <String>{};
|
||||
if (folder.children != null) {
|
||||
for (final child in folder.children!) {
|
||||
if (child is BookmarkFolder) {
|
||||
result.add(child.guid);
|
||||
result.addAll(collectDescendantFolderGuids(child));
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Resolves BookmarkItems from a tree by their GUIDs.
|
||||
List<BookmarkItem> resolveSelectedItems(BookmarkItem root, Set<String> guids) {
|
||||
final result = <BookmarkItem>[];
|
||||
_collectByGuids(root, guids, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
void _collectByGuids(
|
||||
BookmarkItem item,
|
||||
Set<String> guids,
|
||||
List<BookmarkItem> result,
|
||||
) {
|
||||
if (guids.contains(item.guid)) {
|
||||
result.add(item);
|
||||
}
|
||||
if (item is BookmarkFolder && item.children != null) {
|
||||
for (final child in item.children!) {
|
||||
_collectByGuids(child, guids, result);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether a folder can be flattened (non-root, has a parent, has children).
|
||||
bool canFlattenFolder(BookmarkFolder folder) {
|
||||
return folder.parentGuid != null &&
|
||||
!bookmarkRootIds.contains(folder.guid) &&
|
||||
folder.children != null &&
|
||||
folder.children!.isNotEmpty;
|
||||
}
|
||||
|
||||
/// Normalizes a selection set: removes items that are descendants of selected folders.
|
||||
/// This prevents double-applying moves when both a folder and its children are selected.
|
||||
Set<String> normalizeSelection(BookmarkItem root, Set<String> selectedGuids) {
|
||||
final items = resolveSelectedItems(root, selectedGuids);
|
||||
final folderGuidsToRemove = <String>{};
|
||||
|
||||
for (final item in items) {
|
||||
if (item is BookmarkFolder) {
|
||||
_collectAllDescendantGuids(item, folderGuidsToRemove);
|
||||
}
|
||||
}
|
||||
|
||||
return selectedGuids.difference(folderGuidsToRemove);
|
||||
}
|
||||
|
||||
void _collectAllDescendantGuids(BookmarkFolder folder, Set<String> result) {
|
||||
if (folder.children != null) {
|
||||
for (final child in folder.children!) {
|
||||
result.add(child.guid);
|
||||
if (child is BookmarkFolder) {
|
||||
_collectAllDescendantGuids(child, result);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns GUIDs of all bookmark entries matching [url] in the tree.
|
||||
List<String> bookmarkGuidsForUrl(BookmarkItem? root, Uri? url) {
|
||||
final result = <String>[];
|
||||
if (root == null || url == null) return result;
|
||||
|
||||
void collect(BookmarkItem item) {
|
||||
if (item is BookmarkEntry && item.url == url) {
|
||||
result.add(item.guid);
|
||||
}
|
||||
if (item is BookmarkFolder) {
|
||||
for (final child in item.children ?? const <BookmarkItem>[]) {
|
||||
collect(child);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
collect(root);
|
||||
return result;
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
Future<bool?> showDeleteBookmarkDialog(BuildContext context) {
|
||||
return showDialog<bool?>(
|
||||
context: context,
|
||||
builder: (BuildContext context) {
|
||||
return AlertDialog(
|
||||
icon: const Icon(Icons.warning),
|
||||
title: const Text('Delete Bookmark'),
|
||||
content: const Text('Are you sure you want to delete this Bookmark?'),
|
||||
actions: <Widget>[
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
Navigator.pop(context, false);
|
||||
},
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
Navigator.pop(context, true);
|
||||
},
|
||||
child: const Text('Delete'),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
Future<bool?> showDeleteFolderDialog(BuildContext context) {
|
||||
return showDialog<bool?>(
|
||||
context: context,
|
||||
builder: (BuildContext context) {
|
||||
return AlertDialog(
|
||||
icon: const Icon(Icons.warning),
|
||||
title: const Text('Delete Folder'),
|
||||
content: const Text(
|
||||
'Are you sure you want to delete this Folder including all bookmarks?',
|
||||
),
|
||||
actions: <Widget>[
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
Navigator.pop(context, false);
|
||||
},
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
Navigator.pop(context, true);
|
||||
},
|
||||
child: const Text('Delete'),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
Future<bool?> showImportBookmarksDialog(BuildContext context) {
|
||||
return showDialog<bool?>(
|
||||
context: context,
|
||||
builder: (BuildContext context) {
|
||||
return AlertDialog(
|
||||
title: const Text('Import Bookmarks'),
|
||||
content: const Text(
|
||||
'Do you want to erase all existing bookmarks before importing?\n\n'
|
||||
'Choose "Replace" to delete existing bookmarks, or "Merge" to keep them.',
|
||||
),
|
||||
actions: <Widget>[
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
Navigator.pop(context, false);
|
||||
},
|
||||
child: const Text('Merge'),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
Navigator.pop(context, true);
|
||||
},
|
||||
child: const Text('Replace'),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_hooks/flutter_hooks.dart';
|
||||
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:weblibre/features/geckoview/features/bookmarks/presentation/widgets/folder_tree_picker.dart';
|
||||
|
||||
/// Shows a bottom sheet for selecting a bookmark folder destination (for move operations).
|
||||
///
|
||||
/// Returns the selected folder GUID, or null if cancelled.
|
||||
Future<String?> showSelectBookmarkFolderDialog(
|
||||
BuildContext context, {
|
||||
Set<String> excludeFolderGuids = const {},
|
||||
String? initialFolderGuid,
|
||||
}) {
|
||||
return showModalBottomSheet<String>(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
builder: (context) => _SelectBookmarkFolderSheet(
|
||||
excludeFolderGuids: excludeFolderGuids,
|
||||
initialFolderGuid: initialFolderGuid,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
class _SelectBookmarkFolderSheet extends HookConsumerWidget {
|
||||
final Set<String> excludeFolderGuids;
|
||||
final String? initialFolderGuid;
|
||||
|
||||
const _SelectBookmarkFolderSheet({
|
||||
required this.excludeFolderGuids,
|
||||
this.initialFolderGuid,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final selectedGuid = useState(initialFolderGuid ?? BookmarkRoot.mobile.id);
|
||||
|
||||
return SafeArea(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(
|
||||
'Move to Folder',
|
||||
style: Theme.of(context).textTheme.titleLarge,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
ConstrainedBox(
|
||||
constraints: BoxConstraints(
|
||||
maxHeight: MediaQuery.of(context).size.height * 0.5,
|
||||
),
|
||||
child: SingleChildScrollView(
|
||||
child: FolderTreePicker(
|
||||
selectedFolderGuid: selectedGuid,
|
||||
excludeFolderGuids: excludeFolderGuids,
|
||||
entryGuid: BookmarkRoot.root.id,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.end,
|
||||
children: [
|
||||
TextButton(
|
||||
onPressed: () => context.pop(),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
FilledButton(
|
||||
onPressed: () => context.pop(selectedGuid.value),
|
||||
child: const Text('Move'),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
+208
@@ -0,0 +1,208 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
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:flutter_mozilla_components/flutter_mozilla_components.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:weblibre/features/geckoview/features/bookmarks/domain/entities/bookmark_item.dart';
|
||||
import 'package:weblibre/features/geckoview/features/bookmarks/domain/repositories/bookmarks.dart';
|
||||
import 'package:weblibre/features/geckoview/features/bookmarks/presentation/dialogs/delete_bookmark_dialog.dart';
|
||||
import 'package:weblibre/features/geckoview/features/bookmarks/presentation/widgets/folder_tree_picker.dart';
|
||||
import 'package:weblibre/utils/form_validators.dart';
|
||||
import 'package:weblibre/utils/uri_input_parser.dart';
|
||||
|
||||
class BookmarkEntryEditScreen extends HookConsumerWidget {
|
||||
final BookmarkInfo? initialInfo;
|
||||
final BookmarkEntry? exisitingEntry;
|
||||
|
||||
const BookmarkEntryEditScreen({
|
||||
super.key,
|
||||
required this.exisitingEntry,
|
||||
required this.initialInfo,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final formKey = useMemoized(() => GlobalKey<FormState>());
|
||||
|
||||
final nameTextController = useTextEditingController(
|
||||
text: initialInfo?.title ?? exisitingEntry?.title,
|
||||
);
|
||||
final urlTextController = useTextEditingController(
|
||||
text: initialInfo?.url ?? exisitingEntry?.url.toString(),
|
||||
);
|
||||
|
||||
final parentGuid = useState(
|
||||
initialInfo?.parentGuid ??
|
||||
exisitingEntry?.parentGuid ??
|
||||
BookmarkRoot.mobile.id,
|
||||
);
|
||||
|
||||
final addToTop = useState(false);
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: (exisitingEntry != null)
|
||||
? const Text('Edit Bookmark')
|
||||
: const Text('Create Bookmark'),
|
||||
actions: [
|
||||
IconButton(
|
||||
onPressed: () async {
|
||||
if (formKey.currentState?.validate() ?? false) {
|
||||
var newUrl = parseValidatedUrl(
|
||||
urlTextController.text,
|
||||
eagerParsing: true,
|
||||
onlyHttpProtocol: true,
|
||||
);
|
||||
|
||||
if (newUrl == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
newUrl = redactUriCredentials(newUrl);
|
||||
|
||||
if (exisitingEntry != null) {
|
||||
await ref
|
||||
.read(bookmarksRepositoryProvider.notifier)
|
||||
.editBookmark(
|
||||
guid: exisitingEntry!.guid,
|
||||
title:
|
||||
(nameTextController.text != exisitingEntry!.title)
|
||||
? nameTextController.text
|
||||
: null,
|
||||
parentGuid:
|
||||
(parentGuid.value != exisitingEntry!.parentGuid)
|
||||
? parentGuid.value
|
||||
: null,
|
||||
url: (newUrl != exisitingEntry!.url) ? newUrl : null,
|
||||
);
|
||||
|
||||
if (context.mounted) {
|
||||
context.pop();
|
||||
}
|
||||
} else {
|
||||
await ref
|
||||
.read(bookmarksRepositoryProvider.notifier)
|
||||
.addBookmark(
|
||||
parentGuid: parentGuid.value,
|
||||
title: nameTextController.text,
|
||||
url: newUrl,
|
||||
position: addToTop.value ? 0 : null,
|
||||
);
|
||||
|
||||
if (context.mounted) {
|
||||
context.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
icon: const Icon(Icons.check),
|
||||
),
|
||||
],
|
||||
),
|
||||
body: SafeArea(
|
||||
child: Form(
|
||||
key: formKey,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12.0),
|
||||
child: ListView(
|
||||
children: [
|
||||
TextFormField(
|
||||
controller: nameTextController,
|
||||
decoration: const InputDecoration(
|
||||
label: Text('Name'),
|
||||
floatingLabelBehavior: FloatingLabelBehavior.always,
|
||||
),
|
||||
minLines: 1,
|
||||
maxLines: 3,
|
||||
validator: validateRequired,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
TextFormField(
|
||||
controller: urlTextController,
|
||||
keyboardType: TextInputType.url,
|
||||
minLines: 1,
|
||||
maxLines: 10,
|
||||
decoration: const InputDecoration(
|
||||
label: Text('URL'),
|
||||
hintText: 'https://example.com/',
|
||||
floatingLabelBehavior: FloatingLabelBehavior.always,
|
||||
),
|
||||
validator: (value) {
|
||||
return validateUrl(
|
||||
value,
|
||||
onlyHttpProtocol: true,
|
||||
eagerParsing: true,
|
||||
);
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
FolderTreePicker(
|
||||
selectedFolderGuid: parentGuid,
|
||||
entryGuid: BookmarkRoot.root.id,
|
||||
),
|
||||
if (exisitingEntry == null) ...[
|
||||
const SizedBox(height: 8),
|
||||
SwitchListTile(
|
||||
contentPadding: EdgeInsets.zero,
|
||||
title: const Text('Add to top'),
|
||||
value: addToTop.value,
|
||||
onChanged: (value) => addToTop.value = value,
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 16),
|
||||
if (exisitingEntry != null)
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: OutlinedButton.icon(
|
||||
style: OutlinedButton.styleFrom(
|
||||
side: BorderSide(
|
||||
color: Theme.of(context).colorScheme.error,
|
||||
),
|
||||
foregroundColor: Theme.of(context).colorScheme.error,
|
||||
iconColor: Theme.of(context).colorScheme.error,
|
||||
),
|
||||
label: const Text('Delete'),
|
||||
icon: const Icon(MdiIcons.bookmarkRemove),
|
||||
onPressed: () async {
|
||||
final result = await showDeleteBookmarkDialog(context);
|
||||
|
||||
if (result == true) {
|
||||
await ref
|
||||
.read(bookmarksRepositoryProvider.notifier)
|
||||
.delete(exisitingEntry!.guid);
|
||||
|
||||
if (context.mounted) {
|
||||
context.pop();
|
||||
}
|
||||
}
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_hooks/flutter_hooks.dart';
|
||||
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:weblibre/features/geckoview/features/bookmarks/domain/entities/bookmark_item.dart';
|
||||
import 'package:weblibre/features/geckoview/features/bookmarks/domain/repositories/bookmarks.dart';
|
||||
import 'package:weblibre/features/geckoview/features/bookmarks/presentation/dialogs/delete_folder_dialog.dart';
|
||||
import 'package:weblibre/features/geckoview/features/bookmarks/presentation/widgets/folder_tree_picker.dart';
|
||||
import 'package:weblibre/utils/form_validators.dart';
|
||||
|
||||
class BookmarkFolderEditScreen extends HookConsumerWidget {
|
||||
final String? parentGuid;
|
||||
final BookmarkFolder? folder;
|
||||
|
||||
const BookmarkFolderEditScreen({
|
||||
super.key,
|
||||
required this.folder,
|
||||
this.parentGuid,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final formKey = useMemoized(() => GlobalKey<FormState>());
|
||||
final nameTextController = useTextEditingController(text: folder?.title);
|
||||
|
||||
final currentParentGuid = useState(
|
||||
parentGuid ?? folder?.parentGuid ?? BookmarkRoot.mobile.id,
|
||||
);
|
||||
|
||||
final addToTop = useState(false);
|
||||
|
||||
// Check if this is a bookmark root folder (these cannot be moved)
|
||||
final isBookmarkRoot =
|
||||
folder != null && bookmarkRootIds.contains(folder!.guid);
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: (folder != null)
|
||||
? const Text('Edit Folder')
|
||||
: const Text('Create Folder'),
|
||||
actions: [
|
||||
IconButton(
|
||||
onPressed: () async {
|
||||
if (formKey.currentState?.validate() ?? false) {
|
||||
if (folder != null) {
|
||||
await ref
|
||||
.read(bookmarksRepositoryProvider.notifier)
|
||||
.editFolder(
|
||||
guid: folder!.guid,
|
||||
title: (nameTextController.text != folder!.title)
|
||||
? nameTextController.text
|
||||
: null,
|
||||
parentGuid:
|
||||
(!isBookmarkRoot &&
|
||||
currentParentGuid.value != folder!.parentGuid)
|
||||
? currentParentGuid.value
|
||||
: null,
|
||||
);
|
||||
|
||||
if (context.mounted) {
|
||||
context.pop();
|
||||
}
|
||||
} else {
|
||||
await ref
|
||||
.read(bookmarksRepositoryProvider.notifier)
|
||||
.addFolder(
|
||||
parentGuid: currentParentGuid.value,
|
||||
title: nameTextController.text,
|
||||
position: addToTop.value ? 0 : null,
|
||||
);
|
||||
|
||||
if (context.mounted) {
|
||||
context.pop();
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
icon: const Icon(Icons.check),
|
||||
),
|
||||
],
|
||||
),
|
||||
body: SafeArea(
|
||||
child: Form(
|
||||
key: formKey,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12.0),
|
||||
child: ListView(
|
||||
children: [
|
||||
TextFormField(
|
||||
controller: nameTextController,
|
||||
decoration: const InputDecoration(
|
||||
label: Text('Name'),
|
||||
floatingLabelBehavior: FloatingLabelBehavior.always,
|
||||
),
|
||||
validator: validateRequired,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
if (!isBookmarkRoot) ...[
|
||||
FolderTreePicker(
|
||||
selectedFolderGuid: currentParentGuid,
|
||||
excludeFolderGuids: folder != null
|
||||
? {folder!.guid}
|
||||
: const {},
|
||||
entryGuid: BookmarkRoot.root.id,
|
||||
),
|
||||
if (folder == null) ...[
|
||||
const SizedBox(height: 8),
|
||||
SwitchListTile(
|
||||
contentPadding: EdgeInsets.zero,
|
||||
title: const Text('Add to top'),
|
||||
value: addToTop.value,
|
||||
onChanged: (value) => addToTop.value = value,
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 16),
|
||||
],
|
||||
if (folder != null)
|
||||
SizedBox(
|
||||
width: double.infinity,
|
||||
child: OutlinedButton.icon(
|
||||
style: OutlinedButton.styleFrom(
|
||||
side: BorderSide(
|
||||
color: Theme.of(context).colorScheme.error,
|
||||
),
|
||||
foregroundColor: Theme.of(context).colorScheme.error,
|
||||
iconColor: Theme.of(context).colorScheme.error,
|
||||
),
|
||||
label: const Text('Delete'),
|
||||
icon: const Icon(Icons.delete),
|
||||
onPressed: () async {
|
||||
final result = await showDeleteFolderDialog(context);
|
||||
|
||||
if (result == true) {
|
||||
await ref
|
||||
.read(bookmarksRepositoryProvider.notifier)
|
||||
.delete(folder!.guid);
|
||||
|
||||
if (context.mounted) {
|
||||
context.pop();
|
||||
}
|
||||
}
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
+1089
File diff suppressed because it is too large.
Load diff
+164
@@ -0,0 +1,164 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:animated_tree_view/animated_tree_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:flutter_mozilla_components/flutter_mozilla_components.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:weblibre/core/routing/routes.dart';
|
||||
import 'package:weblibre/features/geckoview/features/bookmarks/domain/entities/bookmark_item.dart';
|
||||
import 'package:weblibre/features/geckoview/features/bookmarks/domain/providers/bookmarks.dart';
|
||||
import 'package:weblibre/presentation/widgets/failure_widget.dart';
|
||||
|
||||
/// A widget that displays a tree view of bookmark folders and allows the user
|
||||
/// to select a parent folder.
|
||||
///
|
||||
/// When editing a folder, pass [excludeFolderGuids] to prevent selecting the
|
||||
/// folders or their descendants as the parent (which would create a circular reference).
|
||||
class FolderTreePicker extends HookConsumerWidget {
|
||||
/// The currently selected folder GUID
|
||||
final ValueNotifier<String> selectedFolderGuid;
|
||||
|
||||
/// Optional folder GUIDs to exclude from the tree (along with their descendants).
|
||||
/// Used when editing/moving folders to prevent circular parent relationships.
|
||||
final Set<String> excludeFolderGuids;
|
||||
|
||||
final String entryGuid;
|
||||
|
||||
const FolderTreePicker({
|
||||
required this.selectedFolderGuid,
|
||||
required this.entryGuid,
|
||||
this.excludeFolderGuids = const {},
|
||||
super.key,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final treeKey = useMemoized(() => GlobalKey<TreeViewState>());
|
||||
|
||||
final folderList = ref.watch(bookmarksProvider<BookmarkFolder>(entryGuid));
|
||||
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('Folder', style: Theme.of(context).textTheme.labelMedium),
|
||||
folderList.when(
|
||||
skipLoadingOnReload: true,
|
||||
data: (list) {
|
||||
TreeNode<BookmarkFolder> addChildren(
|
||||
TreeNode<BookmarkFolder>? parent,
|
||||
BookmarkFolder item,
|
||||
) {
|
||||
final node = TreeNode(key: item.guid, data: item, parent: parent);
|
||||
final targetNode = (parent?..add(node)) ?? node;
|
||||
|
||||
if (item.children != null) {
|
||||
for (final child in item.children!) {
|
||||
// Skip excluded folders and their descendants
|
||||
if (child is BookmarkFolder &&
|
||||
!excludeFolderGuids.contains(child.guid)) {
|
||||
addChildren(node, child);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return targetNode;
|
||||
}
|
||||
|
||||
final root = (list != null)
|
||||
? addChildren(null, list)
|
||||
: TreeNode<BookmarkFolder>.root();
|
||||
|
||||
return TreeView.simple(
|
||||
key: treeKey,
|
||||
tree: root,
|
||||
shrinkWrap: true,
|
||||
showRootNode: entryGuid != BookmarkRoot.root.id,
|
||||
onTreeReady: (controller) {
|
||||
controller.expandAllChildren(root, recursive: true);
|
||||
},
|
||||
expansionIndicatorBuilder: (context, tree) =>
|
||||
ChevronIndicator.upDown(
|
||||
tree: tree,
|
||||
padding: const EdgeInsets.symmetric(
|
||||
vertical: 16.0,
|
||||
horizontal: 12.0,
|
||||
),
|
||||
),
|
||||
builder: (context, item) {
|
||||
final isSelected = item.data?.guid == selectedFolderGuid.value;
|
||||
|
||||
// BookmarkRoot.root cannot be selected as a parent
|
||||
final isRootFolder = item.data?.guid == BookmarkRoot.root.id;
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(right: 42.0),
|
||||
child: switch (item.data) {
|
||||
final BookmarkFolder folder => ListTile(
|
||||
key: ValueKey(folder.guid),
|
||||
contentPadding: EdgeInsets.zero,
|
||||
selected: isSelected,
|
||||
enabled: !isRootFolder,
|
||||
leading: (item.isExpanded)
|
||||
? const Icon(MdiIcons.folderOpen)
|
||||
: const Icon(MdiIcons.folder),
|
||||
trailing: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (isSelected) const Icon(Icons.check),
|
||||
IconButton(
|
||||
onPressed: () async {
|
||||
await BookmarkFolderAddRoute(
|
||||
parentGuid: folder.guid,
|
||||
).push(context);
|
||||
},
|
||||
icon: const Icon(MdiIcons.folderPlus),
|
||||
),
|
||||
],
|
||||
),
|
||||
title: Text(folder.title),
|
||||
onTap: !isRootFolder
|
||||
? () {
|
||||
selectedFolderGuid.value = folder.guid;
|
||||
}
|
||||
: null,
|
||||
),
|
||||
null => const SizedBox.shrink(),
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
error: (error, stackTrace) => Center(
|
||||
child: FailureWidget(
|
||||
title: 'Failed to load Bookmark Folders',
|
||||
exception: error,
|
||||
onRetry: () {
|
||||
ref.invalidate(bookmarksProvider<BookmarkFolder>(entryGuid));
|
||||
},
|
||||
),
|
||||
),
|
||||
loading: () => const Center(child: CircularProgressIndicator()),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
+594
@@ -0,0 +1,594 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
|
||||
import 'package:html/dom.dart' as dom;
|
||||
import 'package:html/parser.dart' as html_parser;
|
||||
import 'package:weblibre/core/logger.dart';
|
||||
|
||||
const _containerNormal = 0;
|
||||
const _containerToolbar = 1;
|
||||
const _containerMenu = 2;
|
||||
const _containerUnfiled = 3;
|
||||
const _containerPlaces = 4;
|
||||
|
||||
const _exportIndent = ' ';
|
||||
|
||||
class _Frame {
|
||||
final Map<String, dynamic> folder;
|
||||
int containerNesting = 0;
|
||||
int lastContainerType = _containerNormal;
|
||||
String previousText = '';
|
||||
bool inDescription = false;
|
||||
String? previousLink;
|
||||
Map<String, dynamic>? previousItem;
|
||||
DateTime? previousDateAdded;
|
||||
DateTime? previousLastModifiedDate;
|
||||
|
||||
_Frame(this.folder);
|
||||
}
|
||||
|
||||
class BookmarkHTMLUtils {
|
||||
final GeckoBookmarksService _service;
|
||||
|
||||
BookmarkHTMLUtils(this._service);
|
||||
|
||||
/// Import bookmarks from HTML string
|
||||
Future<int> importFromHTML(String htmlString, {bool replace = false}) async {
|
||||
final importer = _BookmarkImporter(_service, replace);
|
||||
return await importer.importFromHTML(htmlString);
|
||||
}
|
||||
|
||||
/// Export bookmarks to HTML string
|
||||
Future<String> exportToHTML({required BookmarkRoot root}) async {
|
||||
final tree = await _service.getTree(root.id, recursive: true);
|
||||
if (tree == null) {
|
||||
throw Exception('Failed to get bookmarks tree');
|
||||
}
|
||||
|
||||
final exporter = _BookmarkExporter(tree);
|
||||
return exporter.exportToHTML();
|
||||
}
|
||||
}
|
||||
|
||||
class _BookmarkImporter {
|
||||
final GeckoBookmarksService _service;
|
||||
final bool _isImportDefaults;
|
||||
final Map<String, dynamic> _bookmarkTree;
|
||||
final List<_Frame> _frames = [];
|
||||
|
||||
_BookmarkImporter(this._service, this._isImportDefaults)
|
||||
: _bookmarkTree = {
|
||||
'type': BookmarkNodeType.folder.index,
|
||||
'guid': BookmarkRoot.menu.id,
|
||||
'children': <Map<String, dynamic>>[],
|
||||
} {
|
||||
_frames.add(_Frame(_bookmarkTree));
|
||||
}
|
||||
|
||||
_Frame get _curFrame => _frames.last;
|
||||
|
||||
Future<int> importFromHTML(String htmlString) async {
|
||||
final document = html_parser.parse(htmlString);
|
||||
_walkTreeForImport(document.body);
|
||||
return await _importBookmarks();
|
||||
}
|
||||
|
||||
dom.Node? _nextSibling(dom.Node node) {
|
||||
final parent = node.parent;
|
||||
if (parent == null) return null;
|
||||
|
||||
final siblings = parent.nodes;
|
||||
final index = siblings.indexOf(node);
|
||||
|
||||
if (index != -1 && index + 1 < siblings.length) {
|
||||
return siblings[index + 1];
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
void _walkTreeForImport(dom.Node? node) {
|
||||
if (node == null) return;
|
||||
|
||||
dom.Node? current = node;
|
||||
dom.Node? next;
|
||||
|
||||
for (;;) {
|
||||
if (current?.nodeType == dom.Node.ELEMENT_NODE) {
|
||||
_openContainer(current! as dom.Element);
|
||||
} else if (current?.nodeType == dom.Node.TEXT_NODE) {
|
||||
_appendText(current!.text ?? '');
|
||||
}
|
||||
|
||||
if ((next = current?.firstChild) != null) {
|
||||
current = next;
|
||||
continue;
|
||||
}
|
||||
|
||||
for (;;) {
|
||||
if (current?.nodeType == dom.Node.ELEMENT_NODE) {
|
||||
_closeContainer(current! as dom.Element);
|
||||
}
|
||||
if (current == node) return;
|
||||
if ((next = _nextSibling(current!)) != null) {
|
||||
current = next;
|
||||
break;
|
||||
}
|
||||
current = current.parentNode;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void _openContainer(dom.Element element) {
|
||||
switch (element.localName) {
|
||||
case 'h2':
|
||||
case 'h3':
|
||||
case 'h4':
|
||||
case 'h5':
|
||||
case 'h6':
|
||||
_handleHeadBegin(element);
|
||||
case 'a':
|
||||
_handleLinkBegin(element);
|
||||
case 'dl':
|
||||
case 'ul':
|
||||
case 'menu':
|
||||
_handleContainerBegin();
|
||||
case 'dd':
|
||||
_curFrame.inDescription = true;
|
||||
case 'hr':
|
||||
_handleSeparator();
|
||||
}
|
||||
}
|
||||
|
||||
void _closeContainer(dom.Element element) {
|
||||
final frame = _curFrame;
|
||||
|
||||
if (frame.inDescription) {
|
||||
frame.previousText = '';
|
||||
frame.inDescription = false;
|
||||
}
|
||||
|
||||
switch (element.localName) {
|
||||
case 'dl':
|
||||
case 'ul':
|
||||
case 'menu':
|
||||
_handleContainerEnd();
|
||||
case 'h2':
|
||||
case 'h3':
|
||||
case 'h4':
|
||||
case 'h5':
|
||||
case 'h6':
|
||||
_handleHeadEnd();
|
||||
case 'a':
|
||||
_handleLinkEnd();
|
||||
}
|
||||
}
|
||||
|
||||
void _appendText(String str) {
|
||||
_curFrame.previousText += str;
|
||||
}
|
||||
|
||||
void _handleHeadBegin(dom.Element element) {
|
||||
final frame = _curFrame;
|
||||
|
||||
frame.previousLink = null;
|
||||
frame.lastContainerType = _containerNormal;
|
||||
|
||||
if (frame.containerNesting == 0 && _frames.length > 1) {
|
||||
_frames.removeLast();
|
||||
}
|
||||
|
||||
if (element.attributes.containsKey('personal_toolbar_folder')) {
|
||||
if (_isImportDefaults) {
|
||||
frame.lastContainerType = _containerToolbar;
|
||||
}
|
||||
} else if (element.attributes.containsKey('bookmarks_menu')) {
|
||||
if (_isImportDefaults) {
|
||||
frame.lastContainerType = _containerMenu;
|
||||
}
|
||||
} else if (element.attributes.containsKey('unfiled_bookmarks_folder')) {
|
||||
if (_isImportDefaults) {
|
||||
frame.lastContainerType = _containerUnfiled;
|
||||
}
|
||||
} else if (element.attributes.containsKey('places_root')) {
|
||||
if (_isImportDefaults) {
|
||||
frame.lastContainerType = _containerPlaces;
|
||||
}
|
||||
} else {
|
||||
final addDate = element.attributes['add_date'];
|
||||
if (addDate != null) {
|
||||
frame.previousDateAdded = _convertImportedDateToInternalDate(addDate);
|
||||
}
|
||||
final modDate = element.attributes['last_modified'];
|
||||
if (modDate != null) {
|
||||
frame.previousLastModifiedDate = _convertImportedDateToInternalDate(
|
||||
modDate,
|
||||
);
|
||||
}
|
||||
}
|
||||
_curFrame.previousText = '';
|
||||
}
|
||||
|
||||
void _handleLinkBegin(dom.Element element) {
|
||||
final frame = _curFrame;
|
||||
|
||||
frame.previousItem = null;
|
||||
frame.previousText = '';
|
||||
|
||||
final href = element.attributes['href']?.trim();
|
||||
final dateAdded = element.attributes['add_date']?.trim();
|
||||
final lastModified = element.attributes['last_modified']?.trim();
|
||||
final tags = element.attributes['tags']?.trim();
|
||||
final keyword = element.attributes['shortcuturl']?.trim();
|
||||
final postData = element.attributes['post_data']?.trim();
|
||||
final lastCharset = element.attributes['last_charset']?.trim();
|
||||
|
||||
if (href == null || href.isEmpty) {
|
||||
frame.previousLink = null;
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
final uri = Uri.parse(href);
|
||||
if (!uri.hasScheme) {
|
||||
frame.previousLink = null;
|
||||
return;
|
||||
}
|
||||
frame.previousLink = uri.toString();
|
||||
} catch (e) {
|
||||
frame.previousLink = null;
|
||||
return;
|
||||
}
|
||||
|
||||
final bookmark = <String, dynamic>{'url': frame.previousLink};
|
||||
|
||||
if (dateAdded != null) {
|
||||
bookmark['dateAdded'] = _convertImportedDateToInternalDate(
|
||||
dateAdded,
|
||||
).millisecondsSinceEpoch;
|
||||
}
|
||||
if (lastModified != null) {
|
||||
bookmark['lastModified'] = _convertImportedDateToInternalDate(
|
||||
lastModified,
|
||||
).millisecondsSinceEpoch;
|
||||
}
|
||||
if (dateAdded == null && lastModified != null) {
|
||||
bookmark['dateAdded'] = bookmark['lastModified'];
|
||||
}
|
||||
|
||||
if (tags != null && tags.isNotEmpty) {
|
||||
bookmark['tags'] = tags;
|
||||
}
|
||||
if (keyword != null && keyword.isNotEmpty) {
|
||||
bookmark['keyword'] = keyword;
|
||||
}
|
||||
if (postData != null && postData.isNotEmpty) {
|
||||
bookmark['postData'] = postData;
|
||||
}
|
||||
if (lastCharset != null && lastCharset.isNotEmpty) {
|
||||
bookmark['charset'] = lastCharset;
|
||||
}
|
||||
|
||||
(frame.folder['children'] as List).add(bookmark);
|
||||
frame.previousItem = bookmark;
|
||||
}
|
||||
|
||||
void _handleContainerBegin() {
|
||||
_curFrame.containerNesting++;
|
||||
}
|
||||
|
||||
void _handleContainerEnd() {
|
||||
final frame = _curFrame;
|
||||
if (frame.containerNesting > 0) {
|
||||
frame.containerNesting--;
|
||||
}
|
||||
if (_frames.length > 1 && frame.containerNesting == 0) {
|
||||
_frames.removeLast();
|
||||
}
|
||||
}
|
||||
|
||||
void _handleHeadEnd() {
|
||||
_newFrame();
|
||||
}
|
||||
|
||||
void _handleLinkEnd() {
|
||||
final frame = _curFrame;
|
||||
frame.previousText = frame.previousText.trim();
|
||||
|
||||
if (frame.previousItem != null) {
|
||||
frame.previousItem!['title'] = frame.previousText;
|
||||
}
|
||||
|
||||
frame.previousText = '';
|
||||
}
|
||||
|
||||
void _handleSeparator() {
|
||||
final frame = _curFrame;
|
||||
final separator = <String, dynamic>{
|
||||
'type': BookmarkNodeType.separator.index,
|
||||
};
|
||||
(frame.folder['children'] as List).add(separator);
|
||||
frame.previousItem = separator;
|
||||
}
|
||||
|
||||
void _newFrame() {
|
||||
final frame = _curFrame;
|
||||
final containerTitle = frame.previousText;
|
||||
frame.previousText = '';
|
||||
final containerType = frame.lastContainerType;
|
||||
|
||||
final folder = <String, dynamic>{
|
||||
'children': <Map<String, dynamic>>[],
|
||||
'type': BookmarkNodeType.folder.index,
|
||||
};
|
||||
|
||||
switch (containerType) {
|
||||
case _containerNormal:
|
||||
folder['title'] = containerTitle;
|
||||
case _containerPlaces:
|
||||
folder['guid'] = BookmarkRoot.root.id;
|
||||
case _containerMenu:
|
||||
folder['guid'] = BookmarkRoot.menu.id;
|
||||
case _containerUnfiled:
|
||||
folder['guid'] = BookmarkRoot.unfiled.id;
|
||||
case _containerToolbar:
|
||||
folder['guid'] = BookmarkRoot.toolbar.id;
|
||||
}
|
||||
|
||||
(frame.folder['children'] as List).add(folder);
|
||||
|
||||
if (frame.previousDateAdded != null) {
|
||||
folder['dateAdded'] = frame.previousDateAdded!.millisecondsSinceEpoch;
|
||||
frame.previousDateAdded = null;
|
||||
}
|
||||
if (frame.previousLastModifiedDate != null) {
|
||||
folder['lastModified'] =
|
||||
frame.previousLastModifiedDate!.millisecondsSinceEpoch;
|
||||
frame.previousLastModifiedDate = null;
|
||||
}
|
||||
if (!folder.containsKey('dateAdded') &&
|
||||
folder.containsKey('lastModified')) {
|
||||
folder['dateAdded'] = folder['lastModified'];
|
||||
}
|
||||
|
||||
frame.previousItem = folder;
|
||||
_frames.add(_Frame(folder));
|
||||
}
|
||||
|
||||
DateTime _convertImportedDateToInternalDate(String seconds) {
|
||||
try {
|
||||
final parsed = int.tryParse(seconds);
|
||||
if (parsed != null) {
|
||||
return DateTime.fromMillisecondsSinceEpoch(parsed * 1000);
|
||||
}
|
||||
} catch (e) {
|
||||
// Fall through
|
||||
}
|
||||
return DateTime.now();
|
||||
}
|
||||
|
||||
List<Map<String, dynamic>> _getBookmarkTrees() {
|
||||
if (!_isImportDefaults) {
|
||||
return [_bookmarkTree];
|
||||
}
|
||||
|
||||
final bookmarkTrees = <Map<String, dynamic>>[_bookmarkTree];
|
||||
final children = _bookmarkTree['children'] as List<Map<String, dynamic>>;
|
||||
|
||||
_bookmarkTree['children'] = children.where((child) {
|
||||
final guid = child['guid'] as String?;
|
||||
if (guid != null && bookmarkRootIds.contains(guid)) {
|
||||
bookmarkTrees.add(child);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}).toList();
|
||||
|
||||
return bookmarkTrees;
|
||||
}
|
||||
|
||||
Future<int> _importBookmarks() async {
|
||||
if (_isImportDefaults) {
|
||||
// Delete bookmarks from each root folder (except root itself to avoid errors)
|
||||
for (final root in BookmarkRoot.values) {
|
||||
if (root != BookmarkRoot.root) {
|
||||
await _service.eraseEverything(root);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final bookmarkTrees = _getBookmarkTrees();
|
||||
int bookmarkCount = 0;
|
||||
|
||||
for (final tree in bookmarkTrees) {
|
||||
final children = tree['children'] as List?;
|
||||
if (children == null || children.isEmpty) continue;
|
||||
|
||||
bookmarkCount += await _insertTree(tree);
|
||||
}
|
||||
|
||||
return bookmarkCount;
|
||||
}
|
||||
|
||||
Future<int> _insertTree(Map<String, dynamic> node) async {
|
||||
int count = 0;
|
||||
final children = node['children'] as List?;
|
||||
|
||||
if (children == null || children.isEmpty) return 0;
|
||||
|
||||
final parentGuid = node['guid'] as String;
|
||||
|
||||
for (int i = 0; i < children.length; i++) {
|
||||
final child = children[i] as Map<String, dynamic>;
|
||||
final type = child['type'] as int? ?? BookmarkNodeType.item.index;
|
||||
|
||||
if (type == BookmarkNodeType.item.index) {
|
||||
final url = child['url'] as String?;
|
||||
final title = child['title'] as String? ?? '';
|
||||
|
||||
if (url != null && url.isNotEmpty) {
|
||||
try {
|
||||
final uri = Uri.parse(url);
|
||||
if (uri.hasScheme) {
|
||||
await _service.addItem(parentGuid, uri, title, i);
|
||||
count++;
|
||||
}
|
||||
} catch (e) {
|
||||
logger.e('Failed to import bookmark "$title": $e');
|
||||
}
|
||||
}
|
||||
} else if (type == BookmarkNodeType.folder.index) {
|
||||
final title = child['title'] as String? ?? '';
|
||||
try {
|
||||
final newGuid = await _service.addFolder(parentGuid, title, i);
|
||||
child['guid'] = newGuid;
|
||||
count += await _insertTree(child);
|
||||
} catch (e) {
|
||||
logger.e('Failed to import folder "$title": $e');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
}
|
||||
|
||||
class _BookmarkExporter {
|
||||
final BookmarkNode _root;
|
||||
final StringBuffer _buffer = StringBuffer();
|
||||
|
||||
_BookmarkExporter(this._root);
|
||||
|
||||
String exportToHTML() {
|
||||
_writeHeader();
|
||||
_writeContainer(_root);
|
||||
return _buffer.toString();
|
||||
}
|
||||
|
||||
void _write(String text) {
|
||||
_buffer.write(text);
|
||||
}
|
||||
|
||||
void _writeLine(String text) {
|
||||
_buffer.writeln(text);
|
||||
}
|
||||
|
||||
void _writeHeader() {
|
||||
_writeLine('<!DOCTYPE NETSCAPE-Bookmark-file-1>');
|
||||
_writeLine('<!-- This is an automatically generated file.');
|
||||
_writeLine(' It will be read and overwritten.');
|
||||
_writeLine(' DO NOT EDIT! -->');
|
||||
_writeLine(
|
||||
'<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">',
|
||||
);
|
||||
_writeLine('<meta http-equiv="Content-Security-Policy"');
|
||||
_writeLine(
|
||||
' content="default-src \'self\'; script-src \'none\'; img-src data: *; object-src \'none\'"></meta>',
|
||||
);
|
||||
_writeLine('<TITLE>Bookmarks</TITLE>');
|
||||
}
|
||||
|
||||
void _writeContainer(BookmarkNode item, [String indent = '']) {
|
||||
if (item.guid == _root.guid) {
|
||||
_writeLine('<H1>${_escapeHtml(item.title ?? 'Bookmarks')}</H1>');
|
||||
_writeLine('');
|
||||
} else {
|
||||
_write('$indent<DT><H3');
|
||||
_writeDateAttributes(item);
|
||||
|
||||
if (item.guid == BookmarkRoot.toolbar.id) {
|
||||
_write(' PERSONAL_TOOLBAR_FOLDER="true"');
|
||||
} else if (item.guid == BookmarkRoot.unfiled.id) {
|
||||
_write(' UNFILED_BOOKMARKS_FOLDER="true"');
|
||||
}
|
||||
_writeLine('>${_escapeHtml(item.title ?? '')}</H3>');
|
||||
}
|
||||
|
||||
_writeLine('$indent<DL><p>');
|
||||
if (item.children != null) {
|
||||
_writeContainerContents(item, indent);
|
||||
}
|
||||
if (item.guid == _root.guid) {
|
||||
_writeLine('$indent</DL>');
|
||||
} else {
|
||||
_writeLine('$indent</DL><p>');
|
||||
}
|
||||
}
|
||||
|
||||
void _writeContainerContents(BookmarkNode item, String indent) {
|
||||
final localIndent = indent + _exportIndent;
|
||||
|
||||
for (final child in item.children!) {
|
||||
if (child.type == BookmarkNodeType.folder) {
|
||||
_writeContainer(child, localIndent);
|
||||
} else if (child.type == BookmarkNodeType.separator) {
|
||||
_writeSeparator(child, localIndent);
|
||||
} else {
|
||||
_writeItem(child, localIndent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void _writeSeparator(BookmarkNode item, String indent) {
|
||||
_write('$indent<HR');
|
||||
if (item.title != null && item.title!.isNotEmpty) {
|
||||
_write(' NAME="${_escapeHtml(item.title!)}"');
|
||||
}
|
||||
_writeLine('>');
|
||||
}
|
||||
|
||||
void _writeItem(BookmarkNode item, String indent) {
|
||||
if (item.url == null || item.url!.isEmpty) return;
|
||||
|
||||
try {
|
||||
Uri.parse(item.url!);
|
||||
} catch (e) {
|
||||
return;
|
||||
}
|
||||
|
||||
_write('$indent<DT><A HREF="${_escapeUrl(item.url!)}"');
|
||||
_writeDateAttributes(item);
|
||||
|
||||
_writeLine('>${_escapeHtml(item.title ?? '')}</A>');
|
||||
}
|
||||
|
||||
void _writeDateAttributes(BookmarkNode item) {
|
||||
// Convert from microseconds to seconds (UNIX timestamp)
|
||||
if (item.dateAdded > 0) {
|
||||
_write(' ADD_DATE="${item.dateAdded ~/ 1000000}"');
|
||||
}
|
||||
if (item.lastModified > 0) {
|
||||
_write(' LAST_MODIFIED="${item.lastModified ~/ 1000000}"');
|
||||
}
|
||||
}
|
||||
|
||||
String _escapeHtml(String text) {
|
||||
return text
|
||||
.replaceAll('&', '&')
|
||||
.replaceAll('<', '<')
|
||||
.replaceAll('>', '>')
|
||||
.replaceAll('"', '"')
|
||||
.replaceAll("'", ''');
|
||||
}
|
||||
|
||||
String _escapeUrl(String text) {
|
||||
return text.replaceAll('"', '%22');
|
||||
}
|
||||
}
|
||||
+376
@@ -0,0 +1,376 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
// ignore_for_file: unnecessary_raw_strings
|
||||
|
||||
import 'dart:convert';
|
||||
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
|
||||
import 'package:weblibre/core/logger.dart';
|
||||
import 'package:weblibre/utils/uri_input_parser.dart';
|
||||
|
||||
class BookmarkJSONUtils {
|
||||
final GeckoBookmarksService _service;
|
||||
|
||||
BookmarkJSONUtils(this._service);
|
||||
|
||||
/// Import bookmarks from JSON string
|
||||
Future<int> importFromJSON(String jsonString, {bool replace = false}) async {
|
||||
try {
|
||||
final data = jsonDecode(jsonString);
|
||||
|
||||
if (data is! Map<String, dynamic>) {
|
||||
throw Exception('Invalid JSON format');
|
||||
}
|
||||
|
||||
final children = data['children'] as List?;
|
||||
if (children == null || children.isEmpty) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return await _import(data, replace: replace);
|
||||
} catch (ex) {
|
||||
logger.e('Failed to import bookmarks: $ex');
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
/// Export bookmarks to JSON
|
||||
Future<Map<String, dynamic>?> exportToJson({
|
||||
required BookmarkRoot root,
|
||||
}) async {
|
||||
final tree = await _service.getTree(root.id, recursive: true);
|
||||
if (tree == null) {
|
||||
throw Exception('Failed to get bookmarks tree');
|
||||
}
|
||||
|
||||
return _nodeToJson(tree, isRoot: true);
|
||||
}
|
||||
|
||||
/// Import implementation
|
||||
Future<int> _import(
|
||||
Map<String, dynamic> rootNode, {
|
||||
required bool replace,
|
||||
}) async {
|
||||
final nodes =
|
||||
(rootNode['children'] as List?)
|
||||
?.whereType<Map<String, dynamic>>()
|
||||
.where(
|
||||
(node) =>
|
||||
node['root'] != 'tagsFolder' &&
|
||||
node['guid'] != 'tags________',
|
||||
)
|
||||
.toList() ??
|
||||
[];
|
||||
|
||||
if (nodes.isEmpty) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// If replacing, erase existing bookmarks first
|
||||
if (replace) {
|
||||
// Delete bookmarks from each root folder (except root itself to avoid errors)
|
||||
for (final root in BookmarkRoot.values) {
|
||||
if (root != BookmarkRoot.root) {
|
||||
await _service.eraseEverything(root);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
final folderIdToGuidMap = <String, String>{};
|
||||
|
||||
// Translate tree types and build folder map
|
||||
for (final node in nodes) {
|
||||
if (node['children'] == null || (node['children'] as List).isEmpty) {
|
||||
continue;
|
||||
}
|
||||
|
||||
final folders = _translateTreeTypes(node);
|
||||
folderIdToGuidMap.addAll(folders);
|
||||
}
|
||||
|
||||
int bookmarkCount = 0;
|
||||
|
||||
// Insert nodes
|
||||
for (final node in nodes) {
|
||||
if (node['children'] == null || (node['children'] as List).isEmpty) {
|
||||
continue;
|
||||
}
|
||||
|
||||
final guid = node['guid'] as String?;
|
||||
if (guid == null || !bookmarkRootIds.contains(guid)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
_fixupSearchQueries(node, folderIdToGuidMap);
|
||||
|
||||
// Insert the tree recursively
|
||||
bookmarkCount += await _insertTree(node, folderIdToGuidMap);
|
||||
}
|
||||
|
||||
return bookmarkCount;
|
||||
}
|
||||
|
||||
/// Recursively insert bookmark tree
|
||||
Future<int> _insertTree(
|
||||
Map<String, dynamic> node,
|
||||
Map<String, String> folderIdToGuidMap,
|
||||
) async {
|
||||
int count = 0;
|
||||
final children = node['children'] as List?;
|
||||
|
||||
if (children == null || children.isEmpty) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
final parentGuid = node['guid'] as String;
|
||||
|
||||
for (int i = 0; i < children.length; i++) {
|
||||
final child = children[i] as Map<String, dynamic>;
|
||||
final type = _getNodeType(child);
|
||||
|
||||
if (type == BookmarkNodeType.item) {
|
||||
final url = _getNodeUrl(child);
|
||||
final title = child['title'] as String? ?? '';
|
||||
|
||||
if (url != null && url.isNotEmpty) {
|
||||
try {
|
||||
// Validate URL before inserting
|
||||
final uri = Uri.tryParse(url);
|
||||
if (uri != null && uri.hasScheme) {
|
||||
await _service.addItem(parentGuid, uri, title, i);
|
||||
count++;
|
||||
} else {
|
||||
final parsed = Uri.tryParse(url);
|
||||
final redacted = parsed != null
|
||||
? redactUriCredentials(parsed)
|
||||
: url;
|
||||
logger.w('Skipping invalid URL: $redacted');
|
||||
}
|
||||
} catch (e) {
|
||||
logger.e('Failed to import bookmark "$title": $e');
|
||||
}
|
||||
}
|
||||
} else if (type == BookmarkNodeType.folder) {
|
||||
final title = child['title'] as String? ?? '';
|
||||
try {
|
||||
final newGuid = await _service.addFolder(parentGuid, title, i);
|
||||
child['guid'] = newGuid;
|
||||
|
||||
// Recursively insert children
|
||||
count += await _insertTree(child, folderIdToGuidMap);
|
||||
} catch (e) {
|
||||
logger.e('Failed to import folder "$title": $e');
|
||||
}
|
||||
}
|
||||
// Note: Separators are not supported by the Android API
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
/// Translate tree types from JSON format to internal format
|
||||
Map<String, String> _translateTreeTypes(Map<String, dynamic> node) {
|
||||
final folderIdToGuidMap = <String, String>{};
|
||||
|
||||
_normalizeNodeUrl(node);
|
||||
|
||||
final type = node['type'];
|
||||
if (type == 'text/x-moz-place-container') {
|
||||
node['type'] = BookmarkNodeType.folder.index;
|
||||
|
||||
final id = node['id']?.toString();
|
||||
final guid = node['guid'] as String?;
|
||||
if (id != null && guid != null) {
|
||||
folderIdToGuidMap[id] = guid;
|
||||
}
|
||||
} else if (type == 'text/x-moz-place') {
|
||||
node['type'] = BookmarkNodeType.item.index;
|
||||
} else if (type == 'text/x-moz-place-separator') {
|
||||
node['type'] = BookmarkNodeType.separator.index;
|
||||
node.remove('title');
|
||||
}
|
||||
|
||||
final children = node['children'] as List?;
|
||||
if (children != null) {
|
||||
for (final child in children) {
|
||||
if (child is Map<String, dynamic>) {
|
||||
folderIdToGuidMap.addAll(_translateTreeTypes(child));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return folderIdToGuidMap;
|
||||
}
|
||||
|
||||
/// Fix up search queries with folder mappings
|
||||
void _fixupSearchQueries(
|
||||
Map<String, dynamic> node,
|
||||
Map<String, String> folderIdToGuidMap,
|
||||
) {
|
||||
final url = _getNodeUrl(node);
|
||||
if (url != null && url.startsWith('place:')) {
|
||||
node['url'] = _fixupQuery(url, folderIdToGuidMap);
|
||||
}
|
||||
|
||||
final children = node['children'] as List?;
|
||||
if (children != null) {
|
||||
for (final child in children) {
|
||||
if (child is Map<String, dynamic>) {
|
||||
_fixupSearchQueries(child, folderIdToGuidMap);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Replace folder IDs with GUIDs in place: URIs
|
||||
String _fixupQuery(String queryURL, Map<String, String> folderIdToGuidMap) {
|
||||
final regex = RegExp(r'folder=([A-Za-z0-9_]+)');
|
||||
bool invalid = false;
|
||||
|
||||
final result = queryURL.replaceAllMapped(regex, (match) {
|
||||
final folderId = match.group(1)!;
|
||||
final guid = folderIdToGuidMap[folderId];
|
||||
|
||||
if (guid == null) {
|
||||
invalid = true;
|
||||
return 'invalidOldParentId=$folderId';
|
||||
}
|
||||
|
||||
return 'parent=$guid';
|
||||
});
|
||||
|
||||
if (invalid) {
|
||||
return '$result&excludeItems=1';
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Convert BookmarkNode to JSON (for export)
|
||||
Map<String, dynamic>? _nodeToJson(BookmarkNode node, {bool isRoot = false}) {
|
||||
// Skip invalid bookmarks
|
||||
if (node.type == BookmarkNodeType.item) {
|
||||
if (node.url == null || node.url!.isEmpty) {
|
||||
logger.w('Skipping bookmark with invalid URL: ${node.guid}');
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
Uri.parse(node.url!);
|
||||
} catch (e) {
|
||||
logger.w('Skipping bookmark with malformed URL: ${node.url}');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
final json = <String, dynamic>{
|
||||
'guid': node.guid,
|
||||
'title': node.type == BookmarkNodeType.separator
|
||||
? ''
|
||||
: (node.title ?? ''),
|
||||
'index': 0, // Will be set by parent
|
||||
'dateAdded': node.dateAdded,
|
||||
'lastModified': node.lastModified,
|
||||
'typeCode': node.type.index + 1,
|
||||
'type': _getTypeString(node.type),
|
||||
};
|
||||
|
||||
if (isRoot &&
|
||||
node.parentGuid != null &&
|
||||
node.guid != BookmarkRoot.root.id) {
|
||||
json['parentGuid'] = node.parentGuid;
|
||||
}
|
||||
|
||||
final rootName = _getRootName(node.guid);
|
||||
if (rootName != null) {
|
||||
json['root'] = rootName;
|
||||
}
|
||||
|
||||
if (node.type == BookmarkNodeType.item) {
|
||||
json['url'] = node.url;
|
||||
}
|
||||
|
||||
if (node.type == BookmarkNodeType.folder && node.children != null) {
|
||||
final validChildren = <Map<String, dynamic>>[];
|
||||
for (var i = 0; i < node.children!.length; i++) {
|
||||
final childJson = _nodeToJson(node.children![i]);
|
||||
if (childJson != null) {
|
||||
childJson['index'] = validChildren.length;
|
||||
validChildren.add(childJson);
|
||||
}
|
||||
}
|
||||
if (validChildren.isNotEmpty) {
|
||||
json['children'] = validChildren;
|
||||
}
|
||||
}
|
||||
|
||||
return json;
|
||||
}
|
||||
|
||||
/// Convert BookmarkNodeType to Firefox type string
|
||||
String _getTypeString(BookmarkNodeType type) {
|
||||
switch (type) {
|
||||
case BookmarkNodeType.item:
|
||||
return 'text/x-moz-place';
|
||||
case BookmarkNodeType.folder:
|
||||
return 'text/x-moz-place-container';
|
||||
case BookmarkNodeType.separator:
|
||||
return 'text/x-moz-place-separator';
|
||||
}
|
||||
}
|
||||
|
||||
/// Get root folder name for JSON
|
||||
String? _getRootName(String guid) {
|
||||
if (guid == BookmarkRoot.root.id) return 'placesRoot';
|
||||
if (guid == BookmarkRoot.menu.id) return 'bookmarksMenuFolder';
|
||||
if (guid == BookmarkRoot.toolbar.id) return 'toolbarFolder';
|
||||
if (guid == BookmarkRoot.unfiled.id) return 'unfiledBookmarksFolder';
|
||||
if (guid == BookmarkRoot.mobile.id) return 'mobileFolder';
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Get URL from node (accepts both 'url' and 'uri')
|
||||
String? _getNodeUrl(Map<String, dynamic> node) {
|
||||
return node['url'] as String? ?? node['uri'] as String?;
|
||||
}
|
||||
|
||||
/// Normalize 'uri' to 'url' during import
|
||||
void _normalizeNodeUrl(Map<String, dynamic> node) {
|
||||
if (node.containsKey('uri')) {
|
||||
node['url'] = node['uri'];
|
||||
node.remove('uri');
|
||||
}
|
||||
}
|
||||
|
||||
/// Get node type from JSON
|
||||
BookmarkNodeType _getNodeType(Map<String, dynamic> node) {
|
||||
final type = node['type'];
|
||||
if (type is int) {
|
||||
return BookmarkNodeType.values[type];
|
||||
}
|
||||
|
||||
if (type == 'text/x-moz-place-container') {
|
||||
return BookmarkNodeType.folder;
|
||||
} else if (type == 'text/x-moz-place') {
|
||||
return BookmarkNodeType.item;
|
||||
} else {
|
||||
return BookmarkNodeType.separator;
|
||||
}
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
const fontSizeStep = 0.1;
|
||||
const fontSizeMin = 0.5;
|
||||
const fontSizeMax = 3.0;
|
||||
const fontSizeDefault = 1.0;
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/domain/entities/site_permissions.dart';
|
||||
|
||||
/// Permission types with their display configuration
|
||||
enum PermissionType {
|
||||
camera(Icons.videocam, 'Camera'),
|
||||
microphone(Icons.mic, 'Microphone'),
|
||||
location(Icons.location_on, 'Location'),
|
||||
notification(Icons.notifications, 'Notifications'),
|
||||
persistentStorage(Icons.storage, 'Persistent Storage'),
|
||||
crossOriginStorage(Icons.cookie, 'Cross-Origin Storage'),
|
||||
mediaKeySystem(Icons.key, 'Media Key System (DRM)');
|
||||
|
||||
const PermissionType(this.icon, this.label);
|
||||
final IconData icon;
|
||||
final String label;
|
||||
}
|
||||
|
||||
extension SitePermissionsGetter on SitePermissions? {
|
||||
SitePermissionStatus? getStatus(PermissionType type) => switch (type) {
|
||||
PermissionType.camera => this?.camera,
|
||||
PermissionType.microphone => this?.microphone,
|
||||
PermissionType.location => this?.location,
|
||||
PermissionType.notification => this?.notification,
|
||||
PermissionType.persistentStorage => this?.persistentStorage,
|
||||
PermissionType.crossOriginStorage => this?.crossOriginStorageAccess,
|
||||
PermissionType.mediaKeySystem => this?.mediaKeySystemAccess,
|
||||
};
|
||||
}
|
||||
|
||||
extension SitePermissionsUpdater on SitePermissionsWrapper {
|
||||
SitePermissions withStatus(
|
||||
PermissionType type,
|
||||
SitePermissionStatus status,
|
||||
) => switch (type) {
|
||||
PermissionType.camera => copyWith.camera(status),
|
||||
PermissionType.microphone => copyWith.microphone(status),
|
||||
PermissionType.location => copyWith.location(status),
|
||||
PermissionType.notification => copyWith.notification(status),
|
||||
PermissionType.persistentStorage => copyWith.persistentStorage(status),
|
||||
PermissionType.crossOriginStorage => copyWith.crossOriginStorageAccess(
|
||||
status,
|
||||
),
|
||||
PermissionType.mediaKeySystem => copyWith.mediaKeySystemAccess(status),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:fast_equatable/fast_equatable.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/entities/states/tab.dart';
|
||||
|
||||
sealed class Sheet with FastEquatable {}
|
||||
|
||||
final class ViewTabsSheet extends Sheet {
|
||||
@override
|
||||
List<Object?> get hashParameters => [null];
|
||||
}
|
||||
|
||||
final class SiteSettingsSheet extends Sheet {
|
||||
final TabState tabState;
|
||||
|
||||
SiteSettingsSheet({required this.tabState});
|
||||
|
||||
@override
|
||||
List<Object?> get hashParameters => [tabState];
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:copy_with_extension/copy_with_extension.dart';
|
||||
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
|
||||
|
||||
part 'site_permissions.g.dart';
|
||||
|
||||
@CopyWith()
|
||||
class SitePermissionsWrapper extends SitePermissions {
|
||||
SitePermissionsWrapper({
|
||||
required super.origin,
|
||||
super.camera,
|
||||
super.microphone,
|
||||
super.location,
|
||||
super.notification,
|
||||
super.persistentStorage,
|
||||
super.crossOriginStorageAccess,
|
||||
super.mediaKeySystemAccess,
|
||||
super.localDeviceAccess,
|
||||
super.localNetworkAccess,
|
||||
super.autoplayAudible,
|
||||
super.autoplayInaudible,
|
||||
required super.savedAt,
|
||||
});
|
||||
|
||||
factory SitePermissionsWrapper.fromPermission(SitePermissions permissions) {
|
||||
return SitePermissionsWrapper(
|
||||
origin: permissions.origin,
|
||||
camera: permissions.camera,
|
||||
microphone: permissions.microphone,
|
||||
location: permissions.location,
|
||||
notification: permissions.notification,
|
||||
persistentStorage: permissions.persistentStorage,
|
||||
crossOriginStorageAccess: permissions.crossOriginStorageAccess,
|
||||
mediaKeySystemAccess: permissions.mediaKeySystemAccess,
|
||||
localDeviceAccess: permissions.localDeviceAccess,
|
||||
localNetworkAccess: permissions.localNetworkAccess,
|
||||
autoplayAudible: permissions.autoplayAudible,
|
||||
autoplayInaudible: permissions.autoplayInaudible,
|
||||
savedAt: permissions.savedAt,
|
||||
);
|
||||
}
|
||||
}
|
||||
+220
@@ -0,0 +1,220 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'site_permissions.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// CopyWithGenerator
|
||||
// **************************************************************************
|
||||
|
||||
abstract class _$SitePermissionsWrapperCWProxy {
|
||||
SitePermissionsWrapper origin(String origin);
|
||||
|
||||
SitePermissionsWrapper camera(SitePermissionStatus? camera);
|
||||
|
||||
SitePermissionsWrapper microphone(SitePermissionStatus? microphone);
|
||||
|
||||
SitePermissionsWrapper location(SitePermissionStatus? location);
|
||||
|
||||
SitePermissionsWrapper notification(SitePermissionStatus? notification);
|
||||
|
||||
SitePermissionsWrapper persistentStorage(
|
||||
SitePermissionStatus? persistentStorage,
|
||||
);
|
||||
|
||||
SitePermissionsWrapper crossOriginStorageAccess(
|
||||
SitePermissionStatus? crossOriginStorageAccess,
|
||||
);
|
||||
|
||||
SitePermissionsWrapper mediaKeySystemAccess(
|
||||
SitePermissionStatus? mediaKeySystemAccess,
|
||||
);
|
||||
|
||||
SitePermissionsWrapper localDeviceAccess(
|
||||
SitePermissionStatus? localDeviceAccess,
|
||||
);
|
||||
|
||||
SitePermissionsWrapper localNetworkAccess(
|
||||
SitePermissionStatus? localNetworkAccess,
|
||||
);
|
||||
|
||||
SitePermissionsWrapper autoplayAudible(AutoplayStatus? autoplayAudible);
|
||||
|
||||
SitePermissionsWrapper autoplayInaudible(AutoplayStatus? autoplayInaudible);
|
||||
|
||||
SitePermissionsWrapper savedAt(int savedAt);
|
||||
|
||||
/// Creates a new instance with the provided field values.
|
||||
/// Passing `null` to a nullable field nullifies it, while `null` for a non-nullable field is ignored. To update a single field use `SitePermissionsWrapper(...).copyWith.fieldName(value)`.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// SitePermissionsWrapper(...).copyWith(id: 12, name: "My name")
|
||||
/// ```
|
||||
SitePermissionsWrapper call({
|
||||
String origin,
|
||||
SitePermissionStatus? camera,
|
||||
SitePermissionStatus? microphone,
|
||||
SitePermissionStatus? location,
|
||||
SitePermissionStatus? notification,
|
||||
SitePermissionStatus? persistentStorage,
|
||||
SitePermissionStatus? crossOriginStorageAccess,
|
||||
SitePermissionStatus? mediaKeySystemAccess,
|
||||
SitePermissionStatus? localDeviceAccess,
|
||||
SitePermissionStatus? localNetworkAccess,
|
||||
AutoplayStatus? autoplayAudible,
|
||||
AutoplayStatus? autoplayInaudible,
|
||||
int savedAt,
|
||||
});
|
||||
}
|
||||
|
||||
/// Callable proxy for `copyWith` functionality.
|
||||
/// Use as `instanceOfSitePermissionsWrapper.copyWith(...)` or call `instanceOfSitePermissionsWrapper.copyWith.fieldName(value)` for a single field.
|
||||
class _$SitePermissionsWrapperCWProxyImpl
|
||||
implements _$SitePermissionsWrapperCWProxy {
|
||||
const _$SitePermissionsWrapperCWProxyImpl(this._value);
|
||||
|
||||
final SitePermissionsWrapper _value;
|
||||
|
||||
@override
|
||||
SitePermissionsWrapper origin(String origin) => call(origin: origin);
|
||||
|
||||
@override
|
||||
SitePermissionsWrapper camera(SitePermissionStatus? camera) =>
|
||||
call(camera: camera);
|
||||
|
||||
@override
|
||||
SitePermissionsWrapper microphone(SitePermissionStatus? microphone) =>
|
||||
call(microphone: microphone);
|
||||
|
||||
@override
|
||||
SitePermissionsWrapper location(SitePermissionStatus? location) =>
|
||||
call(location: location);
|
||||
|
||||
@override
|
||||
SitePermissionsWrapper notification(SitePermissionStatus? notification) =>
|
||||
call(notification: notification);
|
||||
|
||||
@override
|
||||
SitePermissionsWrapper persistentStorage(
|
||||
SitePermissionStatus? persistentStorage,
|
||||
) => call(persistentStorage: persistentStorage);
|
||||
|
||||
@override
|
||||
SitePermissionsWrapper crossOriginStorageAccess(
|
||||
SitePermissionStatus? crossOriginStorageAccess,
|
||||
) => call(crossOriginStorageAccess: crossOriginStorageAccess);
|
||||
|
||||
@override
|
||||
SitePermissionsWrapper mediaKeySystemAccess(
|
||||
SitePermissionStatus? mediaKeySystemAccess,
|
||||
) => call(mediaKeySystemAccess: mediaKeySystemAccess);
|
||||
|
||||
@override
|
||||
SitePermissionsWrapper localDeviceAccess(
|
||||
SitePermissionStatus? localDeviceAccess,
|
||||
) => call(localDeviceAccess: localDeviceAccess);
|
||||
|
||||
@override
|
||||
SitePermissionsWrapper localNetworkAccess(
|
||||
SitePermissionStatus? localNetworkAccess,
|
||||
) => call(localNetworkAccess: localNetworkAccess);
|
||||
|
||||
@override
|
||||
SitePermissionsWrapper autoplayAudible(AutoplayStatus? autoplayAudible) =>
|
||||
call(autoplayAudible: autoplayAudible);
|
||||
|
||||
@override
|
||||
SitePermissionsWrapper autoplayInaudible(AutoplayStatus? autoplayInaudible) =>
|
||||
call(autoplayInaudible: autoplayInaudible);
|
||||
|
||||
@override
|
||||
SitePermissionsWrapper savedAt(int savedAt) => call(savedAt: savedAt);
|
||||
|
||||
@override
|
||||
/// Creates a new instance with the provided field values.
|
||||
/// Passing `null` to a nullable field nullifies it, while `null` for a non-nullable field is ignored. To update a single field use `SitePermissionsWrapper(...).copyWith.fieldName(value)`.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// SitePermissionsWrapper(...).copyWith(id: 12, name: "My name")
|
||||
/// ```
|
||||
SitePermissionsWrapper call({
|
||||
Object? origin = const $CopyWithPlaceholder(),
|
||||
Object? camera = const $CopyWithPlaceholder(),
|
||||
Object? microphone = const $CopyWithPlaceholder(),
|
||||
Object? location = const $CopyWithPlaceholder(),
|
||||
Object? notification = const $CopyWithPlaceholder(),
|
||||
Object? persistentStorage = const $CopyWithPlaceholder(),
|
||||
Object? crossOriginStorageAccess = const $CopyWithPlaceholder(),
|
||||
Object? mediaKeySystemAccess = const $CopyWithPlaceholder(),
|
||||
Object? localDeviceAccess = const $CopyWithPlaceholder(),
|
||||
Object? localNetworkAccess = const $CopyWithPlaceholder(),
|
||||
Object? autoplayAudible = const $CopyWithPlaceholder(),
|
||||
Object? autoplayInaudible = const $CopyWithPlaceholder(),
|
||||
Object? savedAt = const $CopyWithPlaceholder(),
|
||||
}) {
|
||||
return SitePermissionsWrapper(
|
||||
origin: origin == const $CopyWithPlaceholder() || origin == null
|
||||
? _value.origin
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: origin as String,
|
||||
camera: camera == const $CopyWithPlaceholder()
|
||||
? _value.camera
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: camera as SitePermissionStatus?,
|
||||
microphone: microphone == const $CopyWithPlaceholder()
|
||||
? _value.microphone
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: microphone as SitePermissionStatus?,
|
||||
location: location == const $CopyWithPlaceholder()
|
||||
? _value.location
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: location as SitePermissionStatus?,
|
||||
notification: notification == const $CopyWithPlaceholder()
|
||||
? _value.notification
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: notification as SitePermissionStatus?,
|
||||
persistentStorage: persistentStorage == const $CopyWithPlaceholder()
|
||||
? _value.persistentStorage
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: persistentStorage as SitePermissionStatus?,
|
||||
crossOriginStorageAccess:
|
||||
crossOriginStorageAccess == const $CopyWithPlaceholder()
|
||||
? _value.crossOriginStorageAccess
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: crossOriginStorageAccess as SitePermissionStatus?,
|
||||
mediaKeySystemAccess: mediaKeySystemAccess == const $CopyWithPlaceholder()
|
||||
? _value.mediaKeySystemAccess
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: mediaKeySystemAccess as SitePermissionStatus?,
|
||||
localDeviceAccess: localDeviceAccess == const $CopyWithPlaceholder()
|
||||
? _value.localDeviceAccess
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: localDeviceAccess as SitePermissionStatus?,
|
||||
localNetworkAccess: localNetworkAccess == const $CopyWithPlaceholder()
|
||||
? _value.localNetworkAccess
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: localNetworkAccess as SitePermissionStatus?,
|
||||
autoplayAudible: autoplayAudible == const $CopyWithPlaceholder()
|
||||
? _value.autoplayAudible
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: autoplayAudible as AutoplayStatus?,
|
||||
autoplayInaudible: autoplayInaudible == const $CopyWithPlaceholder()
|
||||
? _value.autoplayInaudible
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: autoplayInaudible as AutoplayStatus?,
|
||||
savedAt: savedAt == const $CopyWithPlaceholder() || savedAt == null
|
||||
? _value.savedAt
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: savedAt as int,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
extension $SitePermissionsWrapperCopyWith on SitePermissionsWrapper {
|
||||
/// Returns a callable class used to build a new instance with modified fields.
|
||||
/// Example: `instanceOfSitePermissionsWrapper.copyWith(...)` or `instanceOfSitePermissionsWrapper.copyWith.fieldName(...)`.
|
||||
// ignore: library_private_types_in_public_api
|
||||
_$SitePermissionsWrapperCWProxy get copyWith =>
|
||||
_$SitePermissionsWrapperCWProxyImpl(this);
|
||||
}
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:copy_with_extension/copy_with_extension.dart';
|
||||
import 'package:fast_equatable/fast_equatable.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:json_annotation/json_annotation.dart';
|
||||
import 'package:weblibre/core/sort_field.dart';
|
||||
import 'package:weblibre/data/database/converters/date_time_range.dart';
|
||||
import 'package:weblibre/features/geckoview/features/tabs/data/entities/tab_mode.dart';
|
||||
|
||||
part 'tab_view_filter_options.g.dart';
|
||||
|
||||
enum TabTypeFilter {
|
||||
all('All Tabs'),
|
||||
regularOnly('Regular'),
|
||||
privateOnly('Private'),
|
||||
isolatedOnly('Isolated');
|
||||
|
||||
final String label;
|
||||
|
||||
const TabTypeFilter(this.label);
|
||||
|
||||
bool matches(TabMode? tabMode) => switch (this) {
|
||||
all => true,
|
||||
regularOnly => tabMode is RegularTabMode,
|
||||
privateOnly => tabMode is PrivateTabMode,
|
||||
isolatedOnly => tabMode is IsolatedTabMode,
|
||||
};
|
||||
}
|
||||
|
||||
enum TabSortType {
|
||||
manual('Default', null),
|
||||
titleAsc('Title A-Z', SortField.titleAsc),
|
||||
titleDesc('Title Z-A', SortField.titleDesc),
|
||||
urlAsc('URL A-Z', SortField.urlAsc),
|
||||
urlDesc('URL Z-A', SortField.urlDesc),
|
||||
newestFirst('Newest First', SortField.dateDesc),
|
||||
oldestFirst('Oldest First', SortField.dateAsc);
|
||||
|
||||
final String label;
|
||||
final SortField? sortField;
|
||||
|
||||
const TabSortType(this.label, this.sortField);
|
||||
}
|
||||
|
||||
enum TabQuickInterval {
|
||||
last1h('Last Hour', Duration(hours: 1)),
|
||||
last3h('Last 3 Hours', Duration(hours: 3)),
|
||||
last8h('Last 8 Hours', Duration(hours: 8)),
|
||||
last1d('Last Day', Duration(days: 1)),
|
||||
last3d('Last 3 Days', Duration(days: 3)),
|
||||
last1w('Last Week', Duration(days: 7)),
|
||||
last1m('Last Month', Duration(days: 30));
|
||||
|
||||
final String label;
|
||||
final Duration duration;
|
||||
|
||||
const TabQuickInterval(this.label, this.duration);
|
||||
|
||||
DateTimeRange<DateTime> toDateRange() {
|
||||
final now = DateTime.now();
|
||||
return DateTimeRange(start: now.subtract(duration), end: now);
|
||||
}
|
||||
}
|
||||
|
||||
@JsonSerializable()
|
||||
@CopyWith()
|
||||
class TabViewFilterOptions with FastEquatable {
|
||||
final TabTypeFilter tabTypeFilter;
|
||||
final TabSortType sortType;
|
||||
final bool sortPinnedFirst;
|
||||
@DateTimeRangeConverter()
|
||||
final DateTimeRange<DateTime>? dateRange;
|
||||
final TabQuickInterval? quickInterval;
|
||||
|
||||
TabViewFilterOptions({
|
||||
required this.tabTypeFilter,
|
||||
required this.sortType,
|
||||
required this.sortPinnedFirst,
|
||||
required this.dateRange,
|
||||
required this.quickInterval,
|
||||
});
|
||||
|
||||
TabViewFilterOptions.withDefaults()
|
||||
: this(
|
||||
tabTypeFilter: TabTypeFilter.all,
|
||||
sortType: TabSortType.manual,
|
||||
sortPinnedFirst: true,
|
||||
dateRange: null,
|
||||
quickInterval: null,
|
||||
);
|
||||
|
||||
bool get hasActiveFilter =>
|
||||
tabTypeFilter != TabTypeFilter.all ||
|
||||
sortType != TabSortType.manual ||
|
||||
dateRange != null ||
|
||||
quickInterval != null;
|
||||
|
||||
DateTimeRange<DateTime>? get effectiveDateRange =>
|
||||
quickInterval?.toDateRange() ?? dateRange;
|
||||
|
||||
bool matchesTab(TabMode? tabMode, DateTime? timestamp) {
|
||||
if (!tabTypeFilter.matches(tabMode)) return false;
|
||||
final range = effectiveDateRange;
|
||||
if (range != null &&
|
||||
timestamp != null &&
|
||||
(timestamp.isBefore(range.start) || timestamp.isAfter(range.end))) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get hashParameters => [
|
||||
tabTypeFilter,
|
||||
sortType,
|
||||
sortPinnedFirst,
|
||||
dateRange,
|
||||
quickInterval,
|
||||
];
|
||||
|
||||
factory TabViewFilterOptions.fromJson(Map<String, dynamic> json) =>
|
||||
_$TabViewFilterOptionsFromJson(json);
|
||||
|
||||
Map<String, dynamic> toJson() => _$TabViewFilterOptionsToJson(this);
|
||||
}
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'tab_view_filter_options.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// CopyWithGenerator
|
||||
// **************************************************************************
|
||||
|
||||
abstract class _$TabViewFilterOptionsCWProxy {
|
||||
TabViewFilterOptions tabTypeFilter(TabTypeFilter tabTypeFilter);
|
||||
|
||||
TabViewFilterOptions sortType(TabSortType sortType);
|
||||
|
||||
TabViewFilterOptions sortPinnedFirst(bool sortPinnedFirst);
|
||||
|
||||
TabViewFilterOptions dateRange(DateTimeRange<DateTime>? dateRange);
|
||||
|
||||
TabViewFilterOptions quickInterval(TabQuickInterval? quickInterval);
|
||||
|
||||
/// Creates a new instance with the provided field values.
|
||||
/// Passing `null` to a nullable field nullifies it, while `null` for a non-nullable field is ignored. To update a single field use `TabViewFilterOptions(...).copyWith.fieldName(value)`.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// TabViewFilterOptions(...).copyWith(id: 12, name: "My name")
|
||||
/// ```
|
||||
TabViewFilterOptions call({
|
||||
TabTypeFilter tabTypeFilter,
|
||||
TabSortType sortType,
|
||||
bool sortPinnedFirst,
|
||||
DateTimeRange<DateTime>? dateRange,
|
||||
TabQuickInterval? quickInterval,
|
||||
});
|
||||
}
|
||||
|
||||
/// Callable proxy for `copyWith` functionality.
|
||||
/// Use as `instanceOfTabViewFilterOptions.copyWith(...)` or call `instanceOfTabViewFilterOptions.copyWith.fieldName(value)` for a single field.
|
||||
class _$TabViewFilterOptionsCWProxyImpl
|
||||
implements _$TabViewFilterOptionsCWProxy {
|
||||
const _$TabViewFilterOptionsCWProxyImpl(this._value);
|
||||
|
||||
final TabViewFilterOptions _value;
|
||||
|
||||
@override
|
||||
TabViewFilterOptions tabTypeFilter(TabTypeFilter tabTypeFilter) =>
|
||||
call(tabTypeFilter: tabTypeFilter);
|
||||
|
||||
@override
|
||||
TabViewFilterOptions sortType(TabSortType sortType) =>
|
||||
call(sortType: sortType);
|
||||
|
||||
@override
|
||||
TabViewFilterOptions sortPinnedFirst(bool sortPinnedFirst) =>
|
||||
call(sortPinnedFirst: sortPinnedFirst);
|
||||
|
||||
@override
|
||||
TabViewFilterOptions dateRange(DateTimeRange<DateTime>? dateRange) =>
|
||||
call(dateRange: dateRange);
|
||||
|
||||
@override
|
||||
TabViewFilterOptions quickInterval(TabQuickInterval? quickInterval) =>
|
||||
call(quickInterval: quickInterval);
|
||||
|
||||
@override
|
||||
/// Creates a new instance with the provided field values.
|
||||
/// Passing `null` to a nullable field nullifies it, while `null` for a non-nullable field is ignored. To update a single field use `TabViewFilterOptions(...).copyWith.fieldName(value)`.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// TabViewFilterOptions(...).copyWith(id: 12, name: "My name")
|
||||
/// ```
|
||||
TabViewFilterOptions call({
|
||||
Object? tabTypeFilter = const $CopyWithPlaceholder(),
|
||||
Object? sortType = const $CopyWithPlaceholder(),
|
||||
Object? sortPinnedFirst = const $CopyWithPlaceholder(),
|
||||
Object? dateRange = const $CopyWithPlaceholder(),
|
||||
Object? quickInterval = const $CopyWithPlaceholder(),
|
||||
}) {
|
||||
return TabViewFilterOptions(
|
||||
tabTypeFilter:
|
||||
tabTypeFilter == const $CopyWithPlaceholder() || tabTypeFilter == null
|
||||
? _value.tabTypeFilter
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: tabTypeFilter as TabTypeFilter,
|
||||
sortType: sortType == const $CopyWithPlaceholder() || sortType == null
|
||||
? _value.sortType
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: sortType as TabSortType,
|
||||
sortPinnedFirst:
|
||||
sortPinnedFirst == const $CopyWithPlaceholder() ||
|
||||
sortPinnedFirst == null
|
||||
? _value.sortPinnedFirst
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: sortPinnedFirst as bool,
|
||||
dateRange: dateRange == const $CopyWithPlaceholder()
|
||||
? _value.dateRange
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: dateRange as DateTimeRange<DateTime>?,
|
||||
quickInterval: quickInterval == const $CopyWithPlaceholder()
|
||||
? _value.quickInterval
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: quickInterval as TabQuickInterval?,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
extension $TabViewFilterOptionsCopyWith on TabViewFilterOptions {
|
||||
/// Returns a callable class used to build a new instance with modified fields.
|
||||
/// Example: `instanceOfTabViewFilterOptions.copyWith(...)` or `instanceOfTabViewFilterOptions.copyWith.fieldName(...)`.
|
||||
// ignore: library_private_types_in_public_api
|
||||
_$TabViewFilterOptionsCWProxy get copyWith =>
|
||||
_$TabViewFilterOptionsCWProxyImpl(this);
|
||||
}
|
||||
|
||||
// **************************************************************************
|
||||
// JsonSerializableGenerator
|
||||
// **************************************************************************
|
||||
|
||||
TabViewFilterOptions _$TabViewFilterOptionsFromJson(
|
||||
Map<String, dynamic> json,
|
||||
) => TabViewFilterOptions(
|
||||
tabTypeFilter: $enumDecode(_$TabTypeFilterEnumMap, json['tabTypeFilter']),
|
||||
sortType: $enumDecode(_$TabSortTypeEnumMap, json['sortType']),
|
||||
sortPinnedFirst: json['sortPinnedFirst'] as bool,
|
||||
dateRange: const DateTimeRangeConverter().fromJson(
|
||||
json['dateRange'] as Map<String, dynamic>?,
|
||||
),
|
||||
quickInterval: $enumDecodeNullable(
|
||||
_$TabQuickIntervalEnumMap,
|
||||
json['quickInterval'],
|
||||
),
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$TabViewFilterOptionsToJson(
|
||||
TabViewFilterOptions instance,
|
||||
) => <String, dynamic>{
|
||||
'tabTypeFilter': _$TabTypeFilterEnumMap[instance.tabTypeFilter]!,
|
||||
'sortType': _$TabSortTypeEnumMap[instance.sortType]!,
|
||||
'sortPinnedFirst': instance.sortPinnedFirst,
|
||||
'dateRange': const DateTimeRangeConverter().toJson(instance.dateRange),
|
||||
'quickInterval': _$TabQuickIntervalEnumMap[instance.quickInterval],
|
||||
};
|
||||
|
||||
const _$TabTypeFilterEnumMap = {
|
||||
TabTypeFilter.all: 'all',
|
||||
TabTypeFilter.regularOnly: 'regularOnly',
|
||||
TabTypeFilter.privateOnly: 'privateOnly',
|
||||
TabTypeFilter.isolatedOnly: 'isolatedOnly',
|
||||
};
|
||||
|
||||
const _$TabSortTypeEnumMap = {
|
||||
TabSortType.manual: 'manual',
|
||||
TabSortType.titleAsc: 'titleAsc',
|
||||
TabSortType.titleDesc: 'titleDesc',
|
||||
TabSortType.urlAsc: 'urlAsc',
|
||||
TabSortType.urlDesc: 'urlDesc',
|
||||
TabSortType.newestFirst: 'newestFirst',
|
||||
TabSortType.oldestFirst: 'oldestFirst',
|
||||
};
|
||||
|
||||
const _$TabQuickIntervalEnumMap = {
|
||||
TabQuickInterval.last1h: 'last1h',
|
||||
TabQuickInterval.last3h: 'last3h',
|
||||
TabQuickInterval.last8h: 'last8h',
|
||||
TabQuickInterval.last1d: 'last1d',
|
||||
TabQuickInterval.last3d: 'last3d',
|
||||
TabQuickInterval.last1w: 'last1w',
|
||||
TabQuickInterval.last1m: 'last1m',
|
||||
};
|
||||
@@ -0,0 +1,687 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:collection/collection.dart';
|
||||
import 'package:fast_equatable/fast_equatable.dart';
|
||||
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
|
||||
import 'package:nullability/nullability.dart';
|
||||
import 'package:riverpod/riverpod.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:weblibre/core/sort_field.dart';
|
||||
import 'package:weblibre/features/bangs/data/models/bang_data.dart';
|
||||
import 'package:weblibre/features/bangs/data/models/bang_key.dart';
|
||||
import 'package:weblibre/features/bangs/domain/repositories/data.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/entities/states/tab.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers/selected_tab.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers/tab_list.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers/tab_state.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/domain/entities/tab_view_filter_options.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/presentation/controllers/tab_view_controllers.dart';
|
||||
import 'package:weblibre/features/geckoview/features/history/domain/repositories/history.dart';
|
||||
import 'package:weblibre/features/geckoview/features/search/domain/entities/tab_preview.dart';
|
||||
import 'package:weblibre/features/geckoview/features/tabs/data/entities/container_filter.dart';
|
||||
import 'package:weblibre/features/geckoview/features/tabs/data/entities/tab_entity.dart';
|
||||
import 'package:weblibre/features/geckoview/features/tabs/data/models/container_data.dart';
|
||||
import 'package:weblibre/features/geckoview/features/tabs/domain/providers.dart';
|
||||
import 'package:weblibre/features/geckoview/features/tabs/domain/providers/selected_container.dart';
|
||||
import 'package:weblibre/features/geckoview/features/tabs/domain/repositories/gecko_inference.dart';
|
||||
import 'package:weblibre/features/geckoview/features/tabs/domain/repositories/tab_search.dart';
|
||||
import 'package:weblibre/features/user/data/models/general_settings.dart';
|
||||
import 'package:weblibre/features/user/domain/repositories/general_settings.dart';
|
||||
|
||||
part 'providers.g.dart';
|
||||
|
||||
typedef TabStateWithContainer = (TabState, ContainerData?);
|
||||
|
||||
@Riverpod()
|
||||
bool canManualTabReorder(Ref ref) {
|
||||
final filterOptions = ref.watch(tabViewFilterControllerProvider);
|
||||
|
||||
final hasActiveSearch = ref.watch(
|
||||
tabSearchRepositoryProvider(
|
||||
TabSearchPartition.preview,
|
||||
).select((value) => (value.value?.query ?? '').isNotEmpty),
|
||||
);
|
||||
|
||||
return !filterOptions.hasActiveFilter && !hasActiveSearch;
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
class SelectedBangTrigger extends _$SelectedBangTrigger {
|
||||
// ignore: document_ignores api decision
|
||||
// ignore: use_setters_to_change_properties
|
||||
void setTrigger(BangKey trigger) {
|
||||
state = trigger;
|
||||
}
|
||||
|
||||
void clearTrigger() {
|
||||
state = null;
|
||||
}
|
||||
|
||||
@override
|
||||
BangKey? build({String? domain}) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Riverpod()
|
||||
class SelectedBangData extends _$SelectedBangData {
|
||||
@override
|
||||
BangData? build({String? domain}) {
|
||||
final repository = ref.watch(bangDataRepositoryProvider.notifier);
|
||||
final selectedBangTrigger = ref.watch(
|
||||
selectedBangTriggerProvider(domain: domain),
|
||||
);
|
||||
|
||||
final subscription = repository.watchBang(selectedBangTrigger).listen((
|
||||
value,
|
||||
) {
|
||||
if (ref.mounted) {
|
||||
state = value;
|
||||
}
|
||||
});
|
||||
|
||||
ref.onDispose(() async {
|
||||
await subscription.cancel();
|
||||
});
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Riverpod()
|
||||
EquatableValue<List<DefaultTabEntity>> containerTabEntities(
|
||||
Ref ref,
|
||||
ContainerFilter containerFilter,
|
||||
) {
|
||||
final containerTabs = ref.watch(
|
||||
watchContainerTabIdsProvider(
|
||||
containerFilter,
|
||||
).select((value) => value.value),
|
||||
);
|
||||
final tabList = ref.watch(tabListProvider);
|
||||
final orderKeys = ref.watch(
|
||||
watchTabOrderKeysProvider.select((value) => value.value),
|
||||
);
|
||||
|
||||
final availableTabs =
|
||||
containerTabs?.where((tabId) => tabList.value.contains(tabId)).toList() ??
|
||||
[];
|
||||
|
||||
switch (containerFilter) {
|
||||
case ContainerFilterById():
|
||||
return EquatableValue(
|
||||
availableTabs
|
||||
.map(
|
||||
(t) => DefaultTabEntity(
|
||||
tabId: t,
|
||||
orderKey: orderKeys?[t] ?? '',
|
||||
containerId: containerFilter.containerId,
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
);
|
||||
case ContainerFilterDisabled():
|
||||
return ref.watch(
|
||||
watchTabsContainerIdProvider(EquatableValue(availableTabs)).select(
|
||||
(value) => EquatableValue(
|
||||
value.value?.entries
|
||||
.map(
|
||||
(e) => DefaultTabEntity(
|
||||
tabId: e.key,
|
||||
orderKey: orderKeys?[e.key] ?? '',
|
||||
containerId: e.value,
|
||||
),
|
||||
)
|
||||
.toList() ??
|
||||
[],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@Riverpod()
|
||||
EquatableValue<Map<String, TabState>> containerTabStates(
|
||||
Ref ref,
|
||||
ContainerFilter containerFilter,
|
||||
) {
|
||||
final availableTabs = ref.watch(
|
||||
containerTabEntitiesProvider(containerFilter),
|
||||
);
|
||||
final tabStates = ref.watch(tabStatesProvider);
|
||||
|
||||
return EquatableValue({
|
||||
for (final tabEntity in availableTabs.value)
|
||||
if (tabStates.containsKey(tabEntity.tabId))
|
||||
tabEntity.tabId: tabStates[tabEntity.tabId]!,
|
||||
});
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
EquatableValue<List<TabStateWithContainer>> fifoTabStates(Ref ref) {
|
||||
final containerData = ref
|
||||
.watch(watchContainersWithCountProvider.select((value) => value.value))
|
||||
.mapNotNull(
|
||||
(value) => Map.fromEntries(value.map((c) => MapEntry(c.id, c))),
|
||||
);
|
||||
|
||||
final sortedTabs = ref.watch(
|
||||
watchTabsFifoProvider.select((value) => value.value),
|
||||
);
|
||||
|
||||
final tabStates = ref.watch(tabStatesProvider);
|
||||
|
||||
return EquatableValue([
|
||||
if (sortedTabs != null)
|
||||
for (final tab in sortedTabs)
|
||||
if (tabStates.containsKey(tab.id))
|
||||
(
|
||||
tabStates[tab.id]!,
|
||||
tab.containerId.mapNotNull(
|
||||
(containerId) => containerData?[containerId],
|
||||
),
|
||||
),
|
||||
]);
|
||||
}
|
||||
|
||||
@Riverpod()
|
||||
EquatableValue<List<TabStateWithContainer>>
|
||||
selectedContainerTabStatesWithContainer(Ref ref) {
|
||||
final filter = ref.watch(
|
||||
selectedContainerProvider.select(
|
||||
(value) => ContainerFilterById(containerId: value),
|
||||
),
|
||||
);
|
||||
|
||||
final containerData = ref
|
||||
.watch(watchContainersWithCountProvider.select((value) => value.value))
|
||||
.mapNotNull(
|
||||
(value) => Map.fromEntries(value.map((c) => MapEntry(c.id, c))),
|
||||
);
|
||||
|
||||
final sortedTabs = ref.watch(
|
||||
containerTabEntitiesProvider(filter).select((value) => value.value),
|
||||
);
|
||||
|
||||
final tabStates = ref.watch(tabStatesProvider);
|
||||
|
||||
final pinnedTabIds = ref.watch(
|
||||
watchPinnedTabIdsProvider.select((value) => value.value),
|
||||
);
|
||||
|
||||
final orderKeys = {for (final tab in sortedTabs) tab.tabId: tab.orderKey};
|
||||
|
||||
final items = [
|
||||
for (final tabEntity in sortedTabs)
|
||||
if (tabStates.containsKey(tabEntity.tabId))
|
||||
(
|
||||
tabStates[tabEntity.tabId]!,
|
||||
tabEntity.containerId.mapNotNull(
|
||||
(containerId) => containerData?[containerId],
|
||||
),
|
||||
),
|
||||
];
|
||||
|
||||
items.sort((a, b) {
|
||||
final aPinned = pinnedTabIds?.contains(a.$1.id) ?? false;
|
||||
final bPinned = pinnedTabIds?.contains(b.$1.id) ?? false;
|
||||
|
||||
if (aPinned != bPinned) {
|
||||
return aPinned ? -1 : 1;
|
||||
}
|
||||
|
||||
final aOrderKey = orderKeys[a.$1.id] ?? '';
|
||||
final bOrderKey = orderKeys[b.$1.id] ?? '';
|
||||
return aOrderKey.compareTo(bOrderKey);
|
||||
});
|
||||
|
||||
return EquatableValue(items);
|
||||
}
|
||||
|
||||
@Riverpod()
|
||||
EquatableValue<List<TabStateWithContainer>> quickTabSwitcherTabStates(
|
||||
Ref ref,
|
||||
QuickTabSwitcherMode mode,
|
||||
) {
|
||||
final effectiveMode = ref.watch(
|
||||
generalSettingsWithDefaultsProvider.select(
|
||||
(settings) => settings.effectiveUiQuickTabSwitcherMode(),
|
||||
),
|
||||
);
|
||||
final selectedTabId = ref.watch(selectedTabProvider);
|
||||
|
||||
final tabStates = switch (effectiveMode) {
|
||||
QuickTabSwitcherMode.lastUsedTabs => ref.watch(fifoTabStatesProvider).value,
|
||||
QuickTabSwitcherMode.containerTabs =>
|
||||
ref.watch(selectedContainerTabStatesWithContainerProvider).value,
|
||||
};
|
||||
|
||||
return EquatableValue(switch (effectiveMode) {
|
||||
QuickTabSwitcherMode.lastUsedTabs =>
|
||||
tabStates.where((state) => state.$1.id != selectedTabId).toList(),
|
||||
QuickTabSwitcherMode.containerTabs => tabStates,
|
||||
});
|
||||
}
|
||||
|
||||
@Riverpod()
|
||||
Future<List<VisitInfo>> quickTabSwitcherHistorySuggestions(
|
||||
Ref ref,
|
||||
QuickTabSwitcherMode mode,
|
||||
) async {
|
||||
final effectiveMode = ref.watch(
|
||||
generalSettingsWithDefaultsProvider.select(
|
||||
(settings) => settings.effectiveUiQuickTabSwitcherMode(),
|
||||
),
|
||||
);
|
||||
final showHistorySuggestions = ref.watch(
|
||||
generalSettingsWithDefaultsProvider.select(
|
||||
(settings) => settings.quickTabSwitcherShowHistorySuggestions,
|
||||
),
|
||||
);
|
||||
|
||||
if (!showHistorySuggestions) {
|
||||
return [];
|
||||
}
|
||||
|
||||
final hasTabStates = ref.watch(
|
||||
quickTabSwitcherTabStatesProvider(
|
||||
effectiveMode,
|
||||
).select((value) => value.value.isNotEmpty),
|
||||
);
|
||||
if (hasTabStates) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return ref
|
||||
.read(historyRepositoryProvider.notifier)
|
||||
.getVisitsPaginated(count: 25);
|
||||
}
|
||||
|
||||
@Riverpod()
|
||||
AsyncValue<bool> quickTabSwitcherHasResults(
|
||||
Ref ref,
|
||||
QuickTabSwitcherMode mode,
|
||||
) {
|
||||
final effectiveMode = ref.watch(
|
||||
generalSettingsWithDefaultsProvider.select(
|
||||
(settings) => settings.effectiveUiQuickTabSwitcherMode(),
|
||||
),
|
||||
);
|
||||
final showQuickTabSwitcherBar = ref.watch(
|
||||
generalSettingsWithDefaultsProvider.select(
|
||||
(settings) => settings.tabBarShowQuickTabSwitcherBar,
|
||||
),
|
||||
);
|
||||
if (!showQuickTabSwitcherBar) {
|
||||
return const AsyncValue.data(false);
|
||||
}
|
||||
|
||||
final hasResults = ref.watch(
|
||||
quickTabSwitcherTabStatesProvider(
|
||||
effectiveMode,
|
||||
).select((value) => value.value.isNotEmpty),
|
||||
);
|
||||
|
||||
if (hasResults) {
|
||||
return const AsyncValue.data(true);
|
||||
}
|
||||
|
||||
return ref
|
||||
.watch(quickTabSwitcherHistorySuggestionsProvider(effectiveMode))
|
||||
.whenData((visits) => visits.isNotEmpty);
|
||||
}
|
||||
|
||||
@Riverpod()
|
||||
EquatableValue<List<TabEntity>> suggestedTabEntities(
|
||||
Ref ref,
|
||||
String? containerId,
|
||||
) {
|
||||
final enableAiFeatures = ref.watch(
|
||||
generalSettingsWithDefaultsProvider.select(
|
||||
(settings) => settings.enableLocalAiFeatures,
|
||||
),
|
||||
);
|
||||
|
||||
if (!enableAiFeatures) {
|
||||
return EquatableValue([]);
|
||||
}
|
||||
|
||||
final excludedTabIds = ref.watch(
|
||||
watchContainerTabIdsProvider(
|
||||
// ignore: provider_parameters
|
||||
ContainerFilterById(containerId: containerId),
|
||||
).select((value) => EquatableValue(value.value)),
|
||||
);
|
||||
|
||||
final orderKeys = ref.watch(
|
||||
watchTabOrderKeysProvider.select((value) => value.value),
|
||||
);
|
||||
|
||||
final suggestions = ref.watch(
|
||||
containerTabSuggestionsProvider(containerId).select(
|
||||
(value) => EquatableValue(
|
||||
value.value.mapNotNull(
|
||||
(result) => result
|
||||
.whereNot(
|
||||
(tabId) => excludedTabIds.value?.contains(tabId) ?? false,
|
||||
)
|
||||
.map(
|
||||
(tabId) => DefaultTabEntity(
|
||||
tabId: tabId,
|
||||
orderKey: orderKeys?[tabId] ?? '',
|
||||
containerId: containerId,
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
) ??
|
||||
const [],
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return suggestions;
|
||||
}
|
||||
|
||||
List<TabEntity> _applyTabFiltersAndSort(
|
||||
List<TabEntity> entities,
|
||||
TabViewFilterOptions filterOptions,
|
||||
Map<String, TabState> tabStates,
|
||||
Set<String> pinnedTabIds,
|
||||
Map<String, DateTime>? tabTimestamps,
|
||||
) {
|
||||
final sortField = filterOptions.sortType.sortField;
|
||||
final filteredRows = <_TabFilterRow>[];
|
||||
var hasPinned = false;
|
||||
|
||||
for (final entity in entities) {
|
||||
final tabState = tabStates[entity.tabId];
|
||||
final timestamp = tabTimestamps?[entity.tabId];
|
||||
|
||||
if (!filterOptions.matchesTab(tabState?.tabMode, timestamp)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
final isPinned = pinnedTabIds.contains(entity.tabId);
|
||||
hasPinned = hasPinned || isPinned;
|
||||
|
||||
filteredRows.add(
|
||||
_TabFilterRow(
|
||||
entity: entity,
|
||||
isPinned: isPinned,
|
||||
titleKey:
|
||||
sortField == SortField.titleAsc || sortField == SortField.titleDesc
|
||||
? (tabState?.titleOrAuthority ?? '').toLowerCase()
|
||||
: null,
|
||||
urlKey: sortField == SortField.urlAsc || sortField == SortField.urlDesc
|
||||
? (tabState?.url.toString() ?? '')
|
||||
: null,
|
||||
dateKey:
|
||||
sortField == SortField.dateAsc || sortField == SortField.dateDesc
|
||||
? (timestamp ?? DateTime(0))
|
||||
: null,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
if (sortField != null) {
|
||||
filteredRows.sort((a, b) {
|
||||
if (filterOptions.sortPinnedFirst && a.isPinned != b.isPinned) {
|
||||
return b.isPinned ? 1 : -1;
|
||||
}
|
||||
|
||||
final cmp = switch (sortField) {
|
||||
SortField.titleAsc => a.titleKey!.compareTo(b.titleKey!),
|
||||
SortField.titleDesc => b.titleKey!.compareTo(a.titleKey!),
|
||||
SortField.urlAsc => a.urlKey!.compareTo(b.urlKey!),
|
||||
SortField.urlDesc => b.urlKey!.compareTo(a.urlKey!),
|
||||
SortField.dateAsc => a.dateKey!.compareTo(b.dateKey!),
|
||||
SortField.dateDesc => b.dateKey!.compareTo(a.dateKey!),
|
||||
};
|
||||
|
||||
if (cmp == 0) return a.entity.orderKey.compareTo(b.entity.orderKey);
|
||||
|
||||
return cmp;
|
||||
});
|
||||
|
||||
return filteredRows.map((row) => row.entity).toList();
|
||||
}
|
||||
|
||||
if (!hasPinned || !filterOptions.sortPinnedFirst) {
|
||||
return filteredRows.map((row) => row.entity).toList();
|
||||
}
|
||||
|
||||
final pinned = <TabEntity>[];
|
||||
final unpinned = <TabEntity>[];
|
||||
for (final row in filteredRows) {
|
||||
if (row.isPinned) {
|
||||
pinned.add(row.entity);
|
||||
} else {
|
||||
unpinned.add(row.entity);
|
||||
}
|
||||
}
|
||||
|
||||
return [...pinned, ...unpinned];
|
||||
}
|
||||
|
||||
class _TabFilterRow {
|
||||
final TabEntity entity;
|
||||
final bool isPinned;
|
||||
final String? titleKey;
|
||||
final String? urlKey;
|
||||
final DateTime? dateKey;
|
||||
|
||||
const _TabFilterRow({
|
||||
required this.entity,
|
||||
required this.isPinned,
|
||||
required this.titleKey,
|
||||
required this.urlKey,
|
||||
required this.dateKey,
|
||||
});
|
||||
}
|
||||
|
||||
@Riverpod()
|
||||
EquatableValue<List<TabEntity>> seamlessFilteredTabEntities(
|
||||
Ref ref, {
|
||||
required TabSearchPartition searchPartition,
|
||||
required ContainerFilter containerFilter,
|
||||
required bool groupTrees,
|
||||
}) {
|
||||
final orderKeys = ref.watch(
|
||||
watchTabOrderKeysProvider.select((value) => value.value),
|
||||
);
|
||||
|
||||
final tabSearchResults = ref
|
||||
.watch(
|
||||
tabSearchRepositoryProvider(searchPartition).select(
|
||||
(value) => EquatableValue(
|
||||
value.value.mapNotNull(
|
||||
(result) => result.results
|
||||
.map(
|
||||
(tab) => SearchResultTabEntity(
|
||||
tabId: tab.id,
|
||||
orderKey: orderKeys?[tab.id] ?? '',
|
||||
containerId: tab.containerId,
|
||||
searchQuery: result.query,
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
.value;
|
||||
|
||||
final availableTabs = ref.watch(
|
||||
containerTabEntitiesProvider(containerFilter),
|
||||
);
|
||||
|
||||
// Tree mode: no filtering/sorting, return as-is
|
||||
if (groupTrees && tabSearchResults == null) {
|
||||
final trees = ref.watch(
|
||||
watchTabTreesProvider.select(
|
||||
(value) => EquatableValue(
|
||||
value.value?.map((tree) {
|
||||
// Find the container ID for the latest tab
|
||||
final containerForTab = availableTabs.value
|
||||
.where((t) => t.tabId == tree.latestTabId)
|
||||
.firstOrNull
|
||||
?.containerId;
|
||||
|
||||
return TabTreeEntity(
|
||||
tabId: tree.latestTabId,
|
||||
orderKey: orderKeys?[tree.latestTabId] ?? '',
|
||||
containerId: containerForTab,
|
||||
rootId: tree.rootTabId,
|
||||
totalTabs: tree.totalTabs,
|
||||
);
|
||||
}).toList() ??
|
||||
[],
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
return EquatableValue(
|
||||
trees.value
|
||||
.where(
|
||||
(tree) => availableTabs.value.any(
|
||||
(available) => available.tabId == tree.tabId,
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
|
||||
final tabStates = ref.watch(tabStatesProvider);
|
||||
|
||||
final filterOptions = ref.watch(tabViewFilterControllerProvider);
|
||||
|
||||
final pinnedTabIds = ref.watch(
|
||||
watchPinnedTabIdsProvider.select(
|
||||
(value) => value.value ?? const <String>{},
|
||||
),
|
||||
);
|
||||
|
||||
// Only pull timestamps from DB when date filtering/sorting is active
|
||||
final needsTimestamps =
|
||||
filterOptions.effectiveDateRange != null ||
|
||||
filterOptions.sortType.sortField == SortField.dateAsc ||
|
||||
filterOptions.sortType.sortField == SortField.dateDesc;
|
||||
final tabTimestamps = needsTimestamps
|
||||
? ref.watch(watchTabTimestampsProvider.select((value) => value.value))
|
||||
: null;
|
||||
|
||||
if (tabSearchResults == null) {
|
||||
if (filterOptions.hasActiveFilter || pinnedTabIds.isNotEmpty) {
|
||||
return EquatableValue(
|
||||
_applyTabFiltersAndSort(
|
||||
availableTabs.value,
|
||||
filterOptions,
|
||||
tabStates,
|
||||
pinnedTabIds,
|
||||
tabTimestamps,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return availableTabs;
|
||||
}
|
||||
|
||||
final searchFiltered = tabSearchResults
|
||||
.where(
|
||||
(tab) => availableTabs.value.any(
|
||||
(available) => available.tabId == tab.tabId,
|
||||
),
|
||||
)
|
||||
.toList();
|
||||
|
||||
if (filterOptions.hasActiveFilter || pinnedTabIds.isNotEmpty) {
|
||||
return EquatableValue(
|
||||
_applyTabFiltersAndSort(
|
||||
searchFiltered,
|
||||
filterOptions,
|
||||
tabStates,
|
||||
pinnedTabIds,
|
||||
tabTimestamps,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return EquatableValue(searchFiltered);
|
||||
}
|
||||
|
||||
@Riverpod()
|
||||
EquatableValue<List<TabPreview>> filteredTabPreviews(
|
||||
Ref ref,
|
||||
TabSearchPartition searchPartition,
|
||||
ContainerFilter containerFilter,
|
||||
) {
|
||||
final tabSearchResults = ref
|
||||
.watch(
|
||||
tabSearchRepositoryProvider(
|
||||
searchPartition,
|
||||
).select((value) => EquatableValue(value.value)),
|
||||
)
|
||||
.value;
|
||||
|
||||
final availableTabStates = ref.watch(
|
||||
containerTabStatesProvider(containerFilter),
|
||||
);
|
||||
|
||||
if (tabSearchResults == null) {
|
||||
return EquatableValue([]);
|
||||
}
|
||||
|
||||
return EquatableValue(
|
||||
tabSearchResults.results
|
||||
.where((tab) => availableTabStates.value.containsKey(tab.id))
|
||||
.map((tab) {
|
||||
final tabState = availableTabStates.value[tab.id]!;
|
||||
|
||||
return TabPreview(
|
||||
id: tab.id,
|
||||
containerId: tab.containerId,
|
||||
title: tab.title ?? tabState.title,
|
||||
icon: tabState.icon,
|
||||
url: tab.cleanUrl ?? tabState.url,
|
||||
highlightedUrl: tab.url,
|
||||
extractedContent: tab.extractedContent,
|
||||
fullContent: tab.fullContent,
|
||||
sourceSearchQuery: tabSearchResults.query,
|
||||
);
|
||||
})
|
||||
.whereType<TabPreview>()
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
|
||||
@Riverpod()
|
||||
class AppLinksModeNotifier extends _$AppLinksModeNotifier {
|
||||
final _service = GeckoEngineSettingsService();
|
||||
|
||||
Future<void> setMode(AppLinksMode mode) async {
|
||||
await _service.setAppLinksMode(mode);
|
||||
ref.invalidateSelf();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<AppLinksMode> build() {
|
||||
return _service.getAppLinksMode();
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,101 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:nullability/nullability.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:rxdart/rxdart.dart';
|
||||
import 'package:weblibre/core/logger.dart';
|
||||
import 'package:weblibre/core/routing/routes.dart';
|
||||
import 'package:weblibre/data/models/received_intent_parameter.dart';
|
||||
import 'package:weblibre/features/app_widget/domain/services/home_widget.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers.dart';
|
||||
import 'package:weblibre/features/share_intent/domain/entities/shared_content.dart';
|
||||
import 'package:weblibre/features/share_intent/domain/services/sharing_intent.dart';
|
||||
|
||||
part 'intent.g.dart';
|
||||
|
||||
final _contentParserTransformer =
|
||||
StreamTransformer<ReceivedIntentParameter, SharedContent>.fromHandlers(
|
||||
handleData: (parameter, sink) {
|
||||
final parsed = parameter.content.mapNotNull(
|
||||
(content) => SharedContent.parse(
|
||||
content,
|
||||
contextId: parameter.contextId,
|
||||
),
|
||||
);
|
||||
|
||||
if (parsed != null) {
|
||||
sink.add(parsed);
|
||||
} else if (parameter.tool == 'search') {
|
||||
sink.add(SharedText(SearchRoute.emptySearchText));
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
@Riverpod()
|
||||
class EngineBoundIntentStream extends _$EngineBoundIntentStream {
|
||||
@override
|
||||
Stream<SharedContent> build() {
|
||||
final engineReady = ref.watch(engineReadyStateProvider);
|
||||
if (!engineReady) {
|
||||
return const Stream.empty();
|
||||
}
|
||||
|
||||
final sharingItentStream = ref.watch(sharingIntentStreamProvider);
|
||||
final appWidgetLaunchStream = ref.watch(appWidgetLaunchStreamProvider);
|
||||
|
||||
// Create a broadcast stream controller to buffer events
|
||||
final controller = StreamController<SharedContent>.broadcast();
|
||||
|
||||
final subscription =
|
||||
MergeStream([
|
||||
sharingItentStream.transform(_contentParserTransformer),
|
||||
appWidgetLaunchStream.transform(_contentParserTransformer),
|
||||
]).listen(
|
||||
controller.add,
|
||||
onError: (Object error, StackTrace stackTrace) {
|
||||
logger.e(
|
||||
'Intent stream error',
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
controller.addError(error, stackTrace);
|
||||
},
|
||||
onDone: controller.close,
|
||||
);
|
||||
|
||||
ref.onDispose(() async {
|
||||
await subscription.cancel();
|
||||
await controller.close();
|
||||
});
|
||||
|
||||
return controller.stream;
|
||||
}
|
||||
|
||||
@override
|
||||
bool updateShouldNotify(
|
||||
AsyncValue<SharedContent> previous,
|
||||
AsyncValue<SharedContent> next,
|
||||
) {
|
||||
// Always notify if e.g. same link opened consecutive that are elseiwese filtered on == comaprison
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'intent.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(EngineBoundIntentStream)
|
||||
final engineBoundIntentStreamProvider = EngineBoundIntentStreamProvider._();
|
||||
|
||||
final class EngineBoundIntentStreamProvider
|
||||
extends $StreamNotifierProvider<EngineBoundIntentStream, SharedContent> {
|
||||
EngineBoundIntentStreamProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'engineBoundIntentStreamProvider',
|
||||
isAutoDispose: true,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$engineBoundIntentStreamHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
EngineBoundIntentStream create() => EngineBoundIntentStream();
|
||||
}
|
||||
|
||||
String _$engineBoundIntentStreamHash() =>
|
||||
r'618eb6431da93989de6f1780cba2993458b0014e';
|
||||
|
||||
abstract class _$EngineBoundIntentStream
|
||||
extends $StreamNotifier<SharedContent> {
|
||||
Stream<SharedContent> build();
|
||||
@$mustCallSuper
|
||||
@override
|
||||
void runBuild() {
|
||||
final ref = this.ref as $Ref<AsyncValue<SharedContent>, SharedContent>;
|
||||
final element =
|
||||
ref.element
|
||||
as $ClassProviderElement<
|
||||
AnyNotifier<AsyncValue<SharedContent>, SharedContent>,
|
||||
AsyncValue<SharedContent>,
|
||||
Object?,
|
||||
Object?
|
||||
>;
|
||||
element.handleCreate(ref, build);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'dart:ui';
|
||||
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
part 'lifecycle.g.dart';
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
class BrowserViewLifecycle extends _$BrowserViewLifecycle {
|
||||
// ignore: use_setters_to_change_properties
|
||||
void update(AppLifecycleState? newState) {
|
||||
state = newState;
|
||||
}
|
||||
|
||||
@override
|
||||
AppLifecycleState? build() {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'lifecycle.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(BrowserViewLifecycle)
|
||||
final browserViewLifecycleProvider = BrowserViewLifecycleProvider._();
|
||||
|
||||
final class BrowserViewLifecycleProvider
|
||||
extends $NotifierProvider<BrowserViewLifecycle, AppLifecycleState?> {
|
||||
BrowserViewLifecycleProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'browserViewLifecycleProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$browserViewLifecycleHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
BrowserViewLifecycle create() => BrowserViewLifecycle();
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(AppLifecycleState? value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<AppLifecycleState?>(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$browserViewLifecycleHash() =>
|
||||
r'9082d058611aaaae268b60b8ce130150f73d453d';
|
||||
|
||||
abstract class _$BrowserViewLifecycle extends $Notifier<AppLifecycleState?> {
|
||||
AppLifecycleState? build();
|
||||
@$mustCallSuper
|
||||
@override
|
||||
void runBuild() {
|
||||
final ref = this.ref as $Ref<AppLifecycleState?, AppLifecycleState?>;
|
||||
final element =
|
||||
ref.element
|
||||
as $ClassProviderElement<
|
||||
AnyNotifier<AppLifecycleState?, AppLifecycleState?>,
|
||||
AppLifecycleState?,
|
||||
Object?,
|
||||
Object?
|
||||
>;
|
||||
element.handleCreate(ref, build);
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/domain/entities/site_permissions.dart';
|
||||
|
||||
part 'site_permissions.g.dart';
|
||||
|
||||
typedef PermissionUpdater = SitePermissions Function(SitePermissionsWrapper);
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
class SitePermissionsRepository extends _$SitePermissionsRepository {
|
||||
final _api = GeckoSitePermissionsApi();
|
||||
|
||||
Future<SitePermissions?> getPermissions() async {
|
||||
final permissions = await _api.getSitePermissions(origin, isPrivate);
|
||||
state = AsyncValue.data(permissions);
|
||||
|
||||
return permissions;
|
||||
}
|
||||
|
||||
Future<void> updatePermission(PermissionUpdater updater) async {
|
||||
final currentPermissions =
|
||||
await getPermissions() ??
|
||||
SitePermissions(
|
||||
origin: origin,
|
||||
savedAt: DateTime.now().millisecondsSinceEpoch,
|
||||
);
|
||||
|
||||
await setPermissions(
|
||||
updater(SitePermissionsWrapper.fromPermission(currentPermissions)),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> setPermissions(SitePermissions permissions) async {
|
||||
if (permissions.origin != origin) {
|
||||
throw Exception('Origin does not match');
|
||||
}
|
||||
|
||||
await _api.setSitePermissions(permissions, isPrivate);
|
||||
ref.invalidateSelf();
|
||||
}
|
||||
|
||||
Future<void> deletePermissions() async {
|
||||
await _api.deleteSitePermissions(origin, isPrivate);
|
||||
ref.invalidateSelf();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<SitePermissions?> build({
|
||||
required String origin,
|
||||
required bool isPrivate,
|
||||
}) async {
|
||||
final permissions = await _api.getSitePermissions(origin, isPrivate);
|
||||
return permissions;
|
||||
}
|
||||
}
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'site_permissions.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(SitePermissionsRepository)
|
||||
final sitePermissionsRepositoryProvider = SitePermissionsRepositoryFamily._();
|
||||
|
||||
final class SitePermissionsRepositoryProvider
|
||||
extends
|
||||
$AsyncNotifierProvider<SitePermissionsRepository, SitePermissions?> {
|
||||
SitePermissionsRepositoryProvider._({
|
||||
required SitePermissionsRepositoryFamily super.from,
|
||||
required ({String origin, bool isPrivate}) super.argument,
|
||||
}) : super(
|
||||
retry: null,
|
||||
name: r'sitePermissionsRepositoryProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$sitePermissionsRepositoryHash();
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return r'sitePermissionsRepositoryProvider'
|
||||
''
|
||||
'$argument';
|
||||
}
|
||||
|
||||
@$internal
|
||||
@override
|
||||
SitePermissionsRepository create() => SitePermissionsRepository();
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return other is SitePermissionsRepositoryProvider &&
|
||||
other.argument == argument;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return argument.hashCode;
|
||||
}
|
||||
}
|
||||
|
||||
String _$sitePermissionsRepositoryHash() =>
|
||||
r'b821fbd3a457f5b9cfc6c9d398c93f09c6b30b0b';
|
||||
|
||||
final class SitePermissionsRepositoryFamily extends $Family
|
||||
with
|
||||
$ClassFamilyOverride<
|
||||
SitePermissionsRepository,
|
||||
AsyncValue<SitePermissions?>,
|
||||
SitePermissions?,
|
||||
FutureOr<SitePermissions?>,
|
||||
({String origin, bool isPrivate})
|
||||
> {
|
||||
SitePermissionsRepositoryFamily._()
|
||||
: super(
|
||||
retry: null,
|
||||
name: r'sitePermissionsRepositoryProvider',
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
isAutoDispose: false,
|
||||
);
|
||||
|
||||
SitePermissionsRepositoryProvider call({
|
||||
required String origin,
|
||||
required bool isPrivate,
|
||||
}) => SitePermissionsRepositoryProvider._(
|
||||
argument: (origin: origin, isPrivate: isPrivate),
|
||||
from: this,
|
||||
);
|
||||
|
||||
@override
|
||||
String toString() => r'sitePermissionsRepositoryProvider';
|
||||
}
|
||||
|
||||
abstract class _$SitePermissionsRepository
|
||||
extends $AsyncNotifier<SitePermissions?> {
|
||||
late final _$args = ref.$arg as ({String origin, bool isPrivate});
|
||||
String get origin => _$args.origin;
|
||||
bool get isPrivate => _$args.isPrivate;
|
||||
|
||||
FutureOr<SitePermissions?> build({
|
||||
required String origin,
|
||||
required bool isPrivate,
|
||||
});
|
||||
@$mustCallSuper
|
||||
@override
|
||||
void runBuild() {
|
||||
final ref =
|
||||
this.ref as $Ref<AsyncValue<SitePermissions?>, SitePermissions?>;
|
||||
final element =
|
||||
ref.element
|
||||
as $ClassProviderElement<
|
||||
AnyNotifier<AsyncValue<SitePermissions?>, SitePermissions?>,
|
||||
AsyncValue<SitePermissions?>,
|
||||
Object?,
|
||||
Object?
|
||||
>;
|
||||
element.handleCreate(
|
||||
ref,
|
||||
() => build(origin: _$args.origin, isPrivate: _$args.isPrivate),
|
||||
);
|
||||
}
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
part 'tracking_protection.g.dart';
|
||||
|
||||
/// Repository for managing per-site Enhanced Tracking Protection exceptions
|
||||
///
|
||||
/// Wraps the GeckoTrackingProtectionApi and handles state invalidation
|
||||
/// automatically after mutations.
|
||||
@Riverpod(keepAlive: true)
|
||||
class TrackingProtectionRepository extends _$TrackingProtectionRepository {
|
||||
final _api = GeckoTrackingProtectionApi();
|
||||
|
||||
/// Check if a tab has a tracking protection exception
|
||||
///
|
||||
/// Returns true if ETP is disabled for this site
|
||||
Future<bool> containsException(String tabId) {
|
||||
return _api.containsException(tabId);
|
||||
}
|
||||
|
||||
/// Add tracking protection exception for a tab (disable ETP for this site)
|
||||
Future<void> addException(String tabId) async {
|
||||
await _api.addException(tabId);
|
||||
await _invalidateWithDelay();
|
||||
}
|
||||
|
||||
/// Remove tracking protection exception for a tab (enable ETP for this site)
|
||||
Future<void> removeException(String tabId) async {
|
||||
await _api.removeException(tabId);
|
||||
await _invalidateWithDelay();
|
||||
}
|
||||
|
||||
/// Remove a specific exception by URL and refresh the exceptions list
|
||||
Future<void> removeExceptionByUrl(String url) async {
|
||||
await _api.removeExceptionByUrl(url);
|
||||
await _invalidateWithDelay();
|
||||
}
|
||||
|
||||
/// Remove all tracking protection exceptions
|
||||
Future<void> removeAllExceptions() async {
|
||||
await _api.removeAllExceptions();
|
||||
await _invalidateWithDelay();
|
||||
}
|
||||
|
||||
/// Helper method to invalidate repository state after mutations with delay
|
||||
Future<void> _invalidateWithDelay() async {
|
||||
await Future.delayed(const Duration(milliseconds: 100)).whenComplete(() {
|
||||
if (ref.mounted) {
|
||||
ref.invalidateSelf();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Future<List<TrackingProtectionException>> build() {
|
||||
return _api.fetchExceptions();
|
||||
}
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'tracking_protection.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
/// Repository for managing per-site Enhanced Tracking Protection exceptions
|
||||
///
|
||||
/// Wraps the GeckoTrackingProtectionApi and handles state invalidation
|
||||
/// automatically after mutations.
|
||||
|
||||
@ProviderFor(TrackingProtectionRepository)
|
||||
final trackingProtectionRepositoryProvider =
|
||||
TrackingProtectionRepositoryProvider._();
|
||||
|
||||
/// Repository for managing per-site Enhanced Tracking Protection exceptions
|
||||
///
|
||||
/// Wraps the GeckoTrackingProtectionApi and handles state invalidation
|
||||
/// automatically after mutations.
|
||||
final class TrackingProtectionRepositoryProvider
|
||||
extends
|
||||
$AsyncNotifierProvider<
|
||||
TrackingProtectionRepository,
|
||||
List<TrackingProtectionException>
|
||||
> {
|
||||
/// Repository for managing per-site Enhanced Tracking Protection exceptions
|
||||
///
|
||||
/// Wraps the GeckoTrackingProtectionApi and handles state invalidation
|
||||
/// automatically after mutations.
|
||||
TrackingProtectionRepositoryProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'trackingProtectionRepositoryProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$trackingProtectionRepositoryHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
TrackingProtectionRepository create() => TrackingProtectionRepository();
|
||||
}
|
||||
|
||||
String _$trackingProtectionRepositoryHash() =>
|
||||
r'f4b09ed513da6bd5a9f4d01833a2dbba990f59de';
|
||||
|
||||
/// Repository for managing per-site Enhanced Tracking Protection exceptions
|
||||
///
|
||||
/// Wraps the GeckoTrackingProtectionApi and handles state invalidation
|
||||
/// automatically after mutations.
|
||||
|
||||
abstract class _$TrackingProtectionRepository
|
||||
extends $AsyncNotifier<List<TrackingProtectionException>> {
|
||||
FutureOr<List<TrackingProtectionException>> build();
|
||||
@$mustCallSuper
|
||||
@override
|
||||
void runBuild() {
|
||||
final ref =
|
||||
this.ref
|
||||
as $Ref<
|
||||
AsyncValue<List<TrackingProtectionException>>,
|
||||
List<TrackingProtectionException>
|
||||
>;
|
||||
final element =
|
||||
ref.element
|
||||
as $ClassProviderElement<
|
||||
AnyNotifier<
|
||||
AsyncValue<List<TrackingProtectionException>>,
|
||||
List<TrackingProtectionException>
|
||||
>,
|
||||
AsyncValue<List<TrackingProtectionException>>,
|
||||
Object?,
|
||||
Object?
|
||||
>;
|
||||
element.handleCreate(ref, build);
|
||||
}
|
||||
}
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:weblibre/core/logger.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers.dart';
|
||||
import 'package:weblibre/features/geckoview/features/preferences/data/repositories/preference_observer.dart';
|
||||
|
||||
part 'browser_addon.g.dart';
|
||||
|
||||
const _signatureRequiredPref = 'xpinstall.signatures.required';
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
class AllowUnsignedExtensions extends _$AllowUnsignedExtensions {
|
||||
Future<void> setAllowUnsigned({required bool allow}) async {
|
||||
final fixator = ref.read(preferenceFixatorProvider.notifier);
|
||||
if (allow) {
|
||||
await fixator.register(_signatureRequiredPref, false);
|
||||
} else {
|
||||
await fixator.unregister(_signatureRequiredPref);
|
||||
await GeckoPrefService().applyPrefs({_signatureRequiredPref: true});
|
||||
}
|
||||
state = AsyncData(allow);
|
||||
}
|
||||
|
||||
@override
|
||||
FutureOr<bool> build() async {
|
||||
final prefs =
|
||||
await GeckoPrefService().getPrefs([_signatureRequiredPref]);
|
||||
final pref = prefs[_signatureRequiredPref];
|
||||
final allowUnsigned = pref?.value == false;
|
||||
|
||||
// Re-register with fixator to prevent Gecko from resetting
|
||||
if (allowUnsigned) {
|
||||
await ref
|
||||
.read(preferenceFixatorProvider.notifier)
|
||||
.register(_signatureRequiredPref, false);
|
||||
}
|
||||
|
||||
return allowUnsigned;
|
||||
}
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
class BrowserAddonService extends _$BrowserAddonService {
|
||||
Future<Uri> getAddonXpiUrl(String guid) async {
|
||||
final url = 'https://addons.mozilla.org/api/v5/addons/addon/$guid/';
|
||||
|
||||
try {
|
||||
final response = await http.get(Uri.parse(url));
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final data = jsonDecode(response.body) as Map<String, dynamic>;
|
||||
|
||||
// ignore: avoid_dynamic_calls
|
||||
final xpiUrl = data['current_version']['file']['url'] as String;
|
||||
|
||||
return Uri.parse(xpiUrl);
|
||||
} else {
|
||||
throw Exception('Failed to load addon data: ${response.statusCode}');
|
||||
}
|
||||
} catch (e) {
|
||||
throw Exception('Error fetching addon data: $e');
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> install(String addonGuid) async {
|
||||
try {
|
||||
final xpiUrl = await getAddonXpiUrl(addonGuid);
|
||||
if (!ref.mounted) return false;
|
||||
|
||||
await ref.read(addonServiceProvider).installAddon(xpiUrl);
|
||||
|
||||
return true;
|
||||
} catch (e, s) {
|
||||
logger.e('Failed installing $addonGuid', error: e, stackTrace: s);
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
Future<bool> installFromFile(String filePath) async {
|
||||
try {
|
||||
// Validate file exists and has .xpi extension
|
||||
final file = File(filePath);
|
||||
if (!file.existsSync()) {
|
||||
throw Exception('File does not exist: $filePath');
|
||||
}
|
||||
|
||||
final extension = filePath.toLowerCase();
|
||||
if (!extension.endsWith('.xpi')) {
|
||||
throw Exception('Invalid file type. Expected .xpi file');
|
||||
}
|
||||
|
||||
// Create file:// URI and install
|
||||
final fileUri = Uri.file(filePath);
|
||||
if (!ref.mounted) return false;
|
||||
|
||||
await ref.read(addonServiceProvider).installAddon(fileUri);
|
||||
|
||||
return true;
|
||||
} catch (e, s) {
|
||||
logger.e(
|
||||
'Failed installing from file: $filePath',
|
||||
error: e,
|
||||
stackTrace: s,
|
||||
);
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void build() {}
|
||||
}
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'browser_addon.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(AllowUnsignedExtensions)
|
||||
final allowUnsignedExtensionsProvider = AllowUnsignedExtensionsProvider._();
|
||||
|
||||
final class AllowUnsignedExtensionsProvider
|
||||
extends $AsyncNotifierProvider<AllowUnsignedExtensions, bool> {
|
||||
AllowUnsignedExtensionsProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'allowUnsignedExtensionsProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$allowUnsignedExtensionsHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
AllowUnsignedExtensions create() => AllowUnsignedExtensions();
|
||||
}
|
||||
|
||||
String _$allowUnsignedExtensionsHash() =>
|
||||
r'3b67f51cabf8e2f37d992320c5b93bb61c6dbe1f';
|
||||
|
||||
abstract class _$AllowUnsignedExtensions extends $AsyncNotifier<bool> {
|
||||
FutureOr<bool> build();
|
||||
@$mustCallSuper
|
||||
@override
|
||||
void runBuild() {
|
||||
final ref = this.ref as $Ref<AsyncValue<bool>, bool>;
|
||||
final element =
|
||||
ref.element
|
||||
as $ClassProviderElement<
|
||||
AnyNotifier<AsyncValue<bool>, bool>,
|
||||
AsyncValue<bool>,
|
||||
Object?,
|
||||
Object?
|
||||
>;
|
||||
element.handleCreate(ref, build);
|
||||
}
|
||||
}
|
||||
|
||||
@ProviderFor(BrowserAddonService)
|
||||
final browserAddonServiceProvider = BrowserAddonServiceProvider._();
|
||||
|
||||
final class BrowserAddonServiceProvider
|
||||
extends $NotifierProvider<BrowserAddonService, void> {
|
||||
BrowserAddonServiceProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'browserAddonServiceProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$browserAddonServiceHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
BrowserAddonService create() => BrowserAddonService();
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(void value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<void>(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$browserAddonServiceHash() =>
|
||||
r'b90e69ce77b846d6056c800f232a8aa50b4b21d0';
|
||||
|
||||
abstract class _$BrowserAddonService extends $Notifier<void> {
|
||||
void build();
|
||||
@$mustCallSuper
|
||||
@override
|
||||
void runBuild() {
|
||||
final ref = this.ref as $Ref<void, void>;
|
||||
final element =
|
||||
ref.element
|
||||
as $ClassProviderElement<
|
||||
AnyNotifier<void, void>,
|
||||
void,
|
||||
Object?,
|
||||
Object?
|
||||
>;
|
||||
element.handleCreate(ref, build);
|
||||
}
|
||||
}
|
||||
+76
@@ -0,0 +1,76 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:weblibre/features/user/data/models/general_settings.dart';
|
||||
|
||||
part 'browser_data.g.dart';
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
class BrowserDataService extends _$BrowserDataService {
|
||||
final _service = GeckoDeleteBrowserDataService();
|
||||
|
||||
var _onStartDeleted = false;
|
||||
|
||||
Future<void> deleteDataOnEngineStart(
|
||||
Set<DeleteBrowsingDataType>? types,
|
||||
) async {
|
||||
if (!_onStartDeleted) {
|
||||
_onStartDeleted = true;
|
||||
return deleteData(types);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> deleteData(Set<DeleteBrowsingDataType>? types) async {
|
||||
if (types != null) {
|
||||
for (final type in types) {
|
||||
switch (type) {
|
||||
case DeleteBrowsingDataType.tabs:
|
||||
await _service.deleteTabs();
|
||||
case DeleteBrowsingDataType.history:
|
||||
await _service.deleteBrowsingHistory();
|
||||
case DeleteBrowsingDataType.cookies:
|
||||
await _service.deleteCookiesAndSiteData();
|
||||
case DeleteBrowsingDataType.cache:
|
||||
await _service.deleteCachedFiles();
|
||||
case DeleteBrowsingDataType.permissions:
|
||||
await _service.deleteSitePermissions();
|
||||
case DeleteBrowsingDataType.downloads:
|
||||
await _service.deleteDownloads();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> clearDataForContext(String contextId) {
|
||||
return _service.clearDataForContext(contextId);
|
||||
}
|
||||
|
||||
Future<void> clearContainerDataOnEngineStart(List<String> contextIds) async {
|
||||
if (!_onStartDeleted && contextIds.isNotEmpty) {
|
||||
for (final contextId in contextIds) {
|
||||
await clearDataForContext(contextId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void build() {}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'browser_data.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(BrowserDataService)
|
||||
final browserDataServiceProvider = BrowserDataServiceProvider._();
|
||||
|
||||
final class BrowserDataServiceProvider
|
||||
extends $NotifierProvider<BrowserDataService, void> {
|
||||
BrowserDataServiceProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'browserDataServiceProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$browserDataServiceHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
BrowserDataService create() => BrowserDataService();
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(void value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<void>(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$browserDataServiceHash() =>
|
||||
r'861943be10c4dea325484b6a28ba21f3ff0d29fa';
|
||||
|
||||
abstract class _$BrowserDataService extends $Notifier<void> {
|
||||
void build();
|
||||
@$mustCallSuper
|
||||
@override
|
||||
void runBuild() {
|
||||
final ref = this.ref as $Ref<void, void>;
|
||||
final element =
|
||||
ref.element
|
||||
as $ClassProviderElement<
|
||||
AnyNotifier<void, void>,
|
||||
void,
|
||||
Object?,
|
||||
Object?
|
||||
>;
|
||||
element.handleCreate(ref, build);
|
||||
}
|
||||
}
|
||||
+306
@@ -0,0 +1,306 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:collection/collection.dart';
|
||||
import 'package:flutter/material.dart' show ThemeMode;
|
||||
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
|
||||
import 'package:riverpod/riverpod.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:weblibre/core/logger.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/domain/services/browser_addon.dart';
|
||||
import 'package:weblibre/features/geckoview/features/preferences/data/repositories/preference_observer.dart';
|
||||
import 'package:weblibre/features/geckoview/features/preferences/data/repositories/preference_settings.dart';
|
||||
import 'package:weblibre/features/user/domain/repositories/engine_settings.dart';
|
||||
import 'package:weblibre/features/user/domain/repositories/general_settings.dart';
|
||||
|
||||
part 'engine_settings_replication.g.dart';
|
||||
|
||||
/// Checks if any Custom ETP setting changed between two EngineSettings instances.
|
||||
bool _customEtpSettingsChanged(
|
||||
GeckoEngineSettings? previous,
|
||||
GeckoEngineSettings current,
|
||||
) {
|
||||
if (previous == null) return true;
|
||||
return previous.blockCookies != current.blockCookies ||
|
||||
previous.customCookiePolicy != current.customCookiePolicy ||
|
||||
previous.blockTrackingContent != current.blockTrackingContent ||
|
||||
previous.trackingContentScope != current.trackingContentScope ||
|
||||
previous.blockCryptominers != current.blockCryptominers ||
|
||||
previous.blockFingerprinters != current.blockFingerprinters ||
|
||||
previous.blockRedirectTrackers != current.blockRedirectTrackers ||
|
||||
previous.blockSuspectedFingerprinters !=
|
||||
current.blockSuspectedFingerprinters ||
|
||||
previous.suspectedFingerprintersScope !=
|
||||
current.suspectedFingerprintersScope ||
|
||||
previous.allowListBaseline != current.allowListBaseline ||
|
||||
previous.allowListConvenience != current.allowListConvenience;
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
class EngineSettingsReplicationService
|
||||
extends _$EngineSettingsReplicationService {
|
||||
final _service = GeckoEngineSettingsService();
|
||||
|
||||
@override
|
||||
void build() {
|
||||
var initialSettingsSent = false;
|
||||
|
||||
ref.listen(
|
||||
fireImmediately: true,
|
||||
generalSettingsWithDefaultsProvider.select(
|
||||
(settings) => settings.themeMode,
|
||||
),
|
||||
(previous, next) async {
|
||||
final theme = switch (next) {
|
||||
ThemeMode.system => ColorScheme.system,
|
||||
ThemeMode.light => ColorScheme.light,
|
||||
ThemeMode.dark => ColorScheme.dark,
|
||||
};
|
||||
|
||||
await _service.preferredColorScheme(theme);
|
||||
},
|
||||
onError: (error, stackTrace) {
|
||||
logger.e(
|
||||
'Error listening to generalSettingsRepositoryProvider',
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
ref.listen(
|
||||
fireImmediately: true,
|
||||
generalSettingsWithDefaultsProvider.select(
|
||||
(settings) => settings.pullToRefreshEnabled,
|
||||
),
|
||||
(previous, next) async {
|
||||
await _service.setPullToRefreshEnabled(next);
|
||||
},
|
||||
onError: (error, stackTrace) {
|
||||
logger.e(
|
||||
'Error listening to pullToRefreshEnabled',
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
ref.listen(
|
||||
fireImmediately: true,
|
||||
generalSettingsWithDefaultsProvider.select(
|
||||
(settings) => settings.useExternalDownloadManager,
|
||||
),
|
||||
(previous, next) async {
|
||||
await _service.setUseExternalDownloadManager(next);
|
||||
},
|
||||
onError: (error, stackTrace) {
|
||||
logger.e(
|
||||
'Error listening to useExternalDownloadManager',
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
ref.listen(
|
||||
fireImmediately: true,
|
||||
engineSettingsRepositoryProvider,
|
||||
(previous, next) async {
|
||||
final settings = next.value;
|
||||
|
||||
if (settings != null) {
|
||||
if (initialSettingsSent && previous != null) {
|
||||
if (previous.value?.javascriptEnabled !=
|
||||
settings.javascriptEnabled) {
|
||||
await _service.javascriptEnabled(settings.javascriptEnabled);
|
||||
}
|
||||
// Check if tracking protection policy mode changed OR any custom ETP setting changed
|
||||
final policyModeChanged =
|
||||
previous.value?.trackingProtectionPolicy !=
|
||||
settings.trackingProtectionPolicy;
|
||||
final customSettingsChanged =
|
||||
settings.trackingProtectionPolicy ==
|
||||
TrackingProtectionPolicy.custom &&
|
||||
_customEtpSettingsChanged(previous.value, settings);
|
||||
|
||||
if (policyModeChanged || customSettingsChanged) {
|
||||
// Always send full custom settings when in CUSTOM mode
|
||||
if (settings.trackingProtectionPolicy ==
|
||||
TrackingProtectionPolicy.custom) {
|
||||
await _service.customTrackingProtectionPolicy(
|
||||
trackingProtectionPolicy: settings.trackingProtectionPolicy,
|
||||
contentBlocking: settings.contentBlocking,
|
||||
blockCookies: settings.blockCookies,
|
||||
customCookiePolicy: settings.customCookiePolicy,
|
||||
blockTrackingContent: settings.blockTrackingContent,
|
||||
trackingContentScope: settings.trackingContentScope,
|
||||
blockCryptominers: settings.blockCryptominers,
|
||||
blockFingerprinters: settings.blockFingerprinters,
|
||||
blockRedirectTrackers: settings.blockRedirectTrackers,
|
||||
blockSuspectedFingerprinters:
|
||||
settings.blockSuspectedFingerprinters,
|
||||
suspectedFingerprintersScope:
|
||||
settings.suspectedFingerprintersScope,
|
||||
allowListBaseline: settings.allowListBaseline,
|
||||
allowListConvenience: settings.allowListConvenience,
|
||||
);
|
||||
} else {
|
||||
await _service.trackingProtectionPolicy(
|
||||
settings.trackingProtectionPolicy,
|
||||
contentBlocking: settings.contentBlocking,
|
||||
);
|
||||
}
|
||||
}
|
||||
if (previous.value?.httpsOnlyMode != settings.httpsOnlyMode) {
|
||||
await _service.httpsOnlyMode(settings.httpsOnlyMode);
|
||||
}
|
||||
if (previous.value?.globalPrivacyControlEnabled !=
|
||||
settings.globalPrivacyControlEnabled) {
|
||||
await _service.globalPrivacyControlEnabled(
|
||||
settings.globalPrivacyControlEnabled,
|
||||
);
|
||||
}
|
||||
if (previous.value?.preferredColorScheme !=
|
||||
settings.preferredColorScheme) {
|
||||
await _service.preferredColorScheme(
|
||||
settings.preferredColorScheme,
|
||||
);
|
||||
}
|
||||
if (previous.value?.cookieBannerHandlingMode !=
|
||||
settings.cookieBannerHandlingMode) {
|
||||
await _service.cookieBannerHandlingMode(
|
||||
settings.cookieBannerHandlingMode,
|
||||
);
|
||||
}
|
||||
if (previous.value?.cookieBannerHandlingModePrivateBrowsing !=
|
||||
settings.cookieBannerHandlingModePrivateBrowsing) {
|
||||
await _service.cookieBannerHandlingModePrivateBrowsing(
|
||||
settings.cookieBannerHandlingModePrivateBrowsing,
|
||||
);
|
||||
}
|
||||
if (previous.value?.cookieBannerHandlingGlobalRules !=
|
||||
settings.cookieBannerHandlingGlobalRules) {
|
||||
await _service.cookieBannerHandlingGlobalRules(
|
||||
settings.cookieBannerHandlingGlobalRules,
|
||||
);
|
||||
}
|
||||
if (previous.value?.cookieBannerHandlingGlobalRulesSubFrames !=
|
||||
settings.cookieBannerHandlingGlobalRulesSubFrames) {
|
||||
await _service.cookieBannerHandlingGlobalRulesSubFrames(
|
||||
settings.cookieBannerHandlingGlobalRulesSubFrames,
|
||||
);
|
||||
}
|
||||
if (previous.value?.webContentIsolationStrategy !=
|
||||
settings.webContentIsolationStrategy) {
|
||||
await _service.webContentIsolationStrategy(
|
||||
settings.webContentIsolationStrategy,
|
||||
);
|
||||
}
|
||||
if (previous.value?.contentBlocking != settings.contentBlocking) {
|
||||
await _service.contentBlocking(settings.contentBlocking);
|
||||
}
|
||||
if (previous.value?.dohSettings != settings.dohSettings) {
|
||||
await _service.dohSettings(settings.dohSettings);
|
||||
}
|
||||
if (previous.value?.fingerprintingProtectionOverrides !=
|
||||
settings.fingerprintingProtectionOverrides) {
|
||||
await _service.fingerprintingProtectionOverrides(
|
||||
settings.fingerprintingProtectionOverrides,
|
||||
);
|
||||
}
|
||||
if (previous.value?.enablePdfJs != settings.enablePdfJs) {
|
||||
await ref
|
||||
.read(preferenceFixatorProvider.notifier)
|
||||
.register('pdfjs.disabled', !settings.enablePdfJs);
|
||||
}
|
||||
if (!const DeepCollectionEquality.unordered().equals(
|
||||
previous.value?.locales,
|
||||
settings.locales,
|
||||
)) {
|
||||
await ref
|
||||
.read(preferenceFixatorProvider.notifier)
|
||||
.register(
|
||||
'intl.accept_languages',
|
||||
settings.locales.join(','),
|
||||
);
|
||||
}
|
||||
// Web Content Settings
|
||||
if (previous.value?.webFontsEnabled != settings.webFontsEnabled) {
|
||||
await _service.webFontsEnabled(settings.webFontsEnabled);
|
||||
}
|
||||
if (previous.value?.automaticFontSizeAdjustment !=
|
||||
settings.automaticFontSizeAdjustment) {
|
||||
await _service.automaticFontSizeAdjustment(
|
||||
settings.automaticFontSizeAdjustment,
|
||||
);
|
||||
}
|
||||
if (previous.value?.fontSizeFactor != settings.fontSizeFactor) {
|
||||
await _service.fontSizeFactor(settings.fontSizeFactor);
|
||||
}
|
||||
if (previous.value?.fontInflationEnabled !=
|
||||
settings.fontInflationEnabled) {
|
||||
await _service.fontInflationEnabled(
|
||||
settings.fontInflationEnabled,
|
||||
);
|
||||
}
|
||||
if (previous.value?.inputAutoZoomEnabled !=
|
||||
settings.inputAutoZoomEnabled) {
|
||||
await _service.inputAutoZoomEnabled(
|
||||
settings.inputAutoZoomEnabled,
|
||||
);
|
||||
}
|
||||
// LNA Settings
|
||||
if (previous.value?.lnaBlocking != settings.lnaBlocking) {
|
||||
await _service.lnaBlocking(settings.lnaBlocking);
|
||||
}
|
||||
if (previous.value?.lnaBlockTrackers != settings.lnaBlockTrackers) {
|
||||
await _service.lnaBlockTrackers(settings.lnaBlockTrackers);
|
||||
}
|
||||
if (previous.value?.lnaEnabled != settings.lnaEnabled) {
|
||||
await _service.lnaEnabled(settings.lnaEnabled);
|
||||
}
|
||||
} else {
|
||||
await _service.setDefaultSettings(settings);
|
||||
await ref
|
||||
.read(startupPreferenceEnforcementServiceProvider.notifier)
|
||||
.apply();
|
||||
await ref
|
||||
.read(preferenceFixatorProvider.notifier)
|
||||
.register('pdfjs.disabled', !settings.enablePdfJs);
|
||||
await ref
|
||||
.read(preferenceFixatorProvider.notifier)
|
||||
.register('intl.accept_languages', settings.locales.join(','));
|
||||
|
||||
// Initialize unsigned extensions fixator from Gecko pref
|
||||
await ref.read(allowUnsignedExtensionsProvider.future);
|
||||
|
||||
initialSettingsSent = true;
|
||||
}
|
||||
}
|
||||
},
|
||||
onError: (error, stackTrace) {
|
||||
logger.e(
|
||||
'Error listening to engineSettingsRepositoryProvider',
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'engine_settings_replication.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(EngineSettingsReplicationService)
|
||||
final engineSettingsReplicationServiceProvider =
|
||||
EngineSettingsReplicationServiceProvider._();
|
||||
|
||||
final class EngineSettingsReplicationServiceProvider
|
||||
extends $NotifierProvider<EngineSettingsReplicationService, void> {
|
||||
EngineSettingsReplicationServiceProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'engineSettingsReplicationServiceProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$engineSettingsReplicationServiceHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
EngineSettingsReplicationService create() =>
|
||||
EngineSettingsReplicationService();
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(void value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<void>(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$engineSettingsReplicationServiceHash() =>
|
||||
r'81443c37d18ad82f0694cd0e1115ccdf8a0f4c06';
|
||||
|
||||
abstract class _$EngineSettingsReplicationService extends $Notifier<void> {
|
||||
void build();
|
||||
@$mustCallSuper
|
||||
@override
|
||||
void runBuild() {
|
||||
final ref = this.ref as $Ref<void, void>;
|
||||
final element =
|
||||
ref.element
|
||||
as $ClassProviderElement<
|
||||
AnyNotifier<void, void>,
|
||||
void,
|
||||
Object?,
|
||||
Object?
|
||||
>;
|
||||
element.handleCreate(ref, build);
|
||||
}
|
||||
}
|
||||
+255
@@ -0,0 +1,255 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:fast_equatable/fast_equatable.dart';
|
||||
import 'package:nullability/nullability.dart';
|
||||
import 'package:riverpod/riverpod.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:synchronized/synchronized.dart';
|
||||
import 'package:weblibre/core/logger.dart';
|
||||
import 'package:weblibre/features/geckoview/features/tabs/data/providers.dart';
|
||||
import 'package:weblibre/features/geckoview/features/tabs/domain/providers.dart';
|
||||
import 'package:weblibre/features/geckoview/features/tabs/domain/repositories/container.dart';
|
||||
import 'package:weblibre/features/tor/domain/repositories/tor_proxy.dart';
|
||||
import 'package:weblibre/features/tor/domain/services/tor_proxy.dart';
|
||||
import 'package:weblibre/features/user/data/models/tor_settings.dart';
|
||||
import 'package:weblibre/features/user/domain/repositories/tor_settings.dart';
|
||||
|
||||
part 'proxy_settings_replication.g.dart';
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
class ProxySettingsReplication extends _$ProxySettingsReplication {
|
||||
var _proxiedIsolationContexts = <String>{};
|
||||
|
||||
final _recomputeLock = Lock();
|
||||
|
||||
Future<void> _queueIsolatedProxyAliasesRecompute() async {
|
||||
if (_recomputeLock.inLock) {
|
||||
return;
|
||||
}
|
||||
|
||||
await _recomputeLock.synchronized(() async {
|
||||
try {
|
||||
await _recomputeIsolatedProxyAliases();
|
||||
} catch (error, stackTrace) {
|
||||
logger.e(
|
||||
'Error recomputing isolated proxy aliases',
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _recomputeIsolatedProxyAliases() async {
|
||||
final db = ref.read(tabDatabaseProvider);
|
||||
|
||||
final contextContainerMap = <String, Set<String>>{};
|
||||
final pairs = await db.tabDao.isolatedContextContainerPairs().get();
|
||||
|
||||
for (final pair in pairs) {
|
||||
final isolationContextId = pair.isolationContextId;
|
||||
final containerId = pair.containerId;
|
||||
|
||||
if (isolationContextId == null || containerId == null) continue;
|
||||
|
||||
contextContainerMap
|
||||
.putIfAbsent(isolationContextId, () => <String>{})
|
||||
.add(containerId);
|
||||
}
|
||||
|
||||
final containers = await ref
|
||||
.read(containerRepositoryProvider.notifier)
|
||||
.getAllContainersWithCount();
|
||||
|
||||
// Build set of container IDs that have useProxy enabled.
|
||||
final proxiedContainerIds = <String>{
|
||||
for (final c in containers)
|
||||
if (c.metadata.useProxy) c.id,
|
||||
};
|
||||
|
||||
// Compute which isolation contexts need proxy aliases.
|
||||
// A context needs an alias if ANY of its associated containers
|
||||
// has useProxy enabled.
|
||||
final newProxied = <String>{
|
||||
for (final entry in contextContainerMap.entries)
|
||||
if (entry.value.any(proxiedContainerIds.contains)) entry.key,
|
||||
};
|
||||
|
||||
// Remove aliases that are no longer needed.
|
||||
final toRemove = _proxiedIsolationContexts.difference(newProxied);
|
||||
for (final contextId in toRemove) {
|
||||
await ref
|
||||
.read(torProxyRepositoryProvider.notifier)
|
||||
.removeContainerProxy(contextId);
|
||||
}
|
||||
|
||||
// Add aliases that are newly needed.
|
||||
final toAdd = newProxied.difference(_proxiedIsolationContexts);
|
||||
for (final contextId in toAdd) {
|
||||
await ref
|
||||
.read(torProxyRepositoryProvider.notifier)
|
||||
.addContainerProxy(contextId);
|
||||
}
|
||||
|
||||
_proxiedIsolationContexts = newProxied;
|
||||
}
|
||||
|
||||
@override
|
||||
void build() {
|
||||
ref.listen(
|
||||
fireImmediately: true,
|
||||
torProxyServiceProvider.select((data) => data.value),
|
||||
(previous, next) async {
|
||||
await ref
|
||||
.read(torProxyRepositoryProvider.notifier)
|
||||
.setProxyPort(next?.socksPort ?? -1);
|
||||
},
|
||||
onError: (error, stackTrace) {
|
||||
logger.e(
|
||||
'Error listening to torProxyServiceProvider',
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
ref.listen(
|
||||
fireImmediately: true,
|
||||
watchContainersWithCountProvider.select(
|
||||
(value) => EquatableValue(value.value),
|
||||
),
|
||||
(previous, next) async {
|
||||
if (next.value != null) {
|
||||
for (final container in next.value!) {
|
||||
if (container.metadata.contextualIdentity.isNotEmpty) {
|
||||
if (container.metadata.useProxy) {
|
||||
await ref
|
||||
.read(torProxyRepositoryProvider.notifier)
|
||||
.addContainerProxy(container.metadata.contextualIdentity!);
|
||||
} else {
|
||||
await ref
|
||||
.read(torProxyRepositoryProvider.notifier)
|
||||
.removeContainerProxy(
|
||||
container.metadata.contextualIdentity!,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
onError: (error, stackTrace) {
|
||||
logger.e(
|
||||
'Error listening to containersWithCountProvider',
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
ref.listen(
|
||||
fireImmediately: true,
|
||||
torSettingsWithDefaultsProvider.select(
|
||||
(value) => value.proxyPrivateTabsTor,
|
||||
),
|
||||
(previous, next) async {
|
||||
if (next) {
|
||||
await ref
|
||||
.read(torProxyRepositoryProvider.notifier)
|
||||
.addContainerProxy('private');
|
||||
} else {
|
||||
await ref
|
||||
.read(torProxyRepositoryProvider.notifier)
|
||||
.removeContainerProxy('private');
|
||||
}
|
||||
},
|
||||
onError: (error, stackTrace) {
|
||||
logger.e(
|
||||
'Error listening to generalSettingsRepositoryProvider',
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
ref.listen(
|
||||
fireImmediately: true,
|
||||
torSettingsWithDefaultsProvider.select(
|
||||
(value) => value.proxyRegularTabsMode,
|
||||
),
|
||||
(previous, next) async {
|
||||
switch (next) {
|
||||
case TorRegularTabProxyMode.container:
|
||||
await ref
|
||||
.read(torProxyRepositoryProvider.notifier)
|
||||
.removeContainerProxy('general');
|
||||
case TorRegularTabProxyMode.all:
|
||||
await ref
|
||||
.read(torProxyRepositoryProvider.notifier)
|
||||
.addContainerProxy('general');
|
||||
}
|
||||
},
|
||||
onError: (error, stackTrace) {
|
||||
logger.e(
|
||||
'Error listening to generalSettingsRepositoryProvider',
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
ref.listen(watchAllAssignedSitesProvider, (previous, next) async {
|
||||
if (next.hasValue) {
|
||||
await ref
|
||||
.read(torProxyRepositoryProvider.notifier)
|
||||
.setSiteAssignments(next.requireValue);
|
||||
}
|
||||
});
|
||||
|
||||
ref.listen(
|
||||
fireImmediately: true,
|
||||
watchIsolatedContextContainerMapProvider.select(
|
||||
(value) => EquatableValue(value.value),
|
||||
),
|
||||
(previous, next) => _queueIsolatedProxyAliasesRecompute(),
|
||||
onError: (error, stackTrace) {
|
||||
logger.e(
|
||||
'Error listening to isolated context proxy aliases',
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
ref.listen(
|
||||
fireImmediately: true,
|
||||
watchContainersWithCountProvider.select(
|
||||
(value) => EquatableValue(value.value),
|
||||
),
|
||||
(previous, next) => _queueIsolatedProxyAliasesRecompute(),
|
||||
onError: (error, stackTrace) {
|
||||
logger.e(
|
||||
'Error listening to container proxy changes for isolated aliases',
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'proxy_settings_replication.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(ProxySettingsReplication)
|
||||
final proxySettingsReplicationProvider = ProxySettingsReplicationProvider._();
|
||||
|
||||
final class ProxySettingsReplicationProvider
|
||||
extends $NotifierProvider<ProxySettingsReplication, void> {
|
||||
ProxySettingsReplicationProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'proxySettingsReplicationProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$proxySettingsReplicationHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
ProxySettingsReplication create() => ProxySettingsReplication();
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(void value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<void>(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$proxySettingsReplicationHash() =>
|
||||
r'7f47a561441cc2d594e9380d62dcc31f4c1059d3';
|
||||
|
||||
abstract class _$ProxySettingsReplication extends $Notifier<void> {
|
||||
void build();
|
||||
@$mustCallSuper
|
||||
@override
|
||||
void runBuild() {
|
||||
final ref = this.ref as $Ref<void, void>;
|
||||
final element =
|
||||
ref.element
|
||||
as $ClassProviderElement<
|
||||
AnyNotifier<void, void>,
|
||||
void,
|
||||
Object?,
|
||||
Object?
|
||||
>;
|
||||
element.handleCreate(ref, build);
|
||||
}
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import 'package:fast_equatable/fast_equatable.dart';
|
||||
import 'package:lexo_rank/lexo_rank.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/features/contextual_toolbar/data/repositories/contextual_toolbar_config_repository.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/features/contextual_toolbar/domain/entities/toolbar_button_spec.dart';
|
||||
import 'package:weblibre/features/user/data/database/definitions.drift.dart'
|
||||
show ToolbarButtonConfig;
|
||||
|
||||
part 'toolbar_button_configs.g.dart';
|
||||
|
||||
List<ToolbarButtonConfig> _buildDefaultToolbarButtonConfigs() {
|
||||
String? lastKey;
|
||||
|
||||
return toolbarButtonSpecs.map((spec) {
|
||||
final key = lastKey == null
|
||||
? LexoRank.middle().value
|
||||
: LexoRank.parse(lastKey!).genNext().value;
|
||||
|
||||
lastKey = key;
|
||||
|
||||
return ToolbarButtonConfig(
|
||||
buttonId: spec.id.name,
|
||||
orderKey: key,
|
||||
isVisible: spec.defaultVisible,
|
||||
fallbackId: spec.defaultFallback?.name,
|
||||
);
|
||||
}).toList();
|
||||
}
|
||||
|
||||
final defaultToolbarButtonConfigs = EquatableValue(
|
||||
_buildDefaultToolbarButtonConfigs(),
|
||||
);
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
Stream<List<ToolbarButtonConfig>> toolbarButtonConfigs(Ref ref) async* {
|
||||
final repository = ref.watch(contextualToolbarConfigRepositoryProvider);
|
||||
await repository.seedMissingDefaults();
|
||||
yield* repository.watchAll();
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
EquatableValue<List<ToolbarButtonConfig>> effectiveToolbarButtonConfigs(
|
||||
Ref ref,
|
||||
) {
|
||||
final configsAsync = ref.watch(toolbarButtonConfigsProvider);
|
||||
|
||||
return configsAsync.when(
|
||||
data: (configs) {
|
||||
final filtered = configs
|
||||
.where((config) => knownToolbarButtonIds.contains(config.buttonId))
|
||||
.toList();
|
||||
|
||||
if (filtered.isEmpty) {
|
||||
return defaultToolbarButtonConfigs;
|
||||
}
|
||||
|
||||
return EquatableValue(filtered);
|
||||
},
|
||||
loading: () => defaultToolbarButtonConfigs,
|
||||
error: (_, _) => defaultToolbarButtonConfigs,
|
||||
);
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'toolbar_button_configs.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(toolbarButtonConfigs)
|
||||
final toolbarButtonConfigsProvider = ToolbarButtonConfigsProvider._();
|
||||
|
||||
final class ToolbarButtonConfigsProvider
|
||||
extends
|
||||
$FunctionalProvider<
|
||||
AsyncValue<List<ToolbarButtonConfig>>,
|
||||
List<ToolbarButtonConfig>,
|
||||
Stream<List<ToolbarButtonConfig>>
|
||||
>
|
||||
with
|
||||
$FutureModifier<List<ToolbarButtonConfig>>,
|
||||
$StreamProvider<List<ToolbarButtonConfig>> {
|
||||
ToolbarButtonConfigsProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'toolbarButtonConfigsProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$toolbarButtonConfigsHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$StreamProviderElement<List<ToolbarButtonConfig>> $createElement(
|
||||
$ProviderPointer pointer,
|
||||
) => $StreamProviderElement(pointer);
|
||||
|
||||
@override
|
||||
Stream<List<ToolbarButtonConfig>> create(Ref ref) {
|
||||
return toolbarButtonConfigs(ref);
|
||||
}
|
||||
}
|
||||
|
||||
String _$toolbarButtonConfigsHash() =>
|
||||
r'02f79c2087a3a5413fe879405c05f4a4d1eaffeb';
|
||||
|
||||
@ProviderFor(effectiveToolbarButtonConfigs)
|
||||
final effectiveToolbarButtonConfigsProvider =
|
||||
EffectiveToolbarButtonConfigsProvider._();
|
||||
|
||||
final class EffectiveToolbarButtonConfigsProvider
|
||||
extends
|
||||
$FunctionalProvider<
|
||||
EquatableValue<List<ToolbarButtonConfig>>,
|
||||
EquatableValue<List<ToolbarButtonConfig>>,
|
||||
EquatableValue<List<ToolbarButtonConfig>>
|
||||
>
|
||||
with $Provider<EquatableValue<List<ToolbarButtonConfig>>> {
|
||||
EffectiveToolbarButtonConfigsProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'effectiveToolbarButtonConfigsProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$effectiveToolbarButtonConfigsHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$ProviderElement<EquatableValue<List<ToolbarButtonConfig>>> $createElement(
|
||||
$ProviderPointer pointer,
|
||||
) => $ProviderElement(pointer);
|
||||
|
||||
@override
|
||||
EquatableValue<List<ToolbarButtonConfig>> create(Ref ref) {
|
||||
return effectiveToolbarButtonConfigs(ref);
|
||||
}
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(EquatableValue<List<ToolbarButtonConfig>> value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride:
|
||||
$SyncValueProvider<EquatableValue<List<ToolbarButtonConfig>>>(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$effectiveToolbarButtonConfigsHash() =>
|
||||
r'dd876160f586c64237a42a29eb63cb119f962b02';
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/features/contextual_toolbar/domain/entities/toolbar_button_spec.dart';
|
||||
import 'package:weblibre/features/user/data/database/daos/toolbar_button_config.dart';
|
||||
import 'package:weblibre/features/user/data/database/definitions.drift.dart'
|
||||
show ToolbarButtonConfig;
|
||||
import 'package:weblibre/features/user/data/providers.dart';
|
||||
|
||||
part 'contextual_toolbar_config_repository.g.dart';
|
||||
|
||||
class ContextualToolbarConfigRepository {
|
||||
ContextualToolbarConfigRepository(this._dao);
|
||||
|
||||
final ToolbarButtonConfigDao _dao;
|
||||
|
||||
Stream<List<ToolbarButtonConfig>> watchAll() => _dao.watchAll();
|
||||
|
||||
Future<void> replaceAll(List<ToolbarButtonConfig> configs) {
|
||||
return _dao.replaceAll(configs);
|
||||
}
|
||||
|
||||
Future<void> assignOrderKey(String buttonId, {required String orderKey}) {
|
||||
return _dao.assignOrderKey(buttonId, orderKey: orderKey);
|
||||
}
|
||||
|
||||
Future<void> assignVisibility(String buttonId, {required bool visible}) {
|
||||
return _dao.assignVisibility(buttonId, visible: visible);
|
||||
}
|
||||
|
||||
Future<void> assignFallback(String buttonId, String? fallbackId) {
|
||||
return _dao.assignFallback(buttonId, fallbackId);
|
||||
}
|
||||
|
||||
Future<String> generateLeadingOrderKey() {
|
||||
return _dao.generateLeadingOrderKey().getSingle();
|
||||
}
|
||||
|
||||
Future<String> generateTrailingOrderKey() {
|
||||
return _dao.generateTrailingOrderKey().getSingle();
|
||||
}
|
||||
|
||||
Future<String?> generateOrderKeyAfterButtonId(String buttonId) {
|
||||
return _dao.generateOrderKeyAfterButtonId(buttonId).getSingleOrNull();
|
||||
}
|
||||
|
||||
Future<String> generateOrderKeyBeforeButtonId(String buttonId) {
|
||||
return _dao.generateOrderKeyBeforeButtonId(buttonId).getSingle();
|
||||
}
|
||||
|
||||
Future<void> seedMissingDefaults() {
|
||||
return _dao.seedMissing(
|
||||
toolbarButtonSpecs
|
||||
.map(
|
||||
(spec) => (
|
||||
buttonId: spec.id.name,
|
||||
defaultVisible: spec.defaultVisible,
|
||||
defaultFallback: spec.defaultFallback?.name,
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
ContextualToolbarConfigRepository contextualToolbarConfigRepository(Ref ref) {
|
||||
return ContextualToolbarConfigRepository(
|
||||
ref.watch(userDatabaseProvider).toolbarButtonConfigDao,
|
||||
);
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'contextual_toolbar_config_repository.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(contextualToolbarConfigRepository)
|
||||
final contextualToolbarConfigRepositoryProvider =
|
||||
ContextualToolbarConfigRepositoryProvider._();
|
||||
|
||||
final class ContextualToolbarConfigRepositoryProvider
|
||||
extends
|
||||
$FunctionalProvider<
|
||||
ContextualToolbarConfigRepository,
|
||||
ContextualToolbarConfigRepository,
|
||||
ContextualToolbarConfigRepository
|
||||
>
|
||||
with $Provider<ContextualToolbarConfigRepository> {
|
||||
ContextualToolbarConfigRepositoryProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'contextualToolbarConfigRepositoryProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() =>
|
||||
_$contextualToolbarConfigRepositoryHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$ProviderElement<ContextualToolbarConfigRepository> $createElement(
|
||||
$ProviderPointer pointer,
|
||||
) => $ProviderElement(pointer);
|
||||
|
||||
@override
|
||||
ContextualToolbarConfigRepository create(Ref ref) {
|
||||
return contextualToolbarConfigRepository(ref);
|
||||
}
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(ContextualToolbarConfigRepository value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<ContextualToolbarConfigRepository>(
|
||||
value,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$contextualToolbarConfigRepositoryHash() =>
|
||||
r'96bb0c00019e076ef65d3e901ba850de0fccbb1b';
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
enum ToolbarButtonId {
|
||||
back,
|
||||
forward,
|
||||
bookmarks,
|
||||
bookmarkToggle,
|
||||
share,
|
||||
addTab,
|
||||
tabsCount,
|
||||
navigationMenu,
|
||||
reload,
|
||||
readerMode,
|
||||
desktop,
|
||||
translation,
|
||||
findInPage,
|
||||
closeTab,
|
||||
inputUrl,
|
||||
duplicateTab,
|
||||
increaseFont,
|
||||
decreaseFont,
|
||||
moveToBackground,
|
||||
pageUp,
|
||||
pageDown,
|
||||
font,
|
||||
extensionShortcut,
|
||||
quit,
|
||||
}
|
||||
+198
@@ -0,0 +1,198 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import 'package:weblibre/features/geckoview/features/browser/features/contextual_toolbar/domain/entities/toolbar_button_id.dart';
|
||||
|
||||
class ToolbarButtonSpec {
|
||||
final ToolbarButtonId id;
|
||||
final bool defaultVisible;
|
||||
final ToolbarButtonId? defaultFallback;
|
||||
final bool canBeFallbackTarget;
|
||||
|
||||
const ToolbarButtonSpec({
|
||||
required this.id,
|
||||
required this.defaultVisible,
|
||||
this.defaultFallback,
|
||||
this.canBeFallbackTarget = true,
|
||||
});
|
||||
}
|
||||
|
||||
const backToolbarButtonSpec = ToolbarButtonSpec(
|
||||
id: ToolbarButtonId.back,
|
||||
defaultVisible: true,
|
||||
defaultFallback: ToolbarButtonId.bookmarks,
|
||||
);
|
||||
|
||||
const forwardToolbarButtonSpec = ToolbarButtonSpec(
|
||||
id: ToolbarButtonId.forward,
|
||||
defaultVisible: true,
|
||||
defaultFallback: ToolbarButtonId.share,
|
||||
);
|
||||
|
||||
const bookmarksToolbarButtonSpec = ToolbarButtonSpec(
|
||||
id: ToolbarButtonId.bookmarks,
|
||||
defaultVisible: false,
|
||||
);
|
||||
|
||||
const bookmarkToggleToolbarButtonSpec = ToolbarButtonSpec(
|
||||
id: ToolbarButtonId.bookmarkToggle,
|
||||
defaultVisible: false,
|
||||
);
|
||||
|
||||
const shareToolbarButtonSpec = ToolbarButtonSpec(
|
||||
id: ToolbarButtonId.share,
|
||||
defaultVisible: false,
|
||||
);
|
||||
|
||||
const addTabToolbarButtonSpec = ToolbarButtonSpec(
|
||||
id: ToolbarButtonId.addTab,
|
||||
defaultVisible: true,
|
||||
);
|
||||
|
||||
const tabsCountToolbarButtonSpec = ToolbarButtonSpec(
|
||||
id: ToolbarButtonId.tabsCount,
|
||||
defaultVisible: true,
|
||||
);
|
||||
|
||||
const navigationMenuToolbarButtonSpec = ToolbarButtonSpec(
|
||||
id: ToolbarButtonId.navigationMenu,
|
||||
defaultVisible: true,
|
||||
);
|
||||
|
||||
const reloadToolbarButtonSpec = ToolbarButtonSpec(
|
||||
id: ToolbarButtonId.reload,
|
||||
defaultVisible: false,
|
||||
);
|
||||
|
||||
const readerModeToolbarButtonSpec = ToolbarButtonSpec(
|
||||
id: ToolbarButtonId.readerMode,
|
||||
defaultVisible: false,
|
||||
canBeFallbackTarget: false,
|
||||
);
|
||||
|
||||
const desktopToolbarButtonSpec = ToolbarButtonSpec(
|
||||
id: ToolbarButtonId.desktop,
|
||||
defaultVisible: false,
|
||||
);
|
||||
|
||||
const translationToolbarButtonSpec = ToolbarButtonSpec(
|
||||
id: ToolbarButtonId.translation,
|
||||
defaultVisible: false,
|
||||
canBeFallbackTarget: false,
|
||||
);
|
||||
|
||||
const findInPageToolbarButtonSpec = ToolbarButtonSpec(
|
||||
id: ToolbarButtonId.findInPage,
|
||||
defaultVisible: false,
|
||||
);
|
||||
|
||||
const closeTabToolbarButtonSpec = ToolbarButtonSpec(
|
||||
id: ToolbarButtonId.closeTab,
|
||||
defaultVisible: false,
|
||||
canBeFallbackTarget: false,
|
||||
);
|
||||
|
||||
const inputUrlToolbarButtonSpec = ToolbarButtonSpec(
|
||||
id: ToolbarButtonId.inputUrl,
|
||||
defaultVisible: false,
|
||||
);
|
||||
|
||||
const duplicateTabToolbarButtonSpec = ToolbarButtonSpec(
|
||||
id: ToolbarButtonId.duplicateTab,
|
||||
defaultVisible: false,
|
||||
);
|
||||
|
||||
const increaseFontToolbarButtonSpec = ToolbarButtonSpec(
|
||||
id: ToolbarButtonId.increaseFont,
|
||||
defaultVisible: false,
|
||||
);
|
||||
|
||||
const decreaseFontToolbarButtonSpec = ToolbarButtonSpec(
|
||||
id: ToolbarButtonId.decreaseFont,
|
||||
defaultVisible: false,
|
||||
);
|
||||
|
||||
const moveToBackgroundToolbarButtonSpec = ToolbarButtonSpec(
|
||||
id: ToolbarButtonId.moveToBackground,
|
||||
defaultVisible: false,
|
||||
canBeFallbackTarget: false,
|
||||
);
|
||||
|
||||
const pageUpToolbarButtonSpec = ToolbarButtonSpec(
|
||||
id: ToolbarButtonId.pageUp,
|
||||
defaultVisible: false,
|
||||
canBeFallbackTarget: false,
|
||||
);
|
||||
|
||||
const pageDownToolbarButtonSpec = ToolbarButtonSpec(
|
||||
id: ToolbarButtonId.pageDown,
|
||||
defaultVisible: false,
|
||||
canBeFallbackTarget: false,
|
||||
);
|
||||
|
||||
const fontToolbarButtonSpec = ToolbarButtonSpec(
|
||||
id: ToolbarButtonId.font,
|
||||
defaultVisible: false,
|
||||
);
|
||||
|
||||
const extensionShortcutToolbarButtonSpec = ToolbarButtonSpec(
|
||||
id: ToolbarButtonId.extensionShortcut,
|
||||
defaultVisible: false,
|
||||
canBeFallbackTarget: false,
|
||||
);
|
||||
|
||||
const quitToolbarButtonSpec = ToolbarButtonSpec(
|
||||
id: ToolbarButtonId.quit,
|
||||
defaultVisible: false,
|
||||
canBeFallbackTarget: false,
|
||||
);
|
||||
|
||||
const toolbarButtonSpecs = [
|
||||
backToolbarButtonSpec,
|
||||
forwardToolbarButtonSpec,
|
||||
bookmarksToolbarButtonSpec,
|
||||
bookmarkToggleToolbarButtonSpec,
|
||||
shareToolbarButtonSpec,
|
||||
addTabToolbarButtonSpec,
|
||||
tabsCountToolbarButtonSpec,
|
||||
navigationMenuToolbarButtonSpec,
|
||||
reloadToolbarButtonSpec,
|
||||
readerModeToolbarButtonSpec,
|
||||
desktopToolbarButtonSpec,
|
||||
translationToolbarButtonSpec,
|
||||
findInPageToolbarButtonSpec,
|
||||
closeTabToolbarButtonSpec,
|
||||
inputUrlToolbarButtonSpec,
|
||||
duplicateTabToolbarButtonSpec,
|
||||
increaseFontToolbarButtonSpec,
|
||||
decreaseFontToolbarButtonSpec,
|
||||
moveToBackgroundToolbarButtonSpec,
|
||||
pageUpToolbarButtonSpec,
|
||||
pageDownToolbarButtonSpec,
|
||||
fontToolbarButtonSpec,
|
||||
extensionShortcutToolbarButtonSpec,
|
||||
quitToolbarButtonSpec,
|
||||
];
|
||||
|
||||
final Map<String, ToolbarButtonSpec> toolbarButtonSpecsById = {
|
||||
for (final spec in toolbarButtonSpecs) spec.id.name: spec,
|
||||
};
|
||||
|
||||
final Set<String> knownToolbarButtonIds = toolbarButtonSpecsById.keys.toSet();
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:fast_equatable/fast_equatable.dart';
|
||||
|
||||
sealed class ToolbarFallbackChoice with FastEquatable {
|
||||
ToolbarFallbackChoice();
|
||||
|
||||
factory ToolbarFallbackChoice.fromStored(String? storedFallbackId) {
|
||||
if (storedFallbackId != null) {
|
||||
return ToolbarFallbackButton(buttonId: storedFallbackId);
|
||||
}
|
||||
return ToolbarFallbackNone();
|
||||
}
|
||||
|
||||
String? resolveRuntimeFallbackId();
|
||||
|
||||
String? toStoredFallbackId() => resolveRuntimeFallbackId();
|
||||
}
|
||||
|
||||
class ToolbarFallbackButton extends ToolbarFallbackChoice {
|
||||
final String buttonId;
|
||||
|
||||
ToolbarFallbackButton({required this.buttonId});
|
||||
|
||||
@override
|
||||
List<Object?> get hashParameters => [buttonId];
|
||||
|
||||
@override
|
||||
String resolveRuntimeFallbackId() => buttonId;
|
||||
}
|
||||
|
||||
class ToolbarFallbackNone extends ToolbarFallbackChoice {
|
||||
ToolbarFallbackNone();
|
||||
|
||||
@override
|
||||
List<Object?> get hashParameters => [null];
|
||||
|
||||
@override
|
||||
String? resolveRuntimeFallbackId() => null;
|
||||
}
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import 'package:weblibre/features/geckoview/features/browser/features/contextual_toolbar/domain/entities/toolbar_fallback_choice.dart';
|
||||
import 'package:weblibre/features/user/data/database/definitions.drift.dart';
|
||||
|
||||
class ContextualToolbarButtonResolution {
|
||||
const ContextualToolbarButtonResolution({
|
||||
required this.buttonId,
|
||||
required this.isEnabled,
|
||||
});
|
||||
|
||||
final String buttonId;
|
||||
final bool isEnabled;
|
||||
}
|
||||
|
||||
List<ContextualToolbarButtonResolution> resolveVisibleContextualToolbarButtons({
|
||||
required List<ToolbarButtonConfig> configs,
|
||||
required Set<String> knownButtonIds,
|
||||
required bool Function(String buttonId) isPrimaryAvailable,
|
||||
}) {
|
||||
final configById = {for (final config in configs) config.buttonId: config};
|
||||
final resolvedButtons = <ContextualToolbarButtonResolution>[];
|
||||
final seenIds = <String>{};
|
||||
|
||||
for (final config in configs.where((config) => config.isVisible)) {
|
||||
final resolvedButton = resolveContextualToolbarButton(
|
||||
config: config,
|
||||
configById: configById,
|
||||
knownButtonIds: knownButtonIds,
|
||||
isPrimaryAvailable: isPrimaryAvailable,
|
||||
);
|
||||
if (resolvedButton == null) {
|
||||
continue;
|
||||
}
|
||||
if (seenIds.add(resolvedButton.buttonId)) {
|
||||
resolvedButtons.add(resolvedButton);
|
||||
}
|
||||
}
|
||||
|
||||
return resolvedButtons;
|
||||
}
|
||||
|
||||
ContextualToolbarButtonResolution? resolveContextualToolbarButton({
|
||||
required ToolbarButtonConfig config,
|
||||
required Map<String, ToolbarButtonConfig> configById,
|
||||
required Set<String> knownButtonIds,
|
||||
required bool Function(String buttonId) isPrimaryAvailable,
|
||||
Set<String> visited = const {},
|
||||
}) {
|
||||
if (visited.contains(config.buttonId)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!knownButtonIds.contains(config.buttonId)) {
|
||||
return ContextualToolbarButtonResolution(
|
||||
buttonId: config.buttonId,
|
||||
isEnabled: true,
|
||||
);
|
||||
}
|
||||
|
||||
if (isPrimaryAvailable(config.buttonId)) {
|
||||
return ContextualToolbarButtonResolution(
|
||||
buttonId: config.buttonId,
|
||||
isEnabled: true,
|
||||
);
|
||||
}
|
||||
|
||||
final fallbackId = ToolbarFallbackChoice.fromStored(
|
||||
config.fallbackId,
|
||||
).resolveRuntimeFallbackId();
|
||||
if (fallbackId == null) {
|
||||
return ContextualToolbarButtonResolution(
|
||||
buttonId: config.buttonId,
|
||||
isEnabled: false,
|
||||
);
|
||||
}
|
||||
|
||||
final fallbackConfig = configById[fallbackId];
|
||||
if (fallbackConfig == null) {
|
||||
return knownButtonIds.contains(fallbackId)
|
||||
? ContextualToolbarButtonResolution(
|
||||
buttonId: fallbackId,
|
||||
isEnabled: true,
|
||||
)
|
||||
: ContextualToolbarButtonResolution(
|
||||
buttonId: config.buttonId,
|
||||
isEnabled: false,
|
||||
);
|
||||
}
|
||||
|
||||
return resolveContextualToolbarButton(
|
||||
config: fallbackConfig,
|
||||
configById: configById,
|
||||
knownButtonIds: knownButtonIds,
|
||||
isPrimaryAvailable: isPrimaryAvailable,
|
||||
visited: {...visited, config.buttonId},
|
||||
);
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:fast_equatable/fast_equatable.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/entities/states/tab.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/domain/entities/sheet.dart';
|
||||
|
||||
class ContextualToolbarScope with FastEquatable {
|
||||
final String? selectedTabId;
|
||||
final Sheet? displayedSheet;
|
||||
final TabState? tabState;
|
||||
final bool isPreview;
|
||||
|
||||
ContextualToolbarScope({
|
||||
required this.selectedTabId,
|
||||
required this.displayedSheet,
|
||||
required this.tabState,
|
||||
required this.isPreview,
|
||||
});
|
||||
|
||||
@override
|
||||
List<Object?> get hashParameters => [
|
||||
selectedTabId,
|
||||
displayedSheet,
|
||||
tabState,
|
||||
isPreview,
|
||||
];
|
||||
}
|
||||
+997
@@ -0,0 +1,997 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:fast_equatable/fast_equatable.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:flutter_mozilla_components/flutter_mozilla_components.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:weblibre/core/routing/routes.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/entities/states/readerable.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers/desktop_mode.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers/tab_session.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers/tab_state.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers/web_extensions_state.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/repositories/tab.dart';
|
||||
import 'package:weblibre/features/geckoview/features/bookmarks/domain/repositories/bookmarks.dart';
|
||||
import 'package:weblibre/features/geckoview/features/bookmarks/domain/utils/bookmark_tree_utils.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/domain/entities/font_size_constants.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/features/contextual_toolbar/domain/entities/toolbar_button_spec.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/features/contextual_toolbar/presentation/models/contextual_toolbar_scope.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/features/contextual_toolbar/presentation/widgets/contextual_bar_buttons.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/presentation/utils/tab_close_confirmation.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/presentation/widgets/extension_shortcut_menu.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/presentation/widgets/font_size_bottom_sheet.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/presentation/widgets/navigation_buttons.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/presentation/widgets/tabs_action_button.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/presentation/widgets/translation_bottom_sheet.dart';
|
||||
import 'package:weblibre/features/geckoview/features/find_in_page/presentation/controllers/find_in_page.dart';
|
||||
import 'package:weblibre/features/geckoview/features/readerview/presentation/controllers/readerable.dart';
|
||||
import 'package:weblibre/features/geckoview/features/tabs/data/entities/tab_mode.dart';
|
||||
import 'package:weblibre/features/settings/presentation/controllers/save_settings.dart';
|
||||
import 'package:weblibre/features/user/data/models/engine_settings.dart';
|
||||
import 'package:weblibre/features/user/domain/presentation/dialogs/quit_browser_dialog.dart';
|
||||
import 'package:weblibre/features/user/domain/repositories/engine_settings.dart';
|
||||
import 'package:weblibre/features/user/domain/repositories/general_settings.dart';
|
||||
import 'package:weblibre/utils/exit_app.dart';
|
||||
import 'package:weblibre/utils/move_to_background.dart';
|
||||
import 'package:weblibre/utils/ui_helper.dart' as ui_helper;
|
||||
|
||||
class ToolbarButtonDefinition {
|
||||
final ToolbarButtonSpec spec;
|
||||
final String label;
|
||||
final IconData icon;
|
||||
final bool Function(ContextualToolbarScope scope, WidgetRef ref)?
|
||||
isPrimaryAvailable;
|
||||
final Widget Function(
|
||||
ContextualToolbarScope scope,
|
||||
BuildContext context,
|
||||
WidgetRef ref,
|
||||
)
|
||||
builder;
|
||||
final List<String> longPressActions;
|
||||
|
||||
const ToolbarButtonDefinition({
|
||||
required this.spec,
|
||||
required this.label,
|
||||
required this.icon,
|
||||
this.isPrimaryAvailable,
|
||||
required this.builder,
|
||||
this.longPressActions = const [],
|
||||
});
|
||||
}
|
||||
|
||||
final List<ToolbarButtonDefinition> toolbarButtonRegistry = [
|
||||
ToolbarButtonDefinition(
|
||||
spec: backToolbarButtonSpec,
|
||||
label: 'Back',
|
||||
icon: Icons.arrow_back,
|
||||
isPrimaryAvailable: (scope, ref) =>
|
||||
scope.tabState?.historyState.canGoBack == true ||
|
||||
scope.tabState?.isLoading == true,
|
||||
longPressActions: ['History Menu (Previous pages)'],
|
||||
builder: (scope, context, ref) {
|
||||
if (scope.isPreview) {
|
||||
return NavigateBackButtonView(
|
||||
canGoBack: true,
|
||||
isLoading: false,
|
||||
onPressed: () {},
|
||||
onLongPress: () {},
|
||||
);
|
||||
}
|
||||
return NavigateBackButton(
|
||||
selectedTabId: scope.selectedTabId,
|
||||
isLoading: scope.tabState?.isLoading ?? false,
|
||||
);
|
||||
},
|
||||
),
|
||||
ToolbarButtonDefinition(
|
||||
spec: forwardToolbarButtonSpec,
|
||||
label: 'Forward',
|
||||
icon: Icons.arrow_forward,
|
||||
isPrimaryAvailable: (scope, ref) =>
|
||||
scope.tabState?.historyState.canGoForward == true,
|
||||
longPressActions: ['History Menu (Forward pages)'],
|
||||
builder: (scope, context, ref) {
|
||||
if (scope.isPreview) {
|
||||
return NavigateForwardButtonView(
|
||||
canGoForward: true,
|
||||
onPressed: () {},
|
||||
onLongPress: () {},
|
||||
);
|
||||
}
|
||||
return NavigateForwardButton(selectedTabId: scope.selectedTabId);
|
||||
},
|
||||
),
|
||||
ToolbarButtonDefinition(
|
||||
spec: bookmarksToolbarButtonSpec,
|
||||
label: 'Bookmarks',
|
||||
icon: MdiIcons.bookmarkMultiple,
|
||||
longPressActions: ['Add Bookmark', 'Remove Bookmark'],
|
||||
builder: (scope, context, ref) => _BookmarkToolbarButton(scope: scope),
|
||||
),
|
||||
ToolbarButtonDefinition(
|
||||
spec: bookmarkToggleToolbarButtonSpec,
|
||||
label: 'Bookmark',
|
||||
icon: Icons.bookmark_border,
|
||||
longPressActions: ['Open Bookmarks'],
|
||||
builder: (scope, context, ref) =>
|
||||
_BookmarkToggleToolbarButton(scope: scope),
|
||||
),
|
||||
ToolbarButtonDefinition(
|
||||
spec: shareToolbarButtonSpec,
|
||||
label: 'Share',
|
||||
icon: Icons.share,
|
||||
isPrimaryAvailable: (scope, ref) => scope.selectedTabId != null,
|
||||
builder: (scope, context, ref) => scope.isPreview
|
||||
? ShareMenuButtonView(onPressed: () {})
|
||||
: ShareMenuButton(selectedTabId: scope.selectedTabId),
|
||||
),
|
||||
ToolbarButtonDefinition(
|
||||
spec: addTabToolbarButtonSpec,
|
||||
label: 'New Tab',
|
||||
icon: MdiIcons.tabPlus,
|
||||
longPressActions: [
|
||||
'Add Regular Tab',
|
||||
'Add Child Tab',
|
||||
'Add Private Tab',
|
||||
'Add Isolated Tab',
|
||||
],
|
||||
builder: (scope, context, ref) => scope.isPreview
|
||||
? AddTabButtonView(onPressed: () {}, onLongPress: () {})
|
||||
: const AddTabButton(),
|
||||
),
|
||||
ToolbarButtonDefinition(
|
||||
spec: tabsCountToolbarButtonSpec,
|
||||
label: 'Tabs',
|
||||
icon: MdiIcons.tab,
|
||||
longPressActions: [
|
||||
'Add Regular Tab',
|
||||
'Add Child Tab',
|
||||
'Add Private Tab',
|
||||
'Add Isolated Tab',
|
||||
],
|
||||
builder: (scope, context, ref) => scope.isPreview
|
||||
? TabsCountButtonView(
|
||||
isActive: false,
|
||||
onTap: () {},
|
||||
onLongPress: () {},
|
||||
buttonBuilder: (isActive, onTap, onLongPress) {
|
||||
return TabsActionButtonView(
|
||||
isActive: isActive,
|
||||
tabCountText: '5',
|
||||
onTap: onTap,
|
||||
onLongPress: onLongPress,
|
||||
);
|
||||
},
|
||||
)
|
||||
: TabsCountButton(
|
||||
selectedTabId: scope.selectedTabId,
|
||||
displayedSheet: scope.displayedSheet,
|
||||
showLongPressMenu: false,
|
||||
),
|
||||
),
|
||||
ToolbarButtonDefinition(
|
||||
spec: navigationMenuToolbarButtonSpec,
|
||||
label: 'Menu',
|
||||
icon: Icons.more_vert,
|
||||
builder: (scope, context, ref) => scope.isPreview
|
||||
? NavigationMenuButtonView(onTap: () {})
|
||||
: NavigationMenuButton(selectedTabId: scope.selectedTabId),
|
||||
),
|
||||
ToolbarButtonDefinition(
|
||||
spec: reloadToolbarButtonSpec,
|
||||
label: 'Reload',
|
||||
icon: Icons.refresh,
|
||||
longPressActions: ['Hard Refresh (bypass cache)'],
|
||||
isPrimaryAvailable: (scope, ref) => scope.selectedTabId != null,
|
||||
builder: (scope, context, ref) => _ReloadToolbarButton(scope: scope),
|
||||
),
|
||||
ToolbarButtonDefinition(
|
||||
spec: readerModeToolbarButtonSpec,
|
||||
label: 'Reader Mode',
|
||||
icon: MdiIcons.bookOpenOutline,
|
||||
isPrimaryAvailable: (scope, ref) {
|
||||
final readerableState =
|
||||
scope.tabState?.readerableState ?? ReaderableState.$default();
|
||||
final enableReadability = ref.read(
|
||||
generalSettingsWithDefaultsProvider.select(
|
||||
(value) => value.enableReadability,
|
||||
),
|
||||
);
|
||||
final enforceReadability = ref.read(
|
||||
generalSettingsWithDefaultsProvider.select(
|
||||
(value) => value.enforceReadability,
|
||||
),
|
||||
);
|
||||
return (readerableState.readerable &&
|
||||
(enableReadability || readerableState.active)) ||
|
||||
(enforceReadability && enableReadability);
|
||||
},
|
||||
builder: (scope, context, ref) {
|
||||
if (scope.isPreview) {
|
||||
return IconButton(
|
||||
onPressed: () {},
|
||||
icon: const Icon(MdiIcons.bookOpenOutline),
|
||||
);
|
||||
}
|
||||
return _ReaderModeToolbarButton(selectedTabId: scope.selectedTabId);
|
||||
},
|
||||
),
|
||||
ToolbarButtonDefinition(
|
||||
spec: desktopToolbarButtonSpec,
|
||||
label: 'Desktop Site',
|
||||
icon: Icons.desktop_windows,
|
||||
isPrimaryAvailable: (scope, ref) => scope.selectedTabId != null,
|
||||
builder: (scope, context, ref) {
|
||||
if (scope.isPreview) {
|
||||
return IconButton(
|
||||
onPressed: () {},
|
||||
icon: const Icon(Icons.desktop_windows_outlined),
|
||||
);
|
||||
}
|
||||
return _DesktopModeToolbarButton(selectedTabId: scope.selectedTabId);
|
||||
},
|
||||
),
|
||||
ToolbarButtonDefinition(
|
||||
spec: translationToolbarButtonSpec,
|
||||
label: 'Translate',
|
||||
icon: Icons.translate,
|
||||
longPressActions: ['Show Translation Options'],
|
||||
isPrimaryAvailable: (scope, ref) {
|
||||
if (scope.selectedTabId == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
final engineState = ref.read(translationEngineStateProvider);
|
||||
final readerActive = scope.tabState?.readerableState.active ?? false;
|
||||
return !readerActive && engineState?.isEngineSupported == true;
|
||||
},
|
||||
builder: (scope, context, ref) {
|
||||
if (scope.isPreview) {
|
||||
return IconButton(onPressed: () {}, icon: const Icon(Icons.translate));
|
||||
}
|
||||
return _TranslateToolbarButton(selectedTabId: scope.selectedTabId);
|
||||
},
|
||||
),
|
||||
ToolbarButtonDefinition(
|
||||
spec: findInPageToolbarButtonSpec,
|
||||
label: 'Find in Page',
|
||||
icon: Icons.search,
|
||||
isPrimaryAvailable: (scope, ref) => scope.selectedTabId != null,
|
||||
builder: (scope, context, ref) {
|
||||
return IconButton(
|
||||
onPressed: scope.isPreview
|
||||
? () {}
|
||||
: () {
|
||||
final tabId = scope.selectedTabId;
|
||||
if (tabId != null) {
|
||||
ref.read(findInPageControllerProvider(tabId).notifier).show();
|
||||
}
|
||||
},
|
||||
icon: const Icon(Icons.search),
|
||||
);
|
||||
},
|
||||
),
|
||||
ToolbarButtonDefinition(
|
||||
spec: closeTabToolbarButtonSpec,
|
||||
label: 'Close Tab',
|
||||
icon: MdiIcons.tabMinus,
|
||||
longPressActions: ['Close Others', 'Close from Same Host'],
|
||||
isPrimaryAvailable: (scope, ref) => scope.selectedTabId != null,
|
||||
builder: (scope, context, ref) => _CloseTabToolbarButton(scope: scope),
|
||||
),
|
||||
ToolbarButtonDefinition(
|
||||
spec: inputUrlToolbarButtonSpec,
|
||||
label: 'Address Bar',
|
||||
icon: Icons.edit,
|
||||
builder: (scope, context, ref) {
|
||||
return IconButton(
|
||||
onPressed: scope.isPreview
|
||||
? () {}
|
||||
: () async {
|
||||
final tabState = scope.tabState;
|
||||
if (tabState != null) {
|
||||
final searchText = tabState.url.scheme == 'about'
|
||||
? SearchRoute.emptySearchText
|
||||
: tabState.url.toString();
|
||||
await SearchRoute(
|
||||
tabId: tabState.id,
|
||||
searchText: searchText.isEmpty
|
||||
? SearchRoute.emptySearchText
|
||||
: searchText,
|
||||
tabType: tabState.tabMode.toTabType(),
|
||||
).push(context);
|
||||
} else {
|
||||
await const SearchRoute(
|
||||
tabType: TabType.regular,
|
||||
).push(context);
|
||||
}
|
||||
},
|
||||
icon: const Icon(Icons.edit),
|
||||
);
|
||||
},
|
||||
),
|
||||
ToolbarButtonDefinition(
|
||||
spec: duplicateTabToolbarButtonSpec,
|
||||
label: 'Duplicate Tab',
|
||||
icon: MdiIcons.contentDuplicate,
|
||||
longPressActions: [
|
||||
'Clone as Regular',
|
||||
'Clone as Private',
|
||||
'Clone as Isolated',
|
||||
],
|
||||
isPrimaryAvailable: (scope, ref) => scope.selectedTabId != null,
|
||||
builder: (scope, context, ref) {
|
||||
return scope.isPreview
|
||||
? CloneTabButtonView(onPressed: () {}, onLongPress: () {})
|
||||
: CloneTabButton(selectedTabId: scope.selectedTabId);
|
||||
},
|
||||
),
|
||||
ToolbarButtonDefinition(
|
||||
spec: increaseFontToolbarButtonSpec,
|
||||
label: 'Increase Font',
|
||||
icon: MdiIcons.formatFontSizeIncrease,
|
||||
builder: (scope, context, ref) {
|
||||
return IconButton(
|
||||
onPressed: scope.isPreview
|
||||
? () {}
|
||||
: () => _adjustFontSize(context, ref, increase: true),
|
||||
icon: const Icon(MdiIcons.formatFontSizeIncrease),
|
||||
);
|
||||
},
|
||||
),
|
||||
ToolbarButtonDefinition(
|
||||
spec: decreaseFontToolbarButtonSpec,
|
||||
label: 'Decrease Font',
|
||||
icon: MdiIcons.formatFontSizeDecrease,
|
||||
builder: (scope, context, ref) {
|
||||
return IconButton(
|
||||
onPressed: scope.isPreview
|
||||
? () {}
|
||||
: () => _adjustFontSize(context, ref, increase: false),
|
||||
icon: const Icon(MdiIcons.formatFontSizeDecrease),
|
||||
);
|
||||
},
|
||||
),
|
||||
ToolbarButtonDefinition(
|
||||
spec: moveToBackgroundToolbarButtonSpec,
|
||||
label: 'Background',
|
||||
icon: MdiIcons.arrowCollapseDown,
|
||||
builder: (scope, context, ref) {
|
||||
return IconButton(
|
||||
onPressed: scope.isPreview ? () {} : moveToBackground,
|
||||
icon: const Icon(MdiIcons.arrowCollapseDown),
|
||||
);
|
||||
},
|
||||
),
|
||||
ToolbarButtonDefinition(
|
||||
spec: pageUpToolbarButtonSpec,
|
||||
label: 'Page Up',
|
||||
icon: MdiIcons.chevronDoubleUp,
|
||||
longPressActions: ['Scroll to Top'],
|
||||
isPrimaryAvailable: (scope, ref) => scope.selectedTabId != null,
|
||||
builder: (scope, context, ref) {
|
||||
return IconButton(
|
||||
onPressed: scope.isPreview
|
||||
? () {}
|
||||
: () async {
|
||||
final tabId = scope.selectedTabId;
|
||||
if (tabId != null) {
|
||||
await ref
|
||||
.read(tabSessionProvider(tabId: tabId).notifier)
|
||||
.pageUp();
|
||||
}
|
||||
},
|
||||
onLongPress: scope.isPreview
|
||||
? () {}
|
||||
: () async {
|
||||
final tabId = scope.selectedTabId;
|
||||
if (tabId != null) {
|
||||
await ref
|
||||
.read(tabSessionProvider(tabId: tabId).notifier)
|
||||
.scrollToTop();
|
||||
}
|
||||
},
|
||||
icon: const Icon(MdiIcons.chevronDoubleUp),
|
||||
);
|
||||
},
|
||||
),
|
||||
ToolbarButtonDefinition(
|
||||
spec: pageDownToolbarButtonSpec,
|
||||
label: 'Page Down',
|
||||
icon: MdiIcons.chevronDoubleDown,
|
||||
longPressActions: ['Scroll to Bottom'],
|
||||
isPrimaryAvailable: (scope, ref) => scope.selectedTabId != null,
|
||||
builder: (scope, context, ref) {
|
||||
return IconButton(
|
||||
onPressed: scope.isPreview
|
||||
? () {}
|
||||
: () async {
|
||||
final tabId = scope.selectedTabId;
|
||||
if (tabId != null) {
|
||||
await ref
|
||||
.read(tabSessionProvider(tabId: tabId).notifier)
|
||||
.pageDown();
|
||||
}
|
||||
},
|
||||
onLongPress: scope.isPreview
|
||||
? () {}
|
||||
: () async {
|
||||
final tabId = scope.selectedTabId;
|
||||
if (tabId != null) {
|
||||
await ref
|
||||
.read(tabSessionProvider(tabId: tabId).notifier)
|
||||
.scrollToBottom();
|
||||
}
|
||||
},
|
||||
icon: const Icon(MdiIcons.chevronDoubleDown),
|
||||
);
|
||||
},
|
||||
),
|
||||
ToolbarButtonDefinition(
|
||||
spec: fontToolbarButtonSpec,
|
||||
label: 'Text Size',
|
||||
icon: MdiIcons.formatSize,
|
||||
builder: (scope, context, ref) {
|
||||
if (scope.isPreview) {
|
||||
return IconButton(
|
||||
onPressed: () {},
|
||||
icon: const Icon(MdiIcons.formatSize),
|
||||
);
|
||||
}
|
||||
return _FontToolbarButton(selectedTabId: scope.selectedTabId);
|
||||
},
|
||||
),
|
||||
ToolbarButtonDefinition(
|
||||
spec: extensionShortcutToolbarButtonSpec,
|
||||
label: 'Extensions',
|
||||
icon: MdiIcons.puzzle,
|
||||
longPressActions: ['Extensions Menu'],
|
||||
isPrimaryAvailable: (scope, ref) => ref
|
||||
.read(
|
||||
webExtensionsStateProvider(
|
||||
WebExtensionActionType.browser,
|
||||
).select((value) => value.values),
|
||||
)
|
||||
.isNotEmpty,
|
||||
builder: (scope, context, ref) {
|
||||
if (scope.isPreview) {
|
||||
return IconButton(onPressed: () {}, icon: const Icon(MdiIcons.puzzle));
|
||||
}
|
||||
return const _ExtensionShortcutToolbarButton();
|
||||
},
|
||||
),
|
||||
ToolbarButtonDefinition(
|
||||
spec: quitToolbarButtonSpec,
|
||||
label: 'Quit',
|
||||
icon: MdiIcons.power,
|
||||
longPressActions: ['Quit without confirmation'],
|
||||
builder: (scope, context, ref) {
|
||||
return IconButton(
|
||||
onPressed: scope.isPreview
|
||||
? () {}
|
||||
: () async {
|
||||
final result = await showQuitBrowserDialog(context);
|
||||
if (result == true) {
|
||||
await exitApp(ref.container);
|
||||
}
|
||||
},
|
||||
onLongPress: scope.isPreview
|
||||
? null
|
||||
: () async {
|
||||
await exitApp(ref.container);
|
||||
},
|
||||
icon: const Icon(MdiIcons.power),
|
||||
);
|
||||
},
|
||||
),
|
||||
];
|
||||
|
||||
final Map<String, ToolbarButtonDefinition> toolbarButtonRegistryById = {
|
||||
for (final def in toolbarButtonRegistry) def.spec.id.name: def,
|
||||
};
|
||||
|
||||
Future<void> _closeTab(
|
||||
BuildContext context,
|
||||
WidgetRef ref,
|
||||
String? selectedTabId,
|
||||
) async {
|
||||
if (selectedTabId == null) return;
|
||||
|
||||
final tabState = ref.read(tabStateProvider(selectedTabId));
|
||||
if (tabState != null && tabState.tabMode is IsolatedTabMode) {
|
||||
final allStates = ref.read(tabStatesProvider);
|
||||
final groupCount = allStates.values
|
||||
.where((s) => s.isolationContextId == tabState.isolationContextId)
|
||||
.length;
|
||||
if (groupCount <= 1 && context.mounted) {
|
||||
final confirmed = await ui_helper.confirmIsolatedTabClose(context);
|
||||
if (!confirmed) return;
|
||||
}
|
||||
}
|
||||
|
||||
await ref.read(tabRepositoryProvider.notifier).closeTab(selectedTabId);
|
||||
|
||||
if (context.mounted) {
|
||||
ui_helper.showTabUndoClose(
|
||||
context,
|
||||
ref.read(tabRepositoryProvider.notifier).undoClose,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ExtensionShortcutToolbarButton extends HookConsumerWidget {
|
||||
const _ExtensionShortcutToolbarButton();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final menuController = useMemoized(MenuController.new);
|
||||
|
||||
return ExtensionShortcutMenu(
|
||||
controller: menuController,
|
||||
child: IconButton(
|
||||
onPressed: () {
|
||||
if (menuController.isOpen) {
|
||||
menuController.close();
|
||||
} else {
|
||||
menuController.open();
|
||||
}
|
||||
},
|
||||
icon: const Icon(MdiIcons.puzzle),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ReloadToolbarButton extends HookConsumerWidget {
|
||||
final ContextualToolbarScope scope;
|
||||
|
||||
const _ReloadToolbarButton({required this.scope});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final menuController = useMemoized(MenuController.new);
|
||||
|
||||
return MenuAnchor(
|
||||
controller: menuController,
|
||||
builder: (context, controller, child) => child!,
|
||||
menuChildren: [
|
||||
MenuItemButton(
|
||||
leadingIcon: const Icon(Icons.refresh),
|
||||
onPressed: () async {
|
||||
final tabId = scope.selectedTabId;
|
||||
if (tabId != null) {
|
||||
await ref
|
||||
.read(tabSessionProvider(tabId: tabId).notifier)
|
||||
.reload(flags: LoadUrlFlags.BYPASS_CACHE);
|
||||
}
|
||||
},
|
||||
child: const Text('Hard Refresh'),
|
||||
),
|
||||
],
|
||||
child: IconButton(
|
||||
onPressed: scope.isPreview
|
||||
? () {}
|
||||
: () async {
|
||||
final tabId = scope.selectedTabId;
|
||||
if (tabId != null) {
|
||||
await ref
|
||||
.read(tabSessionProvider(tabId: tabId).notifier)
|
||||
.reload();
|
||||
}
|
||||
},
|
||||
onLongPress: scope.isPreview
|
||||
? null
|
||||
: () {
|
||||
if (menuController.isOpen) {
|
||||
menuController.close();
|
||||
} else {
|
||||
menuController.open();
|
||||
}
|
||||
},
|
||||
icon: const Icon(Icons.refresh),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _CloseTabToolbarButton extends HookConsumerWidget {
|
||||
final ContextualToolbarScope scope;
|
||||
|
||||
const _CloseTabToolbarButton({required this.scope});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final menuController = useMemoized(MenuController.new);
|
||||
final host = ref.watch(
|
||||
tabStateProvider(scope.selectedTabId).select((s) => s?.url.host),
|
||||
);
|
||||
|
||||
return MenuAnchor(
|
||||
controller: menuController,
|
||||
builder: (context, controller, child) => child!,
|
||||
menuChildren: [
|
||||
MenuItemButton(
|
||||
leadingIcon: const Icon(Icons.tab),
|
||||
onPressed: () async {
|
||||
final tabStates = ref.read(tabStatesProvider);
|
||||
final otherIds = tabStates.keys
|
||||
.where((id) => id != scope.selectedTabId)
|
||||
.toList();
|
||||
if (otherIds.isNotEmpty) {
|
||||
await closeTabsWithConfirmation(context, ref, otherIds);
|
||||
}
|
||||
},
|
||||
child: const Text('Close Others'),
|
||||
),
|
||||
if (host != null && host.isNotEmpty)
|
||||
MenuItemButton(
|
||||
leadingIcon: const Icon(Icons.language),
|
||||
onPressed: () async {
|
||||
final tabStates = ref.read(tabStatesProvider);
|
||||
final sameHostIds = tabStates.entries
|
||||
.where((e) => e.value.url.host == host)
|
||||
.map((e) => e.key)
|
||||
.toList();
|
||||
if (sameHostIds.isNotEmpty) {
|
||||
await closeTabsWithConfirmation(context, ref, sameHostIds);
|
||||
}
|
||||
},
|
||||
child: const Text('Close from Same Host'),
|
||||
),
|
||||
],
|
||||
child: IconButton(
|
||||
onPressed: scope.isPreview
|
||||
? () {}
|
||||
: () => _closeTab(context, ref, scope.selectedTabId),
|
||||
onLongPress: scope.isPreview
|
||||
? null
|
||||
: () {
|
||||
if (menuController.isOpen) {
|
||||
menuController.close();
|
||||
} else {
|
||||
menuController.open();
|
||||
}
|
||||
},
|
||||
icon: const Icon(MdiIcons.tabMinus),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _BookmarkToolbarButton extends HookConsumerWidget {
|
||||
final ContextualToolbarScope scope;
|
||||
|
||||
const _BookmarkToolbarButton({required this.scope});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final menuController = useMemoized(MenuController.new);
|
||||
|
||||
final tabUrl = scope.tabState?.url;
|
||||
final bookmarkable = tabUrl != null && !scope.isPreview;
|
||||
|
||||
final existingGuids = ref
|
||||
.watch(
|
||||
bookmarksRepositoryProvider.select(
|
||||
(async) => EquatableValue(
|
||||
bookmarkable
|
||||
? bookmarkGuidsForUrl(async.value, tabUrl)
|
||||
: const <String>[],
|
||||
),
|
||||
),
|
||||
)
|
||||
.value;
|
||||
|
||||
final isBookmarked = existingGuids.isNotEmpty;
|
||||
|
||||
return MenuAnchor(
|
||||
controller: menuController,
|
||||
builder: (context, controller, child) => child!,
|
||||
menuChildren: [
|
||||
if (isBookmarked)
|
||||
MenuItemButton(
|
||||
leadingIcon: const Icon(MdiIcons.bookmarkRemove),
|
||||
onPressed: () async {
|
||||
for (final guid in existingGuids) {
|
||||
await ref
|
||||
.read(bookmarksRepositoryProvider.notifier)
|
||||
.delete(guid);
|
||||
}
|
||||
if (context.mounted) {
|
||||
ui_helper.showInfoMessage(context, 'Bookmark removed');
|
||||
}
|
||||
},
|
||||
child: const Text('Remove Bookmark'),
|
||||
)
|
||||
else
|
||||
MenuItemButton(
|
||||
leadingIcon: const Icon(MdiIcons.bookmarkPlus),
|
||||
onPressed: !bookmarkable
|
||||
? null
|
||||
: () async {
|
||||
await ref
|
||||
.read(bookmarksRepositoryProvider.notifier)
|
||||
.addBookmark(
|
||||
parentGuid: BookmarkRoot.mobile.id,
|
||||
url: tabUrl,
|
||||
title: scope.tabState!.titleOrAuthority,
|
||||
);
|
||||
|
||||
if (context.mounted) {
|
||||
ui_helper.showInfoMessage(context, 'Bookmark added');
|
||||
}
|
||||
},
|
||||
child: const Text('Add Bookmark'),
|
||||
),
|
||||
],
|
||||
child: IconButton(
|
||||
onPressed: scope.isPreview
|
||||
? () {}
|
||||
: () async {
|
||||
await BookmarkListRoute(
|
||||
entryGuid: BookmarkRoot.root.id,
|
||||
).push(context);
|
||||
},
|
||||
onLongPress: scope.isPreview
|
||||
? null
|
||||
: () {
|
||||
if (menuController.isOpen) {
|
||||
menuController.close();
|
||||
} else {
|
||||
menuController.open();
|
||||
}
|
||||
},
|
||||
icon: const Icon(MdiIcons.bookmarkMultiple),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _BookmarkToggleToolbarButton extends ConsumerWidget {
|
||||
final ContextualToolbarScope scope;
|
||||
|
||||
const _BookmarkToggleToolbarButton({required this.scope});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final tabUrl = scope.tabState?.url;
|
||||
final bookmarkable = tabUrl != null && !scope.isPreview;
|
||||
final existingGuids = ref
|
||||
.watch(
|
||||
bookmarksRepositoryProvider.select(
|
||||
(async) => EquatableValue(
|
||||
bookmarkable
|
||||
? bookmarkGuidsForUrl(async.value, tabUrl)
|
||||
: const <String>[],
|
||||
),
|
||||
),
|
||||
)
|
||||
.value;
|
||||
|
||||
final isBookmarked = existingGuids.isNotEmpty;
|
||||
|
||||
return IconButton(
|
||||
tooltip: isBookmarked ? 'Remove bookmark' : 'Add bookmark',
|
||||
onPressed: scope.isPreview
|
||||
? () {}
|
||||
: !bookmarkable
|
||||
? null
|
||||
: () async {
|
||||
if (isBookmarked) {
|
||||
for (final guid in existingGuids) {
|
||||
await ref
|
||||
.read(bookmarksRepositoryProvider.notifier)
|
||||
.delete(guid);
|
||||
}
|
||||
|
||||
if (context.mounted) {
|
||||
ui_helper.showInfoMessage(context, 'Bookmark removed');
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
await ref
|
||||
.read(bookmarksRepositoryProvider.notifier)
|
||||
.addBookmark(
|
||||
parentGuid: BookmarkRoot.mobile.id,
|
||||
url: tabUrl,
|
||||
title: scope.tabState!.titleOrAuthority,
|
||||
);
|
||||
|
||||
if (context.mounted) {
|
||||
ui_helper.showInfoMessage(context, 'Bookmark added');
|
||||
}
|
||||
},
|
||||
onLongPress: scope.isPreview
|
||||
? null
|
||||
: () async {
|
||||
await BookmarkListRoute(
|
||||
entryGuid: BookmarkRoot.root.id,
|
||||
).push(context);
|
||||
},
|
||||
icon: Icon(isBookmarked ? Icons.bookmark : Icons.bookmark_border),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _adjustFontSize(
|
||||
BuildContext context,
|
||||
WidgetRef ref, {
|
||||
required bool increase,
|
||||
}) async {
|
||||
final settings = ref.read(engineSettingsWithDefaultsProvider);
|
||||
|
||||
if (settings.automaticFontSizeAdjustment) {
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text(
|
||||
'Disable automatic font size in settings to adjust manually',
|
||||
),
|
||||
duration: Duration(seconds: 2),
|
||||
),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
final current = settings.fontSizeFactor;
|
||||
final newValue = increase
|
||||
? (current + fontSizeStep).clamp(fontSizeMin, fontSizeMax)
|
||||
: (current - fontSizeStep).clamp(fontSizeMin, fontSizeMax);
|
||||
final rounded = (newValue * 10).round() / 10;
|
||||
|
||||
if (rounded == current) return;
|
||||
|
||||
await ref
|
||||
.read(saveEngineSettingsControllerProvider.notifier)
|
||||
.save(
|
||||
(currentSettings) => currentSettings.copyWith.fontSizeFactor(rounded),
|
||||
);
|
||||
}
|
||||
|
||||
class _ReaderModeToolbarButton extends ConsumerWidget {
|
||||
final String? selectedTabId;
|
||||
|
||||
const _ReaderModeToolbarButton({required this.selectedTabId});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final readerableState = ref.watch(
|
||||
tabStateProvider(
|
||||
selectedTabId,
|
||||
).select((state) => state?.readerableState ?? ReaderableState.$default()),
|
||||
);
|
||||
final isReaderLoading = ref.watch(
|
||||
readerableScreenControllerProvider.select((state) => state.isLoading),
|
||||
);
|
||||
|
||||
return IconButton(
|
||||
onPressed: isReaderLoading
|
||||
? null
|
||||
: () async {
|
||||
await ref
|
||||
.read(readerableScreenControllerProvider.notifier)
|
||||
.toggleReaderView(!readerableState.active);
|
||||
},
|
||||
icon: Icon(
|
||||
readerableState.active ? MdiIcons.bookOpen : MdiIcons.bookOpenOutline,
|
||||
color: readerableState.active
|
||||
? Theme.of(context).colorScheme.primary
|
||||
: null,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _DesktopModeToolbarButton extends ConsumerWidget {
|
||||
final String? selectedTabId;
|
||||
|
||||
const _DesktopModeToolbarButton({required this.selectedTabId});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
if (selectedTabId == null) {
|
||||
return const IconButton(
|
||||
onPressed: null,
|
||||
icon: Icon(Icons.desktop_windows),
|
||||
);
|
||||
}
|
||||
|
||||
final desktopEnabled = ref.watch(desktopModeProvider(selectedTabId!));
|
||||
|
||||
return IconButton(
|
||||
onPressed: () {
|
||||
ref.read(desktopModeProvider(selectedTabId!).notifier).toggle();
|
||||
},
|
||||
icon: Icon(
|
||||
desktopEnabled ? Icons.desktop_windows : Icons.desktop_windows_outlined,
|
||||
color: desktopEnabled ? Theme.of(context).colorScheme.primary : null,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _TranslateToolbarButton extends ConsumerWidget {
|
||||
final String? selectedTabId;
|
||||
|
||||
const _TranslateToolbarButton({required this.selectedTabId});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final isTranslated = ref.watch(
|
||||
tabStateProvider(
|
||||
selectedTabId,
|
||||
).select((s) => s?.translationState.isTranslated ?? false),
|
||||
);
|
||||
|
||||
return IconButton(
|
||||
onPressed: () async {
|
||||
final tabId = selectedTabId;
|
||||
if (tabId != null) {
|
||||
if (isTranslated) {
|
||||
await ref
|
||||
.read(tabSessionProvider(tabId: tabId).notifier)
|
||||
.translateRestore();
|
||||
} else {
|
||||
await showTranslationBottomSheet(context, selectedTabId: tabId);
|
||||
}
|
||||
}
|
||||
},
|
||||
onLongPress: () async {
|
||||
final tabId = selectedTabId;
|
||||
if (tabId != null) {
|
||||
await showTranslationBottomSheet(context, selectedTabId: tabId);
|
||||
}
|
||||
},
|
||||
icon: Icon(
|
||||
isTranslated ? MdiIcons.translateOff : Icons.translate,
|
||||
color: isTranslated ? Theme.of(context).colorScheme.primary : null,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _FontToolbarButton extends ConsumerWidget {
|
||||
final String? selectedTabId;
|
||||
|
||||
const _FontToolbarButton({required this.selectedTabId});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final isCustom = ref.watch(
|
||||
engineSettingsWithDefaultsProvider.select(
|
||||
(s) => !s.automaticFontSizeAdjustment && s.fontSizeFactor != 1.0,
|
||||
),
|
||||
);
|
||||
|
||||
return IconButton(
|
||||
onPressed: () => showFontSizeBottomSheet(context),
|
||||
icon: Icon(
|
||||
MdiIcons.formatSize,
|
||||
color: isCustom ? Theme.of(context).colorScheme.primary : null,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
+454
@@ -0,0 +1,454 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_material_design_icons/flutter_material_design_icons.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:weblibre/core/design/app_colors.dart';
|
||||
import 'package:weblibre/core/routing/routes.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/controllers/bottom_sheet.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/entities/tab_container_selection.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers/tab_state.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/repositories/tab.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/domain/entities/sheet.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/presentation/widgets/browser_menu_sheet.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/presentation/widgets/share_bottom_sheet.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/presentation/widgets/tab_creation_menu.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/presentation/widgets/tabs_action_button.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/presentation/widgets/toolbar_button.dart';
|
||||
import 'package:weblibre/features/geckoview/features/tabs/data/entities/tab_mode.dart';
|
||||
import 'package:weblibre/features/geckoview/features/tabs/domain/repositories/tab.dart'
|
||||
as tab_data;
|
||||
import 'package:weblibre/features/user/domain/repositories/general_settings.dart';
|
||||
import 'package:weblibre/presentation/hooks/menu_controller.dart';
|
||||
import 'package:weblibre/utils/ui_helper.dart' as ui_helper;
|
||||
|
||||
class ShareMenuButton extends StatelessWidget {
|
||||
final String? selectedTabId;
|
||||
|
||||
const ShareMenuButton({super.key, required this.selectedTabId});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ShareMenuButtonView(
|
||||
onPressed: selectedTabId == null
|
||||
? null
|
||||
: () async {
|
||||
await showShareBottomSheet(
|
||||
context,
|
||||
selectedTabId: selectedTabId!,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class ShareMenuButtonView extends StatelessWidget {
|
||||
const ShareMenuButtonView({super.key, this.onPressed});
|
||||
|
||||
final VoidCallback? onPressed;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return IconButton(onPressed: onPressed, icon: const Icon(Icons.share));
|
||||
}
|
||||
}
|
||||
|
||||
class NavigationMenuButton extends StatelessWidget {
|
||||
final String? selectedTabId;
|
||||
|
||||
const NavigationMenuButton({super.key, required this.selectedTabId});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return NavigationMenuButtonView(
|
||||
onTap: () async {
|
||||
await showBrowserMenuSheet(context);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class NavigationMenuButtonView extends StatelessWidget {
|
||||
const NavigationMenuButtonView({super.key, this.onTap});
|
||||
|
||||
final VoidCallback? onTap;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return ToolbarButton(onTap: onTap, child: const Icon(Icons.more_vert));
|
||||
}
|
||||
}
|
||||
|
||||
class AddTabButton extends HookConsumerWidget {
|
||||
const AddTabButton({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final tabMenuController = useMenuController();
|
||||
|
||||
return TabCreationMenu(
|
||||
controller: tabMenuController,
|
||||
child: AddTabButtonView(
|
||||
onPressed: () async {
|
||||
final settings = ref.read(generalSettingsWithDefaultsProvider);
|
||||
|
||||
await SearchRoute(
|
||||
tabType:
|
||||
ref.read(selectedTabTypeProvider) ??
|
||||
settings.effectiveDefaultCreateTabType,
|
||||
).push(context);
|
||||
|
||||
if (context.mounted) {
|
||||
const BrowserRoute().go(context);
|
||||
}
|
||||
},
|
||||
onLongPress: () {
|
||||
if (tabMenuController.isOpen) {
|
||||
tabMenuController.close();
|
||||
} else {
|
||||
tabMenuController.open();
|
||||
}
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class AddTabButtonView extends StatelessWidget {
|
||||
const AddTabButtonView({super.key, this.onPressed, this.onLongPress});
|
||||
|
||||
final VoidCallback? onPressed;
|
||||
final VoidCallback? onLongPress;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return IconButton(
|
||||
onPressed: onPressed,
|
||||
icon: const Icon(MdiIcons.tabPlus),
|
||||
onLongPress: onLongPress,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class CloneTabButton extends HookConsumerWidget {
|
||||
const CloneTabButton({super.key, required this.selectedTabId});
|
||||
|
||||
final String? selectedTabId;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final tabMenuController = useMenuController();
|
||||
|
||||
return CloneTabMenu(
|
||||
controller: tabMenuController,
|
||||
selectedTabId: selectedTabId,
|
||||
child: CloneTabButtonView(
|
||||
onPressed: selectedTabId == null
|
||||
? null
|
||||
: () => _cloneCurrentTabMode(context, ref, selectedTabId!),
|
||||
onLongPress: selectedTabId == null
|
||||
? null
|
||||
: () {
|
||||
if (tabMenuController.isOpen) {
|
||||
tabMenuController.close();
|
||||
} else {
|
||||
tabMenuController.open();
|
||||
}
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class CloneTabButtonView extends StatelessWidget {
|
||||
const CloneTabButtonView({super.key, this.onPressed, this.onLongPress});
|
||||
|
||||
final VoidCallback? onPressed;
|
||||
final VoidCallback? onLongPress;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return IconButton(
|
||||
onPressed: onPressed,
|
||||
onLongPress: onLongPress,
|
||||
icon: const Icon(MdiIcons.contentDuplicate),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class CloneTabMenu extends HookConsumerWidget {
|
||||
const CloneTabMenu({
|
||||
super.key,
|
||||
required this.child,
|
||||
required this.controller,
|
||||
required this.selectedTabId,
|
||||
});
|
||||
|
||||
final Widget child;
|
||||
final MenuController controller;
|
||||
final String? selectedTabId;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final showIsolatedTabUi = ref.watch(
|
||||
generalSettingsWithDefaultsProvider.select(
|
||||
(value) => value.showIsolatedTabUi,
|
||||
),
|
||||
);
|
||||
|
||||
return MenuAnchor(
|
||||
controller: controller,
|
||||
builder: (context, controller, child) {
|
||||
return child!;
|
||||
},
|
||||
menuChildren: [
|
||||
MenuItemButton(
|
||||
leadingIcon: const Icon(MdiIcons.tab),
|
||||
onPressed: selectedTabId == null
|
||||
? null
|
||||
: () => _cloneTabAsRegular(context, ref, selectedTabId!),
|
||||
child: const Text('Clone as Regular'),
|
||||
),
|
||||
MenuItemButton(
|
||||
leadingIcon: Icon(
|
||||
MdiIcons.dominoMask,
|
||||
color: AppColors.of(context).privateTabPurple,
|
||||
),
|
||||
onPressed: selectedTabId == null
|
||||
? null
|
||||
: () => _cloneTabAsPrivate(context, ref, selectedTabId!),
|
||||
child: const Text('Clone as Private'),
|
||||
),
|
||||
if (showIsolatedTabUi)
|
||||
MenuItemButton(
|
||||
leadingIcon: Icon(
|
||||
MdiIcons.snowflake,
|
||||
color: AppColors.of(context).isolatedTabTeal,
|
||||
),
|
||||
onPressed: selectedTabId == null
|
||||
? null
|
||||
: () => _cloneTabAsIsolated(context, ref, selectedTabId!),
|
||||
child: const Text('Clone as Isolated'),
|
||||
),
|
||||
],
|
||||
child: child,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class TabsCountButtonView extends StatelessWidget {
|
||||
const TabsCountButtonView({
|
||||
super.key,
|
||||
required this.isActive,
|
||||
required this.onTap,
|
||||
this.onLongPress,
|
||||
this.buttonBuilder,
|
||||
});
|
||||
|
||||
final bool isActive;
|
||||
final VoidCallback onTap;
|
||||
final VoidCallback? onLongPress;
|
||||
final Widget Function(
|
||||
bool isActive,
|
||||
VoidCallback onTap,
|
||||
VoidCallback? onLongPress,
|
||||
)?
|
||||
buttonBuilder;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return (buttonBuilder != null)
|
||||
? buttonBuilder!(isActive, onTap, onLongPress)
|
||||
: TabsActionButton(
|
||||
isActive: isActive,
|
||||
onTap: onTap,
|
||||
onLongPress: onLongPress,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _cloneCurrentTabMode(
|
||||
BuildContext context,
|
||||
WidgetRef ref,
|
||||
String selectedTabId,
|
||||
) async {
|
||||
final containerData = await ref
|
||||
.read(tab_data.tabDataRepositoryProvider.notifier)
|
||||
.getTabContainerData(selectedTabId);
|
||||
|
||||
final tabId = await ref
|
||||
.read(tabRepositoryProvider.notifier)
|
||||
.duplicateTab(
|
||||
selectTabId: selectedTabId,
|
||||
containerData: containerData,
|
||||
selectTab: false,
|
||||
);
|
||||
|
||||
if (context.mounted) {
|
||||
final repo = ref.read(tabRepositoryProvider.notifier);
|
||||
ui_helper.showTabSwitchMessage(
|
||||
context,
|
||||
onSwitch: () => repo.selectTab(tabId),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _cloneTabAsRegular(
|
||||
BuildContext context,
|
||||
WidgetRef ref,
|
||||
String selectedTabId,
|
||||
) {
|
||||
return _cloneTabAsMode(context, ref, selectedTabId, mode: TabMode.regular);
|
||||
}
|
||||
|
||||
Future<void> _cloneTabAsPrivate(
|
||||
BuildContext context,
|
||||
WidgetRef ref,
|
||||
String selectedTabId,
|
||||
) {
|
||||
return _cloneTabAsMode(context, ref, selectedTabId, mode: TabMode.private);
|
||||
}
|
||||
|
||||
Future<void> _cloneTabAsIsolated(
|
||||
BuildContext context,
|
||||
WidgetRef ref,
|
||||
String selectedTabId,
|
||||
) {
|
||||
return _cloneTabAsMode(
|
||||
context,
|
||||
ref,
|
||||
selectedTabId,
|
||||
mode: TabMode.newIsolated(),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _cloneTabAsMode(
|
||||
BuildContext context,
|
||||
WidgetRef ref,
|
||||
String selectedTabId, {
|
||||
required TabMode mode,
|
||||
}) async {
|
||||
final tabState = ref.read(tabStateProvider(selectedTabId));
|
||||
if (tabState == null) return;
|
||||
|
||||
final containerData = await ref
|
||||
.read(tab_data.tabDataRepositoryProvider.notifier)
|
||||
.getTabContainerData(selectedTabId);
|
||||
final repo = ref.read(tabRepositoryProvider.notifier);
|
||||
|
||||
final tabId = switch (mode) {
|
||||
RegularTabMode() =>
|
||||
tabState.tabMode is RegularTabMode
|
||||
? await repo.duplicateTab(
|
||||
selectTabId: selectedTabId,
|
||||
containerData: containerData,
|
||||
selectTab: false,
|
||||
)
|
||||
: await repo.addTab(
|
||||
tabMode: TabMode.regular,
|
||||
url: tabState.url,
|
||||
containerSelection: containerData == null
|
||||
? const TabContainerSelection.unassigned()
|
||||
: TabContainerSelection.specific(containerData),
|
||||
selectTab: false,
|
||||
),
|
||||
PrivateTabMode() =>
|
||||
tabState.tabMode is PrivateTabMode
|
||||
? await repo.duplicateTab(
|
||||
selectTabId: selectedTabId,
|
||||
containerData: containerData,
|
||||
selectTab: false,
|
||||
)
|
||||
: await repo.addTab(
|
||||
tabMode: TabMode.private,
|
||||
url: tabState.url,
|
||||
containerSelection: containerData == null
|
||||
? const TabContainerSelection.unassigned()
|
||||
: TabContainerSelection.specific(containerData),
|
||||
selectTab: false,
|
||||
),
|
||||
IsolatedTabMode() => await repo.addTab(
|
||||
tabMode: TabMode.newIsolated(),
|
||||
url: tabState.url,
|
||||
containerSelection: containerData == null
|
||||
? const TabContainerSelection.unassigned()
|
||||
: TabContainerSelection.specific(containerData),
|
||||
selectTab: false,
|
||||
),
|
||||
};
|
||||
|
||||
if (context.mounted) {
|
||||
ui_helper.showTabSwitchMessage(
|
||||
context,
|
||||
onSwitch: () => repo.selectTab(tabId),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class TabsCountButton extends HookConsumerWidget {
|
||||
const TabsCountButton({
|
||||
super.key,
|
||||
required this.selectedTabId,
|
||||
required this.displayedSheet,
|
||||
required this.showLongPressMenu,
|
||||
});
|
||||
|
||||
final String? selectedTabId;
|
||||
final Sheet? displayedSheet;
|
||||
final bool showLongPressMenu;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final tabMenuController = useMenuController();
|
||||
|
||||
return TabCreationMenu(
|
||||
controller: tabMenuController,
|
||||
child: TabsCountButtonView(
|
||||
isActive: displayedSheet is ViewTabsSheet,
|
||||
onTap: () async {
|
||||
final tabViewBottomSheet = ref
|
||||
.read(generalSettingsWithDefaultsProvider)
|
||||
.tabViewBottomSheet;
|
||||
|
||||
if (tabViewBottomSheet) {
|
||||
if (displayedSheet case ViewTabsSheet()) {
|
||||
ref.read(bottomSheetControllerProvider.notifier).requestDismiss();
|
||||
} else {
|
||||
ref
|
||||
.read(bottomSheetControllerProvider.notifier)
|
||||
.show(ViewTabsSheet());
|
||||
}
|
||||
} else {
|
||||
await const TabViewRoute().push(context);
|
||||
}
|
||||
},
|
||||
onLongPress: showLongPressMenu
|
||||
? () {
|
||||
if (tabMenuController.isOpen) {
|
||||
tabMenuController.close();
|
||||
} else {
|
||||
tabMenuController.open();
|
||||
}
|
||||
}
|
||||
: null,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
+131
@@ -0,0 +1,131 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_hooks/flutter_hooks.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers/tab_state.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/domain/entities/sheet.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/features/contextual_toolbar/data/providers/toolbar_button_configs.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/features/contextual_toolbar/domain/entities/toolbar_button_spec.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/features/contextual_toolbar/domain/services/toolbar_button_resolution.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/features/contextual_toolbar/presentation/models/contextual_toolbar_scope.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/features/contextual_toolbar/presentation/toolbar_button_registry.dart';
|
||||
|
||||
class ContextualToolbar extends HookConsumerWidget {
|
||||
const ContextualToolbar({
|
||||
super.key,
|
||||
required this.selectedTabId,
|
||||
required this.displayedSheet,
|
||||
});
|
||||
|
||||
final String? selectedTabId;
|
||||
final Sheet? displayedSheet;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final tabState = ref.watch(tabStateProvider(selectedTabId));
|
||||
final configs = ref.watch(effectiveToolbarButtonConfigsProvider);
|
||||
|
||||
final scope = ContextualToolbarScope(
|
||||
selectedTabId: selectedTabId,
|
||||
displayedSheet: displayedSheet,
|
||||
tabState: tabState,
|
||||
isPreview: false,
|
||||
);
|
||||
|
||||
final resolvedButtons = useMemoized(
|
||||
() => resolveVisibleContextualToolbarButtons(
|
||||
configs: configs.value,
|
||||
knownButtonIds: knownToolbarButtonIds,
|
||||
isPrimaryAvailable: (buttonId) {
|
||||
final def = toolbarButtonRegistryById[buttonId];
|
||||
return def?.isPrimaryAvailable?.call(scope, ref) ?? true;
|
||||
},
|
||||
),
|
||||
[configs, scope],
|
||||
);
|
||||
|
||||
final buttons = resolvedButtons
|
||||
.map((button) => _buildButton(scope, context, ref, button))
|
||||
.toList();
|
||||
|
||||
return ContextualToolbarView(buttons: buttons);
|
||||
}
|
||||
|
||||
Widget _buildButton(
|
||||
ContextualToolbarScope scope,
|
||||
BuildContext context,
|
||||
WidgetRef ref,
|
||||
ContextualToolbarButtonResolution button,
|
||||
) {
|
||||
final def = toolbarButtonRegistryById[button.buttonId];
|
||||
if (def == null) return const SizedBox.shrink();
|
||||
|
||||
final child = def.builder(scope, context, ref);
|
||||
|
||||
if (button.isEnabled) {
|
||||
return child;
|
||||
}
|
||||
|
||||
return Opacity(opacity: 0.38, child: IgnorePointer(child: child));
|
||||
}
|
||||
}
|
||||
|
||||
class ContextualToolbarView extends StatelessWidget {
|
||||
const ContextualToolbarView({super.key, required this.buttons});
|
||||
|
||||
final List<Widget> buttons;
|
||||
|
||||
static const _minButtonWidth = 48.0;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (buttons.isEmpty) return const SizedBox.shrink();
|
||||
|
||||
return LayoutBuilder(
|
||||
builder: (context, constraints) {
|
||||
final fitsEvenly =
|
||||
constraints.maxWidth >= _minButtonWidth * buttons.length;
|
||||
|
||||
if (fitsEvenly) {
|
||||
return Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
|
||||
children: buttons,
|
||||
);
|
||||
}
|
||||
|
||||
return SingleChildScrollView(
|
||||
scrollDirection: Axis.horizontal,
|
||||
child: Row(
|
||||
children: buttons
|
||||
.map(
|
||||
(button) => SizedBox(
|
||||
width: _minButtonWidth,
|
||||
child: Center(child: button),
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_material_design_icons/flutter_material_design_icons.dart';
|
||||
import 'package:riverpod/experimental/persist.dart';
|
||||
import 'package:riverpod_annotation/experimental/json_persist.dart';
|
||||
import 'package:riverpod_annotation/experimental/persist.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/domain/entities/tab_view_filter_options.dart';
|
||||
import 'package:weblibre/features/user/data/providers.dart';
|
||||
|
||||
part 'tab_view_controllers.g.dart';
|
||||
|
||||
enum TabsViewMode {
|
||||
list(MdiIcons.folderTable, 'List'),
|
||||
grid(MdiIcons.table, 'Grid'),
|
||||
tree(MdiIcons.familyTree, 'Tree');
|
||||
|
||||
final IconData icon;
|
||||
final String label;
|
||||
|
||||
const TabsViewMode(this.icon, this.label);
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
class TabsViewModeController extends _$TabsViewModeController {
|
||||
void set(TabsViewMode mode) {
|
||||
if (mode != state) {
|
||||
state = mode;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
TabsViewMode build() {
|
||||
persist(
|
||||
ref.watch(riverpodDatabaseStorageProvider),
|
||||
key: 'TabsViewMode',
|
||||
encode: (state) => jsonEncode([state.name]),
|
||||
decode: (encoded) {
|
||||
final name = (jsonDecode(encoded) as List<dynamic>).first as String;
|
||||
return TabsViewMode.values.firstWhere((e) => e.name == name);
|
||||
},
|
||||
);
|
||||
|
||||
return stateOrNull ?? TabsViewMode.list;
|
||||
}
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
@JsonPersist()
|
||||
class TabViewFilterController extends _$TabViewFilterController {
|
||||
void setTabTypeFilter(TabTypeFilter filter) {
|
||||
state = state.copyWith.tabTypeFilter(filter);
|
||||
}
|
||||
|
||||
void setSortType(TabSortType sort) {
|
||||
state = state.copyWith.sortType(sort);
|
||||
}
|
||||
|
||||
void setSortPinnedFirst(bool value) {
|
||||
state = state.copyWith(sortPinnedFirst: value);
|
||||
}
|
||||
|
||||
void setDateRange(DateTimeRange<DateTime>? range) {
|
||||
// ignore: avoid_redundant_argument_values
|
||||
state = state.copyWith(dateRange: range, quickInterval: null);
|
||||
}
|
||||
|
||||
void setQuickInterval(TabQuickInterval? interval) {
|
||||
// ignore: avoid_redundant_argument_values
|
||||
state = state.copyWith(quickInterval: interval, dateRange: null);
|
||||
}
|
||||
|
||||
void reset() {
|
||||
state = TabViewFilterOptions.withDefaults();
|
||||
}
|
||||
|
||||
@override
|
||||
TabViewFilterOptions build() {
|
||||
persist(
|
||||
ref.watch(riverpodDatabaseStorageProvider),
|
||||
key: 'TabViewFilterOptions',
|
||||
);
|
||||
|
||||
return stateOrNull ?? TabViewFilterOptions.withDefaults();
|
||||
}
|
||||
}
|
||||
|
||||
@Riverpod()
|
||||
class TabsReorderableController extends _$TabsReorderableController {
|
||||
void toggle() {
|
||||
state = !state;
|
||||
}
|
||||
|
||||
void hide() {
|
||||
if (state) {
|
||||
state = false;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
bool build() {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
+210
@@ -0,0 +1,210 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'tab_view_controllers.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(TabsViewModeController)
|
||||
final tabsViewModeControllerProvider = TabsViewModeControllerProvider._();
|
||||
|
||||
final class TabsViewModeControllerProvider
|
||||
extends $NotifierProvider<TabsViewModeController, TabsViewMode> {
|
||||
TabsViewModeControllerProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'tabsViewModeControllerProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$tabsViewModeControllerHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
TabsViewModeController create() => TabsViewModeController();
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(TabsViewMode value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<TabsViewMode>(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$tabsViewModeControllerHash() =>
|
||||
r'e013b174218fcad81981f7d939cf161c3b002adc';
|
||||
|
||||
abstract class _$TabsViewModeController extends $Notifier<TabsViewMode> {
|
||||
TabsViewMode build();
|
||||
@$mustCallSuper
|
||||
@override
|
||||
void runBuild() {
|
||||
final ref = this.ref as $Ref<TabsViewMode, TabsViewMode>;
|
||||
final element =
|
||||
ref.element
|
||||
as $ClassProviderElement<
|
||||
AnyNotifier<TabsViewMode, TabsViewMode>,
|
||||
TabsViewMode,
|
||||
Object?,
|
||||
Object?
|
||||
>;
|
||||
element.handleCreate(ref, build);
|
||||
}
|
||||
}
|
||||
|
||||
@ProviderFor(TabViewFilterController)
|
||||
@JsonPersist()
|
||||
final tabViewFilterControllerProvider = TabViewFilterControllerProvider._();
|
||||
|
||||
@JsonPersist()
|
||||
final class TabViewFilterControllerProvider
|
||||
extends $NotifierProvider<TabViewFilterController, TabViewFilterOptions> {
|
||||
TabViewFilterControllerProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'tabViewFilterControllerProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$tabViewFilterControllerHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
TabViewFilterController create() => TabViewFilterController();
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(TabViewFilterOptions value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<TabViewFilterOptions>(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$tabViewFilterControllerHash() =>
|
||||
r'95e8a03d60ebe05e0c5df38f810f951a4fe2ed78';
|
||||
|
||||
@JsonPersist()
|
||||
abstract class _$TabViewFilterControllerBase
|
||||
extends $Notifier<TabViewFilterOptions> {
|
||||
TabViewFilterOptions build();
|
||||
@$mustCallSuper
|
||||
@override
|
||||
void runBuild() {
|
||||
final ref = this.ref as $Ref<TabViewFilterOptions, TabViewFilterOptions>;
|
||||
final element =
|
||||
ref.element
|
||||
as $ClassProviderElement<
|
||||
AnyNotifier<TabViewFilterOptions, TabViewFilterOptions>,
|
||||
TabViewFilterOptions,
|
||||
Object?,
|
||||
Object?
|
||||
>;
|
||||
element.handleCreate(ref, build);
|
||||
}
|
||||
}
|
||||
|
||||
@ProviderFor(TabsReorderableController)
|
||||
final tabsReorderableControllerProvider = TabsReorderableControllerProvider._();
|
||||
|
||||
final class TabsReorderableControllerProvider
|
||||
extends $NotifierProvider<TabsReorderableController, bool> {
|
||||
TabsReorderableControllerProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'tabsReorderableControllerProvider',
|
||||
isAutoDispose: true,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$tabsReorderableControllerHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
TabsReorderableController create() => TabsReorderableController();
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(bool value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<bool>(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$tabsReorderableControllerHash() =>
|
||||
r'f169e9dc04055ef611f17ebe121f0f51f6a294cb';
|
||||
|
||||
abstract class _$TabsReorderableController extends $Notifier<bool> {
|
||||
bool build();
|
||||
@$mustCallSuper
|
||||
@override
|
||||
void runBuild() {
|
||||
final ref = this.ref as $Ref<bool, bool>;
|
||||
final element =
|
||||
ref.element
|
||||
as $ClassProviderElement<
|
||||
AnyNotifier<bool, bool>,
|
||||
bool,
|
||||
Object?,
|
||||
Object?
|
||||
>;
|
||||
element.handleCreate(ref, build);
|
||||
}
|
||||
}
|
||||
|
||||
// **************************************************************************
|
||||
// JsonGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
abstract class _$TabViewFilterController extends _$TabViewFilterControllerBase {
|
||||
/// The default key used by [persist].
|
||||
String get key {
|
||||
const resolvedKey = "TabViewFilterController";
|
||||
return resolvedKey;
|
||||
}
|
||||
|
||||
/// A variant of [persist], for JSON-specific encoding.
|
||||
///
|
||||
/// You can override [key] to customize the key used for storage.
|
||||
PersistResult persist(
|
||||
FutureOr<Storage<String, String>> storage, {
|
||||
String? key,
|
||||
String Function(TabViewFilterOptions state)? encode,
|
||||
TabViewFilterOptions Function(String encoded)? decode,
|
||||
StorageOptions options = const StorageOptions(),
|
||||
}) {
|
||||
return NotifierPersistX(this).persist<String, String>(
|
||||
storage,
|
||||
key: key ?? this.key,
|
||||
encode: encode ?? $jsonCodex.encode,
|
||||
decode:
|
||||
decode ??
|
||||
(encoded) {
|
||||
final e = $jsonCodex.decode(encoded);
|
||||
return TabViewFilterOptions.fromJson(e as Map<String, Object?>);
|
||||
},
|
||||
options: options,
|
||||
);
|
||||
}
|
||||
}
|
||||
+108
@@ -0,0 +1,108 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:riverpod/riverpod.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers/tab_state.dart';
|
||||
import 'package:weblibre/features/user/domain/repositories/general_settings.dart';
|
||||
|
||||
part 'toolbar_visibility.g.dart';
|
||||
|
||||
enum ToolbarVisibility { visible, hidden, dismissed }
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
class ToolbarVisibilityController extends _$ToolbarVisibilityController {
|
||||
@override
|
||||
ToolbarVisibility build(String? tabId) {
|
||||
// Show toolbar when loading starts
|
||||
ref.listen(tabStatesProvider.select((tabs) => tabs[tabId]?.isLoading), (
|
||||
previous,
|
||||
next,
|
||||
) {
|
||||
if (!ref.read(generalSettingsWithDefaultsProvider).autoHideTabBar) {
|
||||
return;
|
||||
}
|
||||
if (next == true) {
|
||||
show();
|
||||
}
|
||||
});
|
||||
|
||||
// Show toolbar on navigation (history state change)
|
||||
ref.listen(tabStatesProvider.select((tabs) => tabs[tabId]?.historyState), (
|
||||
previous,
|
||||
next,
|
||||
) {
|
||||
if (!ref.read(generalSettingsWithDefaultsProvider).autoHideTabBar) {
|
||||
return;
|
||||
}
|
||||
if (next != null && previous != null && previous != next) {
|
||||
show();
|
||||
}
|
||||
});
|
||||
|
||||
// Force-show when GeckoView requests toolbar expansion
|
||||
// (e.g. touch on form input)
|
||||
ref.listen<bool>(
|
||||
tabStatesProvider.select(
|
||||
(tabs) => tabs[tabId]?.showToolbarAsExpanded ?? false,
|
||||
),
|
||||
(previous, next) {
|
||||
if (next && previous != next) {
|
||||
forceShow();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
return ToolbarVisibility.visible;
|
||||
}
|
||||
|
||||
/// Hide toolbar via scroll. All guards checked internally.
|
||||
void requestHide() {
|
||||
if (state != ToolbarVisibility.visible) return;
|
||||
|
||||
final settings = ref.read(generalSettingsWithDefaultsProvider);
|
||||
if (!settings.autoHideTabBar) return;
|
||||
|
||||
final isLoading = ref.read(tabStatesProvider)[tabId]?.isLoading ?? false;
|
||||
if (isLoading) return;
|
||||
|
||||
final viewportService = ref.read(viewportServiceProvider);
|
||||
if (!viewportService.isBrowserHandlingScrollEnabled) return;
|
||||
|
||||
state = ToolbarVisibility.hidden;
|
||||
}
|
||||
|
||||
/// Show toolbar (scroll-up, tab change, loading start, etc).
|
||||
/// Won't show if manually dismissed — use forceShow() for that.
|
||||
void show() {
|
||||
if (state != ToolbarVisibility.hidden) return;
|
||||
state = ToolbarVisibility.visible;
|
||||
}
|
||||
|
||||
/// Force-show unconditionally + un-dismiss.
|
||||
void forceShow() {
|
||||
state = ToolbarVisibility.visible;
|
||||
}
|
||||
|
||||
/// Dismiss toolbar (user swipe). Only affects this tab.
|
||||
void dismiss() {
|
||||
state = ToolbarVisibility.dismissed;
|
||||
}
|
||||
}
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'toolbar_visibility.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(ToolbarVisibilityController)
|
||||
final toolbarVisibilityControllerProvider =
|
||||
ToolbarVisibilityControllerFamily._();
|
||||
|
||||
final class ToolbarVisibilityControllerProvider
|
||||
extends $NotifierProvider<ToolbarVisibilityController, ToolbarVisibility> {
|
||||
ToolbarVisibilityControllerProvider._({
|
||||
required ToolbarVisibilityControllerFamily super.from,
|
||||
required String? super.argument,
|
||||
}) : super(
|
||||
retry: null,
|
||||
name: r'toolbarVisibilityControllerProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$toolbarVisibilityControllerHash();
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return r'toolbarVisibilityControllerProvider'
|
||||
''
|
||||
'($argument)';
|
||||
}
|
||||
|
||||
@$internal
|
||||
@override
|
||||
ToolbarVisibilityController create() => ToolbarVisibilityController();
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(ToolbarVisibility value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<ToolbarVisibility>(value),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return other is ToolbarVisibilityControllerProvider &&
|
||||
other.argument == argument;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode {
|
||||
return argument.hashCode;
|
||||
}
|
||||
}
|
||||
|
||||
String _$toolbarVisibilityControllerHash() =>
|
||||
r'e947508c351d4cbbe8c63289171a6d0a34f1a61a';
|
||||
|
||||
final class ToolbarVisibilityControllerFamily extends $Family
|
||||
with
|
||||
$ClassFamilyOverride<
|
||||
ToolbarVisibilityController,
|
||||
ToolbarVisibility,
|
||||
ToolbarVisibility,
|
||||
ToolbarVisibility,
|
||||
String?
|
||||
> {
|
||||
ToolbarVisibilityControllerFamily._()
|
||||
: super(
|
||||
retry: null,
|
||||
name: r'toolbarVisibilityControllerProvider',
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
isAutoDispose: false,
|
||||
);
|
||||
|
||||
ToolbarVisibilityControllerProvider call(String? tabId) =>
|
||||
ToolbarVisibilityControllerProvider._(argument: tabId, from: this);
|
||||
|
||||
@override
|
||||
String toString() => r'toolbarVisibilityControllerProvider';
|
||||
}
|
||||
|
||||
abstract class _$ToolbarVisibilityController
|
||||
extends $Notifier<ToolbarVisibility> {
|
||||
late final _$args = ref.$arg as String?;
|
||||
String? get tabId => _$args;
|
||||
|
||||
ToolbarVisibility build(String? tabId);
|
||||
@$mustCallSuper
|
||||
@override
|
||||
void runBuild() {
|
||||
final ref = this.ref as $Ref<ToolbarVisibility, ToolbarVisibility>;
|
||||
final element =
|
||||
ref.element
|
||||
as $ClassProviderElement<
|
||||
AnyNotifier<ToolbarVisibility, ToolbarVisibility>,
|
||||
ToolbarVisibility,
|
||||
Object?,
|
||||
Object?
|
||||
>;
|
||||
element.handleCreate(ref, () => build(_$args));
|
||||
}
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_material_design_icons/flutter_material_design_icons.dart';
|
||||
|
||||
enum BookmarkAllChoice { fast, detailed }
|
||||
|
||||
/// Dialog to select between fast (automatic) or detailed (one-by-one) bookmark import.
|
||||
Future<BookmarkAllChoice?> showBookmarkAllDialog(BuildContext context) {
|
||||
return showDialog<BookmarkAllChoice>(
|
||||
context: context,
|
||||
builder: (context) => SimpleDialog(
|
||||
title: const Text('Bookmark All Tabs'),
|
||||
children: [
|
||||
ListTile(
|
||||
leading: const Icon(MdiIcons.fastForward),
|
||||
title: const Text('Fast'),
|
||||
subtitle: const Text(
|
||||
'Automatically add all tabs to a selected folder',
|
||||
),
|
||||
onTap: () {
|
||||
Navigator.of(context).pop(BookmarkAllChoice.fast);
|
||||
},
|
||||
),
|
||||
ListTile(
|
||||
leading: const Icon(MdiIcons.stepForward),
|
||||
title: const Text('Detailed'),
|
||||
subtitle: const Text('Review and edit each bookmark individually'),
|
||||
onTap: () {
|
||||
Navigator.of(context).pop(BookmarkAllChoice.detailed);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Shows a confirmation dialog before clearing site data.
|
||||
///
|
||||
/// Returns true if the user confirms, false otherwise.
|
||||
Future<bool?> showClearSiteDataDialog(
|
||||
BuildContext context, {
|
||||
required String host,
|
||||
required String formattedTypes,
|
||||
}) {
|
||||
return showDialog<bool>(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
icon: const Icon(Icons.warning),
|
||||
title: const Text('Clear Site Data'),
|
||||
content: Text(
|
||||
'This will clear $formattedTypes for $host.\n\n'
|
||||
'You may need to log in again.',
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context, false),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () => Navigator.pop(context, true),
|
||||
child: const Text('Clear'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:weblibre/features/geckoview/features/tabs/data/database/definitions.drift.dart';
|
||||
|
||||
/// Dialog to select between extracted or full content for sharing.
|
||||
/// Shows options for extracted (reader-optimized) vs full (complete) content.
|
||||
Future<void> showContentSelectionDialog(
|
||||
BuildContext context, {
|
||||
required Widget title,
|
||||
required TabData tabData,
|
||||
required Future<void> Function(String content, String? fileName)
|
||||
shareMarkdownAction,
|
||||
}) async {
|
||||
await showDialog(
|
||||
context: context,
|
||||
builder: (context) => SimpleDialog(
|
||||
title: title,
|
||||
children: [
|
||||
ListTile(
|
||||
title: const Text('Extracted Content'),
|
||||
subtitle: const Text(
|
||||
'Reader-optimized content without navigation and ads',
|
||||
),
|
||||
onTap: () async {
|
||||
Navigator.of(context).pop();
|
||||
await shareMarkdownAction(
|
||||
tabData.extractedContentMarkdown!,
|
||||
tabData.title ?? tabData.url?.authority,
|
||||
);
|
||||
},
|
||||
),
|
||||
ListTile(
|
||||
title: const Text('Full Content'),
|
||||
subtitle: const Text(
|
||||
'Complete page including all elements and structure',
|
||||
),
|
||||
onTap: () async {
|
||||
Navigator.of(context).pop();
|
||||
await shareMarkdownAction(
|
||||
tabData.fullContentMarkdown!,
|
||||
tabData.title ?? tabData.url?.authority,
|
||||
);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_hooks/flutter_hooks.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:nullability/nullability.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/domain/services/browser_data.dart';
|
||||
import 'package:weblibre/features/user/data/models/general_settings.dart';
|
||||
|
||||
/// Shows a bottom sheet to select and delete browsing data.
|
||||
Future<void> showDeleteDataDialog(
|
||||
BuildContext context, {
|
||||
Set<DeleteBrowsingDataType> initialSettings = const {},
|
||||
}) {
|
||||
return showModalBottomSheet(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
builder: (context) => _DeleteDataSheet(initialSettings: initialSettings),
|
||||
);
|
||||
}
|
||||
|
||||
class _DeleteDataSheet extends HookConsumerWidget {
|
||||
final Set<DeleteBrowsingDataType> initialSettings;
|
||||
|
||||
const _DeleteDataSheet({required this.initialSettings});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final selections = useState(initialSettings);
|
||||
|
||||
return SafeArea(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(
|
||||
'Delete Browsing Data',
|
||||
style: Theme.of(context).textTheme.titleLarge,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
for (final type in DeleteBrowsingDataType.values)
|
||||
CheckboxListTile.adaptive(
|
||||
value: selections.value.contains(type),
|
||||
controlAffinity: ListTileControlAffinity.leading,
|
||||
title: Text(type.title),
|
||||
subtitle: type.description.mapNotNull(
|
||||
(description) => Text(description),
|
||||
),
|
||||
onChanged: (value) {
|
||||
if (value == true) {
|
||||
selections.value = {...selections.value, type};
|
||||
} else {
|
||||
selections.value = {...selections.value}..remove(type);
|
||||
}
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
FilledButton.icon(
|
||||
onPressed: selections.value.isEmpty
|
||||
? null
|
||||
: () async {
|
||||
await ref
|
||||
.read(browserDataServiceProvider.notifier)
|
||||
.deleteData(selections.value);
|
||||
|
||||
if (context.mounted) {
|
||||
context.pop();
|
||||
}
|
||||
},
|
||||
style: FilledButton.styleFrom(
|
||||
backgroundColor: Theme.of(context).colorScheme.error,
|
||||
foregroundColor: Theme.of(context).colorScheme.onError,
|
||||
),
|
||||
label: const Text('Delete'),
|
||||
icon: const Icon(Icons.delete_forever),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
+187
@@ -0,0 +1,187 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:file_picker/file_picker.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_hooks/flutter_hooks.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'package:weblibre/features/geckoview/features/browser/domain/services/browser_addon.dart';
|
||||
import 'package:weblibre/utils/ui_helper.dart';
|
||||
|
||||
Future<bool?> showInstallLocalAddonDialog(BuildContext context) {
|
||||
return showModalBottomSheet<bool?>(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
builder: (context) => const _InstallLocalAddonSheet(),
|
||||
);
|
||||
}
|
||||
|
||||
class _InstallLocalAddonSheet extends HookConsumerWidget {
|
||||
const _InstallLocalAddonSheet();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final selectedFile = useState<String?>(null);
|
||||
final isInstalling = useState(false);
|
||||
final errorMessage = useState<String?>(null);
|
||||
|
||||
Future<void> pickFile() async {
|
||||
try {
|
||||
final result = await FilePicker.platform.pickFiles();
|
||||
|
||||
if (result != null && result.files.isNotEmpty) {
|
||||
final path = result.files.single.path;
|
||||
if (path != null) {
|
||||
final extension = p.extension(path).toLowerCase();
|
||||
if (extension == '.xpi') {
|
||||
selectedFile.value = path;
|
||||
errorMessage.value = null;
|
||||
} else {
|
||||
errorMessage.value = 'Please select an .xpi file';
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
errorMessage.value = 'Failed to pick file: $e';
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> install() async {
|
||||
if (selectedFile.value == null) return;
|
||||
|
||||
isInstalling.value = true;
|
||||
errorMessage.value = null;
|
||||
|
||||
try {
|
||||
await ref
|
||||
.read(browserAddonServiceProvider.notifier)
|
||||
.installFromFile(selectedFile.value!);
|
||||
|
||||
if (context.mounted) {
|
||||
showInfoMessage(context, 'Extension installed successfully');
|
||||
context.pop(true);
|
||||
}
|
||||
} catch (e) {
|
||||
final errorString = e.toString();
|
||||
if (errorString.contains('NotSigned') ||
|
||||
errorString.contains('SIGNEDSTATE')) {
|
||||
errorMessage.value =
|
||||
'This extension is not signed by Mozilla. Enable "Allow unsigned extensions" in Extensions settings to install it.';
|
||||
} else {
|
||||
errorMessage.value = 'Installation failed: $errorString';
|
||||
}
|
||||
} finally {
|
||||
isInstalling.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
final fileName = selectedFile.value != null
|
||||
? p.basename(selectedFile.value!)
|
||||
: 'No file selected';
|
||||
|
||||
return SafeArea(
|
||||
child: Padding(
|
||||
padding: EdgeInsets.only(
|
||||
left: 16,
|
||||
right: 16,
|
||||
top: 16,
|
||||
bottom: MediaQuery.of(context).viewInsets.bottom + 16,
|
||||
),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(
|
||||
'Install Extension from File',
|
||||
style: Theme.of(context).textTheme.titleLarge,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
OutlinedButton.icon(
|
||||
onPressed: isInstalling.value ? null : pickFile,
|
||||
icon: const Icon(Icons.folder_open),
|
||||
label: const Text('Select XPI File'),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context).colorScheme.surfaceContainerHighest,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
selectedFile.value != null
|
||||
? Icons.extension
|
||||
: Icons.file_present_outlined,
|
||||
size: 20,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
fileName,
|
||||
style: TextStyle(
|
||||
color: selectedFile.value != null
|
||||
? null
|
||||
: Theme.of(context).colorScheme.outline,
|
||||
),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (errorMessage.value != null) ...[
|
||||
const SizedBox(height: 8),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context).colorScheme.errorContainer,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Text(
|
||||
errorMessage.value!,
|
||||
style: TextStyle(
|
||||
color: Theme.of(context).colorScheme.onErrorContainer,
|
||||
),
|
||||
maxLines: 10,
|
||||
),
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 16),
|
||||
FilledButton(
|
||||
onPressed: selectedFile.value == null || isInstalling.value
|
||||
? null
|
||||
: install,
|
||||
child: isInstalling.value
|
||||
? const SizedBox(
|
||||
height: 20,
|
||||
width: 20,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: const Text('Install'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Shows a dialog asking the user whether to keep a tab that was opened from another app.
|
||||
///
|
||||
/// Returns true if the user wants to keep the tab, false if they want to discard it.
|
||||
Future<bool?> showKeepTabDialog(BuildContext context) {
|
||||
return showDialog<bool>(
|
||||
context: context,
|
||||
builder: (context) => AlertDialog(
|
||||
title: const Text('Keep tab?'),
|
||||
content: const Text(
|
||||
'This tab was opened from another app. Do you want to keep it or discard it?',
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(false),
|
||||
child: const Text('Discard'),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () => Navigator.of(context).pop(true),
|
||||
child: const Text('Keep'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:pretty_qr_code/pretty_qr_code.dart';
|
||||
|
||||
Future<void> showQrCode(BuildContext context, String data) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
|
||||
return showDialog(
|
||||
context: context,
|
||||
builder: (context) {
|
||||
return Dialog(
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
const Text(
|
||||
'Share QR Code',
|
||||
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.onSurface,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: colorScheme.outline),
|
||||
),
|
||||
child: PrettyQrView.data(
|
||||
data: data,
|
||||
decoration: const PrettyQrDecoration(
|
||||
image: PrettyQrDecorationImage(
|
||||
image: AssetImage('assets/icon/icon.png'),
|
||||
),
|
||||
),
|
||||
//Increase level to mitigate image cutout
|
||||
errorCorrectLevel: QrErrorCorrectLevel.H,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.end,
|
||||
children: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
child: const Text('Close'),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_hooks/flutter_hooks.dart';
|
||||
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:weblibre/features/geckoview/features/bookmarks/presentation/widgets/folder_tree_picker.dart';
|
||||
|
||||
/// Bottom sheet to select a bookmark folder.
|
||||
/// Returns the selected folder GUID or null if cancelled.
|
||||
Future<String?> showSelectFolderDialog(BuildContext context) {
|
||||
return showModalBottomSheet<String>(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
builder: (context) => const _SelectFolderSheet(),
|
||||
);
|
||||
}
|
||||
|
||||
class _SelectFolderSheet extends HookConsumerWidget {
|
||||
const _SelectFolderSheet();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final selectedFolderGuid = useState(BookmarkRoot.mobile.id);
|
||||
|
||||
return SafeArea(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text(
|
||||
'Select folder',
|
||||
style: Theme.of(context).textTheme.titleLarge,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
ConstrainedBox(
|
||||
constraints: BoxConstraints(
|
||||
maxHeight: MediaQuery.of(context).size.height * 0.5,
|
||||
),
|
||||
child: SingleChildScrollView(
|
||||
child: FolderTreePicker(
|
||||
selectedFolderGuid: selectedFolderGuid,
|
||||
entryGuid: BookmarkRoot.root.id,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.end,
|
||||
children: [
|
||||
TextButton(
|
||||
onPressed: () => context.pop(),
|
||||
child: const Text('Cancel'),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
FilledButton(
|
||||
onPressed: () => context.pop(selectedFolderGuid.value),
|
||||
child: const Text('Select'),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:collection/collection.dart';
|
||||
import 'package:fast_equatable/fast_equatable.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:go_router/go_router.dart';
|
||||
import 'package:graphview/GraphView.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:nullability/nullability.dart';
|
||||
import 'package:skeletonizer/skeletonizer.dart';
|
||||
import 'package:weblibre/core/routing/routes.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/controllers/bottom_sheet.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers/selected_tab.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/presentation/widgets/tab_view/tab_preview.dart';
|
||||
import 'package:weblibre/features/geckoview/features/tabs/domain/providers.dart';
|
||||
import 'package:weblibre/features/user/domain/repositories/general_settings.dart';
|
||||
import 'package:weblibre/utils/ui_helper.dart';
|
||||
|
||||
class TabTreeDialog extends HookConsumerWidget {
|
||||
final String tabId;
|
||||
final Size childSize;
|
||||
|
||||
const TabTreeDialog(
|
||||
this.tabId, {
|
||||
super.key,
|
||||
this.childSize = const Size(200, 300),
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final selectedTabId = ref.watch(selectedTabProvider);
|
||||
final tabs = ref.watch(watchTabDescendantsProvider(tabId));
|
||||
|
||||
final graph = useMemoized(() {
|
||||
final graph = Graph()..isTree = true;
|
||||
|
||||
if (tabs.hasValue) {
|
||||
for (final MapEntry(:key, :value) in tabs.requireValue.entries) {
|
||||
if (value != null) {
|
||||
final current = Node.Id(key);
|
||||
final parent = Node.Id(value);
|
||||
|
||||
graph.addEdge(parent, current);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return graph;
|
||||
}, [EquatableValue(tabs.value), selectedTabId]);
|
||||
|
||||
final graphViewController = useMemoized(() => GraphViewController());
|
||||
|
||||
final graphAlgo = useMemoized(() {
|
||||
final config = BuchheimWalkerConfiguration()
|
||||
..siblingSeparation = 100
|
||||
..levelSeparation = 150
|
||||
..subtreeSeparation = 150
|
||||
..orientation = BuchheimWalkerConfiguration.ORIENTATION_TOP_BOTTOM;
|
||||
|
||||
return BuchheimWalkerAlgorithm(config, TreeEdgeRenderer(config));
|
||||
}, [selectedTabId]);
|
||||
|
||||
return Dialog.fullscreen(
|
||||
child: Scaffold(
|
||||
appBar: AppBar(
|
||||
backgroundColor: Theme.of(context).colorScheme.surface,
|
||||
elevation: 0,
|
||||
leading: const CloseButton(),
|
||||
),
|
||||
floatingActionButton: FloatingActionButton(
|
||||
child: const Icon(MdiIcons.target),
|
||||
onPressed: () {
|
||||
if (selectedTabId != null) {
|
||||
final node = graph.nodes.firstWhereOrNull(
|
||||
(element) => element.key?.value == selectedTabId,
|
||||
);
|
||||
|
||||
if (node != null) {
|
||||
graphViewController.animateToNode(ValueKey(selectedTabId));
|
||||
} else {
|
||||
showErrorMessage(
|
||||
context,
|
||||
'The current tab is not part of this tree',
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
),
|
||||
extendBodyBehindAppBar: true,
|
||||
body: Skeletonizer(
|
||||
enabled: !tabs.hasValue || tabs.value?.isEmpty == true,
|
||||
child: Skeleton.replace(
|
||||
replacement: const Bone.square(),
|
||||
child: GraphView.builder(
|
||||
graph: graph,
|
||||
algorithm: graphAlgo,
|
||||
controller: graphViewController,
|
||||
initialNode: selectedTabId.mapNotNull((tabId) => ValueKey(tabId)),
|
||||
paint: Paint()
|
||||
..color = Theme.of(context).colorScheme.outline
|
||||
..strokeWidth = 1
|
||||
..style = PaintingStyle.stroke,
|
||||
builder: (Node node) {
|
||||
final id = node.key!.value as String;
|
||||
return SizedBox.fromSize(
|
||||
size: childSize,
|
||||
child: SingleGridTabPreview(
|
||||
key: ValueKey(id),
|
||||
tabId: id,
|
||||
activeTabId: selectedTabId,
|
||||
onClose: () {
|
||||
final tabViewBottomSheet = ref
|
||||
.read(generalSettingsWithDefaultsProvider)
|
||||
.tabViewBottomSheet;
|
||||
|
||||
if (tabViewBottomSheet) {
|
||||
ref
|
||||
.read(bottomSheetControllerProvider.notifier)
|
||||
.requestDismiss();
|
||||
}
|
||||
|
||||
const BrowserRoute().go(context);
|
||||
},
|
||||
onBeforeDelete: () {
|
||||
if (graph.nodes.length <= 2) {
|
||||
context.pop();
|
||||
}
|
||||
},
|
||||
sourceSearchQuery: null,
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'dart:math' as math;
|
||||
|
||||
import 'package:copy_with_extension/copy_with_extension.dart';
|
||||
import 'package:fast_equatable/fast_equatable.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
part 'browser_viewport_toolbar_insets.g.dart';
|
||||
|
||||
@CopyWith()
|
||||
class BrowserViewportToolbarInsetsState with FastEquatable {
|
||||
final int dynamicToolbarMaxHeightPx;
|
||||
final int verticalClippingPx;
|
||||
|
||||
BrowserViewportToolbarInsetsState({
|
||||
this.dynamicToolbarMaxHeightPx = 0,
|
||||
this.verticalClippingPx = 0,
|
||||
});
|
||||
|
||||
static final zero = BrowserViewportToolbarInsetsState();
|
||||
|
||||
int get effectiveBottomInsetPx =>
|
||||
math.max(0, dynamicToolbarMaxHeightPx + verticalClippingPx);
|
||||
|
||||
@override
|
||||
List<Object?> get hashParameters => [
|
||||
dynamicToolbarMaxHeightPx,
|
||||
verticalClippingPx,
|
||||
];
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
class BrowserViewportToolbarInsetsController
|
||||
extends _$BrowserViewportToolbarInsetsController {
|
||||
@override
|
||||
BrowserViewportToolbarInsetsState build() {
|
||||
return BrowserViewportToolbarInsetsState.zero;
|
||||
}
|
||||
|
||||
void setDynamicToolbarMaxHeight(int heightPx) {
|
||||
if (state.dynamicToolbarMaxHeightPx == heightPx) {
|
||||
return;
|
||||
}
|
||||
|
||||
state = state.copyWith(dynamicToolbarMaxHeightPx: heightPx);
|
||||
}
|
||||
|
||||
void setVerticalClipping(int clippingPx) {
|
||||
if (state.verticalClippingPx == clippingPx) {
|
||||
return;
|
||||
}
|
||||
|
||||
state = state.copyWith(verticalClippingPx: clippingPx);
|
||||
}
|
||||
|
||||
void reset() {
|
||||
if (state == BrowserViewportToolbarInsetsState.zero) {
|
||||
return;
|
||||
}
|
||||
|
||||
state = BrowserViewportToolbarInsetsState.zero;
|
||||
}
|
||||
}
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'browser_viewport_toolbar_insets.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// CopyWithGenerator
|
||||
// **************************************************************************
|
||||
|
||||
abstract class _$BrowserViewportToolbarInsetsStateCWProxy {
|
||||
BrowserViewportToolbarInsetsState dynamicToolbarMaxHeightPx(
|
||||
int dynamicToolbarMaxHeightPx,
|
||||
);
|
||||
|
||||
BrowserViewportToolbarInsetsState verticalClippingPx(int verticalClippingPx);
|
||||
|
||||
/// Creates a new instance with the provided field values.
|
||||
/// Passing `null` to a nullable field nullifies it, while `null` for a non-nullable field is ignored. To update a single field use `BrowserViewportToolbarInsetsState(...).copyWith.fieldName(value)`.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// BrowserViewportToolbarInsetsState(...).copyWith(id: 12, name: "My name")
|
||||
/// ```
|
||||
BrowserViewportToolbarInsetsState call({
|
||||
int dynamicToolbarMaxHeightPx,
|
||||
int verticalClippingPx,
|
||||
});
|
||||
}
|
||||
|
||||
/// Callable proxy for `copyWith` functionality.
|
||||
/// Use as `instanceOfBrowserViewportToolbarInsetsState.copyWith(...)` or call `instanceOfBrowserViewportToolbarInsetsState.copyWith.fieldName(value)` for a single field.
|
||||
class _$BrowserViewportToolbarInsetsStateCWProxyImpl
|
||||
implements _$BrowserViewportToolbarInsetsStateCWProxy {
|
||||
const _$BrowserViewportToolbarInsetsStateCWProxyImpl(this._value);
|
||||
|
||||
final BrowserViewportToolbarInsetsState _value;
|
||||
|
||||
@override
|
||||
BrowserViewportToolbarInsetsState dynamicToolbarMaxHeightPx(
|
||||
int dynamicToolbarMaxHeightPx,
|
||||
) => call(dynamicToolbarMaxHeightPx: dynamicToolbarMaxHeightPx);
|
||||
|
||||
@override
|
||||
BrowserViewportToolbarInsetsState verticalClippingPx(
|
||||
int verticalClippingPx,
|
||||
) => call(verticalClippingPx: verticalClippingPx);
|
||||
|
||||
@override
|
||||
/// Creates a new instance with the provided field values.
|
||||
/// Passing `null` to a nullable field nullifies it, while `null` for a non-nullable field is ignored. To update a single field use `BrowserViewportToolbarInsetsState(...).copyWith.fieldName(value)`.
|
||||
///
|
||||
/// Example:
|
||||
/// ```dart
|
||||
/// BrowserViewportToolbarInsetsState(...).copyWith(id: 12, name: "My name")
|
||||
/// ```
|
||||
BrowserViewportToolbarInsetsState call({
|
||||
Object? dynamicToolbarMaxHeightPx = const $CopyWithPlaceholder(),
|
||||
Object? verticalClippingPx = const $CopyWithPlaceholder(),
|
||||
}) {
|
||||
return BrowserViewportToolbarInsetsState(
|
||||
dynamicToolbarMaxHeightPx:
|
||||
dynamicToolbarMaxHeightPx == const $CopyWithPlaceholder() ||
|
||||
dynamicToolbarMaxHeightPx == null
|
||||
? _value.dynamicToolbarMaxHeightPx
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: dynamicToolbarMaxHeightPx as int,
|
||||
verticalClippingPx:
|
||||
verticalClippingPx == const $CopyWithPlaceholder() ||
|
||||
verticalClippingPx == null
|
||||
? _value.verticalClippingPx
|
||||
// ignore: cast_nullable_to_non_nullable
|
||||
: verticalClippingPx as int,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
extension $BrowserViewportToolbarInsetsStateCopyWith
|
||||
on BrowserViewportToolbarInsetsState {
|
||||
/// Returns a callable class used to build a new instance with modified fields.
|
||||
/// Example: `instanceOfBrowserViewportToolbarInsetsState.copyWith(...)` or `instanceOfBrowserViewportToolbarInsetsState.copyWith.fieldName(...)`.
|
||||
// ignore: library_private_types_in_public_api
|
||||
_$BrowserViewportToolbarInsetsStateCWProxy get copyWith =>
|
||||
_$BrowserViewportToolbarInsetsStateCWProxyImpl(this);
|
||||
}
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
|
||||
@ProviderFor(BrowserViewportToolbarInsetsController)
|
||||
final browserViewportToolbarInsetsControllerProvider =
|
||||
BrowserViewportToolbarInsetsControllerProvider._();
|
||||
|
||||
final class BrowserViewportToolbarInsetsControllerProvider
|
||||
extends
|
||||
$NotifierProvider<
|
||||
BrowserViewportToolbarInsetsController,
|
||||
BrowserViewportToolbarInsetsState
|
||||
> {
|
||||
BrowserViewportToolbarInsetsControllerProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'browserViewportToolbarInsetsControllerProvider',
|
||||
isAutoDispose: false,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() =>
|
||||
_$browserViewportToolbarInsetsControllerHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
BrowserViewportToolbarInsetsController create() =>
|
||||
BrowserViewportToolbarInsetsController();
|
||||
|
||||
/// {@macro riverpod.override_with_value}
|
||||
Override overrideWithValue(BrowserViewportToolbarInsetsState value) {
|
||||
return $ProviderOverride(
|
||||
origin: this,
|
||||
providerOverride: $SyncValueProvider<BrowserViewportToolbarInsetsState>(
|
||||
value,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _$browserViewportToolbarInsetsControllerHash() =>
|
||||
r'ae6444dc84383bef7d957e3bbd1c48d9ebba15ec';
|
||||
|
||||
abstract class _$BrowserViewportToolbarInsetsController
|
||||
extends $Notifier<BrowserViewportToolbarInsetsState> {
|
||||
BrowserViewportToolbarInsetsState build();
|
||||
@$mustCallSuper
|
||||
@override
|
||||
void runBuild() {
|
||||
final ref =
|
||||
this.ref
|
||||
as $Ref<
|
||||
BrowserViewportToolbarInsetsState,
|
||||
BrowserViewportToolbarInsetsState
|
||||
>;
|
||||
final element =
|
||||
ref.element
|
||||
as $ClassProviderElement<
|
||||
AnyNotifier<
|
||||
BrowserViewportToolbarInsetsState,
|
||||
BrowserViewportToolbarInsetsState
|
||||
>,
|
||||
BrowserViewportToolbarInsetsState,
|
||||
Object?,
|
||||
Object?
|
||||
>;
|
||||
element.handleCreate(ref, build);
|
||||
}
|
||||
}
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:weblibre/extensions/uri.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers/tab_state.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/domain/repositories/site_permissions.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/presentation/widgets/sheets/tracking_protection_provider.dart';
|
||||
import 'package:weblibre/features/geckoview/features/tabs/data/entities/tab_mode.dart';
|
||||
|
||||
part 'site_settings_badge_provider.g.dart';
|
||||
|
||||
/// Provider that determines whether to show the site settings badge on the tab icon.
|
||||
/// Returns true if any site-specific setting has been altered from defaults.
|
||||
@Riverpod()
|
||||
Future<bool> showSiteSettingsBadge(Ref ref) async {
|
||||
final tabState = ref.watch(selectedTabStateProvider);
|
||||
if (tabState == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check tracking protection exception
|
||||
final hasTrackingException = await ref.watch(
|
||||
hasTrackingProtectionExceptionProvider(tabState.id).future,
|
||||
);
|
||||
|
||||
if (!tabState.url.hasScheme || !tabState.url.isHttpOrHttps) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Watch site permissions
|
||||
final permissions = await ref.watch(
|
||||
sitePermissionsRepositoryProvider(
|
||||
origin: tabState.url.origin,
|
||||
isPrivate: tabState.tabMode is PrivateTabMode,
|
||||
).future,
|
||||
);
|
||||
|
||||
if (hasTrackingException) {
|
||||
return true;
|
||||
}
|
||||
// Check for altered permissions
|
||||
if (_hasAlteredPermissions(permissions)) {
|
||||
return true;
|
||||
}
|
||||
// Check for altered autoplay settings
|
||||
if (_hasAlteredAutoplay(permissions)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/// Checks if any permission has been explicitly set to allowed or blocked
|
||||
bool _hasAlteredPermissions(SitePermissions? permissions) {
|
||||
if (permissions == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check all permission fields
|
||||
final permissionStatuses = [
|
||||
permissions.camera,
|
||||
permissions.microphone,
|
||||
permissions.location,
|
||||
permissions.notification,
|
||||
permissions.persistentStorage,
|
||||
permissions.crossOriginStorageAccess,
|
||||
permissions.mediaKeySystemAccess,
|
||||
permissions.localDeviceAccess,
|
||||
permissions.localNetworkAccess,
|
||||
];
|
||||
|
||||
return permissionStatuses.any(
|
||||
(status) =>
|
||||
status != null &&
|
||||
(status == SitePermissionStatus.allowed ||
|
||||
status == SitePermissionStatus.blocked),
|
||||
);
|
||||
}
|
||||
|
||||
/// Checks if autoplay settings differ from defaults
|
||||
/// Default: autoplayAudible = blocked (null), autoplayInaudible = allowed (null)
|
||||
bool _hasAlteredAutoplay(SitePermissions? permissions) {
|
||||
if (permissions == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
final audible = permissions.autoplayAudible;
|
||||
final inaudible = permissions.autoplayInaudible;
|
||||
|
||||
// Check if audible differs from default (null or blocked)
|
||||
final audibleAltered = audible != null && audible != AutoplayStatus.blocked;
|
||||
|
||||
// Check if inaudible differs from default (null or allowed)
|
||||
final inaudibleAltered =
|
||||
inaudible != null && inaudible != AutoplayStatus.allowed;
|
||||
|
||||
return audibleAltered || inaudibleAltered;
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'site_settings_badge_provider.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
// ignore_for_file: type=lint, type=warning
|
||||
/// Provider that determines whether to show the site settings badge on the tab icon.
|
||||
/// Returns true if any site-specific setting has been altered from defaults.
|
||||
|
||||
@ProviderFor(showSiteSettingsBadge)
|
||||
final showSiteSettingsBadgeProvider = ShowSiteSettingsBadgeProvider._();
|
||||
|
||||
/// Provider that determines whether to show the site settings badge on the tab icon.
|
||||
/// Returns true if any site-specific setting has been altered from defaults.
|
||||
|
||||
final class ShowSiteSettingsBadgeProvider
|
||||
extends $FunctionalProvider<AsyncValue<bool>, bool, FutureOr<bool>>
|
||||
with $FutureModifier<bool>, $FutureProvider<bool> {
|
||||
/// Provider that determines whether to show the site settings badge on the tab icon.
|
||||
/// Returns true if any site-specific setting has been altered from defaults.
|
||||
ShowSiteSettingsBadgeProvider._()
|
||||
: super(
|
||||
from: null,
|
||||
argument: null,
|
||||
retry: null,
|
||||
name: r'showSiteSettingsBadgeProvider',
|
||||
isAutoDispose: true,
|
||||
dependencies: null,
|
||||
$allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@override
|
||||
String debugGetCreateSourceHash() => _$showSiteSettingsBadgeHash();
|
||||
|
||||
@$internal
|
||||
@override
|
||||
$FutureProviderElement<bool> $createElement($ProviderPointer pointer) =>
|
||||
$FutureProviderElement(pointer);
|
||||
|
||||
@override
|
||||
FutureOr<bool> create(Ref ref) {
|
||||
return showSiteSettingsBadge(ref);
|
||||
}
|
||||
}
|
||||
|
||||
String _$showSiteSettingsBadgeHash() =>
|
||||
r'c68e3b37b6f25e02779123b3f642a58dc98ba3a7';
|
||||
+1333
File diff suppressed because it is too large.
Load diff
+127
@@ -0,0 +1,127 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_hooks/flutter_hooks.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:weblibre/core/routing/routes.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers/tab_state.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/presentation/controllers/tab_view_controllers.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/presentation/widgets/tab_view/tab_grid_view.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/presentation/widgets/tab_view/tab_list_view.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/presentation/widgets/tab_view/tab_tree_view.dart';
|
||||
import 'package:weblibre/features/sync/domain/repositories/sync.dart';
|
||||
import 'package:weblibre/features/user/domain/repositories/general_settings.dart';
|
||||
import 'package:weblibre/presentation/hooks/scroll_visibility.dart';
|
||||
|
||||
class TabViewScreen extends HookConsumerWidget {
|
||||
const TabViewScreen({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final disableAnimations = MediaQuery.disableAnimationsOf(context);
|
||||
final tabsViewMode = ref.watch(tabsViewModeControllerProvider);
|
||||
final tabsReorderable = ref.watch(tabsReorderableControllerProvider);
|
||||
|
||||
final isSyncedScope = ref.watch(
|
||||
effectiveTabsTrayScopeProvider.select(
|
||||
(scope) => scope == TabsTrayScope.synced,
|
||||
),
|
||||
);
|
||||
|
||||
final effectiveTabsViewMode = isSyncedScope
|
||||
? TabsViewMode.list
|
||||
: tabsViewMode;
|
||||
|
||||
final scrollController = useScrollController(keys: [tabsReorderable]);
|
||||
|
||||
// Track FAB visibility based on scroll direction
|
||||
final isFabVisible = useScrollVisibility(
|
||||
scrollController,
|
||||
disableAnimations: disableAnimations,
|
||||
);
|
||||
|
||||
return Dialog.fullscreen(
|
||||
child: Scaffold(
|
||||
body: SafeArea(
|
||||
child: switch (effectiveTabsViewMode) {
|
||||
TabsViewMode.list => ViewTabListWidget(
|
||||
key: ValueKey(tabsReorderable),
|
||||
scrollController: scrollController,
|
||||
tabsReorderable: tabsReorderable,
|
||||
showNewTabFab: false,
|
||||
onClose: () {
|
||||
const BrowserRoute().go(context);
|
||||
},
|
||||
),
|
||||
TabsViewMode.grid => ViewTabGridWidget(
|
||||
key: ValueKey(tabsReorderable),
|
||||
scrollController: scrollController,
|
||||
tabsReorderable: tabsReorderable,
|
||||
showNewTabFab: false,
|
||||
onClose: () {
|
||||
const BrowserRoute().go(context);
|
||||
},
|
||||
),
|
||||
TabsViewMode.tree => ViewTabTreesWidget(
|
||||
scrollController: scrollController,
|
||||
showNewTabFab: false,
|
||||
onClose: () {
|
||||
const BrowserRoute().go(context);
|
||||
},
|
||||
),
|
||||
},
|
||||
),
|
||||
floatingActionButton: isSyncedScope
|
||||
? null
|
||||
: AnimatedSlide(
|
||||
duration: disableAnimations
|
||||
? Duration.zero
|
||||
: const Duration(milliseconds: 200),
|
||||
offset: isFabVisible.value ? Offset.zero : const Offset(0, 2),
|
||||
curve: Curves.easeInOut,
|
||||
child: AnimatedOpacity(
|
||||
duration: disableAnimations
|
||||
? Duration.zero
|
||||
: const Duration(milliseconds: 200),
|
||||
opacity: isFabVisible.value ? 1.0 : 0.0,
|
||||
child: FloatingActionButton(
|
||||
onPressed: () async {
|
||||
final settings = ref.read(
|
||||
generalSettingsWithDefaultsProvider,
|
||||
);
|
||||
|
||||
await SearchRoute(
|
||||
tabType:
|
||||
ref.read(selectedTabTypeProvider) ??
|
||||
settings.effectiveDefaultCreateTabType,
|
||||
).push(context);
|
||||
|
||||
if (context.mounted) {
|
||||
const BrowserRoute().go(context);
|
||||
}
|
||||
},
|
||||
child: const Icon(Icons.add),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers/tab_state.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/repositories/tab.dart';
|
||||
import 'package:weblibre/utils/ui_helper.dart' as ui_helper;
|
||||
|
||||
int countIsolatedGroupsRemovedByClosingTabs(
|
||||
WidgetRef ref,
|
||||
Iterable<String> tabIds,
|
||||
) {
|
||||
final idsToClose = tabIds.toSet();
|
||||
if (idsToClose.isEmpty) return 0;
|
||||
|
||||
final allStates = ref.read(tabStatesProvider);
|
||||
final isolatedCloseCounts = <String, int>{};
|
||||
|
||||
for (final tabId in idsToClose) {
|
||||
final contextId = allStates[tabId]?.isolationContextId;
|
||||
if (contextId != null) {
|
||||
isolatedCloseCounts.update(
|
||||
contextId,
|
||||
(count) => count + 1,
|
||||
ifAbsent: () => 1,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return isolatedCloseCounts.entries.where((entry) {
|
||||
final totalInGroup = allStates.values
|
||||
.where((state) => state.isolationContextId == entry.key)
|
||||
.length;
|
||||
return totalInGroup == entry.value;
|
||||
}).length;
|
||||
}
|
||||
|
||||
Future<bool> confirmBulkTabCloseIfNeeded(
|
||||
BuildContext context,
|
||||
WidgetRef ref,
|
||||
Iterable<String> tabIds,
|
||||
) async {
|
||||
final groupsToDelete = countIsolatedGroupsRemovedByClosingTabs(ref, tabIds);
|
||||
if (groupsToDelete <= 0) return true;
|
||||
if (!context.mounted) return false;
|
||||
|
||||
return ui_helper.confirmIsolatedTabClose(context, groupCount: groupsToDelete);
|
||||
}
|
||||
|
||||
Future<bool> closeTabsWithConfirmation(
|
||||
BuildContext context,
|
||||
WidgetRef ref,
|
||||
Iterable<String> tabIds,
|
||||
) async {
|
||||
final idsToClose = tabIds.toSet().toList();
|
||||
if (idsToClose.isEmpty) return false;
|
||||
|
||||
final tabRepository = ref.read(tabRepositoryProvider.notifier);
|
||||
|
||||
if (!await confirmBulkTabCloseIfNeeded(context, ref, idsToClose)) {
|
||||
return false;
|
||||
}
|
||||
if (!context.mounted) {
|
||||
return false;
|
||||
}
|
||||
|
||||
await tabRepository.closeTabs(idsToClose);
|
||||
return true;
|
||||
}
|
||||
+343
@@ -0,0 +1,343 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_material_design_icons/flutter_material_design_icons.dart';
|
||||
import 'package:flutter_svg/svg.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:weblibre/core/design/app_colors.dart';
|
||||
import 'package:weblibre/core/routing/routes.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers/tab_list.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/repositories/tab.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/presentation/providers/browser_viewport_toolbar_insets.dart';
|
||||
import 'package:weblibre/features/geckoview/features/tabs/data/models/container_data.dart';
|
||||
import 'package:weblibre/features/geckoview/features/tabs/domain/providers/selected_container.dart';
|
||||
import 'package:weblibre/features/geckoview/features/tabs/utils/container_colors.dart';
|
||||
import 'package:weblibre/features/quotes/data/database/definitions.drift.dart';
|
||||
import 'package:weblibre/features/quotes/domain/providers.dart';
|
||||
import 'package:weblibre/features/user/domain/repositories/general_settings.dart';
|
||||
import 'package:weblibre/presentation/widgets/browser_page.dart';
|
||||
|
||||
class BrowserHome extends ConsumerWidget {
|
||||
const BrowserHome({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final theme = Theme.of(context);
|
||||
final colorScheme = theme.colorScheme;
|
||||
final settings = ref.watch(generalSettingsWithDefaultsProvider);
|
||||
final quoteAsync = ref.watch(randomQuoteProvider);
|
||||
final hasTabs = ref.watch(
|
||||
tabListProvider.select((tabs) => tabs.value.isNotEmpty),
|
||||
);
|
||||
final viewportToolbarInsets = ref.watch(
|
||||
browserViewportToolbarInsetsControllerProvider,
|
||||
);
|
||||
|
||||
final containerData = ref.watch(
|
||||
selectedContainerDataProvider.select((value) => value.value),
|
||||
);
|
||||
final hasContainerTabs = ref.watch(
|
||||
selectedContainerTabCountProvider.select(
|
||||
(data) => switch (data) {
|
||||
AsyncData(:final value) => value > 0,
|
||||
_ => false,
|
||||
},
|
||||
),
|
||||
);
|
||||
|
||||
final pixelRatio = MediaQuery.devicePixelRatioOf(context);
|
||||
|
||||
final bottomViewportInset =
|
||||
viewportToolbarInsets.effectiveBottomInsetPx / pixelRatio;
|
||||
|
||||
Future<void> openNewTab() {
|
||||
return SearchRoute(
|
||||
tabType: settings.effectiveDefaultCreateTabType,
|
||||
).push(context);
|
||||
}
|
||||
|
||||
Future<void> viewTabs() {
|
||||
return const TabViewRoute().push(context);
|
||||
}
|
||||
|
||||
Future<void> resumeLatestTab() async {
|
||||
await ref.read(tabRepositoryProvider.notifier).resumeLatestTab();
|
||||
}
|
||||
|
||||
Future<void> resumeLatestContainerTab() async {
|
||||
final containerId = ref.read(selectedContainerProvider);
|
||||
await ref
|
||||
.read(tabRepositoryProvider.notifier)
|
||||
.resumeLatestContainerTab(containerId);
|
||||
}
|
||||
|
||||
return BrowserPage(
|
||||
child: BrowserPageContent(
|
||||
bottomViewportInset: bottomViewportInset,
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (containerData != null)
|
||||
_ContainerHeader(container: containerData)
|
||||
else
|
||||
BrandHeader(colorScheme: colorScheme),
|
||||
const SizedBox(height: 24),
|
||||
if (!hasTabs) ...[
|
||||
Text(
|
||||
'WebLibre is ready',
|
||||
textAlign: TextAlign.center,
|
||||
style: theme.textTheme.headlineSmall?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Text(
|
||||
'A browser that respects you. Open a tab and experience the web, libre.',
|
||||
textAlign: TextAlign.center,
|
||||
style: theme.textTheme.bodyLarge?.copyWith(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
height: 1.45,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 28),
|
||||
] else if (containerData != null) ...[
|
||||
Text(
|
||||
containerData.name?.isNotEmpty == true
|
||||
? containerData.name!
|
||||
: 'Container',
|
||||
textAlign: TextAlign.center,
|
||||
style: theme.textTheme.headlineSmall?.copyWith(
|
||||
fontWeight: FontWeight.w700,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Text(
|
||||
hasContainerTabs
|
||||
? 'No matching tab selected'
|
||||
: 'No open tabs in this container',
|
||||
textAlign: TextAlign.center,
|
||||
style: theme.textTheme.bodyLarge?.copyWith(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
height: 1.45,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 28),
|
||||
],
|
||||
Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.all(20),
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.surfaceContainer.withValues(alpha: 0.9),
|
||||
borderRadius: BorderRadius.circular(28),
|
||||
border: Border.all(
|
||||
color: Color.alphaBlend(
|
||||
AppColors.brandGrey.withValues(alpha: 0.18),
|
||||
colorScheme.outlineVariant,
|
||||
),
|
||||
),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Container(
|
||||
width: 36,
|
||||
height: 36,
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surfaceContainerHigh,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: const Icon(MdiIcons.formatQuoteOpen, size: 18),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
'A thought for the road',
|
||||
style: theme.textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
),
|
||||
IconButton.filledTonal(
|
||||
tooltip: 'Refresh quote',
|
||||
onPressed: () {
|
||||
ref.invalidate(randomQuoteProvider);
|
||||
},
|
||||
icon: const Icon(Icons.refresh_rounded),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
switch (quoteAsync) {
|
||||
AsyncData(:final value) => _QuoteBlock(quote: value),
|
||||
AsyncError() => Text(
|
||||
'Open a new tab and make this space your own.',
|
||||
style: theme.textTheme.bodyLarge?.copyWith(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
height: 1.5,
|
||||
),
|
||||
),
|
||||
_ => const LinearProgressIndicator(minHeight: 3),
|
||||
},
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
Wrap(
|
||||
alignment: WrapAlignment.center,
|
||||
spacing: 12,
|
||||
runSpacing: 12,
|
||||
children: [
|
||||
if (hasTabs)
|
||||
OutlinedButton.icon(
|
||||
onPressed: viewTabs,
|
||||
icon: const Icon(Icons.tab_rounded),
|
||||
label: const Text('View tabs'),
|
||||
),
|
||||
FilledButton.icon(
|
||||
onPressed: openNewTab,
|
||||
icon: const Icon(Icons.add_rounded),
|
||||
label: const Text('New tab'),
|
||||
),
|
||||
if (hasContainerTabs)
|
||||
FilledButton.tonalIcon(
|
||||
onPressed: resumeLatestContainerTab,
|
||||
icon: const Icon(Icons.history_rounded),
|
||||
label: const Text('Resume last tab'),
|
||||
)
|
||||
else if (hasTabs && containerData == null)
|
||||
FilledButton.tonalIcon(
|
||||
onPressed: resumeLatestTab,
|
||||
icon: const Icon(Icons.history_rounded),
|
||||
label: const Text('Resume last tab'),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ContainerHeader extends StatelessWidget {
|
||||
final ContainerData container;
|
||||
|
||||
const _ContainerHeader({required this.container});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
final containerColor = container.color;
|
||||
|
||||
return Container(
|
||||
width: 112,
|
||||
height: 112,
|
||||
padding: const EdgeInsets.all(20),
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(32),
|
||||
gradient: LinearGradient(
|
||||
begin: Alignment.topLeft,
|
||||
end: Alignment.bottomRight,
|
||||
colors: [
|
||||
Color.alphaBlend(
|
||||
ContainerColors.forChip(containerColor),
|
||||
colorScheme.surfaceContainerHighest,
|
||||
),
|
||||
Color.alphaBlend(
|
||||
containerColor.withValues(alpha: 0.12),
|
||||
colorScheme.surfaceContainer,
|
||||
),
|
||||
],
|
||||
),
|
||||
border: Border.all(
|
||||
color: Color.alphaBlend(
|
||||
containerColor.withValues(alpha: 0.25),
|
||||
colorScheme.outlineVariant.withValues(alpha: 0.45),
|
||||
),
|
||||
),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: colorScheme.shadow.withValues(alpha: 0.08),
|
||||
blurRadius: 32,
|
||||
offset: const Offset(0, 18),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Center(
|
||||
child: SvgPicture.asset('assets/icon/icon.svg', width: 72, height: 72),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _QuoteBlock extends StatelessWidget {
|
||||
final Quote? quote;
|
||||
|
||||
const _QuoteBlock({required this.quote});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final colorScheme = theme.colorScheme;
|
||||
|
||||
if (quote == null) {
|
||||
return Text(
|
||||
'Open a new tab and make this space your own.',
|
||||
style: theme.textTheme.bodyLarge?.copyWith(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
height: 1.5,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'"${quote!.quote}"',
|
||||
style: theme.textTheme.bodyLarge?.copyWith(
|
||||
height: 1.55,
|
||||
color: colorScheme.onSurface,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Text(
|
||||
'- ${quote!.author}',
|
||||
style: theme.textTheme.titleSmall?.copyWith(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
if (quote!.source case final String source when source.isNotEmpty) ...[
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
source,
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
+2151
File diff suppressed because it is too large.
Load diff
+442
@@ -0,0 +1,442 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_material_design_icons/flutter_material_design_icons.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:skeletonizer/skeletonizer.dart';
|
||||
import 'package:text_scroll/text_scroll.dart';
|
||||
import 'package:weblibre/core/design/app_colors.dart';
|
||||
import 'package:weblibre/core/routing/routes.dart';
|
||||
import 'package:weblibre/extensions/uri.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/controllers/bottom_sheet.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/entities/states/tab.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers/tab_state.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/domain/entities/sheet.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/presentation/providers/site_settings_badge_provider.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/presentation/widgets/tab_icon.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/presentation/widgets/toolbar_button.dart';
|
||||
import 'package:weblibre/features/geckoview/features/tabs/data/entities/tab_mode.dart';
|
||||
import 'package:weblibre/features/user/domain/repositories/general_settings.dart';
|
||||
import 'package:weblibre/presentation/widgets/uri_breadcrumb.dart';
|
||||
|
||||
class CompactAppBarTitle extends ConsumerWidget {
|
||||
const CompactAppBarTitle({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final tabState = ref.watch(selectedTabStateProvider);
|
||||
final selectedTabType = ref.watch(selectedTabTypeProvider);
|
||||
final settings = ref.watch(generalSettingsWithDefaultsProvider);
|
||||
final isTabTuneledAsync = ref.watch(isTabTunneledProvider(tabState?.id));
|
||||
final showSiteSettingsBadge = ref.watch(
|
||||
showSiteSettingsBadgeProvider.select((value) => value.value == true),
|
||||
);
|
||||
|
||||
if (tabState == null) {
|
||||
return _EmptyAppBarAddressField(
|
||||
onTap: () async {
|
||||
await SearchRoute(
|
||||
tabType: selectedTabType ?? settings.effectiveDefaultCreateTabType,
|
||||
).push(context);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
return CompactAppBarTitleView(
|
||||
tabState: tabState,
|
||||
isTabTunneled:
|
||||
isTabTuneledAsync.hasValue && isTabTuneledAsync.value == true,
|
||||
showSiteSettingsBadge: showSiteSettingsBadge,
|
||||
longPressUrlCopy: settings.tabBarLongPressUrlCopy,
|
||||
onSiteSettingsTap: () {
|
||||
ref
|
||||
.read(bottomSheetControllerProvider.notifier)
|
||||
.show(SiteSettingsSheet(tabState: tabState));
|
||||
},
|
||||
onTitleTap: () async {
|
||||
await SearchRoute(
|
||||
tabId: tabState.id,
|
||||
searchText: _searchTextForTab(tabState),
|
||||
tabType: tabState.tabMode.toTabType(),
|
||||
).push(context);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class CompactAppBarTitleView extends StatelessWidget {
|
||||
const CompactAppBarTitleView({
|
||||
super.key,
|
||||
required this.tabState,
|
||||
required this.isTabTunneled,
|
||||
required this.showSiteSettingsBadge,
|
||||
required this.onSiteSettingsTap,
|
||||
required this.onTitleTap,
|
||||
this.tabIcon,
|
||||
this.longPressUrlCopy = true,
|
||||
});
|
||||
|
||||
final TabState tabState;
|
||||
final bool isTabTunneled;
|
||||
final bool showSiteSettingsBadge;
|
||||
final VoidCallback onSiteSettingsTap;
|
||||
final VoidCallback onTitleTap;
|
||||
final Widget? tabIcon;
|
||||
final bool longPressUrlCopy;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final appColors = AppColors.of(context);
|
||||
|
||||
return Row(
|
||||
children: [
|
||||
ToolbarButton(
|
||||
onTap: onSiteSettingsTap,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(right: 4.0),
|
||||
child: Stack(
|
||||
clipBehavior: Clip.none,
|
||||
children: [
|
||||
tabIcon ?? TabIcon(tabState: tabState, iconSize: 24),
|
||||
Positioned(
|
||||
top: -4,
|
||||
right: -4,
|
||||
child: Icon(
|
||||
MdiIcons.shieldHalfFull,
|
||||
size: 10,
|
||||
color: showSiteSettingsBadge
|
||||
? appColors.warningAmber
|
||||
: Colors.green,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: GestureDetector(
|
||||
onTap: onTitleTap,
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 12),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surfaceContainerHighest,
|
||||
borderRadius: BorderRadius.circular(24),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (tabState.tabMode is PrivateTabMode) ...[
|
||||
Icon(
|
||||
MdiIcons.dominoMask,
|
||||
color: appColors.privateTabPurple,
|
||||
size: 16,
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
] else if (tabState.tabMode is IsolatedTabMode) ...[
|
||||
Icon(
|
||||
MdiIcons.snowflake,
|
||||
color: appColors.isolatedTabTeal,
|
||||
size: 16,
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
],
|
||||
if (isTabTunneled) ...[
|
||||
const Icon(MdiIcons.tunnelOutline, size: 16),
|
||||
const SizedBox(width: 4),
|
||||
],
|
||||
_SecurityStatusIcon(tabState: tabState, size: 16),
|
||||
const SizedBox(width: 6),
|
||||
Flexible(
|
||||
child: UriBreadcrumb(
|
||||
uri: tabState.url,
|
||||
style: theme.textTheme.bodyMedium?.copyWith(
|
||||
color: theme.colorScheme.onSurface,
|
||||
),
|
||||
onTooltipTriggered: longPressUrlCopy
|
||||
? () async {
|
||||
await Clipboard.setData(
|
||||
ClipboardData(text: tabState.url.toString()),
|
||||
);
|
||||
}
|
||||
: null,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8.0),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class AppBarTitle extends ConsumerWidget {
|
||||
const AppBarTitle({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final tabState = ref.watch(selectedTabStateProvider);
|
||||
final selectedTabType = ref.watch(selectedTabTypeProvider);
|
||||
final settings = ref.watch(generalSettingsWithDefaultsProvider);
|
||||
final isTabTuneledAsync = ref.watch(isTabTunneledProvider(tabState?.id));
|
||||
final showSiteSettingsBadge = ref.watch(
|
||||
showSiteSettingsBadgeProvider.select((value) => value.value == true),
|
||||
);
|
||||
|
||||
if (tabState == null) {
|
||||
return _EmptyAppBarAddressField(
|
||||
onTap: () async {
|
||||
await SearchRoute(
|
||||
tabType: selectedTabType ?? settings.effectiveDefaultCreateTabType,
|
||||
).push(context);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
return AppBarTitleView(
|
||||
tabState: tabState,
|
||||
isTabTunneled:
|
||||
isTabTuneledAsync.hasValue && isTabTuneledAsync.value == true,
|
||||
showSiteSettingsBadge: showSiteSettingsBadge,
|
||||
longPressUrlCopy: settings.tabBarLongPressUrlCopy,
|
||||
onSiteSettingsTap: () {
|
||||
ref
|
||||
.read(bottomSheetControllerProvider.notifier)
|
||||
.show(SiteSettingsSheet(tabState: tabState));
|
||||
},
|
||||
onTitleTap: () async {
|
||||
await SearchRoute(
|
||||
tabId: tabState.id,
|
||||
searchText: _searchTextForTab(tabState),
|
||||
tabType: tabState.tabMode.toTabType(),
|
||||
).push(context);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class AppBarTitleView extends StatelessWidget {
|
||||
const AppBarTitleView({
|
||||
super.key,
|
||||
required this.tabState,
|
||||
required this.isTabTunneled,
|
||||
required this.showSiteSettingsBadge,
|
||||
required this.onSiteSettingsTap,
|
||||
required this.onTitleTap,
|
||||
required this.longPressUrlCopy,
|
||||
this.tabIcon,
|
||||
});
|
||||
|
||||
final TabState tabState;
|
||||
final bool isTabTunneled;
|
||||
final bool showSiteSettingsBadge;
|
||||
final VoidCallback onSiteSettingsTap;
|
||||
final VoidCallback onTitleTap;
|
||||
final Widget? tabIcon;
|
||||
final bool longPressUrlCopy;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
final appColors = AppColors.of(context);
|
||||
|
||||
return Row(
|
||||
children: [
|
||||
ToolbarButton(
|
||||
onTap: onSiteSettingsTap,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.only(right: 4.0),
|
||||
child: Stack(
|
||||
clipBehavior: Clip.none,
|
||||
children: [
|
||||
tabIcon ?? TabIcon(tabState: tabState, iconSize: 24),
|
||||
Positioned(
|
||||
top: -4,
|
||||
right: -4,
|
||||
child: Icon(
|
||||
MdiIcons.shieldHalfFull,
|
||||
size: 10,
|
||||
color: showSiteSettingsBadge
|
||||
? appColors.warningAmber
|
||||
: Colors.green,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
Expanded(
|
||||
child: GestureDetector(
|
||||
onTap: onTitleTap,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Skeletonizer(
|
||||
enabled: tabState.title.isEmpty,
|
||||
child: Skeleton.replace(
|
||||
replacement: const Padding(
|
||||
padding: EdgeInsets.only(right: 4, top: 1, bottom: 1),
|
||||
child: Bone.text(),
|
||||
),
|
||||
child: TextScroll(
|
||||
key: ValueKey(tabState.title),
|
||||
tabState.title,
|
||||
style: theme.textTheme.bodyLarge?.copyWith(
|
||||
color: theme.colorScheme.onSurface,
|
||||
),
|
||||
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: [
|
||||
if (tabState.tabMode is PrivateTabMode) ...[
|
||||
Icon(
|
||||
MdiIcons.dominoMask,
|
||||
color: appColors.privateTabPurple,
|
||||
size: 14,
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
] else if (tabState.tabMode is IsolatedTabMode) ...[
|
||||
Icon(
|
||||
MdiIcons.snowflake,
|
||||
color: appColors.isolatedTabTeal,
|
||||
size: 14,
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
],
|
||||
if (isTabTunneled) ...[
|
||||
const Icon(MdiIcons.tunnelOutline, size: 14),
|
||||
const SizedBox(width: 4),
|
||||
],
|
||||
_SecurityStatusIcon(tabState: tabState, size: 14),
|
||||
const SizedBox(width: 4),
|
||||
Expanded(
|
||||
child: UriBreadcrumb(
|
||||
uri: tabState.url,
|
||||
style: theme.textTheme.bodyMedium?.copyWith(
|
||||
color: theme.colorScheme.onSurface,
|
||||
),
|
||||
onTooltipTriggered: longPressUrlCopy
|
||||
? () async {
|
||||
await Clipboard.setData(
|
||||
ClipboardData(text: tabState.url.toString()),
|
||||
);
|
||||
}
|
||||
: null,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8.0),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _SecurityStatusIcon extends StatelessWidget {
|
||||
const _SecurityStatusIcon({required this.tabState, required this.size});
|
||||
|
||||
final TabState tabState;
|
||||
final double size;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (tabState.url.isHttp) {
|
||||
return Icon(
|
||||
MdiIcons.lockOff,
|
||||
color: Theme.of(context).colorScheme.error,
|
||||
size: size,
|
||||
);
|
||||
} else if (tabState.readerableState.active) {
|
||||
return Icon(MdiIcons.lockMinus, size: size);
|
||||
} else if (!tabState.securityInfoState.secure) {
|
||||
return Icon(
|
||||
MdiIcons.lockAlert,
|
||||
color: Theme.of(context).colorScheme.errorContainer,
|
||||
size: size,
|
||||
);
|
||||
} else if (!tabState.isLoading) {
|
||||
return Icon(MdiIcons.lock, size: size);
|
||||
}
|
||||
|
||||
return Icon(MdiIcons.timerSand, size: size);
|
||||
}
|
||||
}
|
||||
|
||||
class _EmptyAppBarAddressField extends StatelessWidget {
|
||||
const _EmptyAppBarAddressField({required this.onTap});
|
||||
|
||||
final VoidCallback onTap;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 8),
|
||||
child: GestureDetector(
|
||||
onTap: onTap,
|
||||
child: Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 12),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.surfaceContainerHighest,
|
||||
borderRadius: BorderRadius.circular(24),
|
||||
),
|
||||
alignment: Alignment.center,
|
||||
child: Text(
|
||||
'Search or enter URL',
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: theme.textTheme.bodyMedium?.copyWith(
|
||||
color: theme.colorScheme.onSurface,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
String _searchTextForTab(TabState tabState) {
|
||||
final searchText = tabState.url.scheme == 'about'
|
||||
? ''
|
||||
: tabState.url.toString();
|
||||
|
||||
return searchText.isEmpty ? SearchRoute.emptySearchText : searchText;
|
||||
}
|
||||
+700
@@ -0,0 +1,700 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:fast_equatable/fast_equatable.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.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:weblibre/core/design/app_colors.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/controllers/bottom_sheet.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers/selected_tab.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/repositories/tab.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/domain/entities/sheet.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/domain/providers.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/features/contextual_toolbar/data/providers/toolbar_button_configs.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/features/contextual_toolbar/domain/entities/toolbar_button_id.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/features/contextual_toolbar/presentation/widgets/contextual_bar_buttons.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/features/contextual_toolbar/presentation/widgets/contextual_toolbar.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/presentation/controllers/toolbar_visibility.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/presentation/widgets/browser_modules/app_bar_title.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/presentation/widgets/tab_icon.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/presentation/widgets/tab_menu.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/presentation/widgets/toolbar_button.dart';
|
||||
import 'package:weblibre/features/geckoview/features/readerview/presentation/controllers/readerable.dart';
|
||||
import 'package:weblibre/features/geckoview/features/readerview/presentation/widgets/reader_button.dart';
|
||||
import 'package:weblibre/features/geckoview/features/tabs/data/entities/tab_mode.dart';
|
||||
import 'package:weblibre/features/geckoview/features/tabs/domain/providers.dart';
|
||||
import 'package:weblibre/features/geckoview/features/tabs/utils/container_colors.dart';
|
||||
import 'package:weblibre/features/user/data/models/general_settings.dart';
|
||||
import 'package:weblibre/features/user/domain/repositories/general_settings.dart';
|
||||
import 'package:weblibre/presentation/widgets/selectable_chips.dart';
|
||||
import 'package:weblibre/presentation/widgets/url_icon.dart';
|
||||
|
||||
class BrowserTopAppBar extends StatelessWidget {
|
||||
final bool showMainToolbar;
|
||||
final bool showContextualToolbar;
|
||||
final bool showQuickTabSwitcherBar;
|
||||
final bool isSmallWebMode;
|
||||
final bool enableGestures;
|
||||
|
||||
late final BrowserTabBar _tabBar;
|
||||
late final _size = Size.fromHeight(_tabBar.getToolbarHeight());
|
||||
|
||||
BrowserTopAppBar({
|
||||
super.key,
|
||||
required this.showMainToolbar,
|
||||
required this.showContextualToolbar,
|
||||
required this.showQuickTabSwitcherBar,
|
||||
required this.isSmallWebMode,
|
||||
this.enableGestures = true,
|
||||
}) {
|
||||
_tabBar = BrowserTabBar(
|
||||
showMainToolbar: showMainToolbar,
|
||||
displayedSheet: null,
|
||||
showContextualToolbar: false,
|
||||
showQuickTabSwitcherBar: false,
|
||||
isSmallWebMode: isSmallWebMode,
|
||||
enableGestures: enableGestures,
|
||||
hideMainToolbarButtonsDuplicatedInContextualToolbar:
|
||||
showContextualToolbar,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SafeArea(
|
||||
child: SizedBox(height: preferredSize.height, child: _tabBar),
|
||||
);
|
||||
}
|
||||
|
||||
Size get preferredSize => _size;
|
||||
}
|
||||
|
||||
class BrowserBottomAppBar extends StatelessWidget {
|
||||
final bool showMainToolbar;
|
||||
final bool showContextualToolbar;
|
||||
final bool showQuickTabSwitcherBar;
|
||||
final bool isSmallWebMode;
|
||||
final Sheet? displayedSheet;
|
||||
final bool enableGestures;
|
||||
|
||||
late final BrowserTabBar _tabBar;
|
||||
late final _size = Size.fromHeight(_tabBar.getToolbarHeight());
|
||||
|
||||
BrowserBottomAppBar({
|
||||
super.key,
|
||||
required this.showMainToolbar,
|
||||
required this.displayedSheet,
|
||||
required this.showContextualToolbar,
|
||||
required this.showQuickTabSwitcherBar,
|
||||
required this.isSmallWebMode,
|
||||
this.enableGestures = true,
|
||||
}) {
|
||||
_tabBar = BrowserTabBar(
|
||||
displayedSheet: displayedSheet,
|
||||
showMainToolbar: showMainToolbar,
|
||||
showContextualToolbar: showContextualToolbar,
|
||||
showQuickTabSwitcherBar: showQuickTabSwitcherBar,
|
||||
isSmallWebMode: isSmallWebMode,
|
||||
enableGestures: enableGestures,
|
||||
hideMainToolbarButtonsDuplicatedInContextualToolbar:
|
||||
showContextualToolbar,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final bottomPadding = MediaQuery.of(context).padding.bottom;
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
|
||||
return Material(
|
||||
shadowColor: Colors.transparent,
|
||||
surfaceTintColor: Colors.transparent,
|
||||
color: colorScheme.surfaceContainer,
|
||||
child: Padding(
|
||||
padding: EdgeInsets.only(bottom: bottomPadding),
|
||||
child: SizedBox(height: _size.height, child: _tabBar),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Size get preferredSize => _size;
|
||||
}
|
||||
|
||||
class BrowserTabBar extends HookConsumerWidget {
|
||||
final bool showMainToolbar;
|
||||
final bool showContextualToolbar;
|
||||
final bool showQuickTabSwitcherBar;
|
||||
final Sheet? displayedSheet;
|
||||
final bool hideMainToolbarButtonsDuplicatedInContextualToolbar;
|
||||
final bool isSmallWebMode;
|
||||
final bool enableGestures;
|
||||
|
||||
const BrowserTabBar({
|
||||
super.key,
|
||||
required this.showMainToolbar,
|
||||
required this.displayedSheet,
|
||||
required this.showContextualToolbar,
|
||||
required this.showQuickTabSwitcherBar,
|
||||
required this.isSmallWebMode,
|
||||
required this.enableGestures,
|
||||
this.hideMainToolbarButtonsDuplicatedInContextualToolbar = false,
|
||||
});
|
||||
|
||||
static const contextualToolabarHeight = 54.0;
|
||||
static const quickTabSwitcherHeight = 48.0;
|
||||
|
||||
bool get displayAppBar =>
|
||||
showMainToolbar &&
|
||||
(!showContextualToolbar || displayedSheet is! ViewTabsSheet);
|
||||
|
||||
bool get displayQuickTabSwitcher =>
|
||||
showQuickTabSwitcherBar && displayedSheet is! ViewTabsSheet;
|
||||
|
||||
double getToolbarHeight() {
|
||||
var height = 0.0;
|
||||
|
||||
if (displayAppBar) {
|
||||
height += kToolbarHeight;
|
||||
}
|
||||
|
||||
if (showContextualToolbar) {
|
||||
height += contextualToolabarHeight;
|
||||
}
|
||||
|
||||
if (displayQuickTabSwitcher) {
|
||||
height += quickTabSwitcherHeight;
|
||||
}
|
||||
|
||||
return height;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final selectedTabId = ref.watch(selectedTabProvider);
|
||||
final settings = ref.watch(generalSettingsWithDefaultsProvider);
|
||||
|
||||
// Determine which buttons are actually visible in the contextual toolbar
|
||||
// so we only hide them from the main toolbar when they're genuinely present there.
|
||||
final contextualConfigs = ref
|
||||
.watch(effectiveToolbarButtonConfigsProvider)
|
||||
.value;
|
||||
|
||||
final tabsCountInContextual =
|
||||
hideMainToolbarButtonsDuplicatedInContextualToolbar &&
|
||||
contextualConfigs.any(
|
||||
(c) => c.buttonId == ToolbarButtonId.tabsCount.name && c.isVisible,
|
||||
);
|
||||
|
||||
final menuInContextual =
|
||||
hideMainToolbarButtonsDuplicatedInContextualToolbar &&
|
||||
contextualConfigs.any(
|
||||
(c) =>
|
||||
c.buttonId == ToolbarButtonId.navigationMenu.name && c.isVisible,
|
||||
);
|
||||
|
||||
final showMainToolbarTabsCount = !isSmallWebMode && !tabsCountInContextual;
|
||||
final showMainToolbarNavigationButton =
|
||||
!isSmallWebMode && !menuInContextual;
|
||||
|
||||
final containerColor = ref.watch(
|
||||
watchTabContainerDataProvider(
|
||||
selectedTabId,
|
||||
).select((data) => data.value?.color),
|
||||
);
|
||||
|
||||
final quickTabSwitcherMode = settings.effectiveUiQuickTabSwitcherMode();
|
||||
|
||||
final tabBarPosition = settings.tabBarPosition;
|
||||
|
||||
final dragStartPosition = useRef(Offset.zero);
|
||||
|
||||
final showTabTitle = displayedSheet is! ViewTabsSheet;
|
||||
|
||||
final backgroundColor =
|
||||
(settings.showContainerUi &&
|
||||
containerColor != null &&
|
||||
displayedSheet is! ViewTabsSheet)
|
||||
? ContainerColors.forAppBar(containerColor)
|
||||
: null;
|
||||
|
||||
return BrowserTabBarView(
|
||||
showMainToolbar: showMainToolbar,
|
||||
showContextualToolbar: showContextualToolbar,
|
||||
showQuickTabSwitcherBar: showQuickTabSwitcherBar,
|
||||
displayAppBar: displayAppBar,
|
||||
displayQuickTabSwitcher: displayQuickTabSwitcher,
|
||||
backgroundColor: backgroundColor,
|
||||
title: showTabTitle
|
||||
? settings.tabBarLayout == TabBarLayout.compact
|
||||
? const CompactAppBarTitle()
|
||||
: const AppBarTitle()
|
||||
: null,
|
||||
actions: [
|
||||
if (isSmallWebMode)
|
||||
ReaderButton(
|
||||
buttonBuilder: (isLoading, readerActive, icon) => ToolbarButton(
|
||||
onTap: isLoading
|
||||
? null
|
||||
: () async {
|
||||
await ref
|
||||
.read(readerableScreenControllerProvider.notifier)
|
||||
.toggleReaderView(!readerActive);
|
||||
},
|
||||
child: icon,
|
||||
),
|
||||
),
|
||||
if (showMainToolbarTabsCount)
|
||||
TabsCountButton(
|
||||
selectedTabId: selectedTabId,
|
||||
displayedSheet: displayedSheet,
|
||||
showLongPressMenu: true,
|
||||
),
|
||||
if (showMainToolbarNavigationButton)
|
||||
NavigationMenuButton(selectedTabId: selectedTabId),
|
||||
],
|
||||
quickTabSwitcher: QuickTabSwitcher(
|
||||
quickTabSwitcherMode: quickTabSwitcherMode,
|
||||
),
|
||||
contextualToolbar: ContextualToolbar(
|
||||
selectedTabId: selectedTabId,
|
||||
displayedSheet: displayedSheet,
|
||||
),
|
||||
onHorizontalDragStart: !enableGestures
|
||||
? null
|
||||
: (details) {
|
||||
dragStartPosition.value = details.globalPosition;
|
||||
},
|
||||
onHorizontalDragEnd: !enableGestures
|
||||
? null
|
||||
: (details) async {
|
||||
final distance = dragStartPosition.value - details.globalPosition;
|
||||
|
||||
if (distance.dx.abs() > 50 && distance.dy.abs() < 20) {
|
||||
final selectedTab = ref.read(selectedTabProvider);
|
||||
final setting = await ref
|
||||
.read(generalSettingsRepositoryProvider.notifier)
|
||||
.fetchSettings();
|
||||
|
||||
if (selectedTab != null) {
|
||||
switch (setting.tabBarSwipeAction) {
|
||||
case TabBarSwipeAction.switchLastOpened:
|
||||
await ref
|
||||
.read(tabRepositoryProvider.notifier)
|
||||
.selectPreviouslyOpenedTab(selectedTab);
|
||||
case TabBarSwipeAction.navigateOrderedTabs:
|
||||
if (distance.dx < 0) {
|
||||
await ref
|
||||
.read(tabRepositoryProvider.notifier)
|
||||
.selectPreviousTab(selectedTab);
|
||||
} else {
|
||||
await ref
|
||||
.read(tabRepositoryProvider.notifier)
|
||||
.selectNextTab(selectedTab);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
onVerticalDragStart: !enableGestures
|
||||
? null
|
||||
: (details) {
|
||||
dragStartPosition.value = details.globalPosition;
|
||||
},
|
||||
onVerticalDragEnd: !enableGestures
|
||||
? null
|
||||
: (details) {
|
||||
final distance = dragStartPosition.value - details.globalPosition;
|
||||
|
||||
// Swipe direction for dismiss depends on toolbar position:
|
||||
// - Bottom bar: swipe down to dismiss (positive distance.dy)
|
||||
// - Top bar: swipe up to dismiss (negative distance.dy)
|
||||
const dismissThreshold = kToolbarHeight * 0.5;
|
||||
final shouldDismiss = switch (tabBarPosition) {
|
||||
TabBarPosition.bottom =>
|
||||
distance.dy.isNegative &&
|
||||
distance.dy.abs() > dismissThreshold,
|
||||
TabBarPosition.top =>
|
||||
!distance.dy.isNegative &&
|
||||
distance.dy.abs() > dismissThreshold,
|
||||
};
|
||||
if (shouldDismiss &&
|
||||
ref.read(bottomSheetControllerProvider) == null) {
|
||||
unawaited(HapticFeedback.lightImpact());
|
||||
ref
|
||||
.read(
|
||||
toolbarVisibilityControllerProvider(
|
||||
selectedTabId,
|
||||
).notifier,
|
||||
)
|
||||
.dismiss();
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class BrowserTabBarView extends StatelessWidget {
|
||||
const BrowserTabBarView({
|
||||
super.key,
|
||||
required this.showMainToolbar,
|
||||
required this.showContextualToolbar,
|
||||
required this.showQuickTabSwitcherBar,
|
||||
required this.displayAppBar,
|
||||
required this.displayQuickTabSwitcher,
|
||||
required this.backgroundColor,
|
||||
required this.title,
|
||||
required this.actions,
|
||||
required this.quickTabSwitcher,
|
||||
required this.contextualToolbar,
|
||||
this.onHorizontalDragStart,
|
||||
this.onHorizontalDragEnd,
|
||||
this.onVerticalDragStart,
|
||||
this.onVerticalDragEnd,
|
||||
});
|
||||
|
||||
final bool showMainToolbar;
|
||||
final bool showContextualToolbar;
|
||||
final bool showQuickTabSwitcherBar;
|
||||
final bool displayAppBar;
|
||||
final bool displayQuickTabSwitcher;
|
||||
final Color? backgroundColor;
|
||||
final Widget? title;
|
||||
final List<Widget> actions;
|
||||
final Widget quickTabSwitcher;
|
||||
final Widget contextualToolbar;
|
||||
final GestureDragStartCallback? onHorizontalDragStart;
|
||||
final GestureDragEndCallback? onHorizontalDragEnd;
|
||||
final GestureDragStartCallback? onVerticalDragStart;
|
||||
final GestureDragEndCallback? onVerticalDragEnd;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
|
||||
return GestureDetector(
|
||||
// Tap handling moved to AppBarTitle for split icon/title behavior
|
||||
onHorizontalDragStart: onHorizontalDragStart,
|
||||
onHorizontalDragEnd: onHorizontalDragEnd,
|
||||
onVerticalDragStart: onVerticalDragStart,
|
||||
onVerticalDragEnd: onVerticalDragEnd,
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (showQuickTabSwitcherBar)
|
||||
Visibility(
|
||||
visible: displayQuickTabSwitcher,
|
||||
maintainState: true,
|
||||
child: quickTabSwitcher,
|
||||
),
|
||||
if (showMainToolbar)
|
||||
Visibility(
|
||||
visible: displayAppBar,
|
||||
maintainState: true,
|
||||
child: AppBar(
|
||||
primary: false,
|
||||
automaticallyImplyLeading: false,
|
||||
backgroundColor:
|
||||
backgroundColor ?? colorScheme.surfaceContainer,
|
||||
scrolledUnderElevation: 0,
|
||||
shadowColor: Colors.transparent,
|
||||
surfaceTintColor: Colors.transparent,
|
||||
titleSpacing: 0.0,
|
||||
leadingWidth: 40.0,
|
||||
toolbarHeight: kToolbarHeight,
|
||||
title: title,
|
||||
actions: actions,
|
||||
),
|
||||
),
|
||||
if (showContextualToolbar) contextualToolbar,
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class QuickTabSwitcherItem with FastEquatable {
|
||||
final Color? color;
|
||||
final String id;
|
||||
final bool isActive;
|
||||
final TabMode tabMode;
|
||||
final bool isHistory;
|
||||
final bool isPinned;
|
||||
final String title;
|
||||
final Uri url;
|
||||
final Widget avatar;
|
||||
|
||||
QuickTabSwitcherItem({
|
||||
required this.color,
|
||||
required this.id,
|
||||
required this.isActive,
|
||||
required this.tabMode,
|
||||
required this.isHistory,
|
||||
required this.isPinned,
|
||||
required this.title,
|
||||
required this.url,
|
||||
required this.avatar,
|
||||
});
|
||||
|
||||
@override
|
||||
List<Object?> get hashParameters => [
|
||||
color,
|
||||
id,
|
||||
isActive,
|
||||
tabMode,
|
||||
isHistory,
|
||||
isPinned,
|
||||
title,
|
||||
url,
|
||||
avatar,
|
||||
];
|
||||
}
|
||||
|
||||
class QuickTabSwitcher extends HookConsumerWidget {
|
||||
final QuickTabSwitcherMode quickTabSwitcherMode;
|
||||
|
||||
const QuickTabSwitcher({super.key, required this.quickTabSwitcherMode});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final showIsolatedTabUi = ref.watch(
|
||||
generalSettingsWithDefaultsProvider.select((s) => s.showIsolatedTabUi),
|
||||
);
|
||||
final showTitles = ref.watch(
|
||||
generalSettingsWithDefaultsProvider.select(
|
||||
(s) => s.quickTabSwitcherShowTitles,
|
||||
),
|
||||
);
|
||||
final effectiveMode = ref.watch(
|
||||
generalSettingsWithDefaultsProvider.select(
|
||||
(settings) => settings.effectiveUiQuickTabSwitcherMode(),
|
||||
),
|
||||
);
|
||||
final pinnedTabIds = ref.watch(
|
||||
watchPinnedTabIdsProvider.select((value) => value.value),
|
||||
);
|
||||
final tabStates = ref.watch(
|
||||
quickTabSwitcherTabStatesProvider(quickTabSwitcherMode),
|
||||
);
|
||||
final selectedTabId = ref.watch(selectedTabProvider);
|
||||
final historySuggestions = ref
|
||||
.watch(quickTabSwitcherHistorySuggestionsProvider(quickTabSwitcherMode))
|
||||
.value;
|
||||
final availableItems = tabStates.value
|
||||
.map<QuickTabSwitcherItem>(
|
||||
(state) => QuickTabSwitcherItem(
|
||||
color: state.$2?.color,
|
||||
id: state.$1.id,
|
||||
isActive: state.$1.id == selectedTabId,
|
||||
title: state.$1.titleOrAuthority,
|
||||
tabMode: state.$1.tabMode,
|
||||
isHistory: false,
|
||||
isPinned: pinnedTabIds?.contains(state.$1.id) ?? false,
|
||||
url: state.$1.url,
|
||||
avatar: TabIcon(tabState: state.$1, iconSize: 20),
|
||||
),
|
||||
)
|
||||
.followedBy(
|
||||
(historySuggestions ?? []).map<QuickTabSwitcherItem>((state) {
|
||||
final url = Uri.parse(state.url);
|
||||
|
||||
return QuickTabSwitcherItem(
|
||||
color: null,
|
||||
id: state.url,
|
||||
isActive: false,
|
||||
title: state.title ?? url.authority,
|
||||
tabMode: TabMode.regular,
|
||||
isHistory: true,
|
||||
isPinned: false,
|
||||
url: url,
|
||||
avatar: UrlIcon([url], iconSize: 20),
|
||||
);
|
||||
}),
|
||||
)
|
||||
.toList();
|
||||
|
||||
final activeItem = availableItems.firstWhere(
|
||||
(item) => item.isActive,
|
||||
orElse: () => availableItems.first,
|
||||
);
|
||||
|
||||
final chipScrollController = useScrollController();
|
||||
|
||||
return QuickTabSwitcherView(
|
||||
availableItems: availableItems,
|
||||
activeItem: activeItem.isActive ? activeItem : null,
|
||||
scrollController: chipScrollController,
|
||||
showTitles: showTitles,
|
||||
showIsolatedTabUi: showIsolatedTabUi,
|
||||
onSelected: (item) async {
|
||||
if (!item.isHistory && item.isActive) {
|
||||
return;
|
||||
}
|
||||
if (item.isHistory) {
|
||||
await ref
|
||||
.read(tabRepositoryProvider.notifier)
|
||||
.addTab(url: item.url, tabMode: TabMode.regular, selectTab: true);
|
||||
} else {
|
||||
await ref.read(tabRepositoryProvider.notifier).selectTab(item.id);
|
||||
}
|
||||
},
|
||||
itemWrapBuilder: (child, item) {
|
||||
if (item.isHistory) {
|
||||
return child;
|
||||
}
|
||||
|
||||
return TabMenu(
|
||||
selectedTabId: item.id,
|
||||
enableFindInPage: false,
|
||||
enableFetchFeeds: false,
|
||||
enableDesktopMode: false,
|
||||
enableReaderMode: false,
|
||||
enableReloadButton: false,
|
||||
enableNavigationButtons: false,
|
||||
enableAddToHomeScreen: false,
|
||||
enablePinTab: effectiveMode == QuickTabSwitcherMode.containerTabs,
|
||||
builder: (context, controller, _) {
|
||||
return InkWell(
|
||||
onLongPress: () {
|
||||
if (controller.isOpen) {
|
||||
controller.close();
|
||||
} else {
|
||||
controller.open();
|
||||
}
|
||||
},
|
||||
child: child,
|
||||
);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class QuickTabSwitcherView extends StatelessWidget {
|
||||
const QuickTabSwitcherView({
|
||||
super.key,
|
||||
required this.availableItems,
|
||||
required this.activeItem,
|
||||
required this.scrollController,
|
||||
required this.showTitles,
|
||||
required this.showIsolatedTabUi,
|
||||
required this.onSelected,
|
||||
required this.itemWrapBuilder,
|
||||
});
|
||||
|
||||
final List<QuickTabSwitcherItem> availableItems;
|
||||
final QuickTabSwitcherItem? activeItem;
|
||||
final ScrollController scrollController;
|
||||
final bool showTitles;
|
||||
final bool showIsolatedTabUi;
|
||||
final Future<void> Function(QuickTabSwitcherItem item) onSelected;
|
||||
final Widget Function(Widget child, QuickTabSwitcherItem item)
|
||||
itemWrapBuilder;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final appColors = AppColors.of(context);
|
||||
|
||||
if (availableItems.isEmpty) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 4.0),
|
||||
child: SizedBox(
|
||||
height: 48,
|
||||
width: double.maxFinite,
|
||||
child:
|
||||
SelectableChips<QuickTabSwitcherItem, QuickTabSwitcherItem, String>(
|
||||
enableDelete: false,
|
||||
sortSelectedFirst: false,
|
||||
scrollController: scrollController,
|
||||
itemId: (item) => item.id,
|
||||
selectedItem: activeItem,
|
||||
selectedBorderColor: Theme.of(context).colorScheme.primary,
|
||||
labelPadding: (item) =>
|
||||
(!showTitles &&
|
||||
!item.isHistory &&
|
||||
!item.isPinned &&
|
||||
item.tabMode is! PrivateTabMode &&
|
||||
item.tabMode is! IsolatedTabMode)
|
||||
? EdgeInsets.zero
|
||||
: null,
|
||||
itemLabel: (item) {
|
||||
return Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (item.isHistory || showTitles)
|
||||
ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 64),
|
||||
child: Text(item.title),
|
||||
),
|
||||
if (showIsolatedTabUi && item.tabMode is IsolatedTabMode)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(left: 8.0),
|
||||
child: Icon(
|
||||
MdiIcons.snowflake,
|
||||
color: appColors.isolatedTabTeal,
|
||||
size: 20,
|
||||
),
|
||||
)
|
||||
else if (item.tabMode is PrivateTabMode)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(left: 8.0),
|
||||
child: Icon(
|
||||
MdiIcons.dominoMask,
|
||||
color: appColors.privateTabPurple,
|
||||
size: 20,
|
||||
),
|
||||
),
|
||||
if (item.isPinned)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(left: 8.0),
|
||||
child: Icon(
|
||||
MdiIcons.pin,
|
||||
color: Theme.of(context).colorScheme.primary,
|
||||
size: 20,
|
||||
),
|
||||
),
|
||||
if (item.isHistory)
|
||||
const Padding(
|
||||
padding: EdgeInsets.only(left: 8.0),
|
||||
child: Icon(MdiIcons.history, size: 20),
|
||||
),
|
||||
],
|
||||
);
|
||||
},
|
||||
itemAvatar: (item) => item.avatar,
|
||||
itemBackgroundColor: (item) => item.color != null
|
||||
? ContainerColors.forChip(item.color!)
|
||||
: null,
|
||||
onSelected: onSelected,
|
||||
itemWrap: itemWrapBuilder,
|
||||
availableItems: availableItems,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_material_design_icons/flutter_material_design_icons.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/entities/states/readerable.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers/selected_tab.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers/tab_state.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/presentation/controllers/toolbar_visibility.dart';
|
||||
import 'package:weblibre/features/geckoview/features/readerview/domain/providers/readerable.dart';
|
||||
|
||||
class BrowserFab extends HookConsumerWidget {
|
||||
const BrowserFab({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final selectedTabId = ref.watch(selectedTabProvider);
|
||||
final toolbarState = ref.watch(
|
||||
toolbarVisibilityControllerProvider(selectedTabId),
|
||||
);
|
||||
|
||||
final appearanceButtonVisible = ref.watch(
|
||||
appearanceButtonVisibilityProvider.select(
|
||||
(value) => value.value ?? false,
|
||||
),
|
||||
);
|
||||
|
||||
final readerabilityState = ref.watch(
|
||||
selectedTabStateProvider.select(
|
||||
(state) => state?.readerableState ?? ReaderableState.$default(),
|
||||
),
|
||||
);
|
||||
|
||||
final Widget child;
|
||||
if (readerabilityState.active && appearanceButtonVisible) {
|
||||
child = FloatingActionButton(
|
||||
key: const ValueKey('appearance_fab'),
|
||||
heroTag: 'appearance_fab',
|
||||
onPressed: () async {
|
||||
await ref.read(readerableServiceProvider).onAppearanceButtonTap();
|
||||
},
|
||||
child: const Icon(MdiIcons.formatFont),
|
||||
);
|
||||
} else if (toolbarState == ToolbarVisibility.dismissed) {
|
||||
child = FloatingActionButton(
|
||||
key: const ValueKey('dock_fab'),
|
||||
heroTag: 'dock_fab',
|
||||
onPressed: () {
|
||||
ref
|
||||
.read(toolbarVisibilityControllerProvider(selectedTabId).notifier)
|
||||
.forceShow();
|
||||
},
|
||||
child: const Icon(MdiIcons.dockBottom),
|
||||
);
|
||||
} else {
|
||||
child = const SizedBox.shrink(key: ValueKey('no_fab'));
|
||||
}
|
||||
|
||||
return child;
|
||||
}
|
||||
}
|
||||
+671
@@ -0,0 +1,671 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/scheduler.dart';
|
||||
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:nullability/nullability.dart';
|
||||
import 'package:quick_actions/quick_actions.dart';
|
||||
import 'package:weblibre/core/logger.dart';
|
||||
import 'package:weblibre/core/providers/device_info.dart';
|
||||
import 'package:weblibre/core/providers/router.dart';
|
||||
import 'package:weblibre/core/routing/routes.dart';
|
||||
import 'package:weblibre/features/bangs/domain/providers/bangs.dart';
|
||||
import 'package:weblibre/features/bangs/domain/services/search_history_cleanup.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/entities/tab_container_selection.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers/browser_extension.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers/tab_session.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers/tab_state.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers/web_extensions_state.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/repositories/tab.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/domain/providers.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/domain/providers/intent.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/domain/providers/lifecycle.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/domain/services/browser_data.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/domain/services/engine_settings_replication.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/domain/services/proxy_settings_replication.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/presentation/widgets/browser_home.dart';
|
||||
import 'package:weblibre/features/geckoview/features/history/domain/repositories/history.dart';
|
||||
import 'package:weblibre/features/geckoview/features/preferences/data/repositories/preference_observer.dart';
|
||||
import 'package:weblibre/features/geckoview/features/pwa/domain/providers.dart';
|
||||
import 'package:weblibre/features/geckoview/features/tabs/data/entities/tab_mode.dart';
|
||||
import 'package:weblibre/features/geckoview/features/tabs/domain/providers/selected_container.dart';
|
||||
import 'package:weblibre/features/geckoview/features/tabs/domain/repositories/container.dart';
|
||||
import 'package:weblibre/features/geckoview/features/tabs/domain/repositories/tab.dart';
|
||||
import 'package:weblibre/features/share_intent/domain/entities/shared_content.dart';
|
||||
import 'package:weblibre/features/user/data/models/general_settings.dart';
|
||||
import 'package:weblibre/features/user/domain/providers/profile_auth.dart';
|
||||
import 'package:weblibre/features/user/domain/repositories/cache.dart';
|
||||
import 'package:weblibre/features/user/domain/repositories/general_settings.dart';
|
||||
import 'package:weblibre/features/user/domain/services/local_authentication.dart';
|
||||
import 'package:weblibre/features/web_feed/domain/providers/add_dialog_blocking.dart';
|
||||
import 'package:weblibre/features/web_feed/domain/services/article_content_processor.dart';
|
||||
import 'package:weblibre/presentation/hooks/on_initialization.dart';
|
||||
import 'package:weblibre/utils/ui_helper.dart';
|
||||
|
||||
class BrowserView extends StatefulHookConsumerWidget {
|
||||
final Duration screenshotPeriod;
|
||||
final Duration suggestionTimeout;
|
||||
final Future<void> Function()? postInitializationStep;
|
||||
final StreamSink<Offset>? pointerMoveEventSink;
|
||||
|
||||
const BrowserView({
|
||||
super.key,
|
||||
this.screenshotPeriod = const Duration(seconds: 10),
|
||||
this.suggestionTimeout = const Duration(seconds: 30),
|
||||
this.postInitializationStep,
|
||||
this.pointerMoveEventSink,
|
||||
});
|
||||
|
||||
@override
|
||||
ConsumerState<ConsumerStatefulWidget> createState() => _BrowserViewState();
|
||||
}
|
||||
|
||||
class _BrowserViewState extends ConsumerState<BrowserView>
|
||||
with WidgetsBindingObserver {
|
||||
Timer? _periodicScreenshotUpdate;
|
||||
final Completer<void> _initializationCompleter = Completer<void>();
|
||||
|
||||
//This is managed by widget state changes to resume a timer
|
||||
bool _timerPaused = false;
|
||||
|
||||
DateTime? _suggestionCountTime;
|
||||
|
||||
static const _pointerThrottleInterval = Duration(milliseconds: 32);
|
||||
DateTime _lastPointerEvent = DateTime(0);
|
||||
Offset _accumulatedDelta = Offset.zero;
|
||||
|
||||
Future<void> _timerTick(Timer timer) async {
|
||||
await ref
|
||||
.read(selectedTabSessionProvider)
|
||||
.requestScreenshot(requireImageResult: false)
|
||||
.onError((error, stackTrace) {
|
||||
logger.e(error, stackTrace: stackTrace);
|
||||
timer.cancel();
|
||||
|
||||
return null;
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
useOnInitialization(() async {
|
||||
await ref
|
||||
.read(generalSettingsRepositoryProvider.notifier)
|
||||
.fetchSettings()
|
||||
.then((settings) async {
|
||||
await ref
|
||||
.read(browserDataServiceProvider.notifier)
|
||||
.deleteDataOnEngineStart(settings.deleteBrowsingDataOnQuit);
|
||||
|
||||
if (settings.historyAutoCleanInterval > Duration.zero) {
|
||||
await ref
|
||||
.read(historyRepositoryProvider.notifier)
|
||||
.deleteVisitsBetween(
|
||||
DateTime(0),
|
||||
DateTime.now().subtract(settings.historyAutoCleanInterval),
|
||||
);
|
||||
}
|
||||
|
||||
if (settings.unassignedTabsAutoCleanInterval > Duration.zero) {
|
||||
await ref
|
||||
.read(tabDataRepositoryProvider.notifier)
|
||||
.deleteUnassignedTabsOlderThan(
|
||||
DateTime.now().subtract(
|
||||
settings.unassignedTabsAutoCleanInterval,
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
// Clear data for containers with clearDataOnExit enabled
|
||||
final containersToClear = await ref
|
||||
.read(containerRepositoryProvider.notifier)
|
||||
.getContainersToClearOnExit();
|
||||
|
||||
if (containersToClear.isNotEmpty) {
|
||||
await ref
|
||||
.read(browserDataServiceProvider.notifier)
|
||||
.clearContainerDataOnEngineStart(containersToClear);
|
||||
}
|
||||
});
|
||||
|
||||
final showHome = ref.watch(shouldShowBrowserHomeProvider);
|
||||
|
||||
final topRoute = ref.watch(currentTopRouteProvider);
|
||||
final androidInfoAsync = ref.watch(androidDeviceInfoProvider);
|
||||
|
||||
final isGeckoViewVisible = androidInfoAsync.when(
|
||||
data: (androidInfo) {
|
||||
if (androidInfo == null) {
|
||||
// Not Android, always show GeckoView based on route
|
||||
return topRoute is GoRoute && topRoute.name == BrowserRoute.name;
|
||||
}
|
||||
// Android: only apply visibility fix on Android 12 and lower (API <= 31)
|
||||
if (androidInfo.sdkInt <= 31) {
|
||||
return topRoute is GoRoute && topRoute.name == BrowserRoute.name;
|
||||
}
|
||||
// Android 13+: always show GeckoView
|
||||
return true;
|
||||
},
|
||||
loading: () => true, // Show by default while loading
|
||||
error: (_, _) => true, // Show by default on error
|
||||
);
|
||||
|
||||
return Listener(
|
||||
behavior: HitTestBehavior.translucent,
|
||||
onPointerUp: (widget.pointerMoveEventSink != null)
|
||||
? (_) {
|
||||
if (_accumulatedDelta != Offset.zero) {
|
||||
widget.pointerMoveEventSink!.add(_accumulatedDelta);
|
||||
_accumulatedDelta = Offset.zero;
|
||||
}
|
||||
}
|
||||
: null,
|
||||
onPointerMove: (widget.pointerMoveEventSink != null)
|
||||
? (event) {
|
||||
if (event.down) {
|
||||
_accumulatedDelta += event.localDelta;
|
||||
final now = DateTime.now();
|
||||
if (now.difference(_lastPointerEvent) >=
|
||||
_pointerThrottleInterval) {
|
||||
_lastPointerEvent = now;
|
||||
widget.pointerMoveEventSink!.add(_accumulatedDelta);
|
||||
_accumulatedDelta = Offset.zero;
|
||||
}
|
||||
}
|
||||
}
|
||||
: null,
|
||||
child: Stack(
|
||||
children: [
|
||||
Visibility(
|
||||
visible: isGeckoViewVisible,
|
||||
child: GeckoView(
|
||||
preInitializationStep: () async {
|
||||
await ref
|
||||
.read(eventServiceProvider)
|
||||
.viewReadyStateEvents
|
||||
.firstWhere((state) => state == true)
|
||||
.timeout(
|
||||
const Duration(seconds: 3),
|
||||
onTimeout: () {
|
||||
logger.e(
|
||||
'Browser fragement not reported ready, trying to intitialize anyways',
|
||||
);
|
||||
return true;
|
||||
},
|
||||
);
|
||||
},
|
||||
postInitializationStep: () async {
|
||||
await widget.postInitializationStep?.call();
|
||||
|
||||
if (!_initializationCompleter.isCompleted) {
|
||||
const quickActions = QuickActions();
|
||||
|
||||
//Debounce: https://github.com/flutter/flutter/issues/131121
|
||||
DateTime? lastAction;
|
||||
await quickActions.initialize((type) async {
|
||||
if (lastAction == null ||
|
||||
DateTime.now().difference(lastAction!) >
|
||||
const Duration(seconds: 5)) {
|
||||
if (type == 'new_tab') {
|
||||
lastAction = DateTime.now();
|
||||
|
||||
final router = await ref.read(routerProvider.future);
|
||||
const route = SearchRoute(tabType: TabType.regular);
|
||||
|
||||
await router.push(route.location);
|
||||
} else if (type == 'new_private_tab') {
|
||||
lastAction = DateTime.now();
|
||||
|
||||
final router = await ref.read(routerProvider.future);
|
||||
const route = SearchRoute(tabType: TabType.private);
|
||||
|
||||
await router.push(route.location);
|
||||
} else if (type == 'new_isolated_tab') {
|
||||
final settings = ref.read(
|
||||
generalSettingsWithDefaultsProvider,
|
||||
);
|
||||
if (!settings.showIsolatedTabUi) {
|
||||
return;
|
||||
}
|
||||
|
||||
lastAction = DateTime.now();
|
||||
|
||||
final router = await ref.read(routerProvider.future);
|
||||
const route = SearchRoute(tabType: TabType.isolated);
|
||||
|
||||
await router.push(route.location);
|
||||
} else {
|
||||
throw UnimplementedError(
|
||||
'Unknown quick action shortcut type',
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
final settings = ref.read(
|
||||
generalSettingsWithDefaultsProvider,
|
||||
);
|
||||
await quickActions.setShortcutItems([
|
||||
//TODO: add icons
|
||||
const ShortcutItem(
|
||||
type: 'new_tab',
|
||||
localizedTitle: 'New Tab',
|
||||
),
|
||||
const ShortcutItem(
|
||||
type: 'new_private_tab',
|
||||
localizedTitle: 'New Private Tab',
|
||||
),
|
||||
if (settings.showIsolatedTabUi)
|
||||
const ShortcutItem(
|
||||
type: 'new_isolated_tab',
|
||||
localizedTitle: 'New Isolated Tab',
|
||||
),
|
||||
]);
|
||||
|
||||
_initializationCompleter.complete();
|
||||
}
|
||||
},
|
||||
),
|
||||
),
|
||||
if (showHome) const Positioned.fill(child: BrowserHome()),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
ref
|
||||
.read(browserViewLifecycleProvider.notifier)
|
||||
.update(SchedulerBinding.instance.lifecycleState);
|
||||
});
|
||||
|
||||
WidgetsBinding.instance.addObserver(this);
|
||||
|
||||
ref.listenManual(
|
||||
selectedTabStateProvider.select(
|
||||
(state) => (
|
||||
tabId: state?.id,
|
||||
isLoading: state?.isLoading,
|
||||
isFullScreen: state?.isFullScreen,
|
||||
),
|
||||
),
|
||||
(previous, next) {
|
||||
if (previous?.tabId != next.tabId ||
|
||||
next.isLoading == true ||
|
||||
next.isFullScreen == true) {
|
||||
_periodicScreenshotUpdate?.cancel();
|
||||
_periodicScreenshotUpdate = null;
|
||||
_timerPaused = false;
|
||||
return;
|
||||
}
|
||||
|
||||
if ((_periodicScreenshotUpdate?.isActive ?? false) == false) {
|
||||
_timerPaused = false;
|
||||
_periodicScreenshotUpdate?.cancel();
|
||||
_periodicScreenshotUpdate = Timer.periodic(
|
||||
widget.screenshotPeriod,
|
||||
_timerTick,
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
ref.listenManual(feedRequestedProvider, (previous, next) async {
|
||||
if (next.value.mapNotNull(Uri.tryParse) case final Uri url) {
|
||||
if (GoRouterState.of(context).topRoute?.name != FeedAddRoute.name) {
|
||||
if (ref.read(addFeedDialogBlockingProvider.notifier).canPush(url)) {
|
||||
await FeedAddRoute(uri: url.toString()).push(context);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
ref.listenManual(
|
||||
engineBoundIntentStreamProvider,
|
||||
(previous, next) async {
|
||||
await _initializationCompleter.future;
|
||||
|
||||
next.whenData((sharedContent) async {
|
||||
final router = await ref.read(routerProvider.future);
|
||||
final settings = ref.read(generalSettingsWithDefaultsProvider);
|
||||
|
||||
// Resolve container from shortcut intent context ID
|
||||
final containerSelection = await _resolveContainerSelection(
|
||||
ref,
|
||||
sharedContent.contextId,
|
||||
);
|
||||
|
||||
switch (settings.tabIntentOpenSetting) {
|
||||
case TabIntentOpenSetting.regular:
|
||||
case TabIntentOpenSetting.private:
|
||||
switch (sharedContent) {
|
||||
case SharedUrl():
|
||||
await ref
|
||||
.read(tabRepositoryProvider.notifier)
|
||||
.addTab(
|
||||
url: sharedContent.url,
|
||||
tabMode:
|
||||
settings.tabIntentOpenSetting ==
|
||||
TabIntentOpenSetting.private
|
||||
? TabMode.private
|
||||
: TabMode.regular,
|
||||
launchedFromIntent: true,
|
||||
selectTab: true,
|
||||
containerSelection: containerSelection,
|
||||
);
|
||||
case SharedText():
|
||||
final bang =
|
||||
ref.read(selectedBangDataProvider()) ??
|
||||
await ref.read(defaultSearchBangDataProvider.future);
|
||||
|
||||
await ref
|
||||
.read(tabRepositoryProvider.notifier)
|
||||
.addTab(
|
||||
url: bang?.getTemplateUrl(sharedContent.text),
|
||||
tabMode:
|
||||
settings.tabIntentOpenSetting ==
|
||||
TabIntentOpenSetting.private
|
||||
? TabMode.private
|
||||
: TabMode.regular,
|
||||
launchedFromIntent: true,
|
||||
selectTab: true,
|
||||
);
|
||||
}
|
||||
case TabIntentOpenSetting.ask:
|
||||
switch (sharedContent) {
|
||||
case SharedUrl():
|
||||
final route = OpenSharedContentRoute(
|
||||
sharedUrl: sharedContent.url.toString(),
|
||||
);
|
||||
await router.push(route.location);
|
||||
case SharedText():
|
||||
final route = SearchRoute(
|
||||
tabType:
|
||||
ref.read(selectedTabTypeProvider) ??
|
||||
settings.effectiveDefaultCreateTabType,
|
||||
searchText: sharedContent.text,
|
||||
launchedFromIntent: true, //launched from intent
|
||||
);
|
||||
await router.push(route.location);
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
onError: (error, stackTrace) {
|
||||
logger.e(
|
||||
'Error listening to engineBoundIntentStreamProvider',
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
//Initialize and register dependencies
|
||||
ref.listenManual(
|
||||
fireImmediately: true,
|
||||
tabRepositoryProvider,
|
||||
(previous, next) {},
|
||||
onError: (error, stackTrace) {
|
||||
logger.e(
|
||||
'Error listening to tabRepositoryProvider',
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
ref.listenManual(
|
||||
fireImmediately: true,
|
||||
selectionActionServiceProvider,
|
||||
(previous, next) {},
|
||||
onError: (error, stackTrace) {
|
||||
logger.e(
|
||||
'Error listening to selectionActionServiceProvider',
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
ref.listenManual(
|
||||
fireImmediately: true,
|
||||
webExtensionsStateProvider(WebExtensionActionType.browser),
|
||||
(previous, next) {},
|
||||
onError: (error, stackTrace) {
|
||||
logger.e(
|
||||
'Error listening to webExtensionsStateProvider',
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
ref.listenManual(
|
||||
fireImmediately: true,
|
||||
webExtensionsStateProvider(WebExtensionActionType.page),
|
||||
(previous, next) {},
|
||||
onError: (error, stackTrace) {
|
||||
logger.e(
|
||||
'Error listening to webExtensionsStateProvider',
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
ref.listenManual(
|
||||
fireImmediately: true,
|
||||
cacheRepositoryProvider,
|
||||
(previous, next) {},
|
||||
onError: (error, stackTrace) {
|
||||
logger.e(
|
||||
'Error listening to cacheRepositoryProvider',
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
ref.listenManual(
|
||||
fireImmediately: true,
|
||||
preferenceFixatorProvider,
|
||||
(previous, next) {},
|
||||
onError: (error, stackTrace) {
|
||||
logger.e(
|
||||
'Error listening to preferenceFixatorProvider',
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
ref.listenManual(
|
||||
fireImmediately: true,
|
||||
searchHistoryCleanupServiceProvider,
|
||||
(previous, next) {},
|
||||
onError: (error, stackTrace) {
|
||||
logger.e(
|
||||
'Error listening to searchHistoryCleanupServiceProvider',
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
ref.listenManual(
|
||||
fireImmediately: true,
|
||||
engineSettingsReplicationServiceProvider,
|
||||
(previous, next) {},
|
||||
onError: (error, stackTrace) {
|
||||
logger.e(
|
||||
'Error listening to engineSettingsReplicationServiceProvider',
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
ref.listenManual(
|
||||
fireImmediately: true,
|
||||
proxySettingsReplicationProvider,
|
||||
(previous, next) {},
|
||||
onError: (error, stackTrace) {
|
||||
logger.e(
|
||||
'Error listening to proxySettingsReplicationProvider',
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
ref.listenManual(
|
||||
fireImmediately: true,
|
||||
articleContentProcessorServiceProvider,
|
||||
(previous, next) {},
|
||||
onError: (error, stackTrace) {
|
||||
logger.e(
|
||||
'Error listening to articleContentProcessorServiceProvider',
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
// Ensure PWA manifest state is collected and stays alive
|
||||
ref.listenManual(
|
||||
fireImmediately: true,
|
||||
pwaManifestStateProvider,
|
||||
(previous, next) {},
|
||||
onError: (error, stackTrace) {
|
||||
logger.e(
|
||||
'Error listening to pwaManifestStateProvider',
|
||||
error: error,
|
||||
stackTrace: stackTrace,
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void didChangeAppLifecycleState(AppLifecycleState state) {
|
||||
super.didChangeAppLifecycleState(state);
|
||||
|
||||
ref.read(browserViewLifecycleProvider.notifier).update(state);
|
||||
|
||||
switch (state) {
|
||||
case AppLifecycleState.detached:
|
||||
case AppLifecycleState.inactive:
|
||||
case AppLifecycleState.hidden:
|
||||
case AppLifecycleState.paused:
|
||||
if (_periodicScreenshotUpdate?.isActive == true) {
|
||||
_periodicScreenshotUpdate?.cancel();
|
||||
_timerPaused = true;
|
||||
}
|
||||
|
||||
ref
|
||||
.read(localAuthenticationServiceProvider.notifier)
|
||||
.evictCacheOnBackground();
|
||||
|
||||
if (state == AppLifecycleState.paused) {
|
||||
_suggestionCountTime = DateTime.now();
|
||||
}
|
||||
case AppLifecycleState.resumed:
|
||||
if (_timerPaused) {
|
||||
_periodicScreenshotUpdate?.cancel();
|
||||
_periodicScreenshotUpdate = Timer.periodic(
|
||||
widget.screenshotPeriod,
|
||||
_timerTick,
|
||||
);
|
||||
_timerPaused = false;
|
||||
}
|
||||
|
||||
unawaited(
|
||||
ref.read(profileAuthStateProvider.notifier).revalidateAfterResume(),
|
||||
);
|
||||
|
||||
if (_suggestionCountTime != null &&
|
||||
DateTime.now().difference(_suggestionCountTime!) >
|
||||
widget.suggestionTimeout) {
|
||||
final topRoute = ref.read(currentTopRouteProvider);
|
||||
|
||||
//Don't do anything if a child route is active
|
||||
if (topRoute is GoRoute && topRoute.name == BrowserRoute.name) {
|
||||
final settings = ref.read(generalSettingsWithDefaultsProvider);
|
||||
|
||||
if (settings.allowClipboardAccess) {
|
||||
unawaited(
|
||||
showSuggestNewTabMessage(
|
||||
context,
|
||||
onAdd: (searchText) async {
|
||||
await SearchRoute(
|
||||
tabType:
|
||||
ref.read(selectedTabTypeProvider) ??
|
||||
settings.effectiveDefaultCreateTabType,
|
||||
searchText: searchText ?? SearchRoute.emptySearchText,
|
||||
).push(context);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_suggestionCountTime = null;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> dispose() async {
|
||||
WidgetsBinding.instance.removeObserver(this);
|
||||
|
||||
_periodicScreenshotUpdate?.cancel();
|
||||
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolves a [TabContainerSelection] from a shortcut intent's context ID.
|
||||
/// Returns [TabContainerSelection.useSelected] if no contextId or container not found.
|
||||
Future<TabContainerSelection> _resolveContainerSelection(
|
||||
WidgetRef ref,
|
||||
String? contextId,
|
||||
) async {
|
||||
if (contextId == null) return const TabContainerSelection.useSelected();
|
||||
|
||||
final container = await ref
|
||||
.read(containerRepositoryProvider.notifier)
|
||||
.getContainerByContextualIdentity(contextId);
|
||||
|
||||
if (container != null) {
|
||||
return TabContainerSelection.specific(container);
|
||||
}
|
||||
|
||||
return const TabContainerSelection.useSelected();
|
||||
}
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'dart:async';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_hooks/flutter_hooks.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
|
||||
class DraggableFab extends HookConsumerWidget {
|
||||
final Widget child;
|
||||
final double fabSize;
|
||||
final bool bottomToolbarVisible;
|
||||
final double bottomAppBarHeight;
|
||||
final double bottomSafeArea;
|
||||
|
||||
const DraggableFab({
|
||||
super.key,
|
||||
required this.child,
|
||||
this.fabSize = 56.0,
|
||||
required this.bottomToolbarVisible,
|
||||
required this.bottomAppBarHeight,
|
||||
required this.bottomSafeArea,
|
||||
});
|
||||
|
||||
static const _edgePadding = 16.0;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final mediaQuery = MediaQuery.of(context);
|
||||
final screenSize = mediaQuery.size;
|
||||
final padding = mediaQuery.padding;
|
||||
final disableAnimations = mediaQuery.disableAnimations;
|
||||
|
||||
final isDragging = useState(false);
|
||||
final customOffset = useState<Offset?>(null);
|
||||
final dragStartOffset = useRef<Offset?>(null);
|
||||
final dragStartPosition = useRef<Offset?>(null);
|
||||
|
||||
// Calculate default position (bottom-right, respecting toolbar)
|
||||
final defaultBottom = bottomToolbarVisible
|
||||
? bottomAppBarHeight + _edgePadding
|
||||
: _edgePadding + bottomSafeArea;
|
||||
const defaultRight = _edgePadding;
|
||||
final defaultLeft = screenSize.width - fabSize - defaultRight;
|
||||
final defaultTop = screenSize.height - fabSize - defaultBottom;
|
||||
|
||||
// Current position: custom if set, otherwise default
|
||||
final currentLeft = customOffset.value?.dx ?? defaultLeft;
|
||||
final currentTop = customOffset.value?.dy ?? defaultTop;
|
||||
|
||||
return Positioned(
|
||||
left: currentLeft,
|
||||
top: currentTop,
|
||||
child: GestureDetector(
|
||||
onLongPressStart: (details) {
|
||||
isDragging.value = true;
|
||||
unawaited(HapticFeedback.mediumImpact());
|
||||
dragStartOffset.value = Offset(currentLeft, currentTop);
|
||||
dragStartPosition.value = details.globalPosition;
|
||||
},
|
||||
onLongPressMoveUpdate: (details) {
|
||||
if (!isDragging.value ||
|
||||
dragStartOffset.value == null ||
|
||||
dragStartPosition.value == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
final delta = details.globalPosition - dragStartPosition.value!;
|
||||
final newOffset = dragStartOffset.value! + delta;
|
||||
|
||||
// Clamp to screen bounds
|
||||
customOffset.value = _clampToBounds(
|
||||
newOffset,
|
||||
screenSize: screenSize,
|
||||
padding: padding,
|
||||
);
|
||||
},
|
||||
onLongPressEnd: (details) {
|
||||
isDragging.value = false;
|
||||
dragStartOffset.value = null;
|
||||
dragStartPosition.value = null;
|
||||
},
|
||||
child: AnimatedScale(
|
||||
duration: disableAnimations
|
||||
? Duration.zero
|
||||
: const Duration(milliseconds: 150),
|
||||
scale: isDragging.value ? 1.1 : 1.0,
|
||||
child: child,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Offset _clampToBounds(
|
||||
Offset offset, {
|
||||
required Size screenSize,
|
||||
required EdgeInsets padding,
|
||||
}) {
|
||||
const minEdgePadding = 8.0;
|
||||
|
||||
return Offset(
|
||||
offset.dx.clamp(
|
||||
padding.left + minEdgePadding,
|
||||
screenSize.width - fabSize - padding.right - minEdgePadding,
|
||||
),
|
||||
offset.dy.clamp(
|
||||
padding.top + minEdgePadding,
|
||||
screenSize.height - fabSize - padding.bottom - minEdgePadding,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
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:skeletonizer/skeletonizer.dart';
|
||||
import 'package:weblibre/extensions/uri.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers/tab_state.dart';
|
||||
|
||||
class CertificateTile extends HookConsumerWidget {
|
||||
const CertificateTile({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final tabState = ref.watch(selectedTabStateProvider);
|
||||
|
||||
if (tabState == null) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
|
||||
final icon = useMemoized(() {
|
||||
if (tabState.url.isHttp) {
|
||||
return ListTile(
|
||||
leading: Icon(
|
||||
MdiIcons.lockOff,
|
||||
color: Theme.of(context).colorScheme.error,
|
||||
),
|
||||
title: Text(
|
||||
'Connection is not secure',
|
||||
style: TextStyle(color: Theme.of(context).colorScheme.error),
|
||||
),
|
||||
);
|
||||
} else if (tabState.readerableState.active) {
|
||||
return const SizedBox.shrink();
|
||||
} else if (!tabState.securityInfoState.secure) {
|
||||
return ListTile(
|
||||
leading: Icon(
|
||||
MdiIcons.lockAlert,
|
||||
color: Theme.of(context).colorScheme.errorContainer,
|
||||
),
|
||||
title: Text(
|
||||
'Connection is not secure',
|
||||
style: TextStyle(
|
||||
color: Theme.of(context).colorScheme.errorContainer,
|
||||
),
|
||||
),
|
||||
);
|
||||
} else if (!tabState.isLoading) {
|
||||
return ListTile(
|
||||
leading: const Icon(MdiIcons.lock),
|
||||
title: const Text('Connection is secure'),
|
||||
subtitle: Text('Verified By: ${tabState.securityInfoState.issuer}'),
|
||||
);
|
||||
} else {
|
||||
return Skeletonizer(
|
||||
child: ListTile(
|
||||
leading: const Skeleton.keep(child: Icon(MdiIcons.timerSand)),
|
||||
title: Text(BoneMock.title),
|
||||
subtitle: Text(BoneMock.subtitle),
|
||||
),
|
||||
);
|
||||
}
|
||||
}, [tabState]);
|
||||
|
||||
return icon;
|
||||
}
|
||||
}
|
||||
+158
@@ -0,0 +1,158 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'dart:math';
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class DraggableScrollableHeader extends StatefulWidget {
|
||||
final DraggableScrollableController controller;
|
||||
final Widget child;
|
||||
|
||||
// Velocity control parameters
|
||||
final double velocitySensitivity;
|
||||
final double maxVelocity;
|
||||
final double minVelocity;
|
||||
final Duration animationDuration;
|
||||
final Curve animationCurve;
|
||||
final double dragSensitivity;
|
||||
|
||||
const DraggableScrollableHeader({
|
||||
super.key,
|
||||
required this.controller,
|
||||
required this.child,
|
||||
this.velocitySensitivity = 0.25, // Higher = more sensitive to velocity
|
||||
this.maxVelocity = 2500.0, // Maximum velocity to consider
|
||||
this.minVelocity = 50.0, // Minimum velocity to trigger momentum
|
||||
this.animationDuration = const Duration(milliseconds: 300),
|
||||
this.animationCurve = Curves.decelerate,
|
||||
this.dragSensitivity = 1.0, // Controls drag responsiveness
|
||||
});
|
||||
|
||||
@override
|
||||
State<DraggableScrollableHeader> createState() =>
|
||||
_DraggableScrollableHeaderState();
|
||||
}
|
||||
|
||||
class _DraggableScrollableHeaderState extends State<DraggableScrollableHeader>
|
||||
with TickerProviderStateMixin {
|
||||
late AnimationController _animationController;
|
||||
late Animation<double>? _animation;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_animationController = AnimationController(
|
||||
vsync: this,
|
||||
duration: widget.animationDuration,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_animationController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _animateToPosition(
|
||||
double targetSize, {
|
||||
Duration? customDuration,
|
||||
}) async {
|
||||
if (MediaQuery.disableAnimationsOf(context)) {
|
||||
widget.controller.jumpTo(targetSize);
|
||||
return;
|
||||
}
|
||||
|
||||
if (customDuration != null) {
|
||||
_animationController.duration = customDuration;
|
||||
} else {
|
||||
_animationController.duration = widget.animationDuration;
|
||||
}
|
||||
|
||||
_animation = Tween<double>(begin: widget.controller.size, end: targetSize)
|
||||
.animate(
|
||||
CurvedAnimation(
|
||||
parent: _animationController,
|
||||
curve: widget.animationCurve,
|
||||
),
|
||||
);
|
||||
|
||||
_animationController.reset();
|
||||
await _animationController.forward();
|
||||
|
||||
_animation!.addListener(() {
|
||||
widget.controller.jumpTo(_animation!.value);
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return GestureDetector(
|
||||
onVerticalDragUpdate: (details) {
|
||||
_animationController.stop();
|
||||
|
||||
// Apply drag sensitivity
|
||||
final adjustedDelta = details.delta.dy * widget.dragSensitivity;
|
||||
|
||||
widget.controller.jumpTo(
|
||||
min(
|
||||
1,
|
||||
widget.controller.pixelsToSize(
|
||||
widget.controller.pixels - adjustedDelta,
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
onVerticalDragEnd: (details) async {
|
||||
final velocity = details.primaryVelocity ?? 0;
|
||||
final currentSize = widget.controller.size;
|
||||
|
||||
// Clamp velocity to defined range
|
||||
final clampedVelocity = velocity.clamp(
|
||||
-widget.maxVelocity,
|
||||
widget.maxVelocity,
|
||||
);
|
||||
|
||||
// Only apply momentum if velocity exceeds minimum threshold
|
||||
if (clampedVelocity.abs() < widget.minVelocity) {
|
||||
return; // No momentum, stay at current position
|
||||
}
|
||||
|
||||
// Calculate momentum-based target with sensitivity control
|
||||
final velocityFactor =
|
||||
clampedVelocity / 1000 * widget.velocitySensitivity;
|
||||
double targetSize = currentSize - velocityFactor;
|
||||
|
||||
// Clamp to valid range
|
||||
targetSize = targetSize.clamp(0.0, 1.0);
|
||||
|
||||
// Calculate animation duration based on velocity (faster velocity = longer animation)
|
||||
final velocityRatio = clampedVelocity.abs() / widget.maxVelocity;
|
||||
final dynamicDuration = Duration(
|
||||
milliseconds:
|
||||
(widget.animationDuration.inMilliseconds * (0.5 + velocityRatio))
|
||||
.round(),
|
||||
);
|
||||
|
||||
await _animateToPosition(targetSize, customDuration: dynamicDuration);
|
||||
},
|
||||
child: widget.child,
|
||||
);
|
||||
}
|
||||
}
|
||||
+52
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class ErrorContainer extends StatelessWidget {
|
||||
final Widget content;
|
||||
|
||||
const ErrorContainer({super.key, required this.content});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return Container(
|
||||
margin: const EdgeInsets.symmetric(horizontal: 16.0),
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.errorContainer,
|
||||
borderRadius: BorderRadius.circular(4.0),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(8.0),
|
||||
child: Icon(
|
||||
Icons.warning,
|
||||
size: 36,
|
||||
color: theme.colorScheme.onErrorContainer,
|
||||
),
|
||||
),
|
||||
Expanded(child: content),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:nullability/nullability.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/entities/states/web_extension.dart';
|
||||
import 'package:weblibre/presentation/widgets/safe_raw_image.dart';
|
||||
|
||||
class ExtensionBadgeIcon extends StatelessWidget {
|
||||
final WebExtensionState state;
|
||||
|
||||
const ExtensionBadgeIcon(this.state, {super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final hasBadge = state.badgeText.isNotEmpty;
|
||||
|
||||
return Badge(
|
||||
isLabelVisible: hasBadge,
|
||||
label: hasBadge ? Text(state.badgeText!) : null,
|
||||
textColor: state.badgeTextColor,
|
||||
backgroundColor: state.badgeBackgroundColor,
|
||||
child: RepaintBoundary(
|
||||
child: SafeRawImage(image: state.icon, width: 24, height: 24),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers/web_extensions_state.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/presentation/widgets/extension_badge_icon.dart';
|
||||
|
||||
class ExtensionShortcutMenu extends HookConsumerWidget {
|
||||
final Widget child;
|
||||
final MenuController controller;
|
||||
|
||||
const ExtensionShortcutMenu({
|
||||
super.key,
|
||||
required this.child,
|
||||
required this.controller,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final browserExtensions = ref.watch(
|
||||
webExtensionsStateProvider(
|
||||
WebExtensionActionType.browser,
|
||||
).select((value) => value.values.toList()),
|
||||
);
|
||||
|
||||
return MenuAnchor(
|
||||
controller: controller,
|
||||
builder: (context, controller, child) {
|
||||
return child!;
|
||||
},
|
||||
menuChildren: [
|
||||
...browserExtensions.map(
|
||||
(extension) => MenuItemButton(
|
||||
onPressed: () async {
|
||||
//Use parents .ref because after onPressed this consumer gets disposed already
|
||||
await ref
|
||||
.read(addonServiceProvider)
|
||||
.invokeAddonAction(
|
||||
extension.extensionId,
|
||||
WebExtensionActionType.browser,
|
||||
);
|
||||
},
|
||||
leadingIcon: Padding(
|
||||
padding: const EdgeInsets.only(top: 4.0),
|
||||
child: ExtensionBadgeIcon(extension),
|
||||
),
|
||||
child: Text(extension.title ?? ''),
|
||||
),
|
||||
),
|
||||
],
|
||||
child: Visibility(visible: browserExtensions.isNotEmpty, child: child),
|
||||
);
|
||||
}
|
||||
}
|
||||
+162
@@ -0,0 +1,162 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_material_design_icons/flutter_material_design_icons.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/domain/entities/font_size_constants.dart';
|
||||
import 'package:weblibre/features/settings/presentation/controllers/save_settings.dart';
|
||||
import 'package:weblibre/features/user/data/models/engine_settings.dart';
|
||||
import 'package:weblibre/features/user/domain/repositories/engine_settings.dart';
|
||||
|
||||
Future<void> showFontSizeBottomSheet(BuildContext context) {
|
||||
return showModalBottomSheet(
|
||||
context: context,
|
||||
shape: const RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
|
||||
),
|
||||
builder: (context) => const FontSizeBottomSheet(),
|
||||
);
|
||||
}
|
||||
|
||||
class FontSizeBottomSheet extends ConsumerWidget {
|
||||
const FontSizeBottomSheet({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final settings = ref.watch(engineSettingsWithDefaultsProvider);
|
||||
final factor = settings.fontSizeFactor;
|
||||
final isAutomatic = settings.automaticFontSizeAdjustment;
|
||||
final canDecrease = !isAutomatic && factor > fontSizeMin;
|
||||
final canIncrease = !isAutomatic && factor < fontSizeMax;
|
||||
final isDefault = factor == fontSizeDefault;
|
||||
|
||||
return SafeArea(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(24, 20, 24, 24),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Icon(
|
||||
MdiIcons.formatSize,
|
||||
color: Theme.of(context).colorScheme.primary,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
'Text Size',
|
||||
style: Theme.of(context).textTheme.titleMedium,
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
if (isAutomatic)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 16),
|
||||
child: Card(
|
||||
color: Theme.of(context).colorScheme.surfaceContainerHighest,
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.info_outline,
|
||||
size: 20,
|
||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
'Automatic font size is enabled. '
|
||||
'Disable in Settings to adjust manually.',
|
||||
style: Theme.of(context).textTheme.bodySmall,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
IconButton.filled(
|
||||
onPressed: canDecrease
|
||||
? () => _adjustFontSize(ref, increase: false)
|
||||
: null,
|
||||
icon: const Icon(MdiIcons.formatFontSizeDecrease),
|
||||
),
|
||||
const SizedBox(width: 24),
|
||||
SizedBox(
|
||||
width: 72,
|
||||
child: Text(
|
||||
'${(factor * 100).round()}%',
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.headlineMedium,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 24),
|
||||
IconButton.filled(
|
||||
onPressed: canIncrease
|
||||
? () => _adjustFontSize(ref, increase: true)
|
||||
: null,
|
||||
icon: const Icon(MdiIcons.formatFontSizeIncrease),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (!isDefault && !isAutomatic) ...[
|
||||
const SizedBox(height: 16),
|
||||
TextButton(
|
||||
onPressed: () => _resetFontSize(ref),
|
||||
child: const Text('Reset to 100%'),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _adjustFontSize(WidgetRef ref, {required bool increase}) async {
|
||||
final current = ref.read(engineSettingsWithDefaultsProvider).fontSizeFactor;
|
||||
final newValue = increase
|
||||
? (current + fontSizeStep).clamp(fontSizeMin, fontSizeMax)
|
||||
: (current - fontSizeStep).clamp(fontSizeMin, fontSizeMax);
|
||||
final rounded = (newValue * 10).round() / 10;
|
||||
|
||||
if (rounded == current) return;
|
||||
|
||||
await ref
|
||||
.read(saveEngineSettingsControllerProvider.notifier)
|
||||
.save(
|
||||
(currentSettings) => currentSettings.copyWith.fontSizeFactor(rounded),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _resetFontSize(WidgetRef ref) async {
|
||||
await ref
|
||||
.read(saveEngineSettingsControllerProvider.notifier)
|
||||
.save(
|
||||
(currentSettings) =>
|
||||
currentSettings.copyWith.fontSizeFactor(fontSizeDefault),
|
||||
);
|
||||
}
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_hooks/flutter_hooks.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/entities/states/history.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers/tab_state.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/presentation/widgets/history_menu_item.dart';
|
||||
|
||||
enum HistoryMenuDirection { back, forward }
|
||||
|
||||
class HistoryMenu extends HookConsumerWidget {
|
||||
const HistoryMenu({
|
||||
super.key,
|
||||
required this.selectedTabId,
|
||||
required this.controller,
|
||||
required this.direction,
|
||||
required this.child,
|
||||
});
|
||||
|
||||
final String? selectedTabId;
|
||||
final MenuController controller;
|
||||
final HistoryMenuDirection direction;
|
||||
final Widget child;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final historyState = ref.watch(
|
||||
tabStateProvider(selectedTabId).select((state) => state?.historyState),
|
||||
);
|
||||
|
||||
final menuItems = useMemoized(() => _buildMenuItems(historyState), [
|
||||
historyState,
|
||||
]);
|
||||
|
||||
return MenuAnchor(
|
||||
controller: controller,
|
||||
consumeOutsideTap: true,
|
||||
menuChildren: menuItems,
|
||||
child: child,
|
||||
);
|
||||
}
|
||||
|
||||
List<Widget> _buildMenuItems(HistoryState? historyState) {
|
||||
if (historyState == null || historyState.items.isEmpty) {
|
||||
return [
|
||||
MenuItemButton(
|
||||
child: Text(
|
||||
direction == HistoryMenuDirection.back
|
||||
? 'No previous pages'
|
||||
: 'No forward pages',
|
||||
),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
final items = historyState.items.indexed;
|
||||
final currentIndex = historyState.currentIndex;
|
||||
|
||||
final historyItems = switch (direction) {
|
||||
// Back: oldest at top, newest at bottom (close to button)
|
||||
HistoryMenuDirection.back => items.where((e) => e.$1 < currentIndex),
|
||||
// Forward: furthest at top, closest at bottom (close to button)
|
||||
HistoryMenuDirection.forward =>
|
||||
items.where((e) => e.$1 > currentIndex).toList().reversed,
|
||||
};
|
||||
|
||||
if (historyItems.isEmpty) {
|
||||
final message = direction == HistoryMenuDirection.back
|
||||
? 'No previous pages'
|
||||
: 'No forward pages';
|
||||
return [MenuItemButton(child: Text(message))];
|
||||
}
|
||||
|
||||
return historyItems
|
||||
.map(
|
||||
(e) => HistoryMenuItem(
|
||||
selectedTabId: selectedTabId,
|
||||
item: e.$2,
|
||||
historyIndex: e.$1,
|
||||
),
|
||||
)
|
||||
.toList();
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/entities/states/history.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers/tab_session.dart';
|
||||
import 'package:weblibre/presentation/widgets/uri_breadcrumb.dart';
|
||||
import 'package:weblibre/presentation/widgets/url_icon.dart';
|
||||
|
||||
class HistoryMenuItem extends HookConsumerWidget {
|
||||
const HistoryMenuItem({
|
||||
super.key,
|
||||
required this.selectedTabId,
|
||||
required this.item,
|
||||
required this.historyIndex,
|
||||
});
|
||||
|
||||
final String? selectedTabId;
|
||||
final HistoryItem item;
|
||||
final int historyIndex;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final theme = Theme.of(context);
|
||||
|
||||
return MenuItemButton(
|
||||
leadingIcon: UrlIcon([item.url], iconSize: 24),
|
||||
closeOnActivate: false,
|
||||
onPressed: () async {
|
||||
await ref
|
||||
.read(tabSessionProvider(tabId: selectedTabId).notifier)
|
||||
.goToHistoryIndex(index: historyIndex);
|
||||
|
||||
if (context.mounted) {
|
||||
MenuController.maybeOf(context)?.close();
|
||||
}
|
||||
},
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(maxWidth: 280),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
item.title.isNotEmpty ? item.title : item.url.authority,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: theme.textTheme.bodyMedium?.copyWith(
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
UriBreadcrumb(
|
||||
uri: item.url,
|
||||
style: theme.textTheme.bodySmall?.copyWith(
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
+418
@@ -0,0 +1,418 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_material_design_icons/flutter_material_design_icons.dart';
|
||||
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:nullability/nullability.dart';
|
||||
import 'package:share_plus/share_plus.dart';
|
||||
import 'package:skeletonizer/skeletonizer.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers/tab_session.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers/tab_state.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/presentation/dialogs/content_selection_dialog.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/presentation/dialogs/qr_code.dart';
|
||||
import 'package:weblibre/features/geckoview/features/tabs/data/database/definitions.drift.dart';
|
||||
import 'package:weblibre/features/geckoview/features/tabs/data/entities/tab_mode.dart';
|
||||
import 'package:weblibre/features/geckoview/features/tabs/domain/repositories/tab.dart';
|
||||
import 'package:weblibre/features/sync/domain/repositories/sync.dart';
|
||||
import 'package:weblibre/presentation/hooks/cached_future.dart';
|
||||
import 'package:weblibre/utils/ui_helper.dart' as ui_helper;
|
||||
|
||||
class ShareMenuItemButton extends HookConsumerWidget {
|
||||
const ShareMenuItemButton({super.key, required this.selectedTabId});
|
||||
|
||||
final String? selectedTabId;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
return MenuItemButton(
|
||||
leadingIcon: const Icon(Icons.share),
|
||||
closeOnActivate: false,
|
||||
onPressed: () async {
|
||||
final tabState = ref.read(tabStateProvider(selectedTabId))!;
|
||||
|
||||
await SharePlus.instance.share(ShareParams(uri: tabState.url));
|
||||
|
||||
if (context.mounted) {
|
||||
MenuController.maybeOf(context)?.close();
|
||||
}
|
||||
},
|
||||
child: const Text('Share Link'),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class ShowQrCodeMenuItemButton extends HookConsumerWidget {
|
||||
const ShowQrCodeMenuItemButton({super.key, required this.selectedTabId});
|
||||
|
||||
final String? selectedTabId;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
return MenuItemButton(
|
||||
leadingIcon: const Icon(Icons.qr_code),
|
||||
closeOnActivate: false,
|
||||
onPressed: () async {
|
||||
final tabState = ref.read(tabStateProvider(selectedTabId))!;
|
||||
|
||||
await showQrCode(context, tabState.url.toString());
|
||||
|
||||
if (context.mounted) {
|
||||
MenuController.maybeOf(context)?.close();
|
||||
}
|
||||
},
|
||||
child: const Text('Show QR Code'),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class SaveToPdfMenuItemButton extends HookConsumerWidget {
|
||||
const SaveToPdfMenuItemButton({super.key, required this.selectedTabId});
|
||||
|
||||
final String? selectedTabId;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
return MenuItemButton(
|
||||
leadingIcon: const Icon(MdiIcons.filePdfBox),
|
||||
closeOnActivate: false,
|
||||
onPressed: () async {
|
||||
await ref
|
||||
.read(tabSessionProvider(tabId: selectedTabId).notifier)
|
||||
.saveToPdf();
|
||||
|
||||
if (context.mounted) {
|
||||
MenuController.maybeOf(context)?.close();
|
||||
}
|
||||
},
|
||||
child: const Text('Export as PDF'),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class PrintMenuItemButton extends HookConsumerWidget {
|
||||
const PrintMenuItemButton({super.key, required this.selectedTabId});
|
||||
|
||||
final String? selectedTabId;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
return MenuItemButton(
|
||||
leadingIcon: const Icon(MdiIcons.printer),
|
||||
closeOnActivate: false,
|
||||
onPressed: () async {
|
||||
try {
|
||||
await ref
|
||||
.read(tabSessionProvider(tabId: selectedTabId).notifier)
|
||||
.printContent();
|
||||
} catch (e) {
|
||||
if (context.mounted) {
|
||||
ui_helper.showErrorMessage(context, 'Failed to print page');
|
||||
}
|
||||
}
|
||||
|
||||
if (context.mounted) {
|
||||
MenuController.maybeOf(context)?.close();
|
||||
}
|
||||
},
|
||||
child: const Text('Print'),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class ShareMarkdownActionMenuItemButton extends HookConsumerWidget {
|
||||
const ShareMarkdownActionMenuItemButton({
|
||||
super.key,
|
||||
required this.selectedTabId,
|
||||
required this.icon,
|
||||
required this.title,
|
||||
required this.shareMarkdownAction,
|
||||
});
|
||||
|
||||
final String selectedTabId;
|
||||
final Widget icon;
|
||||
final Widget title;
|
||||
final Future<void> Function(String content, String? fileName)
|
||||
shareMarkdownAction;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
return MenuItemButton(
|
||||
leadingIcon: icon,
|
||||
closeOnActivate: false,
|
||||
onPressed: () => _handleShare(context, ref),
|
||||
child: title,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _handleShare(BuildContext context, WidgetRef ref) async {
|
||||
final tabData = await ref
|
||||
.read(tabDataRepositoryProvider.notifier)
|
||||
.getTabDataById(selectedTabId);
|
||||
|
||||
if (tabData == null || tabData.fullContentMarkdown.isEmpty) {
|
||||
if (context.mounted) {
|
||||
MenuController.maybeOf(context)?.close();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
final shouldShowDialog =
|
||||
tabData.isProbablyReaderable == true &&
|
||||
tabData.extractedContentMarkdown.isNotEmpty;
|
||||
|
||||
if (shouldShowDialog && context.mounted) {
|
||||
await _showContentSelectionDialog(context, tabData);
|
||||
} else {
|
||||
await shareMarkdownAction(
|
||||
tabData.fullContentMarkdown!,
|
||||
tabData.title ?? tabData.url?.authority,
|
||||
);
|
||||
}
|
||||
|
||||
if (context.mounted) {
|
||||
MenuController.maybeOf(context)?.close();
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _showContentSelectionDialog(
|
||||
BuildContext context,
|
||||
TabData tabData,
|
||||
) async {
|
||||
await showContentSelectionDialog(
|
||||
context,
|
||||
title: title,
|
||||
tabData: tabData,
|
||||
shareMarkdownAction: shareMarkdownAction,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class ShareScreenshotMenuItemButton extends HookConsumerWidget {
|
||||
const ShareScreenshotMenuItemButton({super.key, required this.selectedTabId});
|
||||
|
||||
final String? selectedTabId;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
return MenuItemButton(
|
||||
leadingIcon: const Icon(Icons.mobile_screen_share),
|
||||
closeOnActivate: false,
|
||||
child: const Text('Share Screenshot'),
|
||||
onPressed: () async {
|
||||
final screenshot = await ref
|
||||
.read(selectedTabSessionProvider)
|
||||
.requestScreenshot();
|
||||
|
||||
final tabState = ref.read(tabStateProvider(selectedTabId))!;
|
||||
|
||||
if (screenshot != null) {
|
||||
ui.decodeImageFromList(screenshot, (result) async {
|
||||
try {
|
||||
final png = await result.toByteData(
|
||||
format: ui.ImageByteFormat.png,
|
||||
);
|
||||
|
||||
if (png != null) {
|
||||
final file = XFile.fromData(
|
||||
png.buffer.asUint8List(),
|
||||
mimeType: 'image/png',
|
||||
);
|
||||
|
||||
await SharePlus.instance.share(
|
||||
ShareParams(
|
||||
files: [file],
|
||||
subject: tabState.titleOrAuthority,
|
||||
),
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
result.dispose();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (context.mounted) {
|
||||
MenuController.maybeOf(context)?.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class OpenInAppMenuItemButton extends HookConsumerWidget {
|
||||
const OpenInAppMenuItemButton({super.key, required this.selectedTabId});
|
||||
|
||||
static final _service = GeckoAppLinksService();
|
||||
|
||||
final String? selectedTabId;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final tabState = ref.watch(tabStateProvider(selectedTabId));
|
||||
final url = tabState?.url;
|
||||
final hasExternalApp = useCachedFuture(
|
||||
// ignore: discarded_futures useFuture
|
||||
() => url != null ? _service.hasExternalApp(url) : Future.value(false),
|
||||
[url],
|
||||
);
|
||||
|
||||
if (hasExternalApp.data != true) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
|
||||
return MenuItemButton(
|
||||
leadingIcon: const Icon(Icons.open_in_new),
|
||||
closeOnActivate: false,
|
||||
child: const Text('Open in App'),
|
||||
onPressed: () async {
|
||||
if (url == null) return;
|
||||
|
||||
final success = await _service.openAppLink(url);
|
||||
|
||||
if (success && context.mounted) {
|
||||
MenuController.maybeOf(context)?.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class CopyAddressMenuItemButton extends HookConsumerWidget {
|
||||
const CopyAddressMenuItemButton({super.key, required this.selectedTabId});
|
||||
|
||||
final String? selectedTabId;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
return MenuItemButton(
|
||||
leadingIcon: const Icon(MdiIcons.contentCopy),
|
||||
closeOnActivate: false,
|
||||
child: const Text('Copy Address'),
|
||||
onPressed: () async {
|
||||
final tabState = ref.read(tabStateProvider(selectedTabId))!;
|
||||
|
||||
await Clipboard.setData(ClipboardData(text: tabState.url.toString()));
|
||||
|
||||
if (context.mounted) {
|
||||
MenuController.maybeOf(context)?.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class SendTabToDeviceMenuItemButton extends HookConsumerWidget {
|
||||
final String? selectedTabId;
|
||||
|
||||
const SendTabToDeviceMenuItemButton({super.key, required this.selectedTabId});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
if (selectedTabId == null) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
|
||||
final isAuthenticated = ref.watch(syncIsAuthenticatedProvider);
|
||||
final devices = ref.watch(syncDevicesProvider);
|
||||
|
||||
if (!isAuthenticated) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
|
||||
return Skeletonizer(
|
||||
enabled: devices.isLoading && devices.value == null,
|
||||
child: SubmenuButton(
|
||||
leadingIcon: const Icon(Icons.send_outlined),
|
||||
menuChildren: devices.when(
|
||||
data: (deviceList) {
|
||||
final targets = deviceList
|
||||
.where((device) => !device.isCurrentDevice && device.canSendTab)
|
||||
.toList(growable: false);
|
||||
|
||||
if (targets.isEmpty) {
|
||||
return const [MenuItemButton(child: Text('No target devices'))];
|
||||
}
|
||||
|
||||
return targets
|
||||
.map((device) {
|
||||
return MenuItemButton(
|
||||
closeOnActivate: false,
|
||||
leadingIcon: const Icon(Icons.devices_other),
|
||||
child: Text(device.displayName),
|
||||
onPressed: () async {
|
||||
final tabState = ref.read(
|
||||
tabStateProvider(selectedTabId),
|
||||
);
|
||||
if (tabState == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
final title = tabState.title.isNotEmpty
|
||||
? tabState.title
|
||||
: tabState.url.toString();
|
||||
|
||||
final success = await ref
|
||||
.read(syncRepositoryProvider.notifier)
|
||||
.sendTabToDevice(
|
||||
deviceId: device.deviceId,
|
||||
title: title,
|
||||
url: tabState.url.toString(),
|
||||
private: tabState.tabMode == TabMode.private,
|
||||
);
|
||||
|
||||
if (context.mounted) {
|
||||
if (success) {
|
||||
ui_helper.showInfoMessage(
|
||||
context,
|
||||
'Sent tab to ${device.displayName}',
|
||||
);
|
||||
} else {
|
||||
ui_helper.showErrorMessage(
|
||||
context,
|
||||
'Failed to send tab',
|
||||
);
|
||||
}
|
||||
|
||||
MenuController.maybeOf(context)?.close();
|
||||
}
|
||||
},
|
||||
);
|
||||
})
|
||||
.toList(growable: false);
|
||||
},
|
||||
loading: () => const [
|
||||
MenuItemButton(
|
||||
leadingIcon: Icon(Icons.devices_other),
|
||||
child: Text('Loading devices...'),
|
||||
),
|
||||
],
|
||||
error: (_, _) => const [
|
||||
MenuItemButton(child: Text('Failed to load devices')),
|
||||
],
|
||||
),
|
||||
child: const Text('Send To Device'),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
+174
@@ -0,0 +1,174 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers/tab_session.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers/tab_state.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/presentation/widgets/history_menu.dart';
|
||||
import 'package:weblibre/features/geckoview/features/readerview/presentation/controllers/readerable.dart';
|
||||
import 'package:weblibre/presentation/hooks/menu_controller.dart';
|
||||
|
||||
class NavigateForwardButtonView extends StatelessWidget {
|
||||
const NavigateForwardButtonView({
|
||||
super.key,
|
||||
required this.canGoForward,
|
||||
this.onPressed,
|
||||
this.onLongPress,
|
||||
});
|
||||
|
||||
final bool canGoForward;
|
||||
final VoidCallback? onPressed;
|
||||
final VoidCallback? onLongPress;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return IconButton(
|
||||
onPressed: canGoForward ? onPressed : null,
|
||||
onLongPress: canGoForward ? onLongPress : null,
|
||||
icon: const Icon(Icons.arrow_forward),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class NavigateBackButtonView extends StatelessWidget {
|
||||
const NavigateBackButtonView({
|
||||
super.key,
|
||||
required this.canGoBack,
|
||||
required this.isLoading,
|
||||
this.onPressed,
|
||||
this.onLongPress,
|
||||
});
|
||||
|
||||
final bool canGoBack;
|
||||
final bool isLoading;
|
||||
final VoidCallback? onPressed;
|
||||
final VoidCallback? onLongPress;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return IconButton(
|
||||
onPressed: (canGoBack || isLoading) ? onPressed : null,
|
||||
onLongPress: (canGoBack && !isLoading) ? onLongPress : null,
|
||||
icon: isLoading ? const Icon(Icons.close) : const Icon(Icons.arrow_back),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class NavigateForwardButton extends HookConsumerWidget {
|
||||
const NavigateForwardButton({
|
||||
super.key,
|
||||
required this.selectedTabId,
|
||||
this.menuControllerToClose,
|
||||
this.canGoForward = true,
|
||||
});
|
||||
|
||||
final String? selectedTabId;
|
||||
final MenuController? menuControllerToClose;
|
||||
final bool canGoForward;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final historyMenuController = useMenuController();
|
||||
|
||||
return HistoryMenu(
|
||||
selectedTabId: selectedTabId,
|
||||
controller: historyMenuController,
|
||||
direction: HistoryMenuDirection.forward,
|
||||
child: NavigateForwardButtonView(
|
||||
canGoForward: canGoForward,
|
||||
onPressed: () async {
|
||||
final controller = ref.read(
|
||||
tabSessionProvider(tabId: selectedTabId).notifier,
|
||||
);
|
||||
|
||||
await controller.goForward();
|
||||
menuControllerToClose?.close();
|
||||
},
|
||||
onLongPress: () {
|
||||
if (historyMenuController.isOpen) {
|
||||
historyMenuController.close();
|
||||
} else {
|
||||
historyMenuController.open();
|
||||
}
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class NavigateBackButton extends HookConsumerWidget {
|
||||
const NavigateBackButton({
|
||||
super.key,
|
||||
required this.selectedTabId,
|
||||
required this.isLoading,
|
||||
this.menuControllerToClose,
|
||||
this.canGoBack = true,
|
||||
});
|
||||
|
||||
final String? selectedTabId;
|
||||
final bool isLoading;
|
||||
final MenuController? menuControllerToClose;
|
||||
final bool canGoBack;
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final historyMenuController = useMenuController();
|
||||
|
||||
return HistoryMenu(
|
||||
selectedTabId: selectedTabId,
|
||||
controller: historyMenuController,
|
||||
direction: HistoryMenuDirection.back,
|
||||
child: NavigateBackButtonView(
|
||||
canGoBack: canGoBack,
|
||||
isLoading: isLoading,
|
||||
onPressed: () async {
|
||||
final controller = ref.read(
|
||||
tabSessionProvider(tabId: selectedTabId).notifier,
|
||||
);
|
||||
|
||||
final isReaderActive = ref.read(
|
||||
selectedTabStateProvider.select(
|
||||
(state) => state?.readerableState.active ?? false,
|
||||
),
|
||||
);
|
||||
|
||||
if (isLoading) {
|
||||
await controller.stopLoading();
|
||||
} else if (isReaderActive) {
|
||||
await ref
|
||||
.read(readerableScreenControllerProvider.notifier)
|
||||
.toggleReaderView(false);
|
||||
} else {
|
||||
await controller.goBack();
|
||||
}
|
||||
|
||||
menuControllerToClose?.close();
|
||||
},
|
||||
onLongPress: () {
|
||||
if (historyMenuController.isOpen) {
|
||||
historyMenuController.close();
|
||||
} else {
|
||||
historyMenuController.open();
|
||||
}
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
+470
@@ -0,0 +1,470 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
import 'dart:async';
|
||||
import 'dart:ui' as ui;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:flutter_hooks/flutter_hooks.dart';
|
||||
import 'package:flutter_material_design_icons/flutter_material_design_icons.dart';
|
||||
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:share_plus/share_plus.dart';
|
||||
import 'package:skeletonizer/skeletonizer.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers/tab_session.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers/tab_state.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/presentation/dialogs/qr_code.dart';
|
||||
import 'package:weblibre/features/geckoview/features/open_link_tools/domain/entities/url_cleaner_result.dart';
|
||||
import 'package:weblibre/features/geckoview/features/open_link_tools/domain/services/url_cleaner_catalog_service.dart';
|
||||
import 'package:weblibre/features/geckoview/features/open_link_tools/presentation/dialogs/tracking_details_dialog.dart';
|
||||
import 'package:weblibre/features/geckoview/features/open_link_tools/presentation/hooks/url_cleaner_controller.dart';
|
||||
import 'package:weblibre/features/geckoview/features/tabs/data/entities/tab_mode.dart';
|
||||
import 'package:weblibre/features/sync/domain/repositories/sync.dart';
|
||||
import 'package:weblibre/features/user/domain/repositories/general_settings.dart';
|
||||
import 'package:weblibre/presentation/hooks/cached_future.dart';
|
||||
import 'package:weblibre/utils/ui_helper.dart' as ui_helper;
|
||||
|
||||
Future<void> showShareBottomSheet(
|
||||
BuildContext context, {
|
||||
required String selectedTabId,
|
||||
}) {
|
||||
return showModalBottomSheet(
|
||||
context: context,
|
||||
shape: const RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
|
||||
),
|
||||
builder: (context) => ShareBottomSheet(selectedTabId: selectedTabId),
|
||||
);
|
||||
}
|
||||
|
||||
class ShareBottomSheet extends HookConsumerWidget {
|
||||
final String selectedTabId;
|
||||
|
||||
const ShareBottomSheet({super.key, required this.selectedTabId});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final settings = ref.watch(generalSettingsWithDefaultsProvider);
|
||||
final catalogAsync = ref.watch(urlCleanerCatalogServiceProvider);
|
||||
|
||||
final tabUrl = ref.watch(
|
||||
tabStateProvider(selectedTabId).select((v) => v?.url),
|
||||
);
|
||||
|
||||
final cleanedUrl = useState<Uri?>(null);
|
||||
final cleaner = useUrlCleanerController(
|
||||
sourceUrl: (cleanedUrl.value ?? tabUrl)?.toString(),
|
||||
rules: catalogAsync.value,
|
||||
cleanerEnabled: settings.urlCleanerEnabled,
|
||||
allowReferralMarketing: settings.urlCleanerAllowReferralMarketing,
|
||||
autoApply: settings.urlCleanerAutoApply,
|
||||
getCurrentUrl: () => (cleanedUrl.value ?? tabUrl)?.toString(),
|
||||
onApplyCleanedUrl: (cleanedUrlValue) {
|
||||
cleanedUrl.value = Uri.parse(cleanedUrlValue);
|
||||
},
|
||||
);
|
||||
|
||||
void applyCleanUrl() {
|
||||
if (cleaner.applyCleanUrl()) {
|
||||
ui_helper.showInfoMessage(context, 'URL cleaned');
|
||||
}
|
||||
}
|
||||
|
||||
void applySelectedTrackingRemovals(String previewUrl) {
|
||||
if (cleaner.applyPreviewUrl(previewUrl)) {
|
||||
ui_helper.showInfoMessage(context, 'URL preview applied');
|
||||
}
|
||||
}
|
||||
|
||||
final effectiveUrl = cleanedUrl.value ?? tabUrl;
|
||||
final cleaningHappened = cleanedUrl.value != null;
|
||||
final hasActiveTracking = cleaner.result?.removedParams.isNotEmpty ?? false;
|
||||
final urlWasCleaned = cleaningHappened && !hasActiveTracking;
|
||||
final trackingStatusTrailing = cleaningHappened
|
||||
? Icon(
|
||||
hasActiveTracking
|
||||
? MdiIcons.shieldLinkVariantOutline
|
||||
: MdiIcons.shieldLinkVariant,
|
||||
size: 18,
|
||||
color: Theme.of(context).colorScheme.primary,
|
||||
)
|
||||
: null;
|
||||
final showCleanerTile = tabUrl != null && cleaner.showTile;
|
||||
|
||||
return SafeArea(
|
||||
child: SingleChildScrollView(
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
// Header with URL and tracking status
|
||||
_ShareHeader(
|
||||
url: effectiveUrl?.toString() ?? '',
|
||||
urlWasCleaned: urlWasCleaned,
|
||||
hasTracking: showCleanerTile && !cleaner.applied,
|
||||
cleanerResult: showCleanerTile ? cleaner.result : null,
|
||||
allowReferralMarketing: settings.urlCleanerAllowReferralMarketing,
|
||||
onClean: showCleanerTile && !cleaner.applied
|
||||
? applyCleanUrl
|
||||
: null,
|
||||
onApplySelectedRemovals: applySelectedTrackingRemovals,
|
||||
),
|
||||
|
||||
// Copy Address
|
||||
ListTile(
|
||||
leading: const Icon(MdiIcons.contentCopy),
|
||||
title: const Text('Copy Address'),
|
||||
trailing: trackingStatusTrailing,
|
||||
onTap: () async {
|
||||
await Clipboard.setData(
|
||||
ClipboardData(text: effectiveUrl.toString()),
|
||||
);
|
||||
if (context.mounted) Navigator.pop(context);
|
||||
},
|
||||
),
|
||||
|
||||
// Open in App (conditional)
|
||||
_OpenInAppTile(selectedTabId: selectedTabId),
|
||||
|
||||
// Share Screenshot
|
||||
ListTile(
|
||||
leading: const Icon(Icons.mobile_screen_share),
|
||||
title: const Text('Share Screenshot'),
|
||||
onTap: () async {
|
||||
final screenshot = await ref
|
||||
.read(selectedTabSessionProvider)
|
||||
.requestScreenshot();
|
||||
|
||||
final ts = ref.read(tabStateProvider(selectedTabId))!;
|
||||
|
||||
if (screenshot != null) {
|
||||
ui.decodeImageFromList(screenshot, (result) async {
|
||||
try {
|
||||
final png = await result.toByteData(
|
||||
format: ui.ImageByteFormat.png,
|
||||
);
|
||||
|
||||
if (png != null) {
|
||||
final file = XFile.fromData(
|
||||
png.buffer.asUint8List(),
|
||||
mimeType: 'image/png',
|
||||
);
|
||||
|
||||
await SharePlus.instance.share(
|
||||
ShareParams(
|
||||
files: [file],
|
||||
subject: ts.titleOrAuthority,
|
||||
),
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
result.dispose();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (context.mounted) Navigator.pop(context);
|
||||
},
|
||||
),
|
||||
|
||||
// Share Link
|
||||
ListTile(
|
||||
leading: const Icon(Icons.share),
|
||||
title: const Text('Share Link'),
|
||||
trailing: trackingStatusTrailing,
|
||||
onTap: () async {
|
||||
await SharePlus.instance.share(ShareParams(uri: effectiveUrl));
|
||||
if (context.mounted) Navigator.pop(context);
|
||||
},
|
||||
),
|
||||
|
||||
// Send To Device (conditional)
|
||||
_SendToDeviceTile(selectedTabId: selectedTabId),
|
||||
|
||||
// Show QR Code
|
||||
ListTile(
|
||||
leading: const Icon(Icons.qr_code),
|
||||
title: const Text('Show QR Code'),
|
||||
trailing: trackingStatusTrailing,
|
||||
onTap: () async {
|
||||
if (context.mounted) {
|
||||
Navigator.pop(context);
|
||||
await showQrCode(context, effectiveUrl.toString());
|
||||
}
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _ShareHeader extends StatelessWidget {
|
||||
final String url;
|
||||
final bool urlWasCleaned;
|
||||
final bool hasTracking;
|
||||
final UrlCleanerResult? cleanerResult;
|
||||
final bool allowReferralMarketing;
|
||||
final VoidCallback? onClean;
|
||||
final ValueChanged<String>? onApplySelectedRemovals;
|
||||
|
||||
const _ShareHeader({
|
||||
required this.url,
|
||||
required this.urlWasCleaned,
|
||||
required this.hasTracking,
|
||||
required this.allowReferralMarketing,
|
||||
this.cleanerResult,
|
||||
this.onClean,
|
||||
this.onApplySelectedRemovals,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
final paramCount = cleanerResult?.removedParams.length ?? 0;
|
||||
final hasTappableDetails = paramCount > 0;
|
||||
|
||||
return InkWell(
|
||||
onTap: hasTappableDetails
|
||||
? () {
|
||||
unawaited(
|
||||
showDialog(
|
||||
context: context,
|
||||
builder: (context) => TrackingDetailsDialog(
|
||||
currentUrl: url,
|
||||
result: cleanerResult!,
|
||||
allowReferralMarketing: allowReferralMarketing,
|
||||
onApplySelectedRemovals: onApplySelectedRemovals,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
: null,
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.surfaceContainerHighest,
|
||||
borderRadius: const BorderRadius.vertical(top: Radius.circular(16)),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
url,
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: TextStyle(
|
||||
color: urlWasCleaned
|
||||
? colorScheme.primary
|
||||
: colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
if (hasTracking)
|
||||
Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.warning_amber_rounded,
|
||||
size: 14,
|
||||
color: colorScheme.error,
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
paramCount == 1
|
||||
? '1 tracking parameter detected'
|
||||
: '$paramCount tracking parameters detected',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: colorScheme.error,
|
||||
),
|
||||
),
|
||||
],
|
||||
)
|
||||
else if (urlWasCleaned)
|
||||
Row(
|
||||
children: [
|
||||
Icon(
|
||||
MdiIcons.checkCircle,
|
||||
size: 14,
|
||||
color: colorScheme.primary,
|
||||
),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
'Link is clean',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: colorScheme.primary,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (hasTracking && onClean != null)
|
||||
IconButton.filledTonal(
|
||||
onPressed: onClean,
|
||||
icon: const Icon(MdiIcons.linkVariantRemove),
|
||||
tooltip: 'Remove tracking',
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _OpenInAppTile extends HookConsumerWidget {
|
||||
final String selectedTabId;
|
||||
|
||||
static final _service = GeckoAppLinksService();
|
||||
|
||||
const _OpenInAppTile({required this.selectedTabId});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final tabState = ref.watch(tabStateProvider(selectedTabId));
|
||||
final url = tabState?.url;
|
||||
final hasExternalApp = useCachedFuture(
|
||||
() => url != null ? _service.hasExternalApp(url) : Future.value(false),
|
||||
[url],
|
||||
);
|
||||
|
||||
if (hasExternalApp.data != true) return const SizedBox.shrink();
|
||||
|
||||
return ListTile(
|
||||
leading: const Icon(Icons.open_in_new),
|
||||
title: const Text('Open in App'),
|
||||
onTap: () async {
|
||||
if (url == null) return;
|
||||
final success = await _service.openAppLink(url);
|
||||
if (success && context.mounted) Navigator.pop(context);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _SendToDeviceTile extends ConsumerWidget {
|
||||
final String selectedTabId;
|
||||
|
||||
const _SendToDeviceTile({required this.selectedTabId});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final isAuthenticated = ref.watch(syncIsAuthenticatedProvider);
|
||||
final devices = ref.watch(syncDevicesProvider);
|
||||
|
||||
if (!isAuthenticated) return const SizedBox.shrink();
|
||||
|
||||
return Skeletonizer(
|
||||
enabled: devices.isLoading && devices.value == null,
|
||||
child: Theme(
|
||||
data: Theme.of(context).copyWith(dividerColor: Colors.transparent),
|
||||
child: ExpansionTile(
|
||||
leading: const Icon(Icons.send_outlined),
|
||||
title: const Text('Send To Device'),
|
||||
children: devices.when(
|
||||
data: (deviceList) {
|
||||
final targets = deviceList
|
||||
.where(
|
||||
(device) => !device.isCurrentDevice && device.canSendTab,
|
||||
)
|
||||
.toList(growable: false);
|
||||
|
||||
if (targets.isEmpty) {
|
||||
return const [
|
||||
ListTile(
|
||||
contentPadding: EdgeInsets.only(left: 72, right: 16),
|
||||
title: Text('No target devices'),
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
return targets
|
||||
.map(
|
||||
(device) => ListTile(
|
||||
contentPadding: const EdgeInsets.only(
|
||||
left: 72,
|
||||
right: 16,
|
||||
),
|
||||
leading: const Icon(Icons.devices_other, size: 18),
|
||||
title: Text(device.displayName),
|
||||
dense: true,
|
||||
onTap: () async {
|
||||
final tabState = ref.read(
|
||||
tabStateProvider(selectedTabId),
|
||||
);
|
||||
if (tabState == null) return;
|
||||
|
||||
final title = tabState.title.isNotEmpty
|
||||
? tabState.title
|
||||
: tabState.url.toString();
|
||||
|
||||
final success = await ref
|
||||
.read(syncRepositoryProvider.notifier)
|
||||
.sendTabToDevice(
|
||||
deviceId: device.deviceId,
|
||||
title: title,
|
||||
url: tabState.url.toString(),
|
||||
private: tabState.tabMode == TabMode.private,
|
||||
);
|
||||
|
||||
if (context.mounted) {
|
||||
Navigator.pop(context);
|
||||
if (success) {
|
||||
ui_helper.showInfoMessage(
|
||||
context,
|
||||
'Sent tab to ${device.displayName}',
|
||||
);
|
||||
} else {
|
||||
ui_helper.showErrorMessage(
|
||||
context,
|
||||
'Failed to send tab',
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
),
|
||||
)
|
||||
.toList(growable: false);
|
||||
},
|
||||
loading: () => const [
|
||||
ListTile(
|
||||
contentPadding: EdgeInsets.only(left: 72, right: 16),
|
||||
leading: Icon(Icons.devices_other, size: 18),
|
||||
title: Text('Loading devices...'),
|
||||
),
|
||||
],
|
||||
error: (_, _) => const [
|
||||
ListTile(
|
||||
contentPadding: EdgeInsets.only(left: 72, right: 16),
|
||||
title: Text('Failed to load devices'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
+241
@@ -0,0 +1,241 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_hooks/flutter_hooks.dart';
|
||||
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:weblibre/core/logger.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers/tab_session.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/presentation/dialogs/clear_site_data_dialog.dart';
|
||||
import 'package:weblibre/utils/ui_helper.dart';
|
||||
|
||||
/// Section widget for clearing site data
|
||||
class ClearSiteDataSection extends HookConsumerWidget {
|
||||
final Uri url;
|
||||
final ValueChanged<bool>? onExpandedChanged;
|
||||
|
||||
const ClearSiteDataSection({
|
||||
required this.url,
|
||||
this.onExpandedChanged,
|
||||
super.key,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final isExpanded = useState(false);
|
||||
final isClearing = useState(false);
|
||||
final selectedTypes = useState<Set<ClearDataType>>({
|
||||
ClearDataType.allSiteData,
|
||||
ClearDataType.authSessions,
|
||||
});
|
||||
|
||||
void toggleType(ClearDataType type) {
|
||||
final newTypes = Set<ClearDataType>.from(selectedTypes.value);
|
||||
if (newTypes.contains(type)) {
|
||||
newTypes.remove(type);
|
||||
} else {
|
||||
newTypes.add(type);
|
||||
}
|
||||
selectedTypes.value = newTypes;
|
||||
}
|
||||
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
ListTile(
|
||||
leading: const Icon(Icons.delete_sweep),
|
||||
title: const Text('Clear Site Data'),
|
||||
subtitle: Text(
|
||||
isExpanded.value
|
||||
? 'Select data types to clear'
|
||||
: 'Cookies, cache, and site data',
|
||||
),
|
||||
trailing: Icon(
|
||||
isExpanded.value ? Icons.expand_less : Icons.expand_more,
|
||||
),
|
||||
onTap: () {
|
||||
final newValue = !isExpanded.value;
|
||||
isExpanded.value = newValue;
|
||||
onExpandedChanged?.call(newValue);
|
||||
},
|
||||
),
|
||||
if (isExpanded.value) ...[
|
||||
_DataTypeCheckbox(
|
||||
label: 'Cookies',
|
||||
subtitle: 'Login tokens, preferences, tracking data',
|
||||
type: ClearDataType.cookies,
|
||||
isSelected: selectedTypes.value.contains(ClearDataType.cookies),
|
||||
onChanged: (selected) => toggleType(ClearDataType.cookies),
|
||||
),
|
||||
_DataTypeCheckbox(
|
||||
label: 'Cached Files',
|
||||
subtitle: 'Images, scripts, stylesheets',
|
||||
type: ClearDataType.allCaches,
|
||||
isSelected: selectedTypes.value.contains(ClearDataType.allCaches),
|
||||
onChanged: (selected) => toggleType(ClearDataType.allCaches),
|
||||
),
|
||||
_DataTypeCheckbox(
|
||||
label: 'Site Data',
|
||||
subtitle: 'Offline storage, databases, local files',
|
||||
type: ClearDataType.allSiteData,
|
||||
isSelected: selectedTypes.value.contains(ClearDataType.allSiteData),
|
||||
onChanged: (selected) => toggleType(ClearDataType.allSiteData),
|
||||
),
|
||||
_DataTypeCheckbox(
|
||||
label: 'Auth Sessions',
|
||||
subtitle: 'Saved logins, active sessions',
|
||||
type: ClearDataType.authSessions,
|
||||
isSelected: selectedTypes.value.contains(
|
||||
ClearDataType.authSessions,
|
||||
),
|
||||
onChanged: (selected) => toggleType(ClearDataType.authSessions),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 16.0,
|
||||
vertical: 8.0,
|
||||
),
|
||||
child: SizedBox(
|
||||
width: double.infinity,
|
||||
child: FilledButton.icon(
|
||||
onPressed: isClearing.value || selectedTypes.value.isEmpty
|
||||
? null
|
||||
: () => _showConfirmationAndClear(
|
||||
context,
|
||||
ref,
|
||||
isClearing,
|
||||
selectedTypes.value,
|
||||
),
|
||||
icon: isClearing.value
|
||||
? const SizedBox(
|
||||
width: 16,
|
||||
height: 16,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: const Icon(Icons.delete),
|
||||
label: Text(isClearing.value ? 'Clearing...' : 'Clear Now'),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _showConfirmationAndClear(
|
||||
BuildContext context,
|
||||
WidgetRef ref,
|
||||
ValueNotifier<bool> isClearing,
|
||||
Set<ClearDataType> selectedTypes,
|
||||
) async {
|
||||
if (selectedTypes.isEmpty) {
|
||||
showErrorMessage(context, 'Select at least one data type');
|
||||
return;
|
||||
}
|
||||
|
||||
final confirmed = await showClearSiteDataDialog(
|
||||
context,
|
||||
host: url.host,
|
||||
formattedTypes: _formatTypes(selectedTypes),
|
||||
);
|
||||
|
||||
if (confirmed == true && context.mounted) {
|
||||
isClearing.value = true;
|
||||
try {
|
||||
await _clearData(ref, selectedTypes);
|
||||
if (context.mounted) {
|
||||
showInfoMessage(context, 'Site data cleared');
|
||||
}
|
||||
} catch (e, s) {
|
||||
logger.e('Failed to clear site data', error: e, stackTrace: s);
|
||||
if (context.mounted) {
|
||||
showErrorMessage(context, 'Failed to clear site data: $e');
|
||||
}
|
||||
} finally {
|
||||
isClearing.value = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
String _formatTypes(Set<ClearDataType> types) {
|
||||
final labels = types.map((t) {
|
||||
switch (t) {
|
||||
case ClearDataType.cookies:
|
||||
return 'cookies';
|
||||
case ClearDataType.allCaches:
|
||||
return 'cached files';
|
||||
case ClearDataType.allSiteData:
|
||||
return 'site data';
|
||||
case ClearDataType.authSessions:
|
||||
return 'auth sessions';
|
||||
}
|
||||
}).toList();
|
||||
|
||||
if (labels.length == 1) return labels.first;
|
||||
if (labels.length == 2) return '${labels[0]} and ${labels[1]}';
|
||||
return '${labels.sublist(0, labels.length - 1).join(', ')}, and ${labels.last}';
|
||||
}
|
||||
|
||||
Future<void> _clearData(
|
||||
WidgetRef ref,
|
||||
Set<ClearDataType> selectedTypes,
|
||||
) async {
|
||||
final host = url.host;
|
||||
|
||||
// Get base domain using PSL API (falls back to host on error)
|
||||
final pslApi = GeckoPublicSuffixListApi();
|
||||
final baseDomain = await pslApi.getPublicSuffixPlusOne(host);
|
||||
|
||||
// Clear data via API
|
||||
final clearApi = GeckoDeleteBrowsingDataController();
|
||||
await clearApi.clearDataForHost(baseDomain, selectedTypes.toList());
|
||||
|
||||
// Reload tab
|
||||
await ref.read(selectedTabSessionProvider).reload();
|
||||
}
|
||||
}
|
||||
|
||||
class _DataTypeCheckbox extends StatelessWidget {
|
||||
final String label;
|
||||
final String subtitle;
|
||||
final ClearDataType type;
|
||||
final bool isSelected;
|
||||
final ValueChanged<bool> onChanged;
|
||||
|
||||
const _DataTypeCheckbox({
|
||||
required this.label,
|
||||
required this.subtitle,
|
||||
required this.type,
|
||||
required this.isSelected,
|
||||
required this.onChanged,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return CheckboxListTile(
|
||||
title: Text(label),
|
||||
subtitle: Text(subtitle),
|
||||
value: isSelected,
|
||||
onChanged: (value) => onChanged(value ?? false),
|
||||
controlAffinity: ListTileControlAffinity.trailing,
|
||||
);
|
||||
}
|
||||
}
|
||||
+311
@@ -0,0 +1,311 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_hooks/flutter_hooks.dart';
|
||||
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
|
||||
import 'package:hooks_riverpod/hooks_riverpod.dart';
|
||||
import 'package:weblibre/features/geckoview/domain/providers/tab_session.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/domain/entities/permission_type.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/domain/entities/site_permissions.dart';
|
||||
import 'package:weblibre/features/geckoview/features/browser/domain/repositories/site_permissions.dart';
|
||||
|
||||
/// Section widget displaying site permissions with toggles
|
||||
class PermissionsSection extends HookConsumerWidget {
|
||||
final String origin;
|
||||
final bool isPrivate;
|
||||
|
||||
const PermissionsSection({
|
||||
required this.origin,
|
||||
required this.isPrivate,
|
||||
super.key,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final permissionsAsync = ref.watch(
|
||||
sitePermissionsRepositoryProvider(origin: origin, isPrivate: isPrivate),
|
||||
);
|
||||
|
||||
return permissionsAsync.when(
|
||||
data: (permissions) => _PermissionsList(
|
||||
origin: origin,
|
||||
isPrivate: isPrivate,
|
||||
permissions: permissions,
|
||||
),
|
||||
loading: () => const Padding(
|
||||
padding: EdgeInsets.all(16.0),
|
||||
child: Center(child: CircularProgressIndicator()),
|
||||
),
|
||||
error: (error, stack) => Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Text('Error loading permissions: $error'),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _PermissionsList extends HookConsumerWidget {
|
||||
final String origin;
|
||||
final bool isPrivate;
|
||||
final SitePermissions? permissions;
|
||||
|
||||
const _PermissionsList({
|
||||
required this.origin,
|
||||
required this.isPrivate,
|
||||
required this.permissions,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final showAll = useState(false);
|
||||
|
||||
// Memoize the update callback to avoid recreating closures
|
||||
Future<void> updatePermission(PermissionUpdater updater) async {
|
||||
await ref
|
||||
.read(
|
||||
sitePermissionsRepositoryProvider(
|
||||
origin: origin,
|
||||
isPrivate: isPrivate,
|
||||
).notifier,
|
||||
)
|
||||
.updatePermission(updater);
|
||||
await ref.read(selectedTabSessionProvider).reload();
|
||||
}
|
||||
|
||||
// Build permission entries - only recalculates when permissions change
|
||||
final allPermissions = useMemoized(
|
||||
() => PermissionType.values
|
||||
.map(
|
||||
(type) => _PermissionEntry(
|
||||
icon: type.icon,
|
||||
label: type.label,
|
||||
status: permissions.getStatus(type),
|
||||
onChanged: (status) =>
|
||||
updatePermission((w) => w.withStatus(type, status)),
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
[permissions],
|
||||
);
|
||||
|
||||
// Filter to only show permissions that have been explicitly set (not noDecision)
|
||||
// Only recalculates when allPermissions changes
|
||||
final setPermissions = useMemoized(
|
||||
() => allPermissions
|
||||
.where(
|
||||
(p) =>
|
||||
p.status != null && p.status != SitePermissionStatus.noDecision,
|
||||
)
|
||||
.toList(),
|
||||
[allPermissions],
|
||||
);
|
||||
|
||||
final permissionsToShow = showAll.value ? allPermissions : setPermissions;
|
||||
final hiddenCount = allPermissions.length - setPermissions.length;
|
||||
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0),
|
||||
child: Row(
|
||||
children: [
|
||||
Text(
|
||||
'Permissions',
|
||||
style: Theme.of(context).textTheme.titleSmall?.copyWith(
|
||||
color: Theme.of(context).colorScheme.primary,
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
if (hiddenCount > 0)
|
||||
TextButton(
|
||||
onPressed: () => showAll.value = !showAll.value,
|
||||
child: Text(showAll.value ? 'Show less' : 'Show all'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
...permissionsToShow.map(
|
||||
(entry) => _PermissionTile(
|
||||
icon: entry.icon,
|
||||
label: entry.label,
|
||||
status: entry.status,
|
||||
onChanged: entry.onChanged,
|
||||
),
|
||||
),
|
||||
if (permissionsToShow.isEmpty && !showAll.value)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 16.0,
|
||||
vertical: 8.0,
|
||||
),
|
||||
child: Text(
|
||||
'No permissions set for this site',
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: Theme.of(context).colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8.0),
|
||||
_AutoplayTile(
|
||||
audibleStatus: permissions?.autoplayAudible,
|
||||
inaudibleStatus: permissions?.autoplayInaudible,
|
||||
onChanged: (audible, inaudible) => updatePermission(
|
||||
(p) => p.copyWith(
|
||||
autoplayAudible: audible,
|
||||
autoplayInaudible: inaudible,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _PermissionEntry {
|
||||
final IconData icon;
|
||||
final String label;
|
||||
final SitePermissionStatus? status;
|
||||
final ValueChanged<SitePermissionStatus> onChanged;
|
||||
|
||||
_PermissionEntry({
|
||||
required this.icon,
|
||||
required this.label,
|
||||
required this.status,
|
||||
required this.onChanged,
|
||||
});
|
||||
}
|
||||
|
||||
class _PermissionTile extends StatelessWidget {
|
||||
final IconData icon;
|
||||
final String label;
|
||||
final SitePermissionStatus? status;
|
||||
final ValueChanged<SitePermissionStatus> onChanged;
|
||||
|
||||
const _PermissionTile({
|
||||
required this.icon,
|
||||
required this.label,
|
||||
required this.status,
|
||||
required this.onChanged,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final currentStatus = status ?? SitePermissionStatus.noDecision;
|
||||
|
||||
return ListTile(
|
||||
leading: Icon(icon),
|
||||
title: Text(label),
|
||||
trailing: DropdownButton<SitePermissionStatus>(
|
||||
value: currentStatus,
|
||||
underline: const SizedBox(),
|
||||
items: const [
|
||||
DropdownMenuItem(
|
||||
value: SitePermissionStatus.noDecision,
|
||||
child: Text('Ask'),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: SitePermissionStatus.allowed,
|
||||
child: Text('Allow'),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: SitePermissionStatus.blocked,
|
||||
child: Text('Block'),
|
||||
),
|
||||
],
|
||||
onChanged: (value) {
|
||||
if (value != null) {
|
||||
onChanged(value);
|
||||
}
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class _AutoplayTile extends StatelessWidget {
|
||||
final AutoplayStatus? audibleStatus;
|
||||
final AutoplayStatus? inaudibleStatus;
|
||||
final void Function(AutoplayStatus?, AutoplayStatus?) onChanged;
|
||||
|
||||
const _AutoplayTile({
|
||||
required this.audibleStatus,
|
||||
required this.inaudibleStatus,
|
||||
required this.onChanged,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// Determine the combined autoplay setting
|
||||
final combinedStatus = _getCombinedStatus();
|
||||
|
||||
return ListTile(
|
||||
leading: const Icon(Icons.play_circle),
|
||||
title: const Text('Autoplay'),
|
||||
trailing: DropdownButton<_AutoplayCombined>(
|
||||
value: combinedStatus,
|
||||
underline: const SizedBox(),
|
||||
items: const [
|
||||
DropdownMenuItem(
|
||||
value: _AutoplayCombined.allowAll,
|
||||
child: Text('Allow All'),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: _AutoplayCombined.blockAudible,
|
||||
child: Text('Block Audible'),
|
||||
),
|
||||
DropdownMenuItem(
|
||||
value: _AutoplayCombined.blockAll,
|
||||
child: Text('Block All'),
|
||||
),
|
||||
],
|
||||
onChanged: (value) {
|
||||
if (value == null) return;
|
||||
switch (value) {
|
||||
case _AutoplayCombined.allowAll:
|
||||
onChanged(AutoplayStatus.allowed, AutoplayStatus.allowed);
|
||||
case _AutoplayCombined.blockAudible:
|
||||
onChanged(AutoplayStatus.blocked, AutoplayStatus.allowed);
|
||||
case _AutoplayCombined.blockAll:
|
||||
onChanged(AutoplayStatus.blocked, AutoplayStatus.blocked);
|
||||
}
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
_AutoplayCombined _getCombinedStatus() {
|
||||
final audible = audibleStatus ?? AutoplayStatus.blocked;
|
||||
final inaudible = inaudibleStatus ?? AutoplayStatus.allowed;
|
||||
|
||||
if (audible == AutoplayStatus.allowed &&
|
||||
inaudible == AutoplayStatus.allowed) {
|
||||
return _AutoplayCombined.allowAll;
|
||||
} else if (audible == AutoplayStatus.blocked &&
|
||||
inaudible == AutoplayStatus.allowed) {
|
||||
return _AutoplayCombined.blockAudible;
|
||||
} else {
|
||||
return _AutoplayCombined.blockAll;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
enum _AutoplayCombined { allowAll, blockAudible, blockAll }
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
* Copyright (c) 2024-2026 Fabian Freund.
|
||||
*
|
||||
* This file is part of WebLibre
|
||||
* (see https://weblibre.eu).
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU Affero General Public License as
|
||||
* published by the Free Software Foundation, either version 3 of the
|
||||
* License, or (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU Affero General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU Affero General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
import 'package:flutter_mozilla_components/flutter_mozilla_components.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
|
||||
part 'site_permissions_provider.g.dart';
|
||||
|
||||
/// Provider to get the public suffix plus one (eTLD+1) for a host
|
||||
@Riverpod()
|
||||
Future<String> publicSuffixPlusOne(Ref ref, String host) {
|
||||
final api = GeckoPublicSuffixListApi();
|
||||
return api.getPublicSuffixPlusOne(host);
|
||||
}
|
||||
Loaded 100 of 904 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user