import { BooleanInput , coerceBooleanProperty } from '@angular/cdk/coercion' ; import { DOCUMENT } from '@angular/common' ; import { AfterViewChecked , Attribute , ChangeDetectionStrategy , Component , ElementRef , ErrorHandler , inject , Inject , InjectionToken , Input , OnChanges , OnDestroy , OnInit , SimpleChanges , ViewEncapsulation , } from '@angular/core' ; import { Subscription } from 'rxjs' ; import { take } from 'rxjs/operators' ; import { SbbIconRegistry } from './icon-registry' ; docs-private export const SBB_ICON_LOCATION = new InjectionToken < SbbIconLocation > ( 'sbb-icon-location' , { providedIn : 'root' , factory : SBB_ICON_LOCATION_FACTORY , } ) ; docs-private export interface SbbIconLocation { getPathname : ( ) => string ; } docs-private export function SBB_ICON_LOCATION_FACTORY ( ) { const document = inject ( DOCUMENT ) ; const location = document ? document . location : null ; return { getPathname : ( ) => ( location ? location . pathname + location . search : '' ) , } ; } /** SVG attributes that accept a FuncIRI (e.g. `url(<something>)`). */ const funcIriAttributes = [ 'clip-path' , 'color-profile' , 'src' , 'cursor' , 'fill' , 'filter' , 'marker' , 'marker-start' , 'marker-mid' , 'marker-end' , 'mask' , 'stroke' , ] ; /** Selector that can be used to find all elements that are using a `FuncIRI`. */ const funcIriAttributeSelector = funcIriAttributes . map ( ( attr ) => `[${ attr }]` ) . join ( ', ' ) ; /** Regex that can be used to extract the id out of a FuncIRI. */ const funcIriPattern = /^url\(['"]?#(.*?)['"]?\)$/ ; /**
 * Component to display an icon. It can be used in the following ways:
 *
 * - Specify the svgIcon input to load an SVG icon from a URL previously registered with the
 *   addSvgIcon, addSvgIconInNamespace, addSvgIconSet, or addSvgIconSetInNamespace methods of
 *   SbbIconRegistry. If the svgIcon value contains a colon it is assumed to be in the format
 *   "[namespace]:[name]", if not the value will be the name of an icon in the default namespace.
 *   Examples:
 *     `<sbb-icon svgIcon="example"></sbb-icon>
 *     <sbb-icon svgIcon="kom:cloud-ice-medium"></sbb-icon>`
 *
 * - Use a font ligature as an icon by putting the ligature text in the content of the `<sbb-icon>`
 *   component. You can specify a font by setting the fontSet input to either the CSS class to
 *   apply to use the desired font, or to an alias previously registered with
 *   SbbIconRegistry.registerFontClassAlias.
 *   Examples:
 *     `<sbb-icon>home</sbb-icon>
 *     <sbb-icon fontSet="myfont">sun</sbb-icon>`
 *
 * - Specify a font glyph to be included via CSS rules by setting the fontSet input to specify the
 *   font, and the fontIcon input to specify the icon. Typically the fontIcon will specify a
 *   CSS class which causes the glyph to be displayed via a :before selector, as in
 *   https://fortawesome.github.io/Font-Awesome/examples/
 *   Example:
 *     `<sbb-icon fontSet="fa" fontIcon="alarm"></sbb-icon>`
 */ @ Component ( { template : '<ng-content></ng-content>' , selector : 'sbb-icon' , exportAs : 'sbbIcon' , styleUrls : [ 'icon.css' ] , inputs : [ 'color' ] , host : { role : 'img' , class : 'sbb-icon notranslate' , '[class.sbb-icon-inline]' : 'inline' , } , encapsulation : ViewEncapsulation . None , changeDetection : ChangeDetectionStrategy . OnPush , } ) export class SbbIcon implements OnChanges , OnInit , AfterViewChecked , OnDestroy { /**
     * Whether the icon should be inlined, automatically sizing the icon to match the font size of
     * the element the icon is contained in.
     */ @ Input ( ) get inline ( ) : boolean { return this . _inline ; } set inline ( inline ) { this . _inline = coerceBooleanProperty ( inline ) ; } private _inline : boolean = false ; /** Name of the icon in the SVG icon set. */ @ Input ( ) svgIcon : string ; /** Font set that the icon is a part of. */ @ Input ( ) get fontSet ( ) : string { return this . _fontSet ; } set fontSet ( value ) { this . _fontSet = this . _cleanupFontValue ( value ) ; } private _fontSet : string ; /** Name of an icon within a font set. */ @ Input ( ) get fontIcon ( ) : string { return this . _fontIcon ; } set fontIcon ( value ) { this . _fontIcon = this . _cleanupFontValue ( value ) ; } private _fontIcon : string ; private _previousFontSetClass : string ; private _previousFontIconClass : string ; /** Keeps track of the current page path. */ private _previousPath ? : string ; /** Keeps track of the elements and attributes that we've prefixed with the current path. */ private _elementsWithExternalReferences ? : Map < Element , { name : string ; value : string ; } [ ] > ; /** Subscription to the current in-progress SVG icon request. */ private _currentIconFetch = Subscription . EMPTY ; constructor ( private _elementRef , private _iconRegistry , @ Attribute ( 'aria-hidden' ) ariaHidden , @ Inject ( SBB_ICON_LOCATION ) private _location , private readonly _errorHandler ) { if ( ! ariaHidden ) { this . _elementRef . nativeElement . setAttribute ( 'aria-hidden' , 'true' ) ; } } /**
     * Splits an svgIcon binding value into its icon set and icon name components.
     * Returns a 2-element array of [(icon set), (icon name)].
     * The separator for the two fields is ':'. If there is no separator, an empty
     * string is returned for the icon set and the entire value is returned for
     * the icon name. If the argument is falsy, returns an array of two empty strings.
     * Throws an error if the name contains two or more ':' separators.
     * Examples:
     *   `'kom:cloud-ice-medium' -> ['kom', 'cloud-ice-medium']
     *   'custom-icon' -> ['', 'custom-icon']
     *   null -> ['', '']
     *   'a:b:c' -> (throws Error)`
     */ private _splitIconName ( iconName ) { if ( ! iconName ) { return [ '' , '' ] ; } const parts = iconName . split ( ':' ) ; switch ( parts . length ) { case 1 : return [ '' , parts [ 0 ] ] ; case 2 : return < [ string , string ] > parts ; default : throw Error ( `Invalid icon name: "${ iconName }"` ) ; } } ngOnChanges ( changes ) { const svgIconChanges = changes [ 'svgIcon' ] ; if ( svgIconChanges ) { this . _currentIconFetch . unsubscribe ( ) ; if ( this . svgIcon ) { const [ namespace , iconName ] = this . _splitIconName ( this . svgIcon ) ; this . _currentIconFetch = this . _iconRegistry . getNamedSvgIcon ( iconName , namespace ) . pipe ( take ( 1 ) ) . subscribe ( ( svg ) => this . _setSvgElement ( svg , namespace ) , ( err ) => { const errorMessage = `Error retrieving icon ${ namespace }:${ iconName }! ${ err . message }` ; this . _errorHandler . handleError ( new Error ( errorMessage ) ) ; } ) ; } else if ( svgIconChanges . previousValue ) { this . _clearSvgElement ( ) ; } } if ( this . _usingFontIcon ( ) ) { this . _updateFontIconClasses ( ) ; } } ngOnInit ( ) { if ( this . _usingFontIcon ( ) ) { this . _updateFontIconClasses ( ) ; } } ngAfterViewChecked ( ) { const cachedElements = this . _elementsWithExternalReferences ; if ( cachedElements && cachedElements . size ) { const newPath = this . _location . getPathname ( ) ; if ( newPath !== this . _previousPath ) { this . _previousPath = newPath ; this . _prependPathToReferences ( newPath ) ; } } } ngOnDestroy ( ) { this . _currentIconFetch . unsubscribe ( ) ; if ( this . _elementsWithExternalReferences ) { this . _elementsWithExternalReferences . clear ( ) ; } } private _usingFontIcon ( ) { return ! this . svgIcon ; } private _setSvgElement ( svg , namespace ) { this . _clearSvgElement ( ) ; const styleTags = svg . querySelectorAll ( 'style' ) as NodeListOf < HTMLStyleElement > ; for ( let i = 0 ; i < styleTags . length ; i ++ ) { styleTags [ i ] . textContent += ' ' ; } const path = this . _location . getPathname ( ) ; this . _previousPath = path ; this . _cacheChildrenWithExternalReferences ( svg ) ; this . _prependPathToReferences ( path ) ; this . _elementRef . nativeElement . appendChild ( svg ) ; } private _clearSvgElement ( ) { const layoutElement = this . _elementRef . nativeElement ; let childCount = layoutElement . childNodes . length ; if ( this . _elementsWithExternalReferences ) { this . _elementsWithExternalReferences . clear ( ) ; } while ( childCount -- ) { const child = layoutElement . childNodes [ childCount ] ; if ( child . nodeType !== 1 || child . nodeName . toLowerCase ( ) === 'svg' ) { layoutElement . removeChild ( child ) ; } } } private _updateFontIconClasses ( ) { if ( ! this . _usingFontIcon ( ) ) { return ; } const elem = this . _elementRef . nativeElement ; const fontSetClass = this . fontSet ? this . _iconRegistry . classNameForFontAlias ( this . fontSet ) : this . _iconRegistry . getDefaultFontSetClass ( ) ; if ( fontSetClass !== this . _previousFontSetClass ) { if ( this . _previousFontSetClass ) { elem . classList . remove ( this . _previousFontSetClass ) ; } if ( fontSetClass ) { elem . classList . add ( fontSetClass ) ; } this . _previousFontSetClass = fontSetClass ; } if ( this . fontIcon !== this . _previousFontIconClass ) { if ( this . _previousFontIconClass ) { elem . classList . remove ( this . _previousFontIconClass ) ; } if ( this . fontIcon ) { elem . classList . add ( this . fontIcon ) ; } this . _previousFontIconClass = this . fontIcon ; } } /**
     * Cleans up a value to be used as a fontIcon or fontSet.
     * Since the value ends up being assigned as a CSS class, we
     * have to trim the value and omit space-separated values.
     */ private _cleanupFontValue ( value ) { return typeof value === 'string' ? value . trim ( ) . split ( ' ' ) [ 0 ] : value ; } /**
     * Prepends the current path to all elements that have an attribute pointing to a `FuncIRI`
     * reference. This is required because WebKit browsers require references to be prefixed with
     * the current path, if the page has a `base` tag.
     */ private _prependPathToReferences ( path ) { const elements = this . _elementsWithExternalReferences ; if ( elements ) { elements . forEach ( ( attrs , element ) => { attrs . forEach ( ( attr ) => { element . setAttribute ( attr . name , `url('${ path }#${ attr . value }')` ) ; } ) ; } ) ; } } /**
     * Caches the children of an SVG element that have `url()`
     * references that we need to prefix with the current path.
     */ private _cacheChildrenWithExternalReferences ( element ) { const elementsWithFuncIri = element . querySelectorAll ( funcIriAttributeSelector ) ; const elements = ( this . _elementsWithExternalReferences = this . _elementsWithExternalReferences || new Map ( ) ) ; for ( let i = 0 ; i < elementsWithFuncIri . length ; i ++ ) { funcIriAttributes . forEach ( ( attr ) => { const elementWithReference = elementsWithFuncIri [ i ] ; const value = elementWithReference . getAttribute ( attr ) ; const match = value ? value . match ( funcIriPattern ) : null ; if ( match ) { let attributes = elements . get ( elementWithReference ) ; if ( ! attributes ) { attributes = [ ] ; elements . set ( elementWithReference , attributes ) ; } attributes ! . push ( { name : attr , value : match [ 1 ] } ) ; } } ) ; } } }