import * as i0 from '@angular/core';
import { InjectionToken, Injectable, Inject, Optional, Directive, Input, HostBinding, input, booleanAttribute, computed, inject, DestroyRef, effect, HostListener, SkipSelf, signal, NgModule, EventEmitter, LOCALE_ID, Pipe, Injector, untracked } from '@angular/core';
import { AgentType, DSCacheService, DSCoreService, SmartFilterBarService, SmartBusinessService, TimeRangeType, TimeGranularity, OffSetDirection, omitBlank as omitBlank$1 } from '@metad/ocap-core';
import { Subject, merge, EMPTY, Observable, of, switchMap, isObservable, tap, takeUntil, BehaviorSubject, interval, startWith, map, distinctUntilChanged, debounceTime } from 'rxjs';
import { coerceBooleanProperty } from '@angular/cdk/coercion';
import { mixinColor } from '@angular/material/core';
import * as i1 from '@angular/cdk/overlay';
import { TemplatePortal } from '@angular/cdk/portal';
import { toObservable, toSignal, takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { subDays, startOfWeek, startOfMonth, subMonths, endOfMonth, startOfQuarter, endOfWeek, endOfQuarter, startOfYear, endOfYear, subYears } from 'date-fns';
import { trigger, transition, style, animate } from '@angular/animations';
import { TranslateService } from '@ngx-translate/core';
import { HttpParams, HttpErrorResponse } from '@angular/common/http';
import { negate, isNil, isEqual, isEmpty, isString, includes, merge as merge$1 } from 'lodash-es';
import { filter } from 'rxjs/operators';
import { DecimalPipe } from '@angular/common';

const OCAP_AGENT_TOKEN = new InjectionToken('OCAP-Agent');
const OCAP_MODEL_TOKEN = new InjectionToken('OCAP-Model');
const OCAP_DATASOURCE_TOKEN = new InjectionToken('OCAP-DataSource');
var EntityCapacity;
(function (EntityCapacity) {
    EntityCapacity["Dimension"] = "Dimension";
    EntityCapacity["Hierarchy"] = "Hierarchy";
    EntityCapacity["Measure"] = "Measure";
    EntityCapacity["Indicator"] = "Indicator";
    EntityCapacity["Calculation"] = "Calculation";
    EntityCapacity["Parameter"] = "Parameter";
})(EntityCapacity || (EntityCapacity = {}));

class NgmAgentService {
    constructor(agents) {
        this.agents = agents;
        this.error$ = new Subject();
        this._error$ = merge(...this.agents.map((agent) => agent.selectError()));
    }
    selectLocalAgentStatus() {
        const localAgent = this.agents.find((agent) => agent.type === AgentType.Local);
        if (!localAgent) {
            throw new Error(`Can't found Local Agent config`);
        }
        return localAgent?.selectStatus() ?? EMPTY;
    }
    error(err) {
        this.error$.next(err);
    }
    selectError() {
        return this._error$;
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NgmAgentService, deps: [{ token: OCAP_AGENT_TOKEN }], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NgmAgentService }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NgmAgentService, decorators: [{
            type: Injectable
        }], ctorParameters: () => [{ type: Array, decorators: [{
                    type: Inject,
                    args: [OCAP_AGENT_TOKEN]
                }] }] });
class NgmDSCacheService extends DSCacheService {
    constructor() {
        super();
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NgmDSCacheService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NgmDSCacheService }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NgmDSCacheService, decorators: [{
            type: Injectable
        }], ctorParameters: () => [] });

class NgmDSCoreService extends DSCoreService {
    constructor(agents, models, dataSourceFactory, cacheService) {
        super(agents, models, dataSourceFactory, cacheService);
        this.agents = agents;
        this.models = models;
        this.dataSourceFactory = dataSourceFactory;
    }
    ngOnDestroy() {
        super.onDestroy();
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NgmDSCoreService, deps: [{ token: OCAP_AGENT_TOKEN }, { token: OCAP_MODEL_TOKEN, optional: true }, { token: OCAP_DATASOURCE_TOKEN, optional: true }, { token: NgmDSCacheService, optional: true }], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NgmDSCoreService }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NgmDSCoreService, decorators: [{
            type: Injectable
        }], ctorParameters: () => [{ type: Array, decorators: [{
                    type: Inject,
                    args: [OCAP_AGENT_TOKEN]
                }] }, { type: Array, decorators: [{
                    type: Optional
                }, {
                    type: Inject,
                    args: [OCAP_MODEL_TOKEN]
                }] }, { type: Array, decorators: [{
                    type: Optional
                }, {
                    type: Inject,
                    args: [OCAP_DATASOURCE_TOKEN]
                }] }, { type: NgmDSCacheService, decorators: [{
                    type: Optional
                }] }] });

const _NgmAppearanceBase = mixinColor(class {
    constructor(_elementRef) {
        this._elementRef = _elementRef;
    }
});
class AppearanceDirective extends _NgmAppearanceBase {
    /**
     * Sets `outline` appearance
     */
    get outline() {
        return this.ngmAppearance === 'outline';
    }
    set outline(value) {
        if (coerceBooleanProperty(value)) {
            this.ngmAppearance = 'outline';
        }
    }
    get hero() {
        return this.ngmAppearance === 'hero';
    }
    set hero(value) {
        if (coerceBooleanProperty(value)) {
            this.ngmAppearance = 'hero';
        }
    }
    get acrylic() {
        return this.ngmAppearance === 'acrylic';
    }
    set acrylic(value) {
        if (coerceBooleanProperty(value)) {
            this.ngmAppearance = 'acrylic';
        }
    }
    get opacity() {
        return this.ngmAppearance === 'opacity';
    }
    set opacity(value) {
        if (coerceBooleanProperty(value)) {
            this.ngmAppearance = 'opacity';
        }
    }
    get dashed() {
        return this.ngmAppearance === 'dashed';
    }
    set dashed(value) {
        if (coerceBooleanProperty(value)) {
            this.ngmAppearance = 'dashed';
        }
    }
    get danger() {
        return this.ngmAppearance === 'danger';
    }
    set danger(value) {
        if (coerceBooleanProperty(value)) {
            this.ngmAppearance = 'danger';
        }
    }
    constructor(elementRef) {
        super(elementRef);
        this.ngmAppearance = 'filled';
        /** Emits when the chip is focused. */
        this._onFocus = new Subject();
        /** Whether the chip has focus. */
        this._hasFocus = false;
    }
    /** Allows for programmatic focusing of the chip. */
    focus() {
        if (!this._hasFocus) {
            this._elementRef.nativeElement.focus();
            this._onFocus.next({ chip: this });
        }
        this._hasFocus = true;
    }
    getLabel() {
        throw new Error('Method not implemented.');
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: AppearanceDirective, deps: [{ token: i0.ElementRef }], target: i0.ɵɵFactoryTarget.Directive }); }
    static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "17.3.12", type: AppearanceDirective, isStandalone: true, selector: "[ngmAppearance]", inputs: { color: "color", ngmAppearance: "ngmAppearance", outline: "outline", hero: "hero", acrylic: "acrylic", opacity: "opacity", dashed: "dashed", danger: "danger" }, host: { listeners: { "focus": "focus()" }, properties: { "class.ngm-appearance-outline": "this.outline", "class.ngm-appearance-hero": "this.hero", "class.ngm-appearance-acrylic": "this.acrylic", "class.ngm-appearance-opacity": "this.opacity", "class.ngm-appearance-dashed": "this.dashed", "class.ngm-appearance-danger": "this.danger" } }, usesInheritance: true, ngImport: i0 }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: AppearanceDirective, decorators: [{
            type: Directive,
            args: [{
                    standalone: true,
                    selector: '[ngmAppearance]',
                    inputs: ['color'],
                    host: {
                        '(focus)': 'focus()'
                    }
                }]
        }], ctorParameters: () => [{ type: i0.ElementRef }], propDecorators: { ngmAppearance: [{
                type: Input
            }], outline: [{
                type: Input
            }, {
                type: HostBinding,
                args: ['class.ngm-appearance-outline']
            }], hero: [{
                type: Input
            }, {
                type: HostBinding,
                args: ['class.ngm-appearance-hero']
            }], acrylic: [{
                type: Input
            }, {
                type: HostBinding,
                args: ['class.ngm-appearance-acrylic']
            }], opacity: [{
                type: Input
            }, {
                type: HostBinding,
                args: ['class.ngm-appearance-opacity']
            }], dashed: [{
                type: Input
            }, {
                type: HostBinding,
                args: ['class.ngm-appearance-dashed']
            }], danger: [{
                type: Input
            }, {
                type: HostBinding,
                args: ['class.ngm-appearance-danger']
            }] } });

class ButtonGroupDirective {
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: ButtonGroupDirective, deps: [], target: i0.ɵɵFactoryTarget.Directive }); }
    static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "17.3.12", type: ButtonGroupDirective, isStandalone: true, selector: "[ngmButtonGroup]", host: { classAttribute: "ngm-button-group" }, ngImport: i0 }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: ButtonGroupDirective, decorators: [{
            type: Directive,
            args: [{
                    standalone: true,
                    selector: '[ngmButtonGroup]',
                    host: {
                        class: 'ngm-button-group'
                    }
                }]
        }] });

/**
 * Defines the posible values of the components' display density.
 */
var DisplayDensity;
(function (DisplayDensity) {
    DisplayDensity["comfortable"] = "comfortable";
    DisplayDensity["cosy"] = "cosy";
    DisplayDensity["compact"] = "compact";
})(DisplayDensity || (DisplayDensity = {}));
/**
 * @deprecated use hostDirectives {@link NgmDensityDirective }.
 *
 * 组件的 display density 配置
 *
 * [Guidance on high-density spacing](https://material.io/design/layout/applying-density.html)
 */
class DensityDirective {
    get densityCosy() {
        return this.displayDensity === DisplayDensity.comfortable;
    }
    get densityCompact() {
        return this.displayDensity === DisplayDensity.compact;
    }
    get densityComfortable() {
        return this.displayDensity === DisplayDensity.cosy;
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: DensityDirective, deps: [], target: i0.ɵɵFactoryTarget.Directive }); }
    static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "14.0.0", version: "17.3.12", type: DensityDirective, isStandalone: true, selector: "[displayDensity]", inputs: { displayDensity: "displayDensity" }, host: { properties: { "class.ngm-density__comfortable": "this.densityCosy", "class.ngm-density__compact": "this.densityCompact", "class.ngm-density__cosy": "this.densityComfortable" } }, ngImport: i0 }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: DensityDirective, decorators: [{
            type: Directive,
            args: [{
                    standalone: true,
                    selector: '[displayDensity]'
                }]
        }], propDecorators: { displayDensity: [{
                type: Input
            }], densityCosy: [{
                type: HostBinding,
                args: ['class.ngm-density__comfortable']
            }], densityCompact: [{
                type: HostBinding,
                args: ['class.ngm-density__compact']
            }], densityComfortable: [{
                type: HostBinding,
                args: ['class.ngm-density__cosy']
            }] } });
class NgmDensityDirective {
    constructor() {
        this.ngmDensity = input(null, {
            alias: 'ngm-density'
        });
        this.small = input(false, {
            transform: booleanAttribute
        });
        this.large = input(false, {
            transform: booleanAttribute
        });
        this.cosy = computed(() => !this.ngmDensity() && !this.small() && !this.large());
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NgmDensityDirective, deps: [], target: i0.ɵɵFactoryTarget.Directive }); }
    static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "17.3.12", type: NgmDensityDirective, isStandalone: true, selector: "[ngmDensity],[ngm-density]", inputs: { ngmDensity: { classPropertyName: "ngmDensity", publicName: "ngm-density", isSignal: true, isRequired: false, transformFunction: null }, small: { classPropertyName: "small", publicName: "small", isSignal: true, isRequired: false, transformFunction: null }, large: { classPropertyName: "large", publicName: "large", isSignal: true, isRequired: false, transformFunction: null } }, host: { properties: { "class.ngm-density__cosy": "cosy()", "class.ngm-density__compact": "small()", "class.small": "small()", "class.ngm-density__comfortable": "large()", "class.large": "large()", "class": "ngmDensity()" } }, ngImport: i0 }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NgmDensityDirective, decorators: [{
            type: Directive,
            args: [{
                    standalone: true,
                    selector: '[ngmDensity],[ngm-density]',
                    host: {
                        '[class.ngm-density__cosy]': 'cosy()',
                        '[class.ngm-density__compact]': 'small()',
                        '[class.small]': 'small()',
                        '[class.ngm-density__comfortable]': 'large()',
                        '[class.large]': 'large()',
                        '[class]': 'ngmDensity()'
                    }
                }]
        }] });

class NgmTooltipDirective {
    constructor(overlay, elementRef, positionBuilder, viewContainerRef) {
        this.overlay = overlay;
        this.elementRef = elementRef;
        this.positionBuilder = positionBuilder;
        this.viewContainerRef = viewContainerRef;
        this.destroyRef = inject(DestroyRef);
        // Inputs
        this.ngmTooltip = input();
        this.ngmTooltipContext = input();
        //   readonly showDelay = input<number>()
        this.hideDelay = input();
        this.ngmTooltipPositions = input();
        // register a destroy callback
        this.unregisterFn = this.destroyRef.onDestroy(() => {
            clearTimeout(this.detachTimeoutId); // 确保组件销毁时清理计时器
            this.overlayRef.dispose();
        });
        effect(() => {
            this.overlayRef?.dispose();
            this.overlayRef = this.overlay.create({
                positionStrategy: this.positionBuilder.flexibleConnectedTo(this.elementRef).withPositions(this.ngmTooltipPositions() ?? [
                    {
                        originX: 'center',
                        originY: 'bottom',
                        overlayX: 'center',
                        overlayY: 'top',
                        offsetY: 8
                    }
                ]),
                scrollStrategy: this.overlay.scrollStrategies.close()
            });
        });
    }
    show() {
        if (this.ngmTooltip()) {
            if (this.detachTimeoutId) {
                clearTimeout(this.detachTimeoutId); // 防止 mouseenter 时清理正在进行的 detach 计时器
                this.detachTimeoutId = null;
            }
            this.overlayRef.detach();
            const portal = new TemplatePortal(this.ngmTooltip(), this.viewContainerRef, this.ngmTooltipContext());
            this.overlayRef.attach(portal);
        }
    }
    hide() {
        this.detachTimeoutId = setTimeout(() => {
            this.overlayRef.detach();
        }, this.hideDelay() ?? 0);
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NgmTooltipDirective, deps: [{ token: i1.Overlay }, { token: i0.ElementRef }, { token: i1.OverlayPositionBuilder }, { token: i0.ViewContainerRef }], target: i0.ɵɵFactoryTarget.Directive }); }
    static { this.ɵdir = i0.ɵɵngDeclareDirective({ minVersion: "17.1.0", version: "17.3.12", type: NgmTooltipDirective, isStandalone: true, selector: "[ngmTooltip]", inputs: { ngmTooltip: { classPropertyName: "ngmTooltip", publicName: "ngmTooltip", isSignal: true, isRequired: false, transformFunction: null }, ngmTooltipContext: { classPropertyName: "ngmTooltipContext", publicName: "ngmTooltipContext", isSignal: true, isRequired: false, transformFunction: null }, hideDelay: { classPropertyName: "hideDelay", publicName: "hideDelay", isSignal: true, isRequired: false, transformFunction: null }, ngmTooltipPositions: { classPropertyName: "ngmTooltipPositions", publicName: "ngmTooltipPositions", isSignal: true, isRequired: false, transformFunction: null } }, host: { listeners: { "mouseenter": "show()", "mouseleave": "hide()" } }, ngImport: i0 }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NgmTooltipDirective, decorators: [{
            type: Directive,
            args: [{
                    selector: '[ngmTooltip]',
                    standalone: true
                }]
        }], ctorParameters: () => [{ type: i1.Overlay }, { type: i0.ElementRef }, { type: i1.OverlayPositionBuilder }, { type: i0.ViewContainerRef }], propDecorators: { show: [{
                type: HostListener,
                args: ['mouseenter']
            }], hide: [{
                type: HostListener,
                args: ['mouseleave']
            }] } });

class NgmSmartFilterBarService extends SmartFilterBarService {
    constructor(parent) {
        super(parent);
    }
    ngOnDestroy() {
        super.onDestroy();
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NgmSmartFilterBarService, deps: [{ token: NgmSmartFilterBarService, optional: true, skipSelf: true }], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NgmSmartFilterBarService }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NgmSmartFilterBarService, decorators: [{
            type: Injectable
        }], ctorParameters: () => [{ type: NgmSmartFilterBarService, decorators: [{
                    type: Optional
                }, {
                    type: SkipSelf
                }] }] });

/**
 */
class NgmSmartBusinessService extends SmartBusinessService {
    constructor(dsCoreService, smartFilterBar) {
        super(dsCoreService, smartFilterBar);
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NgmSmartBusinessService, deps: [{ token: NgmDSCoreService }, { token: NgmSmartFilterBarService, optional: true }], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NgmSmartBusinessService }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NgmSmartBusinessService, decorators: [{
            type: Injectable
        }], ctorParameters: () => [{ type: NgmDSCoreService }, { type: NgmSmartFilterBarService, decorators: [{
                    type: Optional
                }] }] });

function csvDownload(data, name, delimiter) {
    const items = data;
    const filename = name || `export.csv`;
    const d = delimiter || `,`;
    const header = Array.from(new Set(items.reduce((r, e) => [...r, ...Object.keys(e)], [])));
    const csv = items.map((row) => header.map((fieldName) => JSON.stringify(row[fieldName] === 0 ? 0 : row[fieldName] || '')).join(d));
    csv.unshift(header.join(d));
    const csvStr = csv.join('\r\n');
    const blob = new Blob([csvStr], {
        type: 'text/plain;charset=utf-8'
    });
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.href = url;
    link.download = filename;
    link.style.display = 'none';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
}

/**
 * 树状结构的选择模式
 */
var TreeSelectionMode;
(function (TreeSelectionMode) {
    TreeSelectionMode["Individual"] = "Individual";
    TreeSelectionMode["ParentOnly"] = "ParentOnly";
    TreeSelectionMode["LeafOnly"] = "LeafOnly";
    TreeSelectionMode["ParentChild"] = "ParentChild"; // 输出所有选中的 Parent 和 Children
})(TreeSelectionMode || (TreeSelectionMode = {}));

var ThemesEnum;
(function (ThemesEnum) {
    ThemesEnum["system"] = "system";
    ThemesEnum["default"] = "default";
    ThemesEnum["light"] = "light";
    ThemesEnum["dark"] = "dark";
    ThemesEnum["dark-green"] = "dark-green";
    ThemesEnum["thin"] = "thin";
})(ThemesEnum || (ThemesEnum = {}));
// Window pregers color scheme
function prefersColorScheme() {
    return new Observable((subscriber) => {
        const mediaQueryList = window.matchMedia('(prefers-color-scheme: dark)');
        function onChange({ matches }) {
            if (matches) {
                // subscriber.next(ThemesEnum.dark) // @todo change back when dark theme complete
                subscriber.next(ThemesEnum.light);
            }
            else {
                subscriber.next(ThemesEnum.light);
            }
        }
        mediaQueryList.addEventListener('change', onChange);
        // subscriber.next(mediaQueryList.matches ? ThemesEnum.dark : ThemesEnum.light)
        subscriber.next(mediaQueryList.matches ? ThemesEnum.light : ThemesEnum.light);
        return () => mediaQueryList.removeEventListener('change', onChange);
    });
}

const NGM_DATE_VARIABLES = new InjectionToken('Date Variables', {
    providedIn: 'root',
    factory: NX_DATE_VARIABLES_FACTORY
});
var DateVariableEnum;
(function (DateVariableEnum) {
    DateVariableEnum["SYSTEMTIME"] = "SYSTEMTIME";
    DateVariableEnum["TODAY"] = "TODAY";
    DateVariableEnum["YESTERDAY"] = "YESTERDAY";
    DateVariableEnum["DBY"] = "DBY";
    DateVariableEnum["DAYS_7_AGO"] = "DAYS_7_AGO";
    DateVariableEnum["DAYS_8_AGO"] = "DAYS_8_AGO";
    DateVariableEnum["DAYS_14_AGO"] = "DAYS_14_AGO";
    DateVariableEnum["DAYS_15_AGO"] = "DAYS_15_AGO";
    DateVariableEnum["DAYS_30_AGO"] = "DAYS_30_AGO";
    DateVariableEnum["DAYS_31_AGO"] = "DAYS_31_AGO";
    DateVariableEnum["RECENT_7_DAYS"] = "RECENT_7_DAYS";
    DateVariableEnum["RECENT_14_DAYS"] = "RECENT_14_DAYS";
    DateVariableEnum["RECENT_30_DAYS"] = "RECENT_30_DAYS";
    DateVariableEnum["RECENT_90_DAYS"] = "RECENT_90_DAYS";
    DateVariableEnum["RECENT_180_DAYS"] = "RECENT_180_DAYS";
    DateVariableEnum["THIS_WEEK"] = "THIS_WEEK";
    DateVariableEnum["THIS_MONTH"] = "THIS_MONTH";
    DateVariableEnum["PREVIOUS_MONTH"] = "PREVIOUS_MONTH";
    DateVariableEnum["THIS_QUARTER"] = "THIS_QUARTER";
    DateVariableEnum["THIS_WHOLE_WEEK"] = "THIS_WHOLE_WEEK";
    DateVariableEnum["THIS_WHOLE_MONTH"] = "THIS_WHOLE_MONTH";
    DateVariableEnum["THIS_WHOLE_QUARTER"] = "THIS_WHOLE_QUARTER";
    DateVariableEnum["THIS_WHOLE_YEAR"] = "THIS_WHOLE_YEAR";
    DateVariableEnum["YEAR_TO_TODAY"] = "YEAR_TO_TODAY";
    DateVariableEnum["YEAR_TO_YESTERDAY"] = "YEAR_TO_YESTERDAY";
    DateVariableEnum["PREVIOUS_YEAR"] = "PREVIOUS_YEAR";
})(DateVariableEnum || (DateVariableEnum = {}));
// 系统预定义的时间变量
function NX_DATE_VARIABLES_FACTORY() {
    return [
        {
            id: DateVariableEnum.SYSTEMTIME,
            name: '系统时间',
            deps: [],
            useFactory: () => {
                return new Date();
            }
        },
        {
            id: DateVariableEnum.TODAY,
            name: '当前日期',
            deps: ['SYSTEMTIME'],
            useFactory: ([systemTime]) => {
                return systemTime;
            },
            dateRange: {
                type: TimeRangeType.Standard,
                granularity: TimeGranularity.Day,
                lookBack: 0,
                lookAhead: 0
            }
        },
        {
            id: DateVariableEnum.YESTERDAY,
            name: '昨天',
            deps: ['TODAY'],
            useFactory: ([today]) => {
                return subDays(today, 1);
            },
            dateRange: {
                type: TimeRangeType.Offset,
                granularity: TimeGranularity.Day,
                lookBack: 0,
                lookAhead: 0,
                current: {
                    direction: OffSetDirection.LookBack,
                    granularity: TimeGranularity.Day,
                    amount: 1
                }
            }
        },
        {
            id: DateVariableEnum.DBY,
            name: '前天',
            deps: ['TODAY'],
            useFactory: ([today]) => {
                return subDays(today, 2);
            },
            dateRange: {
                type: TimeRangeType.Offset,
                granularity: TimeGranularity.Day,
                lookBack: 0,
                lookAhead: 0,
                current: {
                    direction: OffSetDirection.LookBack,
                    granularity: TimeGranularity.Day,
                    amount: 2
                }
            }
        },
        {
            id: DateVariableEnum.DAYS_7_AGO,
            name: '七天前',
            deps: ['TODAY'],
            useFactory: ([today]) => {
                return subDays(today, 7);
            },
            dateRange: {
                type: TimeRangeType.Offset,
                granularity: TimeGranularity.Day,
                lookBack: 0,
                lookAhead: 0,
                current: {
                    direction: OffSetDirection.LookBack,
                    granularity: TimeGranularity.Day,
                    amount: 7
                }
            }
        },
        {
            id: DateVariableEnum.DAYS_8_AGO,
            name: '八天前',
            deps: ['TODAY'],
            useFactory: ([today]) => {
                return subDays(today, 8);
            },
            dateRange: {
                type: TimeRangeType.Offset,
                granularity: TimeGranularity.Day,
                lookBack: 0,
                lookAhead: 0,
                current: {
                    direction: OffSetDirection.LookBack,
                    granularity: TimeGranularity.Day,
                    amount: 8
                }
            }
        },
        {
            id: DateVariableEnum.DAYS_14_AGO,
            name: '十四天前',
            deps: ['TODAY'],
            useFactory: ([today]) => {
                return subDays(today, 14);
            },
            dateRange: {
                type: TimeRangeType.Offset,
                granularity: TimeGranularity.Day,
                lookBack: 0,
                lookAhead: 0,
                current: {
                    direction: OffSetDirection.LookBack,
                    granularity: TimeGranularity.Day,
                    amount: 14
                }
            }
        },
        {
            id: DateVariableEnum.DAYS_15_AGO,
            name: '十五天前',
            deps: ['TODAY'],
            useFactory: ([today]) => {
                return subDays(today, 15);
            },
            dateRange: {
                type: TimeRangeType.Offset,
                granularity: TimeGranularity.Day,
                lookBack: 0,
                lookAhead: 0,
                current: {
                    direction: OffSetDirection.LookBack,
                    granularity: TimeGranularity.Day,
                    amount: 15
                }
            }
        },
        {
            id: DateVariableEnum.DAYS_30_AGO,
            name: '三十天前',
            deps: ['TODAY'],
            useFactory: ([today]) => {
                return subDays(today, 30);
            },
            dateRange: {
                type: TimeRangeType.Offset,
                granularity: TimeGranularity.Day,
                lookBack: 0,
                lookAhead: 0,
                current: {
                    direction: OffSetDirection.LookBack,
                    granularity: TimeGranularity.Day,
                    amount: 30
                }
            }
        },
        {
            id: DateVariableEnum.DAYS_31_AGO,
            name: '三十一天前',
            deps: ['TODAY'],
            useFactory: ([today]) => {
                return subDays(today, 31);
            },
            dateRange: {
                type: TimeRangeType.Offset,
                granularity: TimeGranularity.Day,
                lookBack: 0,
                lookAhead: 0,
                current: {
                    direction: OffSetDirection.LookBack,
                    granularity: TimeGranularity.Day,
                    amount: 31
                }
            }
        },
        {
            id: DateVariableEnum.RECENT_7_DAYS,
            name: '最近七天',
            deps: ['TODAY'],
            useFactory: ([today]) => {
                return [subDays(today, 7), today];
            },
            dateRange: {
                type: TimeRangeType.Standard,
                granularity: TimeGranularity.Day,
                lookBack: 7,
                lookAhead: 0
            }
        },
        {
            id: DateVariableEnum.RECENT_14_DAYS,
            name: '最近十四天',
            deps: ['TODAY'],
            useFactory: ([today]) => {
                return [subDays(today, 14), today];
            },
            dateRange: {
                type: TimeRangeType.Standard,
                granularity: TimeGranularity.Day,
                lookBack: 14,
                lookAhead: 0
            }
        },
        {
            id: DateVariableEnum.RECENT_30_DAYS,
            name: '最近三十天',
            deps: ['TODAY'],
            useFactory: ([today]) => {
                return [subDays(today, 30), today];
            },
            dateRange: {
                type: TimeRangeType.Standard,
                granularity: TimeGranularity.Day,
                lookBack: 30,
                lookAhead: 0
            }
        },
        {
            id: DateVariableEnum.RECENT_90_DAYS,
            name: '最近九十天',
            deps: ['TODAY'],
            useFactory: ([today]) => {
                return [subDays(today, 90), today];
            },
            dateRange: {
                type: TimeRangeType.Standard,
                granularity: TimeGranularity.Day,
                lookBack: 90,
                lookAhead: 0
            }
        },
        {
            id: DateVariableEnum.RECENT_180_DAYS,
            name: '最近一百八十天',
            deps: ['TODAY'],
            useFactory: ([today]) => {
                return [subDays(today, 180), today];
            },
            dateRange: {
                type: TimeRangeType.Standard,
                granularity: TimeGranularity.Day,
                lookBack: 180,
                lookAhead: 0
            }
        },
        {
            id: DateVariableEnum.THIS_WEEK,
            name: '本周',
            deps: ['TODAY'],
            useFactory: ([today]) => {
                return [startOfWeek(today, { weekStartsOn: 1 }), today];
            }
        },
        {
            id: DateVariableEnum.THIS_MONTH,
            name: '本月',
            deps: ['TODAY'],
            useFactory: ([today]) => {
                return [startOfMonth(today), today];
            },
            dateRange: {
                type: TimeRangeType.Standard,
                granularity: TimeGranularity.Month,
                lookBack: 0,
                lookAhead: 0
            }
        },
        {
            id: DateVariableEnum.PREVIOUS_MONTH,
            name: '上月',
            deps: ['TODAY'],
            useFactory: ([today]) => {
                const start = subMonths(today, 1);
                return [start, endOfMonth(start)];
            },
            dateRange: {
                type: TimeRangeType.Offset,
                granularity: TimeGranularity.Month,
                lookBack: 0,
                lookAhead: 0,
                current: {
                    direction: OffSetDirection.LookBack,
                    granularity: TimeGranularity.Month,
                    amount: 1
                }
            }
        },
        {
            id: DateVariableEnum.THIS_QUARTER,
            name: '本季度',
            deps: ['TODAY'],
            useFactory: ([today]) => {
                return [startOfQuarter(today), today];
            },
            dateRange: {
                type: TimeRangeType.Standard,
                granularity: TimeGranularity.Quarter,
                lookBack: 0,
                lookAhead: 0
            }
        },
        {
            id: DateVariableEnum.YEAR_TO_TODAY,
            name: '当前年至当天',
            deps: ['TODAY'],
            useFactory: ([today]) => {
                return [new Date(today.getFullYear(), 0, 1), today];
            }
        },
        {
            id: DateVariableEnum.YEAR_TO_YESTERDAY,
            name: '当前年至昨天',
            deps: ['TODAY'],
            useFactory: ([today]) => {
                return [new Date(today.getFullYear(), 0, 1), subDays(today, 1)];
            }
        },
        {
            id: DateVariableEnum.THIS_WHOLE_WEEK,
            name: '本周(包含整周)',
            deps: ['TODAY'],
            useFactory: ([today]) => {
                return [startOfWeek(today, { weekStartsOn: 1 }), endOfWeek(today, { weekStartsOn: 1 })];
            }
        },
        {
            id: DateVariableEnum.THIS_WHOLE_MONTH,
            name: '本月(包含整月)',
            deps: ['TODAY'],
            useFactory: ([today]) => {
                return [startOfMonth(today), endOfMonth(today)];
            }
        },
        {
            id: DateVariableEnum.THIS_WHOLE_QUARTER,
            name: '本季度(包含整季度)',
            deps: ['TODAY'],
            useFactory: ([today]) => {
                return [startOfQuarter(today), endOfQuarter(today)];
            }
        },
        {
            id: DateVariableEnum.THIS_WHOLE_YEAR,
            name: '今年(包含整年)',
            deps: ['TODAY'],
            useFactory: ([today]) => {
                return [startOfYear(today), endOfYear(today)];
            }
        },
        {
            id: DateVariableEnum.PREVIOUS_YEAR,
            name: '去年',
            deps: ['TODAY'],
            useFactory: ([today]) => {
                const lastYear = subYears(today, 1);
                return [startOfYear(lastYear), endOfYear(lastYear)];
            },
            dateRange: {
                type: TimeRangeType.Offset,
                granularity: TimeGranularity.Year,
                lookBack: 0,
                lookAhead: 0,
                current: {
                    direction: OffSetDirection.LookBack,
                    amount: 1
                }
            }
        }
    ];
}

const TIME_GRANULARITY_SEQUENCES = {
    0: [TimeGranularity.Year, TimeGranularity.Month],
    1: [TimeGranularity.Year, TimeGranularity.Quarter, TimeGranularity.Month],
    2: [TimeGranularity.Year, TimeGranularity.Month, TimeGranularity.Day],
    3: [TimeGranularity.Year, TimeGranularity.Quarter, TimeGranularity.Month, TimeGranularity.Day],
};
const PERIODS = [
    {
        name: '1W',
        granularity: TimeGranularity.Day,
        lookBack: 7
    },
    {
        name: '1M',
        granularity: TimeGranularity.Day,
        lookBack: 30
    },
    {
        name: '3M',
        granularity: TimeGranularity.Day,
        lookBack: 90
    },
    {
        name: '6M',
        granularity: TimeGranularity.Day,
        lookBack: 180
    },
    {
        name: '1Y',
        granularity: TimeGranularity.Month,
        lookBack: 12
    },
    {
        name: '2Y',
        granularity: TimeGranularity.Month,
        lookBack: 24
    },
    {
        name: '3Y',
        granularity: TimeGranularity.Month,
        lookBack: 36
    },
    {
        name: '4Y',
        granularity: TimeGranularity.Month,
        lookBack: 48
    },
    {
        name: '5Y',
        granularity: TimeGranularity.Month,
        lookBack: 60
    }
];

var NgmLanguageEnum;
(function (NgmLanguageEnum) {
    NgmLanguageEnum["Chinese"] = "zh-CN";
    NgmLanguageEnum["SimplifiedChinese"] = "zh-Hans";
    NgmLanguageEnum["TraditionalChinese"] = "zh-Hant";
    NgmLanguageEnum["English"] = "en";
})(NgmLanguageEnum || (NgmLanguageEnum = {}));

class NgmThemeService {
    #themeClass$;
    constructor() {
        this.#themeClass$ = signal('');
        this.themeClass$ = toObservable(this.#themeClass$);
        this.themeClass = this.#themeClass$.asReadonly();
        const initialClass = document.body.classList.contains(ThemesEnum.dark) ? ThemesEnum.dark : ThemesEnum.light;
        this.#themeClass$.set(initialClass);
        // Efficiently listen for class changes using MutationObserver:
        const observer = new MutationObserver((mutations) => {
            for (const mutation of mutations) {
                if (mutation.type === 'attributes' && mutation.attributeName === 'class') {
                    const newClass = document.body.classList.contains(ThemesEnum.dark) ? ThemesEnum.dark : ThemesEnum.light;
                    if (newClass !== this.#themeClass$()) {
                        this.#themeClass$.set(newClass);
                    }
                }
            }
        });
        observer.observe(document.body, { attributes: true });
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NgmThemeService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NgmThemeService, providedIn: 'root' }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NgmThemeService, decorators: [{
            type: Injectable,
            args: [{
                    providedIn: 'root'
                }]
        }], ctorParameters: () => [] });

class NgmOcapCoreService {
    constructor() {
        this.dateVariables = inject(NGM_DATE_VARIABLES);
        /**
         * 接收各组件创建修改计算字段的事件, 发给组件进行实际更新
         * 暂时使用这种间接的方式
         */
        this.#entityUpdateEvent$ = new Subject();
        this.#openCalculation = signal((params) => EMPTY);
    }
    /**
     * 接收各组件创建修改计算字段的事件, 发给组件进行实际更新
     * 暂时使用这种间接的方式
     */
    #entityUpdateEvent$;
    #openCalculation;
    updateEntity(event) {
        this.#entityUpdateEvent$.next(event);
    }
    onEntityUpdate() {
        return this.#entityUpdateEvent$.asObservable();
    }
    getDateVariables() {
        return this.dateVariables;
    }
    execDateVariables(id) {
        const dateVariable = this.dateVariables.find((item) => item.id === id);
        if (!dateVariable) {
            try {
                return new Date(id);
            }
            catch (err) {
                throw new Error(`Can't found date variable or date '${id}'`);
            }
        }
        return dateVariable.useFactory(dateVariable.deps?.map((dep) => this.execDateVariables(dep)));
    }
    openCalculation(params) {
        return of(params).pipe(switchMap(this.#openCalculation()));
    }
    setCalculationHandler(handler) {
        this.#openCalculation.set(handler);
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NgmOcapCoreService, deps: [], target: i0.ɵɵFactoryTarget.Injectable }); }
    static { this.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NgmOcapCoreService }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NgmOcapCoreService, decorators: [{
            type: Injectable
        }] });

function provideFadeAnimation(timings = '300ms') {
    return trigger('fadeAnimation', [
        transition(':enter', [style({ opacity: 0 }), animate(timings, style({ opacity: 1 }))]),
        transition(':leave', [animate(timings, style({ opacity: 0 }))])
    ]);
}
const fadeAnimation = provideFadeAnimation();

function injectTranslate(key) {
    const translate = inject(TranslateService);
    return toSignal(translate.stream(key));
}

class OcapCoreModule {
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: OcapCoreModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule }); }
    static { this.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "14.0.0", version: "17.3.12", ngImport: i0, type: OcapCoreModule, imports: [DensityDirective, AppearanceDirective, ButtonGroupDirective], exports: [DensityDirective, AppearanceDirective, ButtonGroupDirective] }); }
    static { this.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: OcapCoreModule }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: OcapCoreModule, decorators: [{
            type: NgModule,
            args: [{
                    imports: [DensityDirective, AppearanceDirective, ButtonGroupDirective],
                    exports: [DensityDirective, AppearanceDirective, ButtonGroupDirective],
                    declarations: [],
                    providers: []
                }]
        }] });
function provideOcapCore() {
    return [NgmDSCoreService, NgmOcapCoreService];
}

const isNotNil = negate(isNil);
const filterNil = filter(negate(isNil));
const isNotEqual = negate(isEqual);
const isNotEmpty = negate(isEmpty);
function isBlank(value) {
    return isNil(value) || isString(value) && !value.trim();
}
function nonBlank(value) {
    return !isBlank(value);
}
/**
 *@hidden
 */
function cloneArray(array, deep) {
    const arr = [];
    if (!array) {
        return arr;
    }
    let i = array.length;
    while (i--) {
        arr[i] = deep ? cloneValue(array[i]) : array[i];
    }
    return arr;
}
/**
 * Doesn't clone leaf items
 * @hidden
 */
function cloneHierarchicalArray(array, childDataKey) {
    const result = [];
    if (!array) {
        return result;
    }
    for (const item of array) {
        const clonedItem = cloneValue(item);
        if (Array.isArray(item[childDataKey])) {
            clonedItem[childDataKey] = cloneHierarchicalArray(clonedItem[childDataKey], childDataKey);
        }
        result.push(clonedItem);
    }
    return result;
}
/**
 * Deep clones all first level keys of Obj2 and merges them to Obj1
 * @param obj1 Object to merge into
 * @param obj2 Object to merge from
 * @returns Obj1 with merged cloned keys from Obj2
 * @hidden
 */
function mergeObjects(obj1, obj2) {
    if (!isObject(obj1)) {
        throw new Error(`Cannot merge into ${obj1}. First param must be an object.`);
    }
    if (!isObject(obj2)) {
        return obj1;
    }
    for (const key of Object.keys(obj2)) {
        obj1[key] = cloneValue(obj2[key]);
    }
    return obj1;
}
/**
 * Creates deep clone of provided value.
 * Supports primitive values, dates and objects.
 * If passed value is array returns shallow copy of the array.
 * @param value value to clone
 * @returns Deep copy of provided value
 *@hidden
 */
function cloneValue(value) {
    if (isDate(value)) {
        return new Date(value.getTime());
    }
    if (Array.isArray(value)) {
        return [...value];
    }
    if (value instanceof Map || value instanceof Set) {
        return value;
    }
    if (isObject(value)) {
        const result = {};
        for (const key of Object.keys(value)) {
            result[key] = cloneValue(value[key]);
        }
        return result;
    }
    return value;
}
/**
 * Checks if provided variable is Object
 * @param value Value to check
 * @returns true if provided variable is Object
 *@hidden
 */
function isObject(value) {
    return value && value.toString() === '[object Object]';
}
/**
 * Checks if provided variable is Date
 * @param value Value to check
 * @returns true if provided variable is Date
 *@hidden
 */
function isDate(value) {
    return Object.prototype.toString.call(value) === '[object Date]';
}
/**
 *@hidden
 */
var KEYCODES;
(function (KEYCODES) {
    KEYCODES[KEYCODES["ENTER"] = 13] = "ENTER";
    KEYCODES[KEYCODES["SPACE"] = 32] = "SPACE";
    KEYCODES[KEYCODES["ESCAPE"] = 27] = "ESCAPE";
    KEYCODES[KEYCODES["LEFT_ARROW"] = 37] = "LEFT_ARROW";
    KEYCODES[KEYCODES["UP_ARROW"] = 38] = "UP_ARROW";
    KEYCODES[KEYCODES["RIGHT_ARROW"] = 39] = "RIGHT_ARROW";
    KEYCODES[KEYCODES["DOWN_ARROW"] = 40] = "DOWN_ARROW";
    KEYCODES[KEYCODES["F2"] = 113] = "F2";
    KEYCODES[KEYCODES["TAB"] = 9] = "TAB";
    KEYCODES[KEYCODES["CTRL"] = 17] = "CTRL";
    KEYCODES[KEYCODES["Z"] = 90] = "Z";
    KEYCODES[KEYCODES["Y"] = 89] = "Y";
    KEYCODES[KEYCODES["X"] = 88] = "X";
    KEYCODES[KEYCODES["BACKSPACE"] = 8] = "BACKSPACE";
    KEYCODES[KEYCODES["DELETE"] = 46] = "DELETE";
    KEYCODES[KEYCODES["INPUT_METHOD"] = 229] = "INPUT_METHOD";
})(KEYCODES || (KEYCODES = {}));
/**
 *@hidden
 */
var KEYS;
(function (KEYS) {
    KEYS["ENTER"] = "Enter";
    KEYS["SPACE"] = " ";
    KEYS["SPACE_IE"] = "Spacebar";
    KEYS["ESCAPE"] = "Escape";
    KEYS["ESCAPE_IE"] = "Esc";
    KEYS["LEFT_ARROW"] = "ArrowLeft";
    KEYS["LEFT_ARROW_IE"] = "Left";
    KEYS["UP_ARROW"] = "ArrowUp";
    KEYS["UP_ARROW_IE"] = "Up";
    KEYS["RIGHT_ARROW"] = "ArrowRight";
    KEYS["RIGHT_ARROW_IE"] = "Right";
    KEYS["DOWN_ARROW"] = "ArrowDown";
    KEYS["DOWN_ARROW_IE"] = "Down";
    KEYS["F2"] = "F2";
    KEYS["TAB"] = "Tab";
    KEYS["SEMICOLON"] = ";";
    KEYS["HOME"] = "Home";
    KEYS["END"] = "End";
})(KEYS || (KEYS = {}));
/**
 *@hidden
 * Returns the actual size of the node content, using Range
 * ```typescript
 * let range = document.createRange();
 * let column = this.grid.columnList.filter(c => c.field === 'ID')[0];
 *
 * let size = getNodeSizeViaRange(range, column.cells[0].nativeElement);
 * ```
 */
function getNodeSizeViaRange(range, node) {
    let overflow = null;
    if (!isFirefox()) {
        overflow = node.style.overflow;
        // we need that hack - otherwise content won't be measured correctly in IE/Edge
        node.style.overflow = 'visible';
    }
    range.selectNodeContents(node);
    const width = range.getBoundingClientRect().width;
    if (!isFirefox()) {
        // we need that hack - otherwise content won't be measured correctly in IE/Edge
        node.style.overflow = overflow;
    }
    return width;
}
/**
 *@hidden
 */
function isIE() {
    return navigator.appVersion.indexOf('Trident/') > 0;
}
/**
 *@hidden
 */
function isEdge() {
    const edgeBrowser = /Edge[\/\s](\d+\.\d+)/.test(navigator.userAgent);
    return edgeBrowser;
}
/**
 *@hidden
 */
function isFirefox() {
    const firefoxBrowser = /Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent);
    return firefoxBrowser;
}
// /**
//  * @hidden
//  */
// @Injectable({ providedIn: 'root' })
// export class PlatformUtil {
//   public isBrowser: boolean = isPlatformBrowser(this.platformId)
//   public isIOS =
//     this.isBrowser && /iPad|iPhone|iPod/.test(navigator.userAgent) && !('MSStream' in window)
//   constructor(@Inject(PLATFORM_ID) private platformId: Object) {}
// }
/**
 * @hidden
 */
function isLeftClick(event) {
    return event.button === 0;
}
/** @hidden */
function isNavigationKey(key) {
    return ([
        'down',
        'up',
        'left',
        'right',
        'arrowdown',
        'arrowup',
        'arrowleft',
        'arrowright',
        'home',
        'end',
        'space',
        'spacebar',
        ' ',
    ].indexOf(key) !== -1);
}
const NAVIGATION_KEYS = new Set([
    'down',
    'up',
    'left',
    'right',
    'arrowdown',
    'arrowup',
    'arrowleft',
    'arrowright',
    'home',
    'end',
    'space',
    'spacebar',
    ' ',
]);
const ROW_EXPAND_KEYS = new Set('right down arrowright arrowdown'.split(' '));
const ROW_COLLAPSE_KEYS = new Set('left up arrowleft arrowup'.split(' '));
const SUPPORTED_KEYS = new Set([
    ...Array.from(NAVIGATION_KEYS),
    'tab',
    'enter',
    'f2',
    'escape',
    'esc',
]);
function convertToBoolProperty(val) {
    if (typeof val === 'string') {
        val = val.toLowerCase().trim();
        return val === 'true' || val === '';
    }
    return !!val;
}
/** Button events to pass to `DebugElement.triggerEventHandler` for RouterLink event handler */
const ButtonClickEvents = {
    left: { button: 0 },
    right: { button: 2 },
};
/** Simulate element click. Defaults to mouse left-button click event. */
function click(el, eventObj = ButtonClickEvents.left) {
    if (el instanceof HTMLElement) {
        el.click();
    }
    else {
        el.triggerEventHandler('click', eventObj);
    }
}
const mkenum = (x) => x;
// Search options
function includeIgnoreCase(text, target) {
    const keywords = target.split(/\s+/g);
    const matchs = String(text).match(new RegExp(`(${keywords.join('|')})`, 'ig'));
    return matchs;
}
/**
 * 分解高亮字符串
 *
 * @param text
 * @param highlight
 * @returns
 */
function splitByHighlight(text, highlight) {
    if (highlight && text) {
        const keywords = Array.isArray(highlight) ? highlight : highlight.split(/\s+/g);
        const matchs = String(text).match(new RegExp(`(${keywords.join('|')})`, 'ig'));
        const results = String(text).split(new RegExp(`(${keywords.join('|')})`, 'i'));
        if (results?.length > 1) {
            return results.map(value => includes(matchs, value) ? { match: true, value } : { value });
        }
    }
    return [{ value: text }];
}
function toParams(query) {
    let params = new HttpParams();
    Object.keys(query).forEach((key) => {
        if (isJsObject(query[key])) {
            params = toSubParams(params, key, query[key]);
        }
        else {
            params = params.append(key.toString(), query[key]);
        }
    });
    return params;
}
function isJsObject(object) {
    return (object !== null && object !== undefined && typeof object === 'object');
}
function toSubParams(params, key, object) {
    Object.keys(object).forEach((childKey) => {
        if (isJsObject(object[childKey])) {
            params = toSubParams(params, `${key}[${childKey}]`, object[childKey]);
        }
        else {
            params = params.append(`${key}[${childKey}]`, object[childKey]);
        }
    });
    return params;
}
function mergeOptions(obj1, ...objs) {
    return merge$1(obj1, ...objs.map(item => omitBlank(item)));
}
function omitBlank(obj) {
    if (Array.isArray(obj)) {
        return obj.map(value => omitBlank(value));
    }
    else if (typeof obj === "object") {
        return Object.entries(obj)
            .filter(([, v]) => !isBlank(v))
            .reduce((r, [key, value]) => ({ ...r, [key]: omitBlank(value) }), {});
    }
    else {
        return obj;
    }
}
/**
 * Try get error message from any error object
 */
function getErrorMessage(err) {
    let error;
    if (typeof err === 'string') {
        error = err;
    }
    else if (err instanceof HttpErrorResponse) {
        error = err?.error?.message ?? err.message;
    }
    else if (err instanceof Error) {
        error = err?.message;
    }
    else if (err?.error instanceof Error) {
        error = err?.error?.message;
    }
    else if (err) {
        // 实在没办法则转成 JSON string
        error = JSON.stringify(err);
    }
    return error;
}
function filterSearch(items, text) {
    if (typeof text !== 'string')
        return items;
    const words = text?.split(' ').filter(nonBlank).map((word) => word.toLowerCase());
    return words?.length ? items.filter((item) => words.every((word) => item.caption?.toLowerCase().includes(word) || item.key.toLowerCase().includes(word))) : items;
}

class NgmMissingTranslationHandler {
    handle(params) {
        if (params.interpolateParams) {
            return params.interpolateParams['Default'] || params.key;
        }
        return params.key;
    }
}

var localeEn = {
    lang: 'en',
    shortNumberFactor: 3,
    shortNumberUnits: 'K,M,B,T,Q'
};

/**
 * This const is used to store the locale data registered with `registerLocaleData`
 */
const LOCALE_DATA = {};
/**
 * Index of each type of locale data from the locale data array
 */
var LocaleDataIndex;
(function (LocaleDataIndex) {
    LocaleDataIndex[LocaleDataIndex["LocaleId"] = 0] = "LocaleId";
    LocaleDataIndex[LocaleDataIndex["DayPeriodsFormat"] = 1] = "DayPeriodsFormat";
    LocaleDataIndex[LocaleDataIndex["DayPeriodsStandalone"] = 2] = "DayPeriodsStandalone";
    LocaleDataIndex[LocaleDataIndex["DaysFormat"] = 3] = "DaysFormat";
    LocaleDataIndex[LocaleDataIndex["DaysStandalone"] = 4] = "DaysStandalone";
    LocaleDataIndex[LocaleDataIndex["MonthsFormat"] = 5] = "MonthsFormat";
    LocaleDataIndex[LocaleDataIndex["MonthsStandalone"] = 6] = "MonthsStandalone";
    LocaleDataIndex[LocaleDataIndex["Eras"] = 7] = "Eras";
    LocaleDataIndex[LocaleDataIndex["FirstDayOfWeek"] = 8] = "FirstDayOfWeek";
    LocaleDataIndex[LocaleDataIndex["WeekendRange"] = 9] = "WeekendRange";
    LocaleDataIndex[LocaleDataIndex["DateFormat"] = 10] = "DateFormat";
    LocaleDataIndex[LocaleDataIndex["TimeFormat"] = 11] = "TimeFormat";
    LocaleDataIndex[LocaleDataIndex["DateTimeFormat"] = 12] = "DateTimeFormat";
    LocaleDataIndex[LocaleDataIndex["NumberSymbols"] = 13] = "NumberSymbols";
    LocaleDataIndex[LocaleDataIndex["NumberFormats"] = 14] = "NumberFormats";
    LocaleDataIndex[LocaleDataIndex["CurrencyCode"] = 15] = "CurrencyCode";
    LocaleDataIndex[LocaleDataIndex["CurrencySymbol"] = 16] = "CurrencySymbol";
    LocaleDataIndex[LocaleDataIndex["CurrencyName"] = 17] = "CurrencyName";
    LocaleDataIndex[LocaleDataIndex["Currencies"] = 18] = "Currencies";
    LocaleDataIndex[LocaleDataIndex["Directionality"] = 19] = "Directionality";
    LocaleDataIndex[LocaleDataIndex["PluralCase"] = 20] = "PluralCase";
    LocaleDataIndex[LocaleDataIndex["ExtraData"] = 21] = "ExtraData";
})(LocaleDataIndex || (LocaleDataIndex = {}));
/**
 * Register locale data to be used internally by Angular. See the
 * ["I18n guide"](guide/i18n#i18n-pipes) to know how to import additional locale data.
 *
 * The signature `registerLocaleData(data: any, extraData?: any)` is deprecated since v5.1
 */
function registerLocaleData(data, localeId, extraData) {
    if (typeof localeId !== 'string') {
        extraData = localeId;
        localeId = data[LocaleDataIndex.LocaleId];
    }
    localeId = localeId.toLowerCase().replace(/_/g, '-');
    LOCALE_DATA[localeId] = data;
    if (extraData) {
        LOCALE_DATA[localeId][LocaleDataIndex.ExtraData] = extraData;
    }
}
/**
 * Finds the locale data for a given locale.
 *
 * @param locale The locale code.
 * @returns The locale data.
 * @see [Internationalization (i18n) Guide](https://angular.io/guide/i18n)
 */
function findLocaleData(locale) {
    const normalizedLocale = normalizeLocale(locale);
    let match = getLocaleData(normalizedLocale);
    if (match) {
        return match;
    }
    // let's try to find a parent locale
    const parentLocale = normalizedLocale.split('-')[0];
    match = getLocaleData(parentLocale);
    if (match) {
        return match;
    }
    if (parentLocale === 'en') {
        return localeEn;
    }
    throw new Error(`Missing locale data for the locale "${locale}".`);
}
/**
 * Helper function to get the given `normalizedLocale` from `LOCALE_DATA`
 * or from the global `ng.common.locale`.
 */
function getLocaleData(normalizedLocale) {
    return LOCALE_DATA[normalizedLocale];
}
/**
 * Returns the canonical form of a locale name - lowercase with `_` replaced with `-`.
 */
function normalizeLocale(locale) {
    return locale.toLowerCase().replace(/_/g, '-');
}

/**
 * 英文 shortNumber 基础配置
 */
var enUS = {
    lang: 'en-US',
    shortNumberFactor: 3,
    shortNumberUnits: 'K,M,B,T,Q'
};

/**
 * 中文 shortNumber 基础配置
 */
var zhHans = {
    lang: 'zh-Hans',
    shortNumberFactor: 4,
    shortNumberUnits: '万,亿,万亿',
    DateVariable: {
        [DateVariableEnum.SYSTEMTIME]: '系统时间',
        [DateVariableEnum.TODAY]: '当前日期',
        [DateVariableEnum.YESTERDAY]: '昨天',
        [DateVariableEnum.DBY]: '前天',
        [DateVariableEnum.DAYS_7_AGO]: '七天前',
        [DateVariableEnum.DAYS_8_AGO]: '八天前',
        [DateVariableEnum.DAYS_14_AGO]: '十四天前',
        [DateVariableEnum.DAYS_15_AGO]: '十五天前',
        [DateVariableEnum.DAYS_30_AGO]: '三十天前',
        [DateVariableEnum.DAYS_31_AGO]: '三十一天前',
        [DateVariableEnum.RECENT_7_DAYS]: '最近七天',
        [DateVariableEnum.RECENT_14_DAYS]: '最近十四天',
        [DateVariableEnum.RECENT_30_DAYS]: '最近三十天',
        [DateVariableEnum.RECENT_90_DAYS]: '最近九十天',
        [DateVariableEnum.RECENT_180_DAYS]: '最近一百八十天',
        [DateVariableEnum.THIS_WEEK]: '本周',
        [DateVariableEnum.THIS_MONTH]: '本月',
        [DateVariableEnum.PREVIOUS_MONTH]: '上月',
        [DateVariableEnum.THIS_QUARTER]: '本季度',
        [DateVariableEnum.YEAR_TO_TODAY]: '当前年至当天',
        [DateVariableEnum.YEAR_TO_YESTERDAY]: '当前年至昨天',
        [DateVariableEnum.THIS_WHOLE_WEEK]: '本周(包含整周)',
        [DateVariableEnum.THIS_WHOLE_MONTH]: '本月(包含整月)',
        [DateVariableEnum.THIS_WHOLE_QUARTER]: '本季度(包含整季度)',
        [DateVariableEnum.THIS_WHOLE_YEAR]: '今年(包含整年)',
        [DateVariableEnum.PREVIOUS_YEAR]: '去年'
    },
    NgCore: {
        Widget: {
            Rank: '排名',
            Top: '前'
        }
    }
};

/**
 * 中文 shortNumber 基礎配置
 */
var zhHant = {
    lang: 'zh-Hant',
    shortNumberFactor: 4,
    shortNumberUnits: '萬,億,萬億',
    DateVariable: {
        [DateVariableEnum.SYSTEMTIME]: '系統時間',
        [DateVariableEnum.TODAY]: '當前日期',
        [DateVariableEnum.YESTERDAY]: '昨天',
        [DateVariableEnum.DBY]: '前天',
        [DateVariableEnum.DAYS_7_AGO]: '七天前',
        [DateVariableEnum.DAYS_8_AGO]: '八天前',
        [DateVariableEnum.DAYS_14_AGO]: '十四天前',
        [DateVariableEnum.DAYS_15_AGO]: '十五天前',
        [DateVariableEnum.DAYS_30_AGO]: '三十天前',
        [DateVariableEnum.DAYS_31_AGO]: '三十一天前',
        [DateVariableEnum.RECENT_7_DAYS]: '最近七天',
        [DateVariableEnum.RECENT_14_DAYS]: '最近十四天',
        [DateVariableEnum.RECENT_30_DAYS]: '最近三十天',
        [DateVariableEnum.RECENT_90_DAYS]: '最近九十天',
        [DateVariableEnum.RECENT_180_DAYS]: '最近一百八十天',
        [DateVariableEnum.THIS_WEEK]: '本周',
        [DateVariableEnum.THIS_MONTH]: '本月',
        [DateVariableEnum.PREVIOUS_MONTH]: '上月',
        [DateVariableEnum.THIS_QUARTER]: '本季度',
        [DateVariableEnum.YEAR_TO_TODAY]: '當前年至當天',
        [DateVariableEnum.YEAR_TO_YESTERDAY]: '當前年至昨天',
        [DateVariableEnum.THIS_WHOLE_WEEK]: '本周(包含整周)',
        [DateVariableEnum.THIS_WHOLE_MONTH]: '本月(包含整月)',
        [DateVariableEnum.THIS_WHOLE_QUARTER]: '本季度(包含整季度)',
        [DateVariableEnum.THIS_WHOLE_YEAR]: '今年(包含整年)',
        [DateVariableEnum.PREVIOUS_YEAR]: '去年'
    },
    NgCore: {
        Widget: {
            Rank: '排名',
            Top: '前'
        }
    }
};

function mapLangToLocale(lang) {
    switch (lang) {
        case 'en':
            return 'en-US';
        case 'zh':
        case 'zh-CN':
            return 'zh-Hans';
        default:
            return lang;
    }
}

/**
 * Creates an effect.
 *
 * This effect is subscribed to throughout the lifecycle of the ComponentStore.
 * @param generator A function that takes an origin Observable input and
 *     returns an Observable. The Observable that is returned will be
 *     subscribed to for the life of the component.
 * @return A function that, when called, will trigger the origin Observable.
 */
function effectAction(generator) {
    const _destroyed$ = takeUntilDestroyed();
    const origin$ = new Subject();
    generator(origin$)
        // tied to the lifecycle 👇 of ComponentStore
        .pipe(_destroyed$)
        .subscribe();
    return ((observableOrValue) => {
        const observable$ = isObservable(observableOrValue)
            ? observableOrValue
            : of(observableOrValue);
        return observable$.pipe(_destroyed$).subscribe((value) => {
            // any new 👇 value is pushed into a stream
            origin$.next(value);
        });
    });
}

function createEventEmitter(observable, options) {
    const { unsubscribe, isAsync } = options || {};
    const emitter = new EventEmitter(isAsync === true);
    let obs = observable.pipe(tap((val) => emitter.next(val)));
    if (unsubscribe != null) {
        obs = obs.pipe(takeUntil(unsubscribe));
    }
    obs.subscribe();
    return emitter;
}

function makeid(length) {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
    const characters = chars + '0123456789';
    const charactersLength = characters.length;
    // 首字母为英文字符
    let result = chars.charAt(Math.floor(Math.random() * chars.length));
    for (let i = 0; i < length - 1; i++) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
    }
    return result;
}

/**
 * @hidden
 * @internal
 *
 * Creates a new ResizeObserver on `target` and returns it as an Observable.
 * Run the resizeObservable outside angular zone, because it patches the MutationObserver which causes an infinite loop.
 * Related issue: https://github.com/angular/angular/issues/31712
 */
function resizeObservable(target) {
    return new Observable((observer) => {
        const instance = new ResizeObserver((entries) => {
            observer.next(entries);
        });
        instance.observe(target);
        const unsubscribe = () => instance.disconnect();
        return unsubscribe;
    });
}

var NgmFormatNumberStyle;
(function (NgmFormatNumberStyle) {
    NgmFormatNumberStyle["short"] = "short";
    NgmFormatNumberStyle["standard"] = "standard";
    NgmFormatNumberStyle["long"] = "long";
})(NgmFormatNumberStyle || (NgmFormatNumberStyle = {}));
var NgmRoundingMode;
(function (NgmRoundingMode) {
    NgmRoundingMode["none"] = "none";
    NgmRoundingMode["ceil"] = "ceil";
    NgmRoundingMode["floor"] = "floor";
    NgmRoundingMode["round"] = "round";
})(NgmRoundingMode || (NgmRoundingMode = {}));
const FORMATOPTIONS = {
    decimals: 2, // 保留几个小数
    // shortDecimals: 2,
    // shortLimit: 1000, // 大于此参数的才进行short
    shortRefNumber: undefined, // 用户自定义的比例因子,默认按照语言文件里面
    // style: NgmFormatNumberStyle.short, // 默认 short 类型 为 short
    // roundingMode: NgmRoundingMode.none, // 舍入行为
    // Delimiter: ',', // 分隔符
    // showDelimiter: true, // 是否启用分隔符
    isformatNumber: true,
};
/**
 * Ref to [CurrencyPipe](https://github.com/angular/angular/blob/11.2.13/packages/common/src/pipes/number_pipe.ts#L163-L287)
 */
class NgmShortNumberPipe {
    constructor(_locale) {
        this._locale = _locale;
    }
    transform(value, locale, factor, shortUnits) {
        if (value === null || value === undefined) {
            return null;
        }
        return formatShortNumber(value, locale || this._locale, Number(factor), shortUnits);
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NgmShortNumberPipe, deps: [{ token: LOCALE_ID }], target: i0.ɵɵFactoryTarget.Pipe }); }
    static { this.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "17.3.12", ngImport: i0, type: NgmShortNumberPipe, isStandalone: true, name: "shortNumber" }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NgmShortNumberPipe, decorators: [{
            type: Pipe,
            args: [{
                    standalone: true,
                    name: 'shortNumber',
                }]
        }], ctorParameters: () => [{ type: undefined, decorators: [{
                    type: Inject,
                    args: [LOCALE_ID]
                }] }] });
/**
 * shorNumber
 * @param value 传入的需要进行 short 的数据
 *
 * @returns null 或者 short结果数组 (例如: ['4.53', 'K'] ['5.62', '万'])
 */
function formatShortNumber(value, locale, factor, shortUnits) {
    try {
        const num = strToNumber(value);
        const localeData = findLocaleData(locale);
        factor = factor || localeData?.shortNumberFactor;
        shortUnits = shortUnits || localeData?.shortNumberUnits;
        let resultValue = num;
        let resultName = '';
        const units = shortUnits?.split(',').reverse();
        units?.every((unitName, i) => {
            const rounder = Math.pow(10, (units.length - i) * factor);
            if (Math.abs(num) >= rounder) {
                resultValue = num / rounder;
                resultName = unitName;
                return false;
            }
            return true;
        });
        return [Number(resultValue), resultName];
    }
    catch (error) {
        throw invalidPipeArgumentError(DecimalPipe, error.message);
    }
}
/**
 * Transforms a string into a number (if needed).
 */
function strToNumber(value) {
    // Convert strings to numbers
    if (typeof value === 'string' && !isNaN(Number(value) - parseFloat(value))) {
        return Number(value);
    }
    if (typeof value !== 'number') {
        throw new Error(`${value} is not a number`);
    }
    return value;
}
function invalidPipeArgumentError(type, value) {
    return Error(`InvalidPipeArgument: '${value}' for pipe '${stringify(type)}'`);
}
/**
 * @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.io/license
 */
function stringify(token) {
    if (typeof token === 'string') {
        return token;
    }
    if (Array.isArray(token)) {
        return '[' + token.map(stringify).join(', ') + ']';
    }
    if (token == null) {
        return '' + token;
    }
    if (token.overriddenName) {
        return `${token.overriddenName}`;
    }
    if (token.name) {
        return `${token.name}`;
    }
    const res = token.toString();
    if (res == null) {
        return '' + res;
    }
    const newLineIndex = res.indexOf('\n');
    return newLineIndex === -1 ? res : res.substring(0, newLineIndex);
}
/**
 * Concatenates two strings with separator, allocating new strings only when necessary.
 *
 * @param before before string.
 * @param separator separator string.
 * @param after after string.
 * @returns concatenated string.
 */
function concatStringsWithSpace(before, after) {
    return (before == null || before === '') ?
        (after === null ? '' : after) :
        ((after == null || after === '') ? before : before + ' ' + after);
}

class OmitBlankPipe {
    transform(value) {
        if (value === null || value === undefined) {
            return null;
        }
        return omitBlank$1(value);
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: OmitBlankPipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe }); }
    static { this.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "17.3.12", ngImport: i0, type: OmitBlankPipe, isStandalone: true, name: "omitBlank" }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: OmitBlankPipe, decorators: [{
            type: Pipe,
            args: [{
                    standalone: true,
                    name: 'omitBlank'
                }]
        }] });

class NgmI18nPipe {
    constructor() {
        this.translate = inject(TranslateService);
    }
    transform(value) {
        if (typeof value === 'string') {
            return value;
        }
        else if (typeof value === 'object' && value !== null) {
            return value[mapLanguage(this.translate.currentLang)] ?? value['en_US'];
        }
        else {
            return (value ?? '');
        }
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NgmI18nPipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe }); }
    static { this.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "17.3.12", ngImport: i0, type: NgmI18nPipe, isStandalone: true, name: "i18n" }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NgmI18nPipe, decorators: [{
            type: Pipe,
            args: [{
                    standalone: true,
                    name: 'i18n'
                }]
        }] });
function mapLanguage(l) {
    switch (l) {
        case NgmLanguageEnum.Chinese:
        case NgmLanguageEnum.SimplifiedChinese:
        case NgmLanguageEnum.TraditionalChinese:
            return 'zh_Hans';
        default:
            return 'en_US';
    }
}

class NgmIsNilPipe {
    transform(value, text) {
        return value == null || value == undefined ? text ?? value : value;
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NgmIsNilPipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe }); }
    static { this.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "17.3.12", ngImport: i0, type: NgmIsNilPipe, isStandalone: true, name: "isNil" }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: NgmIsNilPipe, decorators: [{
            type: Pipe,
            args: [{
                    standalone: true,
                    name: 'isNil'
                }]
        }] });

class RelativeTimesPipe {
    constructor() {
        this.destroyRef = inject(DestroyRef);
        this.injector = inject(Injector);
        this.period$ = new BehaviorSubject(1000); // Default period of 1 second
        this.now$ = toSignal(this.period$.pipe(switchMap((period) => interval(period)), startWith(0), map(() => Date.now())), { initialValue: Date.now(), manualCleanup: true });
        this.destroyRef.onDestroy(() => {
            // Manually clean up the observables subscribed in now$
            this.now$.destroy?.();
        });
    }
    transform(value, period) {
        if (!value)
            return null;
        const inputTime = new Date(value).getTime();
        if (isNaN(inputTime))
            return null;
        if (this.period$.value !== period) {
            this.period$.next(period);
        }
        const now = this.now$(); // Get the current timestamp from signal
        return (Math.floor((now - inputTime) / this.period$.value) * this.period$.value) / 1000;
    }
    static { this.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: RelativeTimesPipe, deps: [], target: i0.ɵɵFactoryTarget.Pipe }); }
    static { this.ɵpipe = i0.ɵɵngDeclarePipe({ minVersion: "14.0.0", version: "17.3.12", ngImport: i0, type: RelativeTimesPipe, isStandalone: true, name: "relativeTimes", pure: false }); }
}
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "17.3.12", ngImport: i0, type: RelativeTimesPipe, decorators: [{
            type: Pipe,
            args: [{
                    name: 'relativeTimes',
                    standalone: true,
                    pure: false // Non-pure pipeline, supports updates every second
                }]
        }], ctorParameters: () => [] });

const TailwindThemeVars = {
    // https://daisyui.com/docs/colors/
    'base-content': 'var(--color-base-content)',
    // Custom colors
    'text-primary': 'var(--color-text-primary)',
    'text-secondary': 'var(--color-text-secondary)',
    'text-tertiary': 'var(--color-text-tertiary)',
    'text-quaternary': 'var(--color-text-quaternary)',
    'text-destructive': 'var(--color-text-destructive)',
    'text-success': 'var(--color-text-success)',
    'text-warning': 'var(--color-text-warning)',
    'text-destructive-secondary': 'var(--color-text-destructive-secondary)',
    'text-success-secondary': 'var(--color-text-success-secondary)',
    'text-warning-secondary': 'var(--color-text-warning-secondary)',
    'text-accent': 'var(--color-text-accent)',
    'text-primary-on-surface': 'var(--color-text-primary-on-surface)',
    'text-placeholder': 'var(--color-text-placeholder)',
    'text-disabled': 'var(--color-text-disabled)',
    'text-accent-secondary': 'var(--color-text-accent-secondary)',
    'text-accent-light-mode-only': 'var(--color-text-accent-light-mode-only)',
    'text-text-selected': 'var(--color-text-text-selected)',
    'text-secondary-on-surface': 'var(--color-text-secondary-on-surface)',
    'text-logo-text': 'var(--color-text-logo-text)',
    'text-empty-state-icon': 'var(--color-text-empty-state-icon)',
    'text-inverted': 'var(--color-text-inverted)',
    'divider-subtle': 'var(--color-divider-subtle)',
    'divider-regular': 'var(--color-divider-regular)',
    'divider-deep': 'var(--color-divider-deep)',
    'divider-burn': 'var(--color-divider-burn)',
    'divider-intense': 'var(--color-divider-intense)',
    'divider-solid': 'var(--color-divider-solid)',
    'divider-solid-alt': 'var(--color-divider-solid-alt)',
    'hover-bg': 'var(--color-hover-bg)',
    'danger-bg': 'var(--color-danger-bg)',
    'token-main-surface-primary': 'var(--main-surface-primary)',
    'token-main-surface-secondary': 'var(--main-surface-secondary)',
    'token-main-surface-low': 'var(--ngm-color-surface-container-low)',
    'token-text-secondary': 'var(--text-secondary)',
    'token-border-medium': 'var(--border-medium)',
    'token-border-light': 'var(--border-light)',
    'components-card-option-selected-border': 'var(--components-card-option-selected-border)',
    'components-card-bg': 'var(--color-components-card-bg)',
    'components-panel-bg': 'var(--color-components-panel-bg)',
    'components-panel-border': 'var(--color-components-panel-border)',
    'components-button-primary-text': 'var(--color-components-button-primary-text)',
    'components-button-primary-border': 'var(--color-components-button-primary-border)',
    'components-button-primary-bg': 'var(--color-components-button-primary-bg)',
    'components-input-bg': 'var(--color-components-input-bg)',
    'components-list-option-bg': 'var(--color-components-list-option-bg)',
    'components-list-option-active-bg': 'var(--color-components-list-option-active-bg)',
};

function linkedModel(options) {
    const { initialValue, compute, update } = options;
    const internalState = computed(compute);
    let currentValue = initialValue;
    const derived = signal(initialValue);
    // Use effect to automatically synchronize
    effect(() => {
        currentValue = internalState();
        derived.set(currentValue);
    }, { allowSignalWrites: true });
    effect(() => {
        if (derived() !== currentValue) {
            update(derived(), currentValue);
            currentValue = derived();
        }
    }, { allowSignalWrites: true });
    return derived;
}
function attrModel(model, name, initialValue = null) {
    return linkedModel({
        initialValue,
        compute: () => model()?.[name],
        update: (value) => {
            model.update((state) => ({ ...(state ?? {}), [name]: value }));
        }
    });
}

function bindFormControlToSignal(formControl, signal) {
    // Sync formControl → signal
    const sub = formControl.valueChanges
        .pipe(startWith(formControl.value), distinctUntilChanged())
        .subscribe((val) => {
        // Avoid unnecessary updates
        if (val !== signal()) {
            signal.set(val);
        }
    });
    // Sync signal → formControl
    effect(() => {
        const current = signal();
        if (formControl.value !== current) {
            formControl.setValue(current); // prevent loop
        }
    });
    // Optional: return unsubscribe function
    return () => sub.unsubscribe();
}

/**
 * @deprecated Will be replaced by the official `Resource` after upgrading to Angular 19
 */
function myResource(options) {
    const valueSig = signal(null);
    const errorSig = signal(null);
    const statusSig = signal('idle');
    const refreshTrigger = signal(0);
    const requestSig = computed(() => {
        // 使用 refreshTrigger 使得 refresh 时也会重新请求
        refreshTrigger();
        return options.request();
    });
    // 自动 effect 监控 requestSig 变化，执行 loader
    effect(() => {
        const requestVal = requestSig();
        statusSig.set('loading');
        errorSig.set(null);
        options
            .loader({ request: untracked(() => requestVal) }) // 避免循环依赖
            .then((res) => {
            valueSig.set(res);
            statusSig.set('success');
        })
            .catch((err) => {
            errorSig.set(err);
            statusSig.set('error');
        });
    }, { allowSignalWrites: true });
    return {
        value: computed(() => valueSig()),
        error: computed(() => errorSig()),
        status: computed(() => statusSig()),
        reload: () => refreshTrigger.set(refreshTrigger() + 1)
    };
}
/**
 *
 * @deprecated Will be replaced by the official `Resource` after upgrading to Angular 19
 */
function myRxResource(options) {
    const valueSig = signal(null);
    const errorSig = signal(null);
    const statusSig = signal('idle');
    const refreshTrigger = signal(0);
    const requestSig = computed(() => {
        refreshTrigger();
        return options.request();
    });
    let currentSub = null;
    // 保证资源释放（避免订阅泄漏）
    const destroyRef = inject(DestroyRef);
    effect(() => {
        const req = requestSig();
        statusSig.set('loading');
        errorSig.set(null);
        // 取消上一个订阅
        if (currentSub) {
            currentSub.unsubscribe();
        }
        const obs$ = options.loader({ request: untracked(() => req) });
        currentSub = obs$.subscribe({
            next: (res) => {
                valueSig.set(res);
                statusSig.set('success');
            },
            error: (err) => {
                errorSig.set(err);
                statusSig.set('error');
            }
        });
    }, { allowSignalWrites: true });
    // 注销组件时，清理订阅
    destroyRef.onDestroy(() => {
        if (currentSub) {
            currentSub.unsubscribe();
        }
    });
    return {
        value: computed(() => valueSig()),
        error: computed(() => errorSig()),
        status: computed(() => statusSig()),
        reload: () => refreshTrigger.set(refreshTrigger() + 1)
    };
}

function debouncedSignal(sourceSignal, debounceTimeInMs = 0) {
    const source$ = toObservable(sourceSignal);
    const debounced$ = source$.pipe(debounceTime(debounceTimeInMs));
    return toSignal(debounced$, {
        initialValue: sourceSignal(),
    });
}

/**
 * Generated bundle index. Do not edit.
 */

export { AppearanceDirective, ButtonClickEvents, ButtonGroupDirective, DateVariableEnum, DensityDirective, DisplayDensity, EntityCapacity, FORMATOPTIONS, KEYCODES, KEYS, LocaleDataIndex, NAVIGATION_KEYS, NGM_DATE_VARIABLES, NX_DATE_VARIABLES_FACTORY, NgmAgentService, NgmDSCacheService, NgmDSCoreService, NgmDensityDirective, NgmFormatNumberStyle, NgmI18nPipe, NgmIsNilPipe, NgmLanguageEnum, NgmMissingTranslationHandler, NgmOcapCoreService, NgmRoundingMode, NgmShortNumberPipe, NgmSmartBusinessService, NgmSmartFilterBarService, NgmThemeService, NgmTooltipDirective, OCAP_AGENT_TOKEN, OCAP_DATASOURCE_TOKEN, OCAP_MODEL_TOKEN, OcapCoreModule, OmitBlankPipe, PERIODS, ROW_COLLAPSE_KEYS, ROW_EXPAND_KEYS, RelativeTimesPipe, SUPPORTED_KEYS, TIME_GRANULARITY_SEQUENCES, TailwindThemeVars, ThemesEnum, TreeSelectionMode, attrModel, bindFormControlToSignal, click, cloneArray, cloneHierarchicalArray, cloneValue, concatStringsWithSpace, convertToBoolProperty, createEventEmitter, csvDownload, debouncedSignal, effectAction, enUS, fadeAnimation, filterNil, filterSearch, findLocaleData, formatShortNumber, getErrorMessage, getLocaleData, getNodeSizeViaRange, includeIgnoreCase, injectTranslate, invalidPipeArgumentError, isBlank, isDate, isEdge, isFirefox, isIE, isLeftClick, isNavigationKey, isNotEmpty, isNotEqual, isNotNil, isObject, linkedModel, makeid, mapLangToLocale, mergeObjects, mergeOptions, mkenum, myResource, myRxResource, nonBlank, omitBlank, prefersColorScheme, provideFadeAnimation, provideOcapCore, registerLocaleData, resizeObservable, splitByHighlight, stringify, toParams, zhHans, zhHant };
//# sourceMappingURL=metad-ocap-angular-core.mjs.map
