Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add theme support in browser edition #4304

Merged
merged 5 commits into from
Nov 2, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
- Added support for selecting multiple files in the attachment file picker. #4278
- browser edition:
- support for selecting custom chat wallpaper #4306
- support for themes #4304

## Changed
- style: avoid scrolling to account list items such that they're at the very edge of the list #4252
Expand Down
1 change: 0 additions & 1 deletion packages/frontend/src/components/Settings/Appearance.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -317,7 +317,6 @@ function BackgroundSelector({

async function setThemeFunction(address: string) {
try {
runtime.resolveThemeAddress(address)
await runtime.setDesktopSetting('activeTheme', address)
return true
} catch (error) {
Expand Down
3 changes: 2 additions & 1 deletion packages/runtime/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,6 @@ export interface Runtime {
theme: Theme
data: string
} | null>
resolveThemeAddress(address: string): Promise<string>
saveBackgroundImage(file: string, isDefaultPicture: boolean): Promise<string>

/** only support this if you have a real implementation for `isDroppedFileFromOutside` */
Expand All @@ -142,6 +141,8 @@ export interface Runtime {

// callbacks to set
onChooseLanguage: ((locale: string) => Promise<void>) | undefined
/** backend notifies ui to reload theme,
* either because system theme changed or the theme changed that was watched by --theme-watch */
onThemeUpdate: (() => void) | undefined
onShowDialog:
| ((kind: 'about' | 'keybindings' | 'settings') => void)
Expand Down
31 changes: 31 additions & 0 deletions packages/shared/themes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
export function parseThemeMetaData(rawTheme: string): {
name: string
description: string
} {
const meta_data_block =
/.theme-meta ?{([^]*)}/gm.exec(rawTheme)?.[1].trim() || ''

const regex = /--(\w*): ?['"]([^]*?)['"];?/gi

const meta: { [key: string]: string } = {}

let last_result: any = true

while (last_result) {
last_result = regex.exec(meta_data_block)
if (last_result) {
meta[last_result[1]] = last_result[2]
}
}

// check if name and description are defined
if (!meta.name || !meta.description) {
throw new Error(
'The meta variables meta.name and meta.description must be defined'
)
}

return <any>meta
}

export const HIDDEN_THEME_PREFIX = 'dev_'
64 changes: 50 additions & 14 deletions packages/target-browser/runtime-browser/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ import { BaseDeltaChat, yerpc } from '@deltachat/jsonrpc-client'

import type { getLogger as getLoggerFunction } from '@deltachat-desktop/shared/logger.js'
import type { setLogHandler as setLogHandlerFunction } from '@deltachat-desktop/shared/logger.js'
import {
HIDDEN_THEME_PREFIX,
parseThemeMetaData,
} from '@deltachat-desktop/shared/themes.js'

import { MessageToBackend } from '../src/runtime-ws-protocol.js'

Expand Down Expand Up @@ -118,19 +122,27 @@ class BrowserRuntime implements Runtime {
}
}

onResumeFromSleep: (() => void) | undefined
onChooseLanguage: ((locale: string) => Promise<void>) | undefined
onThemeUpdate: (() => void) | undefined
onShowDialog:
| ((kind: 'about' | 'keybindings' | 'settings') => void)
| undefined
onOpenQrUrl: ((url: string) => void) | undefined
// #region event callbacks from runtime backend

onWebxdcSendToChat:
| ((
file: { file_name: string; file_content: string } | null,
text: string | null
) => void)
| undefined
onThemeUpdate: (() => void) | undefined //!!!TODO!!!

// not used in browser, there is no menu to trigger these
onChooseLanguage: ((locale: string) => Promise<void>) | undefined
onShowDialog:
| ((kind: 'about' | 'keybindings' | 'settings') => void)
| undefined

// not used in browser - other reasons
onResumeFromSleep: (() => void) | undefined
onOpenQrUrl: ((url: string) => void) | undefined

// #endregion

openMapsWebxdc(_accountId: number, _chatId?: number | undefined): void {
throw new Error('Method not implemented.')
Expand Down Expand Up @@ -262,15 +274,39 @@ class BrowserRuntime implements Runtime {
throw new Error('setDesktopSettings request failed')
}
}
getAvailableThemes(): Promise<Theme[]> {
throw new Error('Method not implemented.')
async getAvailableThemes(): Promise<Theme[]> {
return (await fetch('/themes.json')).json()
}
async getActiveTheme(): Promise<{ theme: Theme; data: string } | null> {
return null
}
resolveThemeAddress(_address: string): Promise<string> {
this.log.critical('Method not implemented.')
throw new Error('Method not implemented.')
const address = (await this.getDesktopSettings()).activeTheme
let [location, id] = address.split(':')
if (location === 'system') {
location = 'dc'
id = window.matchMedia('(prefers-color-scheme: dark)').matches
? 'dark'
: 'light'
}
if (location !== 'dc') {
throw new Error('only dc themes are implmented in the browser edition')
}

const realPath = `/themes/${id}.css`
const theme_file_request = await fetch(realPath)
if (!theme_file_request.ok) {
throw new Error('error loading theme: ' + theme_file_request.statusText)
}
const data = await theme_file_request.text()
const metadata = parseThemeMetaData(data)

return {
theme: {
address,
description: metadata.description,
name: metadata.name,
is_prototype: id.startsWith(HIDDEN_THEME_PREFIX),
},
data,
}
}
async clearWebxdcDOMStorage(_accountId: number): Promise<void> {
// not applicable in browser
Expand Down
5 changes: 5 additions & 0 deletions packages/target-browser/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { helpRoute } from './help'
import { cleanupLogFolder, createLogHandler } from './log-handler'
import { getLogger, setLogHandler } from '@deltachat-desktop/shared/logger'
import { RCConfig } from './rc-config'
import { readThemeDir } from './themes'

const logHandler = createLogHandler()
setLogHandler(logHandler.log, RCConfig)
Expand Down Expand Up @@ -164,6 +165,10 @@ app.use('/background', express.static(join(DATA_DIR, 'background')))
app.use('/backend-api', BackendApiRoute)
app.use(helpRoute)

app.get('/themes.json', async (req, res) => {
res.json(await readThemeDir())
})

const sslserver = https.createServer(
{
key: await readFile(PRIVATE_CERTIFICATE_KEY),
Expand Down
46 changes: 46 additions & 0 deletions packages/target-browser/src/themes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { basename, join } from 'path'
import { DIST_DIR } from './config'
import { readdir, readFile } from 'fs/promises'

import { Theme } from '@deltachat-desktop/shared/shared-types'
import { getLogger } from '@deltachat-desktop/shared/logger'
import {
HIDDEN_THEME_PREFIX,
parseThemeMetaData,
} from '@deltachat-desktop/shared/themes'

const log = getLogger('main/themes')

const dc_theme_dir = join(DIST_DIR, 'themes')

export async function readThemeDir(
path: string = dc_theme_dir,
prefix: string = 'dc'
): Promise<Theme[]> {
const files = await readdir(path)
return Promise.all(
files
.filter(f => f.endsWith('.css') && f.charAt(0) !== '_')
.map(async f => {
const address = prefix + ':' + basename(f, '.css')
const file_content = await readFile(join(path, f), 'utf-8')
try {
const theme_meta = parseThemeMetaData(file_content)
return {
name: theme_meta.name,
description: theme_meta.description,
address,
is_prototype: f.startsWith(HIDDEN_THEME_PREFIX),
}
} catch (error) {
log.error('Error while parsing theme ${address}: ', error)
return {
name: address + ' [Invalid Meta]',
description: '[missing description]',
address: prefix + ':' + basename(f, '.css'),
is_prototype: f.startsWith(HIDDEN_THEME_PREFIX),
}
}
})
)
}
3 changes: 0 additions & 3 deletions packages/target-electron/runtime-electron/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -166,9 +166,6 @@ class ElectronRuntime implements Runtime {
getActiveTheme(): Promise<{ theme: Theme; data: string } | null> {
return ipcBackend.invoke('themes.getActiveTheme')
}
resolveThemeAddress(address: string): Promise<string> {
return ipcBackend.invoke('themes.getAvailableThemes', address)
}
async clearWebxdcDOMStorage(accountId: number): Promise<void> {
ipcBackend.invoke('webxdc.clearWebxdcDOMStorage', accountId)
}
Expand Down
49 changes: 9 additions & 40 deletions packages/target-electron/src/themes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,51 +3,24 @@ import { readFile, readdir } from 'fs/promises'
import { join, basename } from 'path'
import { app as rawApp, ipcMain, nativeTheme } from 'electron'

import { Theme } from '../../shared/shared-types.js'
import { getCustomThemesPath, htmlDistDir } from './application-constants.js'
import { ExtendedAppMainProcess } from './types.js'
import * as mainWindow from './windows/main.js'
import { getLogger } from '../../shared/logger.js'
import { DesktopSettings } from './desktop_settings.js'

import { Theme } from '@deltachat-desktop/shared/shared-types.js'
import {
HIDDEN_THEME_PREFIX,
parseThemeMetaData,
} from '@deltachat-desktop/shared/themes'

const app = rawApp as ExtendedAppMainProcess

const log = getLogger('main/themes')

const dc_theme_dir = join(htmlDistDir(), 'themes')

function parseThemeMetaData(rawTheme: string): {
name: string
description: string
} {
const meta_data_block =
/.theme-meta ?{([^]*)}/gm.exec(rawTheme)?.[1].trim() || ''

const regex = /--(\w*): ?['"]([^]*?)['"];?/gi

const meta: { [key: string]: string } = {}

let last_result: any = true

while (last_result) {
last_result = regex.exec(meta_data_block)
if (last_result) {
meta[last_result[1]] = last_result[2]
}
}

// check if name and description are defined
if (!meta.name || !meta.description) {
throw new Error(
'The meta variables meta.name and meta.description must be defined'
)
}

return <any>meta
}

const hidden_theme_prefix = 'dev_'

async function readThemeDir(path: string, prefix: string): Promise<Theme[]> {
const files = await readdir(path)
return Promise.all(
Expand All @@ -62,15 +35,15 @@ async function readThemeDir(path: string, prefix: string): Promise<Theme[]> {
name: theme_meta.name,
description: theme_meta.description,
address,
is_prototype: f.startsWith(hidden_theme_prefix),
is_prototype: f.startsWith(HIDDEN_THEME_PREFIX),
}
} catch (error) {
log.error('Error while parsing theme ${address}: ', error)
return {
name: address + ' [Invalid Meta]',
description: '[missing description]',
address: prefix + ':' + basename(f, '.css'),
is_prototype: f.startsWith(hidden_theme_prefix),
is_prototype: f.startsWith(HIDDEN_THEME_PREFIX),
}
}
})
Expand Down Expand Up @@ -101,7 +74,7 @@ export async function loadTheme(
name: theme_meta.name,
description: theme_meta.description,
address: theme_address,
is_prototype: basename(effective_path).startsWith(hidden_theme_prefix),
is_prototype: basename(effective_path).startsWith(HIDDEN_THEME_PREFIX),
},
data: themedata,
}
Expand Down Expand Up @@ -186,8 +159,4 @@ ipcMain.handle('themes.getActiveTheme', async () => {
}
})

ipcMain.handle('themes.resolveThemeAddress', (_, address: string) =>
resolveThemeAddress(address)
)

ipcMain.handle('themes.getAvailableThemes', getAvailableThemes)
Loading