docs: add angular.dev (#52536)

PR Close #52536
This commit is contained in:
twerske
2023-11-06 08:42:56 -08:00
committed by Andrew Scott
parent 8bbec83dfd
commit 651c34735d
3179 changed files with 193754 additions and 0 deletions
+4
View File
@@ -38,3 +38,7 @@ integration/typings_test_ts49/node_modules
integration/typings_test_ts50/node_modules
integration/typings_test_ts51/node_modules
integration/typings_test_ts52/node_modules
# Temporarily ignore all of adev
adev/
+2
View File
@@ -29,6 +29,8 @@ export const format: FormatConfig = {
'!packages/core/src/i18n/locale_en.ts',
'!packages/common/locales/closure-locale.ts',
'!packages/common/src/i18n/currencies.ts',
// Temporarily disable formatting for adev
'!adev/**',
],
},
'buildifier': true,
+16
View File
@@ -1057,6 +1057,22 @@ groups:
- dylhunn
- mgechev
# =========================================================
# Docs: Angular Dev Site
# =========================================================
angular-dev:
<<: *defaults
conditions:
- >
contains_any_globs(files, [
'adev/**/{.*,*}'
])
reviewers:
users:
- twerske
- josephperrott
- jelbourn
# =========================================================
# Docs-infra
# =========================================================
+67
View File
@@ -0,0 +1,67 @@
# See http://help.github.com/ignore-files/ for more about ignoring files.
# Compiled output
/dist
/tmp
/out-tsc
/bazel-out
/src/assets/tutorials
/src/assets/previews
/TEMP
# Node
node_modules
npm-debug.log
yarn-error.log
# IDEs and editors
.idea/
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# Visual Studio Code
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history/*
# Miscellaneous
/.angular/cache
.sass-cache/
/connect.lock
/coverage
/libpeerconnection.log
testem.log
/typings
# Ignore ng-dev logs and user-config
.ng-dev.err*
.ng-dev.log
.ng-dev.user*
# System files
.DS_Store
Thumbs.db
# Yarn v2+. Zero installs disabled since we are not using PnP.
.pnp.*
.yarn/*
!.yarn/patches
!.yarn/plugins
!.yarn/releases
!.yarn/sdks
!.yarn/versions
!.yarn/yarn.js
# Firebase
.firebase
*-debug.log
.runtimeconfig.json
+42
View File
@@ -0,0 +1,42 @@
{
// Default state for all rules
"default": true,
// MD013/line-length - Line length
"MD013": {
// Number of characters
"line_length": 750,
// Include code blocks
"code_blocks": false,
// Include tables
"tables": false
},
// MD034/bare-URL-used - Do not lint bare url - we display links in config code that does not match linter styles
"MD034": false,
// MD038 - Spaces inside code span elements - We display inline templates in codeblocks
"MD038": false,
// MD046/code-block-style - Do not lint inline code blocks - we display formatted CLI output in code that does not match linter styles
"MD046": false,
// MD049/emphasis-style - Emphasis style should be consistent
"MD049": false,
// TODO: Enable the following rules as MD improvements:
// MD024/no-duplicate-heading/no-duplicate-header - Multiple headings with the same content
"MD024": false,
// MD033/no-inline-html - Inline HTML
"MD033": false,
// MD051/link-fragments - Link fragments should be valid
"MD051": false,
// MD052/reference-links-images - Reference links and images should use a label that is defined
"MD052": false,
// MD037/no-space-in-emphasis - Inline lists (such as in tables) incorrectly trigger this warning.
"MD037": false
}
+1
View File
@@ -0,0 +1 @@
node_modules/
+2
View File
@@ -0,0 +1,2 @@
.yarn/releases/*.cjs
src/content/examples/**/*.*
+5
View File
@@ -0,0 +1,5 @@
# Ignoring documentation style examples
/src/content/api-examples
/src/content/examples
/src/content/tutorials
node_modules/
+130
View File
@@ -0,0 +1,130 @@
{
"customSyntax": "postcss-scss",
"defaultSeverity": "error",
"reportNeedlessDisables": true,
"reportInvalidScopeDisables": true,
"plugins": [
"./tools/stylelint/loader-rule.js",
"./tools/stylelint/no-concrete-rules.ts",
"./tools/stylelint/no-import.ts",
"./tools/stylelint/no-unused-import.ts",
"./tools/stylelint/selector-no-deep.ts",
"./tools/stylelint/single-line-comment-only.ts"
],
"rules": {
"@angular/selector-no-deep": true,
"@angular/no-unused-import": true,
"@angular/single-line-comment-only": true,
"@angular/no-import": true,
"color-hex-case": "lower",
"color-no-invalid-hex": true,
"function-calc-no-unspaced-operator": true,
"function-comma-space-after": "always-single-line",
"function-comma-space-before": "never",
"function-name-case": "lower",
"function-url-quotes": "always",
"function-url-scheme-disallowed-list": ["data"],
"function-whitespace-after": "always",
"number-leading-zero": "always",
"number-no-trailing-zeros": true,
"length-zero-no-unit": true,
"string-no-newline": true,
"string-quotes": "single",
"unit-case": "lower",
"unit-no-unknown": true,
"unit-allowed-list": [
"px",
"%",
"deg",
"s",
"ms",
"em",
"rem",
"vh",
"vw",
"vmin",
"fr",
"ch",
"lvh",
"svh",
"dvh"
],
"value-list-comma-space-after": "always-single-line",
"value-list-comma-space-before": "never",
"shorthand-property-no-redundant-values": true,
"property-case": "lower",
"no-duplicate-at-import-rules": true,
"declaration-block-no-duplicate-properties": [
true,
{
"ignore": ["consecutive-duplicates-with-different-values"]
}
],
"declaration-block-trailing-semicolon": "always",
"declaration-block-single-line-max-declarations": 1,
"declaration-block-semicolon-space-before": "never",
"declaration-block-semicolon-space-after": "always-single-line",
"declaration-block-semicolon-newline-before": "never-multi-line",
"declaration-block-semicolon-newline-after": "always-multi-line",
"declaration-colon-space-after": "always-single-line",
"declaration-property-value-disallowed-list": [
{"/.*/": ["initial"]},
{"message": "The `initial` value is not supported in IE."}
],
"block-closing-brace-newline-after": "always",
"block-closing-brace-newline-before": "always-multi-line",
"block-opening-brace-newline-after": "always-multi-line",
"block-opening-brace-space-before": "always-multi-line",
"selector-attribute-brackets-space-inside": "never",
"selector-attribute-operator-space-after": "never",
"selector-attribute-operator-space-before": "never",
"selector-combinator-space-after": "always",
"selector-combinator-space-before": "always",
"selector-pseudo-class-case": "lower",
"selector-pseudo-class-parentheses-space-inside": "never",
"selector-pseudo-element-case": "lower",
"selector-pseudo-element-colon-notation": "double",
"selector-pseudo-element-no-unknown": true,
"selector-type-case": "lower",
"selector-max-id": 0,
"no-missing-end-of-source-newline": true,
"no-eol-whitespace": true,
"max-line-length": [
100,
{
"ignorePattern": "/https?://.*/"
}
],
"linebreaks": "unix",
"selector-class-pattern": [
"^_?(docs-|adev-|cm-|mat-|mdc-|xterm|ͼ3|ͼ2u|ͼ1|ng-|hljs-|as-|cdk-)",
{
"resolveNestedSelectors": true
}
]
},
"overrides": [
{
"files": ["projects/shared/src/lib/styles/_split.scss"],
"rules": {
"selector-pseudo-element-no-unknown": [
true,
{
"ignorePseudoElements": ["ng-deep"]
}
]
}
}
]
}
+3
View File
@@ -0,0 +1,3 @@
# Angular.dev: The new home for Angular developers (https://angular.dev)
Read more about our initial launch on the [Angular blog](https://goo.gle/angular-dot-dev).
+143
View File
@@ -0,0 +1,143 @@
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"angular-dev": {
"projectType": "application",
"schematics": {
"@schematics/angular:component": {
"style": "scss",
"standalone": true,
"changeDetection": "OnPush"
}
},
"root": "projects/angular-dev",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:application",
"options": {
"outputPath": "dist/angular-dev",
"index": "src/index.html",
"browser": "src/main.ts",
"server": "src/main.server.ts",
"prerender": true,
"polyfills": ["src/polyfills.ts", "zone.js"],
"tsConfig": "tsconfig.app.json",
"inlineStyleLanguage": "scss",
"assets": [
"src/favicon.ico",
"src/robots.txt",
"src/assets"
],
"styles": ["projects/shared/src/lib/styles/global-styles.scss"],
"scripts": [],
"webWorkerTsConfig": "tsconfig.worker.json"
},
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kb",
"maximumError": "1mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "2kb",
"maximumError": "5kb"
}
],
"outputHashing": "all"
},
"development": {
"optimization": false,
"extractLicenses": false,
"sourceMap": true,
"fileReplacements": [
{
"replace": "src/environments/environment.ts",
"with": "src/environments/environment.development.ts"
}
]
}
},
"defaultConfiguration": "production"
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"configurations": {
"production": {
"buildTarget": "angular-dev:build:production"
},
"development": {
"buildTarget": "angular-dev:build:development"
}
},
"defaultConfiguration": "development",
"options": {
"buildTarget": "web-ui:build",
"headers": {
"Cross-Origin-Opener-Policy": "same-origin",
"Cross-Origin-Embedder-Policy": "require-corp"
}
}
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"buildTarget": "angular-dev:build"
}
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"polyfills": ["zone.js", "zone.js/testing"],
"tsConfig": "tsconfig.spec.json",
"include": ["src/app"],
"inlineStyleLanguage": "scss",
"assets": ["src/favicon.ico", "src/assets"],
"styles": ["projects/shared/src/lib/styles/global-styles.scss"],
"scripts": [],
"webWorkerTsConfig": "tsconfig.worker.json"
}
}
}
},
"shared": {
"projectType": "library",
"root": "projects/shared",
"sourceRoot": "projects/shared/src",
"prefix": "lib",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:ng-packagr",
"options": {
"project": "projects/shared/ng-package.json"
},
"configurations": {
"production": {
"tsConfig": "projects/shared/tsconfig.lib.prod.json"
},
"development": {
"tsConfig": "projects/shared/tsconfig.lib.json"
}
},
"defaultConfiguration": "production"
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"tsConfig": "projects/shared/tsconfig.spec.json",
"polyfills": ["zone.js", "zone.js/testing"]
}
}
}
}
},
"cli": {
"analytics": "dca119a9-da31-47f7-a6cb-b60541037021"
}
}
+122
View File
@@ -0,0 +1,122 @@
{
"name": "blossom",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "yarn generate-all && ng serve",
"build": "ng build angular-dev",
"watch": "ng build --watch --configuration development",
"test": "ng test",
"ng-dev": "cross-env TS_NODE_PROJECT=$PWD/.ng-dev/tsconfig.json TS_NODE_TRANSPILE_ONLY=1 node --no-warnings --loader ts-node/esm node_modules/@angular/ng-dev/bundles/cli.mjs",
"lint": "tslint -c tslint.json --project tsconfig.json && stylelint \"projects/**/*.+(css|scss)\" --config .stylelintrc.json && markdownlint \"projects/**/*.md\"",
"lint-fix": "markdownlint --fix '**/*.md'",
"format": "yarn ng-dev format changed && tslint -c tslint.json --fix --project tsconfig.json",
"serve:prerender": "http-server -c-l dist/angular-dev/browser",
"postinstall": "yarn generate-all",
"generate-all": "yarn generate-tutorials && yarn generate-docs && yarn generate-previews && yarn set-version && yarn generate-api && yarn generate-cli",
"generate-api": "ts-node-esm ./prerender/api-gen/index.ts all ./src/assets/content/api",
"generate-cli": "ts-node-esm ./prerender/api-gen/cli-index.ts all ./src/assets/content/cli",
"generate-docs": "ts-node-esm ./prerender/markdown-pipeline/index.mts",
"generate-previews": "ts-node-esm scripts/examples/generate-previews-components-map.mts",
"generate-tutorials": "ts-node scripts/tutorials/generate-tutorials.ts",
"check-links": "ts-node scripts/checks/check-links.ts",
"new-example": "ts-node-esm scripts/examples/create-example.mts",
"new-tutorial": "ts-node scripts/tutorials/new-tutorial.ts",
"new-playground-template": "ts-node scripts/tutorials/new-playground-template.ts",
"update-tutorials-package-lock": "ts-node scripts/tutorials/update-package-lock.ts",
"set-version": "ts-node-esm scripts/versions/set-current-version.mts",
"prepare": "husky install"
},
"private": true,
"dependencies": {
"@angular/animations": "^17.0.0-rc.1",
"@angular/cdk": "17.0.0-rc.1",
"@angular/common": "^17.0.0-rc.1",
"@angular/compiler": "^17.0.0-rc.1",
"@angular/core": "^17.0.0-rc.1",
"@angular/elements": "^17.0.0-rc.1",
"@angular/forms": "^17.0.0-rc.1",
"@angular/material": "17.0.0-rc.1",
"@angular/platform-browser": "^17.0.0-rc.1",
"@angular/platform-browser-dynamic": "^17.0.0-rc.1",
"@angular/platform-server": "^17.0.0-rc.1",
"@angular/router": "^17.0.0-rc.1",
"@angular/service-worker": "^17.0.0-rc.1",
"@codemirror/autocomplete": "^6.9.0",
"@codemirror/commands": "^6.2.4",
"@codemirror/lang-angular": "^0.1.2",
"@codemirror/lang-css": "^6.2.1",
"@codemirror/lang-html": "^6.4.3",
"@codemirror/lang-javascript": "^6.1.8",
"@codemirror/lang-sass": "^6.0.1",
"@codemirror/language": "^6.7.0",
"@codemirror/lint": "^6.4.0",
"@codemirror/search": "^6.4.0",
"@codemirror/state": "^6.2.1",
"@codemirror/tooltip": "^0.19.16",
"@codemirror/view": "^6.12.0",
"@lezer/highlight": "^1.1.6",
"@typescript/vfs": "^1.5.0",
"@webcontainer/api": "^1.1.5",
"algoliasearch": "^4.20.0",
"angular-split": "16.2.1",
"diff": "^5.1.0",
"express": "^4.15.2",
"gsap": "^3.12.2",
"highlight.js": "^11.8.0",
"jszip": "^3.10.1",
"ngx-progressbar": "^11.1.0",
"ogl": "^1.0.1",
"preact": "^10.17.1",
"preact-render-to-string": "^6.2.1",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"xterm": "^5.1.0",
"xterm-addon-fit": "^0.7.0",
"zone.js": "~0.14.0"
},
"devDependencies": {
"@angular-devkit/build-angular": "17.0.0-rc.3",
"@angular/build-tooling": "https://github.com/angular/dev-infra-private-build-tooling-builds.git#bb8a1cf74bda7e7a193cc449ca9558bc3ce55ad0",
"@angular/cli": "17.0.0-rc.3",
"@angular/compiler-cli": "^17.0.0-rc.1",
"@angular/ng-dev": "https://github.com/angular/dev-infra-private-ng-dev-builds.git#09c58eaf121b8e71edbe863c373854c0a221e290",
"@inquirer/prompts": "^3.0.2",
"@mermaid-js/mermaid-cli": "^10.3.1",
"@types/algoliasearch": "^4.0.0",
"@types/diff": "^5.0.3",
"@types/dom-navigation": "~1.0.0",
"@types/dom-view-transitions": "~1.0.1",
"@types/express": "^4.17.0",
"@types/jasmine": "~4.3.0",
"@types/jsdom": "^21.1.2",
"@types/marked": "^5.0.1",
"@types/node": "^18.11.9",
"cross-env": "^7.0.3",
"emoji-regex": "^10.2.1",
"firebase-tools": "latest",
"glob": "^10.2.7",
"html-entities": "^2.4.0",
"http-server": "^14.1.1",
"husky": "^8.0.0",
"jasmine-core": "~4.5.0",
"jsdom": "^22.1.0",
"karma": "~6.4.0",
"karma-chrome-launcher": "~3.1.0",
"karma-coverage": "~2.2.0",
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.0.0",
"markdownlint-cli": "^0.36.0",
"marked": "^5.1.1",
"ng-packagr": "17.0.0-next.1",
"postcss-scss": "^4.0.4",
"prettier": "^2.8.4",
"stylelint": "^14.14.0",
"ts-node": "^10.8.1",
"tslint": "^6.1.3",
"tslint-eslint-rules": "5.4.0",
"typescript": "~5.2.0",
"uuid": "^9.0.0",
"vrsource-tslint-rules": "6.0.0"
}
}
+116
View File
@@ -0,0 +1,116 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/* tslint:disable:no-console */
import {NavigationItem} from '@angular/docs-shared';
import {readFileSync} from 'fs';
import {glob} from 'glob';
import {join} from 'path';
import {SUB_NAVIGATION_DATA} from '../../src/app/sub-navigation-data';
// PATHS
const PROJECT_FOLDER_PATH = join(__dirname, '../../src');
// SKIP Files
const SKIPED_ORPHAN = ['kitchen-sink', 'error', 'examples'];
main();
async function main() {
const contentDir = join(PROJECT_FOLDER_PATH, 'content');
const mdFiles = await retrieveAllMarkdownFiles(contentDir);
const allowedPaths = new Set([
...SUB_NAVIGATION_DATA.docs.flatMap((item: any) => getPaths(item)),
SUB_NAVIGATION_DATA.reference.flatMap((item: any) => getPaths(item)),
SUB_NAVIGATION_DATA.footer.flatMap((item: any) => getPaths(item)),
]);
const contentPaths = new Set([
...SUB_NAVIGATION_DATA.docs.flatMap((item: any) => getContentPaths(item)),
...SUB_NAVIGATION_DATA.reference.flatMap((item: any) => getContentPaths(item)),
...SUB_NAVIGATION_DATA.footer.flatMap((item: any) => getContentPaths(item)),
]);
// Regular expression to match relative links
const regex = /\]\((?!https?:\/\/)([^)]+)\)/g;
const orphanFiles: string[] = [];
for (const {path} of mdFiles) {
if (
!contentPaths.has(path.slice(0, -3)) &&
!path.startsWith('tutorials') &&
!SKIPED_ORPHAN.some((skip) => path.startsWith(skip))
) {
orphanFiles.push(path.slice(0, -3));
}
}
if (orphanFiles.length > 0) {
console.log('======== ORPHAN FILES =========\n');
orphanFiles.forEach((file) => console.warn(file));
}
const deadLinks: {path: string; links: string[]}[] = [];
for (const {content, path} of mdFiles) {
let match;
const matches = [];
while ((match = regex.exec(content)) !== null) {
const relativeLink = match[1].split('#')[0];
if (!allowedPaths.has(relativeLink) && relativeLink.startsWith('guide')) {
matches.push(relativeLink);
}
}
if (matches.length) {
deadLinks.push({path, links: matches});
}
}
if (deadLinks.length > 0) {
console.warn('\n\n======== DEAD RELATIVE LINKS =========\n');
deadLinks.forEach(({path, links}) => {
console.warn(path);
links.forEach((path) => console.log(`\t ${path}`));
});
}
if (deadLinks.length > 0 || orphanFiles.length > 0) {
throw new Error('Check fails');
}
}
function getPaths(navItem: NavigationItem): string[] {
return [
...(navItem.path ? [navItem.path] : []),
...(navItem.children ?? []).flatMap((item) => getPaths(item)),
];
}
function getContentPaths(navItem: NavigationItem): string[] {
return [
...(navItem.contentPath ? [navItem.contentPath] : []),
...(navItem.children ?? []).flatMap((item) => getContentPaths(item)),
];
}
/**
* Recursively search the provided directory for all markdown files and
* asyncronously load them.
*/
async function retrieveAllMarkdownFiles(
baseDir: string,
): Promise<{path: string; content: string}[]> {
const files = await glob('**/*.md', {
root: baseDir,
cwd: baseDir,
ignore: ['**/node_modules/**'],
});
return files.map((fullPathToFile) => ({
path: fullPathToFile,
content: readFileSync(join(baseDir, fullPathToFile), {encoding: 'utf-8'}),
}));
}
+135
View File
@@ -0,0 +1,135 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {input, confirm} from '@inquirer/prompts';
import {existsSync} from 'fs';
import {copyFile, mkdir, writeFile} from 'fs/promises';
import {dirname, join} from 'path';
import {fileURLToPath} from 'url';
import {copyFolder} from './utils/fs.mjs';
const EXAMPLES_BASE = join(
dirname(fileURLToPath(import.meta.url)),
'../../src/content/examples',
);
const STACKBLITZ_TEMPLATE = join(
dirname(fileURLToPath(import.meta.url)),
'../../src/content/stackblitz-template',
);
const MAIN_TS_FILENAME = 'main.ts';
const STACKBLITZ_CONFIG_FILENAME = 'stackblitz.json';
createExample();
async function createExample(): Promise<void> {
console.info('Create example');
const name = await input({message: 'What is the example name?'});
const description = await input({message: 'Could you provide the description of the example?'});
const tags: string[] = [];
let addMoreTags = true;
while (addMoreTags) {
const tag = await input({message: 'Could you provide the tag of the example?'});
if (!!tag) {
tags.push(tag);
}
console.info();
addMoreTags = await confirm({message: 'Would you like to add another tag?', default: true});
}
const shouldCopySrcAppFolderFromTemplate = await confirm({
message: 'Would you like to copy /src/app/**.* from template?',
default: true,
});
const shouldCopyMainTsFromTemplate = await confirm({
message: 'Would you like to copy /src/main.ts from template?',
default: false,
});
const examplePath = join(EXAMPLES_BASE, name);
await createEmptyExample(examplePath, name, description, tags);
await copyFilesFromTemplate(
examplePath,
shouldCopySrcAppFolderFromTemplate,
shouldCopyMainTsFromTemplate,
);
}
/**
* Create the directory and marker files for the new example.
*/
async function createEmptyExample(
examplePath: string,
exampleName: string,
description: string,
tags: string[],
): Promise<void> {
validateExampleName(exampleName);
await ensureExamplePath(examplePath);
await writeStackBlitzFile(examplePath, description, tags);
}
function validateExampleName(exampleName: string): void {
if (/\s/.test(exampleName)) {
throw new Error(`Unable to create example. The example name contains spaces: '${exampleName}'`);
}
}
/**
* Ensure that the new example directory exists.
*/
async function ensureExamplePath(examplePath: string): Promise<void> {
if (existsSync(examplePath)) {
throw new Error(
`Unable to create example. The path to the new example already exists: ${examplePath}`,
);
}
await mkdir(examplePath);
}
/**
* Write the `stackblitz.json` file into the new example.
*/
async function writeStackBlitzFile(
examplePath: string,
description: string,
tags: string[],
): Promise<void> {
const config = {
description,
ignore: ['**/*.d.ts', '**/*.js', '**/*.[1,2].*'],
tags,
};
await writeFile(
join(examplePath, STACKBLITZ_CONFIG_FILENAME),
JSON.stringify(config, null, 2) + '\n',
);
}
async function copyFilesFromTemplate(
examplePath: string,
shouldCopySrcAppFolderFromTemplate: boolean,
shouldCopyMainTsFromTemplate: boolean,
): Promise<void> {
if (shouldCopySrcAppFolderFromTemplate) {
const appTemplateFolderPath = join(STACKBLITZ_TEMPLATE, 'src/app');
const exampleAppFolderPath = join(examplePath, 'src/app');
await copyFolder(appTemplateFolderPath, exampleAppFolderPath);
}
if (shouldCopyMainTsFromTemplate) {
const mainTsTemplatePath = join(STACKBLITZ_TEMPLATE, 'src', MAIN_TS_FILENAME);
const exampleMainTsPath = join(examplePath, 'src', MAIN_TS_FILENAME);
await copyFile(mainTsTemplatePath, exampleMainTsPath);
}
}
@@ -0,0 +1,158 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import ts from 'typescript';
import * as fs from 'fs';
import {dirname, join, relative} from 'path';
import {fileURLToPath} from 'url';
import {readFile, writeFile} from 'fs/promises';
const TYPESCRIPT_EXTENSION = '.ts';
const SKIP_FILES_WITH_EXTENSIONS = ['.e2e-spec.ts', '.spec.ts', '.po.ts'];
const EXAMPLES_PATH = `../../content/examples`;
interface File {
path: string;
content: string;
}
interface AnalyzedFiles {
path: string;
componentNames: string[];
}
/** Absolute disk path to the project directory. */
const examplesDir = join(
dirname(fileURLToPath(import.meta.url)),
'../../src/content/examples',
);
const projectDir = join(dirname(fileURLToPath(import.meta.url)), '../../src');
const previewsComponentMapFileName = 'previews.ts';
main();
async function main() {
const files = await retrieveAllTypescriptFiles(
examplesDir,
(path) => !SKIP_FILES_WITH_EXTENSIONS.some((extensionToSkip) => path.endsWith(extensionToSkip)),
);
const filesWithComponent = files
.map((file) => ({
componentNames: analyzeFile(file),
path: file.path,
}))
.filter((result) => result.componentNames.length > 0);
const previewsComponentMap = generatePreviewsComponentMap(filesWithComponent);
fs.mkdirSync(join(projectDir, 'assets/previews'), {recursive: true});
await writeFile(
join(projectDir, 'assets/previews', previewsComponentMapFileName),
previewsComponentMap,
);
}
/** Recursively search the provided directory for all typescript files and asynchronously load them. */
function retrieveAllTypescriptFiles(
baseDir: string,
predicateFn: (path: string) => boolean,
): Promise<File[]> {
const typescriptFiles: Promise<File>[] = [];
const checkFilesInDirectory = (dir: string) => {
const files = fs.readdirSync(dir, {withFileTypes: true});
for (const file of files) {
const fullPathToFile = join(dir, file.name);
const relativeFilePath = relative(baseDir, fullPathToFile);
if (
file.isFile() &&
file.name.endsWith(TYPESCRIPT_EXTENSION) &&
predicateFn(relativeFilePath)
) {
typescriptFiles.push(
readFile(fullPathToFile, {encoding: 'utf-8'}).then((fileContent) => {
return {
path: relativeFilePath,
content: fileContent,
};
}),
);
} else if (file.isDirectory()) {
checkFilesInDirectory(fullPathToFile);
}
}
};
checkFilesInDirectory(baseDir);
return Promise.all(typescriptFiles);
}
/** Returns list of the `Standalone` @Component class names for given file */
function analyzeFile(file: File): string[] {
const componentClassNames: string[] = [];
const sourceFile = ts.createSourceFile(file.path, file.content, ts.ScriptTarget.Latest, false);
const visitNode = (node: ts.Node): void => {
if (ts.isClassDeclaration(node)) {
const decorators = ts.getDecorators(node);
const componentName = node.name ? node.name.text : null;
if (decorators && decorators.length) {
for (const decorator of decorators) {
const call = decorator.expression;
if (
ts.isCallExpression(call) &&
ts.isIdentifier(call.expression) &&
call.expression.text === 'Component' &&
call.arguments.length > 0 &&
ts.isObjectLiteralExpression(call.arguments[0])
) {
const hasStandaloneProperty = call.arguments[0].properties.some(
(property) =>
property.name &&
ts.isIdentifier(property.name) &&
property.name.text === 'standalone',
);
if (hasStandaloneProperty && componentName) {
componentClassNames.push(componentName);
}
}
}
}
}
ts.forEachChild(node, visitNode);
};
visitNode(sourceFile);
return componentClassNames;
}
function generatePreviewsComponentMap(data: AnalyzedFiles[]): string {
let result = '';
for (const fileData of data) {
for (const componentName of fileData.componentNames) {
const key = `${fileData.path}${
fileData.componentNames.length > 1 ? '_' + componentName : ''
}`.replace(/\\/g, '/');
result += `['${key}']: () => import('${EXAMPLES_PATH}/${fileData.path
.replace(/\\/g, '/')
.replace('.ts', '')}').then(c => c.${componentName}),\n`;
}
}
return fs
.readFileSync('scripts/examples/previews-components.template', 'utf8')
.replace(/\${previewsComponents}/g, result);
}
@@ -0,0 +1,23 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
/**
******************************************************************************
* DO NOT MANUALLY EDIT THIS FILE. THIS FILE IS AUTOMATICALLY GENERATED.
******************************************************************************
*/
import {Type} from '@angular/core';
/**
* Map of the previews components, values are functions which returns the promise of the component type, which will be displayed as preview in the ExampleViewer component.
* Keys has to be equal to paths written down in the docs markdown files.
*/
export const PREVIEWS_COMPONENTS_MAP: Record<string, () => Promise<Type<unknown>>> = {
${previewsComponents}
};
@@ -0,0 +1,221 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {dirname, join} from 'path';
import {readFile, writeFile} from 'fs/promises';
import {
ASSETS_EXAMPLE_PATH,
CSS_TS_COPYRIGHT,
EXAMPLES_PATH,
HTML_COPYRIGHT,
STACKBLITZ_TEMPLATE_PATH,
STACKBLITZ_CONFIG_FILENAME,
TEMPORARY_EXAMPLES_PATH,
EXCLUDE_FILES_FOR_STACKBLITZ,
} from './utils/examples-constants.mjs';
import {copyFolder, createFolder, removeFolder} from './utils/fs.mjs';
import jsdom from 'jsdom';
import {glob} from 'glob';
import {regionParser} from './../../prerender/markdown-pipeline/regions/region-parser.mjs';
interface StackblitzConfig {
ignore: string[];
file: string;
tags: string[];
description: string;
}
export async function generateStackblitzExample(
exampleFolderName: string,
primaryFilePath: string,
title: string,
) {
const exampleDir = join(EXAMPLES_PATH, exampleFolderName);
const temporaryExampleDir = join(TEMPORARY_EXAMPLES_PATH, exampleFolderName);
const config = await readFile(join(exampleDir, STACKBLITZ_CONFIG_FILENAME), 'utf-8');
const stackblitzConfig: StackblitzConfig = JSON.parse(config);
primaryFilePath = join(...primaryFilePath.split('/'));
await createFolder(temporaryExampleDir);
await combineTemplateWithExample(exampleDir, temporaryExampleDir);
await generateStackblitzHtml(
temporaryExampleDir,
stackblitzConfig,
exampleFolderName,
primaryFilePath,
title,
);
await removeFolder(temporaryExampleDir);
}
async function combineTemplateWithExample(
exampleDir: string,
temporaryExampleDir: string,
): Promise<void> {
// Copy template files to TEMP folder
await copyFolder(STACKBLITZ_TEMPLATE_PATH, temporaryExampleDir);
// Copy example files to TEMP folder
await copyFolder(exampleDir, temporaryExampleDir);
}
async function generateStackblitzHtml(
temporaryExampleDir: string,
stackBlitzConfig: StackblitzConfig,
exampleFolderName: string,
primaryFilePath: string,
title: string,
): Promise<void> {
const defaultIncludes = [
'**/*.ts',
'**/*.js',
'**/*.css',
'**/*.html',
'**/*.md',
'**/*.json',
'**/*.svg',
];
const exampleFilePaths = await glob(defaultIncludes, {
cwd: temporaryExampleDir,
nodir: true,
dot: true,
ignore: stackBlitzConfig.ignore,
});
const postData = await createPostData(
temporaryExampleDir,
stackBlitzConfig,
exampleFilePaths,
title,
);
const primaryFile = getPrimaryFile(primaryFilePath ?? stackBlitzConfig.file, exampleFilePaths);
const html = createStackblitzHtml(postData, primaryFile);
const stackblitzHtmlPath = join(
join(ASSETS_EXAMPLE_PATH, exampleFolderName),
`${primaryFile}.html`,
);
await createFolder(dirname(stackblitzHtmlPath));
await writeFile(stackblitzHtmlPath, html, 'utf-8');
}
function getPrimaryFile(primaryFilePath: string, exampleFilePaths: string[]): string {
if (primaryFilePath) {
if (!exampleFilePaths.some((filePath) => filePath === primaryFilePath)) {
throw new Error(`The specified primary file (${primaryFilePath}) does not exist!`);
}
return primaryFilePath;
} else {
const defaultPrimaryFilePaths = [
'src/app/app.component.html',
'src/app/app.component.ts',
'src/app/main.ts',
];
const primaryFile = defaultPrimaryFilePaths.find((path) =>
exampleFilePaths.some((filePath) => filePath === path),
);
if (!primaryFile) {
throw new Error(
`None of the default primary files (${defaultPrimaryFilePaths.join(', ')}) exists.`,
);
}
return primaryFile;
}
}
async function createPostData(
exampleDir: string,
config: StackblitzConfig,
exampleFilePaths: string[],
title: string,
): Promise<Record<string, string>> {
const postData: Record<string, string> = {};
for (const filePath of exampleFilePaths) {
if (EXCLUDE_FILES_FOR_STACKBLITZ.some((excludedFile) => filePath.endsWith(excludedFile))) {
continue;
}
let content = await readFile(join(exampleDir, filePath), 'utf-8');
content = appendCopyright(filePath, content);
content = extractRegions(filePath, content);
postData[`project[files][${filePath}]`] = content;
}
const tags = ['angular', 'example', ...(config.tags || [])];
tags.forEach((tag, index) => (postData[`project[tags][${index}]`] = tag));
postData['project[description]'] = `Angular Example - ${config.description}`;
postData['project[template]'] = 'node';
postData['project[title]'] = title ?? 'Angular Example';
return postData;
}
function createStackblitzHtml(postData: Record<string, string>, primaryFile: string): string {
const baseHtml = createBaseStackblitzHtml(primaryFile);
const doc = new jsdom.JSDOM(baseHtml).window.document;
const form = doc.querySelector('form');
for (const [key, value] of Object.entries(postData)) {
const element = htmlToElement(doc, `<input type="hidden" name="${key}">`);
if (element && form) {
element.setAttribute('value', value as string);
form.appendChild(element);
}
}
return doc.documentElement.outerHTML;
}
function createBaseStackblitzHtml(primaryFile: string) {
const file = `?file=${primaryFile}`;
const action = `https://stackblitz.com/run${file}`;
return `
<!DOCTYPE html><html lang="en"><body>
<form id="mainForm" method="post" action="${action}" target="_self"></form>
<script>
var embedded = 'ctl=1';
var isEmbedded = window.location.search.indexOf(embedded) > -1;
if (isEmbedded) {
var form = document.getElementById('mainForm');
var action = form.action;
var actionHasParams = action.indexOf('?') > -1;
var symbol = actionHasParams ? '&' : '?'
form.action = form.action + symbol + embedded;
}
document.getElementById("mainForm").submit();
</script>
</body></html>
`.trim();
}
function appendCopyright(filename: string, content: string): string {
if (filename.endsWith('.html')) {
return `${HTML_COPYRIGHT}${content}`;
} else if (filename.endsWith('.ts') || filename.endsWith('.css')) {
return `${CSS_TS_COPYRIGHT}${content}`;
}
return content;
}
function htmlToElement(document: Document, html: string) {
const div = document.createElement('div');
div.innerHTML = html;
return div.firstElementChild;
}
function extractRegions(path: string, contents: string): string {
const regionParserResult = regionParser(contents, path);
return regionParserResult.contents;
}
+8
View File
@@ -0,0 +1,8 @@
{
"extends": "../../tsconfig.json",
"ts-node": {
"compilerOptions": {
"module": "es2020"
}
}
}
@@ -0,0 +1,55 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {dirname, join} from 'path';
import {fileURLToPath} from 'url';
const BASE = dirname(fileURLToPath(import.meta.url));
// Directory paths
export const ASSETS_EXAMPLE_PATH = join(
BASE,
'../../../src/assets/content/examples',
);
export const EXAMPLES_PATH = join(BASE, '../../../src/content/examples');
export const STACKBLITZ_TEMPLATE_PATH = join(
BASE,
'../../../src/content/stackblitz-template',
);
export const TEMPORARY_EXAMPLES_PATH = join(fileURLToPath(import.meta.url), '../../../../TEMP');
// Extensions
export const TEST_FILES_EXTENSION_SUFFIX = '.spec.ts';
export const TEST_FILES_E2E_EXTENSION_SUFFIX = '.e2e-spec.ts';
// Filename
// TODO: BUILD.bazel and example-config will be deprecated when migration to standalone examples will be done.
export const BUILD_BAZEL_FILENAME = 'BUILD.bazel';
export const EXAMPLE_CONFIG_FILENAME = 'example-config.json';
export const STACKBLITZ_CONFIG_FILENAME = 'stackblitz.json';
// Copyright
const PAD = '\n\n';
const COPYRIGHT =
'@license\n' +
'Copyright Google LLC All Rights Reserved.\n' +
'\n' +
'Use of this source code is governed by an MIT-style license that can be\n' +
'found in the LICENSE file at https://angular.dev/license\n';
export const CSS_TS_COPYRIGHT = `/*\n${COPYRIGHT}\n*/${PAD}`;
export const HTML_COPYRIGHT = `<!-- \n${COPYRIGHT}\n-->${PAD}`;
// Exclude
export const EXCLUDE_FILES_FOR_STACKBLITZ = [
STACKBLITZ_CONFIG_FILENAME,
BUILD_BAZEL_FILENAME,
EXAMPLE_CONFIG_FILENAME,
TEST_FILES_EXTENSION_SUFFIX,
TEST_FILES_E2E_EXTENSION_SUFFIX,
];
+77
View File
@@ -0,0 +1,77 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Dirent, existsSync, readdirSync} from 'fs';
import {copyFile, mkdir, readFile, readdir, rm, stat} from 'fs/promises';
import {join, relative} from 'path';
export async function copyFolder(source: string, destination: string) {
if (!existsSync(destination)) {
await mkdir(destination, {recursive: true});
}
const files = await readdir(source);
for (const file of files) {
const sourcePath = join(source, file);
const destPath = join(destination, file);
const stats = await stat(sourcePath);
const isDirectory = await stats.isDirectory();
if (isDirectory) {
await copyFolder(sourcePath, destPath);
} else {
await copyFile(sourcePath, destPath);
}
}
}
/** Recursively search the provided directory for all files which satisfy predicate and asynchronously load them. */
export function retrieveFiles(
baseDir: string,
predicate?: (file: Dirent) => boolean,
): Promise<{path: string; content: string}[]> {
const filesWithContent: Promise<{path: string; content: string}>[] = [];
const checkFilesInDirectory = (dir: string) => {
const files = readdirSync(dir, {withFileTypes: true});
for (const file of files) {
const fullPathToFile = join(dir, file.name);
if (file.isFile() && (predicate ? predicate(file) : true)) {
filesWithContent.push(
readFile(fullPathToFile, {encoding: 'utf-8'}).then((fileContent) => {
return {
path: relative(baseDir, fullPathToFile),
content: fileContent,
};
}),
);
} else if (file.isDirectory()) {
checkFilesInDirectory(fullPathToFile);
}
}
};
checkFilesInDirectory(baseDir);
return Promise.all(filesWithContent);
}
export async function createFolder(path: string): Promise<void> {
if (!existsSync(path)) {
await mkdir(path, {recursive: true});
}
}
export async function removeFolder(path: string): Promise<void> {
if (existsSync(path)) {
await rm(path, {recursive: true});
}
}
@@ -0,0 +1,35 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {dirname, join} from 'path';
import {fileURLToPath} from 'url';
// FOLDER NAMES
export const ASSETS_FOLDER_NAME = 'assets';
export const CONTENT_FOLDER_NAME = 'content';
export const EXAMPLES_FOLDER_NAME = 'examples';
export const TUTORIALS_FOLDER_NAME = 'tutorials';
// PATHS
export const BASE_PATH = dirname(fileURLToPath(import.meta.url));
export const ASSETS_EXAMPLES_PATH = 'assets/content/examples';
export const PROJECT_FOLDER_PATH = join(BASE_PATH, '../../src');
export const ASSETS_CONTENT_FOLDER_PATH = join(
PROJECT_FOLDER_PATH,
ASSETS_FOLDER_NAME,
CONTENT_FOLDER_NAME,
);
export const CONTENT_FOLDER_PATH = join(PROJECT_FOLDER_PATH, CONTENT_FOLDER_NAME);
export const EXAMPLES_FOLDER_PATH = join(CONTENT_FOLDER_PATH, EXAMPLES_FOLDER_NAME);
export const TUTORIALS_FOLDER_PATH = join(CONTENT_FOLDER_PATH, TUTORIALS_FOLDER_NAME);
// TODO: Update the branch/sha
// URLS
export const GITHUB_CONTENT_URL = 'https://github.com/angular/angular/blob/main/adev/src/content';
export const GITHUB_EDIT_CONTENT_URL =
'https://github.com/angular/angular/edit/main/adev/src/content';
@@ -0,0 +1,146 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {run} from '@mermaid-js/mermaid-cli';
import {readFile, writeFile} from 'fs/promises';
import {marked} from 'marked';
import {v4 as uuidv4} from 'uuid';
import {
DocsCodeMultifileToken,
DocsCodeToken,
DocsCodeTripleTickBlockToken,
} from './tranformations/docs-code.mjs';
import {generateStackblitzExample} from './../../scripts/examples/stackblitz-builder.mjs';
export const MERMAID_TEMP_FOLDER = 'TEMP';
const MERMAID_INPUT = `${MERMAID_TEMP_FOLDER}/mermaid-input-#{id}.mmd`;
const MERMAID_OUTPUT_SVG = `${MERMAID_TEMP_FOLDER}/mermaid-output-#{id}.svg`;
// If token type is 'docs-code' or 'docs-code-triple-tick' and language is 'mermaid' then we can try to render Mermaid svg.
export async function docsWalkTokens(walkToken: marked.Tokens.Generic): Promise<void> {
const token = walkToken as DocsCodeToken | DocsCodeTripleTickBlockToken | DocsCodeMultifileToken;
await handleMermaid(token);
await handleStackblitzExamples(token);
}
async function handleMermaid(
token: DocsCodeToken | DocsCodeMultifileToken | DocsCodeTripleTickBlockToken,
) {
if (
token.language === 'mermaid' &&
(token.type === 'docs-code' || token.type === 'docs-code-triple-tick')
) {
token.code = await renderMermaidToSvg(token.code);
}
}
async function handleStackblitzExamples(
token: DocsCodeToken | DocsCodeTripleTickBlockToken | DocsCodeMultifileToken,
) {
if (
(token.type !== 'docs-code' && token.type !== 'docs-code-multifile') ||
!token.preview ||
!token.path
) {
return;
}
const defaultCodeToken: marked.Tokens.Generic =
token.type === 'docs-code-multifile' ? token.paneTokens[0] : token;
const path: string = defaultCodeToken['diff'] ?? defaultCodeToken['path'];
const pathToExampleRule = /([^\/]+)\/(.+)/s;
const pathToExampleSegments = path.match(pathToExampleRule);
if (!pathToExampleSegments) {
return;
}
const exampleFolder = pathToExampleSegments[1];
const primaryFilePath = pathToExampleSegments[2];
await generateStackblitzExample(exampleFolder, primaryFilePath, defaultCodeToken['header']);
}
export async function renderMermaidToSvg(content: string): Promise<string> {
// Generate input and output path
const mermaidTempFileId = uuidv4();
const input = MERMAID_INPUT.replace('#{id}', mermaidTempFileId);
const output = MERMAID_OUTPUT_SVG.replace('#{id}', mermaidTempFileId) as `${string}.svg`;
// Create *.mmd file with provided content.
await writeFile(input, content);
// Execute rendering. The generated SVG file will be written in the output path.
await run(input, output, {
quiet: true,
puppeteerConfig: {headless: 1},
parseMMDOptions: {
mermaidConfig: {
themeCSS: `
background-color: var(--page-background) !important; // svg background color
g {
rect {
stroke: black !important; // border around the rectangles, same for dark/light theme
filter: drop-shadow(5px 5px 0px var(--vivid-pink));
}
}
.messageText, .pieTitleText {
fill: var(--primary-contrast) !important; // pie chart title text and line labels
}
.pieOuterCircle {
stroke-width: 1px;
}
.pieCircle {
stroke-width: 1.5px;
}
.legend {
rect {
filter: none;
opacity: 0.7;
}
text {
fill: var(--primary-contrast) !important; // legend label text color
}
}
.slice { // e.g. text on the pie charts
fill: var(--primary-contrast) !important;
}
.flowchart-link, line { // lines
stroke: var(--primary-contrast) !important;
}
.marker,
#statediagram-barbEnd,
.transition,
#arrowhead path { // arrows
stroke: var(--primary-contrast) !important;
fill: var(--primary-contrast) !important;
}
.cluster rect {
stroke: var(--primary-contrast) !important;
fill: var(--page-background) !important;
}
`,
theme: 'base',
themeVariables: {
fontFamily: 'sans-serif',
primaryColor: '#fff',
primaryBorderColor: '#000',
pie1: '#0546ff',
pie2: '#f637e3',
pie3: '#f11653',
pie4: '#8001c6',
pie5: '#00c572',
pie6: '#fe3700',
},
},
},
});
// Read the content of generated SVG file.
return await readFile(output, 'utf8');
}
@@ -0,0 +1,22 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {resetHeaderIdsOfCurrentDocument} from './state.mjs';
/**
* Custom hooks for marked that will be used to post-transform markdown files with parent styles for Angular docs.
*/
export const hooks = {
preprocess(html: string): string {
resetHeaderIdsOfCurrentDocument();
return html;
},
postprocess(html: string): string {
return html;
},
};
+189
View File
@@ -0,0 +1,189 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {existsSync} from 'fs';
import {copyFile, mkdir, readdir, rm, stat, writeFile} from 'fs/promises';
import {marked} from 'marked';
import {dirname, join} from 'path';
import {PROJECT_FOLDER_PATH} from './constants.mjs';
import {MERMAID_TEMP_FOLDER, docsWalkTokens} from './docs-walk-tokens.mjs';
import {hooks} from './hooks.mjs';
import {renderer} from './renderer.mjs';
import {setCurrentParsedFilePath} from './state.mjs';
import {docsAlertExtension} from './tranformations/docs-alert.mjs';
import {docsCalloutExtension} from './tranformations/docs-callout.mjs';
import {docsCardContainerExtension, docsCardExtension} from './tranformations/docs-card.mjs';
import {
docsCodeExtension,
docsCodeMultifileExtension,
docsTripleTickMarkdownCodeExtension,
} from './tranformations/docs-code.mjs';
import {docsDecorativeHeaderExtension} from './tranformations/docs-decorative-header.mjs';
import {docsPillExtension, docsPillRowExtension} from './tranformations/docs-pill.mjs';
import {docsVideoExtension} from './tranformations/docs-video.mjs';
import {docsStepExtension, docsWorkflowExtension} from './tranformations/docs-workflow.mjs';
import {retrieveAllMarkdownFiles} from './utils.mjs';
declare var logs: string[];
(globalThis as any).logs = [];
/**
* Fully configured processor instance.
*
* Marked was chosen as our processor as it is a popular and well supported by the community. Additionally,
* its processing of custom HTML allows for a more direct interactions rather than being done within a custom
* AST representation as other solutions provide.
*/
marked.use({
mangle: false,
headerIds: false,
renderer,
hooks,
extensions: [
/** Custom Extensions are @type marked.TokenizerAndRendererExtension but the this.renderer uses a custom Token that extends marked.Tokens.Generic which is not exported by @types/marked */
// @ts-ignore @types/marked
docsCardExtension,
// @ts-ignore @types/marked
docsCardContainerExtension,
// @ts-ignore @types/marked
docsCalloutExtension,
// @ts-ignore @types/marked
docsDecorativeHeaderExtension,
// @ts-ignore @types/marked
docsPillRowExtension,
// @ts-ignore @types/marked
docsPillExtension,
// @ts-ignore @types/marked
docsWorkflowExtension,
// @ts-ignore @types/marked
docsStepExtension,
// @ts-ignore @types/marked
docsCodeExtension,
// @ts-ignore @types/marked
docsCodeMultifileExtension,
// @ts-ignore @types/marked
docsTripleTickMarkdownCodeExtension,
// @ts-ignore @types/marked
docsAlertExtension,
// @ts-ignore @types/marked
docsVideoExtension,
],
// Marked will return a promise if the async option is true.
// The async option will tell marked to await any walkTokens functions before parsing the tokens and returning an HTML string.
// More details: https://marked.js.org/using_pro#async
async: true,
walkTokens: docsWalkTokens,
});
main();
async function main() {
/** Create temporary folder which helps to generate mermaid diagrams in the svg format */
await createTempMermaidFolder();
/** Generate Docs Content */
await generateContent(
join(PROJECT_FOLDER_PATH, 'content'),
join(PROJECT_FOLDER_PATH, 'assets', 'content'),
);
/** Copy the images from source content folder to assets */
await copyFolder(
join(PROJECT_FOLDER_PATH, 'content', 'images'),
join(PROJECT_FOLDER_PATH, 'assets', 'content', 'images'),
);
/** Remove temp folder */
await cleanUp();
}
async function generateContent(baseDir: string, distDir: string) {
const consoleTimeLabel = '\nMarkdown files processed in';
console.info(`Processing markdown files...`);
console.time(consoleTimeLabel);
/** List of all markdown files in the content directory. */
const files = await retrieveAllMarkdownFiles(baseDir);
/** These directories have no markdown destined to be in the docs */
const skipDirectories = ['examples'];
const filteredFiles = files.filter((f) => !skipDirectories.some((dir) => f.path.startsWith(dir)));
await Promise.all(
filteredFiles.map((file) =>
mkdir(join(distDir, dirname(file.path)), {recursive: true}).catch(console.error),
),
);
let hadWarnings = false;
for (let index = 0; index < filteredFiles.length; index++) {
const file = filteredFiles[index];
// Basic progress report
process.stdout.write('\r\x1b[K');
process.stdout.write(`${index}/${filteredFiles.length} - Processing ${file.path}`);
// keep in mind write doesn't write a newline like console.log does
// Logging is handcrafted because markedjs provides no solution
// Moreover it has no context of filename as it is only string based
// So we're using a global `logs` array
if (logs.length) {
console.warn('\n');
logs.forEach((log) => {
console.warn(`${file.path}: ${log}`);
});
console.warn('\n');
logs.length = 0;
hadWarnings = true;
}
setCurrentParsedFilePath(file.path);
const processedFile = await marked.parse(file.content, {async: true});
const htmlFilePath = `${file.path}.html`;
await writeFile(join(distDir, htmlFilePath), processedFile.toString());
}
if (hadWarnings) {
console.warn(
`\n\nYou can resolve the ambiguities by editing the mentioned file(s) and adding a specific link using the Markdown syntax.`,
);
}
console.timeEnd(consoleTimeLabel);
}
async function createTempMermaidFolder() {
if (!existsSync(MERMAID_TEMP_FOLDER)) {
await mkdir(MERMAID_TEMP_FOLDER);
}
}
async function cleanUp() {
if (existsSync(MERMAID_TEMP_FOLDER)) {
await rm(MERMAID_TEMP_FOLDER, {recursive: true});
}
}
async function copyFolder(source: string, destination: string) {
if (!existsSync(destination)) {
await mkdir(destination);
}
const files = await readdir(source);
for (const file of files) {
const sourcePath = join(source, file);
const destPath = join(destination, file);
const stats = await stat(sourcePath);
(await stats.isDirectory()) ? copyFolder(sourcePath, destPath) : copyFile(sourcePath, destPath);
}
}
@@ -0,0 +1,3 @@
# Code Regions
All the files in the regions folder were implemented based on angular.io: <https://github.com/angular/angular/tree/main/aio/tools/transforms/examples-package/services>.
@@ -0,0 +1,13 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// These kind of comments are used CSS and other languages that do not support inline comments
export const regionStartMatcher = /^\s*\/\*\s*#docregion\s*(.*)\s*\*\/\s*$/;
export const regionEndMatcher = /^\s*\/\*\s*#enddocregion\s*(.*)\s*\*\/\s*$/;
export const plasterMatcher = /^\s*\/\*\s*#docplaster\s*(.*)\s*\*\/\s*$/;
export const createPlasterComment = (plaster: string) => `/* ${plaster} */`;
@@ -0,0 +1,14 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// These kind of comments are used in HTML
export const regionStartMatcher = /^\s*<!--\s*#docregion\s*(.*?)\s*(?:-->)?\s*$/;
export const regionEndMatcher = /^\s*<!--\s*#enddocregion\s*(.*?)\s*-->\s*$/;
export const plasterMatcher = /^\s*<!--\s*#docplaster\s*(.*?)\s*-->\s*$/;
export const createPlasterComment = (plaster: string) => `<!-- ${plaster} -->`;
@@ -0,0 +1,13 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// These kind of comments are used in languages that do not support block comments, such as Jade
export const regionStartMatcher = /^\s*\/\/\s*#docregion\s*(.*)\s*$/;
export const regionEndMatcher = /^\s*\/\/\s*#enddocregion\s*(.*)\s*$/;
export const plasterMatcher = /^\s*\/\/\s*#docplaster\s*(.*)\s*$/;
export const createPlasterComment = (plaster: string) => `// ${plaster}`;
@@ -0,0 +1,13 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// This comment type is used in C like languages such as JS, TS, etc
export const regionStartMatcher = /^\s*\/\/\s*#docregion\s*(.*)\s*$/;
export const regionEndMatcher = /^\s*\/\/\s*#enddocregion\s*(.*)\s*$/;
export const plasterMatcher = /^\s*\/\/\s*#docplaster\s*(.*)\s*$/;
export const createPlasterComment = (plaster: string) => `/* ${plaster} */`;
@@ -0,0 +1,13 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// These type of comments are used in hash comment based languages such as bash and Yaml
export const regionStartMatcher = /^\s*#\s*#docregion\s*(.*)\s*$/;
export const regionEndMatcher = /^\s*#\s*#enddocregion\s*(.*)\s*$/;
export const plasterMatcher = /^\s*#\s*#docplaster\s*(.*)\s*$/;
export const createPlasterComment = (plaster: string) => `# ${plaster}`;
@@ -0,0 +1,196 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import * as blockC from './region-matchers/block-c.mjs';
import * as html from './region-matchers/html.mjs';
import * as inlineC from './region-matchers/inline-c.mjs';
import * as inlineCOnly from './region-matchers/inline-c-only.mjs';
import * as inlineHash from './region-matchers/inline-hash.mjs';
import {FileType, removeEslintComments} from './removeEslintComments.mjs';
const WHOLE_FILE_REGION_NAME = '';
const DEFAULT_PLASTER = '. . .';
const REGION_MATCHERS = {
ts: inlineC,
js: inlineC,
mjs: inlineCOnly,
es6: inlineC,
html: html,
svg: html,
css: blockC,
conf: inlineHash,
yaml: inlineHash,
yml: inlineHash,
sh: inlineHash,
jade: inlineCOnly,
pug: inlineCOnly,
json: inlineCOnly,
'json.annotated': inlineCOnly,
};
interface Region {
lines: string[];
open?: boolean;
ranges: {from: number; to?: number}[];
}
/**
* NOTE: We assume that the tag defining the beginning and end of the region will be in different lines in each case.
* For example, in HTML, we don't expect to have the following code on one line: <!-- docregion name -->content<!--enddocregion name-->
*/
export const regionParser = (contents: string, filePath: string) => {
const fileType: FileType | undefined = filePath?.split('.').pop() as FileType;
if (!fileType) {
throw new Error(`Incorrect file type for region parser: ${filePath}!`);
}
const regionMatcher = REGION_MATCHERS[fileType];
const openRegions: string[] = [];
const regionMap: Record<string, Region> = {};
let countOfRegionLines = 0;
if (regionMatcher) {
let plaster = regionMatcher.createPlasterComment(DEFAULT_PLASTER);
const lines = removeEslintComments(contents, fileType)
.split(/\r?\n/)
.filter((line, index) => {
const startRegion = line.match(regionMatcher.regionStartMatcher);
const endRegion = line.match(regionMatcher.regionEndMatcher);
const updatePlaster = line.match(regionMatcher.plasterMatcher);
// start region processing
if (startRegion) {
// open up the specified region
handleStartRegion(
startRegion,
regionMap,
index,
countOfRegionLines,
plaster,
openRegions,
);
} else if (endRegion) {
// end region processing
handleEndRegion(openRegions, endRegion, regionMap, index, countOfRegionLines);
} else if (updatePlaster) {
// doc plaster processing
const plasterString = updatePlaster[1].trim();
plaster = plasterString ? regionMatcher.createPlasterComment(plasterString) : '';
} else {
// simple line of content processing
openRegions.forEach((regionName) => regionMap[regionName].lines.push(line));
// do not filter out this line from the content
return true;
}
// this line contained an annotation so let's filter it out
countOfRegionLines++;
return false;
});
if (!regionMap[WHOLE_FILE_REGION_NAME]) {
regionMap[WHOLE_FILE_REGION_NAME] = {lines, ranges: [{from: 1, to: lines.length + 1}]};
}
return {
contents: lines.join('\n'),
regionMap,
totalLinesCount: lines.length,
};
} else {
return {contents, regionMap, totalLinesCount: 0};
}
};
function handleStartRegion(
startRegion: RegExpMatchArray,
regionMap: Record<string, Region>,
index: number,
countOfRegionLines: number,
plaster: string,
openRegions: string[],
) {
const regionNames = getRegionNames(startRegion[1]);
if (regionNames.length === 0) {
regionNames.push(WHOLE_FILE_REGION_NAME);
}
for (const regionName of regionNames) {
const region = regionMap[regionName];
if (region) {
if (region.open) {
throw new Error(`Tried to open a region, named "${regionName}", that is already open`);
}
// Region is opened, set from range value.
region.open = true;
region.ranges.push({from: getFromRangeValue(index, countOfRegionLines)});
if (plaster) {
// Use the same indent as the docregion marker
const indent = startRegion[0].split(/[^ ]/, 1);
region.lines.push(indent + plaster);
}
} else {
regionMap[regionName] = {
lines: [],
open: true,
ranges: [
{
from: getFromRangeValue(index, countOfRegionLines),
},
],
};
}
openRegions.push(regionName);
}
}
function handleEndRegion(
openRegions: string[],
endRegion: RegExpMatchArray,
regionMap: Record<string, Region>,
index: number,
countOfRegionLines: number,
) {
if (openRegions.length === 0) {
throw new Error('Tried to close a region when none are open');
}
// close down the specified region (or most recent if no name is given)
const regionNames = getRegionNames(endRegion[1]);
if (regionNames.length === 0) {
regionNames.push(openRegions[openRegions.length - 1]);
}
for (const regionName of regionNames) {
const region = regionMap[regionName];
if (!region || !region.open) {
throw new Error(`Tried to close a region, named "${regionName}", that is not open`);
}
// Region is closed, we can define the last line number of the region
region.open = false;
region.ranges[region.ranges.length - 1].to = index - countOfRegionLines;
removeLast(openRegions, regionName);
}
}
function getFromRangeValue(index: number, countOfRegionLines: number): number {
return index - countOfRegionLines + 1;
}
function getRegionNames(input: string): string[] {
return input.trim() === '' ? [] : input.split(',').map((name) => name.trim());
}
function removeLast(array: string[], item: string): void {
const index = array.lastIndexOf(item);
array.splice(index, 1);
}
@@ -0,0 +1,58 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export type FileType =
| 'ts'
| 'js'
| 'mjs'
| 'es6'
| 'html'
| 'svg'
| 'css'
| 'conf'
| 'yaml'
| 'yml'
| 'sh'
| 'jade'
| 'pug'
| 'json'
| 'json.annotated';
export function removeEslintComments(input: string, fileType: FileType) {
if (!input || (fileType !== 'ts' && fileType !== 'js' && fileType !== 'html')) {
return input;
}
const regexForFileType = regexesForFileTypes[fileType];
return input.replace(regexForFileType, '');
}
const jsRegexes = [
/\/\/ *eslint-disable(?:-next-line)?(?: .*)?(?:\n *|$)/,
/\n? *\/\/ *eslint-(?:disable-line|enable)(?: .*)?(?=\n|$)/,
/\/\*\s*eslint-disable(?:-next-line)?(?: [\s\S]*?)?\*\/ *(?:\n *)?/,
/\n? *\/\*\s*eslint-(?:disable-line|enable)(?: [\s\S]*?)?\*\//,
];
const htmlRegexes = [
/<!--\s*eslint-disable(?:-next-line)?(?: [\s\S]*?)?--> *(?:\n *)?/,
/\n? *<!--\s*eslint-(?:disable-line|enable)(?: [\s\S]*?)?-->/,
];
const joinRegexes = (regexes: any) =>
new RegExp(regexes.map((regex: any) => `(?:${regex.source})`).join('|'), 'g');
const htmlRegex = joinRegexes(htmlRegexes);
// Note: the js regex needs to also include the html ones to account for inline templates in @Components
const jsRegex = joinRegexes([...jsRegexes, ...htmlRegexes]);
const regexesForFileTypes = {
js: jsRegex,
ts: jsRegex,
html: htmlRegex,
};
@@ -0,0 +1,61 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Renderer as MarkedRenderer, marked} from 'marked';
import {handleCode} from './tranformations/code.mjs';
import {handleEmoji} from './tranformations/emoji.mjs';
import {transformH1} from './tranformations/h1.mjs';
import {transformHeader} from './tranformations/header.mjs';
import {transformImage} from './tranformations/image.mjs';
import {transformLink} from './tranformations/link.mjs';
import {transformDocsList} from './tranformations/lists.mjs';
import {transformDocsTable} from './tranformations/table.mjs';
/**
* Custom renderer for marked that will be used to transform markdown files to HTML
* files that can be used in the Angular docs.
*/
export const renderer: Partial<MarkedRenderer> = {
// All headers have tabindex="-1"
// so that we can focus relevant sections on
// navigation for accessibility purposes.
heading(label: string, level: number) {
switch (level) {
// Custom H1 header element with page breadcrumb and docs edit button link to GitHub
case 1:
return transformH1(label);
// Custom headers include an anchor link and href
default:
return transformHeader(label, level);
}
},
// Custom table styling
table(header: string, body: string) {
return transformDocsTable(header, body);
},
// Custom list styling
list(body: string, ordered: boolean) {
return transformDocsList(body, ordered);
},
// Custom list styling
image(href: string | null, title: string | null, text: string) {
return transformImage(href, title, text);
},
// Handles special behavior for external links
link(href: string | null, title: string | null, text: string) {
return transformLink(href, title, text);
},
// Custom code span styling
codespan(this: marked.RendererThis, code: string): string {
return handleCode(code);
},
// Custom text styling
text(this: marked.RendererThis, code: string): string {
return handleEmoji(code);
},
};
@@ -0,0 +1,58 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {TUTORIALS_FOLDER_NAME} from './constants.mjs';
export const enum DocumentType {
DOCS,
TUTORIAL,
}
let currentParsedPath: string | null = null;
let currentParsedDocumentType: DocumentType = DocumentType.DOCS;
const headerIds = new Map<string, number>();
export const setCurrentParsedFilePath = (path: string) => {
currentParsedPath = path;
setCurrentParsedDocumentType(
path.startsWith(TUTORIALS_FOLDER_NAME) ? DocumentType.TUTORIAL : DocumentType.DOCS,
);
};
export const getCurrentParsedFilePath = (): string | null => currentParsedPath;
export const setCurrentParsedDocumentType = (type: DocumentType) => {
currentParsedDocumentType = type;
};
export const getCurrentParsedDocumentType = (): DocumentType => currentParsedDocumentType;
export const getHeaderId = (id: string): string => {
const numberOfHeaderOccurrencesInTheDocument = headerIds.get(id) ?? 0;
headerIds.set(id, numberOfHeaderOccurrencesInTheDocument + 1);
const cleanedUpId = id
.toLowerCase()
.replaceAll(/<code>(.*?)<\/code>/g, '$1') // remove <code>
.replaceAll(/<strong>(.*?)<\/strong>/g, '$1') // remove <strong>
.replaceAll(/<em>(.*?)<\/em>/g, '$1') // remove <em>
.replace(/\s|\//g, '-') // remove spaces and slashes
.replace(/gt;|lt;/g, '') // remove escaped < and >
.replace(/&#\d+;/g, '') // remove HTML entities
.replace(/[^0-9a-zA-Z\-]/g, ''); // only keep letters, digits & dashes
const headerId = numberOfHeaderOccurrencesInTheDocument
? `${cleanedUpId}-${numberOfHeaderOccurrencesInTheDocument}`
: cleanedUpId;
return headerId;
};
export const resetHeaderIdsOfCurrentDocument = (): void => {
headerIds.clear();
};
@@ -0,0 +1,120 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {readFileSync, readdirSync} from 'fs';
import {join} from 'path';
import {ClassEntry, DocEntry, EntryType} from '../../api-gen/entities';
import {handleEmoji} from './emoji.mjs';
// global defined in the index
declare const logs: string[];
// API
interface EntryCollection {
moduleName: string;
entries: DocEntry[];
}
function parseEntryData(srcs: string[]): EntryCollection[] {
return srcs.map((jsonDataFilePath) => {
const fileContent = readFileSync(jsonDataFilePath, {encoding: 'utf8'});
return JSON.parse(fileContent) as EntryCollection;
});
}
interface ParsedEntry {
module: string;
members: string[];
type: EntryType;
isDeprecated: boolean;
}
let apiEntries: undefined | Map<string, Array<ParsedEntry>>;
function getApiEntries(): Map<string, Array<ParsedEntry>> {
const DEV_DATA_PATH = join('prerender', 'api-gen', 'dev-data', 'api');
const filePaths = readdirSync(DEV_DATA_PATH).map((fileName) => join(DEV_DATA_PATH, fileName));
const entryCollections: EntryCollection[] = parseEntryData(filePaths);
const entries = new Map<string, Array<ParsedEntry>>();
entryCollections.forEach((module) => {
const moduleName = module.moduleName.slice(9); // removing "@angular/"" from the name
module.entries.forEach((entry) => {
const members = (entry as ClassEntry).members?.map((m) => m.name) ?? [];
const parsedEntry = {
module: moduleName,
members,
type: entry.entryType,
isDeprecated: entry.jsdocTags.some((tag) => tag.name === 'deprecated'),
};
if (!entries.has(entry.name)) {
entries.set(entry.name, [parsedEntry]);
} else {
entries.get(entry.name)?.push(parsedEntry);
}
});
});
return entries;
}
function defaultCodeBlock(text: string) {
return `<code>${handleEmoji(text)}</code>`;
}
export function handleCode(text: string): string {
if (!apiEntries) {
apiEntries = getApiEntries();
}
// strip trailing the braces for functions,
// remove leading @ for decorators
let entity = text.replace(/^@|(\(\))$/g, '');
let method: string | undefined;
// We're parsing a class.method
if (entity.includes('.')) {
[entity, method] = entity.split('.');
}
if (apiEntries.has(entity)) {
const isDecorator = text.startsWith('@');
const entries = apiEntries.get(entity);
const nonDeprecated = entries?.find((e) => e.isDeprecated);
let entry: ParsedEntry | undefined;
if (entries?.length === 1) {
entry = entries[0];
} else if (entries?.length === 2 && nonDeprecated) {
// Sometime we move an entry from one package to another and deprecate the original entry.
// In this case we have 2 entries with one deprecated, we take the non-deprecated one
entry = nonDeprecated;
}
if (entry) {
if (isDecorator && entry.type !== 'decorator') {
return defaultCodeBlock(text);
}
if (entity && method && entry.members.includes(method)) {
return `<a href="api/${entry.module}/${entity}#${method}"><code>${text}</code></a>`;
}
return `<a href="api/${entry.module}/${entity}"><code>${text}</code></a>`;
} else {
logs.push(`Cannot resolve the ambiguity for: ${entity}`);
}
}
return defaultCodeBlock(text);
}
@@ -0,0 +1,66 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {marked} from 'marked';
import {AlertSeverityLevel} from './enums/levels.mjs';
interface DocsAlertToken extends marked.Tokens.Generic {
type: 'docs-alert';
body: string;
severityLevel: string;
tokens: marked.Token[];
}
interface DocsAlert {
alert: RegExpExecArray | null;
severityLevel: string;
}
export const docsAlertExtension = {
name: 'docs-alert',
level: 'block',
tokenizer(this: marked.TokenizerThis, src: string): DocsAlertToken | undefined {
const match: DocsAlert = {
alert: null,
severityLevel: AlertSeverityLevel.HELPFUL,
};
for (let level in AlertSeverityLevel) {
// Capture group 1: all alert text content after the severity level
const rule = new RegExp('^s*' + level + ': (.*?)\n', 's');
const possibleMatch = rule.exec(src);
if (possibleMatch?.[1]) {
match.alert = possibleMatch;
match.severityLevel = level;
}
}
if (match?.alert) {
const token: DocsAlertToken = {
type: 'docs-alert',
raw: match.alert[0],
body: match.alert[1].trim(),
severityLevel: match.severityLevel,
tokens: [],
};
token.body = `**${
token.severityLevel === AlertSeverityLevel.TLDR ? 'TL;DR' : token.severityLevel
}:** ${token.body}`;
this.lexer.blockTokens(token.body, token.tokens);
return token;
}
return undefined;
},
renderer(this: marked.RendererThis, token: DocsAlertToken) {
return `
<div class="docs-alert docs-alert-${token.severityLevel.toLowerCase()}">
${this.parser.parse(token.tokens)}
</div>
`;
},
};
@@ -0,0 +1,70 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {marked} from 'marked';
import {CalloutSeverityLevel} from './enums/levels.mjs';
interface DocsCalloutToken extends marked.Tokens.Generic {
type: 'docs-callout';
title: string;
titleTokens: marked.Token[];
severityLevel: CalloutSeverityLevel;
body: string;
bodyTokens: marked.Token[];
}
// Capture group 1: all attributes on the opening tag
// Capture group 2: all content between the open and close tags
const calloutRule = /^<docs-callout([^>]*)>((?:.(?!\/docs-callout))*)<\/docs-callout>/s;
const titleRule = /title="([^"]*)"/;
const isImportantRule = /important/;
const isCriticalRule = /critical/;
export const docsCalloutExtension = {
name: 'docs-callout',
level: 'block',
start(src: string) {
return src.match(/^\s*<docs-callout/m)?.index;
},
tokenizer(this: marked.TokenizerThis, src: string): DocsCalloutToken | undefined {
const match = calloutRule.exec(src);
if (match) {
const attr = match[1].trim();
const title = titleRule.exec(attr);
let severityLevel = CalloutSeverityLevel.HELPFUL;
if (isImportantRule.exec(attr)) severityLevel = CalloutSeverityLevel.IMPORTANT;
if (isCriticalRule.exec(attr)) severityLevel = CalloutSeverityLevel.CRITICAL;
const body = match[2].trim();
const token: DocsCalloutToken = {
type: 'docs-callout',
raw: match[0],
severityLevel: severityLevel,
title: title ? title[1] : '',
titleTokens: [],
body: body ?? '',
bodyTokens: [],
};
this.lexer.inlineTokens(token.title, token.titleTokens);
this.lexer.blockTokens(token.body, token.bodyTokens);
return token;
}
return undefined;
},
renderer(this: marked.RendererThis, token: DocsCalloutToken) {
return `
<div class="docs-callout docs-callout-${token.severityLevel.toLowerCase()}">
<h3>${this.parser.parseInline(token.titleTokens)}</h3>
<p>${this.parser.parse(token.bodyTokens)}</p>
</div>
`;
},
};
@@ -0,0 +1,169 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {marked} from 'marked';
import {targetForExternalHref} from './helpers.mjs';
import {PROJECT_FOLDER_PATH} from '../constants.mjs';
import {join} from 'path';
import {readFileSync} from 'fs';
interface DocsCardContainerToken extends marked.Tokens.Generic {
type: 'docs-card-container';
cards: string;
tokens: marked.Token[];
}
const cardContainerRule = /^<docs-card-container>(.*?)<\/docs-card-container>/s;
export const docsCardContainerExtension = {
name: 'docs-card-container',
level: 'block',
start(src: string) {
return src.match(/^\s*<docs-card-container/m)?.index;
},
tokenizer(this: marked.TokenizerThis, src: string): DocsCardContainerToken | undefined {
const match = cardContainerRule.exec(src);
if (match) {
const body = match[1];
const token: DocsCardContainerToken = {
type: 'docs-card-container',
raw: match[0],
cards: body ?? '',
tokens: [],
};
this.lexer.blockTokens(token.cards, token.tokens);
return token;
}
return undefined;
},
renderer(this: marked.RendererThis, token: DocsCardContainerToken) {
return `
<div class="docs-card-grid">
${this.parser.parse(token.tokens)}
</div>
`;
},
};
interface DocsCardToken extends marked.Tokens.Generic {
type: 'docs-card';
title: string;
body: string;
link?: string;
href?: string;
imgSrc?: string;
tokens: marked.Token[];
}
// Capture group 1: all attributes on the opening tag
// Capture group 2: all content between the open and close tags
const cardRule = /^[^<]*<docs-card\s([^>]*)>((?:.(?!\/docs-card))*)<\/docs-card>/s;
const titleRule = /title="([^"]*)"/;
const linkRule = /link="([^"]*)"/;
const hrefRule = /href="([^"]*)"/;
const imgSrcRule = /imgSrc="([^"]*)"/;
export const docsCardExtension = {
name: 'docs-card',
level: 'block',
start(src: string) {
return src.match(/^\s*<docs-card\s*/m)?.index;
},
tokenizer(this: marked.TokenizerThis, src: string): DocsCardToken | undefined {
const match = cardRule.exec(src);
if (match) {
const attr = match[1].trim();
const title = titleRule.exec(attr);
const link = linkRule.exec(attr);
const href = hrefRule.exec(attr);
const imgSrc = imgSrcRule.exec(attr);
const body = match[2].trim();
const token: DocsCardToken = {
type: 'docs-card',
raw: match[0],
title: title ? title[1] : '',
body: body ?? '',
href: href ? href[1] : undefined,
link: link ? link[1] : undefined,
imgSrc: imgSrc ? imgSrc[1] : undefined,
tokens: [],
};
this.lexer.blockTokens(token.body, token.tokens);
return token;
}
return undefined;
},
renderer(this: marked.RendererThis, token: DocsCardToken) {
return token.imgSrc ? getCardWithSvgIllustration(this, token) : getStandardCard(this, token);
},
};
function getStandardCard(renderer: marked.RendererThis, token: DocsCardToken) {
if (token.href) {
return `
<a href="${token.href}" ${targetForExternalHref(token.href)} class="docs-card">
<div>
<h3>${token.title}</h3>
<p>${renderer.parser.parse(token.tokens)}</p>
</div>
<span>${token.link ? token.link : 'Learn more'}</span>
</a>
`;
}
return `
<div class="docs-card">
<div>
<h3>${token.title}</h3>
<p>${renderer.parser.parse(token.tokens)}</p>
</div>
${token.link ? `<span>${token.link}</span>` : ''}
</div>
`;
}
function getCardWithSvgIllustration(renderer: marked.RendererThis, token: DocsCardToken) {
// We can assume that all illustrations are svg files
// We need to read svg content, instead of renering svg with `img`,
// cause we would like to use CSS variables to support dark and light mode.
const illustration = getSvgIllustration(token.imgSrc!);
if (token.href) {
return `
<a href="${token.href}" ${targetForExternalHref(
token.href,
)} class="docs-card docs-card-with-svg">
${illustration}
<div class="docs-card-text-content">
<div>
<h3>${token.title}</h3>
${renderer.parser.parse(token.tokens)}
</div>
<span>${token.link ? token.link : 'Learn more'}</span>
</div>
</a>
`;
}
return `
<div class="docs-card docs-card-with-svg">
${illustration}
<div class="docs-card-text-content">
<h3>${token.title}</h3>
${renderer.parser.parse(token.tokens)}
</div>
</div>
`;
}
function getSvgIllustration(path: string): string {
return readFileSync(join(PROJECT_FOLDER_PATH, path), {encoding: 'utf-8'});
}
@@ -0,0 +1,445 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {marked} from 'marked';
import hljs from 'highlight.js';
import * as diff from 'diff';
import {join} from 'path';
import {readFileSync} from 'fs';
import {decode} from 'html-entities';
import {regionParser} from '../regions/region-parser.mjs';
import {EXAMPLES_FOLDER_PATH, TUTORIALS_FOLDER_PATH} from '../constants.mjs';
import {DocumentType, getCurrentParsedDocumentType} from '../state.mjs';
/** Marked token for a multifile custom docs element. */
export interface DocsCodeMultifileToken extends marked.Tokens.Generic {
type: 'docs-code-multifile';
// The example path used for linking to Stackblitz or rendering a preview
path: string | undefined;
// The raw nested Markdown of <docs-code> examples in the multifile example
panes: string;
// The DocsCodeToken of the nested <docs-code> examples
paneTokens: marked.Token[];
// True if we should display preview
preview: boolean;
}
/** Marked token for a custom docs element. */
export interface DocsCodeToken extends marked.Tokens.Generic {
type: 'docs-code';
// Nested code OR the code from the optional file path
code: string;
// The example file path
path: string | undefined;
// The example display header
header: string | undefined;
// Code language
language: string | undefined;
// True if styled with line numbers
linenums: boolean | undefined;
// The lines to display highlighting on
highlight: string | undefined;
// The example path to determine diff (lines added/removed)
diff: string | undefined;
// The lines viewable in collapsed view
visibleLines: string | undefined;
// The name of the viewable region in the collapsed view
visibleRegion: string | undefined;
// True if we should display preview
preview: boolean;
}
export interface DocsCodeTripleTickBlockToken extends marked.Tokens.Generic {
type: 'docs-code-triple-tick';
// Nested code
code: string;
// Code language
language: string | undefined;
}
interface DiffMetadata {
code: string;
linesAdded: number[];
linesRemoved: number[];
}
// Capture group 1: all attributes on the opening tag
// Capture group 2: all content between the open and close tags
const multiFileCodeRule = /^\s*<docs-code-multifile(.*?)>(.*?)<\/docs-code-multifile>/s;
const singleFileSelfClosingCodeRule = /^\s*<docs-code\s([^>]*)((?:.(?!\/>))*)\/>/s;
const singleFileCodeRule = /^\s*<docs-code\s([^>]*)>((?:.(?!\/docs-code))*)<\/docs-code>/s;
// TODO: use regex for code implemented in the marked package: https://github.com/markedjs/marked/blob/4e6acc8b8517eafe0036a914f58b6f53d4b12ca6/src/rules.ts#L72C1-L73C1
const tripleTickCodeRule = /^\s*`{3}(\w+)[\r\n]+(.*?)[\r\n]+`{3}/s;
const pathRule = /path="([^"]*)"/;
const headerRule = /header="([^"]*)"/;
const linenumsRule = /linenums/;
const highlightRule = /highlight="([^"]*)"/;
const diffRule = /diff="([^"]*)"/;
const languageRule = /language="([^"]*)"/;
const visibleLinesRule = /visibleLines="([^"]*)"/;
const visibleRegionRule = /visibleRegion="([^"]*)"/;
const previewRule = /preview/;
const lineNumberClassName: string = 'hljs-ln-number';
const lineMultifileClassName: string = 'hljs-ln-line';
const lineAddedClassName: string = 'add';
const lineRemovedClassName: string = 'remove';
const lineHighlightedClassName: string = 'highlighted';
const mermaidClassName = 'mermaid';
export const docsCodeMultifileExtension = {
name: 'docs-code-multifile',
level: 'block',
start(src: string) {
return src.match(/^\s*<docs-code-multifile/)?.index;
},
tokenizer(this: marked.TokenizerThis, src: string): DocsCodeMultifileToken | undefined {
const match = multiFileCodeRule.exec(src);
if (match) {
const attr = match[1].trim();
const path = pathRule.exec(attr);
const preview = previewRule.exec(attr) ? true : false;
const token: DocsCodeMultifileToken = {
type: 'docs-code-multifile',
raw: match[0],
path: path?.[1],
panes: match[2].trim(),
paneTokens: [],
preview: preview,
};
this.lexer.blockTokens(token.panes, token.paneTokens);
return token;
}
return undefined;
},
renderer(this: marked.RendererThis, token: DocsCodeMultifileToken) {
const attributes = getAttribute('path', token.path) + getAttribute('preview', token.preview);
return `
<div class="docs-code-multifile"${attributes}>
${this.parser.parse(token.paneTokens)}
</div>
`;
},
};
export const docsCodeExtension = {
name: 'docs-code',
level: 'block',
start(src: string) {
return src.match(/^<docs-code\s/)?.index;
},
tokenizer(this: marked.TokenizerThis, src: string): DocsCodeToken | undefined {
const code = singleFileCodeRule.exec(src);
const selfClosingCode = singleFileSelfClosingCodeRule.exec(src);
const match = selfClosingCode ?? code;
if (match) {
const attr = match[1].trim();
const path = pathRule.exec(attr);
const header = headerRule.exec(attr);
const linenums = linenumsRule.exec(attr);
const highlight = highlightRule.exec(attr);
const diff = diffRule.exec(attr);
const language = languageRule.exec(attr);
const visibleLines = visibleLinesRule.exec(attr);
const visibleRegion = visibleRegionRule.exec(attr);
const preview = previewRule.exec(attr) ? true : false;
let code = match[2].trim();
if (path && path[1]) {
code = getCodeFromPath(path[1]);
}
const token: DocsCodeToken = {
type: 'docs-code',
raw: match[0],
code: code,
path: path?.[1],
header: header?.[1],
linenums: !!linenums,
highlight: highlight?.[1],
diff: diff?.[1],
language: language?.[1],
visibleLines: visibleLines?.[1],
visibleRegion: visibleRegion?.[1],
preview: preview,
};
return token;
}
return undefined;
},
renderer(this: marked.RendererThis, token: DocsCodeToken) {
return formatDocsCode(token);
},
};
export const docsTripleTickMarkdownCodeExtension = {
name: 'docs-code-triple-tick',
level: 'block',
start(src: string) {
return src.match(/^(```)\s/)?.index;
},
tokenizer(this: marked.TokenizerThis, src: string): DocsCodeTripleTickBlockToken | undefined {
const match = tripleTickCodeRule.exec(src);
if (match) {
const token: DocsCodeTripleTickBlockToken = {
raw: match[0],
type: 'docs-code-triple-tick',
code: match[2],
language: match[1],
};
return token;
}
return undefined;
},
renderer(this: marked.RendererThis, token: DocsCodeTripleTickBlockToken) {
return formatDocsCode({code: token.code, language: token.language});
},
};
function formatDocsCode(token: Partial<DocsCodeToken>): string {
let diffData: DiffMetadata | null = null;
if (!token.code) {
throw new Error('Undefined code in DocsCodeToken!');
}
let code = token.code;
if (token.diff) {
diffData = getDiffData(token.diff, code);
code = diffData.code;
}
const highlightedLines = token.highlight ? getRangeValues(token.highlight) : [];
const extractRegionsResult = extractRegions(token, code);
code = extractRegionsResult.code;
// Add highlighting based on the code language
code = getHighlightedCode(token.language, code, diffData, highlightedLines, !!token.linenums);
const attributes =
getAttribute(
'visibleLines',
getRangeValues(extractRegionsResult.visibleLines ?? token.visibleLines)?.toString(),
) +
getAttribute('path', token.diff ?? token.path) +
getAttribute('preview', token.preview) +
getAttribute('header', token.header) +
getAttribute('mermaid', token.language === mermaidClassName);
const classes = getClass('shell', token.language == 'shell');
const header = token.header ? `<div class="docs-code-header"><h3>${token.header}</h3></div>` : '';
return `
<div class="docs-code${classes}"${attributes}>
${header}
<pre class="adev-mini-scroll-track">
<code>${code}</code>
</pre>
</div>
`;
}
function getCodeFromPath(path: string): string {
const rootFolder =
getCurrentParsedDocumentType() === DocumentType.DOCS
? EXAMPLES_FOLDER_PATH
: TUTORIALS_FOLDER_PATH;
return readFileSync(join(rootFolder, path), {encoding: 'utf-8'});
}
function getHighlightedCode(
language: string | undefined,
code: string,
diffData: DiffMetadata | null,
highlightedLines: number[] | null,
displayLineNums: boolean,
): string {
if (language == 'none' || language == 'file' || language == mermaidClassName || !highlightedLines)
return code;
// Decode the code content to replace HTML entities to characters
const decodedCode = decode(code);
const highlightResult = language
? hljs.highlight(decodedCode, {language})
: hljs.highlightAuto(decodedCode);
return appendModifierClassesToCodeLinesElements(
highlightResult.value,
diffData,
highlightedLines,
displayLineNums,
);
}
function appendModifierClassesToCodeLinesElements(
htmlString: string,
diffData: DiffMetadata | null,
highlightedLines: number[],
displayLineNums: boolean,
): string {
const lines = getLines(htmlString);
let finalHtml = '';
let lineIndex = 0;
let resultFileLineIndex = 1;
const linesCount = lines.length;
if (linesCount === 0) {
return htmlString;
}
do {
const isRemovedLine = diffData?.linesRemoved.includes(lineIndex);
const isAddedLine = diffData?.linesAdded.includes(lineIndex);
const isHighlighted = highlightedLines.includes(lineIndex);
const statusClasses = `${getClass(lineAddedClassName, isAddedLine)}${getClass(
lineRemovedClassName,
isRemovedLine,
)}${getClass(lineHighlightedClassName, isHighlighted)}`;
if (displayLineNums) {
if (isRemovedLine) {
finalHtml += `<span role="presentation" class="${lineNumberClassName}${statusClasses}">-</span>`;
} else {
finalHtml += `<span role="presentation" class="${lineNumberClassName}${statusClasses}">${
isAddedLine ? '+' : resultFileLineIndex
}</span>`;
resultFileLineIndex++;
}
}
finalHtml += `<div class="${lineMultifileClassName}${statusClasses}">${lines[lineIndex]}</div>`;
lineIndex++;
} while (lineIndex < linesCount);
return finalHtml;
}
function getDiffData(diffPath: string, code: string): DiffMetadata {
const changedCode = getCodeFromPath(diffPath);
const change = diff.diffLines(code, changedCode);
const getLinesRange = (start: number, count: number): number[] =>
Array.from(Array(count).keys()).map((i) => i + start);
let processedLines = 0;
return change.reduce(
(prev: DiffMetadata, part: diff.Change) => {
const diff: DiffMetadata = {
code: `${prev.code}${part.value}`,
linesAdded: part.added
? [...prev.linesAdded, ...getLinesRange(processedLines, part.count ?? 0)]
: prev.linesAdded,
linesRemoved: part.removed
? [...prev.linesRemoved, ...getLinesRange(processedLines, part.count ?? 0)]
: prev.linesRemoved,
};
processedLines += part.count ?? 0;
return diff;
},
{
code: '',
linesAdded: [],
linesRemoved: [],
},
);
}
function extractRegions(
token: Partial<DocsCodeToken>,
code: string,
): {code: string; visibleLines?: string} {
if (!token.path) return {code};
const result = regionParser(code, token.path);
if (token.visibleRegion) {
const region = result.regionMap[token.visibleRegion];
if (!region) throw new Error(`Cannot find ${token.visibleRegion} in ${token.path}!`);
return {
code: result.contents,
visibleLines: `[${region.ranges.map(
(range) => `[${range.from}, ${range.to ?? result.totalLinesCount + 1}]`,
)}]`,
};
}
return {
code: result.contents,
};
}
function getLines(text: string): string[] {
if (text.length === 0) {
return [];
}
return text.split(/\r\n|\r|\n/g);
}
function getAttribute(name: string, value: boolean | number | string | undefined): string {
return value ? ` ${name}="${value}"` : '';
}
function getClass(name: string, value: boolean | number | string | undefined): string {
return value ? ` ${name}` : ``;
}
/**
* The function used to generate ranges of highlighted or visible lines in code blocks
*/
function getRangeValues(token?: string): number[] | null {
const getAllValuesFromRange = (range: any[]) => {
const [start, end] = range;
for (let i = start; i <= end; i++) {
result.push(i - 1);
}
};
if (!token) {
return null;
}
let result: number[] = [];
try {
const boundaryValueArray = JSON.parse(token);
if (!Array.isArray(boundaryValueArray)) {
throw new Error('Provided token has wrong format!\n', boundaryValueArray);
}
// Flat Array
if (
boundaryValueArray.length === 2 &&
!Array.isArray(boundaryValueArray[0]) &&
!Array.isArray(boundaryValueArray[1])
) {
getAllValuesFromRange(boundaryValueArray);
} else {
for (const range of boundaryValueArray) {
if (Array.isArray(range) && range.length === 2) {
getAllValuesFromRange(range);
} else if (!Number.isNaN(range)) {
result.push(Number(range - 1));
} else {
throw new Error('Input has wrong format!\n', range);
}
}
}
return result;
} catch {
return null;
}
}
@@ -0,0 +1,84 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
import {marked} from 'marked';
import {getPageTitle} from './h1.mjs';
import {readFileSync} from 'fs';
import {join} from 'path';
import {PROJECT_FOLDER_PATH} from '../constants.mjs';
interface DocsDecorativeHeaderToken extends marked.Tokens.Generic {
type: 'docs-decorative-header';
title: string;
imgSrc: string;
body: string;
}
// Capture group 1: all attributes on the opening tag
// Capture group 2: all content between the open and close tags
const decorativeHeaderRule =
/^[^<]*<docs-decorative-header\s([^>]*)>((?:.(?!\/docs-decorative-header))*)<\/docs-decorative-header>/s;
const imgSrcRule = /imgSrc="([^"]*)"/;
const titleRule = /title="([^"]*)"/;
export const docsDecorativeHeaderExtension = {
name: 'docs-decorative-header',
level: 'block',
start(src: string) {
return src.match(/^\s*<docs-decorative-header\s*/m)?.index;
},
tokenizer(this: marked.TokenizerThis, src: string): DocsDecorativeHeaderToken | undefined {
const match = decorativeHeaderRule.exec(src);
if (match) {
const attr = match[1].trim();
const body = match[2].trim();
const imgSrc = imgSrcRule.exec(attr);
const title = titleRule.exec(attr);
const token: DocsDecorativeHeaderToken = {
type: 'docs-decorative-header',
raw: match[0],
title: title ? title[1] : '',
imgSrc: imgSrc ? imgSrc[1] : '../assets/images/globe.svg',
body: body ?? '',
};
return token;
}
return undefined;
},
renderer(this: marked.RendererThis, token: DocsDecorativeHeaderToken) {
// We can assume that all illustrations are svg files
// We need to read svg content, instead of renering svg with `img`,
// cause we would like to use CSS variables to support dark and light mode.
const illustration = getSvgIllustration(token.imgSrc);
return `
<div class="docs-decorative-header-container">
<div class="docs-decorative-header">
<div class="docs-header-content">
<docs-breadcrumb></docs-breadcrumb>
${getPageTitle(token.title)}
<p>${token.body}</p>
</div>
<!-- illustration -->
${illustration}
</div>
</div>
`;
},
};
function getSvgIllustration(path: string): string {
return readFileSync(join(PROJECT_FOLDER_PATH, path), {encoding: 'utf-8'});
}
@@ -0,0 +1,103 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {marked} from 'marked';
import {isExternalLink, targetForExternalHref} from './helpers.mjs';
interface DocsPillRowToken extends marked.Tokens.Generic {
type: 'docs-pill-row';
pills: string;
tokens: marked.Token[];
}
// Capture group 1: all content between the open and close tags
const pillRowRule = /^\s*<docs-pill-row>((?:.(?!docs-pill-row))*)<\/docs-pill-row>/s;
export const docsPillRowExtension = {
name: 'docs-pill-row',
level: 'block',
start(src: string) {
return src.match(/^\s*<docs-pill-row/m)?.index;
},
tokenizer(this: marked.TokenizerThis, src: string): DocsPillRowToken | undefined {
const match = pillRowRule.exec(src);
if (match) {
const body = match[1];
const token: DocsPillRowToken = {
type: 'docs-pill-row',
raw: match[0],
pills: body ?? '',
tokens: [],
};
this.lexer.inlineTokens(token.pills, token.tokens);
return token;
}
return undefined;
},
renderer(this: marked.RendererThis, token: DocsPillRowToken) {
return `
<nav class="docs-pill-row">
${this.parser.parseInline(token.tokens)}
</nav>
`;
},
};
interface DocsPillToken extends marked.Tokens.Generic {
type: 'docs-pill';
title: string;
href: string;
tokens: marked.Token[];
}
// Capture group 1: all attributes on the docs-pill tag
const pillRule = /^\s*<docs-pill\s((?:.(?!\n))*)\/>/s;
const titleRule = /title="([^"]*)"/;
const hrefRule = /href="([^"]*)"/;
export const docsPillExtension = {
name: 'docs-pill',
level: 'inline',
start(src: string) {
return src.indexOf('<docs-pill ');
},
tokenizer(this: marked.TokenizerThis, src: string): DocsPillToken | undefined {
const match = pillRule.exec(src);
if (match) {
const attr = match[1].trim();
const title = titleRule.exec(attr);
const href = hrefRule.exec(attr);
const token: DocsPillToken = {
type: 'docs-pill',
raw: match[0],
title: title ? title[1] : '',
href: href ? href[1] : '',
tokens: [],
};
this.lexer.inlineTokens(token.title, token.tokens);
return token;
}
return undefined;
},
renderer(this: marked.RendererThis, token: DocsPillToken) {
return `
<a class="docs-pill" href="${token.href}" ${targetForExternalHref(token.href)}>
${this.parser.parseInline(token.tokens)}
${
isExternalLink(token.href)
? '<docs-icon class="docs-icon-small">open_in_new</docs-icon>'
: ''
}
</a>
`;
},
};
@@ -0,0 +1,69 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {marked} from 'marked';
interface DocsVideoToken extends marked.Tokens.Generic {
type: 'docs-video';
src: string;
title: string | undefined;
}
// Capture group 1: all attributes on the opening tag
const videoRule = /^<docs-video([^>]*)\/>/s;
const srcRule = /src="([^"]*)"/;
const titleRule = /title="([^"]*)"/;
const validYTUrlPrefix = 'https://www.youtube.com/embed/';
export const docsVideoExtension = {
name: 'docs-video',
level: 'block',
start(src: string) {
return src.match(/^\s*<docs-video/m)?.index;
},
tokenizer(this: marked.TokenizerThis, src: string): DocsVideoToken | undefined {
const match = videoRule.exec(src);
if (match) {
const attr = match[1].trim();
const src = srcRule.exec(attr);
const title = titleRule.exec(attr);
if (src) {
return {
type: 'docs-video',
raw: match[0],
src: src?.[1],
title: title?.[1],
};
}
}
return undefined;
},
renderer(this: marked.RendererThis, token: DocsVideoToken) {
if (!token.src.startsWith(validYTUrlPrefix)) {
process.stdout.write(
`\n<docs-video> cannot load: ${token.src}. YouTube Player API expects src to begin with ${validYTUrlPrefix}.\n`,
);
}
return `
<div class="docs-video-container">
<iframe
class="docs-video"
src="${token.src}"
${token.title ? `title="${token.title}"` : ''}
allow="accelerometer; encrypted-media; gyroscope; picture-in-picture"
allowfullscreen
credentialless
title="Video player"
></iframe>
</div>
`;
},
};
@@ -0,0 +1,99 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {marked} from 'marked';
import {transformHeader} from './header.mjs';
interface DocsWorkflowToken extends marked.Tokens.Generic {
type: 'docs-workflow';
steps: string;
tokens: marked.Token[];
}
// Capture group 1: all content between the open and close tags
const workflowRule = /^<docs-workflow>(.*?)<\/docs-workflow>/s;
export const docsWorkflowExtension = {
name: 'docs-workflow',
level: 'block',
start(src: string) {
return src.match(/^\s*<docs-workflow/m)?.index;
},
tokenizer(this: marked.TokenizerThis, src: string): DocsWorkflowToken | undefined {
const match = workflowRule.exec(src);
if (match) {
const steps = match[1];
const token: DocsWorkflowToken = {
type: 'docs-workflow',
raw: match[0],
steps: steps ?? '',
tokens: [],
};
this.lexer.blockTokens(token.steps, token.tokens);
return token;
}
return undefined;
},
renderer(this: marked.RendererThis, token: DocsWorkflowToken) {
return `
<ol class="docs-steps">
${this.parser.parse(token.tokens)}
</ol>
`;
},
};
interface DocsStepToken extends marked.Tokens.Generic {
type: 'docs-step';
title: string;
body: string;
tokens: marked.Token[];
}
// Capture group 1: all attributes on the opening tag
// Capture group 2: all content between the open and close tags
const stepRule = /^\s*<docs-step([^>]*)>((?:.(?!\/docs-step))*)<\/docs-step>/s;
const titleRule = /title="([^"]*)"/;
export const docsStepExtension = {
name: 'docs-step',
level: 'block',
start(src: string) {
return src.match(/^\s*<docs-step/m)?.index;
},
tokenizer(this: marked.TokenizerThis, src: string): DocsStepToken | undefined {
const match = stepRule.exec(src);
if (match) {
const attr = match[1].trim();
const title = titleRule.exec(attr);
const body = match[2].trim();
const token: DocsStepToken = {
type: 'docs-step',
raw: match[0],
title: title ? title[1] : '',
body: body,
tokens: [],
};
this.lexer.blockTokens(token.body, token.tokens);
return token;
}
return undefined;
},
renderer(this: marked.RendererThis, token: DocsStepToken) {
return `
<li>
<span class="docs-step-number" aria-hidden="true"></span>
${transformHeader(token.title, 3)}
${this.parser.parse(token.tokens)}
</li>
`;
},
};
@@ -0,0 +1,19 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import emojiRegex from 'emoji-regex';
const UNICODE_EMOJI_REGEX = /&#x[\dA-Fa-f]+;/g;
const regex = emojiRegex();
export function handleEmoji(text: string): string {
return text.match(regex) || text.match(UNICODE_EMOJI_REGEX)
? `<span class="docs-emoji">${text}</span>`
: text;
}
@@ -0,0 +1,26 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
// Enum with the severity levels for alerts and callouts
export enum CalloutSeverityLevel {
HELPFUL = 'HELPFUL',
IMPORTANT = 'IMPORTANT',
CRITICAL = 'CRITICAL',
}
export enum AlertSeverityLevel {
Note = 'Note',
Tip = 'Tip',
TODO = 'TODO',
QUESTION = 'QUESTION',
Summary = 'Summary',
TLDR = 'TLDR',
CRITICAL = 'CRITICAL',
IMPORTANT = 'IMPORTANT',
HELPFUL = 'HELPFUL',
}
@@ -0,0 +1,39 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {GITHUB_EDIT_CONTENT_URL} from '../constants.mjs';
import {DocumentType, getCurrentParsedDocumentType, getCurrentParsedFilePath} from '../state.mjs';
export function transformH1(text: string) {
// For tutorials pages, we don't have to display docs-breadcrumb
return `
<!-- Document Header -->
<header class="docs-header">
${
getCurrentParsedDocumentType() === DocumentType.TUTORIAL
? ''
: '<docs-breadcrumb></docs-breadcrumb>'
}
${getPageTitle(text)}
</header>
`;
}
// TODO: Add back pencil icon once code is open sourced
export function getPageTitle(text: string): string {
return `
<!-- Page title -->
<div class="docs-page-title">
<h1 tabindex="-1">${text}</h1>
<a class="docs-github-links" target="_blank" href="${GITHUB_EDIT_CONTENT_URL}/${getCurrentParsedFilePath()}" title="Edit this page" aria-label="Edit this page">
<!-- Pencil -->
<!-- <docs-icon role="presentation">edit</docs-icon> -->
</a>
</div>`;
}
@@ -0,0 +1,26 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {getHeaderId} from '../state.mjs';
import {mapBackticksToCodeElement} from '../utils.mjs';
export function transformHeader(text: string, level: number) {
// Nested anchor elements are invalid in HTML
// They might happen when we have a code block in a heading
// regex aren't perfect for that but this one should be "good enough"
const regex = /<a\s+(?:[^>]*?\s+)?href.*?>(.*?)<\/a>/gi;
const anchorLessText = text.replace(regex, '$1');
const link = getHeaderId(anchorLessText);
const label = mapBackticksToCodeElement(anchorLessText);
return `
<h${level} id="${link}">
<a href="#${link}" class="docs-anchor" tabindex="-1">${label}</a>
</h${level}>`;
}
@@ -0,0 +1,13 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export const isExternalLink = (href: string | undefined | null) =>
href?.startsWith('http') ?? false;
export const targetForExternalHref = (href: string | undefined | null) =>
isExternalLink(href) ? `target="_blank"` : '';
@@ -0,0 +1,17 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {normalize} from 'path';
// TODO: Make sure we're setting up correct image optimization
export function transformImage(href: string | null, title: string | null, text: string) {
const src = href?.startsWith('./') ? `assets/content/${normalize(href)}` : href;
return `
<img src="${src}" alt="${text}" title="${title}" class="docs-image">
`;
}
@@ -0,0 +1,15 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {targetForExternalHref} from './helpers.mjs';
export function transformLink(href: string | null, title: string | null, text: string) {
return `<a href="${href}" ${title ? `title=${title}` : ''} ${targetForExternalHref(
href,
)}>${text}</a>`;
}
@@ -0,0 +1,22 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export function transformDocsList(body: string, ordered: boolean) {
if (ordered) {
return `
<ol class="docs-ordered-list">
${body}
</ol>
`;
}
return `
<ul class="docs-list">
${body}
</ul>
`;
}
@@ -0,0 +1,22 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export function transformDocsTable(header: string, body: string) {
return `
<div class="docs-table adev-scroll-track-transparent">
<table>
<thead>
${header}
</thead>
<tbody>
${body}
</tbody>
</table>
</div>
`;
}
@@ -0,0 +1,31 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {readFileSync} from 'fs';
import {glob} from 'glob';
import {join} from 'path';
export function mapBackticksToCodeElement(text: string): string {
return text.replaceAll(/`(.*?)`/g, '<code>$1</code>');
}
/** Recursively search the provided directory for all markdown files and asyncronously load them. */
export async function retrieveAllMarkdownFiles(
baseDir: string,
): Promise<{path: string; content: string}[]> {
const files = await glob('**/*.md', {
root: baseDir,
cwd: baseDir,
ignore: ['**/node_modules/**'],
});
return files.map((filePath) => ({
path: filePath,
content: readFileSync(join(baseDir, filePath), {encoding: 'utf-8'}),
}));
}
+19
View File
@@ -0,0 +1,19 @@
# Tutorial Scripts
The tutorials scripts are responsible for generating the tutorials source code and metadata by reading the tutorials content from [`src/content/tutorials`](/src/content/tutorials).
_See [the tutorials content README](/src/content/tutorials/README.md) for more information about the tutorials content._
For each tutorial, the following JSON files are generated and stored at `src/assets/tutorials`:
- `source-code/<tutorial-pathname>.json`: contains the tutorial source code in the [WebContainer](https://webcontainers.io) `FileSystemTree` format. It's
used to mount the tutorial files in the WebContainer. See the WebContainer docs for more info: <https://webcontainers.io/guides/working-with-the-file-system>
- `metadata/<tutorial-pathname>.json`: the tutorial metadata has all the information necessary to manage the tutorial in app.
It contains the tutorial `config.json`, the previous and next step, the next tutorial, and the code editor file paths and contents.
- `routes.json`: defines all routes for the tutorials, used at [`src/app/sub-navigation-data.ts`](/src/app/sub-navigation-data.ts) to populate the tutorials nav.
## Usage
```bash
yarn generate-tutorials
```
@@ -0,0 +1,84 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {NavigationItem} from '@angular/docs-shared';
import {PagePrefix} from '../../src/app/core/enums/pages';
import type {TutorialNavigationData, TutorialNavigationItem, TutorialStep} from './tutorials-types';
import {createDirectoryAndWriteFile} from './utils/filesystem';
import {TUTORIALS_ROUTES_NODE_PATH} from './utils/node-constants';
/** the step is used only in this function to sort the nav items */
export type TutorialNavigationItemWithStep = TutorialNavigationItem & {
tutorialData: TutorialNavigationData & {
step: TutorialStep['step'];
};
};
export async function buildTutorialsNavigationItems(
initialNavigationItems: TutorialNavigationItemWithStep[],
) {
const sortedInitialNavigationItems = initialNavigationItems.sort((a, b) => {
if (!a.tutorialData?.step || !b.tutorialData?.step) return 0;
if (a.tutorialData.step < b.tutorialData.step) return -1;
else if (a.tutorialData.step > b.tutorialData.step) return 1;
return 0;
});
const addTutorialPagePrefixToNavItemPath = (path: string) => `${PagePrefix.TUTORIALS}/${path}`;
const navItemMap = new Map<NavigationItem['path'], TutorialNavigationItem>();
for (const navItem of sortedInitialNavigationItems) {
const pathParts = navItem.path.split('/');
const topLevelPath = pathParts[0];
const topLevelNavItem = navItemMap.get(topLevelPath);
const isNavItemTopLevelPath = pathParts.length === 1;
const newNavItem: TutorialNavigationItem = {
path: addTutorialPagePrefixToNavItemPath(navItem.path),
label: navItem.label,
contentPath: navItem.contentPath,
tutorialData: navItem.tutorialData,
};
if (!topLevelNavItem) {
// create new map entry
navItemMap.set(
topLevelPath,
isNavItemTopLevelPath ? newNavItem : ({children: [newNavItem]} as TutorialNavigationItem),
);
} else if (isNavItemTopLevelPath) {
// add top level path to existing map entry
navItemMap.set(topLevelPath, {
...newNavItem,
...topLevelNavItem,
});
} else if (!topLevelNavItem.children) {
// create children in existing map entry
topLevelNavItem.children = [newNavItem];
navItemMap.set(topLevelPath, topLevelNavItem);
} else {
// add children to existing map entry
topLevelNavItem.children.push(newNavItem);
navItemMap.set(topLevelPath, topLevelNavItem);
}
}
const tutorialNavigationItems = Array.from(navItemMap.values());
await createDirectoryAndWriteFile(
TUTORIALS_ROUTES_NODE_PATH,
JSON.stringify(tutorialNavigationItems),
);
}
@@ -0,0 +1,204 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {mkdir, rm, writeFile} from 'fs/promises';
import {basename, join, sep} from 'path';
import {
GLOB_OPTIONS,
INTRO_DIRECTORY,
PLAYGROUND_ROUTE_NODE_PATH,
STEPS_DIRECTORY,
TUTORIALS_ASSETS_NODE_PATH,
TUTORIALS_COMMON_NODE_PATH,
TUTORIALS_METADATA_NODE_PATH,
TUTORIALS_PROJECT_PATH,
TUTORIALS_SOURCE_CODE_NODE_PATH,
} from './utils/node-constants';
import {createDirectoryAndWriteFile, getFilesContents, globWithCwdPath} from './utils/filesystem';
import {
TutorialNavigationItemWithStep,
buildTutorialsNavigationItems,
} from './generate-tutorials-routes';
import {copyCommonAssetsToAppAssets, getTutorialCommonFiles} from './tutorial-type/common';
import {getHomepagePlaygroundFiles} from './tutorial-type/homepage';
import {getIntroAndStepsTutorialFiles} from './tutorial-type/intro-and-steps';
import {getTutorialPlaygroundFiles, isPlaygroundRouteData} from './tutorial-type/playground';
import {PlaygroundFiles, TutorialFiles} from './tutorials-types';
import {
TUTORIALS_COMMON_DIRECTORY,
TUTORIALS_HOMEPAGE_DIRECTORY,
TUTORIALS_PLAYGROUND_DIRECTORY,
} from './utils/web-constants';
main();
/**
* Builds and stores the tutorials source codes and metadata into JSON files.
* These files are later used to load the tutorials into the WebContainer file system
* and manage the tutorials in the embedded editor.
*
* @see https://webcontainers.io/guides/working-with-the-file-system
*/
export async function main() {
const consoleTimeLabel = 'Tutorials files build done in';
// Informs the developers that this script is running and how much time it took
console.info('Building tutorials files...');
console.time(consoleTimeLabel);
const tutorialsFiles = await getTutorialsFiles();
// Clean up the directory before writing the files
await rm(TUTORIALS_ASSETS_NODE_PATH, {recursive: true}).catch(() => {
// `rm` throws if the directory doesn't exist, meaning this script is
// being executed for the first time
});
await Promise.all([
mkdir(TUTORIALS_ASSETS_NODE_PATH, {recursive: true}),
mkdir(TUTORIALS_SOURCE_CODE_NODE_PATH, {recursive: true}),
mkdir(TUTORIALS_METADATA_NODE_PATH, {recursive: true}),
]);
const writeFilesPromises: Promise<void>[] = [];
const tutorialsRoutes: TutorialNavigationItemWithStep[] = [];
tutorialsFiles.forEach(({sourceCode, metadata, route, sourceCodeZip}, tutorialName) => {
if (sourceCode) {
const filePath = join(TUTORIALS_SOURCE_CODE_NODE_PATH, tutorialName + '.json');
const fileContents = JSON.stringify(sourceCode);
if (tutorialName.includes(sep)) {
writeFilesPromises.push(createDirectoryAndWriteFile(filePath, fileContents));
} else {
writeFilesPromises.push(writeFile(filePath, fileContents));
}
}
if (metadata) {
const filePath = join(TUTORIALS_METADATA_NODE_PATH, tutorialName + '.json');
const fileContents = JSON.stringify(metadata);
if (tutorialName.includes(sep)) {
writeFilesPromises.push(createDirectoryAndWriteFile(filePath, fileContents));
} else {
writeFilesPromises.push(writeFile(filePath, fileContents));
}
}
if (route) {
if (isPlaygroundRouteData(route)) {
writeFilesPromises.push(
createDirectoryAndWriteFile(PLAYGROUND_ROUTE_NODE_PATH, JSON.stringify(route)),
);
} else {
tutorialsRoutes.push({
...route,
path: tutorialName,
});
}
}
if (sourceCodeZip) {
const filePath = join(TUTORIALS_SOURCE_CODE_NODE_PATH, tutorialName + '.zip');
writeFilesPromises.push(createDirectoryAndWriteFile(filePath, sourceCodeZip));
}
});
await Promise.all([
...writeFilesPromises,
copyCommonAssetsToAppAssets(),
buildTutorialsNavigationItems(tutorialsRoutes),
]);
console.timeEnd(consoleTimeLabel);
}
/**
* Retrieve the tutorials source code and generate a Map representing the files
* and contents that will be stored in the filesystem.
*
* Those files are later used by the `/tutorials` pages.
*
* The map key is the project name and the value contain the contents for each
* .json file.
*/
async function getTutorialsFiles(): Promise<Map<string, TutorialFiles | PlaygroundFiles>> {
const [tutorialsProjects, commonTutorialFiles] = await Promise.all([
globWithCwdPath('**', {
...GLOB_OPTIONS,
ignore: [...(GLOB_OPTIONS.ignore as string[]), '*.md', TUTORIALS_COMMON_DIRECTORY],
maxDepth: 1,
cwd: TUTORIALS_PROJECT_PATH,
}),
globWithCwdPath('**', {
...GLOB_OPTIONS,
cwd: TUTORIALS_COMMON_NODE_PATH,
nodir: true,
}),
]);
const tutorialsFiles = new Map<string, TutorialFiles | PlaygroundFiles>();
// tutorials depends on the common project files so here we handle it first
const commonFilesContents = await getFilesContents(commonTutorialFiles);
tutorialsFiles.set(
TUTORIALS_COMMON_DIRECTORY,
await getTutorialCommonFiles(commonTutorialFiles, commonFilesContents),
);
await Promise.all(
tutorialsProjects.map(async (tutorialPath) => {
const tutorialName = basename(tutorialPath);
const [tutorialDirectories, tutorialFiles] = await Promise.all([
globWithCwdPath('**/', {...GLOB_OPTIONS, cwd: tutorialPath}),
globWithCwdPath('**', {...GLOB_OPTIONS, nodir: true, cwd: tutorialPath}),
]);
try {
if (tutorialName === TUTORIALS_PLAYGROUND_DIRECTORY) {
const playgroundFiles = await getTutorialPlaygroundFiles(commonFilesContents);
playgroundFiles.forEach((playgroundFiles, playgroundName) => {
tutorialsFiles.set(playgroundName, playgroundFiles);
});
} else if (tutorialName === TUTORIALS_HOMEPAGE_DIRECTORY) {
const homepageFiles = await getHomepagePlaygroundFiles(commonFilesContents);
tutorialsFiles.set(TUTORIALS_HOMEPAGE_DIRECTORY, homepageFiles);
} else if (
tutorialDirectories.some((directory) => directory.includes(STEPS_DIRECTORY)) &&
tutorialDirectories.some((directory) => directory.includes(INTRO_DIRECTORY))
) {
const tutorialStepsFiles = await getIntroAndStepsTutorialFiles(
tutorialName,
tutorialDirectories,
tutorialFiles,
commonFilesContents,
);
tutorialStepsFiles.forEach((stepFiles, stepName) => {
tutorialsFiles.set(stepName, stepFiles);
});
} else {
throw `Could not find "${INTRO_DIRECTORY}" and/or "${STEPS_DIRECTORY}" directories.`;
}
} catch (error) {
console.error(`\n❌ Failed to parse tutorial at ${TUTORIALS_PROJECT_PATH}/${tutorialName}`);
console.error(`\t${error}\n`);
process.exit(1);
}
}),
);
return tutorialsFiles;
}
@@ -0,0 +1,56 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {join} from 'path';
import {glob} from 'glob';
import {input} from '@inquirer/prompts';
import {TutorialType} from './utils/web-constants';
import {parseConfig} from './tutorials-config';
import {createDirectoryAndWriteFile} from './utils/filesystem';
import {CONFIG_FILE, GLOB_OPTIONS, TUTORIALS_PLAYGROUND_NODE_PATH} from './utils/node-constants';
import {validatePathAnswer} from './utils/cli';
createTemplate();
async function createTemplate() {
const existingTemplates = await glob('**/', {
...GLOB_OPTIONS,
absolute: false,
cwd: TUTORIALS_PLAYGROUND_NODE_PATH,
maxDepth: 1,
});
const path = await askTemplatePath(existingTemplates);
const title = await input({message: 'What is the title for the template?'});
const templatePath = `${TUTORIALS_PLAYGROUND_NODE_PATH}/${path}`;
const config = await parseConfig({
type: TutorialType.EDITOR_ONLY,
title,
openFiles: ['src/main.ts'],
});
await Promise.all([
createDirectoryAndWriteFile(join(templatePath, CONFIG_FILE), JSON.stringify(config, null, 2)),
createDirectoryAndWriteFile(join(templatePath, 'src', 'main.ts'), ''),
]);
console.info(`\n✅ Template created at ${templatePath}`);
}
function askTemplatePath(existingTemplates: string[]) {
const placeholder = 'path-to-template';
return input({
message: 'What is the path of the template?',
default: placeholder,
validate: (answer) => validatePathAnswer(answer, existingTemplates, placeholder),
});
}
+203
View File
@@ -0,0 +1,203 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {join} from 'path';
import {select, input, confirm} from '@inquirer/prompts';
import {glob} from 'glob';
import {createDirectoryAndWriteFile} from './utils/filesystem';
import {
CONFIG_FILE,
CONTENT_PLACEHOLDER,
GLOB_OPTIONS,
INTRO_DIRECTORY,
STEPS_DIRECTORY,
TUTORIALS_PROJECT_PATH,
TUTORIAL_CONTENT_FILENAME,
} from './utils/node-constants';
import type {TutorialConfig} from './tutorials-types';
import {parseConfig} from './tutorials-config';
import {
TUTORIALS_COMMON_DIRECTORY,
TUTORIALS_PLAYGROUND_DIRECTORY,
TutorialType,
} from './utils/web-constants';
import {validatePathAnswer} from './utils/cli';
type TutorialFields = TutorialConfig & {
path: string;
};
type TutorialToCreate = {
intro: TutorialFields;
steps: Array<TutorialFields & {step: number}>;
};
createTutorial();
async function createTutorial() {
const existingTutorials = await glob('**/', {
ignore: [
...(GLOB_OPTIONS.ignore as string[]),
TUTORIALS_COMMON_DIRECTORY,
TUTORIALS_PLAYGROUND_DIRECTORY,
],
cwd: TUTORIALS_PROJECT_PATH,
maxDepth: 1,
});
const introPath = await askTutorialPath(existingTutorials);
const introType = await askTutorialType('What is the type of the tutorial intro?');
const introTitle = await input({message: 'What is the title for the tutorial intro?'});
const introNextTutorial = await askAboutNextTutorial(existingTutorials);
const tutorialToCreate: TutorialToCreate = {
intro: {
type: introType as any, // Note: casting to any here as a workaround for the enum type error
title: introTitle,
path: introPath,
openFiles: [''],
nextTutorial: introNextTutorial,
},
steps: [],
};
let addMoreSteps = true;
let step = 1;
while (addMoreSteps) {
console.info(`\nStep ${step}`);
const path = await askTutorialStepPath(tutorialToCreate.steps);
const type = await askTutorialType('What is the type of the step?');
const title = await input({message: 'What is the title of the step?'});
tutorialToCreate.steps.push({
step,
type: type as any, // Note: casting to any here as a workaround for the enum type error
path,
title,
openFiles: [''],
});
step++;
console.info();
addMoreSteps = await confirm({message: 'Would you like to add another step?', default: true});
}
const tutorialPath = `${TUTORIALS_PROJECT_PATH}/${tutorialToCreate.intro.path}`;
await Promise.all([
createIntroFiles(tutorialToCreate.intro),
...createStepsFiles(tutorialPath, tutorialToCreate.steps),
]);
console.info(`\n✅ Tutorial created at ${tutorialPath}`);
}
function askTutorialType(message: string = 'What is the type of the tutorial?') {
return select<TutorialConfig['type']>({
message: message,
choices: [
{
name: 'CLI only: a tutorial for the Angular CLI in-browser unsing the embedded terminal',
value: TutorialType.CLI,
},
{name: 'Local app: a tutorial for building an app locally', value: TutorialType.LOCAL},
{
name: 'Embedded editor: a tutorial for building an app in-browser using the embedded editor',
value: TutorialType.EDITOR,
},
],
});
}
function askAboutNextTutorial(
existingTutorials: string[],
message: string = 'What should be the next tutorial?',
) {
return select({
message,
choices: [
...existingTutorials.map((tutorial) => ({name: tutorial, value: tutorial})),
{name: 'None', value: undefined},
],
});
}
function askTutorialPath(existingTutorials: string[]) {
const placeholder = 'path-to-tutorial';
return input({
message: 'What is the path of the tutorial?',
default: placeholder,
validate: (answer) => validatePathAnswer(answer, existingTutorials, placeholder),
});
}
function askTutorialStepPath(createdSteps: TutorialToCreate['steps']) {
const placeholder = 'path-to-step';
const existingSteps = createdSteps.map((step) => step.path);
return input({
message: 'What is the path of the step?',
default: placeholder,
validate: (answer) => validatePathAnswer(answer, existingSteps, placeholder),
});
}
async function createIntroFiles(intro: TutorialToCreate['intro']): Promise<Promise<void>[]> {
const tutorialPath = `${TUTORIALS_PROJECT_PATH}/${intro.path}`;
const config = await parseConfig({
type: intro.type as any, // Note: casting to any here as a workaround for the enum type error
title: intro.title,
openFiles: intro.openFiles,
nextTutorial: intro.nextTutorial,
});
return [
createDirectoryAndWriteFile(
join(tutorialPath, INTRO_DIRECTORY, CONFIG_FILE),
JSON.stringify(config, null, 2),
),
createDirectoryAndWriteFile(
join(tutorialPath, INTRO_DIRECTORY, TUTORIAL_CONTENT_FILENAME),
CONTENT_PLACEHOLDER,
),
];
}
function createStepsFiles(
tutorialPath: string,
steps: TutorialToCreate['steps'],
): Promise<Promise<void>[]>[] {
const tutorialStepsPath = join(tutorialPath, STEPS_DIRECTORY);
return steps
.map(async (step) => {
const stepPath = join(tutorialStepsPath, `${step.step}-${step.path}`);
const config = await parseConfig({
type: step.type as any, // Note: casting to any here as a workaround for the enum type error
title: step.title,
openFiles: step.openFiles,
});
return [
createDirectoryAndWriteFile(`${stepPath}/${CONFIG_FILE}`, JSON.stringify(config, null, 2)),
createDirectoryAndWriteFile(
`${stepPath}/${TUTORIAL_CONTENT_FILENAME}`,
CONTENT_PLACEHOLDER,
),
];
})
.flat();
}
@@ -0,0 +1,62 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {copyFile, mkdir} from 'fs/promises';
import {glob} from 'glob';
import {filesAndContentsToRecord} from '../utils/filesystem';
import {TUTORIALS_COMMON_DIRECTORY} from '../utils/web-constants';
import {getFileSystemTree, shouldUseFileInWebContainer} from '../utils/webcontainers';
import type {FileAndContent, TutorialFiles} from '../tutorials-types';
import {TUTORIALS_COMMON_ASSETS_DEST, TUTORIALS_COMMON_ASSETS_SRC} from '../utils/node-constants';
const BEFORE_COMMON_PATH_REGEX = new RegExp(`.*\/${TUTORIALS_COMMON_DIRECTORY}\/`);
export async function getTutorialCommonFiles(
files: string[],
filesContents: FileAndContent[],
): Promise<TutorialFiles> {
const filesPath = files.filter(shouldUseFileInWebContainer).map(getCleanFilePath);
const filesContentsWithoutPath = filesContents.map(({path, content}) => ({
path: getCleanFilePath(path),
content,
}));
const fileSystemTree = getFileSystemTree(
filesPath,
filesAndContentsToRecord(filesContentsWithoutPath),
);
return {sourceCode: fileSystemTree};
}
export function getCleanFilePath(path: string) {
return path.replace(BEFORE_COMMON_PATH_REGEX, '');
}
export async function copyCommonAssetsToAppAssets() {
const [commonAssets] = await Promise.all([
// List of files for the assets from the tutorial common directory/app.
glob(['**/*.png', '**/*.jpg'], {
cwd: TUTORIALS_COMMON_ASSETS_SRC,
nodir: true,
absolute: true,
}),
// Ensure the common directory for tutorial assets exists.
mkdir(TUTORIALS_COMMON_ASSETS_DEST, {recursive: true}),
]);
await Promise.all(
commonAssets.map((asset) =>
copyFile(asset, asset.replace(TUTORIALS_COMMON_ASSETS_SRC, TUTORIALS_COMMON_ASSETS_DEST)),
),
);
}
@@ -0,0 +1,146 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {basename} from 'path';
import {
filesAndContentsToRecord,
getFilesContents,
getPackageJsonFromFiles,
globWithCwdPath,
} from '../utils/filesystem';
import {
GLOB_OPTIONS,
TUTORIALS_COMMON_NODE_PATH,
TUTORIALS_HOMEPAGE_NODE_PATH,
} from '../utils/node-constants';
import {getCleanFilePath as getCleanCommonFilePath} from './common';
import {getTutorialConfig, validateOpenFilesConfig} from '../tutorials-config';
import {
FileAndContent,
FileAndContentRecord,
TutorialFiles,
TutorialMetadata,
} from '../tutorials-types';
import {getAllFiles, validatePackageJson} from '../utils/metadata';
import {TUTORIALS_HOMEPAGE_DIRECTORY, TutorialType} from '../utils/web-constants';
import {getFileSystemTree, shouldUseFileInWebContainer} from '../utils/webcontainers';
const BEFORE_HOMEPAGE_PATH_REGEX = new RegExp(`.*\/${TUTORIALS_HOMEPAGE_DIRECTORY}\/`);
export async function getHomepagePlaygroundFiles(
commonFiles: FileAndContent[],
): Promise<TutorialFiles> {
const homepagePlaygroundFiles = await globWithCwdPath('**', {
...GLOB_OPTIONS,
cwd: TUTORIALS_HOMEPAGE_NODE_PATH,
nodir: true,
});
const config = await getTutorialConfig(homepagePlaygroundFiles);
if (config.type !== TutorialType.EDITOR_ONLY)
throw new Error(`Homepage must be of type "${TutorialType.EDITOR_ONLY}"`);
const filesContents = await getFilesContents(homepagePlaygroundFiles);
const tutorialFiles = getTutorialFiles(filesContents, commonFiles);
if (config.openFiles) {
validateOpenFilesConfig(
TUTORIALS_HOMEPAGE_NODE_PATH,
config.openFiles,
Object.keys(tutorialFiles),
);
} else {
config.openFiles = Object.keys(tutorialFiles);
}
const hasPackageJson = homepagePlaygroundFiles.some((file) => basename(file) === 'package.json');
let dependencies: TutorialMetadata['dependencies'];
if (hasPackageJson) {
const packageJson = getPackageJsonFromFiles(filesContents);
dependencies = {
...packageJson.dependencies,
...packageJson.devDependencies,
};
validatePackageJson(homepagePlaygroundFiles, packageJson, getPackageJsonFromFiles(commonFiles));
}
const allFiles = getAllFiles(
homepagePlaygroundFiles,
commonFiles.map(({path}) => path),
getCleanFilePath,
);
return {
sourceCode: getSourceCode(homepagePlaygroundFiles, filesContents),
metadata: {
type: config.type,
allFiles,
dependencies,
tutorialFiles,
openFiles: config.openFiles ?? Object.keys(tutorialFiles),
hiddenFiles: config.openFiles
? Object.keys(tutorialFiles).filter((filename) => !config.openFiles!.includes(filename))
: [],
},
};
}
function getSourceCode(tutorialFiles: string[], filesContents: FileAndContent[]) {
// TODO: reuse this as it's duplicated in getTutorialFiles
const fileSystemTreeContents = filesContents
.filter(({path}) => shouldUseFileInWebContainer(path))
// remove steps paths from file contents
.map(({path, content}) => ({
path: getCleanFilePath(path),
content,
}));
const fileSystemTreeFiles = tutorialFiles
.filter((filename) => shouldUseFileInWebContainer(filename))
.map(getCleanFilePath);
return getFileSystemTree(fileSystemTreeFiles, filesAndContentsToRecord(fileSystemTreeContents));
}
function getTutorialFiles(
filesContents: FileAndContent[],
commonFiles: FileAndContent[],
): FileAndContentRecord {
const playgroundFilesForCodeEditor = filesContents
.filter(({path}) => shouldUseFileInWebContainer(getCleanFilePath(path)))
.map(({path, content}) => ({
path: getCleanFilePath(path),
content,
}));
const commonFilesForCodeEditor = commonFiles
.filter(({path}) => shouldUseFileInWebContainer(path))
.map(({path, content}) => ({
path: getCleanCommonFilePath(path),
content,
}));
return {
...filesAndContentsToRecord(commonFilesForCodeEditor),
...filesAndContentsToRecord(playgroundFilesForCodeEditor),
};
}
function getCleanFilePath(path: string) {
if (path.includes(TUTORIALS_COMMON_NODE_PATH)) return getCleanCommonFilePath(path);
return path.replace(BEFORE_HOMEPAGE_PATH_REGEX, '');
}
@@ -0,0 +1,402 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {basename, dirname, join} from 'path';
import {
filesAndContentsToRecord,
getFilesContents,
getPackageJsonFromFiles,
getZipBuffer,
globWithCwdPath,
recordToFilesAndContents,
} from '../utils/filesystem';
import {
ANSWER_DIRECTORY,
GLOB_OPTIONS,
INTRO_DIRECTORY,
STEPS_DIRECTORY,
TUTORIALS_PROJECT_PATH,
} from '../utils/node-constants';
import {getFileSystemTree, shouldUseFileInWebContainer} from '../utils/webcontainers';
import {getCleanFilePath as getCleanCommonFilePath} from './common';
import {TutorialNavigationItemWithStep} from '../generate-tutorials-routes';
import {getTutorialConfig, validateOpenFilesConfig} from '../tutorials-config';
import type {
FileAndContent,
FileAndContentRecord,
TutorialConfig,
TutorialFiles,
TutorialMetadata,
TutorialStep,
} from '../tutorials-types';
import {
TUTORIALS_COMMON_DIRECTORY,
TUTORIALS_DIST_PATH,
TUTORIALS_SOURCE_CODE_WEB_PATH,
TutorialType,
} from '../utils/web-constants';
import {getAllFiles, validatePackageJson} from '../utils/metadata';
export const TUTORIALS_DIRECTORY_REGEX = /^[a-z-0-9]*$/;
export const STEPS_DIRECTORY_REGEX = /^([0-9]|[0-9][0-9])-[A-Za-z-0-9]*$/;
const BEFORE_STEP_PATH_REGEX = new RegExp(`.*\/${STEPS_DIRECTORY}\/[^\/]+\/`);
const BEFORE_INTRO_PATH_REGEX = new RegExp(`.*\/${INTRO_DIRECTORY}\/`);
export async function getIntroAndStepsTutorialFiles(
tutorialName: string,
tutorialDirectories: string[],
tutorialFiles: string[],
commonTutorialFiles: FileAndContent[],
): Promise<Map<string, TutorialFiles>> {
const tutorialSteps = getTutorialSteps(tutorialName, tutorialDirectories);
const introAndStepsFiles = new Map<TutorialStep['url'], TutorialFiles>();
const tutorialCommonFiles = tutorialFiles.filter((file) =>
isCommonTutorialFile(tutorialName, file),
);
const introFiles = await getTutorialIntroFiles(
tutorialName,
[
...tutorialCommonFiles,
...tutorialFiles.filter((file) => file.includes(`/${INTRO_DIRECTORY}/`)),
],
tutorialSteps,
commonTutorialFiles,
);
introAndStepsFiles.set(tutorialName, introFiles);
await Promise.all(
tutorialSteps.map(async (step) => {
const stepFiles = tutorialFiles.filter((file) => file.includes(step.path));
let nextTutorial;
if (introFiles.route && 'tutorialData' in introFiles.route) {
nextTutorial = introFiles.route.tutorialData.nextTutorial;
}
const stepSourceCodeAndMetadata = await getStepFiles(
[...tutorialCommonFiles, ...stepFiles],
{
...step,
nextTutorial,
},
commonTutorialFiles,
);
introAndStepsFiles.set(step.url, stepSourceCodeAndMetadata);
}),
);
return introAndStepsFiles;
}
async function getTutorialIntroFiles(
tutorialName: string,
introTutorialFiles: string[],
tutorialSteps: TutorialStep[],
commonFilesContents: FileAndContent[],
) {
return getStepFiles(
introTutorialFiles,
{
step: 0,
name: tutorialName,
path: dirname(introTutorialFiles[0]),
nextStep: tutorialSteps.find((step) => step.step === 0 || step.step === 1)?.url, // assume the first tutorialSteps array item is the first step
url: tutorialName,
},
commonFilesContents,
);
}
async function getStepFiles(
stepFiles: string[],
step: TutorialStep,
commonFilesContents: FileAndContent[],
): Promise<TutorialFiles> {
const config = await getTutorialConfig(stepFiles);
// if src is present in the config, add files to the step files
if (config.src) {
const srcFiles = await getExternalTutorialFiles(step, config.src);
stepFiles.push(...srcFiles);
}
const filesContents = await getFilesContents(stepFiles);
const route: Omit<TutorialNavigationItemWithStep, 'path'> = {
label: config.title,
contentPath: getTutorialContentPath(stepFiles),
tutorialData: {
type: config.type,
title: config.title,
step: step.step,
nextStep: step.nextStep,
previousStep: step.previousStep,
nextTutorial: config.nextTutorial ?? step.nextTutorial,
},
};
if (config.type === TutorialType.LOCAL) {
const hasFilesToDownload =
filesContents.filter(({path}) => shouldUseFileInWebContainer(path)).length > 0;
if (!hasFilesToDownload) {
return {route};
} else {
const filesToDownload = getFilesToDownload(commonFilesContents, filesContents);
route.tutorialData.sourceCodeZipPath = join(
TUTORIALS_SOURCE_CODE_WEB_PATH,
step.url + '.zip',
);
return {
sourceCodeZip: await getZipBuffer(filesToDownload),
route,
};
}
}
const tutorialFiles = getTutorialFiles(filesContents);
if (config.openFiles) {
validateOpenFilesConfig(step.path, config.openFiles, Object.keys(tutorialFiles));
} else if (config.type === TutorialType.EDITOR) {
config.openFiles = Object.keys(tutorialFiles);
}
const hasPackageJson = stepFiles.some((file) => basename(file) === 'package.json');
let dependencies: TutorialMetadata['dependencies'];
if (hasPackageJson) {
const packageJson = getPackageJsonFromFiles(filesContents);
dependencies = {
...packageJson.dependencies,
...packageJson.devDependencies,
};
validatePackageJson(stepFiles, packageJson, getPackageJsonFromFiles(commonFilesContents));
}
const fileSystemTreeContents = filesContents
.filter(({path}) => shouldUseFileInWebContainer(path))
.map(({path, content}) => ({path: getCleanFilePath(path), content}));
const fileSystemTreeFiles = stepFiles.filter(shouldUseFileInWebContainer).map(getCleanFilePath);
const allFiles = getAllFiles(
stepFiles,
commonFilesContents.map(({path}) => path),
getCleanFilePath,
);
const metadata: TutorialMetadata = {
type: config.type,
allFiles,
tutorialFiles,
answerFiles: await getAnswerFiles(step, filesContents, config.answerSrc),
openFiles: config.openFiles ?? Object.keys(tutorialFiles),
hiddenFiles: config.openFiles
? Object.keys(tutorialFiles).filter((filename) => !config.openFiles!.includes(filename))
: [],
dependencies,
};
return {
metadata,
sourceCode: getFileSystemTree(
fileSystemTreeFiles,
filesAndContentsToRecord(fileSystemTreeContents),
),
route,
};
}
export function getTutorialSteps(
tutorialName: string,
tutorialDirectories: string[],
): TutorialStep[] {
const stepsDirectories = tutorialDirectories.filter((directory) => {
const isStepDirectory = directory.includes(`${tutorialName}/${STEPS_DIRECTORY}/`);
if (!isStepDirectory) return false;
const stepPathParts = directory.split('/');
// steps directory is always right after STEPS_DIRECTORY in the path, e.g. `learn-angular/steps/1-getting-started`
const stepDirectoryIndex = stepPathParts.indexOf(STEPS_DIRECTORY) + 1;
const step = stepPathParts[stepDirectoryIndex];
return step === stepPathParts.at(-1);
});
const steps: TutorialStep[] = [];
for (const stepDirectoryPath of stepsDirectories) {
const stepDirectory = basename(stepDirectoryPath);
// force the tutorials steps to follow the pattern steps/{step}-{name}
if (!STEPS_DIRECTORY_REGEX.test(stepDirectory))
throw `Invalid step directory '${stepDirectory}'. The step directory must start with a number > 0, followed by a hyphen and a name. For example: '1-intro'`;
const [step, ...nameParts] = stepDirectory.replace(`${STEPS_DIRECTORY}/`, '').split('-');
const name = nameParts.join('-');
steps.push({
step: Number(step),
name,
path: stepDirectoryPath,
url: join(tutorialName, name),
});
}
return steps.map((step) => {
const previousStep = steps.find(({step: previousStep}) => previousStep === step.step - 1);
const nextStep = steps.find(({step: nextStep}) => nextStep === step.step + 1);
return {
...step,
nextStep: nextStep?.url,
previousStep: previousStep?.url ?? tutorialName,
};
});
}
/**
* Filter files that won't be used in the WebContainer.
*/
function getTutorialFiles(
tutorialFilesContents: FileAndContent[],
): Record<FileAndContent['path'], FileAndContent['content']> {
const tutorialFiles = tutorialFilesContents
.filter(({path}) => shouldUseFileInWebContainer(path))
.map(({path, content}) => ({
path: getCleanFilePath(path),
content,
}));
return filesAndContentsToRecord(tutorialFiles);
}
async function getAnswerFiles(
step: TutorialStep,
filesContents: FileAndContent[],
answerSrc: TutorialConfig['answerSrc'],
): Promise<FileAndContentRecord> {
const removeAnswerPathFromFiles = (filesAndContents: FileAndContent[]) =>
filesAndContents.map(({path, content}) => ({
path: path.replace(`${ANSWER_DIRECTORY}/`, ''),
content,
}));
if (answerSrc) {
const answerSrcFiles = await getExternalTutorialFiles(step, answerSrc);
const answerFiles = await getFilesContents(answerSrcFiles);
return getTutorialFiles(removeAnswerPathFromFiles(answerFiles));
}
const answerFiles = filesContents.filter(({path}) => path.includes(`${ANSWER_DIRECTORY}/`));
return getTutorialFiles(removeAnswerPathFromFiles(answerFiles));
}
/**
* Get files external to the current tutorial directory.
*/
async function getExternalTutorialFiles(
step: TutorialStep,
relativePath: string,
): Promise<string[]> {
const externalFilesPath = join(step.path, relativePath);
const files = await globWithCwdPath('**', {
...GLOB_OPTIONS,
cwd: externalFilesPath,
nodir: true,
});
return files;
}
function getTutorialContentPath(stepFiles: string[]) {
const tutorialContentPath = stepFiles.find((filename) => filename.endsWith('README.md'));
if (!tutorialContentPath) {
const tutorialPath = dirname(stepFiles[0]);
throw `Tutorial at ${tutorialPath} is missing a README.md for content`;
}
const contentPathWithDistPath = tutorialContentPath.replace(
TUTORIALS_PROJECT_PATH,
TUTORIALS_DIST_PATH,
);
return contentPathWithDistPath.replace(/\.[^.]+$/, '');
}
/**
* Clean the file path by making it relative to the project root.
*
* @example
* ```ts
* getCleanFilePath('path-to-tutorial/intro/src/app/app.component.ts') => 'src/app/app.component.ts'
* getCleanFilePath('path-to-tutorial/steps/1-step/src/app/app.component.ts') => 'src/app/app.component.ts'
* ```
*/
function getCleanFilePath(path: string) {
if (path.includes(TUTORIALS_COMMON_DIRECTORY)) return getCleanCommonFilePath(path);
if (path.includes(STEPS_DIRECTORY)) return path.replace(BEFORE_STEP_PATH_REGEX, '');
return path.replace(BEFORE_INTRO_PATH_REGEX, '');
}
/**
* Merge common project files with the step files to get the final files to download.
*/
function getFilesToDownload(
commonFilesContents: FileAndContent[],
stepFilesWithoutAnswer: FileAndContent[],
) {
const commonFilesWithoutPath = commonFilesContents.map(({path, content}) => ({
path: getCleanCommonFilePath(path),
content,
}));
const stepFilesWithoutPath = stepFilesWithoutAnswer
.filter(({path}) => shouldUseFileInWebContainer(path))
.map(({path, content}) => ({
path: getCleanFilePath(path),
content,
}));
// use object to easily override common files with step files
const filesToDownload = {
...filesAndContentsToRecord(commonFilesWithoutPath),
...filesAndContentsToRecord(stepFilesWithoutPath),
};
return recordToFilesAndContents(filesToDownload);
}
function isCommonTutorialFile(tutorialPath: string, filePath: string) {
return filePath.includes(join(tutorialPath, TUTORIALS_COMMON_DIRECTORY));
}
@@ -0,0 +1,289 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {glob} from 'glob';
import {basename, join, sep} from 'path';
import {
filesAndContentsToRecord,
getFilesContents,
getPackageJsonFromFiles,
globWithCwdPath,
} from '../utils/filesystem';
import {CONFIG_FILE, GLOB_OPTIONS, TUTORIALS_PLAYGROUND_NODE_PATH} from '../utils/node-constants';
import {
DEFAULT_PLAYGROUND_TEMPLATE,
STARTER_PLAYGROUND_TEMPLATE,
TUTORIALS_COMMON_DIRECTORY,
TUTORIALS_PLAYGROUND_DIRECTORY,
TutorialType,
} from '../utils/web-constants';
import {getFileSystemTree, shouldUseFileInWebContainer} from '../utils/webcontainers';
import {getTutorialConfig, validateOpenFilesConfig} from '../tutorials-config';
import {
FileAndContent,
FileAndContentRecord,
PlaygroundFiles,
PlaygroundRouteData,
PlaygroundTemplate,
TutorialConfig,
TutorialFiles,
TutorialMetadata,
} from '../tutorials-types';
import {getAllFiles, validatePackageJson} from '../utils/metadata';
import {getCleanFilePath as getCleanCommonFilePath} from './common';
// used to avoid recreating a regex in loops
const beforePlaygroundPathRegexCache = new Map<string, RegExp>();
export async function getTutorialPlaygroundFiles(
commonFiles: FileAndContent[],
): Promise<Map<string, PlaygroundFiles>> {
const cwd = TUTORIALS_PLAYGROUND_NODE_PATH;
const [playgroundProjects, playgroundFiles] = await Promise.all([
glob('*/', {
ignore: [TUTORIALS_COMMON_DIRECTORY],
cwd,
}),
globWithCwdPath('**', {
...GLOB_OPTIONS,
nodir: true,
cwd,
}),
]);
const playgroundCommonFiles = playgroundFiles.filter(isPlaygroundCommonFile);
const playgroundFilesMap = new Map<string, PlaygroundFiles>();
const templates: PlaygroundTemplate[] = [];
await Promise.all(
playgroundProjects.map(async (project) => {
const projectFiles = playgroundFiles.filter((file) =>
file.startsWith(`${cwd}${sep}${project}${sep}`),
);
if (!projectFiles.length) {
throw new Error(
`Project at ${join(TUTORIALS_PLAYGROUND_NODE_PATH, project)} has no files.`,
);
}
const projectFilesAndPlaygroundCommonFiles = [...playgroundCommonFiles, ...projectFiles];
const projectPath = join(TUTORIALS_PLAYGROUND_DIRECTORY, project);
const {sourceCode, metadata, route} = await getPlaygroundFiles(
projectPath,
projectFilesAndPlaygroundCommonFiles,
commonFiles,
);
// store only sourceCode and metadata per playground template
playgroundFilesMap.set(projectPath, {sourceCode, metadata});
// compose playground templates from each project route object
if (route) templates.push(...route!.templates);
}),
);
const defaultTemplate = templates.find((template) =>
template.path.endsWith(DEFAULT_PLAYGROUND_TEMPLATE),
);
if (!defaultTemplate) {
throw new Error(`Invalid default playground template path '${DEFAULT_PLAYGROUND_TEMPLATE}'`);
}
const starterTemplate = templates.find((template) =>
template.path.endsWith(STARTER_PLAYGROUND_TEMPLATE),
);
if (!starterTemplate) {
throw new Error(`Invalid starter playground template path '${STARTER_PLAYGROUND_TEMPLATE}'`);
}
playgroundFilesMap.set(TUTORIALS_PLAYGROUND_DIRECTORY, {
route: {
templates: templates.sort((a, b) => {
const aPath = a.path.toLowerCase();
const bPath = b.path.toLowerCase();
if (aPath < bPath) return -1;
if (aPath > bPath) return 1;
return 0;
}),
defaultTemplate,
starterTemplate,
},
});
return playgroundFilesMap;
}
async function getPlaygroundFiles(
project: string,
playgroundFiles: string[],
commonFiles: FileAndContent[],
): Promise<PlaygroundFiles> {
const config = await getTutorialConfig(playgroundFiles);
if (config.type !== TutorialType.EDITOR_ONLY)
throw new Error(`Playground must be of type "${TutorialType.EDITOR_ONLY}"`);
const filesContents = await getFilesContents(playgroundFiles);
const projectFiles = getProjectFiles(project, config.openFiles, filesContents, commonFiles);
if (config.openFiles) {
validateOpenFilesConfig(
TUTORIALS_PLAYGROUND_NODE_PATH,
config.openFiles,
Object.keys(projectFiles),
);
}
const hasPackageJson = playgroundFiles.some((file) => basename(file) === 'package.json');
let dependencies: TutorialMetadata['dependencies'];
if (hasPackageJson) {
const packageJson = getPackageJsonFromFiles(filesContents);
dependencies = {
...packageJson.dependencies,
...packageJson.devDependencies,
};
validatePackageJson(playgroundFiles, packageJson, getPackageJsonFromFiles(commonFiles));
}
const allFiles = getAllFiles(
playgroundFiles,
commonFiles.map(({path}) => path),
(path: string) => getCleanFilePath(project, path),
);
return {
sourceCode: getSourceCode(project, playgroundFiles, filesContents),
metadata: {
type: config.type,
allFiles,
dependencies,
tutorialFiles: projectFiles,
openFiles: config.openFiles ?? Object.keys(projectFiles),
hiddenFiles: config.openFiles
? Object.keys(projectFiles).filter((filename) => !config.openFiles!.includes(filename))
: [],
},
route: {
templates: [{path: project, label: config.title}],
},
};
}
function getProjectFiles(
project: string,
openFiles: TutorialConfig['openFiles'],
playgroundFilesContents: FileAndContent[],
commonFiles: FileAndContent[],
): FileAndContentRecord {
const playgroundFilesForCodeEditor = playgroundFilesContents
// remove files that should not be shown in the code editor
.filter(({path}) => shouldUseFileInWebContainer(path))
// remove playground path from file paths
.map(({path, content}) => ({
path: getCleanFilePath(project, path),
content,
}));
if (!openFiles) return filesAndContentsToRecord(playgroundFilesForCodeEditor);
const commonFilesForCodeEditor = commonFiles
// remove files that should not be shown in the code editor
.filter(({path}) => shouldUseFileInWebContainer(getCleanCommonFilePath(path)))
// remove common path from file paths
.map(({path, content}) => ({
path: getCleanCommonFilePath(path),
content,
}));
const commonAndPlaygroundFiles = {
...filesAndContentsToRecord(commonFilesForCodeEditor),
...filesAndContentsToRecord(playgroundFilesForCodeEditor),
};
const openFilesConfigWithContents: FileAndContentRecord = {};
for (const openFile of openFiles) {
if (commonAndPlaygroundFiles[openFile]) {
openFilesConfigWithContents[openFile] = commonAndPlaygroundFiles[openFile];
} else {
throw `At ${TUTORIALS_PLAYGROUND_NODE_PATH}/${CONFIG_FILE}.\n\tCould not find file "${openFile}" in playground or common files`;
}
}
return openFilesConfigWithContents;
}
export function getSourceCode(
project: string,
tutorialFiles: string[],
filesContents: FileAndContent[],
) {
const fileSystemTreeContents = filesContents
// filter out config files
.filter(({path}) => shouldUseFileInWebContainer(path))
// remove steps paths from file contents
.map(({path, content}) => ({
path: getCleanFilePath(project, path),
content,
}));
const fileSystemTreeFiles = tutorialFiles
.filter(shouldUseFileInWebContainer)
.map((filename) => getCleanFilePath(project, filename));
return getFileSystemTree(fileSystemTreeFiles, filesAndContentsToRecord(fileSystemTreeContents));
}
/**
* Create a regex that matches the string before the project name in a path.
*
* This is used to remove the project name from the path, keeping only the path
* relative to the project root.
*/
function getBeforePlaygroundProjectRegex(project: string): RegExp {
const projectRegex = beforePlaygroundPathRegexCache.get(project);
if (projectRegex) return projectRegex;
const newRegex = new RegExp(`.*\/${project}\/`);
beforePlaygroundPathRegexCache.set(project, newRegex);
return newRegex;
}
function getCleanFilePath(project: string, path: string) {
if (isPlaygroundCommonFile(path)) {
return getCleanCommonFilePath(path);
}
return path.replace(getBeforePlaygroundProjectRegex(project), '');
}
export function isPlaygroundRouteData(
routeData: PlaygroundRouteData | TutorialFiles['route'],
): routeData is PlaygroundRouteData {
return (routeData as PlaygroundRouteData).templates !== undefined;
}
function isPlaygroundCommonFile(path: string) {
return path.includes(TUTORIALS_COMMON_DIRECTORY);
}
@@ -0,0 +1,145 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {basename, join} from 'path';
import {readdir} from 'fs/promises';
import {glob} from 'glob';
import {getFileContents} from './utils/filesystem';
import {
CONFIG_FILE,
CONFIG_KEYS,
REQUIRED_CONFIGS,
TUTORIALS_PROJECT_PATH,
} from './utils/node-constants';
import type {TutorialConfig} from './tutorials-types';
import {TutorialType} from './utils/web-constants';
export async function getTutorialConfig(tutorialFiles: string[]): Promise<TutorialConfig> {
const configFilePath = tutorialFiles.find((file) => basename(file) === CONFIG_FILE);
if (!configFilePath) throw `Can't find ${CONFIG_FILE}`;
const configFileContents = await getFileContents(configFilePath);
let config: TutorialConfig;
try {
config = JSON.parse(String(configFileContents));
config = await parseConfig(config);
return config;
} catch (err) {
throw `${configFilePath.replace(`${TUTORIALS_PROJECT_PATH}/`, '')}: ${err}`;
}
}
export async function parseConfig(config: TutorialConfig): Promise<TutorialConfig> {
const tutorialConfigKeys = Object.keys(config);
REQUIRED_CONFIGS.forEach((requiredConfig) => {
if (!tutorialConfigKeys.includes(requiredConfig)) {
throw `missing required config '${requiredConfig}'`;
}
});
for (const key of tutorialConfigKeys) {
// @ts-expect-error
if (!CONFIG_KEYS.includes(key)) throw `invalid config '${key}'`;
}
if (config.nextTutorial) {
if (typeof config.nextTutorial !== 'string') {
throw '"nextTutorial" must be a string';
}
const path = join(TUTORIALS_PROJECT_PATH, config.nextTutorial);
// check if nextTutorial directory exists
try {
await readdir(path);
} catch (error) {
throw `the nextTutorial "${config.nextTutorial}" doesn't exist at ${path}`;
}
}
if (config.src) {
if (typeof config.src !== 'string') {
throw '"src" must be a string';
}
// check if src directory exists
const srcFiles = await glob(`**/${config.src}`, {cwd: TUTORIALS_PROJECT_PATH});
if (!srcFiles.length) throw `could not find "src" "${config.src}"`;
}
if (config.answerSrc) {
if (typeof config.answerSrc !== 'string') {
throw '"answerSrc" must be a string';
}
// check if answerSrc directory exists
const answerSrcFiles = await glob(`**/${config.answerSrc}`, {cwd: TUTORIALS_PROJECT_PATH});
if (!answerSrcFiles.length) throw `could not find "answerSrc" "${config.answerSrc}"`;
}
switch (config.type) {
case TutorialType.EDITOR:
assertOpenFiles(config.openFiles);
return config;
case TutorialType.CLI:
return config;
case TutorialType.LOCAL:
return config;
case TutorialType.EDITOR_ONLY:
assertOpenFiles(config.openFiles);
return config;
default:
throw 'invalid config';
}
}
function assertOpenFiles(
openFiles: TutorialConfig['openFiles'],
): asserts openFiles is string[] | undefined {
if (openFiles === undefined) return;
const errorMessage = '"openFiles" must be an array of strings';
if (!Array.isArray(openFiles)) {
throw errorMessage;
}
for (const openFile of openFiles) {
if (typeof openFile !== 'string') throw errorMessage;
}
}
/**
* Check if openFiles exist in tutorial files.
*/
export function validateOpenFilesConfig(
tutorialPath: string,
openFiles: NonNullable<TutorialConfig['openFiles']>,
tutorialFiles: string[],
) {
for (const openFile of openFiles) {
if (!tutorialFiles.includes(openFile)) {
throw `At: ${tutorialPath}/${CONFIG_FILE}\n\tCould not find "${openFile}" in the tutorial files`;
}
}
}
+152
View File
@@ -0,0 +1,152 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import type {FileSystemTree} from '@webcontainer/api';
import type {TutorialNavigationItemWithStep} from './generate-tutorials-routes';
import {NavigationItem} from '@angular/docs-shared';
import {TutorialType} from './utils/web-constants';
/**
* Represents the contents of the tutorial files to be generated by the build script
*/
export type TutorialFiles = {
sourceCode?: FileSystemTree;
metadata?: TutorialMetadata;
sourceCodeZip?: Buffer;
route?: Omit<TutorialNavigationItemWithStep, 'path'>;
};
export type PlaygroundFiles = {
sourceCode?: FileSystemTree;
metadata?: TutorialMetadata;
sourceCodeZip?: undefined;
route?: PlaygroundRouteData;
};
/** Represents the contents of the tutorial config file */
export type TutorialMetadata = {
type: TutorialConfig['type'];
/** a record of all tutorials filenames and its contents */
tutorialFiles: FileAndContentRecord;
/** a record of filenames and contents for the tutorial answer */
answerFiles?: FileAndContentRecord;
/** files that are part of the project but are not visible in the code editor */
hiddenFiles: string[];
/**
* All files in the project, used to find the difference between new and old projects
* when changing projects
*/
allFiles: string[];
openFiles: NonNullable<TutorialConfig['openFiles']>;
/** whether a package.json exists */
dependencies?: Record<string, string>;
};
export type TutorialStep = {
step: number;
name: string;
path: string;
url: string;
nextStep?: TutorialStep['url'];
previousStep?: TutorialStep['url'];
nextTutorial?: string;
};
export type TutorialConfig =
| EditorTutorialConfig
| LocalTutorialConfig
| CliTutorialConfig
| EditorOnlyTutorialConfig;
export interface TutorialConfigBase {
type: TutorialType;
/** The tutorial title */
title: string;
/** The name of the tutorial folder that will be started after the current one ends. */
nextTutorial?: string;
/** The path to the tutorial src folder when it's external to the tutorial */
src?: string;
/** The path to the tutorial answer folder when it's external to the tutorial */
answerSrc?: string;
/** An array of files to be open in the editor */
openFiles?: string[];
}
/** Represents a tutorial config with all the embedded editor components enabled */
export interface EditorTutorialConfig extends TutorialConfigBase {
type: TutorialType.EDITOR;
}
/** Represents a tutorial config that won't use the embedded editor */
export interface LocalTutorialConfig extends TutorialConfigBase {
type: TutorialType.LOCAL;
// fields that must be undefined for local app tutorials
openFiles?: undefined;
src?: undefined;
answerSrc?: undefined;
}
/** Represents a tutorial config that supports only the interactive terminal for the Angular CLI */
export type CliTutorialConfig = Omit<LocalTutorialConfig, 'type'> & {
type: TutorialType.CLI;
};
export type EditorOnlyTutorialConfig = Omit<EditorTutorialConfig, 'type'> & {
type: TutorialType.EDITOR_ONLY;
};
export type FileAndContent = {
path: string;
content: string | Buffer;
};
export type FileAndContentRecord = Record<FileAndContent['path'], FileAndContent['content']>;
export type TutorialNavigationItem = {
path: NonNullable<NavigationItem['path']>;
label: NonNullable<NavigationItem['label']>;
children?: TutorialNavigationItem[];
parent?: TutorialNavigationItem;
contentPath?: string;
tutorialData: TutorialNavigationData;
};
export type TutorialNavigationData = {
type: TutorialConfig['type'];
title: TutorialConfig['title'];
nextStep?: string;
previousStep?: string;
nextTutorial?: string;
sourceCodeZipPath?: string;
};
export type PlaygroundRouteData = {
templates: PlaygroundTemplate[];
defaultTemplate?: PlaygroundTemplate;
starterTemplate?: PlaygroundTemplate;
};
export type PlaygroundTemplate = Required<Pick<NavigationItem, 'path' | 'label'>>;
// Note: only the fields being used are defined in this type
export interface PackageJson {
dependencies: Record<string, string>;
devDependencies: Record<string, string>;
}
@@ -0,0 +1,36 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {glob} from 'glob';
import {TUTORIALS_CONTENT_NODE_PATH} from './utils/node-constants';
import {dirname} from 'path';
import {execSync} from 'child_process';
main();
/**
* This script updates the package-lock.json files for all tutorials
* after manually changing the dependencies in the package.json files
*/
async function main() {
const tutorialsPackageJsons = await glob('**/package.json', {
ignore: ['**/node_modules'],
absolute: true,
cwd: TUTORIALS_CONTENT_NODE_PATH,
});
for (const path of tutorialsPackageJsons) {
const directory = dirname(path);
console.info(`\nUpdating lock file at ${directory}\n`);
execSync('npm install --package-lock-only', {
cwd: directory,
stdio: [null, null, 'inherit'],
});
}
}
+29
View File
@@ -0,0 +1,29 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {TUTORIALS_DIRECTORY_REGEX} from '../tutorial-type/intro-and-steps';
export function validatePathAnswer(
answer: string,
existingPaths: string[],
placeholder: string,
): string | true {
if (answer === placeholder) {
return 'Please define the path';
}
if (!TUTORIALS_DIRECTORY_REGEX.test(answer)) {
return `The path must be in the format of "${placeholder}"`;
}
if (existingPaths.includes(answer)) {
return `'${answer}' already exists`;
}
return true;
}
@@ -0,0 +1,150 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {basename, dirname} from 'path';
import {mkdir, readFile, writeFile} from 'fs/promises';
import {GlobOptionsWithFileTypesFalse, glob} from 'glob';
import JSZip from 'jszip';
import type {FileAndContent, FileAndContentRecord, PackageJson} from '../tutorials-types';
const fileContentsCache = new Map<string, string | Buffer>();
export async function getFileContents(path: string): Promise<string | Buffer> {
if (fileContentsCache.get(path)) {
return fileContentsCache.get(path)!;
}
const fileBuffer = await readFile(path);
if (isBufferImage(fileBuffer)) {
fileContentsCache.set(path, fileBuffer);
return fileBuffer;
}
fileContentsCache.set(path, fileBuffer.toString());
return fileBuffer.toString();
}
export async function getFilesContents(files: string[]): Promise<FileAndContent[]> {
const filesContents: FileAndContent[] = [];
await Promise.all(
files.map((path) =>
getFileContents(path).then((fileContents) => {
filesContents.push({path, content: fileContents});
}),
),
);
return filesContents;
}
export async function createDirectoryAndWriteFile(path: string, fileContents: string | Buffer) {
await mkdir(dirname(path), {recursive: true}).catch(() => {
// ignore error if directory already exists
});
await writeFile(path, fileContents);
}
export function filesAndContentsToRecord(filesAndContents: FileAndContent[]): FileAndContentRecord {
return Object.fromEntries(filesAndContents.map(({path, content}) => [path, content]));
}
export function recordToFilesAndContents(filesRecord: FileAndContentRecord): FileAndContent[] {
return Object.entries(filesRecord).map(([path, content]) => ({path, content}));
}
export async function getZipBuffer(files: FileAndContent[]): Promise<Buffer> {
const zip = new JSZip();
for (const file of files) {
zip.file(file.path, file.content, {binary: true});
}
return await zip.generateAsync({type: 'nodebuffer'});
}
export async function globWithCwdPath(
pattern: string | string[],
optionsWithCwd: Omit<GlobOptionsWithFileTypesFalse, 'cwd'> & {cwd: string},
) {
const files = await glob(pattern, optionsWithCwd);
return getFilesWithCwdPath(optionsWithCwd.cwd, files).sort();
}
export function getFilesWithCwdPath(cwdPath: string, files: string[]) {
return files.map((file) => file.substring(file.indexOf(cwdPath)));
}
function isBufferImage(buffer: Buffer) {
return isBufferPng(buffer) || isBufferJpg(buffer) || isBufferGif(buffer);
}
/**
* Check initial bytes of the buffer(aka magic numbers) to see if it's a PNG file.
*
* See https://en.wikipedia.org/wiki/Magic_number_(programming)#Magic_numbers_in_files
*/
function isBufferPng(buffer: Buffer) {
const pngSignature = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
return bufferMatchInitialBytes(buffer, pngSignature);
}
/**
* Check initial bytes of the buffer(aka magic numbers) to see if it's a JPG file.
*
* See https://en.wikipedia.org/wiki/Magic_number_(programming)#Magic_numbers_in_files
*/
function isBufferJpg(buffer: Buffer) {
const jpgSignature = [0xff, 0xd8, 0xff];
return bufferMatchInitialBytes(buffer, jpgSignature);
}
/**
* Check initial bytes of the buffer(aka magic numbers) to see if it's a GIF file.
*
* See https://en.wikipedia.org/wiki/Magic_number_(programming)#Magic_numbers_in_files
*/
function isBufferGif(buffer: Buffer) {
const gifSignature = [0x47, 0x49, 0x46];
return bufferMatchInitialBytes(buffer, gifSignature);
}
/**
* Check if the initial bytes of a buffer matches the expected bytes.
*/
function bufferMatchInitialBytes(buffer: Buffer, expectedInitialBytes: number[]) {
for (const [index, byte] of expectedInitialBytes.entries()) {
if (buffer[index] !== byte) return false;
}
return true;
}
export function getPackageJsonFromFiles(filesAndContents: FileAndContent[]): PackageJson {
const packageJson = filesAndContents.find(({path}) => basename(path) === 'package.json');
if (!packageJson)
throw new Error(`Could not find ${dirname(filesAndContents[0].path)}/package.json`);
let parsedPackageJsonContent: PackageJson;
try {
parsedPackageJsonContent = JSON.parse(packageJson.content as string);
} catch (e) {
throw new Error(`Could not JSON.parse ${dirname(filesAndContents[0].path)}/package.json`);
}
return parsedPackageJsonContent;
}
@@ -0,0 +1,74 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {basename, dirname} from 'path';
import {PackageJson} from '../tutorials-types';
import {shouldUseFileInWebContainer} from './webcontainers';
export function validatePackageJson(
files: string[],
projectPackageJson: PackageJson,
commonPackageJson: PackageJson,
): void {
if (!files.some((file) => basename(file) === 'package-lock.json')) {
throw new Error(
`Tutorial at ${dirname(
files[0],
)} has a package.json but is missing a package-lock.json. A lock file is required for faster installs.`,
);
}
const commonDependencies = {
...commonPackageJson.dependencies,
...commonPackageJson.devDependencies,
};
const projectDependencies = {
...projectPackageJson.dependencies,
...projectPackageJson.devDependencies,
};
const projectDependenciesNames = Object.keys(projectDependencies);
for (const dependency of Object.keys(commonDependencies)) {
if (!projectDependenciesNames.includes(dependency)) {
throw new Error(
`Tutorial at ${dirname(files[0])} is missing '${dependency}' as a dependency.`,
);
} else {
const commonDependencyVersion = commonDependencies[dependency];
const projectDependencyVersion = projectDependencies[dependency];
if (commonDependencyVersion !== projectDependencyVersion) {
throw new Error(
`${dirname(
files[0],
)} has a different version of '${dependency}' than the common package.json.
The common version is ${commonDependencyVersion}.
The project version is ${projectDependencyVersion}.
Please update the project package.json to match the common package.json, or update both.`,
);
}
}
}
}
export function getAllFiles(
projectFiles: string[],
commonFiles: string[],
getCleanFilePath: (file: string) => string,
) {
const commonAndProjectPaths = [...commonFiles, ...projectFiles]
.map((file) => getCleanFilePath(file))
.filter(shouldUseFileInWebContainer);
const uniquePaths = Array.from(new Set(commonAndProjectPaths));
return uniquePaths;
}
@@ -0,0 +1,115 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {join} from 'path';
import type {TutorialConfigBase} from '../tutorials-types';
import {
TUTORIALS_ASSETS_METADATA_DIRECTORY,
TUTORIALS_ASSETS_ROUTES_DIRECTORY,
TUTORIALS_ASSETS_SOURCE_CODE_DIRECTORY,
TUTORIALS_COMMON_DIRECTORY,
TUTORIALS_HOMEPAGE_DIRECTORY,
TUTORIALS_PLAYGROUND_DIRECTORY,
} from './web-constants';
import {GlobOptionsWithFileTypesFalse} from 'glob';
export const CONTENT_PATH = join('projects', 'angular-dev', 'src', 'content');
export const TUTORIALS_PROJECT_PATH = join(CONTENT_PATH, 'tutorials');
export const TUTORIALS_ASSETS_NODE_PATH = join(
'projects',
'angular-dev',
'src',
'assets',
'tutorials',
);
export const TUTORIALS_PLAYGROUND_NODE_PATH = join(
TUTORIALS_PROJECT_PATH,
TUTORIALS_PLAYGROUND_DIRECTORY,
);
export const TUTORIALS_HOMEPAGE_NODE_PATH = join(
TUTORIALS_PROJECT_PATH,
TUTORIALS_HOMEPAGE_DIRECTORY,
);
export const TUTORIALS_COMMON_NODE_PATH = join(TUTORIALS_PROJECT_PATH, TUTORIALS_COMMON_DIRECTORY);
/** The common location where the tutorial assets are stored. */
export const TUTORIALS_COMMON_ASSETS_SRC = join(TUTORIALS_COMMON_NODE_PATH, 'src', 'assets');
/** The common location for the tutorial assets to be served from. */
export const TUTORIALS_COMMON_ASSETS_DEST = join(TUTORIALS_ASSETS_NODE_PATH, 'common');
export const TUTORIALS_SOURCE_CODE_NODE_PATH = join(
TUTORIALS_ASSETS_NODE_PATH,
TUTORIALS_ASSETS_SOURCE_CODE_DIRECTORY,
);
export const TUTORIALS_METADATA_NODE_PATH = join(
TUTORIALS_ASSETS_NODE_PATH,
TUTORIALS_ASSETS_METADATA_DIRECTORY,
);
export const TUTORIALS_CONTENT_NODE_PATH = join(
'projects',
'angular-dev',
'src',
'content',
'tutorials',
);
export const TUTORIALS_ROUTES_NODE_PATH = join(
TUTORIALS_ASSETS_NODE_PATH,
TUTORIALS_ASSETS_ROUTES_DIRECTORY,
'tutorials.json',
);
export const PLAYGROUND_ROUTE_NODE_PATH = join(
TUTORIALS_ASSETS_NODE_PATH,
TUTORIALS_ASSETS_ROUTES_DIRECTORY,
'playground.json',
);
export const TUTORIALS_COMMON_ASSETS_PATH = join(TUTORIALS_COMMON_NODE_PATH, 'src', 'assets');
export const IGNORED_BASENAMES = [
'.DS_Store',
'LICENSE',
'.gitignore',
'.editorconfig',
'.gitkeep',
'favicon.ico',
];
export const IGNORED_EXTENSIONS = ['.map'];
export const IGNORED_DIRECTORIES = ['.git'];
export const TUTORIAL_CONTENT_FILENAME = 'README.md';
export const ANSWER_DIRECTORY = 'answer';
export const INTRO_DIRECTORY = 'intro';
export const STEPS_DIRECTORY = 'steps';
export const CONFIG_FILE = 'config.json';
export const CONFIG_KEYS: Array<keyof TutorialConfigBase> = [
'title',
'type',
'nextTutorial',
'src',
'answerSrc',
'openFiles',
];
export const REQUIRED_CONFIGS: Array<keyof Pick<TutorialConfigBase, 'title' | 'type'>> = [
'title',
'type',
];
export const CONTENT_PLACEHOLDER = 'Insert content here';
export const GLOB_OPTIONS: GlobOptionsWithFileTypesFalse = {
dot: false,
absolute: true,
posix: true,
ignore: [
'.',
'**/node_modules/**',
...IGNORED_BASENAMES.map((ignoredBasename) => `**/${ignoredBasename}`),
...IGNORED_EXTENSIONS.map((ext) => `**/*${ext}`),
...IGNORED_DIRECTORIES.map((dir) => `**/${dir}/**`),
],
};
@@ -0,0 +1,31 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export const TUTORIALS_ASSETS_WEB_PATH = '/assets/tutorials';
export const TUTORIALS_DIST_PATH = 'tutorials';
export const TUTORIALS_PLAYGROUND_DIRECTORY = 'playground';
/** the playground template that loads by default when entering the /playground page */
export const DEFAULT_PLAYGROUND_TEMPLATE = '0-minigame';
export const STARTER_PLAYGROUND_TEMPLATE = '3-hello-world';
export const TUTORIALS_HOMEPAGE_DIRECTORY = 'homepage';
export const TUTORIALS_COMMON_DIRECTORY = 'common';
export const TUTORIALS_ASSETS_SOURCE_CODE_DIRECTORY = 'source-code';
export const TUTORIALS_ASSETS_METADATA_DIRECTORY = 'metadata';
export const TUTORIALS_ASSETS_ROUTES_DIRECTORY = 'routes';
export const TUTORIALS_SOURCE_CODE_WEB_PATH = `${TUTORIALS_ASSETS_WEB_PATH}/${TUTORIALS_ASSETS_SOURCE_CODE_DIRECTORY}`;
export const TUTORIALS_METADATA_WEB_PATH = `${TUTORIALS_ASSETS_WEB_PATH}/${TUTORIALS_ASSETS_METADATA_DIRECTORY}`;
export const enum TutorialType {
CLI = 'cli',
LOCAL = 'local',
EDITOR = 'editor',
EDITOR_ONLY = 'editor-only',
}
@@ -0,0 +1,91 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {basename, dirname, extname} from 'path';
import {DirectoryNode, FileNode, FileSystemTree} from '@webcontainer/api';
import {ANSWER_DIRECTORY, CONFIG_FILE} from './node-constants';
import {FileAndContent, FileAndContentRecord} from '../tutorials-types';
/**
* Create a WebContainer's FileSystemTree from a list of files and its contents
*/
export function getFileSystemTree(files: string[], filesContents: FileAndContentRecord) {
const fileSystemTree: FileSystemTree = {};
for (let filepath of files) {
const dir = dirname(filepath);
const filename = basename(filepath);
if (dir === '.') {
const fileNode: FileNode = {file: {contents: filesContents[filepath]}};
fileSystemTree[filename] = fileNode;
} else {
const dirParts = dir.split('/');
buildFileSystemTree(fileSystemTree, dirParts, filename, filesContents[filepath]);
}
}
return fileSystemTree;
}
/**
* Builds a WebContainer's file system tree object recursively, mutating the
* `fileSystemTree` parameter.
*
* @see https://webcontainers.io/api#filesystemtree
*/
export function buildFileSystemTree(
fileSystemTree: FileSystemTree,
fileDirectories: string[],
filename: FileAndContent['path'],
fileContents: FileAndContent['content'],
): void {
if (fileDirectories.length === 1) {
const directory = fileDirectories[0];
const fileNode: FileNode = {file: {contents: fileContents}};
fileSystemTree[directory] = {
...fileSystemTree[directory],
directory: {
...(fileSystemTree[directory]
? (fileSystemTree[directory] as DirectoryNode).directory
: undefined),
[filename]: fileNode,
},
};
return;
}
const nextDirectory = fileDirectories.shift();
if (!nextDirectory) return;
if (!fileSystemTree[nextDirectory]) {
fileSystemTree[nextDirectory] = {directory: {}};
}
buildFileSystemTree(
(fileSystemTree[nextDirectory] as DirectoryNode).directory,
fileDirectories,
filename,
fileContents,
);
}
export function shouldUseFileInWebContainer(filename: string) {
return (
basename(filename) !== CONFIG_FILE &&
['.md', '.png', '.jpg'].includes(extname(filename)) === false &&
!filename.includes(`${ANSWER_DIRECTORY}/`)
);
}
@@ -0,0 +1,57 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {readFile, writeFile} from 'fs/promises';
import {dirname, join} from 'path';
import {argv} from 'process';
import {fileURLToPath} from 'url';
import {VersionsConfig, VersionMode} from './types.mjs';
// CONSTANTS
const MODE_ARG = 'v=';
const VERSIONS_CONFIG = 'versions.json';
// PATHS
const ASSETS = join(
dirname(fileURLToPath(import.meta.url)),
'../../src/assets',
);
const VERSIONS_CONFIG_PATH = join(ASSETS, VERSIONS_CONFIG);
main();
async function main() {
console.info('Updating version...');
const versionsConfig: VersionsConfig = JSON.parse(await readFile(VERSIONS_CONFIG_PATH, 'utf-8'));
const currentVersion = (await getCurrentVersion()) ?? 'stable';
if (
currentVersion !== 'next' &&
currentVersion !== 'rc' &&
currentVersion !== 'stable' &&
Number.isNaN(currentVersion)
) {
throw new Error('Invalid mode value provided!');
}
versionsConfig.currentVersion = currentVersion;
await updateConfig(versionsConfig);
console.info('Updating version successfully done!');
}
async function updateConfig(config: VersionsConfig): Promise<void> {
await writeFile(VERSIONS_CONFIG_PATH, `${JSON.stringify(config, null, 2)}\n`);
}
async function getCurrentVersion(): Promise<VersionMode | undefined> {
return argv.find((arg) => arg.startsWith(MODE_ARG))?.replaceAll(MODE_ARG, '') as VersionMode;
}
+8
View File
@@ -0,0 +1,8 @@
{
"extends": "../../tsconfig.json",
"ts-node": {
"compilerOptions": {
"module": "es2020"
}
}
}
+20
View File
@@ -0,0 +1,20 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export interface VersionUrl {
version: VersionMode;
url: string;
}
export type VersionMode = 'stable' | 'rc' | 'next' | number;
export interface VersionsConfig {
currentVersion: VersionMode;
currentVersions: VersionUrl[];
historicalVersions: VersionUrl[];
}
+7
View File
@@ -0,0 +1,7 @@
{
"$schema": "../../node_modules/ng-packagr/ng-package.schema.json",
"dest": "../../dist/shared",
"lib": {
"entryFile": "src/public-api.ts"
}
}
+12
View File
@@ -0,0 +1,12 @@
{
"name": "shared",
"version": "0.0.1",
"peerDependencies": {
"@angular/common": "^16.0.1",
"@angular/core": "^16.0.1"
},
"dependencies": {
"tslib": "^2.3.0"
},
"sideEffects": false
}
@@ -0,0 +1,52 @@
<!-- Algolia logo -->
<svg
id="Layer_1"
class="adev-algolia-logo"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 2196.2 500"
>
<defs>
<style>
.cls-1,
.cls-2 {
fill: #003dff;
}
.cls-2 {
fill-rule: evenodd;
}
</style>
</defs>
<path
class="cls-2"
d="M1070.38,275.3V5.91c0-3.63-3.24-6.39-6.82-5.83l-50.46,7.94c-2.87,.45-4.99,2.93-4.99,5.84l.17,273.22c0,12.92,0,92.7,95.97,95.49,3.33,.1,6.09-2.58,6.09-5.91v-40.78c0-2.96-2.19-5.51-5.12-5.84-34.85-4.01-34.85-47.57-34.85-54.72Z"
/>
<rect class="cls-1" x="1845.88" y="104.73" width="62.58" height="277.9" rx="5.9" ry="5.9" />
<path
class="cls-2"
d="M1851.78,71.38h50.77c3.26,0,5.9-2.64,5.9-5.9V5.9c0-3.62-3.24-6.39-6.82-5.83l-50.77,7.95c-2.87,.45-4.99,2.92-4.99,5.83v51.62c0,3.26,2.64,5.9,5.9,5.9Z"
/>
<path
class="cls-2"
d="M1764.03,275.3V5.91c0-3.63-3.24-6.39-6.82-5.83l-50.46,7.94c-2.87,.45-4.99,2.93-4.99,5.84l.17,273.22c0,12.92,0,92.7,95.97,95.49,3.33,.1,6.09-2.58,6.09-5.91v-40.78c0-2.96-2.19-5.51-5.12-5.84-34.85-4.01-34.85-47.57-34.85-54.72Z"
/>
<path
class="cls-2"
d="M1631.95,142.72c-11.14-12.25-24.83-21.65-40.78-28.31-15.92-6.53-33.26-9.85-52.07-9.85-18.78,0-36.15,3.17-51.92,9.85-15.59,6.66-29.29,16.05-40.76,28.31-11.47,12.23-20.38,26.87-26.76,44.03-6.38,17.17-9.24,37.37-9.24,58.36,0,20.99,3.19,36.87,9.55,54.21,6.38,17.32,15.14,32.11,26.45,44.36,11.29,12.23,24.83,21.62,40.6,28.46,15.77,6.83,40.12,10.33,52.4,10.48,12.25,0,36.78-3.82,52.7-10.48,15.92-6.68,29.46-16.23,40.78-28.46,11.29-12.25,20.05-27.04,26.25-44.36,6.22-17.34,9.24-33.22,9.24-54.21,0-20.99-3.34-41.19-10.03-58.36-6.38-17.17-15.14-31.8-26.43-44.03Zm-44.43,163.75c-11.47,15.75-27.56,23.7-48.09,23.7-20.55,0-36.63-7.8-48.1-23.7-11.47-15.75-17.21-34.01-17.21-61.2,0-26.89,5.59-49.14,17.06-64.87,11.45-15.75,27.54-23.52,48.07-23.52,20.55,0,36.63,7.78,48.09,23.52,11.47,15.57,17.36,37.98,17.36,64.87,0,27.19-5.72,45.3-17.19,61.2Z"
/>
<path
class="cls-2"
d="M894.42,104.73h-49.33c-48.36,0-90.91,25.48-115.75,64.1-14.52,22.58-22.99,49.63-22.99,78.73,0,44.89,20.13,84.92,51.59,111.1,2.93,2.6,6.05,4.98,9.31,7.14,12.86,8.49,28.11,13.47,44.52,13.47,1.23,0,2.46-.03,3.68-.09,.36-.02,.71-.05,1.07-.07,.87-.05,1.75-.11,2.62-.2,.34-.03,.68-.08,1.02-.12,.91-.1,1.82-.21,2.73-.34,.21-.03,.42-.07,.63-.1,32.89-5.07,61.56-30.82,70.9-62.81v57.83c0,3.26,2.64,5.9,5.9,5.9h50.42c3.26,0,5.9-2.64,5.9-5.9V110.63c0-3.26-2.64-5.9-5.9-5.9h-56.32Zm0,206.92c-12.2,10.16-27.97,13.98-44.84,15.12-.16,.01-.33,.03-.49,.04-1.12,.07-2.24,.1-3.36,.1-42.24,0-77.12-35.89-77.12-79.37,0-10.25,1.96-20.01,5.42-28.98,11.22-29.12,38.77-49.74,71.06-49.74h49.33v142.83Z"
/>
<path
class="cls-2"
d="M2133.97,104.73h-49.33c-48.36,0-90.91,25.48-115.75,64.1-14.52,22.58-22.99,49.63-22.99,78.73,0,44.89,20.13,84.92,51.59,111.1,2.93,2.6,6.05,4.98,9.31,7.14,12.86,8.49,28.11,13.47,44.52,13.47,1.23,0,2.46-.03,3.68-.09,.36-.02,.71-.05,1.07-.07,.87-.05,1.75-.11,2.62-.2,.34-.03,.68-.08,1.02-.12,.91-.1,1.82-.21,2.73-.34,.21-.03,.42-.07,.63-.1,32.89-5.07,61.56-30.82,70.9-62.81v57.83c0,3.26,2.64,5.9,5.9,5.9h50.42c3.26,0,5.9-2.64,5.9-5.9V110.63c0-3.26-2.64-5.9-5.9-5.9h-56.32Zm0,206.92c-12.2,10.16-27.97,13.98-44.84,15.12-.16,.01-.33,.03-.49,.04-1.12,.07-2.24,.1-3.36,.1-42.24,0-77.12-35.89-77.12-79.37,0-10.25,1.96-20.01,5.42-28.98,11.22-29.12,38.77-49.74,71.06-49.74h49.33v142.83Z"
/>
<path
class="cls-2"
d="M1314.05,104.73h-49.33c-48.36,0-90.91,25.48-115.75,64.1-11.79,18.34-19.6,39.64-22.11,62.59-.58,5.3-.88,10.68-.88,16.14s.31,11.15,.93,16.59c4.28,38.09,23.14,71.61,50.66,94.52,2.93,2.6,6.05,4.98,9.31,7.14,12.86,8.49,28.11,13.47,44.52,13.47h0c17.99,0,34.61-5.93,48.16-15.97,16.29-11.58,28.88-28.54,34.48-47.75v50.26h-.11v11.08c0,21.84-5.71,38.27-17.34,49.36-11.61,11.08-31.04,16.63-58.25,16.63-11.12,0-28.79-.59-46.6-2.41-2.83-.29-5.46,1.5-6.27,4.22l-12.78,43.11c-1.02,3.46,1.27,7.02,4.83,7.53,21.52,3.08,42.52,4.68,54.65,4.68,48.91,0,85.16-10.75,108.89-32.21,21.48-19.41,33.15-48.89,35.2-88.52V110.63c0-3.26-2.64-5.9-5.9-5.9h-56.32Zm0,64.1s.65,139.13,0,143.36c-12.08,9.77-27.11,13.59-43.49,14.7-.16,.01-.33,.03-.49,.04-1.12,.07-2.24,.1-3.36,.1-1.32,0-2.63-.03-3.94-.1-40.41-2.11-74.52-37.26-74.52-79.38,0-10.25,1.96-20.01,5.42-28.98,11.22-29.12,38.77-49.74,71.06-49.74h49.33Z"
/>
<path
class="cls-1"
d="M249.83,0C113.3,0,2,110.09,.03,246.16c-2,138.19,110.12,252.7,248.33,253.5,42.68,.25,83.79-10.19,120.3-30.03,3.56-1.93,4.11-6.83,1.08-9.51l-23.38-20.72c-4.75-4.21-11.51-5.4-17.36-2.92-25.48,10.84-53.17,16.38-81.71,16.03-111.68-1.37-201.91-94.29-200.13-205.96,1.76-110.26,92-199.41,202.67-199.41h202.69V407.41l-115-102.18c-3.72-3.31-9.42-2.66-12.42,1.31-18.46,24.44-48.53,39.64-81.93,37.34-46.33-3.2-83.87-40.5-87.34-86.81-4.15-55.24,39.63-101.52,94-101.52,49.18,0,89.68,37.85,93.91,85.95,.38,4.28,2.31,8.27,5.52,11.12l29.95,26.55c3.4,3.01,8.79,1.17,9.63-3.3,2.16-11.55,2.92-23.58,2.07-35.92-4.82-70.34-61.8-126.93-132.17-131.26-80.68-4.97-148.13,58.14-150.27,137.25-2.09,77.1,61.08,143.56,138.19,145.26,32.19,.71,62.03-9.41,86.14-26.95l150.26,133.2c6.44,5.71,16.61,1.14,16.61-7.47V9.48C499.66,4.25,495.42,0,490.18,0H249.83Z"
/>
</svg>

After

Width:  |  Height:  |  Size: 5.0 KiB

@@ -0,0 +1,17 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {Component} from '@angular/core';
@Component({
selector: 'docs-algolia-icon',
standalone: true,
imports: [],
templateUrl: './algolia-icon.component.html',
})
export class AlgoliaIcon {}
@@ -0,0 +1,13 @@
@for (breadcrumb of breadcrumbItems(); track breadcrumb) {
<div class="docs-breadcrumb">
@if (breadcrumb.path) {
@if (breadcrumb.isExternal) {
<a [href]="breadcrumb.path">{{ breadcrumb.label }}</a>
} @else {
<a [routerLink]="'/' + breadcrumb.path">{{ breadcrumb.label }}</a>
}
} @else {
<span>{{ breadcrumb.label }}</span>
}
</div>
}
@@ -0,0 +1,25 @@
:host {
display: flex;
align-items: center;
padding-block-end: 1.5rem;
}
.docs-breadcrumb {
span {
color: var(--quaternary-contrast);
font-size: 0.875rem;
display: flex;
align-items: center;
}
&:not(:last-child) {
span {
&::after {
content: 'chevron_right';
font-family: var(--icons);
margin-inline: 0.5rem;
color: var(--quinary-contrast);
}
}
}
}
@@ -0,0 +1,29 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {Breadcrumb} from './breadcrumb.component';
describe('Breadcrumb', () => {
let component: Breadcrumb;
let fixture: ComponentFixture<Breadcrumb>;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [Breadcrumb],
});
fixture = TestBed.createComponent(Breadcrumb);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});
@@ -0,0 +1,50 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ChangeDetectionStrategy, Component, OnInit, inject, signal} from '@angular/core';
import {NavigationState} from '../../services';
import {NavigationItem} from '../../interfaces';
import {NgFor, NgIf} from '@angular/common';
import {RouterLink} from '@angular/router';
@Component({
selector: 'docs-breadcrumb',
standalone: true,
imports: [NgIf, NgFor, RouterLink],
templateUrl: './breadcrumb.component.html',
styleUrls: ['./breadcrumb.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class Breadcrumb implements OnInit {
private readonly navigationState = inject(NavigationState);
breadcrumbItems = signal<NavigationItem[]>([]);
ngOnInit(): void {
this.setBreadcrumbItemsBasedOnNavigationStructure();
}
private setBreadcrumbItemsBasedOnNavigationStructure(): void {
let breadcrumbs: NavigationItem[] = [];
const traverse = (node: NavigationItem | null) => {
if (!node) {
return;
}
if (node.parent) {
breadcrumbs = [node.parent, ...breadcrumbs];
traverse(node.parent);
}
};
traverse(this.navigationState.activeNavigationItem());
this.breadcrumbItems.set(breadcrumbs);
}
}
@@ -0,0 +1,22 @@
@if (!hasAccepted()) {
<div class="docs-cookies-popup adev-invert-mode">
<p>This site uses cookies from Google to deliver its services and to analyze traffic.</p>
<div>
<a href="https://policies.google.com/technologies/cookies" target="_blank" rel="noopener">
<button class="adev-primary-btn" [attr.text]="'Learn more'" aria-label="Learn More">
Learn more
</button>
</a>
<button
type="button"
(click)="accept()"
class="adev-primary-btn"
[attr.text]="'Ok, Got it'"
aria-label="Ok, Got it"
>
Ok, Got it
</button>
</div>
</div>
}
@@ -0,0 +1,40 @@
:host {
position: fixed;
bottom: 0.5rem;
right: 0.5rem;
z-index: var(--z-index-cookie-consent);
opacity: 0;
visibility: hidden;
animation: 1s linear forwards 0.5s fadeIn;
}
.docs-cookies-popup {
padding: 1rem;
background-color: var(--page-background);
border: 1px solid var(--senary-contrast);
border-radius: 0.25rem;
font-size: 0.875rem;
max-width: 265px;
transition: background-color 0.3s ease, border-color 0.3s ease, color 0.3s ease;
box-shadow: 0 0 10px 0 rgba(0, 0, 0, 0.1);
> div {
display: flex;
gap: 0.5rem;
align-items: center;
width: 100%;
margin-block-start: 1rem;
}
p {
margin-block: 0;
color: var(--primary-contrast);
}
}
@keyframes fadeIn {
100% {
opacity: 100%;
visibility: visible;
}
}
@@ -0,0 +1,80 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {CookiePopup, STORAGE_KEY} from './cookie-popup.component';
import {LOCAL_STORAGE} from '../../providers';
import {MockLocalStorage} from '../../utils/test.utils';
describe('CookiePopup', () => {
let fixture: ComponentFixture<CookiePopup>;
let mockLocalStorage = new MockLocalStorage();
beforeEach(() => {
TestBed.configureTestingModule({
imports: [CookiePopup],
providers: [
{
provide: LOCAL_STORAGE,
useValue: mockLocalStorage,
},
],
});
});
it('should make the popup visible by default', () => {
initComponent(false);
expect(getCookiesPopup()).not.toBeNull();
});
it('should hide the cookies popup if the user has already accepted cookies', () => {
initComponent(true);
expect(getCookiesPopup()).toBeNull();
});
it('should hide the cookies popup', () => {
initComponent(false);
accept();
fixture.detectChanges();
expect(getCookiesPopup()).toBeNull();
});
it('should store the user confirmation', () => {
initComponent(false);
expect(mockLocalStorage.getItem(STORAGE_KEY)).toBeNull();
accept();
expect(mockLocalStorage.getItem(STORAGE_KEY)).toBe('true');
});
// Helpers
function getCookiesPopup() {
return (fixture.nativeElement as HTMLElement).querySelector('.docs-cookies-popup');
}
function accept() {
(fixture.nativeElement as HTMLElement)
.querySelector<HTMLButtonElement>('button[text="Ok, Got it"]')
?.click();
}
function initComponent(cookiesAccepted: boolean) {
mockLocalStorage.setItem(STORAGE_KEY, cookiesAccepted ? 'true' : null);
fixture = TestBed.createComponent(CookiePopup);
fixture.detectChanges();
}
});
@@ -0,0 +1,47 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ChangeDetectionStrategy, Component, inject, signal} from '@angular/core';
import {NgIf} from '@angular/common';
import {LOCAL_STORAGE} from '../../providers';
export const STORAGE_KEY = 'docs-accepts-cookies';
@Component({
selector: 'docs-cookie-popup',
standalone: true,
imports: [NgIf],
templateUrl: './cookie-popup.component.html',
styleUrls: ['./cookie-popup.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CookiePopup {
private readonly localStorage = inject(LOCAL_STORAGE);
/** Whether the user has accepted the cookie disclaimer. */
hasAccepted = signal<boolean>(false);
constructor() {
// Needs to be in a try/catch, because some browsers will
// throw when using `localStorage` in private mode.
try {
this.hasAccepted.set(this.localStorage?.getItem(STORAGE_KEY) === 'true');
} catch {
this.hasAccepted.set(false);
}
}
/** Accepts the cookie disclaimer. */
protected accept(): void {
try {
this.localStorage?.setItem(STORAGE_KEY, 'true');
} catch {}
this.hasAccepted.set(true);
}
}
@@ -0,0 +1,18 @@
<i>
<svg
aria-hidden="true"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
xmlns="http://www.w3.org/2000/svg"
class="adev-copy"
>
<path
d="M5 22C4.45 22 3.97917 21.8042 3.5875 21.4125C3.19583 21.0208 3 20.55 3 20V6H5V20H16V22H5ZM9 18C8.45 18 7.97917 17.8042 7.5875 17.4125C7.19583 17.0208 7 16.55 7 16V4C7 3.45 7.19583 2.97917 7.5875 2.5875C7.97917 2.19583 8.45 2 9 2H18C18.55 2 19.0208 2.19583 19.4125 2.5875C19.8042 2.97917 20 3.45 20 4V16C20 16.55 19.8042 17.0208 19.4125 17.4125C19.0208 17.8042 18.55 18 18 18H9ZM9 16H18V4H9V16Z"
fill="#A39FA9"
/>
</svg>
</i>
<docs-icon class="adev-check">check</docs-icon>
@@ -0,0 +1,120 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ComponentFixture, TestBed, fakeAsync, tick} from '@angular/core/testing';
import {
CONFIRMATION_DISPLAY_TIME_MS,
CopySourceCodeButton,
} from './copy-source-code-button.component';
import {Component, Input} from '@angular/core';
import {By} from '@angular/platform-browser';
import {Clipboard} from '@angular/cdk/clipboard';
const SUCCESSFULLY_COPY_CLASS_NAME = 'docs-copy-source-code-button-success';
const FAILED_COPY_CLASS_NAME = 'docs-copy-source-code-button-failed';
describe('CopySourceCodeButton', () => {
let component: CodeSnippetWrapper;
let fixture: ComponentFixture<CodeSnippetWrapper>;
let copySpy: jasmine.Spy<(text: string) => boolean>;
beforeEach(() => {
TestBed.configureTestingModule({
imports: [CodeSnippetWrapper],
});
fixture = TestBed.createComponent(CodeSnippetWrapper);
component = fixture.componentInstance;
fixture.detectChanges();
});
beforeEach(() => {
const clipboardService = TestBed.inject(Clipboard);
copySpy = spyOn(clipboardService, 'copy');
});
it('should call clipboard service when clicked on copy source code', () => {
const expectedCodeToBeCopied = 'npm install -g @angular/cli';
component.code = expectedCodeToBeCopied;
fixture.detectChanges();
const button = fixture.debugElement.query(By.directive(CopySourceCodeButton)).nativeElement;
button.click();
expect(copySpy.calls.argsFor(0)[0].trim()).toBe(expectedCodeToBeCopied);
});
it('should not copy lines marked as deleted when code snippet contains diff', () => {
const codeInHtmlFormat = `
<code>
<div class="hljs-ln-line remove"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> *<span class="hljs-attr">ngFor</span>=<span class="hljs-string">"let product of products"</span>&gt;</span></div>
<div class="hljs-ln-line add"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> *<span class="hljs-attr">ngFor</span>=<span class="hljs-string">"let product of products()"</span>&gt;</span></div>
</code>
`;
const expectedCodeToBeCopied = `<div *ngFor="let product of products()">`;
component.code = codeInHtmlFormat;
fixture.detectChanges();
const button = fixture.debugElement.query(By.directive(CopySourceCodeButton)).nativeElement;
button.click();
expect(copySpy.calls.argsFor(0)[0].trim()).toBe(expectedCodeToBeCopied);
});
it(`should set ${SUCCESSFULLY_COPY_CLASS_NAME} for ${CONFIRMATION_DISPLAY_TIME_MS} ms when copy was executed properly`, fakeAsync(() => {
component.code = 'example';
fixture.detectChanges();
const button = fixture.debugElement.query(By.directive(CopySourceCodeButton)).nativeElement;
button.click();
fixture.detectChanges();
expect(button).toHaveClass(SUCCESSFULLY_COPY_CLASS_NAME);
tick(CONFIRMATION_DISPLAY_TIME_MS);
fixture.detectChanges();
expect(button).not.toHaveClass(SUCCESSFULLY_COPY_CLASS_NAME);
}));
it(`should set ${FAILED_COPY_CLASS_NAME} for ${CONFIRMATION_DISPLAY_TIME_MS} ms when copy failed`, fakeAsync(() => {
component.code = 'example';
copySpy.and.throwError('Fake copy error');
fixture.detectChanges();
const button = fixture.debugElement.query(By.directive(CopySourceCodeButton)).nativeElement;
button.click();
fixture.detectChanges();
expect(button).toHaveClass(FAILED_COPY_CLASS_NAME);
tick(CONFIRMATION_DISPLAY_TIME_MS);
fixture.detectChanges();
expect(button).not.toHaveClass(FAILED_COPY_CLASS_NAME);
}));
});
@Component({
template: `
<pre>
<code [innerHtml]="code"></code>
</pre>
<button docs-copy-source-code></button>
`,
imports: [CopySourceCodeButton],
standalone: true,
})
class CodeSnippetWrapper {
@Input({required: true}) code!: string;
}
@@ -0,0 +1,89 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
ElementRef,
WritableSignal,
inject,
signal,
} from '@angular/core';
import {CommonModule} from '@angular/common';
import {Clipboard} from '@angular/cdk/clipboard';
import {IconComponent} from '../icon/icon.component';
export const REMOVED_LINE_CLASS_NAME = '.hljs-ln-line.remove';
export const CONFIRMATION_DISPLAY_TIME_MS = 2000;
@Component({
selector: 'button[docs-copy-source-code]',
standalone: true,
imports: [CommonModule, IconComponent],
templateUrl: './copy-source-code-button.component.html',
host: {
'type': 'button',
'aria-label': 'Copy example source to clipboard',
'title': 'Copy example source',
'(click)': 'copySourceCode()',
'[class.docs-copy-source-code-button-success]': 'showCopySuccess()',
'[class.docs-copy-source-code-button-failed]': 'showCopyFailure()',
},
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class CopySourceCodeButton {
private readonly changeDetector = inject(ChangeDetectorRef);
private readonly clipboard = inject(Clipboard);
private readonly elementRef = inject(ElementRef);
protected readonly showCopySuccess = signal(false);
protected readonly showCopyFailure = signal(false);
copySourceCode(): void {
try {
const codeElement = this.elementRef.nativeElement.parentElement.querySelector(
'code',
) as HTMLElement;
const sourceCode = this.getSourceCode(codeElement);
this.clipboard.copy(sourceCode);
this.showResult(this.showCopySuccess);
} catch {
this.showResult(this.showCopyFailure);
}
}
private getSourceCode(codeElement: HTMLElement): string {
this.showCopySuccess.set(false);
this.showCopyFailure.set(false);
const removedLines: NodeList = codeElement.querySelectorAll(REMOVED_LINE_CLASS_NAME);
if (removedLines.length) {
// Get only those lines which are not marked as removed
const formattedText = Array.from(codeElement.querySelectorAll('.hljs-ln-line:not(.remove)'))
.map((line) => (line as HTMLDivElement).innerText)
.join('\n');
return formattedText.trim();
} else {
const text: string = codeElement.innerText || '';
return text.replaceAll(`\n\n\n`, ``).trim();
}
}
private showResult(messageState: WritableSignal<boolean>) {
messageState.set(true);
setTimeout(() => {
messageState.set(false);
// It's required for code snippets embedded in the ExampleViewer.
this.changeDetector.markForCheck();
}, CONFIRMATION_DISPLAY_TIME_MS);
}
}
@@ -0,0 +1,145 @@
@use '../../styles/links' as links;
:host {
--translate-y: clamp(5px, 0.25em, 7px);
}
.docs-viewer {
display: flex;
flex-direction: column;
padding: var(--layout-padding);
max-width: var(--page-width);
width: 100%;
box-sizing: border-box;
@media only screen and (max-width: 1430px) {
container: docs-content / inline-size;
}
// If rendered on the docs page, accommodate width for TOC
adev-docs & {
@media only screen and (min-width: 1430px) and (max-width: 1550px) {
width: calc(100% - 195px - var(--layout-padding));
max-width: var(--page-width);
}
}
pre {
margin-block: 0;
padding-block: 0.75rem;
}
h1,
h2,
h3,
h4,
h5,
h6 {
.docs-anchor {
margin-block-start: 2.5rem;
display: inline-block;
color: inherit;
&::after {
content: '\e157'; // codepoint for "link"
font-family: 'Material Symbols Outlined';
opacity: 0;
margin-left: 8px;
vertical-align: middle;
color: var(--quaternary-contrast);
font-size: clamp(18px, 1.25em, 30px);
transition: opacity 0.3s ease;
}
&:hover {
&::after {
opacity: 1;
}
}
}
}
h1 {
font-size: 2.5rem;
margin-block-end: 0;
}
h2 {
font-size: 2rem;
margin-block-end: 0.5rem;
}
h3 {
font-size: 1.5rem;
margin-block-end: 0.5rem;
}
h4 {
font-size: 1.25rem;
margin-block-end: 0.5rem;
}
h5 {
font-size: 1rem;
margin-block-end: 0;
}
h6 {
font-size: 0.875rem;
margin-block-end: 0;
}
> :last-child {
margin-block-end: 0;
}
a:not(.docs-github-links):not(.docs-card):not(.docs-pill):not(.docs-example-github-link) {
&[href^='http:'],
&[href^='https:'] {
@include links.external-link-with-icon();
}
}
&-scroll-margin-large {
h2,
h3 {
scroll-margin: 5em;
}
}
}
.docs-header {
margin-block-end: 1rem;
& > p:first-child {
color: var(--quaternary-contrast);
font-weight: 500;
margin: 0;
}
}
.docs-page-title {
display: flex;
justify-content: space-between;
h1 {
margin-block: 0;
font-size: 2.25rem;
}
a {
color: var(--primary-contrast);
height: fit-content;
docs-icon {
color: var(--gray-400);
transition: color 0.3s ease;
}
&:hover {
docs-icon {
color: var(--primary-contrast);
}
}
}
}
@@ -0,0 +1,104 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ComponentFixture, TestBed} from '@angular/core/testing';
import {By} from '@angular/platform-browser';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {RouterTestingModule} from '@angular/router/testing';
import {DocContent, ExampleViewerContentLoader} from '../../interfaces';
import {EXAMPLE_VIEWER_CONTENT_LOADER} from '../../providers';
import {CodeExampleViewMode, ExampleViewer} from '../example-viewer/example-viewer.component';
import {DocViewer} from './docs-viewer.component';
describe('DocViewer', () => {
let fixture: ComponentFixture<DocViewer>;
let exampleContentSpy: jasmine.SpyObj<ExampleViewerContentLoader>;
const sampleDocContentWithExampleViewerPlaceholders: DocContent = {
id: 'id',
contents: `<div class="docs-code linenums" visibleLines="[12, 31]" expanded="true" path="hello-world/hello-world-new.ts">
<div class="docs-code-header">A styled code example</div>
<pre>
<code><div class="hljs-ln-line"><span class="hljs-comment">/*!</div><div class="hljs-ln-line"> * @license</div><div class="hljs-ln-line"> * Copyright Google LLC All Rights Reserved.</div><div class="hljs-ln-line"> *</div><div class="hljs-ln-line"> * Use of this source code is governed by an MIT-style license that can be</div><div class="hljs-ln-line"> * found in the LICENSE file at https://angular.dev/license</div><div class="hljs-ln-line"> */</span></div><div class="hljs-ln-line"></div><div class="hljs-ln-line remove"><span class="hljs-keyword">import</span> {ChangeDetectorRef, Component, <span class="hljs-keyword">inject</span>, signal} <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;@angular/core&#x27;</span>;</div><div class="hljs-ln-line add"><span class="hljs-keyword">import</span> {Component, signal} <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;@angular/core&#x27;</span>;</div><div class="hljs-ln-line"><span class="hljs-keyword">import</span> {CommonModule} <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;@angular/common&#x27;</span>;</div><div class="hljs-ln-line"></div><div class="hljs-ln-line highlighted">@Component({</div><div class="hljs-ln-line highlighted"> selector: <span class="hljs-string">&#x27;hello-world&#x27;</span>,</div><div class="hljs-ln-line highlighted"> standalone: <span class="hljs-keyword">true</span>,</div><div class="hljs-ln-line highlighted"> imports: [CommonModule],</div><div class="hljs-ln-line highlighted"> templateUrl: <span class="hljs-string">&#x27;./hello-world.html&#x27;</span>,</div><div class="hljs-ln-line highlighted"> styleUrls: [<span class="hljs-string">&#x27;./hello-world.css&#x27;</span>],</div><div class="hljs-ln-line highlighted">})</div><div class="hljs-ln-line">export <span class="hljs-keyword">default</span> <span class="hljs-keyword">class</span> HelloWorldComponent {</div><div class="hljs-ln-line remove"> world = <span class="hljs-string">&#x27;World&#x27;</span>;</div><div class="hljs-ln-line add"> world = <span class="hljs-string">&#x27;World!!!&#x27;</span>;</div><div class="hljs-ln-line"> <span class="hljs-keyword">count</span> = signal(<span class="hljs-number">0</span>);</div><div class="hljs-ln-line remove"> changeDetector = <span class="hljs-keyword">inject</span>(ChangeDetectorRef);</div><div class="hljs-ln-line"></div><div class="hljs-ln-line"> increase(): <span class="hljs-keyword">void</span> {</div><div class="hljs-ln-line"> <span class="hljs-keyword">this</span>.<span class="hljs-keyword">count</span>.update((<span class="hljs-keyword">previous</span>) =&gt; {</div><div class="hljs-ln-line highlighted"> <span class="hljs-keyword">return</span> <span class="hljs-keyword">previous</span> + <span class="hljs-number">1</span>;</div><div class="hljs-ln-line"> });</div><div class="hljs-ln-line remove"> <span class="hljs-keyword">this</span>.changeDetector.detectChanges();</div><div class="hljs-ln-line"> }</div><div class="hljs-ln-line">}</div><div class="hljs-ln-line"></div></code>
</pre>
</div>`,
};
const sampleDocContentWithExpandedExampleViewerPlaceholders: DocContent = {
id: 'id',
contents: ` <div class="docs-code-multifile" expanded="true" path="hello-world/hello-world-new.ts">
<div class="docs-code" visibleLines="[12, 31]" path="hello-world/hello-world-new.ts">
<pre>
<code><div class="hljs-ln-line"><span class="hljs-comment">/*!</div><div class="hljs-ln-line"> * @license</div><div class="hljs-ln-line"> * Copyright Google LLC All Rights Reserved.</div><div class="hljs-ln-line"> *</div><div class="hljs-ln-line"> * Use of this source code is governed by an MIT-style license that can be</div><div class="hljs-ln-line"> * found in the LICENSE file at https://angular.dev/license</div><div class="hljs-ln-line"> */</span></div><div class="hljs-ln-line"></div><div class="hljs-ln-line remove"><span class="hljs-keyword">import</span> {ChangeDetectorRef, Component, <span class="hljs-keyword">inject</span>, signal} <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;@angular/core&#x27;</span>;</div><div class="hljs-ln-line add"><span class="hljs-keyword">import</span> {Component, signal} <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;@angular/core&#x27;</span>;</div><div class="hljs-ln-line"><span class="hljs-keyword">import</span> {CommonModule} <span class="hljs-keyword">from</span> <span class="hljs-string">&#x27;@angular/common&#x27;</span>;</div><div class="hljs-ln-line"></div><div class="hljs-ln-line">@Component({</div><div class="hljs-ln-line"> selector: <span class="hljs-string">&#x27;hello-world&#x27;</span>,</div><div class="hljs-ln-line"> standalone: <span class="hljs-keyword">true</span>,</div><div class="hljs-ln-line"> imports: [CommonModule],</div><div class="hljs-ln-line"> templateUrl: <span class="hljs-string">&#x27;./hello-world.html&#x27;</span>,</div><div class="hljs-ln-line"> styleUrls: [<span class="hljs-string">&#x27;./hello-world.css&#x27;</span>],</div><div class="hljs-ln-line">})</div><div class="hljs-ln-line">export <span class="hljs-keyword">default</span> <span class="hljs-keyword">class</span> HelloWorldComponent {</div><div class="hljs-ln-line remove"> world = <span class="hljs-string">&#x27;World&#x27;</span>;</div><div class="hljs-ln-line add"> world = <span class="hljs-string">&#x27;World!!!&#x27;</span>;</div><div class="hljs-ln-line"> <span class="hljs-keyword">count</span> = signal(<span class="hljs-number">0</span>);</div><div class="hljs-ln-line remove"> changeDetector = <span class="hljs-keyword">inject</span>(ChangeDetectorRef);</div><div class="hljs-ln-line"></div><div class="hljs-ln-line"> increase(): <span class="hljs-keyword">void</span> {</div><div class="hljs-ln-line"> <span class="hljs-keyword">this</span>.<span class="hljs-keyword">count</span>.update((<span class="hljs-keyword">previous</span>) =&gt; {</div><div class="hljs-ln-line"> <span class="hljs-keyword">return</span> <span class="hljs-keyword">previous</span> + <span class="hljs-number">1</span>;</div><div class="hljs-ln-line"> });</div><div class="hljs-ln-line remove"> <span class="hljs-keyword">this</span>.changeDetector.detectChanges();</div><div class="hljs-ln-line"> }</div><div class="hljs-ln-line">}</div><div class="hljs-ln-line"></div></code>
</pre>
</div>
<div class="docs-code linenums" path="hello-world/hello-world.html">
<pre>
<code><div class="hljs-ln-line"><span class="language-xml"><span class="hljs-tag">&lt;<span class="hljs-name">h2</span>&gt;</span>Hello </span><span class="hljs-template-variable">{{ <span class="hljs-name">world</span> }}</span><span class="language-xml"><span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span></div><div class="hljs-ln-line"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> (<span class="hljs-attr">click</span>)=<span class="hljs-string">&quot;increase()&quot;</span>&gt;</span>Increase<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></div><div class="hljs-ln-line"><span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Counter: </span><span class="hljs-template-variable">{{ <span class="hljs-name">count</span>() }}</span><span class="language-xml"><span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span></div><div class="hljs-ln-line"></span></div></code>
</pre>
</div>
</div>`,
};
beforeEach(() => {
exampleContentSpy = jasmine.createSpyObj('ExampleContentLoader', ['getCodeExampleData']);
});
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [DocViewer, NoopAnimationsModule, RouterTestingModule],
providers: [{provide: EXAMPLE_VIEWER_CONTENT_LOADER, useValue: exampleContentSpy}],
}).compileComponents();
fixture = TestBed.createComponent(DocViewer);
fixture.detectChanges();
});
it('should load doc into innerHTML', () => {
const fixture = TestBed.createComponent(DocViewer);
fixture.componentRef.setInput('docContent', 'hello world');
fixture.detectChanges();
expect(fixture.nativeElement.innerHTML).toBe('hello world');
});
it('should instantiate example viewer in snippet view mode', async () => {
const fixture = TestBed.createComponent(DocViewer);
fixture.componentRef.setInput(
'docContent',
sampleDocContentWithExampleViewerPlaceholders.contents,
);
fixture.detectChanges();
await fixture.whenStable();
const exampleViewer = fixture.debugElement.query(By.directive(ExampleViewer));
expect(exampleViewer).not.toBeNull();
expect(exampleViewer.componentInstance.view()).toBe(CodeExampleViewMode.SNIPPET);
});
it('should display example viewer in multi file mode when user clicks expand', async () => {
const fixture = TestBed.createComponent(DocViewer);
fixture.componentRef.setInput(
'docContent',
sampleDocContentWithExpandedExampleViewerPlaceholders.contents,
);
fixture.detectChanges();
await fixture.whenStable();
const exampleViewer = fixture.debugElement.query(By.directive(ExampleViewer));
const expandButton = fixture.debugElement.query(
By.css('button[aria-label="Expand code example"]'),
);
expandButton.nativeElement.click();
expect(exampleViewer).not.toBeNull();
expect(exampleViewer.componentInstance.view()).toBe(CodeExampleViewMode.MULTI_FILE);
expect(exampleViewer.componentInstance.tabs().length).toBe(2);
});
});
@@ -0,0 +1,332 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {CommonModule, DOCUMENT, isPlatformBrowser, Location} from '@angular/common';
import {
ApplicationRef,
ChangeDetectionStrategy,
Component,
ComponentRef,
createComponent,
DestroyRef,
ElementRef,
EnvironmentInjector,
inject,
Injector,
Input,
OnChanges,
PLATFORM_ID,
SimpleChanges,
Type,
ViewContainerRef,
ViewEncapsulation,
ɵInitialRenderPendingTasks as PendingRenderTasks,
EventEmitter,
Output,
} from '@angular/core';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
import {
handleHrefClickEventWithRouter,
IconComponent,
NavigationState,
Snippet,
TableOfContents,
TOC_SKIP_CONTENT_MARKER,
} from '@angular/docs-shared';
import {Router} from '@angular/router';
import {fromEvent} from 'rxjs';
import {Breadcrumb} from '../breadcrumb/breadcrumb.component';
import {CopySourceCodeButton} from '../copy-source-code-button/copy-source-code-button.component';
import {ExampleViewer} from '../example-viewer/example-viewer.component';
/// <reference types="@types/dom-view-transitions" />
const TOC_HOST_ELEMENT_NAME = 'docs-table-of-contents';
export const ASSETS_EXAMPLES_PATH = 'assets/content/examples';
export const DOCS_VIEWER_SELECTOR = 'docs-viewer';
export const DOCS_CODE_SELECTOR = '.docs-code';
export const DOCS_CODE_MUTLIFILE_SELECTOR = '.docs-code-multifile';
// TODO: Update the branch/sha
export const GITHUB_CONTENT_URL =
'https://github.com/angular/angular/blob/main/adev/src/content/examples/';
@Component({
selector: DOCS_VIEWER_SELECTOR,
standalone: true,
imports: [CommonModule],
template: '',
styleUrls: ['docs-viewer.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
host: {
'[class.docs-animate-content]': 'animateContent',
},
})
export class DocViewer implements OnChanges {
@Input() docContent?: string;
@Input() hasToc = false;
@Output() contentLoaded = new EventEmitter<void>();
private readonly destroyRef = inject(DestroyRef);
private readonly document = inject(DOCUMENT);
private readonly elementRef = inject(ElementRef);
private readonly location = inject(Location);
private readonly navigationState = inject(NavigationState);
private readonly platformId = inject(PLATFORM_ID);
private readonly router = inject(Router);
private readonly viewContainer = inject(ViewContainerRef);
private readonly environmentInjector = inject(EnvironmentInjector);
private readonly injector = inject(Injector);
private readonly appRef = inject(ApplicationRef);
// tslint:disable-next-line:no-unused-variable
private animateContent = false;
private readonly pendingRenderTasks = inject(PendingRenderTasks);
private countOfExamples = 0;
async ngOnChanges(changes: SimpleChanges): Promise<void> {
const taskId = this.pendingRenderTasks.add();
if ('docContent' in changes) {
await this.renderContentsAndRunClientSetup(this.docContent!);
}
this.pendingRenderTasks.remove(taskId);
}
async renderContentsAndRunClientSetup(content?: string): Promise<void> {
const isBrowser = isPlatformBrowser(this.platformId);
const contentContainer = this.elementRef.nativeElement;
if (content) {
if (isBrowser && !(this.document as any).startViewTransition) {
// Apply a special class to the host node to trigger animation.
// Note: when a page is hydrated, the `content` would be empty,
// so we don't trigger an animation to avoid a content flickering
// visual effect. In addition, if the browser supports view transitions (startViewTransition is present), the animation is handled by the native View Transition API so it does not need to be done here.
this.animateContent = true;
}
contentContainer.innerHTML = content;
}
if (isBrowser) {
// First we setup event listeners on the HTML we just loaded.
// We want to do this before things like the example viewers are loaded.
this.setupAnchorListeners(contentContainer);
// Rewrite relative anchors (hrefs starting with `#`) because relative hrefs are relative to the base URL, which is '/'
this.rewriteRelativeAnchors(contentContainer);
// In case when content contains placeholders for executable examples, create ExampleViewer components.
await this.loadExamples();
// In case when content contains static code snippets, then create buttons
// responsible for copy source code.
this.loadCopySourceCodeButtons();
}
// Display Breadcrumb component if the `<docs-breadcrumb>` element exists
this.loadBreadcrumb(contentContainer);
// Display Icon component if the `<docs-icon>` element exists
this.loadIcons(contentContainer);
// Render ToC
this.renderTableOfContents(contentContainer);
this.contentLoaded.next();
}
/**
* Load ExampleViewer component when:
* - exists docs-code-multifile element with multiple files OR
* - exists docs-code element with single file AND
* - 'preview' attribute was provided OR
* - 'visibleLines' attribute was provided
*/
private async loadExamples(): Promise<void> {
const multifileCodeExamples = <HTMLElement[]>(
Array.from(this.elementRef.nativeElement.querySelectorAll(DOCS_CODE_MUTLIFILE_SELECTOR))
);
for (let placeholder of multifileCodeExamples) {
const path = placeholder.getAttribute('path')!;
const snippets = this.getCodeSnippetsFromMultifileWrapper(placeholder);
await this.renderExampleViewerComponents(placeholder, snippets, path);
}
const docsCodeElements = this.elementRef.nativeElement.querySelectorAll(DOCS_CODE_SELECTOR);
for (const placeholder of docsCodeElements) {
const snippet = this.getStandaloneCodeSnippet(placeholder);
if (snippet) {
await this.renderExampleViewerComponents(placeholder, [snippet], snippet.name);
}
}
}
private renderTableOfContents(element: HTMLElement): void {
if (!this.hasToc) {
return;
}
const firstHeading = element.querySelector<HTMLHeadingElement>('h2,h3[id]');
if (!firstHeading) {
return;
}
// Since the content of the main area is dynamically created and there is
// no host element for a ToC component, we create it manually.
let tocHostElement: HTMLElement | null = element.querySelector(TOC_HOST_ELEMENT_NAME);
if (!tocHostElement) {
tocHostElement = this.document.createElement(TOC_HOST_ELEMENT_NAME);
tocHostElement.setAttribute(TOC_SKIP_CONTENT_MARKER, 'true');
firstHeading?.parentNode?.insertBefore(tocHostElement, firstHeading);
}
this.renderComponent(TableOfContents, tocHostElement, {contentSourceElement: element});
}
private async renderExampleViewerComponents(
placeholder: HTMLElement,
snippets: Snippet[],
path: string,
): Promise<void> {
const preview = Boolean(placeholder.getAttribute('preview'));
const title = placeholder.getAttribute('header') ?? undefined;
const firstCodeSnippetTitle =
snippets.length > 0 ? snippets[0].title ?? snippets[0].name : undefined;
const exampleRef = this.viewContainer.createComponent(ExampleViewer);
this.countOfExamples++;
exampleRef.instance.metadata = {
title: title ?? firstCodeSnippetTitle,
path,
files: snippets,
preview,
id: this.countOfExamples,
};
exampleRef.instance.githubUrl = `${GITHUB_CONTENT_URL}/${snippets[0].name}`;
exampleRef.instance.stackblitzUrl = `${ASSETS_EXAMPLES_PATH}/${snippets[0].name}.html`;
placeholder.parentElement!.replaceChild(exampleRef.location.nativeElement, placeholder);
await exampleRef.instance.renderExample();
}
private getCodeSnippetsFromMultifileWrapper(element: HTMLElement): Snippet[] {
const tabs = <Element[]>Array.from(element.querySelectorAll(DOCS_CODE_SELECTOR));
return tabs.map((tab) => ({
name: tab.getAttribute('path') ?? tab.getAttribute('header') ?? '',
content: tab.innerHTML,
visibleLinesRange: tab.getAttribute('visibleLines') ?? undefined,
}));
}
private getStandaloneCodeSnippet(element: HTMLElement): Snippet | null {
const visibleLines = element.getAttribute('visibleLines') ?? undefined;
const preview = element.getAttribute('preview');
if (!visibleLines && !preview) {
return null;
}
const content = element.querySelector('pre')!;
const path = element.getAttribute('path')!;
const title = element.getAttribute('header') ?? undefined;
return {
title,
name: path,
content: content?.outerHTML,
visibleLinesRange: visibleLines,
};
}
// If the content contains static code snippets, we should add buttons to copy
// the code
private loadCopySourceCodeButtons(): void {
const staticCodeSnippets = <Element[]>(
Array.from(this.elementRef.nativeElement.querySelectorAll('.docs-code:not([mermaid])'))
);
for (let codeSnippet of staticCodeSnippets) {
const copySourceCodeButton = this.viewContainer.createComponent(CopySourceCodeButton);
codeSnippet.appendChild(copySourceCodeButton.location.nativeElement);
}
}
private loadBreadcrumb(element: HTMLElement): void {
const breadcrumbPlaceholder = element.querySelector('docs-breadcrumb') as HTMLElement;
const activeNavigationItem = this.navigationState.activeNavigationItem();
if (breadcrumbPlaceholder && !!activeNavigationItem?.parent) {
this.renderComponent(Breadcrumb, breadcrumbPlaceholder);
}
}
private loadIcons(element: HTMLElement): void {
element.querySelectorAll('docs-icon').forEach((iconsPlaceholder) => {
this.renderComponent(IconComponent, iconsPlaceholder as HTMLElement);
});
}
/**
* Helper method to render a component dynamically in a context of this class.
*/
private renderComponent<T>(
type: Type<T>,
hostElement: HTMLElement,
inputs?: {[key: string]: unknown},
): ComponentRef<T> {
const componentRef = createComponent(type, {
hostElement,
elementInjector: this.injector,
environmentInjector: this.environmentInjector,
});
if (inputs) {
for (const [name, value] of Object.entries(inputs)) {
componentRef.setInput(name, value);
}
}
// Trigger change detection after setting inputs.
componentRef.changeDetectorRef.detectChanges();
// Attach a view to the ApplicationRef for change detection
// purposes and for hydration serialization to pick it up
// during SSG.
this.appRef.attachView(componentRef.hostView);
return componentRef;
}
private setupAnchorListeners(element: HTMLElement): void {
element.querySelectorAll(`a[href]`).forEach((anchor) => {
// Get the target element's ID from the href attribute
const url = new URL((anchor as HTMLAnchorElement).href);
const isExternalLink = url.origin !== this.document.location.origin;
if (isExternalLink) {
return;
}
fromEvent(anchor, 'click')
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((e) => {
handleHrefClickEventWithRouter(e, this.router);
});
});
}
private rewriteRelativeAnchors(element: HTMLElement) {
for (const anchor of Array.from(element.querySelectorAll(`a[href^="#"]:not(a[download])`))) {
const url = new URL((anchor as HTMLAnchorElement).href);
(anchor as HTMLAnchorElement).href = this.location.path() + url.hash;
}
}
}
@@ -0,0 +1,155 @@
<div class="docs-example-viewer" role="group">
<header class="docs-example-viewer-actions">
@if (view() === CodeExampleViewMode.SNIPPET) {
<span>{{ exampleMetadata()?.title }}</span>
}
@if (view() === CodeExampleViewMode.MULTI_FILE) {
<mat-tab-group
#codeTabs
animationDuration="0ms"
mat-stretch-tabs="false"
>
@for (tab of tabs(); track tab) {
<mat-tab [label]="tab.name"></mat-tab>
}
</mat-tab-group>
}
<div class="docs-example-viewer-icons">
<button
type="button"
class="docs-example-copy-link"
[attr.aria-label]="'Copy link to ' + exampleMetadata()?.title + ' example to the clipboard'"
(click)="copyLink()"
>
<i aria-hidden="true">
<svg
aria-hidden="true"
width="24"
height="24"
viewBox="0 0 24 24"
fill="inherit"
xmlns="http://www.w3.org/2000/svg"
>
<!-- link icon -->
<path
d="M11 17H7C5.61667 17 4.4375 16.5125 3.4625 15.5375C2.4875 14.5625 2 13.3833 2 12C2 10.6167 2.4875 9.4375 3.4625 8.4625C4.4375 7.4875 5.61667 7 7 7H11V9H7C6.16667 9 5.45833 9.29167 4.875 9.875C4.29167 10.4583 4 11.1667 4 12C4 12.8333 4.29167 13.5417 4.875 14.125C5.45833 14.7083 6.16667 15 7 15H11V17ZM8 13V11H16V13H8ZM13 17V15H17C17.8333 15 18.5417 14.7083 19.125 14.125C19.7083 13.5417 20 12.8333 20 12C20 11.1667 19.7083 10.4583 19.125 9.875C18.5417 9.29167 17.8333 9 17 9H13V7H17C18.3833 7 19.5625 7.4875 20.5375 8.4625C21.5125 9.4375 22 10.6167 22 12C22 13.3833 21.5125 14.5625 20.5375 15.5375C19.5625 16.5125 18.3833 17 17 17H13Z"
fill="inherit"
/>
</svg>
</i>
</button>
<ng-container *ngTemplateOutlet="openCodeInExternalProvider" />
@if (expandable()) {
<button
type="button"
(click)="toggleExampleVisibility()"
[attr.title]="(expanded() ? 'Collapse' : 'Expand') + ' example'"
[attr.aria-label]="(expanded() ? 'Collapse' : 'Expand') + ' code example'"
>
<i aria-hidden="true">
@if (!expanded()) {
<svg
aria-hidden="true"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
viewBox="0 0 24 24"
fill="none"
>
<!-- Expand arrow -->
<path d="M3 21v-8h2v4.6L17.6 5H13V3h8v8h-2V6.4L6.4 19H11v2H3Z" />
</svg>
} @else {
<svg
aria-hidden="true"
xmlns="http://www.w3.org/2000/svg"
width="24"
height="24"
fill="none"
>
<path
fill="var(--gray-400)"
d="M3.4 22 2 20.6 8.6 14H4v-2h8v8h-2v-4.6L3.4 22ZM12 12V4h2v4.6L20.6 2 22 3.4 15.4 10H20v2h-8Z"
/>
</svg>
}
</i>
</button>
}
</div>
</header>
<div
class="docs-example-viewer-code-wrapper"
[class.docs-example-viewer-snippet]="view() === CodeExampleViewMode.SNIPPET"
[class.docs-example-viewer-multi-file]="view() === CodeExampleViewMode.MULTI_FILE"
>
<button docs-copy-source-code></button>
<docs-viewer [docContent]="snippetCode()?.content" />
</div>
@if (exampleComponent) {
<div class="docs-example-viewer-preview">
<ng-container *ngComponentOutlet="exampleComponent" />
</div>
}
<ng-template #openCodeInExternalProvider>
@if (exampleComponent) {
@if (githubUrl) {
<a
[href]="githubUrl"
target="_blank"
title="Open example on GitHub"
class="docs-example-github-link"
aria-label="Open example on GitHub"
>
<i aria-hidden="true">
<svg
aria-hidden="true"
width="24"
height="24"
viewBox="0 0 24 24"
fill="inherit"
xmlns="http://www.w3.org/2000/svg"
>
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M9.16141 22.8681C9.16141 22.5894 9.15159 21.8509 9.14614 20.8707C5.96014 21.5798 5.28759 19.296 5.28759 19.296C4.76668 17.9389 4.01559 17.5778 4.01559 17.5778C2.97541 16.8485 4.09414 16.8638 4.09414 16.8638C5.24396 16.9467 5.84886 18.0747 5.84886 18.0747C6.8705 19.8692 8.52923 19.3516 9.18268 19.0505C9.28686 18.2912 9.5825 17.7736 9.90977 17.4801C7.36632 17.184 4.69196 16.176 4.69196 11.6754C4.69196 10.3936 5.13868 9.34523 5.87123 8.52377C5.75396 8.22705 5.36014 7.03305 5.98359 5.41577C5.98359 5.41577 6.94577 5.09996 9.13359 6.61959C10.0467 6.35941 11.0269 6.2285 12.0016 6.22414C12.9741 6.2285 13.9538 6.35941 14.869 6.61959C17.0558 5.09996 18.0163 5.41577 18.0163 5.41577C18.6414 7.0325 18.2481 8.2265 18.1298 8.52377C18.864 9.34523 19.3069 10.3936 19.3069 11.6754C19.3069 16.1874 16.6287 17.1801 14.077 17.4709C14.4889 17.8336 14.8543 18.5503 14.8543 19.6461C14.8543 21.2165 14.8396 22.4836 14.8396 22.8681C14.8396 23.1829 15.0463 23.5478 15.6278 23.4327C20.1758 21.877 23.4545 17.4774 23.4545 12.2907C23.4545 5.80359 18.3256 0.54541 11.9994 0.54541C5.67432 0.54541 0.54541 5.80359 0.54541 12.2907C0.545956 17.479 3.82796 21.8814 8.37977 23.4343C8.95196 23.5418 9.16141 23.179 9.16141 22.8681Z"
fill="inherit"
/>
</svg>
</i>
</a>
}
@if (stackblitzUrl) {
<a
[href]="stackblitzUrl"
target="_blank"
class="docs-example-stackblitz-link"
title="Edit this example in StackBlitz"
aria-label="Edit this example in StackBlitz"
>
<i aria-hidden="true">
<svg
width="24"
height="24"
viewBox="0 0 356 511"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M138.719 150.22C62.6928 232.614 0.340573 300.4 0.158928 300.856C-0.0227172 301.311 33.9559 301.799 75.6665 301.939L151.505 302.195L117.656 396.511C74.7852 515.966 76.7972 510.288 77.3522 510.288C78.2145 510.288 355.296 209.735 355.296 208.799C355.296 208.245 325.263 207.879 279.943 207.879C233.709 207.879 204.591 207.518 204.591 206.943C204.591 206.428 220.136 162.751 239.137 109.883C279.06 -1.20153 278.545 0.264614 277.638 0.347453C277.26 0.382384 214.746 67.8247 138.719 150.22Z"
/>
</svg>
</i>
</a>
}
}
</ng-template>
</div>
@@ -0,0 +1,133 @@
:host {
.docs-example-viewer-preview {
.adev-dark-mode & {
background: var(--gray-100);
}
@media screen and (prefers-color-scheme: dark) {
background: var(--gray-100);
}
.adev-light-mode & {
background: var(--page-background);
}
}
}
.docs-example-viewer {
border: 1px solid var(--senary-contrast);
border-radius: 0.25rem;
overflow: hidden;
}
// Example viewer header
.docs-example-viewer-actions {
background: var(--subtle-purple);
display: flex;
justify-content: space-between;
align-items: center;
gap: 0.5rem;
border-bottom: 1px solid var(--senary-contrast);
transition: background 0.3s ease, border-color 0.3s ease;
padding-inline-end: 0.65rem;
font-family: var(--inter-tight-font);
mat-tab-group {
max-width: calc(100% - 140px);
}
span:first-of-type {
background-image: var(--purple-to-blue-horizontal-gradient);
background-clip: text;
-webkit-background-clip: text;
color: transparent;
padding: 0.7rem 1.1rem;
font-size: 0.875rem;
font-style: normal;
font-weight: 400;
line-height: 1.4rem;
letter-spacing: -0.00875rem;
margin: 0;
word-wrap: break-word;
width: fit-content;
}
.docs-example-viewer-icons {
display: flex;
gap: 0.75rem;
svg {
fill: var(--gray-400);
}
}
a,
button {
padding: 0;
margin: 0;
cursor: pointer;
height: 24px;
width: 24px;
path {
transition: fill 0.3s ease;
}
&:hover {
svg {
fill: var(--tertiary-contrast);
}
}
}
}
// Example viewer code
.docs-example-viewer-code-wrapper {
position: relative;
font-size: 0.875rem;
// TODO: only show this if there is a preview
// border-block-end: 1px solid var(--senary-contrast);
transition: border-color 0.3s ease;
container: viewerblock / inline-size;
background-color: var(--octonary-contrast);
button[docs-copy-source-code] {
top: 0.31rem;
@container viewerblock (min-width: 400px) {
background-color: transparent;
border: 1px solid transparent;
}
}
}
// stylelint-disable-next-line
::ng-deep {
.docs-example-viewer-preview {
// stylelint-disable-next-line
all: initial;
display: block;
padding: 1rem;
border-block-start: 1px solid var(--senary-contrast);
*,
code::before,
code,
pre,
a,
i,
p,
h1,
h2,
h3,
h4,
h5,
h6,
ol,
ul,
li,
hr,
input,
select,
table {
all: revert;
}
}
}
@@ -0,0 +1,228 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {ComponentFixture, TestBed, waitForAsync} from '@angular/core/testing';
import {ExampleViewer} from './example-viewer.component';
import {DocsContentLoader, ExampleMetadata, ExampleViewerContentLoader} from '../../interfaces';
import {DOCS_CONTENT_LOADER, EXAMPLE_VIEWER_CONTENT_LOADER} from '../../providers';
import {Component} from '@angular/core';
import {NoopAnimationsModule} from '@angular/platform-browser/animations';
import {HarnessLoader} from '@angular/cdk/testing';
import {TestbedHarnessEnvironment} from '@angular/cdk/testing/testbed';
import {Clipboard} from '@angular/cdk/clipboard';
import {By} from '@angular/platform-browser';
import {MatTabGroupHarness} from '@angular/material/tabs/testing';
import {CopySourceCodeButton} from '../copy-source-code-button/copy-source-code-button.component';
import {ActivatedRoute} from '@angular/router';
describe('ExampleViewer', () => {
let component: ExampleViewer;
let fixture: ComponentFixture<ExampleViewer>;
let loader: HarnessLoader;
let exampleContentSpy: jasmine.SpyObj<ExampleViewerContentLoader>;
let contentServiceSpy: jasmine.SpyObj<DocsContentLoader>;
beforeEach(() => {
exampleContentSpy = jasmine.createSpyObj('ExampleContentLoader', ['loadPreview']);
contentServiceSpy = jasmine.createSpyObj('ContentLoader', ['getContent']);
contentServiceSpy.getContent.and.returnValue(Promise.resolve(undefined));
});
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [ExampleViewer, NoopAnimationsModule],
providers: [
{provide: EXAMPLE_VIEWER_CONTENT_LOADER, useValue: exampleContentSpy},
{provide: DOCS_CONTENT_LOADER, useValue: contentServiceSpy},
{provide: ActivatedRoute, useValue: {snapshot: {fragment: 'fragment'}}},
],
}).compileComponents();
fixture = TestBed.createComponent(ExampleViewer);
component = fixture.componentInstance;
loader = TestbedHarnessEnvironment.loader(fixture);
fixture.detectChanges();
});
it('should set file extensions as tab names when all files have different extension', waitForAsync(async () => {
component.metadata = getMetadata({
files: [
{name: 'file.ts', content: ''},
{name: 'file.html', content: ''},
{name: 'file.css', content: ''},
],
});
await component.renderExample();
expect(component.tabs()!.length).toBe(3);
expect(component.tabs()![0].name).toBe('TS');
expect(component.tabs()![1].name).toBe('HTML');
expect(component.tabs()![2].name).toBe('CSS');
}));
it('should generate correct code content for multi file mode when it is expanded', waitForAsync(async () => {
component.metadata = getMetadata({
files: [
{name: 'file.ts', content: 'typescript file'},
{name: 'file.html', content: 'html file'},
{name: 'file.css', content: 'css file'},
],
});
await component.renderExample();
expect(component.tabs()!.length).toBe(3);
expect(component.tabs()![0].code).toBe('typescript file');
expect(component.tabs()![1].code).toBe('html file');
expect(component.tabs()![2].code).toBe('css file');
}));
it('should set file names as tab names when there is at least one duplication', async () => {
component.metadata = getMetadata({
files: [
{name: 'example.ts', content: 'typescript file'},
{name: 'example.html', content: 'html file'},
{name: 'another-example.ts', content: 'css file'},
],
});
await component.renderExample();
expect(component.tabs()!.length).toBe(3);
expect(component.tabs()![0].name).toBe('example.ts');
expect(component.tabs()![1].name).toBe('example.html');
expect(component.tabs()![2].name).toBe('another-example.ts');
});
it('should expandable be false when none of the example files have defined visibleLinesRange ', waitForAsync(async () => {
component.metadata = getMetadata();
await component.renderExample();
expect(component.expandable()).toBeFalse();
}));
it('should expandable be true when at least one example file has defined visibleLinesRange ', waitForAsync(async () => {
component.metadata = getMetadata({
files: [
{name: 'example.ts', content: 'typescript file'},
{
name: 'example.html',
content: 'html file',
visibleLinesRange: '[1, 2]',
},
{name: 'another-example.ts', content: 'css file'},
],
});
await component.renderExample();
expect(component.expandable()).toBeTrue();
}));
it('should set exampleComponent when metadata contains path and preview is true', waitForAsync(async () => {
exampleContentSpy.loadPreview.and.resolveTo(ExampleComponent);
component.metadata = getMetadata({
path: 'example.ts',
preview: true,
});
await component.renderExample();
expect(component.exampleComponent).toBe(ExampleComponent);
}));
it('should display GitHub button when githubUrl is provided and there is preview', waitForAsync(async () => {
exampleContentSpy.loadPreview.and.resolveTo(ExampleComponent);
component.metadata = getMetadata({
path: 'example.ts',
preview: true,
});
component.githubUrl = 'https://github.com/';
await component.renderExample();
const githubButton = fixture.debugElement.query(
By.css('a[aria-label="Open example on GitHub"]'),
);
expect(githubButton).toBeTruthy();
expect(githubButton.nativeElement.href).toBe(component.githubUrl);
}));
it('should display StackBlitz button when stackblitzUrl is provided and there is preview', waitForAsync(async () => {
exampleContentSpy.loadPreview.and.resolveTo(ExampleComponent);
component.metadata = getMetadata({
path: 'example.ts',
preview: true,
});
component.stackblitzUrl = 'https://stackblitz.com/';
await component.renderExample();
const stackblitzButton = fixture.debugElement.query(
By.css('a[aria-label="Edit this example in StackBlitz"]'),
);
expect(stackblitzButton).toBeTruthy();
expect(stackblitzButton.nativeElement.href).toBe(component.stackblitzUrl);
}));
it('should set expanded flag in metadata after toggleExampleVisibility', waitForAsync(async () => {
component.metadata = getMetadata();
await component.renderExample();
component.toggleExampleVisibility();
expect(component.expanded()).toBeTrue();
const tabGroup = await loader.getHarness(MatTabGroupHarness);
const tab = await tabGroup.getSelectedTab();
expect(await tab.getLabel()).toBe('TS');
component.toggleExampleVisibility();
expect(component.expanded()).toBeFalse();
}));
it('should call clipboard service when clicked on copy source code', waitForAsync(async () => {
const expectedCodeSnippetContent = 'typescript code';
component.metadata = getMetadata({
files: [
{
name: 'example.ts',
content: `<pre><code>${expectedCodeSnippetContent}</code></pre>`,
},
{name: 'example.css', content: ''},
],
});
const clipboardService = TestBed.inject(Clipboard);
const spy = spyOn(clipboardService, 'copy');
await component.renderExample();
const button = fixture.debugElement.query(By.directive(CopySourceCodeButton)).nativeElement;
button.click();
expect(spy.calls.argsFor(0)[0].trim()).toBe(expectedCodeSnippetContent);
}));
it('should call clipboard service when clicked on copy example link', waitForAsync(async () => {
component.metadata = getMetadata();
component.expanded.set(true);
fixture.detectChanges();
const clipboardService = TestBed.inject(Clipboard);
const spy = spyOn(clipboardService, 'copy');
await component.renderExample();
const button = fixture.debugElement.query(
By.css('button.docs-example-copy-link'),
).nativeElement;
button.click();
expect(spy.calls.argsFor(0)[0].trim()).toBe(`http://localhost:9876/context.html#example-1`);
}));
});
const getMetadata = (value: Partial<ExampleMetadata> = {}): ExampleMetadata => {
return {
id: 1,
files: [
{name: 'example.ts', content: ''},
{name: 'example.css', content: ''},
],
preview: false,
...value,
};
};
@Component({
template: '',
standalone: true,
})
class ExampleComponent {}
@@ -0,0 +1,237 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {
ChangeDetectionStrategy,
Component,
DestroyRef,
Input,
Type,
computed,
inject,
ChangeDetectorRef,
ViewChild,
signal,
ElementRef,
forwardRef,
} from '@angular/core';
import {CommonModule, DOCUMENT} from '@angular/common';
import {MatTabGroup, MatTabsModule} from '@angular/material/tabs';
import {Clipboard} from '@angular/cdk/clipboard';
import {CopySourceCodeButton} from '../copy-source-code-button/copy-source-code-button.component';
import {ExampleMetadata, Snippet} from '../../interfaces';
import {EXAMPLE_VIEWER_CONTENT_LOADER} from '../../providers';
import {DocViewer} from '../docs-viewer/docs-viewer.component';
import {takeUntilDestroyed} from '@angular/core/rxjs-interop';
export enum CodeExampleViewMode {
SNIPPET = 'snippet',
MULTI_FILE = 'multi',
}
export const CODE_LINE_NUMBER_CLASS_NAME = 'hljs-ln-number';
export const CODE_LINE_CLASS_NAME = 'hljs-ln-line';
export const GAP_CODE_LINE_CLASS_NAME = 'gap';
export const HIDDEN_CLASS_NAME = 'hidden';
@Component({
selector: 'docs-example-viewer',
standalone: true,
imports: [CommonModule, forwardRef(() => DocViewer), CopySourceCodeButton, MatTabsModule],
templateUrl: './example-viewer.component.html',
styleUrls: ['./example-viewer.component.scss'],
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class ExampleViewer {
// TODO: replace by signal-based input when it'll be available
@Input({required: true}) set metadata(value: ExampleMetadata) {
this.exampleMetadata.set(value);
}
@Input() githubUrl: string | null = null;
@Input() stackblitzUrl: string | null = null;
@ViewChild('codeTabs') matTabGroup?: MatTabGroup;
private readonly changeDetector = inject(ChangeDetectorRef);
private readonly clipboard = inject(Clipboard);
private readonly destroyRef = inject(DestroyRef);
private readonly document = inject(DOCUMENT);
private readonly elementRef = inject(ElementRef<HTMLElement>);
private readonly exampleViewerContentLoader = inject(EXAMPLE_VIEWER_CONTENT_LOADER);
private readonly shouldDisplayFullName = computed(() => {
const fileExtensions =
this.exampleMetadata()?.files.map((file) => this.getFileExtension(file.name)) ?? [];
// Display full file names only when exist files with the same extension
return new Set(fileExtensions).size !== fileExtensions.length;
});
CodeExampleViewMode = CodeExampleViewMode;
exampleComponent?: Type<unknown>;
expanded = signal<boolean>(false);
exampleMetadata = signal<ExampleMetadata | null>(null);
snippetCode = signal<Snippet | undefined>(undefined);
tabs = computed(() =>
this.exampleMetadata()?.files.map((file) => ({
name:
file.title ?? (this.shouldDisplayFullName() ? file.name : this.getFileExtension(file.name)),
code: file.content,
})),
);
view = computed(() =>
this.exampleMetadata()?.files.length === 1
? CodeExampleViewMode.SNIPPET
: CodeExampleViewMode.MULTI_FILE,
);
expandable = computed(() =>
this.exampleMetadata()?.files.some((file) => !!file.visibleLinesRange),
);
async renderExample(): Promise<void> {
// Lazy load live example component
if (this.exampleMetadata()?.path && this.exampleMetadata()?.preview) {
this.exampleComponent = await this.exampleViewerContentLoader.loadPreview(
this.exampleMetadata()?.path!,
);
}
this.snippetCode.set(this.exampleMetadata()?.files[0]);
this.changeDetector.detectChanges();
this.setCodeLinesVisibility();
this.elementRef.nativeElement.setAttribute(
'id',
`example-${this.exampleMetadata()?.id.toString()!}`,
);
this.matTabGroup?.realignInkBar();
this.listenToMatTabIndexChange();
}
toggleExampleVisibility(): void {
this.expanded.update((expanded) => !expanded);
this.setCodeLinesVisibility();
}
copyLink(): void {
// Reconstruct the URL using `origin + pathname` so we drop any pre-existing hash.
const fullUrl = location.origin + location.pathname + '#example-' + this.exampleMetadata()?.id;
this.clipboard.copy(fullUrl);
}
private listenToMatTabIndexChange(): void {
this.matTabGroup?.realignInkBar();
this.matTabGroup?.selectedIndexChange
.pipe(takeUntilDestroyed(this.destroyRef))
.subscribe((index) => {
this.snippetCode.set(this.exampleMetadata()?.files[index]);
this.setCodeLinesVisibility();
});
}
private getFileExtension(name: string): string {
const segments = name.split('.');
return segments.length ? segments[segments.length - 1].toLocaleUpperCase() : '';
}
private setCodeLinesVisibility(): void {
this.expanded()
? this.handleExpandedStateForCodeBlock()
: this.handleCollapsedStateForCodeBlock();
}
private handleExpandedStateForCodeBlock(): void {
const lines = <HTMLDivElement[]>(
Array.from(
this.elementRef.nativeElement.querySelectorAll(
`.${CODE_LINE_CLASS_NAME}.${HIDDEN_CLASS_NAME}`,
),
)
);
const lineNumbers = <HTMLSpanElement[]>(
Array.from(
this.elementRef.nativeElement.querySelectorAll(
`.${CODE_LINE_NUMBER_CLASS_NAME}.${HIDDEN_CLASS_NAME}`,
),
)
);
const gapLines = <HTMLDivElement[]>(
Array.from(
this.elementRef.nativeElement.querySelectorAll(
`.${CODE_LINE_CLASS_NAME}.${GAP_CODE_LINE_CLASS_NAME}`,
),
)
);
for (const line of lines) {
line.classList.remove(HIDDEN_CLASS_NAME);
}
for (const lineNumber of lineNumbers) {
lineNumber.classList.remove(HIDDEN_CLASS_NAME);
}
for (const expandLine of gapLines) {
expandLine.remove();
}
}
private handleCollapsedStateForCodeBlock(): void {
const visibleLinesRange = this.snippetCode()?.visibleLinesRange;
if (!visibleLinesRange) {
return;
}
const linesToDisplay = (visibleLinesRange?.split(',') ?? []).map((line) => Number(line));
const lines = <HTMLDivElement[]>(
Array.from(this.elementRef.nativeElement.querySelectorAll(`.${CODE_LINE_CLASS_NAME}`))
);
const lineNumbers = <HTMLSpanElement[]>(
Array.from(this.elementRef.nativeElement.querySelectorAll(`.${CODE_LINE_NUMBER_CLASS_NAME}`))
);
const appendGapBefore = [];
for (const [index, line] of lines.entries()) {
if (!linesToDisplay.includes(index)) {
line.classList.add(HIDDEN_CLASS_NAME);
} else if (!linesToDisplay.includes(index - 1)) {
appendGapBefore.push(line);
}
}
for (const [index, lineNumber] of lineNumbers.entries()) {
if (!linesToDisplay.includes(index)) {
lineNumber.classList.add(HIDDEN_CLASS_NAME);
}
}
// Create gap line between visible ranges. For example we would like to display 10-16 and 20-29 lines.
// We should display separator, gap between those two scopes.
// TODO: we could replace div it with the component, and allow to expand code block after click.
for (const [index, element] of appendGapBefore.entries()) {
if (index === 0) {
continue;
}
const separator = this.document.createElement('div');
separator.textContent = `...`;
separator.classList.add(CODE_LINE_CLASS_NAME);
separator.classList.add(GAP_CODE_LINE_CLASS_NAME);
element.parentNode?.insertBefore(separator, element);
}
}
}
@@ -0,0 +1 @@
<ng-content></ng-content>
@@ -0,0 +1,3 @@
.docs-icon_high-contrast {
color: var(--primary-contrast);
}
@@ -0,0 +1,58 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {DOCUMENT} from '@angular/common';
import {
ChangeDetectionStrategy,
ChangeDetectorRef,
Component,
afterNextRender,
inject,
} from '@angular/core';
@Component({
selector: 'docs-icon',
standalone: true,
templateUrl: './icon.component.html',
styleUrl: './icon.component.scss',
host: {
'[class]': 'MATERIAL_SYMBOLS_OUTLINED',
'[style.font-size.px]': 'fontSize',
'aria-hidden': 'true',
},
changeDetection: ChangeDetectionStrategy.OnPush,
})
export class IconComponent {
private readonly cdRef = inject(ChangeDetectorRef);
get fontSize(): number | null {
return IconComponent.isFontLoaded ? null : 0;
}
protected readonly MATERIAL_SYMBOLS_OUTLINED = 'material-symbols-outlined';
private static isFontLoaded: boolean = false;
/** Share the same promise across different instances of the component */
private static whenFontLoad?: Promise<FontFace[]> | undefined;
constructor() {
if (IconComponent.isFontLoaded) {
return;
}
const document = inject(DOCUMENT);
afterNextRender(async () => {
IconComponent.whenFontLoad ??= document.fonts.load('normal 1px "Material Symbols Outlined"');
await IconComponent.whenFontLoad;
IconComponent.isFontLoaded = true;
// We need to ensure CD is triggered on the component when the font is loaded
this.cdRef.markForCheck();
});
}
}
+17
View File
@@ -0,0 +1,17 @@
/*!
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
export * from './cookie-popup/cookie-popup.component';
export * from './docs-viewer/docs-viewer.component';
export * from './navigation-list/navigation-list.component';
export * from './select/select.component';
export * from './slide-toggle/slide-toggle.component';
export * from './table-of-contents/table-of-contents.component';
export * from './text-field/text-field.component';
export * from './icon/icon.component';
export * from './search-dialog/search-dialog.component';

Some files were not shown because too many files have changed in this diff Show More