Skip to content

Commit

Permalink
clean code #21
Browse files Browse the repository at this point in the history
  • Loading branch information
robindemourat committed Jan 14, 2025
1 parent 956d602 commit eff975b
Show file tree
Hide file tree
Showing 12 changed files with 57 additions and 78 deletions.
2 changes: 1 addition & 1 deletion background/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,5 @@ import "@plasmohq/messaging/background"

import { startHub } from "@plasmohq/messaging/pub-sub"

console.log(`BGSW - Starting Hub`)
console.debug(`BGSW - Starting Hub`)
startHub()
16 changes: 6 additions & 10 deletions background/ports/activitycrud.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,10 @@ import { type BrowseViewEvent,
type YoutubeVideoMetadata,type YoutubeShortMetadata,type TwitchLiveMetadata,type GenericViewEventMetadata,
type CaptureEventsList
} from "~types/captureEventsTypes"
import { ACTION_END, ACTION_PROGRESS, APPEND_ACTIVITY_EVENTS, BROWSE_VIEW, DELETE_ALL_DATA, DUPLICATE_DAY_DATA, GET_ACTIVITY_EVENTS, GET_BINNED_ACTIVITY_OUTLINE, GET_CHANNELS, GET_HABITS_DATA, LIVE_USER_ACTIVITY_RECORD, PLATFORMS, PREPEND_ACTIVITY_EVENTS, REPLACE_ACTIVITY_EVENTS, SERIALIZE_ALL_DATA } from "~constants";
import { ACTION_END, ACTION_PROGRESS, APPEND_ACTIVITY_EVENTS, BROWSE_VIEW, DELETE_ALL_DATA, DUPLICATE_DAY_IN_MS_DATA, GET_ACTIVITY_EVENTS, GET_BINNED_ACTIVITY_OUTLINE, GET_CHANNELS, GET_HABITS_DATA, LIVE_USER_ACTIVITY_RECORD, PLATFORMS, PREPEND_ACTIVITY_EVENTS, REPLACE_ACTIVITY_EVENTS, DAY_IN_MS } from "~constants";
import { buildDateKey, getDateBin } from "~helpers";
import type { AllData } from "~types/io";



const DAY = 24 * 3600 * 1000;

const storage = new Storage({
area: "local",
// copiedKeyList: ["shield-modulation"],
Expand All @@ -34,7 +30,7 @@ const checkTimeOfDaySpan = (date: number, [from, to]: [String, String]) : Boolea
toDate.setMinutes(+toMinutes);
// if to date is smaller than from date extend to next day
if (+toHours < +fromHours) {
toDate = new Date(toDate.getTime() + DAY);
toDate = new Date(toDate.getTime() + DAY_IN_MS);
}
return date > fromDate.getTime() && date < toDate.getTime();
}
Expand Down Expand Up @@ -308,7 +304,7 @@ const handler: PlasmoMessaging.PortHandler = async (req, res) => {
}
case GET_BINNED_ACTIVITY_OUTLINE:
const {
bin = DAY, // 'day',
bin = DAY_IN_MS, // 'day',
...settings
} = payload as GetBinnedActivityPayload;
filteredEvents = filterEvents(activity, settings as FilterEventsPayload)
Expand Down Expand Up @@ -537,7 +533,7 @@ const handler: PlasmoMessaging.PortHandler = async (req, res) => {
// }
// })
// break;
case DUPLICATE_DAY_DATA:
case DUPLICATE_DAY_IN_MS_DATA:
interface DuplicateDayDataPayload {
daySlug: string,
numberOfDays: number
Expand All @@ -562,11 +558,11 @@ const handler: PlasmoMessaging.PortHandler = async (req, res) => {
injectionIds.forEach(id => {
injectionIdMap.set(id, generateId());
})
const DAY = 3600 * 24 * 1000;
const DAY_IN_MS = 3600 * 24 * 1000;
const thatDayEvents = dayEvents.map(event => {
return {
...event,
date: new Date(new Date(event.date).getTime() - DAY * i),
date: new Date(new Date(event.date).getTime() - DAY_IN_MS * i),
injectionId: injectionIdMap.get(event.injectionId),
id: generateId()
}
Expand Down
6 changes: 2 additions & 4 deletions components/Diary/DayTimeline.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@ import { useMemo } from "react"
import { inferTickTimespan, timeOfDayToMs } from "~helpers"
import { scaleLinear } from 'd3-scale';
import Measure from 'react-measure';
import { BROWSE_VIEW, LIVE_USER_ACTIVITY_RECORD, PLATFORMS_COLORS } from "~constants";

const DAY = 24 * 3600 * 1000;
import { BROWSE_VIEW, LIVE_USER_ACTIVITY_RECORD, PLATFORMS_COLORS, DAY_IN_MS } from "~constants";

export default function DayTimeline({
width: inputWidth,
Expand Down Expand Up @@ -34,7 +32,7 @@ export default function DayTimeline({
// if end time is smaller than start time add a day

if (toTimeInMs < fromTimeInMs) {
toTimeInMs += DAY;
toTimeInMs += DAY_IN_MS;
}
const realStartInMs = date + fromTimeInMs;
const realEndInMs = date + toTimeInMs;
Expand Down
6 changes: 3 additions & 3 deletions components/Diary/DiaryWrapper.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import Cover from './Cover';
import DayPage from './DayPage';
import A5Imposed from './A5Imposed';
import { formatNumber, timeOfDayToMs } from '~helpers';
import { DAY_IN_MS } from '~constants';

function DiaryWrapper({
timeSpan,
Expand Down Expand Up @@ -46,14 +47,13 @@ function DiaryWrapper({
}
// @todo compute that in a worker
const dataByDay = useMemo(() => {
const DAY = 24 * 3600 * 1000;
const fromDay = new Date(timeSpan[0]).getTime();
const toDay = new Date(timeSpan[1]).getTime();

let [fromTimeInMs, toTimeInMs] = timeOfDaySpan.map(timeOfDayToMs);
// if end time is smaller than start time add a day
if (toTimeInMs < fromTimeInMs) {
toTimeInMs += DAY;
toTimeInMs += DAY_IN_MS;
}
let current = fromDay;
const days = {}
Expand All @@ -75,7 +75,7 @@ function DiaryWrapper({
}
}

current += DAY;
current += DAY_IN_MS;
}
return days;
}, [visibleEvents, timeSpan, daysOfWeek]);
Expand Down
15 changes: 7 additions & 8 deletions components/FormComponents/DatePicker.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { prettyDate } from '~helpers';

import 'react-tooltip/dist/react-tooltip.css'
import {buildDateKey} from '~helpers';
import { DAY_IN_MS } from '~constants';

const formatDatepickerDate = d => {
d.setHours(0);
Expand All @@ -14,8 +15,6 @@ const formatDatepickerDate = d => {
return d;
}

const DAY = 3600 * 24 * 1000;

export default function DatePicker({
value,
range,
Expand Down Expand Up @@ -113,7 +112,7 @@ export default function DatePicker({
if (i === 0) {
// const startDateDay = firstOfMonth.getDay();
// add days before
let dayBefore = new Date(firstOfMonth.getTime() - DAY);
let dayBefore = new Date(firstOfMonth.getTime() - DAY_IN_MS);
let dayCount = 0;
while (dayBefore.getDay() >= +startOfWeekId) {
const newDay = {
Expand All @@ -123,7 +122,7 @@ export default function DatePicker({
weekId: dayBefore.getDay()
}
daysOfThisWeek = [newDay, ...daysOfThisWeek]
dayBefore = new Date(dayBefore.getTime() - DAY);
dayBefore = new Date(dayBefore.getTime() - DAY_IN_MS);
dayCount++;
}
// add days
Expand All @@ -134,7 +133,7 @@ export default function DatePicker({
dateNumber: currentDay.getDate(),
weekId: currentDay.getDay()
})
currentDay = new Date(currentDay.getTime() + DAY);
currentDay = new Date(currentDay.getTime() + DAY_IN_MS);
dayCount++;
}
} else {
Expand All @@ -147,7 +146,7 @@ export default function DatePicker({
dateNumber: currentDay.getDate(),
date: currentDay,
})
currentDay = new Date(currentDay.getTime() + DAY);
currentDay = new Date(currentDay.getTime() + DAY_IN_MS);
dayCount++;
}
}
Expand Down Expand Up @@ -267,7 +266,7 @@ export default function DatePicker({
const isSelected = range ? tempValue ?
date >= tempValue[0] && date <= tempValue[1] : false
: date.getTime() === value?.getTime();
const key = date ? buildDateKey(new Date(date.getTime() + DAY)) : '';
const key = date ? buildDateKey(new Date(date.getTime() + DAY_IN_MS)) : '';
const data = daysData[key];
const isDisabled = disableDatalessDays && !data;
const count = data?.value || 0;
Expand All @@ -279,7 +278,7 @@ export default function DatePicker({
}
if (range) {
if (isSelecting) {
const toDate = date.getTime() === tempValue[0].getTime() ? new Date(date.getTime() + DAY - 1) : date;
const toDate = date.getTime() === tempValue[0].getTime() ? new Date(date.getTime() + DAY_IN_MS - 1) : date;
setTempValue([tempValue[0], toDate]);
onChange([tempValue[0], toDate]);
setIsSelecting(false);
Expand Down
4 changes: 3 additions & 1 deletion constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,4 +84,6 @@ export const DEFAULT_ANNOTATIONS = {
export const PLATFORMS_COLORS = {
twitch: '#aa43ff',
youtube: '#ff0001'
}
}

export const DAY_IN_MS = 24 * 3600 * 1000;
14 changes: 6 additions & 8 deletions generateMockData.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,9 @@
// Array.from(document.querySelectorAll('td:nth-child(odd) a')).map(el => el.getAttribute('href').slice(1)).join('\n')

import { readFile } from 'fs/promises';
import { writeFile, writeFileSync } from 'fs';
import { csvFormat } from 'd3-dsv';
import { Language } from 'voynich-ipsum';
import { v4 as genId } from 'uuid';
import {DAY_IN_MS} from './constants';

import { PLATFORMS } from '~constants';

Expand All @@ -23,29 +22,28 @@ const buildMockData = ({
numberOfPastDays
}) => {
let events = [];
const DAY = 24 * 3600 * 1000;
let today = new Date();
today.setHours(0)
today.setMinutes(0)
today = today.getTime();
today = today - today % DAY;
today = today - today % DAY_IN_MS;

for (let i = 0; i < numberOfPastDays; i++) {
const day = today - DAY * i;
const day = today - DAY_IN_MS * i;
// decide if it was an active day
const wasActive = tossCoin(0.6);
if (wasActive) {
// set number of sessions
const numberOfSessions = Math.round(Math.random() * (MAX_NUMBER_OF_SESSIONS - MIN_NUMBER_OF_SESSIONS) + MIN_NUMBER_OF_SESSIONS)
// for each session create fake activity
let time = day + Math.random() * DAY;
let time = day + Math.random() * DAY_IN_MS;
let sessionIndex = 0;
while (time < day + DAY && sessionIndex < numberOfSessions) {
while (time < day + DAY_IN_MS && sessionIndex < numberOfSessions) {
const sessionDuration = Math.floor(Math.random() * 2 * 3600 * 1000);
const sessionStart = time + Math.floor(Math.random() * 3 * 3600 * 1000);
const sessionId = genId()
time = sessionStart;
if (time < day + DAY) {
if (time < day + DAY_IN_MS) {
const sessionEnd = sessionStart + sessionDuration;

// choose platform
Expand Down
10 changes: 5 additions & 5 deletions generateMockDataOld.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {writeFile, writeFileSync} from 'fs';
import { csvFormat } from 'd3-dsv';
import { Language } from 'voynich-ipsum';
import { v4 as genId } from 'uuid';
import {DAY_IN_MS} from './constants';

const lang = new Language({ seed: 1 });

Expand All @@ -29,14 +30,13 @@ const buildMockData = ({
const endOfUseReal = endOfUse || new Date().getTime();
const startOfUseReal = startOfUse || endOfUseReal - (3 * 30 * 24 * 3600 * 1000) // 3 months;

const DAY = 24 * 3600 * 1000;
const slices = [];
for (let i = startOfUseReal; i < endOfUseReal + DAY; i += DAY) {
for (let i = startOfUseReal; i < endOfUseReal + DAY_IN_MS; i += DAY_IN_MS) {
const numberOfSlices = parseInt(Math.random() * 5);
let sliceStartRel = parseInt(Math.random() * (DAY * .2));
let sliceStartRel = parseInt(Math.random() * (DAY_IN_MS * .2));
let currentSliceIndex = 0;
while (currentSliceIndex < numberOfSlices && sliceStartRel < DAY) {
const remainingTime = DAY - sliceStartRel;
while (currentSliceIndex < numberOfSlices && sliceStartRel < DAY_IN_MS) {
const remainingTime = DAY_IN_MS - sliceStartRel;
const duration = parseInt(Math.random() * remainingTime * .8);
const sliceStart = i + sliceStartRel;
const sliceEnd = i + sliceStartRel + duration;
Expand Down
28 changes: 14 additions & 14 deletions helpers.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Browser } from "~types/captureEventsTypes";
import { type Browser } from "~types/captureEventsTypes";

export function getBrowser(): Browser {
const ua = navigator.userAgent
Expand Down Expand Up @@ -85,7 +85,7 @@ export const getPlatform = (url: String): String => {
}
}

export function downloadJSONData(data:Object, filename='selfie-data.json') {
export function downloadJSONData(data:Object, filename='selfie-data.json'): void {

let blob = new Blob([JSON.stringify(data)], { type: 'application/json' });
let dlURL = window.URL.createObjectURL(blob);
Expand All @@ -95,7 +95,7 @@ export function downloadJSONData(data:Object, filename='selfie-data.json') {
document.body.appendChild(a);
a.click();
}
export function downloadTextfile(data:Object, filename='selfie-data.json', mimetype = 'application/json') {
export function downloadTextfile(data:string, filename:string='selfie-data.json', mimetype:string = 'application/json'): void {
let blob = new Blob([data], { type: mimetype });
let dlURL = window.URL.createObjectURL(blob);
let a = document.createElement('a');
Expand All @@ -105,7 +105,7 @@ export function downloadTextfile(data:Object, filename='selfie-data.json', mimet
a.click();
}

export function JSONArrayToCSVStr (items = []) {
export function JSONArrayToCSVStr (items:Array<object> = []):string {
const replacer = (key, value) => value === null ? '' : value // specify how you want to handle null values here
let header = new Set(Object.keys(items[0]));
const outputItems = items.map((item, i) => {
Expand Down Expand Up @@ -153,10 +153,10 @@ export function JSONArrayToCSVStr (items = []) {
return outputItem;
})
// console.log('outputItems', outputItems);
header = Array.from(header).sort();
const headerArray:Array<string> = Array.from(header).sort();
const csv = [
header.join(','), // header row first
...outputItems.map(row => header.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','))
headerArray.join(','), // header row first
...outputItems.map(row => headerArray.map(fieldName => JSON.stringify(row[fieldName], replacer)).join(','))
].join('\r\n');
return csv;
}
Expand All @@ -168,7 +168,7 @@ export function JSONArrayToCSVStr (items = []) {
* @param {string} style='fr'
* @returns {string}
*/
export const formatNumber = (n: Number, style: String = 'fr'): String => {
export const formatNumber = (n: number, style: string = 'fr'): string => {
if (+n === 0) {
return '0';
}
Expand Down Expand Up @@ -198,7 +198,7 @@ export const formatNumber = (n: Number, style: String = 'fr'): String => {
+ (floatPart === undefined ? '' : style === 'fr' ? ',' + floatPart : '.' + floatPart)
}

export function lengthInUtf8Bytes(str) {
export function lengthInUtf8Bytes(str:string):number {
// Matches only the 10.. bytes that are non-initial characters in a multi-byte sequence.
const m = encodeURIComponent(str).match(/%[89ABab]/g);
return str.length + (m ? m.length : 0);
Expand All @@ -208,7 +208,7 @@ export function timeOfDayToMs (span) {
return +hours * 3600 * 1000 + (+minutes) * 60 * 1000;
}

export function inferTickTimespan(timeSpan, zoomLevel = 1) {
export function inferTickTimespan(timeSpan: number, zoomLevel:number = 1):number {
const scale = timeSpan / zoomLevel;
let span;
if (scale < 150000) {
Expand Down Expand Up @@ -236,20 +236,20 @@ export function inferTickTimespan(timeSpan, zoomLevel = 1) {
return span;
}

export function buildDateKey (date) {
export function buildDateKey (date:Date):string {
return new Date(date).toJSON().split('T')[0];
}

export function prettyDate(date, daysMap, monthsMap) {
export function prettyDate(date:Date, daysMap:object, monthsMap:object) {
return date?.getTime ? `${daysMap[date.getDay()].toLowerCase()} ${date.getDate() === 1 ? '1<sup>er</sup>' : date.getDate()} ${monthsMap[date.getMonth()]} ${date.getFullYear()}` : ''
};

export function getDateBin(date, binInMs) {
export function getDateBin(date:Date, binInMs:number):number {
const timeInMs = date.getHours() * 3600 * 1000 + date.getMinutes() * 60 * 1000 + date.getSeconds() * 1000 + date.getMilliseconds();
return timeInMs - timeInMs%binInMs;
}

export function msToNiceDuration (d) {
export function msToNiceDuration (d:number):string {
const hours = Math.floor(d / 3600000);
const minutes = Math.floor((d - hours * 3600000) / 60000);
return hours ? `${hours}h${minutes}mn` : minutes + 'mn'
Expand Down
11 changes: 0 additions & 11 deletions options.tsx

This file was deleted.

Loading

0 comments on commit eff975b

Please sign in to comment.