Skip to content

Commit

Permalink
refactor override transpilation
Browse files Browse the repository at this point in the history
  • Loading branch information
bckohan committed Nov 17, 2023
1 parent a97a3f7 commit 601961f
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 40 deletions.
6 changes: 3 additions & 3 deletions render_static/tests/js_tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -3370,7 +3370,7 @@ def tearDown(self):
{% override "constructor" %}
constructor (value, name, label, alt, str, str0) {
{{ default_impl }}
{{ default_impl }}
this.constructor_context = {
'enum': {% autoescape off %}"{{enum}}"{% endautoescape %},
'class_name': "{{class_name}}",
Expand Down Expand Up @@ -3408,7 +3408,7 @@ def tearDown(self):
'to_string': {% if to_string %}true{% else %}false{% endif %},
'str_prop': "{{ str_prop }}"
};
{{ default_impl }}
{{ default_impl }}
}
{% endoverride %}
Expand All @@ -3424,7 +3424,7 @@ def tearDown(self):
'to_string': {% if to_string %}true{% else %}false{% endif %},
'str_prop': "{{ str_prop }}"
};
{{ default_impl }}
{{ default_impl }}
}
{% endoverride %}
Expand Down
54 changes: 38 additions & 16 deletions render_static/transpilers/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
from django.apps import apps
from django.apps.config import AppConfig
from django.utils.module_loading import import_module, import_string
from django.utils.safestring import SafeString

if TYPE_CHECKING:
from render_static.templatetags.render_static import (
Expand Down Expand Up @@ -156,21 +157,6 @@ def get_line(self, line: Optional[str]) -> str:
"""
return f'{self.prefix_}{self.indent_ * self.level_}{line}{self.nl_}'

def get_lines(self, lines: Generator[Optional[str], None, None]) -> str:
"""
Returns a string of lines from a generator with the indentation and
newlines added. This is meant to be used in place during overrides,
so the first newline has no indents. So it will have the line prefix
of {{ default_impl }}.
"""
lines_str = ''
for idx, line in enumerate(lines):
if idx == 0:
lines_str += f'{line}{self.nl_}'
else:
lines_str += self.get_line(line)
return lines_str

def write_line(self, line: Optional[str]) -> None:
"""
Writes a line to the rendered code file, respecting
Expand Down Expand Up @@ -241,7 +227,12 @@ def parents(self):
for parent in self.parents_
if parent is not self.target
]


@property
def context(self):
"""A local template render context passed to overrides"""
return {} # pragma: no cover

def __init__(
self,
to_javascript: Union[str, Callable] = to_javascript_,
Expand All @@ -258,6 +249,37 @@ def __init__(
self.parents_ = []
assert callable(self.to_javascript), 'To_javascript is not callable!'

def transpile_override(
self,
override: str,
default_impl: Union[str, Generator[Optional[str], None, None]]
) -> Generator[str, None, None]:
"""
Returns a string of lines from a generator with the indentation and
newlines added. This is meant to be used in place during overrides,
so the first newline has no indents. So it will have the line prefix
of {{ default_impl }}.
:param override: The name of the override to transpile
:param default_impl: The default implementation to use if the override
is not present. May be a single line string or a generator of
lines.
"""
d_impl = default_impl
if isinstance(default_impl, Generator):
d_impl = ''
for idx, line in enumerate(default_impl):
if idx == 0:
d_impl += f'{line}{self.nl_}'
else:
d_impl += self.get_line(line)
d_impl.rstrip(self.nl_)

yield from self.overrides_.pop(override).transpile({
**self.context,
'default_impl': SafeString(d_impl)
})

@abstractmethod
def include_target(self, target: TranspilerTarget):
"""
Expand Down
29 changes: 8 additions & 21 deletions render_static/transpilers/enums_to_js.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
)

from django.db.models import IntegerChoices, TextChoices
from django.utils.safestring import SafeString
from render_static.transpilers import Transpiler, TranspilerTarget

try:
Expand Down Expand Up @@ -488,10 +487,7 @@ def visit(
yield from self.to_string(enum)
yield ''
if 'get' in self.overrides_:
yield from self.overrides_.pop('get').transpile({
**self.context,
'default_impl': self.get_lines(self.getter_impl())
})
yield from self.transpile_override('get', self.getter_impl())
else:
yield from self.getter()
yield ''
Expand Down Expand Up @@ -571,10 +567,10 @@ def constructor_impl() -> Generator[str, None, None]:
yield f'this.{self.str_prop} = {self.str_prop};'

if 'constructor' in self.overrides_:
yield from self.overrides_.pop('constructor').transpile({
**self.context,
'default_impl': self.get_lines(constructor_impl())
})
yield from self.transpile_override(
'constructor',
constructor_impl()
)
else:
yield f'constructor ({", ".join(props)}) {{'
self.indent()
Expand All @@ -592,10 +588,7 @@ def ci_compare(self) -> Generator[Optional[str], None, None]:
"=== 0 : a === b;"
)
if 'ciCompare' in self.overrides_:
yield from self.overrides_.pop('ciCompare').transpile({
**self.context,
'default_impl': SafeString(self.get_line(impl))
})
yield from self.transpile_override('ciCompare', impl)
else:
yield 'static ciCompare(a, b) {'
self.indent()
Expand All @@ -616,10 +609,7 @@ def to_string( # pylint: disable=W0613
"""
impl = f'return this.{self.str_prop};'
if 'toString' in self.overrides_:
yield from self.overrides_.pop('toString').transpile({
**self.context,
'default_impl': self.get_line(impl)
})
yield from self.transpile_override('toString', impl)
else:
yield 'toString() {'
self.indent()
Expand Down Expand Up @@ -699,10 +689,7 @@ def iterator(
enums = [f'{self.class_name}.{enm.name}' for enm in enum]
impl = f'return [{", ".join(enums)}][Symbol.iterator]();'
if '[Symbol.iterator]' in self.overrides_:
yield from self.overrides_.pop('[Symbol.iterator]').transpile({
**self.context,
'default_impl': self.get_line(impl)
})
yield from self.transpile_override('[Symbol.iterator]', impl)
else:
yield 'static [Symbol.iterator]() {'
self.indent()
Expand Down

0 comments on commit 601961f

Please sign in to comment.