Skip to content

Commit

Permalink
refer prefers-color-scheme media query for color schemes thanks to …
Browse files Browse the repository at this point in the history
…mui v6
  • Loading branch information
rhysd committed Aug 27, 2024
1 parent 5c27421 commit 4e21e81
Show file tree
Hide file tree
Showing 11 changed files with 23 additions and 56 deletions.
8 changes: 4 additions & 4 deletions v2/src/assets.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use crate::config::Config;
use crate::renderer::Theme as WindowTheme;
use crate::renderer::Theme;
use phf::phf_map;
use std::borrow::Cow;
use std::fs;
Expand Down Expand Up @@ -168,11 +168,11 @@ pub struct Assets {
}

impl Assets {
pub fn new(config: &Config, theme: WindowTheme) -> Self {
pub fn new(config: &Config, theme: Theme) -> Self {
let hl = config.preview().highlight();
let hljs_css = match theme {
WindowTheme::Light => load_hljs_css(&hl.light, HLJS_DEFAULT_LIGHT_CSS),
WindowTheme::Dark => load_hljs_css(&hl.dark, HLJS_DEFAULT_DARK_CSS),
Theme::Light => load_hljs_css(&hl.light, HLJS_DEFAULT_LIGHT_CSS),
Theme::Dark => load_hljs_css(&hl.dark, HLJS_DEFAULT_DARK_CSS),
};

let markdown_css = if let Some(css) = load_user_css(config) {
Expand Down
4 changes: 1 addition & 3 deletions v2/src/renderer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ pub enum MessageToRenderer<'a> {
Config {
keymaps: &'a HashMap<String, KeyAction>,
search: &'a SearchConfig,
theme: Theme,
recent: &'a [&'a Path],
home: Option<&'a Path>,
window: WindowAppearance,
Expand Down Expand Up @@ -110,7 +109,7 @@ pub trait RawMessageWriter {
fn write_to(self, writer: impl io::Write) -> io::Result<Self::Output>;
}

#[derive(Clone, Copy, PartialEq, Eq, Debug, Serialize)]
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Theme {
Dark,
Light,
Expand Down Expand Up @@ -168,7 +167,6 @@ pub trait Renderer {
fn send_message_raw<W: RawMessageWriter>(&self, writer: W) -> Result<W::Output>;
fn set_title(&self, title: &str);
fn window_state(&self) -> Option<WindowState>;
fn theme(&self) -> Theme;
fn show(&self);
fn hide(&self);
fn print(&self) -> Result<()>;
Expand Down
1 change: 0 additions & 1 deletion v2/src/shiba.rs
Original file line number Diff line number Diff line change
Expand Up @@ -303,7 +303,6 @@ where
self.renderer.send_message(MessageToRenderer::Config {
keymaps: self.config.keymaps(),
search: self.config.search(),
theme: self.renderer.theme(),
recent: &self.history.iter().collect::<Vec<_>>(),
home: self.preview.home_dir(),
window: self.renderer.window_appearance(),
Expand Down
21 changes: 7 additions & 14 deletions v2/src/wry/webview.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,22 +26,19 @@ pub type EventLoop = tao::event_loop::EventLoop<Event>;
#[cfg(not(target_os = "macos"))]
const ICON_RGBA: &[u8] = include_bytes!("../assets/icon_32x32.rgba");

fn window_theme(window: &Window) -> RendererTheme {
match window.theme() {
fn create_webview(window: &Window, event_loop: &EventLoop, config: &Config) -> Result<WebView> {
let ipc_proxy = event_loop.create_proxy();
let file_drop_proxy = event_loop.create_proxy();
let navigation_proxy = event_loop.create_proxy();
let theme = match window.theme() {
Theme::Light => RendererTheme::Light,
Theme::Dark => RendererTheme::Dark,
t => {
log::error!("Unknown window theme: {:?}", t);
RendererTheme::Light
}
}
}

fn create_webview(window: &Window, event_loop: &EventLoop, config: &Config) -> Result<WebView> {
let ipc_proxy = event_loop.create_proxy();
let file_drop_proxy = event_loop.create_proxy();
let navigation_proxy = event_loop.create_proxy();
let loader = Assets::new(config, window_theme(window));
};
let loader = Assets::new(config, theme);

let user_dir = config.data_dir().path().map(|dir| dir.join("WebView"));
log::debug!("WebView user data directory: {:?}", user_dir);
Expand Down Expand Up @@ -319,10 +316,6 @@ impl Renderer for WebViewRenderer {
Some(WindowState { width, height, x, y, fullscreen, zoom_level, always_on_top, maximized })
}

fn theme(&self) -> RendererTheme {
window_theme(&self.window)
}

fn show(&self) {
self.window.set_visible(true);
}
Expand Down
5 changes: 2 additions & 3 deletions v2/web/components/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,7 @@ import type { GlobalDispatcher } from '../dispatcher';

// Note: `CssBaseline` is not available since it sets `background-color` and prevents vibrant window.

const LIGHT_THEME = createTheme({ palette: { mode: 'light' } });
const DARK_THEME = createTheme({ palette: { mode: 'dark' } });
const THEME = createTheme({ colorSchemes: { dark: true } });

interface Props {
dispatcher: GlobalDispatcher;
Expand Down Expand Up @@ -76,7 +75,7 @@ export const App: React.FC<Props> = ({ dispatcher }) => {
}, []); // Run only when component was mounted

return (
<ThemeProvider theme={config.theme === 'light' ? LIGHT_THEME : DARK_THEME}>
<ThemeProvider theme={THEME}>
<ConfigContext.Provider value={config}>
<Preview tree={previewTree} headings={headings} path={currentPath} dispatch={dispatch} />
{searchInput}
Expand Down
5 changes: 3 additions & 2 deletions v2/web/components/Preview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { WindowBar } from './WindowBar';
import { SideBar } from './SideBar';
import { Article } from './Article';
import { ConfigContext } from './ConfigContext';
import { IS_DARK } from '../css';
import type { MarkdownReactTree } from '../markdown';
import type { Dispatch, Heading } from '../reducer';

Expand Down Expand Up @@ -34,7 +35,7 @@ export interface Props {
}

export const Preview: React.FC<Props> = ({ tree, headings, path, dispatch }) => {
const { titleBar, vibrant, borderTop, theme } = useContext(ConfigContext);
const { titleBar, vibrant, borderTop } = useContext(ConfigContext);

if (tree.root === null) {
return <></>;
Expand All @@ -48,7 +49,7 @@ export const Preview: React.FC<Props> = ({ tree, headings, path, dispatch }) =>
boxSizing?: string;
} = {};
if (!vibrant) {
sx.bgcolor = theme === 'light' ? 'grey.100' : 'grey.900';
sx.bgcolor = IS_DARK ? 'grey.900' : 'grey.100';
}
if (borderTop) {
sx.borderTop = 1;
Expand Down
2 changes: 2 additions & 0 deletions v2/web/css.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
export const IS_DARK = window.matchMedia('(prefers-color-scheme: dark)').matches;

export function parseColor(color: string): [number, number, number] | null {
if (!color.startsWith('#')) {
return null;
Expand Down
8 changes: 0 additions & 8 deletions v2/web/dispatcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,6 @@ export class GlobalDispatcher {
this.keymap.register(msg.keymaps, this);
this.dispatch(
initConfig({
theme: msg.theme === 'Dark' ? 'dark' : 'light',
titleBar: !msg.window.title,
vibrant: msg.window.vibrancy,
hideScrollBar: !msg.window.scrollBar,
Expand All @@ -90,13 +89,6 @@ export class GlobalDispatcher {
);
this.dispatch(setSearchMatcher(msg.search.matcher));
this.dispatch(setRecentFiles(msg.recent));
// `this.state.theme` is not available since it is updated *after* the first rendering of Markdown content.
// 1. Receive `config` IPC message
// 2. Dispatch `setTheme` action
// 3. Receive `render_tree` IPC message
// 4. Render the Markdown content (at this point, `this.state.theme` has not been changed yet)
// 5. Dispatched `setTheme` action is handled and `this.state` is updated
this.markdown.theme = msg.theme;
break;
case 'search':
this.openSearch();
Expand Down
2 changes: 0 additions & 2 deletions v2/web/ipc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,6 @@ export type KeyAction =

export type KeyMaps = Record<string, KeyAction>;
export type SearchMatcher = 'SmartCase' | 'CaseSensitive' | 'CaseInsensitive' | 'CaseSensitiveRegex';
export type WindowTheme = 'Dark' | 'Light';
export type Platform = 'Mac' | 'Windows' | 'Linux';
export type RenderTreeTableAlign = 'left' | 'center' | 'right' | null;
export type AlertKind = 'warning' | 'important' | 'caution' | 'note' | 'tip';
Expand Down Expand Up @@ -207,7 +206,6 @@ export type MessageFromMain =
search: {
matcher: SearchMatcher;
};
theme: WindowTheme;
recent: string[];
home: string | null;
window: {
Expand Down
21 changes: 4 additions & 17 deletions v2/web/markdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,26 +18,16 @@ import type {
RenderTreeFootNoteDef,
RenderTreeTableAlign,
RenderTreeCodeFence,
WindowTheme,
AlertKind,
} from './ipc';
import { IS_DARK } from './css';
import * as log from './log';
import { Mermaid } from './components/Mermaid';

class MermaidRenderer {
private theme: 'default' | 'dark' = 'default';
private initialized = false;
private id = 0;

setTheme(theme: WindowTheme): void {
const next = theme === 'Light' ? 'default' : 'dark';
if (this.theme !== next && this.initialized) {
this.initialized = false;
log.debug('Mermaid will be initialized again since the window theme was changed', this.theme, next, theme);
}
this.theme = next;
}

resetId(): void {
this.id = 0;
}
Expand All @@ -46,8 +36,9 @@ class MermaidRenderer {
if (this.initialized) {
return;
}
mermaid.initialize({ startOnLoad: false, theme: this.theme });
log.debug('Initialized mermaid renderer', this.theme);
const theme = IS_DARK ? 'dark' : 'default';
mermaid.initialize({ startOnLoad: false, theme });
log.debug('Initialized mermaid renderer', theme);
this.initialized = true;
}

Expand Down Expand Up @@ -524,10 +515,6 @@ export class ReactMarkdownRenderer {
private readonly mermaid = new MermaidRenderer();
private readonly mathjax = new MathJaxRenderer();

set theme(theme: WindowTheme) {
this.mermaid.setTheme(theme);
}

render(tree: RenderTreeElem[]): Promise<MarkdownReactTree> {
this.mermaid.resetId();
const renderer = new RenderTreeToReact(this.mermaid, this.mathjax);
Expand Down
2 changes: 0 additions & 2 deletions v2/web/reducer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ export interface Heading {
}

export interface Config {
theme: Theme;
titleBar: boolean;
vibrant: boolean;
hideScrollBar: boolean;
Expand All @@ -52,7 +51,6 @@ export interface State {
}

export const INITIAL_CONFIG: Config = {
theme: 'light',
titleBar: true,
vibrant: false,
hideScrollBar: false,
Expand Down

0 comments on commit 4e21e81

Please sign in to comment.