Skip to content

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

Python

Remove the page-load flicker: build-time Tailwind CSS, embedded translations, view transitions

Murtaza Nasir7304fc3660ea
diff --git a/.dockerignore b/.dockerignore
index 1a676efb..bef95b32 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -39,6 +39,8 @@ exports/
auto-process/
# Non-runtime directories
+.cache/
+node_modules/
temp/
docs/
site/
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index f975d745..cf19c164 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -49,6 +49,9 @@ jobs:
- name: Install dependencies
run: pip install -r requirements.txt pytest pytest-cov
+ - name: Build the Tailwind stylesheet as the image build does
+ run: scripts/build_css.sh
+
- name: Run test suite
env:
# The app tests run against an isolated SQLite DB (see conftest.py).
@@ -123,7 +126,8 @@ jobs:
# JavaScript errors, leftover template text, or a header whose user menu
# does not open (tests/e2e/test_browser_smoke.py). Vendor files are
# downloaded exactly as the Dockerfile does it, in production mode, so a
- # reference to a file the image lacks fails here.
+ # reference to a file the image lacks fails here. The Tailwind stylesheet
+ # is compiled with the same pinned CLI as the Dockerfile css-stage.
runs-on: ubuntu-latest
steps:
@@ -142,6 +146,9 @@ jobs:
- name: Download vendor files as the image build does
run: PRODUCTION=1 python scripts/download_offline_deps.py
+ - name: Build the Tailwind stylesheet as the image build does
+ run: scripts/build_css.sh
+
- name: Install Chromium
run: python -m playwright install --with-deps chromium
diff --git a/.gitignore b/.gitignore
index 5a1bb322..89e4f401 100644
--- a/.gitignore
+++ b/.gitignore
@@ -59,3 +59,6 @@ temp/ux-redesign-*.md
# Internal-only documentation (design system, working notes, etc.).
# Lives on disk for local reference but is never tracked.
+
+# Tailwind CSS: generated by scripts/build_css.sh or the Dockerfile css-stage
+static/css/tailwind.css
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 2a1a9194..673de746 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -254,9 +254,13 @@ docker-compose -f docker-compose.dev.yml up -d --build
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
pip install -r requirements.txt
+python scripts/download_offline_deps.py # vendor JavaScript, CSS and fonts
+scripts/build_css.sh # static/css/tailwind.css (Linux x64/arm64)
python src/app.py --debug
```
+The Tailwind stylesheet is compiled from the templates and scripts. After a change to the Tailwind classes in a template or script, run `scripts/build_css.sh` again, or keep `scripts/build_css.sh --watch` running. Only complete class names written out in the source are compiled; a class name assembled from parts at runtime (for example `bg-${color}-500`) is missing from the stylesheet.
+
## What Happens After You Submit a PR?
1. **CLA Reminder**: Our bot posts a reminder about the CLA terms (by submitting, you've accepted them)
diff --git a/Dockerfile b/Dockerfile
index d3849658..80912b62 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -67,7 +67,39 @@ RUN apt-get update && apt-get install -y --no-install-recommends wget xz-utils \
&& rm -rf /tmp/ff.tar.xz /tmp/ffmpeg-dir
###############################################################################
-# Stage 3: Runtime — lean final image with only what's needed
+# Stage 3: CSS - compile static/css/tailwind.css with the standalone Tailwind
+# CLI (no Node.js). Only the class names found in templates, static/js and src
+# are compiled (tailwind.config.js). The CLI release is pinned and each arch
+# binary's SHA-256 is verified; scripts/build_css.sh holds the same pin for
+# local builds, and both are updated together.
+###############################################################################
+FROM python:3.11-slim AS css-stage
+
+ARG TAILWIND_VERSION=v3.4.19
+ARG TAILWIND_SHA256_amd64=4af3198c015616ea7d6617974ec3d70d987ecc00c1ca8463b0a30fd65cc7c06e
+ARG TAILWIND_SHA256_arm64=e5b2d27694daa80cc52ec29553ba2c6bd43d86bd51a9d633ed24058b9c05a676
+
+RUN apt-get update && apt-get install -y --no-install-recommends wget \
+ && rm -rf /var/lib/apt/lists/* \
+ && case "$(dpkg --print-architecture)" in \
+ amd64) TW_ARCH=x64; SHA256="${TAILWIND_SHA256_amd64}" ;; \
+ arm64) TW_ARCH=arm64; SHA256="${TAILWIND_SHA256_arm64}" ;; \
+ *) echo "Unsupported architecture: $(dpkg --print-architecture)" >&2; exit 1 ;; \
+ esac \
+ && wget -q "https://github.com/tailwindlabs/tailwindcss/releases/download/${TAILWIND_VERSION}/tailwindcss-linux-${TW_ARCH}" -O /usr/local/bin/tailwindcss \
+ && echo "${SHA256} /usr/local/bin/tailwindcss" | sha256sum -c - \
+ && chmod +x /usr/local/bin/tailwindcss
+
+WORKDIR /build
+COPY tailwind.config.js ./
+COPY static/css/tailwind.input.css static/css/
+COPY templates templates
+COPY static/js static/js
+COPY src src
+RUN tailwindcss -c tailwind.config.js -i static/css/tailwind.input.css -o static/css/tailwind.css --minify
+
+###############################################################################
+# Stage 4: Runtime — lean final image with only what's needed
###############################################################################
FROM python:3.11-slim
@@ -86,6 +118,9 @@ COPY --from=builder /app/static/vendor /app/static/vendor
# Copy application code
COPY . .
+# Compiled Tailwind stylesheet (not in git; see the css-stage above)
+COPY --from=css-stage /build/static/css/tailwind.css /app/static/css/tailwind.css
+
# Create necessary directories
RUN mkdir -p /data/uploads /data/instance && chmod 755 /data/uploads /data/instance
diff --git a/scripts/build_css.sh b/scripts/build_css.sh
new file mode 100755
index 00000000..51358870
--- /dev/null
+++ b/scripts/build_css.sh
@@ -0,0 +1,47 @@
+#!/bin/sh
+# static/css/tailwind.css is compiled here from static/css/tailwind.input.css
+# and tailwind.config.js with the standalone Tailwind CSS CLI (no Node.js needed).
+#
+# scripts/build_css.sh # one minified build
+# scripts/build_css.sh --watch # rebuild on template or script changes
+#
+# The CLI is downloaded once into .cache/tailwindcss/ (gitignored) and its
+# SHA-256 is verified. The version and checksums are the same as in the
+# css-stage of the Dockerfile; when the pin is changed, both places are
+# updated together.
+set -eu
+
+TAILWIND_VERSION=v3.4.19
+TAILWIND_SHA256_x64=4af3198c015616ea7d6617974ec3d70d987ecc00c1ca8463b0a30fd65cc7c06e
+TAILWIND_SHA256_arm64=e5b2d27694daa80cc52ec29553ba2c6bd43d86bd51a9d633ed24058b9c05a676
+
+ROOT=$(cd "$(dirname "$0")/.." && pwd)
+cd "$ROOT"
+
+case "$(uname -s)-$(uname -m)" in
+ Linux-x86_64) ASSET=tailwindcss-linux-x64; SHA256=$TAILWIND_SHA256_x64 ;;
+ Linux-aarch64|Linux-arm64) ASSET=tailwindcss-linux-arm64; SHA256=$TAILWIND_SHA256_arm64 ;;
+ *) echo "build_css.sh: unsupported platform $(uname -s)-$(uname -m); Linux x64 and arm64 are supported" >&2; exit 1 ;;
+esac
+
+CACHE="$ROOT/.cache/tailwindcss/$TAILWIND_VERSION"
+CLI="$CACHE/$ASSET"
+if [ ! -x "$CLI" ]; then
+ mkdir -p "$CACHE"
+ URL="https://github.com/tailwindlabs/tailwindcss/releases/download/$TAILWIND_VERSION/$ASSET"
+ echo "Downloading $URL"
+ if command -v curl >/dev/null 2>&1; then
+ curl -fsSL "$URL" -o "$CLI.tmp"
+ else
+ wget -q "$URL" -O "$CLI.tmp"
+ fi
+ echo "$SHA256 $CLI.tmp" | sha256sum -c - >/dev/null || {
+ echo "build_css.sh: checksum mismatch for $ASSET $TAILWIND_VERSION" >&2
+ rm -f "$CLI.tmp"
+ exit 1
+ }
+ chmod +x "$CLI.tmp"
+ mv "$CLI.tmp" "$CLI"
+fi
+
+"$CLI" -c tailwind.config.js -i static/css/tailwind.input.css -o static/css/tailwind.css --minify "$@"
diff --git a/scripts/download_offline_deps.py b/scripts/download_offline_deps.py
index f7fa8e8e..6e96210b 100644
--- a/scripts/download_offline_deps.py
+++ b/scripts/download_offline_deps.py
@@ -18,7 +18,6 @@ DEPENDENCIES = {
"swagger-ui.css": "https://cdn.jsdelivr.net/npm/[email protected]/swagger-ui.css",
},
"js": {
- "tailwind.min.js": "https://cdn.tailwindcss.com/3.4.0",
"vue.global.js": "https://cdn.jsdelivr.net/npm/vue@3/dist/vue.global.js",
"marked.min.js": "https://cdn.jsdelivr.net/npm/marked/marked.min.js",
"easymde.min.js": "https://cdn.jsdelivr.net/npm/easymde/dist/easymde.min.js",
diff --git a/src/api/inquire.py b/src/api/inquire.py
index 1b298288..c0838539 100644
--- a/src/api/inquire.py
+++ b/src/api/inquire.py
@@ -61,10 +61,14 @@ def inquire():
).first() is not None
# Render the inquire page with user context for theming
+ # The interface language, as on the other pages (it was missing here, so
+ # Inquire always appeared in the browser language).
+ user_language = current_user.ui_language or 'en'
return render_template('inquire.html',
use_asr_endpoint=USE_ASR_ENDPOINT,
current_user=current_user,
- is_team_admin=is_team_admin)
+ is_team_admin=is_team_admin,
+ user_language=user_language)
diff --git a/src/app.py b/src/app.py
index 38da12f7..5ec7d556 100644
--- a/src/app.py
+++ b/src/app.py
@@ -713,6 +713,13 @@ _app_version = get_version()
def inject_app_version():
return {'app_version': _app_version}
+from src.utils.i18n_bootstrap import i18n_bootstrap as _i18n_bootstrap
+
+def inject_i18n_bootstrap():
+ """Translations embedded in pages that load i18n.js (includes/i18n_bootstrap.html)."""
+ return {'i18n_bootstrap': _i18n_bootstrap}
+
@app.context_processor
def inject_inquire_mode_flag():
"""The shared header shows the Inquire button on every page."""
diff --git a/src/utils/i18n_bootstrap.py b/src/utils/i18n_bootstrap.py
new file mode 100644
index 00000000..adc92b77
--- /dev/null
+++ b/src/utils/i18n_bootstrap.py
@@ -0,0 +1,77 @@
+"""Translations embedded in the page for the client-side i18n (static/js/i18n.js).
+
+Pages that load i18n.js include templates/includes/i18n_bootstrap.html first.
+In that include, ``window.__I18N_BOOTSTRAP = {locale, translations}`` is set
+to the user's interface language and English, so the first render is already
+translated and no locale file has to be fetched before it.
+
+Locale files are read from static/locales/ and cached per process; a file
+is read again when its modification time changes.
+"""
+
+import json
+import logging
+import os
+import re
+import threading
+
+logger = logging.getLogger(__name__)
+
+FALLBACK_LOCALE = 'en'
+_LOCALE_RE = re.compile(r'^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})?$')
+_LOCALES_DIR = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
+ 'static', 'locales')
+
+_cache = {}
+_lock = threading.Lock()
+
+
+def _load(locale):
+ """Return the parsed locale file, or None when it is missing or invalid."""
+ if not locale or not _LOCALE_RE.match(locale):
+ return None
+ path = os.path.join(_LOCALES_DIR, f'{locale}.json')
+ try:
+ mtime = os.stat(path).st_mtime
+ except OSError:
+ return None
+ cached = _cache.get(locale)
+ if cached and cached[0] == mtime:
+ return cached[1]
+ with _lock:
+ try:
+ with open(path, encoding='utf-8') as f:
+ data = json.load(f)
+ except (OSError, ValueError) as e:
+ logger.error("Locale file %s could not be read: %s", path, e)
+ return None
+ _cache[locale] = (mtime, data)
+ return data
+
+
+def i18n_bootstrap(locale=None):
+ """Return ``{'locale': ..., 'translations': {code: dict}}`` for the page.
+
+ ``locale`` defaults to the signed-in user's interface language. English
+ is always included as the fallback; for an unknown locale, only English is returned.
+ """
+ if not locale:
+ try:
+ from flask_login import current_user
+ if current_user and current_user.is_authenticated:
+ locale = getattr(current_user, 'ui_language', None)
+ except Exception: # outside a request context
+ locale = None
+ locale = locale or FALLBACK_LOCALE
+
+ translations = {}
+ data = _load(locale)
+ if data is None:
+ locale = FALLBACK_LOCALE
+ else:
+ translations[locale] = data
+ if FALLBACK_LOCALE not in translations:
+ fallback = _load(FALLBACK_LOCALE)
+ if fallback is not None:
+ translations[FALLBACK_LOCALE] = fallback
+ return {'locale': locale, 'translations': translations}
diff --git a/static/css/styles.css b/static/css/styles.css
index 71eb1190..38ac3835 100644
--- a/static/css/styles.css
+++ b/static/css/styles.css
@@ -1,3 +1,24 @@
+/* Page-to-page navigation: a short cross-fade between same-origin pages in
+ browsers with cross-document View Transitions (Chrome and Edge 126+, Safari
+ 18.2+); elsewhere this rule has no effect. styles.css is loaded on every page,
+ and both pages of a navigation have to opt in. In-page changes (modals,
+ the loading overlay) are not affected. */
+@view-transition {
+ navigation: auto;
+}
+
+::view-transition-old(root),
+::view-transition-new(root) {
+ animation-duration: 150ms;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ ::view-transition-old(root),
+ ::view-transition-new(root) {
+ animation: none;
+ }
+}
+
body.unloaded {
opacity: 0;
transition: opacity 0.5s ease-in-out;
diff --git a/static/css/tailwind.input.css b/static/css/tailwind.input.css
new file mode 100644
index 00000000..daa8565c
--- /dev/null
+++ b/static/css/tailwind.input.css
@@ -0,0 +1,6 @@
+/* Source for static/css/tailwind.css. The output is generated by
+ scripts/build_css.sh (or the css-stage of the Dockerfile) and is not
+ committed. Configuration: tailwind.config.js. */
+@tailwind base;
+@tailwind components;
+@tailwind utilities;
diff --git a/static/js/i18n.js b/static/js/i18n.js
index 5f6a521c..876283e4 100644
--- a/static/js/i18n.js
+++ b/static/js/i18n.js
@@ -34,11 +34,47 @@ class I18n {
await this.loadLocale(this.fallbackLocale);
}
- if (!this.isReady) {
- this.isReady = true;
- this._resolveReady();
- window.dispatchEvent(new CustomEvent('i18nReady', { detail: { locale: this.currentLocale } }));
+ this._markReady();
+ }
+
+ _markReady() {
+ if (this.isReady) return;
+ this.isReady = true;
+ this._resolveReady();
+ window.dispatchEvent(new CustomEvent('i18nReady', { detail: { locale: this.currentLocale } }));
+ }
+
+ /**
+ * Use translations embedded in the page (window.__I18N_BOOTSTRAP, from
+ * templates/includes/i18n_bootstrap.html), so the first render is already
+ * translated and no locale file is fetched for it. The locale is chosen as
+ * in init(). When the chosen locale is not among the embedded ones, ready
+ * stays pending and the locale is fetched by init() as before.
+ * @param {{locale: string, translations: Object<string, Object>}} data
+ * @returns {boolean} true when the translations are ready
+ */
+ applyBootstrap(data) {
+ if (!data || typeof data !== 'object' || !data.translations || typeof data.translations !== 'object') {
+ return false;
}
+ for (const [code, table] of Object.entries(data.translations)) {
+ if (table && typeof table === 'object') {
+ this.translations[code] = table;
+ this.loadedLocales.add(code);
+ }
+ }
+ let savedLocale = null;
+ try {
+ savedLocale = localStorage.getItem('preferredLanguage');
+ } catch (e) {
+ savedLocale = null;
+ }
+ this.currentLocale = savedLocale || data.locale || this.fallbackLocale;
+ if (!this.loadedLocales.has(this.currentLocale) || !this.loadedLocales.has(this.fallbackLocale)) {
+ return false;
+ }
+ this._markReady();
+ return true;
}
/**
@@ -319,6 +355,11 @@ const i18n = new I18n();
if (typeof window !== 'undefined') {
// Ensure window.i18n exists with at least a basic t function
window.i18n = i18n;
+
+ // Translations embedded in the page are used at once (see applyBootstrap).
+ if (window.__I18N_BOOTSTRAP) {
+ i18n.applyBootstrap(window.__I18N_BOOTSTRAP);
+ }
// Add a fallback t function if the class method isn't ready
if (!window.i18n.t) {
diff --git a/static/js/i18n.test.js b/static/js/i18n.test.js
new file mode 100644
index 00000000..48172037
--- /dev/null
+++ b/static/js/i18n.test.js
@@ -0,0 +1,110 @@
+import { describe, it, expect, vi } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import vm from 'node:vm';
+
+// i18n.js is a classic script that sets window.i18n, so it is run here in a
+// fresh context per test with a minimal window, localStorage and fetch.
+const SOURCE = readFileSync(fileURLToPath(new URL('./i18n.js', import.meta.url)), 'utf8');
+
+const EN = { nav: { account: 'Account', admin: 'Admin' }, only: { english: 'English only' } };
+const DE = { nav: { account: 'Konto' } };
+const FR = { nav: { account: 'Compte' } };
+
+function load({ bootstrap, saved = null, files = { en: EN, de: DE, fr: FR } } = {}) {
+ const events = [];
+ const store = new Map(saved ? [['preferredLanguage', saved]] : []);
+ const fetch = vi.fn(async (url) => {
+ const code = url.match(/locales\/(.+)\.json$/)[1];
+ return files[code]
+ ? { ok: true, json: async () => files[code] }
+ : { ok: false, json: async () => ({}) };
+ });
+ const window = {
+ dispatchEvent: (e) => events.push({ type: e.type, detail: e.detail }),
+ };
+ if (bootstrap !== undefined) window.__I18N_BOOTSTRAP = bootstrap;
+ const context = vm.createContext({
+ window,
+ fetch,
+ CustomEvent,
+ console: { log() {}, warn() {}, error() {} },
+ navigator: { language: 'en-US' },
+ localStorage: {
+ getItem: (k) => (store.has(k) ? store.get(k) : null),
+ setItem: (k, v) => store.set(k, String(v)),
+ },
+ });
+ vm.runInContext(SOURCE, context);
+ return { i18n: window.i18n, fetch, events, store };
+}
+
+describe('i18n bootstrap', () => {
+ it('is ready synchronously with the embedded locale and no fetch', async () => {
+ const { i18n, fetch, events } = load({ bootstrap: { locale: 'de', translations: { de: DE, en: EN } } });
+ expect(i18n.isReady).toBe(true);
+ expect(i18n.getLocale()).toBe('de');
+ expect(i18n.t('nav.account')).toBe('Konto');
+ expect(i18n.t('only.english')).toBe('English only'); // English fallback
+ expect(events.map(e => e.type)).toEqual(['i18nReady']);
+ await expect(i18n.ready).resolves.toBeUndefined();
+ await i18n.init('de'); // the pages still call init(); nothing is fetched
+ expect(fetch).not.toHaveBeenCalled();
+ expect(events).toHaveLength(1);
+ });
+
+ it('keeps the saved language first, as init() does, and fetches it when not embedded', async () => {
+ const { i18n, fetch, events } = load({
+ bootstrap: { locale: 'de', translations: { de: DE, en: EN } },
+ saved: 'fr',
+ });
+ expect(i18n.isReady).toBe(false);
+ expect(i18n.t('nav.account')).toBe('Account'); // English until French arrives
+ await i18n.init('de');
+ expect(fetch).toHaveBeenCalledTimes(1);
+ expect(fetch.mock.calls[0][0]).toBe('/static/locales/fr.json');
+ expect(i18n.isReady).toBe(true);
+ expect(i18n.t('nav.account')).toBe('Compte');
+ expect(events.map(e => e.type)).toEqual(['i18nReady']);
+ });
+
+ it('uses a saved language that is embedded', () => {
+ const { i18n } = load({ bootstrap: { locale: 'en', translations: { de: DE, en: EN } }, saved: 'de' });
+ expect(i18n.isReady).toBe(true);
+ expect(i18n.t('nav.account')).toBe('Konto');
+ });
+
+ it('works as before without a bootstrap', async () => {
+ const { i18n, fetch, events } = load();
+ expect(i18n.isReady).toBe(false);
+ await i18n.init('de');
+ expect(fetch.mock.calls.map(c => c[0])).toEqual(['/static/locales/de.json', '/static/locales/en.json']);
+ expect(i18n.t('nav.account')).toBe('Konto');
+ expect(events.map(e => e.type)).toEqual(['i18nReady']);
+ });
+
+ it('ignores a malformed bootstrap', async () => {
+ for (const bootstrap of [null, 'x', { locale: 'de' }, { locale: 'de', translations: 'x' }]) {
+ const { i18n } = load({ bootstrap });
+ expect(i18n.isReady).toBe(false);
+ await i18n.init('en');
+ expect(i18n.t('nav.account')).toBe('Account');
+ }
+ });
+
+ it('waits for English when only the locale is embedded', async () => {
+ const { i18n, fetch } = load({ bootstrap: { locale: 'de', translations: { de: DE } } });
+ expect(i18n.isReady).toBe(false);
+ await i18n.init('de');
+ expect(fetch.mock.calls.map(c => c[0])).toEqual(['/static/locales/en.json']);
+ expect(i18n.isReady).toBe(true);
+ });
+
+ it('changes language with setLocale as before', async () => {
+ const { i18n, events, store } = load({ bootstrap: { locale: 'en', translations: { en: EN } } });
+ await i18n.setLocale('fr');
+ expect(i18n.t('nav.account')).toBe('Compte');
+ expect(store.get('preferredLanguage')).toBe('fr');
+ expect(events.map(e => e.type)).toEqual(['i18nReady', 'localeChanged']);
+ });
+});
diff --git a/static/js/modules/utils/errorDisplay.js b/static/js/modules/utils/errorDisplay.js
index 2c0df054..a5a9ae17 100644
--- a/static/js/modules/utils/errorDisplay.js
+++ b/static/js/modules/utils/errorDisplay.js
@@ -231,16 +231,32 @@ export function generateErrorHTML(error, showTechnical = false) {
unknown: 'gray'
};
+ // Full literal class names per color. The Tailwind stylesheet is compiled at
+ // build time from complete class strings in the source files; names assembled
+ // from a color variable are absent from it.
+ const colorClasses = {
+ amber: { box: 'bg-amber-500/10 border-amber-500/30', badge: 'bg-amber-500/20', icon: 'text-amber-500', title: 'text-amber-600 dark:text-amber-400' },
+ orange: { box: 'bg-orange-500/10 border-orange-500/30', badge: 'bg-orange-500/20', icon: 'text-orange-500', title: 'text-orange-600 dark:text-orange-400' },
+ red: { box: 'bg-red-500/10 border-red-500/30', badge: 'bg-red-500/20', icon: 'text-red-500', title: 'text-red-600 dark:text-red-400' },
+ yellow: { box: 'bg-yellow-500/10 border-yellow-500/30', badge: 'bg-yellow-500/20', icon: 'text-yellow-500', title: 'text-yellow-600 dark:text-yellow-400' },
+ blue: { box: 'bg-blue-500/10 border-blue-500/30', badge: 'bg-blue-500/20', icon: 'text-blue-500', title: 'text-blue-600 dark:text-blue-400' },
+ purple: { box: 'bg-purple-500/10 border-purple-500/30', badge: 'bg-purple-500/20', icon: 'text-purple-500', title: 'text-purple-600 dark:text-purple-400' },
+ pink: { box: 'bg-pink-500/10 border-pink-500/30', badge: 'bg-pink-500/20', icon: 'text-pink-500', title: 'text-pink-600 dark:text-pink-400' },
+ indigo: { box: 'bg-indigo-500/10 border-indigo-500/30', badge: 'bg-indigo-500/20', icon: 'text-indigo-500', title: 'text-indigo-600 dark:text-indigo-400' },
+ gray: { box: 'bg-gray-500/10 border-gray-500/30', badge: 'bg-gray-500/20', icon: 'text-gray-500', title: 'text-gray-600 dark:text-gray-400' }
+ };
+
const color = typeColors[error.type] || 'gray';
+ const cls = colorClasses[color] || colorClasses.gray;
let html = `
- <div class="error-display bg-${color}-500/10 border border-${color}-500/30 rounded-lg p-4">
+ <div class="error-display border ${cls.box} rounded-lg p-4">
<div class="flex items-start gap-3">
- <div class="flex-shrink-0 w-10 h-10 rounded-full bg-${color}-500/20 flex items-center justify-center">
- <i class="fas ${error.icon} text-${color}-500"></i>
+ <div class="flex-shrink-0 w-10 h-10 rounded-full ${cls.badge} flex items-center justify-center">
+ <i class="fas ${error.icon} ${cls.icon}"></i>
</div>
<div class="flex-1 min-w-0">
- <h3 class="text-lg font-semibold text-${color}-600 dark:text-${color}-400 mb-1">
+ <h3 class="text-lg font-semibold ${cls.title} mb-1">
${escapeHtml(error.title)}
</h3>
<p class="text-[var(--text-primary)] mb-2">
diff --git a/static/sw.js b/static/sw.js
index f63025f8..64f3f364 100644
--- a/static/sw.js
+++ b/static/sw.js
@@ -9,6 +9,7 @@ const ASSETS_TO_CACHE = [
'/static/offline.html',
'/static/manifest.json',
'/static/css/styles.css',
+ '/static/css/tailwind.css',
'/static/js/app.modular.js',
'/static/js/i18n.js',
'/static/js/csrf-refresh.js',
@@ -16,7 +17,6 @@ const ASSETS_TO_CACHE = [
'/static/img/icon-512x512.png',
'/static/img/favicon.ico',
// Local vendor assets (no external CDN dependencies)
- '/static/vendor/js/tailwind.min.js',
'/static/vendor/js/vue.global.js',
'/static/vendor/js/marked.min.js',
'/static/vendor/js/easymde.min.js',
diff --git a/tailwind.config.js b/tailwind.config.js
new file mode 100644
index 00000000..fbcfa467
--- /dev/null
+++ b/tailwind.config.js
@@ -0,0 +1,34 @@
+// Tailwind CSS configuration for the stylesheet compiled at build time
+// (scripts/build_css.sh locally, the css-stage of the Dockerfile for images).
+// The output, static/css/tailwind.css, is linked from every page template.
+//
+// Only complete class names that appear literally in the files below are
+// compiled. A class name assembled at runtime from parts (for example
+// `bg-${color}-500`) is absent from the output; each full class name has to
+// be written out instead (see static/js/modules/utils/errorDisplay.js).
+
+/** @type {import('tailwindcss').Config} */
+export default {
+ content: [
+ './templates/**/*.html',
+ './static/js/**/*.js',
+ './src/**/*.py',
+ ],
+ // The theme is applied with the "dark" class on <html> (applyTheme in the
+ // templates, global-header.js), not with the system preference.
+ darkMode: 'class',
+ theme: {
+ extend: {
+ maxHeight: {
+ '85vh': '85vh',
+ '90vh': '90vh',
+ },
+ colors: {
+ primary: 'var(--bg-primary)',
+ secondary: 'var(--bg-secondary)',
+ accent: 'var(--bg-accent)',
+ },
+ },
+ },
+ plugins: [],
+};
diff --git a/templates/account.html b/templates/account.html
index d6d81acb..8d43ef53 100644
--- a/templates/account.html
+++ b/templates/account.html
@@ -8,11 +8,11 @@
<title>{{ title }} - Speakr</title>
<link rel="icon" href="{{ url_for('static', filename='img/favicon.ico') }}" type="image/svg+xml">
<!-- All dependencies bundled locally for offline support -->
-<script src="{{ url_for('static', filename='vendor/js/tailwind.min.js') }}"></script>
<!-- All dependencies bundled locally for offline support -->
<link rel="stylesheet" href="{{ url_for('static', filename='vendor/css/fontawesome.min.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='css/primitives.css') }}">
+ {% include 'includes/i18n_bootstrap.html' %}
<script src="{{ url_for('static', filename='js/i18n.js') }}"></script>
<script src="{{ url_for('static', filename='js/asr-languages.js') }}"></script>
<script src="{{ url_for('static', filename='js/organizer-modals.js') }}"></script>
@@ -461,6 +461,10 @@
display: none;
}
</style>
+ <!-- Tailwind utilities, compiled at build time (scripts/build_css.sh). Last in
+ <head> so that, as with the former runtime build, they follow the page's
+ own stylesheets in the cascade. -->
+ <link rel="stylesheet" href="{{ url_for('static', filename='css/tailwind.css') }}">
</head>
<body class="bg-[var(--bg-primary)] text-[var(--text-primary)] h-full flex flex-col overflow-hidden">
{% set page_label = 'Account' %}
diff --git a/templates/admin.html b/templates/admin.html
index d5a2ad44..9fa9e932 100644
--- a/templates/admin.html
+++ b/templates/admin.html
@@ -12,7 +12,6 @@
<link rel="icon" href="{{ url_for('static', filename='img/favicon.ico') }}" type="image/svg+xml">
<!-- All dependencies bundled locally for offline support -->
-<script src="{{ url_for('static', filename='vendor/js/tailwind.min.js') }}"></script>
<!-- All dependencies bundled locally for offline support -->
<script src="{{ url_for('static', filename='vendor/js/vue.global.js') }}"></script>
<script src="{{ url_for('static', filename='vendor/js/chart.umd.min.js') }}"></script>
@@ -20,6 +19,7 @@
<link rel="stylesheet" href="{{ url_for('static', filename='vendor/css/fontawesome.min.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='css/primitives.css') }}">
+ {% include 'includes/i18n_bootstrap.html' %}
<script src="{{ url_for('static', filename='js/i18n.js') }}"></script>
<style>
/* Hide Vue content until compiled */
@@ -135,6 +135,10 @@
})();
});
</script>
+ <!-- Tailwind utilities, compiled at build time (scripts/build_css.sh). Last in
+ <head> so that, as with the former runtime build, they follow the page's
+ own stylesheets in the cascade. -->
+ <link rel="stylesheet" href="{{ url_for('static', filename='css/tailwind.css') }}">
</head>
<body class="bg-[var(--bg-primary)] text-[var(--text-primary)] h-full flex flex-col overflow-hidden">
{% set page_label = ('Team Management' if is_team_admin and not current_user.is_admin else 'Admin') %}
diff --git a/templates/auth/check_email.html b/templates/auth/check_email.html
index a836b198..46cca90f 100644
--- a/templates/auth/check_email.html
+++ b/templates/auth/check_email.html
@@ -6,7 +6,6 @@
<meta name="robots" content="noindex, nofollow, noarchive, nosnippet, noimageindex">
<title>{{ title }} - Speakr</title>
<link rel="icon" href="{{ url_for('static', filename='img/favicon.ico') }}" type="image/svg+xml">
- <script src="{{ url_for('static', filename='vendor/js/tailwind.min.js') }}"></script>
<link rel="stylesheet" href="{{ url_for('static', filename='vendor/css/fontawesome.min.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">
@@ -36,6 +35,10 @@
}
applyTheme();
</script>
+ <!-- Tailwind utilities, compiled at build time (scripts/build_css.sh). Last in
+ <head> so that, as with the former runtime build, they follow the page's
+ own stylesheets in the cascade. -->
+ <link rel="stylesheet" href="{{ url_for('static', filename='css/tailwind.css') }}">
</head>
<body class="bg-[var(--bg-primary)] text-[var(--text-primary)]">
<div class="container mx-auto px-4 sm:px-6 lg:px-8 py-6 flex flex-col min-h-screen">
diff --git a/templates/auth/forgot_password.html b/templates/auth/forgot_password.html
index 9af13a1b..49c5987b 100644
--- a/templates/auth/forgot_password.html
+++ b/templates/auth/forgot_password.html
@@ -6,7 +6,6 @@
<meta name="robots" content="noindex, nofollow, noarchive, nosnippet, noimageindex">
<title>{{ title }} - Speakr</title>
<link rel="icon" href="{{ url_for('static', filename='img/favicon.ico') }}" type="image/svg+xml">
- <script src="{{ url_for('static', filename='vendor/js/tailwind.min.js') }}"></script>
<link rel="stylesheet" href="{{ url_for('static', filename='vendor/css/fontawesome.min.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">
@@ -36,6 +35,10 @@
}
applyTheme();
</script>
+ <!-- Tailwind utilities, compiled at build time (scripts/build_css.sh). Last in
+ <head> so that, as with the former runtime build, they follow the page's
+ own stylesheets in the cascade. -->
+ <link rel="stylesheet" href="{{ url_for('static', filename='css/tailwind.css') }}">
</head>
<body class="bg-[var(--bg-primary)] text-[var(--text-primary)]">
<div class="container mx-auto px-4 sm:px-6 lg:px-8 py-6 flex flex-col min-h-screen">
diff --git a/templates/auth/reset_password.html b/templates/auth/reset_password.html
index 25e31787..be69086d 100644
--- a/templates/auth/reset_password.html
+++ b/templates/auth/reset_password.html
@@ -6,7 +6,6 @@
<meta name="robots" content="noindex, nofollow, noarchive, nosnippet, noimageindex">
<title>{{ title }} - Speakr</title>
<link rel="icon" href="{{ url_for('static', filename='img/favicon.ico') }}" type="image/svg+xml">
- <script src="{{ url_for('static', filename='vendor/js/tailwind.min.js') }}"></script>
<link rel="stylesheet" href="{{ url_for('static', filename='vendor/css/fontawesome.min.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">
@@ -36,6 +35,10 @@
}
applyTheme();
</script>
+ <!-- Tailwind utilities, compiled at build time (scripts/build_css.sh). Last in
+ <head> so that, as with the former runtime build, they follow the page's
+ own stylesheets in the cascade. -->
+ <link rel="stylesheet" href="{{ url_for('static', filename='css/tailwind.css') }}">
</head>
<body class="bg-[var(--bg-primary)] text-[var(--text-primary)]">
<div class="container mx-auto px-4 sm:px-6 lg:px-8 py-6 flex flex-col min-h-screen">
diff --git a/templates/auth/verify_success.html b/templates/auth/verify_success.html
index 96718f7b..f77ae651 100644
--- a/templates/auth/verify_success.html
+++ b/templates/auth/verify_success.html
@@ -6,7 +6,6 @@
<meta name="robots" content="noindex, nofollow, noarchive, nosnippet, noimageindex">
<title>{{ title }} - Speakr</title>
<link rel="icon" href="{{ url_for('static', filename='img/favicon.ico') }}" type="image/svg+xml">
- <script src="{{ url_for('static', filename='vendor/js/tailwind.min.js') }}"></script>
<link rel="stylesheet" href="{{ url_for('static', filename='vendor/css/fontawesome.min.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">
@@ -36,6 +35,10 @@
}
applyTheme();
</script>
+ <!-- Tailwind utilities, compiled at build time (scripts/build_css.sh). Last in
+ <head> so that, as with the former runtime build, they follow the page's
+ own stylesheets in the cascade. -->
+ <link rel="stylesheet" href="{{ url_for('static', filename='css/tailwind.css') }}">
</head>
<body class="bg-[var(--bg-primary)] text-[var(--text-primary)]">
<div class="container mx-auto px-4 sm:px-6 lg:px-8 py-6 flex flex-col min-h-screen">
diff --git a/templates/group-admin.html b/templates/group-admin.html
index f768e4ca..d4f81758 100644
--- a/templates/group-admin.html
+++ b/templates/group-admin.html
@@ -12,12 +12,12 @@
<link rel="icon" href="{{ url_for('static', filename='img/favicon.ico') }}" type="image/svg+xml">
<!-- All dependencies bundled locally for offline support -->
-<script src="{{ url_for('static', filename='vendor/js/tailwind.min.js') }}"></script>
<!-- All dependencies bundled locally for offline support -->
<script src="{{ url_for('static', filename='vendor/js/vue.global.js') }}"></script>
<!-- All dependencies bundled locally for offline support -->
<link rel="stylesheet" href="{{ url_for('static', filename='vendor/css/fontawesome.min.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">
+ {% include 'includes/i18n_bootstrap.html' %}
<script src="{{ url_for('static', filename='js/i18n.js') }}"></script>
<style>
/* Hide Vue content until compiled */
@@ -111,6 +111,10 @@
}
applyTheme();
</script>
+ <!-- Tailwind utilities, compiled at build time (scripts/build_css.sh). Last in
+ <head> so that, as with the former runtime build, they follow the page's
+ own stylesheets in the cascade. -->
+ <link rel="stylesheet" href="{{ url_for('static', filename='css/tailwind.css') }}">
</head>
<body class="bg-[var(--bg-primary)] text-[var(--text-primary)]">
{% set page_label = 'Group Management' %}
diff --git a/templates/includes/i18n_bootstrap.html b/templates/includes/i18n_bootstrap.html
new file mode 100644
index 00000000..82d4faec
--- /dev/null
+++ b/templates/includes/i18n_bootstrap.html
@@ -0,0 +1,3 @@
+{# Translations for static/js/i18n.js, embedded so the first render is already
+ translated (src/utils/i18n_bootstrap.py). Include before i18n.js. #}
+<script>window.__I18N_BOOTSTRAP = {{ i18n_bootstrap(user_language|default(none))|tojson }};</script>
diff --git a/templates/index.html b/templates/index.html
index 92d56d2e..4991b10d 100644
--- a/templates/index.html
+++ b/templates/index.html
@@ -61,7 +61,6 @@
<title>Speakr - Audio Transcription & Summarization</title>
{% include 'includes/loading_overlay.html' %}
<!-- All dependencies bundled locally for offline support -->
- <script src="{{ url_for('static', filename='vendor/js/tailwind.min.js') }}"></script>
<script src="{{ url_for('static', filename='vendor/js/vue.global.js') }}"></script>
<script src="{{ url_for('static', filename='vendor/js/marked.min.js') }}"></script>
<script src="{{ url_for('static', filename='vendor/js/purify.min.js') }}"></script>
@@ -77,24 +76,10 @@
<link rel="apple-touch-icon" sizes="180x180" href="{{ url_for('static', filename='img/icon-180x180.png') }}">
<link rel="manifest" href="{{ url_for('static', filename='manifest.json') }}">
<meta name="theme-color" content="#2563eb">
- <script>
- tailwind.config = {
- darkMode: 'class',
- theme: {
- extend: {
- maxHeight: {
- '85vh': '85vh',
- '90vh': '90vh'
- },
- colors: {
- primary: 'var(--bg-primary)',
- secondary: 'var(--bg-secondary)',
- accent: 'var(--bg-accent)'
- }
- }
- }
- }
- </script>
+ <!-- Tailwind utilities, compiled at build time (scripts/build_css.sh). Last in
+ <head> so that, as with the former runtime build, they follow the page's
+ own stylesheets in the cascade. -->
+ <link rel="stylesheet" href="{{ url_for('static', filename='css/tailwind.css') }}">
</head>
<body class="h-full bg-[var(--bg-primary)] text-[var(--text-primary)] transition-colors duration-300">
<div id="loader" class="fixed inset-0 bg-gray-800 flex items-center justify-center z-50">
@@ -192,6 +177,7 @@
<script src="{{ url_for('static', filename='js/csrf-refresh.js') }}"></script>
<!-- i18n System -->
+ {% include 'includes/i18n_bootstrap.html' %}
<script src="{{ url_for('static', filename='js/i18n.js') }}"></script>
<!-- Initialize i18n immediately with fallback -->
diff --git a/templates/inquire.html b/templates/inquire.html
index 476e14db..aa571910 100644
--- a/templates/inquire.html
+++ b/templates/inquire.html
@@ -20,7 +20,6 @@
<meta name="robots" content="noindex, nofollow, noarchive, nosnippet, noimageindex">
<title>Inquire Mode - Speakr</title>
<!-- All dependencies bundled locally for offline support -->
-<script src="{{ url_for('static', filename='vendor/js/tailwind.min.js') }}"></script>
<!-- All dependencies bundled locally for offline support -->
<script src="{{ url_for('static', filename='vendor/js/vue.global.js') }}"></script>
<!-- All dependencies bundled locally for offline support -->
@@ -31,6 +30,7 @@
<link rel="stylesheet" href="{{ url_for('static', filename='vendor/css/fontawesome.min.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='css/primitives.css') }}">
+ {% include 'includes/i18n_bootstrap.html' %}
<script src="{{ url_for('static', filename='js/i18n.js') }}"></script>
<link rel="icon" href="{{ url_for('static', filename='img/favicon.ico') }}">
<link rel="icon" type="image/png" sizes="32x32" href="{{ url_for('static', filename='img/icon-32x32.png') }}">
@@ -38,20 +38,6 @@
<!-- Loading overlay to prevent FOUC -->
{% include 'includes/loading_overlay.html' %}
- <script>
- tailwind.config = {
- darkMode: 'class',
- theme: {
- extend: {
- colors: {
- primary: 'var(--bg-primary)',
- secondary: 'var(--bg-secondary)',
- accent: 'var(--bg-accent)'
- }
- }
- }
- }
- </script>
<style>
/* Custom checkbox styling for better visual feedback */
.filter-checkbox {
@@ -213,6 +199,10 @@
text-decoration: underline;
}
</style>
+ <!-- Tailwind utilities, compiled at build time (scripts/build_css.sh). Last in
+ <head> so that, as with the former runtime build, they follow the page's
+ own stylesheets in the cascade. -->
+ <link rel="stylesheet" href="{{ url_for('static', filename='css/tailwind.css') }}">
</head>
<body class="h-full bg-[var(--bg-primary)] text-[var(--text-primary)] transition-colors duration-300">
<div id="inquire-app" v-cloak class="h-full flex flex-col"
diff --git a/templates/login.html b/templates/login.html
index 2b6d379e..857d981d 100644
--- a/templates/login.html
+++ b/templates/login.html
@@ -7,7 +7,6 @@
<title>{{ title }} - Speakr</title>
<link rel="icon" href="{{ url_for('static', filename='img/favicon.ico') }}" type="image/svg+xml">
<!-- All dependencies bundled locally for offline support -->
-<script src="{{ url_for('static', filename='vendor/js/tailwind.min.js') }}"></script>
<!-- All dependencies bundled locally for offline support -->
<link rel="stylesheet" href="{{ url_for('static', filename='vendor/css/fontawesome.min.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">
@@ -49,6 +48,10 @@
}
applyTheme();
</script>
+ <!-- Tailwind utilities, compiled at build time (scripts/build_css.sh). Last in
+ <head> so that, as with the former runtime build, they follow the page's
+ own stylesheets in the cascade. -->
+ <link rel="stylesheet" href="{{ url_for('static', filename='css/tailwind.css') }}">
</head>
<body class="bg-[var(--bg-primary)] text-[var(--text-primary)]">
<div class="container mx-auto px-4 sm:px-6 lg:px-8 py-6 flex flex-col min-h-screen">
diff --git a/templates/register.html b/templates/register.html
index 99a4addd..09a1922f 100644
--- a/templates/register.html
+++ b/templates/register.html
@@ -7,7 +7,6 @@
<title>{{ title }} - Speakr</title>
<link rel="icon" href="{{ url_for('static', filename='img/favicon.ico') }}" type="image/svg+xml">
<!-- All dependencies bundled locally for offline support -->
-<script src="{{ url_for('static', filename='vendor/js/tailwind.min.js') }}"></script>
<!-- All dependencies bundled locally for offline support -->
<link rel="stylesheet" href="{{ url_for('static', filename='vendor/css/fontawesome.min.css') }}">
<link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">
@@ -49,6 +48,10 @@
}
applyTheme();
</script>
+ <!-- Tailwind utilities, compiled at build time (scripts/build_css.sh). Last in
+ <head> so that, as with the former runtime build, they follow the page's
+ own stylesheets in the cascade. -->
+ <link rel="stylesheet" href="{{ url_for('static', filename='css/tailwind.css') }}">
</head>
<body class="bg-[var(--bg-primary)] text-[var(--text-primary)]">
<div class="container mx-auto px-4 sm:px-6 lg:px-8 py-6 flex flex-col min-h-screen">
diff --git a/templates/share.html b/templates/share.html
index 357649a4..0bcb8105 100644
--- a/templates/share.html
+++ b/templates/share.html
@@ -5,8 +5,6 @@
<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>
- <!-- All dependencies bundled locally for offline support -->
-<script src="{{ url_for('static', filename='vendor/js/tailwind.min.js') }}"></script>
<link rel="stylesheet" href="{{ url_for('static', filename='css/styles.css') }}">
<!-- All dependencies bundled locally for offline support -->
<script src="{{ url_for('static', filename='vendor/js/vue.global.js') }}"></script>
@@ -19,23 +17,6 @@
{% include 'includes/loading_overlay.html' %}
<script>
- tailwind.config = {
- darkMode: 'class',
- theme: {
- extend: {
- maxHeight: {
- '85vh': '85vh',
- '90vh': '90vh'
- },
- colors: {
- primary: 'var(--bg-primary)',
- secondary: 'var(--bg-secondary)',
- accent: 'var(--bg-accent)'
- }
- }
- }
- }
-
// Function to apply the theme based on localStorage and system preference
function applyTheme() {
// Guard against early execution
@@ -75,6 +56,10 @@
applyTheme();
}
</script>
+ <!-- Tailwind utilities, compiled at build time (scripts/build_css.sh). Last in
+ <head> so that, as with the former runtime build, they follow the page's
+ own stylesheets in the cascade. -->
+ <link rel="stylesheet" href="{{ url_for('static', filename='css/tailwind.css') }}">
</head>
<body class="h-full bg-[var(--bg-primary)] text-[var(--text-primary)] transition-colors duration-300">
<div id="app" class="h-full flex flex-col" data-recording='{{ recording|tojson|safe }}'>
diff --git a/tests/e2e/test_browser_smoke.py b/tests/e2e/test_browser_smoke.py
index 358571c6..f5b81994 100644
--- a/tests/e2e/test_browser_smoke.py
+++ b/tests/e2e/test_browser_smoke.py
@@ -11,7 +11,12 @@ Chromium, and fails on:
- any JavaScript error (uncaught exception or console error);
- template text left in the page (``${`` or ``{{``);
- a header that is not mounted, or a user menu that does not open with its
- entries.
+ entries;
+- the Tailwind Play CDN build (vendor/js/tailwind.min.js or
+ cdn.tailwindcss.com) requested, or its "should not be used in production"
+ console warning; the stylesheet is compiled at build time instead;
+- Tailwind utilities from static/css/tailwind.css not applied;
+- translation keys (for example ``nav.account``) shown as text in the header.
It runs only with SPEAKR_BROWSER_SMOKE=1 against a running Speakr at
SPEAKR_BASE_URL (the test.yml browser-smoke job starts one from source with
@@ -48,25 +53,36 @@ PASSWORD = os.environ.get("SPEAKR_SMOKE_PASSWORD", _example.get("ADMIN_PASSWORD"
MENU_ENTRIES = ("Notifications", "Settings", "Shared Transcripts", "Sign Out")
IGNORED_CONSOLE = (re.compile(r"chrome-extension://"), re.compile(r"Failed to load resource"))
+PLAY_CDN = re.compile(r"tailwind\.min\.js|cdn\.tailwindcss\.com")
+# A translation key: two or more dot-separated identifiers, the first one
+# lower case (nav.account, inquire.title, tokenBudget.percentage).
+TRANSLATION_KEY = re.compile(r"\b[a-z][a-zA-Z]*(?:\.[a-zA-Z]+)+\b")
class PageProblems:
"""Collects failed responses and JavaScript errors for the current page."""
def __init__(self, page):
- self.failed, self.errors = [], []
+ self.failed, self.errors, self.play_cdn = [], [], []
+ page.on("request", self._request)
page.on("response", self._response)
page.on("pageerror", lambda exc: self.errors.append(f"uncaught: {exc}"))
page.on("console", self._console)
+ def _request(self, request):
+ if PLAY_CDN.search(request.url):
+ self.play_cdn.append(f"request: {request.url}")
+
def _response(self, response):
if response.url.startswith(BASE) and response.status >= 400:
self.failed.append(f"{response.status} {response.url}")
def _console(self, msg):
+ text = msg.text
+ if "cdn.tailwindcss.com" in text:
+ self.play_cdn.append(f"console {msg.type}: {text}")
if msg.type != "error":
return
- text = msg.text
location = (msg.location or {}).get("url", "")
if any(p.search(text) or p.search(location) for p in IGNORED_CONSOLE):
return
@@ -75,6 +91,7 @@ class PageProblems:
def reset(self):
self.failed.clear()
self.errors.clear()
+ self.play_cdn.clear()
@pytest.fixture(scope="module")
@@ -116,6 +133,26 @@ def _check_common(page, problems, path):
assert not leftovers, f"{path}: template text left in the page: {leftovers}"
assert not problems.failed, f"{path}: failed requests: {problems.failed}"
assert not problems.errors, f"{path}: JavaScript errors: {problems.errors}"
+ assert not problems.play_cdn, f"{path}: Tailwind Play CDN in use: {problems.play_cdn}"
+ # Utilities from the compiled stylesheet apply (a probe element, so the
+ # check does not depend on any page's markup).
+ probe = page.evaluate("""() => {
+ const el = document.createElement('div');
+ el.className = 'rounded-lg px-4 hidden';
+ document.body.appendChild(el);
+ const s = getComputedStyle(el);
+ const out = {display: s.display, radius: s.borderTopLeftRadius, padding: s.paddingLeft};
+ el.remove();
+ return out;
+ }""")
+ assert probe == {"display": "none", "radius": "8px", "padding": "16px"}, f"{path}: Tailwind utilities not applied: {probe}"
+
+
+def _check_header_translated(page, path, selector):
+ header = page.locator(selector).first
+ assert header.count() == 1, f"{path}: no header ({selector})"
+ keys = TRANSLATION_KEY.findall(header.inner_text())
+ assert not keys, f"{path}: translation keys shown in the header: {keys}"
def _check_user_menu(page, path):
@@ -135,6 +172,7 @@ def test_main_view(browser_page):
page, problems = browser_page
_open(page, problems, "/")
assert page.locator("[data-v-app]").count() >= 1, "/: the app did not mount"
+ _check_header_translated(page, "/", "header")
_check_user_menu(page, "/")
_check_common(page, problems, "/")
@@ -149,6 +187,7 @@ def test_settings_pages(browser_page, path):
assert header.get_attribute("data-v-app") is not None, f"{path}: the page header did not mount"
label = header.locator(".t-meta").first.inner_text().strip()
assert label, f"{path}: the page label in the header is empty"
+ _check_header_translated(page, path, "#global-header")
_check_user_menu(page, path)
if path == "/account":
tabs = page.locator(".tabs button:visible, .tabs a:visible")
@@ -163,6 +202,7 @@ def test_inquire_page(browser_page):
pytest.skip("Inquire mode is not enabled")
problems.failed[:] = [f for f in problems.failed if "/inquire " not in f]
assert page.locator("#inquire-app[data-v-app]").count() == 1, "/inquire: the app did not mount"
+ _check_header_translated(page, "/inquire", "#inquire-app header")
_check_user_menu(page, "/inquire")
_check_common(page, problems, "/inquire")
diff --git a/tests/test_page_assets.py b/tests/test_page_assets.py
new file mode 100644
index 00000000..bb6c9d4e
--- /dev/null
+++ b/tests/test_page_assets.py
@@ -0,0 +1,165 @@
+"""Pages load the compiled Tailwind stylesheet and embed their translations.
+
+Tailwind CSS used to be generated in the browser by the Play CDN script
+(vendor/js/tailwind.min.js), so every page was painted unstyled first and
+restyled once the script had run. The stylesheet is now compiled at build
+time (scripts/build_css.sh, the Dockerfile css-stage) and linked in <head>.
+Translations for i18n.js are embedded in the page
+(templates/includes/i18n_bootstrap.html), so the first render shows text and
+not translation keys.
+
+SHARED-DB: the test users are removed afterwards.
+"""
+
+import os
+import re
+import sys
+import uuid
+from unittest.mock import patch
+
+import pytest
+from flask import g
+from flask.testing import FlaskClient
+
+ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+sys.path.insert(0, ROOT)
+
+from src.app import app, db
+from src.models import User
+from src.utils.i18n_bootstrap import i18n_bootstrap
+
+app.config["WTF_CSRF_ENABLED"] = False
+
+TEMPLATES = os.path.join(ROOT, "templates")
+CSS_LINK = "filename='css/tailwind.css'"
+I18N_SCRIPT = "filename='js/i18n.js'"
+BOOTSTRAP_INCLUDE = "{% include 'includes/i18n_bootstrap.html' %}"
+
+
+def _page_templates():
+ """Full pages: templates with their own <head>."""
+ pages = []
+ for dirpath, _, files in os.walk(TEMPLATES):
+ for name in files:
+ if name.endswith(".html"):
+ path = os.path.join(dirpath, name)
+ if "</head>" in open(path, encoding="utf-8").read():
+ pages.append(os.path.relpath(path, TEMPLATES))
+ return sorted(pages)
+
+
+PAGES = _page_templates()
+
+
+def _read(rel):
+ return open(os.path.join(TEMPLATES, rel), encoding="utf-8").read()
+
+
+def test_page_templates_are_found():
+ assert {"index.html", "account.html", "admin.html", "inquire.html", "login.html", "share.html"} <= set(PAGES)
+
+
[email protected]("rel", PAGES)
+def test_each_page_links_the_compiled_stylesheet_last_in_head(rel):
+ text = _read(rel)
+ assert "tailwind.min.js" not in text and "tailwind.config" not in text, rel
+ head = text.split("</head>", 1)[0]
+ assert head.count(CSS_LINK) == 1, rel
+ # Last stylesheet in <head>, as the runtime-generated styles were, so the
+ # cascade order against the page's own styles is unchanged.
+ after = head.split(CSS_LINK, 1)[1]
+ assert "<link" not in after and "<style" not in after, rel
+
+
[email protected]("rel", [p for p in PAGES if I18N_SCRIPT in _read(p)])
+def test_pages_that_load_i18n_embed_the_translations_first(rel):
+ text = _read(rel)
+ assert text.count(BOOTSTRAP_INCLUDE) == 1, rel
+ assert text.index(BOOTSTRAP_INCLUDE) < text.index(I18N_SCRIPT), rel
+
+
+def test_no_code_references_the_play_cdn_build():
+ for top in ("templates", os.path.join("static", "js"), os.path.join("static", "sw.js")):
+ target = os.path.join(ROOT, top)
+ paths = [target] if os.path.isfile(target) else [
+ os.path.join(d, f) for d, _, fs in os.walk(target) for f in fs if f.endswith((".html", ".js"))]
+ for path in paths:
+ assert "tailwind.min.js" not in open(path, encoding="utf-8").read(), path
+
+
+def test_the_service_worker_caches_the_compiled_stylesheet():
+ text = open(os.path.join(ROOT, "static", "sw.js"), encoding="utf-8").read()
+ assert "'/static/css/tailwind.css'" in text
+
+
+def test_compiled_stylesheet_has_the_dynamic_error_colors():
+ """Runs where the stylesheet has been built (CI builds it first)."""
+ path = os.path.join(ROOT, "static", "css", "tailwind.css")
+ if not os.path.exists(path):
+ pytest.skip("static/css/tailwind.css is not built; run scripts/build_css.sh")
+ css = open(path, encoding="utf-8").read()
+ for cls in (r".bg-amber-500\/10", r".border-indigo-500\/30", r".dark\:text-pink-400", r".text-\[var\(--text-primary\)\]"):
+ assert cls in css, cls
+
+
+# --- i18n_bootstrap() --------------------------------------------------------
+
+def test_bootstrap_has_the_locale_and_english():
+ data = i18n_bootstrap("de")
+ assert data["locale"] == "de"
+ assert set(data["translations"]) == {"de", "en"}
+ assert data["translations"]["de"]["nav"]["account"] != data["translations"]["en"]["nav"]["account"]
+
+
+def test_bootstrap_for_english_has_one_table():
+ data = i18n_bootstrap("en")
+ assert data == {"locale": "en", "translations": {"en": data["translations"]["en"]}}
+
+
[email protected]("locale", ["xx", "../en", "en/../de", "", None])
+def test_bootstrap_for_an_unknown_or_invalid_locale_is_english_only(locale):
+ with app.test_request_context():
+ data = i18n_bootstrap(locale)
+ assert data["locale"] == "en"
+ assert list(data["translations"]) == ["en"]
+
+
+# --- Rendered pages -----------------------------------------------------------
+
+class _Client(FlaskClient):
+ def open(self, *args, **kwargs):
+ g.pop("_login_user", None)
+ return super().open(*args, **kwargs)
+
+
+def german_client():
+ with app.app_context():
+ s = uuid.uuid4().hex[:8]
+ user = User(username=f"pa_{s}", email=f"pa_{s}@local.test", password="x", is_admin=True, ui_language="de")
+ db.session.add(user)
+ db.session.commit()
+ client = _Client(app, app.response_class)
+ with client.session_transaction() as sess:
+ sess["_user_id"] = str(user.id)
+ sess["_fresh"] = True
+ yield client
+ db.session.delete(db.session.get(User, user.id))
+ db.session.commit()
+
+
[email protected]("path", ["/", "/account", "/admin", "/inquire"])
+def test_rendered_pages_embed_the_users_language_before_i18n(german_client, path):
+ with patch("src.app.ENABLE_INQUIRE_MODE", True), patch("src.api.inquire.ENABLE_INQUIRE_MODE", True):
+ response = german_client.get(path)
+ assert response.status_code == 200, path
+ html = response.get_data(as_text=True)
+ assert "/static/css/tailwind.css" in html.split("</head>", 1)[0], path
+ m = re.search(r"window\.__I18N_BOOTSTRAP = (\{.*?\});</script>", html, re.S)
+ assert m, path
+ assert html.index("window.__I18N_BOOTSTRAP") < html.index("/static/js/i18n.js"), path
+ import json
+ data = json.loads(m.group(1))
+ assert data["locale"] == "de" and set(data["translations"]) == {"de", "en"}, path
+ # |tojson escapes markup characters, so no translation can end the script.
+ assert "</" not in m.group(1), path