Reverse the sense of the terms snippet and sample. (#48254)

This commit is contained in:
Greg Spencer
2020-01-08 15:28:02 -08:00
committed by Flutter GitHub Bot
parent dbed575c01
commit fabf4e3d0d
156 changed files with 583 additions and 583 deletions

View File

@@ -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
![Code sample image](assets/code_sample.png)
![Code snippet image](assets/code_snippet.png)
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
![Code snippet image](assets/code_snippet.png)
![Code sample image](assets/code_sample.png)
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

View File

@@ -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}

View File

@@ -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>

View 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}

View File

@@ -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';

View File

@@ -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$'), '');
}

View File

@@ -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 =

View File

@@ -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')));
});
});
}

View File

@@ -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'},