Compare commits

..

13 Commits

Author SHA1 Message Date
Peter Stockings
25d1774e53 perf: remove redundant COUNT query and use bulk insert for CSV imports 2026-03-15 00:24:26 +11:00
Peter Stockings
25aa7de043 Add minification of html, css, & js and brotli compression to reduce page size 2026-03-14 23:58:37 +11:00
Peter Stockings
f7ce1c3fd6 Shrink profile pic 2026-03-13 22:42:30 +11:00
Peter Stockings
e2d85f0a88 Make table view responsive 2026-03-13 15:28:06 +11:00
Peter Stockings
910d583966 Make date filters responsive 2026-03-13 15:20:58 +11:00
Peter Stockings
eca31040af Update DIY HTMX to trigger on input update 2026-03-13 15:18:09 +11:00
Peter Stockings
086784b2a2 Add table view 2026-03-13 15:14:00 +11:00
Peter Stockings
a9802f300b Move date filter to graph view 2026-03-13 15:11:11 +11:00
Peter Stockings
6f216944bf Improve look of graphs 2026-03-12 22:56:26 +11:00
Peter Stockings
675ca02818 Add diy replacement for turbo 2026-03-11 22:57:54 +11:00
Peter Stockings
5b43bca7ca Defer loading of profile pic 2026-03-10 19:40:19 +11:00
Peter Stockings
808143f92b Improve badge performance 2026-03-10 19:23:56 +11:00
Peter Stockings
dcef99c3bf perf: massive reduction in application bundle size
- Replaced Alpine.js and Turbolinks with lightweight vanilla JS event listeners
- Swapped HTMX CDN import for a custom 15-line native JS polyfill
- Removed Google Fonts ('Inter') in favor of the native system font stack
- Extracted repeated SVGs in list views into a `<defs>` block to shrink HTML
- Reduced dashboard pagination PAGE_SIZE from 50 to 25
- Minified Tailwind CSS output and enabled Gzip/Brotli via Flask-Compress
2026-03-10 19:10:47 +11:00
23 changed files with 1078 additions and 2342 deletions

View File

@@ -7,6 +7,7 @@ WORKDIR /app
# Copy only the necessary files for TailwindCSS build # Copy only the necessary files for TailwindCSS build
COPY package.json package-lock.json ./ COPY package.json package-lock.json ./
COPY ./app/templates ./app/templates COPY ./app/templates ./app/templates
COPY ./app/static/js ./app/static/js
COPY tailwind.config.js ./ COPY tailwind.config.js ./
# Install Node.js dependencies # Install Node.js dependencies
@@ -39,6 +40,7 @@ COPY . .
# Copy the built TailwindCSS assets from the first stage # Copy the built TailwindCSS assets from the first stage
COPY --from=tailwind-builder /app/app/static/css/tailwind.css ./app/static/css/tailwind.css COPY --from=tailwind-builder /app/app/static/css/tailwind.css ./app/static/css/tailwind.css
COPY --from=tailwind-builder /app/app/static/js/diy-turbo.min.js ./app/static/js/diy-turbo.min.js
# Run tests during the build process # Run tests during the build process
RUN pytest --maxfail=5 --disable-warnings -v || (echo "Tests failed. Exiting." && exit 1) RUN pytest --maxfail=5 --disable-warnings -v || (echo "Tests failed. Exiting." && exit 1)

View File

@@ -4,12 +4,16 @@ from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate from flask_migrate import Migrate
from flask_bcrypt import Bcrypt from flask_bcrypt import Bcrypt
from flask_login import LoginManager from flask_login import LoginManager
from flask_compress import Compress
from flask_minify import Minify
# Initialize Flask extensions # Initialize Flask extensions
db = SQLAlchemy() db = SQLAlchemy()
migrate = Migrate() migrate = Migrate()
bcrypt = Bcrypt() bcrypt = Bcrypt()
login_manager = LoginManager() login_manager = LoginManager()
compress = Compress()
minify = Minify(html=True, js=True, cssless=True, fail_safe=True)
login_manager.login_view = 'auth.login' login_manager.login_view = 'auth.login'
login_manager.login_message_category = 'info' login_manager.login_message_category = 'info'
@@ -26,6 +30,9 @@ def create_app():
migrate.init_app(app, db) migrate.init_app(app, db)
bcrypt.init_app(app) bcrypt.init_app(app)
login_manager.init_app(app) login_manager.init_app(app)
compress.init_app(app)
minify.init_app(app)
# Import models here to avoid circular imports # Import models here to avoid circular imports
from app.models import User # Import the User model from app.models import User # Import the User model

View File

@@ -11,10 +11,10 @@ class User(UserMixin, db.Model):
class Profile(db.Model): class Profile(db.Model):
id = db.Column(db.Integer, primary_key=True) id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False) user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False, index=True)
name = db.Column(db.String(100)) name = db.Column(db.String(100))
email = db.Column(db.String(150), unique=True) email = db.Column(db.String(150), unique=True)
profile_pic = db.Column(db.Text) # Store image as a base64 string profile_pic = db.deferred(db.Column(db.Text)) # Store image as a base64 string, deferred so it doesn't load on every query
systolic_threshold = db.Column(db.Integer, default=140) systolic_threshold = db.Column(db.Integer, default=140)
diastolic_threshold = db.Column(db.Integer, default=90) diastolic_threshold = db.Column(db.Integer, default=90)
dark_mode = db.Column(db.Boolean, default=False) dark_mode = db.Column(db.Boolean, default=False)

View File

@@ -17,16 +17,17 @@ def manage_data():
try: try:
csv_data = csv.reader(StringIO(file.read().decode('utf-8'))) csv_data = csv.reader(StringIO(file.read().decode('utf-8')))
next(csv_data) # Skip the header row next(csv_data) # Skip the header row
readings_to_add = []
for row in csv_data: for row in csv_data:
timestamp, systolic, diastolic, heart_rate = row timestamp, systolic, diastolic, heart_rate = row
reading = Reading( readings_to_add.append(Reading(
user_id=current_user.id, user_id=current_user.id,
timestamp=datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S'), timestamp=datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S'),
systolic=int(systolic), systolic=int(systolic),
diastolic=int(diastolic), diastolic=int(diastolic),
heart_rate=int(heart_rate), heart_rate=int(heart_rate),
) ))
db.session.add(reading) db.session.bulk_save_objects(readings_to_add)
db.session.commit() db.session.commit()
flash('Data imported successfully!', 'success') flash('Data imported successfully!', 'success')
except Exception as e: except Exception as e:

View File

@@ -11,7 +11,7 @@ from datetime import date, datetime, timedelta
main = Blueprint('main', __name__) main = Blueprint('main', __name__)
# Number of readings to show per page in list view # Number of readings to show per page in list view
PAGE_SIZE = 50 PAGE_SIZE = 25
@main.route('/', methods=['GET']) @main.route('/', methods=['GET'])
def landing(): def landing():
@@ -27,25 +27,10 @@ def dashboard():
"""Render the dashboard shell and default list view.""" """Render the dashboard shell and default list view."""
user_tz = timezone(current_user.profile.timezone or 'UTC') user_tz = timezone(current_user.profile.timezone or 'UTC')
# Get date range for filters
first_reading, last_reading = get_reading_date_range(current_user.id, user_tz)
start_date = request.form.get('start_date') or request.args.get('start_date') or (first_reading and first_reading.strftime('%Y-%m-%d'))
end_date = request.form.get('end_date') or request.args.get('end_date') or (last_reading and last_reading.strftime('%Y-%m-%d'))
# Calculate weekly averages via SQL # Calculate weekly averages via SQL
systolic_avg, diastolic_avg, heart_rate_avg = calculate_weekly_summary_sql(current_user.id) systolic_avg, diastolic_avg, heart_rate_avg = calculate_weekly_summary_sql(current_user.id)
# Badges need paginated or all readings. We'll fetch all readings for badges badges = calculate_progress_badges(current_user.id, user_tz)
# Note: To avoid huge queries, we might want a specific badge query in the future.
# For now, let's fetch current month readings + previous as a rough approximation or keep behavior.
# A generic query for badges:
all_readings = Reading.query.filter_by(user_id=current_user.id).order_by(Reading.timestamp.desc()).all()
badges = calculate_progress_badges(all_readings)
# We will default to showing the list view on initial load
page = request.args.get('page', 1, type=int)
paginated = fetch_readings_paginated(current_user.id, start_date, end_date, user_tz, page, PAGE_SIZE)
annotate_readings(paginated.items, user_tz)
return render_template( return render_template(
'dashboard.html', 'dashboard.html',
@@ -54,20 +39,28 @@ def dashboard():
systolic_avg=systolic_avg, systolic_avg=systolic_avg,
diastolic_avg=diastolic_avg, diastolic_avg=diastolic_avg,
heart_rate_avg=heart_rate_avg, heart_rate_avg=heart_rate_avg,
start_date=start_date,
end_date=end_date,
delete_form=DeleteForm(), delete_form=DeleteForm(),
active_view='list', active_view='list',
# default view context
readings=paginated.items,
pagination=paginated
) )
@main.route('/dashboard/list', methods=['GET']) @main.route('/dashboard/list', methods=['GET'])
@login_required @login_required
def dashboard_list(): def dashboard_list():
user_tz = timezone(current_user.profile.timezone or 'UTC')
page = request.args.get('page', 1, type=int)
# List view is no longer constrained by date filter
paginated = fetch_readings_paginated(current_user.id, None, None, user_tz, page, PAGE_SIZE)
annotate_readings(paginated.items, user_tz)
return render_template('partials/dashboard_list.html', readings=paginated.items, pagination=paginated)
@main.route('/dashboard/table', methods=['GET'])
@login_required
def dashboard_table():
user_tz = timezone(current_user.profile.timezone or 'UTC') user_tz = timezone(current_user.profile.timezone or 'UTC')
first_reading, last_reading = get_reading_date_range(current_user.id, user_tz) first_reading, last_reading = get_reading_date_range(current_user.id, user_tz)
start_date = request.args.get('start_date') or (first_reading and first_reading.strftime('%Y-%m-%d')) start_date = request.args.get('start_date') or (first_reading and first_reading.strftime('%Y-%m-%d'))
end_date = request.args.get('end_date') or (last_reading and last_reading.strftime('%Y-%m-%d')) end_date = request.args.get('end_date') or (last_reading and last_reading.strftime('%Y-%m-%d'))
page = request.args.get('page', 1, type=int) page = request.args.get('page', 1, type=int)
@@ -75,7 +68,7 @@ def dashboard_list():
paginated = fetch_readings_paginated(current_user.id, start_date, end_date, user_tz, page, PAGE_SIZE) paginated = fetch_readings_paginated(current_user.id, start_date, end_date, user_tz, page, PAGE_SIZE)
annotate_readings(paginated.items, user_tz) annotate_readings(paginated.items, user_tz)
return render_template('partials/dashboard_list.html', readings=paginated.items, pagination=paginated) return render_template('partials/dashboard_table.html', readings=paginated.items, pagination=paginated, start_date=start_date, end_date=end_date)
@main.route('/dashboard/weekly', methods=['GET']) @main.route('/dashboard/weekly', methods=['GET'])
@login_required @login_required
@@ -125,14 +118,26 @@ def dashboard_monthly():
@login_required @login_required
def dashboard_graph(): def dashboard_graph():
user_tz = timezone(current_user.profile.timezone or 'UTC') user_tz = timezone(current_user.profile.timezone or 'UTC')
now = datetime.now(user_tz) first_reading, last_reading = get_reading_date_range(current_user.id, user_tz)
month_start = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
month_start_utc = month_start.astimezone(utc) start_date = request.args.get('start_date') or (first_reading and first_reading.strftime('%Y-%m-%d'))
end_date = request.args.get('end_date') or (last_reading and last_reading.strftime('%Y-%m-%d'))
if start_date and end_date:
start_dt = user_tz.localize(datetime.strptime(start_date, '%Y-%m-%d')).astimezone(utc)
end_dt = user_tz.localize(datetime.strptime(end_date, '%Y-%m-%d')).astimezone(utc) + timedelta(days=1) - timedelta(seconds=1)
calendar_readings = fetch_readings_for_range(current_user.id, start_dt, end_dt)
else:
now = datetime.now(user_tz)
month_start = now.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
month_start_utc = month_start.astimezone(utc)
calendar_readings = fetch_readings_for_range(current_user.id, month_start_utc)
calendar_readings = fetch_readings_for_range(current_user.id, month_start_utc)
annotate_readings(calendar_readings, user_tz) annotate_readings(calendar_readings, user_tz)
graph_data = prepare_graph_data(calendar_readings) graph_data = prepare_graph_data(calendar_readings)
graph_data['start_date'] = start_date
graph_data['end_date'] = end_date
return render_template('partials/dashboard_graph.html', **graph_data) return render_template('partials/dashboard_graph.html', **graph_data)
@@ -240,55 +245,102 @@ def generate_weekly_calendar(readings_by_day, selected_date, local_tz):
] ]
def prepare_graph_data(readings): def prepare_graph_data(readings):
"""Prepare data for graph rendering.""" """Prepare data for graph rendering, reversing so chronological order is left-to-right."""
chronological_readings = list(reversed(readings))
n = len(chronological_readings)
time_percentages = []
systolic_vals = [r.systolic for r in chronological_readings]
diastolic_vals = [r.diastolic for r in chronological_readings]
hr_vals = [r.heart_rate for r in chronological_readings]
sys_avg = round(sum(systolic_vals) / n, 1) if n > 0 else 0
dia_avg = round(sum(diastolic_vals) / n, 1) if n > 0 else 0
hr_avg = round(sum(hr_vals) / n, 1) if n > 0 else 0
if n == 0:
pass
elif n == 1:
time_percentages = [0.5]
else:
first_time = chronological_readings[0].timestamp.timestamp()
last_time = chronological_readings[-1].timestamp.timestamp()
time_span = last_time - first_time
for r in chronological_readings:
if time_span == 0:
time_percentages.append(0.5)
else:
p = (r.timestamp.timestamp() - first_time) / time_span
time_percentages.append(p)
return { return {
'timestamps': [r.timestamp.strftime('%b %d') for r in readings], 'timestamps': [r.timestamp.strftime('%b %d\n%H:%M') for r in chronological_readings],
'systolic': [r.systolic for r in readings], 'systolic': systolic_vals,
'diastolic': [r.diastolic for r in readings], 'diastolic': diastolic_vals,
'heart_rate': [r.heart_rate for r in readings], 'heart_rate': hr_vals,
'time_percentages': time_percentages,
'sys_avg': sys_avg,
'dia_avg': dia_avg,
'hr_avg': hr_avg,
} }
def calculate_progress_badges(readings): def calculate_progress_badges(user_id, user_tz):
"""Generate badges based on user activity and milestones.""" """Generate badges based on user activity and milestones using optimized queries."""
now = datetime.utcnow().date() # Fetch only timestamps (index-only scan on the composite index)
timestamps = db.session.query(Reading.timestamp).filter(Reading.user_id == user_id).order_by(Reading.timestamp.desc()).all()
total_readings = len(timestamps)
return _compute_badges(total_readings, timestamps, user_tz)
def _compute_badges(total_readings, timestamps, user_tz, now_local=None):
if now_local is None:
now_local = datetime.now(user_tz).date()
badges = [] badges = []
if not readings: if total_readings == 0:
return badges return badges
# Use reversed() instead of re-sorting — readings come in desc order from DB streak_count = 0
sorted_readings = list(reversed(readings)) if timestamps:
streak_count = 1 distinct_dates = []
daily_streak = True last_date = None
for (ts,) in timestamps:
local_date = utc.localize(ts).astimezone(user_tz).date()
if local_date != last_date:
distinct_dates.append(local_date)
last_date = local_date
previous_date = sorted_readings[0].timestamp.date() if distinct_dates:
most_recent_date = distinct_dates[0]
if (now_local - most_recent_date).days <= 1:
streak_count = 1
current_check_date = most_recent_date
for reading in sorted_readings[1:]: for d in distinct_dates[1:]:
current_date = reading.timestamp.date() if (current_check_date - d).days == 1:
streak_count += 1
current_check_date = d
else:
break
if (current_date - previous_date).days == 1: if streak_count >= 1:
streak_count += 1
elif (current_date - previous_date).days > 1:
daily_streak = False
previous_date = current_date
if daily_streak and streak_count >= 1:
badges.append(f"Current Streak: {streak_count} Days") badges.append(f"Current Streak: {streak_count} Days")
if daily_streak and streak_count >= 7: if streak_count >= 7:
badges.append("Logged Every Day for a Week") badges.append("Logged Every Day for a Week")
if streak_count >= 30:
if daily_streak and streak_count >= 30 and previous_date == now:
badges.append("Monthly Streak") badges.append("Monthly Streak")
if all(5 <= r.timestamp.hour < 12 for r in sorted_readings[-7:]): last_7_readings = timestamps[:7]
badges.append("Morning Riser: Logged Readings Every Morning for a Week") if len(last_7_readings) == 7:
if all(5 <= utc.localize(ts).astimezone(user_tz).hour < 12 for (ts,) in last_7_readings):
badges.append("Morning Riser: Logged Readings Every Morning for a Week")
if all(18 <= r.timestamp.hour <= 23 for r in sorted_readings[-7:]): if all(18 <= utc.localize(ts).astimezone(user_tz).hour <= 23 for (ts,) in last_7_readings):
badges.append("Night Owl: Logged Readings Every Night for a Week") badges.append("Night Owl: Logged Readings Every Night for a Week")
milestones = [10, 50, 100, 500, 1000, 5000, 10000] milestones = [10, 50, 100, 500, 1000, 5000, 10000]
highest_milestone = max((m for m in milestones if len(readings) >= m), default=None) highest_milestone = max((m for m in milestones if total_readings >= m), default=None)
if highest_milestone: if highest_milestone:
badges.append(f"{highest_milestone} Readings Logged") badges.append(f"{highest_milestone} Readings Logged")

View File

@@ -33,7 +33,7 @@ def profile():
try: try:
image = Image.open(io.BytesIO(file_data)) image = Image.open(io.BytesIO(file_data))
image = image.convert("RGB") # Ensure it's in RGB format image = image.convert("RGB") # Ensure it's in RGB format
image.thumbnail((300, 300)) # Resize to a maximum of 300x300 pixels image.thumbnail((200, 200)) # Resize to a maximum of 200x200 pixels
# Save the resized image to a buffer # Save the resized image to a buffer
buffer = io.BytesIO() buffer = io.BytesIO()

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1,68 @@
document.addEventListener('click', async (e) => {
const link = e.target.closest('a');
if (!link) return;
const url = link.getAttribute('href');
if (!url || url.startsWith('#') || url.startsWith('javascript:')) return;
// Only intercept same-origin links
if (link.origin !== window.location.origin) return;
// Ignore links that open in a new tab, download, or modifier keys
if (link.target === '_blank' || link.hasAttribute('download')) return;
if (e.ctrlKey || e.shiftKey || e.metaKey || e.altKey) return;
// Optional: add a "data-turbo='false'" attribute check to disable it on specific links
if (link.getAttribute('data-turbo') === 'false') return;
e.preventDefault();
document.body.style.cursor = 'wait';
try {
const response = await fetch(url);
if (!response.ok) throw new Error('Fetch failed');
const html = await response.text();
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
document.title = doc.title;
document.body.innerHTML = doc.body.innerHTML;
// Carry over classes on the body if they changed
document.body.className = doc.body.className;
document.body.style.cursor = 'default';
window.history.pushState({}, '', url);
window.scrollTo(0, 0);
// Dispatch a custom event so other scripts can re-initialize if necessary
document.dispatchEvent(new Event('diy-turbo:load'));
} catch (error) {
console.error('DIY Turbo navigation error:', error);
window.location.href = url; // fallback
}
});
window.addEventListener('popstate', async () => {
document.body.style.cursor = 'wait';
try {
const response = await fetch(window.location.href);
if (!response.ok) throw new Error('Fetch failed');
const html = await response.text();
const parser = new DOMParser();
const doc = parser.parseFromString(html, 'text/html');
document.title = doc.title;
document.body.innerHTML = doc.body.innerHTML;
document.body.className = doc.body.className;
document.body.style.cursor = 'default';
document.dispatchEvent(new Event('diy-turbo:load'));
} catch (error) {
console.error('DIY Turbo popstate error:', error);
window.location.reload(); // fallback
}
});

1
app/static/js/diy-turbo.min.js vendored Normal file
View File

@@ -0,0 +1 @@
document.addEventListener("click",async t=>{const e=t.target.closest("a");if(!e)return;const o=e.getAttribute("href");if(o&&!o.startsWith("#")&&!o.startsWith("javascript:")&&e.origin===window.location.origin&&!("_blank"===e.target||e.hasAttribute("download")||t.ctrlKey||t.shiftKey||t.metaKey||t.altKey||"false"===e.getAttribute("data-turbo"))){t.preventDefault(),document.body.style.cursor="wait";try{const t=await fetch(o);if(!t.ok)throw new Error("Fetch failed");const e=await t.text(),r=(new DOMParser).parseFromString(e,"text/html");document.title=r.title,document.body.innerHTML=r.body.innerHTML,document.body.className=r.body.className,document.body.style.cursor="default",window.history.pushState({},"",o),window.scrollTo(0,0),document.dispatchEvent(new Event("diy-turbo:load"))}catch(t){console.error("DIY Turbo navigation error:",t),window.location.href=o}}}),window.addEventListener("popstate",async()=>{document.body.style.cursor="wait";try{const t=await fetch(window.location.href);if(!t.ok)throw new Error("Fetch failed");const e=await t.text(),o=(new DOMParser).parseFromString(e,"text/html");document.title=o.title,document.body.innerHTML=o.body.innerHTML,document.body.className=o.body.className,document.body.style.cursor="default",document.dispatchEvent(new Event("diy-turbo:load"))}catch(t){console.error("DIY Turbo popstate error:",t),window.location.reload()}});

File diff suppressed because one or more lines are too long

View File

@@ -6,17 +6,13 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{% block title %}BP Tracker{% endblock %}</title> <title>{% block title %}BP Tracker{% endblock %}</title>
<link rel="icon" type="image/svg+xml" sizes="any" href="{{ url_for('static', filename='images/favicon.svg') }}"> <link rel="icon" type="image/svg+xml" sizes="any" href="{{ url_for('static', filename='images/favicon.svg') }}">
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet">
<link href="/static/css/tailwind.css" rel="stylesheet"> <link href="/static/css/tailwind.css" rel="stylesheet">
<script src="/static/js/alpine.min.js" defer></script> <script src="{{ url_for('static', filename='js/diy-turbo.min.js') }}"></script>
<script src="https://unpkg.com/htmx.org@1.9.10"></script>
<script src="/static/js/turbolinks.min.js"></script>
</head> </head>
<body class="bg-gray-50 text-gray-800 font-sans antialiased"> <body class="bg-gray-50 text-gray-800 font-sans antialiased">
<nav class="flex items-center justify-between flex-wrap p-6 fixed w-full z-10 top-0 transition-colors duration-300 shadow-md" <nav id="mobile-nav"
x-data="{ isOpen: false }" @keydown.escape="isOpen = false" @click.away="isOpen = false" class="flex items-center justify-between flex-wrap p-6 fixed w-full z-10 top-0 transition-colors duration-300 shadow-md bg-primary-800">
:class="{ 'bg-primary-900' : isOpen , 'bg-primary-800' : !isOpen}">
<!--Logo etc--> <!--Logo etc-->
<div class="flex items-center flex-shrink-0 text-white mr-6"> <div class="flex items-center flex-shrink-0 text-white mr-6">
<a class="text-white no-underline hover:text-white hover:no-underline" href="/"> <a class="text-white no-underline hover:text-white hover:no-underline" href="/">
@@ -25,20 +21,18 @@
</div> </div>
<!--Toggle button (hidden on large screens)--> <!--Toggle button (hidden on large screens)-->
<button @click="isOpen = !isOpen" type="button" <button id="mobile-menu-btn" type="button"
class="block lg:hidden px-2 text-gray-500 hover:text-white focus:outline-none focus:text-white" class="block lg:hidden px-2 text-gray-500 hover:text-white focus:outline-none focus:text-white transition">
:class="{ 'transition transform-180': isOpen }">
<svg class="h-6 w-6 fill-current" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"> <svg class="h-6 w-6 fill-current" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path x-show="isOpen" fill-rule="evenodd" clip-rule="evenodd" <path id="icon-close" class="hidden" fill-rule="evenodd" clip-rule="evenodd"
d="M18.278 16.864a1 1 0 0 1-1.414 1.414l-4.829-4.828-4.828 4.828a1 1 0 0 1-1.414-1.414l4.828-4.829-4.828-4.828a1 1 0 0 1 1.414-1.414l4.829 4.828 4.828-4.828a1 1 0 1 1 1.414 1.414l-4.828 4.829 4.828 4.828z" /> d="M18.278 16.864a1 1 0 0 1-1.414 1.414l-4.829-4.828-4.828 4.828a1 1 0 0 1-1.414-1.414l4.828-4.829-4.828-4.828a1 1 0 0 1 1.414-1.414l4.829 4.828 4.828-4.828a1 1 0 1 1 1.414 1.414l-4.828 4.829 4.828 4.828z" />
<path x-show="!isOpen" fill-rule="evenodd" <path id="icon-menu" fill-rule="evenodd"
d="M4 5h16a1 1 0 0 1 0 2H4a1 1 0 1 1 0-2zm0 6h16a1 1 0 0 1 0 2H4a1 1 0 0 1 0-2zm0 6h16a1 1 0 0 1 0 2H4a1 1 0 0 1 0-2z" /> d="M4 5h16a1 1 0 0 1 0 2H4a1 1 0 1 1 0-2zm0 6h16a1 1 0 0 1 0 2H4a1 1 0 0 1 0-2zm0 6h16a1 1 0 0 1 0 2H4a1 1 0 0 1 0-2z" />
</svg> </svg>
</button> </button>
<!--Menu--> <!--Menu-->
<div class="w-full flex-grow lg:flex lg:items-center lg:w-auto" <div id="mobile-menu" class="w-full flex-grow lg:flex lg:items-center lg:w-auto hidden shadow-3xl">
:class="{ 'block shadow-3xl': isOpen, 'hidden': !isOpen }" x-show.transition="true">
<ul class="pt-6 lg:pt-0 list-reset lg:flex justify-end flex-1 items-center"> <ul class="pt-6 lg:pt-0 list-reset lg:flex justify-end flex-1 items-center">
{% if current_user.is_authenticated %} {% if current_user.is_authenticated %}
<li class="mr-3"> <li class="mr-3">
@@ -62,20 +56,8 @@
<li class="mr-3"> <li class="mr-3">
<a class="flex items-center gap-2 text-primary-200 no-underline hover:text-white font-medium transition-colors py-2 px-4" <a class="flex items-center gap-2 text-primary-200 no-underline hover:text-white font-medium transition-colors py-2 px-4"
href="{{ url_for('user.profile') }}"> href="{{ url_for('user.profile') }}">
{% if current_user.profile and current_user.profile.profile_pic %}
<img src="{{ url_for('user.profile_image', user_id=current_user.id) }}" alt="Profile Picture" <img src="{{ url_for('user.profile_image', user_id=current_user.id) }}" alt="Profile Picture"
class="w-8 h-8 rounded-full border-2 border-white object-cover group-hover:scale-105 transition"> class="w-8 h-8 rounded-full border-2 border-white object-cover group-hover:scale-105 transition">
{% else %}
<!-- Default SVG Icon -->
<div
class="w-8 h-8 bg-primary-100 rounded-full flex items-center justify-center border-2 border-white">
<svg xmlns="http://www.w3.org/2000/svg" fill="currentColor" class="w-5 h-5 text-gray-600"
viewBox="0 0 24 24">
<path
d="M12 12c2.76 0 5-2.24 5-5s-2.24-5-5-5-5 2.24-5 5 2.24 5 5 5zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z" />
</svg>
</div>
{% endif %}
<span class=" text-sm font-medium group-hover:underline <span class=" text-sm font-medium group-hover:underline
{% if request.path == url_for('user.profile') %} {% if request.path == url_for('user.profile') %}
text-white text-white
@@ -121,11 +103,11 @@
{% if messages %} {% if messages %}
<div class="fixed top-24 right-4 z-50 space-y-4"> <div class="fixed top-24 right-4 z-50 space-y-4">
{% for category, message in messages %} {% for category, message in messages %}
<div class="flex items-center justify-between p-4 rounded-xl shadow-xl text-white bg-{{ 'red' if category == 'danger' else 'primary' }}-500 min-w-[300px]" <div
x-data="{ visible: true }" x-show="visible" x-transition.duration.300ms> class="flash-message flex items-center justify-between p-4 rounded-xl shadow-xl text-white bg-{{ 'red' if category == 'danger' else 'primary' }}-500 min-w-[300px] transition-all duration-300">
<span class="font-medium">{{ message }}</span> <span class="font-medium">{{ message }}</span>
<button @click="visible = false" <button
class="text-2xl font-bold ml-4 hover:text-gray-200 transition-colors">&times;</button> class="flash-close-btn text-2xl font-bold ml-4 hover:text-gray-200 transition-colors">&times;</button>
</div> </div>
{% endfor %} {% endfor %}
</div> </div>
@@ -146,6 +128,168 @@
</div> </div>
</footer> </footer>
<script>
// Use document for event delegation since body is replaced by diy-turbo
document.addEventListener('click', async (e) => {
// Flash messages close button
const flashCloseBtn = e.target.closest('.flash-close-btn');
if (flashCloseBtn) {
const el = flashCloseBtn.closest('.flash-message');
if (el) {
el.style.opacity = '0';
setTimeout(() => el.remove(), 300);
}
return;
}
// Micro-HTMX implementation
const htmxTrigger = e.target.closest('[hx-get]');
if (htmxTrigger) {
if (htmxTrigger.tagName === 'FORM') return; // Let submit handler deal with forms
e.preventDefault();
const url = htmxTrigger.getAttribute('hx-get');
const targetSelector = htmxTrigger.getAttribute('hx-target');
if (!url || !targetSelector) return;
const targetEl = document.querySelector(targetSelector);
if (!targetEl) return;
try {
const response = await fetch(url);
if (!response.ok) throw new Error('Fetch failed');
targetEl.innerHTML = await response.text();
} catch (err) {
console.error('Micro-HTMX error:', err);
}
return;
}
// Mobile Menu Toggle Button
const menuBtn = e.target.closest('#mobile-menu-btn');
if (menuBtn) {
const menu = document.getElementById('mobile-menu');
const nav = document.getElementById('mobile-nav');
const iconMenu = document.getElementById('icon-menu');
const iconClose = document.getElementById('icon-close');
if (menu) {
const isHidden = menu.classList.contains('hidden');
if (!isHidden) {
menu.classList.add('hidden');
nav.classList.replace('bg-primary-900', 'bg-primary-800');
iconMenu.classList.remove('hidden');
iconClose.classList.add('hidden');
menuBtn.classList.remove('rotate-180', 'transform');
} else {
menu.classList.remove('hidden');
nav.classList.replace('bg-primary-800', 'bg-primary-900');
iconMenu.classList.add('hidden');
iconClose.classList.remove('hidden');
menuBtn.classList.add('rotate-180', 'transform');
}
}
return;
}
// Handle clicks outside of nav/menu to close mobile menu
const nav = document.getElementById('mobile-nav');
const menu = document.getElementById('mobile-menu');
if (nav && menu && !nav.contains(e.target) && !menu.classList.contains('hidden')) {
menu.classList.add('hidden');
nav.classList.replace('bg-primary-900', 'bg-primary-800');
const iconMenu = document.getElementById('icon-menu');
const iconClose = document.getElementById('icon-close');
const mobileMenuBtn = document.getElementById('mobile-menu-btn');
if (iconMenu) iconMenu.classList.remove('hidden');
if (iconClose) iconClose.classList.add('hidden');
if (mobileMenuBtn) mobileMenuBtn.classList.remove('rotate-180', 'transform');
}
});
// Handle Escape key to close mobile menu
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape') {
const menu = document.getElementById('mobile-menu');
if (menu && !menu.classList.contains('hidden')) {
const nav = document.getElementById('mobile-nav');
menu.classList.add('hidden');
if (nav) nav.classList.replace('bg-primary-900', 'bg-primary-800');
const iconMenu = document.getElementById('icon-menu');
const iconClose = document.getElementById('icon-close');
const mobileMenuBtn = document.getElementById('mobile-menu-btn');
if (iconMenu) iconMenu.classList.remove('hidden');
if (iconClose) iconClose.classList.add('hidden');
if (mobileMenuBtn) mobileMenuBtn.classList.remove('rotate-180', 'transform');
}
}
});
// Auto-submit forms when inputs change
document.addEventListener('change', (e) => {
const htmxForm = e.target.closest('form[hx-get], form[hx-post]');
if (htmxForm) {
htmxForm.dispatchEvent(new Event('submit', { cancelable: true, bubbles: true }));
}
});
// Handle form submissions for Micro-HTMX
document.addEventListener('submit', async (e) => {
const htmxForm = e.target.closest('form[hx-get], form[hx-post]');
if (htmxForm) {
e.preventDefault();
const method = htmxForm.hasAttribute('hx-post') ? 'POST' : 'GET';
let url = htmxForm.getAttribute('hx-get') || htmxForm.getAttribute('hx-post');
const targetSelector = htmxForm.getAttribute('hx-target');
if (!url || !targetSelector) return;
const targetEl = document.querySelector(targetSelector);
if (!targetEl) return;
try {
let fetchOpts = { method };
if (method === 'GET') {
const formData = new FormData(htmxForm);
const params = new URLSearchParams(formData).toString();
if (params) {
url += (url.includes('?') ? '&' : '?') + params;
}
} else {
fetchOpts.body = new FormData(htmxForm);
}
const response = await fetch(url, fetchOpts);
if (!response.ok) throw new Error('Fetch failed');
targetEl.innerHTML = await response.text();
} catch (err) {
console.error('Micro-HTMX submit error:', err);
}
}
});
// Handle auto-loading elements
const handleAutoLoads = async () => {
const elements = document.querySelectorAll('[hx-trigger="load"][hx-get]');
for (const el of elements) {
const url = el.getAttribute('hx-get');
try {
const response = await fetch(url);
if (!response.ok) throw new Error('Auto-fetch failed');
el.innerHTML = await response.text();
el.removeAttribute('hx-trigger'); // ensure it only loads once per page view
} catch (err) {
console.error('Micro-HTMX autoload error:', err);
}
}
};
document.addEventListener('DOMContentLoaded', handleAutoLoads);
document.addEventListener('diy-turbo:load', handleAutoLoads);
</script>
</body> </body>
</html> </html>

View File

@@ -40,73 +40,75 @@
</div> </div>
</div> </div>
<div x-data="{ open: {{ 'true' if request.method == 'POST' else 'false' }} }" class="relative">
<!-- Compact Icon -->
<button @click="open = !open"
class="bg-primary-600 text-white p-3 rounded-full shadow-lg focus:outline-none hover:bg-primary-700">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2"
stroke="currentColor" class="w-6 h-6">
<path x-show="!open" stroke-linecap="round" stroke-linejoin="round" d="M6 9l6 6 6-6" />
<path x-show="open" x-cloak stroke-linecap="round" stroke-linejoin="round" d="M18 15l-6-6-6 6" />
</svg>
</button>
<!-- Collapsible Filter Form -->
<div x-show="open" x-transition.duration.300ms
class="w-full md:w-1/3 bg-white p-6 rounded-xl shadow-lg border border-gray-200">
<div class="flex justify-between items-center mb-4">
<h3 class="text-lg font-bold text-gray-800">Filter Readings</h3>
</div>
<form method="POST" action="{{ url_for('main.dashboard') }}" class="space-y-4">
<!-- Start Date -->
<div>
<label for="start_date" class="block text-sm font-medium text-gray-700">Start Date</label>
<input type="date" name="start_date" id="start_date"
class="w-full p-3 border border-gray-300 rounded-xl shadow-sm focus:outline-none focus:ring-2 focus:ring-primary-500">
</div>
<!-- End Date -->
<div>
<label for="end_date" class="block text-sm font-medium text-gray-700">End Date</label>
<input type="date" name="end_date" id="end_date"
class="w-full p-3 border border-gray-300 rounded-xl shadow-sm focus:outline-none focus:ring-2 focus:ring-primary-500">
</div>
<!-- Apply Button -->
<div>
<button type="submit"
class="w-full bg-primary-600 text-white py-2 rounded-xl font-semibold shadow-md hover:bg-primary-700 focus:outline-none">
Apply Filters
</button>
</div>
</form>
</div>
</div>
<div class="max-w-5xl mx-auto" x-data="{ activeView: '{{ active_view }}' }">
<div class="max-w-5xl mx-auto">
<!-- Tabs --> <!-- Tabs -->
<div class="flex border-b mb-4"> <div class="flex border-b mb-4 overflow-x-auto" id="dashboard-tabs">
<button @click="activeView = 'list'" hx-get="{{ url_for('main.dashboard_list') }}" <button hx-get="{{ url_for('main.dashboard_list') }}" hx-target="#dashboard-content"
hx-target="#dashboard-content" :class="{'border-primary-600 text-primary-600': activeView === 'list'}" class="tab-btn px-4 py-2 text-sm font-medium border-b-2 whitespace-nowrap {{ 'border-primary-600 text-primary-600' if active_view == 'list' else 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300' }}">List
class="px-4 py-2 text-sm font-medium border-b-2">List View</button> View</button>
<button @click="activeView = 'weekly'" hx-get="{{ url_for('main.dashboard_weekly') }}" <button hx-get="{{ url_for('main.dashboard_table') }}" hx-target="#dashboard-content"
hx-target="#dashboard-content" :class="{'border-primary-600 text-primary-600': activeView === 'weekly'}" class="tab-btn px-4 py-2 text-sm font-medium border-b-2 whitespace-nowrap {{ 'border-primary-600 text-primary-600' if active_view == 'table' else 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300' }}">Table
class="px-4 py-2 text-sm font-medium border-b-2">Weekly View</button> View</button>
<button @click="activeView = 'monthly'" hx-get="{{ url_for('main.dashboard_monthly') }}" <button hx-get="{{ url_for('main.dashboard_weekly') }}" hx-target="#dashboard-content"
hx-target="#dashboard-content" class="tab-btn px-4 py-2 text-sm font-medium border-b-2 whitespace-nowrap {{ 'border-primary-600 text-primary-600' if active_view == 'weekly' else 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300' }}">Weekly
:class="{'border-primary-600 text-primary-600': activeView === 'monthly'}" View</button>
class="px-4 py-2 text-sm font-medium border-b-2">Monthly View</button> <button hx-get="{{ url_for('main.dashboard_monthly') }}" hx-target="#dashboard-content"
<button @click="activeView = 'graph'" hx-get="{{ url_for('main.dashboard_graph') }}" class="tab-btn px-4 py-2 text-sm font-medium border-b-2 whitespace-nowrap {{ 'border-primary-600 text-primary-600' if active_view == 'monthly' else 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300' }}">Monthly
hx-target="#dashboard-content" :class="{'border-primary-600 text-primary-600': activeView === 'graph'}" View</button>
class="px-4 py-2 text-sm font-medium border-b-2">Graph View</button> <button hx-get="{{ url_for('main.dashboard_graph') }}" hx-target="#dashboard-content"
class="tab-btn px-4 py-2 text-sm font-medium border-b-2 whitespace-nowrap {{ 'border-primary-600 text-primary-600' if active_view == 'graph' else 'border-transparent text-gray-500 hover:text-gray-700 hover:border-gray-300' }}">Graph
View</button>
</div> </div>
<!-- Dashboard Content Target Area for HTMX --> <!-- Dashboard Content Target Area for HTMX -->
<div id="dashboard-content"> <div id="dashboard-content" hx-get="{{ url_for('main.dashboard_list') }}" hx-trigger="load">
{% include 'partials/dashboard_list.html' %} <div class="flex justify-center items-center p-12">
<div class="animate-spin rounded-full h-8 w-8 border-b-2 border-primary-600"></div>
</div>
</div> </div>
</div> </div>
</div> </div>
<script>
// Use event delegation for dashboard interactions to survive DIY Turbo page replacements
document.addEventListener('click', (e) => {
// Filter Form Toggle
const filterBtn = e.target.closest('#filter-btn');
if (filterBtn) {
const filterForm = document.getElementById('filter-form');
const iconClosed = document.getElementById('filter-icon-closed');
const iconOpen = document.getElementById('filter-icon-open');
if (filterForm) {
const isHidden = filterForm.classList.contains('hidden');
if (isHidden) {
filterForm.classList.remove('hidden');
if (iconClosed) iconClosed.classList.add('hidden');
if (iconOpen) iconOpen.classList.remove('hidden');
} else {
filterForm.classList.add('hidden');
if (iconClosed) iconClosed.classList.remove('hidden');
if (iconOpen) iconOpen.classList.add('hidden');
}
}
return;
}
// Tabs
const tabBtn = e.target.closest('.tab-btn');
if (tabBtn) {
const tabBtns = document.querySelectorAll('.tab-btn');
tabBtns.forEach(b => {
b.classList.remove('border-primary-600', 'text-primary-600');
});
tabBtn.classList.add('border-primary-600', 'text-primary-600');
// The click will still bubble up and be caught by the Micro-HTMX logic in _layout.html
return;
}
});
</script>
{% endblock %} {% endblock %}

View File

@@ -1,64 +1,346 @@
<div class="space-y-6"> <style>
<!-- Blood Pressure Graph --> .svg-tooltip-group .svg-tooltip-content {
<div> opacity: 0;
<h3 class="text-sm font-semibold text-gray-600 mb-2">Blood Pressure (mmHg)</h3> visibility: hidden;
<svg viewBox="0 0 600 250" xmlns="http://www.w3.org/2000/svg" class="w-full"> transition: opacity 0.2s ease-in-out;
<!-- Axes --> pointer-events: none;
<line x1="50" y1="200" x2="550" y2="200" stroke="black" stroke-width="1" /> <!-- X-axis --> }
<line x1="50" y1="20" x2="50" y2="200" stroke="black" stroke-width="1" /> <!-- Y-axis -->
<!-- Y-axis Labels (Blood Pressure Values) --> .svg-tooltip-group:hover .svg-tooltip-content {
{% for value in range(50, 201, 50) %} opacity: 1;
<text x="40" y="{{ 200 - (value / 200 * 180) }}" font-size="10" text-anchor="end">{{ value }}</text> visibility: visible;
{% endfor %} }
</style>
<div class="space-y-8">
<!-- Graph Date Filter -->
<div class="bg-white rounded-2xl shadow-sm border border-gray-100 p-4 mb-2">
<form hx-get="{{ url_for('main.dashboard_graph') }}" hx-target="#dashboard-content"
class="flex flex-col sm:flex-row gap-4">
<!-- Start Date -->
<div class="flex-1">
<label for="start_date" class="block text-sm font-medium text-gray-700 mb-1">Start Date</label>
<input type="date" name="start_date" id="start_date" value="{{ start_date or '' }}"
class="w-full p-2.5 border border-gray-300 rounded-xl shadow-sm focus:outline-none focus:ring-2 focus:ring-primary-500 text-gray-700">
</div>
<!-- X-axis Labels (Timestamps) --> <!-- End Date -->
{% for i in range(timestamps|length) %} <div class="flex-1">
<text x="{{ 50 + i * 50 }}" y="215" font-size="10" text-anchor="middle">{{ timestamps[i] }}</text> <label for="end_date" class="block text-sm font-medium text-gray-700 mb-1">End Date</label>
{% endfor %} <input type="date" name="end_date" id="end_date" value="{{ end_date or '' }}"
class="w-full p-2.5 border border-gray-300 rounded-xl shadow-sm focus:outline-none focus:ring-2 focus:ring-primary-500 text-gray-700">
</div>
</form>
</div>
<!-- Blood Pressure Graph Card -->
<div class="bg-white rounded-2xl shadow-lg border border-gray-100 p-6 transition-all hover:shadow-xl">
<div class="flex flex-col md:flex-row md:items-center justify-between mb-6">
<div>
<h3 class="text-xl font-bold text-gray-800">Blood Pressure Trends</h3>
<p class="text-sm text-gray-500 mt-1">Systolic vs Diastolic over time (mmHg)</p>
</div>
<div class="flex space-x-6 text-sm mt-4 md:mt-0 bg-gray-50 px-4 py-2 rounded-full">
<div class="flex items-center"><span
class="w-3 h-3 rounded-full bg-blue-500 mr-2 shadow-sm"></span><span
class="font-medium text-gray-700">Systolic</span></div>
<div class="flex items-center"><span
class="w-3 h-3 rounded-full bg-pink-500 mr-2 shadow-sm"></span><span
class="font-medium text-gray-700">Diastolic</span></div>
</div>
</div>
<!-- Graph Lines --> <div class="w-full overflow-x-auto pb-4">
<!-- Systolic Line --> <svg viewBox="0 0 800 350" class="w-full min-w-[600px] h-auto drop-shadow-sm font-sans"
<polyline fill="none" stroke="blue" stroke-width="2" style="max-height: 350px;">
points="{% for i in range(timestamps|length) %}{{ 50 + i * 50 }},{{ 200 - (systolic[i] / 200 * 180) }} {% endfor %}" /> <defs>
<linearGradient id="sysGrad" x1="0" x2="0" y1="0" y2="1">
<stop offset="0%" stop-color="#3b82f6" stop-opacity="0.3" />
<stop offset="100%" stop-color="#3b82f6" stop-opacity="0.0" />
</linearGradient>
<linearGradient id="diaGrad" x1="0" x2="0" y1="0" y2="1">
<stop offset="0%" stop-color="#ec4899" stop-opacity="0.3" />
<stop offset="100%" stop-color="#ec4899" stop-opacity="0.0" />
</linearGradient>
</defs>
<!-- Diastolic Line --> {% if timestamps %}
<polyline fill="none" stroke="red" stroke-width="2" {% set n = timestamps|length %}
points="{% for i in range(timestamps|length) %}{{ 50 + i * 50 }},{{ 200 - (diastolic[i] / 200 * 180) }} {% endfor %}" /> {% set spacing = 700 / (n - 1) if n > 1 else 0 %}
<!-- Axis Labels --> <!-- Horizontal Grid Lines & Y-Axis Labels -->
<text x="25" y="110" font-size="12" transform="rotate(-90, 25, 110)" text-anchor="middle">Blood Pressure {% for value in range(50, 201, 50) %}
(mmHg)</text> {% set y = 280 - (value / 200 * 250) %}
<text x="300" y="240" font-size="12" text-anchor="middle">Date</text> <line x1="50" y1="{{ y }}" x2="750" y2="{{ y }}" stroke="#e5e7eb" stroke-width="1"
</svg> stroke-dasharray="4 4" />
<text x="40" y="{{ y + 4 }}" font-size="12" fill="#9ca3af" text-anchor="end" font-weight="500">{{ value
}}</text>
{% endfor %}
<!-- X-Axis Base Line -->
<line x1="50" y1="280" x2="750" y2="280" stroke="#d1d5db" stroke-width="1" />
<!-- X-Axis Labels -->
{% set ns = namespace(last_x=-100) %}
{% for i in range(n) %}
{% set x = 50 + time_percentages[i] * 700 if n > 1 else 400 %}
<!-- Optimization: only draw label if it has enough horizontal space from the last drawn label -->
{% set is_last = (i == n - 1) %}
{% if x - ns.last_x > 45 or is_last %}
<!-- If it's the last label but too close to the previous, maybe we draw it anyway but it will overlap. We prevent overlap by aggressively spacing. -->
{% if not is_last or x - ns.last_x > 40 or ns.last_x == -100 %}
<text x="{{ x }}" y="310" font-size="11" fill="#6b7280" text-anchor="middle" font-weight="500"
transform="rotate(-25 {{ x }} 310)">{{
timestamps[i] }}</text>
{% set ns.last_x = x %}
{% endif %}
{% endif %}
{% endfor %}
<!-- Systolic Filled Area -->
<polygon fill="url(#sysGrad)" points="{% if n>1 %}50{% else %}400{% endif %},280
{% for i in range(n) %}
{% set x = 50 + time_percentages[i] * 700 if n > 1 else 400 %}
{% set y = 280 - (systolic[i] / 200 * 250) %}
{{ x }},{{ y }}
{% endfor %}
{% if n>1 %}{{ 50 + (n - 1) * spacing }}{% else %}400{% endif %},280" />
<!-- Systolic Line -->
<polyline fill="none" stroke="#3b82f6" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"
points="{% for i in range(n) %}
{% set x = 50 + time_percentages[i] * 700 if n > 1 else 400 %}
{% set y = 280 - (systolic[i] / 200 * 250) %}
{{ x }},{{ y }}
{% endfor %}" />
<!-- Systolic Points -->
{% for i in range(n) %}
{% set x = 50 + time_percentages[i] * 700 if n > 1 else 400 %}
{% set y = 280 - (systolic[i] / 200 * 250) %}
<circle cx="{{ x }}" cy="{{ y }}" r="5" fill="#ffffff" stroke="#3b82f6" stroke-width="2.5"></circle>
{% endfor %}
<!-- Diastolic Filled Area -->
<polygon fill="url(#diaGrad)" points="{% if n>1 %}50{% else %}400{% endif %},280
{% for i in range(n) %}
{% set x = 50 + time_percentages[i] * 700 if n > 1 else 400 %}
{% set y = 280 - (diastolic[i] / 200 * 250) %}
{{ x }},{{ y }}
{% endfor %}
{% if n>1 %}{{ 50 + (n - 1) * spacing }}{% else %}400{% endif %},280" />
<!-- Diastolic Line -->
<polyline fill="none" stroke="#ec4899" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"
points="{% for i in range(n) %}
{% set x = 50 + time_percentages[i] * 700 if n > 1 else 400 %}
{% set y = 280 - (diastolic[i] / 200 * 250) %}
{{ x }},{{ y }}
{% endfor %}" />
<!-- Diastolic Points -->
{% for i in range(n) %}
{% set x = 50 + time_percentages[i] * 700 if n > 1 else 400 %}
{% set y = 280 - (diastolic[i] / 200 * 250) %}
<circle cx="{{ x }}" cy="{{ y }}" r="5" fill="#ffffff" stroke="#ec4899" stroke-width="2.5"></circle>
{% endfor %}
<!-- Tooltips (Rendered last to stay on top) -->
{% for i in range(n) %}
{% set x = 50 + time_percentages[i] * 700 if n > 1 else 400 %}
{% set ySys = 280 - (systolic[i] / 200 * 250) %}
<g class="svg-tooltip-group" style="cursor: pointer;">
<circle cx="{{ x }}" cy="{{ ySys }}" r="15" fill="transparent" />
<circle cx="{{ x }}" cy="{{ ySys }}" r="7" fill="#ffffff" stroke="#3b82f6" stroke-width="2.5"
class="svg-tooltip-content" />
<g class="svg-tooltip-content">
<rect x="{{ x - 64 }}" y="{{ ySys - 54 }}" width="128" height="40" fill="#1f2937" rx="6" />
<polygon points="{{ x - 6 }},{{ ySys - 14 }} {{ x + 6 }},{{ ySys - 14 }} {{ x }},{{ ySys - 6 }}"
fill="#1f2937" />
<text x="{{ x }}" y="{{ ySys - 36 }}" font-size="11" fill="#f3f4f6" text-anchor="middle"
font-weight="600" class="font-sans">{{ timestamps[i] }}</text>
<text x="{{ x }}" y="{{ ySys - 22 }}" font-size="11" fill="#93c5fd" text-anchor="middle"
font-weight="500" class="font-sans">Systolic: {{ systolic[i] }}</text>
</g>
</g>
{% set yDia = 280 - (diastolic[i] / 200 * 250) %}
<g class="svg-tooltip-group" style="cursor: pointer;">
<circle cx="{{ x }}" cy="{{ yDia }}" r="15" fill="transparent" />
<circle cx="{{ x }}" cy="{{ yDia }}" r="7" fill="#ffffff" stroke="#ec4899" stroke-width="2.5"
class="svg-tooltip-content" />
<g class="svg-tooltip-content">
<rect x="{{ x - 64 }}" y="{{ yDia - 54 }}" width="128" height="40" fill="#1f2937" rx="6" />
<polygon points="{{ x - 6 }},{{ yDia - 14 }} {{ x + 6 }},{{ yDia - 14 }} {{ x }},{{ yDia - 6 }}"
fill="#1f2937" />
<text x="{{ x }}" y="{{ yDia - 36 }}" font-size="11" fill="#f3f4f6" text-anchor="middle"
font-weight="600" class="font-sans">{{ timestamps[i] }}</text>
<text x="{{ x }}" y="{{ yDia - 22 }}" font-size="11" fill="#f472b6" text-anchor="middle"
font-weight="500" class="font-sans">Diastolic: {{ diastolic[i] }}</text>
</g>
</g>
{% endfor %}
<!-- Average Lines -->
{% set ySysAvg = 280 - (sys_avg / 200 * 250) %}
<g class="svg-tooltip-group" style="cursor: default;">
<line x1="50" y1="{{ ySysAvg }}" x2="750" y2="{{ ySysAvg }}" stroke="#3b82f6" stroke-width="2"
stroke-dasharray="8 6" opacity="0.8" />
<line x1="50" y1="{{ ySysAvg }}" x2="750" y2="{{ ySysAvg }}" stroke="transparent"
stroke-width="15" /> <!-- Invisible hover anchor -->
<g class="svg-tooltip-content">
<rect x="336" y="{{ ySysAvg - 34 }}" width="128" height="26" fill="#1f2937" rx="6" />
<polygon points="394,{{ ySysAvg - 8 }} 406,{{ ySysAvg - 8 }} 400,{{ ySysAvg - 2 }}"
fill="#1f2937" />
<text x="400" y="{{ ySysAvg - 17 }}" font-size="11" fill="#93c5fd" text-anchor="middle"
font-weight="600" class="font-sans">Avg Systolic: {{ sys_avg }}</text>
</g>
</g>
{% set yDiaAvg = 280 - (dia_avg / 200 * 250) %}
<g class="svg-tooltip-group" style="cursor: default;">
<line x1="50" y1="{{ yDiaAvg }}" x2="750" y2="{{ yDiaAvg }}" stroke="#ec4899" stroke-width="2"
stroke-dasharray="8 6" opacity="0.8" />
<line x1="50" y1="{{ yDiaAvg }}" x2="750" y2="{{ yDiaAvg }}" stroke="transparent"
stroke-width="15" /> <!-- Invisible hover anchor -->
<g class="svg-tooltip-content">
<rect x="336" y="{{ yDiaAvg - 34 }}" width="128" height="26" fill="#1f2937" rx="6" />
<polygon points="394,{{ yDiaAvg - 8 }} 406,{{ yDiaAvg - 8 }} 400,{{ yDiaAvg - 2 }}"
fill="#1f2937" />
<text x="400" y="{{ yDiaAvg - 17 }}" font-size="11" fill="#f472b6" text-anchor="middle"
font-weight="600" class="font-sans">Avg Diastolic: {{ dia_avg }}</text>
</g>
</g>
{% else %}
<rect x="50" y="30" width="700" height="250" fill="#f9fafb" rx="10" />
<text x="400" y="155" font-size="16" fill="#9ca3af" text-anchor="middle" font-weight="500">No data
available for the selected period.</text>
{% endif %}
</svg>
</div>
</div> </div>
<!-- Heart Rate Graph --> <!-- Heart Rate Graph Card -->
<div> <div class="bg-white rounded-2xl shadow-lg border border-gray-100 p-6 transition-all hover:shadow-xl">
<h3 class="text-sm font-semibold text-gray-600 mb-2">Heart Rate (bpm)</h3> <div class="flex flex-col md:flex-row md:items-center justify-between mb-6">
<svg viewBox="0 0 600 250" xmlns="http://www.w3.org/2000/svg" class="w-full"> <div>
<!-- Axes --> <h3 class="text-xl font-bold text-gray-800">Heart Rate</h3>
<line x1="50" y1="200" x2="550" y2="200" stroke="black" stroke-width="1" /> <!-- X-axis --> <p class="text-sm text-gray-500 mt-1">Beats per minute over time (bpm)</p>
<line x1="50" y1="20" x2="50" y2="200" stroke="black" stroke-width="1" /> <!-- Y-axis --> </div>
<div class="flex space-x-6 text-sm mt-4 md:mt-0 bg-gray-50 px-4 py-2 rounded-full">
<div class="flex items-center"><span
class="w-3 h-3 rounded-full bg-emerald-500 mr-2 shadow-sm"></span><span
class="font-medium text-gray-700">Heart Rate</span></div>
</div>
</div>
<!-- Y-axis Labels (Heart Rate Values) --> <div class="w-full overflow-x-auto pb-4">
{% for value in range(50, 201, 50) %} <svg viewBox="0 0 800 350" class="w-full min-w-[600px] h-auto drop-shadow-sm font-sans"
<text x="40" y="{{ 200 - (value / 200 * 180) }}" font-size="10" text-anchor="end">{{ value }}</text> style="max-height: 350px;">
{% endfor %} <defs>
<linearGradient id="hrGrad" x1="0" x2="0" y1="0" y2="1">
<stop offset="0%" stop-color="#10b981" stop-opacity="0.3" />
<stop offset="100%" stop-color="#10b981" stop-opacity="0.0" />
</linearGradient>
</defs>
<!-- X-axis Labels (Timestamps) --> {% if timestamps %}
{% for i in range(timestamps|length) %} {% set n = timestamps|length %}
<text x="{{ 50 + i * 50 }}" y="215" font-size="10" text-anchor="middle">{{ timestamps[i] }}</text> {% set spacing = 700 / (n - 1) if n > 1 else 0 %}
{% endfor %}
<!-- Heart Rate Line --> <!-- Horizontal Grid Lines & Y-Axis Labels -->
<polyline fill="none" stroke="green" stroke-width="2" {% for value in range(50, 201, 50) %}
points="{% for i in range(timestamps|length) %}{{ 50 + i * 50 }},{{ 200 - (heart_rate[i] / 200 * 180) }} {% endfor %}" /> {% set y = 280 - (value / 200 * 250) %}
<line x1="50" y1="{{ y }}" x2="750" y2="{{ y }}" stroke="#e5e7eb" stroke-width="1"
stroke-dasharray="4 4" />
<text x="40" y="{{ y + 4 }}" font-size="12" fill="#9ca3af" text-anchor="end" font-weight="500">{{ value
}}</text>
{% endfor %}
<!-- Axis Labels --> <!-- X-Axis Base Line -->
<text x="25" y="110" font-size="12" transform="rotate(-90, 25, 110)" text-anchor="middle">Heart Rate <line x1="50" y1="280" x2="750" y2="280" stroke="#d1d5db" stroke-width="1" />
(bpm)</text>
<text x="300" y="240" font-size="12" text-anchor="middle">Date</text> <!-- X-Axis Labels -->
</svg> {% set ns = namespace(last_x=-100) %}
{% for i in range(n) %}
{% set x = 50 + time_percentages[i] * 700 if n > 1 else 400 %}
{% set is_last = (i == n - 1) %}
{% if x - ns.last_x > 45 or is_last %}
{% if not is_last or x - ns.last_x > 40 or ns.last_x == -100 %}
<text x="{{ x }}" y="310" font-size="11" fill="#6b7280" text-anchor="middle" font-weight="500"
transform="rotate(-25 {{ x }} 310)">{{
timestamps[i] }}</text>
{% set ns.last_x = x %}
{% endif %}
{% endif %}
{% endfor %}
<!-- Heart Rate Filled Area -->
<polygon fill="url(#hrGrad)" points="{% if n>1 %}50{% else %}400{% endif %},280
{% for i in range(n) %}
{% set x = 50 + time_percentages[i] * 700 if n > 1 else 400 %}
{% set y = 280 - (heart_rate[i] / 200 * 250) %}
{{ x }},{{ y }}
{% endfor %}
{% if n>1 %}{{ 50 + (n - 1) * spacing }}{% else %}400{% endif %},280" />
<!-- Heart Rate Line -->
<polyline fill="none" stroke="#10b981" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"
points="{% for i in range(n) %}
{% set x = 50 + time_percentages[i] * 700 if n > 1 else 400 %}
{% set y = 280 - (heart_rate[i] / 200 * 250) %}
{{ x }},{{ y }}
{% endfor %}" />
<!-- Heart Rate Points -->
{% for i in range(n) %}
{% set x = 50 + time_percentages[i] * 700 if n > 1 else 400 %}
{% set y = 280 - (heart_rate[i] / 200 * 250) %}
<circle cx="{{ x }}" cy="{{ y }}" r="5" fill="#ffffff" stroke="#10b981" stroke-width="2.5"></circle>
{% endfor %}
<!-- Tooltips (Rendered last to stay on top) -->
{% for i in range(n) %}
{% set x = 50 + time_percentages[i] * 700 if n > 1 else 400 %}
{% set yHR = 280 - (heart_rate[i] / 200 * 250) %}
<g class="svg-tooltip-group" style="cursor: pointer;">
<circle cx="{{ x }}" cy="{{ yHR }}" r="15" fill="transparent" />
<circle cx="{{ x }}" cy="{{ yHR }}" r="7" fill="#ffffff" stroke="#10b981" stroke-width="2.5"
class="svg-tooltip-content" />
<g class="svg-tooltip-content">
<rect x="{{ x - 64 }}" y="{{ yHR - 54 }}" width="128" height="40" fill="#1f2937" rx="6" />
<polygon points="{{ x - 6 }},{{ yHR - 14 }} {{ x + 6 }},{{ yHR - 14 }} {{ x }},{{ yHR - 6 }}"
fill="#1f2937" />
<text x="{{ x }}" y="{{ yHR - 36 }}" font-size="11" fill="#f3f4f6" text-anchor="middle"
font-weight="600" class="font-sans">{{ timestamps[i] }}</text>
<text x="{{ x }}" y="{{ yHR - 22 }}" font-size="11" fill="#34d399" text-anchor="middle"
font-weight="500" class="font-sans">Heart Rate: {{ heart_rate[i] }}</text>
</g>
</g>
{% endfor %}
<!-- Average Line -->
{% set yHrAvg = 280 - (hr_avg / 200 * 250) %}
<g class="svg-tooltip-group" style="cursor: default;">
<line x1="50" y1="{{ yHrAvg }}" x2="750" y2="{{ yHrAvg }}" stroke="#10b981" stroke-width="2"
stroke-dasharray="8 6" opacity="0.8" />
<line x1="50" y1="{{ yHrAvg }}" x2="750" y2="{{ yHrAvg }}" stroke="transparent" stroke-width="15" />
<!-- Invisible hover anchor -->
<g class="svg-tooltip-content">
<rect x="336" y="{{ yHrAvg - 34 }}" width="128" height="26" fill="#1f2937" rx="6" />
<polygon points="394,{{ yHrAvg - 8 }} 406,{{ yHrAvg - 8 }} 400,{{ yHrAvg - 2 }}"
fill="#1f2937" />
<text x="400" y="{{ yHrAvg - 17 }}" font-size="11" fill="#34d399" text-anchor="middle"
font-weight="600" class="font-sans">Avg Heart Rate: {{ hr_avg }}</text>
</g>
</g>
{% else %}
<rect x="50" y="30" width="700" height="250" fill="#f9fafb" rx="10" />
<text x="400" y="155" font-size="16" fill="#9ca3af" text-anchor="middle" font-weight="500">No data
available for the selected period.</text>
{% endif %}
</svg>
</div>
</div> </div>
</div> </div>

View File

@@ -1,3 +1,10 @@
<svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
<defs>
<path id="icon-clock" stroke-linecap="round" stroke-linejoin="round"
d="M12 8v4l3 3m9-3a9 9 0 1 1-18 0 9 9 0 0 1 18 0z" />
<path id="icon-chevron" stroke-linecap="round" stroke-linejoin="round" d="M8.25 4.5l7.5 7.5-7.5 7.5" />
</defs>
</svg>
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3"> <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
{% for reading in readings %} {% for reading in readings %}
<a href="{{ url_for('reading.edit_reading', reading_id=reading.id) }}" <a href="{{ url_for('reading.edit_reading', reading_id=reading.id) }}"
@@ -8,8 +15,7 @@
<div class="flex items-center text-gray-400 text-xs mb-1"> <div class="flex items-center text-gray-400 text-xs mb-1">
<svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5 mr-1" fill="none" viewBox="0 0 24 24" <svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5 mr-1" fill="none" viewBox="0 0 24 24"
stroke="currentColor" stroke-width="2"> stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" <use href="#icon-clock"></use>
d="M12 8v4l3 3m9-3a9 9 0 1 1-18 0 9 9 0 0 1 18 0z" />
</svg> </svg>
<span title="{{ reading.local_timestamp.strftime('%d %b %Y, %I:%M %p') }}"> <span title="{{ reading.local_timestamp.strftime('%d %b %Y, %I:%M %p') }}">
{{ reading.relative_timestamp }} {{ reading.relative_timestamp }}
@@ -34,7 +40,7 @@
<div class="text-gray-300"> <div class="text-gray-300">
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2" <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="2"
stroke="currentColor" class="h-4 w-4"> stroke="currentColor" class="h-4 w-4">
<path stroke-linecap="round" stroke-linejoin="round" d="M8.25 4.5l7.5 7.5-7.5 7.5" /> <use href="#icon-chevron"></use>
</svg> </svg>
</div> </div>
</div> </div>

Before

Width:  |  Height:  |  Size: 3.5 KiB

After

Width:  |  Height:  |  Size: 3.7 KiB

View File

@@ -0,0 +1,172 @@
<div class="space-y-6">
<!-- Table Date Filter -->
<div class="bg-white rounded-2xl shadow-sm border border-gray-100 p-4 mb-2">
<form hx-get="{{ url_for('main.dashboard_table') }}" hx-target="#dashboard-content"
class="flex flex-col sm:flex-row gap-4">
<!-- Start Date -->
<div class="flex-1">
<label for="start_date" class="block text-sm font-medium text-gray-700 mb-1">Start Date</label>
<input type="date" name="start_date" id="start_date" value="{{ start_date or '' }}"
class="w-full p-2.5 border border-gray-300 rounded-xl shadow-sm focus:outline-none focus:ring-2 focus:ring-primary-500 text-gray-700">
</div>
<!-- End Date -->
<div class="flex-1">
<label for="end_date" class="block text-sm font-medium text-gray-700 mb-1">End Date</label>
<input type="date" name="end_date" id="end_date" value="{{ end_date or '' }}"
class="w-full p-2.5 border border-gray-300 rounded-xl shadow-sm focus:outline-none focus:ring-2 focus:ring-primary-500 text-gray-700">
</div>
</form>
</div>
<!-- Data Container -->
<div class="bg-transparent md:bg-white md:rounded-2xl md:shadow-sm md:border md:border-gray-100 overflow-hidden">
<!-- Mobile Card View (Hidden on medium screens and up) -->
<div class="md:hidden space-y-4">
{% for reading in readings %}
<div class="bg-white p-4 rounded-xl shadow-sm border border-gray-100 flex flex-col gap-3">
<div class="flex justify-between items-center border-b border-gray-50 pb-2">
<div class="flex items-center gap-2">
<svg class="w-4 h-4 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
</svg>
<span class="text-sm font-bold text-gray-800">{{ reading.local_timestamp.strftime('%Y-%m-%d')
}}</span>
</div>
<span class="text-sm font-medium text-gray-500">{{ reading.local_timestamp.strftime('%I:%M %p')
}}</span>
</div>
<div class="flex justify-between items-center">
<span class="text-xs font-semibold text-gray-500 uppercase tracking-wider">Blood Pressure</span>
<div class="flex items-baseline gap-1">
<span
class="font-bold text-lg {{ 'text-red-500' if reading.systolic >= 130 else 'text-gray-900' }}">{{
reading.systolic }}</span>
<span class="font-medium text-gray-400">/</span>
<span
class="font-bold text-lg {{ 'text-red-500' if reading.diastolic >= 80 else 'text-gray-900' }}">{{
reading.diastolic }}</span>
<span class="text-xs text-gray-500 font-medium ml-1">mmHg</span>
</div>
</div>
<div class="flex justify-between items-center">
<span class="text-xs font-semibold text-gray-500 uppercase tracking-wider">Heart Rate</span>
<div class="flex items-baseline">
<span class="font-bold text-lg text-gray-900">{{ reading.heart_rate }}</span>
<span class="text-xs text-gray-500 font-medium ml-1">bpm</span>
</div>
</div>
<div class="flex justify-end pt-3 mt-1 border-t border-gray-50">
<a href="{{ url_for('reading.edit_reading', reading_id=reading.id) }}"
class="inline-flex items-center gap-1 text-primary-600 hover:text-primary-800 text-sm font-bold transition-colors">
Edit
<svg class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 5l7 7-7 7" />
</svg>
</a>
</div>
</div>
{% else %}
<div
class="bg-white p-8 text-center rounded-xl shadow-sm border border-gray-100 flex flex-col items-center gap-3">
<svg class="w-12 h-12 text-gray-300" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2"
d="M20 13V6a2 2 0 00-2-2H6a2 2 0 00-2 2v7m16 0v5a2 2 0 01-2 2H6a2 2 0 01-2-2v-5m16 0h-2.586a1 1 0 00-.707.293l-2.414 2.414a1 1 0 01-.707.293h-3.172a1 1 0 01-.707-.293l-2.414-2.414A1 1 0 006.586 13H4" />
</svg>
<span class="text-sm font-medium text-gray-500">No readings found for this date range.</span>
</div>
{% endfor %}
</div>
<!-- Desktop Table View (Hidden on small screens) -->
<div class="hidden md:block overflow-x-auto">
<table class="min-w-full divide-y divide-gray-200">
<thead class="bg-gray-50">
<tr>
<th scope="col"
class="px-6 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">
Date</th>
<th scope="col"
class="px-6 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">
Time</th>
<th scope="col"
class="px-6 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">
Systolic</th>
<th scope="col"
class="px-6 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">
Diastolic</th>
<th scope="col"
class="px-6 py-3 text-left text-xs font-semibold text-gray-500 uppercase tracking-wider">
Heart Rate</th>
<th scope="col"
class="px-6 py-3 text-right text-xs font-semibold text-gray-500 uppercase tracking-wider">
Actions</th>
</tr>
</thead>
<tbody class="bg-white divide-y divide-gray-200">
{% for reading in readings %}
<tr class="hover:bg-gray-50 transition-colors">
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{
reading.local_timestamp.strftime('%Y-%m-%d') }}</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{{
reading.local_timestamp.strftime('%I:%M %p') }}</td>
<td
class="px-6 py-4 whitespace-nowrap text-sm font-semibold {{ 'text-red-500' if reading.systolic >= 130 else 'text-gray-900' }}">
{{ reading.systolic }}</td>
<td
class="px-6 py-4 whitespace-nowrap text-sm font-semibold {{ 'text-red-500' if reading.diastolic >= 80 else 'text-gray-900' }}">
{{ reading.diastolic }}</td>
<td class="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{{ reading.heart_rate }} bpm</td>
<td class="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
<a href="{{ url_for('reading.edit_reading', reading_id=reading.id) }}"
class="text-primary-600 hover:text-primary-900">Edit</a>
</td>
</tr>
{% else %}
<tr>
<td colspan="6" class="px-6 py-12 text-center text-sm text-gray-500">
No readings found for this date range.
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
<!-- Pagination Controls -->
{% if pagination.pages > 1 %}
<div class="flex justify-center items-center gap-2 mt-6">
{% if pagination.has_prev %}
<button
hx-get="{{ url_for('main.dashboard_table', page=pagination.prev_num, start_date=start_date, end_date=end_date) }}"
hx-target="#dashboard-content" class="px-3 py-1 rounded bg-gray-200 hover:bg-gray-300 text-sm">&laquo;
Prev</button>
{% endif %}
{% for page_num in pagination.iter_pages(left_edge=1, right_edge=1, left_current=2, right_current=2) %}
{% if page_num %}
<button hx-get="{{ url_for('main.dashboard_table', page=page_num, start_date=start_date, end_date=end_date) }}"
hx-target="#dashboard-content"
class="px-3 py-1 rounded text-sm {% if page_num == pagination.page %}bg-primary-600 text-white{% else %}bg-gray-200 hover:bg-gray-300{% endif %}">
{{ page_num }}
</button>
{% else %}
<span class="text-gray-400"></span>
{% endif %}
{% endfor %}
{% if pagination.has_next %}
<button
hx-get="{{ url_for('main.dashboard_table', page=pagination.next_num, start_date=start_date, end_date=end_date) }}"
hx-target="#dashboard-content" class="px-3 py-1 rounded bg-gray-200 hover:bg-gray-300 text-sm">Next
&raquo;</button>
{% endif %}
</div>
{% endif %}
</div>

View File

@@ -15,13 +15,8 @@
<div class="bg-white p-6 rounded-lg shadow-md mb-6"> <div class="bg-white p-6 rounded-lg shadow-md mb-6">
<div class="flex items-center justify-center mb-4"> <div class="flex items-center justify-center mb-4">
{% if profile.profile_pic %}
<img src="{{ url_for('user.profile_image', user_id=current_user.id) }}" alt="Profile Picture" <img src="{{ url_for('user.profile_image', user_id=current_user.id) }}" alt="Profile Picture"
class="w-44 h-44 rounded-full border"> class="w-32 h-32 rounded-full border object-cover shadow">
{% else %}
<img src="{{ url_for('static', filename='default.png') }}" alt="Default Profile Picture"
class="w-44 h-44 rounded-full border">
{% endif %}
</div> </div>

View File

@@ -0,0 +1,32 @@
"""Add user id index on profile
Revision ID: bd83e779fcc1
Revises: 8cfe56a1e597
Create Date: 2026-03-10 19:33:12.629077
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'bd83e779fcc1'
down_revision = '8cfe56a1e597'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('profile', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_profile_user_id'), ['user_id'], unique=False)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('profile', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_profile_user_id'))
# ### end Alembic commands ###

77
package-lock.json generated
View File

@@ -8,10 +8,14 @@
"name": "bloodpressure", "name": "bloodpressure",
"version": "1.0.0", "version": "1.0.0",
"license": "ISC", "license": "ISC",
"dependencies": {
"tailwindcss": "^3.0.0"
},
"devDependencies": { "devDependencies": {
"autoprefixer": "^10.4.20", "autoprefixer": "^10.4.20",
"postcss": "^8.4.49", "postcss": "^8.4.49",
"tailwindcss": "^3.4.17" "tailwindcss": "^3.4.17",
"terser": "^5.46.0"
} }
}, },
"node_modules/@alloc/quick-lru": { "node_modules/@alloc/quick-lru": {
@@ -75,6 +79,16 @@
"node": ">=6.0.0" "node": ">=6.0.0"
} }
}, },
"node_modules/@jridgewell/source-map": {
"version": "0.3.11",
"resolved": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.11.tgz",
"integrity": "sha512-ZMp1V8ZFcPG5dIWnQLr3NSI1MiCU7UETdS/A0G8V/XWHvJv3ZsFqutJn1Y5RPmAPX6F3BiE397OqveU/9NCuIA==",
"dev": true,
"dependencies": {
"@jridgewell/gen-mapping": "^0.3.5",
"@jridgewell/trace-mapping": "^0.3.25"
}
},
"node_modules/@jridgewell/sourcemap-codec": { "node_modules/@jridgewell/sourcemap-codec": {
"version": "1.5.0", "version": "1.5.0",
"resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.0.tgz", "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.0.tgz",
@@ -136,6 +150,18 @@
"node": ">=14" "node": ">=14"
} }
}, },
"node_modules/acorn": {
"version": "8.16.0",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.16.0.tgz",
"integrity": "sha512-UVJyE9MttOsBQIDKw1skb9nAwQuR5wuGD3+82K6JgJlm/Y+KI92oNsMNGZCYdDsVtRHSak0pcV5Dno5+4jh9sw==",
"dev": true,
"bin": {
"acorn": "bin/acorn"
},
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/ansi-regex": { "node_modules/ansi-regex": {
"version": "6.1.0", "version": "6.1.0",
"resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.1.0.tgz", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.1.0.tgz",
@@ -293,6 +319,12 @@
"node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
} }
}, },
"node_modules/buffer-from": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
"integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",
"dev": true
},
"node_modules/camelcase-css": { "node_modules/camelcase-css": {
"version": "2.0.1", "version": "2.0.1",
"resolved": "https://registry.npmjs.org/camelcase-css/-/camelcase-css-2.0.1.tgz", "resolved": "https://registry.npmjs.org/camelcase-css/-/camelcase-css-2.0.1.tgz",
@@ -1175,6 +1207,15 @@
"url": "https://github.com/sponsors/isaacs" "url": "https://github.com/sponsors/isaacs"
} }
}, },
"node_modules/source-map": {
"version": "0.6.1",
"resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz",
"integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==",
"dev": true,
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/source-map-js": { "node_modules/source-map-js": {
"version": "1.2.1", "version": "1.2.1",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
@@ -1184,6 +1225,16 @@
"node": ">=0.10.0" "node": ">=0.10.0"
} }
}, },
"node_modules/source-map-support": {
"version": "0.5.21",
"resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz",
"integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==",
"dev": true,
"dependencies": {
"buffer-from": "^1.0.0",
"source-map": "^0.6.0"
}
},
"node_modules/string-width": { "node_modules/string-width": {
"version": "5.1.2", "version": "5.1.2",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz",
@@ -1351,6 +1402,30 @@
"node": ">=14.0.0" "node": ">=14.0.0"
} }
}, },
"node_modules/terser": {
"version": "5.46.0",
"resolved": "https://registry.npmjs.org/terser/-/terser-5.46.0.tgz",
"integrity": "sha512-jTwoImyr/QbOWFFso3YoU3ik0jBBDJ6JTOQiy/J2YxVJdZCc+5u7skhNwiOR3FQIygFqVUPHl7qbbxtjW2K3Qg==",
"dev": true,
"dependencies": {
"@jridgewell/source-map": "^0.3.3",
"acorn": "^8.15.0",
"commander": "^2.20.0",
"source-map-support": "~0.5.20"
},
"bin": {
"terser": "bin/terser"
},
"engines": {
"node": ">=10"
}
},
"node_modules/terser/node_modules/commander": {
"version": "2.20.3",
"resolved": "https://registry.npmjs.org/commander/-/commander-2.20.3.tgz",
"integrity": "sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ==",
"dev": true
},
"node_modules/thenify": { "node_modules/thenify": {
"version": "3.3.1", "version": "3.3.1",
"resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz", "resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz",

View File

@@ -4,8 +4,8 @@
"description": "", "description": "",
"main": "index.js", "main": "index.js",
"scripts": { "scripts": {
"build": "npx tailwindcss -o ./app/static/css/tailwind.css --minify", "build": "npx tailwindcss -o ./app/static/css/tailwind.css --minify && npx terser ./app/static/js/diy-turbo.js -o ./app/static/js/diy-turbo.min.js -c -m",
"serve": "npx tailwindcss -o ./app/static/css/tailwind.css --watch" "serve": "npx tailwindcss -o ./app/static/css/tailwind.css --minify --watch"
}, },
"author": "", "author": "",
"license": "ISC", "license": "ISC",
@@ -15,6 +15,7 @@
"devDependencies": { "devDependencies": {
"autoprefixer": "^10.4.20", "autoprefixer": "^10.4.20",
"postcss": "^8.4.49", "postcss": "^8.4.49",
"tailwindcss": "^3.4.17" "tailwindcss": "^3.4.17",
"terser": "^5.46.0"
} }
} }

View File

@@ -8,6 +8,7 @@ email-validator==2.2.0
exceptiongroup==1.2.2 exceptiongroup==1.2.2
flask==3.1.0 flask==3.1.0
Flask-Bcrypt==1.0.1 Flask-Bcrypt==1.0.1
Flask-Compress==1.14
Flask-Login==0.6.3 Flask-Login==0.6.3
Flask-Migrate==4.0.7 Flask-Migrate==4.0.7
flask-sqlalchemy==3.1.1 flask-sqlalchemy==3.1.1
@@ -36,3 +37,5 @@ typing-extensions==4.12.2
werkzeug==3.1.3 werkzeug==3.1.3
wtforms==3.2.1 wtforms==3.2.1
zipp==3.21.0 zipp==3.21.0
Flask-Minify==0.43
Brotli==1.2.0

View File

@@ -3,9 +3,6 @@ module.exports = {
content: ["./app/templates/**/*.html"], content: ["./app/templates/**/*.html"],
theme: { theme: {
extend: { extend: {
fontFamily: {
sans: ['Inter', 'sans-serif'],
},
colors: { colors: {
primary: { primary: {
50: '#f0fdfa', 50: '#f0fdfa',

View File

@@ -7,13 +7,19 @@ project_root = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
sys.path.insert(0, project_root) sys.path.insert(0, project_root)
from app.models import Reading from app.models import Reading
from app.routes.main import calculate_progress_badges from app.routes.main import _compute_badges
from pytz import utc
def calculate_progress_badges_test_helper(readings, test_now=None):
total = len(readings)
timestamps = [(r.timestamp,) for r in sorted(readings, key=lambda x: x.timestamp, reverse=True)]
now_date = test_now.date() if test_now else datetime.utcnow().date()
return _compute_badges(total, timestamps, utc, now_local=now_date)
def test_no_readings(): def test_no_readings():
readings = [] readings = []
badges = calculate_progress_badges(readings) badges = calculate_progress_badges_test_helper(readings)
assert badges == [] assert badges == []
@@ -22,7 +28,7 @@ def test_daily_streak():
readings = [ readings = [
Reading(timestamp=now - timedelta(days=i)) for i in range(3) Reading(timestamp=now - timedelta(days=i)) for i in range(3)
] # 3-day streak ] # 3-day streak
badges = calculate_progress_badges(readings) badges = calculate_progress_badges_test_helper(readings, test_now=now)
assert "Current Streak: 3 Days" in badges assert "Current Streak: 3 Days" in badges
@@ -31,7 +37,7 @@ def test_weekly_streak():
readings = [ readings = [
Reading(timestamp=now - timedelta(days=i)) for i in range(7) Reading(timestamp=now - timedelta(days=i)) for i in range(7)
] # 7-day streak ] # 7-day streak
badges = calculate_progress_badges(readings) badges = calculate_progress_badges_test_helper(readings, test_now=now)
assert "Logged Every Day for a Week" in badges assert "Logged Every Day for a Week" in badges
@@ -40,7 +46,7 @@ def test_morning_riser():
readings = [ readings = [
Reading(timestamp=now - timedelta(days=i)) for i in range(7) Reading(timestamp=now - timedelta(days=i)) for i in range(7)
] ]
badges = calculate_progress_badges(readings) badges = calculate_progress_badges_test_helper(readings, test_now=now)
assert "Morning Riser: Logged Readings Every Morning for a Week" in badges assert "Morning Riser: Logged Readings Every Morning for a Week" in badges
@@ -49,7 +55,7 @@ def test_night_owl():
readings = [ readings = [
Reading(timestamp=now - timedelta(days=i)) for i in range(7) Reading(timestamp=now - timedelta(days=i)) for i in range(7)
] ]
badges = calculate_progress_badges(readings) badges = calculate_progress_badges_test_helper(readings, test_now=now)
assert "Night Owl: Logged Readings Every Night for a Week" in badges assert "Night Owl: Logged Readings Every Night for a Week" in badges
@@ -57,7 +63,7 @@ def test_milestones():
readings = [ readings = [
Reading(timestamp=datetime.utcnow()) for _ in range(50) Reading(timestamp=datetime.utcnow()) for _ in range(50)
] # 50 readings ] # 50 readings
badges = calculate_progress_badges(readings) badges = calculate_progress_badges_test_helper(readings)
assert "50 Readings Logged" in badges assert "50 Readings Logged" in badges
assert "100 Readings Logged" not in badges # Ensure only the highest milestone assert "100 Readings Logged" not in badges # Ensure only the highest milestone
@@ -67,5 +73,5 @@ def test_no_streak_with_gaps():
readings = [ readings = [
Reading(timestamp=now - timedelta(days=i * 2)) for i in range(3) Reading(timestamp=now - timedelta(days=i * 2)) for i in range(3)
] # Gaps in dates ] # Gaps in dates
badges = calculate_progress_badges(readings) badges = calculate_progress_badges_test_helper(readings, test_now=now)
assert "Current Streak" not in badges assert "Current Streak" not in badges