11ty / webc

Single File Web Components
MIT License
1.3k stars 36 forks source link

bug: `webc:for` does not work with any Iterable #179

Open Zearin opened 1 year ago

Zearin commented 1 year ago

I’m trying to loop over some data in a WebC component. After struggling on and off for a few weeks, I remembered that I could set breakpoints in VSCode and use the debugger to hone in on the problem.

I discovered this line of the ast, where loopContent is a JavaScript Map object, but (inside of async getLoopContent()), the AST call to Looping.parse() has reported its type as Array.

Since the AST is expecting an array, it when it tries to call .map() on loopContent, it throws.

(I tried using both webc:for="(key, val) of this.$data and webc:for="(key, val) of this.$data.entries(). The same error happens, because neither are actually an Array object, but Map and MapIterator.)

Zearin commented 1 year ago

(Thinking on this a bit more this morning)


I’m not technical enough to understand the nuances of an AST, so maybe there is a reason that the line of code mentioned above (AstSerializer.getLoopContent())—which depends on the type field in the object returned by Looping.parse()—is expecting that type field to be only Object or Array.

(…aaand this is where my ignorance of how of parsers and ASTs work may show…)

Wouldn’t it be better to just use the Iterator Protocol on whatever is being looped over? That way, users of WebC can expect iteration on their data to work just as it does anywhere else.

(I can see this is also connected with the Virtual Machine evaluating the code inline, but I don’t fully understand how.)

Zearin commented 1 year ago

(How could I forget?! 🤭)

The WebC documentation says:

It works with Objects and any Iterable (String, Array, Map, Set, etc).

Zearin commented 1 year ago

Started a test case for this bug in #180.

Zearin commented 1 year ago

(Renamed this issue from:

bug: “loopContent.map is not a function (via TypeError)”

To:

bug: webc:for does not work with any Iterable