Skip to content

Commit cb2a85f

Browse files
committed
remove custom templating solution
1 parent 1106dfd commit cb2a85f

File tree

2 files changed

+51
-30
lines changed

2 files changed

+51
-30
lines changed

Diff for: src/idom/web/module.py

+4-26
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@
99
from dataclasses import dataclass
1010
from functools import partial
1111
from pathlib import Path
12-
from typing import Any, Dict, List, NewType, Optional, Set, Tuple, Union, overload
12+
from string import Template
13+
from typing import Any, List, NewType, Optional, Set, Tuple, Union, overload
1314
from urllib.parse import urlparse
1415

1516
from typing_extensions import Protocol
@@ -103,7 +104,6 @@ def module_from_template(
103104
**Templates**
104105
105106
- ``react``: for modules exporting React components
106-
- ``react-default``: for React modules that use ``export default``
107107
108108
Parameters:
109109
template:
@@ -148,9 +148,8 @@ def module_from_template(
148148
target_file = _web_module_path(package_name, "from-template")
149149
if not target_file.exists():
150150
target_file.parent.mkdir(parents=True, exist_ok=True)
151-
target_file.write_text(
152-
_resolve_template(template_file, {"$PACKAGE": package, "$CDN": cdn})
153-
)
151+
template = Template(template_file.read())
152+
target_file.write_text(template.substitute({"$PACKAGE": package, "$CDN": cdn}))
154153

155154
return WebModule(
156155
source="from-template/" + package_name + module_name_suffix(package_name),
@@ -328,24 +327,3 @@ def _web_module_path(name: str, prefix: str = "") -> Path:
328327
directory /= prefix
329328
path = directory.joinpath(*name.split("/"))
330329
return path.with_suffix(path.suffix)
331-
332-
333-
def _resolve_template(file: Path, substitutions: Dict[str, str]) -> str:
334-
# NOTE: If this needs to be any more complex than it is, we should really
335-
# reconsider this solution. Either use a real templating solution like Jinja
336-
# or do something else entirely.
337-
resolved_lines = []
338-
for line in file.read_text().splitlines():
339-
if line.startswith("$TEMPLATE:"):
340-
relative_path = line.split(":", 1)[1].strip()
341-
inner_template_file = file.parent.joinpath(*relative_path.split("/"))
342-
resolved_lines.append(_resolve_template(inner_template_file, {}))
343-
else:
344-
resolved_lines.append(line)
345-
346-
result = "\n".join(resolved_lines)
347-
if substitutions:
348-
for k, v in substitutions.items():
349-
result = result.replace(k, v)
350-
351-
return result

Diff for: src/idom/web/templates/react.default.js

+47-4
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,48 @@
1-
// add the default export
2-
export { default } from "$CDN/$PACKAGE";
1+
export default from "$CDN/$PACKAGE";
2+
export * from "$CDN/$PACKAGE";
33

4-
// insert the normal react template
5-
$TEMPLATE:react.js
4+
import * as React from "$CDN/react";
5+
import * as ReactDOM from "$CDN/react-dom";
6+
7+
export function bind(node, config) {
8+
return {
9+
create: (component, props, children) =>
10+
React.createElement(component, wrapEventHandlers(props), ...children),
11+
render: (element) => ReactDOM.render(element, node),
12+
unmount: () => ReactDOM.unmountComponentAtNode(node),
13+
};
14+
}
15+
16+
function wrapEventHandlers(props) {
17+
const newProps = Object.assign({}, props);
18+
for (const [key, value] of Object.entries(props)) {
19+
if (typeof value === "function") {
20+
newProps[key] = makeJsonSafeEventHandler(value);
21+
}
22+
}
23+
return newProps;
24+
}
25+
26+
function makeJsonSafeEventHandler(oldHandler) {
27+
// Since we can't really know what the event handlers get passed we have to check if
28+
// they are JSON serializable or not. We can allow normal synthetic events to pass
29+
// through since the original handler already knows how to serialize those for us.
30+
return function safeEventHandler() {
31+
oldHandler(
32+
...Array.from(arguments).filter((value) => {
33+
if (typeof value === "object" && value.nativeEvent) {
34+
// this is probably a standard React synthetic event
35+
return true;
36+
} else {
37+
try {
38+
JSON.stringify(value);
39+
} catch (err) {
40+
console.error("Failed to serialize some event data");
41+
return false;
42+
}
43+
return true;
44+
}
45+
})
46+
);
47+
};
48+
}

0 commit comments

Comments
 (0)