zaphyra's git: oeffisearch

fast and simple tripplanner

1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
34 
35 
36 
37 
38 
39 
40 
41 
42 
43 
44 
45 
46 
47 
48 
49 
50 
51 
52 
53 
54 
55 
56 
57 
58 
59 
60 
61 
62 
63 
64 
65 
66 
67 
68 
69 
70 
71 
72 
73 
74 
75 
76 
77 
78 
79 
80 
import { upperFirst } from './helpers.js';
import { getDefaultLanguage } from './translate.js';
import { getDefaultProfile } from './hafasClient.js';

let   state = {};
const subscribers = new Set();
const defaultSettings = {
	language: getDefaultLanguage(),
	profile: getDefaultProfile(),
	products: {},
	accessibility: 'none',
	walkingSpeed: 'normal',
	transferTime: 0,
	loyaltyCard: 'NONE',
	ageGroup: 'E',
	journeysViewMode: 'canvas',
	bikeFriendly: false,
	combineDateTime: false,
	showVia: false,
	showPrices: true,
	showDS100: true,
};

export const settings = {};
export const initSettings = async () => {
	let properties = {
		subscribe: { value: callback => {
			subscribers.add(callback);
			return () => subscribers.delete(callback);
		}},
		toggleProduct: {
			value: product => {
				let products = state.products;
				products[product] = !products[product];
				localStorage[`products.${product}`] = JSON.stringify(products[product]);
				state.products = products;
			},
		},
	};

	Object.keys(defaultSettings).forEach(key => {
		if (typeof defaultSettings[key] === 'object') {
			let prefix = `${key}.`;
			state[key] = {};

			Object.keys(localStorage)
				.filter(element => element.startsWith(prefix))
				.forEach(element => {
					state[key][element.slice(prefix.length)] = JSON.parse(localStorage[element]);
				});
		} else {
			state[key] = localStorage[key] ? JSON.parse(localStorage[key]) : defaultSettings[key];
		}

		properties[key] = {
			enumerable: true,
			get: () => state[key],
			set: newValue => {
				state[key] = newValue;
				if (typeof newValue === 'object') {
					Object.keys(newValue).forEach(objKey => {
						localStorage[`${key}.${objKey}`] = JSON.stringify(newValue[objKey]);
					});
				} else {
					localStorage[key] = JSON.stringify(newValue);
				}
				subscribers.forEach(callback => callback(settings));
			},
		};

		properties[`set${upperFirst(key)}`] = {
			value: newValue => { settings[key] = newValue; },
		};

		if (typeof defaultSettings[key] === 'boolean')
			properties[`toggle${upperFirst(key)}`] = { value: () => { settings[key] = !settings[key]; } };
	});

	Object.defineProperties(settings, properties);
};