Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added thematic toggle and preferences page #51

Open
wants to merge 18 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
18 commits
Select commit Hold shift + click to select a range
251c3a5
Added model for preferences, tagged to to user mode, added view to fe…
Icyviolet23 Nov 29, 2023
bda516b
added toggle
kc12341 Dec 6, 2023
56baa4c
added click functionality to toggle, switching dark and light mode
kc12341 Dec 6, 2023
784d1ca
added dark/light mode toggle javascript functionality found in bootst…
kc12341 Dec 6, 2023
7327257
added dropdown with just text, but not integrated with javascript tog…
kc12341 Dec 6, 2023
339e71c
added active mode status label on the dropdown, modified JS to accoun…
kc12341 Dec 6, 2023
69bd847
integrated Kyle's changes by toggling light and dark mode based on us…
Icyviolet23 Dec 7, 2023
56d1491
replaced bootstrap implementation with self implementation for more f…
kc12341 Dec 8, 2023
fc2c5b8
removed auto from dropdown since it was not necessary
kc12341 Dec 8, 2023
3b8d801
saves theme to local storage and reduced code redundancy in toggleThe…
kc12341 Dec 8, 2023
8a90eb2
removed console logging statements
kc12341 Dec 8, 2023
50d55af
Setting color mode directly without JS
kc12341 Dec 8, 2023
c9ef6a2
Removing script from base.html
kc12341 Dec 8, 2023
3ad8573
accepted suggestions to remove script from base.html
kc12341 Dec 8, 2023
f4140e9
added suggested changes to remove script from base.html from code rep…
kc12341 Dec 8, 2023
003d993
Enumeration changes for language and color mode changes
kc12341 Dec 8, 2023
66c2035
new tests for added toggle functionality
kc12341 Dec 8, 2023
122e4fb
Merge branch 'theme-toggle' of https://github.com/adrienneli104/careg…
kc12341 Dec 8, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions accounts/migrations/0003_user_preferences.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Generated by Django 4.2.7 on 2023-11-29 02:51

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

dependencies = [
("preferences", "__first__"),
("accounts", "0002_alter_user_table"),
]

operations = [
migrations.AddField(
model_name="user",
name="preferences",
field=models.OneToOneField(
blank=True,
null=True,
on_delete=django.db.models.deletion.CASCADE,
to="preferences.preferences",
),
),
]
8 changes: 7 additions & 1 deletion accounts/models.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from django.contrib.auth.models import AbstractUser
from django.utils.translation import gettext_lazy as _

from django.db import models
from preferences.models import Preferences

class User(AbstractUser):
class Meta:
Expand All @@ -10,3 +11,8 @@ class Meta:

def __str__(self):
return self.username

#store user preferences in a one to one mapping
preferences = models.OneToOneField(Preferences, on_delete=models.CASCADE, blank=True, null=True)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let’s define the recon the Preferences model rather than the user. Then, use a ‘reverse_name=“preferences”’ on the ‘user’ OneToOne field attached to the Preferences model. That way, we assign the user to the Preferences instance directly in view.py.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
preferences = models.OneToOneField(Preferences, on_delete=models.CASCADE, blank=True, null=True)



1 change: 1 addition & 0 deletions core/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
"homes",
"residents",
"work",
"preferences"
]

CRISPY_ALLOWED_TEMPLATE_PACKS = "bootstrap5"
Expand Down
4 changes: 4 additions & 0 deletions core/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,5 +47,9 @@
"work/",
include("work.urls"),
),
path(
"preferences/",
include("preferences.urls"),
),
path("", TemplateView.as_view(template_name="home.html"), name="home"),
]
2 changes: 1 addition & 1 deletion manage.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/usr/bin/env python
#!/usr/bin/env python3
"""Django's command-line utility for administrative tasks."""
import os
import sys
Expand Down
14 changes: 14 additions & 0 deletions preferences/forms.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from django import forms
from django.forms import ModelForm
from preferences.models import Preferences

class PreferencesForm (ModelForm):
class Meta:
model = Preferences
fields = ('Language', 'Mode')
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

These fields should match the model fields

Suggested change
fields = ('Language', 'Mode')
fields = ('language', 'color_mode')

widgets = {
'Language': forms.Select(attrs={'class': 'form-control'}),
'Mode': forms.Select(attrs={'class': 'form-control'}),
}
labels = {'Language': 'Preferred Language',
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remember i18n tag for these labels using gettext. E.g. _("Preferred Language")

'Mode': 'Preferred Mode'}
17 changes: 17 additions & 0 deletions preferences/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
from django.db import models

from django.utils.translation import gettext_lazy as _
from django.conf import settings

# for user preferences
class Preferences (models.Model):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I believe adding a ‘user = models.OneToOne(…)’ field on the ‘Preferences’ model will make the view.py code simpler.

class LanguageTextChoices(TextChoices):
ENGLISH = "english", _("English")
SUOMI = "suomi", _("Suomi")

class ColorModeTextChoices(TextChoices):
DARK = "dark", _("Dark")
LIGHT = "light", _("Light")

language = models.CharField (max_length = 30, blank=True, choices=LanguageTextChoices)
color_mode = models.CharField (max_length = 30, blank=True, choices=ColorModeTextChoices)
46 changes: 46 additions & 0 deletions preferences/templates/preferences.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
{% extends 'base.html' %}

{% load i18n %}
{% load crispy_forms_tags %}

{% block content %}
<div class="card-body py-5 px-md-5">
<div class="row d-flex justify-content-center ">
<div class="col-lg-8">
<h2 class="fw-bold " id = "set-preference-message">Set Preferences</h2>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remember i18n ´translate'tag here.

<div class="container">
<div class="col-sm-20 " style="text-align: left">
<form action = "{% url 'preferences-view' %}" id = "preferences_form" method="post">
<table>
{{form|crispy}}
</table>
{% csrf_token %}
<button class="btn btn-primary " id = "submit_preferences_button" type="submit">Submit</button>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I18n tag here

</form>
</div>
</div>
</div>
</div>
</div>

<div class="card-body py-5 px-md-5">
<div class="row d-flex justify-content-center ">
<div class="col-lg-8">
<h2 class="fw-bold" id = "current-preferences">Your Current Preferences</h2>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Remember to add template internationalization so we can translate this string into the user language.

<div class="col-lg-15">
{% if not request.user.preferences %}
<h3 class="fw" id = "no-preferences">No current preferences. Set some!</h3>
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please add i18n tag ´translate' here.

{% else %}
{% for name, value in fields %}
{% if name != "id" %}
<h3 class="fw">{{ name }} : {{ value }}</h3>
{% endif %}
{% endfor %}
{% endif %}
</div>
</div>
</div>
</div>

{% endblock content %}

10 changes: 10 additions & 0 deletions preferences/urls.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
from django.urls import path
from .views import setPreferences

urlpatterns = [
path(
"",
setPreferences,
name="preferences-view",
),
]
43 changes: 43 additions & 0 deletions preferences/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
from django.shortcuts import render, redirect, reverse
from django.contrib.auth.decorators import login_required
from preferences.forms import PreferencesForm
from preferences.models import Preferences
from django.core import serializers

# this function creates a blank preference model form on GET request
# and returns a context with the form and the fields from the preference
# object tagged to the current user
# on non GET request we update the database to save the new preferences
@login_required
def setPreferences (request):
context = {}
if request.method == 'GET':
context['form'] = PreferencesForm ()
# null check for preferences field
if request.user.preferences:
fields = [(field.name, field.value_to_string(request.user.preferences)) for field in Preferences._meta.fields]
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is probably unnecessary

Suggested change
fields = [(field.name, field.value_to_string(request.user.preferences)) for field in Preferences._meta.fields]

context['fields'] = fields
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we only need to return a form instance pre-populated with the existing user preferences.Django takes care of everything else.

Suggested change
context['fields'] = fields
context['form'] = PreferencesForm(instance=request.user.preferences)

return render(request, '../templates/preferences.html', context)

# for any other request type that is not GET
form = PreferencesForm(request.POST)
context['form'] = form

if not form.is_valid():
return render(request, '../templates/preferences.html', context)

preferences = Preferences(
Language = form.cleaned_data['Language'],
Mode = form.cleaned_data['Mode'],
)

preferences.save ()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This can just be ‘form.save()’, so there is no need to create a temporary Preferences instance above

Suggested change
preferences.save ()
preferences = form.save()


request.user.preferences = preferences
request.user.save ()

# extract the fields to be displayed from the preferences
fields = [(field.name, field.value_to_string(request.user.preferences)) for field in Preferences._meta.fields]
context['fields'] = fields

return render(request, '../templates/preferences.html', context)
3 changes: 2 additions & 1 deletion templates/base.html
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
<!-- extra CSS to load after primary CSS -->
{% block extra_css %}{% endblock extra_css %}
</head>
<body>
<body data-bs-theme="{{ request.user.preferences.Mode }}">
{% include "navigation.html" %}

<div class="container">
Expand All @@ -24,3 +24,4 @@
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
</body>
</html>

64 changes: 64 additions & 0 deletions templates/navigation.html
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,12 @@
{% translate "Residents" %}
</a>
</li>

<li class="nav-item">
<a href="{% url 'preferences-view' %}" class="nav-link">
{% translate "Preferences" %}
</a>
</li>
</ul>
<ul class="navbar-nav ms-auto mb-2 mb-lg-0">
{% include "i18n.html" %}
Expand All @@ -56,6 +62,28 @@
<a class="nav-link" href="{% url 'signup' %}">{% translate "Sign up" %}</a>
</li>
{% endif %}

<li class="nav-item dropdown">
<!-- can refer to i18n.html for dropdown here-->
<button class="btn btn-link nav-link py-2 px-0 px-lg-2 dropdown-toggle d-flex align-items-center" id="bd-theme" type="button" aria-expanded="false" data-bs-toggle="dropdown" data-bs-display="static" aria-label="Toggle theme (dark)">
<a id="theme-label">Dark</a>
<span class="d-lg-none ms-2" id="bd-theme-text">Toggle Theme</span>
</button>
<ul class="dropdown-menu dropdown-menu-end" aria-labelledby="bd-theme-text">
<li>
<button type="button" id="light-dropdown" class="dropdown-item d-flex align-items-center" data-bs-theme-value="light" aria-pressed="true">
Light
</button>
</li>

<li>
<button type="button" id="dark-dropdown" class="dropdown-item d-flex align-items-center active" data-bs-theme-value="dark" aria-pressed="false">
Dark
</button>
</li>
</ul>
</li>

</ul>
</div>
</div>
Expand Down Expand Up @@ -88,3 +116,39 @@ <h2 class="modal-title" id="addWorkModalLabel">
</div>
</div>
</div>

<script>

function toggleTheme(theme) {
const currTheme = document.documentElement.getAttribute('data-bs-theme');
if (currTheme === theme) return;

// changes the attribute of the root element and saves to local storage
document.documentElement.setAttribute('data-bs-theme', theme);
localStorage.setItem('theme', theme);

// changes active label on dropdown
const btn = document.getElementById('theme-label');
btn.innerHTML = theme.charAt(0).toUpperCase() + theme.slice(1);
}

// changes the first parameter's class to active, and the second to not active
function changeActiveStatus(dropdown1, dropdown2) {
dropdown1.setAttribute('class', dropdown1.getAttribute('class') + ' active');
dropdown2.setAttribute('class', dropdown2.getAttribute('class').replace(' active', ''));
}

let lightMode = document.getElementById('light-dropdown');
let darkMode = document.getElementById('dark-dropdown');

lightMode.addEventListener('click', function() {
toggleTheme('light');
changeActiveStatus(lightMode, darkMode);
});

darkMode.addEventListener('click', function() {
toggleTheme('dark');
changeActiveStatus(darkMode, lightMode);
});

</script>
61 changes: 61 additions & 0 deletions templates/tests/toggle_tests.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@

/*
To run these tests, do the following, add testToggle() to the eventListeners
for the dropdown so that this function runs every time a user uses the toggle.
If the console raises errors, then the tests do not pass.
*/

function testToggle() {
const currTheme = document.documentElement.getAttribute('data-bs-theme');

// SCENARIO 1: dark mode should change to light mode
if (currTheme === 'dark') {
// check if data-bs-theme attribute actually changes to dark mode
toggleTheme('light');
assert(document.documentElement.getAttribute('data-bs-theme') === 'light');

// check if the text label correctly switches
assert(document.getElementById('theme-label').innerHTML === 'Light')

// check if the correct option is highlighted in the dropdown
changeActiveStatus(lightMode, darkMode);
assert('active' in document.getElementById('light-dropdown').getAttribute('class'))
assert(!('active' in document.getElementById('dark-dropdown').getAttribute('class')))
}

// SCENARIO 2: dark mode should remain if "dark" is selected
if (currTheme === 'dark') {
toggleTheme('dark');
assert(document.documentElement.getAttribute('data-bs-theme') === 'dark');

assert(document.getElementById('theme-label').innerHTML === 'Dark')

changeActiveStatus(lightMode, darkMode);
assert(!('active' in document.getElementById('light-dropdown').getAttribute('class')))
assert('active' in document.getElementById('dark-dropdown').getAttribute('class'))
}

// SCENARIO 3: light mode should change to dark mode
if (currTheme === 'light') {
toggleTheme('dark');
assert(document.documentElement.getAttribute('data-bs-theme') === 'dark');

assert(document.getElementById('theme-label').innerHTML === 'Dark')

changeActiveStatus(darkMode, lightMode);
assert('active' in document.getElementById('dark-dropdown').getAttribute('class'))
assert(!('active' in document.getElementById('light-dropdown').getAttribute('class')))
}

// SCENARIO 4: light mode should remain if "light" is selected
if (currTheme === 'light') {
toggleTheme('light');
assert(document.documentElement.getAttribute('data-bs-theme') === 'light');

assert(document.getElementById('theme-label').innerHTML === 'Light')

changeActiveStatus(lightMode, lightMode);
assert('active' in document.getElementById('light-dropdown').getAttribute('class'))
assert(!('active' in document.getElementById('dark-dropdown').getAttribute('class')))
}
}