Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Angular meets Project Fugu: Produktivitäts-PWAs...

Angular meets Project Fugu: Produktivitäts-PWAs auf Desktopniveau (Hands-on)

Progressive Web Apps sind ein plattformübergreifend einsetzbares Anwendungsmodell auf Web-Basis. Dank Project Fugu, einer Initiative der Chrome-Contributors Google, Microsoft und Intel, wird das Web um noch mächtigere Features erweitert. Damit können Entwickler endlich auch Produktivitäts-Apps wie Büro- und Bearbeitungsprogramme oder IDEs sinnvoll ins Web bringen.

In diesem Workshop zeigt Ihnen Christian Liebel von Thinktecture, wie Sie mit Angular Produktivitätsapps auf Desktopniveau entwickeln können – Zugriff auf das Dateisystem und die Zwischenablage sowie Dateizuordnungen inklusive. Und Sie können mitentwickeln: Bitte bringen Sie dazu Ihr Notebook (ohne Corporate-Proxys/Unternehmensrichtlinien) mit installiertem Google Chrome Canary, Node.js und Microsoft Visual Studio Code mit.

Christian Liebel

March 24, 2022
Tweet

More Decks by Christian Liebel

Other Decks in Programming

Transcript

  1. Hello, it’s me. Angular meets Project Fugu Produktivitäts-PWAs auf Desktopniveau

    Christian Liebel Twitter: @christianliebel Email: christian.liebel @thinktecture.com Angular & PWA Slides: thinktecture.com /christian-liebel
  2. Things NOT to expect - Blueprint for PWA development -

    No AuthN/AuthZ - No 1:1 support Things To Expect - Extensive/up-to-date insights into PWA and Project Fugu - A productivity app use case that works on your desktop & smartphone - Lots of fun Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  3. https://paint.js.org – Productivity app – Draw images – Lots of

    actions & tools – Installable – Read/save files – Copy/paste images from/to clipboard – Share files to other apps – Register for file extensions Demo Use Case Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  4. (Workshop Edition) – Productivity app – Draw images – Lots

    of actions & tools – Installable – Read/save files – Copy/paste images from/to clipboard – Share files to other apps – Register for file extensions Demo Use Case Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  5. Setup complete? (Node.js, Google Chrome, Editor, Git) Setup (1/3) LAB

    Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  6. git clone https://github.com/thinktecture/angular- days-spring-2022-fugu.git cd angular-days-spring-2022-fugu npm i npm start

    Setup (3/3) LAB Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  7. Canvas – Plain bitmap for the web – Cross-platform, hardware-

    accelerated graphics operations – Supports different contexts (2D, 3D: WebGL, WebGL 2.0) – Supported on all evergreen browsers and on IE 9+ Paint Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  8. Canvas Add a canvas element to app.component.html (line 5): <canvas

    #canvas width="600" height="480"></canvas> Query the canvas element in app.component.ts (line 10): @ViewChild('canvas') canvas: ElementRef<HTMLCanvasElement>; context: CanvasRenderingContext2D; Paint EX #1 Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  9. Canvas 2D Context fillRect(x, y, width, height) strokeRect(x, y, width,

    height) beginPath() moveTo(x, y) lineTo(x, y) fill() stroke() Paint Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  10. Canvas 2D Context Get the 2D context and prepare the

    canvas in app.component.ts in the method ngAfterViewInit(): const canvas = this.canvas.nativeElement; const ctx = this.context = canvas.getContext('2d'); ctx.fillStyle = 'white'; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.fillStyle = 'black'; Paint EX #2 Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  11. Low-latency Rendering Paint Web pages need to synchronize with the

    DOM on graphics updates causing latencies that can make drawing difficult Low-latency rendering skips syncing with the DOM with can lead to a more natural experience Supported on Chrome (Chrome OS and Windows only) Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  12. Low-latency Rendering Opt-in to low-latency rendering (app.component.ts): const ctx =

    this.context = canvas.getContext('2d', { desynchronized: true }); Paint EX #3 Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  13. Pointer Events Paint Users nowadays use different input methods, cross-platform

    apps should cover all of them Pointer Events offer an abstract interface to catch all input methods (pointerdown, pointermove, pointerup) event.offsetX/event.offsetY contain the pointer’s position relative to the listener Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  14. Pointer Events Add event listeners (app.component.html and app.component.ts): <canvas #canvas

    width="600" height="480" (pointerdown)="onPointerDown($event)" (pointermove)="onPointerMove(canvas, $event)" (pointerup)="onPointerUp()"></canvas> onPointerMove(canvas: HTMLCanvasElement, event: PointerEvent): void { this.context.fillRect(Math.floor(event.offsetX), Math.floor(event.offsetY), 2, 2); } Paint EX #4 Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  15. Bresenham Line Algorithm The user may move faster than the

    input can be processed For this case, we need to remember the previous point and interpolate the points in between The Bresenham line algorithm calculates the missing pixels between two given points Paint Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  16. Bresenham Line Algorithm Update the method onPointerMove() in app.component.ts: if

    (this.previousPoint) { const currentPoint = {x: Math.floor(event.offsetX), y: Math.floor(event.offsetY)}; const points = this.paintService.bresenhamLine(this.previousPoint.x, this.previousPoint.y, currentPoint.x, currentPoint.y); for (const {x, y} of points) { this.context.fillRect(x, y, 2, 2); } this.previousPoint = currentPoint; } Paint EX #5 Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  17. Color Selection For this demo, we will only implement the

    brush tool. However, we want to bring in some color. A simple method to implement a color selection is to use the HTML color-type input element that shows the native color picker: <input type="color"> Paint Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  18. Color Selection 1. In app.component.html, add the following input to

    the <nav> node: <input type="color" (change)="colorChange($event)"> 2. In app.component.ts, add the following code in the method colorChange(): this.context.fillStyle = $event.target.value; Paint EX #6 Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  19. Responsive Linkable Discoverable Installable App-like Connectivity Independent Fresh Safe Re-engageable

    Progressive Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  20. Web App Manifest Distinguishes Web Apps from Websites JSON-based file

    containing metadata for apps only Apps can be identified by search engines, app store providers, etc. PWA Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  21. manifest.webmanifest { "short_name": "Paint", "name": "Paint Workshop", "theme_color": "white", "icons":

    [{ "src": "icon.png", "sizes": "512x512" }], "start_url": "/index.html", "display": "standalone", "shortcuts": [/* … */] } PWA Names Icons Display Mode Shortcuts Start URL Theme color (status bar/window bar) Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  22. Manifest Icon Purposes (any) any context (e.g. app icon) monochrome

    different color requirements (at risk) maskable user agent masks icon as required PWA Safe Zone Windows iOS Android Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  23. Web App Manifest 1. In your console, run: npx ng

    add @angular/pwa 2. Update the new file manifest.webmanifest and set: a) name and short_name to values of your choice b) theme_color to #000080 and background_color to #808080 3. In index.html, set theme_color to #000080 as well. 4. Run npm start 5. Test manifest in DevTools: F12 > Application > Manifest PWA EX #7 Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  24. Manifest Shortcuts PWA Secondary entrypoints for your application (e.g., home

    screen quick actions, jump lists, …) Static definition in Web App Manifest Dynamic API may follow in the future Supported by Google Chrome for Android Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  25. Web App Manifest 1. In manifest.webmanifest, add (at least) the

    following shortcut: "shortcuts": [{ "name": "About Paint", "short_name": "About", "description": "Show information about Paint", "url": "/index.html", "icons": [{ "src": "assets/icons/icon-512x512.png", "sizes": "512x512" }] }], 2. Test in DevTools: F12 > Application > Manifest PWA EX #8 Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  26. Web App Manifest – Chrome Installability Signals Web App is

    not already installed Meets a user engagement heuristic (previously: user has interacted with domain for at least 30 seconds) Includes a Web App Manifest that has short_name or name, at least a 192px and 512px icon, a start_url and a display mode of fullscreen, standalone or minimal-ui Served over HTTPS Has a registered service worker with a fetch event handler PWA Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  27. Service Worker JavaScript snippet executed in an own thread, registered

    by the website Acts as a controller, proxy, or interceptor Has a cache to store responses (for offline availability and performance) Can wake up even when the website is closed and perform background tasks (e.g., push notifications or sync) PWA Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  28. Service Worker PWA Service Worker Internet Website HTML/JS Cache fetch

    Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  29. NgServiceWorker Angular CLI supports Service Worker generation by simply adding

    PWA support: ng add @angular/pwa One-size-fits-all Service Worker Pre-defined functionality, limited customizability PWA Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  30. Workbox Toolchain by Google Includes a CLI Generates a service

    worker implementation from directory contents (e.g., build output, or our development directory) Allows you to modify the service worker behavior (maximum flexibility) PWA Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  31. Service Worker 1. Start build with npx ng build --prod

    2. Go to dist folder: cd dist/angular-days-spring-2022-fugu 3. Start with npx lite-server 4. Test in DevTools: F12 > Application > Service Worker 5. Install the app: Address Bar > Install PWA EX #9 Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  32. Push Notifications Just as native apps, PWAs can receive push

    notifications Combination of two technologies: Web Notifications and Push API (Not supported on Safari for macOS, iOS and iPadOS!) Angular meets Project Fugu Produktivitäts-PWAs auf Desktopniveau PWA
  33. Service Worker Debugging More information on installed service workers can

    be found on • about://serviceworker- internals (Chromium) • about:serviceworkers (Mozilla Firefox) PWA Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  34. Lighthouse PWA Auditing tool by Google, integrated in Chrome DevTools

    Automatically checks performance metrics, PWA support, accessibility, SEO and other best practices and gives tips on how to improve Can simulate mobile devices Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  35. Lighthouse 1. Make sure only one tab/window of your PWA

    is open 2. Open DevTools: F12 > Lighthouse 3. Make sure to select at least the “Progressive Web App” category 4. Click “Generate report” PWA EX #10 Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  36. Project Fugu Capabilities »Let’s bring the web back – API

    by API« Thomas Steiner, Google Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  37. Capabilities Contacts Picker Screen Wake Lock API File System Access

    API Shape Detection API Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  38. Fugu Process – Write an Explainer (https://github.com/WICG/native-file- system/blob/master/EXPLAINER.md) – Discuss

    capability with developers, browser vendors, standard orgs – Iterate – Compile a design document – W3C TAG Review (https://github.com/w3ctag/design- reviews/issues/390) – Formal spec within Web Incubator Community Group (WICG, https://wicg.github.io/native-file-system/) Capabilities Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  39. Fugu Process – Implementation in Chromium – Launches behind a

    flag (chrome://flags/#enable-experimental-web- platform-features) – Origin Trial (https://developers.chrome.com/origintrials/) – Transfer to W3C Working Group + Recommendation? Capabilities Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  40. File System Access API Some applications heavily rely on working

    with files (e.g. Visual Studio Code, Adobe Photoshop, …) File System Access API allows you to open, save and override files and directories Shipped with Google Chrome 86 Capabilities Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  41. File System Access API 1. Add the following buttons to

    the <nav> bar in app.component.html (before the color input): <button (click)="open()">Open</button> <button (click)="save()">Save</button> <button (click)="copy()">Copy</button> <button (click)="paste()">Paste</button> <button (click)="share()">Share</button> Capabilities EX #11 Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  42. File System Access API 2. Add the following lines at

    the top of app.component.ts: private fileOptions = { types: [{ description: 'PNG files', accept: {'image/png': ['.png']} }] }; Capabilities EX #11 Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  43. File System Access API 3. Add the following lines in

    the method save of app.component.ts: const blob = await this.paintService.toBlob(this.canvas.nativeElement); const handle = await (window as any).showSaveFilePicker(this.fileOptions); const writable = await handle.createWritable(); await writable.write(blob); await writable.close(); Capabilities EX #11 Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  44. File System Access API Add the following code int the

    method open() of app.component.ts: const [handle] = await (window as any).showOpenFilePicker(this.fileOptions); const file = await handle.getFile(); const image = await this.paintService.getImage(file); this.context.drawImage(image, 0, 0); Capabilities EX #12 Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  45. Async Clipboard API Allows reading from/writing to the clipboard in

    an asynchronous manner (UI won’t freeze during long-running operations) Reading from the clipboard requires user consent first (privacy!) Supported by Chrome, Edge and Safari Capabilities Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  46. Async Clipboard API Add the following code in the method

    copy() of app.component.ts: const blob = await this.paintService.toBlob(this.canvas.nativeElement); await navigator.clipboard.write([ new ClipboardItem({[blob.type]: blob}) ]); Capabilities EX #13 Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  47. Async Clipboard API Add the following code in the method

    paste() of app.component.ts: const clipboardItems = await navigator.clipboard.read(); for (const clipboardItem of clipboardItems) { for (const type of clipboardItem.types) { if (type === 'image/png') { const blob = await clipboardItem.getType(type); const image = await this.paintService.getImage(blob); this.context.drawImage(image, 0, 0); } } } Capabilities EX #14 Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  48. Web Share API Allows sharing a title, URL, text, or

    files API can only be invoked as a result of a user action (i.e. a click or keypress) Files supported in Chrome on Android, Edge on Windows Capabilities Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  49. Web Share API Add the following code in the share()

    method in the app.component.ts: const blob = await this.paintService.toBlob(this.canvas.nativeElement); const file = new File([blob], 'untitled.png', {type: 'image/png'}); const item = {files: [file], title: 'untitled.png'}; if (await navigator.canShare(item)) { await navigator.share(item); } Capabilities EX #15 Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  50. File System Handling API Register your PWA as a handler

    for file extensions Requires installing the application first Declare supported extensions in Web App Manifest and add imperative code to your application logic Capabilities Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  51. File System Handling API 1. Enable the following flag in

    Chrome Canary and restart the browser: chrome://flags/#file-handling-api 2. Add the following property to your manifest (manifest.webmanifest): "file_handlers": [{ "action": "/index.html", "accept": { "image/png": [".png"] } }] Capabilities EX #16 Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  52. File System Handling API 3. Add the following code to

    the bottom of the ngAfterViewInit() method of app.component.ts: if ('launchQueue' in window) { (window as any).launchQueue.setConsumer(async params => { const [handle] = params.files; if (handle) { const file = await handle.getFile(); const image = await this.paintService.getImage(file); ctx.drawImage(image, 0, 0); } }); } 4. Re-generate Service Worker: npm run build -- --prod in main folder 5. Go to dist/basta-spring-2021-pwa-fugu and run npx lite-server Capabilities EX #16 Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  53. Summary - Project Fugu helps the web to become more

    and more capable - Project Fugu APIs could bring many more app experiences to the web (IDEs, productivity apps, etc.) - But: Web is threatened by alternative approaches and platforms, support for modern Web API varies from platform to platform - You can make a difference! - File bugs in browser engine bugtrackers - File Fugu requests: https://goo.gle/new-fugu-request Capabilities Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  54. Overview Use available interfaces and functions of a system (opposite

    of Graceful Degradation) Users with modern, feature-rich browsers get a better experience Apps are available on older browsers, but with limited functionality Concept: Browser feature support should grow over time—thereby more users can enjoy an increasing number of features Progressive Enhancement Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  55. Overview if ('serviceWorker' in navigator) { navigator.serviceWorker.register(…) .then(() => /*

    … */); } In JavaScript: check whether an API/feature is available. If yes—use it! Otherwise: 1. Disable the functionality 2. Fall back to an alternative API (if available) Progressive Enhancement Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu
  56. New powerful APIs regularly ship with new releases of Chromium-based

    browsers Some only add minor finishing touches, others enable whole application categories as productivity apps to finally make the shift to the web Some APIs already made their way into other browsers (e.g., Web Share) Fugu process makes sure that capabilities are implemented in a secure, privacy-preserving manner Let’s make the web a more capable platform! Summary Produktivitäts-PWAs auf Desktopniveau Angular meets Project Fugu