-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmarkdown_widget_builder.dart
More file actions
303 lines (249 loc) · 8.97 KB
/
Copy pathmarkdown_widget_builder.dart
File metadata and controls
303 lines (249 loc) · 8.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
/// Markdown widget builder.
///
// Time-stamp: <Thursday 2024-11-14 21:33:15 +1100 Graham Williams>
///
/// Copyright (C) 2024, Software Innovation Institute, ANU.
///
/// Licensed under the MIT License (the "License").
///
/// License: https://choosealicense.com/licenses/mit/.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
///
/// Authors: Tony Chen
library;
import 'package:flutter/material.dart';
import 'package:audioplayers/audioplayers.dart';
import 'package:media_kit/media_kit.dart';
import 'package:markdown_widget_builder/src/constants/pkg.dart' as pkg;
import 'package:markdown_widget_builder/src/utils/command_parser.dart';
import 'package:markdown_widget_builder/src/widgets/input_field.dart';
/// Sets the media path inside the package.
void setMarkdownMediaPath(String newMediaPath) {
pkg.setMediaPath(newMediaPath);
}
/// The MarkdownWidgetBuilder is a stateful widget that takes in markdown-like
/// content and a title. It uses the CommandParser to interpret custom commands
/// embedded in the content and build corresponding Flutter widgets, including
/// images, inputs, sliders, videos, audio players, and more. It also supports
/// pagination if the content is split into pages, allowing the user to navigate
/// between pages.
class MarkdownWidgetBuilder extends StatefulWidget {
/// The markdown content containing custom commands to render.
final String content;
/// A title (e.g., for a survey or form) that may be displayed or used in
/// callbacks.
final String title;
/// An optional submit URL that might be used for form submission.
final String? submitUrl;
/// A callback for when a menu item is selected, providing the selected title
/// and content.
final void Function(String title, String content)? onMenuItemSelected;
/// A custom function to be called when submit/save button is pressed
/// Note that the package assumes this function has one input argument
/// to pass the response Map. An example function is below
/// ignore: unintended_html_in_doc_comment
/// void onSubmit (Map<String, dynamic> responseMap) {
/// print (responseMap.toString());
/// }
final Function? onSubmit;
const MarkdownWidgetBuilder({
super.key,
required this.content,
required this.title,
this.submitUrl,
this.onMenuItemSelected,
this.onSubmit,
});
@override
State<MarkdownWidgetBuilder> createState() => _MarkdownWidgetBuilderState();
}
class _MarkdownWidgetBuilderState extends State<MarkdownWidgetBuilder> {
// State maps for various widget types and their values.
final Map<String, String> _inputValues = {};
final Map<String, double> _sliderValues = {};
final Map<String, Map<String, dynamic>> _sliders = {};
final Map<String, String?> _radioValues = {};
final Map<String, Set<String>> _checkboxValues = {};
final Map<String, DateTime?> _dateValues = {};
final Map<String, String?> _dropdownValues = {};
final Map<String, List<String>> _dropdownOptions = {};
final Map<String, GlobalKey<InputFieldState>> _inputFieldKeys = {};
final Map<String, bool> _hiddenContentVisibility = {};
// Maps for hidden content and required widgets tracking.
final Map<String, String> _hiddenContentMap = {};
final Set<String> _requiredWidgets = {};
// Media player instances for video and audio.
final Map<String, Player> _videoPlayers = {};
final Map<String, AudioPlayer> _audioPlayers = {};
// Keeps track of the current page index if content is split into multiple
// pages.
int _currentPage = 0;
@override
void initState() {
super.initState();
MediaKit.ensureInitialized();
}
@override
void dispose() {
// Dispose all video and audio players to release resources when the widget
// is removed.
_videoPlayers.forEach((key, player) {
player.dispose();
});
_audioPlayers.forEach((key, player) {
player.dispose();
});
super.dispose();
}
/// Builds the pages by parsing the content with CommandParser.
/// CommandParser returns a list of pages, each page containing a list of
/// widgets.
List<List<Widget>> _buildPages() {
final parser = CommandParser(
context: context,
content: widget.content,
fullContent: widget.content,
onMenuItemSelected: widget.onMenuItemSelected,
onSubmit: widget.onSubmit,
state: {
'_inputValues': _inputValues,
'_sliderValues': _sliderValues,
'_sliders': _sliders,
'_radioValues': _radioValues,
'_checkboxValues': _checkboxValues,
'_dateValues': _dateValues,
'_dropdownValues': _dropdownValues,
'_dropdownOptions': _dropdownOptions,
'_inputFieldKeys': _inputFieldKeys,
'_hiddenContentVisibility': _hiddenContentVisibility,
'_requiredWidgets': _requiredWidgets,
'_hiddenContentMap': _hiddenContentMap,
},
setStateCallback: () => setState(() {}),
surveyTitle: widget.title,
);
List<List<Widget>> pages = parser.parse();
if (pages.isEmpty) {
// If no pages are returned, at least have one empty page to avoid errors.
pages = [[]];
}
return pages;
}
/// Navigate to the next page if available.
void _goToNextPage(int totalPages) {
if (_currentPage < totalPages - 1) {
setState(() {
_currentPage++;
});
}
}
/// Navigate to the previous page if available.
void _goToPrevPage() {
if (_currentPage > 0) {
setState(() {
_currentPage--;
});
}
}
/// Navigate directly to a specific page [index].
void _goToPage(int index) {
setState(() {
_currentPage = index;
});
}
/// Builds a navigation bar for pagination, allowing the user to move between
/// pages.
Widget _buildPageNavBar(BuildContext context, int totalPages) {
final prevButton = TextButton(
onPressed: _currentPage > 0 ? _goToPrevPage : null,
child: const Row(
children: [
Icon(Icons.chevron_left),
Text('Previous'),
],
),
);
final nextButton = TextButton(
onPressed: _currentPage < totalPages - 1
? () => _goToNextPage(totalPages)
: null,
child: const Row(
children: [
Text('Next'),
Icon(Icons.chevron_right),
],
),
);
// Create a set of number buttons for direct page navigation.
final numberButtons = List.generate(totalPages, (index) {
final isSelected = index == _currentPage;
return TextButton(
onPressed: () => _goToPage(index),
style: TextButton.styleFrom(
backgroundColor: isSelected ? Colors.lightBlueAccent : null,
shape: const CircleBorder(),
),
child: Text(
'${index + 1}',
style: TextStyle(
color: isSelected ? Colors.white : Colors.black,
),
),
);
});
// The nav bar is centered and scrollable if there are many pages.
return Center(
child: FractionallySizedBox(
child: SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
prevButton,
...numberButtons,
nextButton,
],
),
),
),
);
}
@override
Widget build(BuildContext context) {
// Parse the pages every time build() is called to reflect any state
// changes.
final pages = _buildPages();
final currentPageWidgets = pages[_currentPage];
// Show navigation only if multiple pages.
final showPagination = pages.length > 1;
return Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
// Display the widgets for the current page.
...currentPageWidgets,
// If pagination is needed, add spacing and the navigation bar.
if (showPagination) const SizedBox(height: 20),
if (showPagination) _buildPageNavBar(context, pages.length),
],
),
);
}
}