Skip to content

Commit

Permalink
Set up settings in local storage
Browse files Browse the repository at this point in the history
  • Loading branch information
LucaScorpion committed Jan 26, 2024
1 parent 3c9386f commit 992eb96
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 4 deletions.
8 changes: 4 additions & 4 deletions src/content/add-billability-chart.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { TimeChimpApi, User } from '../TimeChimpApi';
import { toIsoDate } from '../date';
import { endOfWeek, getWeek, startOfWeek, subWeeks } from 'date-fns';
import { calculateTimeStats } from './stats';
import { getSettings } from './settings';

const api = new TimeChimpApi();

Expand Down Expand Up @@ -42,18 +43,17 @@ async function doAddBillabilityChart(date: Date, user: User) {
api.getCompany(),
]);

// TODO: Only set this when that setting is enabled.
const contractHours = user.contractHours;
const settings = getSettings();

const stats = calculateTimeStats(
times,
contractHours,
settings.relativeToContractHours ? user.contractHours : undefined,
SHOW_WEEKS,
ROLLING_AVG_WEEKS,
);
createOrUpdateChart(
stats,
!!contractHours,
settings.relativeToContractHours,
company.theme?.mainColor,
chartContainer,
);
Expand Down
60 changes: 60 additions & 0 deletions src/content/settings.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
const STORAGE_KEY = 'tcbc-settings';

export interface Settings {
relativeToContractHours: boolean;
}

let settings: Settings | undefined;

const DEFAULT_SETTINGS: Settings = {
relativeToContractHours: false,
};

export function getSettings(): Settings {
// Try to load the settings.
if (!settings) {
tryLoadSettings();
}

// If the settings are still unset, loading failed.
// Set the default settings.
if (!settings) {
settings = { ...DEFAULT_SETTINGS };
saveSettings();
}

return settings;
}

export function updateSettings(updates: Partial<Settings>) {
settings = {
...DEFAULT_SETTINGS,
...settings,
...updates,
};
saveSettings();
}

function tryLoadSettings() {
try {
loadSettings();
} catch (e) {
console.error(`Failed to load ${STORAGE_KEY}: ${e}`);
}
}

function loadSettings() {
const str = localStorage.getItem(STORAGE_KEY);
if (!str) {
return;
}

const obj = JSON.parse(str);
settings = {
relativeToContractHours: obj.relativeToContractHours,
};
}

function saveSettings() {
localStorage.setItem(STORAGE_KEY, JSON.stringify(settings));
}

0 comments on commit 992eb96

Please sign in to comment.