├── .browserslistrc ├── .editorconfig ├── .gitignore ├── .nvmrc ├── .vscode ├── extensions.json ├── launch.json └── tasks.json ├── README.md ├── angular.json ├── karma.conf.js ├── ngsw-config.json ├── package-lock.json ├── package.json ├── src ├── app │ ├── app.component.html │ ├── app.component.scss │ ├── app.component.ts │ ├── app.module.ts │ ├── article.ts │ ├── beep.service.ts │ ├── camera-access.ts │ ├── shopping-cart-item │ │ ├── shopping-cart-item.component.html │ │ ├── shopping-cart-item.component.scss │ │ └── shopping-cart-item.component.ts │ ├── shopping-cart.ts │ └── update.service.ts ├── assets │ ├── beep.wav │ ├── classy_crab_blue.png │ ├── classy_crab_gold.png │ ├── classy_crab_red.png │ ├── classy_crab_unknown.png │ └── icons │ │ ├── icon-128x128.png │ │ ├── icon-144x144.png │ │ ├── icon-152x152.png │ │ ├── icon-192x192.png │ │ ├── icon-384x384.png │ │ ├── icon-512x512.png │ │ ├── icon-72x72.png │ │ └── icon-96x96.png ├── environments │ ├── environment.prod.ts │ └── environment.ts ├── favicon.ico ├── index.html ├── main.ts ├── manifest.webmanifest ├── polyfills.ts ├── styles.scss └── test.ts ├── tsconfig.app.json ├── tsconfig.json └── tsconfig.spec.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 | -------------------------------------------------------------------------------- /.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 | 16 | # IDEs and editors 17 | /.idea 18 | .project 19 | .classpath 20 | .c9/ 21 | *.launch 22 | .settings/ 23 | *.sublime-workspace 24 | 25 | # IDE - VSCode 26 | .vscode/* 27 | !.vscode/settings.json 28 | !.vscode/tasks.json 29 | !.vscode/launch.json 30 | !.vscode/extensions.json 31 | .history/* 32 | 33 | # misc 34 | /.angular/cache 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 | -------------------------------------------------------------------------------- /.nvmrc: -------------------------------------------------------------------------------- 1 | 16 2 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=827846 3 | "recommendations": ["angular.ng-template"] 4 | } 5 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 3 | "version": "0.2.0", 4 | "configurations": [ 5 | { 6 | "name": "ng serve", 7 | "type": "pwa-chrome", 8 | "request": "launch", 9 | "preLaunchTask": "npm: start", 10 | "url": "http://localhost:4200/" 11 | }, 12 | { 13 | "name": "ng test", 14 | "type": "chrome", 15 | "request": "launch", 16 | "preLaunchTask": "npm: test", 17 | "url": "http://localhost:9876/debug.html" 18 | } 19 | ] 20 | } 21 | -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | // For more information, visit: https://go.microsoft.com/fwlink/?LinkId=733558 3 | "version": "2.0.0", 4 | "tasks": [ 5 | { 6 | "type": "npm", 7 | "script": "start", 8 | "isBackground": true, 9 | "problemMatcher": { 10 | "owner": "typescript", 11 | "pattern": "$tsc", 12 | "background": { 13 | "activeOnStart": true, 14 | "beginsPattern": { 15 | "regexp": "(.*?)" 16 | }, 17 | "endsPattern": { 18 | "regexp": "bundle generation complete" 19 | } 20 | } 21 | } 22 | }, 23 | { 24 | "type": "npm", 25 | "script": "test", 26 | "isBackground": true, 27 | "problemMatcher": { 28 | "owner": "typescript", 29 | "pattern": "$tsc", 30 | "background": { 31 | "activeOnStart": true, 32 | "beginsPattern": { 33 | "regexp": "(.*?)" 34 | }, 35 | "endsPattern": { 36 | "regexp": "bundle generation complete" 37 | } 38 | } 39 | } 40 | } 41 | ] 42 | } 43 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Mobile Scanning Demo 2 | 3 | This project demonstrates 1D barcode scanning in mobile web apps. 4 | 5 | To build and run the app yourself, run the following commands, and point your browser at https://localhost:4200. 6 | 7 | ```shell script 8 | npm install -g @angular/cli 9 | npm install 10 | ng serve --ssl=true --host=0.0.0.0 11 | ``` 12 | 13 | If you don't want to run it yourself, you can check it out here: https://ean-crab-scanner.web.app/ 14 | -------------------------------------------------------------------------------- /angular.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "version": 1, 4 | "newProjectRoot": "projects", 5 | "projects": { 6 | "mobile-scanning-demo": { 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/mobile-scanning-demo", 24 | "index": "src/index.html", 25 | "main": "src/main.ts", 26 | "polyfills": "src/polyfills.ts", 27 | "tsConfig": "tsconfig.app.json", 28 | "inlineStyleLanguage": "scss", 29 | "assets": [ 30 | "src/favicon.ico", 31 | "src/assets", 32 | "src/manifest.webmanifest" 33 | ], 34 | "styles": [ 35 | "src/styles.scss" 36 | ], 37 | "scripts": [], 38 | "serviceWorker": true, 39 | "ngswConfigPath": "ngsw-config.json" 40 | }, 41 | "configurations": { 42 | "production": { 43 | "budgets": [ 44 | { 45 | "type": "initial", 46 | "maximumWarning": "500kb", 47 | "maximumError": "1mb" 48 | }, 49 | { 50 | "type": "anyComponentStyle", 51 | "maximumWarning": "2kb", 52 | "maximumError": "4kb" 53 | } 54 | ], 55 | "fileReplacements": [ 56 | { 57 | "replace": "src/environments/environment.ts", 58 | "with": "src/environments/environment.prod.ts" 59 | } 60 | ], 61 | "outputHashing": "all" 62 | }, 63 | "development": { 64 | "buildOptimizer": false, 65 | "optimization": false, 66 | "vendorChunk": true, 67 | "extractLicenses": false, 68 | "sourceMap": true, 69 | "namedChunks": true 70 | } 71 | }, 72 | "defaultConfiguration": "production" 73 | }, 74 | "serve": { 75 | "builder": "@angular-devkit/build-angular:dev-server", 76 | "configurations": { 77 | "production": { 78 | "browserTarget": "mobile-scanning-demo:build:production" 79 | }, 80 | "development": { 81 | "browserTarget": "mobile-scanning-demo:build:development" 82 | } 83 | }, 84 | "defaultConfiguration": "development" 85 | }, 86 | "extract-i18n": { 87 | "builder": "@angular-devkit/build-angular:extract-i18n", 88 | "options": { 89 | "browserTarget": "mobile-scanning-demo:build" 90 | } 91 | }, 92 | "test": { 93 | "builder": "@angular-devkit/build-angular:karma", 94 | "options": { 95 | "main": "src/test.ts", 96 | "polyfills": "src/polyfills.ts", 97 | "tsConfig": "tsconfig.spec.json", 98 | "karmaConfig": "karma.conf.js", 99 | "inlineStyleLanguage": "scss", 100 | "assets": [ 101 | "src/favicon.ico", 102 | "src/assets", 103 | "src/manifest.webmanifest" 104 | ], 105 | "styles": [ 106 | "src/styles.scss" 107 | ], 108 | "scripts": [] 109 | } 110 | } 111 | } 112 | } 113 | }, 114 | "defaultProject": "mobile-scanning-demo" 115 | } 116 | -------------------------------------------------------------------------------- /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/mobile-scanning-demo'), 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 | -------------------------------------------------------------------------------- /ngsw-config.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/service-worker/config/schema.json", 3 | "index": "/index.html", 4 | "assetGroups": [ 5 | { 6 | "name": "app", 7 | "installMode": "prefetch", 8 | "resources": { 9 | "files": [ 10 | "/favicon.ico", 11 | "/index.html", 12 | "/manifest.webmanifest", 13 | "/*.css", 14 | "/*.js" 15 | ] 16 | } 17 | }, 18 | { 19 | "name": "assets", 20 | "installMode": "lazy", 21 | "updateMode": "prefetch", 22 | "resources": { 23 | "files": [ 24 | "/assets/**", 25 | "/*.(svg|cur|jpg|jpeg|png|apng|webp|avif|gif|otf|ttf|woff|woff2)" 26 | ] 27 | } 28 | } 29 | ] 30 | } 31 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "mobile-scanning-demo", 3 | "version": "1.1.0", 4 | "author": "alex@classycode.com", 5 | "license": "Apache-2.0", 6 | "scripts": { 7 | "ng": "ng", 8 | "start": "ng serve", 9 | "build": "ng build", 10 | "watch": "ng build --watch --configuration development", 11 | "test": "ng test" 12 | }, 13 | "private": true, 14 | "dependencies": { 15 | "@angular/animations": "~13.1.0", 16 | "@angular/common": "~13.1.0", 17 | "@angular/compiler": "~13.1.0", 18 | "@angular/core": "~13.1.0", 19 | "@angular/forms": "~13.1.0", 20 | "@angular/platform-browser": "~13.1.0", 21 | "@angular/platform-browser-dynamic": "~13.1.0", 22 | "@angular/router": "~13.1.0", 23 | "@angular/service-worker": "~13.1.0", 24 | "@ericblade/quagga2": "^1.4.2", 25 | "rxjs": "~7.4.0", 26 | "tslib": "^2.3.0", 27 | "zone.js": "~0.11.4" 28 | }, 29 | "devDependencies": { 30 | "@angular-devkit/build-angular": "~13.1.2", 31 | "@angular/cli": "~13.1.2", 32 | "@angular/compiler-cli": "~13.1.0", 33 | "@types/jasmine": "~3.10.0", 34 | "@types/node": "^12.11.1", 35 | "jasmine-core": "~3.10.0", 36 | "karma": "~6.3.0", 37 | "karma-chrome-launcher": "~3.1.0", 38 | "karma-coverage": "~2.1.0", 39 | "karma-jasmine": "~4.0.0", 40 | "karma-jasmine-html-reporter": "~1.7.0", 41 | "typescript": "~4.5.2" 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/app/app.component.html: -------------------------------------------------------------------------------- 1 |
2 | {{ errorMessage }} 3 |
4 | 5 |
6 | 7 |
8 | 9 |
10 | This is a companion app for the blog post located here. 11 | The source code is available on Github. 12 |
13 | 14 |
15 |
16 | 17 | 18 |   19 | 20 |
21 | 22 |
23 | 24 |
25 | 26 | Shopping cart is empty 27 | 28 | 29 | 33 | 34 | 35 |
36 | Total: {{ totalPrice }} USD 37 |
38 |
39 |
40 | -------------------------------------------------------------------------------- /src/app/app.component.scss: -------------------------------------------------------------------------------- 1 | .error-message { 2 | background-color: black; 3 | text-align: center; 4 | color: red; 5 | padding: 8px; 6 | } 7 | 8 | #scanner-container { 9 | height: 300px; 10 | position: relative; 11 | } 12 | 13 | #scanner-container::ng-deep canvas { 14 | visibility: hidden; 15 | position: absolute; 16 | left: 0; 17 | top: 0; 18 | } 19 | 20 | #scanner-container::ng-deep video { 21 | width: 100%; 22 | height: 300px; 23 | object-fit: cover; 24 | } 25 | 26 | .controls { 27 | padding-top: 8px; 28 | padding-left: 16px; 29 | padding-right: 16px; 30 | } 31 | 32 | .shopping-cart { 33 | padding: 16px; 34 | } 35 | 36 | .instructions { 37 | padding-left: 16px; 38 | padding-right: 16px; 39 | padding-top: 16px; 40 | font-size: 0.6em; 41 | z-index: 100; 42 | } 43 | 44 | .shopping-cart-total { 45 | margin-top: 16px; 46 | font-size: 1.6em; 47 | font-weight: bold; 48 | text-align: right; 49 | } 50 | -------------------------------------------------------------------------------- /src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { AfterViewInit, ChangeDetectorRef, Component } from '@angular/core'; 2 | import { BeepService } from './beep.service'; 3 | import Quagga from '@ericblade/quagga2'; 4 | import { Article } from './article'; 5 | import { ShoppingCart } from './shopping-cart'; 6 | import { UpdateService } from './update.service'; 7 | import { environment } from '../environments/environment'; 8 | import { getMainBarcodeScanningCamera } from './camera-access'; 9 | 10 | @Component({ 11 | selector: 'app-root', 12 | templateUrl: './app.component.html', 13 | styleUrls: ['./app.component.scss'] 14 | }) 15 | export class AppComponent implements AfterViewInit { 16 | 17 | started: boolean | undefined; 18 | errorMessage: string | undefined; 19 | acceptAnyCode = true; 20 | items: [Article, number][] = []; 21 | totalPrice: number = 0; 22 | 23 | private catalogue: Article[] = [ 24 | { name: 'Classy Crab (red)', ean: '7601234567890', image: 'assets/classy_crab_red.png', price: 10 }, 25 | { name: 'Classy Crab (blue)', ean: '7601234561232', image: 'assets/classy_crab_blue.png', price: 10 }, 26 | { name: 'Classy Crab (gold, ltd. ed.)', ean: '7601234564561', image: 'assets/classy_crab_gold.png', price: 50 } 27 | ]; 28 | 29 | private shoppingCart: ShoppingCart; 30 | private lastScannedCode: string | undefined; 31 | private lastScannedCodeDate: number | undefined; 32 | 33 | constructor(private changeDetectorRef: ChangeDetectorRef, 34 | private beepService: BeepService, 35 | private updateService: UpdateService) { 36 | this.shoppingCart = new ShoppingCart(); 37 | } 38 | 39 | ngAfterViewInit(): void { 40 | if (!navigator.mediaDevices || !(typeof navigator.mediaDevices.getUserMedia === 'function')) { 41 | this.errorMessage = 'getUserMedia is not supported'; 42 | return; 43 | } 44 | 45 | this.initializeScanner(); 46 | 47 | if (environment.production) { 48 | setTimeout(() => { 49 | this.updateService.checkForUpdates(); 50 | }, 10000); 51 | } 52 | } 53 | 54 | private initializeScanner(): Promise { 55 | if (!navigator.mediaDevices || !(typeof navigator.mediaDevices.getUserMedia === 'function')) { 56 | this.errorMessage = 'getUserMedia is not supported. Please use Chrome on Android or Safari on iOS'; 57 | this.started = false; 58 | return Promise.reject(this.errorMessage); 59 | } 60 | 61 | // enumerate devices and do some heuristics to find a suitable first camera 62 | return Quagga.CameraAccess.enumerateVideoDevices() 63 | .then(mediaDeviceInfos => { 64 | const mainCamera = getMainBarcodeScanningCamera(mediaDeviceInfos); 65 | if (mainCamera) { 66 | console.log(`Using ${mainCamera.label} (${mainCamera.deviceId}) as initial camera`); 67 | return this.initializeScannerWithDevice(mainCamera.deviceId); 68 | } else { 69 | console.error(`Unable to determine suitable camera, will fall back to default handling`); 70 | return this.initializeScannerWithDevice(undefined); 71 | } 72 | }) 73 | .catch(error => { 74 | this.errorMessage = `Failed to enumerate devices: ${error}`; 75 | this.started = false; 76 | }); 77 | } 78 | 79 | private initializeScannerWithDevice(preferredDeviceId: string | undefined): Promise { 80 | console.log(`Initializing Quagga scanner...`); 81 | 82 | const constraints: MediaTrackConstraints = {}; 83 | if (preferredDeviceId) { 84 | // if we have a specific device, we select that 85 | constraints.deviceId = preferredDeviceId; 86 | } else { 87 | // otherwise we tell the browser we want a camera facing backwards (note that browser does not always care about this) 88 | constraints.facingMode = 'environment'; 89 | } 90 | 91 | return Quagga.init({ 92 | inputStream: { 93 | type: 'LiveStream', 94 | constraints, 95 | area: { // defines rectangle of the detection/localization area 96 | top: '25%', // top offset 97 | right: '10%', // right offset 98 | left: '10%', // left offset 99 | bottom: '25%' // bottom offset 100 | }, 101 | target: document.querySelector('#scanner-container') ?? undefined 102 | }, 103 | decoder: { 104 | readers: ['ean_reader'], 105 | multiple: false 106 | }, 107 | // See: https://github.com/ericblade/quagga2/blob/master/README.md#locate 108 | locate: false 109 | }, 110 | (err) => { 111 | if (err) { 112 | console.error(`Quagga initialization failed: ${err}`); 113 | this.errorMessage = `Initialization error: ${err}`; 114 | this.started = false; 115 | } else { 116 | console.log(`Quagga initialization succeeded`); 117 | Quagga.start(); 118 | this.started = true; 119 | this.changeDetectorRef.detectChanges(); 120 | Quagga.onDetected((res) => { 121 | if (res.codeResult.code) { 122 | this.onBarcodeScanned(res.codeResult.code); 123 | } 124 | }); 125 | } 126 | }); 127 | } 128 | 129 | onBarcodeScanned(code: string) { 130 | 131 | // ignore duplicates for an interval of 1.5 seconds 132 | const now = new Date().getTime(); 133 | if (code === this.lastScannedCode 134 | && ((this.lastScannedCodeDate !== undefined) && (now < this.lastScannedCodeDate + 1500))) { 135 | return; 136 | } 137 | 138 | // only accept articles from catalogue 139 | let article = this.catalogue.find(a => a.ean === code); 140 | if (!article) { 141 | if (this.acceptAnyCode) { 142 | article = this.createUnknownArticle(code); 143 | } else { 144 | return; 145 | } 146 | } 147 | this.shoppingCart.addArticle(article); 148 | this.items = this.shoppingCart.contents; 149 | this.totalPrice = this.shoppingCart.totalPrice; 150 | 151 | this.lastScannedCode = code; 152 | this.lastScannedCodeDate = now; 153 | this.beepService.beep(); 154 | this.changeDetectorRef.detectChanges(); 155 | } 156 | 157 | clearCart() { 158 | this.shoppingCart.clear(); 159 | this.items = this.shoppingCart.contents; 160 | } 161 | 162 | private createUnknownArticle(code: string): Article { 163 | return { 164 | ean: code, 165 | name: `Code ${code}`, 166 | image: 'assets/classy_crab_unknown.png', 167 | price: 42 168 | } 169 | } 170 | 171 | } 172 | -------------------------------------------------------------------------------- /src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { BrowserModule } from '@angular/platform-browser'; 3 | import { FormsModule } from '@angular/forms'; 4 | import { ServiceWorkerModule, SwRegistrationOptions } from '@angular/service-worker'; 5 | 6 | import { AppComponent } from './app.component'; 7 | import { ShoppingCartItemComponent } from './shopping-cart-item/shopping-cart-item.component'; 8 | 9 | import { environment } from '../environments/environment'; 10 | 11 | @NgModule({ 12 | declarations: [ 13 | AppComponent, 14 | ShoppingCartItemComponent 15 | ], 16 | imports: [ 17 | BrowserModule, 18 | FormsModule, 19 | 20 | // PWA support 21 | ServiceWorkerModule.register('ngsw-worker.js') 22 | ], 23 | providers: [ 24 | { 25 | provide: SwRegistrationOptions, 26 | useFactory: () => { 27 | return { 28 | enabled: environment.production, 29 | registrationStrategy: 'registerImmediately' 30 | }; 31 | } 32 | }, 33 | ], 34 | bootstrap: [AppComponent] 35 | }) 36 | export class AppModule { 37 | } 38 | -------------------------------------------------------------------------------- /src/app/article.ts: -------------------------------------------------------------------------------- 1 | export interface Article { 2 | ean: string; 3 | name: string; 4 | image: string; 5 | price: number; 6 | } 7 | -------------------------------------------------------------------------------- /src/app/beep.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | 3 | @Injectable({ 4 | providedIn: 'root' 5 | }) 6 | export class BeepService { 7 | 8 | constructor() { 9 | } 10 | 11 | beep() { 12 | const audio = new Audio(); 13 | audio.src = 'assets/beep.wav'; 14 | audio.load(); 15 | audio.play(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/app/camera-access.ts: -------------------------------------------------------------------------------- 1 | const environmentFacingCameraLabelStrings: string[] = [ 2 | 'rear', 3 | 'back', 4 | 'rück', 5 | 'arrière', 6 | 'trasera', 7 | 'trás', 8 | 'traseira', 9 | 'posteriore', 10 | '后面', 11 | '後面', 12 | '背面', 13 | '后置', // alternative 14 | '後置', // alternative 15 | '背置', // alternative 16 | 'задней', 17 | 'الخلفية', 18 | '후', 19 | 'arka', 20 | 'achterzijde', 21 | 'หลัง', 22 | 'baksidan', 23 | 'bagside', 24 | 'sau', 25 | 'bak', 26 | 'tylny', 27 | 'takakamera', 28 | 'belakang', 29 | 'אחורית', 30 | 'πίσω', 31 | 'spate', 32 | 'hátsó', 33 | 'zadní', 34 | 'darrere', 35 | 'zadná', 36 | 'задня', 37 | 'stražnja', 38 | 'belakang', 39 | 'बैक' 40 | ]; 41 | 42 | export function isKnownBackCameraLabel(label: string): boolean { 43 | const labelLowerCase = label.toLowerCase(); 44 | return environmentFacingCameraLabelStrings.some(str => { 45 | return labelLowerCase.includes(str); 46 | }); 47 | } 48 | 49 | export function getMainBarcodeScanningCamera(devices: MediaDeviceInfo[]): MediaDeviceInfo | undefined { 50 | const backCameras = devices.filter(v => isKnownBackCameraLabel(v.label)); 51 | const sortedBackCameras = backCameras.sort((a, b) => a.label.localeCompare(b.label)); 52 | return sortedBackCameras.length > 0 ? sortedBackCameras[0] : undefined; 53 | } 54 | -------------------------------------------------------------------------------- /src/app/shopping-cart-item/shopping-cart-item.component.html: -------------------------------------------------------------------------------- 1 |
2 | 3 | 4 | 5 |
{{ article.name }}
6 | 7 |
{{ count }}
8 |
9 | -------------------------------------------------------------------------------- /src/app/shopping-cart-item/shopping-cart-item.component.scss: -------------------------------------------------------------------------------- 1 | .shopping-cart-item { 2 | padding: 16px; 3 | vertical-align: center; 4 | border-bottom-width: 1px; 5 | border-bottom-style: solid; 6 | border-bottom-color: #aaaaaa; 7 | display: flex; 8 | flex-direction: row; 9 | align-items: center; 10 | } 11 | 12 | .article-image { 13 | width: 40px; 14 | height: 40px; 15 | object-fit: cover; 16 | } 17 | 18 | .article-name { 19 | margin-left: 8px; 20 | font-size: 1.4em; 21 | } 22 | 23 | .article-count { 24 | margin-left: auto; 25 | font-size: 1.4em; 26 | text-align: right; 27 | } 28 | -------------------------------------------------------------------------------- /src/app/shopping-cart-item/shopping-cart-item.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, Input, OnInit } from '@angular/core'; 2 | import { Article } from '../article'; 3 | 4 | @Component({ 5 | selector: 'app-shopping-cart-item', 6 | templateUrl: './shopping-cart-item.component.html', 7 | styleUrls: ['./shopping-cart-item.component.scss'] 8 | }) 9 | export class ShoppingCartItemComponent implements OnInit { 10 | 11 | constructor() { 12 | } 13 | 14 | @Input() 15 | article: Article | undefined; 16 | 17 | @Input() 18 | count: number | undefined; 19 | 20 | ngOnInit(): void { 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /src/app/shopping-cart.ts: -------------------------------------------------------------------------------- 1 | import { Article } from './article'; 2 | 3 | export class ShoppingCart { 4 | 5 | private items: Map; 6 | 7 | constructor() { 8 | this.items = new Map(); 9 | } 10 | 11 | addArticle(article: Article) { 12 | const existingArticleCount = this.items.get(article) ?? 0; 13 | if (existingArticleCount !== 0) { 14 | this.items.set(article, existingArticleCount + 1); 15 | } else { 16 | this.items.set(article, 1); 17 | } 18 | } 19 | 20 | clear() { 21 | this.items.clear(); 22 | } 23 | 24 | get isEmpty(): boolean { 25 | return this.items.size === 0; 26 | } 27 | 28 | get totalPrice(): number { 29 | let total = 0; 30 | for (const entry of this.items.entries()) { 31 | total += entry[0].price * entry[1]; 32 | } 33 | return total; 34 | } 35 | 36 | get contents(): [Article, number][] { 37 | let result = []; 38 | for (const entry of this.items.entries()) { 39 | result.push(entry); 40 | } 41 | return result; 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /src/app/update.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { SwUpdate } from '@angular/service-worker'; 3 | 4 | @Injectable({ 5 | providedIn: 'root' 6 | }) 7 | export class UpdateService { 8 | 9 | constructor(private swUpdate: SwUpdate) { 10 | swUpdate.available.subscribe(event => { 11 | if (window.confirm(`A new update is available. Would you like to load the latest version?`)) { 12 | swUpdate.activateUpdate().then(() => document.location.reload()); 13 | } 14 | }); 15 | } 16 | 17 | checkForUpdates() { 18 | this.swUpdate.checkForUpdate(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/assets/beep.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/classycodeoss/mobile-scanning-demo/af5540498ea16aad07fcd43401e975c042a24e31/src/assets/beep.wav -------------------------------------------------------------------------------- /src/assets/classy_crab_blue.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/classycodeoss/mobile-scanning-demo/af5540498ea16aad07fcd43401e975c042a24e31/src/assets/classy_crab_blue.png -------------------------------------------------------------------------------- /src/assets/classy_crab_gold.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/classycodeoss/mobile-scanning-demo/af5540498ea16aad07fcd43401e975c042a24e31/src/assets/classy_crab_gold.png -------------------------------------------------------------------------------- /src/assets/classy_crab_red.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/classycodeoss/mobile-scanning-demo/af5540498ea16aad07fcd43401e975c042a24e31/src/assets/classy_crab_red.png -------------------------------------------------------------------------------- /src/assets/classy_crab_unknown.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/classycodeoss/mobile-scanning-demo/af5540498ea16aad07fcd43401e975c042a24e31/src/assets/classy_crab_unknown.png -------------------------------------------------------------------------------- /src/assets/icons/icon-128x128.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/classycodeoss/mobile-scanning-demo/af5540498ea16aad07fcd43401e975c042a24e31/src/assets/icons/icon-128x128.png -------------------------------------------------------------------------------- /src/assets/icons/icon-144x144.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/classycodeoss/mobile-scanning-demo/af5540498ea16aad07fcd43401e975c042a24e31/src/assets/icons/icon-144x144.png -------------------------------------------------------------------------------- /src/assets/icons/icon-152x152.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/classycodeoss/mobile-scanning-demo/af5540498ea16aad07fcd43401e975c042a24e31/src/assets/icons/icon-152x152.png -------------------------------------------------------------------------------- /src/assets/icons/icon-192x192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/classycodeoss/mobile-scanning-demo/af5540498ea16aad07fcd43401e975c042a24e31/src/assets/icons/icon-192x192.png -------------------------------------------------------------------------------- /src/assets/icons/icon-384x384.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/classycodeoss/mobile-scanning-demo/af5540498ea16aad07fcd43401e975c042a24e31/src/assets/icons/icon-384x384.png -------------------------------------------------------------------------------- /src/assets/icons/icon-512x512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/classycodeoss/mobile-scanning-demo/af5540498ea16aad07fcd43401e975c042a24e31/src/assets/icons/icon-512x512.png -------------------------------------------------------------------------------- /src/assets/icons/icon-72x72.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/classycodeoss/mobile-scanning-demo/af5540498ea16aad07fcd43401e975c042a24e31/src/assets/icons/icon-72x72.png -------------------------------------------------------------------------------- /src/assets/icons/icon-96x96.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/classycodeoss/mobile-scanning-demo/af5540498ea16aad07fcd43401e975c042a24e31/src/assets/icons/icon-96x96.png -------------------------------------------------------------------------------- /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` 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/plugins/zone-error'; // Included with Angular CLI. 17 | -------------------------------------------------------------------------------- /src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/classycodeoss/mobile-scanning-demo/af5540498ea16aad07fcd43401e975c042a24e31/src/favicon.ico -------------------------------------------------------------------------------- /src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | PWA Scan Demo 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /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/manifest.webmanifest: -------------------------------------------------------------------------------- 1 | { 2 | "name": "PWA Scan Demo", 3 | "short_name": "PWA Scan Demo", 4 | "theme_color": "#ffffff", 5 | "background_color": "#1e3270", 6 | "display": "standalone", 7 | "scope": "./", 8 | "start_url": "./", 9 | "icons": [ 10 | { 11 | "src": "assets/icons/icon-72x72.png", 12 | "sizes": "72x72", 13 | "type": "image/png", 14 | "purpose": "maskable any" 15 | }, 16 | { 17 | "src": "assets/icons/icon-96x96.png", 18 | "sizes": "96x96", 19 | "type": "image/png", 20 | "purpose": "maskable any" 21 | }, 22 | { 23 | "src": "assets/icons/icon-128x128.png", 24 | "sizes": "128x128", 25 | "type": "image/png", 26 | "purpose": "maskable any" 27 | }, 28 | { 29 | "src": "assets/icons/icon-144x144.png", 30 | "sizes": "144x144", 31 | "type": "image/png", 32 | "purpose": "maskable any" 33 | }, 34 | { 35 | "src": "assets/icons/icon-152x152.png", 36 | "sizes": "152x152", 37 | "type": "image/png", 38 | "purpose": "maskable any" 39 | }, 40 | { 41 | "src": "assets/icons/icon-192x192.png", 42 | "sizes": "192x192", 43 | "type": "image/png", 44 | "purpose": "maskable any" 45 | }, 46 | { 47 | "src": "assets/icons/icon-384x384.png", 48 | "sizes": "384x384", 49 | "type": "image/png", 50 | "purpose": "maskable any" 51 | }, 52 | { 53 | "src": "assets/icons/icon-512x512.png", 54 | "sizes": "512x512", 55 | "type": "image/png", 56 | "purpose": "maskable any" 57 | } 58 | ] 59 | } 60 | -------------------------------------------------------------------------------- /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 recent versions of Safari, Chrome (including 12 | * Opera), Edge on the desktop, and iOS and Chrome on mobile. 13 | * 14 | * Learn more in https://angular.io/guide/browser-support 15 | */ 16 | 17 | /*************************************************************************************************** 18 | * BROWSER POLYFILLS 19 | */ 20 | 21 | /** 22 | * By default, zone.js will patch all possible macroTask and DomEvents 23 | * user can disable parts of macroTask/DomEvents patch by setting following flags 24 | * because those flags need to be set before `zone.js` being loaded, and webpack 25 | * will put import in the top of bundle, so user need to create a separate file 26 | * in this directory (for example: zone-flags.ts), and put the following flags 27 | * into that file, and then add the following code before importing zone.js. 28 | * import './zone-flags'; 29 | * 30 | * The flags allowed in zone-flags.ts are listed here. 31 | * 32 | * The following flags will work for all browsers. 33 | * 34 | * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame 35 | * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick 36 | * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames 37 | * 38 | * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js 39 | * with the following flag, it will bypass `zone.js` patch for IE/Edge 40 | * 41 | * (window as any).__Zone_enable_cross_context_check = true; 42 | * 43 | */ 44 | 45 | /*************************************************************************************************** 46 | * Zone JS is required by default for Angular itself. 47 | */ 48 | import 'zone.js'; // Included with Angular CLI. 49 | 50 | 51 | /*************************************************************************************************** 52 | * APPLICATION IMPORTS 53 | */ 54 | -------------------------------------------------------------------------------- /src/styles.scss: -------------------------------------------------------------------------------- 1 | /* You can add global styles to this file, and also import other style files */ 2 | 3 | html, body { height: 100%; } 4 | body { margin: 0; font-family: Roboto, "Helvetica Neue", sans-serif; } 5 | -------------------------------------------------------------------------------- /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/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 | (id: string): T; 13 | keys(): string[]; 14 | }; 15 | }; 16 | 17 | // First, initialize the Angular testing environment. 18 | getTestBed().initTestEnvironment( 19 | BrowserDynamicTestingModule, 20 | platformBrowserDynamicTesting(), 21 | ); 22 | 23 | // Then we find all the tests. 24 | const context = require.context('./', true, /\.spec\.ts$/); 25 | // And load the modules. 26 | context.keys().map(context); 27 | -------------------------------------------------------------------------------- /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 | "noImplicitOverride": true, 10 | "noPropertyAccessFromIndexSignature": true, 11 | "noImplicitReturns": true, 12 | "noFallthroughCasesInSwitch": true, 13 | "sourceMap": true, 14 | "declaration": false, 15 | "downlevelIteration": true, 16 | "experimentalDecorators": true, 17 | "moduleResolution": "node", 18 | "importHelpers": true, 19 | "target": "es2017", 20 | "module": "es2020", 21 | "lib": [ 22 | "es2020", 23 | "dom" 24 | ] 25 | }, 26 | "angularCompilerOptions": { 27 | "enableI18nLegacyMessageIdFormat": false, 28 | "strictInjectionParameters": true, 29 | "strictInputAccessModifiers": true, 30 | "strictTemplates": true 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /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 | --------------------------------------------------------------------------------