repo_id
stringlengths 21
168
| file_path
stringlengths 36
210
| content
stringlengths 1
9.98M
| __index_level_0__
int64 0
0
|
---|---|---|---|
mirrored_repositories/chattingapp | mirrored_repositories/chattingapp/lib/main.dart | import 'package:chattingapp/screen/homescreen.dart';
import 'package:chattingapp/screen/loginscreen.dart';
import 'package:chattingapp/widgets/user_card_list.dart';
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
late Size mq;
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: HomeScreen(),
);
}
}
| 0 |
mirrored_repositories/chattingapp/lib | mirrored_repositories/chattingapp/lib/widgets/user_card_list.dart | import 'package:cached_network_image/cached_network_image.dart';
import 'package:chattingapp/firebase/firestore.dart';
import 'package:chattingapp/main.dart';
import 'package:chattingapp/screen/chatScreen.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../model/chat_user.dart';
import '../model/message.dart';
class UserCardList extends StatefulWidget {
final ChatUser user;
const UserCardList({super.key, required this.user});
@override
State<UserCardList> createState() => _UserCardListState();
}
class _UserCardListState extends State<UserCardList> {
//list message info(if null--> no message)
Message? _message;
@override
Widget build(BuildContext context) {
return Card(
// margin: EdgeInsets.symmetric(horizontal: mq.width * 0.4, vertical: 4),
//shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(15)),
elevation: 0.5,
child: InkWell(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (_) => ChatScreen(
user: widget.user,
)));
},
child: StreamBuilder(
stream: APIs.getLastMessages(widget.user),
builder: (context, snapshot) {
final data = snapshot.data?.docs;
if (data != null && data.first.exists) {
_message = Message.fromJson(data.first.data());
}
return ListTile(
leading: ClipRRect(
borderRadius: BorderRadius.circular(
MediaQuery.of(context).size.height * .3),
child: CachedNetworkImage(
fit: BoxFit.fill,
width: MediaQuery.of(context).size.height * .055,
height: MediaQuery.of(context).size.height * .055,
imageUrl: widget.user.image,
errorWidget: (context, url, error) => const CircleAvatar(
child: Icon(CupertinoIcons.person),
),
),
),
//user name
title: Text(widget.user.name),
//last message
subtitle: Text(
_message != null ? _message!.msg : widget.user.about,
maxLines: 1,
),
trailing: Container(
width: 10,
height: 10,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: Colors.greenAccent.shade400),
),
//trailing: Text("12:00PM"),
);
},
)),
);
}
}
| 0 |
mirrored_repositories/chattingapp/lib | mirrored_repositories/chattingapp/lib/widgets/message_card.dart | import 'dart:developer';
import 'package:chattingapp/firebase/firestore.dart';
import 'package:chattingapp/helper/myDateUtil.dart';
import 'package:flutter/src/widgets/container.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter/material.dart';
import '../main.dart';
import '../model/message.dart';
class MessageCard extends StatefulWidget {
const MessageCard({super.key, required this.message});
final Message message;
@override
State<MessageCard> createState() => _MessageCardState();
}
class _MessageCardState extends State<MessageCard> {
@override
Widget build(BuildContext context) {
return APIs.user.uid == widget.message.fromId
? _greenMessage()
: _blueMessage();
}
//sender or another user message
Widget _blueMessage() {
//update last read message if send and receiver are different
if (widget.message.read.isNotEmpty) {
APIs.updateMessageReadStatus(widget.message);
log('message read updated');
}
return Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Flexible(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
padding: const EdgeInsets.all(8.0),
//margin: EdgeInsets.symmetric(horizontal: mq.width * 0.4),
decoration: BoxDecoration(
color: Color.fromARGB(255, 221, 245, 255),
border: Border.all(color: Colors.lightBlue),
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(30),
topRight: Radius.circular(30),
bottomRight: Radius.circular(30))),
child: Text(
widget.message.msg,
style: const TextStyle(fontSize: 15),
),
),
),
),
Text(
MyDateUtil.getFormattedTime(
context: context, time: widget.message.sent),
style: const TextStyle(fontSize: 12, color: Colors.black54),
)
],
),
);
}
//our or user message
Widget _greenMessage() {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
if (widget.message.read.isNotEmpty)
const Icon(
Icons.done_all_rounded,
color: Colors.blue,
size: 20,
),
Text(
MyDateUtil.getFormattedTime(
context: context, time: widget.message.sent),
style: const TextStyle(fontSize: 12, color: Colors.black54),
),
],
),
Flexible(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
padding: const EdgeInsets.all(8.0),
//margin: EdgeInsets.symmetric(horizontal: mq.width * 0.4),
decoration: BoxDecoration(
color: Color.fromARGB(255, 178, 245, 176),
border: Border.all(color: Colors.lightGreen),
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(30),
topRight: Radius.circular(30),
bottomLeft: Radius.circular(30))),
child: Text(
widget.message.msg,
style: const TextStyle(fontSize: 15),
),
),
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/chattingapp/lib | mirrored_repositories/chattingapp/lib/widgets/dialog.dart | import 'package:flutter/material.dart';
class Dialogs {
static void showSnackBar(BuildContext context, String msg) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(msg)));
}
static void showProgressBar(BuildContext context) {
showDialog(
context: context,
builder: (_) => Center(child: CircularProgressIndicator()));
}
}
| 0 |
mirrored_repositories/chattingapp/lib | mirrored_repositories/chattingapp/lib/model/chat_user.dart | class ChatUser {
late String image;
late String about;
late String name;
late String createdAt;
late bool isOnline;
late String id;
late String lastActive;
late String email;
late String pushToken;
ChatUser({
required this.image,
required this.about,
required this.createdAt,
required this.email,
required this.id,
required this.isOnline,
required this.lastActive,
required this.name,
required this.pushToken,
});
ChatUser.fromJson(Map<String, dynamic> json) {
image = json['image'] ?? '';
about = json['about'] ?? '';
name = json['name'] ?? '';
createdAt = json['created_at'] ?? '';
email = json['email'] ?? '';
id = json['id'] ?? '';
isOnline = json['is_online'] ?? '';
pushToken = json['push_token'] ?? '';
lastActive = json['last_active'] ?? '';
}
Map<String, dynamic> toJson() {
final data = <String, dynamic>{};
data['image'] = image;
data['about'] = about;
data['name'] = name;
data['created_at'] = createdAt;
data['is_online'] = isOnline;
data['id'] = id;
data['last_active'] = lastActive;
data['email'] = email;
data['push_token'] = pushToken;
return data;
}
}
| 0 |
mirrored_repositories/chattingapp/lib | mirrored_repositories/chattingapp/lib/model/message.dart | import 'package:flutter/rendering.dart';
class Message {
late final String toId;
late final String msg;
late final String read;
late final Type type;
late final String fromId;
late final String sent;
Message(
{required this.fromId,
required this.msg,
required this.read,
required this.sent,
required this.toId,
required this.type});
Message.fromJson(Map<String, dynamic> json) {
toId = json['toId'].toString();
msg = json['msg'].toString();
read = json['read'].toString();
type = json['type'].toString() == Type.image.name ? Type.image : Type.text;
fromId = json['fromId'].toString();
sent = json['sent'].toString();
}
Map<String, dynamic> toJson() {
final data = <String, dynamic>{};
data['toId'] = toId;
data['msg'] = msg;
data['read'] = read;
data['type'] = type.name;
data['fromId'] = fromId;
data['sent'] = sent;
return data;
}
}
enum Type { text, image }
| 0 |
mirrored_repositories/chattingapp/lib | mirrored_repositories/chattingapp/lib/screen/profilescreen.dart | // ignore_for_file: use_build_context_synchronously
import 'dart:developer';
import 'dart:io';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:chattingapp/firebase/firestore.dart';
import 'package:chattingapp/main.dart';
import 'package:chattingapp/model/chat_user.dart';
import 'package:chattingapp/screen/loginscreen.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
import 'package:image_picker/image_picker.dart';
import '../widgets/dialog.dart';
class ProfileScreen extends StatefulWidget {
final ChatUser user;
const ProfileScreen({super.key, required this.user});
@override
State<ProfileScreen> createState() => _ProfileScreenState();
}
class _ProfileScreenState extends State<ProfileScreen> {
final _formKey = GlobalKey<FormState>();
String? _image;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () => FocusScope.of(context).unfocus(),
child: Scaffold(
appBar: AppBar(
title: const Text("Welcome to Lets chat"),
leading:
const IconButton(icon: Icon(Icons.logout), onPressed: null)),
floatingActionButton: FloatingActionButton.extended(
onPressed: () async {
Dialogs.showProgressBar(context);
await APIs.auth.signOut().then((value) async {
await GoogleSignIn().signOut().then((value) {
Navigator.pop(context);
Navigator.pushReplacement(context,
MaterialPageRoute(builder: (_) => LoginScreen()));
});
});
},
icon: const Icon(Icons.logout),
label: const Text("logout"),
backgroundColor: Colors.redAccent.shade200,
),
body: Form(
key: _formKey,
child: SingleChildScrollView(
child: Column(
children: [
Padding(
padding: const EdgeInsets.all(28.0),
child: Center(
child: Stack(
children: [
_image != null
?
//local image
ClipRRect(
borderRadius: BorderRadius.circular(
MediaQuery.of(context).size.height * .3),
child: Image.file(
File(_image!),
width:
MediaQuery.of(context).size.height * .2,
height:
MediaQuery.of(context).size.height * .2,
fit: BoxFit.cover,
),
)
:
//image from server
ClipRRect(
borderRadius: BorderRadius.circular(
MediaQuery.of(context).size.height * .3),
child: CachedNetworkImage(
fit: BoxFit.fill,
width:
MediaQuery.of(context).size.height * .2,
height:
MediaQuery.of(context).size.height * .2,
imageUrl: widget.user.image,
errorWidget: (context, url, error) =>
const CircleAvatar(
child: Icon(CupertinoIcons.person),
),
),
),
Positioned(
bottom: 0,
right: 0,
child: MaterialButton(
onPressed: () {
_showBottomSheet();
},
child: const Icon(Icons.edit),
color: Colors.white,
shape: const CircleBorder(),
),
)
],
),
),
),
Text(
widget.user.email,
style: const TextStyle(fontSize: 18),
),
Padding(
padding: const EdgeInsets.all(18.0),
child: TextFormField(
initialValue: widget.user.name,
onSaved: (val) => APIs.me.name = val ?? '',
validator: (val) => val != null && val.isNotEmpty
? null
: 'required Field',
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15)),
prefixIcon: Icon(Icons.person),
hintText: "eg enter your name",
label: Text("name")),
),
),
Padding(
padding: const EdgeInsets.all(18.0),
child: TextFormField(
initialValue: widget.user.about,
onSaved: (val) => APIs.me.about = val ?? '',
validator: (val) => val != null && val.isNotEmpty
? null
: 'required Field',
//initialValue: widget.user.name,
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(15)),
prefixIcon: Icon(Icons.info_outline),
hintText: "eg feeling happy",
label: Text("about you")),
),
),
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
),
child: ElevatedButton.icon(
onPressed: () {
if (_formKey.currentState!.validate()) {
_formKey.currentState!.save();
APIs.updateUserInfo();
}
},
icon: const Icon(Icons.edit),
label: const Text("Update")),
)
],
),
),
)),
);
}
void _showBottomSheet() {
showModalBottomSheet(
context: context,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.only(
topLeft: Radius.circular(20), topRight: Radius.circular(20))),
builder: (_) {
return ListView(
shrinkWrap: true,
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: Text(
"Pick Profile Picture",
textAlign: TextAlign.center,
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ElevatedButton(
style: ElevatedButton.styleFrom(
shape: const CircleBorder(),
backgroundColor: Colors.white,
fixedSize: Size(
MediaQuery.of(context).size.width * 0.3,
MediaQuery.of(context).size.height * 0.15)),
onPressed: () async {
final ImagePicker picker = ImagePicker();
// Pick an image.
final XFile? image = await picker.pickImage(
source: ImageSource.gallery, imageQuality: 80);
if (image != null) {
log('Image path: ${image.path}');
setState(() {
_image = image.path;
});
APIs.updateProfilePicture(File(_image!));
Navigator.pop(context);
}
},
child: const Icon(
Icons.image,
color: Colors.blue,
)),
ElevatedButton(
style: ElevatedButton.styleFrom(
shape: const CircleBorder(),
backgroundColor: Colors.white,
fixedSize: Size(
MediaQuery.of(context).size.width * 0.3,
MediaQuery.of(context).size.height * 0.15)),
onPressed: () async {
final ImagePicker picker = ImagePicker();
// Pick an image.
final XFile? image = await picker.pickImage(
source: ImageSource.camera, imageQuality: 80);
if (image != null) {
log('Image path: ${image.path}');
setState(() {
_image = image.path;
});
APIs.updateProfilePicture(File(_image!));
Navigator.pop(context);
}
},
child: const Icon(
Icons.camera,
color: Colors.blue,
)),
],
),
),
],
);
});
}
}
| 0 |
mirrored_repositories/chattingapp/lib | mirrored_repositories/chattingapp/lib/screen/chatScreen.dart | import 'dart:convert';
import 'dart:developer';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:chattingapp/model/chat_user.dart';
import 'package:chattingapp/model/message.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/src/widgets/container.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter/material.dart';
import '../firebase/firestore.dart';
import '../widgets/message_card.dart';
class ChatScreen extends StatefulWidget {
final ChatUser user;
const ChatScreen({super.key, required this.user});
@override
State<ChatScreen> createState() => _ChatScreenState();
}
class _ChatScreenState extends State<ChatScreen> {
//for storing messages
List<Message> _list = [];
final _textController = TextEditingController();
@override
Widget build(BuildContext context) {
return SafeArea(
child: Scaffold(
backgroundColor: Color.fromARGB(255, 187, 229, 245),
appBar: AppBar(
automaticallyImplyLeading: false,
flexibleSpace: _appBar(),
),
body: Column(
children: [
Expanded(
child: StreamBuilder(
stream: APIs.getAllMessages(widget.user),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
case ConnectionState.none:
// return const Center(child: CircularProgressIndicator());
return SizedBox();
case ConnectionState.active:
case ConnectionState.done:
final data = snapshot.data?.docs;
_list = data
?.map((e) => Message.fromJson(e.data()))
.toList() ??
[];
//log('Data: ${jsonEncode(data![0].data())}');
//final _list = ['hi', 'hello'];
// _list.clear();
// _list.add(Message(
// fromId: APIs.user.uid,
// msg: 'hijjjjjjjj',
// read: 'read',
// sent: '12.00 AM',
// toId: 'xyz',
// type: Type.text));
// _list.add(Message(
// fromId: 'APIs.user.uid',
// msg: 'hellojjjjjjjj',
// read: 'read',
// sent: '2.00 AM',
// toId: 'abc',
// type: Type.text));
if (_list.isNotEmpty) {
return ListView.builder(
itemCount: _list.length,
padding: const EdgeInsets.only(
top: 10,
),
physics: const BouncingScrollPhysics(),
itemBuilder: (context, index) {
//return Text("Message: ${_list[index]}");
return MessageCard(message: _list[index]);
// return Text('Name: ${_list[index]}');
});
} else {
return const Center(
child: Text(
"Say Hiiii ! 👋",
style: TextStyle(fontSize: 22),
));
}
}
}),
),
_chatInput()
],
),
),
);
}
Widget _appBar() {
return Row(
children: [
IconButton(
onPressed: () {
Navigator.pop(context);
},
icon: const Icon(Icons.arrow_back),
color: Colors.black,
),
ClipRRect(
borderRadius:
BorderRadius.circular(MediaQuery.of(context).size.height * .3),
child: CachedNetworkImage(
fit: BoxFit.fill,
width: MediaQuery.of(context).size.height * .055,
height: MediaQuery.of(context).size.height * .055,
imageUrl: widget.user.image,
errorWidget: (context, url, error) => const CircleAvatar(
child: Icon(CupertinoIcons.person),
),
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(widget.user.name),
const Text("Last Seen not available"),
],
),
),
],
);
}
Widget _chatInput() {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
children: [
Expanded(
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15)),
child: Row(
children: [
IconButton(
onPressed: () {},
icon: const Icon(
Icons.emoji_emotions,
color: Colors.blueAccent,
)),
Expanded(
child: TextField(
controller: _textController,
keyboardType: TextInputType.multiline,
maxLines: null,
decoration: const InputDecoration(
hintText: "Type Something...",
hintStyle: TextStyle(color: Colors.blueAccent),
border: InputBorder.none),
)),
IconButton(
onPressed: () {},
icon: const Icon(
Icons.image,
color: Colors.blueAccent,
)),
IconButton(
onPressed: () {},
icon: const Icon(
Icons.camera,
color: Colors.blueAccent,
))
],
),
),
),
//send message button
MaterialButton(
onPressed: () {
if (_textController.text.isNotEmpty) {
APIs.sendMessage(widget.user, _textController.text);
_textController.text = '';
}
},
color: Colors.greenAccent,
padding:
const EdgeInsets.only(top: 10, bottom: 10, right: 5, left: 10),
shape: const CircleBorder(),
child: const Icon(
Icons.send,
size: 26,
color: Colors.white,
),
)
],
),
);
}
}
| 0 |
mirrored_repositories/chattingapp/lib | mirrored_repositories/chattingapp/lib/screen/loginscreen.dart | import 'dart:developer';
import 'dart:io';
import 'package:chattingapp/firebase/firestore.dart';
import 'package:chattingapp/main.dart';
import 'package:chattingapp/screen/homescreen.dart';
import 'package:chattingapp/widgets/dialog.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:google_sign_in/google_sign_in.dart';
class LoginScreen extends StatefulWidget {
const LoginScreen({super.key});
@override
State<LoginScreen> createState() => _LoginScreenState();
}
class _LoginScreenState extends State<LoginScreen> {
bool _isAnimate = false;
@override
void initState() {
super.initState();
Future.delayed(const Duration(milliseconds: 500), (() {
setState(() {
_isAnimate = true;
});
}));
}
_handleGoogleBtnClick() {
Dialogs.showProgressBar(context);
_signInWithGoogle().then((user) async {
Navigator.pop(context);
if (user != null) {
if (await (APIs.userExists())) {
Navigator.push(context,
MaterialPageRoute(builder: ((context) => const HomeScreen())));
} else {
await APIs.createUser().then((value) {
Navigator.push(context,
MaterialPageRoute(builder: ((context) => const HomeScreen())));
});
}
} else {
Dialogs.showSnackBar(context, "please log in ");
}
});
}
Future<UserCredential?> _signInWithGoogle() async {
try {
await InternetAddress.lookup('google.com');
final GoogleSignInAccount? googleUser = await GoogleSignIn().signIn();
// Obtain the auth details from the request
final GoogleSignInAuthentication? googleAuth =
await googleUser?.authentication;
// Create a new credential
final credential = GoogleAuthProvider.credential(
accessToken: googleAuth?.accessToken,
idToken: googleAuth?.idToken,
);
// Once signed in, return the UserCredential
return await FirebaseAuth.instance.signInWithCredential(credential);
} catch (e) {
log('_signInWithGoogle: $e');
Dialogs.showSnackBar(context,
"Something went wrong(please check your internet connection)");
return null;
}
// Trigger the authentication flow
}
@override
Widget build(BuildContext context) {
mq = MediaQuery.of(context).size;
return Scaffold(
appBar: AppBar(
title: Center(child: Text("Welcome to Lets Chat")),
),
body: Stack(
children: [
AnimatedPositioned(
top: mq.height * 0.15,
right: _isAnimate ? mq.width * 0.25 : mq.width * .01,
width: mq.width * 0.5,
duration: const Duration(seconds: 1),
child: Image.asset("images/chat.png")),
AnimatedPositioned(
top: mq.height * 0.55,
right: _isAnimate ? mq.width * 0.25 : mq.width * .01,
width: mq.width * 0.5,
duration: const Duration(seconds: 1),
child: ElevatedButton(
onPressed: () {
_handleGoogleBtnClick();
},
child: const Text("Sign In With Google"),
),
),
],
),
);
}
}
| 0 |
mirrored_repositories/chattingapp/lib | mirrored_repositories/chattingapp/lib/screen/homescreen.dart | import 'dart:developer';
import 'package:chattingapp/firebase/firestore.dart';
import 'package:chattingapp/model/chat_user.dart';
import 'package:chattingapp/screen/loginscreen.dart';
import 'package:chattingapp/widgets/dialog.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/container.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:google_sign_in/google_sign_in.dart';
import '../widgets/user_card_list.dart';
import 'profilescreen.dart';
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
@override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
List<ChatUser> list = [];
//for searcging searched items
final List<ChatUser> _searchList = [];
//for storing search status
bool _isSearching = false;
@override
void initState() {
// TODO: implement initState
super.initState();
APIs.getSelfInfo();
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: (() => FocusScope.of(context).unfocus()),
child: WillPopScope(
onWillPop: () {
if (_isSearching) {
setState(() {
_isSearching = !_isSearching;
});
return Future.value(false);
} else {
return Future.value(true);
}
},
child: Scaffold(
appBar: AppBar(
title: _isSearching
? TextField(
decoration: const InputDecoration(
border: InputBorder.none,
hintText: 'Name, Email....',
),
autofocus: true,
onChanged: (val) {
_searchList.clear();
for (var i in list) {
if (i.name
.toLowerCase()
.contains(val.toLowerCase()) ||
i.email
.toLowerCase()
.contains(val.toLowerCase())) {
_searchList.add(i);
}
setState(() {
_searchList;
});
}
},
)
: Text("Welcome to Lets chat"),
actions: [
IconButton(
onPressed: () {
setState(() {
_isSearching = !_isSearching;
});
},
icon: Icon(_isSearching
? CupertinoIcons.clear_circled_solid
: Icons.search)),
IconButton(
onPressed: (() {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ProfileScreen(
user: APIs.me,
)));
}),
icon: Icon(Icons.more_vert))
],
leading: IconButton(
icon: const Icon(Icons.logout),
onPressed: (() async {
await FirebaseAuth.instance.signOut();
await GoogleSignIn().signOut();
Dialogs.showProgressBar(context);
Navigator.push(
context,
MaterialPageRoute(
builder: ((context) => const LoginScreen())));
}),
)),
body: StreamBuilder(
stream: APIs.getAllUsers(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
case ConnectionState.none:
return const Center(child: CircularProgressIndicator());
case ConnectionState.active:
case ConnectionState.done:
final data = snapshot.data?.docs;
list = data
?.map((e) => ChatUser.fromJson(e.data()))
.toList() ??
[];
if (list.isNotEmpty) {
return ListView.builder(
itemCount:
_isSearching ? _searchList.length : list.length,
physics: BouncingScrollPhysics(),
itemBuilder: (context, index) {
return UserCardList(
user: _isSearching
? _searchList[index]
: list[index],
);
//return Text('Name: ${list[index]}');
});
} else {
return Center(child: Text("no connection available"));
}
}
})),
),
);
}
}
| 0 |
mirrored_repositories/chattingapp/lib | mirrored_repositories/chattingapp/lib/helper/myDateUtil.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class MyDateUtil {
static String getFormattedTime(
{required BuildContext context, required String time}) {
final date = DateTime.fromMillisecondsSinceEpoch(int.parse(time));
return TimeOfDay.fromDateTime(date).format(context);
}
}
| 0 |
mirrored_repositories/chattingapp/lib | mirrored_repositories/chattingapp/lib/firebase/firestore.dart | import 'dart:developer';
import 'dart:io';
import 'package:chattingapp/model/chat_user.dart';
import 'package:chattingapp/model/message.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:firebase_storage/firebase_storage.dart';
class APIs {
//for authentication
static FirebaseAuth auth = FirebaseAuth.instance;
//for accessing cloud firestore databse
static FirebaseFirestore firestore = FirebaseFirestore.instance;
//for accessing firebase storage
static FirebaseStorage storage = FirebaseStorage.instance;
//to return current user
static User get user => auth.currentUser!;
//for storing self information
static late ChatUser me;
//for checking if user exists or not
static Future<bool> userExists() async {
return (await firestore.collection('users').doc(user.uid).get()).exists;
}
//for getting current user info
static Future<void> getSelfInfo() async {
await firestore.collection('users').doc(user.uid).get().then((user) async {
if (user.exists) {
me = ChatUser.fromJson(user.data()!);
} else {
await createUser().then((value) => getSelfInfo());
}
});
}
//for creating a new user
static Future<void> createUser() async {
final time = DateTime.now().millisecondsSinceEpoch.toString();
final chatUser = ChatUser(
image: user.photoURL.toString(),
about: "Hey, I'm using Lets Chat",
createdAt: time,
email: user.email.toString(),
id: user.uid,
isOnline: false,
lastActive: time,
name: user.displayName.toString(),
pushToken: '');
return await firestore
.collection('users')
.doc(user.uid)
.set(chatUser.toJson());
}
//to get all the user except the login user
static Stream<QuerySnapshot<Map<String, dynamic>>> getAllUsers() {
return APIs.firestore
.collection('users')
.where('id', isNotEqualTo: user.uid)
.snapshots();
}
//for updating user information
static Future<void> updateUserInfo() async {
await firestore
.collection('users')
.doc(user.uid)
.update({'name': me.name, 'about': me.about});
}
//for updating picture of user
static Future<void> updateProfilePicture(File file) async {
final ext = file.path.split('.').last;
log('Extension: $ext');
final ref = storage.ref().child('profile_picture/${user.uid}.');
await ref
.putFile(file, SettableMetadata(contentType: 'images/$ext'))
.then((p0) {
log('Data Transferred: ${p0.bytesTransferred / 1000}kb');
});
//updating image in firestore database
me.image = await ref.getDownloadURL();
await firestore.collection('users').doc(user.uid).update({
'image': me.image,
});
}
///*****chat screen Related APIS *****/
//usefule for getting conversation id
static String getConversationID(String id) => user.uid.hashCode <= id.hashCode
? '${user.uid}_$id'
: '${id}_${user.uid}';
//for getting all messages of a specific conversation from firestore database
static Stream<QuerySnapshot<Map<String, dynamic>>> getAllMessages(
ChatUser user) {
return firestore
.collection('chats/${getConversationID(user.id)}/messages/')
.snapshots();
}
//for sending message
static Future<void> sendMessage(ChatUser chatUser, String msg) async {
//message sending time (also used as id)
final time = DateTime.now().millisecondsSinceEpoch.toString();
//message to send
final Message message = Message(
fromId: user.uid,
msg: msg,
read: '',
sent: time,
toId: chatUser.id,
type: Type.text);
final ref = firestore
.collection('chats/${getConversationID(chatUser.id)}/messages/');
await ref.doc(time).set(message.toJson());
}
//update read status of message
static Future<void> updateMessageReadStatus(Message message) async {
firestore
.collection('chats/${getConversationID(message.fromId)}/messages/')
.doc(message.sent)
.update({'read': DateTime.now().millisecondsSinceEpoch.toString()});
}
//get only last message of a specific chat
static Stream<QuerySnapshot<Map<String, dynamic>>> getLastMessages(
ChatUser user) {
return firestore
.collection('chats/${getConversationID(user.id)}/messages/')
.limit(1)
.snapshots();
}
}
| 0 |
mirrored_repositories/chattingapp | mirrored_repositories/chattingapp/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility in the flutter_test package. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:chattingapp/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget(const MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/Flutter-Hive-Todo-App/flutter_hive_tdo | mirrored_repositories/Flutter-Hive-Todo-App/flutter_hive_tdo/lib/main.dart | //? CodeWithFlexz on Instagram
//* AmirBayat0 on Github
//! Programming with Flexz on Youtube
import 'package:flutter/material.dart';
import 'package:hive_flutter/hive_flutter.dart';
///
import '../data/hive_data_store.dart';
import '../models/task.dart';
import '../view/home/home_view.dart';
Future<void> main() async {
/// Initial Hive DB
await Hive.initFlutter();
/// Register Hive Adapter
Hive.registerAdapter<Task>(TaskAdapter());
/// Open box
var box = await Hive.openBox<Task>("tasksBox");
/// Delete data from previous day
// ignore: avoid_function_literals_in_foreach_calls
box.values.forEach((task) {
if (task.createdAtTime.day != DateTime.now().day) {
task.delete();
} else {}
});
runApp(BaseWidget(child: const MyApp()));
}
class BaseWidget extends InheritedWidget {
BaseWidget({Key? key, required this.child}) : super(key: key, child: child);
final HiveDataStore dataStore = HiveDataStore();
final Widget child;
static BaseWidget of(BuildContext context) {
final base = context.dependOnInheritedWidgetOfExactType<BaseWidget>();
if (base != null) {
return base;
} else {
throw StateError('Could not find ancestor widget of type BaseWidget');
}
}
@override
bool updateShouldNotify(covariant InheritedWidget oldWidget) {
return false;
}
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Hive Todo App',
theme: ThemeData(
textTheme: const TextTheme(
headline1: TextStyle(
color: Colors.black,
fontSize: 45,
fontWeight: FontWeight.bold,
),
subtitle1: TextStyle(
color: Colors.grey,
fontSize: 16,
fontWeight: FontWeight.w300,
),
headline2: TextStyle(
color: Colors.white,
fontSize: 21,
),
headline3: TextStyle(
color: Color.fromARGB(255, 234, 234, 234),
fontSize: 14,
fontWeight: FontWeight.w400,
),
headline4: TextStyle(
color: Colors.grey,
fontSize: 17,
),
headline5: TextStyle(
color: Colors.grey,
fontSize: 16,
),
subtitle2: TextStyle(
color: Colors.black,
fontWeight: FontWeight.w500,
),
headline6: TextStyle(
fontSize: 40,
color: Colors.black,
fontWeight: FontWeight.w300,
),
),
),
home: const HomeView(),
);
}
}
| 0 |
mirrored_repositories/Flutter-Hive-Todo-App/flutter_hive_tdo/lib/view | mirrored_repositories/Flutter-Hive-Todo-App/flutter_hive_tdo/lib/view/home/home_view.dart | // ignore_for_file: must_be_immutable
import 'package:animate_do/animate_do.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:hive_flutter/adapters.dart';
import 'package:lottie/lottie.dart';
import 'package:flutter_slider_drawer/flutter_slider_drawer.dart';
///
import '../../main.dart';
import '../../models/task.dart';
import '../../utils/colors.dart';
import '../../utils/constanst.dart';
import '../../view/home/widgets/task_widget.dart';
import '../../view/tasks/task_view.dart';
import '../../utils/strings.dart';
class HomeView extends StatefulWidget {
const HomeView({Key? key}) : super(key: key);
@override
// ignore: library_private_types_in_public_api
_HomeViewState createState() => _HomeViewState();
}
class _HomeViewState extends State<HomeView> {
GlobalKey<SliderDrawerState> dKey = GlobalKey<SliderDrawerState>();
/// Checking Done Tasks
int checkDoneTask(List<Task> task) {
int i = 0;
for (Task doneTasks in task) {
if (doneTasks.isCompleted) {
i++;
}
}
return i;
}
/// Checking The Value Of the Circle Indicator
dynamic valueOfTheIndicator(List<Task> task) {
if (task.isNotEmpty) {
return task.length;
} else {
return 3;
}
}
@override
Widget build(BuildContext context) {
final base = BaseWidget.of(context);
var textTheme = Theme.of(context).textTheme;
return ValueListenableBuilder(
valueListenable: base.dataStore.listenToTask(),
builder: (ctx, Box<Task> box, Widget? child) {
var tasks = box.values.toList();
/// Sort Task List
tasks.sort(((a, b) => a.createdAtDate.compareTo(b.createdAtDate)));
return Scaffold(
backgroundColor: Colors.white,
/// Floating Action Button
floatingActionButton: const FAB(),
/// Body
body: SliderDrawer(
isDraggable: false,
key: dKey,
animationDuration: 1000,
/// My AppBar
appBar: MyAppBar(
drawerKey: dKey,
),
/// My Drawer Slider
slider: MySlider(),
/// Main Body
child: _buildBody(
tasks,
base,
textTheme,
),
),
);
});
}
/// Main Body
SizedBox _buildBody(
List<Task> tasks,
BaseWidget base,
TextTheme textTheme,
) {
return SizedBox(
width: double.infinity,
height: double.infinity,
child: Column(
children: [
/// Top Section Of Home page : Text, Progrss Indicator
Container(
margin: const EdgeInsets.fromLTRB(55, 0, 0, 0),
width: double.infinity,
height: 100,
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
/// CircularProgressIndicator
SizedBox(
width: 25,
height: 25,
child: CircularProgressIndicator(
valueColor: const AlwaysStoppedAnimation(MyColors.primaryColor),
backgroundColor: Colors.grey,
value: checkDoneTask(tasks) / valueOfTheIndicator(tasks),
),
),
const SizedBox(
width: 25,
),
/// Texts
Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(MyString.mainTitle, style: textTheme.headline1),
const SizedBox(
height: 3,
),
Text("${checkDoneTask(tasks)} of ${tasks.length} task",
style: textTheme.subtitle1),
],
)
],
),
),
/// Divider
const Padding(
padding: EdgeInsets.only(top: 10),
child: Divider(
thickness: 2,
indent: 100,
),
),
/// Bottom ListView : Tasks
SizedBox(
width: double.infinity,
height: 585,
child: tasks.isNotEmpty
? ListView.builder(
physics: const BouncingScrollPhysics(),
itemCount: tasks.length,
itemBuilder: (BuildContext context, int index) {
var task = tasks[index];
return Dismissible(
direction: DismissDirection.horizontal,
background: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
Icon(
Icons.delete_outline,
color: Colors.grey,
),
SizedBox(
width: 8,
),
Text(MyString.deletedTask,
style: TextStyle(
color: Colors.grey,
))
],
),
onDismissed: (direction) {
base.dataStore.dalateTask(task: task);
},
key: Key(task.id),
child: TaskWidget(
task: tasks[index],
),
);
},
)
/// if All Tasks Done Show this Widgets
: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
/// Lottie
FadeIn(
child: SizedBox(
width: 200,
height: 200,
child: Lottie.asset(
lottieURL,
animate: tasks.isNotEmpty ? false : true,
),
),
),
/// Bottom Texts
FadeInUp(
from: 30,
child: const Text(MyString.doneAllTask),
),
],
),
)
],
),
);
}
}
/// My Drawer Slider
class MySlider extends StatelessWidget {
MySlider({
Key? key,
}) : super(key: key);
/// Icons
List<IconData> icons = [
CupertinoIcons.home,
CupertinoIcons.person_fill,
CupertinoIcons.settings,
CupertinoIcons.info_circle_fill,
];
/// Texts
List<String> texts = [
"Home",
"Profile",
"Settings",
"Details",
];
@override
Widget build(BuildContext context) {
var textTheme = Theme.of(context).textTheme;
return Container(
padding: const EdgeInsets.symmetric(vertical: 90),
decoration: const BoxDecoration(
gradient: LinearGradient(
colors: MyColors.primaryGradientColor,
begin: Alignment.topLeft,
end: Alignment.bottomRight),
),
child: Column(
children: [
const CircleAvatar(
radius: 50,
backgroundImage: AssetImage('assets/img/main.png'),
),
const SizedBox(
height: 8,
),
Text("AmirHossein Bayat", style: textTheme.headline2),
Text("junior flutter dev", style: textTheme.headline3),
Container(
margin: const EdgeInsets.symmetric(
vertical: 30,
horizontal: 10,
),
width: double.infinity,
height: 300,
child: ListView.builder(
itemCount: icons.length,
physics: const NeverScrollableScrollPhysics(),
itemBuilder: (ctx, i) {
return InkWell(
// ignore: avoid_print
onTap: () => print("$i Selected"),
child: Container(
margin: const EdgeInsets.all(5),
child: ListTile(
leading: Icon(
icons[i],
color: Colors.white,
size: 30,
),
title: Text(
texts[i],
style: const TextStyle(
color: Colors.white,
),
)),
),
);
}),
)
],
),
);
}
}
/// My App Bar
class MyAppBar extends StatefulWidget with PreferredSizeWidget {
MyAppBar({Key? key,
required this.drawerKey,
}) : super(key: key);
GlobalKey<SliderDrawerState> drawerKey;
@override
State<MyAppBar> createState() => _MyAppBarState();
@override
Size get preferredSize => const Size.fromHeight(100);
}
class _MyAppBarState extends State<MyAppBar>
with SingleTickerProviderStateMixin {
late AnimationController controller;
bool isDrawerOpen = false;
@override
void initState() {
super.initState();
controller = AnimationController(
vsync: this,
duration: const Duration(milliseconds: 1000),
);
}
@override
void dispose() {
controller.dispose();
super.dispose();
}
/// toggle for drawer and icon aniamtion
void toggle() {
setState(() {
isDrawerOpen = !isDrawerOpen;
if (isDrawerOpen) {
controller.forward();
widget.drawerKey.currentState!.openSlider();
} else {
controller.reverse();
widget.drawerKey.currentState!.closeSlider();
}
});
}
@override
Widget build(BuildContext context) {
var base = BaseWidget.of(context).dataStore.box;
return SizedBox(
width: double.infinity,
height: 132,
child: Padding(
padding: const EdgeInsets.only(top: 20),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
/// Animated Icon - Menu & Close
Padding(
padding: const EdgeInsets.only(left: 20),
child: IconButton(
splashColor: Colors.transparent,
highlightColor: Colors.transparent,
icon: AnimatedIcon(
icon: AnimatedIcons.menu_close,
progress: controller,
size: 40,
),
onPressed: toggle),
),
/// Delete Icon
Padding(
padding: const EdgeInsets.only(right: 20),
child: GestureDetector(
onTap: () {
base.isEmpty
? warningNoTask(context)
: deleteAllTask(context);
},
child: const Icon(
CupertinoIcons.trash,
size: 40,
),
),
),
],
),
),
);
}
}
/// Floating Action Button
class FAB extends StatelessWidget {
const FAB({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
Navigator.of(context).push(
CupertinoPageRoute(
builder: (context) => TaskView(
taskControllerForSubtitle: null,
taskControllerForTitle: null,
task: null,
),
),
);
},
child: Material(
borderRadius: BorderRadius.circular(15),
elevation: 10,
child: Container(
width: 70,
height: 70,
decoration: BoxDecoration(
color: MyColors.primaryColor,
borderRadius: BorderRadius.circular(15),
),
child: const Center(
child: Icon(
Icons.add,
color: Colors.white,
)),
),
),
);
}
}
| 0 |
mirrored_repositories/Flutter-Hive-Todo-App/flutter_hive_tdo/lib/view/home | mirrored_repositories/Flutter-Hive-Todo-App/flutter_hive_tdo/lib/view/home/widgets/task_widget.dart | import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
///
import '../../../models/task.dart';
import '../../../utils/colors.dart';
import '../../../view/tasks/task_view.dart';
class TaskWidget extends StatefulWidget {
const TaskWidget({Key? key, required this.task}) : super(key: key);
final Task task;
@override
// ignore: library_private_types_in_public_api
_TaskWidgetState createState() => _TaskWidgetState();
}
class _TaskWidgetState extends State<TaskWidget> {
TextEditingController taskControllerForTitle = TextEditingController();
TextEditingController taskControllerForSubtitle = TextEditingController();
@override
void initState() {
super.initState();
taskControllerForTitle.text = widget.task.title;
taskControllerForSubtitle.text = widget.task.subtitle;
}
@override
void dispose() {
taskControllerForTitle.dispose();
taskControllerForSubtitle.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
Navigator.push(
context,
CupertinoPageRoute(
builder: (ctx) => TaskView(
taskControllerForTitle: taskControllerForTitle,
taskControllerForSubtitle: taskControllerForSubtitle,
task: widget.task,
),
),
);
},
/// Main Card
child: AnimatedContainer(
duration: const Duration(milliseconds: 600),
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
decoration: BoxDecoration(
color: widget.task.isCompleted
? const Color.fromARGB(154, 119, 144, 229)
: Colors.white,
borderRadius: BorderRadius.circular(8),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(.1),
offset: const Offset(0, 4),
blurRadius: 10)
]),
child: ListTile(
/// Check icon
leading: GestureDetector(
onTap: () {
widget.task.isCompleted = !widget.task.isCompleted;
widget.task.save();
},
child: AnimatedContainer(
duration: const Duration(milliseconds: 600),
decoration: BoxDecoration(
color: widget.task.isCompleted
? MyColors.primaryColor
: Colors.white,
shape: BoxShape.circle,
border: Border.all(color: Colors.grey, width: .8)),
child: const Icon(
Icons.check,
color: Colors.white,
),
),
),
/// title of Task
title: Padding(
padding: const EdgeInsets.only(bottom: 5, top: 3),
child: Text(
taskControllerForTitle.text,
style: TextStyle(
color: widget.task.isCompleted
? MyColors.primaryColor
: Colors.black,
fontWeight: FontWeight.w500,
decoration: widget.task.isCompleted
? TextDecoration.lineThrough
: null),
),
),
/// Description of task
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
taskControllerForSubtitle.text,
style: TextStyle(
color: widget.task.isCompleted
? MyColors.primaryColor
: const Color.fromARGB(255, 164, 164, 164),
fontWeight: FontWeight.w300,
decoration: widget.task.isCompleted
? TextDecoration.lineThrough
: null,
),
),
/// Date & Time of Task
Align(
alignment: Alignment.centerRight,
child: Padding(
padding: const EdgeInsets.only(
bottom: 10,
top: 10,
),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
DateFormat('hh:mm a')
.format(widget.task.createdAtTime),
style: TextStyle(
fontSize: 14,
color: widget.task.isCompleted
? Colors.white
: Colors.grey),
),
Text(
DateFormat.yMMMEd()
.format(widget.task.createdAtDate),
style: TextStyle(
fontSize: 12,
color: widget.task.isCompleted
? Colors.white
: Colors.grey),
),
],
),
),
),
],
)),
),
);
}
}
| 0 |
mirrored_repositories/Flutter-Hive-Todo-App/flutter_hive_tdo/lib/view | mirrored_repositories/Flutter-Hive-Todo-App/flutter_hive_tdo/lib/view/tasks/task_view.dart | // ignore_for_file: prefer_typing_uninitialized_variables
import 'package:flutter/material.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:intl/intl.dart';
///
import '../../main.dart';
import '../../models/task.dart';
import '../../utils/colors.dart';
import '../../utils/constanst.dart';
import '../../utils/strings.dart';
// ignore: must_be_immutable
class TaskView extends StatefulWidget {
TaskView({
Key? key,
required this.taskControllerForTitle,
required this.taskControllerForSubtitle,
required this.task,
}) : super(key: key);
TextEditingController? taskControllerForTitle;
TextEditingController? taskControllerForSubtitle;
final Task? task;
@override
State<TaskView> createState() => _TaskViewState();
}
class _TaskViewState extends State<TaskView> {
var title;
var subtitle;
DateTime? time;
DateTime? date;
/// Show Selected Time As String Format
String showTime(DateTime? time) {
if (widget.task?.createdAtTime == null) {
if (time == null) {
return DateFormat('hh:mm a').format(DateTime.now()).toString();
} else {
return DateFormat('hh:mm a').format(time).toString();
}
} else {
return DateFormat('hh:mm a')
.format(widget.task!.createdAtTime)
.toString();
}
}
/// Show Selected Time As DateTime Format
DateTime showTimeAsDateTime(DateTime? time) {
if (widget.task?.createdAtTime == null) {
if (time == null) {
return DateTime.now();
} else {
return time;
}
} else {
return widget.task!.createdAtTime;
}
}
/// Show Selected Date As String Format
String showDate(DateTime? date) {
if (widget.task?.createdAtDate == null) {
if (date == null) {
return DateFormat.yMMMEd().format(DateTime.now()).toString();
} else {
return DateFormat.yMMMEd().format(date).toString();
}
} else {
return DateFormat.yMMMEd().format(widget.task!.createdAtDate).toString();
}
}
// Show Selected Date As DateTime Format
DateTime showDateAsDateTime(DateTime? date) {
if (widget.task?.createdAtDate == null) {
if (date == null) {
return DateTime.now();
} else {
return date;
}
} else {
return widget.task!.createdAtDate;
}
}
/// If any Task Already exist return TRUE otherWise FALSE
bool isTaskAlreadyExistBool() {
if (widget.taskControllerForTitle?.text == null &&
widget.taskControllerForSubtitle?.text == null) {
return true;
} else {
return false;
}
}
/// If any task already exist app will update it otherwise the app will add a new task
dynamic isTaskAlreadyExistUpdateTask() {
if (widget.taskControllerForTitle?.text != null &&
widget.taskControllerForSubtitle?.text != null) {
try {
widget.taskControllerForTitle?.text = title;
widget.taskControllerForSubtitle?.text = subtitle;
// widget.task?.createdAtDate = date!;
// widget.task?.createdAtTime = time!;
widget.task?.save();
Navigator.of(context).pop();
} catch (error) {
nothingEnterOnUpdateTaskMode(context);
}
} else {
if (title != null && subtitle != null) {
var task = Task.create(
title: title,
createdAtTime: time,
createdAtDate: date,
subtitle: subtitle,
);
BaseWidget.of(context).dataStore.addTask(task: task);
Navigator.of(context).pop();
} else {
emptyFieldsWarning(context);
}
}
}
/// Delete Selected Task
dynamic deleteTask() {
return widget.task?.delete();
}
@override
Widget build(BuildContext context) {
var textTheme = Theme.of(context).textTheme;
return GestureDetector(
onTap: () => FocusManager.instance.primaryFocus?.unfocus(),
child: Scaffold(
backgroundColor: Colors.white,
appBar: const MyAppBar(),
body: SizedBox(
width: double.infinity,
height: double.infinity,
child: Center(
child: SingleChildScrollView(
physics: const BouncingScrollPhysics(),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: [
/// new / update Task Text
_buildTopText(textTheme),
/// Middle Two TextFileds, Time And Date Selection Box
_buildMiddleTextFieldsANDTimeAndDateSelection(
context, textTheme),
/// All Bottom Buttons
_buildBottomButtons(context),
],
),
),
),
),
),
);
}
/// All Bottom Buttons
Padding _buildBottomButtons(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(bottom: 20),
child: Row(
mainAxisAlignment: isTaskAlreadyExistBool()
? MainAxisAlignment.center
: MainAxisAlignment.spaceEvenly,
children: [
isTaskAlreadyExistBool()
? Container()
/// Delete Task Button
: Container(
width: 150,
height: 55,
decoration: BoxDecoration(
border:
Border.all(color: MyColors.primaryColor, width: 2),
borderRadius: BorderRadius.circular(15)),
child: MaterialButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
),
minWidth: 150,
height: 55,
onPressed: () {
deleteTask();
Navigator.pop(context);
},
color: Colors.white,
child: Row(
children: const [
Icon(
Icons.close,
color: MyColors.primaryColor,
),
SizedBox(
width: 5,
),
Text(
MyString.deleteTask,
style: TextStyle(
color: MyColors.primaryColor,
),
),
],
),
),
),
/// Add or Update Task Button
MaterialButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(15),
),
minWidth: 150,
height: 55,
onPressed: () {
isTaskAlreadyExistUpdateTask();
},
color: MyColors.primaryColor,
child: Text(
isTaskAlreadyExistBool()
? MyString.addTaskString
: MyString.updateTaskString,
style: const TextStyle(
color: Colors.white,
),
),
),
],
),
);
}
/// Middle Two TextFileds And Time And Date Selection Box
SizedBox _buildMiddleTextFieldsANDTimeAndDateSelection(
BuildContext context, TextTheme textTheme) {
return SizedBox(
width: double.infinity,
height: 535,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
/// Title of TextFiled
Padding(
padding: const EdgeInsets.only(left: 30),
child: Text(MyString.titleOfTitleTextField,
style: textTheme.headline4),
),
/// Title TextField
Container(
width: MediaQuery.of(context).size.width,
margin: const EdgeInsets.symmetric(horizontal: 16),
child: ListTile(
title: TextFormField(
controller: widget.taskControllerForTitle,
maxLines: 6,
cursorHeight: 60,
style: const TextStyle(color: Colors.black),
decoration: InputDecoration(
enabledBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.grey.shade300),
),
focusedBorder: UnderlineInputBorder(
borderSide: BorderSide(color: Colors.grey.shade300),
),
),
onFieldSubmitted: (value) {
title = value;
FocusManager.instance.primaryFocus?.unfocus();
},
onChanged: (value) {
title = value;
},
),
),
),
const SizedBox(
height: 10,
),
/// Note TextField
Container(
width: MediaQuery.of(context).size.width,
margin: const EdgeInsets.symmetric(horizontal: 16),
child: ListTile(
title: TextFormField(
controller: widget.taskControllerForSubtitle,
style: const TextStyle(color: Colors.black),
decoration: InputDecoration(
prefixIcon: const Icon(Icons.bookmark_border, color: Colors.grey),
border: InputBorder.none,
counter: Container(),
hintText: MyString.addNote,
),
onFieldSubmitted: (value) {
subtitle = value;
},
onChanged: (value) {
subtitle = value;
},
),
),
),
/// Time Picker
GestureDetector(
onTap: () {
DatePicker.showTimePicker(context,
showTitleActions: true,
showSecondsColumn: false,
onChanged: (_) {}, onConfirm: (selectedTime) {
setState(() {
if (widget.task?.createdAtTime == null) {
time = selectedTime;
} else {
widget.task!.createdAtTime = selectedTime;
}
});
FocusManager.instance.primaryFocus?.unfocus();
}, currentTime: showTimeAsDateTime(time));
},
child: Container(
margin: const EdgeInsets.fromLTRB(20, 20, 20, 10),
width: double.infinity,
height: 55,
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(color: Colors.grey.shade300, width: 1),
borderRadius: BorderRadius.circular(10),
),
child: Row(
children: [
Padding(
padding: const EdgeInsets.only(left: 10),
child:
Text(MyString.timeString, style: textTheme.headline5),
),
Expanded(child: Container()),
Container(
margin: const EdgeInsets.only(right: 10),
width: 80,
height: 35,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Colors.grey.shade100),
child: Center(
child: Text(
showTime(time),
style: textTheme.subtitle2,
),
),
)
],
),
),
),
/// Date Picker
GestureDetector(
onTap: () {
DatePicker.showDatePicker(context,
showTitleActions: true,
minTime: DateTime.now(),
maxTime: DateTime(2030, 3, 5),
onChanged: (_) {}, onConfirm: (selectedDate) {
setState(() {
if (widget.task?.createdAtDate == null) {
date = selectedDate;
} else {
widget.task!.createdAtDate = selectedDate;
}
});
FocusManager.instance.primaryFocus?.unfocus();
}, currentTime: showDateAsDateTime(date));
},
child: Container(
margin: const EdgeInsets.fromLTRB(20, 10, 20, 10),
width: double.infinity,
height: 55,
decoration: BoxDecoration(
color: Colors.white,
border: Border.all(color: Colors.grey.shade300, width: 1),
borderRadius: BorderRadius.circular(10),
),
child: Row(
children: [
Padding(
padding: const EdgeInsets.only(left: 10),
child:
Text(MyString.dateString, style: textTheme.headline5),
),
Expanded(child: Container()),
Container(
margin: const EdgeInsets.only(right: 10),
width: 140,
height: 35,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Colors.grey.shade100),
child: Center(
child: Text(
showDate(date),
style: textTheme.subtitle2,
),
),
)
],
),
),
)
],
),
);
}
/// new / update Task Text
SizedBox _buildTopText(TextTheme textTheme) {
return SizedBox(
width: double.infinity,
height: 100,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const SizedBox(
width: 70,
child: Divider(
thickness: 2,
),
),
RichText(
text: TextSpan(
text: isTaskAlreadyExistBool()
? MyString.addNewTask
: MyString.updateCurrentTask,
style: textTheme.headline6,
children: const [
TextSpan(
text: MyString.taskStrnig,
style: TextStyle(
fontWeight: FontWeight.w400,
),
)
]),
),
const SizedBox(
width: 70,
child: Divider(
thickness: 2,
),
),
],
),
);
}
}
/// AppBar
class MyAppBar extends StatelessWidget with PreferredSizeWidget {
const MyAppBar({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return SizedBox(
width: double.infinity,
height: 150,
child: Padding(
padding: const EdgeInsets.only(top: 20),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.only(left: 20),
child: GestureDetector(
onTap: () {
Navigator.of(context).pop();
},
child: const Icon(
Icons.arrow_back_ios_new_rounded,
size: 50,
),
),
),
],
),
),
);
}
@override
Size get preferredSize => const Size.fromHeight(100);
}
| 0 |
mirrored_repositories/Flutter-Hive-Todo-App/flutter_hive_tdo/lib | mirrored_repositories/Flutter-Hive-Todo-App/flutter_hive_tdo/lib/models/task.dart | import 'package:uuid/uuid.dart';
import 'package:hive/hive.dart';
part 'task.g.dart';
@HiveType(typeId: 0)
class Task extends HiveObject {
Task(
{required this.id,
required this.title,
required this.subtitle,
required this.createdAtTime,
required this.createdAtDate,
required this.isCompleted});
/// ID
@HiveField(0)
final String id;
/// TITLE
@HiveField(1)
String title;
/// SUBTITLE
@HiveField(2)
String subtitle;
/// CREATED AT TIME
@HiveField(3)
DateTime createdAtTime;
/// CREATED AT DATE
@HiveField(4)
DateTime createdAtDate;
/// IS COMPLETED
@HiveField(5)
bool isCompleted;
/// create new Task
factory Task.create({
required String? title,
required String? subtitle,
DateTime? createdAtTime,
DateTime? createdAtDate,
}) =>
Task(
id: const Uuid().v1(),
title: title ?? "",
subtitle: subtitle ?? "",
createdAtTime: createdAtTime ?? DateTime.now(),
isCompleted: false,
createdAtDate: createdAtDate ?? DateTime.now(),
);
}
| 0 |
mirrored_repositories/Flutter-Hive-Todo-App/flutter_hive_tdo/lib | mirrored_repositories/Flutter-Hive-Todo-App/flutter_hive_tdo/lib/models/task.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'task.dart';
// **************************************************************************
// TypeAdapterGenerator
// **************************************************************************
class TaskAdapter extends TypeAdapter<Task> {
@override
final int typeId = 0;
@override
Task read(BinaryReader reader) {
final numOfFields = reader.readByte();
final fields = <int, dynamic>{
for (int i = 0; i < numOfFields; i++) reader.readByte(): reader.read(),
};
return Task(
id: fields[0] as String,
title: fields[1] as String,
subtitle: fields[2] as String,
createdAtTime: fields[3] as DateTime,
createdAtDate: fields[4] as DateTime,
isCompleted: fields[5] as bool,
);
}
@override
void write(BinaryWriter writer, Task obj) {
writer
..writeByte(6)
..writeByte(0)
..write(obj.id)
..writeByte(1)
..write(obj.title)
..writeByte(2)
..write(obj.subtitle)
..writeByte(3)
..write(obj.createdAtTime)
..writeByte(4)
..write(obj.createdAtDate)
..writeByte(5)
..write(obj.isCompleted);
}
@override
int get hashCode => typeId.hashCode;
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is TaskAdapter &&
runtimeType == other.runtimeType &&
typeId == other.typeId;
}
| 0 |
mirrored_repositories/Flutter-Hive-Todo-App/flutter_hive_tdo/lib | mirrored_repositories/Flutter-Hive-Todo-App/flutter_hive_tdo/lib/data/hive_data_store.dart | import 'package:flutter/foundation.dart';
import 'package:hive_flutter/hive_flutter.dart';
///
import '../models/task.dart';
class HiveDataStore {
static const boxName = "tasksBox";
final Box<Task> box = Hive.box<Task>(boxName);
/// Add new Task
Future<void> addTask({required Task task}) async {
await box.put(task.id, task);
}
/// Show task
Future<Task?> getTask({required String id}) async {
return box.get(id);
}
/// Update task
Future<void> updateTask({required Task task}) async {
await task.save();
}
/// Delete task
Future<void> dalateTask({required Task task}) async {
await task.delete();
}
ValueListenable<Box<Task>> listenToTask() {
return box.listenable();
}
}
| 0 |
mirrored_repositories/Flutter-Hive-Todo-App/flutter_hive_tdo/lib | mirrored_repositories/Flutter-Hive-Todo-App/flutter_hive_tdo/lib/utils/constanst.dart | import 'package:flutter/material.dart';
import 'package:ftoast/ftoast.dart';
import 'package:panara_dialogs/panara_dialogs.dart';
///
import '../utils/strings.dart';
import '../../main.dart';
/// Empty Title & Subtite TextFields Warning
emptyFieldsWarning(context) {
return FToast.toast(
context,
msg: MyString.oopsMsg,
subMsg: "You must fill all Fields!",
corner: 20.0,
duration: 2000,
padding: const EdgeInsets.all(20),
);
}
/// Nothing Enter When user try to edit the current tesk
nothingEnterOnUpdateTaskMode(context) {
return FToast.toast(
context,
msg: MyString.oopsMsg,
subMsg: "You must edit the tasks then try to update it!",
corner: 20.0,
duration: 3000,
padding: const EdgeInsets.all(20),
);
}
/// No task Warning Dialog
dynamic warningNoTask(BuildContext context) {
return PanaraInfoDialog.showAnimatedGrow(
context,
title: MyString.oopsMsg,
message:
"There is no Task For Delete!\n Try adding some and then try to delete it!",
buttonText: "Okay",
onTapDismiss: () {
Navigator.pop(context);
},
panaraDialogType: PanaraDialogType.warning,
);
}
/// Delete All Task Dialog
dynamic deleteAllTask(BuildContext context) {
return PanaraConfirmDialog.show(
context,
title: MyString.areYouSure,
message:
"Do You really want to delete all tasks? You will no be able to undo this action!",
confirmButtonText: "Yes",
cancelButtonText: "No",
onTapCancel: () {
Navigator.pop(context);
},
onTapConfirm: () {
BaseWidget.of(context).dataStore.box.clear();
Navigator.pop(context);
},
panaraDialogType: PanaraDialogType.error,
barrierDismissible: false,
);
}
/// lottie asset address
String lottieURL = 'assets/lottie/1.json';
| 0 |
mirrored_repositories/Flutter-Hive-Todo-App/flutter_hive_tdo/lib | mirrored_repositories/Flutter-Hive-Todo-App/flutter_hive_tdo/lib/utils/colors.dart | import 'package:flutter/material.dart';
class MyColors {
static const Color primaryColor = Color(0xff4568dc);
static const List<Color> primaryGradientColor = [
Color(0xff4568dc),
Color(0xffb06ab3),
];
}
| 0 |
mirrored_repositories/Flutter-Hive-Todo-App/flutter_hive_tdo/lib | mirrored_repositories/Flutter-Hive-Todo-App/flutter_hive_tdo/lib/utils/strings.dart | class MyString {
static const String mainTitle = "My Tasks";
static const String deletedTask = "This task was deleted";
static const String doneAllTask = "You Have Done All Tasks!👌";
static const String addNewTask = "Add New ";
static const String updateCurrentTask = "Update ";
static const String taskStrnig = "Task";
static const String titleOfTitleTextField = "What are you planing😇?";
static const String addNote = 'Add Note';
static const String timeString = "Time";
static const String dateString = "Date";
static const String deleteTask = "Delete Task";
static const String addTaskString = "Add Task";
static const String updateTaskString = "Update Task";
static const String oopsMsg = "Oops!";
static const String areYouSure = "Are You Sure?";
}
| 0 |
mirrored_repositories/liquid_swipe_c4 | mirrored_repositories/liquid_swipe_c4/lib/liquid_switch.dart | ////////////////////////////////////////////
///follor For more ig: @Countrol4offical
///@[email protected]
////////////////////////////////////////////
import 'package:flutter/material.dart';
import 'package:liquid_swipe/liquid_swipe.dart';
class LiquidSwipeExample extends StatefulWidget {
const LiquidSwipeExample({Key? key}) : super(key: key);
@override
_LiquidSwipeExampleState createState() => _LiquidSwipeExampleState();
}
class _LiquidSwipeExampleState extends State<LiquidSwipeExample> {
// Photos from google
final pages = [
Container(
height: double.infinity,
child: Image.network(
'https://i.pinimg.com/originals/5f/d0/96/5fd096420ae0175ce6e56605b5744032.jpg',
fit: BoxFit.cover,
),
),
Container(
height: double.infinity,
child: Image.network(
'https://wallpaperaccess.com/full/1387301.jpg',
fit: BoxFit.cover,
),
),
Container(
height: double.infinity,
child: Image.network(
'https://wallpapermemory.com/uploads/783/nebula-wallpaper-hd-1024x768-91564.jpg',
fit: BoxFit.cover,
),
),
Container(
height: double.infinity,
child: Image.network(
'https://c4.wallpaperflare.com/wallpaper/103/695/630/space-galaxy-astronomical-object-universe-wallpaper-preview.jpg',
fit: BoxFit.cover,
),
),
Container(
height: double.infinity,
child: Image.network(
'https://wallpaperaccess.com/full/1866544.jpg',
fit: BoxFit.cover,
),
),
Container(
height: double.infinity,
child: Image.network(
'https://wallpaperaccess.com/full/1198665.jpg',
fit: BoxFit.cover,
),
),
Container(
height: double.infinity,
child: Image.network(
"https://wallpaperaccess.com/full/4422642.jpg",
fit: BoxFit.cover,
),
),
];
@override
Widget build(BuildContext context) {
return Scaffold(
body: Builder(
builder: (context) {
return LiquidSwipe(
pages: pages,
fullTransitionValue: 880,
waveType: WaveType.circularReveal,
slideIconWidget: Icon(
Icons.arrow_back_ios,
color: Colors.white,
),
positionSlideIcon: 0.8,
onPageChangeCallback: (page) {
print(page);
},
liquidController: LiquidController(),
);
},
),
);
}
}
| 0 |
mirrored_repositories/liquid_swipe_c4 | mirrored_repositories/liquid_swipe_c4/lib/main.dart |
import 'package:flutter/material.dart';
import 'package:liquid_swipe_c4/liquid_switch.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner:false,
title: 'Material App',
home:LiquidSwipeExample(),
);
}
} | 0 |
mirrored_repositories/liquid_swipe_c4 | mirrored_repositories/liquid_swipe_c4/test/widget_test.dart | // This is a basic Flutter widget test.
//
// To perform an interaction with a widget in your test, use the WidgetTester
// utility that Flutter provides. For example, you can send tap and scroll
// gestures. You can also use WidgetTester to find child widgets in the widget
// tree, read text, and verify that the values of widget properties are correct.
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:liquid_swipe_c4/main.dart';
void main() {
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// Build our app and trigger a frame.
await tester.pumpWidget( MyApp());
// Verify that our counter starts at 0.
expect(find.text('0'), findsOneWidget);
expect(find.text('1'), findsNothing);
// Tap the '+' icon and trigger a frame.
await tester.tap(find.byIcon(Icons.add));
await tester.pump();
// Verify that our counter has incremented.
expect(find.text('0'), findsNothing);
expect(find.text('1'), findsOneWidget);
});
}
| 0 |
mirrored_repositories/flutter-dota2-app | mirrored_repositories/flutter-dota2-app/lib/main.dart | import 'package:dotariverpod/screens/onboard.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:get/get.dart';
void main() {
runApp(
const ProviderScope(
child: GetMaterialApp(
debugShowCheckedModeBanner: false,
title: 'Dota 2 API',
home: OnBoardView(),
),
),
);
}
| 0 |
mirrored_repositories/flutter-dota2-app/lib | mirrored_repositories/flutter-dota2-app/lib/models/heroes_models.dart | // ignore_for_file: public_member_api_docs, sort_constructors_first
import 'package:json_annotation/json_annotation.dart';
part 'heroes_models.g.dart';
@JsonSerializable()
class HeroesModel {
String? name;
String? localizedName;
String? primaryAttr;
String? attackType;
List<String>? roles;
int? legs;
HeroesModel({
this.name,
this.localizedName,
this.primaryAttr,
this.attackType,
this.roles,
this.legs,
});
factory HeroesModel.fromJson(Map<String, dynamic> json) =>
_$HeroesModelFromJson(json);
Map<String, dynamic> toJson() => _$HeroesModelToJson(this);
}
| 0 |
mirrored_repositories/flutter-dota2-app/lib | mirrored_repositories/flutter-dota2-app/lib/models/heroes_models.g.dart | // GENERATED CODE - DO NOT MODIFY BY HAND
part of 'heroes_models.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
HeroesModel _$HeroesModelFromJson(Map<String, dynamic> json) => HeroesModel(
name: json['name'] as String?,
localizedName: json['localized_name'] as String?,
primaryAttr: json['primary_attr'] as String?,
attackType: json['attack_type'] as String?,
roles:
(json['roles'] as List<dynamic>?)?.map((e) => e as String).toList(),
legs: json['legs'] as int?,
);
Map<String, dynamic> _$HeroesModelToJson(HeroesModel instance) =>
<String, dynamic>{
'name': instance.name,
'localized_name': instance.localizedName,
'primary_attr': instance.primaryAttr,
'attack_type': instance.attackType,
'roles': instance.roles,
'legs': instance.legs,
};
| 0 |
mirrored_repositories/flutter-dota2-app/lib | mirrored_repositories/flutter-dota2-app/lib/api/dota_api.dart | import 'dart:convert';
import 'package:dotariverpod/constant/api_constant.dart';
import 'package:dotariverpod/models/heroes_models.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:http/http.dart' as http;
class DotaApiService {
Future<List<HeroesModel>> fetchHeroes() async {
final options = {
'headers': {
'Authorization': Authorization,
'X-RapidAPI-Key': RapidApiKey,
'X-RapidAPI-Host': RapidApiHost,
}
};
final response =
await http.get(Uri.parse(api), headers: options['headers']);
if (response.statusCode == 200) {
List data = jsonDecode(response.body);
return data.map((e) => HeroesModel.fromJson(e)).toList();
} else {
throw Exception('Failed to load data');
}
}
}
final heroesApiServiceProvider = Provider<DotaApiService>((ref) {
return DotaApiService();
});
| 0 |
mirrored_repositories/flutter-dota2-app/lib | mirrored_repositories/flutter-dota2-app/lib/constant/api_constant.dart | // ignore_for_file: constant_identifier_names
const String api = 'https://dota-2-heroes1.p.rapidapi.com/Dota/Heroes';
const String RapidApiKey = '11b2e90425mshb00435f88ca1c48p1e12bajsn3f2fdf15b6e5';
const String RapidApiHost = 'dota-2-heroes1.p.rapidapi.com';
const String Authorization = 'Basic Ym90OjEyMw==';
| 0 |
mirrored_repositories/flutter-dota2-app/lib | mirrored_repositories/flutter-dota2-app/lib/provider/dota_provider.dart | // ignore_for_file: non_constant_identifier_names
import 'package:dotariverpod/api/dota_api.dart';
import 'package:dotariverpod/models/heroes_models.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
final DotaProvider = FutureProvider<List<HeroesModel>>((ref) async {
return ref.watch(heroesApiServiceProvider).fetchHeroes();
});
| 0 |
mirrored_repositories/flutter-dota2-app/lib | mirrored_repositories/flutter-dota2-app/lib/screens/detail.dart | import 'package:dotariverpod/provider/dota_provider.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:google_fonts/google_fonts.dart';
class DetailView extends ConsumerWidget {
const DetailView({super.key, required this.getIndex});
final int getIndex;
@override
Widget build(BuildContext context, WidgetRef ref) {
final detailData = ref.watch(DotaProvider);
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
foregroundColor: Colors.black,
centerTitle: false,
elevation: 0,
actions: [
IconButton(
onPressed: () {},
icon: const Icon(Icons.notifications_none_rounded),
),
],
title: Text(
'Dota 2 API',
style: GoogleFonts.poppins(fontSize: 17, fontWeight: FontWeight.bold),
),
),
body: SingleChildScrollView(
child: Column(
children: [
detailData.when(
data: (data) => Text('${data[getIndex].name}'),
error: ((error, stackTrace) => const Text('error')),
loading: () => const Center(
child: CircularProgressIndicator(),
),
)
],
),
),
);
}
}
| 0 |
mirrored_repositories/flutter-dota2-app/lib | mirrored_repositories/flutter-dota2-app/lib/screens/dashboard.dart | import 'package:dotariverpod/provider/dota_provider.dart';
import 'package:dotariverpod/screens/detail.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:get/get.dart';
import 'package:google_fonts/google_fonts.dart';
class DashboardView extends ConsumerWidget {
const DashboardView({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final getHero = ref.watch(DotaProvider);
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.white,
foregroundColor: Colors.black,
centerTitle: false,
elevation: 0,
actions: [
IconButton(
onPressed: () {},
icon: const Icon(Icons.notifications_none_rounded),
),
],
title: Text(
'Dota 2 API',
style: GoogleFonts.poppins(fontSize: 17, fontWeight: FontWeight.bold),
),
),
body: SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.only(left: 30, bottom: 10, top: 10),
child: Text(
'News Update',
style: GoogleFonts.poppins(
fontSize: 17,
fontWeight: FontWeight.bold,
),
),
),
Container(
width: double.infinity,
height: 200,
margin: const EdgeInsets.symmetric(vertical: 10, horizontal: 30),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
image: const DecorationImage(
fit: BoxFit.fill,
image: AssetImage('assets/images/muerta.png'),
),
),
),
Padding(
padding: const EdgeInsets.only(left: 30, top: 10, bottom: 10),
child: Text(
'All Heroes',
style: GoogleFonts.poppins(
fontSize: 17,
fontWeight: FontWeight.bold,
),
),
),
SingleChildScrollView(
child: getHero.when(
data: (data) => Container(
margin: const EdgeInsets.symmetric(horizontal: 20),
height: MediaQuery.of(context).size.height,
child: ListView.builder(
itemCount: data.length,
itemBuilder: (context, index) {
return InkWell(
onTap: () {
Get.to((context) => DetailView(getIndex: index));
},
child: Card(
margin: const EdgeInsets.symmetric(vertical: 10),
elevation: 3,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
shadowColor: Colors.green,
color: Colors.white,
child: Container(
height: 60,
alignment: Alignment.center,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
),
child: Text(
'${data[index].localizedName}',
style: GoogleFonts.poppins(
fontSize: 16,
fontWeight: FontWeight.w600,
),
),
),
),
);
},
),
),
error: ((error, stackTrace) => const Text('error')),
loading: () => const Center(
child: CircularProgressIndicator(),
),
),
)
],
),
),
bottomNavigationBar: BottomNavigationBar(
type: BottomNavigationBarType.fixed,
selectedItemColor: Colors.white,
unselectedItemColor: Colors.white,
backgroundColor: Colors.black,
items: const [
BottomNavigationBarItem(
label: 'Home',
icon: Icon(Icons.home_rounded),
),
BottomNavigationBarItem(
label: 'Setting',
icon: Icon(Icons.settings_rounded),
),
],
),
);
}
}
| 0 |
mirrored_repositories/flutter-dota2-app/lib | mirrored_repositories/flutter-dota2-app/lib/screens/onboard.dart | import 'package:dotariverpod/screens/dashboard.dart';
import 'package:flutter/material.dart';
import 'package:gap/gap.dart';
import 'package:get/route_manager.dart';
import 'package:google_fonts/google_fonts.dart';
class OnBoardView extends StatelessWidget {
const OnBoardView({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
decoration: const BoxDecoration(
image: DecorationImage(
fit: BoxFit.cover,
image: AssetImage('assets/images/onboard.png')),
),
child: Container(
decoration: BoxDecoration(
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
Colors.black.withOpacity(0),
Colors.black.withOpacity(0.85),
],
),
),
child: Padding(
padding: const EdgeInsets.all(40),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.end,
children: [
Text(
'Know Your Hero To Become Hero',
textAlign: TextAlign.center,
style: GoogleFonts.poppins(
fontSize: 35,
fontWeight: FontWeight.bold,
color: Colors.white,
),
),
Text(
'Discover Dota 2 Heroes with our Seamless Information Experiences.',
textAlign: TextAlign.center,
style: GoogleFonts.poppins(
fontSize: 15,
fontWeight: FontWeight.w400,
color: Colors.white,
),
),
const Gap(30),
ElevatedButton(
style: ElevatedButton.styleFrom(
shape: const StadiumBorder(),
minimumSize: const Size(double.infinity, 50),
backgroundColor: const Color(0XFFDB890E)),
onPressed: () {
Get.to(const DashboardView());
},
child: Text(
'Getting Started',
style: GoogleFonts.poppins(
fontSize: 18,
fontWeight: FontWeight.w500,
),
),
)
],
),
),
),
),
);
}
}
| 0 |
mirrored_repositories/flutter-dota2-app | mirrored_repositories/flutter-dota2-app/test/widget_test.dart | // // This is a basic Flutter widget test.
// //
// // To perform an interaction with a widget in your test, use the WidgetTester
// // utility in the flutter_test package. For example, you can send tap and scroll
// // gestures. You can also use WidgetTester to find child widgets in the widget
// // tree, read text, and verify that the values of widget properties are correct.
// import 'package:flutter/material.dart';
// import 'package:flutter_test/flutter_test.dart';
// import 'package:dotariverpod/main.dart';
// void main() {
// testWidgets('Counter increments smoke test', (WidgetTester tester) async {
// // Build our app and trigger a frame.
// await tester.pumpWidget(const MyApp());
// // Verify that our counter starts at 0.
// expect(find.text('0'), findsOneWidget);
// expect(find.text('1'), findsNothing);
// // Tap the '+' icon and trigger a frame.
// await tester.tap(find.byIcon(Icons.add));
// await tester.pump();
// // Verify that our counter has incremented.
// expect(find.text('0'), findsNothing);
// expect(find.text('1'), findsOneWidget);
// });
// }
| 0 |
mirrored_repositories/license_page_example | mirrored_repositories/license_page_example/lib/main.dart | import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:license_page_example/page/licenses_custom_page.dart';
import 'package:license_page_example/page/licenses_registry_page.dart';
import 'package:license_page_example/page/licenses_simple_page.dart';
Future main() async {
WidgetsFlutterBinding.ensureInitialized();
await SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
DeviceOrientation.portraitDown,
]);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
static final String title = 'License Page';
@override
Widget build(BuildContext context) => MaterialApp(
debugShowCheckedModeBanner: false,
title: title,
theme: ThemeData(primaryColor: Colors.indigoAccent),
home: MainPage(title: title),
);
}
class MainPage extends StatefulWidget {
final String title;
const MainPage({
@required this.title,
});
@override
_MainPageState createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> {
@override
Widget build(BuildContext context) => Scaffold(
backgroundColor: Colors.black,
appBar: AppBar(
title: Text(widget.title),
),
body: Padding(
padding: EdgeInsets.all(32),
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
buildButton(
text: 'Simple Licenses',
onClicked: () => Navigator.of(context).push(MaterialPageRoute(
builder: (context) => LicensesSimplePage(),
)),
// onClicked: () => showLicensePage(
// context: context,
// applicationName: 'My App Name',
// applicationIcon: Padding(
// padding: EdgeInsets.all(8),
// child:
// Image.asset('assets/logo.png', width: 48, height: 48),
// ),
// applicationVersion: '0.0.1',
// applicationLegalese: 'Copyright My Company',
// ),
),
const SizedBox(height: 24),
buildButton(
text: 'Registry Licenses',
onClicked: () => Navigator.of(context).push(MaterialPageRoute(
builder: (context) => LicensesRegistryPage(),
)),
),
const SizedBox(height: 24),
buildButton(
text: 'Custom Licenses',
onClicked: () => Navigator.of(context).push(MaterialPageRoute(
builder: (context) => LicensesCustomPage(),
)),
),
],
),
),
),
);
Widget buildButton({
@required String text,
@required VoidCallback onClicked,
}) =>
ElevatedButton(
style: ElevatedButton.styleFrom(
minimumSize: Size.fromHeight(50),
),
child: Text(text, style: TextStyle(fontSize: 20)),
onPressed: onClicked,
);
}
| 0 |
mirrored_repositories/license_page_example/lib | mirrored_repositories/license_page_example/lib/page/licenses_custom_page.dart | import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:license_page_example/model/license.dart';
import 'package:license_page_example/widget/licenses_widget.dart';
class LicensesCustomPage extends StatelessWidget {
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
title: Text('Licenses'),
centerTitle: true,
),
body: FutureBuilder<List<License>>(
future: loadLicenses(context),
builder: (context, snapshot) {
final licenses = snapshot.data;
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
default:
if (snapshot.hasError) {
return Center(child: Text('Some error occurred!'));
} else {
return LicensesWidget(licenses: licenses);
}
}
},
),
);
Future<List<License>> loadLicenses(BuildContext context) async {
final bundle = DefaultAssetBundle.of(context);
final licenses = await bundle.loadString('assets/licenses.json');
return json
.decode(licenses)
.map<License>((license) => License.fromJson(license))
.toList();
}
}
| 0 |
mirrored_repositories/license_page_example/lib | mirrored_repositories/license_page_example/lib/page/licenses_registry_page.dart | import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:license_page_example/model/license.dart';
import 'package:license_page_example/widget/licenses_widget.dart';
class LicensesRegistryPage extends StatelessWidget {
@override
Widget build(BuildContext context) => Scaffold(
appBar: AppBar(
title: Text('Licenses'),
centerTitle: true,
),
body: FutureBuilder<List<License>>(
future: loadLicenses(),
builder: (context, snapshot) {
final licenses = snapshot.data;
switch (snapshot.connectionState) {
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
default:
if (snapshot.hasError) {
return Center(child: Text('Some error occurred!'));
} else {
return LicensesWidget(licenses: licenses);
}
}
},
),
);
Future<List<License>> loadLicenses() async =>
LicenseRegistry.licenses.asyncMap<License>((license) async {
final title = license.packages.join('\n');
final text = license.paragraphs
.map<String>((paragraph) => paragraph.text)
.join('\n\n');
return License(title, text);
}).toList();
}
| 0 |
mirrored_repositories/license_page_example/lib | mirrored_repositories/license_page_example/lib/page/licenses_simple_page.dart | import 'package:flutter/material.dart';
class LicensesSimplePage extends StatelessWidget {
@override
Widget build(BuildContext context) => Theme(
data: ThemeData.dark(),
child: LicensePage(
applicationName: 'My App Name',
applicationIcon: Padding(
padding: EdgeInsets.all(8),
child: Image.asset('assets/logo.png', width: 48, height: 48),
),
applicationVersion: '0.0.1',
applicationLegalese: 'Copyright ${DateTime.now().year} My Company',
),
);
}
| 0 |
mirrored_repositories/license_page_example/lib | mirrored_repositories/license_page_example/lib/model/license.dart | class License {
String title;
String text;
License(this.title, this.text);
License.fromJson(Map<String, dynamic> json) {
title = json['title'];
text = json['text'];
}
}
| 0 |
mirrored_repositories/license_page_example/lib | mirrored_repositories/license_page_example/lib/widget/licenses_widget.dart | import 'package:flutter/material.dart';
import 'package:license_page_example/model/license.dart';
class LicensesWidget extends StatelessWidget {
final List<License> licenses;
const LicensesWidget({
Key key,
@required this.licenses,
}) : super(key: key);
@override
Widget build(BuildContext context) => ListView.builder(
padding: EdgeInsets.only(bottom: 24),
itemCount: licenses.length,
itemBuilder: (context, index) {
final license = licenses[index];
return ListTile(
title: Container(
padding: const EdgeInsets.symmetric(vertical: 24),
child: Text(
license.title,
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
),
),
subtitle: Text(
license.text,
style: TextStyle(fontSize: 18, color: Colors.black),
),
);
},
);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/scripts | mirrored_repositories/AppFlowy/frontend/scripts/flutter_release_build/build_flowy.dart | import 'dart:io';
part 'tool.dart';
const excludeTagBegin = 'BEGIN: EXCLUDE_IN_RELEASE';
const excludeTagEnd = 'END: EXCLUDE_IN_RELEASE';
Future<void> main(List<String> args) async {
const help = '''
A build script that modifies build assets before building the release version of AppFlowy.
args[0] (required): The subcommand to use (build, include-directives, exclude-directives, run).
- run: calls exclude-directives, build, include-directives.
- build: builds the release version of AppFlowy.
- include-directives: adds the directives from pubspec.yaml.
- exclude-directives: removes the directives from pubspec.yaml.
args[1] (required): The repository root for appflowy (the directory containing pubspec.yaml).
args[2] (required): version (only relevant for build). The version of the app to build.
''';
const numArgs = 3;
assert(args.length == numArgs,
'Expected ${numArgs}, got ${args.length}. Read the following for instructions about how to use this script.\n\n$help');
if (args[0] == '-h' || args[0] == '--help') {
stdout.write(help);
stdout.flush();
}
// parse the vesrion
final version = args[2];
// parse the first required argument
final repositoryRoot = Directory(args[1]);
assert(await repositoryRoot.exists(),
'$repositoryRoot is an invalid directory. Please try again with a valid directory.\n\n$help');
// parse the command
final command = args[0];
final tool =
BuildTool(repositoryRoot: repositoryRoot.path, appVersion: version);
switch (command) {
case 'run':
await tool.run();
break;
case 'build':
await tool.build();
break;
case 'include-directives':
await tool.directives(ModifyMode.include);
break;
case 'exclude-directives':
await tool.directives(ModifyMode.exclude);
break;
default:
throw StateError('Invalid command: $command');
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/scripts | mirrored_repositories/AppFlowy/frontend/scripts/flutter_release_build/tool.dart | part of 'build_flowy.dart';
enum _ScanMode {
ignore,
target,
}
enum ModifyMode {
include,
exclude,
}
class BuildTool {
const BuildTool({
required this.repositoryRoot,
required this.appVersion,
this.arch,
});
final String repositoryRoot;
final String appVersion;
final String? arch;
String get projectRoot =>
[repositoryRoot, 'appflowy_flutter'].join(Platform.pathSeparator);
File get pubspec =>
File([projectRoot, 'pubspec.yaml'].join(Platform.pathSeparator));
Future<String> get _architecture async =>
await Process.run('uname', ['-m']).then((value) => value.stdout.trim());
Future<String> get _commandForOS async {
// Check the operating system and CPU architecture
final os = Platform.operatingSystem;
final arch = this.arch ??
(Platform.isMacOS ? await _architecture : Platform.localHostname);
// Determine the appropriate command based on the OS and architecture
if (os == 'windows') {
return 'cargo make --env APP_VERSION=$appVersion --profile production-windows-x86 appflowy --verbose';
}
if (os == 'linux') {
return 'cargo make --env APP_VERSION=$appVersion --profile production-linux-x86_64 appflowy';
}
if (os == 'macos') {
if (arch == 'x86_64') {
return 'cargo make --env APP_VERSION=$appVersion --profile production-mac-x86_64 appflowy';
}
if (arch == 'arm64') {
return 'cargo make --env APP_VERSION=$appVersion --profile production-mac-arm64 appflowy';
}
throw 'Unsupported CPU architecture: $arch';
}
throw 'Unsupported operating system: $os';
}
/// Scans a file for lines between # BEGIN: EXCLUDE_IN_RELEASE and
/// END: EXCLUDE_IN_RELEASE. Will add a comment to remove those assets
/// from the build.
Future<void> process_directives(
File file, {
required ModifyMode mode,
}) async {
// Read the contents of the file into a list
var lines = await file.readAsLines();
// Find the lines between BEGIN: EXCLUDE_IN_RELEASE and END: EXCLUDE_IN_RELEASE
var scanMode = _ScanMode.ignore;
for (var i = 0; i < lines.length; i++) {
var line = lines[i];
if (line.contains(excludeTagBegin)) {
scanMode = _ScanMode.target;
} else if (line.contains(excludeTagEnd)) {
scanMode = _ScanMode.ignore;
} else if (scanMode == _ScanMode.target) {
lines[i] = _modify(line, mode: mode);
}
}
// Write the modified contents back to the file
await file.writeAsString(lines.join('\n'), flush: true);
}
String _modify(String line, {required ModifyMode mode}) {
switch (mode) {
case ModifyMode.include:
return line.split('#').where((element) => element != '#').join();
case ModifyMode.exclude:
return '#$line';
}
}
Future<void> build() async {
final cwd = Directory.current;
Directory.current = repositoryRoot;
final cmd = await _commandForOS;
// Run the command using the Process.run() function
// final build = await Process.run('echo', ['hello'], runInShell: true);
final build =
await Process.start(cmd.split(' ')[0], cmd.split(' ').sublist(1));
await stdout.addStream(build.stdout);
await stderr.addStream(build.stderr);
Directory.current = cwd;
}
Future<void> directives(ModifyMode mode) async {
await process_directives(pubspec, mode: mode);
}
Future<void> run() async {
final pubspec = this.pubspec;
await process_directives(pubspec, mode: ModifyMode.exclude);
await build();
await process_directives(pubspec, mode: ModifyMode.include);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/main.dart | import 'package:flutter/material.dart';
import 'startup/startup.dart';
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await runAppFlowy();
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/shared/feature_flags.dart | import 'dart:convert';
import 'package:appflowy/core/config/kv.dart';
import 'package:appflowy/core/config/kv_keys.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:collection/collection.dart';
typedef FeatureFlagMap = Map<FeatureFlag, bool>;
/// The [FeatureFlag] is used to control the front-end features of the app.
///
/// For example, if your feature is still under development,
/// you can set the value to `false` to hide the feature.
enum FeatureFlag {
// used to control the visibility of the collaborative workspace feature
// if it's on, you can see the workspace list and the workspace settings
// in the top-left corner of the app
collaborativeWorkspace,
// used to control the visibility of the members settings
// if it's on, you can see the members settings in the settings page
membersSettings,
// used to control the sync feature of the document
// if it's on, the document will be synced the events from server in real-time
syncDocument,
// used to control the sync feature of the database
// if it's on, the collaborators will show in the database
syncDatabase,
// used for ignore the conflicted feature flag
unknown;
static Future<void> initialize() async {
final values = await getIt<KeyValueStorage>().getWithFormat<FeatureFlagMap>(
KVKeys.featureFlag,
(value) => Map.from(jsonDecode(value)).map(
(key, value) {
final k = FeatureFlag.values.firstWhereOrNull(
(e) => e.name == key,
) ??
FeatureFlag.unknown;
return MapEntry(k, value as bool);
},
),
) ??
{};
_values = {
...{for (final flag in FeatureFlag.values) flag: false},
...values,
};
}
static UnmodifiableMapView<FeatureFlag, bool> get data =>
UnmodifiableMapView(_values);
Future<void> turnOn() async {
await update(true);
}
Future<void> turnOff() async {
await update(false);
}
Future<void> update(bool value) async {
_values[this] = value;
await getIt<KeyValueStorage>().set(
KVKeys.featureFlag,
jsonEncode(
_values.map((key, value) => MapEntry(key.name, value)),
),
);
}
static Future<void> clear() async {
_values = {};
await getIt<KeyValueStorage>().remove(KVKeys.featureFlag);
}
bool get isOn {
if ([
// release this feature in version 0.5.5
FeatureFlag.collaborativeWorkspace,
FeatureFlag.membersSettings,
// release this feature in version 0.5.4
FeatureFlag.syncDatabase,
FeatureFlag.syncDocument,
].contains(this)) {
return true;
}
if (_values.containsKey(this)) {
return _values[this]!;
}
switch (this) {
case FeatureFlag.collaborativeWorkspace:
return false;
case FeatureFlag.membersSettings:
return false;
case FeatureFlag.syncDocument:
return true;
case FeatureFlag.syncDatabase:
return true;
case FeatureFlag.unknown:
return false;
}
}
String get description {
switch (this) {
case FeatureFlag.collaborativeWorkspace:
return 'if it\'s on, you can see the workspace list and the workspace settings in the top-left corner of the app';
case FeatureFlag.membersSettings:
return 'if it\'s on, you can see the members settings in the settings page';
case FeatureFlag.syncDocument:
return 'if it\'s on, the document will be synced in real-time';
case FeatureFlag.syncDatabase:
return 'if it\'s on, the collaborators will show in the database';
case FeatureFlag.unknown:
return '';
}
}
String get key => 'appflowy_feature_flag_${toString()}';
}
FeatureFlagMap _values = {};
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/shared/custom_image_cache_manager.dart | import 'package:appflowy/shared/appflowy_cache_manager.dart';
import 'package:appflowy/startup/tasks/prelude.dart';
import 'package:file/file.dart' hide FileSystem;
import 'package:file/local.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:path/path.dart' as p;
class CustomImageCacheManager extends CacheManager
with ImageCacheManager
implements ICache {
CustomImageCacheManager._()
: super(
Config(
key,
fileSystem: CustomIOFileSystem(key),
),
);
factory CustomImageCacheManager() => _instance;
static final CustomImageCacheManager _instance = CustomImageCacheManager._();
static const key = 'image_cache';
@override
Future<int> cacheSize() async {
// https://github.com/Baseflow/flutter_cache_manager/issues/239#issuecomment-719475429
// this package does not provide a way to get the cache size
return 0;
}
@override
Future<void> clearAll() async {
await emptyCache();
}
}
class CustomIOFileSystem implements FileSystem {
CustomIOFileSystem(this._cacheKey) : _fileDir = createDirectory(_cacheKey);
final Future<Directory> _fileDir;
final String _cacheKey;
static Future<Directory> createDirectory(String key) async {
final baseDir = await appFlowyApplicationDataDirectory();
final path = p.join(baseDir.path, key);
const fs = LocalFileSystem();
final directory = fs.directory(path);
await directory.create(recursive: true);
return directory;
}
@override
Future<File> createFile(String name) async {
final directory = await _fileDir;
if (!(await directory.exists())) {
await createDirectory(_cacheKey);
}
return directory.childFile(name);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/shared/appflowy_network_image.dart | import 'dart:convert';
import 'package:appflowy/shared/custom_image_cache_manager.dart';
import 'package:appflowy/util/string_extension.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:string_validator/string_validator.dart';
/// This widget handles the downloading and caching of either internal or network images.
///
/// It will append the access token to the URL if the URL is internal.
class FlowyNetworkImage extends StatelessWidget {
const FlowyNetworkImage({
super.key,
this.userProfilePB,
this.width,
this.height,
this.fit = BoxFit.cover,
this.progressIndicatorBuilder,
this.errorWidgetBuilder,
required this.url,
});
final UserProfilePB? userProfilePB;
final String url;
final double? width;
final double? height;
final BoxFit fit;
final ProgressIndicatorBuilder? progressIndicatorBuilder;
final LoadingErrorWidgetBuilder? errorWidgetBuilder;
@override
Widget build(BuildContext context) {
assert(isURL(url));
if (url.isAppFlowyCloudUrl) {
assert(userProfilePB != null && userProfilePB!.token.isNotEmpty);
}
final manager = CustomImageCacheManager();
return CachedNetworkImage(
cacheManager: manager,
httpHeaders: _header(),
imageUrl: url,
fit: fit,
width: width,
height: height,
progressIndicatorBuilder: progressIndicatorBuilder,
errorWidget: (context, url, error) =>
errorWidgetBuilder?.call(context, url, error) ??
const SizedBox.shrink(),
errorListener: (value) {
// try to clear the image cache.
manager.removeFile(url);
Log.error(value.toString());
},
);
}
Map<String, String> _header() {
final header = <String, String>{};
final token = userProfilePB?.token;
if (token != null) {
try {
final decodedToken = jsonDecode(token);
header['Authorization'] = 'Bearer ${decodedToken['access_token']}';
} catch (e) {
Log.error('unable to decode token: $e');
}
}
return header;
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/shared/appflowy_cache_manager.dart | import 'package:appflowy/shared/feature_flags.dart';
import 'package:appflowy_backend/log.dart';
import 'package:path_provider/path_provider.dart';
class FlowyCacheManager {
final _caches = <ICache>[];
// if you add a new cache, you should register it here.
void registerCache(ICache cache) {
_caches.add(cache);
}
void unregisterAllCache(ICache cache) {
_caches.clear();
}
Future<void> clearAllCache() async {
try {
for (final cache in _caches) {
await cache.clearAll();
}
Log.info('Cache cleared');
} catch (e) {
Log.error(e);
}
}
Future<int> getCacheSize() async {
try {
int tmpDirSize = 0;
for (final cache in _caches) {
tmpDirSize += await cache.cacheSize();
}
Log.info('Cache size: $tmpDirSize');
return tmpDirSize;
} catch (e) {
Log.error(e);
return 0;
}
}
}
abstract class ICache {
Future<int> cacheSize();
Future<void> clearAll();
}
class TemporaryDirectoryCache implements ICache {
@override
Future<int> cacheSize() async {
final tmpDir = await getTemporaryDirectory();
final tmpDirStat = await tmpDir.stat();
return tmpDirStat.size;
}
@override
Future<void> clearAll() async {
final tmpDir = await getTemporaryDirectory();
await tmpDir.delete(recursive: true);
}
}
class FeatureFlagCache implements ICache {
@override
Future<int> cacheSize() async {
return 0;
}
@override
Future<void> clearAll() async {
await FeatureFlag.clear();
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/shared/list_extension.dart | extension Unique<E, Id> on List<E> {
List<E> unique([Id Function(E element)? id]) {
final ids = <dynamic>{};
final list = [...this];
list.retainWhere((x) => ids.add(id != null ? id(x) : x as Id));
return list;
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/shared/af_role_pb_extension.dart | import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart';
import 'package:easy_localization/easy_localization.dart';
extension AFRolePBExtension on AFRolePB {
bool get isOwner => this == AFRolePB.Owner;
bool get isMember => this == AFRolePB.Member;
bool get canInvite => isOwner;
bool get canDelete => isOwner;
bool get canUpdate => isOwner;
bool get canLeave => this != AFRolePB.Owner;
String get description {
switch (this) {
case AFRolePB.Owner:
return LocaleKeys.settings_appearance_members_owner.tr();
case AFRolePB.Member:
return LocaleKeys.settings_appearance_members_member.tr();
case AFRolePB.Guest:
return LocaleKeys.settings_appearance_members_guest.tr();
}
throw UnimplementedError('Unknown role: $this');
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/shared/cloud_image_checker.dart | import 'dart:convert';
import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart';
import 'package:http/http.dart' as http;
Future<bool> isImageExistOnCloud({
required String url,
required UserProfilePB userProfilePB,
}) async {
final header = <String, String>{};
final token = userProfilePB.token;
try {
final decodedToken = jsonDecode(token);
header['Authorization'] = 'Bearer ${decodedToken['access_token']}';
final response = await http.get(Uri.http(url), headers: header);
return response.statusCode == 200;
} catch (_) {
return false;
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/shared | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/shared/patterns/common_patterns.dart | const _trailingZerosPattern = r'^(\d+(?:\.\d*?[1-9](?=0|\b))?)\.?0*$';
final trailingZerosRegex = RegExp(_trailingZerosPattern);
const _hrefPattern =
r'https?://(?:www\.)?[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,}(?:/[^\s]*)?';
final hrefRegex = RegExp(_hrefPattern);
/// This pattern allows for both HTTP and HTTPS Scheme
/// It allows for query parameters
/// It only allows the following image extensions: .png, .jpg, .gif, .webm
///
const _imgUrlPattern =
r'(https?:\/\/)([^\s(["<,>/]*)(\/)[^\s[",><]*(.png|.jpg|.gif|.webm)(\?[^\s[",><]*)?';
final imgUrlRegex = RegExp(_imgUrlPattern);
const _appflowyCloudUrlPattern = r'^(https:\/\/)(.*)(\.appflowy\.cloud\/)(.*)';
final appflowyCloudUrlRegex = RegExp(_appflowyCloudUrlPattern);
const _camelCasePattern = '(?<=[a-z])[A-Z]';
final camelCaseRegex = RegExp(_camelCasePattern);
const _macOSVolumesPattern = '^/Volumes/[^/]+';
final macOSVolumesRegex = RegExp(_macOSVolumesPattern);
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/shared | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/shared/patterns/date_time_patterns.dart | /// RegExp to match Twelve Hour formats
/// Source: https://stackoverflow.com/a/33906224
///
/// Matches eg: "05:05 PM", "5:50 Pm", "10:59 am", etc.
///
const _twelveHourTimePattern =
r'\b((1[0-2]|0?[1-9]):([0-5][0-9]) ([AaPp][Mm]))';
final twelveHourTimeRegex = RegExp(_twelveHourTimePattern);
bool isTwelveHourTime(String? time) => twelveHourTimeRegex.hasMatch(time ?? '');
/// RegExp to match Twenty Four Hour formats
/// Source: https://stackoverflow.com/a/7536768
///
/// Matches eg: "0:01", "04:59", "16:30", etc.
///
const _twentyFourHourtimePattern = r'^([0-1]?[0-9]|2[0-3]):[0-5][0-9]$';
final tewentyFourHourTimeRegex = RegExp(_twentyFourHourtimePattern);
bool isTwentyFourHourTime(String? time) =>
tewentyFourHourTimeRegex.hasMatch(time ?? '');
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/appearance_defaults.dart | import 'package:flowy_infra/theme.dart';
import 'package:flutter/material.dart';
/// A class for the default appearance settings for the app
class DefaultAppearanceSettings {
static const kDefaultFontFamily = 'Poppins';
static const kDefaultThemeMode = ThemeMode.system;
static const kDefaultThemeName = "Default";
static const kDefaultTheme = BuiltInTheme.defaultTheme;
static Color getDefaultDocumentCursorColor(BuildContext context) {
return Theme.of(context).colorScheme.primary;
}
static Color getDefaultDocumentSelectionColor(BuildContext context) {
return Theme.of(context).colorScheme.primary.withOpacity(0.2);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/edit_panel/edit_context.dart | import 'package:equatable/equatable.dart';
import 'package:flutter/material.dart';
abstract class EditPanelContext extends Equatable {
const EditPanelContext({
required this.identifier,
required this.title,
required this.child,
});
final String identifier;
final String title;
final Widget child;
@override
List<Object> get props => [identifier];
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/edit_panel/edit_panel_bloc.dart | import 'package:appflowy/workspace/application/edit_panel/edit_context.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'edit_panel_bloc.freezed.dart';
class EditPanelBloc extends Bloc<EditPanelEvent, EditPanelState> {
EditPanelBloc() : super(EditPanelState.initial()) {
on<EditPanelEvent>((event, emit) async {
await event.map(
startEdit: (e) async {
emit(state.copyWith(isEditing: true, editContext: e.context));
},
endEdit: (value) async {
emit(state.copyWith(isEditing: false, editContext: null));
},
);
});
}
}
@freezed
class EditPanelEvent with _$EditPanelEvent {
const factory EditPanelEvent.startEdit(EditPanelContext context) = _StartEdit;
const factory EditPanelEvent.endEdit(EditPanelContext context) = _EndEdit;
}
@freezed
class EditPanelState with _$EditPanelState {
const factory EditPanelState({
required bool isEditing,
required EditPanelContext? editContext,
}) = _EditPanelState;
factory EditPanelState.initial() => const EditPanelState(
isEditing: false,
editContext: null,
);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/notification/notification_service.dart | import 'package:flutter/foundation.dart';
import 'package:local_notifier/local_notifier.dart';
const _appName = "AppFlowy";
/// Manages Local Notifications
///
/// Currently supports:
/// - MacOS
/// - Windows
/// - Linux
///
class NotificationService {
static Future<void> initialize() async {
await localNotifier.setup(appName: _appName);
}
}
/// Creates and shows a Notification
///
class NotificationMessage {
NotificationMessage({
required String title,
required String body,
String? identifier,
VoidCallback? onClick,
}) {
_notification = LocalNotification(
identifier: identifier,
title: title,
body: body,
)..onClick = onClick;
_show();
}
late final LocalNotification _notification;
void _show() => _notification.show();
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/view/view_service.dart | import 'dart:async';
import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/protobuf.dart';
import 'package:appflowy_result/appflowy_result.dart';
class ViewBackendService {
static Future<FlowyResult<ViewPB, FlowyError>> createView({
/// The [layoutType] is the type of the view.
required ViewLayoutPB layoutType,
/// The [parentViewId] is the parent view id.
required String parentViewId,
/// The [name] is the name of the view.
required String name,
String? desc,
/// The default value of [openAfterCreate] is false, meaning the view will
/// not be opened nor set as the current view. However, if set to true, the
/// view will be opened and set as the current view. Upon relaunching the
/// app, this view will be opened
bool openAfterCreate = false,
/// The initial data should be a JSON that represent the DocumentDataPB.
/// Currently, only support create document with initial data.
List<int>? initialDataBytes,
/// The [ext] is used to pass through the custom configuration
/// to the backend.
/// Linking the view to the existing database, it needs to pass
/// the database id. For example: "database_id": "xxx"
///
Map<String, String> ext = const {},
/// The [index] is the index of the view in the parent view.
/// If the index is null, the view will be added to the end of the list.
int? index,
ViewSectionPB? section,
}) {
final payload = CreateViewPayloadPB.create()
..parentViewId = parentViewId
..name = name
..desc = desc ?? ""
..layout = layoutType
..setAsCurrent = openAfterCreate
..initialData = initialDataBytes ?? [];
if (ext.isNotEmpty) {
payload.meta.addAll(ext);
}
if (desc != null) {
payload.desc = desc;
}
if (index != null) {
payload.index = index;
}
if (section != null) {
payload.section = section;
}
return FolderEventCreateView(payload).send();
}
/// The orphan view is meant to be a view that is not attached to any parent view. By default, this
/// view will not be shown in the view list unless it is attached to a parent view that is shown in
/// the view list.
static Future<FlowyResult<ViewPB, FlowyError>> createOrphanView({
required String viewId,
required ViewLayoutPB layoutType,
required String name,
String? desc,
/// The initial data should be a JSON that represent the DocumentDataPB.
/// Currently, only support create document with initial data.
List<int>? initialDataBytes,
}) {
final payload = CreateOrphanViewPayloadPB.create()
..viewId = viewId
..name = name
..desc = desc ?? ""
..layout = layoutType
..initialData = initialDataBytes ?? [];
return FolderEventCreateOrphanView(payload).send();
}
static Future<FlowyResult<ViewPB, FlowyError>> createDatabaseLinkedView({
required String parentViewId,
required String databaseId,
required ViewLayoutPB layoutType,
required String name,
}) {
return ViewBackendService.createView(
layoutType: layoutType,
parentViewId: parentViewId,
name: name,
ext: {
'database_id': databaseId,
},
);
}
/// Returns a list of views that are the children of the given [viewId].
static Future<FlowyResult<List<ViewPB>, FlowyError>> getChildViews({
required String viewId,
}) {
final payload = ViewIdPB.create()..value = viewId;
return FolderEventGetView(payload).send().then((result) {
return result.fold(
(view) => FlowyResult.success(view.childViews),
(error) => FlowyResult.failure(error),
);
});
}
static Future<FlowyResult<void, FlowyError>> delete({
required String viewId,
}) {
final request = RepeatedViewIdPB.create()..items.add(viewId);
return FolderEventDeleteView(request).send();
}
static Future<FlowyResult<void, FlowyError>> deleteView({
required String viewId,
}) {
final request = RepeatedViewIdPB.create()..items.add(viewId);
return FolderEventDeleteView(request).send();
}
static Future<FlowyResult<void, FlowyError>> duplicate({
required ViewPB view,
}) {
return FolderEventDuplicateView(view).send();
}
static Future<FlowyResult<void, FlowyError>> favorite({
required String viewId,
}) {
final request = RepeatedViewIdPB.create()..items.add(viewId);
return FolderEventToggleFavorite(request).send();
}
static Future<FlowyResult<ViewPB, FlowyError>> updateView({
required String viewId,
String? name,
bool? isFavorite,
}) {
final payload = UpdateViewPayloadPB.create()..viewId = viewId;
if (name != null) {
payload.name = name;
}
if (isFavorite != null) {
payload.isFavorite = isFavorite;
}
return FolderEventUpdateView(payload).send();
}
static Future<FlowyResult<void, FlowyError>> updateViewIcon({
required String viewId,
required String viewIcon,
ViewIconTypePB iconType = ViewIconTypePB.Emoji,
}) {
final icon = ViewIconPB()
..ty = iconType
..value = viewIcon;
final payload = UpdateViewIconPayloadPB.create()
..viewId = viewId
..icon = icon;
return FolderEventUpdateViewIcon(payload).send();
}
// deprecated
static Future<FlowyResult<void, FlowyError>> moveView({
required String viewId,
required int fromIndex,
required int toIndex,
}) {
final payload = MoveViewPayloadPB.create()
..viewId = viewId
..from = fromIndex
..to = toIndex;
return FolderEventMoveView(payload).send();
}
/// Move the view to the new parent view.
///
/// supports nested view
/// if the [prevViewId] is null, the view will be moved to the beginning of the list
static Future<FlowyResult<void, FlowyError>> moveViewV2({
required String viewId,
required String newParentId,
required String? prevViewId,
ViewSectionPB? fromSection,
ViewSectionPB? toSection,
}) {
final payload = MoveNestedViewPayloadPB(
viewId: viewId,
newParentId: newParentId,
prevViewId: prevViewId,
fromSection: fromSection,
toSection: toSection,
);
return FolderEventMoveNestedView(payload).send();
}
Future<List<ViewPB>> fetchViewsWithLayoutType(
ViewLayoutPB? layoutType,
) async {
final views = await fetchViews();
if (layoutType == null) {
return views;
}
return views
.where(
(element) => layoutType == element.layout,
)
.toList();
}
Future<List<ViewPB>> fetchViews() async {
final result = <ViewPB>[];
return FolderEventReadCurrentWorkspace().send().then((value) async {
final workspace = value.toNullable();
if (workspace != null) {
final views = workspace.views;
for (final view in views) {
result.add(view);
final childViews = await getAllViews(view);
result.addAll(childViews);
}
}
return result;
});
}
Future<List<ViewPB>> getAllViews(ViewPB view) async {
final result = <ViewPB>[];
final childViews = await getChildViews(viewId: view.id).then(
(value) => value.toNullable(),
);
if (childViews != null && childViews.isNotEmpty) {
result.addAll(childViews);
final views = await Future.wait(
childViews.map((e) async => getAllViews(e)),
);
result.addAll(views.expand((element) => element));
}
return result;
}
static Future<FlowyResult<ViewPB, FlowyError>> getView(
String viewId,
) async {
final payload = ViewIdPB.create()..value = viewId;
return FolderEventGetView(payload).send();
}
static Future<FlowyResult<RepeatedViewPB, FlowyError>> getViewAncestors(
String viewId,
) async {
final payload = ViewIdPB.create()..value = viewId;
return FolderEventGetViewAncestors(payload).send();
}
Future<FlowyResult<ViewPB, FlowyError>> getChildView({
required String parentViewId,
required String childViewId,
}) async {
final payload = ViewIdPB.create()..value = parentViewId;
return FolderEventGetView(payload).send().then((result) {
return result.fold(
(app) => FlowyResult.success(
app.childViews.firstWhere((e) => e.id == childViewId),
),
(error) => FlowyResult.failure(error),
);
});
}
static Future<FlowyResult<void, FlowyError>> updateViewsVisibility(
List<ViewPB> views,
bool isPublic,
) async {
final payload = UpdateViewVisibilityStatusPayloadPB(
viewIds: views.map((e) => e.id).toList(),
isPublic: isPublic,
);
return FolderEventUpdateViewVisibilityStatus(payload).send();
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/view/prelude.dart | export 'view_bloc.dart';
export 'view_listener.dart';
export 'view_service.dart';
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/view/view_bloc.dart | import 'dart:convert';
import 'package:appflowy/core/config/kv.dart';
import 'package:appflowy/core/config/kv_keys.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/workspace/application/favorite/favorite_listener.dart';
import 'package:appflowy/workspace/application/recent/recent_service.dart';
import 'package:appflowy/workspace/application/view/view_listener.dart';
import 'package:appflowy/workspace/application/view/view_service.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:collection/collection.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:protobuf/protobuf.dart';
part 'view_bloc.freezed.dart';
class ViewBloc extends Bloc<ViewEvent, ViewState> {
ViewBloc({required this.view})
: viewBackendSvc = ViewBackendService(),
listener = ViewListener(viewId: view.id),
favoriteListener = FavoriteListener(),
super(ViewState.init(view)) {
_dispatch();
}
final ViewPB view;
final ViewBackendService viewBackendSvc;
final ViewListener listener;
final FavoriteListener favoriteListener;
@override
Future<void> close() async {
await listener.stop();
await favoriteListener.stop();
return super.close();
}
void _dispatch() {
on<ViewEvent>(
(event, emit) async {
await event.map(
initial: (e) async {
listener.start(
onViewUpdated: (result) {
add(ViewEvent.viewDidUpdate(FlowyResult.success(result)));
},
onViewChildViewsUpdated: (result) async {
final view = await _updateChildViews(result);
if (!isClosed && view != null) {
add(ViewEvent.viewUpdateChildView(view));
}
},
);
favoriteListener.start(
favoritesUpdated: (result, isFavorite) {
result.fold(
(result) {
final current = result.items
.firstWhereOrNull((v) => v.id == state.view.id);
if (current != null) {
add(
ViewEvent.viewDidUpdate(
FlowyResult.success(current),
),
);
}
},
(error) {},
);
},
);
final isExpanded = await _getViewIsExpanded(view);
emit(state.copyWith(isExpanded: isExpanded));
await _loadViewsWhenExpanded(emit, isExpanded);
},
setIsEditing: (e) {
emit(state.copyWith(isEditing: e.isEditing));
},
setIsExpanded: (e) async {
if (e.isExpanded && !state.isExpanded) {
await _loadViewsWhenExpanded(emit, true);
} else {
emit(state.copyWith(isExpanded: e.isExpanded));
}
await _setViewIsExpanded(view, e.isExpanded);
},
viewDidUpdate: (e) async {
final result = await ViewBackendService.getView(
view.id,
);
final view_ = result.fold((l) => l, (r) => null);
e.result.fold(
(view) async {
// ignore child view changes because it only contains one level
// children data.
if (_isSameViewIgnoreChildren(view, state.view)) {
// do nothing.
}
emit(
state.copyWith(
view: view_ ?? view,
successOrFailure: FlowyResult.success(null),
),
);
},
(error) => emit(
state.copyWith(successOrFailure: FlowyResult.failure(error)),
),
);
},
rename: (e) async {
final result = await ViewBackendService.updateView(
viewId: view.id,
name: e.newName,
);
emit(
result.fold(
(l) {
final view = state.view;
view.freeze();
final newView = view.rebuild(
(b) => b.name = e.newName,
);
return state.copyWith(
successOrFailure: FlowyResult.success(null),
view: newView,
);
},
(error) => state.copyWith(
successOrFailure: FlowyResult.failure(error),
),
),
);
},
delete: (e) async {
final result = await ViewBackendService.delete(viewId: view.id);
emit(
result.fold(
(l) =>
state.copyWith(successOrFailure: FlowyResult.success(null)),
(error) => state.copyWith(
successOrFailure: FlowyResult.failure(error),
),
),
);
await RecentService().updateRecentViews([view.id], false);
},
duplicate: (e) async {
final result = await ViewBackendService.duplicate(view: view);
emit(
result.fold(
(l) =>
state.copyWith(successOrFailure: FlowyResult.success(null)),
(error) => state.copyWith(
successOrFailure: FlowyResult.failure(error),
),
),
);
},
move: (value) async {
final result = await ViewBackendService.moveViewV2(
viewId: value.from.id,
newParentId: value.newParentId,
prevViewId: value.prevId,
fromSection: value.fromSection,
toSection: value.toSection,
);
emit(
result.fold(
(l) =>
state.copyWith(successOrFailure: FlowyResult.success(null)),
(error) => state.copyWith(
successOrFailure: FlowyResult.failure(error),
),
),
);
},
createView: (e) async {
final result = await ViewBackendService.createView(
parentViewId: view.id,
name: e.name,
desc: '',
layoutType: e.layoutType,
ext: {},
openAfterCreate: e.openAfterCreated,
section: e.section,
);
emit(
result.fold(
(view) => state.copyWith(
lastCreatedView: view,
successOrFailure: FlowyResult.success(null),
),
(error) => state.copyWith(
successOrFailure: FlowyResult.failure(error),
),
),
);
},
viewUpdateChildView: (e) async {
emit(
state.copyWith(
view: e.result,
),
);
},
updateViewVisibility: (value) async {
final view = value.view;
await ViewBackendService.updateViewsVisibility(
[view],
value.isPublic,
);
},
);
},
);
}
Future<void> _loadViewsWhenExpanded(
Emitter<ViewState> emit,
bool isExpanded,
) async {
if (!isExpanded) {
emit(
state.copyWith(
view: view,
isExpanded: false,
isLoading: false,
),
);
return;
}
final viewsOrFailed =
await ViewBackendService.getChildViews(viewId: state.view.id);
viewsOrFailed.fold(
(childViews) {
state.view.freeze();
final viewWithChildViews = state.view.rebuild((b) {
b.childViews.clear();
b.childViews.addAll(childViews);
});
emit(
state.copyWith(
view: viewWithChildViews,
isExpanded: true,
isLoading: false,
),
);
},
(error) => emit(
state.copyWith(
successOrFailure: FlowyResult.failure(error),
isExpanded: true,
isLoading: false,
),
),
);
}
Future<void> _setViewIsExpanded(ViewPB view, bool isExpanded) async {
final result = await getIt<KeyValueStorage>().get(KVKeys.expandedViews);
final Map map;
if (result != null) {
map = jsonDecode(result);
} else {
map = {};
}
if (isExpanded) {
map[view.id] = true;
} else {
map.remove(view.id);
}
await getIt<KeyValueStorage>().set(KVKeys.expandedViews, jsonEncode(map));
}
Future<bool> _getViewIsExpanded(ViewPB view) {
return getIt<KeyValueStorage>().get(KVKeys.expandedViews).then((result) {
if (result == null) {
return false;
}
final map = jsonDecode(result);
return map[view.id] ?? false;
});
}
Future<ViewPB?> _updateChildViews(
ChildViewUpdatePB update,
) async {
if (update.createChildViews.isNotEmpty) {
// refresh the child views if the update isn't empty
// because there's no info to get the inserted index.
assert(update.parentViewId == this.view.id);
final view = await ViewBackendService.getView(
update.parentViewId,
);
return view.fold((l) => l, (r) => null);
}
final view = state.view;
view.freeze();
final childViews = [...view.childViews];
if (update.deleteChildViews.isNotEmpty) {
childViews.removeWhere((v) => update.deleteChildViews.contains(v.id));
return view.rebuild((p0) {
p0.childViews.clear();
p0.childViews.addAll(childViews);
});
}
if (update.updateChildViews.isNotEmpty) {
final view = await ViewBackendService.getView(
update.parentViewId,
);
final childViews = view.fold((l) => l.childViews, (r) => []);
bool isSameOrder = true;
if (childViews.length == update.updateChildViews.length) {
for (var i = 0; i < childViews.length; i++) {
if (childViews[i].id != update.updateChildViews[i].id) {
isSameOrder = false;
break;
}
}
} else {
isSameOrder = false;
}
if (!isSameOrder) {
return view.fold((l) => l, (r) => null);
}
}
return null;
}
bool _isSameViewIgnoreChildren(ViewPB from, ViewPB to) {
return _hash(from) == _hash(to);
}
int _hash(ViewPB view) => Object.hash(
view.id,
view.name,
view.createTime,
view.icon,
view.parentViewId,
view.layout,
);
}
@freezed
class ViewEvent with _$ViewEvent {
const factory ViewEvent.initial() = Initial;
const factory ViewEvent.setIsEditing(bool isEditing) = SetEditing;
const factory ViewEvent.setIsExpanded(bool isExpanded) = SetIsExpanded;
const factory ViewEvent.rename(String newName) = Rename;
const factory ViewEvent.delete() = Delete;
const factory ViewEvent.duplicate() = Duplicate;
const factory ViewEvent.move(
ViewPB from,
String newParentId,
String? prevId,
ViewSectionPB? fromSection,
ViewSectionPB? toSection,
) = Move;
const factory ViewEvent.createView(
String name,
ViewLayoutPB layoutType, {
/// open the view after created
@Default(true) bool openAfterCreated,
ViewSectionPB? section,
}) = CreateView;
const factory ViewEvent.viewDidUpdate(
FlowyResult<ViewPB, FlowyError> result,
) = ViewDidUpdate;
const factory ViewEvent.viewUpdateChildView(ViewPB result) =
ViewUpdateChildView;
const factory ViewEvent.updateViewVisibility(ViewPB view, bool isPublic) =
UpdateViewVisibility;
}
@freezed
class ViewState with _$ViewState {
const factory ViewState({
required ViewPB view,
required bool isEditing,
required bool isExpanded,
required FlowyResult<void, FlowyError> successOrFailure,
@Default(true) bool isLoading,
@Default(null) ViewPB? lastCreatedView,
}) = _ViewState;
factory ViewState.init(ViewPB view) => ViewState(
view: view,
isExpanded: false,
isEditing: false,
successOrFailure: FlowyResult.success(null),
);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/view/view_listener.dart | import 'dart:async';
import 'dart:typed_data';
import 'package:appflowy/core/notification/folder_notification.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/notification.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-notification/subject.pb.dart';
import 'package:appflowy_backend/rust_stream.dart';
import 'package:appflowy_result/appflowy_result.dart';
// Delete the view from trash, which means the view was deleted permanently
typedef DeleteViewNotifyValue = FlowyResult<ViewPB, FlowyError>;
// The view get updated
typedef UpdateViewNotifiedValue = ViewPB;
// Restore the view from trash
typedef RestoreViewNotifiedValue = FlowyResult<ViewPB, FlowyError>;
// Move the view to trash
typedef MoveToTrashNotifiedValue = FlowyResult<DeletedViewPB, FlowyError>;
class ViewListener {
ViewListener({required this.viewId});
StreamSubscription<SubscribeObject>? _subscription;
void Function(UpdateViewNotifiedValue)? _updatedViewNotifier;
void Function(ChildViewUpdatePB)? _updateViewChildViewsNotifier;
void Function(DeleteViewNotifyValue)? _deletedNotifier;
void Function(RestoreViewNotifiedValue)? _restoredNotifier;
void Function(MoveToTrashNotifiedValue)? _moveToTrashNotifier;
bool _isDisposed = false;
FolderNotificationParser? _parser;
final String viewId;
void start({
void Function(UpdateViewNotifiedValue)? onViewUpdated,
void Function(ChildViewUpdatePB)? onViewChildViewsUpdated,
void Function(DeleteViewNotifyValue)? onViewDeleted,
void Function(RestoreViewNotifiedValue)? onViewRestored,
void Function(MoveToTrashNotifiedValue)? onViewMoveToTrash,
}) {
if (_isDisposed) {
Log.warn("ViewListener is already disposed");
return;
}
_updatedViewNotifier = onViewUpdated;
_deletedNotifier = onViewDeleted;
_restoredNotifier = onViewRestored;
_moveToTrashNotifier = onViewMoveToTrash;
_updateViewChildViewsNotifier = onViewChildViewsUpdated;
_parser = FolderNotificationParser(
id: viewId,
callback: (ty, result) {
_handleObservableType(ty, result);
},
);
_subscription =
RustStreamReceiver.listen((observable) => _parser?.parse(observable));
}
void _handleObservableType(
FolderNotification ty,
FlowyResult<Uint8List, FlowyError> result,
) {
switch (ty) {
case FolderNotification.DidUpdateView:
result.fold(
(payload) {
final view = ViewPB.fromBuffer(payload);
_updatedViewNotifier?.call(view);
},
(error) => Log.error(error),
);
break;
case FolderNotification.DidUpdateChildViews:
result.fold(
(payload) {
final pb = ChildViewUpdatePB.fromBuffer(payload);
_updateViewChildViewsNotifier?.call(pb);
},
(error) => Log.error(error),
);
break;
case FolderNotification.DidDeleteView:
result.fold(
(payload) => _deletedNotifier
?.call(FlowyResult.success(ViewPB.fromBuffer(payload))),
(error) => _deletedNotifier?.call(FlowyResult.failure(error)),
);
break;
case FolderNotification.DidRestoreView:
result.fold(
(payload) => _restoredNotifier
?.call(FlowyResult.success(ViewPB.fromBuffer(payload))),
(error) => _restoredNotifier?.call(FlowyResult.failure(error)),
);
break;
case FolderNotification.DidMoveViewToTrash:
result.fold(
(payload) => _moveToTrashNotifier
?.call(FlowyResult.success(DeletedViewPB.fromBuffer(payload))),
(error) => _moveToTrashNotifier?.call(FlowyResult.failure(error)),
);
break;
default:
break;
}
}
Future<void> stop() async {
_isDisposed = true;
_parser = null;
await _subscription?.cancel();
_updatedViewNotifier = null;
_deletedNotifier = null;
_restoredNotifier = null;
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/view/view_ext.dart | import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy/plugins/database/board/presentation/board_page.dart';
import 'package:appflowy/plugins/database/calendar/presentation/calendar_page.dart';
import 'package:appflowy/plugins/database/grid/presentation/grid_page.dart';
import 'package:appflowy/plugins/database/grid/presentation/mobile_grid_page.dart';
import 'package:appflowy/plugins/database/tab_bar/tab_bar_view.dart';
import 'package:appflowy/plugins/document/document.dart';
import 'package:appflowy/startup/plugin/plugin.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:flutter/material.dart';
enum FlowyPlugin {
editor,
kanban,
}
class PluginArgumentKeys {
static String selection = "selection";
static String rowId = "row_id";
}
extension ViewExtension on ViewPB {
Widget defaultIcon() => FlowySvg(
switch (layout) {
ViewLayoutPB.Board => FlowySvgs.board_s,
ViewLayoutPB.Calendar => FlowySvgs.date_s,
ViewLayoutPB.Grid => FlowySvgs.grid_s,
ViewLayoutPB.Document => FlowySvgs.document_s,
_ => FlowySvgs.document_s,
},
);
PluginType get pluginType => switch (layout) {
ViewLayoutPB.Board => PluginType.board,
ViewLayoutPB.Calendar => PluginType.calendar,
ViewLayoutPB.Document => PluginType.editor,
ViewLayoutPB.Grid => PluginType.grid,
_ => throw UnimplementedError(),
};
Plugin plugin({
Map<String, dynamic> arguments = const {},
}) {
switch (layout) {
case ViewLayoutPB.Board:
case ViewLayoutPB.Calendar:
case ViewLayoutPB.Grid:
final String? rowId = arguments[PluginArgumentKeys.rowId];
return DatabaseTabBarViewPlugin(
view: this,
pluginType: pluginType,
initialRowId: rowId,
);
case ViewLayoutPB.Document:
final Selection? initialSelection =
arguments[PluginArgumentKeys.selection];
return DocumentPlugin(
view: this,
pluginType: pluginType,
initialSelection: initialSelection,
);
}
throw UnimplementedError;
}
DatabaseTabBarItemBuilder tabBarItem() => switch (layout) {
ViewLayoutPB.Board => BoardPageTabBarBuilderImpl(),
ViewLayoutPB.Calendar => CalendarPageTabBarBuilderImpl(),
ViewLayoutPB.Grid => DesktopGridTabBarBuilderImpl(),
_ => throw UnimplementedError,
};
DatabaseTabBarItemBuilder mobileTabBarItem() => switch (layout) {
ViewLayoutPB.Board => BoardPageTabBarBuilderImpl(),
ViewLayoutPB.Calendar => CalendarPageTabBarBuilderImpl(),
ViewLayoutPB.Grid => MobileGridTabBarBuilderImpl(),
_ => throw UnimplementedError,
};
FlowySvgData get iconData => layout.icon;
}
extension ViewLayoutExtension on ViewLayoutPB {
FlowySvgData get icon => switch (this) {
ViewLayoutPB.Grid => FlowySvgs.grid_s,
ViewLayoutPB.Board => FlowySvgs.board_s,
ViewLayoutPB.Calendar => FlowySvgs.date_s,
ViewLayoutPB.Document => FlowySvgs.document_s,
_ => throw Exception('Unknown layout type'),
};
bool get isDatabaseView => switch (this) {
ViewLayoutPB.Grid ||
ViewLayoutPB.Board ||
ViewLayoutPB.Calendar =>
true,
ViewLayoutPB.Document => false,
_ => throw Exception('Unknown layout type'),
};
}
extension ViewFinder on List<ViewPB> {
ViewPB? findView(String id) {
for (final view in this) {
if (view.id == id) {
return view;
}
if (view.childViews.isNotEmpty) {
final v = view.childViews.findView(id);
if (v != null) {
return v;
}
}
}
return null;
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/export/document_exporter.dart | import 'dart:convert';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/plugins/document/application/document_data_pb_extension.dart';
import 'package:appflowy/plugins/document/application/prelude.dart';
import 'package:appflowy/plugins/document/presentation/editor_plugins/parsers/document_markdown_parsers.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:easy_localization/easy_localization.dart';
const List<NodeParser> _customParsers = [
MathEquationNodeParser(),
CalloutNodeParser(),
ToggleListNodeParser(),
CustomImageNodeParser(),
];
enum DocumentExportType {
json,
markdown,
text,
html,
}
class DocumentExporter {
const DocumentExporter(
this.view,
);
final ViewPB view;
Future<FlowyResult<String, FlowyError>> export(
DocumentExportType type,
) async {
final documentService = DocumentService();
final result = await documentService.openDocument(viewId: view.id);
return result.fold(
(r) {
final document = r.toDocument();
if (document == null) {
return FlowyResult.failure(
FlowyError(
msg: LocaleKeys.settings_files_exportFileFail.tr(),
),
);
}
switch (type) {
case DocumentExportType.json:
return FlowyResult.success(jsonEncode(document));
case DocumentExportType.markdown:
final markdown = documentToMarkdown(
document,
customParsers: _customParsers,
);
return FlowyResult.success(markdown);
case DocumentExportType.text:
throw UnimplementedError();
case DocumentExportType.html:
final html = documentToHTML(
document,
);
return FlowyResult.success(html);
}
},
(error) => FlowyResult.failure(error),
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/sidebar | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/sidebar/rename_view/rename_view_bloc.dart | import 'package:appflowy_popover/appflowy_popover.dart';
import 'package:bloc/bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'rename_view_bloc.freezed.dart';
class RenameViewBloc extends Bloc<RenameViewEvent, RenameViewState> {
RenameViewBloc(PopoverController controller)
: _controller = controller,
super(RenameViewState(controller: controller)) {
on<RenameViewEvent>((event, emit) {
event.when(
open: () => _controller.show(),
);
});
}
final PopoverController _controller;
@override
Future<void> close() async {
_controller.close();
await super.close();
}
}
@freezed
class RenameViewEvent with _$RenameViewEvent {
const factory RenameViewEvent.open() = _Open;
}
@freezed
class RenameViewState with _$RenameViewState {
const factory RenameViewState({
required PopoverController controller,
}) = _RenameViewState;
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/sidebar | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/sidebar/folder/folder_bloc.dart | import 'dart:convert';
import 'package:appflowy/core/config/kv.dart';
import 'package:appflowy/core/config/kv_keys.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'folder_bloc.freezed.dart';
enum FolderCategoryType {
favorite,
private,
public;
ViewSectionPB get toViewSectionPB {
switch (this) {
case FolderCategoryType.private:
return ViewSectionPB.Private;
case FolderCategoryType.public:
return ViewSectionPB.Public;
case FolderCategoryType.favorite:
throw UnimplementedError();
}
}
}
class FolderBloc extends Bloc<FolderEvent, FolderState> {
FolderBloc({
required FolderCategoryType type,
}) : super(FolderState.initial(type)) {
on<FolderEvent>((event, emit) async {
await event.map(
initial: (e) async {
// fetch the expand status
final isExpanded = await _getFolderExpandStatus();
emit(state.copyWith(isExpanded: isExpanded));
},
expandOrUnExpand: (e) async {
final isExpanded = e.isExpanded ?? !state.isExpanded;
await _setFolderExpandStatus(e.isExpanded ?? !state.isExpanded);
emit(state.copyWith(isExpanded: isExpanded));
},
);
});
}
Future<void> _setFolderExpandStatus(bool isExpanded) async {
final result = await getIt<KeyValueStorage>().get(KVKeys.expandedViews);
var map = {};
if (result != null) {
map = jsonDecode(result);
}
if (isExpanded) {
// set expand status to true if it's not expanded
map[state.type.name] = true;
} else {
// remove the expand status if it's expanded
map.remove(state.type.name);
}
await getIt<KeyValueStorage>().set(KVKeys.expandedViews, jsonEncode(map));
}
Future<bool> _getFolderExpandStatus() async {
return getIt<KeyValueStorage>().get(KVKeys.expandedViews).then((result) {
if (result == null) {
return true;
}
final map = jsonDecode(result);
return map[state.type.name] ?? true;
});
}
}
@freezed
class FolderEvent with _$FolderEvent {
const factory FolderEvent.initial() = Initial;
const factory FolderEvent.expandOrUnExpand({
bool? isExpanded,
}) = ExpandOrUnExpand;
}
@freezed
class FolderState with _$FolderState {
const factory FolderState({
required FolderCategoryType type,
required bool isExpanded,
}) = _FolderState;
factory FolderState.initial(
FolderCategoryType type,
) =>
FolderState(
type: type,
isExpanded: true,
);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/tabs/tabs_state.dart | part of 'tabs_bloc.dart';
class TabsState {
TabsState({
this.currentIndex = 0,
List<PageManager>? pageManagers,
}) : _pageManagers = pageManagers ?? [PageManager()];
final int currentIndex;
final List<PageManager> _pageManagers;
int get pages => _pageManagers.length;
PageManager get currentPageManager => _pageManagers[currentIndex];
List<PageManager> get pageManagers => _pageManagers;
/// This opens a new tab given a [Plugin] and a [View].
///
/// If the [Plugin.id] is already associated with an open tab,
/// then it selects that tab.
///
TabsState openView(Plugin plugin, ViewPB view) {
final selectExistingPlugin = _selectPluginIfOpen(plugin.id);
if (selectExistingPlugin == null) {
_pageManagers.add(PageManager()..setPlugin(plugin));
return copyWith(newIndex: pages - 1, pageManagers: [..._pageManagers]);
}
return selectExistingPlugin;
}
TabsState closeView(String pluginId) {
// Avoid closing the only open tab
if (_pageManagers.length == 1) {
return this;
}
_pageManagers.removeWhere((pm) => pm.plugin.id == pluginId);
/// If currentIndex is greater than the amount of allowed indices
/// And the current selected tab isn't the first (index 0)
/// as currentIndex cannot be -1
/// Then decrease currentIndex by 1
final newIndex = currentIndex > pages - 1 && currentIndex > 0
? currentIndex - 1
: currentIndex;
return copyWith(
newIndex: newIndex,
pageManagers: [..._pageManagers],
);
}
/// This opens a plugin in the current selected tab,
/// due to how Document currently works, only one tab
/// per plugin can currently be active.
///
/// If the plugin is already open in a tab, then that tab
/// will become selected.
///
TabsState openPlugin({required Plugin plugin}) {
final selectExistingPlugin = _selectPluginIfOpen(plugin.id);
if (selectExistingPlugin == null) {
final pageManagers = [..._pageManagers];
pageManagers[currentIndex].setPlugin(plugin);
return copyWith(pageManagers: pageManagers);
}
return selectExistingPlugin;
}
/// Checks if a [Plugin.id] is already associated with an open tab.
/// Returns a [TabState] with new index if there is a match.
///
/// If no match it returns null
///
TabsState? _selectPluginIfOpen(String id) {
final index = _pageManagers.indexWhere((pm) => pm.plugin.id == id);
if (index == -1) {
return null;
}
if (index == currentIndex) {
return this;
}
return copyWith(newIndex: index);
}
TabsState copyWith({
int? newIndex,
List<PageManager>? pageManagers,
}) =>
TabsState(
currentIndex: newIndex ?? currentIndex,
pageManagers: pageManagers ?? _pageManagers,
);
void dispose() {
for (final manager in pageManagers) {
manager.dispose();
}
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/tabs/tabs_event.dart | part of 'tabs_bloc.dart';
@freezed
class TabsEvent with _$TabsEvent {
const factory TabsEvent.moveTab() = _MoveTab;
const factory TabsEvent.closeTab(String pluginId) = _CloseTab;
const factory TabsEvent.closeCurrentTab() = _CloseCurrentTab;
const factory TabsEvent.selectTab(int index) = _SelectTab;
const factory TabsEvent.openTab({
required Plugin plugin,
required ViewPB view,
}) = _OpenTab;
const factory TabsEvent.openPlugin({required Plugin plugin, ViewPB? view}) =
_OpenPlugin;
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/tabs/tabs_bloc.dart | import 'package:appflowy/plugins/util.dart';
import 'package:appflowy/startup/plugin/plugin.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/workspace/application/view/view_ext.dart';
import 'package:appflowy/workspace/presentation/home/home_stack.dart';
import 'package:appflowy/workspace/presentation/home/menu/menu_shared_state.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:bloc/bloc.dart';
import 'package:flutter/foundation.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'tabs_bloc.freezed.dart';
part 'tabs_event.dart';
part 'tabs_state.dart';
class TabsBloc extends Bloc<TabsEvent, TabsState> {
TabsBloc() : super(TabsState()) {
menuSharedState = getIt<MenuSharedState>();
_dispatch();
}
late final MenuSharedState menuSharedState;
@override
Future<void> close() {
state.dispose();
return super.close();
}
void _dispatch() {
on<TabsEvent>(
(event, emit) async {
event.when(
selectTab: (int index) {
if (index != state.currentIndex &&
index >= 0 &&
index < state.pages) {
emit(state.copyWith(newIndex: index));
_setLatestOpenView();
}
},
moveTab: () {},
closeTab: (String pluginId) {
emit(state.closeView(pluginId));
_setLatestOpenView();
},
closeCurrentTab: () {
emit(state.closeView(state.currentPageManager.plugin.id));
_setLatestOpenView();
},
openTab: (Plugin plugin, ViewPB view) {
emit(state.openView(plugin, view));
_setLatestOpenView(view);
},
openPlugin: (Plugin plugin, ViewPB? view) {
emit(state.openPlugin(plugin: plugin));
_setLatestOpenView(view);
},
);
},
);
}
void _setLatestOpenView([ViewPB? view]) {
if (view != null) {
menuSharedState.latestOpenView = view;
} else {
final pageManager = state.currentPageManager;
final notifier = pageManager.plugin.notifier;
if (notifier is ViewPluginNotifier) {
menuSharedState.latestOpenView = notifier.view;
}
}
}
/// Adds a [TabsEvent.openTab] event for the provided [ViewPB]
void openTab(ViewPB view) =>
add(TabsEvent.openTab(plugin: view.plugin(), view: view));
/// Adds a [TabsEvent.openPlugin] event for the provided [ViewPB]
void openPlugin(
ViewPB view, {
Map<String, dynamic> arguments = const {},
}) =>
add(
TabsEvent.openPlugin(
plugin: view.plugin(arguments: arguments),
view: view,
),
);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/workspace/workspace_bloc.dart | import 'package:appflowy/user/application/user_service.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/workspace.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'workspace_bloc.freezed.dart';
class WorkspaceBloc extends Bloc<WorkspaceEvent, WorkspaceState> {
WorkspaceBloc({required this.userService}) : super(WorkspaceState.initial()) {
_dispatch();
}
final UserBackendService userService;
void _dispatch() {
on<WorkspaceEvent>(
(event, emit) async {
await event.map(
initial: (e) async {
await _fetchWorkspaces(emit);
},
createWorkspace: (e) async {
await _createWorkspace(e.name, e.desc, emit);
},
workspacesReceived: (e) async {
emit(
e.workspacesOrFail.fold(
(workspaces) => state.copyWith(
workspaces: workspaces,
successOrFailure: FlowyResult.success(null),
),
(error) => state.copyWith(
successOrFailure: FlowyResult.failure(error),
),
),
);
},
);
},
);
}
Future<void> _fetchWorkspaces(Emitter<WorkspaceState> emit) async {
final workspacesOrFailed = await userService.getWorkspaces();
emit(
workspacesOrFailed.fold(
(workspaces) => state.copyWith(
workspaces: [],
successOrFailure: FlowyResult.success(null),
),
(error) {
Log.error(error);
return state.copyWith(successOrFailure: FlowyResult.failure(error));
},
),
);
}
Future<void> _createWorkspace(
String name,
String desc,
Emitter<WorkspaceState> emit,
) async {
final result = await userService.createWorkspace(name, desc);
emit(
result.fold(
(workspace) {
return state.copyWith(successOrFailure: FlowyResult.success(null));
},
(error) {
Log.error(error);
return state.copyWith(successOrFailure: FlowyResult.failure(error));
},
),
);
}
}
@freezed
class WorkspaceEvent with _$WorkspaceEvent {
const factory WorkspaceEvent.initial() = Initial;
const factory WorkspaceEvent.createWorkspace(String name, String desc) =
CreateWorkspace;
const factory WorkspaceEvent.workspacesReceived(
FlowyResult<List<WorkspacePB>, FlowyError> workspacesOrFail,
) = WorkspacesReceived;
}
@freezed
class WorkspaceState with _$WorkspaceState {
const factory WorkspaceState({
required bool isLoading,
required List<WorkspacePB> workspaces,
required FlowyResult<void, FlowyError> successOrFailure,
}) = _WorkspaceState;
factory WorkspaceState.initial() => WorkspaceState(
isLoading: false,
workspaces: List.empty(),
successOrFailure: FlowyResult.success(null),
);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/workspace/prelude.dart | export 'workspace_bloc.dart';
export 'workspace_listener.dart';
export 'workspace_service.dart';
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/workspace/workspace_listener.dart | import 'dart:async';
import 'dart:typed_data';
import 'package:appflowy/core/notification/folder_notification.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/notification.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/workspace.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart'
show UserProfilePB;
import 'package:appflowy_result/appflowy_result.dart';
import 'package:flowy_infra/notifier.dart';
typedef RootViewsNotifyValue = FlowyResult<List<ViewPB>, FlowyError>;
typedef WorkspaceNotifyValue = FlowyResult<WorkspacePB, FlowyError>;
/// The [WorkspaceListener] listens to the changes including the below:
///
/// - The root views of the workspace. (Not including the views are inside the root views)
/// - The workspace itself.
class WorkspaceListener {
WorkspaceListener({required this.user, required this.workspaceId});
final UserProfilePB user;
final String workspaceId;
PublishNotifier<RootViewsNotifyValue>? _appsChangedNotifier =
PublishNotifier();
PublishNotifier<WorkspaceNotifyValue>? _workspaceUpdatedNotifier =
PublishNotifier();
FolderNotificationListener? _listener;
void start({
void Function(RootViewsNotifyValue)? appsChanged,
void Function(WorkspaceNotifyValue)? onWorkspaceUpdated,
}) {
if (appsChanged != null) {
_appsChangedNotifier?.addPublishListener(appsChanged);
}
if (onWorkspaceUpdated != null) {
_workspaceUpdatedNotifier?.addPublishListener(onWorkspaceUpdated);
}
_listener = FolderNotificationListener(
objectId: workspaceId,
handler: _handleObservableType,
);
}
void _handleObservableType(
FolderNotification ty,
FlowyResult<Uint8List, FlowyError> result,
) {
switch (ty) {
case FolderNotification.DidUpdateWorkspace:
result.fold(
(payload) => _workspaceUpdatedNotifier?.value =
FlowyResult.success(WorkspacePB.fromBuffer(payload)),
(error) =>
_workspaceUpdatedNotifier?.value = FlowyResult.failure(error),
);
break;
case FolderNotification.DidUpdateWorkspaceViews:
result.fold(
(payload) => _appsChangedNotifier?.value =
FlowyResult.success(RepeatedViewPB.fromBuffer(payload).items),
(error) => _appsChangedNotifier?.value = FlowyResult.failure(error),
);
break;
default:
break;
}
}
Future<void> stop() async {
await _listener?.stop();
_appsChangedNotifier?.dispose();
_appsChangedNotifier = null;
_workspaceUpdatedNotifier?.dispose();
_workspaceUpdatedNotifier = null;
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/workspace/workspace_service.dart | import 'dart:async';
import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/protobuf.dart';
import 'package:appflowy_result/appflowy_result.dart';
class WorkspaceService {
WorkspaceService({required this.workspaceId});
final String workspaceId;
Future<FlowyResult<ViewPB, FlowyError>> createView({
required String name,
required ViewSectionPB viewSection,
String? desc,
int? index,
}) {
final payload = CreateViewPayloadPB.create()
..parentViewId = workspaceId
..name = name
// only allow document layout for the top-level views
..layout = ViewLayoutPB.Document
..section = viewSection;
if (desc != null) {
payload.desc = desc;
}
if (index != null) {
payload.index = index;
}
return FolderEventCreateView(payload).send();
}
Future<FlowyResult<WorkspacePB, FlowyError>> getWorkspace() {
return FolderEventReadCurrentWorkspace().send();
}
Future<FlowyResult<List<ViewPB>, FlowyError>> getPublicViews() {
final payload = GetWorkspaceViewPB.create()..value = workspaceId;
return FolderEventReadWorkspaceViews(payload).send().then((result) {
return result.fold(
(views) => FlowyResult.success(views.items),
(error) => FlowyResult.failure(error),
);
});
}
Future<FlowyResult<List<ViewPB>, FlowyError>> getPrivateViews() {
final payload = GetWorkspaceViewPB.create()..value = workspaceId;
return FolderEventReadPrivateViews(payload).send().then((result) {
return result.fold(
(views) => FlowyResult.success(views.items),
(error) => FlowyResult.failure(error),
);
});
}
Future<FlowyResult<void, FlowyError>> moveView({
required String viewId,
required int fromIndex,
required int toIndex,
}) {
final payload = MoveViewPayloadPB.create()
..viewId = viewId
..from = fromIndex
..to = toIndex;
return FolderEventMoveView(payload).send();
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/workspace/workspace_sections_listener.dart | import 'dart:async';
import 'dart:typed_data';
import 'package:appflowy/core/notification/folder_notification.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/notification.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart'
show UserProfilePB;
import 'package:appflowy_result/appflowy_result.dart';
import 'package:flowy_infra/notifier.dart';
typedef SectionNotifyValue = FlowyResult<SectionViewsPB, FlowyError>;
/// The [WorkspaceSectionsListener] listens to the changes including the below:
///
/// - The root views inside different section of the workspace. (Not including the views are inside the root views)
/// depends on the section type(s).
class WorkspaceSectionsListener {
WorkspaceSectionsListener({
required this.user,
required this.workspaceId,
});
final UserProfilePB user;
final String workspaceId;
final _sectionNotifier = PublishNotifier<SectionNotifyValue>();
late final FolderNotificationListener _listener;
void start({
void Function(SectionNotifyValue)? sectionChanged,
}) {
if (sectionChanged != null) {
_sectionNotifier.addPublishListener(sectionChanged);
}
_listener = FolderNotificationListener(
objectId: workspaceId,
handler: _handleObservableType,
);
}
void _handleObservableType(
FolderNotification ty,
FlowyResult<Uint8List, FlowyError> result,
) {
switch (ty) {
case FolderNotification.DidUpdateSectionViews:
final FlowyResult<SectionViewsPB, FlowyError> value = result.fold(
(s) => FlowyResult.success(
SectionViewsPB.fromBuffer(s),
),
(f) => FlowyResult.failure(f),
);
_sectionNotifier.value = value;
break;
default:
break;
}
}
Future<void> stop() async {
_sectionNotifier.dispose();
await _listener.stop();
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/command_palette/search_listener.dart | import 'dart:async';
import 'dart:typed_data';
import 'package:appflowy/core/notification/search_notification.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-search/entities.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:flowy_infra/notifier.dart';
// Do not modify!
const _searchObjectId = "SEARCH_IDENTIFIER";
class SearchListener {
SearchListener();
PublishNotifier<RepeatedSearchResultPB>? _updateNotifier = PublishNotifier();
PublishNotifier<RepeatedSearchResultPB>? _updateDidCloseNotifier =
PublishNotifier();
SearchNotificationListener? _listener;
void start({
required void Function(RepeatedSearchResultPB) onResultsChanged,
required void Function(RepeatedSearchResultPB) onResultsClosed,
}) {
_updateNotifier?.addPublishListener(onResultsChanged);
_updateDidCloseNotifier?.addPublishListener(onResultsClosed);
_listener = SearchNotificationListener(
objectId: _searchObjectId,
handler: _handler,
);
}
void _handler(
SearchNotification ty,
FlowyResult<Uint8List, FlowyError> result,
) {
switch (ty) {
case SearchNotification.DidUpdateResults:
result.fold(
(payload) => _updateNotifier?.value =
RepeatedSearchResultPB.fromBuffer(payload),
(err) => Log.error(err),
);
break;
case SearchNotification.DidCloseResults:
result.fold(
(payload) => _updateDidCloseNotifier?.value =
RepeatedSearchResultPB.fromBuffer(payload),
(err) => Log.error(err),
);
break;
default:
break;
}
}
Future<void> stop() async {
await _listener?.stop();
_updateNotifier?.dispose();
_updateNotifier = null;
_updateDidCloseNotifier?.dispose();
_updateDidCloseNotifier = null;
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/command_palette/search_result_ext.dart | import 'package:flutter/material.dart';
import 'package:appflowy/generated/flowy_svgs.g.dart';
import 'package:appflowy_backend/protobuf/flowy-search/entities.pb.dart';
extension GetIcon on SearchResultPB {
Widget? getIcon() {
if (icon.ty == ResultIconTypePB.Emoji) {
return icon.value.isNotEmpty
? Text(
icon.value,
style: const TextStyle(fontSize: 18.0),
)
: null;
} else if (icon.ty == ResultIconTypePB.Icon) {
return FlowySvg(icon.getViewSvg(), size: const Size.square(20));
}
return null;
}
}
extension _ToViewIcon on ResultIconPB {
FlowySvgData getViewSvg() => switch (value) {
"0" => FlowySvgs.document_s,
"1" => FlowySvgs.grid_s,
"2" => FlowySvgs.board_s,
"3" => FlowySvgs.date_s,
_ => FlowySvgs.document_s,
};
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/command_palette/command_palette_bloc.dart | import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:appflowy/plugins/trash/application/trash_listener.dart';
import 'package:appflowy/plugins/trash/application/trash_service.dart';
import 'package:appflowy/workspace/application/command_palette/search_listener.dart';
import 'package:appflowy/workspace/application/command_palette/search_service.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/trash.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-search/entities.pb.dart';
import 'package:bloc/bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'command_palette_bloc.freezed.dart';
class CommandPaletteBloc
extends Bloc<CommandPaletteEvent, CommandPaletteState> {
CommandPaletteBloc() : super(CommandPaletteState.initial()) {
_searchListener.start(
onResultsChanged: _onResultsChanged,
onResultsClosed: _onResultsClosed,
);
_initTrash();
_dispatch();
}
Timer? _debounceOnChanged;
final TrashService _trashService = TrashService();
final SearchListener _searchListener = SearchListener();
final TrashListener _trashListener = TrashListener();
String? _oldQuery;
@override
Future<void> close() {
_trashListener.close();
_searchListener.stop();
return super.close();
}
void _dispatch() {
on<CommandPaletteEvent>((event, emit) async {
event.when(
searchChanged: _debounceOnSearchChanged,
trashChanged: (trash) async {
if (trash != null) {
emit(state.copyWith(trash: trash));
return;
}
final trashOrFailure = await _trashService.readTrash();
final trashRes = trashOrFailure.fold(
(trash) => trash,
(error) => null,
);
if (trashRes != null) {
emit(state.copyWith(trash: trashRes.items));
}
},
performSearch: (search) async {
if (search.isNotEmpty) {
_oldQuery = state.query;
emit(state.copyWith(query: search, isLoading: true));
await SearchBackendService.performSearch(search);
} else {
emit(state.copyWith(query: null, isLoading: false, results: []));
}
},
resultsChanged: (results, didClose) {
if (state.query != _oldQuery) {
emit(state.copyWith(results: []));
}
final searchResults = _filterDuplicates(results.items);
searchResults.sort((a, b) => b.score.compareTo(a.score));
emit(
state.copyWith(
results: searchResults,
isLoading: !didClose,
),
);
},
);
});
}
Future<void> _initTrash() async {
_trashListener.start(
trashUpdated: (trashOrFailed) {
final trash = trashOrFailed.fold(
(trash) => trash,
(error) => null,
);
add(CommandPaletteEvent.trashChanged(trash: trash));
},
);
final trashOrFailure = await _trashService.readTrash();
final trashRes = trashOrFailure.fold(
(trash) => trash,
(error) => null,
);
add(CommandPaletteEvent.trashChanged(trash: trashRes?.items));
}
void _debounceOnSearchChanged(String value) {
_debounceOnChanged?.cancel();
_debounceOnChanged = Timer(
const Duration(milliseconds: 300),
() => _performSearch(value),
);
}
List<SearchResultPB> _filterDuplicates(List<SearchResultPB> results) {
final currentItems = [...state.results];
final res = [...results];
for (final item in results) {
final duplicateIndex = currentItems.indexWhere((a) => a.id == item.id);
if (duplicateIndex == -1) {
continue;
}
final duplicate = currentItems[duplicateIndex];
if (item.score < duplicate.score) {
res.remove(item);
} else {
currentItems.remove(duplicate);
}
}
return res..addAll(currentItems);
}
void _performSearch(String value) =>
add(CommandPaletteEvent.performSearch(search: value));
void _onResultsChanged(RepeatedSearchResultPB results) =>
add(CommandPaletteEvent.resultsChanged(results: results));
void _onResultsClosed(RepeatedSearchResultPB results) =>
add(CommandPaletteEvent.resultsChanged(results: results, didClose: true));
}
@freezed
class CommandPaletteEvent with _$CommandPaletteEvent {
const factory CommandPaletteEvent.searchChanged({required String search}) =
_SearchChanged;
const factory CommandPaletteEvent.performSearch({required String search}) =
_PerformSearch;
const factory CommandPaletteEvent.resultsChanged({
required RepeatedSearchResultPB results,
@Default(false) bool didClose,
}) = _ResultsChanged;
const factory CommandPaletteEvent.trashChanged({
@Default(null) List<TrashPB>? trash,
}) = _TrashChanged;
}
@freezed
class CommandPaletteState with _$CommandPaletteState {
const CommandPaletteState._();
const factory CommandPaletteState({
@Default(null) String? query,
required List<SearchResultPB> results,
required bool isLoading,
@Default([]) List<TrashPB> trash,
}) = _CommandPaletteState;
factory CommandPaletteState.initial() =>
const CommandPaletteState(results: [], isLoading: false);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/command_palette/search_service.dart | import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-search/entities.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
class SearchBackendService {
static Future<FlowyResult<void, FlowyError>> performSearch(
String keyword,
) async {
final request = SearchQueryPB(search: keyword);
return SearchEventSearch(request).send();
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/view_info/view_info_bloc.dart | import 'package:appflowy/util/int64_extension.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:appflowy_editor/appflowy_editor.dart';
import 'package:bloc/bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'view_info_bloc.freezed.dart';
class ViewInfoBloc extends Bloc<ViewInfoEvent, ViewInfoState> {
ViewInfoBloc({required this.view}) : super(ViewInfoState.initial()) {
on<ViewInfoEvent>((event, emit) {
event.when(
started: () {
emit(state.copyWith(createdAt: view.createTime.toDateTime()));
},
unregisterEditorState: () {
_clearWordCountService();
emit(state.copyWith(documentCounters: null));
},
registerEditorState: (editorState) {
_clearWordCountService();
_wordCountService = WordCountService(editorState: editorState)
..addListener(_onWordCountChanged)
..register();
emit(
state.copyWith(
documentCounters: _wordCountService!.documentCounters,
),
);
},
wordCountChanged: () {
emit(
state.copyWith(
documentCounters: _wordCountService?.documentCounters,
),
);
},
);
});
}
final ViewPB view;
WordCountService? _wordCountService;
@override
Future<void> close() async {
_clearWordCountService();
await super.close();
}
void _onWordCountChanged() => add(const ViewInfoEvent.wordCountChanged());
void _clearWordCountService() {
_wordCountService
?..removeListener(_onWordCountChanged)
..dispose();
_wordCountService = null;
}
}
@freezed
class ViewInfoEvent with _$ViewInfoEvent {
const factory ViewInfoEvent.started() = _Started;
const factory ViewInfoEvent.unregisterEditorState() = _UnregisterEditorState;
const factory ViewInfoEvent.registerEditorState({
required EditorState editorState,
}) = _RegisterEditorState;
const factory ViewInfoEvent.wordCountChanged() = _WordCountChanged;
}
@freezed
class ViewInfoState with _$ViewInfoState {
const factory ViewInfoState({
required Counters? documentCounters,
required DateTime? createdAt,
}) = _ViewInfoState;
factory ViewInfoState.initial() => const ViewInfoState(
documentCounters: null,
createdAt: null,
);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/user/user_workspace_bloc.dart | import 'package:appflowy/core/config/kv.dart';
import 'package:appflowy/core/config/kv_keys.dart';
import 'package:appflowy/generated/locale_keys.g.dart';
import 'package:appflowy/shared/feature_flags.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/user/application/user_listener.dart';
import 'package:appflowy/user/application/user_service.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-error/code.pbenum.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/protobuf.dart';
import 'package:appflowy_backend/protobuf/flowy-user/protobuf.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:collection/collection.dart';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:protobuf/protobuf.dart';
part 'user_workspace_bloc.freezed.dart';
class UserWorkspaceBloc extends Bloc<UserWorkspaceEvent, UserWorkspaceState> {
UserWorkspaceBloc({
required this.userProfile,
}) : _userService = UserBackendService(userId: userProfile.id),
_listener = UserListener(userProfile: userProfile),
super(UserWorkspaceState.initial()) {
on<UserWorkspaceEvent>(
(event, emit) async {
await event.when(
initial: () async {
_listener
..didUpdateUserWorkspaces = (workspaces) {
add(UserWorkspaceEvent.updateWorkspaces(workspaces));
}
..start();
final result = await _fetchWorkspaces();
final currentWorkspace = result.$1;
final workspaces = result.$2;
final isCollabWorkspaceOn =
userProfile.authenticator == AuthenticatorPB.AppFlowyCloud &&
FeatureFlag.collaborativeWorkspace.isOn;
if (currentWorkspace != null && result.$3 == true) {
final result = await _userService
.openWorkspace(currentWorkspace.workspaceId);
result.onSuccess((s) async {
await getIt<KeyValueStorage>().set(
KVKeys.lastOpenedWorkspaceId,
currentWorkspace.workspaceId,
);
});
}
emit(
state.copyWith(
currentWorkspace: currentWorkspace,
workspaces: workspaces,
isCollabWorkspaceOn: isCollabWorkspaceOn,
actionResult: null,
),
);
},
fetchWorkspaces: () async {
final result = await _fetchWorkspaces();
emit(
state.copyWith(
currentWorkspace: result.$1,
workspaces: result.$2,
),
);
},
createWorkspace: (name) async {
emit(
state.copyWith(
actionResult: const UserWorkspaceActionResult(
actionType: UserWorkspaceActionType.create,
isLoading: true,
result: null,
),
),
);
final result = await _userService.createUserWorkspace(name);
final workspaces = result.fold(
(s) => [...state.workspaces, s],
(e) => state.workspaces,
);
emit(
state.copyWith(
workspaces: workspaces,
actionResult: UserWorkspaceActionResult(
actionType: UserWorkspaceActionType.create,
isLoading: false,
result: result,
),
),
);
// open the created workspace by default
result.onSuccess((s) {
add(OpenWorkspace(s.workspaceId));
});
},
deleteWorkspace: (workspaceId) async {
emit(
state.copyWith(
actionResult: const UserWorkspaceActionResult(
actionType: UserWorkspaceActionType.delete,
isLoading: true,
result: null,
),
),
);
final remoteWorkspaces = await _fetchWorkspaces().then(
(value) => value.$2,
);
if (state.workspaces.length <= 1 || remoteWorkspaces.length <= 1) {
// do not allow to delete the last workspace, otherwise the user
// cannot do create workspace again
final result = FlowyResult.failure(
FlowyError(
code: ErrorCode.Internal,
msg: LocaleKeys.workspace_cannotDeleteTheOnlyWorkspace.tr(),
),
);
return emit(
state.copyWith(
actionResult: UserWorkspaceActionResult(
actionType: UserWorkspaceActionType.delete,
result: result,
isLoading: false,
),
),
);
}
final result = await _userService.deleteWorkspaceById(workspaceId);
final workspaces = result.fold(
// remove the deleted workspace from the list instead of fetching
// the workspaces again
(s) => state.workspaces
.where((e) => e.workspaceId != workspaceId)
.toList(),
(e) => state.workspaces,
);
result.onSuccess((_) {
// if the current workspace is deleted, open the first workspace
if (state.currentWorkspace?.workspaceId == workspaceId) {
add(OpenWorkspace(workspaces.first.workspaceId));
}
});
emit(
state.copyWith(
workspaces: workspaces,
actionResult: UserWorkspaceActionResult(
actionType: UserWorkspaceActionType.delete,
result: result,
isLoading: false,
),
),
);
},
openWorkspace: (workspaceId) async {
emit(
state.copyWith(
actionResult: const UserWorkspaceActionResult(
actionType: UserWorkspaceActionType.open,
isLoading: true,
result: null,
),
),
);
final result = await _userService.openWorkspace(workspaceId);
final currentWorkspace = result.fold(
(s) => state.workspaces.firstWhereOrNull(
(e) => e.workspaceId == workspaceId,
),
(e) => state.currentWorkspace,
);
result.onSuccess((_) async {
await getIt<KeyValueStorage>().set(
KVKeys.lastOpenedWorkspaceId,
workspaceId,
);
});
emit(
state.copyWith(
currentWorkspace: currentWorkspace,
actionResult: UserWorkspaceActionResult(
actionType: UserWorkspaceActionType.open,
isLoading: false,
result: result,
),
),
);
},
renameWorkspace: (workspaceId, name) async {
final result =
await _userService.renameWorkspace(workspaceId, name);
final workspaces = result.fold(
(s) => state.workspaces.map(
(e) {
if (e.workspaceId == workspaceId) {
e.freeze();
return e.rebuild((p0) {
p0.name = name;
});
}
return e;
},
).toList(),
(f) => state.workspaces,
);
final currentWorkspace = workspaces.firstWhere(
(e) => e.workspaceId == state.currentWorkspace?.workspaceId,
);
emit(
state.copyWith(
workspaces: workspaces,
currentWorkspace: currentWorkspace,
actionResult: UserWorkspaceActionResult(
actionType: UserWorkspaceActionType.rename,
isLoading: false,
result: result,
),
),
);
},
updateWorkspaceIcon: (workspaceId, icon) async {
final result = await _userService.updateWorkspaceIcon(
workspaceId,
icon,
);
final workspaces = result.fold(
(s) => state.workspaces.map(
(e) {
if (e.workspaceId == workspaceId) {
e.freeze();
return e.rebuild((p0) {
p0.icon = icon;
});
}
return e;
},
).toList(),
(f) => state.workspaces,
);
final currentWorkspace = workspaces.firstWhere(
(e) => e.workspaceId == state.currentWorkspace?.workspaceId,
);
emit(
state.copyWith(
workspaces: workspaces,
currentWorkspace: currentWorkspace,
actionResult: UserWorkspaceActionResult(
actionType: UserWorkspaceActionType.updateIcon,
isLoading: false,
result: result,
),
),
);
},
leaveWorkspace: (workspaceId) async {
final result = await _userService.leaveWorkspace(workspaceId);
final workspaces = result.fold(
(s) => state.workspaces
.where((e) => e.workspaceId != workspaceId)
.toList(),
(e) => state.workspaces,
);
result.onSuccess((_) {
// if leaving the current workspace, open the first workspace
if (state.currentWorkspace?.workspaceId == workspaceId) {
add(OpenWorkspace(workspaces.first.workspaceId));
}
});
emit(
state.copyWith(
workspaces: workspaces,
actionResult: UserWorkspaceActionResult(
actionType: UserWorkspaceActionType.leave,
isLoading: false,
result: result,
),
),
);
},
updateWorkspaces: (workspaces) async {
emit(
state.copyWith(
workspaces: workspaces.items
..sort(
(a, b) =>
a.createdAtTimestamp.compareTo(b.createdAtTimestamp),
),
),
);
},
);
},
);
}
@override
Future<void> close() {
_listener.stop();
return super.close();
}
final UserProfilePB userProfile;
final UserBackendService _userService;
final UserListener _listener;
Future<
(
UserWorkspacePB? currentWorkspace,
List<UserWorkspacePB> workspaces,
bool shouldOpenWorkspace,
)> _fetchWorkspaces() async {
try {
final lastOpenedWorkspaceId = await getIt<KeyValueStorage>().get(
KVKeys.lastOpenedWorkspaceId,
);
final currentWorkspace =
await _userService.getCurrentWorkspace().getOrThrow();
final workspaces = await _userService.getWorkspaces().getOrThrow();
if (workspaces.isEmpty) {
workspaces.add(convertWorkspacePBToUserWorkspace(currentWorkspace));
}
UserWorkspacePB? currentWorkspaceInList = workspaces
.firstWhereOrNull((e) => e.workspaceId == currentWorkspace.id);
if (lastOpenedWorkspaceId != null) {
final lastOpenedWorkspace = workspaces
.firstWhereOrNull((e) => e.workspaceId == lastOpenedWorkspaceId);
if (lastOpenedWorkspace != null) {
currentWorkspaceInList = lastOpenedWorkspace;
}
}
currentWorkspaceInList ??= workspaces.firstOrNull;
return (
currentWorkspaceInList,
workspaces
..sort(
(a, b) => a.createdAtTimestamp.compareTo(b.createdAtTimestamp),
),
lastOpenedWorkspaceId != currentWorkspace.id
);
} catch (e) {
Log.error('fetch workspace error: $e');
return (null, <UserWorkspacePB>[], false);
}
}
UserWorkspacePB convertWorkspacePBToUserWorkspace(WorkspacePB workspace) {
return UserWorkspacePB.create()
..workspaceId = workspace.id
..name = workspace.name
..createdAtTimestamp = workspace.createTime;
}
}
@freezed
class UserWorkspaceEvent with _$UserWorkspaceEvent {
const factory UserWorkspaceEvent.initial() = Initial;
const factory UserWorkspaceEvent.fetchWorkspaces() = FetchWorkspaces;
const factory UserWorkspaceEvent.createWorkspace(String name) =
CreateWorkspace;
const factory UserWorkspaceEvent.deleteWorkspace(String workspaceId) =
DeleteWorkspace;
const factory UserWorkspaceEvent.openWorkspace(String workspaceId) =
OpenWorkspace;
const factory UserWorkspaceEvent.renameWorkspace(
String workspaceId,
String name,
) = _RenameWorkspace;
const factory UserWorkspaceEvent.updateWorkspaceIcon(
String workspaceId,
String icon,
) = _UpdateWorkspaceIcon;
const factory UserWorkspaceEvent.leaveWorkspace(String workspaceId) =
LeaveWorkspace;
const factory UserWorkspaceEvent.updateWorkspaces(
RepeatedUserWorkspacePB workspaces,
) = UpdateWorkspaces;
}
enum UserWorkspaceActionType {
none,
create,
delete,
open,
rename,
updateIcon,
fetchWorkspaces,
leave;
}
class UserWorkspaceActionResult {
const UserWorkspaceActionResult({
required this.actionType,
required this.isLoading,
required this.result,
});
final UserWorkspaceActionType actionType;
final bool isLoading;
final FlowyResult<void, FlowyError>? result;
}
@freezed
class UserWorkspaceState with _$UserWorkspaceState {
const UserWorkspaceState._();
const factory UserWorkspaceState({
@Default(null) UserWorkspacePB? currentWorkspace,
@Default([]) List<UserWorkspacePB> workspaces,
@Default(null) UserWorkspaceActionResult? actionResult,
@Default(false) bool isCollabWorkspaceOn,
}) = _UserWorkspaceState;
factory UserWorkspaceState.initial() => const UserWorkspaceState();
@override
int get hashCode => runtimeType.hashCode;
final DeepCollectionEquality _deepCollectionEquality =
const DeepCollectionEquality();
@override
bool operator ==(Object other) {
if (identical(this, other)) return true;
return other is UserWorkspaceState &&
other.currentWorkspace == currentWorkspace &&
_deepCollectionEquality.equals(other.workspaces, workspaces) &&
identical(other.actionResult, actionResult);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/user/prelude.dart | export 'settings_user_bloc.dart';
export 'user_workspace_bloc.dart';
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/user/settings_user_bloc.dart | import 'package:appflowy/user/application/user_listener.dart';
import 'package:appflowy/user/application/user_service.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-user/user_profile.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'settings_user_bloc.freezed.dart';
class SettingsUserViewBloc extends Bloc<SettingsUserEvent, SettingsUserState> {
SettingsUserViewBloc(this.userProfile)
: _userListener = UserListener(userProfile: userProfile),
_userService = UserBackendService(userId: userProfile.id),
super(SettingsUserState.initial(userProfile)) {
_dispatch();
}
final UserBackendService _userService;
final UserListener _userListener;
final UserProfilePB userProfile;
@override
Future<void> close() async {
await _userListener.stop();
return super.close();
}
void _dispatch() {
on<SettingsUserEvent>(
(event, emit) async {
await event.when(
initial: () async {
_loadUserProfile();
_userListener.start(onProfileUpdated: _profileUpdated);
},
didReceiveUserProfile: (UserProfilePB newUserProfile) {
emit(state.copyWith(userProfile: newUserProfile));
},
updateUserName: (String name) {
_userService.updateUserProfile(name: name).then((result) {
result.fold(
(l) => null,
(err) => Log.error(err),
);
});
},
updateUserIcon: (String iconUrl) {
_userService.updateUserProfile(iconUrl: iconUrl).then((result) {
result.fold(
(l) => null,
(err) => Log.error(err),
);
});
},
removeUserIcon: () {
// Empty Icon URL = No icon
_userService.updateUserProfile(iconUrl: "").then((result) {
result.fold(
(l) => null,
(err) => Log.error(err),
);
});
},
updateUserOpenAIKey: (openAIKey) {
_userService.updateUserProfile(openAIKey: openAIKey).then((result) {
result.fold(
(l) => null,
(err) => Log.error(err),
);
});
},
updateUserStabilityAIKey: (stabilityAIKey) {
_userService
.updateUserProfile(stabilityAiKey: stabilityAIKey)
.then((result) {
result.fold(
(l) => null,
(err) => Log.error(err),
);
});
},
updateUserEmail: (String email) {
_userService.updateUserProfile(email: email).then((result) {
result.fold(
(l) => null,
(err) => Log.error(err),
);
});
},
);
},
);
}
void _loadUserProfile() {
UserBackendService.getCurrentUserProfile().then((result) {
if (isClosed) {
return;
}
result.fold(
(userProfile) => add(
SettingsUserEvent.didReceiveUserProfile(userProfile),
),
(err) => Log.error(err),
);
});
}
void _profileUpdated(
FlowyResult<UserProfilePB, FlowyError> userProfileOrFailed,
) {
userProfileOrFailed.fold(
(newUserProfile) {
add(SettingsUserEvent.didReceiveUserProfile(newUserProfile));
},
(err) => Log.error(err),
);
}
}
@freezed
class SettingsUserEvent with _$SettingsUserEvent {
const factory SettingsUserEvent.initial() = _Initial;
const factory SettingsUserEvent.updateUserName(String name) = _UpdateUserName;
const factory SettingsUserEvent.updateUserEmail(String email) = _UpdateEmail;
const factory SettingsUserEvent.updateUserIcon({required String iconUrl}) =
_UpdateUserIcon;
const factory SettingsUserEvent.removeUserIcon() = _RemoveUserIcon;
const factory SettingsUserEvent.updateUserOpenAIKey(String openAIKey) =
_UpdateUserOpenaiKey;
const factory SettingsUserEvent.updateUserStabilityAIKey(
String stabilityAIKey,
) = _UpdateUserStabilityAIKey;
const factory SettingsUserEvent.didReceiveUserProfile(
UserProfilePB newUserProfile,
) = _DidReceiveUserProfile;
}
@freezed
class SettingsUserState with _$SettingsUserState {
const factory SettingsUserState({
required UserProfilePB userProfile,
required FlowyResult<void, String> successOrFailure,
}) = _SettingsUserState;
factory SettingsUserState.initial(UserProfilePB userProfile) =>
SettingsUserState(
userProfile: userProfile,
successOrFailure: FlowyResult.success(null),
);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/recent/prelude.dart | export 'recent_service.dart';
export 'recent_views_bloc.dart';
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/recent/recent_views_bloc.dart | import 'package:appflowy/workspace/application/recent/recent_listener.dart';
import 'package:appflowy/workspace/application/recent/recent_service.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'recent_views_bloc.freezed.dart';
class RecentViewsBloc extends Bloc<RecentViewsEvent, RecentViewsState> {
RecentViewsBloc() : super(RecentViewsState.initial()) {
_dispatch();
}
final _service = RecentService();
final _listener = RecentViewsListener();
@override
Future<void> close() async {
await _listener.stop();
return super.close();
}
void _dispatch() {
on<RecentViewsEvent>(
(event, emit) async {
await event.map(
initial: (e) async {
_listener.start(
recentViewsUpdated: (result) => _onRecentViewsUpdated(result),
);
add(const RecentViewsEvent.fetchRecentViews());
},
addRecentViews: (e) async {
await _service.updateRecentViews(e.viewIds, true);
},
removeRecentViews: (e) async {
await _service.updateRecentViews(e.viewIds, false);
},
fetchRecentViews: (e) async {
final result = await _service.readRecentViews();
result.fold(
(views) => emit(state.copyWith(views: views.items)),
(error) => Log.error(error),
);
},
);
},
);
}
void _onRecentViewsUpdated(
FlowyResult<RepeatedViewIdPB, FlowyError> result,
) {
add(const RecentViewsEvent.fetchRecentViews());
}
}
@freezed
class RecentViewsEvent with _$RecentViewsEvent {
const factory RecentViewsEvent.initial() = Initial;
const factory RecentViewsEvent.addRecentViews(List<String> viewIds) =
AddRecentViews;
const factory RecentViewsEvent.removeRecentViews(List<String> viewIds) =
RemoveRecentViews;
const factory RecentViewsEvent.fetchRecentViews() = FetchRecentViews;
}
@freezed
class RecentViewsState with _$RecentViewsState {
const factory RecentViewsState({
required List<ViewPB> views,
}) = _RecentViewsState;
factory RecentViewsState.initial() => const RecentViewsState(
views: [],
);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/recent/recent_service.dart | import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/protobuf.dart';
import 'package:appflowy_result/appflowy_result.dart';
class RecentService {
Future<FlowyResult<void, FlowyError>> updateRecentViews(
List<String> viewIds,
bool addInRecent,
) async {
return FolderEventUpdateRecentViews(
UpdateRecentViewPayloadPB(viewIds: viewIds, addInRecent: addInRecent),
).send();
}
Future<FlowyResult<RepeatedViewPB, FlowyError>> readRecentViews() {
return FolderEventReadRecentViews().send();
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/recent/recent_listener.dart | import 'dart:async';
import 'package:appflowy/core/notification/folder_notification.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/notification.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-notification/subject.pb.dart';
import 'package:appflowy_backend/rust_stream.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:flutter/foundation.dart';
typedef RecentViewsUpdated = void Function(
FlowyResult<RepeatedViewIdPB, FlowyError> result,
);
class RecentViewsListener {
StreamSubscription<SubscribeObject>? _streamSubscription;
FolderNotificationParser? _parser;
RecentViewsUpdated? _recentViewsUpdated;
void start({
RecentViewsUpdated? recentViewsUpdated,
}) {
_recentViewsUpdated = recentViewsUpdated;
_parser = FolderNotificationParser(
id: 'recent_views',
callback: _observableCallback,
);
_streamSubscription = RustStreamReceiver.listen(
(observable) => _parser?.parse(observable),
);
}
void _observableCallback(
FolderNotification ty,
FlowyResult<Uint8List, FlowyError> result,
) {
if (_recentViewsUpdated == null) {
return;
}
result.fold(
(payload) {
final view = RepeatedViewIdPB.fromBuffer(payload);
_recentViewsUpdated?.call(
FlowyResult.success(view),
);
},
(error) => _recentViewsUpdated?.call(
FlowyResult.failure(error),
),
);
}
Future<void> stop() async {
_parser = null;
await _streamSubscription?.cancel();
_recentViewsUpdated = null;
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/action_navigation/navigation_action.dart | enum ActionType {
openView,
jumpToBlock,
openRow,
}
class ActionArgumentKeys {
static String view = "view";
static String nodePath = "node_path";
static String rowId = "row_id";
}
/// A [NavigationAction] is used to communicate with the
/// [ActionNavigationBloc] to perform actions based on an event
/// triggered by pressing a notification, such as opening a specific
/// view and jumping to a specific block.
///
class NavigationAction {
const NavigationAction({
this.type = ActionType.openView,
this.arguments,
required this.objectId,
});
final ActionType type;
final String objectId;
final Map<String, dynamic>? arguments;
NavigationAction copyWith({
ActionType? type,
String? objectId,
Map<String, dynamic>? arguments,
}) =>
NavigationAction(
type: type ?? this.type,
objectId: objectId ?? this.objectId,
arguments: arguments ?? this.arguments,
);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/action_navigation/action_navigation_bloc.dart | import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/user/application/auth/auth_service.dart';
import 'package:appflowy/workspace/application/action_navigation/navigation_action.dart';
import 'package:appflowy/workspace/application/view/view_service.dart';
import 'package:appflowy/workspace/application/workspace/workspace_listener.dart';
import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:bloc/bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'action_navigation_bloc.freezed.dart';
class ActionNavigationBloc
extends Bloc<ActionNavigationEvent, ActionNavigationState> {
ActionNavigationBloc() : super(const ActionNavigationState.initial()) {
on<ActionNavigationEvent>((event, emit) async {
await event.when(
initialize: () async {
final views = await ViewBackendService().fetchViews();
emit(state.copyWith(views: views));
await initializeListeners();
},
viewsChanged: (views) {
emit(state.copyWith(views: views));
},
performAction: (action, nextActions) {
emit(state.copyWith(action: action, nextActions: nextActions));
if (nextActions.isNotEmpty) {
final newActions = [...nextActions];
final next = newActions.removeAt(0);
add(
ActionNavigationEvent.performAction(
action: next,
nextActions: newActions,
),
);
} else {
emit(state.setNoAction());
}
},
);
});
}
WorkspaceListener? _workspaceListener;
@override
Future<void> close() async {
await _workspaceListener?.stop();
return super.close();
}
Future<void> initializeListeners() async {
if (_workspaceListener != null) {
return;
}
final userOrFailure = await getIt<AuthService>().getUser();
final user = userOrFailure.fold((s) => s, (f) => null);
if (user == null) {
_workspaceListener = null;
return;
}
final workspaceSettingsOrFailure =
await FolderEventGetCurrentWorkspaceSetting().send();
final workspaceId = workspaceSettingsOrFailure.fold(
(s) => s.workspaceId,
(f) => null,
);
if (workspaceId == null) {
_workspaceListener = null;
return;
}
_workspaceListener = WorkspaceListener(
user: user,
workspaceId: workspaceId,
);
_workspaceListener?.start(
appsChanged: (_) async {
final views = await ViewBackendService().fetchViews();
add(ActionNavigationEvent.viewsChanged(views));
},
);
}
}
@freezed
class ActionNavigationEvent with _$ActionNavigationEvent {
const factory ActionNavigationEvent.initialize() = _Initialize;
const factory ActionNavigationEvent.performAction({
required NavigationAction action,
@Default([]) List<NavigationAction> nextActions,
}) = _PerformAction;
const factory ActionNavigationEvent.viewsChanged(List<ViewPB> views) =
_ViewsChanged;
}
class ActionNavigationState {
const ActionNavigationState.initial()
: action = null,
nextActions = const [],
views = const [];
const ActionNavigationState({
required this.action,
this.nextActions = const [],
this.views = const [],
});
final NavigationAction? action;
final List<NavigationAction> nextActions;
final List<ViewPB> views;
ActionNavigationState copyWith({
NavigationAction? action,
List<NavigationAction>? nextActions,
List<ViewPB>? views,
}) =>
ActionNavigationState(
action: action ?? this.action,
nextActions: nextActions ?? this.nextActions,
views: views ?? this.views,
);
ActionNavigationState setNoAction() =>
ActionNavigationState(action: null, nextActions: [], views: views);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/menu/sidebar_sections_bloc.dart | import 'dart:async';
import 'package:appflowy/startup/plugin/plugin.dart';
import 'package:appflowy/startup/startup.dart';
import 'package:appflowy/workspace/application/tabs/tabs_bloc.dart';
import 'package:appflowy/workspace/application/view/view_ext.dart';
import 'package:appflowy/workspace/application/workspace/workspace_sections_listener.dart';
import 'package:appflowy/workspace/application/workspace/workspace_service.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-user/user_profile.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'sidebar_sections_bloc.freezed.dart';
class SidebarSection {
const SidebarSection({
required this.publicViews,
required this.privateViews,
});
const SidebarSection.empty()
: publicViews = const [],
privateViews = const [];
final List<ViewPB> publicViews;
final List<ViewPB> privateViews;
List<ViewPB> get views => publicViews + privateViews;
SidebarSection copyWith({
List<ViewPB>? publicViews,
List<ViewPB>? privateViews,
}) {
return SidebarSection(
publicViews: publicViews ?? this.publicViews,
privateViews: privateViews ?? this.privateViews,
);
}
}
/// The [SidebarSectionsBloc] is responsible for
/// managing the root views in different sections of the workspace.
class SidebarSectionsBloc
extends Bloc<SidebarSectionsEvent, SidebarSectionsState> {
SidebarSectionsBloc() : super(SidebarSectionsState.initial()) {
on<SidebarSectionsEvent>(
(event, emit) async {
await event.when(
initial: (userProfile, workspaceId) async {
_initial(userProfile, workspaceId);
final sectionViews = await _getSectionViews();
if (sectionViews != null) {
emit(
state.copyWith(
section: sectionViews,
),
);
}
},
reset: (userProfile, workspaceId) async {
_reset(userProfile, workspaceId);
final sectionViews = await _getSectionViews();
if (sectionViews != null) {
emit(
state.copyWith(
section: sectionViews,
),
);
}
},
createRootViewInSection: (name, section, desc, index) async {
final result = await _workspaceService.createView(
name: name,
viewSection: section,
desc: desc,
index: index,
);
result.fold(
(view) => emit(
state.copyWith(
lastCreatedRootView: view,
createRootViewResult: FlowyResult.success(null),
),
),
(error) {
Log.error('Failed to create root view: $error');
emit(
state.copyWith(
createRootViewResult: FlowyResult.failure(error),
),
);
},
);
},
receiveSectionViewsUpdate: (sectionViews) async {
final section = sectionViews.section;
switch (section) {
case ViewSectionPB.Public:
emit(
state.copyWith(
section: state.section.copyWith(
publicViews: sectionViews.views,
),
),
);
case ViewSectionPB.Private:
emit(
state.copyWith(
section: state.section.copyWith(
privateViews: sectionViews.views,
),
),
);
break;
default:
break;
}
},
moveRootView: (fromIndex, toIndex, fromSection, toSection) async {
final views = fromSection == ViewSectionPB.Public
? List<ViewPB>.from(state.section.publicViews)
: List<ViewPB>.from(state.section.privateViews);
if (fromIndex < 0 || fromIndex >= views.length) {
Log.error(
'Invalid fromIndex: $fromIndex, maxIndex: ${views.length - 1}',
);
return;
}
final view = views[fromIndex];
final result = await _workspaceService.moveView(
viewId: view.id,
fromIndex: fromIndex,
toIndex: toIndex,
);
result.fold(
(value) {
views.insert(toIndex, views.removeAt(fromIndex));
var newState = state;
if (fromSection == ViewSectionPB.Public) {
newState = newState.copyWith(
section: newState.section.copyWith(publicViews: views),
);
} else if (fromSection == ViewSectionPB.Private) {
newState = newState.copyWith(
section: newState.section.copyWith(privateViews: views),
);
}
emit(newState);
},
(error) {
Log.error('Failed to move root view: $error');
},
);
},
reload: (userProfile, workspaceId) async {
_initial(userProfile, workspaceId);
final sectionViews = await _getSectionViews();
if (sectionViews != null) {
emit(
state.copyWith(
section: sectionViews,
),
);
// try to open the fist view in public section or private section
if (sectionViews.publicViews.isNotEmpty) {
getIt<TabsBloc>().add(
TabsEvent.openPlugin(
plugin: sectionViews.publicViews.first.plugin(),
),
);
} else if (sectionViews.privateViews.isNotEmpty) {
getIt<TabsBloc>().add(
TabsEvent.openPlugin(
plugin: sectionViews.privateViews.first.plugin(),
),
);
} else {
getIt<TabsBloc>().add(
TabsEvent.openPlugin(
plugin: makePlugin(pluginType: PluginType.blank),
),
);
}
}
},
);
},
);
}
late WorkspaceService _workspaceService;
WorkspaceSectionsListener? _listener;
@override
Future<void> close() async {
await _listener?.stop();
_listener = null;
return super.close();
}
ViewSectionPB? getViewSection(ViewPB view) {
final publicViews = state.section.publicViews.map((e) => e.id);
final privateViews = state.section.privateViews.map((e) => e.id);
if (publicViews.contains(view.id)) {
return ViewSectionPB.Public;
} else if (privateViews.contains(view.id)) {
return ViewSectionPB.Private;
} else {
return null;
}
}
Future<SidebarSection?> _getSectionViews() async {
try {
final publicViews = await _workspaceService.getPublicViews().getOrThrow();
final privateViews =
await _workspaceService.getPrivateViews().getOrThrow();
return SidebarSection(
publicViews: publicViews,
privateViews: privateViews,
);
} catch (e) {
Log.error('Failed to get section views: $e');
return null;
}
}
void _initial(UserProfilePB userProfile, String workspaceId) {
_workspaceService = WorkspaceService(workspaceId: workspaceId);
_listener = WorkspaceSectionsListener(
user: userProfile,
workspaceId: workspaceId,
)..start(
sectionChanged: (result) {
if (!isClosed) {
result.fold(
(s) => add(SidebarSectionsEvent.receiveSectionViewsUpdate(s)),
(f) => Log.error('Failed to receive section views: $f'),
);
}
},
);
}
void _reset(UserProfilePB userProfile, String workspaceId) {
_listener?.stop();
_listener = null;
_initial(userProfile, workspaceId);
}
}
@freezed
class SidebarSectionsEvent with _$SidebarSectionsEvent {
const factory SidebarSectionsEvent.initial(
UserProfilePB userProfile,
String workspaceId,
) = _Initial;
const factory SidebarSectionsEvent.reset(
UserProfilePB userProfile,
String workspaceId,
) = _Reset;
const factory SidebarSectionsEvent.createRootViewInSection({
required String name,
required ViewSectionPB viewSection,
String? desc,
int? index,
}) = _CreateRootViewInSection;
const factory SidebarSectionsEvent.moveRootView({
required int fromIndex,
required int toIndex,
required ViewSectionPB fromSection,
required ViewSectionPB toSection,
}) = _MoveRootView;
const factory SidebarSectionsEvent.receiveSectionViewsUpdate(
SectionViewsPB sectionViews,
) = _ReceiveSectionViewsUpdate;
const factory SidebarSectionsEvent.reload(
UserProfilePB userProfile,
String workspaceId,
) = _Reload;
}
@freezed
class SidebarSectionsState with _$SidebarSectionsState {
const factory SidebarSectionsState({
required SidebarSection section,
@Default(null) ViewPB? lastCreatedRootView,
FlowyResult<void, FlowyError>? createRootViewResult,
}) = _SidebarSectionsState;
factory SidebarSectionsState.initial() => const SidebarSectionsState(
section: SidebarSection.empty(),
);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/menu/prelude.dart | export 'menu_user_bloc.dart';
export 'sidebar_sections_bloc.dart';
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/menu/menu_user_bloc.dart | import 'package:appflowy/user/application/user_listener.dart';
import 'package:appflowy/user/application/user_service.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/workspace.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-user/user_profile.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'menu_user_bloc.freezed.dart';
class MenuUserBloc extends Bloc<MenuUserEvent, MenuUserState> {
MenuUserBloc(this.userProfile)
: _userListener = UserListener(userProfile: userProfile),
_userWorkspaceListener = UserWorkspaceListener(),
_userService = UserBackendService(userId: userProfile.id),
super(MenuUserState.initial(userProfile)) {
_dispatch();
}
final UserBackendService _userService;
final UserListener _userListener;
final UserWorkspaceListener _userWorkspaceListener;
final UserProfilePB userProfile;
@override
Future<void> close() async {
await _userListener.stop();
await _userWorkspaceListener.stop();
return super.close();
}
void _dispatch() {
on<MenuUserEvent>(
(event, emit) async {
await event.when(
initial: () async {
_userListener.start(onProfileUpdated: _profileUpdated);
await _initUser();
},
fetchWorkspaces: () async {
//
},
didReceiveUserProfile: (UserProfilePB newUserProfile) {
emit(state.copyWith(userProfile: newUserProfile));
},
updateUserName: (String name) {
_userService.updateUserProfile(name: name).then((result) {
result.fold(
(l) => null,
(err) => Log.error(err),
);
});
},
);
},
);
}
Future<void> _initUser() async {
final result = await _userService.initUser();
result.fold((l) => null, (error) => Log.error(error));
}
void _profileUpdated(
FlowyResult<UserProfilePB, FlowyError> userProfileOrFailed,
) {
if (isClosed) {
return;
}
userProfileOrFailed.fold(
(newUserProfile) => add(
MenuUserEvent.didReceiveUserProfile(newUserProfile),
),
(err) => Log.error(err),
);
}
}
@freezed
class MenuUserEvent with _$MenuUserEvent {
const factory MenuUserEvent.initial() = _Initial;
const factory MenuUserEvent.fetchWorkspaces() = _FetchWorkspaces;
const factory MenuUserEvent.updateUserName(String name) = _UpdateUserName;
const factory MenuUserEvent.didReceiveUserProfile(
UserProfilePB newUserProfile,
) = _DidReceiveUserProfile;
}
@freezed
class MenuUserState with _$MenuUserState {
const factory MenuUserState({
required UserProfilePB userProfile,
required List<WorkspacePB>? workspaces,
required FlowyResult<void, String> successOrFailure,
}) = _MenuUserState;
factory MenuUserState.initial(UserProfilePB userProfile) => MenuUserState(
userProfile: userProfile,
workspaces: null,
successOrFailure: FlowyResult.success(null),
);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/favorite/prelude.dart | export 'favorite_bloc.dart';
export 'favorite_listener.dart';
export 'favorite_service.dart';
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/favorite/favorite_bloc.dart | import 'package:appflowy/workspace/application/favorite/favorite_service.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import 'favorite_listener.dart';
part 'favorite_bloc.freezed.dart';
class FavoriteBloc extends Bloc<FavoriteEvent, FavoriteState> {
FavoriteBloc() : super(FavoriteState.initial()) {
_dispatch();
}
final _service = FavoriteService();
final _listener = FavoriteListener();
@override
Future<void> close() async {
await _listener.stop();
return super.close();
}
void _dispatch() {
on<FavoriteEvent>(
(event, emit) async {
await event.when(
initial: () async {
_listener.start(
favoritesUpdated: _onFavoritesUpdated,
);
final result = await _service.readFavorites();
emit(
result.fold(
(view) => state.copyWith(
views: view.items,
),
(error) => state.copyWith(
views: [],
),
),
);
},
fetchFavorites: () async {
final result = await _service.readFavorites();
emit(
result.fold(
(view) => state.copyWith(
views: view.items,
),
(error) => state.copyWith(
views: [],
),
),
);
},
toggle: (view) async {
await _service.toggleFavorite(
view.id,
!view.isFavorite,
);
},
);
},
);
}
void _onFavoritesUpdated(
FlowyResult<RepeatedViewPB, FlowyError> favoriteOrFailed,
bool didFavorite,
) {
favoriteOrFailed.fold(
(favorite) => add(const FetchFavorites()),
(error) => Log.error(error),
);
}
}
@freezed
class FavoriteEvent with _$FavoriteEvent {
const factory FavoriteEvent.initial() = Initial;
const factory FavoriteEvent.toggle(ViewPB view) = ToggleFavorite;
const factory FavoriteEvent.fetchFavorites() = FetchFavorites;
}
@freezed
class FavoriteState with _$FavoriteState {
const factory FavoriteState({
required List<ViewPB> views,
}) = _FavoriteState;
factory FavoriteState.initial() => const FavoriteState(
views: [],
);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/favorite/favorite_service.dart | import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/protobuf.dart';
import 'package:appflowy_result/appflowy_result.dart';
class FavoriteService {
Future<FlowyResult<RepeatedViewPB, FlowyError>> readFavorites() {
return FolderEventReadFavorites().send();
}
Future<FlowyResult<void, FlowyError>> toggleFavorite(
String viewId,
bool favoriteStatus,
) async {
final id = RepeatedViewIdPB.create()..items.add(viewId);
return FolderEventToggleFavorite(id).send();
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/favorite/favorite_listener.dart | import 'dart:async';
import 'package:appflowy/core/notification/folder_notification.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/notification.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-notification/subject.pb.dart';
import 'package:appflowy_backend/rust_stream.dart';
import 'package:appflowy_result/appflowy_result.dart';
import 'package:flutter/foundation.dart';
typedef FavoriteUpdated = void Function(
FlowyResult<RepeatedViewPB, FlowyError> result,
bool isFavorite,
);
class FavoriteListener {
StreamSubscription<SubscribeObject>? _streamSubscription;
FolderNotificationParser? _parser;
FavoriteUpdated? _favoriteUpdated;
void start({
FavoriteUpdated? favoritesUpdated,
}) {
_favoriteUpdated = favoritesUpdated;
_parser = FolderNotificationParser(
id: 'favorite',
callback: _observableCallback,
);
_streamSubscription = RustStreamReceiver.listen(
(observable) => _parser?.parse(observable),
);
}
void _observableCallback(
FolderNotification ty,
FlowyResult<Uint8List, FlowyError> result,
) {
switch (ty) {
case FolderNotification.DidFavoriteView:
result.onSuccess(
(success) => _favoriteUpdated?.call(
FlowyResult.success(RepeatedViewPB.fromBuffer(success)),
true,
),
);
case FolderNotification.DidUnfavoriteView:
result.map(
(success) => _favoriteUpdated?.call(
FlowyResult.success(RepeatedViewPB.fromBuffer(success)),
false,
),
);
break;
default:
break;
}
}
Future<void> stop() async {
_parser = null;
await _streamSubscription?.cancel();
_streamSubscription = null;
_favoriteUpdated = null;
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/home/prelude.dart | 0 |
|
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/home/home_service.dart | import 'dart:async';
import 'package:appflowy_backend/dispatch/dispatch.dart';
import 'package:appflowy_backend/protobuf/flowy-error/errors.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:appflowy_result/appflowy_result.dart';
class HomeService {
static Future<FlowyResult<ViewPB, FlowyError>> readApp({
required String appId,
}) {
final payload = ViewIdPB.create()..value = appId;
return FolderEventGetView(payload).send();
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/home/home_bloc.dart | import 'package:appflowy/user/application/user_listener.dart';
import 'package:appflowy_backend/log.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/view.pb.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/workspace.pb.dart'
show WorkspaceSettingPB;
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flowy_infra/time/duration.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'home_bloc.freezed.dart';
class HomeBloc extends Bloc<HomeEvent, HomeState> {
HomeBloc(WorkspaceSettingPB workspaceSetting)
: _workspaceListener = UserWorkspaceListener(),
super(HomeState.initial(workspaceSetting)) {
_dispatch(workspaceSetting);
}
final UserWorkspaceListener _workspaceListener;
@override
Future<void> close() async {
await _workspaceListener.stop();
return super.close();
}
void _dispatch(WorkspaceSettingPB workspaceSetting) {
on<HomeEvent>(
(event, emit) async {
await event.map(
initial: (_Initial value) {
Future.delayed(const Duration(milliseconds: 300), () {
if (!isClosed) {
add(HomeEvent.didReceiveWorkspaceSetting(workspaceSetting));
}
});
_workspaceListener.start(
onSettingUpdated: (result) {
result.fold(
(setting) =>
add(HomeEvent.didReceiveWorkspaceSetting(setting)),
(r) => Log.error(r),
);
},
);
},
showLoading: (e) async {
emit(state.copyWith(isLoading: e.isLoading));
},
didReceiveWorkspaceSetting: (_DidReceiveWorkspaceSetting value) {
final latestView = value.setting.hasLatestView()
? value.setting.latestView
: state.latestView;
emit(
state.copyWith(
workspaceSetting: value.setting,
latestView: latestView,
),
);
},
);
},
);
}
}
enum MenuResizeType {
slide,
drag,
}
extension MenuResizeTypeExtension on MenuResizeType {
Duration duration() {
switch (this) {
case MenuResizeType.drag:
return 30.milliseconds;
case MenuResizeType.slide:
return 350.milliseconds;
}
}
}
@freezed
class HomeEvent with _$HomeEvent {
const factory HomeEvent.initial() = _Initial;
const factory HomeEvent.showLoading(bool isLoading) = _ShowLoading;
const factory HomeEvent.didReceiveWorkspaceSetting(
WorkspaceSettingPB setting,
) = _DidReceiveWorkspaceSetting;
}
@freezed
class HomeState with _$HomeState {
const factory HomeState({
required bool isLoading,
required WorkspaceSettingPB workspaceSetting,
ViewPB? latestView,
}) = _HomeState;
factory HomeState.initial(WorkspaceSettingPB workspaceSetting) => HomeState(
isLoading: false,
workspaceSetting: workspaceSetting,
);
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/home/home_setting_bloc.dart | import 'package:appflowy/user/application/user_listener.dart';
import 'package:appflowy/workspace/application/edit_panel/edit_context.dart';
import 'package:appflowy/workspace/application/settings/appearance/appearance_cubit.dart';
import 'package:appflowy_backend/protobuf/flowy-folder/workspace.pb.dart'
show WorkspaceSettingPB;
import 'package:flowy_infra/size.dart';
import 'package:flowy_infra/time/duration.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
part 'home_setting_bloc.freezed.dart';
class HomeSettingBloc extends Bloc<HomeSettingEvent, HomeSettingState> {
HomeSettingBloc(
WorkspaceSettingPB workspaceSetting,
AppearanceSettingsCubit appearanceSettingsCubit,
double screenWidthPx,
) : _listener = UserWorkspaceListener(),
_appearanceSettingsCubit = appearanceSettingsCubit,
super(
HomeSettingState.initial(
workspaceSetting,
appearanceSettingsCubit.state,
screenWidthPx,
),
) {
_dispatch();
}
final UserWorkspaceListener _listener;
final AppearanceSettingsCubit _appearanceSettingsCubit;
@override
Future<void> close() async {
await _listener.stop();
return super.close();
}
void _dispatch() {
on<HomeSettingEvent>(
(event, emit) async {
await event.map(
initial: (_Initial value) {},
setEditPanel: (e) async {
emit(state.copyWith(panelContext: e.editContext));
},
dismissEditPanel: (value) async {
emit(state.copyWith(panelContext: null));
},
didReceiveWorkspaceSetting: (_DidReceiveWorkspaceSetting value) {
emit(state.copyWith(workspaceSetting: value.setting));
},
collapseMenu: (_CollapseMenu e) {
final isMenuCollapsed = !state.isMenuCollapsed;
_appearanceSettingsCubit.saveIsMenuCollapsed(isMenuCollapsed);
emit(
state.copyWith(
isMenuCollapsed: isMenuCollapsed,
keepMenuCollapsed: isMenuCollapsed,
),
);
},
checkScreenSize: (_CheckScreenSize e) {
final bool isScreenSmall =
e.screenWidthPx < PageBreaks.tabletLandscape;
if (state.isScreenSmall != isScreenSmall) {
final isMenuCollapsed = isScreenSmall || state.keepMenuCollapsed;
emit(
state.copyWith(
isMenuCollapsed: isMenuCollapsed,
isScreenSmall: isScreenSmall,
),
);
} else {
emit(state.copyWith(isScreenSmall: isScreenSmall));
}
},
editPanelResizeStart: (_EditPanelResizeStart e) {
emit(
state.copyWith(
resizeType: MenuResizeType.drag,
resizeStart: state.resizeOffset,
),
);
},
editPanelResized: (_EditPanelResized e) {
final newPosition =
(e.offset + state.resizeStart).clamp(-50, 200).toDouble();
if (state.resizeOffset != newPosition) {
emit(state.copyWith(resizeOffset: newPosition));
}
},
editPanelResizeEnd: (_EditPanelResizeEnd e) {
_appearanceSettingsCubit.saveMenuOffset(state.resizeOffset);
emit(state.copyWith(resizeType: MenuResizeType.slide));
},
);
},
);
}
}
enum MenuResizeType {
slide,
drag,
}
extension MenuResizeTypeExtension on MenuResizeType {
Duration duration() {
switch (this) {
case MenuResizeType.drag:
return 30.milliseconds;
case MenuResizeType.slide:
return 350.milliseconds;
}
}
}
@freezed
class HomeSettingEvent with _$HomeSettingEvent {
const factory HomeSettingEvent.initial() = _Initial;
const factory HomeSettingEvent.setEditPanel(EditPanelContext editContext) =
_ShowEditPanel;
const factory HomeSettingEvent.dismissEditPanel() = _DismissEditPanel;
const factory HomeSettingEvent.didReceiveWorkspaceSetting(
WorkspaceSettingPB setting,
) = _DidReceiveWorkspaceSetting;
const factory HomeSettingEvent.collapseMenu() = _CollapseMenu;
const factory HomeSettingEvent.checkScreenSize(double screenWidthPx) =
_CheckScreenSize;
const factory HomeSettingEvent.editPanelResized(double offset) =
_EditPanelResized;
const factory HomeSettingEvent.editPanelResizeStart() = _EditPanelResizeStart;
const factory HomeSettingEvent.editPanelResizeEnd() = _EditPanelResizeEnd;
}
@freezed
class HomeSettingState with _$HomeSettingState {
const factory HomeSettingState({
required EditPanelContext? panelContext,
required WorkspaceSettingPB workspaceSetting,
required bool unauthorized,
required bool isMenuCollapsed,
required bool keepMenuCollapsed,
required bool isScreenSmall,
required double resizeOffset,
required double resizeStart,
required MenuResizeType resizeType,
}) = _HomeSettingState;
factory HomeSettingState.initial(
WorkspaceSettingPB workspaceSetting,
AppearanceSettingsState appearanceSettingsState,
double screenWidthPx,
) {
return HomeSettingState(
panelContext: null,
workspaceSetting: workspaceSetting,
unauthorized: false,
isMenuCollapsed: appearanceSettingsState.isMenuCollapsed,
isScreenSmall: screenWidthPx < PageBreaks.tabletLandscape,
keepMenuCollapsed: false,
resizeOffset: appearanceSettingsState.menuOffset,
resizeStart: 0,
resizeType: MenuResizeType.slide,
);
}
}
| 0 |
mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application | mirrored_repositories/AppFlowy/frontend/appflowy_flutter/lib/workspace/application/settings/prelude.dart | export 'application_data_storage.dart';
export 'create_file_settings_cubit.dart';
export 'settings_dialog_bloc.dart';
| 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.