forked from dart-lang/dart-pad
-
Notifications
You must be signed in to change notification settings - Fork 0
/
embed.dart
1390 lines (1153 loc) · 41.7 KB
/
embed.dart
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'dart:convert';
import 'dart:html' hide Document, Console;
import 'dart:math' as math;
import 'package:mdc_web/mdc_web.dart';
import 'package:split/split.dart';
import 'check_localstorage.dart';
import 'completion.dart';
import 'context.dart';
import 'core/dependencies.dart';
import 'core/modules.dart';
import 'dart_pad.dart';
import 'editing/editor_codemirror.dart';
import 'elements/analysis_results_controller.dart';
import 'elements/button.dart';
import 'elements/console.dart';
import 'elements/counter.dart';
import 'elements/dialog.dart';
import 'elements/elements.dart';
import 'elements/material_tab_controller.dart';
import 'modules/dart_pad_module.dart';
import 'modules/dartservices_module.dart';
import 'search_controller.dart';
import 'services/common.dart';
import 'services/dartservices.dart';
import 'services/execution_iframe.dart';
import 'sharing/editor_ui.dart';
import 'sharing/gists.dart';
import 'src/ga.dart';
import 'util/detect_flutter.dart';
import 'util/query_params.dart' show queryParams;
const int defaultSplitterWidth = 6;
Embed? get embed => _embed;
Embed? _embed;
void init(EmbedOptions options) {
_embed = Embed(options);
}
// ignore: constant_identifier_names
enum EmbedMode { dart, flutter, html, inline, flutter_showcase }
class EmbedOptions {
final EmbedMode mode;
const EmbedOptions(this.mode);
}
/// An embeddable DartPad UI that provides the ability to test the user's code
/// snippet against a desired result.
class Embed extends EditorUi {
final EmbedOptions options;
var _executionButtonCount = 0;
late final MDCButton reloadGistButton;
late final MDCButton installButton;
late final MDCButton formatButton;
late final MDCButton showHintButton;
late final MDCButton copyCodeButton;
late final MDCButton openInDartPadButton;
late final MDCButton menuButton;
MDCButton? editorCodeInputTabButton;
late final DElement navBarElement;
late final EmbedTabController tabController;
late final DElement solutionTab;
late final MDCMenu menu;
late final DElement showTestCodeCheckmark;
late final DElement editableTestSolutionCheckmark;
bool _editableTestSolution = false;
bool _showTestCode = false;
late final Counter unreadConsoleCounter;
late final FlashBox testResultBox;
late final FlashBox hintBox;
final CodeMirrorFactory editorFactory = codeMirrorFactory;
@override
late final EmbedContext context;
late Splitter splitter;
late final Console consoleExpandController;
DElement? webOutputLabel;
late final DElement featureMessage;
late final MDCLinearProgress linearProgress;
Map<String, String> lastInjectedSourceCode = <String, String>{};
bool _editorIsBusy = true;
bool get editorIsBusy => _editorIsBusy;
@override
Document get currentDocument => context.dartDocument;
/// Toggles the state of several UI components based on whether the editor is
/// too busy to handle code changes, execute/reset requests, etc.
set editorIsBusy(bool value) {
_editorIsBusy = value;
if (value) {
linearProgress.root.classes.remove('hide');
} else {
linearProgress.root.classes.add('hide');
}
editor.readOnly = value;
runButton.disabled = value;
formatButton.disabled = value;
reloadGistButton.disabled = value;
showHintButton.disabled = value;
copyCodeButton.disabled = value;
}
Embed(this.options) {
_initHostListener();
if (!checkLocalStorage()) {
dialog.showOk(
'Missing browser features',
'DartPad requires localStorage to be enabled. '
'For more information, visit '
'<a href="https://dart.dev/tools/dartpad/troubleshoot" '
'target="_parent">dart.dev/tools/dartpad/troubleshoot</a>.');
}
tabController =
EmbedTabController(MDCTabBar(querySelector('.mdc-tab-bar')!), dialog);
final tabNames = options.mode == EmbedMode.html
? const ['dart', 'html', 'css', 'solution', 'test']
: const ['dart', 'solution', 'test'];
for (final tabName in tabNames) {
// The HTML ID and ga.sendEvent use 'editor' for the 'dart' tab.
final String contextName = (tabName == 'dart') ? 'editor' : tabName;
tabController.registerTab(
TabElement(querySelector('#$contextName-tab')!, name: tabName,
onSelect: () {
ga.sendEvent('edit', contextName);
context.switchTo(tabName);
editor.resize();
editor.focus();
}),
);
}
solutionTab = DElement(querySelector('#solution-tab')!);
navBarElement = DElement(querySelector('#navbar')!);
unreadConsoleCounter =
Counter(querySelector('#unread-console-counter') as SpanElement);
runButton = MDCButton(querySelector('#execute') as ButtonElement)
..onClick.listen((_) => handleRun());
// Flutter showcase mode
final editorCodeInputTabButtonElement =
querySelector('#editor-panel-show-code-button');
if (editorCodeInputTabButtonElement != null) {
editorCodeInputTabButton =
MDCButton(editorCodeInputTabButtonElement as ButtonElement)
..onClick.listen(
(_) => _toggleCodeInput(),
);
}
reloadGistButton = MDCButton(querySelector('#reload-gist') as ButtonElement)
..onClick.listen((_) {
if (gistId!.isNotEmpty || sampleId.isNotEmpty || githubParamsPresent) {
_loadAndShowGist();
} else {
_resetCode();
}
});
copyCodeButton =
MDCButton(querySelector('#copy-code') as ButtonElement, isIcon: true)
..onClick.listen((_) => _handleCopyCode());
openInDartPadButton = MDCButton(
querySelector('#open-in-dartpad') as ButtonElement,
isIcon: true)
..onClick.listen((_) => _handleOpenInDartPad());
showHintButton = MDCButton(querySelector('#show-hint') as ButtonElement)
..onClick.listen((_) {
final hintElement = DivElement()..text = context.hint;
final showSolutionButton = AnchorElement()
..style.cursor = 'pointer'
..text = 'Show solution';
showSolutionButton.onClick.listen((_) {
tabController.selectTab('solution', force: true);
});
hintBox.showElements([hintElement, showSolutionButton]);
ga.sendEvent('view', 'hint');
})
..element.hidden = true;
tabController.setTabVisibility('test', false);
showTestCodeCheckmark = DElement(querySelector('#show-test-checkmark')!);
editableTestSolutionCheckmark =
DElement(querySelector('#editable-test-solution-checkmark')!);
menuButton =
MDCButton(querySelector('#menu-button') as ButtonElement, isIcon: true)
..onClick.listen((_) {
menu.open = !menu.open!;
});
menu = MDCMenu(querySelector('#main-menu'))
..setAnchorCorner(AnchorCorner.bottomLeft)
..setAnchorElement(menuButton.element);
menu.listen('MDCMenu:selected', (e) {
final detail = (e as CustomEvent).detail as Map;
final selectedIndex = detail['index'] as int?;
switch (selectedIndex) {
case 0:
// Show test code
_showTestCode = !_showTestCode;
showTestCodeCheckmark.toggleClass('hide', !_showTestCode);
tabController.setTabVisibility('test', _showTestCode);
break;
case 1:
// Editable test/solution
_editableTestSolution = !_editableTestSolution;
editableTestSolutionCheckmark.toggleClass(
'hide', !_editableTestSolution);
context.testAndSolutionReadOnly = !_editableTestSolution;
break;
}
});
formatButton = MDCButton(querySelector('#format-code') as ButtonElement)
..onClick.listen(
(_) => _format(),
);
installButton = MDCButton(querySelector('#install-button') as ButtonElement)
..onClick.listen(
(_) => _showInstallPage(),
);
testResultBox = FlashBox(querySelector('#test-result-box') as DivElement);
hintBox = FlashBox(querySelector('#hint-box') as DivElement);
final editorTheme = isDarkMode ? 'darkpad' : 'dartpad';
editor =
editorFactory.createFromElement(querySelector('#user-code-editor')!)
..theme = editorTheme
..mode = 'dart'
..keyMap = window.localStorage['codemirror_keymap'] ?? 'default'
..showLineNumbers = true;
if (!showInstallButton) {
querySelector('#install-button')!.setAttribute('hidden', '');
}
executionService =
ExecutionServiceIFrame(querySelector('#frame') as IFrameElement)
..frameSrc =
isDarkMode ? 'scripts/frame_dark.html' : 'scripts/frame.html';
executionService.onStderr.listen((err) {
consoleExpandController.showOutput(err, error: true);
});
executionService.onStdout.listen((msg) {
consoleExpandController.showOutput(msg);
});
executionService.testResults.listen((result) {
if (result.messages.isEmpty) {
result.messages
.add(result.success ? 'All tests passed!' : 'Test failed.');
}
testResultBox.showStrings(
result.messages,
result.success ? FlashBoxStyle.success : FlashBoxStyle.warn,
);
if (result.success) {
window.parent?.postMessage({
'action': 'taskCompleted',
'recommendedReward': 'dash-hat',
'callbackId': 'string',
}, '*');
}
ga.sendEvent(
'execution', (result.success) ? 'test-success' : 'test-failure');
});
analysisResultsController = AnalysisResultsController(
DElement(querySelector('#issues')!),
DElement(querySelector('#issues-message')!),
DElement(querySelector('#issues-toggle')!),
snackbar,
)..onItemClicked.listen((item) {
if (item.sourceName == 'test.dart') {
// must be test editor
if (!_showTestCode) {
_showTestCode = true;
showTestCodeCheckmark.toggleClass('hide', !_showTestCode);
tabController.setTabVisibility('test', _showTestCode);
}
tabController.selectTab('test');
_jumpToTest(item.line, item.charStart, item.charLength, focus: true);
} else {
tabController.selectTab('dart');
_jumpTo(item.line, item.charStart, item.charLength, focus: true);
}
});
if (options.mode == EmbedMode.flutter ||
options.mode == EmbedMode.html ||
options.mode == EmbedMode.flutter_showcase) {
final controller = _ConsoleExpandController(
expandButton: querySelector('#console-output-header')!,
footer: querySelector('#console-output-footer')!,
expandIcon: querySelector('#console-expand-icon')!,
unreadCounter: unreadConsoleCounter,
consoleElement: querySelector('#console-output-container')!,
editorUi: this,
onSizeChanged: () {
editor.resize();
},
darkMode: isDarkMode);
consoleExpandController = controller;
if (shouldOpenConsole) {
controller.open();
}
} else {
consoleExpandController = Console(
DElement(querySelector('#console-output-container')!),
darkMode: isDarkMode);
}
final MDCButton clearConsoleButton = MDCButton(
querySelector('#console-clear-button') as ButtonElement,
isIcon: true);
clearConsoleButton.onClick.listen((event) {
clearOutput();
event.stopPropagation();
});
final webOutputLabelElement = querySelector('#web-output-label');
if (webOutputLabelElement != null) {
webOutputLabel = DElement(webOutputLabelElement);
}
featureMessage = DElement(querySelector('#feature-message')!);
featureMessage.toggleAttr('hidden', true);
linearProgress = MDCLinearProgress(querySelector('#progress-bar')!);
linearProgress.determinate = false;
_initBusyLights();
_initModules().then((_) => _init()).then((_) => _emitReady());
SearchController(editorFactory, editor, snackbar);
}
/// Initializes a listener for messages from the parent window. Allows this
/// embedded iframe to display and run arbitrary Dart code.
void _initHostListener() {
window.addEventListener('message', (Object? event) {
final data = (event as MessageEvent).data;
if (data is! Map) {
// Ignore unexpected messages
return;
}
final type = data['type'];
if (type == 'sourceCode') {
lastInjectedSourceCode =
Map<String, String>.from(data['sourceCode'] as Map);
_resetCode();
if (autoRunEnabled) {
handleRun();
}
}
});
}
/// Sends a ready message to the parent page
void _emitReady() {
window.parent!.postMessage(const {'sender': 'frame', 'type': 'ready'}, '*');
}
// Option for the GitHub gist ID that should be loaded into the editors.
String? get gistId {
final id = queryParams.gistId;
return isLegalGistId(id) ? id : '';
}
// Option for Light / Dark theme (defaults to light)
bool get isDarkMode {
return queryParams.theme == 'dark';
}
// Option to run the snippet immediately (defaults to false)
bool get autoRunEnabled {
return queryParams.autoRunEnabled;
}
bool get shouldOpenConsole {
return queryParams.shouldOpenConsole;
}
// Whether or not to show the Install button. (defaults to true)
bool get showInstallButton {
if (queryParams.hasShowInstallButton) {
return queryParams.showInstallButton;
}
// Default to true
return true;
}
// ID of an API Doc sample that should be loaded into the editors.
String get sampleId => queryParams.sampleId ?? '';
// An optional channel indicating which version of the API Docs to use when
// loading a sample. Defaults to the stable channel.
FlutterSdkChannel get sampleChannel {
final channelStr = queryParams.sampleChannel?.toLowerCase();
if (channelStr == 'master') {
return FlutterSdkChannel.master;
} else if (channelStr == 'beta') {
return FlutterSdkChannel.beta;
} else {
return FlutterSdkChannel.stable;
}
}
// GitHub params for loading an exercise from a repo. The first three are
// required to load something, while the fourth, gh_ref, is an optional branch
// name or commit SHA.
String get githubOwner => queryParams.githubOwner ?? '';
String get githubRepo => queryParams.githubRepo ?? '';
String get githubPath => queryParams.githubPath ?? '';
String? get githubRef => queryParams.githubRef;
bool get githubParamsPresent =>
githubOwner.isNotEmpty && githubRepo.isNotEmpty && githubPath.isNotEmpty;
Future<void> _initModules() async {
final modules = ModuleManager();
modules.register(DartPadModule());
modules.register(DartServicesModule());
await modules.start();
}
void _initBusyLights() {
busyLight = DBusyLight(querySelector('#dartbusy')!);
}
void _init() {
deps[GistLoader] = GistLoader.defaultFilters();
deps[Analytics] = Analytics();
final channel = queryParams.channel;
if (Channel.urlMapping.keys.contains(channel)) {
dartServices.rootUrl = Channel.urlMapping[channel]!;
}
updateVersions();
context = EmbedContext(editor, !_editableTestSolution);
editorFactory.registerCompleter(
'dart', DartCompleter(dartServices, context.dartDocument));
context.onDartDirty.listen((_) => busyLight.on());
context.onDartReconcile.listen((_) => performAnalysis());
initKeyBindings();
var horizontal = true;
final webOutput = querySelector('#web-output')!;
List<Element> splitterElements;
if (options.mode == EmbedMode.flutter || options.mode == EmbedMode.html) {
final editorAndConsoleContainer =
querySelector('#editor-and-console-container')!;
splitterElements = [editorAndConsoleContainer, webOutput];
} else if (options.mode == EmbedMode.inline) {
final editorContainer = querySelector('#editor-container')!;
final consoleView = querySelector('#console-view')!;
consoleView.removeAttribute('hidden');
splitterElements = [editorContainer, consoleView];
horizontal = false;
} else if (options.mode == EmbedMode.flutter_showcase) {
// do not split elements in flutter_showcase mode
splitterElements = <Element>[];
} else {
final editorContainer = querySelector('#editor-container')!;
final consoleView = querySelector('#console-view')!;
consoleView.removeAttribute('hidden');
splitterElements = [editorContainer, consoleView];
}
// Flutter showcase mode does not show code input by default
if (options.mode == EmbedMode.flutter_showcase) {
querySelector('#editor-and-console-container')
?.setAttribute('hidden', '');
_updateShowcase();
} else {
splitter = flexSplit(
splitterElements,
horizontal: horizontal,
gutterSize: defaultSplitterWidth,
// set initial sizes (in percentages)
sizes: [initialSplitPercent, (100 - initialSplitPercent)],
// set the minimum sizes (in pixels)
minSize: [100, 100],
);
listenForResize(splitterElements[0]);
}
if (gistId!.isNotEmpty || sampleId.isNotEmpty || githubParamsPresent) {
_loadAndShowGist(analyze: false);
}
if (gistId!.isEmpty) {
openInDartPadButton.toggleAttr('hidden', true);
}
// set enabled/disabled state of various buttons
editorIsBusy = false;
}
@override
void initKeyBindings() {
keys.bind(const ['ctrl-space', 'macctrl-space'], () {
if (editor.hasFocus) {
editor.showCompletions();
}
}, 'Completion');
keys.bind(const ['alt-enter'], () {
if (context.focusedEditor == 'dart') {
editor.showCompletions(onlyShowFixes: true);
}
}, 'Quick fix');
keys.bind(const ['shift-ctrl-f', 'shift-macctrl-f'], () {
_format();
}, 'Format');
document.onKeyUp.listen(_handleAutoCompletion);
super.initKeyBindings();
}
Future<void> _loadAndShowGist({bool analyze = true}) async {
if (gistId!.isEmpty && sampleId.isEmpty && !githubParamsPresent) {
print('Cannot load gist: neither id, sample_id, nor GitHub repo info is '
'present.');
return;
}
editorIsBusy = true;
final loader = deps[GistLoader] as GistLoader?;
try {
Gist gist;
if (gistId!.isNotEmpty) {
gist = await loader!.loadGist(gistId);
} else if (sampleId.isNotEmpty) {
// Right now, there are only two hosted versions of the docs: master and
// stable. Default to stable for dev and beta.
final channel = (sampleChannel == FlutterSdkChannel.master)
? FlutterSdkChannel.master
: FlutterSdkChannel.stable;
gist = await loader!.loadGistFromAPIDocs(sampleId, channel);
} else {
gist = await loader!.loadGistFromRepo(
owner: githubOwner,
repo: githubRepo,
path: githubPath,
ref: githubRef,
);
}
setContextSources(<String, String>{
'main.dart': gist.getFile('main.dart')?.content ?? '',
'index.html': gist.getFile('index.html')?.content ?? '',
'styles.css': gist.getFile('styles.css')?.content ?? '',
'solution.dart': gist.getFile('solution.dart')?.content ?? '',
'test.dart': gist.getFile('test.dart')?.content ?? '',
'hint.txt': gist.getFile('hint.txt')?.content ?? '',
});
if (analyze) {
unawaited(performAnalysis());
}
if (autoRunEnabled) {
unawaited(handleRun());
}
} on GistLoaderException catch (ex) {
// No gist was loaded, so clear the editors.
setContextSources(<String, String>{});
if (ex.failureType == GistLoaderFailureType.contentNotFound) {
await dialog.showOk(
'Error loading gist',
'No gist was found for the gist ID, sample ID, or repository '
'information provided.');
} else if (ex.failureType == GistLoaderFailureType.rateLimitExceeded) {
await dialog.showOk(
'Error loading files',
'GitHub\'s rate limit for '
'API requests has been exceeded. This is typically caused by '
'repeatedly loading a single page that has many DartPad embeds or '
'when many users are accessing DartPad (and therefore GitHub\'s '
'API server) from a single, shared IP address. Quotas are '
'typically renewed within an hour, so the best course of action is '
'to try back later.');
} else if (ex.failureType ==
GistLoaderFailureType.invalidExerciseMetadata) {
if (ex.message != null) {
print(ex.message);
}
await dialog.showOk(
'Error loading files',
'DartPad could not load the requested exercise. Either one of the '
'required files wasn\'t available, or the exercise metadata was '
'invalid.');
} else {
await dialog.showOk('Error loading files',
'An error occurred while the requested files.');
}
}
}
void _resetCode() {
setContextSources(lastInjectedSourceCode);
Timer.run(() => unawaited(performAnalysis()));
}
void _handleCopyCode() {
final textElement = document.createElement('textarea') as TextAreaElement;
textElement.value = _getActiveSourceCode();
document.body!.append(textElement);
textElement.select();
document.execCommand('copy');
textElement.remove();
}
void _handleOpenInDartPad() {
window.open(window.location.href, 'DartPad_$gistId');
}
/// Returns the name of the current embed mode
/// (html, flutter, inline, dart, flutter_showcase).
String get _modeName {
return options.mode.toString().split('.').last;
}
String _getActiveSourceCode() {
final activeTabName = tabController.selectedTab.name;
switch (activeTabName) {
case 'dart':
return context.dartSource;
case 'css':
return context.cssSource;
case 'html':
return context.htmlSource;
case 'solution':
return context.solution;
case 'test':
return context.testMethod;
default:
return context.dartSource;
}
}
void setContextSources(Map<String, String> sources) {
context.dartSource = sources['main.dart'] ?? '';
context.solution = sources['solution.dart'] ?? '';
context.testMethod = sources['test.dart'] ?? '';
context.htmlSource = sources['index.html'] ?? '';
context.cssSource = sources['styles.css'] ?? '';
context.hint = sources['hint.txt'] ?? '';
if (sources.containsKey('ga_id')) {
_sendVirtualPageView(sources['ga_id']);
}
tabController.setTabVisibility(
'test', context.testMethod.isNotEmpty && _showTestCode);
menuButton.toggleAttr('hidden', false);
showHintButton.element.hidden = context.hint.isEmpty;
solutionTab.toggleAttr('hidden', context.solution.isEmpty);
editorIsBusy = false;
}
@override
String get fullDartSource => '${context.dartSource}\n${context.testMethod}\n'
'${executionService.testResultDecoration}';
@override
Future<bool> handleRun() async {
if (editorIsBusy) {
return false;
}
if (context.dartSource.isEmpty) {
unawaited(dialog.showOk(
'No code to execute',
'Try entering some Dart code into the "Dart" tab, then click this '
'button again to run it.'));
return false;
}
_executionButtonCount++;
ga.sendEvent('execution', 'initiated', label: '$_executionButtonCount');
editorIsBusy = true;
testResultBox.hide();
hintBox.hide();
consoleExpandController.clear();
final success = await super.handleRun();
editorIsBusy = false;
// The iframe will show Flutter output for the rest of the lifetime of the
// app, so hide the label.
webOutputLabel?.setAttr('hidden');
return success;
}
void _toggleCodeInput() {
final editorAndConsoleContainer =
querySelector('#editor-and-console-container')!;
final webOutput = querySelector('#web-output')!;
final isEditorHidden = editorAndConsoleContainer.hidden;
if (isEditorHidden) {
// show code input, hide UI output
editorCodeInputTabButton!.text = 'Hide code';
editorAndConsoleContainer.removeAttribute('hidden');
webOutput.setAttribute('hidden', '');
_updateShowcase(isEditorVisible: true);
// run format to force to display the code & show caret in the editor
_format();
} else {
// hide code input, show UI output
editorCodeInputTabButton!.text = 'Show code';
editorAndConsoleContainer.setAttribute('hidden', '');
webOutput.removeAttribute('hidden');
_updateShowcase();
}
}
void _updateShowcase({bool isEditorVisible = false}) {
final webOutput = querySelector('#web-output')!;
final editorAndConsoleContainer =
querySelector('#editor-and-console-container')!;
splitter = flexSplit(
<Element>[isEditorVisible ? editorAndConsoleContainer : webOutput],
horizontal: true,
gutterSize: 0,
sizes: [100],
minSize: [100],
);
}
void _sendVirtualPageView(String? id) {
final url = Uri.parse(window.location.toString());
final newParams = Map<String, String?>.from(url.queryParameters);
newParams['ga_id'] = id;
final pageName = url.replace(queryParameters: newParams);
final path = '${pageName.path}?${pageName.query}';
ga.sendPage(pageName: path);
}
@override
void displayIssues(List<AnalysisIssue> issues) {
testResultBox.hide();
hintBox.hide();
// Handle possiblity of issues in appended test code.
analysisResultsController
.display(detectIssuesInTestSourceAndModifyIssuesAccordingly(issues));
}
// We append test source code to the user's source code, because of
// this we possibly have a special situation..
// There could be warnings or errors in the *TEST* code that is being
// appended to the user's dart source.
// This can result in issues with line numbers that are
// outside the user's dart source. This would confusing to the users.
// We are going to do one of two things:
// - If the test source is currently HIDDEN and the issue kind is
// not and `error` (it is `info` or `warning`) then we will REMOVE
// the issue from the list so as to "hide" it.
// - If the test source is showing, *or* if the issue is an `error`, we are
// going to adjust the line number so it reflects where it is in the
// test source editor, and we will set the `sourceName` for the issue to
// `test.dart`.
List<AnalysisIssue> detectIssuesInTestSourceAndModifyIssuesAccordingly(
List<AnalysisIssue> issues) {
final int dartSourceLineCount = context.dartSourceLineCount;
final int dartSourceCharCount = context.dartSource.length;
issues = issues.map((issue) {
if (issue.line > dartSourceLineCount) {
// This is in the test source, do we adjust or hide it ?
// (We never hide errors).
if (issue.kind != 'error' && !_showTestCode) {
// We want to remove the message later so flag it.
return AnalysisIssue(line: -99);
} else {
// Adjust the line number, charStart and set sourceName
// to indicate this issue is in the test code.
return AnalysisIssue(
kind: issue.kind,
line: (issue.line - dartSourceLineCount - 1),
message: issue.message,
sourceName: 'test.dart',
hasFixes: issue.hasFixes,
charStart: (issue.charStart - dartSourceCharCount),
charLength: issue.charLength,
url: issue.url,
diagnosticMessages: issue.diagnosticMessages,
correction: issue.correction);
}
}
return issue;
}).toList();
issues.removeWhere((issue) => issue.line == -99);
return issues;
}
void _showInstallPage() {
if (_modeName == 'dart' || _modeName == 'html') {
ga.sendEvent('main', 'install-dart');
window.open('https://dart.dev/get-dart', '_blank');
} else {
ga.sendEvent('main', 'install-flutter');
window.open('https://flutter.dev/get-started/install', '_blank');
}
}
Future<void> _format() async {
final originalSource = context.dartSource;
final input = SourceRequest()..source = originalSource;
try {
formatButton.disabled = true;
final result =
await dartServices.format(input).timeout(serviceCallTimeout);
busyLight.reset();
formatButton.disabled = false;
// Check that the user hasn't edited the source since the format request.
if (originalSource == context.dartSource) {
// And, check that the format request did modify the source code.
if (originalSource != result.newString) {
context.dartSource = result.newString;
unawaited(performAnalysis());
}
}
} catch (e) {
busyLight.reset();
formatButton.disabled = false;
print(e);
}
}
void _handleAutoCompletion(KeyboardEvent e) {
if (context.focusedEditor == 'dart' &&
editor.hasFocus &&
e.keyCode == KeyCode.PERIOD) {
editor.showCompletions(autoInvoked: true);
}
}
int get initialSplitPercent {
const defaultSplitPercentage = 70;
var s = queryParams.initialSplit ?? defaultSplitPercentage;
// keep the split within the range [5, 95]
s = math.min(s, 95);
s = math.max(s, 5);
return s;
}
void _jumpTo(int line, int charStart, int charLength, {bool focus = false}) {
final doc = context.dartDocument;
doc.select(
doc.posFromIndex(charStart), doc.posFromIndex(charStart + charLength));
if (focus) context.focus();
}
void _jumpToTest(int line, int charStart, int charLength,
{bool focus = false}) {
final doc = context.testDocument;
doc.select(
doc.posFromIndex(charStart), doc.posFromIndex(charStart + charLength));
if (focus) context.focus();
}
@override
void clearOutput() {
consoleExpandController.clear();
}
@override
bool get shouldAddFirebaseJs => hasFirebaseContent(fullDartSource);
@override
bool get shouldCompileDDC =>
options.mode == EmbedMode.flutter ||
options.mode == EmbedMode.flutter_showcase;
@override
void showOutput(String message, {bool error = false}) {
consoleExpandController.showOutput(message, error: error);
}
}
// material-components-web uses specific classes for its navigation styling,
// rather than an attribute. This class extends the tab controller code to also
// toggle that class.
class EmbedTabController extends MaterialTabController {
final Dialog _dialog;
bool _userHasSeenSolution = false;
EmbedTabController(super.tabBar, this._dialog);
@override
void registerTab(TabElement tab) {
tabs.add(tab);
try {
tab.onClick
.listen((_) => selectTab(tab.name, force: _userHasSeenSolution));
} catch (e, st) {
print('Error from registerTab: $e\n$st');
}
}
/// This method will throw if the tabName is not the name of a current tab.
@override
Future<void> selectTab(String tabName, {bool force = false}) async {
// Show a confirmation dialog if the solution tab is tapped
if (tabName == 'solution' && !force) {
final result = await _dialog.showYesNo(
'Show solution?',
'If you just want a hint, click <span style="font-weight:bold">Cancel'
'</span> and then <span style="font-weight:bold">Hint</span>.',
yesText: 'Show solution',
noText: 'Cancel',
);
// Go back to the editor tab
if (result == DialogResult.no || result == DialogResult.cancel) {
tabName = 'dart';
}
}
if (tabName == 'solution') {
ga.sendEvent('view', 'solution');
_userHasSeenSolution = true;
}
await super.selectTab(tabName);
}
}