|
| 1 | +/*! |
| 2 | + * @license |
| 3 | + * Copyright Google LLC All Rights Reserved. |
| 4 | + * |
| 5 | + * Use of this source code is governed by an MIT-style license that can be |
| 6 | + * found in the LICENSE file at https://angular.dev/license |
| 7 | + */ |
| 8 | + |
| 9 | +import {Injectable, inject} from '@angular/core'; |
| 10 | +import {NavigationItem} from '@angular/docs'; |
| 11 | +import {Meta, Title} from '@angular/platform-browser'; |
| 12 | +import {ActivatedRouteSnapshot, RouterStateSnapshot, TitleStrategy} from '@angular/router'; |
| 13 | + |
| 14 | +export const ROUTE_TITLE_PROPERTY = 'label'; |
| 15 | +export const ROUTE_PARENT_PROPERTY = 'parent'; |
| 16 | +export const TITLE_SUFFIX = 'Angular 日本語版'; |
| 17 | +export const TITLE_SEPARATOR = ' • '; |
| 18 | +export const DEFAULT_PAGE_TITLE = 'Overview'; |
| 19 | + |
| 20 | +export const TITLE_OG_META_TAG = 'og:title'; |
| 21 | +export const TITLE_TWITTER_META_TAG = 'twitter:title'; |
| 22 | + |
| 23 | +export const ALL_TITLE_META_TAGS = [TITLE_OG_META_TAG, TITLE_TWITTER_META_TAG]; |
| 24 | + |
| 25 | +@Injectable({providedIn: 'root'}) |
| 26 | +export class ADevTitleStrategy extends TitleStrategy { |
| 27 | + private readonly title = inject(Title); |
| 28 | + private readonly meta = inject(Meta); |
| 29 | + |
| 30 | + constructor() { |
| 31 | + super(); |
| 32 | + } |
| 33 | + |
| 34 | + override updateTitle(routerState: RouterStateSnapshot) { |
| 35 | + const title = this.buildTitle(routerState); |
| 36 | + |
| 37 | + if (title !== undefined) { |
| 38 | + this.title.setTitle(title); |
| 39 | + ALL_TITLE_META_TAGS.forEach((tag) => this.meta.updateTag({property: tag, content: title})); |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + override buildTitle(snapshot: RouterStateSnapshot): string { |
| 44 | + let route: ActivatedRouteSnapshot = snapshot.root; |
| 45 | + |
| 46 | + while (route.firstChild) { |
| 47 | + route = route.firstChild; |
| 48 | + } |
| 49 | + |
| 50 | + const data = route.data as NavigationItem; |
| 51 | + const routeTitle = data.label ?? ''; |
| 52 | + |
| 53 | + const prefix = |
| 54 | + routeTitle.startsWith(DEFAULT_PAGE_TITLE) && data.parent |
| 55 | + ? `${data.parent.label}${TITLE_SEPARATOR}` |
| 56 | + : ''; |
| 57 | + |
| 58 | + return !!routeTitle ? `${prefix}${routeTitle}${TITLE_SEPARATOR}${TITLE_SUFFIX}` : TITLE_SUFFIX; |
| 59 | + } |
| 60 | +} |
0 commit comments