1/* 2 * Copyright 2024 Google LLC 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17import { Injectable } from '@angular/core'; 18 19export const LOOP_VIDEO = 'loop_video'; 20 21type PreferencesData = { 22 loopVideo: boolean; 23 playbackRate: number; 24}; 25 26const PREFERENCES_DEFAULT_JSON = JSON.stringify({ 27 loopVideo: false, 28 playbackRate: 1, 29}); 30 31@Injectable() 32export class Preferences { 33 private _preferences: PreferencesData; 34 35 constructor() { 36 this._preferences = loadPreferences(); 37 } 38 39 get loopVideo(): boolean { 40 return this._preferences.loopVideo; 41 } 42 43 set loopVideo(value: boolean) { 44 if (this.loopVideo == value) return; 45 this._preferences.loopVideo = value; 46 storePreferences(this._preferences); 47 } 48 49 get playbackRate(): number { 50 return this._preferences.playbackRate; 51 } 52 53 set playbackRate(value: number) { 54 if (this.playbackRate == value) return; 55 this._preferences.playbackRate = value; 56 storePreferences(this._preferences); 57 } 58} 59 60function loadPreferences(): PreferencesData { 61 const defaults = JSON.parse(PREFERENCES_DEFAULT_JSON); 62 try { 63 return { 64 ...defaults, 65 ...JSON.parse(localStorage.getItem('preferences') ?? '{}'), 66 }; 67 } catch (e) { 68 console.error('Unable to restore preferences', e); 69 return defaults; 70 } 71} 72 73function storePreferences(preferences: PreferencesData) { 74 localStorage.setItem('preferences', JSON.stringify(preferences)); 75} 76