_id
stringlengths 21
254
| text
stringlengths 1
93.7k
| metadata
dict |
---|---|---|
angular/adev/shared-docs/pipeline/api-gen/rendering/regions/region-matchers/inline-c.ts_0_558 | /*!
* @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} */`;
| {
"end_byte": 558,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/regions/region-matchers/inline-c.ts"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/regions/region-matchers/inline-c-only.ts_0_583 | /*!
* @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}`;
| {
"end_byte": 583,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/regions/region-matchers/inline-c-only.ts"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/regions/region-matchers/block-c.ts_0_605 | /*!
* @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} */`;
| {
"end_byte": 605,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/regions/region-matchers/block-c.ts"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/shiki/shiki.ts_0_1472 | let highlighter: any;
export async function initHighlighter() {
const {createHighlighter} = await import('shiki');
highlighter = await createHighlighter({
themes: ['github-light', 'github-dark'],
langs: [
'javascript',
'typescript',
'angular-html',
'angular-ts',
'shell',
'html',
'http',
'json',
'jsonc',
'nginx',
'markdown',
'apache',
],
});
}
export function codeToHtml(
code: string,
language: string | undefined,
options?: {removeFunctionKeyword?: boolean},
): string {
const html = highlighter.codeToHtml(code, {
lang: language ?? 'text',
themes: {
light: 'github-light',
dark: 'github-dark',
},
cssVariablePrefix: '--shiki-',
defaultColor: false,
});
if (options?.removeFunctionKeyword) {
return replaceKeywordFromShikiHtml('function', html);
}
return html;
}
export function replaceKeywordFromShikiHtml(
keyword: string,
shikiHtml: string,
replaceWith = '',
): string {
return (
shikiHtml
// remove the leading space of the element after the "function" element
.replace(new RegExp(`(<[^>]*>${keyword}<\\/\\w+><[^>]*>)(\\s)(\\w+<\\/\\w+>)`, 'g'), '$1$3')
// Shiki requires the keyword function for highlighting functions signatures
// We don't want to display it so we remove elements with the keyword
.replace(new RegExp(`<[^>]*>${keyword}<\\/\\w+>`, 'g'), replaceWith)
);
}
| {
"end_byte": 1472,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/shiki/shiki.ts"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/test/BUILD.bazel_0_768 | load("//adev/shared-docs/pipeline/api-gen/rendering:render_api_to_html.bzl", "render_api_to_html")
load("//tools:defaults.bzl", "jasmine_node_test", "ts_library")
render_api_to_html(
name = "test",
srcs = [
"fake-cli-entries.json",
"fake-entries.json",
],
)
ts_library(
name = "unit_test_lib",
testonly = True,
srcs = glob(
[
"**/*.spec.ts",
],
),
deps = [
"//adev/shared-docs/pipeline/api-gen/rendering:render_api_to_html_lib",
"@npm//@bazel/runfiles",
"@npm//@types/jsdom",
"@npm//jsdom",
],
)
jasmine_node_test(
name = "unit_tests",
data = [
"@npm//jsdom",
] + glob([
"**/*.json",
]),
deps = [":unit_test_lib"],
)
| {
"end_byte": 768,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/test/BUILD.bazel"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/test/marked.spec.ts_0_3017 | import {runfiles} from '@bazel/runfiles';
import {readFile} from 'fs/promises';
import {JSDOM} from 'jsdom';
import {renderEntry} from '../rendering';
import {getRenderable} from '../processing';
import {initHighlighter} from '../shiki/shiki';
import {configureMarkedGlobally} from '../marked/configuration';
import {setSymbols} from '../symbol-context';
// Note: The tests will probably break if the schema of the api extraction changes.
// All entries in the fake-entries are extracted from Angular's api.
// You can just generate them an copy/replace the items in the fake-entries file.
describe('markdown to html', () => {
const entries = new Map<string, DocumentFragment>();
const entries2 = new Map<string, string>();
beforeAll(async () => {
await initHighlighter();
await configureMarkedGlobally();
const entryContent = await readFile(runfiles.resolvePackageRelative('fake-entries.json'), {
encoding: 'utf-8',
});
const entryJson = JSON.parse(entryContent) as any;
const symbols = new Map<string, string>([
['AfterRenderPhase', 'core'],
['afterRender', 'core'],
]);
setSymbols(symbols);
for (const entry of entryJson.entries) {
const renderableJson = getRenderable(entry, '@angular/fakeentry');
const fragment = JSDOM.fragment(await renderEntry(renderableJson));
entries.set(entry['name'], fragment);
entries2.set(entry['name'], await renderEntry(renderableJson));
}
});
it('should render description correctly', () => {
const afterNextRenderEntry = entries.get('afterNextRender')!;
const header = afterNextRenderEntry.querySelector('.docs-reference-header')!;
expect(header).toBeDefined();
expect(header.outerHTML).not.toContain('```');
console.log(entries2.get('afterNextRender'));
const list = afterNextRenderEntry.querySelector('ul')!;
expect(list).toBeDefined();
// List are rendered
expect(list.outerHTML).toContain('<li>');
// Code blocks are rendered
expect(list.outerHTML).toContain('<code>mixedReadWrite</code>');
});
it('should render multiple {@link} blocks', () => {
const provideClientHydrationEntry = entries.get('provideClientHydration')!;
expect(provideClientHydrationEntry).toBeDefined();
const cardItem = provideClientHydrationEntry.querySelector('.docs-reference-card-item')!;
expect(cardItem.innerHTML).not.toContain('@link');
});
it('should create cross-links', () => {
const entry = entries.get('AfterRenderOptions')!;
expect(entry).toBeDefined();
// In the description
const descriptionItem = entry.querySelector('.docs-reference-description')!;
expect(descriptionItem.innerHTML).toContain('<a href="/api/core/afterRender">afterRender</a>');
// In the card
const cardItem = entry.querySelectorAll('.docs-reference-card-item')[1];
expect(cardItem.innerHTML).toContain(
'<a href="/api/core/AfterRenderPhase#MixedReadWrite">AfterRenderPhase.MixedReadWrite</a>',
);
});
});
| {
"end_byte": 3017,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/test/marked.spec.ts"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/test/cli.spec.ts_0_1406 | import {runfiles} from '@bazel/runfiles';
import {readFile} from 'fs/promises';
import {JSDOM} from 'jsdom';
import {renderEntry} from '../rendering';
import {getRenderable} from '../processing';
import {initHighlighter} from '../shiki/shiki';
import {configureMarkedGlobally} from '../marked/configuration';
describe('CLI docs to html', () => {
let fragment: DocumentFragment;
let entryJson: any;
beforeAll(async () => {
await initHighlighter();
await configureMarkedGlobally();
const entryContent = await readFile(runfiles.resolvePackageRelative('fake-cli-entries.json'), {
encoding: 'utf-8',
});
entryJson = JSON.parse(entryContent) as any;
const renderableJson = getRenderable(entryJson, '');
fragment = JSDOM.fragment(await renderEntry(renderableJson));
});
it('should subcommands correctly', async () => {
const generateComponentSubcommand = entryJson.subcommands.find(
(subcommand: any) => subcommand.name === 'component',
);
const renderableJson = getRenderable(generateComponentSubcommand, '');
fragment = JSDOM.fragment(await renderEntry(renderableJson));
const cliTocs = fragment.querySelectorAll('.docs-reference-cli-toc')!;
expect(cliTocs.length).toBe(2);
expect(cliTocs[0].textContent).toContain('ng component[name][options]');
expect(cliTocs[1].textContent).toContain('ng c[name][options]');
});
});
| {
"end_byte": 1406,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/test/cli.spec.ts"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/test/transforms/jsdoc-transforms.spec.ts_0_2998 | import {setCurrentSymbol, setSymbols} from '../../symbol-context';
import {addHtmlAdditionalLinks} from '../../transforms/jsdoc-transforms';
// @ts-ignore This compiles fine, but Webstorm doesn't like the ESM import in a CJS context.
describe('jsdoc transforms', () => {
it('should transform links', () => {
setCurrentSymbol('Router');
setSymbols(
new Map([
['Route', 'test'],
['Router', 'test'],
['Router.someMethod', 'test'],
['Router.someMethodWithParenthesis', 'test'],
['FormGroup', 'test'],
['FormGroup.someMethod', 'test'],
]),
);
const entry = addHtmlAdditionalLinks({
jsdocTags: [
{
name: 'see',
comment: '[Angular](https://angular.io)',
},
{
name: 'see',
comment: '[Angular](https://angular.io "Angular")',
},
{
name: 'see',
comment: '{@link Route}',
},
{
name: 'see',
comment: '{@link Route Something else}',
},
{
name: 'see',
comment: '{@link #someMethod}',
},
{
name: 'see',
comment: '{@link #someMethodWithParenthesis()}',
},
{
name: 'see',
comment: '{@link someMethod()}',
},
{
name: 'see',
comment: '{@link FormGroup.someMethod()}',
},
{
name: 'see',
comment: '{@link https://angular.dev/api/core/ApplicationRef}',
},
{
name: 'see',
comment: '{@link https://angular.dev}',
},
],
moduleName: 'test',
});
expect(entry.additionalLinks[0]).toEqual({
label: 'Angular',
url: 'https://angular.io',
title: undefined,
});
expect(entry.additionalLinks[1]).toEqual({
label: 'Angular',
url: 'https://angular.io',
title: 'Angular',
});
expect(entry.additionalLinks[2]).toEqual({
label: 'Route',
url: '/api/test/Route',
});
expect(entry.additionalLinks[3]).toEqual({
label: 'Something else',
url: '/api/test/Route',
});
expect(entry.additionalLinks[4]).toEqual({
label: 'someMethod',
url: '/api/test/Router#someMethod',
});
expect(entry.additionalLinks[5]).toEqual({
label: 'someMethodWithParenthesis()',
url: '/api/test/Router#someMethodWithParenthesis',
});
expect(entry.additionalLinks[6]).toEqual({
label: 'someMethod()',
url: '/api/test/Router#someMethod',
});
expect(entry.additionalLinks[7]).toEqual({
label: 'FormGroup.someMethod()',
url: '/api/test/FormGroup#someMethod',
});
expect(entry.additionalLinks[8]).toEqual({
label: 'ApplicationRef',
url: 'https://angular.dev/api/core/ApplicationRef',
});
expect(entry.additionalLinks[9]).toEqual({
label: 'angular.dev',
url: 'https://angular.dev',
});
});
});
| {
"end_byte": 2998,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/test/transforms/jsdoc-transforms.spec.ts"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/marked/renderer.ts_0_2009 | /*!
* @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, Tokens} from 'marked';
import {codeToHtml} from '../shiki/shiki';
/**
* 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<Renderer> = {
code({lang, text}): string {
const highlightResult = codeToHtml(text, lang)
// remove spaces/line-breaks between elements to not mess-up `pre` style
.replace(/>\s+</g, '><');
return `
<div class="docs-code" role="group">
<pre class="docs-mini-scroll-track">
${highlightResult}
</pre>
</div>
`;
},
image({href, title, text}): string {
return `
<img src="${href}" alt="${text}" title="${title}" class="docs-image">
`;
},
link(this: Renderer, {href, tokens}): string {
return `<a href="${href}">${this.parser.parseInline(tokens)}</a>`;
},
list(this: Renderer, {items, ordered, start}) {
if (ordered) {
return `
<ol class="docs-ordered-list">
${items.map((item) => this.listitem(item)).join('')}
</ol>
`;
}
return `
<ul class="docs-list">
${items.map((item) => this.listitem(item)).join('')}
</ul>
`;
},
table(this: Renderer, {header, rows}: Tokens.Table) {
return `
<div class="docs-table docs-scroll-track-transparent">
<table>
<thead>
${this.tablerow({
text: header.map((cell) => this.tablecell(cell)).join(''),
})}
</thead>
<tbody>
${rows
.map((row) =>
this.tablerow({
text: row.map((cell) => this.tablecell(cell)).join(''),
}),
)
.join('')}
</tbody>
</table>
</div>
`;
},
};
| {
"end_byte": 2009,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/marked/renderer.ts"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/marked/configuration.ts_0_221 | import {marked} from 'marked';
import {renderer} from './renderer';
/** Globally configures marked for rendering JsDoc content to HTML. */
export function configureMarkedGlobally() {
marked.use({
renderer,
});
}
| {
"end_byte": 221,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/marked/configuration.ts"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/transforms/decorator-transforms.ts_0_1136 | /*!
* @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 {DecoratorEntry} from '../entities';
import {DecoratorEntryRenderable} from '../entities/renderables';
import {addRenderableCodeToc} from './code-transforms';
import {
addHtmlAdditionalLinks,
addHtmlDescription,
addHtmlJsDocTagComments,
addHtmlUsageNotes,
setEntryFlags,
} from './jsdoc-transforms';
import {addRenderableMembers} from './member-transforms';
import {addModuleName} from './module-name';
/** Given an unprocessed class entry, get the fully renderable class entry. */
export function getDecoratorRenderable(
classEntry: DecoratorEntry,
moduleName: string,
): DecoratorEntryRenderable {
return setEntryFlags(
addRenderableCodeToc(
addRenderableMembers(
addHtmlAdditionalLinks(
addHtmlUsageNotes(
addHtmlJsDocTagComments(addHtmlDescription(addModuleName(classEntry, moduleName))),
),
),
),
),
) as DecoratorEntryRenderable;
}
| {
"end_byte": 1136,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/transforms/decorator-transforms.ts"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/transforms/initializer-api-functions-transform.ts_0_767 | import {InitializerApiFunctionEntry} from '../entities';
import {InitializerApiFunctionRenderable} from '../entities/renderables';
import {addRenderableCodeToc} from './code-transforms';
import {
addHtmlAdditionalLinks,
addHtmlDescription,
addHtmlJsDocTagComments,
addHtmlUsageNotes,
setEntryFlags,
} from './jsdoc-transforms';
import {addModuleName} from './module-name';
export function getInitializerApiFunctionRenderable(
entry: InitializerApiFunctionEntry,
moduleName: string,
): InitializerApiFunctionRenderable {
return setEntryFlags(
addRenderableCodeToc(
addHtmlJsDocTagComments(
addHtmlUsageNotes(
addHtmlDescription(addHtmlAdditionalLinks(addModuleName(entry, moduleName))),
),
),
),
);
}
| {
"end_byte": 767,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/transforms/initializer-api-functions-transform.ts"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/transforms/interface-transforms.ts_0_1106 | /*!
* @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 {InterfaceEntry} from '../entities';
import {InterfaceEntryRenderable} from '../entities/renderables';
import {addRenderableCodeToc} from './code-transforms';
import {
addHtmlAdditionalLinks,
addHtmlDescription,
addHtmlJsDocTagComments,
addHtmlUsageNotes,
setEntryFlags,
} from './jsdoc-transforms';
import {addRenderableMembers} from './member-transforms';
import {addModuleName} from './module-name';
/** Given an unprocessed interface entry, get the fully renderable interface entry. */
export function getInterfaceRenderable(
entry: InterfaceEntry,
moduleName: string,
): InterfaceEntryRenderable {
return setEntryFlags(
addRenderableCodeToc(
addRenderableMembers(
addHtmlAdditionalLinks(
addHtmlUsageNotes(
addHtmlJsDocTagComments(addHtmlDescription(addModuleName(entry, moduleName))),
),
),
),
),
);
}
| {
"end_byte": 1106,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/transforms/interface-transforms.ts"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/transforms/enum-transforms.ts_0_1074 | /*!
* @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 {EnumEntry} from '../entities';
import {EnumEntryRenderable} from '../entities/renderables';
import {addRenderableCodeToc} from './code-transforms';
import {
addHtmlAdditionalLinks,
addHtmlDescription,
addHtmlJsDocTagComments,
addHtmlUsageNotes,
setEntryFlags,
} from './jsdoc-transforms';
import {addRenderableMembers} from './member-transforms';
import {addModuleName} from './module-name';
/** Given an unprocessed enum entry, get the fully renderable enum entry. */
export function getEnumRenderable(classEntry: EnumEntry, moduleName: string): EnumEntryRenderable {
return setEntryFlags(
addRenderableCodeToc(
addRenderableMembers(
addHtmlAdditionalLinks(
addHtmlUsageNotes(
addHtmlJsDocTagComments(addHtmlDescription(addModuleName(classEntry, moduleName))),
),
),
),
),
);
}
| {
"end_byte": 1074,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/transforms/enum-transforms.ts"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/transforms/type-alias-transforms.ts_0_1021 | /*!
* @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 {TypeAliasEntry} from '../entities';
import {TypeAliasEntryRenderable} from '../entities/renderables';
import {addRenderableCodeToc} from './code-transforms';
import {
addHtmlAdditionalLinks,
addHtmlDescription,
addHtmlJsDocTagComments,
addHtmlUsageNotes,
setEntryFlags,
} from './jsdoc-transforms';
import {addModuleName} from './module-name';
/** Given an unprocessed type alias entry, get the fully renderable type alias entry. */
export function getTypeAliasRenderable(
typeAliasEntry: TypeAliasEntry,
moduleName: string,
): TypeAliasEntryRenderable {
return setEntryFlags(
addRenderableCodeToc(
addHtmlAdditionalLinks(
addHtmlUsageNotes(
addHtmlJsDocTagComments(addHtmlDescription(addModuleName(typeAliasEntry, moduleName))),
),
),
),
);
}
| {
"end_byte": 1021,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/transforms/type-alias-transforms.ts"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/transforms/url-transforms.ts_0_1119 | /*!
* @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 API_PREFIX = 'api';
export const MODULE_NAME_PREFIX = '@angular/';
export function getLinkToModule(moduleName: string, symbol: string, subSymbol?: string) {
return `/${API_PREFIX}/${moduleName}/${symbol}${subSymbol ? `#${subSymbol}` : ''}`;
}
export const normalizePath = (path: string): string => {
if (path[0] === '/') {
return path.substring(1);
}
return path;
};
export const normalizeTabUrl = (tabName: string): string => {
return tabName
.toLowerCase()
.replace(/<code>(.*?)<\/code>/g, '$1') // remove <code>
.replace(/<strong>(.*?)<\/strong>/g, '$1') // remove <strong>
.replace(/<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
};
| {
"end_byte": 1119,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/transforms/url-transforms.ts"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/transforms/params-transforms.ts_0_669 | /*!
* @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 {HasModuleName, HasParams, HasRenderableParams} from '../entities/traits';
import {addHtmlDescription} from './jsdoc-transforms';
import {addModuleName} from './module-name';
export function addRenderableFunctionParams<T extends HasParams & HasModuleName>(
entry: T,
): T & HasRenderableParams {
const params = entry.params.map((param) =>
addHtmlDescription(addModuleName(param, entry.moduleName)),
);
return {
...entry,
params,
};
}
| {
"end_byte": 669,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/transforms/params-transforms.ts"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/transforms/member-transforms.ts_0_2296 | /*!
* @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 {MemberEntry, MemberTags, MemberType} from '../entities';
import {HasMembers, HasModuleName, HasRenderableMembers} from '../entities/traits';
import {
addHtmlDescription,
addHtmlJsDocTagComments,
addHtmlUsageNotes,
setEntryFlags,
} from './jsdoc-transforms';
import {addModuleName} from './module-name';
const lifecycleMethods = [
'ngAfterContentChecked',
'ngAfterContentChecked',
'ngAfterContentInit',
'ngAfterViewChecked',
'ngAfterViewChecked',
'ngAfterViewInit',
'ngDoCheck',
'ngDoCheck',
'ngOnChanges',
'ngOnDestroy',
'ngOnInit',
];
/** Gets a list of members with Angular lifecycle methods removed. */
export function filterLifecycleMethods(members: MemberEntry[]): MemberEntry[] {
return members.filter((m) => !lifecycleMethods.includes(m.name));
}
/** Merges getter and setter entries with the same name into a single entry. */
export function mergeGettersAndSetters(members: MemberEntry[]): MemberEntry[] {
const getters = new Set<string>();
const setters = new Set<string>();
// Note all getter and setter names for the class.
for (const member of members) {
if (member.memberType === MemberType.Getter) getters.add(member.name);
if (member.memberType === MemberType.Setter) setters.add(member.name);
}
// Mark getter-only members as `readonly`.
for (const member of members) {
if (member.memberType === MemberType.Getter && !setters.has(member.name)) {
member.memberType = MemberType.Property;
member.memberTags.push(MemberTags.Readonly);
}
}
// Filter out setters that have a corresponding getter.
return members.filter(
(member) => member.memberType !== MemberType.Setter || !getters.has(member.name),
);
}
export function addRenderableMembers<T extends HasMembers & HasModuleName>(
entry: T,
): T & HasRenderableMembers {
const members = entry.members.map((member) =>
setEntryFlags(
addHtmlDescription(
addHtmlUsageNotes(addHtmlJsDocTagComments(addModuleName(member, entry.moduleName))),
),
),
);
return {
...entry,
members,
};
}
| {
"end_byte": 2296,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/transforms/member-transforms.ts"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/transforms/code-transforms.ts_0_8265 | /*!
* @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 {
DocEntry,
FunctionSignatureMetadata,
MemberEntry,
MemberTags,
ParameterEntry,
PropertyEntry,
} from '../entities';
import {
isClassEntry,
isClassMethodEntry,
isConstantEntry,
isDecoratorEntry,
isDeprecatedEntry,
isEnumEntry,
isFunctionEntry,
isGetterEntry,
isInitializerApiFunctionEntry,
isInterfaceEntry,
isSetterEntry,
isTypeAliasEntry,
} from '../entities/categorization';
import {CodeLineRenderable} from '../entities/renderables';
import {HasModuleName, HasRenderableToc} from '../entities/traits';
import {getModuleName} from '../symbol-context';
import {codeToHtml, replaceKeywordFromShikiHtml} from '../shiki/shiki';
import {filterLifecycleMethods, mergeGettersAndSetters} from './member-transforms';
import {getLinkToModule} from './url-transforms';
// Allows to generate links for code lines.
interface CodeTableOfContentsData {
// The contents of code block.
contents: string;
// The keys are code line numbers and the values are ids.
codeLineNumbersWithIdentifiers: Map<number, string>;
deprecatedLineNumbers: number[];
}
/** Split generated code with syntax highlighting into single lines */
export function splitLines(text: string): string[] {
if (text.length === 0) {
return [];
}
return text.split(/\r\n|\r|\n/g);
}
/**
* Based on provided docEntry:
* 1. Build metadata
* 2. Run syntax highlighting
* 3. Generate list of renderable code lines.
*/
export function addRenderableCodeToc<T extends DocEntry & HasModuleName>(
entry: T,
): T & HasRenderableToc {
const metadata = mapDocEntryToCode(entry);
appendPrefixAndSuffix(entry, metadata);
let codeWithSyntaxHighlighting = codeToHtml(metadata.contents, 'typescript', {
removeFunctionKeyword: true,
});
if (isDecoratorEntry(entry)) {
// Shiki requires a keyword for correct formating of Decorators
// We use an interface and then replace it with a '@'
codeWithSyntaxHighlighting = replaceKeywordFromShikiHtml(
'interface',
codeWithSyntaxHighlighting,
'@',
);
}
// shiki returns the lines wrapped by 2 node : 1 pre node, 1 code node.
// As leveraging jsdom isn't trivial here, we rely on a regex to extract the line nodes
const pattern = /(.*?)<code.*?>(.*?)<\/code>(.*)/s;
const match = codeWithSyntaxHighlighting.match(pattern);
if (!match) {
return {...entry, codeLinesGroups: new Map(), afterCodeGroups: '', beforeCodeGroups: ''};
}
const beforeCode = match[1];
const insideCode = match[2];
const afterCode = match[3];
// Note: Don't expect enum value in signatures to be linked correctly
// as skihi already splits them into separate span blocks.
// Only the enum itself will recieve a link
const codeWithLinks = addApiLinksToHtml(insideCode);
const lines = splitLines(codeWithLinks);
const groups = groupCodeLines(lines, metadata, entry);
return {
...entry,
codeLinesGroups: groups,
beforeCodeGroups: beforeCode,
afterCodeGroups: afterCode,
};
}
/** Group overloaded methods */
function groupCodeLines(lines: string[], metadata: CodeTableOfContentsData, entry: DocEntry) {
const hasSingleSignature = isFunctionEntry(entry) && entry.signatures.length === 1;
return lines.reduce((groups, line, index) => {
const tocItem: CodeLineRenderable = {
contents: line,
id: hasSingleSignature ? undefined : metadata.codeLineNumbersWithIdentifiers.get(index),
isDeprecated: metadata.deprecatedLineNumbers.some((lineNumber) => lineNumber === index),
};
if (tocItem.id !== undefined && groups.has(tocItem.id)) {
const group = groups.get(tocItem.id);
group?.push(tocItem);
} else {
groups.set(tocItem.id ?? index.toString(), [tocItem]);
}
return groups;
}, new Map<string, CodeLineRenderable[]>());
}
export function mapDocEntryToCode(entry: DocEntry): CodeTableOfContentsData {
const isDeprecated = isDeprecatedEntry(entry);
const deprecatedLineNumbers = isDeprecated ? [0] : [];
if (isClassEntry(entry)) {
const members = filterLifecycleMethods(mergeGettersAndSetters(entry.members));
return getCodeTocData(members, true, isDeprecated);
}
if (isDecoratorEntry(entry)) {
return getCodeTocData(entry.members, true, isDeprecated);
}
if (isConstantEntry(entry)) {
return {
contents: `const ${entry.name}: ${entry.type};`,
codeLineNumbersWithIdentifiers: new Map(),
deprecatedLineNumbers,
};
}
if (isEnumEntry(entry)) {
return getCodeTocData(entry.members, true, isDeprecated);
}
if (isInterfaceEntry(entry)) {
return getCodeTocData(mergeGettersAndSetters(entry.members), true, isDeprecated);
}
if (isFunctionEntry(entry)) {
const codeLineNumbersWithIdentifiers = new Map<number, string>();
const hasSingleSignature = entry.signatures.length === 1;
if (entry.signatures.length > 0) {
const initialMetadata: CodeTableOfContentsData = {
contents: '',
codeLineNumbersWithIdentifiers: new Map<number, string>(),
deprecatedLineNumbers,
};
return entry.signatures.reduce(
(acc: CodeTableOfContentsData, curr: FunctionSignatureMetadata, index: number) => {
const lineNumber = index;
acc.codeLineNumbersWithIdentifiers.set(lineNumber, `${curr.name}_${index}`);
acc.contents += getMethodCodeLine(curr, [], hasSingleSignature, true);
// We don't want to add line break after the last item
if (!hasSingleSignature && index < entry.signatures.length - 1) {
acc.contents += '\n';
}
if (isDeprecatedEntry(curr)) {
acc.deprecatedLineNumbers.push(lineNumber);
}
return acc;
},
initialMetadata,
);
}
return {
// It is important to add the function keyword as shiki will only highlight valid ts
contents: `function ${getMethodCodeLine(entry.implementation, [], true)}`,
codeLineNumbersWithIdentifiers,
deprecatedLineNumbers,
};
}
if (isInitializerApiFunctionEntry(entry)) {
const codeLineNumbersWithIdentifiers = new Map<number, string>();
const showTypesInSignaturePreview = !!entry.__docsMetadata__?.showTypesInSignaturePreview;
let lines: string[] = [];
for (const [index, callSignature] of entry.callFunction.signatures.entries()) {
lines.push(
printInitializerFunctionSignatureLine(
callSignature.name,
callSignature,
showTypesInSignaturePreview,
),
);
const id = `${callSignature.name}_${index}`;
codeLineNumbersWithIdentifiers.set(lines.length - 1, id);
}
if (Object.keys(entry.subFunctions).length > 0) {
lines.push('');
for (const [i, subFunction] of entry.subFunctions.entries()) {
for (const [index, subSignature] of subFunction.signatures.entries()) {
lines.push(
printInitializerFunctionSignatureLine(
`${entry.name}.${subFunction.name}`,
subSignature,
showTypesInSignaturePreview,
),
);
const id = `${entry.name}_${subFunction.name}_${index}`;
codeLineNumbersWithIdentifiers.set(lines.length - 1, id);
}
if (i < entry.subFunctions.length - 1) {
lines.push('');
}
}
}
return {
contents: lines.join('\n'),
codeLineNumbersWithIdentifiers,
deprecatedLineNumbers,
};
}
if (isTypeAliasEntry(entry)) {
const contents = `type ${entry.name} = ${entry.type}`;
if (isDeprecated) {
const numberOfLinesOfCode = getNumberOfLinesOfCode(contents);
for (let i = 0; i < numberOfLinesOfCode; i++) {
deprecatedLineNumbers.push(i);
}
}
return {
contents,
codeLineNumbersWithIdentifiers: new Map(),
deprecatedLineNumbers,
};
}
return {
contents: '',
codeLineNumbersWithIdentifiers: new Map(),
deprecatedLineNumbers,
};
}
/** Generate code ToC data for list of members. */ | {
"end_byte": 8265,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/transforms/code-transforms.ts"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/transforms/code-transforms.ts_8266_15800 | function getCodeTocData(
members: MemberEntry[],
hasPrefixLine: boolean,
isDeprecated: boolean,
): CodeTableOfContentsData {
const initialMetadata: CodeTableOfContentsData = {
contents: '',
codeLineNumbersWithIdentifiers: new Map<number, string>(),
deprecatedLineNumbers: isDeprecated ? [0] : [],
};
// In case when hasPrefixLine is true we should take it into account when we're generating
// `codeLineNumbersWithIdentifiers` below.
const skip = !!hasPrefixLine ? 1 : 0;
let lineNumber = skip;
return members.reduce((acc: CodeTableOfContentsData, curr: MemberEntry, index: number) => {
const setTocData = (entry: DocEntry | MemberEntry, content: string) => {
acc.contents += ` ${content.trim()}\n`;
acc.codeLineNumbersWithIdentifiers.set(lineNumber, entry.name);
if (isDeprecatedEntry(entry)) {
acc.deprecatedLineNumbers.push(lineNumber);
}
lineNumber++;
};
if (isClassMethodEntry(curr)) {
if (curr.signatures.length > 0) {
curr.signatures.forEach((signature) => {
setTocData(signature, getMethodCodeLine(signature, curr.memberTags));
});
} else {
setTocData(curr, getMethodCodeLine(curr.implementation, curr.memberTags));
}
} else {
setTocData(curr, getCodeLine(curr));
}
return acc;
}, initialMetadata);
}
function getCodeLine(member: MemberEntry): string {
if (isGetterEntry(member)) {
return getGetterCodeLine(member);
} else if (isSetterEntry(member)) {
return getSetterCodeLine(member);
}
return getPropertyCodeLine(member as PropertyEntry);
}
/** Map getter, setter and property entry to text */
function getPropertyCodeLine(member: PropertyEntry): string {
const isOptional = isOptionalMember(member);
const tags = getTags(member);
return `${tags.join(' ')} ${member.name}${markOptional(isOptional)}: ${member.type};`;
}
/** Map method entry to text */
function getMethodCodeLine(
member: FunctionSignatureMetadata,
memberTags: MemberTags[] = [],
displayParamsInNewLines: boolean = false,
isFunction: boolean = false,
): string {
displayParamsInNewLines &&= member.params.length > 0;
return `${isFunction ? 'function' : ''}${memberTags.join(' ')} ${member.name}(${displayParamsInNewLines ? '\n ' : ''}${member.params
.map((param) => mapParamEntry(param))
.join(`,${displayParamsInNewLines ? '\n ' : ' '}`)}${
displayParamsInNewLines ? '\n' : ''
}): ${member.returnType};`.trim();
}
function mapParamEntry(entry: ParameterEntry) {
return `${entry.isRestParam ? '...' : ''}${entry.name}${markOptional(entry.isOptional)}: ${
entry.type
}`;
}
function getGetterCodeLine(member: PropertyEntry): string {
const tags = getTags(member);
return `${tags.join(' ')} get ${member.name}(): ${member.type};`;
}
function getSetterCodeLine(member: PropertyEntry): string {
const tags = getTags(member);
return `${tags.join(' ')} set ${member.name}(value: ${member.type});`;
}
function markOptional(isOptional: boolean): string {
return isOptional ? '?' : '';
}
function isOptionalMember(member: PropertyEntry): boolean {
return member.memberTags.some((tag) => tag === 'optional');
}
function getTags(member: PropertyEntry): string[] {
return member.memberTags
.map((tag) => {
if (tag === 'input') {
return !member.inputAlias || member.name === member.inputAlias
? '@Input()'
: `@Input('${member.inputAlias}')`;
} else if (tag === 'output') {
return !member.outputAlias || member.name === member.outputAlias
? '@Output()'
: `@Output('${member.outputAlias}')`;
} else if (tag === 'optional') {
return '';
}
return tag;
})
.filter((tag) => !!tag);
}
function getNumberOfLinesOfCode(contents: string): number {
return contents.split('\n').length;
}
/** Prints an initializer function signature into a single line. */
export function printInitializerFunctionSignatureLine(
name: string,
signature: FunctionSignatureMetadata,
showTypesInSignaturePreview: boolean,
): string {
let res = name;
if (signature.generics.length > 0) {
res += '<';
for (let i = 0; i < signature.generics.length; i++) {
const generic = signature.generics[i];
res += generic.name;
if (generic.default !== undefined) {
res += ` = ${generic.default}`;
}
if (i < signature.generics.length - 1) {
res += ', ';
}
}
res += '>';
}
res += '(';
for (let i = 0; i < signature.params.length; i++) {
const param = signature.params[i];
if (param.isRestParam) {
res += '...';
}
res += `${param.name}${markOptional(param.isOptional)}`;
if (showTypesInSignaturePreview) {
res += `: ${param.type}`;
}
if (i < signature.params.length - 1) {
res += ', ';
}
}
res += ')';
if (showTypesInSignaturePreview) {
res += `: ${signature.returnType}`;
}
res += ';';
return `function ${res}`;
}
function appendPrefixAndSuffix(entry: DocEntry, codeTocData: CodeTableOfContentsData): void {
const appendFirstAndLastLines = (
data: CodeTableOfContentsData,
firstLine: string,
lastLine: string,
) => {
data.contents = `${firstLine}\n${data.contents}${lastLine}`;
};
if (isClassEntry(entry) || isInterfaceEntry(entry)) {
const generics =
entry.generics?.length > 0
? `<${entry.generics
.map((g) => (g.constraint ? `${g.name} extends ${g.constraint}` : g.name))
.join(', ')}>`
: '';
const extendsStr = entry.extends ? ` extends ${entry.extends}` : '';
// TODO: remove the ? when we distinguish Class & Decorator entries
const implementsStr =
entry.implements?.length > 0 ? ` implements ${entry.implements.join(' ,')}` : '';
const signature = `${entry.name}${generics}${extendsStr}${implementsStr}`;
if (isClassEntry(entry)) {
const abstractPrefix = entry.isAbstract ? 'abstract ' : '';
appendFirstAndLastLines(codeTocData, `${abstractPrefix}class ${signature} {`, `}`);
}
if (isInterfaceEntry(entry)) {
appendFirstAndLastLines(codeTocData, `interface ${signature} {`, `}`);
}
}
if (isEnumEntry(entry)) {
appendFirstAndLastLines(codeTocData, `enum ${entry.name} {`, `}`);
}
if (isDecoratorEntry(entry)) {
appendFirstAndLastLines(codeTocData, `interface ${entry.name} ({`, `})`);
}
}
/**
* Replaces any code block that isn't already wrapped by an anchor element
* by a link if the symbol is known
*/
export function addApiLinksToHtml(htmlString: string): string {
const result = htmlString.replace(
// This regex looks for span/code blocks not wrapped by an anchor block.
// Their content are then replaced with a link if the symbol is known
// The captured content ==> vvvvvvvv
/(?<!<a[^>]*>)(<(?:(?:span)|(?:code))[^>]*>\s*)([^<]*?)(\s*<\/(?:span|code)>)/g,
(type: string, span1: string, potentialSymbolName: string, span2: string) => {
let [symbol, subSymbol] = potentialSymbolName.split(/(?:#|\.)/) as [string, string?];
// mySymbol() => mySymbol
const symbolWithoutInvocation = symbol.replace(/\([^)]*\);?/g, '');
const moduleName = getModuleName(symbolWithoutInvocation)!;
if (moduleName) {
return `${span1}<a href="${getLinkToModule(moduleName, symbol, subSymbol)}">${potentialSymbolName}</a>${span2}`;
}
return type;
},
);
return result;
} | {
"end_byte": 15800,
"start_byte": 8266,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/transforms/code-transforms.ts"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/transforms/function-transforms.ts_0_1559 | /*!
* @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 {FunctionEntry, FunctionSignatureMetadata} from '../entities';
import {
FunctionEntryRenderable,
FunctionSignatureMetadataRenderable,
} from '../entities/renderables';
import {addRenderableCodeToc} from './code-transforms';
import {
addHtmlAdditionalLinks,
addHtmlDescription,
addHtmlJsDocTagComments,
addHtmlUsageNotes,
setEntryFlags,
} from './jsdoc-transforms';
import {addModuleName} from './module-name';
import {addRenderableFunctionParams} from './params-transforms';
/** Given an unprocessed function entry, get the fully renderable function entry. */
export function getFunctionRenderable(
entry: FunctionEntry,
moduleName: string,
): FunctionEntryRenderable {
return setEntryFlags(
addRenderableCodeToc(
addHtmlAdditionalLinks(
addHtmlUsageNotes(
setEntryFlags(
addHtmlJsDocTagComments(addHtmlDescription(addModuleName(entry, moduleName))),
),
),
),
),
);
}
export function getFunctionMetadataRenderable(
entry: FunctionSignatureMetadata,
moduleName: string = '',
): FunctionSignatureMetadataRenderable {
return addHtmlAdditionalLinks(
addRenderableFunctionParams(
addHtmlUsageNotes(
setEntryFlags(
addHtmlJsDocTagComments(addHtmlDescription(addModuleName(entry, moduleName))),
),
),
),
);
}
| {
"end_byte": 1559,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/transforms/function-transforms.ts"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/transforms/module-name.ts_0_387 | /*!
* @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 {HasModuleName} from '../entities/traits';
export function addModuleName<T>(entry: T, moduleName: string): T & HasModuleName {
return {
...entry,
moduleName,
};
}
| {
"end_byte": 387,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/transforms/module-name.ts"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/transforms/cli-transforms.ts_0_2066 | /*!
* @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 {CliCommand, CliOption} from '../cli-entities';
import {
CliCardRenderable,
CliCommandRenderable,
CliOptionRenderable,
} from '../entities/renderables';
/** Given an unprocessed CLI entry, get the fully renderable CLI entry. */
export function getCliRenderable(command: CliCommand): CliCommandRenderable {
return {
...command,
subcommands: command.subcommands?.map((sub) => getCliRenderable(sub)),
htmlDescription: marked.parse(command.longDescription ?? command.shortDescription) as string,
cards: getCliCardsRenderable(command),
argumentsLabel: getArgumentsLabel(command),
hasOptions: getOptions(command).length > 0,
};
}
export function getCliCardsRenderable(command: CliCommand): CliCardRenderable[] {
const cards: CliCardRenderable[] = [];
const args = getArgs(command);
const options = getOptions(command);
if (args.length > 0) {
cards.push({
type: 'Arguments',
items: getRenderableOptions(args),
});
}
if (options.length > 0) {
cards.push({
type: 'Options',
items: getRenderableOptions(options),
});
}
return cards;
}
function getRenderableOptions(items: CliOption[]): CliOptionRenderable[] {
return items.map((option) => ({
...option,
isDeprecated: option.deprecated,
description: marked.parse(option.description) as string,
}));
}
function getArgumentsLabel(command: CliCommand): string {
const args = getArgs(command);
if (args.length === 0) {
return '';
}
return command.command.replace(`${command.name} `, '');
}
function getArgs(command: CliCommand): CliOption[] {
return command.options.filter((options) => options.positional !== undefined);
}
function getOptions(command: CliCommand): CliOption[] {
return command.options.filter((option) => option.positional === undefined);
}
| {
"end_byte": 2066,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/transforms/cli-transforms.ts"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/transforms/jsdoc-transforms.ts_0_7246 | /*!
* @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 {JsDocTagEntry} from '../entities';
import {
getDeprecatedEntry,
isDeprecatedEntry,
isDeveloperPreview,
isExperimental,
} from '../entities/categorization';
import {LinkEntryRenderable} from '../entities/renderables';
import {
HasAdditionalLinks,
HasDeprecatedFlag,
HasDescription,
HasDeveloperPreviewFlag,
HasHtmlDescription,
HasHtmlUsageNotes,
HasJsDocTags,
HasModuleName,
HasRenderableJsDocTags,
hasExperimentalFlag,
} from '../entities/traits';
import {getLinkToModule} from './url-transforms';
import {addApiLinksToHtml} from './code-transforms';
import {getCurrentSymbol, getModuleName, logUnknownSymbol} from '../symbol-context';
export const JS_DOC_USAGE_NOTES_TAG = 'usageNotes';
export const JS_DOC_SEE_TAG = 'see';
export const JS_DOC_DESCRIPTION_TAG = 'description';
// Some links are written in the following format: {@link Route}
const jsDoclinkRegex = /\{\s*@link\s+([^}]+)\s*\}/;
const jsDoclinkRegexGlobal = new RegExp(jsDoclinkRegex.source, 'g');
/** Given an entity with a description, gets the entity augmented with an `htmlDescription`. */
export function addHtmlDescription<T extends HasDescription & HasModuleName>(
entry: T,
): T & HasHtmlDescription {
const firstParagraphRule = /(.*?)(?:\n\n|$)/s;
let jsDocDescription = '';
if ('jsdocTags' in entry) {
jsDocDescription =
(entry.jsdocTags as JsDocTagEntry[]).find((tag) => tag.name === JS_DOC_DESCRIPTION_TAG)
?.comment ?? '';
}
const description = !!entry.description ? entry.description : jsDocDescription;
const shortTextMatch = description.match(firstParagraphRule);
const htmlDescription = getHtmlForJsDocText(description, entry).trim();
const shortHtmlDescription = getHtmlForJsDocText(
shortTextMatch ? shortTextMatch[0] : '',
entry,
).trim();
return {
...entry,
htmlDescription,
shortHtmlDescription,
};
}
/**
* Given an entity with JsDoc tags, gets the entity with JsDocTagRenderable entries that
* have been augmented with an `htmlComment`.
*/
export function addHtmlJsDocTagComments<T extends HasJsDocTags & HasModuleName>(
entry: T,
): T & HasRenderableJsDocTags {
return {
...entry,
jsdocTags: entry.jsdocTags.map((tag) => ({
...tag,
htmlComment: getHtmlForJsDocText(tag.comment, entry),
})),
};
}
/** Given an entity with `See also` links. */
export function addHtmlAdditionalLinks<T extends HasJsDocTags & HasModuleName>(
entry: T,
): T & HasAdditionalLinks {
return {
...entry,
additionalLinks: getHtmlAdditionalLinks(entry),
};
}
export function addHtmlUsageNotes<T extends HasJsDocTags>(entry: T): T & HasHtmlUsageNotes {
const usageNotesTag = entry.jsdocTags.find((tag) => tag.name === JS_DOC_USAGE_NOTES_TAG);
const htmlUsageNotes = usageNotesTag
? (marked.parse(
convertJsDocExampleToHtmlExample(wrapExampleHtmlElementsWithCode(usageNotesTag.comment)),
) as string)
: '';
const transformedHtml = addApiLinksToHtml(htmlUsageNotes);
return {
...entry,
htmlUsageNotes: transformedHtml,
};
}
/** Given a markdown JsDoc text, gets the rendered HTML. */
function getHtmlForJsDocText<T extends HasModuleName>(text: string, entry: T): string {
const parsed = marked.parse(convertLinks(wrapExampleHtmlElementsWithCode(text))) as string;
return addApiLinksToHtml(parsed);
}
export function setEntryFlags<T extends HasJsDocTags & HasModuleName>(
entry: T,
): T & HasDeprecatedFlag & HasDeveloperPreviewFlag & hasExperimentalFlag {
const deprecationMessage = getDeprecatedEntry(entry);
return {
...entry,
isDeprecated: isDeprecatedEntry(entry),
deprecationMessage: deprecationMessage
? getHtmlForJsDocText(deprecationMessage, entry)
: deprecationMessage,
isDeveloperPreview: isDeveloperPreview(entry),
isExperimental: isExperimental(entry),
};
}
function getHtmlAdditionalLinks<T extends HasJsDocTags>(entry: T): LinkEntryRenderable[] {
const markdownLinkRule = /\[(.*?)\]\((.*?)(?: "(.*?)")?\)/;
const seeAlsoLinks = entry.jsdocTags
.filter((tag) => tag.name === JS_DOC_SEE_TAG)
.map((tag) => tag.comment)
.map((comment) => {
const markdownLinkMatch = comment.match(markdownLinkRule);
if (markdownLinkMatch) {
return {
label: markdownLinkMatch[1],
url: markdownLinkMatch[2],
title: markdownLinkMatch[3],
};
}
const linkMatch = comment.match(jsDoclinkRegex);
if (linkMatch) {
const link = linkMatch[1];
const {url, label} = parseAtLink(link);
return {label, url};
}
return undefined;
})
.filter((link): link is LinkEntryRenderable => !!link);
return seeAlsoLinks;
}
/**
* Some descriptions in the text contain HTML elements like `input` or `img`,
* we should wrap such elements using `code`.
* Otherwise DocViewer will try to render those elements.
*/
function wrapExampleHtmlElementsWithCode(text: string) {
return text
.replace(/'<input>'/g, `<code><input></code>`)
.replace(/'<img>'/g, `<code><img></code>`);
}
function convertJsDocExampleToHtmlExample(text: string): string {
const codeExampleAtRule = /{@example (\S+) region=(['"])([^'"]+)\2\s*}/g;
return text.replace(
codeExampleAtRule,
(_: string, path: string, separator: string, region: string) => {
return `<code-example path="${path}" region="${region}" />`;
},
);
}
/**
* Converts {@link } tags into html anchor elements
*/
function convertLinks(text: string) {
return text.replace(jsDoclinkRegexGlobal, (_, link) => {
const {label, url} = parseAtLink(link);
return `<a href="${url}"><code>${label}</code></a>`;
});
}
function parseAtLink(link: string): {label: string; url: string} {
// Because of microsoft/TypeScript/issues/59679
// getTextOfJSDocComment introduces an extra space between the symbol and a trailing ()
link = link.replace(/ \(\)$/, '');
let [rawSymbol, description] = link.split(/\s(.+)/);
if (rawSymbol.startsWith('#')) {
rawSymbol = rawSymbol.substring(1);
} else if (rawSymbol.startsWith('http://') || rawSymbol.startsWith('https://')) {
return {
url: rawSymbol,
label: rawSymbol.split('/').pop()!,
};
}
let [symbol, subSymbol] = rawSymbol.replace(/\(\)$/, '').split(/(?:#|\.)/);
let moduleName = getModuleName(symbol);
const label = description ?? rawSymbol;
const currentSymbol = getCurrentSymbol();
if (!moduleName) {
// 2nd attemp, try to get the module name in the context of the current symbol
moduleName = getModuleName(`${currentSymbol}.${symbol}`);
if (!moduleName || !currentSymbol) {
// TODO: remove the links that generate this error
// TODO: throw an error when there are no more warning generated
logUnknownSymbol(link, symbol);
return {label, url: '#'};
}
subSymbol = symbol;
symbol = currentSymbol;
}
return {label, url: getLinkToModule(moduleName, symbol, subSymbol)};
}
| {
"end_byte": 7246,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/transforms/jsdoc-transforms.ts"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/transforms/constant-transforms.ts_0_1004 | /*!
* @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 {ConstantEntry} from '../entities';
import {ConstantEntryRenderable} from '../entities/renderables';
import {addRenderableCodeToc} from './code-transforms';
import {
addHtmlAdditionalLinks,
addHtmlDescription,
addHtmlJsDocTagComments,
addHtmlUsageNotes,
setEntryFlags,
} from './jsdoc-transforms';
import {addModuleName} from './module-name';
/** Given an unprocessed constant entry, get the fully renderable constant entry. */
export function getConstantRenderable(
classEntry: ConstantEntry,
moduleName: string,
): ConstantEntryRenderable {
return setEntryFlags(
addRenderableCodeToc(
addHtmlAdditionalLinks(
addHtmlUsageNotes(
addHtmlJsDocTagComments(addHtmlDescription(addModuleName(classEntry, moduleName))),
),
),
),
);
}
| {
"end_byte": 1004,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/transforms/constant-transforms.ts"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/transforms/class-transforms.ts_0_1088 | /*!
* @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 {ClassEntry} from '../entities';
import {ClassEntryRenderable} from '../entities/renderables';
import {addRenderableCodeToc} from './code-transforms';
import {
addHtmlAdditionalLinks,
addHtmlDescription,
addHtmlJsDocTagComments,
addHtmlUsageNotes,
setEntryFlags,
} from './jsdoc-transforms';
import {addRenderableMembers} from './member-transforms';
import {addModuleName} from './module-name';
/** Given an unprocessed class entry, get the fully renderable class entry. */
export function getClassRenderable(
classEntry: ClassEntry,
moduleName: string,
): ClassEntryRenderable {
return setEntryFlags(
addRenderableCodeToc(
addRenderableMembers(
addHtmlAdditionalLinks(
addHtmlUsageNotes(
addHtmlJsDocTagComments(addHtmlDescription(addModuleName(classEntry, moduleName))),
),
),
),
),
);
}
| {
"end_byte": 1088,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/transforms/class-transforms.ts"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/styling/css-classes.ts_0_1180 | /**
* @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
*/
// TODO(jelbourn): all of these CSS classes should use the `docs-` prefix.
export const PARAM_KEYWORD_CLASS_NAME = 'docs-param-keyword';
export const PARAM_GROUP_CLASS_NAME = 'docs-param-group';
export const REFERENCE_HEADER = 'docs-reference-header';
export const REFERENCE_MEMBERS = 'docs-reference-members';
export const REFERENCE_DEPRECATED = 'docs-reference-deprecated';
export const REFERENCE_MEMBERS_CONTAINER = 'docs-reference-members-container';
export const REFERENCE_MEMBER_CARD = 'docs-reference-member-card';
export const REFERENCE_MEMBER_CARD_HEADER = 'docs-reference-card-header';
export const REFERENCE_MEMBER_CARD_BODY = 'docs-reference-card-body';
export const REFERENCE_MEMBER_CARD_ITEM = 'docs-reference-card-item';
export const HEADER_CLASS_NAME = 'docs-reference-header';
export const HEADER_ENTRY_CATEGORY = 'docs-reference-category';
export const HEADER_ENTRY_TITLE = 'docs-reference-title';
export const HEADER_ENTRY_LABEL = 'docs-api-item-label';
| {
"end_byte": 1180,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/styling/css-classes.ts"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/templates/cli-reference.tsx_0_2277 | /*!
* @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 { Fragment, h } from 'preact';
import { CliCommandRenderable } from '../entities/renderables';
import { REFERENCE_MEMBERS, REFERENCE_MEMBERS_CONTAINER } from '../styling/css-classes';
import { CliCard } from './cli-card';
import { HeaderCli } from './header-cli';
import { RawHtml } from './raw-html';
/** Component to render a CLI command reference document. */
export function CliCommandReference(entry: CliCommandRenderable) {
return (
<div className="cli">
<div className="docs-reference-cli-content">
<HeaderCli command={entry} />
{[entry.name, ...entry.aliases].map((command) =>
<div class="docs-code docs-reference-cli-toc">
<pre class="docs-mini-scroll-track">
<code>
<div className={'shiki line cli'}>
ng {commandName(entry, command)}
{entry.argumentsLabel ? <button member-id={'Arguments'} className="shiki-ln-line-argument">{entry.argumentsLabel}</button> : <></>}
{entry.hasOptions ? <button member-id={'Options'} className="shiki-ln-line-option">[options]</button> : <></>}
</div>
</code>
</pre>
</div>
)}
<RawHtml value={entry.htmlDescription}/>
{entry.subcommands && entry.subcommands?.length > 0 ? <>
<h3>Sub-commands</h3>
<p>This command has the following sub-commands</p>
<ul>
{entry.subcommands.map((subcommand) =>
<li>
<a href={`cli/${entry.name}/${subcommand.name}`}>{subcommand.name}</a>
</li>
)}
</ul>
</> : <></>}
</div>
<div className={REFERENCE_MEMBERS_CONTAINER}>
<div className={REFERENCE_MEMBERS}>
{entry.cards.map((card) => <CliCard card={card} />)}
</div>
</div>
</div>
);
}
function commandName(entry: CliCommandRenderable, command: string) {
if (entry.parentCommand?.name) {
return `${entry.parentCommand?.name} ${command}`;
} else {
return command;
}
} | {
"end_byte": 2277,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/templates/cli-reference.tsx"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/templates/header-cli.tsx_0_956 | /*!
* @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 {h} from 'preact';
import {CliCommandRenderable} from '../entities/renderables';
import {HEADER_CLASS_NAME, HEADER_ENTRY_CATEGORY, HEADER_ENTRY_LABEL, HEADER_ENTRY_TITLE} from '../styling/css-classes';
/** Component to render a header of the CLI page. */
export function HeaderCli(props: {command: CliCommandRenderable}) {
const command = props.command;
return (
<header className={HEADER_CLASS_NAME}>
<span className={HEADER_ENTRY_CATEGORY}>CLI</span>
<div className={HEADER_ENTRY_TITLE}>
<div>
<h1>{command.parentCommand?.name} {command.name}</h1>
<div className={HEADER_ENTRY_LABEL} data-mode={"full"} data-type={'command'}>{'Command'}</div>
</div>
</div>
</header>
);
}
| {
"end_byte": 956,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/templates/header-cli.tsx"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/templates/cli-card.tsx_0_1948 | /*!
* @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 {Fragment, h} from 'preact';
import {CliCardRenderable} from '../entities/renderables';
import {DeprecatedLabel} from './deprecated-label';
import { REFERENCE_MEMBER_CARD, REFERENCE_MEMBER_CARD_HEADER } from '../styling/css-classes';
export function CliCard(props: {card: CliCardRenderable}) {
return (
<div id={props.card.type} class={REFERENCE_MEMBER_CARD} tabIndex={-1}>
<header>
<div class={REFERENCE_MEMBER_CARD_HEADER}>
<h3>{props.card.type}</h3>
</div>
</header>
<div class="docs-reference-card-body">
{props.card.items.map((item) => (
<div class="docs-ref-content">
{item.deprecated ? <DeprecatedLabel entry={item} /> : <></>}
<div class="docs-ref-option-and-description">
<div class="docs-reference-option">
<code>{item.name}</code>
{item.aliases?.map((alias) => (
<div class="docs-reference-option-aliases">
<span>Alias</span>
<code>{alias} </code>
</div>
))}
</div>
<div dangerouslySetInnerHTML={{__html: item.description}}></div>
</div>
<div class="docs-reference-type-and-default">
<span>Value Type</span>
<code>{item.type}</code>
{/* Default Value */}
{item.default !== undefined ? <span>Default</span> : <></>}
{props.card.type === 'Options' && item.default !== undefined ? (
<code>{item.default.toString()}</code>
) : (
<></>
)}
</div>
</div>
))}
</div>
</div>
);
}
| {
"end_byte": 1948,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/templates/cli-card.tsx"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/templates/function-reference.tsx_0_2878 | /*!
* @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 {h} from 'preact';
import {FunctionEntryRenderable, FunctionSignatureMetadataRenderable} from '../entities/renderables';
import {
REFERENCE_MEMBERS,
REFERENCE_MEMBERS_CONTAINER,
REFERENCE_MEMBER_CARD,
REFERENCE_MEMBER_CARD_BODY,
REFERENCE_MEMBER_CARD_HEADER,
} from '../styling/css-classes';
import {ClassMethodInfo} from './class-method-info';
import {HeaderApi} from './header-api';
import {TabApi} from './tab-api';
import {TabDescription} from './tab-description';
import {TabUsageNotes} from './tab-usage-notes';
import {HighlightTypeScript} from './highlight-ts';
import {printInitializerFunctionSignatureLine} from '../transforms/code-transforms';
import {getFunctionMetadataRenderable} from '../transforms/function-transforms';
import {CodeSymbol} from './code-symbols';
export const signatureCard = (
name: string,
signature: FunctionSignatureMetadataRenderable,
opts: {id: string},
printSignaturesAsHeader: boolean,
) => {
return (
<div class={REFERENCE_MEMBER_CARD} id={opts.id} tabIndex={-1}>
<header>
{printSignaturesAsHeader ? (
<code>
<HighlightTypeScript
code={printInitializerFunctionSignatureLine(
name,
signature,
// Always omit types in signature headers, to keep them short.
true,
)}
removeFunctionKeyword={true}
/>
</code>
) : (
<div className={REFERENCE_MEMBER_CARD_HEADER}>
<h3>{name}</h3>
<div>
<CodeSymbol code={signature.returnType} />
</div>
</div>
)}
</header>
<div class={REFERENCE_MEMBER_CARD_BODY}>
<ClassMethodInfo entry={signature} />
</div>
</div>
);
};
/** Component to render a function API reference document. */
export function FunctionReference(entry: FunctionEntryRenderable) {
// Use signatures as header if there are multiple signatures.
const printSignaturesAsHeader = entry.signatures.length > 1;
return (
<div class="api">
<HeaderApi entry={entry} />
<TabApi entry={entry} />
<TabDescription entry={entry} />
<TabUsageNotes entry={entry} />
<div className={REFERENCE_MEMBERS_CONTAINER}>
<div className={REFERENCE_MEMBERS}>
{entry.signatures.map((s, i) =>
signatureCard(
s.name,
getFunctionMetadataRenderable(s, entry.moduleName),
{
id: `${s.name}_${i}`,
},
printSignaturesAsHeader,
),
)}
</div>
</div>
</div>
);
}
| {
"end_byte": 2878,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/templates/function-reference.tsx"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/templates/class-member-list.tsx_0_574 | /*!
* @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 {h} from 'preact';
import {MemberEntryRenderable} from '../entities/renderables';
import {ClassMember} from './class-member';
export function ClassMemberList(props: {members: MemberEntryRenderable[]}) {
return (
<div class="docs-reference-members">
{props.members.map((member) => (
<ClassMember member={member} />
))}
</div>
);
}
| {
"end_byte": 574,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/templates/class-member-list.tsx"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/templates/tab-usage-notes.tsx_0_799 | /*!
* @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 {Fragment, h} from 'preact';
import {DocEntryRenderable} from '../entities/renderables';
import {normalizeTabUrl} from '../transforms/url-transforms';
import {RawHtml} from './raw-html';
const USAGE_NOTES_TAB_NAME = 'Usage Notes';
/** Component to render the usage notes tab. */
export function TabUsageNotes(props: {entry: DocEntryRenderable}) {
if (!props.entry.htmlUsageNotes) {
return (<></>);
}
return (
<div data-tab={USAGE_NOTES_TAB_NAME} data-tab-url={normalizeTabUrl(USAGE_NOTES_TAB_NAME)}>
<RawHtml value={props.entry.htmlUsageNotes} />
</div>
);
}
| {
"end_byte": 799,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/templates/tab-usage-notes.tsx"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/templates/constant-reference.tsx_0_792 | /*!
* @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 {h} from 'preact';
import {ConstantEntryRenderable} from '../entities/renderables';
import {HeaderApi} from './header-api';
import {TabDescription} from './tab-description';
import {TabUsageNotes} from './tab-usage-notes';
import {TabApi} from './tab-api';
/** Component to render a constant API reference document. */
export function ConstantReference(entry: ConstantEntryRenderable) {
return (
<div class="api">
<HeaderApi entry={entry} />
<TabApi entry={entry} />
<TabDescription entry={entry} />
<TabUsageNotes entry={entry} />
</div>
);
}
| {
"end_byte": 792,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/templates/constant-reference.tsx"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/templates/class-reference.tsx_0_1154 | /*!
* @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 {Fragment, h} from 'preact';
import {ClassEntryRenderable, DecoratorEntryRenderable} from '../entities/renderables';
import {ClassMemberList} from './class-member-list';
import {HeaderApi} from './header-api';
import {REFERENCE_MEMBERS_CONTAINER} from '../styling/css-classes';
import {TabDescription} from './tab-description';
import {TabUsageNotes} from './tab-usage-notes';
import {TabApi} from './tab-api';
/** Component to render a class API reference document. */
export function ClassReference(entry: ClassEntryRenderable | DecoratorEntryRenderable) {
return (
<div class="api">
<HeaderApi entry={entry} />
<TabApi entry={entry} />
<TabDescription entry={entry} />
<TabUsageNotes entry={entry} />
{entry.members.length > 0 ? (
<div class={REFERENCE_MEMBERS_CONTAINER}>
<ClassMemberList members={entry.members} />
</div>
) : (
<></>
)}
</div>
);
}
| {
"end_byte": 1154,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/templates/class-reference.tsx"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/templates/code-line.tsx_0_1142 | /*!
* @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 {h} from 'preact';
import {CodeLineRenderable} from '../entities/renderables';
export function CodeLine(props: {line: CodeLineRenderable}) {
const line = props.line;
const className = `line ${line.isDeprecated ? `shiki-deprecated` : ''}`;
// extracting the line that is wrapped by shiki's <span class="line">
// The captured group is greedy to include all nested elements
const pattern = /<span[^>]*\bclass=["']line["'][^>]*>(.*)<\/span>/s;
const match = line.contents.match(pattern);
//
let highlightedContent = match ? match[1] : line.contents;
if (line.id) {
return (
<button
aria-describedby="jump-msg"
type="button"
className={className}
member-id={line.id}
dangerouslySetInnerHTML={{__html: highlightedContent}}
></button>
);
} else {
return <span class={className} dangerouslySetInnerHTML={{__html: highlightedContent}}></span>;
}
}
| {
"end_byte": 1142,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/templates/code-line.tsx"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/templates/highlight-ts.tsx_0_615 | /*!
* @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 {h} from 'preact';
import {RawHtml} from './raw-html';
import {codeToHtml} from '../shiki/shiki';
/** Component to render a header of the CLI page. */
export function HighlightTypeScript(props: {code: string; removeFunctionKeyword?: boolean}) {
const result = codeToHtml(props.code, 'typescript', {
removeFunctionKeyword: props.removeFunctionKeyword,
});
return <RawHtml value={result} />;
}
| {
"end_byte": 615,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/templates/highlight-ts.tsx"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/templates/code-symbols.tsx_0_948 | import {h} from 'preact';
import {getModuleName} from '../symbol-context';
import {getLinkToModule} from '../transforms/url-transforms';
const symbolRegex = /([a-zA-Z_$][a-zA-Z_$0-9\.]*)/;
/**
* Component that generates a code block with a link to a Symbol if it's known,
* else generates a string code block
*/
export function CodeSymbol(props: {code: string}) {
return (
<code>
{props.code.split(symbolRegex).map((rawSymbol, index) => {
// Every even index is a non-match when the regex has 1 capturing group
if (index % 2 === 0) return rawSymbol;
let [symbol, subSymbol] = rawSymbol.split('.'); // Also takes care of methods, enum value etc.
const moduleName = getModuleName(symbol);
if (moduleName) {
const url = getLinkToModule(moduleName, symbol, subSymbol);
return <a href={url}>{rawSymbol}</a>;
}
return rawSymbol;
})}
</code>
);
}
| {
"end_byte": 948,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/templates/code-symbols.tsx"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/templates/deprecated-label.tsx_0_968 | /*!
* @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 {Fragment, h} from 'preact';
import {PARAM_KEYWORD_CLASS_NAME} from '../styling/css-classes';
export function DeprecatedLabel(props: {
entry: {isDeprecated: boolean} | {deprecationMessage: string | null};
}) {
const entry = props.entry;
if ('deprecationMessage' in entry && entry.deprecationMessage !== null) {
return (
<div className={'docs-deprecation-message'}>
<span className={`${PARAM_KEYWORD_CLASS_NAME} docs-deprecated`}>@deprecated</span>
<span dangerouslySetInnerHTML={{__html: entry.deprecationMessage}}></span>
</div>
);
} else if ('isDeprecated' in entry && entry.isDeprecated) {
return <span className={`${PARAM_KEYWORD_CLASS_NAME} docs-deprecated`}>@deprecated</span>;
}
return <></>;
}
| {
"end_byte": 968,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/templates/deprecated-label.tsx"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/templates/header-api.tsx_0_3287 | /*!
* @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 {h} from 'preact';
import {EntryType, isDocEntryWithSourceInfo} from '../entities';
import {DocEntryRenderable} from '../entities/renderables';
import {
HEADER_CLASS_NAME,
HEADER_ENTRY_CATEGORY,
HEADER_ENTRY_LABEL,
HEADER_ENTRY_TITLE,
} from '../styling/css-classes';
import {DocsPillRow} from './docs-pill-row';
/** Component to render a header of the API page. */
export function HeaderApi(props: {entry: DocEntryRenderable; showFullDescription?: boolean}) {
const entry = props.entry;
// TODO: This link point to the main branch.
// When ADEV is not deployed on the main branch branch anymore,
// We should update it to point to the tag of the released version which ADEV runs on.
const sourceUrl = isDocEntryWithSourceInfo(entry)
? `https://github.com/angular/angular/blob/main${entry.source.filePath}#L${entry.source.startLine}-L${entry.source.endLine}`
: null;
return (
<header className={HEADER_CLASS_NAME}>
<span className={HEADER_ENTRY_CATEGORY}>{entry.moduleName}</span>
<div className={HEADER_ENTRY_TITLE}>
<div>
<h1>{entry.name}</h1>
<div
className={HEADER_ENTRY_LABEL}
data-mode={'full'}
data-type={entry.entryType.toLowerCase()}
>
{getEntryTypeDisplayName(entry.entryType)}
</div>
{entry.isDeprecated && (
<div className={HEADER_ENTRY_LABEL} data-mode={'full'} data-type="deprecated">
Deprecated
</div>
)}
{entry.isDeveloperPreview && (
<div className={HEADER_ENTRY_LABEL} data-mode={'full'} data-type="developer_preview">
<a href="/reference/releases#developer-preview">Developer preview</a>
</div>
)}
{entry.isExperimental && (
<div className={HEADER_ENTRY_LABEL} data-mode={'full'} data-type="experimental">
<a href="/reference/releases#experimental">Experimental</a>
</div>
)}
</div>
{sourceUrl && (
<a
class="docs-github-links"
target="_blank"
href={sourceUrl}
title="View source"
aria-label="View source"
>
<i role="presentation" aria-hidden="true" class="material-symbols-outlined">
code
</i>
</a>
)}
</div>
<section
className={'docs-reference-description'}
dangerouslySetInnerHTML={{
__html: props.showFullDescription ? entry.htmlDescription : entry.shortHtmlDescription,
}}
></section>
<DocsPillRow links={entry.additionalLinks} />
</header>
);
}
function getEntryTypeDisplayName(entryType: EntryType | string): string {
switch (entryType) {
case EntryType.NgModule:
return 'NgModule';
case EntryType.TypeAlias:
return 'Type Alias';
case EntryType.UndecoratedClass:
return 'Class';
case EntryType.InitializerApiFunction:
return 'Initializer API';
}
return entryType;
}
| {
"end_byte": 3287,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/templates/header-api.tsx"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/templates/initializer-api-function.tsx_0_2629 | /*!
* @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 {h, JSX} from 'preact';
import {InitializerApiFunctionRenderable} from '../entities/renderables';
import {HeaderApi} from './header-api';
import {TabApi} from './tab-api';
import {TabUsageNotes} from './tab-usage-notes';
import {REFERENCE_MEMBERS, REFERENCE_MEMBERS_CONTAINER} from '../styling/css-classes';
import {getFunctionMetadataRenderable} from '../transforms/function-transforms';
import {signatureCard} from './function-reference';
/** Component to render a constant API reference document. */
export function InitializerApiFunction(entry: InitializerApiFunctionRenderable) {
// Use signatures as header if there are multiple signatures.
const printSignaturesAsHeader =
entry.callFunction.signatures.length > 1 ||
entry.subFunctions.some((sub) => sub.signatures.length > 1);
// If the initializer API function is just a function, checked by existence of an
// implementation, and the descriptions of the "API" and the first function match,
// avoid rendering it another time in the member card.
if (
entry.callFunction.signatures.length === 1 &&
entry.callFunction.implementation !== null &&
entry.description === entry.callFunction.signatures[0].description
) {
entry.callFunction.signatures[0].description = '';
}
return (
<div class="api">
<HeaderApi entry={entry} showFullDescription={true} />
<TabApi entry={entry} />
<TabUsageNotes entry={entry} />
<div class={REFERENCE_MEMBERS_CONTAINER}>
<div class={REFERENCE_MEMBERS}>
{entry.callFunction.signatures.map((s, i) =>
signatureCard(
s.name,
getFunctionMetadataRenderable(s, entry.moduleName),
{
id: `${s.name}_${i}`,
},
printSignaturesAsHeader,
),
)}
{entry.subFunctions.reduce(
(elements, subFunction) => [
...elements,
...subFunction.signatures.map((s, i) =>
signatureCard(
`${entry.name}.${s.name}`,
getFunctionMetadataRenderable(s, entry.moduleName),
{
id: `${entry.name}_${s.name}_${i}`,
},
printSignaturesAsHeader,
),
),
],
[] as JSX.Element[],
)}
</div>
</div>
</div>
);
}
| {
"end_byte": 2629,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/templates/initializer-api-function.tsx"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/templates/class-member.tsx_0_2600 | /*!
* @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 {Fragment, h} from 'preact';
import {
isClassMethodEntry,
isGetterEntry,
isPropertyEntry,
isSetterEntry,
} from '../entities/categorization';
import {MemberEntryRenderable} from '../entities/renderables';
import {
REFERENCE_MEMBER_CARD,
REFERENCE_MEMBER_CARD_BODY,
REFERENCE_MEMBER_CARD_HEADER,
REFERENCE_MEMBER_CARD_ITEM,
} from '../styling/css-classes';
import {ClassMethodInfo} from './class-method-info';
import {DeprecatedLabel} from './deprecated-label';
import {RawHtml} from './raw-html';
import {getFunctionMetadataRenderable} from '../transforms/function-transforms';
import {CodeSymbol} from './code-symbols';
export function ClassMember(props: {member: MemberEntryRenderable}) {
const body = (
<div className={REFERENCE_MEMBER_CARD_BODY}>
{isClassMethodEntry(props.member) ? (
(props.member.signatures.length
? props.member.signatures
: [props.member.implementation]
).map((sig) => {
const renderableMember = getFunctionMetadataRenderable(sig);
return <ClassMethodInfo entry={renderableMember} options={{showUsageNotes: true}} />;
})
) : props.member.htmlDescription || props.member.deprecationMessage ? (
<div className={REFERENCE_MEMBER_CARD_ITEM}>
<DeprecatedLabel entry={props.member} />
<RawHtml value={props.member.htmlDescription} />
</div>
) : (
<></>
)}
</div>
);
const memberName = props.member.name;
const returnType = getMemberType(props.member);
return (
<div id={memberName} className={REFERENCE_MEMBER_CARD} tabIndex={-1}>
<header>
<div className={REFERENCE_MEMBER_CARD_HEADER}>
<h3>{memberName}</h3>
<div>
{isClassMethodEntry(props.member) && props.member.signatures.length > 1 ? (
<span>{props.member.signatures.length} overloads</span>
) : returnType ? (
<CodeSymbol code={returnType} />
) : (
<></>
)}
</div>
</div>
</header>
{body}
</div>
);
}
function getMemberType(entry: MemberEntryRenderable): string | null {
if (isClassMethodEntry(entry)) {
return entry.implementation.returnType;
} else if (isPropertyEntry(entry) || isGetterEntry(entry) || isSetterEntry(entry)) {
return entry.type;
}
return null;
}
| {
"end_byte": 2600,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/templates/class-member.tsx"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/templates/tab-api.tsx_0_835 | /*!
* @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 {h} from 'preact';
import {DocEntryRenderable} from '../entities/renderables';
import {HasRenderableToc} from '../entities/traits';
import {normalizeTabUrl} from '../transforms/url-transforms';
import {CodeTableOfContents} from './code-table-of-contents';
const API_TAB_NAME = 'API';
/** Component to render the API tab. */
export function TabApi(props: {entry: DocEntryRenderable & HasRenderableToc}) {
return (
<div data-tab={API_TAB_NAME} data-tab-url={normalizeTabUrl(API_TAB_NAME)}>
<div class={'docs-reference-api-tab'}>
<CodeTableOfContents entry={props.entry} />
</div>
</div>
);
}
| {
"end_byte": 835,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/templates/tab-api.tsx"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/templates/parameter.tsx_0_986 | /*!
* @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 {h} from 'preact';
import {ParameterEntryRenderable} from '../entities/renderables';
import {RawHtml} from './raw-html';
import {PARAM_GROUP_CLASS_NAME} from '../styling/css-classes';
import {CodeSymbol} from './code-symbols';
/** Component to render a function or method parameter reference doc fragment. */
export function Parameter(props: {param: ParameterEntryRenderable}) {
const param = props.param;
return (
<div className={PARAM_GROUP_CLASS_NAME}>
{/*TODO: isOptional, isRestParam*/}
<span class="docs-param-keyword">@param</span>
<span class="docs-param-name">{param.name}</span>
<CodeSymbol code={param.type} />
<RawHtml value={param.htmlDescription} className="docs-parameter-description" />
</div>
);
}
| {
"end_byte": 986,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/templates/parameter.tsx"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/templates/enum-reference.tsx_0_1195 | /*!
* @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 {h, Fragment} from 'preact';
import {EnumEntryRenderable, MemberEntryRenderable} from '../entities/renderables';
import {HeaderApi} from './header-api';
import {TabDescription} from './tab-description';
import {TabApi} from './tab-api';
import {REFERENCE_MEMBERS, REFERENCE_MEMBERS_CONTAINER} from '../styling/css-classes';
import {ClassMember} from './class-member';
/** Component to render a enum API reference document. */
export function EnumReference(entry: EnumEntryRenderable) {
return (
<div class="api">
<HeaderApi entry={entry} />
<TabApi entry={entry} />
<TabDescription entry={entry} />
{
entry.members.length > 0
? (
<div class={REFERENCE_MEMBERS_CONTAINER}>
<div class={REFERENCE_MEMBERS}>
{entry.members.map((member: MemberEntryRenderable) => (<ClassMember member={member}/>))}
</div>
</div>
)
: (<></>)
}
</div>
);
}
| {
"end_byte": 1195,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/templates/enum-reference.tsx"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/templates/type-alias-reference.tsx_0_797 | /*!
* @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 {h} from 'preact';
import {TypeAliasEntryRenderable} from '../entities/renderables';
import {HeaderApi} from './header-api';
import {TabDescription} from './tab-description';
import {TabUsageNotes} from './tab-usage-notes';
import {TabApi} from './tab-api';
/** Component to render a type alias API reference document. */
export function TypeAliasReference(entry: TypeAliasEntryRenderable) {
return (
<div class="api">
<HeaderApi entry={entry} />
<TabApi entry={entry} />
<TabDescription entry={entry} />
<TabUsageNotes entry={entry} />
</div>
);
}
| {
"end_byte": 797,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/templates/type-alias-reference.tsx"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/templates/docs-pill-row.tsx_0_707 | /*!
* @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 {Fragment, h} from 'preact';
import {LinkEntryRenderable} from '../entities/renderables';
/** Component to render a function or method parameter reference doc fragment. */
export function DocsPillRow(props: {links: LinkEntryRenderable[]}) {
if (props.links.length === 0) return <></>;
return (
<nav class="docs-pill-row">
{props.links.map((link) => (
<a class="docs-pill" href={link.url} title={link.title}>
{link.label}
</a>
))}
</nav>
);
}
| {
"end_byte": 707,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/templates/docs-pill-row.tsx"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/templates/code-table-of-contents.tsx_0_850 | /*!
* @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 {h} from 'preact';
import {renderToString} from 'preact-render-to-string';
import {CodeLineGroup} from './code-line-group';
import {HasRenderableToc} from '../entities/traits';
export function CodeTableOfContents(props: {entry: HasRenderableToc}) {
const html = `${props.entry.beforeCodeGroups}
<code>
${Array.from(props.entry.codeLinesGroups)
.map(([_, group]) => renderToString(<CodeLineGroup lines={group} />))
.join('')}
</code>
${props.entry.afterCodeGroups}`;
return (
<div class="docs-code">
<pre class="docs-mini-scroll-track" dangerouslySetInnerHTML={{__html: html}}></pre>
</div>
);
}
| {
"end_byte": 850,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/templates/code-table-of-contents.tsx"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/templates/tab-description.tsx_0_1346 | /*!
* @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 {Fragment, h} from 'preact';
import {DocEntryRenderable} from '../entities/renderables';
import {normalizeTabUrl} from '../transforms/url-transforms';
import {RawHtml} from './raw-html';
import {CodeSymbol} from './code-symbols';
const DESCRIPTION_TAB_NAME = 'Description';
/** Component to render the description tab. */
export function TabDescription(props: {entry: DocEntryRenderable}) {
const exportedBy = props.entry.jsdocTags.filter((t) => t.name === 'ngModule');
if (
(!props.entry.htmlDescription ||
props.entry.htmlDescription === props.entry.shortHtmlDescription) &&
!exportedBy.length
) {
return <></>;
}
return (
<div data-tab={DESCRIPTION_TAB_NAME} data-tab-url={normalizeTabUrl(DESCRIPTION_TAB_NAME)}>
<RawHtml value={props.entry.htmlDescription} />
{exportedBy.length ? (
<>
<hr />
<h2>Exported by</h2>
<ul>
{exportedBy.map((tag) => (
<li>
<CodeSymbol code={tag.comment} />
</li>
))}
</ul>
</>
) : (
<></>
)}
</div>
);
}
| {
"end_byte": 1346,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/templates/tab-description.tsx"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/templates/docs-reference.tsx_0_634 | /*!
* @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 {h} from 'preact';
import {DocEntryRenderable} from '../entities/renderables';
import {HeaderApi} from './header-api';
import {TabDescription} from './tab-description';
/** Component to render a block or element API reference document. */
export function DocsReference(entry: DocEntryRenderable) {
return (
<div class="api">
<HeaderApi entry={entry} />
<TabDescription entry={entry} />
</div>
);
}
| {
"end_byte": 634,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/templates/docs-reference.tsx"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/templates/raw-html.tsx_0_575 | /*!
* @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 {h} from 'preact';
/** Convenience component to render raw html */
export function RawHtml(props: {value: string, className?: string}) {
// Unfortunately, there does not seem to be a way to render the raw html
// into a text node without introducing a div.
return <div className={props.className} dangerouslySetInnerHTML={({__html: props.value})}></div>;
}
| {
"end_byte": 575,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/templates/raw-html.tsx"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/templates/class-method-info.tsx_0_1967 | /*!
* @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 {Fragment, h} from 'preact';
import {
FunctionEntryRenderable,
FunctionSignatureMetadataRenderable,
MethodEntryRenderable,
ParameterEntryRenderable,
} from '../entities/renderables';
import {PARAM_KEYWORD_CLASS_NAME, REFERENCE_MEMBER_CARD_ITEM} from '../styling/css-classes';
import {DeprecatedLabel} from './deprecated-label';
import {Parameter} from './parameter';
import {RawHtml} from './raw-html';
import {CodeSymbol} from './code-symbols';
/**
* Component to render the method-specific parts of a class's API reference.
*/
export function ClassMethodInfo(props: {
entry: FunctionSignatureMetadataRenderable;
options?: {
showUsageNotes?: boolean;
};
}) {
const entry = props.entry;
return (
<div
className={`${REFERENCE_MEMBER_CARD_ITEM} ${entry.isDeprecated ? 'docs-reference-card-item-deprecated' : ''}`}
>
<RawHtml value={entry.htmlDescription} className={'docs-function-definition'} />
{/* In case when method is overloaded we need to indicate which overload is deprecated */}
{entry.isDeprecated ? (
<div>
<DeprecatedLabel entry={entry} />
</div>
) : (
<></>
)}
{entry.params.map((param: ParameterEntryRenderable) => (
<Parameter param={param} />
))}
<div className={'docs-return-type'}>
<span className={PARAM_KEYWORD_CLASS_NAME}>@returns</span>
<CodeSymbol code={entry.returnType} />
</div>
{entry.htmlUsageNotes && props.options?.showUsageNotes ? (
<div className={'docs-usage-notes'}>
<span className={PARAM_KEYWORD_CLASS_NAME}>Usage notes</span>
<RawHtml value={entry.htmlUsageNotes} />
</div>
) : (
<></>
)}
</div>
);
}
| {
"end_byte": 1967,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/templates/class-method-info.tsx"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/templates/code-line-group.tsx_0_654 | /*!
* @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 {h} from 'preact';
import {CodeLineRenderable} from '../entities/renderables';
import {CodeLine} from './code-line';
export function CodeLineGroup(props: {lines: CodeLineRenderable[]}) {
if (props.lines.length > 1) {
return (<div class="shiki-ln-group">
{
props.lines.map(line =>
<CodeLine line={line} />
)
}
</div>);
} else {
return <CodeLine line={props.lines[0]} />;
}
}
| {
"end_byte": 654,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/templates/code-line-group.tsx"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/entities/traits.ts_0_2311 | import {JsDocTagEntry, MemberEntry, ParameterEntry} from '../entities';
import {
CodeLineRenderable,
JsDocTagRenderable,
LinkEntryRenderable,
MemberEntryRenderable,
ParameterEntryRenderable,
} from './renderables';
/** A doc entry that has jsdoc tags. */
export interface HasJsDocTags {
jsdocTags: JsDocTagEntry[];
}
export interface HasAdditionalLinks {
additionalLinks: LinkEntryRenderable[];
}
/** A doc entry that has jsdoc tags transformed for rendering. */
export interface HasRenderableJsDocTags {
jsdocTags: JsDocTagRenderable[];
}
/** A doc entry that has a description. */
export interface HasDescription {
description: string;
}
/** A doc entry that has a transformed html description. */
export interface HasHtmlDescription {
htmlDescription: string;
shortHtmlDescription: string;
}
/** A doc entry that has a usage notes. */
export interface HasUsageNotes {
usageNotes: string;
}
/** A doc entry that has a transformed html usage notes. */
export interface HasHtmlUsageNotes {
htmlUsageNotes: string;
}
/** A doc entry that has members transformed for rendering. */
export interface HasMembers {
members: MemberEntry[];
}
/** A doc entry that has members groups transformed for rendering. */
export interface HasRenderableMembersGroups {
membersGroups: Map<string, MemberEntryRenderable[]>;
}
/** A doc entry that has members transformed for rendering. */
export interface HasRenderableMembers {
members: MemberEntryRenderable[];
}
/** A doc entry that has an associated JS module name. */
export interface HasModuleName {
moduleName: string;
}
/** A doc entry that has ToC transformed for rendering. */
export interface HasRenderableToc {
beforeCodeGroups: string;
codeLinesGroups: Map<string, CodeLineRenderable[]>;
afterCodeGroups: string;
}
/** A doc entry that has params transformed for rendering. */
export interface HasParams {
params: ParameterEntry[];
}
/** A doc entry that has params for rendering. */
export interface HasRenderableParams {
params: ParameterEntryRenderable[];
}
export interface HasDeprecatedFlag {
isDeprecated: boolean;
deprecationMessage: string | null;
}
export interface HasDeveloperPreviewFlag {
isDeveloperPreview: boolean;
}
export interface hasExperimentalFlag {
isExperimental: boolean;
}
| {
"end_byte": 2311,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/entities/traits.ts"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/entities/categorization.ts_0_5735 | import {
ClassEntry,
ConstantEntry,
DecoratorEntry,
DocEntry,
EntryType,
EnumEntry,
FunctionEntry,
InitializerApiFunctionEntry,
InterfaceEntry,
MemberEntry,
MemberType,
MethodEntry,
PropertyEntry,
TypeAliasEntry,
} from '../entities';
import {CliCommand} from '../cli-entities';
import {
ClassEntryRenderable,
CliCommandRenderable,
ConstantEntryRenderable,
DecoratorEntryRenderable,
DocEntryRenderable,
EnumEntryRenderable,
FunctionEntryRenderable,
InitializerApiFunctionRenderable,
InterfaceEntryRenderable,
MemberEntryRenderable,
MethodEntryRenderable,
TypeAliasEntryRenderable,
} from './renderables';
import {HasJsDocTags} from './traits';
/** Gets whether the given entry represents a class */
export function isClassEntry(entry: DocEntryRenderable): entry is ClassEntryRenderable;
export function isClassEntry(entry: DocEntry): entry is ClassEntry;
export function isClassEntry(entry: DocEntry): entry is ClassEntry {
// TODO: add something like `statementType` to extraction so we don't have to check so many
// entry types here.
return (
entry.entryType === EntryType.UndecoratedClass ||
entry.entryType === EntryType.Component ||
entry.entryType === EntryType.Pipe ||
entry.entryType === EntryType.NgModule ||
entry.entryType === EntryType.Directive
);
}
export function isDecoratorEntry(entry: DocEntryRenderable): entry is DecoratorEntryRenderable;
export function isDecoratorEntry(entry: DocEntry): entry is DecoratorEntry;
export function isDecoratorEntry(entry: DocEntry): entry is DecoratorEntry {
return entry.entryType === EntryType.Decorator;
}
/** Gets whether the given entry represents a constant */
export function isConstantEntry(entry: DocEntryRenderable): entry is ConstantEntryRenderable;
export function isConstantEntry(entry: DocEntry): entry is ConstantEntry;
export function isConstantEntry(entry: DocEntry): entry is ConstantEntry {
return entry.entryType === EntryType.Constant;
}
/** Gets whether the given entry represents a type alias */
export function isTypeAliasEntry(entry: DocEntryRenderable): entry is TypeAliasEntryRenderable;
export function isTypeAliasEntry(entry: DocEntry): entry is TypeAliasEntry;
export function isTypeAliasEntry(entry: DocEntry): entry is TypeAliasEntry {
return entry.entryType === EntryType.TypeAlias;
}
/** Gets whether the given entry represents an enum */
export function isEnumEntry(entry: DocEntryRenderable): entry is EnumEntryRenderable;
export function isEnumEntry(entry: DocEntry): entry is EnumEntry;
export function isEnumEntry(entry: DocEntry): entry is EnumEntry {
return entry.entryType === EntryType.Enum;
}
/** Gets whether the given entry represents an interface. */
export function isInterfaceEntry(entry: DocEntryRenderable): entry is InterfaceEntryRenderable;
export function isInterfaceEntry(entry: DocEntry): entry is InterfaceEntry;
export function isInterfaceEntry(entry: DocEntry): entry is InterfaceEntry {
return entry.entryType === EntryType.Interface;
}
/** Gets whether the given member entry is a method entry. */
export function isClassMethodEntry(entry: MemberEntryRenderable): entry is MethodEntryRenderable;
export function isClassMethodEntry(entry: MemberEntry): entry is MethodEntry;
export function isClassMethodEntry(entry: MemberEntry): entry is MethodEntry {
return entry.memberType === MemberType.Method;
}
/** Gets whether the given entry represents a function */
export function isFunctionEntry(entry: DocEntryRenderable): entry is FunctionEntryRenderable;
export function isFunctionEntry(entry: DocEntry): entry is FunctionEntry;
export function isFunctionEntry(entry: DocEntry): entry is FunctionEntry {
return entry.entryType === EntryType.Function;
}
export function isInitializerApiFunctionEntry(
entry: DocEntryRenderable,
): entry is InitializerApiFunctionRenderable;
export function isInitializerApiFunctionEntry(
entry: DocEntry,
): entry is InitializerApiFunctionEntry;
export function isInitializerApiFunctionEntry(
entry: DocEntry,
): entry is InitializerApiFunctionEntry {
return entry.entryType === EntryType.InitializerApiFunction;
}
/** Gets whether the given entry represents a property */
export function isPropertyEntry(entry: MemberEntry): entry is PropertyEntry {
return entry.memberType === MemberType.Property;
}
/** Gets whether the given entry represents a getter */
export function isGetterEntry(entry: MemberEntry): entry is PropertyEntry {
return entry.memberType === MemberType.Getter;
}
/** Gets whether the given entry represents a setter */
export function isSetterEntry(entry: MemberEntry): entry is PropertyEntry {
return entry.memberType === MemberType.Setter;
}
/** Gets whether the given entry is deprecated. */
export function isDeprecatedEntry<T extends HasJsDocTags>(entry: T) {
return entry.jsdocTags.some((tag) => tag.name === 'deprecated');
}
export function getDeprecatedEntry<T extends HasJsDocTags>(entry: T) {
return entry.jsdocTags.find((tag) => tag.name === 'deprecated')?.comment ?? null;
}
/** Gets whether the given entry is developer preview. */
export function isDeveloperPreview<T extends HasJsDocTags>(entry: T) {
return entry.jsdocTags.some((tag) => tag.name === 'developerPreview');
}
/** Gets whether the given entry is is experimental. */
export function isExperimental<T extends HasJsDocTags>(entry: T) {
return entry.jsdocTags.some((tag) => tag.name === 'experimental');
}
/** Gets whether the given entry is a cli entry. */
export function isCliEntry(entry: unknown): entry is CliCommandRenderable;
export function isCliEntry(entry: unknown): entry is CliCommand {
return (entry as CliCommand).command !== undefined;
}
| {
"end_byte": 5735,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/entities/categorization.ts"
} |
angular/adev/shared-docs/pipeline/api-gen/rendering/entities/renderables.ts_0_4180 | /*!
* @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 {
ClassEntry,
ConstantEntry,
DecoratorEntry,
DocEntry,
EnumEntry,
FunctionEntry,
FunctionSignatureMetadata,
InitializerApiFunctionEntry,
JsDocTagEntry,
MemberEntry,
ParameterEntry,
TypeAliasEntry,
} from '../entities';
import {CliCommand, CliOption} from '../cli-entities';
import {HasRenderableToc} from './traits';
/** JsDoc tag info augmented with transformed content for rendering. */
export interface JsDocTagRenderable extends JsDocTagEntry {
htmlComment: string;
}
/** A documentation entry augmented with transformed content for rendering. */
export interface DocEntryRenderable extends DocEntry {
moduleName: string;
htmlDescription: string;
shortHtmlDescription: string;
jsdocTags: JsDocTagRenderable[];
additionalLinks: LinkEntryRenderable[];
htmlUsageNotes: string;
isDeprecated: boolean;
isDeveloperPreview: boolean;
isExperimental: boolean;
}
/** Documentation entity for a constant augmented transformed content for rendering. */
export type ConstantEntryRenderable = ConstantEntry &
DocEntryRenderable &
HasRenderableToc & {
codeLinesGroups: Map<string, CodeLineRenderable[]>;
};
/** Documentation entity for a type alias augmented transformed content for rendering. */
export type TypeAliasEntryRenderable = TypeAliasEntry & DocEntryRenderable & HasRenderableToc;
/** Documentation entity for a TypeScript class augmented transformed content for rendering. */
export type ClassEntryRenderable = ClassEntry &
DocEntryRenderable &
HasRenderableToc & {
members: MemberEntryRenderable[];
};
export type DecoratorEntryRenderable = DecoratorEntry &
DocEntryRenderable &
HasRenderableToc & {
members: MemberEntryRenderable[];
};
/** Documentation entity for a TypeScript enum augmented transformed content for rendering. */
export type EnumEntryRenderable = EnumEntry &
DocEntryRenderable &
HasRenderableToc & {
members: MemberEntryRenderable[];
};
/** Documentation entity for a TypeScript interface augmented transformed content for rendering. */
export type InterfaceEntryRenderable = ClassEntryRenderable;
export type FunctionEntryRenderable = FunctionEntry &
DocEntryRenderable &
HasRenderableToc & {
deprecationMessage: string | null;
};
export type FunctionSignatureMetadataRenderable = FunctionSignatureMetadata &
DocEntryRenderable & {
params: ParameterEntryRenderable[];
};
/** Sub-entry for a single class or enum member augmented with transformed content for rendering. */
export interface MemberEntryRenderable extends MemberEntry {
htmlDescription: string;
jsdocTags: JsDocTagRenderable[];
deprecationMessage: string | null;
htmlUsageNotes: string;
}
/** Sub-entry for a class method augmented transformed content for rendering. */
export type MethodEntryRenderable = MemberEntryRenderable &
FunctionEntryRenderable & {
params: ParameterEntryRenderable[];
};
/** Sub-entry for a single function parameter augmented transformed content for rendering. */
export interface ParameterEntryRenderable extends ParameterEntry {
htmlDescription: string;
}
export interface CodeLineRenderable {
contents: string;
isDeprecated: boolean;
id?: string;
}
export interface LinkEntryRenderable {
label: string;
url: string;
title?: string;
}
export type CliOptionRenderable = CliOption & {
isDeprecated: boolean;
};
export type CliCardItemRenderable = CliOptionRenderable;
export interface CliCardRenderable {
type: 'Options' | 'Arguments';
items: CliCardItemRenderable[];
}
/** A CLI command augmented with transformed content for rendering. */
export type CliCommandRenderable = CliCommand & {
htmlDescription: string;
cards: CliCardRenderable[];
argumentsLabel: string;
hasOptions: boolean;
subcommands?: CliCommandRenderable[];
};
export interface InitializerApiFunctionRenderable
extends Omit<InitializerApiFunctionEntry, 'jsdocTags'>,
DocEntryRenderable,
HasRenderableToc {}
| {
"end_byte": 4180,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/rendering/entities/renderables.ts"
} |
angular/adev/shared-docs/pipeline/api-gen/extraction/extract_api_to_json.bzl_0_4383 | load("@build_bazel_rules_nodejs//:providers.bzl", "run_node")
def _extract_api_to_json(ctx):
"""Implementation of the extract_api_to_json rule"""
# Define arguments that will be passed to the underlying nodejs program.
args = ctx.actions.args()
# Use a param file because we may have a large number of inputs.
args.set_param_file_format("multiline")
args.use_param_file("%s", use_always = True)
# Pass the module_name for the extracted APIs. This will be something like "@angular/core".
args.add(ctx.attr.module_name)
# Pass the module_label for the extracted APIs, This is something like core for "@angular/core".
args.add(ctx.attr.module_label)
# Pass the set of private modules that should not be included in the API reference.
args.add_joined(ctx.attr.private_modules, join_with = ",")
# Pass the entry_point for from which to extract public symbols.
args.add(ctx.file.entry_point)
# Pass the set of source files from which API reference data will be extracted.
args.add_joined(ctx.files.srcs, join_with = ",")
# Pass the name of the output JSON file.
json_output = ctx.outputs.output_name
args.add(json_output.path)
# Pass the import path map
# TODO: consider module_mappings_aspect to deal with path mappings instead of manually
# specifying them
# https://github.com/bazelbuild/rules_nodejs/blob/5.x/internal/linker/link_node_modules.bzl#L236
path_map = {}
for target, path in ctx.attr.import_map.items():
files = target.files.to_list()
if len(files) != 1:
fail("Expected a single file in import_map target %s" % target.label)
path_map[path] = files[0].path
args.add(json.encode(path_map))
# Pass the set of (optional) extra entries
args.add_joined(ctx.files.extra_entries, join_with = ",")
# Define an action that runs the nodejs_binary executable. This is
# the main thing that this rule does.
run_node(
ctx = ctx,
inputs = depset(ctx.files.srcs + ctx.files.extra_entries),
executable = "_extract_api_to_json",
outputs = [json_output],
arguments = [args],
)
# The return value describes what the rule is producing. In this case we need to specify
# the "DefaultInfo" with the output JSON files.
return [DefaultInfo(files = depset([json_output]))]
extract_api_to_json = rule(
# Point to the starlark function that will execute for this rule.
implementation = _extract_api_to_json,
doc = """Rule that extracts Angular API reference information from TypeScript
sources and write it to a JSON file""",
# The attributes that can be set to this rule.
attrs = {
"srcs": attr.label_list(
doc = """The source files for this rule. This must include one or more
TypeScript files.""",
allow_empty = False,
allow_files = True,
),
"output_name": attr.output(
doc = """Name of the JSON output file.""",
),
"entry_point": attr.label(
doc = """Source file entry-point from which to extract public symbols""",
mandatory = True,
allow_single_file = True,
),
"private_modules": attr.string_list(
doc = """List of private modules that should not be included in the API symbol linking""",
),
"import_map": attr.label_keyed_string_dict(
doc = """Map of import path to the index.ts file for that import""",
allow_files = True,
),
"module_name": attr.string(
doc = """JS Module name to be used for the extracted symbols""",
mandatory = True,
),
"module_label": attr.string(
doc = """Module label to be used for the extracted symbols. To be used as display name, for example in API docs""",
),
"extra_entries": attr.label_list(
doc = """JSON files that contain extra entries to append to the final collection.""",
allow_files = True,
),
# The executable for this rule (private).
"_extract_api_to_json": attr.label(
default = Label("//adev/shared-docs/pipeline/api-gen/extraction:extract_api_to_json"),
executable = True,
cfg = "exec",
),
},
)
| {
"end_byte": 4383,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/extraction/extract_api_to_json.bzl"
} |
angular/adev/shared-docs/pipeline/api-gen/extraction/BUILD.bazel_0_1795 | load("@angular//tools/esm-interop:index.bzl", "nodejs_binary")
load("@npm//@angular/build-tooling/bazel/esbuild:index.bzl", "esbuild")
load("@npm//@angular/build-tooling/bazel:defaults.bzl", "ts_library")
package(default_visibility = ["//adev/shared-docs/pipeline/api-gen:__subpackages__"])
esbuild(
name = "bin",
entry_point = ":index.ts",
external = [
"@angular/compiler-cli",
"typescript",
],
format = "esm",
output = "bin.mjs",
platform = "node",
target = "es2022",
deps = [
":extract_api_to_json_lib",
"@angular//packages/compiler-cli",
"@npm//typescript",
],
)
ts_library(
name = "extract_api_to_json_lib",
srcs = glob(["**/*.ts"]),
devmode_module = "commonjs",
tsconfig = "//adev:tsconfig.json",
deps = [
"@angular//packages/compiler",
"@angular//packages/compiler-cli",
"@npm//@bazel/runfiles",
"@npm//@types/node",
"@npm//typescript",
],
)
# Action binary for the api_gen bazel rule.
nodejs_binary(
name = "extract_api_to_json",
data = [
":bin",
"@angular//packages/compiler",
"@angular//packages/compiler-cli",
"@npm//typescript",
],
entry_point = "bin.mjs",
# Note: Using the linker here as we need it for ESM. The linker is not
# super reliably when running concurrently on Windows- but we have existing
# actions using the linker. An alternative would be to:
# - bundle the Angular compiler into a CommonJS bundle
# - use the patched resolution- but also patch the ESM imports (similar to how FW does it).
visibility = ["//visibility:public"],
)
# Expose the sources in the dev-infra NPM package.
filegroup(
name = "files",
srcs = glob(["**/*"]),
)
| {
"end_byte": 1795,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/extraction/BUILD.bazel"
} |
angular/adev/shared-docs/pipeline/api-gen/extraction/index.ts_0_3712 | import {readFileSync, writeFileSync} from 'fs';
import path from 'path';
// @ts-ignore This compiles fine, but Webstorm doesn't like the ESM import in a CJS context.
import {
NgtscProgram,
CompilerOptions,
createCompilerHost,
DocEntry,
EntryCollection,
InterfaceEntry,
ClassEntry,
} from '@angular/compiler-cli';
import ts from 'typescript';
function main() {
const [paramFilePath] = process.argv.slice(2);
const rawParamLines = readFileSync(paramFilePath, {encoding: 'utf8'}).split('\n');
const [
moduleName,
moduleLabel,
serializedPrivateModules,
entryPointExecRootRelativePath,
srcs,
outputFilenameExecRootRelativePath,
serializedPathMapWithExecRootRelativePaths,
extraEntriesSrcs,
] = rawParamLines;
const privateModules = new Set(serializedPrivateModules.split(','));
// The path map is a serialized JSON map of import path to index.ts file.
// For example, {'@angular/core': 'path/to/some/index.ts'}
const pathMap = JSON.parse(serializedPathMapWithExecRootRelativePaths) as Record<string, string>;
// The tsconfig expects the path map in the form of path -> array of actual locations.
// We also resolve the exec root relative paths to absolute paths to disambiguate.
const resolvedPathMap: {[key: string]: string[]} = {};
for (const [importPath, filePath] of Object.entries(pathMap)) {
resolvedPathMap[importPath] = [path.resolve(filePath)];
// In addition to the exact import path,
// also add wildcard mappings for subdirectories.
const importPathWithWildcard = path.join(importPath, '*');
resolvedPathMap[importPathWithWildcard] = [
path.join(path.resolve(path.dirname(filePath)), '*'),
];
}
const compilerOptions: CompilerOptions = {
paths: resolvedPathMap,
rootDir: '.',
skipLibCheck: true,
target: ts.ScriptTarget.ES2022,
moduleResolution: ts.ModuleResolutionKind.NodeNext,
experimentalDecorators: true,
};
const compilerHost = createCompilerHost({options: compilerOptions});
const program: NgtscProgram = new NgtscProgram(srcs.split(','), compilerOptions, compilerHost);
const extraEntries: DocEntry[] = (extraEntriesSrcs ?? '')
.split(',')
.filter((path) => !!path)
.reduce((result: DocEntry[], path) => {
return result.concat(JSON.parse(readFileSync(path, {encoding: 'utf8'})) as DocEntry[]);
}, []);
const apiDoc = program.getApiDocumentation(entryPointExecRootRelativePath, privateModules);
const extractedEntries = apiDoc.entries;
const combinedEntries = extractedEntries.concat(extraEntries);
const normalized = moduleName.replace('@', '').replace(/[\/]/g, '_');
const output = JSON.stringify({
moduleLabel: moduleLabel || moduleName,
moduleName: moduleName,
normalizedModuleName: normalized,
entries: combinedEntries,
symbols: [
// Symbols referenced, originating from other packages
...apiDoc.symbols.entries(),
// Exported symbols from the current package
...apiDoc.entries.map((entry) => [entry.name, moduleName]),
// Also doing it for every member of classes/interfaces
...apiDoc.entries.flatMap((entry) => [
[entry.name, moduleName],
...getEntriesFromMembers(entry).map((member) => [member, moduleName]),
]),
],
} as EntryCollection);
writeFileSync(outputFilenameExecRootRelativePath, output, {encoding: 'utf8'});
}
function getEntriesFromMembers(entry: DocEntry): string[] {
if (!hasMembers(entry)) {
return [];
}
return entry.members.map((member) => `${entry.name}.${member.name}`);
}
function hasMembers(entry: DocEntry): entry is InterfaceEntry | ClassEntry {
return 'members' in entry;
}
main();
| {
"end_byte": 3712,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/extraction/index.ts"
} |
angular/adev/shared-docs/pipeline/api-gen/extraction/test/fake-source.ts_0_450 | // @ts-ignore Intentionally nonexistent path for testing purposes.
import {Version} from '@angular/dummy-package';
/**
* I have a description with some `Code`.
*/
export class UserProfile {
/** The user's name */
name: string = 'Morgan';
}
// By using an implicit type coming from a path-mapped import,
// we test that the extractor can correctly resolve type information
// from other packages.
export const VERSION = new Version('789def');
| {
"end_byte": 450,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/extraction/test/fake-source.ts"
} |
angular/adev/shared-docs/pipeline/api-gen/extraction/test/BUILD.bazel_0_1247 | load("//adev/shared-docs/pipeline/api-gen/extraction:extract_api_to_json.bzl", "extract_api_to_json")
package(default_visibility = ["//adev/shared-docs/pipeline/api-gen:__subpackages__"])
extract_api_to_json(
name = "test",
srcs = [
"fake-source.ts",
"//adev/shared-docs/pipeline/api-gen/extraction/test/dummy-entry-point:dummy_package",
],
entry_point = "fake-source.ts",
import_map = {
"//adev/shared-docs/pipeline/api-gen/extraction/test/dummy-entry-point:index.ts": "@angular/dummy-package",
},
module_name = "@angular/core",
output_name = "api.json",
private_modules = [""],
)
extract_api_to_json(
name = "test_with_extra_entries",
srcs = [
"fake-source.ts",
"//adev/shared-docs/pipeline/api-gen/extraction/test/dummy-entry-point:dummy_package",
],
entry_point = "fake-source.ts",
extra_entries = [
"extra.json",
],
import_map = {
"//adev/shared-docs/pipeline/api-gen/extraction/test/dummy-entry-point:index.ts": "@angular/dummy-package",
},
module_name = "@angular/core",
output_name = "extra_api.json",
private_modules = [""],
)
filegroup(
name = "source_files",
srcs = ["fake-source.ts"],
)
| {
"end_byte": 1247,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/extraction/test/BUILD.bazel"
} |
angular/adev/shared-docs/pipeline/api-gen/extraction/test/dummy-entry-point/BUILD.bazel_0_153 | package(default_visibility = ["//adev/shared-docs/pipeline/api-gen:__subpackages__"])
filegroup(
name = "dummy_package",
srcs = ["index.ts"],
)
| {
"end_byte": 153,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/extraction/test/dummy-entry-point/BUILD.bazel"
} |
angular/adev/shared-docs/pipeline/api-gen/extraction/test/dummy-entry-point/index.ts_0_114 | export class Version {
constructor(public sha: string = '') {}
}
export const VERSION = new Version('123abc');
| {
"end_byte": 114,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/api-gen/extraction/test/dummy-entry-point/index.ts"
} |
angular/adev/shared-docs/pipeline/guides/state.ts_0_1398 | /*!
* @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
*/
const headerIds = new Map<string, number>();
export const getHeaderId = (heading: string): string => {
const numberOfHeaderOccurrencesInTheDocument = headerIds.get(heading) ?? 0;
headerIds.set(heading, numberOfHeaderOccurrencesInTheDocument + 1);
// extract the extended markdown heading id
// ex: ## MyHeading {# myId}
const match = heading.match(/{#([\w-]+)}/);
let extractedId: string;
if (match) {
extractedId = match[1];
} else {
extractedId = heading
.toLowerCase()
.replace(/<code>(.*?)<\/code>/g, '$1') // remove <code>
.replace(/<strong>(.*?)<\/strong>/g, '$1') // remove <strong>
.replace(/<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(/[^\p{L}\d\-]/gu, ''); // only keep letters, digits & dashes
}
const headerId = numberOfHeaderOccurrencesInTheDocument
? `${extractedId}-${numberOfHeaderOccurrencesInTheDocument}`
: extractedId;
return headerId;
};
export const resetHeaderIdsOfCurrentDocument = (): void => {
headerIds.clear();
};
| {
"end_byte": 1398,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/guides/state.ts"
} |
angular/adev/shared-docs/pipeline/guides/helpers.ts_0_586 | /*!
* @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
*/
/** Whether the link provided is external to the application. */
export function isExternalLink(href: string | undefined | null) {
return href?.startsWith('http') ?? false;
}
/** Provide the correct target for the anchor tag based on the link provided. */
export function anchorTarget(href: string | undefined | null) {
return isExternalLink(href) ? ` target="_blank"` : '';
}
| {
"end_byte": 586,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/guides/helpers.ts"
} |
angular/adev/shared-docs/pipeline/guides/parse.ts_0_2246 | /*!
* @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 {hooks} from './hooks';
import {Renderer} from './renderer';
import {docsAlertExtension} from './extensions/docs-alert';
import {docsCalloutExtension} from './extensions/docs-callout';
import {docsPillExtension} from './extensions/docs-pill/docs-pill';
import {docsPillRowExtension} from './extensions/docs-pill/docs-pill-row';
import {docsVideoExtension} from './extensions/docs-video';
import {docsWorkflowExtension} from './extensions/docs-workflow/docs-workflow';
import {docsStepExtension} from './extensions/docs-workflow/docs-step';
import {docsCardExtension} from './extensions/docs-card/docs-card';
import {docsCardContainerExtension} from './extensions/docs-card/docs-card-container';
import {docsDecorativeHeaderExtension} from './extensions/docs-decorative-header';
import {docsCodeBlockExtension} from './extensions/docs-code/docs-code-block';
import {docsCodeExtension} from './extensions/docs-code/docs-code';
import {docsCodeMultifileExtension} from './extensions/docs-code/docs-code-multifile';
import {ParserContext, setContext} from './utils';
import {walkTokens} from './walk-tokens';
export async function parseMarkdown(
markdownContent: string,
context: ParserContext,
): Promise<string> {
setContext(context);
marked.use({
hooks,
extensions: [
docsAlertExtension,
docsCalloutExtension,
docsPillExtension,
docsPillRowExtension,
docsVideoExtension,
docsWorkflowExtension,
docsStepExtension,
docsCardExtension,
docsCardContainerExtension,
docsDecorativeHeaderExtension,
docsCodeBlockExtension,
docsCodeExtension,
docsCodeMultifileExtension,
],
walkTokens,
// The async option causes marked to await walkTokens functions before parsing the tokens and returning an HTML string.
// We leverage this to allow us to use async libraries like mermaid and building stackblitz examples.
async: true,
});
return marked.parse(markdownContent, {renderer: new Renderer()});
}
| {
"end_byte": 2246,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/guides/parse.ts"
} |
angular/adev/shared-docs/pipeline/guides/utils.ts_0_1644 | /*!
* @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, readFileSync} from 'fs';
import {join} from 'path';
import {cwd} from 'process';
// TODO(josephperrott): Set edit content url based on the owner, repo and branch.
/** The base url for edting the a file in the repository. */
const GITHUB_EDIT_CONTENT_URL = 'https://github.com/angular/angular/edit/main';
/** Get the page title with edit button to modify the page source. */
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}/${context?.markdownFilePath}" title="Edit this page" aria-label="Edit this page">
<!-- Pencil -->
<docs-icon role="presentation">edit</docs-icon>
</a>
</div>`;
}
/** Configuration using environment for parser, providing context. */
export interface ParserContext {
markdownFilePath?: string;
}
let context: ParserContext = {};
export function setContext(envContext: Partial<ParserContext>) {
context = envContext;
}
/** The base directory of the workspace the script is running in. */
const WORKSPACE_DIR = cwd();
export function loadWorkspaceRelativeFile(filePath: string): string {
const fullFilePath = join(WORKSPACE_DIR, filePath);
if (!existsSync(fullFilePath)) {
throw Error(`Cannot find: ${filePath}`);
}
return readFileSync(fullFilePath, {encoding: 'utf-8'});
}
| {
"end_byte": 1644,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/guides/utils.ts"
} |
angular/adev/shared-docs/pipeline/guides/walk-tokens.ts_0_886 | import {Token} from 'marked';
import {DocsCodeToken} from './extensions/docs-code/docs-code';
/**
* Describe a HANDLE_MERMAID value which esbuild will use at build time to determine if the mermaid
* related code should be included in the bundle.
* THIS VALUE IS NOT AVAILABLE AT RUNTIME.
*/
export declare const HANDLE_MERMAID: boolean;
/** Type guard for if a provided token is the DocsCodeToken. */
function isDocsCodeToken(token: Token): token is DocsCodeToken {
return !!(token as DocsCodeToken).language;
}
/**
* Handle the provided token based on the token itself replacing its content/data in place
* as appropriate.
*/
export async function walkTokens(token: Token): Promise<void> {
if (!isDocsCodeToken(token) || token.language !== 'mermaid') {
return;
}
if (HANDLE_MERMAID) {
return (await import('./mermaid')).processMermaidCodeBlock(token);
}
}
| {
"end_byte": 886,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/guides/walk-tokens.ts"
} |
angular/adev/shared-docs/pipeline/guides/BUILD.bazel_0_853 | load("//tools:defaults.bzl", "ts_library")
ts_library(
name = "guides",
srcs = glob(
[
"**/*.ts",
],
exclude = ["index.ts"],
),
visibility = [
"//adev/shared-docs:__subpackages__",
],
deps = [
"@npm//@bazel/runfiles",
"@npm//@types/diff",
"@npm//@types/jsdom",
"@npm//@types/node",
"@npm//diff",
"@npm//emoji-regex",
"@npm//html-entities",
"@npm//jsdom",
"@npm//marked",
"@npm//mermaid",
"@npm//playwright-core",
"@npm//shiki",
],
)
ts_library(
name = "index",
srcs = [
"index.ts",
],
visibility = [
"//adev/shared-docs:__subpackages__",
],
deps = [
":guides",
"@npm//@types/node",
],
)
exports_files([
"index.ts",
])
| {
"end_byte": 853,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/guides/BUILD.bazel"
} |
angular/adev/shared-docs/pipeline/guides/renderer.ts_0_730 | import {Renderer as _Renderer} from 'marked';
import {linkRender} from './tranformations/link';
import {tableRender} from './tranformations/table';
import {listRender} from './tranformations/list';
import {imageRender} from './tranformations/image';
import {textRender} from './tranformations/text';
import {headingRender} from './tranformations/heading';
/**
* Custom renderer for marked that will be used to transform markdown files to HTML
* files that can be used in the Angular docs.
*/
export class Renderer extends _Renderer {
override link = linkRender;
override table = tableRender;
override list = listRender;
override image = imageRender;
override text = textRender;
override heading = headingRender;
}
| {
"end_byte": 730,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/guides/renderer.ts"
} |
angular/adev/shared-docs/pipeline/guides/index.ts_0_1399 | /*!
* @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, writeFileSync} from 'fs';
import path from 'path';
import {parseMarkdown} from './parse';
import {initHighlighter} from './extensions/docs-code/format/highlight';
async function main() {
const [paramFilePath] = process.argv.slice(2);
const rawParamLines = readFileSync(paramFilePath, {encoding: 'utf8'}).split('\n');
const [srcs, outputFilenameExecRootRelativePath] = rawParamLines;
// The highlighter needs to be setup asynchronously
// so we're doing it at the start of the pipeline
await initHighlighter();
for (const filePath of srcs.split(',')) {
if (!filePath.endsWith('.md')) {
throw new Error(`Input file "${filePath}" does not end in a ".md" file extension.`);
}
const markdownContent = readFileSync(filePath, {encoding: 'utf8'});
const htmlOutputContent = await parseMarkdown(markdownContent, {markdownFilePath: filePath});
// The expected file name structure is the [name of the file].md.html.
const htmlFileName = filePath + '.html';
const htmlOutputPath = path.join(outputFilenameExecRootRelativePath, htmlFileName);
writeFileSync(htmlOutputPath, htmlOutputContent, {encoding: 'utf8'});
}
}
main();
| {
"end_byte": 1399,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/guides/index.ts"
} |
angular/adev/shared-docs/pipeline/guides/index.d.ts_0_427 | // This definition file is a temporary workaround until the toolchain is able to read d.mts definition files
// TODO: delete this file when the toolchains supports .d.mts files
declare module 'shiki' {
function createHighlighter(params: {
themes: any[];
langs: string[];
cssVariablePrefix?: string;
defaultColor?: boolean;
}): unknown;
type HighlighterGeneric<BundledLangKeys, BundledThemeKeys> = any;
}
| {
"end_byte": 427,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/guides/index.d.ts"
} |
angular/adev/shared-docs/pipeline/guides/hooks.ts_0_627 | /*!
* @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 {MarkedExtension} from 'marked';
import {resetHeaderIdsOfCurrentDocument} from './state';
/**
* Custom hooks for marked that will be used to post-transform markdown files with parent styles for docs.
*/
export const hooks: MarkedExtension['hooks'] = {
preprocess(html: string): string {
resetHeaderIdsOfCurrentDocument();
return html;
},
postprocess(html: string): string {
return html;
},
};
| {
"end_byte": 627,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/guides/hooks.ts"
} |
angular/adev/shared-docs/pipeline/guides/extensions/docs-alert.ts_0_2053 | /*!
* @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 {RendererThis, Token, TokenizerThis, Tokens} from 'marked';
/** Enum of all available alert severities. */
export enum AlertSeverityLevel {
Note = 'NOTE',
Tip = 'TIP',
TODO = 'TODO',
QUESTION = 'QUESTION',
Summary = 'SUMMARY',
TLDR = 'TLDR',
CRITICAL = 'CRITICAL',
IMPORTANT = 'IMPORTANT',
HELPFUL = 'HELPFUL',
}
/** Token for docs-alerts */
interface DocsAlertToken extends Tokens.Generic {
type: 'docs-alert';
body: string;
severityLevel: string;
tokens: Token[];
}
interface DocsAlert {
alert: RegExpExecArray | null;
severityLevel: string;
}
export const docsAlertExtension = {
name: 'docs-alert',
level: 'block' as const,
tokenizer(this: TokenizerThis, src: string): DocsAlertToken | undefined {
let match: DocsAlert | undefined;
for (let level in AlertSeverityLevel) {
// Capture group 1: all alert text content after the severity level
const rule = new RegExp('^s*' + level + ': (.*?)\n(\n|$)', 's');
const possibleMatch = rule.exec(src);
if (possibleMatch?.[1]) {
match = {
severityLevel: level,
alert: possibleMatch,
};
}
}
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: RendererThis, token: DocsAlertToken) {
return `
<div class="docs-alert docs-alert-${token.severityLevel.toLowerCase()}">
${this.parser.parse(token.tokens)}
</div>
`;
},
};
| {
"end_byte": 2053,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/guides/extensions/docs-alert.ts"
} |
angular/adev/shared-docs/pipeline/guides/extensions/docs-callout.ts_0_2312 | /*!
* @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 {Tokens, Token, TokenizerThis, RendererThis} from 'marked';
/** Enum of all available callout severities. */
export enum CalloutSeverityLevel {
HELPFUL = 'HELPFUL',
IMPORTANT = 'IMPORTANT',
CRITICAL = 'CRITICAL',
}
/** Token for docs-callouts */
interface DocsCalloutToken extends Tokens.Generic {
type: 'docs-callout';
title: string;
titleTokens: Token[];
severityLevel: CalloutSeverityLevel;
body: string;
bodyTokens: 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' as const,
start(src: string) {
return src.match(/^\s*<docs-callout/m)?.index;
},
tokenizer(this: TokenizerThis, src: string) {
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: RendererThis, token: DocsCalloutToken) {
return `
<div class="docs-callout docs-callout-${token.severityLevel.toLowerCase()}">
<h3>${this.parser.parseInline(token.titleTokens)}</h3>
${this.parser.parse(token.bodyTokens)}
</div>
`;
},
};
| {
"end_byte": 2312,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/guides/extensions/docs-callout.ts"
} |
angular/adev/shared-docs/pipeline/guides/extensions/docs-video.ts_0_1856 | /*!
* @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 {Tokens, TokenizerThis, RendererThis} from 'marked';
interface DocsVideoToken extends 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' as const,
start(src: string) {
return src.match(/^\s*<docs-video/m)?.index;
},
tokenizer(this: 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 !== null) {
return {
type: 'docs-video',
raw: match[0],
src: src[1],
title: title?.[1],
};
}
}
return undefined;
},
renderer(this: RendererThis, token: DocsVideoToken) {
if (!token.src.startsWith(validYTUrlPrefix)) {
process.stdout.write(
`<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>
`;
},
};
| {
"end_byte": 1856,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/guides/extensions/docs-video.ts"
} |
angular/adev/shared-docs/pipeline/guides/extensions/docs-decorative-header.ts_0_2347 | /*!
* @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 {TokenizerThis, Tokens, RendererThis} from 'marked';
import {getPageTitle, loadWorkspaceRelativeFile} from '../utils';
interface DocsDecorativeHeaderToken extends 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' as const,
start(src: string) {
return src.match(/^\s*<docs-decorative-header\s*/m)?.index;
},
tokenizer(this: 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] : '',
body: body ?? '',
};
return token;
}
return undefined;
},
renderer(this: 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 = token.imgSrc ? loadWorkspaceRelativeFile(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>
`;
},
};
| {
"end_byte": 2347,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/guides/extensions/docs-decorative-header.ts"
} |
angular/adev/shared-docs/pipeline/guides/extensions/docs-workflow/docs-workflow.ts_0_1287 | /*!
* @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 {Token, Tokens, RendererThis, TokenizerThis} from 'marked';
interface DocsWorkflowToken extends Tokens.Generic {
type: 'docs-workflow';
steps: string;
tokens: 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' as const,
start(src: string) {
return src.match(/^\s*<docs-workflow/m)?.index;
},
tokenizer(this: 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: RendererThis, token: DocsWorkflowToken) {
return `
<ol class="docs-steps">
${this.parser.parse(token.tokens)}
</ol>
`;
},
};
| {
"end_byte": 1287,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/guides/extensions/docs-workflow/docs-workflow.ts"
} |
angular/adev/shared-docs/pipeline/guides/extensions/docs-workflow/docs-step.ts_0_1657 | /*!
* @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 {Token, Tokens, RendererThis, TokenizerThis} from 'marked';
import {formatHeading, headingRender} from '../../tranformations/heading';
interface DocsStepToken extends Tokens.Generic {
type: 'docs-step';
title: string;
body: string;
tokens: 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' as const,
start(src: string) {
return src.match(/^\s*<docs-step/m)?.index;
},
tokenizer(this: 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: RendererThis, token: DocsStepToken) {
return `
<li>
<span class="docs-step-number" aria-hidden="true"></span>
${formatHeading({text: token.title, depth: 3})}
${this.parser.parse(token.tokens)}
</li>
`;
},
};
| {
"end_byte": 1657,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/guides/extensions/docs-workflow/docs-step.ts"
} |
angular/adev/shared-docs/pipeline/guides/extensions/docs-card/docs-card-container.ts_0_1297 | /*!
* @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 {Tokens, Token, RendererThis, TokenizerThis} from 'marked';
interface DocsCardContainerToken extends Tokens.Generic {
type: 'docs-card-container';
cards: string;
tokens: Token[];
}
const cardContainerRule = /^<docs-card-container>(.*?)<\/docs-card-container>/s;
export const docsCardContainerExtension = {
name: 'docs-card-container',
level: 'block' as const,
start(src: string) {
return src.match(/^\s*<docs-card-container/m)?.index;
},
tokenizer(this: 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: RendererThis, token: DocsCardContainerToken) {
return `
<div class="docs-card-grid">
${this.parser.parse(token.tokens)}
</div>
`;
},
};
| {
"end_byte": 1297,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/guides/extensions/docs-card/docs-card-container.ts"
} |
angular/adev/shared-docs/pipeline/guides/extensions/docs-card/docs-card.ts_0_3592 | /*!
* @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 {Tokens, Token, RendererThis, TokenizerThis} from 'marked';
import {anchorTarget} from '../../helpers';
import {loadWorkspaceRelativeFile} from '../../utils';
interface DocsCardToken extends Tokens.Generic {
type: 'docs-card';
title: string;
body: string;
link?: string;
href?: string;
imgSrc?: string;
tokens: 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' as const,
start(src: string) {
return src.match(/^\s*<docs-card\s*/m)?.index;
},
tokenizer(this: 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: RendererThis, token: DocsCardToken) {
return token.imgSrc ? getCardWithSvgIllustration(this, token) : getStandardCard(this, token);
},
};
function getStandardCard(renderer: RendererThis, token: DocsCardToken) {
if (token.href) {
return `
<a href="${token.href}" ${anchorTarget(token.href)} class="docs-card">
<div>
<h3>${token.title}</h3>
${renderer.parser.parse(token.tokens)}
</div>
<span>${token.link ? token.link : 'Learn more'}</span>
</a>
`;
}
return `
<div class="docs-card">
<div>
<h3>${token.title}</h3>
${renderer.parser.parse(token.tokens)}
</div>
${token.link ? `<span>${token.link}</span>` : ''}
</div>
`;
}
function getCardWithSvgIllustration(renderer: 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 = loadWorkspaceRelativeFile(token.imgSrc!);
if (token.href) {
return `
<a href="${token.href}" ${anchorTarget(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>
`;
}
| {
"end_byte": 3592,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/guides/extensions/docs-card/docs-card.ts"
} |
angular/adev/shared-docs/pipeline/guides/extensions/docs-pill/docs-pill-row.ts_0_1312 | /*!
* @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 {Token, Tokens, RendererThis, TokenizerThis} from 'marked';
interface DocsPillRowToken extends Tokens.Generic {
type: 'docs-pill-row';
pills: string;
tokens: 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' as const,
start(src: string) {
return src.match(/^\s*<docs-pill-row/m)?.index;
},
tokenizer(this: 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: RendererThis, token: DocsPillRowToken) {
return `
<nav class="docs-pill-row">
${this.parser.parseInline(token.tokens)}
</nav>
`;
},
};
| {
"end_byte": 1312,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/guides/extensions/docs-pill/docs-pill-row.ts"
} |
angular/adev/shared-docs/pipeline/guides/extensions/docs-pill/docs-pill.ts_0_1689 | /*!
* @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 {Token, Tokens, RendererThis, TokenizerThis} from 'marked';
import {anchorTarget, isExternalLink} from '../../helpers';
interface DocsPillToken extends Tokens.Generic {
type: 'docs-pill';
title: string;
href: string;
tokens: 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' as const,
start(src: string) {
return src.indexOf('<docs-pill ');
},
tokenizer(this: 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: RendererThis, token: DocsPillToken) {
return `
<a class="docs-pill" href="${token.href}"${anchorTarget(token.href)}>
${this.parser.parseInline(token.tokens)}${
isExternalLink(token.href)
? '<docs-icon class="docs-icon-small">open_in_new</docs-icon>'
: ''
}
</a>
`;
},
};
| {
"end_byte": 1689,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/guides/extensions/docs-pill/docs-pill.ts"
} |
angular/adev/shared-docs/pipeline/guides/extensions/docs-code/docs-code.ts_0_2798 | /*!
* @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 {TokenizerThis, RendererThis} from 'marked';
import {CodeToken, formatCode} from './format/index';
import {FileType, removeEslintComments} from './sanitizers/eslint';
import {loadWorkspaceRelativeFile} from '../../utils';
/** Marked token for a custom docs element. */
export interface DocsCodeToken extends CodeToken {
type: 'docs-code';
}
// Capture group 1: all attributes on the opening tag
// Capture group 2: all content between the open and close tags
const singleFileCodeRule =
/^\s*<docs-code((?:\s+[\w-]+(?:="[^"]*"|='[^']*'|=[^\s>]*)?)*)\s*(?:\/>|>(.*?)<\/docs-code>)/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/;
export const docsCodeExtension = {
name: 'docs-code',
level: 'block' as const,
start(src: string) {
return src.match(/^<docs-code\s/)?.index;
},
tokenizer(this: TokenizerThis, src: string): DocsCodeToken | undefined {
const match = singleFileCodeRule.exec(src);
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 = loadWorkspaceRelativeFile(path[1]);
// Remove ESLint Comments
const fileType: FileType | undefined = path[1]?.split('.').pop() as FileType;
code = removeEslintComments(code, fileType);
}
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: RendererThis, token: DocsCodeToken) {
return formatCode(token);
},
};
| {
"end_byte": 2798,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/guides/extensions/docs-code/docs-code.ts"
} |
angular/adev/shared-docs/pipeline/guides/extensions/docs-code/docs-code-block.ts_0_1566 | /*!
* @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 {TokenizerThis, RendererThis} from 'marked';
import {CodeToken, formatCode} from './format/index';
export interface DocsCodeBlock extends CodeToken {
type: 'docs-code-block';
// Nested code
code: string;
// Code language
language: string | undefined;
}
// TODO: use regex for code implemented in the marked package: https://github.com/markedjs/marked/blob/4e6acc8b8517eafe0036a914f58b6f53d4b12ca6/src/rules.ts#L72C1-L73C1
/**
* Regex for discovering code blocks, notably this is more limited than
* standard discovery of this as it only allows for exactly 3 ticks rather
* than three or more.
*/
const tripleTickCodeRule = /^\s*`{3}(\S+)[\r\n]+(.*?)[\r\n]+`{3}/s;
export const docsCodeBlockExtension = {
name: 'docs-code-block',
level: 'block' as const,
start(src: string) {
return src.match(/^(```)\s/)?.index;
},
tokenizer(this: TokenizerThis, src: string): DocsCodeBlock | undefined {
const match = tripleTickCodeRule.exec(src);
if (match) {
const token: DocsCodeBlock = {
raw: match[0],
type: 'docs-code-block',
code: match[2],
language: match[1],
};
return token;
}
return undefined;
},
renderer(this: RendererThis, token: DocsCodeBlock) {
if (token.language === 'mermaid') {
return token.code;
}
return formatCode(token);
},
};
| {
"end_byte": 1566,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/guides/extensions/docs-code/docs-code-block.ts"
} |
angular/adev/shared-docs/pipeline/guides/extensions/docs-code/docs-code-multifile.ts_0_2287 | /*!
* @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 {Tokens, Token, TokenizerThis, RendererThis} from 'marked';
import {JSDOM} from 'jsdom';
/** Marked token for a multifile custom docs element. */
export interface DocsCodeMultifileToken extends 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: Token[];
// True if we should display preview
preview: boolean;
}
// 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 pathRule = /path="([^"]*)"/;
const previewRule = /preview/;
export const docsCodeMultifileExtension = {
name: 'docs-code-multifile',
level: 'block' as const,
start(src: string) {
return src.match(/^\s*<docs-code-multifile/)?.index;
},
tokenizer(this: 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: RendererThis, token: DocsCodeMultifileToken) {
const el = JSDOM.fragment(`
<div class="docs-code-multifile">
${this.parser.parse(token.paneTokens)}
</div>
`).firstElementChild!;
if (token.path) {
el.setAttribute('path', token.path);
}
if (token.preview) {
el.setAttribute('preview', `${token.preview}`);
}
return el.outerHTML;
},
};
| {
"end_byte": 2287,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/guides/extensions/docs-code/docs-code-multifile.ts"
} |
angular/adev/shared-docs/pipeline/guides/extensions/docs-code/regions/region-parser.ts_0_6114 | /*!
* @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
*/
// Region parsing is done within this pipeline to allow for retrieving a subset of a file
// by extracting only the portion of the file between the provided regionblock comments.
// This also allows for documentation to be included within the source code more easily
// in an extractable manner.
import * as blockC from './region-matchers/block-c';
import * as html from './region-matchers/html';
import * as inlineC from './region-matchers/inline-c';
import * as inlineCOnly from './region-matchers/inline-c-only';
import * as inlineHash from './region-matchers/inline-hash';
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}[];
}
type FileType =
| 'ts'
| 'js'
| 'mjs'
| 'es6'
| 'html'
| 'svg'
| 'css'
| 'conf'
| 'yaml'
| 'yml'
| 'sh'
| 'jade'
| 'pug'
| 'json'
| 'json.annotated';
/**
* 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, fileType: FileType) => {
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 = contents.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());
}
/** Remove last instance of the provided item from the array. */
function removeLast(array: string[], item: string): void {
const index = array.lastIndexOf(item);
array.splice(index, 1);
}
| {
"end_byte": 6114,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/guides/extensions/docs-code/regions/region-parser.ts"
} |
angular/adev/shared-docs/pipeline/guides/extensions/docs-code/regions/region-matchers/inline-hash.ts_0_565 | /*!
* @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}`;
| {
"end_byte": 565,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/guides/extensions/docs-code/regions/region-matchers/inline-hash.ts"
} |
angular/adev/shared-docs/pipeline/guides/extensions/docs-code/regions/region-matchers/html.ts_0_562 | /*!
* @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} -->`;
| {
"end_byte": 562,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/guides/extensions/docs-code/regions/region-matchers/html.ts"
} |
angular/adev/shared-docs/pipeline/guides/extensions/docs-code/regions/region-matchers/inline-c.ts_0_558 | /*!
* @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} */`;
| {
"end_byte": 558,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/guides/extensions/docs-code/regions/region-matchers/inline-c.ts"
} |
angular/adev/shared-docs/pipeline/guides/extensions/docs-code/regions/region-matchers/inline-c-only.ts_0_583 | /*!
* @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}`;
| {
"end_byte": 583,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/guides/extensions/docs-code/regions/region-matchers/inline-c-only.ts"
} |
angular/adev/shared-docs/pipeline/guides/extensions/docs-code/regions/region-matchers/block-c.ts_0_605 | /*!
* @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} */`;
| {
"end_byte": 605,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/guides/extensions/docs-code/regions/region-matchers/block-c.ts"
} |
angular/adev/shared-docs/pipeline/guides/extensions/docs-code/sanitizers/eslint.ts_0_1845 | /*!
* @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';
/**
* Remove any ESLint comments from the provided code string. This is particularly useful as we may
* want to store code formatted for an example that would not be allowed in our repo. For instance,
* we can disable ESLint to allow for a `console` usage, despite not allowing it typically, so that
* it can be used in an example in documenation.
*/
export function removeEslintComments(input: string, fileType: FileType) {
if (!input || (fileType !== 'ts' && fileType !== 'js' && fileType !== 'html')) {
return input;
}
return input.replace(regexesForFileTypes[fileType], '');
}
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,
};
| {
"end_byte": 1845,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/guides/extensions/docs-code/sanitizers/eslint.ts"
} |
angular/adev/shared-docs/pipeline/guides/extensions/docs-code/format/highlight.ts_0_3845 | import {decode} from 'html-entities';
import {CodeToken} from './index';
import {expandRangeStringValues} from './range';
import {JSDOM} from 'jsdom';
import {createHighlighter, HighlighterGeneric} from 'shiki';
const lineNumberClassName: string = 'shiki-ln-number';
const lineAddedClassName: string = 'add';
const lineRemovedClassName: string = 'remove';
const lineHighlightedClassName: string = 'highlighted';
let highlighter: HighlighterGeneric<any, any>;
/**
* Highlighter needs to setup asynchronously
*
* This is intended to be invoked at the start of the pipeline
*/
export async function initHighlighter() {
highlighter = await createHighlighter({
themes: ['github-light', 'github-dark'],
langs: [
'javascript',
'typescript',
'angular-html',
'angular-ts',
'shell',
'html',
'http',
'json',
'nginx',
'markdown',
'apache',
],
});
}
/**
* Updates the provided token's code value to include syntax highlighting.
*/
export function highlightCode(token: CodeToken) {
// TODO(josephperrott): Handle mermaid usages i.e. language == mermaidClassName
if (token.language !== 'none' && token.language !== 'file') {
// Decode the code content to replace HTML entities to characters
const decodedCode = decode(token.code);
const fallbackLanguage = token.path?.endsWith('html') ? 'angular-html' : 'angular-ts';
const value = highlighter.codeToHtml(decodedCode, {
// we chose ts a fallback language as most example are ts.
// Idealy all examples should have a specified language
lang: token.language ?? fallbackLanguage,
themes: {
light: 'github-light',
dark: 'github-dark',
},
cssVariablePrefix: '--shiki-',
defaultColor: false,
});
token.code = value;
}
const dom = new JSDOM(token.code);
const document = dom.window.document;
const lines = document.body.querySelectorAll('.line');
// removing whitespaces text nodes so we don't have spaces between codelines
removeWhitespaceNodes(document.body.querySelector('.shiki > code'));
const linesCount = lines.length;
if (linesCount === 0) {
return;
}
let lineIndex = 0;
let resultFileLineIndex = 1;
const highlightedLineRanges = token.highlight ? expandRangeStringValues(token.highlight) : [];
do {
const isRemovedLine = token.diffMetadata?.linesRemoved.includes(lineIndex);
const isAddedLine = token.diffMetadata?.linesAdded.includes(lineIndex);
const isHighlighted = highlightedLineRanges.includes(lineIndex);
const addClasses = (el: Element) => {
if (isRemovedLine) {
el.classList.add(lineRemovedClassName);
}
if (isAddedLine) {
el.classList.add(lineAddedClassName);
}
if (isHighlighted) {
el.classList.add(lineHighlightedClassName);
}
};
const currentline = lines[lineIndex];
addClasses(currentline);
if (!!token.linenums) {
const lineNumberEl = JSDOM.fragment(
`<span role="presentation" class="${lineNumberClassName}"></span>`,
).firstElementChild!;
addClasses(lineNumberEl);
lineNumberEl.textContent = isRemovedLine ? '-' : isAddedLine ? '+' : `${resultFileLineIndex}`;
currentline.parentElement!.insertBefore(lineNumberEl, currentline);
resultFileLineIndex++;
}
lineIndex++;
} while (lineIndex < linesCount);
token.code = document.body.innerHTML;
}
/**
*
* Removed whitespaces between 1st level children
*/
function removeWhitespaceNodes(parent: Element | null) {
if (!parent) {
return;
}
const childNodes = parent.childNodes;
for (let i = childNodes.length - 1; i >= 0; i--) {
const node = childNodes[i];
if (node.nodeType === 3 && !/\S/.test(node.nodeValue!)) {
parent.removeChild(node);
}
}
}
| {
"end_byte": 3845,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/guides/extensions/docs-code/format/highlight.ts"
} |
angular/adev/shared-docs/pipeline/guides/extensions/docs-code/format/diff.ts_0_1352 | import {diffLines, Change as DiffChange} from 'diff';
import {CodeToken} from './index';
import {loadWorkspaceRelativeFile} from '../../../utils';
export interface DiffMetadata {
code: string;
linesAdded: number[];
linesRemoved: number[];
}
/**
* Updates the provided token with diff information if a path to a diff is provided.
*/
export function calculateDiff(token: CodeToken) {
if (!token.diff) {
return;
}
const diffCode = loadWorkspaceRelativeFile(token.diff);
const change = diffLines(diffCode, token.code);
const getLinesRange = (start: number, count: number): number[] =>
Array.from(Array(count).keys()).map((i) => i + start);
let processedLines = 0;
token.diffMetadata = change.reduce(
(prev: DiffMetadata, part: DiffChange) => {
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: [],
},
);
token.code = token.diffMetadata.code;
}
| {
"end_byte": 1352,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/guides/extensions/docs-code/format/diff.ts"
} |
angular/adev/shared-docs/pipeline/guides/extensions/docs-code/format/range.ts_0_1326 | /**
* Expand a provided set of range values into a singel array of all values in the range.
*
* For example, [[1,3], [12-13]] is expanded to [1,2,3,12,13].
*/
export function expandRangeStringValues(rangeString: string | undefined): number[] {
if (rangeString === undefined) {
return [];
}
const getAllValuesFromRange = (range: any[]) => {
const [start, end] = range;
for (let i = start; i <= end; i++) {
result.push(i - 1);
}
};
let result: number[] = [];
try {
const boundaryValueArray = JSON.parse(rangeString) as any;
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 [];
}
}
| {
"end_byte": 1326,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/guides/extensions/docs-code/format/range.ts"
} |
angular/adev/shared-docs/pipeline/guides/extensions/docs-code/format/region.ts_0_930 | import {CodeToken} from './index';
import {regionParser} from '../regions/region-parser';
import {FileType} from '../sanitizers/eslint';
/**
* Updates the provided token to include the extracted region as the visible lines for the token.
*/
export function extractRegions(token: CodeToken) {
const fileType: FileType | undefined = token.path?.split('.').pop() as FileType;
const parsedRegions = regionParser(token.code, fileType);
// The code in the token is always replaced with the version of the code with region markers removed.
token.code = parsedRegions.contents;
if (token.visibleRegion) {
const region = parsedRegions.regionMap[token.visibleRegion];
if (!region) {
throw new Error(`Cannot find ${token.visibleRegion} in ${token.path}!`);
}
token.visibleLines = `[${region.ranges.map(
(range) => `[${range.from}, ${range.to ?? parsedRegions.totalLinesCount + 1}]`,
)}]`;
}
}
| {
"end_byte": 930,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/guides/extensions/docs-code/format/region.ts"
} |
angular/adev/shared-docs/pipeline/guides/extensions/docs-code/format/index.ts_0_2651 | import {Tokens} from 'marked';
import {DiffMetadata, calculateDiff} from './diff';
import {highlightCode} from './highlight';
import {extractRegions} from './region';
import {JSDOM} from 'jsdom';
import {expandRangeStringValues} from './range';
/** Marked token for a custom docs element. */
export interface CodeToken extends Tokens.Generic {
/* Nested code OR the code from the optional file path */
code: string;
/* Code language */
language: string | undefined;
/* The example file path */
path?: string;
/* The example display header */
header?: string;
/* Whether stling should include line numbers */
linenums?: boolean;
/* The example path to determine diff (lines added/removed) */
diff?: string;
/* The lines viewable in collapsed view */
visibleLines?: string;
/* The name of the viewable region in the collapsed view */
visibleRegion?: string;
/* Whether we should display preview */
preview?: boolean;
/* The lines to display highlighting on */
highlight?: string;
/** The generated diff metadata if created in the code formating process. */
diffMetadata?: DiffMetadata;
}
export function formatCode(token: CodeToken) {
if (token.visibleLines !== undefined && token.visibleRegion !== undefined) {
throw Error('Cannot define visible lines and visible region at the same time');
}
extractRegions(token);
calculateDiff(token);
highlightCode(token);
const containerEl = JSDOM.fragment(`
<div class="docs-code">
${buildHeaderElement(token)}
<pre class="docs-mini-scroll-track">
${token.code}
</pre>
</div>
`).firstElementChild!;
applyContainerAttributesAndClasses(containerEl, token);
return containerEl.outerHTML;
}
/** Build the header element if a header is provided in the token. */
function buildHeaderElement(token: CodeToken) {
return token.header ? `<div class="docs-code-header"><h3>${token.header}</h3></div>` : '';
}
function applyContainerAttributesAndClasses(el: Element, token: CodeToken) {
// Attributes
// String value attributes
if (token.diff) {
el.setAttribute('path', token.diff);
}
if (token.path) {
el.setAttribute('path', token.path);
}
if (token.visibleLines) {
el.setAttribute('visibleLines', expandRangeStringValues(token.visibleLines).toString());
}
if (token.header) {
el.setAttribute('header', token.header);
}
// Boolean value attributes
if (token.preview) {
el.setAttribute('preview', 'true');
}
if (token.language === 'mermaid') {
el.setAttribute('mermaid', 'true');
}
// Classes
if (token.language === 'shell') {
el.classList.add('shell');
}
}
| {
"end_byte": 2651,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/guides/extensions/docs-code/format/index.ts"
} |
angular/adev/shared-docs/pipeline/guides/testing/bootstrap.init.ts_0_112 | // Set HANDLE_MERMAID to false as unit testing does not handle mermaid.
(global as any).HANDLE_MERMAID = false;
| {
"end_byte": 112,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/guides/testing/bootstrap.init.ts"
} |
angular/adev/shared-docs/pipeline/guides/testing/BUILD.bazel_0_702 | load("//tools:defaults.bzl", "jasmine_node_test", "ts_library")
ts_library(
name = "unit_test_lib",
testonly = True,
srcs = glob([
"**/*.spec.ts",
]),
deps = [
"//adev/shared-docs/pipeline/guides",
"@npm//@bazel/runfiles",
"@npm//@types/jsdom",
"@npm//jsdom",
],
)
ts_library(
name = "bootstrap",
testonly = True,
srcs = [
"bootstrap.init.ts",
],
)
jasmine_node_test(
name = "unit_tests",
bootstrap = [
":bootstrap",
],
data = [
"@npm//jsdom",
] + glob([
"**/*.html",
"**/*.md",
"**/*.svg",
"**/*.ts",
]),
deps = [":unit_test_lib"],
)
| {
"end_byte": 702,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/adev/shared-docs/pipeline/guides/testing/BUILD.bazel"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.