Add table creation

This commit is contained in:
Andrew 2023-04-11 02:42:20 +07:00
parent 09c9549004
commit 4a5039cb19
19 changed files with 1132 additions and 141 deletions

View file

@ -0,0 +1,242 @@
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:recase/recase.dart';
import 'package:tuuli_app/api/model/table_field_model.dart';
import 'package:tuuli_app/api/model/tables_list_model.dart';
import 'package:tuuli_app/widgets/table_field_widget.dart';
class EditTableBottomSheetResult {
final String tableName;
final List<TableField> fields;
EditTableBottomSheetResult(this.tableName, this.fields);
}
class EditTableBottomSheet extends StatefulWidget {
final TableModel? table;
const EditTableBottomSheet({super.key, this.table});
@override
State<StatefulWidget> createState() => _EditTableBottomSheetState();
}
class _EditTableBottomSheetState extends State<EditTableBottomSheet> {
var tableName = "".obs;
late final List<TableField> fields;
final newFieldName = TextEditingController();
String? newFieldType;
var newFieldPrimary = false;
var newFieldUnique = false;
@override
void initState() {
super.initState();
fields = widget.table?.columns ?? [];
if (widget.table != null) {
tableName.value = widget.table!.tableName;
}
}
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Obx(
() => Text(
tableName.isEmpty
? "Edit table"
: "Edit table \"${tableName.value.pascalCase}\"",
style: Theme.of(context).textTheme.headlineSmall,
),
),
const Spacer(),
IconButton(
onPressed: Get.back,
icon: const Icon(Icons.cancel),
)
],
),
if (widget.table == null) const Divider(),
if (widget.table == null)
TextFormField(
decoration: const InputDecoration(
labelText: 'Table name',
hintText: 'Enter table name',
),
readOnly: widget.table != null,
maxLength: 15,
onChanged: (value) => tableName.value = value,
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter table name';
}
return null;
},
),
const Divider(),
Text(
"Fields",
style: Theme.of(context).textTheme.titleLarge,
),
if (fields.isEmpty) const Text("No fields"),
...fields
.map((e) => TableFieldWidget(
field: e,
onRemove: () => _removeColumn(e.fieldName),
))
.toList(growable: false),
if (widget.table == null) const SizedBox(width: 16),
if (widget.table == null)
Card(
child: Container(
padding: const EdgeInsets.all(8),
margin: const EdgeInsets.all(8),
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text("Add new field"),
const SizedBox(height: 8),
Row(
children: [
Flexible(
child: TextFormField(
controller: newFieldName,
decoration: const InputDecoration(
labelText: 'Column name',
hintText: 'Enter column name',
border: OutlineInputBorder(),
),
),
),
const SizedBox(width: 8),
Flexible(
child: DropdownButtonFormField(
decoration: const InputDecoration(
labelText: 'Column type',
hintText: 'Choose column type',
border: OutlineInputBorder(),
),
items: possibleFieldTypes.keys
.map((e) => DropdownMenuItem(
value: e,
child: Text(e.pascalCase),
))
.toList(growable: false),
value: newFieldType,
onChanged: (value) => newFieldType = value,
),
),
const SizedBox(width: 16),
ToggleButtons(
isSelected: [
newFieldPrimary,
newFieldUnique,
!newFieldPrimary && !newFieldUnique
],
onPressed: (index) {
setState(() {
newFieldPrimary = index == 0;
newFieldUnique = index == 1;
});
},
children: const [
Text("Primary"),
Text("Unique"),
Text("Normal"),
],
),
const SizedBox(width: 16),
ElevatedButton(
onPressed: _addNewField,
child: const Text("Add field"),
),
],
),
],
),
),
),
const SizedBox(height: 32),
ElevatedButton(
onPressed: _saveTable,
child: const Text("Save table"),
),
],
),
),
);
}
void _addNewField() {
if (newFieldType == null) {
return;
}
final fieldName = newFieldName.text;
if (fieldName.isEmpty ||
fields.any((element) => element.fieldName == fieldName)) {
Get.defaultDialog(
title: "Error",
middleText: "Field name is empty or already exists",
);
return;
}
final field = TableField.parseTableField(
"$fieldName:$newFieldType${newFieldUnique ? ":unique" : ""}${newFieldPrimary ? ":primary" : ""}",
);
if (field.isPrimary && !field.canBePrimary()) {
Get.defaultDialog(
title: "Error",
middleText: "Field type \"${field.fieldType}\" can't be primary",
);
return;
}
setState(() {
newFieldName.clear();
newFieldType = null;
newFieldPrimary = false;
newFieldUnique = false;
fields.add(field);
});
}
void _saveTable() {
if (tableName.isEmpty) {
Get.defaultDialog(
title: "Error",
middleText: "Table name is empty",
);
return;
}
if (fields.isEmpty) {
Get.defaultDialog(
title: "Error",
middleText: "Table must have at least one field",
);
return;
}
Get.back(result: EditTableBottomSheetResult(tableName.value, fields));
}
void _removeColumn(String name) {
setState(() {
fields.removeWhere((element) => element.fieldName == name);
});
}
}

View file

@ -28,23 +28,25 @@ class _CheckupPageState extends State<CheckupPage>
@override
Widget build(BuildContext context) {
return AnimatedBackground(
behaviour: RandomParticleBehaviour(),
vsync: this,
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Checking credentials...',
style: Theme.of(context).textTheme.headlineMedium,
),
const SizedBox(height: 16),
const SizedBox.square(
dimension: 32,
child: CircularProgressIndicator(),
),
],
return Scaffold(
body: AnimatedBackground(
behaviour: RandomParticleBehaviour(),
vsync: this,
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'Checking credentials...',
style: Theme.of(context).textTheme.headlineMedium,
),
const SizedBox(height: 16),
const SizedBox.square(
dimension: 32,
child: CircularProgressIndicator(),
),
],
),
),
),
);

View file

@ -1,5 +1,20 @@
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:tuuli_app/api/api_client.dart';
import 'package:tuuli_app/api/model/tables_list_model.dart';
import 'package:tuuli_app/c.dart';
import 'package:tuuli_app/pages/home_panels/none_panel.dart';
import 'package:tuuli_app/pages/home_panels/settings_panel.dart';
import 'package:tuuli_app/pages/home_panels/tables_list_panel.dart';
import 'package:tuuli_app/pages/home_panels/users_list_panel.dart';
enum PageType {
none,
tables,
users,
settings,
}
class HomePage extends StatefulWidget {
const HomePage({super.key});
@ -9,25 +24,151 @@ class HomePage extends StatefulWidget {
}
class _HomePageState extends State<HomePage> {
final apiClient = Get.find<ApiClient>();
TablesListModel tables = TablesListModel([]);
bool get isNarrow =>
(MediaQuery.of(context).size.width - C.materialDrawerWidth) <= 600;
@override
void initState() {
super.initState();
_refreshData();
}
var currentPage = PageType.none;
final pageNames = {
PageType.none: "Home",
PageType.tables: "Tables",
PageType.users: "Users",
PageType.settings: "Settings",
};
AppBar get appBar => AppBar(
title: Text(pageNames[currentPage]!),
actions: [
IconButton(
icon: const Icon(Icons.home),
onPressed: () {
Get.offAllNamed("/");
},
),
IconButton(
icon: const Icon(Icons.refresh),
onPressed: _refreshData,
),
],
);
ListView get drawerOptions => ListView(
children: [
ListTile(
leading: const Icon(Icons.table_chart),
title: const Text("Tables"),
onTap: () {
setState(() {
currentPage = PageType.tables;
});
},
),
ListTile(
leading: const Icon(Icons.person),
title: const Text("Users"),
onTap: () {
setState(() {
currentPage = PageType.users;
});
},
),
ListTile(
leading: const Icon(Icons.settings),
title: const Text("Settings"),
onTap: () {
setState(() {
currentPage = PageType.settings;
});
},
),
const Divider(),
ListTile(
leading: const Icon(Icons.logout),
title: const Text("Logout"),
onTap: () {
GetStorage().erase().then((value) {
GetStorage().save();
Get.offAllNamed("/");
});
},
),
],
);
@override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
return Scaffold(
appBar: appBar,
drawer: isNarrow
? Drawer(
width: C.materialDrawerWidth,
child: drawerOptions,
)
: null,
body: Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Home Page',
style: Theme.of(context).textTheme.headlineMedium,
Container(
width: C.materialDrawerWidth,
decoration: BoxDecoration(
color: Colors.black.withAlpha(100),
border: Border(
right: BorderSide(
color: Theme.of(context).dividerColor,
width: 1,
),
),
),
child: drawerOptions,
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () {
Get.offNamed("/login");
},
child: const Text('Login'),
LimitedBox(
maxWidth: MediaQuery.of(context).size.width - C.materialDrawerWidth,
child: Builder(builder: (context) {
switch (currentPage) {
case PageType.tables:
return TablesListPanel(tables: tables);
case PageType.users:
return const UsersListPanel();
case PageType.settings:
return const SettingsPanel();
case PageType.none:
default:
return const NonePanel();
}
}),
),
],
),
);
}
void _refreshData() {
apiClient.tablesList().then(
(value) => value.unfold(
(tables) {
setState(() {
this.tables = tables;
});
},
(error) {
ScaffoldMessenger.of(context).hideCurrentSnackBar();
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(error.toString()),
),
);
},
),
);
}
}

View file

@ -0,0 +1,15 @@
import 'package:flutter/material.dart';
class NonePanel extends StatelessWidget {
const NonePanel({super.key});
@override
Widget build(BuildContext context) {
return Center(
child: Text(
'Use the menu for navigation',
style: Theme.of(context).textTheme.headlineSmall,
),
);
}
}

View file

@ -0,0 +1,36 @@
import 'package:flutter/material.dart';
import 'package:get/get.dart';
class SettingsPanel extends StatefulWidget {
const SettingsPanel({super.key});
@override
State<StatefulWidget> createState() => _SettingsPanelState();
}
class _SettingsPanelState extends State<SettingsPanel> {
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: IntrinsicHeight(
child: _buildBody(),
),
);
}
Widget _buildBody() {
return Column(
children: [
Text(
'Settings',
style: Theme.of(context).textTheme.headlineSmall,
),
],
);
}
}

View file

@ -0,0 +1,179 @@
import 'package:bottom_sheet/bottom_sheet.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:recase/recase.dart';
import 'package:tuuli_app/api/api_client.dart';
import 'package:tuuli_app/api/model/tables_list_model.dart';
import 'package:tuuli_app/c.dart';
import 'package:tuuli_app/pages/bottomsheers/edit_table_bottomsheet.dart';
class TablesListPanel extends StatefulWidget {
final TablesListModel tables;
const TablesListPanel({super.key, required this.tables});
@override
State<StatefulWidget> createState() => _TablesListPanelState();
}
class _TablesListPanelState extends State<TablesListPanel> {
final apiClient = Get.find<ApiClient>();
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return _buildTableList();
}
Widget _buildTableCard(BuildContext ctx, TableModel table) {
return Card(
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: () => _openTable(table),
child: Container(
margin: const EdgeInsets.all(5),
padding: const EdgeInsets.all(5),
child: Stack(
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Text(
table.tableName.pascalCase,
style: const TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
Row(
children: [
Text(
table.system ? "System" : "Userland",
style: const TextStyle(
fontSize: 12,
),
),
],
),
Row(
children: [
Text(
"${table.columns.length} column(s)",
style: const TextStyle(
fontSize: 11,
fontStyle: FontStyle.italic,
),
),
],
)
],
),
],
),
),
),
);
}
Widget get newTableCard => Card(
clipBehavior: Clip.antiAlias,
child: InkWell(
onTap: _createNewTable,
child: Container(
margin: const EdgeInsets.all(5),
padding: const EdgeInsets.all(5),
child: const Icon(Icons.add),
),
),
);
Widget _buildTableList() {
var tableItems = widget.tables.tables
.where((table) => !table.hidden && !table.system)
.toList(growable: false);
if (tableItems.isEmpty) {
return Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: [
Text(
"No tables found",
style: TextStyle(
color: Theme.of(context).disabledColor,
fontSize: 24,
),
),
const SizedBox(height: 4),
Text(
"Maybe create one?",
style: TextStyle(
color: Theme.of(context).disabledColor,
fontSize: 14,
),
),
const SizedBox(height: 16),
ElevatedButton.icon(
onPressed: _createNewTable,
icon: const Icon(Icons.add),
label: const Text("Create table"),
)
],
),
);
}
return GridView.builder(
shrinkWrap: true,
itemCount: tableItems.length + 1,
itemBuilder: (ctx, i) =>
i == 0 ? newTableCard : _buildTableCard(ctx, tableItems[i - 1]),
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 5,
childAspectRatio: 5 / 2,
),
);
}
void _createNewTable() async {
final result = await showFlexibleBottomSheet<EditTableBottomSheetResult>(
minHeight: 0,
initHeight: 0.75,
maxHeight: 1,
context: context,
builder: (_, __, ___) => const EditTableBottomSheet(),
anchors: [0, 0.5, 1],
isSafeArea: true,
isDismissible: false,
);
if (result == null) return;
await apiClient
.createTable(result.tableName, result.fields)
.then((e) => e.unfold((_) {
Get.snackbar(
"Success",
"Table created",
colorText: Colors.white,
);
}, (error) {
Get.defaultDialog(
title: "Error",
middleText: error.toString(),
textConfirm: "OK",
onConfirm: () => Get.back(),
);
}));
}
void _openTable(TableModel table) async {
// TODO: Open table
}
}

View file

@ -0,0 +1,36 @@
import 'package:flutter/material.dart';
import 'package:get/get.dart';
class UsersListPanel extends StatefulWidget {
const UsersListPanel({super.key});
@override
State<StatefulWidget> createState() => _UsersListPanelState();
}
class _UsersListPanelState extends State<UsersListPanel> {
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: IntrinsicHeight(
child: _buildBody(),
),
);
}
Widget _buildBody() {
return Column(
children: [
Text(
'Users',
style: Theme.of(context).textTheme.headlineSmall,
),
],
);
}
}

View file

@ -26,73 +26,75 @@ class _LoginPageState extends State<LoginPage> with TickerProviderStateMixin {
Widget build(BuildContext context) {
final screenSize = MediaQuery.of(context).size;
final formWidth = screenSize.width <= 600 ? screenSize.width : 300.0;
return Stack(
children: [
AnimatedBackground(
behaviour: RandomParticleBehaviour(),
vsync: this,
child: const SizedBox.square(
dimension: 0,
return Scaffold(
body: Stack(
children: [
AnimatedBackground(
behaviour: RandomParticleBehaviour(),
vsync: this,
child: const SizedBox.square(
dimension: 0,
),
),
),
Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
LimitedBox(
maxWidth: formWidth,
child: Container(
color: Colors.black.withAlpha(100),
padding: const EdgeInsets.all(16),
child: Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TextFormField(
controller: loginController,
enabled: !submitted,
decoration: const InputDecoration(
labelText: 'Login',
hintText: 'Enter your login',
Row(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
LimitedBox(
maxWidth: formWidth,
child: Container(
color: Colors.black.withAlpha(100),
padding: const EdgeInsets.all(16),
child: Form(
key: _formKey,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TextFormField(
controller: loginController,
enabled: !submitted,
decoration: const InputDecoration(
labelText: 'Login',
hintText: 'Enter your login',
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter your Login';
}
return null;
},
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter your Login';
}
return null;
},
),
TextFormField(
controller: passwordController,
obscureText: true,
enabled: !submitted,
decoration: const InputDecoration(
labelText: 'Password',
hintText: 'Enter your password',
TextFormField(
controller: passwordController,
obscureText: true,
enabled: !submitted,
decoration: const InputDecoration(
labelText: 'Password',
hintText: 'Enter your password',
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter your password';
}
return null;
},
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Please enter your password';
}
return null;
},
),
const SizedBox(height: 16),
ElevatedButton(
onPressed: submitted ? null : _submit,
child: const Text('Login'),
),
],
const SizedBox(height: 16),
ElevatedButton(
onPressed: submitted ? null : _submit,
child: const Text('Login'),
),
],
),
),
),
),
),
],
),
],
],
),
],
),
);
}
@ -121,13 +123,16 @@ class _LoginPageState extends State<LoginPage> with TickerProviderStateMixin {
content: Text('Login successful'),
),
);
apiClient.setAccessToken(data.accessToken);
GetStorage()
.write("accessToken", data.accessToken)
.then((value) => GetStorage().save());
Timer(1.seconds, () {
ScaffoldMessenger.of(context).hideCurrentSnackBar();
WidgetsBinding.instance.addPostFrameCallback((_) {
Get.offAllNamed("/home");
.then((value) => GetStorage().save())
.then((value) {
Timer(1.seconds, () {
ScaffoldMessenger.of(context).hideCurrentSnackBar();
WidgetsBinding.instance.addPostFrameCallback((_) {
Get.offAllNamed("/home");
});
});
});
}, (error) {

View file

@ -1,19 +1,50 @@
import 'package:animated_background/animated_background.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/scheduler/ticker.dart';
import 'package:get/get.dart';
class NotFoundPage extends StatelessWidget {
class NotFoundPage extends StatefulWidget {
const NotFoundPage({super.key});
@override
State<StatefulWidget> createState() => _NotFoundPageState();
}
class _NotFoundPageState extends State<NotFoundPage>
with TickerProviderStateMixin {
@override
Widget build(BuildContext context) {
return AnimatedBackground(
behaviour: RandomParticleBehaviour(),
vsync: Scaffold.of(context),
child: Center(
child: Text(
'Page not found',
style: Theme.of(context).textTheme.headlineMedium,
return Scaffold(
body: AnimatedBackground(
behaviour: RandomParticleBehaviour(),
vsync: this,
child: Center(
child: Text(
'Page not found',
style: Theme.of(context).textTheme.headlineMedium,
),
),
),
bottomSheet: Container(
color: Colors.black.withAlpha(100),
padding: const EdgeInsets.all(16),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (Navigator.of(context).canPop())
ElevatedButton(
onPressed: () {
Get.back(canPop: false);
},
child: const Text('Go back'),
),
const SizedBox(width: 16),
ElevatedButton(
onPressed: () {
Get.offAllNamed("/");
},
child: const Text('Go home'),
),
],
),
),
);