Skip to content

Commit 938f478

Browse files
committed
refactor(cdk/a11y): add ID generator service
Adds a service to generate unique IDs.
1 parent bd75077 commit 938f478

File tree

3 files changed

+50
-0
lines changed

3 files changed

+50
-0
lines changed

src/cdk/a11y/id-generator.ts

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
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 {APP_ID, inject, Injectable} from '@angular/core';
10+
11+
/**
12+
* Keeps track of the ID count per prefix. This helps us make the IDs a bit more deterministic
13+
* like they were before the service was introduced. Note that ideally we wouldn't have to do
14+
* this, but there are some internal tests that rely on the IDs.
15+
*/
16+
const counters: Record<string, number> = {};
17+
18+
/** Service that generates unique IDs for DOM nodes. */
19+
@Injectable({providedIn: 'root'})
20+
export class _IdGenerator {
21+
private _appId = inject(APP_ID);
22+
23+
/**
24+
* Generates a unique ID with a specific prefix.
25+
* @param prefix Prefix to add to the ID.
26+
*/
27+
getId(prefix: string): string {
28+
// Omit the app ID if it's the default `ng`. Since the vast majority of pages have one
29+
// Angular app on them, we can reduce the amount of breakages by not adding it.
30+
if (this._appId !== 'ng') {
31+
prefix += this._appId;
32+
}
33+
34+
if (!counters.hasOwnProperty(prefix)) {
35+
counters[prefix] = 0;
36+
}
37+
38+
return `${prefix}${counters[prefix]++}`;
39+
}
40+
}

src/cdk/a11y/public-api.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,3 +36,4 @@ export {
3636
HighContrastModeDetector,
3737
HighContrastMode,
3838
} from './high-contrast-mode/high-contrast-mode-detector';
39+
export {_IdGenerator} from './id-generator';

tools/public_api_guard/cdk/a11y.md

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,15 @@ export interface Highlightable extends ListKeyManagerOption {
291291
setInactiveStyles(): void;
292292
}
293293

294+
// @public
295+
export class _IdGenerator {
296+
getId(prefix: string): string;
297+
// (undocumented)
298+
static ɵfac: i0.ɵɵFactoryDeclaration<_IdGenerator, never>;
299+
// (undocumented)
300+
static ɵprov: i0.ɵɵInjectableDeclaration<_IdGenerator>;
301+
}
302+
294303
// @public
295304
export const INPUT_MODALITY_DETECTOR_DEFAULT_OPTIONS: InputModalityDetectorOptions;
296305

0 commit comments

Comments
 (0)