Skip to content

Commit

Permalink
WIP support for compiling HTML into a render method.
Browse files Browse the repository at this point in the history
  • Loading branch information
tatut committed Jan 15, 2024
1 parent 2bc99b7 commit 70e0b90
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 3 deletions.
54 changes: 54 additions & 0 deletions src/LiveWeb-Developer/LWDevHTMLCompiler.class.st
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
"
I compile HTML into `renderOn:` methods.
I provide JS to convert an HTML DOM into JSON which can be compiled.
We don't parse HTML in Smalltalk, we just provide the JS that turns a DOM node into
JSON.
A DOM element like:
<div id=""foo"" class=""bar"">something <strong>here</strong></div>
is turned into JSON as:
[""div"", {""id"": ""foo"", ""class"": ""bar}, ""something "", [""strong"", {}, ""here""]]
So [tag, attrs, ...content] where attrs is always an object, even if the element
has no attributes. After tag and attrs, the rest of the elements are its children
which can be other elements or strings.
"
Class {
#name : #LWDevHTMLCompiler,
#superclass : #Object,
#category : #'LiveWeb-Developer'
}

{ #category : #'as yet unclassified' }
LWDevHTMLCompiler class >> htmlToJsonScript [
"JavaScript code to JSONify a DOM node"
^ '
function htmlToJsonWalk(elt) {
if(elt.nodeName == "#text") {
return elt.nodeValue;
} else {
let json = [ elt.tagName ];
let attrs = { };
elt.getAttributeNames().forEach(a=>{
attrs[a] = elt.getAttribute(a)
});
json.push(attrs);
let cs = elt.childNodes;
for(let i=0; i<cs.length; i++) json.push(htmlToJsonWalk(cs[i]));
return json;
}
}
function htmlToJson(str) {
let tpl = document.createElement("template");
tpl.innerHTML = str;
return {src: str, parsed: htmlToJsonWalk(tpl.content.children[0])};
}
'
]

{ #category : #testing }
LWDevHTMLCompiler class >> isHTMLMethod: m [
"Check if the given method is an HTML method."
(m pragmaAt: 'lwHTML:') isNotNil
]
8 changes: 5 additions & 3 deletions src/LiveWeb-Developer/LWDevPage.class.st
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ LWDevPage >> body: _args [
LWDevPage >> head: _args [
^ LWFragmentContainer new
add: (super head: _args);
add: '
add: (String streamContents: [ :out |
out << '
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.23.1/ace.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.23.1/ext-language_tools.min.js"></script>
<script>function initEditor() {
Expand All @@ -36,8 +37,9 @@ console.log(e.classList);
bindKey: {win: "Ctrl-s", mac: "Command-s"},
exec: function(editor) { window.event.preventDefault(); lwCompileMethod(side, editor.session.getValue()); },
readOnly: true});
}
</script>';
}';
<< (LWDevHTMLCompiler htmlToJsonScript);
<< '</script>' ]);
yourself

]

0 comments on commit 70e0b90

Please sign in to comment.