Skip to content

Speakr is a personal, self-hosted web application designed for transcribing audio recordings

Python

Theme saved with the account (D#419)

Murtaza Nasir4d8649fdcfe7
diff --git a/src/api/system.py b/src/api/system.py
index 8e600087..c8d02f9e 100644
--- a/src/api/system.py
+++ b/src/api/system.py
@@ -58,6 +58,10 @@ def init_system_helpers(**kwargs):
+# Color scheme ids, as in colorSchemes in static/js/app.modular.js.
+THEME_COLOR_SCHEMES = ('blue', 'emerald', 'purple', 'rose', 'amber', 'teal')
+
+
# --- Routes ---
@system_bp.route('/api/user/preferences', methods=['POST'])
@@ -76,7 +80,17 @@ def save_user_preferences():
if mode not in ('range', 'single'):
return jsonify({'error': 'Invalid speaker_count_mode'}), 400
current_user.speaker_count_mode = mode
-
+
+ # Theme, saved when the user changes it so other devices follow (D#419).
+ if 'dark_mode' in data:
+ if not isinstance(data['dark_mode'], bool):
+ return jsonify({'error': 'Invalid dark_mode'}), 400
+ current_user.theme_dark_mode = data['dark_mode']
+ if 'color_scheme' in data:
+ if data['color_scheme'] not in THEME_COLOR_SCHEMES:
+ return jsonify({'error': 'Invalid color_scheme'}), 400
+ current_user.theme_color_scheme = data['color_scheme']
+
db.session.commit()
return jsonify({
diff --git a/src/app.py b/src/app.py
index 287d09d1..f0096f99 100644
--- a/src/app.py
+++ b/src/app.py
@@ -789,6 +789,18 @@ def inject_i18n_bootstrap():
"""Translations embedded in pages that load i18n.js (includes/i18n_bootstrap.html)."""
return {'i18n_bootstrap': _i18n_bootstrap}
+def inject_account_theme():
+ """The theme saved with the signed-in user's account (D#419), for
+ includes/theme_account.html. None for a visitor who is not signed in."""
+ from flask import has_request_context
+ from flask_login import current_user
+ if not has_request_context() or not current_user.is_authenticated:
+ return {'account_theme': None}
+ return {'account_theme': {'dark': current_user.theme_dark_mode,
+ 'scheme': current_user.theme_color_scheme}}
+
+
@app.context_processor
def inject_inquire_mode_flag():
"""The shared header shows the Inquire button on every page."""
diff --git a/src/init_db.py b/src/init_db.py
index 83f03d07..2b3a5f33 100644
--- a/src/init_db.py
+++ b/src/init_db.py
@@ -397,6 +397,13 @@ def _run_migrations(app, engine):
if add_column_if_not_exists(engine, 'user', 'monthly_transcription_budget', 'INTEGER'):
app.logger.info("Added monthly_transcription_budget column to user table")
+ # Light/dark mode and color scheme saved with the account (D#419);
+ # null until the user changes them
+ if add_column_if_not_exists(engine, 'user', 'theme_dark_mode', 'BOOLEAN'):
+ app.logger.info("Added theme_dark_mode column to user table")
+ if add_column_if_not_exists(engine, 'user', 'theme_color_scheme', 'VARCHAR(16)'):
+ app.logger.info("Added theme_color_scheme column to user table")
+
# Storage quota in megabytes (#413)
if add_column_if_not_exists(engine, 'user', 'storage_quota_mb', 'INTEGER'):
app.logger.info("Added storage_quota_mb column to user table")
diff --git a/src/models/user.py b/src/models/user.py
index fb66fb0b..4ca38de1 100644
--- a/src/models/user.py
+++ b/src/models/user.py
@@ -109,6 +109,10 @@ class User(db.Model, UserMixin):
# Speaker-count entry mode in transcription UIs: 'range' (min/max)
# or 'single' (one count, stored as min == max). Null means 'range' (#362).
speaker_count_mode = db.Column(db.String(10), nullable=True)
+ # Light/dark mode and color scheme chosen in the app (D#419). Null until
+ # the user changes them; until then each browser keeps its own setting.
+ theme_dark_mode = db.Column(db.Boolean, nullable=True)
+ theme_color_scheme = db.Column(db.String(16), nullable=True)
# Audio player placement in the recording-detail view. 'bottom'
# (default) keeps the player anchored under the content columns;
# 'top' renders it above the columns so it sits closer to the
diff --git a/static/js/global-header.js b/static/js/global-header.js
index 482c48ef..4b271c22 100644
--- a/static/js/global-header.js
+++ b/static/js/global-header.js
@@ -70,6 +70,7 @@ async function mountGlobalHeader() {
isDarkMode.value = !isDarkMode.value;
localStorage.setItem('darkMode', isDarkMode.value);
applyTheme(isDarkMode.value);
+ if (window.speakrSaveTheme) window.speakrSaveTheme('darkMode');
};
const openInMainApp = (query) => { window.location.href = `/?${query}`; };
diff --git a/static/js/modules/composables/ui.js b/static/js/modules/composables/ui.js
index cb528e90..8f537c1d 100644
--- a/static/js/modules/composables/ui.js
+++ b/static/js/modules/composables/ui.js
@@ -73,6 +73,7 @@ export function useUI(state, utils, processedTranscription) {
// Re-apply current color scheme for new mode
applyColorScheme(currentColorScheme.value);
+ if (window.speakrSaveTheme) window.speakrSaveTheme('darkMode');
};
// Initialize dark mode from storage
@@ -144,12 +145,14 @@ export function useUI(state, utils, processedTranscription) {
// Select a color scheme
const selectColorScheme = (schemeId) => {
applyColorScheme(schemeId);
+ if (window.speakrSaveTheme) window.speakrSaveTheme('colorScheme');
showToast(t('messages.colorSchemeApplied'), 'fa-palette');
};
// Reset to default color scheme
const resetColorScheme = () => {
applyColorScheme('blue');
+ if (window.speakrSaveTheme) window.speakrSaveTheme('colorScheme');
showToast(t('messages.colorSchemeReset'), 'fa-undo');
};
diff --git a/static/js/shared-components.js b/static/js/shared-components.js
index 06a7ce14..cfc8c71f 100644
--- a/static/js/shared-components.js
+++ b/static/js/shared-components.js
@@ -15,6 +15,7 @@ function useDarkMode() {
document.documentElement.classList.remove('dark');
localStorage.setItem('darkMode', 'false');
}
+ if (window.speakrSaveTheme) window.speakrSaveTheme('darkMode');
};
const initializeDarkMode = () => {
@@ -107,6 +108,7 @@ function useColorScheme() {
const selectColorScheme = (schemeId) => {
applyColorScheme(schemeId);
+ if (window.speakrSaveTheme) window.speakrSaveTheme('colorScheme');
const scheme = colorSchemes[isDarkMode.value ? 'dark' : 'light'].find(s => s.id === schemeId);
if (window.showToast && scheme) {
window.showToast(`Applied ${scheme.name} theme`, 'fa-palette');
@@ -115,6 +117,7 @@ function useColorScheme() {
const resetColorScheme = () => {
applyColorScheme('blue');
+ if (window.speakrSaveTheme) window.speakrSaveTheme('colorScheme');
if (window.showToast) {
const defaultScheme = colorSchemes[isDarkMode.value ? 'dark' : 'light'].find(s => s.id === 'blue');
window.showToast(`Reset to default ${defaultScheme?.name || 'Ocean Blue'} theme`, 'fa-undo');
diff --git a/templates/account.html b/templates/account.html
index 4c58d7f6..4e2705e5 100644
--- a/templates/account.html
+++ b/templates/account.html
@@ -2,6 +2,7 @@
<html lang="en" class="h-full">
<head>
<meta charset="UTF-8">
+ {% include 'includes/theme_account.html' %}
<meta name="viewport" content="width=device-width, initial-scale=1.0, interactive-widget=resizes-content">
<meta name="csrf-token" content="{{ csrf_token() }}">
<meta name="robots" content="noindex, nofollow, noarchive, nosnippet, noimageindex">
diff --git a/templates/admin.html b/templates/admin.html
index 20ba0581..48840c94 100644
--- a/templates/admin.html
+++ b/templates/admin.html
@@ -2,6 +2,7 @@
<html lang="en" class="h-full">
<head>
<meta charset="UTF-8">
+ {% include 'includes/theme_account.html' %}
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="csrf-token" content="{{ csrf_token() }}">
<meta name="robots" content="noindex, nofollow, noarchive, nosnippet, noimageindex">
@@ -3514,6 +3515,7 @@ Summarization Instructions:
document.documentElement.classList.remove('dark');
localStorage.setItem('darkMode', 'false');
}
+ if (window.speakrSaveTheme) window.speakrSaveTheme('darkMode');
};
// Initialize dark mode
diff --git a/templates/group-admin.html b/templates/group-admin.html
index d4f81758..9f1fefb1 100644
--- a/templates/group-admin.html
+++ b/templates/group-admin.html
@@ -2,6 +2,7 @@
<html lang="en">
<head>
<meta charset="UTF-8">
+ {% include 'includes/theme_account.html' %}
<meta name="viewport" content="width=device-width, initial-scale=1.0, interactive-widget=resizes-content">
<meta name="csrf-token" content="{{ csrf_token() }}">
<meta name="robots" content="noindex, nofollow, noarchive, nosnippet, noimageindex">
@@ -1489,6 +1490,7 @@
document.documentElement.classList.remove('dark');
localStorage.setItem('darkMode', 'false');
}
+ if (window.speakrSaveTheme) window.speakrSaveTheme('darkMode');
};
const initializeDarkMode = () => {
diff --git a/templates/includes/theme_account.html b/templates/includes/theme_account.html
new file mode 100644
index 00000000..a48a9976
--- /dev/null
+++ b/templates/includes/theme_account.html
@@ -0,0 +1,32 @@
+{#- The theme saved with the user's account (D#419). Include first in <head>,
+ before includes/theme_bootstrap.html and any script that reads the theme.
+ A saved value replaces this browser's copy in localStorage, which every
+ page reads. Nothing is saved until the user changes the mode or scheme
+ (window.speakrSaveTheme), so until then each browser keeps its own. -#}
+{% if account_theme %}
+<script>
+ (function () {
+ var saved = {{ account_theme|tojson }};
+ try {
+ if (saved.dark !== null) localStorage.setItem('darkMode', saved.dark ? 'true' : 'false');
+ if (saved.scheme) localStorage.setItem('colorScheme', saved.scheme);
+ } catch (e) {}
+ var pending = {}, timer = null;
+ window.speakrSaveTheme = function (key) {
+ try {
+ if (key === 'darkMode') pending.dark_mode = localStorage.getItem('darkMode') === 'true';
+ if (key === 'colorScheme') pending.color_scheme = localStorage.getItem('colorScheme') || 'blue';
+ } catch (e) { return; }
+ clearTimeout(timer);
+ timer = setTimeout(function () {
+ var body = pending; pending = {};
+ fetch('/api/user/preferences', {
+ method: 'POST', credentials: 'same-origin',
+ headers: {'Content-Type': 'application/json', 'X-CSRFToken': {{ csrf_token()|tojson }}},
+ body: JSON.stringify(body)
+ }).catch(function () {});
+ }, 300);
+ };
+ })();
+</script>
+{% endif %}
diff --git a/templates/index.html b/templates/index.html
index ae307cd4..bb5ac953 100644
--- a/templates/index.html
+++ b/templates/index.html
@@ -5,6 +5,7 @@
<!-- interactive-widget=resizes-content: on Android Chrome the on-screen
keyboard resizes the layout so the UI fits the space above it. -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, interactive-widget=resizes-content">
+ {% include 'includes/theme_account.html' %}
{% include 'includes/theme_bootstrap.html' %}
<script>
// Keyboard-safe viewport. The on-screen keyboard shrinks the VISUAL
diff --git a/templates/inquire.html b/templates/inquire.html
index bd5d9919..21389be2 100644
--- a/templates/inquire.html
+++ b/templates/inquire.html
@@ -4,6 +4,7 @@
<meta charset="UTF-8">
<!-- interactive-widget=resizes-content: keyboard resizes layout (Android). -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, interactive-widget=resizes-content">
+ {% include 'includes/theme_account.html' %}
{% include 'includes/theme_bootstrap.html' %}
<script>
// Keyboard-safe viewport (see index.html for rationale): mirror the
diff --git a/templates/share.html b/templates/share.html
index 6c1c40a3..64a84540 100644
--- a/templates/share.html
+++ b/templates/share.html
@@ -2,6 +2,7 @@
<html lang="en" class="h-full">
<head>
<meta charset="UTF-8">
+ {% include 'includes/theme_account.html' %}
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="robots" content="noindex, nofollow, noarchive, nosnippet, noimageindex">
<title>Shared Recording - {{ recording.title }}</title>
@@ -804,6 +805,7 @@
}
localStorage.setItem('darkMode', newDarkMode.toString());
+ if (window.speakrSaveTheme) window.speakrSaveTheme('darkMode');
}
function showToast(message) {
diff --git a/tests/test_account_theme.py b/tests/test_account_theme.py
new file mode 100644
index 00000000..4cc9cc69
--- /dev/null
+++ b/tests/test_account_theme.py
@@ -0,0 +1,90 @@
+"""Light/dark mode and color scheme saved with the account (D#419).
+
+The theme was kept only in the browser's localStorage. It is now also saved
+with the account when the user changes it, and a saved value replaces the
+browser's copy on every page the user opens. Accounts that have not changed
+it since the upgrade have no saved value, and each browser keeps its own.
+
+SHARED-DB: the test users are removed afterwards.
+"""
+
+import json
+import os
+import re
+import secrets
+import sys
+
+import pytest
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from src.app import app, db
+from src.models import User
+
+app.config["WTF_CSRF_ENABLED"] = False
+
+
+def user():
+ with app.app_context():
+ s = secrets.token_hex(4)
+ u = User(username=f"theme_{s}", email=f"theme_{s}@local.test", password="x")
+ db.session.add(u)
+ db.session.commit()
+ uid = u.id
+ yield uid
+ with app.app_context():
+ db.session.delete(db.session.get(User, uid))
+ db.session.commit()
+
+
+def _client(uid):
+ client = app.test_client()
+ with client.session_transaction() as sess:
+ sess["_user_id"] = str(uid)
+ return client
+
+
+def _saved_theme(html):
+ m = re.search(r"var saved = (\{.*?\});", html)
+ return json.loads(m.group(1)) if m else None
+
+
+def test_nothing_is_saved_until_the_user_changes_the_theme(user):
+ page = _client(user).get("/").get_data(as_text=True)
+ assert _saved_theme(page) == {"dark": None, "scheme": None}
+ assert "window.speakrSaveTheme" in page
+
+
+def test_a_saved_theme_is_written_to_every_page(user):
+ client = _client(user)
+ resp = client.post("/api/user/preferences", json={"dark_mode": True, "color_scheme": "teal"})
+ assert resp.status_code == 200
+ for path in ("/", "/account"):
+ page = client.get(path).get_data(as_text=True)
+ assert _saved_theme(page) == {"dark": True, "scheme": "teal"}, path
+ # The account value is applied before the page reads localStorage.
+ page = client.get("/").get_data(as_text=True)
+ assert page.index("var saved =") < page.index("localStorage.getItem('darkMode')")
+
+
+def test_one_setting_can_be_saved_alone(user):
+ client = _client(user)
+ assert client.post("/api/user/preferences", json={"color_scheme": "rose"}).status_code == 200
+ with app.app_context():
+ u = db.session.get(User, user)
+ assert (u.theme_dark_mode, u.theme_color_scheme) == (None, "rose")
+
+
[email protected]("body", [{"dark_mode": "yes"}, {"color_scheme": "red"}, {"color_scheme": "<x>"}])
+def test_invalid_values_are_refused(user, body):
+ client = _client(user)
+ assert client.post("/api/user/preferences", json=body).status_code == 400
+ with app.app_context():
+ u = db.session.get(User, user)
+ assert (u.theme_dark_mode, u.theme_color_scheme) == (None, None)
+
+
+def test_signed_out_pages_have_no_account_theme():
+ page = app.test_client().get("/login").get_data(as_text=True)
+ assert "speakrSaveTheme" not in page
diff --git a/tests/test_page_assets.py b/tests/test_page_assets.py
index 8ffd3f8b..4011e23c 100644
--- a/tests/test_page_assets.py
+++ b/tests/test_page_assets.py
@@ -193,8 +193,9 @@ def test_scripts_follow_the_stylesheets(page):
"""
head = _read(page).split("</head>")[0]
last_css = max(m.start() for m in re.finditer(r'rel="stylesheet"', head))
+ # The theme includes are inline scripts and must come first (D#419).
early = [m.group(0) for m in re.finditer(r"<script src=[^>]*>|\{% include '[^']*' %\}", head)
- if m.start() < last_css and "theme_bootstrap" not in m.group(0)]
+ if m.start() < last_css and not any(t in m.group(0) for t in ("theme_bootstrap", "theme_account"))]
assert not early, f"{page}: before the last stylesheet: {early}"