Adding a new settings page and other tweaks for how it looks

This commit is contained in:
2026-08-20 17:04:21 -04:00
parent 13de434e6c
commit a604569a45
6 changed files with 649 additions and 68 deletions
+140
View File
@@ -32,6 +32,91 @@ QUIZ_INDICATORS = {'quiz', 'exam', 'test', 'assessment', 'exercise', 'assignment
# COURSES_LIBRARY_PATH env var.
LIBRARY_PATH = os.environ.get('COURSES_LIBRARY_PATH', '/app/courses')
# App-wide (non per-course) persisted data, e.g. display settings. Matches
# the ./data volume mount in docker-compose.yml.
DATA_DIR = os.environ.get('OFFLINEU_DATA_DIR', '/app/data')
SETTINGS_FILE = os.path.join(DATA_DIR, 'settings.json')
DEFAULT_SETTINGS = {
'theme': 'dark', # 'dark' | 'light'
'accent_color': '#007acc', # any #rrggbb hex
'font_family': 'system', # 'system' | 'sans' | 'serif' | 'monospace'
'font_size': 'medium', # 'small' | 'medium' | 'large' | 'xlarge'
'layout_width': 'wide', # 'normal' | 'wide' | 'full'
'density': 'comfortable', # 'comfortable' | 'compact'
'card_style': 'flat', # 'flat' | 'elevated' | 'bordered'
'corner_radius': 'rounded', # 'sharp' | 'rounded' | 'pill'
}
# Allowed values for every setting except accent_color (validated separately
# as a hex string). Anything outside these sets is rejected/ignored on save.
SETTINGS_CHOICES = {
'theme': {'dark', 'light'},
'font_family': {'system', 'sans', 'serif', 'monospace'},
'font_size': {'small', 'medium', 'large', 'xlarge'},
'layout_width': {'normal', 'wide', 'full'},
'density': {'comfortable', 'compact'},
'card_style': {'flat', 'elevated', 'bordered'},
'corner_radius': {'sharp', 'rounded', 'pill'},
}
# How each choice resolves to an actual CSS value. Keeping this server-side
# (rather than duplicating the mapping in JS) means the client just applies
# whatever /api/settings hands back.
FONT_FAMILY_CSS = {
'system': "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif",
'sans': "Arial, Helvetica, sans-serif",
'serif': "Georgia, 'Times New Roman', serif",
'monospace': "'Courier New', Consolas, monospace",
}
FONT_SIZE_CSS = {'small': '14px', 'medium': '16px', 'large': '18px', 'xlarge': '20px'}
LAYOUT_WIDTH_CSS = {'normal': '1000px', 'wide': '1600px', 'full': '100%'}
RADIUS_CSS = {'sharp': '2px', 'rounded': '8px', 'pill': '999px'}
HEX_COLOR_RE = re.compile(r'^#[0-9a-fA-F]{6}$')
def load_settings() -> Dict[str, Any]:
"""Load persisted display settings, filling in defaults for anything missing/invalid."""
settings = dict(DEFAULT_SETTINGS)
try:
if os.path.exists(SETTINGS_FILE):
with open(SETTINGS_FILE, 'r') as f:
saved = json.load(f)
for key, value in saved.items():
if key == 'accent_color' and isinstance(value, str) and HEX_COLOR_RE.match(value):
settings[key] = value
elif key in SETTINGS_CHOICES and value in SETTINGS_CHOICES[key]:
settings[key] = value
except (json.JSONDecodeError, OSError) as e:
print(f"Could not load settings, using defaults: {e}")
return settings
def save_settings(new_settings: Dict[str, Any]) -> Dict[str, Any]:
"""Validate and persist display settings; unknown/invalid keys are ignored."""
current = load_settings()
for key, value in new_settings.items():
if key == 'accent_color' and isinstance(value, str) and HEX_COLOR_RE.match(value):
current[key] = value
elif key in SETTINGS_CHOICES and value in SETTINGS_CHOICES[key]:
current[key] = value
os.makedirs(DATA_DIR, exist_ok=True)
with open(SETTINGS_FILE, 'w') as f:
json.dump(current, f, indent=2)
return current
def settings_css_vars(settings: Dict[str, Any]) -> Dict[str, str]:
"""Resolve a settings dict into the actual CSS custom-property values."""
return {
'--accent': settings['accent_color'],
'--font-family': FONT_FAMILY_CSS[settings['font_family']],
'--font-size-base': FONT_SIZE_CSS[settings['font_size']],
'--container-max-width': LAYOUT_WIDTH_CSS[settings['layout_width']],
'--radius': RADIUS_CSS[settings['corner_radius']],
}
@dataclass
class Lesson:
@@ -545,6 +630,61 @@ def browse_library():
})
@app.route('/settings')
def settings_page():
"""Render the display-settings page."""
current = load_settings()
return render_template(
'settings.html',
settings=current,
theme_choices=sorted(SETTINGS_CHOICES['theme']),
font_family_choices=['system', 'sans', 'serif', 'monospace'],
font_size_choices=['small', 'medium', 'large', 'xlarge'],
layout_width_choices=['normal', 'wide', 'full'],
density_choices=['comfortable', 'compact'],
card_style_choices=['flat', 'elevated', 'bordered'],
corner_radius_choices=['sharp', 'rounded', 'pill'],
)
@app.route('/api/settings', methods=['GET'])
def get_settings_api():
"""Return current settings plus their resolved CSS values, for the shared theme script."""
current = load_settings()
return jsonify({
'settings': current,
'css_vars': settings_css_vars(current)
})
@app.route('/api/settings', methods=['POST'])
def save_settings_api():
"""Persist updated display settings."""
try:
new_settings = request.get_json(force=True) or {}
saved = save_settings(new_settings)
return jsonify({
'success': True,
'settings': saved,
'css_vars': settings_css_vars(saved)
})
except Exception as e:
return jsonify({'success': False, 'error': str(e)}), 400
@app.route('/api/settings/reset', methods=['POST'])
def reset_settings_api():
"""Reset settings back to defaults."""
os.makedirs(DATA_DIR, exist_ok=True)
with open(SETTINGS_FILE, 'w') as f:
json.dump(DEFAULT_SETTINGS, f, indent=2)
return jsonify({
'success': True,
'settings': DEFAULT_SETTINGS,
'css_vars': settings_css_vars(DEFAULT_SETTINGS)
})
@app.route('/load_course', methods=['POST'])
def load_course():
"""Load course from selected directory"""