├── src
├── assets
│ └── .gitkeep
├── app
│ ├── app.component.less
│ ├── app.module.ts
│ ├── app.component.html
│ ├── app.component.spec.ts
│ └── app.component.ts
├── environments
│ ├── environment.prod.ts
│ └── environment.ts
├── favicon.ico
├── styles.less
├── tsconfig.app.json
├── tsconfig.spec.json
├── index.html
├── tslint.json
├── main.ts
├── test.ts
├── karma.conf.js
└── polyfills.ts
├── .prettierrc
├── projects
└── angular-page-visibility-lib
│ ├── tsconfig.lib.prod.json
│ ├── src
│ ├── lib
│ │ ├── angular-page-visibility.state.enum.ts
│ │ ├── angular-page-visibility.module.ts
│ │ ├── angular-page-visibility.service.spec.ts
│ │ ├── angular-page-visibility.service.ts
│ │ └── angular-page-visibility.decorators.ts
│ ├── public_api.ts
│ └── test.ts
│ ├── ng-package.prod.json
│ ├── ng-package.json
│ ├── tsconfig.spec.json
│ ├── tslint.json
│ ├── tsconfig.lib.json
│ ├── package.json
│ └── karma.conf.js
├── wiki
├── angular-page-vsibility-state.enum.md
├── on-page-unloaded.decorator.md
├── on-page-prerender.decorator.md
├── on-page-hidden.decorator.md
├── on-page-visible.decorator.md
├── on-page-visibility-change.decorator.md
└── page-visibility.service.md
├── e2e
├── src
│ ├── app.po.ts
│ └── app.e2e-spec.ts
├── tsconfig.e2e.json
└── protractor.conf.js
├── .editorconfig
├── .versionrc.json
├── browserslist
├── .github
└── workflows
│ ├── ci-workflow.yml
│ ├── to-release-major-workflow.yml
│ ├── to-release-minor-workflow.yml
│ └── to-release-patch-workflow.yml
├── tsconfig.json
├── .gitignore
├── LICENSE
├── CHANGELOG.md
├── package.json
├── tslint.json
├── README.md
└── angular.json
/src/assets/.gitkeep:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/src/app/app.component.less:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/.prettierrc:
--------------------------------------------------------------------------------
1 | {
2 | "singleQuote": true,
3 | "trailingComma": "all"
4 | }
5 |
--------------------------------------------------------------------------------
/src/environments/environment.prod.ts:
--------------------------------------------------------------------------------
1 | export const environment = {
2 | production: true
3 | };
4 |
--------------------------------------------------------------------------------
/src/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/olivierlsc/angular-page-visibility/HEAD/src/favicon.ico
--------------------------------------------------------------------------------
/src/styles.less:
--------------------------------------------------------------------------------
1 | /* You can add global styles to this file, and also import other style files */
2 |
--------------------------------------------------------------------------------
/projects/angular-page-visibility-lib/tsconfig.lib.prod.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "./tsconfig.lib.json",
3 | "angularCompilerOptions": {
4 | "enableIvy": false
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/projects/angular-page-visibility-lib/src/lib/angular-page-visibility.state.enum.ts:
--------------------------------------------------------------------------------
1 | export enum AngularPageVisibilityStateEnum {
2 | VISIBLE,
3 | HIDDEN,
4 | PRERENDER,
5 | UNLOADED
6 | }
7 |
--------------------------------------------------------------------------------
/wiki/angular-page-vsibility-state.enum.md:
--------------------------------------------------------------------------------
1 | # AngularPageVisibilityStateEnum
2 |
3 | Enum contains all visibility status.
4 |
5 | ## VISIBLE
6 |
7 | ## HIDDEN
8 |
9 | ## PRERENDER
10 |
11 | ## UNLOADED
12 |
--------------------------------------------------------------------------------
/projects/angular-page-visibility-lib/ng-package.prod.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "../../node_modules/ng-packagr/ng-package.schema.json",
3 | "dest": "../../dist/angular-page-visibility",
4 | "lib": {
5 | "entryFile": "src/public_api.ts"
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/e2e/src/app.po.ts:
--------------------------------------------------------------------------------
1 | import { browser, by, element } from 'protractor';
2 |
3 | export class AppPage {
4 | navigateTo() {
5 | return browser.get('/');
6 | }
7 |
8 | getParagraphText() {
9 | return element(by.css('app-root h1')).getText();
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/projects/angular-page-visibility-lib/ng-package.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "../../node_modules/ng-packagr/ng-package.schema.json",
3 | "dest": "../../dist/angular-page-visibility",
4 | "deleteDestPath": false,
5 | "lib": {
6 | "entryFile": "src/public_api.ts"
7 | }
8 | }
9 |
--------------------------------------------------------------------------------
/e2e/tsconfig.e2e.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../tsconfig.json",
3 | "compilerOptions": {
4 | "outDir": "../out-tsc/app",
5 | "module": "commonjs",
6 | "target": "es5",
7 | "types": [
8 | "jasmine",
9 | "jasminewd2",
10 | "node"
11 | ]
12 | }
13 | }
--------------------------------------------------------------------------------
/src/tsconfig.app.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../tsconfig.json",
3 | "compilerOptions": {
4 | "outDir": "../out-tsc/app",
5 | "types": []
6 | },
7 | "files": [
8 | "main.ts",
9 | "polyfills.ts"
10 | ],
11 | "include": [
12 | "src/**/*.d.ts"
13 | ]
14 | }
15 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | # Editor configuration, see http://editorconfig.org
2 | root = true
3 |
4 | [*]
5 | charset = utf-8
6 | indent_style = space
7 | indent_size = 2
8 | insert_final_newline = true
9 | trim_trailing_whitespace = true
10 |
11 | [*.md]
12 | max_line_length = off
13 | trim_trailing_whitespace = false
14 |
--------------------------------------------------------------------------------
/.versionrc.json:
--------------------------------------------------------------------------------
1 | {
2 | "bumpFiles": [
3 | {
4 | "filename": "package.json",
5 | "type": "json"
6 | },
7 | {
8 | "filename": "package-lock.json",
9 | "type": "json"
10 | },
11 | {
12 | "filename": "projects/angular-page-visibility-lib/package.json",
13 | "type": "json"
14 | }
15 | ]
16 | }
17 |
--------------------------------------------------------------------------------
/projects/angular-page-visibility-lib/src/public_api.ts:
--------------------------------------------------------------------------------
1 | /*
2 | * Public API Surface of angular-page-visibility-lib
3 | */
4 |
5 | export * from './lib/angular-page-visibility.state.enum';
6 | export * from './lib/angular-page-visibility.service';
7 | export* from './lib/angular-page-visibility.decorators';
8 | export * from './lib/angular-page-visibility.module';
9 |
--------------------------------------------------------------------------------
/src/tsconfig.spec.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../tsconfig.json",
3 | "compilerOptions": {
4 | "outDir": "../out-tsc/spec",
5 | "types": [
6 | "jasmine",
7 | "node"
8 | ]
9 | },
10 | "files": [
11 | "test.ts",
12 | "polyfills.ts"
13 | ],
14 | "include": [
15 | "**/*.spec.ts",
16 | "**/*.d.ts"
17 | ]
18 | }
19 |
--------------------------------------------------------------------------------
/projects/angular-page-visibility-lib/tsconfig.spec.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../../tsconfig.json",
3 | "compilerOptions": {
4 | "outDir": "../../out-tsc/spec",
5 | "types": [
6 | "jasmine",
7 | "node"
8 | ]
9 | },
10 | "files": [
11 | "src/test.ts"
12 | ],
13 | "include": [
14 | "**/*.spec.ts",
15 | "**/*.d.ts"
16 | ]
17 | }
18 |
--------------------------------------------------------------------------------
/src/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | AngularPageVisibilityApp
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
--------------------------------------------------------------------------------
/projects/angular-page-visibility-lib/src/lib/angular-page-visibility.module.ts:
--------------------------------------------------------------------------------
1 | import { NgModule } from '@angular/core';
2 | import { AngularPageVisibilityService } from './angular-page-visibility.service';
3 |
4 | @NgModule({
5 | imports: [],
6 | declarations: [],
7 | providers: [AngularPageVisibilityService],
8 | exports: []
9 | })
10 | export class AngularPageVisibilityModule { }
11 |
--------------------------------------------------------------------------------
/e2e/src/app.e2e-spec.ts:
--------------------------------------------------------------------------------
1 | import { AppPage } from './app.po';
2 |
3 | describe('workspace-project App', () => {
4 | let page: AppPage;
5 |
6 | beforeEach(() => {
7 | page = new AppPage();
8 | });
9 |
10 | it('should display welcome message', () => {
11 | page.navigateTo();
12 | expect(page.getParagraphText()).toEqual('Welcome to angular-page-visibility-app!');
13 | });
14 | });
15 |
--------------------------------------------------------------------------------
/src/tslint.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../tslint.json",
3 | "rules": {
4 | "directive-selector": [
5 | true,
6 | "attribute",
7 | "app",
8 | "camelCase"
9 | ],
10 | "component-selector": [
11 | true,
12 | "element",
13 | "app",
14 | "kebab-case"
15 | ]
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/browserslist:
--------------------------------------------------------------------------------
1 | # This file is currently used by autoprefixer to adjust CSS to support the below specified browsers
2 | # For additional information regarding the format and rule options, please see:
3 | # https://github.com/browserslist/browserslist#queries
4 | # For IE 9-11 support, please uncomment the last line of the file and adjust as needed
5 | > 0.5%
6 | last 2 versions
7 | Firefox ESR
8 | not dead
9 | # IE 9-11
--------------------------------------------------------------------------------
/src/main.ts:
--------------------------------------------------------------------------------
1 | import { enableProdMode } from '@angular/core';
2 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
3 |
4 | import { AppModule } from './app/app.module';
5 | import { environment } from './environments/environment';
6 |
7 | if (environment.production) {
8 | enableProdMode();
9 | }
10 |
11 | platformBrowserDynamic().bootstrapModule(AppModule)
12 | .catch(err => console.log(err));
13 |
--------------------------------------------------------------------------------
/projects/angular-page-visibility-lib/tslint.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../../tslint.json",
3 | "rules": {
4 | "directive-selector": [
5 | true,
6 | "attribute",
7 | "apvl",
8 | "camelCase"
9 | ],
10 | "component-selector": [
11 | true,
12 | "element",
13 | "apvl",
14 | "kebab-case"
15 | ]
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/.github/workflows/ci-workflow.yml:
--------------------------------------------------------------------------------
1 | name: CI
2 | on:
3 | push:
4 | branches:
5 | - master
6 | pull_request:
7 | branches:
8 | - master
9 | jobs:
10 | build:
11 | runs-on: ubuntu-latest
12 | steps:
13 | - name: Checks-out repository
14 | uses: actions/checkout@v2
15 | - name: Install
16 | run: |
17 | npm install
18 | - name: Build
19 | run: |
20 | npm run build:lib
21 |
--------------------------------------------------------------------------------
/src/app/app.module.ts:
--------------------------------------------------------------------------------
1 | import { BrowserModule } from '@angular/platform-browser';
2 | import { NgModule } from '@angular/core';
3 | import { AppComponent } from './app.component';
4 | import { AngularPageVisibilityModule } from 'angular-page-visibility';
5 |
6 | @NgModule({
7 | declarations: [
8 | AppComponent
9 | ],
10 | imports: [
11 | BrowserModule,
12 | AngularPageVisibilityModule
13 | ],
14 | providers: [],
15 | bootstrap: [AppComponent]
16 | })
17 | export class AppModule { }
18 |
--------------------------------------------------------------------------------
/projects/angular-page-visibility-lib/src/lib/angular-page-visibility.service.spec.ts:
--------------------------------------------------------------------------------
1 | import { TestBed, inject } from '@angular/core/testing';
2 | import { AngularPageVisibilityService } from './angular-page-visibility.service';
3 |
4 | describe('AngularPageVisibilityLibService', () => {
5 | beforeEach(() => {
6 | TestBed.configureTestingModule({
7 | providers: [AngularPageVisibilityService]
8 | });
9 | });
10 |
11 | it('should be created', inject([AngularPageVisibilityService], (service: AngularPageVisibilityService) => {
12 | expect(service).toBeTruthy();
13 | }));
14 | });
15 |
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compileOnSave": false,
3 | "compilerOptions": {
4 | "baseUrl": "./",
5 | "downlevelIteration": true,
6 | "outDir": "./dist/out-tsc",
7 | "sourceMap": true,
8 | "declaration": false,
9 | "module": "esnext",
10 | "moduleResolution": "node",
11 | "emitDecoratorMetadata": true,
12 | "experimentalDecorators": true,
13 | "target": "es5",
14 | "typeRoots": ["node_modules/@types"],
15 | "lib": ["es2017", "dom"],
16 | "paths": {
17 | "angular-page-visibility": ["dist/angular-page-visibility"],
18 | "angular-page-visibility/*": ["dist/angular-page-visibility/*"]
19 | }
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # See http://help.github.com/ignore-files/ for more about ignoring files.
2 |
3 | # compiled output
4 | /dist
5 | /tmp
6 | /out-tsc
7 |
8 | # dependencies
9 | /node_modules
10 |
11 | # IDEs and editors
12 | /.idea
13 | .project
14 | .classpath
15 | .c9/
16 | *.launch
17 | .settings/
18 | *.sublime-workspace
19 |
20 | # IDE - VSCode
21 | .vscode/*
22 | !.vscode/settings.json
23 | !.vscode/tasks.json
24 | !.vscode/launch.json
25 | !.vscode/extensions.json
26 |
27 | # misc
28 | /.sass-cache
29 | /connect.lock
30 | /coverage
31 | /libpeerconnection.log
32 | npm-debug.log
33 | yarn-error.log
34 | testem.log
35 | /typings
36 |
37 | # System Files
38 | .DS_Store
39 | Thumbs.db
40 |
--------------------------------------------------------------------------------
/wiki/on-page-unloaded.decorator.md:
--------------------------------------------------------------------------------
1 | # @OnPageUnloaded()
2 |
3 | Decorate the method in the controller to run when the page is status unloaded.
4 |
5 | Example:
6 |
7 | ```ts
8 | import { Component, OnDestroy, Inject, OnInit } from '@angular/core';
9 | import { OnPageUnloaded } from "angular-page-visibility";
10 |
11 | @Component( {
12 | selector : 'app-root',
13 | templateUrl : './app.component.html',
14 | styleUrls : [ './app.component.scss' ]
15 | } )
16 | export class AppComponent implements OnDestroy, OnInit {
17 | ...
18 | @OnPageUnloaded()
19 | logWhenPageUnloaded (): void {
20 | console.log( 'OnPageUnloaded => unloaded' );
21 | }
22 | ...
23 | }
24 | ```
25 |
--------------------------------------------------------------------------------
/wiki/on-page-prerender.decorator.md:
--------------------------------------------------------------------------------
1 | # @OnPagePrerender()
2 |
3 | Decorate the method in the controller to run when the page is status prerender.
4 |
5 | Example:
6 |
7 | ```ts
8 | import { Component, OnDestroy, Inject, OnInit } from '@angular/core';
9 | import { OnPagePrerender } from "angular-page-visibility";
10 |
11 | @Component( {
12 | selector : 'app-root',
13 | templateUrl : './app.component.html',
14 | styleUrls : [ './app.component.scss' ]
15 | } )
16 | export class AppComponent implements OnDestroy, OnInit {
17 | ...
18 | @OnPagePrerender()
19 | logWhenPagePrerender (): void {
20 | console.log( 'OnPagePrerender => prerender' );
21 | }
22 | ...
23 | }
24 | ```
25 |
--------------------------------------------------------------------------------
/src/environments/environment.ts:
--------------------------------------------------------------------------------
1 | // This file can be replaced during build by using the `fileReplacements` array.
2 | // `ng build ---prod` replaces `environment.ts` with `environment.prod.ts`.
3 | // The list of file replacements can be found in `angular.json`.
4 |
5 | export const environment = {
6 | production: false
7 | };
8 |
9 | /*
10 | * In development mode, to ignore zone related error stack frames such as
11 | * `zone.run`, `zoneDelegate.invokeTask` for easier debugging, you can
12 | * import the following file, but please comment it out in production mode
13 | * because it will have performance impact when throw error
14 | */
15 | // import 'zone.js/dist/zone-error'; // Included with Angular CLI.
16 |
--------------------------------------------------------------------------------
/src/test.ts:
--------------------------------------------------------------------------------
1 | // This file is required by karma.conf.js and loads recursively all the .spec and framework files
2 |
3 | import 'zone.js/dist/zone-testing';
4 | import { getTestBed } from '@angular/core/testing';
5 | import {
6 | BrowserDynamicTestingModule,
7 | platformBrowserDynamicTesting
8 | } from '@angular/platform-browser-dynamic/testing';
9 |
10 | declare const require: any;
11 |
12 | // First, initialize the Angular testing environment.
13 | getTestBed().initTestEnvironment(
14 | BrowserDynamicTestingModule,
15 | platformBrowserDynamicTesting()
16 | );
17 | // Then we find all the tests.
18 | const context = require.context('./', true, /\.spec\.ts$/);
19 | // And load the modules.
20 | context.keys().map(context);
21 |
--------------------------------------------------------------------------------
/projects/angular-page-visibility-lib/src/test.ts:
--------------------------------------------------------------------------------
1 | // This file is required by karma.conf.js and loads recursively all the .spec and framework files
2 |
3 | import 'core-js/es7/reflect';
4 | import 'zone.js/dist/zone';
5 | import 'zone.js/dist/zone-testing';
6 | import { getTestBed } from '@angular/core/testing';
7 | import {
8 | BrowserDynamicTestingModule,
9 | platformBrowserDynamicTesting
10 | } from '@angular/platform-browser-dynamic/testing';
11 |
12 | declare const require: any;
13 |
14 | // First, initialize the Angular testing environment.
15 | getTestBed().initTestEnvironment(
16 | BrowserDynamicTestingModule,
17 | platformBrowserDynamicTesting()
18 | );
19 | // Then we find all the tests.
20 | const context = require.context('./', true, /\.spec\.ts$/);
21 | // And load the modules.
22 | context.keys().map(context);
23 |
--------------------------------------------------------------------------------
/wiki/on-page-hidden.decorator.md:
--------------------------------------------------------------------------------
1 | # @OnPageHidden()
2 |
3 | Decorate the method in the controller to run when the page is hidden.
4 |
5 | Example:
6 |
7 | ```ts
8 | import { Component, OnDestroy, Inject, OnInit } from '@angular/core';
9 | import { OnPageHidden } from "angular-page-visibility";
10 |
11 | @Component( {
12 | selector : 'app-root',
13 | templateUrl : './app.component.html',
14 | styleUrls : [ './app.component.scss' ]
15 | } )
16 | export class AppComponent implements OnDestroy, OnInit {
17 | title = 'app';
18 |
19 | constructor() {
20 | }
21 |
22 | ngOnInit(): void {
23 | }
24 |
25 | @OnPageHidden()
26 | logWhenPageHidden(): void {
27 | console.log( 'OnPageHidden' );
28 | console.log( 'hidden' );
29 | }
30 |
31 | ngOnDestroy(): void {
32 | }
33 | }
34 | ```
35 |
--------------------------------------------------------------------------------
/e2e/protractor.conf.js:
--------------------------------------------------------------------------------
1 | // Protractor configuration file, see link for more information
2 | // https://github.com/angular/protractor/blob/master/lib/config.ts
3 |
4 | const { SpecReporter } = require('jasmine-spec-reporter');
5 |
6 | exports.config = {
7 | allScriptsTimeout: 11000,
8 | specs: [
9 | './src/**/*.e2e-spec.ts'
10 | ],
11 | capabilities: {
12 | 'browserName': 'chrome'
13 | },
14 | directConnect: true,
15 | baseUrl: 'http://localhost:4200/',
16 | framework: 'jasmine',
17 | jasmineNodeOpts: {
18 | showColors: true,
19 | defaultTimeoutInterval: 30000,
20 | print: function() {}
21 | },
22 | onPrepare() {
23 | require('ts-node').register({
24 | project: require('path').join(__dirname, './tsconfig.e2e.json')
25 | });
26 | jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
27 | }
28 | };
--------------------------------------------------------------------------------
/wiki/on-page-visible.decorator.md:
--------------------------------------------------------------------------------
1 | # @OnPageVisible()
2 |
3 | Decorate the method in the controller to run when the page is visible.
4 |
5 | Example:
6 |
7 | ```ts
8 | import { Component, OnDestroy, Inject, OnInit } from '@angular/core';
9 | import { OnPageVisible } from "angular-page-visibility";
10 |
11 | @Component( {
12 | selector : 'app-root',
13 | templateUrl : './app.component.html',
14 | styleUrls : [ './app.component.scss' ]
15 | } )
16 | export class AppComponent implements OnDestroy, OnInit {
17 | title = 'app';
18 |
19 | constructor() {
20 | }
21 |
22 | ngOnInit(): void {
23 | }
24 |
25 | @OnPageVisible()
26 | logWhenPageVisible(): void {
27 | console.log( 'OnPageVisible' );
28 | console.log( 'visible' );
29 | }
30 |
31 | ngOnDestroy(): void {
32 | }
33 | }
34 | ```
35 |
--------------------------------------------------------------------------------
/projects/angular-page-visibility-lib/tsconfig.lib.json:
--------------------------------------------------------------------------------
1 | {
2 | "extends": "../../tsconfig.json",
3 | "compilerOptions": {
4 | "outDir": "../../out-tsc/lib",
5 | "target": "es2015",
6 | "module": "es2015",
7 | "moduleResolution": "node",
8 | "declaration": true,
9 | "sourceMap": true,
10 | "inlineSources": true,
11 | "emitDecoratorMetadata": true,
12 | "experimentalDecorators": true,
13 | "importHelpers": true,
14 | "types": [],
15 | "lib": [
16 | "dom",
17 | "es2015"
18 | ]
19 | },
20 | "angularCompilerOptions": {
21 | "skipTemplateCodegen": true,
22 | "strictMetadataEmit": true,
23 | "fullTemplateTypeCheck": true,
24 | "strictInjectionParameters": true,
25 | "flatModuleId": "AUTOGENERATED",
26 | "flatModuleOutFile": "AUTOGENERATED"
27 | },
28 | "exclude": [
29 | "src/test.ts",
30 | "**/*.spec.ts"
31 | ]
32 | }
33 |
--------------------------------------------------------------------------------
/projects/angular-page-visibility-lib/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "angular-page-visibility",
3 | "version": "11.0.0",
4 | "license": "MIT",
5 | "repository": {
6 | "type": "git",
7 | "url": "git+https://github.com/olivierlsc/angular-page-visibility.git"
8 | },
9 | "author": "Olivier LIN-SI-CHENG",
10 | "bugs": {
11 | "url": "https://github.com/olivierlsc/angular-page-visibility/issues"
12 | },
13 | "homepage": "https://github.com/olivierlsc/angular-page-visibility#readme",
14 | "keywords": [
15 | "angular6",
16 | "angular7",
17 | "angular8",
18 | "angular9",
19 | "angular10",
20 | "angular11",
21 | "page visibility",
22 | "page not visibility",
23 | "page visibility api",
24 | "page active",
25 | "page not active"
26 | ],
27 | "peerDependencies": {
28 | "@angular/common": ">=6.0.0 <12",
29 | "@angular/core": ">=6.0.0 <12",
30 | "rxjs": ">=6.0.0 <7"
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/src/karma.conf.js:
--------------------------------------------------------------------------------
1 | // Karma configuration file, see link for more information
2 | // https://karma-runner.github.io/1.0/config/configuration-file.html
3 |
4 | module.exports = function (config) {
5 | config.set({
6 | basePath: '',
7 | frameworks: ['jasmine', '@angular-devkit/build-angular'],
8 | plugins: [
9 | require('karma-jasmine'),
10 | require('karma-chrome-launcher'),
11 | require('karma-jasmine-html-reporter'),
12 | require('karma-coverage-istanbul-reporter'),
13 | require('@angular-devkit/build-angular/plugins/karma')
14 | ],
15 | client: {
16 | clearContext: false // leave Jasmine Spec Runner output visible in browser
17 | },
18 | coverageIstanbulReporter: {
19 | dir: require('path').join(__dirname, '../coverage'),
20 | reports: ['html', 'lcovonly'],
21 | fixWebpackSourcePaths: true
22 | },
23 | reporters: ['progress', 'kjhtml'],
24 | port: 9876,
25 | colors: true,
26 | logLevel: config.LOG_INFO,
27 | autoWatch: true,
28 | browsers: ['Chrome'],
29 | singleRun: false
30 | });
31 | };
--------------------------------------------------------------------------------
/projects/angular-page-visibility-lib/karma.conf.js:
--------------------------------------------------------------------------------
1 | // Karma configuration file, see link for more information
2 | // https://karma-runner.github.io/1.0/config/configuration-file.html
3 |
4 | module.exports = function (config) {
5 | config.set({
6 | basePath: '',
7 | frameworks: ['jasmine', '@angular-devkit/build-angular'],
8 | plugins: [
9 | require('karma-jasmine'),
10 | require('karma-chrome-launcher'),
11 | require('karma-jasmine-html-reporter'),
12 | require('karma-coverage-istanbul-reporter'),
13 | require('@angular-devkit/build-angular/plugins/karma')
14 | ],
15 | client: {
16 | clearContext: false // leave Jasmine Spec Runner output visible in browser
17 | },
18 | coverageIstanbulReporter: {
19 | dir: require('path').join(__dirname, '../../coverage'),
20 | reports: ['html', 'lcovonly'],
21 | fixWebpackSourcePaths: true
22 | },
23 | reporters: ['progress', 'kjhtml'],
24 | port: 9876,
25 | colors: true,
26 | logLevel: config.LOG_INFO,
27 | autoWatch: true,
28 | browsers: ['Chrome'],
29 | singleRun: false
30 | });
31 | };
32 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2017 olivierlsc
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/src/app/app.component.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | Welcome to {{ title }}!
5 |
6 |

7 |
8 | Here are some links to help you start:
9 |
10 | -
11 |
12 |
13 | -
14 |
15 |
16 | -
17 |
18 |
19 |
20 |
21 |
--------------------------------------------------------------------------------
/src/app/app.component.spec.ts:
--------------------------------------------------------------------------------
1 | import { TestBed, waitForAsync } from '@angular/core/testing';
2 | import { AppComponent } from './app.component';
3 | describe('AppComponent', () => {
4 | beforeEach(
5 | waitForAsync(() => {
6 | TestBed.configureTestingModule({
7 | declarations: [AppComponent],
8 | }).compileComponents();
9 | }),
10 | );
11 | it(
12 | 'should create the app',
13 | waitForAsync(() => {
14 | const fixture = TestBed.createComponent(AppComponent);
15 | const app = fixture.debugElement.componentInstance;
16 | expect(app).toBeTruthy();
17 | }),
18 | );
19 | it(
20 | `should have as title 'angular-page-visibility-app'`,
21 | waitForAsync(() => {
22 | const fixture = TestBed.createComponent(AppComponent);
23 | const app = fixture.debugElement.componentInstance;
24 | expect(app.title).toEqual('angular-page-visibility-app');
25 | }),
26 | );
27 | it(
28 | 'should render title in a h1 tag',
29 | waitForAsync(() => {
30 | const fixture = TestBed.createComponent(AppComponent);
31 | fixture.detectChanges();
32 | const compiled = fixture.debugElement.nativeElement;
33 | expect(compiled.querySelector('h1').textContent).toContain(
34 | 'Welcome to angular-page-visibility-app!',
35 | );
36 | }),
37 | );
38 | });
39 |
--------------------------------------------------------------------------------
/.github/workflows/to-release-major-workflow.yml:
--------------------------------------------------------------------------------
1 | name: TO_RELEASE_MAJOR
2 | on: workflow_dispatch
3 | jobs:
4 | build:
5 | runs-on: ubuntu-latest
6 | steps:
7 | - name: Checks-out repository
8 | uses: actions/checkout@v2
9 | - uses: actions/setup-node@v1
10 | with:
11 | node-version: '12.x'
12 | registry-url: 'https://registry.npmjs.org'
13 | - name: Install
14 | run: |
15 | npm install
16 | - name: Init git identity
17 | run: |
18 | git config --global user.email "${{ secrets.MY_EMAIL }}"
19 | git config --global user.name "${{ secrets.MY_NAME }}"
20 | - name: Release major
21 | run: |
22 | npm run release:major
23 | - name: Extract branch name
24 | shell: bash
25 | run: echo "##[set-output name=branch;]$(echo ${GITHUB_REF#refs/heads/})"
26 | id: extract_branch
27 | - name: Push new tag
28 | run: |
29 | git push --follow-tags https://${{ secrets.MY_LOGIN }}:${{ secrets.MY_GITHUB_TOKEN }}@github.com/olivierlsc/angular-page-visibility.git HEAD:${{ steps.extract_branch.outputs.branch }}
30 | - name: Build lib
31 | run: |
32 | npm run build:lib
33 | - name: Publish lib on NPM registry
34 | run: |
35 | npm run publish
36 | env:
37 | NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
38 |
--------------------------------------------------------------------------------
/.github/workflows/to-release-minor-workflow.yml:
--------------------------------------------------------------------------------
1 | name: TO_RELEASE_MINOR
2 | on: workflow_dispatch
3 | jobs:
4 | build:
5 | runs-on: ubuntu-latest
6 | steps:
7 | - name: Checks-out repository
8 | uses: actions/checkout@v2
9 | - uses: actions/setup-node@v1
10 | with:
11 | node-version: '12.x'
12 | registry-url: 'https://registry.npmjs.org'
13 | - name: Install
14 | run: |
15 | npm install
16 | - name: Init git identity
17 | run: |
18 | git config --global user.email "${{ secrets.MY_EMAIL }}"
19 | git config --global user.name "${{ secrets.MY_NAME }}"
20 | - name: Release minor
21 | run: |
22 | npm run release:minor
23 | - name: Extract branch name
24 | shell: bash
25 | run: echo "##[set-output name=branch;]$(echo ${GITHUB_REF#refs/heads/})"
26 | id: extract_branch
27 | - name: Push new tag
28 | run: |
29 | git push --follow-tags https://${{ secrets.MY_LOGIN }}:${{ secrets.MY_GITHUB_TOKEN }}@github.com/olivierlsc/angular-page-visibility.git HEAD:${{ steps.extract_branch.outputs.branch }}
30 | - name: Build lib
31 | run: |
32 | npm run build:lib
33 | - name: Publish lib on NPM registry
34 | run: |
35 | npm run publish
36 | env:
37 | NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
38 |
--------------------------------------------------------------------------------
/.github/workflows/to-release-patch-workflow.yml:
--------------------------------------------------------------------------------
1 | name: TO_RELEASE_PATCH
2 | on: workflow_dispatch
3 | jobs:
4 | build:
5 | runs-on: ubuntu-latest
6 | steps:
7 | - name: Checks-out repository
8 | uses: actions/checkout@v2
9 | - uses: actions/setup-node@v1
10 | with:
11 | node-version: '12.x'
12 | registry-url: 'https://registry.npmjs.org'
13 | - name: Install
14 | run: |
15 | npm install
16 | - name: Init git identity
17 | run: |
18 | git config --global user.email "${{ secrets.MY_EMAIL }}"
19 | git config --global user.name "${{ secrets.MY_NAME }}"
20 | - name: Release patch
21 | run: |
22 | npm run release:patch
23 | - name: Extract branch name
24 | shell: bash
25 | run: echo "##[set-output name=branch;]$(echo ${GITHUB_REF#refs/heads/})"
26 | id: extract_branch
27 | - name: Push new tag
28 | run: |
29 | git push --follow-tags https://${{ secrets.MY_LOGIN }}:${{ secrets.MY_GITHUB_TOKEN }}@github.com/olivierlsc/angular-page-visibility.git HEAD:${{ steps.extract_branch.outputs.branch }}
30 | - name: Build lib
31 | run: |
32 | npm run build:lib
33 | - name: Publish lib on NPM registry
34 | run: |
35 | npm run publish
36 | env:
37 | NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
38 |
--------------------------------------------------------------------------------
/wiki/on-page-visibility-change.decorator.md:
--------------------------------------------------------------------------------
1 | # @OnPageVisibilityChange()
2 |
3 | Decorate the method in the controller to run when the page visibility change.
4 |
5 | Example:
6 |
7 | ```ts
8 | import { Component, OnDestroy, Inject, OnInit } from '@angular/core';
9 | import { OnPageVisibilityChange, AngularPageVisibilityStateEnum } from "angular-page-visibility";
10 |
11 | @Component( {
12 | selector : 'app-root',
13 | templateUrl : './app.component.html',
14 | styleUrls : [ './app.component.scss' ]
15 | } )
16 | export class AppComponent implements OnDestroy, OnInit {
17 | ...
18 | @OnPageVisibilityChange()
19 | logWhenPageVisibilityChange ( visibilityState: AngularPageVisibilityStateEnum ): void {
20 | if ( AngularPageVisibilityStateEnum[visibilityState]
21 | === AngularPageVisibilityStateEnum[AngularPageVisibilityStateEnum.VISIBLE]) {
22 | console.log( 'OnPageVisibilityChange => visible' );
23 | } else if (AngularPageVisibilityStateEnum[visibilityState]
24 | === AngularPageVisibilityStateEnum[AngularPageVisibilityStateEnum.HIDDEN]) {
25 | console.log( 'OnPageVisibilityChange => hidden' );
26 | } else if (AngularPageVisibilityStateEnum[visibilityState]
27 | === AngularPageVisibilityStateEnum[AngularPageVisibilityStateEnum.PRERENDER]) {
28 | console.log( 'OnPageVisibilityChange => prerender' );
29 | } else if (AngularPageVisibilityStateEnum[visibilityState]
30 | === AngularPageVisibilityStateEnum[AngularPageVisibilityStateEnum.UNLOADED]) {
31 | console.log( 'OnPageVisibilityChange => unloaded' );
32 | }
33 | }
34 | ...
35 | }
36 | ```
37 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
4 |
5 | ## [11.0.0](https://github.com/olivierlsc/angular-page-visibility/compare/9.0.6...11.0.0) (2021-04-23)
6 |
7 | ### Features
8 |
9 | - **ng11:** update to ng11 version ([3a82d69](https://github.com/olivierlsc/angular-page-visibility/commit/3a82d6977fa295146544c45c8ba9cd94c4b82444))
10 |
11 | ### 9.0.6 (2020-08-18)
12 |
13 | ### Features
14 |
15 | - Add Angular Universal Support ([8438815](https://github.com/olivierlsc/angular-page-visibility/commit/843881540da39c61d0bede1aa5acb67f343a9531))
16 |
17 | ### 9.0.5 (2020-08-13)
18 |
19 | ### 9.0.4 (2020-08-13)
20 |
21 | ### 9.0.3 (2020-08-12)
22 |
23 | ### 9.0.2 (2020-08-12)
24 |
25 | ### 9.0.1 (2020-08-12)
26 |
27 | ### Features
28 |
29 | - **ci/cd:** add push tags ([8157958](https://github.com/olivierlsc/angular-page-visibility/commit/8157958c686729bffcf248820bf9f799324a2875))
30 |
31 | ## [9.0.0](https://github.com/olivierlsc/angular-page-visibility/compare/v6.1.4...v9.0.0) (2020-05-02)
32 |
33 | ### Features
34 |
35 | - init standard-version ([ee1f56a](https://github.com/olivierlsc/angular-page-visibility/commit/ee1f56ab063874c91b41f0ca179e895e2cda657e))
36 | - migrate to angular 9 ([e947c3e](https://github.com/olivierlsc/angular-page-visibility/commit/e947c3eb5202f99aaabaec4306df62deac72e8c2))
37 | - update to angular 9 ([3d275d3](https://github.com/olivierlsc/angular-page-visibility/commit/3d275d3e55b702ff31df97d9ba6af0e905e09576))
38 |
39 | ### Bug Fixes
40 |
41 | - OnPageVisible ([ae85409](https://github.com/olivierlsc/angular-page-visibility/commit/ae85409dc82f15665e28bd06d711ba1960bb70ab))
42 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "angular-page-visibility-app",
3 | "version": "11.0.0",
4 | "license": "MIT",
5 | "scripts": {
6 | "ng": "ng",
7 | "prestart": "npm run build:lib",
8 | "start": "ng serve",
9 | "prebuild": "npm run build:lib",
10 | "build": "ng build",
11 | "build:lib": "ng build --prod angular-page-visibility-lib && cp *.md dist/angular-page-visibility",
12 | "test": "ng test",
13 | "lint": "ng lint",
14 | "publish": "npm publish dist/angular-page-visibility",
15 | "e2e": "ng e2e",
16 | "release": "standard-version",
17 | "release:major": "npm run release -- -t '' --release-as major",
18 | "release:minor": "npm run release -- -t '' --release-as minor",
19 | "release:patch": "npm run release -- -t '' --release-as patch"
20 | },
21 | "repository": {
22 | "type": "git",
23 | "url": "git+https://github.com/olivierlsc/angular-page-visibility.git"
24 | },
25 | "author": "Olivier LIN-SI-CHENG",
26 | "bugs": {
27 | "url": "https://github.com/olivierlsc/angular-page-visibility/issues"
28 | },
29 | "homepage": "https://github.com/olivierlsc/angular-page-visibility#readme",
30 | "private": true,
31 | "dependencies": {
32 | "@angular/animations": "^11.2.11",
33 | "@angular/common": "^11.2.11",
34 | "@angular/compiler": "^11.2.11",
35 | "@angular/core": "^11.2.11",
36 | "@angular/forms": "^11.2.11",
37 | "@angular/http": "^7.2.12",
38 | "@angular/platform-browser": "^11.2.11",
39 | "@angular/platform-browser-dynamic": "^11.2.11",
40 | "@angular/router": "^11.2.11",
41 | "core-js": "2.6.5",
42 | "rxjs": "^6.6.7",
43 | "zone.js": "^0.10.3"
44 | },
45 | "devDependencies": {
46 | "@angular-devkit/build-angular": "^0.901.4",
47 | "@angular-devkit/build-ng-packagr": "^0.901.4",
48 | "@angular/cli": "^11.2.10",
49 | "@angular/compiler-cli": "^11.2.11",
50 | "@angular/language-service": "^11.2.11",
51 | "@types/jasmine": "~3.3.12",
52 | "@types/jasminewd2": "~2.0.6",
53 | "@types/node": "~11.13.2",
54 | "codelyzer": "~5.0.0",
55 | "husky": "^2.2.0",
56 | "jasmine-core": "~3.4.0",
57 | "jasmine-spec-reporter": "~4.2.1",
58 | "karma": "~4.0.1",
59 | "karma-chrome-launcher": "~2.2.0",
60 | "karma-coverage-istanbul-reporter": "~2.0.5",
61 | "karma-jasmine": "~2.0.1",
62 | "karma-jasmine-html-reporter": "^1.4.0",
63 | "ng-packagr": "^5.0.1",
64 | "prettier": "1.16.4",
65 | "pretty-quick": "^1.10.0",
66 | "protractor": "~5.4.2",
67 | "standard-version": "^8.0.1",
68 | "ts-node": "~8.0.3",
69 | "tsickle": "^0.34.3",
70 | "tslib": "^1.11.1",
71 | "tslint": "~5.15.0",
72 | "typescript": "^4.1.5"
73 | },
74 | "husky": {
75 | "hooks": {
76 | "pre-commit": "pretty-quick --staged"
77 | }
78 | }
79 | }
80 |
--------------------------------------------------------------------------------
/src/polyfills.ts:
--------------------------------------------------------------------------------
1 | /**
2 | * This file includes polyfills needed by Angular and is loaded before the app.
3 | * You can add your own extra polyfills to this file.
4 | *
5 | * This file is divided into 2 sections:
6 | * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
7 | * 2. Application imports. Files imported after ZoneJS that should be loaded before your main
8 | * file.
9 | *
10 | * The current setup is for so-called "evergreen" browsers; the last versions of browsers that
11 | * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera),
12 | * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile.
13 | *
14 | * Learn more in https://angular.io/guide/browser-support
15 | */
16 |
17 | /***************************************************************************************************
18 | * BROWSER POLYFILLS
19 | */
20 |
21 | /** IE10 and IE11 requires the following for NgClass support on SVG elements */
22 | // import 'classlist.js'; // Run `npm install --save classlist.js`.
23 |
24 | /**
25 | * Web Animations `@angular/platform-browser/animations`
26 | * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari.
27 | * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0).
28 | */
29 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`.
30 |
31 | /**
32 | * By default, zone.js will patch all possible macroTask and DomEvents
33 | * user can disable parts of macroTask/DomEvents patch by setting following flags
34 | * because those flags need to be set before `zone.js` being loaded, and webpack
35 | * will put import in the top of bundle, so user need to create a separate file
36 | * in this directory (for example: zone-flags.ts), and put the following flags
37 | * into that file, and then add the following code before importing zone.js.
38 | * import './zone-flags';
39 | *
40 | * The flags allowed in zone-flags.ts are listed here.
41 | *
42 | * The following flags will work for all browsers.
43 | *
44 | * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame
45 | * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick
46 | * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames
47 | *
48 | * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js
49 | * with the following flag, it will bypass `zone.js` patch for IE/Edge
50 | *
51 | * (window as any).__Zone_enable_cross_context_check = true;
52 | *
53 | */
54 |
55 | /***************************************************************************************************
56 | * Zone JS is required by default for Angular itself.
57 | */
58 | import 'zone.js/dist/zone'; // Included with Angular CLI.
59 |
60 |
61 | /***************************************************************************************************
62 | * APPLICATION IMPORTS
63 | */
64 |
--------------------------------------------------------------------------------
/tslint.json:
--------------------------------------------------------------------------------
1 | {
2 | "rulesDirectory": [
3 | "node_modules/codelyzer"
4 | ],
5 | "rules": {
6 | "arrow-return-shorthand": true,
7 | "callable-types": true,
8 | "class-name": true,
9 | "comment-format": [
10 | true,
11 | "check-space"
12 | ],
13 | "curly": true,
14 | "deprecation": {
15 | "severity": "warn"
16 | },
17 | "eofline": true,
18 | "forin": true,
19 | "import-blacklist": [
20 | true,
21 | "rxjs/Rx"
22 | ],
23 | "import-spacing": true,
24 | "indent": [
25 | true,
26 | "spaces"
27 | ],
28 | "interface-over-type-literal": true,
29 | "label-position": true,
30 | "max-line-length": [
31 | true,
32 | 140
33 | ],
34 | "member-access": false,
35 | "member-ordering": [
36 | true,
37 | {
38 | "order": [
39 | "static-field",
40 | "instance-field",
41 | "static-method",
42 | "instance-method"
43 | ]
44 | }
45 | ],
46 | "no-arg": true,
47 | "no-bitwise": true,
48 | "no-console": [
49 | true,
50 | "debug",
51 | "info",
52 | "time",
53 | "timeEnd",
54 | "trace"
55 | ],
56 | "no-construct": true,
57 | "no-debugger": true,
58 | "no-duplicate-super": true,
59 | "no-empty": false,
60 | "no-empty-interface": true,
61 | "no-eval": true,
62 | "no-inferrable-types": [
63 | true,
64 | "ignore-params"
65 | ],
66 | "no-misused-new": true,
67 | "no-non-null-assertion": true,
68 | "no-shadowed-variable": true,
69 | "no-string-literal": false,
70 | "no-string-throw": true,
71 | "no-switch-case-fall-through": true,
72 | "no-trailing-whitespace": true,
73 | "no-unnecessary-initializer": true,
74 | "no-unused-expression": true,
75 | "no-use-before-declare": true,
76 | "no-var-keyword": true,
77 | "object-literal-sort-keys": false,
78 | "one-line": [
79 | true,
80 | "check-open-brace",
81 | "check-catch",
82 | "check-else",
83 | "check-whitespace"
84 | ],
85 | "prefer-const": true,
86 | "quotemark": [
87 | true,
88 | "single"
89 | ],
90 | "radix": true,
91 | "semicolon": [
92 | true,
93 | "always"
94 | ],
95 | "triple-equals": [
96 | true,
97 | "allow-null-check"
98 | ],
99 | "typedef-whitespace": [
100 | true,
101 | {
102 | "call-signature": "nospace",
103 | "index-signature": "nospace",
104 | "parameter": "nospace",
105 | "property-declaration": "nospace",
106 | "variable-declaration": "nospace"
107 | }
108 | ],
109 | "unified-signatures": true,
110 | "variable-name": false,
111 | "whitespace": [
112 | true,
113 | "check-branch",
114 | "check-decl",
115 | "check-operator",
116 | "check-separator",
117 | "check-type"
118 | ],
119 | "no-output-on-prefix": true,
120 | "no-inputs-metadata-property": true,
121 | "no-outputs-metadata-property": true,
122 | "no-host-metadata-property": true,
123 | "no-input-rename": true,
124 | "no-output-rename": true,
125 | "use-lifecycle-interface": true,
126 | "use-pipe-transform-interface": true,
127 | "component-class-suffix": true,
128 | "directive-class-suffix": true
129 | }
130 | }
131 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Angular Page Visibility
2 |
3 | ## Getting started
4 |
5 | First, install it.
6 |
7 | ```bash
8 | npm install --save angular-page-visibility@latest
9 | ```
10 |
11 | Then, import it into your `@NgModule` :
12 |
13 | ```ts
14 | import { BrowserModule } from '@angular/platform-browser';
15 | import { NgModule } from '@angular/core';
16 | import { AppComponent } from './app.component';
17 | import { AngularPageVisibilityModule } from 'angular-page-visibility';
18 |
19 | @NgModule({
20 | declarations: [AppComponent],
21 | imports: [BrowserModule, AngularPageVisibilityModule],
22 | providers: [],
23 | bootstrap: [AppComponent],
24 | })
25 | export class AppModule {}
26 | ```
27 |
28 | Finally, decorate your component :
29 |
30 | ```ts
31 | import { Component, OnInit, OnDestroy } from '@angular/core';
32 | import {
33 | OnPageVisible, OnPageHidden,
34 | OnPageVisibilityChange,
35 | AngularPageVisibilityStateEnum,
36 | OnPagePrerender, OnPageUnloaded} from 'angular-page-visibility';
37 | import { Subscription } from 'rxjs';
38 |
39 | @Component({
40 | selector: 'app-root',
41 | templateUrl: './app.component.html',
42 | styleUrls: ['./app.component.less']
43 | })
44 | export class AppComponent implements OnInit, OnDestroy {
45 | ...
46 | @OnPageVisible()
47 | logWhenPageVisible (): void {
48 | console.log( 'OnPageVisible => visible' );
49 | }
50 |
51 | @OnPageHidden()
52 | logWhenPageHidden (): void {
53 | console.log( 'OnPageHidden => hidden' );
54 | }
55 |
56 | @OnPagePrerender()
57 | logWhenPagePrerender (): void {
58 | console.log( 'OnPagePrerender => prerender' );
59 | }
60 |
61 | @OnPageUnloaded()
62 | logWhenPageUnloaded (): void {
63 | console.log( 'OnPageUnloaded => unloaded' );
64 | }
65 |
66 | @OnPageVisibilityChange()
67 | logWhenPageVisibilityChange ( visibilityState: AngularPageVisibilityStateEnum ): void {
68 | if ( AngularPageVisibilityStateEnum[visibilityState]
69 | === AngularPageVisibilityStateEnum[AngularPageVisibilityStateEnum.VISIBLE]) {
70 | console.log( 'OnPageVisibilityChange => visible' );
71 | } else if (AngularPageVisibilityStateEnum[visibilityState]
72 | === AngularPageVisibilityStateEnum[AngularPageVisibilityStateEnum.HIDDEN]) {
73 | console.log( 'OnPageVisibilityChange => hidden' );
74 | } else if (AngularPageVisibilityStateEnum[visibilityState]
75 | === AngularPageVisibilityStateEnum[AngularPageVisibilityStateEnum.PRERENDER]) {
76 | console.log( 'OnPageVisibilityChange => prerender' );
77 | } else if (AngularPageVisibilityStateEnum[visibilityState]
78 | === AngularPageVisibilityStateEnum[AngularPageVisibilityStateEnum.UNLOADED]) {
79 | console.log( 'OnPageVisibilityChange => unloaded' );
80 | }
81 | }
82 | ...
83 | }
84 | ```
85 |
86 | ## Angular support
87 |
88 | Supports Angular 11 and old versions.
89 |
90 | ## Features and API
91 |
92 | - [@OnPageVisible](./wiki/on-page-visible.decorator.md)
93 | - [@OnPageHidden](./wiki/on-page-hidden.decorator.md)
94 | - [@OnPagePrerender](./wiki/on-page-prerender.decorator.md)
95 | - [@OnPageUnloaded](./wiki/on-page-unloaded.decorator.md)
96 | - [@OnPageVisibilityChange](./wiki/on-page-visibility-change.decorator.md)
97 | - [AngularPageVisibilityService](./wiki/page-visibility.service.md)
98 |
99 | ## For any questions, suggestions, or feature requests
100 |
101 | [Please file an issue](https://github.com/olivierlsc/angular-page-visibility/issues)!
102 |
103 | ## License
104 |
105 | License under the MIT License (MIT)
106 |
107 | Copyright © 2017-2020 [Olivier LIN-SI-CHENG](https://www.olivierlinsicheng.com)
108 |
109 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
110 |
111 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
112 |
113 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
114 |
115 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
116 |
--------------------------------------------------------------------------------
/src/app/app.component.ts:
--------------------------------------------------------------------------------
1 | import { Component, OnInit, OnDestroy } from '@angular/core';
2 | import {
3 | AngularPageVisibilityService,
4 | OnPageVisible,
5 | OnPageHidden,
6 | OnPageVisibilityChange,
7 | AngularPageVisibilityStateEnum,
8 | OnPagePrerender,
9 | OnPageUnloaded,
10 | } from 'angular-page-visibility';
11 | import { Subscription } from 'rxjs';
12 |
13 | @Component({
14 | selector: 'app-root',
15 | templateUrl: './app.component.html',
16 | styleUrls: ['./app.component.less'],
17 | })
18 | export class AppComponent implements OnInit, OnDestroy {
19 | title = 'angular-page-visibility-app';
20 | private onPageVisibleSubscription: Subscription;
21 | private onPageHiddenSubscription: Subscription;
22 | private onPagePrerenderSubscription: Subscription;
23 | private onPageUnloadedSubscription: Subscription;
24 | private onPageVisibilityChangeSubscription: Subscription;
25 | private isPageVisible: boolean;
26 |
27 | constructor(
28 | private angularPageVisibilityService: AngularPageVisibilityService,
29 | ) {}
30 |
31 | ngOnInit(): void {
32 | if (this.angularPageVisibilityService.isPageVisible()) {
33 | console.log('OnInit => visible');
34 | }
35 | if (this.angularPageVisibilityService.isPageHidden()) {
36 | console.log('OnInit => hidden');
37 | }
38 | this.onPageVisibleSubscription = this.angularPageVisibilityService.$onPageVisible.subscribe(
39 | () => {
40 | console.log('OnInit => visible');
41 | },
42 | );
43 |
44 | this.onPageHiddenSubscription = this.angularPageVisibilityService.$onPageHidden.subscribe(
45 | () => {
46 | console.log('OnInit => hidden');
47 | },
48 | );
49 |
50 | this.onPagePrerenderSubscription = this.angularPageVisibilityService.$onPagePrerender.subscribe(
51 | () => {
52 | console.log('OnInit => prerender');
53 | },
54 | );
55 |
56 | this.onPageUnloadedSubscription = this.angularPageVisibilityService.$onPageUnloaded.subscribe(
57 | () => {
58 | console.log('OnInit => unloaded');
59 | },
60 | );
61 |
62 | this.onPageVisibilityChangeSubscription = this.angularPageVisibilityService.$onPageVisibilityChange.subscribe(
63 | (visibilityState: AngularPageVisibilityStateEnum) => {
64 | if (visibilityState === AngularPageVisibilityStateEnum.VISIBLE) {
65 | console.log('OnInit => visibilityChange => visible');
66 | } else if (visibilityState === AngularPageVisibilityStateEnum.HIDDEN) {
67 | console.log('OnInit => visibilityChange => hidden');
68 | } else if (
69 | visibilityState === AngularPageVisibilityStateEnum.PRERENDER
70 | ) {
71 | console.log('OnInit => visibilityChange => prerender');
72 | } else if (
73 | visibilityState === AngularPageVisibilityStateEnum.UNLOADED
74 | ) {
75 | console.log('OnInit => visibilityChange => unloaded');
76 | }
77 | },
78 | );
79 | }
80 |
81 | @OnPageVisible()
82 | logWhenPageVisible(): void {
83 | console.log('OnPageVisible => visible');
84 | this.isPageVisible = true;
85 | console.log(this.isPageVisible);
86 | console.log(this.angularPageVisibilityService.isPageVisible());
87 | }
88 |
89 | @OnPageHidden()
90 | logWhenPageHidden(): void {
91 | console.log('OnPageHidden => hidden');
92 | this.isPageVisible = false;
93 | console.log(this.isPageVisible);
94 | console.log(this.angularPageVisibilityService.isPageHidden());
95 | }
96 |
97 | @OnPagePrerender()
98 | logWhenPagePrerender(): void {
99 | console.log('OnPagePrerender => prerender');
100 | }
101 |
102 | @OnPageUnloaded()
103 | logWhenPageUnloaded(): void {
104 | console.log('OnPageUnloaded => unloaded');
105 | }
106 |
107 | @OnPageVisibilityChange()
108 | logWhenPageVisibilityChange(
109 | visibilityState: AngularPageVisibilityStateEnum,
110 | ): void {
111 | if (
112 | AngularPageVisibilityStateEnum[visibilityState] ===
113 | AngularPageVisibilityStateEnum[AngularPageVisibilityStateEnum.VISIBLE]
114 | ) {
115 | console.log('OnPageVisibilityChange => visible');
116 | } else if (
117 | AngularPageVisibilityStateEnum[visibilityState] ===
118 | AngularPageVisibilityStateEnum[AngularPageVisibilityStateEnum.HIDDEN]
119 | ) {
120 | console.log('OnPageVisibilityChange => hidden');
121 | } else if (
122 | AngularPageVisibilityStateEnum[visibilityState] ===
123 | AngularPageVisibilityStateEnum[AngularPageVisibilityStateEnum.PRERENDER]
124 | ) {
125 | console.log('OnPageVisibilityChange => prerender');
126 | } else if (
127 | AngularPageVisibilityStateEnum[visibilityState] ===
128 | AngularPageVisibilityStateEnum[AngularPageVisibilityStateEnum.UNLOADED]
129 | ) {
130 | console.log('OnPageVisibilityChange => unloaded');
131 | }
132 | }
133 |
134 | ngOnDestroy(): void {
135 | this.onPageVisibleSubscription.unsubscribe();
136 | this.onPageHiddenSubscription.unsubscribe();
137 | this.onPagePrerenderSubscription.unsubscribe();
138 | this.onPageUnloadedSubscription.unsubscribe();
139 | this.onPageVisibilityChangeSubscription.unsubscribe();
140 | }
141 | }
142 |
--------------------------------------------------------------------------------
/projects/angular-page-visibility-lib/src/lib/angular-page-visibility.service.ts:
--------------------------------------------------------------------------------
1 | import {Inject, Injectable, PLATFORM_ID} from '@angular/core';
2 | import { Observable, Subject } from "rxjs";
3 | import { AngularPageVisibilityStateEnum } from "./angular-page-visibility.state.enum";
4 | import {isPlatformServer} from '@angular/common';
5 |
6 | class HiddenKeyConstant {
7 | static DEFAULT = "hidden";
8 | static MS = "msHidden";
9 | static WEB_KIT = "webkitHidden";
10 | }
11 |
12 | class VisibilityStatusConstant {
13 | static VISIBLE = "visible";
14 | static HIDDEN = "hidden";
15 | static PRERENDER = "prerender";
16 | static UNLOADED = "unloaded";
17 | }
18 |
19 | @Injectable({
20 | providedIn: "root"
21 | })
22 | export class AngularPageVisibilityService {
23 | private onPageVisibleSource: Subject = new Subject();
24 | private onPageHiddenSource: Subject = new Subject();
25 | private onPagePrerenderSource: Subject = new Subject();
26 | private onPageUnloadedSource: Subject = new Subject();
27 | private onPageVisibilityChangeSource: Subject<
28 | AngularPageVisibilityStateEnum
29 | > = new Subject();
30 | private hidden: string;
31 | private visibilityChange: string;
32 | private visibilityState: string;
33 | private document: Document;
34 | $onPageVisible: Observable = this.onPageVisibleSource.asObservable();
35 | $onPageHidden: Observable = this.onPageHiddenSource.asObservable();
36 | $onPagePrerender: Observable<
37 | void
38 | > = this.onPagePrerenderSource.asObservable();
39 | $onPageUnloaded: Observable = this.onPageUnloadedSource.asObservable();
40 | $onPageVisibilityChange: Observable<
41 | AngularPageVisibilityStateEnum
42 | > = this.onPageVisibilityChangeSource.asObservable();
43 |
44 | constructor(@Inject(PLATFORM_ID) private platformId: Object) {
45 | this.addEventListenerVibilityChange();
46 | }
47 |
48 | isPageVisible(): boolean {
49 | return (
50 | VisibilityStatusConstant.VISIBLE === this.getVisibilityState() ||
51 | !this.isHidden()
52 | );
53 | }
54 |
55 | isPageHidden(): boolean {
56 | return (
57 | VisibilityStatusConstant.HIDDEN === this.getVisibilityState() ||
58 | this.isHidden()
59 | );
60 | }
61 |
62 | isPagePrerender(): boolean {
63 | return VisibilityStatusConstant.PRERENDER === this.getVisibilityState();
64 | }
65 |
66 | isPageUnloaded(): boolean {
67 | return VisibilityStatusConstant.UNLOADED === this.getVisibilityState();
68 | }
69 |
70 | private isHidden(): boolean {
71 | return document[this.hidden];
72 | }
73 |
74 | private getVisibilityState(): string {
75 | return document[this.visibilityState];
76 | }
77 |
78 | private defineBrowserSupport() {
79 | if (typeof document[HiddenKeyConstant.DEFAULT] !== "undefined") {
80 | // Opera 12.10 and Firefox 18 and later support
81 | this.hidden = HiddenKeyConstant.DEFAULT;
82 | this.visibilityChange = "visibilitychange";
83 | this.visibilityState = "visibilityState";
84 | } else if (typeof document[HiddenKeyConstant.MS] !== "undefined") {
85 | this.hidden = HiddenKeyConstant.MS;
86 | this.visibilityChange = "msvisibilitychange";
87 | this.visibilityState = "msVisibilityState";
88 | } else if (typeof document[HiddenKeyConstant.WEB_KIT] !== "undefined") {
89 | this.hidden = HiddenKeyConstant.WEB_KIT;
90 | this.visibilityChange = "webkitvisibilitychange";
91 | this.visibilityState = "webkitVisibilityState";
92 | }
93 | }
94 |
95 | private addEventListenerVibilityChange(): void {
96 | if (isPlatformServer(this.platformId)) {
97 | return;
98 | }
99 |
100 | this.defineBrowserSupport();
101 | document.addEventListener(
102 | this.visibilityChange,
103 | () => {
104 | const vibilityState = this.getVisibilityState();
105 | switch (vibilityState) {
106 | case VisibilityStatusConstant.VISIBLE:
107 | this.onPageVisibilityChangeSource.next(
108 | AngularPageVisibilityStateEnum.VISIBLE
109 | );
110 | this.onPageVisibleSource.next();
111 | break;
112 | case VisibilityStatusConstant.HIDDEN:
113 | this.onPageVisibilityChangeSource.next(
114 | AngularPageVisibilityStateEnum.HIDDEN
115 | );
116 | this.onPageHiddenSource.next();
117 | break;
118 | case VisibilityStatusConstant.PRERENDER:
119 | this.onPageVisibilityChangeSource.next(
120 | AngularPageVisibilityStateEnum.PRERENDER
121 | );
122 | this.onPagePrerenderSource.next();
123 | break;
124 | case VisibilityStatusConstant.UNLOADED:
125 | this.onPageVisibilityChangeSource.next(
126 | AngularPageVisibilityStateEnum.UNLOADED
127 | );
128 | this.onPageUnloadedSource.next();
129 | break;
130 | default:
131 | if (this.isHidden()) {
132 | this.onPageVisibilityChangeSource.next(
133 | AngularPageVisibilityStateEnum.HIDDEN
134 | );
135 | this.onPageHiddenSource.next();
136 | } else {
137 | this.onPageVisibilityChangeSource.next(
138 | AngularPageVisibilityStateEnum.VISIBLE
139 | );
140 | this.onPageVisibleSource.next();
141 | }
142 | }
143 | },
144 | false
145 | );
146 | }
147 | }
148 |
--------------------------------------------------------------------------------
/angular.json:
--------------------------------------------------------------------------------
1 | {
2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
3 | "version": 1,
4 | "newProjectRoot": "projects",
5 | "projects": {
6 | "angular-page-visibility-app": {
7 | "root": "",
8 | "sourceRoot": "src",
9 | "projectType": "application",
10 | "prefix": "app",
11 | "schematics": {
12 | "@schematics/angular:component": {
13 | "style": "less"
14 | }
15 | },
16 | "architect": {
17 | "build": {
18 | "builder": "@angular-devkit/build-angular:browser",
19 | "options": {
20 | "aot": true,
21 | "outputPath": "dist/angular-page-visibility-app",
22 | "index": "src/index.html",
23 | "main": "src/main.ts",
24 | "polyfills": "src/polyfills.ts",
25 | "tsConfig": "src/tsconfig.app.json",
26 | "assets": ["src/favicon.ico", "src/assets"],
27 | "styles": ["src/styles.less"],
28 | "scripts": []
29 | },
30 | "configurations": {
31 | "production": {
32 | "budgets": [
33 | {
34 | "type": "anyComponentStyle",
35 | "maximumWarning": "6kb"
36 | }
37 | ],
38 | "fileReplacements": [
39 | {
40 | "replace": "src/environments/environment.ts",
41 | "with": "src/environments/environment.prod.ts"
42 | }
43 | ],
44 | "optimization": true,
45 | "outputHashing": "all",
46 | "sourceMap": false,
47 | "extractCss": true,
48 | "namedChunks": false,
49 | "aot": true,
50 | "extractLicenses": true,
51 | "vendorChunk": false,
52 | "buildOptimizer": true
53 | }
54 | }
55 | },
56 | "serve": {
57 | "builder": "@angular-devkit/build-angular:dev-server",
58 | "options": {
59 | "browserTarget": "angular-page-visibility-app:build"
60 | },
61 | "configurations": {
62 | "production": {
63 | "browserTarget": "angular-page-visibility-app:build:production"
64 | }
65 | }
66 | },
67 | "extract-i18n": {
68 | "builder": "@angular-devkit/build-angular:extract-i18n",
69 | "options": {
70 | "browserTarget": "angular-page-visibility-app:build"
71 | }
72 | },
73 | "test": {
74 | "builder": "@angular-devkit/build-angular:karma",
75 | "options": {
76 | "main": "src/test.ts",
77 | "polyfills": "src/polyfills.ts",
78 | "tsConfig": "src/tsconfig.spec.json",
79 | "karmaConfig": "src/karma.conf.js",
80 | "styles": ["src/styles.less"],
81 | "scripts": [],
82 | "assets": ["src/favicon.ico", "src/assets"]
83 | }
84 | },
85 | "lint": {
86 | "builder": "@angular-devkit/build-angular:tslint",
87 | "options": {
88 | "tsConfig": ["src/tsconfig.app.json", "src/tsconfig.spec.json"],
89 | "exclude": ["**/node_modules/**"]
90 | }
91 | }
92 | }
93 | },
94 | "angular-page-visibility-app-e2e": {
95 | "root": "e2e/",
96 | "projectType": "application",
97 | "architect": {
98 | "e2e": {
99 | "builder": "@angular-devkit/build-angular:protractor",
100 | "options": {
101 | "protractorConfig": "e2e/protractor.conf.js",
102 | "devServerTarget": "angular-page-visibility-app:serve"
103 | },
104 | "configurations": {
105 | "production": {
106 | "devServerTarget": "angular-page-visibility-app:serve:production"
107 | }
108 | }
109 | },
110 | "lint": {
111 | "builder": "@angular-devkit/build-angular:tslint",
112 | "options": {
113 | "tsConfig": "e2e/tsconfig.e2e.json",
114 | "exclude": ["**/node_modules/**"]
115 | }
116 | }
117 | }
118 | },
119 | "angular-page-visibility-lib": {
120 | "root": "projects/angular-page-visibility-lib",
121 | "sourceRoot": "projects/angular-page-visibility-lib/src",
122 | "projectType": "library",
123 | "prefix": "apvl",
124 | "architect": {
125 | "build": {
126 | "builder": "@angular-devkit/build-ng-packagr:build",
127 | "options": {
128 | "tsConfig": "projects/angular-page-visibility-lib/tsconfig.lib.json",
129 | "project": "projects/angular-page-visibility-lib/ng-package.json"
130 | },
131 | "configurations": {
132 | "production": {
133 | "tsConfig": "projects/angular-page-visibility-lib/tsconfig.lib.prod.json",
134 | "project": "projects/angular-page-visibility-lib/ng-package.prod.json",
135 | "tsConfig": "projects/angular-page-visibility-lib/tsconfig.lib.prod.json"
136 | }
137 | }
138 | },
139 | "test": {
140 | "builder": "@angular-devkit/build-angular:karma",
141 | "options": {
142 | "main": "projects/angular-page-visibility-lib/src/test.ts",
143 | "tsConfig": "projects/angular-page-visibility-lib/tsconfig.spec.json",
144 | "karmaConfig": "projects/angular-page-visibility-lib/karma.conf.js"
145 | }
146 | },
147 | "lint": {
148 | "builder": "@angular-devkit/build-angular:tslint",
149 | "options": {
150 | "tsConfig": [
151 | "projects/angular-page-visibility-lib/tsconfig.lib.json",
152 | "projects/angular-page-visibility-lib/tsconfig.spec.json"
153 | ],
154 | "exclude": ["**/node_modules/**"]
155 | }
156 | }
157 | }
158 | }
159 | },
160 | "defaultProject": "angular-page-visibility-app",
161 | "cli": {
162 | "analytics": "63f49321-814b-4232-ae7c-5f50db104d74"
163 | }
164 | }
165 |
--------------------------------------------------------------------------------
/projects/angular-page-visibility-lib/src/lib/angular-page-visibility.decorators.ts:
--------------------------------------------------------------------------------
1 | import { Injector, StaticProvider } from '@angular/core';
2 | import { AngularPageVisibilityService } from './angular-page-visibility.service';
3 | import { AngularPageVisibilityStateEnum } from './angular-page-visibility.state.enum';
4 | import { Subscription } from 'rxjs';
5 |
6 | const providers: StaticProvider[] = [
7 | { provide: AngularPageVisibilityService, deps: [] },
8 | ];
9 | const injector = Injector.create({ providers: providers });
10 | const pageVisibilityService = injector.get(AngularPageVisibilityService);
11 |
12 | export function OnPageVisibilityChange(): MethodDecorator {
13 | return function(
14 | target: any,
15 | propertyKey: string,
16 | descriptor: PropertyDescriptor,
17 | ) {
18 | const originalMethod = descriptor.value;
19 | let onPageHiddenSubscription: Subscription;
20 | if (!target.ngOnInit) {
21 | buildNewMethodNgOnInit(target);
22 | }
23 | const originalNgOnInit = target.ngOnInit;
24 | target.ngOnInit = function(...args) {
25 | onPageHiddenSubscription = pageVisibilityService.$onPageVisibilityChange.subscribe(
26 | (visibilityState: AngularPageVisibilityStateEnum) =>
27 | originalMethod.call(this, [visibilityState]),
28 | );
29 | if (originalNgOnInit) {
30 | originalNgOnInit.call(this, args);
31 | }
32 | };
33 | if (!target.ngOnDestroy) {
34 | buildNewMethodNgOnDestroy(target);
35 | }
36 | const originalNgOnDestroy = target.ngOnDestroy;
37 | target.ngOnDestroy = function(...args) {
38 | onPageHiddenSubscription.unsubscribe();
39 | if (originalNgOnDestroy) {
40 | originalNgOnDestroy.call(this, args);
41 | }
42 | };
43 | };
44 | }
45 |
46 | export function OnPageHidden(): MethodDecorator {
47 | return function(
48 | target: any,
49 | propertyKey: string,
50 | descriptor: PropertyDescriptor,
51 | ) {
52 | const originalMethod = descriptor.value;
53 | let onPageHiddenSubscription: Subscription;
54 | if (!target.ngOnInit) {
55 | buildNewMethodNgOnInit(target);
56 | }
57 | const originalNgOnInit = target.ngOnInit;
58 | target.ngOnInit = function(...args) {
59 | onPageHiddenSubscription = pageVisibilityService.$onPageHidden.subscribe(
60 | () => originalMethod.call(this),
61 | );
62 | if (originalNgOnInit) {
63 | originalNgOnInit.call(this, args);
64 | }
65 | };
66 | if (!target.ngOnDestroy) {
67 | buildNewMethodNgOnDestroy(target);
68 | }
69 | const originalNgOnDestroy = target.ngOnDestroy;
70 | target.ngOnDestroy = function(...args) {
71 | onPageHiddenSubscription.unsubscribe();
72 | if (originalNgOnDestroy) {
73 | originalNgOnDestroy.call(this, args);
74 | }
75 | };
76 | };
77 | }
78 |
79 | export function OnPageVisible(): MethodDecorator {
80 | return function(
81 | target: any,
82 | propertyKey: string,
83 | descriptor: PropertyDescriptor,
84 | ) {
85 | const originalMethod = descriptor.value;
86 | if (!target.ngOnInit) {
87 | buildNewMethodNgOnInit(target);
88 | }
89 | const originalNgOnInit = target.ngOnInit;
90 | let onPageVisibleSubscription: Subscription;
91 | target.ngOnInit = function(...args) {
92 | onPageVisibleSubscription = pageVisibilityService.$onPageVisible.subscribe(
93 | () => originalMethod.call(this),
94 | );
95 | if (originalNgOnInit) {
96 | originalNgOnInit.call(this, args);
97 | }
98 | };
99 | if (!target.ngOnDestroy) {
100 | buildNewMethodNgOnDestroy(target);
101 | }
102 | const originalNgOnDestroy = target.ngOnDestroy;
103 | target.ngOnDestroy = function(...args) {
104 | onPageVisibleSubscription.unsubscribe();
105 | if (originalNgOnDestroy) {
106 | originalNgOnDestroy.call(this, args);
107 | }
108 | };
109 | };
110 | }
111 |
112 | export function OnPagePrerender(): MethodDecorator {
113 | return function(
114 | target: any,
115 | propertyKey: string,
116 | descriptor: PropertyDescriptor,
117 | ) {
118 | const originalMethod = descriptor.value;
119 | let onPagePrerenderSubscription: Subscription;
120 | if (!target.ngOnInit) {
121 | buildNewMethodNgOnInit(target);
122 | }
123 | const originalNgOnInit = target.ngOnInit;
124 | target.ngOnInit = function(...args) {
125 | onPagePrerenderSubscription = pageVisibilityService.$onPagePrerender.subscribe(
126 | () => originalMethod.call(this),
127 | );
128 | if (originalNgOnInit) {
129 | originalNgOnInit.call(this, args);
130 | }
131 | };
132 | if (!target.ngOnDestroy) {
133 | buildNewMethodNgOnDestroy(target);
134 | }
135 | const originalNgOnDestroy = target.ngOnDestroy;
136 | target.ngOnDestroy = function(...args) {
137 | onPagePrerenderSubscription.unsubscribe();
138 | if (originalNgOnDestroy) {
139 | originalNgOnDestroy.call(this, args);
140 | }
141 | };
142 | };
143 | }
144 |
145 | export function OnPageUnloaded(): MethodDecorator {
146 | return function(
147 | target: any,
148 | propertyKey: string,
149 | descriptor: PropertyDescriptor,
150 | ) {
151 | const originalMethod = descriptor.value;
152 | let onPageUnloadedSubscription: Subscription;
153 | if (!target.ngOnInit) {
154 | buildNewMethodNgOnInit(target);
155 | }
156 | const originalNgOnInit = target.ngOnInit;
157 | target.ngOnInit = function(...args) {
158 | onPageUnloadedSubscription = pageVisibilityService.$onPageUnloaded.subscribe(
159 | () => originalMethod.call(this),
160 | );
161 | if (originalNgOnInit) {
162 | originalNgOnInit.call(this, args);
163 | }
164 | };
165 | if (!target.ngOnDestroy) {
166 | buildNewMethodNgOnDestroy(target);
167 | }
168 | const originalNgOnDestroy = target.ngOnDestroy;
169 | target.ngOnDestroy = function(...args) {
170 | onPageUnloadedSubscription.unsubscribe();
171 | if (originalNgOnDestroy) {
172 | originalNgOnDestroy.call(this, args);
173 | }
174 | };
175 | };
176 | }
177 |
178 | function buildNewMethodNgOnInit(target: any) {
179 | newMethod(target, 'ngOnInit');
180 | }
181 |
182 | function buildNewMethodNgOnDestroy(target: any) {
183 | newMethod(target, 'ngOnDestroy');
184 | }
185 |
186 | function newMethod(target: any, name: string) {
187 | Object.defineProperty(target, name, {
188 | value: function(...args) {},
189 | writable: true,
190 | });
191 | }
192 |
--------------------------------------------------------------------------------
/wiki/page-visibility.service.md:
--------------------------------------------------------------------------------
1 | # AngularPageVisibilityService
2 |
3 | ## .isPageVisible(): boolean
4 |
5 | Return true if page is visible.
6 |
7 | Example:
8 |
9 | ```ts
10 | import { Component } from '@angular/core';
11 | import { AngularPageVisibilityService } from 'angular-page-visibility';
12 | import { Subscription } from "rxjs/Subscription";
13 |
14 | @Component( {
15 | selector : 'app-root' ,
16 | templateUrl : './app.component.html' ,
17 | styleUrls : [ './app.component.scss' ]
18 | } )
19 | export class AppComponent {
20 | ...
21 | constructor () {
22 | if ( this.angularPageVisibilityService.isPageVisible() ) {
23 | console.log( 'OnInit => visible' );
24 | }
25 | }
26 | ...
27 | }
28 | ```
29 |
30 | ## .isPageHidden(): boolean
31 |
32 | Return true if page is hidden.
33 |
34 | Example:
35 |
36 | ```ts
37 | import { Component } from '@angular/core';
38 | import { AngularPageVisibilityService } from 'angular-page-visibility';
39 | import { Subscription } from "rxjs/Subscription";
40 |
41 | @Component( {
42 | selector : 'app-root' ,
43 | templateUrl : './app.component.html' ,
44 | styleUrls : [ './app.component.scss' ]
45 | } )
46 | export class AppComponent {
47 | ...
48 | constructor () {
49 | if ( this.angularPageVisibilityService.isPageHidden() ) {
50 | console.log( 'OnInit => hidden' );
51 | }
52 | }
53 | ...
54 | }
55 | ```
56 |
57 | ## .isPagePrerender(): boolean
58 |
59 | Return true if page status is prerender.
60 |
61 | Example:
62 |
63 | ```ts
64 | import { Component } from '@angular/core';
65 | import { AngularPageVisibilityService } from 'angular-page-visibility';
66 | import { Subscription } from "rxjs/Subscription";
67 |
68 | @Component( {
69 | selector : 'app-root' ,
70 | templateUrl : './app.component.html' ,
71 | styleUrls : [ './app.component.scss' ]
72 | } )
73 | export class AppComponent {
74 | ...
75 | constructor () {
76 | if ( this.angularPageVisibilityService.isPagePrerender() ) {
77 | console.log( 'constructor => prerender' );
78 | }
79 | }
80 | ...
81 | }
82 | ```
83 |
84 | ## .isPageUnloaded(): boolean
85 |
86 | Return true if page status is unloaded.
87 |
88 | Example:
89 |
90 | ```ts
91 | import { Component } from '@angular/core';
92 | import { AngularPageVisibilityService } from 'angular-page-visibility';
93 | import { Subscription } from "rxjs/Subscription";
94 |
95 | @Component( {
96 | selector : 'app-root' ,
97 | templateUrl : './app.component.html' ,
98 | styleUrls : [ './app.component.scss' ]
99 | } )
100 | export class AppComponent {
101 | ...
102 | constructor () {
103 | if ( this.angularPageVisibilityService.isPageUnloaded() ) {
104 | console.log( 'constructor => unloaded' );
105 | }
106 | }
107 | ...
108 | }
109 |
110 | ## .$onPageVisible : Observable
111 |
112 | Return Observable to run if page is visible.
113 |
114 | Example:
115 |
116 | ```ts
117 |
118 | import { Component, OnInit, OnDestroy } from '@angular/core';
119 | import { AngularPageVisibilityService } from 'angular-page-visibility';
120 | import { Subscription } from 'rxjs';
121 |
122 | @Component({
123 | selector: 'app-root',
124 | templateUrl: './app.component.html',
125 | styleUrls: ['./app.component.less']
126 | })
127 | export class AppComponent implements OnInit, OnDestroy {
128 | private onPageVisibleSubscription: Subscription;
129 |
130 | constructor(private angularPageVisibilityService: AngularPageVisibilityService) {}
131 |
132 | ngOnInit(): void {
133 | this.onPageVisibleSubscription = this.angularPageVisibilityService.$onPageVisible.subscribe( () => {
134 | console.log( 'OnInit => visible' );
135 | } );
136 | }
137 |
138 | ngOnDestroy(): void {
139 | this.onPageVisibleSubscription.unsubscribe();
140 | }
141 | }
142 |
143 | ```
144 |
145 | ## .$onPageHidden : Observable
146 |
147 | Return Observable to run if page is hidden.
148 |
149 | Example:
150 |
151 | ```ts
152 | import { Component, OnInit, OnDestroy } from '@angular/core';
153 | import { AngularPageVisibilityService } from 'angular-page-visibility';
154 | import { Subscription } from 'rxjs';
155 |
156 | @Component({
157 | selector: 'app-root',
158 | templateUrl: './app.component.html',
159 | styleUrls: ['./app.component.less']
160 | })
161 | export class AppComponent implements OnInit, OnDestroy {
162 | private onPageHiddenSubscription: Subscription;
163 |
164 | constructor(private angularPageVisibilityService: AngularPageVisibilityService) {}
165 |
166 | ngOnInit(): void {
167 | this.onPageHiddenSubscription = this.angularPageVisibilityService.$onPageHidden.subscribe( () => {
168 | console.log( 'OnInit => hidden' );
169 | } );
170 | }
171 |
172 | ngOnDestroy(): void {
173 | this.onPageHiddenSubscription.unsubscribe();
174 | }
175 | }
176 |
177 | ```
178 |
179 | ## .$onPagePrerender : Observable
180 |
181 | Return Observable to run if page status is prerender.
182 |
183 | Example:
184 |
185 | ```ts
186 |
187 | import { Component, OnInit, OnDestroy } from '@angular/core';
188 | import { AngularPageVisibilityService } from 'angular-page-visibility';
189 | import { Subscription } from 'rxjs';
190 |
191 | @Component({
192 | selector: 'app-root',
193 | templateUrl: './app.component.html',
194 | styleUrls: ['./app.component.less']
195 | })
196 | export class AppComponent implements OnInit, OnDestroy {
197 | private onPagePrerenderSubscription: Subscription;
198 |
199 | constructor(private angularPageVisibilityService: AngularPageVisibilityService) {}
200 |
201 | ngOnInit(): void {
202 | this.onPagePrerenderSubscription = this.angularPageVisibilityService.$onPagePrerender.subscribe( () => {
203 | console.log( 'OnInit => prerender' );
204 | });
205 | }
206 |
207 | ngOnDestroy(): void {
208 | this.onPagePrerenderSubscription.unsubscribe();
209 | }
210 | }
211 |
212 | ```
213 |
214 | ## .$onPageUnloaded : Observable
215 |
216 | Return Observable to run if page status is unloaded.
217 |
218 | Example:
219 |
220 | ```ts
221 |
222 | import { Component, OnInit, OnDestroy } from '@angular/core';
223 | import { AngularPageVisibilityService } from 'angular-page-visibility';
224 | import { Subscription } from 'rxjs';
225 |
226 | @Component({
227 | selector: 'app-root',
228 | templateUrl: './app.component.html',
229 | styleUrls: ['./app.component.less']
230 | })
231 | export class AppComponent implements OnInit, OnDestroy {
232 | private onPageUnloadedSubscription: Subscription;
233 |
234 | constructor(private angularPageVisibilityService: AngularPageVisibilityService) {}
235 |
236 | ngOnInit(): void {
237 | this.onPageUnloadedSubscription = this.angularPageVisibilityService.$onPageUnloaded.subscribe(() => {
238 | console.log( 'OnInit => unloaded' );
239 | });
240 | }
241 |
242 | ngOnDestroy(): void {
243 | this.onPageUnloadedSubscription.unsubscribe();
244 | }
245 | }
246 |
247 | ```
248 |
249 | ## .$onPageVisibilityChange : Observable
250 |
251 | Return Observable to run if page visibility change.
252 |
253 | Example:
254 |
255 | ```ts
256 |
257 | import { Component, OnInit, OnDestroy } from '@angular/core';
258 | import { AngularPageVisibilityService, AngularPageVisibilityStateEnum } from 'angular-page-visibility';
259 | import { Subscription } from 'rxjs';
260 |
261 | @Component({
262 | selector: 'app-root',
263 | templateUrl: './app.component.html',
264 | styleUrls: ['./app.component.less']
265 | })
266 | export class AppComponent implements OnInit, OnDestroy {
267 | private onPageVisibilityChangeSubscription: Subscription;
268 |
269 | constructor(private angularPageVisibilityService: AngularPageVisibilityService) {}
270 |
271 | ngOnInit(): void {
272 | this.onPageVisibilityChangeSubscription = this.angularPageVisibilityService
273 | .$onPageVisibilityChange.subscribe( ( visibilityState: AngularPageVisibilityStateEnum ) => {
274 | if ( visibilityState === AngularPageVisibilityStateEnum.VISIBLE ) {
275 | console.log( 'OnInit => visibilityChange => visible' );
276 | } else if (visibilityState === AngularPageVisibilityStateEnum.HIDDEN) {
277 | console.log( 'OnInit => visibilityChange => hidden' );
278 | } else if (visibilityState === AngularPageVisibilityStateEnum.PRERENDER) {
279 | console.log( 'OnInit => visibilityChange => prerender' );
280 | } else if (visibilityState === AngularPageVisibilityStateEnum.UNLOADED) {
281 | console.log( 'OnInit => visibilityChange => unloaded' );
282 | }
283 | } );
284 | }
285 |
286 | ngOnDestroy(): void {
287 | this.onPageVisibilityChangeSubscription.unsubscribe();
288 | }
289 | }
290 |
291 | ```
292 |
--------------------------------------------------------------------------------