Reverse the sense of the terms snippet and sample. (#48254)
This commit is contained in:
committed by
Flutter GitHub Bot
parent
dbed575c01
commit
fabf4e3d0d
@@ -107,10 +107,10 @@ class SampleCheckerException implements Exception {
|
||||
/// error output from the analyzer is parsed for details, and the problem
|
||||
/// locations are translated back to the source location.
|
||||
///
|
||||
/// For snippets, the snippets are generated using the snippets tool, and they
|
||||
/// are analyzed with the samples. If errors are found in snippets, then the
|
||||
/// line number of the start of the snippet is given instead of the actual error
|
||||
/// line, since snippets get reformatted when written, and the line numbers
|
||||
/// For samples, the samples are generated using the snippets tool, and they
|
||||
/// are analyzed with the snippets. If errors are found in samples, then the
|
||||
/// line number of the start of the sample is given instead of the actual error
|
||||
/// line, since samples get reformatted when written, and the line numbers
|
||||
/// don't necessarily match. It does, however, print the source of the
|
||||
/// problematic line.
|
||||
class SampleChecker {
|
||||
@@ -209,7 +209,7 @@ class SampleChecker {
|
||||
Map<String, List<AnalysisError>> errors = <String, List<AnalysisError>>{};
|
||||
try {
|
||||
final Map<String, Section> sections = <String, Section>{};
|
||||
final Map<String, Snippet> snippets = <String, Snippet>{};
|
||||
final Map<String, Sample> snippets = <String, Sample>{};
|
||||
_extractSamples(sections, snippets);
|
||||
errors = _analyze(_tempDirectory, sections, snippets);
|
||||
} finally {
|
||||
@@ -242,10 +242,10 @@ class SampleChecker {
|
||||
/// Creates a name for the snippets tool to use for the snippet ID from a
|
||||
/// filename and starting line number.
|
||||
String _createNameFromSource(String prefix, String filename, int start) {
|
||||
String snippetId = path.split(filename).join('.');
|
||||
snippetId = path.basenameWithoutExtension(snippetId);
|
||||
snippetId = '$prefix.$snippetId.$start';
|
||||
return snippetId;
|
||||
String sampleId = path.split(filename).join('.');
|
||||
sampleId = path.basenameWithoutExtension(sampleId);
|
||||
sampleId = '$prefix.$sampleId.$start';
|
||||
return sampleId;
|
||||
}
|
||||
|
||||
// Precompiles the snippets tool if _snippetsSnapshotPath isn't set yet, and
|
||||
@@ -273,42 +273,42 @@ class SampleChecker {
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes out the given [snippet] to an output file in the [_tempDirectory] and
|
||||
/// Writes out the given sample to an output file in the [_tempDirectory] and
|
||||
/// returns the output file.
|
||||
File _writeSnippet(Snippet snippet) {
|
||||
File _writeSample(Sample sample) {
|
||||
// Generate the snippet.
|
||||
final String snippetId = _createNameFromSource('snippet', snippet.start.filename, snippet.start.line);
|
||||
final String inputName = '$snippetId.input';
|
||||
final String sampleId = _createNameFromSource('sample', sample.start.filename, sample.start.line);
|
||||
final String inputName = '$sampleId.input';
|
||||
// Now we have a filename like 'lib.src.material.foo_widget.123.dart' for each snippet.
|
||||
final File inputFile = File(path.join(_tempDirectory.path, inputName))..createSync(recursive: true);
|
||||
inputFile.writeAsStringSync(snippet.input.join('\n'));
|
||||
final File outputFile = File(path.join(_tempDirectory.path, '$snippetId.dart'));
|
||||
inputFile.writeAsStringSync(sample.input.join('\n'));
|
||||
final File outputFile = File(path.join(_tempDirectory.path, '$sampleId.dart'));
|
||||
final List<String> args = <String>[
|
||||
'--output=${outputFile.absolute.path}',
|
||||
'--input=${inputFile.absolute.path}',
|
||||
...snippet.args,
|
||||
...sample.args,
|
||||
];
|
||||
if (verbose)
|
||||
print('Generating snippet for ${snippet.start?.filename}:${snippet.start?.line}');
|
||||
print('Generating sample for ${sample.start?.filename}:${sample.start?.line}');
|
||||
final ProcessResult process = _runSnippetsScript(args);
|
||||
if (verbose)
|
||||
stderr.write('${process.stderr}');
|
||||
if (process.exitCode != 0) {
|
||||
throw SampleCheckerException(
|
||||
'Unable to create snippet for ${snippet.start.filename}:${snippet.start.line} '
|
||||
'Unable to create sample for ${sample.start.filename}:${sample.start.line} '
|
||||
'(using input from ${inputFile.path}):\n${process.stdout}\n${process.stderr}',
|
||||
file: snippet.start.filename,
|
||||
line: snippet.start.line,
|
||||
file: sample.start.filename,
|
||||
line: sample.start.line,
|
||||
);
|
||||
}
|
||||
return outputFile;
|
||||
}
|
||||
|
||||
/// Extracts the samples from the Dart files in [_flutterPackage], writes them
|
||||
/// to disk, and adds them to the appropriate [sectionMap] or [snippetMap].
|
||||
void _extractSamples(Map<String, Section> sectionMap, Map<String, Snippet> snippetMap) {
|
||||
/// to disk, and adds them to the appropriate [sectionMap] or [sampleMap].
|
||||
void _extractSamples(Map<String, Section> sectionMap, Map<String, Sample> sampleMap) {
|
||||
final List<Section> sections = <Section>[];
|
||||
final List<Snippet> snippets = <Snippet>[];
|
||||
final List<Sample> samples = <Sample>[];
|
||||
|
||||
for (final File file in _listDartFiles(_flutterPackage, recursive: true)) {
|
||||
final String relativeFilePath = path.relative(file.path, from: _flutterPackage.path);
|
||||
@@ -334,12 +334,12 @@ class SampleChecker {
|
||||
throw SampleCheckerException('Snippet section unterminated.', file: relativeFilePath, line: lineNumber);
|
||||
}
|
||||
if (_dartDocSampleEndRegex.hasMatch(trimmedLine)) {
|
||||
snippets.add(
|
||||
Snippet(
|
||||
samples.add(
|
||||
Sample(
|
||||
start: startLine,
|
||||
input: block,
|
||||
args: snippetArgs,
|
||||
serial: snippets.length,
|
||||
serial: samples.length,
|
||||
),
|
||||
);
|
||||
snippetArgs = <String>[];
|
||||
@@ -407,7 +407,7 @@ class SampleChecker {
|
||||
startLine = Line('', filename: relativeFilePath, line: lineNumber + 1, indent: 3);
|
||||
inPreamble = true;
|
||||
} else if (sampleMatch != null) {
|
||||
inSnippet = sampleMatch != null && (sampleMatch[1] == 'snippet' || sampleMatch[1] == 'dartpad');
|
||||
inSnippet = sampleMatch != null && (sampleMatch[1] == 'sample' || sampleMatch[1] == 'dartpad');
|
||||
if (inSnippet) {
|
||||
startLine = Line(
|
||||
'',
|
||||
@@ -425,7 +425,7 @@ class SampleChecker {
|
||||
inSampleSection = !inSnippet;
|
||||
} else if (RegExp(r'///\s*#+\s+[Ss]ample\s+[Cc]ode:?$').hasMatch(trimmedLine)) {
|
||||
throw SampleCheckerException(
|
||||
"Found deprecated '## Sample code' section: use {@tool sample}...{@end-tool} instead.",
|
||||
"Found deprecated '## Sample code' section: use {@tool snippet}...{@end-tool} instead.",
|
||||
file: relativeFilePath,
|
||||
line: lineNumber,
|
||||
);
|
||||
@@ -437,10 +437,10 @@ class SampleChecker {
|
||||
for (final Section section in sections) {
|
||||
sectionMap[_writeSection(section).path] = section;
|
||||
}
|
||||
for (final Snippet snippet in snippets) {
|
||||
final File snippetFile = _writeSnippet(snippet);
|
||||
snippet.contents = snippetFile.readAsLinesSync();
|
||||
snippetMap[snippetFile.absolute.path] = snippet;
|
||||
for (final Sample sample in samples) {
|
||||
final File snippetFile = _writeSample(sample);
|
||||
sample.contents = snippetFile.readAsLinesSync();
|
||||
sampleMap[snippetFile.absolute.path] = sample;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -506,7 +506,7 @@ linter:
|
||||
|
||||
/// Writes out a sample section to the disk and returns the file.
|
||||
File _writeSection(Section section) {
|
||||
final String sectionId = _createNameFromSource('sample', section.start.filename, section.start.line);
|
||||
final String sectionId = _createNameFromSource('snippet', section.start.filename, section.start.line);
|
||||
final File outputFile = File(path.join(_tempDirectory.path, '$sectionId.dart'))..createSync(recursive: true);
|
||||
final List<Line> mainContents = <Line>[
|
||||
...headers,
|
||||
@@ -520,7 +520,7 @@ linter:
|
||||
|
||||
/// Invokes the analyzer on the given [directory] and returns the stdout.
|
||||
List<String> _runAnalyzer(Directory directory) {
|
||||
print('Starting analysis of samples.');
|
||||
print('Starting analysis of code samples.');
|
||||
_createConfigurationFiles(directory);
|
||||
final ProcessResult result = Process.runSync(
|
||||
_flutter,
|
||||
@@ -556,7 +556,7 @@ linter:
|
||||
Map<String, List<AnalysisError>> _analyze(
|
||||
Directory directory,
|
||||
Map<String, Section> sections,
|
||||
Map<String, Snippet> snippets,
|
||||
Map<String, Sample> samples,
|
||||
) {
|
||||
final List<String> errors = _runAnalyzer(directory);
|
||||
final Map<String, List<AnalysisError>> analysisErrors = <String, List<AnalysisError>>{};
|
||||
@@ -587,7 +587,7 @@ linter:
|
||||
final String line = parts[4];
|
||||
final String column = parts[5];
|
||||
final String errorCode = parts[6];
|
||||
final int lineNumber = int.parse(line, radix: 10) - (isSample ? headerLength : 0);
|
||||
final int lineNumber = int.parse(line, radix: 10) - (isSnippet ? headerLength : 0);
|
||||
final int columnNumber = int.parse(column, radix: 10);
|
||||
if (lineNumber < 0 && errorCode == 'unused_import') {
|
||||
// We don't care about unused imports.
|
||||
@@ -621,7 +621,7 @@ linter:
|
||||
// We don't really care if sample code isn't used!
|
||||
continue;
|
||||
}
|
||||
if (isSnippet) {
|
||||
if (isSample) {
|
||||
addAnalysisError(
|
||||
file,
|
||||
AnalysisError(
|
||||
@@ -630,7 +630,7 @@ linter:
|
||||
message,
|
||||
errorCode,
|
||||
null,
|
||||
snippet: snippets[file.path],
|
||||
sample: samples[file.path],
|
||||
),
|
||||
);
|
||||
} else {
|
||||
@@ -794,7 +794,7 @@ class Line {
|
||||
String toString() => '$filename:$line: $code';
|
||||
}
|
||||
|
||||
/// A class to represent a section of sample code, marked by "{@tool sample}...{@end-tool}".
|
||||
/// A class to represent a section of sample code, marked by "{@tool snippet}...{@end-tool}".
|
||||
class Section {
|
||||
const Section(this.code);
|
||||
factory Section.combine(List<Section> sections) {
|
||||
@@ -841,12 +841,12 @@ class Section {
|
||||
final List<Line> code;
|
||||
}
|
||||
|
||||
/// A class to represent a snippet in the dartdoc comments, marked by
|
||||
/// "{@tool snippet ...}...{@end-tool}". Snippets are processed separately from
|
||||
/// regular samples, because they must be injected into templates in order to be
|
||||
/// A class to represent a sample in the dartdoc comments, marked by
|
||||
/// "{@tool sample ...}...{@end-tool}". Samples are processed separately from
|
||||
/// regular snippets, because they must be injected into templates in order to be
|
||||
/// analyzed.
|
||||
class Snippet {
|
||||
Snippet({this.start, List<String> input, List<String> args, this.serial}) {
|
||||
class Sample {
|
||||
Sample({this.start, List<String> input, List<String> args, this.serial}) {
|
||||
this.input = input.toList();
|
||||
this.args = args.toList();
|
||||
}
|
||||
@@ -858,7 +858,7 @@ class Snippet {
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
final StringBuffer buf = StringBuffer('snippet ${args.join(' ')}\n');
|
||||
final StringBuffer buf = StringBuffer('sample ${args.join(' ')}\n');
|
||||
int count = start.line;
|
||||
for (final String line in input) {
|
||||
buf.writeln(' ${count.toString().padLeft(4, ' ')}: $line');
|
||||
@@ -878,7 +878,7 @@ class AnalysisError {
|
||||
this.message,
|
||||
this.errorCode,
|
||||
this.source, {
|
||||
this.snippet,
|
||||
this.sample,
|
||||
});
|
||||
|
||||
final int line;
|
||||
@@ -886,15 +886,15 @@ class AnalysisError {
|
||||
final String message;
|
||||
final String errorCode;
|
||||
final Line source;
|
||||
final Snippet snippet;
|
||||
final Sample sample;
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
if (source != null) {
|
||||
return '${source.toStringWithColumn(column)}\n>>> $message ($errorCode)';
|
||||
} else if (snippet != null) {
|
||||
return 'In snippet starting at '
|
||||
'${snippet.start.filename}:${snippet.start.line}:${snippet.contents[line - 1]}\n'
|
||||
} else if (sample != null) {
|
||||
return 'In sample starting at '
|
||||
'${sample.start.filename}:${sample.start.line}:${sample.contents[line - 1]}\n'
|
||||
'>>> $message ($errorCode)';
|
||||
} else {
|
||||
return '<source unknown>:$line:$column\n>>> $message ($errorCode)';
|
||||
|
||||
@@ -22,7 +22,7 @@
|
||||
/// blabla 0.0, the penzance blabla is blabla not blabla at all. Bla the blabla
|
||||
/// 1.0, the blabla is blabla blabla blabla an blabla blabla.
|
||||
///
|
||||
/// {@tool sample}
|
||||
/// {@tool snippet}
|
||||
/// Bla blabla blabla some [Text] when the `_blabla` blabla blabla is true, and
|
||||
/// blabla it when it is blabla:
|
||||
///
|
||||
@@ -54,7 +54,7 @@
|
||||
/// ```
|
||||
/// {@end-tool}
|
||||
///
|
||||
/// {@tool sample}
|
||||
/// {@tool snippet}
|
||||
/// Bla blabla blabla some [Text] when the `_blabla` blabla blabla is true, and
|
||||
/// blabla finale blabla:
|
||||
///
|
||||
@@ -66,7 +66,7 @@
|
||||
/// ```
|
||||
/// {@end-tool}
|
||||
///
|
||||
/// {@tool sample}
|
||||
/// {@tool snippet}
|
||||
/// regular const constructor
|
||||
///
|
||||
/// ```dart
|
||||
@@ -74,21 +74,21 @@
|
||||
/// ```
|
||||
/// {@end-tool}
|
||||
///
|
||||
/// {@tool sample}
|
||||
/// {@tool snippet}
|
||||
/// const private constructor
|
||||
/// ```dart
|
||||
/// const _Text('Poor wandering ones!')
|
||||
/// ```
|
||||
/// {@end-tool}
|
||||
///
|
||||
/// {@tool sample}
|
||||
/// {@tool snippet}
|
||||
/// yet another const private constructor
|
||||
/// ```dart
|
||||
/// const _Text.__('Poor wandering ones!')
|
||||
/// ```
|
||||
/// {@end-tool}
|
||||
///
|
||||
/// {@tool sample}
|
||||
/// {@tool snippet}
|
||||
/// const variable
|
||||
///
|
||||
/// ```dart
|
||||
@@ -96,7 +96,7 @@
|
||||
/// ```
|
||||
/// {@end-tool}
|
||||
///
|
||||
/// {@tool sample}
|
||||
/// {@tool snippet}
|
||||
/// more const variables
|
||||
///
|
||||
/// ```dart
|
||||
|
||||
@@ -27,7 +27,7 @@ void main() {
|
||||
]);
|
||||
expect(stdoutLines, <String>[
|
||||
'Found 7 sample code sections.',
|
||||
'Starting analysis of samples.',
|
||||
'Starting analysis of code samples.',
|
||||
'',
|
||||
]);
|
||||
}, skip: Platform.isWindows);
|
||||
|
||||
@@ -9,8 +9,8 @@ in the source code into API documentation, as seen on https://api.flutter.dev/.
|
||||
## Table of Contents
|
||||
|
||||
- [Types of code blocks](#types-of-code-blocks)
|
||||
- [Sample tool](#sample-tool)
|
||||
- [Snippet tool](#snippet-tool)
|
||||
- [Sample tool](#sample-tool)
|
||||
- [Skeletons](#skeletons)
|
||||
- [Test Doc Generation Workflow](#test-doc-generation-workflow)
|
||||
|
||||
@@ -18,21 +18,21 @@ in the source code into API documentation, as seen on https://api.flutter.dev/.
|
||||
|
||||
There's two kinds of code blocks.
|
||||
|
||||
* samples, which are more or less context-free snippets that we
|
||||
* snippets, which are more or less context-free code snippets that we
|
||||
magically determine how to analyze, and
|
||||
|
||||
* snippets, which get placed into a full-fledged application, and can
|
||||
* samples, which get placed into a full-fledged application, and can
|
||||
be actually executed inline in the documentation using DartPad.
|
||||
|
||||
### Sample Tool
|
||||
### Snippet Tool
|
||||
|
||||

|
||||

|
||||
|
||||
The code `sample` tool generates a block containing a description and example
|
||||
code. Here is an example of the code `sample` tool in use:
|
||||
The code `snippet` tool generates a block containing a description and example
|
||||
code. Here is an example of the code `snippet` tool in use:
|
||||
|
||||
```dart
|
||||
/// {@tool sample}
|
||||
/// {@tool snippet}
|
||||
///
|
||||
/// If the avatar is to have an image, the image should be specified in the
|
||||
/// [backgroundImage] property:
|
||||
@@ -48,13 +48,13 @@ code. Here is an example of the code `sample` tool in use:
|
||||
This will generate sample code that can be copied to the clipboard and added
|
||||
to existing applications.
|
||||
|
||||
This uses the skeleton for [sample](config/skeletons/sample.html)
|
||||
This uses the skeleton for [snippet](config/skeletons/snippet.html)
|
||||
snippets when generating the HTML to put into the Dart docs.
|
||||
|
||||
#### Analysis
|
||||
|
||||
The `../bots/analyze-sample-code.dart` script finds code inside the
|
||||
`@tool sample` sections and uses the Dart analyzer to check them.
|
||||
`@tool snippet` sections and uses the Dart analyzer to check them.
|
||||
|
||||
There are several kinds of sample code you can specify:
|
||||
|
||||
@@ -91,16 +91,16 @@ You can assume that the entire Flutter framework and most common
|
||||
`dart:*` packages are imported and in scope; `dart:math` as `math` and
|
||||
`dart:ui` as `ui`.
|
||||
|
||||
### Snippet Tool
|
||||
### Sample Tool
|
||||
|
||||

|
||||

|
||||
|
||||
The code `snippet` tool can expand sample code into full Flutter applications.
|
||||
The code `sample` tool can expand sample code into full Flutter applications.
|
||||
These sample applications can be directly copied and used to demonstrate the
|
||||
API's functionality in a sample application:
|
||||
|
||||
```dart
|
||||
/// {@tool snippet --template=stateless_widget_material}
|
||||
/// {@tool sample --template=stateless_widget_material}
|
||||
/// This example shows how to make a simple [FloatingActionButton] in a
|
||||
/// [Scaffold], with a pink [backgroundColor] and a thumbs up [Icon].
|
||||
///
|
||||
@@ -126,10 +126,10 @@ API's functionality in a sample application:
|
||||
/// {@end-tool}
|
||||
```
|
||||
|
||||
This uses the skeleton for [application](config/skeletons/application.html)
|
||||
This uses the skeleton for [application](config/skeletons/sample.html)
|
||||
snippets.
|
||||
|
||||
Code `snippets` also allow for quick Flutter app generation using the following command:
|
||||
Code `sample` also allow for quick Flutter app generation using the following command:
|
||||
|
||||
```bash
|
||||
flutter create --sample=[directory.File.sampleNumber] [name_of_project_directory]
|
||||
@@ -138,12 +138,12 @@ flutter create --sample=[directory.File.sampleNumber] [name_of_project_directory
|
||||
#### Templates
|
||||
|
||||
In order to support showing an entire app when you click on the right tab of
|
||||
the code snippet UI, we have to be able to insert the `snippet` into the template
|
||||
and instantiate the right parts.
|
||||
the code sample UI, we have to be able to insert the `sample` block into the
|
||||
template and instantiate the right parts.
|
||||
|
||||
To do this, there is a [config/templates](config/templates) directory that
|
||||
contains a list of templates. These templates represent an entire app that the
|
||||
`snippet` can be placed into, basically a replacement for `lib/main.dart` in a
|
||||
`sample` can be placed into, basically a replacement for `lib/main.dart` in a
|
||||
flutter app package.
|
||||
|
||||
For more information about how to create, use, or update templates, see
|
||||
@@ -152,7 +152,7 @@ For more information about how to create, use, or update templates, see
|
||||
#### Analysis
|
||||
|
||||
The `../bots/analyze-sample-code.dart` script finds code inside the
|
||||
`@tool snippet` sections and uses the Dart analyzer to check them
|
||||
`@tool sample` sections and uses the Dart analyzer to check them
|
||||
after applying the specified template.
|
||||
|
||||
## Skeletons
|
||||
@@ -161,17 +161,17 @@ A skeleton (in relation to this tool) is an HTML template into which the Dart
|
||||
code blocks and descriptions are interpolated.
|
||||
|
||||
There is currently one skeleton for
|
||||
[application](config/skeletons/application.html) `snippets` and one for
|
||||
[sample](config/skeletons/sample.html) `snippets`, but there could be more.
|
||||
[application](config/skeletons/sample.html) samples and one for
|
||||
[snippet](config/skeletons/snippet.html) code samples, but there could be more.
|
||||
|
||||
Skeletons use mustache notation (e.g. `{{code}}`) to mark where components will
|
||||
be interpolated into the template. It doesn't actually use the mustache
|
||||
package, since these are simple string substitutions, but it uses the same
|
||||
syntax.
|
||||
|
||||
The code block generation tools process the source input and emit HTML for output,
|
||||
which dartdoc places back into the documentation. Any options given to the
|
||||
`{@tool ...}` directive are passed on verbatim to the tool.
|
||||
The code block generation tools process the source input and emit HTML for
|
||||
output, which dartdoc places back into the documentation. Any options given to
|
||||
the `{@tool ...}` directive are passed on verbatim to the tool.
|
||||
|
||||
The `snippets` tool renders these examples through a combination of markdown
|
||||
and HTML using the `{@inject-html}` dartdoc directive.
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 38 KiB After Width: | Height: | Size: 111 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 111 KiB After Width: | Height: | Size: 38 KiB |
@@ -1,43 +0,0 @@
|
||||
{@inject-html}
|
||||
<a name="{{id}}"></a>
|
||||
<div class="anchor-container">
|
||||
<a class="anchor-button-overlay anchor-button" title="Copy link to clipboard"
|
||||
onmouseenter="fixHref(this, '{{id}}');"
|
||||
onclick="fixHref(this, '{{id}}'); copyStringToClipboard(this.href);"
|
||||
href="#">
|
||||
<i class="material-icons copy-image">link</i>
|
||||
</a>
|
||||
</div>
|
||||
<div class="snippet-buttons">
|
||||
<script>var visibleSnippet{{serial}} = "shortSnippet{{serial}}";</script>
|
||||
<button id="shortSnippet{{serial}}Button"
|
||||
onclick="visibleSnippet{{serial}} = showSnippet('shortSnippet{{serial}}', visibleSnippet{{serial}});"
|
||||
selected>Sample</button>
|
||||
<button id="longSnippet{{serial}}Button"
|
||||
onclick="visibleSnippet{{serial}} = showSnippet('longSnippet{{serial}}', visibleSnippet{{serial}});">Sample in an App</button>
|
||||
</div>
|
||||
<div class="snippet-container">
|
||||
<div class="snippet" id="shortSnippet{{serial}}">
|
||||
{{description}}
|
||||
<div class="copyable-container">
|
||||
<button class="copy-button-overlay copy-button" title="Copy to clipboard"
|
||||
onclick="copyTextToClipboard(visibleSnippet{{serial}});">
|
||||
<i class="material-icons copy-image">assignment</i>
|
||||
</button>
|
||||
<pre class="language-{{language}}"><code class="language-{{language}}">{{code}}</code></pre>
|
||||
</div>
|
||||
</div>
|
||||
<div class="snippet" id="longSnippet{{serial}}" hidden>
|
||||
<div class="snippet-description">To create a sample project with this code snippet, run:<br/>
|
||||
<span class="snippet-create-command">flutter create --sample={{id}} mysample</span>
|
||||
</div>
|
||||
<div class="copyable-container">
|
||||
<button class="copy-button-overlay copy-button" title="Copy to clipboard"
|
||||
onclick="copyTextToClipboard(visibleSnippet{{serial}});">
|
||||
<i class="material-icons copy-image">assignment</i>
|
||||
</button>
|
||||
<pre class="language-{{language}}"><code class="language-{{language}}">{{app}}</code></pre>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{@end-inject-html}
|
||||
@@ -9,16 +9,34 @@
|
||||
</a>
|
||||
</div>
|
||||
<div class="snippet-buttons">
|
||||
<button id="shortSnippet{{serial}}Button" selected>Sample</button>
|
||||
<script>var visibleSnippet{{serial}} = "shortSnippet{{serial}}";</script>
|
||||
<button id="shortSnippet{{serial}}Button"
|
||||
onclick="visibleSnippet{{serial}} = showSnippet('shortSnippet{{serial}}', visibleSnippet{{serial}});"
|
||||
selected>Sample</button>
|
||||
<button id="longSnippet{{serial}}Button"
|
||||
onclick="visibleSnippet{{serial}} = showSnippet('longSnippet{{serial}}', visibleSnippet{{serial}});">Sample in an App</button>
|
||||
</div>
|
||||
<div class="snippet-container">
|
||||
<div class="snippet">{{description}}
|
||||
<div class="snippet" id="shortSnippet{{serial}}">
|
||||
{{description}}
|
||||
<div class="copyable-container">
|
||||
<button class="copy-button-overlay copy-button" title="Copy to clipboard"
|
||||
onclick="copyTextToClipboard(findSiblingWithId(this, 'sample-code'));">
|
||||
onclick="copyTextToClipboard(visibleSnippet{{serial}});">
|
||||
<i class="material-icons copy-image">assignment</i>
|
||||
</button>
|
||||
<pre class="language-{{language}}" id="sample-code"><code class="language-{{language}}">{{code}}</code></pre>
|
||||
<pre class="language-{{language}}"><code class="language-{{language}}">{{code}}</code></pre>
|
||||
</div>
|
||||
</div>
|
||||
<div class="snippet" id="longSnippet{{serial}}" hidden>
|
||||
<div class="snippet-description">To create a sample project with this code snippet, run:<br/>
|
||||
<span class="snippet-create-command">flutter create --sample={{id}} mysample</span>
|
||||
</div>
|
||||
<div class="copyable-container">
|
||||
<button class="copy-button-overlay copy-button" title="Copy to clipboard"
|
||||
onclick="copyTextToClipboard(visibleSnippet{{serial}});">
|
||||
<i class="material-icons copy-image">assignment</i>
|
||||
</button>
|
||||
<pre class="language-{{language}}"><code class="language-{{language}}">{{app}}</code></pre>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
25
dev/snippets/config/skeletons/snippet.html
Normal file
25
dev/snippets/config/skeletons/snippet.html
Normal file
@@ -0,0 +1,25 @@
|
||||
{@inject-html}
|
||||
<a name="{{id}}"></a>
|
||||
<div class="anchor-container">
|
||||
<a class="anchor-button-overlay anchor-button" title="Copy link to clipboard"
|
||||
onmouseenter="fixHref(this, '{{id}}');"
|
||||
onclick="fixHref(this, '{{id}}'); copyStringToClipboard(this.href);"
|
||||
href="#">
|
||||
<i class="material-icons copy-image">link</i>
|
||||
</a>
|
||||
</div>
|
||||
<div class="snippet-buttons">
|
||||
<button id="shortSnippet{{serial}}Button" selected>Sample</button>
|
||||
</div>
|
||||
<div class="snippet-container">
|
||||
<div class="snippet">{{description}}
|
||||
<div class="copyable-container">
|
||||
<button class="copy-button-overlay copy-button" title="Copy to clipboard"
|
||||
onclick="copyTextToClipboard(findSiblingWithId(this, 'sample-code'));">
|
||||
<i class="material-icons copy-image">assignment</i>
|
||||
</button>
|
||||
<pre class="language-{{language}}" id="sample-code"><code class="language-{{language}}">{{code}}</code></pre>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{@end-inject-html}
|
||||
@@ -11,10 +11,10 @@ import 'package:path/path.dart' as path;
|
||||
enum SnippetType {
|
||||
/// Produces a snippet that includes the code interpolated into an application
|
||||
/// template.
|
||||
application,
|
||||
sample,
|
||||
|
||||
/// Produces a nicely formatted sample code, but no application.
|
||||
sample,
|
||||
snippet,
|
||||
}
|
||||
|
||||
/// Return the name of an enum item.
|
||||
@@ -69,7 +69,7 @@ class Configuration {
|
||||
|
||||
/// Gets the skeleton file to use for the given [SnippetType] and DartPad preference.
|
||||
File getHtmlSkeletonFile(SnippetType type, {bool showDartPad = false}) {
|
||||
assert(!showDartPad || type == SnippetType.application,
|
||||
assert(!showDartPad || type == SnippetType.sample,
|
||||
'Only application snippets work with dartpad.');
|
||||
final String filename =
|
||||
'${showDartPad ? 'dartpad-' : ''}${getEnumName(type)}.html';
|
||||
|
||||
@@ -32,13 +32,13 @@ void main(List<String> argList) {
|
||||
SnippetType.values.map<String>((SnippetType type) => getEnumName(type)).toList();
|
||||
parser.addOption(
|
||||
_kTypeOption,
|
||||
defaultsTo: getEnumName(SnippetType.application),
|
||||
defaultsTo: getEnumName(SnippetType.sample),
|
||||
allowed: snippetTypes,
|
||||
allowedHelp: <String, String>{
|
||||
getEnumName(SnippetType.application):
|
||||
'Produce a code snippet complete with embedding the sample in an '
|
||||
'application template.',
|
||||
getEnumName(SnippetType.sample):
|
||||
'Produce a code sample application complete with embedding the sample in an '
|
||||
'application template.',
|
||||
getEnumName(SnippetType.snippet):
|
||||
'Produce a nicely formatted piece of sample code. Does not embed the '
|
||||
'sample into an application template.',
|
||||
},
|
||||
@@ -52,7 +52,7 @@ void main(List<String> argList) {
|
||||
parser.addOption(
|
||||
_kOutputOption,
|
||||
defaultsTo: null,
|
||||
help: 'The output path for the generated snippet application. Overrides '
|
||||
help: 'The output path for the generated sample application. Overrides '
|
||||
'the naming generated by the --package/--library/--element arguments. '
|
||||
'Metadata will be written alongside in a .json file. '
|
||||
'The basename of this argument is used as the ID',
|
||||
@@ -60,22 +60,22 @@ void main(List<String> argList) {
|
||||
parser.addOption(
|
||||
_kInputOption,
|
||||
defaultsTo: environment['INPUT'],
|
||||
help: 'The input file containing the snippet code to inject.',
|
||||
help: 'The input file containing the sample code to inject.',
|
||||
);
|
||||
parser.addOption(
|
||||
_kPackageOption,
|
||||
defaultsTo: environment['PACKAGE_NAME'],
|
||||
help: 'The name of the package that this snippet belongs to.',
|
||||
help: 'The name of the package that this sample belongs to.',
|
||||
);
|
||||
parser.addOption(
|
||||
_kLibraryOption,
|
||||
defaultsTo: environment['LIBRARY_NAME'],
|
||||
help: 'The name of the library that this snippet belongs to.',
|
||||
help: 'The name of the library that this sample belongs to.',
|
||||
);
|
||||
parser.addOption(
|
||||
_kElementOption,
|
||||
defaultsTo: environment['ELEMENT_NAME'],
|
||||
help: 'The name of the element that this snippet belongs to.',
|
||||
help: 'The name of the element that this sample belongs to.',
|
||||
);
|
||||
parser.addOption(
|
||||
_kSerialOption,
|
||||
@@ -92,9 +92,9 @@ void main(List<String> argList) {
|
||||
_kShowDartPad,
|
||||
defaultsTo: false,
|
||||
negatable: false,
|
||||
help: 'Indicates whether DartPad should be included in the snippet\'s '
|
||||
help: 'Indicates whether DartPad should be included in the sample\'s '
|
||||
'final HTML output. This flag only applies when the type parameter is '
|
||||
'"application".',
|
||||
'"sample".',
|
||||
);
|
||||
|
||||
final ArgResults args = parser.parse(argList);
|
||||
@@ -108,9 +108,9 @@ void main(List<String> argList) {
|
||||
.firstWhere((SnippetType type) => getEnumName(type) == args[_kTypeOption], orElse: () => null);
|
||||
assert(snippetType != null, "Unable to find '${args[_kTypeOption]}' in SnippetType enum.");
|
||||
|
||||
if (args[_kShowDartPad] == true && snippetType != SnippetType.application) {
|
||||
if (args[_kShowDartPad] == true && snippetType != SnippetType.sample) {
|
||||
errorExit('${args[_kTypeOption]} was selected, but the --dartpad flag is only valid '
|
||||
'for application snippets.');
|
||||
'for application sample code.');
|
||||
}
|
||||
|
||||
if (args[_kInputOption] == null) {
|
||||
@@ -125,12 +125,12 @@ void main(List<String> argList) {
|
||||
}
|
||||
|
||||
String template;
|
||||
if (snippetType == SnippetType.application) {
|
||||
if (snippetType == SnippetType.sample) {
|
||||
final String templateArg = args[_kTemplateOption] as String;
|
||||
if (templateArg == null || templateArg.isEmpty) {
|
||||
stderr.writeln(parser.usage);
|
||||
errorExit('The --$_kTemplateOption option must be specified on the command '
|
||||
'line for application snippets.');
|
||||
'line for application samples.');
|
||||
}
|
||||
template = templateArg.replaceAll(RegExp(r'.tmpl$'), '');
|
||||
}
|
||||
|
||||
@@ -48,7 +48,7 @@ class SnippetGenerator {
|
||||
static DartFormatter formatter = DartFormatter(pageWidth: 80, fixes: StyleFix.all);
|
||||
|
||||
/// This returns the output file for a given snippet ID. Only used for
|
||||
/// [SnippetType.application] snippets.
|
||||
/// [SnippetType.sample] snippets.
|
||||
File getOutputFile(String id) => File(path.join(configuration.outputDirectory.path, '$id.dart'));
|
||||
|
||||
/// Gets the path to the template file requested.
|
||||
@@ -60,7 +60,7 @@ class SnippetGenerator {
|
||||
|
||||
/// Injects the [injections] into the [template], and turning the
|
||||
/// "description" injection into a comment. Only used for
|
||||
/// [SnippetType.application] snippets.
|
||||
/// [SnippetType.sample] snippets.
|
||||
String interpolateTemplate(List<_ComponentTuple> injections, String template, Map<String, Object> metadata) {
|
||||
final RegExp moustacheRegExp = RegExp('{{([^}]+)}}');
|
||||
return template.replaceAllMapped(moustacheRegExp, (Match match) {
|
||||
@@ -99,7 +99,7 @@ class SnippetGenerator {
|
||||
/// components, and we care about the order of the injections.
|
||||
///
|
||||
/// Takes into account the [type] and doesn't substitute in the id and the app
|
||||
/// if not a [SnippetType.application] snippet.
|
||||
/// if not a [SnippetType.sample] snippet.
|
||||
String interpolateSkeleton(SnippetType type, List<_ComponentTuple> injections, String skeleton, Map<String, Object> metadata) {
|
||||
final List<String> result = <String>[];
|
||||
const HtmlEscape htmlEscape = HtmlEscape();
|
||||
@@ -133,7 +133,7 @@ class SnippetGenerator {
|
||||
'element': metadata['element'] as String ?? '',
|
||||
'app': '',
|
||||
};
|
||||
if (type == SnippetType.application) {
|
||||
if (type == SnippetType.sample) {
|
||||
substitutions
|
||||
..['serial'] = metadata['serial']?.toString() ?? '0'
|
||||
..['app'] = htmlEscape.convert(injections.firstWhere((_ComponentTuple tuple) => tuple.name == 'app').mergedContent);
|
||||
@@ -201,20 +201,20 @@ class SnippetGenerator {
|
||||
/// comment markers).
|
||||
///
|
||||
/// The [type] is the type of snippet to create: either a
|
||||
/// [SnippetType.application] or a [SnippetType.sample].
|
||||
/// [SnippetType.sample] or a [SnippetType.snippet].
|
||||
///
|
||||
/// [showDartPad] indicates whether DartPad should be shown where possible.
|
||||
/// Currently, this value only has an effect if [type] is
|
||||
/// [SnippetType.application], in which case an alternate skeleton file is
|
||||
/// [SnippetType.sample], in which case an alternate skeleton file is
|
||||
/// used to create the final HTML output.
|
||||
///
|
||||
/// The [template] must not be null if the [type] is
|
||||
/// [SnippetType.application], and specifies the name of the template to use
|
||||
/// [SnippetType.sample], and specifies the name of the template to use
|
||||
/// for the application code.
|
||||
///
|
||||
/// The [id] is a string ID to use for the output file, and to tell the user
|
||||
/// about in the `flutter create` hint. It must not be null if the [type] is
|
||||
/// [SnippetType.application].
|
||||
/// [SnippetType.sample].
|
||||
String generate(
|
||||
File input,
|
||||
SnippetType type, {
|
||||
@@ -223,14 +223,14 @@ class SnippetGenerator {
|
||||
File output,
|
||||
@required Map<String, Object> metadata,
|
||||
}) {
|
||||
assert(template != null || type != SnippetType.application);
|
||||
assert(template != null || type != SnippetType.sample);
|
||||
assert(metadata != null && metadata['id'] != null);
|
||||
assert(input != null);
|
||||
assert(!showDartPad || type == SnippetType.application,
|
||||
assert(!showDartPad || type == SnippetType.sample,
|
||||
'Only application snippets work with dartpad.');
|
||||
final List<_ComponentTuple> snippetData = parseInput(_loadFileAsUtf8(input));
|
||||
switch (type) {
|
||||
case SnippetType.application:
|
||||
case SnippetType.sample:
|
||||
final Directory templatesDir = configuration.templatesDirectory;
|
||||
if (templatesDir == null) {
|
||||
stderr.writeln('Unable to find the templates directory.');
|
||||
@@ -272,7 +272,7 @@ class SnippetGenerator {
|
||||
});
|
||||
metadataFile.writeAsStringSync(jsonEncoder.convert(metadata));
|
||||
break;
|
||||
case SnippetType.sample:
|
||||
case SnippetType.snippet:
|
||||
break;
|
||||
}
|
||||
final String skeleton =
|
||||
|
||||
@@ -32,22 +32,22 @@ void main() {
|
||||
matches(RegExp(r'[/\\]flutter sdk[/\\]dev[/\\]snippets[/\\]config[/\\]templates')));
|
||||
});
|
||||
test('html skeleton file for sample is correct', () async {
|
||||
expect(
|
||||
config.getHtmlSkeletonFile(SnippetType.snippet).path,
|
||||
matches(RegExp(
|
||||
r'[/\\]flutter sdk[/\\]dev[/\\]snippets[/\\]config[/\\]skeletons[/\\]snippet.html')));
|
||||
});
|
||||
test('html skeleton file for app with no dartpad is correct', () async {
|
||||
expect(
|
||||
config.getHtmlSkeletonFile(SnippetType.sample).path,
|
||||
matches(RegExp(
|
||||
r'[/\\]flutter sdk[/\\]dev[/\\]snippets[/\\]config[/\\]skeletons[/\\]sample.html')));
|
||||
});
|
||||
test('html skeleton file for app with no dartpad is correct', () async {
|
||||
expect(
|
||||
config.getHtmlSkeletonFile(SnippetType.application).path,
|
||||
matches(RegExp(
|
||||
r'[/\\]flutter sdk[/\\]dev[/\\]snippets[/\\]config[/\\]skeletons[/\\]application.html')));
|
||||
});
|
||||
test('html skeleton file for app with dartpad is correct', () async {
|
||||
expect(
|
||||
config.getHtmlSkeletonFile(SnippetType.application, showDartPad: true).path,
|
||||
config.getHtmlSkeletonFile(SnippetType.sample, showDartPad: true).path,
|
||||
matches(RegExp(
|
||||
r'[/\\]flutter sdk[/\\]dev[/\\]snippets[/\\]config[/\\]skeletons[/\\]dartpad-application.html')));
|
||||
r'[/\\]flutter sdk[/\\]dev[/\\]snippets[/\\]config[/\\]skeletons[/\\]dartpad-sample.html')));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -37,20 +37,20 @@ main() {
|
||||
{{code}}
|
||||
}
|
||||
''');
|
||||
configuration.getHtmlSkeletonFile(SnippetType.application).writeAsStringSync('''
|
||||
configuration.getHtmlSkeletonFile(SnippetType.sample).writeAsStringSync('''
|
||||
<div>HTML Bits</div>
|
||||
{{description}}
|
||||
<pre>{{code}}</pre>
|
||||
<pre>{{app}}</pre>
|
||||
<div>More HTML Bits</div>
|
||||
''');
|
||||
configuration.getHtmlSkeletonFile(SnippetType.sample).writeAsStringSync('''
|
||||
configuration.getHtmlSkeletonFile(SnippetType.snippet).writeAsStringSync('''
|
||||
<div>HTML Bits</div>
|
||||
{{description}}
|
||||
<pre>{{code}}</pre>
|
||||
<div>More HTML Bits</div>
|
||||
''');
|
||||
configuration.getHtmlSkeletonFile(SnippetType.application, showDartPad: true).writeAsStringSync('''
|
||||
configuration.getHtmlSkeletonFile(SnippetType.sample, showDartPad: true).writeAsStringSync('''
|
||||
<div>HTML Bits (DartPad-style)</div>
|
||||
<iframe class="snippet-dartpad" src="https://dartpad.dev/embed-flutter.html?split=60&run=true&sample_id={{id}}"></iframe>
|
||||
<div>More HTML Bits</div>
|
||||
@@ -83,7 +83,7 @@ void main() {
|
||||
|
||||
final String html = generator.generate(
|
||||
inputFile,
|
||||
SnippetType.application,
|
||||
SnippetType.sample,
|
||||
template: 'template',
|
||||
metadata: <String, Object>{
|
||||
'id': 'id',
|
||||
@@ -126,7 +126,7 @@ void main() {
|
||||
|
||||
final String html = generator.generate(
|
||||
inputFile,
|
||||
SnippetType.sample,
|
||||
SnippetType.snippet,
|
||||
metadata: <String, Object>{'id': 'id'},
|
||||
);
|
||||
expect(html, contains('<div>HTML Bits</div>'));
|
||||
@@ -155,7 +155,7 @@ void main() {
|
||||
|
||||
final String html = generator.generate(
|
||||
inputFile,
|
||||
SnippetType.application,
|
||||
SnippetType.sample,
|
||||
showDartPad: true,
|
||||
template: 'template',
|
||||
metadata: <String, Object>{'id': 'id'},
|
||||
@@ -185,7 +185,7 @@ void main() {
|
||||
|
||||
generator.generate(
|
||||
inputFile,
|
||||
SnippetType.application,
|
||||
SnippetType.sample,
|
||||
template: 'template',
|
||||
output: outputFile,
|
||||
metadata: <String, Object>{'sourcePath': 'some/path.dart', 'id': 'id'},
|
||||
|
||||
Reference in New Issue
Block a user