feat: made two inputs work correctly

This commit is contained in:
Krzysztof Rudnicki 2024-04-26 13:38:49 +02:00
parent ed8b9a915e
commit b1d9674053
24 changed files with 13920 additions and 0 deletions

42
.gitignore vendored Normal file
View File

@ -0,0 +1,42 @@
# See http://help.github.com/ignore-files/ for more about ignoring files.
# Compiled output
/dist
/tmp
/out-tsc
/bazel-out
# Node
/node_modules
npm-debug.log
yarn-error.log
# IDEs and editors
.idea/
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# Visual Studio Code
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history/*
# Miscellaneous
/.angular/cache
.sass-cache/
/connect.lock
/coverage
/libpeerconnection.log
testem.log
/typings
# System files
.DS_Store
Thumbs.db

View File

@ -0,0 +1,16 @@
# Editor configuration, see https://editorconfig.org
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
[*.ts]
quote_type = single
[*.md]
max_line_length = off
trim_trailing_whitespace = false

42
TS/two-inputs/.gitignore vendored Normal file
View File

@ -0,0 +1,42 @@
# See http://help.github.com/ignore-files/ for more about ignoring files.
# Compiled output
/dist
/tmp
/out-tsc
/bazel-out
# Node
/node_modules
npm-debug.log
yarn-error.log
# IDEs and editors
.idea/
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# Visual Studio Code
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history/*
# Miscellaneous
/.angular/cache
.sass-cache/
/connect.lock
/coverage
/libpeerconnection.log
testem.log
/typings
# System files
.DS_Store
Thumbs.db

4
TS/two-inputs/.vscode/extensions.json vendored Normal file
View File

@ -0,0 +1,4 @@
{
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=827846
"recommendations": ["angular.ng-template"]
}

20
TS/two-inputs/.vscode/launch.json vendored Normal file
View File

@ -0,0 +1,20 @@
{
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "ng serve",
"type": "chrome",
"request": "launch",
"preLaunchTask": "npm: start",
"url": "http://localhost:4200/"
},
{
"name": "ng test",
"type": "chrome",
"request": "launch",
"preLaunchTask": "npm: test",
"url": "http://localhost:9876/debug.html"
}
]
}

42
TS/two-inputs/.vscode/tasks.json vendored Normal file
View File

@ -0,0 +1,42 @@
{
// For more information, visit: https://go.microsoft.com/fwlink/?LinkId=733558
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "start",
"isBackground": true,
"problemMatcher": {
"owner": "typescript",
"pattern": "$tsc",
"background": {
"activeOnStart": true,
"beginsPattern": {
"regexp": "(.*?)"
},
"endsPattern": {
"regexp": "bundle generation complete"
}
}
}
},
{
"type": "npm",
"script": "test",
"isBackground": true,
"problemMatcher": {
"owner": "typescript",
"pattern": "$tsc",
"background": {
"activeOnStart": true,
"beginsPattern": {
"regexp": "(.*?)"
},
"endsPattern": {
"regexp": "bundle generation complete"
}
}
}
}
]
}

27
TS/two-inputs/README.md Normal file
View File

@ -0,0 +1,27 @@
# TwoInputs
This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 17.0.3.
## Development server
Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The application will automatically reload if you change any of the source files.
## Code scaffolding
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`.
## Build
Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory.
## Running unit tests
Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).
## Running end-to-end tests
Run `ng e2e` to execute the end-to-end tests via a platform of your choice. To use this command, you need to first add a package that implements end-to-end testing capabilities.
## Further help
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.

103
TS/two-inputs/angular.json Normal file
View File

@ -0,0 +1,103 @@
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"two-inputs": {
"projectType": "application",
"schematics": {
"@schematics/angular:component": {
"style": "scss"
}
},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:application",
"options": {
"outputPath": "dist/two-inputs",
"index": "src/index.html",
"browser": "src/main.ts",
"polyfills": [
"zone.js"
],
"tsConfig": "tsconfig.app.json",
"inlineStyleLanguage": "scss",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"@angular/material/prebuilt-themes/indigo-pink.css",
"src/styles.scss"
],
"scripts": []
},
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kb",
"maximumError": "1mb"
},
{
"type": "anyComponentStyle",
"maximumWarning": "2kb",
"maximumError": "4kb"
}
],
"outputHashing": "all"
},
"development": {
"optimization": false,
"extractLicenses": false,
"sourceMap": true
}
},
"defaultConfiguration": "production"
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"configurations": {
"production": {
"buildTarget": "two-inputs:build:production"
},
"development": {
"buildTarget": "two-inputs:build:development"
}
},
"defaultConfiguration": "development"
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"buildTarget": "two-inputs:build"
}
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"polyfills": [
"zone.js",
"zone.js/testing"
],
"tsConfig": "tsconfig.spec.json",
"inlineStyleLanguage": "scss",
"assets": [
"src/favicon.ico",
"src/assets"
],
"styles": [
"@angular/material/prebuilt-themes/indigo-pink.css",
"src/styles.scss"
],
"scripts": []
}
}
}
}
}
}

13288
TS/two-inputs/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,40 @@
{
"name": "two-inputs",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test"
},
"private": true,
"dependencies": {
"@angular/animations": "^17.0.0",
"@angular/cdk": "^17.3.5",
"@angular/common": "^17.0.0",
"@angular/compiler": "^17.0.0",
"@angular/core": "^17.0.0",
"@angular/forms": "^17.0.0",
"@angular/material": "^17.3.5",
"@angular/platform-browser": "^17.0.0",
"@angular/platform-browser-dynamic": "^17.0.0",
"@angular/router": "^17.0.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.2"
},
"devDependencies": {
"@angular-devkit/build-angular": "^17.0.3",
"@angular/cli": "^17.0.3",
"@angular/compiler-cli": "^17.0.0",
"@types/jasmine": "~5.1.0",
"jasmine-core": "~5.1.0",
"karma": "~6.4.0",
"karma-chrome-launcher": "~3.2.0",
"karma-coverage": "~2.2.0",
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.1.0",
"typescript": "~5.2.2"
}
}

View File

@ -0,0 +1,30 @@
<mat-form-field class="example-form-field">
<mat-label>min</mat-label>
<input matInput type="number" [(ngModel)]="min" (input)="updateInput()">
</mat-form-field>
<mat-form-field class="example-form-field">
<mat-label>max</mat-label>
<input matInput type="number" [(ngModel)]="max" (input)="updateInput()">
</mat-form-field>
<mat-form-field class="example-form-field">
<mat-label>step</mat-label>
<input matInput type="number" [(ngModel)]="step" (input)="updateInput()">
</mat-form-field>
<mat-form-field class="example-form-field">
<mat-label>targetValue</mat-label>
<input matInput type="number" [(ngModel)]="targetValue" (input)="updateInput()">
</mat-form-field> <br>
<mat-form-field class="example-form-field">
<mat-label>inputOne</mat-label>
<input disabled="true" matInput type="number" [min]="min" [step]="step" [max]="max" [(ngModel)]="inputOne">
</mat-form-field>
<button mat-button (click)="upOne()"> UP </button>
<button mat-button (click)="downOne()"> DOWN </button>
<br>
<mat-form-field class="example-form-field">
<mat-label>inputTwo</mat-label>
<input disabled="true" matInput type="number" [min]="min" [step]="step" [max]="max" [(ngModel)]="inputTwo">
</mat-form-field>
<button mat-button (click)="upTwo()"> UP </button>
<button mat-button (click)="downTwo()"> DOWN </button>
<br>

View File

View File

@ -0,0 +1,29 @@
import { TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [AppComponent],
}).compileComponents();
});
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
it(`should have the 'two-inputs' title`, () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app.title).toEqual('two-inputs');
});
it('should render title', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.nativeElement as HTMLElement;
expect(compiled.querySelector('h1')?.textContent).toContain('Hello, two-inputs');
});
});

View File

@ -0,0 +1,138 @@
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterOutlet } from '@angular/router';
import { MatInputModule } from '@angular/material/input';
import {MatButtonModule} from '@angular/material/button';
import { FormsModule } from '@angular/forms';
@Component({
selector: 'app-root',
standalone: true,
imports: [CommonModule, RouterOutlet, MatInputModule, FormsModule, MatButtonModule],
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
inputOne: number | null = null; // Default initialization to 50
inputTwo: number | null = null; // Default initialization to 50
min: number | null = 100;
max: number | null = 250;
step: number | null = 25;
targetValue: number | null = 325;
indexOne: number = 0;
indexTwo: number = 0;
possibleValues: Array<[number, number]> | null = [];
constructor() {
this.possibleValues = AppComponent.findValidPairs(this.step, this.min, this.max, this.targetValue);
}
ngOnInit() {
this.possibleValues = AppComponent.findValidPairs(this.step, this.min, this.max, this.targetValue);
}
public updateInput() {
this.possibleValues = AppComponent.findValidPairs(this.step, this.min, this.max, this.targetValue);
}
private changeIndex(currentValue: number, direction: boolean) {
this.possibleValues = AppComponent.findValidPairs(this.step, this.min, this.max, this.targetValue);
const length = this.possibleValues?.length;
if(typeof length !== "undefined") {
if(direction) {
if(currentValue + 1 > length - 1) {
return 0;
}
return currentValue + 1;
} else {
if(currentValue - 1 < 0) {
return length - 1;
}
return currentValue - 1;
}
} else {
console.error(`appComponent, changeIndex, length is undefined!`, length);
}
return currentValue;
}
updateTwoValue() {
if(this.possibleValues !== null) {
this.inputOne = this.possibleValues[this.indexOne][0];
if(typeof this.inputOne !== "undefined" && this.inputOne !== null) {
const result = AppComponent.findCorrespondingValue(this.possibleValues, this.inputOne);
if(result !== null) {
[this.inputTwo, this.indexTwo] = result;
return;
}
console.error(`result is null!`);
}
console.error(`this.inputOne is null or undefined!: `, this.inputOne, this.possibleValues, this.indexOne);
}
}
upOne() {
this.indexOne = this.changeIndex(this.indexOne, true);
this.updateTwoValue();
}
downOne() {
this.indexOne = this.changeIndex(this.indexOne, false);
this.updateTwoValue();
}
upTwo() {
this.indexTwo = this.changeIndex(this.indexTwo, true);
if(this.possibleValues !== null) {
this.inputTwo = this.possibleValues[this.indexTwo][1];
const result = AppComponent.findCorrespondingValue(this.possibleValues, this.inputTwo);
if(result !== null) {
[this.inputOne, this.indexOne] = result;
}
}
}
downTwo() {
this.indexTwo = this.changeIndex(this.indexTwo, false);
if(this.possibleValues !== null) {
this.inputTwo = this.possibleValues[this.indexTwo][1];
const result = AppComponent.findCorrespondingValue(this.possibleValues, this.inputTwo);
if(result !== null) {
[this.inputOne, this.indexOne] = result;
}
}
}
private static findCorrespondingValue(pairs: Array<[number, number]>, number: number): [number, number] | null {
for (let index = 0; index < pairs.length; index += 1) {
if (pairs[index][0] === number) {
return [pairs[index][1], index]; // Return n2 if the given number matches n1
} else if (pairs[index][1] === number) {
return [pairs[index][0], index]; // Return n1 if the given number matches n2
}
}
console.error("No corresponding value found for the provided number in the pairs.", pairs, number);
return null; // Return null if no matching number is found
}
private static findValidPairs(x: number | null, y: number | null, z: number | null, ml: number | null): Array<[number, number]> | null {
if (x === null || y === null || z === null || ml === null) {
console.error("findValidPairs, some value is null");
return null;
}
const results: Array<[number, number]> = [];
// Iterate through possible values of n1, which must be multiples of x, at least y, and not more than z
for (let n1 = y; n1 <= ml - y && n1 <= z; n1 += x) {
let n2 = ml - n1;
// Ensure n2 is also a multiple of x, n2 >= y, and n2 <= z
if (n2 % x === 0 && n2 >= y && n2 <= z) {
results.push([n1, n2]);
}
}
return results;
}
}

View File

@ -0,0 +1,9 @@
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { provideAnimationsAsync } from '@angular/platform-browser/animations/async';
export const appConfig: ApplicationConfig = {
providers: [provideRouter(routes), provideAnimationsAsync(), provideAnimationsAsync()]
};

View File

@ -0,0 +1,3 @@
import { Routes } from '@angular/router';
export const routes: Routes = [];

View File

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@ -0,0 +1,15 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>TwoInputs</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body class="mat-typography">
<app-root></app-root>
</body>
</html>

View File

@ -0,0 +1,6 @@
import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { AppComponent } from './app/app.component';
bootstrapApplication(AppComponent, appConfig)
.catch((err) => console.error(err));

View File

@ -0,0 +1,6 @@
/* You can add global styles to this file, and also import other style files */
@use '@angular/material' as mat;
@include mat.core();
html, body { height: 100%; }
body { margin: 0; font-family: Roboto, "Helvetica Neue", sans-serif; }

View File

@ -0,0 +1,14 @@
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": []
},
"files": [
"src/main.ts"
],
"include": [
"src/**/*.d.ts"
]
}

View File

@ -0,0 +1,32 @@
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"compileOnSave": false,
"compilerOptions": {
"outDir": "./dist/out-tsc",
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"esModuleInterop": true,
"sourceMap": true,
"declaration": false,
"experimentalDecorators": true,
"moduleResolution": "node",
"importHelpers": true,
"target": "ES2022",
"module": "ES2022",
"useDefineForClassFields": false,
"lib": [
"ES2022",
"dom"
]
},
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": true
}
}

View File

@ -0,0 +1,14 @@
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/spec",
"types": [
"jasmine"
]
},
"include": [
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
}