From 69c07d1381d759512fb3d4028a4f24cb9032dc07 Mon Sep 17 00:00:00 2001 From: pacnpal <183241239+pacnpal@users.noreply.github.com> Date: Wed, 20 Aug 2025 12:31:33 -0400 Subject: [PATCH] Add new JavaScript and GIF assets for enhanced UI features - Introduced a new loading indicator GIF to improve user experience during asynchronous operations. - Added jQuery Ajax Queue plugin to manage queued Ajax requests, ensuring that new requests wait for previous ones to complete. - Implemented jQuery Autocomplete plugin for enhanced input fields, allowing users to receive suggestions as they type. - Included jQuery Bgiframe plugin to ensure proper rendering of elements in Internet Explorer 6. --- .clinerules | 9 +- accounts/adapters.py | 12 +- accounts/admin.py | 40 +- .../commands/check_all_social_tables.py | 13 +- .../management/commands/create_test_users.py | 16 +- accounts/management/commands/reset_db.py | 11 +- config/django/local.py | 23 +- config/django/production.py | 30 +- pyproject.toml | 2 + scripts/dev_server.sh | 7 + .../css/jquery.autocomplete.css | 38 + .../django_extensions/img/indicator.gif | Bin 0 -> 1553 bytes .../django_extensions/js/jquery.ajaxQueue.js | 116 ++ .../js/jquery.autocomplete.js | 1152 +++++++++++++++++ .../django_extensions/js/jquery.bgiframe.js | 39 + thrillwiki/wsgi.py | 2 +- 16 files changed, 1452 insertions(+), 58 deletions(-) create mode 100644 staticfiles/django_extensions/css/jquery.autocomplete.css create mode 100644 staticfiles/django_extensions/img/indicator.gif create mode 100644 staticfiles/django_extensions/js/jquery.ajaxQueue.js create mode 100644 staticfiles/django_extensions/js/jquery.autocomplete.js create mode 100644 staticfiles/django_extensions/js/jquery.bgiframe.js diff --git a/.clinerules b/.clinerules index 753aef23..f966e91a 100644 --- a/.clinerules +++ b/.clinerules @@ -4,10 +4,9 @@ IMPORTANT: Always follow these instructions exactly when starting the development server: ```bash -lsof -ti :8000 | xargs kill -9; find . -type d -name "__pycache__" -exec rm -r {} +; uv run manage.py tailwind runserver -``` +lsof -ti :8000 | xargs kill -9; find . -type d -name "__pycache__" -exec rm -r {} +; ./scripts/dev_server.sh -Note: These steps must be executed in this exact order as a single command to ensure consistent behavior. +Note: These steps must be executed in this exact order as a single command to ensure consistent behavior. If server does not start correctly, do not attempt to modify the dev_server.sh script. ## Package Management IMPORTANT: When a Python package is needed, only use UV to add it: @@ -24,8 +23,8 @@ uv run manage.py This applies to all management commands including but not limited to: - Making migrations: `uv run manage.py makemigrations` - Applying migrations: `uv run manage.py migrate` -- Creating superuser: `uv run manage.py createsuperuser` -- Starting shell: `uv run manage.py shell` +- Creating superuser: `uv run manage.py createsuperuser` and possible echo commands before for the necessary data input. +- Starting shell: `uv run manage.py shell` and possible echo commands before for the necessary data input. NEVER use `python manage.py` or `uv run python manage.py`. Always use `uv run manage.py` directly. diff --git a/accounts/adapters.py b/accounts/adapters.py index 18973ca8..680ee128 100644 --- a/accounts/adapters.py +++ b/accounts/adapters.py @@ -6,12 +6,13 @@ from django.contrib.sites.shortcuts import get_current_site User = get_user_model() + class CustomAccountAdapter(DefaultAccountAdapter): def is_open_for_signup(self, request): """ Whether to allow sign ups. """ - return getattr(settings, 'ACCOUNT_ALLOW_SIGNUPS', True) + return True def get_email_confirmation_url(self, request, emailconfirmation): """ @@ -25,7 +26,8 @@ class CustomAccountAdapter(DefaultAccountAdapter): Sends the confirmation email. """ current_site = get_current_site(request) - activate_url = self.get_email_confirmation_url(request, emailconfirmation) + activate_url = self.get_email_confirmation_url( + request, emailconfirmation) ctx = { 'user': emailconfirmation.email_address.user, 'activate_url': activate_url, @@ -36,14 +38,16 @@ class CustomAccountAdapter(DefaultAccountAdapter): email_template = 'account/email/email_confirmation_signup' else: email_template = 'account/email/email_confirmation' - self.send_mail(email_template, emailconfirmation.email_address.email, ctx) + self.send_mail( + email_template, emailconfirmation.email_address.email, ctx) + class CustomSocialAccountAdapter(DefaultSocialAccountAdapter): def is_open_for_signup(self, request, sociallogin): """ Whether to allow social account sign ups. """ - return getattr(settings, 'SOCIALACCOUNT_ALLOW_SIGNUPS', True) + return True def populate_user(self, request, sociallogin, data): """ diff --git a/accounts/admin.py b/accounts/admin.py index d8ecc3e1..cf28c4b7 100644 --- a/accounts/admin.py +++ b/accounts/admin.py @@ -5,6 +5,7 @@ from django.urls import reverse from django.contrib.auth.models import Group from .models import User, UserProfile, EmailVerification, TopList, TopListItem + class UserProfileInline(admin.StackedInline): model = UserProfile can_delete = False @@ -26,19 +27,24 @@ class UserProfileInline(admin.StackedInline): }), ) + class TopListItemInline(admin.TabularInline): model = TopListItem extra = 1 fields = ('content_type', 'object_id', 'rank', 'notes') ordering = ('rank',) + @admin.register(User) class CustomUserAdmin(UserAdmin): - list_display = ('username', 'email', 'get_avatar', 'get_status', 'role', 'date_joined', 'last_login', 'get_credits') - list_filter = ('is_active', 'is_staff', 'role', 'is_banned', 'groups', 'date_joined') + list_display = ('username', 'email', 'get_avatar', 'get_status', + 'role', 'date_joined', 'last_login', 'get_credits') + list_filter = ('is_active', 'is_staff', 'role', + 'is_banned', 'groups', 'date_joined') search_fields = ('username', 'email') ordering = ('-date_joined',) - actions = ['activate_users', 'deactivate_users', 'ban_users', 'unban_users'] + actions = ['activate_users', 'deactivate_users', + 'ban_users', 'unban_users'] inlines = [UserProfileInline] fieldsets = ( @@ -67,12 +73,13 @@ class CustomUserAdmin(UserAdmin): }), ) + @admin.display(description='Avatar') def get_avatar(self, obj): if obj.profile.avatar: return format_html('', obj.profile.avatar.url) return format_html('
{}
', obj.username[0].upper()) - get_avatar.short_description = 'Avatar' + @admin.display(description='Status') def get_status(self, obj): if obj.is_banned: return format_html('Banned') @@ -83,8 +90,8 @@ class CustomUserAdmin(UserAdmin): if obj.is_staff: return format_html('Staff') return format_html('Active') - get_status.short_description = 'Status' + @admin.display(description='Ride Credits') def get_credits(self, obj): try: profile = obj.profile @@ -97,24 +104,23 @@ class CustomUserAdmin(UserAdmin): ) except UserProfile.DoesNotExist: return '-' - get_credits.short_description = 'Ride Credits' + @admin.action(description="Activate selected users") def activate_users(self, request, queryset): queryset.update(is_active=True) - activate_users.short_description = "Activate selected users" + @admin.action(description="Deactivate selected users") def deactivate_users(self, request, queryset): queryset.update(is_active=False) - deactivate_users.short_description = "Deactivate selected users" + @admin.action(description="Ban selected users") def ban_users(self, request, queryset): from django.utils import timezone queryset.update(is_banned=True, ban_date=timezone.now()) - ban_users.short_description = "Ban selected users" + @admin.action(description="Unban selected users") def unban_users(self, request, queryset): queryset.update(is_banned=False, ban_date=None, ban_reason='') - unban_users.short_description = "Unban selected users" def save_model(self, request, obj, form, change): creating = not obj.pk @@ -125,10 +131,13 @@ class CustomUserAdmin(UserAdmin): if group: obj.groups.add(group) + @admin.register(UserProfile) class UserProfileAdmin(admin.ModelAdmin): - list_display = ('user', 'display_name', 'coaster_credits', 'dark_ride_credits', 'flat_ride_credits', 'water_ride_credits') - list_filter = ('coaster_credits', 'dark_ride_credits', 'flat_ride_credits', 'water_ride_credits') + list_display = ('user', 'display_name', 'coaster_credits', + 'dark_ride_credits', 'flat_ride_credits', 'water_ride_credits') + list_filter = ('coaster_credits', 'dark_ride_credits', + 'flat_ride_credits', 'water_ride_credits') search_fields = ('user__username', 'user__email', 'display_name', 'bio') fieldsets = ( @@ -148,13 +157,14 @@ class UserProfileAdmin(admin.ModelAdmin): }), ) + @admin.register(EmailVerification) class EmailVerificationAdmin(admin.ModelAdmin): list_display = ('user', 'created_at', 'last_sent', 'is_expired') list_filter = ('created_at', 'last_sent') search_fields = ('user__username', 'user__email', 'token') readonly_fields = ('created_at', 'last_sent') - + fieldsets = ( ('Verification Details', { 'fields': ('user', 'token') @@ -164,13 +174,14 @@ class EmailVerificationAdmin(admin.ModelAdmin): }), ) + @admin.display(description='Status') def is_expired(self, obj): from django.utils import timezone from datetime import timedelta if timezone.now() - obj.last_sent > timedelta(days=1): return format_html('Expired') return format_html('Valid') - is_expired.short_description = 'Status' + @admin.register(TopList) class TopListAdmin(admin.ModelAdmin): @@ -190,6 +201,7 @@ class TopListAdmin(admin.ModelAdmin): ) readonly_fields = ('created_at', 'updated_at') + @admin.register(TopListItem) class TopListItemAdmin(admin.ModelAdmin): list_display = ('top_list', 'content_type', 'object_id', 'rank') diff --git a/accounts/management/commands/check_all_social_tables.py b/accounts/management/commands/check_all_social_tables.py index 5473fbe9..24495c4e 100644 --- a/accounts/management/commands/check_all_social_tables.py +++ b/accounts/management/commands/check_all_social_tables.py @@ -2,6 +2,7 @@ from django.core.management.base import BaseCommand from allauth.socialaccount.models import SocialApp, SocialAccount, SocialToken from django.contrib.sites.models import Site + class Command(BaseCommand): help = 'Check all social auth related tables' @@ -9,7 +10,8 @@ class Command(BaseCommand): # Check SocialApp self.stdout.write('\nChecking SocialApp table:') for app in SocialApp.objects.all(): - self.stdout.write(f'ID: {app.id}, Provider: {app.provider}, Name: {app.name}, Client ID: {app.client_id}') + self.stdout.write( + f'ID: {app.pk}, Provider: {app.provider}, Name: {app.name}, Client ID: {app.client_id}') self.stdout.write('Sites:') for site in app.sites.all(): self.stdout.write(f' - {site.domain}') @@ -17,14 +19,17 @@ class Command(BaseCommand): # Check SocialAccount self.stdout.write('\nChecking SocialAccount table:') for account in SocialAccount.objects.all(): - self.stdout.write(f'ID: {account.id}, Provider: {account.provider}, UID: {account.uid}') + self.stdout.write( + f'ID: {account.pk}, Provider: {account.provider}, UID: {account.uid}') # Check SocialToken self.stdout.write('\nChecking SocialToken table:') for token in SocialToken.objects.all(): - self.stdout.write(f'ID: {token.id}, Account: {token.account}, App: {token.app}') + self.stdout.write( + f'ID: {token.pk}, Account: {token.account}, App: {token.app}') # Check Site self.stdout.write('\nChecking Site table:') for site in Site.objects.all(): - self.stdout.write(f'ID: {site.id}, Domain: {site.domain}, Name: {site.name}') + self.stdout.write( + f'ID: {site.pk}, Domain: {site.domain}, Name: {site.name}') diff --git a/accounts/management/commands/create_test_users.py b/accounts/management/commands/create_test_users.py index c18e0ea3..54b049c5 100644 --- a/accounts/management/commands/create_test_users.py +++ b/accounts/management/commands/create_test_users.py @@ -14,9 +14,10 @@ class Command(BaseCommand): user = User.objects.create_user( username="testuser", email="testuser@example.com", - [PASSWORD-REMOVED]", + password="testpass123", ) - self.stdout.write(self.style.SUCCESS(f"Created test user: {user.username}")) + self.stdout.write(self.style.SUCCESS( + f"Created test user: {user.username}")) else: self.stdout.write(self.style.WARNING("Test user already exists")) @@ -25,11 +26,12 @@ class Command(BaseCommand): moderator = User.objects.create_user( username="moderator", email="moderator@example.com", - [PASSWORD-REMOVED]", + password="modpass123", ) # Create moderator group if it doesn't exist - moderator_group, created = Group.objects.get_or_create(name="Moderators") + moderator_group, created = Group.objects.get_or_create( + name="Moderators") # Add relevant permissions permissions = Permission.objects.filter( @@ -48,9 +50,11 @@ class Command(BaseCommand): moderator.groups.add(moderator_group) self.stdout.write( - self.style.SUCCESS(f"Created moderator user: {moderator.username}") + self.style.SUCCESS( + f"Created moderator user: {moderator.username}") ) else: - self.stdout.write(self.style.WARNING("Moderator user already exists")) + self.stdout.write(self.style.WARNING( + "Moderator user already exists")) self.stdout.write(self.style.SUCCESS("Test users setup complete")) diff --git a/accounts/management/commands/reset_db.py b/accounts/management/commands/reset_db.py index b5445a06..84a1b374 100644 --- a/accounts/management/commands/reset_db.py +++ b/accounts/management/commands/reset_db.py @@ -3,6 +3,7 @@ from django.db import connection from django.contrib.auth.hashers import make_password import uuid + class Command(BaseCommand): help = 'Reset database and create admin user' @@ -57,8 +58,11 @@ class Command(BaseCommand): 'light' ) RETURNING id; """, [make_password('admin'), user_id]) - - user_db_id = cursor.fetchone()[0] + + result = cursor.fetchone() + if result is None: + raise Exception("Failed to create user - no ID returned") + user_db_id = result[0] # Create profile profile_id = str(uuid.uuid4())[:10] @@ -79,7 +83,8 @@ class Command(BaseCommand): self.stdout.write('Superuser created.') except Exception as e: - self.stdout.write(self.style.ERROR(f'Error creating superuser: {str(e)}')) + self.stdout.write(self.style.ERROR( + f'Error creating superuser: {str(e)}')) raise self.stdout.write(self.style.SUCCESS('Database reset complete.')) diff --git a/config/django/local.py b/config/django/local.py index 3bd9a44b..5301face 100644 --- a/config/django/local.py +++ b/config/django/local.py @@ -2,10 +2,13 @@ Local development settings for thrillwiki project. """ +import logging from .base import * from ..settings import database -from ..settings import email # Import the module and use its members, e.g., email.EMAIL_HOST -from ..settings import security # Import the module and use its members, e.g., security.SECURE_HSTS_SECONDS +# Import the module and use its members, e.g., email.EMAIL_HOST +from ..settings import email +# Import the module and use its members, e.g., security.SECURE_HSTS_SECONDS +from ..settings import security from .base import env # Import env for environment variable access # Import database configuration @@ -24,9 +27,8 @@ CSRF_TRUSTED_ORIGINS = [ "https://beta.thrillwiki.com", ] -# GeoDjango Settings for macOS development -GDAL_LIBRARY_PATH = env('GDAL_LIBRARY_PATH', default="/opt/homebrew/lib/libgdal.dylib") -GEOS_LIBRARY_PATH = env('GEOS_LIBRARY_PATH', default="/opt/homebrew/lib/libgeos_c.dylib") +GDAL_LIBRARY_PATH = "/opt/homebrew/lib/libgdal.dylib" +GEOS_LIBRARY_PATH = "/opt/homebrew/lib/libgeos_c.dylib" # Local cache configuration LOC_MEM_CACHE_BACKEND = "django.core.cache.backends.locmem.LocMemCache" @@ -69,6 +71,7 @@ DEVELOPMENT_APPS = [ 'silk', 'debug_toolbar', 'nplusone.ext.django', + 'django_extensions', ] # Add development apps if available @@ -94,17 +97,19 @@ for middleware in DEVELOPMENT_MIDDLEWARE: INTERNAL_IPS = ['127.0.0.1', '::1'] # Silk configuration for development -SILKY_PYTHON_PROFILER = False # Disable profiler to avoid silk_profile installation issues +# Disable profiler to avoid silk_profile installation issues +SILKY_PYTHON_PROFILER = False SILKY_PYTHON_PROFILER_BINARY = False # Disable binary profiler -# SILKY_PYTHON_PROFILER_RESULT_PATH = BASE_DIR / 'profiles' # Not needed when profiler is disabled +SILKY_PYTHON_PROFILER_RESULT_PATH = BASE_DIR / \ + 'profiles' # Not needed when profiler is disabled SILKY_AUTHENTICATION = True # Require login to access Silk SILKY_AUTHORISATION = True # Enable authorization SILKY_MAX_REQUEST_BODY_SIZE = -1 # Don't limit request body size -SILKY_MAX_RESPONSE_BODY_SIZE = 1024 # Limit response body size to 1KB for performance +# Limit response body size to 1KB for performance +SILKY_MAX_RESPONSE_BODY_SIZE = 1024 SILKY_META = True # Record metadata about requests # NPlusOne configuration -import logging NPLUSONE_LOGGER = logging.getLogger('nplusone') NPLUSONE_LOG_LEVEL = logging.WARN diff --git a/config/django/production.py b/config/django/production.py index ab091f83..bc3f5441 100644 --- a/config/django/production.py +++ b/config/django/production.py @@ -2,21 +2,27 @@ Production settings for thrillwiki project. """ -from . import base # Import the module and use its members, e.g., base.BASE_DIR, base***REMOVED*** -from ..settings import database # Import the module and use its members, e.g., database.DATABASES -from ..settings import email # Import the module and use its members, e.g., email.EMAIL_HOST -from ..settings import security # Import the module and use its members, e.g., security.SECURE_HSTS_SECONDS -from ..settings import email # Import the module and use its members, e.g., email.EMAIL_HOST -from ..settings import security # Import the module and use its members, e.g., security.SECURE_HSTS_SECONDS +# Import the module and use its members, e.g., base.BASE_DIR, base***REMOVED*** +from . import base +# Import the module and use its members, e.g., database.DATABASES +from ..settings import database +# Import the module and use its members, e.g., email.EMAIL_HOST +from ..settings import email +# Import the module and use its members, e.g., security.SECURE_HSTS_SECONDS +from ..settings import security +# Import the module and use its members, e.g., email.EMAIL_HOST +from ..settings import email +# Import the module and use its members, e.g., security.SECURE_HSTS_SECONDS +from ..settings import security # Production settings DEBUG = False # Allowed hosts must be explicitly set in production -ALLOWED_HOSTS = base***REMOVED***('ALLOWED_HOSTS') +ALLOWED_HOSTS = base.env.list('ALLOWED_HOSTS') # CSRF trusted origins for production -CSRF_TRUSTED_ORIGINS = base***REMOVED***('CSRF_TRUSTED_ORIGINS', default=[]) +CSRF_TRUSTED_ORIGINS = base.env.list('CSRF_TRUSTED_ORIGINS') # Security settings for production SECURE_SSL_REDIRECT = True @@ -80,18 +86,18 @@ LOGGING = { STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' # Cache settings for production (Redis recommended) -if base***REMOVED***('REDIS_URL', default=None): +redis_url = base.env.str('REDIS_URL', default=None) +if redis_url: CACHES = { 'default': { 'BACKEND': 'django_redis.cache.RedisCache', - 'LOCATION': base***REMOVED***('REDIS_URL'), + 'LOCATION': redis_url, 'OPTIONS': { 'CLIENT_CLASS': 'django_redis.client.DefaultClient', } } } - + # Use Redis for sessions in production SESSION_ENGINE = 'django.contrib.sessions.backends.cache' SESSION_CACHE_ALIAS = 'default' - diff --git a/pyproject.toml b/pyproject.toml index bbadd5c6..310c988b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -50,4 +50,6 @@ dependencies = [ "python-json-logger>=2.0.7", "django-cloudflare-images>=0.6.0", "psutil>=7.0.0", + "django-extensions>=4.1", + "werkzeug>=3.1.3", ] diff --git a/scripts/dev_server.sh b/scripts/dev_server.sh index b6ce2620..3fc96f31 100755 --- a/scripts/dev_server.sh +++ b/scripts/dev_server.sh @@ -77,6 +77,13 @@ else echo "🔄 Running database migrations..." uv run manage.py migrate --noinput fi +echo "Resetting database..." +if uv run manage.py seed_sample_data 2>/dev/null; then + echo "Seeding complete!" +else + echo "Seeding test data to database..." + uv run manage.py seed_sample_data +fi # Create superuser if it doesn't exist echo "👤 Checking for superuser..." diff --git a/staticfiles/django_extensions/css/jquery.autocomplete.css b/staticfiles/django_extensions/css/jquery.autocomplete.css new file mode 100644 index 00000000..0363616e --- /dev/null +++ b/staticfiles/django_extensions/css/jquery.autocomplete.css @@ -0,0 +1,38 @@ +/** + * @fileOverview CSS for jquery-autocomplete, the jQuery Autocompleter + * @author Dylan Verheul + * @license MIT | GPL | Apache 2.0, see LICENSE.txt + * @see https://github.com/dyve/jquery-autocomplete + */ +.acResults { + padding: 0px; + border: 1px solid WindowFrame; + background-color: Window; + overflow: hidden; +} + +.acResults ul { + margin: 0px; + padding: 0px; + list-style-position: outside; + list-style: none; +} + +.acResults ul li { + margin: 0px; + padding: 2px 5px; + cursor: pointer; + display: block; + font: menu; + font-size: 12px; + overflow: hidden; +} + +.acLoading { + background : url('../img/indicator.gif') right center no-repeat; +} + +.acSelect { + background-color: Highlight; + color: HighlightText; +} diff --git a/staticfiles/django_extensions/img/indicator.gif b/staticfiles/django_extensions/img/indicator.gif new file mode 100644 index 0000000000000000000000000000000000000000..085ccaecaf5fa5c34bc14cd2c2ed5cbbd8e25dcb GIT binary patch literal 1553 zcma)+TTl~c6vwlh>nb99Af5rT)t{mCEg5urg=A(g z{C|6SPb~9Xage|wB`SrZk2FOMYM!buln2sX?5Y+T78iB(Zu9cS7|LZyZ++}u$^oi1 z_j@S}bW9OzU2R+RMy&~OT>X-oZ98$jq#ogNfJ!BM-42wHGZk*6s2KD}U*IA%epmxb zm}|6BK9YoIF;*xSL!+z@<64lB7->LTW2Vi4ostCA(z&2XniwNIv}fFo-`MbG;)u4G z^p@F!)|9HhZprHd_vXjDoxs6WkK-6P0@lfxnGT>*p(QHoUV=u1FAqb@b%*W=a3{`LsH5k^AvQNL>6fPpy#oU(&MuH(*aEX4b35*} zn4n7)`I2U%=+Z=?BVZQ?vjQFW4gD@~XSOO6b{qu81`4&LFuU2(ilxW+1|ZkNMnWe79C$gs zWT?Ele|HR{JGPe)5BTW>0Ey?-Ls6S#GoV0tbt6ku7B&*0 z;i9QM$W1Rj*rRIdceL)rAOSl+sDe3LkB87<%){;ZdHp6|SNlopDXRx< zxBDF9-lTo&v`8$humFygUij@qgT=Qzhj8{ym2-{Xciwqq_Xwk%=O3B-MNAL_6e`3U zyxwmXex4`g0^1RYw~Dth3av3Dl^AAlpO3mG!nLr#&ZZ7c_wUboI+deC+&%TFjK2Lm z!Y&f1h|T_On%RCV&=4bx`!>(YezqGVhl&QpED?N6GV)HmzJ9&rh$x*i?*@o9#6QI< z5ZI_MRX;0+pY8$`j)eF#TlUyG(eE%E7S!rj;mj^M5vhUicPm zVWQ2z+imFyg}SRABmOBY_@osR!>7Ov!ioK`NB6_Rv}7Ud?35ed5Sb@?yND?kv~RCa wqs^a3Sh>&&L4)!LKI?D2&k@))k(LESaga|C278ChSzn3NWVkcuNoY&{0f?~U_5c6? literal 0 HcmV?d00001 diff --git a/staticfiles/django_extensions/js/jquery.ajaxQueue.js b/staticfiles/django_extensions/js/jquery.ajaxQueue.js new file mode 100644 index 00000000..aca15d9a --- /dev/null +++ b/staticfiles/django_extensions/js/jquery.ajaxQueue.js @@ -0,0 +1,116 @@ +/** + * Ajax Queue Plugin + */ + +/** + + +
    + + */ +/* + * Queued Ajax requests. + * A new Ajax request won't be started until the previous queued + * request has finished. + */ + +/* + * Synced Ajax requests. + * The Ajax request will happen as soon as you call this method, but + * the callbacks (success/error/complete) won't fire until all previous + * synced requests have been completed. + */ + + +(function(jQuery) { + + var ajax = jQuery.ajax; + + var pendingRequests = {}; + + var synced = []; + var syncedData = []; + + jQuery.ajax = function(settings) { + // create settings for compatibility with ajaxSetup + settings = jQuery.extend(settings, jQuery.extend({}, jQuery.ajaxSettings, settings)); + + var port = settings.port; + + switch(settings.mode) { + case "abort": + if ( pendingRequests[port] ) { + pendingRequests[port].abort(); + } + return pendingRequests[port] = ajax.apply(this, arguments); + case "queue": + var _old = settings.complete; + settings.complete = function(){ + if ( _old ) + _old.apply( this, arguments ); + jQuery([ajax]).dequeue("ajax" + port );; + }; + + jQuery([ ajax ]).queue("ajax" + port, function(){ + ajax( settings ); + }); + return; + case "sync": + var pos = synced.length; + + synced[ pos ] = { + error: settings.error, + success: settings.success, + complete: settings.complete, + done: false + }; + + syncedData[ pos ] = { + error: [], + success: [], + complete: [] + }; + + settings.error = function(){ syncedData[ pos ].error = arguments; }; + settings.success = function(){ syncedData[ pos ].success = arguments; }; + settings.complete = function(){ + syncedData[ pos ].complete = arguments; + synced[ pos ].done = true; + + if ( pos == 0 || !synced[ pos-1 ] ) + for ( var i = pos; i < synced.length && synced[i].done; i++ ) { + if ( synced[i].error ) synced[i].error.apply( jQuery, syncedData[i].error ); + if ( synced[i].success ) synced[i].success.apply( jQuery, syncedData[i].success ); + if ( synced[i].complete ) synced[i].complete.apply( jQuery, syncedData[i].complete ); + + synced[i] = null; + syncedData[i] = null; + } + }; + } + return ajax.apply(this, arguments); + }; + +})((typeof window.jQuery == 'undefined' && typeof window.django != 'undefined') + ? django.jQuery + : jQuery +); diff --git a/staticfiles/django_extensions/js/jquery.autocomplete.js b/staticfiles/django_extensions/js/jquery.autocomplete.js new file mode 100644 index 00000000..77c1db60 --- /dev/null +++ b/staticfiles/django_extensions/js/jquery.autocomplete.js @@ -0,0 +1,1152 @@ +/** + * @fileOverview jquery-autocomplete, the jQuery Autocompleter + * @author Dylan Verheul + * @version 2.4.4 + * @requires jQuery 1.6+ + * @license MIT | GPL | Apache 2.0, see LICENSE.txt + * @see https://github.com/dyve/jquery-autocomplete + */ +(function($) { + "use strict"; + + /** + * jQuery autocomplete plugin + * @param {object|string} options + * @returns (object} jQuery object + */ + $.fn.autocomplete = function(options) { + var url; + if (arguments.length > 1) { + url = options; + options = arguments[1]; + options.url = url; + } else if (typeof options === 'string') { + url = options; + options = { url: url }; + } + var opts = $.extend({}, $.fn.autocomplete.defaults, options); + return this.each(function() { + var $this = $(this); + $this.data('autocompleter', new $.Autocompleter( + $this, + $.meta ? $.extend({}, opts, $this.data()) : opts + )); + }); + }; + + /** + * Store default options + * @type {object} + */ + $.fn.autocomplete.defaults = { + inputClass: 'acInput', + loadingClass: 'acLoading', + resultsClass: 'acResults', + selectClass: 'acSelect', + queryParamName: 'q', + extraParams: {}, + remoteDataType: false, + lineSeparator: '\n', + cellSeparator: '|', + minChars: 2, + maxItemsToShow: 10, + delay: 400, + useCache: true, + maxCacheLength: 10, + matchSubset: true, + matchCase: false, + matchInside: true, + mustMatch: false, + selectFirst: false, + selectOnly: false, + showResult: null, + preventDefaultReturn: 1, + preventDefaultTab: 0, + autoFill: false, + filterResults: true, + filter: true, + sortResults: true, + sortFunction: null, + onItemSelect: null, + onNoMatch: null, + onFinish: null, + matchStringConverter: null, + beforeUseConverter: null, + autoWidth: 'min-width', + useDelimiter: false, + delimiterChar: ',', + delimiterKeyCode: 188, + processData: null, + onError: null, + enabled: true + }; + + /** + * Sanitize result + * @param {Object} result + * @returns {Object} object with members value (String) and data (Object) + * @private + */ + var sanitizeResult = function(result) { + var value, data; + var type = typeof result; + if (type === 'string') { + value = result; + data = {}; + } else if ($.isArray(result)) { + value = result[0]; + data = result.slice(1); + } else if (type === 'object') { + value = result.value; + data = result.data; + } + value = String(value); + if (typeof data !== 'object') { + data = {}; + } + return { + value: value, + data: data + }; + }; + + /** + * Sanitize integer + * @param {mixed} value + * @param {Object} options + * @returns {Number} integer + * @private + */ + var sanitizeInteger = function(value, stdValue, options) { + var num = parseInt(value, 10); + options = options || {}; + if (isNaN(num) || (options.min && num < options.min)) { + num = stdValue; + } + return num; + }; + + /** + * Create partial url for a name/value pair + */ + var makeUrlParam = function(name, value) { + return [name, encodeURIComponent(value)].join('='); + }; + + /** + * Build an url + * @param {string} url Base url + * @param {object} [params] Dictionary of parameters + */ + var makeUrl = function(url, params) { + var urlAppend = []; + $.each(params, function(index, value) { + urlAppend.push(makeUrlParam(index, value)); + }); + if (urlAppend.length) { + url += url.indexOf('?') === -1 ? '?' : '&'; + url += urlAppend.join('&'); + } + return url; + }; + + /** + * Default sort filter + * @param {object} a + * @param {object} b + * @param {boolean} matchCase + * @returns {number} + */ + var sortValueAlpha = function(a, b, matchCase) { + a = String(a.value); + b = String(b.value); + if (!matchCase) { + a = a.toLowerCase(); + b = b.toLowerCase(); + } + if (a > b) { + return 1; + } + if (a < b) { + return -1; + } + return 0; + }; + + /** + * Parse data received in text format + * @param {string} text Plain text input + * @param {string} lineSeparator String that separates lines + * @param {string} cellSeparator String that separates cells + * @returns {array} Array of autocomplete data objects + */ + var plainTextParser = function(text, lineSeparator, cellSeparator) { + var results = []; + var i, j, data, line, value, lines; + // Be nice, fix linebreaks before splitting on lineSeparator + lines = String(text).replace('\r\n', '\n').split(lineSeparator); + for (i = 0; i < lines.length; i++) { + line = lines[i].split(cellSeparator); + data = []; + for (j = 0; j < line.length; j++) { + data.push(decodeURIComponent(line[j])); + } + value = data.shift(); + results.push({ value: value, data: data }); + } + return results; + }; + + /** + * Autocompleter class + * @param {object} $elem jQuery object with one input tag + * @param {object} options Settings + * @constructor + */ + $.Autocompleter = function($elem, options) { + + /** + * Assert parameters + */ + if (!$elem || !($elem instanceof $) || $elem.length !== 1 || $elem.get(0).tagName.toUpperCase() !== 'INPUT') { + throw new Error('Invalid parameter for jquery.Autocompleter, jQuery object with one element with INPUT tag expected.'); + } + + /** + * @constant Link to this instance + * @type object + * @private + */ + var self = this; + + /** + * @property {object} Options for this instance + * @public + */ + this.options = options; + + /** + * @property object Cached data for this instance + * @private + */ + this.cacheData_ = {}; + + /** + * @property {number} Number of cached data items + * @private + */ + this.cacheLength_ = 0; + + /** + * @property {string} Class name to mark selected item + * @private + */ + this.selectClass_ = 'jquery-autocomplete-selected-item'; + + /** + * @property {number} Handler to activation timeout + * @private + */ + this.keyTimeout_ = null; + + /** + * @property {number} Handler to finish timeout + * @private + */ + this.finishTimeout_ = null; + + /** + * @property {number} Last key pressed in the input field (store for behavior) + * @private + */ + this.lastKeyPressed_ = null; + + /** + * @property {string} Last value processed by the autocompleter + * @private + */ + this.lastProcessedValue_ = null; + + /** + * @property {string} Last value selected by the user + * @private + */ + this.lastSelectedValue_ = null; + + /** + * @property {boolean} Is this autocompleter active (showing results)? + * @see showResults + * @private + */ + this.active_ = false; + + /** + * @property {boolean} Is this autocompleter allowed to finish on blur? + * @private + */ + this.finishOnBlur_ = true; + + /** + * Sanitize options + */ + this.options.minChars = sanitizeInteger(this.options.minChars, $.fn.autocomplete.defaults.minChars, { min: 0 }); + this.options.maxItemsToShow = sanitizeInteger(this.options.maxItemsToShow, $.fn.autocomplete.defaults.maxItemsToShow, { min: 0 }); + this.options.maxCacheLength = sanitizeInteger(this.options.maxCacheLength, $.fn.autocomplete.defaults.maxCacheLength, { min: 1 }); + this.options.delay = sanitizeInteger(this.options.delay, $.fn.autocomplete.defaults.delay, { min: 0 }); + if (this.options.preventDefaultReturn != 2) { + this.options.preventDefaultReturn = this.options.preventDefaultReturn ? 1 : 0; + } + if (this.options.preventDefaultTab != 2) { + this.options.preventDefaultTab = this.options.preventDefaultTab ? 1 : 0; + } + + /** + * Init DOM elements repository + */ + this.dom = {}; + + /** + * Store the input element we're attached to in the repository + */ + this.dom.$elem = $elem; + + /** + * Switch off the native autocomplete and add the input class + */ + this.dom.$elem.attr('autocomplete', 'off').addClass(this.options.inputClass); + + /** + * Create DOM element to hold results, and force absolute position + */ + this.dom.$results = $('
    ').hide().addClass(this.options.resultsClass).css({ + position: 'absolute' + }); + $('body').append(this.dom.$results); + + /** + * Attach keyboard monitoring to $elem + */ + $elem.keydown(function(e) { + self.lastKeyPressed_ = e.keyCode; + switch(self.lastKeyPressed_) { + + case self.options.delimiterKeyCode: // comma = 188 + if (self.options.useDelimiter && self.active_) { + self.selectCurrent(); + } + break; + + // ignore navigational & special keys + case 35: // end + case 36: // home + case 16: // shift + case 17: // ctrl + case 18: // alt + case 37: // left + case 39: // right + break; + + case 38: // up + e.preventDefault(); + if (self.active_) { + self.focusPrev(); + } else { + self.activate(); + } + return false; + + case 40: // down + e.preventDefault(); + if (self.active_) { + self.focusNext(); + } else { + self.activate(); + } + return false; + + case 9: // tab + if (self.active_) { + self.selectCurrent(); + if (self.options.preventDefaultTab) { + e.preventDefault(); + return false; + } + } + if (self.options.preventDefaultTab === 2) { + e.preventDefault(); + return false; + } + break; + + case 13: // return + if (self.active_) { + self.selectCurrent(); + if (self.options.preventDefaultReturn) { + e.preventDefault(); + return false; + } + } + if (self.options.preventDefaultReturn === 2) { + e.preventDefault(); + return false; + } + break; + + case 27: // escape + if (self.active_) { + e.preventDefault(); + self.deactivate(true); + return false; + } + break; + + default: + self.activate(); + + } + }); + + /** + * Attach paste event listener because paste may occur much later then keydown or even without a keydown at all + */ + $elem.on('paste', function() { + self.activate(); + }); + + /** + * Finish on blur event + * Use a timeout because instant blur gives race conditions + */ + var onBlurFunction = function() { + self.deactivate(true); + } + $elem.blur(function() { + if (self.finishOnBlur_) { + self.finishTimeout_ = setTimeout(onBlurFunction, 200); + } + }); + /** + * Catch a race condition on form submit + */ + $elem.parents('form').on('submit', onBlurFunction); + + }; + + /** + * Position output DOM elements + * @private + */ + $.Autocompleter.prototype.position = function() { + var offset = this.dom.$elem.offset(); + var height = this.dom.$results.outerHeight(); + var totalHeight = $(window).outerHeight(); + var inputBottom = offset.top + this.dom.$elem.outerHeight(); + var bottomIfDown = inputBottom + height; + // Set autocomplete results at the bottom of input + var position = {top: inputBottom, left: offset.left}; + if (bottomIfDown > totalHeight) { + // Try to set autocomplete results at the top of input + var topIfUp = offset.top - height; + if (topIfUp >= 0) { + position.top = topIfUp; + } + } + this.dom.$results.css(position); + }; + + /** + * Read from cache + * @private + */ + $.Autocompleter.prototype.cacheRead = function(filter) { + var filterLength, searchLength, search, maxPos, pos; + if (this.options.useCache) { + filter = String(filter); + filterLength = filter.length; + if (this.options.matchSubset) { + searchLength = 1; + } else { + searchLength = filterLength; + } + while (searchLength <= filterLength) { + if (this.options.matchInside) { + maxPos = filterLength - searchLength; + } else { + maxPos = 0; + } + pos = 0; + while (pos <= maxPos) { + search = filter.substr(0, searchLength); + if (this.cacheData_[search] !== undefined) { + return this.cacheData_[search]; + } + pos++; + } + searchLength++; + } + } + return false; + }; + + /** + * Write to cache + * @private + */ + $.Autocompleter.prototype.cacheWrite = function(filter, data) { + if (this.options.useCache) { + if (this.cacheLength_ >= this.options.maxCacheLength) { + this.cacheFlush(); + } + filter = String(filter); + if (this.cacheData_[filter] !== undefined) { + this.cacheLength_++; + } + this.cacheData_[filter] = data; + return this.cacheData_[filter]; + } + return false; + }; + + /** + * Flush cache + * @public + */ + $.Autocompleter.prototype.cacheFlush = function() { + this.cacheData_ = {}; + this.cacheLength_ = 0; + }; + + /** + * Call hook + * Note that all called hooks are passed the autocompleter object + * @param {string} hook + * @param data + * @returns Result of called hook, false if hook is undefined + */ + $.Autocompleter.prototype.callHook = function(hook, data) { + var f = this.options[hook]; + if (f && $.isFunction(f)) { + return f(data, this); + } + return false; + }; + + /** + * Set timeout to activate autocompleter + */ + $.Autocompleter.prototype.activate = function() { + if (!this.options.enabled) return; + var self = this; + if (this.keyTimeout_) { + clearTimeout(this.keyTimeout_); + } + this.keyTimeout_ = setTimeout(function() { + self.activateNow(); + }, this.options.delay); + }; + + /** + * Activate autocompleter immediately + */ + $.Autocompleter.prototype.activateNow = function() { + var value = this.beforeUseConverter(this.dom.$elem.val()); + if (value !== this.lastProcessedValue_ && value !== this.lastSelectedValue_) { + this.fetchData(value); + } + }; + + /** + * Get autocomplete data for a given value + * @param {string} value Value to base autocompletion on + * @private + */ + $.Autocompleter.prototype.fetchData = function(value) { + var self = this; + var processResults = function(results, filter) { + if (self.options.processData) { + results = self.options.processData(results); + } + self.showResults(self.filterResults(results, filter), filter); + }; + this.lastProcessedValue_ = value; + if (value.length < this.options.minChars) { + processResults([], value); + } else if (this.options.data) { + processResults(this.options.data, value); + } else { + this.fetchRemoteData(value, function(remoteData) { + processResults(remoteData, value); + }); + } + }; + + /** + * Get remote autocomplete data for a given value + * @param {string} filter The filter to base remote data on + * @param {function} callback The function to call after data retrieval + * @private + */ + $.Autocompleter.prototype.fetchRemoteData = function(filter, callback) { + var data = this.cacheRead(filter); + if (data) { + callback(data); + } else { + var self = this; + var dataType = self.options.remoteDataType === 'json' ? 'json' : 'text'; + var ajaxCallback = function(data) { + var parsed = false; + if (data !== false) { + parsed = self.parseRemoteData(data); + self.cacheWrite(filter, parsed); + } + self.dom.$elem.removeClass(self.options.loadingClass); + callback(parsed); + }; + this.dom.$elem.addClass(this.options.loadingClass); + $.ajax({ + url: this.makeUrl(filter), + success: ajaxCallback, + error: function(jqXHR, textStatus, errorThrown) { + if($.isFunction(self.options.onError)) { + self.options.onError(jqXHR, textStatus, errorThrown); + } else { + ajaxCallback(false); + } + }, + dataType: dataType + }); + } + }; + + /** + * Create or update an extra parameter for the remote request + * @param {string} name Parameter name + * @param {string} value Parameter value + * @public + */ + $.Autocompleter.prototype.setExtraParam = function(name, value) { + var index = $.trim(String(name)); + if (index) { + if (!this.options.extraParams) { + this.options.extraParams = {}; + } + if (this.options.extraParams[index] !== value) { + this.options.extraParams[index] = value; + this.cacheFlush(); + } + } + + return this; + }; + + /** + * Build the url for a remote request + * If options.queryParamName === false, append query to url instead of using a GET parameter + * @param {string} param The value parameter to pass to the backend + * @returns {string} The finished url with parameters + */ + $.Autocompleter.prototype.makeUrl = function(param) { + var self = this; + var url = this.options.url; + var params = $.extend({}, this.options.extraParams); + + if (this.options.queryParamName === false) { + url += encodeURIComponent(param); + } else { + params[this.options.queryParamName] = param; + } + + return makeUrl(url, params); + }; + + /** + * Parse data received from server + * @param remoteData Data received from remote server + * @returns {array} Parsed data + */ + $.Autocompleter.prototype.parseRemoteData = function(remoteData) { + var remoteDataType; + var data = remoteData; + if (this.options.remoteDataType === 'json') { + remoteDataType = typeof(remoteData); + switch (remoteDataType) { + case 'object': + data = remoteData; + break; + case 'string': + data = $.parseJSON(remoteData); + break; + default: + throw new Error("Unexpected remote data type: " + remoteDataType); + } + return data; + } + return plainTextParser(data, this.options.lineSeparator, this.options.cellSeparator); + }; + + /** + * Default filter for results + * @param {Object} result + * @param {String} filter + * @returns {boolean} Include this result + * @private + */ + $.Autocompleter.prototype.defaultFilter = function(result, filter) { + if (!result.value) { + return false; + } + if (this.options.filterResults) { + var pattern = this.matchStringConverter(filter); + var testValue = this.matchStringConverter(result.value); + if (!this.options.matchCase) { + pattern = pattern.toLowerCase(); + testValue = testValue.toLowerCase(); + } + var patternIndex = testValue.indexOf(pattern); + if (this.options.matchInside) { + return patternIndex > -1; + } else { + return patternIndex === 0; + } + } + return true; + }; + + /** + * Filter result + * @param {Object} result + * @param {String} filter + * @returns {boolean} Include this result + * @private + */ + $.Autocompleter.prototype.filterResult = function(result, filter) { + // No filter + if (this.options.filter === false) { + return true; + } + // Custom filter + if ($.isFunction(this.options.filter)) { + return this.options.filter(result, filter); + } + // Default filter + return this.defaultFilter(result, filter); + }; + + /** + * Filter results + * @param results + * @param filter + */ + $.Autocompleter.prototype.filterResults = function(results, filter) { + var filtered = []; + var i, result; + + for (i = 0; i < results.length; i++) { + result = sanitizeResult(results[i]); + if (this.filterResult(result, filter)) { + filtered.push(result); + } + } + if (this.options.sortResults) { + filtered = this.sortResults(filtered, filter); + } + if (this.options.maxItemsToShow > 0 && this.options.maxItemsToShow < filtered.length) { + filtered.length = this.options.maxItemsToShow; + } + return filtered; + }; + + /** + * Sort results + * @param results + * @param filter + */ + $.Autocompleter.prototype.sortResults = function(results, filter) { + var self = this; + var sortFunction = this.options.sortFunction; + if (!$.isFunction(sortFunction)) { + sortFunction = function(a, b, f) { + return sortValueAlpha(a, b, self.options.matchCase); + }; + } + results.sort(function(a, b) { + return sortFunction(a, b, filter, self.options); + }); + return results; + }; + + /** + * Convert string before matching + * @param s + * @param a + * @param b + */ + $.Autocompleter.prototype.matchStringConverter = function(s, a, b) { + var converter = this.options.matchStringConverter; + if ($.isFunction(converter)) { + s = converter(s, a, b); + } + return s; + }; + + /** + * Convert string before use + * @param {String} s + */ + $.Autocompleter.prototype.beforeUseConverter = function(s) { + s = this.getValue(s); + var converter = this.options.beforeUseConverter; + if ($.isFunction(converter)) { + s = converter(s); + } + return s; + }; + + /** + * Enable finish on blur event + */ + $.Autocompleter.prototype.enableFinishOnBlur = function() { + this.finishOnBlur_ = true; + }; + + /** + * Disable finish on blur event + */ + $.Autocompleter.prototype.disableFinishOnBlur = function() { + this.finishOnBlur_ = false; + }; + + /** + * Create a results item (LI element) from a result + * @param result + */ + $.Autocompleter.prototype.createItemFromResult = function(result) { + var self = this; + var $li = $('
  • '); + $li.html(this.showResult(result.value, result.data)); + $li.data({value: result.value, data: result.data}) + .click(function() { + self.selectItem($li); + }) + .mousedown(self.disableFinishOnBlur) + .mouseup(self.enableFinishOnBlur) + ; + return $li; + }; + + /** + * Get all items from the results list + * @param result + */ + $.Autocompleter.prototype.getItems = function() { + return $('>ul>li', this.dom.$results); + }; + + /** + * Show all results + * @param results + * @param filter + */ + $.Autocompleter.prototype.showResults = function(results, filter) { + var numResults = results.length; + var self = this; + var $ul = $('
      '); + var i, result, $li, autoWidth, first = false, $first = false; + + if (numResults) { + for (i = 0; i < numResults; i++) { + result = results[i]; + $li = this.createItemFromResult(result); + $ul.append($li); + if (first === false) { + first = String(result.value); + $first = $li; + $li.addClass(this.options.firstItemClass); + } + if (i === numResults - 1) { + $li.addClass(this.options.lastItemClass); + } + } + + this.dom.$results.html($ul).show(); + + // Always recalculate position since window size or + // input element location may have changed. + this.position(); + if (this.options.autoWidth) { + autoWidth = this.dom.$elem.outerWidth() - this.dom.$results.outerWidth() + this.dom.$results.width(); + this.dom.$results.css(this.options.autoWidth, autoWidth); + } + this.getItems().hover( + function() { self.focusItem(this); }, + function() { /* void */ } + ); + if (this.autoFill(first, filter) || this.options.selectFirst || (this.options.selectOnly && numResults === 1)) { + this.focusItem($first); + } + this.active_ = true; + } else { + this.hideResults(); + this.active_ = false; + } + }; + + $.Autocompleter.prototype.showResult = function(value, data) { + if ($.isFunction(this.options.showResult)) { + return this.options.showResult(value, data); + } else { + return $('

      ').text(value).html(); + } + }; + + $.Autocompleter.prototype.autoFill = function(value, filter) { + var lcValue, lcFilter, valueLength, filterLength; + if (this.options.autoFill && this.lastKeyPressed_ !== 8) { + lcValue = String(value).toLowerCase(); + lcFilter = String(filter).toLowerCase(); + valueLength = value.length; + filterLength = filter.length; + if (lcValue.substr(0, filterLength) === lcFilter) { + var d = this.getDelimiterOffsets(); + var pad = d.start ? ' ' : ''; // if there is a preceding delimiter + this.setValue( pad + value ); + var start = filterLength + d.start + pad.length; + var end = valueLength + d.start + pad.length; + this.selectRange(start, end); + return true; + } + } + return false; + }; + + $.Autocompleter.prototype.focusNext = function() { + this.focusMove(+1); + }; + + $.Autocompleter.prototype.focusPrev = function() { + this.focusMove(-1); + }; + + $.Autocompleter.prototype.focusMove = function(modifier) { + var $items = this.getItems(); + modifier = sanitizeInteger(modifier, 0); + if (modifier) { + for (var i = 0; i < $items.length; i++) { + if ($($items[i]).hasClass(this.selectClass_)) { + this.focusItem(i + modifier); + return; + } + } + } + this.focusItem(0); + }; + + $.Autocompleter.prototype.focusItem = function(item) { + var $item, $items = this.getItems(); + if ($items.length) { + $items.removeClass(this.selectClass_).removeClass(this.options.selectClass); + if (typeof item === 'number') { + if (item < 0) { + item = 0; + } else if (item >= $items.length) { + item = $items.length - 1; + } + $item = $($items[item]); + } else { + $item = $(item); + } + if ($item) { + $item.addClass(this.selectClass_).addClass(this.options.selectClass); + } + } + }; + + $.Autocompleter.prototype.selectCurrent = function() { + var $item = $('li.' + this.selectClass_, this.dom.$results); + if ($item.length === 1) { + this.selectItem($item); + } else { + this.deactivate(false); + } + }; + + $.Autocompleter.prototype.selectItem = function($li) { + var value = $li.data('value'); + var data = $li.data('data'); + var displayValue = this.displayValue(value, data); + var processedDisplayValue = this.beforeUseConverter(displayValue); + this.lastProcessedValue_ = processedDisplayValue; + this.lastSelectedValue_ = processedDisplayValue; + var d = this.getDelimiterOffsets(); + var delimiter = this.options.delimiterChar; + var elem = this.dom.$elem; + var extraCaretPos = 0; + if ( this.options.useDelimiter ) { + // if there is a preceding delimiter, add a space after the delimiter + if ( elem.val().substring(d.start-1, d.start) == delimiter && delimiter != ' ' ) { + displayValue = ' ' + displayValue; + } + // if there is not already a delimiter trailing this value, add it + if ( elem.val().substring(d.end, d.end+1) != delimiter && this.lastKeyPressed_ != this.options.delimiterKeyCode ) { + displayValue = displayValue + delimiter; + } else { + // move the cursor after the existing trailing delimiter + extraCaretPos = 1; + } + } + this.setValue(displayValue); + this.setCaret(d.start + displayValue.length + extraCaretPos); + this.callHook('onItemSelect', { value: value, data: data }); + this.deactivate(true); + elem.focus(); + }; + + $.Autocompleter.prototype.displayValue = function(value, data) { + if ($.isFunction(this.options.displayValue)) { + return this.options.displayValue(value, data); + } + return value; + }; + + $.Autocompleter.prototype.hideResults = function() { + this.dom.$results.hide(); + }; + + $.Autocompleter.prototype.deactivate = function(finish) { + if (this.finishTimeout_) { + clearTimeout(this.finishTimeout_); + } + if (this.keyTimeout_) { + clearTimeout(this.keyTimeout_); + } + if (finish) { + if (this.lastProcessedValue_ !== this.lastSelectedValue_) { + if (this.options.mustMatch) { + this.setValue(''); + } + this.callHook('onNoMatch'); + } + if (this.active_) { + this.callHook('onFinish'); + } + this.lastKeyPressed_ = null; + this.lastProcessedValue_ = null; + this.lastSelectedValue_ = null; + this.active_ = false; + } + this.hideResults(); + }; + + $.Autocompleter.prototype.selectRange = function(start, end) { + var input = this.dom.$elem.get(0); + if (input.setSelectionRange) { + input.focus(); + input.setSelectionRange(start, end); + } else if (input.createTextRange) { + var range = input.createTextRange(); + range.collapse(true); + range.moveEnd('character', end); + range.moveStart('character', start); + range.select(); + } + }; + + /** + * Move caret to position + * @param {Number} pos + */ + $.Autocompleter.prototype.setCaret = function(pos) { + this.selectRange(pos, pos); + }; + + /** + * Get caret position + */ + $.Autocompleter.prototype.getCaret = function() { + var $elem = this.dom.$elem; + var elem = $elem[0]; + var val, selection, range, start, end, stored_range; + if (elem.createTextRange) { // IE + selection = document.selection; + if (elem.tagName.toLowerCase() != 'textarea') { + val = $elem.val(); + range = selection.createRange().duplicate(); + range.moveEnd('character', val.length); + if (range.text === '') { + start = val.length; + } else { + start = val.lastIndexOf(range.text); + } + range = selection.createRange().duplicate(); + range.moveStart('character', -val.length); + end = range.text.length; + } else { + range = selection.createRange(); + stored_range = range.duplicate(); + stored_range.moveToElementText(elem); + stored_range.setEndPoint('EndToEnd', range); + start = stored_range.text.length - range.text.length; + end = start + range.text.length; + } + } else { + start = $elem[0].selectionStart; + end = $elem[0].selectionEnd; + } + return { + start: start, + end: end + }; + }; + + /** + * Set the value that is currently being autocompleted + * @param {String} value + */ + $.Autocompleter.prototype.setValue = function(value) { + if ( this.options.useDelimiter ) { + // set the substring between the current delimiters + var val = this.dom.$elem.val(); + var d = this.getDelimiterOffsets(); + var preVal = val.substring(0, d.start); + var postVal = val.substring(d.end); + value = preVal + value + postVal; + } + this.dom.$elem.val(value); + }; + + /** + * Get the value currently being autocompleted + * @param {String} value + */ + $.Autocompleter.prototype.getValue = function(value) { + if ( this.options.useDelimiter ) { + var d = this.getDelimiterOffsets(); + return value.substring(d.start, d.end).trim(); + } else { + return value; + } + }; + + /** + * Get the offsets of the value currently being autocompleted + */ + $.Autocompleter.prototype.getDelimiterOffsets = function() { + var val = this.dom.$elem.val(); + if ( this.options.useDelimiter ) { + var preCaretVal = val.substring(0, this.getCaret().start); + var start = preCaretVal.lastIndexOf(this.options.delimiterChar) + 1; + var postCaretVal = val.substring(this.getCaret().start); + var end = postCaretVal.indexOf(this.options.delimiterChar); + if ( end == -1 ) end = val.length; + end += this.getCaret().start; + } else { + start = 0; + end = val.length; + } + return { + start: start, + end: end + }; + }; + +})((typeof window.jQuery == 'undefined' && typeof window.django != 'undefined')? django.jQuery : jQuery); diff --git a/staticfiles/django_extensions/js/jquery.bgiframe.js b/staticfiles/django_extensions/js/jquery.bgiframe.js new file mode 100644 index 00000000..1a452ba0 --- /dev/null +++ b/staticfiles/django_extensions/js/jquery.bgiframe.js @@ -0,0 +1,39 @@ +/*! Copyright (c) 2010 Brandon Aaron (http://brandon.aaron.sh/) + * Licensed under the MIT License (LICENSE.txt). + * + * Version 2.1.2 + */ + +(function($){ + +$.fn.bgiframe = ($.browser.msie && /msie 6\.0/i.test(navigator.userAgent) ? function(s) { + s = $.extend({ + top : 'auto', // auto == .currentStyle.borderTopWidth + left : 'auto', // auto == .currentStyle.borderLeftWidth + width : 'auto', // auto == offsetWidth + height : 'auto', // auto == offsetHeight + opacity : true, + src : 'javascript:false;' + }, s); + var html = '