All files / modules platform.ts

90.33% Statements 187/207
81.48% Branches 88/108
87.87% Functions 29/33
90.14% Lines 183/203

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 59411x 11x 11x 11x   11x 11x                                               11x 20x     20x     20x   20x 20x     20x     20x                     20x 20x 20x 20x 20x               3x                       2x       2x 2x 2x   2x 1x     1x                     3x 1x         3x                 2x 2x 1x     2x   2x 2x                   2x                 1x 1x   1x 1x 1x 1x 1x   1x 1x 1x                     1x                 1x 1x             20x     4x             4x 4x     4x 4x 4x 4x     4x 4x 4x   4x 1x   1x 1x 1x 1x     4x 1x   1x 1x 1x 1x     4x 2x   2x 2x 2x 2x     4x 4x                       4x 4x   4x             20x       21x   21x 21x 21x 21x 21x     21x 1x     20x 4x     16x 11x     5x 1x     4x 1x     3x                 26x 21x   26x             20x   2x   2x       2x 2x         1x   1x 1x 1x     1x       1x 1x 1x   1x                 1x                   20x 60x             20x 60x   60x   20x 20x   20x 20x   20x 20x     60x 20x           20x   20x 20x   20x 20x       20x 20x   20x       20x       20x   1x 1x   1x 1x           1x 1x       20x                     20x 20x 20x   20x 20x                                                               20x                                     26x 26x   22x 4x 2x         20x 10x 8x         16x               7x   7x 8x 7x               42x 1x     41x       21x 1x     20x                 65x         65x 10x     55x                   10x         10x                 4x         4x      
import { Injectable } from '@angular/core';
import { Platform } from '@ionic/angular';
import { Router, ActivatedRoute } from '@angular/router';
import { DeviceDetectorService } from 'ngx-device-detector';
 
import { Subject } from 'rxjs';
import { take } from 'rxjs/operators';
 
/** @internal */
interface OSInfo {
    syst: string | null;   // win / linux / mac
    proc: string | null;   // 32 / 64
    arch: string | null;   // ARM / intel
    fext: string | null;   // executable files extension
}
 
/** @internal */
type AvailablePlats = "ios" | "ipad" | "iphone" | "android" | "phablet" | "tablet" | "cordova" | "capacitor" | "electron" | "pwa" | "mobile" | "mobileweb" | "desktop" | "hybrid";
 
/**
 * `platformService` is a service that manages platform detection and configuration.
 * It provides methods and properties to determine the type of device and control the display mode,
 * as well as emitting events related to configuration changes.
 * 
 * @remarks
 * This service is injected at the root level and depends on `DeviceDetectorService`, `Platform`, `Router`, and `ActivatedRoute`.
 */
@Injectable({
    providedIn: 'root'
})
export class platformService {
    private _platforms: Array <AvailablePlats> = [];
    
    /** Indicates whether the current device is a mobile device. */
    public _isMobile = false;
 
    /** Indicates whether the current device is a desktop device. */
    public _isDesktop = false;
    
    private _onKioskChanged = new Subject<null> ();
    private _onThemeChanged = new Subject<null> ();
 
    /** Observable that emits when kiosk mode changes. */
    public OnKioskChanged = this._onKioskChanged.asObservable();
 
    /** Observable that emits when the theme changes. */
    public OnThemeChanged = this._onThemeChanged.asObservable();
 
    /**
     * Retrieves detailed device information from `DeviceDetectorService`.
     * 
     * @returns An object containing details about the device, such as OS, browser, and device type.
     */    
    get DeviceInfo(){
        return this.detector.getDeviceInfo();
    }
 
    private _isready = false;
    private _kioskmode = false;
    private _bodytheme: 'dark' | 'light' | null = null;
    private _bodyzoom = 1;
    private _showscroll = false;
 
     /**
     * Retrieves the current kiosk mode status.
     * 
     * @returns `true` if the device is in kiosk mode, otherwise `false`.
     */
     get _isKiosk(){
        return (this.LegacyMobile || this.LegacyTablet) ? false : this._kioskmode;
    }
 
    /**
     * Sets the kiosk mode and emits an event when the mode changes.
     * 
     * @remarks 
     * Kiosk mode can only be enabled if the device is not recognized as a mobile or tablet device.
     * 
     * @param value - A boolean indicating whether kiosk mode should be enabled (`true`) or disabled (`false`).
     */    
    set _isKiosk(value){
        Iif (this.LegacyMobile || this.LegacyTablet){
            return;     // cannot set kiosk when native keyboard is available
        }
 
        if (value != this._kioskmode){
            this._kioskmode = value;
            this._onKioskChanged.next(null);
 
            if (this._kioskmode){
                console.info("[KIOSK] using virtual keyboard");
            }
            else {
                console.info("[KIOSK] using phisical keyboard");
            }    
        }
    }
 
    /**
     * Retrieves the current theme mode.
     * 
     * @returns The current theme mode, either 'dark' or 'light'.
     */    
    get _theme(): 'dark' | 'light' | null {
        if (this._bodytheme == null){
            Iif (document.body.classList.contains('dark')){
                this._bodytheme = 'dark';
            }
        }
        
        return this._bodytheme;
    }
 
    /**
     * Sets the current theme mode to either 'dark' or 'light' and emits a change event.
     * 
     * @param value - The theme mode to set, either 'dark' or 'light'.
     */
    set _theme(value: 'dark' | 'light'){
        if (value != this._bodytheme){
            if (this._bodytheme && document.body.classList.contains(this._bodytheme)){
                document.body.classList.remove(this._bodytheme);
            }
 
            this._bodytheme = value;
 
            document.body.classList.add(this._bodytheme);
            this._onThemeChanged.next(null);
        }
    }
 
    /**
     * Retrieves the current zoom level of the application.
     * 
     * @returns The current zoom level as a numeric value.
     */    
    get _zoomLevel(){
        return this._bodyzoom;
    }
 
    /**
     * Sets the current zoom level of the application.
     * 
     * @param value - The new zoom level to apply.
     */    
    set _zoomLevel(value){
        if (this._bodyzoom != value){
            this._bodyzoom = value;
 
            const _root = document.documentElement;
            if (_root){
                _root.style.setProperty('--body-scale-width', ((1 / this._bodyzoom) * 100).toString() + '%');
                _root.style.setProperty('--body-scale-height', ((1 / this._bodyzoom) * 100).toString() + '%');
                _root.style.setProperty('--body-scale-level', this._bodyzoom.toString());
 
                _root.style.setProperty('--body-zoom-level', (this._bodyzoom * 100).toString() + '%');
                _root.style.setProperty('--body-zoom-width', '100%');
                _root.style.setProperty('--body-zoom-height', ((1 - this._bodyzoom) * 100) + '%');
            }    
        }
    }
 
    /**
     * Retrieves the visibility status of the scrollbar.
     * 
     * @returns `true` if the scrollbar is visible, otherwise `false`.
     */    
    get _scrollbar(){
        return this._showscroll;
    }
 
    /**
     * Toggles the display of the scroll bar based on the provided value.
     * 
     * @param value - A boolean indicating whether the scroll bar should be shown (`true`) or hidden (`false`).
     */    
    set _scrollbar(value){
        this._showscroll = value;
        this._onThemeChanged.next(null);
    }
 
    /************************/
    /* OS information       */
    /************************/
 
    private _runningos: OSInfo | null = null;
 
    private get _OS(): OSInfo | null {
        const _os: OSInfo = {
            syst: null,     // win / linux / mac
            proc: null,     // 32 / 64
            arch: null,     // ARM / intel
            fext: null,     // executable files extension
        }
    
        const _platform = navigator.platform?.toLowerCase();
        const _useragnt = navigator.userAgent.toLowerCase();
 
        // check with useragnt
        let _win = _useragnt.includes('win');
        let _lin = _useragnt.includes('linux') || _useragnt.includes('x11');
        let _mac = _useragnt.includes('mac');
        let _arm = _useragnt.includes('arm') || _useragnt.includes('aarch') || _useragnt.includes('apple silicon');;
        
        // complete with platform
        _win = _win || _platform.includes('win');
        _lin = _lin || _platform.includes('linux') || _platform.includes('x11');
        _mac = _mac || _platform.includes('mac');
 
        if (_win){
            const _is64 = _useragnt.includes('win64') || _useragnt.includes('wow64');
            
            _os.proc = _is64 ? '64' : '32';
            _os.arch = _arm ? 'arm': 'intel';
            _os.syst = 'win';
            _os.fext = '.exe';
        }
 
        if (_lin){
            const _is64 = _useragnt.includes('x86_64') || _useragnt.includes('amd64');
 
            _os.proc = _is64 ? '64' : '32';
            _os.arch = _arm ? 'arm': 'intel';
            _os.syst = 'linux'
            _os.fext = '';
        }
 
        if (_mac){
            _arm = _arm || _useragnt.includes('apple') && navigator.maxTouchPoints > 0;
 
            _os.proc = '64';
            _os.arch = _arm ? 'arm': 'intel';
            _os.syst = 'mac'
            _os.fext = '';
        }
 
        if (_os.syst && _os.proc && _os.arch){
            return _os;
        }
 
        return null;
    }
    
    /**
     * Returns the Operating System information object.
     * 
     * @returns An object containing system type, processor type, architecture, and file extension for executables
     */    
    get RunningOS(){  
        if (!this._runningos){
            this._runningos = this._OS;
        }
        return this._runningos;
    }    
 
    /************************/
    /* Browser information  */
    /************************/
 
    private _browser: string | null = null;
 
    private get _Browser(){ // https://www.geeksforgeeks.org/how-to-detect-the-user-browser-safari-chrome-ie-firefox-and-opera-using-javascript/
        // Get the user-agent string
        const userAgentString = navigator.userAgent;
               
        const chromeAgent = userAgentString.includes("Chrome");
        const IExplorerAgent = userAgentString.includes("MSIE") || userAgentString.includes("rv:");
        const firefoxAgent = userAgentString.includes("Firefox");
        const safariAgent = userAgentString.includes("Safari");
        const operaAgent = userAgentString.includes("OP");
        
        // the evaluation order is important!
        if (operaAgent){
            return "Opera";
        }
 
        if (chromeAgent){
            return "Chrome";
        }
 
        if (safariAgent){
            return "Safari";
        }
 
        if (firefoxAgent){
            return "Firefox";
        }
 
        if (IExplorerAgent){
            return "IE";
        }
 
        return null;
    }
    
    /**
     * Returns the browser type as a string (e.g., "Chrome", "Safari", "Firefox").
     * 
     * @returns The name of the browser or `null` if it could not be determined.
     */    
    get Browser(){  
        if (!this._browser){
            this._browser = this._Browser;
        }
        return this._browser;
    }
 
    /****************************/
    /* VIEW MODE                */
    /****************************/
    
    private _forcedmode: string | null = null;
    private ForceMode(mode: string){
        const _mode = mode.toLowerCase();
 
        Iif (_mode == 'desktop'){
            this._forcedmode = 'desktop';
        }
        
        if (_mode == 'mobile'){
            this._forcedmode = 'mobile';
        }
    }
 
    set _viewMode(value: string){
        const _mode = value.toLowerCase();
        
        let _reload = false;
        if ((_mode == 'mobile') && !this._ismobile){
            _reload = true;
        }
 
        Iif ((_mode == 'desktop') && !this._isdesktop){
            _reload = true;
        }
 
        if (_reload){
            this.ForceMode(_mode);
            console.info("[FORCE MODE] forcing to '" + _mode + "' and reloading");
 
            this.router.navigate([], {
                relativeTo: this.route,
                queryParams: {
                    mode: _mode
                },
    
                queryParamsHandling: 'merge',   // preserve the existing query params in the route
                skipLocationChange: false       // update the url params
              }).then(() => {
                    window.location.reload();   // reload the page with current parameters
              });                
        }
    }
 
    /****************************/
    /* STARTS HERE              */
    /****************************/
 
    private _angular_add(_platforms: Array <AvailablePlats>){
        for(const _platform of _platforms) {
            Iif (this.platform.is(_platform)){
                this._platforms.push(_platform);
            }
        }
    }
 
    private _detector_add(_platforms: Array <AvailablePlats>){
        for(const _platform of _platforms) {
            let _available = false;
 
            switch(_platform){
                case 'mobile':
                    _available = this.detector.isMobile();
                    break;
                case 'tablet':
                    _available = this.detector.isTablet();
                    break;
                case 'desktop':
                    _available = this.detector.isDesktop();
                    break;
            }
 
            if (_available){
                this._platforms.push(_platform);
            }
        }
    }
 
    private _initialize(){
        this._platforms = []
 
        console.info("[DEVICE] running on browser: [" + this.Browser + "]")
        console.info("[DEVICE] identified platforms ", this.platform.platforms());
 
        const _urlMode = this.route.snapshot.queryParamMap.get("mode");
        Iif (_urlMode){  // use url mode
            this.ForceMode(_urlMode);        
        }
 
        this._angular_add(['cordova', 'ios', 'android']);
        this._detector_add(['mobile', 'tablet', 'desktop']);
        
        Iif (this._forcedmode){
            console.info("[DEVICE] platform forced to ", [ this._forcedmode ]);        
        }
        else {
            console.info("[DEVICE] running on platforms ", this._platforms);        
        }
 
        // retrieve the device mode in the url parameters
        this.route.queryParams.pipe(take(1)).subscribe(
        params => {
            if ('mode' in params){
                this.ForceMode(params['mode']);      
 
                if (this._forcedmode){
                    console.info("[DEVICE] platform forced to ", [ this._forcedmode ]);        
                }
                else E{
                    console.info("[DEVICE] running on platforms ", this._platforms);        
                }
        
                this._isMobile = this._ismobile;
                this._isDesktop = this._isdesktop;    
            }
        });
 
        this._isready = true;
    }
 
    /**
     * Constructor that initializes the platform service with required dependencies and sets up the platform configurations.
     * 
     * @param detector - Device detector service for detecting device-specific information.
     * @param platform - Ionic platform service for managing platform-specific features.
     * @param router - Angular router for navigation.
     * @param route - Activated route for accessing route-specific information.
     */    
    constructor(private detector: DeviceDetectorService, private platform: Platform, private router: Router, private route: ActivatedRoute) {
        this.platform.ready().then(() => {
            this._initialize();
 
            this._isMobile = this._ismobile;
            this._isDesktop = this._isdesktop;
        });
    }
    
    /****************************************/
    /* Wrap the platform used methods       */
    /****************************************/
 
    /**
     * Returns the platform ready status
     * 
     * @returns True when the platform is ready
     */    
    get IsReady(){
        return this._isready;        
    }
 
    /**
     * Wraps the platform resize event.
     * 
     * @returns An observable that emits whenever the platform resize event occurs.
     */    
    get resize(){
        return this.platform.resize;
    }
    
    /**
     * Resolves when the platform is ready.
     * 
     * @returns A promise that resolves when the platform setup is complete.
     */    
    ready(){
        return this.platform.ready();
    }
        
    /**
     * Returns an array of detected platform types.
     * 
     * @returns An array containing the available platform types.
     */    
    platforms(){
        return this._platforms;
    }
    
    /**
     * Determines whether the current platform matches the specified type.
     * 
     * @param _platform - The platform type to check (e.g., "ios", "android", "desktop").
     * @returns `true` if the specified platform is detected; otherwise, `false`.
     */    
    is(_platform: AvailablePlats) {
        const _retval = (this._platforms.includes(_platform));
        if (!_retval){  
            // specific android check
            if (_platform == 'android'){
                if (window.navigator.userAgent.toLowerCase().includes('android')) {
                    return true;
                }
            }
 
            // specific ios check
            if (_platform == 'ios'){
                if (/iPad|iPhone|iPod/.test(window.navigator.userAgent)) {
                    return true;
                }
            }
        }
 
        return _retval; 
    }    
    
    /****************************************/
    /* Query large devices / mobile devices */
    /****************************************/
    
    private get _mobileOS(){
        const _test: Array<'ios' | 'android'> = ['ios', 'android'];
 
        for (const _os of _test){
            if (this.platform.is(_os) || this.is(_os)){
                return true;
            }    
        }
 
        return false;
    }
 
    private get _ismobile(){    // true if is mobile (not tablet)
        if (this._forcedmode){
            return (this._forcedmode == 'mobile');
        }
 
        return this.LegacyMobile;
    }
 
    private get _isdesktop(){
        if (this._forcedmode){
            return (this._forcedmode == 'desktop');
        }
 
        return !this._ismobile
    }
 
    /**
     * Determines if the current device should be considered as a legacy mobile device.
     * 
     * @returns `true` if the device is a legacy mobile device; otherwise, `false`.
     */    
    get LegacyMobile(){
        Iif (!this._isready){
            console.error("[PLATFORM] not ready!")
            return false;
        }
 
        if (this.platform.is('tablet')){
            return this.platform.is('iphone');  // iphones may identify themselves as tablet devices
        }
        else {
            return this.platform.is('mobile') && this._mobileOS;
        }
    }
 
    /**
     * Determines if the current device should be considered as a legacy tablet device.
     * 
     * @returns `true` if the device is a legacy tablet device; otherwise, `false`.
     */    
    get LegacyTablet(){
        Iif (!this._isready){
            console.error("[PLATFORM] not ready!")
            return false;
        }
 
        return !this.LegacyMobile && !this.platform.is('desktop') && this.platform.is('tablet') && this._mobileOS;
    }
 
    /**
     * Determines if the current device should be considered as a legacy desktop device.
     * 
     * @returns `true` if the device is a legacy desktop device; otherwise, `false`.
     */    
    get LegacyDesktop(){
        Iif (!this._isready){
            console.error("[PLATFORM] not ready!")
            return false;
        }
 
        return !this.LegacyMobile;
    }
}