Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

fix(ui): scope zoom shortcuts to chat message text (#8564)

Akarshan Biswas978d7eb4d7cc
diff --git a/src-tauri/tauri.linux.conf.json b/src-tauri/tauri.linux.conf.json
index 31051e1e6..6aab02989 100644
--- a/src-tauri/tauri.linux.conf.json
+++ b/src-tauri/tauri.linux.conf.json
@@ -10,7 +10,7 @@
"minHeight": 740,
"resizable": true,
"fullscreen": false,
- "zoomHotkeysEnabled": true,
+ "zoomHotkeysEnabled": false,
"center": true,
"transparent": false,
"decorations": false,
diff --git a/src-tauri/tauri.macos.conf.json b/src-tauri/tauri.macos.conf.json
index 89ac0370e..a1f373dc6 100644
--- a/src-tauri/tauri.macos.conf.json
+++ b/src-tauri/tauri.macos.conf.json
@@ -10,7 +10,7 @@
"minHeight": 740,
"resizable": true,
"fullscreen": false,
- "zoomHotkeysEnabled": true,
+ "zoomHotkeysEnabled": false,
"center": true,
"hiddenTitle": true,
"transparent": true,
diff --git a/src-tauri/tauri.windows.conf.json b/src-tauri/tauri.windows.conf.json
index 2ce6d6534..8df865db6 100644
--- a/src-tauri/tauri.windows.conf.json
+++ b/src-tauri/tauri.windows.conf.json
@@ -10,7 +10,7 @@
"minHeight": 740,
"resizable": true,
"fullscreen": false,
- "zoomHotkeysEnabled": true,
+ "zoomHotkeysEnabled": false,
"center": true,
"hiddenTitle": true,
"transparent": true,
diff --git a/web-app/src/containers/PlatformMetaKey.tsx b/web-app/src/containers/PlatformMetaKey.tsx
index 9342be944..4331ee483 100644
--- a/web-app/src/containers/PlatformMetaKey.tsx
+++ b/web-app/src/containers/PlatformMetaKey.tsx
@@ -1,9 +1,5 @@
import { useMemo } from 'react'
-
-// Detect if the user is on macOS
-const isMac =
- typeof navigator !== 'undefined' &&
- navigator.userAgent.toUpperCase().indexOf('MAC') >= 0
+import { isMac } from '@/lib/shortcuts'
export function PlatformMetaKey() {
const metaKeySymbol = useMemo(() => {
diff --git a/web-app/src/hooks/__tests__/useInterfaceSettings.test.ts b/web-app/src/hooks/__tests__/useInterfaceSettings.test.ts
index 0d6d074bb..01a0029c0 100644
--- a/web-app/src/hooks/__tests__/useInterfaceSettings.test.ts
+++ b/web-app/src/hooks/__tests__/useInterfaceSettings.test.ts
@@ -1,6 +1,10 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
import { renderHook, act } from '@testing-library/react'
-import { useInterfaceSettings } from '../useInterfaceSettings'
+import {
+ MESSAGE_ZOOM_LEVELS,
+ sanitizeMessageZoom,
+ useInterfaceSettings,
+} from '../useInterfaceSettings'
// Mock constants
vi.mock('@/constants/localStorage', () => ({
@@ -158,6 +162,87 @@ describe('useInterfaceSettings', () => {
})
})
+ describe('message zoom', () => {
+ beforeEach(() => {
+ const { result } = renderHook(() => useInterfaceSettings())
+ act(() => {
+ result.current.resetMessageZoom()
+ })
+ })
+
+ it('defaults to 1', () => {
+ const { result } = renderHook(() => useInterfaceSettings())
+
+ expect(result.current.messageZoom).toBe(1)
+ })
+
+ it('steps up and down through the zoom levels', () => {
+ const { result } = renderHook(() => useInterfaceSettings())
+
+ act(() => {
+ result.current.zoomInMessages()
+ })
+ expect(result.current.messageZoom).toBe(1.1)
+
+ act(() => {
+ result.current.zoomInMessages()
+ })
+ expect(result.current.messageZoom).toBe(1.25)
+
+ act(() => {
+ result.current.zoomOutMessages()
+ })
+ expect(result.current.messageZoom).toBe(1.1)
+ })
+
+ it('clamps at the highest and lowest levels', () => {
+ const { result } = renderHook(() => useInterfaceSettings())
+
+ act(() => {
+ MESSAGE_ZOOM_LEVELS.forEach(() => result.current.zoomInMessages())
+ })
+ expect(result.current.messageZoom).toBe(
+ MESSAGE_ZOOM_LEVELS[MESSAGE_ZOOM_LEVELS.length - 1]
+ )
+
+ act(() => {
+ MESSAGE_ZOOM_LEVELS.forEach(() => result.current.zoomOutMessages())
+ })
+ expect(result.current.messageZoom).toBe(MESSAGE_ZOOM_LEVELS[0])
+ })
+
+ it('is restored by resetInterface', () => {
+ const { result } = renderHook(() => useInterfaceSettings())
+
+ act(() => {
+ result.current.zoomInMessages()
+ })
+ act(() => {
+ result.current.resetInterface()
+ })
+
+ expect(result.current.messageZoom).toBe(1)
+ })
+ })
+
+ describe('sanitizeMessageZoom', () => {
+ it('keeps values that are valid zoom levels', () => {
+ expect(sanitizeMessageZoom(1.25)).toBe(1.25)
+ })
+
+ it('snaps arbitrary values to the nearest level', () => {
+ expect(sanitizeMessageZoom(1.2)).toBe(1.25)
+ expect(sanitizeMessageZoom(5)).toBe(2)
+ expect(sanitizeMessageZoom(0.1)).toBe(0.8)
+ })
+
+ it('falls back to 1 for non-numeric values', () => {
+ expect(sanitizeMessageZoom(undefined)).toBe(1)
+ expect(sanitizeMessageZoom(Number.NaN)).toBe(1)
+ expect(sanitizeMessageZoom('1.5' as never)).toBe(1)
+ })
+ })
+
describe('Type checking', () => {
it('should only accept valid font sizes', () => {
const { result } = renderHook(() => useInterfaceSettings())
diff --git a/web-app/src/hooks/__tests__/useMessageZoom.test.ts b/web-app/src/hooks/__tests__/useMessageZoom.test.ts
new file mode 100644
index 000000000..7881e7b7a
--- /dev/null
+++ b/web-app/src/hooks/__tests__/useMessageZoom.test.ts
@@ -0,0 +1,122 @@
+import { describe, it, expect, beforeEach, vi } from 'vitest'
+import { renderHook, act } from '@testing-library/react'
+import { useMessageZoom } from '../useMessageZoom'
+import { useInterfaceSettings } from '../useInterfaceSettings'
+
+vi.mock('@/constants/localStorage', () => ({
+ localStorageKey: { settingInterface: 'setting-appearance' },
+}))
+
+vi.mock('../useTheme', () => ({
+ useTheme: {
+ getState: vi.fn(() => ({ isDark: false })),
+ subscribe: vi.fn(),
+ },
+}))
+
+vi.mock('zustand/middleware', () => ({
+ persist: (fn: any) => fn,
+ createJSONStorage: () => ({
+ getItem: vi.fn(),
+ setItem: vi.fn(),
+ removeItem: vi.fn(),
+ }),
+}))
+
+const pressKey = (key: string, init: KeyboardEventInit = {}) => {
+ const event = new KeyboardEvent('keydown', {
+ key,
+ ctrlKey: true,
+ cancelable: true,
+ ...init,
+ })
+ act(() => {
+ window.dispatchEvent(event)
+ })
+ return event
+}
+
+const zoom = () => useInterfaceSettings.getState().messageZoom
+
+describe('useMessageZoom', () => {
+ beforeEach(() => {
+ useInterfaceSettings.getState().resetMessageZoom()
+ })
+
+ it('zooms in on the meta key with either "+" or "="', () => {
+ renderHook(() => useMessageZoom())
+
+ expect(pressKey('=').defaultPrevented).toBe(true)
+ expect(zoom()).toBe(1.1)
+
+ pressKey('+', { shiftKey: true })
+ expect(zoom()).toBe(1.25)
+ })
+
+ it('zooms out on the meta key with "-"', () => {
+ renderHook(() => useMessageZoom())
+
+ expect(pressKey('-').defaultPrevented).toBe(true)
+ expect(zoom()).toBe(0.9)
+ })
+
+ it('ignores the keys without the meta key', () => {
+ renderHook(() => useMessageZoom())
+
+ const event = pressKey('=', { ctrlKey: false })
+
+ expect(event.defaultPrevented).toBe(false)
+ expect(zoom()).toBe(1)
+ })
+
+ it('ignores unrelated keys', () => {
+ renderHook(() => useMessageZoom())
+
+ pressKey('a')
+
+ expect(zoom()).toBe(1)
+ })
+
+ it('zooms on ctrl + wheel and prevents the page zoom', () => {
+ renderHook(() => useMessageZoom())
+
+ const up = new WheelEvent('wheel', {
+ deltaY: -120,
+ ctrlKey: true,
+ cancelable: true,
+ })
+ act(() => {
+ window.dispatchEvent(up)
+ })
+ expect(up.defaultPrevented).toBe(true)
+ expect(zoom()).toBe(1.1)
+
+ act(() => {
+ window.dispatchEvent(
+ new WheelEvent('wheel', { deltaY: 120, ctrlKey: true, cancelable: true })
+ )
+ })
+ expect(zoom()).toBe(1)
+ })
+
+ it('leaves plain scrolling alone', () => {
+ renderHook(() => useMessageZoom())
+
+ const event = new WheelEvent('wheel', { deltaY: -120, cancelable: true })
+ act(() => {
+ window.dispatchEvent(event)
+ })
+
+ expect(event.defaultPrevented).toBe(false)
+ expect(zoom()).toBe(1)
+ })
+
+ it('detaches its listeners on unmount', () => {
+ const { unmount } = renderHook(() => useMessageZoom())
+ unmount()
+
+ pressKey('=')
+
+ expect(zoom()).toBe(1)
+ })
+})
diff --git a/web-app/src/hooks/useHotkeys.ts b/web-app/src/hooks/useHotkeys.ts
index a12938bb1..dc65d7631 100644
--- a/web-app/src/hooks/useHotkeys.ts
+++ b/web-app/src/hooks/useHotkeys.ts
@@ -1,10 +1,6 @@
import { useEffect, useMemo } from 'react'
import { useRouter } from '@tanstack/react-router'
-
-// Detect if the user is on macOS
-const isMac =
- typeof navigator !== 'undefined' &&
- navigator.userAgent.toUpperCase().indexOf('MAC') >= 0
+import { isMac } from '@/lib/shortcuts'
interface UseKeyboardShortcutProps {
key: string
diff --git a/web-app/src/hooks/useInterfaceSettings.ts b/web-app/src/hooks/useInterfaceSettings.ts
index 29c2b580e..cb02b4ac4 100644
--- a/web-app/src/hooks/useInterfaceSettings.ts
+++ b/web-app/src/hooks/useInterfaceSettings.ts
@@ -105,8 +105,32 @@ const applyAccentColorToDOM = (colorValue: string, isDark: boolean) => {
root.style.setProperty('--primary', color.primary)
}
+export const MESSAGE_ZOOM_LEVELS = [0.8, 0.9, 1, 1.1, 1.25, 1.5, 1.75, 2]
+const defaultMessageZoom = 1
+
+export const sanitizeMessageZoom = (zoom: unknown): number => {
+ if (typeof zoom !== 'number' || !Number.isFinite(zoom)) {
+ return defaultMessageZoom
+ }
+ return MESSAGE_ZOOM_LEVELS.reduce((nearest, level) =>
+ Math.abs(level - zoom) < Math.abs(nearest - zoom) ? level : nearest
+ )
+}
+
+const stepMessageZoom = (current: number, direction: 1 | -1): number => {
+ const levels =
+ direction === 1 ? MESSAGE_ZOOM_LEVELS : [...MESSAGE_ZOOM_LEVELS].reverse()
+ const from = sanitizeMessageZoom(current)
+ return (
+ levels.find((level) =>
+ direction === 1 ? level > from : level < from
+ ) ?? from
+ )
+}
+
interface InterfaceSettingsState {
fontSize: FontSize
+ messageZoom: number
accentColor: AccentColorValue
notificationPosition: NotificationPosition
showTokenSpeed: boolean
@@ -114,6 +138,9 @@ interface InterfaceSettingsState {
renderHtmlArtifacts: boolean
autoGenerateTitle: boolean
setFontSize: (size: FontSize) => void
+ zoomInMessages: () => void
+ zoomOutMessages: () => void
+ resetMessageZoom: () => void
setAccentColor: (color: AccentColorValue) => void
setNotificationPosition: (position: NotificationPosition) => void
setShowTokenSpeed: (show: boolean) => void
@@ -127,6 +154,9 @@ type InterfaceSettingsPersistedSlice = Omit<
InterfaceSettingsState,
| 'resetInterface'
| 'setFontSize'
+ | 'zoomInMessages'
+ | 'zoomOutMessages'
+ | 'resetMessageZoom'
| 'setAccentColor'
| 'setNotificationPosition'
| 'setShowTokenSpeed'
@@ -148,6 +178,7 @@ const defaultFontSize: FontSize = '16px'
const createDefaultInterfaceValues = (): InterfaceSettingsPersistedSlice => {
return {
fontSize: defaultFontSize,
+ messageZoom: defaultMessageZoom,
accentColor: DEFAULT_ACCENT_COLOR,
notificationPosition: getDefaultNotificationPosition(),
showTokenSpeed: true,
@@ -187,6 +218,7 @@ export const useInterfaceSettings = create<InterfaceSettingsState>()(
// Update state
set({
fontSize: defaultFontSize,
+ messageZoom: defaultMessageZoom,
accentColor: DEFAULT_ACCENT_COLOR,
notificationPosition: getDefaultNotificationPosition(),
showTokenSpeed: true,
@@ -212,6 +244,16 @@ export const useInterfaceSettings = create<InterfaceSettingsState>()(
set({ fontSize: size })
},
+ zoomInMessages: () =>
+ set((state) => ({ messageZoom: stepMessageZoom(state.messageZoom, 1) })),
+
+ zoomOutMessages: () =>
+ set((state) => ({
+ messageZoom: stepMessageZoom(state.messageZoom, -1),
+ })),
+
+ resetMessageZoom: () => set({ messageZoom: defaultMessageZoom }),
+
setNotificationPosition: (position) => {
if (!isNotificationPosition(position)) return
set({ notificationPosition: position })
@@ -240,6 +282,7 @@ export const useInterfaceSettings = create<InterfaceSettingsState>()(
skipHydration: true,
partialize: (state) => ({
fontSize: state.fontSize,
+ messageZoom: state.messageZoom,
accentColor: state.accentColor,
notificationPosition: state.notificationPosition,
showTokenSpeed: state.showTokenSpeed,
@@ -261,6 +304,8 @@ export const useInterfaceSettings = create<InterfaceSettingsState>()(
state.fontSize
)
+ state.messageZoom = sanitizeMessageZoom(state.messageZoom)
+
// Get the current theme state
const { isDark } = useTheme.getState()
diff --git a/web-app/src/hooks/useMessageZoom.ts b/web-app/src/hooks/useMessageZoom.ts
new file mode 100644
index 000000000..fd0771d88
--- /dev/null
+++ b/web-app/src/hooks/useMessageZoom.ts
@@ -0,0 +1,53 @@
+import { useEffect } from 'react'
+import { isMac, PlatformShortcuts, ShortcutAction } from '@/lib/shortcuts'
+import type { ShortcutSpec } from '@/lib/shortcuts'
+import { useInterfaceSettings } from './useInterfaceSettings'
+
+const matchesZoomKey = (event: KeyboardEvent, spec: ShortcutSpec) => {
+ const metaKeyHeld = isMac ? event.metaKey : event.ctrlKey
+ const otherMetaKeyHeld = isMac ? event.ctrlKey : event.metaKey
+ if (!metaKeyHeld || otherMetaKeyHeld || event.altKey) return false
+ // Shift is not compared: '+' only exists as a shifted key on most layouts.
+ return [spec.key, ...(spec.aliasKeys ?? [])].some((key) => key === event.key)
+}
+
+/**
+ * Binds the zoom shortcuts and Ctrl/Cmd + wheel to the chat message scale.
+ *
+ * Native webview zoom is off (`zoomHotkeysEnabled: false`), so these gestures
+ * would otherwise do nothing; the default is still prevented for the browser
+ * build, where the page would zoom instead.
+ */
+export function useMessageZoom() {
+ useEffect(() => {
+ const zoomIn = PlatformShortcuts[ShortcutAction.ZOOM_IN]
+ const zoomOut = PlatformShortcuts[ShortcutAction.ZOOM_OUT]
+
+ const handleKeyDown = (event: KeyboardEvent) => {
+ const { zoomInMessages, zoomOutMessages } = useInterfaceSettings.getState()
+ if (matchesZoomKey(event, zoomIn)) {
+ event.preventDefault()
+ zoomInMessages()
+ } else if (matchesZoomKey(event, zoomOut)) {
+ event.preventDefault()
+ zoomOutMessages()
+ }
+ }
+
+ const handleWheel = (event: WheelEvent) => {
+ if (!event.ctrlKey && !event.metaKey) return
+ if (event.deltaY === 0) return
+ event.preventDefault()
+ const { zoomInMessages, zoomOutMessages } = useInterfaceSettings.getState()
+ if (event.deltaY < 0) zoomInMessages()
+ else zoomOutMessages()
+ }
+
+ window.addEventListener('keydown', handleKeyDown)
+ window.addEventListener('wheel', handleWheel, { passive: false })
+ return () => {
+ window.removeEventListener('keydown', handleKeyDown)
+ window.removeEventListener('wheel', handleWheel)
+ }
+ }, [])
+}
diff --git a/web-app/src/index.css b/web-app/src/index.css
index 9dadaced7..8ca4b80df 100644
--- a/web-app/src/index.css
+++ b/web-app/src/index.css
@@ -76,6 +76,21 @@
}
+/* Chat message zoom. --font-size-base is set inline on this element; the scale
+ has to be redeclared here because the :root copies substitute the root's
+ --font-size-base before inheriting, so overriding it alone changes nothing
+ for rules reading var(--text-*) (markdown.css). */
+.message-zoom {
+ --text-xs: calc(var(--font-size-base) * 0.75);
+ --text-sm: calc(var(--font-size-base) * 0.875);
+ --text-base: var(--font-size-base);
+ --text-lg: calc(var(--font-size-base) * 1.125);
+ --text-xl: calc(var(--font-size-base) * 1.25);
+ --text-2xl: calc(var(--font-size-base) * 1.5);
+ --text-3xl: calc(var(--font-size-base) * 1.875);
+ --text-4xl: calc(var(--font-size-base) * 2.25);
+}
+
:root {
--radius: 0.625rem;
--background: oklch(1 0 0);
diff --git a/web-app/src/lib/shortcuts/const.ts b/web-app/src/lib/shortcuts/const.ts
index fd322f6b5..a408c5708 100644
--- a/web-app/src/lib/shortcuts/const.ts
+++ b/web-app/src/lib/shortcuts/const.ts
@@ -37,11 +37,13 @@ export const PlatformShortcuts: ShortcutMap = {
// Zoom shortcuts - same on both platforms (standard shortcuts)
[ShortcutAction.ZOOM_IN]: {
key: '+',
+ aliasKeys: ['=', 'Add'],
usePlatformMetaKey: true,
},
[ShortcutAction.ZOOM_OUT]: {
key: '-',
+ aliasKeys: ['_', 'Subtract'],
usePlatformMetaKey: true,
},
}
diff --git a/web-app/src/lib/shortcuts/index.ts b/web-app/src/lib/shortcuts/index.ts
index ff545fdae..a76def0e6 100644
--- a/web-app/src/lib/shortcuts/index.ts
+++ b/web-app/src/lib/shortcuts/index.ts
@@ -7,3 +7,4 @@
export * from './types'
export * from './const'
+export * from './platform'
diff --git a/web-app/src/lib/shortcuts/platform.ts b/web-app/src/lib/shortcuts/platform.ts
new file mode 100644
index 000000000..135fd2ec5
--- /dev/null
+++ b/web-app/src/lib/shortcuts/platform.ts
@@ -0,0 +1,9 @@
+/**
+ * Runtime platform detection for shortcuts.
+ *
+ * Deliberately not the IS_MACOS build constant: the same bundle also runs in a
+ * plain browser, where the host OS is only known from the user agent.
+ */
+export const isMac =
+ typeof navigator !== 'undefined' &&
+ navigator.userAgent.toUpperCase().indexOf('MAC') >= 0
diff --git a/web-app/src/lib/shortcuts/types.ts b/web-app/src/lib/shortcuts/types.ts
index 08c387283..4081dc9bd 100644
--- a/web-app/src/lib/shortcuts/types.ts
+++ b/web-app/src/lib/shortcuts/types.ts
@@ -17,6 +17,9 @@ export enum ShortcutAction {
export interface ShortcutSpec {
key: string
+ // Extra KeyboardEvent.key values that trigger the same action, for keys whose
+ // emitted value depends on layout or shift state (e.g. '+' arrives as '=').
+ aliasKeys?: string[]
usePlatformMetaKey?: boolean
altKey?: boolean
shiftKey?: boolean
diff --git a/web-app/src/providers/KeyboardShortcuts.tsx b/web-app/src/providers/KeyboardShortcuts.tsx
index 99d2e9997..33f705f81 100644
--- a/web-app/src/providers/KeyboardShortcuts.tsx
+++ b/web-app/src/providers/KeyboardShortcuts.tsx
@@ -7,6 +7,7 @@ import { route } from '@/constants/routes'
import { PlatformShortcuts, ShortcutAction } from '@/lib/shortcuts'
import { useAgentMode } from '@/hooks/useAgentMode'
import { useAssistantSwitcher } from '@/hooks/useAssistantSwitcher'
+import { useMessageZoom } from '@/hooks/useMessageZoom'
import { TEMPORARY_CHAT_ID } from '@/constants/chat'
export function KeyboardShortcutsProvider() {
@@ -82,6 +83,9 @@ export function KeyboardShortcutsProvider() {
},
})
+ // Zoom In / Zoom Out - scales chat message text only
+ useMessageZoom()
+
// This component doesn't render anything
return null
}
diff --git a/web-app/src/routes/threads/$threadId.tsx b/web-app/src/routes/threads/$threadId.tsx
index 1aca7ab77..4c2489914 100644
--- a/web-app/src/routes/threads/$threadId.tsx
+++ b/web-app/src/routes/threads/$threadId.tsx
@@ -1,4 +1,5 @@
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
+import type { CSSProperties } from 'react'
import { createFileRoute, useParams, useSearch } from '@tanstack/react-router'
import { cn } from '@/lib/utils'
@@ -134,6 +135,8 @@ function ThreadDetail() {
const { threadId } = useParams({ from: Route.id })
const search = useSearch({ from: Route.id })
const searchThreadModel = search.threadModel
+ const fontSize = useInterfaceSettings((state) => state.fontSize)
+ const messageZoom = useInterfaceSettings((state) => state.messageZoom)
const setCurrentThreadId = useThreads((state) => state.setCurrentThreadId)
const setMessages = useMessages((state) => state.setMessages)
const addMessage = useMessages((state) => state.addMessage)
@@ -1647,7 +1650,14 @@ function ThreadDetail() {
</HeaderPage>
<div className="flex flex-1 flex-col h-full overflow-hidden">
{/* Messages Area */}
- <div className="flex-1 relative">
+ <div
+ className="message-zoom flex-1 relative"
+ style={
+ {
+ '--font-size-base': `calc(${fontSize} * ${messageZoom})`,
+ } as CSSProperties
+ }
+ >
<Conversation className="absolute inset-0 text-start">
<ConversationContent
className={cn('mx-auto w-full md:w-4/5 xl:w-4/6')}