-
-
Notifications
You must be signed in to change notification settings - Fork 124
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Basic functionality works for getting/setting attributes from backend…
… components to the frontend.
- Loading branch information
0 parents
commit 27e2e69
Showing
30 changed files
with
2,264 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
root = true | ||
|
||
[*] | ||
end_of_line = lf // Helps keep Windows, Mac, Linux on the same page since they handle end of line differently | ||
charset = utf-8 | ||
trim_trailing_whitespace = true // Auto-trims trailing whitespace | ||
insert_final_newline = true // Auto-adds a blank newline to the end of a file | ||
|
||
[*.scss] | ||
indent_size = 2 // More common to see 2 spaces in SCSS, HTML, and JS | ||
|
||
[*.html] | ||
indent_size = 2 | ||
|
||
[*.js] | ||
indent_size = 2 | ||
|
||
[*.py] | ||
indent_style = space | ||
indent_size = 4 | ||
default_section = THIRDPARTY | ||
known_first_party = django_unicorn,example | ||
known_django = django | ||
sections = FUTURE,STDLIB,DJANGO,THIRDPARTY,FIRSTPARTY,LOCALFOLDER | ||
lines_after_imports = 2 | ||
multi_line_output = 3 | ||
include_trailing_comma = 1 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
[flake8] | ||
max-line-length = 80 | ||
select = C,E,F,W,B,B950 | ||
ignore = E501,W503 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,110 @@ | ||
# Byte-compiled / optimized / DLL files | ||
__pycache__/ | ||
*.py[cod] | ||
*$py.class | ||
|
||
# C extensions | ||
*.so | ||
|
||
# Distribution / packaging | ||
.Python | ||
build/ | ||
develop-eggs/ | ||
dist/ | ||
downloads/ | ||
eggs/ | ||
.eggs/ | ||
lib/ | ||
lib64/ | ||
parts/ | ||
sdist/ | ||
var/ | ||
wheels/ | ||
*.egg-info/ | ||
.installed.cfg | ||
*.egg | ||
MANIFEST | ||
|
||
# PyInstaller | ||
# Usually these files are written by a python script from a template | ||
# before PyInstaller builds the exe, so as to inject date/other infos into it. | ||
*.manifest | ||
*.spec | ||
|
||
# Installer logs | ||
pip-log.txt | ||
pip-delete-this-directory.txt | ||
|
||
# Unit test / coverage reports | ||
htmlcov/ | ||
.tox/ | ||
.coverage | ||
.coverage.* | ||
.cache | ||
nosetests.xml | ||
coverage.xml | ||
*.cover | ||
.hypothesis/ | ||
.pytest_cache/ | ||
|
||
# Translations | ||
*.mo | ||
*.pot | ||
|
||
# Django stuff: | ||
*.log | ||
local_settings.py | ||
db.sqlite3 | ||
|
||
# Flask stuff: | ||
instance/ | ||
.webassets-cache | ||
|
||
# Scrapy stuff: | ||
.scrapy | ||
|
||
# Sphinx documentation | ||
docs/_build/ | ||
|
||
# PyBuilder | ||
target/ | ||
|
||
# Jupyter Notebook | ||
.ipynb_checkpoints | ||
|
||
# pyenv | ||
.python-version | ||
|
||
# celery beat schedule file | ||
celerybeat-schedule | ||
|
||
# SageMath parsed files | ||
*.sage.py | ||
|
||
# Environments | ||
.env | ||
.venv | ||
env/ | ||
venv/ | ||
ENV/ | ||
env.bak/ | ||
venv.bak/ | ||
|
||
# Spyder project settings | ||
.spyderproject | ||
.spyproject | ||
|
||
# Rope project settings | ||
.ropeproject | ||
|
||
# mkdocs documentation | ||
/site | ||
|
||
# mypy | ||
.mypy_cache/ | ||
|
||
# vscode | ||
.vscode/ | ||
.DS_Store | ||
pip-wheel-metadata | ||
TODO.md |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
MIT License | ||
|
||
Copyright (c) 2020 Adam Hill | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
# django-unicorn | ||
The magical fullstack framework for Django. ✨ | ||
|
||
# Install | ||
1. `pip install django-unicorn` | ||
1. `python manage.py startunicorn hello-world` | ||
1. Add `django-unicorn` and `unicorn` to `INSTALL_APPS` in your Django settings file | ||
1. Add `path("unicorn/", include("django_unicorn.urls")),` into your project's `urlpatterns` in `urls.py` | ||
1. Add `{% load unicorn %}` to the top of your base template file | ||
1. Add `{% unicorn_styles %}` and `{% unicorn_scripts %}` into your base HTML file | ||
|
||
# Current functionality | ||
- `unicorn_styles`, `unicorn_scripts`, `unicorn` template tags | ||
- Base `component` class | ||
- Handles text input, checkbox, select options, select multiple options | ||
|
||
# Developing | ||
1. `git clone [email protected]:adamghill/django-unicorn.git` | ||
1. `poetry install` | ||
1. `poetry run example/manage.py migrate` | ||
1. `poetry run example/manage.py runserver 0:8000` | ||
1. Go to `localhost:8000` in your browser | ||
1. To install in another project `pip install -e some_folder/django-unicorn` and follow install instructions above |
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,157 @@ | ||
import importlib | ||
import inspect | ||
import uuid | ||
|
||
from django.conf import settings | ||
from django.template import Context | ||
from django.template.engine import Engine | ||
from django.utils.safestring import mark_safe | ||
|
||
import orjson | ||
from bs4 import BeautifulSoup | ||
from bs4.formatter import HTMLFormatter | ||
|
||
|
||
def convert_to_snake_case(s): | ||
# TODO: Better handling of dash->snake | ||
return s.replace("-", "_") | ||
|
||
|
||
def convert_to_camel_case(s): | ||
# TODO: Better handling of dash/snake->camel-case | ||
s = convert_to_snake_case(s) | ||
return "".join(word.title() for word in s.split("_")) | ||
|
||
|
||
def get_component_class(component_name): | ||
# TODO: Handle the module not being found | ||
module_name = convert_to_snake_case(component_name) | ||
module = importlib.import_module(f"unicorn.components.{module_name}") | ||
|
||
# TODO: Handle the class not being found | ||
class_name = convert_to_camel_case(module_name) | ||
component_class = getattr(module, class_name) | ||
|
||
return component_class | ||
|
||
|
||
class Component: | ||
def __init__(self, id=None): | ||
if not id: | ||
id = uuid.uuid4() | ||
|
||
self.id = id | ||
|
||
def __attributes__(self): | ||
""" | ||
Get attributes that can be called in the component. | ||
""" | ||
non_callables = [ | ||
member[0] for member in inspect.getmembers(self, lambda x: not callable(x)) | ||
] | ||
attribute_names = list( | ||
filter(lambda name: Component._is_public_name(name), non_callables,) | ||
) | ||
|
||
attributes = {} | ||
|
||
for attribute_name in attribute_names: | ||
attributes[attribute_name] = object.__getattribute__(self, attribute_name) | ||
|
||
return attributes | ||
|
||
def __methods__(self): | ||
""" | ||
Get methods that can be called in the component. | ||
""" | ||
|
||
# TODO: Should only take methods that only have self argument? | ||
member_methods = inspect.getmembers(self, inspect.ismethod) | ||
public_methods = filter( | ||
lambda method: Component._is_public_name(method[0]), member_methods | ||
) | ||
methods = {k: v for (k, v) in public_methods} | ||
|
||
return methods | ||
|
||
def __context__(self): | ||
""" | ||
Collects every thing that could be used in the template context. | ||
""" | ||
return { | ||
"attributes": self.__attributes__(), | ||
"methods": self.__methods__(), | ||
} | ||
|
||
def render(self, component_name): | ||
return self.view(component_name) | ||
|
||
def view(self, component_name, data={}): | ||
context = self.__context__() | ||
context_variables = {} | ||
context_variables.update(context["attributes"]) | ||
context_variables.update(context["methods"]) | ||
context_variables.update(data) | ||
|
||
frontend_context_variables = {} | ||
frontend_context_variables.update(context["attributes"]) | ||
frontend_context_variables = orjson.dumps(frontend_context_variables).decode( | ||
"utf-8" | ||
) | ||
|
||
if settings.DEBUG: | ||
context_variables.update({"unicorn_debug": context}) | ||
|
||
template_engine = Engine.get_default() | ||
# TODO: Handle looking in other directories for templates | ||
template = template_engine.get_template(f"unicorn/{component_name}.html") | ||
context = Context(context_variables, autoescape=True) | ||
rendered_template = template.render(context) | ||
|
||
soup = BeautifulSoup(rendered_template, features="html.parser") | ||
root_element = Component._get_root_element(soup) | ||
root_element["unicorn:id"] = str(self.id) | ||
|
||
populate_script = soup.new_tag("script") | ||
populate_script.string = f"populate('{str(self.id)}', '{component_name}', {frontend_context_variables});" | ||
root_element.append(populate_script) | ||
|
||
rendered_template = Component._desoupify(soup) | ||
rendered_template = mark_safe(rendered_template) | ||
|
||
return rendered_template | ||
|
||
@staticmethod | ||
def _is_public_name(name): | ||
""" | ||
Determines if the name should be sent in the context. | ||
""" | ||
protected_names = ( | ||
"id", | ||
"render", | ||
"view", | ||
) | ||
return not (name.startswith("_") or name in protected_names) | ||
|
||
@staticmethod | ||
def _get_root_element(soup): | ||
for element in soup.contents: | ||
if element.name: | ||
return element | ||
|
||
raise Exception("No root element found") | ||
|
||
@staticmethod | ||
def _desoupify(soup): | ||
soup.smooth() | ||
return soup.encode(formatter=UnsortedAttributes()).decode("utf-8") | ||
|
||
|
||
class UnsortedAttributes(HTMLFormatter): | ||
""" | ||
Prevent beautifulsoup from re-ordering attributes. | ||
""" | ||
|
||
def attributes(self, tag): | ||
for k, v in tag.attrs.items(): | ||
yield k, v |
Oops, something went wrong.