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

Nested components proposal #265

Draft
wants to merge 16 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 14 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
10 changes: 10 additions & 0 deletions .all-contributorsrc
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,16 @@
"contributions": [
"code"
]
},
{
"login": "joshiggins",
"name": "Josh Higgins",
"avatar_url": "https://avatars.githubusercontent.com/u/5124298?v=4",
"profile": "https://github.com/joshiggins",
"contributions": [
"test",
"code"
]
}
],
"contributorsPerLine": 7,
Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
![Sponsors](https://www.sponsorama.dev/api/button/sponsor-count/adamghill)

<!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
[![All Contributors](https://img.shields.io/badge/all_contributors-9-orange.svg?style=flat-square)](#contributors-)
[![All Contributors](https://img.shields.io/badge/all_contributors-10-orange.svg?style=flat-square)](#contributors-)
<!-- ALL-CONTRIBUTORS-BADGE:END -->

[Unicorn](https://www.django-unicorn.com) is a reactive component framework that progressively enhances a normal Django view, makes AJAX calls in the background, and dynamically updates the DOM. It seamlessly extends Django past its server-side framework roots without giving up all of its niceties or re-building your website.
Expand Down Expand Up @@ -47,6 +47,7 @@ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/d
<tr>
<td align="center"><a href="http://ambient-innovation.com"><img src="https://avatars.githubusercontent.com/u/3176075?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Ron</b></sub></a><br /><a href="https://github.com/adamghill/django-unicorn/commits?author=GitRon" title="Documentation">📖</a></td>
<td align="center"><a href="https://github.com/Franziskhan"><img src="https://avatars.githubusercontent.com/u/86062014?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Franziskhan</b></sub></a><br /><a href="https://github.com/adamghill/django-unicorn/commits?author=Franziskhan" title="Code">💻</a></td>
<td align="center"><a href="https://github.com/joshiggins"><img src="https://avatars.githubusercontent.com/u/5124298?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Josh Higgins</b></sub></a><br /><a href="https://github.com/adamghill/django-unicorn/commits?author=joshiggins" title="Tests">⚠️</a> <a href="https://github.com/adamghill/django-unicorn/commits?author=joshiggins" title="Code">💻</a></td>
</tr>
</table>

Expand Down
3 changes: 3 additions & 0 deletions conftest.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ def pytest_configure():
{
"BACKEND": "django.template.backends.django.DjangoTemplates",
"DIRS": ["tests"],
"OPTIONS": {
"libraries": {"unicorn": "django_unicorn.templatetags.unicorn",}
},
}
]
databases = {"default": {"ENGINE": "django.db.backends.sqlite3",}}
Expand Down
19 changes: 11 additions & 8 deletions django_unicorn/components/unicorn_template_response.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,17 +95,20 @@ def render(self):
json_tag["id"] = json_element_id
json_tag.string = sanitize_html(init)

# Include init script and json tags from child components
json_tags = [json_tag]
for child in self.component.children:
if hasattr(child, "_init_script"):
init_script = f"{init_script} {child._init_script}"
if hasattr(child, "_json_tags"):
json_tags.extend(child._json_tags)

# Defer rendering the init script and json tag until the outermost
# component (without a parent) is rendered
if self.component.parent:
self.component._init_script = init_script
self.component._json_tag = json_tag
self.component._json_tags = json_tags
else:
json_tags = []
json_tags.append(json_tag)

for child in self.component.children:
init_script = f"{init_script} {child._init_script}"
json_tags.append(child._json_tag)

script_tag = soup.new_tag("script")
script_tag["type"] = "module"
script_tag.string = f"if (typeof Unicorn === 'undefined') {{ console.error('Unicorn is missing. Do you need {{% load unicorn %}} or {{% unicorn_scripts %}}?') }} else {{ {init_script} }}"
Expand Down
139 changes: 73 additions & 66 deletions django_unicorn/static/unicorn/js/component.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,14 @@ import {
import { components } from "./store.js";
import { send } from "./messageSender.js";
import morphdom from "./morphdom/2.6.1/morphdom.js";
import { $, hasValue, isEmpty, isFunction, walk } from "./utils.js";
import {
$,
hasValue,
isEmpty,
isFunction,
walk,
FilterSkipNested,
} from "./utils.js";

/**
* Encapsulate component.
Expand Down Expand Up @@ -164,83 +171,83 @@ export class Component {
this.dbEls = [];

try {
this.walker(this.root, (el) => {
if (el.isSameNode(this.root)) {
// Skip the component root element
return;
}
if (el.getAttribute("unicorn:checksum")) {
// Skip nested components
throw Error();
}
this.walker(
this.root,
(el) => {
if (el.isSameNode(this.root)) {
// Skip the component root element
return;
}

const element = new Element(el);
const element = new Element(el);

if (element.isUnicorn) {
if (hasValue(element.field) && hasValue(element.db)) {
if (!this.attachedDbEvents.some((e) => e.isSame(element))) {
this.attachedDbEvents.push(element);
addDbEventListener(this, element);
if (element.isUnicorn) {
if (hasValue(element.field) && hasValue(element.db)) {
if (!this.attachedDbEvents.some((e) => e.isSame(element))) {
this.attachedDbEvents.push(element);
addDbEventListener(this, element);

// If a field is lazy, also add an event listener for input for dirty states
if (element.field.isLazy) {
// This input event for isLazy will be stopped after dirty is checked when the event fires
addDbEventListener(this, element, "input");
// If a field is lazy, also add an event listener for input for dirty states
if (element.field.isLazy) {
// This input event for isLazy will be stopped after dirty is checked when the event fires
addDbEventListener(this, element, "input");
}
}
}

if (!this.dbEls.some((e) => e.isSame(element))) {
this.dbEls.push(element);
}
} else if (
hasValue(element.model) &&
isEmpty(element.db) &&
isEmpty(element.field)
) {
if (!this.attachedModelEvents.some((e) => e.isSame(element))) {
this.attachedModelEvents.push(element);
addModelEventListener(this, element);

// If a model is lazy, also add an event listener for input for dirty states
if (element.model.isLazy) {
// This input event for isLazy will be stopped after dirty is checked when the event fires
addModelEventListener(this, element, "input");
if (!this.dbEls.some((e) => e.isSame(element))) {
this.dbEls.push(element);
}
} else if (
hasValue(element.model) &&
isEmpty(element.db) &&
isEmpty(element.field)
) {
if (!this.attachedModelEvents.some((e) => e.isSame(element))) {
this.attachedModelEvents.push(element);
addModelEventListener(this, element);

// If a model is lazy, also add an event listener for input for dirty states
if (element.model.isLazy) {
// This input event for isLazy will be stopped after dirty is checked when the event fires
addModelEventListener(this, element, "input");
}
}
}

if (!this.modelEls.some((e) => e.isSame(element))) {
this.modelEls.push(element);
}
} else if (hasValue(element.loading)) {
this.loadingEls.push(element);
if (!this.modelEls.some((e) => e.isSame(element))) {
this.modelEls.push(element);
}
} else if (hasValue(element.loading)) {
this.loadingEls.push(element);

// Hide loading elements that are shown when an action happens
if (element.loading.show) {
element.hide();
// Hide loading elements that are shown when an action happens
if (element.loading.show) {
element.hide();
}
}
}

if (hasValue(element.key)) {
this.keyEls.push(element);
}

element.actions.forEach((action) => {
if (this.actionEvents[action.eventType]) {
this.actionEvents[action.eventType].push({ action, element });
} else {
this.actionEvents[action.eventType] = [{ action, element }];
if (hasValue(element.key)) {
this.keyEls.push(element);
}

if (
!this.attachedEventTypes.some((et) => et === action.eventType)
) {
this.attachedEventTypes.push(action.eventType);
addActionEventListener(this, action.eventType);
element.events.push(action.eventType);
element.actions.forEach((action) => {
if (this.actionEvents[action.eventType]) {
this.actionEvents[action.eventType].push({ action, element });
} else {
this.actionEvents[action.eventType] = [{ action, element }];

if (
!this.attachedEventTypes.some((et) => et === action.eventType)
) {
this.attachedEventTypes.push(action.eventType);
addActionEventListener(this, action.eventType);
element.events.push(action.eventType);
}
}
}
});
}
});
});
}
},
FilterSkipNested
);
} catch (err) {
// nothing
}
Expand Down
24 changes: 22 additions & 2 deletions django_unicorn/static/unicorn/js/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -104,14 +104,34 @@ export function toKebabCase(str) {
return match.map((x) => x.toLowerCase()).join("-");
}

/**
* Filter to accept any element (use with walk)
*/
export const FilterAny = {
acceptNode: (node) => NodeFilter.FILTER_ACCEPT,
};

/**
* Filter to skip nested components (use with walk)
*/
export const FilterSkipNested = {
acceptNode: (node) => {
if (node.getAttribute("unicorn:checksum")) {
// with a tree walker, child nodes are also rejected
return NodeFilter.FILTER_REJECT;
}
return NodeFilter.FILTER_ACCEPT;
},
};

/**
* Traverses the DOM looking for child elements.
*/
export function walk(el, callback) {
export function walk(el, callback, filter = FilterAny) {
const walker = document.createTreeWalker(
el,
NodeFilter.SHOW_ELEMENT,
null,
filter,
false
);

Expand Down
21 changes: 21 additions & 0 deletions example/unicorn/components/nested/actions.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
from django_unicorn.components import UnicornView
from example.coffee.models import Flavor


class ActionsView(UnicornView):
model: Flavor = None
is_editing = False

def edit(self):
self.is_editing = True

# this doesn't do what you expect because resulting dom is scoped to
# this component and the parent component won't get morphed
self.parent.is_editing = True
Copy link
Owner

Choose a reason for hiding this comment

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

@joshiggins So, I tried to add an example and kind of stumbled at this point. Your code "works" so I could merge it in as is, but Unicorn doesn't handle child components in a very intuitive way (I don't think). I'd love to hear any ideas about how this might work better.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I've put some ideas in #253, makes sense to hold this PR off for a bit since it really only solves naive use case where components are nested but otherwise independent.


def cancel(self):
self.is_editing = False

def save(self):
self.model.save()
self.is_editing = False
14 changes: 7 additions & 7 deletions example/unicorn/components/nested/row.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@ class RowView(UnicornView):
model: Flavor = None
is_editing = False

def edit(self):
self.is_editing = True
# def edit(self):
# self.is_editing = True

def cancel(self):
self.is_editing = False
# def cancel(self):
# self.is_editing = False

def save(self):
self.model.save()
self.is_editing = False
# def save(self):
# self.model.save()
# self.is_editing = False
8 changes: 8 additions & 0 deletions example/unicorn/templates/unicorn/nested/actions.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
<td>
{% if is_editing %}
<button unicorn:click="save">Save</button>
<button unicorn:click.discard="cancel" unicorn:partial.key="{{ model.pk }}">Cancel</button>
{% else %}
<button unicorn:click="edit" unicorn:partial.key="{{ model.pk }}">Edit</button>
{% endif %}
</td>
11 changes: 3 additions & 8 deletions example/unicorn/templates/unicorn/nested/row.html
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
{% load unicorn %}

<tr>
<td>
{% if is_editing %}
Expand All @@ -22,12 +24,5 @@
n/a
{% endif %}
</td>
<td>
{% if is_editing %}
<button unicorn:click="save">Save</button>
<button unicorn:click.discard="cancel" unicorn:partial.key="{{ model.pk }}">Cancel</button>
{% else %}
<button unicorn:click="edit" unicorn:partial.key="{{ model.pk }}">Edit</button>
{% endif %}
</td>
{% unicorn 'nested.actions' parent=view key=model.id model=model is_editing=is_editing %}
</tr>
2 changes: 2 additions & 0 deletions example/unicorn/templates/unicorn/nested/table.html
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,6 @@ <h3>{{ name }}</h3>
{% endfor %}
</table>

<button unicorn:click="load_table">Load table</button>

</div>
6 changes: 5 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,14 +1,18 @@
[tool.poetry]
name = "django-unicorn"
version = "0.32.0"
version = "0.33.0"
description = "A magical full-stack framework for Django."
authors = ["Adam Hill <unicorn@adamghill.com>"]
license = "MIT"
readme = "README.md"
repository = "https://github.com/adamghill/django-unicorn/"
homepage = "https://www.django-unicorn.com"
documentation = "https://www.django-unicorn.com/docs/"
keywords = ["django", "python", "javascript", "fullstack"]

[tool.poetry.urls]
"Funding" = "https://github.com/sponsors/adamghill"

[tool.poetry.dependencies]
python = "^3.6"
django = ">=2.2"
Expand Down
9 changes: 9 additions & 0 deletions tests/js/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,15 @@ import fetchMock from "fetch-mock";
import { Element } from "../../django_unicorn/static/unicorn/js/element.js";
import { Component } from "../../django_unicorn/static/unicorn/js/component.js";

/**
* Mock some browser globals using a fake DOM
*/
export function setBrowserMocks() {
const dom = new JSDOM("<div></div>");
global.document = dom.window.document;
global.NodeFilter = dom.window.NodeFilter;
}

/**
* Gets a fake DOM document based on the passed-in HTML fragement.
* @param {String} html HTML fragment.
Expand Down