Skip to content

Commit

Permalink
chore: format
Browse files Browse the repository at this point in the history
  • Loading branch information
timeowilliams committed Sep 22, 2024
1 parent 71d1be5 commit 76ea028
Show file tree
Hide file tree
Showing 12 changed files with 21,059 additions and 127 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/playwright.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
name: Playwright Tests

on:
on:
push:
branches:
- main
Expand Down
11 changes: 7 additions & 4 deletions electron.vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,12 @@ export default defineConfig({
},
// Externalize unnecessary dependencies from the worker
external: ['electron', 'path', 'fs', 'dotenv', '@electron-toolkit/utils', 'electron-store']
},

}
},
define: {
'process.env.API_BASE_URL': JSON.stringify(process.env.VITE_SERVER_URL_PROD || 'https://backend-production-5eec.up.railway.app'),
'process.env.API_BASE_URL': JSON.stringify(
process.env.VITE_SERVER_URL_PROD || 'https://backend-production-5eec.up.railway.app'
)
}
},
preload: {
Expand All @@ -48,7 +49,9 @@ export default defineConfig({
outDir: 'out/renderer'
},
define: {
'process.env.API_BASE_URL': JSON.stringify(process.env.VITE_SERVER_URL_PROD || 'https://backend-production-5eec.up.railway.app'),
'process.env.API_BASE_URL': JSON.stringify(
process.env.VITE_SERVER_URL_PROD || 'https://backend-production-5eec.up.railway.app'
)
}
}
})
21,043 changes: 20,988 additions & 55 deletions playwright-report/index.html

Large diffs are not rendered by default.

16 changes: 8 additions & 8 deletions playwright.config.cjs
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
// @ts-check
import { defineConfig } from "@playwright/test";
import path from "path";
import { defineConfig } from '@playwright/test'
import path from 'path'

export default defineConfig({
testDir: "./tests/e2e",
testDir: './tests/e2e',
use: {
headless: false,
viewport: null,
use: {
video: "on",
},
video: 'on'
}
},
timeout: 120000,
expect: {
timeout: 60000,
timeout: 60000
},
workers: 3,
fullyParallel: true,
retries: 0,
reporter: "html",
});
reporter: 'html'
})
4 changes: 3 additions & 1 deletion src/main/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,6 @@ dotenv.config()

const isProduction = process.env.ENV === 'production'

export const API_BASE_URL = isProduction ? process.env.VITE_SERVER_URL_PROD : process.env.VITE_SERVER_URL_DEV
export const API_BASE_URL = isProduction
? process.env.VITE_SERVER_URL_PROD
: process.env.VITE_SERVER_URL_DEV
26 changes: 11 additions & 15 deletions src/main/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import { electronApp, optimizer, is } from '@electron-toolkit/utils'
const { activeWindow } = await import('get-windows')
import Store from 'electron-store'


import { EmailService } from './emailService'
import { StoreSchema, SiteTimeTracker, ExtendedResult } from './types'
import { getUrlFromResult, formatTime, updateSiteTimeTracker } from './productivityUtils'
Expand All @@ -28,13 +27,10 @@ setupEnvironment()
const isProduction = process.env.ENV === 'production'
console.log('isProduction?', isProduction)
console.log('email', process.env.EMAIL)
console.log('API_BASE_URL', process.env.VITE_SERVER_URL_PROD )


console.log('API_BASE_URL', process.env.VITE_SERVER_URL_PROD)

const emailService = new EmailService(process.env.EMAIL || '', store)


// Initialize environment variables based on the environment
function setupEnvironment(): void {
if (app.isPackaged) {
Expand All @@ -49,7 +45,7 @@ function setupEnvironment(): void {
}

// Store user data in the electron-store and send to worker
function handleUserData(user): void {
function handleUserData(user): void {
store.set('user', {
username: user.username,
firstName: user.firstName,
Expand Down Expand Up @@ -77,7 +73,7 @@ function loadUserData() {
function resetCounters(type: 'daily' | 'weekly') {
if (type === 'daily') {
console.log('Resetting Daily Trackers')
currentSiteTimeTrackers.forEach(tracker => (tracker.timeSpent = 0))
currentSiteTimeTrackers.forEach((tracker) => (tracker.timeSpent = 0))
store.set('lastResetDate', dayjs().format('YYYY-MM-DD'))
} else if (type === 'weekly') {
console.log('Resetting Weekly Trackers')
Expand Down Expand Up @@ -116,8 +112,12 @@ function startActivityMonitoring() {
// Process activity data from active window
function processActivityData(_windowInfoData: ExtendedResult | undefined) {
if (_windowInfoData?.siteTimeTracker) {
console.log(`Time spent on ${_windowInfoData.siteTimeTracker.title}: ${formatTime(_windowInfoData.siteTimeTracker.timeSpent)}`)
console.log(`Last active timestamp: ${new Date(_windowInfoData.siteTimeTracker.lastActiveTimestamp).toISOString()}`)
console.log(
`Time spent on ${_windowInfoData.siteTimeTracker.title}: ${formatTime(_windowInfoData.siteTimeTracker.timeSpent)}`
)
console.log(
`Last active timestamp: ${new Date(_windowInfoData.siteTimeTracker.lastActiveTimestamp).toISOString()}`
)
}
}

Expand Down Expand Up @@ -158,7 +158,7 @@ async function createWindow(): Promise<BrowserWindow> {
return mainWindow
}

app.commandLine.appendSwitch('remote-allow-origins', 'devtools://devtools');
app.commandLine.appendSwitch('remote-allow-origins', 'devtools://devtools')
// Main app ready event
app.whenReady().then(async () => {
console.log('ready!')
Expand All @@ -174,7 +174,6 @@ app.whenReady().then(async () => {
schedulerWorker.postMessage({ type: 'RESET_DAILY' })
}


await createWindow()

setupPeriodicSave()
Expand Down Expand Up @@ -203,7 +202,7 @@ app.on('window-all-closed', () => {
const schedulerWorkerPath = join(__dirname, 'worker.js')
const schedulerWorker = new Worker(schedulerWorkerPath, {
workerData: {
API_BASE_URL: process.env.VITE_SERVER_URL_PROD
API_BASE_URL: process.env.VITE_SERVER_URL_PROD
}
})

Expand All @@ -213,6 +212,3 @@ schedulerWorker.on('message', (message) => {
})
schedulerWorker.on('error', (err) => console.error('Worker Error:', err))
schedulerWorker.on('message', (message) => console.log('Worker Message:', message))



2 changes: 1 addition & 1 deletion src/main/productivityUtils.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@ export declare function capitalizeFirstLetter(text: string): string
export declare function formatUrl(input: string): string
export declare function formatTime(milliseconds: number): string
export declare function updateSiteTimeTracker(windowInfo: Result): SiteTimeTracker
export declare function getOrSetLastResetDate(store: TypedStore):string
export declare function getOrSetLastResetDate(store: TypedStore): string
7 changes: 5 additions & 2 deletions src/main/productivityUtils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { parse } from 'url'
import { MacOSResult, Result, SiteTimeTracker} from './types'
import { MacOSResult, Result, SiteTimeTracker } from './types'

//TODO: Needs to be updated with user's specific sites
const unproductiveSites = ['instagram.com', 'facebook.com']
Expand Down Expand Up @@ -77,7 +77,10 @@ export function formatTime(milliseconds: number): string {
}
}

export function updateSiteTimeTracker(windowInfo: Result, timeTrackers: SiteTimeTracker[]): SiteTimeTracker {
export function updateSiteTimeTracker(
windowInfo: Result,
timeTrackers: SiteTimeTracker[]
): SiteTimeTracker {
const currentTime = Date.now()
const url = getUrlFromResult(windowInfo) || windowInfo.title

Expand Down
2 changes: 0 additions & 2 deletions src/main/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

// Currently use electron-store for persisting data in our electron application.
export interface User {
username: string
Expand All @@ -23,7 +22,6 @@ export interface SiteTimeTracker {

export type ExtendedResult = Result & { url?: string; siteTimeTracker?: SiteTimeTracker }


export type Options = {
/**
Enable the accessibility permission check. _(macOS)_
Expand Down
2 changes: 0 additions & 2 deletions src/renderer/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import { lazy, Suspense, onMount, createSignal } from 'solid-js'
import { Router, Route, A, useLocation } from '@solidjs/router'
import { render } from 'solid-js/web'


import { sendUserToBackend } from './lib/utils'
import './assets/main.css'
import logo from './assets/deepWork.svg'
Expand All @@ -18,7 +17,6 @@ const App = (props) => {
const [isNewUser, setIsNewUser] = createSignal(true)
const location = useLocation()


// Check for the token in localStorage on component mount
onMount(() => {
const token = localStorage.getItem('token') as string
Expand Down
4 changes: 2 additions & 2 deletions src/renderer/src/config.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const isProduction = import.meta.env.PROD;
const isProduction = import.meta.env.PROD

export const API_BASE_URL = isProduction
? import.meta.env.VITE_SERVER_URL_PROD
: import.meta.env.VITE_SERVER_URL_DEV;
: import.meta.env.VITE_SERVER_URL_DEV
67 changes: 33 additions & 34 deletions tests/e2e/userflow.test.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
import { _electron as electron, ElectronApplication, Page } from 'playwright';
import { test, expect } from '@playwright/test';
import {
import { _electron as electron, ElectronApplication, Page } from 'playwright'
import { test, expect } from '@playwright/test'
import {
clickMenuItemById,
findLatestBuild,
ipcMainCallFirstListener,
ipcRendererCallFirstListener,
findLatestBuild,
ipcMainCallFirstListener,
ipcRendererCallFirstListener,
parseElectronApp,
ipcMainInvokeHandler,
ipcRendererInvoke
} from 'electron-playwright-helpers'

test.describe('Electron App', () => {
let electronApp: ElectronApplication;
let electronApp: ElectronApplication

test.beforeAll(async () => {
// Launch the Electron app
Expand All @@ -26,7 +26,7 @@ test.describe('Electron App', () => {
electronApp.on('window', async (page) => {
const filename = page.url()?.split('/').pop()
console.log(`Window opened: ${filename}`)

// capture errors
page.on('pageerror', (error) => {
console.error(error)
Expand All @@ -36,51 +36,50 @@ test.describe('Electron App', () => {
console.log(msg.text())
})
})

})

test.afterAll(async () => {
// Close the Electron app
await electronApp.close();
});
await electronApp.close()
})

test('should load the main window', async () => {
// Get the first window of the Electron app
const window = await electronApp.firstWindow();
const window = await electronApp.firstWindow()

// Ensure the Electron app loads correctly
const title = await window.title();
expect(title).toBe('deepFocus');
});
const title = await window.title()
expect(title).toBe('deepFocus')
})

test('should handle user login', async () => {
const window = await electronApp.firstWindow();
const window = await electronApp.firstWindow()

// Interact with the login form
await window.fill('input[name="email"]', 'timeo.j.williams@gmail.com');
await window.fill('input[name="password"]', 'test');
await window.click('button:has-text("Login")');
await window.fill('input[name="email"]', 'timeo.j.williams@gmail.com')
await window.fill('input[name="password"]', 'test')
await window.click('button:has-text("Login")')

// Validate login success
const logoutButton = window.locator('button:has-text("Logout")');
await expect(logoutButton).toBeVisible();
});
const logoutButton = window.locator('button:has-text("Logout")')
await expect(logoutButton).toBeVisible()
})

test('should send data via IPC', async () => {
const window = await electronApp.firstWindow();
const window = await electronApp.firstWindow()

// Simulate sending data from the renderer process to the main process
await window.evaluate(() => {
window?.electron.ipcRenderer.send('send-user-data', { username: 'testuser' });
});
window?.electron.ipcRenderer.send('send-user-data', { username: 'testuser' })
})

// Simulate listening on the main process for the IPC event
const userData = await electronApp.evaluate(async ({ ipcMain }) => {
return new Promise((resolve) => {
ipcMain.on('send-user-data', (_, data) => resolve(data));
});
});
expect(userData.username).toBe('testuser');
});
});
ipcMain.on('send-user-data', (_, data) => resolve(data))
})
})

expect(userData.username).toBe('testuser')
})
})

0 comments on commit 76ea028

Please sign in to comment.