NDOJ/django_ace/widgets.py

77 lines
2.1 KiB
Python
Raw Permalink Normal View History

2020-01-21 06:35:58 +00:00
"""
Django-ace originally from https://github.com/bradleyayers/django-ace.
"""
from urllib.parse import urljoin
from django import forms
from django.conf import settings
from django.forms.utils import flatatt
from django.utils.safestring import mark_safe
class AceWidget(forms.Textarea):
2022-05-14 17:57:27 +00:00
def __init__(
self,
mode=None,
theme=None,
wordwrap=False,
width="100%",
height="300px",
no_ace_media=False,
2022-06-12 07:57:46 +00:00
toolbar=True,
2022-05-14 17:57:27 +00:00
*args,
**kwargs
):
2020-01-21 06:35:58 +00:00
self.mode = mode
self.theme = theme
self.wordwrap = wordwrap
self.width = width
self.height = height
self.ace_media = not no_ace_media
2022-06-12 07:57:46 +00:00
self.toolbar = toolbar
2020-01-21 06:35:58 +00:00
super(AceWidget, self).__init__(*args, **kwargs)
@property
def media(self):
2022-05-14 17:57:27 +00:00
js = [urljoin(settings.ACE_URL, "ace.js")] if self.ace_media else []
js.append("django_ace/widget.js")
2020-01-21 06:35:58 +00:00
css = {
2022-05-14 17:57:27 +00:00
"screen": ["django_ace/widget.css"],
2020-01-21 06:35:58 +00:00
}
return forms.Media(js=js, css=css)
def render(self, name, value, attrs=None, renderer=None):
attrs = attrs or {}
ace_attrs = {
2022-05-14 17:57:27 +00:00
"class": "django-ace-widget loading",
"style": "width:%s; height:%s" % (self.width, self.height),
"id": "ace_%s" % name,
2020-01-21 06:35:58 +00:00
}
if self.mode:
2022-05-14 17:57:27 +00:00
ace_attrs["data-mode"] = self.mode
2020-01-21 06:35:58 +00:00
if self.theme:
2022-05-14 17:57:27 +00:00
ace_attrs["data-theme"] = self.theme
2020-01-21 06:35:58 +00:00
if self.wordwrap:
2022-05-14 17:57:27 +00:00
ace_attrs["data-wordwrap"] = "true"
2020-01-21 06:35:58 +00:00
2022-05-14 17:57:27 +00:00
attrs.update(
style="width: 100%; min-width: 100%; max-width: 100%; resize: none"
)
2020-01-21 06:35:58 +00:00
textarea = super(AceWidget, self).render(name, value, attrs)
2022-05-14 17:57:27 +00:00
html = "<div%s><div></div></div>%s" % (flatatt(ace_attrs), textarea)
2020-01-21 06:35:58 +00:00
2022-06-12 07:57:46 +00:00
if self.toolbar:
toolbar = (
'<div style="width: {}" class="django-ace-toolbar">'
2024-06-24 19:56:00 +00:00
'<a href="#" class="django-ace-max_min"></a>'
2022-06-12 07:57:46 +00:00
"</div>"
).format(self.width)
html = toolbar + html
html = '<div class="django-ace-editor">{}</div>'.format(html)
2020-01-21 06:35:58 +00:00
return mark_safe(html)