├── .browserslistrc ├── .editorconfig ├── .gitignore ├── README.md ├── angular.json ├── e2e ├── protractor.conf.js ├── src │ ├── app.e2e-spec.ts │ └── app.po.ts └── tsconfig.json ├── karma.conf.js ├── package-lock.json ├── package.json ├── src ├── app │ ├── app.component.html │ ├── app.component.scss │ ├── app.component.spec.ts │ ├── app.component.ts │ ├── app.module.ts │ ├── components │ │ └── todo-manager │ │ │ ├── todo-manager.component.html │ │ │ ├── todo-manager.component.scss │ │ │ └── todo-manager.component.ts │ ├── history │ │ ├── command-handler.ts │ │ ├── common │ │ │ ├── command-factory.ts │ │ │ ├── command-map.ts │ │ │ ├── commands │ │ │ │ ├── add-to-child-collection-command.ts │ │ │ │ ├── add-to-collection-command.ts │ │ │ │ ├── remove-from-child-collection-command.ts │ │ │ │ ├── remove-from-collection-command.ts │ │ │ │ ├── step-number-command.ts │ │ │ │ ├── toggle-boolean-command.ts │ │ │ │ ├── update-properties-command.ts │ │ │ │ └── update-property-command.ts │ │ │ ├── core.ts │ │ │ └── index.ts │ │ ├── index.ts │ │ ├── model.ts │ │ ├── stack.ts │ │ └── undo-history.ts │ ├── model │ │ └── todo-item.ts │ └── services │ │ ├── command.service.ts │ │ ├── todo-commands.ts │ │ └── todo-data.service.ts ├── assets │ └── .gitkeep ├── environments │ ├── environment.prod.ts │ └── environment.ts ├── favicon.ico ├── index.html ├── main.ts ├── polyfills.ts ├── styles.scss └── test.ts ├── tsconfig.app.json ├── tsconfig.json ├── tsconfig.spec.json └── tslint.json /.browserslistrc: -------------------------------------------------------------------------------- 1 | # This file is used by the build system to adjust CSS and JS output to support the specified browsers below. 2 | # For additional information regarding the format and rule options, please see: 3 | # https://github.com/browserslist/browserslist#queries 4 | 5 | # For the full list of supported browsers by the Angular framework, please see: 6 | # https://angular.io/guide/browser-support 7 | 8 | # You can see what browsers were selected by your queries by running: 9 | # npx browserslist 10 | 11 | last 1 Chrome version 12 | last 1 Firefox version 13 | last 2 Edge major versions 14 | last 2 Safari major versions 15 | last 2 iOS major versions 16 | Firefox ESR 17 | not IE 11 # Angular supports IE 11 only as an opt-in. To opt-in, remove the 'not' prefix on this line. 18 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # Editor configuration, see https://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 | [*.ts] 12 | quote_type = single 13 | 14 | [*.md] 15 | max_line_length = off 16 | trim_trailing_whitespace = false 17 | -------------------------------------------------------------------------------- /.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 | # Only exists if Bazel was run 8 | /bazel-out 9 | 10 | # dependencies 11 | /node_modules 12 | 13 | # profiling files 14 | chrome-profiler-events*.json 15 | speed-measure-plugin*.json 16 | 17 | # IDEs and editors 18 | /.idea 19 | .project 20 | .classpath 21 | .c9/ 22 | *.launch 23 | .settings/ 24 | *.sublime-workspace 25 | 26 | # IDE - VSCode 27 | .vscode/* 28 | !.vscode/settings.json 29 | !.vscode/tasks.json 30 | !.vscode/launch.json 31 | !.vscode/extensions.json 32 | .history/* 33 | 34 | # misc 35 | /.sass-cache 36 | /connect.lock 37 | /coverage 38 | /libpeerconnection.log 39 | npm-debug.log 40 | yarn-error.log 41 | testem.log 42 | /typings 43 | 44 | # System Files 45 | .DS_Store 46 | Thumbs.db 47 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Typescript undo/redo demo 2 | A simple Angular to-do list manager that demonstrates a lightweight undo history using TypeScript and the Command Pattern. Read more about it in [Designing a lightweight undo history with TypeScript](https://www.jitblox.com/blog/designing-a-lightweight-undo-history-with-typescript). 3 | 4 | This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 11.0.3. 5 | 6 | ## Development server 7 | 8 | Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. 9 | 10 | ## Code scaffolding 11 | 12 | Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`. 13 | 14 | ## Build 15 | 16 | Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `--prod` flag for a production build. 17 | 18 | ## Running unit tests 19 | 20 | Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). 21 | 22 | ## Running end-to-end tests 23 | 24 | Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/). 25 | 26 | ## Further help 27 | 28 | To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI Overview and Command Reference](https://angular.io/cli) page. 29 | -------------------------------------------------------------------------------- /angular.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "version": 1, 4 | "newProjectRoot": "projects", 5 | "projects": { 6 | "angular-undo-history": { 7 | "projectType": "application", 8 | "schematics": { 9 | "@schematics/angular:component": { 10 | "style": "scss" 11 | }, 12 | "@schematics/angular:application": { 13 | "strict": true 14 | } 15 | }, 16 | "root": "", 17 | "sourceRoot": "src", 18 | "prefix": "app", 19 | "architect": { 20 | "build": { 21 | "builder": "@angular-devkit/build-angular:browser", 22 | "options": { 23 | "outputPath": "dist/angular-undo-history", 24 | "index": "src/index.html", 25 | "main": "src/main.ts", 26 | "polyfills": "src/polyfills.ts", 27 | "tsConfig": "tsconfig.app.json", 28 | "aot": true, 29 | "assets": [ 30 | "src/favicon.ico", 31 | "src/assets" 32 | ], 33 | "styles": [ 34 | "src/styles.scss" 35 | ], 36 | "scripts": [] 37 | }, 38 | "configurations": { 39 | "production": { 40 | "fileReplacements": [ 41 | { 42 | "replace": "src/environments/environment.ts", 43 | "with": "src/environments/environment.prod.ts" 44 | } 45 | ], 46 | "optimization": true, 47 | "outputHashing": "all", 48 | "sourceMap": false, 49 | "namedChunks": false, 50 | "extractLicenses": true, 51 | "vendorChunk": false, 52 | "buildOptimizer": true, 53 | "budgets": [ 54 | { 55 | "type": "initial", 56 | "maximumWarning": "500kb", 57 | "maximumError": "1mb" 58 | }, 59 | { 60 | "type": "anyComponentStyle", 61 | "maximumWarning": "2kb", 62 | "maximumError": "4kb" 63 | } 64 | ] 65 | } 66 | } 67 | }, 68 | "serve": { 69 | "builder": "@angular-devkit/build-angular:dev-server", 70 | "options": { 71 | "browserTarget": "angular-undo-history:build" 72 | }, 73 | "configurations": { 74 | "production": { 75 | "browserTarget": "angular-undo-history:build:production" 76 | } 77 | } 78 | }, 79 | "extract-i18n": { 80 | "builder": "@angular-devkit/build-angular:extract-i18n", 81 | "options": { 82 | "browserTarget": "angular-undo-history:build" 83 | } 84 | }, 85 | "test": { 86 | "builder": "@angular-devkit/build-angular:karma", 87 | "options": { 88 | "main": "src/test.ts", 89 | "polyfills": "src/polyfills.ts", 90 | "tsConfig": "tsconfig.spec.json", 91 | "karmaConfig": "karma.conf.js", 92 | "assets": [ 93 | "src/favicon.ico", 94 | "src/assets" 95 | ], 96 | "styles": [ 97 | "src/styles.scss" 98 | ], 99 | "scripts": [] 100 | } 101 | }, 102 | "lint": { 103 | "builder": "@angular-devkit/build-angular:tslint", 104 | "options": { 105 | "tsConfig": [ 106 | "tsconfig.app.json", 107 | "tsconfig.spec.json", 108 | "e2e/tsconfig.json" 109 | ], 110 | "exclude": [ 111 | "**/node_modules/**" 112 | ] 113 | } 114 | }, 115 | "e2e": { 116 | "builder": "@angular-devkit/build-angular:protractor", 117 | "options": { 118 | "protractorConfig": "e2e/protractor.conf.js", 119 | "devServerTarget": "angular-undo-history:serve" 120 | }, 121 | "configurations": { 122 | "production": { 123 | "devServerTarget": "angular-undo-history:serve:production" 124 | } 125 | } 126 | } 127 | } 128 | } 129 | }, 130 | "defaultProject": "angular-undo-history" 131 | } 132 | -------------------------------------------------------------------------------- /e2e/protractor.conf.js: -------------------------------------------------------------------------------- 1 | // @ts-check 2 | // Protractor configuration file, see link for more information 3 | // https://github.com/angular/protractor/blob/master/lib/config.ts 4 | 5 | const { SpecReporter, StacktraceOption } = require('jasmine-spec-reporter'); 6 | 7 | /** 8 | * @type { import("protractor").Config } 9 | */ 10 | exports.config = { 11 | allScriptsTimeout: 11000, 12 | specs: [ 13 | './src/**/*.e2e-spec.ts' 14 | ], 15 | capabilities: { 16 | browserName: 'chrome' 17 | }, 18 | directConnect: true, 19 | SELENIUM_PROMISE_MANAGER: false, 20 | baseUrl: 'http://localhost:4200/', 21 | framework: 'jasmine', 22 | jasmineNodeOpts: { 23 | showColors: true, 24 | defaultTimeoutInterval: 30000, 25 | print: function() {} 26 | }, 27 | onPrepare() { 28 | require('ts-node').register({ 29 | project: require('path').join(__dirname, './tsconfig.json') 30 | }); 31 | jasmine.getEnv().addReporter(new SpecReporter({ 32 | spec: { 33 | displayStacktrace: StacktraceOption.PRETTY 34 | } 35 | })); 36 | } 37 | }; -------------------------------------------------------------------------------- /e2e/src/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { AppPage } from './app.po'; 2 | import { browser, logging } from 'protractor'; 3 | 4 | describe('workspace-project App', () => { 5 | let page: AppPage; 6 | 7 | beforeEach(() => { 8 | page = new AppPage(); 9 | }); 10 | 11 | it('should display welcome message', async () => { 12 | await page.navigateTo(); 13 | expect(await page.getTitleText()).toEqual('angular-undo-history app is running!'); 14 | }); 15 | 16 | afterEach(async () => { 17 | // Assert that there are no errors emitted from the browser 18 | const logs = await browser.manage().logs().get(logging.Type.BROWSER); 19 | expect(logs).not.toContain(jasmine.objectContaining({ 20 | level: logging.Level.SEVERE, 21 | } as logging.Entry)); 22 | }); 23 | }); 24 | -------------------------------------------------------------------------------- /e2e/src/app.po.ts: -------------------------------------------------------------------------------- 1 | import { browser, by, element } from 'protractor'; 2 | 3 | export class AppPage { 4 | async navigateTo(): Promise { 5 | return browser.get(browser.baseUrl); 6 | } 7 | 8 | async getTitleText(): Promise { 9 | return element(by.css('app-root .content span')).getText(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /e2e/tsconfig.json: -------------------------------------------------------------------------------- 1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */ 2 | { 3 | "extends": "../tsconfig.json", 4 | "compilerOptions": { 5 | "outDir": "../out-tsc/e2e", 6 | "module": "commonjs", 7 | "target": "es2018", 8 | "types": [ 9 | "jasmine", 10 | "node" 11 | ] 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /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'), 13 | require('@angular-devkit/build-angular/plugins/karma') 14 | ], 15 | client: { 16 | jasmine: { 17 | // you can add configuration options for Jasmine here 18 | // the possible options are listed at https://jasmine.github.io/api/edge/Configuration.html 19 | // for example, you can disable the random execution with `random: false` 20 | // or set a specific seed with `seed: 4321` 21 | }, 22 | clearContext: false // leave Jasmine Spec Runner output visible in browser 23 | }, 24 | jasmineHtmlReporter: { 25 | suppressAll: true // removes the duplicated traces 26 | }, 27 | coverageReporter: { 28 | dir: require('path').join(__dirname, './coverage/angular-undo-history'), 29 | subdir: '.', 30 | reporters: [ 31 | { type: 'html' }, 32 | { type: 'text-summary' } 33 | ] 34 | }, 35 | reporters: ['progress', 'kjhtml'], 36 | port: 9876, 37 | colors: true, 38 | logLevel: config.LOG_INFO, 39 | autoWatch: true, 40 | browsers: ['Chrome'], 41 | singleRun: false, 42 | restartOnFileChange: true 43 | }); 44 | }; 45 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "angular-undo-history", 3 | "version": "0.0.0", 4 | "scripts": { 5 | "ng": "ng", 6 | "start": "ng serve", 7 | "build": "ng build", 8 | "test": "ng test", 9 | "lint": "ng lint", 10 | "e2e": "ng e2e" 11 | }, 12 | "private": true, 13 | "dependencies": { 14 | "@angular/animations": "~11.0.3", 15 | "@angular/common": "~11.0.3", 16 | "@angular/compiler": "~11.0.3", 17 | "@angular/core": "~11.0.3", 18 | "@angular/forms": "~11.0.3", 19 | "@angular/platform-browser": "~11.0.3", 20 | "@angular/platform-browser-dynamic": "~11.0.3", 21 | "@angular/router": "~11.0.3", 22 | "rxjs": "~6.6.0", 23 | "tslib": "^2.0.0", 24 | "zone.js": "~0.10.2" 25 | }, 26 | "devDependencies": { 27 | "@angular-devkit/build-angular": "~0.1100.3", 28 | "@angular/cli": "~11.0.3", 29 | "@angular/compiler-cli": "~11.0.3", 30 | "@types/jasmine": "~3.6.0", 31 | "@types/node": "^12.11.1", 32 | "codelyzer": "^6.0.0", 33 | "jasmine-core": "~3.6.0", 34 | "jasmine-spec-reporter": "~5.0.0", 35 | "karma": "~5.1.0", 36 | "karma-chrome-launcher": "~3.1.0", 37 | "karma-coverage": "~2.0.3", 38 | "karma-jasmine": "~4.0.0", 39 | "karma-jasmine-html-reporter": "^1.5.0", 40 | "protractor": "~7.0.0", 41 | "ts-node": "~8.3.0", 42 | "tslint": "~6.1.0", 43 | "typescript": "~4.0.2" 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/app/app.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 | 4 |
5 |
6 |
7 | Undo stack 8 | 9 |
    10 |
  1. {{entry.command.displayName}}
  2. 11 |
12 |
13 |
14 | Redo stack 15 | 16 |
    17 |
  1. {{entry.command.displayName}}
  2. 18 |
19 |
20 |
21 | 22 |
23 |
24 |
25 | -------------------------------------------------------------------------------- /src/app/app.component.scss: -------------------------------------------------------------------------------- 1 | .container { 2 | display: flex; 3 | 4 | .history { 5 | margin-left: auto; 6 | width: 350px; 7 | min-height: 400px; 8 | padding: 5px; 9 | } 10 | } 11 | 12 | .history { 13 | background-color: rgb(211, 202, 202); 14 | display: grid; 15 | grid-template-columns: 1fr 1fr; 16 | grid-template-rows: 1fr auto; 17 | 18 | button { 19 | width: 100px; 20 | } 21 | 22 | li { 23 | font-style: italic; 24 | &:first-child { 25 | font-style: normal; 26 | } 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/app/app.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed } from '@angular/core/testing'; 2 | import { AppComponent } from './app.component'; 3 | 4 | describe('AppComponent', () => { 5 | beforeEach(async () => { 6 | await TestBed.configureTestingModule({ 7 | declarations: [ 8 | AppComponent 9 | ], 10 | }).compileComponents(); 11 | }); 12 | 13 | it('should create the app', () => { 14 | const fixture = TestBed.createComponent(AppComponent); 15 | const app = fixture.componentInstance; 16 | expect(app).toBeTruthy(); 17 | }); 18 | 19 | it(`should have as title 'angular-undo-history'`, () => { 20 | const fixture = TestBed.createComponent(AppComponent); 21 | const app = fixture.componentInstance; 22 | expect(app.title).toEqual('angular-undo-history'); 23 | }); 24 | 25 | it('should render title', () => { 26 | const fixture = TestBed.createComponent(AppComponent); 27 | fixture.detectChanges(); 28 | const compiled = fixture.nativeElement; 29 | expect(compiled.querySelector('.content span').textContent).toContain('angular-undo-history app is running!'); 30 | }); 31 | }); 32 | -------------------------------------------------------------------------------- /src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, HostListener, OnDestroy, OnInit } from '@angular/core'; 2 | import { Subscription } from 'rxjs'; 3 | import { HistoryStackEntry, HistoryAction } from './history'; 4 | import { CommandService } from './services/command.service'; 5 | 6 | @Component({ 7 | selector: 'app-root', 8 | templateUrl: './app.component.html', 9 | styleUrls: ['./app.component.scss'] 10 | }) 11 | export class AppComponent implements OnInit, OnDestroy { 12 | private commandSuccessSubscription!: Subscription; 13 | public undoEntries: HistoryStackEntry[] = []; 14 | public redoEntries: HistoryStackEntry[] = []; 15 | 16 | constructor(private commandService: CommandService) {} 17 | 18 | public ngOnInit(): void { 19 | this.commandSuccessSubscription = this.commandService 20 | .commandSuccess() 21 | .subscribe(args => { 22 | console.log(`Executed ${HistoryAction[args.action]} command '${args.key}'.`); 23 | this.updateHistoryTable(); 24 | }); 25 | } 26 | 27 | public ngOnDestroy(): void { 28 | this.commandSuccessSubscription.unsubscribe(); 29 | } 30 | 31 | private updateHistoryTable(): void { 32 | this.undoEntries = [...this.commandService.getUndoEntries()].reverse(); 33 | this.redoEntries = [...this.commandService.getRedoEntries()].reverse(); 34 | } 35 | 36 | 37 | //#region history event handlers 38 | 39 | public onUndoClick(): void { 40 | this.commandService.undo(); 41 | } 42 | 43 | public onRedoClick(): void { 44 | this.commandService.redo(); 45 | } 46 | 47 | @HostListener('document:keydown.control.z', ['$event']) 48 | public onUndoKey($event: KeyboardEvent) { 49 | this.commandService.undo(); 50 | } 51 | 52 | @HostListener('document:keydown.control.y', ['$event']) 53 | public onRedoKey($event: KeyboardEvent) { 54 | this.commandService.redo(); 55 | } 56 | 57 | public onClearHistoryClick(): void { 58 | this.commandService.clear(); 59 | this.updateHistoryTable(); 60 | } 61 | 62 | //#endregion history handlers 63 | } 64 | -------------------------------------------------------------------------------- /src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { BrowserModule } from '@angular/platform-browser'; 2 | import { NgModule } from '@angular/core'; 3 | import { FormsModule } from '@angular/forms'; 4 | 5 | import { AppComponent } from './app.component'; 6 | import { TodoManagerComponent } from './components/todo-manager/todo-manager.component'; 7 | 8 | @NgModule({ 9 | declarations: [ 10 | AppComponent, 11 | TodoManagerComponent 12 | ], 13 | imports: [ 14 | BrowserModule, 15 | FormsModule 16 | ], 17 | providers: [], 18 | bootstrap: [AppComponent] 19 | }) 20 | export class AppModule { } 21 | -------------------------------------------------------------------------------- /src/app/components/todo-manager/todo-manager.component.html: -------------------------------------------------------------------------------- 1 |

List of to-do items

2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 28 | 29 | 30 |
#TitleDescriptionPriorityDone?Delete
{{item.id}}{{item.title}}{{item.description}}{{item.priority}}
26 | 27 |
31 |

Item details

32 |

No item selected

33 |
34 |
35 | 36 | 37 |
38 |
39 | 40 | 41 |
42 |
43 | 44 | {{currentItem.priority}} 45 |
46 | 47 | 48 |
49 |
50 |
51 | 52 | {{currentItem.done ? 'Done' : 'In progress'}} 53 |
54 | 55 |
56 |
57 |
58 | -------------------------------------------------------------------------------- /src/app/components/todo-manager/todo-manager.component.scss: -------------------------------------------------------------------------------- 1 | .todo-table { 2 | tbody { 3 | border-bottom: 1px solid teal; 4 | tr { 5 | cursor: pointer; 6 | &:hover { 7 | background-color: #db709385; 8 | } 9 | &.active { 10 | background-color: #30b9b136; 11 | } 12 | } 13 | } 14 | 15 | th.id { 16 | width: 20px; 17 | } 18 | 19 | th.title { 20 | width: 200px; 21 | } 22 | 23 | th.description { 24 | // width: 300px; 25 | } 26 | 27 | th.priority { 28 | width: 70px; 29 | } 30 | 31 | th.done { 32 | width: 50px; 33 | } 34 | 35 | td.done { 36 | .check { 37 | display: none; 38 | } 39 | &.checked .check { 40 | display: inline; 41 | } 42 | } 43 | 44 | tr.create-item-row td { 45 | padding: 10px 0; 46 | text-align: right; 47 | } 48 | } 49 | 50 | .todo-form { 51 | width: 100%; 52 | max-width: 460px; 53 | 54 | > div { 55 | margin: 0.5rem 0; 56 | } 57 | 58 | label { 59 | display: inline-block; 60 | width: 200px; 61 | } 62 | 63 | .text-field { 64 | width: 250px; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/app/components/todo-manager/todo-manager.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { TodoItem } from 'src/app/model/todo-item'; 3 | import { TodoDataService } from 'src/app/services/todo-data.service'; 4 | 5 | @Component({ 6 | selector: 'app-todo-manager', 7 | templateUrl: './todo-manager.component.html', 8 | styleUrls: ['./todo-manager.component.scss'] 9 | }) 10 | export class TodoManagerComponent implements OnInit { 11 | public allItems: TodoItem[] = []; 12 | public currentItem?: TodoItem; 13 | 14 | constructor(private dataService: TodoDataService) { } 15 | 16 | public ngOnInit(): void { 17 | this.dataService 18 | .fetchTodoList() 19 | .then(result => { 20 | this.allItems = result; 21 | }) 22 | } 23 | 24 | public onItemRowClick(item: TodoItem): void { 25 | this.currentItem = item; 26 | } 27 | 28 | public onCreateItemClick(): void { 29 | // Taking a shortcut here and not asking the user for a title 30 | this.currentItem = this.dataService.addTodo('untitled'); 31 | } 32 | 33 | public onDeleteItemClick(item: TodoItem, event: MouseEvent): void { 34 | this.dataService.deleteTodo(item); 35 | event.cancelBubble = true; // avoid onItemRowClick events 36 | } 37 | 38 | //#region item detail event handlers 39 | 40 | private executeUpdatePropertiesCommand(newValues: Partial): void { 41 | if (!this.currentItem) 42 | return; 43 | 44 | this.dataService.executeCommand('update-properties', { target: this.currentItem, newValues: newValues }); 45 | } 46 | 47 | public onTitleChange(value: string): void { 48 | this.executeUpdatePropertiesCommand({ title: value }); 49 | } 50 | 51 | public onDescriptionChange(value: string): void { 52 | this.executeUpdatePropertiesCommand({ description: value }); 53 | } 54 | 55 | public onPriorityUpClick(): void { 56 | if (!this.currentItem) 57 | return; 58 | 59 | this.dataService.executeCommand('step-number', { target: this.currentItem, propertyName: 'priority', stepIncrement: 3 }); 60 | } 61 | 62 | public onPriorityDownClick(): void { 63 | if (!this.currentItem) 64 | return; 65 | 66 | this.dataService.executeCommand('step-number', { target: this.currentItem, propertyName: 'priority', stepIncrement: -3 }); 67 | } 68 | 69 | public onToggleDoneClick(): void { 70 | if (!this.currentItem) 71 | return; 72 | 73 | this.dataService.executeCommand('toggle-boolean', { target: this.currentItem, propertyName: 'done' }); 74 | } 75 | 76 | //#endregion item detail event handlers 77 | } 78 | -------------------------------------------------------------------------------- /src/app/history/command-handler.ts: -------------------------------------------------------------------------------- 1 | import { Command, HistoryAction, CommandResult } from './model'; 2 | import { HistoryStackEntry, UndoHistory } from './undo-history'; 3 | 4 | export interface CommandHandlerResult { 5 | key: string; 6 | action: HistoryAction, 7 | result: CommandResult; 8 | } 9 | 10 | export class CommandHandler { 11 | private undoHistory: UndoHistory; 12 | 13 | constructor(undoHistory?: UndoHistory) { 14 | this.undoHistory = undoHistory || new UndoHistory(); 15 | } 16 | 17 | /** 18 | * Executes the command, inspects its result and adds it to the undo history. 19 | * @param key A unique key for the command. 20 | * @param command The command to execute. This can be any object that implements the Command interface. 21 | */ 22 | public execute(key: string, command: Command): CommandHandlerResult { 23 | const commandResult = command.execute(); 24 | if (commandResult.success && commandResult.canUndo) { 25 | const entry: HistoryStackEntry = { key: key, command: command }; 26 | this.undoHistory.add(entry, commandResult, HistoryAction.Execute); 27 | } 28 | return { key: key, result: commandResult, action: HistoryAction.Execute }; 29 | } 30 | 31 | /** 32 | * Undoes the last successfully executed command. 33 | */ 34 | public undo(): CommandHandlerResult | undefined { 35 | const historyItem = this.undoHistory.popUndo(); 36 | if (!historyItem) return; 37 | 38 | const commandResult = historyItem.command.undo(); 39 | return { key: historyItem.key, result: commandResult, action: HistoryAction.Undo }; 40 | } 41 | 42 | /** 43 | * Redoes the last command that is on the redo-stack and 44 | * moves it back to the undo history if successfull. 45 | */ 46 | public redo(): CommandHandlerResult | undefined { 47 | const entry = this.undoHistory.popRedo(); 48 | if (!entry) return; 49 | 50 | const commandResult = entry.command.redo(); 51 | if (commandResult.success) { 52 | // Add back to the undo history 53 | this.undoHistory.add(entry, commandResult, HistoryAction.Redo); 54 | } 55 | 56 | return { key: entry.key, result: commandResult, action: HistoryAction.Redo }; 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/app/history/common/command-factory.ts: -------------------------------------------------------------------------------- 1 | import { Command } from '../model'; 2 | import { commonCommandKeys, CommonCommandMap, isCommonCommand } from './command-map'; 3 | 4 | // Specific commands 5 | import { StepNumberCommand } from './commands/step-number-command'; 6 | import { ToggleBooleanCommand } from './commands/toggle-boolean-command'; 7 | import { UpdatePropertiesCommand } from './commands/update-properties-command'; 8 | import { UpdatePropertyCommand } from './commands/update-property-command'; 9 | import { AddToCollectionCommand } from './commands/add-to-collection-command'; 10 | import { AddToChildCollectionCommand } from './commands/add-to-child-collection-command'; 11 | import { RemoveFromCollectionCommand } from './commands/remove-from-collection-command'; 12 | import { RemoveFromChildCollectionCommand } from './commands/remove-from-child-collection-command'; 13 | 14 | export class CommonCommandFactory { 15 | public create>(key: K, commandData: CommonCommandMap[K]): Command { 16 | if (isCommonCommand(commandData, key, 'update-properties')) { 17 | return new UpdatePropertiesCommand(commandData); 18 | } 19 | if (isCommonCommand(commandData, key, 'update-property')) { 20 | return new UpdatePropertyCommand(commandData); 21 | } 22 | else if (isCommonCommand(commandData, key, 'step-number')) { 23 | return new StepNumberCommand(commandData); 24 | } 25 | else if (isCommonCommand(commandData, key, 'toggle-boolean')) { 26 | return new ToggleBooleanCommand(commandData); 27 | } 28 | else if (isCommonCommand(commandData, key, 'add-to-collection')) { 29 | return new AddToCollectionCommand(commandData); 30 | } 31 | else if (isCommonCommand(commandData, key, 'add-to-child-collection')) { 32 | return new AddToChildCollectionCommand(commandData); 33 | } 34 | else if (isCommonCommand(commandData, key, 'remove-from-collection')) { 35 | return new RemoveFromCollectionCommand(commandData); 36 | } 37 | else if (isCommonCommand(commandData, key, 'remove-from-child-collection')) { 38 | return new RemoveFromChildCollectionCommand(commandData); 39 | } 40 | else 41 | throw `Unable to create common command. Unknown command key '${key}'.`; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/app/history/common/command-map.ts: -------------------------------------------------------------------------------- 1 | import { AddToChildCollectionCommandData } from './commands/add-to-child-collection-command'; 2 | import { AddToCollectionCommandData } from './commands/add-to-collection-command'; 3 | import { RemoveFromChildCollectionCommandData } from './commands/remove-from-child-collection-command'; 4 | import { RemoveFromCollectionCommandData } from './commands/remove-from-collection-command'; 5 | import { StepNumberCommandData } from './commands/step-number-command'; 6 | import { ToggleBooleanCommandData } from './commands/toggle-boolean-command'; 7 | import { UpdatePropertiesCommandData } from './commands/update-properties-command'; 8 | import { UpdatePropertyCommandData } from './commands/update-property-command'; 9 | 10 | /** 11 | * Maps common command keys to the command data that is needed to 12 | * execute them. 13 | */ 14 | export interface CommonCommandMap { 15 | 'update-property': UpdatePropertyCommandData; 16 | 'update-properties': UpdatePropertiesCommandData; 17 | 'add-to-collection': AddToCollectionCommandData; 18 | 'add-to-child-collection': AddToChildCollectionCommandData; 19 | 'remove-from-collection': RemoveFromCollectionCommandData; 20 | 'remove-from-child-collection': RemoveFromChildCollectionCommandData; 21 | 'step-number': StepNumberCommandData; 22 | 'toggle-boolean': ToggleBooleanCommandData; 23 | } 24 | 25 | export type commonCommandKeys = keyof CommonCommandMap; 26 | 27 | /** 28 | * A simple helper function that asserts that the command-data/key combination 29 | * correspond to an expected key in the CommonCommandMap. 30 | * @example if (isCommonCommand(commandData, key, 'update-properties')) { 31 | * return new UpdatePropertiesCommand(commandData); // yes, commandData is UpdatePropertiesCommandData 32 | * } 33 | */ 34 | export function isCommonCommand>( 35 | commandData: CommonCommandMap[keyof CommonCommandMap], 36 | actualKey: string, 37 | expectedKey: K): commandData is CommonCommandMap[K] { 38 | return actualKey === expectedKey; 39 | } 40 | -------------------------------------------------------------------------------- /src/app/history/common/commands/add-to-child-collection-command.ts: -------------------------------------------------------------------------------- 1 | import { Command, CommandResult } from '../../model'; 2 | import { PropertiesHavingType } from '../core'; 3 | 4 | /** 5 | * Adds an element to a target object's child collection. 6 | */ 7 | export interface AddToChildCollectionCommandData { 8 | /** 9 | * The target object that has a collection property of type TElement. 10 | */ 11 | parent: TParent; 12 | /** 13 | * The property name of the child collection. The name must be 14 | * an Array property of TParent. 15 | */ 16 | propertyName: PropertiesHavingType; 17 | /** 18 | * The element to add to the collection. 19 | */ 20 | element: TElement; 21 | } 22 | 23 | export class AddToChildCollectionCommand implements Command { 24 | public displayName: string | undefined; 25 | private createdCollection: boolean = false; 26 | 27 | constructor(private commandData: AddToChildCollectionCommandData) { 28 | this.displayName = `Add to ${commandData.propertyName}`; 29 | } 30 | 31 | public execute(): CommandResult { 32 | let collection: TElement[] | undefined = this.getCollection(); 33 | if (!collection) { 34 | // The collection does not exist yet, create it 35 | collection = []; 36 | this.setCollection(collection); 37 | this.createdCollection = true; // so that we can cleanup after ourselves after an undo 38 | } 39 | 40 | collection.push(this.commandData.element); 41 | return { success: true, canUndo: true }; 42 | } 43 | 44 | public undo(): CommandResult { 45 | let collection = this.getCollection(); 46 | if (!collection) { 47 | // The collection does not exist anymore 48 | return { success: false }; 49 | } 50 | const index = collection.indexOf(this.commandData.element); 51 | if (index === -1) { 52 | // The element does not exist in the collection 53 | return { success: false }; 54 | } 55 | 56 | // The element exists: remove it 57 | collection.splice(index, 1); 58 | 59 | // Cleanup if we created the collection 60 | if (!collection.length && this.createdCollection) { 61 | this.setCollection(undefined); 62 | this.createdCollection = false; 63 | } 64 | return { success: true, canRedo: true }; 65 | } 66 | 67 | public redo(): CommandResult { 68 | return this.execute(); 69 | } 70 | 71 | private getCollection(): TElement[] | undefined { 72 | return (this.commandData.parent as any)[this.commandData.propertyName]; 73 | } 74 | 75 | private setCollection(collection: TElement[] | undefined): void { 76 | (this.commandData.parent as any)[this.commandData.propertyName] = collection; 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /src/app/history/common/commands/add-to-collection-command.ts: -------------------------------------------------------------------------------- 1 | import { Command, CommandResult } from '../../model'; 2 | 3 | /** 4 | * Adds an element to a target collection. 5 | */ 6 | export interface AddToCollectionCommandData { 7 | /** 8 | * The collection to which the element must be added. 9 | */ 10 | collection: TElement[]; 11 | /** 12 | * The element to add to the collection. 13 | */ 14 | element: TElement; 15 | } 16 | 17 | export class AddToCollectionCommand implements Command { 18 | public displayName: string; 19 | 20 | constructor(private commandData: AddToCollectionCommandData ) { 21 | this.displayName = 'Add to collection'; 22 | } 23 | 24 | public execute(): CommandResult { 25 | this.commandData.collection.push(this.commandData.element); 26 | return { success: true, canUndo: true }; 27 | } 28 | 29 | public undo(): CommandResult { 30 | const collection = this.commandData.collection; 31 | const index = collection.indexOf(this.commandData.element); 32 | if (index === -1) 33 | return { success: false }; // the element does not exist in the collection 34 | 35 | collection.splice(index, 1); 36 | return { success: true, canRedo: true }; 37 | } 38 | 39 | public redo(): CommandResult { 40 | return this.execute(); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/app/history/common/commands/remove-from-child-collection-command.ts: -------------------------------------------------------------------------------- 1 | import { Command, CommandResult } from '../../model'; 2 | import { EmptyValueHandling, PropertiesHavingType } from '../core'; 3 | 4 | interface CommandDataBase { 5 | /** 6 | * The target object that has a collection property of type TElement. 7 | */ 8 | parent: TParent; 9 | /** 10 | * The property name of the child collection. The name must be 11 | * an Array property of TParent. 12 | */ 13 | propertyName: PropertiesHavingType; 14 | /** 15 | * Defines how to deal with the target collection after the last element is removed. 16 | * By default, the collection is unmodified. 17 | */ 18 | emptyCollectionHandling?: EmptyValueHandling; 19 | } 20 | 21 | interface RemoveElementByReferenceCommandData extends CommandDataBase { 22 | /** 23 | * The element to remove from the collection. 24 | */ 25 | element: TElement; 26 | /** 27 | * Reserved for RemoveElementByIndexCommandData. 28 | */ 29 | elementIndex?: never; 30 | } 31 | 32 | interface RemoveElementByIndexCommandData extends CommandDataBase { 33 | /** 34 | * The 0-based index of the element to remove from the collection. 35 | */ 36 | elementIndex: number; 37 | /** 38 | * Reserved for RemoveElementByIndexCommandData. 39 | */ 40 | element?: never; 41 | } 42 | 43 | /** 44 | * Removes an element form a target object's child collection. 45 | */ 46 | export type RemoveFromChildCollectionCommandData = 47 | RemoveElementByReferenceCommandData 48 | | RemoveElementByIndexCommandData; 49 | 50 | export class RemoveFromChildCollectionCommand implements Command { 51 | public displayName?: string | undefined; 52 | private originalState?: { index: number, element: TElement }; 53 | 54 | constructor(private commandData: RemoveFromChildCollectionCommandData) { 55 | this.displayName = `Remove from ${commandData.propertyName}`; 56 | } 57 | 58 | public execute(): CommandResult { 59 | const collection = this.getCollection(); 60 | if (!collection) { 61 | // No collection means nothing to delete either 62 | return { success: false }; 63 | } 64 | 65 | const index = this.getElementIndex(collection); 66 | if (index < 0) { 67 | // The element does not exist in the collection, or the caller provided a negative number. 68 | return { success: false }; 69 | } 70 | if (index >= collection.length) { 71 | // Caller provided a value greater than the length of the array. Avoid Array.splice 72 | // adding new elements. 73 | return { success: false }; 74 | } 75 | 76 | this.originalState = { index: index, element: collection[index] }; 77 | collection.splice(index, 1); 78 | if (!collection.length) { 79 | // The collection is empty now. Should we clear the property? 80 | switch (this.commandData.emptyCollectionHandling) { 81 | case EmptyValueHandling.SetNull: 82 | this.setCollection(null) 83 | break; 84 | case EmptyValueHandling.SetUndefined: 85 | this.setCollection(undefined); 86 | break; 87 | } 88 | } 89 | return { success: true, canUndo: true }; 90 | } 91 | 92 | /** 93 | * Adds the element back into the collection at its original position. 94 | */ 95 | public undo(): CommandResult { 96 | if (!this.originalState) 97 | return { success: false }; 98 | 99 | let collection = this.getCollection(); 100 | if (!collection) { 101 | // The collection does not exist anymore, recreate it 102 | collection = [this.originalState.element]; 103 | this.setCollection(collection); 104 | } 105 | else 106 | collection.splice(this.originalState.index, 0, this.originalState.element); 107 | 108 | this.originalState = undefined; 109 | return { success: true, canRedo: true }; 110 | } 111 | 112 | public redo(): CommandResult { 113 | return this.execute(); 114 | } 115 | 116 | private getElementIndex(collection: TElement[]): number { 117 | const byReferenceCommand = this.commandData as RemoveElementByReferenceCommandData; 118 | if (byReferenceCommand.element) { 119 | // Remove by reference 120 | return collection.indexOf(byReferenceCommand.element); 121 | } 122 | else { 123 | // Remove by index 124 | return (this.commandData as RemoveElementByIndexCommandData).elementIndex; 125 | } 126 | } 127 | 128 | private getCollection(): TElement[] | undefined { 129 | return (this.commandData.parent as any)[this.commandData.propertyName]; 130 | } 131 | 132 | private setCollection(collection: TElement[] | undefined | null): void { 133 | (this.commandData.parent as any)[this.commandData.propertyName] = collection; 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /src/app/history/common/commands/remove-from-collection-command.ts: -------------------------------------------------------------------------------- 1 | import { Command, CommandResult } from '../../model'; 2 | 3 | interface RemoveElementByReferenceCommandData { 4 | /** 5 | * The collection from which the element must be removed. 6 | */ 7 | collection: TElement[]; 8 | /** 9 | * The element to remove from the collection. 10 | */ 11 | element: TElement; 12 | /** 13 | * Reserved for RemoveElementByIndexCommandData. 14 | */ 15 | elementIndex?: never; 16 | } 17 | 18 | interface RemoveElementByIndexCommandData { 19 | /** 20 | * The collection from which the element must be removed. 21 | */ 22 | collection: TElement[]; 23 | /** 24 | * The 0-based index of the element to remove from the collection. 25 | */ 26 | elementIndex: number; 27 | /** 28 | * Reserved for RemoveElementByIndexCommandData 29 | */ 30 | element?: never; 31 | } 32 | 33 | export type RemoveFromCollectionCommandData = 34 | RemoveElementByReferenceCommandData 35 | | RemoveElementByIndexCommandData; 36 | 37 | export class RemoveFromCollectionCommand implements Command { 38 | public displayName: string; 39 | private originalState?: { index: number, element: TElement }; 40 | 41 | constructor(private commandData: RemoveFromCollectionCommandData) { 42 | this.displayName = 'Remove from collection'; 43 | } 44 | 45 | public execute(): CommandResult { 46 | const index = this.getElementIndex(); 47 | if (index < 0) { 48 | // The element does not exist, or caller provided a negative number. 49 | return { success: false }; 50 | } 51 | const collection = this.commandData.collection; 52 | if (index >= collection.length) { 53 | // Caller provided a value greater than the length of the array. Avoid Array.splice 54 | // adding new elements. 55 | return { success: false }; 56 | } 57 | 58 | this.originalState = { index: index, element: collection[index] }; 59 | collection.splice(index, 1); 60 | return { success: true, canUndo: true }; 61 | } 62 | 63 | public undo(): CommandResult { 64 | if (!this.originalState) 65 | return { success: false }; 66 | 67 | const collection = this.commandData.collection; 68 | collection.splice(this.originalState.index, 0, this.originalState.element); 69 | this.originalState = undefined; 70 | return { success: true, canRedo: true }; 71 | } 72 | 73 | public redo(): CommandResult { 74 | return this.execute(); 75 | } 76 | 77 | private getElementIndex(): number { 78 | const byReferenceCommand = this.commandData as RemoveElementByReferenceCommandData; 79 | if (byReferenceCommand.element) { 80 | // Remove by reference 81 | return this.commandData.collection.indexOf(byReferenceCommand.element); 82 | } 83 | else { 84 | // Remove by index 85 | return (this.commandData as RemoveElementByIndexCommandData).elementIndex; 86 | } 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /src/app/history/common/commands/step-number-command.ts: -------------------------------------------------------------------------------- 1 | import { Command, CommandResult } from '../../model'; 2 | import { PropertiesHavingType } from '../core'; 3 | 4 | /** 5 | * Increments a numeric property with a specified amount. 6 | */ 7 | export interface StepNumberCommandData { 8 | /** 9 | * The target object. 10 | */ 11 | target: TTarget; 12 | /** 13 | * The name of the numeric property to increment. 14 | */ 15 | propertyName: PropertiesHavingType; 16 | /** 17 | * The value by which the property is incremented. This can also 18 | * be a negative number, decrementing the value. 19 | */ 20 | stepIncrement: number; 21 | } 22 | 23 | export class StepNumberCommand implements Command { 24 | public displayName?: string; 25 | 26 | constructor( 27 | private commandData: StepNumberCommandData 28 | ) { 29 | 30 | } 31 | 32 | public execute(): CommandResult { 33 | const key = this.commandData.propertyName; 34 | this.displayName = this.commandData.stepIncrement > 0 ? `Step ${key}: +${this.commandData.stepIncrement}` : `Step ${key}: ${this.commandData.stepIncrement}`; 35 | return this.increment(this.commandData.stepIncrement); 36 | } 37 | 38 | public undo(): CommandResult { 39 | return this.increment(-this.commandData.stepIncrement); 40 | } 41 | 42 | public redo(): CommandResult { 43 | return this.increment(this.commandData.stepIncrement); 44 | } 45 | 46 | private increment(increment: number): CommandResult { 47 | const key = this.commandData.propertyName; 48 | 49 | let value = (this.commandData.target as any)[key] as number; 50 | if (!value) value = 0; 51 | 52 | const newValue = value + increment; 53 | 54 | (this.commandData.target as any)[key] = newValue; 55 | 56 | return { 57 | success: true, 58 | canUndo: true, 59 | canRedo: true // this can be repeated infinitely 60 | }; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/app/history/common/commands/toggle-boolean-command.ts: -------------------------------------------------------------------------------- 1 | import { Command, CommandResult } from '../../model'; 2 | import { PropertiesHavingType } from '../core'; 3 | 4 | /** 5 | * Toggles the value of a boolean property. 6 | */ 7 | export interface ToggleBooleanCommandData { 8 | target: TTarget; 9 | propertyName: PropertiesHavingType; 10 | } 11 | 12 | export class ToggleBooleanCommand implements Command { 13 | public displayName?: string; 14 | 15 | constructor( 16 | private commandData: ToggleBooleanCommandData 17 | ) { 18 | 19 | } 20 | 21 | public execute(): CommandResult { 22 | this.displayName = `Toggle ${this.commandData.propertyName}`; 23 | return this.toggle(); 24 | } 25 | 26 | public undo(): CommandResult { 27 | return this.toggle(); 28 | } 29 | 30 | public redo(): CommandResult { 31 | return this.toggle(); 32 | } 33 | 34 | private toggle(): CommandResult { 35 | const key = this.commandData.propertyName; 36 | 37 | let value = !!(this.commandData.target as any)[key]; 38 | (this.commandData.target as any)[key] = !value; 39 | 40 | return { 41 | success: true, 42 | canUndo: true, 43 | canRedo: true // this can be repeated infinitely 44 | }; 45 | } 46 | } 47 | -------------------------------------------------------------------------------- /src/app/history/common/commands/update-properties-command.ts: -------------------------------------------------------------------------------- 1 | import { Command, CommandResult } from '../../model'; 2 | 3 | /** 4 | * Updates multiple properties of a target object. 5 | */ 6 | export interface UpdatePropertiesCommandData { 7 | /** 8 | * The target object. 9 | */ 10 | target: TTarget; 11 | /** 12 | * A partial instance of the target type with only the values to be updated. 13 | */ 14 | newValues: Partial; 15 | } 16 | 17 | export class UpdatePropertiesCommand implements Command { 18 | private previousValues?: Partial; 19 | public displayName?: string; 20 | 21 | constructor( 22 | private commandData: UpdatePropertiesCommandData 23 | ) { 24 | 25 | } 26 | 27 | public execute(): CommandResult { 28 | const newValues = this.commandData.newValues; 29 | if (!newValues) { 30 | return { success: false }; 31 | } 32 | 33 | this.displayName = `Update ${Object.keys(this.commandData.newValues).join(' | ')}`; 34 | 35 | this.previousValues = this.updateProperties(newValues); 36 | return { 37 | success: true, 38 | canUndo: true, 39 | canRedo: false // setting the same properties twice is not useful 40 | }; 41 | } 42 | 43 | public undo(): CommandResult { 44 | if (!this.previousValues) 45 | return { success: false }; 46 | 47 | this.updateProperties(this.previousValues); 48 | this.previousValues = undefined; 49 | return { success: true }; 50 | } 51 | 52 | public redo(): CommandResult { 53 | if (this.previousValues) // we can only redo in this state 54 | return { success: false }; 55 | 56 | return this.execute(); 57 | } 58 | 59 | private updateProperties(newValues: Partial): Partial { 60 | const target = this.commandData.target; 61 | const keys = Object.keys(newValues); 62 | 63 | const previousValues: Partial = {}; 64 | keys.forEach(key => { 65 | // 1: store the current value for an undo 66 | (previousValues as any)[key] = (target as any)[key]; 67 | // 2: update 68 | (target as any)[key] = (newValues as any)[key]; 69 | }); 70 | 71 | return previousValues; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/app/history/common/commands/update-property-command.ts: -------------------------------------------------------------------------------- 1 | import { Command, CommandResult } from '../../model'; 2 | 3 | /** 4 | * Updates a single property of a target object. 5 | */ 6 | export interface UpdatePropertyCommandData { 7 | /** 8 | * The target object. 9 | */ 10 | target: TTarget; 11 | /** 12 | * The name of the property to be updated. The name must be a property of TTarget. 13 | */ 14 | propertyName: keyof(TTarget); 15 | /** 16 | * The new property value. 17 | */ 18 | newValue?: any; 19 | } 20 | 21 | export class UpdatePropertyCommand implements Command { 22 | private previousValue?: any; 23 | public displayName: string; 24 | 25 | constructor(private commandData: UpdatePropertyCommandData) { 26 | this.displayName = `Update ${commandData.propertyName}`; 27 | } 28 | 29 | public execute(): CommandResult { 30 | this.previousValue = this.updateProperty(this.commandData.newValue); 31 | return { success: true, canUndo: true }; 32 | } 33 | 34 | public undo(): CommandResult { 35 | this.updateProperty(this.previousValue); 36 | this.previousValue = undefined; 37 | return { success: true, canRedo: true }; 38 | } 39 | 40 | public redo(): CommandResult { 41 | return this.execute(); 42 | } 43 | 44 | private updateProperty(value?: any): any { 45 | const target = this.commandData.target; 46 | const key = this.commandData.propertyName; 47 | 48 | const currentValue = target[key]; 49 | target[key] = value; 50 | return currentValue; 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/app/history/common/core.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Restrict keyof T so that it only accepts keys that are of a certain type (TK). 3 | * For example, "key: PropertiesOfType" restricts key to properties 4 | * of type T that have a boolean type. 5 | */ 6 | export type PropertiesHavingType = keyof Pick; 7 | 8 | export const enum EmptyValueHandling { 9 | /** 10 | * Do not deal with empty values. 11 | */ 12 | None = 0, 13 | /** 14 | * Set the value to undefined. 15 | */ 16 | SetUndefined = 1, 17 | /** 18 | * Set the value to null. 19 | */ 20 | SetNull = 2 21 | } 22 | -------------------------------------------------------------------------------- /src/app/history/common/index.ts: -------------------------------------------------------------------------------- 1 | export * from './command-map' 2 | export * from './command-factory' 3 | export { EmptyValueHandling } from './core'; 4 | export { AddToChildCollectionCommandData} from './commands/add-to-child-collection-command'; 5 | export { AddToCollectionCommandData } from './commands/add-to-collection-command'; 6 | export { RemoveFromChildCollectionCommandData } from './commands/remove-from-child-collection-command'; 7 | export { RemoveFromCollectionCommandData } from './commands/remove-from-collection-command'; 8 | export { StepNumberCommandData } from './commands/step-number-command'; 9 | export { ToggleBooleanCommandData } from './commands/toggle-boolean-command'; 10 | export { UpdatePropertiesCommandData } from './commands/update-properties-command'; 11 | export { UpdatePropertyCommandData } from './commands/update-property-command'; 12 | -------------------------------------------------------------------------------- /src/app/history/index.ts: -------------------------------------------------------------------------------- 1 | export { CommandResult, Command, HistoryAction } from './model'; 2 | export { CommandHandler, CommandHandlerResult } from './command-handler' 3 | export { UndoHistory, HistoryStackEntry } from './undo-history' 4 | -------------------------------------------------------------------------------- /src/app/history/model.ts: -------------------------------------------------------------------------------- 1 | export interface CommandResult { 2 | success: boolean; 3 | canUndo?: boolean; 4 | canRedo?: boolean; 5 | } 6 | 7 | export interface Command { 8 | /** 9 | * Executes the command for the first time. 10 | */ 11 | execute(): CommandResult; 12 | /** 13 | * Cancels the action that was executed by the execute() function. 14 | */ 15 | undo(): CommandResult; 16 | /** 17 | * Re-executes the action that was executed by the execute() function. 18 | */ 19 | redo(): CommandResult; 20 | /** 21 | * An optional name that can be used for logging or debugging. 22 | */ 23 | displayName?: string; 24 | } 25 | 26 | export enum HistoryAction { 27 | Execute, 28 | Undo, 29 | Redo 30 | } 31 | -------------------------------------------------------------------------------- /src/app/history/stack.ts: -------------------------------------------------------------------------------- 1 | export class Stack { 2 | private data: T[] = []; 3 | private top: number = 0; 4 | 5 | constructor() { 6 | } 7 | 8 | public push(element: T) { 9 | this.data[this.top] = element; 10 | this.top = this.top + 1; 11 | } 12 | 13 | public length(): number { 14 | return this.top; 15 | } 16 | 17 | public peek(offset?: number): T | undefined { 18 | const delta = offset ? offset + 1 : 1; 19 | const ix = this.top - delta; 20 | if (ix < 0) 21 | return; 22 | 23 | return this.data[ix]; 24 | } 25 | 26 | public clear(): void { 27 | this.data.length = this.top = 0; 28 | } 29 | 30 | public pop(): T | undefined { 31 | if (this.top === 0) 32 | return; 33 | 34 | this.top = this.top - 1; 35 | return this.data.pop(); 36 | } 37 | 38 | public getAll(): T[] { 39 | return this.data; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/app/history/undo-history.ts: -------------------------------------------------------------------------------- 1 | import { Command, HistoryAction, CommandResult } from './model'; 2 | import { Stack } from './stack'; 3 | 4 | export interface HistoryStackEntry { 5 | key: string; 6 | command: Command; 7 | } 8 | 9 | export class UndoHistory { 10 | private undoStack: Stack = new Stack(); 11 | private redoStack: Stack = new Stack(); 12 | 13 | public add( 14 | entry: HistoryStackEntry, 15 | result: CommandResult, 16 | action: HistoryAction): void { 17 | 18 | if (result.canUndo) 19 | this.undoStack.push(entry); 20 | 21 | let canRedo: boolean = false; 22 | switch (action) { 23 | case HistoryAction.Execute: 24 | this.redoStack.clear(); 25 | canRedo = !!result.canRedo; 26 | break; 27 | case HistoryAction.Redo: 28 | // If the redo can repeated, add back to the redo stack, but only if it was the last command 29 | canRedo = !!result.canRedo && !this.redoStack.peek(); 30 | break; 31 | } 32 | 33 | if (canRedo) 34 | this.pushRedo(entry); 35 | } 36 | 37 | private pushRedo(entry: HistoryStackEntry): void { 38 | const nextRedoEntry = this.redoStack.peek(); 39 | if (nextRedoEntry == null || nextRedoEntry !== entry) 40 | this.redoStack.push(entry); 41 | } 42 | 43 | public getUndoEntries(): HistoryStackEntry[] { 44 | return this.undoStack.getAll(); 45 | } 46 | 47 | public getRedoEntries(): HistoryStackEntry[] { 48 | return this.redoStack.getAll(); 49 | } 50 | 51 | public clear() { 52 | this.undoStack.clear(); 53 | this.redoStack.clear(); 54 | } 55 | 56 | public popUndo(): HistoryStackEntry | undefined { 57 | const entry = this.undoStack.pop(); 58 | if (entry) { 59 | this.pushRedo(entry); 60 | } 61 | return entry; 62 | } 63 | 64 | 65 | public popRedo(): HistoryStackEntry | undefined { 66 | // The item should be pushed back onto the undo-stack if executed succesfully. 67 | return this.redoStack.pop(); 68 | } 69 | 70 | public peekRedo(): HistoryStackEntry | undefined { 71 | return this.redoStack.peek(); 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/app/model/todo-item.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Represents a single item on a todo list. 3 | */ 4 | export interface TodoItem { 5 | /** 6 | * A unique item ID. 7 | */ 8 | id: number; 9 | 10 | /** 11 | * The title of the TODO item. 12 | */ 13 | title: string; 14 | 15 | /** 16 | * The item description. 17 | */ 18 | description?: string; 19 | 20 | /** 21 | * An integer that indicates the item priority. 22 | */ 23 | priority?: number; 24 | 25 | /** 26 | * True if the item is done. 27 | */ 28 | done?: boolean; 29 | } 30 | -------------------------------------------------------------------------------- /src/app/services/command.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Observable, Subject } from 'rxjs'; 3 | import { Command, CommandHandler, CommandHandlerResult, HistoryStackEntry, UndoHistory } from '../history'; 4 | 5 | /** 6 | * An Angular wrapper around the CommandHandler. 7 | * This wrapper is registered as a singleton service, assuming a single undo 8 | * stack for the entire application. 9 | */ 10 | @Injectable({ providedIn: 'root' }) 11 | export class CommandService { 12 | private undoHistory: UndoHistory; 13 | private handler: CommandHandler; 14 | private commandSuccessSubject = new Subject(); 15 | 16 | constructor() { 17 | this.undoHistory = new UndoHistory(); 18 | this.handler = new CommandHandler(this.undoHistory); 19 | } 20 | 21 | /** 22 | * An observable that emits a result each time a command is 23 | * executed or undone successfully. 24 | */ 25 | public commandSuccess(): Observable { 26 | return this.commandSuccessSubject.asObservable(); 27 | } 28 | 29 | private emitCommandSuccess(handlerResult: CommandHandlerResult | undefined): void { 30 | if (!handlerResult || !handlerResult.result.success) 31 | return 32 | 33 | // Notify commandSuccess subscribers 34 | this.commandSuccessSubject.next(handlerResult); 35 | } 36 | 37 | public execute(key: string, command: Command): void { 38 | const executeResult = this.handler.execute(key, command); 39 | this.emitCommandSuccess(executeResult); 40 | } 41 | 42 | public undo(): void { 43 | const undoResult = this.handler.undo(); 44 | this.emitCommandSuccess(undoResult); 45 | } 46 | 47 | public redo(): void { 48 | const redoResult = this.handler.redo(); 49 | this.emitCommandSuccess(redoResult); 50 | } 51 | 52 | public clear(): void { 53 | this.undoHistory.clear(); 54 | } 55 | 56 | /** 57 | * Exposes the undo stack. Usually only needed for debugging. 58 | */ 59 | public getUndoEntries(): HistoryStackEntry[] { 60 | return this.undoHistory.getUndoEntries(); 61 | } 62 | 63 | /** 64 | * Exposes the redo stack. Usually only needed for debugging. 65 | */ 66 | public getRedoEntries(): HistoryStackEntry[] { 67 | return this.undoHistory.getRedoEntries(); 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/app/services/todo-commands.ts: -------------------------------------------------------------------------------- 1 | import { Command } from '../history'; 2 | import { CommonCommandFactory, commonCommandKeys, CommonCommandMap } from '../history/common'; 3 | 4 | import { TodoItem } from '../model/todo-item'; 5 | 6 | export interface TodoCommandMap extends CommonCommandMap { 7 | // Implement todo-specific commands here 8 | // 'my-todo-command': MyCommandData; 9 | } 10 | 11 | type todoCommandkeys = keyof TodoCommandMap; 12 | 13 | export class TodoCommandFactory extends CommonCommandFactory { 14 | public create(key: K, commandData: TodoCommandMap[K]): Command { 15 | // if (isTodoCommand(commandData, key, 'my-todo-command')) { 16 | // 17 | // } 18 | return super.create(key as commonCommandKeys, commandData as any); 19 | } 20 | } 21 | 22 | export function isTodoCommand( 23 | commandData: TodoCommandMap[keyof TodoCommandMap], 24 | actualKey: string, 25 | expectedKey: K): commandData is TodoCommandMap[K] { 26 | return actualKey === expectedKey; 27 | } 28 | -------------------------------------------------------------------------------- /src/app/services/todo-data.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable, OnDestroy } from '@angular/core'; 2 | import { Subscription } from 'rxjs'; 3 | import { TodoItem } from '../model/todo-item'; 4 | import { CommandService } from './command.service'; 5 | import { TodoCommandFactory, TodoCommandMap } from './todo-commands'; 6 | 7 | @Injectable({ providedIn: 'root' }) 8 | export class TodoDataService implements OnDestroy { 9 | private commandFactory: TodoCommandFactory; 10 | private commandSuccessSubscription!: Subscription; 11 | 12 | private todoData: TodoItem[] = [ 13 | { id: 1, title: 'Create data model', description: 'Create the application\'s data model.', priority: 1, done: true }, 14 | { id: 2, title: 'Define mock data', description: 'Create some realistic mock data.', priority: 2 }, 15 | { id: 3, title: 'Create main layout', description: 'Create the main layout and navigation for the application.', priority: 3 }, 16 | { id: 4, title: 'Design pages', description: 'Create initial design of most important pages.', priority: 4 }, 17 | { id: 5, title: 'Get customer feedback', description: 'Get feedback on the design from the customer.', priority: 5 } 18 | ] 19 | 20 | constructor(private commandService: CommandService) { 21 | this.commandFactory = new TodoCommandFactory(); 22 | this.commandSuccessSubscription = commandService 23 | .commandSuccess() 24 | .subscribe((args) => { 25 | const key = args.key as keyof TodoCommandMap; // contains the command's unique key 26 | const action = args.action; // Execute, Undo, or Redo 27 | // TODO: you might want to sync your data here 28 | }); 29 | } 30 | 31 | public fetchTodoList(): Promise { 32 | // TODO: you might want to make the todo list observable 33 | return Promise.resolve(this.todoData); 34 | } 35 | 36 | public executeCommand(key: K, commandData: TodoCommandMap[K]) { 37 | const command = this.commandFactory.create(key, commandData); 38 | this.commandService.execute(key, command); 39 | } 40 | 41 | public addTodo(title: string): TodoItem { 42 | const newItem: TodoItem = { id: this.todoData.length + 1, title: title}; 43 | this.executeCommand('add-to-collection', { collection: this.todoData, element: newItem }); 44 | return newItem; 45 | } 46 | 47 | public deleteTodo(item: TodoItem): void { 48 | this.executeCommand('remove-from-collection', { collection: this.todoData, element: item }); 49 | } 50 | 51 | public ngOnDestroy(): void { 52 | this.commandSuccessSubscription.unsubscribe(); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdelaat/typescript-undo-redo-demo/42de18334837d58a7ed72e52922d030eb1ea38ed/src/assets/.gitkeep -------------------------------------------------------------------------------- /src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true 3 | }; 4 | -------------------------------------------------------------------------------- /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 | * For easier debugging in development mode, you can import the following file 11 | * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`. 12 | * 13 | * This import should be commented out in production mode because it will have a negative impact 14 | * on performance if an error is thrown. 15 | */ 16 | // import 'zone.js/dist/zone-error'; // Included with Angular CLI. 17 | -------------------------------------------------------------------------------- /src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mdelaat/typescript-undo-redo-demo/42de18334837d58a7ed72e52922d030eb1ea38ed/src/favicon.ico -------------------------------------------------------------------------------- /src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | TypeScript undo/redo demo 6 | 7 | 8 | 9 | 10 | 11 |

TypeScript undo/redo demo

12 |

A simple to-do manager that demonstrates the Command pattern for undo/redo functionality.

13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /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.error(err)); 13 | -------------------------------------------------------------------------------- /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 | /** 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 | -------------------------------------------------------------------------------- /src/styles.scss: -------------------------------------------------------------------------------- 1 | body, input.text-field { 2 | font-family: 'Courier New', Courier, monospace; 3 | } 4 | 5 | .table { 6 | width: 100%; 7 | table-layout: fixed; 8 | border-collapse: collapse; 9 | td, th { 10 | padding: 0 0.5rem; 11 | vertical-align: top; 12 | } 13 | 14 | th { 15 | font-weight: bold; 16 | text-align: left; 17 | } 18 | } 19 | 20 | .pull-right { 21 | float: right; 22 | } 23 | -------------------------------------------------------------------------------- /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: { 11 | context(path: string, deep?: boolean, filter?: RegExp): { 12 | keys(): string[]; 13 | (id: string): T; 14 | }; 15 | }; 16 | 17 | // First, initialize the Angular testing environment. 18 | getTestBed().initTestEnvironment( 19 | BrowserDynamicTestingModule, 20 | platformBrowserDynamicTesting() 21 | ); 22 | // Then we find all the tests. 23 | const context = require.context('./', true, /\.spec\.ts$/); 24 | // And load the modules. 25 | context.keys().map(context); 26 | -------------------------------------------------------------------------------- /tsconfig.app.json: -------------------------------------------------------------------------------- 1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */ 2 | { 3 | "extends": "./tsconfig.json", 4 | "compilerOptions": { 5 | "outDir": "./out-tsc/app", 6 | "types": [] 7 | }, 8 | "files": [ 9 | "src/main.ts", 10 | "src/polyfills.ts" 11 | ], 12 | "include": [ 13 | "src/**/*.d.ts" 14 | ] 15 | } 16 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */ 2 | { 3 | "compileOnSave": false, 4 | "compilerOptions": { 5 | "baseUrl": "./", 6 | "outDir": "./dist/out-tsc", 7 | "forceConsistentCasingInFileNames": true, 8 | "strict": true, 9 | "noImplicitReturns": true, 10 | "noFallthroughCasesInSwitch": true, 11 | "sourceMap": true, 12 | "declaration": false, 13 | "downlevelIteration": true, 14 | "experimentalDecorators": true, 15 | "moduleResolution": "node", 16 | "importHelpers": true, 17 | "target": "es2015", 18 | "module": "es2020", 19 | "lib": [ 20 | "es2018", 21 | "dom" 22 | ] 23 | }, 24 | "angularCompilerOptions": { 25 | "strictInjectionParameters": true, 26 | "strictInputAccessModifiers": true, 27 | "strictTemplates": true 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */ 2 | { 3 | "extends": "./tsconfig.json", 4 | "compilerOptions": { 5 | "outDir": "./out-tsc/spec", 6 | "types": [ 7 | "jasmine" 8 | ] 9 | }, 10 | "files": [ 11 | "src/test.ts", 12 | "src/polyfills.ts" 13 | ], 14 | "include": [ 15 | "src/**/*.spec.ts", 16 | "src/**/*.d.ts" 17 | ] 18 | } 19 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "tslint:recommended", 3 | "rulesDirectory": [ 4 | "codelyzer" 5 | ], 6 | "rules": { 7 | "align": { 8 | "options": [ 9 | "parameters", 10 | "statements" 11 | ] 12 | }, 13 | "array-type": false, 14 | "arrow-return-shorthand": true, 15 | "curly": true, 16 | "deprecation": { 17 | "severity": "warning" 18 | }, 19 | "eofline": true, 20 | "import-blacklist": [ 21 | true, 22 | "rxjs/Rx" 23 | ], 24 | "import-spacing": true, 25 | "indent": { 26 | "options": [ 27 | "spaces" 28 | ] 29 | }, 30 | "max-classes-per-file": false, 31 | "max-line-length": [ 32 | true, 33 | 140 34 | ], 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-console": [ 47 | true, 48 | "debug", 49 | "info", 50 | "time", 51 | "timeEnd", 52 | "trace" 53 | ], 54 | "no-empty": false, 55 | "no-inferrable-types": [ 56 | true, 57 | "ignore-params" 58 | ], 59 | "no-non-null-assertion": true, 60 | "no-redundant-jsdoc": true, 61 | "no-switch-case-fall-through": true, 62 | "no-var-requires": false, 63 | "object-literal-key-quotes": [ 64 | true, 65 | "as-needed" 66 | ], 67 | "quotemark": [ 68 | true, 69 | "single" 70 | ], 71 | "semicolon": { 72 | "options": [ 73 | "always" 74 | ] 75 | }, 76 | "space-before-function-paren": { 77 | "options": { 78 | "anonymous": "never", 79 | "asyncArrow": "always", 80 | "constructor": "never", 81 | "method": "never", 82 | "named": "never" 83 | } 84 | }, 85 | "typedef": [ 86 | true, 87 | "call-signature" 88 | ], 89 | "typedef-whitespace": { 90 | "options": [ 91 | { 92 | "call-signature": "nospace", 93 | "index-signature": "nospace", 94 | "parameter": "nospace", 95 | "property-declaration": "nospace", 96 | "variable-declaration": "nospace" 97 | }, 98 | { 99 | "call-signature": "onespace", 100 | "index-signature": "onespace", 101 | "parameter": "onespace", 102 | "property-declaration": "onespace", 103 | "variable-declaration": "onespace" 104 | } 105 | ] 106 | }, 107 | "variable-name": { 108 | "options": [ 109 | "ban-keywords", 110 | "check-format", 111 | "allow-pascal-case" 112 | ] 113 | }, 114 | "whitespace": { 115 | "options": [ 116 | "check-branch", 117 | "check-decl", 118 | "check-operator", 119 | "check-separator", 120 | "check-type", 121 | "check-typecast" 122 | ] 123 | }, 124 | "component-class-suffix": true, 125 | "contextual-lifecycle": true, 126 | "directive-class-suffix": true, 127 | "no-conflicting-lifecycle": true, 128 | "no-host-metadata-property": true, 129 | "no-input-rename": true, 130 | "no-inputs-metadata-property": true, 131 | "no-output-native": true, 132 | "no-output-on-prefix": true, 133 | "no-output-rename": true, 134 | "no-outputs-metadata-property": true, 135 | "template-banana-in-box": true, 136 | "template-no-negated-async": true, 137 | "use-lifecycle-interface": true, 138 | "use-pipe-transform-interface": true, 139 | "directive-selector": [ 140 | true, 141 | "attribute", 142 | "app", 143 | "camelCase" 144 | ], 145 | "component-selector": [ 146 | true, 147 | "element", 148 | "app", 149 | "kebab-case" 150 | ] 151 | } 152 | } 153 | --------------------------------------------------------------------------------